diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000000000..6d76a5bca8235 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,8 @@ +[run] +branch = True +source = sklearn +include = */sklearn/* +omit = + */sklearn/externals/* + */benchmarks/* + */setup.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000..72acbf634c57e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,26 @@ +/sklearn/__check_build/_check_build.c -diff +/sklearn/_hmmc.c -diff +/sklearn/_isotonic.c -diff +/sklearn/cluster/_hierarchical.c -diff +/sklearn/cluster/_k_means.c -diff +/sklearn/datasets/_svmlight_format.c -diff +/sklearn/ensemble/_gradient_boosting.c -diff +/sklearn/feature_extraction/_hashing.c -diff +/sklearn/linear_model/cd_fast.c -diff +/sklearn/linear_model/sgd_fast.c -diff +/sklearn/metrics/pairwise_fast.c -diff +/sklearn/neighbors/ball_tree.c -diff +/sklearn/neighbors/kd_tree.c -diff +/sklearn/svm/liblinear.c -diff +/sklearn/svm/libsvm.c -diff +/sklearn/svm/libsvm_sparse.c -diff +/sklearn/tree/_tree.c -diff +/sklearn/tree/_utils.c -diff +/sklearn/utils/arrayfuncs.c -diff +/sklearn/utils/graph_shortest_path.c -diff +/sklearn/utils/lgamma.c -diff +/sklearn/utils/_logistic_sigmoid.c -diff +/sklearn/utils/murmurhash.c -diff +/sklearn/utils/seq_dataset.c -diff +/sklearn/utils/sparsefuncs_fast.c -diff +/sklearn/utils/weight_vector.c -diff diff --git a/.gitignore b/.gitignore index babc86d86b999..ace2c21bfd0ed 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,9 @@ *.pyc *.so +*.pyd *~ .#* +*.lprof *.swp *.swo .DS_Store @@ -10,14 +12,17 @@ sklearn/datasets/__config__.py sklearn/**/*.html dist/ +MANIFEST doc/_build/ doc/auto_examples/ doc/modules/generated/ doc/datasets/generated/ +*.pdf pip-log.txt scikit_learn.egg-info/ .coverage coverage +*.py,cover tags covtype.data.gz 20news-18828/ @@ -30,6 +35,9 @@ coverages samples doc/coverages doc/samples +*.prof +.tox/ +.coverage lfw_preprocessed/ nips2010_pdf/ @@ -39,3 +47,9 @@ nips2010_pdf/ *.tgz examples/cluster/joblib +reuters/ +benchmarks/bench_covertype_data/ + +*.prefs +.pydevproject +.idea diff --git a/.landscape.yml b/.landscape.yml new file mode 100644 index 0000000000000..4774bdc1a2984 --- /dev/null +++ b/.landscape.yml @@ -0,0 +1,5 @@ +pylint: + disable: + - unpacking-non-sequence +ignore-paths: + - sklearn/externals diff --git a/.mailmap b/.mailmap index 1824ab8de52dd..d07fe161195bc 100644 --- a/.mailmap +++ b/.mailmap @@ -1,69 +1,105 @@ -Gael Varoquaux gvaroquaux -Gael Varoquaux Gael varoquaux -Gael Varoquaux GaelVaroquaux -Gael Varoquaux Varoquaux -Olivier Grisel ogrisel -Olivier Grisel Olivier Grisel -Alexandre Gramfort Alexandre Gramfort -Alexandre Gramfort Alexandre Gramfort -Alexandre Gramfort Alexandre Gramfort -Matthieu Perrot Matthieu Perrot -Matthieu Perrot revilyo -Vincent Michel vincent -Vincent Michel vincent -Vincent Michel vincent M -Vincent Michel Vincent M -Vincent Michel Vincent Michel -Vincent Michel Vincent M -Vincent Michel Vincent michel -Vincent Michel Vincent Michel +Alexandre Gramfort +Alexandre Gramfort +Alexandre Gramfort +Andreas Mueller +Andreas Mueller +Andreas Mueller +Andreas Mueller +Andreas Mueller +Arnaud Joly +Arnaud Joly +Arnaud Joly +Anne-Laure Fouque Ariel Rokem arokem -Bertrand Thirion bthirion -Peter Prettenhofer pprett -Anne-Laure Fouque Anne-Laure FOUQUE -Vincent Dubourg dubourg -Vincent Dubourg dubourg -Christian Osendorfer osdf -James Bergstra james.bergstra -Xinfan Meng mxf -Jan Schlüter f0k -Vlad Niculae vene -Virgile Fritsch VirgileFritsch -Virgile Fritsch Virgile -Virgile Fritsch Virgile -Jean Kossaifi Jean KOSSAIFI -Jean Kossaifi JeanKossaifi -Jean Kossaifi Jean Kossaifi -Jake VanderPlas Jacob Vanderplas -Jake VanderPlas Jake Vanderplas -Jake VanderPlas Jake Vanderplas -Andreas Mueller Andy -Andreas Mueller unknown -Andreas Mueller andy -Andreas Mueller Andreas Mueller -Andreas Mueller Andreas Müller -Brian Holt bdholt1 -Brian Holt Brian Holt -Robert Layton robertlayton -Robert Layton = -Fabian Pedregosa Fabian Pedregosa -Lars Buitinck Lars Buitinck -Lars Buitinck unknown -Lars Buitinck Lars Buitinck +Bala Subrahmanyam Varanasi +Bertrand Thirion +Brandyn A. White +Brian Cheung +Brian Cheung +Brian Cheung +Brian Holt +Christian Osendorfer +Clay Woolam +Denis Engemann +Denis Engemann +Denis Engemann +Denis Engemann +Diego Molla DraXus draxus -Edouard DUCHESNAY Edouard Duchesnay -Edouard DUCHESNAY Edouard Duchesnay -Edouard DUCHESNAY duchesnay -Edouard DUCHESNAY duchesnay -Emmanuelle Gouillart Emmanuelle Gouillart -Emmanuelle Gouillart emmanuelle -Gilles Louppe Gilles Louppe -Nelle Varoquaux Nelle Varoquaux -Nicolas Pinto Nicolas Pinto -Olivier Hervieu Olivier Hervieu -Satrajit Ghosh Satrajit Ghosh -Shiqiao Du Shiqiao Du -Shiqiao Du Shiqiao -Tim Sheerman-Chase Tim Sheerman-Chase -Vincent Schut Vincent Schut -iBayer ibayer +Edouard DUCHESNAY +Edouard DUCHESNAY +Edouard DUCHESNAY +Emmanuelle Gouillart +Emmanuelle Gouillart +Eustache Diemert +Fabian Pedregosa +Fabian Pedregosa +Fabian Pedregosa +Federico Vaggi +Federico Vaggi +Gael Varoquaux +Gael Varoquaux +Gael Varoquaux +Gilles Louppe +Hamzeh Alsalhi <93hamsal@gmail.com> +Harikrishnan S +Hendrik Heuer +Hrishikesh Huilgolkar +Immanuel Bayer +Jake VanderPlas +Jake VanderPlas +Jake VanderPlas +James Bergstra +Jaques Grobler +Jan Schl�ter +Jean Kossaifi +Jean Kossaifi +Jean Kossaifi +Joel Nothman +Kyle Kastner +Lars Buitinck +Lars Buitinck +Lars Buitinck +Manoj Kumar +Matthieu Perrot +Maheshakya Wijewardena +Michael Bommarito +Michael Eickenberg +Michael Eickenberg +Nelle Varoquaux +Nelle Varoquaux +Nicolas Pinto +Noel Dawe +Noel Dawe +Olivier Grisel +Olivier Grisel +Olivier Hervieu +Paul Butler +Peter Prettenhofer +Robert Layton +Roman Sinayev +Roman Sinayev +Ronald Phlypo +Satrajit Ghosh +Shiqiao Du +Shiqiao Du +Thomas Unterthiner +Tim Sheerman-Chase +Vincent Dubourg +Vincent Dubourg +Vincent Michel +Vincent Michel +Vincent Michel +Vincent Michel +Vincent Michel +Vincent Schut +Virgile Fritsch +Virgile Fritsch +Vlad Niculae +Wei Li +Wei Li +X006 +Xinfan Meng +Yannick Schwartz +Yannick Schwartz + diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000000..c1779a7a89ddb --- /dev/null +++ b/.travis.yml @@ -0,0 +1,29 @@ +language: python +virtualenv: + system_site_packages: true +env: + matrix: + - DISTRIB="ubuntu" PYTHON_VERSION="2.7" INSTALL_ATLAS="true" + COVERAGE="true" + # This environment tests the oldest supported anaconda env + - DISTRIB="conda" PYTHON_VERSION="2.6" INSTALL_MKL="false" + NUMPY_VERSION="1.6.2" SCIPY_VERSION="0.11.0" + # This environment tests the newest supported anaconda env + - DISTRIB="conda" PYTHON_VERSION="3.4" INSTALL_MKL="true" + NUMPY_VERSION="1.8.1" SCIPY_VERSION="0.14.0" +install: source continuous_integration/install.sh +script: bash continuous_integration/test_script.sh +after_success: + # Ignore coveralls failures as the coveralls server is not very reliable + # but we don't want travis to report a failure in the github UI just + # because the coverage report failed to be published. + - if [[ "$COVERAGE" == "true" ]]; then coveralls || echo "failed"; fi +cache: apt + +notifications: + webhooks: + urls: + - https://webhooks.gitter.im/e/4ffabb4df010b70cd624 + on_success: change # options: [always|never|change] default: always + on_failure: always # options: [always|never|change] default: always + on_start: false # default: false diff --git a/AUTHORS.rst b/AUTHORS.rst index 150f4e32ecfdc..0f15c5b328378 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -13,8 +13,8 @@ this project as part of his thesis. In 2010 Fabian Pedregosa, Gael Varoquaux, Alexandre Gramfort and Vincent Michel of INRIA took leadership of the project and made the first public -release, February the 1st 2010. Since then, several releases have appeard -following a ~3 month cycle, and a striving international community has +release, February the 1st 2010. Since then, several releases have appeared +following a ~3 month cycle, and a thriving international community has been leading the development. People @@ -24,26 +24,10 @@ People * David Cournapeau - * Fred Mailhot - - * David Cooke - - * David Huard - - * Dave Morrill - - * Ed Schofield - - * Eric Jones - * Jarrod Millman * `Matthieu Brucher `_ - * Travis Oliphant - - * Pearu Peterson - * `Fabian Pedregosa `_ * `Gael Varoquaux `_ @@ -96,10 +80,14 @@ People * `Gilles Louppe `_ - * `Andreas Müller `_ (release manager) + * `Andreas Müller `_ (release manager) * `Satra Ghosh `_ + * `Wei Li `_ + + * `Arnaud Joly `_ + + * `Kemal Eren `_ -If I forgot anyone, do not hesitate to send me an email to -fabian.pedregosa@inria.fr and I'll include you in the list. + * `Michael Becker `_ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 45ad937019618..4b472efde23aa 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,10 +3,10 @@ Contributing code ================= **Note: This document is just to get started, visit [**Contributing -page**](http://scikit-learn.org/stable/developers/index.html#coding-guidelines) -for the full contributor's guide. Make sure to read it carefully to make +page**](http://scikit-learn.org/stable/developers/index.html) +for the full contributor's guide. Please be sure to read it carefully to make the code review process go as smoothly as possible and maximize the -likelihood of your contribution to get merged.** +likelihood of your contribution being merged.** How to contribute ----------------- @@ -22,6 +22,7 @@ GitHub: 2. Clone this copy to your local disk: $ git clone git@github.com:YourLogin/scikit-learn.git + $ cd scikit-learn 3. Create a branch to hold your changes: @@ -29,7 +30,7 @@ GitHub: and start making changes. Never work in the ``master`` branch! -4. Work on this copy, on your computer, using Git to do the version +4. Work on this copy on your computer using Git to do the version control. When you're done editing, do: $ git add modified_files @@ -41,10 +42,10 @@ GitHub: Finally, go to the web page of the your fork of the scikit-learn repo, and click 'Pull request' to send your changes to the maintainers for -review. request. This will send an email to the committers. +review. This will send an email to the committers. -(If any of the above seems like magic to you, then look up the [Git documentation](http://git-scm.com/documentation) -on the web.) +(If any of the above seems like magic to you, then look up the +[Git documentation](http://git-scm.com/documentation) on the web.) It is recommended to check that your contribution complies with the following rules before submitting a pull request: @@ -76,7 +77,7 @@ scale in dimensionality: n_features is expected to be lower than You can also check for common programming errors with the following tools: -- Code with a good unittest coverage (at least 80%), check with: +- Code with good unittest coverage (at least 80%), check with: $ pip install nose coverage $ nosetests --with-coverage path/to/tests_for_package @@ -119,7 +120,7 @@ reStructuredText documents (like this one), tutorials, etc. reStructuredText documents live in the source code repository under the doc/ directory. -You can edit the documentation using any text editor, and then generate +You can edit the documentation using any text editor and then generate the HTML output by typing ``make html`` from the doc/ directory. Alternatively, ``make`` can be used to quickly generate the documentation without the example gallery. The resulting HTML files will @@ -127,13 +128,14 @@ be placed in _build/html/ and are viewable in a web browser. See the README file in the doc/ directory for more information. For building the documentation, you will need -[sphinx](http://sphinx.pocoo.org/) and -[matplotlib](http://matplotlib.sourceforge.net/). +[sphinx](http://sphinx.pocoo.org/), +[matplotlib](http://matplotlib.sourceforge.net/), and +[pillow](http://pillow.readthedocs.org/en/latest/). When you are writing documentation, it is important to keep a good compromise between mathematical and algorithmic details, and give intuition to the reader on what the algorithm does. It is best to always -start with a small paragraph with a hand-waiving explanation of what the +start with a small paragraph with a hand-waving explanation of what the method does to the data and a figure (coming from an example) illustrating it. @@ -143,4 +145,3 @@ Further Information Visit the [Contributing Code](http://scikit-learn.org/stable/developers/index.html#coding-guidelines) section of the website for more information including conforming to the API spec and profiling contributed code. - diff --git a/COPYING b/COPYING index be4673609e21e..4886cbd6585d0 100644 --- a/COPYING +++ b/COPYING @@ -1,6 +1,6 @@ New BSD License -Copyright (c) 2007 - 2012 The scikit-learn developers. +Copyright (c) 2007–2014 The scikit-learn developers. All rights reserved. diff --git a/MANIFEST.in b/MANIFEST.in index fc33b3641f378..ed0ca0e87274e 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,5 +1,9 @@ include *.rst recursive-include doc * recursive-include examples * -recursive-include sklearn *.c *.h *.pyx +recursive-include sklearn *.c *.h *.pyx *.pxd *.pxi recursive-include sklearn/datasets *.csv *.csv.gz *.rst *.jpg *.txt +include COPYING +include AUTHORS.rst +include README.rst + diff --git a/Makefile b/Makefile index a647fa2c2211b..f48ce7bdd92b4 100644 --- a/Makefile +++ b/Makefile @@ -9,44 +9,40 @@ CTAGS ?= ctags all: clean inplace test -clean-pyc: - find sklearn -name "*.pyc" | xargs rm -f - -clean-so: - find sklearn -name "*.so" | xargs rm -f - find sklearn -name "*.pyd" | xargs rm -f - -clean-build: - rm -rf build - clean-ctags: rm -f tags -clean: clean-build clean-pyc clean-so clean-ctags +clean: clean-ctags + $(PYTHON) setup.py clean + rm -rf dist in: inplace # just a shortcut inplace: + # to avoid errors in 0.15 upgrade + rm -f sklearn/utils/sparsefuncs*.so + rm -f sklearn/utils/random*.so $(PYTHON) setup.py build_ext -i test-code: in - $(NOSETESTS) -s sklearn + $(NOSETESTS) -s -v sklearn +test-sphinxext: + $(NOSETESTS) -s -v doc/sphinxext/ test-doc: - $(NOSETESTS) -s --with-doctest --doctest-tests --doctest-extension=rst \ - --doctest-extension=inc --doctest-fixtures=_fixture doc/ doc/modules/ \ - doc/developers doc/tutorial/basic doc/tutorial/statistical_inference + $(NOSETESTS) -s -v doc/*.rst doc/modules/ doc/datasets/ \ + doc/developers doc/tutorial/basic doc/tutorial/statistical_inference \ + doc/tutorial/text_analytics test-coverage: rm -rf coverage .coverage - $(NOSETESTS) -s --with-coverage --cover-html --cover-html-dir=coverage \ - --cover-package=sklearn sklearn + $(NOSETESTS) -s -v --with-coverage sklearn -test: test-code test-doc +test: test-code test-sphinxext test-doc trailing-spaces: - find sklearn -name "*.py" | xargs perl -pi -e 's/[ \t]*$$//' + find sklearn -name "*.py" -exec perl -pi -e 's/[ \t]*$$//' {} \; cython: - find sklearn -name "*.pyx" | xargs $(CYTHON) + find sklearn -name "*.pyx" -exec $(CYTHON) {} \; ctags: # make tags for symbol based navigation in emacs and vim @@ -54,7 +50,11 @@ ctags: $(CTAGS) -R * doc: inplace - make -C doc html + $(MAKE) -C doc html doc-noplot: inplace - make -C doc html-noplot + $(MAKE) -C doc html-noplot + +code-analysis: + flake8 sklearn | grep -v __init__ | grep -v external + pylint -E -i y sklearn/ -d E1103,E0611,E1101 diff --git a/README-py3k.rst b/README-py3k.rst deleted file mode 100644 index 516864219489d..0000000000000 --- a/README-py3k.rst +++ /dev/null @@ -1,24 +0,0 @@ -Support for Python 3 -==================== - -There is experimental support for python3 in some modules, the status -of these is: - - svm : OK - linear_models : ? - cluster : ? - covariance : ? - grid_search : ? - mixture : ? - externals.joblib : ? - utils.sparsetools : FAILS to compile - -To generate python3 compatible sources for selected modules, run the -2to3 tool on the module:: - - 2to3 -wn --no-diffs sklearn/$module - -If you would like to help with porting to python3, please propose -yourself in the scikit-learn mailing list: - - https://lists.sourceforge.net/lists/listinfo/scikit-learn-general diff --git a/README.rst b/README.rst index d0b4c83d72a21..74150165ab7ce 100644 --- a/README.rst +++ b/README.rst @@ -1,5 +1,13 @@ .. -*- mode: rst -*- +|Travis|_ |AppVeyor|_ + +.. |Travis| image:: https://api.travis-ci.org/scikit-learn/scikit-learn.png?branch=master +.. _Travis: https://travis-ci.org/scikit-learn/scikit-learn + +.. |AppVeyor| image:: https://img.shields.io/appveyor/ci/sklearn-ci/scikit-learn/master.png +.. _AppVeyor: https://ci.appveyor.com/project/sklearn-ci/scikit-learn/history + scikit-learn ============ @@ -29,11 +37,25 @@ Important links Dependencies ============ -The required dependencies to build the software are Python >= 2.6, -setuptools, Numpy >= 1.3, SciPy >= 0.7 and a working C/C++ compiler. -This configuration matches the Ubuntu 10.04 LTS release from April 2010. +scikit-learn is tested to work under Python 2.6, Python 2.7, and Python 3.4. +(using the same codebase thanks to an embedded copy of +`six `_). It should also work with Python 3.3. + +The required dependencies to build the software are NumPy >= 1.6.1, +SciPy >= 0.9 and a working C/C++ compiler. + +For running the examples Matplotlib >= 1.1.1 is required and for running the +tests you need nose >= 1.1.2. + +This configuration matches the Ubuntu Precise 12.04 LTS release from April +2012. -To run the tests you will also need nose >= 0.10. +scikit-learn also uses CBLAS, the C interface to the Basic Linear Algebra +Subprograms library. scikit-learn comes with a reference implementation, but +the system CBLAS will be detected by the build system and used if present. +CBLAS exists in many implementations; see `Linear algebra libraries +`_ +for known issues. Install @@ -42,7 +64,7 @@ Install This package uses distutils, which is the default way of installing python modules. To install in your home directory, use:: - python setup.py install --home + python setup.py install --user To install for all users on Unix/Linux:: @@ -61,23 +83,40 @@ GIT You can check the latest sources with the command:: - git clone git://github.com/scikit-learn/scikit-learn.git + git clone https://github.com/scikit-learn/scikit-learn.git or if you have write privileges:: git clone git@github.com:scikit-learn/scikit-learn.git +Contributing +~~~~~~~~~~~~ + +Quick tutorial on how to go about setting up your environment to +contribute to scikit-learn: https://github.com/scikit-learn/scikit-learn/blob/master/CONTRIBUTING.md + +Before opening a Pull Request, have a look at the +full Contributing page to make sure your code complies +with our guidelines: http://scikit-learn.org/stable/developers/index.html + + Testing ------- After installation, you can launch the test suite from outside the -source directory (you will need to have nosetest installed):: +source directory (you will need to have the ``nose`` package installed):: + + $ nosetests -v sklearn + +Under Windows, it is recommended to use the following command (adjust the path +to the ``python.exe`` program) as using the ``nosetests.exe`` program can badly +interact with tests that use ``multiprocessing``:: - python -c "import sklearn; sklearn.test()" + C:\Python34\python.exe -c "import nose; nose.main()" -v sklearn -See web page http://scikit-learn.org/stable/install.html#testing +See the web page http://scikit-learn.org/stable/install.html#testing for more information. - Random number generation can be controled during testing by setting - the SKLEARN_SEED environment variable + Random number generation can be controlled during testing by setting + the ``SKLEARN_SEED`` environment variable. diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 0000000000000..2df4287b8a47d --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,81 @@ +# AppVeyor.com is a Continuous Integration service to build and run tests under +# Windows + +environment: + global: + # SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the + # /E:ON and /V:ON options are not enabled in the batch script intepreter + # See: http://stackoverflow.com/a/13751649/163740 + CMD_IN_ENV: "cmd /E:ON /V:ON /C .\\continuous_integration\\appveyor\\run_with_env.cmd" + WHEELHOUSE_UPLOADER_USERNAME: sklearn-appveyor + WHEELHOUSE_UPLOADER_SECRET: + secure: BQm8KfEj6v2Y+dQxb2syQvTFxDnHXvaNktkLcYSq7jfbTOO6eH9n09tfQzFUVcWZ + + matrix: + - PYTHON: "C:\\Python27" + PYTHON_VERSION: "2.7.8" + PYTHON_ARCH: "32" + + - PYTHON: "C:\\Python27-x64" + PYTHON_VERSION: "2.7.8" + PYTHON_ARCH: "64" + + - PYTHON: "C:\\Python34" + PYTHON_VERSION: "3.4.1" + PYTHON_ARCH: "32" + + - PYTHON: "C:\\Python34-x64" + PYTHON_VERSION: "3.4.1" + PYTHON_ARCH: "64" + + +install: + # Collect info to debug rare and random download errors from Rackspace cloud store + - "nslookup 28daf2247a33ed269873-7b1aad3fab3cc330e1fd9d109892382a.r6.cf2.rackcdn.com" + + # Install Python (from the official .msi of http://python.org) and pip when + # not already installed. + - "powershell ./continuous_integration/appveyor/install.ps1" + - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" + + # Check that we have the expected version and architecture for Python + - "python --version" + - "python -c \"import struct; print(struct.calcsize('P') * 8)\"" + + # Install the build and runtime dependencies of the project. + - "%CMD_IN_ENV% pip install --timeout=60 -r continuous_integration/appveyor/requirements.txt" + - "%CMD_IN_ENV% python setup.py bdist_wheel bdist_wininst -b doc/logos/scikit-learn-logo.bmp" + - ps: "ls dist" + + # Install the genreated wheel package to test it + - "pip install --pre --no-index --find-links dist/ scikit-learn" + +# Not a .NET project, we build scikit-learn in the install step instead +build: false + +test_script: + # Change to a non-source folder to make sure we run the tests on the + # installed library. + - "mkdir empty_folder" + - "cd empty_folder" + + - "python -c \"import nose; nose.main()\" -s -v sklearn" + + # Move back to the project folder + - "cd .." + +artifacts: + # Archive the generated wheel package in the ci.appveyor.com build report. + - path: dist\* + +on_success: + # Upload the generated wheel package to Rackspace + # On Windows, Apache Libcloud cannot find a standard CA cert bundle so we + # disable the ssl checks. + - "python -m wheelhouse_uploader upload --no-ssl-check --local-folder=dist sklearn-windows-wheels" + +notifications: + - provider: Webhook + url: https://webhooks.gitter.im/e/0dc8e57cd38105aeb1b4 + on_build_success: false + on_build_failure: True diff --git a/benchmarks/bench_20newsgroups.py b/benchmarks/bench_20newsgroups.py new file mode 100644 index 0000000000000..5bd56f32d6f67 --- /dev/null +++ b/benchmarks/bench_20newsgroups.py @@ -0,0 +1,97 @@ +from __future__ import print_function, division +from time import time +import argparse +import numpy as np + +from sklearn.dummy import DummyClassifier + +from sklearn.datasets import fetch_20newsgroups_vectorized +from sklearn.metrics import accuracy_score +from sklearn.utils.validation import check_array + +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import ExtraTreesClassifier +from sklearn.ensemble import AdaBoostClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.naive_bayes import MultinomialNB + +ESTIMATORS = { + "dummy": DummyClassifier(), + "random_forest": RandomForestClassifier(n_estimators=100, + max_features="sqrt", + min_samples_split=10), + "extra_trees": ExtraTreesClassifier(n_estimators=100, + max_features="sqrt", + min_samples_split=10), + "logistic_regression": LogisticRegression(), + "naive_bayes": MultinomialNB(), + "adaboost": AdaBoostClassifier(n_estimators=10), +} + + +############################################################################### +# Data + +if __name__ == "__main__": + + parser = argparse.ArgumentParser() + parser.add_argument('-e', '--estimators', nargs="+", required=True, + choices=ESTIMATORS) + args = vars(parser.parse_args()) + + data_train = fetch_20newsgroups_vectorized(subset="train") + data_test = fetch_20newsgroups_vectorized(subset="test") + X_train = check_array(data_train.data, dtype=np.float32, + accept_sparse="csc") + X_test = check_array(data_test.data, dtype=np.float32, accept_sparse="csr") + y_train = data_train.target + y_test = data_test.target + + print("20 newsgroups") + print("=============") + print("X_train.shape = {0}".format(X_train.shape)) + print("X_train.format = {0}".format(X_train.format)) + print("X_train.dtype = {0}".format(X_train.dtype)) + print("X_train density = {0}" + "".format(X_train.nnz / np.product(X_train.shape))) + print("y_train {0}".format(y_train.shape)) + print("X_test {0}".format(X_test.shape)) + print("X_test.format = {0}".format(X_test.format)) + print("X_test.dtype = {0}".format(X_test.dtype)) + print("y_test {0}".format(y_test.shape)) + print() + + print("Classifier Training") + print("===================") + accuracy, train_time, test_time = {}, {}, {} + for name in sorted(args["estimators"]): + clf = ESTIMATORS[name] + try: + clf.set_params(random_state=0) + except (TypeError, ValueError): + pass + + print("Training %s ... " % name, end="") + t0 = time() + clf.fit(X_train, y_train) + train_time[name] = time() - t0 + t0 = time() + y_pred = clf.predict(X_test) + test_time[name] = time() - t0 + accuracy[name] = accuracy_score(y_test, y_pred) + print("done") + + print() + print("Classification performance:") + print("===========================") + print() + print("%s %s %s %s" % ("Classifier ", "train-time", "test-time", + "Accuracy")) + print("-" * 44) + for name in sorted(accuracy, key=accuracy.get): + print("%s %s %s %s" % (name.ljust(16), + ("%.4fs" % train_time[name]).center(10), + ("%.4fs" % test_time[name]).center(10), + ("%.4f" % accuracy[name]).center(10))) + + print() diff --git a/benchmarks/bench_covertype.py b/benchmarks/bench_covertype.py index cbbf9841e8712..0678153e315f5 100644 --- a/benchmarks/bench_covertype.py +++ b/benchmarks/bench_covertype.py @@ -14,15 +14,14 @@ [..] Classification performance: =========================== - Classifier train-time test-time error-rate -------------------------------------------- - Liblinear 11.8977s 0.0285s 0.2305 - GaussianNB 3.5931s 0.6645s 0.3633 - SGD 0.2924s 0.0114s 0.2300 - CART 39.9829s 0.0345s 0.0476 - RandomForest 794.6232s 1.0526s 0.0249 - Extra-Trees 1401.7051s 1.1181s 0.0230 + liblinear 15.9744s 0.0705s 0.2305 + GaussianNB 3.0666s 0.3884s 0.4841 + SGD 1.0558s 0.1152s 0.2300 + CART 79.4296s 0.0523s 0.0469 + RandomForest 1190.1620s 0.5881s 0.0243 + ExtraTrees 640.3194s 0.6495s 0.0198 The same task has been used in a number of papers including: @@ -41,204 +40,150 @@ [1] http://archive.ics.uci.edu/ml/datasets/Covertype """ -from __future__ import division - -print __doc__ - -# Author: Peter Prettenhoer -# License: BSD Style. +from __future__ import division, print_function -# $Id$ +# Author: Peter Prettenhofer +# Arnaud Joly +# License: BSD 3 clause -from time import time import os -import sys +from time import time +import argparse import numpy as np -from optparse import OptionParser +from sklearn.datasets import fetch_covtype, get_data_home from sklearn.svm import LinearSVC from sklearn.linear_model import SGDClassifier from sklearn.naive_bayes import GaussianNB from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier -from sklearn import metrics - -op = OptionParser() -op.add_option("--classifiers", - dest="classifiers", default='liblinear,GaussianNB,SGD,CART', - help="comma-separated list of classifiers to benchmark. " - "default: %default. available: " - "liblinear,GaussianNB,SGD,CART,ExtraTrees,RandomForest") - -op.print_help() - -(opts, args) = op.parse_args() -if len(args) > 0: - op.error("this script takes no arguments.") - sys.exit(1) - -###################################################################### -## Download the data, if not already on disk -if not os.path.exists('covtype.data.gz'): - # Download the data - import urllib - print "Downloading data, Please Wait (11MB)..." - opener = urllib.urlopen( - 'http://archive.ics.uci.edu/ml/' - 'machine-learning-databases/covtype/covtype.data.gz') - open('covtype.data.gz', 'wb').write(opener.read()) - -###################################################################### -## Load dataset -print("Loading dataset...") -import gzip -f = gzip.open('covtype.data.gz') -X = np.fromstring(f.read().replace(",", " "), dtype=np.float64, sep=" ", - count=-1) -X = X.reshape((581012, 55)) -f.close() - -# class 1 vs. all others. -y = np.ones(X.shape[0]) * -1 -y[np.where(X[:, -1] == 1)] = 1 -X = X[:, :-1] - -###################################################################### -## Create train-test split (as [Joachims, 2006]) -print("Creating train-test split...") -idx = np.arange(X.shape[0]) -np.random.seed(13) -np.random.shuffle(idx) -train_idx = idx[:522911] -test_idx = idx[522911:] - -X_train = X[train_idx] -y_train = y[train_idx] -X_test = X[test_idx] -y_test = y[test_idx] - -# free memory -del X -del y - -###################################################################### -## Standardize first 10 features (the numerical ones) -mean = X_train.mean(axis=0) -std = X_train.std(axis=0) -mean[10:] = 0.0 -std[10:] = 1.0 -X_train = (X_train - mean) / std -X_test = (X_test - mean) / std - -###################################################################### -## Print dataset statistics -print("") -print("Dataset statistics:") -print("===================") -print("%s %d" % ("number of features:".ljust(25), - X_train.shape[1])) -print("%s %d" % ("number of classes:".ljust(25), - np.unique(y_train).shape[0])) -print("%s %d (%d, %d)" % ("number of train samples:".ljust(25), - X_train.shape[0], np.sum(y_train == 1), - np.sum(y_train == -1))) -print("%s %d (%d, %d)" % ("number of test samples:".ljust(25), - X_test.shape[0], np.sum(y_test == 1), - np.sum(y_test == -1))) - - -classifiers = dict() - - -###################################################################### -## Benchmark classifiers -def benchmark(clf): - t0 = time() - clf.fit(X_train, y_train) - train_time = time() - t0 - t0 = time() - pred = clf.predict(X_test) - test_time = time() - t0 - err = metrics.zero_one(y_test, pred) / float(pred.shape[0]) - return err, train_time, test_time - -###################################################################### -## Train Liblinear model -liblinear_parameters = { - 'loss': 'l2', - 'penalty': 'l2', - 'C': 1000, - 'dual': False, - 'tol': 1e-3, - } -classifiers['liblinear'] = LinearSVC(**liblinear_parameters) - -###################################################################### -## Train GaussianNB model -classifiers['GaussianNB'] = GaussianNB() - -###################################################################### -## Train SGD model -sgd_parameters = { - 'alpha': 0.001, - 'n_iter': 2, - } -classifiers['SGD'] = SGDClassifier(**sgd_parameters) - -###################################################################### -## Train CART model -classifiers['CART'] = DecisionTreeClassifier(min_samples_split=5, - max_depth=None) - -###################################################################### -## Train RandomForest model -classifiers['RandomForest'] = RandomForestClassifier(n_estimators=20, - min_samples_split=5, - max_features=None, - max_depth=None) - -###################################################################### -## Train Extra-Trees model -classifiers['ExtraTrees'] = ExtraTreesClassifier(n_estimators=20, - min_samples_split=5, - max_features=None, - max_depth=None) - - -selected_classifiers = opts.classifiers.split(',') -for name in selected_classifiers: - if name not in classifiers: - op.error('classifier %r unknown' % name) - sys.exit(1) - -print("") -print("Training Classifiers") -print("====================") -print("") -err, train_time, test_time = {}, {}, {} -for name in sorted(selected_classifiers): - print("Training %s ..." % name) - err[name], train_time[name], test_time[name] = benchmark(classifiers[name]) - -###################################################################### -## Print classification performance -print("") -print("Classification performance:") -print("===========================") -print("") - - -def print_row(clf_type, train_time, test_time, err): - print("%s %s %s %s" % (clf_type.ljust(12), - ("%.4fs" % train_time).center(10), - ("%.4fs" % test_time).center(10), - ("%.4f" % err).center(10))) - -print("%s %s %s %s" % ("Classifier ", "train-time", "test-time", - "error-rate")) -print("-" * 44) - -for name in sorted(selected_classifiers, key=lambda name: err[name]): - print_row(name, train_time[name], test_time[name], err[name]) -print("") -print("") +from sklearn.ensemble import GradientBoostingClassifier +from sklearn.metrics import zero_one_loss +from sklearn.externals.joblib import Memory +from sklearn.utils import check_array + +# Memoize the data extraction and memory map the resulting +# train / test splits in readonly mode +memory = Memory(os.path.join(get_data_home(), 'covertype_benchmark_data'), + mmap_mode='r') + + +@memory.cache +def load_data(dtype=np.float32, order='C', random_state=13): + """Load the data, then cache and memmap the train/test split""" + ###################################################################### + ## Load dataset + print("Loading dataset...") + data = fetch_covtype(download_if_missing=True, shuffle=True, + random_state=random_state) + X = check_array(data['data'], dtype=dtype, order=order) + y = (data['target'] != 1).astype(np.int) + + ## Create train-test split (as [Joachims, 2006]) + print("Creating train-test split...") + n_train = 522911 + X_train = X[:n_train] + y_train = y[:n_train] + X_test = X[n_train:] + y_test = y[n_train:] + + ## Standardize first 10 features (the numerical ones) + mean = X_train.mean(axis=0) + std = X_train.std(axis=0) + mean[10:] = 0.0 + std[10:] = 1.0 + X_train = (X_train - mean) / std + X_test = (X_test - mean) / std + return X_train, X_test, y_train, y_test + + +ESTIMATORS = { + 'GBRT': GradientBoostingClassifier(n_estimators=250), + 'ExtraTrees': ExtraTreesClassifier(n_estimators=20), + 'RandomForest': RandomForestClassifier(n_estimators=20), + 'CART': DecisionTreeClassifier(min_samples_split=5), + 'SGD': SGDClassifier(alpha=0.001, n_iter=2), + 'GaussianNB': GaussianNB(), + 'liblinear': LinearSVC(loss="l2", penalty="l2", C=1000, dual=False, + tol=1e-3) +} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument('--classifiers', nargs="+", + choices=ESTIMATORS, type=str, + default=['liblinear', 'GaussianNB', 'SGD', 'CART'], + help="list of classifiers to benchmark.") + parser.add_argument('--n-jobs', nargs="?", default=1, type=int, + help="Number of concurrently running workers for " + "models that support parallelism.") + parser.add_argument('--order', nargs="?", default="C", type=str, + choices=["F", "C"], + help="Allow to choose between fortran and C ordered " + "data") + parser.add_argument('--random-seed', nargs="?", default=13, type=int, + help="Common seed used by random number generator.") + args = vars(parser.parse_args()) + + print(__doc__) + + X_train, X_test, y_train, y_test = load_data( + order=args["order"], random_state=args["random_seed"]) + + print("") + print("Dataset statistics:") + print("===================") + print("%s %d" % ("number of features:".ljust(25), X_train.shape[1])) + print("%s %d" % ("number of classes:".ljust(25), np.unique(y_train).size)) + print("%s %s" % ("data type:".ljust(25), X_train.dtype)) + print("%s %d (pos=%d, neg=%d, size=%dMB)" + % ("number of train samples:".ljust(25), + X_train.shape[0], np.sum(y_train == 1), + np.sum(y_train == 0), int(X_train.nbytes / 1e6))) + print("%s %d (pos=%d, neg=%d, size=%dMB)" + % ("number of test samples:".ljust(25), + X_test.shape[0], np.sum(y_test == 1), + np.sum(y_test == 0), int(X_test.nbytes / 1e6))) + + print() + print("Training Classifiers") + print("====================") + error, train_time, test_time = {}, {}, {} + for name in sorted(args["classifiers"]): + print("Training %s ... " % name, end="") + estimator = ESTIMATORS[name] + estimator_params = estimator.get_params() + + estimator.set_params(**{p: args["random_seed"] + for p in estimator_params + if p.endswith("random_state")}) + + if "n_jobs" in estimator_params: + estimator.set_params(n_jobs=args["n_jobs"]) + + time_start = time() + estimator.fit(X_train, y_train) + train_time[name] = time() - time_start + + time_start = time() + y_pred = estimator.predict(X_test) + test_time[name] = time() - time_start + + error[name] = zero_one_loss(y_test, y_pred) + + print("done") + + print() + print("Classification performance:") + print("===========================") + print("%s %s %s %s" + % ("Classifier ", "train-time", "test-time", "error-rate")) + print("-" * 44) + for name in sorted(args["classifiers"], key=error.get): + print("%s %s %s %s" % (name.ljust(12), + ("%.4fs" % train_time[name]).center(10), + ("%.4fs" % test_time[name]).center(10), + ("%.4f" % error[name]).center(10))) + + print() diff --git a/benchmarks/bench_glm.py b/benchmarks/bench_glm.py index fed5e5bc106f8..598ba5fe2a95d 100644 --- a/benchmarks/bench_glm.py +++ b/benchmarks/bench_glm.py @@ -24,7 +24,7 @@ for i in range(n_iter): - print 'Iteration %s of %s' % (i, n_iter) + print('Iteration %s of %s' % (i, n_iter)) n_samples, n_features = 10 * i + 3, 10 * i + 3 @@ -46,12 +46,13 @@ lasso.fit(X, Y) time_lasso[i] = total_seconds(datetime.now() - start) - pl.xlabel('Dimesions') - pl.ylabel('Time (in seconds)') + pl.figure('scikit-learn GLM benchmark results') + pl.xlabel('Dimensions') + pl.ylabel('Time (s)') pl.plot(dimensions, time_ridge, color='r') pl.plot(dimensions, time_ols, color='g') pl.plot(dimensions, time_lasso, color='b') - pl.legend(['Ridge', 'OLS', 'LassoLars']) + pl.legend(['Ridge', 'OLS', 'LassoLars'], loc='upper left') pl.axis('tight') pl.show() diff --git a/benchmarks/bench_glmnet.py b/benchmarks/bench_glmnet.py index b9c77fbed0609..4b9c35040c526 100644 --- a/benchmarks/bench_glmnet.py +++ b/benchmarks/bench_glmnet.py @@ -38,9 +38,9 @@ def bench(factory, X, Y, X_test, Y_test, ref_coef): delta = (time() - tstart) # stop time - print "duration: %0.3fs" % delta - print "rmse: %f" % rmse(Y_test, clf.predict(X_test)) - print "mean coef abs diff: %f" % abs(ref_coef - clf.coef_.ravel()).mean() + print("duration: %0.3fs" % delta) + print("rmse: %f" % rmse(Y_test, clf.predict(X_test))) + print("mean coef abs diff: %f" % abs(ref_coef - clf.coef_.ravel()).mean()) return delta @@ -58,9 +58,9 @@ def bench(factory, X, Y, X_test, Y_test, ref_coef): n_informative = n_features / 10 n_test_samples = 1000 for i in range(1, n + 1): - print '==================' - print 'Iteration %s of %s' % (i, n) - print '==================' + print('==================') + print('Iteration %s of %s' % (i, n)) + print('==================') X, Y, coef_ = make_regression( n_samples=(i * step) + n_test_samples, n_features=n_features, @@ -71,9 +71,9 @@ def bench(factory, X, Y, X_test, Y_test, ref_coef): X = X[:(i * step)] Y = Y[:(i * step)] - print "benching scikit: " + print("benchmarking scikit-learn: ") scikit_results.append(bench(ScikitLasso, X, Y, X_test, Y_test, coef_)) - print "benching glmnet: " + print("benchmarking glmnet: ") glmnet_results.append(bench(GlmnetLasso, X, Y, X_test, Y_test, coef_)) pl.clf() @@ -83,10 +83,10 @@ def bench(factory, X, Y, X_test, Y_test, ref_coef): pl.plot(xx, glmnet_results, 'r-', label='glmnet') pl.legend() pl.xlabel('number of samples to classify') - pl.ylabel('time (in seconds)') + pl.ylabel('Time (s)') pl.show() - # now do a bench where the number of points is fixed + # now do a benchmark where the number of points is fixed # and the variable is the number of features scikit_results = [] @@ -96,9 +96,9 @@ def bench(factory, X, Y, X_test, Y_test, ref_coef): n_samples = 500 for i in range(1, n + 1): - print '==================' - print 'Iteration %02d of %02d' % (i, n) - print '==================' + print('==================') + print('Iteration %02d of %02d' % (i, n)) + print('==================') n_features = i * step n_informative = n_features / 10 @@ -111,18 +111,18 @@ def bench(factory, X, Y, X_test, Y_test, ref_coef): X = X[:n_samples] Y = Y[:n_samples] - print "benching scikit: " + print("benchmarking scikit-learn: ") scikit_results.append(bench(ScikitLasso, X, Y, X_test, Y_test, coef_)) - print "benching glmnet: " + print("benchmarking glmnet: ") glmnet_results.append(bench(GlmnetLasso, X, Y, X_test, Y_test, coef_)) xx = np.arange(100, 100 + n * step, step) - pl.figure() + pl.figure('scikit-learn vs. glmnet benchmark results') pl.title('Regression in high dimensional spaces (%d samples)' % n_samples) pl.plot(xx, scikit_results, 'b-', label='scikit-learn') pl.plot(xx, glmnet_results, 'r-', label='glmnet') pl.legend() pl.xlabel('number of features') - pl.ylabel('time (in seconds)') + pl.ylabel('Time (s)') pl.axis('tight') pl.show() diff --git a/benchmarks/bench_isotonic.py b/benchmarks/bench_isotonic.py new file mode 100644 index 0000000000000..f9bc497698f72 --- /dev/null +++ b/benchmarks/bench_isotonic.py @@ -0,0 +1,91 @@ +""" +Benchmarks of isotonic regression performance. + +We generate a synthetic dataset of size 10^n, for n in [min, max], and +examine the time taken to run isotonic regression over the dataset. + +The timings are then output to stdout, or visualized on a log-log scale +with matplotlib. + +This alows the scaling of the algorithm with the problem size to be +visualized and understood. +""" +from __future__ import print_function + +import numpy as np +import gc +from datetime import datetime +from sklearn.isotonic import isotonic_regression +from sklearn.utils.bench import total_seconds +import matplotlib.pyplot as plt +import argparse + + +def generate_perturbed_logarithm_dataset(size): + return np.random.randint(-50, 50, size=n) \ + + 50. * np.log(1 + np.arange(n)) + + +def generate_logistic_dataset(size): + X = np.sort(np.random.normal(size=size)) + return np.random.random(size=size) < 1.0 / (1.0 + np.exp(-X)) + + +DATASET_GENERATORS = { + 'perturbed_logarithm': generate_perturbed_logarithm_dataset, + 'logistic': generate_logistic_dataset +} + + +def bench_isotonic_regression(Y): + """ + Runs a single iteration of isotonic regression on the input data, + and reports the total time taken (in seconds). + """ + gc.collect() + + tstart = datetime.now() + isotonic_regression(Y) + delta = datetime.now() - tstart + return total_seconds(delta) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="Isotonic Regression benchmark tool") + parser.add_argument('--iterations', type=int, required=True, + help="Number of iterations to average timings over " + "for each problem size") + parser.add_argument('--log_min_problem_size', type=int, required=True, + help="Base 10 logarithm of the minimum problem size") + parser.add_argument('--log_max_problem_size', type=int, required=True, + help="Base 10 logarithm of the maximum problem size") + parser.add_argument('--show_plot', action='http://github.com/store_true', + help="Plot timing output with matplotlib") + parser.add_argument('--dataset', choices=DATASET_GENERATORS.keys(), + required=True) + + args = parser.parse_args() + + timings = [] + for exponent in range(args.log_min_problem_size, + args.log_max_problem_size): + n = 10 ** exponent + Y = DATASET_GENERATORS[args.dataset](n) + time_per_iteration = \ + [bench_isotonic_regression(Y) for i in range(args.iterations)] + timing = (n, np.mean(time_per_iteration)) + timings.append(timing) + + # If we're not plotting, dump the timing to stdout + if not args.show_plot: + print(n, np.mean(time_per_iteration)) + + if args.show_plot: + plt.plot(*zip(*timings)) + plt.title("Average time taken running isotonic regression") + plt.xlabel('Number of observations') + plt.ylabel('Time (s)') + plt.axis('tight') + plt.loglog() + plt.show() diff --git a/benchmarks/bench_lasso.py b/benchmarks/bench_lasso.py index c72b21eb54a0a..7934fe1fdb0ba 100644 --- a/benchmarks/bench_lasso.py +++ b/benchmarks/bench_lasso.py @@ -19,20 +19,18 @@ def compute_bench(alpha, n_samples, n_features, precompute): - lasso_results = [] lars_lasso_results = [] - n_test_samples = 0 it = 0 for ns in n_samples: for nf in n_features: it += 1 - print '==================' - print 'Iteration %s of %s' % (it, max(len(n_samples), - len(n_features))) - print '==================' + print('==================') + print('Iteration %s of %s' % (it, max(len(n_samples), + len(n_features)))) + print('==================') n_informative = nf // 10 X, Y, coef_ = make_regression(n_samples=ns, n_features=nf, n_informative=n_informative, @@ -41,7 +39,7 @@ def compute_bench(alpha, n_samples, n_features, precompute): X /= np.sqrt(np.sum(X ** 2, axis=0)) # Normalize data gc.collect() - print "- benching Lasso" + print("- benchmarking Lasso") clf = Lasso(alpha=alpha, fit_intercept=False, precompute=precompute) tstart = time() @@ -49,7 +47,7 @@ def compute_bench(alpha, n_samples, n_features, precompute): lasso_results.append(time() - tstart) gc.collect() - print "- benching LassoLars" + print("- benchmarking LassoLars") clf = LassoLars(alpha=alpha, fit_intercept=False, normalize=False, precompute=precompute) tstart = time() @@ -70,16 +68,16 @@ def compute_bench(alpha, n_samples, n_features, precompute): lasso_results, lars_lasso_results = compute_bench(alpha, list_n_samples, [n_features], precompute=True) - pl.clf() + pl.figure('scikit-learn LASSO benchmark results') pl.subplot(211) pl.plot(list_n_samples, lasso_results, 'b-', - label='Lasso (with precomputed Gram matrix)') + label='Lasso') pl.plot(list_n_samples, lars_lasso_results, 'r-', - label='LassoLars (with precomputed Gram matrix)') - pl.title('Lasso benchmark (%d features - alpha=%s)' % (n_features, alpha)) + label='LassoLars') + pl.title('precomputed Gram matrix, %d features, alpha=%s' % (n_features, alpha)) pl.legend(loc='upper left') pl.xlabel('number of samples') - pl.ylabel('time (in seconds)') + pl.ylabel('Time (s)') pl.axis('tight') n_samples = 2000 @@ -89,9 +87,9 @@ def compute_bench(alpha, n_samples, n_features, precompute): pl.subplot(212) pl.plot(list_n_features, lasso_results, 'b-', label='Lasso') pl.plot(list_n_features, lars_lasso_results, 'r-', label='LassoLars') - pl.title('Lasso benchmark (%d samples - alpha=%s)' % (n_samples, alpha)) + pl.title('%d samples, alpha=%s' % (n_samples, alpha)) pl.legend(loc='upper left') pl.xlabel('number of features') - pl.ylabel('time (in seconds)') + pl.ylabel('Time (s)') pl.axis('tight') pl.show() diff --git a/benchmarks/bench_mnist.py b/benchmarks/bench_mnist.py new file mode 100644 index 0000000000000..fbf42adad79d8 --- /dev/null +++ b/benchmarks/bench_mnist.py @@ -0,0 +1,164 @@ +""" +======================= +MNIST dataset benchmark +======================= + +Benchmark on the MNIST dataset. The dataset comprises 70,000 samples +and 784 features. Here, we consider the task of predicting +10 classes - digits from 0 to 9 from their raw images. By contrast to the +covertype dataset, the feature space is homogenous. + +Example of output : + + [..] + Classification performance: + =========================== + Classifier train-time test-time error-rat + ------------------------------------------------------------ + Nystroem-SVM 105.07s 0.91s 0.0227 + ExtraTrees 48.20s 1.22s 0.0288 + RandomForest 47.17s 1.21s 0.0304 + SampledRBF-SVM 140.45s 0.84s 0.0486 + CART 22.84s 0.16s 0.1214 + dummy 0.01s 0.02s 0.8973 + +""" +from __future__ import division, print_function + +# Author: Issam H. Laradji +# Arnaud Joly +# License: BSD 3 clause + +import os +from time import time +import argparse +import numpy as np + +from sklearn.datasets import fetch_mldata +from sklearn.datasets import get_data_home +from sklearn.ensemble import ExtraTreesClassifier +from sklearn.ensemble import RandomForestClassifier +from sklearn.dummy import DummyClassifier +from sklearn.externals.joblib import Memory +from sklearn.kernel_approximation import Nystroem +from sklearn.kernel_approximation import RBFSampler +from sklearn.metrics import zero_one_loss +from sklearn.pipeline import make_pipeline +from sklearn.svm import LinearSVC +from sklearn.tree import DecisionTreeClassifier +from sklearn.utils import check_array + +# Memoize the data extraction and memory map the resulting +# train / test splits in readonly mode +memory = Memory(os.path.join(get_data_home(), 'mnist_benchmark_data'), + mmap_mode='r') + + +@memory.cache +def load_data(dtype=np.float32, order='F'): + """Load the data, then cache and memmap the train/test split""" + ###################################################################### + ## Load dataset + print("Loading dataset...") + data = fetch_mldata('MNIST original') + X = check_array(data['data'], dtype=dtype, order=order) + y = data["target"] + + # Normalize features + X = X / 255 + + ## Create train-test split (as [Joachims, 2006]) + print("Creating train-test split...") + n_train = 60000 + X_train = X[:n_train] + y_train = y[:n_train] + X_test = X[n_train:] + y_test = y[n_train:] + + return X_train, X_test, y_train, y_test + + +ESTIMATORS = { + "dummy": DummyClassifier(), + 'CART': DecisionTreeClassifier(), + 'ExtraTrees': ExtraTreesClassifier(n_estimators=100), + 'RandomForest': RandomForestClassifier(n_estimators=100), + 'Nystroem-SVM': + make_pipeline(Nystroem(gamma=0.015, n_components=1000), LinearSVC(C=100)), + 'SampledRBF-SVM': + make_pipeline(RBFSampler(gamma=0.015, n_components=1000), LinearSVC(C=100)) +} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument('--classifiers', nargs="+", + choices=ESTIMATORS, type=str, + default=['ExtraTrees', 'Nystroem-SVM'], + help="list of classifiers to benchmark.") + parser.add_argument('--n-jobs', nargs="?", default=1, type=int, + help="Number of concurrently running workers for " + "models that support parallelism.") + parser.add_argument('--order', nargs="?", default="C", type=str, + choices=["F", "C"], + help="Allow to choose between fortran and C ordered " + "data") + parser.add_argument('--random-seed', nargs="?", default=0, type=int, + help="Common seed used by random number generator.") + args = vars(parser.parse_args()) + + print(__doc__) + + X_train, X_test, y_train, y_test = load_data(order=args["order"]) + + print("") + print("Dataset statistics:") + print("===================") + print("%s %d" % ("number of features:".ljust(25), X_train.shape[1])) + print("%s %d" % ("number of classes:".ljust(25), np.unique(y_train).size)) + print("%s %s" % ("data type:".ljust(25), X_train.dtype)) + print("%s %d (size=%dMB)" % ("number of train samples:".ljust(25), + X_train.shape[0], int(X_train.nbytes / 1e6))) + print("%s %d (size=%dMB)" % ("number of test samples:".ljust(25), + X_test.shape[0], int(X_test.nbytes / 1e6))) + + print() + print("Training Classifiers") + print("====================") + error, train_time, test_time = {}, {}, {} + for name in sorted(args["classifiers"]): + print("Training %s ... " % name, end="") + estimator = ESTIMATORS[name] + estimator_params = estimator.get_params() + + estimator.set_params(**{p: args["random_seed"] + for p in estimator_params + if p.endswith("random_state")}) + + if "n_jobs" in estimator_params: + estimator.set_params(n_jobs=args["n_jobs"]) + + time_start = time() + estimator.fit(X_train, y_train) + train_time[name] = time() - time_start + + time_start = time() + y_pred = estimator.predict(X_test) + test_time[name] = time() - time_start + + error[name] = zero_one_loss(y_test, y_pred) + + print("done") + + print() + print("Classification performance:") + print("===========================") + print("{0: <24} {1: >10} {2: >11} {3: >12}" + "".format("Classifier ", "train-time", "test-time", "error-rate")) + print("-" * 60) + for name in sorted(args["classifiers"], key=error.get): + + print("{0: <23} {1: >10.2f}s {2: >10.2f}s {3: >12.4f}" + "".format(name, train_time[name], test_time[name], error[name])) + + print() diff --git a/benchmarks/bench_multilabel_metrics.py b/benchmarks/bench_multilabel_metrics.py new file mode 100755 index 0000000000000..669d8604e05f0 --- /dev/null +++ b/benchmarks/bench_multilabel_metrics.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python +""" +A comparison of multilabel target formats and metrics over them +""" +from __future__ import division +from __future__ import print_function + +from timeit import timeit +from functools import partial +import itertools +import argparse +import sys + +import matplotlib.pyplot as plt +import scipy.sparse as sp +import numpy as np + +from sklearn.datasets import make_multilabel_classification +from sklearn.metrics import (f1_score, accuracy_score, hamming_loss, + jaccard_similarity_score) +from sklearn.utils.testing import ignore_warnings + + +METRICS = { + 'f1': partial(f1_score, average='micro'), + 'f1-by-sample': partial(f1_score, average='samples'), + 'accuracy': accuracy_score, + 'hamming': hamming_loss, + 'jaccard': jaccard_similarity_score, +} + +FORMATS = { + 'sequences': lambda y: [list(np.flatnonzero(s)) for s in y], + 'dense': lambda y: y, + 'csr': lambda y: sp.csr_matrix(y), + 'csc': lambda y: sp.csc_matrix(y), +} + + +@ignore_warnings +def benchmark(metrics=tuple(v for k, v in sorted(METRICS.items())), + formats=tuple(v for k, v in sorted(FORMATS.items())), + samples=1000, classes=4, density=.2, + n_times=5): + """Times metric calculations for a number of inputs + + Parameters + ---------- + metrics : array-like of callables (1d or 0d) + The metric functions to time. + + formats : array-like of callables (1d or 0d) + These may transform a dense indicator matrix into multilabel + representation. + + samples : array-like of ints (1d or 0d) + The number of samples to generate as input. + + classes : array-like of ints (1d or 0d) + The number of classes in the input. + + density : array-like of ints (1d or 0d) + The density of positive labels in the input. + + n_times : int + Time calling the metric n_times times. + + Returns + ------- + array of floats shaped like (metrics, formats, samples, classes, density) + Time in seconds. + """ + metrics = np.atleast_1d(metrics) + samples = np.atleast_1d(samples) + classes = np.atleast_1d(classes) + density = np.atleast_1d(density) + formats = np.atleast_1d(formats) + out = np.zeros((len(metrics), len(formats), len(samples), len(classes), + len(density)), dtype=float) + it = itertools.product(samples, classes, density) + for i, (s, c, d) in enumerate(it): + _, y_true = make_multilabel_classification(n_samples=s, n_features=1, + n_classes=c, n_labels=d * c, + return_indicator=True, + random_state=42) + _, y_pred = make_multilabel_classification(n_samples=s, n_features=1, + n_classes=c, n_labels=d * c, + return_indicator=True, + random_state=84) + for j, f in enumerate(formats): + f_true = f(y_true) + f_pred = f(y_pred) + for k, metric in enumerate(metrics): + t = timeit(partial(metric, f_true, f_pred), number=n_times) + + out[k, j].flat[i] = t + return out + + +def _tabulate(results, metrics, formats): + """Prints results by metric and format + + Uses the last ([-1]) value of other fields + """ + column_width = max(max(len(k) for k in formats) + 1, 8) + first_width = max(len(k) for k in metrics) + head_fmt = ('{:<{fw}s}' + '{:>{cw}s}' * len(formats)) + row_fmt = ('{:<{fw}s}' + '{:>{cw}.3f}' * len(formats)) + print(head_fmt.format('Metric', *formats, + cw=column_width, fw=first_width)) + for metric, row in zip(metrics, results[:, :, -1, -1, -1]): + print(row_fmt.format(metric, *row, + cw=column_width, fw=first_width)) + + +def _plot(results, metrics, formats, title, x_ticks, x_label, + format_markers=('x', '|', 'o', '+'), + metric_colors=('c', 'm', 'y', 'k', 'g', 'r', 'b')): + """ + Plot the results by metric, format and some other variable given by + x_label + """ + fig = plt.figure('scikit-learn multilabel metrics benchmarks') + plt.title(title) + ax = fig.add_subplot(111) + for i, metric in enumerate(metrics): + for j, format in enumerate(formats): + ax.plot(x_ticks, results[i, j].flat, + label='{}, {}'.format(metric, format), + marker=format_markers[j], + color=metric_colors[i % len(metric_colors)]) + ax.set_xlabel(x_label) + ax.set_ylabel('Time (s)') + ax.legend() + plt.show() + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument('metrics', nargs='*', default=sorted(METRICS), + help='Specifies metrics to benchmark, defaults to all. ' + 'Choices are: {}'.format(sorted(METRICS))) + ap.add_argument('--formats', nargs='+', choices=sorted(FORMATS), + help='Specifies multilabel formats to benchmark ' + '(defaults to all).') + ap.add_argument('--samples', type=int, default=1000, + help='The number of samples to generate') + ap.add_argument('--classes', type=int, default=10, + help='The number of classes') + ap.add_argument('--density', type=float, default=.2, + help='The average density of labels per sample') + ap.add_argument('--plot', choices=['classes', 'density', 'samples'], + default=None, + help='Plot time with respect to this parameter varying ' + 'up to the specified value') + ap.add_argument('--n-steps', default=10, type=int, + help='Plot this many points for each metric') + ap.add_argument('--n-times', + default=5, type=int, + help="Time performance over n_times trials") + args = ap.parse_args() + + if args.plot is not None: + max_val = getattr(args, args.plot) + if args.plot in ('classes', 'samples'): + min_val = 2 + else: + min_val = 0 + steps = np.linspace(min_val, max_val, num=args.n_steps + 1)[1:] + if args.plot in ('classes', 'samples'): + steps = np.unique(np.round(steps).astype(int)) + setattr(args, args.plot, steps) + + if args.metrics is None: + args.metrics = sorted(METRICS) + if args.formats is None: + args.formats = sorted(FORMATS) + + results = benchmark([METRICS[k] for k in args.metrics], + [FORMATS[k] for k in args.formats], + args.samples, args.classes, args.density, + args.n_times) + + _tabulate(results, args.metrics, args.formats) + + if args.plot is not None: + print('Displaying plot', file=sys.stderr) + title = ('Multilabel metrics with %s' % + ', '.join('{0}={1}'.format(field, getattr(args, field)) + for field in ['samples', 'classes', 'density'] + if args.plot != field)) + _plot(results, args.metrics, args.formats, title, steps, args.plot) diff --git a/benchmarks/bench_plot_approximate_neighbors.py b/benchmarks/bench_plot_approximate_neighbors.py new file mode 100644 index 0000000000000..3354c38170e9d --- /dev/null +++ b/benchmarks/bench_plot_approximate_neighbors.py @@ -0,0 +1,171 @@ +""" +Benchmark for approximate nearest neighbor search using +locality sensitive hashing forest. + +There are two types of benchmarks. + +First, accuracy of LSHForest queries are measured for various +hyper-parameters and index sizes. + +Second, speed up of LSHForest queries compared to brute force +method in exact nearest neighbors is measures for the +aforementioned settings. In general, speed up is increasing as +the index size grows. +""" + +from __future__ import division + +import numpy as np +from tempfile import gettempdir +from time import time + +from sklearn.neighbors import NearestNeighbors +from sklearn.neighbors.approximate import LSHForest +from sklearn.datasets import make_blobs +from sklearn.externals.joblib import Memory + +m = Memory(cachedir=gettempdir()) + + +@m.cache() +def make_data(n_samples, n_features, n_queries, random_state=0): + """Create index and query data.""" + print('Generating random blob-ish data') + X, _ = make_blobs(n_samples=n_samples + n_queries, + n_features=n_features, centers=100, + shuffle=True, random_state=random_state) + + # Keep the last samples as held out query vectors: note since we used + # shuffle=True we have ensured that index and query vectors are + # samples from the same distribution (a mixture of 100 gaussians in this + # case) + return X[:n_samples], X[n_samples:] + + +def calc_exact_neighbors(X, queries, n_queries, n_neighbors): + """Measures average times for exact neighbor queries.""" + print ('Building NearestNeighbors for %d samples in %d dimensions' % + (X.shape[0], X.shape[1])) + nbrs = NearestNeighbors(algorithm='brute', metric='cosine').fit(X) + average_time = 0 + + t0 = time() + neighbors = nbrs.kneighbors(queries, n_neighbors=n_neighbors, + return_distance=False) + average_time = (time() - t0) / n_queries + return neighbors, average_time + + +def calc_accuracy(X, queries, n_queries, n_neighbors, exact_neighbors, + average_time_exact, **lshf_params): + """Calculates accuracy and the speed up of LSHForest.""" + print('Building LSHForest for %d samples in %d dimensions' % + (X.shape[0], X.shape[1])) + lshf = LSHForest(**lshf_params) + t0 = time() + lshf.fit(X) + lshf_build_time = time() - t0 + print('Done in %0.3fs' % lshf_build_time) + + accuracy = 0 + + t0 = time() + approx_neighbors = lshf.kneighbors(queries, n_neighbors=n_neighbors, + return_distance=False) + average_time_approx = (time() - t0) / n_queries + + for i in range(len(queries)): + accuracy += np.in1d(approx_neighbors[i], exact_neighbors[i]).mean() + + accuracy /= n_queries + speed_up = average_time_exact / average_time_approx + + print('Average time for lshf neighbor queries: %0.3fs' % + average_time_approx) + print ('Average time for exact neighbor queries: %0.3fs' % + average_time_exact) + print ('Average Accuracy : %0.2f' % accuracy) + print ('Speed up: %0.1fx' % speed_up) + + return speed_up, accuracy + + +if __name__ == '__main__': + import matplotlib.pyplot as plt + # Initialize index sizes + n_samples = [int(1e3), int(1e4), int(1e5), int(1e6)] + n_features = int(1e2) + n_queries = 100 + n_neighbors = 10 + + X_index, X_query = make_data(np.max(n_samples), n_features, n_queries, + random_state=0) + + params_list = [{'n_estimators': 3, 'n_candidates': 50}, + {'n_estimators': 5, 'n_candidates': 70}, + {'n_estimators': 10, 'n_candidates': 100}] + + accuracies = np.zeros((len(n_samples), len(params_list)), dtype=float) + speed_ups = np.zeros((len(n_samples), len(params_list)), dtype=float) + + for i, sample_size in enumerate(n_samples): + print ('==========================================================') + print ('Sample size: %i' % sample_size) + print ('------------------------') + exact_neighbors, average_time_exact = calc_exact_neighbors( + X_index[:sample_size], X_query, n_queries, n_neighbors) + for j, params in enumerate(params_list): + print ('LSHF parameters: n_estimators = %i, n_candidates = %i' % + (params['n_estimators'], params['n_candidates'])) + speed_ups[i, j], accuracies[i, j] = calc_accuracy( + X_index[:sample_size], X_query, n_queries, n_neighbors, + exact_neighbors, average_time_exact, random_state=0, **params) + print ('') + print ('==========================================================') + + # Set labels for LSHForest parameters + colors = ['c', 'm', 'y'] + p1 = plt.Rectangle((0, 0), 0.1, 0.1, fc=colors[0]) + p2 = plt.Rectangle((0, 0), 0.1, 0.1, fc=colors[1]) + p3 = plt.Rectangle((0, 0), 0.1, 0.1, fc=colors[2]) + + labels = ['n_estimators=' + str(params_list[0]['n_estimators']) + + ', n_candidates=' + str(params_list[0]['n_candidates']), + 'n_estimators=' + str(params_list[1]['n_estimators']) + + ', n_candidates=' + str(params_list[1]['n_candidates']), + 'n_estimators=' + str(params_list[2]['n_estimators']) + + ', n_candidates=' + str(params_list[2]['n_candidates'])] + + # Plot precision + plt.figure() + plt.legend((p1, p2, p3), (labels[0], labels[1], labels[2]), + loc='upper left') + + for i in range(len(params_list)): + plt.scatter(n_samples, accuracies[:, i], c=colors[i]) + plt.plot(n_samples, accuracies[:, i], c=colors[i]) + plt.ylim([0, 1.3]) + plt.xlim(np.min(n_samples), np.max(n_samples)) + plt.semilogx() + plt.ylabel("Precision@10") + plt.xlabel("Index size") + plt.grid(which='both') + plt.title("Precision of first 10 neighbors with index size") + + # Plot speed up + plt.figure() + plt.legend((p1, p2, p3), (labels[0], labels[1], labels[2]), + loc='upper left') + + for i in range(len(params_list)): + plt.scatter(n_samples, speed_ups[:, i], c=colors[i]) + plt.plot(n_samples, speed_ups[:, i], c=colors[i]) + plt.ylim(0, np.max(speed_ups)) + plt.xlim(np.min(n_samples), np.max(n_samples)) + plt.semilogx() + plt.ylabel("Speed up") + plt.xlabel("Index size") + plt.grid(which='both') + plt.title("Relationship between Speed up and index size") + + plt.show() diff --git a/benchmarks/bench_plot_fastkmeans.py b/benchmarks/bench_plot_fastkmeans.py index 974136b758577..4677fd21be056 100644 --- a/benchmarks/bench_plot_fastkmeans.py +++ b/benchmarks/bench_plot_fastkmeans.py @@ -1,6 +1,7 @@ -from time import time +from __future__ import print_function from collections import defaultdict +from time import time import numpy as np from numpy import random as nr @@ -11,7 +12,6 @@ def compute_bench(samples_range, features_range): it = 0 - iterations = 200 results = defaultdict(lambda: []) chunk = 100 @@ -19,40 +19,39 @@ def compute_bench(samples_range, features_range): for n_samples in samples_range: for n_features in features_range: it += 1 - print '==============================' - print 'Iteration %03d of %03d' % (it, max_it) - print '==============================' - print '' + print('==============================') + print('Iteration %03d of %03d' % (it, max_it)) + print('==============================') + print() data = nr.random_integers(-50, 50, (n_samples, n_features)) - print 'K-Means' + print('K-Means') tstart = time() - kmeans = KMeans(init='k-means++', - k=10).fit(data) + kmeans = KMeans(init='k-means++', n_clusters=10).fit(data) delta = time() - tstart - print "Speed: %0.3fs" % delta - print "Inertia: %0.5f" % kmeans.inertia_ - print '' + print("Speed: %0.3fs" % delta) + print("Inertia: %0.5f" % kmeans.inertia_) + print() results['kmeans_speed'].append(delta) results['kmeans_quality'].append(kmeans.inertia_) - print 'Fast K-Means' + print('Fast K-Means') # let's prepare the data in small chunks mbkmeans = MiniBatchKMeans(init='k-means++', - k=10, - batch_size=chunk) + n_clusters=10, + batch_size=chunk) tstart = time() mbkmeans.fit(data) delta = time() - tstart - print "Speed: %0.3fs" % delta - print "Inertia: %f" % mbkmeans.inertia_ - print '' - print '' + print("Speed: %0.3fs" % delta) + print("Inertia: %f" % mbkmeans.inertia_) + print() + print() - results['minibatchkmeans_speed'].append(delta) - results['minibatchkmeans_quality'].append(mbkmeans.inertia_) + results['MiniBatchKMeans Speed'].append(delta) + results['MiniBatchKMeans Quality'].append(mbkmeans.inertia_) return results @@ -63,31 +62,31 @@ def compute_bench_2(chunks): means = np.array([[1, 1], [-1, -1], [1, -1], [-1, 1], [0.5, 0.5], [0.75, -0.5], [-1, 0.75], [1, 0]]) X = np.empty((0, 2)) - for i in xrange(8): + for i in range(8): X = np.r_[X, means[i] + 0.8 * np.random.randn(n_features, 2)] max_it = len(chunks) it = 0 for chunk in chunks: it += 1 - print '==============================' - print 'Iteration %03d of %03d' % (it, max_it) - print '==============================' - print '' + print('==============================') + print('Iteration %03d of %03d' % (it, max_it)) + print('==============================') + print() - print 'Fast K-Means' + print('Fast K-Means') tstart = time() mbkmeans = MiniBatchKMeans(init='k-means++', - k=8, - batch_size=chunk) + n_clusters=8, + batch_size=chunk) mbkmeans.fit(X) delta = time() - tstart - print "Speed: %0.3fs" % delta - print "Inertia: %0.3fs" % mbkmeans.inertia_ - print '' + print("Speed: %0.3fs" % delta) + print("Inertia: %0.3fs" % mbkmeans.inertia_) + print() - results['minibatchkmeans_speed'].append(delta) - results['minibatchkmeans_quality'].append(mbkmeans.inertia_) + results['MiniBatchKMeans Speed'].append(delta) + results['MiniBatchKMeans Quality'].append(mbkmeans.inertia_) return results @@ -109,7 +108,7 @@ def compute_bench_2(chunks): t for (label, t) in results.iteritems() if "speed" not in label]]) - fig = plt.figure() + fig = plt.figure('scikit-learn K-Means benchmark results') for c, (label, timings) in zip('brcy', sorted(results.iteritems())): if 'speed' in label: @@ -133,7 +132,7 @@ def compute_bench_2(chunks): ax = fig.add_subplot(2, 2, i + 2) y = np.asarray(timings) ax.plot(chunks, y, color=c, alpha=0.8) - ax.set_xlabel('chunks') + ax.set_xlabel('Chunks') ax.set_ylabel(label) plt.show() diff --git a/benchmarks/bench_plot_incremental_pca.py b/benchmarks/bench_plot_incremental_pca.py new file mode 100644 index 0000000000000..495d58f0f43ee --- /dev/null +++ b/benchmarks/bench_plot_incremental_pca.py @@ -0,0 +1,156 @@ +""" +======================== +IncrementalPCA benchmark +======================== + +Benchmarks for IncrementalPCA + +""" + +import numpy as np +import gc +from time import time +from collections import defaultdict +import matplotlib.pyplot as plt +from sklearn.datasets import fetch_lfw_people +from sklearn.decomposition import IncrementalPCA, RandomizedPCA, PCA + + +def plot_results(X, y, label): + plt.plot(X, y, label=label, marker='o') + + +def benchmark(estimator, data): + gc.collect() + print("Benching %s" % estimator) + t0 = time() + estimator.fit(data) + training_time = time() - t0 + data_t = estimator.transform(data) + data_r = estimator.inverse_transform(data_t) + reconstruction_error = np.mean(np.abs(data - data_r)) + return {'time': training_time, 'error': reconstruction_error} + + +def plot_feature_times(all_times, batch_size, all_components, data): + plt.figure() + plot_results(all_components, all_times['pca'], label="PCA") + plot_results(all_components, all_times['ipca'], + label="IncrementalPCA, bsize=%i" % batch_size) + plot_results(all_components, all_times['rpca'], label="RandomizedPCA") + plt.legend(loc="upper left") + plt.suptitle("Algorithm runtime vs. n_components\n \ + LFW, size %i x %i" % data.shape) + plt.xlabel("Number of components (out of max %i)" % data.shape[1]) + plt.ylabel("Time (seconds)") + + +def plot_feature_errors(all_errors, batch_size, all_components, data): + plt.figure() + plot_results(all_components, all_errors['pca'], label="PCA") + plot_results(all_components, all_errors['ipca'], + label="IncrementalPCA, bsize=%i" % batch_size) + plot_results(all_components, all_errors['rpca'], label="RandomizedPCA") + plt.legend(loc="lower left") + plt.suptitle("Algorithm error vs. n_components\n" + "LFW, size %i x %i" % data.shape) + plt.xlabel("Number of components (out of max %i)" % data.shape[1]) + plt.ylabel("Mean absolute error") + + +def plot_batch_times(all_times, n_features, all_batch_sizes, data): + plt.figure() + plot_results(all_batch_sizes, all_times['pca'], label="PCA") + plot_results(all_batch_sizes, all_times['rpca'], label="RandomizedPCA") + plot_results(all_batch_sizes, all_times['ipca'], label="IncrementalPCA") + plt.legend(loc="lower left") + plt.suptitle("Algorithm runtime vs. batch_size for n_components %i\n \ + LFW, size %i x %i" % ( + n_features, data.shape[0], data.shape[1])) + plt.xlabel("Batch size") + plt.ylabel("Time (seconds)") + + +def plot_batch_errors(all_errors, n_features, all_batch_sizes, data): + plt.figure() + plot_results(all_batch_sizes, all_errors['pca'], label="PCA") + plot_results(all_batch_sizes, all_errors['ipca'], label="IncrementalPCA") + plt.legend(loc="lower left") + plt.suptitle("Algorithm error vs. batch_size for n_components %i\n \ + LFW, size %i x %i" % ( + n_features, data.shape[0], data.shape[1])) + plt.xlabel("Batch size") + plt.ylabel("Mean absolute error") + + +def fixed_batch_size_comparison(data): + all_features = [i.astype(int) for i in np.linspace(data.shape[1] // 10, + data.shape[1], num=5)] + batch_size = 1000 + # Compare runtimes and error for fixed batch size + all_times = defaultdict(list) + all_errors = defaultdict(list) + for n_components in all_features: + pca = PCA(n_components=n_components) + rpca = RandomizedPCA(n_components=n_components, random_state=1999) + ipca = IncrementalPCA(n_components=n_components, batch_size=batch_size) + results_dict = {k: benchmark(est, data) for k, est in [('pca', pca), + ('ipca', ipca), + ('rpca', rpca)]} + + for k in sorted(results_dict.keys()): + all_times[k].append(results_dict[k]['time']) + all_errors[k].append(results_dict[k]['error']) + + plot_feature_times(all_times, batch_size, all_features, data) + plot_feature_errors(all_errors, batch_size, all_features, data) + + +def variable_batch_size_comparison(data): + batch_sizes = [i.astype(int) for i in np.linspace(data.shape[0] // 10, + data.shape[0], num=10)] + + for n_components in [i.astype(int) for i in + np.linspace(data.shape[1] // 10, + data.shape[1], num=4)]: + all_times = defaultdict(list) + all_errors = defaultdict(list) + pca = PCA(n_components=n_components) + rpca = RandomizedPCA(n_components=n_components, random_state=1999) + results_dict = {k: benchmark(est, data) for k, est in [('pca', pca), + ('rpca', rpca)]} + + # Create flat baselines to compare the variation over batch size + all_times['pca'].extend([results_dict['pca']['time']] * + len(batch_sizes)) + all_errors['pca'].extend([results_dict['pca']['error']] * + len(batch_sizes)) + all_times['rpca'].extend([results_dict['rpca']['time']] * + len(batch_sizes)) + all_errors['rpca'].extend([results_dict['rpca']['error']] * + len(batch_sizes)) + for batch_size in batch_sizes: + ipca = IncrementalPCA(n_components=n_components, + batch_size=batch_size) + results_dict = {k: benchmark(est, data) for k, est in [('ipca', + ipca)]} + all_times['ipca'].append(results_dict['ipca']['time']) + all_errors['ipca'].append(results_dict['ipca']['error']) + + plot_batch_times(all_times, n_components, batch_sizes, data) + # RandomizedPCA error is always worse (approx 100x) than other PCA + # tests + plot_batch_errors(all_errors, n_components, batch_sizes, data) + +faces = fetch_lfw_people(resize=.2, min_faces_per_person=5) +# limit dataset to 5000 people (don't care who they are!) +X = faces.data[:5000] +n_samples, h, w = faces.images.shape +n_features = X.shape[1] + +X -= X.mean(axis=0) +X /= X.std(axis=0) + +fixed_batch_size_comparison(X) +variable_batch_size_comparison(X) +plt.show() diff --git a/benchmarks/bench_plot_lasso_path.py b/benchmarks/bench_plot_lasso_path.py index 845368e9e8e24..4456ab1aaedd1 100644 --- a/benchmarks/bench_plot_lasso_path.py +++ b/benchmarks/bench_plot_lasso_path.py @@ -2,12 +2,14 @@ The input data is mostly low rank but is a fat infinite tail. """ +from __future__ import print_function + +from collections import defaultdict import gc -from time import time import sys +from time import time import numpy as np -from collections import defaultdict from sklearn.linear_model import lars_path from sklearn.linear_model import lasso_path @@ -24,9 +26,9 @@ def compute_bench(samples_range, features_range): for n_samples in samples_range: for n_features in features_range: it += 1 - print '====================' - print 'Iteration %03d of %03d' % (it, max_it) - print '====================' + print('====================') + print('Iteration %03d of %03d' % (it, max_it)) + print('====================') dataset_kwargs = { 'n_samples': n_samples, 'n_features': n_features, @@ -35,46 +37,46 @@ def compute_bench(samples_range, features_range): #'effective_rank': None, 'bias': 0.0, } - print "n_samples: %d" % n_samples - print "n_features: %d" % n_features + print("n_samples: %d" % n_samples) + print("n_features: %d" % n_features) X, y = make_regression(**dataset_kwargs) gc.collect() - print "benching lars_path (with Gram):", + print("benchmarking lars_path (with Gram):", end='') sys.stdout.flush() tstart = time() G = np.dot(X.T, X) # precomputed Gram matrix Xy = np.dot(X.T, y) lars_path(X, y, Xy=Xy, Gram=G, method='lasso') delta = time() - tstart - print "%0.3fs" % delta + print("%0.3fs" % delta) results['lars_path (with Gram)'].append(delta) gc.collect() - print "benching lars_path (without Gram):", + print("benchmarking lars_path (without Gram):", end='') sys.stdout.flush() tstart = time() lars_path(X, y, method='lasso') delta = time() - tstart - print "%0.3fs" % delta + print("%0.3fs" % delta) results['lars_path (without Gram)'].append(delta) gc.collect() - print "benching lasso_path (with Gram):", + print("benchmarking lasso_path (with Gram):", end='') sys.stdout.flush() tstart = time() lasso_path(X, y, precompute=True) delta = time() - tstart - print "%0.3fs" % delta + print("%0.3fs" % delta) results['lasso_path (with Gram)'].append(delta) gc.collect() - print "benching lasso_path (without Gram):", + print("benchmarking lasso_path (without Gram):", end='') sys.stdout.flush() tstart = time() lasso_path(X, y, precompute=False) delta = time() - tstart - print "%0.3fs" % delta + print("%0.3fs" % delta) results['lasso_path (without Gram)'].append(delta) return results @@ -88,11 +90,11 @@ def compute_bench(samples_range, features_range): features_range = np.linspace(10, 2000, 5).astype(np.int) results = compute_bench(samples_range, features_range) - max_time = max(max(t) for t in results.itervalues()) + max_time = max(max(t) for t in results.values()) - fig = plt.figure() + fig = plt.figure('scikit-learn Lasso path benchmark results') i = 1 - for c, (label, timings) in zip('bcry', sorted(results.iteritems())): + for c, (label, timings) in zip('bcry', sorted(results.items())): ax = fig.add_subplot(2, 2, i, projection='3d') X, Y = np.meshgrid(samples_range, features_range) Z = np.asarray(timings).reshape(samples_range.shape[0], @@ -107,7 +109,7 @@ def compute_bench(samples_range, features_range): ax.set_xlabel('n_samples') ax.set_ylabel('n_features') - ax.set_zlabel('time (s)') + ax.set_zlabel('Time (s)') ax.set_zlim3d(0.0, max_time * 1.1) ax.set_title(label) #ax.legend() diff --git a/benchmarks/bench_plot_neighbors.py b/benchmarks/bench_plot_neighbors.py index 3cfc9883997ec..d163fb46b7193 100644 --- a/benchmarks/bench_plot_neighbors.py +++ b/benchmarks/bench_plot_neighbors.py @@ -44,7 +44,7 @@ def barplot_neighbors(Nrange=2 ** np.arange(1, 11), for alg in algorithms]) for i, NN in enumerate(Nrange): - print "N = %i (%i out of %i)" % (NN, i + 1, len(Nrange)) + print("N = %i (%i out of %i)" % (NN, i + 1, len(Nrange))) X = get_data(NN, D, dataset) for algorithm in algorithms: nbrs = neighbors.NearestNeighbors(n_neighbors=min(NN, k), @@ -67,7 +67,7 @@ def barplot_neighbors(Nrange=2 ** np.arange(1, 11), for alg in algorithms]) for i, DD in enumerate(Drange): - print "D = %i (%i out of %i)" % (DD, i + 1, len(Drange)) + print("D = %i (%i out of %i)" % (DD, i + 1, len(Drange))) X = get_data(N, DD, dataset) for algorithm in algorithms: nbrs = neighbors.NearestNeighbors(n_neighbors=k, @@ -92,7 +92,7 @@ def barplot_neighbors(Nrange=2 ** np.arange(1, 11), X = get_data(N, DD, dataset) for i, kk in enumerate(krange): - print "k = %i (%i out of %i)" % (kk, i + 1, len(krange)) + print("k = %i (%i out of %i)" % (kk, i + 1, len(krange))) for algorithm in algorithms: nbrs = neighbors.NearestNeighbors(n_neighbors=kk, algorithm=algorithm, @@ -131,10 +131,10 @@ def barplot_neighbors(Nrange=2 ** np.arange(1, 11), xvals = 0.1 + i * (1 + len(vals)) + np.arange(len(vals)) width = 0.8 - pl.bar(xvals, build_time[alg] - bottom, - width, bottom, color='r') - pl.bar(xvals, query_time[alg], - width, build_time[alg], color='b') + c_bar = pl.bar(xvals, build_time[alg] - bottom, + width, bottom, color='r') + q_bar = pl.bar(xvals, query_time[alg], + width, build_time[alg], color='b') tick_vals += list(xvals + 0.5 * width) tick_labels += ['%i' % val for val in vals] @@ -145,7 +145,7 @@ def barplot_neighbors(Nrange=2 ** np.arange(1, 11), va='top', bbox=dict(facecolor='w', edgecolor='w', alpha=0.5)) - pl.ylabel('time (seconds)') + pl.ylabel('Time (s)') ax.xaxis.set_major_locator(ticker.FixedLocator(tick_vals)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(tick_labels)) @@ -174,10 +174,10 @@ def barplot_neighbors(Nrange=2 ** np.arange(1, 11), transform=ax.transAxes, rotation=-90, ha='right', va='center') - pl.gcf().suptitle("%s data\nred = construction; blue = N-point query" - % (dataset[0].upper() + dataset[1:]), - fontsize=16) + pl.gcf().suptitle("%s data set" % dataset.capitalize(), fontsize=16) + pl.figlegend((c_bar, q_bar), ('construction', 'N-point query'), + 'upper right') if __name__ == '__main__': barplot_neighbors(dataset='digits') diff --git a/benchmarks/bench_plot_nmf.py b/benchmarks/bench_plot_nmf.py index 27c903e055a8c..db19462914a73 100644 --- a/benchmarks/bench_plot_nmf.py +++ b/benchmarks/bench_plot_nmf.py @@ -2,13 +2,18 @@ Benchmarks of Non-Negative Matrix Factorization """ +from __future__ import print_function + +from collections import defaultdict import gc from time import time + import numpy as np -from collections import defaultdict +from scipy.linalg import norm from sklearn.decomposition.nmf import NMF, _initialize_nmf from sklearn.datasets.samples_generator import make_low_rank_matrix +from sklearn.externals.six.moves import xrange def alt_nnmf(V, r, max_iter=1000, tol=1e-3, R=None): @@ -24,7 +29,7 @@ def alt_nnmf(V, r, max_iter=1000, tol=1e-3, R=None): r : integer number of latent features max_iter : integer, optional - maximum number of iterations (default: 10000) + maximum number of iterations (default: 1000) tol : double tolerance threshold for early exit (when the update factor is within tol of 1., the function exits) @@ -49,7 +54,7 @@ def alt_nnmf(V, r, max_iter=1000, tol=1e-3, R=None): n, m = V.shape if R == "svd": W, H = _initialize_nmf(V, r) - elif R == None: + elif R is None: R = np.random.mtrand._rand W = np.abs(R.standard_normal((n, r))) H = np.abs(R.standard_normal((r, m))) @@ -59,14 +64,20 @@ def alt_nnmf(V, r, max_iter=1000, tol=1e-3, R=None): H *= updateH updateW = np.dot(V, H.T) / (np.dot(W, np.dot(H, H.T)) + eps) W *= updateW - if True or (i % 10) == 0: + if i % 10 == 0: max_update = max(updateW.max(), updateH.max()) if abs(1. - max_update) < tol: break return W, H -def compute_bench(samples_range, features_range, rank=50, tolerance=1e-7): +def report(error, time): + print("Frobenius loss: %.5f" % error) + print("Took: %.2fs" % time) + print() + + +def benchmark(samples_range, features_range, rank=50, tolerance=1e-5): it = 0 timeset = defaultdict(lambda: []) err = defaultdict(lambda: []) @@ -74,74 +85,73 @@ def compute_bench(samples_range, features_range, rank=50, tolerance=1e-7): max_it = len(samples_range) * len(features_range) for n_samples in samples_range: for n_features in features_range: - it += 1 - print '====================' - print 'Iteration %03d of %03d' % (it, max_it) - print '====================' + print("%2d samples, %2d features" % (n_samples, n_features)) + print('=======================') X = np.abs(make_low_rank_matrix(n_samples, n_features, effective_rank=rank, tail_strength=0.2)) gc.collect() - print "benching nndsvd-nmf: " + print("benchmarking nndsvd-nmf: ") tstart = time() m = NMF(n_components=30, tol=tolerance, init='nndsvd').fit(X) tend = time() - tstart timeset['nndsvd-nmf'].append(tend) err['nndsvd-nmf'].append(m.reconstruction_err_) - print m.reconstruction_err_, tend + report(m.reconstruction_err_, tend) gc.collect() - print "benching nndsvda-nmf: " + print("benchmarking nndsvda-nmf: ") tstart = time() m = NMF(n_components=30, init='nndsvda', tol=tolerance).fit(X) tend = time() - tstart timeset['nndsvda-nmf'].append(tend) err['nndsvda-nmf'].append(m.reconstruction_err_) - print m.reconstruction_err_, tend + report(m.reconstruction_err_, tend) gc.collect() - print "benching nndsvdar-nmf: " + print("benchmarking nndsvdar-nmf: ") tstart = time() m = NMF(n_components=30, init='nndsvdar', tol=tolerance).fit(X) tend = time() - tstart timeset['nndsvdar-nmf'].append(tend) err['nndsvdar-nmf'].append(m.reconstruction_err_) - print m.reconstruction_err_, tend + report(m.reconstruction_err_, tend) gc.collect() - print "benching random-nmf" + print("benchmarking random-nmf") tstart = time() m = NMF(n_components=30, init=None, max_iter=1000, tol=tolerance).fit(X) tend = time() - tstart timeset['random-nmf'].append(tend) err['random-nmf'].append(m.reconstruction_err_) - print m.reconstruction_err_, tend + report(m.reconstruction_err_, tend) gc.collect() - print "benching alt-random-nmf" + print("benchmarking alt-random-nmf") tstart = time() W, H = alt_nnmf(X, r=30, R=None, tol=tolerance) tend = time() - tstart timeset['alt-random-nmf'].append(tend) err['alt-random-nmf'].append(np.linalg.norm(X - np.dot(W, H))) - print np.linalg.norm(X - np.dot(W, H)), tend + report(norm(X - np.dot(W, H)), tend) return timeset, err if __name__ == '__main__': from mpl_toolkits.mplot3d import axes3d # register the 3d projection + axes3d import matplotlib.pyplot as plt samples_range = np.linspace(50, 500, 3).astype(np.int) features_range = np.linspace(50, 500, 3).astype(np.int) - timeset, err = compute_bench(samples_range, features_range) + timeset, err = benchmark(samples_range, features_range) for i, results in enumerate((timeset, err)): - fig = plt.figure() + fig = plt.figure('scikit-learn Non-Negative Matrix Factorization benchmark results') ax = fig.gca(projection='3d') for c, (label, timings) in zip('rbgcm', sorted(results.iteritems())): X, Y = np.meshgrid(samples_range, features_range) @@ -156,7 +166,7 @@ def compute_bench(samples_range, features_range, rank=50, tolerance=1e-7): ax.set_xlabel('n_samples') ax.set_ylabel('n_features') - zlabel = 'time (s)' if i == 0 else 'reconstruction error' + zlabel = 'Time (s)' if i == 0 else 'reconstruction error' ax.set_zlabel(zlabel) ax.legend() plt.show() diff --git a/benchmarks/bench_plot_omp_lars.py b/benchmarks/bench_plot_omp_lars.py index 7341c892911bc..debc3c3be4567 100644 --- a/benchmarks/bench_plot_omp_lars.py +++ b/benchmarks/bench_plot_omp_lars.py @@ -3,9 +3,11 @@ The input data is mostly low rank but is a fat infinite tail. """ +from __future__ import print_function + import gc -from time import time import sys +from time import time import numpy as np @@ -28,9 +30,9 @@ def compute_bench(samples_range, features_range): for i_f, n_features in enumerate(features_range): it += 1 n_informative = n_features / 10 - print '====================' - print 'Iteration %03d of %03d' % (it, max_it) - print '====================' + print('====================') + print('Iteration %03d of %03d' % (it, max_it)) + print('====================') # dataset_kwargs = { # 'n_train_samples': n_samples, # 'n_test_samples': 2, @@ -47,49 +49,49 @@ def compute_bench(samples_range, features_range): 'n_nonzero_coefs': n_informative, 'random_state': 0 } - print "n_samples: %d" % n_samples - print "n_features: %d" % n_features + print("n_samples: %d" % n_samples) + print("n_features: %d" % n_features) y, X, _ = make_sparse_coded_signal(**dataset_kwargs) X = np.asfortranarray(X) gc.collect() - print "benching lars_path (with Gram):", + print("benchmarking lars_path (with Gram):", end='') sys.stdout.flush() tstart = time() G = np.dot(X.T, X) # precomputed Gram matrix Xy = np.dot(X.T, y) lars_path(X, y, Xy=Xy, Gram=G, max_iter=n_informative) delta = time() - tstart - print "%0.3fs" % delta + print("%0.3fs" % delta) lars_gram[i_f, i_s] = delta gc.collect() - print "benching lars_path (without Gram):", + print("benchmarking lars_path (without Gram):", end='') sys.stdout.flush() tstart = time() lars_path(X, y, Gram=None, max_iter=n_informative) delta = time() - tstart - print "%0.3fs" % delta + print("%0.3fs" % delta) lars[i_f, i_s] = delta gc.collect() - print "benching orthogonal_mp (with Gram):", + print("benchmarking orthogonal_mp (with Gram):", end='') sys.stdout.flush() tstart = time() - orthogonal_mp(X, y, precompute_gram=True, + orthogonal_mp(X, y, precompute=True, n_nonzero_coefs=n_informative) delta = time() - tstart - print "%0.3fs" % delta + print("%0.3fs" % delta) omp_gram[i_f, i_s] = delta gc.collect() - print "benching orthogonal_mp (without Gram):", + print("benchmarking orthogonal_mp (without Gram):", end='') sys.stdout.flush() tstart = time() - orthogonal_mp(X, y, precompute_gram=False, + orthogonal_mp(X, y, precompute=False, n_nonzero_coefs=n_informative) delta = time() - tstart - print "%0.3fs" % delta + print("%0.3fs" % delta) omp[i_f, i_s] = delta results['time(LARS) / time(OMP)\n (w/ Gram)'] = (lars_gram / omp_gram) @@ -101,10 +103,10 @@ def compute_bench(samples_range, features_range): samples_range = np.linspace(1000, 5000, 5).astype(np.int) features_range = np.linspace(1000, 5000, 5).astype(np.int) results = compute_bench(samples_range, features_range) - max_time = max(np.max(t) for t in results.itervalues()) + max_time = max(np.max(t) for t in results.values()) import pylab as pl - fig = pl.figure() + fig = pl.figure('scikit-learn OMP vs. LARS benchmark results') for i, (label, timings) in enumerate(sorted(results.iteritems())): ax = fig.add_subplot(1, 2, i) vmax = max(1 - timings.min(), -1 + timings.max()) diff --git a/benchmarks/bench_plot_parallel_pairwise.py b/benchmarks/bench_plot_parallel_pairwise.py index 36dac9f409211..c17f42d7ca5eb 100644 --- a/benchmarks/bench_plot_parallel_pairwise.py +++ b/benchmarks/bench_plot_parallel_pairwise.py @@ -1,5 +1,5 @@ # Author: Mathieu Blondel -# License: BSD Style. +# License: BSD 3 clause import time import pylab as pl @@ -25,11 +25,11 @@ def plot(func): func(X, n_jobs=-1) multi_core.append(time.time() - start) - pl.figure() + pl.figure('scikit-learn parallel %s benchmark results' % func.__name__) pl.plot(sample_sizes, one_core, label="one core") pl.plot(sample_sizes, multi_core, label="multi core") pl.xlabel('n_samples') - pl.ylabel('time') + pl.ylabel('Time (s)') pl.title('Parallel %s' % func.__name__) pl.legend() diff --git a/benchmarks/bench_plot_svd.py b/benchmarks/bench_plot_svd.py index 9f76a23dcc881..ce5cba9d54ecf 100644 --- a/benchmarks/bench_plot_svd.py +++ b/benchmarks/bench_plot_svd.py @@ -1,4 +1,4 @@ -"""Benchmarks of Singular Values Decomposition (Exact and Approximate) +"""Benchmarks of Singular Value Decomposition (Exact and Approximate) The data is mostly low rank but is a fat infinite tail. """ @@ -12,7 +12,7 @@ from sklearn.datasets.samples_generator import make_low_rank_matrix -def compute_bench(samples_range, features_range, n_iterations=3, rank=50): +def compute_bench(samples_range, features_range, n_iter=3, rank=50): it = 0 @@ -22,33 +22,33 @@ def compute_bench(samples_range, features_range, n_iterations=3, rank=50): for n_samples in samples_range: for n_features in features_range: it += 1 - print '====================' - print 'Iteration %03d of %03d' % (it, max_it) - print '====================' + print('====================') + print('Iteration %03d of %03d' % (it, max_it)) + print('====================') X = make_low_rank_matrix(n_samples, n_features, effective_rank=rank, tail_strength=0.2) gc.collect() - print "benching scipy svd: " + print("benchmarking scipy svd: ") tstart = time() svd(X, full_matrices=False) results['scipy svd'].append(time() - tstart) gc.collect() - print "benching scikit-learn randomized_svd: n_iterations=0" + print("benchmarking scikit-learn randomized_svd: n_iter=0") tstart = time() - randomized_svd(X, rank, n_iterations=0) - results['scikit-learn randomized_svd (n_iterations=0)'].append( + randomized_svd(X, rank, n_iter=0) + results['scikit-learn randomized_svd (n_iter=0)'].append( time() - tstart) gc.collect() - print ("benching scikit-learn randomized_svd: n_iterations=%d " - % n_iterations) + print("benchmarking scikit-learn randomized_svd: n_iter=%d " + % n_iter) tstart = time() - randomized_svd(X, rank, n_iterations=n_iterations) - results['scikit-learn randomized_svd (n_iterations=%d)' - % n_iterations].append(time() - tstart) + randomized_svd(X, rank, n_iter=n_iter) + results['scikit-learn randomized_svd (n_iter=%d)' + % n_iter].append(time() - tstart) return results @@ -61,7 +61,8 @@ def compute_bench(samples_range, features_range, n_iterations=3, rank=50): features_range = np.linspace(2, 1000, 4).astype(np.int) results = compute_bench(samples_range, features_range) - fig = plt.figure() + label = 'scikit-learn singular value decomposition benchmark results' + fig = plt.figure(label) ax = fig.gca(projection='3d') for c, (label, timings) in zip('rbg', sorted(results.iteritems())): X, Y = np.meshgrid(samples_range, features_range) @@ -76,6 +77,6 @@ def compute_bench(samples_range, features_range, n_iterations=3, rank=50): ax.set_xlabel('n_samples') ax.set_ylabel('n_features') - ax.set_zlabel('time (s)') + ax.set_zlabel('Time (s)') ax.legend() plt.show() diff --git a/benchmarks/bench_plot_ward.py b/benchmarks/bench_plot_ward.py index 452a19c1e7406..0159cc5232f08 100644 --- a/benchmarks/bench_plot_ward.py +++ b/benchmarks/bench_plot_ward.py @@ -1,5 +1,5 @@ """ -Bench the scikit's ward implement compared to scipy's +Benchmark scikit-learn's Ward implement compared to SciPy's """ import time @@ -8,9 +8,9 @@ from scipy.cluster import hierarchy import pylab as pl -from sklearn.cluster import Ward +from sklearn.cluster import AgglomerativeClustering -ward = Ward(n_clusters=3) +ward = AgglomerativeClustering(n_clusters=3, linkage='ward') n_samples = np.logspace(.5, 3, 9) n_features = np.logspace(1, 3.5, 7) @@ -31,7 +31,7 @@ ratio = scikits_time / scipy_time -pl.clf() +pl.figure("scikit-learn Ward's method benchmark results") pl.imshow(np.log(ratio), aspect='auto', origin="lower") pl.colorbar() pl.contour(ratio, levels=[1, ], colors='k') diff --git a/benchmarks/bench_random_projections.py b/benchmarks/bench_random_projections.py new file mode 100644 index 0000000000000..4379e50e98ab5 --- /dev/null +++ b/benchmarks/bench_random_projections.py @@ -0,0 +1,254 @@ +""" +=========================== +Random projection benchmark +=========================== + +Benchmarks for random projections. + +""" +from __future__ import division +from __future__ import print_function + +import gc +import sys +import optparse +from datetime import datetime +import collections + +import numpy as np +import scipy.sparse as sp + +from sklearn import clone +from sklearn.externals.six.moves import xrange +from sklearn.random_projection import (SparseRandomProjection, + GaussianRandomProjection, + johnson_lindenstrauss_min_dim) + + +def type_auto_or_float(val): + if val == "auto": + return "auto" + else: + return float(val) + + +def type_auto_or_int(val): + if val == "auto": + return "auto" + else: + return int(val) + + +def compute_time(t_start, delta): + mu_second = 0.0 + 10 ** 6 # number of microseconds in a second + + return delta.seconds + delta.microseconds / mu_second + + +def bench_scikit_transformer(X, transfomer): + gc.collect() + + clf = clone(transfomer) + + # start time + t_start = datetime.now() + clf.fit(X) + delta = (datetime.now() - t_start) + # stop time + time_to_fit = compute_time(t_start, delta) + + # start time + t_start = datetime.now() + clf.transform(X) + delta = (datetime.now() - t_start) + # stop time + time_to_transform = compute_time(t_start, delta) + + return time_to_fit, time_to_transform + + +# Make some random data with uniformly located non zero entries with +# Gaussian distributed values +def make_sparse_random_data(n_samples, n_features, n_nonzeros, + random_state=None): + rng = np.random.RandomState(random_state) + data_coo = sp.coo_matrix( + (rng.randn(n_nonzeros), + (rng.randint(n_samples, size=n_nonzeros), + rng.randint(n_features, size=n_nonzeros))), + shape=(n_samples, n_features)) + return data_coo.toarray(), data_coo.tocsr() + + +def print_row(clf_type, time_fit, time_transform): + print("%s | %s | %s" % (clf_type.ljust(30), + ("%.4fs" % time_fit).center(12), + ("%.4fs" % time_transform).center(12))) + + +if __name__ == "__main__": + ########################################################################### + # Option parser + ########################################################################### + op = optparse.OptionParser() + op.add_option("--n-times", + dest="n_times", default=5, type=int, + help="Benchmark results are average over n_times experiments") + + op.add_option("--n-features", + dest="n_features", default=10 ** 4, type=int, + help="Number of features in the benchmarks") + + op.add_option("--n-components", + dest="n_components", default="auto", + help="Size of the random subspace." + " ('auto' or int > 0)") + + op.add_option("--ratio-nonzeros", + dest="ratio_nonzeros", default=10 ** -3, type=float, + help="Number of features in the benchmarks") + + op.add_option("--n-samples", + dest="n_samples", default=500, type=int, + help="Number of samples in the benchmarks") + + op.add_option("--random-seed", + dest="random_seed", default=13, type=int, + help="Seed used by the random number generators.") + + op.add_option("--density", + dest="density", default=1 / 3, + help="Density used by the sparse random projection." + " ('auto' or float (0.0, 1.0]") + + op.add_option("--eps", + dest="eps", default=0.5, type=float, + help="See the documentation of the underlying transformers.") + + op.add_option("--transformers", + dest="selected_transformers", + default='GaussianRandomProjection,SparseRandomProjection', + type=str, + help="Comma-separated list of transformer to benchmark. " + "Default: %default. Available: " + "GaussianRandomProjection,SparseRandomProjection") + + op.add_option("--dense", + dest="dense", + default=False, + action="http://github.com/store_true", + help="Set input space as a dense matrix.") + + (opts, args) = op.parse_args() + if len(args) > 0: + op.error("this script takes no arguments.") + sys.exit(1) + opts.n_components = type_auto_or_int(opts.n_components) + opts.density = type_auto_or_float(opts.density) + selected_transformers = opts.selected_transformers.split(',') + + ########################################################################### + # Generate dataset + ########################################################################### + n_nonzeros = int(opts.ratio_nonzeros * opts.n_features) + + print('Dataset statics') + print("===========================") + print('n_samples \t= %s' % opts.n_samples) + print('n_features \t= %s' % opts.n_features) + if opts.n_components == "auto": + print('n_components \t= %s (auto)' % + johnson_lindenstrauss_min_dim(n_samples=opts.n_samples, + eps=opts.eps)) + else: + print('n_components \t= %s' % opts.n_components) + print('n_elements \t= %s' % (opts.n_features * opts.n_samples)) + print('n_nonzeros \t= %s per feature' % n_nonzeros) + print('ratio_nonzeros \t= %s' % opts.ratio_nonzeros) + print('') + + ########################################################################### + # Set transformer input + ########################################################################### + transformers = {} + + ########################################################################### + # Set GaussianRandomProjection input + gaussian_matrix_params = { + "n_components": opts.n_components, + "random_state": opts.random_seed + } + transformers["GaussianRandomProjection"] = \ + GaussianRandomProjection(**gaussian_matrix_params) + + ########################################################################### + # Set SparseRandomProjection input + sparse_matrix_params = { + "n_components": opts.n_components, + "random_state": opts.random_seed, + "density": opts.density, + "eps": opts.eps, + } + + transformers["SparseRandomProjection"] = \ + SparseRandomProjection(**sparse_matrix_params) + + ########################################################################### + # Perform benchmark + ########################################################################### + time_fit = collections.defaultdict(list) + time_transform = collections.defaultdict(list) + + print('Benchmarks') + print("===========================") + print("Generate dataset benchmarks... ", end="") + X_dense, X_sparse = make_sparse_random_data(opts.n_samples, + opts.n_features, + n_nonzeros, + random_state=opts.random_seed) + X = X_dense if opts.dense else X_sparse + print("done") + + for name in selected_transformers: + print("Perform benchmarks for %s..." % name) + + for iteration in xrange(opts.n_times): + print("\titer %s..." % iteration, end="") + time_to_fit, time_to_transform = bench_scikit_transformer(X_dense, + transformers[name]) + time_fit[name].append(time_to_fit) + time_transform[name].append(time_to_transform) + print("done") + + print("") + + ########################################################################### + # Print results + ########################################################################### + print("Script arguments") + print("===========================") + arguments = vars(opts) + print("%s \t | %s " % ("Arguments".ljust(16), + "Value".center(12),)) + print(25 * "-" + ("|" + "-" * 14) * 1) + for key, value in arguments.items(): + print("%s \t | %s " % (str(key).ljust(16), + str(value).strip().center(12))) + print("") + + print("Transformer performance:") + print("===========================") + print("Results are averaged over %s repetition(s)." % opts.n_times) + print("") + print("%s | %s | %s" % ("Transformer".ljust(30), + "fit".center(12), + "transform".center(12))) + print(31 * "-" + ("|" + "-" * 14) * 2) + + for name in sorted(selected_transformers): + print_row(name, + np.mean(time_fit[name]), + np.mean(time_transform[name])) + + print("") + print("") diff --git a/benchmarks/bench_sample_without_replacement.py b/benchmarks/bench_sample_without_replacement.py new file mode 100644 index 0000000000000..90c382e906bcc --- /dev/null +++ b/benchmarks/bench_sample_without_replacement.py @@ -0,0 +1,207 @@ +""" +Benchmarks for sampling without replacement of integer. + +""" +from __future__ import division +from __future__ import print_function + +import gc +import sys +import optparse +from datetime import datetime +import operator + +import matplotlib.pyplot as plt +import numpy as np +import random + +from sklearn.externals.six.moves import xrange +from sklearn.utils.random import sample_without_replacement + + +def compute_time(t_start, delta): + mu_second = 0.0 + 10 ** 6 # number of microseconds in a second + + return delta.seconds + delta.microseconds / mu_second + + +def bench_sample(sampling, n_population, n_samples): + gc.collect() + # start time + t_start = datetime.now() + sampling(n_population, n_samples) + delta = (datetime.now() - t_start) + # stop time + time = compute_time(t_start, delta) + return time + +if __name__ == "__main__": + ########################################################################### + # Option parser + ########################################################################### + op = optparse.OptionParser() + op.add_option("--n-times", + dest="n_times", default=5, type=int, + help="Benchmark results are average over n_times experiments") + + op.add_option("--n-population", + dest="n_population", default=100000, type=int, + help="Size of the population to sample from.") + + op.add_option("--n-step", + dest="n_steps", default=5, type=int, + help="Number of step interval between 0 and n_population.") + + default_algorithms = "custom-tracking-selection,custom-auto," \ + "custom-reservoir-sampling,custom-pool,"\ + "python-core-sample,numpy-permutation" + + op.add_option("--algorithm", + dest="selected_algorithm", + default=default_algorithms, + type=str, + help="Comma-separated list of transformer to benchmark. " + "Default: %default. \nAvailable: %default") + + # op.add_option("--random-seed", + # dest="random_seed", default=13, type=int, + # help="Seed used by the random number generators.") + + (opts, args) = op.parse_args() + if len(args) > 0: + op.error("this script takes no arguments.") + sys.exit(1) + + selected_algorithm = opts.selected_algorithm.split(',') + for key in selected_algorithm: + if key not in default_algorithms.split(','): + raise ValueError("Unknown sampling algorithm \"%s\" not in (%s)." + % (key, default_algorithms)) + + ########################################################################### + # List sampling algorithm + ########################################################################### + # We assume that sampling algorithm has the following signature: + # sample(n_population, n_sample) + # + sampling_algorithm = {} + + ########################################################################### + # Set Python core input + sampling_algorithm["python-core-sample"] = \ + lambda n_population, n_sample: \ + random.sample(xrange(n_population), n_sample) + + ########################################################################### + # Set custom automatic method selection + sampling_algorithm["custom-auto"] = \ + lambda n_population, n_samples, random_state=None: \ + sample_without_replacement(n_population, + n_samples, + method="auto", + random_state=random_state) + + ########################################################################### + # Set custom tracking based method + sampling_algorithm["custom-tracking-selection"] = \ + lambda n_population, n_samples, random_state=None: \ + sample_without_replacement(n_population, + n_samples, + method="tracking_selection", + random_state=random_state) + + ########################################################################### + # Set custom reservoir based method + sampling_algorithm["custom-reservoir-sampling"] = \ + lambda n_population, n_samples, random_state=None: \ + sample_without_replacement(n_population, + n_samples, + method="reservoir_sampling", + random_state=random_state) + + ########################################################################### + # Set custom reservoir based method + sampling_algorithm["custom-pool"] = \ + lambda n_population, n_samples, random_state=None: \ + sample_without_replacement(n_population, + n_samples, + method="pool", + random_state=random_state) + + ########################################################################### + # Numpy permutation based + sampling_algorithm["numpy-permutation"] = \ + lambda n_population, n_sample: \ + np.random.permutation(n_population)[:n_sample] + + ########################################################################### + # Remove unspecified algorithm + sampling_algorithm = dict((key, value) + for key, value in sampling_algorithm.items() + if key in selected_algorithm) + + ########################################################################### + # Perform benchmark + ########################################################################### + time = {} + n_samples = np.linspace(start=0, stop=opts.n_population, + num=opts.n_steps).astype(np.int) + + ratio = n_samples / opts.n_population + + print('Benchmarks') + print("===========================") + + for name in sorted(sampling_algorithm): + print("Perform benchmarks for %s..." % name, end="") + time[name] = np.zeros(shape=(opts.n_steps, opts.n_times)) + + for step in xrange(opts.n_steps): + for it in xrange(opts.n_times): + time[name][step, it] = bench_sample(sampling_algorithm[name], + opts.n_population, + n_samples[step]) + + print("done") + + print("Averaging results...", end="") + for name in sampling_algorithm: + time[name] = np.mean(time[name], axis=1) + print("done\n") + + # Print results + ########################################################################### + print("Script arguments") + print("===========================") + arguments = vars(opts) + print("%s \t | %s " % ("Arguments".ljust(16), + "Value".center(12),)) + print(25 * "-" + ("|" + "-" * 14) * 1) + for key, value in arguments.items(): + print("%s \t | %s " % (str(key).ljust(16), + str(value).strip().center(12))) + print("") + + print("Sampling algorithm performance:") + print("===============================") + print("Results are averaged over %s repetition(s)." % opts.n_times) + print("") + + fig = plt.figure('scikit-learn sample w/o replacement benchmark results') + plt.title("n_population = %s, n_times = %s" % + (opts.n_population, opts.n_times)) + ax = fig.add_subplot(111) + for name in sampling_algorithm: + ax.plot(ratio, time[name], label=name) + + ax.set_xlabel('ratio of n_sample / n_population') + ax.set_ylabel('Time (s)') + ax.legend() + + # Sort legend labels + handles, labels = ax.get_legend_handles_labels() + hl = sorted(zip(handles, labels), key=operator.itemgetter(1)) + handles2, labels2 = zip(*hl) + ax.legend(handles2, labels2, loc=0) + + plt.show() diff --git a/benchmarks/bench_sgd_regression.py b/benchmarks/bench_sgd_regression.py index e07bd0add590b..63e3e4c51846b 100644 --- a/benchmarks/bench_sgd_regression.py +++ b/benchmarks/bench_sgd_regression.py @@ -2,13 +2,13 @@ Benchmark for SGD regression Compares SGD regression against coordinate descent and Ridge -on synthetik data. +on synthetic data. """ -print __doc__ +print(__doc__) # Author: Peter Prettenhofer -# License: BSD Style. +# License: BSD 3 clause import numpy as np import pylab as pl @@ -30,6 +30,7 @@ sgd_results = np.zeros((len(list_n_samples), len(list_n_features), 2)) elnet_results = np.zeros((len(list_n_samples), len(list_n_features), 2)) ridge_results = np.zeros((len(list_n_samples), len(list_n_features), 2)) + asgd_results = np.zeros((len(list_n_samples), len(list_n_features), 2)) for i, n_train in enumerate(list_n_samples): for j, n_features in enumerate(list_n_features): X, y, coef = make_regression( @@ -41,10 +42,10 @@ X_test = X[n_train:] y_test = y[n_train:] - print "=======================" - print "Round %d %d" % (i, j) - print "n_features:", n_features - print "n_samples:", n_train + print("=======================") + print("Round %d %d" % (i, j)) + print("n_features:", n_features) + print("n_samples:", n_train) # Shuffle data idx = np.arange(n_train) @@ -64,8 +65,8 @@ y_test = (y_test - mean) / std gc.collect() - print "- benching ElasticNet" - clf = ElasticNet(alpha=alpha, rho=0.5, fit_intercept=False) + print("- benchmarking ElasticNet") + clf = ElasticNet(alpha=alpha, l1_ratio=0.5, fit_intercept=False) tstart = time() clf.fit(X_train, y_train) elnet_results[i, j, 0] = mean_squared_error(clf.predict(X_test), @@ -73,9 +74,9 @@ elnet_results[i, j, 1] = time() - tstart gc.collect() - print "- benching SGD" + print("- benchmarking SGD") n_iter = np.ceil(10 ** 4.0 / n_train) - clf = SGDRegressor(alpha=alpha, fit_intercept=False, + clf = SGDRegressor(alpha=alpha / n_train, fit_intercept=False, n_iter=n_iter, learning_rate="invscaling", eta0=.01, power_t=0.25) @@ -86,7 +87,22 @@ sgd_results[i, j, 1] = time() - tstart gc.collect() - print "- benching RidgeRegression" + print("n_iter", n_iter) + print("- benchmarking A-SGD") + n_iter = np.ceil(10 ** 4.0 / n_train) + clf = SGDRegressor(alpha=alpha / n_train, fit_intercept=False, + n_iter=n_iter, learning_rate="invscaling", + eta0=.002, power_t=0.05, + average=(n_iter * n_train // 2)) + + tstart = time() + clf.fit(X_train, y_train) + asgd_results[i, j, 0] = mean_squared_error(clf.predict(X_test), + y_test) + asgd_results[i, j, 1] = time() - tstart + + gc.collect() + print("- benchmarking RidgeRegression") clf = Ridge(alpha=alpha, fit_intercept=False) tstart = time() clf.fit(X_train, y_train) @@ -97,13 +113,16 @@ # Plot results i = 0 m = len(list_n_features) - pl.figure(figsize=(5 * 2, 4 * m)) + pl.figure('scikit-learn SGD regression benchmark results', + figsize=(5 * 2, 4 * m)) for j in range(m): pl.subplot(m, 2, i + 1) pl.plot(list_n_samples, np.sqrt(elnet_results[:, j, 0]), label="ElasticNet") pl.plot(list_n_samples, np.sqrt(sgd_results[:, j, 0]), label="SGDRegressor") + pl.plot(list_n_samples, np.sqrt(asgd_results[:, j, 0]), + label="A-SGDRegressor") pl.plot(list_n_samples, np.sqrt(ridge_results[:, j, 0]), label="Ridge") pl.legend(prop={"size": 10}) @@ -117,6 +136,8 @@ label="ElasticNet") pl.plot(list_n_samples, np.sqrt(sgd_results[:, j, 1]), label="SGDRegressor") + pl.plot(list_n_samples, np.sqrt(asgd_results[:, j, 1]), + label="A-SGDRegressor") pl.plot(list_n_samples, np.sqrt(ridge_results[:, j, 1]), label="Ridge") pl.legend(prop={"size": 10}) diff --git a/benchmarks/bench_sparsify.py b/benchmarks/bench_sparsify.py new file mode 100644 index 0000000000000..6affa4f3ebdc8 --- /dev/null +++ b/benchmarks/bench_sparsify.py @@ -0,0 +1,104 @@ +""" +Benchmark SGD prediction time with dense/sparse coefficients. + +Invoke with +----------- + +$ kernprof.py -l sparsity_benchmark.py +$ python -m line_profiler sparsity_benchmark.py.lprof + +Typical output +-------------- + +input data sparsity: 0.050000 +true coef sparsity: 0.000100 +test data sparsity: 0.027400 +model sparsity: 0.000024 +r^2 on test data (dense model) : 0.233651 +r^2 on test data (sparse model) : 0.233651 +Wrote profile results to sparsity_benchmark.py.lprof +Timer unit: 1e-06 s + +File: sparsity_benchmark.py +Function: benchmark_dense_predict at line 51 +Total time: 0.532979 s + +Line # Hits Time Per Hit % Time Line Contents +============================================================== + 51 @profile + 52 def benchmark_dense_predict(): + 53 301 640 2.1 0.1 for _ in range(300): + 54 300 532339 1774.5 99.9 clf.predict(X_test) + +File: sparsity_benchmark.py +Function: benchmark_sparse_predict at line 56 +Total time: 0.39274 s + +Line # Hits Time Per Hit % Time Line Contents +============================================================== + 56 @profile + 57 def benchmark_sparse_predict(): + 58 1 10854 10854.0 2.8 X_test_sparse = csr_matrix(X_test) + 59 301 477 1.6 0.1 for _ in range(300): + 60 300 381409 1271.4 97.1 clf.predict(X_test_sparse) +""" + +from scipy.sparse.csr import csr_matrix +import numpy as np +from sklearn.linear_model.stochastic_gradient import SGDRegressor +from sklearn.metrics import r2_score + +np.random.seed(42) + + +def sparsity_ratio(X): + return np.count_nonzero(X) / float(n_samples * n_features) + +n_samples, n_features = 5000, 300 +X = np.random.randn(n_samples, n_features) +inds = np.arange(n_samples) +np.random.shuffle(inds) +X[inds[int(n_features / 1.2):]] = 0 # sparsify input +print("input data sparsity: %f" % sparsity_ratio(X)) +coef = 3 * np.random.randn(n_features) +inds = np.arange(n_features) +np.random.shuffle(inds) +coef[inds[n_features/2:]] = 0 # sparsify coef +print("true coef sparsity: %f" % sparsity_ratio(coef)) +y = np.dot(X, coef) + +# add noise +y += 0.01 * np.random.normal((n_samples,)) + +# Split data in train set and test set +n_samples = X.shape[0] +X_train, y_train = X[:n_samples / 2], y[:n_samples / 2] +X_test, y_test = X[n_samples / 2:], y[n_samples / 2:] +print("test data sparsity: %f" % sparsity_ratio(X_test)) + +############################################################################### +clf = SGDRegressor(penalty='l1', alpha=.2, fit_intercept=True, n_iter=2000) +clf.fit(X_train, y_train) +print("model sparsity: %f" % sparsity_ratio(clf.coef_)) + + +def benchmark_dense_predict(): + for _ in range(300): + clf.predict(X_test) + + +def benchmark_sparse_predict(): + X_test_sparse = csr_matrix(X_test) + for _ in range(300): + clf.predict(X_test_sparse) + + +def score(y_test, y_pred, case): + r2 = r2_score(y_test, y_pred) + print("r^2 on test data (%s) : %f" % (case, r2)) + +score(y_test, clf.predict(X_test), 'dense model') +benchmark_dense_predict() +clf.sparsify() +score(y_test, clf.predict(X_test), 'sparse model') +benchmark_sparse_predict() diff --git a/benchmarks/bench_tree.py b/benchmarks/bench_tree.py index 77f76d8e7049a..ca97cf9be275b 100644 --- a/benchmarks/bench_tree.py +++ b/benchmarks/bench_tree.py @@ -26,7 +26,7 @@ def bench_scikit_tree_classifier(X, Y): - """Bench with scikit-learn decision tree classifier""" + """Benchmark with scikit-learn decision tree classifier""" from sklearn.tree import DecisionTreeClassifier @@ -44,7 +44,7 @@ def bench_scikit_tree_classifier(X, Y): def bench_scikit_tree_regressor(X, Y): - """Bench with scikit-learn decision tree regressor""" + """Benchmark with scikit-learn decision tree regressor""" from sklearn.tree import DecisionTreeRegressor @@ -63,9 +63,9 @@ def bench_scikit_tree_regressor(X, Y): if __name__ == '__main__': - print '============================================' - print 'Warning: this is going to take a looong time' - print '============================================' + print('============================================') + print('Warning: this is going to take a looong time') + print('============================================') n = 10 step = 10000 @@ -73,9 +73,9 @@ def bench_scikit_tree_regressor(X, Y): dim = 10 n_classes = 10 for i in range(n): - print '============================================' - print 'Entering iteration %s of %s' % (i, n) - print '============================================' + print('============================================') + print('Entering iteration %s of %s' % (i, n)) + print('============================================') n_samples += step X = np.random.randn(n_samples, dim) Y = np.random.randint(0, n_classes, (n_samples,)) @@ -84,14 +84,14 @@ def bench_scikit_tree_regressor(X, Y): bench_scikit_tree_regressor(X, Y) xx = range(0, n * step, step) - pl.figure(1) + pl.figure('scikit-learn tree benchmark results') pl.subplot(211) pl.title('Learning with varying number of samples') pl.plot(xx, scikit_classifier_results, 'g-', label='classification') pl.plot(xx, scikit_regressor_results, 'r-', label='regression') - pl.legend() + pl.legend(loc='upper left') pl.xlabel('number of samples') - pl.ylabel('time (in seconds)') + pl.ylabel('Time (s)') scikit_classifier_results = [] scikit_regressor_results = [] @@ -102,9 +102,9 @@ def bench_scikit_tree_regressor(X, Y): dim = start_dim for i in range(0, n): - print '============================================' - print 'Entering iteration %s of %s' % (i, n) - print '============================================' + print('============================================') + print('Entering iteration %s of %s' % (i, n)) + print('============================================') dim += step X = np.random.randn(100, dim) Y = np.random.randint(0, n_classes, (100,)) @@ -117,8 +117,8 @@ def bench_scikit_tree_regressor(X, Y): pl.title('Learning in high dimensional spaces') pl.plot(xx, scikit_classifier_results, 'g-', label='classification') pl.plot(xx, scikit_regressor_results, 'r-', label='regression') - pl.legend() + pl.legend(loc='upper left') pl.xlabel('number of dimensions') - pl.ylabel('time (in seconds)') + pl.ylabel('Time (s)') pl.axis('tight') pl.show() diff --git a/continuous_integration/appveyor/install.ps1 b/continuous_integration/appveyor/install.ps1 new file mode 100644 index 0000000000000..2a96d3372ecab --- /dev/null +++ b/continuous_integration/appveyor/install.ps1 @@ -0,0 +1,101 @@ +# Sample script to install Python and pip under Windows +# Authors: Olivier Grisel and Kyle Kastner +# License: BSD 3 clause + +$BASE_URL = "https://www.python.org/ftp/python/" +$GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py" +$GET_PIP_PATH = "C:\get-pip.py" + + +function DownloadPython ($python_version, $platform_suffix) { + $webclient = New-Object System.Net.WebClient + $filename = "python-" + $python_version + $platform_suffix + ".msi" + $url = $BASE_URL + $python_version + "/" + $filename + + $basedir = $pwd.Path + "\" + $filepath = $basedir + $filename + if (Test-Path $filename) { + Write-Host "Reusing" $filepath + return $filepath + } + + # Download and retry up to 3 times in case of network transient errors. + Write-Host "Downloading" $filename "from" $url + $retry_attempts = 2 + for($i=0; $i -lt $retry_attempts; $i++){ + try { + $webclient.DownloadFile($url, $filepath) + break + } + Catch [Exception]{ + Start-Sleep 1 + } + } + if (Test-Path $filepath) { + Write-Host "File saved at" $filepath + } else { + # Retry once to get the error message if any at the last try + $webclient.DownloadFile($url, $filepath) + } + return $filepath +} + + +function InstallPython ($python_version, $architecture, $python_home) { + Write-Host "Installing Python" $python_version "for" $architecture "bit architecture to" $python_home + if (Test-Path $python_home) { + Write-Host $python_home "already exists, skipping." + return $false + } + if ($architecture -eq "32") { + $platform_suffix = "" + } else { + $platform_suffix = ".amd64" + } + $msipath = DownloadPython $python_version $platform_suffix + Write-Host "Installing" $msipath "to" $python_home + $install_log = $python_home + ".log" + $install_args = "/qn /log $install_log /i $msipath TARGETDIR=$python_home" + $uninstall_args = "/qn /x $msipath" + RunCommand "msiexec.exe" $install_args + if (-not(Test-Path $python_home)) { + Write-Host "Python seems to be installed else-where, reinstalling." + RunCommand "msiexec.exe" $uninstall_args + RunCommand "msiexec.exe" $install_args + } + if (Test-Path $python_home) { + Write-Host "Python $python_version ($architecture) installation complete" + } else { + Write-Host "Failed to install Python in $python_home" + Get-Content -Path $install_log + Exit 1 + } +} + +function RunCommand ($command, $command_args) { + Write-Host $command $command_args + Start-Process -FilePath $command -ArgumentList $command_args -Wait -Passthru +} + + +function InstallPip ($python_home) { + $pip_path = $python_home + "\Scripts\pip.exe" + $python_path = $python_home + "\python.exe" + if (-not(Test-Path $pip_path)) { + Write-Host "Installing pip..." + $webclient = New-Object System.Net.WebClient + $webclient.DownloadFile($GET_PIP_URL, $GET_PIP_PATH) + Write-Host "Executing:" $python_path $GET_PIP_PATH + Start-Process -FilePath "$python_path" -ArgumentList "$GET_PIP_PATH" -Wait -Passthru + } else { + Write-Host "pip already installed." + } +} + + +function main () { + InstallPython $env:PYTHON_VERSION $env:PYTHON_ARCH $env:PYTHON + InstallPip $env:PYTHON +} + +main diff --git a/continuous_integration/appveyor/requirements.txt b/continuous_integration/appveyor/requirements.txt new file mode 100644 index 0000000000000..d86a2b15601d3 --- /dev/null +++ b/continuous_integration/appveyor/requirements.txt @@ -0,0 +1,15 @@ +# Fetch numpy and scipy wheels from the sklearn rackspace wheelhouse. +# Those wheels were generated by @ogrisel by calling `wheel convert` on +# the binaries from http://www.lfd.uci.edu/~gohlke/pythonlibs/ +# This is a temporary solution. As soon as numpy and scipy provide official +# wheel for windows we ca delete this --find-links line. +--find-links http://28daf2247a33ed269873-7b1aad3fab3cc330e1fd9d109892382a.r6.cf2.rackcdn.com/index.html + +# fix the versions of numpy to force the use of numpy and scipy to use the whl +# of the rackspace folder instead of trying to install from more recent +# source tarball published on PyPI +numpy==1.8.1 +scipy==0.14.0 +nose +wheel +wheelhouse_uploader diff --git a/continuous_integration/appveyor/run_with_env.cmd b/continuous_integration/appveyor/run_with_env.cmd new file mode 100644 index 0000000000000..0c70d633a91eb --- /dev/null +++ b/continuous_integration/appveyor/run_with_env.cmd @@ -0,0 +1,47 @@ +:: To build extensions for 64 bit Python 3, we need to configure environment +:: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of: +:: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1) +:: +:: To build extensions for 64 bit Python 2, we need to configure environment +:: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of: +:: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0) +:: +:: 32 bit builds do not require specific environment configurations. +:: +:: Note: this script needs to be run with the /E:ON and /V:ON flags for the +:: cmd interpreter, at least for (SDK v7.0) +:: +:: More details at: +:: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows +:: http://stackoverflow.com/a/13751649/163740 +:: +:: Author: Olivier Grisel +:: License: BSD 3 clause +@ECHO OFF + +SET COMMAND_TO_RUN=%* +SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows + +SET MAJOR_PYTHON_VERSION="%PYTHON_VERSION:~0,1%" +IF %MAJOR_PYTHON_VERSION% == "2" ( + SET WINDOWS_SDK_VERSION="v7.0" +) ELSE IF %MAJOR_PYTHON_VERSION% == "3" ( + SET WINDOWS_SDK_VERSION="v7.1" +) ELSE ( + ECHO Unsupported Python version: "%MAJOR_PYTHON_VERSION%" + EXIT 1 +) + +IF "%PYTHON_ARCH%"=="64" ( + ECHO Configuring Windows SDK %WINDOWS_SDK_VERSION% for Python %MAJOR_PYTHON_VERSION% on a 64 bit architecture + SET DISTUTILS_USE_SDK=1 + SET MSSdk=1 + "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION% + "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release + ECHO Executing: %COMMAND_TO_RUN% + call %COMMAND_TO_RUN% || EXIT 1 +) ELSE ( + ECHO Using default MSVC build environment for 32 bit architecture + ECHO Executing: %COMMAND_TO_RUN% + call %COMMAND_TO_RUN% || EXIT 1 +) diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh new file mode 100755 index 0000000000000..9a422df88cca6 --- /dev/null +++ b/continuous_integration/install.sh @@ -0,0 +1,70 @@ +#!/bin/bash +# This script is meant to be called by the "install" step defined in +# .travis.yml. See http://docs.travis-ci.com/ for more details. +# The behavior of the script is controlled by environment variabled defined +# in the .travis.yml in the top level folder of the project. + +# License: 3-clause BSD + +set -e + +# Fix the compilers to workaround avoid having the Python 3.4 build +# lookup for g++44 unexpectedly. +export CC=gcc +export CXX=g++ + +sudo apt-get update -qq +if [[ "$INSTALL_ATLAS" == "true" ]]; then + sudo apt-get install -qq libatlas3gf-base libatlas-dev +fi + +if [[ "$DISTRIB" == "conda" ]]; then + # Deactivate the travis-provided virtual environment and setup a + # conda-based environment instead + deactivate + + # Use the miniconda installer for faster download / install of conda + # itself + wget http://repo.continuum.io/miniconda/Miniconda-3.6.0-Linux-x86_64.sh \ + -O miniconda.sh + chmod +x miniconda.sh && ./miniconda.sh -b + export PATH=/home/travis/miniconda/bin:$PATH + conda update --yes conda + + # Configure the conda environment and put it in the path using the + # provided versions + conda create -n testenv --yes python=$PYTHON_VERSION pip nose \ + numpy=$NUMPY_VERSION scipy=$SCIPY_VERSION + source activate testenv + + if [[ "$INSTALL_MKL" == "true" ]]; then + # Make sure that MKL is used + conda install --yes mkl + else + # Make sure that MKL is not used + conda remove --yes --features mkl || echo "MKL not installed" + fi + +elif [[ "$DISTRIB" == "ubuntu" ]]; then + # Use standard ubuntu packages in their default version + sudo apt-get install -qq python-scipy + # At the time of writing numpy 1.9.1 is included in the travis + # virtualenv but we want to used numpy installed through apt-get + # install. + deactivate + # Create a new virtualenv using system site packages for numpy and scipy + virtualenv --system-site-packages testvenv + source testvenv/bin/activate + pip install nose +fi + +if [[ "$COVERAGE" == "true" ]]; then + pip install coverage coveralls +fi + +# Build scikit-learn in the install.sh script to collapse the verbose +# build output in the travis output when it succeeds. +python --version +python -c "import numpy; print('numpy %s' % numpy.__version__)" +python -c "import scipy; print('scipy %s' % scipy.__version__)" +python setup.py build_ext --inplace diff --git a/continuous_integration/test_script.sh b/continuous_integration/test_script.sh new file mode 100644 index 0000000000000..ddb1d82b363fe --- /dev/null +++ b/continuous_integration/test_script.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# This script is meant to be called by the "script" step defined in +# .travis.yml. See http://docs.travis-ci.com/ for more details. +# The behavior of the script is controlled by environment variabled defined +# in the .travis.yml in the top level folder of the project. + +# License: 3-clause BSD + +set -e + +python --version +python -c "import numpy; print('numpy %s' % numpy.__version__)" +python -c "import scipy; print('scipy %s' % scipy.__version__)" + +# Skip tests that require large downloads over the network to save bandwith +# usage as travis workers are stateless and therefore traditional local +# disk caching does not work. +export SKLEARN_SKIP_NETWORK_TESTS=1 + +# Do not use "make test" or "make test-coverage" as they enable verbose mode +# which renders travis output too slow to display in a browser. +if [[ "$COVERAGE" == "true" ]]; then + nosetests -s --with-coverage sklearn +else + nosetests -s sklearn +fi + +make test-doc test-sphinxext diff --git a/continuous_integration/windows/windows_testing_downloader.ps1 b/continuous_integration/windows/windows_testing_downloader.ps1 new file mode 100644 index 0000000000000..bb9cc5a44e85b --- /dev/null +++ b/continuous_integration/windows/windows_testing_downloader.ps1 @@ -0,0 +1,270 @@ +# Author: Kyle Kastner +# License: BSD 3 clause + +# This script is a helper to download the base python, numpy, and scipy +# packages from their respective websites. +# To quickly execute the script, run the following Powershell command: +# powershell.exe -ExecutionPolicy unrestricted "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/scikit-learn/scikit-learn/master/continuous_integration/windows/windows_testing_downloader.ps1'))" + +# This is a stopgap solution to make Windows testing easier +# until Windows CI issues are resolved. + +# Rackspace's default Windows VMs have several security features enabled by default. +# The DisableInternetExplorerESC function disables a feature which +# prevents any webpage from opening without explicit permission. +# This is a default setting of Windows VMs on Rackspace, and makes it annoying to +# download other packages to test! + +# Powershell scripts are also disabled by default. One must run the command: +# set-executionpolicy unrestricted +# from a Powershell terminal with administrator rights to enable scripts. +# To start an administrator Powershell terminal, right click second icon from the left on Windows Server 2012's bottom taskbar. + +param ( + [string]$python = "None", + [string]$nogit = "False" +) + +function DisableInternetExplorerESC { + # Disables InternetExplorerESC to enable easier manual downloads of testing packages. + # http://stackoverflow.com/questions/9368305/disable-ie-security-on-windows-server-via-powershell + $AdminKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}" + $UserKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}" + Set-ItemProperty -Path $AdminKey -Name "IsInstalled" -Value 0 + Set-ItemProperty -Path $UserKey -Name "IsInstalled" -Value 0 + Stop-Process -Name Explorer + Write-Host "IE Enhanced Security Configuration (ESC) has been disabled." -ForegroundColor Green +} + +function DownloadPackages ($package_dict, $append_string) { + $webclient = New-Object System.Net.WebClient + + ForEach ($key in $package_dict.Keys) { + $url = $package_dict[$key] + $file = $key + $append_string + if ($url -match "(\.*exe$)") { + $file = $file + ".exe" + } elseif ($url -match "(\.*msi$)") { + $file = $file + ".msi" + } else { + $file = $file + ".py" + } + $basedir = $pwd.Path + "\" + $filepath = $basedir + $file + Write-Host "Downloading" $file "from" $url + + # Retry up to 5 times in case of network transient errors. + $retry_attempts = 5 + for($i=0; $i -lt $retry_attempts; $i++){ + try{ + $webclient.DownloadFile($url, $filepath) + break + } + Catch [Exception]{ + Start-Sleep 1 + } + } + Write-Host "File saved at" $filepath + } +} + +function InstallPython($match_string) { + $pkg_regex = "python" + $match_string + "*" + $pkg = Get-ChildItem -Filter $pkg_regex -Name + Invoke-Expression -Command "msiexec /qn /i $pkg" + + Write-Host "Installing Python" + Start-Sleep 25 + Write-Host "Python installation complete" +} + +function InstallPip($match_string, $python_version) { + $pkg_regex = "get-pip" + $match_string + "*" + $py = $python_version -replace "\." + $pkg = Get-ChildItem -Filter $pkg_regex -Name + $python_path = "C:\Python" + $py + "\python.exe" + Invoke-Expression -Command "$python_path $pkg" +} + +function EnsurePip($python_version) { + $py = $python_version -replace "\." + $python_path = "C:\Python" + $py + "\python.exe" + Invoke-Expression -Command "$python_path -m ensurepip" +} + +function GetPythonHome($python_version) { + $py = $python_version -replace "\." + $pypath = "C:\Python" + $py + "\" + return $pypath +} + +function GetPipPath($python_version) { + $py = $python_version -replace "\." + $pypath = GetPythonHome $python_version + if ($py.StartsWith("3")) { + $pip = $pypath + "Scripts\pip3.exe" + } else { + $pip = $pypath + "Scripts\pip.exe" + } + return $pip +} + +function PipInstall($pkg_name, $python_version, $extra_args) { + $pip = GetPipPath $python_version + Invoke-Expression -Command "$pip install $pkg_name" +} + +function InstallNose($python_version) { + PipInstall "nose" $python_version +} + +function WheelInstall($name, $url, $python_version) { + $pip = GetPipPath $python_version + $args = "install --use-wheel --no-index" + Invoke-Expression -Command "$pip $args $url $name" +} + +function InstallWheel($python_version) { + PipInstall "virtualenv" $python_version + PipInstall "wheel" $python_version +} + +function InstallNumpy($package_dict, $python_version) { + #Don't pass name so we can use URL directly. + WheelInstall "" $package_dict["numpy"] $python_version +} + +function InstallScipy($package_dict, $python_version) { + #Don't pass name so we can use URL directly. + WheelInstall "" $package_dict["scipy"] $python_version +} + +function InstallGit { + $pkg_regex = "git*" + $pkg = Get-ChildItem -Filter $pkg_regex -Name + $pkg_cmd = $pwd.ToString() + "\" + $pkg + " /verysilent" + Invoke-Expression -Command $pkg_cmd + + Write-Host "Installing Git" + Start-Sleep 20 + # Remove the installer - seems to cause weird issues with Git Bash + Invoke-Expression -Command "rm git.exe" + Write-Host "Git installation complete" +} + +function ReadAndUpdateFromRegistry { + # http://stackoverflow.com/questions/14381650/how-to-update-windows-powershell-session-environment-variables-from-registry + foreach($level in "Machine","User") { + [Environment]::GetEnvironmentVariables($level).GetEnumerator() | % { + # For Path variables, append the new values, if they're not already in there + if($_.Name -match 'Path$') { + $_.Value = ($((Get-Content "Env:$($_.Name)") + ";$($_.Value)") -split ';' | Select -unique) -join ';' + } + $_ + } | Set-Content -Path { "Env:$($_.Name)" } + } +} + +function UpdatePaths($python_version) { + #This function makes local path updates required in order to install Python and supplementary packages in a single shell. + $pypath = GetPythonHome $python_version + $env:PATH = $env:PATH + ";" + $pypath + $env:PYTHONPATH = $pypath + "DLLs;" + $pypath + "Lib;" + $pypath + "Lib\site-packages" + $env:PYTHONHOME = $pypath + Write-Host "PYTHONHOME temporarily set to" $env:PYTHONHOME + Write-Host "PYTHONPATH temporarily set to" $env:PYTHONPATH + Write-Host "PATH temporarily set to" $env:PATH +} + +function Python27URLs { + # Function returns a dictionary of packages to download for Python 2.7. + $urls = @{ + "python" = "https://www.python.org/ftp/python/2.7.7/python-2.7.7.msi" + "numpy" = "http://28daf2247a33ed269873-7b1aad3fab3cc330e1fd9d109892382a.r6.cf2.rackcdn.com/numpy-1.8.1-cp27-none-win32.whl" + "scipy" = "http://28daf2247a33ed269873-7b1aad3fab3cc330e1fd9d109892382a.r6.cf2.rackcdn.com/scipy-0.14.0-cp27-none-win32.whl" + "get-pip" = "https://bootstrap.pypa.io/get-pip.py" + } + return $urls +} + +function Python34URLs { + # Function returns a dictionary of packages to download for Python 3.4. + $urls = @{ + "python" = "https://www.python.org/ftp/python/3.4.1/python-3.4.1.msi" + "numpy" = "http://28daf2247a33ed269873-7b1aad3fab3cc330e1fd9d109892382a.r6.cf2.rackcdn.com/numpy-1.8.1-cp34-none-win32.whl" + "scipy" = "http://28daf2247a33ed269873-7b1aad3fab3cc330e1fd9d109892382a.r6.cf2.rackcdn.com/scipy-0.14.0-cp34-none-win32.whl" + } + return $urls +} + +function GitURLs { + # Function returns a dictionary of packages to download for Git + $urls = @{ + "git" = "https://github.com/msysgit/msysgit/releases/download/Git-1.9.4-preview20140611/Git-1.9.4-preview20140611.exe" + } + return $urls +} + +function main { + $versions = @{ + "2.7" = Python27URLs + "3.4" = Python34URLs + } + + if ($nogit -eq "False") { + Write-Host "Downloading and installing Gitbash" + $urls = GitURLs + DownloadPackages $urls "" + InstallGit ".exe" + } + + if (($python -eq "None")) { + Write-Host "Installing all supported python versions" + Write-Host "Current versions supported are:" + ForEach ($key in $versions.Keys) { + Write-Host $key + $all_python += @($key) + } + } elseif(!($versions.ContainsKey($python))) { + Write-Host "Python version not recognized!" + Write-Host "Pass python version with -python" + Write-Host "Current versions supported are:" + ForEach ($key in $versions.Keys) { + Write-Host $key + } + return + } else { + $all_python += @($python) + } + ForEach ($py in $all_python) { + Write-Host "Installing Python" $py + DisableInternetExplorerESC + $pystring = $py -replace "\." + $pystring = "_py" + $pystring + $package_dict = $versions[$py] + + # This will download the whl packages as well which is + # clunky but makes configuration simpler. + DownloadPackages $package_dict $pystring + UpdatePaths $py + InstallPython $pystring + ReadAndUpdateFromRegistry + if ($package_dict.ContainsKey("get-pip")) { + InstallPip $pystring $py + } else { + EnsurePip $py + } + InstallNose $py + InstallWheel $py + + # The installers below here use wheel packages. + # Wheels were created from CGohlke's installers with + # wheel convert + # These are hosted in Rackspace Cloud Files. + InstallNumpy $package_dict $py + InstallScipy $package_dict $py + } + return +} + +main diff --git a/doc/Makefile b/doc/Makefile index 2ca8b8e3fcf23..c986436a99902 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -3,7 +3,7 @@ # You can set these variables from the command line. SPHINXOPTS = -SPHINXBUILD = sphinx-build +SPHINXBUILD ?= sphinx-build PAPER = BUILDDIR = _build @@ -12,7 +12,7 @@ PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex latexpdf changes linkcheck doctest +.PHONY: help clean html dirhtml pickle json latex latexpdf changes linkcheck doctest optipng all: html-noplot @@ -22,8 +22,6 @@ help: @echo " dirhtml to make HTML files named index.html in directories" @echo " pickle to make pickle files" @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " changes to make an overview of all changed/added/deprecated items" @@ -33,18 +31,22 @@ help: clean: -rm -rf $(BUILDDIR)/* -rm -rf auto_examples/ - -rm -rf doc/generated/* + -rm -rf generated/* -rm -rf modules/generated/* html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + # These two lines make the build a bit more lengthy, and the + # the embedding of images more robust + rm -rf $(BUILDDIR)/html/_images + #rm -rf _build/doctrees/ + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html/stable @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html/stable" html-noplot: - $(SPHINXBUILD) -D plot_gallery=False -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + $(SPHINXBUILD) -D plot_gallery=0 -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html/stable @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html/stable." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @@ -61,21 +63,6 @@ json: @echo @echo "Build finished; now you can process the JSON files." -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/scikit-learn.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/scikit-learn.qhc" - latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @@ -107,3 +94,9 @@ doctest: download-data: python -c "from sklearn.datasets.lfw import check_fetch_lfw; check_fetch_lfw()" + +# Optimize PNG files. Needs OptiPNG. Change the -P argument to the number of +# cores you have available, so -P 64 if you have a real computer ;) +optipng: + find _build auto_examples */generated -name '*.png' -print0 \ + | xargs -0 -n 1 -P 4 optipng -o10 diff --git a/doc/README b/doc/README index fe8462644222f..9d67d1e7e2010 100644 --- a/doc/README +++ b/doc/README @@ -21,13 +21,21 @@ To build the PDF manual, run Upload the generated doc to sourceforge --------------------------------------- -First of, generate the html documentation:: +First off, generate HTML documentation:: make html -This should create a directory _build/html with the documentation in html -format. +This should create a directory _build/html/stable with the documentation in +html format. +Next, make sure you have the PNG optimizer OptiPNG installed. +The PNG files generated by Matplotlib tend to be ~20% too big, and they're +costing us bandwidth. Then issue:: + + make optipng + +This may take some time. If you have a big machine at your disposal, +check the ``Makefile``; it has a hint on how to speed up this target. Now can upload the generated HTML documentation using scp or some other SFTP clients. @@ -42,7 +50,7 @@ An example session might look like the following for Username "jsmith" uploading a file for this project, using rsync with the right switch for the permissions: -[jsmith@linux ~]$ rsync -rltvz --delete _build/html/ \ +[jsmith@linux ~]$ rsync -rltvz --delete _build/html/stable/ \ > jsmith,scikit-learn@web.sourceforge.net:htdocs/dev -essh Connecting to web.sourceforge.net... The authenticity of host 'web.sourceforge.net (216.34.181.57)' can't be established. @@ -52,3 +60,15 @@ Warning: Permanently added 'web.sourceforge.net,216.34.181.57' (RSA) to the list jsmith,fooproject@web.sourceforge.net's password: sending incremental file list ... + + +Development documentation automated build +----------------------------------------- + +A Rackspace cloud server named 'docbuilder' is continuously building the master branch +to update the http://scikit-learn.org/dev tree of the website. + +The configuration of this server is managed at: + + http://github.com/scikit-learn/sklearn-docbuilder + diff --git a/doc/about.rst b/doc/about.rst index 22e8924047ad4..48259d6bd91c9 100644 --- a/doc/about.rst +++ b/doc/about.rst @@ -20,7 +20,7 @@ citations to the following paper: Bibtex entry:: @article{scikit-learn, - title={{Scikit-learn: Machine Learning in Python }}, + title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and @@ -31,19 +31,44 @@ citations to the following paper: year={2011} } +Artwork +------- + +High quality PNG and SVG logos are available in the `doc/logos/ `_ source directory. + +.. image:: images/scikit-learn-logo-notext.png + :align: center + Funding ------- `INRIA `_ actively supports this project. It has -provided funding for Fabian Pedregosa to work on this project full -time in the period 2010-2012. It also hosts coding sprints and other -events. +provided funding for Fabian Pedregosa (2010-2012), Jaques Grobler +(2012-2013) and Olivier Grisel (2013-2015) to work on this project +full-time. It also hosts coding sprints and other events. .. image:: images/inria-logo.jpg + :align: center + +`Paris-Saclay Center for Data Science `_ +funded one year for a developer to work on the project full-time +(2014-2015). + +.. image:: images/cds-logo.png + :align: center -`Google `_ sponsored David -Cournapeau with a Summer of Code Scholarship in the summer of 2007 and -`Vlad Niculae`_ in 2011. If +The following students were sponsored by `Google `_ +to work on scikit-learn through the +`Google Summer of Code `_ +program. + +- 2007 - David Cournapeau +- 2011 - `Vlad Niculae`_ +- 2012 - `Vlad Niculae`_, Immanuel Bayer. +- 2013 - `Kemal Eren`_, Nicolas Trésegnie +- 2014 - Hamzeh Alsalhi, Issam Laradji, Maheshakya Wijewardena, Manoj Kumar. + +It also provided funding for sprints and events around scikit-learn. If you would like to participate in the next Google Summer of code program, please see `this page `_ @@ -53,3 +78,114 @@ The `NeuroDebian `_ project providing `Debian `Dr. James V. Haxby `_ (`Dartmouth College `_). +The `PSF `_ helped find and manage funding for our +2011 Granada sprint. More information can be found `here +`_ + +`tinyclues `_ funded the 2011 international Granada +sprint. + + +Donating to the project +~~~~~~~~~~~~~~~~~~~~~~~ + +If you are interested in donating to the project or to one of our code-sprints, you can use +the *Paypal* button below or the `NumFOCUS Donations Page `_ (if you use the latter, please indicate that you are donating for the scikit-learn project). + +All donations will be handled by `NumFOCUS +`_, a non-profit-organization which is +managed by a board of `Scipy community members +`_. NumFOCUS's mission is to foster +scientific computing software, in particular in Python. As a fiscal home +of scikit-learn, it ensures that money is available when needed to keep +the project funded and available while in compliance with tax regulations. + +The received donations for the scikit-learn project mostly will go towards covering travel-expenses +for code sprints, as well as towards the organization budget of the project [#f1]_. + +.. raw :: html + +

+
+ + + + +
+
+ +.. rubric:: Notes + +.. [#f1] Regarding the organization budget in particular, we might use some of the donated funds to pay for other project expenses such as DNS, hosting or continuous integration services. + + +The 2013' Paris international sprint +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +|center-div| |telecom| |tinyclues| |afpy| |FNRS| + + |end-div| + + + +.. |center-div| raw:: html + +
+ + +.. |telecom| image:: http://f.hypotheses.org/wp-content/blogs.dir/331/files/2011/03/Logo-TPT.jpg + :width: 150px + :target: http://www.telecom-paristech.fr/ + + +.. |tinyclues| image:: http://www.tinyclues.com/static/img/logo.png + :width: 150px + :target: http://www.tinyclues.com/ + + +.. |afpy| image:: http://www.afpy.org/logo.png + :width: 150px + :target: http://www.afpy.org + + +.. |SGR| image:: http://www.svi.cnrs-bellevue.fr/wikimedia/images/Logo_svi_inp.png + :width: 150px + :target: http://www.svi.cnrs-bellevue.fr + +.. |FNRS| image:: http://www.fnrs.be/uploaddocs/images/COMMUNIQUER/FRS-FNRS_rose_transp.png + :width: 150px + :target: http://www.frs-fnrs.be/ + +.. figure:: http://sites.uclouvain.be/dysco/pmwiki/uploads/Main/dysco.gif + :width: 150px + :target: http://sites.uclouvain.be/dysco/ + + IAP VII/19 - DYSCO + +.. |end-div| raw:: html + +
+ +*For more information on this sprint, see* `here `_ + + +Infrastructure support +---------------------- + +- We would like to thank `Rackspace `_ for providing + us with a free `Rackspace Cloud `_ account to + automatically build the documentation and the example gallery from for the + development version of scikit-learn using `this tool + `_. + +- We would also like to thank `Shining Panda + `_ for free CPU time on their Continuous + Integration server. + diff --git a/doc/conf.py b/doc/conf.py index 3de9c8c36db8e..a02882ffdde2e 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -12,8 +12,10 @@ # All configuration values have a default; values that are commented out # serve to show the default. +from __future__ import print_function import sys import os +from sklearn.externals.six import u # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory @@ -21,6 +23,8 @@ # absolute, like shown here. sys.path.insert(0, os.path.abspath('sphinxext')) +from github_link import make_linkcode_resolve + # -- General configuration --------------------------------------------------- # Try to override the matplotlib configuration as early as possible @@ -33,16 +37,11 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['gen_rst', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', - 'sphinx.ext.pngmath', + 'sphinx.ext.pngmath', 'numpy_ext.numpydoc', + 'sphinx.ext.linkcode', ] -try: - import numpy_ext.numpydoc - extensions.append('numpy_ext.numpydoc') - # With older versions of sphinx, this causes a crash - autosummary_generate = True -except: - # Older version of sphinx - extensions.append('numpy_ext_old.numpydoc') + +autosummary_generate = True autodoc_default_flags = ['members', 'inherited-members'] @@ -65,17 +64,17 @@ master_doc = 'index' # General information about the project. -project = u'scikit-learn' -copyright = u'2010–2011, scikit-learn developers (BSD License)' +project = u('scikit-learn') +copyright = u('2010 - 2014, scikit-learn developers (BSD License)') # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '0.13-git' -# The full version, including alpha/beta/rc tags. import sklearn +version = sklearn.__version__ +# The full version, including alpha/beta/rc tags. release = sklearn.__version__ # The language for content autogenerated by Sphinx. Refer to documentation @@ -126,7 +125,9 @@ # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -html_theme_options = {'oldversion':False, 'collapsiblesidebar': True} +html_theme_options = {'oldversion': False, 'collapsiblesidebar': True, + 'google_analytics': True, 'surveybanner': False, + 'sprintbanner': True} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['themes'] @@ -203,11 +204,8 @@ # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). -latex_documents = [ - ('index', 'user_guide.tex', u'scikit-learn user guide', - u'scikit-learn developers', 'manual'), - -] +latex_documents = [('index', 'user_guide.tex', u('scikit-learn user guide'), + u('scikit-learn developers'), 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. @@ -218,7 +216,7 @@ #latex_use_parts = False # Additional stuff for the LaTeX preamble. -latex_preamble = """ +latex_preamble = r""" \usepackage{amsmath}\usepackage{amsfonts}\usepackage{bm}\usepackage{morefloats} \usepackage{enumitem} \setlistdepth{10} """ @@ -230,3 +228,26 @@ #latex_use_modindex = True trim_doctests_flags = True + + +def generate_example_rst(app, what, name, obj, options, lines): + # generate empty examples files, so that we don't get + # inclusion errors if there are no examples for a class / module + examples_path = os.path.join(app.srcdir, "modules", "generated", + "%s.examples" % name) + if not os.path.exists(examples_path): + # touch file + open(examples_path, 'w').close() + + +def setup(app): + # to hide/show the prompt in code examples: + app.add_javascript('js/copybutton.js') + app.connect('autodoc-process-docstring', generate_example_rst) + + +# The following is used by sphinx.ext.linkcode to provide links to github +linkcode_resolve = make_linkcode_resolve('sklearn', + u'https://github.com/scikit-learn/' + 'scikit-learn/blob/{revision}/' + '{package}/{path}#L{lineno}') diff --git a/doc/data_transforms.rst b/doc/data_transforms.rst index 3b4aaa4f691fb..d27f67cf73c5e 100644 --- a/doc/data_transforms.rst +++ b/doc/data_transforms.rst @@ -5,8 +5,31 @@ Dataset transformations ----------------------- +scikit-learn provides a library of transformers, which may clean (see +:ref:`preprocessing`), reduce (see :ref:`data_reduction`), expand (see +:ref:`kernel_approximation`) or generate (see :ref:`feature_extraction`) +feature representations. + +Like other estimators, these are represented by classes with ``fit`` method, +which learns model parameters (e.g. mean and standard deviation for +normalization) from a training set, and a ``transform`` method which applies +this transformation model to unseen data. ``fit_transform`` may be more +convenient and efficient for modelling and transforming the training data +simultaneously. + +Combining such transformers, either in parallel or series is covered in +:ref:`combining_estimators`. :ref:`metrics` covers transforming feature +spaces into affinity matrices, while :ref:`preprocessing_targets` considers +transformations of the target space (e.g. categorical labels) for use in +scikit-learn. + .. toctree:: - modules/preprocessing + modules/pipeline modules/feature_extraction + modules/preprocessing + modules/unsupervised_reduction + modules/random_projection modules/kernel_approximation + modules/metrics + modules/preprocessing_targets diff --git a/doc/datasets/covtype.rst b/doc/datasets/covtype.rst new file mode 100644 index 0000000000000..c0ed4ea08af3d --- /dev/null +++ b/doc/datasets/covtype.rst @@ -0,0 +1,20 @@ + +.. _covtype: + +Forest covertypes +================= + +The samples in this dataset correspond to 30×30m patches of forest in the US, +collected for the task of predicting each patch's cover type, +i.e. the dominant species of tree. +There are seven covertypes, making this a multiclass classification problem. +Each sample has 54 features, described on the +`dataset's homepage `_. +Some of the features are boolean indicators, +while others are discrete or continuous measurements. + +:func:`sklearn.datasets.fetch_covtype` will load the covertype dataset; +it returns a dictionary-like object +with the feature matrix in the ``data`` member +and the target values in ``target``. +The dataset will be downloaded from the web if necessary. diff --git a/doc/datasets/index.rst b/doc/datasets/index.rst index 9e0e2758d54fa..2e36c85b659da 100644 --- a/doc/datasets/index.rst +++ b/doc/datasets/index.rst @@ -32,11 +32,11 @@ numpy array X and an array of length n_samples containing the targets y. The toy datasets as well as the 'real world' datasets and the datasets fetched from mldata.org have more sophisticated structure. -These functions return a ``bunch`` (which is a dictionary that is -accessible with the 'dict.key' syntax). -All datasets have at least two keys, ``data``, containg an array of shape -``n_samples x n_features`` (except for 20newsgroups) and ``target``, a numpy -array of length ``n_features``, containing the targets. +These functions return a dictionary-like object holding at least two items: +an array of shape ``n_samples`` * `` n_features`` with key ``data`` +(except for 20newsgroups) +and a NumPy array of length ``n_samples``, containing the target values, +with key ``target``. The datasets also contain a description in ``DESCR`` and some contain ``feature_names`` and ``target_names``. @@ -81,7 +81,7 @@ and pipeline on 2D data. load_sample_images load_sample_image -.. image:: ../auto_examples/cluster/images/plot_color_quantization_1.png +.. image:: ../auto_examples/cluster/images/plot_color_quantization_001.png :target: ../auto_examples/cluster/plot_color_quantization.html :scale: 30 :align: right @@ -106,34 +106,116 @@ Sample generators ================= In addition, scikit-learn includes various random sample generators that -can be used to build artifical datasets of controled size and complexity. +can be used to build artificial datasets of controlled size and complexity. -.. image:: ../auto_examples/datasets/images/plot_random_dataset_1.png +Generators for classification and clustering +-------------------------------------------- + +These generators produce a matrix of features and corresponding discrete +targets. + +Single label +~~~~~~~~~~~~ + +Both :func:`make_blobs` and :func:`make_classification` create multiclass +datasets by allocating each class one or more normally-distributed clusters of +points. :func:`make_blobs` provides greater control regarding the centers and +standard deviations of each cluster, and is used to demonstrate clustering. +:func:`make_classification` specialises in introducing noise by way of: +correlated, redundant and uninformative features; multiple Gaussian clusters +per class; and linear transformations of the feature space. + +:func:`make_gaussian_quantiles` divides a single Gaussian cluster into +near-equal-size classes separated by concentric hyperspheres. +:func:`make_hastie_10_2` generates a similar binary, 10-dimensional problem. + +.. image:: ../auto_examples/datasets/images/plot_random_dataset_001.png :target: ../auto_examples/datasets/plot_random_dataset.html :scale: 50 :align: center +:func:`make_circles` and :func:`make_moons` generate 2d binary classification +datasets that are challenging to certain algorithms (e.g. centroid-based +clustering or linear classification), including optional Gaussian noise. +They are useful for visualisation. produces Gaussian +data with a spherical decision boundary for binary classification. + +Multilabel +~~~~~~~~~~ + +:func:`make_multilabel_classification` generates random samples with multiple +labels, reflecting a bag of words drawn from a mixture of topics. The number of +topics for each document is drawn from a Poisson distribution, and the topics +themselves are drawn from a fixed random distribution. Similarly, the number of +words is drawn from Poisson, with words drawn from a multinomial, where each +topic defines a probability distribution over words. Simplifications with +respect to true bag-of-words mixtures include: + +* Per-topic word distributions are independently drawn, where in reality all + would be affected by a sparse base distribution, and would be correlated. +* For a document generated from multiple topics, all topics are weighted + equally in generating its bag of words. +* Documents without labels words at random, rather than from a base + distribution. + +.. image:: ../auto_examples/datasets/images/plot_random_multilabel_dataset_001.png + :target: ../auto_examples/datasets/plot_random_multilabel_dataset.html + :scale: 50 + :align: center + +Biclustering +~~~~~~~~~~~~ + +.. autosummary:: + + :toctree: ../modules/generated/ + :template: function.rst + + make_biclusters + make_checkerboard + + +Generators for regression +------------------------- + +:func:`make_regression` produces regression targets as an optionally-sparse +random linear combination of random features, with noise. Its informative +features may be uncorrelated, or low rank (few features account for most of the +variance). + +Other regression generators generate functions deterministically from +randomized features. :func:`make_sparse_uncorrelated` produces a target as a +linear combination of four features with fixed coefficients. +Others encode explicitly non-linear relations: +:func:`make_friedman1` is related by polynomial and sine transforms; +:func:`make_friedman2` includes feature multiplication and reciprocation; and +:func:`make_friedman3` is similar with an arctan transformation on the target. + +Generators for manifold learning +-------------------------------- + +.. autosummary:: + + :toctree: ../modules/generated/ + :template: function.rst + + make_s_curve + make_swiss_roll + +Generators for decomposition +---------------------------- + .. autosummary:: :toctree: ../modules/generated/ :template: function.rst - make_classification - make_multilabel_classification - make_regression - make_blobs - make_friedman1 - make_friedman2 - make_friedman3 - make_hastie_10_2 make_low_rank_matrix make_sparse_coded_signal - make_sparse_uncorrelated make_spd_matrix - make_swiss_roll - make_s_curve make_sparse_spd_matrix + .. _libsvm_loader: Datasets in svmlight / libsvm format @@ -172,11 +254,12 @@ features:: _`Faster API-compatible implementation`: https://github.com/mblondel/svmlight-loader -.. include:: olivetti_faces.inc +.. include:: olivetti_faces.rst -.. include:: twenty_newsgroups.inc +.. include:: twenty_newsgroups.rst -.. include:: mldata.inc +.. include:: mldata.rst -.. include:: labeled_faces.inc +.. include:: labeled_faces.rst +.. include:: covtype.rst diff --git a/doc/datasets/labeled_faces.inc b/doc/datasets/labeled_faces.rst similarity index 97% rename from doc/datasets/labeled_faces.inc rename to doc/datasets/labeled_faces.rst index d38700597d88b..8786335e6fec0 100644 --- a/doc/datasets/labeled_faces.inc +++ b/doc/datasets/labeled_faces.rst @@ -43,7 +43,7 @@ classification task (hence supervised learning):: >>> lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4) >>> for name in lfw_people.target_names: - ... print name + ... print(name) ... Ariel Sharon Colin Powell @@ -97,7 +97,7 @@ possible to get an additional dimension with the RGB color channels by passing ``color=True``, in that case the shape will be ``(2200, 2, 62, 47, 3)``. -The ``fetch_lfw_pairs`` datasets is subdived in 3 subsets: the development +The ``fetch_lfw_pairs`` datasets is subdivided into 3 subsets: the development ``train`` set, the development ``test`` set and an evaluation ``10_folds`` set meant to compute performance metrics using a 10-folds cross validation scheme. @@ -115,5 +115,3 @@ Examples -------- :ref:`example_applications_face_recognition.py` - - diff --git a/doc/datasets/mldata.inc b/doc/datasets/mldata.rst similarity index 99% rename from doc/datasets/mldata.inc rename to doc/datasets/mldata.rst index 337e9b1fec2ef..5620a43df3ee5 100644 --- a/doc/datasets/mldata.inc +++ b/doc/datasets/mldata.rst @@ -68,5 +68,3 @@ datasets: ... data_home=custom_data_home) >>> iris3 = fetch_mldata('datasets-UCI iris', target_name='class', ... data_name='double0', data_home=custom_data_home) - - diff --git a/doc/datasets/mldata_fixture.py b/doc/datasets/mldata_fixture.py index e57a2506e8ee9..37d9f9af05dc3 100644 --- a/doc/datasets/mldata_fixture.py +++ b/doc/datasets/mldata_fixture.py @@ -1,6 +1,6 @@ """Fixture module to skip the datasets loading when offline -Mock urllib2 access to mldata.org +Mock urllib2 access to mldata.org and create a temporary data folder. """ from os import makedirs @@ -10,12 +10,22 @@ import shutil from sklearn import datasets -from sklearn.utils.testing import mock_urllib2 +from sklearn.utils.testing import install_mldata_mock +from sklearn.utils.testing import uninstall_mldata_mock def globs(globs): + # Create a temporary folder for the data fetcher + global custom_data_home + custom_data_home = tempfile.mkdtemp() + makedirs(join(custom_data_home, 'mldata')) + globs['custom_data_home'] = custom_data_home + return globs + + +def setup_module(): # setup mock urllib2 module to avoid downloading from mldata.org - mock_dataset = { + install_mldata_mock({ 'mnist-original': { 'data': np.empty((70000, 784)), 'label': np.repeat(np.arange(10, dtype='d'), 7000), @@ -27,20 +37,9 @@ def globs(globs): 'double0': np.empty((150, 4)), 'class': np.empty((150,)), }, - } - - global custom_data_home - custom_data_home = tempfile.mkdtemp() - makedirs(join(custom_data_home, 'mldata')) - globs['custom_data_home'] = custom_data_home - - global _urllib2_ref - _urllib2_ref = datasets.mldata.urllib2 - globs['_urllib2_ref'] = _urllib2_ref - datasets.mldata.urllib2 = mock_urllib2(mock_dataset) - return globs + }) -def teardown_module(module): - datasets.mldata.urllib2 = _urllib2_ref +def teardown_module(): + uninstall_mldata_mock() shutil.rmtree(custom_data_home) diff --git a/doc/datasets/olivetti_faces.inc b/doc/datasets/olivetti_faces.rst similarity index 89% rename from doc/datasets/olivetti_faces.inc rename to doc/datasets/olivetti_faces.rst index 189e6f363c265..4c774f75ed293 100644 --- a/doc/datasets/olivetti_faces.inc +++ b/doc/datasets/olivetti_faces.rst @@ -8,7 +8,10 @@ The Olivetti faces dataset This dataset contains a set of face images taken between April 1992 and April 1994 at AT&T Laboratories Cambridge. The website describing the original dataset is now defunct, but archived copies can be accessed through -`the Internet Archive's Wayback Machine`_. +`the Internet Archive's Wayback Machine`_. The +:func:`sklearn.datasets.fetch_olivetti_faces` function is the data +fetching / caching function that downloads the data +archive from AT&T. .. _the Internet Archive's Wayback Machine: http://wayback.archive.org/web/*/http://www.uk.research.att.com/facedatabase.html diff --git a/doc/datasets/twenty_newsgroups.inc b/doc/datasets/twenty_newsgroups.inc deleted file mode 100644 index 8d41f4a0aac8a..0000000000000 --- a/doc/datasets/twenty_newsgroups.inc +++ /dev/null @@ -1,116 +0,0 @@ -.. _20newsgroups: - -The 20 newsgroups text dataset -============================== - -The 20 newsgroups dataset comprises around 18000 newsgroups posts on -20 topics splitted in two subsets: one for training (or development) -and the other one for testing (or for performance evaluation). The split -between the train and test set is based upon a messages posted before -and after a specific date. - -This module contains two loaders. The first one, -``sklearn.datasets.fetch_20newsgroups``, -returns a list of the raw text files that can be fed to text feature -extractors such as :class:`sklearn.feature_extraction.text.Vectorizer` -with custom parameters so as to extract feature vectors. -The second one, ``sklearn.datasets.fetch_20newsgroups_vectorized``, -returns ready-to-use features, i.e., it is not necessary to use a feature -extractor. - -Usage ------ - -The ``sklearn.datasets.fetch_20newsgroups`` function is a data -fetching / caching functions that downloads the data archive from -the original `20 newsgroups website`_, extracts the archive contents -in the ``~/scikit_learn_data/20news_home`` folder and calls the -``sklearn.datasets.load_file`` on either the training or -testing set folder, or both of them:: - - >>> from sklearn.datasets import fetch_20newsgroups - >>> newsgroups_train = fetch_20newsgroups(subset='train') - - >>> from pprint import pprint - >>> pprint(list(newsgroups_train.target_names)) - ['alt.atheism', - 'comp.graphics', - 'comp.os.ms-windows.misc', - 'comp.sys.ibm.pc.hardware', - 'comp.sys.mac.hardware', - 'comp.windows.x', - 'misc.forsale', - 'rec.autos', - 'rec.motorcycles', - 'rec.sport.baseball', - 'rec.sport.hockey', - 'sci.crypt', - 'sci.electronics', - 'sci.med', - 'sci.space', - 'soc.religion.christian', - 'talk.politics.guns', - 'talk.politics.mideast', - 'talk.politics.misc', - 'talk.religion.misc'] - -The real data lies in the ``filenames`` and ``target`` attributes. The target -attribute is the integer index of the category:: - - >>> newsgroups_train.filenames.shape - (11314,) - >>> newsgroups_train.target.shape - (11314,) - >>> newsgroups_train.target[:10] - array([12, 6, 9, 8, 6, 7, 9, 2, 13, 19]) - -It is possible to load only a sub-selection of the categories by passing the -list of the categories to load to the ``fetch_20newsgroups`` function:: - - >>> cats = ['alt.atheism', 'sci.space'] - >>> newsgroups_train = fetch_20newsgroups(subset='train', categories=cats) - - >>> list(newsgroups_train.target_names) - ['alt.atheism', 'sci.space'] - >>> newsgroups_train.filenames.shape - (1073,) - >>> newsgroups_train.target.shape - (1073,) - >>> newsgroups_train.target[:10] - array([1, 1, 1, 0, 1, 0, 0, 1, 1, 1]) - -In order to feed predictive or clustering models with the text data, -one first need to turn the text into vectors of numerical values suitable -for statistical analysis. This can be achieved with the utilities of the -``sklearn.feature_extraction.text`` as demonstrated in the following -example that extract `TF-IDF`_ vectors of unigram tokens:: - - - >>> from sklearn.feature_extraction.text import Vectorizer - >>> documents = [open(f).read() for f in newsgroups_train.filenames] - >>> vectorizer = Vectorizer() - >>> vectors = vectorizer.fit_transform(documents) - >>> vectors.shape - (1073, 21108) - -The extracted TF-IDF vectors are very sparse with an average of 118 non zero -components by sample in a more than 20000 dimensional space (less than 1% non -zero features):: - - >>> vectors.nnz / vectors.shape[0] - 118 - -``sklearn.datasets.fetch_20newsgroups_vectorized`` is a function which returns -ready-to-use tfidf features instead of file names. - -.. _`20 newsgroups website`: http://people.csail.mit.edu/jrennie/20Newsgroups/ -.. _`TF-IDF`: http://en.wikipedia.org/wiki/Tf-idf - - -.. topic:: Examples - - * :ref:`example_grid_search_text_feature_extraction.py` - - * :ref:`example_document_classification_20newsgroups.py` - - diff --git a/doc/datasets/twenty_newsgroups.rst b/doc/datasets/twenty_newsgroups.rst new file mode 100644 index 0000000000000..003366efa4606 --- /dev/null +++ b/doc/datasets/twenty_newsgroups.rst @@ -0,0 +1,217 @@ +.. _20newsgroups: + +The 20 newsgroups text dataset +============================== + +The 20 newsgroups dataset comprises around 18000 newsgroups posts on +20 topics split in two subsets: one for training (or development) +and the other one for testing (or for performance evaluation). The split +between the train and test set is based upon a messages posted before +and after a specific date. + +This module contains two loaders. The first one, +``sklearn.datasets.fetch_20newsgroups``, +returns a list of the raw texts that can be fed to text feature +extractors such as :class:`sklearn.feature_extraction.text.Vectorizer` +with custom parameters so as to extract feature vectors. +The second one, ``sklearn.datasets.fetch_20newsgroups_vectorized``, +returns ready-to-use features, i.e., it is not necessary to use a feature +extractor. + +Usage +----- + +The ``sklearn.datasets.fetch_20newsgroups`` function is a data +fetching / caching functions that downloads the data archive from +the original `20 newsgroups website`_, extracts the archive contents +in the ``~/scikit_learn_data/20news_home`` folder and calls the +``sklearn.datasets.load_file`` on either the training or +testing set folder, or both of them:: + + >>> from sklearn.datasets import fetch_20newsgroups + >>> newsgroups_train = fetch_20newsgroups(subset='train') + + >>> from pprint import pprint + >>> pprint(list(newsgroups_train.target_names)) + ['alt.atheism', + 'comp.graphics', + 'comp.os.ms-windows.misc', + 'comp.sys.ibm.pc.hardware', + 'comp.sys.mac.hardware', + 'comp.windows.x', + 'misc.forsale', + 'rec.autos', + 'rec.motorcycles', + 'rec.sport.baseball', + 'rec.sport.hockey', + 'sci.crypt', + 'sci.electronics', + 'sci.med', + 'sci.space', + 'soc.religion.christian', + 'talk.politics.guns', + 'talk.politics.mideast', + 'talk.politics.misc', + 'talk.religion.misc'] + +The real data lies in the ``filenames`` and ``target`` attributes. The target +attribute is the integer index of the category:: + + >>> newsgroups_train.filenames.shape + (11314,) + >>> newsgroups_train.target.shape + (11314,) + >>> newsgroups_train.target[:10] + array([12, 6, 9, 8, 6, 7, 9, 2, 13, 19]) + +It is possible to load only a sub-selection of the categories by passing the +list of the categories to load to the ``fetch_20newsgroups`` function:: + + >>> cats = ['alt.atheism', 'sci.space'] + >>> newsgroups_train = fetch_20newsgroups(subset='train', categories=cats) + + >>> list(newsgroups_train.target_names) + ['alt.atheism', 'sci.space'] + >>> newsgroups_train.filenames.shape + (1073,) + >>> newsgroups_train.target.shape + (1073,) + >>> newsgroups_train.target[:10] + array([1, 1, 1, 0, 1, 0, 0, 1, 1, 1]) + +Converting text to vectors +-------------------------- + +In order to feed predictive or clustering models with the text data, +one first need to turn the text into vectors of numerical values suitable +for statistical analysis. This can be achieved with the utilities of the +``sklearn.feature_extraction.text`` as demonstrated in the following +example that extract `TF-IDF`_ vectors of unigram tokens +from a subset of 20news:: + + >>> from sklearn.feature_extraction.text import TfidfVectorizer + >>> categories = ['alt.atheism', 'talk.religion.misc', + ... 'comp.graphics', 'sci.space'] + >>> newsgroups_train = fetch_20newsgroups(subset='train', + ... categories=categories) + >>> vectorizer = TfidfVectorizer() + >>> vectors = vectorizer.fit_transform(newsgroups_train.data) + >>> vectors.shape + (2034, 34118) + +The extracted TF-IDF vectors are very sparse, with an average of 159 non-zero +components by sample in a more than 30000-dimensional space +(less than .5% non-zero features):: + + >>> vectors.nnz / float(vectors.shape[0]) + 159.01327433628319 + +``sklearn.datasets.fetch_20newsgroups_vectorized`` is a function which returns +ready-to-use tfidf features instead of file names. + +.. _`20 newsgroups website`: http://people.csail.mit.edu/jrennie/20Newsgroups/ +.. _`TF-IDF`: http://en.wikipedia.org/wiki/Tf-idf + + +Filtering text for more realistic training +------------------------------------------ +It is easy for a classifier to overfit on particular things that appear in the +20 Newsgroups data, such as newsgroup headers. Many classifiers achieve very +high F-scores, but their results would not generalize to other documents that +aren't from this window of time. + +For example, let's look at the results of a multinomial Naive Bayes classifier, +which is fast to train and achieves a decent F-score:: + + >>> from sklearn.naive_bayes import MultinomialNB + >>> from sklearn import metrics + >>> newsgroups_test = fetch_20newsgroups(subset='test', + ... categories=categories) + >>> vectors_test = vectorizer.transform(newsgroups_test.data) + >>> clf = MultinomialNB(alpha=.01) + >>> clf.fit(vectors, newsgroups_train.target) + >>> pred = clf.predict(vectors_test) + >>> metrics.f1_score(newsgroups_test.target, pred, average='weighted') + 0.88251152461278892 + +(The example :ref:`example_text_document_classification_20newsgroups.py` shuffles +the training and test data, instead of segmenting by time, and in that case +multinomial Naive Bayes gets a much higher F-score of 0.88. Are you suspicious +yet of what's going on inside this classifier?) + +Let's take a look at what the most informative features are: + + >>> import numpy as np + >>> def show_top10(classifier, vectorizer, categories): + ... feature_names = np.asarray(vectorizer.get_feature_names()) + ... for i, category in enumerate(categories): + ... top10 = np.argsort(classifier.coef_[i])[-10:] + ... print("%s: %s" % (category, " ".join(feature_names[top10]))) + ... + >>> show_top10(clf, vectorizer, newsgroups_train.target_names) + alt.atheism: sgi livesey atheists writes people caltech com god keith edu + comp.graphics: organization thanks files subject com image lines university edu graphics + sci.space: toronto moon gov com alaska access henry nasa edu space + talk.religion.misc: article writes kent people christian jesus sandvik edu com god + +You can now see many things that these features have overfit to: + +- Almost every group is distinguished by whether headers such as + ``NNTP-Posting-Host:`` and ``Distribution:`` appear more or less often. +- Another significant feature involves whether the sender is affiliated with + a university, as indicated either by their headers or their signature. +- The word "article" is a significant feature, based on how often people quote + previous posts like this: "In article [article ID], [name] <[e-mail address]> + wrote:" +- Other features match the names and e-mail addresses of particular people who + were posting at the time. + +With such an abundance of clues that distinguish newsgroups, the classifiers +barely have to identify topics from text at all, and they all perform at the +same high level. + +For this reason, the functions that load 20 Newsgroups data provide a +parameter called **remove**, telling it what kinds of information to strip out +of each file. **remove** should be a tuple containing any subset of +``('headers', 'footers', 'quotes')``, telling it to remove headers, signature +blocks, and quotation blocks respectively. + + >>> newsgroups_test = fetch_20newsgroups(subset='test', + ... remove=('headers', 'footers', 'quotes'), + ... categories=categories) + >>> vectors_test = vectorizer.transform(newsgroups_test.data) + >>> pred = clf.predict(vectors_test) + >>> metrics.f1_score(pred, newsgroups_test.target, average='weighted') + 0.78409163025839435 + +This classifier lost over a lot of its F-score, just because we removed +metadata that has little to do with topic classification. +It loses even more if we also strip this metadata from the training data: + + >>> newsgroups_train = fetch_20newsgroups(subset='train', + ... remove=('headers', 'footers', 'quotes'), + ... categories=categories) + >>> vectors = vectorizer.fit_transform(newsgroups_train.data) + >>> clf = BernoulliNB(alpha=.01) + >>> clf.fit(vectors, newsgroups_train.target) + >>> vectors_test = vectorizer.transform(newsgroups_test.data) + >>> pred = clf.predict(vectors_test) + >>> metrics.f1_score(newsgroups_test.target, pred, average='weighted') + 0.73160869205141166 + +Some other classifiers cope better with this harder version of the task. Try +running :ref:`example_model_selection_grid_search_text_feature_extraction.py` with and without +the ``--filter`` option to compare the results. + +.. topic:: Recommendation + + When evaluating text classifiers on the 20 Newsgroups data, you + should strip newsgroup-related metadata. In scikit-learn, you can do this by + setting ``remove=('headers', 'footers', 'quotes')``. The F-score will be + lower because it is more realistic. + +.. topic:: Examples + + * :ref:`example_model_selection_grid_search_text_feature_extraction.py` + + * :ref:`example_text_document_classification_20newsgroups.py` diff --git a/doc/developers/index.rst b/doc/developers/index.rst index 74edc4b69f6e8..316c18dffd3b7 100644 --- a/doc/developers/index.rst +++ b/doc/developers/index.rst @@ -42,6 +42,23 @@ extension in place:: python setup.py build_ext --inplace + +Another option is to use the ``develop`` option if you change your code a lot +and do not want to have to reinstall every time. This basically builds the +extension in place and creates a link to the development directory (see +):: + + python setup.py develop + +.. note:: + + if you decide to do that you have to rerun:: + + python setup.py build_ext --inplace + + every time the source code of a compiled extension is + changed (for instance when switching branches or pulling changes from upstream). + On Unix-like systems, you can simply type ``make`` in the top-level folder to build in-place and launch all the tests. Have a look at the ``Makefile`` for additional utilities. @@ -61,7 +78,8 @@ How to contribute ----------------- The preferred way to contribute to scikit-learn is to fork the `main -repository `__ on GitHub: +repository `__ on GitHub, +then submit a "pull request" (PR): 1. `Create an account `_ on GitHub if you do not already have one. @@ -99,8 +117,8 @@ email to the mailing list in order to get more visibility. .. note:: In the above setup, your ``origin`` remote repository points to - YourLogin/scikit-learn.git. If you wish to `fetch/merge` from the main - repository instead of your `forked` one, you will need to add another remote + YourLogin/scikit-learn.git. If you wish to fetch/merge from the main + repository instead of your forked one, you will need to add another remote to use instead of ``origin``. If we choose the name ``upstream`` for it, the command will be:: @@ -134,18 +152,13 @@ rules before submitting a pull request: * At least one paragraph of narrative documentation with links to references in the literature (with PDF links when possible) and - the example. - - The documentation should also include expected time and space - complexity of the algorithm and scalability, e.g. "this algorithm can - scale to a large number of samples > 100000, but does not scale in - dimensionality: n_features is expected to be lower than 100". - - To build the documentation, see the `documentation`_ section below. + the example. For more details on writing and building the + documentation, see the :ref:`contribute_documentation` section. You can also check for common programming errors with the following tools: - * Code with a good unittest coverage (at least 80%), check with:: + * Code with a good unittest coverage (at least 90%, better 100%), check + with:: $ pip install nose coverage $ nosetests --with-coverage path/to/tests_for_package @@ -181,6 +194,15 @@ and Cython optimizations. on all new contributions will get the overall code base quality in the right direction. +.. note:: + + For two very well documented and more detailed guides on development + workflow, please pay a visit to the `Scipy Development Workflow + `_ - + and the `Astropy Workflow for Developers + `_ + sections. + Easy Issues ----------- @@ -209,15 +231,53 @@ and are viewable in a web browser. See the README file in the doc/ directory for more information. For building the documentation, you will need `sphinx -`_ and `matplotlib -`_. +`_, +`matplotlib `_ and +`pillow `_. -When you are writing documentation, it is important to keep a good +**When you are writing documentation**, it is important to keep a good compromise between mathematical and algorithmic details, and give -intuition to the reader on what the algorithm does. It is best to always +intuition to the reader on what the algorithm does. + +Basically, to elaborate on the above, it is best to always start with a small paragraph with a hand-waiving explanation of what the -method does to the data and a figure (coming from an example) illustrating -it. +method does to the data. Then, it is very helpful +to point out why the feature is useful and when it should be used - +the latter also including "big O" +(:math:`O\left(g\left(n\right)\right)`) +complexities of the algorithm, as opposed to just *rules of thumb*, +as the latter can be very machine-dependent. +If those complexities are not available, then rules of thumb +may be provided instead. + +Secondly, a generated figure from an example (as mentioned in the previous +paragraph) should then be included to further provide some +intuition. + +Next, one or two small code examples to show its use can be added. + +Next, any math and equations, followed by references, +can be added to further the documentation. Not starting the +documentation with the maths makes it more friendly towards +users that are just interested in what the feature will do, as +opposed to how it works "under the hood". + +Finally, follow the formatting rules below to make it consistently good: + + * Add "See also" in docstrings for related classes/functions. + + * "See also" in docstrings should be one line per reference, + with a colon and an explanation, for example:: + + See also + -------- + SelectKBest: Select features based on the k highest scores. + SelectFpr: Select features based on a false positive rate test. + + * For unwritten formatting rules, try to follow existing good works: + + * For "References" in docstrings, see the Silhouette Coefficient + (:func:`sklearn.metrics.silhouette_score`). .. warning:: **Sphinx version** @@ -232,7 +292,7 @@ Testing and improving test coverage ------------------------------------ High-quality `unit testing `_ -is a corner-stone of the sciki-learn development process. For this +is a corner-stone of the scikit-learn development process. For this purpose, we use the `nose `_ package. The tests are functions appropriately names, located in `tests` subdirectories, that check the validity of the algorithms and the @@ -340,7 +400,13 @@ In addition, we add the following guidelines: * Use relative imports for references inside scikit-learn. - * **Please don't use `import *` in any case**. It is considered harmful + * Unit tests are an exception to the previous rule; + they should use absolute imports, exactly as client code would. + A corollary is that, if ``sklearn.foo`` exports a class or function + that is implemented in ``sklearn.foo.bar.baz``, + the test should import it from ``sklearn.foo``. + + * **Please don't use ``import *`` in any case**. It is considered harmful by the `official Python recommendations `_. It makes the code harder to read as the origin of symbols is no @@ -364,15 +430,14 @@ Input validation The module :mod:`sklearn.utils` contains various functions for doing input validation and conversion. Sometimes, ``np.asarray`` suffices for validation; -do `not` use ``np.asanyarray`` or ``np.atleast_2d``, since those let NumPy's +do *not* use ``np.asanyarray`` or ``np.atleast_2d``, since those let NumPy's ``np.matrix`` through, which has a different API (e.g., ``*`` means dot product on ``np.matrix``, but Hadamard product on ``np.ndarray``). -In other cases, be sure to call :func:`safe_asarray`, :func:`atleast2d_or_csr`, -:func:`as_float_array` or :func:`array2d` on any array-like argument passed to a -scikit-learn API function. The exact function to use depends mainly on whether -``scipy.sparse`` matrices must be accepted. +In other cases, be sure to call :func:`check_array` on any array-like argument +passed to a scikit-learn API function. The exact parameters to use depends +mainly on whether and which ``scipy.sparse`` matrices must be accepted. For more information, refer to the :ref:`developers-utils` page. @@ -412,6 +477,106 @@ Here's a simple example of code using some of the above guidelines:: i = random_state.randint(X.shape[0]) return X[i] +If you use randomness in an estimator instead of a freestanding function, +some additional guidelines apply. + +First off, the estimator should take a ``random_state`` argument to its +``__init__`` with a default value of ``None``. +It should store that argument's value, **unmodified**, +in an attribute ``random_state``. +``fit`` can call ``check_random_state`` on that attribute +to get an actual random number generator. +If, for some reason, randomness is needed after ``fit``, +the RNG should be stored in an attribute ``random_state_``. +The following example should make this clear:: + + class GaussianNoise(BaseEstimator, TransformerMixin): + """This estimator ignores its input and returns random Gaussian noise. + + It also does not adhere to all scikit-learn conventions, + but showcases how to handle randomness. + """ + + def __init__(self, n_components=100, random_state=None): + self.random_state = random_state + + # the arguments are ignored anyway, so we make them optional + def fit(self, X=None, y=None): + self.random_state_ = check_random_state(self.random_state) + + def transform(self, X): + n_samples = X.shape[0] + return self.random_state_.randn(n_samples, n_components) + +The reason for this setup is reproducibility: +when an estimator is ``fit`` twice to the same data, +it should produce an identical model both times, +hence the validation in ``fit``, not ``__init__``. + +Deprecation +----------- + +If any publicly accessible method, function, attribute or parameter +is renamed, we still support the old one for two releases and issue +a deprecation warning when it is called/passed/accessed. +E.g., if the function ``zero_one`` is renamed to ``zero_one_loss``, +we add the decorator ``deprecated`` (from ``sklearn.utils``) +to ``zero_one`` and call ``zero_one_loss`` from that function:: + + from ..utils import deprecated + + def zero_one_loss(y_true, y_pred, normalize=True): + # actual implementation + + @deprecated("Function 'zero_one' has been renamed to " + "'zero_one_loss' and will be removed in release 0.15." + "Default behavior is changed from 'normalize=False' to " + "'normalize=True'") + def zero_one(y_true, y_pred, normalize=False): + return zero_one_loss(y_true, y_pred, normalize) + +If an attribute is to be deprecated, +use the decorator ``deprecated`` on a property. +E.g., renaming an attribute ``labels_`` to ``classes_`` can be done as:: + + @property + @deprecated("Attribute labels_ is deprecated and " + "will be removed in 0.15. Use 'classes_' instead") + def labels_(self): + return self.classes_ + +If a parameter has to be deprecated, use ``DeprecationWarning`` appropriately. +In following example, k is deprecated and renamed to n_clusters:: + + import warnings + + def example_function(n_clusters=8, k=None): + if k is not None: + warnings.warn("'k' was renamed to n_clusters and will " + "be removed in 0.15.", + DeprecationWarning) + n_clusters = k + + +.. currentmodule:: sklearn + +Python 3.x support +------------------ + +All scikit-learn code should work unchanged in both Python 2.[67] +and 3.2 or newer. Since Python 3.x is not backwards compatible, +that may require changes to code and it certainly requires testing +on both 2.6 or 2.7, and 3.2 or newer. + +For most numerical algorithms, Python 3.x support is easy: +just remember that ``print`` is a function and +integer division is written ``//``. +String handling has been overhauled, though, as have parts of +the Python standard library. +The `six `_ package helps with +cross-compatibility and is included in scikit-learn as +``sklearn.externals.six``. + APIs of scikit-learn objects ============================ @@ -429,7 +594,11 @@ multiple interfaces): :Estimator: - The base object, implements:: + The base object, implements a ``fit`` method to learn from data, either:: + + estimator = obj.fit(data, targets) + + or:: estimator = obj.fit(data) @@ -439,6 +608,11 @@ multiple interfaces): prediction = obj.predict(data) + Classification algorithms usually also offer a way to quantify certainty + of a prediction, either using ``decision_function`` or ``predict_proba``:: + + probability = obj.predict_proba(data) + :Transformer: For filtering or modifying the data, in a supervised or unsupervised @@ -453,8 +627,8 @@ multiple interfaces): :Model: - A model that can give a goodness of fit or a likelihood of unseen - data, implements (higher is better):: + A model that can give a `goodness of fit `_ + measure or a likelihood of unseen data, implements (higher is better):: score = obj.score(data) @@ -470,10 +644,10 @@ classifier or a regressor. All estimators implement the fit method:: All built-in estimators also have a ``set_params`` method, which sets data-independent parameters (overriding previous parameter values passed -to ``__init__``). This method is not required for an object to be an -estimator. +to ``__init__``). -All estimators should inherit from ``sklearn.base.BaseEstimator``. +All estimators in the main scikit-learn codebase should inherit from +``sklearn.base.BaseEstimator``. Instantiation ^^^^^^^^^^^^^ @@ -491,21 +665,26 @@ The arguments accepted by ``__init__`` should all be keyword arguments with a default value. In other words, a user should be able to instantiate an estimator without passing any arguments to it. The arguments should all correspond to hyperparameters describing the model or the optimisation -problem the estimator tries to solve. +problem the estimator tries to solve. These initial arguments (or parameters) +are always remembered by the estimator. +Also note that they should not be documented under the "Attributes" section, +but rather under the "Parameters" section for that estimator. In addition, **every keyword argument accepted by ``__init__`` should correspond to an attribute on the instance**. Scikit-learn relies on this to find the relevant attributes to set on an estimator when doing model selection. -To summarize, a `__init__` should look like:: +To summarize, an ``__init__`` should look like:: def __init__(self, param1=1, param2=2): self.param1 = param1 self.param2 = param2 -There should be no logic, and the parameters should not be changed. -The corresponding logic should be put where the parameters are used. The -following is wrong:: +There should be no logic, not even input validation, +and the parameters should not be changed. +The corresponding logic should be put where the parameters are used, +typically in ``fit``. +The following is wrong:: def __init__(self, param1=1, param2=2, param3=3): # WRONG: parameters should not be modified @@ -516,8 +695,9 @@ following is wrong:: # the argument in the constructor self.param3 = param2 -Scikit-learn relies on this mechanism to introspect objects to set -their parameters by cross-validation. +The reason for postponing the validation is that the same validation +would have to be performed in ``set_params``, +which is used in algorithms like ``GridSearchCV``. Fitting ^^^^^^^ @@ -552,8 +732,11 @@ is not met, an exception of type ``ValueError`` should be raised. ``y`` might be ignored in the case of unsupervised learning. However, to make it possible to use the estimator as part of a pipeline that can mix both supervised and unsupervised transformers, even unsupervised -estimators are kindly asked to accept a ``y=None`` keyword argument in +estimators need to accept a ``y=None`` keyword argument in the second position that is just ignored by the estimator. +For the same reason, ``fit_predict``, ``fit_transform``, ``score`` +and ``partial_fit`` methods need to accept a ``y`` argument in +the second place if they are implemented. The method should return the object (``self``). This pattern is useful to be able to implement quick one liners in an IPython session such as:: @@ -570,7 +753,15 @@ data dependent. A tolerance stopping criterion ``tol`` is not directly data dependent (although the optimal value according to some scoring function probably is). -Any attribute that ends with ``_`` is expected to be overridden when +Estimated Attributes +^^^^^^^^^^^^^^^^^^^^ + +Attributes that have been estimated from the data must always have a name +ending with trailing underscore, for example the coefficients of +some regression estimator would be stored in a ``coef_`` attribute after +``fit`` has been called. + +The last-mentioned attributes are expected to be overridden when you call ``fit`` a second time without taking any previous value into account: **fit should be idempotent**. @@ -580,14 +771,115 @@ Optional Arguments In iterative algorithms, the number of iterations should be specified by an integer called ``n_iter``. -Unresolved API issues ----------------------- -Some things are must still be decided: - - * what should happen when predict is called before ``fit()`` ? - * which exception should be raised when the shape of arrays do not match - in ``fit()`` ? +Rolling your own estimator +========================== +If you want to implement a new estimator that is scikit-learn-compatible, +whether it is just for you or for contributing it to sklearn, there are several +internals of scikit-learn that you should be aware of in addition to the +sklearn API outlined above. + +The main motivation to make a class compatible to the scikit-learn estimator +interface might be that you want to use it together with model assessment and +selection tools such as :class:`grid_search.GridSearchCV`. + +For this to work, you need to implement the following interface. +If a dependency on scikit-learn is okay for your code, +you can prevent a lot of boilerplate code +by deriving a class from ``BaseEstimator`` +and optionally the mixin classes in ``sklearn.base``. +E.g., here's a custom classifier:: + + >>> import numpy as np + >>> from sklearn.base import BaseEstimator, ClassifierMixin + >>> class MajorityClassifier(BaseEstimator, ClassifierMixin): + ... """Predicts the majority class of its training data.""" + ... def __init__(self): + ... pass + ... def fit(self, X, y): + ... self.classes_, indices = np.unique(["foo", "bar", "foo"], + ... return_inverse=True) + ... self.majority_ = np.argmax(np.bincount(indices)) + ... return self + ... def predict(self, X): + ... return np.repeat(self.classes_[self.majority_], len(X)) + + +get_params and set_params +------------------------- +All sklearn estimator have ``get_params`` and ``set_params`` functions. +The ``get_params`` function takes no arguments and returns a dict of the +``__init__`` parameters of the estimator, together with their values. +It must take one keyword argument, ``deep``, +which receives a boolean value that determines +whether the method should return the parameters of sub-estimators +(for most estimators, this can be ignored). +The default value for ``deep`` should be true. + +The ``set_params`` on the other hand takes as input a dict of the form +``'parameter': value`` and sets the parameter of the estimator using this dict. + +While the ``get_params`` mechanism is not essential (see :ref:`cloning` below), +the ``set_params`` function is necessary as it is used to set parameters during +grid searches. + +The easiest way to implement these functions, and to get a sensible +``__repr__`` method, is to inherit from ``sklearn.base.BaseEstimator``. If you +do not want to make your code dependent on scikit-learn, the easiest way to +implement the interface is:: + + def get_params(self, deep=True): + # suppose this estimator has parameters "alpha" and "recursive" + return {"alpha": self.alpha, "recursive": self.recursive} + + def set_params(self, **parameters): + for parameter, value in parameters.items(): + self.setattr(parameter, value) + + +Parameters and init +------------------- +As :class:`grid_search.GridSearchCV` uses ``set_params`` +to apply parameter setting to estimators, +it is essential that calling ``set_params`` has the same effect +as setting parameters using the ``__init__`` method. +The easiest and recommended way to accomplish this is to +**not do any parameter validation in ``__init__``**. +All logic behind estimator parameters, +like translating string arguments into functions, should be done in ``fit``. + +Also it is expected that parameters with trailing ``_`` are **not to be set +inside the ``__init__`` method**. All and only the public attributes set by +fit have a trailing ``_``. As a result the existence of parameters with +trailing ``_`` is used to check if the estimator has been fitted. + +.. _cloning: + +Cloning +------- +For using :class:`grid_search.GridSearch` or any functionality of the +:mod:`cross_validation` module, an estimator must support the ``base.clone`` +function to replicate an estimator. +This can be done by providing a ``get_params`` method. +If ``get_params`` is present, then ``clone(estimator)`` will be an instance of +``type(estimator)`` on which ``set_params`` has been called with clones of +the result of ``estimator.get_params()``. + +Objects that do not provide this method will be deep-copied +(using the Python standard function ``copy.deepcopy``) +if ``safe=False`` is passed to ``clone``. + +Pipeline compatibility +---------------------- +For an estimator to be usable together with ``pipeline.Pipeline`` in any but the +last step, it needs to provide a ``fit`` or ``fit_transform`` function. +To be able to evaluate the pipeline on any data but the training set, +it also needs to provide a ``transform`` function. +There are no special requirements for the last step in a pipeline, except that +it has a ``fit`` function. All ``fit`` and ``fit_transform`` functions must +take arguments ``X, y``, even if y is not used. Similarly, for ``score`` to be +usable, the last step of the pipeline needs to have a ``score`` function that +accepts an optional ``y``. Working notes ------------- @@ -599,5 +891,36 @@ advised to maintain notes on the `GitHub wiki Specific models --------------- +Classifiers should accept ``y`` (target) arguments to ``fit`` +that are sequences (lists, arrays) of either strings or integers. +They should not assume that the class labels +are a contiguous range of integers; +instead, they should store a list of classes +in a ``classes_`` attribute or property. +The order of class labels in this attribute +should match the order in which ``predict_proba``, ``predict_log_proba`` +and ``decision_function`` return their values. +The easiest way to achieve this is to put:: + + self.classes_, y = np.unique(y, return_inverse=True) + +in ``fit``. +This returns a new ``y`` that contains class indexes, rather than labels, +in the range [0, ``n_classes``). + +A classifier's ``predict`` method should return +arrays containing class labels from ``classes_``. +In a classifier that implements ``decision_function``, +this can be achieved with:: + + def predict(self, X): + D = self.decision_function(X) + return self.classes_[np.argmax(D, axis=1)] + In linear models, coefficients are stored in an array called ``coef_``, and the independent term is stored in ``intercept_``. +``sklearn.linear_model.base`` contains a few base classes and mixins +that implement common linear model patterns. + +The :mod:`sklearn.utils.multiclass` module contains useful functions +for working with multiclass and multilabel problems. diff --git a/doc/developers/maintainer.rst b/doc/developers/maintainer.rst new file mode 100644 index 0000000000000..ff05626e1f1ae --- /dev/null +++ b/doc/developers/maintainer.rst @@ -0,0 +1,48 @@ +Maintainer / core-developer information +======================================== + +Making a release +------------------ + +1. Update docs: + + - edit the doc/whats_new.rst file to add release title and commit + statistics. You can retrieve commit statistics with:: + + $ git shortlog -ns 0.998.. + + - edit the doc/conf.py to increase the version number + + - edit the doc/themes/scikit-learn/layout.html to change the 'News' + entry of the front page. + +2. Update the version number in sklearn/__init__.py, the __version__ + variable + +3. Create the tag and push it:: + + $ git tag 0.999 + + $ git push origin --tags + +4. create tarballs: + + - Wipe clean your repo:: + + $ git clean -xfd + + - Register and upload on PyPI:: + + $ python setup.py sdist register upload + + - Upload manually the tarball on SourceForge: + https://sourceforge.net/projects/scikit-learn/files/ + +5. Push the documentation to the website (see README in doc folder) + + +6. Build binaries for windows and push them to PyPI:: + + $ python setup.py bdist_wininst upload + + And upload them also to sourceforge diff --git a/doc/developers/performance.rst b/doc/developers/performance.rst index 68919daeb20bc..75cfa914e616f 100644 --- a/doc/developers/performance.rst +++ b/doc/developers/performance.rst @@ -16,9 +16,9 @@ code for the scikit-learn project. implementation optimization. Times and times, hours of efforts invested in optimizing complicated - implementation details have been rended irrelevant by the late discovery - of simple **algorithmic tricks**, or by using another algorithm altogether - that is better suited to the problem. + implementation details have been rendered irrelevant by the subsequent + discovery of simple **algorithmic tricks**, or by using another algorithm + altogether that is better suited to the problem. The section :ref:`warm-restarts` gives an example of such a trick. @@ -31,7 +31,7 @@ Python, Cython or C/C++? In general, the scikit-learn project emphasizes the **readability** of the source code to make it easy for the project users to dive into the source code so as to understand how the algorithm behaves on their data -but also for ease of maintanability (by the developers). +but also for ease of maintainability (by the developers). When implementing a new algorithm is thus recommended to **start implementing it in Python using Numpy and Scipy** by taking care of avoiding @@ -39,7 +39,8 @@ looping code using the vectorized idioms of those libraries. In practice this means trying to **replace any nested for loops by calls to equivalent Numpy array methods**. The goal is to avoid the CPU wasting time in the Python interpreter rather than crunching numbers to fit your statistical -model. +model. It's generally a good idea to consider NumPy and SciPy performance tips: +http://wiki.scipy.org/PerformanceTips Sometimes however an algorithm cannot be expressed efficiently in simple vectorized Numpy code. In this case, the recommended strategy is the @@ -75,6 +76,37 @@ When using Cython, include the generated C source code alongside with the Cython source code. The goal is to make it possible to install the scikit on any machine with Python, Numpy, Scipy and C/C++ compiler. +Fast matrix multiplications +=========================== + +Matrix multiplications (matrix-matrix and matrix-vector) are usually handled +using the NumPy function ``np.dot``, but in versions of NumPy before 1.7.2 +this function is suboptimal when the inputs are not both in the C (row-major) +layout; in that case, the inputs may be implicitly copied to obtain the right +layout. This obviously consumes memory and takes time. + +The function ``fast_dot`` in ``sklearn.utils.extmath`` offers a fast +replacement for ``np.dot`` that prevents copies from being made in some cases. +In all other cases, it dispatches to ``np.dot`` and when the NumPy version is +new enough, it is in fact an alias for that function, making it a drop-in +replacement. Example usage of ``fast_dot``:: + + >>> import numpy as np + >>> from sklearn.utils.extmath import fast_dot + >>> X = np.random.random_sample([2, 10]) + >>> np.allclose(np.dot(X, X.T), fast_dot(X, X.T)) + True + +This function operates optimally on 2-dimensional arrays, both of the same +dtype, which should be either single or double precision float. If these +requirements aren't met or the BLAS package is not available, the call is +silently dispatched to ``numpy.dot``. If you want to be sure when the original +``numpy.dot`` has been invoked in a situation where it is suboptimal, you can +activate the related warning:: + + >>> import warnings + >>> from sklearn.utils.validation import NonBLASDotWarning + >>> warnings.simplefilter('always', NonBLASDotWarning) # doctest: +SKIP .. _profiling-python-code: @@ -87,7 +119,7 @@ for interactively exploring the relevant part for the code. Suppose we want to profile the Non Negative Matrix Factorization module of the scikit. Let us setup a new IPython session and load the digits -dataset and as in the :ref:`example_plot_digits_classification.py` example:: +dataset and as in the :ref:`example_classification_plot_digits_classification.py` example:: In [1]: from sklearn.decomposition import NMF @@ -123,7 +155,7 @@ magic command:: 1 0.000 0.000 0.000 0.000 nmf.py:337(__init__) 1 0.000 0.000 1.681 1.681 nmf.py:461(fit) -The ``totime`` columns is the most interesting: it gives to total time spent +The ``tottime`` column is the most interesting: it gives to total time spent executing the code of a given function ignoring the time spent in executing the sub-functions. The real total time (local code + sub-function calls) is given by the ``cumtime`` column. @@ -132,7 +164,7 @@ Note the use of the ``-l nmf.py`` that restricts the output to lines that contains the "nmf.py" string. This is useful to have a quick look at the hotspot of the nmf Python module it-self ignoring anything else. -Here is the begining of the output of the same command without the ``-l nmf.py`` +Here is the beginning of the output of the same command without the ``-l nmf.py`` filter:: In [5] %prun NMF(n_components=16, tol=1e-2).fit(X) @@ -328,8 +360,8 @@ directory:: 7 13.61 MB -152.59 MB del b 8 13.61 MB 0.00 MB return a -Another useful magic that ``memory_profiler`` defines is `%memit`, which is -analogous to `%timeit`. It can be used as follows:: +Another useful magic that ``memory_profiler`` defines is ``%memit``, which is +analogous to ``%timeit``. It can be used as follows:: In [1]: import numpy as np @@ -346,7 +378,7 @@ Performance tips for the Cython developer If profiling of the Python code reveals that the Python interpreter overhead is larger by one order of magnitude or more than the cost of the actual numerical computation (e.g. ``for`` loops over vector components, -nested evaluation of conditional expression, scalar arithmetics...), it +nested evaluation of conditional expression, scalar arithmetic...), it is probably adequate to extract the hotspot portion of the code as a standalone function in a ``.pyx`` file, add static type declarations and then use Cython to generate a C program suitable to be compiled as a @@ -359,7 +391,7 @@ important in practice on the existing cython codebase in the scikit-learn project. TODO: html report, type declarations, bound checks, division by zero checks, -memory alignement, direct blas calls... +memory alignment, direct blas calls... - http://www.euroscipy.org/file/3696?vid=download - http://conference.scipy.org/proceedings/SciPy2009/paper_1/ @@ -373,7 +405,7 @@ Profiling compiled extensions When working with compiled extensions (written in C/C++ with a wrapper or directly as Cython extension), the default Python profiler is useless: -we need a dedicated tool to instrospect what's happening inside the +we need a dedicated tool to introspect what's happening inside the compiled extension it-self. Using yep and google-perftools diff --git a/doc/developers/utilities.rst b/doc/developers/utilities.rst index 7313ca976eec1..c5740632337fa 100644 --- a/doc/developers/utilities.rst +++ b/doc/developers/utilities.rst @@ -27,20 +27,21 @@ should be used when applicable. - :func:`assert_all_finite`: Throw an error if array contains NaNs or Infs. -- :func:`safe_asarray`: Convert input to array or sparse matrix. Equivalent - to ``np.asarray``, but sparse matrices are passed through. - - :func:`as_float_array`: convert input to an array of floats. If a sparse matrix is passed, a sparse matrix will be returned. -- :func:`array2d`: equivalent to ``np.atleast_2d``, but the ``order`` and - ``dtype`` of the input are maintained. +- :func:`check_array`: convert input to 2d array, raise error on sparse + matrices. Allowed sparse matrix formats can be given optionally, as well as + allowing 1d or nd arrays. Calls :func:`assert_all_finite` by default. -- :func:`atleast2d_or_csr`: equivalent to ``array2d``, but if a sparse matrix - is passed, will convert to csr format. Also calls ``assert_all_finite``. +- :func:`check_X_y`: check that X and y have consistent length, calls + check_array on X, and column_or_1d on y. For multilabel classification or + multitarget regression, specify multi_output=True, in which case check_array + will be called on y. -- :func:`check_arrays`: check that all input arrays have consistent first - dimensions. This will work for an arbitrary number of arrays. +- :func:`indexable`: check that all input arrays have consistent length and can + be sliced or indexed using safe_index. This is used to validate input for + cross-validation. - :func:`warn_if_not_float`: Warn if input is not a floating-point value. the input ``X`` is assumed to have ``X.dtype``. @@ -125,14 +126,22 @@ Efficient Linear Algebra & Array Operations Used in ``sklearn.cluster.k_means``. +Efficient Random Sampling +========================= + +- :func:`random.sample_without_replacement`: implements efficient algorithms + for sampling ``n_samples`` integers from a population of size ``n_population`` + without replacement. + + Efficient Routines for Sparse Matrices ====================================== The ``sklearn.utils.sparsefuncs`` cython module hosts compiled extensions to efficiently process ``scipy.sparse`` data. -- :func:`sparsefuncs.mean_variance_axis0`: compute the means and - variances along axis 0 of a CSR matrix. +- :func:`sparsefuncs.mean_variance_axis`: compute the means and + variances along a specified axis of a CSR matrix. Used for normalizing the tolerance stopping criterion in :class:`sklearn.cluster.k_means_.KMeans`. @@ -173,39 +182,19 @@ Graph Routines Backports ========= -- :class:`fixes.Counter` (partial backport of ``collections.Counter`` from - Python 2.7) Used in ``sklearn.feature_extraction.text``. - -- :func:`fixes.unique`: (backport of ``np.unique`` from numpy 1.4). Find the - unique entries in an array. In numpy versions < 1.4, ``np.unique`` is less - flexible. Used in :mod:`sklearn.cross_validation`. - -- :func:`fixes.copysign`: (backport of ``np.copysign`` from numpy 1.4). - Change the sign of ``x1`` to that of ``x2``, element-wise. - -- :func:`fixes.in1d`: (backport of ``np.in1d`` from numpy 1.4). - Test whether each element of an array is in a second array. Used in - ``sklearn.datasets.twenty_newsgroups`` and - ``sklearn.feature_extraction.image``. - -- :func:`fixes.savemat` (backport of ``scipy.io.savemat`` from scipy 0.7.2). - Save an array in MATLAB-format. In earlier versions, the keyword - ``oned_as`` is not available. - -- :func:`fixes.count_nonzero` (backport of ``np.count_nonzero`` from - numpy 1.6). Count the nonzero elements of a matrix. Used in - tests of :mod:`sklearn.linear_model`. +- :func:`fixes.expit`: Logistic sigmoid function. Replacement for SciPy 0.10's + ``scipy.special.expit``. -- :func:`arrayfuncs.solve_triangular` - (Back-ported from scipy v0.9) Used in ``sklearn.linear_model.omp``, - independent back-ports in ``sklearn.mixture.gmm`` and - :mod:`sklearn.gaussian_process`. - -- :func:`sparsetools.cs_graph_components` - (backported from ``scipy.sparse.cs_graph_components`` in scipy 0.9). +- :func:`sparsetools.connected_components` + (backported from ``scipy.sparse.connected_components`` in scipy 0.12). Used in ``sklearn.cluster.hierarchical``, as well as in tests for :mod:`sklearn.feature_extraction`. +- :func:`fixes.isclose` + (backported from ``numpy.isclose`` in numpy 1.8.1). + In versions before 1.7, this function was not available in + numpy. Used in ``sklearn.metrics``. + ARPACK ------ @@ -242,8 +231,26 @@ Testing Functions - :func:`testing.assert_in`, :func:`testing.assert_not_in`: Assertions for container membership. Designed for forward compatibility with Nose 1.0. -- :class:`mock_urllib2`: Object which mocks the urllib2 module to fake - requests of mldata. Used in tests of :mod:`sklearn.datasets`. +- :func:`testing.assert_raise_message`: Assertions for checking the + error raise message. + +- :func:`testing.mock_mldata_urlopen`: Mocks the urlopen function to fake + requests to mldata.org. Used in tests of :mod:`sklearn.datasets`. + +- :func:`testing.all_estimators` : returns a list of all estimators in + sklearn to test for consistent behavior and interfaces. + +Multiclass and multilabel utility function +========================================== + +- :func:`multiclass.is_multilabel`: Helper function to check if the task + is a multi-label classification one. + +- :func:`multiclass.is_label_indicator_matrix`: Helper function to check if + a classification output is in label indicator matrix format. + +- :func:`multiclass.unique_labels`: Helper function to extract an ordered + array of unique labels from different formats of target. Helper Functions @@ -253,10 +260,6 @@ Helper Functions to ``n``. Used in ``sklearn.decomposition.dict_learning`` and ``sklearn.cluster.k_means``. -- :class:`arraybuilder.ArrayBuilder`: Helper class to incrementally build - a 1-d numpy.ndarray. Currently used in - ``sklearn.datasets._svmlight_format.pyx``. - - :func:`safe_mask`: Helper function to convert a mask to the format expected by the numpy array or scipy sparse matrix on which to use it (sparse matrices support integer indices only while numpy arrays support both @@ -270,17 +273,17 @@ Hash Functions ============== - :func:`murmurhash3_32` provides a python wrapper for the - `MurmurHash3_x86_32` C++ non cryptographic hash function. This hash + ``MurmurHash3_x86_32`` C++ non cryptographic hash function. This hash function is suitable for implementing lookup tables, Bloom filters, Count Min Sketch, feature hashing and implicitly defined sparse random projections:: >>> from sklearn.utils import murmurhash3_32 - >>> murmurhash3_32("some feature", seed=0) - -384616559 + >>> murmurhash3_32("some feature", seed=0) == -384616559 + True - >>> murmurhash3_32("some feature", seed=0, positive=True) - 3910350737L + >>> murmurhash3_32("some feature", seed=0, positive=True) == 3910350737 + True The ``sklearn.utils.murmurhash`` module can also be "cimported" from other cython modules so as to benefit from the high performance of diff --git a/doc/documentation.rst b/doc/documentation.rst new file mode 100644 index 0000000000000..b0bd741fcab71 --- /dev/null +++ b/doc/documentation.rst @@ -0,0 +1,112 @@ +.. raw:: html + +
+ +Documentation of scikit-learn 0.17.dev0 +======================================= + +.. raw:: html + + + +
+
+

Quick Start

+
A very short introduction into machine learning + problems and how to solve them using scikit-learn. + Introduced basic concepts and conventions. +
+
+
+

User Guide

+
The main documentation. This contains an + in-depth description of all algorithms and how + to apply them. +
+
+ + +
+ + +
+
+

Tutorials

+
Useful tutorials for developing a feel + for some of scikit-learn's applications in the + machine learning field. +
+
+
+

API

+
The exact API of all functions and classes, as given by the docstrings. + The API documents expected types and allowed features for all functions, + and all parameters available for the algorithms. +
+
+ +
+

Additional Resources

+
Talks given, slide-sets and other information relevant to scikit-learn. +
+
+
+ +
+
+

Contributing

+
Information on how to contribute. This also + contains useful information for advanced users, for example + how to build their own estimators. +
+
+ +
+

Flow Chart

+
A graphical overview of basic areas of machine + learning, and guidance which kind of algorithms + to use in a given situation. +
+
+
+

FAQ

+
Frequently asked questions about the project and contributing. +
+
+
+ +
+
+

Related packages

+
Other machine learning packages for Python and + related projects. Also algorithms that are slightly out of + scope or not well established enough for scikit-learn. +
+
+ +
diff --git a/doc/faq.rst b/doc/faq.rst new file mode 100644 index 0000000000000..6a189fab76342 --- /dev/null +++ b/doc/faq.rst @@ -0,0 +1,151 @@ +.. _faq: + +=========================== +Frequently Asked Questions +=========================== + +Here we try to give some answers to questions that regularly pop up on the mailing list. + +What is the project name (a lot of people get it wrong)? +-------------------------------------------------------- +scikit-learn, but not scikit or SciKit nor sci-kit learn. Also not scikits.learn or scikits-learn, which where previously used. + +How do you pronounce the project name? +------------------------------------------ +sy-kit learn. sci stands for science! + +Why scikit? +------------ +There are multiple scikits, which are scientific toolboxes build around SciPy. +You can find a list at ``_. +Apart from scikit-learn, another popular one is `scikit-image `_. + +How can I contribute to scikit-learn? +----------------------------------------- +See :ref:`contributing`. + +Can I add this new algorithm that I (or someone else) just published? +------------------------------------------------------------------------- +No. As a rule we only add well-established algorithms. A rule of thumb is at least +3 years since publications, 200+ citations and wide use and usefullness. A +technique that provides a clear-cut improvement (e.g. an enhanced data +structure or efficient approximation) on a widely-used method will also be +considered for inclusion. +Your implementation doesn't need to be in scikit-learn to be used together +with scikit-learn tools, though. Implement your favorite algorithm +in a scikit-learn compatible way, upload it to github and we will list +it under :ref:`related_projects`. +Also see selectiveness_. + + +Can I add this classical algorithm from the 80s? +--------------------------------------------------- +Depends. If there is a common usecase within the scope of scikit-learn, such +as classification, regression or clustering, where it outperforms methods +that are already implemented in scikit-learn, we will consider it. + +.. _selectiveness: + +Why are you so selective on what algorithms you include in scikit-learn? +------------------------------------------------------------------------ +Code is maintenance cost, and we need to balance the amount of +code we have with the size of the team (and add to this the fact that +complexity scales non linearly with the number of features). +The package relies on core developers using their free time to +fix bugs, maintain code and review contributions. +Any algorithm that is added needs future attention by the developers, +at which point the original author might long have lost interest. +Also see `this thread on the mailing list +`_. + +Why did you remove HMMs from scikit-learn? +-------------------------------------------- +See :ref:`adding_graphical_models`. + +.. _adding_graphical_models: + +Will you add graphical models or sequence prediction to scikit-learn? +------------------------------------------------------------------------ +Not in the foreseeable future. +scikit-learn tries to provide a unified API for the basic tasks in machine +learning, with pipelines and meta-algorithms like grid search to tie +everything together. The required concepts, APIs, algorithms and +expertise required for structured learning are different from what +scikit-learn has to offer. If we started doing arbitrary structured +learning, we'd need to redesign the whole package and the project +would likely collapse under its own weight. + +There are two project with API similar to scikit-learn that +do structured prediction: + +* `pystruct `_ handles general structured + learning (focuses on SSVMs on arbitrary graph structures with + approximate inference; defines the notion of sample as an instance of + the graph structure) + +* `seqlearn `_ handles sequences only (focuses on + exact inference; has HMMs, but mostly for the sake of completeness; + treats a feature vector as a sample and uses an offset encoding for + the dependencies between feature vectors) + +Will you add GPU support? +-------------------------- +No, or at least not in the near future. The main reason is that GPU support will introduce many software dependencies and introduce platform specific issues. +scikit-learn is designed to be easy to install on a wide variety of platforms. +Outside of neural networks, GPUs don't play a large role in machine learning today, and much larger gains in speed can often be achieved by a careful choice of algorithms. + +Do you support PyPy? +-------------------- + +In case you didn't know, `PyPy `_ is the new, fast, +just-in-time compiling Python implementation. We don't support it. +When the `NumPy support `_ +in PyPy is complete or near-complete, and SciPy is ported over as well, +we can start thinking of a port. +We use too much of NumPy to work with a partial implementation. + +How do I deal with string data (or trees, graphs...)? +----------------------------------------------------- + +scikit-learn estimators assume you'll feed them real-valued feature vectors. +This assumption is hard-coded in pretty much all of the library. +However, you can feed non-numerical inputs to estimators in several ways. + +If you have text documents, you can use a term frequency features; see +:ref:`text_feature_extraction` for the built-in *text vectorizers*. +For more general feature extraction from any kind of data, see +:ref:`dict_feature_extraction` and :ref:`feature_hashing`. + +Another common case is when you have non-numerical data and a custom distance +(or similarity) metric on these data. Examples include strings with edit +distance (aka. Levenshtein distance; e.g., DNA or RNA sequences). These can be +encoded as numbers, but doing so is painful and error-prone. Working with +distance metrics on arbitrary data can be done in two ways. + +Firstly, many estimators take precomputed distance/similarity matrices, so if +the dataset is not too large, you can compute distances for all pairs of inputs. +If the dataset is large, you can use feature vectors with only one "feature", +which is an index into a separate data structure, and supply a custom metric +function that looks up the actual data in this data structure. E.g., to use +DBSCAN with Levenshtein distances:: + + >>> from leven import levenshtein # doctest: +SKIP + >>> import numpy as np + >>> from sklearn.cluster import dbscan + >>> data = ["ACCTCCTAGAAG", "ACCTACTAGAAGTT", "GAATATTAGGCCGA"] + >>> def lev_metric(x, y): + ... i, j = int(x[0]), int(y[0]) # extract indices + ... return levenshtein(data[i], data[j]) + ... + >>> X = np.arange(len(data)).reshape(-1, 1) + >>> X + array([[0], + [1], + [2]]) + >>> dbscan(X, metric=lev_metric, eps=5, min_samples=2) # doctest: +SKIP + ([0, 1], array([ 0, 0, -1])) + +(This uses the third-party edit distance package ``leven``.) + +Similar tricks can be used, with some care, for tree kernels, graph kernels, +etc. diff --git a/doc/images/blank_image.png b/doc/images/blank_image.png deleted file mode 100644 index 4913b99b19fe0..0000000000000 Binary files a/doc/images/blank_image.png and /dev/null differ diff --git a/doc/images/cds-logo.png b/doc/images/cds-logo.png new file mode 100644 index 0000000000000..98cfea26578b1 Binary files /dev/null and b/doc/images/cds-logo.png differ diff --git a/doc/images/google-logo.png b/doc/images/google-logo.png deleted file mode 100644 index 1019ff3f2f647..0000000000000 Binary files a/doc/images/google-logo.png and /dev/null differ diff --git a/doc/images/last_digit.png b/doc/images/last_digit.png index f6c715a54e216..cc327c3b41d12 100644 Binary files a/doc/images/last_digit.png and b/doc/images/last_digit.png differ diff --git a/doc/images/ml_map.png b/doc/images/ml_map.png new file mode 100644 index 0000000000000..73ebd9c05fcc4 Binary files /dev/null and b/doc/images/ml_map.png differ diff --git a/doc/images/no_image.png b/doc/images/no_image.png new file mode 100644 index 0000000000000..8c2d48d5d3f00 Binary files /dev/null and b/doc/images/no_image.png differ diff --git a/doc/images/plot_digits_classification.png b/doc/images/plot_digits_classification.png index e56cf364a3571..b88cbdfabdab7 100644 Binary files a/doc/images/plot_digits_classification.png and b/doc/images/plot_digits_classification.png differ diff --git a/doc/images/plot_face_recognition_1.png b/doc/images/plot_face_recognition_1.png index 94016383a027c..c523fd1b40190 100644 Binary files a/doc/images/plot_face_recognition_1.png and b/doc/images/plot_face_recognition_1.png differ diff --git a/doc/images/plot_face_recognition_2.png b/doc/images/plot_face_recognition_2.png index 83e05f0a05ed4..9d9435d57112d 100644 Binary files a/doc/images/plot_face_recognition_2.png and b/doc/images/plot_face_recognition_2.png differ diff --git a/doc/images/rbm_graph.png b/doc/images/rbm_graph.png new file mode 100644 index 0000000000000..27c0dd32a2dd0 Binary files /dev/null and b/doc/images/rbm_graph.png differ diff --git a/doc/images/scikit-learn-logo-notext.png b/doc/images/scikit-learn-logo-notext.png new file mode 100644 index 0000000000000..ce1e1056c66a6 Binary files /dev/null and b/doc/images/scikit-learn-logo-notext.png differ diff --git a/doc/index.rst b/doc/index.rst index a6baf3708099c..b8173f11edced 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -1,202 +1,386 @@ +.. We want the previous/next button to work on the user guide pages and on the + API. We have to put the doctree so that sphinx populates the + rellinks. Yet, we don't want it to be displayed on the main page, hence we + don't display through the css. -.. - We are putting the title as a raw HTML so that it doesn't appear in - the contents - .. raw:: html -

scikit-learn: machine learning in Python

- +
-.. - Here we are building a banner: a javascript selects randomly 4 images in - the list +.. toctree:: -.. only:: html + tutorial/index + user_guide + auto_examples/index + faq + support + whats_new + presentations + about + documentation + datasets/index + datasets/covtype + datasets/labeled_faces + datasets/mldata + datasets/olivetti_faces + datasets/twenty_newsgroups + modules/classes + testimonials/testimonials + developers/index + developers/debugging + developers/maintainer + developers/performance + developers/utilities + install + tutorial/basic/tutorial + tutorial/machine_learning_map/index - .. |banner1| image:: auto_examples/svm/images/plot_oneclass_1.png - :height: 139 - :target: auto_examples/svm/plot_oneclass.html - .. |banner2| image:: auto_examples/cluster/images/plot_ward_structured_vs_unstructured_2.png - :height: 139 - :target: auto_examples/cluster/plot_ward_structured_vs_unstructured.html - .. |banner3| image:: auto_examples/gaussian_process/images/plot_gp_regression_1.png - :height: 139 - :target: auto_examples/gaussian_process/plot_gp_regression.html +.. raw:: html - .. |banner4| image:: auto_examples/cluster/images/plot_lena_ward_segmentation_1.png - :height: 139 - :target: auto_examples/cluster/plot_lena_ward_segmentation.html +
- .. |banner5| image:: auto_examples/svm/images/plot_svm_nonlinear_1.png - :height: 139 - :target: auto_examples/svm/plot_svm_nonlinear.html - .. |banner6| image:: auto_examples/applications/images/plot_species_distribution_modeling_1.png - :height: 139 - :target: auto_examples/applications/plot_species_distribution_modeling.html +.. This is were the real work starts. - .. |banner7| image:: auto_examples/gaussian_process/images/plot_gp_probabilistic_classification_after_regression_1.png - :height: 139 - :target: auto_examples/gaussian_process/plot_gp_probabilistic_classification_after_regression.html - .. |banner8| image:: auto_examples/ensemble/images/plot_forest_importances_faces_1.png - :height: 139 - :target: auto_examples/ensemble/plot_forest_importances_faces.html +.. raw:: html - .. |banner9| image:: auto_examples/svm/images/plot_weighted_samples_1.png - :height: 139 - :target: auto_examples/svm/plot_weighted_samples.html + +
+
+
- .. |banner10| image:: auto_examples/linear_model/images/plot_sgd_weighted_samples_1.png - :height: 139 - :target: auto_examples/linear_model/plot_sgd_weighted_samples.html + +
+

- .. |banner11| image:: auto_examples/cluster/images/plot_kmeans_digits_1.png - :height: 139 - :target: auto_examples/cluster/plot_kmeans_digits.html +:ref:`Classification ` - .. |banner12| image:: auto_examples/decomposition/images/plot_faces_decomposition_2.png - :height: 139 - :target: auto_examples/decomposition/plot_faces_decomposition.html +.. raw:: html - .. |banner13| image:: auto_examples/decomposition/images/plot_faces_decomposition_3.png - :height: 139 - :target: auto_examples/decomposition/plot_faces_decomposition.html +

+
+

Identifying to which category an object belongs to.

+ +
+
- - - |center-div| |banner1| |banner2| |banner3| |banner4| |banner5| |banner6| |banner7| |banner8| |banner9| |banner10| |banner11| |banner12| |banner13| |banner14| |end-div| - - -.. topic:: Easy-to-use and general-purpose machine learning in Python - - ``scikit-learn`` is a Python module integrating classic machine - learning algorithms in the tightly-knit scientific Python - world (`numpy `_, `scipy - `_, `matplotlib - `_). - It aims to provide simple and efficient solutions to learning - problems, accessible to everybody and reusable in various - contexts: **machine-learning as a versatile tool for science and - engineering**. - - -.. raw:: html - - - -
- - - - - -
- -**License:** Open source, commercially usable: **BSD license** (3 clause) - -.. include:: includes/big_toc_css.rst - -Documentation for scikit-learn **version** |release|. For other versions and -printable format, see :ref:`documentation_resources`. - -User Guide -========== + +
+

-.. toctree:: - :maxdepth: 2 +:ref:`Regression ` + +.. raw:: html - user_guide.rst +

+
+

Predicting a continuous-valued attribute associated with an object.

+ +
+
-.. toctree:: - :hidden: + +
+

+ +:ref:`Clustering` + +.. raw:: html - support - whats_new - presentations +

+
+

Automatic grouping of similar objects into sets.

+ +
+
+ + +
+
+ + +
+

+ +:ref:`Dimensionality reduction` + +.. raw:: html + +

+
+

Reducing the number of random variables to consider.

+ +
+
+ + +
+

+ +:ref:`Model selection` + +.. raw:: html + +

+
+

Comparing, validating and choosing parameters and models.

+ +
+
+ + + +
+

+ +:ref:`Preprocessing` + +.. raw:: html + +

+
+

Feature extraction and normalization.

+ +
+
+ + +
+
+ + +
+
+ +
+

News

+ +
+ + +
+

Community

+ + +
+ + +
+ + Help us, donate! + Cite us! + + Read more about donations +
+ + +
+

Who uses scikit-learn?

+ + +

+ + More testimonials + +

+
+ +
+
+ + +
+
+ +
+
+
+ + + diff --git a/doc/install.rst b/doc/install.rst index ca6448c8f99ee..34d872dba2ff0 100644 --- a/doc/install.rst +++ b/doc/install.rst @@ -1,12 +1,14 @@ -========================= -Installing `scikit-learn` -========================= +.. _installation-instructions: + +======================= +Installing scikit-learn +======================= There are different ways to get scikit-learn installed: * Install the version of scikit-learn provided by your - :ref:`operating system distribution ` . This - is the quickest option for those who have operating systems that + :ref:`operating system or Python distribution `. + This is the quickest option for those who have operating systems that distribute scikit-learn. * :ref:`Install an official release `. This @@ -15,7 +17,7 @@ There are different ways to get scikit-learn installed: scikit-learn. * :ref:`Install the latest development version - `. This is best for users who want the + `. This is best for users who want the latest-and-greatest features and aren't afraid of running brand-new code. @@ -24,114 +26,144 @@ There are different ways to get scikit-learn installed: If you wish to contribute to the project, it's recommended you :ref:`install the latest development version`. + .. _install_official_release: Installing an official release ============================== +Scikit-learn requires: -Installing from source ----------------------- +- Python (>= 2.6 or >= 3.3), +- NumPy (>= 1.6.1), +- SciPy (>= 0.9). -Installing from source requires you to have installed python (>= 2.6), numpy -(>= 1.3), scipy (>= 0.7), setuptools, python development headers and a working -C++ compiler. Under Debian-based systems you can get all this by executing with -root privileges:: - sudo apt-get install python-dev python-numpy python-numpy-dev python-setuptools python-numpy-dev python-scipy libatlas-dev g++ +Windows +------- -.. note:: +First you need to install `numpy `_ and `scipy +`_ from their own official installers. - In Order to build the documentation and run the example code contains in - this documentation you will need matplotlib:: +Wheel packages (.whl files) for scikit-learn from `PyPI +`_ can be installed with the `pip +`_ utility. +Open a console and type the following to install or upgrade scikit-learn to the +latest stable release:: - sudo apt-get install python-matplotlib + pip install -U scikit-learn -.. note:: +If there are no binary packages matching your Python version you might +to try to install scikit-learn and its dependencies from `Christoph Gohlke +Unofficial Windows installers +`_ +or from a :ref:`Python distribution ` instead. - On Ubuntu LTS (10.04) the package `libatlas-dev` is called `libatlas-headers` -Easy install -~~~~~~~~~~~~ +Mac OSX +------- -This is usually the fastest way to install the latest stable -release. If you have pip or easy_install, you can install or update -with the command:: +Scikit-learn and its dependencies are all available as wheel packages for OSX:: - pip install -U scikit-learn + pip install -U numpy scipy scikit-learn -or:: - easy_install -U scikit-learn +Linux +----- -for easy_install. Note that you might need root privileges to run -these commands. +At this time scikit-learn does not provide official binary packages for Linux +so you have to build from source. -From source package -~~~~~~~~~~~~~~~~~~~ +Installing build dependencies +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Download the package from http://pypi.python.org/pypi/scikit-learn/ -, unpack the sources and cd into archive. +Installing from source requires you to have installed the scikit-learn runtime +dependencies, Python development headers and a working C/C++ compiler. +Under Debian-based operating systems, which include Ubuntu, if you have +Python 2 you can install all these requirements by issuing:: -This packages uses distutils, which is the default way of installing -python modules. The install command is:: + sudo apt-get install build-essential python-dev python-setuptools \ + python-numpy python-scipy \ + libatlas-dev libatlas3gf-base - python setup.py install +If you have Python 3:: + sudo apt-get install build-essential python3-dev python3-setuptools \ + python3-numpy python3-scipy \ + libatlas-dev libatlas3gf-base -Windows installer ------------------ +On recent Debian and Ubuntu (e.g. Ubuntu 13.04 or later) make sure that ATLAS +is used to provide the implementation of the BLAS and LAPACK linear algebra +routines:: -You can download a windows installer from `downloads -`_ in the -project's web page. Note that must also have installed the packages -numpy and setuptools. + sudo update-alternatives --set libblas.so.3 \ + /usr/lib/atlas-base/atlas/libblas.so.3 + sudo update-alternatives --set liblapack.so.3 \ + /usr/lib/atlas-base/atlas/liblapack.so.3 -This package is also expected to work with python(x,y) as of 2.6.5.5. +.. note:: -.. topic:: **Installing on Windows 64bit** + In order to build the documentation and run the example code contains in + this documentation you will need matplotlib:: - To install a 64bit version of the scikit, you can download the - binaries from http://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-learn - Note that this will require a compatible version of numpy, scipy and - matplotlib. The easiest option is to also download them from the same - URL. + sudo apt-get install python-matplotlib -Building on windows -------------------- +.. note:: -To build scikit-learn on windows you will need a C/C++ compiler in -addition to numpy, scipy and setuptools. At least -`MinGW `_ (a port of GCC to Windows OS) and the -Microsoft Visual C++ 2008 should work out of the box. To force the use -of a particular compiler, write a file named ``setup.cfg`` in the -source directory with the content:: + The above installs the ATLAS implementation of BLAS + (the Basic Linear Algebra Subprograms library). + Ubuntu 11.10 and later, and recent (testing) versions of Debian, + offer an alternative implementation called OpenBLAS. - [build_ext] - compiler=my_compiler + Using OpenBLAS can give speedups in some scikit-learn modules, + but can freeze joblib/multiprocessing prior to OpenBLAS version 0.2.8-4, + so using it is not recommended unless you know what you're doing. - [build] - compiler=my_compiler + If you do want to use OpenBLAS, then replacing ATLAS only requires a couple + of commands. ATLAS has to be removed, otherwise NumPy may not work:: -where ``my_compiler`` should be one of ``mingw32`` or ``msvc``. + sudo apt-get remove libatlas3gf-base libatlas-dev + sudo apt-get install libopenblas-dev -When the appropriate compiler has been set, and assuming Python is -in your PATH (see -`Python FAQ for windows `_ -for more details), installation is done by -executing the command:: + sudo update-alternatives --set libblas.so.3 \ + /usr/lib/openblas-base/libopenblas.so.0 + sudo update-alternatives --set liblapack.so.3 \ + /usr/lib/lapack/liblapack.so.3 - python setup.py install +On Red Hat and clones (e.g. CentOS), install the dependencies using:: + sudo yum -y install gcc gcc-c++ numpy python-devel scipy -To build a precompiled package like the ones distributed at -`the downloads section `_, -the command to execute is:: - python setup.py bdist_wininst -b doc/logos/scikit-learn-logo.bmp +Building scikit-learn with pip +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -This will create an installable binary under directory ``dist/``. +This is usually the fastest way to install or upgrade to the latest stable +release:: + + pip install --user --install-option="--prefix=" -U scikit-learn + +The ``--user`` flag ask pip to install scikit-learn in the ``$HOME/.local`` +folder therefore not requiring root permission. This flag should make pip +ignore any old version of scikit-learn previously installed on the system while +benefiting from system packages for numpy and scipy. Those dependencies can +be long and complex to build correctly from source. + +The ``--install-option="--prefix="`` flag is only required if Python has a +``distutils.cfg`` configuration with a predefined ``prefix=`` entry. + + +From source package +~~~~~~~~~~~~~~~~~~~ + +Download the source package from http://pypi.python.org/pypi/scikit-learn/ +, unpack the sources and cd into the source directory. + +This packages uses distutils, which is the default way of installing +python modules. The install command is:: + + python setup.py install .. _install_by_distribution: @@ -146,54 +178,79 @@ These can make installation and upgrading much easier for users since the integration includes the ability to automatically install dependencies (numpy, scipy) that scikit-learn requires. -The following is a list of Linux distributions that provide their own -version of scikit-learn: +The following is an incomplete list of Python and OS distributions +that provide their own version of scikit-learn. Debian and derivatives (Ubuntu) ------------------------------- -The Debian package is named python-sklearn (formerly -python-scikits-learn) and can be installed using the following -commands with root privileges:: +The Debian package is named ``python-sklearn`` +(formerly ``python-scikits-learn``) +and can be installed using the following command:: - apt-get install python-sklearn + sudo apt-get install python-sklearn Additionally, backport builds of the most recent release of scikit-learn for existing releases of Debian and Ubuntu are available -from `NeuroDebian repository -`__ . +from the `NeuroDebian repository +`_ . -Python(x, y) ------------- +A quick-'n'-dirty way of rolling your own ``.deb`` package +is to `use stdeb `_. -The `Python(x, y) `_ distributes scikit-learn as an additional plugin, which can -be found in the `Additional plugins `_ -page. +Python(x,y) for Windows +----------------------- -Enthought Python distribution ------------------------------ +The `Python(x,y) `_ project distributes +scikit-learn as an additional plugin, which can be found in the `Additional +plugins `_ page. + + +Canopy and Anaconda for all supported platforms +----------------------------------------------- -The `Enthought Python Distribution -`_ already ships a recent -version. +`Canopy +`_ and `Anaconda +`_ ships a recent +version, in addition to a large set of scientific python library. -Macports --------- +MacPorts for Mac OSX +-------------------- -The macport's package is named `py26-sklearn` or `py27-sklearn` depending -on the version of Python. It can be installed by typing the following +The MacPorts package is named ``py-scikits-learn``, +where ``XY`` denotes the Python version. +It can be installed by typing the following command:: - sudo port install py26-sklearn + sudo port install py26-scikit-learn or:: - sudo port install py27-sklearn + sudo port install py27-scikit-learn + + +Arch Linux +---------- + +Arch Linux's package is provided through the `official repositories +`_ as +``python-scikit-learn`` for Python 3 and ``python2-scikit-learn`` for Python 2. +It can be installed by typing the following command: -depending on the version of Python you want to use. +.. code-block:: none + + # pacman -S python-scikit-learn + +or: + +.. code-block:: none + + # pacman -S python2-scikit-learn + +depending on the version of Python you use. NetBSD @@ -203,12 +260,133 @@ scikit-learn is available via `pkgsrc-wip `_ http://pkgsrc.se/wip/py-scikit_learn +Fedora +------ + +The Fedora package is called ``python-scikit-learn`` for the Python 2 version +and ``python3-scikit-learn`` for the Python 3 version. Both versions can +be installed using ``yum``:: + + $ sudo yum install python-scikit-learn + +or:: + + $ sudo yum install python3-scikit-learn + + +Building on windows +=================== + +To build scikit-learn on Windows you need a working C/C++ compiler in +addition to numpy, scipy and setuptools. + +Picking the right compiler depends on the version of Python (2 or 3) +and the architecture of the Python interpreter, 32-bit or 64-bit. +You can check the Python version by running the following in ``cmd`` or +``powershell`` console:: + + python --version + +and the architecture with:: + + python -c "import struct; print(struct.calcsize('P') * 8)" + +The above commands assume that you have the Python installation folder in your +PATH environment variable. + + +32-bit Python +------------- + +For 32-bit Python it is possible use the standalone installers for +`Microsoft Visual C++ Express 2008 `_ +for Python 2 or +`Microsoft Visual C++ Express 2010 `_ +or Python 3. + +Once installed you should be able to build scikit-learn without any +particular configuration by running the following command in the scikit-learn +folder:: + + python setup.py install + + +64-bit Python +------------- + +For the 64-bit architecture, you either need the full Visual Studio or +the free Windows SDKs that can be downloaded from the links below. + +The Windows SDKs include the MSVC compilers both for 32 and 64-bit +architectures. They come as a ``GRMSDKX_EN_DVD.iso`` file that can be mounted +as a new drive with a ``setup.exe`` installer in it. + +- For Python 2 you need SDK **v7.0**: `MS Windows SDK for Windows 7 and .NET + Framework 3.5 SP1 + `_ + +- For Python 3 you need SDK **v7.1**: `MS Windows SDK for Windows 7 and .NET + Framework 4 + `_ + +Both SDKs can be installed in parallel on the same host. To use the Windows +SDKs, you need to setup the environment of a ``cmd`` console launched with the +following flags (at least for SDK v7.0):: + + cmd /E:ON /V:ON /K + +Then configure the build environment with:: + + SET DISTUTILS_USE_SDK=1 + SET MSSdk=1 + "C:\Program Files\Microsoft SDKs\Windows\v7.0\Setup\WindowsSdkVer.exe" -q -version:v7.0 + "C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\SetEnv.cmd" /x64 /release + +Finally you can build scikit-learn in the same ``cmd`` console:: + + python setup.py install + +Replace ``v7.0`` by the ``v7.1`` in the above commands to do the same for +Python 3 instead of Python 2. + +Replace ``/x64`` by ``/x86`` to build for 32-bit Python instead of 64-bit +Python. + + +Building binary packages and installers +--------------------------------------- + +The ``.whl`` package and ``.exe`` installers can be built with:: + + pip install wheel + python setup.py bdist_wheel bdist_wininst -b doc/logos/scikit-learn-logo.bmp + +The resulting packages are generated in the ``dist/`` folder. + + +Using an alternative compiler +----------------------------- + +It is possible to use `MinGW `_ (a port of GCC to Windows +OS) as an alternative to MSVC for 32-bit Python. Not that extensions built with +mingw32 can be redistributed as reusable packages as they depend on GCC runtime +libraries typically not installed on end-users environment. + +To force the use of a particular compiler, pass the ``--compiler`` flag to the +build step:: + + python setup.py build --compiler=my_compiler install + +where ``my_compiler`` should be one of ``mingw32`` or ``msvc``. + + .. _install_bleeding_edge: Bleeding Edge ============= -See section :ref:`git_repo` on how to get the development version. +See section :ref:`git_repo` on how to get the development version. Then follow +the previous instructions to build from source depending on your platform. .. _testing: @@ -216,33 +394,38 @@ See section :ref:`git_repo` on how to get the development version. Testing ======= +Testing scikit-learn once installed +----------------------------------- + Testing requires having the `nose `_ library. After installation, the package can be tested by executing *from outside* the source directory:: - nosetests sklearn --exe + $ nosetests -v sklearn -This should give you a lot of output (and some warnings) but -eventually should finish with the a text similar to:: +Under Windows, it is recommended to use the following command (adjust the path +to the ``python.exe`` program) as using the ``nosetests.exe`` program can badly +interact with tests that use ``multiprocessing``:: - Ran 601 tests in 27.920s - OK (SKIP=2) + C:\Python34\python.exe -c "import nose; nose.main()" -v sklearn -otherwise please consider posting an issue into the `bug tracker -`_ or to the -:ref:`mailing_lists`. +This should give you a lot of output (and some warnings) but +eventually should finish with a message similar to:: -.. note:: **Alternative testing method** + Ran 3246 tests in 260.618s + OK (SKIP=20) - If for some reason the recommended method is failing for you, please try - the alternate method:: +Otherwise, please consider posting an issue into the `bug tracker +`_ or to the +:ref:`mailing_lists` including the traceback of the individual failures +and errors. - python -c "import sklearn; sklearn.test()" - This method might display doctest failures because of nosetests issues. +Testing scikit-learn from within the source folder +-------------------------------------------------- -scikit-learn can also be tested without having the package +Scikit-learn can also be tested without having the package installed. For this you must compile the sources inplace from the source directory:: @@ -250,12 +433,18 @@ source directory:: Test can now be run using nosetests:: - nosetests sklearn/ + nosetests -v sklearn/ -This is automated in the commands:: +This is automated by the commands:: make in and:: make test + + +You can also install a symlink named ``site-packages/scikit-learn.egg-link`` +to the development folder of scikit-learn with:: + + pip install --editable . diff --git a/doc/logos/scikit-learn-logo-notext.png b/doc/logos/scikit-learn-logo-notext.png index b1ecda03ec7ad..ce1e1056c66a6 100644 Binary files a/doc/logos/scikit-learn-logo-notext.png and b/doc/logos/scikit-learn-logo-notext.png differ diff --git a/doc/logos/scikit-learn-logo-small.png b/doc/logos/scikit-learn-logo-small.png index 6541a54a241ec..32f15792df266 100644 Binary files a/doc/logos/scikit-learn-logo-small.png and b/doc/logos/scikit-learn-logo-small.png differ diff --git a/doc/logos/scikit-learn-logo-thumb.png b/doc/logos/scikit-learn-logo-thumb.png index b18e8bdc20a08..2e804752b5824 100644 Binary files a/doc/logos/scikit-learn-logo-thumb.png and b/doc/logos/scikit-learn-logo-thumb.png differ diff --git a/doc/logos/scikit-learn-logo.bmp b/doc/logos/scikit-learn-logo.bmp new file mode 100644 index 0000000000000..6bf8992f048fe Binary files /dev/null and b/doc/logos/scikit-learn-logo.bmp differ diff --git a/doc/logos/scikit-learn-logo.png b/doc/logos/scikit-learn-logo.png index 4b0b759cfab08..a20d5256356aa 100644 Binary files a/doc/logos/scikit-learn-logo.png and b/doc/logos/scikit-learn-logo.png differ diff --git a/doc/model_selection.rst b/doc/model_selection.rst index c13a7821f68f8..daec6a6ed83e4 100644 --- a/doc/model_selection.rst +++ b/doc/model_selection.rst @@ -2,11 +2,13 @@ .. _model_selection: -Model Selection ------------------------ +Model selection and evaluation +------------------------------ .. toctree:: modules/cross_validation modules/grid_search - modules/pipeline + modules/model_evaluation + modules/model_persistence + modules/learning_curve diff --git a/doc/modules/biclustering.rst b/doc/modules/biclustering.rst new file mode 100644 index 0000000000000..1509902aefc14 --- /dev/null +++ b/doc/modules/biclustering.rst @@ -0,0 +1,306 @@ +.. _biclustering: + +============ +Biclustering +============ + +Biclustering can be performed with the module +:mod:`sklearn.cluster.bicluster`. Biclustering algorithms simultaneously +cluster rows and columns of a data matrix. These clusters of rows and +columns are known as biclusters. Each determines a submatrix of the +original data matrix with some desired properties. + +For instance, given a matrix of shape ``(10, 10)``, one possible bicluster +with three rows and two columns induces a submatrix of shape ``(3, 2)``:: + + >>> import numpy as np + >>> data = np.arange(100).reshape(10, 10) + >>> rows = np.array([0, 2, 3])[:, np.newaxis] + >>> columns = np.array([1, 2]) + >>> data[rows, columns] + array([[ 1, 2], + [21, 22], + [31, 32]]) + +For visualization purposes, given a bicluster, the rows and columns of +the data matrix may be rearranged to make the bicluster contiguous. + +Algorithms differ in how they define biclusters. Some of the +common types include: + +* constant values, constant rows, or constant columns +* unusually high or low values +* submatrices with low variance +* correlated rows or columns + +Algorithms also differ in how rows and columns may be assigned to +biclusters, which leads to different bicluster structures. Block +diagonal or checkerboard structures occur when rows and columns are +divided into partitions. + +If each row and each column belongs to exactly one bicluster, then +rearranging the rows and columns of the data matrix reveals the +biclusters on the diagonal. Here is an example of this structure +where biclusters have higher average values than the other rows and +columns: + +.. figure:: ../auto_examples/bicluster/images/plot_spectral_coclustering_003.png + :target: ../auto_examples/bicluster/images/plot_spectral_coclustering_003.png + :align: center + :scale: 50 + + An example of biclusters formed by partitioning rows and columns. + +In the checkerboard case, each row belongs to all column clusters, and +each column belongs to all row clusters. Here is an example of this +structure where the variance of the values within each bicluster is +small: + +.. figure:: ../auto_examples/bicluster/images/plot_spectral_biclustering_003.png + :target: ../auto_examples/bicluster/images/plot_spectral_biclustering_003.png + :align: center + :scale: 50 + + An example of checkerboard biclusters. + +After fitting a model, row and column cluster membership can be found +in the ``rows_`` and ``columns_`` attributes. ``rows_[i]`` is a binary vector +with nonzero entries corresponding to rows that belong to bicluster +``i``. Similarly, ``columns_[i]`` indicates which columns belong to +bicluster ``i``. + +Some models also have ``row_labels_`` and ``column_labels_`` attributes. +These models partition the rows and columns, such as in the block +diagonal and checkerboard bicluster structures. + +.. note:: + + Biclustering has many other names in different fields including + co-clustering, two-mode clustering, two-way clustering, block + clustering, coupled two-way clustering, etc. The names of some + algorithms, such as the Spectral Co-Clustering algorithm, reflect + these alternate names. + + +.. currentmodule:: sklearn.cluster.bicluster + + +.. _spectral_coclustering: + +Spectral Co-Clustering +====================== + +The :class:`SpectralCoclustering` algorithm finds biclusters with +values higher than those in the corresponding other rows and columns. +Each row and each column belongs to exactly one bicluster, so +rearranging the rows and columns to make partitions contiguous reveals +these high values along the diagonal: + +.. note:: + + The algorithm treats the input data matrix as a bipartite graph: the + rows and columns of the matrix correspond to the two sets of vertices, + and each entry corresponds to an edge between a row and a column. The + algorithm approximates the normalized cut of this graph to find heavy + subgraphs. + + +Mathematical formulation +------------------------ + +An approximate solution to the optimal normalized cut may be found via +the generalized eigenvalue decomposition of the Laplacian of the +graph. Usually this would mean working directly with the Laplacian +matrix. If the original data matrix :math:`A` has shape :math:`m +\times n`, the Laplacian matrix for the corresponding bipartite graph +has shape :math:`(m + n) \times (m + n)`. However, in this case it is +possible to work directly with :math:`A`, which is smaller and more +efficient. + +The input matrix :math:`A` is preprocessed as follows: + +.. math:: + A_n = R^{-1/2} A C^{-1/2} + +Where :math:`R` is the diagonal matrix with entry :math:`i` equal to +:math:`\sum_{j} A_{ij}` and :math:`C` is the diagonal matrix with +entry :math:`j` equal to :math:`\sum_{i} A_{ij}`. + +The singular value decomposition, :math:`A_n = U \Sigma V^\top`, +provides the partitions of the rows and columns of :math:`A`. A subset +of the left singular vectors gives the row partitions, and a subset +of the right singular vectors gives the column partitions. + +The :math:`\ell = \lceil \log_2 k \rceil` singular vectors, starting +from the second, provide the desired partitioning information. They +are used to form the matrix :math:`Z`: + +.. math:: + Z = \begin{bmatrix} R^{-1/2} U \\\\ + C^{-1/2} V + \end{bmatrix} + +where the the columns of :math:`U` are :math:`u_2, \dots, u_{\ell + +1}`, and similarly for :math:`V`. + +Then the rows of :math:`Z` are clustered using :ref:`k-means +`. The first ``n_rows`` labels provide the row partitioning, +and the remaining ``n_columns`` labels provide the column partitioning. + + +.. topic:: Examples: + + * :ref:`example_bicluster_plot_spectral_coclustering.py`: A simple example + showing how to generate a data matrix with biclusters and apply + this method to it. + + * :ref:`example_bicluster_bicluster_newsgroups.py`: An example of finding + biclusters in the twenty newsgroup dataset. + + +.. topic:: References: + + * Dhillon, Inderjit S, 2001. `Co-clustering documents and words using + bipartite spectral graph partitioning + `__. + + +.. _spectral_biclustering: + +Spectral Biclustering +===================== + +The :class:`SpectralBiclustering` algorithm assumes that the input +data matrix has a hidden checkerboard structure. The rows and columns +of a matrix with this structure may be partitioned so that the entries +of any bicluster in the Cartesian product of row clusters and column +clusters is are approximately constant. For instance, if there are two +row partitions and three column partitions, each row will belong to +three biclusters, and each column will belong to two biclusters. + +The algorithm partitions the rows and columns of a matrix so that a +corresponding blockwise-constant checkerboard matrix provides a good +approximation to the original matrix. + + +Mathematical formulation +------------------------ + +The input matrix :math:`A` is first normalized to make the +checkerboard pattern more obvious. There are three possible methods: + +1. *Independent row and column normalization*, as in Spectral + Co-Clustering. This method makes the rows sum to a constant and the + columns sum to a different constant. + +2. **Bistochastization**: repeated row and column normalization until + convergence. This method makes both rows and columns sum to the + same constant. + +3. **Log normalization**: the log of the data matrix is computed: :math:`L = + \log A`. Then the column mean :math:`\overline{L_{i \cdot}}`, row mean + :math:`\overline{L_{\cdot j}}`, and overall mean :math:`\overline{L_{\cdot + \cdot}}` of :math:`L` are computed. The final matrix is computed + according to the formula + +.. math:: + K_{ij} = L_{ij} - \overline{L_{i \cdot}} - \overline{L_{\cdot + j}} + \overline{L_{\cdot \cdot}} + +After normalizing, the first few singular vectors are computed, just +as in the Spectral Co-Clustering algorithm. + +If log normalization was used, all the singular vectors are +meaningful. However, if independent normalization or bistochastization +were used, the first singular vectors, :math:`u_1` and :math:`v_1`. +are discarded. From now on, the "first" singular vectors refers to +:math:`u_2 \dots u_{p+1}` and :math:`v_2 \dots v_{p+1}` except in the +case of log normalization. + +Given these singular vectors, they are ranked according to which can +be best approximated by a piecewise-constant vector. The +approximations for each vector are found using one-dimensional k-means +and scored using the Euclidean distance. Some subset of the best left +and right singular vector are selected. Next, the data is projected to +this best subset of singular vectors and clustered. + +For instance, if :math:`p` singular vectors were calculated, the +:math:`q` best are found as described, where :math:`q`__. + + +.. _biclustering_evaluation: + +.. currentmodule:: sklearn.metrics + +Biclustering evaluation +======================= + +There are two ways of evaluating a biclustering result: internal and +external. Internal measures, such as cluster stability, rely only on +the data and the result themselves. Currently there are no internal +bicluster measures in scikit-learn. External measures refer to an +external source of information, such as the true solution. When +working with real data the true solution is usually unknown, but +biclustering artificial data may be useful for evaluating algorithms +precisely because the true solution is known. + +To compare a set of found biclusters to the set of true biclusters, +two similarity measures are needed: a similarity measure for +individual biclusters, and a way to combine these individual +similarities into an overall score. + +To compare individual biclusters, several measures have been used. For +now, only the Jaccard index is implemented: + +.. math:: + J(A, B) = \frac{|A \cap B|}{|A| + |B| - |A \cap B|} + +where :math:`A` and :math:`B` are biclusters, :math:`|A \cap B|` is +the number of elements in their intersection. The Jaccard index +achieves its minimum of 0 when the biclusters to not overlap at all +and its maximum of 1 when they are identical. + +Several methods have been developed to compare two sets of biclusters. +For now, only :func:`consensus_score` (Hochreiter et. al., 2010) is +available: + +1. Compute bicluster similarities for pairs of biclusters, one in each + set, using the Jaccard index or a similar measure. + +2. Assign biclusters from one set to another in a one-to-one fashion + to maximize the sum of their similarities. This step is performed + using the Hungarian algorithm. + +3. The final sum of similarities is divided by the size of the larger + set. + +The minimum consensus score, 0, occurs when all pairs of biclusters +are totally dissimilar. The maximum score, 1, occurs when both sets +are identical. + + +.. topic:: References: + + * Hochreiter, Bodenhofer, et. al., 2010. `FABIA: factor analysis + for bicluster acquisition + `__. diff --git a/doc/modules/calibration.rst b/doc/modules/calibration.rst new file mode 100644 index 0000000000000..686416caf73f7 --- /dev/null +++ b/doc/modules/calibration.rst @@ -0,0 +1,202 @@ +.. _calibration: + +======================= +Probability calibration +======================= + +.. currentmodule:: sklearn.calibration + + +When performing classification you often want not only to predict the class +label, but also obtain a probability of the respective label. This probability +gives you some kind of confidence on the prediction. Some models can give you +poor estimates of the class probabilities and some even do not not support +probability prediction. The calibration module allows you to better calibrate +the probabilities of a given model, or to add support for probability +prediction. + +Well calibrated classifiers are probabilistic classifiers for which the output +of the predict_proba method can be directly interpreted as a confidence level. +For instance, a well calibrated (binary) classifier should classify the samples +such that among the samples to which it gave a predict_proba value close to 0.8, +approximately 80% actually belong to the positive class. The following plot compares +how well the probabilistic predictions of different classifiers are calibrated: + +.. figure:: ../auto_examples/calibration/images/plot_compare_calibration_001.png + :target: ../auto_examples/calibration/plot_compare_calibration.html + :align: center + +.. currentmodule:: sklearn.linear_model + +:class:`LogisticRegression` returns well calibrated predictions by default as it directly +optimizes log-loss. In contrast, the other methods return biased probabilities; +with different biases per method: + +.. currentmodule:: sklearn.naive_bayes + +* :class:`GaussianNB` tends to push probabilties to 0 or 1 (note the + counts in the histograms). This is mainly because it makes the assumption + that features are conditionally independent given the class, which is not + the case in this dataset which contains 2 redundant features. + +.. currentmodule:: sklearn.ensemble + +* :class:`RandomForestClassifier` shows the opposite behavior: the histograms + show peaks at approximately 0.2 and 0.9 probability, while probabilities close to + 0 or 1 are very rare. An explanation for this is given by Niculescu-Mizil + and Caruana [4]: "Methods such as bagging and random forests that average + predictions from a base set of models can have difficulty making predictions + near 0 and 1 because variance in the underlying base models will bias + predictions that should be near zero or one away from these values. Because + predictions are restricted to the interval [0,1], errors caused by variance + tend to be one-sided near zero and one. For example, if a model should + predict p = 0 for a case, the only way bagging can achieve this is if all + bagged trees predict zero. If we add noise to the trees that bagging is + averaging over, this noise will cause some trees to predict values larger + than 0 for this case, thus moving the average prediction of the bagged + ensemble away from 0. We observe this effect most strongly with random + forests because the base-level trees trained with random forests have + relatively high variance due to feature subseting." As a result, the + calibration curve shows a characteristic sigmoid shape, indicating that the + classifier could trust its "intuition" more and return probabilties closer + to 0 or 1 typically. + +.. currentmodule:: sklearn.svm + +* Linear Support Vector Classification (:class:`LinearSVC`) shows an even more sigmoid curve + as the RandomForestClassifier, which is typical for maximum-margin methods + (compare Niculescu-Mizil and Caruana [4]), which focus on hard samples + that are close to the decision boundary (the support vectors). + +.. currentmodule:: sklearn.calibration + +Two approaches for performing calibration of probabilistic predictions are +provided: a parametric approach based on Platt's sigmoid model and a +non-parametric approach based on isotonic regression (:mod:`sklearn.isotonic`). +Probability calibration should be done on new data not used for model fitting. +The class :class:`CalibratedClassifierCV` uses a cross-validation generator and +estimates for each split the model parameter on the train samples and the +calibration of the test samples. The probabilities predicted for the +folds are then averaged. Already fitted classifiers can be calibrated by +:class:`CalibratedClassifierCV` via the paramter cv="prefit". In this case, +the user has to take care manually that data for model fitting and calibration +are disjoint. + +The following images demonstrate the benefit of probability calibration. +The first image present a dataset with 2 classes and 3 blobs of +data. The blob in the middle contains random samples of each class. +The probability for the samples in this blob should be 0.5. + +.. figure:: ../auto_examples/calibration/images/plot_calibration_001.png + :target: ../auto_examples/calibration/plot_calibration.html + :align: center + +The following image shows on the data above the estimated probability +using a Gaussian naive Bayes classifier without calibration, +with a sigmoid calibration and with a non-parametric isotonic +calibration. One can observe that the non-parametric model +provides the most accurate probability estimates for samples +in the middle, i.e., 0.5. + +.. figure:: ../auto_examples/calibration/images/plot_calibration_002.png + :target: ../auto_examples/calibration/plot_calibration.html + :align: center + +.. currentmodule:: sklearn.metrics + +The following experiment is performed on an artificial dataset for binary +classification with 100.000 samples (1.000 of them are used for model fitting) +with 20 features. Of the 20 features, only 2 are informative and 10 are +redundant. The figure shows the estimated probabilities obtained with +logistic regression, a linear support-vector classifier (SVC), and linear SVC with +both isotonic calibration and sigmoid calibration. The calibration performance +is evaluated with Brier score :func:`brier_score_loss`, reported in the legend +(the smaller the better). + +.. figure:: ../auto_examples/calibration/images/plot_calibration_curve_002.png + :target: ../auto_examples/calibration/plot_calibration_curve.html + :align: center + +One can observe here that logistic regression is well calibrated as its curve is +nearly diagonal. Linear SVC's calibration curve has a sigmoid curve, which is +typical for an under-confident classifier. In the case of LinearSVC, this is +caused by the margin property of the hinge loss, which lets the model focus on +hard samples that are close to the decision boundary (the support vectors). Both +kinds of calibration can fix this issue and yield nearly identical results. +The next figure shows the calibration curve of Gaussian naive Bayes on +the same data, with both kinds of calibration and also without calibration. + +.. figure:: ../auto_examples/calibration/images/plot_calibration_curve_001.png + :target: ../auto_examples/calibration/plot_calibration_curve.html + :align: center + +One can see that Gaussian naive Bayes performs very badly but does so in an +other way than linear SVC: While linear SVC exhibited a sigmoid calibration +curve, Gaussian naive Bayes' calibration curve has a transposed-sigmoid shape. +This is typical for an over-confident classifier. In this case, the classifier's +overconfidence is caused by the redundant features which violate the naive Bayes +assumption of feature-independence. + +Calibration of the probabilities of Gaussian naive Bayes with isotonic +regression can fix this issue as can be seen from the nearly diagonal +calibration curve. Sigmoid calibration also improves the brier score slightly, +albeit not as strongly as the non-parametric isotonic calibration. This is an +intrinsic limitation of sigmoid calibration, whose parametric form assumes a +sigmoid rather than a transposed-sigmoid curve. The non-parametric isotonic +calibration model, however, makes no such strong assumptions and can deal with +either shape, provided that there is sufficient calibration data. In general, +sigmoid calibration is preferable if the calibration curve is sigmoid and when +there is few calibration data while isotonic calibration is preferable for non- +sigmoid calibration curves and in situations where many additional data can be +used for calibration. + +.. currentmodule:: sklearn.calibration + +:class:`CalibratedClassifierCV` can also deal with classification tasks that +involve more than two classes if the base estimator can do so. In this case, +the classifier is calibrated first for each class separately in an one-vs-rest +fashion. When predicting probabilities for unseen data, the calibrated +probabilities for each class are predicted separately. As those probabilities +do not necessarily sum to one, a postprocessing is performed to normalize them. + +The next image illustrates how sigmoid calibration changes predicted +probabilities for a 3-class classification problem. Illustrated is the standard +2-simplex, where the three corners correspond to the three classes. Arrows point +from the probability vectors predicted by an uncalibrated classifier to the +probability vectors predicted by the same classifier after sigmoid calibration +on a hold-out validation set. Colors indicate the true class of an instance +(red: class 1, green: class 2, blue: class 3). + +.. figure:: ../auto_examples/calibration/images/plot_calibration_multiclass_000.png + :target: ../auto_examples/calibration/plot_calibration_multiclass.html + :align: center + +The base classifier is a random forest classifier with 25 base estimators +(trees). If this classifier is trained on all 800 training datapoints, it is +overly confident in its predictions and thus incurs a large log-loss. +Calibrating an identical classifier, which was trained on 600 datapoints, with +method='sigmoid' on the remaining 200 datapoints reduces the confidence of the +predictions, i.e., moves the probability vectors from the edges of the simplex +towards the center: + +.. figure:: ../auto_examples/calibration/images/plot_calibration_multiclass_001.png + :target: ../auto_examples/calibration/plot_calibration_multiclass.html + :align: center + +This calibration results in a lower log-loss. Note that an alternative would +have been to increase the number of base estimators which would have resulted in +a similar decrease in log-loss. + +.. topic:: References: + + .. [1] Obtaining calibrated probability estimates from decision trees + and naive Bayesian classifiers, B. Zadrozny & C. Elkan, ICML 2001 + + .. [2] Transforming Classifier Scores into Accurate Multiclass + Probability Estimates, B. Zadrozny & C. Elkan, (KDD 2002) + + .. [3] Probabilistic Outputs for Support Vector Machines and Comparisons to + Regularized Likelihood Methods, J. Platt, (1999) + + .. [4] Predicting Good Probabilities with Supervised Learning, + A. Niculescu-Mizil & R. Caruana, ICML 2005 diff --git a/doc/modules/classes.rst b/doc/modules/classes.rst index cc48154098b4c..eefe6d6a6f3d4 100644 --- a/doc/modules/classes.rst +++ b/doc/modules/classes.rst @@ -7,8 +7,39 @@ the :ref:`full user guide ` for further details, as the class and function raw specifications may not be enough to give full guidelines on their uses. -.. contents:: List of modules - :local: + +.. _base_ref: + +:mod:`sklearn.base`: Base classes and utility functions +======================================================= + +.. automodule:: sklearn.base + :no-members: + :no-inherited-members: + +Base classes +------------ +.. currentmodule:: sklearn + +.. autosummary:: + :toctree: generated/ + :template: class.rst + + base.BaseEstimator + base.ClassifierMixin + base.ClusterMixin + base.RegressorMixin + base.TransformerMixin + +Functions +--------- +.. currentmodule:: sklearn + +.. autosummary:: + :toctree: generated/ + :template: function.rst + + base.clone .. _cluster_ref: @@ -31,7 +62,10 @@ Classes :template: class.rst cluster.AffinityPropagation + cluster.AgglomerativeClustering + cluster.Birch cluster.DBSCAN + cluster.FeatureAgglomeration cluster.KMeans cluster.MiniBatchKMeans cluster.MeanShift @@ -52,6 +86,28 @@ Functions cluster.mean_shift cluster.spectral_clustering +.. _bicluster_ref: + +:mod:`sklearn.cluster.bicluster`: Biclustering +============================================== + +.. automodule:: sklearn.cluster.bicluster + :no-members: + :no-inherited-members: + +**User guide:** See the :ref:`biclustering` section for further details. + +Classes +------- +.. currentmodule:: sklearn.cluster.bicluster + +.. autosummary:: + :toctree: generated/ + :template: class.rst + + SpectralBiclustering + SpectralCoclustering + .. _covariance_ref: :mod:`sklearn.covariance`: Covariance Estimators @@ -106,12 +162,12 @@ Functions :toctree: generated/ :template: class.rst - cross_validation.Bootstrap cross_validation.KFold cross_validation.LeaveOneLabelOut cross_validation.LeaveOneOut cross_validation.LeavePLabelOut cross_validation.LeavePOut + cross_validation.PredefinedSplit cross_validation.StratifiedKFold cross_validation.ShuffleSplit cross_validation.StratifiedShuffleSplit @@ -122,6 +178,7 @@ Functions cross_validation.train_test_split cross_validation.cross_val_score + cross_validation.cross_val_predict cross_validation.permutation_test_score cross_validation.check_cv @@ -145,6 +202,8 @@ Loaders :toctree: generated/ :template: function.rst + datasets.clear_data_home + datasets.get_data_home datasets.fetch_20newsgroups datasets.fetch_20newsgroups_vectorized datasets.load_boston @@ -157,11 +216,17 @@ Loaders datasets.load_lfw_people datasets.fetch_lfw_people datasets.load_linnerud + datasets.mldata_filename datasets.fetch_mldata datasets.fetch_olivetti_faces + datasets.fetch_california_housing + datasets.fetch_covtype + datasets.load_mlcomp datasets.load_sample_image datasets.load_sample_images datasets.load_svmlight_file + datasets.load_svmlight_files + datasets.dump_svmlight_file Samples generator ----------------- @@ -178,6 +243,7 @@ Samples generator datasets.make_friedman1 datasets.make_friedman2 datasets.make_friedman3 + datasets.make_gaussian_quantiles datasets.make_hastie_10_2 datasets.make_low_rank_matrix datasets.make_moons @@ -189,6 +255,8 @@ Samples generator datasets.make_sparse_uncorrelated datasets.make_spd_matrix datasets.make_swiss_roll + datasets.make_biclusters + datasets.make_checkerboard .. _decomposition_ref: @@ -209,11 +277,13 @@ Samples generator :template: class.rst decomposition.PCA - decomposition.ProbabilisticPCA + decomposition.IncrementalPCA decomposition.ProjectedGradientNMF decomposition.RandomizedPCA decomposition.KernelPCA + decomposition.FactorAnalysis decomposition.FastICA + decomposition.TruncatedSVD decomposition.NMF decomposition.SparsePCA decomposition.MiniBatchSparsePCA @@ -230,6 +300,29 @@ Samples generator decomposition.dict_learning_online decomposition.sparse_encode +.. _dummy_ref: + +:mod:`sklearn.dummy`: Dummy estimators +====================================== + +.. automodule:: sklearn.dummy + :no-members: + :no-inherited-members: + +**User guide:** See the :ref:`model_evaluation` section for further details. + +.. currentmodule:: sklearn + +.. autosummary:: + :toctree: generated/ + :template: class.rst + + dummy.DummyClassifier + dummy.DummyRegressor + +.. autosummary:: + :toctree: generated/ + :template: function.rst .. _ensemble_ref: @@ -248,17 +341,39 @@ Samples generator :toctree: generated/ :template: class.rst - ensemble.RandomForestClassifier - ensemble.RandomForestRegressor + ensemble.AdaBoostClassifier + ensemble.AdaBoostRegressor + ensemble.BaggingClassifier + ensemble.BaggingRegressor ensemble.ExtraTreesClassifier ensemble.ExtraTreesRegressor ensemble.GradientBoostingClassifier ensemble.GradientBoostingRegressor + ensemble.RandomForestClassifier + ensemble.RandomTreesEmbedding + ensemble.RandomForestRegressor + +.. autosummary:: + :toctree: generated/ + :template: function.rst + + +partial dependence +------------------ + +.. automodule:: sklearn.ensemble.partial_dependence + :no-members: + :no-inherited-members: + +.. currentmodule:: sklearn .. autosummary:: :toctree: generated/ :template: function.rst + ensemble.partial_dependence.partial_dependence + ensemble.partial_dependence.plot_partial_dependence + .. _feature_extraction_ref: @@ -278,6 +393,7 @@ Samples generator :template: class.rst feature_extraction.DictVectorizer + feature_extraction.FeatureHasher From images ----------- @@ -317,6 +433,7 @@ From text :template: class.rst feature_extraction.text.CountVectorizer + feature_extraction.text.HashingVectorizer feature_extraction.text.TfidfTransformer feature_extraction.text.TfidfVectorizer @@ -338,6 +455,7 @@ From text :toctree: generated/ :template: class.rst + feature_selection.GenericUnivariateSelect feature_selection.SelectPercentile feature_selection.SelectKBest feature_selection.SelectFpr @@ -345,6 +463,7 @@ From text feature_selection.SelectFwe feature_selection.RFE feature_selection.RFECV + feature_selection.VarianceThreshold .. autosummary:: :toctree: generated/ @@ -407,19 +526,21 @@ From text :template: class.rst grid_search.GridSearchCV - grid_search.IterGrid + grid_search.ParameterGrid + grid_search.ParameterSampler + grid_search.RandomizedSearchCV -.. _hmm_ref: +.. _isotonic_ref: -:mod:`sklearn.hmm`: Hidden Markov Models -======================================== +:mod:`sklearn.isotonic`: Isotonic regression +============================================ -.. automodule:: sklearn.hmm +.. automodule:: sklearn.isotonic :no-members: :no-inherited-members: -**User guide:** See the :ref:`hmm` section for further details. +**User guide:** See the :ref:`isotonic` section for further details. .. currentmodule:: sklearn @@ -427,10 +548,14 @@ From text :toctree: generated/ :template: class.rst - hmm.GaussianHMM - hmm.MultinomialHMM - hmm.GMMHMM + isotonic.IsotonicRegression +.. autosummary:: + :toctree: generated + :template: function.rst + + isotonic.isotonic_regression + isotonic.check_increasing .. _kernel_approximation_ref: @@ -449,18 +574,21 @@ From text :toctree: generated/ :template: class.rst - kernel_approximation.RBFSampler kernel_approximation.AdditiveChi2Sampler + kernel_approximation.Nystroem + kernel_approximation.RBFSampler kernel_approximation.SkewedChi2Sampler -:mod:`sklearn.semi_supervised` Semi-Supervised Learning +.. _kernel_ridge_ref: + +:mod:`sklearn.kernel_ridge` Kernel Ridge Regression ======================================================== -.. automodule:: sklearn.semi_supervised +.. automodule:: sklearn.kernel_ridge :no-members: :no-inherited-members: -**User guide:** See the :ref:`semi_supervised` section for further details. +**User guide:** See the :ref:`kernel_ridge` section for further details. .. currentmodule:: sklearn @@ -468,8 +596,7 @@ From text :toctree: generated/ :template: class.rst - semi_supervised.LabelPropagation - semi_supervised.LabelSpreading + kernel_ridge.KernelRidge .. _lda_ref: @@ -491,6 +618,24 @@ From text lda.LDA +.. _learning_curve_ref: + +:mod:`sklearn.learning_curve` Learning curve evaluation +======================================================= + +.. automodule:: sklearn.learning_curve + :no-members: + :no-inherited-members: + +.. currentmodule:: sklearn + +.. autosummary:: + :toctree: generated/ + :template: function.rst + + learning_curve.learning_curve + learning_curve.validation_curve + .. _linear_model_ref: :mod:`sklearn.linear_model`: Generalized Linear Models @@ -512,7 +657,6 @@ From text linear_model.BayesianRidge linear_model.ElasticNet linear_model.ElasticNetCV - linear_model.IsotonicRegression linear_model.Lars linear_model.LarsCV linear_model.Lasso @@ -522,24 +666,31 @@ From text linear_model.LassoLarsIC linear_model.LinearRegression linear_model.LogisticRegression + linear_model.LogisticRegressionCV linear_model.MultiTaskLasso linear_model.MultiTaskElasticNet + linear_model.MultiTaskLassoCV + linear_model.MultiTaskElasticNetCV linear_model.OrthogonalMatchingPursuit + linear_model.OrthogonalMatchingPursuitCV + linear_model.PassiveAggressiveClassifier + linear_model.PassiveAggressiveRegressor linear_model.Perceptron linear_model.RandomizedLasso linear_model.RandomizedLogisticRegression + linear_model.RANSACRegressor linear_model.Ridge linear_model.RidgeClassifier linear_model.RidgeClassifierCV linear_model.RidgeCV linear_model.SGDClassifier linear_model.SGDRegressor + linear_model.TheilSenRegressor .. autosummary:: :toctree: generated/ :template: function.rst - linear_model.isotonic_regression linear_model.lars_path linear_model.lasso_path linear_model.lasso_stability_path @@ -567,12 +718,15 @@ From text manifold.LocallyLinearEmbedding manifold.Isomap manifold.MDS + manifold.SpectralEmbedding + manifold.TSNE .. autosummary:: :toctree: generated :template: function.rst manifold.locally_linear_embedding + manifold.spectral_embedding .. _metrics_ref: @@ -580,49 +734,94 @@ From text :mod:`sklearn.metrics`: Metrics =============================== +See the :ref:`model_evaluation` section and the :ref:`metrics` section of the +user guide for further details. + .. automodule:: sklearn.metrics :no-members: :no-inherited-members: .. currentmodule:: sklearn +Model Selection Interface +------------------------- +See the :ref:`scoring_parameter` section of the user guide for further +details. + +.. autosummary:: + :toctree: generated/ + :template: function.rst + + metrics.make_scorer + metrics.get_scorer + Classification metrics ---------------------- +See the :ref:`classification_metrics` section of the user guide for further +details. + .. autosummary:: :toctree: generated/ :template: function.rst - metrics.confusion_matrix - metrics.roc_curve + metrics.accuracy_score metrics.auc - metrics.precision_score - metrics.recall_score - metrics.fbeta_score - metrics.f1_score - metrics.auc_score metrics.average_precision_score - metrics.precision_recall_fscore_support + metrics.brier_score_loss metrics.classification_report - metrics.precision_recall_curve - metrics.zero_one_score - metrics.zero_one + metrics.confusion_matrix + metrics.f1_score + metrics.fbeta_score + metrics.hamming_loss metrics.hinge_loss + metrics.jaccard_similarity_score + metrics.log_loss + metrics.matthews_corrcoef + metrics.precision_recall_curve + metrics.precision_recall_fscore_support + metrics.precision_score + metrics.recall_score + metrics.roc_auc_score + metrics.roc_curve + metrics.zero_one_loss + metrics.brier_score_loss Regression metrics ------------------ +See the :ref:`regression_metrics` section of the user guide for further +details. + .. autosummary:: :toctree: generated/ :template: function.rst - metrics.r2_score + metrics.explained_variance_score + metrics.mean_absolute_error metrics.mean_squared_error + metrics.median_absolute_error + metrics.r2_score + +Multilabel ranking metrics +-------------------------- +See the :ref:`multilabel_ranking_metrics` section of the user guide for further +details. + +.. autosummary:: + :toctree: generated/ + :template: function.rst + + metrics.coverage_error + metrics.label_ranking_average_precision_score + + Clustering metrics ------------------ -See the :ref:`clustering` section of the user guide for further details. +See the :ref:`clustering_evaluation` section of the user guide for further +details. .. automodule:: sklearn.metrics.cluster :no-members: @@ -642,11 +841,29 @@ See the :ref:`clustering` section of the user guide for further details. metrics.mutual_info_score metrics.normalized_mutual_info_score metrics.silhouette_score + metrics.silhouette_samples metrics.v_measure_score +Biclustering metrics +-------------------- + +See the :ref:`biclustering_evaluation` section of the user guide for +further details. + +.. currentmodule:: sklearn + +.. autosummary:: + :toctree: generated/ + :template: function.rst + + metrics.consensus_score + + Pairwise metrics ---------------- +See the :ref:`metrics` section of the user guide for further details. + .. automodule:: sklearn.metrics.pairwise :no-members: :no-inherited-members: @@ -657,15 +874,20 @@ Pairwise metrics :toctree: generated/ :template: function.rst + metrics.pairwise.additive_chi2_kernel + metrics.pairwise.chi2_kernel + metrics.pairwise.distance_metrics metrics.pairwise.euclidean_distances - metrics.pairwise.manhattan_distances + metrics.pairwise.kernel_metrics metrics.pairwise.linear_kernel - metrics.pairwise.polynomial_kernel - metrics.pairwise.rbf_kernel - metrics.pairwise.distance_metrics + metrics.pairwise.manhattan_distances metrics.pairwise.pairwise_distances - metrics.pairwise.kernel_metrics metrics.pairwise.pairwise_kernels + metrics.pairwise.polynomial_kernel + metrics.pairwise.rbf_kernel + metrics.pairwise_distances + metrics.pairwise_distances_argmin + metrics.pairwise_distances_argmin_min .. _mixture_ref: @@ -711,18 +933,6 @@ Pairwise metrics multiclass.OneVsOneClassifier multiclass.OutputCodeClassifier -.. autosummary:: - :toctree: generated - :template: function.rst - - multiclass.fit_ovr - multiclass.predict_ovr - multiclass.fit_ovo - multiclass.predict_ovo - multiclass.fit_ecoc - multiclass.predict_ecoc - - .. _naive_bayes_ref: :mod:`sklearn.naive_bayes`: Naive Bayes @@ -767,8 +977,12 @@ Pairwise metrics neighbors.RadiusNeighborsClassifier neighbors.KNeighborsRegressor neighbors.RadiusNeighborsRegressor - neighbors.BallTree neighbors.NearestCentroid + neighbors.BallTree + neighbors.KDTree + neighbors.LSHForest + neighbors.DistanceMetric + neighbors.KernelDensity .. autosummary:: :toctree: generated/ @@ -777,17 +991,36 @@ Pairwise metrics neighbors.kneighbors_graph neighbors.radius_neighbors_graph +.. _neural_network_ref: -.. _pls_ref: +:mod:`sklearn.neural_network`: Neural network models +===================================================== -:mod:`sklearn.pls`: Partial Least Squares -========================================= +.. automodule:: sklearn.neural_network + :no-members: + :no-inherited-members: + +**User guide:** See the :ref:`neural_network` section for further details. + +.. currentmodule:: sklearn + +.. autosummary:: + :toctree: generated/ + :template: class.rst -.. automodule:: sklearn.pls + neural_network.BernoulliRBM + + +.. _calibration_ref: + +:mod:`sklearn.calibration`: Probability Calibration +=================================================== + +.. automodule:: sklearn.calibration :no-members: :no-inherited-members: -**User guide:** See the :ref:`pls` section for further details. +**User guide:** See the :ref:`calibration` section for further details. .. currentmodule:: sklearn @@ -795,10 +1028,37 @@ Pairwise metrics :toctree: generated/ :template: class.rst - pls.PLSRegression - pls.PLSCanonical - pls.CCA - pls.PLSSVD + calibration.CalibratedClassifierCV + + +.. autosummary:: + :toctree: generated/ + :template: function.rst + + calibration.calibration_curve + + +.. _cross_decomposition_ref: + +:mod:`sklearn.cross_decomposition`: Cross decomposition +======================================================= + +.. automodule:: sklearn.cross_decomposition + :no-members: + :no-inherited-members: + +**User guide:** See the :ref:`cross_decomposition` section for further details. + +.. currentmodule:: sklearn + +.. autosummary:: + :toctree: generated/ + :template: class.rst + + cross_decomposition.PLSRegression + cross_decomposition.PLSCanonical + cross_decomposition.CCA + cross_decomposition.PLSSVD .. _pipeline_ref: @@ -817,6 +1077,14 @@ Pairwise metrics :template: class.rst pipeline.Pipeline + pipeline.FeatureUnion + +.. autosummary:: + :toctree: generated/ + :template: function.rst + + pipeline.make_pipeline + pipeline.make_union .. _preprocessing_ref: @@ -837,20 +1105,26 @@ Pairwise metrics :template: class.rst preprocessing.Binarizer + preprocessing.Imputer preprocessing.KernelCenterer preprocessing.LabelBinarizer preprocessing.LabelEncoder + preprocessing.MultiLabelBinarizer preprocessing.MinMaxScaler preprocessing.Normalizer + preprocessing.OneHotEncoder preprocessing.StandardScaler + preprocessing.PolynomialFeatures .. autosummary:: :toctree: generated/ :template: function.rst - preprocessing.scale - preprocessing.normalize + preprocessing.add_dummy_feature preprocessing.binarize + preprocessing.label_binarize + preprocessing.normalize + preprocessing.scale :mod:`sklearn.qda`: Quadratic Discriminant Analysis @@ -870,6 +1144,54 @@ Pairwise metrics qda.QDA +.. _random_projection_ref: + +:mod:`sklearn.random_projection`: Random projection +=================================================== + +.. automodule:: sklearn.random_projection + :no-members: + :no-inherited-members: + +**User guide:** See the :ref:`random_projection` section for further details. + +.. currentmodule:: sklearn + +.. autosummary:: + :toctree: generated/ + :template: class.rst + + random_projection.GaussianRandomProjection + random_projection.SparseRandomProjection + +.. autosummary:: + :toctree: generated/ + :template: function.rst + + random_projection.johnson_lindenstrauss_min_dim + + +.. _semi_supervised_ref: + +:mod:`sklearn.semi_supervised` Semi-Supervised Learning +======================================================== + +.. automodule:: sklearn.semi_supervised + :no-members: + :no-inherited-members: + +**User guide:** See the :ref:`semi_supervised` section for further details. + +.. currentmodule:: sklearn + +.. autosummary:: + :toctree: generated/ + :template: class.rst + + semi_supervised.LabelPropagation + semi_supervised.LabelSpreading + + .. _svm_ref: :mod:`sklearn.svm`: Support Vector Machines @@ -894,6 +1216,7 @@ Estimators svm.LinearSVC svm.NuSVC svm.SVR + svm.LinearSVR svm.NuSVR svm.OneClassSVM diff --git a/doc/modules/clustering.rst b/doc/modules/clustering.rst index 585ffba6af5ee..bac313d87a5c5 100644 --- a/doc/modules/clustering.rst +++ b/doc/modules/clustering.rst @@ -8,10 +8,10 @@ Clustering unlabeled data can be performed with the module :mod:`sklearn.cluster`. Each clustering algorithm comes in two variants: a class, that implements -the `fit` method to learn the clusters on train data, and a function, +the ``fit`` method to learn the clusters on train data, and a function, that, given train data, returns an array of integer labels corresponding to the different clusters. For the class, the labels over the training -data can be found in the `labels_` attribute. +data can be found in the ``labels_`` attribute. .. currentmodule:: sklearn.cluster @@ -33,7 +33,7 @@ data can be found in the `labels_` attribute. Overview of clustering methods =============================== -.. figure:: ../auto_examples/cluster/images/plot_cluster_comparison_1.png +.. figure:: ../auto_examples/cluster/images/plot_cluster_comparison_001.png :target: ../auto_examples/cluster/plot_cluster_comparison.html :align: center :scale: 50 @@ -53,40 +53,47 @@ Overview of clustering methods * - :ref:`K-Means ` - number of clusters - - Very large `n_samples`, medium `n_clusters` with + - Very large ``n_samples``, medium ``n_clusters`` with :ref:`MiniBatch code ` - - General-purpose, even cluster size, flat geometry, not too many clusters - - Distances between points + - General-purpose, even cluster size, flat geometry, not too many clusters + - Distances between points * - :ref:`Affinity propagation ` - - damping, sample preference + - damping, sample preference - Not scalable with n_samples - Many clusters, uneven cluster size, non-flat geometry - Graph distance (e.g. nearest-neighbor graph) * - :ref:`Mean-shift ` - - bandwidth - - Not scalable with n_samples + - bandwidth + - Not scalable with ``n_samples`` - Many clusters, uneven cluster size, non-flat geometry - - Distances between points + - Distances between points * - :ref:`Spectral clustering ` - number of clusters - - Medium `n_samples`, small `n_clusters` + - Medium ``n_samples``, small ``n_clusters`` - Few clusters, even cluster size, non-flat geometry - Graph distance (e.g. nearest-neighbor graph) - * - :ref:`Hierarchical clustering ` + * - :ref:`Ward hierarchical clustering ` - number of clusters - - Large `n_samples` and `n_clusters` + - Large ``n_samples`` and ``n_clusters`` - Many clusters, possibly connectivity constraints - - Distances between points + - Distances between points + + * - :ref:`Agglomerative clustering ` + - number of clusters, linkage type, distance + - Large ``n_samples`` and ``n_clusters`` + - Many clusters, possibly connectivity constraints, non Euclidean + distances + - Any pairwise distance * - :ref:`DBSCAN ` - neighborhood size - - Very large `n_samples`, medium `n_clusters` + - Very large ``n_samples``, medium ``n_clusters`` - Non-flat geometry, uneven cluster sizes - - Distances between nearest points + - Distances between nearest points * - :ref:`Gaussian mixtures ` - many @@ -94,6 +101,12 @@ Overview of clustering methods - Flat geometry, good for density estimation - Mahalanobis distances to centers + * - :ref:`Birch` + - branching factor, threshold, optional global clusterer. + - Large ``n_clusters`` and ``n_samples`` + - Large dataset, outlier removal, data reduction. + - Euclidean distance between points + Non-flat geometry clustering is useful when the clusters have a specific shape, i.e. a non-flat manifold, and the standard euclidean distance is not the right metric. This case arises in the two top rows of the figure @@ -111,25 +124,89 @@ K-means The :class:`KMeans` algorithm clusters data by trying to separate samples in n groups of equal variance, minimizing a criterion known as the -'inertia' of the groups. This algorithm requires the number of cluster to -be specified. It scales well to large number of samples, however its -results may be dependent on an initialisation. As a result, the computation is -often done several times, with different initialisation of the centroids. - -K-means is often referred to as Lloyd's algorithm. After initialization, -k-means consists of looping between two major steps. First the Voronoi diagram -of the points is calculated using the current centroids. Each segment in the +`inertia ` or within-cluster sum-of-squares. +This algorithm requires the number of clusters to be specified. +It scales well to large number of samples and has been used +across a large range of application areas in many different fields. + +The k-means algorithm divides a set of :math:`N` samples :math:`X` +into :math:`K` disjoint clusters :math:`C`, +each described by the mean :math:`\mu_j` of the samples in the cluster. +The means are commonly called the cluster "centroids"; +note that they are not, in general, points from :math:`X`, +although they live in the same space. +The K-means algorithm aims to choose centroids +that minimise the *inertia*, or within-cluster sum of squared criterion: + +.. math:: \sum_{i=0}^{n}\min_{\mu_j \in C}(||x_j - \mu_i||^2) + +Inertia, or the within-cluster sum of squares criterion, +can be recognized as a measure of how internally coherent clusters are. +It suffers from various drawbacks: + +- Inertia makes the assumption that clusters are convex and isotropic, + which is not always the case. It responds poorly to elongated clusters, + or manifolds with irregular shapes. + +- Inertia is not a normalized metric: we just know that lower values are + better and zero is optimal. But in very high-dimensional spaces, Euclidean + distances tend to become inflated + (this is an instance of the so-called "curse of dimensionality"). + Running a dimensionality reduction algorithm such as `PCA ` + prior to k-means clustering can alleviate this problem + and speed up the computations. + +K-means is often referred to as Lloyd's algorithm. In basic terms, the +algorithm has three steps. The first step chooses the initial centroids, with +the most basic method being to choose :math:`k` samples from the dataset +:math:`X`. After initialization, K-means consists of looping between the +two other steps. The first step assigns each sample to its nearest centroid. +The second step creates new centroids by taking the mean value of all of the +samples assigned to each previous centroid. The difference between the old +and the new centroids are computed and the algorithm repeats these last two +steps until this value is less than a threshold. In other words, it repeats +until the centroids do not move significantly. + +.. image:: ../auto_examples/cluster/images/plot_kmeans_digits_001.png + :target: ../auto_examples/cluster/plot_kmeans_digits.html + :align: right + :scale: 35 + +K-means is equivalent to the expectation-maximization algorithm +with a small, all-equal, diagonal covariance matrix. + +The algorithm can also be understood through the concept of `Voronoi diagrams +`_. First the Voronoi diagram of +the points is calculated using the current centroids. Each segment in the Voronoi diagram becomes a separate cluster. Secondly, the centroids are updated to the mean of each segment. The algorithm then repeats this until a stopping -criteria is fulfilled. Usually, as in this implementation, the algorithm -stops when the relative increment in the results between iterations is less than -the given tolerance value. +criterion is fulfilled. Usually, the algorithm stops when the relative decrease +in the objective function between iterations is less than the given tolerance +value. This is not the case in this implementation: iteration stops when +centroids move less than the tolerance. + +Given enough time, K-means will always converge, however this may be to a local +minimum. This is highly dependent on the initialization of the centroids. +As a result, the computation is often done several times, with different +initializations of the centroids. One method to help address this issue is the +k-means++ initialization scheme, which has been implemented in scikit-learn +(use the ``init='kmeans++'`` parameter). This initializes the centroids to be +(generally) distant from each other, leading to provably better results than +random initialization, as shown in the reference. A parameter can be given to allow K-means to be run in parallel, called -`n_jobs`. Giving this parameter a positive value uses that many processors -(default=1). A value of -1 uses all processors, with -2 using one less, and so -on. Parallelization generally speeds up computation at the cost of memory (in -this case, multiple copies of centroids need to be stored, one for each job). +``n_jobs``. Giving this parameter a positive value uses that many processors +(default: 1). A value of -1 uses all available processors, with -2 using one +less, and so on. Parallelization generally speeds up computation at the cost of +memory (in this case, multiple copies of centroids need to be stored, one for +each job). + +.. warning:: + + The parallel version of K-Means is broken on OS X when numpy uses the + Accelerate Framework. This is expected behavior: Accelerate can be called + after a fork but you need to execv the subprocess with the Python binary + (which multiprocessing does not do under posix). K-means can be used for vector quantization. This is achieved using the transform method of a trained model of :class:`KMeans`. @@ -138,6 +215,13 @@ transform method of a trained model of :class:`KMeans`. * :ref:`example_cluster_plot_kmeans_digits.py`: Clustering handwritten digits +.. topic:: References: + + * `"k-means++: The advantages of careful seeding" + `_ + Arthur, David, and Sergei Vassilvitskii, + *Proceedings of the eighteenth annual ACM-SIAM symposium on Discrete + algorithms*, Society for Industrial and Applied Mathematics (2007) .. _mini_batch_kmeans: @@ -145,14 +229,29 @@ Mini Batch K-Means ------------------ The :class:`MiniBatchKMeans` is a variant of the :class:`KMeans` algorithm -using mini-batches, random subset of the dataset, to compute the centroids. - -Although the :class:`MiniBatchKMeans` converge faster than the KMeans -version, the quality of the results, measured by the inertia, the sum of -the distance of each points to the nearest centroid, is not as good as -the :class:`KMeans` algorithm. - -.. figure:: ../auto_examples/cluster/images/plot_mini_batch_kmeans_1.png +which uses mini-batches to reduce the computation time, while still attempting +to optimise the same objective function. Mini-batches are subsets of the input +data, randomly sampled in each training iteration. These mini-batches +drastically reduce the amount of computation required to converge to a local +solution. In contrast to other algorithms that reduce the convergence time of +k-means, mini-batch k-means produces results that are generally only slightly +worse than the standard algorithm. + +The algorithm iterates between two major steps, similar to vanilla k-means. +In the first step, :math:`b` samples are drawn randomly from the dataset, to form +a mini-batch. These are then assigned to the nearest centroid. In the second +step, the centroids are updated. In contrast to k-means, this is done on a +per-sample basis. For each sample in the mini-batch, the assigned centroid +is updated by taking the streaming average of the sample and all previous +samples assigned to that centroid. This has the effect of decreasing the +rate of change for a centroid over time. These steps are performed until +convergence or a predetermined number of iterations is reached. + +:class:`MiniBatchKMeans` converges faster than :class:`KMeans`, but the quality +of the results is reduced. In practice this difference in quality can be quite +small, as shown in the example and cited reference. + +.. figure:: ../auto_examples/cluster/images/plot_mini_batch_kmeans_001.png :target: ../auto_examples/cluster/plot_mini_batch_kmeans.html :align: center :scale: 100 @@ -163,9 +262,11 @@ the :class:`KMeans` algorithm. * :ref:`example_cluster_plot_mini_batch_kmeans.py`: Comparison of KMeans and MiniBatchKMeans - * :ref:`example_document_clustering.py`: Document clustering using sparse + * :ref:`example_text_document_clustering.py`: Document clustering using sparse MiniBatchKMeans + * :ref:`example_cluster_plot_dict_face_patches.py` + .. topic:: References: @@ -176,18 +277,37 @@ the :class:`KMeans` algorithm. .. _affinity_propagation: -Affinity propagation +Affinity Propagation ==================== -:class:`AffinityPropagation` clusters data by diffusion in the similarity -matrix. This algorithm automatically sets its numbers of cluster. It -will have difficulties scaling to thousands of samples. +:class:`AffinityPropagation` creates clusters by sending messages between +pairs of samples until convergence. A dataset is then described using a small +number of exemplars, which are identified as those most representative of other +samples. The messages sent between pairs represent the suitability for one +sample to be the exemplar of the other, which is updated in response to the +values from other pairs. This updating happens iteratively until convergence, +at which point the final exemplars are chosen, and hence the final clustering +is given. -.. figure:: ../auto_examples/cluster/images/plot_affinity_propagation_1.png +.. figure:: ../auto_examples/cluster/images/plot_affinity_propagation_001.png :target: ../auto_examples/cluster/plot_affinity_propagation.html :align: center :scale: 50 + +Affinity Propagation can be interesting as it chooses the number of +clusters based on the data provided. For this purpose, the two important +parameters are the *preference*, which controls how many exemplars are +used, and the *damping factor*. + +The main drawback of Affinity Propagation is its complexity. The +algorithm has a time complexity of the order :math:`O(N^2 T)`, where :math:`N` +is the number of samples and :math:`T` is the number of iterations until +convergence. Further, the memory complexity is of the order +:math:`O(N^2)` if a dense similarity matrix is used, but reducible if a +sparse similarity matrix is used. This makes Affinity Propagation most +appropriate for small to medium sized datasets. + .. topic:: Examples: * :ref:`example_cluster_plot_affinity_propagation.py`: Affinity @@ -196,19 +316,81 @@ will have difficulties scaling to thousands of samples. * :ref:`example_applications_plot_stock_market.py` Affinity Propagation on Financial time series to find groups of companies +**Algorithm description:** +The messages sent between points belong to one of two categories. The first is +the responsibility :math:`r(i, k)`, +which is the accumulated evidence that sample :math:`k` +should be the exemplar for sample :math:`i`. +The second is the availability :math:`a(i, k)` +which is the accumulated evidence that sample :math:`i` +should choose sample :math:`k` to be its exemplar, +and considers the values for all other samples that :math:`k` should +be an exemplar. In this way, exemplars are chosen by samples if they are (1) +similar enough to many samples and (2) chosen by many samples to be +representative of themselves. + +More formally, the responsibility of a sample :math:`k` +to be the exemplar of sample :math:`i` is given by: + +.. math:: + + r(i, k) \leftarrow s(i, k) - max [ a(i, \acute{k}) + s(i, \acute{k}) \forall \acute{k} \neq k ] + +Where :math:`s(i, k)` is the similarity between samples :math:`i` and :math:`k`. +The availability of sample :math:`k` +to be the exemplar of sample :math:`i` is given by: + +.. math:: + + a(i, k) \leftarrow min [0, r(k, k) + \sum_{\acute{i}~s.t.~\acute{i} \notin \{i, k\}}{r(\acute{i}, k)}] + +To begin with, all values for :math:`r` and :math:`a` are set to zero, +and the calculation of each iterates until convergence. .. _mean_shift: Mean Shift ========== +:class:`MeanShift` clustering aims to discover *blobs* in a smooth density of +samples. It is a centroid based algorithm, which works by updating candidates +for centroids to be the mean of the points within a given region. These +candidates are then filtered in a +post-processing stage to eliminate near-duplicates to form the final set of +centroids. + +Given a candidate centroid :math:`x_i` for iteration :math:`t`, the candidate +is updated according to the following equation: + +.. math:: + + x_i^{t+1} = x_i^t + m(x_i^t) + +Where :math:`N(x_i)` is the neighborhood of samples within a given distance +around :math:`x_i` and :math:`m` is the *mean shift* vector that is computed +for each centroid that +points towards a region of the maximum increase in the density of points. This +is computed using the following equation, effectively updating a centroid to be +the mean of the samples within its neighborhood: -:class:`MeanShift` clusters data by estimating *blobs* in a smooth -density of points matrix. This algorithm automatically sets its numbers -of cluster. It will have difficulties scaling to thousands of samples. -The utility function :func:`estimate_bandwidth` can be used to guess -the optimal bandwidth for :class:`MeanShift` from the data. +.. math:: -.. figure:: ../auto_examples/cluster/images/plot_mean_shift_1.png + m(x_i) = \frac{\sum_{x_j \in N(x_i)}K(x_j - x_i)x_j}{\sum_{x_j \in N(x_i)}K(x_j - x_i)} + +The algorithm automatically sets the number of clusters, instead of relying on a +parameter ``bandwidth``, which dictates the size of the region to search through. +This parameter can be set manually, but can be estimated using the provided +``estimate_bandwidth`` function, which is called if the bandwidth is not set. + +The algorithm is not highly scalable, as it requires multiple nearest neighbor +searches during the execution of the algorithm. The algorithm is guaranteed to +converge, however the algorithm will stop iterating when the change in centroids +is small. + +Labelling a new sample is performed by finding the nearest centroid for a +given sample. + + +.. figure:: ../auto_examples/cluster/images/plot_mean_shift_001.png :target: ../auto_examples/cluster/plot_mean_shift.html :align: center :scale: 50 @@ -219,6 +401,13 @@ the optimal bandwidth for :class:`MeanShift` from the data. * :ref:`example_cluster_plot_mean_shift.py`: Mean Shift clustering on a synthetic 2D datasets with 3 classes. +.. topic:: References: + + * `"Mean shift: A robust approach toward feature space analysis." + `_ + D. Comaniciu, & P. Meer *IEEE Transactions on Pattern Analysis and Machine Intelligence* (2002) + + .. _spectral_clustering: Spectral clustering @@ -227,25 +416,25 @@ Spectral clustering :class:`SpectralClustering` does a low-dimension embedding of the affinity matrix between samples, followed by a KMeans in the low dimensional space. It is especially efficient if the affinity matrix is -sparse and the `pyamg `_ module is -installed. SpectralClustering requires the number of clusters to be -specified. It works well for a small number of clusters but is not -advised when using many clusters. +sparse and the `pyamg `_ module is installed. +SpectralClustering requires the number of clusters to be specified. It +works well for a small number of clusters but is not advised when using +many clusters. For two clusters, it solves a convex relaxation of the `normalised cuts `_ problem on the similarity graph: cutting the graph in two so that the weight of the -edges cut is small compared to the weights in of edges inside each +edges cut is small compared to the weights of the edges inside each cluster. This criteria is especially interesting when working on images: graph vertices are pixels, and edges of the similarity graph are a function of the gradient of the image. -.. |noisy_img| image:: ../auto_examples/cluster/images/plot_segmentation_toy_1.png +.. |noisy_img| image:: ../auto_examples/cluster/images/plot_segmentation_toy_001.png :target: ../auto_examples/cluster/plot_segmentation_toy.html :scale: 50 -.. |segmented_img| image:: ../auto_examples/cluster/images/plot_segmentation_toy_2.png +.. |segmented_img| image:: ../auto_examples/cluster/images/plot_segmentation_toy_002.png :target: ../auto_examples/cluster/plot_segmentation_toy.html :scale: 50 @@ -272,6 +461,33 @@ function of the gradient of the image. * :ref:`example_cluster_plot_lena_segmentation.py`: Spectral clustering to split the image of lena in regions. +.. |lena_kmeans| image:: ../auto_examples/cluster/images/plot_lena_segmentation_001.png + :target: ../auto_examples/cluster/plot_lena_segmentation.html + :scale: 65 + +.. |lena_discretize| image:: ../auto_examples/cluster/images/plot_lena_segmentation_002.png + :target: ../auto_examples/cluster/plot_lena_segmentation.html + :scale: 65 + +Different label assignment strategies +--------------------------------------- + +Different label assignment strategies can be used, corresponding to the +``assign_labels`` parameter of :class:`SpectralClustering`. +The ``"kmeans"`` strategy can match finer details of the data, but it can be +more unstable. In particular, unless you control the ``random_state``, it +may not be reproducible from run-to-run, as it depends on a random +initialization. On the other hand, the ``"discretize"`` strategy is 100% +reproducible, but it tends to create parcels of fairly even and +geometrical shape. + +===================================== ===================================== + ``assign_labels="kmeans"`` ``assign_labels="discretize"`` +===================================== ===================================== +|lena_kmeans| |lena_discretize| +===================================== ===================================== + + .. topic:: References: * `"A Tutorial on Spectral Clustering" @@ -297,56 +513,104 @@ Hierarchical clustering ======================= Hierarchical clustering is a general family of clustering algorithms that -build nested clusters by merging them successively. This hierarchy of -clusters represented as a tree (or dendrogram). The root of the tree is -the unique cluster that gathers all the samples, the leaves being the +build nested clusters by merging or splitting them successively. This +hierarchy of clusters is represented as a tree (or dendrogram). The root of the +tree is the unique cluster that gathers all the samples, the leaves being the clusters with only one sample. See the `Wikipedia page -`_ for more -details. +`_ for more details. + +The :class:`AgglomerativeClustering` object performs a hierarchical clustering +using a bottom up approach: each observation starts in its own cluster, and +clusters are successively merged together. The linkage criteria determines the +metric used for the merge strategy: + +- **Ward** minimizes the sum of squared differences within all clusters. It is a + variance-minimizing approach and in this sense is similar to the k-means + objective function but tackled with an agglomerative hierarchical + approach. +- **Maximum** or **complete linkage** minimizes the maximum distance between + observations of pairs of clusters. +- **Average linkage** minimizes the average of the distances between all + observations of pairs of clusters. + +:class:`AgglomerativeClustering` can also scale to large number of samples +when it is used jointly with a connectivity matrix, but is computationally +expensive when no connectivity constraints are added between samples: it +considers at each step all the possible merges. + +.. topic:: :class:`FeatureAgglomeration` + + The :class:`FeatureAgglomeration` uses agglomerative clustering to + group together features that look very similar, thus decreasing the + number of features. It is a dimensionality reduction tool, see + :ref:`data_reduction`. + +Different linkage type: Ward, complete and average linkage +----------------------------------------------------------- + +:class:`AgglomerativeClustering` supports Ward, average, and complete +linkage strategies. + +.. image:: ../auto_examples/cluster/images/plot_digits_linkage_001.png + :target: ../auto_examples/cluster/plot_digits_linkage.html + :scale: 43 -The :class:`Ward` object performs a hierarchical clustering based on -the Ward algorithm, that is a variance-minimizing approach. At each -step, it minimizes the sum of squared differences within all clusters -(inertia criterion). +.. image:: ../auto_examples/cluster/images/plot_digits_linkage_002.png + :target: ../auto_examples/cluster/plot_digits_linkage.html + :scale: 43 -This algorithm can scale to large number of samples when it is used jointly -with an connectivity matrix, but can be computationally expensive when no -connectivity constraints are added between samples: it considers at each step -all the possible merges. +.. image:: ../auto_examples/cluster/images/plot_digits_linkage_003.png + :target: ../auto_examples/cluster/plot_digits_linkage.html + :scale: 43 + + +Agglomerative cluster has a "rich get richer" behavior that leads to +uneven cluster sizes. In this regard, complete linkage is the worst +strategy, and Ward gives the most regular sizes. However, the affinity +(or distance used in clustering) cannot be varied with Ward, thus for non +Euclidean metrics, average linkage is a good alternative. + +.. topic:: Examples: + + * :ref:`example_cluster_plot_digits_linkage.py`: exploration of the + different linkage strategies in a real dataset. Adding connectivity constraints ------------------------------- -An interesting aspect of the :class:`Ward` object is that connectivity -constraints can be added to this algorithm (only adjacent clusters can be -merged together), through an connectivity matrix that defines for each -sample the neighboring samples following a given structure of the data. For -instance, in the swiss-roll example below, the connectivity constraints -forbid the merging of points that are not adjacent on the swiss roll, and -thus avoid forming clusters that extend across overlapping folds of the -roll. +An interesting aspect of :class:`AgglomerativeClustering` is that +connectivity constraints can be added to this algorithm (only adjacent +clusters can be merged together), through a connectivity matrix that defines +for each sample the neighboring samples following a given structure of the +data. For instance, in the swiss-roll example below, the connectivity +constraints forbid the merging of points that are not adjacent on the swiss +roll, and thus avoid forming clusters that extend across overlapping folds of +the roll. -.. |unstructured| image:: ../auto_examples/cluster/images/plot_ward_structured_vs_unstructured_1.png +.. |unstructured| image:: ../auto_examples/cluster/images/plot_ward_structured_vs_unstructured_001.png :target: ../auto_examples/cluster/plot_ward_structured_vs_unstructured.html :scale: 49 -.. |structured| image:: ../auto_examples/cluster/images/plot_ward_structured_vs_unstructured_2.png +.. |structured| image:: ../auto_examples/cluster/images/plot_ward_structured_vs_unstructured_002.png :target: ../auto_examples/cluster/plot_ward_structured_vs_unstructured.html :scale: 49 .. centered:: |unstructured| |structured| +These constraint are useful to impose a certain local structure, but they +also make the algorithm faster, especially when the number of the samples +is high. The connectivity constraints are imposed via an connectivity matrix: a scipy sparse matrix that has elements only at the intersection of a row and a column with indices of the dataset that should be connected. This -matrix can be constructed from a-priori information, for instance if you -wish to cluster web pages, but only merging pages with a link pointing +matrix can be constructed from a-priori information: for instance, you +may wish to cluster web pages by only merging pages with a link pointing from one to another. It can also be learned from the data, for instance using :func:`sklearn.neighbors.kneighbors_graph` to restrict -merging to nearest neighbors as in the :ref:`swiss roll -` example, or +merging to nearest neighbors as in :ref:`this example +`, or using :func:`sklearn.feature_extraction.image.grid_to_graph` to enable only merging of neighboring pixels on an image, as in the :ref:`Lena ` example. @@ -364,24 +628,113 @@ enable only merging of neighboring pixels on an image, as in the Example of dimensionality reduction with feature agglomeration based on Ward hierarchical clustering. + * :ref:`example_cluster_plot_agglomerative_clustering.py` + +.. warning:: **Connectivity constraints with average and complete linkage** + + Connectivity constraints and complete or average linkage can enhance + the 'rich getting richer' aspect of agglomerative clustering, + particularly so if they are built with + :func:`sklearn.neighbors.kneighbors_graph`. In the limit of a small + number of clusters, they tend to give a few macroscopically occupied + clusters and almost empty ones. (see the discussion in + :ref:`example_cluster_plot_agglomerative_clustering.py`). + +.. image:: ../auto_examples/cluster/images/plot_agglomerative_clustering_001.png + :target: ../auto_examples/cluster/plot_agglomerative_clustering.html + :scale: 38 + +.. image:: ../auto_examples/cluster/images/plot_agglomerative_clustering_002.png + :target: ../auto_examples/cluster/plot_agglomerative_clustering.html + :scale: 38 + +.. image:: ../auto_examples/cluster/images/plot_agglomerative_clustering_003.png + :target: ../auto_examples/cluster/plot_agglomerative_clustering.html + :scale: 38 + +.. image:: ../auto_examples/cluster/images/plot_agglomerative_clustering_004.png + :target: ../auto_examples/cluster/plot_agglomerative_clustering.html + :scale: 38 + + +Varying the metric +------------------- + +Average and complete linkage can be used with a variety of distances (or +affinities), in particular Euclidean distance (*l2*), Manhattan distance +(or Cityblock, or *l1*), cosine distance, or any precomputed affinity +matrix. + +* *l1* distance is often good for sparse features, or sparse noise: ie + many of the features are zero, as in text mining using occurences of + rare words. + +* *cosine* distance is interesting because it is invariant to global + scalings of the signal. + +The guidelines for choosing a metric is to use one that maximizes the +distance between samples in different classes, and minimizes that within +each class. + +.. image:: ../auto_examples/cluster/images/plot_agglomerative_clustering_metrics_005.png + :target: ../auto_examples/cluster/plot_agglomerative_clustering_metrics.html + :scale: 32 + +.. image:: ../auto_examples/cluster/images/plot_agglomerative_clustering_metrics_006.png + :target: ../auto_examples/cluster/plot_agglomerative_clustering_metrics.html + :scale: 32 + +.. image:: ../auto_examples/cluster/images/plot_agglomerative_clustering_metrics_007.png + :target: ../auto_examples/cluster/plot_agglomerative_clustering_metrics.html + :scale: 32 + +.. topic:: Examples: + + * :ref:`example_cluster_plot_agglomerative_clustering_metrics.py` + + .. _dbscan: DBSCAN ====== -The :class:`DBSCAN` algorithm clusters data by finding core points which have -many neighbours within a given radius. After a core point is found, the cluster -is expanded by adding its neighbours to the current cluster and recursively -checking if any are core points. Formally, a point is considered a core point -if it has more than min_points points which are of a similarity greater than -the given threshold eps. This is shown in the figure below, where the color -indicates cluster membership and large circles indicate core points found by -the algorithm. Moreover, the algorithm can detect outliers, indicated by black -points below. The outliers are defined as points which do not belong to -any current cluster and do not have enough close neighbours to start a -new cluster. - -.. |dbscan_results| image:: ../auto_examples/cluster/images/plot_dbscan_1.png +The :class:`DBSCAN` algorithm views clusters as areas of high density +separated by areas of low density. Due to this rather generic view, clusters +found by DBSCAN can be any shape, as opposed to k-means which assumes that +clusters are convex shaped. The central component to the DBSCAN is the concept +of *core samples*, which are samples that are in areas of high density. A +cluster is therefore a set of core samples, each close to each other +(measured by some distance measure) +and a set of non-core samples that are close to a core sample (but are not +themselves core samples). There are two parameters to the algorithm, +``min_samples`` and ``eps``, +which define formally what we mean when we say *dense*. +Higher ``min_samples`` or lower ``eps`` +indicate higher density necessary to form a cluster. + +More formally, we define a core sample as being a sample in the dataset such +that there exist ``min_samples`` other samples within a distance of +``eps``, which are defined as *neighbors* of the core sample. This tells +us that the core sample is in a dense area of the vector space. A cluster +is a set of core samples, that can be built by recursively by taking a core +sample, finding all of its neighbors that are core samples, finding all of +*their* neighbors that are core samples, and so on. A cluster also has a +set of non-core samples, which are samples that are neighbors of a core sample +in the cluster but are not themselves core samples. Intuitively, these samples +are on the fringes of a cluster. + +Any core sample is part of a cluster, by definition. Further, any cluster has +at least ``min_samples`` points in it, following the definition of a core +sample. For any sample that is not a core sample, and does have a +distance higher than ``eps`` to any core sample, it is considered an outlier by +the algorithm. + +In the figure below, the color indicates cluster membership, with large circles +indicating core samples found by the algorithm. Smaller circles are non-core +samples that are still part of a cluster. Moreover, the outliers are indicated +by black points below. + +.. |dbscan_results| image:: ../auto_examples/cluster/images/plot_dbscan_001.png :target: ../auto_examples/cluster/plot_dbscan.html :scale: 50 @@ -389,7 +742,28 @@ new cluster. .. topic:: Examples: - * :ref:`example_cluster_plot_dbscan.py`: Clustering synthetic data with DBSCAN + * :ref:`example_cluster_plot_dbscan.py` + +.. topic:: Implementation + + The algorithm is non-deterministic, but the core samples will + always belong to the same clusters (although the labels may be + different). The non-determinism comes from deciding to which cluster a + non-core sample belongs. A non-core sample can have a distance lower + than ``eps`` to two core samples in different clusters. By the + triangular inequality, those two core samples must be more distant than + ``eps`` from each other, or they would be in the same cluster. The non-core + sample is assigned to whichever cluster is generated first, where + the order is determined randomly. Other than the ordering of + the dataset, the algorithm is deterministic, making the results relatively + stable between runs on the same data. + + The current implementation uses ball trees and kd-trees + to determine the neighborhood of points, + which avoids calculating the full distance matrix + (as was done in scikit-learn versions before 0.14). + The possibility to use custom metrics is retained; + for details, see :class:`NearestNeighbors`. .. topic:: References: @@ -399,6 +773,96 @@ new cluster. In Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226–231. 1996 +.. _birch: + +Birch +===== + +The :class:`Birch` builds a tree called the Characteristic Feature Tree (CFT) +for the given data. The data is essentially lossy compressed to a set of +Characteristic Feature nodes (CF Nodes). The CF Nodes have a number of +subclusters called Characteristic Feature subclusters (CF Subclusters) +and these CF Subclusters located in the non-terminal CF Nodes +can have CF Nodes as children. + +The CF Subclusters hold the necessary information for clustering which prevents +the need to hold the entire input data in memory. This information includes: + +- Number of samples in a subcluster. +- Linear Sum - A n-dimensional vector holding the sum of all samples +- Squared Sum - Sum of the squared L2 norm of all samples. +- Centroids - To avoid recalculation linear sum / n_samples. +- Squared norm of the centroids. + +The Birch algorithm has two parameters, the threshold and the branching factor. +The branching factor limits the number of subclusters in a node and the +threshold limits the distance between the entering sample and the existing +subclusters. + +This algorithm can be viewed as an instance or data reduction method, +since it reduces the input data to a set of subclusters which are obtained directly +from the leaves of the CFT. This reduced data can be further processed by feeding +it into a global clusterer. This global clusterer can be set by ``n_clusters``. +If ``n_clusters`` is set to None, the subclusters from the leaves are directly +read off, otherwise a global clustering step labels these subclusters into global +clusters (labels) and the samples are mapped to the global label of the nearest subcluster. + +**Algorithm description:** + +- A new sample is inserted into the root of the CF Tree which is a CF Node. + It is then merged with the subcluster of the root, that has the smallest + radius after merging, constrained by the threshold and branching factor conditions. + If the subcluster has any child node, then this is done repeatedly till it reaches + a leaf. After finding the nearest subcluster in the leaf, the properties of this + subcluster and the parent subclusters are recursively updated. + +- If the radius of the subcluster obtained by merging the new sample and the + nearest subcluster is greater than the square of the threshold and if the + number of subclusters is greater than the branching factor, then a space is temporarily + allocated to this new sample. The two farthest subclusters are taken and + the subclusters are divided into two groups on the basis of the distance + between these subclusters. + +- If this split node has a parent subcluster and there is room + for a new subcluster, then the parent is split into two. If there is no room, + then this node is again split into two and the process is continued + recursively, till it reaches the root. + +**Birch or MiniBatchKMeans?** + + - Birch does not scale very well to high dimensional data. As a rule of thumb if + ``n_features`` is greater than twenty, it is generally better to use MiniBatchKMeans. + - If the number of instances of data needs to be reduced, or if one wants a + large number of subclusters either as a preprocessing step or otherwise, + Birch is more useful than MiniBatchKMeans. + + +**How to use partial_fit?** + +To avoid the computation of global clustering, for every call of ``partial_fit`` +the user is advised + + 1. To set ``n_clusters=None`` initially + 2. Train all data by multiple calls to partial_fit. + 3. Set ``n_clusters`` to a required value using + ``brc.set_params(n_clusters=n_clusters)``. + 4. Call ``partial_fit`` finally with no arguments, i.e ``brc.partial_fit()`` + which performs the global clustering. + +.. image:: ../auto_examples/cluster/images/plot_birch_vs_minibatchkmeans_001.png + :target: ../auto_examples/cluster/plot_birch_vs_minibatchkmeans.html + +.. topic:: References: + + * Tian Zhang, Raghu Ramakrishnan, Maron Livny + BIRCH: An efficient data clustering method for large databases. + http://www.cs.sfu.ca/CourseCentral/459/han/papers/zhang96.pdf + + * Roberto Perdisci + JBirch - Java implementation of BIRCH clustering algorithm + https://code.google.com/p/jbirch/ + + .. _clustering_evaluation: Clustering performance evaluation @@ -415,33 +879,6 @@ classes according to some similarity metric. .. currentmodule:: sklearn.metrics -Inertia -------- - -Presentation and usage -~~~~~~~~~~~~~~~~~~~~~~ - -TODO: factorize inertia computation out of kmeans and then write me! - - -Advantages -~~~~~~~~~~ - -- No need for the ground truth knowledge of the "real" classes. - -Drawbacks -~~~~~~~~~ - -- Inertia makes the assumption that clusters are convex and isotropic - which is not always the case especially of the clusters are manifolds - with weird shapes: for instance inertia is a useless metrics to evaluate - clustering algorithm that tries to identify nested circles on a 2D plane. - -- Inertia is not a normalized metrics: we just know that lower values are - better and bounded by zero. One potential solution would be to adjust - inertia for random clustering (assuming the number of ground truth classes - is known). - Adjusted Rand index ------------------- @@ -462,7 +899,7 @@ chance normalization**:: >>> metrics.adjusted_rand_score(labels_true, labels_pred) # doctest: +ELLIPSIS 0.24... -One can permute 0 and 1 in the predicted labels and rename `2` by `3` and get +One can permute 0 and 1 in the predicted labels, rename 2 to 3, and get the same score:: >>> labels_pred = [1, 1, 0, 0, 3, 3] @@ -585,7 +1022,7 @@ proposed more recently and is **normalized against chance**:: >>> metrics.adjusted_mutual_info_score(labels_true, labels_pred) # doctest: +ELLIPSIS 0.22504... -One can permute 0 and 1 in the predicted labels and rename `2` by `3` and get +One can permute 0 and 1 in the predicted labels, rename 2 to 3 and get the same score:: >>> labels_pred = [1, 1, 0, 0, 3, 3] @@ -659,32 +1096,30 @@ Drawbacks * :ref:`example_cluster_plot_adjusted_for_chance_measures.py`: Analysis of the impact of the dataset size on the value of clustering measures - for random assignments. This example also includes the Adjusted Rand + for random assignments. This example also includes the Adjusted Rand Index. Mathematical formulation ~~~~~~~~~~~~~~~~~~~~~~~~ -Assume two label assignments (of the same data), :math:`U` with :math:`R` -classes and :math:`V` with :math:`C` classes. The entropy of either is the -amount of uncertaintly for an array, and can be calculated as: -.. math:: H(U) = \sum_{i=1}^{|R|}P(i)\log(P(i)) +Assume two label assignments (of the same N objects), :math:`U` and :math:`V`. +Their entropy is the amount of uncertainty for a partition set, defined by: -Where P(i) is the number of instances in U that are in class :math:`R_i`. -Likewise, for :math:`V`: +.. math:: H(U) = \sum_{i=1}^{|U|}P(i)\log(P(i)) -.. math:: H(V) = \sum_{j=1}^{|C|}P'(j)\log(P'(j)) +where :math:`P(i) = |U_i| / N` is the probability that an object picked at +random from :math:`U` falls into class :math:`U_i`. Likewise for :math:`V`: -Where P'(j) is the number of instances in V that are in class :math:`C_j`. +.. math:: H(V) = \sum_{j=1}^{|V|}P'(j)\log(P'(j)) -The mutual information between :math:`U` and :math:`V` is -calculated by: +With :math:`P'(j) = |V_j| / N`. The mutual information (MI) between :math:`U` +and :math:`V` is calculated by: -.. math:: \text{MI}(U, V) = \sum_{i=1}^{|R|}\sum_{j=1}^{|C|}P(i, j)\log\left(\frac{P(i,j)}{P(i)P'(j)}\right) +.. math:: \text{MI}(U, V) = \sum_{i=1}^{|U|}\sum_{j=1}^{|V|}P(i, j)\log\left(\frac{P(i,j)}{P(i)P'(j)}\right) -Where P(i, j) is the number of instances with label :math:`R_i` -and also with label :math:`C_j`. +where :math:`P(i, j) = |U_i \cap V_j| / N` is the probability that an object +picked at random falls into both classes :math:`U_i` and :math:`V_j`. The normalized mutual information is defined as @@ -697,16 +1132,16 @@ between the label assignments. The expected value for the mutual information can be calculated using the following equation, from Vinh, Epps, and Bailey, (2009). In this equation, -:math:`a_i` is the number of instances with label :math:`U_i` and -:math:`b_j` is the number of instances with label :math:`V_j`. +:math:`a_i = |U_i|` (the number of elements in :math:`U_i`) and +:math:`b_j = |V_j|` (the number of elements in :math:`V_j`). -.. math:: E[\text{MI}(U,V)]=\sum_{i=1}^R \sum_{j=1}^C \sum_{n_{ij}=(a_i+b_j-N)^+ +.. math:: E[\text{MI}(U,V)]=\sum_{i=1}^|U| \sum_{j=1}^|V| \sum_{n_{ij}=(a_i+b_j-N)^+ }^{\min(a_i, b_j)} \frac{n_{ij}}{N}\log \left( \frac{ N.n_{ij}}{a_i b_j}\right) \frac{a_i!b_j!(N-a_i)!(N-b_j)!}{N!n_{ij}!(a_i-n_{ij})!(b_j-n_{ij})! (N-a_i-b_j+n_{ij})!} -Using the expected value, the adjusted mutual information can then be +Using the expected value, the adjusted mutual information can then be calculated using a similar form to that of the adjusted Rand index: .. math:: \text{AMI} = \frac{\text{MI} - E[\text{MI}]}{\max(H(U), H(V)) - E[\text{MI}]} @@ -717,7 +1152,7 @@ calculated using a similar form to that of the adjusted Rand index: knowledge reuse framework for combining multiple partitions". Journal of Machine Learning Research 3: 583–617. doi:10.1162/153244303321897735 - * Vinh, Epps, and Bailey, (2009). "Information theoretic measures + * Vinh, Epps, and Bailey, (2009). "Information theoretic measures for clusterings comparison". Proceedings of the 26th Annual International Conference on Machine Learning - ICML '09. doi:10.1145/1553374.1553511. ISBN 9781605585161. @@ -774,14 +1209,14 @@ Their harmonic mean called **V-measure** is computed by The V-measure is actually equivalent to the mutual information (NMI) discussed above normalized by the sum of the label entropies [B2011]_. -Homogeneity, completensess and V-measure can be computed at once using +Homogeneity, completeness and V-measure can be computed at once using :func:`homogeneity_completeness_v_measure` as follows:: >>> metrics.homogeneity_completeness_v_measure(labels_true, labels_pred) ... # doctest: +ELLIPSIS (0.66..., 0.42..., 0.51...) -The following clustering assignment is slighlty better, since it is +The following clustering assignment is slightly better, since it is homogeneous but not complete:: >>> labels_pred = [0, 0, 0, 1, 2, 2] @@ -807,7 +1242,7 @@ Advantages - Intuitive interpretation: clustering with bad V-measure can be **qualitatively analyzed in terms of homogeneity and completeness** - to better feel what 'kind' of mistakes is done by the assigmenent. + to better feel what 'kind' of mistakes is done by the assignment. - **No assumption is made on the cluster structure**: can be used to compare clustering algorithms such as k-means which assumes isotropic @@ -818,8 +1253,8 @@ Advantages Drawbacks ~~~~~~~~~ -- The previously introduced metrics are **not normalized w.r.t. random - labeling**: this means that depending on the number of samples, +- The previously introduced metrics are **not normalized with regards to + random labeling**: this means that depending on the number of samples, clusters and ground truth classes, a completely random labeling will not always yield the same values for homogeneity, completeness and hence v-measure. In particular **random labeling won't yield zero @@ -830,7 +1265,7 @@ Drawbacks smaller sample sizes or larger number of clusters it is safer to use an adjusted index such as the Adjusted Rand Index (ARI)**. -.. figure:: ../auto_examples/cluster/images/plot_adjusted_for_chance_measures_1.png +.. figure:: ../auto_examples/cluster/images/plot_adjusted_for_chance_measures_001.png :target: ../auto_examples/cluster/plot_adjusted_for_chance_measures.html :align: center :scale: 100 @@ -882,12 +1317,12 @@ mean of homogeneity and completeness**: .. topic:: References .. [RH2007] `V-Measure: A conditional entropy-based external cluster evaluation - measure `_ + measure `_ Andrew Rosenberg and Julia Hirschberg, 2007 .. [B2011] `Identication and Characterization of Events in Social Media `_, Hila - Becker, PhD Thesis. + Becker, PhD Thesis. .. _silhouette_coefficient: @@ -911,11 +1346,11 @@ of two scores: - **b**: The mean distance between a sample and all other points in the *next nearest cluster*. -The Silhoeutte Coefficient *s* for a single sample is then given as: +The Silhouette Coefficient *s* for a single sample is then given as: .. math:: s = \frac{b - a}{max(a, b)} -The Silhouette Coefficient for a set of samples is given as the mean of the +The Silhouette Coefficient for a set of samples is given as the mean of the Silhouette Coefficient for each sample. @@ -933,7 +1368,7 @@ cluster analysis. >>> from sklearn.cluster import KMeans >>> kmeans_model = KMeans(n_clusters=3, random_state=1).fit(X) >>> labels = kmeans_model.labels_ - >>> metrics.silhouette_score(X, labels, metric='euclidean') + >>> metrics.silhouette_score(X, labels, metric='euclidean') ... # doctest: +ELLIPSIS 0.55... diff --git a/doc/modules/computational_performance.rst b/doc/modules/computational_performance.rst new file mode 100644 index 0000000000000..cc5a792a47d57 --- /dev/null +++ b/doc/modules/computational_performance.rst @@ -0,0 +1,342 @@ +.. _computational_performance: + +========================= +Computational Performance +========================= + +For some applications the performance (mainly latency and throughput at +prediction time) of estimators is crucial. It may also be of interest to +consider the training throughput but this is often less important in a +production setup (where it often takes place offline). + +We will review here the orders of magnitude you can expect from a number of +scikit-learn estimators in different contexts and provide some tips and +tricks for overcoming performance bottlenecks. + +Prediction latency is measured as the elapsed time necessary to make a +prediction (e.g. in micro-seconds). Latency is often viewed as a distribution +and operations engineers often focus on the latency at a given percentile of +this distribution (e.g. the 90 percentile). + +Prediction throughput is defined as the number of predictions the software can +deliver in a given amount of time (e.g. in predictions per second). + +An important aspect of performance optimization is also that it can hurt +prediction accuracy. Indeed, simpler models (e.g. linear instead of +non-linear, or with fewer parameters) often run faster but are not always able +to take into account the same exact properties of the data as more complex ones. + +Prediction Latency +================== + +One of the most straight-forward concerns one may have when using/choosing a +machine learning toolkit is the latency at which predictions can be made in a +production environment. + +The main factors that influence the prediction latency are + 1. Number of features + 2. Input data representation and sparsity + 3. Model complexity + 4. Feature extraction + +A last major parameter is also the possibility to do predictions in bulk or +one-at-a-time mode. + +Bulk versus Atomic mode +----------------------- + +In general doing predictions in bulk (many instances at the same time) is +more efficient for a number of reasons (branching predictability, CPU cache, +linear algebra libraries optimizations etc.). Here we see on a setting +with few features that independently of estimator choice the bulk mode is +always faster, and for some of them by 1 to 2 orders of magnitude: + +.. |atomic_prediction_latency| image:: ../auto_examples/applications/images/plot_prediction_latency_001.png + :target: ../auto_examples/applications/plot_prediction_latency.html + :scale: 80 + +.. centered:: |atomic_prediction_latency| + +.. |bulk_prediction_latency| image:: ../auto_examples/applications/images/plot_prediction_latency_002.png + :target: ../auto_examples/applications/plot_prediction_latency.html + :scale: 80 + +.. centered:: |bulk_prediction_latency| + +To benchmark different estimators for your case you can simply change the +``n_features`` parameter in this example: +:ref:`example_applications_plot_prediction_latency.py`. This should give +you an estimate of the order of magnitude of the prediction latency. + +Influence of the Number of Features +----------------------------------- + +Obviously when the number of features increases so does the memory +consumption of each example. Indeed, for a matrix of :math:`M` instances +with :math:`N` features, the space complexity is in :math:`O(NM)`. +From a computing perspective it also means that the number of basic operations +(e.g., multiplications for vector-matrix products in linear models) increases +too. Here is a graph of the evolution of the prediction latency with the +number of features: + +.. |influence_of_n_features_on_latency| image:: ../auto_examples/applications/images/plot_prediction_latency_003.png + :target: ../auto_examples/applications/plot_prediction_latency.html + :scale: 80 + +.. centered:: |influence_of_n_features_on_latency| + +Overall you can expect the prediction time to increase at least linearly with +the number of features (non-linear cases can happen depending on the global +memory footprint and estimator). + +Influence of the Input Data Representation +------------------------------------------ + +Scipy provides sparse matrix datastructures which are optimized for storing +sparse data. The main feature of sparse formats is that you don't store zeros +so if your data is sparse then you use much less memory. A non-zero value in +a sparse (`CSR or CSC `_) +representation will only take on average one 32bit integer position + the 64 +bit floating point value + an additional 32bit per row or column in the matrix. +Using sparse input on a dense (or sparse) linear model can speedup prediction +by quite a bit as only the non zero valued features impact the dot product +and thus the model predictions. Hence if you have 100 non zeros in 1e6 +dimensional space, you only need 100 multiply and add operation instead of 1e6. + +Calculation over a dense representation, however, may leverage highly optimised +vector operations and multithreading in BLAS, and tends to result in fewer CPU +cache misses. So the sparsity should typically be quite high (10% non-zeros +max, to be checked depending on the hardware) for the sparse input +representation to be faster than the dense input representation on a machine +with many CPUs and an optimized BLAS implementation. + +Here is sample code to test the sparsity of your input:: + + def sparsity_ratio(X): + return 1.0 - np.count_nonzero(X) / float(X.shape[0] * X.shape[1]) + print("input sparsity ratio:", sparsity_ratio(X)) + +As a rule of thumb you can consider that if the sparsity ratio is greater +than 90% you can probably benefit from sparse formats. Check Scipy's sparse +matrix formats `documentation `_ +for more information on how to build (or convert your data to) sparse matrix +formats. Most of the time the ``CSR`` and ``CSC`` formats work best. + +Influence of the Model Complexity +--------------------------------- + +Generally speaking, when model complexity increases, predictive power and +latency are supposed to increase. Increasing predictive power is usually +interesting, but for many applications we would better not increase +prediction latency too much. We will now review this idea for different +families of supervised models. + +For :mod:`sklearn.linear_model` (e.g. Lasso, ElasticNet, +SGDClassifier/Regressor, Ridge & RidgeClassifier, +PassiveAgressiveClassifier/Regressor, LinearSVC, LogisticRegression...) the +decision function that is applied at prediction time is the same (a dot product) +, so latency should be equivalent. + +Here is an example using +:class:`sklearn.linear_model.stochastic_gradient.SGDClassifier` with the +``elasticnet`` penalty. The regularization strength is globally controlled by +the ``alpha`` parameter. With a sufficiently high ``alpha``, +one can then increase the ``l1_ratio`` parameter of ``elasticnet`` to +enforce various levels of sparsity in the model coefficients. Higher sparsity +here is interpreted as less model complexity as we need fewer coefficients to +describe it fully. Of course sparsity influences in turn the prediction time +as the sparse dot-product takes time roughly proportional to the number of +non-zero coefficients. + +.. |en_model_complexity| image:: ../auto_examples/applications/images/plot_model_complexity_influence_001.png + :target: ../auto_examples/applications/plot_model_complexity_influence.html + :scale: 80 + +.. centered:: |en_model_complexity| + +For the :mod:`sklearn.svm` family of algorithms with a non-linear kernel, +the latency is tied to the number of support vectors (the fewer the faster). +Latency and throughput should (asymptotically) grow linearly with the number +of support vectors in a SVC or SVR model. The kernel will also influence the +latency as it is used to compute the projection of the input vector once per +support vector. In the following graph the ``nu`` parameter of +:class:`sklearn.svm.classes.NuSVR` was used to influence the number of +support vectors. + +.. |nusvr_model_complexity| image:: ../auto_examples/applications/images/plot_model_complexity_influence_002.png + :target: ../auto_examples/applications/plot_model_complexity_influence.html + :scale: 80 + +.. centered:: |nusvr_model_complexity| + +For :mod:`sklearn.ensemble` of trees (e.g. RandomForest, GBT, +ExtraTrees etc) the number of trees and their depth play the most +important role. Latency and throughput should scale linearly with the number +of trees. In this case we used directly the ``n_estimators`` parameter of +:class:`sklearn.ensemble.gradient_boosting.GradientBoostingRegressor`. + +.. |gbt_model_complexity| image:: ../auto_examples/applications/images/plot_model_complexity_influence_003.png + :target: ../auto_examples/applications/plot_model_complexity_influence.html + :scale: 80 + +.. centered:: |gbt_model_complexity| + +In any case be warned that decreasing model complexity can hurt accuracy as +mentioned above. For instance a non-linearly separable problem can be handled +with a speedy linear model but prediction power will very likely suffer in +the process. + +Feature Extraction Latency +-------------------------- + +Most scikit-learn models are usually pretty fast as they are implemented +either with compiled Cython extensions or optimized computing libraries. +On the other hand, in many real world applications the feature extraction +process (i.e. turning raw data like database rows or network packets into +numpy arrays) governs the overall prediction time. For example on the Reuters +text classification task the whole preparation (reading and parsing SGML +files, tokenizing the text and hashing it into a common vector space) is +taking 100 to 500 times more time than the actual prediction code, depending on +the chosen model. + + .. |prediction_time| image:: ../auto_examples/applications/images/plot_out_of_core_classification_004.png + :target: ../auto_examples/applications/plot_out_of_core_classification.html + :scale: 80 + +.. centered:: |prediction_time| + +In many cases it is thus recommended to carefully time and profile your +feature extraction code as it may be a good place to start optimizing when +your overall latency is too slow for your application. + +Prediction Throughput +===================== + +Another important metric to care about when sizing production systems is the +throughput i.e. the number of predictions you can make in a given amount of +time. Here is a benchmark from the +:ref:`example_applications_plot_prediction_latency.py` example that measures +this quantity for a number of estimators on synthetic data: + +.. |throughput_benchmark| image:: ../auto_examples/applications/images/plot_prediction_latency_004.png + :target: ../auto_examples/applications/plot_prediction_latency.html + :scale: 80 + +.. centered:: |throughput_benchmark| + +These throughputs are achieved on a single process. An obvious way to +increase the throughput of your application is to spawn additional instances +(usually processes in Python because of the +`GIL `_) that share the +same model. One might also add machines to spread the load. A detailed +explanation on how to achieve this is beyond the scope of this documentation +though. + +Tips and Tricks +=============== + +Linear algebra libraries +------------------------ + +As scikit-learn relies heavily on Numpy/Scipy and linear algebra in general it +makes sense to take explicit care of the versions of these libraries. +Basically, you ought to make sure that Numpy is built using an optimized `BLAS +`_ / +`LAPACK `_ library. + +Not all models benefit from optimized BLAS and Lapack implementations. For +instance models based on (randomized) decision trees typically do not rely on +BLAS calls in their inner loops, nor do kernel SVMs (``SVC``, ``SVR``, +``NuSVC``, ``NuSVR``). On the other hand a linear model implemented with a +BLAS DGEMM call (via ``numpy.dot``) will typically benefit hugely from a tuned +BLAS implementation and lead to orders of magnitude speedup over a +non-optimized BLAS. + +You can display the BLAS / LAPACK implementation used by your NumPy / SciPy / +scikit-learn install with the following commands:: + + from numpy.distutils.system_info import get_info + print(get_info('blas_opt')) + print(get_info('lapack_opt')) + +Optimized BLAS / LAPACK implementations include: + - Atlas (need hardware specific tuning by rebuilding on the target machine) + - OpenBLAS + - MKL + - Apple Accelerate and vecLib frameworks (OSX only) + +More information can be found on the `Scipy install page `_ +and in this +`blog post `_ +from Daniel Nouri which has some nice step by step install instructions for +Debian / Ubuntu. + +.. warning:: + + Multithreaded BLAS libraries sometimes conflict with Python's + ``multiprocessing`` module, which is used by e.g. ``GridSearchCV`` and + most other estimators that take an ``n_jobs`` argument (with the exception + of ``SGDClassifier``, ``SGDRegressor``, ``Perceptron``, + ``PassiveAggressiveClassifier`` and tree-based methods such as random + forests). This is true of Apple's Accelerate and OpenBLAS when built with + OpenMP support. + + Besides scikit-learn, NumPy and SciPy also use BLAS internally, as + explained earlier. + + If you experience hanging subprocesses with ``n_jobs>1`` or ``n_jobs=-1``, + make sure you have a single-threaded BLAS library, or set ``n_jobs=1``, + or upgrade to Python 3.4 which has a new version of ``multiprocessing`` + that should be immune to this problem. + +Model Compression +----------------- + +Model compression in scikit-learn only concerns linear models for the moment. +In this context it means that we want to control the model sparsity (i.e. the +number of non-zero coordinates in the model vectors). It is generally a good +idea to combine model sparsity with sparse input data representation. + +Here is sample code that illustrates the use of the ``sparsify()`` method:: + + clf = SGDRegressor(penalty='elasticnet', l1_ratio=0.25) + clf.fit(X_train, y_train).sparsify() + clf.predict(X_test) + +In this example we prefer the ``elasticnet`` penalty as it is often a good +compromise between model compactness and prediction power. One can also +further tune the ``l1_ratio`` parameter (in combination with the +regularization strength ``alpha``) to control this tradeoff. + +A typical `benchmark `_ +on synthetic data yields a >30% decrease in latency when both the model and +input are sparse (with 0.000024 and 0.027400 non-zero coefficients ratio +respectively). Your mileage may vary depending on the sparsity and size of +your data and model. +Furthermore, sparsifying can be very useful to reduce the memory usage of +predictive models deployed on production servers. + +Model Reshaping +--------------- + +Model reshaping consists in selecting only a portion of the available features +to fit a model. In other words, if a model discards features during the +learning phase we can then strip those from the input. This has several +benefits. Firstly it reduces memory (and therefore time) overhead of the +model itself. It also allows to discard explicit +feature selection components in a pipeline once we know which features to +keep from a previous run. Finally, it can help reduce processing time and I/O +usage upstream in the data access and feature extraction layers by not +collecting and building features that are discarded by the model. For instance +if the raw data come from a database, it can make it possible to write simpler +and faster queries or reduce I/O usage by making the queries return lighter +records. +At the moment, reshaping needs to be performed manually in scikit-learn. +In the case of sparse input (particularly in ``CSR`` format), it is generally +sufficient to not generate the relevant features, leaving their columns empty. + +Links +----- + + - `scikit-learn developer performance documentation <../developers/performance.html>`_ + - `Scipy sparse matrix formats documentation `_ diff --git a/doc/modules/covariance.rst b/doc/modules/covariance.rst index f2cc724959afb..9da5be0a4083b 100644 --- a/doc/modules/covariance.rst +++ b/doc/modules/covariance.rst @@ -24,8 +24,8 @@ Empirical covariance ==================== The covariance matrix of a data set is known to be well approximated -with the classical `Maximum Likelihood Estimator` (or `empirical -covariance`), provided the number of observations is large enough +with the classical *maximum likelihood estimator* (or "empirical +covariance"), provided the number of observations is large enough compared to the number of features (the variables describing the observations). More precisely, the Maximum Likelihood Estimator of a sample is an unbiased estimator of the corresponding population @@ -36,7 +36,10 @@ The empirical covariance matrix of a sample can be computed using the :class:`EmpiricalCovariance` object to the data sample with the :meth:`EmpiricalCovariance.fit` method. Be careful that depending whether the data are centered or not, the result will be different, so -one may want to use the `assume_centered` parameter accurately. +one may want to use the ``assume_centered`` parameter accurately. More precisely +if one uses ``assume_centered=False``, then the test set is supposed to have the +same mean vector as the training set. If not so, both should be centered by the +user, and ``assume_centered=True`` should be used. .. topic:: Examples: @@ -45,6 +48,8 @@ one may want to use the `assume_centered` parameter accurately. to data. +.. _shrunk_covariance: + Shrunk Covariance ================= @@ -57,24 +62,28 @@ eigenvalues of the covariance matrix, so the precision matrix obtained from its inversion is not accurate. Sometimes, it even occurs that the empirical covariance matrix cannot be inverted for numerical reasons. To avoid such an inversion problem, a transformation of the -empirical covariance matrix has been introduced: the `shrinkage`. It -consists in reducing the ratio between the smallest and the largest -eigenvalue of the empirical covariance matrix. This can be done by -simply shifting every eigenvalue according to a given offset, which is -equivalent of finding the l2-penalized Maximum Likelihood Estimator of -the covariance matrix, or by reducing the highest eigenvalue while -increasing the smallest with the help of a convex transformation : -:math:`\Sigma_{\rm shrunk} = (1-\alpha)\hat{\Sigma} + -\alpha\frac{{\rm Tr}\hat{\Sigma}}{p}\rm Id`. The latter approach has been -implemented in scikit-learn. - -A convex transformation (with a user-defined shrinkage coefficient) -can be directly applied to a pre-computed covariance with the -:func:`shrunk_covariance` method. Also, a shrunk estimator of the -covariance can be fitted to data with a :class:`ShrunkCovariance` -object and its :meth:`ShrunkCovariance.fit` method. Again, depending -whether the data are centered or not, the result will be different, so -one may want to use the `assume_centered` parameter accurately. +empirical covariance matrix has been introduced: the ``shrinkage``. + +In the scikit-learn, this transformation (with a user-defined shrinkage +coefficient) can be directly applied to a pre-computed covariance with +the :func:`shrunk_covariance` method. Also, a shrunk estimator of the +covariance can be fitted to data with a :class:`ShrunkCovariance` object +and its :meth:`ShrunkCovariance.fit` method. Again, depending whether +the data are centered or not, the result will be different, so one may +want to use the ``assume_centered`` parameter accurately. + + +Mathematically, this shrinkage consists in reducing the ratio between the +smallest and the largest eigenvalue of the empirical covariance matrix. +It can be done by simply shifting every eigenvalue according to a given +offset, which is equivalent of finding the l2-penalized Maximum +Likelihood Estimator of the covariance matrix. In practice, shrinkage +boils down to a simple a convex transformation : :math:`\Sigma_{\rm +shrunk} = (1-\alpha)\hat{\Sigma} + \alpha\frac{{\rm +Tr}\hat{\Sigma}}{p}\rm Id`. + +Choosing the amount of shrinkage, :math:`\alpha` amounts to setting a +bias/variance trade-off, and is discussed below. .. topic:: Examples: @@ -89,17 +98,13 @@ Ledoit-Wolf shrinkage In their 2004 paper [1], O. Ledoit and M. Wolf propose a formula so as to compute the optimal shrinkage coefficient :math:`\alpha` that minimizes the Mean Squared Error between the estimated and the real -covariance matrix in terms of Frobenius norm. +covariance matrix. The Ledoit-Wolf estimator of the covariance matrix can be computed on a sample with the :meth:`ledoit_wolf` function of the `sklearn.covariance` package, or it can be otherwise obtained by fitting a :class:`LedoitWolf` object to the same sample. -[1] O. Ledoit and M. Wolf, "A Well-Conditioned Estimator for Large-Dimensional - Covariance Matrices", Journal of Multivariate Analysis, Volume 88, Issue 2, - February 2004, pages 365-411. - .. topic:: Examples: * See :ref:`example_covariance_plot_covariance_estimation.py` for @@ -107,11 +112,10 @@ fitting a :class:`LedoitWolf` object to the same sample. for visualizing the performances of the Ledoit-Wolf estimator in terms of likelihood. -.. figure:: ../auto_examples/covariance/images/plot_covariance_estimation_1.png - :target: ../auto_examples/covariance/plot_covariance_estimation.html - :align: center - :scale: 65% +[1] O. Ledoit and M. Wolf, "A Well-Conditioned Estimator for Large-Dimensional + Covariance Matrices", Journal of Multivariate Analysis, Volume 88, Issue 2, + February 2004, pages 365-411. .. _oracle_approximating_shrinkage: @@ -127,11 +131,15 @@ Shrinkage Approximating estimator of the covariance. The OAS estimator of the covariance matrix can be computed on a sample with the :meth:`oas` function of the `sklearn.covariance` package, or it can be otherwise obtained by fitting an :class:`OAS` -object to the same sample. The formula we used to implement the OAS -does not correspond to the one given in the article. It has been taken -from the MATLAB program available from the author's webpage -(https://tbayes.eecs.umich.edu/yilun/covestimation). +object to the same sample. +.. figure:: ../auto_examples/covariance/images/plot_covariance_estimation_001.png + :target: ../auto_examples/covariance/plot_covariance_estimation.html + :align: center + :scale: 65% + + Bias-variance trade-off when setting the shrinkage: comparing the + choices of Ledoit-Wolf and OAS estimators [2] Chen et al., "Shrinkage Algorithms for MMSE Covariance Estimation", IEEE Trans. on Sign. Proc., Volume 58, Issue 10, October 2010. @@ -147,11 +155,12 @@ from the MATLAB program available from the author's webpage an :class:`OAS` estimator of the covariance. -.. figure:: ../auto_examples/covariance/images/plot_lw_vs_oas_1.png +.. figure:: ../auto_examples/covariance/images/plot_lw_vs_oas_001.png :target: ../auto_examples/covariance/plot_lw_vs_oas.html :align: center :scale: 75% + .. _sparse_inverse_covariance: Sparse inverse covariance @@ -166,19 +175,19 @@ a sparse precision matrix: by learning independence relations from the data, the estimation of the covariance matrix is better conditioned. This is known as *covariance selection*. -In the small-samples situation, in which `n_samples` is on the order of magnitude -of `n_features` or smaller, sparse inverse covariance estimators tend to work +In the small-samples situation, in which ``n_samples`` is on the order +of ``n_features`` or smaller, sparse inverse covariance estimators tend to work better than shrunk covariance estimators. However, in the opposite situation, or for very correlated data, they can be numerically unstable. In addition, unlike shrinkage estimators, sparse estimators are able to recover off-diagonal structure. The :class:`GraphLasso` estimator uses an l1 penalty to enforce sparsity on -the precision matrix: the higher its `alpha` parameter, the more sparse +the precision matrix: the higher its ``alpha`` parameter, the more sparse the precision matrix. The corresponding :class:`GraphLassoCV` object uses -cross-validation to automatically set the `alpha` parameter. +cross-validation to automatically set the ``alpha`` parameter. -.. figure:: ../auto_examples/covariance/images/plot_sparse_cov_1.png +.. figure:: ../auto_examples/covariance/images/plot_sparse_cov_001.png :target: ../auto_examples/covariance/plot_sparse_cov.html :align: center :scale: 60% @@ -210,18 +219,18 @@ cross-validation to automatically set the `alpha` parameter. The mathematical formulation is the following: -.. math:: - +.. math:: + \hat{K} = \mathrm{argmin}_K \big( \mathrm{tr} S K - \mathrm{log} \mathrm{det} K + \alpha \|K\|_1 \big) -Where `K` is the precision matrix to be estimated, and `S` is the sample -covariance matrix. :math:`\|K\|_1` is the sum of the absolute values of -off-diagonal coefficients of `K`. The algorithm employed to solve this +Where :math:`K` is the precision matrix to be estimated, and :math:`S` is the +sample covariance matrix. :math:`\|K\|_1` is the sum of the absolute values of +off-diagonal coefficients of :math:`K`. The algorithm employed to solve this problem is the GLasso algorithm, from the Friedman 2008 Biostatistics -paper. It is the same algorithm as in the R `glasso` package. +paper. It is the same algorithm as in the R ``glasso`` package. .. topic:: Examples: @@ -235,7 +244,7 @@ paper. It is the same algorithm as in the R `glasso` package. .. topic:: References: - * Friedman et al, `"Sparse inverse covariance estimation with the + * Friedman et al, `"Sparse inverse covariance estimation with the graphical lasso" `_, Biostatistics 9, pp 432, 2008 @@ -255,7 +264,7 @@ sets. Alternatively, robust covariance estimators can be used to perform outlier detection and discard/downweight some observations according to further processing of the data. -The `sklearn.covariance` package implements a robust estimator of covariance, +The ``sklearn.covariance`` package implements a robust estimator of covariance, the Minimum Covariance Determinant [3]. @@ -263,7 +272,7 @@ Minimum Covariance Determinant ------------------------------ The Minimum Covariance Determinant estimator is a robust estimator of -a data set's covariance introduced by P.J.Rousseuw in [3]. The idea +a data set's covariance introduced by P.J. Rousseeuw in [3]. The idea is to find a given proportion (h) of "good" observations which are not outliers and compute their empirical covariance matrix. This empirical covariance matrix is then rescaled to compensate the @@ -273,13 +282,13 @@ weights to observations according to their Mahalanobis distance, leading the a reweighted estimate of the covariance matrix of the data set ("reweighting step"). -Rousseuw and Van Driessen [4] developed the FastMCD algorithm in order +Rousseeuw and Van Driessen [4] developed the FastMCD algorithm in order to compute the Minimum Covariance Determinant. This algorithm is used in scikit-learn when fitting an MCD object to data. The FastMCD algorithm also computes a robust estimate of the data set location at the same time. -Raw estimates can be accessed as `raw_location_` and `raw_covariance_` +Raw estimates can be accessed as ``raw_location_`` and ``raw_covariance_`` attributes of a :class:`MinCovDet` robust covariance estimator object. [3] P. J. Rousseeuw. Least median of squares regression. @@ -294,16 +303,16 @@ attributes of a :class:`MinCovDet` robust covariance estimator object. an example on how to fit a :class:`MinCovDet` object to data and see how the estimate remains accurate despite the presence of outliers. - * See :ref:`example_covariance_plot_mahalanobis_distances.py` to + * See :ref:`example_covariance_plot_mahalanobis_distances.py` to visualize the difference between :class:`EmpiricalCovariance` and :class:`MinCovDet` covariance estimators in terms of Mahalanobis distance (so we get a better estimate of the precision matrix too). -.. |robust_vs_emp| image:: ../auto_examples/covariance/images/plot_robust_vs_empirical_covariance_1.png +.. |robust_vs_emp| image:: ../auto_examples/covariance/images/plot_robust_vs_empirical_covariance_001.png :target: ../auto_examples/covariance/plot_robust_vs_empirical_covariance.html :scale: 49% -.. |mahalanobis| image:: ../auto_examples/covariance/images/plot_mahalanobis_distances_1.png +.. |mahalanobis| image:: ../auto_examples/covariance/images/plot_mahalanobis_distances_001.png :target: ../auto_examples/covariance/plot_mahalanobis_distances.html :scale: 49% @@ -315,7 +324,7 @@ ____ :header-rows: 1 * - Influence of outliers on location and covariance estimates - - Separating inliers from outliers using a Mahalonis distance + - Separating inliers from outliers using a Mahalanobis distance * - |robust_vs_emp| - |mahalanobis| diff --git a/doc/modules/cross_decomposition.rst b/doc/modules/cross_decomposition.rst new file mode 100644 index 0000000000000..c55a2168458a0 --- /dev/null +++ b/doc/modules/cross_decomposition.rst @@ -0,0 +1,42 @@ +.. _cross_decomposition: + +=================== +Cross decomposition +=================== + +.. currentmodule:: sklearn.cross_decomposition + +The cross decomposition module contains two main families of algorithms: the +partial least squares (PLS) and the canonical correlation analysis (CCA). + +These families of algorithms are useful to find linear relations between two +multivariate datasets: the ``X`` and ``Y`` arguments of the ``fit`` method +are 2D arrays. + +.. figure:: ../auto_examples/cross_decomposition/images/plot_compare_cross_decomposition_001.png + :target: ../auto_examples/cross_decomposition/plot_compare_cross_decomposition.html + :scale: 75% + :align: center + + +Cross decomposition algorithms find the fundamental relations between two +matrices (X and Y). They are latent variable approaches to modeling the +covariance structures in these two spaces. They will try to find the +multidimensional direction in the X space that explains the maximum +multidimensional variance direction in the Y space. PLS-regression is +particularly suited when the matrix of predictors has more variables than +observations, and when there is multicollinearity among X values. By contrast, +standard regression will fail in these cases. + +Classes included in this module are :class:`PLSRegression` +:class:`PLSCanonical`, :class:`CCA` and :class:`PLSSVD` + + +.. topic:: Reference: + + * JA Wegelin + `A survey of Partial Least Squares (PLS) methods, with emphasis on the two-block case `_ + +.. topic:: Examples: + + * :ref:`example_cross_decomposition_plot_compare_cross_decomposition.py` diff --git a/doc/modules/cross_validation.rst b/doc/modules/cross_validation.rst index 039afabc662e1..0aa6bf1e3b692 100644 --- a/doc/modules/cross_validation.rst +++ b/doc/modules/cross_validation.rst @@ -1,7 +1,7 @@ .. _cross_validation: =================================================== -Cross-Validation: evaluating estimator performance +Cross-validation: evaluating estimator performance =================================================== .. currentmodule:: sklearn.cross_validation @@ -10,15 +10,18 @@ Learning the parameters of a prediction function and testing it on the same data is a methodological mistake: a model that would just repeat the labels of the samples that it has just seen would have a perfect score but would fail to predict anything useful on yet-unseen data. - -To **avoid over-fitting**, we have to define two different sets : -a **training set** ``X_train, y_train`` which is used for learning -the parameters of a predictive model, and a **testing set** ``X_test, -y_test`` which is used for evaluating the fitted predictive model. - -In scikit-learn such a random split can be quickly computed with the -:func:`train_test_split` helper function. Let load the iris data set to -fit a linear Support Vector Machine model on it:: +This situation is called **overfitting**. +To avoid it, it is common practice when performing +a (supervised) machine learning experiment +to hold out part of the available data as a **test set** ``X_test, y_test``. +Note that the word "experiment" is not intended +to denote academic use only, +because even in commercial settings +machine learning usually starts out experimentally. + +In scikit-learn a random split into training and test sets +can be quickly computed with the :func:`train_test_split` helper function. +Let's load the iris data set to fit a linear support vector machine on it:: >>> import numpy as np >>> from sklearn import cross_validation @@ -44,174 +47,218 @@ data for testing (evaluating) our classifier:: >>> clf.score(X_test, y_test) # doctest: +ELLIPSIS 0.96... -However, by defining these two sets, we drastically reduce the number -of samples which can be used for learning the model, and the results can -depend on a particular random choice for the pair of (train, test) sets. - -A solution is to **split the whole data several consecutive times in -different train set and test set**, and to return the averaged value of -the prediction scores obtained with the different sets. Such a procedure -is called **cross-validation**. This approach can be **computationally -expensive, but does not waste too much data** (as it is the case when -fixing an arbitrary test set), which is a major advantage in problem -such as inverse inference where the number of samples is very small. +When evaluating different settings ("hyperparameters") for estimators, +such as the ``C`` setting that must be manually set for an SVM, +there is still a risk of overfitting *on the test set* +because the parameters can be tweaked until the estimator performs optimally. +This way, knowledge about the test set can "leak" into the model +and evaluation metrics no longer report on generalization performance. +To solve this problem, yet another part of the dataset can be held out +as a so-called "validation set": training proceeds on the training set, +after which evaluation is done on the validation set, +and when the experiment seems to be successful, +final evaluation can be done on the test set. + +However, by partitioning the available data into three sets, +we drastically reduce the number of samples +which can be used for learning the model, +and the results can depend on a particular random choice for the pair of +(train, validation) sets. + +A solution to this problem is a procedure called +`cross-validation `_ +(CV for short). +A test set should still be held out for final evaluation, +but the validation set is no longer needed when doing CV. +In the basic approach, called *k*-fold CV, +the training set is split into *k* smaller sets +(other approaches are described below, +but generally follow the same principles). +The following procedure is followed for each of the *k* "folds": + + * A model is trained using :math:`k-1` of the folds as training data; + * the resulting model is validated on the remaining part of the data + (i.e., it is used as a test set to compute a performance measure + such as accuracy). + +The performance measure reported by *k*-fold cross-validation +is then the average of the values computed in the loop. +This approach can be computationally expensive, +but does not waste too much data +(as it is the case when fixing an arbitrary test set), +which is a major advantage in problem such as inverse inference +where the number of samples is very small. Computing cross-validated metrics ================================= -The simplest way to use perform cross-validation in to call the +The simplest way to use cross-validation is to call the :func:`cross_val_score` helper function on the estimator and the dataset. -The following example demonstrates how to estimate the accuracy of a -linear kernel Support Vector Machine on the iris dataset by splitting -the data and fitting a model and computing the score 5 consecutive times -(with different splits each time):: +The following example demonstrates how to estimate the accuracy of a linear +kernel support vector machine on the iris dataset by splitting the data, fitting +a model and computing the score 5 consecutive times (with different splits each +time):: >>> clf = svm.SVC(kernel='linear', C=1) >>> scores = cross_validation.cross_val_score( ... clf, iris.data, iris.target, cv=5) ... - >>> scores # doctest: +ELLIPSIS - array([ 1. ..., 0.96..., 0.9 ..., 0.96..., 1. ]) + >>> scores # doctest: +ELLIPSIS + array([ 0.96..., 1. ..., 0.96..., 0.96..., 1. ]) -The mean score and the standard deviation of the score estimate are hence given -by:: +The mean score and the 95\% confidence interval of the score estimate are hence +given by:: - >>> print "Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() / 2) - Accuracy: 0.97 (+/- 0.02) + >>> print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2)) + Accuracy: 0.98 (+/- 0.03) By default, the score computed at each CV iteration is the ``score`` -method of the estimator. It is possible to change this by passing a custom -scoring function, e.g. from the metrics module:: +method of the estimator. It is possible to change this by using the +scoring parameter:: >>> from sklearn import metrics - >>> cross_validation.cross_val_score(clf, iris.data, iris.target, cv=5, - ... score_func=metrics.f1_score) - ... # doctest: +ELLIPSIS - array([ 1. ..., 0.96..., 0.89..., 0.96..., 1. ]) + >>> scores = cross_validation.cross_val_score(clf, iris.data, iris.target, + ... cv=5, scoring='f1_weighted') + >>> scores # doctest: +ELLIPSIS + array([ 0.96..., 1. ..., 0.96..., 0.96..., 1. ]) +See :ref:`scoring_parameter` for details. In the case of the Iris dataset, the samples are balanced across target classes hence the accuracy and the F1-score are almost equal. When the ``cv`` argument is an integer, :func:`cross_val_score` uses the -:class:`KFold` or :class:`StratifiedKFold` strategies by default (depending on -the absence or presence of the target array). +:class:`KFold` or :class:`StratifiedKFold` strategies by default, the latter +being used if the estimator derives from :class:`ClassifierMixin +`. -It is also possible to use othe cross validation strategies by passing a cross +It is also possible to use other cross validation strategies by passing a cross validation iterator instead, for instance:: >>> n_samples = iris.data.shape[0] - >>> cv = cross_validation.ShuffleSplit(n_samples, n_iterations=3, + >>> cv = cross_validation.ShuffleSplit(n_samples, n_iter=3, ... test_size=0.3, random_state=0) >>> cross_validation.cross_val_score(clf, iris.data, iris.target, cv=cv) ... # doctest: +ELLIPSIS array([ 0.97..., 0.97..., 1. ]) -The available cross validation iterators are introduced in the following. +.. topic:: Data transformation with held out data -.. topic:: Examples + Just as it is important to test a predictor on data held-out from + training, preprocessing (such as standardization, feature selection, etc.) + and similar :ref:`data transformations ` similarly should + be learnt from a training set and applied to held-out data for prediction:: - * :ref:`example_plot_roc_crossval.py`, - * :ref:`example_plot_rfe_with_cross_validation.py`, - * :ref:`example_grid_search_digits.py`, - * :ref:`example_grid_search_text_feature_extraction.py`, + >>> from sklearn import preprocessing + >>> X_train, X_test, y_train, y_test = cross_validation.train_test_split( + ... iris.data, iris.target, test_size=0.4, random_state=0) + >>> scaler = preprocessing.StandardScaler().fit(X_train) + >>> X_train_transformed = scaler.transform(X_train) + >>> clf = svm.SVC(C=1).fit(X_train_transformed, y_train) + >>> X_test_transformed = scaler.transform(X_test) + >>> clf.score(X_test_transformed, y_test) # doctest: +ELLIPSIS + 0.9333... + A :class:`Pipeline ` makes it easier to compose + estimators, providing this behavior under cross-validation:: -Cross validation iterators -========================== + >>> from sklearn.pipeline import make_pipeline + >>> clf = make_pipeline(preprocessing.StandardScaler(), svm.SVC(C=1)) + >>> cross_validation.cross_val_score(clf, iris.data, iris.target, cv=cv) + ... # doctest: +ELLIPSIS + array([ 0.97..., 0.93..., 0.95...]) -The following sections list utilities to generate boolean masks or indices -that can be used to generate dataset splits according to different cross -validation strategies. + See :ref:`combining_estimators`. +Obtaining predictions by cross-validation +----------------------------------------- -.. topic:: Boolean mask vs integer indices +The function :func:`cross_val_predict` has a similar interface to +:func:`cross_val_score`, but returns, for each element in the input, the +prediction that was obtained for that element when it was in the test set. Only +cross-validation strategies that assign all elements to a test set exactly once +can be used (otherwise, an exception is raised). - Most cross validators support generating both boolean masks or integer - indices to select the samples from a given fold. +These prediction can then be used to evaluate the classifier:: - When the data matrix is sparse, only the integer indices will work as - expected. Integer indexing is hence the default behavior (since version - 0.10). + >>> predicted = cross_validation.cross_val_predict(clf, iris.data, + ... iris.target, cv=10) + >>> metrics.accuracy_score(iris.target, predicted) # doctest: +ELLIPSIS + 0.966... - You can explicitly pass ``indices=False`` to the constructor of the - CV object (when supported) to use the boolean mask method instead. +Note that the result of this computation may be slightly different from those +obtained using :func:`cross_val_score` as the elements are grouped in different +ways. + +The available cross validation iterators are introduced in the following +section. + +.. topic:: Examples + + * :ref:`example_model_selection_plot_roc_crossval.py`, + * :ref:`example_feature_selection_plot_rfe_with_cross_validation.py`, + * :ref:`example_model_selection_grid_search_digits.py`, + * :ref:`example_model_selection_grid_search_text_feature_extraction.py`, + * :ref:`example_plot_cv_predict.py`, + +Cross validation iterators +========================== + +The following sections list utilities to generate indices +that can be used to generate dataset splits according to different cross +validation strategies. K-fold ------ -:class:`KFold` divides all the samples in math:`K` groups of samples, -called folds (if :math:`K = n`, this is equivalent to the *Leave One +:class:`KFold` divides all the samples in :math:`k` groups of samples, +called folds (if :math:`k = n`, this is equivalent to the *Leave One Out* strategy), of equal sizes (if possible). The prediction function is -learned using :math:`K - 1` folds, and the fold left out is used for test. +learned using :math:`k - 1` folds, and the fold left out is used for test. -Example of 2-fold:: +Example of 2-fold cross-validation on a dataset with 4 samples:: >>> import numpy as np >>> from sklearn.cross_validation import KFold - >>> X = np.array([[0., 0.], [1., 1.], [-1., -1.], [2., 2.]]) - >>> Y = np.array([0, 1, 0, 1]) - - >>> kf = KFold(len(Y), 2, indices=False) - >>> print kf - sklearn.cross_validation.KFold(n=4, k=2) + >>> kf = KFold(4, n_folds=2) >>> for train, test in kf: - ... print train, test - [False False True True] [ True True False False] - [ True True False False] [False False True True] + ... print("%s %s" % (train, test)) + [2 3] [0 1] + [0 1] [2 3] Each fold is constituted by two arrays: the first one is related to the *training set*, and the second one to the *test set*. -Thus, one can create the training/test sets using:: - - >>> X_train, X_test, y_train, y_test = X[train], X[test], Y[train], Y[test] - -If X or Y are `scipy.sparse` matrices, train and test need to be integer -indices. It can be obtained by setting the parameter indices to True -when creating the cross-validation procedure:: +Thus, one can create the training/test sets using numpy indexing:: >>> X = np.array([[0., 0.], [1., 1.], [-1., -1.], [2., 2.]]) - >>> Y = np.array([0, 1, 0, 1]) - - >>> kf = KFold(len(Y), 2, indices=True) - >>> for train, test in kf: - ... print train, test - [2 3] [0 1] - [0 1] [2 3] + >>> y = np.array([0, 1, 0, 1]) + >>> X_train, X_test, y_train, y_test = X[train], X[test], y[train], y[test] -Stratified K-Fold +Stratified k-fold ----------------- -:class:`StratifiedKFold` is a variation of *K-fold*, which returns -stratified folds, *i.e* which creates folds by preserving the same -percentage for each target class as in the complete set. +:class:`StratifiedKFold` is a variation of *k-fold* which returns *stratified* +folds: each set contains approximately the same percentage of samples of each +target class as the complete set. -Example of stratified 2-fold:: +Example of stratified 2-fold cross-validation on a dataset with 10 samples from +two slightly unbalanced classes:: >>> from sklearn.cross_validation import StratifiedKFold - >>> X = [[0., 0.], - ... [1., 1.], - ... [-1., -1.], - ... [2., 2.], - ... [3., 3.], - ... [4., 4.], - ... [0., 1.]] - >>> Y = [0, 0, 0, 1, 1, 1, 0] - - >>> skf = StratifiedKFold(Y, 2) - >>> print skf - sklearn.cross_validation.StratifiedKFold(labels=[0 0 0 1 1 1 0], k=2) + >>> labels = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1] + >>> skf = StratifiedKFold(labels, 3) >>> for train, test in skf: - ... print train, test - [1 4 6] [0 2 3 5] - [0 2 3 5] [1 4 6] + ... print("%s %s" % (train, test)) + [2 3 6 7 8 9] [0 1 4 5] + [0 1 3 4 5 8 9] [2 6 7] + [0 1 2 4 5 6 7] [3 8 9] Leave-One-Out - LOO @@ -219,44 +266,74 @@ Leave-One-Out - LOO :class:`LeaveOneOut` (or LOO) is a simple cross-validation. Each learning set is created by taking all the samples except one, the test set being -the sample left out. Thus, for `n` samples, we have `n` different learning -sets and `n` different tests set. This cross-validation procedure does -not waste much data as only one sample is removed from the learning set:: +the sample left out. Thus, for :math:`n` samples, we have :math:`n` different +training sets and :math:`n` different tests set. This cross-validation +procedure does not waste much data as only one sample is removed from the +training set:: >>> from sklearn.cross_validation import LeaveOneOut - >>> X = np.array([[0., 0.], [1., 1.], [-1., -1.], [2., 2.]]) - >>> Y = np.array([0, 1, 0, 1]) - - >>> loo = LeaveOneOut(len(Y)) - >>> print loo - sklearn.cross_validation.LeaveOneOut(n=4) + >>> loo = LeaveOneOut(4) >>> for train, test in loo: - ... print train, test + ... print("%s %s" % (train, test)) [1 2 3] [0] [0 2 3] [1] [0 1 3] [2] [0 1 2] [3] +Potential users of LOO for model selection should weigh a few known caveats. +When compared with :math:`k`-fold cross validation, one builds :math:`n` models +from :math:`n` samples instead of :math:`k` models, where :math:`n > k`. +Moreover, each is trained on :math:`n - 1` samples rather than +:math:`(k-1)n / k`. In both ways, assuming :math:`k` is not too large +and :math:`k < n`, LOO is more computationally expensive than :math:`k`-fold +cross validation. + +In terms of accuracy, LOO often results in high variance as an estimator for the +test error. Intuitively, since :math:`n - 1` of +the :math:`n` samples are used to build each model, models constructed from +folds are virtually identical to each other and to the model built from the +entire training set. + +However, if the learning curve is steep for the training size in question, +then 5- or 10- fold cross validation can overestimate the generalization error. + +As a general rule, most authors, and empirical evidence, suggest that 5- or 10- +fold cross validation should be preferred to LOO. + + +.. topic:: References: + + * http://www.faqs.org/faqs/ai-faq/neural-nets/part3/section-12.html + * T. Hastie, R. Tibshirani, J. Friedman, `The Elements of Statistical Learning + `_, Springer 2009 + * L. Breiman, P. Spector `Submodel selection and evaluation in regression: The X-random case + `_, International Statistical Review 1992 + * R. Kohavi, `A Study of Cross-Validation and Bootstrap for Accuracy Estimation and Model Selection + `_, Intl. Jnt. Conf. AI + * R. Bharat Rao, G. Fung, R. Rosales, `On the Dangers of Cross-Validation. An Experimental Evaluation + `_, SIAM 2008 + * G. James, D. Witten, T. Hastie, R Tibshirani, `An Introduction to + Statistical Learning `_, Springer 2013 + + Leave-P-Out - LPO ----------------- -:class:`LeavePOut` is very similar to *Leave-One-Out*, as it creates all the -possible training/test sets by removing :math:`P` samples from the complete set. +:class:`LeavePOut` is very similar to :class:`LeaveOneOut` as it creates all +the possible training/test sets by removing :math:`p` samples from the complete +set. For :math:`n` samples, this produces :math:`{n \choose p}` train-test +pairs. Unlike :class:`LeaveOneOut` and :class:`KFold`, the test sets will +overlap for :math:`p > 1`. -Example of Leave-2-Out:: +Example of Leave-2-Out on a dataset with 4 samples:: >>> from sklearn.cross_validation import LeavePOut - >>> X = [[0., 0.], [1., 1.], [-1., -1.], [2., 2.]] - >>> Y = [0, 1, 0, 1] - - >>> lpo = LeavePOut(len(Y), 2) - >>> print lpo - sklearn.cross_validation.LeavePOut(n=4, p=2) + >>> lpo = LeavePOut(4, p=2) >>> for train, test in lpo: - ... print train, test + ... print("%s %s" % (train, test)) [2 3] [0 1] [1 3] [0 2] [1 2] [0 3] @@ -268,10 +345,10 @@ Example of Leave-2-Out:: Leave-One-Label-Out - LOLO -------------------------- -:class:`LeaveOneLabelOut` (LOLO) is a cross-validation scheme which -holds out the samples according to a third-party provided label. This -label information can be used to encode arbitrary domain specific -stratifications of the samples as integers. +:class:`LeaveOneLabelOut` (LOLO) is a cross-validation scheme which holds out +the samples according to a third-party provided array of integer labels. This +label information can be used to encode arbitrary domain specific pre-defined +cross-validation folds. Each training set is thus constituted by all the samples except the ones related to a specific label. @@ -281,16 +358,11 @@ create a cross-validation based on the different experiments: we create a training set using the samples of all the experiments except one:: >>> from sklearn.cross_validation import LeaveOneLabelOut - >>> X = [[0., 0.], [1., 1.], [-1., -1.], [2., 2.]] - >>> Y = [0, 1, 0, 1] - >>> labels = [1, 1, 2, 2] + >>> labels = [1, 1, 2, 2] >>> lolo = LeaveOneLabelOut(labels) - >>> print lolo - sklearn.cross_validation.LeaveOneLabelOut(labels=[1, 1, 2, 2]) - >>> for train, test in lolo: - ... print train, test + ... print("%s %s" % (train, test)) [2 3] [0 1] [0 1] [2 3] @@ -298,6 +370,16 @@ Another common application is to use time information: for instance the labels could be the year of collection of the samples and thus allow for cross-validation against time-based splits. +.. warning:: + + Contrary to :class:`StratifiedKFold`, **the ``labels`` of + :class:`LeaveOneLabelOut` should not encode the target class to predict**: + the goal of :class:`StratifiedKFold` is to rebalance dataset classes across + the train / test split to ensure that the train and test folds have + approximately the same percentage of samples of each class while + :class:`LeaveOneLabelOut` will do the opposite by ensuring that the samples + of the train and test fold will not share the same label value. + Leave-P-Label-Out ----------------- @@ -308,16 +390,11 @@ samples related to :math:`P` labels for each training/test set. Example of Leave-2-Label Out:: >>> from sklearn.cross_validation import LeavePLabelOut - >>> X = [[0., 0.], [1., 1.], [-1., -1.], [2., 2.], [3., 3.], [4., 4.]] - >>> Y = [0, 1, 0, 1, 0, 1] - >>> labels = [1, 1, 2, 2, 3, 3] - - >>> lplo = LeavePLabelOut(labels, 2) - >>> print lplo - sklearn.cross_validation.LeavePLabelOut(labels=[1, 1, 2, 2, 3, 3], p=2) + >>> labels = [1, 1, 2, 2, 3, 3] + >>> lplo = LeavePLabelOut(labels, p=2) >>> for train, test in lplo: - ... print train, test + ... print("%s %s" % (train, test)) [4 5] [0 1 2 3] [2 3] [0 1 4 5] [0 1] [2 3 4 5] @@ -331,7 +408,7 @@ Random permutations cross-validation a.k.a. Shuffle & Split The :class:`ShuffleSplit` iterator will generate a user defined number of independent train / test dataset splits. Samples are first shuffled and -then splitted into a pair of train and test sets. +then split into a pair of train and test sets. It is possible to control the randomness for reproducibility of the results by explicitly seeding the ``random_state`` pseudo random number @@ -339,15 +416,10 @@ generator. Here is a usage example:: - >>> ss = cross_validation.ShuffleSplit(5, n_iterations=3, test_size=0.25, + >>> ss = cross_validation.ShuffleSplit(5, n_iter=3, test_size=0.25, ... random_state=0) - >>> len(ss) - 3 - >>> print ss # doctest: +ELLIPSIS - ShuffleSplit(5, n_iterations=3, test_size=0.25, indices=True, ...) - >>> for train_index, test_index in ss: - ... print train_index, test_index + ... print("%s %s" % (train_index, test_index)) ... [1 3 4] [2 0] [1 4 3] [0 2] @@ -357,48 +429,51 @@ Here is a usage example:: validation that allows a finer control on the number of iterations and the proportion of samples in on each side of the train / test split. -See also --------- -:class:`StratifiedShuffleSplit` is a variation of *ShuffleSplit*, which returns -stratified splits, *i.e* which creates splits by preserving the same -percentage for each target class as in the complete set. - -.. _Bootstrap: - -Bootstrapping cross-validation ------------------------------- - -:class:`Bootstrap` -Bootstrapping_ is a general statistics technique that iterates the -computation of an estimator on a resampled dataset. +Predefined Fold-Splits / Validation-Sets +---------------------------------------- -The :class:`Bootstrap` iterator will generate a user defined number -of independent train / test dataset splits. Samples are then drawn -(with replacement) on each side of the split. It furthermore possible -to control the size of the train and test subset to make their union -smaller than the total dataset if it is very large. +For some datasets, a pre-defined split of the data into training- and +validation fold or into several cross-validation folds already +exists. Using :class:`PredefinedSplit` it is possible to use these folds +e.g. when searching for hyperparameters. -.. note:: +For example, when using a validation set, set the ``test_fold`` to 0 for all +samples that are part of the validation set, and to -1 for all other samples. - Contrary to other cross-validation strategies, bootstrapping - will allow some samples to occur several times in each splits. -.. _Bootstrapping: http://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29 - - >>> bs = cross_validation.Bootstrap(9, random_state=0) - >>> len(bs) - 3 - >>> print bs - Bootstrap(9, n_bootstraps=3, train_size=5, test_size=4, random_state=0) - - >>> for train_index, test_index in bs: - ... print train_index, test_index - ... - [1 8 7 7 8] [0 3 0 5] - [5 4 2 4 2] [6 7 1 0] - [4 7 0 1 1] [5 3 6 5] +See also +-------- +:class:`StratifiedShuffleSplit` is a variation of *ShuffleSplit*, which returns +stratified splits, *i.e* which creates splits by preserving the same +percentage for each target class as in the complete set. +A note on shuffling +=================== + +If the data ordering is not arbitrary (e.g. samples with the same label are +contiguous), shuffling it first may be essential to get a meaningful cross- +validation result. However, the opposite may be true if the samples are not +independently and identically distributed. For example, if samples correspond +to news articles, and are ordered by their time of publication, then shuffling +the data will likely lead to a model that is overfit and an inflated validation +score: it will be tested on samples that are artificially similar (close in +time) to training samples. + +Some cross validation iterators, such as :class:`KFold`, have an inbuilt option +to shuffle the data indices before splitting them. Note that: + +* This consumes less memory than shuffling the data directly. +* By default no shuffling occurs, including for the (stratified) K fold cross- + validation performed by specifying ``cv=some_integer`` to + :func:`cross_val_score`, grid search, etc. Keep in mind that + :func:`train_test_split` still returns a random split. +* The ``random_state`` parameter defaults to ``None``, meaning that the + shuffling will be different every time ``KFold(..., shuffle=True)`` is + iterated. However, ``GridSearchCV`` will use the same shuffling for each set + of parameters validated by a single call to its ``fit`` method. +* To ensure results are repeatable (*on the same platform*), use a fixed value + for ``random_state``. Cross validation and model selection ==================================== diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst index e81ecb059bb37..d1c5719349076 100644 --- a/doc/modules/decomposition.rst +++ b/doc/modules/decomposition.rst @@ -10,6 +10,7 @@ Decomposing signals in components (matrix factorization problems) .. _PCA: + Principal component analysis (PCA) ================================== @@ -18,34 +19,81 @@ Exact PCA and probabilistic interpretation PCA is used to decompose a multivariate dataset in a set of successive orthogonal components that explain a maximum amount of the variance. In -scikit-learn, :class:`PCA` is implemented as a `transformer` object -that learns n components in its `fit` method, and can be used on new data -to project it on these components. +scikit-learn, :class:`PCA` is implemented as a *transformer* object +that learns :math:`n` components in its ``fit`` method, and can be used on new +data to project it on these components. -The optional parameter `whiten=True` parameter make it possible to +The optional parameter ``whiten=True`` parameter make it possible to project the data onto the singular space while scaling each component to unit variance. This is often useful if the models down-stream make strong assumptions on the isotropy of the signal: this is for example the case for Support Vector Machines with the RBF kernel and the K-Means -clustering algorithm. However in that case the inverse transform is no -longer exact since some information is lost while forward transforming. - -In addition, the :class:`ProbabilisticPCA` object provides a -probabilistic interpretation of the PCA that can give a likelihood of -data based on the amount of variance it explains. As such it implements a -`score` method that can be used in cross-validation. +clustering algorithm. Below is an example of the iris dataset, which is comprised of 4 features, projected on the 2 dimensions that explain most variance: -.. figure:: ../auto_examples/decomposition/images/plot_pca_vs_lda_1.png +.. figure:: ../auto_examples/decomposition/images/plot_pca_vs_lda_001.png :target: ../auto_examples/decomposition/plot_pca_vs_lda.html :align: center :scale: 75% + +The :class:`PCA` object also provides a +probabilistic interpretation of the PCA that can give a likelihood of +data based on the amount of variance it explains. As such it implements a +`score` method that can be used in cross-validation: + +.. figure:: ../auto_examples/decomposition/images/plot_pca_vs_fa_model_selection_001.png + :target: ../auto_examples/decomposition/plot_pca_vs_fa_model_selection.html + :align: center + :scale: 75% + + .. topic:: Examples: * :ref:`example_decomposition_plot_pca_vs_lda.py` + * :ref:`example_decomposition_plot_pca_vs_fa_model_selection.py` + + +.. _IncrementalPCA: + +Incremental PCA +--------------- + +The :class:`PCA` object is very useful, but has certain limitations for +large datasets. The biggest limitation is that :class:`PCA` only supports +batch processing, which means all of the data to be processed must fit in main +memory. The :class:`IncrementalPCA` object uses a different form of +processing and allows for partial computations which almost +exactly match the results of :class:`PCA` while processing the data in a +minibatch fashion. :class:`IncrementalPCA` makes it possible to implement +out-of-core Principal Component Analysis either by: + + * Using its ``partial_fit`` method on chunks of data fetched sequentially + from the local hard drive or a network database. + + * Calling its fit method on a memory mapped file using ``numpy.memmap``. + +:class:`IncrementalPCA` only stores estimates of component and noise variances, +in order update ``explained_variance_ratio_`` incrementally. This is why +memory usage depends on the number of samples per batch, rather than the +number of samples to be processed in the dataset. + +.. figure:: ../auto_examples/decomposition/images/plot_incremental_pca_001.png + :target: ../auto_examples/decomposition/plot_incremental_pca.html + :align: center + :scale: 75% + +.. figure:: ../auto_examples/decomposition/images/plot_incremental_pca_002.png + :target: ../auto_examples/decomposition/plot_incremental_pca.html + :align: center + :scale: 75% + + +.. topic:: Examples: + + * :ref:`example_decomposition_plot_incremental_pca.py` .. _RandomizedPCA: @@ -53,15 +101,17 @@ features, projected on the 2 dimensions that explain most variance: Approximate PCA --------------- -Often we are interested in projecting the data onto a lower dimensional -space that preserves most of the variance by dropping the singular vector +It is often interesting to project data to a lower-dimensional +space that preserves most of the variance, by dropping the singular vector of components associated with lower singular values. -For instance for face recognition, if we work with 64x64 gray level pixel -pictures the dimensionality of the data is 4096 and it is slow to train a -RBF Support Vector Machine on such wide data. Furthermore we know that -intrinsic dimensionality of the data is much lower than 4096 since all -faces pictures look alike. The samples lie on a manifold of much lower +For instance, if we work with 64x64 pixel gray-level pictures +for face recognition, +the dimensionality of the data is 4096 and it is slow to train an +RBF support vector machine on such wide data. Furthermore we know that +the intrinsic dimensionality of the data is much lower than 4096 since all +pictures of human faces look somewhat alike. +The samples lie on a manifold of much lower dimension (say around 200 for instance). The PCA algorithm can be used to linearly transform the data while both reducing the dimensionality and preserve most of the explained variance at the same time. @@ -78,19 +128,19 @@ singular vectors reshaped as portraits. Since we only require the top and :math:`n_{features} = 64 \times 64 = 4096`, the computation time it less than 1s: -.. |orig_img| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_1.png +.. |orig_img| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_001.png :target: ../auto_examples/decomposition/plot_faces_decomposition.html :scale: 60% -.. |pca_img| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_2.png +.. |pca_img| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_002.png :target: ../auto_examples/decomposition/plot_faces_decomposition.html :scale: 60% .. centered:: |orig_img| |pca_img| :class:`RandomizedPCA` can hence be used as a drop in replacement for -:class:`PCA` minor the exception that we need to give it the size of -the lower dimensional space `n_components` as mandatory input parameter. +:class:`PCA` with the exception that we need to give it the size of +the lower-dimensional space ``n_components`` as a mandatory input parameter. If we note :math:`n_{max} = max(n_{samples}, n_{features})` and :math:`n_{min} = min(n_{samples}, n_{features})`, the time complexity @@ -102,14 +152,9 @@ The memory footprint of :class:`RandomizedPCA` is also proportional to :math:`2 \cdot n_{max} \cdot n_{components}` instead of :math:`n_{max} \cdot n_{min}` for the exact method. -Furthermore :class:`RandomizedPCA` is able to work with -`scipy.sparse` matrices as input which make it suitable for reducing -the dimensionality of features extracted from text documents for -instance. - -Note: the implementation of `inverse_transform` in :class:`RandomizedPCA` -is not the exact inverse transform of `transform` even when -`whiten=False` (default). +Note: the implementation of ``inverse_transform`` in :class:`RandomizedPCA` +is not the exact inverse transform of ``transform`` even when +``whiten=False`` (default). .. topic:: Examples: @@ -131,12 +176,12 @@ Kernel PCA ---------- :class:`KernelPCA` is an extension of PCA which achieves non-linear -dimensionality reduction through the use of kernels. It has many -applications including denoising, compression and structured prediction -(kernel dependency estimation). :class:`KernelPCA` supports both -`transform` and `inverse_transform`. +dimensionality reduction through the use of kernels (see :ref:`metrics`). It +has many applications including denoising, compression and structured +prediction (kernel dependency estimation). :class:`KernelPCA` supports both +``transform`` and ``inverse_transform``. -.. figure:: ../auto_examples/decomposition/images/plot_kernel_pca_1.png +.. figure:: ../auto_examples/decomposition/images/plot_kernel_pca_001.png :target: ../auto_examples/decomposition/plot_kernel_pca.html :align: center :scale: 75% @@ -148,13 +193,13 @@ applications including denoising, compression and structured prediction .. _SparsePCA: -Sparse Principal Components Analysis (SparsePCA and MiniBatchSparsePCA) +Sparse principal components analysis (SparsePCA and MiniBatchSparsePCA) ----------------------------------------------------------------------- :class:`SparsePCA` is a variant of PCA, with the goal of extracting the set of sparse components that best reconstruct the data. -Mini Batch Sparse PCA (:class:`MiniBatchSparsePCA`) is a variant of +Mini-batch sparse PCA (:class:`MiniBatchSparsePCA`) is a variant of :class:`SparsePCA` that is faster but less accurate. The increased speed is reached by iterating over small chunks of the set of features, for a given number of iterations. @@ -181,12 +226,12 @@ there is no notion of vertical adjacency except during the human-friendly visualization as 64x64 pixel images. The fact that the components shown below appear local is the effect of the inherent structure of the data, which makes such local patterns minimize reconstruction error. There exist sparsity-inducing -norms that take into account adjacency and different kinds of structure; see see -[Jen09]_ for a review of such methods. For more details on how to use Sparse PCA, -see the `Examples` section below. +norms that take into account adjacency and different kinds of structure; see +[Jen09]_ for a review of such methods. +For more details on how to use Sparse PCA, see the Examples section, below. -.. |spca_img| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_5.png +.. |spca_img| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_005.png :target: ../auto_examples/decomposition/plot_faces_decomposition.html :scale: 60% @@ -204,16 +249,16 @@ problem solved is a PCA problem (dictionary learning) with an 0 \leq k < n_{components} -The sparsity inducing :math:`\ell_1` norm also prevents learning +The sparsity-inducing :math:`\ell_1` norm also prevents learning components from noise when few training samples are available. The degree of penalization (and thus sparsity) can be adjusted through the -hyperparameter `alpha`. Small values lead to a gently regularized +hyperparameter ``alpha``. Small values lead to a gently regularized factorization, while larger values shrink many coefficients to zero. .. note:: While in the spirit of an online algorithm, the class - :class:`MiniBatchSparsePCA` does not implement `partial_fit` because + :class:`MiniBatchSparsePCA` does not implement ``partial_fit`` because the algorithm is online along the features direction, not the samples direction. @@ -231,6 +276,86 @@ factorization, while larger values shrink many coefficients to zero. R. Jenatton, G. Obozinski, F. Bach, 2009 +.. _LSA: + +Truncated singular value decomposition and latent semantic analysis +=================================================================== + +:class:`TruncatedSVD` implements a variant of singular value decomposition +(SVD) that only computes the :math:`k` largest singular values, +where :math:`k` is a user-specified parameter. + +When truncated SVD is applied to term-document matrices +(as returned by ``CountVectorizer`` or ``TfidfVectorizer``), +this transformation is known as +`latent semantic analysis `_ +(LSA), because it transforms such matrices +to a "semantic" space of low dimensionality. +In particular, LSA is known to combat the effects of synonymy and polysemy +(both of which roughly mean there are multiple meanings per word), +which cause term-document matrices to be overly sparse +and exhibit poor similarity under measures such as cosine similarity. + +.. note:: + LSA is also known as latent semantic indexing, LSI, + though strictly that refers to its use in persistent indexes + for information retrieval purposes. + +Mathematically, truncated SVD applied to training samples :math:`X` +produces a low-rank approximation :math:`X`: + +.. math:: + X \approx X_k = U_k \Sigma_k V_k^\top + +After this operation, :math:`U_k \Sigma_k^\top` +is the transformed training set with :math:`k` features +(called ``n_components`` in the API). + +To also transform a test set :math:`X`, we multiply it with :math:`V_k`: + +.. math:: + X' = X V_k^\top + +.. note:: + Most treatments of LSA in the natural language processing (NLP) + and information retrieval (IR) literature + swap the axis of the matrix :math:`X` so that it has shape + ``n_features`` × ``n_samples``. + We present LSA in a different way that matches the scikit-learn API better, + but the singular values found are the same. + +:class:`TruncatedSVD` is very similar to :class:`PCA`, but differs +in that it works on sample matrices :math:`X` directly +instead of their covariance matrices. +When the columnwise (per-feature) means of :math:`X` +are subtracted from the feature values, +truncated SVD on the resulting matrix is equivalent to PCA. +In practical terms, this means +that the :class:`TruncatedSVD` transformer accepts ``scipy.sparse`` +matrices without the need to densify them, +as densifying may fill up memory even for medium-sized document collections. + +While the :class:`TruncatedSVD` transformer +works with any (sparse) feature matrix, +using it on tf–idf matrices is recommended over raw frequency counts +in an LSA/document processing setting. +In particular, sublinear scaling and inverse document frequency +should be turned on (``sublinear_tf=True, use_idf=True``) +to bring the feature values closer to a Gaussian distribution, +compensating for LSA's erroneous assumptions about textual data. + +.. topic:: Examples: + + * :ref:`example_text_document_clustering.py` + +.. topic:: References: + + * Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze (2008), + *Introduction to Information Retrieval*, Cambridge University Press, + chapter 18: `Matrix decompositions & latent semantic indexing + `_ + + .. _DictionaryLearning: Dictionary Learning @@ -244,11 +369,11 @@ Sparse coding with a precomputed dictionary The :class:`SparseCoder` object is an estimator that can be used to transform signals into sparse linear combination of atoms from a fixed, precomputed dictionary such as a discrete wavelet basis. This object therefore does not -implement a `fit` method. The transformation amounts +implement a ``fit`` method. The transformation amounts to a sparse coding problem: finding a representation of the data as a linear combination of as few dictionary atoms as possible. All variations of dictionary learning implement the following transform methods, controllable via -the `transform_method` initialization parameter: +the ``transform_method`` initialization parameter: * Orthogonal matching pursuit (:ref:`omp`) @@ -265,16 +390,17 @@ They have been shown useful in literature for classification tasks. For image reconstruction tasks, orthogonal matching pursuit yields the most accurate, unbiased reconstruction. -The dictionary learning objects offer, via the `split_code` parameter, the +The dictionary learning objects offer, via the ``split_code`` parameter, the possibility to separate the positive and negative values in the results of sparse coding. This is useful when dictionary learning is used for extracting features that will be used for supervised learning, because it allows the learning algorithm to assign different weights to negative loadings of a particular atom, from to the corresponding positive loading. -The split code for a single sample has length `2 * n_atoms` +The split code for a single sample has length ``2 * n_components`` and is constructed using the following rule: First, the regular code of length -`n_atoms` is computed. Then, the first `n_atoms` entries of the split_code are +``n_components`` is computed. Then, the first ``n_components`` entries of the +``split_code`` are filled with the positive part of the regular code vector. The second half of the split code is filled with the negative part of the code vector, only with a positive sign. Therefore, the split_code is non-negative. @@ -309,11 +435,11 @@ dictionary fixed, and then updating the dictionary to best fit the sparse code. 0 \leq k < n_{atoms} -.. |pca_img2| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_2.png +.. |pca_img2| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_002.png :target: ../auto_examples/decomposition/plot_faces_decomposition.html :scale: 60% -.. |dict_img2| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_6.png +.. |dict_img2| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_006.png :target: ../auto_examples/decomposition/plot_faces_decomposition.html :scale: 60% @@ -328,7 +454,7 @@ The following image shows how a dictionary learned from 4x4 pixel image patches extracted from part of the image of Lena looks like. -.. figure:: ../auto_examples/decomposition/images/plot_image_denoising_1.png +.. figure:: ../auto_examples/decomposition/images/plot_image_denoising_001.png :target: ../auto_examples/decomposition/plot_image_denoising.html :align: center :scale: 50% @@ -359,11 +485,119 @@ mini-batches and optimizes in an online manner by cycling over the mini-batches for the specified number of iterations. However, at the moment it does not implement a stopping condition. -The estimator also implements `partial_fit`, which updates the dictionary by +The estimator also implements ``partial_fit``, which updates the dictionary by iterating only once over a mini-batch. This can be used for online learning when the data is not readily available from the start, or for when the data does not fit into the memory. +.. currentmodule:: sklearn.cluster + +.. image:: ../auto_examples/cluster/images/plot_dict_face_patches_001.png + :target: ../auto_examples/cluster/plot_dict_face_patches.html + :scale: 50% + :align: right + +.. topic:: **Clustering for dictionary learning** + + Note that when using dictionary learning to extract a representation + (e.g. for sparse coding) clustering can be a good proxy to learn the + dictionary. For instance the :class:`MiniBatchKMeans` estimator is + computationally efficient and implements on-line learning with a + ``partial_fit`` method. + + Example: :ref:`example_cluster_plot_dict_face_patches.py` + +.. currentmodule:: sklearn.decomposition + +.. _FA: + +Factor Analysis +=============== + +In unsupervised learning we only have a dataset :math:`X = \{x_1, x_2, \dots, x_n +\}`. How can this dataset be described mathematically? A very simple +`continuous latent variabel` model for :math:`X` is + +.. math:: x_i = W h_i + \mu + \epsilon + +The vector :math:`h_i` is called "latent" because it is unobserved. :math:`\epsilon` is +considered a noise term distributed according to a Gaussian with mean 0 and +covariance :math:`\Psi` (i.e. :math:`\epsilon \sim \mathcal{N}(0, \Psi)`), :math:`\mu` is some +arbitrary offset vector. Such a model is called "generative" as it describes +how :math:`x_i` is generated from :math:`h_i`. If we use all the :math:`x_i`'s as columns to form +a matrix :math:`\mathbf{X}` and all the :math:`h_i`'s as columns of a matrix :math:`\mathbf{H}` +then we can write (with suitably defined :math:`\mathbf{M}` and :math:`\mathbf{E}`): + +.. math:: + \mathbf{X} = W \mathbf{H} + \mathbf{M} + \mathbf{E} + +In other words, we *decomposed* matrix :math:`\mathbf{X}`. + +If :math:`h_i` is given, the above equation automatically implies the following +probabilistic interpretation: + +.. math:: p(x_i|h_i) = \mathcal{N}(Wh_i + \mu, \Psi) + +For a complete probabilistic model we also need a prior distribution for the +latent variable :math:`h`. The most straightforward assumption (based on the nice +properties of the Gaussian distribution) is :math:`h \sim \mathcal{N}(0, +\mathbf{I})`. This yields a Gaussian as the marginal distribution of :math:`x`: + +.. math:: p(x) = \mathcal{N}(\mu, WW^T + \Psi) + +Now, without any further assumptions the idea of having a latent variable :math:`h` +would be superfluous -- :math:`x` can be completely modelled with a mean +and a covariance. We need to impose some more specific structure on one +of these two parameters. A simple additional assumption regards the +structure of the error covariance :math:`\Psi`: + +* :math:`\Psi = \sigma^2 \mathbf{I}`: This assumption leads to + the probabilistic model of :class:`PCA`. + +* :math:`\Psi = diag(\psi_1, \psi_2, \dots, \psi_n)`: This model is called Factor + Analysis, a classical statistical model. The matrix W is sometimes called + the "factor loading matrix". + +Both model essentially estimate a Gaussian with a low-rank covariance matrix. +Because both models are probabilistic they can be integrated in more complex +models, e.g. Mixture of Factor Analysers. One gets very different models (e.g. +:class:`FastICA`) if non-Gaussian priors on the latent variables are assumed. + +Factor analysis *can* produce similar components (the columns of its loading +matrix) to :class:`PCA`. However, one can not make any general statements +about these components (e.g. whether they are orthogonal): + +.. |pca_img3| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_002.png + :target: ../auto_examples/decomposition/plot_faces_decomposition.html + :scale: 60% + +.. |fa_img3| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_009.png + :target: ../auto_examples/decomposition/plot_faces_decomposition.html + :scale: 60% + +.. centered:: |pca_img3| |fa_img3| + +The main advantage for Factor Analysis (over :class:`PCA` is that +it can model the variance in every direction of the input space independently +(heteroscedastic noise): + +.. figure:: ../auto_examples/decomposition/images/plot_faces_decomposition_008.png + :target: ../auto_examples/decomposition/plot_faces_decomposition.html + :align: center + :scale: 75% + +This allows better model selection than probabilistic PCA in the presence +of heteroscedastic noise: + +.. figure:: ../auto_examples/decomposition/images/plot_pca_vs_fa_model_selection_002.png + :target: ../auto_examples/decomposition/plot_pca_vs_fa_model_selection.html + :align: center + :scale: 75% + + +.. topic:: Examples: + + * :ref:`example_decomposition_plot_pca_vs_fa_model_selection.py` .. _ICA: @@ -373,12 +607,16 @@ Independent component analysis (ICA) Independent component analysis separates a multivariate signal into additive subcomponents that are maximally independent. It is implemented in scikit-learn using the :class:`Fast ICA ` -algorithm. +algorithm. Typically, ICA is not used for reducing dimensionality but +for separating superimposed signals. Since the ICA model does not include +a noise term, for the model to be correct, whitening must be applied. +This can be done internally using the whiten argument or manually using one +of the PCA variants. It is classically used to separate mixed signals (a problem known as *blind source separation*), as in the example below: -.. figure:: ../auto_examples/decomposition/images/plot_ica_blind_source_separation_1.png +.. figure:: ../auto_examples/decomposition/images/plot_ica_blind_source_separation_001.png :target: ../auto_examples/decomposition/plot_ica_blind_source_separation.html :align: center :scale: 60% @@ -387,15 +625,15 @@ It is classically used to separate mixed signals (a problem known as ICA can also be used as yet another non linear decomposition that finds components with some sparsity: -.. |pca_img3| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_2.png +.. |pca_img4| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_002.png :target: ../auto_examples/decomposition/plot_faces_decomposition.html :scale: 60% -.. |ica_img3| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_4.png +.. |ica_img4| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_004.png :target: ../auto_examples/decomposition/plot_faces_decomposition.html :scale: 60% -.. centered:: |pca_img3| |ica_img3| +.. centered:: |pca_img4| |ica_img4| .. topic:: Examples: @@ -413,9 +651,20 @@ Non-negative matrix factorization (NMF or NNMF) data and the components are non-negative. :class:`NMF` can be plugged in instead of :class:`PCA` or its variants, in the cases where the data matrix does not contain negative values. +It finds a decomposition of samples :math:`X` +into two matrices :math:`W` and :math:`H` of non-negative elements, +by optimizing for the squared Frobenius norm: + +.. math:: + \arg\min_{W,H} ||X - WH||^2 = \sum_{i,j} X_{ij} - {WH}_{ij} + +This norm is an obvious extension of the Euclidean norm to matrices. +(Other optimization objectives have been suggested in the NMF literature, +in particular Kullback-Leibler divergence, +but these are not currently implemented.) Unlike :class:`PCA`, the representation of a vector is obtained in an additive -fashion, by superimposing the components, without substracting. Such additive +fashion, by superimposing the components, without subtracting. Such additive models are efficient for representing images and text. It has been observed in [Hoyer, 04] that, when carefully constrained, @@ -424,15 +673,15 @@ resulting in interpretable models. The following example displays 16 sparse components found by :class:`NMF` from the images in the Olivetti faces dataset, in comparison with the PCA eigenfaces. -.. |pca_img4| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_2.png +.. |pca_img5| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_002.png :target: ../auto_examples/decomposition/plot_faces_decomposition.html :scale: 60% -.. |nmf_img4| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_3.png +.. |nmf_img5| image:: ../auto_examples/decomposition/images/plot_faces_decomposition_003.png :target: ../auto_examples/decomposition/plot_faces_decomposition.html :scale: 60% -.. centered:: |pca_img4| |nmf_img4| +.. centered:: |pca_img5| |nmf_img5| The :attr:`init` attribute determines the initialization method applied, which @@ -447,12 +696,12 @@ to random perturbations less than the mean of the data divided by 100) are recommended in the dense case. :class:`NMF` can also be initialized with random non-negative matrices, by -passing an integer seed or a `RandomState` to :attr:`init`. +passing an integer seed or a ``RandomState`` to :attr:`init`. In :class:`NMF`, sparseness can be enforced by setting the attribute -:attr:`sparseness` to `data` or `components`. Sparse components lead to -localized features, and sparse data leads to a more efficient representation -of the data. +:attr:`sparseness` to ``"data"`` or ``"components"``. Sparse components lead to +localized features, and sparse data leads to a more efficient representation of +the data. .. topic:: Examples: @@ -462,11 +711,11 @@ of the data. .. topic:: References: * `"Learning the parts of objects by non-negative matrix factorization" - `_ + `_ D. Lee, S. Seung, 1999 * `"Non-negative Matrix Factorization with Sparseness Constraints" - `_ + `_ P. Hoyer, 2004 * `"Projected gradient methods for non-negative matrix factorization" @@ -475,6 +724,5 @@ of the data. * `"SVD based initialization: A head start for nonnegative matrix factorization" - `_ + `_ C. Boutsidis, E. Gallopoulos, 2008 - diff --git a/doc/modules/density.rst b/doc/modules/density.rst new file mode 100644 index 0000000000000..c9f5c271f7f15 --- /dev/null +++ b/doc/modules/density.rst @@ -0,0 +1,180 @@ +.. _density_estimation: + +================== +Density Estimation +================== +.. sectionauthor:: Jake Vanderplas + +Density estimation walks the line between unsupervised learning, feature +engineering, and data modeling. Some of the most popular and useful +density estimation techniques are mixture models such as +Gaussian Mixtures (:class:`sklearn.mixture.GMM`), and neighbor-based +approaches such as the kernel density estimate +(:class:`sklearn.neighbors.KernelDensity`). +Gaussian Mixtures are discussed more fully in the context of +:ref:`clustering `, because the technique is also useful as +an unsupervised clustering scheme. + +Density estimation is a very simple concept, and most people are already +familiar with one common density estimation technique: the histogram. + +Density Estimation: Histograms +============================== +A histogram is a simple visualization of data where bins are defined, and the +number of data points within each bin is tallied. An example of a histogram +can be seen in the upper-left panel of the following figure: + +.. |hist_to_kde| image:: ../auto_examples/neighbors/images/plot_kde_1d_001.png + :target: ../auto_examples/neighbors/plot_kde_1d.html + :scale: 80 + +.. centered:: |hist_to_kde| + +A major problem with histograms, however, is that the choice of binning can +have a disproportionate effect on the resulting visualization. Consider the +upper-right panel of the above figure. It shows a histogram over the same +data, with the bins shifted right. The results of the two visualizations look +entirely different, and might lead to different interpretations of the data. + +Intuitively, one can also think of a histogram as a stack of blocks, one block +per point. By stacking the blocks in the appropriate grid space, we recover +the histogram. But what if, instead of stacking the blocks on a regular grid, +we center each block on the point it represents, and sum the total height at +each location? This idea leads to the lower-left visualization. It is perhaps +not as clean as a histogram, but the fact that the data drive the block +locations mean that it is a much better representation of the underlying +data. + +This visualization is an example of a *kernel density estimation*, in this case +with a top-hat kernel (i.e. a square block at each point). We can recover a +smoother distribution by using a smoother kernel. The bottom-right plot shows +a Gaussian kernel density estimate, in which each point contributes a Gaussian +curve to the total. The result is a smooth density estimate which is derived +from the data, and functions as a powerful non-parametric model of the +distribution of points. + +.. _kernel_density: + +Kernel Density Estimation +========================= +Kernel density estimation in scikit-learn is implemented in the +:class:`sklearn.neighbors.KernelDensity` estimator, which uses the +Ball Tree or KD Tree for efficient queries (see :ref:`neighbors` for +a discussion of these). Though the above example +uses a 1D data set for simplicity, kernel density estimation can be +performed in any number of dimensions, though in practice the curse of +dimensionality causes its performance to degrade in high dimensions. + +In the following figure, 100 points are drawn from a bimodal distribution, +and the kernel density estimates are shown for three choices of kernels: + +.. |kde_1d_distribution| image:: ../auto_examples/neighbors/images/plot_kde_1d_003.png + :target: ../auto_examples/neighbors/plot_kde_1d.html + :scale: 80 + +.. centered:: |kde_1d_distribution| + +It's clear how the kernel shape affects the smoothness of the resulting +distribution. The scikit-learn kernel density estimator can be used as +follows: + + >>> from sklearn.neighbors.kde import KernelDensity + >>> import numpy as np + >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) + >>> kde = KernelDensity(kernel='gaussian', bandwidth=0.2).fit(X) + >>> kde.score_samples(X) + array([-0.41075698, -0.41075698, -0.41076071, -0.41075698, -0.41075698, + -0.41076071]) + +Here we have used ``kernel='gaussian'``, as seen above. +Mathematically, a kernel is a positive function :math:`K(x;h)` +which is controlled by the bandwidth parameter :math:`h`. +Given this kernel form, the density estimate at a point :math:`y` within +a group of points :math:`x_i; i=1\cdots N` is given by: + +.. math:: + \rho_K(y) = \sum_{i=1}^{N} K((y - x_i) / h) + +The bandwidth here acts as a smoothing parameter, controlling the tradeoff +between bias and variance in the result. A large bandwidth leads to a very +smooth (i.e. high-bias) density distribution. A small bandwidth leads +to an unsmooth (i.e. high-variance) density distribution. + +:class:`sklearn.neighbors.KernelDensity` implements several common kernel +forms, which are shown in the following figure: + +.. |kde_kernels| image:: ../auto_examples/neighbors/images/plot_kde_1d_002.png + :target: ../auto_examples/neighbors/plot_kde_1d.html + :scale: 80 + +.. centered:: |kde_kernels| + +The form of these kernels is as follows: + +* Gaussian kernel (``kernel = 'gaussian'``) + + :math:`K(x; h) \propto \exp(- \frac{x^2}{2h^2} )` + +* Tophat kernel (``kernel = 'tophat'``) + + :math:`K(x; h) \propto 1` if :math:`x < h` + +* Epanechnikov kernel (``kernel = 'epanechnikov'``) + + :math:`K(x; h) \propto 1 - \frac{x^2}{h^2}` + +* Exponential kernel (``kernel = 'exponential'``) + + :math:`K(x; h) \propto \exp(-x/h)` + +* Linear kernel (``kernel = 'linear'``) + + :math:`K(x; h) \propto 1 - x/h` if :math:`x < h` + +* Cosine kernel (``kernel = 'cosine'``) + + :math:`K(x; h) \propto \cos(\frac{\pi x}{2h})` if :math:`x < h` + +The kernel density estimator can be used with any of the valid distance +metrics (see :class:`sklearn.neighbors.DistanceMetric` for a list of available metrics), though +the results are properly normalized only for the Euclidean metric. One +particularly useful metric is the +`Haversine distance `_ +which measures the angular distance between points on a sphere. Here +is an example of using a kernel density estimate for a visualization +of geospatial data, in this case the distribution of observations of two +different species on the South American continent: + +.. |species_kde| image:: ../auto_examples/neighbors/images/plot_species_kde_001.png + :target: ../auto_examples/neighbors/plot_species_kde.html + :scale: 80 + +.. centered:: |species_kde| + +One other useful application of kernel density estimation is to learn a +non-parametric generative model of a dataset in order to efficiently +draw new samples from this generative model. +Here is an example of using this process to +create a new set of hand-written digits, using a Gaussian kernel learned +on a PCA projection of the data: + +.. |digits_kde| image:: ../auto_examples/neighbors/images/plot_digits_kde_sampling_001.png + :target: ../auto_examples/neighbors/plot_digits_kde_sampling.html + :scale: 80 + +.. centered:: |digits_kde| + +The "new" data consists of linear combinations of the input data, with weights +probabilistically drawn given the KDE model. + +.. topic:: Examples: + + * :ref:`example_neighbors_plot_kde_1d.py`: computation of simple kernel + density estimates in one dimension. + + * :ref:`example_neighbors_plot_digits_kde_sampling.py`: an example of using + Kernel Density estimation to learn a generative model of the hand-written + digits data, and drawing new samples from this model. + + * :ref:`example_neighbors_plot_species_kde.py`: an example of Kernel Density + estimation using the Haversine distance metric to visualize geospatial data diff --git a/doc/modules/dp-derivation.rst b/doc/modules/dp-derivation.rst index 3e4d1b2d7c048..861ce00fe0f39 100644 --- a/doc/modules/dp-derivation.rst +++ b/doc/modules/dp-derivation.rst @@ -1,4 +1,3 @@ - .. _dpgmm_derivation: .. currentmodule:: sklearn.mixture @@ -29,9 +28,9 @@ not for you. The complexity of this implementation is linear in the number of mixture components and data points. With regards to the -dimensionality, it is linear when using `spherical` or `diag` and -quadratic/cubic when using `tied` or `full`. For `spherical` or `diag` -it is O(n_states * n_points * dimension) and for `tied` or `full` it +dimensionality, it is linear when using ``spherical`` or ``diag`` and +quadratic/cubic when using ``tied`` or ``full``. For ``spherical`` or ``diag`` +it is O(n_states * n_points * dimension) and for ``tied`` or ``full`` it is O(n_states * n_points * dimension^2 + n_states * dimension^3) (it is necessary to invert the covariance/precision matrices and compute its determinant, hence the cubic term). @@ -49,7 +48,7 @@ proportion :math:`\phi_k`, the mean parameters :math:`\mu_k`, the covariance parameters :math:`\Sigma_k`, which is characterized by variational Wishart density, :math:`Wishart(a_k, \mathbf{B_k})`, where :math:`a` is the degrees of freedom, and :math:`B` is the -scale matrix. Depending on the covariance parameterization, +scale matrix. Depending on the covariance parametrization, :math:`B_k` can be a positive scalar, a positive vector or a Symmetric Positive Definite matrix. @@ -157,7 +156,7 @@ distribution. && E_q[\log P(z)] - E_q[\log Q(z)] \\ &=& \sum_{k} \left( - \left(\sum_{j=k+1}^K \nu_{z_{i,j}}\right)(\Psi(\gamma{k,1})-\Psi(\gamma{k,1}+\gamma_{k,2})) + \left(\sum_{j=k+1}^K \nu_{z_{i,j}}\right)(\Psi(\gamma_{k,2})-\Psi(\gamma_{k,1}+\gamma_{k,2})) + \nu_{z_{i,k}}(\Psi(\gamma_{k,1})-\Psi(\gamma_{k,1}+\gamma_{k,2})) - \log \nu_{z_{i,k}} \right) \end{array} @@ -195,8 +194,8 @@ The updates The updates for mu essentially are just weighted expectations of :math:`X` regularized by the prior. We can see this by taking the -gradient of the bound w.r.t. :math:`\nu_{\mu}` and setting it to zero. The -gradient is +gradient of the bound with regards to :math:`\nu_{\mu}` and setting it to zero. +The gradient is .. math:: @@ -287,7 +286,7 @@ distributions of :math:`\sigma` (as there are a lot more :math:`\sigma` s now) and :math:`X`. The bound for :math:`\sigma_{k,d}` is the same bound for :math:`\sigma_k` and can -be safelly ommited. +be safely omitted. **The bound for** :math:`X` : diff --git a/doc/modules/ensemble.rst b/doc/modules/ensemble.rst index e619ff4fd6443..8a717755149e1 100644 --- a/doc/modules/ensemble.rst +++ b/doc/modules/ensemble.rst @@ -7,25 +7,93 @@ Ensemble methods .. currentmodule:: sklearn.ensemble The goal of **ensemble methods** is to combine the predictions of several -models built with a given learning algorithm in order to improve -generalizability / robustness over a single model. +base estimators built with a given learning algorithm in order to improve +generalizability / robustness over a single estimator. Two families of ensemble methods are usually distinguished: - In **averaging methods**, the driving principle is to build several - models independently and then to average their predictions. On average, - the combined model is usually better than any of the single model - because its variance is reduced. + estimators independently and then to average their predictions. On average, + the combined estimator is usually better than any of the single base + estimator because its variance is reduced. - **Examples:** Bagging methods, :ref:`Forests of randomized trees `... + **Examples:** :ref:`Bagging methods `, :ref:`Forests of randomized trees `, ... -- By contrast, in **boosting methods**, models are built sequentially and one - tries to reduce the bias of the combined model. The motivation is to combine - several weak models to produce a powerful ensemble. +- By contrast, in **boosting methods**, base estimators are built sequentially + and one tries to reduce the bias of the combined estimator. The motivation is + to combine several weak models to produce a powerful ensemble. - **Examples:** AdaBoost, Least Squares Boosting, :ref:`Gradient Tree Boosting `, ... + **Examples:** :ref:`AdaBoost `, :ref:`Gradient Tree Boosting `, ... +.. _bagging: + +Bagging meta-estimator +====================== + +In ensemble algorithms, bagging methods form a class of algorithms which build +several instances of a black-box estimator on random subsets of the original +training set and then aggregate their individual predictions to form a final +prediction. These methods are used as a way to reduce the variance of a base +estimator (e.g., a decision tree), by introducing randomization into its +construction procedure and then making an ensemble out of it. In many cases, +bagging methods constitute a very simple way to improve with respect to a +single model, without making it necessary to adapt the underlying base +algorithm. As they provide a way to reduce overfitting, bagging methods work +best with strong and complex models (e.g., fully developed decision trees), in +contrast with boosting methods which usually work best with weak models (e.g., +shallow decision trees). + +Bagging methods come in many flavours but mostly differ from each other by the +way they draw random subsets of the training set: + + * When random subsets of the dataset are drawn as random subsets of the + samples, then this algorithm is known as Pasting [B1999]_. + + * When samples are drawn with replacement, then the method is known as + Bagging [B1996]_. + + * When random subsets of the dataset are drawn as random subsets of + the features, then the method is known as Random Subspaces [H1998]_. + + * Finally, when base estimators are built on subsets of both samples and + features, then the method is known as Random Patches [LG2012]_. + +In scikit-learn, bagging methods are offered as a unified +:class:`BaggingClassifier` meta-estimator (resp. :class:`BaggingRegressor`), +taking as input a user-specified base estimator along with parameters +specifying the strategy to draw random subsets. In particular, ``max_samples`` +and ``max_features`` control the size of the subsets (in terms of samples and +features), while ``bootstrap`` and ``bootstrap_features`` control whether +samples and features are drawn with or without replacement. As an example, the +snippet below illustrates how to instantiate a bagging ensemble of +:class:`KNeighborsClassifier` base estimators, each built on random subsets of +50% of the samples and 50% of the features. + + >>> from sklearn.ensemble import BaggingClassifier + >>> from sklearn.neighbors import KNeighborsClassifier + >>> bagging = BaggingClassifier(KNeighborsClassifier(), + ... max_samples=0.5, max_features=0.5) + +.. topic:: Examples: + + * :ref:`example_ensemble_plot_bias_variance.py` + +.. topic:: References + + .. [B1999] L. Breiman, "Pasting small votes for classification in large + databases and on-line", Machine Learning, 36(1), 85-103, 1999. + + .. [B1996] L. Breiman, "Bagging predictors", Machine Learning, 24(2), + 123-140, 1996. + + .. [H1998] T. Ho, "The random subspace method for constructing decision + forests", Pattern Analysis and Machine Intelligence, 20(8), 832-844, + 1998. + + .. [LG2012] G. Louppe and P. Geurts, "Ensembles on Random Patches", + Machine Learning and Knowledge Discovery in Databases, 346-361, 2012. + .. _forest: Forests of randomized trees @@ -40,7 +108,7 @@ construction. The prediction of the ensemble is given as the averaged prediction of the individual classifiers. As other classifiers, forest classifiers have to be fitted with two -arrays: an array X of size ``[n_samples, n_features]`` holding the +arrays: a sparse or dense array X of size ``[n_samples, n_features]`` holding the training samples, and an array Y of size ``[n_samples]`` holding the target values (class labels) for the training samples:: @@ -54,7 +122,6 @@ Like :ref:`decision trees `, forests of trees also extend to :ref:`multi-output problems ` (if Y is an array of size ``[n_samples, n_outputs]``). - Random Forests -------------- @@ -74,7 +141,6 @@ In contrast to the original publication [B2001]_, the scikit-learn implementation combines classifiers by averaging their probabilistic prediction, instead of letting each classifier vote for a single class. - Extremely Randomized Trees -------------------------- @@ -115,7 +181,7 @@ in bias:: >>> scores.mean() > 0.999 True -.. figure:: ../auto_examples/ensemble/images/plot_forest_iris_1.png +.. figure:: ../auto_examples/ensemble/images/plot_forest_iris_001.png :target: ../auto_examples/ensemble/plot_forest_iris.html :align: center :scale: 75% @@ -130,22 +196,17 @@ addition, note that results will stop getting significantly better beyond a critical number of trees. The latter is the size of the random subsets of features to consider when splitting a node. The lower the greater the reduction of variance, but also the greater the increase in -bias. Empiricial good default values are ``max_features=n_features`` +bias. Empirical good default values are ``max_features=n_features`` for regression problems, and ``max_features=sqrt(n_features)`` for classification tasks (where ``n_features`` is the number of features -in the data). The best results are also usually reached when setting -``max_depth=None`` in combination with ``min_samples_split=1`` (i.e., -when fully developping the trees). Bear in mind though that these values -are usually not optimal. The best parameter values should always be cross- -validated. In addition, note that bootstrap samples are used by default -in random forests (``bootstrap=True``) while the default strategy is to -use the original dataset for building extra-trees (``bootstrap=False``). - -When training on large datasets, where runtime and memory requirements -are important, it might also be beneficial to adjust the ``min_density`` -parameter, that controls a heuristic for speeding up computations in -each tree. See :ref:`Complexity of trees` for details. - +in the data). Good results are often achieved when setting ``max_depth=None`` +in combination with ``min_samples_split=1`` (i.e., when fully developing the +trees). Bear in mind though that these values are usually not optimal, and +might result in models that consume a lot of ram. The best parameter values +should always be cross-validated. In addition, note that in random forests, +bootstrap samples are used by default (``bootstrap=True``) +while the default strategy for extra-trees is to use the whole dataset +(``bootstrap=False``). Parallelization --------------- @@ -165,18 +226,18 @@ amount of time (e.g., on large datasets). * :ref:`example_ensemble_plot_forest_iris.py` * :ref:`example_ensemble_plot_forest_importances_faces.py` - * :ref:`example_ensemble_plot_forest_multioutput.py` - + * :ref:`example_plot_multioutput_face_completion.py` .. topic:: References - .. [B2001] Leo Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001. + .. [B2001] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001. - .. [B1998] Leo Breiman, "Arcing Classifiers", Annals of Statistics 1998. + .. [B1998] L. Breiman, "Arcing Classifiers", Annals of Statistics 1998. - .. [GEW2006] Pierre Geurts, Damien Ernst., and Louis Wehenkel, "Extremely randomized + .. [GEW2006] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. +.. _random_forest_feature_importance: Feature importance evaluation ----------------------------- @@ -197,25 +258,148 @@ The following example shows a color-coded representation of the relative importances of each individual pixel for a face recognition task using a :class:`ExtraTreesClassifier` model. -.. figure:: ../auto_examples/ensemble/images/plot_forest_importances_faces_1.png +.. figure:: ../auto_examples/ensemble/images/plot_forest_importances_faces_001.png :target: ../auto_examples/ensemble/plot_forest_importances_faces.html :align: center :scale: 75 - -In practice those estimates can be computed by explicitly passing -``compute_importances=True`` to the constructor of the decision trees, -random forest and extremly randomized trees models. The result is stored -as an attribute named ``features_importances_`` on the fitted model. This -is an array with shape ``(n_features,)`` whose values are positive and sum -to 1.0. The higher the value, the more important is the contribution of -the matching feature to the prediction function. +In practice those estimates are stored as an attribute named +``feature_importances_`` on the fitted model. This is an array with shape +``(n_features,)`` whose values are positive and sum to 1.0. The higher +the value, the more important is the contribution of the matching feature +to the prediction function. .. topic:: Examples: * :ref:`example_ensemble_plot_forest_importances_faces.py` * :ref:`example_ensemble_plot_forest_importances.py` +.. _random_trees_embedding: + +Totally Random Trees Embedding +------------------------------ + +:class:`RandomTreesEmbedding` implements an unsupervised transformation of the +data. Using a forest of completely random trees, :class:`RandomTreesEmbedding` +encodes the data by the indices of the leaves a data point ends up in. This +index is then encoded in a one-of-K manner, leading to a high dimensional, +sparse binary coding. +This coding can be computed very efficiently and can then be used as a basis +for other learning tasks. +The size and sparsity of the code can be influenced by choosing the number of +trees and the maximum depth per tree. For each tree in the ensemble, the coding +contains one entry of one. The size of the coding is at most ``n_estimators * 2 +** max_depth``, the maximum number of leaves in the forest. + +As neighboring data points are more likely to lie within the same leaf of a tree, +the transformation performs an implicit, non-parametric density estimation. + +.. topic:: Examples: + + * :ref:`example_ensemble_plot_random_forest_embedding.py` + + * :ref:`example_manifold_plot_lle_digits.py` compares non-linear + dimensionality reduction techniques on handwritten digits. + +.. seealso:: + + :ref:`manifold` techniques can also be useful to derive non-linear + representations of feature space, also these approaches focus also on + dimensionality reduction. + + +.. _adaboost: + +AdaBoost +======== + +The module :mod:`sklearn.ensemble` includes the popular boosting algorithm +AdaBoost, introduced in 1995 by Freund and Schapire [FS1995]_. + +The core principle of AdaBoost is to fit a sequence of weak learners (i.e., +models that are only slightly better than random guessing, such as small +decision trees) on repeatedly modified versions of the data. The predictions +from all of them are then combined through a weighted majority vote (or sum) to +produce the final prediction. The data modifications at each so-called boosting +iteration consist of applying weights :math:`w_1`, :math:`w_2`, ..., :math:`w_N` +to each of the training samples. Initially, those weights are all set to +:math:`w_i = 1/N`, so that the first step simply trains a weak learner on the +original data. For each successive iteration, the sample weights are +individually modified and the learning algorithm is reapplied to the reweighted +data. At a given step, those training examples that were incorrectly predicted +by the boosted model induced at the previous step have their weights increased, +whereas the weights are decreased for those that were predicted correctly. As +iterations proceed, examples that are difficult to predict receive +ever-increasing influence. Each subsequent weak learner is thereby forced to +concentrate on the examples that are missed by the previous ones in the sequence +[HTF]_. + +.. figure:: ../auto_examples/ensemble/images/plot_adaboost_hastie_10_2_001.png + :target: ../auto_examples/ensemble/plot_adaboost_hastie_10_2.html + :align: center + :scale: 75 + +AdaBoost can be used both for classification and regression problems: + + - For multi-class classification, :class:`AdaBoostClassifier` implements + AdaBoost-SAMME and AdaBoost-SAMME.R [ZZRH2009]_. + + - For regression, :class:`AdaBoostRegressor` implements AdaBoost.R2 [D1997]_. + +Usage +----- + +The following example shows how to fit an AdaBoost classifier with 100 weak +learners:: + + >>> from sklearn.cross_validation import cross_val_score + >>> from sklearn.datasets import load_iris + >>> from sklearn.ensemble import AdaBoostClassifier + + >>> iris = load_iris() + >>> clf = AdaBoostClassifier(n_estimators=100) + >>> scores = cross_val_score(clf, iris.data, iris.target) + >>> scores.mean() # doctest: +ELLIPSIS + 0.9... + +The number of weak learners is controlled by the parameter ``n_estimators``. The +``learning_rate`` parameter controls the contribution of the weak learners in +the final combination. By default, weak learners are decision stumps. Different +weak learners can be specified through the ``base_estimator`` parameter. +The main parameters to tune to obtain good results are ``n_estimators`` and +the complexity of the base estimators (e.g., its depth ``max_depth`` or +minimum required number of samples at a leaf ``min_samples_leaf`` in case of +decision trees). + +.. topic:: Examples: + + * :ref:`example_ensemble_plot_adaboost_hastie_10_2.py` compares the + classification error of a decision stump, decision tree, and a boosted + decision stump using AdaBoost-SAMME and AdaBoost-SAMME.R. + + * :ref:`example_ensemble_plot_adaboost_multiclass.py` shows the performance + of AdaBoost-SAMME and AdaBoost-SAMME.R on a multi-class problem. + + * :ref:`example_ensemble_plot_adaboost_twoclass.py` shows the decision boundary + and decision function values for a non-linearly separable two-class problem + using AdaBoost-SAMME. + + * :ref:`example_ensemble_plot_adaboost_regression.py` demonstrates regression + with the AdaBoost.R2 algorithm. + +.. topic:: References + + .. [FS1995] Y. Freund, and R. Schapire, "A Decision-Theoretic Generalization of + On-Line Learning and an Application to Boosting", 1997. + + .. [ZZRH2009] J. Zhu, H. Zou, S. Rosset, T. Hastie. "Multi-class AdaBoost", + 2009. + + .. [D1997] H. Drucker. "Improving Regressors using Boosting Techniques", 1997. + + .. [HTF] T. Hastie, R. Tibshirani and J. Friedman, "Elements of + Statistical Learning Ed. 2", Springer, 2009. + .. _gradient_boosting: @@ -236,7 +420,7 @@ The advantages of GBRT are: + Predictive power - + Robustness to outliers in input space (via robust loss functions) + + Robustness to outliers in output space (via robust loss functions) The disadvantages of GBRT are: @@ -251,7 +435,7 @@ Classification --------------- :class:`GradientBoostingClassifier` supports both binary and multi-class -classification via the deviance loss function (``loss='deviance'``). +classification. The following example shows how to fit a gradient boosting classifier with 100 decision stumps as weak learners:: @@ -262,15 +446,12 @@ with 100 decision stumps as weak learners:: >>> X_train, X_test = X[:2000], X[2000:] >>> y_train, y_test = y[:2000], y[2000:] - >>> clf = GradientBoostingClassifier(n_estimators=100, learn_rate=1.0, + >>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0, ... max_depth=1, random_state=0).fit(X_train, y_train) >>> clf.score(X_test, y_test) # doctest: +ELLIPSIS 0.913... -The number of weak learners (i.e. regression trees) is controlled by the -parameter ``n_estimators``; The maximum depth of each tree is controlled via -``max_depth``. The ``learn_rate`` is a hyper-parameter in the range (0.0, 1.0] -that controls overfitting via :ref:`shrinkage `. +The number of weak learners (i.e. regression trees) is controlled by the parameter ``n_estimators``; :ref:`The size of each tree ` can be controlled either by setting the tree depth via ``max_depth`` or by setting the number of leaf nodes via ``max_leaf_nodes``. The ``learning_rate`` is a hyper-parameter in the range (0.0, 1.0] that controls overfitting via :ref:`shrinkage ` . .. note:: @@ -279,7 +460,7 @@ that controls overfitting via :ref:`shrinkage `. thus, the total number of induced trees equals ``n_classes * n_estimators``. For datasets with a large number of classes we strongly recommend to use - :class:`RandomForestClassifier` as an alternative to GBRT. + :class:`RandomForestClassifier` as an alternative to :class:`GradientBoostingClassifier` . Regression ---------- @@ -287,7 +468,7 @@ Regression :class:`GradientBoostingRegressor` supports a number of :ref:`different loss functions ` for regression which can be specified via the argument -``loss`` which defaults to least squares (``'ls'``). +``loss``; the default loss function for regression is least squares (``'ls'``). :: @@ -299,24 +480,78 @@ for regression which can be specified via the argument >>> X, y = make_friedman1(n_samples=1200, random_state=0, noise=1.0) >>> X_train, X_test = X[:200], X[200:] >>> y_train, y_test = y[:200], y[200:] - >>> clf = GradientBoostingRegressor(n_estimators=100, learn_rate=1.0, + >>> est = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, ... max_depth=1, random_state=0, loss='ls').fit(X_train, y_train) - >>> mean_squared_error(y_test, clf.predict(X_test)) # doctest: +ELLIPSIS - 6.90... + >>> mean_squared_error(y_test, est.predict(X_test)) # doctest: +ELLIPSIS + 5.00... The figure below shows the results of applying :class:`GradientBoostingRegressor` -with least squares loss and 500 base learners to the Boston house-price dataset -(see :func:`sklearn.datasets.load_boston`). +with least squares loss and 500 base learners to the Boston house price dataset +(:func:`sklearn.datasets.load_boston`). The plot on the left shows the train and test error at each iteration. -Plots like these are often used for early stopping. The plot on the right -shows the feature importances which can be optained via the ``feature_importance`` -property. - -.. figure:: ../auto_examples/ensemble/images/plot_gradient_boosting_regression_1.png +The train error at each iteration is stored in the +:attr:`~GradientBoostingRegressor.train_score_` attribute +of the gradient boosting model. The test error at each iterations can be obtained +via the :meth:`~GradientBoostingRegressor.staged_predict` method which returns a +generator that yields the predictions at each stage. Plots like these can be used +to determine the optimal number of trees (i.e. ``n_estimators``) by early stopping. +The plot on the right shows the feature importances which can be obtained via +the ``feature_importances_`` property. + +.. figure:: ../auto_examples/ensemble/images/plot_gradient_boosting_regression_001.png :target: ../auto_examples/ensemble/plot_gradient_boosting_regression.html :align: center :scale: 75 +.. topic:: Examples: + + * :ref:`example_ensemble_plot_gradient_boosting_regression.py` + * :ref:`example_ensemble_plot_gradient_boosting_oob.py` + +.. _gradient_boosting_warm_start: + +Fitting additional weak-learners +-------------------------------- + +Both :class:`GradientBoostingRegressor` and :class:`GradientBoostingClassifier` +support ``warm_start=True`` which allows you to add more estimators to an already +fitted model. + +:: + + >>> _ = est.set_params(n_estimators=200, warm_start=True) # set warm_start and new nr of trees + >>> _ = est.fit(X_train, y_train) # fit additional 100 trees to est + >>> mean_squared_error(y_test, est.predict(X_test)) # doctest: +ELLIPSIS + 3.84... + +.. _gradient_boosting_tree_size: + +Controlling the tree size +------------------------- + +The size of the regression tree base learners defines the level of variable +interactions that can be captured by the gradient boosting model. In general, +a tree of depth ``h`` can capture interactions of order ``h`` . +There are two ways in which the size of the individual regression trees can +be controlled. + +If you specify ``max_depth=h`` then complete binary trees +of depth ``h`` will be grown. Such trees will have (at most) ``2**h`` leaf nodes +and ``2**h - 1`` split nodes. + +Alternatively, you can control the tree size by specifying the number of +leaf nodes via the parameter ``max_leaf_nodes``. In this case, +trees will be grown using best-first search where nodes with the highest improvement +in impurity will be expanded first. +A tree with ``max_leaf_nodes=k`` has ``k - 1`` split nodes and thus can +model interactions of up to order ``max_leaf_nodes - 1`` . + +We found that ``max_leaf_nodes=k`` gives comparable results to ``max_depth=k-1`` +but is significantly faster to train at the expense of a slightly higher +training error. +The parameter ``max_leaf_nodes`` corresponds to the variable ``J`` in the +chapter on gradient boosting in [F2001]_ and is related to the parameter +``interaction.depth`` in R's gbm package where ``max_leaf_nodes == interaction.depth + 1`` . Mathematical formulation ------------------------- @@ -341,8 +576,8 @@ a forward stagewise fashion: F_m(x) = F_{m-1}(x) + \gamma_m h_m(x) -At each stage the decision tree :math:`h_m(x)` is choosen that -minimizes the loss function :math:`L` given the current model +At each stage the decision tree :math:`h_m(x)` is chosen to +minimize the loss function :math:`L` given the current model :math:`F_{m-1}` and its fit :math:`F_{m-1}(x_i)` .. math:: @@ -367,7 +602,7 @@ loss function: F_m(x) = F_{m-1}(x) + \gamma_m \sum_{i=1}^{n} \nabla_F L(y_i, F_{m-1}(x_i)) -Where the step length :math:`\gamma_m` is choosen using line search: +Where the step length :math:`\gamma_m` is chosen using line search: .. math:: @@ -395,8 +630,8 @@ the parameter ``loss``: target values. * Huber (``'huber'``): Another robust loss function that combines least squares and least absolute deviation; use ``alpha`` to - control the sensitivity w.r.t. outliers (see [F2001]_ for more - details). + control the sensitivity with regards to outliers (see [F2001]_ for + more details). * Quantile (``'quantile'``): A loss function for quantile regression. Use ``0 < alpha < 1`` to specify the quantile. This loss function can be used to create prediction intervals @@ -415,6 +650,10 @@ the parameter ``loss``: prior probability of each class. At each iteration ``n_classes`` regression trees have to be constructed which makes GBRT rather inefficient for data sets with a large number of classes. + * Exponential loss (``'exponential'``): The same loss function + as :class:`AdaBoostClassifier`. Less robust to mislabeled + examples than ``'deviance'``; can only be used for binary + classification. Regularization ---------------- @@ -433,17 +672,17 @@ the contribution of each weak learner by a factor :math:`\nu`: The parameter :math:`\nu` is also called the **learning rate** because it scales the step length the the gradient descent procedure; it can -be set via the ``learn_rate`` parameter. +be set via the ``learning_rate`` parameter. -The parameter ``learn_rate`` strongly interacts with the parameter +The parameter ``learning_rate`` strongly interacts with the parameter ``n_estimators``, the number of weak learners to fit. Smaller values -of ``learn_rate`` require larger numbers of weak learners to maintain +of ``learning_rate`` require larger numbers of weak learners to maintain a constant training error. Empirical evidence suggests that small -values of ``learn_rate`` favor better test error. [HTF2009]_ +values of ``learning_rate`` favor better test error. [HTF2009]_ recommend to set the learning rate to a small constant -(e.g. ``learn_rate <= 0.1``) and choose ``n_estimators`` by early +(e.g. ``learning_rate <= 0.1``) and choose ``n_estimators`` by early stopping. For a more detailed discussion of the interaction between -``learn_rate`` and ``n_estimators`` see [R2007]_. +``learning_rate`` and ``n_estimators`` see [R2007]_. Subsampling ............ @@ -460,25 +699,188 @@ outperforms no-shrinkage. Subsampling with shrinkage can further increase the accuracy of the model. Subsampling without shrinkage, on the other hand, does poorly. -.. figure:: ../auto_examples/ensemble/images/plot_gradient_boosting_regularization_1.png +.. figure:: ../auto_examples/ensemble/images/plot_gradient_boosting_regularization_001.png :target: ../auto_examples/ensemble/plot_gradient_boosting_regularization.html :align: center :scale: 75 -For ``subsample < 1``, the deviance on the out-of-bag samples in the i-the iteration -is stored in the attribute ``oob_score_[i]``. Out-of-bag estimates can be -used for model selection (e.g. to determine the optimal number of iterations). - Another strategy to reduce the variance is by subsampling the features -analogous to the random splits in Random Forests. The size of the subsample -can be controled via the ``max_features`` parameter. +analogous to the random splits in :class:`RandomForestClassifier` . +The number of subsampled features can be controlled via the ``max_features`` +parameter. + +.. note:: Using a small ``max_features`` value can significantly decrease the runtime. + +Stochastic gradient boosting allows to compute out-of-bag estimates of the +test deviance by computing the improvement in deviance on the examples that are +not included in the bootstrap sample (i.e. the out-of-bag examples). +The improvements are stored in the attribute +:attr:`~GradientBoostingRegressor.oob_improvement_`. ``oob_improvement_[i]`` holds +the improvement in terms of the loss on the OOB samples if you add the i-th stage +to the current predictions. +Out-of-bag estimates can be used for model selection, for example to determine +the optimal number of iterations. OOB estimates are usually very pessimistic thus +we recommend to use cross-validation instead and only use OOB if cross-validation +is too time consuming. +.. topic:: Examples: + + * :ref:`example_ensemble_plot_gradient_boosting_regularization.py` + * :ref:`example_ensemble_plot_gradient_boosting_oob.py` + +Interpretation +-------------- + +Individual decision trees can be interpreted easily by simply +visualizing the tree structure. Gradient boosting models, however, +comprise hundreds of regression trees thus they cannot be easily +interpreted by visual inspection of the individual trees. Fortunately, +a number of techniques have been proposed to summarize and interpret +gradient boosting models. + +Feature importance +.................. + +Often features do not contribute equally to predict the target +response; in many situations the majority of the features are in fact +irrelevant. +When interpreting a model, the first question usually is: what are +those important features and how do they contributing in predicting +the target response? + +Individual decision trees intrinsically perform feature selection by selecting +appropriate split points. This information can be used to measure the +importance of each feature; the basic idea is: the more often a +feature is used in the split points of a tree the more important that +feature is. This notion of importance can be extended to decision tree +ensembles by simply averaging the feature importance of each tree (see +:ref:`random_forest_feature_importance` for more details). + +The feature importance scores of a fit gradient boosting model can be +accessed via the ``feature_importances_`` property:: + + >>> from sklearn.datasets import make_hastie_10_2 + >>> from sklearn.ensemble import GradientBoostingClassifier + + >>> X, y = make_hastie_10_2(random_state=0) + >>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0, + ... max_depth=1, random_state=0).fit(X, y) + >>> clf.feature_importances_ # doctest: +ELLIPSIS + array([ 0.11, 0.1 , 0.11, ... .. topic:: Examples: * :ref:`example_ensemble_plot_gradient_boosting_regression.py` - * :ref:`example_ensemble_plot_gradient_boosting_regularization.py` - * :ref:`example_ensemble_plot_gradient_boosting_quantile.py` + +.. currentmodule:: sklearn.ensemble.partial_dependence + +Partial dependence +.................. + +Partial dependence plots (PDP) show the dependence between the target response +and a set of 'target' features, marginalizing over the +values of all other features (the 'complement' features). +Intuitively, we can interpret the partial dependence as the expected +target response [1]_ as a function of the 'target' features [2]_. + +Due to the limits of human perception the size of the target feature +set must be small (usually, one or two) thus the target features are +usually chosen among the most important features. + +The Figure below shows four one-way and one two-way partial dependence plots +for the California housing dataset: + +.. figure:: ../auto_examples/ensemble/images/plot_partial_dependence_001.png + :target: ../auto_examples/ensemble/plot_partial_dependence.html + :align: center + :scale: 70 + +One-way PDPs tell us about the interaction between the target +response and the target feature (e.g. linear, non-linear). +The upper left plot in the above Figure shows the effect of the +median income in a district on the median house price; we can +clearly see a linear relationship among them. + +PDPs with two target features show the +interactions among the two features. For example, the two-variable PDP in the +above Figure shows the dependence of median house price on joint +values of house age and avg. occupants per household. We can clearly +see an interaction between the two features: +For an avg. occupancy greater than two, the house price is nearly independent +of the house age, whereas for values less than two there is a strong dependence +on age. + +The module :mod:`partial_dependence` provides a convenience function +:func:`~sklearn.ensemble.partial_dependence.plot_partial_dependence` +to create one-way and two-way partial dependence plots. In the below example +we show how to create a grid of partial dependence plots: two one-way +PDPs for the features ``0`` and ``1`` and a two-way PDP between the two +features:: + + >>> from sklearn.datasets import make_hastie_10_2 + >>> from sklearn.ensemble import GradientBoostingClassifier + >>> from sklearn.ensemble.partial_dependence import plot_partial_dependence + + >>> X, y = make_hastie_10_2(random_state=0) + >>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0, + ... max_depth=1, random_state=0).fit(X, y) + >>> features = [0, 1, (0, 1)] + >>> fig, axs = plot_partial_dependence(clf, X, features) #doctest: +SKIP + +For multi-class models, you need to set the class label for which the +PDPs should be created via the ``label`` argument:: + + >>> from sklearn.datasets import load_iris + >>> iris = load_iris() + >>> mc_clf = GradientBoostingClassifier(n_estimators=10, + ... max_depth=1).fit(iris.data, iris.target) + >>> features = [3, 2, (3, 2)] + >>> fig, axs = plot_partial_dependence(mc_clf, X, features, label=0) #doctest: +SKIP + +If you need the raw values of the partial dependence function rather +than the plots you can use the +:func:`~sklearn.ensemble.partial_dependence.partial_dependence` function:: + + >>> from sklearn.ensemble.partial_dependence import partial_dependence + + >>> pdp, axes = partial_dependence(clf, [0], X=X) + >>> pdp # doctest: +ELLIPSIS + array([[ 2.46643157, 2.46643157, ... + >>> axes # doctest: +ELLIPSIS + [array([-1.62497054, -1.59201391, ... + +The function requires either the argument ``grid`` which specifies the +values of the target features on which the partial dependence function +should be evaluated or the argument ``X`` which is a convenience mode +for automatically creating ``grid`` from the training data. If ``X`` +is given, the ``axes`` value returned by the function gives the axis +for each target feature. + +For each value of the 'target' features in the ``grid`` the partial +dependence function need to marginalize the predictions of a tree over +all possible values of the 'complement' features. In decision trees +this function can be evaluated efficiently without reference to the +training data. For each grid point a weighted tree traversal is +performed: if a split node involves a 'target' feature, the +corresponding left or right branch is followed, otherwise both +branches are followed, each branch is weighted by the fraction of +training samples that entered that branch. Finally, the partial +dependence is given by a weighted average of all visited leaves. For +tree ensembles the results of each individual tree are again +averaged. + +.. rubric:: Footnotes + +.. [1] For classification with ``loss='deviance'`` the target + response is logit(p). + +.. [2] More precisely its the expectation of the target response after + accounting for the initial model; partial dependence plots + do not include the ``init`` model. + +.. topic:: Examples: + + * :ref:`example_ensemble_plot_partial_dependence.py` .. topic:: References @@ -491,4 +893,3 @@ can be controled via the ``max_features`` parameter. .. [HTF2009] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical Learning Ed. 2", Springer, 2009. .. [R2007] G. Ridgeway, "Generalized Boosted Models: A guide to the gbm package", 2007 - diff --git a/doc/modules/feature_extraction.rst b/doc/modules/feature_extraction.rst index c61d49a860b91..ab7e1ffefa5ac 100644 --- a/doc/modules/feature_extraction.rst +++ b/doc/modules/feature_extraction.rst @@ -1,4 +1,3 @@ - .. _feature_extraction: ================== @@ -86,9 +85,9 @@ suitable for feeding into a classifier (maybe after being piped into a >>> vec = DictVectorizer() >>> pos_vectorized = vec.fit_transform(pos_window) - >>> pos_vectorized # doctest: +NORMALIZE_WHITESPACE - <1x6 sparse matrix of type '' - with 6 stored elements in COOrdinate format> + >>> pos_vectorized # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + <1x6 sparse matrix of type '<... 'numpy.float64'>' + with 6 stored elements in Compressed Sparse ... format> >>> pos_vectorized.toarray() array([[ 1., 1., 1., 1., 1., 1.]]) >>> vec.get_feature_names() @@ -102,6 +101,118 @@ memory the ``DictVectorizer`` class uses a ``scipy.sparse`` matrix by default instead of a ``numpy.ndarray``. +.. _feature_hashing: + +Feature hashing +=============== + +.. currentmodule:: sklearn.feature_extraction + +The class :class:`FeatureHasher` is a high-speed, low-memory vectorizer that +uses a technique known as +`feature hashing `_, +or the "hashing trick". +Instead of building a hash table of the features encountered in training, +as the vectorizers do, instances of :class:`FeatureHasher` +apply a hash function to the features +to determine their column index in sample matrices directly. +The result is increased speed and reduced memory usage, +at the expense of inspectability; +the hasher does not remember what the input features looked like +and has no ``inverse_transform`` method. + +Since the hash function might cause collisions between (unrelated) features, +a signed hash function is used and the sign of the hash value +determines the sign of the value stored in the output matrix for a feature. +This way, collisions are likely to cancel out rather than accumulate error, +and the expected mean of any output feature's value is zero. + +If ``non_negative=True`` is passed to the constructor, the absolute +value is taken. This undoes some of the collision handling, but allows +the output to be passed to estimators like +:class:`sklearn.naive_bayes.MultinomialNB` or +:class:`sklearn.feature_selection.chi2` +feature selectors that expect non-negative inputs. + +:class:`FeatureHasher` accepts either mappings +(like Python's ``dict`` and its variants in the ``collections`` module), +``(feature, value)`` pairs, or strings, +depending on the constructor parameter ``input_type``. +Mapping are treated as lists of ``(feature, value)`` pairs, +while single strings have an implicit value of 1, +so ``['feat1', 'feat2', 'feat3']`` is interpreted as +``[('feat1', 1), ('feat2', 1), ('feat3', 1)]``. +If a single feature occurs multiple times in a sample, +the associated values will be summed +(so ``('feat', 2)`` and ``('feat', 3.5)`` become ``('feat', 5.5)``). +The output from :class:`FeatureHasher` is always a ``scipy.sparse`` matrix +in the CSR format. + +Feature hashing can be employed in document classification, +but unlike :class:`text.CountVectorizer`, +:class:`FeatureHasher` does not do word +splitting or any other preprocessing except Unicode-to-UTF-8 encoding; +see :ref:`hashing_vectorizer`, below, for a combined tokenizer/hasher. + +As an example, consider a word-level natural language processing task +that needs features extracted from ``(token, part_of_speech)`` pairs. +One could use a Python generator function to extract features:: + + def token_features(token, part_of_speech): + if token.isdigit(): + yield "numeric" + else: + yield "token={}".format(token.lower()) + yield "token,pos={},{}".format(token, part_of_speech) + if token[0].isupper(): + yield "uppercase_initial" + if token.isupper(): + yield "all_uppercase" + yield "pos={}".format(part_of_speech) + +Then, the ``raw_X`` to be fed to ``FeatureHasher.transform`` +can be constructed using:: + + raw_X = (token_features(tok, pos_tagger(tok)) for tok in corpus) + +and fed to a hasher with:: + + hasher = FeatureHasher(input_type='string') + X = hasher.transform(raw_X) + +to get a ``scipy.sparse`` matrix ``X``. + +Note the use of a generator comprehension, +which introduces laziness into the feature extraction: +tokens are only processed on demand from the hasher. + +Implementation details +---------------------- + +:class:`FeatureHasher` uses the signed 32-bit variant of MurmurHash3. +As a result (and because of limitations in ``scipy.sparse``), +the maximum number of features supported is currently :math:`2^{31} - 1`. + +The original formulation of the hashing trick by Weinberger et al. +used two separate hash functions :math:`h` and :math:`\xi` +to determine the column index and sign of a feature, respectively. +The present implementation works under the assumption +that the sign bit of MurmurHash3 is independent of its other bits. + +Since a simple modulo is used to transform the hash function to a column index, +it is advisable to use a power of two as the ``n_features`` parameter; +otherwise the features will not be mapped evenly to the columns. + + +.. topic:: References: + + * Kilian Weinberger, Anirban Dasgupta, John Langford, Alex Smola and + Josh Attenberg (2009). `Feature hashing for large scale multitask learning + `_. Proc. ICML. + + * `MurmurHash3 `_. + + .. _text_feature_extraction: Text feature extraction @@ -123,7 +234,7 @@ In order to address this, scikit-learn provides utilities for the most common ways to extract numerical features from text content, namely: - **tokenizing** strings and giving an integer id for each possible token, - for instance by using whitespaces and punctuation as token separators. + for instance by using white-spaces and punctuation as token separators. - **counting** the occurrences of tokens in each document. @@ -142,7 +253,7 @@ A corpus of documents can thus be represented by a matrix with one row per document and one column per token (e.g. word) occurring in the corpus. We call **vectorization** the general process of turning a collection -of text documents into numerical feature vectors. This specific stragegy +of text documents into numerical feature vectors. This specific strategy (tokenization, counting and normalization) is called the **Bag of Words** or "Bag of n-grams" representation. Documents are described by word occurrences while completely ignoring the relative position information @@ -152,7 +263,7 @@ of the words in the document. Sparsity -------- -As most documents will typically use a very subset of a the words used in +As most documents will typically use a very small subset of the words used in the corpus, the resulting matrix will have many feature values that are zeros (typically more than 99% of them). @@ -179,13 +290,13 @@ reasonable (please see the :ref:`reference documentation ` for the details):: >>> vectorizer = CountVectorizer(min_df=1) - >>> vectorizer # doctest: +NORMALIZE_WHITESPACE - CountVectorizer(analyzer='word', binary=False, charset='utf-8', - charset_error='strict', dtype=, input='content', - lowercase=True, max_df=1.0, max_features=None, max_n=None, min_df=1, - min_n=None, ngram_range=(1, 1), preprocessor=None, stop_words=None, - strip_accents=None, token_pattern=u'(?u)\\b\\w\\w+\\b', tokenizer=None, - vocabulary=None) + >>> vectorizer # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + CountVectorizer(analyzer=...'word', binary=False, decode_error=...'strict', + dtype=<... 'numpy.int64'>, encoding=...'utf-8', input=...'content', + lowercase=True, max_df=1.0, max_features=None, min_df=1, + ngram_range=(1, 1), preprocessor=None, stop_words=None, + strip_accents=None, token_pattern=...'(?u)\\b\\w\\w+\\b', + tokenizer=None, vocabulary=None) Let's use it to tokenize and count the word occurrences of a minimalistic corpus of text documents:: @@ -197,24 +308,27 @@ corpus of text documents:: ... 'Is this the first document?', ... ] >>> X = vectorizer.fit_transform(corpus) - >>> X # doctest: +NORMALIZE_WHITESPACE - <4x9 sparse matrix of type '' - with 19 stored elements in COOrdinate format> + >>> X # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + <4x9 sparse matrix of type '<... 'numpy.int64'>' + with 19 stored elements in Compressed Sparse ... format> The default configuration tokenizes the string by extracting words of at least 2 letters. The specific function that does this step can be requested explicitly:: >>> analyze = vectorizer.build_analyzer() - >>> analyze("This is a text document to analyze.") - [u'this', u'is', u'text', u'document', u'to', u'analyze'] + >>> analyze("This is a text document to analyze.") == ( + ... ['this', 'is', 'text', 'document', 'to', 'analyze']) + True Each term found by the analyzer during the fit is assigned a unique integer index corresponding to a column in the resulting matrix. This interpretation of the columns can be retrieved as follows:: - >>> vectorizer.get_feature_names() - [u'and', u'document', u'first', u'is', u'one', u'second', u'the', u'third', u'this'] + >>> vectorizer.get_feature_names() == ( + ... ['and', 'document', 'first', 'is', 'one', + ... 'second', 'the', 'third', 'this']) + True >>> X.toarray() # doctest: +ELLIPSIS array([[0, 1, 1, 1, 0, 0, 1, 0, 1], @@ -237,15 +351,16 @@ ignored in future calls to the transform method:: Note that in the previous corpus, the first and the last documents have exactly the same words hence are encoded in equal vectors. In particular -we lose the information that the last document is an interogative form. To +we lose the information that the last document is an interrogative form. To preserve some of the local ordering information we can extract 2-grams -of words in addition to the 1-grams (the word themselvs):: +of words in addition to the 1-grams (individual words):: >>> bigram_vectorizer = CountVectorizer(ngram_range=(1, 2), - ... token_pattern=ur'\b\w+\b', min_df=1) + ... token_pattern=r'\b\w+\b', min_df=1) >>> analyze = bigram_vectorizer.build_analyzer() - >>> analyze('Bi-grams are cool!') - [u'bi', u'grams', u'are', u'cool', u'bi grams', u'grams are', u'are cool'] + >>> analyze('Bi-grams are cool!') == ( + ... ['bi', 'grams', 'are', 'cool', 'bi grams', 'grams are', 'are cool']) + True The vocabulary extracted by this vectorizer is hence much bigger and can now resolve ambiguities encoded in local positioning patterns:: @@ -259,10 +374,10 @@ can now resolve ambiguities encoded in local positioning patterns:: [0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1]]...) -In particular the interogative form "Is this" is only present in the +In particular the interrogative form "Is this" is only present in the last document:: - >>> feature_index = bigram_vectorizer.vocabulary_.get(u'is this') + >>> feature_index = bigram_vectorizer.vocabulary_.get('is this') >>> X_2[:, feature_index] # doctest: +ELLIPSIS array([0, 0, 0, 1]...) @@ -273,7 +388,7 @@ Tf–idf term weighting --------------------- In a large text corpus, some words will be very present (e.g. "the", "a", -"is" in English) hence carrying very little meaningul information about +"is" in English) hence carrying very little meaningful information about the actual contents of the document. If we were to feed the direct count data directly to a classifier those very frequent terms would shadow the frequencies of rarer yet more interesting terms. @@ -283,7 +398,7 @@ suitable for usage by a classifier it is very common to use the tf–idf transform. Tf means **term-frequency** while tf–idf means term-frequency times -**inverse document-frequency**. This is a orginally a term weighting +**inverse document-frequency**. This is a originally a term weighting scheme developed for information retrieval (as a ranking function for search engines results), that has also found good use in document classification and clustering. @@ -293,8 +408,9 @@ class:: >>> from sklearn.feature_extraction.text import TfidfTransformer >>> transformer = TfidfTransformer() - >>> transformer - TfidfTransformer(norm='l2', smooth_idf=True, sublinear_tf=False, use_idf=True) + >>> transformer # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + TfidfTransformer(norm=...'l2', smooth_idf=True, sublinear_tf=False, + use_idf=True) Again please see the :ref:`reference documentation ` for the details on all the parameters. @@ -312,9 +428,9 @@ content of the documents:: ... [3, 0, 2]] ... >>> tfidf = transformer.fit_transform(counts) - >>> tfidf # doctest: +NORMALIZE_WHITESPACE - <6x3 sparse matrix of type '' - with 9 stored elements in Compressed Sparse Row format> + >>> tfidf # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + <6x3 sparse matrix of type '<... 'numpy.float64'>' + with 9 stored elements in Compressed Sparse ... format> >>> tfidf.toarray() # doctest: +ELLIPSIS array([[ 0.85..., 0. ..., 0.52...], @@ -332,30 +448,111 @@ attribute:: array([ 1. ..., 2.25..., 1.84...]) -As tf–idf is a very often used for text features, there is also another -class called :class:`TfidfVectorizer` that combines all the option of +As tf–idf is very often used for text features, there is also another +class called :class:`TfidfVectorizer` that combines all the options of :class:`CountVectorizer` and :class:`TfidfTransformer` in a single model:: >>> from sklearn.feature_extraction.text import TfidfVectorizer >>> vectorizer = TfidfVectorizer(min_df=1) >>> vectorizer.fit_transform(corpus) - ... # doctest: +NORMALIZE_WHITESPACE - <4x9 sparse matrix of type '' - with 19 stored elements in Compressed Sparse Row format> + ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + <4x9 sparse matrix of type '<... 'numpy.float64'>' + with 19 stored elements in Compressed Sparse ... format> While the tf–idf normalization is often very useful, there might be cases where the binary occurrence markers might offer better features. This can be achieved by using the ``binary`` parameter of :class:`CountVectorizer`. In particular, some estimators such as :ref:`bernoulli_naive_bayes` explicitly model discrete boolean random -variables. Also, very short text are likely to have noisy tf–idf values +variables. Also, very short texts are likely to have noisy tf–idf values while the binary occurrence info is more stable. -As usual the only way how to best adjust the feature extraction parameters +As usual the best way to adjust the feature extraction parameters is to use a cross-validated grid search, for instance by pipelining the feature extractor with a classifier: - * :ref:`example_grid_search_text_feature_extraction.py` + * :ref:`example_model_selection_grid_search_text_feature_extraction.py` + + +Decoding text files +------------------- +Text is made of characters, but files are made of bytes. These bytes represent +characters according to some *encoding*. To work with text files in Python, +their bytes must be *decoded* to a character set called Unicode. +Common encodings are ASCII, Latin-1 (Western Europe), KOI8-R (Russian) +and the universal encodings UTF-8 and UTF-16. Many others exist. + +.. note:: + An encoding can also be called a 'character set', + but this term is less accurate: several encodings can exist + for a single character set. + +The text feature extractors in scikit-learn know how to decode text files, +but only if you tell them what encoding the files are in. +The :class:`CountVectorizer` takes an ``encoding`` parameter for this purpose. +For modern text files, the correct encoding is probably UTF-8, +which is therefore the default (``encoding="utf-8"``). + +If the text you are loading is not actually encoded with UTF-8, however, +you will get a ``UnicodeDecodeError``. +The vectorizers can be told to be silent about decoding errors +by setting the ``decode_error`` parameter to either ``"ignore"`` +or ``"replace"``. See the documentation for the Python function +``bytes.decode`` for more details +(type ``help(bytes.decode)`` at the Python prompt). + +If you are having trouble decoding text, here are some things to try: + +- Find out what the actual encoding of the text is. The file might come + with a header or README that tells you the encoding, or there might be some + standard encoding you can assume based on where the text comes from. + +- You may be able to find out what kind of encoding it is in general + using the UNIX command ``file``. The Python ``chardet`` module comes with + a script called ``chardetect.py`` that will guess the specific encoding, + though you cannot rely on its guess being correct. + +- You could try UTF-8 and disregard the errors. You can decode byte + strings with ``bytes.decode(errors='replace')`` to replace all + decoding errors with a meaningless character, or set + ``decode_error='replace'`` in the vectorizer. This may damage the + usefulness of your features. + +- Real text may come from a variety of sources that may have used different + encodings, or even be sloppily decoded in a different encoding than the + one it was encoded with. This is common in text retrieved from the Web. + The Python package `ftfy`_ can automatically sort out some classes of + decoding errors, so you could try decoding the unknown text as ``latin-1`` + and then using ``ftfy`` to fix errors. + +- If the text is in a mish-mash of encodings that is simply too hard to sort + out (which is the case for the 20 Newsgroups dataset), you can fall back on + a simple single-byte encoding such as ``latin-1``. Some text may display + incorrectly, but at least the same sequence of bytes will always represent + the same feature. + +For example, the following snippet uses ``chardet`` +(not shipped with scikit-learn, must be installed separately) +to figure out the encoding of three texts. +It then vectorizes the texts and prints the learned vocabulary. +The output is not shown here. + + >>> import chardet # doctest: +SKIP + >>> text1 = b"Sei mir gegr\xc3\xbc\xc3\x9ft mein Sauerkraut" + >>> text2 = b"holdselig sind deine Ger\xfcche" + >>> text3 = b"\xff\xfeA\x00u\x00f\x00 \x00F\x00l\x00\xfc\x00g\x00e\x00l\x00n\x00 \x00d\x00e\x00s\x00 \x00G\x00e\x00s\x00a\x00n\x00g\x00e\x00s\x00,\x00 \x00H\x00e\x00r\x00z\x00l\x00i\x00e\x00b\x00c\x00h\x00e\x00n\x00,\x00 \x00t\x00r\x00a\x00g\x00 \x00i\x00c\x00h\x00 \x00d\x00i\x00c\x00h\x00 \x00f\x00o\x00r\x00t\x00" + >>> decoded = [x.decode(chardet.detect(x)['encoding']) + ... for x in (text1, text2, text3)] # doctest: +SKIP + >>> v = CountVectorizer().fit(decoded).vocabulary_ # doctest: +SKIP + >>> for term in v: print(v) # doctest: +SKIP + +(Depending on the version of ``chardet``, it might get the first one wrong.) + +For an introduction to Unicode and character encodings in general, +see Joel Spolsky's `Absolute Minimum Every Software Developer Must Know +About Unicode `_. + +.. _`ftfy`: http://github.com/LuminosoInsight/python-ftfy Applications and examples @@ -365,18 +562,18 @@ The bag of words representation is quite simplistic but surprisingly useful in practice. In particular in a **supervised setting** it can be successfully combined -with fast and scalable linear models to train **document classificers**, +with fast and scalable linear models to train **document classifiers**, for instance: - * :ref:`example_document_classification_20newsgroups.py` + * :ref:`example_text_document_classification_20newsgroups.py` In an **unsupervised setting** it can be used to group similar documents together by applying clustering algorithms such as :ref:`k_means`: - * :ref:`example_document_clustering.py` + * :ref:`example_text_document_clustering.py` Finally it is possible to discover the main topics of a corpus by -relaxing the hard assignement constraint of clustering, for instance by +relaxing the hard assignment constraint of clustering, for instance by using :ref:`NMF`: * :ref:`example_applications_topics_extraction_with_nmf.py` @@ -387,15 +584,15 @@ Limitations of the Bag of Words representation A collection of unigrams (what bag of words is) cannot capture phrases and multi-word expressions, effectively disregarding any word order -dependence. Additionally, bag of words model doesn't account for potential +dependence. Additionally, the bag of words model doesn't account for potential misspellings or word derivations. N-grams to the rescue! Instead of building a simple collection of unigrams (n=1), one might prefer a collection of bigrams (n=2), where -occurences of pairs of consecutive words are counted. +occurrences of pairs of consecutive words are counted. One might alternatively consider a collection of character n-grams, a -representation resiliant against misspellings and derivations. +representation resilient against misspellings and derivations. For example, let's say we're dealing with a corpus of two documents: ``['words', 'wprds']``. The second document contains a misspelling @@ -408,39 +605,42 @@ decide better:: >>> ngram_vectorizer = CountVectorizer(analyzer='char_wb', ngram_range=(2, 2), min_df=1) >>> counts = ngram_vectorizer.fit_transform(['words', 'wprds']) - >>> ngram_vectorizer.get_feature_names() - [u' w', u'ds', u'or', u'pr', u'rd', u's ', u'wo', u'wp'] + >>> ngram_vectorizer.get_feature_names() == ( + ... [' w', 'ds', 'or', 'pr', 'rd', 's ', 'wo', 'wp']) + True >>> counts.toarray().astype(int) array([[1, 1, 1, 0, 1, 1, 1, 0], [1, 1, 0, 1, 1, 1, 0, 1]]) -In above example, ``'char_wb`` analyzer is used, which creates n-grams +In the above example, ``'char_wb`` analyzer is used, which creates n-grams only from characters inside word boundaries (padded with space on each side). The ``'char'`` analyzer, alternatively, creates n-grams that span across words:: >>> ngram_vectorizer = CountVectorizer(analyzer='char_wb', ngram_range=(5, 5), min_df=1) >>> ngram_vectorizer.fit_transform(['jumpy fox']) - ... # doctest: +NORMALIZE_WHITESPACE - <1x4 sparse matrix of type '' - with 4 stored elements in COOrdinate format> - >>> ngram_vectorizer.get_feature_names() - [u' fox ', u' jump', u'jumpy', u'umpy '] + ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + <1x4 sparse matrix of type '<... 'numpy.int64'>' + with 4 stored elements in Compressed Sparse ... format> + >>> ngram_vectorizer.get_feature_names() == ( + ... [' fox ', ' jump', 'jumpy', 'umpy ']) + True >>> ngram_vectorizer = CountVectorizer(analyzer='char', ngram_range=(5, 5), min_df=1) >>> ngram_vectorizer.fit_transform(['jumpy fox']) - ... # doctest: +NORMALIZE_WHITESPACE - <1x5 sparse matrix of type '' - with 5 stored elements in COOrdinate format> - >>> ngram_vectorizer.get_feature_names() - [u'jumpy', u'mpy f', u'py fo', u'umpy ', u'y fox'] + ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + <1x5 sparse matrix of type '<... 'numpy.int64'>' + with 5 stored elements in Compressed Sparse ... format> + >>> ngram_vectorizer.get_feature_names() == ( + ... ['jumpy', 'mpy f', 'py fo', 'umpy ', 'y fox']) + True The word boundaries-aware variant ``char_wb`` is especially interesting -for languages that use whitespaces for word separation as it generates +for languages that use white-spaces for word separation as it generates significantly less noisy features than the raw ``char`` variant in that case. For such languages it can increase both the predictive accuracy and convergence speed of classifiers trained using such -features while retaining the robustness w.r.t. misspellings and +features while retaining the robustness with regards to misspellings and word derivations. While some local positioning information can be preserved by extracting @@ -454,8 +654,115 @@ into account. Many such models will thus be casted as "Structured output" problems which are currently outside of the scope of scikit-learn. +.. _hashing_vectorizer: + +Vectorizing a large text corpus with the hashing trick +------------------------------------------------------ + +The above vectorization scheme is simple but the fact that it holds an **in- +memory mapping from the string tokens to the integer feature indices** (the +``vocabulary_`` attribute) causes several **problems when dealing with large +datasets**: + +- the larger the corpus, the larger the vocabulary will grow and hence the + memory use too, + +- fitting requires the allocation of intermediate data structures + of size proportional to that of the original dataset. + +- building the word-mapping requires a full pass over the dataset hence it is + not possible to fit text classifiers in a strictly online manner. + +- pickling and un-pickling vectorizers with a large ``vocabulary_`` can be very + slow (typically much slower than pickling / un-pickling flat data structures + such as a NumPy array of the same size), + +- it is not easily possible to split the vectorization work into concurrent sub + tasks as the ``vocabulary_`` attribute would have to be a shared state with a + fine grained synchronization barrier: the mapping from token string to + feature index is dependent on ordering of the first occurrence of each token + hence would have to be shared, potentially harming the concurrent workers' + performance to the point of making them slower than the sequential variant. + +It is possible to overcome those limitations by combining the "hashing trick" +(:ref:`Feature_hashing`) implemented by the +:class:`sklearn.feature_extraction.FeatureHasher` class and the text +preprocessing and tokenization features of the :class:`CountVectorizer`. + +This combination is implementing in :class:`HashingVectorizer`, +a transformer class that is mostly API compatible with :class:`CountVectorizer`. +:class:`HashingVectorizer` is stateless, +meaning that you don't have to call ``fit`` on it:: + + >>> from sklearn.feature_extraction.text import HashingVectorizer + >>> hv = HashingVectorizer(n_features=10) + >>> hv.transform(corpus) + ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + <4x10 sparse matrix of type '<... 'numpy.float64'>' + with 16 stored elements in Compressed Sparse ... format> + +You can see that 16 non-zero feature tokens were extracted in the vector +output: this is less than the 19 non-zeros extracted previously by the +:class:`CountVectorizer` on the same toy corpus. The discrepancy comes from +hash function collisions because of the low value of the ``n_features`` parameter. + +In a real world setting, the ``n_features`` parameter can be left to its +default value of ``2 ** 20`` (roughly one million possible features). If memory +or downstream models size is an issue selecting a lower value such as ``2 ** +18`` might help without introducing too many additional collisions on typical +text classification tasks. + +Note that the dimensionality does not affect the CPU training time of +algorithms which operate on CSR matrices (``LinearSVC(dual=True)``, +``Perceptron``, ``SGDClassifier``, ``PassiveAggressive``) but it does for +algorithms that work with CSC matrices (``LinearSVC(dual=False)``, ``Lasso()``, +etc). + +Let's try again with the default setting:: + + >>> hv = HashingVectorizer() + >>> hv.transform(corpus) + ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + <4x1048576 sparse matrix of type '<... 'numpy.float64'>' + with 19 stored elements in Compressed Sparse ... format> + +We no longer get the collisions, but this comes at the expense of a much larger +dimensionality of the output space. +Of course, other terms than the 19 used here +might still collide with each other. + +The :class:`HashingVectorizer` also comes with the following limitations: + +- it is not possible to invert the model (no ``inverse_transform`` method), + nor to access the original string representation of the features, + because of the one-way nature of the hash function that performs the mapping. + +- it does not provide IDF weighting as that would introduce statefulness in the + model. A :class:`TfidfTransformer` can be appended to it in a pipeline if + required. + +Performing out-of-core scaling with HashingVectorizer +------------------------------------------------------ + +An interesting development of using a :class:`HashingVectorizer` is the ability +to perform `out-of-core`_ scaling. This means that we can learn from data that +does not fit into the computer's main memory. + +.. _out-of-core: http://en.wikipedia.org/wiki/Out-of-core_algorithm + +A strategy to implement out-of-core scaling is to stream data to the estimator +in mini-batches. Each mini-batch is vectorized using :class:`HashingVectorizer` +so as to guarantee that the input space of the estimator has always the same +dimensionality. The amount of memory used at any time is thus bounded by the +size of a mini-batch. Although there is no limit to the amount of data that can +be ingested using such an approach, from a practical point of view the learning +time is often limited by the CPU time one wants to spend on the task. + +For a full-fledged example of out-of-core scaling in a text classification +task see :ref:`example_applications_plot_out_of_core_classification.py`. + Customizing the vectorizer classes ------------------------------------ +---------------------------------- It is possible to customize the behavior by passing a callable to the vectorizer constructor:: @@ -464,28 +771,59 @@ to the vectorizer constructor:: ... return s.split() ... >>> vectorizer = CountVectorizer(tokenizer=my_tokenizer) - >>> vectorizer.build_analyzer()(u"Some... punctuation!") - [u'some...', u'punctuation!'] + >>> vectorizer.build_analyzer()(u"Some... punctuation!") == ( + ... ['some...', 'punctuation!']) + True In particular we name: - * ``preprocessor`` a callable that takes a string as input and return - another string (removing HTML tags or converting to lower case for - instance) + * ``preprocessor``: a callable that takes an entire document as input (as a + single string), and returns a possibly transformed version of the document, + still as an entire string. This can be used to remove HTML tags, lowercase + the entire document, etc. - * ``tokenizer`` a callable that takes a string as input and output a - sequence of feature occurrences (a.k.a. the tokens). + * ``tokenizer``: a callable that takes the output from the preprocessor + and splits it into tokens, then returns a list of these. - * ``analyzer`` a callable that wraps calls to the preprocessor and - tokenizer and further perform some filtering or n-grams extractions - on the tokens. + * ``analyzer``: a callable that replaces the preprocessor and tokenizer. + The default analyzers all call the preprocessor and tokenizer, but custom + analyzers will skip this. N-gram extraction and stop word filtering take + place at the analyzer level, so a custom analyzer may have to reproduce + these steps. + +(Lucene users might recognize these names, but be aware that scikit-learn +concepts may not map one-to-one onto Lucene concepts.) To make the preprocessor, tokenizer and analyzers aware of the model parameters it is possible to derive from the class and override the ``build_preprocessor``, ``build_tokenizer``` and ``build_analyzer`` -factory method instead. - -Customizing the vectorizer can be very useful to handle Asian languages +factory methods instead of passing custom functions. + +Some tips and tricks: + + * If documents are pre-tokenized by an external package, then store them in + files (or strings) with the tokens separated by whitespace and pass + ``analyzer=str.split`` + * Fancy token-level analysis such as stemming, lemmatizing, compound + splitting, filtering based on part-of-speech, etc. are not included in the + scikit-learn codebase, but can be added by customizing either the + tokenizer or the analyzer. + Here's a ``CountVectorizer`` with a tokenizer and lemmatizer using + `NLTK `_:: + + >>> from nltk import word_tokenize # doctest: +SKIP + >>> from nltk.stem import WordNetLemmatizer # doctest: +SKIP + >>> class LemmaTokenizer(object): + ... def __init__(self): + ... self.wnl = WordNetLemmatizer() + ... def __call__(self, doc): + ... return [self.wnl.lemmatize(t) for t in word_tokenize(doc)] + ... + >>> vect = CountVectorizer(tokenizer=LemmaTokenizer()) # doctest: +SKIP + + (Note that this will not filter out punctuation.) + +Customizing the vectorizer can also be useful when handling Asian languages that do not use an explicit word separator such as whitespace. @@ -553,7 +891,7 @@ features or samples. For instance Ward clustering (:ref:`hierarchical_clustering`) can cluster together only neighboring pixels of an image, thus forming contiguous patches: -.. figure:: ../auto_examples/cluster/images/plot_lena_ward_segmentation_1.png +.. figure:: ../auto_examples/cluster/images/plot_lena_ward_segmentation_001.png :target: ../auto_examples/cluster/plot_lena_ward_segmentation.html :align: center :scale: 40 diff --git a/doc/modules/feature_selection.rst b/doc/modules/feature_selection.rst index 0c7bb54b77ec6..3e26b52e82324 100644 --- a/doc/modules/feature_selection.rst +++ b/doc/modules/feature_selection.rst @@ -12,22 +12,74 @@ for feature selection/dimensionality reduction on sample sets, either to improve estimators' accuracy scores or to boost their performance on very high-dimensional datasets. + +Removing features with low variance +=================================== + +:class:`VarianceThreshold` is a simple baseline approach to feature selection. +It removes all features whose variance doesn't meet some threshold. +By default, it removes all zero-variance features, +i.e. features that have the same value in all samples. + +As an example, suppose that we have a dataset with boolean features, +and we want to remove all features that are either one or zero (on or off) +in more than 80% of the samples. +Boolean features are Bernoulli random variables, +and the variance of such variables is given by + +.. math:: \mathrm{Var}[X] = p(1 - p) + +so we can select using the threshold ``.8 * (1 - .8)``:: + + >>> from sklearn.feature_selection import VarianceThreshold + >>> X = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1]] + >>> sel = VarianceThreshold(threshold=(.8 * (1 - .8))) + >>> sel.fit_transform(X) + array([[0, 1], + [1, 0], + [0, 0], + [1, 1], + [1, 0], + [1, 1]]) + +As expected, ``VarianceThreshold`` has removed the first column, +which has a probability :math:`p = 5/6 > .8` of containing a zero. + Univariate feature selection ============================ Univariate feature selection works by selecting the best features based on -univariate statistical tests. It can seen as a preprocessing step -to an estimator. Scikit-Learn exposes feature selection routines -a objects that implement the `transform` method: +univariate statistical tests. It can be seen as a preprocessing step +to an estimator. Scikit-learn exposes feature selection routines +as objects that implement the ``transform`` method: - * selecting the k-best features :class:`SelectKBest` + * :class:`SelectKBest` removes all but the :math:`k` highest scoring features - * setting a percentile of features to keep :class:`SelectPercentile` + * :class:`SelectPercentile` removes all but a user-specified highest scoring + percentage of features * using common univariate statistical tests for each feature: false positive rate :class:`SelectFpr`, false discovery rate :class:`SelectFdr`, or family wise error :class:`SelectFwe`. + * :class:`GenericUnivariateSelect` allows to perform univariate feature + selection with a configurable strategy. This allows to select the best + univariate selection strategy with hyper-parameter search estimator. + +For instance, we can perform a :math:`\chi^2` test to the samples +to retrieve only the two best features as follows: + + >>> from sklearn.datasets import load_iris + >>> from sklearn.feature_selection import SelectKBest + >>> from sklearn.feature_selection import chi2 + >>> iris = load_iris() + >>> X, y = iris.data, iris.target + >>> X.shape + (150, 4) + >>> X_new = SelectKBest(chi2, k=2).fit_transform(X, y) + >>> X_new.shape + (150, 2) + These objects take as input a scoring function that returns univariate p-values: @@ -47,7 +99,7 @@ univariate p-values: .. topic:: Examples: - :ref:`example_plot_feature_selection.py` + :ref:`example_feature_selection_plot_feature_selection.py` Recursive feature elimination @@ -67,10 +119,10 @@ number of features. .. topic:: Examples: - * :ref:`example_plot_rfe_digits.py`: A recursive feature elimination example + * :ref:`example_feature_selection_plot_rfe_digits.py`: A recursive feature elimination example showing the relevance of pixels in a digit classification task. - * :ref:`example_plot_rfe_with_cross_validation.py`: A recursive feature + * :ref:`example_feature_selection_plot_rfe_with_cross_validation.py`: A recursive feature elimination example with automatic tuning of the number of features selected with cross-validation. @@ -85,12 +137,12 @@ L1-based feature selection Selecting non-zero coefficients --------------------------------- -:ref:`Linear models ` penalized with the L1 norm have +:ref:`Linear models ` penalized with the L1 norm have sparse solutions: many of their estimated coefficients are zero. When the goal -is to reduce the dimensionality of the data to use with another classifier, -they expose a `transform` method to select the non-zero coefficient. In +is to reduce the dimensionality of the data to use with another classifier, +they expose a ``transform`` method to select the non-zero coefficient. In particular, sparse estimators useful for this purpose are the -:class:`linear_model.Lasso` for regression, and +:class:`linear_model.Lasso` for regression, and of :class:`linear_model.LogisticRegression` and :class:`svm.LinearSVC` for classification:: @@ -104,13 +156,13 @@ for classification:: >>> X_new.shape (150, 3) -With SVMs and logistic-regression, the parameter C controls the sparsity: +With SVMs and logistic-regression, the parameter C controls the sparsity: the smaller C the fewer features selected. With Lasso, the higher the alpha parameter, the fewer features selected. .. topic:: Examples: - * :ref:`example_document_classification_20newsgroups.py`: Comparison + * :ref:`example_text_document_classification_20newsgroups.py`: Comparison of different algorithms for document classification including L1-based feature selection. @@ -120,7 +172,7 @@ alpha parameter, the fewer features selected. For a good choice of alpha, the :ref:`lasso` can fully recover the exact set of non-zero variables using only few observations, provided - certain specific conditions are met. In paraticular, the number of + certain specific conditions are met. In particular, the number of samples should be "sufficiently large", or L1 models will perform at random, where "sufficiently large" depends on the number of non-zero coefficients, the logarithm of the number of features, the amount of @@ -136,9 +188,9 @@ alpha parameter, the fewer features selected. (:class:`LassoLarsIC`) tends, on the opposite, to set high values of alpha. - **Reference** Richard G. Baraniuk `Compressive Sensing`, IEEE Signal + **Reference** Richard G. Baraniuk "Compressive Sensing", IEEE Signal Processing Magazine [120] July 2007 - http://dsp.rice.edu/files/cs/baraniukCSlecture07.pdf + http://dsp.rice.edu/files/cs/baraniukCSlecture07.pdf .. _randomized_l1: @@ -158,7 +210,7 @@ settings, using the Lasso, while :class:`RandomizedLogisticRegression` uses the logistic regression and is suitable for classification tasks. To get a full path of stability scores you can use :func:`lasso_stability_path`. -.. figure:: ../auto_examples/linear_model/images/plot_sparse_recovery_2.png +.. figure:: ../auto_examples/linear_model/plot_sparse_recovery_003.png :target: ../auto_examples/linear_model/plot_sparse_recovery.html :align: center :scale: 60 @@ -166,7 +218,7 @@ path of stability scores you can use :func:`lasso_stability_path`. Note that for randomized sparse models to be more powerful than standard F statistics at detecting non-zero features, the ground truth model should be sparse, in other words, there should be only a small fraction -of features non zero. +of features non zero. .. topic:: Examples: @@ -176,7 +228,7 @@ of features non zero. .. topic:: References: - * N. Meinshausen, P. Buhlmann, "Stability selection", + * N. Meinshausen, P. Buhlmann, "Stability selection", Journal of the Royal Statistical Society, 72 (2010) http://arxiv.org/pdf/0809.2932 @@ -197,9 +249,11 @@ features:: >>> X, y = iris.data, iris.target >>> X.shape (150, 4) - >>> clf = ExtraTreesClassifier(compute_importances=True, random_state=0) + >>> clf = ExtraTreesClassifier() >>> X_new = clf.fit(X, y).transform(X) - >>> X_new.shape + >>> clf.feature_importances_ # doctest: +SKIP + array([ 0.04..., 0.05..., 0.4..., 0.4...]) + >>> X_new.shape # doctest: +SKIP (150, 2) .. topic:: Examples: @@ -211,4 +265,23 @@ features:: * :ref:`example_ensemble_plot_forest_importances_faces.py`: example on face recognition data. - +Feature selection as part of a pipeline +======================================= + +Feature selection is usually used as a pre-processing step before doing +the actual learning. The recommended way to do this in scikit-learn is +to use a :class:`sklearn.pipeline.Pipeline`:: + + clf = Pipeline([ + ('feature_selection', LinearSVC(penalty="l1")), + ('classification', RandomForestClassifier()) + ]) + clf.fit(X, y) + +In this snippet we make use of a :class:`sklearn.svm.LinearSVC` +to evaluate feature importances and select the most relevant features. +Then, a :class:`sklearn.ensemble.RandomForestClassifier` is trained on the +transformed output, i.e. using only relevant features. You can perform +similar operations with the other feature selection methods and also +classifiers that provide a way to evaluate feature importances of course. +See the :class:`sklearn.pipeline.Pipeline` examples for more details. diff --git a/doc/modules/gaussian_process.rst b/doc/modules/gaussian_process.rst index f8e129cd36a6c..a272dd177fa1e 100644 --- a/doc/modules/gaussian_process.rst +++ b/doc/modules/gaussian_process.rst @@ -19,7 +19,7 @@ The advantages of Gaussian Processes for Machine Learning are: correlation models). - The prediction is probabilistic (Gaussian) so that one can compute - empirical confidence intervals and exceedence probabilities that might be + empirical confidence intervals and exceedance probabilities that might be used to refit (online fitting, adaptive fitting) the prediction in some region of interest. @@ -55,11 +55,11 @@ Say we want to surrogate the function :math:`g(x) = x \sin(x)`. To do so, the function is evaluated onto a design of experiments. Then, we define a GaussianProcess model whose regression and correlation models might be specified using additional kwargs, and ask for the model to be fitted to the -data. Depending on the number of parameters provided at instanciation, the +data. Depending on the number of parameters provided at instantiation, the fitting procedure may recourse to maximum likelihood estimation for the parameters or alternatively it uses the given parameters. -.. figure:: ../auto_examples/gaussian_process/images/plot_gp_regression_1.png +.. figure:: ../auto_examples/gaussian_process/images/plot_gp_regression_001.png :target: ../auto_examples/gaussian_process/plot_gp_regression.html :align: center @@ -100,7 +100,7 @@ equivalent to specifying a fractional variance in the input. That is With ``nugget`` and ``corr`` properly set, Gaussian Processes can be used to robustly recover an underlying function from noisy data: -.. figure:: ../auto_examples/gaussian_process/images/plot_gp_regression_2.png +.. figure:: ../auto_examples/gaussian_process/images/plot_gp_regression_002.png :target: ../auto_examples/gaussian_process/plot_gp_regression.html :align: center @@ -151,7 +151,7 @@ basic least squares linear regression problem: g(X) \approx f(X)^T \beta -Except we additionaly assume some spatial coherence (correlation) between the +Except we additionally assume some spatial coherence (correlation) between the samples dictated by the correlation function. Indeed, ordinary least squares assumes the correlation model :math:`R(|X - X'|)` is one when :math:`X = X'` and zero otherwise : a *dirac* correlation model -- sometimes referred to as a @@ -316,7 +316,7 @@ Correlation Models Common correlation models matches some famous SVM's kernels because they are mostly built on equivalent assumptions. They must fulfill Mercer's conditions -and should additionaly remain stationary. Note however, that the choice of the +and should additionally remain stationary. Note however, that the choice of the correlation model should be made in agreement with the known properties of the original experiment from which the observations come. For instance: diff --git a/doc/modules/glm_data/lasso_enet_coordinate_descent.png b/doc/modules/glm_data/lasso_enet_coordinate_descent.png index 23dae332a76ba..052309c8bb722 100644 Binary files a/doc/modules/glm_data/lasso_enet_coordinate_descent.png and b/doc/modules/glm_data/lasso_enet_coordinate_descent.png differ diff --git a/doc/modules/grid_search.rst b/doc/modules/grid_search.rst index 7d14be86cd1d9..394e8119d20d9 100644 --- a/doc/modules/grid_search.rst +++ b/doc/modules/grid_search.rst @@ -1,67 +1,192 @@ +.. currentmodule:: sklearn.grid_search + .. _grid_search: -========================================== -Grid Search: setting estimator parameters -========================================== +=============================================== +Grid Search: Searching for estimator parameters +=============================================== + +Parameters that are not directly learnt within estimators can be set by +searching a parameter space for the best :ref:`cross_validation` score. +Typical examples include ``C``, ``kernel`` and ``gamma`` for Support Vector +Classifier, ``alpha`` for Lasso, etc. + +Any parameter provided when constructing an estimator may be optimized in this +manner. Specifically, to find the names and current values for all parameters +for a given estimator, use:: + + estimator.get_params() + +Such parameters are often referred to as *hyperparameters* (particularly in +Bayesian learning), distinguishing them from the parameters optimised in a +machine learning procedure. + +A search consists of: -.. currentmodule:: sklearn +- an estimator (regressor or classifier such as ``sklearn.svm.SVC()``); +- a parameter space; +- a method for searching or sampling candidates; +- a cross-validation scheme; and +- a :ref:`score function `. + +Some models allow for specialized, efficient parameter search strategies, +:ref:`outlined below `. +Two generic approaches to sampling search candidates are provided in +scikit-learn: for given values, :class:`GridSearchCV` exhaustively considers +all parameter combinations, while :class:`RandomizedSearchCV` can sample a +given number of candidates from a parameter space with a specified +distribution. After describing these tools we detail +:ref:`best practice ` applicable to both approaches. + +Exhaustive Grid Search +====================== + +The grid search provided by :class:`GridSearchCV` exhaustively generates +candidates from a grid of parameter values specified with the ``param_grid`` +parameter. For instance, the following ``param_grid``:: + + param_grid = [ + {'C': [1, 10, 100, 1000], 'kernel': ['linear']}, + {'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']}, + ] + +specifies that two grids should be explored: one with a linear kernel and +C values in [1, 10, 100, 1000], and the second one with an RBF kernel, +and the cross-product of C values ranging in [1, 10, 100, 1000] and gamma +values in [0.001, 0.0001]. + +The :class:`GridSearchCV` instance implements the usual estimator API: when +"fitting" it on a dataset all the possible combinations of parameter values are +evaluated and the best combination is retained. + +.. currentmodule:: sklearn.grid_search + +.. topic:: Examples: -Grid Search is used to optimize the parameters of a model (e.g. ``C``, -``kernel`` and ``gamma`` for Support Vector Classifier, ``alpha`` for -Lasso, etc.) using an internal :ref:`cross_validation` scheme). + - See :ref:`example_model_selection_grid_search_digits.py` for an example of + Grid Search computation on the digits dataset. + - See :ref:`example_model_selection_grid_search_text_feature_extraction.py` for an example + of Grid Search coupling parameters from a text documents feature + extractor (n-gram count vectorizer and TF-IDF transformer) with a + classifier (here a linear SVM trained with SGD with either elastic + net or L2 penalty) using a :class:`pipeline.Pipeline` instance. -GridSearchCV -============ +Randomized Parameter Optimization +================================= +While using a grid of parameter settings is currently the most widely used +method for parameter optimization, other search methods have more +favourable properties. +:class:`RandomizedSearchCV` implements a randomized search over parameters, +where each setting is sampled from a distribution over possible parameter values. +This has two main benefits over an exhaustive search: -The main class for implementing hyperparameters grid search in -scikit-learn is :class:`grid_search.GridSearchCV`. This class is passed -a base model instance (for example ``sklearn.svm.SVC()``) along with a -grid of potential hyper-parameter values such as:: +* A budget can be chosen independent of the number of parameters and possible values. +* Adding parameters that do not influence the performance does not decrease efficiency. - [{'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']}, - {'C': [1, 10, 100, 1000], 'kernel': ['linear']}] +Specifying how parameters should be sampled is done using a dictionary, very +similar to specifying parameters for :class:`GridSearchCV`. Additionally, +a computation budget, being the number of sampled candidates or sampling +iterations, is specified using the ``n_iter`` parameter. +For each parameter, either a distribution over possible values or a list of +discrete choices (which will be sampled uniformly) can be specified:: -The :class:`grid_search.GridSearchCV` instance implements the usual -estimator API: when "fitting" it on a dataset all the possible -combinations of hyperparameter values are evaluated and the best -combinations is retained. + [{'C': scipy.stats.expon(scale=100), 'gamma': scipy.stats.expon(scale=.1), + 'kernel': ['rbf'], 'class_weight':['auto', None]}] -.. topic:: Model selection: development and evaluation +This example uses the ``scipy.stats`` module, which contains many useful +distributions for sampling parameters, such as ``expon``, ``gamma``, +``uniform`` or ``randint``. +In principle, any function can be passed that provides a ``rvs`` (random +variate sample) method to sample a value. A call to the ``rvs`` function should +provide independent random samples from possible parameter values on +consecutive calls. - Model selection with ``GridSearchCV`` can be seen as a way to use the - labeled data to "train" the hyper-parameters of the grid. + .. warning:: - When evaluating the resulting model it is important to do it on - held-out samples that were not seen during the grid search process: - it is recommended to split the data into a **development set** (to - be fed to the ``GridSearchCV`` instance) and an **evaluation set** - to compute performance metrics. + The distributions in ``scipy.stats`` do not allow specifying a random + state. Instead, they use the global numpy random state, that can be seeded + via ``np.random.seed`` or set using ``np.random.set_state``. - This can be done by using the :func:`cross_validation.train_test_split` - utility function. +For continuous parameters, such as ``C`` above, it is important to specify +a continuous distribution to take full advantage of the randomization. This way, +increasing ``n_iter`` will always lead to a finer search. +.. topic:: Examples: -Examples -======== + * :ref:`example_model_selection_randomized_search.py` compares the usage and efficiency + of randomized search and grid search. -- See :ref:`example_grid_search_digits.py` for an example of - Grid Search computation on the digits dataset. +.. topic:: References: + + * Bergstra, J. and Bengio, Y., + Random search for hyper-parameter optimization, + The Journal of Machine Learning Research (2012) + +.. _grid_search_tips: + +Tips for parameter search +========================= -- See :ref:`example_grid_search_text_feature_extraction.py` for an example - of Grid Search coupling parameters from a text documents feature - extractor (n-gram count vectorizer and TF-IDF transformer) with a - classifier (here a linear SVM trained with SGD with either elastic - net or L2 penalty) using a :class:`pipeline.Pipeline` instance. +.. _gridsearch_scoring: + +Specifying an objective metric +------------------------------ -.. note:: +By default, parameter search uses the ``score`` function of the estimator +to evaluate a parameter setting. These are the +:func:`sklearn.metrics.accuracy_score` for classification and +:func:`sklearn.metrics.r2_score` for regression. For some applications, +other scoring functions are better suited (for example in unbalanced +classification, the accuracy score is often uninformative). An alternative +scoring function can be specified via the ``scoring`` parameter to +:class:`GridSearchCV`, :class:`RandomizedSearchCV` and many of the +specialized cross-validation tools described below. +See :ref:`scoring_parameter` for more details. - Computations can be run in parallel if your OS supports it, by using - the keyword n_jobs=-1, see function signature for more details. +Composite estimators and parameter spaces +----------------------------------------- +:ref:`pipeline` describes building composite estimators whose +parameter space can be searched with these tools. -Alternatives to brute force grid search -======================================= +Model selection: development and evaluation +------------------------------------------- + +Model selection by evaluating various parameter settings can be seen as a way +to use the labeled data to "train" the parameters of the grid. + +When evaluating the resulting model it is important to do it on +held-out samples that were not seen during the grid search process: +it is recommended to split the data into a **development set** (to +be fed to the ``GridSearchCV`` instance) and an **evaluation set** +to compute performance metrics. + +This can be done by using the :func:`cross_validation.train_test_split` +utility function. + +Parallelism +----------- + +:class:`GridSearchCV` and :class:`RandomizedSearchCV` evaluate each parameter +setting independently. Computations can be run in parallel if your OS +supports it, by using the keyword ``n_jobs=-1``. See function signature for +more details. + +Robustness to failure +--------------------- + +Some parameter settings may result in a failure to ``fit`` one or more folds +of the data. By default, this will cause the entire search to fail, even if +some parameter settings could be fully evaluated. Setting ``error_score=0`` +(or `=np.NaN`) will make the procedure robust to such failure, issuing a +warning and setting the score for that fold to 0 (or `NaN`), but completing +the search. + +.. _alternative_cv: + +Alternatives to brute force parameter search +============================================ Model specific cross-validation ------------------------------- @@ -78,16 +203,22 @@ compute the **regularization path** of the estimator. Here is the list of such models: +.. currentmodule:: sklearn + .. autosummary:: :toctree: generated/ :template: class.rst - linear_model.RidgeCV - linear_model.RidgeClassifierCV + linear_model.ElasticNetCV linear_model.LarsCV - linear_model.LassoLarsCV linear_model.LassoCV - linear_model.ElasticNetCV + linear_model.LassoLarsCV + linear_model.LogisticRegressionCV + linear_model.MultiTaskElasticNetCV + linear_model.MultiTaskLassoCV + linear_model.OrthogonalMatchingPursuitCV + linear_model.RidgeCV + linear_model.RidgeClassifierCV Information Criterion @@ -120,7 +251,7 @@ of the training set is left out. This left out portion can be used to estimate the generalization error without having to rely on a separate validation set. This estimate -comes "for free" as no addictional data is needed and can be used for +comes "for free" as no additional data is needed and can be used for model selection. This is currently implemented in the following classes: diff --git a/doc/modules/hmm.rst b/doc/modules/hmm.rst index e2e97f42c637c..609f567b0b3a8 100644 --- a/doc/modules/hmm.rst +++ b/doc/modules/hmm.rst @@ -6,26 +6,36 @@ Hidden Markov Models .. currentmodule:: sklearn.hmm +.. warning:: + + The `sklearn.hmm` module has now been deprecated due to it no longer matching + the scope and the API of the project. It is scheduled for removal in the + 0.17 release of the project. + + This module has been moved to a seperate repository: + https://github.com/hmmlearn/hmmlearn + + `sklearn.hmm` implements the Hidden Markov Models (HMMs). The HMM is a generative probabilistic model, in which a sequence of observable :math:`\mathbf{X}` variable is generated by a sequence of internal hidden -state :math:`\mathbf{Z}`. The hidden states can not be observed directly. +state :math:`\mathbf{Z}`. The hidden states can not be observed directly. The transitions between hidden states are assumed to have the form of a (first-order) Markov chain. They can be specified by the start probability -vector :math:`\boldsymbol{\Pi}` and a transition probability matrix +vector :math:`\boldsymbol{\Pi}` and a transition probability matrix :math:`\mathbf{A}`. The emission probability of an observable can be any distribution with parameters :math:`\boldsymbol{{\Theta}_i}` conditioned on the current hidden state (e.g. multinomial, Gaussian). -The HMM is completely determined by +The HMM is completely determined by :math:`\boldsymbol{\Pi, \mathbf{A}}` and :math:`\boldsymbol{{\Theta}_i}`. There are three fundamental problems for HMMs: -* Given the model parameters and observed data, estimate the optimal +* Given the model parameters and observed data, estimate the optimal sequence of hidden states. -* Given the model parameters and observed data, calculate the likelihood +* Given the model parameters and observed data, calculate the likelihood of the data. * Given just the observed data, estimate the model parameters. @@ -48,7 +58,7 @@ See the ref listed below for further detailed information. Using HMM ========= -Classes in this module include :class:`MultinomalHMM` :class:`GaussianHMM`, +Classes in this module include :class:`MultinomialHMM`, :class:`GaussianHMM`, and :class:`GMMHMM`. They implement HMM with emission probabilities determined by multimomial distributions, Gaussian distributions and mixtures of Gaussian distributions. @@ -62,7 +72,7 @@ constructor. Then, you can generate samples from the HMM by calling `sample`.:: >>> import numpy as np >>> from sklearn import hmm - + >>> startprob = np.array([0.6, 0.3, 0.1]) >>> transmat = np.array([[0.7, 0.2, 0.1], [0.3, 0.5, 0.2], [0.3, 0.3, 0.4]]) >>> means = np.array([[0.0, 0.0], [3.0, -3.0], [5.0, 10.0]]) @@ -73,38 +83,30 @@ constructor. Then, you can generate samples from the HMM by calling `sample`.:: >>> X, Z = model.sample(100) -.. figure:: ../auto_examples/images/plot_hmm_sampling_1.png - :target: ../auto_examples/plot_hmm_sampling.html - :align: center - :scale: 75% - -.. topic:: Examples: - - * :ref:`example_plot_hmm_sampling.py` - -Training HMM parameters and infering the hidden states ------------------------------------------------------- +Training HMM parameters and inferring the hidden states +------------------------------------------------------- -You can train an HMM by calling the `fit` method. The input is "the list" of +You can train an HMM by calling the `fit` method. The input is "the list" of the sequence of observed value. Note, since the EM algorithm is a gradient-based optimization method, it will generally get stuck in local optima. You should try to run `fit` with various initializations and select the highest scored model. -The score of the model can be calculated by the `score` method. +The score of the model can be calculated by the `score` method. The inferred optimal hidden states can be obtained by calling `predict` method. The `predict` method can be specified with decoder algorithm. Currently the Viterbi algorithm (`viterbi`), and maximum a posteriori estimation (`map`) are supported. -This time, the input is a single sequence of observed values.:: +This time, the input is a single sequence of observed values. Note, the states +in model2 will have a different order than those in the generating model.:: >>> model2 = hmm.GaussianHMM(3, "full") >>> model2.fit([X]) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE GaussianHMM(algorithm='viterbi',... - >>> Z2 = model.predict(X) + >>> Z2 = model2.predict(X) .. topic:: Examples: - * :ref:`example_plot_hmm_stock_analysis.py` + * :ref:`example_applications_plot_hmm_stock_analysis.py` Implementing HMMs with custom emission probabilities diff --git a/doc/modules/isotonic.rst b/doc/modules/isotonic.rst new file mode 100644 index 0000000000000..9da18e4f069a2 --- /dev/null +++ b/doc/modules/isotonic.rst @@ -0,0 +1,23 @@ +.. _isotonic: + +=================== +Isotonic regression +=================== + +.. currentmodule:: sklearn.isotonic + +The class :class:`IsotonicRegression` fits a non-decreasing function to data. +It solves the following problem: + + minimize :math:`\sum_i w_i (y_i - \hat{y}_i)^2` + + subject to :math:`\hat{y}_{min} = \hat{y}_1 \le \hat{y}_2 ... \le \hat{y}_n = \hat{y}_{max}` + +where each :math:`w_i` is strictly positive and each :math:`y_i` is an +arbitrary real number. It yields the vector which is composed of non-decreasing +elements the closest in terms of mean squared error. In practice this list +of elements forms a function that is piecewise linear. + +.. figure:: ../auto_examples/images/plot_isotonic_regression_001.png + :target: ../auto_examples/images/plot_isotonic_regression.html + :align: center diff --git a/doc/modules/kernel_approximation.rst b/doc/modules/kernel_approximation.rst index 301e36d4daa5e..7048bf11dcb54 100644 --- a/doc/modules/kernel_approximation.rst +++ b/doc/modules/kernel_approximation.rst @@ -12,27 +12,61 @@ algorithms. .. currentmodule:: sklearn.linear_model -The advantage of using approximate explicit feature maps compared to the -`kernel trick `_, +The advantage of using approximate explicit feature maps compared to the +`kernel trick `_, which makes use of feature maps implicitly, is that explicit mappings can be better suited for online learning and can significantly reduce the cost of learning with very large datasets. Standard kernelized SVMs do not scale well to large datasets, but using an approximate kernel map it is possible to use much more efficient linear SVMs. -In particularly the combination of kernel map approximations with -:class:`SGDClassifier` can make nonlinear learning on large datasets possible. +In particular, the combination of kernel map approximations with +:class:`SGDClassifier` can make non-linear learning on large datasets possible. Since there has not been much empirical work using approximate embeddings, it is advisable to compare results against exact kernel methods when possible. +.. seealso:: -Radial Basis Function Kernel ----------------------------- + :ref:`polynomial_regression` for an exact polynomial transformation. .. currentmodule:: sklearn.kernel_approximation +.. _nystroem_kernel_approx: + +Nystroem Method for Kernel Approximation +---------------------------------------- +The Nystroem method, as implemented in :class:`Nystroem` is a general method +for low-rank approximations of kernels. It achieves this by essentially subsampling +the data on which the kernel is evaluated. +By default :class:`Nystroem` uses the ``rbf`` kernel, but it can use any +kernel function or a precomputed kernel matrix. +The number of samples used - which is also the dimensionality of the features computed - +is given by the parameter ``n_components``. + + +Radial Basis Function Kernel +---------------------------- + The :class:`RBFSampler` constructs an approximate mapping for the radial basis -function kernel. +function kernel, also known as *Random Kitchen Sinks* [RR2007]_. This +transformation can be used to explicitly model a kernel map, prior to applying +a linear algorithm, for example a linear SVM:: + + >>> from sklearn.kernel_approximation import RBFSampler + >>> from sklearn.linear_model import SGDClassifier + >>> X = [[0, 0], [1, 1], [1, 0], [0, 1]] + >>> y = [0, 0, 1, 1] + >>> rbf_feature = RBFSampler(gamma=1, random_state=1) + >>> X_features = rbf_feature.fit_transform(X) + >>> clf = SGDClassifier() # doctest: +NORMALIZE_WHITESPACE + >>> clf.fit(X_features, y) + SGDClassifier(alpha=0.0001, average=False, class_weight=None, epsilon=0.1, + eta0=0.0, fit_intercept=True, l1_ratio=0.15, + learning_rate='optimal', loss='hinge', n_iter=5, n_jobs=1, + penalty='l2', power_t=0.5, random_state=None, shuffle=True, + verbose=0, warm_start=False) + >>> clf.score(X_features, y) + 1.0 The mapping relies on a Monte Carlo approximation to the kernel values. The ``fit`` function performs the Monte Carlo sampling, whereas @@ -41,15 +75,19 @@ inherent randomness of the process, results may vary between different calls to the ``fit`` function. The ``fit`` function takes two arguments: -`n_components`, which is the target dimensionality of the feature transform, -and `gamma`, the parameter of the RBF-kernel. A higher `n_components` will +``n_components``, which is the target dimensionality of the feature transform, +and ``gamma``, the parameter of the RBF-kernel. A higher ``n_components`` will result in a better approximation of the kernel and will yield results more similar to those produced by a kernel SVM. Note that "fitting" the feature function does not actually depend on the data given to the ``fit`` function. Only the dimensionality of the data is used. Details on the method can be found in [RR2007]_. -.. figure:: ../auto_examples/images/plot_kernel_approximation_2.png +For a given value of ``n_components`` :class:`RBFSampler` is often less accurate +as :class:`Nystroem`. :class:`RBFSampler` is cheaper to compute, though, making +use of larger feature spaces more efficient. + +.. figure:: ../auto_examples/images/plot_kernel_approximation_002.png :target: ../auto_examples/plot_kernel_approximation.html :scale: 50% :align: center @@ -64,25 +102,28 @@ Details on the method can be found in [RR2007]_. Additive Chi Squared Kernel --------------------------- -The chi squared kernel is a kernel on histograms, often used in computer vision. +The additive chi squared kernel is a kernel on histograms, often used in computer vision. -The chi squared kernel is given by +The additive chi squared kernel as used here is given by .. math:: k(x, y) = \sum_i \frac{2x_iy_i}{x_i+y_i} +This is not exactly the same as :func:`sklearn.metrics.additive_chi2_kernel`. +The authors of [VZ2010]_ prefer the version above as it is always positive +definite. Since the kernel is additive, it is possible to treat all components :math:`x_i` separately for embedding. This makes it possible to sample the Fourier transform in regular intervals, instead of approximating using Monte Carlo sampling. The class :class:`AdditiveChi2Sampler` implements this component wise -deterministic sampling. Each component is sampled `n` times, yielding -`2n+1` dimensions per input dimension (the multiple of two stems +deterministic sampling. Each component is sampled :math:`n` times, yielding +:math:`2n+1` dimensions per input dimension (the multiple of two stems from the real and complex part of the Fourier transform). -In the literature, `n` is usually choosen to be `1` or `2`, transforming -the dataset to size `n_samples x 5 * n_features` (in the case of `n=2`). +In the literature, :math:`n` is usually chosen to be 1 or 2, transforming +the dataset to size ``n_samples * 5 * n_features`` (in the case of :math:`n=2`). The approximate feature map provided by :class:`AdditiveChi2Sampler` can be combined with the approximate feature map provided by :class:`RBFSampler` to yield an approximate @@ -102,11 +143,11 @@ The skewed chi squared kernel is given by: It has properties that are similar to the exponentiated chi squared kernel often used in computer vision, but allows for a simple Monte Carlo -approximation of the feature map. +approximation of the feature map. The usage of the :class:`SkewedChi2Sampler` is the same as the usage described above for the :class:`RBFSampler`. The only difference is in the free -parameter, that is called `c`. +parameter, that is called :math:`c`. For a motivation for this mapping and the mathematical details see [LS2010]_. @@ -115,22 +156,22 @@ Mathematical Details Kernel methods like support vector machines or kernelized PCA rely on a property of reproducing kernel Hilbert spaces. -For any positive definite kernel function `k` (a so called Mercer kernel), +For any positive definite kernel function :math:`k` (a so called Mercer kernel), it is guaranteed that there exists a mapping :math:`\phi` into a Hilbert space :math:`\mathcal{H}`, such that .. math:: - k(x,y) = < \phi(x), \phi(y)> + k(x,y) = \langle \phi(x), \phi(y) \rangle -Where :math:`< \cdot, \cdot >` denotes the inner product in the +Where :math:`\langle \cdot, \cdot \rangle` denotes the inner product in the Hilbert space. If an algorithm, such as a linear support vector machine or PCA, relies only on the scalar product of data points :math:`x_i`, one may use the value of :math:`k(x_i, x_j)`, which corresponds to applying the algorithm to the mapped data points :math:`\phi(x_i)`. -The advantage of using `k` is that the mapping :math:`\phi` never has +The advantage of using :math:`k` is that the mapping :math:`\phi` never has to be calculated explicitly, allowing for arbitrary large features (even infinite). diff --git a/doc/modules/kernel_ridge.rst b/doc/modules/kernel_ridge.rst new file mode 100644 index 0000000000000..6016604755bbc --- /dev/null +++ b/doc/modules/kernel_ridge.rst @@ -0,0 +1,57 @@ +.. _kernel_ridge: + +=========================== +Kernel ridge regression +=========================== + +.. currentmodule:: sklearn.kernel_ridge + +Kernel ridge regression (KRR) [M2012]_ combines :ref:`ridge_regression` +(linear least squares with l2-norm regularization) with the kernel trick. It +thus learns a linear function in the space induced by the respective kernel and +the data. For non-linear kernels, this corresponds to a non-linear +function in the original space. + +The form of the model learned by :class:`KernelRidge` is identical to support +vector regression (:class:`SVR`). However, different loss functions are used: +KRR uses squared error loss while support vector regression uses +:math:`\epsilon`-insensitive loss, both combined with l2 regularization. In +contrast to :class:`SVR`, fitting :class:`KernelRidge` can be done in +closed-form and is typically faster for medium-sized datasets. On the other +hand, the learned model is non-sparse and thus slower than SVR, which learns +a sparse model for :math:`\epsilon > 0`, at prediction-time. + +The following figure compares :class:`KernelRidge` and :class:`SVR` on +an artificial dataset, which consists of a sinusoidal target function and +strong noise added to every fifth datapoint. The learned model of +:class:`KernelRidge` and :class:`SVR` is plotted, where both +complexity/regularization and bandwidth of the RBF kernel have been optimized +using grid-search. The learned functions are very similar; however, fitting +:class:`KernelRidge` is approx. seven times faster than fitting :class:`SVR` +(both with grid-search). However, prediction of 100000 target values is more +than three times faster with SVR since it has learned a sparse model using only +approx. 1/3 of the 100 training datapoints as support vectors. + +.. figure:: ../auto_examples/images/plot_kernel_ridge_regression_001.png + :target: ../auto_examples/plot_kernel_ridge_regression.html + :align: center + +The next figure compares the time for fitting and prediction of +:class:`KernelRidge` and :class:`SVR` for different sizes of the training set. +Fitting :class:`KernelRidge` is faster than :class:`SVR` for medium-sized +training sets (less than 1000 samples); however, for larger training sets +:class:`SVR` scales better. With regard to prediction time, :class:`SVR` is +faster than :class:`KernelRidge` for all sizes of the training set because of +the learned sparse solution. Note that the degree of sparsity and thus the +prediction time depends on the parameters :math:`\epsilon` and :math:`C` of the +:class:`SVR`; :math:`\epsilon = 0` would correspond to a dense model. + +.. figure:: ../auto_examples/images/plot_kernel_ridge_regression_002.png + :target: ../auto_examples/plot_kernel_ridge_regression.html + :align: center + + +.. topic:: References: + + .. [M2012] "Machine Learning: A Probabilistic Perspective" + Murphy, K. P. - chapter 14.4.3, pp. 492-493, The MIT Press, 2012 diff --git a/doc/modules/label_propagation.rst b/doc/modules/label_propagation.rst index 833383c914c26..80f865f01c4d4 100644 --- a/doc/modules/label_propagation.rst +++ b/doc/modules/label_propagation.rst @@ -9,8 +9,8 @@ Semi-Supervised `Semi-supervised learning `_ is a situation in which in your training data some of the samples are not labeled. The -semi-supervised estimators, in :mod:`sklean.semi_supervised` are able to -make use of this addition unlabeled data to capture better the shape of +semi-supervised estimators in :mod:`sklearn.semi_supervised` are able to +make use of this additional unlabeled data to better capture the shape of the underlying data distribution and generalize better to new samples. These algorithms can perform well when we have a very small amount of labeled points and a large amount of unlabeled points. @@ -18,15 +18,15 @@ labeled points and a large amount of unlabeled points. .. topic:: Unlabeled entries in `y` It is important to assign an identifier to unlabeled points along with the - labeled data when training the model with the `fit` method. The identifier - that this implementation uses the integer value :math:`-1`. + labeled data when training the model with the ``fit`` method. The identifier + that this implementation uses is the integer value :math:`-1`. .. _label_propagation: Label Propagation ================= -Label propagation denote a few variations of semi-supervised graph +Label propagation denotes a few variations of semi-supervised graph inference algorithms. A few features available in this model: @@ -37,7 +37,7 @@ A few features available in this model: :class:`LabelPropagation` and :class:`LabelSpreading`. Both work by constructing a similarity graph over all items in the input dataset. -.. figure:: ../auto_examples/semi_supervised/images/plot_label_propagation_structure_1.png +.. figure:: ../auto_examples/semi_supervised/images/plot_label_propagation_structure_001.png :target: ../auto_examples/semi_supervised/plot_label_propagation_structure.html :align: center :scale: 60% @@ -75,18 +75,17 @@ available: * knn (:math:`1[x' \in kNN(x)]`). :math:`k` is specified by keyword n_neighbors. -RBF kernel will produce a fully connected graph which is represented in memory +The RBF kernel will produce a fully connected graph which is represented in memory by a dense matrix. This matrix may be very large and combined with the cost of performing a full matrix multiplication calculation for each iteration of the algorithm can lead to prohibitively long running times. On the other hand, -the KNN kernel will produce a much more memory friendly sparse matrix +the KNN kernel will produce a much more memory-friendly sparse matrix which can drastically reduce running times. .. topic:: Examples * :ref:`example_semi_supervised_plot_label_propagation_versus_svm_iris.py` * :ref:`example_semi_supervised_plot_label_propagation_structure.py` - * :ref:`example_semi_supervised_plot_label_propagation_versus_svm_iris.py` * :ref:`example_semi_supervised_plot_label_propagation_digits_active_learning.py` .. topic:: References diff --git a/doc/modules/lda_qda.rst b/doc/modules/lda_qda.rst index 854f75f7d650e..c7d251ea9261f 100644 --- a/doc/modules/lda_qda.rst +++ b/doc/modules/lda_qda.rst @@ -1,21 +1,23 @@ .. _lda_qda: ========================================== -Linear and Quadratic Discriminant Analysis +Linear and quadratic discriminant analysis ========================================== .. currentmodule:: sklearn -Linear Discriminant Analysis (:class:`lda.LDA`) and Quadratic Discriminant Analysis (:class:`qda.QDA`) +Linear discriminant analysis (:class:`lda.LDA`) and +quadratic discriminant analysis (:class:`qda.QDA`) are two classic classifiers, with, as their names suggest, a linear and a quadratic decision surface, respectively. -These classifiers are attractive because they have closed form solutions that -can be easily computed, are inherently multi-class, and have proven to work well in practice. +These classifiers are attractive because they have closed-form solutions that +can be easily computed, are inherently multiclass, +and have proven to work well in practice. Also there are no parameters to tune for these algorithms. -.. |ldaqda| image:: ../auto_examples/images/plot_lda_qda_1.png - :target: ../auto_examples/plot_lda_qda.html +.. |ldaqda| image:: ../auto_examples/classification/images/plot_lda_qda_001.png + :target: ../auto_examples/classification/plot_lda_qda.html :scale: 80 .. centered:: |ldaqda| @@ -26,22 +28,17 @@ quadratic boundaries and is therefore more flexible. .. topic:: Examples: - :ref:`example_plot_lda_qda.py`: Comparison of LDA and QDA on synthetic data. - -.. topic:: References: - - .. [3] "The Elements of Statistical Learning", Hastie T., Tibshirani R., - Friedman J., 2008. + :ref:`example_classification_plot_lda_qda.py`: Comparison of LDA and QDA on synthetic data. -Dimensionality Reduction using LDA +Dimensionality reduction using LDA ================================== :class:`lda.LDA` can be used to perform supervised dimensionality reduction by projecting the input data to a subspace consisting of the most discriminant directions. This is implemented in :func:`lda.LDA.transform`. The desired -dimensionality can be set using the `n_components` constructor +dimensionality can be set using the ``n_components`` constructor parameter. This parameter has no influence on :func:`lda.LDA.fit` or :func:`lda.LDA.predict`. @@ -49,12 +46,13 @@ Mathematical Idea ================= Both methods work by modeling the class conditional distribution of the data :math:`P(X|y=k)` -for each class `k`. Predictions can be obtained by using Bayes' rule: +for each class :math:`k`. Predictions can be obtained by using Bayes' rule: .. math:: P(y | X) = P(X | y) \cdot P(y) / P(X) = P(X | y) \cdot P(Y) / ( \sum_{y'} P(X | y') \cdot p(y')) -In linear and quadratic discriminant analysis, `P(X|y)` is modeled as a Gaussian distribution. +In linear and quadratic discriminant analysis, :math:`P(X|y)` +is modelled as a Gaussian distribution. In the case of LDA, the Gaussians for each class are assumed to share the same covariance matrix. This leads to a linear decision surface, as can be seen by comparing the the log-probability rations :math:`log[P(y=k | X) / P(y=l | X)]`. @@ -63,3 +61,57 @@ In the case of QDA, there are no assumptions on the covariance matrices of the G leading to a quadratic decision surface. +Shrinkage +========= + +Shrinkage is a tool to improve estimation of covariance matrices in situations +where the number of training samples is small compared to the number of +features. In this scenario, the empirical sample covariance is a poor +estimator. Shrinkage LDA can be used by setting the ``shrinkage`` parameter of +the :class:`lda.LDA` class to 'auto'. This automatically determines the +optimal shrinkage parameter in an analytic way following the lemma introduced +by Ledoit and Wolf. Note that currently shrinkage only works when setting the +``solver`` parameter to 'lsqr' or 'eigen'. + +The ``shrinkage`` parameter can also be manually set between 0 and 1. In +particular, a value of 0 corresponds to no shrinkage (which means the empirical +covariance matrix will be used) and a value of 1 corresponds to complete +shrinkage (which means that the diagonal matrix of variances will be used as +an estimate for the covariance matrix). Setting this parameter to a value +between these two extrema will estimate a shrunk version of the covariance +matrix. + +.. |shrinkage| image:: ../auto_examples/classification/images/plot_lda_001.png + :target: ../auto_examples/classification/plot_lda.html + :scale: 75 + +.. centered:: |shrinkage| + + +Estimation algorithms +===================== + +The default solver is 'svd'. It can perform both classification and transform, +and it does not rely on the calculation of the covariance matrix. This can be +an advantage in situations where the number of features is large. However, the +'svd' solver cannot be used with shrinkage. + +The 'lsqr' solver is an efficient algorithm that only works for classification. +It supports shrinkage. + +The 'eigen' solver is based on the optimization of the between class scatter to +within class scatter ratio. It can be used for both classification and +transform, and it supports shrinkage. However, the 'eigen' solver needs to +compute the covariance matrix, so it might not be suitable for situations with +a high number of features. + +.. topic:: Examples: + + :ref:`example_classification_plot_lda.py`: Comparison of LDA classifiers with and without shrinkage. + +.. topic:: References: + + Hastie T, Tibshirani R, Friedman J. The Elements of Statistical Learning. Springer, 2009. + + Ledoit O, Wolf M. Honey, I Shrunk the Sample Covariance Matrix. The Journal of Portfolio + Management 30(4), 110-119, 2004. diff --git a/doc/modules/learning_curve.rst b/doc/modules/learning_curve.rst new file mode 100644 index 0000000000000..4cd655fdbb6c0 --- /dev/null +++ b/doc/modules/learning_curve.rst @@ -0,0 +1,158 @@ +.. _learning_curves: + +===================================================== +Validation curves: plotting scores to evaluate models +===================================================== + +.. currentmodule:: sklearn.learning_curve + +Every estimator has its advantages and drawbacks. Its generalization error +can be decomposed in terms of bias, variance and noise. The **bias** of an +estimator is its average error for different training sets. The **variance** +of an estimator indicates how sensitive it is to varying training sets. Noise +is a property of the data. + +In the following plot, we see a function :math:`f(x) = \cos (\frac{3}{2} \pi x)` +and some noisy samples from that function. We use three different estimators +to fit the function: linear regression with polynomial features of degree 1, +4 and 15. We see that the first estimator can at best provide only a poor fit +to the samples and the true function because it is too simple (high bias), +the second estimator approximates it almost perfectly and the last estimator +approximates the training data perfectly but does not fit the true function +very well, i.e. it is very sensitive to varying training data (high variance). + +.. figure:: ../auto_examples/model_selection/images/plot_underfitting_overfitting_001.png + :target: ../auto_examples/model_selection/plot_underfitting_overfitting.html + :align: center + :scale: 50% + +Bias and variance are inherent properties of estimators and we usually have to +select learning algorithms and hyperparameters so that both bias and variance +are as low as possible (see `Bias-variance dilemma +`_). Another way to reduce +the variance of a model is to use more training data. However, you should only +collect more training data if the true function is too complex to be +approximated by an estimator with a lower variance. + +In the simple one-dimensional problem that we have seen in the example it is +easy to see whether the estimator suffers from bias or variance. However, in +high-dimensional spaces, models can become very difficult to visualize. For +this reason, it is often helpful to use the tools described below. + +.. topic:: Examples: + + * :ref:`example_model_selection_plot_underfitting_overfitting.py` + * :ref:`example_model_selection_plot_validation_curve.py` + * :ref:`example_model_selection_plot_learning_curve.py` + + +.. _validation_curve: + +Validation curve +================ + +To validate a model we need a scoring function (see :ref:`model_evaluation`), +for example accuracy for classifiers. The proper way of choosing multiple +hyperparameters of an estimator are of course grid search or similar methods +(see :ref:`grid_search`) that select the hyperparameter with the maximum score +on a validation set or multiple validation sets. Note that if we optimized +the hyperparameters based on a validation score the validation score is biased +and not a good estimate of the generalization any longer. To get a proper +estimate of the generalization we have to compute the score on another test +set. + +However, it is sometimes helpful to plot the influence of a single +hyperparameter on the training score and the validation score to find out +whether the estimator is overfitting or underfitting for some hyperparameter +values. + +The function :func:`validation_curve` can help in this case:: + + >>> import numpy as np + >>> from sklearn.learning_curve import validation_curve + >>> from sklearn.datasets import load_iris + >>> from sklearn.linear_model import Ridge + + >>> np.random.seed(0) + >>> iris = load_iris() + >>> X, y = iris.data, iris.target + >>> indices = np.arange(y.shape[0]) + >>> np.random.shuffle(indices) + >>> X, y = X[indices], y[indices] + + >>> train_scores, valid_scores = validation_curve(Ridge(), X, y, "alpha", + ... np.logspace(-7, 3, 3)) + >>> train_scores # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + array([[ 0.94..., 0.92..., 0.92...], + [ 0.94..., 0.92..., 0.92...], + [ 0.47..., 0.45..., 0.42...]]) + >>> valid_scores # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + array([[ 0.90..., 0.92..., 0.94...], + [ 0.90..., 0.92..., 0.94...], + [ 0.44..., 0.39..., 0.45...]]) + +If the training score and the validation score are both low, the estimator will +be underfitting. If the training score is high and the validation score is low, +the estimator is overfitting and otherwise it is working very well. A low +training score and a high validation score is usually not possible. All three +cases can be found in the plot below where we vary the parameter +:math:`\gamma` of an SVM on the digits dataset. + +.. figure:: ../auto_examples/model_selection/images/plot_validation_curve_001.png + :target: ../auto_examples/model_selection/plot_validation_curve.html + :align: center + :scale: 50% + + +.. _learning_curve: + +Learning curve +============== + +A learning curve shows the validation and training score of an estimator +for varying numbers of training samples. It is a tool to find out how much +we benefit from adding more training data and whether the estimator suffers +more from a variance error or a bias error. If both the validation score and +the training score converge to a value that is too low with increasing +size of the training set, we will not benefit much from more training data. +In the following plot you can see an example: naive Bayes roughly converges +to a low score. + +.. figure:: ../auto_examples/model_selection/images/plot_learning_curve_001.png + :target: ../auto_examples/model_selection/plot_learning_curve.html + :align: center + :scale: 50% + +We will probably have to use an estimator or a parametrization of the +current estimator that can learn more complex concepts (i.e. has a lower +bias). If the training score is much greater than the validation score for +the maximum number of training samples, adding more training samples will +most likely increase generalization. In the following plot you can see that +the SVM could benefit from more training examples. + +.. figure:: ../auto_examples/model_selection/images/plot_learning_curve_002.png + :target: ../auto_examples/model_selection/plot_learning_curve.html + :align: center + :scale: 50% + +We can use the function :func:`learning_curve` to generate the values +that are required to plot such a learning curve (number of samples +that have been used, the average scores on the training sets and the +average scores on the validation sets):: + + >>> from sklearn.learning_curve import learning_curve + >>> from sklearn.svm import SVC + + >>> train_sizes, train_scores, valid_scores = learning_curve( + ... SVC(kernel='linear'), X, y, train_sizes=[50, 80, 110], cv=5) + >>> train_sizes # doctest: +NORMALIZE_WHITESPACE + array([ 50, 80, 110]) + >>> train_scores # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + array([[ 0.98..., 0.98 , 0.98..., 0.98..., 0.98...], + [ 0.98..., 1. , 0.98..., 0.98..., 0.98...], + [ 0.98..., 1. , 0.98..., 0.98..., 0.99...]]) + >>> valid_scores # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + array([[ 1. , 0.93..., 1. , 1. , 0.96...], + [ 1. , 0.96..., 1. , 1. , 0.96...], + [ 1. , 0.96..., 1. , 1. , 0.96...]]) + diff --git a/doc/modules/linear_model.rst b/doc/modules/linear_model.rst index 61fbba73f9c75..01ede74bd60ee 100644 --- a/doc/modules/linear_model.rst +++ b/doc/modules/linear_model.rst @@ -33,19 +33,19 @@ solves a problem of the form: .. math:: \underset{w}{min\,} {|| X w - y||_2}^2 -.. figure:: ../auto_examples/linear_model/images/plot_ols_1.png +.. figure:: ../auto_examples/linear_model/images/plot_ols_001.png :target: ../auto_examples/linear_model/plot_ols.html :align: center :scale: 50% -:class:`LinearRegression` will take in its `fit` method arrays X, y +:class:`LinearRegression` will take in its ``fit`` method arrays X, y and will store the coefficients :math:`w` of the linear model in its -`coef\_` member:: +``coef_`` member:: >>> from sklearn import linear_model >>> clf = linear_model.LinearRegression() >>> clf.fit ([[0, 0], [1, 1], [2, 2]], [0, 1, 2]) - LinearRegression(copy_X=True, fit_intercept=True, normalize=False) + LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False) >>> clf.coef_ array([ 0.5, 0.5]) @@ -70,6 +70,7 @@ This method computes the least squares solution using a singular value decomposition of X. If X is a matrix of size (n, p) this method has a cost of :math:`O(n p^2)`, assuming that :math:`n \geq p`. +.. _ridge_regression: Ridge Regression ================ @@ -89,20 +90,21 @@ Here, :math:`\alpha \geq 0` is a complexity parameter that controls the amount of shrinkage: the larger the value of :math:`\alpha`, the greater the amount of shrinkage and thus the coefficients become more robust to collinearity. -.. figure:: ../auto_examples/linear_model/images/plot_ridge_path_1.png +.. figure:: ../auto_examples/linear_model/images/plot_ridge_path_001.png :target: ../auto_examples/linear_model/plot_ridge_path.html :align: center :scale: 50% -As with other linear models, :class:`Ridge` will take in its `fit` method +As with other linear models, :class:`Ridge` will take in its ``fit`` method arrays X, y and will store the coefficients :math:`w` of the linear model in -its `coef\_` member:: +its ``coef_`` member:: >>> from sklearn import linear_model >>> clf = linear_model.Ridge (alpha = .5) - >>> clf.fit ([[0, 0], [0, 0], [1, 1]], [0, .1, 1]) - Ridge(alpha=0.5, copy_X=True, fit_intercept=True, normalize=False, tol=0.001) + >>> clf.fit ([[0, 0], [0, 0], [1, 1]], [0, .1, 1]) # doctest: +NORMALIZE_WHITESPACE + Ridge(alpha=0.5, copy_X=True, fit_intercept=True, max_iter=None, + normalize=False, solver='auto', tol=0.001) >>> clf.coef_ array([ 0.34545455, 0.34545455]) >>> clf.intercept_ #doctest: +ELLIPSIS @@ -112,7 +114,7 @@ its `coef\_` member:: .. topic:: Examples: * :ref:`example_linear_model_plot_ridge_path.py` - * :ref:`example_document_classification_20newsgroups.py` + * :ref:`example_text_document_classification_20newsgroups.py` Ridge Complexity @@ -138,8 +140,8 @@ as GridSearchCV except that it defaults to Generalized Cross-Validation >>> from sklearn import linear_model >>> clf = linear_model.RidgeCV(alphas=[0.1, 1.0, 10.0]) >>> clf.fit([[0, 0], [0, 0], [1, 1]], [0, .1, 1]) # doctest: +SKIP - RidgeCV(alphas=[0.1, 1.0, 10.0], cv=None, fit_intercept=True, loss_func=None, - normalize=False, score_func=None) + RidgeCV(alphas=[0.1, 1.0, 10.0], cv=None, fit_intercept=True, scoring=None, + normalize=False) >>> clf.alpha_ # doctest: +SKIP 0.1 @@ -182,8 +184,8 @@ for another implementation:: >>> clf = linear_model.Lasso(alpha = 0.1) >>> clf.fit([[0, 0], [1, 1]], [0, 1]) Lasso(alpha=0.1, copy_X=True, fit_intercept=True, max_iter=1000, - normalize=False, positive=False, precompute='auto', tol=0.0001, - warm_start=False) + normalize=False, positive=False, precompute=False, random_state=None, + selection='cyclic', tol=0.0001, warm_start=False) >>> clf.predict([[1, 1]]) array([ 0.8]) @@ -211,28 +213,28 @@ computes the coefficients along the full path of possible values. Setting regularization parameter -------------------------------- -The `alpha` parameter control the degree of sparsity of the coefficients +The ``alpha`` parameter controls the degree of sparsity of the coefficients estimated. Using cross-validation ^^^^^^^^^^^^^^^^^^^^^^^ -scikit-learn exposes objects that set the Lasso `alpha` parameter by +scikit-learn exposes objects that set the Lasso ``alpha`` parameter by cross-validation: :class:`LassoCV` and :class:`LassoLarsCV`. :class:`LassoLarsCV` is based on the :ref:`least_angle_regression` algorithm explained below. For high-dimensional datasets with many collinear regressors, -:class:`LassoCV` is most often preferrable. How, :class:`LassoLarsCV` has +:class:`LassoCV` is most often preferable. However, :class:`LassoLarsCV` has the advantage of exploring more relevant values of `alpha` parameter, and if the number of samples is very small compared to the number of observations, it is often faster than :class:`LassoCV`. -.. |lasso_cv_1| image:: ../auto_examples/linear_model/images/plot_lasso_model_selection_2.png +.. |lasso_cv_1| image:: ../auto_examples/linear_model/images/plot_lasso_model_selection_002.png :target: ../auto_examples/linear_model/plot_lasso_model_selection.html :scale: 48% -.. |lasso_cv_2| image:: ../auto_examples/linear_model/images/plot_lasso_model_selection_3.png +.. |lasso_cv_2| image:: ../auto_examples/linear_model/images/plot_lasso_model_selection_003.png :target: ../auto_examples/linear_model/plot_lasso_model_selection.html :scale: 48% @@ -253,7 +255,7 @@ is correct, i.e. that the data are actually generated by this model. They also tend to break when the problem is badly conditioned (more features than samples). -.. figure:: ../auto_examples/linear_model/images/plot_lasso_model_selection_1.png +.. figure:: ../auto_examples/linear_model/images/plot_lasso_model_selection_001.png :target: ../auto_examples/linear_model/plot_lasso_model_selection.html :align: center :scale: 50% @@ -266,8 +268,18 @@ They also tend to break when the problem is badly conditioned Elastic Net =========== -:class:`ElasticNet` is a linear model trained with L1 and L2 prior as -regularizer. +:class:`ElasticNet` is a linear regression model trained with L1 and L2 prior +as regularizer. This combination allows for learning a sparse model where +few of the weights are non-zero like :class:`Lasso`, while still maintaining +the regularization properties of :class:`Ridge`. We control the convex +combination of L1 and L2 using the ``l1_ratio`` parameter. + +Elastic-net is useful when there are multiple features which are +correlated with one another. Lasso is likely to pick one of these +at random, while elastic-net is likely to pick both. + +A practical advantage of trading-off between Lasso and Ridge is it allows +Elastic-Net to inherit some of Ridge's stability under rotation. The objective function to minimize is in this case @@ -277,13 +289,13 @@ The objective function to minimize is in this case \frac{\alpha(1-\rho)}{2} ||w||_2 ^ 2} -.. figure:: ../auto_examples/linear_model/images/plot_lasso_coordinate_descent_path_1.png +.. figure:: ../auto_examples/linear_model/images/plot_lasso_coordinate_descent_path_001.png :target: ../auto_examples/linear_model/plot_lasso_coordinate_descent_path.html :align: center :scale: 50% -The class :class:`ElasticNetCV` can be used to set the parameters `alpha` -and `rho` by cross-validation. +The class :class:`ElasticNetCV` can be used to set the parameters +``alpha`` (:math:`\alpha`) and ``l1_ratio`` (:math:`\rho`) by cross-validation. .. topic:: Examples: @@ -297,7 +309,7 @@ Multi-task Lasso ================ The :class:`MultiTaskLasso` is a linear model that estimates sparse -coefficients for multiple regression problems jointly: `y` is a 2D array, +coefficients for multiple regression problems jointly: ``y`` is a 2D array, of shape (n_samples, n_tasks). The constraint is that the selected features are the same for all the regression problems, also called tasks. @@ -306,11 +318,11 @@ with a simple Lasso or a MultiTaskLasso. The Lasso estimates yields scattered non-zeros while the non-zeros of the MultiTaskLasso are full columns. -.. |multi_task_lasso_1| image:: ../auto_examples/linear_model/images/plot_multi_task_lasso_support_1.png +.. |multi_task_lasso_1| image:: ../auto_examples/linear_model/images/plot_multi_task_lasso_support_001.png :target: ../auto_examples/linear_model/plot_multi_task_lasso_support.html :scale: 48% -.. |multi_task_lasso_2| image:: ../auto_examples/linear_model/images/plot_multi_task_lasso_support_2.png +.. |multi_task_lasso_2| image:: ../auto_examples/linear_model/images/plot_multi_task_lasso_support_002.png :target: ../auto_examples/linear_model/plot_multi_task_lasso_support.html :scale: 48% @@ -332,7 +344,7 @@ The objective function to minimize is: where; -.. math:: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2} +.. math:: ||W||_{2 1} = \sum_i \sqrt{\sum_j w_{ij}^2} The implementation in the class :class:`MultiTaskLasso` uses coordinate descent as @@ -387,7 +399,7 @@ algorithm, and unlike the implementation based on coordinate_descent, this yields the exact solution, which is piecewise linear as a function of the norm of its coefficients. -.. figure:: ../auto_examples/linear_model/images/plot_lasso_lars_1.png +.. figure:: ../auto_examples/linear_model/images/plot_lasso_lars_001.png :target: ../auto_examples/linear_model/plot_lasso_lars.html :align: center :scale: 50% @@ -421,7 +433,7 @@ the residual. Instead of giving a vector result, the LARS solution consists of a curve denoting the solution for each value of the L1 norm of the -parameter vector. The full coeffients path is stored in the array +parameter vector. The full coefficients path is stored in the array ``coef_path_``, which has size (n_features, max_features+1). The first column is always zero. @@ -529,7 +541,7 @@ The prior for the parameter :math:`w` is given by a spherical Gaussian: .. math:: p(w|\lambda) = \mathcal{N}(w|0,\lambda^{-1}\bold{I_{p}}) -The priors over :math:`\alpha` and :math:`\lambda` are choosen to be `gamma +The priors over :math:`\alpha` and :math:`\lambda` are chosen to be `gamma distributions `__, the conjugate prior for the precision of the Gaussian. @@ -537,14 +549,14 @@ The resulting model is called *Bayesian Ridge Regression*, and is similar to the classical :class:`Ridge`. The parameters :math:`w`, :math:`\alpha` and :math:`\lambda` are estimated jointly during the fit of the model. The remaining hyperparameters are the parameters of the gamma priors over -:math:`\alpha` and :math:`\lambda`. These are usually choosen to be +:math:`\alpha` and :math:`\lambda`. These are usually chosen to be *non-informative*. The parameters are estimated by maximizing the *marginal log likelihood*. By default :math:`\alpha_1 = \alpha_2 = \lambda_1 = \lambda_2 = 1.e^{-6}`. -.. figure:: ../auto_examples/linear_model/images/plot_bayesian_ridge_1.png +.. figure:: ../auto_examples/linear_model/images/plot_bayesian_ridge_001.png :target: ../auto_examples/linear_model/plot_bayesian_ridge.html :align: center :scale: 50% @@ -592,7 +604,7 @@ Automatic Relevance Determination - ARD --------------------------------------- :class:`ARDRegression` is very similar to `Bayesian Ridge Regression`_, -but can lead to sparser weights :math:`w` [1]_. +but can lead to sparser weights :math:`w` [1]_ [2]_. :class:`ARDRegression` poses a different prior over :math:`w`, by dropping the assumption of the Gaussian being spherical. @@ -606,12 +618,12 @@ centered on zero and with a precision :math:`\lambda_{i}`: with :math:`diag \; (A) = \lambda = \{\lambda_{1},...,\lambda_{p}\}`. -In constrast to `Bayesian Ridge Regression`_, each coordinate of :math:`w_{i}` +In contrast to `Bayesian Ridge Regression`_, each coordinate of :math:`w_{i}` has its own standard deviation :math:`\lambda_i`. The prior over all -:math:`\lambda_i` is choosen to be the same gamma distribution given by +:math:`\lambda_i` is chosen to be the same gamma distribution given by hyperparameters :math:`\lambda_1` and :math:`\lambda_2`. -.. figure:: ../auto_examples/linear_model/images/plot_ard_1.png +.. figure:: ../auto_examples/linear_model/images/plot_ard_001.png :target: ../auto_examples/linear_model/plot_ard.html :align: center :scale: 50% @@ -623,7 +635,9 @@ hyperparameters :math:`\lambda_1` and :math:`\lambda_2`. .. topic:: References: - .. [1] David Wipf and Srikantan Nagarajan: `A new view of automatic relevance determination. `_ + .. [1] Christopher M. Bishop: Pattern Recognition and Machine Learning, Chapter 7.2.1 + + .. [2] David Wipf and Srikantan Nagarajan: `A new view of automatic relevance determination. `_ .. _Logistic_regression: @@ -631,18 +645,55 @@ Logistic regression =================== Logistic regression, despite its name, is a linear model for classification -rather than regression. -As such, it minimizes a "hit or miss" cost function -rather than the sum of square residuals (as in ordinary regression). -Logistic regression is also known in the literature as +rather than regression. Logistic regression is also known in the literature as logit regression, maximum-entropy classification (MaxEnt) -or the log-linear classifier. +or the log-linear classifier. In this model, the probabilities describing the possible outcomes of a single trial are modeled using a `logistic function `_. + +The implementation of logistic regression in scikit-learn can be accessed from +class :class:`LogisticRegression`. This +implementation can fit a multiclass (one-vs-rest) logistic regression with optional +L2 or L1 regularization. + +As an optimization problem, binary class L2 penalized logistic regression minimizes +the following cost function: + +.. math:: \underset{w, c}{min\,} \frac{1}{2}w^T w + C \sum_{i=1}^n \log(\exp(- y_i (X_i^T w + c)) + 1) . + +Similarly, L1 regularized logistic regression solves the following optimization problem + +.. math:: \underset{w, c}{min\,} \|w\|_1 + C \sum_{i=1}^n \log(\exp(- y_i (X_i^T w + c)) + 1) . -The :class:`LogisticRegression` class can be used to do L1 or L2 penalized -logistic regression. L1 penalization yields sparse predicting weights. -For L1 penalization :func:`sklearn.svm.l1_min_c` allows to calculate -the lower bound for C in order to get a non "null" (all feature weights to -zero) model. +The solvers implemented in the class :class:`LogisticRegression` +are "liblinear" (which is a wrapper around the C++ library, +LIBLINEAR), "newton-cg" and "lbfgs". + +The lbfgs and newton-cg solvers only support L2 penalization and are found +to converge faster for some high dimensional data. L1 penalization yields +sparse predicting weights. + +Several estimators are available for logistic regression. + +:class:`LogisticRegression` has an option of using three solvers, +"liblinear", "lbfgs" and "newton-cg". + +The solver "liblinear" uses a coordinate descent (CD) algorithm based on +Liblinear. For L1 penalization :func:`sklearn.svm.l1_min_c` allows to +calculate the lower bound for C in order to get a non "null" (all feature weights to +zero) model. This relies on the excellent +`LIBLINEAR library `_, +which is shipped with scikit-learn. However, the CD algorithm implemented in +liblinear cannot learn a true multinomial (multiclass) model; +instead, the optimization problem is decomposed in a "one-vs-rest" fashion +so separate binary classifiers are trained for all classes. +This happens under the hood, so :class:`LogisticRegression` instances +using this solver behave as multiclass classifiers. + +Setting `multi_class` to "multinomial" with the "lbfgs" or "newton-cg" solver +in :class:`LogisticRegression` learns a true multinomial logistic +regression model, which means that its probability estimates should +be better calibrated than the default "one-vs-rest" setting. +L-BFGS and newton-cg cannot optimize L1-penalized models, though, +so the "multinomial" setting does not learn sparse models. .. topic:: Examples: @@ -650,23 +701,50 @@ zero) model. * :ref:`example_linear_model_plot_logistic_path.py` +.. _liblinear_differences: + +.. topic:: Differences from liblinear: + + There might be a difference in the scores obtained between + :class:`LogisticRegression` with ``solver=liblinear`` + or :class:`LinearSVC` and the external liblinear library directly, + when ``fit_intercept=False`` and the fit ``coef_`` (or) the data to + be predicted are zeroes. This is because for the sample(s) with + ``decision_function`` zero, :class:`LogisticRegression` and :class:`LinearSVC` + predict the negative class, while liblinear predicts the positive class. + Note that a model with ``fit_intercept=False`` and having many samples with + ``decision_function`` zero, is likely to be a underfit, bad model and you are + advised to set ``fit_intercept=True`` and increase the intercept_scaling. + .. note:: **Feature selection with sparse logistic regression** A logistic regression with L1 penalty yields sparse models, and can thus be used to perform feature selection, as detailed in :ref:`l1_feature_selection`. +:class:`LogisticRegressionCV` implements Logistic Regression with +builtin cross-validation to find out the optimal C parameter. In +general the "newton-cg" and "lbfgs" solvers are found to be faster +due to warm-starting. For the multiclass case, if `multi_class` +option is set to "ovr", an optimal C is obtained for each class and if +the `multi_class` option is set to "multinomial", an optimal C is +obtained that minimizes the cross-entropy loss. + + Stochastic Gradient Descent - SGD ================================= Stochastic gradient descent is a simple yet very efficient approach -to fit linear models. It is particulary useful when the number of samples +to fit linear models. It is particularly useful when the number of samples (and the number of features) is very large. - +The ``partial_fit`` method allows only/out-of-core learning. The classes :class:`SGDClassifier` and :class:`SGDRegressor` provide functionality to fit linear models for classification and regression using different (convex) loss functions and different penalties. +E.g., with ``loss="log"``, :class:`SGDClassifier` +fits a logistic regression model, +while with ``loss="hinge"`` it fits a linear support vector machine (SVM). .. topic:: References @@ -688,21 +766,348 @@ The last characteristic implies that the Perceptron is slightly faster to train than SGD with the hinge loss and that the resulting models are sparser. -Isotonic regression -==================== +.. _passive_aggressive: + +Passive Aggressive Algorithms +============================= + +The passive-aggressive algorithms are a family of algorithms for large-scale +learning. They are similar to the Perceptron in that they do not require a +learning rate. However, contrary to the Perceptron, they include a +regularization parameter ``C``. + +For classification, :class:`PassiveAggressiveClassifier` can be used with +``loss='hinge'`` (PA-I) or ``loss='squared_hinge'`` (PA-II). For regression, +:class:`PassiveAggressiveRegressor` can be used with +``loss='epsilon_insensitive'`` (PA-I) or +``loss='squared_epsilon_insensitive'`` (PA-II). + +.. topic:: References: -The :class:`IsotonicRegression` fits a non-decreasing function to the data. -It solves the following problem: - minimize :math:`\sum_i w_i (y_i - \hat{y}_i)^2` + * `"Online Passive-Aggressive Algorithms" + `_ + K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR 7 (2006) - subject to :math:`\hat{y}_{min} = \hat{y}_1 \le \hat{y}_2 ... \le \hat{y}_n = \hat{y}_{max}` -where each :math:`w_i` is strictly positive and each :math:`y_i` is an -arbitrary real number. It yields the vector which is composed of non-decreasing -elements the closest in terms of mean squared error. In practice this list -of elements forms a function that is piecewise linear. +Robustness regression: outliers and modeling errors +===================================================== -.. figure:: ../auto_examples/linear_model/images/plot_isotonic_regression_1.png - :target: ../auto_examples/linear_model/images/plot_isotonic_regression.html +Robust regression is interested in fitting a regression model in the +presence of corrupt data: either outliers, or error in the model. + +.. figure:: ../auto_examples/linear_model/images/plot_theilsen_001.png + :target: ../auto_examples/linear_model/plot_theilsen.html + :scale: 50% :align: center + +Different scenario and useful concepts +---------------------------------------- + +There are different things to keep in mind when dealing with data +corrupted by outliers: + +.. |y_outliers| image:: ../auto_examples/linear_model/images/plot_robust_fit_003.png + :target: ../auto_examples/linear_model/plot_robust_fit.html + :scale: 60% + +.. |X_outliers| image:: ../auto_examples/linear_model/images/plot_robust_fit_002.png + :target: ../auto_examples/linear_model/plot_robust_fit.html + :scale: 60% + +.. |large_y_outliers| image:: ../auto_examples/linear_model/images/plot_robust_fit_005.png + :target: ../auto_examples/linear_model/plot_robust_fit.html + :scale: 60% + +* **Outliers in X or in y**? + + ==================================== ==================================== + Outliers in the y direction Outliers in the X direction + ==================================== ==================================== + |y_outliers| |X_outliers| + ==================================== ==================================== + +* **Fraction of outliers versus amplitude of error** + + The number of outlying points matters, but also how much they are + outliers. + + ==================================== ==================================== + Small outliers Large outliers + ==================================== ==================================== + |y_outliers| |large_y_outliers| + ==================================== ==================================== + +An important notion of robust fitting is that of breakdown point: the +fraction of data that can be outlying for the fit to start missing the +inlying data. + +Note that in general, robust fitting in high-dimensional setting (large +`n_features`) is very hard. The robust models here will probably not work +in these settings. + + +.. topic:: **Trade-offs: which estimator?** + + Scikit-learn provides 2 robust regression estimators: + :ref:`RANSAC ` and + :ref:`Theil Sen ` + + * :ref:`RANSAC ` is faster, and scales much better + with the number of samples + + * :ref:`RANSAC ` will deal better with large + outliers in the y direction (most common situation) + + * :ref:`Theil Sen ` will cope better with + medium-size outliers in the X direction, but this property will + disappear in large dimensional settings. + + When in doubt, use :ref:`RANSAC ` + +.. _ransac_regression: + +RANSAC: RANdom SAmple Consensus +-------------------------------- + +RANSAC (RANdom SAmple Consensus) fits a model from random subsets of +inliers from the complete data set. + +RANSAC is a non-deterministic algorithm producing only a reasonable result with +a certain probability, which is dependent on the number of iterations (see +`max_trials` parameter). It is typically used for linear and non-linear +regression problems and is especially popular in the fields of photogrammetric +computer vision. + +The algorithm splits the complete input sample data into a set of inliers, +which may be subject to noise, and outliers, which are e.g. caused by erroneous +measurements or invalid hypotheses about the data. The resulting model is then +estimated only from the determined inliers. + +.. figure:: ../auto_examples/linear_model/images/plot_ransac_001.png + :target: ../auto_examples/linear_model/plot_ransac.html + :align: center + :scale: 50% + +Details of the algorithm +^^^^^^^^^^^^^^^^^^^^^^^^ + +Each iteration performs the following steps: + +1. Select ``min_samples`` random samples from the original data and check + whether the set of data is valid (see ``is_data_valid``). +2. Fit a model to the random subset (``base_estimator.fit``) and check + whether the estimated model is valid (see ``is_model_valid``). +3. Classify all data as inliers or outliers by calculating the residuals + to the estimated model (``base_estimator.predict(X) - y``) - all data + samples with absolute residuals smaller than the ``residual_threshold`` + are considered as inliers. +4. Save fitted model as best model if number of inlier samples is + maximal. In case the current estimated model has the same number of + inliers, it is only considered as the best model if it has better score. + +These steps are performed either a maximum number of times (``max_trials``) or +until one of the special stop criteria are met (see ``stop_n_inliers`` and +``stop_score``). The final model is estimated using all inlier samples (consensus +set) of the previously determined best model. + +The ``is_data_valid`` and ``is_model_valid`` functions allow to identify and reject +degenerate combinations of random sub-samples. If the estimated model is not +needed for identifying degenerate cases, ``is_data_valid`` should be used as it +is called prior to fitting the model and thus leading to better computational +performance. + + +.. topic:: Examples: + + * :ref:`example_linear_model_plot_ransac.py` + * :ref:`example_linear_model_plot_robust_fit.py` + +.. topic:: References: + + * http://en.wikipedia.org/wiki/RANSAC + * `"Random Sample Consensus: A Paradigm for Model Fitting with Applications to + Image Analysis and Automated Cartography" + `_ + Martin A. Fischler and Robert C. Bolles - SRI International (1981) + * `"Performance Evaluation of RANSAC Family" + `_ + Sunglok Choi, Taemin Kim and Wonpil Yu - BMVC (2009) + +.. _theil_sen_regression: + +Theil-Sen estimator: generalized-median-based estimator +-------------------------------------------------------- + +The :class:`TheilSenRegressor` estimator uses a generalization of the median in +multiple dimensions. It is thus robust to multivariate outliers. Note however +that the robustness of the estimator decreases quickly with the dimensionality +of the problem. It looses its robustness properties and becomes no +better than an ordinary least squares in high dimension. + +.. topic:: Examples: + + * :ref:`example_linear_model_plot_theilsen.py` + * :ref:`example_linear_model_plot_robust_fit.py` + +.. topic:: References: + + * http://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator + +Theoretical considerations +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:class:`TheilSenRegressor` is comparable to the :ref:`Ordinary Least Squares +(OLS) ` in terms of asymptotic efficiency and as an +unbiased estimator. In contrast to OLS, Theil-Sen is a non-parametric +method which means it makes no assumption about the underlying +distribution of the data. Since Theil-Sen is a median-based estimator, it +is more robust against corrupted data aka outliers. In univariate +setting, Theil-Sen has a breakdown point of about 29.3% in case of a +simple linear regression which means that it can tolerate arbitrary +corrupted data of up to 29.3%. + +.. figure:: ../auto_examples/linear_model/images/plot_theilsen_001.png + :target: ../auto_examples/linear_model/plot_theilsen.html + :align: center + :scale: 50% + +The implementation of :class:`TheilSenRegressor` in scikit-learn follows a +generalization to a multivariate linear regression model [#f1]_ using the +spatial median which is a generalization of the median to multiple +dimensions [#f2]_. + +In terms of time and space complexity, Theil-Sen scales according to + +.. math:: + \binom{n_{samples}}{n_{subsamples}} + +which makes it infeasible to be applied exhaustively to problems with a +large number of samples and features. Therefore, the magnitude of a +subpopulation can be chosen to limit the time and space complexity by +considering only a random subset of all possible combinations. + +.. topic:: Examples: + + * :ref:`example_linear_model_plot_theilsen.py` + +.. topic:: References: + + .. [#f1] Xin Dang, Hanxiang Peng, Xueqin Wang and Heping Zhang: `Theil-Sen Estimators in a Multiple Linear Regression Model. `_ + + .. [#f2] T. Kärkkäinen and S. Äyrämö: `On Computation of Spatial Median for Robust Data Mining. `_ + +.. _polynomial_regression: + +Polynomial regression: extending linear models with basis functions +=================================================================== + +.. currentmodule:: sklearn.preprocessing + +One common pattern within machine learning is to use linear models trained +on nonlinear functions of the data. This approach maintains the generally +fast performance of linear methods, while allowing them to fit a much wider +range of data. + +For example, a simple linear regression can be extended by constructing +**polynomial features** from the coefficients. In the standard linear +regression case, you might have a model that looks like this for +two-dimensional data: + +.. math:: \hat{y}(w, x) = w_0 + w_1 x_1 + w_2 x_2 + +If we want to fit a paraboloid to the data instead of a plane, we can combine +the features in second-order polynomials, so that the model looks like this: + +.. math:: \hat{y}(w, x) = w_0 + w_1 x_1 + w_2 x_2 + w_3 x_1 x_2 + w_4 x_1^2 + w_5 x_2^2 + +The (sometimes surprising) observation is that this is *still a linear model*: +to see this, imagine creating a new variable + +.. math:: z = [x_1, x_2, x_1 x_2, x_1^2, x_2^2] + +With this re-labeling of the data, our problem can be written + +.. math:: \hat{y}(w, x) = w_0 + w_1 z_1 + w_2 z_2 + w_3 z_3 + w_4 z_4 + w_5 z_5 + +We see that the resulting *polynomial regression* is in the same class of +linear models we'd considered above (i.e. the model is linear in :math:`w`) +and can be solved by the same techniques. By considering linear fits within +a higher-dimensional space built with these basis functions, the model has the +flexibility to fit a much broader range of data. + +Here is an example of applying this idea to one-dimensional data, using +polynomial features of varying degrees: + +.. figure:: ../auto_examples/linear_model/images/plot_polynomial_interpolation_001.png + :target: ../auto_examples/linear_model/plot_polynomial_interpolation.html + :align: center + :scale: 50% + +This figure is created using the :class:`PolynomialFeatures` preprocessor. +This preprocessor transforms an input data matrix into a new data matrix +of a given degree. It can be used as follows:: + + >>> from sklearn.preprocessing import PolynomialFeatures + >>> import numpy as np + >>> X = np.arange(6).reshape(3, 2) + >>> X + array([[0, 1], + [2, 3], + [4, 5]]) + >>> poly = PolynomialFeatures(degree=2) + >>> poly.fit_transform(X) + array([[ 1, 0, 1, 0, 0, 1], + [ 1, 2, 3, 4, 6, 9], + [ 1, 4, 5, 16, 20, 25]]) + +The features of ``X`` have been transformed from :math:`[x_1, x_2]` to +:math:`[1, x_1, x_2, x_1^2, x_1 x_2, x_2^2]`, and can now be used within +any linear model. + +This sort of preprocessing can be streamlined with the +:ref:`Pipeline ` tools. A single object representing a simple +polynomial regression can be created and used as follows:: + + >>> from sklearn.preprocessing import PolynomialFeatures + >>> from sklearn.linear_model import LinearRegression + >>> from sklearn.pipeline import Pipeline + >>> model = Pipeline([('poly', PolynomialFeatures(degree=3)), + ... ('linear', LinearRegression(fit_intercept=False))]) + >>> # fit to an order-3 polynomial data + >>> x = np.arange(5) + >>> y = 3 - 2 * x + x ** 2 - x ** 3 + >>> model = model.fit(x[:, np.newaxis], y) + >>> model.named_steps['linear'].coef_ + array([ 3., -2., 1., -1.]) + +The linear model trained on polynomial features is able to exactly recover +the input polynomial coefficients. + +In some cases it's not necessary to include higher powers of any single feature, +but only the so-called *interaction features* +that multiply together at most :math:`d` distinct features. +These can be gotten from :class:`PolynomialFeatures` with the setting +``interaction_only=True``. + +For example, when dealing with boolean features, +:math:`x_i^n = x_i` for all :math:`n` and is therefore useless; +but :math:`x_i x_j` represents the conjunction of two booleans. +This way, we can solve the XOR problem with a linear classifier:: + + >>> from sklearn.linear_model import Perceptron + >>> from sklearn.preprocessing import PolynomialFeatures + >>> X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) + >>> y = X[:, 0] ^ X[:, 1] + >>> X = PolynomialFeatures(interaction_only=True).fit_transform(X) + >>> X + array([[1, 0, 0, 0], + [1, 0, 1, 0], + [1, 1, 0, 0], + [1, 1, 1, 1]]) + >>> clf = Perceptron(fit_intercept=False, n_iter=10, shuffle=False).fit(X, y) + >>> clf.score(X, y) + 1.0 + + + diff --git a/doc/modules/manifold.rst b/doc/modules/manifold.rst index e68439bc97a1e..5cf546906a72b 100644 --- a/doc/modules/manifold.rst +++ b/doc/modules/manifold.rst @@ -20,12 +20,12 @@ Manifold learning -.. figure:: ../auto_examples/manifold/images/plot_compare_methods_1.png +.. figure:: ../auto_examples/manifold/images/plot_compare_methods_001.png :target: ../auto_examples/manifold/plot_compare_methods.html :align: center :scale: 60 -Manifold learning is an approach to nonlinear dimensionality reduction. +Manifold learning is an approach to non-linear dimensionality reduction. Algorithms for this task are based on the idea that the dimensionality of many data sets is only artificially high. @@ -46,11 +46,11 @@ to be desired. In a random projection, it is likely that the more interesting structure within the data will be lost. -.. |digits_img| image:: ../auto_examples/manifold/images/plot_lle_digits_1.png +.. |digits_img| image:: ../auto_examples/manifold/images/plot_lle_digits_001.png :target: ../auto_examples/manifold/plot_lle_digits.html :scale: 50 -.. |projected_img| image:: ../auto_examples/manifold/images/plot_lle_digits_2.png +.. |projected_img| image:: ../auto_examples/manifold/images/plot_lle_digits_002.png :target: ../auto_examples/manifold/plot_lle_digits.html :scale: 50 @@ -62,22 +62,22 @@ dimensionality reduction frameworks have been designed, such as Principal Component Analysis (PCA), Independent Component Analysis, Linear Discriminant Analysis, and others. These algorithms define specific rubrics to choose an "interesting" linear projection of the data. -These methods can be powerful, but often miss important nonlinear +These methods can be powerful, but often miss important non-linear structure in the data. -.. |PCA_img| image:: ../auto_examples/manifold/images/plot_lle_digits_3.png +.. |PCA_img| image:: ../auto_examples/manifold/images/plot_lle_digits_003.png :target: ../auto_examples/manifold/plot_lle_digits.html :scale: 50 -.. |LDA_img| image:: ../auto_examples/manifold/images/plot_lle_digits_4.png +.. |LDA_img| image:: ../auto_examples/manifold/images/plot_lle_digits_004.png :target: ../auto_examples/manifold/plot_lle_digits.html :scale: 50 .. centered:: |PCA_img| |LDA_img| Manifold Learning can be thought of as an attempt to generalize linear -frameworks like PCA to be sensitive to nonlinear structure in data. Though +frameworks like PCA to be sensitive to non-linear structure in data. Though supervised variants exist, the typical manifold learning problem is unsupervised: it learns the high-dimensional structure of the data from the data itself, without the use of predetermined classifications. @@ -94,6 +94,8 @@ from the data itself, without the use of predetermined classifications. The manifold learning implementations available in sklearn are summarized below +.. _isomap: + Isomap ====== @@ -104,7 +106,7 @@ Isomap seeks a lower-dimensional embedding which maintains geodesic distances between all points. Isomap can be performed with the object :class:`Isomap`. -.. figure:: ../auto_examples/manifold/images/plot_lle_digits_5.png +.. figure:: ../auto_examples/manifold/images/plot_lle_digits_005.png :target: ../auto_examples/manifold/plot_lle_digits.html :align: center :scale: 50 @@ -154,13 +156,13 @@ Locally Linear Embedding Locally linear embedding (LLE) seeks a lower-dimensional projection of the data which preserves distances within local neighborhoods. It can be thought of as a series of local Principal Component Analyses which are globally -compared to find the best nonlinear embedding. +compared to find the best non-linear embedding. Locally linear embedding can be performed with function :func:`locally_linear_embedding` or its object-oriented counterpart :class:`LocallyLinearEmbedding`. -.. figure:: ../auto_examples/manifold/images/plot_lle_digits_6.png +.. figure:: ../auto_examples/manifold/images/plot_lle_digits_006.png :target: ../auto_examples/manifold/plot_lle_digits.html :align: center :scale: 50 @@ -202,7 +204,7 @@ of neighbors is greater than the number of input dimensions, the matrix defining each local neighborhood is rank-deficient. To address this, standard LLE applies an arbitrary regularization parameter :math:`r`, which is chosen relative to the trace of the local weight matrix. Though it can be shown -formally that as :math:`r \to 0`, the solution coverges to the desired +formally that as :math:`r \to 0`, the solution converges to the desired embedding, there is no guarantee that the optimal solution will be found for :math:`r > 0`. This problem manifests itself in embeddings which distort the underlying geometry of the manifold. @@ -214,7 +216,7 @@ linear embedding* (MLLE). MLLE can be performed with function :class:`LocallyLinearEmbedding`, with the keyword ``method = 'modified'``. It requires ``n_neighbors > n_components``. -.. figure:: ../auto_examples/manifold/images/plot_lle_digits_7.png +.. figure:: ../auto_examples/manifold/images/plot_lle_digits_007.png :target: ../auto_examples/manifold/plot_lle_digits.html :align: center :scale: 50 @@ -264,7 +266,7 @@ for small output dimension. HLLE can be performed with function :class:`LocallyLinearEmbedding`, with the keyword ``method = 'hessian'``. It requires ``n_neighbors > n_components * (n_components + 3) / 2``. -.. figure:: ../auto_examples/manifold/images/plot_lle_digits_8.png +.. figure:: ../auto_examples/manifold/images/plot_lle_digits_008.png :target: ../auto_examples/manifold/plot_lle_digits.html :align: center :scale: 50 @@ -297,6 +299,52 @@ The overall complexity of standard HLLE is high-dimensional data" `_ Donoho, D. & Grimes, C. Proc Natl Acad Sci USA. 100:5591 (2003) +.. _spectral_embedding: + +Spectral Embedding +==================== + +Spectral Embedding (also known as Laplacian Eigenmaps) is one method +to calculate non-linear embedding. It finds a low dimensional representation +of the data using a spectral decomposition of the graph Laplacian. +The graph generated can be considered as a discrete approximation of the +low dimensional manifold in the high dimensional space. Minimization of a +cost function based on the graph ensures that points close to each other on +the manifold are mapped close to each other in the low dimensional space, +preserving local distances. Spectral embedding can be performed with the +function :func:`spectral_embedding` or its object-oriented counterpart +:class:`SpectralEmbedding`. + +Complexity +---------- + +The Spectral Embedding algorithm comprises three stages: + +1. **Weighted Graph Construction**. Transform the raw input data into + graph representation using affinity (adjacency) matrix representation. + +2. **Graph Laplacian Construction**. unnormalized Graph Laplacian + is constructed as :math:`L = D - A` for and normalized one as + :math:`L = D^{-\frac{1}{2}} (D - A) D^{-\frac{1}{2}}`. + +3. **Partial Eigenvalue Decomposition**. Eigenvalue decomposition is + done on graph Laplacian + +The overall complexity of spectral embedding is +:math:`O[D \log(k) N \log(N)] + O[D N k^3] + O[d N^2]`. + +* :math:`N` : number of training data points +* :math:`D` : input dimension +* :math:`k` : number of nearest neighbors +* :math:`d` : output dimension + +.. topic:: References: + + * `"Laplacian Eigenmaps for Dimensionality Reduction + and Data Representation" + `_ + M. Belkin, P. Niyogi, Neural Computation, June 2003; 15 (6):1373-1396 + Local Tangent Space Alignment ============================= @@ -310,11 +358,11 @@ tangent spaces to learn the embedding. LTSA can be performed with function :func:`locally_linear_embedding` or its object-oriented counterpart :class:`LocallyLinearEmbedding`, with the keyword ``method = 'ltsa'``. -.. figure:: ../auto_examples/manifold/images/plot_lle_digits_9.png +.. figure:: ../auto_examples/manifold/images/plot_lle_digits_009.png :target: ../auto_examples/manifold/plot_lle_digits.html :align: center :scale: 50 - + Complexity ---------- @@ -348,7 +396,8 @@ The overall complexity of standard LTSA is Multi-dimensional Scaling (MDS) =============================== -Multidimensional scaling (:class:`MDS`) seeks a low-dimensional +`Multidimensional scaling `_ +(:class:`MDS`) seeks a low-dimensional representation of the data in which the distances respect well the distances in the original high-dimensional space. @@ -360,14 +409,14 @@ countries. There exists two types of MDS algorithm: metric and non metric. In the scikit-learn, the class :class:`MDS` implements both. In Metric MDS, the input -simiarity matrix arises from a metric (and thus respects the triangular +similarity matrix arises from a metric (and thus respects the triangular inequality), the distances between output two points are then set to be as -close as possible to the similarity or dissimilarity data. In the non metric -vision, the algorithms will try to preserve the order of the distances, and +close as possible to the similarity or dissimilarity data. In the non-metric +version, the algorithms will try to preserve the order of the distances, and hence seek for a monotonic relationship between the distances in the embedded space and the similarities/dissimilarities. -.. figure:: ../auto_examples/manifold/images/plot_lle_digits_10.png +.. figure:: ../auto_examples/manifold/images/plot_lle_digits_010.png :target: ../auto_examples/manifold/plot_lle_digits.html :align: center :scale: 50 @@ -382,7 +431,7 @@ stress, is then defined by :math:`sum_{i < j} d_{ij}(X) - \hat{d}_{ij}(X)` Metric MDS ---------- -The simplest metric :class:`MDS` model, called `absolute MDS`, disparities are defined by +The simplest metric :class:`MDS` model, called *absolute MDS*, disparities are defined by :math:`\hat{d}_{ij} = S_{ij}`. With absolute MDS, the value :math:`S_{ij}` should then correspond exactly to the distance between point :math:`i` and :math:`j` in the embedding point. @@ -402,7 +451,7 @@ A trivial solution to this problem is to set all the points on the origin. In order to avoid that, the disparities :math:`\hat{d}_{ij}` are normalized. -.. figure:: ../auto_examples/manifold/images/plot_mds_1.png +.. figure:: ../auto_examples/manifold/images/plot_mds_001.png :target: ../auto_examples/manifold/plot_mds.html :align: center :scale: 60 @@ -422,6 +471,84 @@ order to avoid that, the disparities :math:`\hat{d}_{ij}` are normalized. `_ Kruskal, J. Psychometrika, 29, (1964) +.. _t_sne: + +t-distributed Stochastic Neighbor Embedding (t-SNE) +=================================================== + +t-SNE (:class:`TSNE`) converts affinities of data points to probabilities. +The affinities in the original space are represented by Gaussian joint +probabilities and the affinities in the embedded space are represented by +Student's t-distributions. The Kullback-Leibler (KL) divergence of the joint +probabilities in the original space and the embedded space will be minimized +by gradient descent. Note that the KL divergence is not convex, i.e. +multiple restarts with different initializations will end up in local minima +of the KL divergence. Hence, it is sometimes useful to try different seeds +and select the embedding with the lowest KL divergence. + + +.. figure:: ../auto_examples/manifold/images/plot_lle_digits_013.png + :target: ../auto_examples/manifold/plot_lle_digits.html + :align: center + :scale: 50 + + +The main purpose of t-SNE is visualization of high-dimensional data. Hence, +it works best when the data will be embedded on two or three dimensions. + +Optimizing the KL divergence can be a little bit tricky sometimes. There are +three parameters that control the optimization of t-SNE: + +* early exaggeration factor +* learning rate +* maximum number of iterations + +The maximum number of iterations is usually high enough and does not need +any tuning. The optimization consists of two phases: the early exaggeration +phase and the final optimization. During early exaggeration the joint +probabilities in the original space will be artificially increased by +multiplication with a given factor. Larger factors result in larger gaps +between natural clusters in the data. If the factor is too high, the KL +divergence could increase during this phase. Usually it does not have to be +tuned. A critical parameter is the learning rate. If it is too low gradient +descent will get stuck in a bad local minimum. If it is too high the KL +divergence will increase during optimization. More tips can be found in +Laurens van der Maaten's FAQ (see references). + +Standard t-SNE that has been implemented here is usually much slower than +other manifold learning algorithms. The optimization is quite difficult +and the computation of the gradient is on :math:`O[d N^2]`, where :math:`d` +is the number of output dimensions and :math:`N` is the number of samples. + +While Isomap, LLE and variants are best suited to unfold a single continuous +low dimensional manifold, t-SNE will focus on the local structure of the data +and will tend to extract clustered local groups of samples as highlighted on +the S-curve example. This ability to group samples based on the local structure +might be beneficial to visually disentangle a dataset that comprises several +manifolds at once as is the case in the digits dataset. + +Also note that the digits labels roughly match the natural grouping found by +t-SNE while the linear 2D projection of the PCA model yields a representation +where label regions largely overlap. This is a strong clue that this data can +be well separated by non linear methods that focus on the local structure (e.g. +an SVM with a Gaussian RBF kernel). However, failing to visualize well +separated homogeneously labeled groups with t-SNE in 2D does not necessarily +implie that the data cannot be correctly classified by a supervised model. It +might be the case that 2 dimensions are not enough low to accurately represents +the internal structure of the data. + + +.. topic:: References: + + * `"Visualizing High-Dimensional Data Using t-SNE" + `_ + van der Maaten, L.J.P.; Hinton, G. Journal of Machine Learning Research + (2008) + + * `"t-Distributed Stochastic Neighbor Embedding" + `_ + van der Maaten, L.J.P. + Tips on practical use ===================== @@ -449,3 +576,10 @@ Tips on practical use can attempt to understand the source of the singularity: if it is due to disjoint sets, increasing ``n_neighbors`` may help. If it is due to identical points in the dataset, removing these points may help. + +.. seealso:: + + :ref:`random_trees_embedding` can also be useful to derive non-linear + representations of feature space, also it does not perform + dimensionality reduction. + diff --git a/doc/modules/metrics.rst b/doc/modules/metrics.rst new file mode 100644 index 0000000000000..9bba16c7d77ff --- /dev/null +++ b/doc/modules/metrics.rst @@ -0,0 +1,174 @@ +.. _metrics: + +Pairwise metrics, Affinities and Kernels +======================================== + +The :mod:`sklearn.metrics.pairwise` submodule implements utilities to evaluate +pairwise distances or affinity of sets of samples. + +This module contains both distance metrics and kernels. A brief summary is +given on the two here. + +Distance metrics are functions ``d(a, b)`` such that ``d(a, b) < d(a, c)`` +if objects ``a`` and ``b`` are considered "more similar" than objects ``a`` +and ``c``. Two objects exactly alike would have a distance of zero. +One of the most popular examples is Euclidean distance. +To be a 'true' metric, it must obey the following four conditions:: + + 1. d(a, b) >= 0, for all a and b + 2. d(a, b) == 0, if and only if a = b, positive definiteness + 3. d(a, b) == d(b, a), symmetry + 4. d(a, c) <= d(a, b) + d(b, c), the triangle inequality + +Kernels are measures of similarity, i.e. ``s(a, b) > s(a, c)`` +if objects ``a`` and ``b`` are considered "more similar" than objects +``a`` and ``c``. A kernel must also be positive semi-definite. + +There are a number of ways to convert between a distance metric and a +similarity measure, such as a kernel. Let ``D`` be the distance, and ``S`` be +the kernel: + + 1. ``S = np.exp(-D * gamma)``, where one heuristic for choosing + ``gamma`` is ``1 / num_features`` + 2. ``S = 1. / (D / np.max(D))`` + + +.. currentmodule:: sklearn.metrics.pairwise + +Cosine similarity +----------------- +:func:`cosine_similarity` computes the L2-normalized dot product of vectors. +That is, if :math:`x` and :math:`y` are row vectors, +their cosine similarity :math:`k` is defined as: + +.. math:: + + k(x, y) = \frac{x y^\top}{\|x\| \|y\|} + +This is called cosine similarity, because Euclidean (L2) normalization +projects the vectors onto the unit sphere, +and their dot product is then the cosine of the angle between the points +denoted by the vectors. + +This kernel is a popular choice for computing the similarity of documents +represented as tf-idf vectors. +:func:`cosine_similarity` accepts ``scipy.sparse`` matrices. +(Note that the tf-idf functionality in ``sklearn.feature_extraction.text`` +can produce normalized vectors, in which case :func:`cosine_similarity` +is equivalent to :func:`linear_kernel`, only slower.) + +.. topic:: References: + + * C.D. Manning, P. Raghavan and H. Schütze (2008). Introduction to + Information Retrieval. Cambridge University Press. + http://nlp.stanford.edu/IR-book/html/htmledition/the-vector-space-model-for-scoring-1.html + +Linear kernel +------------- +The function :func:`linear_kernel` computes the linear kernel, that is, a +special case of :func:`polynomial_kernel` with ``degree=1`` and ``coef0=0`` (homogeneous). +If ``x`` and ``y`` are column vectors, their linear kernel is: + +.. math:: + + k(x, y) = x^\top y + +Polynomial kernel +----------------- +The function :func:`polynomial_kernel` computes the degree-d polynomial kernel +between two vectors. The polynomial kernel represents the similarity between two +vectors. Conceptually, the polynomial kernels considers not only the similarity +between vectors under the same dimension, but also across dimensions. When used +in machine learning algorithms, this allows to account for feature interaction. + +The polynomial kernel is defined as: + +.. math:: + + k(x, y) = (\gamma x^\top y +c_0)^d + +where: + + * ``x``, ``y`` are the input vectors + * ``d`` is the kernel degree + +If :math:`c_0 = 0` the kernel is said to be homogeneous. + +Sigmoid kernel +-------------- +The function :func:`sigmoid_kernel` computes the sigmoid kernel between two +vectors. The sigmoid kernel is also known as hyperbolic tangent, or Multilayer +Perceptron (because, in the neural network field, it is often used as neuron +activation function). It is defined as: + +.. math:: + + k(x, y) = \tanh( \gamma x^\top y + c_0) + +where: + + * ``x``, ``y`` are the input vectors + * :math:`\gamma` is known as slope + * :math:`c_0` is known as intercept + +RBF kernel +---------- +The function :func:`rbf_kernel` computes the radial basis function (RBF) kernel +between two vectors. This kernel is defined as: + +.. math:: + + k(x, y) = \exp( -\gamma \| x-y \|^2) + +where ``x`` and ``y`` are the input vectors. If :math:`\gamma = \sigma^{-2}` +the kernel is known as the Gaussian kernel of variance :math:`\sigma^2`. + +Chi-squared kernel +------------------ +The chi-squared kernel is a very popular choice for training non-linear SVMs in +computer vision applications. +It can be computed using :func:`chi2_kernel` and then passed to an +:class:`sklearn.svm.SVC` with ``kernel="precomputed"``:: + + >>> from sklearn.svm import SVC + >>> from sklearn.metrics.pairwise import chi2_kernel + >>> X = [[0, 1], [1, 0], [.2, .8], [.7, .3]] + >>> y = [0, 1, 0, 1] + >>> K = chi2_kernel(X, gamma=.5) + >>> K # doctest: +ELLIPSIS + array([[ 1. , 0.36..., 0.89..., 0.58...], + [ 0.36..., 1. , 0.51..., 0.83...], + [ 0.89..., 0.51..., 1. , 0.77... ], + [ 0.58..., 0.83..., 0.77... , 1. ]]) + + >>> svm = SVC(kernel='precomputed').fit(K, y) + >>> svm.predict(K) + array([0, 1, 0, 1]) + +It can also be directly used as the ``kernel`` argument:: + + >>> svm = SVC(kernel=chi2_kernel).fit(X, y) + >>> svm.predict(X) + array([0, 1, 0, 1]) + + +The chi squared kernel is given by + +.. math:: + + k(x, y) = \exp \left (-\gamma \sum_i \frac{(x[i] - y[i]) ^ 2}{x[i] + y[i]} \right ) + +The data is assumed to be non-negative, and is often normalized to have an L1-norm of one. +The normalization is rationalized with the connection to the chi squared distance, +which is a distance between discrete probability distributions. + +The chi squared kernel is most commonly used on histograms (bags) of visual words. + +.. topic:: References: + + * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. + Local features and kernels for classification of texture and object + categories: A comprehensive study + International Journal of Computer Vision 2007 + http://eprints.pascal-network.org/archive/00002309/01/Zhang06-IJCV.pdf + diff --git a/doc/modules/mixture.rst b/doc/modules/mixture.rst index e13d17407a960..2b2560c261144 100644 --- a/doc/modules/mixture.rst +++ b/doc/modules/mixture.rst @@ -14,7 +14,7 @@ matrices supported), sample them, and estimate them from data. Facilities to help determine the appropriate number of components are also provided. - .. figure:: ../auto_examples/mixture/images/plot_gmm_pdf_1.png + .. figure:: ../auto_examples/mixture/images/plot_gmm_pdf_001.png :target: ../auto_examples/mixture/plot_gmm_pdf.html :align: center :scale: 50% @@ -29,7 +29,7 @@ mixture models as generalizing k-means clustering to incorporate information about the covariance structure of the data as well as the centers of the latent Gaussians. -The `scikit-learn` implements different classes to estimate Gaussian +Scikit-learn implements different classes to estimate Gaussian mixture models, that correspond to different estimation strategies, detailed below. @@ -55,7 +55,7 @@ The :class:`GMM` comes with different options to constrain the covariance of the difference classes estimated: spherical, diagonal, tied or full covariance. -.. figure:: ../auto_examples/mixture/images/plot_gmm_classifier_1.png +.. figure:: ../auto_examples/mixture/images/plot_gmm_classifier_001.png :target: ../auto_examples/mixture/plot_gmm_classifier.html :align: center :scale: 75% @@ -102,7 +102,7 @@ only in the asymptotic regime (i.e. if much data is available). Note that using a :ref:`DPGMM ` avoids the specification of the number of components for a Gaussian mixture model. -.. figure:: ../auto_examples/mixture/images/plot_gmm_selection_1.png +.. figure:: ../auto_examples/mixture/images/plot_gmm_selection_001.png :target: ../auto_examples/mixture/plot_gmm_selection.html :align: center :scale: 50% @@ -123,7 +123,7 @@ which latent component (if one has access to this information it gets very easy to fit a separate Gaussian distribution to each set of points). `Expectation-maximization `_ -is a well-fundamented statistical +is a well-founded statistical algorithm to get around this problem by an iterative process. First one assumes random components (randomly centered on data points, learned from k-means, or even just normally distributed around the @@ -190,7 +190,7 @@ much so as to render usage unpractical. Due to its Bayesian nature, the variational algorithm needs more hyper-parameters than expectation-maximization, the most -important of these being the concentration parameter `alpha`. Specifying +important of these being the concentration parameter ``alpha``. Specifying a high value of alpha leads more often to uniformly-sized mixture components, while specifying small (between 0 and 1) values will lead to some mixture components getting almost all the points while most @@ -210,11 +210,11 @@ components, and at the expense of extra computational time the user only needs to specify a loose upper bound on this number and a concentration parameter. -.. |plot_gmm| image:: ../auto_examples/mixture/images/plot_gmm_1.png +.. |plot_gmm| image:: ../auto_examples/mixture/images/plot_gmm_001.png :target: ../auto_examples/mixture/plot_gmm.html :scale: 48% -.. |plot_gmm_sin| image:: ../auto_examples/mixture/images/plot_gmm_sin_1.png +.. |plot_gmm_sin| image:: ../auto_examples/mixture/images/plot_gmm_sin_001.png :target: ../auto_examples/mixture/plot_gmm_sin.html :scale: 48% @@ -239,7 +239,7 @@ data. * :ref:`example_mixture_plot_gmm_sin.py` shows using :class:`GMM` and :class:`DPGMM` to fit a sine wave -Pros and cons of class :class:`DPGMM`: Diriclet process mixture model +Pros and cons of class :class:`DPGMM`: Dirichlet process mixture model ---------------------------------------------------------------------- Pros diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst new file mode 100644 index 0000000000000..1991b710e12c3 --- /dev/null +++ b/doc/modules/model_evaluation.rst @@ -0,0 +1,1331 @@ +.. currentmodule:: sklearn + +.. _model_evaluation: + +======================================================== +Model evaluation: quantifying the quality of predictions +======================================================== + +There are 3 different approaches to evaluate the quality of predictions of a +model: + +* **Estimator score method**: Estimators have a ``score`` method providing a + default evaluation criterion for the problem they are designed to solve. + This is not discussed on this page, but in each estimator's documentation. + +* **Scoring parameter**: Model-evaluation tools using + :ref:`cross-validation ` (such as + :func:`cross_validation.cross_val_score` and + :class:`grid_search.GridSearchCV`) rely on an internal *scoring* strategy. + This is discussed in the section :ref:`scoring_parameter`. + +* **Metric functions**: The :mod:`metrics` module implements functions + assessing prediction error for specific purposes. These metrics are detailed + in sections on :ref:`classification_metrics`, + :ref:`multilabel_ranking_metrics`, :ref:`regression_metrics` and + :ref:`clustering_metrics`. + +Finally, :ref:`dummy_estimators` are useful to get a baseline +value of those metrics for random predictions. + +.. seealso:: + + For "pairwise" metrics, between *samples* and not estimators or + predictions, see the :ref:`metrics` section. + +.. _scoring_parameter: + +The ``scoring`` parameter: defining model evaluation rules +========================================================== + +Model selection and evaluation using tools, such as +:class:`grid_search.GridSearchCV` and +:func:`cross_validation.cross_val_score`, take a ``scoring`` parameter that +controls what metric they apply to the estimators evaluated. + +Common cases: predefined values +------------------------------- + +For the most common use cases, you can designate a scorer object with the +``scoring`` parameter; the table below shows all possible values. +All scorer ojects follow the convention that higher return values are better +than lower return values. Thus the returns from mean_absolute_error +and mean_squared_error, which measure the distance between the model +and the data, are negated. + + +======================== ======================================= ================================== +Scoring Function Comment +======================== ======================================= ================================== +**Classification** +'accuracy' :func:`metrics.accuracy_score` +'average_precision' :func:`metrics.average_precision_score` +'f1' :func:`metrics.f1_score` for binary targets +'f1_micro' :func:`metrics.f1_score` micro-averaged +'f1_macro' :func:`metrics.f1_score` macro-averaged +'f1_weighted' :func:`metrics.f1_score` weighted average +'f1_samples' :func:`metrics.f1_score` by multilabel sample +'log_loss' :func:`metrics.log_loss` requires ``predict_proba`` support +'precision' etc. :func:`metrics.precision_score` suffixes apply as with 'f1' +'recall' etc. :func:`metrics.recall_score` suffixes apply as with 'f1' +'roc_auc' :func:`metrics.roc_auc_score` + +**Clustering** +'adjusted_rand_score' :func:`metrics.adjusted_rand_score` + +**Regression** +'mean_absolute_error' :func:`metrics.mean_absolute_error` +'mean_squared_error' :func:`metrics.mean_squared_error` +'median_absolute_error' :func:`metrics.median_absolute_error` +'r2' :func:`metrics.r2_score` +======================== ======================================= ================================== + +Usage examples: + + >>> from sklearn import svm, cross_validation, datasets + >>> iris = datasets.load_iris() + >>> X, y = iris.data, iris.target + >>> model = svm.SVC() + >>> cross_validation.cross_val_score(model, X, y, scoring='wrong_choice') + Traceback (most recent call last): + ValueError: 'wrong_choice' is not a valid scoring value. Valid options are ['accuracy', 'adjusted_rand_score', 'average_precision', 'f1', 'f1_macro', 'f1_micro', 'f1_samples', 'f1_weighted', 'log_loss', 'mean_absolute_error', 'mean_squared_error', 'median_absolute_error', 'precision', 'precision_macro', 'precision_micro', 'precision_samples', 'precision_weighted', 'r2', 'recall', 'recall_macro', 'recall_micro', 'recall_samples', 'recall_weighted', 'roc_auc'] + >>> clf = svm.SVC(probability=True, random_state=0) + >>> cross_validation.cross_val_score(clf, X, y, scoring='log_loss') # doctest: +ELLIPSIS + array([-0.07..., -0.16..., -0.06...]) + +.. note:: + + The values listed by the ValueError exception correspond to the functions measuring + prediction accuracy described in the following sections. + The scorer objects for those functions are stored in the dictionary + ``sklearn.metrics.SCORERS``. + +.. currentmodule:: sklearn.metrics + +.. _scoring: + +Defining your scoring strategy from metric functions +----------------------------------------------------- + +The module :mod:`sklearn.metric` also exposes a set of simple functions +measuring a prediction error given ground truth and prediction: + +- functions ending with ``_score`` return a value to + maximize, the higher the better. + +- functions ending with ``_error`` or ``_loss`` return a + value to minimize, the lower the better. When converting + into a scorer object using :func:`make_scorer`, set + the ``greater_is_better`` parameter to False (True by default; see the + parameter description below). + +Metrics available for various machine learning tasks are detailed in sections +below. + +Many metrics are not given names to be used as ``scoring`` values, +sometimes because they require additional parameters, such as +:func:`fbeta_score`. In such cases, you need to generate an appropriate +scoring object. The simplest way to generate a callable object for scoring +is by using :func:`make_scorer`. That function converts metrics +into callables that can be used for model evaluation. + +One typical use case is to wrap an existing metric function from the library +with non-default values for its parameters, such as the ``beta`` parameter for +the :func:`fbeta_score` function:: + + >>> from sklearn.metrics import fbeta_score, make_scorer + >>> ftwo_scorer = make_scorer(fbeta_score, beta=2) + >>> from sklearn.grid_search import GridSearchCV + >>> from sklearn.svm import LinearSVC + >>> grid = GridSearchCV(LinearSVC(), param_grid={'C': [1, 10]}, scoring=ftwo_scorer) + +The second use case is to build a completely custom scorer object +from a simple python function using :func:`make_scorer`, which can +take several parameters: + +* the python function you want to use (``my_custom_loss_func`` + in the example below) + +* whether the python function returns a score (``greater_is_better=True``, + the default) or a loss (``greater_is_better=False``). If a loss, the output + of the python function is negated by the scorer object, conforming to + the cross validation convention that scorers return higher values for better models. + +* for classification metrics only: whether the python function you provided requires continuous decision + certainties (``needs_threshold=True``). The default value is + False. + +* any additional parameters, such as ``beta`` in an :func:`f1_score`. + +Here is an example of building custom scorers, and of using the +``greater_is_better`` parameter:: + + >>> import numpy as np + >>> def my_custom_loss_func(ground_truth, predictions): + ... diff = np.abs(ground_truth - predictions).max() + ... return np.log(1 + diff) + ... + >>> # loss_func will negate the return value of my_custom_loss_func, + >>> # which will be np.log(2), 0.693, given the values for ground_truth + >>> # and predictions defined below. + >>> loss = make_scorer(my_custom_loss_func, greater_is_better=False) + >>> score = make_scorer(my_custom_loss_func, greater_is_better=True) + >>> ground_truth = [1, 1] + >>> predictions = [0, 1] + >>> from sklearn.dummy import DummyClassifier + >>> clf = DummyClassifier(strategy='most_frequent', random_state=0) + >>> clf = clf.fit(ground_truth, predictions) + >>> loss(clf,ground_truth, predictions) # doctest: +ELLIPSIS + -0.69... + >>> score(clf,ground_truth, predictions) # doctest: +ELLIPSIS + 0.69... + + +.. _diy_scoring: + +Implementing your own scoring object +------------------------------------ +You can generate even more flexible model scorers by constructing your own +scoring object from scratch, without using the :func:`make_scorer` factory. +For a callable to be a scorer, it needs to meet the protocol specified by +the following two rules: + +- It can be called with parameters ``(estimator, X, y)``, where ``estimator`` + is the model that should be evaluated, ``X`` is validation data, and ``y`` is + the ground truth target for ``X`` (in the supervised case) or ``None`` (in the + unsupervised case). + +- It returns a floating point number that quantifies the + ``estimator`` prediction quality on ``X``, with reference to ``y``. + Again, by convention higher numbers are better, so if your scorer + returns loss, that value should be negated. + + +.. _classification_metrics: + +Classification metrics +======================= + +.. currentmodule:: sklearn.metrics + +The :mod:`sklearn.metrics` module implements several loss, score, and utility +functions to measure classification performance. +Some metrics might require probability estimates of the positive class, +confidence values, or binary decisions values. +Most implementations allow each sample to provide a weighted contribution +to the overall score, through the ``sample_weight`` parameter. + +Some of these are restricted to the binary classification case: + +.. autosummary:: + :template: function.rst + + matthews_corrcoef + precision_recall_curve + roc_curve + + +Others also work in the multiclass case: + +.. autosummary:: + :template: function.rst + + confusion_matrix + hinge_loss + + +Some also work in the multilabel case: + +.. autosummary:: + :template: function.rst + + accuracy_score + classification_report + f1_score + fbeta_score + hamming_loss + jaccard_similarity_score + log_loss + precision_recall_fscore_support + precision_score + recall_score + zero_one_loss + +And some work with binary and multilabel (but not multiclass) problems: + +.. autosummary:: + :template: function.rst + + average_precision_score + roc_auc_score + + +In the following sub-sections, we will describe each of those functions, +preceded by some notes on common API and metric definition. + +From binary to multiclass and multilabel +---------------------------------------- + +Some metrics are essentially defined for binary classification tasks (e.g. +:func:`f1_score`, :func:`roc_auc_score`). In these cases, by default +only the positive label is evaluated, assuming by default that the positive +class is labelled ``1`` (though this may be configurable through the +``pos_label`` parameter). + +.. _average: + +In extending a binary metric to multiclass or multilabel problems, the data +is treated as a collection of binary problems, one for each class. +There are then a number of ways to average binary metric calculations across +the set of classes, each of which may be useful in some scenario. +Where available, you should select among these using the ``average`` parameter. + +* ``"macro"`` simply calculates the mean of the binary metrics, + giving equal weight to each class. In problems where infrequent classes + are nonetheless important, macro-averaging may be a means of highlighting + their performance. On the other hand, the assumption that all classes are + equally important is often untrue, such that macro-averaging will + over-emphasize the typically low performance on an infrequent class. +* ``"weighted"`` accounts for class imbalance by computing the average of + binary metrics in which each class's score is weighted by its presence in the + true data sample. +* ``"micro"`` gives each sample-class pair an equal contribution to the overall + metric (except as a result of sample-weight). Rather than summing the + metric per class, this sums the dividends and divisors that make up the the + per-class metrics to calculate an overall quotient. + Micro-averaging may be preferred in multilabel settings, including + multiclass classification where a majority class is to be ignored. +* ``"samples"`` applies only to multilabel problems. It does not calculate a + per-class measure, instead calculating the metric over the true and predicted + classes for each sample in the evaluation data, and returning their + (``sample_weight``-weighted) average. +* Selecting ``average=None`` will return an array with the score for each + class. + +While multiclass data is provided to the metric, like binary targets, as an +array of class labels, multilabel data is specified as an indicator matrix, +in which cell ``[i, j]`` has value 1 if sample ``i`` has label ``j`` and value +0 otherwise. + + +Accuracy score +-------------- + +The :func:`accuracy_score` function computes the +`accuracy `_, either the fraction +(default) or the count (normalize=False) of correct predictions. + + +In multilabel classification, the function returns the subset accuracy. If +the entire set of predicted labels for a sample strictly match with the true +set of labels, then the subset accuracy is 1.0; otherwise it is 0.0. + +If :math:`\hat{y}_i` is the predicted value of +the :math:`i`-th sample and :math:`y_i` is the corresponding true value, +then the fraction of correct predictions over :math:`n_\text{samples}` is +defined as + +.. math:: + + \texttt{accuracy}(y, \hat{y}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples}-1} 1(\hat{y}_i = y_i) + +where :math:`1(x)` is the `indicator function +`_. + + >>> import numpy as np + >>> from sklearn.metrics import accuracy_score + >>> y_pred = [0, 2, 1, 3] + >>> y_true = [0, 1, 2, 3] + >>> accuracy_score(y_true, y_pred) + 0.5 + >>> accuracy_score(y_true, y_pred, normalize=False) + 2 + +In the multilabel case with binary label indicators: :: + + >>> accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) + 0.5 + +.. topic:: Example: + + * See :ref:`example_feature_selection_plot_permutation_test_for_classification.py` + for an example of accuracy score usage using permutations of + the dataset. + +Confusion matrix +---------------- + +The :func:`confusion_matrix` function evaluates +classification accuracy by computing the `confusion matrix +`_. + +By definition, entry :math:`i, j` in a confusion matrix is +the number of observations actually in group :math:`i`, but +predicted to be in group :math:`j`. Here is an example:: + + >>> from sklearn.metrics import confusion_matrix + >>> y_true = [2, 0, 2, 2, 0, 1] + >>> y_pred = [0, 0, 2, 2, 0, 2] + >>> confusion_matrix(y_true, y_pred) + array([[2, 0, 0], + [0, 0, 1], + [1, 0, 2]]) + +Here is a visual representation of such a confusion matrix (this figure comes +from the :ref:`example_model_selection_plot_confusion_matrix.py` example): + +.. image:: ../auto_examples/model_selection/images/plot_confusion_matrix_001.png + :target: ../auto_examples/model_selection/plot_confusion_matrix.html + :scale: 75 + :align: center + +.. topic:: Example: + + * See :ref:`example_model_selection_plot_confusion_matrix.py` + for an example of using a confusion matrix to evaluate classifier output + quality. + + * See :ref:`example_classification_plot_digits_classification.py` + for an example of using a confusion matrix to classify + hand-written digits. + + * See :ref:`example_text_document_classification_20newsgroups.py` + for an example of using a confusion matrix to classify text + documents. + + +Classification report +---------------------- + +The :func:`classification_report` function builds a text report showing the +main classification metrics. Here is a small example with custom ``target_names`` +and inferred labels:: + + >>> from sklearn.metrics import classification_report + >>> y_true = [0, 1, 2, 2, 0] + >>> y_pred = [0, 0, 2, 2, 0] + >>> target_names = ['class 0', 'class 1', 'class 2'] + >>> print(classification_report(y_true, y_pred, target_names=target_names)) + precision recall f1-score support + + class 0 0.67 1.00 0.80 2 + class 1 0.00 0.00 0.00 1 + class 2 1.00 1.00 1.00 2 + + avg / total 0.67 0.80 0.72 5 + + +.. topic:: Example: + + * See :ref:`example_classification_plot_digits_classification.py` + for an example of classification report usage for + hand-written digits. + + * See :ref:`example_text_document_classification_20newsgroups.py` + for an example of classification report usage for text + documents. + + * See :ref:`example_model_selection_grid_search_digits.py` + for an example of classification report usage for + grid search with nested cross-validation. + +Hamming loss +------------- + +The :func:`hamming_loss` computes the average Hamming loss or `Hamming +distance `_ between two sets +of samples. + +If :math:`\hat{y}_j` is the predicted value for the :math:`j`-th label of +a given sample, :math:`y_j` is the corresponding true value, and +:math:`n_\text{labels}` is the number of classes or labels, then the +Hamming loss :math:`L_{Hamming}` between two samples is defined as: + +.. math:: + + L_{Hamming}(y, \hat{y}) = \frac{1}{n_\text{labels}} \sum_{j=0}^{n_\text{labels} - 1} 1(\hat{y}_j \not= y_j) + +where :math:`1(x)` is the `indicator function +`_. :: + + >>> from sklearn.metrics import hamming_loss + >>> y_pred = [1, 2, 3, 4] + >>> y_true = [2, 2, 3, 4] + >>> hamming_loss(y_true, y_pred) + 0.25 + +In the multilabel case with binary label indicators: :: + + >>> hamming_loss(np.array([[0, 1], [1, 1]]), np.zeros((2, 2))) + 0.75 + +.. note:: + + In multiclass classification, the Hamming loss corresponds to the Hamming + distance between ``y_true`` and ``y_pred`` which is similar to the + :ref:`zero_one_loss` function. However, while zero-one loss penalizes + prediction sets that do not strictly match true sets, the Hamming loss + penalizes individual labels. Thus the Hamming loss, upper bounded by the zero-one + loss, is always between zero and one, inclusive; and predicting a proper subset + or superset of the true labels will give a Hamming loss between + zero and one, exclusive. + +Jaccard similarity coefficient score +------------------------------------- + +The :func:`jaccard_similarity_score` function computes the average (default) +or sum of `Jaccard similarity coefficients +`_, also called the Jaccard index, +between pairs of label sets. + +The Jaccard similarity coefficient of the :math:`i`-th samples, +with a ground truth label set :math:`y_i` and predicted label set +:math:`\hat{y}_i`, is defined as + +.. math:: + + J(y_i, \hat{y}_i) = \frac{|y_i \cap \hat{y}_i|}{|y_i \cup \hat{y}_i|}. + +In binary and multiclass classification, the Jaccard similarity coefficient +score is equal to the classification accuracy. + +:: + + >>> import numpy as np + >>> from sklearn.metrics import jaccard_similarity_score + >>> y_pred = [0, 2, 1, 3] + >>> y_true = [0, 1, 2, 3] + >>> jaccard_similarity_score(y_true, y_pred) + 0.5 + >>> jaccard_similarity_score(y_true, y_pred, normalize=False) + 2 + +In the multilabel case with binary label indicators: :: + + >>> jaccard_similarity_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) + 0.75 + +.. _precision_recall_f_measure_metrics: + +Precision, recall and F-measures +--------------------------------- + +Intuitively, `precision +`_ is the ability +of the classifier not to label as positive a sample that is negative, and +`recall `_ is the +ability of the classifier to find all the positive samples. + +The `F-measure `_ +(:math:`F_\beta` and :math:`F_1` measures) can be interpreted as a weighted +harmonic mean of the precision and recall. A +:math:`F_\beta` measure reaches its best value at 1 and its worst score at 0. +With :math:`\beta = 1`, :math:`F_\beta` and +:math:`F_1` are equivalent, and the recall and the precision are equally important. + +The :func:`precision_recall_curve` computes a precision-recall curve +from the ground truth label and a score given by the classifier +by varying a decision threshold. + +The :func:`average_precision_score` function computes the average precision +(AP) from prediction scores. This score corresponds to the area under the +precision-recall curve. + +Several functions allow you to analyze the precision, recall and F-measures +score: + +.. autosummary:: + :template: function.rst + + average_precision_score + f1_score + fbeta_score + precision_recall_curve + precision_recall_fscore_support + precision_score + recall_score + +Note that the :func:`precision_recall_curve` function is restricted to the +binary case. The :func:`average_precision_score` function works only in +binary classification and multilabel indicator format. + + +.. topic:: Examples: + + * See :ref:`example_text_document_classification_20newsgroups.py` + for an example of :func:`f1_score` usage to classify text + documents. + + * See :ref:`example_model_selection_grid_search_digits.py` + for an example of :func:`precision_score` and :func:`recall_score` usage + to estimate parameters using grid search with nested cross-validation. + + * See :ref:`example_model_selection_plot_precision_recall.py` + for an example of :func:`precision_recall_curve` usage to evaluate + classifier output quality. + + * See :ref:`example_linear_model_plot_sparse_recovery.py` + for an example of :func:`precision_recall_curve` usage to select + features for sparse linear models. + +Binary classification +^^^^^^^^^^^^^^^^^^^^^ + +In a binary classification task, the terms ''positive'' and ''negative'' refer +to the classifier's prediction, and the terms ''true'' and ''false'' refer to +whether that prediction corresponds to the external judgment (sometimes known +as the ''observation''). Given these definitions, we can formulate the +following table: + ++-------------------+------------------------------------------------+ +| | Actual class (observation) | ++-------------------+---------------------+--------------------------+ +| Predicted class | tp (true positive) | fp (false positive) | +| (expectation) | Correct result | Unexpected result | +| +---------------------+--------------------------+ +| | fn (false negative) | tn (true negative) | +| | Missing result | Correct absence of result| ++-------------------+---------------------+--------------------------+ + +In this context, we can define the notions of precision, recall and F-measure: + +.. math:: + + \text{precision} = \frac{tp}{tp + fp}, + +.. math:: + + \text{recall} = \frac{tp}{tp + fn}, + +.. math:: + + F_\beta = (1 + \beta^2) \frac{\text{precision} \times \text{recall}}{\beta^2 \text{precision} + \text{recall}}. + +Here are some small examples in binary classification:: + + >>> from sklearn import metrics + >>> y_pred = [0, 1, 0, 0] + >>> y_true = [0, 1, 0, 1] + >>> metrics.precision_score(y_true, y_pred) + 1.0 + >>> metrics.recall_score(y_true, y_pred) + 0.5 + >>> metrics.f1_score(y_true, y_pred) # doctest: +ELLIPSIS + 0.66... + >>> metrics.fbeta_score(y_true, y_pred, beta=0.5) # doctest: +ELLIPSIS + 0.83... + >>> metrics.fbeta_score(y_true, y_pred, beta=1) # doctest: +ELLIPSIS + 0.66... + >>> metrics.fbeta_score(y_true, y_pred, beta=2) # doctest: +ELLIPSIS + 0.55... + >>> metrics.precision_recall_fscore_support(y_true, y_pred, beta=0.5) # doctest: +ELLIPSIS + (array([ 0.66..., 1. ]), array([ 1. , 0.5]), array([ 0.71..., 0.83...]), array([2, 2]...)) + + + >>> import numpy as np + >>> from sklearn.metrics import precision_recall_curve + >>> from sklearn.metrics import average_precision_score + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> precision, recall, threshold = precision_recall_curve(y_true, y_scores) + >>> precision # doctest: +ELLIPSIS + array([ 0.66..., 0.5 , 1. , 1. ]) + >>> recall + array([ 1. , 0.5, 0.5, 0. ]) + >>> threshold + array([ 0.35, 0.4 , 0.8 ]) + >>> average_precision_score(y_true, y_scores) # doctest: +ELLIPSIS + 0.79... + + + +Multiclass and multilabel classification +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +In multiclass and multilabel classification task, the notions of precision, +recall, and F-measures can be applied to each label independently. +There are a few ways to combine results across labels, +specified by the ``average`` argument to the +:func:`average_precision_score` (multilabel only), :func:`f1_score`, +:func:`fbeta_score`, :func:`precision_recall_fscore_support`, +:func:`precision_score` and :func:`recall_score` functions, as described +:ref:`above `. Note that for "micro"-averaging in a multiclass setting +will produce equal precision, recall and :math:`F`, while "weighted" averaging +may produce an F-score that is not between precision and recall. + +To make this more explicit, consider the following notation: + +* :math:`y` the set of *predicted* :math:`(sample, label)` pairs +* :math:`\hat{y}` the set of *true* :math:`(sample, label)` pairs +* :math:`L` the set of labels +* :math:`S` the set of samples +* :math:`y_s` the subset of :math:`y` with sample :math:`s`, + i.e. :math:`y_s := \left\{(s', l) \in y | s' = s\right\}` +* :math:`y_l` the subset of :math:`y` with label :math:`l` +* similarly, :math:`\hat{y}_s` and :math:`\hat{y}_l` are subsets of + :math:`\hat{y}` +* :math:`P(A, B) := \frac{\left| A \cap B \right|}{\left|A\right|}` +* :math:`R(A, B) := \frac{\left| A \cap B \right|}{\left|B\right|}` + (Conventions vary on handling :math:`B = \emptyset`; this implementation uses + :math:`R(A, B):=0`, and similar for :math:`P`.) +* :math:`F_\beta(A, B) := \left(1 + \beta^2\right) \frac{P(A, B) \times R(A, B)}{\beta^2 P(A, B) + R(A, B)}` + +Then the metrics are defined as: + ++---------------+------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------+ +|``average`` | Precision | Recall | F\_beta | ++===============+==================================================================================================================+==================================================================================================================+======================================================================================================================+ +|``"micro"`` | :math:`P(y, \hat{y})` | :math:`R(y, \hat{y})` | :math:`F_\beta(y, \hat{y})` | ++---------------+------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------+ +|``"samples"`` | :math:`\frac{1}{\left|S\right|} \sum_{s \in S} P(y_s, \hat{y}_s)` | :math:`\frac{1}{\left|S\right|} \sum_{s \in S} R(y_s, \hat{y}_s)` | :math:`\frac{1}{\left|S\right|} \sum_{s \in S} F_\beta(y_s, \hat{y}_s)` | ++---------------+------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------+ +|``"macro"`` | :math:`\frac{1}{\left|L\right|} \sum_{l \in L} P(y_l, \hat{y}_l)` | :math:`\frac{1}{\left|L\right|} \sum_{l \in L} R(y_l, \hat{y}_l)` | :math:`\frac{1}{\left|L\right|} \sum_{l \in L} F_\beta(y_l, \hat{y}_l)` | ++---------------+------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------+ +|``"weighted"`` | :math:`\frac{1}{\sum_{l \in L} \left|\hat{y}_l\right|} \sum_{l \in L} \left|\hat{y}_l\right| P(y_l, \hat{y}_l)` | :math:`\frac{1}{\sum_{l \in L} \left|\hat{y}_l\right|} \sum_{l \in L} \left|\hat{y}_l\right| R(y_l, \hat{y}_l)` | :math:`\frac{1}{\sum_{l \in L} \left|\hat{y}_l\right|} \sum_{l \in L} \left|\hat{y}_l\right| F_\beta(y_l, \hat{y}_l)`| ++---------------+------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------+ +|``None`` | :math:`\langle P(y_l, \hat{y}_l) | l \in L \rangle` | :math:`\langle R(y_l, \hat{y}_l) | l \in L \rangle` | :math:`\langle F_\beta(y_l, \hat{y}_l) | l \in L \rangle` | ++---------------+------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------+ + + >>> from sklearn import metrics + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> metrics.precision_score(y_true, y_pred, average='macro') # doctest: +ELLIPSIS + 0.22... + >>> metrics.recall_score(y_true, y_pred, average='micro') + ... # doctest: +ELLIPSIS + 0.33... + >>> metrics.f1_score(y_true, y_pred, average='weighted') # doctest: +ELLIPSIS + 0.26... + >>> metrics.fbeta_score(y_true, y_pred, average='macro', beta=0.5) # doctest: +ELLIPSIS + 0.23... + >>> metrics.precision_recall_fscore_support(y_true, y_pred, beta=0.5, average=None) + ... # doctest: +ELLIPSIS + (array([ 0.66..., 0. , 0. ]), array([ 1., 0., 0.]), array([ 0.71..., 0. , 0. ]), array([2, 2, 2]...)) + + +Hinge loss +---------- + +The :func:`hinge_loss` function computes the average distance between +the model and the data using +`hinge loss `_, a one-sided metric +that considers only prediction errors. (Hinge +loss is used in maximal margin classifiers such as support vector machines.) + +If the labels are encoded with +1 and -1, :math:`y`: is the true +value, and :math:`w` is the predicted decisions as output by +``decision_function``, then the hinge loss is defined as: + +.. math:: + + L_\text{Hinge}(y, w) = \max\left\{1 - wy, 0\right\} = \left|1 - wy\right|_+ + +If there are more than two labels, :func:`hinge_loss` uses a multiclass variant +due to Crammer & Singer. +`Here `_ is +the paper describing it. + +If :math:`y_w` is the predicted decision for true label and :math:`y_t` is the +maximum of the predicted decisions for all other labels, where predicted +decisions are output by decision function, then multiclass hinge loss is defined +by: + +.. math:: + + L_\text{Hinge}(y_w, y_t) = \max\left\{1 + y_t - y_w, 0\right\} + +Here a small example demonstrating the use of the :func:`hinge_loss` function +with a svm classifier in a binary class problem:: + + >>> from sklearn import svm + >>> from sklearn.metrics import hinge_loss + >>> X = [[0], [1]] + >>> y = [-1, 1] + >>> est = svm.LinearSVC(random_state=0) + >>> est.fit(X, y) + LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True, + intercept_scaling=1, loss='squared_hinge', max_iter=1000, + multi_class='ovr', penalty='l2', random_state=0, tol=0.0001, + verbose=0) + >>> pred_decision = est.decision_function([[-2], [3], [0.5]]) + >>> pred_decision # doctest: +ELLIPSIS + array([-2.18..., 2.36..., 0.09...]) + >>> hinge_loss([-1, 1, 1], pred_decision) # doctest: +ELLIPSIS + 0.3... + +Here is an example demonstrating the use of the :func:`hinge_loss` function +with a svm classifier in a multiclass problem:: + + >>> X = np.array([[0], [1], [2], [3]]) + >>> Y = np.array([0, 1, 2, 3]) + >>> labels = np.array([0, 1, 2, 3]) + >>> est = svm.LinearSVC() + >>> est.fit(X, Y) + LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True, + intercept_scaling=1, loss='squared_hinge', max_iter=1000, + multi_class='ovr', penalty='l2', random_state=None, tol=0.0001, + verbose=0) + >>> pred_decision = est.decision_function([[-1], [2], [3]]) + >>> y_true = [0, 2, 3] + >>> hinge_loss(y_true, pred_decision, labels) #doctest: +ELLIPSIS + 0.56... + + +Log loss +-------- + +Log loss, also called logistic regression loss or +cross-entropy loss, is defined on probability estimates. It is +commonly used in (multinomial) logistic regression and neural networks, as well +as in some variants of expectation-maximization, and can be used to evaluate the +probability outputs (``predict_proba``) of a classifier instead of its +discrete predictions. + +For binary classification with a true label :math:`y \in \{0,1\}` +and a probability estimate :math:`p = \operatorname{Pr}(y = 1)`, +the log loss per sample is the negative log-likelihood +of the classifier given the true label: + +.. math:: + + L_{\log}(y, p) = -\log \operatorname{Pr}(y|p) = -(y \log p) + (1 - y) \log (1 - p)) + +This extends to the multiclass case as follows. +Let the true labels for a set of samples +be encoded as a 1-of-K binary indicator matrix :math:`Y`, +i.e., :math:`y_{i,k} = 1` if sample :math:`i` has label :math:`k` +taken from a set of :math:`K` labels. +Let :math:`P` be a matrix of probability estimates, +with :math:`p_{i,k} = \operatorname{Pr}(t_{i,k} = 1)`. +Then the log loss of the whole set is + +.. math:: + + L_{\log}(Y, P) = -\log \operatorname{Pr}(Y|P) = - \frac{1}{N} \sum_{i=0}^{N-1} \sum_{k=0}^{K-1} y_{i,k} \log p_{i,k} + +To see how this generalizes the binary log loss given above, +note that in the binary case, +:math:`p_{i,0} = 1 - p_{i,1}` and :math:`y_{i,0} = 1 - y_{i,1}`, +so expanding the inner sum over :math:`y_{i,k} \in \{0,1\}` +gives the binary log loss. + +The :func:`log_loss` function computes log loss given a list of ground-truth +labels and a probability matrix, as returned by an estimator's ``predict_proba`` +method. + + >>> from sklearn.metrics import log_loss + >>> y_true = [0, 0, 1, 1] + >>> y_pred = [[.9, .1], [.8, .2], [.3, .7], [.01, .99]] + >>> log_loss(y_true, y_pred) # doctest: +ELLIPSIS + 0.1738... + +The first ``[.9, .1]`` in ``y_pred`` denotes 90% probability that the first +sample has label 0. The log loss is non-negative. + + +Matthews correlation coefficient +--------------------------------- + +The :func:`matthews_corrcoef` function computes the +`Matthew's correlation coefficient (MCC) `_ +for binary classes. Quoting Wikipedia: + + + "The Matthews correlation coefficient is used in machine learning as a + measure of the quality of binary (two-class) classifications. It takes + into account true and false positives and negatives and is generally + regarded as a balanced measure which can be used even if the classes are + of very different sizes. The MCC is in essence a correlation coefficient + value between -1 and +1. A coefficient of +1 represents a perfect + prediction, 0 an average random prediction and -1 an inverse prediction. + The statistic is also known as the phi coefficient." + +If :math:`tp`, :math:`tn`, :math:`fp` and :math:`fn` are respectively the +number of true positives, true negatives, false positives and false negatives, +the MCC coefficient is defined as + +.. math:: + + MCC = \frac{tp \times tn - fp \times fn}{\sqrt{(tp + fp)(tp + fn)(tn + fp)(tn + fn)}}. + +Here is a small example illustrating the usage of the :func:`matthews_corrcoef` +function: + + >>> from sklearn.metrics import matthews_corrcoef + >>> y_true = [+1, +1, +1, -1] + >>> y_pred = [+1, -1, +1, +1] + >>> matthews_corrcoef(y_true, y_pred) # doctest: +ELLIPSIS + -0.33... + +.. _roc_metrics: + +Receiver operating characteristic (ROC) +--------------------------------------- + +The function :func:`roc_curve` computes the +`receiver operating characteristic curve, or ROC curve `_. + Quoting Wikipedia : + + "A receiver operating characteristic (ROC), or simply ROC curve, is a + graphical plot which illustrates the performance of a binary classifier + system as its discrimination threshold is varied. It is created by plotting + the fraction of true positives out of the positives (TPR = true positive + rate) vs. the fraction of false positives out of the negatives (FPR = false + positive rate), at various threshold settings. TPR is also known as + sensitivity, and FPR is one minus the specificity or true negative rate." + +This function requires the true binary +value and the target scores, which can either be probability estimates of the +positive class, confidence values, or binary decisions. +Here is a small example of how to use the :func:`roc_curve` function:: + + >>> import numpy as np + >>> from sklearn.metrics import roc_curve + >>> y = np.array([1, 1, 2, 2]) + >>> scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, tpr, thresholds = roc_curve(y, scores, pos_label=2) + >>> fpr + array([ 0. , 0.5, 0.5, 1. ]) + >>> tpr + array([ 0.5, 0.5, 1. , 1. ]) + >>> thresholds + array([ 0.8 , 0.4 , 0.35, 0.1 ]) + +This figure shows an example of such an ROC curve: + +.. image:: ../auto_examples/model_selection/images/plot_roc_001.png + :target: ../auto_examples/model_selection/plot_roc.html + :scale: 75 + :align: center + +The :func:`roc_auc_score` function computes the area under the receiver +operating characteristic (ROC) curve, which is also denoted by +AUC or AUROC. By computing the +area under the roc curve, the curve information is summarized in one number. +For more information see the `Wikipedia article on AUC +`_. + + >>> import numpy as np + >>> from sklearn.metrics import roc_auc_score + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> roc_auc_score(y_true, y_scores) + 0.75 + +In multi-label classification, the :func:`roc_auc_score` function is +extended by averaging over the labels as :ref:`above `. + +Compared to metrics such as the subset accuracy, the Hamming loss, or the +F1 score, ROC doesn't require optimizing a threshold for each label. The +:func:`roc_auc_score` function can also be used in multi-class classification, +if the predicted outputs have been binarized. + + +.. image:: ../auto_examples/model_selection/images/plot_roc_002.png + :target: ../auto_examples/model_selection/plot_roc.html + :scale: 75 + :align: center + +.. topic:: Examples: + + * See :ref:`example_model_selection_plot_roc.py` + for an example of using ROC to + evaluate the quality of the output of a classifier. + + * See :ref:`example_model_selection_plot_roc_crossval.py` + for an example of using ROC to + evaluate classifier output quality, using cross-validation. + + * See :ref:`example_applications_plot_species_distribution_modeling.py` + for an example of using ROC to + model species distribution. + +.. _zero_one_loss: + +Zero one loss +-------------- + +The :func:`zero_one_loss` function computes the sum or the average of the 0-1 +classification loss (:math:`L_{0-1}`) over :math:`n_{\text{samples}}`. By +default, the function normalizes over the sample. To get the sum of the +:math:`L_{0-1}`, set ``normalize`` to ``False``. + +In multilabel classification, the :func:`zero_one_loss` scores a subset as +one if its labels strictly match the predictions, and as a zero if there +are any errors. By default, the function returns the percentage of imperfectly +predicted subsets. To get the count of such subsets instead, set +``normalize`` to ``False`` + +If :math:`\hat{y}_i` is the predicted value of +the :math:`i`-th sample and :math:`y_i` is the corresponding true value, +then the 0-1 loss :math:`L_{0-1}` is defined as: + +.. math:: + + L_{0-1}(y_i, \hat{y}_i) = 1(\hat{y}_i \not= y_i) + +where :math:`1(x)` is the `indicator function +`_. + + + >>> from sklearn.metrics import zero_one_loss + >>> y_pred = [1, 2, 3, 4] + >>> y_true = [2, 2, 3, 4] + >>> zero_one_loss(y_true, y_pred) + 0.25 + >>> zero_one_loss(y_true, y_pred, normalize=False) + 1 + +In the multilabel case with binary label indicators, where the first label +set [0,1] has an error: :: + + >>> zero_one_loss(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) + 0.5 + + >>> zero_one_loss(np.array([[0, 1], [1, 1]]), np.ones((2, 2)), normalize=False) + 1 + +.. topic:: Example: + + * See :ref:`example_feature_selection_plot_rfe_with_cross_validation.py` + for an example of zero one loss usage to perform recursive feature + elimination with cross-validation. + + +.. _multilabel_ranking_metrics: + +Multilabel ranking metrics +========================== + +.. currentmodule:: sklearn.metrics + +In multilabel learning, each sample can have any number of ground truth labels +associated with it. The goal is to give high scores and better rank to +the ground truth labels. + +Coverage error +-------------- + +The :func:`coverage_error` function computes the average number of labels that +have to be included in the final prediction such that all true labels +are predicted. This is useful if you want to know how many top-scored-labels +you have to predict in average without missing any true one. The best value +of this metrics is thus the average number of true labels. + +Formally, given a binary indicator matrix of the ground truth labels +:math:`y \in \left\{0, 1\right\}^{n_\text{samples} \times n_\text{labels}}` and the +score associated with each label +:math:`\hat{f} \in \mathbb{R}^{n_\text{samples} \times n_\text{labels}}`, +the coverage is defined as + +.. math:: + coverage(y, \hat{f}) = \frac{1}{n_{\text{samples}}} + \sum_{i=0}^{n_{\text{samples}} - 1} \max_{j:y_{ij} = 1} \text{rank}_{ij} + +with :math:`\text{rank}_{ij} = \left|\left\{k: \hat{f}_{ik} \geq \hat{f}_{ij} \right\}\right|`. +Given the rank definition, ties in ``y_scores`` are broken by giving the +maximal rank that would have been assigned to all tied values. + +Here is a small example of usage of this function:: + + >>> import numpy as np + >>> from sklearn.metrics import coverage_error + >>> y_true = np.array([[1, 0, 0], [0, 0, 1]]) + >>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]]) + >>> coverage_error(y_true, y_score) + 2.5 + +Label ranking average precision +------------------------------- + +The :func:`label_ranking_average_precision_score` function +implements label ranking average precision (LRAP). This metric is linked to +the :func:`average_precision_score` function, but is based on the notion of +label ranking instead of precision and recall. + +Label ranking average precision (LRAP) is the average over each ground truth +label assigned to each sample, of the ratio of true vs. total labels with lower +score. This metric will yield better scores if you are able to give better rank +to the labels associated with each sample. The obtained score is always strictly +greater than 0, and the best value is 1. If there is exactly one relevant +label per sample, label ranking average precision is equivalent to the `mean +reciprocal rank `_. + +Formally, given a binary indicator matrix of the ground truth labels +:math:`y \in \mathcal{R}^{n_\text{samples} \times n_\text{labels}}` and the +score associated with each label +:math:`\hat{f} \in \mathcal{R}^{n_\text{samples} \times n_\text{labels}}`, +the average precision is defined as + +.. math:: + LRAP(y, \hat{f}) = \frac{1}{n_{\text{samples}}} + \sum_{i=0}^{n_{\text{samples}} - 1} \frac{1}{|y_i|} + \sum_{j:y_{ij} = 1} \frac{|\mathcal{L}_{ij}|}{\text{rank}_{ij}} + + +with :math:`\mathcal{L}_{ij} = \left\{k: y_{ik} = 1, \hat{f}_{ik} \geq \hat{f}_{ij} \right\}`, +:math:`\text{rank}_{ij} = \left|\left\{k: \hat{f}_{ik} \geq \hat{f}_{ij} \right\}\right|` +and :math:`|\cdot|` is the l0 norm or the cardinality of the set. + +Here is a small example of usage of this function:: + + >>> import numpy as np + >>> from sklearn.metrics import label_ranking_average_precision_score + >>> y_true = np.array([[1, 0, 0], [0, 0, 1]]) + >>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]]) + >>> label_ranking_average_precision_score(y_true, y_score) # doctest: +ELLIPSIS + 0.416... + + +.. _regression_metrics: + +Regression metrics +=================== + +.. currentmodule:: sklearn.metrics + +The :mod:`sklearn.metrics` module implements several loss, score, and utility +functions to measure regression performance. Some of those have been enhanced +to handle the multioutput case: :func:`mean_absolute_error`, +:func:`mean_squared_error`, :func:`median_absolute_error` and :func:`r2_score`. + +Explained variance score +------------------------- + +The :func:`explained_variance_score` computes the `explained variance +regression score `_. + +If :math:`\hat{y}` is the estimated target output, :math:`y` the corresponding +(correct) target output, and :math:`Var` is `Variance +`_, the square of the standard deviation, +then the explained variance is estimated as follow: + +.. math:: + + \texttt{explained\_{}variance}(y, \hat{y}) = 1 - \frac{Var\{ y - \hat{y}\}}{Var\{y\}} + +The best possible score is 1.0, lower values are worse. + +Here is a small example of usage of the :func:`explained_variance_score` +function:: + + >>> from sklearn.metrics import explained_variance_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> explained_variance_score(y_true, y_pred) # doctest: +ELLIPSIS + 0.957... + +Mean absolute error +------------------- + +The :func:`mean_absolute_error` function computes `mean absolute +error `_, a risk +metric corresponding to the expected value of the absolute error loss or +:math:`l1`-norm loss. + +If :math:`\hat{y}_i` is the predicted value of the :math:`i`-th sample, +and :math:`y_i` is the corresponding true value, then the mean absolute error +(MAE) estimated over :math:`n_{\text{samples}}` is defined as + +.. math:: + + \text{MAE}(y, \hat{y}) = \frac{1}{n_{\text{samples}}} \sum_{i=0}^{n_{\text{samples}}-1} \left| y_i - \hat{y}_i \right|. + +Here is a small example of usage of the :func:`mean_absolute_error` function:: + + >>> from sklearn.metrics import mean_absolute_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_absolute_error(y_true, y_pred) + 0.5 + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> mean_absolute_error(y_true, y_pred) + 0.75 + + + +Mean squared error +------------------- + +The :func:`mean_squared_error` function computes `mean square +error `_, a risk +metric corresponding to the expected value of the squared (quadratic) error loss or +loss. + +If :math:`\hat{y}_i` is the predicted value of the :math:`i`-th sample, +and :math:`y_i` is the corresponding true value, then the mean squared error +(MSE) estimated over :math:`n_{\text{samples}}` is defined as + +.. math:: + + \text{MSE}(y, \hat{y}) = \frac{1}{n_\text{samples}} \sum_{i=0}^{n_\text{samples} - 1} (y_i - \hat{y}_i)^2. + +Here is a small example of usage of the :func:`mean_squared_error` +function:: + + >>> from sklearn.metrics import mean_squared_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_squared_error(y_true, y_pred) + 0.375 + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> mean_squared_error(y_true, y_pred) # doctest: +ELLIPSIS + 0.7083... + +.. topic:: Examples: + + * See :ref:`example_ensemble_plot_gradient_boosting_regression.py` + for an example of mean squared error usage to + evaluate gradient boosting regression. + +Median absolute error +--------------------- + +The :func:`median_absolute_error` is particularly interesting because it is +robust to outliers. The loss is calculated by taking the median of all absolute +differences between the target and the prediction. + +If :math:`\hat{y}_i` is the predicted value of the :math:`i`-th sample +and :math:`y_i` is the corresponding true value, then the median absolute error +(MedAE) estimated over :math:`n_{\text{samples}}` is defined as + +.. math:: + + \text{MedAE}(y, \hat{y}) = \text{median}(\mid y_1 - \hat{y}_1 \mid, \ldots, \mid y_n - \hat{y}_n \mid). + +The :func:`median_absolute_error` does not support multioutput. + +Here is a small example of usage of the :func:`median_absolute_error` +function:: + + >>> from sklearn.metrics import median_absolute_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> median_absolute_error(y_true, y_pred) + 0.5 + +R² score, the coefficient of determination +------------------------------------------- + +The :func:`r2_score` function computes R², the `coefficient of +determination `_. +It provides a measure of how well future samples are likely to +be predicted by the model. + +If :math:`\hat{y}_i` is the predicted value of the :math:`i`-th sample +and :math:`y_i` is the corresponding true value, then the score R² estimated +over :math:`n_{\text{samples}}` is defined as + +.. math:: + + R^2(y, \hat{y}) = 1 - \frac{\sum_{i=0}^{n_{\text{samples}} - 1} (y_i - \hat{y}_i)^2}{\sum_{i=0}^{n_\text{samples} - 1} (y_i - \bar{y})^2} + +where :math:`\bar{y} = \frac{1}{n_{\text{samples}}} \sum_{i=0}^{n_{\text{samples}} - 1} y_i`. + +Here is a small example of usage of the :func:`r2_score` function:: + + >>> from sklearn.metrics import r2_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> r2_score(y_true, y_pred) # doctest: +ELLIPSIS + 0.948... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> r2_score(y_true, y_pred) # doctest: +ELLIPSIS + 0.938... + + +.. topic:: Example: + + * See :ref:`example_linear_model_plot_lasso_and_elasticnet.py` + for an example of R² score usage to + evaluate Lasso and Elastic Net on sparse signals. + +.. _clustering_metrics: + +Clustering metrics +====================== + +.. currentmodule:: sklearn.metrics + +The :mod:`sklearn.metrics` module implements several loss, score, and utility +functions. For more information see the :ref:`clustering_evaluation` +section for instance clustering, and :ref:`biclustering_evaluation` for +biclustering. + + +.. _dummy_estimators: + + +Dummy estimators +================= + +.. currentmodule:: sklearn.dummy + +When doing supervised learning, a simple sanity check consists of comparing +one's estimator against simple rules of thumb. :class:`DummyClassifier` +implements three such simple strategies for classification: + +- ``stratified`` generates random predictions by respecting the training + set class distribution. +- ``most_frequent`` always predicts the most frequent label in the training set. +- ``uniform`` generates predictions uniformly at random. +- ``constant`` always predicts a constant label that is provided by the user. + A major motivation of this method is F1-scoring, when the positive class + is in the minority. + +Note that with all these strategies, the ``predict`` method completely ignores +the input data! + +To illustrate :class:`DummyClassifier`, first let's create an imbalanced +dataset:: + + >>> from sklearn.datasets import load_iris + >>> from sklearn.cross_validation import train_test_split + >>> iris = load_iris() + >>> X, y = iris.data, iris.target + >>> y[y != 1] = -1 + >>> X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + +Next, let's compare the accuracy of ``SVC`` and ``most_frequent``:: + + >>> from sklearn.dummy import DummyClassifier + >>> from sklearn.svm import SVC + >>> clf = SVC(kernel='linear', C=1).fit(X_train, y_train) + >>> clf.score(X_test, y_test) # doctest: +ELLIPSIS + 0.63... + >>> clf = DummyClassifier(strategy='most_frequent',random_state=0) + >>> clf.fit(X_train, y_train) + DummyClassifier(constant=None, random_state=0, strategy='most_frequent') + >>> clf.score(X_test, y_test) # doctest: +ELLIPSIS + 0.57... + +We see that ``SVC`` doesn't do much better than a dummy classifier. Now, let's +change the kernel:: + + >>> clf = SVC(kernel='rbf', C=1).fit(X_train, y_train) + >>> clf.score(X_test, y_test) # doctest: +ELLIPSIS + 0.97... + +We see that the accuracy was boosted to almost 100%. A cross validation +strategy is recommended for a better estimate of the accuracy, if it +is not too CPU costly. For more information see the :ref:`cross_validation` +section. Moreover if you want to optimize over the parameter space, it is highly +recommended to use an appropriate methodology; see the :ref:`grid_search` +section for details. + +More generally, when the accuracy of a classifier is too close to random, it +probably means that something went wrong: features are not helpful, a +hyperparameter is not correctly tuned, the classifier is suffering from class +imbalance, etc... + +:class:`DummyRegressor` also implements four simple rules of thumb for regression: + +- ``mean`` always predicts the mean of the training targets. +- ``median`` always predicts the median of the training targets. +- ``quantile`` always predicts a user provided quantile of the training targets. +- ``constant`` always predicts a constant value that is provided by the user. + +In all these strategies, the ``predict`` method completely ignores +the input data. diff --git a/doc/modules/model_persistence.rst b/doc/modules/model_persistence.rst new file mode 100644 index 0000000000000..e1c9e92f70b57 --- /dev/null +++ b/doc/modules/model_persistence.rst @@ -0,0 +1,82 @@ +.. _model_persistence: + +================= +Model persistence +================= + +After training a scikit-learn model, it is desirable to have a way to persist +the model for future use without having to retrain. The following section gives +you an example of how to persist a model with pickle. We'll also review a few +security and maintainability issues when working with pickle serialization. + + +Persistence example +------------------- + +It is possible to save a model in the scikit by using Python's built-in +persistence model, namely `pickle `_:: + + >>> from sklearn import svm + >>> from sklearn import datasets + >>> clf = svm.SVC() + >>> iris = datasets.load_iris() + >>> X, y = iris.data, iris.target + >>> clf.fit(X, y) # doctest: +NORMALIZE_WHITESPACE + SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, + kernel='rbf', max_iter=-1, probability=False, random_state=None, + shrinking=True, tol=0.001, verbose=False) + + >>> import pickle + >>> s = pickle.dumps(clf) + >>> clf2 = pickle.loads(s) + >>> clf2.predict(X[0]) + array([0]) + >>> y[0] + 0 + +In the specific case of the scikit, it may be more interesting to use +joblib's replacement of pickle (``joblib.dump`` & ``joblib.load``), +which is more efficient on objects that carry large numpy arrays internally as +is often the case for fitted scikit-learn estimators, but can only pickle to the +disk and not to a string:: + + >>> from sklearn.externals import joblib + >>> joblib.dump(clf, 'filename.pkl') # doctest: +SKIP + +Later you can load back the pickled model (possibly in another Python process) +with:: + + >>> clf = joblib.load('filename.pkl') # doctest:+SKIP + +.. note:: + + joblib.dump returns a list of filenames. Each individual numpy array + contained in the ``clf`` object is serialized as a separate file on the + filesystem. All files are required in the same folder when reloading the + model with joblib.load. + + +Security & maintainability limitations +-------------------------------------- + +pickle (and joblib by extension), has some issues regarding maintainability +and security. Because of this, + +* Never unpickle untrusted data +* Models saved in one version of scikit-learn might not load in another + version. + +In order to rebuild a similar model with future versions of scikit-learn, +additional metadata should be saved along the pickled model: + +* The training data, e.g. a reference to a immutable snapshot +* The python source code used to generate the model +* The versions of scikit-learn and its dependencies +* The cross validation score obtained on the training data + +This should make it possible to check that the cross-validation score is in the +same range as before. + +If you want to know more about these issues and explore other possible +serialization methods, please refer to this +`talk by Alex Gaynor `_. diff --git a/doc/modules/multiclass.rst b/doc/modules/multiclass.rst index 735759acf0d62..98b5fc0061ef3 100644 --- a/doc/modules/multiclass.rst +++ b/doc/modules/multiclass.rst @@ -7,44 +7,103 @@ Multiclass and multilabel algorithms .. currentmodule:: sklearn.multiclass -This module implements multiclass and multilabel learning algorithms: - - one-vs-the-rest / one-vs-all - - one-vs-one - - error correcting output codes - -Multiclass classification means classification with more than two classes. -Multilabel classification is a different task, where a classifier is used to -predict a set of target labels for each instance; i.e., the set of target -classes is not assumed to be disjoint as in ordinary (binary or multiclass) -classification. This is also called any-of classification. - -The estimators provided in this module are meta-estimators: they require a base -estimator to be provided in their constructor. For example, it is possible to -use these estimators to turn a binary classifier or a regressor into a -multiclass classifier. It is also possible to use these estimators with -multiclass estimators in the hope that their accuracy or runtime performance -improves. - -.. note:: - - You don't need to use these estimators unless you want to experiment with - different multiclass strategies: all classifiers in scikit-learn support - multiclass classification out-of-the-box. Below is a summary of the - classifiers supported in scikit-learn grouped by the strategy used. - - - Inherently multiclass: :ref:`Naive Bayes `, :class:`sklearn.lda.LDA`, - :ref:`Decision Trees `, :ref:`Random Forests ` - - One-Vs-One: :class:`sklearn.svm.SVC`. - - One-Vs-All: :class:`sklearn.svm.LinearSVC`, - :class:`sklearn.linear_model.LogisticRegression`, - :class:`sklearn.linear_model.SGDClassifier`, - :class:`sklearn.linear_model.RidgeClassifier`. - -.. note:: - - At the moment there are no evaluation metrics implemented for multilabel - learnings. - +.. warning:: + All classifiers in scikit-learn do multiclass classification + out-of-the-box. You don't need to use the :mod:`sklearn.multiclass` module + unless you want to experiment with different multiclass strategies. + +The :mod:`sklearn.multiclass` module implements *meta-estimators* to solve +``multiclass`` and ``multilabel`` classification problems +by decomposing such problems into binary classification problems. + + - **Multiclass classification** means a classification task with more than + two classes; e.g., classify a set of images of fruits which may be oranges, + apples, or pears. Multiclass classification makes the assumption that each + sample is assigned to one and only one label: a fruit can be either an + apple or a pear but not both at the same time. + + - **Multilabel classification** assigns to each sample a set of target + labels. This can be thought as predicting properties of a data-point + that are not mutually exclusive, such as topics that are relevant for a + document. A text might be about any of religion, politics, finance or + education at the same time or none of these. + + - **Multioutput-multiclass classification** and **multi-task classification** + means that a single estimator has to handle + several joint classification tasks. This is a generalization + of the multi-label classification task, where the set of classification + problem is restricted to binary classification, and of the multi-class + classification task. *The output format is a 2d numpy array or sparse + matrix.* + + The set of labels can be different for each output variable. + For instance a sample could be assigned "pear" for an output variable that + takes possible values in a finite set of species such as "pear", "apple", + "orange" and "green" for a second output variable that takes possible values + in a finite set of colors such as "green", "red", "orange", "yellow"... + + This means that any classifiers handling multi-output + multiclass or multi-task classification task + supports the multi-label classification task as a special case. + Multi-task classification is similar to the multi-output + classification task with different model formulations. For + more information, see the relevant estimator documentation. + +All scikit-learn classifiers are capable of multiclass classification, +but the meta-estimators offered by :mod:`sklearn.multiclass` +permit changing the way they handle more than two classes +because this may have an effect on classifier performance +(either in terms of generalization error or required computational resources). + +Below is a summary of the classifiers supported by scikit-learn +grouped by strategy; you don't need the meta-estimators in this class +if you're using one of these unless you want custom multiclass behavior: + + - Inherently multiclass: :ref:`Naive Bayes `, + :class:`sklearn.lda.LDA`, + :ref:`Decision Trees `, :ref:`Random Forests `, + :ref:`Nearest Neighbors `, + setting "multi_class=multinomial" in + :class:`sklearn.linear_model.LogisticRegression`. + - One-Vs-One: :class:`sklearn.svm.SVC`. + - One-Vs-All: all linear models except :class:`sklearn.svm.SVC`. + +Some estimators also support multioutput-multiclass classification +tasks :ref:`Decision Trees `, :ref:`Random Forests `, +:ref:`Nearest Neighbors `. + +.. warning:: + + At present, no metric in :mod:`sklearn.metrics` + supports the multioutput-multiclass classification task. + +Multilabel classification format +================================ + +In multilabel learning, the joint set of binary classification tasks is +expressed with label binary indicator array: each sample is one row of a 2d +array of shape (n_samples, n_classes) with binary values: the one, i.e. the non +zero elements, corresponds to the subset of labels. An array such as +``np.array([[1, 0, 0], [0, 1, 1], [0, 0, 0]])`` represents label 0 in the first +sample, labels 1 and 2 in the second sample, and no labels in the third sample. + +Producing multilabel data as a list of sets of labels may be more intuitive. +The transformer :class:`MultiLabelBinarizer ` +will convert between a collection of collections of labels and the indicator +format. + + >>> from sklearn.datasets import make_multilabel_classification + >>> from sklearn.preprocessing import MultiLabelBinarizer + >>> X, Y = make_multilabel_classification(n_samples=5, random_state=0, + ... return_indicator=False) + >>> Y + [[2, 3, 4], [2], [0, 1, 3], [0, 1, 2, 3, 4], [0, 1, 2]] + >>> MultiLabelBinarizer().fit_transform(Y) + array([[0, 0, 1, 1, 1], + [0, 0, 1, 0, 0], + [1, 1, 0, 1, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 0, 0]]) One-Vs-The-Rest =============== @@ -57,14 +116,19 @@ classifiers are needed), one advantage of this approach is its interpretability. Since each class is represented by one and one classifier only, it is possible to gain knowledge about the class by inspecting its corresponding classifier. This is the most commonly used strategy and is a fair -default choice. Below is an example:: +default choice. + +Multiclass learning +------------------- + +Below is an example of multiclass learning using OvR:: >>> from sklearn import datasets >>> from sklearn.multiclass import OneVsRestClassifier >>> from sklearn.svm import LinearSVC >>> iris = datasets.load_iris() >>> X, y = iris.data, iris.target - >>> OneVsRestClassifier(LinearSVC()).fit(X, y).predict(X) + >>> OneVsRestClassifier(LinearSVC(random_state=0)).fit(X, y).predict(X) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -73,15 +137,15 @@ default choice. Below is an example:: 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]) -Multilabel learning with OvR ----------------------------- +Multilabel learning +------------------- :class:`OneVsRestClassifier` also supports multilabel classification. -To use this feature, feed the classifier a list of tuples containing -target labels, like in the example below. +To use this feature, feed the classifier an indicator matrix, in which cell +[i, j] indicates the presence of label j in sample i. -.. figure:: ../auto_examples/images/plot_multilabel_1.png +.. figure:: ../auto_examples/images/plot_multilabel_001.png :target: ../auto_examples/plot_multilabel.html :align: center :scale: 75% @@ -97,20 +161,30 @@ One-Vs-One :class:`OneVsOneClassifier` constructs one classifier per pair of classes. At prediction time, the class which received the most votes is selected. -Since it requires to fit `n_classes * (n_classes - 1) / 2` classifiers, +In the event of a tie (among two classes with an equal number of votes), it +selects the class with the highest aggregate classification confidence by +summing over the pair-wise classification confidence levels computed by the +underlying binary classifiers. + +Since it requires to fit ``n_classes * (n_classes - 1) / 2`` classifiers, this method is usually slower than one-vs-the-rest, due to its O(n_classes^2) complexity. However, this method may be advantageous for algorithms such as kernel algorithms which don't scale well with -`n_samples`. This is because each individual learning problem only involves +``n_samples``. This is because each individual learning problem only involves a small subset of the data whereas, with one-vs-the-rest, the complete -dataset is used `n_classes` times. Below is an example:: +dataset is used ``n_classes`` times. + +Multiclass learning +------------------- + +Below is an example of multiclass learning using OvO:: >>> from sklearn import datasets >>> from sklearn.multiclass import OneVsOneClassifier >>> from sklearn.svm import LinearSVC >>> iris = datasets.load_iris() >>> X, y = iris.data, iris.target - >>> OneVsOneClassifier(LinearSVC()).fit(X, y).predict(X) + >>> OneVsOneClassifier(LinearSVC(random_state=0)).fit(X, y).predict(X) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -120,6 +194,12 @@ dataset is used `n_classes` times. Below is an example:: 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]) +.. topic:: References: + + .. [1] "Pattern Recognition and Machine Learning. Springer", + Christopher M. Bishop, page 183, (First Edition) + + Error-Correcting Output-Codes ============================= @@ -139,8 +219,8 @@ At fitting time, one binary classifier per bit in the code book is fitted. At prediction time, the classifiers are used to project new points in the class space and the class closest to the points is chosen. -In :class:`OutputCodeClassifier`, the `code_size` attribute allows the user to control -the number of classifiers which will be used. It is a percentage of the +In :class:`OutputCodeClassifier`, the ``code_size`` attribute allows the user to +control the number of classifiers which will be used. It is a percentage of the total number of classes. A number between 0 and 1 will require fewer classifiers than @@ -155,14 +235,20 @@ In practice, however, this may not happen as classifier mistakes will typically be correlated. The error-correcting output codes have a similar effect to bagging. -Example:: + +Multiclass learning +------------------- + +Below is an example of multiclass learning using Output-Codes:: >>> from sklearn import datasets >>> from sklearn.multiclass import OutputCodeClassifier >>> from sklearn.svm import LinearSVC >>> iris = datasets.load_iris() >>> X, y = iris.data, iris.target - >>> OutputCodeClassifier(LinearSVC(), code_size=2, random_state=0).fit(X, y).predict(X) + >>> clf = OutputCodeClassifier(LinearSVC(random_state=0), + ... code_size=2, random_state=0) + >>> clf.fit(X, y).predict(X) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, @@ -171,15 +257,14 @@ Example:: 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]) - .. topic:: References: - .. [1] "Solving multiclass learning problems via error-correcting ouput codes", - Dietterich T., Bakiri G., - Journal of Artificial Intelligence Research 2, + .. [1] "Solving multiclass learning problems via error-correcting output codes", + Dietterich T., Bakiri G., + Journal of Artificial Intelligence Research 2, 1995. - .. [2] "The error coding method and PICTs", + .. [2] "The error coding method and PICTs", James G., Hastie T., Journal of Computational and Graphical statistics 7, 1998. diff --git a/doc/modules/naive_bayes.rst b/doc/modules/naive_bayes.rst index b591b733449ca..0e60479eddbff 100644 --- a/doc/modules/naive_bayes.rst +++ b/doc/modules/naive_bayes.rst @@ -47,14 +47,14 @@ and we can use Maximum A Posteriori (MAP) estimation to estimate the former is then the relative frequency of class :math:`y` in the training set. -The different Naive Bayes classifiers differ mainly by the assumptions they make -regarding the distribution of :math:`P(x_i \mid y)`. +The different naive Bayes classifiers differ mainly by the assumptions they +make regarding the distribution of :math:`P(x_i \mid y)`. -In spite of their apparently over-simplified assumptions, Naive Bayes +In spite of their apparently over-simplified assumptions, naive Bayes classifiers have worked quite well in many real-world situations, famously -document classification and spam filtering. They requires a small amount +document classification and spam filtering. They require a small amount of training data to estimate the necessary parameters. (For theoretical -reasons why Naive Bayes works well, and on which types of data it does, see +reasons why naive Bayes works well, and on which types of data it does, see the references below.) Naive Bayes learners and classifiers can be extremely fast compared to more @@ -64,7 +64,7 @@ distribution can be independently estimated as a one dimensional distribution. This in turn helps to alleviate problems stemming from the curse of dimensionality. -On the flip side, although Naive Bayes is known as a decent classifier, +On the flip side, although naive Bayes is known as a decent classifier, it is known to be a bad estimator, so the probability outputs from ``predict_proba`` are not to be taken too seriously. @@ -83,7 +83,7 @@ classification. The likelihood of the features is assumed to be Gaussian: .. math:: - P(x_i \mid y) &= \frac{1}{\sqrt{2\pi\sigma^2_y}} \exp\left(-\frac{ (x_i - \mu_y)^2}{2\pi\sigma^2_y}\right) + P(x_i \mid y) &= \frac{1}{\sqrt{2\pi\sigma^2_y}} \exp\left(-\frac{(x_i - \mu_y)^2}{2\sigma^2_y}\right) The parameters :math:`\sigma_y` and :math:`\mu_y` are estimated using maximum likelihood. @@ -93,16 +93,17 @@ are estimated using maximum likelihood. >>> from sklearn.naive_bayes import GaussianNB >>> gnb = GaussianNB() >>> y_pred = gnb.fit(iris.data, iris.target).predict(iris.data) - >>> print "Number of mislabeled points : %d" % (iris.target != y_pred).sum() - Number of mislabeled points : 6 + >>> print("Number of mislabeled points out of a total %d points : %d" + ... % (iris.data.shape[0],(iris.target != y_pred).sum())) + Number of mislabeled points out of a total 150 points : 6 .. _multinomial_naive_bayes: Multinomial Naive Bayes ----------------------- -:class:`MultinomialNB` implements the Naive Bayes algorithm for multinomially -distributed data, and is one of the two classic Naive Bayes variants used in +:class:`MultinomialNB` implements the naive Bayes algorithm for multinomially +distributed data, and is one of the two classic naive Bayes variants used in text classification (where the data are typically represented as word vector counts, although tf-idf vectors are also known to work well in practice). The distribution is parametrized by vectors @@ -137,7 +138,7 @@ while :math:`\alpha < 1` is called Lidstone smoothing. Bernoulli Naive Bayes --------------------- -:class:`BernoulliNB` implements the Naive Bayes training and classification +:class:`BernoulliNB` implements the naive Bayes training and classification algorithms for data that is distributed according to multivariate Bernoulli distributions; i.e., there may be multiple features but each one is assumed to be a binary-valued (Bernoulli, boolean) variable. @@ -145,11 +146,11 @@ Therefore, this class requires samples to be represented as binary-valued feature vectors; if handed any other kind of data, a ``BernoulliNB`` instance may binarize its input (depending on the ``binarize`` parameter). -The decision rule for Bernoulli Naive Bayes is based on +The decision rule for Bernoulli naive Bayes is based on .. math:: - P(x_i \mid y) = P(i \mid y) x_i \times (1 - P(i \mid y)) (1 - x_i) + P(x_i \mid y) = P(i \mid y) x_i + (1 - P(i \mid y)) (1 - x_i) which differs from multinomial NB's rule in that it explicitly penalizes the non-occurrence of a feature :math:`i` @@ -176,3 +177,26 @@ It is advisable to evaluate both models, if time permits. `_ 3rd Conf. on Email and Anti-Spam (CEAS). + +Out-of-core naive Bayes model fitting +------------------------------------- + +Naive Bayes models can be used to tackle large scale classification problems +for which the full training set might not fit in memory. To handle this case, +:class:`MultinomialNB`, :class:`BernoulliNB`, and :class:`GaussianNB` +expose a ``partial_fit`` method that can be used +incrementally as done with other classifiers as demonstrated in +:ref:`example_applications_plot_out_of_core_classification.py`. Both discrete +classifiers support sample weighting; :class:`GaussianNB` does not. + +Contrary to the ``fit`` method, the first call to ``partial_fit`` needs to be +passed the list of all the expected class labels. + +For an overview of available strategies in scikit-learn, see also the +:ref:`out-of-core learning ` documentation. + +note:: + + The ``partial_fit`` method call of naive Bayes models introduces some + computational overhead. It is recommended to use data chunk sizes that are as + large as possible, that is as the available RAM allows. diff --git a/doc/modules/neighbors.rst b/doc/modules/neighbors.rst index b19f6c9063e67..be1a1aeaa40b9 100644 --- a/doc/modules/neighbors.rst +++ b/doc/modules/neighbors.rst @@ -29,20 +29,28 @@ learning methods, since they simply "remember" all of its training data Despite its simplicity, nearest neighbors has been successful in a large number of classification and regression problems, including -handwritten digits or satellite image scenes. It is often successful -in classification situations where the decision boundary is very irregular. +handwritten digits or satellite image scenes. Being a non-parametric method, +it is often successful in classification situations where the decision +boundary is very irregular. The classes in :mod:`sklearn.neighbors` can handle either Numpy arrays or -`scipy.sparse` matrices as input. Arbitrary Minkowski metrics are supported -for searches. +`scipy.sparse` matrices as input. For dense matrices, a large number of +possible distance metrics are supported. For sparse matrices, arbitrary +Minkowski metrics are supported for searches. +There are many learning routines which rely on nearest neighbors at their +core. One example is :ref:`kernel density estimation `, +discussed in the :ref:`density estimation ` section. + + +.. _unsupervised_neighbors: Unsupervised Nearest Neighbors ============================== :class:`NearestNeighbors` implements unsupervised nearest neighbors learning. It acts as a uniform interface to three different nearest neighbors -algorithms: :class:`BallTree`, :class:`scipy.spatial.cKDTree`, and a +algorithms: :class:`BallTree`, :class:`KDTree`, and a brute-force algorithm based on routines in :mod:`sklearn.metrics.pairwise`. The choice of neighbors search algorithm is controlled through the keyword ``'algorithm'``, which must be one of @@ -51,6 +59,86 @@ The choice of neighbors search algorithm is controlled through the keyword from the training data. For a discussion of the strengths and weaknesses of each option, see `Nearest Neighbor Algorithms`_. + .. warning:: + + Regarding the Nearest Neighbors algorithms, if two + neighbors, neighbor :math:`k+1` and :math:`k`, have identical distances + but different labels, the results will depend on the ordering of the + training data. + +Finding the Nearest Neighbors +----------------------------- +For the simple task of finding the nearest neighbors between two sets of +data, the unsupervised algorithms within :mod:`sklearn.neighbors` can be +used: + + >>> from sklearn.neighbors import NearestNeighbors + >>> import numpy as np + >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) + >>> nbrs = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(X) + >>> distances, indices = nbrs.kneighbors(X) + >>> indices # doctest: +ELLIPSIS + array([[0, 1], + [1, 0], + [2, 1], + [3, 4], + [4, 3], + [5, 4]]...) + >>> distances + array([[ 0. , 1. ], + [ 0. , 1. ], + [ 0. , 1.41421356], + [ 0. , 1. ], + [ 0. , 1. ], + [ 0. , 1.41421356]]) + +Because the query set matches the training set, the nearest neighbor of each +point is the point itself, at a distance of zero. + +It is also possible to efficiently produce a sparse graph showing the +connections between neighboring points: + + >>> nbrs.kneighbors_graph(X).toarray() + array([[ 1., 1., 0., 0., 0., 0.], + [ 1., 1., 0., 0., 0., 0.], + [ 0., 1., 1., 0., 0., 0.], + [ 0., 0., 0., 1., 1., 0.], + [ 0., 0., 0., 1., 1., 0.], + [ 0., 0., 0., 0., 1., 1.]]) + +Our dataset is structured such that points nearby in index order are nearby +in parameter space, leading to an approximately block-diagonal matrix of +K-nearest neighbors. Such a sparse graph is useful in a variety of +circumstances which make use of spatial relationships between points for +unsupervised learning: in particular, see :class:`sklearn.manifold.Isomap`, +:class:`sklearn.manifold.LocallyLinearEmbedding`, and +:class:`sklearn.cluster.SpectralClustering`. + +KDTree and BallTree Classes +--------------------------- +Alternatively, one can use the :class:`KDTree` or :class:`BallTree` classes +directly to find nearest neighbors. This is the functionality wrapped by +the :class:`NearestNeighbors` class used above. The Ball Tree and KD Tree +have the same interface; we'll show an example of using the KD Tree here: + + >>> from sklearn.neighbors import KDTree + >>> import numpy as np + >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) + >>> kdt = KDTree(X, leaf_size=30, metric='euclidean') + >>> kdt.query(X, k=2, return_distance=False) # doctest: +ELLIPSIS + array([[0, 1], + [1, 0], + [2, 1], + [3, 4], + [4, 3], + [5, 4]]...) + +Refer to the :class:`KDTree` and :class:`BallTree` class documentation +for more information on the options available for neighbors searches, +including specification of query strategies, of various distance metrics, etc. +For a list of available metrics, see the documentation of the +:class:`DistanceMetric` class. + .. _classification: Nearest Neighbors Classification @@ -96,11 +184,11 @@ distance can be supplied which is used to compute the weights. -.. |classification_1| image:: ../auto_examples/neighbors/images/plot_classification_1.png +.. |classification_1| image:: ../auto_examples/neighbors/images/plot_classification_001.png :target: ../auto_examples/neighbors/plot_classification.html :scale: 50 -.. |classification_2| image:: ../auto_examples/neighbors/images/plot_classification_2.png +.. |classification_2| image:: ../auto_examples/neighbors/images/plot_classification_002.png :target: ../auto_examples/neighbors/plot_classification.html :scale: 50 @@ -139,17 +227,30 @@ weights proportional to the inverse of the distance from the query point. Alternatively, a user-defined function of the distance can be supplied, which will be used to compute the weights. -.. figure:: ../auto_examples/neighbors/images/plot_regression_1.png +.. figure:: ../auto_examples/neighbors/images/plot_regression_001.png :target: ../auto_examples/neighbors/plot_regression.html :align: center :scale: 75 +The use of multi-output nearest neighbors for regression is demonstrated in +:ref:`example_plot_multioutput_face_completion.py`. In this example, the inputs +X are the pixels of the upper half of faces and the outputs Y are the pixels of +the lower half of those faces. + +.. figure:: ../auto_examples/images/plot_multioutput_face_completion_001.png + :target: ../auto_examples/plot_multioutput_face_completion.html + :scale: 75 + :align: center + .. topic:: Examples: * :ref:`example_neighbors_plot_regression.py`: an example of regression using nearest neighbors. + * :ref:`example_plot_multioutput_face_completion.py`: an example of + multi-output regression using nearest neighbors. + Nearest Neighbor Algorithms =========================== @@ -191,7 +292,7 @@ improvement over brute-force for large :math:`N`. An early approach to taking advantage of this aggregate information was the *KD tree* data structure (short for *K-dimensional tree*), which generalizes two-dimensional *Quad-trees* and 3-dimensional *Oct-trees* -to an arbitrary number of dimensions. The KD tree is a tree +to an arbitrary number of dimensions. The KD tree is a binary tree structure which recursively partitions the parameter space along the data axes, dividing it into nested orthotopic regions into which data points are filed. The construction of a KD tree is very fast: because partitioning @@ -203,7 +304,7 @@ neighbors searches, it becomes inefficient as :math:`D` grows very large: this is one manifestation of the so-called "curse of dimensionality". In scikit-learn, KD tree neighbors searches are specified using the keyword ``algorithm = 'kd_tree'``, and are computed using the class -:class:`scipy.spatial.cKDTree`. +:class:`KDTree`. .. topic:: References: @@ -223,8 +324,8 @@ data structure was developed. Where KD trees partition data along Cartesian axes, ball trees partition data in a series of nesting hyper-spheres. This makes tree construction more costly than that of the KD tree, but -results in a data structure which allows for efficient neighbors searches -even in very high dimensions. +results in a data structure which can be very efficient on highly-structured +data, even in very high dimensions. A ball tree recursively divides the data into nodes defined by a centroid :math:`C` and radius :math:`r`, such that each @@ -237,8 +338,10 @@ is reduced through use of the *triangle inequality*: With this setup, a single distance calculation between a test point and the centroid is sufficient to determine a lower and upper bound on the distance to all points within the node. -Because of the spherical geometry of the ball tree nodes, its performance -does not degrade at high dimensions. In scikit-learn, ball-tree-based +Because of the spherical geometry of the ball tree nodes, it can out-perform +a *KD-tree* in high dimensions, though the actual performance is highly +dependent on the structure of the training data. +In scikit-learn, ball-tree-based neighbors searches are specified using the keyword ``algorithm = 'ball_tree'``, and are computed using the class :class:`sklearn.neighbors.BallTree`. Alternatively, the user can work with the :class:`BallTree` class directly. @@ -264,13 +367,13 @@ depends on a number of factors: to precisely characterise. For small :math:`D` (less than 20 or so) the cost is approximately :math:`O[D\log(N)]`, and the KD tree query can be very efficient. - For larger :math:`D`, the cost increases to nearly `O[DN]`, and + For larger :math:`D`, the cost increases to nearly :math:`O[DN]`, and the overhead due to the tree structure can lead to queries which are slower than brute force. For small data sets (:math:`N` less than 30 or so), :math:`\log(N)` is comparable to :math:`N`, and brute force algorithms can be more efficient - than a tree-based approach. Both :class:`cKDTree` and :class:`BallTree` + than a tree-based approach. Both :class:`KDTree` and :class:`BallTree` address this through providing a *leaf size* parameter: this controls the number of samples at which a query switches to brute-force. This allows both algorithms to approach the efficiency of a brute-force computation for small @@ -279,7 +382,7 @@ depends on a number of factors: * data structure: *intrinsic dimensionality* of the data and/or *sparsity* of the data. Intrinsic dimensionality refers to the dimension :math:`d \le D` of a manifold on which the data lies, which can be linearly - or nonlinearly embedded in the parameter space. Sparsity refers to the + or non-linearly embedded in the parameter space. Sparsity refers to the degree to which the data fills the parameter space (this is to be distinguished from the concept as used in "sparse" matrices. The data matrix may have no zero entries, but the **structure** can still be @@ -316,11 +419,13 @@ depends on a number of factors: a significant fraction of the total cost. If very few query points will be required, brute force is better than a tree-based method. -Currently, ``algorithm = 'auto'`` selects ``'ball_tree'`` if -:math:`k < N/2`, and ``'brute'`` otherwise. This choice is based on -the assumption that the number of query points is at least the same order -as the number of training points, and that ``leaf_size`` is close to its -default value of ``30``. +Currently, ``algorithm = 'auto'`` selects ``'kd_tree'`` if :math:`k < N/2` +and the ``'effective_metric_'`` is in the ``'VALID_METRICS'`` list of +``'kd_tree'``. It selects ``'ball_tree'`` if :math:`k < N/2` and the +``'effective_metric_'`` is not in the ``'VALID_METRICS'`` list of +``'kd_tree'``. It selects ``'brute'`` if :math:`k >= N/2`. This choice is based on the assumption that the number of query points is at least the +same order as the number of training points, and that ``leaf_size`` is +close to its default value of ``30``. Effect of ``leaf_size`` ----------------------- @@ -373,17 +478,17 @@ methods that do not make this assumption. Usage of the default >>> clf = NearestCentroid() >>> clf.fit(X, y) NearestCentroid(metric='euclidean', shrink_threshold=None) - >>> print clf.predict([[-0.8, -1]]) + >>> print(clf.predict([[-0.8, -1]])) [1] Nearest Shrunken Centroid ------------------------- -The :class:`NearestCentroid` classifier has a `shrink_threshold` parameter, +The :class:`NearestCentroid` classifier has a ``shrink_threshold`` parameter, which implements the nearest shrunken centroid classifier. In effect, the value of each feature for each centroid is divided by the within-class variance of -that feature. The feature values are then reduced by `shrink_threshold`. Most +that feature. The feature values are then reduced by ``shrink_threshold``. Most notably, if a particular feature value crosses zero, it is set to zero. In effect, this removes the feature from affecting the classification. This is useful, for example, for removing noisy features. @@ -391,11 +496,11 @@ This is useful, for example, for removing noisy features. In the example below, using a small shrink threshold increases the accuracy of the model from 0.81 to 0.82. -.. |nearest_centroid_1| image:: ../auto_examples/neighbors/images/plot_nearest_centroid_1.png +.. |nearest_centroid_1| image:: ../auto_examples/neighbors/images/plot_nearest_centroid_001.png :target: ../auto_examples/neighbors/plot_classification.html :scale: 50 -.. |nearest_centroid_2| image:: ../auto_examples/neighbors/images/plot_nearest_centroid_2.png +.. |nearest_centroid_2| image:: ../auto_examples/neighbors/images/plot_nearest_centroid_002.png :target: ../auto_examples/neighbors/plot_classification.html :scale: 50 @@ -406,3 +511,177 @@ the model from 0.81 to 0.82. * :ref:`example_neighbors_plot_nearest_centroid.py`: an example of classification using nearest centroid with different shrink thresholds. +Approximate Nearest Neighbors +============================= + +There are many efficient exact nearest neighbor search algorithms for low +dimensions :math:`d` (approximately 50). However these algorithms perform poorly +with respect to space and query time when :math:`d` increases. These algorithms +are not any better than comparing query point to each point from the database in +a high dimension (see :ref:`brute_force`). This is a well-known consequence of +the phenomenon called “The Curse of Dimensionality”. + +There are certain applications where we do not need the exact nearest neighbors +but having a “good guess” would suffice. When answers do not have to be exact, +the :class:`LSHForest` class implements an approximate nearest neighbor search. +Approximate nearest neighbor search methods have been designed to try to speedup +query time with high dimensional data. These techniques are useful when the aim +is to characterize the neighborhood rather than identifying the exact neighbors +themselves (eg: k-nearest neighbors classification and regression). Some of the +most popular approximate nearest neighbor search techniques are locality +sensitive hashing, best bin fit and balanced box-decomposition tree based +search. + +Locality Sensitive Hashing Forest +--------------------------------- + +The vanilla implementation of locality sensitive hashing has a hyper-parameter +that is hard to tune in practice, therefore scikit-learn implements a variant +called :class:`LSHForest` that has more reasonable hyperparameters. +Both methods use internally random hyperplanes to index the samples into +buckets and actual cosine similarities are only computed for samples that +collide with the query hence achieving sublinear scaling. +(see :ref:`Mathematical description of Locality Sensitive +Hashing `). + +:class:`LSHForest` has two main hyper-parameters: ``n_estimators`` and +``n_candidates``. The accuracy of queries can be controlled using these +parameters as demonstrated in the following plots: + +.. figure:: ../auto_examples/neighbors/images/plot_approximate_nearest_neighbors_hyperparameters_001.png + :target: ../auto_examples/neighbors/plot_approximate_nearest_neighbors_hyperparameters.html + :align: center + :scale: 50 + +.. figure:: ../auto_examples/neighbors/images/plot_approximate_nearest_neighbors_hyperparameters_002.png + :target: ../auto_examples/neighbors/plot_approximate_nearest_neighbors_hyperparameters.html + :align: center + :scale: 50 + +As a rule of thumb, a user can set ``n_estimators`` to a large enough value +(e.g. between 10 and 50) and then adjust ``n_candidates`` to trade off accuracy +for query time. + +For small data sets, the brute force method for exact nearest neighbor search +can be faster than LSH Forest. However LSH Forest has a sub-linear query time +scalability with the index size. The exact break even point where LSH Forest +queries become faster than brute force depends on the dimensionality, structure +of the dataset, required level of precision, characteristics of the runtime +environment such as availability of BLAS optimizations, number of CPU cores and +size of the CPU caches. Following graphs depict scalability of LSHForest queries +with index size. + +.. figure:: ../auto_examples/neighbors/images/plot_approximate_nearest_neighbors_scalability_001.png + :target: ../auto_examples/neighbors/plot_approximate_nearest_neighbors_scalability.html + :align: center + :scale: 50 + +.. figure:: ../auto_examples/neighbors/images/plot_approximate_nearest_neighbors_scalability_002.png + :target: ../auto_examples/neighbors/plot_approximate_nearest_neighbors_scalability.html + :align: center + :scale: 50 + +.. figure:: ../auto_examples/neighbors/images/plot_approximate_nearest_neighbors_scalability_003.png + :target: ../auto_examples/neighbors/plot_approximate_nearest_neighbors_scalability.html + :align: center + :scale: 50 + +For fixed :class:`LSHForest` parameters, the accuracy of queries tends to slowly +decrease with larger datasets. The error bars on the previous plots represent +standard deviation across different queries. + +.. topic:: Examples: + + * :ref:`example_neighbors_plot_approximate_nearest_neighbors_hyperparameters.py`: an example of + the behavior of hyperparameters of approximate nearest neighbor search using LSH Forest. + + * :ref:`example_neighbors_plot_approximate_nearest_neighbors_scalability.py`: an example of + scalability of approximate nearest neighbor search using LSH Forest. + +.. _mathematical_description_of_lsh: + +Mathematical description of Locality Sensitive Hashing +------------------------------------------------------ + +Locality sensitive hashing (LSH) techniques have been used in many areas where +nearest neighbor search is performed in high dimensions. The main concept +behind LSH is to hash each data point in the database using multiple +(often simple) hash functions to form a digest (also called a *hash*). At this +point the probability of collision - where two objects have similar digests +- is much higher for the points which are close to each other than that of the +distant points. We describe the requirements for a hash function family to be +locality sensitive as follows. + +A family :math:`H` of functions from a domain :math:`S` to a range :math:`U` +is called :math:`(r, e , p1 , p2 )`-sensitive, with :math:`r, e > 0`, +:math:`p_1 > p_2 > 0`, if for any :math:`p, q \in S`, the following conditions +hold (:math:`D` is the distance function): + +* If :math:`D(p,q) <= r` then :math:`P_H[h(p) = h(q)] >= p_1`, +* If :math:`D(p,q) > r(1 + e)` then :math:`P_H[h(p) = h(q)] <= p_2`. + +As defined, nearby points within a distance of :math:`r` to each other are +likely to collide with probability :math:`p_1`. In contrast, distant points +which are located with the distance more than :math:`r(1 + e)` have a small +probability of :math:`p_2` of collision. Suppose there is a family of LSH +function :math:`H`. An *LSH index* is built as follows: + +1. Choose :math:`k` functions :math:`h_1, h_2, … h_k` uniformly at + random (with replacement) from :math:`H`. For any :math:`p \in S`, place + :math:`p` in the bucket with label + :math:`g(p) = (h_1(p), h_2(p), … h_k(p))`. Observe that if + each :math:`h_i` outputs one “digit”, each bucket has a k-digit label. + +2. Independently perform step 1 :math:`l` times to construct :math:`l` + separate estimators, with hash functions :math:`g_1, g_2, … g_l`. + +The reason to concatenate hash functions in the step 1 is to decrease the +probability of the collision of distant points as much as possible. The +probability drops from :math:`p_2` to :math:`p_2^k` which is negligibly +small for large :math:`k`. The choice of :math:`k` is strongly dependent on +the data set size and structure and is therefore hard to tune in practice. +There is a side effect of having a large :math:`k`; it has the potential of +decreasing the chance of nearby points getting collided. To address this +issue, multiple estimators are constructed in step 2. + +The requirement to tune :math:`k` for a given dataset makes classical LSH +cumbersome to use in practice. The LSH Forest variant has benn designed to +alleviate this requirement by automatically adjusting the number of digits +used to hash the samples. + +LSH Forest is formulated with prefix trees with each leaf of +a tree corresponding to an actual data point in the database. There are +:math:`l` such trees which compose the forest and they are constructed using +independently drawn random sequence of hash functions from :math:`H`. In this +implementation, "Random Projections" is being used as the LSH technique which +is an approximation for the cosine distance. The length of the sequence of +hash functions is kept fixed at 32. Moreover, a prefix tree is implemented +using sorted arrays and binary search. + +There are two phases of tree traversals used in order to answer a query to find +the :math:`m` nearest neighbors of a point :math:`q`. First, a top-down +traversal is performed using a binary search to identify the leaf having the +longest prefix match (maximum depth) with :math:`q`'s label after subjecting +:math:`q` to the same hash functions. :math:`M >> m` points (total candidates) +are extracted from the forest, moving up from the previously found maximum +depth towards the root synchronously across all trees in the bottom-up +traversal. `M` is set to :math:`cl` where :math:`c`, the number of candidates +extracted from each tree, is a constant. Finally, the similarity of each of +these :math:`M` points against point :math:`q` is calculated and the top +:math:`m` points are returned as the nearest neighbors of :math:`q`. Since +most of the time in these queries is spent calculating the distances to +candidates, the speedup compared to brute force search is approximately +:math:`N/M`, where :math:`N` is the number of points in database. + +.. topic:: References: + + * `"Near-Optimal Hashing Algorithms for Approximate Nearest Neighbor in + High Dimensions" + `_, + Alexandr, A., Indyk, P., Foundations of Computer Science, 2006. FOCS + '06. 47th Annual IEEE Symposium + + * `“LSH Forest: Self-Tuning Indexes for Similarity Search” + `_, + Bawa, M., Condie, T., Ganesan, P., WWW '05 Proceedings of the 14th + international conference on World Wide Web Pages 651-660 diff --git a/doc/modules/neural_networks.rst b/doc/modules/neural_networks.rst new file mode 100644 index 0000000000000..9924e76eed600 --- /dev/null +++ b/doc/modules/neural_networks.rst @@ -0,0 +1,161 @@ +.. _neural_network: + +==================================== +Neural network models (unsupervised) +==================================== + +.. currentmodule:: sklearn.neural_network + + +.. _rbm: + +Restricted Boltzmann machines +============================= + +Restricted Boltzmann machines (RBM) are unsupervised nonlinear feature learners +based on a probabilistic model. The features extracted by an RBM or a hierarchy +of RBMs often give good results when fed into a linear classifier such as a +linear SVM or a perceptron. + +The model makes assumptions regarding the distribution of inputs. At the moment, +scikit-learn only provides :class:`BernoulliRBM`, which assumes the inputs are +either binary values or values between 0 and 1, each encoding the probability +that the specific feature would be turned on. + +The RBM tries to maximize the likelihood of the data using a particular +graphical model. The parameter learning algorithm used (:ref:`Stochastic +Maximum Likelihood `) prevents the representations from straying far +from the input data, which makes them capture interesting regularities, but +makes the model less useful for small datasets, and usually not useful for +density estimation. + +The method gained popularity for initializing deep neural networks with the +weights of independent RBMs. This method is known as unsupervised pre-training. + +.. figure:: ../auto_examples/neural_networks/images/plot_rbm_logistic_classification_001.png + :target: ../auto_examples/neural_networks/plot_rbm_logistic_classification.html + :align: center + :scale: 100% + +.. topic:: Examples: + + * :ref:`example_neural_networks_plot_rbm_logistic_classification.py` + + +Graphical model and parametrization +----------------------------------- + +The graphical model of an RBM is a fully-connected bipartite graph. + +.. image:: ../images/rbm_graph.png + :align: center + +The nodes are random variables whose states depend on the state of the other +nodes they are connected to. The model is therefore parameterized by the +weights of the connections, as well as one intercept (bias) term for each +visible and hidden unit, ommited from the image for simplicity. + +The energy function measures the quality of a joint assignment: + +.. math:: + + E(\mathbf{v}, \mathbf{h}) = \sum_i \sum_j w_{ij}v_ih_j + \sum_i b_iv_i + + \sum_j c_jh_j + +In the formula above, :math:`\mathbf{b}` and :math:`\mathbf{c}` are the +intercept vectors for the visible and hidden layers, respectively. The +joint probability of the model is defined in terms of the energy: + +.. math:: + + P(\mathbf{v}, \mathbf{h}) = \frac{e^{-E(\mathbf{v}, \mathbf{h})}}{Z} + + +The word *restricted* refers to the bipartite structure of the model, which +prohibits direct interaction between hidden units, or between visible units. +This means that the following conditional independencies are assumed: + +.. math:: + + h_i \bot h_j | \mathbf{v} \\ + v_i \bot v_j | \mathbf{h} + +The bipartite structure allows for the use of efficient block Gibbs sampling for +inference. + +Bernoulli Restricted Boltzmann machines +--------------------------------------- + +In the :class:`BernoulliRBM`, all units are binary stochastic units. This +means that the input data should either be binary, or real-valued between 0 and +1 signifying the probability that the visible unit would turn on or off. This +is a good model for character recognition, where the interest is on which +pixels are active and which aren't. For images of natural scenes it no longer +fits because of background, depth and the tendency of neighbouring pixels to +take the same values. + +The conditional probability distribution of each unit is given by the +logistic sigmoid activation function of the input it receives: + +.. math:: + + P(v_i=1|\mathbf{h}) = \sigma(\sum_j w_{ij}h_j + b_i) \\ + P(h_i=1|\mathbf{v}) = \sigma(\sum_i w_{ij}v_i + c_j) + +where :math:`\sigma` is the logistic sigmoid function: + +.. math:: + + \sigma(x) = \frac{1}{1 + e^{-x}} + +.. _sml: + +Stochastic Maximum Likelihood learning +-------------------------------------- + +The training algorithm implemented in :class:`BernoulliRBM` is known as +Stochastic Maximum Likelihood (SML) or Persistent Contrastive Divergence +(PCD). Optimizing maximum likelihood directly is infeasible because of +the form of the data likelihood: + +.. math:: + + \log P(v) = \log \sum_h e^{-E(v, h)} - \log \sum_{x, y} e^{-E(x, y)} + +For simplicity the equation above is written for a single training example. +The gradient with respect to the weights is formed of two terms corresponding to +the ones above. They are usually known as the positive gradient and the negative +gradient, because of their respective signs. In this implementation, the +gradients are estimated over mini-batches of samples. + +In maximizing the log-likelihood, the positive gradient makes the model prefer +hidden states that are compatible with the observed training data. Because of +the bipartite structure of RBMs, it can be computed efficiently. The +negative gradient, however, is intractable. Its goal is to lower the energy of +joint states that the model prefers, therefore making it stay true to the data. +It can be approximated by Markov chain Monte Carlo using block Gibbs sampling by +iteratively sampling each of :math:`v` and :math:`h` given the other, until the +chain mixes. Samples generated in this way are sometimes refered as fantasy +particles. This is inefficient and it is difficult to determine whether the +Markov chain mixes. + +The Contrastive Divergence method suggests to stop the chain after a small +number of iterations, :math:`k`, usually even 1. This method is fast and has +low variance, but the samples are far from the model distribution. + +Persistent Contrastive Divergence addresses this. Instead of starting a new +chain each time the gradient is needed, and performing only one Gibbs sampling +step, in PCD we keep a number of chains (fantasy particles) that are updated +:math:`k` Gibbs steps after each weight update. This allows the particles to +explore the space more thoroughly. + +.. topic:: References: + + * `"A fast learning algorithm for deep belief nets" + `_ + G. Hinton, S. Osindero, Y.-W. Teh, 2006 + + * `"Training Restricted Boltzmann Machines using Approximations to + the Likelihood Gradient" + `_ + T. Tieleman, 2008 diff --git a/doc/modules/outlier_detection.rst b/doc/modules/outlier_detection.rst index fb57da80e035a..a99758989e195 100644 --- a/doc/modules/outlier_detection.rst +++ b/doc/modules/outlier_detection.rst @@ -7,7 +7,7 @@ Novelty and Outlier Detection .. currentmodule:: sklearn Many applications require being able to decide whether a new observation -belongs to the same distribution as exiting observations (it is an +belongs to the same distribution as existing observations (it is an `inlier`), or should be considered as different (it is an outlier). Often, this ability is used to clean real data sets. Two important distinction must be made: @@ -24,14 +24,14 @@ The scikit-learn project provides a set of machine learning tools that can be used both for novelty or outliers detection. This strategy is implemented with objects learning in an unsupervised way from the data:: - estimor.fit(X_train) + estimator.fit(X_train) new observations can then be sorted as inliers or outliers with a `predict` method:: estimator.predict(X_test) -Inliers are labeled 0, while outliers are labeled 1. +Inliers are labeled 1, while outliers are labeled -1. Novelty Detection ================= @@ -42,7 +42,7 @@ add one more observation to that data set. Is the new observation so different from the others that we can doubt it is regular? (i.e. does it come from the same distribution?) Or on the contrary, is it so similar to the other that we cannot distinguish it from the original -observations? This is the question adressed by the novelty detection +observations? This is the question addressed by the novelty detection tools and methods. In general, it is about to learn a rough, close frontier delimiting @@ -53,44 +53,50 @@ coming from the same population than the initial observations. Otherwise, if they lay outside the frontier, we can say that they are abnormal with a given confidence in our assessment. -The One-Class SVM has been introduced in [1] for that purpose and -implemented in the :ref:`svm` module in the +The One-Class SVM has been introduced by Schölkopf et al. for that purpose +and implemented in the :ref:`svm` module in the :class:`svm.OneClassSVM` object. It requires the choice of a kernel and a scalar parameter to define a frontier. The RBF kernel is -usually chosen although there exist no exact formula or algorithm to -set its bandwith parameter. This is the default in the scikit-learn +usually chosen although there exists no exact formula or algorithm to +set its bandwidth parameter. This is the default in the scikit-learn implementation. The :math:`\nu` parameter, also known as the margin of the One-Class SVM, corresponds to the probability of finding a new, but regular, observation outside the frontier. +.. topic:: References: + + * `Estimating the support of a high-dimensional distribution + `_ Schölkopf, + Bernhard, et al. Neural computation 13.7 (2001): 1443-1471. + .. topic:: Examples: - * See :ref:`example_svm_plot_oneclass.py` for vizualizing the + * See :ref:`example_svm_plot_oneclass.py` for visualizing the frontier learned around some data by a :class:`svm.OneClassSVM` object. -.. figure:: ../auto_examples/svm/images/plot_oneclass_1.png +.. figure:: ../auto_examples/svm/images/plot_oneclass_001.png :target: ../auto_examples/svm/plot_oneclasse.html :align: center :scale: 75% - + Outlier Detection ================= Outlier detection is similar to novelty detection in the sense that the goal is to separate a core of regular observations from some -polutting ones, called "outliers". Yet, in the case of outlier +polluting ones, called "outliers". Yet, in the case of outlier detection, we don't have a clean data set representing the population of regular observations that can be used to train any tool. -Fitting an elliptic envelop ------------------------------ +Fitting an elliptic envelope +---------------------------- One common way of performing outlier detection is to assume that the regular data come from a known distribution (e.g. data are Gaussian -distributed). From this assumption, we generaly try to define the +distributed). From this assumption, we generally try to define the "shape" of the data, and can define outlying observations as observations which stand far enough from the fit shape. @@ -105,7 +111,7 @@ whithout being influenced by outliers). The Mahalanobis distances obtained from this estimate is used to derive a measure of outlyingness. This strategy is illustrated below. -.. figure:: ../auto_examples/covariance/images/plot_mahalanobis_distances_1.png +.. figure:: ../auto_examples/covariance/images/plot_mahalanobis_distances_001.png :target: ../auto_examples/covariance/plot_mahalanobis_distances.html :align: center :scale: 75% @@ -123,11 +129,11 @@ This strategy is illustrated below. .. [RD1999] Rousseeuw, P.J., Van Driessen, K. "A fast algorithm for the minimum covariance determinant estimator" Technometrics 41(3), 212 (1999) -One-class SVM versus elliptic envelop +One-class SVM versus elliptic envelope -------------------------------------- Strictly-speaking, the One-class SVM is not an outlier-detection method, -but a novelty-detection method: it's training set should not be +but a novelty-detection method: its training set should not be contaminated by outliers as it may fit them. That said, outlier detection in high-dimension, or without any assumptions on the distribution of the inlying data is very challenging, and a One-class SVM gives useful @@ -138,19 +144,19 @@ The examples below illustrate how the performance of the less unimodal. :class:`svm.OneClassSVM` works better on data with multiple modes. -.. |outlier1| image:: ../auto_examples/covariance/images/plot_outlier_detection_1.png +.. |outlier1| image:: ../auto_examples/covariance/images/plot_outlier_detection_001.png :target: ../auto_examples/covariance/plot_outlier_detection.html :scale: 50% -.. |outlier2| image:: ../auto_examples/covariance/images/plot_outlier_detection_2.png +.. |outlier2| image:: ../auto_examples/covariance/images/plot_outlier_detection_002.png :target: ../auto_examples/covariance/plot_outlier_detection.html :scale: 50% -.. |outlier3| image:: ../auto_examples/covariance/images/plot_outlier_detection_3.png +.. |outlier3| image:: ../auto_examples/covariance/images/plot_outlier_detection_003.png :target: ../auto_examples/covariance/plot_outlier_detection.html :scale: 50% -.. list-table:: **Comparing One-class SVM approach, and elliptic envelopp** +.. list-table:: **Comparing One-class SVM approach, and elliptic envelope** :widths: 40 60 * diff --git a/doc/modules/pipeline.rst b/doc/modules/pipeline.rst index 908f001dab1b3..61a0e318da5b8 100644 --- a/doc/modules/pipeline.rst +++ b/doc/modules/pipeline.rst @@ -1,8 +1,13 @@ +.. _combining_estimators: + +=============================================== +Pipeline and FeatureUnion: combining estimators +=============================================== + .. _pipeline: -============================== Pipeline: chaining estimators -============================== +============================= .. currentmodule:: sklearn.pipeline @@ -11,19 +16,19 @@ into one. This is useful as there is often a fixed sequence of steps in processing the data, for example feature selection, normalization and classification. :class:`Pipeline` serves two purposes here: - **Convenience**: You only have to call ``fit`` and ``predict`` once on your + **Convenience**: You only have to call ``fit`` and ``predict`` once on your data to fit a whole sequence of estimators. - + **Joint parameter selection**: You can :ref:`grid search ` over parameters of all estimators in the pipeline at once. -For estimators to be usable within a pipeline, all except the last one need to have -a ``transform`` function. Otherwise, the dataset can not be passed through this -estimator. +All estimators in a pipeline, except the last one, must be transformers +(i.e. must have a ``transform`` method). +The last estimator may be any type (transformer, classifier, etc.). Usage -===== +----- The :class:`Pipeline` is build using a list of ``(key, value)`` pairs, where the ``key`` a string containing the name you want to give this step and ``value`` @@ -37,10 +42,25 @@ is an estimator object:: >>> clf # doctest: +NORMALIZE_WHITESPACE Pipeline(steps=[('reduce_dim', PCA(copy=True, n_components=None, whiten=False)), ('svm', SVC(C=1.0, cache_size=200, class_weight=None, - coef0=0.0, degree=3, gamma=0.0, kernel='rbf', probability=False, - shrinking=True, tol=0.001, verbose=False))]) - -The estimators of the pipeline are stored as a list in the ``steps`` attribute:: + coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=-1, + probability=False, random_state=None, shrinking=True, tol=0.001, + verbose=False))]) + +The utility function :func:`make_pipeline` is a shorthand +for constructing pipelines; +it takes a variable number of estimators and returns a pipeline, +filling in the names automatically:: + + >>> from sklearn.pipeline import make_pipeline + >>> from sklearn.naive_bayes import MultinomialNB + >>> from sklearn.preprocessing import Binarizer + >>> make_pipeline(Binarizer(), MultinomialNB()) # doctest: +NORMALIZE_WHITESPACE + Pipeline(steps=[('binarizer', Binarizer(copy=True, threshold=0.0)), + ('multinomialnb', MultinomialNB(alpha=1.0, + class_prior=None, + fit_prior=True))]) + +The estimators of a pipeline are stored as a list in the ``steps`` attribute:: >>> clf.steps[0] ('reduce_dim', PCA(copy=True, n_components=None, whiten=False)) @@ -53,10 +73,12 @@ and as a ``dict`` in ``named_steps``:: Parameters of the estimators in the pipeline can be accessed using the ``__`` syntax:: - >>> clf.set_params(svm__C=10) # NORMALIZE_WHITESPACE - Pipeline(steps=[('reduce_dim', PCA(copy=True, n_components=None, whiten=False)), ('svm', SVC(C=10, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, - kernel='rbf', probability=False, shrinking=True, tol=0.001, - verbose=False))]) + >>> clf.set_params(svm__C=10) # doctest: +NORMALIZE_WHITESPACE + Pipeline(steps=[('reduce_dim', PCA(copy=True, n_components=None, + whiten=False)), ('svm', SVC(C=10, cache_size=200, class_weight=None, + coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=-1, + probability=False, random_state=None, shrinking=True, tol=0.001, + verbose=False))]) This is particularly important for doing grid searches:: @@ -64,23 +86,84 @@ This is particularly important for doing grid searches:: >>> params = dict(reduce_dim__n_components=[2, 5, 10], ... svm__C=[0.1, 10, 100]) >>> grid_search = GridSearchCV(clf, param_grid=params) - + .. topic:: Examples: - * :ref:`example_feature_selection_pipeline.py` - * :ref:`example_grid_search_text_feature_extraction.py` + * :ref:`example_feature_selection_feature_selection_pipeline.py` + * :ref:`example_model_selection_grid_search_text_feature_extraction.py` * :ref:`example_plot_digits_pipe.py` * :ref:`example_plot_kernel_approximation.py` * :ref:`example_svm_plot_svm_anova.py` +.. topic:: See also: + + * :ref:`grid_search` + Notes -===== +----- Calling ``fit`` on the pipeline is the same as calling ``fit`` on each estimator in turn, ``transform`` the input and pass it on to the next step. -The pipeline has all the methods that the last estimator in the pipline has, +The pipeline has all the methods that the last estimator in the pipeline has, i.e. if the last estimator is a classifier, the :class:`Pipeline` can be used as a classifier. If the last estimator is a transformer, again, so is the pipeline. + + +.. _feature_union: + +FeatureUnion: composite feature spaces +====================================== + +.. currentmodule:: sklearn.pipeline + +:class:`FeatureUnion` combines several transformer objects into a new +transformer that combines their output. A :class:`FeatureUnion` takes +a list of transformer objects. During fitting, each of these +is fit to the data independently. For transforming data, the +transformers are applied in parallel, and the sample vectors they output +are concatenated end-to-end into larger vectors. + +:class:`FeatureUnion` serves the same purposes as :class:`Pipeline` - +convenience and joint parameter estimation and validation. + +:class:`FeatureUnion` and :class:`Pipeline` can be combined to +create complex models. + +(A :class:`FeatureUnion` has no way of checking whether two transformers +might produce identical features. It only produces a union when the +feature sets are disjoint, and making sure they are is the caller's +responsibility.) + + +Usage +----- + +A :class:`FeatureUnion` is built using a list of ``(key, value)`` pairs, +where the ``key`` is the name you want to give to a given transformation +(an arbitrary string; it only serves as an identifier) +and ``value`` is an estimator object:: + + >>> from sklearn.pipeline import FeatureUnion + >>> from sklearn.decomposition import PCA + >>> from sklearn.decomposition import KernelPCA + >>> estimators = [('linear_pca', PCA()), ('kernel_pca', KernelPCA())] + >>> combined = FeatureUnion(estimators) + >>> combined # doctest: +NORMALIZE_WHITESPACE + FeatureUnion(n_jobs=1, transformer_list=[('linear_pca', PCA(copy=True, + n_components=None, whiten=False)), ('kernel_pca', KernelPCA(alpha=1.0, + coef0=1, degree=3, eigen_solver='auto', fit_inverse_transform=False, + gamma=None, kernel='linear', kernel_params=None, max_iter=None, + n_components=None, remove_zero_eig=False, tol=0))], + transformer_weights=None) + +Like pipelines, feature unions have a shorthand constructor called +:func:`make_union` that does require manual naming of the components. + + +.. topic:: Examples: + + * :ref:`example_feature_stacker.py` + * :ref:`example_hetero_feature_union.py` diff --git a/doc/modules/pls.rst b/doc/modules/pls.rst deleted file mode 100644 index 668332461c4f5..0000000000000 --- a/doc/modules/pls.rst +++ /dev/null @@ -1,40 +0,0 @@ -.. _pls: - -====================== -Partial Least Squares -====================== - -.. currentmodule:: sklearn.pls - -Partial least squares (PLS) models are useful to find linear relations -between two multivariate datasets: in PLS the `X` and `Y` arguments of -the `fit` method are 2D arrays. - -.. figure:: ../auto_examples/images/plot_pls_1.png - :target: ../auto_examples/plot_pls.html - :scale: 75% - :align: center - - -PLS finds the fundamental relations between two matrices -(X and Y): it is a latent variable approach to modeling the covariance -structures in these two spaces. A PLS model will try to find the -multidimensional direction in the X space that explains the maximum -multidimensional variance direction in the Y space. PLS-regression is -particularly suited when the matrix of predictors has more variables -than observations, and when there is multicollinearity among X -values. By contrast, standard regression will fail in these cases. - -Classes included in this module are :class:`PLSRegression` -:class:`PLSCanonical`, :class:`CCA` and :class:`PLSSVD` - - -.. topic:: Reference: - - * JA Wegelin - `A survey of Partial Least Squares (PLS) methods, with emphasis on the two-block case `_ - -.. topic:: Examples: - - * :ref:`example_plot_pls.py` - diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst index c1dba225fac50..b68ab79eb2b09 100644 --- a/doc/modules/preprocessing.rst +++ b/doc/modules/preprocessing.rst @@ -12,8 +12,8 @@ into a representation that is more suitable for the downstream estimators. .. _preprocessing_scaler: -Standardization or Mean Removal and Variance Scaling -==================================================== +Standardization, or mean removal and variance scaling +===================================================== **Standardization** of datasets is a **common requirement for many machine learning estimators** implemented in the scikit: they might behave @@ -38,9 +38,10 @@ The function :func:`scale` provides a quick and easy way to perform this operation on a single array-like dataset:: >>> from sklearn import preprocessing - >>> X = [[ 1., -1., 2.], - ... [ 2., 0., 0.], - ... [ 0., 1., -1.]] + >>> import numpy as np + >>> X = np.array([[ 1., -1., 2.], + ... [ 2., 0., 0.], + ... [ 0., 1., -1.]]) >>> X_scaled = preprocessing.scale(X) >>> X_scaled # doctest: +ELLIPSIS @@ -97,6 +98,53 @@ passing ``with_mean=False`` or ``with_std=False`` to the constructor of :class:`StandardScaler`. +Scaling features to a range +--------------------------- +An alternative standardization is scaling features to +lie between a given minimum and maximum value, often between zero and one. +This can be achieved using :class:`MinMaxScaler`. + +The motivation to use this scaling include robustness to very small +standard deviations of features and preserving zero entries in sparse data. + +Here is an example to scale a toy data matrix to the ``[0, 1]`` range:: + + >>> X_train = np.array([[ 1., -1., 2.], + ... [ 2., 0., 0.], + ... [ 0., 1., -1.]]) + ... + >>> min_max_scaler = preprocessing.MinMaxScaler() + >>> X_train_minmax = min_max_scaler.fit_transform(X_train) + >>> X_train_minmax + array([[ 0.5 , 0. , 1. ], + [ 1. , 0.5 , 0.33333333], + [ 0. , 1. , 0. ]]) + +The same instance of the transformer can then be applied to some new test data +unseen during the fit call: the same scaling and shifting operations will be +applied to be consistent with the transformation performed on the train data:: + + >>> X_test = np.array([[ -3., -1., 4.]]) + >>> X_test_minmax = min_max_scaler.transform(X_test) + >>> X_test_minmax + array([[-1.5 , 0. , 1.66666667]]) + +It is possible to introspect the scaler attributes to find about the exact +nature of the transformation learned on the training data:: + + >>> min_max_scaler.scale_ # doctest: +ELLIPSIS + array([ 0.5 , 0.5 , 0.33...]) + + >>> min_max_scaler.min_ # doctest: +ELLIPSIS + array([ 0. , 0.5 , 0.33...]) + +If :class:`MinMaxScaler` is given an explicit ``feature_range=(min, max)`` the +full formula is:: + + X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) + + X_scaled = X_std / (max - min) + min + .. topic:: References: Further discussion on the importance of centering and scaling data is @@ -136,6 +184,17 @@ of :class:`StandardScaler`. This is very useful for scaling the target / response variables used for regression. + +Centering kernel matrices +------------------------- + +If you have a kernel matrix of a kernel :math:`K` that computes a dot product +in a feature space defined by function :math:`phi`, +a :class:`KernelCenterer` can transform the kernel matrix +so that it contains inner products in the feature space +defined by :math:`phi` followed by removal of the mean in that space. + + Normalization ============= @@ -204,15 +263,13 @@ Feature binarization -------------------- **Feature binarization** is the process of **thresholding numerical -features to get boolean values**. This can be useful for downsteam +features to get boolean values**. This can be useful for downstream probabilistic estimators that make assumption that the input data is distributed according to a multi-variate `Bernoulli distribution `_. For instance, -this is the case for the most common class of `(Restricted) Boltzmann -Machines `_ -(not yet implemented in the scikit). +this is the case for the :class:`sklearn.neural_network.BernoulliRBM`. -It is also commmon among the text processing community to use binary +It is also common among the text processing community to use binary feature values (probably to simplify the probabilistic reasoning) even if normalized counts (a.k.a. term frequencies) or TF-IDF valued features often perform slightly better in practice. @@ -257,68 +314,100 @@ to be used when the transformer API is not necessary. To avoid unnecessary memory copies, it is recommended to choose the CSR representation upstream. -Label preprocessing -=================== - -Label binarization ------------------- - -:class:`LabelBinarizer` is a utility class to help create a label indicator -matrix from a list of multi-class labels:: - - >>> lb = preprocessing.LabelBinarizer() - >>> lb.fit([1, 2, 6, 4, 2]) - LabelBinarizer(neg_label=0, pos_label=1) - >>> lb.classes_ - array([1, 2, 4, 6]) - >>> lb.transform([1, 6]) - array([[1, 0, 0, 0], - [0, 0, 0, 1]]) - -:class:`LabelBinarizer` also supports multiple labels per instance:: - - >>> lb.fit_transform([(1, 2), (3,)]) - array([[1, 1, 0], - [0, 0, 1]]) - >>> lb.classes_ - array([1, 2, 3]) - -Label encoding --------------- - -:class:`LabelEncoder` is a utility class to help normalize labels such that -they contain only values between 0 and n_classes-1. This is sometimes useful -for writing efficient Cython routines. :class:`LabelEncoder` can be used as -follows:: - - >>> from sklearn import preprocessing - >>> le = preprocessing.LabelEncoder() - >>> le.fit([1, 2, 2, 6]) - LabelEncoder() - >>> le.classes_ - array([1, 2, 6]) - >>> le.transform([1, 1, 2, 6]) - array([0, 0, 1, 2]) - >>> le.inverse_transform([0, 0, 1, 2]) - array([1, 1, 2, 6]) - -It can also be used to transform non-numerical labels (as long as they are -hashable and comparable) to numerical labels:: - - >>> le = preprocessing.LabelEncoder() - >>> le.fit(["paris", "paris", "tokyo", "amsterdam"]) - LabelEncoder() - >>> list(le.classes_) - ['amsterdam', 'paris', 'tokyo'] - >>> le.transform(["tokyo", "tokyo", "paris"]) - array([2, 2, 1]) - >>> list(le.inverse_transform([2, 2, 1])) - ['tokyo', 'tokyo', 'paris'] - - -.. TODO - - Kernel centering - ================ - - Please @mblondel or someone else write me! + +.. _preprocessing_categorical_features: + +Encoding categorical features +============================= +Often features are not given as continuous values but categorical. +For example a person could have features ``["male", "female"]``, +``["from Europe", "from US", "from Asia"]``, +``["uses Firefox", "uses Chrome", "uses Safari", "uses Internet Explorer"]``. +Such features can be efficiently coded as integers, for instance +``["male", "from US", "uses Internet Explorer"]`` could be expressed as +``[0, 1, 3]`` while ``["female", "from Asia", "uses Chrome"]`` would be +``[1, 2, 1]``. + +Such integer representation can not be used directly with scikit-learn estimators, as these +expect continuous input, and would interpret the categories as being ordered, which is often +not desired (i.e. the set of browsers was ordered arbitrarily). + +One possibility to convert categorical features to features that can be used +with scikit-learn estimators is to use a one-of-K or one-hot encoding, which is +implemented in :class:`OneHotEncoder`. This estimator transforms each +categorical feature with ``m`` possible values into ``m`` binary features, with +only one active. + +Continuing the example above:: + + >>> enc = preprocessing.OneHotEncoder() + >>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]]) # doctest: +ELLIPSIS + OneHotEncoder(categorical_features='all', dtype=<... 'float'>, + handle_unknown='error', n_values='auto', sparse=True) + >>> enc.transform([[0, 1, 3]]).toarray() + array([[ 1., 0., 0., 1., 0., 0., 0., 0., 1.]]) + +By default, how many values each feature can take is inferred automatically from the dataset. +It is possible to specify this explicitly using the parameter ``n_values``. +There are two genders, three possible continents and four web browsers in our +dataset. +Then we fit the estimator, and transform a data point. +In the result, the first two numbers encode the gender, the next set of three +numbers the continent and the last four the web browser. + +See :ref:`dict_feature_extraction` for categorical features that are represented +as a dict, not as integers. + +.. _imputation: + +Imputation of missing values +============================ + +For various reasons, many real world datasets contain missing values, often +encoded as blanks, NaNs or other placeholders. Such datasets however are +incompatible with scikit-learn estimators which assume that all values in an +array are numerical, and that all have and hold meaning. A basic strategy to use +incomplete datasets is to discard entire rows and/or columns containing missing +values. However, this comes at the price of losing data which may be valuable +(even though incomplete). A better strategy is to impute the missing values, +i.e., to infer them from the known part of the data. + +The :class:`Imputer` class provides basic strategies for imputing missing +values, either using the mean, the median or the most frequent value of +the row or column in which the missing values are located. This class +also allows for different missing values encodings. + +The following snippet demonstrates how to replace missing values, +encoded as ``np.nan``, using the mean value of the columns (axis 0) +that contain the missing values:: + + >>> import numpy as np + >>> from sklearn.preprocessing import Imputer + >>> imp = Imputer(missing_values='NaN', strategy='mean', axis=0) + >>> imp.fit([[1, 2], [np.nan, 3], [7, 6]]) + Imputer(axis=0, copy=True, missing_values='NaN', strategy='mean', verbose=0) + >>> X = [[np.nan, 2], [6, np.nan], [7, 6]] + >>> print(imp.transform(X)) # doctest: +ELLIPSIS + [[ 4. 2. ] + [ 6. 3.666...] + [ 7. 6. ]] + +The :class:`Imputer` class also supports sparse matrices:: + + >>> import scipy.sparse as sp + >>> X = sp.csc_matrix([[1, 2], [0, 3], [7, 6]]) + >>> imp = Imputer(missing_values=0, strategy='mean', axis=0) + >>> imp.fit(X) + Imputer(axis=0, copy=True, missing_values=0, strategy='mean', verbose=0) + >>> X_test = sp.csc_matrix([[0, 2], [6, 0], [7, 6]]) + >>> print(imp.transform(X_test)) # doctest: +ELLIPSIS + [[ 4. 2. ] + [ 6. 3.666...] + [ 7. 6. ]] + +Note that, here, missing values are encoded by 0 and are thus implicitly stored +in the matrix. This format is thus suitable when there are many more missing +values than observed values. + +:class:`Imputer` can be used in a Pipeline as a way to build a composite +estimator that supports imputation. See :ref:`example_missing_values.py` diff --git a/doc/modules/preprocessing_targets.rst b/doc/modules/preprocessing_targets.rst new file mode 100644 index 0000000000000..88663a55fa0d4 --- /dev/null +++ b/doc/modules/preprocessing_targets.rst @@ -0,0 +1,65 @@ + +.. currentmodule:: sklearn.preprocessing + +.. _preprocessing_targets: + +========================================== +Transforming the prediction target (``y``) +========================================== + +Label binarization +------------------ + +:class:`LabelBinarizer` is a utility class to help create a label indicator +matrix from a list of multi-class labels:: + + >>> from sklearn import preprocessing + >>> lb = preprocessing.LabelBinarizer() + >>> lb.fit([1, 2, 6, 4, 2]) + LabelBinarizer(neg_label=0, pos_label=1, sparse_output=False) + >>> lb.classes_ + array([1, 2, 4, 6]) + >>> lb.transform([1, 6]) + array([[1, 0, 0, 0], + [0, 0, 0, 1]]) + +For multiple labels per instance, use :class:`MultiLabelBinarizer`:: + + >>> lb = preprocessing.MultiLabelBinarizer() + >>> lb.fit_transform([(1, 2), (3,)]) + array([[1, 1, 0], + [0, 0, 1]]) + >>> lb.classes_ + array([1, 2, 3]) + +Label encoding +-------------- + +:class:`LabelEncoder` is a utility class to help normalize labels such that +they contain only values between 0 and n_classes-1. This is sometimes useful +for writing efficient Cython routines. :class:`LabelEncoder` can be used as +follows:: + + >>> from sklearn import preprocessing + >>> le = preprocessing.LabelEncoder() + >>> le.fit([1, 2, 2, 6]) + LabelEncoder() + >>> le.classes_ + array([1, 2, 6]) + >>> le.transform([1, 1, 2, 6]) + array([0, 0, 1, 2]) + >>> le.inverse_transform([0, 0, 1, 2]) + array([1, 1, 2, 6]) + +It can also be used to transform non-numerical labels (as long as they are +hashable and comparable) to numerical labels:: + + >>> le = preprocessing.LabelEncoder() + >>> le.fit(["paris", "paris", "tokyo", "amsterdam"]) + LabelEncoder() + >>> list(le.classes_) + ['amsterdam', 'paris', 'tokyo'] + >>> le.transform(["tokyo", "tokyo", "paris"]) + array([2, 2, 1]) + >>> list(le.inverse_transform([2, 2, 1])) + ['tokyo', 'tokyo', 'paris'] diff --git a/doc/modules/random_projection.rst b/doc/modules/random_projection.rst new file mode 100644 index 0000000000000..e6ef3cb63e02a --- /dev/null +++ b/doc/modules/random_projection.rst @@ -0,0 +1,162 @@ +.. _random_projection: + +================== +Random Projection +================== +.. currentmodule:: sklearn.random_projection + +The :mod:`sklearn.random_projection` module implements a simple and +computationally efficient way to reduce the dimensionality of the data by +trading a controlled amount of accuracy (as additional variance) for faster +processing times and smaller model sizes. This module implements two types of +unstructured random matrix: +:ref:`Gaussian random matrix ` and +:ref:`sparse random matrix `. + +The dimensions and distribution of random projections matrices are +controlled so as to preserve the pairwise distances between any two +samples of the dataset. Thus random projection is a suitable approximation +technique for distance based method. + + +.. topic:: References: + + * Sanjoy Dasgupta. 2000. + `Experiments with random projection. `_ + In Proceedings of the Sixteenth conference on Uncertainty in artificial + intelligence (UAI'00), Craig Boutilier and Moisés Goldszmidt (Eds.). Morgan + Kaufmann Publishers Inc., San Francisco, CA, USA, 143-151. + + * Ella Bingham and Heikki Mannila. 2001. + `Random projection in dimensionality reduction: applications to image and text data. `_ + In Proceedings of the seventh ACM SIGKDD international conference on + Knowledge discovery and data mining (KDD '01). ACM, New York, NY, USA, + 245-250. + + +.. _johnson_lindenstrauss: + +The Johnson-Lindenstrauss lemma +=============================== + +The main theoretical result behind the efficiency of random projection is the +`Johnson-Lindenstrauss lemma (quoting Wikipedia) +`_: + + In mathematics, the Johnson-Lindenstrauss lemma is a result + concerning low-distortion embeddings of points from high-dimensional + into low-dimensional Euclidean space. The lemma states that a small set + of points in a high-dimensional space can be embedded into a space of + much lower dimension in such a way that distances between the points are + nearly preserved. The map used for the embedding is at least Lipschitz, + and can even be taken to be an orthogonal projection. + +Knowing only the number of samples, the +:func:`sklearn.random_projection.johnson_lindenstrauss_min_dim` estimates +conservatively the minimal size of the random subspace to guarantee a +bounded distortion introduced by the random projection:: + + >>> from sklearn.random_projection import johnson_lindenstrauss_min_dim + >>> johnson_lindenstrauss_min_dim(n_samples=1e6, eps=0.5) + 663 + >>> johnson_lindenstrauss_min_dim(n_samples=1e6, eps=[0.5, 0.1, 0.01]) + array([ 663, 11841, 1112658]) + >>> johnson_lindenstrauss_min_dim(n_samples=[1e4, 1e5, 1e6], eps=0.1) + array([ 7894, 9868, 11841]) + +.. figure:: ../auto_examples/images/plot_johnson_lindenstrauss_bound_001.png + :target: ../auto_examples/plot_johnson_lindenstrauss_bound.html + :scale: 75 + :align: center + +.. figure:: ../auto_examples/images/plot_johnson_lindenstrauss_bound_002.png + :target: ../auto_examples/plot_johnson_lindenstrauss_bound.html + :scale: 75 + :align: center + +.. topic:: Example: + + * See :ref:`example_plot_johnson_lindenstrauss_bound.py` + for a theoretical explication on the Johnson-Lindenstrauss lemma and an + empirical validation using sparse random matrices. + +.. topic:: References: + + * Sanjoy Dasgupta and Anupam Gupta, 1999. + `An elementary proof of the Johnson-Lindenstrauss Lemma. + `_ + +.. _gaussian_random_matrix: + +Gaussian random projection +========================== +The :class:`sklearn.random_projection.GaussianRandomProjection` reduces the +dimensionality by projecting the original input space on a randomly generated +matrix where components are drawn from the following distribution +:math:`N(0, \frac{1}{n_{components}})`. + +Here a small excerpt which illustrates how to use the Gaussian random +projection transformer:: + + >>> import numpy as np + >>> from sklearn import random_projection + >>> X = np.random.rand(100, 10000) + >>> transformer = random_projection.GaussianRandomProjection() + >>> X_new = transformer.fit_transform(X) + >>> X_new.shape + (100, 3947) + + +.. _sparse_random_matrix: + +Sparse random projection +======================== +The :class:`sklearn.random_projection.SparseRandomProjection` reduces the +dimensionality by projecting the original input space using a sparse +random matrix. + +Sparse random matrices are an alternative to dense Gaussian random +projection matrix that guarantees similar embedding quality while being much +more memory efficient and allowing faster computation of the projected data. + +If we define ``s = 1 / density``, the elements of the random matrix +are drawn from + +.. math:: + + \left\{ + \begin{array}{c c l} + -\sqrt{\frac{s}{n_{\text{components}}}} & & 1 / 2s\\ + 0 &\text{with probability} & 1 - 1 / s \\ + +\sqrt{\frac{s}{n_{\text{components}}}} & & 1 / 2s\\ + \end{array} + \right. + +where :math:`n_{\text{components}}` is the size of the projected subspace. +By default the density of non zero elements is set to the minimum density as +recommended by Ping Li et al.: :math:`1 / \sqrt{n_{\text{features}}}`. + +Here a small excerpt which illustrates how to use the sparse random +projection transformer:: + + >>> import numpy as np + >>> from sklearn import random_projection + >>> X = np.random.rand(100,10000) + >>> transformer = random_projection.SparseRandomProjection() + >>> X_new = transformer.fit_transform(X) + >>> X_new.shape + (100, 3947) + + +.. topic:: References: + + * D. Achlioptas. 2003. + `Database-friendly random projections: Johnson-Lindenstrauss with binary + coins `_. + Journal of Computer and System Sciences 66 (2003) 671–687 + + * Ping Li, Trevor J. Hastie, and Kenneth W. Church. 2006. + `Very sparse random projections. `_ + In Proceedings of the 12th ACM SIGKDD international conference on + Knowledge discovery and data mining (KDD '06). ACM, New York, NY, USA, + 287-296. diff --git a/doc/modules/scaling_strategies.rst b/doc/modules/scaling_strategies.rst new file mode 100644 index 0000000000000..56f7f5ec8f3b7 --- /dev/null +++ b/doc/modules/scaling_strategies.rst @@ -0,0 +1,125 @@ +.. _scaling_strategies: + +================================================= +Strategies to scale computationally: bigger data +================================================= + +For some applications the amount of examples, features (or both) and/or the +speed at which they need to be processed are challenging for traditional +approaches. In these cases scikit-learn has a number of options you can +consider to make your system scale. + +Scaling with instances using out-of-core learning +================================================= + +Out-of-core (or "external memory") learning is a technique used to learn from +data that cannot fit in a computer's main memory (RAM). + +Here is sketch of a system designed to achieve this goal: + + 1. a way to stream instances + 2. a way to extract features from instances + 3. an incremental algorithm + +Streaming instances +------------------- +Basically, 1. may be a reader that yields instances from files on a +hard drive, a database, from a network stream etc. However, +details on how to achieve this are beyond the scope of this documentation. + +Extracting features +------------------- +\2. could be any relevant way to extract features among the +different :ref:`feature extraction ` methods supported by +scikit-learn. However, when working with data that needs vectorization and +where the set of features or values is not known in advance one should take +explicit care. A good example is text classification where unknown terms are +likely to be found during training. It is possible to use a statefull +vectorizer if making multiple passes over the data is reasonable from an +application point of view. Otherwise, one can turn up the difficulty by using +a stateless feature extractor. Currently the preferred way to do this is to +use the so-called :ref:`hashing trick` as implemented by +:class:`sklearn.feature_extraction.FeatureHasher` for datasets with categorical +variables represented as list of Python dicts or +:class:`sklearn.feature_extraction.text.HashingVectorizer` for text documents. + +Incremental learning +-------------------- +Finally, for 3. we have a number of options inside scikit-learn. Although all +algorithms cannot learn incrementally (i.e. without seeing all the instances +at once), all estimators implementing the ``partial_fit`` API are candidates. +Actually, the ability to learn incrementally from a mini-batch of instances +(sometimes called "online learning") is key to out-of-core learning as it +guarantees that at any given time there will be only a small amount of +instances in the main memory. Choosing a good size for the mini-batch that +balances relevancy and memory footprint could involve some tuning [1]_. + +Here is a list of incremental estimators for different tasks: + + - Classification + + :class:`sklearn.naive_bayes.MultinomialNB` + + :class:`sklearn.naive_bayes.BernoulliNB` + + :class:`sklearn.linear_model.Perceptron` + + :class:`sklearn.linear_model.SGDClassifier` + + :class:`sklearn.linear_model.PassiveAggressiveClassifier` + - Regression + + :class:`sklearn.linear_model.SGDRegressor` + + :class:`sklearn.linear_model.PassiveAggressiveRegressor` + - Clustering + + :class:`sklearn.cluster.MiniBatchKMeans` + - Decomposition / feature Extraction + + :class:`sklearn.decomposition.MiniBatchDictionaryLearning` + + :class:`sklearn.decomposition.IncrementalPCA` + + :class:`sklearn.cluster.MiniBatchKMeans` + +For classification, a somewhat important thing to note is that although a +stateless feature extraction routine may be able to cope with new/unseen +attributes, the incremental learner itself may be unable to cope with +new/unseen targets classes. In this case you have to pass all the possible +classes to the first ``partial_fit`` call using the ``classes=`` parameter. + +Another aspect to consider when choosing a proper algorithm is that all of them +don't put the same importance on each example over time. Namely, the +``Perceptron`` is still sensitive to badly labeled examples even after many +examples whereas the ``SGD*`` and ``PassiveAggressive*`` families are more +robust to this kind of artifacts. Conversely, the later also tend to give less +importance to remarkably different, yet properly labeled examples when they +come late in the stream as their learning rate decreases over time. + +Examples +-------- +Finally, we have a full-fledged example of +:ref:`example_applications_plot_out_of_core_classification.py`. It is aimed at +providing a starting point for people wanting to build out-of-core learning +systems and demonstrates most of the notions discussed above. + +Furthermore, it also shows the evolution of the performance of different +algorithms with the number of processed examples. + +.. |accuracy_over_time| image:: ../auto_examples/applications/images/plot_out_of_core_classification_001.png + :target: ../auto_examples/applications/plot_out_of_core_classification.html + :scale: 80 + +.. centered:: |accuracy_over_time| + +Now looking at the computation time of the different parts, we see that the +vectorization is much more expensive than learning itself. From the different +algorithms, ``MultinomialNB`` is the most expensive, but its overhead can be +mitigated by increasing the size of the mini-batches (exercise: change +``minibatch_size`` to 100 and 10000 in the program and compare). + +.. |computation_time| image:: ../auto_examples/applications/images/plot_out_of_core_classification_003.png + :target: ../auto_examples/applications/plot_out_of_core_classification.html + :scale: 80 + +.. centered:: |computation_time| + + +Notes +----- + +.. [1] Depending on the algorithm the mini-batch size can influence results or + not. SGD*, PassiveAggressive*, and discrete NaiveBayes are truly online + and are not affected by batch size. Conversely, MiniBatchKMeans + convergence rate is affected by the batch size. Also, its memory + footprint can vary dramatically with batch size. diff --git a/doc/modules/sgd.rst b/doc/modules/sgd.rst index c236a7520ff78..f580395f076b5 100644 --- a/doc/modules/sgd.rst +++ b/doc/modules/sgd.rst @@ -1,4 +1,3 @@ - .. _sgd: =========================== @@ -47,7 +46,7 @@ The class :class:`SGDClassifier` implements a plain stochastic gradient descent learning routine which supports different loss functions and penalties for classification. -.. figure:: ../auto_examples/linear_model/images/plot_sgd_separating_hyperplane_1.png +.. figure:: ../auto_examples/linear_model/images/plot_sgd_separating_hyperplane_001.png :target: ../auto_examples/linear_model/plot_sgd_separating_hyperplane.html :align: center :scale: 75 @@ -62,10 +61,11 @@ for the training samples:: >>> y = [0, 1] >>> clf = SGDClassifier(loss="hinge", penalty="l2") >>> clf.fit(X, y) - SGDClassifier(alpha=0.0001, class_weight=None, epsilon=0.1, eta0=0.0, - fit_intercept=True, learning_rate='optimal', loss='hinge', n_iter=5, - n_jobs=1, penalty='l2', power_t=0.5, rho=0.85, seed=0, - shuffle=False, verbose=0, warm_start=False) + SGDClassifier(alpha=0.0001, average=False, class_weight=None, epsilon=0.1, + eta0=0.0, fit_intercept=True, l1_ratio=0.15, + learning_rate='optimal', loss='hinge', n_iter=5, n_jobs=1, + penalty='l2', power_t=0.5, random_state=None, shuffle=True, + verbose=0, warm_start=False) After being fitted, the model can then be used to predict new values:: @@ -76,28 +76,28 @@ After being fitted, the model can then be used to predict new values:: SGD fits a linear model to the training data. The member ``coef_`` holds the model parameters:: - >>> clf.coef_ - array([[ 9.90090187, 9.90090187]]) + >>> clf.coef_ # doctest: +ELLIPSIS + array([[ 9.9..., 9.9...]]) Member ``intercept_`` holds the intercept (aka offset or bias):: >>> clf.intercept_ # doctest: +ELLIPSIS - array([-9.990...]) + array([-9.9...]) Whether or not the model should use an intercept, i.e. a biased hyperplane, is controlled by the parameter ``fit_intercept``. To get the signed distance to the hyperplane use :meth:`SGDClassifier.decision_function`:: - >>> clf.decision_function([[2., 2.]]) - array([ 29.61357756]) + >>> clf.decision_function([[2., 2.]]) # doctest: +ELLIPSIS + array([ 29.6...]) The concrete loss function can be set via the ``loss`` parameter. :class:`SGDClassifier` supports the following loss functions: * ``loss="hinge"``: (soft-margin) linear Support Vector Machine, * ``loss="modified_huber"``: smoothed hinge loss, - * ``loss="log"``: Logistic Regression, + * ``loss="log"``: logistic regression, * and all regression losses below. The first two loss functions are lazy, they only update the model @@ -105,42 +105,44 @@ parameters if an example violates the margin constraint, which makes training very efficient and may result in sparser models, even when L2 penalty is used. -In the case of binary classification and ``loss="log"`` or -``loss="modified_huber"`` you get a probability estimate :math:`P(y=C|x)` using -:meth:`SGDClassifier.predict_proba`, where `C` is the largest class label:: +Using ``loss="log"`` or ``loss="modified_huber"`` enables the +``predict_proba`` method, which gives a vector of probability estimates +:math:`P(y|x)` per sample :math:`x`:: >>> clf = SGDClassifier(loss="log").fit(X, y) - >>> clf.predict_proba([[1., 1.]]) - array([[ 0.00000051, 0.99999949]]) + >>> clf.predict_proba([[1., 1.]]) # doctest: +ELLIPSIS + array([[ 0.00..., 0.99...]]) The concrete penalty can be set via the ``penalty`` parameter. SGD supports the following penalties: * ``penalty="l2"``: L2 norm penalty on ``coef_``. * ``penalty="l1"``: L1 norm penalty on ``coef_``. - * ``penalty="elasticnet"``: Convex combination of L2 and L1; `rho * L2 + (1 - rho) * L1`. + * ``penalty="elasticnet"``: Convex combination of L2 and L1; + ``(1 - l1_ratio) * L2 + l1_ratio * L1``. The default setting is ``penalty="l2"``. The L1 penalty leads to sparse solutions, driving most coefficients to zero. The Elastic Net solves some deficiencies of the L1 penalty in the presence of highly correlated -attributes. The parameter ``rho`` has to be specified by the user. +attributes. The parameter ``l1_ratio`` controls the convex combination +of L1 and L2 penalty. :class:`SGDClassifier` supports multi-class classification by combining multiple binary classifiers in a "one versus all" (OVA) scheme. For each -of the `K` classes, a binary classifier is learned that discriminates -between that and all other `K-1` classes. At testing time, we compute the +of the :math:`K` classes, a binary classifier is learned that discriminates +between that and all other :math:`K-1` classes. At testing time, we compute the confidence score (i.e. the signed distances to the hyperplane) for each classifier and choose the class with the highest confidence. The Figure below illustrates the OVA approach on the iris dataset. The dashed lines represent the three OVA classifiers; the background colors show the decision surface induced by the three classifiers. -.. figure:: ../auto_examples/linear_model/images/plot_sgd_iris_1.png +.. figure:: ../auto_examples/linear_model/images/plot_sgd_iris_001.png :target: ../auto_examples/linear_model/plot_sgd_iris.html :align: center :scale: 75 -In the case of multi-class classification ``coef_`` is a two-dimensionaly +In the case of multi-class classification ``coef_`` is a two-dimensionally array of ``shape=[n_classes, n_features]`` and ``intercept_`` is a one dimensional array of ``shape=[n_classes]``. The i-th row of ``coef_`` holds the weight vector of the OVA classifier for the i-th class; classes are @@ -158,8 +160,14 @@ further information. - :ref:`example_linear_model_plot_sgd_separating_hyperplane.py`, - :ref:`example_linear_model_plot_sgd_iris.py` - - :ref:`example_linear_model_plot_sgd_weighted_classes.py` - :ref:`example_linear_model_plot_sgd_weighted_samples.py` + - :ref:`example_svm_plot_separating_hyperplane_unbalanced.py` (See the `Note`) + +:class:`SGDClassifier` supports averaged SGD (ASGD). Averaging can be enabled +by setting ```average=True```. ASGD works by averaging the coefficients +of the plain SGD over each iteration over a sample. When using ASGD +the learning rate can be larger and even constant leading on some +datasets to a speed up in training time. Regression ========== @@ -171,11 +179,6 @@ well suited for regression problems with a large number of training samples (> 10.000), for other problems we recommend :class:`Ridge`, :class:`Lasso`, or :class:`ElasticNet`. -.. figure:: ../auto_examples/linear_model/images/plot_sgd_ols_1.png - :target: ../auto_examples/linear_model/plot_sgd_ols.html - :align: center - :scale: 75 - The concrete loss function can be set via the ``loss`` parameter. :class:`SGDRegressor` supports the following loss functions: @@ -188,9 +191,8 @@ robust regression. The width of the insensitive region has to be specified via the parameter ``epsilon``. This parameter depends on the scale of the target variables. -.. topic:: Examples: - - - :ref:`example_linear_model_plot_sgd_ols.py`, +:class:`SGDRegressor` supports averaged SGD as :class:`SGDClassifier`. +Averaging can be enabled by setting ```average=True``` Stochastic Gradient Descent for sparse data @@ -207,7 +209,7 @@ matrix format as defined in `scipy.sparse.csr_matrix .. topic:: Examples: - - :ref:`example_document_classification_20newsgroups.py` + - :ref:`example_text_document_classification_20newsgroups.py` Complexity ========== @@ -253,6 +255,8 @@ Tips on Practical Use it is often wise to scale the feature values by some constant `c` such that the average L2 norm of the training data equals one. + * We found that Averaged SGD works best with a larger number of features + and a higher eta0 .. topic:: References: @@ -275,7 +279,7 @@ training error given by .. math:: - E(w,b) = \sum_{i=1}^{n} L(y_i, f(x_i)) + \alpha R(w) + E(w,b) = \frac{1}{n}\sum_{i=1}^{n} L(y_i, f(x_i)) + \alpha R(w) where :math:`L` is a loss function that measures model (mis)fit and :math:`R` is a regularization term (aka penalty) that penalizes model @@ -291,23 +295,25 @@ Different choices for :math:`L` entail different classifiers such as All of the above loss functions can be regarded as an upper bound on the misclassification error (Zero-one loss) as shown in the Figure below. -.. figure:: ../auto_examples/linear_model/images/plot_sgd_loss_functions_1.png - :align: center - :scale: 75 +.. figure:: ../auto_examples/linear_model/images/plot_sgd_loss_functions_001.png + :target: ../auto_examples/linear_model/plot_sgd_loss_functions.html + :align: center + :scale: 75 Popular choices for the regularization term :math:`R` include: - L2 norm: :math:`R(w) := \frac{1}{2} \sum_{i=1}^{n} w_i^2`, - L1 norm: :math:`R(w) := \sum_{i=1}^{n} |w_i|`, which leads to sparse solutions. - - Elastic Net: :math:`R(w) := \rho \frac{1}{2} \sum_{i=1}^{n} w_i^2 + (1-\rho) \sum_{i=1}^{n} |w_i|`, a convex combination of L2 and L1. + - Elastic Net: :math:`R(w) := \frac{\rho}{2} \sum_{i=1}^{n} w_i^2 + (1-\rho) \sum_{i=1}^{n} |w_i|`, a convex combination of L2 and L1, where :math:`\rho` is given by ``1 - l1_ratio``. The Figure below shows the contours of the different regularization terms in the parameter space when :math:`R(w) = 1`. -.. figure:: ../auto_examples/linear_model/images/plot_sgd_penalties_1.png - :align: center - :scale: 75 +.. figure:: ../auto_examples/linear_model/images/plot_sgd_penalties_001.png + :target: ../auto_examples/linear_model/plot_sgd_penalties.html + :align: center + :scale: 75 SGD --- @@ -338,28 +344,28 @@ is given by \eta^{(t)} = \frac {1}{\alpha (t_0 + t)} -where :math:`t` is the time step (there are a total of `n_samples * epochs` +where :math:`t` is the time step (there are a total of `n_samples * n_iter` time steps), :math:`t_0` is determined based on a heuristic proposed by Léon Bottou such that the expected initial updates are comparable with the expected size of the weights (this assuming that the norm of the training samples is approx. 1). The exact definition can be found in ``_init_t`` in :class:`BaseSGD`. -For regression, the default learning rate schedule, inverse scaling -(``learning_rate='invscaling'``), is given by +For regression the default learning rate schedule is inverse scaling +(``learning_rate='invscaling'``), given by .. math:: \eta^{(t)} = \frac{eta_0}{t^{power\_t}} -where :math:`eta_0` and :math:`power\_t` are hyperparameters choosen by the +where :math:`eta_0` and :math:`power\_t` are hyperparameters chosen by the user via ``eta0`` and ``power_t``, resp. For a constant learning rate use ``learning_rate='constant'`` and use ``eta0`` to specify the learning rate. The model parameters can be accessed through the members ``coef_`` and -``intercept\_``: +``intercept_``: - Member ``coef_`` holds the weights :math:`w` @@ -377,6 +383,11 @@ The model parameters can be accessed through the members ``coef_`` and H. Zou, T. Hastie - Journal of the Royal Statistical Society Series B, 67 (2), 301-320. + * `"Towards Optimal One Pass Large Scale Learning with + Averaged Stochastic Gradient Descent" + `_ + Xu, Wei + Implementation details ====================== diff --git a/doc/modules/svm.rst b/doc/modules/svm.rst index 9d4326ce354e2..f1c1f197911b4 100644 --- a/doc/modules/svm.rst +++ b/doc/modules/svm.rst @@ -31,22 +31,16 @@ The disadvantages of support vector machines include: samples, the method is likely to give poor performances. - SVMs do not directly provide probability estimates, these are - calculated using five-fold cross-validation, and thus - performance can suffer. + calculated using an expensive five-fold cross-validation + (see :ref:`Scores and probabilities `, below). -The support vector machines in scikit-learn support both dens +The support vector machines in scikit-learn support both dense (``numpy.ndarray`` and convertible to that by ``numpy.asarray``) and sparse (any ``scipy.sparse``) sample vectors as input. However, to use an SVM to make predictions for sparse data, it must have been fit on such data. For optimal performance, use C-ordered ``numpy.ndarray`` (dense) or ``scipy.sparse.csr_matrix`` (sparse) with ``dtype=float64``. -In previous versions of scikit-learn, sparse input support existed only -in the ``sklearn.svm.sparse`` module which duplicated the ``sklearn.svm`` -interface. This module still exists for backward compatibility, but is -deprecated and will be removed in scikit-learn 0.12. - -.. TODO: add reference to probability estimates .. _svm_classification: @@ -57,7 +51,7 @@ Classification capable of performing multi-class classification on a dataset. -.. figure:: ../auto_examples/svm/images/plot_iris_1.png +.. figure:: ../auto_examples/svm/images/plot_iris_001.png :target: ../auto_examples/svm/plot_iris.html :align: center @@ -67,35 +61,34 @@ slightly different sets of parameters and have different mathematical formulations (see section :ref:`svm_mathematical_formulation`). On the other hand, :class:`LinearSVC` is another implementation of Support Vector Classification for the case of a linear kernel. Note that -:class:`LinearSVC` does not accept keyword 'kernel', as this is +:class:`LinearSVC` does not accept keyword ``kernel``, as this is assumed to be linear. It also lacks some of the members of -:class:`SVC` and :class:`NuSVC`, like support\_. +:class:`SVC` and :class:`NuSVC`, like ``support_``. As other classifiers, :class:`SVC`, :class:`NuSVC` and -:class:`LinearSVC` take as input two arrays: an array X of size -[n_samples, n_features] holding the training samples, and an array Y -of integer values, size [n_samples], holding the class labels for the -training samples:: +:class:`LinearSVC` take as input two arrays: an array X of size ``[n_samples, +n_features]`` holding the training samples, and an array y of class labels +(strings or integers), size ``[n_samples]``:: >>> from sklearn import svm >>> X = [[0, 0], [1, 1]] - >>> Y = [0, 1] + >>> y = [0, 1] >>> clf = svm.SVC() - >>> clf.fit(X, Y) # doctest: +NORMALIZE_WHITESPACE + >>> clf.fit(X, y) # doctest: +NORMALIZE_WHITESPACE SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, - gamma=0.0, kernel='rbf', probability=False, shrinking=True, tol=0.001, - verbose=False) + gamma=0.0, kernel='rbf', max_iter=-1, probability=False, random_state=None, + shrinking=True, tol=0.001, verbose=False) After being fitted, the model can then be used to predict new values:: >>> clf.predict([[2., 2.]]) - array([ 1.]) + array([1]) SVMs decision function depends on some subset of the training data, called the support vectors. Some properties of these support vectors -can be found in members `support_vectors_`, `support_` and -`n_support`:: +can be found in members ``support_vectors_``, ``support_`` and +``n_support``:: >>> # get support vectors >>> clf.support_vectors_ @@ -115,7 +108,7 @@ Multi-class classification :class:`SVC` and :class:`NuSVC` implement the "one-against-one" approach (Knerr et al., 1990) for multi- class classification. If -n_class is the number of classes, then n_class * (n_class - 1)/2 +``n_class`` is the number of classes, then ``n_class * (n_class - 1) / 2`` classifiers are constructed and each one trains data from two classes:: >>> X = [[0], [1], [2], [3]] @@ -123,8 +116,8 @@ classifiers are constructed and each one trains data from two classes:: >>> clf = svm.SVC() >>> clf.fit(X, Y) # doctest: +NORMALIZE_WHITESPACE SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, - gamma=0.0, kernel='rbf', probability=False, shrinking=True, - tol=0.001, verbose=False) + gamma=0.0, kernel='rbf', max_iter=-1, probability=False, random_state=None, + shrinking=True, tol=0.001, verbose=False) >>> dec = clf.decision_function([[1]]) >>> dec.shape[1] # 4 classes: 4*3/2 = 6 6 @@ -136,8 +129,9 @@ two classes, only one model is trained:: >>> lin_clf = svm.LinearSVC() >>> lin_clf.fit(X, Y) # doctest: +NORMALIZE_WHITESPACE LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True, - intercept_scaling=1, loss='l2', multi_class='ovr', penalty='l2', - tol=0.0001, verbose=0) + intercept_scaling=1, loss='squared_hinge', max_iter=1000, + multi_class='ovr', penalty='l2', random_state=None, tol=0.0001, + verbose=0) >>> dec = lin_clf.decision_function([[1]]) >>> dec.shape[1] 4 @@ -147,23 +141,23 @@ the decision function. Note that the :class:`LinearSVC` also implements an alternative multi-class strategy, the so-called multi-class SVM formulated by Crammer and Singer, by -using the option "multi_class='crammer_singer'". This method is consistent, +using the option ``multi_class='crammer_singer'``. This method is consistent, which is not true for one-vs-rest classification. -In practice, on-vs-rest classification is usually preferred, since the results +In practice, one-vs-rest classification is usually preferred, since the results are mostly similar, but the runtime is significantly less. For "one-vs-rest" :class:`LinearSVC` the attributes ``coef_`` and ``intercept_`` have the shape ``[n_class, n_features]`` and ``[n_class]`` respectively. Each row of the coefficients corresponds to one of the ``n_class`` many -"one-vs-rest" classifiers and simliar for the interecepts, in the +"one-vs-rest" classifiers and similar for the intercepts, in the order of the "one" class. In the case of "one-vs-one" :class:`SVC`, the layout of the attributes is a little more involved. In the case of having a linear kernel, The layout of ``coef_`` and ``intercept_`` is similar to the one -described for :class:`LinearSVC` described above, except that -the shape of ``coef_`` is ``[n_class * (n_class - 1) / 2``, -corresponding to as many binary classifiers. The order for classes +described for :class:`LinearSVC` described above, except that the shape of +``coef_`` is ``[n_class * (n_class - 1) / 2, n_features]``, corresponding to as +many binary classifiers. The order for classes 0 to n is "0 vs 1", "0 vs 2" , ... "0 vs n", "1 vs 2", "1 vs 3", "1 vs n", . . . "n-1 vs n". @@ -177,12 +171,12 @@ for these classifiers. This might be made more clear by an example: -Consider a three class problem with with class 0 having 3 support vectors -:math:`v^{0}_0, v^{1}_0, v^{2}_0` and class 1 and 2 having two support -vectors :math:`v^{0}_1, v^{1}_1` and :math:`v^{0}_1, v^{1}_1` respectively. -For each support vector :math:`v^{j}_i`, there are 2 dual coefficients. -Let's call the coefficient of support vector :math:`v^{j}_i` in the -classifier between classes `i` and `k` :math:`\alpha^{j}_{i,k}`. +Consider a three class problem with with class 0 having three support vectors +:math:`v^{0}_0, v^{1}_0, v^{2}_0` and class 1 and 2 having two support vectors +:math:`v^{0}_1, v^{1}_1` and :math:`v^{0}_2, v^{1}_2` respectively. For each +support vector :math:`v^{j}_i`, there are two dual coefficients. Let's call +the coefficient of support vector :math:`v^{j}_i` in the classifier between +classes :math:`i` and :math:`k` :math:`\alpha^{j}_{i,k}`. Then ``dual_coef_`` looks like this: +------------------------+------------------------+------------------+ @@ -202,6 +196,42 @@ Then ``dual_coef_`` looks like this: +------------------------+------------------------+------------------+ +.. _scores_probabilities: + +Scores and probabilities +------------------------ + +The :class:`SVC` method ``decision_function`` gives per-class scores +for each sample (or a single score per sample in the binary case). +When the constructor option ``probability`` is set to ``True``, +class membership probability estimates +(from the methods ``predict_proba`` and ``predict_log_proba``) are enabled. +In the binary case, the probabilities are calibrated using Platt scaling: +logistic regression on the SVM's scores, +fit by an additional cross-validation on the training data. +In the multiclass case, this is extended as per Wu et al. (2004). + +Needless to say, the cross-validation involved in Platt scaling +is an expensive operation for large datasets. +In addition, the probability estimates may be inconsistent with the scores, +in the sense that the "argmax" of the scores +may not be the argmax of the probabilities. +(E.g., in binary classification, +a sample may be labeled by ``predict`` as belonging to a class +that has probability <½ according to ``predict_proba``.) +Platt's method is also known to have theoretical issues. +If confidence scores are required, but these do not have to be probabilities, +then it is advisable to set ``probability=False`` +and use ``decision_function`` instead of ``predict_proba``. + +.. topic:: References: + + * Wu, Lin and Weng, + `"Probability estimates for multi-class classification by pairwise coupling" + `_. + JMLR 5:975-1005, 2004. + + Unbalanced problems -------------------- @@ -210,11 +240,11 @@ classes or certain individual samples keywords ``class_weight`` and ``sample_weight`` can be used. :class:`SVC` (but not :class:`NuSVC`) implement a keyword -``class_weight`` in the fit method. It's a dictionary of the form +``class_weight`` in the ``fit`` method. It's a dictionary of the form ``{class_label : value}``, where value is a floating point number > 0 -that sets the parameter C of class ``class_label`` to C * value. +that sets the parameter ``C`` of class ``class_label`` to ``C * value``. -.. figure:: ../auto_examples/svm/images/plot_separating_hyperplane_unbalanced_1.png +.. figure:: ../auto_examples/svm/images/plot_separating_hyperplane_unbalanced_001.png :target: ../auto_examples/svm/plot_separating_hyperplane_unbalanced.html :align: center :scale: 75 @@ -222,10 +252,11 @@ that sets the parameter C of class ``class_label`` to C * value. :class:`SVC`, :class:`NuSVC`, :class:`SVR`, :class:`NuSVR` and :class:`OneClassSVM` implement also weights for individual samples in method -``fit`` through keyword sample_weight. +``fit`` through keyword ``sample_weight``. Similar to ``class_weight``, these +set the parameter ``C`` for the i-th example to ``C * sample_weight[i]``. -.. figure:: ../auto_examples/svm/images/plot_weighted_samples_1.png +.. figure:: ../auto_examples/svm/images/plot_weighted_samples_001.png :target: ../auto_examples/svm/plot_weighted_samples.html :align: center :scale: 75 @@ -257,8 +288,12 @@ Vector Regression depends only on a subset of the training data, because the cost function for building the model ignores any training data close to the model prediction. -There are two flavors of Support Vector Regression: :class:`SVR` and -:class:`NuSVR`. +There are three different implementations of Support Vector Regression: +:class:`SVR`, :class:`NuSVR` and :class:`LinearSVR`. :class:`LinearSVR` +provides a faster implementation than :class:`SVR` but only considers +linear kernels, while :class:`NuSVR` implements a slightly different +formulation than :class:`SVR` and :class:`LinearSVR`. See +:ref:`svm_implementation_details` for further details. As with classification classes, the fit method will take as argument vectors X, y, only that in this case y is expected to have @@ -269,9 +304,8 @@ floating point values instead of integer values:: >>> y = [0.5, 2.5] >>> clf = svm.SVR() >>> clf.fit(X, y) # doctest: +NORMALIZE_WHITESPACE - SVR(C=1.0, cache_size=200, coef0=0.0, degree=3, - epsilon=0.1, gamma=0.0, kernel='rbf', probability=False, shrinking=True, - tol=0.001, verbose=False) + SVR(C=1.0, cache_size=200, coef0=0.0, degree=3, epsilon=0.1, gamma=0.0, + kernel='rbf', max_iter=-1, shrinking=True, tol=0.001, verbose=False) >>> clf.predict([[1, 1]]) array([ 1.5]) @@ -280,6 +314,8 @@ floating point values instead of integer values:: * :ref:`example_svm_plot_svm_regression.py` + + .. _svm_outlier_detection: Density estimation, novelty detection @@ -295,7 +331,7 @@ will only take as input an array X, as there are no class labels. See, section :ref:`outlier_detection` for more details on this usage. -.. figure:: ../auto_examples/svm/images/plot_oneclass_1.png +.. figure:: ../auto_examples/svm/images/plot_oneclass_001.png :target: ../auto_examples/svm/plot_oneclass.html :align: center :scale: 75 @@ -331,29 +367,31 @@ Tips on Practical Use ===================== - * **Avoiding data copy**: For SVC, SVR, NuSVC and NuSVR, if the data - passed to certain methods is not C-ordered contiguous, and double - precision, it will be copied before calling the underlying C - implementation. You can check whether a give numpy array is - C-contiguous by inspecting its `flags` attribute. - - For LinearSVC (and LogisticRegression) any input passed as a - numpy array will be copied and converted to the liblinear - internal sparse data representation (double precision floats - and int32 indices of non-zero components). If you want to fit - a large-scale linear classifier without copying a dense numpy - C-contiguous double precision array as input we suggest to use - the SGDClassifier class instead. The objective function can be - configured to be almost the same as the LinearSVC model. - - * **Kernel cache size**: For SVC, SVR, nuSVC and NuSVR, the size of - the kernel cache has a strong impact on run times for larger - problems. If you have enough RAM available, it is recommended to - set `cache_size` to a higher value than the default of 200(MB), - such as 500(MB) or 1000(MB). - - * **Setting C**: C is ``1`` by default and it's a reasonable default choice. - If you have a lot of noisy observations you should decrease it. + * **Avoiding data copy**: For :class:`SVC`, :class:`SVR`, :class:`NuSVC` and + :class:`NuSVR`, if the data passed to certain methods is not C-ordered + contiguous, and double precision, it will be copied before calling the + underlying C implementation. You can check whether a give numpy array is + C-contiguous by inspecting its ``flags`` attribute. + + For :class:`LinearSVC` (and :class:`LogisticRegression + `) any input passed as a numpy + array will be copied and converted to the liblinear internal sparse data + representation (double precision floats and int32 indices of non-zero + components). If you want to fit a large-scale linear classifier without + copying a dense numpy C-contiguous double precision array as input we + suggest to use the :class:`SGDClassifier + ` class instead. The objective + function can be configured to be almost the same as the :class:`LinearSVC` + model. + + * **Kernel cache size**: For :class:`SVC`, :class:`SVR`, :class:`nuSVC` and + :class:`NuSVR`, the size of the kernel cache has a strong impact on run + times for larger problems. If you have enough RAM available, it is + recommended to set ``cache_size`` to a higher value than the default of + 200(MB), such as 500(MB) or 1000(MB). + + * **Setting C**: ``C`` is ``1`` by default and it's a reasonable default + choice. If you have a lot of noisy observations you should decrease it. It corresponds to regularize more the estimation. * Support Vector Machine algorithms are not scale invariant, so **it @@ -363,24 +401,24 @@ Tips on Practical Use applied to the test vector to obtain meaningful results. See section :ref:`preprocessing` for more details on scaling and normalization. - * Parameter nu in NuSVC/OneClassSVM/NuSVR approximates the fraction - of training errors and support vectors. + * Parameter ``nu`` in :class:`NuSVC`/:class:`OneClassSVM`/:class:`NuSVR` + approximates the fraction of training errors and support vectors. - * In SVC, if data for classification are unbalanced (e.g. many - positive and few negative), set class_weight='auto' and/or try - different penalty parameters C. + * In :class:`SVC`, if data for classification are unbalanced (e.g. many + positive and few negative), set ``class_weight='auto'`` and/or try + different penalty parameters ``C``. * The underlying :class:`LinearSVC` implementation uses a random number generator to select features when fitting the model. It is thus not uncommon, to have slightly different results for the same input data. If that happens, try with a smaller tol parameter. - * Using L1 penalization as provided by LinearSVC(loss='l2', - penalty='l1', dual=False) yields a sparse solution, i.e. only a subset of - feature weights is different from zero and contribute to the decision - function. Increasing C yields a more complex model (more feature are - selected). The C value that yields a "null" model (all weights equal to - zero) can be calculated using :func:`l1_min_c`. + * Using L1 penalization as provided by ``LinearSVC(loss='l2', penalty='l1', + dual=False)`` yields a sparse solution, i.e. only a subset of feature + weights is different from zero and contribute to the decision function. + Increasing ``C`` yields a more complex model (more feature are selected). + The ``C`` value that yields a "null" model (all weights equal to zero) can + be calculated using :func:`l1_min_c`. .. _svm_kernels: @@ -390,16 +428,16 @@ Kernel functions The *kernel function* can be any of the following: - * linear: :math:``. + * linear: :math:`\langle x, x'\rangle`. - * polynomial: :math:`(\gamma + r)^d`. `d` is specified by - keyword ``degree``, `r` by ``coef0``. + * polynomial: :math:`(\gamma \langle x, x'\rangle + r)^d`. + :math:`d` is specified by keyword ``degree``, :math:`r` by ``coef0``. - * rbf (:math:`\exp(-\gamma |x-x'|^2), \gamma > 0`). :math:`\gamma` is - specified by keyword ``gamma``. + * rbf: :math:`\exp(-\gamma |x-x'|^2)`. :math:`\gamma` is + specified by keyword ``gamma``, must be greater than 0. - * sigmoid (:math:`\tanh( + r)`), where `r` is specified by - ``coef0``. + * sigmoid (:math:`\tanh(\gamma \langle x,x'\rangle + r)`), + where :math:`r` is specified by ``coef0``. Different kernels are specified by keyword kernel at initialization:: @@ -420,20 +458,19 @@ python function or by precomputing the Gram matrix. Classifiers with custom kernels behave the same way as any other classifiers, except that: - * Field `support_vectors\_` is now empty, only indices of support - vectors are stored in `support_` + * Field ``support_vectors_`` is now empty, only indices of support + vectors are stored in ``support_`` - * A reference (and not a copy) of the first argument in the fit() - method is stored for future reference. If that array changes - between the use of fit() and predict() you will have unexpected - results. + * A reference (and not a copy) of the first argument in the ``fit()`` + method is stored for future reference. If that array changes between the + use of ``fit()`` and ``predict()`` you will have unexpected results. -Using python functions as kernels +Using Python functions as kernels ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can also use your own defined kernels by passing a function to the -keyword `kernel` in the constructor. +keyword ``kernel`` in the constructor. Your kernel must take as arguments two matrices and return a third matrix. @@ -454,9 +491,9 @@ instance that will use that kernel:: Using the Gram matrix ~~~~~~~~~~~~~~~~~~~~~ -Set kernel='precomputed' and pass the Gram matrix instead of X in the -fit method. At the moment, the kernel values between `all` training -vectors and the test vectors must be provided. +Set ``kernel='precomputed'`` and pass the Gram matrix instead of X in the fit +method. At the moment, the kernel values between *all* training vectors and the +test vectors must be provided. >>> import numpy as np >>> from sklearn import svm @@ -467,26 +504,25 @@ vectors and the test vectors must be provided. >>> gram = np.dot(X, X.T) >>> clf.fit(gram, y) # doctest: +NORMALIZE_WHITESPACE SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, - gamma=0.0, kernel='precomputed', probability=False, shrinking=True, - tol=0.001, verbose=False) + gamma=0.0, kernel='precomputed', max_iter=-1, probability=False, + random_state=None, shrinking=True, tol=0.001, verbose=False) >>> # predict on training examples >>> clf.predict(gram) - array([ 0., 1.]) + array([0, 1]) Parameters of the RBF Kernel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -When training an SVM with the *Radial Basis Function* (RBF) kernel, -two parameters must be considered: `C` and `gamma`. The parameter `C`, -common to all SVM kernels, trades off misclassification of training -examples against simplicity of the decision surface. A low `C` makes -the decision surface smooth, while a high `C` aims at classifying all -training examples correctly. `gamma` defines how much influence a -single training example has. The larger `gamma` is, the closer other -examples must be to be affected. - -Proper choice of `C` and `gamma` is critical to the SVM's performance. -One is advised to use :class:`GridSearchCV` with `C` and `gamma` spaced +When training an SVM with the *Radial Basis Function* (RBF) kernel, two +parameters must be considered: ``C`` and ``gamma``. The parameter ``C``, +common to all SVM kernels, trades off misclassification of training examples +against simplicity of the decision surface. A low ``C`` makes the decision +surface smooth, while a high ``C`` aims at classifying all training examples +correctly. ``gamma`` defines how much influence a single training example has. +The larger ``gamma`` is, the closer other examples must be to be affected. + +Proper choice of ``C`` and ``gamma`` is critical to the SVM's performance. One +is advised to use :class:`sklearn.grid_search.GridSearchCV` with ``C`` and ``gamma`` spaced exponentially far apart to choose good values. .. topic:: Examples: @@ -507,16 +543,16 @@ margin), since in general the larger the margin the lower the generalization error of the classifier. -.. figure:: ../auto_examples/svm/images/plot_separating_hyperplane_1.png +.. figure:: ../auto_examples/svm/images/plot_separating_hyperplane_001.png :align: center :scale: 75 SVC --- -Given training vectors :math:`x_i \in R^p`, i=1,..., n, in two -classes, and a vector :math:`y \in R^n` such that :math:`y_i \in {1, --1}`, SVC solves the following primal problem: +Given training vectors :math:`x_i \in R^p`, i=1,..., n, in two classes, and a +vector :math:`y \in R^n` such that :math:`y_i \in \{1, -1\}`, SVC solves the +following primal problem: .. math:: @@ -538,29 +574,29 @@ Its dual is \textrm {subject to } & y^T \alpha = 0\\ & 0 \leq \alpha_i \leq C, i=1, ..., l -where :math:`e` is the vector of all ones, C > 0 is the upper bound, Q -is an n by n positive semidefinite matrix, :math:`Q_ij \equiv K(x_i, -x_j)` and :math:`\phi (x_i)^T \phi (x)` is the kernel. Here training -vectors are mapped into a higher (maybe infinite) dimensional space by -the function :math:`\phi`. +where :math:`e` is the vector of all ones, :math:`C > 0` is the upper bound, +:math:`Q` is an :math:`n` by :math:`n` positive semidefinite matrix, +:math:`Q_{ij} \equiv K(x_i, x_j)` and :math:`\phi (x_i)^T \phi (x)` +is the kernel. Here training vectors are mapped into a higher (maybe infinite) +dimensional space by the function :math:`\phi`. The decision function is: -.. math:: sgn(\sum_{i=1}^n y_i \alpha_i K(x_i, x) + \rho) +.. math:: \operatorname{sgn}(\sum_{i=1}^n y_i \alpha_i K(x_i, x) + \rho) .. note:: - While SVM models derived from libsvm and liblinear use *C* as regularization - parameter, most other estimators use *alpha*. The relation between both is - :math:`C = \frac{n_samples}{alpha}`. + While SVM models derived from `libsvm`_ and `liblinear`_ use ``C`` as + regularization parameter, most other estimators use ``alpha``. The relation + between both is :math:`C = \frac{n\_samples}{alpha}`. .. TODO multiclass case ?/ -This parameters can be accessed through the members `dual_coef\_` -which holds the product :math:`y_i \alpha_i`, `support_vectors\_` which -holds the support vectors, and `intercept\_` which holds the independent -term :math:`-\rho` : +This parameters can be accessed through the members ``dual_coef_` +which holds the product :math:`y_i \alpha_i`, ``support_vectors_`` which +holds the support vectors, and ``intercept_`` which holds the independent +term :math:`\rho` : .. topic:: References: @@ -584,9 +620,10 @@ support vectors and training errors. The parameter :math:`\nu \in (0, 1]` is an upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. -It can be shown that the `\nu`-SVC formulation is a reparametrization -of the `C`-SVC and therefore mathematically equivalent. +It can be shown that the :math:`\nu`-SVC formulation is a reparametrization +of the :math:`C`-SVC and therefore mathematically equivalent. +.. _svm_implementation_details: Implementation details ====================== diff --git a/doc/modules/tree.rst b/doc/modules/tree.rst index 5652e978c2be2..7df76f39d0b07 100644 --- a/doc/modules/tree.rst +++ b/doc/modules/tree.rst @@ -16,7 +16,7 @@ For instance, in the example below, decision trees learn from data to approximate a sine curve with a set of if-then-else decision rules. The deeper the tree, the more complex the decision rules and the fitter the model. -.. figure:: ../auto_examples/tree/images/plot_tree_regression_1.png +.. figure:: ../auto_examples/tree/images/plot_tree_regression_001.png :target: ../auto_examples/tree/plot_tree_regression.html :scale: 75 :align: center @@ -42,7 +42,7 @@ Some advantages of decision trees are: - Uses a white box model. If a given situation is observable in a model, the explanation for the condition is easily explained by boolean logic. - By constrast, in a black box model (e.g., in an artificial neural + By contrast, in a black box model (e.g., in an artificial neural network), results may be more difficult to interpret. - Possible to validate a model using statistical tests. That makes it @@ -90,10 +90,10 @@ Classification :class:`DecisionTreeClassifier` is a class capable of performing multi-class classification on a dataset. -As other classifiers, :class:`DecisionTreeClassifier` take as input two -arrays: an array X of size ``[n_samples, n_features]`` holding the training -samples, and an array Y of integer values, size ``[n_samples]``, holding -the class labels for the training samples:: +As other classifiers, :class:`DecisionTreeClassifier` take as input two arrays: +an array X, sparse or dense, of size ``[n_samples, n_features]`` holding the +training samples, and an array Y of integer values, size ``[n_samples]``, +holding the class labels for the training samples:: >>> from sklearn import tree >>> X = [[0, 0], [1, 1]] @@ -101,10 +101,16 @@ the class labels for the training samples:: >>> clf = tree.DecisionTreeClassifier() >>> clf = clf.fit(X, Y) -After being fitted, the model can then be used to predict new values:: +After being fitted, the model can then be used to predict the class of samples:: >>> clf.predict([[2., 2.]]) - array([ 1.]) + array([1]) + +Alternatively, the probability of each class can be predicted, which is the +fraction of training samples of the same class in a leaf:: + + >>> clf.predict_proba([[2., 2.]]) + array([[ 0., 1.]]) :class:`DecisionTreeClassifier` is capable of both binary (where the labels are [-1, 1]) classification and multiclass (where the labels are @@ -123,9 +129,27 @@ Once trained, we can export the tree in `Graphviz exporter. Below is an example export of a tree trained on the entire iris dataset:: - >>> from StringIO import StringIO - >>> out = StringIO() - >>> out = tree.export_graphviz(clf, out_file=out) + >>> from sklearn.externals.six import StringIO + >>> with open("iris.dot", 'w') as f: + ... f = tree.export_graphviz(clf, out_file=f) + +Then we can use Graphviz's ``dot`` tool to create a PDF file (or any other +supported file type): ``dot -Tpdf iris.dot -o iris.pdf``. + +:: + + >>> import os + >>> os.unlink('iris.dot') + +Alternatively, if we have Python module ``pydot`` installed, we can generate +a PDF file (or any other supported file type) directly in Python:: + + >>> from sklearn.externals.six import StringIO # doctest: +SKIP + >>> import pydot # doctest: +SKIP + >>> dot_data = StringIO() # doctest: +SKIP + >>> tree.export_graphviz(clf, out_file=dot_data) # doctest: +SKIP + >>> graph = pydot.graph_from_dot_data(dot_data.getvalue()) # doctest: +SKIP + >>> graph.write_pdf("iris.pdf") # doctest: +SKIP .. only:: html @@ -137,12 +161,18 @@ iris dataset:: .. figure:: ../images/iris.pdf :align: center -After being fitted, the model can then be used to predict new values:: +After being fitted, the model can then be used to predict the class of samples:: - >>> clf.predict(iris.data[0, :]) - array([ 0.]) + >>> clf.predict(iris.data[:1, :]) + array([0]) -.. figure:: ../auto_examples/tree/images/plot_iris_1.png +Alternatively, the probability of each class can be predicted, which is the +fraction of training samples of the same class in a leaf:: + + >>> clf.predict_proba(iris.data[:1, :]) + array([[ 1., 0., 0.]]) + +.. figure:: ../auto_examples/tree/images/plot_iris_001.png :target: ../auto_examples/tree/plot_iris.html :align: center :scale: 75 @@ -157,7 +187,7 @@ After being fitted, the model can then be used to predict new values:: Regression ========== -.. figure:: ../auto_examples/tree/images/plot_tree_regression_1.png +.. figure:: ../auto_examples/tree/images/plot_tree_regression_001.png :target: ../auto_examples/tree/plot_tree_regression.html :scale: 75 :align: center @@ -177,7 +207,6 @@ instead of integer values:: >>> clf.predict([[1, 1]]) array([ 0.5]) - .. topic:: Examples: * :ref:`example_tree_plot_tree_regression.py` @@ -222,29 +251,29 @@ The use of multi-output trees for regression is demonstrated in :ref:`example_tree_plot_tree_regression_multioutput.py`. In this example, the input X is a single real value and the outputs Y are the sine and cosine of X. -.. figure:: ../auto_examples/tree/images/plot_tree_regression_multioutput_1.png +.. figure:: ../auto_examples/tree/images/plot_tree_regression_multioutput_001.png :target: ../auto_examples/tree/plot_tree_regression_multioutput.html :scale: 75 :align: center The use of multi-output trees for classification is demonstrated in -:ref:`example_ensemble_plot_forest_multioutput.py`. In this example, the inputs +:ref:`example_plot_multioutput_face_completion.py`. In this example, the inputs X are the pixels of the upper half of faces and the outputs Y are the pixels of the lower half of those faces. -.. figure:: ../auto_examples/ensemble/images/plot_forest_multioutput_1.png - :target: ../auto_examples/ensemble/plot_forest_multioutput.html +.. figure:: ../auto_examples/images/plot_multioutput_face_completion_001.png + :target: ../auto_examples/plot_multioutput_face_completion.html :scale: 75 :align: center .. topic:: Examples: * :ref:`example_tree_plot_tree_regression_multioutput.py` - * :ref:`example_ensemble_plot_forest_multioutput.py` + * :ref:`example_plot_multioutput_face_completion.py` .. topic:: References: - * M. Dumont et al, `Fast multi-class image annotation with random subwindows + * M. Dumont et al, `Fast multi-class image annotation with random subwindows and multiple output randomized trees `_, International Conference on Computer Vision Theory and Applications 2009 @@ -255,47 +284,23 @@ Complexity ========== In general, the run time cost to construct a balanced binary tree is -:math:`O(n_{samples}n_{features}log(n_{samples}))` and query time -:math:`O(log(n_{samples}))`. Although the tree construction algorithm attempts +:math:`O(n_{samples}n_{features}\log(n_{samples}))` and query time +:math:`O(\log(n_{samples}))`. Although the tree construction algorithm attempts to generate balanced trees, they will not always be balanced. Assuming that the subtrees remain approximately balanced, the cost at each node consists of searching through :math:`O(n_{features})` to find the feature that offers the largest reduction in entropy. This has a cost of -:math:`O(n_{features}n_{samples}log(n_{samples}))` at each node, leading to a +:math:`O(n_{features}n_{samples}\log(n_{samples}))` at each node, leading to a total cost over the entire trees (by summing the cost at each node) of -:math:`O(n_{features}n_{samples}^{2}log(n_{samples}))`. +:math:`O(n_{features}n_{samples}^{2}\log(n_{samples}))`. Scikit-learn offers a more efficient implementation for the construction of decision trees. A naive implementation (as above) would recompute the class label histograms (for classification) or the means (for regression) at for each new split point along a given feature. By presorting the feature over all relevant samples, and retaining a running label count, we reduce the complexity -at each node to :math:`O(n_{features}log(n_{samples}))`, which results in a -total cost of :math:`O(n_{features}n_{samples}log(n_{samples}))`. - -This implementation also offers a parameter `min_density` to control an -optimization heuristic. A sample mask is used to mask data points that are -inactive at a given node, which avoids the copying of data (important for large -datasets or training trees within an ensemble). Density is defined as the ratio -of 'active' data samples to total samples at a given node. The minimum density -parameter specifies the level below which fancy indexing (and therefore data -copied) and the sample mask reset. -If `min_density` is 1, then fancy indexing is always used for data partitioning -during the tree building phase. In this case, the size of memory (as a -proportion of the input data :math:`a`) required at a node of depth :math:`n` -can be approximated using a geometric series: :math:`size = a \frac{1 - r^n}{1 - -r}` where :math:`r` is the ratio of samples used at each node. A best case -analysis shows that the lowest memory requirement (for an infinitely deep tree) -is :math:`2 \times a`, where each partition divides the data in half. A worst -case analysis shows that the memory requirement can increase to :math:`n \times -a`. In practise it usually requires 3 to 4 times :math:`a`. -Setting `min_density` to 0 will always use the sample mask to select the subset -of samples at each node. This results in little to no additional memory being -allocated, making it appropriate for massive datasets or within ensemble -learners. The default value for `min_density` is 0.1 which empirically -leads to fast training for many problems. -Typically high values of ``min_density`` will lead to excessive reallocation, -slowing down the algorithm significantly. +at each node to :math:`O(n_{features}\log(n_{samples}))`, which results in a +total cost of :math:`O(n_{features}n_{samples}\log(n_{samples}))`. Tips on practical use @@ -326,12 +331,30 @@ Tips on practical use create arbitrary small leaves, though ``min_samples_split`` is more common in the literature. - * Balance your dataset before training to prevent the tree from creating - a tree biased toward the classes that are dominant. - - * All decision trees use Fortran ordered ``np.float32`` arrays internally. + * Balance your dataset before training to prevent the tree from being biased + toward the classes that are dominant. Class balancing can be done by + sampling an equal number of samples from each class, or preferably by + normalizing the sum of the sample weights (``sample_weight``) for each + class to the same value. Also note that weight-based pre-pruning criteria, + such as ``min_weight_fraction_leaf``, will then be less biased toward + dominant classes than criteria that are not aware of the sample weights, + like ``min_samples_leaf``. + + * If the samples are weighted, it will be easier to optimize the tree + structure using weight-based pre-pruning criterion such as + ``min_weight_fraction_leaf``, which ensure that leaf nodes contain at least + a fraction of the overall sum of the sample weights. + + * All decision trees use ``np.float32`` arrays internally. If training data is not in this format, a copy of the dataset will be made. + * If the input matrix X is very sparse, it is recommended to convert to sparse + ``csc_matrix` before calling fit and sparse ``csr_matrix`` before calling + predict. Training time can be orders of magnitude faster for a sparse + matrix input compared to a dense matrix when features have zero values in + most of the samples. + + .. _tree_algorithms: @@ -405,11 +428,11 @@ Select the parameters that minimises the impurity .. math:: - \theta^* = argmin_\theta G(Q, \theta) + \theta^* = \operatorname{argmin}_\theta G(Q, \theta) Recurse for subsets :math:`Q_{left}(\theta^*)` and :math:`Q_{right}(\theta^*)` until the maximum allowable depth is reached, -:math:`N_m < min\_samples` or :math:`N_m = 1`. +:math:`N_m < \min_{samples}` or :math:`N_m = 1`. Classification criteria ----------------------- @@ -434,13 +457,13 @@ Cross-Entropy .. math:: - H(X_m) = \sum_k p_{mk} log(p_{mk}) + H(X_m) = \sum_k p_{mk} \log(p_{mk}) and Misclassification .. math:: - H(X_m) = 1 - max(p_{mk}) + H(X_m) = 1 - \max(p_{mk}) Regression criteria ------------------- diff --git a/doc/modules/unsupervised_reduction.rst b/doc/modules/unsupervised_reduction.rst new file mode 100644 index 0000000000000..9eb9da2de1620 --- /dev/null +++ b/doc/modules/unsupervised_reduction.rst @@ -0,0 +1,60 @@ + +.. _data_reduction: + +===================================== +Unsupervised dimensionality reduction +===================================== + +If your number of features is high, it may be useful to reduce it with an +unsupervised step prior to supervised steps. Many of the +:ref:`unsupervised-learning` methods implement a ``transform`` method that +can be used to reduce the dimensionality. Below we discuss two specific +example of this pattern that are heavily used. + +.. topic:: **Pipelining** + + The unsupervised data reduction and the supervised estimator can be + chained in one step. See :ref:`pipeline`. + +.. currentmodule:: sklearn + +PCA: principal component analysis +---------------------------------- + +:class:`decomposition.PCA` looks for a combination of features that +capture well the variance of the original features. See :ref:`decompositions`. + +.. topic:: **Examples** + + * :ref:`example_applications_face_recognition.py` + +Random projections +------------------- + +The module: :mod:`random_projection` provides several tools for data +reduction by random projections. See the relevant section of the +documentation: :ref:`random_projection`. + +.. topic:: **Examples** + + * :ref:`example_plot_johnson_lindenstrauss_bound.py` + +Feature agglomeration +------------------------ + +:class:`cluster.FeatureAgglomeration` applies +:ref:`hierarchical_clustering` to group together features that behave +similarly. + +.. topic:: **Examples** + + * :ref:`example_cluster_plot_feature_agglomeration_vs_univariate_selection.py` + * :ref:`example_cluster_plot_digits_agglomeration.py` + +.. topic:: **Feature scaling** + + Note that if features have very different scaling or statistical + properties, :class:`cluster.FeatureAgglomeration` may not be able to + capture the links between related features. Using a + :class:`preprocessing.StandardScaler` can be useful in these settings. + diff --git a/doc/presentations.rst b/doc/presentations.rst index b593288a1b7ac..4a0c08546e436 100644 --- a/doc/presentations.rst +++ b/doc/presentations.rst @@ -1,15 +1,38 @@ =========================================== -Presentations and Tutorials on Scikit-Learn +External Resources, Videos and Talks =========================================== For written tutorials, see the :ref:`Tutorial section ` of the documentation. +New to Scientific Python? +========================== +For those that are still new to the scientific Python ecosystem, we highly +recommend the `Python Scientific Lecture Notes +`_. This will help you find your footing a +bit and will definitely improve your scikit-learn experience. A basic +understanding of NumPy arrays is recommended to make the most of scikit-learn. + +External Tutorials +=================== + +There are several online tutorials available which are geared toward +specific subject areas: + +- `Machine Learning for NeuroImaging in Python `_ +- `Machine Learning for Astronomical Data Analysis `_ + .. _videos: Videos ====== +- An introduction to scikit-learn `Part + I `_ and + `Part II `_ at Scipy 2013 + by `Gael Varoquaux`_, `Jake Vanderplas`_ and `Olivier Grisel`_. Notebooks on + `github `_. + - `Introduction to scikit-learn `_ by `Gael Varoquaux`_ at ICML 2010 @@ -17,12 +40,11 @@ Videos A three minute video from a very early stage of the scikit, explaining the basic idea and approach we are following. -- `Introduction to statistical learning with scikit - learn `_ by - `Gael Varoquaux`_ at SciPy 2011 +- `Introduction to statistical learning with scikit-learn `_ + by `Gael Varoquaux`_ at SciPy 2011 An extensive tutorial, consisting of four sessions of one hour. - The tutorial covers basics of machine learning, + The tutorial covers the basics of machine learning, many algorithms and how to apply them using scikit-learn. The material corresponding is now in the scikit-learn documentation section :ref:`stat_learn_tut_index`. @@ -39,13 +61,18 @@ Videos - `Introduction to Interactive Predictive Analytics in Python with scikit-learn `_ by `Olivier Grisel`_ at PyCon 2012 - 3-hours long introduction to prediction tasks using the scikit-learn. + 3-hours long introduction to prediction tasks using scikit-learn. - `scikit-learn - Machine Learning in Python `_ by `Jake Vanderplas`_ at the 2012 PyData workshop at Google Interactive demonstration of some scikit-learn features. 75 minutes. +- `scikit-learn tutorial `_ by `Jake Vanderplas`_ at PyData NYC 2012 + + Presentation using the online tutorial, 45 minutes. + + .. _Gael Varoquaux: http://gael-varoquaux.info .. _Jake Vanderplas: http://www.astro.washington.edu/users/vanderplas/ .. _Olivier Grisel: http://twitter.com/ogrisel diff --git a/doc/related_projects.rst b/doc/related_projects.rst new file mode 100644 index 0000000000000..4413fad8dfe41 --- /dev/null +++ b/doc/related_projects.rst @@ -0,0 +1,84 @@ +.. _related_projects: + +===================================== +Related Projects +===================================== + +Below is a list of sister-projects, extensions and domain specific packages. + +Related Packages +---------------- +Other packages useful for data analysis and machine learning. + +- `Pandas `_ Tools for working with heterogeneous and + columnar data, relational queries, time series and basic statistics. + +- `sklearn_pandas `_ bridge for + scikit-learn pipelines and pandas data frame with dedicated transformers. + +- `Scikit-Learn Laboratory + `_ A command-line + wrapper around scikit-learn that makes it easy to run machine learning + experiments with multiple learners and large feature sets. + +- `theano `_ A CPU/GPU array + processing framework geared towards deep learning research. + +- `Statsmodel `_ Estimating and analysing + statistical models. More focused on statistical tests and less on prediction + than scikit-learn. + +- `PyMC `_ Bayesian statistical models and fitting algorithms. + + +Extensions and Algorithms +------------------------- +Libraries that provide a scikit-learn like interface and can be used with +scikit-learn tools. + +- `pylearn2 `_ A deep learning and + neural network library build on theano with scikit-learn like interface. + +- `lightning `_ Fast state-of-the-art + linear model solvers (SDCA, AdaGrad, SVRG, SAG, etc...). + +- `Seqlearn `_ Sequence classification + using HMMs or structured perceptron. + +- `HMMLearn `_ Implementation of hidden + markov models that was previously part of scikit-learn. + +- `PyStruct `_ General conditional random fields + and structured prediction. + +- `py-earth `_ Multivariate adaptive regression splines + +- `sklearn-compiledtrees `_ + Generate a C++ implementation of the predict function for decision trees (and + ensembles) trained by sklearn. Useful for latency-sensitive production + environments. + +- `lda `_: Fast implementation of Latent + Dirichlet Allocation in Cython. + +- `Sparse Filtering `_ + Unsupervised feature learning based on sparse-filtering + +- `Kernel Regression `_ + Implementation of Nadaraya-Watson kernel regression with automatic bandwidth + selection + + +Domain Specific Packages +------------------------- +- `scikit-image `_ Image processing and computer vision in python. +- `Natural language toolkit (nltk) `_ Natual language processing and some machine learning. +- `NiLearn `_ Machine learning for neuro-imaging. +- `AstroML `_ Machine learning for astronomy. +- `MSMBuilder `_ Machine learning for protein conformational dynamics time series. + + + +Snippets and tidbits +--------------------- +The `wiki `_ has more! diff --git a/doc/sphinxext/gen_rst.py b/doc/sphinxext/gen_rst.py index aa77edcd3b397..a3e62e50bdaf0 100644 --- a/doc/sphinxext/gen_rst.py +++ b/doc/sphinxext/gen_rst.py @@ -7,19 +7,67 @@ Files that generate images should start with 'plot' """ +from __future__ import division, print_function from time import time +import ast import os +import re import shutil import traceback import glob import sys -from StringIO import StringIO - -import matplotlib -matplotlib.use('Agg') +import gzip +import posixpath +import subprocess +import warnings +from sklearn.externals import six + + +# Try Python 2 first, otherwise load from Python 3 +try: + from StringIO import StringIO + import cPickle as pickle + import urllib2 as urllib + from urllib2 import HTTPError, URLError +except ImportError: + from io import StringIO + import pickle + import urllib.request + import urllib.error + import urllib.parse + from urllib.error import HTTPError, URLError + + +try: + # Python 2 built-in + execfile +except NameError: + def execfile(filename, global_vars=None, local_vars=None): + with open(filename, encoding='utf-8') as f: + code = compile(f.read(), filename, 'exec') + exec(code, global_vars, local_vars) + +try: + basestring +except NameError: + basestring = str import token import tokenize +import numpy as np + +try: + # make sure that the Agg backend is set before importing any + # matplotlib + import matplotlib + matplotlib.use('Agg') +except ImportError: + # this script can be imported by nosetest to find tests to run: we should not + # impose the matplotlib requirement in that case. + pass + + +from sklearn.externals import joblib ############################################################################### # A tee object to redict streams to multiple outputs @@ -38,6 +86,281 @@ def flush(self): self.file1.flush() self.file2.flush() +############################################################################### +# Documentation link resolver objects + + +def _get_data(url): + """Helper function to get data over http or from a local file""" + if url.startswith('http://'): + # Try Python 2, use Python 3 on exception + try: + resp = urllib.urlopen(url) + encoding = resp.headers.dict.get('content-encoding', 'plain') + except AttributeError: + resp = urllib.request.urlopen(url) + encoding = resp.headers.get('content-encoding', 'plain') + data = resp.read() + if encoding == 'plain': + pass + elif encoding == 'gzip': + data = StringIO(data) + data = gzip.GzipFile(fileobj=data).read() + else: + raise RuntimeError('unknown encoding') + else: + with open(url, 'r') as fid: + data = fid.read() + fid.close() + + return data + +mem = joblib.Memory(cachedir='_build') +get_data = mem.cache(_get_data) + + +def parse_sphinx_searchindex(searchindex): + """Parse a Sphinx search index + + Parameters + ---------- + searchindex : str + The Sphinx search index (contents of searchindex.js) + + Returns + ------- + filenames : list of str + The file names parsed from the search index. + objects : dict + The objects parsed from the search index. + """ + def _select_block(str_in, start_tag, end_tag): + """Select first block delimited by start_tag and end_tag""" + start_pos = str_in.find(start_tag) + if start_pos < 0: + raise ValueError('start_tag not found') + depth = 0 + for pos in range(start_pos, len(str_in)): + if str_in[pos] == start_tag: + depth += 1 + elif str_in[pos] == end_tag: + depth -= 1 + + if depth == 0: + break + sel = str_in[start_pos + 1:pos] + return sel + + def _parse_dict_recursive(dict_str): + """Parse a dictionary from the search index""" + dict_out = dict() + pos_last = 0 + pos = dict_str.find(':') + while pos >= 0: + key = dict_str[pos_last:pos] + if dict_str[pos + 1] == '[': + # value is a list + pos_tmp = dict_str.find(']', pos + 1) + if pos_tmp < 0: + raise RuntimeError('error when parsing dict') + value = dict_str[pos + 2: pos_tmp].split(',') + # try to convert elements to int + for i in range(len(value)): + try: + value[i] = int(value[i]) + except ValueError: + pass + elif dict_str[pos + 1] == '{': + # value is another dictionary + subdict_str = _select_block(dict_str[pos:], '{', '}') + value = _parse_dict_recursive(subdict_str) + pos_tmp = pos + len(subdict_str) + else: + raise ValueError('error when parsing dict: unknown elem') + + key = key.strip('"') + if len(key) > 0: + dict_out[key] = value + + pos_last = dict_str.find(',', pos_tmp) + if pos_last < 0: + break + pos_last += 1 + pos = dict_str.find(':', pos_last) + + return dict_out + + # Make sure searchindex uses UTF-8 encoding + if hasattr(searchindex, 'decode'): + searchindex = searchindex.decode('UTF-8') + + # parse objects + query = 'objects:' + pos = searchindex.find(query) + if pos < 0: + raise ValueError('"objects:" not found in search index') + + sel = _select_block(searchindex[pos:], '{', '}') + objects = _parse_dict_recursive(sel) + + # parse filenames + query = 'filenames:' + pos = searchindex.find(query) + if pos < 0: + raise ValueError('"filenames:" not found in search index') + filenames = searchindex[pos + len(query) + 1:] + filenames = filenames[:filenames.find(']')] + filenames = [f.strip('"') for f in filenames.split(',')] + + return filenames, objects + + +class SphinxDocLinkResolver(object): + """ Resolve documentation links using searchindex.js generated by Sphinx + + Parameters + ---------- + doc_url : str + The base URL of the project website. + searchindex : str + Filename of searchindex, relative to doc_url. + extra_modules_test : list of str + List of extra module names to test. + relative : bool + Return relative links (only useful for links to documentation of this + package). + """ + + def __init__(self, doc_url, searchindex='searchindex.js', + extra_modules_test=None, relative=False): + self.doc_url = doc_url + self.relative = relative + self._link_cache = {} + + self.extra_modules_test = extra_modules_test + self._page_cache = {} + if doc_url.startswith('http://'): + if relative: + raise ValueError('Relative links are only supported for local ' + 'URLs (doc_url cannot start with "http://)/"') + searchindex_url = doc_url + '/' + searchindex + else: + searchindex_url = os.path.join(doc_url, searchindex) + + # detect if we are using relative links on a Windows system + if os.name.lower() == 'nt' and not doc_url.startswith('http://'): + if not relative: + raise ValueError('You have to use relative=True for the local' + ' package on a Windows system.') + self._is_windows = True + else: + self._is_windows = False + + # download and initialize the search index + sindex = get_data(searchindex_url) + filenames, objects = parse_sphinx_searchindex(sindex) + + self._searchindex = dict(filenames=filenames, objects=objects) + + def _get_link(self, cobj): + """Get a valid link, False if not found""" + + fname_idx = None + full_name = cobj['module_short'] + '.' + cobj['name'] + if full_name in self._searchindex['objects']: + value = self._searchindex['objects'][full_name] + if isinstance(value, dict): + value = value[next(iter(value.keys()))] + fname_idx = value[0] + elif cobj['module_short'] in self._searchindex['objects']: + value = self._searchindex['objects'][cobj['module_short']] + if cobj['name'] in value.keys(): + fname_idx = value[cobj['name']][0] + + if fname_idx is not None: + fname = self._searchindex['filenames'][fname_idx] + '.html' + + if self._is_windows: + fname = fname.replace('/', '\\') + link = os.path.join(self.doc_url, fname) + else: + link = posixpath.join(self.doc_url, fname) + + if hasattr(link, 'decode'): + link = link.decode('utf-8', 'replace') + + if link in self._page_cache: + html = self._page_cache[link] + else: + html = get_data(link) + self._page_cache[link] = html + + # test if cobj appears in page + comb_names = [cobj['module_short'] + '.' + cobj['name']] + if self.extra_modules_test is not None: + for mod in self.extra_modules_test: + comb_names.append(mod + '.' + cobj['name']) + url = False + if hasattr(html, 'decode'): + # Decode bytes under Python 3 + html = html.decode('utf-8', 'replace') + + for comb_name in comb_names: + if hasattr(comb_name, 'decode'): + # Decode bytes under Python 3 + comb_name = comb_name.decode('utf-8', 'replace') + if comb_name in html: + url = link + u'#' + comb_name + link = url + else: + link = False + + return link + + def resolve(self, cobj, this_url): + """Resolve the link to the documentation, returns None if not found + + Parameters + ---------- + cobj : dict + Dict with information about the "code object" for which we are + resolving a link. + cobi['name'] : function or class name (str) + cobj['module_short'] : shortened module name (str) + cobj['module'] : module name (str) + this_url: str + URL of the current page. Needed to construct relative URLs + (only used if relative=True in constructor). + + Returns + ------- + link : str | None + The link (URL) to the documentation. + """ + full_name = cobj['module_short'] + '.' + cobj['name'] + link = self._link_cache.get(full_name, None) + if link is None: + # we don't have it cached + link = self._get_link(cobj) + # cache it for the future + self._link_cache[full_name] = link + + if link is False or link is None: + # failed to resolve + return None + + if self.relative: + link = os.path.relpath(link, start=this_url) + if self._is_windows: + # replace '\' with '/' so it on the web + link = link.replace('\\', '/') + + # for some reason, the relative link goes one directory too high up + link = link[3:] + + return link + + ############################################################################### rst_template = """ @@ -67,6 +390,7 @@ def flush(self): :lines: %(end_row)s- **Total running time of the example:** %(time_elapsed) .2f seconds +(%(time_m) .0f minutes %(time_s) .2f seconds) """ # The following strings are used when we have several pictures: we use @@ -89,19 +413,32 @@ def flush(self): :align: center """ +# The following dictionary contains the information used to create the +# thumbnails for the front page of the scikit-learn home page. +# key: first image in set +# values: (number of plot in set, height of thumbnail) +carousel_thumbs = {'plot_classifier_comparison_001.png': (1, 600), + 'plot_outlier_detection_001.png': (3, 372), + 'plot_gp_regression_001.png': (2, 250), + 'plot_adaboost_twoclass_001.png': (1, 372), + 'plot_compare_methods_001.png': (1, 349)} + -def extract_docstring(filename): +def extract_docstring(filename, ignore_heading=False): """ Extract a module-level docstring, if any """ - lines = file(filename).readlines() + if six.PY2: + lines = open(filename).readlines() + else: + lines = open(filename, encoding='utf-8').readlines() start_row = 0 if lines[0].startswith('#!'): lines.pop(0) start_row = 1 - docstring = '' first_par = '' - tokens = tokenize.generate_tokens(iter(lines).next) + line_iterator = iter(lines) + tokens = tokenize.generate_tokens(lambda: next(line_iterator)) for tok_type, tok_content, _, (erow, _), _ in tokens: tok_type = token.tok_name[tok_type] if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'): @@ -110,10 +447,23 @@ def extract_docstring(filename): docstring = eval(tok_content) # If the docstring is formatted with several paragraphs, extract # the first one: - paragraphs = '\n'.join(line.rstrip() - for line in docstring.split('\n')).split('\n\n') - if len(paragraphs) > 0: - first_par = paragraphs[0] + paragraphs = '\n'.join( + line.rstrip() for line + in docstring.split('\n')).split('\n\n') + if paragraphs: + if ignore_heading: + if len(paragraphs) > 1: + first_par = re.sub('\n', ' ', paragraphs[1]) + first_par = ((first_par[:95] + '...') + if len(first_par) > 95 else first_par) + else: + raise ValueError("Docstring not found by gallery.\n" + "Please check the layout of your" + " example file:\n {}\n and make sure" + " it's correct".format(filename)) + else: + first_par = paragraphs[0] + break return docstring, first_par, erow + 1 + start_row @@ -123,7 +473,11 @@ def generate_example_rst(app): examples. """ root_dir = os.path.join(app.builder.srcdir, 'auto_examples') - example_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples') + example_dir = os.path.abspath(os.path.join(app.builder.srcdir, '..', + 'examples')) + generated_dir = os.path.abspath(os.path.join(app.builder.srcdir, + 'modules', 'generated')) + try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: @@ -132,118 +486,321 @@ def generate_example_rst(app): os.makedirs(example_dir) if not os.path.exists(root_dir): os.makedirs(root_dir) + if not os.path.exists(generated_dir): + os.makedirs(generated_dir) # we create an index.rst with all examples - fhindex = file(os.path.join(root_dir, 'index.rst'), 'w') - #Note: The sidebar button has been removed from the examples page for now + fhindex = open(os.path.join(root_dir, 'index.rst'), 'w') + # Note: The sidebar button has been removed from the examples page for now # due to how it messes up the layout. Will be fixed at a later point fhindex.write("""\ + + .. raw:: html - - + + +.. _examples-index: + Examples ======== -.. _examples-index: """) # Here we don't use an os.walk, but we recurse only twice: flat is # better than nested. - generate_dir_rst('.', fhindex, example_dir, root_dir, plot_gallery) - for dir in sorted(os.listdir(example_dir)): - if os.path.isdir(os.path.join(example_dir, dir)): - generate_dir_rst(dir, fhindex, example_dir, root_dir, plot_gallery) + seen_backrefs = set() + generate_dir_rst('.', fhindex, example_dir, root_dir, plot_gallery, seen_backrefs) + for directory in sorted(os.listdir(example_dir)): + if os.path.isdir(os.path.join(example_dir, directory)): + generate_dir_rst(directory, fhindex, example_dir, root_dir, plot_gallery, seen_backrefs) fhindex.flush() -def generate_dir_rst(dir, fhindex, example_dir, root_dir, plot_gallery): +def extract_line_count(filename, target_dir): + # Extract the line count of a file + example_file = os.path.join(target_dir, filename) + if six.PY2: + lines = open(example_file).readlines() + else: + lines = open(example_file, encoding='utf-8').readlines() + start_row = 0 + if lines and lines[0].startswith('#!'): + lines.pop(0) + start_row = 1 + line_iterator = iter(lines) + tokens = tokenize.generate_tokens(lambda: next(line_iterator)) + check_docstring = True + erow_docstring = 0 + for tok_type, _, _, (erow, _), _ in tokens: + tok_type = token.tok_name[tok_type] + if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'): + continue + elif (tok_type == 'STRING') and check_docstring: + erow_docstring = erow + check_docstring = False + return erow_docstring+1+start_row, erow+1+start_row + + +def line_count_sort(file_list, target_dir): + # Sort the list of examples by line-count + new_list = [x for x in file_list if x.endswith('.py')] + unsorted = np.zeros(shape=(len(new_list), 2)) + unsorted = unsorted.astype(np.object) + for count, exmpl in enumerate(new_list): + docstr_lines, total_lines = extract_line_count(exmpl, target_dir) + unsorted[count][1] = total_lines - docstr_lines + unsorted[count][0] = exmpl + index = np.lexsort((unsorted[:, 0].astype(np.str), + unsorted[:, 1].astype(np.float))) + if not len(unsorted): + return [] + return np.array(unsorted[index][:, 0]).tolist() + + +def _thumbnail_div(subdir, full_dir, fname, snippet): + """Generates RST to place a thumbnail in a gallery""" + thumb = os.path.join(full_dir, 'images', 'thumb', fname[:-3] + '.png') + link_name = os.path.join(full_dir, fname).replace(os.path.sep, '_') + ref_name = os.path.join(subdir, fname).replace(os.path.sep, '_') + if ref_name.startswith('._'): + ref_name = ref_name[2:] + out = [] + out.append(""" + +.. raw:: html + + +
+ +""".format(snippet)) + + out.append('.. figure:: %s\n' % thumb) + if link_name.startswith('._'): + link_name = link_name[2:] + if full_dir != '.': + out.append(' :target: ./%s/%s.html\n\n' % (full_dir, fname[:-3])) + else: + out.append(' :target: ./%s.html\n\n' % link_name[:-3]) + out.append(""" :ref:`example_%s` + + +.. raw:: html + +
+ +""" % (ref_name)) + return ''.join(out) + + +def generate_dir_rst(directory, fhindex, example_dir, root_dir, plot_gallery, seen_backrefs): """ Generate the rst file for an example directory. """ - if not dir == '.': - target_dir = os.path.join(root_dir, dir) - src_dir = os.path.join(example_dir, dir) + if not directory == '.': + target_dir = os.path.join(root_dir, directory) + src_dir = os.path.join(example_dir, directory) else: target_dir = root_dir src_dir = example_dir if not os.path.exists(os.path.join(src_dir, 'README.txt')): - print 80 * '_' - print ('Example directory %s does not have a README.txt file' - % src_dir) - print 'Skipping this directory' - print 80 * '_' - return + raise ValueError('Example directory %s does not have a README.txt' % + src_dir) + fhindex.write(""" %s -""" % file(os.path.join(src_dir, 'README.txt')).read()) +""" % open(os.path.join(src_dir, 'README.txt')).read()) if not os.path.exists(target_dir): os.makedirs(target_dir) - - def sort_key(a): - # put last elements without a plot - if not a.startswith('plot') and a.endswith('.py'): - return 'zz' + a - return a - for fname in sorted(os.listdir(src_dir), key=sort_key): + sorted_listdir = line_count_sort(os.listdir(src_dir), + src_dir) + if not os.path.exists(os.path.join(directory, 'images', 'thumb')): + os.makedirs(os.path.join(directory, 'images', 'thumb')) + for fname in sorted_listdir: if fname.endswith('py'): - generate_file_rst(fname, target_dir, src_dir, plot_gallery) - thumb = os.path.join(dir, 'images', 'thumb', fname[:-3] + '.png') - link_name = os.path.join(dir, fname).replace(os.path.sep, '_') - fhindex.write('.. figure:: %s\n' % thumb) - if link_name.startswith('._'): - link_name = link_name[2:] - if dir != '.': - fhindex.write(' :target: ./%s/%s.html\n\n' % (dir, - fname[:-3])) - else: - fhindex.write(' :target: ./%s.html\n\n' % link_name[:-3]) - fhindex.write(""" :ref:`example_%s` + backrefs = generate_file_rst(fname, target_dir, src_dir, root_dir, plot_gallery) + new_fname = os.path.join(src_dir, fname) + _, snippet, _ = extract_docstring(new_fname, True) + fhindex.write(_thumbnail_div(directory, directory, fname, snippet)) + fhindex.write(""" .. toctree:: :hidden: %s/%s -""" % (link_name, dir, fname[:-3])) +""" % (directory, fname[:-3])) + for backref in backrefs: + include_path = os.path.join(root_dir, '../modules/generated/%s.examples' % backref) + seen = backref in seen_backrefs + with open(include_path, 'a' if seen else 'w') as ex_file: + if not seen: + # heading + print(file=ex_file) + print('Examples using ``%s``' % backref, file=ex_file) + print('-----------------%s--' % ('-' * len(backref)), + file=ex_file) + print(file=ex_file) + rel_dir = os.path.join('../../auto_examples', directory) + ex_file.write(_thumbnail_div(directory, rel_dir, fname, snippet)) + seen_backrefs.add(backref) fhindex.write(""" .. raw:: html -
+
""") # clear at the end of the section +# modules for which we embed links into example code +DOCMODULES = ['sklearn', 'matplotlib', 'numpy', 'scipy'] + -def generate_file_rst(fname, target_dir, src_dir, plot_gallery): +def make_thumbnail(in_fname, out_fname, width, height): + """Make a thumbnail with the same aspect ratio centered in an + image with a given width and height + """ + # local import to avoid testing dependency on PIL: + try: + from PIL import Image + except ImportError: + import Image + img = Image.open(in_fname) + width_in, height_in = img.size + scale_w = width / float(width_in) + scale_h = height / float(height_in) + + if height_in * scale_w <= height: + scale = scale_w + else: + scale = scale_h + + width_sc = int(round(scale * width_in)) + height_sc = int(round(scale * height_in)) + + # resize the image + img.thumbnail((width_sc, height_sc), Image.ANTIALIAS) + + # insert centered + thumb = Image.new('RGB', (width, height), (255, 255, 255)) + pos_insert = ((width - width_sc) // 2, (height - height_sc) // 2) + thumb.paste(img, pos_insert) + + thumb.save(out_fname) + # Use optipng to perform lossless compression on the resized image if + # software is installed + if os.environ.get('SKLEARN_DOC_OPTIPNG', False): + try: + subprocess.call(["optipng", "-quiet", "-o", "9", out_fname]) + except Exception: + warnings.warn('Install optipng to reduce the size of the generated images') + + +def get_short_module_name(module_name, obj_name): + """ Get the shortest possible module name """ + parts = module_name.split('.') + short_name = module_name + for i in range(len(parts) - 1, 0, -1): + short_name = '.'.join(parts[:i]) + try: + exec('from %s import %s' % (short_name, obj_name)) + except ImportError: + # get the last working module name + short_name = '.'.join(parts[:(i + 1)]) + break + return short_name + + +class NameFinder(ast.NodeVisitor): + """Finds the longest form of variable names and their imports in code + + Only retains names from imported modules. + """ + + def __init__(self): + super(NameFinder, self).__init__() + self.imported_names = {} + self.accessed_names = set() + + def visit_Import(self, node, prefix=''): + for alias in node.names: + local_name = alias.asname or alias.name + self.imported_names[local_name] = prefix + alias.name + + def visit_ImportFrom(self, node): + self.visit_Import(node, node.module + '.') + + def visit_Name(self, node): + self.accessed_names.add(node.id) + + def visit_Attribute(self, node): + attrs = [] + while isinstance(node, ast.Attribute): + attrs.append(node.attr) + node = node.value + + if isinstance(node, ast.Name): + # This is a.b, not e.g. a().b + attrs.append(node.id) + self.accessed_names.add('.'.join(reversed(attrs))) + else: + # need to get a in a().b + self.visit(node) + + def get_mapping(self): + for name in self.accessed_names: + local_name = name.split('.', 1)[0] + remainder = name[len(local_name):] + if local_name in self.imported_names: + # Join import path to relative path + full_name = self.imported_names[local_name] + remainder + yield name, full_name + + +def identify_names(code): + """Builds a codeobj summary by identifying and resovles used names + + >>> code = ''' + ... from a.b import c + ... import d as e + ... print(c) + ... e.HelloWorld().f.g + ... ''' + >>> for name, o in sorted(identify_names(code).items()): + ... print(name, o['name'], o['module'], o['module_short']) + c c a.b a.b + e.HelloWorld HelloWorld d d + """ + finder = NameFinder() + finder.visit(ast.parse(code)) + + example_code_obj = {} + for name, full_name in finder.get_mapping(): + # name is as written in file (e.g. np.asarray) + # full_name includes resolved import path (e.g. numpy.asarray) + module, attribute = full_name.rsplit('.', 1) + # get shortened module name + module_short = get_short_module_name(module, attribute) + cobj = {'name': attribute, 'module': module, + 'module_short': module_short} + example_code_obj[name] = cobj + return example_code_obj + + +def generate_file_rst(fname, target_dir, src_dir, root_dir, plot_gallery): """ Generate the rst file for a given example. + + Returns the set of sklearn functions/classes imported in the example. """ base_image_name = os.path.splitext(fname)[0] - image_fname = '%s_%%s.png' % base_image_name + image_fname = '%s_%%03d.png' % base_image_name this_template = rst_template last_dir = os.path.split(src_dir)[-1] @@ -270,8 +827,8 @@ def generate_file_rst(fname, target_dir, src_dir, plot_gallery): stdout_path = os.path.join(image_dir, 'stdout_%s.txt' % base_image_name) time_path = os.path.join(image_dir, - 'time_%s.txt' % base_image_name) - thumb_file = os.path.join(thumb_dir, fname[:-3] + '.png') + 'time_%s.txt' % base_image_name) + thumb_file = os.path.join(thumb_dir, base_image_name + '.png') time_elapsed = 0 if plot_gallery and fname.startswith('plot'): # generate the plot as png image if file name @@ -285,11 +842,10 @@ def generate_file_rst(fname, target_dir, src_dir, plot_gallery): if os.path.exists(time_path): time_elapsed = float(open(time_path).read()) - if (not os.path.exists(first_image_file) or - os.stat(first_image_file).st_mtime <= - os.stat(src_file).st_mtime): + if not os.path.exists(first_image_file) or \ + os.stat(first_image_file).st_mtime <= os.stat(src_file).st_mtime: # We need to execute the code - print 'plotting %s' % fname + print('plotting %s' % fname) t0 = time() import matplotlib.pyplot as plt plt.close('all') @@ -307,13 +863,14 @@ def generate_file_rst(fname, target_dir, src_dir, plot_gallery): time_elapsed = time() - t0 sys.stdout = orig_stdout my_stdout = my_buffer.getvalue() + if '__doc__' in my_globals: # The __doc__ is often printed in the example, we # don't with to echo it my_stdout = my_stdout.replace( - my_globals['__doc__'], - '') - my_stdout = my_stdout.strip() + my_globals['__doc__'], + '') + my_stdout = my_stdout.strip().expandtabs() if my_stdout: stdout = '**Script output**::\n\n %s\n\n' % ( '\n '.join(my_stdout.split('\n'))) @@ -327,37 +884,65 @@ def generate_file_rst(fname, target_dir, src_dir, plot_gallery): # incrementally: 1, 2, 3 and not 1, 2, 5) # * iterate over [fig_mngr.num for fig_mngr in # matplotlib._pylab_helpers.Gcf.get_all_fig_managers()] - for fig_num in (fig_mngr.num for fig_mngr in - matplotlib._pylab_helpers.Gcf.get_all_fig_managers()): + fig_managers = matplotlib._pylab_helpers.Gcf.get_all_fig_managers() + for fig_mngr in fig_managers: # Set the fig_num figure as the current figure as we can't # save a figure that's not the current figure. - plt.figure(fig_num) - plt.savefig(image_path % fig_num) - figure_list.append(image_fname % fig_num) + fig = plt.figure(fig_mngr.num) + kwargs = {} + to_rgba = matplotlib.colors.colorConverter.to_rgba + for attr in ['facecolor', 'edgecolor']: + fig_attr = getattr(fig, 'get_' + attr)() + default_attr = matplotlib.rcParams['figure.' + attr] + if to_rgba(fig_attr) != to_rgba(default_attr): + kwargs[attr] = fig_attr + + fig.savefig(image_path % fig_mngr.num, **kwargs) + figure_list.append(image_fname % fig_mngr.num) except: - print 80 * '_' - print '%s is not compiling:' % fname + print(80 * '_') + print('%s is not compiling:' % fname) traceback.print_exc() - print 80 * '_' + print(80 * '_') finally: os.chdir(cwd) sys.stdout = orig_stdout - - print " - time elapsed : %.2g sec" % time_elapsed + + print(" - time elapsed : %.2g sec" % time_elapsed) else: figure_list = [f[len(image_dir):] - for f in glob.glob(image_path % '[1-9]')] - #for f in glob.glob(image_path % '*')] + for f in glob.glob(image_path.replace("%03d", + '[0-9][0-9][0-9]'))] + figure_list.sort() # generate thumb file this_template = plot_rst_template - from matplotlib import image + car_thumb_path = os.path.join(os.path.split(root_dir)[0], '_build/html/stable/_images/') + # Note: normaly, make_thumbnail is used to write to the path contained in `thumb_file` + # which is within `auto_examples/../images/thumbs` depending on the example. + # Because the carousel has different dimensions than those of the examples gallery, + # I did not simply reuse them all as some contained whitespace due to their default gallery + # thumbnail size. Below, for a few cases, seperate thumbnails are created (the originals can't + # just be overwritten with the carousel dimensions as it messes up the examples gallery layout). + # The special carousel thumbnails are written directly to _build/html/stable/_images/, + # as for some reason unknown to me, Sphinx refuses to copy my 'extra' thumbnails from the + # auto examples gallery to the _build folder. This works fine as is, but it would be cleaner to + # have it happen with the rest. Ideally the should be written to 'thumb_file' as well, and then + # copied to the _images folder during the `Copying Downloadable Files` step like the rest. + if not os.path.exists(car_thumb_path): + os.makedirs(car_thumb_path) if os.path.exists(first_image_file): - image.thumbnail(first_image_file, thumb_file, 0.2) + # We generate extra special thumbnails for the carousel + carousel_tfile = os.path.join(car_thumb_path, base_image_name + '_carousel.png') + first_img = image_fname % 1 + if first_img in carousel_thumbs: + make_thumbnail((image_path % carousel_thumbs[first_img][0]), + carousel_tfile, carousel_thumbs[first_img][1], 190) + make_thumbnail(first_image_file, thumb_file, 400, 280) if not os.path.exists(thumb_file): - # create something not to replace the thumbnail - shutil.copy('images/blank_image.png', thumb_file) + # create something to replace the thumbnail + make_thumbnail('images/no_image.png', thumb_file, 200, 140) docstring, short_desc, end_row = extract_docstring(example_file) @@ -371,15 +956,134 @@ def generate_file_rst(fname, target_dir, src_dir, plot_gallery): for figure_name in figure_list: image_list += HLIST_IMAGE_TEMPLATE % figure_name.lstrip('/') - f = open(os.path.join(target_dir, fname[:-2] + 'rst'), 'w') + time_m, time_s = divmod(time_elapsed, 60) + f = open(os.path.join(target_dir, base_image_name + '.rst'), 'w') f.write(this_template % locals()) f.flush() + # save variables so we can later add links to the documentation + if six.PY2: + example_code_obj = identify_names(open(example_file).read()) + else: + example_code_obj = \ + identify_names(open(example_file, encoding='utf-8').read()) + if example_code_obj: + codeobj_fname = example_file[:-3] + '_codeobj.pickle' + with open(codeobj_fname, 'wb') as fid: + pickle.dump(example_code_obj, fid, pickle.HIGHEST_PROTOCOL) + + backrefs = set('{module_short}.{name}'.format(**entry) + for entry in example_code_obj.values() + if entry['module'].startswith('sklearn')) + return backrefs + + +def embed_code_links(app, exception): + """Embed hyperlinks to documentation into example code""" + if exception is not None: + return + print('Embedding documentation hyperlinks in examples..') + + if app.builder.name == 'latex': + # Don't embed hyperlinks when a latex builder is used. + return + + # Add resolvers for the packages for which we want to show links + doc_resolvers = {} + doc_resolvers['sklearn'] = SphinxDocLinkResolver(app.builder.outdir, + relative=True) + + resolver_urls = { + 'matplotlib': 'http://matplotlib.org/', + 'numpy': 'http://docs.scipy.org/doc/numpy-1.6.0', + 'scipy': 'http://docs.scipy.org/doc/scipy-0.11.0/reference', + } + for this_module, url in resolver_urls.items(): + try: + doc_resolvers[this_module] = SphinxDocLinkResolver(url) + except HTTPError as e: + print("The following HTTP Error has occurred:\n") + print(e.code) + except URLError as e: + print("\n...\n" + "Warning: Embedding the documentation hyperlinks requires " + "internet access.\nPlease check your network connection.\n" + "Unable to continue embedding `{0}` links due to a URL " + "Error:\n".format(this_module)) + print(e.args) + + example_dir = os.path.join(app.builder.srcdir, 'auto_examples') + html_example_dir = os.path.abspath(os.path.join(app.builder.outdir, + 'auto_examples')) + + # patterns for replacement + link_pattern = '%s' + orig_pattern = '%s' + period = '.' + + for dirpath, _, filenames in os.walk(html_example_dir): + for fname in filenames: + print('\tprocessing: %s' % fname) + full_fname = os.path.join(html_example_dir, dirpath, fname) + subpath = dirpath[len(html_example_dir) + 1:] + pickle_fname = os.path.join(example_dir, subpath, + fname[:-5] + '_codeobj.pickle') + + if os.path.exists(pickle_fname): + # we have a pickle file with the objects to embed links for + with open(pickle_fname, 'rb') as fid: + example_code_obj = pickle.load(fid) + fid.close() + str_repl = {} + # generate replacement strings with the links + for name, cobj in example_code_obj.items(): + this_module = cobj['module'].split('.')[0] + + if this_module not in doc_resolvers: + continue + + try: + link = doc_resolvers[this_module].resolve(cobj, + full_fname) + except (HTTPError, URLError) as e: + print("The following error has occurred:\n") + print(repr(e)) + continue + + if link is not None: + parts = name.split('.') + name_html = period.join(orig_pattern % part + for part in parts) + str_repl[name_html] = link_pattern % (link, name_html) + # do the replacement in the html file + + # ensure greediness + names = sorted(str_repl, key=len, reverse=True) + expr = re.compile(r'(? 0: + with open(full_fname, 'rb') as fid: + lines_in = fid.readlines() + with open(full_fname, 'wb') as fid: + for line in lines_in: + line = line.decode('utf-8') + line = expr.sub(substitute_link, line) + fid.write(line.encode('utf-8')) + print('[done]') + def setup(app): app.connect('builder-inited', generate_example_rst) app.add_config_value('plot_gallery', True, 'html') + # embed links after build is finished + app.connect('build-finished', embed_code_links) + # Sphinx hack: sphinx copies generated images to the build directory # each time the docs are made. If the desired image name already # exists, it appends a digit to prevent overwrites. The problem is, @@ -400,3 +1104,8 @@ def setup(app): for filename in filelist: if filename.endswith('png'): os.remove(os.path.join(build_image_dir, filename)) + + +def setup_module(): + # HACK: Stop nosetests running setup() above + pass diff --git a/doc/sphinxext/github_link.py b/doc/sphinxext/github_link.py new file mode 100644 index 0000000000000..ba0dd434e6ff6 --- /dev/null +++ b/doc/sphinxext/github_link.py @@ -0,0 +1,84 @@ +from operator import attrgetter +import inspect +import subprocess +import os +import sys +from functools import partial + +REVISION_CMD = 'git rev-parse --short HEAD' + + +def _get_git_revision(): + try: + revision = subprocess.check_output(REVISION_CMD.split()).strip() + except subprocess.CalledProcessError: + print('Failed to execute git to get revision') + return None + return revision.decode('utf-8') + + +def _linkcode_resolve(domain, info, package, url_fmt, revision): + """Determine a link to online source for a class/method/function + + This is called by sphinx.ext.linkcode + + An example with a long-untouched module that everyone has + >>> _linkcode_resolve('py', {'module': 'tty', + ... 'fullname': 'setraw'}, + ... package='tty', + ... url_fmt='http://hg.python.org/cpython/file/' + ... '{revision}/Lib/{package}/{path}#L{lineno}', + ... revision='xxxx') + 'http://hg.python.org/cpython/file/xxxx/Lib/tty/tty.py#L18' + """ + + if revision is None: + return + if domain not in ('py', 'pyx'): + return + if not info.get('module') or not info.get('fullname'): + return + + class_name = info['fullname'].split('.')[0] + if type(class_name) != str: + # Python 2 only + class_name = class_name.encode('utf-8') + module = __import__(info['module'], fromlist=[class_name]) + obj = attrgetter(info['fullname'])(module) + + try: + fn = inspect.getsourcefile(obj) + except Exception: + fn = None + if not fn: + try: + fn = inspect.getsourcefile(sys.modules[obj.__module__]) + except Exception: + fn = None + if not fn: + return + + fn = os.path.relpath(fn, + start=os.path.dirname(__import__(package).__file__)) + try: + lineno = inspect.getsourcelines(obj)[1] + except Exception: + lineno = '' + return url_fmt.format(revision=revision, package=package, + path=fn, lineno=lineno) + + +def make_linkcode_resolve(package, url_fmt): + """Returns a linkcode_resolve function for the given URL format + + revision is a git commit reference (hash or name) + + package is the name of the root module of the package + + url_fmt is along the lines of ('https://github.com/USER/PROJECT/' + 'blob/{revision}/{package}/' + '{path}#L{lineno}') + """ + revision = _get_git_revision() + return partial(_linkcode_resolve, revision=revision, package=package, + url_fmt=url_fmt) diff --git a/doc/sphinxext/numpy_ext/docscrape.py b/doc/sphinxext/numpy_ext/docscrape.py index e9670c05f5a63..84caa064b3edc 100644 --- a/doc/sphinxext/numpy_ext/docscrape.py +++ b/doc/sphinxext/numpy_ext/docscrape.py @@ -6,8 +6,12 @@ import textwrap import re import pydoc -from StringIO import StringIO from warnings import warn +# Try Python 2 first, otherwise load from Python 3 +try: + from StringIO import StringIO +except: + from io import StringIO class Reader(object): @@ -115,7 +119,7 @@ def __getitem__(self, key): return self._parsed_data[key] def __setitem__(self, key, val): - if not self._parsed_data.has_key(key): + if key not in self._parsed_data: warn("Unknown section %s" % key) else: self._parsed_data[key] = val @@ -435,7 +439,7 @@ def __init__(self, func, role='func', doc=None, config={}): argspec = inspect.formatargspec(*argspec) argspec = argspec.replace('*', '\*') signature = '%s%s' % (func_name, argspec) - except TypeError, e: + except TypeError as e: signature = '%s()' % func_name self['Signature'] = signature @@ -458,7 +462,7 @@ def __str__(self): if self._role: if not roles.has_key(self._role): - print "Warning: invalid role %s" % self._role + print("Warning: invalid role %s" % self._role) out += '.. %s:: %s\n \n\n' % (roles.get(self._role, ''), func_name) diff --git a/doc/sphinxext/numpy_ext/docscrape_sphinx.py b/doc/sphinxext/numpy_ext/docscrape_sphinx.py index bcf7e70731cc7..ca28300eab8a4 100644 --- a/doc/sphinxext/numpy_ext/docscrape_sphinx.py +++ b/doc/sphinxext/numpy_ext/docscrape_sphinx.py @@ -2,10 +2,9 @@ import inspect import textwrap import pydoc -import sphinx -from docscrape import NumpyDocString -from docscrape import FunctionDoc -from docscrape import ClassDoc +from .docscrape import NumpyDocString +from .docscrape import FunctionDoc +from .docscrape import ClassDoc class SphinxDocString(NumpyDocString): @@ -156,6 +155,7 @@ def _str_references(self): out += [''] # Latex collects all references to a separate bibliography, # so we need to insert links to it + import sphinx # local import to avoid test dependency if sphinx.__version__ >= "0.6": out += ['.. only:: latex', ''] else: @@ -188,14 +188,14 @@ def __str__(self, indent=0, func_role="obj"): out += self._str_index() + [''] out += self._str_summary() out += self._str_extended_summary() - for param_list in ('Parameters', 'Returns', 'Raises'): + for param_list in ('Parameters', 'Returns', 'Raises', 'Attributes'): out += self._str_param_list(param_list) out += self._str_warnings() out += self._str_see_also(func_role) out += self._str_section('Notes') out += self._str_references() out += self._str_examples() - for param_list in ('Attributes', 'Methods'): + for param_list in ('Methods',): out += self._str_member_list(param_list) out = self._str_indent(out, indent) return '\n'.join(out) diff --git a/doc/sphinxext/numpy_ext/numpydoc.py b/doc/sphinxext/numpy_ext/numpydoc.py index 62adb56ae7489..6ff03e0d7e593 100644 --- a/doc/sphinxext/numpy_ext/numpydoc.py +++ b/doc/sphinxext/numpy_ext/numpydoc.py @@ -17,12 +17,14 @@ """ +from __future__ import unicode_literals + +import sys # Only needed to check Python version import os import re import pydoc -from docscrape_sphinx import get_doc_object -from docscrape_sphinx import SphinxDocString -from sphinx.util.compat import Directive +from .docscrape_sphinx import get_doc_object +from .docscrape_sphinx import SphinxDocString import inspect @@ -34,17 +36,20 @@ def mangle_docstrings(app, what, name, obj, options, lines, if what == 'module': # Strip top title - title_re = re.compile(ur'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*', + title_re = re.compile(r'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*', re.I | re.S) - lines[:] = title_re.sub(u'', u"\n".join(lines)).split(u"\n") + lines[:] = title_re.sub('', "\n".join(lines)).split("\n") else: - doc = get_doc_object(obj, what, u"\n".join(lines), config=cfg) - lines[:] = unicode(doc).split(u"\n") + doc = get_doc_object(obj, what, "\n".join(lines), config=cfg) + if sys.version_info[0] < 3: + lines[:] = unicode(doc).splitlines() + else: + lines[:] = str(doc).splitlines() if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \ obj.__name__: if hasattr(obj, '__module__'): - v = dict(full_name=u"%s.%s" % (obj.__module__, obj.__name__)) + v = dict(full_name="%s.%s" % (obj.__module__, obj.__name__)) else: v = dict(full_name=obj.__name__) lines += [u'', u'.. htmlonly::', ''] @@ -55,7 +60,7 @@ def mangle_docstrings(app, what, name, obj, options, lines, references = [] for line in lines: line = line.strip() - m = re.match(ur'^.. \[([a-z0-9_.-])\]', line, re.I) + m = re.match(r'^.. \[([a-z0-9_.-])\]', line, re.I) if m: references.append(m.group(1)) @@ -64,8 +69,8 @@ def mangle_docstrings(app, what, name, obj, options, lines, if references: for i, line in enumerate(lines): for r in references: - if re.match(ur'^\d+$', r): - new_r = u"R%d" % (reference_offset[0] + int(r)) + if re.match(r'^\d+$', r): + new_r = "R%d" % (reference_offset[0] + int(r)) else: new_r = u"%s%d" % (r, reference_offset[0]) lines[i] = lines[i].replace(u'[%s]_' % r, @@ -91,16 +96,20 @@ def mangle_signature(app, what, name, obj, doc = SphinxDocString(pydoc.getdoc(obj)) if doc['Signature']: - sig = re.sub(u"^[^(]*", u"", doc['Signature']) - return sig, u'' + sig = re.sub("^[^(]*", "", doc['Signature']) + return sig, '' def setup(app, get_doc_object_=get_doc_object): global get_doc_object get_doc_object = get_doc_object_ - app.connect('autodoc-process-docstring', mangle_docstrings) - app.connect('autodoc-process-signature', mangle_signature) + if sys.version_info[0] < 3: + app.connect(b'autodoc-process-docstring', mangle_docstrings) + app.connect(b'autodoc-process-signature', mangle_signature) + else: + app.connect('autodoc-process-docstring', mangle_docstrings) + app.connect('autodoc-process-signature', mangle_signature) app.add_config_value('numpydoc_edit_link', None, False) app.add_config_value('numpydoc_use_plots', None, False) app.add_config_value('numpydoc_show_class_members', True, True) @@ -113,9 +122,13 @@ def setup(app, get_doc_object_=get_doc_object): # Docstring-mangling domains #----------------------------------------------------------------------------- -from docutils.statemachine import ViewList -from sphinx.domains.c import CDomain -from sphinx.domains.python import PythonDomain +try: + import sphinx # lazy to avoid test dependency +except ImportError: + CDomain = PythonDomain = object +else: + from sphinx.domains.c import CDomain + from sphinx.domains.python import PythonDomain class ManglingDomainBase(object): @@ -170,6 +183,8 @@ def run(self): lines = list(self.content) mangle_docstrings(env.app, objtype, name, None, None, lines) + # local import to avoid testing dependency + from docutils.statemachine import ViewList self.content = ViewList(lines, self.content.parent) return base_directive.run(self) diff --git a/doc/sphinxext/numpy_ext_old/docscrape.py b/doc/sphinxext/numpy_ext_old/docscrape.py deleted file mode 100644 index 5eecdde36d79d..0000000000000 --- a/doc/sphinxext/numpy_ext_old/docscrape.py +++ /dev/null @@ -1,498 +0,0 @@ -"""Extract reference documentation from the NumPy source tree. - -""" - -import inspect -import textwrap -import re -import pydoc -from StringIO import StringIO -from warnings import warn - - -class Reader(object): - """A line-based string reader. - - """ - def __init__(self, data): - """ - Parameters - ---------- - data : str - String with lines separated by '\n'. - - """ - if isinstance(data, list): - self._str = data - else: - self._str = data.split('\n') # store string as list of lines - - self.reset() - - def __getitem__(self, n): - return self._str[n] - - def reset(self): - self._l = 0 # current line nr - - def read(self): - if not self.eof(): - out = self[self._l] - self._l += 1 - return out - else: - return '' - - def seek_next_non_empty_line(self): - for l in self[self._l:]: - if l.strip(): - break - else: - self._l += 1 - - def eof(self): - return self._l >= len(self._str) - - def read_to_condition(self, condition_func): - start = self._l - for line in self[start:]: - if condition_func(line): - return self[start:self._l] - self._l += 1 - if self.eof(): - return self[start: self._l + 1] - return [] - - def read_to_next_empty_line(self): - self.seek_next_non_empty_line() - - def is_empty(line): - return not line.strip() - return self.read_to_condition(is_empty) - - def read_to_next_unindented_line(self): - def is_unindented(line): - return (line.strip() and (len(line.lstrip()) == len(line))) - return self.read_to_condition(is_unindented) - - def peek(self, n=0): - if self._l + n < len(self._str): - return self[self._l + n] - else: - return '' - - def is_empty(self): - return not ''.join(self._str).strip() - - -class NumpyDocString(object): - def __init__(self, docstring): - docstring = textwrap.dedent(docstring).split('\n') - - self._doc = Reader(docstring) - self._parsed_data = { - 'Signature': '', - 'Summary': [''], - 'Extended Summary': [], - 'Parameters': [], - 'Returns': [], - 'Raises': [], - 'Warns': [], - 'Other Parameters': [], - 'Attributes': [], - 'Methods': [], - 'See Also': [], - 'Notes': [], - 'Warnings': [], - 'References': '', - 'Examples': '', - 'index': {} - } - - self._parse() - - def __getitem__(self, key): - return self._parsed_data[key] - - def __setitem__(self, key, val): - if not self._parsed_data.has_key(key): - warn("Unknown section %s" % key) - else: - self._parsed_data[key] = val - - def _is_at_section(self): - self._doc.seek_next_non_empty_line() - - if self._doc.eof(): - return False - - l1 = self._doc.peek().strip() # e.g. Parameters - - if l1.startswith('.. index::'): - return True - - l2 = self._doc.peek(1).strip() # ---------- or ========== - return l2.startswith('-' * len(l1)) or l2.startswith('=' * len(l1)) - - def _strip(self, doc): - i = 0 - j = 0 - for i, line in enumerate(doc): - if line.strip(): - break - - for j, line in enumerate(doc[::-1]): - if line.strip(): - break - - return doc[i: len(doc) - j] - - def _read_to_next_section(self): - section = self._doc.read_to_next_empty_line() - - while not self._is_at_section() and not self._doc.eof(): - if not self._doc.peek(-1).strip(): # previous line was empty - section += [''] - - section += self._doc.read_to_next_empty_line() - - return section - - def _read_sections(self): - while not self._doc.eof(): - data = self._read_to_next_section() - name = data[0].strip() - - if name.startswith('..'): # index section - yield name, data[1:] - elif len(data) < 2: - yield StopIteration - else: - yield name, self._strip(data[2:]) - - def _parse_param_list(self, content): - r = Reader(content) - params = [] - while not r.eof(): - header = r.read().strip() - if ' : ' in header: - arg_name, arg_type = header.split(' : ')[:2] - else: - arg_name, arg_type = header, '' - - desc = r.read_to_next_unindented_line() - desc = dedent_lines(desc) - - params.append((arg_name, arg_type, desc)) - - return params - - _name_rgx = re.compile(r"^\s*(:(?P\w+):`(?P[a-zA-Z0-9_.-]+)`|" - r" (?P[a-zA-Z0-9_.-]+))\s*", re.X) - - def _parse_see_also(self, content): - """ - func_name : Descriptive text - continued text - another_func_name : Descriptive text - func_name1, func_name2, :meth:`func_name`, func_name3 - - """ - items = [] - - def parse_item_name(text): - """Match ':role:`name`' or 'name'""" - m = self._name_rgx.match(text) - if m: - g = m.groups() - if g[1] is None: - return g[3], None - else: - return g[2], g[1] - raise ValueError("%s is not a item name" % text) - - def push_item(name, rest): - if not name: - return - name, role = parse_item_name(name) - items.append((name, list(rest), role)) - del rest[:] - - current_func = None - rest = [] - - for line in content: - if not line.strip(): - continue - - m = self._name_rgx.match(line) - if m and line[m.end():].strip().startswith(':'): - push_item(current_func, rest) - current_func, line = line[:m.end()], line[m.end():] - rest = [line.split(':', 1)[1].strip()] - if not rest[0]: - rest = [] - elif not line.startswith(' '): - push_item(current_func, rest) - current_func = None - if ',' in line: - for func in line.split(','): - push_item(func, []) - elif line.strip(): - current_func = line - elif current_func is not None: - rest.append(line.strip()) - push_item(current_func, rest) - return items - - def _parse_index(self, section, content): - """ - .. index: default - :refguide: something, else, and more - - """ - def strip_each_in(lst): - return [s.strip() for s in lst] - - out = {} - section = section.split('::') - if len(section) > 1: - out['default'] = strip_each_in(section[1].split(','))[0] - for line in content: - line = line.split(':') - if len(line) > 2: - out[line[1]] = strip_each_in(line[2].split(',')) - return out - - def _parse_summary(self): - """Grab signature (if given) and summary""" - if self._is_at_section(): - return - - summary = self._doc.read_to_next_empty_line() - summary_str = " ".join([s.strip() for s in summary]).strip() - if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str): - self['Signature'] = summary_str - if not self._is_at_section(): - self['Summary'] = self._doc.read_to_next_empty_line() - else: - self['Summary'] = summary - - if not self._is_at_section(): - self['Extended Summary'] = self._read_to_next_section() - - def _parse(self): - self._doc.reset() - self._parse_summary() - - for (section, content) in self._read_sections(): - if not section.startswith('..'): - section = ' '.join([s.capitalize() for s in section.split(' ')]) - if section in ('Parameters', 'Attributes', 'Methods', - 'Returns', 'Raises', 'Warns'): - self[section] = self._parse_param_list(content) - elif section.startswith('.. index::'): - self['index'] = self._parse_index(section, content) - elif section == 'See Also': - self['See Also'] = self._parse_see_also(content) - else: - self[section] = content - - # string conversion routines - - def _str_header(self, name, symbol='-'): - return [name, len(name) * symbol] - - def _str_indent(self, doc, indent=4): - out = [] - for line in doc: - out += [' ' * indent + line] - return out - - def _str_signature(self): - if self['Signature']: - return [self['Signature'].replace('*', '\*')] + [''] - else: - return [''] - - def _str_summary(self): - if self['Summary']: - return self['Summary'] + [''] - else: - return [] - - def _str_extended_summary(self): - if self['Extended Summary']: - return self['Extended Summary'] + [''] - else: - return [] - - def _str_param_list(self, name): - out = [] - if self[name]: - out += self._str_header(name) - for param, param_type, desc in self[name]: - out += ['%s : %s' % (param, param_type)] - out += self._str_indent(desc) - out += [''] - return out - - def _str_section(self, name): - out = [] - if self[name]: - out += self._str_header(name) - out += self[name] - out += [''] - return out - - def _str_see_also(self, func_role): - if not self['See Also']: - return [] - out = [] - out += self._str_header("See Also") - last_had_desc = True - for func, desc, role in self['See Also']: - if role: - link = ':%s:`%s`' % (role, func) - elif func_role: - link = ':%s:`%s`' % (func_role, func) - else: - link = "`%s`_" % func - if desc or last_had_desc: - out += [''] - out += [link] - else: - out[-1] += ", %s" % link - if desc: - out += self._str_indent([' '.join(desc)]) - last_had_desc = True - else: - last_had_desc = False - out += [''] - return out - - def _str_index(self): - idx = self['index'] - out = [] - out += ['.. index:: %s' % idx.get('default', '')] - for section, references in idx.iteritems(): - if section == 'default': - continue - out += [' :%s: %s' % (section, ', '.join(references))] - return out - - def __str__(self, func_role=''): - out = [] - out += self._str_signature() - out += self._str_summary() - out += self._str_extended_summary() - for param_list in ('Parameters', 'Returns', 'Raises'): - out += self._str_param_list(param_list) - out += self._str_section('Warnings') - out += self._str_see_also(func_role) - for s in ('Notes', 'References', 'Examples'): - out += self._str_section(s) - out += self._str_index() - return '\n'.join(out) - - -def indent(str, indent=4): - indent_str = ' ' * indent - if str is None: - return indent_str - lines = str.split('\n') - return '\n'.join(indent_str + l for l in lines) - - -def dedent_lines(lines): - """Deindent a list of lines maximally""" - return textwrap.dedent("\n".join(lines)).split("\n") - - -def header(text, style='-'): - return text + '\n' + style * len(text) + '\n' - - -class FunctionDoc(NumpyDocString): - def __init__(self, func, role='func'): - self._f = func - self._role = role # e.g. "func" or "meth" - try: - NumpyDocString.__init__(self, inspect.getdoc(func) or '') - except ValueError, e: - print '*' * 78 - print "ERROR: '%s' while parsing `%s`" % (e, self._f) - print '*' * 78 - #print "Docstring follows:" - #print doclines - #print '='*78 - - if not self['Signature']: - func, func_name = self.get_func() - try: - # try to read signature - argspec = inspect.getargspec(func) - argspec = inspect.formatargspec(*argspec) - argspec = argspec.replace('*', '\*') - signature = '%s%s' % (func_name, argspec) - except TypeError, e: - signature = '%s()' % func_name - self['Signature'] = signature - - def get_func(self): - func_name = getattr(self._f, '__name__', self.__class__.__name__) - if inspect.isclass(self._f): - func = getattr(self._f, '__call__', self._f.__init__) - else: - func = self._f - return func, func_name - - def __str__(self): - out = '' - - func, func_name = self.get_func() - signature = self['Signature'].replace('*', '\*') - - roles = {'func': 'function', - 'meth': 'method'} - - if self._role: - if not roles.has_key(self._role): - print "Warning: invalid role %s" % self._role - out += '.. %s:: %s\n \n\n' % (roles.get(self._role, ''), - func_name) - - out += super(FunctionDoc, self).__str__(func_role=self._role) - return out - - -class ClassDoc(NumpyDocString): - def __init__(self, cls, modulename='', func_doc=FunctionDoc): - if not inspect.isclass(cls): - raise ValueError("Initialise using a class. Got %r" % cls) - self._cls = cls - - if modulename and not modulename.endswith('.'): - modulename += '.' - self._mod = modulename - self._name = cls.__name__ - self._func_doc = func_doc - - NumpyDocString.__init__(self, pydoc.getdoc(cls)) - - @property - def methods(self): - return [name for name, func in inspect.getmembers(self._cls) - if not name.startswith('_') and callable(func)] - - def __str__(self): - out = '' - out += super(ClassDoc, self).__str__() - out += "\n\n" - - #for m in self.methods: - # print "Parsing `%s`" % m - # out += str(self._func_doc(getattr(self._cls,m), 'meth')) + '\n\n' - # out += '.. index::\n single: %s; %s\n\n' % (self._name, m) - - return out diff --git a/doc/sphinxext/numpy_ext_old/docscrape_sphinx.py b/doc/sphinxext/numpy_ext_old/docscrape_sphinx.py deleted file mode 100644 index 3e1d666e06607..0000000000000 --- a/doc/sphinxext/numpy_ext_old/docscrape_sphinx.py +++ /dev/null @@ -1,143 +0,0 @@ -import re -import inspect -import textwrap -import pydoc - -from docscrape import NumpyDocString -from docscrape FunctionDoc -from docscrape ClassDoc - - -class SphinxDocString(NumpyDocString): - # string conversion routines - def _str_header(self, name, symbol='`'): - return ['.. rubric:: ' + name, ''] - - def _str_field_list(self, name): - return [':' + name + ':'] - - def _str_indent(self, doc, indent=4): - out = [] - for line in doc: - out += [' ' * indent + line] - return out - - def _str_signature(self): - return [''] - if self['Signature']: - return ['``%s``' % self['Signature']] + [''] - else: - return [''] - - def _str_summary(self): - return self['Summary'] + [''] - - def _str_extended_summary(self): - return self['Extended Summary'] + [''] - - def _str_param_list(self, name): - out = [] - if self[name]: - out += self._str_field_list(name) - out += [''] - for param, param_type, desc in self[name]: - out += self._str_indent(['**%s** : %s' % (param.strip(), - param_type)]) - out += [''] - out += self._str_indent(desc, 8) - out += [''] - return out - - def _str_section(self, name): - out = [] - if self[name]: - out += self._str_header(name) - out += [''] - content = textwrap.dedent("\n".join(self[name])).split("\n") - out += content - out += [''] - return out - - def _str_see_also(self, func_role): - out = [] - if self['See Also']: - see_also = super(SphinxDocString, self)._str_see_also(func_role) - out = ['.. seealso::', ''] - out += self._str_indent(see_also[2:]) - return out - - def _str_warnings(self): - out = [] - if self['Warnings']: - out = ['.. warning::', ''] - out += self._str_indent(self['Warnings']) - return out - - def _str_index(self): - idx = self['index'] - out = [] - if len(idx) == 0: - return out - - out += ['.. index:: %s' % idx.get('default', '')] - for section, references in idx.iteritems(): - if section == 'default': - continue - elif section == 'refguide': - out += [' single: %s' % (', '.join(references))] - else: - out += [' %s: %s' % (section, ','.join(references))] - return out - - def _str_references(self): - out = [] - if self['References']: - out += self._str_header('References') - if isinstance(self['References'], str): - self['References'] = [self['References']] - out.extend(self['References']) - out += [''] - return out - - def __str__(self, indent=0, func_role="obj"): - out = [] - out += self._str_signature() - out += self._str_index() + [''] - out += self._str_summary() - out += self._str_extended_summary() - for param_list in ('Parameters', 'Attributes', 'Methods', - 'Returns', 'Raises'): - out += self._str_param_list(param_list) - out += self._str_warnings() - out += self._str_see_also(func_role) - out += self._str_section('Notes') - out += self._str_references() - out += self._str_section('Examples') - out = self._str_indent(out, indent) - return '\n'.join(out) - - -class SphinxFunctionDoc(SphinxDocString, FunctionDoc): - pass - - -class SphinxClassDoc(SphinxDocString, ClassDoc): - pass - - -def get_doc_object(obj, what=None): - if what is None: - if inspect.isclass(obj): - what = 'class' - elif inspect.ismodule(obj): - what = 'module' - elif callable(obj): - what = 'function' - else: - what = 'object' - if what == 'class': - return SphinxClassDoc(obj, '', func_doc=SphinxFunctionDoc) - elif what in ('function', 'method'): - return SphinxFunctionDoc(obj, '') - else: - return SphinxDocString(pydoc.getdoc(obj)) diff --git a/doc/sphinxext/numpy_ext_old/numpydoc.py b/doc/sphinxext/numpy_ext_old/numpydoc.py deleted file mode 100644 index 6e69d4601f9a3..0000000000000 --- a/doc/sphinxext/numpy_ext_old/numpydoc.py +++ /dev/null @@ -1,123 +0,0 @@ -""" -======== -numpydoc -======== - -Sphinx extension that handles docstrings in the Numpy standard format. [1] - -It will: - -- Convert Parameters etc. sections to field lists. -- Convert See Also section to a See also entry. -- Renumber references. -- Extract the signature from the docstring, if it can't be determined otherwise. - -.. [1] http://projects.scipy.org/scipy/numpy/wiki/CodingStyleGuidelines#docstring-standard - -""" - -import os -import re -import pydoc -import inspect - -from docscrape_sphinx import get_doc_object -from docscrape_sphinx import SphinxDocString - - -def mangle_docstrings(app, what, name, obj, options, lines, - reference_offset=[0]): - if what == 'module': - # Strip top title - title_re = re.compile(r'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*', - re.I | re.S) - lines[:] = title_re.sub('', "\n".join(lines)).split("\n") - else: - doc = get_doc_object(obj, what) - lines[:] = str(doc).split("\n") - - if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \ - obj.__name__: - v = dict(full_name=obj.__name__) - lines += [''] + (app.config.numpydoc_edit_link % v).split("\n") - - # replace reference numbers so that there are no duplicates - references = [] - for l in lines: - l = l.strip() - if l.startswith('.. ['): - try: - references.append(int(l[len('.. ['):l.index(']')])) - except ValueError: - print "WARNING: invalid reference in %s docstring" % name - - # Start renaming from the biggest number, otherwise we may - # overwrite references. - references.sort() - if references: - for i, line in enumerate(lines): - for r in references: - new_r = reference_offset[0] + r - lines[i] = lines[i].replace('[%d]_' % r, - '[%d]_' % new_r) - lines[i] = lines[i].replace('.. [%d]' % r, - '.. [%d]' % new_r) - - reference_offset[0] += len(references) - - -def mangle_signature(app, what, name, obj, options, sig, retann): - # Do not try to inspect classes that don't define `__init__` - if (inspect.isclass(obj) and - 'initializes x; see ' in pydoc.getdoc(obj.__init__)): - return '', '' - - if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')): - return - if not hasattr(obj, '__doc__'): - return - - doc = SphinxDocString(pydoc.getdoc(obj)) - if doc['Signature']: - sig = re.sub("^[^(]*", "", doc['Signature']) - return sig, '' - - -def initialize(app): - try: - app.connect('autodoc-process-signature', mangle_signature) - except: - monkeypatch_sphinx_ext_autodoc() - - -def setup(app, get_doc_object_=get_doc_object): - global get_doc_object - get_doc_object = get_doc_object_ - - app.connect('autodoc-process-docstring', mangle_docstrings) - app.connect('builder-inited', initialize) - app.add_config_value('numpydoc_edit_link', None, True) - -#------------------------------------------------------------------------------ -# Monkeypatch sphinx.ext.autodoc to accept argspecless autodocs (Sphinx < 0.5) -#------------------------------------------------------------------------------ - - -def monkeypatch_sphinx_ext_autodoc(): - global _original_format_signature - import sphinx.ext.autodoc - - if sphinx.ext.autodoc.format_signature is our_format_signature: - return - - print "[numpydoc] Monkeypatching sphinx.ext.autodoc ..." - _original_format_signature = sphinx.ext.autodoc.format_signature - sphinx.ext.autodoc.format_signature = our_format_signature - - -def our_format_signature(what, obj): - r = mangle_signature(None, what, None, obj, None, None, None) - if r is not None: - return r[0] - else: - return _original_format_signature(what, obj) diff --git a/doc/supervised_learning.rst b/doc/supervised_learning.rst index 3d09a193ef777..cde197287bee9 100644 --- a/doc/supervised_learning.rst +++ b/doc/supervised_learning.rst @@ -8,15 +8,18 @@ Supervised learning .. toctree:: modules/linear_model + modules/lda_qda.rst + modules/kernel_ridge.rst modules/svm modules/sgd modules/neighbors modules/gaussian_process - modules/pls + modules/cross_decomposition.rst modules/naive_bayes modules/tree modules/ensemble modules/multiclass modules/feature_selection.rst modules/label_propagation.rst - modules/lda_qda.rst + modules/isotonic.rst + modules/calibration.rst diff --git a/doc/support.rst b/doc/support.rst index 763ead7e90670..bf079d624b559 100644 --- a/doc/support.rst +++ b/doc/support.rst @@ -10,7 +10,7 @@ There are several ways to get in touch with the developers. Mailing List ============ -- The main mailing list is `scikit-learn-general +- The main mailing list is `scikit-learn-general `_. - There is also a commit list `scikit-learn-commits @@ -27,7 +27,7 @@ User questions the `[scikit-learn] `_ tag. -- For general theoretical or methodoligocal Machine Learning questions +- For general theoretical or methodological Machine Learning questions `metaoptimize.com/qa `_ is probably a more suitable venue. @@ -52,7 +52,7 @@ or continuous variable regression. Bug tracker =========== -If you think you've encoutered a bug, please report it to the issue tracker: +If you think you've encountered a bug, please report it to the issue tracker: https://github.com/scikit-learn/scikit-learn/issues @@ -67,7 +67,7 @@ Don't forget to include: To help developers fix your bug faster, please link to a https://gist.github.com holding a standalone minimalistic python script that reproduces your bug and optionally a minimalistic subsample of your dataset (for instance exported -as CSV files using `numpy.savetxt`). +as CSV files using ``numpy.savetxt``). Note: gists are git cloneable repositories and thus you can use git to push datafiles to them. @@ -93,7 +93,9 @@ Documentation resources This documentation is relative to |release|. Documentation for other versions can be found here: - * `Development version `_ + * `0.15 `_ + * `0.14 `_ + * `0.13 `_ * `0.12 `_ * `0.11 `_ * `0.10 `_ diff --git a/doc/templates/class.rst b/doc/templates/class.rst index 6e17cfa585e82..d223675bac525 100644 --- a/doc/templates/class.rst +++ b/doc/templates/class.rst @@ -1,5 +1,5 @@ -{{ fullname }} -{{ underline }} +:mod:`{{module}}`.{{objname}} +{{ underline }}============== .. currentmodule:: {{ module }} @@ -9,4 +9,8 @@ .. automethod:: __init__ {% endblock %} +.. include:: {{module}}.{{objname}}.examples +.. raw:: html + +
diff --git a/doc/templates/class_with_call.rst b/doc/templates/class_with_call.rst new file mode 100644 index 0000000000000..70e46d3583189 --- /dev/null +++ b/doc/templates/class_with_call.rst @@ -0,0 +1,17 @@ +:mod:`{{module}}`.{{objname}} +{{ underline }}=============== + +.. currentmodule:: {{ module }} + +.. autoclass:: {{ objname }} + + {% block methods %} + .. automethod:: __init__ + .. automethod:: __call__ + {% endblock %} + +.. include:: {{module}}.{{objname}}.examples + +.. raw:: html + +
diff --git a/doc/templates/function.rst b/doc/templates/function.rst index 317222f0fb713..f4b11eda770e4 100644 --- a/doc/templates/function.rst +++ b/doc/templates/function.rst @@ -1,8 +1,12 @@ -{{ fullname }} -{{ underline }} +:mod:`{{module}}`.{{objname}} +{{ underline }}==================== .. currentmodule:: {{ module }} .. autofunction:: {{ objname }} +.. include:: {{module}}.{{objname}}.examples +.. raw:: html + +
diff --git a/doc/testimonials/README.txt b/doc/testimonials/README.txt new file mode 100644 index 0000000000000..1ba1f31bd367f --- /dev/null +++ b/doc/testimonials/README.txt @@ -0,0 +1,8 @@ + + +To find the list of people we contacted, see: +https://docs.google.com/spreadsheet/ccc?key=0AhGnAxuBDhjmdDYwNzlZVE5SMkFsMjNBbGlaWkpNZ1E&usp=sharing + +To obtain access to this file, send an email to: +nelle dot varoquaux at gmail dot com + diff --git a/doc/sphinxext/numpy_ext_old/__init__.py b/doc/testimonials/images/Makefile similarity index 100% rename from doc/sphinxext/numpy_ext_old/__init__.py rename to doc/testimonials/images/Makefile diff --git a/doc/testimonials/images/aweber.png b/doc/testimonials/images/aweber.png new file mode 100644 index 0000000000000..30b12bde483c4 Binary files /dev/null and b/doc/testimonials/images/aweber.png differ diff --git a/doc/testimonials/images/bestofmedia-logo.png b/doc/testimonials/images/bestofmedia-logo.png new file mode 100644 index 0000000000000..e99cfbdf0341a Binary files /dev/null and b/doc/testimonials/images/bestofmedia-logo.png differ diff --git a/doc/testimonials/images/birchbox.jpg b/doc/testimonials/images/birchbox.jpg new file mode 100644 index 0000000000000..54ee5366668c6 Binary files /dev/null and b/doc/testimonials/images/birchbox.jpg differ diff --git a/doc/testimonials/images/change-logo.png b/doc/testimonials/images/change-logo.png new file mode 100644 index 0000000000000..d579dd29ec8fe Binary files /dev/null and b/doc/testimonials/images/change-logo.png differ diff --git a/doc/testimonials/images/datapublica.png b/doc/testimonials/images/datapublica.png new file mode 100644 index 0000000000000..1aa26bf2f83fd Binary files /dev/null and b/doc/testimonials/images/datapublica.png differ diff --git a/doc/testimonials/images/datarobot.png b/doc/testimonials/images/datarobot.png new file mode 100644 index 0000000000000..5e53b6134613e Binary files /dev/null and b/doc/testimonials/images/datarobot.png differ diff --git a/doc/testimonials/images/evernote.png b/doc/testimonials/images/evernote.png new file mode 100644 index 0000000000000..b6936727f7402 Binary files /dev/null and b/doc/testimonials/images/evernote.png differ diff --git a/doc/testimonials/images/howaboutwe.png b/doc/testimonials/images/howaboutwe.png new file mode 100644 index 0000000000000..26f8f3f87f8ce Binary files /dev/null and b/doc/testimonials/images/howaboutwe.png differ diff --git a/doc/testimonials/images/inria.png b/doc/testimonials/images/inria.png new file mode 100644 index 0000000000000..228f1dfdf11ce Binary files /dev/null and b/doc/testimonials/images/inria.png differ diff --git a/doc/testimonials/images/lovely.png b/doc/testimonials/images/lovely.png new file mode 100644 index 0000000000000..0349b861c7d85 Binary files /dev/null and b/doc/testimonials/images/lovely.png differ diff --git a/doc/testimonials/images/machinalis.png b/doc/testimonials/images/machinalis.png new file mode 100644 index 0000000000000..efb4d10e9cfac Binary files /dev/null and b/doc/testimonials/images/machinalis.png differ diff --git a/doc/testimonials/images/okcupid.png b/doc/testimonials/images/okcupid.png new file mode 100644 index 0000000000000..f73de3cdf6d63 Binary files /dev/null and b/doc/testimonials/images/okcupid.png differ diff --git a/doc/testimonials/images/peerindex.png b/doc/testimonials/images/peerindex.png new file mode 100644 index 0000000000000..1538dadfe46c5 Binary files /dev/null and b/doc/testimonials/images/peerindex.png differ diff --git a/doc/testimonials/images/phimeca.png b/doc/testimonials/images/phimeca.png new file mode 100644 index 0000000000000..3f8d5d3aa492b Binary files /dev/null and b/doc/testimonials/images/phimeca.png differ diff --git a/doc/testimonials/images/rangespan.png b/doc/testimonials/images/rangespan.png new file mode 100644 index 0000000000000..272c17077cef6 Binary files /dev/null and b/doc/testimonials/images/rangespan.png differ diff --git a/doc/testimonials/images/solido_logo.png b/doc/testimonials/images/solido_logo.png new file mode 100644 index 0000000000000..0bbb47a1093e5 Binary files /dev/null and b/doc/testimonials/images/solido_logo.png differ diff --git a/doc/testimonials/images/spotify.png b/doc/testimonials/images/spotify.png new file mode 100644 index 0000000000000..13ed314c3c910 Binary files /dev/null and b/doc/testimonials/images/spotify.png differ diff --git a/doc/testimonials/images/telecomparistech.jpg b/doc/testimonials/images/telecomparistech.jpg new file mode 100644 index 0000000000000..ddf35ebdc3e4e Binary files /dev/null and b/doc/testimonials/images/telecomparistech.jpg differ diff --git a/doc/testimonials/images/yhat.png b/doc/testimonials/images/yhat.png new file mode 100644 index 0000000000000..148c381f09f77 Binary files /dev/null and b/doc/testimonials/images/yhat.png differ diff --git a/doc/testimonials/testimonials.rst b/doc/testimonials/testimonials.rst new file mode 100644 index 0000000000000..8bfd9ae278d2c --- /dev/null +++ b/doc/testimonials/testimonials.rst @@ -0,0 +1,641 @@ +.. _testimonials: + +================================================================================ +Who is using scikit-learn? +================================================================================ + +.. raw:: html + +
+ + +.. to add a testimonials, just XXX + +`Spotify `_ +------------------------------------ + +.. raw:: html + + + +Scikit-learn provides a toolbox with solid implementations of a bunch of +state-of-the-art models and makes it easy to plug them into existing +applications. We've been using it quite a lot for music recommendations at +Spotify and I think it's the most well-designed ML package I've seen so +far. + +.. raw:: html + + + +Erik Bernhardsson, Engineering Manager Music Discovery & Machine Learning, Spotify + +.. raw:: html + + + +`Inria `_ +------------------------------- + +.. raw:: html + + + +.. title Scikit-learn for efficient and easier machine learning research +.. Author: Gaël Varoquaux + + +At INRIA, we use scikit-learn to support leading-edge basic research in many +teams: `Parietal `_ for neuroimaging, `Lear +`_ for computer vision, `Visages +`_ for medical image analysis, `Privatics +`_ for security. The project is a fantastic +tool to address difficult applications of machine learing in an academic +environment as it is performant and versatile, but all easy-to-use and well +documented, which makes it well suited to grad students. + + +.. raw:: html + + + +Gaël Varoquaux, research at Parietal + +.. raw:: html + + + + +`Evernote `_ +---------------------------------- + +.. raw:: html + + + + +Building a classifier is typically an iterative process of exploring +the data, selecting the features (the attributes of the data believed +to be predictive in some way), training the models, and finally +evaluating them. For many of these tasks, we relied on the excellent +scikit-learn package for Python. + +`Read more `_ + +.. raw:: html + + + +Mark Ayzenshtat, VP, Augmented Intelligence + +.. raw:: html + + + +`Télécom ParisTech `_ +-------------------------------------------------------- + +.. raw:: html + + + + +At Telecom ParisTech, scikit-learn is used for hands-on sessions and home +assignments in introductory and advanced machine learning courses. The classes +are for undergrads and masters students. The great benefit of scikit-learn is +its fast learning curve that allows students to quickly start working on +interesting and motivating problems. + +.. raw:: html + + + +Alexandre Gramfort, Assistant Professor + +.. raw:: html + + + + +`AWeber `_ +------------------------------------------ + +.. raw:: html + + + + +The scikit-learn toolkit is indispensable for the Data Analysis and Management +team at AWeber. It allows us to do AWesome stuff we would not otherwise have +the time or resources to accomplish. The documentation is excellent, allowing +new engineers to quickly evaluate and apply many different algorithms to our +data. The text feature extraction utilities are useful when working with the +large volume of email content we have at AWeber. The RandomizedPCA +implementation, along with Pipelining and FeatureUnions, allows us to develop +complex machine learning algorithms efficiently and reliably. + +Anyone interested in learning more about how AWeber deploys scikit-learn in a +production environment should check out talks from PyData Boston by AWeber's +Michael Becker available at https://github.com/mdbecker/pydata_2013 + +.. raw:: html + + + +Michael Becker, Software Engineer, Data Analysis and Management Ninjas + +.. raw:: html + + + +`Yhat `_ +------------------------------------------ + +.. raw:: html + + + +The combination of consistent APIs, thorough documentation, and top notch +implementation make scikit-learn our favorite machine learning package in +Python. scikit-learn makes doing advanced analysis in Python accessible to +anyone. At Yhat, we make it easy to integrate these models into your production +applications. Thus eliminating the unnecessary dev time encountered +productionizing analytical work. + + +.. raw:: html + + + +Greg Lamp, Co-founder Yhat + +.. raw:: html + + + +`Rangespan `_ +------------------------------------------ + +.. raw:: html + + + +The Python scikit-learn toolkit is a core tool in the data science +group at Rangespan. Its large collection of well documented models and +algorithms allow our team of data scientists to prototype fast and +quickly iterate to find the right solution to our learning problems. +We find that scikit-learn is not only the right tool for prototyping, +but its careful and well tested implementation give us the confidence +to run scikit-learn models in production. + +.. raw:: html + + + +Jurgen Van Gael, Data Science Director at Rangespan Ltd + +.. raw:: html + + + +`Birchbox `_ +------------------------------------------ + +.. raw:: html + + + +At Birchbox, we face a range of machine learning problems typical to +E-commerce: product recommendation, user clustering, inventory prediction, +trends detection, etc. Scikit-learn lets us experiment with many models, +especially in the exploration phase of a new project: the data can be passed +around in a consistent way; models are easy to save and reuse; updates keep us +informed of new developments from the pattern discovery research community. +Scikit-learn is an important tool for our team, built the right way in the +right language. + +.. raw:: html + + + +Thierry Bertin-Mahieux, Birchbox, Data Scientist + +.. raw:: html + + + + +`Bestofmedia Group `_ +-------------------------------------------------- + +.. raw:: html + + + +Scikit-learn is our #1 toolkit for all things machine learning +at Bestofmedia. We use it for a variety of tasks (e.g. spam fighting, +ad click prediction, various ranking models) thanks to the varied, +state-of-the-art algorithm implementations packaged into it. +In the lab it accelerates prototyping of complex pipelines. In +production I can say it has proven to be robust and efficient enough +to be deployed for business critical components. + +.. raw:: html + + + +Eustache Diemert, Lead Scientist Bestofmedia Group + +.. raw:: html + + + +`Change.org `_ +-------------------------------------------------- + +.. raw:: html + + + +At change.org we automate the use of scikit-learn's RandomForestClassifier +in our production systems to drive email targeting that reaches millions +of users across the world each week. In the lab, scikit-learn's ease-of-use, +performance, and overall variety of algorithms implemented has proved invaluable +in giving us a single reliable source to turn to for our machine-learning needs. + +.. raw:: html + + + +Vijay Ramesh, Software Engineer in Data/science at Change.org + +.. raw:: html + + + +`PHIMECA Engineering `_ +---------------------------------------------------------- + +.. raw:: html + + + +At PHIMECA Engineering, we use scikit-learn estimators as surrogates for +expensive-to-evaluate numerical models (mostly but not exclusively +finite-element mechanical models) for speeding up the intensive post-processing +operations involved in our simulation-based decision making framework. +Scikit-learn's fit/predict API together with its efficient cross-validation +tools considerably eases the task of selecting the best-fit estimator. We are +also using scikit-learn for illustrating concepts in our training sessions. +Trainees are always impressed by the ease-of-use of scikit-learn despite the +apparent theoretical complexity of machine learning. + +.. raw:: html + + + +Vincent Dubourg, PHIMECA Engineering, PhD Engineer + +.. raw:: html + + + +`HowAboutWe `_ +---------------------------------------------------------- + +.. raw:: html + + + +At HowAboutWe, scikit-learn lets us implement a wide array of machine learning +techniques in analysis and in production, despite having a small team. We use +scikit-learn’s classification algorithms to predict user behavior, enabling us +to (for example) estimate the value of leads from a given traffic source early +in the lead’s tenure on our site. Also, our users' profiles consist of +primarily unstructured data (answers to open-ended questions), so we use +scikit-learn’s feature extraction and dimensionality reduction tools to +translate these unstructured data into inputs for our matchmaking system. + +.. raw:: html + + + +Daniel Weitzenfeld, Senior Data Scientist at HowAboutWe + +.. raw:: html + + + + +`PeerIndex `_ +---------------------------------------- + +.. raw:: html + + + +At PeerIndex we use scientific methodology to build the Influence Graph - a +unique dataset that allows us to identify who’s really influential and in which +context. To do this, we have to tackle a range of machine learning and +predictive modeling problems. Scikit-learn has emerged as our primary tool for +developing prototypes and making quick progress. From predicting missing data +and classifying tweets to clustering communities of social media users, scikit- +learn proved useful in a variety of applications. Its very intuitive interface +and excellent compatibility with other python tools makes it and indispensable +tool in our daily research efforts. + +.. raw:: html + + + +Ferenc Huszar - Senior Data Scientist at Peerindex + +.. raw:: html + + + + +`DataRobot `_ +---------------------------------------- + +.. raw:: html + + + +DataRobot is building next generation predictive analytics software to make data scientists more productive, and scikit-learn is an integral part of our system. The variety of machine learning techniques in combination with the solid implementations that scikit-learn offers makes it a one-stop-shopping library for machine learning in Python. Moreover, its consistent API, well-tested code and permissive licensing allow us to use it in a production environment. Scikit-learn has literally saved us years of work we would have had to do ourselves to bring our product to market. + +.. raw:: html + + + +Jeremy Achin, CEO & Co-founder DataRobot Inc. + +.. raw:: html + + + + +`OkCupid `_ +-------------------------------------- + +.. raw:: html + + + +We're using scikit-learn at OkCupid to evaluate and improve our matchmaking +system. The range of features it has, especially preprocessing utilities, means +we can use it for a wide variety of projects, and it's performant enough to +handle the volume of data that we need to sort through. The documentation is +really thorough, as well, which makes the library quite easy to use. + +.. raw:: html + + + +David Koh - Senior Data Scientist at OkCupid + +.. raw:: html + + + + +`Lovely `_ +----------------------------------------- + +.. raw:: html + + + +At Lovely, we strive to deliver the best apartment marketplace, with respect to +our users and our listings. From understanding user behavior, improving data +quality, and detecting fraud, scikit-learn is a regular tool for gathering +insights, predictive modeling and improving our product. The easy-to-read +documentation and intuitive architecture of the API makes machine learning both +explorable and accessible to a wide range of python developers. I'm constantly +recommending that more developers and scientists try scikit-learn. + +.. raw:: html + + + +Simon Frid - Data Scientist, Lead at Lovely + +.. raw:: html + + + + + +`Data Publica `_ +---------------------------------------------- + +.. raw:: html + + + +Data Publica builds a new predictive sales tool for commercial and marketing teams called C-Radar. +We extensively use scikit-learn to build segmentations of customers through clustering, and to predict future customers based on past partnerships success or failure. +We also categorize companies using their website communication thanks to scikit-learn and its machine learning algorithm implementations. +Eventually, machine learning makes it possible to detect weak signals that traditional tools cannot see. +All these complex tasks are performed in an easy and straightforward way thanks to the great quality of the scikit-learn framework. + +.. raw:: html + + + +Guillaume Lebourgeois & Samuel Charron - Data Scientists at Data Publica + +.. raw:: html + + + + + +`Machinalis `_ +----------------------------------------- + +.. raw:: html + + + +Scikit-learn is the cornerstone of all the machine learning projects carried at +Machinalis. It has a consistent API, a wide selection of algorithms and lots +of auxiliary tools to deal with the boilerplate. +We have used it in production environments on a variety of projects +including click-through rate prediction, `information extraction `_, +and even counting sheep! + +In fact, we use it so much that we've started to freeze our common use cases +into Python packages, some of them open-sourced, like +`FeatureForge `_ . +Scikit-learn in one word: Awesome. + +.. raw:: html + + + +Rafael Carrascosa, Lead developer + + +`solido `_ +----------------------------------------- + +.. raw:: html + + + +Scikit-learn is helping to drive Moore’s Law, via Solido. Solido creates +computer-aided design tools used by the majority of top-20 semiconductor +companies and fabs, to design the bleeding-edge chips inside smartphones, +automobiles, and more. Scikit-learn helps to power Solido’s algorithms for +rare-event estimation, worst-case verification, optimization, and more. At +Solido, we are particularly fond of scikit-learn’s libraries for Gaussian +Process models, large-scale regularized linear regression, and classification. +Scikit-learn has increased our productivity, because for many ML problems we no +longer need to “roll our own” code. `This PyData 2014 talk `_ has details. + + +.. raw:: html + + + +Trent McConaghy, founder, Solido Design Automation Inc. + +.. raw:: html + + + + diff --git a/doc/themes/scikit-learn/layout.html b/doc/themes/scikit-learn/layout.html index 3b7dc7d5cee47..8dcadf93cdecf 100644 --- a/doc/themes/scikit-learn/layout.html +++ b/doc/themes/scikit-learn/layout.html @@ -3,7 +3,7 @@ ~~~~~~~~~~~~~~~~~ Layout for scikit-learn, after a design made by Angel Soler - (http://webylimonada.org) + (http://angelsoler.net) Update: Collapsable sidebar added - 13/03/2012 - Jaques Grobler Update: Next-page button added - 16/03/2012 - Jaques Grobler @@ -13,189 +13,270 @@ :license: BSD #} {% extends "basic/layout.html" %} - -{% if theme_collapsiblesidebar|tobool %} -{% set script_files = script_files + ['_static/sidebar.js'] %} -{% endif %} +{% set css_files = css_files + ["_static/gallery.css"] %} + +{% block htmltitle %} + {{ super() }} + + + + +{% endblock %} {% block extrahead %} - + {% if pagename != 'index' %} + {% if theme_collapsiblesidebar|tobool %} + + {% endif %} + {% endif %} + + + + + {% endblock %} {%- if pagename == 'index' %} {% set title = 'scikit-learn: machine learning in Python' %} {%- endif %} +{%- if pagename == 'documentation' %} + {% set title = 'Documentation scikit-learn: machine learning in Python' %} +{%- endif %} + {% block header %} - {%- if theme_oldversion == true %} -
-

Warning: This documentation is - for {{project}} version {{ release|e }}. - — - Latest stable version

-
- {%- endif %} -
-
+
+
{%- if logo %} - + +

{%- endif %} - {%- block navbar -%} - + + {%- endblock -%} + +
-
- {%- endblock -%} -
+{%- if pagename == 'index' %} + + +{%- endif %} + {% endblock %} {% block content %} -
- -
-
- {%- if pagename != 'index' %} - {%- if parents %} -
- {% else %} - -

This documentation is - for {{project}} version {{ release|e }} - — Other versions

- {% else %} -

News

+ + + Fork me on GitHub + -

scikit-learn 0.12 is available - for download. - See what's new and tips - on installing.

+
+{%- if pagename != 'index' and pagename != 'documentation' %} +
+
-

Presentations

-

Get into the spirit with videos from Scikit-Learn tutorials.

+ {%- if rellinks[1:] %} -

Participate

+ {%- if parents %} +
+ {% else %} +
+ {% endif %} -

Fork - the source - code, join the - mailing - lists, report bugs to - the issue - tracker or participate in the next - coding sprint. Read More... -

+ -

Funding

-

Generous funding provided - by INRIA, - Google - and others.

-

INRIA

-

INRIA

+ {%- for rellink in rellinks[1:]|reverse %} + + {%- if not loop.last %} +
+   +
+ {%- endif %} + {%- endfor %} -

Read more ...

+ + {%- if parents %} +
+   +
+ + {%- endif %} +
{% endif %} -

Citing

-

If you use the software, please consider - citing scikit-learn.

- {%- if (pagename != 'index') %} -

{{ _('This page') }}

- {{ toc }} - {% endif %} + {%- if pagename != "install" %} +

This documentation is for {{project}} version {{ release|e }}Other versions

+ {%- endif %} +

If you use the software, please consider citing scikit-learn.

+ {{ toc }}
-
+
+{% endif %}
@@ -205,34 +286,28 @@

{{ _('This page') }}

- {% endblock %} - {% block relbar1 %}{% endblock %} {% block relbar2 %}{% endblock %} {%- block footer %} @@ -244,23 +319,35 @@

{{ _('This page') }}

{% endif %} {%- for rellink in rellinks[1:]|reverse %} {%- endfor %} {% endif %}
- -{%- endblock %} + {% if theme_google_analytics|tobool %} + + {% endif %} + + +{%- endblock %} diff --git a/doc/themes/scikit-learn/static/ML_MAPS_README.rst b/doc/themes/scikit-learn/static/ML_MAPS_README.rst new file mode 100644 index 0000000000000..93e53f18dca55 --- /dev/null +++ b/doc/themes/scikit-learn/static/ML_MAPS_README.rst @@ -0,0 +1,93 @@ +Machine Learning Cheat Sheet (for scikit-learn) +=============================================== + +This document is intended to explain how to edit +the machine learning cheat sheet, originally created +by Andreas Mueller: + +(http://peekaboo-vision.blogspot.de/2013/01/machine-learning-cheat-sheet-for-scikit.html) + +The image is made interactive using an imagemap, and uses the jQuery Map Hilight plugin module +by David Lynch (http://davidlynch.org/projects/maphilight/docs/) to highlight +the different items on the image upon mouseover. + +Modifying the map on the docs is currently a little bit tedious, +so I'll try to make it as simple as possible. + +1. Editing the layout of the map and it's paths. +------------------------------------------------ + +Use a Graphics editor like Inkscape Vector Graphics Editor +to open the ml_map.svg file, in this folder. From there +you can move objects around, ect. as you need. + +Save when done, and make sure to export a .PNG file +to replace the old-outdated ml_map.png, as that file +is used as a background image. + +2. Accessing the paths of the SVG file and exporting them. +---------------------------------------------------------- + +Use an image manipulation package like GIMP Image Editor to open +the ml_map.svg file, in this folder. With GIMP, make sure +to select 'Import paths'. + +Once the image has been opened, you can see all imported paths on the paths tab. +You can edit these or create new paths. In GIMP, right-clicking one of the +paths and choosing: Path Tool will allow you to see the paths on +the image. The paths will be exported later and will be used to +make the click able regions on our image map. + +3. Export paths as SVG files +---------------------------- + +After you've edited a path or created a new one, right click it on +the paths menu and choose 'Export Path..'. This way we extract just +that path on its own as 'new_area.svg' for example. + +4. Edit the SVG file +--------------------- +Using a script made by David Lynch, we will convert the svg files into +html maps. To do this, open the svg file in question in any text editor. +Make sure that the 'width' and 'height' are not in 'in' or 'px', i.e +"100" is OK, but "100px" or "1.25in" are not. + +Then wrap the tags in and tags. +Then the file is ready for the script. + +5. From SVG to HTML map +----------------------- + +Use the provided svg2imagemap.py script on your edited svg file: + +$ python svg2imagemap.py new_area.svg + +where new_area.svg is our file. + +6. Add the new map to the main html file +------------------------------------------ + +Copy the code from the newly created 'new_area.html' +file. Open the ml_map.html file. + +Add the that you copied +after the last tag in the ml_map.html file. + +Add the link address to 'href' and a tooltip to +'title' within your tag. + +If you wish to add the green and blue hover effect +to the area, add +data-maphilight='{"strokeColor":"0000ff","strokeWidth":5,"fillColor":"66FF66","fillOpacity":0.4}' + +to your area tag, as done in the other tags above. + +Save the file, and you're done. + +----------------------------------------------------- + +I'll take some time to make some scripts to automate this process +a bit more at some point, as it is not difficult to do, +but tedious. + +-Jaques Grobler diff --git a/doc/themes/scikit-learn/static/css/bootstrap-responsive.css b/doc/themes/scikit-learn/static/css/bootstrap-responsive.css new file mode 100644 index 0000000000000..09e88ce3fecc2 --- /dev/null +++ b/doc/themes/scikit-learn/static/css/bootstrap-responsive.css @@ -0,0 +1,1109 @@ +/*! + * Bootstrap Responsive v2.3.2 + * + * Copyright 2012 Twitter, Inc + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world @twitter by @mdo and @fat. + */ + +.clearfix { + *zoom: 1; +} + +.clearfix:before, +.clearfix:after { + display: table; + line-height: 0; + content: ""; +} + +.clearfix:after { + clear: both; +} + +.hide-text { + font: 0/0 a; + color: transparent; + text-shadow: none; + background-color: transparent; + border: 0; +} + +.input-block-level { + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +@-ms-viewport { + width: device-width; +} + +.hidden { + display: none; + visibility: hidden; +} + +.visible-phone { + display: none !important; +} + +.visible-tablet { + display: none !important; +} + +.hidden-desktop { + display: none !important; +} + +.visible-desktop { + display: inherit !important; +} + +@media (min-width: 768px) and (max-width: 979px) { + .hidden-desktop { + display: inherit !important; + } + .visible-desktop { + display: none !important ; + } + .visible-tablet { + display: inherit !important; + } + .hidden-tablet { + display: none !important; + } +} + +@media (max-width: 767px) { + .hidden-desktop { + display: inherit !important; + } + .visible-desktop { + display: none !important; + } + .visible-phone { + display: inherit !important; + } + .hidden-phone { + display: none !important; + } +} + +.visible-print { + display: none !important; +} + +@media print { + .visible-print { + display: inherit !important; + } + .hidden-print { + display: none !important; + } +} + +@media (min-width: 1200px) { + .row { + margin-left: -30px; + *zoom: 1; + } + .row:before, + .row:after { + display: table; + line-height: 0; + content: ""; + } + .row:after { + clear: both; + } + [class*="span"] { + float: left; + min-height: 1px; + margin-left: 30px; + } + .container, + .navbar-static-top .container, + .navbar-fixed-top .container, + .navbar-fixed-bottom .container { + width: 1170px; + } + .span12 { + width: 1170px; + } + .span11 { + width: 1070px; + } + .span10 { + width: 970px; + } + .span9 { + width: 870px; + } + .span8 { + width: 770px; + } + .span7 { + width: 670px; + } + .span6 { + width: 570px; + } + .span5 { + width: 470px; + } + .span4 { + width: 370px; + } + .span3 { + width: 270px; + } + .span2 { + width: 170px; + } + .span1 { + width: 70px; + } + .offset12 { + margin-left: 1230px; + } + .offset11 { + margin-left: 1130px; + } + .offset10 { + margin-left: 1030px; + } + .offset9 { + margin-left: 930px; + } + .offset8 { + margin-left: 830px; + } + .offset7 { + margin-left: 730px; + } + .offset6 { + margin-left: 630px; + } + .offset5 { + margin-left: 530px; + } + .offset4 { + margin-left: 430px; + } + .offset3 { + margin-left: 330px; + } + .offset2 { + margin-left: 230px; + } + .offset1 { + margin-left: 130px; + } + .row-fluid { + width: 100%; + *zoom: 1; + } + .row-fluid:before, + .row-fluid:after { + display: table; + line-height: 0; + content: ""; + } + .row-fluid:after { + clear: both; + } + .row-fluid [class*="span"] { + display: block; + float: left; + width: 100%; + min-height: 30px; + margin-left: 2.564102564102564%; + *margin-left: 2.5109110747408616%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .row-fluid [class*="span"]:first-child { + margin-left: 0; + } + .row-fluid .controls-row [class*="span"] + [class*="span"] { + margin-left: 2.564102564102564%; + } + .row-fluid .span12 { + width: 100%; + *width: 99.94680851063829%; + } + .row-fluid .span11 { + width: 91.45299145299145%; + *width: 91.39979996362975%; + } + .row-fluid .span10 { + width: 82.90598290598291%; + *width: 82.8527914166212%; + } + .row-fluid .span9 { + width: 74.35897435897436%; + *width: 74.30578286961266%; + } + .row-fluid .span8 { + width: 65.81196581196582%; + *width: 65.75877432260411%; + } + .row-fluid .span7 { + width: 57.26495726495726%; + *width: 57.21176577559556%; + } + .row-fluid .span6 { + width: 48.717948717948715%; + *width: 48.664757228587014%; + } + .row-fluid .span5 { + width: 40.17094017094017%; + *width: 40.11774868157847%; + } + .row-fluid .span4 { + width: 31.623931623931625%; + *width: 31.570740134569924%; + } + .row-fluid .span3 { + width: 23.076923076923077%; + *width: 23.023731587561375%; + } + .row-fluid .span2 { + width: 14.52991452991453%; + *width: 14.476723040552828%; + } + .row-fluid .span1 { + width: 5.982905982905983%; + *width: 5.929714493544281%; + } + .row-fluid .offset12 { + margin-left: 105.12820512820512%; + *margin-left: 105.02182214948171%; + } + .row-fluid .offset12:first-child { + margin-left: 102.56410256410257%; + *margin-left: 102.45771958537915%; + } + .row-fluid .offset11 { + margin-left: 96.58119658119658%; + *margin-left: 96.47481360247316%; + } + .row-fluid .offset11:first-child { + margin-left: 94.01709401709402%; + *margin-left: 93.91071103837061%; + } + .row-fluid .offset10 { + margin-left: 88.03418803418803%; + *margin-left: 87.92780505546462%; + } + .row-fluid .offset10:first-child { + margin-left: 85.47008547008548%; + *margin-left: 85.36370249136206%; + } + .row-fluid .offset9 { + margin-left: 79.48717948717949%; + *margin-left: 79.38079650845607%; + } + .row-fluid .offset9:first-child { + margin-left: 76.92307692307693%; + *margin-left: 76.81669394435352%; + } + .row-fluid .offset8 { + margin-left: 70.94017094017094%; + *margin-left: 70.83378796144753%; + } + .row-fluid .offset8:first-child { + margin-left: 68.37606837606839%; + *margin-left: 68.26968539734497%; + } + .row-fluid .offset7 { + margin-left: 62.393162393162385%; + *margin-left: 62.28677941443899%; + } + .row-fluid .offset7:first-child { + margin-left: 59.82905982905982%; + *margin-left: 59.72267685033642%; + } + .row-fluid .offset6 { + margin-left: 53.84615384615384%; + *margin-left: 53.739770867430444%; + } + .row-fluid .offset6:first-child { + margin-left: 51.28205128205128%; + *margin-left: 51.175668303327875%; + } + .row-fluid .offset5 { + margin-left: 45.299145299145295%; + *margin-left: 45.1927623204219%; + } + .row-fluid .offset5:first-child { + margin-left: 42.73504273504273%; + *margin-left: 42.62865975631933%; + } + .row-fluid .offset4 { + margin-left: 36.75213675213675%; + *margin-left: 36.645753773413354%; + } + .row-fluid .offset4:first-child { + margin-left: 34.18803418803419%; + *margin-left: 34.081651209310785%; + } + .row-fluid .offset3 { + margin-left: 28.205128205128204%; + *margin-left: 28.0987452264048%; + } + .row-fluid .offset3:first-child { + margin-left: 25.641025641025642%; + *margin-left: 25.53464266230224%; + } + .row-fluid .offset2 { + margin-left: 19.65811965811966%; + *margin-left: 19.551736679396257%; + } + .row-fluid .offset2:first-child { + margin-left: 17.094017094017094%; + *margin-left: 16.98763411529369%; + } + .row-fluid .offset1 { + margin-left: 11.11111111111111%; + *margin-left: 11.004728132387708%; + } + .row-fluid .offset1:first-child { + margin-left: 8.547008547008547%; + *margin-left: 8.440625568285142%; + } + input, + textarea, + .uneditable-input { + margin-left: 0; + } + .controls-row [class*="span"] + [class*="span"] { + margin-left: 30px; + } + input.span12, + textarea.span12, + .uneditable-input.span12 { + width: 1156px; + } + input.span11, + textarea.span11, + .uneditable-input.span11 { + width: 1056px; + } + input.span10, + textarea.span10, + .uneditable-input.span10 { + width: 956px; + } + input.span9, + textarea.span9, + .uneditable-input.span9 { + width: 856px; + } + input.span8, + textarea.span8, + .uneditable-input.span8 { + width: 756px; + } + input.span7, + textarea.span7, + .uneditable-input.span7 { + width: 656px; + } + input.span6, + textarea.span6, + .uneditable-input.span6 { + width: 556px; + } + input.span5, + textarea.span5, + .uneditable-input.span5 { + width: 456px; + } + input.span4, + textarea.span4, + .uneditable-input.span4 { + width: 356px; + } + input.span3, + textarea.span3, + .uneditable-input.span3 { + width: 256px; + } + input.span2, + textarea.span2, + .uneditable-input.span2 { + width: 156px; + } + input.span1, + textarea.span1, + .uneditable-input.span1 { + width: 56px; + } + .thumbnails { + margin-left: -30px; + } + .thumbnails > li { + margin-left: 30px; + } + .row-fluid .thumbnails { + margin-left: 0; + } +} + +@media (min-width: 768px) and (max-width: 979px) { + .row { + margin-left: -20px; + *zoom: 1; + } + .row:before, + .row:after { + display: table; + line-height: 0; + content: ""; + } + .row:after { + clear: both; + } + [class*="span"] { + float: left; + min-height: 1px; + margin-left: 20px; + } + .container, + .navbar-static-top .container, + .navbar-fixed-top .container, + .navbar-fixed-bottom .container { + width: 724px; + } + .span12 { + width: 724px; + } + .span11 { + width: 662px; + } + .span10 { + width: 600px; + } + .span9 { + width: 538px; + } + .span8 { + width: 476px; + } + .span7 { + width: 414px; + } + .span6 { + width: 352px; + } + .span5 { + width: 290px; + } + .span4 { + width: 228px; + } + .span3 { + width: 166px; + } + .span2 { + width: 104px; + } + .span1 { + width: 42px; + } + .offset12 { + margin-left: 764px; + } + .offset11 { + margin-left: 702px; + } + .offset10 { + margin-left: 640px; + } + .offset9 { + margin-left: 578px; + } + .offset8 { + margin-left: 516px; + } + .offset7 { + margin-left: 454px; + } + .offset6 { + margin-left: 392px; + } + .offset5 { + margin-left: 330px; + } + .offset4 { + margin-left: 268px; + } + .offset3 { + margin-left: 206px; + } + .offset2 { + margin-left: 144px; + } + .offset1 { + margin-left: 82px; + } + .row-fluid { + width: 100%; + *zoom: 1; + } + .row-fluid:before, + .row-fluid:after { + display: table; + line-height: 0; + content: ""; + } + .row-fluid:after { + clear: both; + } + .row-fluid [class*="span"] { + display: block; + float: left; + width: 100%; + min-height: 30px; + margin-left: 2.7624309392265194%; + *margin-left: 2.709239449864817%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .row-fluid [class*="span"]:first-child { + margin-left: 0; + } + .row-fluid .controls-row [class*="span"] + [class*="span"] { + margin-left: 2.7624309392265194%; + } + .row-fluid .span12 { + width: 100%; + *width: 99.94680851063829%; + } + .row-fluid .span11 { + width: 91.43646408839778%; + *width: 91.38327259903608%; + } + .row-fluid .span10 { + width: 82.87292817679558%; + *width: 82.81973668743387%; + } + .row-fluid .span9 { + width: 74.30939226519337%; + *width: 74.25620077583166%; + } + .row-fluid .span8 { + width: 65.74585635359117%; + *width: 65.69266486422946%; + } + .row-fluid .span7 { + width: 57.18232044198895%; + *width: 57.12912895262725%; + } + .row-fluid .span6 { + width: 48.61878453038674%; + *width: 48.56559304102504%; + } + .row-fluid .span5 { + width: 40.05524861878453%; + *width: 40.00205712942283%; + } + .row-fluid .span4 { + width: 31.491712707182323%; + *width: 31.43852121782062%; + } + .row-fluid .span3 { + width: 22.92817679558011%; + *width: 22.87498530621841%; + } + .row-fluid .span2 { + width: 14.3646408839779%; + *width: 14.311449394616199%; + } + .row-fluid .span1 { + width: 5.801104972375691%; + *width: 5.747913483013988%; + } + .row-fluid .offset12 { + margin-left: 105.52486187845304%; + *margin-left: 105.41847889972962%; + } + .row-fluid .offset12:first-child { + margin-left: 102.76243093922652%; + *margin-left: 102.6560479605031%; + } + .row-fluid .offset11 { + margin-left: 96.96132596685082%; + *margin-left: 96.8549429881274%; + } + .row-fluid .offset11:first-child { + margin-left: 94.1988950276243%; + *margin-left: 94.09251204890089%; + } + .row-fluid .offset10 { + margin-left: 88.39779005524862%; + *margin-left: 88.2914070765252%; + } + .row-fluid .offset10:first-child { + margin-left: 85.6353591160221%; + *margin-left: 85.52897613729868%; + } + .row-fluid .offset9 { + margin-left: 79.8342541436464%; + *margin-left: 79.72787116492299%; + } + .row-fluid .offset9:first-child { + margin-left: 77.07182320441989%; + *margin-left: 76.96544022569647%; + } + .row-fluid .offset8 { + margin-left: 71.2707182320442%; + *margin-left: 71.16433525332079%; + } + .row-fluid .offset8:first-child { + margin-left: 68.50828729281768%; + *margin-left: 68.40190431409427%; + } + .row-fluid .offset7 { + margin-left: 62.70718232044199%; + *margin-left: 62.600799341718584%; + } + .row-fluid .offset7:first-child { + margin-left: 59.94475138121547%; + *margin-left: 59.838368402492065%; + } + .row-fluid .offset6 { + margin-left: 54.14364640883978%; + *margin-left: 54.037263430116376%; + } + .row-fluid .offset6:first-child { + margin-left: 51.38121546961326%; + *margin-left: 51.27483249088986%; + } + .row-fluid .offset5 { + margin-left: 45.58011049723757%; + *margin-left: 45.47372751851417%; + } + .row-fluid .offset5:first-child { + margin-left: 42.81767955801105%; + *margin-left: 42.71129657928765%; + } + .row-fluid .offset4 { + margin-left: 37.01657458563536%; + *margin-left: 36.91019160691196%; + } + .row-fluid .offset4:first-child { + margin-left: 34.25414364640884%; + *margin-left: 34.14776066768544%; + } + .row-fluid .offset3 { + margin-left: 28.45303867403315%; + *margin-left: 28.346655695309746%; + } + .row-fluid .offset3:first-child { + margin-left: 25.69060773480663%; + *margin-left: 25.584224756083227%; + } + .row-fluid .offset2 { + margin-left: 19.88950276243094%; + *margin-left: 19.783119783707537%; + } + .row-fluid .offset2:first-child { + margin-left: 17.12707182320442%; + *margin-left: 17.02068884448102%; + } + .row-fluid .offset1 { + margin-left: 11.32596685082873%; + *margin-left: 11.219583872105325%; + } + .row-fluid .offset1:first-child { + margin-left: 8.56353591160221%; + *margin-left: 8.457152932878806%; + } + input, + textarea, + .uneditable-input { + margin-left: 0; + } + .controls-row [class*="span"] + [class*="span"] { + margin-left: 20px; + } + input.span12, + textarea.span12, + .uneditable-input.span12 { + width: 710px; + } + input.span11, + textarea.span11, + .uneditable-input.span11 { + width: 648px; + } + input.span10, + textarea.span10, + .uneditable-input.span10 { + width: 586px; + } + input.span9, + textarea.span9, + .uneditable-input.span9 { + width: 524px; + } + input.span8, + textarea.span8, + .uneditable-input.span8 { + width: 462px; + } + input.span7, + textarea.span7, + .uneditable-input.span7 { + width: 400px; + } + input.span6, + textarea.span6, + .uneditable-input.span6 { + width: 338px; + } + input.span5, + textarea.span5, + .uneditable-input.span5 { + width: 276px; + } + input.span4, + textarea.span4, + .uneditable-input.span4 { + width: 214px; + } + input.span3, + textarea.span3, + .uneditable-input.span3 { + width: 152px; + } + input.span2, + textarea.span2, + .uneditable-input.span2 { + width: 90px; + } + input.span1, + textarea.span1, + .uneditable-input.span1 { + width: 28px; + } +} + +@media (max-width: 767px) { + body { + padding-right: 20px; + padding-left: 20px; + } + .navbar-fixed-top, + .navbar-fixed-bottom, + .navbar-static-top { + margin-right: -20px; + margin-left: -20px; + } + .container-fluid { + padding: 0; + } + .dl-horizontal dt { + float: none; + width: auto; + clear: none; + text-align: left; + } + .dl-horizontal dd { + margin-left: 0; + } + .container { + width: auto; + } + .row-fluid { + width: 100%; + } + .row, + .thumbnails { + margin-left: 0; + } + .thumbnails > li { + float: none; + margin-left: 0; + } + [class*="span"], + .uneditable-input[class*="span"], + .row-fluid [class*="span"] { + display: block; + float: none; + width: 100%; + margin-left: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .span12, + .row-fluid .span12 { + width: 100%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .row-fluid [class*="offset"]:first-child { + margin-left: 0; + } + .input-large, + .input-xlarge, + .input-xxlarge, + input[class*="span"], + select[class*="span"], + textarea[class*="span"], + .uneditable-input { + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .input-prepend input, + .input-append input, + .input-prepend input[class*="span"], + .input-append input[class*="span"] { + display: inline-block; + width: auto; + } + .controls-row [class*="span"] + [class*="span"] { + margin-left: 0; + } + .modal { + position: fixed; + top: 20px; + right: 20px; + left: 20px; + width: auto; + margin: 0; + } + .modal.fade { + top: -100px; + } + .modal.fade.in { + top: 20px; + } +} + +@media (max-width: 480px) { + .nav-collapse { + -webkit-transform: translate3d(0, 0, 0); + } + .page-header h1 small { + display: block; + line-height: 20px; + } + input[type="checkbox"], + input[type="radio"] { + border: 1px solid #ccc; + } + .form-horizontal .control-label { + float: none; + width: auto; + padding-top: 0; + text-align: left; + } + .form-horizontal .controls { + margin-left: 0; + } + .form-horizontal .control-list { + padding-top: 0; + } + .form-horizontal .form-actions { + padding-right: 10px; + padding-left: 10px; + } + .media .pull-left, + .media .pull-right { + display: block; + float: none; + margin-bottom: 10px; + } + .media-object { + margin-right: 0; + margin-left: 0; + } + .modal { + top: 10px; + right: 10px; + left: 10px; + } + .modal-header .close { + padding: 10px; + margin: -10px; + } + .carousel-caption { + position: static; + } +} + +@media (max-width: 979px) { + body { + padding-top: 0; + } + .navbar-fixed-top, + .navbar-fixed-bottom { + position: static; + } + .navbar-fixed-top { + margin-bottom: 20px; + } + .navbar-fixed-bottom { + margin-top: 20px; + } + .navbar-fixed-top .navbar-inner, + .navbar-fixed-bottom .navbar-inner { + padding: 5px; + } + .navbar .container { + width: auto; + padding: 0; + } + .navbar .brand { + padding-right: 10px; + padding-left: 10px; + margin: 0 0 0 -5px; + } + .nav-collapse { + clear: both; + } + .nav-collapse .nav { + float: none; + margin: 0 0 10px; + } + .nav-collapse .nav > li { + float: none; + } + .nav-collapse .nav > li > a { + margin-bottom: 2px; + } + .nav-collapse .nav > .divider-vertical { + display: none; + } + .nav-collapse .nav .nav-header { + color: #777777; + text-shadow: none; + } + .nav-collapse .nav > li > a, + .nav-collapse .dropdown-menu a { + padding: 9px 15px; + font-weight: bold; + color: #777777; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + } + .nav-collapse .btn { + padding: 4px 10px 4px; + font-weight: normal; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + } + .nav-collapse .dropdown-menu li + li a { + margin-bottom: 2px; + } + .nav-collapse .nav > li > a:hover, + .nav-collapse .nav > li > a:focus, + .nav-collapse .dropdown-menu a:hover, + .nav-collapse .dropdown-menu a:focus { + background-color: #f2f2f2; + } + .navbar-inverse .nav-collapse .nav > li > a, + .navbar-inverse .nav-collapse .dropdown-menu a { + color: #999999; + } + .navbar-inverse .nav-collapse .nav > li > a:hover, + .navbar-inverse .nav-collapse .nav > li > a:focus, + .navbar-inverse .nav-collapse .dropdown-menu a:hover, + .navbar-inverse .nav-collapse .dropdown-menu a:focus { + background-color: #111111; + } + .nav-collapse.in .btn-group { + padding: 0; + margin-top: 5px; + } + .nav-collapse .dropdown-menu { + position: static; + top: auto; + left: auto; + display: none; + float: none; + max-width: none; + padding: 0; + margin: 0 15px; + background-color: transparent; + border: none; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + } + .nav-collapse .open > .dropdown-menu { + display: block; + } + .nav-collapse .dropdown-menu:before, + .nav-collapse .dropdown-menu:after { + display: none; + } + .nav-collapse .dropdown-menu .divider { + display: none; + } + .nav-collapse .nav > li > .dropdown-menu:before, + .nav-collapse .nav > li > .dropdown-menu:after { + display: none; + } + .nav-collapse .navbar-form, + .nav-collapse .navbar-search { + float: none; + padding: 10px 15px; + margin: 10px 0; + border-top: 1px solid #f2f2f2; + border-bottom: 1px solid #f2f2f2; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); + -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); + } + .navbar-inverse .nav-collapse .navbar-form, + .navbar-inverse .nav-collapse .navbar-search { + border-top-color: #111111; + border-bottom-color: #111111; + } + .navbar .nav-collapse .nav.pull-right { + float: none; + margin-left: 0; + } + .nav-collapse, + .nav-collapse.collapse { + height: 0; + overflow: hidden; + } + .navbar .btn-navbar { + display: block; + } + .navbar-static .navbar-inner { + padding-right: 10px; + padding-left: 10px; + } +} + +@media (min-width: 980px) { + .nav-collapse.collapse { + height: auto !important; + overflow: visible !important; + } +} diff --git a/doc/themes/scikit-learn/static/css/bootstrap-responsive.min.css b/doc/themes/scikit-learn/static/css/bootstrap-responsive.min.css new file mode 100644 index 0000000000000..f4ede63f32e2e --- /dev/null +++ b/doc/themes/scikit-learn/static/css/bootstrap-responsive.min.css @@ -0,0 +1,9 @@ +/*! + * Bootstrap Responsive v2.3.2 + * + * Copyright 2012 Twitter, Inc + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world @twitter by @mdo and @fat. + */.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}@-ms-viewport{width:device-width}.hidden{display:none;visibility:hidden}.visible-phone{display:none!important}.visible-tablet{display:none!important}.hidden-desktop{display:none!important}.visible-desktop{display:inherit!important}@media(min-width:768px) and (max-width:979px){.hidden-desktop{display:inherit!important}.visible-desktop{display:none!important}.visible-tablet{display:inherit!important}.hidden-tablet{display:none!important}}@media(max-width:767px){.hidden-desktop{display:inherit!important}.visible-desktop{display:none!important}.visible-phone{display:inherit!important}.hidden-phone{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:inherit!important}.hidden-print{display:none!important}}@media(min-width:1200px){.row{margin-left:-30px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:30px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:1170px}.span12{width:1170px}.span11{width:1070px}.span10{width:970px}.span9{width:870px}.span8{width:770px}.span7{width:670px}.span6{width:570px}.span5{width:470px}.span4{width:370px}.span3{width:270px}.span2{width:170px}.span1{width:70px}.offset12{margin-left:1230px}.offset11{margin-left:1130px}.offset10{margin-left:1030px}.offset9{margin-left:930px}.offset8{margin-left:830px}.offset7{margin-left:730px}.offset6{margin-left:630px}.offset5{margin-left:530px}.offset4{margin-left:430px}.offset3{margin-left:330px}.offset2{margin-left:230px}.offset1{margin-left:130px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.564102564102564%;*margin-left:2.5109110747408616%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.564102564102564%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.45299145299145%;*width:91.39979996362975%}.row-fluid .span10{width:82.90598290598291%;*width:82.8527914166212%}.row-fluid .span9{width:74.35897435897436%;*width:74.30578286961266%}.row-fluid .span8{width:65.81196581196582%;*width:65.75877432260411%}.row-fluid .span7{width:57.26495726495726%;*width:57.21176577559556%}.row-fluid .span6{width:48.717948717948715%;*width:48.664757228587014%}.row-fluid .span5{width:40.17094017094017%;*width:40.11774868157847%}.row-fluid .span4{width:31.623931623931625%;*width:31.570740134569924%}.row-fluid .span3{width:23.076923076923077%;*width:23.023731587561375%}.row-fluid .span2{width:14.52991452991453%;*width:14.476723040552828%}.row-fluid .span1{width:5.982905982905983%;*width:5.929714493544281%}.row-fluid .offset12{margin-left:105.12820512820512%;*margin-left:105.02182214948171%}.row-fluid .offset12:first-child{margin-left:102.56410256410257%;*margin-left:102.45771958537915%}.row-fluid .offset11{margin-left:96.58119658119658%;*margin-left:96.47481360247316%}.row-fluid .offset11:first-child{margin-left:94.01709401709402%;*margin-left:93.91071103837061%}.row-fluid .offset10{margin-left:88.03418803418803%;*margin-left:87.92780505546462%}.row-fluid .offset10:first-child{margin-left:85.47008547008548%;*margin-left:85.36370249136206%}.row-fluid .offset9{margin-left:79.48717948717949%;*margin-left:79.38079650845607%}.row-fluid .offset9:first-child{margin-left:76.92307692307693%;*margin-left:76.81669394435352%}.row-fluid .offset8{margin-left:70.94017094017094%;*margin-left:70.83378796144753%}.row-fluid .offset8:first-child{margin-left:68.37606837606839%;*margin-left:68.26968539734497%}.row-fluid .offset7{margin-left:62.393162393162385%;*margin-left:62.28677941443899%}.row-fluid .offset7:first-child{margin-left:59.82905982905982%;*margin-left:59.72267685033642%}.row-fluid .offset6{margin-left:53.84615384615384%;*margin-left:53.739770867430444%}.row-fluid .offset6:first-child{margin-left:51.28205128205128%;*margin-left:51.175668303327875%}.row-fluid .offset5{margin-left:45.299145299145295%;*margin-left:45.1927623204219%}.row-fluid .offset5:first-child{margin-left:42.73504273504273%;*margin-left:42.62865975631933%}.row-fluid .offset4{margin-left:36.75213675213675%;*margin-left:36.645753773413354%}.row-fluid .offset4:first-child{margin-left:34.18803418803419%;*margin-left:34.081651209310785%}.row-fluid .offset3{margin-left:28.205128205128204%;*margin-left:28.0987452264048%}.row-fluid .offset3:first-child{margin-left:25.641025641025642%;*margin-left:25.53464266230224%}.row-fluid .offset2{margin-left:19.65811965811966%;*margin-left:19.551736679396257%}.row-fluid .offset2:first-child{margin-left:17.094017094017094%;*margin-left:16.98763411529369%}.row-fluid .offset1{margin-left:11.11111111111111%;*margin-left:11.004728132387708%}.row-fluid .offset1:first-child{margin-left:8.547008547008547%;*margin-left:8.440625568285142%}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:30px}input.span12,textarea.span12,.uneditable-input.span12{width:1156px}input.span11,textarea.span11,.uneditable-input.span11{width:1056px}input.span10,textarea.span10,.uneditable-input.span10{width:956px}input.span9,textarea.span9,.uneditable-input.span9{width:856px}input.span8,textarea.span8,.uneditable-input.span8{width:756px}input.span7,textarea.span7,.uneditable-input.span7{width:656px}input.span6,textarea.span6,.uneditable-input.span6{width:556px}input.span5,textarea.span5,.uneditable-input.span5{width:456px}input.span4,textarea.span4,.uneditable-input.span4{width:356px}input.span3,textarea.span3,.uneditable-input.span3{width:256px}input.span2,textarea.span2,.uneditable-input.span2{width:156px}input.span1,textarea.span1,.uneditable-input.span1{width:56px}.thumbnails{margin-left:-30px}.thumbnails>li{margin-left:30px}.row-fluid .thumbnails{margin-left:0}}@media(min-width:768px) and (max-width:979px){.row{margin-left:-20px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:20px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:724px}.span12{width:724px}.span11{width:662px}.span10{width:600px}.span9{width:538px}.span8{width:476px}.span7{width:414px}.span6{width:352px}.span5{width:290px}.span4{width:228px}.span3{width:166px}.span2{width:104px}.span1{width:42px}.offset12{margin-left:764px}.offset11{margin-left:702px}.offset10{margin-left:640px}.offset9{margin-left:578px}.offset8{margin-left:516px}.offset7{margin-left:454px}.offset6{margin-left:392px}.offset5{margin-left:330px}.offset4{margin-left:268px}.offset3{margin-left:206px}.offset2{margin-left:144px}.offset1{margin-left:82px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.7624309392265194%;*margin-left:2.709239449864817%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.7624309392265194%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.43646408839778%;*width:91.38327259903608%}.row-fluid .span10{width:82.87292817679558%;*width:82.81973668743387%}.row-fluid .span9{width:74.30939226519337%;*width:74.25620077583166%}.row-fluid .span8{width:65.74585635359117%;*width:65.69266486422946%}.row-fluid .span7{width:57.18232044198895%;*width:57.12912895262725%}.row-fluid .span6{width:48.61878453038674%;*width:48.56559304102504%}.row-fluid .span5{width:40.05524861878453%;*width:40.00205712942283%}.row-fluid .span4{width:31.491712707182323%;*width:31.43852121782062%}.row-fluid .span3{width:22.92817679558011%;*width:22.87498530621841%}.row-fluid .span2{width:14.3646408839779%;*width:14.311449394616199%}.row-fluid .span1{width:5.801104972375691%;*width:5.747913483013988%}.row-fluid .offset12{margin-left:105.52486187845304%;*margin-left:105.41847889972962%}.row-fluid .offset12:first-child{margin-left:102.76243093922652%;*margin-left:102.6560479605031%}.row-fluid .offset11{margin-left:96.96132596685082%;*margin-left:96.8549429881274%}.row-fluid .offset11:first-child{margin-left:94.1988950276243%;*margin-left:94.09251204890089%}.row-fluid .offset10{margin-left:88.39779005524862%;*margin-left:88.2914070765252%}.row-fluid .offset10:first-child{margin-left:85.6353591160221%;*margin-left:85.52897613729868%}.row-fluid .offset9{margin-left:79.8342541436464%;*margin-left:79.72787116492299%}.row-fluid .offset9:first-child{margin-left:77.07182320441989%;*margin-left:76.96544022569647%}.row-fluid .offset8{margin-left:71.2707182320442%;*margin-left:71.16433525332079%}.row-fluid .offset8:first-child{margin-left:68.50828729281768%;*margin-left:68.40190431409427%}.row-fluid .offset7{margin-left:62.70718232044199%;*margin-left:62.600799341718584%}.row-fluid .offset7:first-child{margin-left:59.94475138121547%;*margin-left:59.838368402492065%}.row-fluid .offset6{margin-left:54.14364640883978%;*margin-left:54.037263430116376%}.row-fluid .offset6:first-child{margin-left:51.38121546961326%;*margin-left:51.27483249088986%}.row-fluid .offset5{margin-left:45.58011049723757%;*margin-left:45.47372751851417%}.row-fluid .offset5:first-child{margin-left:42.81767955801105%;*margin-left:42.71129657928765%}.row-fluid .offset4{margin-left:37.01657458563536%;*margin-left:36.91019160691196%}.row-fluid .offset4:first-child{margin-left:34.25414364640884%;*margin-left:34.14776066768544%}.row-fluid .offset3{margin-left:28.45303867403315%;*margin-left:28.346655695309746%}.row-fluid .offset3:first-child{margin-left:25.69060773480663%;*margin-left:25.584224756083227%}.row-fluid .offset2{margin-left:19.88950276243094%;*margin-left:19.783119783707537%}.row-fluid .offset2:first-child{margin-left:17.12707182320442%;*margin-left:17.02068884448102%}.row-fluid .offset1{margin-left:11.32596685082873%;*margin-left:11.219583872105325%}.row-fluid .offset1:first-child{margin-left:8.56353591160221%;*margin-left:8.457152932878806%}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:20px}input.span12,textarea.span12,.uneditable-input.span12{width:710px}input.span11,textarea.span11,.uneditable-input.span11{width:648px}input.span10,textarea.span10,.uneditable-input.span10{width:586px}input.span9,textarea.span9,.uneditable-input.span9{width:524px}input.span8,textarea.span8,.uneditable-input.span8{width:462px}input.span7,textarea.span7,.uneditable-input.span7{width:400px}input.span6,textarea.span6,.uneditable-input.span6{width:338px}input.span5,textarea.span5,.uneditable-input.span5{width:276px}input.span4,textarea.span4,.uneditable-input.span4{width:214px}input.span3,textarea.span3,.uneditable-input.span3{width:152px}input.span2,textarea.span2,.uneditable-input.span2{width:90px}input.span1,textarea.span1,.uneditable-input.span1{width:28px}}@media(max-width:767px){body{padding-right:20px;padding-left:20px}.navbar-fixed-top,.navbar-fixed-bottom,.navbar-static-top{margin-right:-20px;margin-left:-20px}.container-fluid{padding:0}.dl-horizontal dt{float:none;width:auto;clear:none;text-align:left}.dl-horizontal dd{margin-left:0}.container{width:auto}.row-fluid{width:100%}.row,.thumbnails{margin-left:0}.thumbnails>li{float:none;margin-left:0}[class*="span"],.uneditable-input[class*="span"],.row-fluid [class*="span"]{display:block;float:none;width:100%;margin-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.span12,.row-fluid .span12{width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="offset"]:first-child{margin-left:0}.input-large,.input-xlarge,.input-xxlarge,input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.input-prepend input,.input-append input,.input-prepend input[class*="span"],.input-append input[class*="span"]{display:inline-block;width:auto}.controls-row [class*="span"]+[class*="span"]{margin-left:0}.modal{position:fixed;top:20px;right:20px;left:20px;width:auto;margin:0}.modal.fade{top:-100px}.modal.fade.in{top:20px}}@media(max-width:480px){.nav-collapse{-webkit-transform:translate3d(0,0,0)}.page-header h1 small{display:block;line-height:20px}input[type="checkbox"],input[type="radio"]{border:1px solid #ccc}.form-horizontal .control-label{float:none;width:auto;padding-top:0;text-align:left}.form-horizontal .controls{margin-left:0}.form-horizontal .control-list{padding-top:0}.form-horizontal .form-actions{padding-right:10px;padding-left:10px}.media .pull-left,.media .pull-right{display:block;float:none;margin-bottom:10px}.media-object{margin-right:0;margin-left:0}.modal{top:10px;right:10px;left:10px}.modal-header .close{padding:10px;margin:-10px}.carousel-caption{position:static}}@media(max-width:979px){body{padding-top:0}.navbar-fixed-top,.navbar-fixed-bottom{position:static}.navbar-fixed-top{margin-bottom:20px}.navbar-fixed-bottom{margin-top:20px}.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding:5px}.navbar .container{width:auto;padding:0}.navbar .brand{padding-right:10px;padding-left:10px;margin:0 0 0 -5px}.nav-collapse{clear:both}.nav-collapse .nav{float:none;margin:0 0 10px}.nav-collapse .nav>li{float:none}.nav-collapse .nav>li>a{margin-bottom:2px}.nav-collapse .nav>.divider-vertical{display:none}.nav-collapse .nav .nav-header{color:#777;text-shadow:none}.nav-collapse .nav>li>a,.nav-collapse .dropdown-menu a{padding:9px 15px;font-weight:bold;color:#777;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.nav-collapse .btn{padding:4px 10px 4px;font-weight:normal;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.nav-collapse .dropdown-menu li+li a{margin-bottom:2px}.nav-collapse .nav>li>a:hover,.nav-collapse .nav>li>a:focus,.nav-collapse .dropdown-menu a:hover,.nav-collapse .dropdown-menu a:focus{background-color:#f2f2f2}.navbar-inverse .nav-collapse .nav>li>a,.navbar-inverse .nav-collapse .dropdown-menu a{color:#999}.navbar-inverse .nav-collapse .nav>li>a:hover,.navbar-inverse .nav-collapse .nav>li>a:focus,.navbar-inverse .nav-collapse .dropdown-menu a:hover,.navbar-inverse .nav-collapse .dropdown-menu a:focus{background-color:#111}.nav-collapse.in .btn-group{padding:0;margin-top:5px}.nav-collapse .dropdown-menu{position:static;top:auto;left:auto;display:none;float:none;max-width:none;padding:0;margin:0 15px;background-color:transparent;border:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.nav-collapse .open>.dropdown-menu{display:block}.nav-collapse .dropdown-menu:before,.nav-collapse .dropdown-menu:after{display:none}.nav-collapse .dropdown-menu .divider{display:none}.nav-collapse .nav>li>.dropdown-menu:before,.nav-collapse .nav>li>.dropdown-menu:after{display:none}.nav-collapse .navbar-form,.nav-collapse .navbar-search{float:none;padding:10px 15px;margin:10px 0;border-top:1px solid #f2f2f2;border-bottom:1px solid #f2f2f2;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1)}.navbar-inverse .nav-collapse .navbar-form,.navbar-inverse .nav-collapse .navbar-search{border-top-color:#111;border-bottom-color:#111}.navbar .nav-collapse .nav.pull-right{float:none;margin-left:0}.nav-collapse,.nav-collapse.collapse{height:0;overflow:hidden}.navbar .btn-navbar{display:block}.navbar-static .navbar-inner{padding-right:10px;padding-left:10px}}@media(min-width:980px){.nav-collapse.collapse{height:auto!important;overflow:visible!important}} diff --git a/doc/themes/scikit-learn/static/css/bootstrap.css b/doc/themes/scikit-learn/static/css/bootstrap.css new file mode 100644 index 0000000000000..265f0e223e10d --- /dev/null +++ b/doc/themes/scikit-learn/static/css/bootstrap.css @@ -0,0 +1,6315 @@ +/*! + * Bootstrap v2.3.2 + * + * Copyright 2012 Twitter, Inc + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world @twitter by @mdo and @fat. + */ +.clearfix { + *zoom: 1; +} +.clearfix:before, +.clearfix:after { + display: table; + content: ""; + line-height: 0; +} +.clearfix:after { + clear: both; +} +.hide-text { + font: 0/0 a; + color: transparent; + text-shadow: none; + background-color: transparent; + border: 0; +} +.input-block-level { + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +nav, +section { + display: block; +} +audio, +canvas, +video { + display: inline-block; + *display: inline; + *zoom: 1; +} +audio:not([controls]) { + display: none; +} +html { + font-size: 100%; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; +} +a:focus { + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} +a:hover, +a:active { + outline: 0; +} +sub, +sup { + position: relative; + font-size: 75%; + line-height: 0; + vertical-align: baseline; +} +sup { + top: -0.5em; +} +sub { + bottom: -0.25em; +} +img { + /* Responsive images (ensure images don't scale beyond their parents) */ + + max-width: 100%; + /* Part 1: Set a maxium relative to the parent */ + + width: auto\9; + /* IE7-8 need help adjusting responsive images */ + + height: auto; + /* Part 2: Scale the height according to the width, otherwise you get stretching */ + + vertical-align: middle; + border: 0; + -ms-interpolation-mode: bicubic; +} +#map_canvas img, +.google-maps img { + max-width: none; +} +button, +input, +select, +textarea { + margin: 0; + font-size: 100%; + vertical-align: middle; +} +button, +input { + *overflow: visible; + line-height: normal; +} +button::-moz-focus-inner, +input::-moz-focus-inner { + padding: 0; + border: 0; +} +button, +html input[type="button"], +input[type="reset"], +input[type="submit"] { + -webkit-appearance: button; + cursor: pointer; +} +label, +select, +button, +input[type="button"], +input[type="reset"], +input[type="submit"], +input[type="radio"], +input[type="checkbox"] { + cursor: pointer; +} +input[type="search"] { + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; + -webkit-appearance: textfield; +} +input[type="search"]::-webkit-search-decoration, +input[type="search"]::-webkit-search-cancel-button { + -webkit-appearance: none; +} +textarea { + overflow: auto; + vertical-align: top; +} +@media print { + * { + text-shadow: none !important; + color: #000 !important; + background: transparent !important; + box-shadow: none !important; + } + a, + a:visited { + text-decoration: underline; + } + a[href]:after { + content: " (" attr(href) ")"; + } + abbr[title]:after { + content: " (" attr(title) ")"; + } + .ir a:after, + a[href^="javascript:"]:after, + a[href^="#"]:after { + content: ""; + } + pre, + blockquote { + border: 1px solid #999; + page-break-inside: avoid; + } + thead { + display: table-header-group; + } + tr, + img { + page-break-inside: avoid; + } + img { + max-width: 100% !important; + } + @page { + margin: 0.5cm; + } + p, + h2, + h3 { + orphans: 3; + widows: 3; + } + h2, + h3 { + page-break-after: avoid; + } +} +body { + margin: 0; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 20px; + color: #333333; + background-color: #ffffff; +} +a { + color: #0088cc; + text-decoration: none; +} +a:hover, +a:focus { + color: #005580; + text-decoration: underline; +} +.img-rounded { + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} +.img-polaroid { + padding: 4px; + background-color: #fff; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.2); + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); +} +.img-circle { + -webkit-border-radius: 500px; + -moz-border-radius: 500px; + border-radius: 500px; +} +.row { + margin-left: -20px; + *zoom: 1; +} +.row:before, +.row:after { + display: table; + content: ""; + line-height: 0; +} +.row:after { + clear: both; +} +[class*="span"] { + float: left; + min-height: 1px; + margin-left: 20px; +} +.container, +.navbar-static-top .container, +.navbar-fixed-top .container, +.navbar-fixed-bottom .container { + width: 940px; +} +.span12 { + width: 940px; +} +.span11 { + width: 860px; +} +.span10 { + width: 780px; +} +.span9 { + width: 700px; +} +.span8 { + width: 620px; +} +.span7 { + width: 540px; +} +.span6 { + width: 460px; +} +.span5 { + width: 380px; +} +.span4 { + width: 300px; +} +.span3 { + width: 220px; +} +.span2 { + width: 140px; +} +.span1 { + width: 60px; +} +.offset12 { + margin-left: 980px; +} +.offset11 { + margin-left: 900px; +} +.offset10 { + margin-left: 820px; +} +.offset9 { + margin-left: 740px; +} +.offset8 { + margin-left: 660px; +} +.offset7 { + margin-left: 580px; +} +.offset6 { + margin-left: 500px; +} +.offset5 { + margin-left: 420px; +} +.offset4 { + margin-left: 340px; +} +.offset3 { + margin-left: 260px; +} +.offset2 { + margin-left: 180px; +} +.offset1 { + margin-left: 100px; +} +.row-fluid { + width: 100%; + *zoom: 1; +} +.row-fluid:before, +.row-fluid:after { + display: table; + content: ""; + line-height: 0; +} +.row-fluid:after { + clear: both; +} +.row-fluid [class*="span"] { + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + float: left; + margin-left: 2.127659574468085%; + *margin-left: 2.074468085106383%; +} +.row-fluid [class*="span"]:first-child { + margin-left: 0; +} +.row-fluid .controls-row [class*="span"] + [class*="span"] { + margin-left: 2.127659574468085%; +} +.row-fluid .span12 { + width: 100%; + *width: 99.94680851063829%; +} +.row-fluid .span11 { + width: 91.48936170212765%; + *width: 91.43617021276594%; +} +.row-fluid .span10 { + width: 82.97872340425532%; + *width: 82.92553191489361%; +} +.row-fluid .span9 { + width: 74.46808510638297%; + *width: 74.41489361702126%; +} +.row-fluid .span8 { + width: 65.95744680851064%; + *width: 65.90425531914893%; +} +.row-fluid .span7 { + width: 57.44680851063829%; + *width: 57.39361702127659%; +} +.row-fluid .span6 { + width: 48.93617021276595%; + *width: 48.88297872340425%; +} +.row-fluid .span5 { + width: 40.42553191489362%; + *width: 40.37234042553192%; +} +.row-fluid .span4 { + width: 31.914893617021278%; + *width: 31.861702127659576%; +} +.row-fluid .span3 { + width: 23.404255319148934%; + *width: 23.351063829787233%; +} +.row-fluid .span2 { + width: 14.893617021276595%; + *width: 14.840425531914894%; +} +.row-fluid .span1 { + width: 6.382978723404255%; + *width: 6.329787234042553%; +} +.row-fluid .offset12 { + margin-left: 104.25531914893617%; + *margin-left: 104.14893617021275%; +} +.row-fluid .offset12:first-child { + margin-left: 102.12765957446808%; + *margin-left: 102.02127659574467%; +} +.row-fluid .offset11 { + margin-left: 95.74468085106382%; + *margin-left: 95.6382978723404%; +} +.row-fluid .offset11:first-child { + margin-left: 93.61702127659574%; + *margin-left: 93.51063829787232%; +} +.row-fluid .offset10 { + margin-left: 87.23404255319149%; + *margin-left: 87.12765957446807%; +} +.row-fluid .offset10:first-child { + margin-left: 85.1063829787234%; + *margin-left: 84.99999999999999%; +} +.row-fluid .offset9 { + margin-left: 78.72340425531914%; + *margin-left: 78.61702127659572%; +} +.row-fluid .offset9:first-child { + margin-left: 76.59574468085106%; + *margin-left: 76.48936170212764%; +} +.row-fluid .offset8 { + margin-left: 70.2127659574468%; + *margin-left: 70.10638297872339%; +} +.row-fluid .offset8:first-child { + margin-left: 68.08510638297872%; + *margin-left: 67.9787234042553%; +} +.row-fluid .offset7 { + margin-left: 61.70212765957446%; + *margin-left: 61.59574468085106%; +} +.row-fluid .offset7:first-child { + margin-left: 59.574468085106375%; + *margin-left: 59.46808510638297%; +} +.row-fluid .offset6 { + margin-left: 53.191489361702125%; + *margin-left: 53.085106382978715%; +} +.row-fluid .offset6:first-child { + margin-left: 51.063829787234035%; + *margin-left: 50.95744680851063%; +} +.row-fluid .offset5 { + margin-left: 44.68085106382979%; + *margin-left: 44.57446808510638%; +} +.row-fluid .offset5:first-child { + margin-left: 42.5531914893617%; + *margin-left: 42.4468085106383%; +} +.row-fluid .offset4 { + margin-left: 36.170212765957444%; + *margin-left: 36.06382978723405%; +} +.row-fluid .offset4:first-child { + margin-left: 34.04255319148936%; + *margin-left: 33.93617021276596%; +} +.row-fluid .offset3 { + margin-left: 27.659574468085104%; + *margin-left: 27.5531914893617%; +} +.row-fluid .offset3:first-child { + margin-left: 25.53191489361702%; + *margin-left: 25.425531914893618%; +} +.row-fluid .offset2 { + margin-left: 19.148936170212764%; + *margin-left: 19.04255319148936%; +} +.row-fluid .offset2:first-child { + margin-left: 17.02127659574468%; + *margin-left: 16.914893617021278%; +} +.row-fluid .offset1 { + margin-left: 10.638297872340425%; + *margin-left: 10.53191489361702%; +} +.row-fluid .offset1:first-child { + margin-left: 8.51063829787234%; + *margin-left: 8.404255319148938%; +} +[class*="span"].hide, +.row-fluid [class*="span"].hide { + display: none; +} +[class*="span"].pull-right, +.row-fluid [class*="span"].pull-right { + float: right; +} +.container { + margin-right: auto; + margin-left: auto; + *zoom: 1; +} +.container:before, +.container:after { + display: table; + content: ""; + line-height: 0; +} +.container:after { + clear: both; +} +.container-fluid { + padding-right: 20px; + padding-left: 20px; + *zoom: 1; +} +.container-fluid:before, +.container-fluid:after { + display: table; + content: ""; + line-height: 0; +} +.container-fluid:after { + clear: both; +} +p { + margin: 0 0 10px; +} +.lead { + margin-bottom: 20px; + font-size: 21px; + font-weight: 200; + line-height: 30px; +} +small { + font-size: 85%; +} +strong { + font-weight: bold; +} +em { + font-style: italic; +} +cite { + font-style: normal; +} +.muted { + color: #999999; +} +a.muted:hover, +a.muted:focus { + color: #808080; +} +.text-warning { + color: #c09853; +} +a.text-warning:hover, +a.text-warning:focus { + color: #a47e3c; +} +.text-error { + color: #b94a48; +} +a.text-error:hover, +a.text-error:focus { + color: #953b39; +} +.text-info { + color: #3a87ad; +} +a.text-info:hover, +a.text-info:focus { + color: #2d6987; +} +.text-success { + color: #468847; +} +a.text-success:hover, +a.text-success:focus { + color: #356635; +} +.text-left { + text-align: left; +} +.text-right { + text-align: right; +} +.text-center { + text-align: center; +} +h1, +h2, +h3, +h4, +h5, +h6 { + margin: 10px 0; + font-family: inherit; + font-weight: bold; + line-height: 20px; + color: inherit; + text-rendering: optimizelegibility; +} +h1 small, +h2 small, +h3 small, +h4 small, +h5 small, +h6 small { + font-weight: normal; + line-height: 1; + color: #999999; +} +h1, +h2, +h3 { + line-height: 40px; +} +h1 { + font-size: 38.5px; +} +h2 { + font-size: 31.5px; +} +h3 { + font-size: 24.5px; +} +h4 { + font-size: 17.5px; +} +h5 { + font-size: 14px; +} +h6 { + font-size: 11.9px; +} +h1 small { + font-size: 24.5px; +} +h2 small { + font-size: 17.5px; +} +h3 small { + font-size: 14px; +} +h4 small { + font-size: 14px; +} +.page-header { + padding-bottom: 9px; + margin: 20px 0 30px; + border-bottom: 1px solid #eeeeee; +} +ul, +ol { + padding: 0; + margin: 0 0 10px 25px; +} +ul ul, +ul ol, +ol ol, +ol ul { + margin-bottom: 0; +} +li { + line-height: 20px; +} +ul.unstyled, +ol.unstyled { + margin-left: 0; + list-style: none; +} +ul.inline, +ol.inline { + margin-left: 0; + list-style: none; +} +ul.inline > li, +ol.inline > li { + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ + + *zoom: 1; + padding-left: 5px; + padding-right: 5px; +} +dl { + margin-bottom: 20px; +} +dt, +dd { + line-height: 20px; +} +dt { + font-weight: bold; +} +dd { + margin-left: 10px; +} +.dl-horizontal { + *zoom: 1; +} +.dl-horizontal:before, +.dl-horizontal:after { + display: table; + content: ""; + line-height: 0; +} +.dl-horizontal:after { + clear: both; +} +.dl-horizontal dt { + float: left; + width: 160px; + clear: left; + text-align: right; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.dl-horizontal dd { + margin-left: 180px; +} +hr { + margin: 20px 0; + border: 0; + border-top: 1px solid #eeeeee; + border-bottom: 1px solid #ffffff; +} +abbr[title], +abbr[data-original-title] { + cursor: help; + border-bottom: 1px dotted #999999; +} +abbr.initialism { + font-size: 90%; + text-transform: uppercase; +} +blockquote { + padding: 0 0 0 15px; + margin: 0 0 20px; + border-left: 5px solid #eeeeee; +} +blockquote p { + margin-bottom: 0; + font-size: 17.5px; + font-weight: 300; + line-height: 1.25; +} +blockquote small { + display: block; + line-height: 20px; + color: #999999; +} +blockquote small:before { + content: '\2014 \00A0'; +} +blockquote.pull-right { + float: right; + padding-right: 15px; + padding-left: 0; + border-right: 5px solid #eeeeee; + border-left: 0; +} +blockquote.pull-right p, +blockquote.pull-right small { + text-align: right; +} +blockquote.pull-right small:before { + content: ''; +} +blockquote.pull-right small:after { + content: '\00A0 \2014'; +} +q:before, +q:after, +blockquote:before, +blockquote:after { + content: ""; +} +address { + display: block; + margin-bottom: 20px; + font-style: normal; + line-height: 20px; +} +code, +pre { + padding: 0 3px 2px; + font-family: Monaco, Menlo, Consolas, "Courier New", monospace; + font-size: 12px; + color: #333333; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} +code { + padding: 2px 4px; + color: #d14; + background-color: #f7f7f9; + border: 1px solid #e1e1e8; + white-space: nowrap; +} +pre { + display: block; + padding: 9.5px; + margin: 0 0 10px; + font-size: 13px; + line-height: 20px; + word-break: break-all; + word-wrap: break-word; + white-space: pre; + white-space: pre-wrap; + background-color: #f5f5f5; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.15); + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +pre.prettyprint { + margin-bottom: 20px; +} +pre code { + padding: 0; + color: inherit; + white-space: pre; + white-space: pre-wrap; + background-color: transparent; + border: 0; +} +.pre-scrollable { + max-height: 340px; + overflow-y: scroll; +} +.label, +.badge { + display: inline-block; + padding: 2px 4px; + font-size: 11.844px; + font-weight: bold; + line-height: 14px; + color: #ffffff; + vertical-align: baseline; + white-space: nowrap; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #999999; +} +.label { + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} +.badge { + padding-left: 9px; + padding-right: 9px; + -webkit-border-radius: 9px; + -moz-border-radius: 9px; + border-radius: 9px; +} +.label:empty, +.badge:empty { + display: none; +} +a.label:hover, +a.label:focus, +a.badge:hover, +a.badge:focus { + color: #ffffff; + text-decoration: none; + cursor: pointer; +} +.label-important, +.badge-important { + background-color: #b94a48; +} +.label-important[href], +.badge-important[href] { + background-color: #953b39; +} +.label-warning, +.badge-warning { + background-color: #f89406; +} +.label-warning[href], +.badge-warning[href] { + background-color: #c67605; +} +.label-success, +.badge-success { + background-color: #468847; +} +.label-success[href], +.badge-success[href] { + background-color: #356635; +} +.label-info, +.badge-info { + background-color: #3a87ad; +} +.label-info[href], +.badge-info[href] { + background-color: #2d6987; +} +.label-inverse, +.badge-inverse { + background-color: #333333; +} +.label-inverse[href], +.badge-inverse[href] { + background-color: #1a1a1a; +} +.btn .label, +.btn .badge { + position: relative; + top: -1px; +} +.btn-mini .label, +.btn-mini .badge { + top: 0; +} +table { + max-width: 100%; + background-color: transparent; + border-collapse: collapse; + border-spacing: 0; +} +.table { + width: 100%; + margin-bottom: 20px; +} +.table th, +.table td { + padding: 8px; + line-height: 20px; + text-align: left; + vertical-align: top; + border-top: 1px solid #dddddd; +} +.table th { + font-weight: bold; +} +.table thead th { + vertical-align: bottom; +} +.table caption + thead tr:first-child th, +.table caption + thead tr:first-child td, +.table colgroup + thead tr:first-child th, +.table colgroup + thead tr:first-child td, +.table thead:first-child tr:first-child th, +.table thead:first-child tr:first-child td { + border-top: 0; +} +.table tbody + tbody { + border-top: 2px solid #dddddd; +} +.table .table { + background-color: #ffffff; +} +.table-condensed th, +.table-condensed td { + padding: 4px 5px; +} +.table-bordered { + border: 1px solid #dddddd; + border-collapse: separate; + *border-collapse: collapse; + border-left: 0; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +.table-bordered th, +.table-bordered td { + border-left: 1px solid #dddddd; +} +.table-bordered caption + thead tr:first-child th, +.table-bordered caption + tbody tr:first-child th, +.table-bordered caption + tbody tr:first-child td, +.table-bordered colgroup + thead tr:first-child th, +.table-bordered colgroup + tbody tr:first-child th, +.table-bordered colgroup + tbody tr:first-child td, +.table-bordered thead:first-child tr:first-child th, +.table-bordered tbody:first-child tr:first-child th, +.table-bordered tbody:first-child tr:first-child td { + border-top: 0; +} +.table-bordered thead:first-child tr:first-child > th:first-child, +.table-bordered tbody:first-child tr:first-child > td:first-child, +.table-bordered tbody:first-child tr:first-child > th:first-child { + -webkit-border-top-left-radius: 4px; + -moz-border-radius-topleft: 4px; + border-top-left-radius: 4px; +} +.table-bordered thead:first-child tr:first-child > th:last-child, +.table-bordered tbody:first-child tr:first-child > td:last-child, +.table-bordered tbody:first-child tr:first-child > th:last-child { + -webkit-border-top-right-radius: 4px; + -moz-border-radius-topright: 4px; + border-top-right-radius: 4px; +} +.table-bordered thead:last-child tr:last-child > th:first-child, +.table-bordered tbody:last-child tr:last-child > td:first-child, +.table-bordered tbody:last-child tr:last-child > th:first-child, +.table-bordered tfoot:last-child tr:last-child > td:first-child, +.table-bordered tfoot:last-child tr:last-child > th:first-child { + -webkit-border-bottom-left-radius: 4px; + -moz-border-radius-bottomleft: 4px; + border-bottom-left-radius: 4px; +} +.table-bordered thead:last-child tr:last-child > th:last-child, +.table-bordered tbody:last-child tr:last-child > td:last-child, +.table-bordered tbody:last-child tr:last-child > th:last-child, +.table-bordered tfoot:last-child tr:last-child > td:last-child, +.table-bordered tfoot:last-child tr:last-child > th:last-child { + -webkit-border-bottom-right-radius: 4px; + -moz-border-radius-bottomright: 4px; + border-bottom-right-radius: 4px; +} +.table-bordered tfoot + tbody:last-child tr:last-child td:first-child { + -webkit-border-bottom-left-radius: 0; + -moz-border-radius-bottomleft: 0; + border-bottom-left-radius: 0; +} +.table-bordered tfoot + tbody:last-child tr:last-child td:last-child { + -webkit-border-bottom-right-radius: 0; + -moz-border-radius-bottomright: 0; + border-bottom-right-radius: 0; +} +.table-bordered caption + thead tr:first-child th:first-child, +.table-bordered caption + tbody tr:first-child td:first-child, +.table-bordered colgroup + thead tr:first-child th:first-child, +.table-bordered colgroup + tbody tr:first-child td:first-child { + -webkit-border-top-left-radius: 4px; + -moz-border-radius-topleft: 4px; + border-top-left-radius: 4px; +} +.table-bordered caption + thead tr:first-child th:last-child, +.table-bordered caption + tbody tr:first-child td:last-child, +.table-bordered colgroup + thead tr:first-child th:last-child, +.table-bordered colgroup + tbody tr:first-child td:last-child { + -webkit-border-top-right-radius: 4px; + -moz-border-radius-topright: 4px; + border-top-right-radius: 4px; +} +.table-striped tbody > tr:nth-child(odd) > td, +.table-striped tbody > tr:nth-child(odd) > th { + background-color: #f9f9f9; +} +.table-hover tbody tr:hover > td, +.table-hover tbody tr:hover > th { + background-color: #f5f5f5; +} +table td[class*="span"], +table th[class*="span"], +.row-fluid table td[class*="span"], +.row-fluid table th[class*="span"] { + display: table-cell; + float: none; + margin-left: 0; +} +.table td.span1, +.table th.span1 { + float: none; + width: 44px; + margin-left: 0; +} +.table td.span2, +.table th.span2 { + float: none; + width: 124px; + margin-left: 0; +} +.table td.span3, +.table th.span3 { + float: none; + width: 204px; + margin-left: 0; +} +.table td.span4, +.table th.span4 { + float: none; + width: 284px; + margin-left: 0; +} +.table td.span5, +.table th.span5 { + float: none; + width: 364px; + margin-left: 0; +} +.table td.span6, +.table th.span6 { + float: none; + width: 444px; + margin-left: 0; +} +.table td.span7, +.table th.span7 { + float: none; + width: 524px; + margin-left: 0; +} +.table td.span8, +.table th.span8 { + float: none; + width: 604px; + margin-left: 0; +} +.table td.span9, +.table th.span9 { + float: none; + width: 684px; + margin-left: 0; +} +.table td.span10, +.table th.span10 { + float: none; + width: 764px; + margin-left: 0; +} +.table td.span11, +.table th.span11 { + float: none; + width: 844px; + margin-left: 0; +} +.table td.span12, +.table th.span12 { + float: none; + width: 924px; + margin-left: 0; +} +.table tbody tr.success > td { + background-color: #dff0d8; +} +.table tbody tr.error > td { + background-color: #f2dede; +} +.table tbody tr.warning > td { + background-color: #fcf8e3; +} +.table tbody tr.info > td { + background-color: #d9edf7; +} +.table-hover tbody tr.success:hover > td { + background-color: #d0e9c6; +} +.table-hover tbody tr.error:hover > td { + background-color: #ebcccc; +} +.table-hover tbody tr.warning:hover > td { + background-color: #faf2cc; +} +.table-hover tbody tr.info:hover > td { + background-color: #c4e3f3; +} +form { + margin: 0 0 20px; +} +fieldset { + padding: 0; + margin: 0; + border: 0; +} +legend { + display: block; + width: 100%; + padding: 0; + margin-bottom: 20px; + font-size: 21px; + line-height: 40px; + color: #333333; + border: 0; + border-bottom: 1px solid #e5e5e5; +} +legend small { + font-size: 15px; + color: #999999; +} +label, +input, +button, +select, +textarea { + font-size: 14px; + font-weight: normal; + line-height: 20px; +} +input, +button, +select, +textarea { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; +} +label { + display: block; + margin-bottom: 5px; +} +select, +textarea, +input[type="text"], +input[type="password"], +input[type="datetime"], +input[type="datetime-local"], +input[type="date"], +input[type="month"], +input[type="time"], +input[type="week"], +input[type="number"], +input[type="email"], +input[type="url"], +input[type="search"], +input[type="tel"], +input[type="color"], +.uneditable-input { + display: inline-block; + height: 20px; + padding: 4px 6px; + margin-bottom: 10px; + font-size: 14px; + line-height: 20px; + color: #555555; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + vertical-align: middle; +} +input, +textarea, +.uneditable-input { + width: 206px; +} +textarea { + height: auto; +} +textarea, +input[type="text"], +input[type="password"], +input[type="datetime"], +input[type="datetime-local"], +input[type="date"], +input[type="month"], +input[type="time"], +input[type="week"], +input[type="number"], +input[type="email"], +input[type="url"], +input[type="search"], +input[type="tel"], +input[type="color"], +.uneditable-input { + background-color: #ffffff; + border: 1px solid #cccccc; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -webkit-transition: border linear .2s, box-shadow linear .2s; + -moz-transition: border linear .2s, box-shadow linear .2s; + -o-transition: border linear .2s, box-shadow linear .2s; + transition: border linear .2s, box-shadow linear .2s; +} +textarea:focus, +input[type="text"]:focus, +input[type="password"]:focus, +input[type="datetime"]:focus, +input[type="datetime-local"]:focus, +input[type="date"]:focus, +input[type="month"]:focus, +input[type="time"]:focus, +input[type="week"]:focus, +input[type="number"]:focus, +input[type="email"]:focus, +input[type="url"]:focus, +input[type="search"]:focus, +input[type="tel"]:focus, +input[type="color"]:focus, +.uneditable-input:focus { + border-color: rgba(82, 168, 236, 0.8); + outline: 0; + outline: thin dotted \9; + /* IE6-9 */ + + -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); + -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); + box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); +} +input[type="radio"], +input[type="checkbox"] { + margin: 4px 0 0; + *margin-top: 0; + /* IE7 */ + + margin-top: 1px \9; + /* IE8-9 */ + + line-height: normal; +} +input[type="file"], +input[type="image"], +input[type="submit"], +input[type="reset"], +input[type="button"], +input[type="radio"], +input[type="checkbox"] { + width: auto; +} +select, +input[type="file"] { + height: 30px; + /* In IE7, the height of the select element cannot be changed by height, only font-size */ + + *margin-top: 4px; + /* For IE7, add top margin to align select with labels */ + + line-height: 30px; +} +select { + width: 220px; + border: 1px solid #cccccc; + background-color: #ffffff; +} +select[multiple], +select[size] { + height: auto; +} +select:focus, +input[type="file"]:focus, +input[type="radio"]:focus, +input[type="checkbox"]:focus { + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} +.uneditable-input, +.uneditable-textarea { + color: #999999; + background-color: #fcfcfc; + border-color: #cccccc; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + cursor: not-allowed; +} +.uneditable-input { + overflow: hidden; + white-space: nowrap; +} +.uneditable-textarea { + width: auto; + height: auto; +} +input:-moz-placeholder, +textarea:-moz-placeholder { + color: #999999; +} +input:-ms-input-placeholder, +textarea:-ms-input-placeholder { + color: #999999; +} +input::-webkit-input-placeholder, +textarea::-webkit-input-placeholder { + color: #999999; +} +.radio, +.checkbox { + min-height: 20px; + padding-left: 20px; +} +.radio input[type="radio"], +.checkbox input[type="checkbox"] { + float: left; + margin-left: -20px; +} +.controls > .radio:first-child, +.controls > .checkbox:first-child { + padding-top: 5px; +} +.radio.inline, +.checkbox.inline { + display: inline-block; + padding-top: 5px; + margin-bottom: 0; + vertical-align: middle; +} +.radio.inline + .radio.inline, +.checkbox.inline + .checkbox.inline { + margin-left: 10px; +} +.input-mini { + width: 60px; +} +.input-small { + width: 90px; +} +.input-medium { + width: 150px; +} +.input-large { + width: 210px; +} +.input-xlarge { + width: 270px; +} +.input-xxlarge { + width: 530px; +} +input[class*="span"], +select[class*="span"], +textarea[class*="span"], +.uneditable-input[class*="span"], +.row-fluid input[class*="span"], +.row-fluid select[class*="span"], +.row-fluid textarea[class*="span"], +.row-fluid .uneditable-input[class*="span"] { + float: none; + margin-left: 0; +} +.input-append input[class*="span"], +.input-append .uneditable-input[class*="span"], +.input-prepend input[class*="span"], +.input-prepend .uneditable-input[class*="span"], +.row-fluid input[class*="span"], +.row-fluid select[class*="span"], +.row-fluid textarea[class*="span"], +.row-fluid .uneditable-input[class*="span"], +.row-fluid .input-prepend [class*="span"], +.row-fluid .input-append [class*="span"] { + display: inline-block; +} +input, +textarea, +.uneditable-input { + margin-left: 0; +} +.controls-row [class*="span"] + [class*="span"] { + margin-left: 20px; +} +input.span12, +textarea.span12, +.uneditable-input.span12 { + width: 926px; +} +input.span11, +textarea.span11, +.uneditable-input.span11 { + width: 846px; +} +input.span10, +textarea.span10, +.uneditable-input.span10 { + width: 766px; +} +input.span9, +textarea.span9, +.uneditable-input.span9 { + width: 686px; +} +input.span8, +textarea.span8, +.uneditable-input.span8 { + width: 606px; +} +input.span7, +textarea.span7, +.uneditable-input.span7 { + width: 526px; +} +input.span6, +textarea.span6, +.uneditable-input.span6 { + width: 446px; +} +input.span5, +textarea.span5, +.uneditable-input.span5 { + width: 366px; +} +input.span4, +textarea.span4, +.uneditable-input.span4 { + width: 286px; +} +input.span3, +textarea.span3, +.uneditable-input.span3 { + width: 206px; +} +input.span2, +textarea.span2, +.uneditable-input.span2 { + width: 126px; +} +input.span1, +textarea.span1, +.uneditable-input.span1 { + width: 46px; +} +.controls-row { + *zoom: 1; +} +.controls-row:before, +.controls-row:after { + display: table; + content: ""; + line-height: 0; +} +.controls-row:after { + clear: both; +} +.controls-row [class*="span"], +.row-fluid .controls-row [class*="span"] { + float: left; +} +.controls-row .checkbox[class*="span"], +.controls-row .radio[class*="span"] { + padding-top: 5px; +} +input[disabled], +select[disabled], +textarea[disabled], +input[readonly], +select[readonly], +textarea[readonly] { + cursor: not-allowed; + background-color: #eeeeee; +} +input[type="radio"][disabled], +input[type="checkbox"][disabled], +input[type="radio"][readonly], +input[type="checkbox"][readonly] { + background-color: transparent; +} +.control-group.warning .control-label, +.control-group.warning .help-block, +.control-group.warning .help-inline { + color: #c09853; +} +.control-group.warning .checkbox, +.control-group.warning .radio, +.control-group.warning input, +.control-group.warning select, +.control-group.warning textarea { + color: #c09853; +} +.control-group.warning input, +.control-group.warning select, +.control-group.warning textarea { + border-color: #c09853; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); +} +.control-group.warning input:focus, +.control-group.warning select:focus, +.control-group.warning textarea:focus { + border-color: #a47e3c; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; +} +.control-group.warning .input-prepend .add-on, +.control-group.warning .input-append .add-on { + color: #c09853; + background-color: #fcf8e3; + border-color: #c09853; +} +.control-group.error .control-label, +.control-group.error .help-block, +.control-group.error .help-inline { + color: #b94a48; +} +.control-group.error .checkbox, +.control-group.error .radio, +.control-group.error input, +.control-group.error select, +.control-group.error textarea { + color: #b94a48; +} +.control-group.error input, +.control-group.error select, +.control-group.error textarea { + border-color: #b94a48; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); +} +.control-group.error input:focus, +.control-group.error select:focus, +.control-group.error textarea:focus { + border-color: #953b39; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; +} +.control-group.error .input-prepend .add-on, +.control-group.error .input-append .add-on { + color: #b94a48; + background-color: #f2dede; + border-color: #b94a48; +} +.control-group.success .control-label, +.control-group.success .help-block, +.control-group.success .help-inline { + color: #468847; +} +.control-group.success .checkbox, +.control-group.success .radio, +.control-group.success input, +.control-group.success select, +.control-group.success textarea { + color: #468847; +} +.control-group.success input, +.control-group.success select, +.control-group.success textarea { + border-color: #468847; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); +} +.control-group.success input:focus, +.control-group.success select:focus, +.control-group.success textarea:focus { + border-color: #356635; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; +} +.control-group.success .input-prepend .add-on, +.control-group.success .input-append .add-on { + color: #468847; + background-color: #dff0d8; + border-color: #468847; +} +.control-group.info .control-label, +.control-group.info .help-block, +.control-group.info .help-inline { + color: #3a87ad; +} +.control-group.info .checkbox, +.control-group.info .radio, +.control-group.info input, +.control-group.info select, +.control-group.info textarea { + color: #3a87ad; +} +.control-group.info input, +.control-group.info select, +.control-group.info textarea { + border-color: #3a87ad; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); +} +.control-group.info input:focus, +.control-group.info select:focus, +.control-group.info textarea:focus { + border-color: #2d6987; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; +} +.control-group.info .input-prepend .add-on, +.control-group.info .input-append .add-on { + color: #3a87ad; + background-color: #d9edf7; + border-color: #3a87ad; +} +input:focus:invalid, +textarea:focus:invalid, +select:focus:invalid { + color: #b94a48; + border-color: #ee5f5b; +} +input:focus:invalid:focus, +textarea:focus:invalid:focus, +select:focus:invalid:focus { + border-color: #e9322d; + -webkit-box-shadow: 0 0 6px #f8b9b7; + -moz-box-shadow: 0 0 6px #f8b9b7; + box-shadow: 0 0 6px #f8b9b7; +} +.form-actions { + padding: 19px 20px 20px; + margin-top: 20px; + margin-bottom: 20px; + background-color: #f5f5f5; + border-top: 1px solid #e5e5e5; + *zoom: 1; +} +.form-actions:before, +.form-actions:after { + display: table; + content: ""; + line-height: 0; +} +.form-actions:after { + clear: both; +} +.help-block, +.help-inline { + color: #595959; +} +.help-block { + display: block; + margin-bottom: 10px; +} +.help-inline { + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ + + *zoom: 1; + vertical-align: middle; + padding-left: 5px; +} +.input-append, +.input-prepend { + display: inline-block; + margin-bottom: 10px; + vertical-align: middle; + font-size: 0; + white-space: nowrap; +} +.input-append input, +.input-prepend input, +.input-append select, +.input-prepend select, +.input-append .uneditable-input, +.input-prepend .uneditable-input, +.input-append .dropdown-menu, +.input-prepend .dropdown-menu, +.input-append .popover, +.input-prepend .popover { + font-size: 14px; +} +.input-append input, +.input-prepend input, +.input-append select, +.input-prepend select, +.input-append .uneditable-input, +.input-prepend .uneditable-input { + position: relative; + margin-bottom: 0; + *margin-left: 0; + vertical-align: top; + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; +} +.input-append input:focus, +.input-prepend input:focus, +.input-append select:focus, +.input-prepend select:focus, +.input-append .uneditable-input:focus, +.input-prepend .uneditable-input:focus { + z-index: 2; +} +.input-append .add-on, +.input-prepend .add-on { + display: inline-block; + width: auto; + height: 20px; + min-width: 16px; + padding: 4px 5px; + font-size: 14px; + font-weight: normal; + line-height: 20px; + text-align: center; + text-shadow: 0 1px 0 #ffffff; + background-color: #eeeeee; + border: 1px solid #ccc; +} +.input-append .add-on, +.input-prepend .add-on, +.input-append .btn, +.input-prepend .btn, +.input-append .btn-group > .dropdown-toggle, +.input-prepend .btn-group > .dropdown-toggle { + vertical-align: top; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +.input-append .active, +.input-prepend .active { + background-color: #a9dba9; + border-color: #46a546; +} +.input-prepend .add-on, +.input-prepend .btn { + margin-right: -1px; +} +.input-prepend .add-on:first-child, +.input-prepend .btn:first-child { + -webkit-border-radius: 4px 0 0 4px; + -moz-border-radius: 4px 0 0 4px; + border-radius: 4px 0 0 4px; +} +.input-append input, +.input-append select, +.input-append .uneditable-input { + -webkit-border-radius: 4px 0 0 4px; + -moz-border-radius: 4px 0 0 4px; + border-radius: 4px 0 0 4px; +} +.input-append input + .btn-group .btn:last-child, +.input-append select + .btn-group .btn:last-child, +.input-append .uneditable-input + .btn-group .btn:last-child { + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; +} +.input-append .add-on, +.input-append .btn, +.input-append .btn-group { + margin-left: -1px; +} +.input-append .add-on:last-child, +.input-append .btn:last-child, +.input-append .btn-group:last-child > .dropdown-toggle { + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; +} +.input-prepend.input-append input, +.input-prepend.input-append select, +.input-prepend.input-append .uneditable-input { + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +.input-prepend.input-append input + .btn-group .btn, +.input-prepend.input-append select + .btn-group .btn, +.input-prepend.input-append .uneditable-input + .btn-group .btn { + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; +} +.input-prepend.input-append .add-on:first-child, +.input-prepend.input-append .btn:first-child { + margin-right: -1px; + -webkit-border-radius: 4px 0 0 4px; + -moz-border-radius: 4px 0 0 4px; + border-radius: 4px 0 0 4px; +} +.input-prepend.input-append .add-on:last-child, +.input-prepend.input-append .btn:last-child { + margin-left: -1px; + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; +} +.input-prepend.input-append .btn-group:first-child { + margin-left: 0; +} +input.search-query { + padding-right: 14px; + padding-right: 4px \9; + padding-left: 14px; + padding-left: 4px \9; + /* IE7-8 doesn't have border-radius, so don't indent the padding */ + + margin-bottom: 0; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; +} +/* Allow for input prepend/append in search forms */ +.form-search .input-append .search-query, +.form-search .input-prepend .search-query { + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +.form-search .input-append .search-query { + -webkit-border-radius: 14px 0 0 14px; + -moz-border-radius: 14px 0 0 14px; + border-radius: 14px 0 0 14px; +} +.form-search .input-append .btn { + -webkit-border-radius: 0 14px 14px 0; + -moz-border-radius: 0 14px 14px 0; + border-radius: 0 14px 14px 0; +} +.form-search .input-prepend .search-query { + -webkit-border-radius: 0 14px 14px 0; + -moz-border-radius: 0 14px 14px 0; + border-radius: 0 14px 14px 0; +} +.form-search .input-prepend .btn { + -webkit-border-radius: 14px 0 0 14px; + -moz-border-radius: 14px 0 0 14px; + border-radius: 14px 0 0 14px; +} +.form-search input, +.form-inline input, +.form-horizontal input, +.form-search textarea, +.form-inline textarea, +.form-horizontal textarea, +.form-search select, +.form-inline select, +.form-horizontal select, +.form-search .help-inline, +.form-inline .help-inline, +.form-horizontal .help-inline, +.form-search .uneditable-input, +.form-inline .uneditable-input, +.form-horizontal .uneditable-input, +.form-search .input-prepend, +.form-inline .input-prepend, +.form-horizontal .input-prepend, +.form-search .input-append, +.form-inline .input-append, +.form-horizontal .input-append { + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ + + *zoom: 1; + margin-bottom: 0; + vertical-align: middle; +} +.form-search .hide, +.form-inline .hide, +.form-horizontal .hide { + display: none; +} +.form-search label, +.form-inline label, +.form-search .btn-group, +.form-inline .btn-group { + display: inline-block; +} +.form-search .input-append, +.form-inline .input-append, +.form-search .input-prepend, +.form-inline .input-prepend { + margin-bottom: 0; +} +.form-search .radio, +.form-search .checkbox, +.form-inline .radio, +.form-inline .checkbox { + padding-left: 0; + margin-bottom: 0; + vertical-align: middle; +} +.form-search .radio input[type="radio"], +.form-search .checkbox input[type="checkbox"], +.form-inline .radio input[type="radio"], +.form-inline .checkbox input[type="checkbox"] { + float: left; + margin-right: 3px; + margin-left: 0; +} +.control-group { + margin-bottom: 10px; +} +legend + .control-group { + margin-top: 20px; + -webkit-margin-top-collapse: separate; +} +.form-horizontal .control-group { + margin-bottom: 20px; + *zoom: 1; +} +.form-horizontal .control-group:before, +.form-horizontal .control-group:after { + display: table; + content: ""; + line-height: 0; +} +.form-horizontal .control-group:after { + clear: both; +} +.form-horizontal .control-label { + float: left; + width: 160px; + padding-top: 5px; + text-align: right; +} +.form-horizontal .controls { + *display: inline-block; + *padding-left: 20px; + margin-left: 180px; + *margin-left: 0; +} +.form-horizontal .controls:first-child { + *padding-left: 180px; +} +.form-horizontal .help-block { + margin-bottom: 0; +} +.form-horizontal input + .help-block, +.form-horizontal select + .help-block, +.form-horizontal textarea + .help-block, +.form-horizontal .uneditable-input + .help-block, +.form-horizontal .input-prepend + .help-block, +.form-horizontal .input-append + .help-block { + margin-top: 10px; +} +.form-horizontal .form-actions { + padding-left: 180px; +} +.btn { + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ + + *zoom: 1; + padding: 4px 12px; + margin-bottom: 0; + font-size: 14px; + line-height: 20px; + text-align: center; + vertical-align: middle; + cursor: pointer; + color: #333333; + text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); + background-color: #f5f5f5; + background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6)); + background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6); + background-image: -o-linear-gradient(top, #ffffff, #e6e6e6); + background-image: linear-gradient(to bottom, #ffffff, #e6e6e6); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0); + border-color: #e6e6e6 #e6e6e6 #bfbfbf; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + *background-color: #e6e6e6; + /* Darken IE7 buttons by default so they stand out more given they won't have borders */ + + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + border: 1px solid #cccccc; + *border: 0; + border-bottom-color: #b3b3b3; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + *margin-left: .3em; + -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); + -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); + box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); +} +.btn:hover, +.btn:focus, +.btn:active, +.btn.active, +.btn.disabled, +.btn[disabled] { + color: #333333; + background-color: #e6e6e6; + *background-color: #d9d9d9; +} +.btn:active, +.btn.active { + background-color: #cccccc \9; +} +.btn:first-child { + *margin-left: 0; +} +.btn:hover, +.btn:focus { + color: #333333; + text-decoration: none; + background-position: 0 -15px; + -webkit-transition: background-position 0.1s linear; + -moz-transition: background-position 0.1s linear; + -o-transition: background-position 0.1s linear; + transition: background-position 0.1s linear; +} +.btn:focus { + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} +.btn.active, +.btn:active { + background-image: none; + outline: 0; + -webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); + -moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); + box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); +} +.btn.disabled, +.btn[disabled] { + cursor: default; + background-image: none; + opacity: 0.65; + filter: alpha(opacity=65); + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} +.btn-large { + padding: 11px 19px; + font-size: 17.5px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} +.btn-large [class^="icon-"], +.btn-large [class*=" icon-"] { + margin-top: 4px; +} +.btn-small { + padding: 2px 10px; + font-size: 11.9px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} +.btn-small [class^="icon-"], +.btn-small [class*=" icon-"] { + margin-top: 0; +} +.btn-mini [class^="icon-"], +.btn-mini [class*=" icon-"] { + margin-top: -1px; +} +.btn-mini { + padding: 0 6px; + font-size: 10.5px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} +.btn-block { + display: block; + width: 100%; + padding-left: 0; + padding-right: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} +.btn-block + .btn-block { + margin-top: 5px; +} +input[type="submit"].btn-block, +input[type="reset"].btn-block, +input[type="button"].btn-block { + width: 100%; +} +.btn-primary.active, +.btn-warning.active, +.btn-danger.active, +.btn-success.active, +.btn-info.active, +.btn-inverse.active { + color: rgba(255, 255, 255, 0.75); +} +.btn-primary { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #006dcc; + background-image: -moz-linear-gradient(top, #0088cc, #0044cc); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc)); + background-image: -webkit-linear-gradient(top, #0088cc, #0044cc); + background-image: -o-linear-gradient(top, #0088cc, #0044cc); + background-image: linear-gradient(to bottom, #0088cc, #0044cc); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0); + border-color: #0044cc #0044cc #002a80; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + *background-color: #0044cc; + /* Darken IE7 buttons by default so they stand out more given they won't have borders */ + + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); +} +.btn-primary:hover, +.btn-primary:focus, +.btn-primary:active, +.btn-primary.active, +.btn-primary.disabled, +.btn-primary[disabled] { + color: #ffffff; + background-color: #0044cc; + *background-color: #003bb3; +} +.btn-primary:active, +.btn-primary.active { + background-color: #003399 \9; +} +.btn-warning { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #faa732; + background-image: -moz-linear-gradient(top, #fbb450, #f89406); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); + background-image: -webkit-linear-gradient(top, #fbb450, #f89406); + background-image: -o-linear-gradient(top, #fbb450, #f89406); + background-image: linear-gradient(to bottom, #fbb450, #f89406); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); + border-color: #f89406 #f89406 #ad6704; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + *background-color: #f89406; + /* Darken IE7 buttons by default so they stand out more given they won't have borders */ + + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); +} +.btn-warning:hover, +.btn-warning:focus, +.btn-warning:active, +.btn-warning.active, +.btn-warning.disabled, +.btn-warning[disabled] { + color: #ffffff; + background-color: #f89406; + *background-color: #df8505; +} +.btn-warning:active, +.btn-warning.active { + background-color: #c67605 \9; +} +.btn-danger { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #da4f49; + background-image: -moz-linear-gradient(top, #ee5f5b, #bd362f); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f)); + background-image: -webkit-linear-gradient(top, #ee5f5b, #bd362f); + background-image: -o-linear-gradient(top, #ee5f5b, #bd362f); + background-image: linear-gradient(to bottom, #ee5f5b, #bd362f); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0); + border-color: #bd362f #bd362f #802420; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + *background-color: #bd362f; + /* Darken IE7 buttons by default so they stand out more given they won't have borders */ + + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); +} +.btn-danger:hover, +.btn-danger:focus, +.btn-danger:active, +.btn-danger.active, +.btn-danger.disabled, +.btn-danger[disabled] { + color: #ffffff; + background-color: #bd362f; + *background-color: #a9302a; +} +.btn-danger:active, +.btn-danger.active { + background-color: #942a25 \9; +} +.btn-success { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #5bb75b; + background-image: -moz-linear-gradient(top, #62c462, #51a351); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351)); + background-image: -webkit-linear-gradient(top, #62c462, #51a351); + background-image: -o-linear-gradient(top, #62c462, #51a351); + background-image: linear-gradient(to bottom, #62c462, #51a351); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0); + border-color: #51a351 #51a351 #387038; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + *background-color: #51a351; + /* Darken IE7 buttons by default so they stand out more given they won't have borders */ + + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); +} +.btn-success:hover, +.btn-success:focus, +.btn-success:active, +.btn-success.active, +.btn-success.disabled, +.btn-success[disabled] { + color: #ffffff; + background-color: #51a351; + *background-color: #499249; +} +.btn-success:active, +.btn-success.active { + background-color: #408140 \9; +} +.btn-info { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #49afcd; + background-image: -moz-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4)); + background-image: -webkit-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -o-linear-gradient(top, #5bc0de, #2f96b4); + background-image: linear-gradient(to bottom, #5bc0de, #2f96b4); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0); + border-color: #2f96b4 #2f96b4 #1f6377; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + *background-color: #2f96b4; + /* Darken IE7 buttons by default so they stand out more given they won't have borders */ + + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); +} +.btn-info:hover, +.btn-info:focus, +.btn-info:active, +.btn-info.active, +.btn-info.disabled, +.btn-info[disabled] { + color: #ffffff; + background-color: #2f96b4; + *background-color: #2a85a0; +} +.btn-info:active, +.btn-info.active { + background-color: #24748c \9; +} +.btn-inverse { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #363636; + background-image: -moz-linear-gradient(top, #444444, #222222); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222)); + background-image: -webkit-linear-gradient(top, #444444, #222222); + background-image: -o-linear-gradient(top, #444444, #222222); + background-image: linear-gradient(to bottom, #444444, #222222); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0); + border-color: #222222 #222222 #000000; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + *background-color: #222222; + /* Darken IE7 buttons by default so they stand out more given they won't have borders */ + + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); +} +.btn-inverse:hover, +.btn-inverse:focus, +.btn-inverse:active, +.btn-inverse.active, +.btn-inverse.disabled, +.btn-inverse[disabled] { + color: #ffffff; + background-color: #222222; + *background-color: #151515; +} +.btn-inverse:active, +.btn-inverse.active { + background-color: #080808 \9; +} +button.btn, +input[type="submit"].btn { + *padding-top: 3px; + *padding-bottom: 3px; +} +button.btn::-moz-focus-inner, +input[type="submit"].btn::-moz-focus-inner { + padding: 0; + border: 0; +} +button.btn.btn-large, +input[type="submit"].btn.btn-large { + *padding-top: 7px; + *padding-bottom: 7px; +} +button.btn.btn-small, +input[type="submit"].btn.btn-small { + *padding-top: 3px; + *padding-bottom: 3px; +} +button.btn.btn-mini, +input[type="submit"].btn.btn-mini { + *padding-top: 1px; + *padding-bottom: 1px; +} +.btn-link, +.btn-link:active, +.btn-link[disabled] { + background-color: transparent; + background-image: none; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} +.btn-link { + border-color: transparent; + cursor: pointer; + color: #0088cc; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +.btn-link:hover, +.btn-link:focus { + color: #005580; + text-decoration: underline; + background-color: transparent; +} +.btn-link[disabled]:hover, +.btn-link[disabled]:focus { + color: #333333; + text-decoration: none; +} +[class^="icon-"], +[class*=" icon-"] { + display: inline-block; + width: 14px; + height: 14px; + *margin-right: .3em; + line-height: 14px; + vertical-align: text-top; + background-image: url("http://github.com/img/glyphicons-halflings.png"); + background-position: 14px 14px; + background-repeat: no-repeat; + margin-top: 1px; +} +/* White icons with optional class, or on hover/focus/active states of certain elements */ +.icon-white, +.nav-pills > .active > a > [class^="icon-"], +.nav-pills > .active > a > [class*=" icon-"], +.nav-list > .active > a > [class^="icon-"], +.nav-list > .active > a > [class*=" icon-"], +.navbar-inverse .nav > .active > a > [class^="icon-"], +.navbar-inverse .nav > .active > a > [class*=" icon-"], +.dropdown-menu > li > a:hover > [class^="icon-"], +.dropdown-menu > li > a:focus > [class^="icon-"], +.dropdown-menu > li > a:hover > [class*=" icon-"], +.dropdown-menu > li > a:focus > [class*=" icon-"], +.dropdown-menu > .active > a > [class^="icon-"], +.dropdown-menu > .active > a > [class*=" icon-"], +.dropdown-submenu:hover > a > [class^="icon-"], +.dropdown-submenu:focus > a > [class^="icon-"], +.dropdown-submenu:hover > a > [class*=" icon-"], +.dropdown-submenu:focus > a > [class*=" icon-"] { + background-image: url("http://github.com/img/glyphicons-halflings-white.png"); +} +.icon-glass { + background-position: 0 0; +} +.icon-music { + background-position: -24px 0; +} +.icon-search { + background-position: -48px 0; +} +.icon-envelope { + background-position: -72px 0; +} +.icon-heart { + background-position: -96px 0; +} +.icon-star { + background-position: -120px 0; +} +.icon-star-empty { + background-position: -144px 0; +} +.icon-user { + background-position: -168px 0; +} +.icon-film { + background-position: -192px 0; +} +.icon-th-large { + background-position: -216px 0; +} +.icon-th { + background-position: -240px 0; +} +.icon-th-list { + background-position: -264px 0; +} +.icon-ok { + background-position: -288px 0; +} +.icon-remove { + background-position: -312px 0; +} +.icon-zoom-in { + background-position: -336px 0; +} +.icon-zoom-out { + background-position: -360px 0; +} +.icon-off { + background-position: -384px 0; +} +.icon-signal { + background-position: -408px 0; +} +.icon-cog { + background-position: -432px 0; +} +.icon-trash { + background-position: -456px 0; +} +.icon-home { + background-position: 0 -24px; +} +.icon-file { + background-position: -24px -24px; +} +.icon-time { + background-position: -48px -24px; +} +.icon-road { + background-position: -72px -24px; +} +.icon-download-alt { + background-position: -96px -24px; +} +.icon-download { + background-position: -120px -24px; +} +.icon-upload { + background-position: -144px -24px; +} +.icon-inbox { + background-position: -168px -24px; +} +.icon-play-circle { + background-position: -192px -24px; +} +.icon-repeat { + background-position: -216px -24px; +} +.icon-refresh { + background-position: -240px -24px; +} +.icon-list-alt { + background-position: -264px -24px; +} +.icon-lock { + background-position: -287px -24px; +} +.icon-flag { + background-position: -312px -24px; +} +.icon-headphones { + background-position: -336px -24px; +} +.icon-volume-off { + background-position: -360px -24px; +} +.icon-volume-down { + background-position: -384px -24px; +} +.icon-volume-up { + background-position: -408px -24px; +} +.icon-qrcode { + background-position: -432px -24px; +} +.icon-barcode { + background-position: -456px -24px; +} +.icon-tag { + background-position: 0 -48px; +} +.icon-tags { + background-position: -25px -48px; +} +.icon-book { + background-position: -48px -48px; +} +.icon-bookmark { + background-position: -72px -48px; +} +.icon-print { + background-position: -96px -48px; +} +.icon-camera { + background-position: -120px -48px; +} +.icon-font { + background-position: -144px -48px; +} +.icon-bold { + background-position: -167px -48px; +} +.icon-italic { + background-position: -192px -48px; +} +.icon-text-height { + background-position: -216px -48px; +} +.icon-text-width { + background-position: -240px -48px; +} +.icon-align-left { + background-position: -264px -48px; +} +.icon-align-center { + background-position: -288px -48px; +} +.icon-align-right { + background-position: -312px -48px; +} +.icon-align-justify { + background-position: -336px -48px; +} +.icon-list { + background-position: -360px -48px; +} +.icon-indent-left { + background-position: -384px -48px; +} +.icon-indent-right { + background-position: -408px -48px; +} +.icon-facetime-video { + background-position: -432px -48px; +} +.icon-picture { + background-position: -456px -48px; +} +.icon-pencil { + background-position: 0 -72px; +} +.icon-map-marker { + background-position: -24px -72px; +} +.icon-adjust { + background-position: -48px -72px; +} +.icon-tint { + background-position: -72px -72px; +} +.icon-edit { + background-position: -96px -72px; +} +.icon-share { + background-position: -120px -72px; +} +.icon-check { + background-position: -144px -72px; +} +.icon-move { + background-position: -168px -72px; +} +.icon-step-backward { + background-position: -192px -72px; +} +.icon-fast-backward { + background-position: -216px -72px; +} +.icon-backward { + background-position: -240px -72px; +} +.icon-play { + background-position: -264px -72px; +} +.icon-pause { + background-position: -288px -72px; +} +.icon-stop { + background-position: -312px -72px; +} +.icon-forward { + background-position: -336px -72px; +} +.icon-fast-forward { + background-position: -360px -72px; +} +.icon-step-forward { + background-position: -384px -72px; +} +.icon-eject { + background-position: -408px -72px; +} +.icon-chevron-left { + background-position: -432px -72px; +} +.icon-chevron-right { + background-position: -456px -72px; +} +.icon-plus-sign { + background-position: 0 -96px; +} +.icon-minus-sign { + background-position: -24px -96px; +} +.icon-remove-sign { + background-position: -48px -96px; +} +.icon-ok-sign { + background-position: -72px -96px; +} +.icon-question-sign { + background-position: -96px -96px; +} +.icon-info-sign { + background-position: -120px -96px; +} +.icon-screenshot { + background-position: -144px -96px; +} +.icon-remove-circle { + background-position: -168px -96px; +} +.icon-ok-circle { + background-position: -192px -96px; +} +.icon-ban-circle { + background-position: -216px -96px; +} +.icon-arrow-left { + background-position: -240px -96px; +} +.icon-arrow-right { + background-position: -264px -96px; +} +.icon-arrow-up { + background-position: -289px -96px; +} +.icon-arrow-down { + background-position: -312px -96px; +} +.icon-share-alt { + background-position: -336px -96px; +} +.icon-resize-full { + background-position: -360px -96px; +} +.icon-resize-small { + background-position: -384px -96px; +} +.icon-plus { + background-position: -408px -96px; +} +.icon-minus { + background-position: -433px -96px; +} +.icon-asterisk { + background-position: -456px -96px; +} +.icon-exclamation-sign { + background-position: 0 -120px; +} +.icon-gift { + background-position: -24px -120px; +} +.icon-leaf { + background-position: -48px -120px; +} +.icon-fire { + background-position: -72px -120px; +} +.icon-eye-open { + background-position: -96px -120px; +} +.icon-eye-close { + background-position: -120px -120px; +} +.icon-warning-sign { + background-position: -144px -120px; +} +.icon-plane { + background-position: -168px -120px; +} +.icon-calendar { + background-position: -192px -120px; +} +.icon-random { + background-position: -216px -120px; + width: 16px; +} +.icon-comment { + background-position: -240px -120px; +} +.icon-magnet { + background-position: -264px -120px; +} +.icon-chevron-up { + background-position: -288px -120px; +} +.icon-chevron-down { + background-position: -313px -119px; +} +.icon-retweet { + background-position: -336px -120px; +} +.icon-shopping-cart { + background-position: -360px -120px; +} +.icon-folder-close { + background-position: -384px -120px; + width: 16px; +} +.icon-folder-open { + background-position: -408px -120px; + width: 16px; +} +.icon-resize-vertical { + background-position: -432px -119px; +} +.icon-resize-horizontal { + background-position: -456px -118px; +} +.icon-hdd { + background-position: 0 -144px; +} +.icon-bullhorn { + background-position: -24px -144px; +} +.icon-bell { + background-position: -48px -144px; +} +.icon-certificate { + background-position: -72px -144px; +} +.icon-thumbs-up { + background-position: -96px -144px; +} +.icon-thumbs-down { + background-position: -120px -144px; +} +.icon-hand-right { + background-position: -144px -144px; +} +.icon-hand-left { + background-position: -168px -144px; +} +.icon-hand-up { + background-position: -192px -144px; +} +.icon-hand-down { + background-position: -216px -144px; +} +.icon-circle-arrow-right { + background-position: -240px -144px; +} +.icon-circle-arrow-left { + background-position: -264px -144px; +} +.icon-circle-arrow-up { + background-position: -288px -144px; +} +.icon-circle-arrow-down { + background-position: -312px -144px; +} +.icon-globe { + background-position: -336px -144px; +} +.icon-wrench { + background-position: -360px -144px; +} +.icon-tasks { + background-position: -384px -144px; +} +.icon-filter { + background-position: -408px -144px; +} +.icon-briefcase { + background-position: -432px -144px; +} +.icon-fullscreen { + background-position: -456px -144px; +} +.btn-group { + position: relative; + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ + + *zoom: 1; + font-size: 0; + vertical-align: middle; + white-space: nowrap; + *margin-left: .3em; +} +.btn-group:first-child { + *margin-left: 0; +} +.btn-group + .btn-group { + margin-left: 5px; +} +.btn-toolbar { + font-size: 0; + margin-top: 10px; + margin-bottom: 10px; +} +.btn-toolbar > .btn + .btn, +.btn-toolbar > .btn-group + .btn, +.btn-toolbar > .btn + .btn-group { + margin-left: 5px; +} +.btn-group > .btn { + position: relative; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +.btn-group > .btn + .btn { + margin-left: -1px; +} +.btn-group > .btn, +.btn-group > .dropdown-menu, +.btn-group > .popover { + font-size: 14px; +} +.btn-group > .btn-mini { + font-size: 10.5px; +} +.btn-group > .btn-small { + font-size: 11.9px; +} +.btn-group > .btn-large { + font-size: 17.5px; +} +.btn-group > .btn:first-child { + margin-left: 0; + -webkit-border-top-left-radius: 4px; + -moz-border-radius-topleft: 4px; + border-top-left-radius: 4px; + -webkit-border-bottom-left-radius: 4px; + -moz-border-radius-bottomleft: 4px; + border-bottom-left-radius: 4px; +} +.btn-group > .btn:last-child, +.btn-group > .dropdown-toggle { + -webkit-border-top-right-radius: 4px; + -moz-border-radius-topright: 4px; + border-top-right-radius: 4px; + -webkit-border-bottom-right-radius: 4px; + -moz-border-radius-bottomright: 4px; + border-bottom-right-radius: 4px; +} +.btn-group > .btn.large:first-child { + margin-left: 0; + -webkit-border-top-left-radius: 6px; + -moz-border-radius-topleft: 6px; + border-top-left-radius: 6px; + -webkit-border-bottom-left-radius: 6px; + -moz-border-radius-bottomleft: 6px; + border-bottom-left-radius: 6px; +} +.btn-group > .btn.large:last-child, +.btn-group > .large.dropdown-toggle { + -webkit-border-top-right-radius: 6px; + -moz-border-radius-topright: 6px; + border-top-right-radius: 6px; + -webkit-border-bottom-right-radius: 6px; + -moz-border-radius-bottomright: 6px; + border-bottom-right-radius: 6px; +} +.btn-group > .btn:hover, +.btn-group > .btn:focus, +.btn-group > .btn:active, +.btn-group > .btn.active { + z-index: 2; +} +.btn-group .dropdown-toggle:active, +.btn-group.open .dropdown-toggle { + outline: 0; +} +.btn-group > .btn + .dropdown-toggle { + padding-left: 8px; + padding-right: 8px; + -webkit-box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); + -moz-box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); + box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); + *padding-top: 5px; + *padding-bottom: 5px; +} +.btn-group > .btn-mini + .dropdown-toggle { + padding-left: 5px; + padding-right: 5px; + *padding-top: 2px; + *padding-bottom: 2px; +} +.btn-group > .btn-small + .dropdown-toggle { + *padding-top: 5px; + *padding-bottom: 4px; +} +.btn-group > .btn-large + .dropdown-toggle { + padding-left: 12px; + padding-right: 12px; + *padding-top: 7px; + *padding-bottom: 7px; +} +.btn-group.open .dropdown-toggle { + background-image: none; + -webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); + -moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); + box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); +} +.btn-group.open .btn.dropdown-toggle { + background-color: #e6e6e6; +} +.btn-group.open .btn-primary.dropdown-toggle { + background-color: #0044cc; +} +.btn-group.open .btn-warning.dropdown-toggle { + background-color: #f89406; +} +.btn-group.open .btn-danger.dropdown-toggle { + background-color: #bd362f; +} +.btn-group.open .btn-success.dropdown-toggle { + background-color: #51a351; +} +.btn-group.open .btn-info.dropdown-toggle { + background-color: #2f96b4; +} +.btn-group.open .btn-inverse.dropdown-toggle { + background-color: #222222; +} +.btn .caret { + margin-top: 8px; + margin-left: 0; +} +.btn-large .caret { + margin-top: 6px; +} +.btn-large .caret { + border-left-width: 5px; + border-right-width: 5px; + border-top-width: 5px; +} +.btn-mini .caret, +.btn-small .caret { + margin-top: 8px; +} +.dropup .btn-large .caret { + border-bottom-width: 5px; +} +.btn-primary .caret, +.btn-warning .caret, +.btn-danger .caret, +.btn-info .caret, +.btn-success .caret, +.btn-inverse .caret { + border-top-color: #ffffff; + border-bottom-color: #ffffff; +} +.btn-group-vertical { + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ + + *zoom: 1; +} +.btn-group-vertical > .btn { + display: block; + float: none; + max-width: 100%; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +.btn-group-vertical > .btn + .btn { + margin-left: 0; + margin-top: -1px; +} +.btn-group-vertical > .btn:first-child { + -webkit-border-radius: 4px 4px 0 0; + -moz-border-radius: 4px 4px 0 0; + border-radius: 4px 4px 0 0; +} +.btn-group-vertical > .btn:last-child { + -webkit-border-radius: 0 0 4px 4px; + -moz-border-radius: 0 0 4px 4px; + border-radius: 0 0 4px 4px; +} +.btn-group-vertical > .btn-large:first-child { + -webkit-border-radius: 6px 6px 0 0; + -moz-border-radius: 6px 6px 0 0; + border-radius: 6px 6px 0 0; +} +.btn-group-vertical > .btn-large:last-child { + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; +} +.nav { + margin-left: 0; + margin-bottom: 20px; + list-style: none; +} +.nav > li > a { + display: block; +} +.nav > li > a:hover, +.nav > li > a:focus { + text-decoration: none; + background-color: #eeeeee; +} +.nav > li > a > img { + max-width: none; +} +.nav > .pull-right { + float: right; +} +.nav-header { + display: block; + padding: 3px 15px; + font-size: 11px; + font-weight: bold; + line-height: 20px; + color: #999999; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + text-transform: uppercase; +} +.nav li + .nav-header { + margin-top: 9px; +} +.nav-list { + padding-left: 15px; + padding-right: 15px; + margin-bottom: 0; +} +.nav-list > li > a, +.nav-list .nav-header { + margin-left: -15px; + margin-right: -15px; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); +} +.nav-list > li > a { + padding: 3px 15px; +} +.nav-list > .active > a, +.nav-list > .active > a:hover, +.nav-list > .active > a:focus { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); + background-color: #0088cc; +} +.nav-list [class^="icon-"], +.nav-list [class*=" icon-"] { + margin-right: 2px; +} +.nav-list .divider { + *width: 100%; + height: 1px; + margin: 9px 1px; + *margin: -5px 0 5px; + overflow: hidden; + background-color: #e5e5e5; + border-bottom: 1px solid #ffffff; +} +.nav-tabs, +.nav-pills { + *zoom: 1; +} +.nav-tabs:before, +.nav-pills:before, +.nav-tabs:after, +.nav-pills:after { + display: table; + content: ""; + line-height: 0; +} +.nav-tabs:after, +.nav-pills:after { + clear: both; +} +.nav-tabs > li, +.nav-pills > li { + float: left; +} +.nav-tabs > li > a, +.nav-pills > li > a { + padding-right: 12px; + padding-left: 12px; + margin-right: 2px; + line-height: 14px; +} +.nav-tabs { + border-bottom: 1px solid #ddd; +} +.nav-tabs > li { + margin-bottom: -1px; +} +.nav-tabs > li > a { + padding-top: 8px; + padding-bottom: 8px; + line-height: 20px; + border: 1px solid transparent; + -webkit-border-radius: 4px 4px 0 0; + -moz-border-radius: 4px 4px 0 0; + border-radius: 4px 4px 0 0; +} +.nav-tabs > li > a:hover, +.nav-tabs > li > a:focus { + border-color: #eeeeee #eeeeee #dddddd; +} +.nav-tabs > .active > a, +.nav-tabs > .active > a:hover, +.nav-tabs > .active > a:focus { + color: #555555; + background-color: #ffffff; + border: 1px solid #ddd; + border-bottom-color: transparent; + cursor: default; +} +.nav-pills > li > a { + padding-top: 8px; + padding-bottom: 8px; + margin-top: 2px; + margin-bottom: 2px; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} +.nav-pills > .active > a, +.nav-pills > .active > a:hover, +.nav-pills > .active > a:focus { + color: #ffffff; + background-color: #0088cc; +} +.nav-stacked > li { + float: none; +} +.nav-stacked > li > a { + margin-right: 0; +} +.nav-tabs.nav-stacked { + border-bottom: 0; +} +.nav-tabs.nav-stacked > li > a { + border: 1px solid #ddd; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +.nav-tabs.nav-stacked > li:first-child > a { + -webkit-border-top-right-radius: 4px; + -moz-border-radius-topright: 4px; + border-top-right-radius: 4px; + -webkit-border-top-left-radius: 4px; + -moz-border-radius-topleft: 4px; + border-top-left-radius: 4px; +} +.nav-tabs.nav-stacked > li:last-child > a { + -webkit-border-bottom-right-radius: 4px; + -moz-border-radius-bottomright: 4px; + border-bottom-right-radius: 4px; + -webkit-border-bottom-left-radius: 4px; + -moz-border-radius-bottomleft: 4px; + border-bottom-left-radius: 4px; +} +.nav-tabs.nav-stacked > li > a:hover, +.nav-tabs.nav-stacked > li > a:focus { + border-color: #ddd; + z-index: 2; +} +.nav-pills.nav-stacked > li > a { + margin-bottom: 3px; +} +.nav-pills.nav-stacked > li:last-child > a { + margin-bottom: 1px; +} +.nav-tabs .dropdown-menu { + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; +} +.nav-pills .dropdown-menu { + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} +.nav .dropdown-toggle .caret { + border-top-color: #0088cc; + border-bottom-color: #0088cc; + margin-top: 6px; +} +.nav .dropdown-toggle:hover .caret, +.nav .dropdown-toggle:focus .caret { + border-top-color: #005580; + border-bottom-color: #005580; +} +/* move down carets for tabs */ +.nav-tabs .dropdown-toggle .caret { + margin-top: 8px; +} +.nav .active .dropdown-toggle .caret { + border-top-color: #fff; + border-bottom-color: #fff; +} +.nav-tabs .active .dropdown-toggle .caret { + border-top-color: #555555; + border-bottom-color: #555555; +} +.nav > .dropdown.active > a:hover, +.nav > .dropdown.active > a:focus { + cursor: pointer; +} +.nav-tabs .open .dropdown-toggle, +.nav-pills .open .dropdown-toggle, +.nav > li.dropdown.open.active > a:hover, +.nav > li.dropdown.open.active > a:focus { + color: #ffffff; + background-color: #999999; + border-color: #999999; +} +.nav li.dropdown.open .caret, +.nav li.dropdown.open.active .caret, +.nav li.dropdown.open a:hover .caret, +.nav li.dropdown.open a:focus .caret { + border-top-color: #ffffff; + border-bottom-color: #ffffff; + opacity: 1; + filter: alpha(opacity=100); +} +.tabs-stacked .open > a:hover, +.tabs-stacked .open > a:focus { + border-color: #999999; +} +.tabbable { + *zoom: 1; +} +.tabbable:before, +.tabbable:after { + display: table; + content: ""; + line-height: 0; +} +.tabbable:after { + clear: both; +} +.tab-content { + overflow: auto; +} +.tabs-below > .nav-tabs, +.tabs-right > .nav-tabs, +.tabs-left > .nav-tabs { + border-bottom: 0; +} +.tab-content > .tab-pane, +.pill-content > .pill-pane { + display: none; +} +.tab-content > .active, +.pill-content > .active { + display: block; +} +.tabs-below > .nav-tabs { + border-top: 1px solid #ddd; +} +.tabs-below > .nav-tabs > li { + margin-top: -1px; + margin-bottom: 0; +} +.tabs-below > .nav-tabs > li > a { + -webkit-border-radius: 0 0 4px 4px; + -moz-border-radius: 0 0 4px 4px; + border-radius: 0 0 4px 4px; +} +.tabs-below > .nav-tabs > li > a:hover, +.tabs-below > .nav-tabs > li > a:focus { + border-bottom-color: transparent; + border-top-color: #ddd; +} +.tabs-below > .nav-tabs > .active > a, +.tabs-below > .nav-tabs > .active > a:hover, +.tabs-below > .nav-tabs > .active > a:focus { + border-color: transparent #ddd #ddd #ddd; +} +.tabs-left > .nav-tabs > li, +.tabs-right > .nav-tabs > li { + float: none; +} +.tabs-left > .nav-tabs > li > a, +.tabs-right > .nav-tabs > li > a { + min-width: 74px; + margin-right: 0; + margin-bottom: 3px; +} +.tabs-left > .nav-tabs { + float: left; + margin-right: 19px; + border-right: 1px solid #ddd; +} +.tabs-left > .nav-tabs > li > a { + margin-right: -1px; + -webkit-border-radius: 4px 0 0 4px; + -moz-border-radius: 4px 0 0 4px; + border-radius: 4px 0 0 4px; +} +.tabs-left > .nav-tabs > li > a:hover, +.tabs-left > .nav-tabs > li > a:focus { + border-color: #eeeeee #dddddd #eeeeee #eeeeee; +} +.tabs-left > .nav-tabs .active > a, +.tabs-left > .nav-tabs .active > a:hover, +.tabs-left > .nav-tabs .active > a:focus { + border-color: #ddd transparent #ddd #ddd; + *border-right-color: #ffffff; +} +.tabs-right > .nav-tabs { + float: right; + margin-left: 19px; + border-left: 1px solid #ddd; +} +.tabs-right > .nav-tabs > li > a { + margin-left: -1px; + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; +} +.tabs-right > .nav-tabs > li > a:hover, +.tabs-right > .nav-tabs > li > a:focus { + border-color: #eeeeee #eeeeee #eeeeee #dddddd; +} +.tabs-right > .nav-tabs .active > a, +.tabs-right > .nav-tabs .active > a:hover, +.tabs-right > .nav-tabs .active > a:focus { + border-color: #ddd #ddd #ddd transparent; + *border-left-color: #ffffff; +} +.nav > .disabled > a { + color: #999999; +} +.nav > .disabled > a:hover, +.nav > .disabled > a:focus { + text-decoration: none; + background-color: transparent; + cursor: default; +} +.navbar { + overflow: visible; + margin-bottom: 20px; + *position: relative; + *z-index: 2; +} +.navbar-inner { + min-height: 40px; + padding-left: 20px; + padding-right: 20px; + background-color: #fafafa; + background-image: -moz-linear-gradient(top, #ffffff, #f2f2f2); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2)); + background-image: -webkit-linear-gradient(top, #ffffff, #f2f2f2); + background-image: -o-linear-gradient(top, #ffffff, #f2f2f2); + background-image: linear-gradient(to bottom, #ffffff, #f2f2f2); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff2f2f2', GradientType=0); + border: 1px solid #d4d4d4; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); + -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); + box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); + *zoom: 1; +} +.navbar-inner:before, +.navbar-inner:after { + display: table; + content: ""; + line-height: 0; +} +.navbar-inner:after { + clear: both; +} +.navbar .container { + width: auto; +} +.nav-collapse.collapse { + height: auto; + overflow: visible; +} +.navbar .brand { + float: left; + display: block; + padding: 10px 20px 10px; + margin-left: -20px; + font-size: 20px; + font-weight: 200; + color: #777777; + text-shadow: 0 1px 0 #ffffff; +} +.navbar .brand:hover, +.navbar .brand:focus { + text-decoration: none; +} +.navbar-text { + margin-bottom: 0; + line-height: 40px; + color: #777777; +} +.navbar-link { + color: #777777; +} +.navbar-link:hover, +.navbar-link:focus { + color: #333333; +} +.navbar .divider-vertical { + height: 40px; + margin: 0 9px; + border-left: 1px solid #f2f2f2; + border-right: 1px solid #ffffff; +} +.navbar .btn, +.navbar .btn-group { + margin-top: 5px; +} +.navbar .btn-group .btn, +.navbar .input-prepend .btn, +.navbar .input-append .btn, +.navbar .input-prepend .btn-group, +.navbar .input-append .btn-group { + margin-top: 0; +} +.navbar-form { + margin-bottom: 0; + *zoom: 1; +} +.navbar-form:before, +.navbar-form:after { + display: table; + content: ""; + line-height: 0; +} +.navbar-form:after { + clear: both; +} +.navbar-form input, +.navbar-form select, +.navbar-form .radio, +.navbar-form .checkbox { + margin-top: 5px; +} +.navbar-form input, +.navbar-form select, +.navbar-form .btn { + display: inline-block; + margin-bottom: 0; +} +.navbar-form input[type="image"], +.navbar-form input[type="checkbox"], +.navbar-form input[type="radio"] { + margin-top: 3px; +} +.navbar-form .input-append, +.navbar-form .input-prepend { + margin-top: 5px; + white-space: nowrap; +} +.navbar-form .input-append input, +.navbar-form .input-prepend input { + margin-top: 0; +} +.navbar-search { + position: relative; + float: left; + margin-top: 5px; + margin-bottom: 0; +} +.navbar-search .search-query { + margin-bottom: 0; + padding: 4px 14px; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 13px; + font-weight: normal; + line-height: 1; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; +} +.navbar-static-top { + position: static; + margin-bottom: 0; +} +.navbar-static-top .navbar-inner { + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +.navbar-fixed-top, +.navbar-fixed-bottom { + position: fixed; + right: 0; + left: 0; + z-index: 1030; + margin-bottom: 0; +} +.navbar-fixed-top .navbar-inner, +.navbar-static-top .navbar-inner { + border-width: 0 0 1px; +} +.navbar-fixed-bottom .navbar-inner { + border-width: 1px 0 0; +} +.navbar-fixed-top .navbar-inner, +.navbar-fixed-bottom .navbar-inner { + padding-left: 0; + padding-right: 0; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +.navbar-static-top .container, +.navbar-fixed-top .container, +.navbar-fixed-bottom .container { + width: 940px; +} +.navbar-fixed-top { + top: 0; +} +.navbar-fixed-top .navbar-inner, +.navbar-static-top .navbar-inner { + -webkit-box-shadow: 0 1px 10px rgba(0,0,0,.1); + -moz-box-shadow: 0 1px 10px rgba(0,0,0,.1); + box-shadow: 0 1px 10px rgba(0,0,0,.1); +} +.navbar-fixed-bottom { + bottom: 0; +} +.navbar-fixed-bottom .navbar-inner { + -webkit-box-shadow: 0 -1px 10px rgba(0,0,0,.1); + -moz-box-shadow: 0 -1px 10px rgba(0,0,0,.1); + box-shadow: 0 -1px 10px rgba(0,0,0,.1); +} +.navbar .nav { + position: relative; + left: 0; + display: block; + float: left; + margin: 0 10px 0 0; +} +.navbar .nav.pull-right { + float: right; + margin-right: 0; +} +.navbar .nav > li { + float: left; +} +.navbar .nav > li > a { + float: none; + padding: 10px 15px 10px; + color: #777777; + text-decoration: none; + text-shadow: 0 1px 0 #ffffff; +} +.navbar .nav .dropdown-toggle .caret { + margin-top: 8px; +} +.navbar .nav > li > a:focus, +.navbar .nav > li > a:hover { + background-color: transparent; + color: #333333; + text-decoration: none; +} +.navbar .nav > .active > a, +.navbar .nav > .active > a:hover, +.navbar .nav > .active > a:focus { + color: #555555; + text-decoration: none; + background-color: #e5e5e5; + -webkit-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); + -moz-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); + box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); +} +.navbar .btn-navbar { + display: none; + float: right; + padding: 7px 10px; + margin-left: 5px; + margin-right: 5px; + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #ededed; + background-image: -moz-linear-gradient(top, #f2f2f2, #e5e5e5); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#e5e5e5)); + background-image: -webkit-linear-gradient(top, #f2f2f2, #e5e5e5); + background-image: -o-linear-gradient(top, #f2f2f2, #e5e5e5); + background-image: linear-gradient(to bottom, #f2f2f2, #e5e5e5); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2', endColorstr='#ffe5e5e5', GradientType=0); + border-color: #e5e5e5 #e5e5e5 #bfbfbf; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + *background-color: #e5e5e5; + /* Darken IE7 buttons by default so they stand out more given they won't have borders */ + + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); + -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); + box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); +} +.navbar .btn-navbar:hover, +.navbar .btn-navbar:focus, +.navbar .btn-navbar:active, +.navbar .btn-navbar.active, +.navbar .btn-navbar.disabled, +.navbar .btn-navbar[disabled] { + color: #ffffff; + background-color: #e5e5e5; + *background-color: #d9d9d9; +} +.navbar .btn-navbar:active, +.navbar .btn-navbar.active { + background-color: #cccccc \9; +} +.navbar .btn-navbar .icon-bar { + display: block; + width: 18px; + height: 2px; + background-color: #f5f5f5; + -webkit-border-radius: 1px; + -moz-border-radius: 1px; + border-radius: 1px; + -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); + -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); + box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); +} +.btn-navbar .icon-bar + .icon-bar { + margin-top: 3px; +} +.navbar .nav > li > .dropdown-menu:before { + content: ''; + display: inline-block; + border-left: 7px solid transparent; + border-right: 7px solid transparent; + border-bottom: 7px solid #ccc; + border-bottom-color: rgba(0, 0, 0, 0.2); + position: absolute; + top: -7px; + left: 9px; +} +.navbar .nav > li > .dropdown-menu:after { + content: ''; + display: inline-block; + border-left: 6px solid transparent; + border-right: 6px solid transparent; + border-bottom: 6px solid #ffffff; + position: absolute; + top: -6px; + left: 10px; +} +.navbar-fixed-bottom .nav > li > .dropdown-menu:before { + border-top: 7px solid #ccc; + border-top-color: rgba(0, 0, 0, 0.2); + border-bottom: 0; + bottom: -7px; + top: auto; +} +.navbar-fixed-bottom .nav > li > .dropdown-menu:after { + border-top: 6px solid #ffffff; + border-bottom: 0; + bottom: -6px; + top: auto; +} +.navbar .nav li.dropdown > a:hover .caret, +.navbar .nav li.dropdown > a:focus .caret { + border-top-color: #333333; + border-bottom-color: #333333; +} +.navbar .nav li.dropdown.open > .dropdown-toggle, +.navbar .nav li.dropdown.active > .dropdown-toggle, +.navbar .nav li.dropdown.open.active > .dropdown-toggle { + background-color: #e5e5e5; + color: #555555; +} +.navbar .nav li.dropdown > .dropdown-toggle .caret { + border-top-color: #777777; + border-bottom-color: #777777; +} +.navbar .nav li.dropdown.open > .dropdown-toggle .caret, +.navbar .nav li.dropdown.active > .dropdown-toggle .caret, +.navbar .nav li.dropdown.open.active > .dropdown-toggle .caret { + border-top-color: #555555; + border-bottom-color: #555555; +} +.navbar .pull-right > li > .dropdown-menu, +.navbar .nav > li > .dropdown-menu.pull-right { + left: auto; + right: 0; +} +.navbar .pull-right > li > .dropdown-menu:before, +.navbar .nav > li > .dropdown-menu.pull-right:before { + left: auto; + right: 12px; +} +.navbar .pull-right > li > .dropdown-menu:after, +.navbar .nav > li > .dropdown-menu.pull-right:after { + left: auto; + right: 13px; +} +.navbar .pull-right > li > .dropdown-menu .dropdown-menu, +.navbar .nav > li > .dropdown-menu.pull-right .dropdown-menu { + left: auto; + right: 100%; + margin-left: 0; + margin-right: -1px; + -webkit-border-radius: 6px 0 6px 6px; + -moz-border-radius: 6px 0 6px 6px; + border-radius: 6px 0 6px 6px; +} +.navbar-inverse .navbar-inner { + background-color: #1b1b1b; + background-image: -moz-linear-gradient(top, #222222, #111111); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111)); + background-image: -webkit-linear-gradient(top, #222222, #111111); + background-image: -o-linear-gradient(top, #222222, #111111); + background-image: linear-gradient(to bottom, #222222, #111111); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0); + border-color: #252525; +} +.navbar-inverse .brand, +.navbar-inverse .nav > li > a { + color: #999999; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); +} +.navbar-inverse .brand:hover, +.navbar-inverse .nav > li > a:hover, +.navbar-inverse .brand:focus, +.navbar-inverse .nav > li > a:focus { + color: #ffffff; +} +.navbar-inverse .brand { + color: #999999; +} +.navbar-inverse .navbar-text { + color: #999999; +} +.navbar-inverse .nav > li > a:focus, +.navbar-inverse .nav > li > a:hover { + background-color: transparent; + color: #ffffff; +} +.navbar-inverse .nav .active > a, +.navbar-inverse .nav .active > a:hover, +.navbar-inverse .nav .active > a:focus { + color: #ffffff; + background-color: #111111; +} +.navbar-inverse .navbar-link { + color: #999999; +} +.navbar-inverse .navbar-link:hover, +.navbar-inverse .navbar-link:focus { + color: #ffffff; +} +.navbar-inverse .divider-vertical { + border-left-color: #111111; + border-right-color: #222222; +} +.navbar-inverse .nav li.dropdown.open > .dropdown-toggle, +.navbar-inverse .nav li.dropdown.active > .dropdown-toggle, +.navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle { + background-color: #111111; + color: #ffffff; +} +.navbar-inverse .nav li.dropdown > a:hover .caret, +.navbar-inverse .nav li.dropdown > a:focus .caret { + border-top-color: #ffffff; + border-bottom-color: #ffffff; +} +.navbar-inverse .nav li.dropdown > .dropdown-toggle .caret { + border-top-color: #999999; + border-bottom-color: #999999; +} +.navbar-inverse .nav li.dropdown.open > .dropdown-toggle .caret, +.navbar-inverse .nav li.dropdown.active > .dropdown-toggle .caret, +.navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle .caret { + border-top-color: #ffffff; + border-bottom-color: #ffffff; +} +.navbar-inverse .navbar-search .search-query { + color: #ffffff; + background-color: #515151; + border-color: #111111; + -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); + -moz-box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); + box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); + -webkit-transition: none; + -moz-transition: none; + -o-transition: none; + transition: none; +} +.navbar-inverse .navbar-search .search-query:-moz-placeholder { + color: #cccccc; +} +.navbar-inverse .navbar-search .search-query:-ms-input-placeholder { + color: #cccccc; +} +.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder { + color: #cccccc; +} +.navbar-inverse .navbar-search .search-query:focus, +.navbar-inverse .navbar-search .search-query.focused { + padding: 5px 15px; + color: #333333; + text-shadow: 0 1px 0 #ffffff; + background-color: #ffffff; + border: 0; + -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + outline: 0; +} +.navbar-inverse .btn-navbar { + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #0e0e0e; + background-image: -moz-linear-gradient(top, #151515, #040404); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#151515), to(#040404)); + background-image: -webkit-linear-gradient(top, #151515, #040404); + background-image: -o-linear-gradient(top, #151515, #040404); + background-image: linear-gradient(to bottom, #151515, #040404); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515', endColorstr='#ff040404', GradientType=0); + border-color: #040404 #040404 #000000; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + *background-color: #040404; + /* Darken IE7 buttons by default so they stand out more given they won't have borders */ + + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); +} +.navbar-inverse .btn-navbar:hover, +.navbar-inverse .btn-navbar:focus, +.navbar-inverse .btn-navbar:active, +.navbar-inverse .btn-navbar.active, +.navbar-inverse .btn-navbar.disabled, +.navbar-inverse .btn-navbar[disabled] { + color: #ffffff; + background-color: #040404; + *background-color: #000000; +} +.navbar-inverse .btn-navbar:active, +.navbar-inverse .btn-navbar.active { + background-color: #000000 \9; +} +.breadcrumb { + padding: 8px 15px; + margin: 0 0 20px; + list-style: none; + background-color: #f5f5f5; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +.breadcrumb > li { + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ + + *zoom: 1; + text-shadow: 0 1px 0 #ffffff; +} +.breadcrumb > li > .divider { + padding: 0 5px; + color: #ccc; +} +.breadcrumb > .active { + color: #999999; +} +.pagination { + margin: 20px 0; +} +.pagination ul { + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ + + *zoom: 1; + margin-left: 0; + margin-bottom: 0; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); +} +.pagination ul > li { + display: inline; +} +.pagination ul > li > a, +.pagination ul > li > span { + float: left; + padding: 4px 12px; + line-height: 20px; + text-decoration: none; + background-color: #ffffff; + border: 1px solid #dddddd; + border-left-width: 0; +} +.pagination ul > li > a:hover, +.pagination ul > li > a:focus, +.pagination ul > .active > a, +.pagination ul > .active > span { + background-color: #f5f5f5; +} +.pagination ul > .active > a, +.pagination ul > .active > span { + color: #999999; + cursor: default; +} +.pagination ul > .disabled > span, +.pagination ul > .disabled > a, +.pagination ul > .disabled > a:hover, +.pagination ul > .disabled > a:focus { + color: #999999; + background-color: transparent; + cursor: default; +} +.pagination ul > li:first-child > a, +.pagination ul > li:first-child > span { + border-left-width: 1px; + -webkit-border-top-left-radius: 4px; + -moz-border-radius-topleft: 4px; + border-top-left-radius: 4px; + -webkit-border-bottom-left-radius: 4px; + -moz-border-radius-bottomleft: 4px; + border-bottom-left-radius: 4px; +} +.pagination ul > li:last-child > a, +.pagination ul > li:last-child > span { + -webkit-border-top-right-radius: 4px; + -moz-border-radius-topright: 4px; + border-top-right-radius: 4px; + -webkit-border-bottom-right-radius: 4px; + -moz-border-radius-bottomright: 4px; + border-bottom-right-radius: 4px; +} +.pagination-centered { + text-align: center; +} +.pagination-right { + text-align: right; +} +.pagination-large ul > li > a, +.pagination-large ul > li > span { + padding: 11px 19px; + font-size: 17.5px; +} +.pagination-large ul > li:first-child > a, +.pagination-large ul > li:first-child > span { + -webkit-border-top-left-radius: 6px; + -moz-border-radius-topleft: 6px; + border-top-left-radius: 6px; + -webkit-border-bottom-left-radius: 6px; + -moz-border-radius-bottomleft: 6px; + border-bottom-left-radius: 6px; +} +.pagination-large ul > li:last-child > a, +.pagination-large ul > li:last-child > span { + -webkit-border-top-right-radius: 6px; + -moz-border-radius-topright: 6px; + border-top-right-radius: 6px; + -webkit-border-bottom-right-radius: 6px; + -moz-border-radius-bottomright: 6px; + border-bottom-right-radius: 6px; +} +.pagination-mini ul > li:first-child > a, +.pagination-small ul > li:first-child > a, +.pagination-mini ul > li:first-child > span, +.pagination-small ul > li:first-child > span { + -webkit-border-top-left-radius: 3px; + -moz-border-radius-topleft: 3px; + border-top-left-radius: 3px; + -webkit-border-bottom-left-radius: 3px; + -moz-border-radius-bottomleft: 3px; + border-bottom-left-radius: 3px; +} +.pagination-mini ul > li:last-child > a, +.pagination-small ul > li:last-child > a, +.pagination-mini ul > li:last-child > span, +.pagination-small ul > li:last-child > span { + -webkit-border-top-right-radius: 3px; + -moz-border-radius-topright: 3px; + border-top-right-radius: 3px; + -webkit-border-bottom-right-radius: 3px; + -moz-border-radius-bottomright: 3px; + border-bottom-right-radius: 3px; +} +.pagination-small ul > li > a, +.pagination-small ul > li > span { + padding: 2px 10px; + font-size: 11.9px; +} +.pagination-mini ul > li > a, +.pagination-mini ul > li > span { + padding: 0 6px; + font-size: 10.5px; +} +.pager { + margin: 20px 0; + list-style: none; + text-align: center; + *zoom: 1; +} +.pager:before, +.pager:after { + display: table; + content: ""; + line-height: 0; +} +.pager:after { + clear: both; +} +.pager li { + display: inline; +} +.pager li > a, +.pager li > span { + display: inline-block; + padding: 5px 14px; + background-color: #fff; + border: 1px solid #ddd; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; +} +.pager li > a:hover, +.pager li > a:focus { + text-decoration: none; + background-color: #f5f5f5; +} +.pager .next > a, +.pager .next > span { + float: right; +} +.pager .previous > a, +.pager .previous > span { + float: left; +} +.pager .disabled > a, +.pager .disabled > a:hover, +.pager .disabled > a:focus, +.pager .disabled > span { + color: #999999; + background-color: #fff; + cursor: default; +} +.thumbnails { + margin-left: -20px; + list-style: none; + *zoom: 1; +} +.thumbnails:before, +.thumbnails:after { + display: table; + content: ""; + line-height: 0; +} +.thumbnails:after { + clear: both; +} +.row-fluid .thumbnails { + margin-left: 0; +} +.thumbnails > li { + float: left; + margin-bottom: 20px; + margin-left: 20px; +} +.thumbnail { + display: block; + padding: 4px; + line-height: 20px; + border: 1px solid #ddd; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); + -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); + -webkit-transition: all 0.2s ease-in-out; + -moz-transition: all 0.2s ease-in-out; + -o-transition: all 0.2s ease-in-out; + transition: all 0.2s ease-in-out; +} +a.thumbnail:hover, +a.thumbnail:focus { + border-color: #0088cc; + -webkit-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); + -moz-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); + box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); +} +.thumbnail > img { + display: block; + max-width: 100%; + margin-left: auto; + margin-right: auto; +} +.thumbnail .caption { + padding: 9px; + color: #555555; +} +.alert { + padding: 8px 35px 8px 14px; + margin-bottom: 20px; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + background-color: #fcf8e3; + border: 1px solid #fbeed5; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +.alert, +.alert h4 { + color: #c09853; +} +.alert h4 { + margin: 0; +} +.alert .close { + position: relative; + top: -2px; + right: -21px; + line-height: 20px; +} +.alert-success { + background-color: #dff0d8; + border-color: #d6e9c6; + color: #468847; +} +.alert-success h4 { + color: #468847; +} +.alert-danger, +.alert-error { + background-color: #f2dede; + border-color: #eed3d7; + color: #b94a48; +} +.alert-danger h4, +.alert-error h4 { + color: #b94a48; +} +.alert-info { + background-color: #d9edf7; + border-color: #bce8f1; + color: #3a87ad; +} +.alert-info h4 { + color: #3a87ad; +} +.alert-block { + padding-top: 14px; + padding-bottom: 14px; +} +.alert-block > p, +.alert-block > ul { + margin-bottom: 0; +} +.alert-block p + p { + margin-top: 5px; +} +@-webkit-keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} +@-moz-keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} +@-ms-keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} +@-o-keyframes progress-bar-stripes { + from { + background-position: 0 0; + } + to { + background-position: 40px 0; + } +} +@keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} +.progress { + overflow: hidden; + height: 20px; + margin-bottom: 20px; + background-color: #f7f7f7; + background-image: -moz-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9)); + background-image: -webkit-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: -o-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: linear-gradient(to bottom, #f5f5f5, #f9f9f9); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0); + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +.progress .bar { + width: 0%; + height: 100%; + color: #ffffff; + float: left; + font-size: 12px; + text-align: center; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #0e90d2; + background-image: -moz-linear-gradient(top, #149bdf, #0480be); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be)); + background-image: -webkit-linear-gradient(top, #149bdf, #0480be); + background-image: -o-linear-gradient(top, #149bdf, #0480be); + background-image: linear-gradient(to bottom, #149bdf, #0480be); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0); + -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -moz-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-transition: width 0.6s ease; + -moz-transition: width 0.6s ease; + -o-transition: width 0.6s ease; + transition: width 0.6s ease; +} +.progress .bar + .bar { + -webkit-box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); + -moz-box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); + box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); +} +.progress-striped .bar { + background-color: #149bdf; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + -webkit-background-size: 40px 40px; + -moz-background-size: 40px 40px; + -o-background-size: 40px 40px; + background-size: 40px 40px; +} +.progress.active .bar { + -webkit-animation: progress-bar-stripes 2s linear infinite; + -moz-animation: progress-bar-stripes 2s linear infinite; + -ms-animation: progress-bar-stripes 2s linear infinite; + -o-animation: progress-bar-stripes 2s linear infinite; + animation: progress-bar-stripes 2s linear infinite; +} +.progress-danger .bar, +.progress .bar-danger { + background-color: #dd514c; + background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35)); + background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -o-linear-gradient(top, #ee5f5b, #c43c35); + background-image: linear-gradient(to bottom, #ee5f5b, #c43c35); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0); +} +.progress-danger.progress-striped .bar, +.progress-striped .bar-danger { + background-color: #ee5f5b; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); +} +.progress-success .bar, +.progress .bar-success { + background-color: #5eb95e; + background-image: -moz-linear-gradient(top, #62c462, #57a957); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957)); + background-image: -webkit-linear-gradient(top, #62c462, #57a957); + background-image: -o-linear-gradient(top, #62c462, #57a957); + background-image: linear-gradient(to bottom, #62c462, #57a957); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff57a957', GradientType=0); +} +.progress-success.progress-striped .bar, +.progress-striped .bar-success { + background-color: #62c462; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); +} +.progress-info .bar, +.progress .bar-info { + background-color: #4bb1cf; + background-image: -moz-linear-gradient(top, #5bc0de, #339bb9); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9)); + background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9); + background-image: -o-linear-gradient(top, #5bc0de, #339bb9); + background-image: linear-gradient(to bottom, #5bc0de, #339bb9); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff339bb9', GradientType=0); +} +.progress-info.progress-striped .bar, +.progress-striped .bar-info { + background-color: #5bc0de; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); +} +.progress-warning .bar, +.progress .bar-warning { + background-color: #faa732; + background-image: -moz-linear-gradient(top, #fbb450, #f89406); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); + background-image: -webkit-linear-gradient(top, #fbb450, #f89406); + background-image: -o-linear-gradient(top, #fbb450, #f89406); + background-image: linear-gradient(to bottom, #fbb450, #f89406); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); +} +.progress-warning.progress-striped .bar, +.progress-striped .bar-warning { + background-color: #fbb450; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); +} +.hero-unit { + padding: 60px; + margin-bottom: 30px; + font-size: 18px; + font-weight: 200; + line-height: 30px; + color: inherit; + background-color: #4eacc5; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} +.hero-unit h1 { + margin-bottom: 0; + font-size: 60px; + line-height: 1; + color: inherit; + letter-spacing: -1px; +} +.hero-unit li { + line-height: 30px; +} +.media, +.media-body { + overflow: hidden; + *overflow: visible; + zoom: 1; +} +.media, +.media .media { + margin-top: 15px; +} +.media:first-child { + margin-top: 0; +} +.media-object { + display: block; +} +.media-heading { + margin: 0 0 5px; +} +.media > .pull-left { + margin-right: 10px; +} +.media > .pull-right { + margin-left: 10px; +} +.media-list { + margin-left: 0; + list-style: none; +} +.tooltip { + position: absolute; + z-index: 1030; + display: block; + visibility: visible; + font-size: 11px; + line-height: 1.4; + opacity: 0; + filter: alpha(opacity=0); +} +.tooltip.in { + opacity: 0.8; + filter: alpha(opacity=80); +} +.tooltip.top { + margin-top: -3px; + padding: 5px 0; +} +.tooltip.right { + margin-left: 3px; + padding: 0 5px; +} +.tooltip.bottom { + margin-top: 3px; + padding: 5px 0; +} +.tooltip.left { + margin-left: -3px; + padding: 0 5px; +} +.tooltip-inner { + max-width: 200px; + padding: 8px; + color: #ffffff; + text-align: center; + text-decoration: none; + background-color: #000000; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +.tooltip-arrow { + position: absolute; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; +} +.tooltip.top .tooltip-arrow { + bottom: 0; + left: 50%; + margin-left: -5px; + border-width: 5px 5px 0; + border-top-color: #000000; +} +.tooltip.right .tooltip-arrow { + top: 50%; + left: 0; + margin-top: -5px; + border-width: 5px 5px 5px 0; + border-right-color: #000000; +} +.tooltip.left .tooltip-arrow { + top: 50%; + right: 0; + margin-top: -5px; + border-width: 5px 0 5px 5px; + border-left-color: #000000; +} +.tooltip.bottom .tooltip-arrow { + top: 0; + left: 50%; + margin-left: -5px; + border-width: 0 5px 5px; + border-bottom-color: #000000; +} +.popover { + position: absolute; + top: 0; + left: 0; + z-index: 1010; + display: none; + max-width: 276px; + padding: 1px; + text-align: left; + background-color: #ffffff; + -webkit-background-clip: padding-box; + -moz-background-clip: padding; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.2); + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + white-space: normal; +} +.popover.top { + margin-top: -10px; +} +.popover.right { + margin-left: 10px; +} +.popover.bottom { + margin-top: 10px; +} +.popover.left { + margin-left: -10px; +} +.popover-title { + margin: 0; + padding: 8px 14px; + font-size: 14px; + font-weight: normal; + line-height: 18px; + background-color: #f7f7f7; + border-bottom: 1px solid #ebebeb; + -webkit-border-radius: 5px 5px 0 0; + -moz-border-radius: 5px 5px 0 0; + border-radius: 5px 5px 0 0; +} +.popover-title:empty { + display: none; +} +.popover-content { + padding: 9px 14px; +} +.popover .arrow, +.popover .arrow:after { + position: absolute; + display: block; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; +} +.popover .arrow { + border-width: 11px; +} +.popover .arrow:after { + border-width: 10px; + content: ""; +} +.popover.top .arrow { + left: 50%; + margin-left: -11px; + border-bottom-width: 0; + border-top-color: #999; + border-top-color: rgba(0, 0, 0, 0.25); + bottom: -11px; +} +.popover.top .arrow:after { + bottom: 1px; + margin-left: -10px; + border-bottom-width: 0; + border-top-color: #ffffff; +} +.popover.right .arrow { + top: 50%; + left: -11px; + margin-top: -11px; + border-left-width: 0; + border-right-color: #999; + border-right-color: rgba(0, 0, 0, 0.25); +} +.popover.right .arrow:after { + left: 1px; + bottom: -10px; + border-left-width: 0; + border-right-color: #ffffff; +} +.popover.bottom .arrow { + left: 50%; + margin-left: -11px; + border-top-width: 0; + border-bottom-color: #999; + border-bottom-color: rgba(0, 0, 0, 0.25); + top: -11px; +} +.popover.bottom .arrow:after { + top: 1px; + margin-left: -10px; + border-top-width: 0; + border-bottom-color: #ffffff; +} +.popover.left .arrow { + top: 50%; + right: -11px; + margin-top: -11px; + border-right-width: 0; + border-left-color: #999; + border-left-color: rgba(0, 0, 0, 0.25); +} +.popover.left .arrow:after { + right: 1px; + border-right-width: 0; + border-left-color: #ffffff; + bottom: -10px; +} +.modal-backdrop { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 1040; + background-color: #000000; +} +.modal-backdrop.fade { + opacity: 0; +} +.modal-backdrop, +.modal-backdrop.fade.in { + opacity: 0.8; + filter: alpha(opacity=80); +} +.modal { + position: fixed; + top: 10%; + left: 50%; + z-index: 1050; + width: 560px; + margin-left: -280px; + background-color: #ffffff; + border: 1px solid #999; + border: 1px solid rgba(0, 0, 0, 0.3); + *border: 1px solid #999; + /* IE6-7 */ + + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -webkit-background-clip: padding-box; + -moz-background-clip: padding-box; + background-clip: padding-box; + outline: none; +} +.modal.fade { + -webkit-transition: opacity .3s linear, top .3s ease-out; + -moz-transition: opacity .3s linear, top .3s ease-out; + -o-transition: opacity .3s linear, top .3s ease-out; + transition: opacity .3s linear, top .3s ease-out; + top: -25%; +} +.modal.fade.in { + top: 10%; +} +.modal-header { + padding: 9px 15px; + border-bottom: 1px solid #eee; +} +.modal-header .close { + margin-top: 2px; +} +.modal-header h3 { + margin: 0; + line-height: 30px; +} +.modal-body { + position: relative; + overflow-y: auto; + max-height: 400px; + padding: 15px; +} +.modal-form { + margin-bottom: 0; +} +.modal-footer { + padding: 14px 15px 15px; + margin-bottom: 0; + text-align: right; + background-color: #f5f5f5; + border-top: 1px solid #ddd; + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; + -webkit-box-shadow: inset 0 1px 0 #ffffff; + -moz-box-shadow: inset 0 1px 0 #ffffff; + box-shadow: inset 0 1px 0 #ffffff; + *zoom: 1; +} +.modal-footer:before, +.modal-footer:after { + display: table; + content: ""; + line-height: 0; +} +.modal-footer:after { + clear: both; +} +.modal-footer .btn + .btn { + margin-left: 5px; + margin-bottom: 0; +} +.modal-footer .btn-group .btn + .btn { + margin-left: -1px; +} +.modal-footer .btn-block + .btn-block { + margin-left: 0; +} +.dropup, +.dropdown { + position: relative; +} +.dropdown-toggle { + *margin-bottom: -3px; +} +.dropdown-toggle:active, +.open .dropdown-toggle { + outline: 0; +} +.caret { + display: inline-block; + width: 0; + height: 0; + vertical-align: top; + border-top: 4px solid #000000; + border-right: 4px solid transparent; + border-left: 4px solid transparent; + content: ""; +} +.dropdown .caret { + margin-top: 8px; + margin-left: 2px; +} +.dropdown-menu { + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + padding: 5px 0; + margin: 2px 0 0; + list-style: none; + background-color: #ffffff; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.2); + *border-right-width: 2px; + *border-bottom-width: 2px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -webkit-background-clip: padding-box; + -moz-background-clip: padding; + background-clip: padding-box; +} +.dropdown-menu.pull-right { + right: 0; + left: auto; +} +.dropdown-menu .divider { + *width: 100%; + height: 1px; + margin: 9px 1px; + *margin: -5px 0 5px; + overflow: hidden; + background-color: #e5e5e5; + border-bottom: 1px solid #ffffff; +} +.dropdown-menu > li > a { + display: block; + padding: 3px 20px; + clear: both; + font-weight: normal; + line-height: 20px; + color: #333333; + white-space: nowrap; +} +.dropdown-menu > li > a:hover, +.dropdown-menu > li > a:focus, +.dropdown-submenu:hover > a, +.dropdown-submenu:focus > a { + text-decoration: none; + color: #ffffff; + background-color: #0081c2; + background-image: -moz-linear-gradient(top, #0088cc, #0077b3); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); + background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); + background-image: -o-linear-gradient(top, #0088cc, #0077b3); + background-image: linear-gradient(to bottom, #0088cc, #0077b3); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); +} +.dropdown-menu > .active > a, +.dropdown-menu > .active > a:hover, +.dropdown-menu > .active > a:focus { + color: #ffffff; + text-decoration: none; + outline: 0; + background-color: #0081c2; + background-image: -moz-linear-gradient(top, #0088cc, #0077b3); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); + background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); + background-image: -o-linear-gradient(top, #0088cc, #0077b3); + background-image: linear-gradient(to bottom, #0088cc, #0077b3); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); +} +.dropdown-menu > .disabled > a, +.dropdown-menu > .disabled > a:hover, +.dropdown-menu > .disabled > a:focus { + color: #999999; +} +.dropdown-menu > .disabled > a:hover, +.dropdown-menu > .disabled > a:focus { + text-decoration: none; + background-color: transparent; + background-image: none; + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + cursor: default; +} +.open { + *z-index: 1000; +} +.open > .dropdown-menu { + display: block; +} +.dropdown-backdrop { + position: fixed; + left: 0; + right: 0; + bottom: 0; + top: 0; + z-index: 990; +} +.pull-right > .dropdown-menu { + right: 0; + left: auto; +} +.dropup .caret, +.navbar-fixed-bottom .dropdown .caret { + border-top: 0; + border-bottom: 4px solid #000000; + content: ""; +} +.dropup .dropdown-menu, +.navbar-fixed-bottom .dropdown .dropdown-menu { + top: auto; + bottom: 100%; + margin-bottom: 1px; +} +.dropdown-submenu { + position: relative; +} +.dropdown-submenu > .dropdown-menu { + top: 0; + left: 100%; + margin-top: -6px; + margin-left: -1px; + -webkit-border-radius: 0 6px 6px 6px; + -moz-border-radius: 0 6px 6px 6px; + border-radius: 0 6px 6px 6px; +} +.dropdown-submenu:hover > .dropdown-menu { + display: block; +} +.dropup .dropdown-submenu > .dropdown-menu { + top: auto; + bottom: 0; + margin-top: 0; + margin-bottom: -2px; + -webkit-border-radius: 5px 5px 5px 0; + -moz-border-radius: 5px 5px 5px 0; + border-radius: 5px 5px 5px 0; +} +.dropdown-submenu > a:after { + display: block; + content: " "; + float: right; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; + border-width: 5px 0 5px 5px; + border-left-color: #cccccc; + margin-top: 5px; + margin-right: -10px; +} +.dropdown-submenu:hover > a:after { + border-left-color: #ffffff; +} +.dropdown-submenu.pull-left { + float: none; +} +.dropdown-submenu.pull-left > .dropdown-menu { + left: -100%; + margin-left: 10px; + -webkit-border-radius: 6px 0 6px 6px; + -moz-border-radius: 6px 0 6px 6px; + border-radius: 6px 0 6px 6px; +} +.dropdown .dropdown-menu .nav-header { + padding-left: 20px; + padding-right: 20px; +} +.typeahead { + z-index: 1051; + margin-top: 2px; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +.accordion { + margin-bottom: 20px; +} +.accordion-group { + margin-bottom: 2px; + border: 1px solid #e5e5e5; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +.accordion-heading { + border-bottom: 0; +} +.accordion-heading .accordion-toggle { + display: block; + padding: 8px 15px; +} +.accordion-toggle { + cursor: pointer; +} +.accordion-inner { + padding: 9px 15px; + border-top: 1px solid #e5e5e5; +} +.carousel { + position: relative; + margin-bottom: 20px; + line-height: 1; +} +.carousel-inner { + overflow: hidden; + width: 100%; + position: relative; +} +.carousel-inner > .item { + display: none; + position: relative; + -webkit-transition: 0.6s ease-in-out left; + -moz-transition: 0.6s ease-in-out left; + -o-transition: 0.6s ease-in-out left; + transition: 0.6s ease-in-out left; +} +.carousel-inner > .item > img, +.carousel-inner > .item > a > img { + display: block; + line-height: 1; +} +.carousel-inner > .active, +.carousel-inner > .next, +.carousel-inner > .prev { + display: block; +} +.carousel-inner > .active { + left: 0; +} +.carousel-inner > .next, +.carousel-inner > .prev { + position: absolute; + top: 0; + width: 100%; +} +.carousel-inner > .next { + left: 100%; +} +.carousel-inner > .prev { + left: -100%; +} +.carousel-inner > .next.left, +.carousel-inner > .prev.right { + left: 0; +} +.carousel-inner > .active.left { + left: -100%; +} +.carousel-inner > .active.right { + left: 100%; +} +.carousel-control { + position: absolute; + top: 40%; + left: 15px; + width: 40px; + height: 40px; + margin-top: -20px; + font-size: 60px; + font-weight: 100; + line-height: 30px; + color: #ffffff; + text-align: center; + background: #222222; + border: 3px solid #ffffff; + -webkit-border-radius: 23px; + -moz-border-radius: 23px; + border-radius: 23px; + opacity: 0.5; + filter: alpha(opacity=50); +} +.carousel-control.right { + left: auto; + right: 15px; +} +.carousel-control:hover, +.carousel-control:focus { + color: #ffffff; + text-decoration: none; + opacity: 0.9; + filter: alpha(opacity=90); +} +.carousel-indicators { + position: absolute; + top: 15px; + right: 15px; + z-index: 5; + margin: 0; + list-style: none; +} +.carousel-indicators li { + display: block; + float: left; + width: 10px; + height: 10px; + margin-left: 5px; + text-indent: -999px; + background-color: #ccc; + background-color: rgba(255, 255, 255, 0.25); + border-radius: 5px; +} +.carousel-indicators .active { + background-color: #fff; +} +.carousel-caption { + position: absolute; + left: 0; + right: 0; + bottom: 0; + padding: 15px; + background: #333333; + background: rgba(0, 0, 0, 0.75); +} +.carousel-caption h4, +.carousel-caption p { + color: #ffffff; + line-height: 20px; +} +.carousel-caption h4 { + margin: 0 0 5px; +} +.carousel-caption p { + margin-bottom: 0; +} +.well { + min-height: 20px; + padding: 19px; + margin-bottom: 20px; + background-color: #f5f5f5; + border: 1px solid #e3e3e3; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); +} +.well blockquote { + border-color: #ddd; + border-color: rgba(0, 0, 0, 0.15); +} +.well-large { + padding: 24px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} +.well-small { + padding: 9px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} +.close { + float: right; + font-size: 20px; + font-weight: bold; + line-height: 20px; + color: #000000; + text-shadow: 0 1px 0 #ffffff; + opacity: 0.2; + filter: alpha(opacity=20); +} +.close:hover, +.close:focus { + color: #000000; + text-decoration: none; + cursor: pointer; + opacity: 0.4; + filter: alpha(opacity=40); +} +button.close { + padding: 0; + cursor: pointer; + background: transparent; + border: 0; + -webkit-appearance: none; +} +.pull-right { + float: right; +} +.pull-left { + float: left; +} +.hide { + display: none; +} +.show { + display: block; +} +.invisible { + visibility: hidden; +} +.affix { + position: fixed; +} +.fade { + opacity: 0; + -webkit-transition: opacity 0.15s linear; + -moz-transition: opacity 0.15s linear; + -o-transition: opacity 0.15s linear; + transition: opacity 0.15s linear; +} +.fade.in { + opacity: 1; +} +.collapse { + position: relative; + height: 0; + overflow: hidden; + -webkit-transition: height 0.35s ease; + -moz-transition: height 0.35s ease; + -o-transition: height 0.35s ease; + transition: height 0.35s ease; +} +.collapse.in { + height: auto; +} +@-ms-viewport { + width: device-width; +} +.hidden { + display: none; + visibility: hidden; +} +.visible-phone { + display: none !important; +} +.visible-tablet { + display: none !important; +} +.hidden-desktop { + display: none !important; +} +.visible-desktop { + display: inherit !important; +} +@media (min-width: 768px) and (max-width: 979px) { + .hidden-desktop { + display: inherit !important; + } + .visible-desktop { + display: none !important ; + } + .visible-tablet { + display: inherit !important; + } + .hidden-tablet { + display: none !important; + } +} +@media (max-width: 767px) { + .hidden-desktop { + display: inherit !important; + } + .visible-desktop { + display: none !important; + } + .visible-phone { + display: inherit !important; + } + .hidden-phone { + display: none !important; + } +} +.visible-print { + display: none !important; +} +@media print { + .visible-print { + display: inherit !important; + } + .hidden-print { + display: none !important; + } +} +@media (max-width: 767px) { + body { + padding-left: 20px; + padding-right: 20px; + } + .navbar-fixed-top, + .navbar-fixed-bottom, + .navbar-static-top { + margin-left: -20px; + margin-right: -20px; + } + .container-fluid { + padding: 0; + } + .dl-horizontal dt { + float: none; + clear: none; + width: auto; + text-align: left; + } + .dl-horizontal dd { + margin-left: 0; + } + .container { + width: auto; + } + .row-fluid { + width: 100%; + } + .row, + .thumbnails { + margin-left: 0; + } + .thumbnails > li { + float: none; + margin-left: 0; + } + [class*="span"], + .uneditable-input[class*="span"], + .row-fluid [class*="span"] { + float: none; + display: block; + width: 100%; + margin-left: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .span12, + .row-fluid .span12 { + width: 100%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .row-fluid [class*="offset"]:first-child { + margin-left: 0; + } + .input-large, + .input-xlarge, + .input-xxlarge, + input[class*="span"], + select[class*="span"], + textarea[class*="span"], + .uneditable-input { + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + .input-prepend input, + .input-append input, + .input-prepend input[class*="span"], + .input-append input[class*="span"] { + display: inline-block; + width: auto; + } + .controls-row [class*="span"] + [class*="span"] { + margin-left: 0; + } + .modal { + position: fixed; + top: 20px; + left: 20px; + right: 20px; + width: auto; + margin: 0; + } + .modal.fade { + top: -100px; + } + .modal.fade.in { + top: 20px; + } +} +@media (max-width: 480px) { + .nav-collapse { + -webkit-transform: translate3d(0, 0, 0); + } + .page-header h1 small { + display: block; + line-height: 20px; + } + input[type="checkbox"], + input[type="radio"] { + border: 1px solid #ccc; + } + .form-horizontal .control-label { + float: none; + width: auto; + padding-top: 0; + text-align: left; + } + .form-horizontal .controls { + margin-left: 0; + } + .form-horizontal .control-list { + padding-top: 0; + } + .form-horizontal .form-actions { + padding-left: 10px; + padding-right: 10px; + } + .media .pull-left, + .media .pull-right { + float: none; + display: block; + margin-bottom: 10px; + } + .media-object { + margin-right: 0; + margin-left: 0; + } + .modal { + top: 10px; + left: 10px; + right: 10px; + } + .modal-header .close { + padding: 10px; + margin: -10px; + } + .carousel-caption { + position: static; + } +} +@media (min-width: 768px) and (max-width: 979px) { + .row { + margin-left: -20px; + *zoom: 1; + } + .row:before, + .row:after { + display: table; + content: ""; + line-height: 0; + } + .row:after { + clear: both; + } + [class*="span"] { + float: left; + min-height: 1px; + margin-left: 20px; + } + .container, + .navbar-static-top .container, + .navbar-fixed-top .container, + .navbar-fixed-bottom .container { + width: 724px; + } + .span12 { + width: 724px; + } + .span11 { + width: 662px; + } + .span10 { + width: 600px; + } + .span9 { + width: 538px; + } + .span8 { + width: 476px; + } + .span7 { + width: 414px; + } + .span6 { + width: 352px; + } + .span5 { + width: 290px; + } + .span4 { + width: 228px; + } + .span3 { + width: 166px; + } + .span2 { + width: 104px; + } + .span1 { + width: 42px; + } + .offset12 { + margin-left: 764px; + } + .offset11 { + margin-left: 702px; + } + .offset10 { + margin-left: 640px; + } + .offset9 { + margin-left: 578px; + } + .offset8 { + margin-left: 516px; + } + .offset7 { + margin-left: 454px; + } + .offset6 { + margin-left: 392px; + } + .offset5 { + margin-left: 330px; + } + .offset4 { + margin-left: 268px; + } + .offset3 { + margin-left: 206px; + } + .offset2 { + margin-left: 144px; + } + .offset1 { + margin-left: 82px; + } + .row-fluid { + width: 100%; + *zoom: 1; + } + .row-fluid:before, + .row-fluid:after { + display: table; + content: ""; + line-height: 0; + } + .row-fluid:after { + clear: both; + } + .row-fluid [class*="span"] { + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + float: left; + margin-left: 2.7624309392265194%; + *margin-left: 2.709239449864817%; + } + .row-fluid [class*="span"]:first-child { + margin-left: 0; + } + .row-fluid .controls-row [class*="span"] + [class*="span"] { + margin-left: 2.7624309392265194%; + } + .row-fluid .span12 { + width: 100%; + *width: 99.94680851063829%; + } + .row-fluid .span11 { + width: 91.43646408839778%; + *width: 91.38327259903608%; + } + .row-fluid .span10 { + width: 82.87292817679558%; + *width: 82.81973668743387%; + } + .row-fluid .span9 { + width: 74.30939226519337%; + *width: 74.25620077583166%; + } + .row-fluid .span8 { + width: 65.74585635359117%; + *width: 65.69266486422946%; + } + .row-fluid .span7 { + width: 57.18232044198895%; + *width: 57.12912895262725%; + } + .row-fluid .span6 { + width: 48.61878453038674%; + *width: 48.56559304102504%; + } + .row-fluid .span5 { + width: 40.05524861878453%; + *width: 40.00205712942283%; + } + .row-fluid .span4 { + width: 31.491712707182323%; + *width: 31.43852121782062%; + } + .row-fluid .span3 { + width: 22.92817679558011%; + *width: 22.87498530621841%; + } + .row-fluid .span2 { + width: 14.3646408839779%; + *width: 14.311449394616199%; + } + .row-fluid .span1 { + width: 5.801104972375691%; + *width: 5.747913483013988%; + } + .row-fluid .offset12 { + margin-left: 105.52486187845304%; + *margin-left: 105.41847889972962%; + } + .row-fluid .offset12:first-child { + margin-left: 102.76243093922652%; + *margin-left: 102.6560479605031%; + } + .row-fluid .offset11 { + margin-left: 96.96132596685082%; + *margin-left: 96.8549429881274%; + } + .row-fluid .offset11:first-child { + margin-left: 94.1988950276243%; + *margin-left: 94.09251204890089%; + } + .row-fluid .offset10 { + margin-left: 88.39779005524862%; + *margin-left: 88.2914070765252%; + } + .row-fluid .offset10:first-child { + margin-left: 85.6353591160221%; + *margin-left: 85.52897613729868%; + } + .row-fluid .offset9 { + margin-left: 79.8342541436464%; + *margin-left: 79.72787116492299%; + } + .row-fluid .offset9:first-child { + margin-left: 77.07182320441989%; + *margin-left: 76.96544022569647%; + } + .row-fluid .offset8 { + margin-left: 71.2707182320442%; + *margin-left: 71.16433525332079%; + } + .row-fluid .offset8:first-child { + margin-left: 68.50828729281768%; + *margin-left: 68.40190431409427%; + } + .row-fluid .offset7 { + margin-left: 62.70718232044199%; + *margin-left: 62.600799341718584%; + } + .row-fluid .offset7:first-child { + margin-left: 59.94475138121547%; + *margin-left: 59.838368402492065%; + } + .row-fluid .offset6 { + margin-left: 54.14364640883978%; + *margin-left: 54.037263430116376%; + } + .row-fluid .offset6:first-child { + margin-left: 51.38121546961326%; + *margin-left: 51.27483249088986%; + } + .row-fluid .offset5 { + margin-left: 45.58011049723757%; + *margin-left: 45.47372751851417%; + } + .row-fluid .offset5:first-child { + margin-left: 42.81767955801105%; + *margin-left: 42.71129657928765%; + } + .row-fluid .offset4 { + margin-left: 37.01657458563536%; + *margin-left: 36.91019160691196%; + } + .row-fluid .offset4:first-child { + margin-left: 34.25414364640884%; + *margin-left: 34.14776066768544%; + } + .row-fluid .offset3 { + margin-left: 28.45303867403315%; + *margin-left: 28.346655695309746%; + } + .row-fluid .offset3:first-child { + margin-left: 25.69060773480663%; + *margin-left: 25.584224756083227%; + } + .row-fluid .offset2 { + margin-left: 19.88950276243094%; + *margin-left: 19.783119783707537%; + } + .row-fluid .offset2:first-child { + margin-left: 17.12707182320442%; + *margin-left: 17.02068884448102%; + } + .row-fluid .offset1 { + margin-left: 11.32596685082873%; + *margin-left: 11.219583872105325%; + } + .row-fluid .offset1:first-child { + margin-left: 8.56353591160221%; + *margin-left: 8.457152932878806%; + } + input, + textarea, + .uneditable-input { + margin-left: 0; + } + .controls-row [class*="span"] + [class*="span"] { + margin-left: 20px; + } + input.span12, + textarea.span12, + .uneditable-input.span12 { + width: 710px; + } + input.span11, + textarea.span11, + .uneditable-input.span11 { + width: 648px; + } + input.span10, + textarea.span10, + .uneditable-input.span10 { + width: 586px; + } + input.span9, + textarea.span9, + .uneditable-input.span9 { + width: 524px; + } + input.span8, + textarea.span8, + .uneditable-input.span8 { + width: 462px; + } + input.span7, + textarea.span7, + .uneditable-input.span7 { + width: 400px; + } + input.span6, + textarea.span6, + .uneditable-input.span6 { + width: 338px; + } + input.span5, + textarea.span5, + .uneditable-input.span5 { + width: 276px; + } + input.span4, + textarea.span4, + .uneditable-input.span4 { + width: 214px; + } + input.span3, + textarea.span3, + .uneditable-input.span3 { + width: 152px; + } + input.span2, + textarea.span2, + .uneditable-input.span2 { + width: 90px; + } + input.span1, + textarea.span1, + .uneditable-input.span1 { + width: 28px; + } +} +@media (min-width: 1200px) { + .row { + margin-left: -30px; + *zoom: 1; + } + .row:before, + .row:after { + display: table; + content: ""; + line-height: 0; + } + .row:after { + clear: both; + } + [class*="span"] { + float: left; + min-height: 1px; + margin-left: 30px; + } + .container, + .navbar-static-top .container, + .navbar-fixed-top .container, + .navbar-fixed-bottom .container { + width: 1170px; + } + .span12 { + width: 1170px; + } + .span11 { + width: 1070px; + } + .span10 { + width: 970px; + } + .span9 { + width: 870px; + } + .span8 { + width: 770px; + } + .span7 { + width: 670px; + } + .span6 { + width: 570px; + } + .span5 { + width: 470px; + } + .span4 { + width: 370px; + } + .span3 { + width: 270px; + } + .span2 { + width: 170px; + } + .span1 { + width: 70px; + } + .offset12 { + margin-left: 1230px; + } + .offset11 { + margin-left: 1130px; + } + .offset10 { + margin-left: 1030px; + } + .offset9 { + margin-left: 930px; + } + .offset8 { + margin-left: 830px; + } + .offset7 { + margin-left: 730px; + } + .offset6 { + margin-left: 630px; + } + .offset5 { + margin-left: 530px; + } + .offset4 { + margin-left: 430px; + } + .offset3 { + margin-left: 330px; + } + .offset2 { + margin-left: 230px; + } + .offset1 { + margin-left: 130px; + } + .row-fluid { + width: 100%; + *zoom: 1; + } + .row-fluid:before, + .row-fluid:after { + display: table; + content: ""; + line-height: 0; + } + .row-fluid:after { + clear: both; + } + .row-fluid [class*="span"] { + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + float: left; + margin-left: 2.564102564102564%; + *margin-left: 2.5109110747408616%; + } + .row-fluid [class*="span"]:first-child { + margin-left: 0; + } + .row-fluid .controls-row [class*="span"] + [class*="span"] { + margin-left: 2.564102564102564%; + } + .row-fluid .span12 { + width: 100%; + *width: 99.94680851063829%; + } + .row-fluid .span11 { + width: 91.45299145299145%; + *width: 91.39979996362975%; + } + .row-fluid .span10 { + width: 82.90598290598291%; + *width: 82.8527914166212%; + } + .row-fluid .span9 { + width: 74.35897435897436%; + *width: 74.30578286961266%; + } + .row-fluid .span8 { + width: 65.81196581196582%; + *width: 65.75877432260411%; + } + .row-fluid .span7 { + width: 57.26495726495726%; + *width: 57.21176577559556%; + } + .row-fluid .span6 { + width: 48.717948717948715%; + *width: 48.664757228587014%; + } + .row-fluid .span5 { + width: 40.17094017094017%; + *width: 40.11774868157847%; + } + .row-fluid .span4 { + width: 31.623931623931625%; + *width: 31.570740134569924%; + } + .row-fluid .span3 { + width: 23.076923076923077%; + *width: 23.023731587561375%; + } + .row-fluid .span2 { + width: 14.52991452991453%; + *width: 14.476723040552828%; + } + .row-fluid .span1 { + width: 5.982905982905983%; + *width: 5.929714493544281%; + } + .row-fluid .offset12 { + margin-left: 105.12820512820512%; + *margin-left: 105.02182214948171%; + } + .row-fluid .offset12:first-child { + margin-left: 102.56410256410257%; + *margin-left: 102.45771958537915%; + } + .row-fluid .offset11 { + margin-left: 96.58119658119658%; + *margin-left: 96.47481360247316%; + } + .row-fluid .offset11:first-child { + margin-left: 94.01709401709402%; + *margin-left: 93.91071103837061%; + } + .row-fluid .offset10 { + margin-left: 88.03418803418803%; + *margin-left: 87.92780505546462%; + } + .row-fluid .offset10:first-child { + margin-left: 85.47008547008548%; + *margin-left: 85.36370249136206%; + } + .row-fluid .offset9 { + margin-left: 79.48717948717949%; + *margin-left: 79.38079650845607%; + } + .row-fluid .offset9:first-child { + margin-left: 76.92307692307693%; + *margin-left: 76.81669394435352%; + } + .row-fluid .offset8 { + margin-left: 70.94017094017094%; + *margin-left: 70.83378796144753%; + } + .row-fluid .offset8:first-child { + margin-left: 68.37606837606839%; + *margin-left: 68.26968539734497%; + } + .row-fluid .offset7 { + margin-left: 62.393162393162385%; + *margin-left: 62.28677941443899%; + } + .row-fluid .offset7:first-child { + margin-left: 59.82905982905982%; + *margin-left: 59.72267685033642%; + } + .row-fluid .offset6 { + margin-left: 53.84615384615384%; + *margin-left: 53.739770867430444%; + } + .row-fluid .offset6:first-child { + margin-left: 51.28205128205128%; + *margin-left: 51.175668303327875%; + } + .row-fluid .offset5 { + margin-left: 45.299145299145295%; + *margin-left: 45.1927623204219%; + } + .row-fluid .offset5:first-child { + margin-left: 42.73504273504273%; + *margin-left: 42.62865975631933%; + } + .row-fluid .offset4 { + margin-left: 36.75213675213675%; + *margin-left: 36.645753773413354%; + } + .row-fluid .offset4:first-child { + margin-left: 34.18803418803419%; + *margin-left: 34.081651209310785%; + } + .row-fluid .offset3 { + margin-left: 28.205128205128204%; + *margin-left: 28.0987452264048%; + } + .row-fluid .offset3:first-child { + margin-left: 25.641025641025642%; + *margin-left: 25.53464266230224%; + } + .row-fluid .offset2 { + margin-left: 19.65811965811966%; + *margin-left: 19.551736679396257%; + } + .row-fluid .offset2:first-child { + margin-left: 17.094017094017094%; + *margin-left: 16.98763411529369%; + } + .row-fluid .offset1 { + margin-left: 11.11111111111111%; + *margin-left: 11.004728132387708%; + } + .row-fluid .offset1:first-child { + margin-left: 8.547008547008547%; + *margin-left: 8.440625568285142%; + } + input, + textarea, + .uneditable-input { + margin-left: 0; + } + .controls-row [class*="span"] + [class*="span"] { + margin-left: 30px; + } + input.span12, + textarea.span12, + .uneditable-input.span12 { + width: 1156px; + } + input.span11, + textarea.span11, + .uneditable-input.span11 { + width: 1056px; + } + input.span10, + textarea.span10, + .uneditable-input.span10 { + width: 956px; + } + input.span9, + textarea.span9, + .uneditable-input.span9 { + width: 856px; + } + input.span8, + textarea.span8, + .uneditable-input.span8 { + width: 756px; + } + input.span7, + textarea.span7, + .uneditable-input.span7 { + width: 656px; + } + input.span6, + textarea.span6, + .uneditable-input.span6 { + width: 556px; + } + input.span5, + textarea.span5, + .uneditable-input.span5 { + width: 456px; + } + input.span4, + textarea.span4, + .uneditable-input.span4 { + width: 356px; + } + input.span3, + textarea.span3, + .uneditable-input.span3 { + width: 256px; + } + input.span2, + textarea.span2, + .uneditable-input.span2 { + width: 156px; + } + input.span1, + textarea.span1, + .uneditable-input.span1 { + width: 56px; + } + .thumbnails { + margin-left: -30px; + } + .thumbnails > li { + margin-left: 30px; + } + .row-fluid .thumbnails { + margin-left: 0; + } +} +@media (max-width: 979px) { + body { + padding-top: 0; + } + .navbar-fixed-top, + .navbar-fixed-bottom { + position: static; + } + .navbar-fixed-top { + margin-bottom: 20px; + } + .navbar-fixed-bottom { + margin-top: 20px; + } + .navbar-fixed-top .navbar-inner, + .navbar-fixed-bottom .navbar-inner { + padding: 5px; + } + .navbar .container { + width: auto; + padding: 0; + } + .navbar .brand { + padding-left: 10px; + padding-right: 10px; + margin: 0 0 0 -5px; + } + .nav-collapse { + clear: both; + } + .nav-collapse .nav { + float: none; + margin: 0 0 10px; + } + .nav-collapse .nav > li { + float: none; + } + .nav-collapse .nav > li > a { + margin-bottom: 2px; + } + .nav-collapse .nav > .divider-vertical { + display: none; + } + .nav-collapse .nav .nav-header { + color: #777777; + text-shadow: none; + } + .nav-collapse .nav > li > a, + .nav-collapse .dropdown-menu a { + padding: 9px 15px; + font-weight: bold; + color: #777777; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + } + .nav-collapse .btn { + padding: 4px 10px 4px; + font-weight: normal; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + } + .nav-collapse .dropdown-menu li + li a { + margin-bottom: 2px; + } + .nav-collapse .nav > li > a:hover, + .nav-collapse .nav > li > a:focus, + .nav-collapse .dropdown-menu a:hover, + .nav-collapse .dropdown-menu a:focus { + background-color: #f2f2f2; + } + .navbar-inverse .nav-collapse .nav > li > a, + .navbar-inverse .nav-collapse .dropdown-menu a { + color: #999999; + } + .navbar-inverse .nav-collapse .nav > li > a:hover, + .navbar-inverse .nav-collapse .nav > li > a:focus, + .navbar-inverse .nav-collapse .dropdown-menu a:hover, + .navbar-inverse .nav-collapse .dropdown-menu a:focus { + background-color: #111111; + } + .nav-collapse.in .btn-group { + margin-top: 5px; + padding: 0; + } + .nav-collapse .dropdown-menu { + position: static; + top: auto; + left: auto; + float: none; + display: none; + max-width: none; + margin: 0 15px; + padding: 0; + background-color: transparent; + border: none; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + } + .nav-collapse .open > .dropdown-menu { + display: block; + } + .nav-collapse .dropdown-menu:before, + .nav-collapse .dropdown-menu:after { + display: none; + } + .nav-collapse .dropdown-menu .divider { + display: none; + } + .nav-collapse .nav > li > .dropdown-menu:before, + .nav-collapse .nav > li > .dropdown-menu:after { + display: none; + } + .nav-collapse .navbar-form, + .nav-collapse .navbar-search { + float: none; + padding: 10px 15px; + margin: 10px 0; + border-top: 1px solid #f2f2f2; + border-bottom: 1px solid #f2f2f2; + -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); + -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); + box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); + } + .navbar-inverse .nav-collapse .navbar-form, + .navbar-inverse .nav-collapse .navbar-search { + border-top-color: #111111; + border-bottom-color: #111111; + } + .navbar .nav-collapse .nav.pull-right { + float: none; + margin-left: 0; + } + .nav-collapse, + .nav-collapse.collapse { + overflow: hidden; + height: 0; + } + .navbar .btn-navbar { + display: block; + } + .navbar-static .navbar-inner { + padding-left: 10px; + padding-right: 10px; + } +} +@media (min-width: 980px) { + .nav-collapse.collapse { + height: auto !important; + overflow: visible !important; + } +} diff --git a/doc/themes/scikit-learn/static/css/bootstrap.min.css b/doc/themes/scikit-learn/static/css/bootstrap.min.css new file mode 100644 index 0000000000000..2f4146227e04c --- /dev/null +++ b/doc/themes/scikit-learn/static/css/bootstrap.min.css @@ -0,0 +1,857 @@ +/*! + * Bootstrap v2.3.2 + * + * Copyright 2012 Twitter, Inc + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world @twitter by @mdo and @fat. + */ +.clearfix{*zoom:1;}.clearfix:before,.clearfix:after{display:table;content:"";line-height:0;} +.clearfix:after{clear:both;} +.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0;} +.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} +article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block;} +audio,canvas,video{display:inline-block;*display:inline;*zoom:1;} +audio:not([controls]){display:none;} +html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;} +a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;} +a:hover,a:active{outline:0;} +sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline;} +sup{top:-0.5em;} +sub{bottom:-0.25em;} +img{max-width:100%;width:auto\9;height:auto;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic;} +#map_canvas img,.google-maps img{max-width:none;} +button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle;} +button,input{*overflow:visible;line-height:normal;} +button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0;} +button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer;} +label,select,button,input[type="button"],input[type="reset"],input[type="submit"],input[type="radio"],input[type="checkbox"]{cursor:pointer;} +input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield;} +input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none;} +textarea{overflow:auto;vertical-align:top;} +.img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;} +.img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);-webkit-box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);-moz-box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);} +.img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px;} +.row{margin-left:-20px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;} +.row:after{clear:both;} +[class*="span"]{float:left;min-height:1px;margin-left:20px;} +.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px;} +.span12{width:940px;} +.span11{width:860px;} +.span10{width:780px;} +.span9{width:700px;} +.span8{width:620px;} +.span7{width:540px;} +.span6{width:460px;} +.span5{width:380px;} +.span4{width:300px;} +.span3{width:220px;} +.span2{width:140px;} +.span1{width:60px;} +.offset12{margin-left:980px;} +.offset11{margin-left:900px;} +.offset10{margin-left:820px;} +.offset9{margin-left:740px;} +.offset8{margin-left:660px;} +.offset7{margin-left:580px;} +.offset6{margin-left:500px;} +.offset5{margin-left:420px;} +.offset4{margin-left:340px;} +.offset3{margin-left:260px;} +.offset2{margin-left:180px;} +.offset1{margin-left:100px;} +.row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;} +.row-fluid:after{clear:both;} +.row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;} +.row-fluid [class*="span"]:first-child{margin-left:0;} +.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.127659574468085%;} +.row-fluid .span12{width:100%;*width:99.94680851063829%;} +.row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%;} +.row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%;} +.row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%;} +.row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%;} +.row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%;} +.row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%;} +.row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%;} +.row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%;} +.row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%;} +.row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%;} +.row-fluid .span1{width:6.382978723404255%;*width:6.329787234042553%;} +.row-fluid .offset12{margin-left:104.25531914893617%;*margin-left:104.14893617021275%;} +.row-fluid .offset12:first-child{margin-left:102.12765957446808%;*margin-left:102.02127659574467%;} +.row-fluid .offset11{margin-left:95.74468085106382%;*margin-left:95.6382978723404%;} +.row-fluid .offset11:first-child{margin-left:93.61702127659574%;*margin-left:93.51063829787232%;} +.row-fluid .offset10{margin-left:87.23404255319149%;*margin-left:87.12765957446807%;} +.row-fluid .offset10:first-child{margin-left:85.1063829787234%;*margin-left:84.99999999999999%;} +.row-fluid .offset9{margin-left:78.72340425531914%;*margin-left:78.61702127659572%;} +.row-fluid .offset9:first-child{margin-left:76.59574468085106%;*margin-left:76.48936170212764%;} +.row-fluid .offset8{margin-left:70.2127659574468%;*margin-left:70.10638297872339%;} +.row-fluid .offset8:first-child{margin-left:68.08510638297872%;*margin-left:67.9787234042553%;} +.row-fluid .offset7{margin-left:61.70212765957446%;*margin-left:61.59574468085106%;} +.row-fluid .offset7:first-child{margin-left:59.574468085106375%;*margin-left:59.46808510638297%;} +.row-fluid .offset6{margin-left:53.191489361702125%;*margin-left:53.085106382978715%;} +.row-fluid .offset6:first-child{margin-left:51.063829787234035%;*margin-left:50.95744680851063%;} +.row-fluid .offset5{margin-left:44.68085106382979%;*margin-left:44.57446808510638%;} +.row-fluid .offset5:first-child{margin-left:42.5531914893617%;*margin-left:42.4468085106383%;} +.row-fluid .offset4{margin-left:36.170212765957444%;*margin-left:36.06382978723405%;} +.row-fluid .offset4:first-child{margin-left:34.04255319148936%;*margin-left:33.93617021276596%;} +.row-fluid .offset3{margin-left:27.659574468085104%;*margin-left:27.5531914893617%;} +.row-fluid .offset3:first-child{margin-left:25.53191489361702%;*margin-left:25.425531914893618%;} +.row-fluid .offset2{margin-left:19.148936170212764%;*margin-left:19.04255319148936%;} +.row-fluid .offset2:first-child{margin-left:17.02127659574468%;*margin-left:16.914893617021278%;} +.row-fluid .offset1{margin-left:10.638297872340425%;*margin-left:10.53191489361702%;} +.row-fluid .offset1:first-child{margin-left:8.51063829787234%;*margin-left:8.404255319148938%;} +[class*="span"].hide,.row-fluid [class*="span"].hide{display:none;} +[class*="span"].pull-right,.row-fluid [class*="span"].pull-right{float:right;} +.container{margin-right:auto;margin-left:auto;*zoom:1;}.container:before,.container:after{display:table;content:"";line-height:0;} +.container:after{clear:both;} +.container-fluid{padding-right:20px;padding-left:20px;*zoom:1;}.container-fluid:before,.container-fluid:after{display:table;content:"";line-height:0;} +.container-fluid:after{clear:both;} +p{margin:0 0 10px;} +.lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px;} +small{font-size:85%;} +strong{font-weight:bold;} +em{font-style:italic;} +cite{font-style:normal;} +.muted{color:#999999;} +a.muted:hover,a.muted:focus{color:#808080;} +.text-warning{color:#c09853;} +a.text-warning:hover,a.text-warning:focus{color:#a47e3c;} +.text-error{color:#b94a48;} +a.text-error:hover,a.text-error:focus{color:#953b39;} +.text-info{color:#3a87ad;} +a.text-info:hover,a.text-info:focus{color:#2d6987;} +.text-success{color:#468847;} +a.text-success:hover,a.text-success:focus{color:#356635;} +.text-left{text-align:left;} +.text-right{text-align:right;} +.text-center{text-align:center;} +.page-header{padding-bottom:9px;margin:20px 0 30px;border-bottom:1px solid #eeeeee;} +ul,ol{padding:0;margin:0 0 10px 25px;} +ul ul,ul ol,ol ol,ol ul{margin-bottom:0;} +li{line-height:20px;} +ul.unstyled,ol.unstyled{margin-left:0;list-style:none;} +ul.inline,ol.inline{margin-left:0;list-style:none;}ul.inline>li,ol.inline>li{display:inline-block;*display:inline;*zoom:1;padding-left:5px;padding-right:5px;} +dl{margin-bottom:20px;} +dt,dd{line-height:20px;} +dt{font-weight:bold;} +dd{margin-left:10px;} +.dl-horizontal{*zoom:1;}.dl-horizontal:before,.dl-horizontal:after{display:table;content:"";line-height:0;} +.dl-horizontal:after{clear:both;} +.dl-horizontal dt{float:left;width:160px;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;} +.dl-horizontal dd{margin-left:180px;} +hr{margin:20px 0;border:0;border-top:1px solid #eeeeee;border-bottom:1px solid #ffffff;} +abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999999;} +abbr.initialism{font-size:90%;text-transform:uppercase;} +blockquote small{display:block;line-height:20px;color:#999999;}blockquote small:before{content:'\2014 \00A0';} +blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eeeeee;border-left:0;}blockquote.pull-right p,blockquote.pull-right small{text-align:right;} +blockquote.pull-right small:before{content:'';} +blockquote.pull-right small:after{content:'\00A0 \2014';} +q:before,q:after,blockquote:before,blockquote:after{content:"";} +address{display:block;margin-bottom:20px;font-style:normal;line-height:20px;} +code,pre{padding:0 3px 2px;font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;color:#333333;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} +code{padding:2px 4px;color:#d14;background-color:#f7f7f9;border:1px solid #e1e1e8;white-space:nowrap;} +pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:20px;word-break:break-all;word-wrap:break-word;white-space:pre;white-space:pre-wrap;background-color:#f5f5f5;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}pre.prettyprint{margin-bottom:20px;} +pre code{padding:0;color:inherit;white-space:pre;white-space:pre-wrap;background-color:transparent;border:0;} +.pre-scrollable{max-height:340px;overflow-y:scroll;} +.label,.badge{display:inline-block;padding:2px 4px;font-size:11.844px;font-weight:bold;line-height:14px;color:#ffffff;vertical-align:baseline;white-space:nowrap;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#999999;} +.label{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} +.badge{padding-left:9px;padding-right:9px;-webkit-border-radius:9px;-moz-border-radius:9px;border-radius:9px;} +.label:empty,.badge:empty{display:none;} +a.label:hover,a.label:focus,a.badge:hover,a.badge:focus{color:#ffffff;text-decoration:none;cursor:pointer;} +.label-important,.badge-important{background-color:#b94a48;} +.label-important[href],.badge-important[href]{background-color:#953b39;} +.label-warning,.badge-warning{background-color:#f89406;} +.label-warning[href],.badge-warning[href]{background-color:#c67605;} +.label-success,.badge-success{background-color:#468847;} +.label-success[href],.badge-success[href]{background-color:#356635;} +.label-info,.badge-info{background-color:#3a87ad;} +.label-info[href],.badge-info[href]{background-color:#2d6987;} +.label-inverse,.badge-inverse{background-color:#333333;} +.label-inverse[href],.badge-inverse[href]{background-color:#1a1a1a;} +.btn .label,.btn .badge{position:relative;top:-1px;} +.btn-mini .label,.btn-mini .badge{top:0;} +table{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;} +.table{width:100%;margin-bottom:20px;}.table th,.table td{padding:8px;line-height:20px;text-align:left;vertical-align:top;border-top:1px solid #dddddd;} +.table th{font-weight:bold;} +.table thead th{vertical-align:bottom;} +.table caption+thead tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child th,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child th,.table thead:first-child tr:first-child td{border-top:0;} +.table tbody+tbody{border-top:2px solid #dddddd;} +.table .table{background-color:#ffffff;} +.table-condensed th,.table-condensed td{padding:4px 5px;} +.table-bordered{border:1px solid #dddddd;border-collapse:separate;*border-collapse:collapse;border-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}.table-bordered th,.table-bordered td{border-left:1px solid #dddddd;} +.table-bordered caption+thead tr:first-child th,.table-bordered caption+tbody tr:first-child th,.table-bordered caption+tbody tr:first-child td,.table-bordered colgroup+thead tr:first-child th,.table-bordered colgroup+tbody tr:first-child th,.table-bordered colgroup+tbody tr:first-child td,.table-bordered thead:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child td{border-top:0;} +.table-bordered thead:first-child tr:first-child>th:first-child,.table-bordered tbody:first-child tr:first-child>td:first-child,.table-bordered tbody:first-child tr:first-child>th:first-child{-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;} +.table-bordered thead:first-child tr:first-child>th:last-child,.table-bordered tbody:first-child tr:first-child>td:last-child,.table-bordered tbody:first-child tr:first-child>th:last-child{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;} +.table-bordered thead:last-child tr:last-child>th:first-child,.table-bordered tbody:last-child tr:last-child>td:first-child,.table-bordered tbody:last-child tr:last-child>th:first-child,.table-bordered tfoot:last-child tr:last-child>td:first-child,.table-bordered tfoot:last-child tr:last-child>th:first-child{-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;} +.table-bordered thead:last-child tr:last-child>th:last-child,.table-bordered tbody:last-child tr:last-child>td:last-child,.table-bordered tbody:last-child tr:last-child>th:last-child,.table-bordered tfoot:last-child tr:last-child>td:last-child,.table-bordered tfoot:last-child tr:last-child>th:last-child{-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;} +.table-bordered tfoot+tbody:last-child tr:last-child td:first-child{-webkit-border-bottom-left-radius:0;-moz-border-radius-bottomleft:0;border-bottom-left-radius:0;} +.table-bordered tfoot+tbody:last-child tr:last-child td:last-child{-webkit-border-bottom-right-radius:0;-moz-border-radius-bottomright:0;border-bottom-right-radius:0;} +.table-bordered caption+thead tr:first-child th:first-child,.table-bordered caption+tbody tr:first-child td:first-child,.table-bordered colgroup+thead tr:first-child th:first-child,.table-bordered colgroup+tbody tr:first-child td:first-child{-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;} +.table-bordered caption+thead tr:first-child th:last-child,.table-bordered caption+tbody tr:first-child td:last-child,.table-bordered colgroup+thead tr:first-child th:last-child,.table-bordered colgroup+tbody tr:first-child td:last-child{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;} +.table-striped tbody>tr:nth-child(odd)>td,.table-striped tbody>tr:nth-child(odd)>th{background-color:#f9f9f9;} +.table-hover tbody tr:hover>td,.table-hover tbody tr:hover>th{background-color:#f5f5f5;} +table td[class*="span"],table th[class*="span"],.row-fluid table td[class*="span"],.row-fluid table th[class*="span"]{display:table-cell;float:none;margin-left:0;} +.table td.span1,.table th.span1{float:none;width:44px;margin-left:0;} +.table td.span2,.table th.span2{float:none;width:124px;margin-left:0;} +.table td.span3,.table th.span3{float:none;width:204px;margin-left:0;} +.table td.span4,.table th.span4{float:none;width:284px;margin-left:0;} +.table td.span5,.table th.span5{float:none;width:364px;margin-left:0;} +.table td.span6,.table th.span6{float:none;width:444px;margin-left:0;} +.table td.span7,.table th.span7{float:none;width:524px;margin-left:0;} +.table td.span8,.table th.span8{float:none;width:604px;margin-left:0;} +.table td.span9,.table th.span9{float:none;width:684px;margin-left:0;} +.table td.span10,.table th.span10{float:none;width:764px;margin-left:0;} +.table td.span11,.table th.span11{float:none;width:844px;margin-left:0;} +.table td.span12,.table th.span12{float:none;width:924px;margin-left:0;} +.table tbody tr.success>td{background-color:#dff0d8;} +.table tbody tr.error>td{background-color:#f2dede;} +.table tbody tr.warning>td{background-color:#fcf8e3;} +.table tbody tr.info>td{background-color:#d9edf7;} +.table-hover tbody tr.success:hover>td{background-color:#d0e9c6;} +.table-hover tbody tr.error:hover>td{background-color:#ebcccc;} +.table-hover tbody tr.warning:hover>td{background-color:#faf2cc;} +.table-hover tbody tr.info:hover>td{background-color:#c4e3f3;} +form{margin:0 0 20px;} +fieldset{padding:0;margin:0;border:0;} +legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333333;border:0;border-bottom:1px solid #e5e5e5;}legend small{font-size:15px;color:#999999;} +label,input,button,select,textarea{font-size:14px;font-weight:normal;line-height:20px;} +input,button,select,textarea{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;} +label{display:block;margin-bottom:5px;} +select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px 6px;margin-bottom:10px;font-size:14px;line-height:20px;color:#555555;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;vertical-align:middle;} +input,textarea,.uneditable-input{width:206px;} +textarea{height:auto;} +textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear .2s, box-shadow linear .2s;-moz-transition:border linear .2s, box-shadow linear .2s;-o-transition:border linear .2s, box-shadow linear .2s;transition:border linear .2s, box-shadow linear .2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);} +input[type="radio"],input[type="checkbox"]{margin:4px 0 0;*margin-top:0;margin-top:1px \9;line-height:normal;} +input[type="file"],input[type="image"],input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;} +select,input[type="file"]{height:30px;*margin-top:4px;line-height:30px;} +select{width:220px;border:1px solid #cccccc;background-color:#ffffff;} +select[multiple],select[size]{height:auto;} +select:focus,input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;} +.uneditable-input,.uneditable-textarea{color:#999999;background-color:#fcfcfc;border-color:#cccccc;-webkit-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);-moz-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);cursor:not-allowed;} +.uneditable-input{overflow:hidden;white-space:nowrap;} +.uneditable-textarea{width:auto;height:auto;} +input:-moz-placeholder,textarea:-moz-placeholder{color:#999999;} +input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#999999;} +input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:#999999;} +.radio,.checkbox{min-height:20px;padding-left:20px;} +.radio input[type="radio"],.checkbox input[type="checkbox"]{float:left;margin-left:-20px;} +.controls>.radio:first-child,.controls>.checkbox:first-child{padding-top:5px;} +.radio.inline,.checkbox.inline{display:inline-block;padding-top:5px;margin-bottom:0;vertical-align:middle;} +.radio.inline+.radio.inline,.checkbox.inline+.checkbox.inline{margin-left:10px;} +.input-mini{width:60px;} +.input-small{width:90px;} +.input-medium{width:150px;} +.input-large{width:210px;} +.input-xlarge{width:270px;} +.input-xxlarge{width:530px;} +input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"]{float:none;margin-left:0;} +.input-append input[class*="span"],.input-append .uneditable-input[class*="span"],.input-prepend input[class*="span"],.input-prepend .uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"],.row-fluid .input-prepend [class*="span"],.row-fluid .input-append [class*="span"]{display:inline-block;} +input,textarea,.uneditable-input{margin-left:0;} +.controls-row [class*="span"]+[class*="span"]{margin-left:20px;} +input.span12,textarea.span12,.uneditable-input.span12{width:926px;} +input.span11,textarea.span11,.uneditable-input.span11{width:846px;} +input.span10,textarea.span10,.uneditable-input.span10{width:766px;} +input.span9,textarea.span9,.uneditable-input.span9{width:686px;} +input.span8,textarea.span8,.uneditable-input.span8{width:606px;} +input.span7,textarea.span7,.uneditable-input.span7{width:526px;} +input.span6,textarea.span6,.uneditable-input.span6{width:446px;} +input.span5,textarea.span5,.uneditable-input.span5{width:366px;} +input.span4,textarea.span4,.uneditable-input.span4{width:286px;} +input.span3,textarea.span3,.uneditable-input.span3{width:206px;} +input.span2,textarea.span2,.uneditable-input.span2{width:126px;} +input.span1,textarea.span1,.uneditable-input.span1{width:46px;} +.controls-row{*zoom:1;}.controls-row:before,.controls-row:after{display:table;content:"";line-height:0;} +.controls-row:after{clear:both;} +.controls-row [class*="span"],.row-fluid .controls-row [class*="span"]{float:left;} +.controls-row .checkbox[class*="span"],.controls-row .radio[class*="span"]{padding-top:5px;} +input[disabled],select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#eeeeee;} +input[type="radio"][disabled],input[type="checkbox"][disabled],input[type="radio"][readonly],input[type="checkbox"][readonly]{background-color:transparent;} +.control-group.warning .control-label,.control-group.warning .help-block,.control-group.warning .help-inline{color:#c09853;} +.control-group.warning .checkbox,.control-group.warning .radio,.control-group.warning input,.control-group.warning select,.control-group.warning textarea{color:#c09853;} +.control-group.warning input,.control-group.warning select,.control-group.warning textarea{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.warning input:focus,.control-group.warning select:focus,.control-group.warning textarea:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #dbc59e;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #dbc59e;} +.control-group.warning .input-prepend .add-on,.control-group.warning .input-append .add-on{color:#c09853;background-color:#fcf8e3;border-color:#c09853;} +.control-group.error .control-label,.control-group.error .help-block,.control-group.error .help-inline{color:#b94a48;} +.control-group.error .checkbox,.control-group.error .radio,.control-group.error input,.control-group.error select,.control-group.error textarea{color:#b94a48;} +.control-group.error input,.control-group.error select,.control-group.error textarea{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.error input:focus,.control-group.error select:focus,.control-group.error textarea:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #d59392;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #d59392;} +.control-group.error .input-prepend .add-on,.control-group.error .input-append .add-on{color:#b94a48;background-color:#f2dede;border-color:#b94a48;} +.control-group.success .control-label,.control-group.success .help-block,.control-group.success .help-inline{color:#468847;} +.control-group.success .checkbox,.control-group.success .radio,.control-group.success input,.control-group.success select,.control-group.success textarea{color:#468847;} +.control-group.success input,.control-group.success select,.control-group.success textarea{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.success input:focus,.control-group.success select:focus,.control-group.success textarea:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7aba7b;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7aba7b;} +.control-group.success .input-prepend .add-on,.control-group.success .input-append .add-on{color:#468847;background-color:#dff0d8;border-color:#468847;} +.control-group.info .control-label,.control-group.info .help-block,.control-group.info .help-inline{color:#3a87ad;} +.control-group.info .checkbox,.control-group.info .radio,.control-group.info input,.control-group.info select,.control-group.info textarea{color:#3a87ad;} +.control-group.info input,.control-group.info select,.control-group.info textarea{border-color:#3a87ad;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.info input:focus,.control-group.info select:focus,.control-group.info textarea:focus{border-color:#2d6987;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7ab5d3;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7ab5d3;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7ab5d3;} +.control-group.info .input-prepend .add-on,.control-group.info .input-append .add-on{color:#3a87ad;background-color:#d9edf7;border-color:#3a87ad;} +input:focus:invalid,textarea:focus:invalid,select:focus:invalid{color:#b94a48;border-color:#ee5f5b;}input:focus:invalid:focus,textarea:focus:invalid:focus,select:focus:invalid:focus{border-color:#e9322d;-webkit-box-shadow:0 0 6px #f8b9b7;-moz-box-shadow:0 0 6px #f8b9b7;box-shadow:0 0 6px #f8b9b7;} +.form-actions{padding:19px 20px 20px;margin-top:20px;margin-bottom:20px;background-color:#f5f5f5;border-top:1px solid #e5e5e5;*zoom:1;}.form-actions:before,.form-actions:after{display:table;content:"";line-height:0;} +.form-actions:after{clear:both;} +.help-block,.help-inline{color:#595959;} +.help-block{display:block;margin-bottom:10px;} +.help-inline{display:inline-block;*display:inline;*zoom:1;vertical-align:middle;padding-left:5px;} +.input-append,.input-prepend{display:inline-block;margin-bottom:10px;vertical-align:middle;font-size:0;white-space:nowrap;}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input,.input-append .dropdown-menu,.input-prepend .dropdown-menu,.input-append .popover,.input-prepend .popover{font-size:14px;} +.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input{position:relative;margin-bottom:0;*margin-left:0;vertical-align:top;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;}.input-append input:focus,.input-prepend input:focus,.input-append select:focus,.input-prepend select:focus,.input-append .uneditable-input:focus,.input-prepend .uneditable-input:focus{z-index:2;} +.input-append .add-on,.input-prepend .add-on{display:inline-block;width:auto;height:20px;min-width:16px;padding:4px 5px;font-size:14px;font-weight:normal;line-height:20px;text-align:center;text-shadow:0 1px 0 #ffffff;background-color:#eeeeee;border:1px solid #ccc;} +.input-append .add-on,.input-prepend .add-on,.input-append .btn,.input-prepend .btn,.input-append .btn-group>.dropdown-toggle,.input-prepend .btn-group>.dropdown-toggle{vertical-align:top;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} +.input-append .active,.input-prepend .active{background-color:#a9dba9;border-color:#46a546;} +.input-prepend .add-on,.input-prepend .btn{margin-right:-1px;} +.input-prepend .add-on:first-child,.input-prepend .btn:first-child{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px;} +.input-append input,.input-append select,.input-append .uneditable-input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px;}.input-append input+.btn-group .btn:last-child,.input-append select+.btn-group .btn:last-child,.input-append .uneditable-input+.btn-group .btn:last-child{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;} +.input-append .add-on,.input-append .btn,.input-append .btn-group{margin-left:-1px;} +.input-append .add-on:last-child,.input-append .btn:last-child,.input-append .btn-group:last-child>.dropdown-toggle{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;} +.input-prepend.input-append input,.input-prepend.input-append select,.input-prepend.input-append .uneditable-input{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}.input-prepend.input-append input+.btn-group .btn,.input-prepend.input-append select+.btn-group .btn,.input-prepend.input-append .uneditable-input+.btn-group .btn{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;} +.input-prepend.input-append .add-on:first-child,.input-prepend.input-append .btn:first-child{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px;} +.input-prepend.input-append .add-on:last-child,.input-prepend.input-append .btn:last-child{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;} +.input-prepend.input-append .btn-group:first-child{margin-left:0;} +input.search-query{padding-right:14px;padding-right:4px \9;padding-left:14px;padding-left:4px \9;margin-bottom:0;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;} +.form-search .input-append .search-query,.form-search .input-prepend .search-query{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} +.form-search .input-append .search-query{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px;} +.form-search .input-append .btn{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0;} +.form-search .input-prepend .search-query{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0;} +.form-search .input-prepend .btn{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px;} +.form-search input,.form-inline input,.form-horizontal input,.form-search textarea,.form-inline textarea,.form-horizontal textarea,.form-search select,.form-inline select,.form-horizontal select,.form-search .help-inline,.form-inline .help-inline,.form-horizontal .help-inline,.form-search .uneditable-input,.form-inline .uneditable-input,.form-horizontal .uneditable-input,.form-search .input-prepend,.form-inline .input-prepend,.form-horizontal .input-prepend,.form-search .input-append,.form-inline .input-append,.form-horizontal .input-append{display:inline-block;*display:inline;*zoom:1;margin-bottom:0;vertical-align:middle;} +.form-search .hide,.form-inline .hide,.form-horizontal .hide{display:none;} +.form-search label,.form-inline label,.form-search .btn-group,.form-inline .btn-group{display:inline-block;} +.form-search .input-append,.form-inline .input-append,.form-search .input-prepend,.form-inline .input-prepend{margin-bottom:0;} +.form-search .radio,.form-search .checkbox,.form-inline .radio,.form-inline .checkbox{padding-left:0;margin-bottom:0;vertical-align:middle;} +.form-search .radio input[type="radio"],.form-search .checkbox input[type="checkbox"],.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:left;margin-right:3px;margin-left:0;} +.control-group{margin-bottom:10px;} +legend+.control-group{margin-top:20px;-webkit-margin-top-collapse:separate;} +.form-horizontal .control-group{margin-bottom:20px;*zoom:1;}.form-horizontal .control-group:before,.form-horizontal .control-group:after{display:table;content:"";line-height:0;} +.form-horizontal .control-group:after{clear:both;} +.form-horizontal .control-label{float:left;width:160px;padding-top:5px;text-align:right;} +.form-horizontal .controls{*display:inline-block;*padding-left:20px;margin-left:180px;*margin-left:0;}.form-horizontal .controls:first-child{*padding-left:180px;} +.form-horizontal .help-block{margin-bottom:0;} +.form-horizontal input+.help-block,.form-horizontal select+.help-block,.form-horizontal textarea+.help-block,.form-horizontal .uneditable-input+.help-block,.form-horizontal .input-prepend+.help-block,.form-horizontal .input-append+.help-block{margin-top:10px;} +.form-horizontal .form-actions{padding-left:180px;} +.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333333;text-shadow:0 1px 1px rgba(255, 255, 255, 0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top, #ffffff, #e6e6e6);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6));background-image:-webkit-linear-gradient(top, #ffffff, #e6e6e6);background-image:-o-linear-gradient(top, #ffffff, #e6e6e6);background-image:linear-gradient(to bottom, #ffffff, #e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #cccccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333333;background-color:#e6e6e6;*background-color:#d9d9d9;} +.btn:active,.btn.active{background-color:#cccccc \9;} +.btn:first-child{*margin-left:0;} +.btn:hover,.btn:focus{color:#333333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position 0.1s linear;-moz-transition:background-position 0.1s linear;-o-transition:background-position 0.1s linear;transition:background-position 0.1s linear;} +.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;} +.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);} +.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:0.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;} +.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;} +.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px;} +.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} +.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0;} +.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px;} +.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} +.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} +.btn-block+.btn-block{margin-top:5px;} +input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%;} +.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255, 255, 255, 0.75);} +.btn-primary{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top, #0088cc, #0044cc);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc));background-image:-webkit-linear-gradient(top, #0088cc, #0044cc);background-image:-o-linear-gradient(top, #0088cc, #0044cc);background-image:linear-gradient(to bottom, #0088cc, #0044cc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#0044cc #0044cc #002a80;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#0044cc;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#ffffff;background-color:#0044cc;*background-color:#003bb3;} +.btn-primary:active,.btn-primary.active{background-color:#003399 \9;} +.btn-warning{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#ffffff;background-color:#f89406;*background-color:#df8505;} +.btn-warning:active,.btn-warning.active{background-color:#c67605 \9;} +.btn-danger{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#da4f49;background-image:-moz-linear-gradient(top, #ee5f5b, #bd362f);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f));background-image:-webkit-linear-gradient(top, #ee5f5b, #bd362f);background-image:-o-linear-gradient(top, #ee5f5b, #bd362f);background-image:linear-gradient(to bottom, #ee5f5b, #bd362f);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0);border-color:#bd362f #bd362f #802420;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#bd362f;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#ffffff;background-color:#bd362f;*background-color:#a9302a;} +.btn-danger:active,.btn-danger.active{background-color:#942a25 \9;} +.btn-success{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#5bb75b;background-image:-moz-linear-gradient(top, #62c462, #51a351);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351));background-image:-webkit-linear-gradient(top, #62c462, #51a351);background-image:-o-linear-gradient(top, #62c462, #51a351);background-image:linear-gradient(to bottom, #62c462, #51a351);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0);border-color:#51a351 #51a351 #387038;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#51a351;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#ffffff;background-color:#51a351;*background-color:#499249;} +.btn-success:active,.btn-success.active{background-color:#408140 \9;} +.btn-info{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#49afcd;background-image:-moz-linear-gradient(top, #5bc0de, #2f96b4);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4));background-image:-webkit-linear-gradient(top, #5bc0de, #2f96b4);background-image:-o-linear-gradient(top, #5bc0de, #2f96b4);background-image:linear-gradient(to bottom, #5bc0de, #2f96b4);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0);border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#2f96b4;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#ffffff;background-color:#2f96b4;*background-color:#2a85a0;} +.btn-info:active,.btn-info.active{background-color:#24748c \9;} +.btn-inverse{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#363636;background-image:-moz-linear-gradient(top, #444444, #222222);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222));background-image:-webkit-linear-gradient(top, #444444, #222222);background-image:-o-linear-gradient(top, #444444, #222222);background-image:linear-gradient(to bottom, #444444, #222222);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0);border-color:#222222 #222222 #000000;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#222222;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#ffffff;background-color:#222222;*background-color:#151515;} +.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9;} +button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px;}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0;} +button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px;} +button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px;} +button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px;} +.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;} +.btn-link{border-color:transparent;cursor:pointer;color:#0088cc;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} +.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent;} +.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333333;text-decoration:none;} +[class^="icon-"],[class*=" icon-"]{display:inline-block;width:14px;height:14px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("http://github.com/img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat;margin-top:1px;} +.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:focus>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>li>a:focus>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:focus>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"],.dropdown-submenu:focus>a>[class*=" icon-"]{background-image:url("http://github.com/img/glyphicons-halflings-white.png");} +.icon-glass{background-position:0 0;} +.icon-music{background-position:-24px 0;} +.icon-search{background-position:-48px 0;} +.icon-envelope{background-position:-72px 0;} +.icon-heart{background-position:-96px 0;} +.icon-star{background-position:-120px 0;} +.icon-star-empty{background-position:-144px 0;} +.icon-user{background-position:-168px 0;} +.icon-film{background-position:-192px 0;} +.icon-th-large{background-position:-216px 0;} +.icon-th{background-position:-240px 0;} +.icon-th-list{background-position:-264px 0;} +.icon-ok{background-position:-288px 0;} +.icon-remove{background-position:-312px 0;} +.icon-zoom-in{background-position:-336px 0;} +.icon-zoom-out{background-position:-360px 0;} +.icon-off{background-position:-384px 0;} +.icon-signal{background-position:-408px 0;} +.icon-cog{background-position:-432px 0;} +.icon-trash{background-position:-456px 0;} +.icon-home{background-position:0 -24px;} +.icon-file{background-position:-24px -24px;} +.icon-time{background-position:-48px -24px;} +.icon-road{background-position:-72px -24px;} +.icon-download-alt{background-position:-96px -24px;} +.icon-download{background-position:-120px -24px;} +.icon-upload{background-position:-144px -24px;} +.icon-inbox{background-position:-168px -24px;} +.icon-play-circle{background-position:-192px -24px;} +.icon-repeat{background-position:-216px -24px;} +.icon-refresh{background-position:-240px -24px;} +.icon-list-alt{background-position:-264px -24px;} +.icon-lock{background-position:-287px -24px;} +.icon-flag{background-position:-312px -24px;} +.icon-headphones{background-position:-336px -24px;} +.icon-volume-off{background-position:-360px -24px;} +.icon-volume-down{background-position:-384px -24px;} +.icon-volume-up{background-position:-408px -24px;} +.icon-qrcode{background-position:-432px -24px;} +.icon-barcode{background-position:-456px -24px;} +.icon-tag{background-position:0 -48px;} +.icon-tags{background-position:-25px -48px;} +.icon-book{background-position:-48px -48px;} +.icon-bookmark{background-position:-72px -48px;} +.icon-print{background-position:-96px -48px;} +.icon-camera{background-position:-120px -48px;} +.icon-font{background-position:-144px -48px;} +.icon-bold{background-position:-167px -48px;} +.icon-italic{background-position:-192px -48px;} +.icon-text-height{background-position:-216px -48px;} +.icon-text-width{background-position:-240px -48px;} +.icon-align-left{background-position:-264px -48px;} +.icon-align-center{background-position:-288px -48px;} +.icon-align-right{background-position:-312px -48px;} +.icon-align-justify{background-position:-336px -48px;} +.icon-list{background-position:-360px -48px;} +.icon-indent-left{background-position:-384px -48px;} +.icon-indent-right{background-position:-408px -48px;} +.icon-facetime-video{background-position:-432px -48px;} +.icon-picture{background-position:-456px -48px;} +.icon-pencil{background-position:0 -72px;} +.icon-map-marker{background-position:-24px -72px;} +.icon-adjust{background-position:-48px -72px;} +.icon-tint{background-position:-72px -72px;} +.icon-edit{background-position:-96px -72px;} +.icon-share{background-position:-120px -72px;} +.icon-check{background-position:-144px -72px;} +.icon-move{background-position:-168px -72px;} +.icon-step-backward{background-position:-192px -72px;} +.icon-fast-backward{background-position:-216px -72px;} +.icon-backward{background-position:-240px -72px;} +.icon-play{background-position:-264px -72px;} +.icon-pause{background-position:-288px -72px;} +.icon-stop{background-position:-312px -72px;} +.icon-forward{background-position:-336px -72px;} +.icon-fast-forward{background-position:-360px -72px;} +.icon-step-forward{background-position:-384px -72px;} +.icon-eject{background-position:-408px -72px;} +.icon-chevron-left{background-position:-432px -72px;} +.icon-chevron-right{background-position:-456px -72px;} +.icon-plus-sign{background-position:0 -96px;} +.icon-minus-sign{background-position:-24px -96px;} +.icon-remove-sign{background-position:-48px -96px;} +.icon-ok-sign{background-position:-72px -96px;} +.icon-question-sign{background-position:-96px -96px;} +.icon-info-sign{background-position:-120px -96px;} +.icon-screenshot{background-position:-144px -96px;} +.icon-remove-circle{background-position:-168px -96px;} +.icon-ok-circle{background-position:-192px -96px;} +.icon-ban-circle{background-position:-216px -96px;} +.icon-arrow-left{background-position:-240px -96px;} +.icon-arrow-right{background-position:-264px -96px;} +.icon-arrow-up{background-position:-289px -96px;} +.icon-arrow-down{background-position:-312px -96px;} +.icon-share-alt{background-position:-336px -96px;} +.icon-resize-full{background-position:-360px -96px;} +.icon-resize-small{background-position:-384px -96px;} +.icon-plus{background-position:-408px -96px;} +.icon-minus{background-position:-433px -96px;} +.icon-asterisk{background-position:-456px -96px;} +.icon-exclamation-sign{background-position:0 -120px;} +.icon-gift{background-position:-24px -120px;} +.icon-leaf{background-position:-48px -120px;} +.icon-fire{background-position:-72px -120px;} +.icon-eye-open{background-position:-96px -120px;} +.icon-eye-close{background-position:-120px -120px;} +.icon-warning-sign{background-position:-144px -120px;} +.icon-plane{background-position:-168px -120px;} +.icon-calendar{background-position:-192px -120px;} +.icon-random{background-position:-216px -120px;width:16px;} +.icon-comment{background-position:-240px -120px;} +.icon-magnet{background-position:-264px -120px;} +.icon-chevron-up{background-position:-288px -120px;} +.icon-chevron-down{background-position:-313px -119px;} +.icon-retweet{background-position:-336px -120px;} +.icon-shopping-cart{background-position:-360px -120px;} +.icon-folder-close{background-position:-384px -120px;width:16px;} +.icon-folder-open{background-position:-408px -120px;width:16px;} +.icon-resize-vertical{background-position:-432px -119px;} +.icon-resize-horizontal{background-position:-456px -118px;} +.icon-hdd{background-position:0 -144px;} +.icon-bullhorn{background-position:-24px -144px;} +.icon-bell{background-position:-48px -144px;} +.icon-certificate{background-position:-72px -144px;} +.icon-thumbs-up{background-position:-96px -144px;} +.icon-thumbs-down{background-position:-120px -144px;} +.icon-hand-right{background-position:-144px -144px;} +.icon-hand-left{background-position:-168px -144px;} +.icon-hand-up{background-position:-192px -144px;} +.icon-hand-down{background-position:-216px -144px;} +.icon-circle-arrow-right{background-position:-240px -144px;} +.icon-circle-arrow-left{background-position:-264px -144px;} +.icon-circle-arrow-up{background-position:-288px -144px;} +.icon-circle-arrow-down{background-position:-312px -144px;} +.icon-globe{background-position:-336px -144px;} +.icon-wrench{background-position:-360px -144px;} +.icon-tasks{background-position:-384px -144px;} +.icon-filter{background-position:-408px -144px;} +.icon-briefcase{background-position:-432px -144px;} +.icon-fullscreen{background-position:-456px -144px;} +.btn-group{position:relative;display:inline-block;*display:inline;*zoom:1;font-size:0;vertical-align:middle;white-space:nowrap;*margin-left:.3em;}.btn-group:first-child{*margin-left:0;} +.btn-group+.btn-group{margin-left:5px;} +.btn-toolbar{font-size:0;margin-top:10px;margin-bottom:10px;}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group{margin-left:5px;} +.btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} +.btn-group>.btn+.btn{margin-left:-1px;} +.btn-group>.btn,.btn-group>.dropdown-menu,.btn-group>.popover{font-size:14px;} +.btn-group>.btn-mini{font-size:10.5px;} +.btn-group>.btn-small{font-size:11.9px;} +.btn-group>.btn-large{font-size:17.5px;} +.btn-group>.btn:first-child{margin-left:0;-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;} +.btn-group>.btn:last-child,.btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;} +.btn-group>.btn.large:first-child{margin-left:0;-webkit-border-top-left-radius:6px;-moz-border-radius-topleft:6px;border-top-left-radius:6px;-webkit-border-bottom-left-radius:6px;-moz-border-radius-bottomleft:6px;border-bottom-left-radius:6px;} +.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;-moz-border-radius-topright:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;-moz-border-radius-bottomright:6px;border-bottom-right-radius:6px;} +.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active{z-index:2;} +.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0;} +.btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);*padding-top:5px;*padding-bottom:5px;} +.btn-group>.btn-mini+.dropdown-toggle{padding-left:5px;padding-right:5px;*padding-top:2px;*padding-bottom:2px;} +.btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px;} +.btn-group>.btn-large+.dropdown-toggle{padding-left:12px;padding-right:12px;*padding-top:7px;*padding-bottom:7px;} +.btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);} +.btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6;} +.btn-group.open .btn-primary.dropdown-toggle{background-color:#0044cc;} +.btn-group.open .btn-warning.dropdown-toggle{background-color:#f89406;} +.btn-group.open .btn-danger.dropdown-toggle{background-color:#bd362f;} +.btn-group.open .btn-success.dropdown-toggle{background-color:#51a351;} +.btn-group.open .btn-info.dropdown-toggle{background-color:#2f96b4;} +.btn-group.open .btn-inverse.dropdown-toggle{background-color:#222222;} +.btn .caret{margin-top:8px;margin-left:0;} +.btn-large .caret{margin-top:6px;} +.btn-large .caret{border-left-width:5px;border-right-width:5px;border-top-width:5px;} +.btn-mini .caret,.btn-small .caret{margin-top:8px;} +.dropup .btn-large .caret{border-bottom-width:5px;} +.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;} +.btn-group-vertical{display:inline-block;*display:inline;*zoom:1;} +.btn-group-vertical>.btn{display:block;float:none;max-width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} +.btn-group-vertical>.btn+.btn{margin-left:0;margin-top:-1px;} +.btn-group-vertical>.btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0;} +.btn-group-vertical>.btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px;} +.btn-group-vertical>.btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0;} +.btn-group-vertical>.btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;} +.nav{margin-left:0;margin-bottom:20px;list-style:none;} +.nav>li>a{display:block;} +.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eeeeee;} +.nav>li>a>img{max-width:none;} +.nav>.pull-right{float:right;} +.nav-header{display:block;padding:3px 15px;font-size:11px;font-weight:bold;line-height:20px;color:#999999;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);text-transform:uppercase;} +.nav li+.nav-header{margin-top:9px;} +.nav-list{padding-left:15px;padding-right:15px;margin-bottom:0;} +.nav-list>li>a,.nav-list .nav-header{margin-left:-15px;margin-right:-15px;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);} +.nav-list>li>a{padding:3px 15px;} +.nav-list>.active>a,.nav-list>.active>a:hover,.nav-list>.active>a:focus{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.2);background-color:#0088cc;} +.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{margin-right:2px;} +.nav-list .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #ffffff;} +.nav-tabs,.nav-pills{*zoom:1;}.nav-tabs:before,.nav-pills:before,.nav-tabs:after,.nav-pills:after{display:table;content:"";line-height:0;} +.nav-tabs:after,.nav-pills:after{clear:both;} +.nav-tabs>li,.nav-pills>li{float:left;} +.nav-tabs>li>a,.nav-pills>li>a{padding-right:12px;padding-left:12px;margin-right:2px;line-height:14px;} +.nav-tabs{border-bottom:1px solid #ddd;} +.nav-tabs>li{margin-bottom:-1px;} +.nav-tabs>li>a{padding-top:8px;padding-bottom:8px;line-height:20px;border:1px solid transparent;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0;}.nav-tabs>li>a:hover,.nav-tabs>li>a:focus{border-color:#eeeeee #eeeeee #dddddd;} +.nav-tabs>.active>a,.nav-tabs>.active>a:hover,.nav-tabs>.active>a:focus{color:#555555;background-color:#ffffff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default;} +.nav-pills>li>a{padding-top:8px;padding-bottom:8px;margin-top:2px;margin-bottom:2px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;} +.nav-pills>.active>a,.nav-pills>.active>a:hover,.nav-pills>.active>a:focus{color:#ffffff;background-color:#0088cc;} +.nav-stacked>li{float:none;} +.nav-stacked>li>a{margin-right:0;} +.nav-tabs.nav-stacked{border-bottom:0;} +.nav-tabs.nav-stacked>li>a{border:1px solid #ddd;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} +.nav-tabs.nav-stacked>li:first-child>a{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;} +.nav-tabs.nav-stacked>li:last-child>a{-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;} +.nav-tabs.nav-stacked>li>a:hover,.nav-tabs.nav-stacked>li>a:focus{border-color:#ddd;z-index:2;} +.nav-pills.nav-stacked>li>a{margin-bottom:3px;} +.nav-pills.nav-stacked>li:last-child>a{margin-bottom:1px;} +.nav-tabs .dropdown-menu{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;} +.nav-pills .dropdown-menu{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;} +.nav .dropdown-toggle .caret{border-top-color:#0088cc;border-bottom-color:#0088cc;margin-top:6px;} +.nav .dropdown-toggle:hover .caret,.nav .dropdown-toggle:focus .caret{border-top-color:#005580;border-bottom-color:#005580;} +.nav-tabs .dropdown-toggle .caret{margin-top:8px;} +.nav .active .dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff;} +.nav-tabs .active .dropdown-toggle .caret{border-top-color:#555555;border-bottom-color:#555555;} +.nav>.dropdown.active>a:hover,.nav>.dropdown.active>a:focus{cursor:pointer;} +.nav-tabs .open .dropdown-toggle,.nav-pills .open .dropdown-toggle,.nav>li.dropdown.open.active>a:hover,.nav>li.dropdown.open.active>a:focus{color:#ffffff;background-color:#999999;border-color:#999999;} +.nav li.dropdown.open .caret,.nav li.dropdown.open.active .caret,.nav li.dropdown.open a:hover .caret,.nav li.dropdown.open a:focus .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;opacity:1;filter:alpha(opacity=100);} +.tabs-stacked .open>a:hover,.tabs-stacked .open>a:focus{border-color:#999999;} +.tabbable{*zoom:1;}.tabbable:before,.tabbable:after{display:table;content:"";line-height:0;} +.tabbable:after{clear:both;} +.tab-content{overflow:auto;} +.tabs-below>.nav-tabs,.tabs-right>.nav-tabs,.tabs-left>.nav-tabs{border-bottom:0;} +.tab-content>.tab-pane,.pill-content>.pill-pane{display:none;} +.tab-content>.active,.pill-content>.active{display:block;} +.tabs-below>.nav-tabs{border-top:1px solid #ddd;} +.tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0;} +.tabs-below>.nav-tabs>li>a{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px;}.tabs-below>.nav-tabs>li>a:hover,.tabs-below>.nav-tabs>li>a:focus{border-bottom-color:transparent;border-top-color:#ddd;} +.tabs-below>.nav-tabs>.active>a,.tabs-below>.nav-tabs>.active>a:hover,.tabs-below>.nav-tabs>.active>a:focus{border-color:transparent #ddd #ddd #ddd;} +.tabs-left>.nav-tabs>li,.tabs-right>.nav-tabs>li{float:none;} +.tabs-left>.nav-tabs>li>a,.tabs-right>.nav-tabs>li>a{min-width:74px;margin-right:0;margin-bottom:3px;} +.tabs-left>.nav-tabs{float:left;margin-right:19px;border-right:1px solid #ddd;} +.tabs-left>.nav-tabs>li>a{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px;} +.tabs-left>.nav-tabs>li>a:hover,.tabs-left>.nav-tabs>li>a:focus{border-color:#eeeeee #dddddd #eeeeee #eeeeee;} +.tabs-left>.nav-tabs .active>a,.tabs-left>.nav-tabs .active>a:hover,.tabs-left>.nav-tabs .active>a:focus{border-color:#ddd transparent #ddd #ddd;*border-right-color:#ffffff;} +.tabs-right>.nav-tabs{float:right;margin-left:19px;border-left:1px solid #ddd;} +.tabs-right>.nav-tabs>li>a{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;} +.tabs-right>.nav-tabs>li>a:hover,.tabs-right>.nav-tabs>li>a:focus{border-color:#eeeeee #eeeeee #eeeeee #dddddd;} +.tabs-right>.nav-tabs .active>a,.tabs-right>.nav-tabs .active>a:hover,.tabs-right>.nav-tabs .active>a:focus{border-color:#ddd #ddd #ddd transparent;*border-left-color:#ffffff;} +.nav>.disabled>a{color:#999999;} +.nav>.disabled>a:hover,.nav>.disabled>a:focus{text-decoration:none;background-color:transparent;cursor:default;} +.navbar-inner{min-height:40px;padding-left:20px;padding-right:20px;background-color:#fafafa;background-image:-moz-linear-gradient(top, #ffffff, #f2f2f2);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2));background-image:-webkit-linear-gradient(top, #ffffff, #f2f2f2);background-image:-o-linear-gradient(top, #ffffff, #f2f2f2);background-image:linear-gradient(to bottom, #ffffff, #f2f2f2);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff2f2f2', GradientType=0);border:1px solid #d4d4d4;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);-moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);*zoom:1;}.navbar-inner:before,.navbar-inner:after{display:table;content:"";line-height:0;} +.navbar-inner:after{clear:both;} +.navbar .container{width:auto;} +.nav-collapse.collapse{height:auto;overflow:visible;} +.navbar .brand{float:left;display:block;padding:10px 20px 10px;margin-left:-20px;font-size:20px;font-weight:200;color:#777777;text-shadow:0 1px 0 #ffffff;}.navbar .brand:hover,.navbar .brand:focus{text-decoration:none;} +.navbar-text{margin-bottom:0;line-height:40px;color:#777777;} +.navbar-link{color:#777777;}.navbar-link:hover,.navbar-link:focus{color:#333333;} +.navbar .divider-vertical{height:40px;margin:0 9px;border-left:1px solid #f2f2f2;border-right:1px solid #ffffff;} +.navbar .btn,.navbar .btn-group{margin-top:5px;} +.navbar .btn-group .btn,.navbar .input-prepend .btn,.navbar .input-append .btn,.navbar .input-prepend .btn-group,.navbar .input-append .btn-group{margin-top:0;} +.navbar-form{margin-bottom:0;*zoom:1;}.navbar-form:before,.navbar-form:after{display:table;content:"";line-height:0;} +.navbar-form:after{clear:both;} +.navbar-form input,.navbar-form select,.navbar-form .radio,.navbar-form .checkbox{margin-top:5px;} +.navbar-form input,.navbar-form select,.navbar-form .btn{display:inline-block;margin-bottom:0;} +.navbar-form input[type="image"],.navbar-form input[type="checkbox"],.navbar-form input[type="radio"]{margin-top:3px;} +.navbar-form .input-append,.navbar-form .input-prepend{margin-top:5px;white-space:nowrap;}.navbar-form .input-append input,.navbar-form .input-prepend input{margin-top:0;} +.navbar-search{position:relative;float:left;margin-top:5px;margin-bottom:0;}.navbar-search .search-query{margin-bottom:0;padding:4px 14px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;font-weight:normal;line-height:1;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;} +.navbar-static-top{position:static;margin-bottom:0;}.navbar-static-top .navbar-inner{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} +.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;margin-bottom:0;} +.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{border-width:0 0 1px;} +.navbar-fixed-bottom .navbar-inner{border-width:1px 0 0;} +.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding-left:0;padding-right:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} +.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px;} +.navbar-fixed-top{top:0;} +.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{-webkit-box-shadow:0 1px 10px rgba(0,0,0,.1);-moz-box-shadow:0 1px 10px rgba(0,0,0,.1);box-shadow:0 1px 10px rgba(0,0,0,.1);} +.navbar-fixed-bottom{bottom:0;}.navbar-fixed-bottom .navbar-inner{-webkit-box-shadow:0 -1px 10px rgba(0,0,0,.1);-moz-box-shadow:0 -1px 10px rgba(0,0,0,.1);box-shadow:0 -1px 10px rgba(0,0,0,.1);} +.navbar .nav{position:relative;left:0;display:block;float:left;margin:0 10px 0 0;} +.navbar .nav.pull-right{float:right;margin-right:0;} +.navbar .nav>li{float:left;} +.navbar .nav>li>a{float:none;padding:10px 15px 10px;color:#777777;text-decoration:none;text-shadow:0 1px 0 #ffffff;} +.navbar .nav .dropdown-toggle .caret{margin-top:8px;} +.navbar .nav>li>a:focus,.navbar .nav>li>a:hover{background-color:transparent;color:#333333;text-decoration:none;} +.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus{color:#555555;text-decoration:none;background-color:#e5e5e5;-webkit-box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);-moz-box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);} +.navbar .btn-navbar{display:none;float:right;padding:7px 10px;margin-left:5px;margin-right:5px;color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#ededed;background-image:-moz-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#e5e5e5));background-image:-webkit-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:-o-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:linear-gradient(to bottom, #f2f2f2, #e5e5e5);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2', endColorstr='#ffe5e5e5', GradientType=0);border-color:#e5e5e5 #e5e5e5 #bfbfbf;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#e5e5e5;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075);box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075);}.navbar .btn-navbar:hover,.navbar .btn-navbar:focus,.navbar .btn-navbar:active,.navbar .btn-navbar.active,.navbar .btn-navbar.disabled,.navbar .btn-navbar[disabled]{color:#ffffff;background-color:#e5e5e5;*background-color:#d9d9d9;} +.navbar .btn-navbar:active,.navbar .btn-navbar.active{background-color:#cccccc \9;} +.navbar .btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);-moz-box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);} +.btn-navbar .icon-bar+.icon-bar{margin-top:3px;} +.navbar .nav>li>.dropdown-menu:before{content:'';display:inline-block;border-left:7px solid transparent;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-bottom-color:rgba(0, 0, 0, 0.2);position:absolute;top:-7px;left:9px;} +.navbar .nav>li>.dropdown-menu:after{content:'';display:inline-block;border-left:6px solid transparent;border-right:6px solid transparent;border-bottom:6px solid #ffffff;position:absolute;top:-6px;left:10px;} +.navbar-fixed-bottom .nav>li>.dropdown-menu:before{border-top:7px solid #ccc;border-top-color:rgba(0, 0, 0, 0.2);border-bottom:0;bottom:-7px;top:auto;} +.navbar-fixed-bottom .nav>li>.dropdown-menu:after{border-top:6px solid #ffffff;border-bottom:0;bottom:-6px;top:auto;} +.navbar .nav li.dropdown>a:hover .caret,.navbar .nav li.dropdown>a:focus .caret{border-top-color:#333333;border-bottom-color:#333333;} +.navbar .nav li.dropdown.open>.dropdown-toggle,.navbar .nav li.dropdown.active>.dropdown-toggle,.navbar .nav li.dropdown.open.active>.dropdown-toggle{background-color:#e5e5e5;color:#555555;} +.navbar .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#777777;border-bottom-color:#777777;} +.navbar .nav li.dropdown.open>.dropdown-toggle .caret,.navbar .nav li.dropdown.active>.dropdown-toggle .caret,.navbar .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#555555;border-bottom-color:#555555;} +.navbar .pull-right>li>.dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right{left:auto;right:0;}.navbar .pull-right>li>.dropdown-menu:before,.navbar .nav>li>.dropdown-menu.pull-right:before{left:auto;right:12px;} +.navbar .pull-right>li>.dropdown-menu:after,.navbar .nav>li>.dropdown-menu.pull-right:after{left:auto;right:13px;} +.navbar .pull-right>li>.dropdown-menu .dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right .dropdown-menu{left:auto;right:100%;margin-left:0;margin-right:-1px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px;} +.navbar-inverse .navbar-inner{background-color:#1b1b1b;background-image:-moz-linear-gradient(top, #222222, #111111);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111));background-image:-webkit-linear-gradient(top, #222222, #111111);background-image:-o-linear-gradient(top, #222222, #111111);background-image:linear-gradient(to bottom, #222222, #111111);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0);border-color:#252525;} +.navbar-inverse .brand,.navbar-inverse .nav>li>a{color:#999999;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);}.navbar-inverse .brand:hover,.navbar-inverse .nav>li>a:hover,.navbar-inverse .brand:focus,.navbar-inverse .nav>li>a:focus{color:#ffffff;} +.navbar-inverse .brand{color:#999999;} +.navbar-inverse .navbar-text{color:#999999;} +.navbar-inverse .nav>li>a:focus,.navbar-inverse .nav>li>a:hover{background-color:transparent;color:#ffffff;} +.navbar-inverse .nav .active>a,.navbar-inverse .nav .active>a:hover,.navbar-inverse .nav .active>a:focus{color:#ffffff;background-color:#111111;} +.navbar-inverse .navbar-link{color:#999999;}.navbar-inverse .navbar-link:hover,.navbar-inverse .navbar-link:focus{color:#ffffff;} +.navbar-inverse .divider-vertical{border-left-color:#111111;border-right-color:#222222;} +.navbar-inverse .nav li.dropdown.open>.dropdown-toggle,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle{background-color:#111111;color:#ffffff;} +.navbar-inverse .nav li.dropdown>a:hover .caret,.navbar-inverse .nav li.dropdown>a:focus .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;} +.navbar-inverse .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#999999;border-bottom-color:#999999;} +.navbar-inverse .nav li.dropdown.open>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;} +.navbar-inverse .navbar-search .search-query{color:#ffffff;background-color:#515151;border-color:#111111;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15);box-shadow:inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15);-webkit-transition:none;-moz-transition:none;-o-transition:none;transition:none;}.navbar-inverse .navbar-search .search-query:-moz-placeholder{color:#cccccc;} +.navbar-inverse .navbar-search .search-query:-ms-input-placeholder{color:#cccccc;} +.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder{color:#cccccc;} +.navbar-inverse .navbar-search .search-query:focus,.navbar-inverse .navbar-search .search-query.focused{padding:5px 15px;color:#333333;text-shadow:0 1px 0 #ffffff;background-color:#ffffff;border:0;-webkit-box-shadow:0 0 3px rgba(0, 0, 0, 0.15);-moz-box-shadow:0 0 3px rgba(0, 0, 0, 0.15);box-shadow:0 0 3px rgba(0, 0, 0, 0.15);outline:0;} +.navbar-inverse .btn-navbar{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#0e0e0e;background-image:-moz-linear-gradient(top, #151515, #040404);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#151515), to(#040404));background-image:-webkit-linear-gradient(top, #151515, #040404);background-image:-o-linear-gradient(top, #151515, #040404);background-image:linear-gradient(to bottom, #151515, #040404);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515', endColorstr='#ff040404', GradientType=0);border-color:#040404 #040404 #000000;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#040404;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.navbar-inverse .btn-navbar:hover,.navbar-inverse .btn-navbar:focus,.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active,.navbar-inverse .btn-navbar.disabled,.navbar-inverse .btn-navbar[disabled]{color:#ffffff;background-color:#040404;*background-color:#000000;} +.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active{background-color:#000000 \9;} +.breadcrumb{padding:8px 15px;margin:0 0 20px;list-style:none;background-color:#f5f5f5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}.breadcrumb>li{display:inline-block;*display:inline;*zoom:1;text-shadow:0 1px 0 #ffffff;}.breadcrumb>li>.divider{padding:0 5px;color:#ccc;} +.breadcrumb>.active{color:#999999;} +.pagination{margin:20px 0;} +.pagination ul{display:inline-block;*display:inline;*zoom:1;margin-left:0;margin-bottom:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);} +.pagination ul>li{display:inline;} +.pagination ul>li>a,.pagination ul>li>span{float:left;padding:4px 12px;line-height:20px;text-decoration:none;background-color:#ffffff;border:1px solid #dddddd;border-left-width:0;} +.pagination ul>li>a:hover,.pagination ul>li>a:focus,.pagination ul>.active>a,.pagination ul>.active>span{background-color:#f5f5f5;} +.pagination ul>.active>a,.pagination ul>.active>span{color:#999999;cursor:default;} +.pagination ul>.disabled>span,.pagination ul>.disabled>a,.pagination ul>.disabled>a:hover,.pagination ul>.disabled>a:focus{color:#999999;background-color:transparent;cursor:default;} +.pagination ul>li:first-child>a,.pagination ul>li:first-child>span{border-left-width:1px;-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;} +.pagination ul>li:last-child>a,.pagination ul>li:last-child>span{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;} +.pagination-centered{text-align:center;} +.pagination-right{text-align:right;} +.pagination-large ul>li>a,.pagination-large ul>li>span{padding:11px 19px;font-size:17.5px;} +.pagination-large ul>li:first-child>a,.pagination-large ul>li:first-child>span{-webkit-border-top-left-radius:6px;-moz-border-radius-topleft:6px;border-top-left-radius:6px;-webkit-border-bottom-left-radius:6px;-moz-border-radius-bottomleft:6px;border-bottom-left-radius:6px;} +.pagination-large ul>li:last-child>a,.pagination-large ul>li:last-child>span{-webkit-border-top-right-radius:6px;-moz-border-radius-topright:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;-moz-border-radius-bottomright:6px;border-bottom-right-radius:6px;} +.pagination-mini ul>li:first-child>a,.pagination-small ul>li:first-child>a,.pagination-mini ul>li:first-child>span,.pagination-small ul>li:first-child>span{-webkit-border-top-left-radius:3px;-moz-border-radius-topleft:3px;border-top-left-radius:3px;-webkit-border-bottom-left-radius:3px;-moz-border-radius-bottomleft:3px;border-bottom-left-radius:3px;} +.pagination-mini ul>li:last-child>a,.pagination-small ul>li:last-child>a,.pagination-mini ul>li:last-child>span,.pagination-small ul>li:last-child>span{-webkit-border-top-right-radius:3px;-moz-border-radius-topright:3px;border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;-moz-border-radius-bottomright:3px;border-bottom-right-radius:3px;} +.pagination-small ul>li>a,.pagination-small ul>li>span{padding:2px 10px;font-size:11.9px;} +.pagination-mini ul>li>a,.pagination-mini ul>li>span{padding:0 6px;font-size:10.5px;} +.pager{margin:20px 0;list-style:none;text-align:center;*zoom:1;}.pager:before,.pager:after{display:table;content:"";line-height:0;} +.pager:after{clear:both;} +.pager li{display:inline;} +.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;} +.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5;} +.pager .next>a,.pager .next>span{float:right;} +.pager .previous>a,.pager .previous>span{float:left;} +.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999999;background-color:#fff;cursor:default;} +.thumbnails{margin-left:-20px;list-style:none;*zoom:1;}.thumbnails:before,.thumbnails:after{display:table;content:"";line-height:0;} +.thumbnails:after{clear:both;} +.row-fluid .thumbnails{margin-left:0;} +.thumbnails>li{float:left;margin-bottom:20px;margin-left:20px;} +.thumbnail{display:block;padding:4px;line-height:20px;border:1px solid #ddd;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);-moz-box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);-webkit-transition:all 0.2s ease-in-out;-moz-transition:all 0.2s ease-in-out;-o-transition:all 0.2s ease-in-out;transition:all 0.2s ease-in-out;} +a.thumbnail:hover,a.thumbnail:focus{border-color:#0088cc;-webkit-box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);-moz-box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);} +.thumbnail>img{display:block;max-width:100%;margin-left:auto;margin-right:auto;} +.thumbnail .caption{padding:9px;color:#555555;} +.alert{padding:8px 35px 8px 14px;margin-bottom:20px;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);background-color:#fcf8e3;border:1px solid #fbeed5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} +.alert,.alert h4{color:#c09853;} +.alert h4{margin:0;} +.alert .close{position:relative;top:-2px;right:-21px;line-height:20px;} +.alert-success{background-color:#dff0d8;border-color:#d6e9c6;color:#468847;} +.alert-success h4{color:#468847;} +.alert-danger,.alert-error{background-color:#f2dede;border-color:#eed3d7;color:#b94a48;} +.alert-danger h4,.alert-error h4{color:#b94a48;} +.alert-info{background-color:#d9edf7;border-color:#bce8f1;color:#3a87ad;} +.alert-info h4{color:#3a87ad;} +.alert-block{padding-top:14px;padding-bottom:14px;} +.alert-block>p,.alert-block>ul{margin-bottom:0;} +.alert-block p+p{margin-top:5px;} +@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-o-keyframes progress-bar-stripes{from{background-position:0 0;} to{background-position:40px 0;}}@keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}.progress{overflow:hidden;height:20px;margin-bottom:20px;background-color:#f7f7f7;background-image:-moz-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9));background-image:-webkit-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:-o-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:linear-gradient(to bottom, #f5f5f5, #f9f9f9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0);-webkit-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);-moz-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} +.progress .bar{width:0%;height:100%;color:#ffffff;float:left;font-size:12px;text-align:center;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#0e90d2;background-image:-moz-linear-gradient(top, #149bdf, #0480be);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be));background-image:-webkit-linear-gradient(top, #149bdf, #0480be);background-image:-o-linear-gradient(top, #149bdf, #0480be);background-image:linear-gradient(to bottom, #149bdf, #0480be);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0);-webkit-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);-moz-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition:width 0.6s ease;-moz-transition:width 0.6s ease;-o-transition:width 0.6s ease;transition:width 0.6s ease;} +.progress .bar+.bar{-webkit-box-shadow:inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15);-moz-box-shadow:inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15);} +.progress-striped .bar{background-color:#149bdf;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);-webkit-background-size:40px 40px;-moz-background-size:40px 40px;-o-background-size:40px 40px;background-size:40px 40px;} +.progress.active .bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite;} +.progress-danger .bar,.progress .bar-danger{background-color:#dd514c;background-image:-moz-linear-gradient(top, #ee5f5b, #c43c35);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35));background-image:-webkit-linear-gradient(top, #ee5f5b, #c43c35);background-image:-o-linear-gradient(top, #ee5f5b, #c43c35);background-image:linear-gradient(to bottom, #ee5f5b, #c43c35);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0);} +.progress-danger.progress-striped .bar,.progress-striped .bar-danger{background-color:#ee5f5b;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} +.progress-success .bar,.progress .bar-success{background-color:#5eb95e;background-image:-moz-linear-gradient(top, #62c462, #57a957);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957));background-image:-webkit-linear-gradient(top, #62c462, #57a957);background-image:-o-linear-gradient(top, #62c462, #57a957);background-image:linear-gradient(to bottom, #62c462, #57a957);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff57a957', GradientType=0);} +.progress-success.progress-striped .bar,.progress-striped .bar-success{background-color:#62c462;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} +.progress-info .bar,.progress .bar-info{background-color:#4bb1cf;background-image:-moz-linear-gradient(top, #5bc0de, #339bb9);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9));background-image:-webkit-linear-gradient(top, #5bc0de, #339bb9);background-image:-o-linear-gradient(top, #5bc0de, #339bb9);background-image:linear-gradient(to bottom, #5bc0de, #339bb9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff339bb9', GradientType=0);} +.progress-info.progress-striped .bar,.progress-striped .bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} +.progress-warning .bar,.progress .bar-warning{background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);} +.progress-warning.progress-striped .bar,.progress-striped .bar-warning{background-color:#fbb450;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} +.hero-unit{padding:60px;margin-bottom:30px;font-size:18px;font-weight:200;line-height:30px;color:inherit;background-color:#4eacc5;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;}.hero-unit h1{margin-bottom:0;font-size:60px;line-height:1;color:inherit;letter-spacing:-1px;} +.hero-unit li{line-height:30px;} +.media,.media-body{overflow:hidden;*overflow:visible;zoom:1;} +.media,.media .media{margin-top:15px;} +.media:first-child{margin-top:0;} +.media-object{display:block;} +.media-heading{margin:0 0 5px;} +.media>.pull-left{margin-right:10px;} +.media>.pull-right{margin-left:10px;} +.media-list{margin-left:0;list-style:none;} +.tooltip{position:absolute;z-index:1030;display:block;visibility:visible;font-size:11px;line-height:1.4;opacity:0;filter:alpha(opacity=0);}.tooltip.in{opacity:0.8;filter:alpha(opacity=80);} +.tooltip.top{margin-top:-3px;padding:5px 0;} +.tooltip.right{margin-left:3px;padding:0 5px;} +.tooltip.bottom{margin-top:3px;padding:5px 0;} +.tooltip.left{margin-left:-3px;padding:0 5px;} +.tooltip-inner{max-width:200px;padding:8px;color:#ffffff;text-align:center;text-decoration:none;background-color:#000000;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} +.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid;} +.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000000;} +.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000000;} +.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000000;} +.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000000;} +.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;background-color:#ffffff;-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-moz-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);white-space:normal;}.popover.top{margin-top:-10px;} +.popover.right{margin-left:10px;} +.popover.bottom{margin-top:10px;} +.popover.left{margin-left:-10px;} +.popover-title{margin:0;padding:8px 14px;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0;}.popover-title:empty{display:none;} +.popover-content{padding:9px 14px;} +.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid;} +.popover .arrow{border-width:11px;} +.popover .arrow:after{border-width:10px;content:"";} +.popover.top .arrow{left:50%;margin-left:-11px;border-bottom-width:0;border-top-color:#999;border-top-color:rgba(0, 0, 0, 0.25);bottom:-11px;}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-bottom-width:0;border-top-color:#ffffff;} +.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-left-width:0;border-right-color:#999;border-right-color:rgba(0, 0, 0, 0.25);}.popover.right .arrow:after{left:1px;bottom:-10px;border-left-width:0;border-right-color:#ffffff;} +.popover.bottom .arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0, 0, 0, 0.25);top:-11px;}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#ffffff;} +.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0, 0, 0, 0.25);}.popover.left .arrow:after{right:1px;border-right-width:0;border-left-color:#ffffff;bottom:-10px;} +.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000000;}.modal-backdrop.fade{opacity:0;} +.modal-backdrop,.modal-backdrop.fade.in{opacity:0.8;filter:alpha(opacity=80);} +.modal{position:fixed;top:10%;left:50%;z-index:1050;width:560px;margin-left:-280px;background-color:#ffffff;border:1px solid #999;border:1px solid rgba(0, 0, 0, 0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);-moz-box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box;outline:none;}.modal.fade{-webkit-transition:opacity .3s linear, top .3s ease-out;-moz-transition:opacity .3s linear, top .3s ease-out;-o-transition:opacity .3s linear, top .3s ease-out;transition:opacity .3s linear, top .3s ease-out;top:-25%;} +.modal.fade.in{top:10%;} +.modal-header{padding:9px 15px;border-bottom:1px solid #eee;}.modal-header .close{margin-top:2px;} +.modal-header h3{margin:0;line-height:30px;} +.modal-body{position:relative;overflow-y:auto;max-height:400px;padding:15px;} +.modal-form{margin-bottom:0;} +.modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;-webkit-box-shadow:inset 0 1px 0 #ffffff;-moz-box-shadow:inset 0 1px 0 #ffffff;box-shadow:inset 0 1px 0 #ffffff;*zoom:1;}.modal-footer:before,.modal-footer:after{display:table;content:"";line-height:0;} +.modal-footer:after{clear:both;} +.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0;} +.modal-footer .btn-group .btn+.btn{margin-left:-1px;} +.modal-footer .btn-block+.btn-block{margin-left:0;} +.dropup,.dropdown{position:relative;} +.dropdown-toggle{*margin-bottom:-3px;} +.dropdown-toggle:active,.open .dropdown-toggle{outline:0;} +.caret{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid #000000;border-right:4px solid transparent;border-left:4px solid transparent;content:"";} +.dropdown .caret{margin-top:8px;margin-left:2px;} +.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#ffffff;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);*border-right-width:2px;*border-bottom-width:2px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-moz-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box;}.dropdown-menu.pull-right{right:0;left:auto;} +.dropdown-menu .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #ffffff;} +.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:20px;color:#333333;white-space:nowrap;} +.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-submenu:hover>a,.dropdown-submenu:focus>a{text-decoration:none;color:#ffffff;background-color:#0081c2;background-image:-moz-linear-gradient(top, #0088cc, #0077b3);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3));background-image:-webkit-linear-gradient(top, #0088cc, #0077b3);background-image:-o-linear-gradient(top, #0088cc, #0077b3);background-image:linear-gradient(to bottom, #0088cc, #0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0);} +.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#ffffff;text-decoration:none;outline:0;background-color:#0081c2;background-image:-moz-linear-gradient(top, #0088cc, #0077b3);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3));background-image:-webkit-linear-gradient(top, #0088cc, #0077b3);background-image:-o-linear-gradient(top, #0088cc, #0077b3);background-image:linear-gradient(to bottom, #0088cc, #0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0);} +.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999999;} +.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);cursor:default;} +.open{*z-index:1000;}.open>.dropdown-menu{display:block;} +.dropdown-backdrop{position:fixed;left:0;right:0;bottom:0;top:0;z-index:990;} +.pull-right>.dropdown-menu{right:0;left:auto;} +.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000000;content:"";} +.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px;} +.dropdown-submenu{position:relative;} +.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px;} +.dropdown-submenu:hover>.dropdown-menu{display:block;} +.dropup .dropdown-submenu>.dropdown-menu{top:auto;bottom:0;margin-top:0;margin-bottom:-2px;-webkit-border-radius:5px 5px 5px 0;-moz-border-radius:5px 5px 5px 0;border-radius:5px 5px 5px 0;} +.dropdown-submenu>a:after{display:block;content:" ";float:right;width:0;height:0;border-color:transparent;border-style:solid;border-width:5px 0 5px 5px;border-left-color:#cccccc;margin-top:5px;margin-right:-10px;} +.dropdown-submenu:hover>a:after{border-left-color:#ffffff;} +.dropdown-submenu.pull-left{float:none;}.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px;} +.dropdown .dropdown-menu .nav-header{padding-left:20px;padding-right:20px;} +.typeahead{z-index:1051;margin-top:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} +.accordion{margin-bottom:20px;} +.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} +.accordion-heading{border-bottom:0;} +.accordion-heading .accordion-toggle{display:block;padding:8px 15px;} +.accordion-toggle{cursor:pointer;} +.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5;} +.carousel{position:relative;margin-bottom:20px;line-height:1;} +.carousel-inner{overflow:hidden;width:100%;position:relative;} +.carousel-inner>.item{display:none;position:relative;-webkit-transition:0.6s ease-in-out left;-moz-transition:0.6s ease-in-out left;-o-transition:0.6s ease-in-out left;transition:0.6s ease-in-out left;}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;line-height:1;} +.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block;} +.carousel-inner>.active{left:0;} +.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%;} +.carousel-inner>.next{left:100%;} +.carousel-inner>.prev{left:-100%;} +.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0;} +.carousel-inner>.active.left{left:-100%;} +.carousel-inner>.active.right{left:100%;} +.carousel-control{position:absolute;top:40%;left:15px;width:40px;height:40px;margin-top:-20px;font-size:60px;font-weight:100;line-height:30px;color:#ffffff;text-align:center;background:#222222;border:3px solid #ffffff;-webkit-border-radius:23px;-moz-border-radius:23px;border-radius:23px;opacity:0.5;filter:alpha(opacity=50);}.carousel-control.right{left:auto;right:15px;} +.carousel-control:hover,.carousel-control:focus{color:#ffffff;text-decoration:none;opacity:0.9;filter:alpha(opacity=90);} +.carousel-indicators{position:absolute;top:15px;right:15px;z-index:5;margin:0;list-style:none;}.carousel-indicators li{display:block;float:left;width:10px;height:10px;margin-left:5px;text-indent:-999px;background-color:#ccc;background-color:rgba(255, 255, 255, 0.25);border-radius:5px;} +.carousel-indicators .active{background-color:#fff;} +.carousel-caption{position:absolute;left:0;right:0;bottom:0;padding:15px;background:#333333;background:rgba(0, 0, 0, 0.75);} +.carousel-caption h4,.carousel-caption p{color:#ffffff;line-height:20px;} +.carousel-caption h4{margin:0 0 5px;} +.carousel-caption p{margin-bottom:0;} +.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);}.well blockquote{border-color:#ddd;border-color:rgba(0, 0, 0, 0.15);} +.well-large{padding:24px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;} +.well-small{padding:9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} +.close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000000;text-shadow:0 1px 0 #ffffff;opacity:0.2;filter:alpha(opacity=20);}.close:hover,.close:focus{color:#000000;text-decoration:none;cursor:pointer;opacity:0.4;filter:alpha(opacity=40);} +button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none;} +.pull-right{float:right;} +.pull-left{float:left;} +.hide{display:none;} +.show{display:block;} +.invisible{visibility:hidden;} +.affix{position:fixed;} +.fade{opacity:0;-webkit-transition:opacity 0.15s linear;-moz-transition:opacity 0.15s linear;-o-transition:opacity 0.15s linear;transition:opacity 0.15s linear;}.fade.in{opacity:1;} +.collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height 0.35s ease;-moz-transition:height 0.35s ease;-o-transition:height 0.35s ease;transition:height 0.35s ease;}.collapse.in{height:auto;} +@-ms-viewport{width:device-width;}.hidden{display:none;visibility:hidden;} +.visible-phone{display:none !important;} +.visible-tablet{display:none !important;} +.hidden-desktop{display:none !important;} +.visible-desktop{display:inherit !important;} +@media (min-width:768px) and (max-width:979px){.hidden-desktop{display:inherit !important;} .visible-desktop{display:none !important ;} .visible-tablet{display:inherit !important;} .hidden-tablet{display:none !important;}}@media (max-width:767px){.hidden-desktop{display:inherit !important;} .visible-desktop{display:none !important;} .visible-phone{display:inherit !important;} .hidden-phone{display:none !important;}}.visible-print{display:none !important;} +@media print{.visible-print{display:inherit !important;} .hidden-print{display:none !important;}}@media (max-width:767px){body{padding-left:20px;padding-right:20px;} .navbar-fixed-top,.navbar-fixed-bottom,.navbar-static-top{margin-left:-20px;margin-right:-20px;} .container-fluid{padding:0;} .dl-horizontal dt{float:none;clear:none;width:auto;text-align:left;} .dl-horizontal dd{margin-left:0;} .container{width:auto;} .row-fluid{width:100%;} .row,.thumbnails{margin-left:0;} .thumbnails>li{float:none;margin-left:0;} [class*="span"],.uneditable-input[class*="span"],.row-fluid [class*="span"]{float:none;display:block;width:100%;margin-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .span12,.row-fluid .span12{width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .row-fluid [class*="offset"]:first-child{margin-left:0;} .input-large,.input-xlarge,.input-xxlarge,input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .input-prepend input,.input-append input,.input-prepend input[class*="span"],.input-append input[class*="span"]{display:inline-block;width:auto;} .controls-row [class*="span"]+[class*="span"]{margin-left:0;} .modal{position:fixed;top:20px;left:20px;right:20px;width:auto;margin:0;}.modal.fade{top:-100px;} .modal.fade.in{top:20px;}}@media (max-width:480px){.nav-collapse{-webkit-transform:translate3d(0, 0, 0);} .page-header h1 small{display:block;line-height:20px;} input[type="checkbox"],input[type="radio"]{border:1px solid #ccc;} .form-horizontal .control-label{float:none;width:auto;padding-top:0;text-align:left;} .form-horizontal .controls{margin-left:0;} .form-horizontal .control-list{padding-top:0;} .form-horizontal .form-actions{padding-left:10px;padding-right:10px;} .media .pull-left,.media .pull-right{float:none;display:block;margin-bottom:10px;} .media-object{margin-right:0;margin-left:0;} .modal{top:10px;left:10px;right:10px;} .modal-header .close{padding:10px;margin:-10px;} .carousel-caption{position:static;}}@media (min-width:768px) and (max-width:979px){.row{margin-left:-20px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;} .row:after{clear:both;} [class*="span"]{float:left;min-height:1px;margin-left:20px;} .container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:724px;} .span12{width:724px;} .span11{width:662px;} .span10{width:600px;} .span9{width:538px;} .span8{width:476px;} .span7{width:414px;} .span6{width:352px;} .span5{width:290px;} .span4{width:228px;} .span3{width:166px;} .span2{width:104px;} .span1{width:42px;} .offset12{margin-left:764px;} .offset11{margin-left:702px;} .offset10{margin-left:640px;} .offset9{margin-left:578px;} .offset8{margin-left:516px;} .offset7{margin-left:454px;} .offset6{margin-left:392px;} .offset5{margin-left:330px;} .offset4{margin-left:268px;} .offset3{margin-left:206px;} .offset2{margin-left:144px;} .offset1{margin-left:82px;} .row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;} .row-fluid:after{clear:both;} .row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.7624309392265194%;*margin-left:2.709239449864817%;} .row-fluid [class*="span"]:first-child{margin-left:0;} .row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.7624309392265194%;} .row-fluid .span12{width:100%;*width:99.94680851063829%;} .row-fluid .span11{width:91.43646408839778%;*width:91.38327259903608%;} .row-fluid .span10{width:82.87292817679558%;*width:82.81973668743387%;} .row-fluid .span9{width:74.30939226519337%;*width:74.25620077583166%;} .row-fluid .span8{width:65.74585635359117%;*width:65.69266486422946%;} .row-fluid .span7{width:57.18232044198895%;*width:57.12912895262725%;} .row-fluid .span6{width:48.61878453038674%;*width:48.56559304102504%;} .row-fluid .span5{width:40.05524861878453%;*width:40.00205712942283%;} .row-fluid .span4{width:31.491712707182323%;*width:31.43852121782062%;} .row-fluid .span3{width:22.92817679558011%;*width:22.87498530621841%;} .row-fluid .span2{width:14.3646408839779%;*width:14.311449394616199%;} .row-fluid .span1{width:5.801104972375691%;*width:5.747913483013988%;} .row-fluid .offset12{margin-left:105.52486187845304%;*margin-left:105.41847889972962%;} .row-fluid .offset12:first-child{margin-left:102.76243093922652%;*margin-left:102.6560479605031%;} .row-fluid .offset11{margin-left:96.96132596685082%;*margin-left:96.8549429881274%;} .row-fluid .offset11:first-child{margin-left:94.1988950276243%;*margin-left:94.09251204890089%;} .row-fluid .offset10{margin-left:88.39779005524862%;*margin-left:88.2914070765252%;} .row-fluid .offset10:first-child{margin-left:85.6353591160221%;*margin-left:85.52897613729868%;} .row-fluid .offset9{margin-left:79.8342541436464%;*margin-left:79.72787116492299%;} .row-fluid .offset9:first-child{margin-left:77.07182320441989%;*margin-left:76.96544022569647%;} .row-fluid .offset8{margin-left:71.2707182320442%;*margin-left:71.16433525332079%;} .row-fluid .offset8:first-child{margin-left:68.50828729281768%;*margin-left:68.40190431409427%;} .row-fluid .offset7{margin-left:62.70718232044199%;*margin-left:62.600799341718584%;} .row-fluid .offset7:first-child{margin-left:59.94475138121547%;*margin-left:59.838368402492065%;} .row-fluid .offset6{margin-left:54.14364640883978%;*margin-left:54.037263430116376%;} .row-fluid .offset6:first-child{margin-left:51.38121546961326%;*margin-left:51.27483249088986%;} .row-fluid .offset5{margin-left:45.58011049723757%;*margin-left:45.47372751851417%;} .row-fluid .offset5:first-child{margin-left:42.81767955801105%;*margin-left:42.71129657928765%;} .row-fluid .offset4{margin-left:37.01657458563536%;*margin-left:36.91019160691196%;} .row-fluid .offset4:first-child{margin-left:34.25414364640884%;*margin-left:34.14776066768544%;} .row-fluid .offset3{margin-left:28.45303867403315%;*margin-left:28.346655695309746%;} .row-fluid .offset3:first-child{margin-left:25.69060773480663%;*margin-left:25.584224756083227%;} .row-fluid .offset2{margin-left:19.88950276243094%;*margin-left:19.783119783707537%;} .row-fluid .offset2:first-child{margin-left:17.12707182320442%;*margin-left:17.02068884448102%;} .row-fluid .offset1{margin-left:11.32596685082873%;*margin-left:11.219583872105325%;} .row-fluid .offset1:first-child{margin-left:8.56353591160221%;*margin-left:8.457152932878806%;} input,textarea,.uneditable-input{margin-left:0;} .controls-row [class*="span"]+[class*="span"]{margin-left:20px;} input.span12,textarea.span12,.uneditable-input.span12{width:710px;} input.span11,textarea.span11,.uneditable-input.span11{width:648px;} input.span10,textarea.span10,.uneditable-input.span10{width:586px;} input.span9,textarea.span9,.uneditable-input.span9{width:524px;} input.span8,textarea.span8,.uneditable-input.span8{width:462px;} input.span7,textarea.span7,.uneditable-input.span7{width:400px;} input.span6,textarea.span6,.uneditable-input.span6{width:338px;} input.span5,textarea.span5,.uneditable-input.span5{width:276px;} input.span4,textarea.span4,.uneditable-input.span4{width:214px;} input.span3,textarea.span3,.uneditable-input.span3{width:152px;} input.span2,textarea.span2,.uneditable-input.span2{width:90px;} input.span1,textarea.span1,.uneditable-input.span1{width:28px;}}@media (min-width:1200px){.row{margin-left:-30px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;} .row:after{clear:both;} [class*="span"]{float:left;min-height:1px;margin-left:30px;} .container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:1170px;} .span12{width:1170px;} .span11{width:1070px;} .span10{width:970px;} .span9{width:870px;} .span8{width:770px;} .span7{width:670px;} .span6{width:570px;} .span5{width:470px;} .span4{width:370px;} .span3{width:270px;} .span2{width:170px;} .span1{width:70px;} .offset12{margin-left:1230px;} .offset11{margin-left:1130px;} .offset10{margin-left:1030px;} .offset9{margin-left:930px;} .offset8{margin-left:830px;} .offset7{margin-left:730px;} .offset6{margin-left:630px;} .offset5{margin-left:530px;} .offset4{margin-left:430px;} .offset3{margin-left:330px;} .offset2{margin-left:230px;} .offset1{margin-left:130px;} .row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;} .row-fluid:after{clear:both;} .row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.564102564102564%;*margin-left:2.5109110747408616%;} .row-fluid [class*="span"]:first-child{margin-left:0;} .row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.564102564102564%;} .row-fluid .span12{width:100%;*width:99.94680851063829%;} .row-fluid .span11{width:91.45299145299145%;*width:91.39979996362975%;} .row-fluid .span10{width:82.90598290598291%;*width:82.8527914166212%;} .row-fluid .span9{width:74.35897435897436%;*width:74.30578286961266%;} .row-fluid .span8{width:65.81196581196582%;*width:65.75877432260411%;} .row-fluid .span7{width:57.26495726495726%;*width:57.21176577559556%;} .row-fluid .span6{width:48.717948717948715%;*width:48.664757228587014%;} .row-fluid .span5{width:40.17094017094017%;*width:40.11774868157847%;} .row-fluid .span4{width:31.623931623931625%;*width:31.570740134569924%;} .row-fluid .span3{width:23.076923076923077%;*width:23.023731587561375%;} .row-fluid .span2{width:14.52991452991453%;*width:14.476723040552828%;} .row-fluid .span1{width:5.982905982905983%;*width:5.929714493544281%;} .row-fluid .offset12{margin-left:105.12820512820512%;*margin-left:105.02182214948171%;} .row-fluid .offset12:first-child{margin-left:102.56410256410257%;*margin-left:102.45771958537915%;} .row-fluid .offset11{margin-left:96.58119658119658%;*margin-left:96.47481360247316%;} .row-fluid .offset11:first-child{margin-left:94.01709401709402%;*margin-left:93.91071103837061%;} .row-fluid .offset10{margin-left:88.03418803418803%;*margin-left:87.92780505546462%;} .row-fluid .offset10:first-child{margin-left:85.47008547008548%;*margin-left:85.36370249136206%;} .row-fluid .offset9{margin-left:79.48717948717949%;*margin-left:79.38079650845607%;} .row-fluid .offset9:first-child{margin-left:76.92307692307693%;*margin-left:76.81669394435352%;} .row-fluid .offset8{margin-left:70.94017094017094%;*margin-left:70.83378796144753%;} .row-fluid .offset8:first-child{margin-left:68.37606837606839%;*margin-left:68.26968539734497%;} .row-fluid .offset7{margin-left:62.393162393162385%;*margin-left:62.28677941443899%;} .row-fluid .offset7:first-child{margin-left:59.82905982905982%;*margin-left:59.72267685033642%;} .row-fluid .offset6{margin-left:53.84615384615384%;*margin-left:53.739770867430444%;} .row-fluid .offset6:first-child{margin-left:51.28205128205128%;*margin-left:51.175668303327875%;} .row-fluid .offset5{margin-left:45.299145299145295%;*margin-left:45.1927623204219%;} .row-fluid .offset5:first-child{margin-left:42.73504273504273%;*margin-left:42.62865975631933%;} .row-fluid .offset4{margin-left:36.75213675213675%;*margin-left:36.645753773413354%;} .row-fluid .offset4:first-child{margin-left:34.18803418803419%;*margin-left:34.081651209310785%;} .row-fluid .offset3{margin-left:28.205128205128204%;*margin-left:28.0987452264048%;} .row-fluid .offset3:first-child{margin-left:25.641025641025642%;*margin-left:25.53464266230224%;} .row-fluid .offset2{margin-left:19.65811965811966%;*margin-left:19.551736679396257%;} .row-fluid .offset2:first-child{margin-left:17.094017094017094%;*margin-left:16.98763411529369%;} .row-fluid .offset1{margin-left:11.11111111111111%;*margin-left:11.004728132387708%;} .row-fluid .offset1:first-child{margin-left:8.547008547008547%;*margin-left:8.440625568285142%;} input,textarea,.uneditable-input{margin-left:0;} .controls-row [class*="span"]+[class*="span"]{margin-left:30px;} input.span12,textarea.span12,.uneditable-input.span12{width:1156px;} input.span11,textarea.span11,.uneditable-input.span11{width:1056px;} input.span10,textarea.span10,.uneditable-input.span10{width:956px;} input.span9,textarea.span9,.uneditable-input.span9{width:856px;} input.span8,textarea.span8,.uneditable-input.span8{width:756px;} input.span7,textarea.span7,.uneditable-input.span7{width:656px;} input.span6,textarea.span6,.uneditable-input.span6{width:556px;} input.span5,textarea.span5,.uneditable-input.span5{width:456px;} input.span4,textarea.span4,.uneditable-input.span4{width:356px;} input.span3,textarea.span3,.uneditable-input.span3{width:256px;} input.span2,textarea.span2,.uneditable-input.span2{width:156px;} input.span1,textarea.span1,.uneditable-input.span1{width:56px;} .thumbnails{margin-left:-30px;} .thumbnails>li{margin-left:30px;} .row-fluid .thumbnails{margin-left:0;}}@media (max-width:979px){body{padding-top:0;} .navbar-fixed-top,.navbar-fixed-bottom{position:static;} .navbar-fixed-top{margin-bottom:20px;} .navbar-fixed-bottom{margin-top:20px;} .navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding:5px;} .navbar .container{width:auto;padding:0;} .navbar .brand{padding-left:10px;padding-right:10px;margin:0 0 0 -5px;} .nav-collapse{clear:both;} .nav-collapse .nav{float:none;margin:0 0 10px;} .nav-collapse .nav>li{float:none;} .nav-collapse .nav>li>a{margin-bottom:2px;} .nav-collapse .nav>.divider-vertical{display:none;} .nav-collapse .nav .nav-header{color:#777777;text-shadow:none;} .nav-collapse .nav>li>a,.nav-collapse .dropdown-menu a{padding:9px 15px;font-weight:bold;color:#777777;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} .nav-collapse .btn{padding:4px 10px 4px;font-weight:normal;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} .nav-collapse .dropdown-menu li+li a{margin-bottom:2px;} .nav-collapse .nav>li>a:hover,.nav-collapse .nav>li>a:focus,.nav-collapse .dropdown-menu a:hover,.nav-collapse .dropdown-menu a:focus{background-color:#f2f2f2;} .navbar-inverse .nav-collapse .nav>li>a,.navbar-inverse .nav-collapse .dropdown-menu a{color:#999999;} .navbar-inverse .nav-collapse .nav>li>a:hover,.navbar-inverse .nav-collapse .nav>li>a:focus,.navbar-inverse .nav-collapse .dropdown-menu a:hover,.navbar-inverse .nav-collapse .dropdown-menu a:focus{background-color:#111111;} .nav-collapse.in .btn-group{margin-top:5px;padding:0;} .nav-collapse .dropdown-menu{position:static;top:auto;left:auto;float:none;display:none;max-width:none;margin:0 15px;padding:0;background-color:transparent;border:none;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;} .nav-collapse .open>.dropdown-menu{display:block;} .nav-collapse .dropdown-menu:before,.nav-collapse .dropdown-menu:after{display:none;} .nav-collapse .dropdown-menu .divider{display:none;} .nav-collapse .nav>li>.dropdown-menu:before,.nav-collapse .nav>li>.dropdown-menu:after{display:none;} .nav-collapse .navbar-form,.nav-collapse .navbar-search{float:none;padding:10px 15px;margin:10px 0;border-top:1px solid #f2f2f2;border-bottom:1px solid #f2f2f2;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1);} .navbar-inverse .nav-collapse .navbar-form,.navbar-inverse .nav-collapse .navbar-search{border-top-color:#111111;border-bottom-color:#111111;} .navbar .nav-collapse .nav.pull-right{float:none;margin-left:0;} .nav-collapse,.nav-collapse.collapse{overflow:hidden;height:0;} .navbar .btn-navbar{display:block;} .navbar-static .navbar-inner{padding-left:10px;padding-right:10px;}}@media (min-width:980px){.nav-collapse.collapse{height:auto !important;overflow:visible !important;}} diff --git a/sklearn/externals/joblib/test/__init__.py b/doc/themes/scikit-learn/static/css/examples.css similarity index 100% rename from sklearn/externals/joblib/test/__init__.py rename to doc/themes/scikit-learn/static/css/examples.css diff --git a/doc/themes/scikit-learn/static/gallery.css b/doc/themes/scikit-learn/static/gallery.css new file mode 100644 index 0000000000000..27dce45618b4e --- /dev/null +++ b/doc/themes/scikit-learn/static/gallery.css @@ -0,0 +1,73 @@ +/******** For the gallery **************/ + +/* ------- Fix maximum size of thumbnails in example gallery -------------- */ +div.thumbnailContainer img { + max-width: 160px; + max-height: 160px; + /*display: block;*/ + margin: auto auto auto -8px; + display: inline; +} + +div.thumbnailContainer div.figure { + float: left; + margin: 10px 11px 7em 11px; + -webkit-border-radius: 10px; + -moz-border-radius: 10px; + border-radius: 10px; + border: 2px solid #FFF; + background-color: #FFF; + width: 150px; + height: 100px; + -webkit-background-size: 150px 100px; + -moz-background-size: 150px 100px; +} + +*[tooltip] { + position: relative; + float: left; +} + +*[tooltip]:hover:after{ + background: rgba(0,0,0,.8); + border-radius: 5px; + color: white; + content: attr(tooltip); + left: 95%; + padding: 5px 15px; + position: absolute; + z-index: 98; + width: 220px; + bottom: 52% +} + + +*[tooltip]:hover:before { + content: ""; + position: absolute; + z-index: 99; + border: solid; + border-color: #333 transparent; + border-width: 18px 0px 0px 20px; + left: 85%; + bottom: 58% +} + +div.thumbnailContainer { + box-shadow: none; + border: solid white 1px; + padding-top: 5px; +} + +div.thumbnailContainer:hover { + box-shadow: 0 0 15px rgba(142, 176, 202, 0.5); + border: solid #B4DDFC 1px; +} + +div.thumbnailContainer div p { + margin: 0 0 .1em 0; +} + +div.thumbnailContainer div a { + display: block; /* To have a better hover behavior */ +} diff --git a/doc/themes/scikit-learn/static/img/FNRS-logo.png b/doc/themes/scikit-learn/static/img/FNRS-logo.png new file mode 100644 index 0000000000000..925559035ca9c Binary files /dev/null and b/doc/themes/scikit-learn/static/img/FNRS-logo.png differ diff --git a/doc/themes/scikit-learn/static/img/forkme.png b/doc/themes/scikit-learn/static/img/forkme.png new file mode 100644 index 0000000000000..5cf7a6c2162ff Binary files /dev/null and b/doc/themes/scikit-learn/static/img/forkme.png differ diff --git a/doc/themes/scikit-learn/static/img/glyphicons-halflings-white.png b/doc/themes/scikit-learn/static/img/glyphicons-halflings-white.png new file mode 100644 index 0000000000000..3bf6484a29d8d Binary files /dev/null and b/doc/themes/scikit-learn/static/img/glyphicons-halflings-white.png differ diff --git a/doc/themes/scikit-learn/static/img/glyphicons-halflings.png b/doc/themes/scikit-learn/static/img/glyphicons-halflings.png new file mode 100644 index 0000000000000..8bc9e642b762a Binary files /dev/null and b/doc/themes/scikit-learn/static/img/glyphicons-halflings.png differ diff --git a/doc/themes/scikit-learn/static/img/google.png b/doc/themes/scikit-learn/static/img/google.png new file mode 100644 index 0000000000000..a4f0830735994 Binary files /dev/null and b/doc/themes/scikit-learn/static/img/google.png differ diff --git a/doc/images/inria-small.jpg b/doc/themes/scikit-learn/static/img/inria-small.jpg similarity index 100% rename from doc/images/inria-small.jpg rename to doc/themes/scikit-learn/static/img/inria-small.jpg diff --git a/doc/themes/scikit-learn/static/img/inria-small.png b/doc/themes/scikit-learn/static/img/inria-small.png new file mode 100644 index 0000000000000..a77ace28d4807 Binary files /dev/null and b/doc/themes/scikit-learn/static/img/inria-small.png differ diff --git a/doc/themes/scikit-learn/static/img/plot_classifier_comparison_1.png b/doc/themes/scikit-learn/static/img/plot_classifier_comparison_1.png new file mode 100644 index 0000000000000..387adf0b03f83 Binary files /dev/null and b/doc/themes/scikit-learn/static/img/plot_classifier_comparison_1.png differ diff --git a/doc/themes/scikit-learn/static/img/plot_manifold_sphere_1.png b/doc/themes/scikit-learn/static/img/plot_manifold_sphere_1.png new file mode 100644 index 0000000000000..17630fb0f9913 Binary files /dev/null and b/doc/themes/scikit-learn/static/img/plot_manifold_sphere_1.png differ diff --git a/doc/themes/scikit-learn/static/img/scikit-learn-logo-notext.png b/doc/themes/scikit-learn/static/img/scikit-learn-logo-notext.png new file mode 100644 index 0000000000000..ce1e1056c66a6 Binary files /dev/null and b/doc/themes/scikit-learn/static/img/scikit-learn-logo-notext.png differ diff --git a/doc/themes/scikit-learn/static/img/scikit-learn-logo-small.png b/doc/themes/scikit-learn/static/img/scikit-learn-logo-small.png new file mode 100644 index 0000000000000..5882603c25a00 Binary files /dev/null and b/doc/themes/scikit-learn/static/img/scikit-learn-logo-small.png differ diff --git a/doc/themes/scikit-learn/static/img/scikit-learn-logo.png b/doc/themes/scikit-learn/static/img/scikit-learn-logo.png new file mode 100644 index 0000000000000..2c75cc2a1386b Binary files /dev/null and b/doc/themes/scikit-learn/static/img/scikit-learn-logo.png differ diff --git a/doc/themes/scikit-learn/static/img/scikit-learn-logo.svg b/doc/themes/scikit-learn/static/img/scikit-learn-logo.svg new file mode 100644 index 0000000000000..47ee0c75d5661 --- /dev/null +++ b/doc/themes/scikit-learn/static/img/scikit-learn-logo.svg @@ -0,0 +1,1050 @@ + + + + + + + + + scikit-learn/doc/logos/scikit-learn-logo.svg at master · scikit-learn/scikit-learn + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +
+
+ + + + + +
+ + + + +
+ + +
+
+ + + + + +
+ + This repository + + +
+
+ +
+ + +
This repository
+
+ +
+ + +
All repositories
+
+ +
+
+
+ + + + + + + + +
+ +
+ + + + + + + + + + + + +
+
+ + + + + + + + +
+ +
+
+ + +
    + +
  • +
    + +
    + + + + + Unwatch + + + +
    +
    +
    + Notification status + +
    + +
    + +
    + +
    + +

    Not watching

    + You only receive notifications for discussions in which you participate or are @mentioned. + + + Watch + +
    +
    + +
    + +
    + +

    Watching

    + You receive notifications for all discussions in this repository. + + + Unwatch + +
    +
    + +
    + +
    + +

    Ignoring

    + You do not receive any notifications for discussions in this repository. + + + Stop ignoring + +
    +
    + +
    + +
    +
    +
    + +
    +
  • + +
  • + + + +
  • + + +
  • + + Fork + + +
  • + + +
+ +

+ public + + + /scikit-learn + + + Octocat-spinner-32 + + +

+
+
+ +
+ +
+ +
+ + + + +
+ + + + +
+

HTTPS clone URL

+ + + + +
+ + + +
+

SSH clone URL

+ + + + +
+ + + +
+

Subversion checkout URL

+ + + + +
+ + + +

You can clone with + HTTPS, + SSH, + Subversion, + and other methods. +

+ + + + + + Download ZIP + +
+
+ +
+ + + + + + + + +Show File Finder + +
+ + + +
+ + + branch: + master + + +
+ +
+
+ Switch branches/tags + +
+ +
+
+ +
+
+ +
+
+ +
+ +
+ + +
+ + 0.6.X +
+
+ + 0.7.X +
+
+ + 0.8.X +
+
+ + 0.9.X +
+
+ + 0.10.X +
+
+ + 0.11.X +
+
+ + 0.12.X +
+
+ + 0.13.X +
+
+ + debian +
+ +
+ + master +
+
+ +
+ +
+

Create branch:

+ from ‘master’ +
+ + + +
+ +
+ +
+
+ + +
+ + sprint01 +
+ + + + + + + + + + +
+ + debian/0.5-1 +
+
+ + debian/0.4-3 +
+
+ + debian/0.4-2 +
+
+ + debian/0.4-1 +
+
+ + debian/0.3-4 +
+
+ + debian/0.3-3 +
+
+ + debian/0.3-2 +
+
+ + debian/0.3-1 +
+ + +
+ + 0.13.1 +
+
+ + 0.13 +
+ +
+ + 0.12.1 +
+
+ + 0.12 +
+ +
+ + 0.11-beta +
+
+ + 0.11 +
+ +
+ + 0.10 +
+ +
+ + 0.9 +
+ +
+ + 0.8.1 +
+
+ + 0.8 +
+ +
+ + 0.7.1 +
+
+ + 0.7 +
+
+ + 0.6-rc +
+
+ + 0.6.0 +
+
+ + 0.5.rc3 +
+
+ + 0.5.rc2 +
+
+ + 0.5.rc +
+
+ + 0.5 +
+
+ + 0.4 +
+
+ + 0.3 +
+
+ + 0.2-beta +
+
+ + 0.2 +
+
+ + 0.1-beta +
+
+ + 0.1 +
+
+ +
Nothing to show
+
+ +
+
+
+ + +
+ + +
+ Fetching contributors… + +
+

Octocat-spinner-32-eaf2f5

+

Cannot retrieve contributors at this time

+
+
+ +
+
+
+
+ + file + 110 lines (107 sloc) + 6.944 kb +
+ + +
+
+ + + + + +
+ 1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 + + +
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Generator: Adobe Illustrator 14.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 43363) -->

<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   version="1.1"
   id="Layer_1"
   x="0px"
   y="0px"
   width="792px"
   height="612px"
   viewBox="0 0 792 612"
   enable-background="new 0 0 792 612"
   xml:space="preserve"
   inkscape:version="0.48.2 r9819"
   sodipodi:docname="scikit-learn-logo.svg"><metadata
   id="metadata35"><rdf:RDF><cc:Work
       rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
         rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs
   id="defs33" /><sodipodi:namedview
   pagecolor="#ffffff"
   bordercolor="#666666"
   borderopacity="1"
   objecttolerance="10"
   gridtolerance="10"
   guidetolerance="10"
   inkscape:pageopacity="0"
   inkscape:pageshadow="2"
   inkscape:window-width="1019"
   inkscape:window-height="958"
   id="namedview31"
   showgrid="false"
   inkscape:zoom="2.1814013"
   inkscape:cx="276.47817"
   inkscape:cy="330.56501"
   inkscape:window-x="246"
   inkscape:window-y="247"
   inkscape:window-maximized="0"
   inkscape:current-layer="Layer_1" />
<g
   id="g3">
<path
   fill="#F89939"
   d="M333.32,347.348c33.869-33.867,39.498-83.146,12.572-110.07c-26.922-26.921-76.199-21.293-110.066,12.572 c-33.867,33.866-24.07,98.568-12.57,110.07C232.549,369.213,299.455,381.213,333.32,347.348z"
   id="path5" />
<path
   fill="#3499CD"
   d="M194.35,298.411c-19.648-19.648-48.242-22.919-63.867-7.295c-15.621,15.622-12.355,44.22,7.297,63.865 c19.652,19.654,57.195,13.969,63.863,7.295C207.039,356.889,214.004,318.061,194.35,298.411z"
   id="path7" />
</g>
<g
   id="g9">
<g
   id="g11">
<path
   fill="#010101"
   d="M262.143,339.047c-3.471,3.195-6.516,5.553-9.133,7.068c-2.617,1.52-5.113,2.279-7.488,2.279 c-2.732,0-4.936-1.059-6.607-3.178c-1.674-2.121-2.508-4.965-2.508-8.543c0-5.361,1.162-11.797,3.486-19.301 c2.32-7.51,5.145-14.43,8.463-20.761l9.729-3.602c0.305-0.102,0.537-0.154,0.691-0.154c0.738,0,1.348,0.544,1.816,1.627 c0.473,1.088,0.711,2.55,0.711,4.388c0,5.209-1.199,10.252-3.602,15.129c-2.402,4.879-6.154,10.086-11.26,15.627 c-0.205,2.656-0.307,4.48-0.307,5.477c0,2.223,0.408,3.982,1.225,5.285c0.818,1.305,1.902,1.953,3.256,1.953 c1.381,0,2.848-0.494,4.406-1.49c1.555-0.998,3.93-3.064,7.121-6.207V339.047z M247.475,324.074 c3.242-3.605,5.875-7.648,7.891-12.121c2.016-4.475,3.023-8.324,3.023-11.549c0-0.94-0.139-1.704-0.418-2.278 c-0.281-0.575-0.641-0.864-1.074-0.864c-0.941,0-2.316,2.352-4.117,7.057C250.979,309.023,249.211,315.609,247.475,324.074z"
   id="path13" />
<path
   fill="#010101"
   d="M290.795,339.047c-3.242,3.195-6.152,5.553-8.732,7.068c-2.58,1.52-5.424,2.279-8.541,2.279 c-3.473,0-6.275-1.111-8.41-3.33c-2.131-2.225-3.195-5.146-3.195-8.773c0-5.412,1.875-10.309,5.633-14.688 c3.75-4.381,7.914-6.57,12.484-6.57c2.375,0,4.275,0.615,5.707,1.84c1.43,1.227,2.145,2.834,2.145,4.826 c0,5.287-5.617,9.574-16.852,12.869c1.02,4.977,3.688,7.469,8.004,7.469c1.686,0,3.293-0.453,4.824-1.357 c1.535-0.908,3.844-2.922,6.934-6.035V339.047z M270.725,331.963c6.535-1.84,9.805-5.234,9.805-10.188 c0-2.451-0.895-3.676-2.68-3.676c-1.686,0-3.293,1.281-4.824,3.85C271.49,324.514,270.725,327.85,270.725,331.963z"
   id="path15" />
<path
   fill="#010101"
   d="M331.701,339.047c-4.086,3.881-7.01,6.412-8.77,7.588c-1.762,1.174-3.447,1.76-5.057,1.76 c-4.035,0-5.936-3.561-5.707-10.686c-2.553,3.65-4.91,6.344-7.068,8.084c-2.156,1.736-4.383,2.602-6.684,2.602 c-2.244,0-4.152-1.051-5.725-3.158s-2.354-4.691-2.354-7.758c0-3.828,1.051-7.48,3.156-10.955 c2.109-3.473,4.809-6.279,8.102-8.424s6.207-3.219,8.732-3.219c3.193,0,5.428,1.469,6.705,4.404l7.828-4.326h2.148l-3.381,11.221 c-1.736,5.645-2.607,9.514-2.607,11.607c0,2.195,0.777,3.293,2.336,3.293c0.992,0,2.09-0.529,3.291-1.59s2.883-2.676,5.053-4.846 V339.047z M303.664,341.156c2.553,0,4.959-2.176,7.223-6.529c2.26-4.355,3.389-8.373,3.389-12.049c0-1.428-0.322-2.547-0.957-3.35 c-0.641-0.807-1.496-1.207-2.566-1.207c-2.555,0-4.977,2.17-7.258,6.512c-2.285,4.342-3.43,8.338-3.43,11.986 c0,1.381,0.34,2.498,1.016,3.354S302.615,341.156,303.664,341.156z"
   id="path17" />
<path
   fill="#010101"
   d="M360.314,339.047c-6.41,6.281-11.352,9.424-14.824,9.424c-1.559,0-2.875-0.658-3.945-1.969 c-1.07-1.316-1.609-2.945-1.609-4.887c0-3.6,1.93-8.424,5.785-14.477c-1.891,0.971-3.957,1.645-6.205,2.029 c-1.66,3.064-4.266,6.359-7.814,9.879h-0.879v-3.443c1.99-2.068,3.791-4.291,5.4-6.666c-2.199-0.971-3.295-2.414-3.295-4.326 c0-1.969,0.668-4.068,2.012-6.305c1.34-2.232,3.184-3.348,5.535-3.348c1.992,0,2.986,1.018,2.986,3.062 c0,1.609-0.574,3.906-1.725,6.895c4.238-0.461,7.941-3.701,11.109-9.729l3.484-0.154l-3.562,9.805 c-1.48,4.137-2.438,6.955-2.871,8.447s-0.652,2.816-0.652,3.963c0,1.074,0.25,1.932,0.746,2.566 c0.498,0.643,1.17,0.959,2.012,0.959c0.918,0,1.801-0.314,2.643-0.936c0.842-0.631,2.732-2.359,5.67-5.193V339.047z"
   id="path19" />
<path
   fill="#010101"
   d="M397.928,339.047c-5.898,6.234-10.957,9.348-15.168,9.348c-1.711,0-3.09-0.6-4.137-1.801 c-1.049-1.199-1.572-2.807-1.572-4.824c0-2.732,1.125-6.908,3.373-12.523c1.199-3.014,1.801-4.932,1.801-5.746 c0-0.818-0.322-1.227-0.957-1.227c-0.357,0-0.832,0.18-1.418,0.535c-0.539,0.357-1.164,0.859-1.879,1.496 c-0.637,0.586-1.354,1.301-2.145,2.141c-0.691,0.721-1.432,1.537-2.219,2.453l-2.148,2.492c-0.943,1.148-1.531,2.359-1.76,3.637 c-0.385,2.17-0.639,4.164-0.768,5.979c-0.078,1.35-0.115,3.174-0.115,5.477l-8.465,1.988c-0.279-3.447-0.422-6.014-0.422-7.697 c0-4.111,0.479-8.006,1.438-11.682c0.957-3.68,2.494-7.814,4.615-12.412l9.344-1.799c-1.965,5.287-3.254,9.447-3.867,12.484 c4.188-4.672,7.508-7.906,9.969-9.709c2.457-1.801,4.645-2.697,6.557-2.697c1.299,0,2.385,0.49,3.25,1.471 c0.869,0.982,1.301,2.215,1.301,3.689c0,2.449-1.098,6.484-3.291,12.104c-1.508,3.854-2.262,6.355-2.262,7.51 c0,1.537,0.627,2.305,1.881,2.305c1.867,0,4.891-2.465,9.064-7.393V339.047z"
   id="path21" />
</g>
</g>
<rect
   x="273.943"
   y="285.613"
   fill="none"
   width="225.242"
   height="83.948"
   id="rect23" />
<text
   transform="translate(273.9414,302.2061)"
   font-size="23.0795"
   id="text25"
   style="font-size:23.0795002px;fill:#ffffff;font-family:Helvetica">scikit</text>

<rect
   x="345.568"
   y="357.979"
   fill="none"
   width="327.432"
   height="42.963"
   id="rect27" />
<text
   transform="matrix(1 0 0 1 345.5684 375.5176)"
   fill="#010101"
   font-family="'Verdana'"
   font-size="23.0795"
   id="text29">machine learning in Python</text>

</svg>
+
+
+ +
+
+ + + + +
+ +
+ +
+
+ + +
+ +
+ +
+ + +
+
+
+ +
+
+
+
+
+
+ +
+ + + +
+ + + Something went wrong with that request. Please try again. +
+ + + + + diff --git a/doc/themes/scikit-learn/static/img/telecom.png b/doc/themes/scikit-learn/static/img/telecom.png new file mode 100644 index 0000000000000..818b4585fc528 Binary files /dev/null and b/doc/themes/scikit-learn/static/img/telecom.png differ diff --git a/doc/themes/scikit-learn/static/jquery.js b/doc/themes/scikit-learn/static/jquery.js index 82b98e1d76664..16ad06c5acaad 100644 --- a/doc/themes/scikit-learn/static/jquery.js +++ b/doc/themes/scikit-learn/static/jquery.js @@ -1,32 +1,4 @@ -/* - * jQuery 1.2.6 - New Wave Javascript - * - * Copyright (c) 2008 John Resig (jquery.com) - * Dual licensed under the MIT (MIT-LICENSE.txt) - * and GPL (GPL-LICENSE.txt) licenses. - * - * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $ - * $Rev: 5685 $ - */ -(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else -return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else -return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else -selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else -this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else -return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else -jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else -jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("",""]||!tags.indexOf("",""]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
"]||!tags.indexOf("",""]||(!tags.indexOf("",""]||!tags.indexOf("",""]||jQuery.browser.msie&&[1,"div
","
"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf(""&&tags.indexOf("=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else -ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&¬xml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&¬xml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&¬xml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else -while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return im[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else -for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("
").append(res.responseText.replace(//g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else -xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else -jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else -for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else -s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else -e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;ithis.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})(); \ No newline at end of file +/*! jQuery v1.7.2 jquery.com | jquery.org/license */ +(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"":"")+""),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;e=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="
"+""+"
",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="
t
",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="
",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( +a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&j.push({elem:this,matches:d.slice(e)});for(k=0;k0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
","
"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f +.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(;d1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]===""&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); \ No newline at end of file diff --git a/doc/themes/scikit-learn/static/jquery.maphilight.js b/doc/themes/scikit-learn/static/jquery.maphilight.js new file mode 100644 index 0000000000000..5e176d77f762c --- /dev/null +++ b/doc/themes/scikit-learn/static/jquery.maphilight.js @@ -0,0 +1,362 @@ +(function($) { + var has_VML, has_canvas, create_canvas_for, add_shape_to, clear_canvas, shape_from_area, + canvas_style, hex_to_decimal, css3color, is_image_loaded, options_from_area; + + has_canvas = !!document.createElement('canvas').getContext; + + // VML: more complex + has_VML = (function() { + var a = document.createElement('div'); + a.innerHTML = ''; + var b = a.firstChild; + b.style.behavior = "url(#default#VML)"; + return b ? typeof b.adj == "object": true; + })(); + + if(!(has_canvas || has_VML)) { + $.fn.maphilight = function() { return this; }; + return; + } + + if(has_canvas) { + hex_to_decimal = function(hex) { + return Math.max(0, Math.min(parseInt(hex, 16), 255)); + }; + css3color = function(color, opacity) { + return 'rgba('+hex_to_decimal(color.substr(0,2))+','+hex_to_decimal(color.substr(2,2))+','+hex_to_decimal(color.substr(4,2))+','+opacity+')'; + }; + create_canvas_for = function(img) { + var c = $('').get(0); + c.getContext("2d").clearRect(0, 0, c.width, c.height); + return c; + }; + var draw_shape = function(context, shape, coords, x_shift, y_shift) { + x_shift = x_shift || 0; + y_shift = y_shift || 0; + + context.beginPath(); + if(shape == 'rect') { + // x, y, width, height + context.rect(coords[0] + x_shift, coords[1] + y_shift, coords[2] - coords[0], coords[3] - coords[1]); + } else if(shape == 'poly') { + context.moveTo(coords[0] + x_shift, coords[1] + y_shift); + for(i=2; i < coords.length; i+=2) { + context.lineTo(coords[i] + x_shift, coords[i+1] + y_shift); + } + } else if(shape == 'circ') { + // x, y, radius, startAngle, endAngle, anticlockwise + context.arc(coords[0] + x_shift, coords[1] + y_shift, coords[2], 0, Math.PI * 2, false); + } + context.closePath(); + } + add_shape_to = function(canvas, shape, coords, options, name) { + var i, context = canvas.getContext('2d'); + + // Because I don't want to worry about setting things back to a base state + + // Shadow has to happen first, since it's on the bottom, and it does some clip / + // fill operations which would interfere with what comes next. + if(options.shadow) { + context.save(); + if(options.shadowPosition == "inside") { + // Cause the following stroke to only apply to the inside of the path + draw_shape(context, shape, coords); + context.clip(); + } + + // Redraw the shape shifted off the canvas massively so we can cast a shadow + // onto the canvas without having to worry about the stroke or fill (which + // cannot have 0 opacity or width, since they're what cast the shadow). + var x_shift = canvas.width * 100; + var y_shift = canvas.height * 100; + draw_shape(context, shape, coords, x_shift, y_shift); + + context.shadowOffsetX = options.shadowX - x_shift; + context.shadowOffsetY = options.shadowY - y_shift; + context.shadowBlur = options.shadowRadius; + context.shadowColor = css3color(options.shadowColor, options.shadowOpacity); + + // Now, work out where to cast the shadow from! It looks better if it's cast + // from a fill when it's an outside shadow or a stroke when it's an interior + // shadow. Allow the user to override this if they need to. + var shadowFrom = options.shadowFrom; + if (!shadowFrom) { + if (options.shadowPosition == 'outside') { + shadowFrom = 'fill'; + } else { + shadowFrom = 'stroke'; + } + } + if (shadowFrom == 'stroke') { + context.strokeStyle = "rgba(0,0,0,1)"; + context.stroke(); + } else if (shadowFrom == 'fill') { + context.fillStyle = "rgba(0,0,0,1)"; + context.fill(); + } + context.restore(); + + // and now we clean up + if(options.shadowPosition == "outside") { + context.save(); + // Clear out the center + draw_shape(context, shape, coords); + context.globalCompositeOperation = "destination-out"; + context.fillStyle = "rgba(0,0,0,1);"; + context.fill(); + context.restore(); + } + } + + context.save(); + + draw_shape(context, shape, coords); + + // fill has to come after shadow, otherwise the shadow will be drawn over the fill, + // which mostly looks weird when the shadow has a high opacity + if(options.fill) { + context.fillStyle = css3color(options.fillColor, options.fillOpacity); + context.fill(); + } + // Likewise, stroke has to come at the very end, or it'll wind up under bits of the + // shadow or the shadow-background if it's present. + if(options.stroke) { + context.strokeStyle = css3color(options.strokeColor, options.strokeOpacity); + context.lineWidth = options.strokeWidth; + context.stroke(); + } + + context.restore(); + + if(options.fade) { + $(canvas).css('opacity', 0).animate({opacity: 1}, 100); + } + }; + clear_canvas = function(canvas) { + canvas.getContext('2d').clearRect(0, 0, canvas.width,canvas.height); + }; + } else { // ie executes this code + create_canvas_for = function(img) { + return $('').get(0); + }; + add_shape_to = function(canvas, shape, coords, options, name) { + var fill, stroke, opacity, e; + fill = ''; + stroke = (options.stroke ? 'strokeweight="'+options.strokeWidth+'" stroked="t" strokecolor="#'+options.strokeColor+'"' : 'stroked="f"'); + opacity = ''; + if(shape == 'rect') { + e = $(''); + } else if(shape == 'poly') { + e = $(''); + } else if(shape == 'circ') { + e = $(''); + } + e.get(0).innerHTML = fill+opacity; + $(canvas).append(e); + }; + clear_canvas = function(canvas) { + $(canvas).find('[name=highlighted]').remove(); + }; + } + + shape_from_area = function(area) { + var i, coords = area.getAttribute('coords').split(','); + for (i=0; i < coords.length; i++) { coords[i] = parseFloat(coords[i]); } + return [area.getAttribute('shape').toLowerCase().substr(0,4), coords]; + }; + + options_from_area = function(area, options) { + var $area = $(area); + return $.extend({}, options, $.metadata ? $area.metadata() : false, $area.data('maphilight')); + }; + + is_image_loaded = function(img) { + if(!img.complete) { return false; } // IE + if(typeof img.naturalWidth != "undefined" && img.naturalWidth === 0) { return false; } // Others + return true; + }; + + canvas_style = { + position: 'absolute', + left: 0, + top: 0, + padding: 0, + border: 0 + }; + + var ie_hax_done = false; + $.fn.maphilight = function(opts) { + opts = $.extend({}, $.fn.maphilight.defaults, opts); + + if(has_VML && !ie_hax_done) { + document.namespaces.add("v", "urn:schemas-microsoft-com:vml"); + var style = document.createStyleSheet(); + var shapes = ['shape','rect', 'oval', 'circ', 'fill', 'stroke', 'imagedata', 'group','textbox']; + $.each(shapes, + function() { + style.addRule('v\\:' + this, "behavior: url(#default#VML); antialias:true"); + } + ); + ie_hax_done = true; + } + + return this.each(function() { + var img, wrap, options, map, canvas, canvas_always, mouseover, highlighted_shape, usemap; + img = $(this); + + if(!is_image_loaded(this)) { + // If the image isn't fully loaded, this won't work right. Try again later. + return window.setTimeout(function() { + img.maphilight(opts); + }, 200); + } + + options = $.extend({}, opts, $.metadata ? img.metadata() : false, img.data('maphilight')); + + // jQuery bug with Opera, results in full-url#usemap being returned from jQuery's attr. + // So use raw getAttribute instead. + usemap = img.get(0).getAttribute('usemap'); + + if (!usemap) { + return + } + + map = $('map[name="'+usemap.substr(1)+'"]'); + + if(!(img.is('img,input[type="image"]') && usemap && map.size() > 0)) { + return; + } + + if(img.hasClass('maphilighted')) { + // We're redrawing an old map, probably to pick up changes to the options. + // Just clear out all the old stuff. + var wrapper = img.parent(); + img.insertBefore(wrapper); + wrapper.remove(); + $(map).unbind('.maphilight').find('area[coords]').unbind('.maphilight'); + } + + wrap = $('
').css({ + display:'block', + background:'url("http://github.com/'+this.src+'")', + position:'absolute', + padding:0, + width:this.width, + height:this.height + }); + if(options.wrapClass) { + if(options.wrapClass === true) { + wrap.addClass($(this).attr('class')); + } else { + wrap.addClass(options.wrapClass); + } + } + img.before(wrap).css('opacity', 0).css(canvas_style).remove(); + if(has_VML) { img.css('filter', 'Alpha(opacity=0)'); } + wrap.append(img); + + canvas = create_canvas_for(this); + $(canvas).css(canvas_style); + canvas.height = this.height; + canvas.width = this.width; + + mouseover = function(e) { + var shape, area_options; + area_options = options_from_area(this, options); + if( + !area_options.neverOn + && + !area_options.alwaysOn + ) { + shape = shape_from_area(this); + add_shape_to(canvas, shape[0], shape[1], area_options, "highlighted"); + if(area_options.groupBy) { + var areas; + // two ways groupBy might work; attribute and selector + if(/^[a-zA-Z][\-a-zA-Z]+$/.test(area_options.groupBy)) { + areas = map.find('area['+area_options.groupBy+'="'+$(this).attr(area_options.groupBy)+'"]'); + } else { + areas = map.find(area_options.groupBy); + } + var first = this; + areas.each(function() { + if(this != first) { + var subarea_options = options_from_area(this, options); + if(!subarea_options.neverOn && !subarea_options.alwaysOn) { + var shape = shape_from_area(this); + add_shape_to(canvas, shape[0], shape[1], subarea_options, "highlighted"); + } + } + }); + } + // workaround for IE7, IE8 not rendering the final rectangle in a group + if(!has_canvas) { + $(canvas).append(''); + } + } + } + + $(map).bind('alwaysOn.maphilight', function() { + // Check for areas with alwaysOn set. These are added to a *second* canvas, + // which will get around flickering during fading. + if(canvas_always) { + clear_canvas(canvas_always); + } + if(!has_canvas) { + $(canvas).empty(); + } + $(map).find('area[coords]').each(function() { + var shape, area_options; + area_options = options_from_area(this, options); + if(area_options.alwaysOn) { + if(!canvas_always && has_canvas) { + canvas_always = create_canvas_for(img[0]); + $(canvas_always).css(canvas_style); + canvas_always.width = img[0].width; + canvas_always.height = img[0].height; + img.before(canvas_always); + } + area_options.fade = area_options.alwaysOnFade; // alwaysOn shouldn't fade in initially + shape = shape_from_area(this); + if (has_canvas) { + add_shape_to(canvas_always, shape[0], shape[1], area_options, ""); + } else { + add_shape_to(canvas, shape[0], shape[1], area_options, ""); + } + } + }); + }); + + $(map).trigger('alwaysOn.maphilight').find('area[coords]') + .bind('mouseover.maphilight', mouseover) + .bind('mouseout.maphilight', function(e) { clear_canvas(canvas); }); + + img.before(canvas); // if we put this after, the mouseover events wouldn't fire. + + img.addClass('maphilighted'); + }); + }; + $.fn.maphilight.defaults = { + fill: true, + fillColor: '000000', + fillOpacity: 0.2, + stroke: true, + strokeColor: 'ff0000', + strokeOpacity: 1, + strokeWidth: 1, + fade: true, + alwaysOn: false, + neverOn: false, + groupBy: false, + wrapClass: true, + // plenty of shadow: + shadow: false, + shadowX: 0, + shadowY: 0, + shadowRadius: 6, + shadowColor: '000000', + shadowOpacity: 0.8, + shadowPosition: 'outside', + shadowFrom: false + }; +})(jQuery); diff --git a/doc/themes/scikit-learn/static/jquery.maphilight.min.js b/doc/themes/scikit-learn/static/jquery.maphilight.min.js new file mode 100644 index 0000000000000..23f82ac9ec4ae --- /dev/null +++ b/doc/themes/scikit-learn/static/jquery.maphilight.min.js @@ -0,0 +1 @@ +(function(G){var B,J,C,K,N,M,I,E,H,A,L;J=!!document.createElement("canvas").getContext;B=(function(){var P=document.createElement("div");P.innerHTML='';var O=P.firstChild;O.style.behavior="url(#default#VML)";return O?typeof O.adj=="object":true})();if(!(J||B)){G.fn.maphilight=function(){return this};return }if(J){E=function(O){return Math.max(0,Math.min(parseInt(O,16),255))};H=function(O,P){return"rgba("+E(O.substr(0,2))+","+E(O.substr(2,2))+","+E(O.substr(4,2))+","+P+")"};C=function(O){var P=G('').get(0);P.getContext("2d").clearRect(0,0,P.width,P.height);return P};var F=function(Q,O,R,P,S){P=P||0;S=S||0;Q.beginPath();if(O=="rect"){Q.rect(R[0]+P,R[1]+S,R[2]-R[0],R[3]-R[1])}else{if(O=="poly"){Q.moveTo(R[0]+P,R[1]+S);for(i=2;i').get(0)};K=function(P,S,T,W,O){var U,V,Q,R;U='';V=(W.stroke?'strokeweight="'+W.strokeWidth+'" stroked="t" strokecolor="#'+W.strokeColor+'"':'stroked="f"');Q='';if(S=="rect"){R=G('')}else{if(S=="poly"){R=G('')}else{if(S=="circ"){R=G('')}}}R.get(0).innerHTML=U+Q;G(P).append(R)};N=function(O){G(O).find("[name=highlighted]").remove()}}M=function(P){var O,Q=P.getAttribute("coords").split(",");for(O=0;O0)){return }if(W.hasClass("maphilighted")){var R=W.parent();W.insertBefore(R);R.remove();G(S).unbind(".maphilight").find("area[coords]").unbind(".maphilight")}T=G("
").css({display:"block",background:'url("http://github.com/'+this.src+'")',position:"absolute",padding:0,width:"2100px",height:this.height});if(a.wrapClass){if(a.wrapClass===true){T.addClass(G(this).attr("class"))}else{T.addClass(a.wrapClass)}}W.before(T).css("opacity",0).css(I).remove();if(B){W.css("filter","Alpha(opacity=0)")}T.append(W);V=C(this);G(V).css(I);V.height=this.height;V.width=this.width;Z=function(f){var c,d;d=L(this,a);if(!d.neverOn&&!d.alwaysOn){c=M(this);K(V,c[0],c[1],d,"highlighted");if(d.groupBy){var b;if(/^[a-zA-Z][\-a-zA-Z]+$/.test(d.groupBy)){b=S.find("area["+d.groupBy+'="'+G(this).attr(d.groupBy)+'"]')}else{b=S.find(d.groupBy)}var g=this;b.each(function(){if(this!=g){var h=L(this,a);if(!h.neverOn&&!h.alwaysOn){var e=M(this);K(V,e[0],e[1],h,"highlighted")}}})}if(!J){G(V).append("")}}};G(S).bind("alwaysOn.maphilight",function(){if(X){N(X)}if(!J){G(V).empty()}G(S).find("area[coords]").each(function(){var b,c;c=L(this,a);if(c.alwaysOn){if(!X&&J){X=C(W[0]);G(X).css(I);X.width=W[0].width;X.height=W[0].height;W.before(X)}c.fade=c.alwaysOnFade;b=M(this);if(J){K(X,b[0],b[1],c,"")}else{K(V,b[0],b[1],c,"")}}})});G(S).trigger("alwaysOn.maphilight").find("area[coords]").bind("mouseover.maphilight",Z).bind("mouseout.maphilight",function(b){N(V)});W.before(V);W.addClass("maphilighted")})};G.fn.maphilight.defaults={fill:true,fillColor:"000000",fillOpacity:0.2,stroke:true,strokeColor:"ff0000",strokeOpacity:1,strokeWidth:1,fade:true,alwaysOn:false,neverOn:false,groupBy:false,wrapClass:true,shadow:false,shadowX:0,shadowY:0,shadowRadius:6,shadowColor:"000000",shadowOpacity:0.8,shadowPosition:"outside",shadowFrom:false}})(jQuery); \ No newline at end of file diff --git a/doc/themes/scikit-learn/static/js/bootstrap.js b/doc/themes/scikit-learn/static/js/bootstrap.js new file mode 100644 index 0000000000000..643e71cdf0878 --- /dev/null +++ b/doc/themes/scikit-learn/static/js/bootstrap.js @@ -0,0 +1,2280 @@ +/* =================================================== + * bootstrap-transition.js v2.3.2 + * http://twitter.github.com/bootstrap/javascript.html#transitions + * =================================================== + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ========================================================== */ + + +!function ($) { + + "use strict"; // jshint ;_; + + + /* CSS TRANSITION SUPPORT (http://www.modernizr.com/) + * ======================================================= */ + + $(function () { + + $.support.transition = (function () { + + var transitionEnd = (function () { + + var el = document.createElement('bootstrap') + , transEndEventNames = { + 'WebkitTransition' : 'webkitTransitionEnd' + , 'MozTransition' : 'transitionend' + , 'OTransition' : 'oTransitionEnd otransitionend' + , 'transition' : 'transitionend' + } + , name + + for (name in transEndEventNames){ + if (el.style[name] !== undefined) { + return transEndEventNames[name] + } + } + + }()) + + return transitionEnd && { + end: transitionEnd + } + + })() + + }) + +}(window.jQuery);/* ========================================================== + * bootstrap-alert.js v2.3.2 + * http://twitter.github.com/bootstrap/javascript.html#alerts + * ========================================================== + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ========================================================== */ + + +!function ($) { + + "use strict"; // jshint ;_; + + + /* ALERT CLASS DEFINITION + * ====================== */ + + var dismiss = '[data-dismiss="alert"]' + , Alert = function (el) { + $(el).on('click', dismiss, this.close) + } + + Alert.prototype.close = function (e) { + var $this = $(this) + , selector = $this.attr('data-target') + , $parent + + if (!selector) { + selector = $this.attr('href') + selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 + } + + $parent = $(selector) + + e && e.preventDefault() + + $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) + + $parent.trigger(e = $.Event('close')) + + if (e.isDefaultPrevented()) return + + $parent.removeClass('in') + + function removeElement() { + $parent + .trigger('closed') + .remove() + } + + $.support.transition && $parent.hasClass('fade') ? + $parent.on($.support.transition.end, removeElement) : + removeElement() + } + + + /* ALERT PLUGIN DEFINITION + * ======================= */ + + var old = $.fn.alert + + $.fn.alert = function (option) { + return this.each(function () { + var $this = $(this) + , data = $this.data('alert') + if (!data) $this.data('alert', (data = new Alert(this))) + if (typeof option == 'string') data[option].call($this) + }) + } + + $.fn.alert.Constructor = Alert + + + /* ALERT NO CONFLICT + * ================= */ + + $.fn.alert.noConflict = function () { + $.fn.alert = old + return this + } + + + /* ALERT DATA-API + * ============== */ + + $(document).on('click.alert.data-api', dismiss, Alert.prototype.close) + +}(window.jQuery);/* ============================================================ + * bootstrap-button.js v2.3.2 + * http://twitter.github.com/bootstrap/javascript.html#buttons + * ============================================================ + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================ */ + + +!function ($) { + + "use strict"; // jshint ;_; + + + /* BUTTON PUBLIC CLASS DEFINITION + * ============================== */ + + var Button = function (element, options) { + this.$element = $(element) + this.options = $.extend({}, $.fn.button.defaults, options) + } + + Button.prototype.setState = function (state) { + var d = 'disabled' + , $el = this.$element + , data = $el.data() + , val = $el.is('input') ? 'val' : 'html' + + state = state + 'Text' + data.resetText || $el.data('resetText', $el[val]()) + + $el[val](data[state] || this.options[state]) + + // push to event loop to allow forms to submit + setTimeout(function () { + state == 'loadingText' ? + $el.addClass(d).attr(d, d) : + $el.removeClass(d).removeAttr(d) + }, 0) + } + + Button.prototype.toggle = function () { + var $parent = this.$element.closest('[data-toggle="buttons-radio"]') + + $parent && $parent + .find('.active') + .removeClass('active') + + this.$element.toggleClass('active') + } + + + /* BUTTON PLUGIN DEFINITION + * ======================== */ + + var old = $.fn.button + + $.fn.button = function (option) { + return this.each(function () { + var $this = $(this) + , data = $this.data('button') + , options = typeof option == 'object' && option + if (!data) $this.data('button', (data = new Button(this, options))) + if (option == 'toggle') data.toggle() + else if (option) data.setState(option) + }) + } + + $.fn.button.defaults = { + loadingText: 'loading...' + } + + $.fn.button.Constructor = Button + + + /* BUTTON NO CONFLICT + * ================== */ + + $.fn.button.noConflict = function () { + $.fn.button = old + return this + } + + + /* BUTTON DATA-API + * =============== */ + + $(document).on('click.button.data-api', '[data-toggle^=button]', function (e) { + var $btn = $(e.target) + if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') + $btn.button('toggle') + }) + +}(window.jQuery);/* ========================================================== + * bootstrap-carousel.js v2.3.2 + * http://twitter.github.com/bootstrap/javascript.html#carousel + * ========================================================== + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ========================================================== */ + + +!function ($) { + + "use strict"; // jshint ;_; + + + /* CAROUSEL CLASS DEFINITION + * ========================= */ + + var Carousel = function (element, options) { + this.$element = $(element) + this.$indicators = this.$element.find('.carousel-indicators') + this.options = options + this.options.pause == 'hover' && this.$element + .on('mouseenter', $.proxy(this.pause, this)) + .on('mouseleave', $.proxy(this.cycle, this)) + } + + Carousel.prototype = { + + cycle: function (e) { + if (!e) this.paused = false + if (this.interval) clearInterval(this.interval); + this.options.interval + && !this.paused + && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) + return this + } + + , getActiveIndex: function () { + this.$active = this.$element.find('.item.active') + this.$items = this.$active.parent().children() + return this.$items.index(this.$active) + } + + , to: function (pos) { + var activeIndex = this.getActiveIndex() + , that = this + + if (pos > (this.$items.length - 1) || pos < 0) return + + if (this.sliding) { + return this.$element.one('slid', function () { + that.to(pos) + }) + } + + if (activeIndex == pos) { + return this.pause().cycle() + } + + return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) + } + + , pause: function (e) { + if (!e) this.paused = true + if (this.$element.find('.next, .prev').length && $.support.transition.end) { + this.$element.trigger($.support.transition.end) + this.cycle(true) + } + clearInterval(this.interval) + this.interval = null + return this + } + + , next: function () { + if (this.sliding) return + return this.slide('next') + } + + , prev: function () { + if (this.sliding) return + return this.slide('prev') + } + + , slide: function (type, next) { + var $active = this.$element.find('.item.active') + , $next = next || $active[type]() + , isCycling = this.interval + , direction = type == 'next' ? 'left' : 'right' + , fallback = type == 'next' ? 'first' : 'last' + , that = this + , e + + this.sliding = true + + isCycling && this.pause() + + $next = $next.length ? $next : this.$element.find('.item')[fallback]() + + e = $.Event('slide', { + relatedTarget: $next[0] + , direction: direction + }) + + if ($next.hasClass('active')) return + + if (this.$indicators.length) { + this.$indicators.find('.active').removeClass('active') + this.$element.one('slid', function () { + var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) + $nextIndicator && $nextIndicator.addClass('active') + }) + } + + if ($.support.transition && this.$element.hasClass('slide')) { + this.$element.trigger(e) + if (e.isDefaultPrevented()) return + $next.addClass(type) + $next[0].offsetWidth // force reflow + $active.addClass(direction) + $next.addClass(direction) + this.$element.one($.support.transition.end, function () { + $next.removeClass([type, direction].join(' ')).addClass('active') + $active.removeClass(['active', direction].join(' ')) + that.sliding = false + setTimeout(function () { that.$element.trigger('slid') }, 0) + }) + } else { + this.$element.trigger(e) + if (e.isDefaultPrevented()) return + $active.removeClass('active') + $next.addClass('active') + this.sliding = false + this.$element.trigger('slid') + } + + isCycling && this.cycle() + + return this + } + + } + + + /* CAROUSEL PLUGIN DEFINITION + * ========================== */ + + var old = $.fn.carousel + + $.fn.carousel = function (option) { + return this.each(function () { + var $this = $(this) + , data = $this.data('carousel') + , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option) + , action = typeof option == 'string' ? option : options.slide + if (!data) $this.data('carousel', (data = new Carousel(this, options))) + if (typeof option == 'number') data.to(option) + else if (action) data[action]() + else if (options.interval) data.pause().cycle() + }) + } + + $.fn.carousel.defaults = { + interval: 5000 + , pause: 'hover' + } + + $.fn.carousel.Constructor = Carousel + + + /* CAROUSEL NO CONFLICT + * ==================== */ + + $.fn.carousel.noConflict = function () { + $.fn.carousel = old + return this + } + + /* CAROUSEL DATA-API + * ================= */ + + $(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { + var $this = $(this), href + , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 + , options = $.extend({}, $target.data(), $this.data()) + , slideIndex + + $target.carousel(options) + + if (slideIndex = $this.attr('data-slide-to')) { + $target.data('carousel').pause().to(slideIndex).cycle() + } + + e.preventDefault() + }) + +}(window.jQuery);/* ============================================================= + * bootstrap-collapse.js v2.3.2 + * http://twitter.github.com/bootstrap/javascript.html#collapse + * ============================================================= + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================ */ + + +!function ($) { + + "use strict"; // jshint ;_; + + + /* COLLAPSE PUBLIC CLASS DEFINITION + * ================================ */ + + var Collapse = function (element, options) { + this.$element = $(element) + this.options = $.extend({}, $.fn.collapse.defaults, options) + + if (this.options.parent) { + this.$parent = $(this.options.parent) + } + + this.options.toggle && this.toggle() + } + + Collapse.prototype = { + + constructor: Collapse + + , dimension: function () { + var hasWidth = this.$element.hasClass('width') + return hasWidth ? 'width' : 'height' + } + + , show: function () { + var dimension + , scroll + , actives + , hasData + + if (this.transitioning || this.$element.hasClass('in')) return + + dimension = this.dimension() + scroll = $.camelCase(['scroll', dimension].join('-')) + actives = this.$parent && this.$parent.find('> .accordion-group > .in') + + if (actives && actives.length) { + hasData = actives.data('collapse') + if (hasData && hasData.transitioning) return + actives.collapse('hide') + hasData || actives.data('collapse', null) + } + + this.$element[dimension](0) + this.transition('addClass', $.Event('show'), 'shown') + $.support.transition && this.$element[dimension](this.$element[0][scroll]) + } + + , hide: function () { + var dimension + if (this.transitioning || !this.$element.hasClass('in')) return + dimension = this.dimension() + this.reset(this.$element[dimension]()) + this.transition('removeClass', $.Event('hide'), 'hidden') + this.$element[dimension](0) + } + + , reset: function (size) { + var dimension = this.dimension() + + this.$element + .removeClass('collapse') + [dimension](size || 'auto') + [0].offsetWidth + + this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') + + return this + } + + , transition: function (method, startEvent, completeEvent) { + var that = this + , complete = function () { + if (startEvent.type == 'show') that.reset() + that.transitioning = 0 + that.$element.trigger(completeEvent) + } + + this.$element.trigger(startEvent) + + if (startEvent.isDefaultPrevented()) return + + this.transitioning = 1 + + this.$element[method]('in') + + $.support.transition && this.$element.hasClass('collapse') ? + this.$element.one($.support.transition.end, complete) : + complete() + } + + , toggle: function () { + this[this.$element.hasClass('in') ? 'hide' : 'show']() + } + + } + + + /* COLLAPSE PLUGIN DEFINITION + * ========================== */ + + var old = $.fn.collapse + + $.fn.collapse = function (option) { + return this.each(function () { + var $this = $(this) + , data = $this.data('collapse') + , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option) + if (!data) $this.data('collapse', (data = new Collapse(this, options))) + if (typeof option == 'string') data[option]() + }) + } + + $.fn.collapse.defaults = { + toggle: true + } + + $.fn.collapse.Constructor = Collapse + + + /* COLLAPSE NO CONFLICT + * ==================== */ + + $.fn.collapse.noConflict = function () { + $.fn.collapse = old + return this + } + + + /* COLLAPSE DATA-API + * ================= */ + + $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) { + var $this = $(this), href + , target = $this.attr('data-target') + || e.preventDefault() + || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 + , option = $(target).data('collapse') ? 'toggle' : $this.data() + $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed') + $(target).collapse(option) + }) + +}(window.jQuery);/* ============================================================ + * bootstrap-dropdown.js v2.3.2 + * http://twitter.github.com/bootstrap/javascript.html#dropdowns + * ============================================================ + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================ */ + + +!function ($) { + + "use strict"; // jshint ;_; + + + /* DROPDOWN CLASS DEFINITION + * ========================= */ + + var toggle = '[data-toggle=dropdown]' + , Dropdown = function (element) { + var $el = $(element).on('click.dropdown.data-api', this.toggle) + $('html').on('click.dropdown.data-api', function () { + $el.parent().removeClass('open') + }) + } + + Dropdown.prototype = { + + constructor: Dropdown + + , toggle: function (e) { + var $this = $(this) + , $parent + , isActive + + if ($this.is('.disabled, :disabled')) return + + $parent = getParent($this) + + isActive = $parent.hasClass('open') + + clearMenus() + + if (!isActive) { + if ('ontouchstart' in document.documentElement) { + // if mobile we we use a backdrop because click events don't delegate + $('
or
. + + Call withAttribute with a series of attribute names and values. Specify the list + of filter attributes names and values as: + - keyword arguments, as in (class="Customer",align="right"), or + - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") ) + For attribute names with a namespace prefix, you must use the second form. Attribute + names are matched insensitive to upper/lower case. + + To verify that the attribute exists, but without specifying a value, pass + withAttribute.ANY_VALUE as the value. + """ + if args: + attrs = args[:] + else: + attrs = attrDict.items() + attrs = [(k,v) for k,v in attrs] + def pa(s,l,tokens): + for attrName,attrValue in attrs: + if attrName not in tokens: + raise ParseException(s,l,"no matching attribute " + attrName) + if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue: + raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" % + (attrName, tokens[attrName], attrValue)) + return pa +withAttribute.ANY_VALUE = object() + +opAssoc = _Constants() +opAssoc.LEFT = object() +opAssoc.RIGHT = object() + +def operatorPrecedence( baseExpr, opList ): + """Helper method for constructing grammars of expressions made up of + operators working in a precedence hierarchy. Operators may be unary or + binary, left- or right-associative. Parse actions can also be attached + to operator expressions. + + Parameters: + - baseExpr - expression representing the most basic element for the nested + - opList - list of tuples, one for each operator precedence level in the + expression grammar; each tuple is of the form + (opExpr, numTerms, rightLeftAssoc, parseAction), where: + - opExpr is the pyparsing expression for the operator; + may also be a string, which will be converted to a Literal + - numTerms is the number of terms for this operator (must + be 1 or 2) + - rightLeftAssoc is the indicator whether the operator is + right or left associative, using the pyparsing-defined + constants opAssoc.RIGHT and opAssoc.LEFT. + - parseAction is the parse action to be associated with + expressions matching this operator expression (the + parse action tuple member may be omitted) + """ + ret = Forward() + lastExpr = baseExpr | ( Suppress('(') + ret + Suppress(')') ) + for i,operDef in enumerate(opList): + opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4] + thisExpr = Forward()#.setName("expr%d" % i) + if rightLeftAssoc == opAssoc.LEFT: + if arity == 1: + matchExpr = Group( FollowedBy(lastExpr + opExpr) + lastExpr + OneOrMore( opExpr ) ) + elif arity == 2: + matchExpr = Group( FollowedBy(lastExpr + opExpr + lastExpr) + lastExpr + OneOrMore( opExpr + lastExpr ) ) + else: + raise ValueError, "operator must be unary (1) or binary (2)" + elif rightLeftAssoc == opAssoc.RIGHT: + if arity == 1: + # try to avoid LR with this extra test + if not isinstance(opExpr, Optional): + opExpr = Optional(opExpr) + matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr ) + elif arity == 2: + matchExpr = Group( FollowedBy(lastExpr + opExpr + thisExpr) + lastExpr + OneOrMore( opExpr + thisExpr ) ) + else: + raise ValueError, "operator must be unary (1) or binary (2)" + else: + raise ValueError, "operator must indicate right or left associativity" + if pa: + matchExpr.setParseAction( pa ) + thisExpr << ( matchExpr | lastExpr ) + lastExpr = thisExpr + ret << lastExpr + return ret + +dblQuotedString = Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*"').setName("string enclosed in double quotes") +sglQuotedString = Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*'").setName("string enclosed in single quotes") +quotedString = Regex(r'''(?:"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*")|(?:'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*')''').setName("quotedString using single or double quotes") +unicodeString = Combine(_L('u') + quotedString.copy()) + +def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString): + """Helper method for defining nested lists enclosed in opening and closing + delimiters ("(" and ")" are the default). + + Parameters: + - opener - opening character for a nested list (default="("); can also be a pyparsing expression + - closer - closing character for a nested list (default=")"); can also be a pyparsing expression + - content - expression for items within the nested lists (default=None) + - ignoreExpr - expression for ignoring opening and closing delimiters (default=quotedString) + + If an expression is not provided for the content argument, the nested + expression will capture all whitespace-delimited content between delimiters + as a list of separate values. + + Use the ignoreExpr argument to define expressions that may contain + opening or closing characters that should not be treated as opening + or closing characters for nesting, such as quotedString or a comment + expression. Specify multiple expressions using an Or or MatchFirst. + The default is quotedString, but if no expressions are to be ignored, + then pass None for this argument. + """ + if opener == closer: + raise ValueError("opening and closing strings cannot be the same") + if content is None: + if isinstance(opener,__BASE_STRING__) and isinstance(closer,__BASE_STRING__): + content = (empty+CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS).setParseAction(lambda t:t[0].strip())) + else: + raise ValueError("opening and closing arguments must be strings if no content expression is given") + ret = Forward() + if ignoreExpr is not None: + ret << Group( Suppress(opener) + ZeroOrMore( ignoreExpr | ret | content ) + Suppress(closer) ) + else: + ret << Group( Suppress(opener) + ZeroOrMore( ret | content ) + Suppress(closer) ) + return ret + +alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]") +punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]") + +anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_:")) +commonHTMLEntity = Combine(_L("&") + oneOf("gt lt amp nbsp quot").setResultsName("entity") +";") +_htmlEntityMap = dict(zip("gt lt amp nbsp quot".split(),"><& '")) +replaceHTMLEntity = lambda t : t.entity in _htmlEntityMap and _htmlEntityMap[t.entity] or None + +# it's easy to get these comment structures wrong - they're very common, so may as well make them available +cStyleComment = Regex(r"/\*(?:[^*]*\*+)+?/").setName("C style comment") + +htmlComment = Regex(r"") +restOfLine = Regex(r".*").leaveWhitespace() +dblSlashComment = Regex(r"\/\/(\\\n|.)*").setName("// comment") +cppStyleComment = Regex(r"/(?:\*(?:[^*]*\*+)+?/|/[^\n]*(?:\n[^\n]*)*?(?:(?",) + try: + tokens = simpleSQL.parseString( teststring ) + tokenlist = tokens.asList() + print (tokenlist) + print ("tokens = ", tokens) + print ("tokens.columns =", tokens.columns) + print ("tokens.tables =", tokens.tables) + print (tokens.asXML("SQL",True)) + except ParseException,err: + print (err.line) + print (" "*(err.column-1) + "^") + print (err) + print() + + selectToken = CaselessLiteral( "select" ) + fromToken = CaselessLiteral( "from" ) + + ident = Word( alphas, alphanums + "_$" ) + columnName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens ) + columnNameList = Group( delimitedList( columnName ) )#.setName("columns") + tableName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens ) + tableNameList = Group( delimitedList( tableName ) )#.setName("tables") + simpleSQL = ( selectToken + \ + ( '*' | columnNameList ).setResultsName( "columns" ) + \ + fromToken + \ + tableNameList.setResultsName( "tables" ) ) + + test( "SELECT * from XYZZY, ABC" ) + test( "select * from SYS.XYZZY" ) + test( "Select A from Sys.dual" ) + test( "Select AA,BB,CC from Sys.dual" ) + test( "Select A, B, C from Sys.dual" ) + test( "Select A, B, C from Sys.dual" ) + test( "Xelect A, B, C from Sys.dual" ) + test( "Select A, B, C frox Sys.dual" ) + test( "Select" ) + test( "Select ^^^ frox Sys.dual" ) + test( "Select A, B, C from Sys.dual, Table2 " ) diff --git a/doc/tutorial/machine_learning_map/svg2imagemap.py b/doc/tutorial/machine_learning_map/svg2imagemap.py new file mode 100644 index 0000000000000..c2e592d5232fb --- /dev/null +++ b/doc/tutorial/machine_learning_map/svg2imagemap.py @@ -0,0 +1,90 @@ +#!/usr/local/bin/python + +""" +This script converts a subset of SVG into an HTML imagemap + +Note *subset*. It only handles elements, for which it only pays +attention to the M and L commands. Futher, it only notices the "translate" +transform. + +It was written to generate the examples in the documentation for maphilight, +and thus is very squarely aimed at handling several SVG maps from wikipedia. +It *assumes* that all the s it will need are inside a . Any +outside of a will be ignored. + +It takes several possible arguments, in the form: +$ svn2imagemap.py FILENAME [x y [group1 group2 ... groupN]] + +FILENAME must be the name of an SVG file. All other arguments are optional. + +x and y, if present, are the dimensions of the image you'll be creating from +the SVG. If not present, it assumes the values of the width and height +attributes in the SVG file. + +group1 through groupN are group ids. If only want particular groups used, +enter their ids here and all others will be ignored. +""" + +import os +import re +import sys +import xml.dom.minidom + +import parse_path + +if len(sys.argv) == 1: + sys.exit("svn2imagemap.py FILENAME [x y [group1 group2 ... groupN]]") +if not os.path.exists(sys.argv[1]): + sys.exit("Input file does not exist") +x, y, groups = None, None, None +if len(sys.argv) >= 3: + x = float(sys.argv[2]) + y = float(sys.argv[3]) + if len(sys.argv) > 3: + groups = sys.argv[4:] + +svg_file = xml.dom.minidom.parse(sys.argv[1]) +svg = svg_file.getElementsByTagName('svg')[0] + +raw_width = float(svg.getAttribute('width')) +raw_height = float(svg.getAttribute('height')) +width_ratio = x and (x / raw_width) or 1 +height_ratio = y and (y / raw_height) or 1 + +if groups: + elements = [g for g in svg.getElementsByTagName('g') if (g.hasAttribute('id') and g.getAttribute('id') in groups)] + elements.extend([p for p in svg.getElementsByTagName('path') if (p.hasAttribute('id') and p.getAttribute('id') in groups)]) +else: + elements = svg.getElementsByTagName('g') + +parsed_groups = {} +for e in elements: + paths = [] + if e.nodeName == 'g': + for path in e.getElementsByTagName('path'): + points = parse_path.get_points(path.getAttribute('d')) + for pointset in points: + paths.append([path.getAttribute('id'), pointset]) + else: + points = parse_path.get_points(e.getAttribute('d')) + for pointset in points: + paths.append([e.getAttribute('id'), pointset]) + if e.hasAttribute('transform'): + print e.getAttribute('id'), e.getAttribute('transform') + for transform in re.findall(r'(\w+)\((-?\d+.?\d*),(-?\d+.?\d*)\)', e.getAttribute('transform')): + if transform[0] == 'translate': + x_shift = float(transform[1]) + y_shift = float(transform[2]) + for path in paths: + path[1] = [(p[0] + x_shift, p[1] + y_shift) for p in path[1]] + + parsed_groups[e.getAttribute('id')] = paths + +out = [] +for g in parsed_groups: + for path in parsed_groups[g]: + out.append('' % + (path[0], ', '.join([("%d,%d" % (p[0]*width_ratio, p[1]*height_ratio)) for p in path[1]]))) + +outfile = open(sys.argv[1].replace('.svg', '.html'), 'w') +outfile.write('\n'.join(out)) diff --git a/doc/tutorial/statistical_inference/finding_help.rst b/doc/tutorial/statistical_inference/finding_help.rst index afa37882ac75a..96e1ebd790723 100644 --- a/doc/tutorial/statistical_inference/finding_help.rst +++ b/doc/tutorial/statistical_inference/finding_help.rst @@ -10,7 +10,7 @@ clarification in the docstring or the online documentation, please feel free to ask on the `Mailing List `_ -Q&A communities with Machine Learning practictioners +Q&A communities with Machine Learning practitioners ---------------------------------------------------- :Metaoptimize/QA: @@ -36,3 +36,7 @@ Q&A communities with Machine Learning practictioners .. _`good freely available textbooks on machine learning`: http://metaoptimize.com/qa/questions/186/good-freely-available-textbooks-on-machine-learning .. _`What are some good resources for learning about machine learning`: http://www.quora.com/What-are-some-good-resources-for-learning-about-machine-learning + +-- _'An excellent free online course for Machine Learning taught by Professor Andrew Ng of Stanford': https://www.coursera.org/course/ml + +-- _'Another excellent free online course that takes a more general approach to Artificial Intelligence':http://www.udacity.com/overview/Course/cs271/CourseRev/1 diff --git a/doc/tutorial/statistical_inference/index.rst b/doc/tutorial/statistical_inference/index.rst index 74d84dfdfe53b..19cfa01302325 100644 --- a/doc/tutorial/statistical_inference/index.rst +++ b/doc/tutorial/statistical_inference/index.rst @@ -13,31 +13,19 @@ A tutorial on statistical-learning for scientific data processing linking different observations, to classifying observations, or learning the structure in an unlabeled dataset. - This tutorial will explore `statistical learning`, that is the use of + This tutorial will explore *statistical learning*, the use of machine learning techniques with the goal of `statistical inference `_: drawing conclusions on the data at hand. - ``sklearn`` is a Python module integrating classic machine + Scikit-learn is a Python module integrating classic machine learning algorithms in the tightly-knit world of scientific Python - packages (`numpy `_, `scipy + packages (`NumPy `_, `SciPy `_, `matplotlib `_). .. include:: ../../includes/big_toc_css.rst -.. warning:: - - In scikit-learn release 0.9, the import path has changed from - `scikits.learn` to `sklearn`. To import with cross-version - compatibility, use:: - - try: - from sklearn import something - except ImportError: - from scikits.learn import something - - .. toctree:: :maxdepth: 2 @@ -47,4 +35,3 @@ A tutorial on statistical-learning for scientific data processing unsupervised_learning putting_together finding_help - diff --git a/doc/tutorial/statistical_inference/model_selection.rst b/doc/tutorial/statistical_inference/model_selection.rst index 4d6dca8dad953..a77ca00459eb8 100644 --- a/doc/tutorial/statistical_inference/model_selection.rst +++ b/doc/tutorial/statistical_inference/model_selection.rst @@ -7,7 +7,7 @@ Model selection: choosing estimators and their parameters Score, and cross-validated scores ================================== -As we have seen, every estimator exposes a `score` method that can judge +As we have seen, every estimator exposes a ``score`` method that can judge the quality of the fit (or the prediction) on new data. **Bigger is better**. @@ -38,7 +38,7 @@ data in *folds* that we use for training and testing:: ... y_test = y_train.pop(k) ... y_train = np.concatenate(y_train) ... scores.append(svc.fit(X_train, y_train).score(X_test, y_test)) - >>> print scores + >>> print(scores) [0.93489148580968284, 0.95659432387312182, 0.93989983305509184] .. currentmodule:: sklearn.cross_validation @@ -53,25 +53,25 @@ Cross-validation generators The code above to split data in train and test sets is tedious to write. -The `sklearn` exposes cross-validation generators to generate list +Scikit-learn exposes cross-validation generators to generate list of indices for this purpose:: >>> from sklearn import cross_validation - >>> k_fold = cross_validation.KFold(n=6, k=3, indices=True) + >>> k_fold = cross_validation.KFold(n=6, n_folds=3) >>> for train_indices, test_indices in k_fold: - ... print 'Train: %s | test: %s' % (train_indices, test_indices) + ... print('Train: %s | test: %s' % (train_indices, test_indices)) Train: [2 3 4 5] | test: [0 1] Train: [0 1 4 5] | test: [2 3] Train: [0 1 2 3] | test: [4 5] The cross-validation can then be implemented easily:: - >>> kfold = cross_validation.KFold(len(X_digits), k=3) + >>> kfold = cross_validation.KFold(len(X_digits), n_folds=3) >>> [svc.fit(X_digits[train], y_digits[train]).score(X_digits[test], y_digits[test]) ... for train, test in kfold] [0.93489148580968284, 0.95659432387312182, 0.93989983305509184] -To compute the `score` method of an estimator, the sklearn exposes +To compute the ``score`` method of an estimator, the sklearn exposes a helper function:: >>> cross_validation.cross_val_score(svc, X_digits, y_digits, cv=kfold, n_jobs=-1) @@ -97,9 +97,9 @@ of the computer. * - - Split it K folds, train on K-1, test on left-out + - Split it K folds, train on K-1 and then test on left-out - - Make sure that all classes are even accross the folds + - It preserves the class ratios / label distribution within each fold. - Leave one observation out @@ -107,22 +107,22 @@ of the computer. .. currentmodule:: sklearn.svm -.. image:: ../../auto_examples/exercises/images/plot_cv_digits_1.png - :target: ../../auto_examples/exercises/plot_cv_digits.html - :align: right - :scale: 100 - .. topic:: **Exercise** :class: green + .. image:: ../../auto_examples/exercises/images/plot_cv_digits_001.png + :target: ../../auto_examples/exercises/plot_cv_digits.html + :align: right + :scale: 90 + On the digits dataset, plot the cross-validation score of a :class:`SVC` - estimator with an RBF kernel as a function of parameter `C` (use a - logarithmic grid of points, from `1` to `10`). + estimator with an linear kernel as a function of parameter ``C`` (use a + logarithmic grid of points, from 1 to 10). .. literalinclude:: ../../auto_examples/exercises/plot_cv_digits.py :lines: 13-23 - Solution: :download:`../../auto_examples/exercises/plot_cv_digits.py` + **Solution:** :ref:`example_exercises_plot_cv_digits.py` @@ -140,23 +140,23 @@ parameters to maximize the cross-validation score. This object takes an estimator during the construction and exposes an estimator API:: >>> from sklearn.grid_search import GridSearchCV - >>> gammas = np.logspace(-6, -1, 10) - >>> clf = GridSearchCV(estimator=svc, param_grid=dict(gamma=gammas), + >>> Cs = np.logspace(-6, -1, 10) + >>> clf = GridSearchCV(estimator=svc, param_grid=dict(C=Cs), ... n_jobs=-1) - >>> clf.fit(X_digits[:1000], y_digits[:1000]) # doctest: +ELLIPSIS + >>> clf.fit(X_digits[:1000], y_digits[:1000]) # doctest: +ELLIPSIS GridSearchCV(cv=None,... - >>> clf.best_score_ - 0.988991985997974 - >>> clf.best_estimator_.gamma - 9.9999999999999995e-07 + >>> clf.best_score_ # doctest: +ELLIPSIS + 0.925... + >>> clf.best_estimator_.C # doctest: +ELLIPSIS + 0.0077... >>> # Prediction performance on test set is not as good as on train set - >>> clf.score(X_digits[1000:], y_digits[1000:]) - 0.94228356336260977 + >>> clf.score(X_digits[1000:], y_digits[1000:]) # doctest: +ELLIPSIS + 0.943... -By default the :class:`GridSearchCV` uses a 3-fold cross-validation. However, if -it detects that a classifier is passed, rather than a regressor, it uses +By default, the :class:`GridSearchCV` uses a 3-fold cross-validation. However, +if it detects that a classifier is passed, rather than a regressor, it uses a stratified 3-fold. .. topic:: Nested cross-validation @@ -164,17 +164,18 @@ a stratified 3-fold. :: >>> cross_validation.cross_val_score(clf, X_digits, y_digits) - array([ 0.97996661, 0.98163606, 0.98330551]) + ... # doctest: +ELLIPSIS + array([ 0.938..., 0.963..., 0.944...]) Two cross-validation loops are performed in parallel: one by the - :class:`GridSearchCV` estimator to set `gamma`, the other one by - `cross_val_score` to measure the prediction performance of the + :class:`GridSearchCV` estimator to set ``gamma`` and the other one by + ``cross_val_score`` to measure the prediction performance of the estimator. The resulting scores are unbiased estimates of the prediction score on new data. .. warning:: - You cannot nest objects with parallel computing (n_jobs different + You cannot nest objects with parallel computing (``n_jobs`` different than 1). .. _cv_estimators_tut: @@ -183,8 +184,8 @@ Cross-validated estimators ---------------------------- Cross-validation to set a parameter can be done more efficiently on an -algorithm-by-algorithm basis. This is why, for certain estimators, the -sklearn exposes :ref:`cross_validation` estimators, that set their parameter +algorithm-by-algorithm basis. This is why for certain estimators the +sklearn exposes :ref:`cross_validation` estimators that set their parameter automatically by cross-validation:: >>> from sklearn import linear_model, datasets @@ -194,11 +195,12 @@ automatically by cross-validation:: >>> y_diabetes = diabetes.target >>> lasso.fit(X_diabetes, y_diabetes) LassoCV(alphas=None, copy_X=True, cv=None, eps=0.001, fit_intercept=True, - max_iter=1000, n_alphas=100, normalize=False, precompute='auto', - tol=0.0001, verbose=False) + max_iter=1000, n_alphas=100, n_jobs=1, normalize=False, positive=False, + precompute='auto', random_state=None, selection='cyclic', tol=0.0001, + verbose=False) >>> # The estimator chose automatically its lambda: >>> lasso.alpha_ # doctest: +ELLIPSIS - 0.01318... + 0.01229... These estimators are called similarly to their counterparts, with 'CV' appended to their name. @@ -212,8 +214,8 @@ appended to their name. **Bonus**: How much can you trust the selection of alpha? .. literalinclude:: ../../auto_examples/exercises/plot_cv_diabetes.py - :lines: 11-23 + :lines: 17-24 - Solution: :download:`../../auto_examples/exercises/plot_cv_diabetes.py` + **Solution:** :ref:`example_exercises_plot_cv_diabetes.py` diff --git a/doc/tutorial/statistical_inference/putting_together.rst b/doc/tutorial/statistical_inference/putting_together.rst index be87cea3750d7..7ca7abfc5a47c 100644 --- a/doc/tutorial/statistical_inference/putting_together.rst +++ b/doc/tutorial/statistical_inference/putting_together.rst @@ -8,16 +8,16 @@ Putting it all together Pipelining ============ -We have seen that some estimators can transform data, and some estimators -can predict variables. We can create combined estimators: +We have seen that some estimators can transform data and that some estimators +can predict variables. We can also create combined estimators: -.. image:: ../../auto_examples/images/plot_digits_pipe_1.png +.. image:: ../../auto_examples/images/plot_digits_pipe_001.png :target: ../../auto_examples/plot_digits_pipe.html :scale: 65 :align: right .. literalinclude:: ../../auto_examples/plot_digits_pipe.py - :lines: 24-67 + :lines: 26-66 @@ -26,7 +26,7 @@ Face recognition with eigenfaces ================================= The dataset used in this example is a preprocessed excerpt of the -"Labeled Faces in the Wild", aka LFW_: +"Labeled Faces in the Wild", also known as LFW_: http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz (233MB) @@ -71,10 +71,6 @@ Expected results for the top 5 most represented people in the dataset:: Open problem: Stock Market Structure ===================================== -Can we predict the variation in stock prices for Google? +Can we predict the variation in stock prices for Google over a given time frame? :ref:`stock_market` - - - - diff --git a/doc/tutorial/statistical_inference/settings.rst b/doc/tutorial/statistical_inference/settings.rst index e3aa300f584b4..fead00cf952fb 100644 --- a/doc/tutorial/statistical_inference/settings.rst +++ b/doc/tutorial/statistical_inference/settings.rst @@ -1,12 +1,12 @@ -=============================================================================== -Statistical learning: the setting and the estimator object in the scikit-learn -=============================================================================== +========================================================================== +Statistical learning: the setting and the estimator object in scikit-learn +========================================================================== Datasets ========= -The `scikit-learn` deals with learning information from one or more +Scikit-learn deals with learning information from one or more datasets that are represented as 2D arrays. They can be understood as a list of multi-dimensional observations. We say that the first axis of these arrays is the **samples** axis, while the second is the @@ -24,14 +24,14 @@ these arrays is the **samples** axis, while the second is the It is made of 150 observations of irises, each described by 4 features: their sepal and petal length and width, as detailed in - `iris.DESCR`. + ``iris.DESCR``. -When the data is not intially in the `(n_samples, n_features)` shape, it -needs to be preprocessed to be used by the scikit. +When the data is not initially in the ``(n_samples, n_features)`` shape, it +needs to be preprocessed in order to be used by scikit-learn. -.. topic:: An example of reshaping data: the digits dataset +.. topic:: An example of reshaping data would be the digits dataset - .. image:: ../../auto_examples/datasets/images/plot_digits_last_image_1.png + .. image:: ../../auto_examples/datasets/images/plot_digits_last_image_001.png :target: ../../auto_examples/datasets/plot_digits_last_image.html :align: right :scale: 60 @@ -46,7 +46,7 @@ needs to be preprocessed to be used by the scikit. >>> pl.imshow(digits.images[-1], cmap=pl.cm.gray_r) #doctest: +SKIP - To use this dataset with the scikit, we transform each 8x8 image in a + To use this dataset with the scikit, we transform each 8x8 image into a feature vector of length 64 :: >>> data = digits.images.reshape((digits.images.shape[0], -1)) @@ -68,16 +68,16 @@ Estimators objects **Fitting data**: the main API implemented by scikit-learn is that of the `estimator`. An estimator is any object that learns from data; -it may a classification, regression or clustering algorithm or -a `transformer` that extracts/filters useful features from raw data. +it may be a classification, regression or clustering algorithm or +a *transformer* that extracts/filters useful features from raw data. -All estimator objects expose a `fit` method, that takes a dataset +All estimator objects expose a ``fit`` method that takes a dataset (usually a 2-d array): >>> estimator.fit(data) **Estimator parameters**: All the parameters of an estimator can be set -when it is instantiated, or by modifying the corresponding attribute:: +when it is instantiated or by modifying the corresponding attribute:: >>> estimator = Estimator(param1=1, param2=2) >>> estimator.param1 @@ -90,4 +90,3 @@ underscore:: >>> estimator.estimated_param_ #doctest: +SKIP - diff --git a/doc/tutorial/statistical_inference/supervised_learning.rst b/doc/tutorial/statistical_inference/supervised_learning.rst index ca57af93b3eaa..901d0409fa6b9 100644 --- a/doc/tutorial/statistical_inference/supervised_learning.rst +++ b/doc/tutorial/statistical_inference/supervised_learning.rst @@ -7,39 +7,38 @@ Supervised learning: predicting an output variable from high-dimensional observa .. topic:: The problem solved in supervised learning - :ref:`Supervised learning ` + :ref:`Supervised learning ` consists in learning the link between two - datasets: the observed data `X`, and an external variable `y` that we - are trying to predict, usually called `target` or `labels`. Most often, - `y` is a 1D array of length `n_samples`. - - All supervised `estimators `_ - in the `scikit-learn` implement a `fit(X, y)` - method to fit the model, and a `predict(X)` method that, given - unlabeled observations `X`, returns the predicted labels - `y`. + datasets: the observed data ``X`` and an external variable ``y`` that we + are trying to predict, usually called "target" or "labels". Most often, + ``y`` is a 1D array of length ``n_samples``. + + All supervised `estimators `_ + in scikit-learn implement a ``fit(X, y)`` method to fit the model + and a ``predict(X)`` method that, given unlabeled observations ``X``, + returns the predicted labels ``y``. .. topic:: Vocabulary: classification and regression If the prediction task is to classify the observations in a set of finite labels, in other words to "name" the objects observed, the task - is said to be a **classification** task. On the opposite, if the goal - is to predict a continous target variable, it is said to be a + is said to be a **classification** task. On the other hand, if the goal + is to predict a continuous target variable, it is said to be a **regression** task. - In the `scikit-learn`, for classification tasks, `y` is a vector of - integers. + When doing classification in scikit-learn, ``y`` is a vector of integers + or strings. - Note: See the :ref:`Introduction to machine learning with Scikit-learn + Note: See the :ref:`Introduction to machine learning with scikit-learn Tutorial ` for a quick run-through on the basic machine - learning vocabulary used within Scikit-learn. + learning vocabulary used within scikit-learn. Nearest neighbor and the curse of dimensionality ================================================= .. topic:: Classifying irises: - - .. image:: ../../auto_examples/datasets/images/plot_iris_dataset_1.png + + .. image:: ../../auto_examples/datasets/images/plot_iris_dataset_001.png :target: ../../auto_examples/datasets/plot_iris_dataset.html :align: right :scale: 65 @@ -59,24 +58,24 @@ Nearest neighbor and the curse of dimensionality k-Nearest neighbors classifier ------------------------------- -The simplest possible classifier is the +The simplest possible classifier is the `nearest neighbor `_: -given a new observation ``X_test``, find in the training set (i.e. the data +given a new observation ``X_test``, find in the training set (i.e. the data used to train the estimator) the observation with the closest feature vector. (Please see the :ref:`Nearest Neighbors section` of the online Scikit-learn documentation for more information about this type of classifier.) .. topic:: Training set and testing set - When experimenting with learning algorithm, it is important not to + While experimenting with any learning algorithm, it is important not to test the prediction of an estimator on the data used to fit the - estimator, as this would not be evaluating the performance of the + estimator as this would not be evaluating the performance of the estimator on **new data**. This is why datasets are often split into *train* and *test* data. **KNN (k nearest neighbors) classification example**: -.. image:: ../../auto_examples/neighbors/images/plot_classification_1.png +.. image:: ../../auto_examples/neighbors/images/plot_classification_001.png :target: ../../auto_examples/neighbors/plot_classification.html :align: center :scale: 70 @@ -94,9 +93,9 @@ Scikit-learn documentation for more information about this type of classifier.) >>> # Create and fit a nearest-neighbor classifier >>> from sklearn.neighbors import KNeighborsClassifier >>> knn = KNeighborsClassifier() - >>> knn.fit(iris_X_train, iris_y_train) - KNeighborsClassifier(algorithm='auto', leaf_size=30, n_neighbors=5, p=2, - warn_on_equidistant=True, weights='uniform') + >>> knn.fit(iris_X_train, iris_y_train) # doctest: +NORMALIZE_WHITESPACE + KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', + metric_params=None, n_neighbors=5, p=2, weights='uniform') >>> knn.predict(iris_X_test) array([1, 2, 1, 0, 0, 0, 2, 1, 2, 0]) >>> iris_y_test @@ -107,27 +106,28 @@ Scikit-learn documentation for more information about this type of classifier.) The curse of dimensionality ------------------------------- -For an estimator to be effective, you need the distance between neighboring -points to be less than some value `d`, which depends on the problem. -In one dimension, this requires on average `n ~ 1/d` points. -In the context of the above `KNN` example, if the data is only described by -one feature, with values ranging from 0 to 1 and with `n` training observations, -new data will thus be no further away than `1/n`. +For an estimator to be effective, you need the distance between neighboring +points to be less than some value :math:`d`, which depends on the problem. +In one dimension, this requires on average :math:`n ~ 1/d` points. +In the context of the above :math:`k`-NN example, if the data is described by +just one feature with values ranging from 0 to 1 and with :math:`n` training +observations, then new data will be no further away than :math:`1/n`. Therefore, the nearest neighbor decision rule will be efficient as soon as -`1/n` is small compared to the scale of between-class feature variations. +:math:`1/n` is small compared to the scale of between-class feature variations. -If the number of features is `p`, you now require `n ~ 1/d^p` points. -Let's say that we require 10 points in one dimension: Now `10^p` points -are required in `p` dimensions to pave the `[0, 1]` space. -As `p` becomes large, the number of training points required for a good +If the number of features is :math:`p`, you now require :math:`n ~ 1/d^p` +points. Let's say that we require 10 points in one dimension: now :math:`10^p` +points are required in :math:`p` dimensions to pave the :math:`[0, 1]` space. +As :math:`p` becomes large, the number of training points required for a good estimator grows exponentially. -For example, if each point is just a single number (8 bytes), then an -effective `KNN` estimator in a paltry `p~20` dimensions would require more training -data than the current estimated size of the entire internet! (±1000 Exabytes or so). +For example, if each point is just a single number (8 bytes), then an +effective :math:`k`-NN estimator in a paltry :math:`p~20` dimensions would +require more training data than the current estimated size of the entire +internet (±1000 Exabytes or so). -This is called the -`curse of dimensionality `_ +This is called the +`curse of dimensionality `_ and is a core problem that machine learning addresses. Linear model: from regression to sparsity @@ -144,9 +144,9 @@ Linear model: from regression to sparsity >>> diabetes_X_test = diabetes.data[-20:] >>> diabetes_y_train = diabetes.target[:-20] >>> diabetes_y_test = diabetes.target[-20:] - + The task at hand is to predict disease progression from physiological - variables. + variables. Linear regression ------------------ @@ -154,11 +154,11 @@ Linear regression .. currentmodule:: sklearn.linear_model :class:`LinearRegression`, -in it's simplest form, fits a linear model to the data set by adjusting -a set of parameters, in order to make the sum of the squared residuals -of the model as small as possilbe. +in it's simplest form, fits a linear model to the data set by adjusting +a set of parameters in order to make the sum of the squared residuals +of the model as small as possible. -.. image:: ../../auto_examples/linear_model/images/plot_ols_1.png +.. image:: ../../auto_examples/linear_model/images/plot_ols_001.png :target: ../../auto_examples/linear_model/plot_ols.html :scale: 40 :align: right @@ -170,16 +170,16 @@ Linear models: :math:`y = X\beta + \epsilon` * :math:`\beta`: Coefficients * :math:`\epsilon`: Observation noise -:: +:: >>> from sklearn import linear_model >>> regr = linear_model.LinearRegression() >>> regr.fit(diabetes_X_train, diabetes_y_train) - LinearRegression(copy_X=True, fit_intercept=True, normalize=False) - >>> print regr.coef_ + LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False) + >>> print(regr.coef_) [ 0.30349955 -237.63931533 510.53060544 327.73698041 -814.13170937 492.81458798 102.84845219 184.60648906 743.51961675 76.09517222] - + >>> # The mean square error >>> np.mean((regr.predict(diabetes_X_test)-diabetes_y_test)**2)# doctest: +ELLIPSIS 2004.56760268... @@ -193,13 +193,13 @@ Linear models: :math:`y = X\beta + \epsilon` .. _shrinkage: -Shrinkage +Shrinkage ---------- If there are few data points per dimension, noise in the observations induces high variance: -.. image:: ../../auto_examples/linear_model/images/plot_ols_ridge_variance_1.png +.. image:: ../../auto_examples/linear_model/images/plot_ols_ridge_variance_001.png :target: ../../auto_examples/linear_model/plot_ols_ridge_variance.html :scale: 70 :align: right @@ -210,7 +210,7 @@ induces high variance: >>> y = [.5, 1] >>> test = np.c_[ 0, 2].T >>> regr = linear_model.LinearRegression() - + >>> import pylab as pl # doctest: +SKIP >>> pl.figure() # doctest: +SKIP @@ -223,12 +223,12 @@ induces high variance: -A solution, in high-dimensional statistical learning, is to *shrink* the +A solution in high-dimensional statistical learning is to *shrink* the regression coefficients to zero: any two randomly chosen set of observations are likely to be uncorrelated. This is called :class:`Ridge` regression: -.. image:: ../../auto_examples/linear_model/images/plot_ols_ridge_variance_2.png +.. image:: ../../auto_examples/linear_model/images/plot_ols_ridge_variance_002.png :target: ../../auto_examples/linear_model/plot_ols_ridge_variance.html :scale: 70 :align: right @@ -247,24 +247,25 @@ regression: ... pl.scatter(this_X, y, s=3) # doctest: +SKIP This is an example of **bias/variance tradeoff**: the larger the ridge -`alpha` parameter, the higher the bias and the lower the variance. +``alpha`` parameter, the higher the bias and the lower the variance. -We can choose `alpha` to minimize left out error, this time using the -diabetes dataset, rather than our synthetic data:: +We can choose ``alpha`` to minimize left out error, this time using the +diabetes dataset rather than our synthetic data:: >>> alphas = np.logspace(-4, -1, 6) - >>> print [regr.set_params(alpha=alpha + >>> from __future__ import print_function + >>> print([regr.set_params(alpha=alpha ... ).fit(diabetes_X_train, diabetes_y_train, - ... ).score(diabetes_X_test, diabetes_y_test) for alpha in alphas] # doctest: +ELLIPSIS + ... ).score(diabetes_X_test, diabetes_y_test) for alpha in alphas]) # doctest: +ELLIPSIS [0.5851110683883..., 0.5852073015444..., 0.5854677540698..., 0.5855512036503..., 0.5830717085554..., 0.57058999437...] .. note:: Capturing in the fitted parameters noise that prevents the model to - generalize to new data is called + generalize to new data is called `overfitting `_. The bias introduced - by the ridge regression is called a + by the ridge regression is called a `regularization `_. .. _sparsity: @@ -273,15 +274,15 @@ Sparsity ---------- -.. |diabetes_ols_1| image:: ../../auto_examples/linear_model/images/plot_ols_3d_1.png +.. |diabetes_ols_1| image:: ../../auto_examples/linear_model/images/plot_ols_3d_001.png :target: ../../auto_examples/linear_model/plot_ols_3d.html :scale: 65 -.. |diabetes_ols_3| image:: ../../auto_examples/linear_model/images/plot_ols_3d_3.png +.. |diabetes_ols_3| image:: ../../auto_examples/linear_model/images/plot_ols_3d_003.png :target: ../../auto_examples/linear_model/plot_ols_3d.html :scale: 65 -.. |diabetes_ols_2| image:: ../../auto_examples/linear_model/images/plot_ols_3d_2.png +.. |diabetes_ols_2| image:: ../../auto_examples/linear_model/images/plot_ols_3d_002.png :target: ../../auto_examples/linear_model/plot_ols_3d.html :scale: 65 @@ -292,73 +293,72 @@ Sparsity **Fitting only features 1 and 2** -.. centered:: |diabetes_ols_1| |diabetes_ols_3| |diabetes_ols_2| +.. centered:: |diabetes_ols_1| |diabetes_ols_3| |diabetes_ols_2| .. note:: A representation of the full diabetes dataset would involve 11 - dimensions (10 feature dimensions, and one of the target variable). It + dimensions (10 feature dimensions and one of the target variable). It is hard to develop an intuition on such representation, but it may be useful to keep in mind that it would be a fairly *empty* space. -We can see that although feature 2 has a strong coefficient on the full -model, it conveys little information on `y` when considered with feature -1. +We can see that, although feature 2 has a strong coefficient on the full +model, it conveys little information on ``y`` when considered with feature 1. -To improve the conditioning of the problem (mitigate the -:ref:`curse_of_dimensionality`), it would be interesting to select only the -informative features and set non-informative ones, like feature 2 to 0. Ridge +To improve the conditioning of the problem (i.e. mitigating the +:ref:`curse_of_dimensionality`), it would be interesting to select only the +informative features and set non-informative ones, like feature 2 to 0. Ridge regression will decrease their contribution, but not set them to zero. Another -penalization approach, called :ref:`lasso` (least absolute shrinkage and -selection operator), can set some coefficients to zero. Such methods are -called **sparse method**, and sparsity can be seen as an -application of Occam's razor: `prefer simpler models`. +penalization approach, called :ref:`lasso` (least absolute shrinkage and +selection operator), can set some coefficients to zero. Such methods are +called **sparse method** and sparsity can be seen as an +application of Occam's razor: *prefer simpler models*. -:: +:: >>> regr = linear_model.Lasso() >>> scores = [regr.set_params(alpha=alpha ... ).fit(diabetes_X_train, diabetes_y_train - ... ).score(diabetes_X_test, diabetes_y_test) + ... ).score(diabetes_X_test, diabetes_y_test) ... for alpha in alphas] >>> best_alpha = alphas[scores.index(max(scores))] >>> regr.alpha = best_alpha >>> regr.fit(diabetes_X_train, diabetes_y_train) Lasso(alpha=0.025118864315095794, copy_X=True, fit_intercept=True, - max_iter=1000, normalize=False, positive=False, precompute='auto', - tol=0.0001, warm_start=False) - >>> print regr.coef_ + max_iter=1000, normalize=False, positive=False, precompute=False, + random_state=None, selection='cyclic', tol=0.0001, warm_start=False) + >>> print(regr.coef_) [ 0. -212.43764548 517.19478111 313.77959962 -160.8303982 -0. -187.19554705 69.38229038 508.66011217 71.84239008] -.. topic:: **Different algorithms for a same problem** +.. topic:: **Different algorithms for the same problem** Different algorithms can be used to solve the same mathematical - problem. For instance the `Lasso` object in the `scikit-learn` - solves the lasso regression using a - `coordinate decent `_ method, - that is efficient on large datasets. However, the `scikit-learn` also - provides the :class:`LassoLars` object, using the *LARS* which is very - efficient for problems in which the weight vector estimated is very - sparse, that is problems with very few observations. + problem. For instance the ``Lasso`` object in scikit-learn + solves the lasso regression problem using a + `coordinate decent `_ method, + that is efficient on large datasets. However, scikit-learn also + provides the :class:`LassoLars` object using the *LARS* algorthm, + which is very efficient for problems in which the weight vector estimated + is very sparse (i.e. problems with very few observations). .. _clf_tut: Classification --------------- -.. image:: ../../auto_examples/linear_model/images/plot_logistic_1.png +.. image:: ../../auto_examples/linear_model/images/plot_logistic_001.png :target: ../../auto_examples/linear_model/plot_logistic.html :scale: 65 :align: right -For classification, as in the labeling -`iris `_ task, linear -regression is not the right approach, as it will give too much weight to -data far from the decision frontier. A linear approach is to fit a sigmoid -function, or **logistic** function: +For classification, as in the labeling +`iris `_ task, linear +regression is not the right approach as it will give too much weight to +data far from the decision frontier. A linear approach is to fit a sigmoid +function or **logistic** function: .. math:: @@ -370,28 +370,29 @@ function, or **logistic** function: >>> logistic = linear_model.LogisticRegression(C=1e5) >>> logistic.fit(iris_X_train, iris_y_train) LogisticRegression(C=100000.0, class_weight=None, dual=False, - fit_intercept=True, intercept_scaling=1, penalty='l2', - tol=0.0001) + fit_intercept=True, intercept_scaling=1, max_iter=100, + multi_class='ovr', penalty='l2', random_state=None, + solver='liblinear', tol=0.0001, verbose=0) This is known as :class:`LogisticRegression`. -.. image:: ../../auto_examples/linear_model/images/plot_iris_logistic_1.png +.. image:: ../../auto_examples/linear_model/images/plot_iris_logistic_001.png :target: ../../auto_examples/linear_model/plot_iris_logistic.html :scale: 83 .. topic:: Multiclass classification If you have several classes to predict, an option often used is to fit - one-versus-all classifiers, and use a voting heuristic for the final + one-versus-all classifiers and then use a voting heuristic for the final decision. .. topic:: Shrinkage and sparsity with logistic regression - The `C` parameter controls the amount of regularization in the - :class:`LogisticRegression` object: a large value for `C` results in + The ``C`` parameter controls the amount of regularization in the + :class:`LogisticRegression` object: a large value for ``C`` results in less regularization. - `penalty="l2"` gives :ref:`shrinkage` (i.e. non-sparse coefficients), while - `penalty="l1"` gives :ref:`sparsity`. + ``penalty="l2"`` gives :ref:`shrinkage` (i.e. non-sparse coefficients), while + ``penalty="l1"`` gives :ref:`sparsity`. .. topic:: **Exercise** :class: green @@ -400,10 +401,10 @@ This is known as :class:`LogisticRegression`. model. Leave out the last 10% and test prediction performance on these observations. - .. literalinclude:: ../../auto_examples/exercises/plot_digits_classification_exercise.py - :lines: 12-17 + .. literalinclude:: ../../auto_examples/exercises/digits_classification_exercise.py + :lines: 15-19 - Solution: :download:`../../auto_examples/exercises/plot_digits_classification_exercise.py` + Solution: :download:`../../auto_examples/exercises/digits_classification_exercise.py` Support vector machines (SVMs) @@ -413,21 +414,21 @@ Linear SVMs ------------- -:ref:`svm` belong to the discrimant model family: they try to find a combination of +:ref:`svm` belong to the discriminant model family: they try to find a combination of samples to build a plane maximizing the margin between the two classes. -Regularization is set by the `C` parameter: a small value for `C` means the margin +Regularization is set by the ``C`` parameter: a small value for ``C`` means the margin is calculated using many or all of the observations around the separating line (more regularization); -a large value for `C` means the margin is calculated on observations close to +a large value for ``C`` means the margin is calculated on observations close to the separating line (less regularization). .. currentmodule :: sklearn.svm -.. |svm_margin_unreg| image:: ../../auto_examples/svm/images/plot_svm_margin_1.png +.. |svm_margin_unreg| image:: ../../auto_examples/svm/images/plot_svm_margin_001.png :target: ../../auto_examples/svm/plot_svm_margin.html :scale: 70 -.. |svm_margin_reg| image:: ../../auto_examples/svm/images/plot_svm_margin_2.png +.. |svm_margin_reg| image:: ../../auto_examples/svm/images/plot_svm_margin_002.png :target: ../../auto_examples/svm/plot_svm_margin.html :scale: 70 @@ -439,21 +440,22 @@ the separating line (less regularization). |svm_margin_unreg| |svm_margin_reg| ============================= ============================== -.. image:: ../../auto_examples/svm/images/plot_svm_iris_1.png - :target: ../../auto_examples/svm/plot_svm_iris.html - :scale: 83 +.. topic:: Example: + + - :ref:`example_svm_plot_iris.py` + SVMs can be used in regression --:class:`SVR` (Support Vector Regression)--, or in -classification --:class:`SVC` (Support Vector Classification). +classification --:class:`SVC` (Support Vector Classification). :: >>> from sklearn import svm >>> svc = svm.SVC(kernel='linear') - >>> svc.fit(iris_X_train, iris_y_train) + >>> svc.fit(iris_X_train, iris_y_train) # doctest: +NORMALIZE_WHITESPACE SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, - kernel='linear', probability=False, shrinking=True, tol=0.001, - verbose=False) + kernel='linear', max_iter=-1, probability=False, random_state=None, + shrinking=True, tol=0.001, verbose=False) .. warning:: **Normalizing data** @@ -468,86 +470,86 @@ Using kernels -------------- Classes are not always linearly separable in feature space. The solution is to -build a decision function that is not linear but that may be for instance -polynomial. This is done using the *kernel trick* that can be seen as -creating an decision energy by positioning *kernels* on observations: +build a decision function that is not linear but may be polynomial instead. +This is done using the *kernel trick* that can be seen as +creating a decision energy by positioning *kernels* on observations: -.. |svm_kernel_linear| image:: ../../auto_examples/svm/images/plot_svm_kernels_1.png +.. |svm_kernel_linear| image:: ../../auto_examples/svm/images/plot_svm_kernels_001.png :target: ../../auto_examples/svm/plot_svm_kernels.html - :scale: 65 + :scale: 65 -.. |svm_kernel_poly| image:: ../../auto_examples/svm/images/plot_svm_kernels_2.png +.. |svm_kernel_poly| image:: ../../auto_examples/svm/images/plot_svm_kernels_002.png :target: ../../auto_examples/svm/plot_svm_kernels.html :scale: 65 .. rst-class:: centered .. list-table:: - - * - + + * + - **Linear kernel** - + - **Polynomial kernel** - - - * - + + + * + - |svm_kernel_linear| - |svm_kernel_poly| - - * - + + * + - :: >>> svc = svm.SVC(kernel='linear') - :: - >>> svc = svm.SVC(kernel='poly', + >>> svc = svm.SVC(kernel='poly', ... degree=3) >>> # degree: polynomial degree -.. |svm_kernel_rbf| image:: ../../auto_examples/svm/images/plot_svm_kernels_3.png +.. |svm_kernel_rbf| image:: ../../auto_examples/svm/images/plot_svm_kernels_003.png :target: ../../auto_examples/svm/plot_svm_kernels.html :scale: 65 .. rst-class:: centered .. list-table:: - - * - + + * + - **RBF kernel (Radial Basis Function)** - - - * - + + + * + - |svm_kernel_rbf| - * - + * + - :: - >>> svc = svm.SVC(kernel='rbf') - >>> # gamma: inverse of size of + >>> svc = svm.SVC(kernel='rbf') + >>> # gamma: inverse of size of >>> # radial kernel .. topic:: **Interactive example** - See the :ref:`SVM GUI ` to download - `svm_gui.py`; add data points of both classes with right and left button, + See the :ref:`SVM GUI ` to download + ``svm_gui.py``; add data points of both classes with right and left button, fit the model and change parameters and data. -.. image:: ../../auto_examples/datasets/images/plot_iris_dataset_1.png +.. image:: ../../auto_examples/datasets/images/plot_iris_dataset_001.png :target: ../../auto_examples/datasets/plot_iris_dataset.html :align: right :scale: 70 @@ -562,13 +564,10 @@ creating an decision energy by positioning *kernels* on observations: **Warning**: the classes are ordered, do not leave out the last 10%, you would be testing on only one class. - **Hint**: You can use the `decision_function` method on a grid to get + **Hint**: You can use the ``decision_function`` method on a grid to get intuitions. .. literalinclude:: ../../auto_examples/exercises/plot_iris_exercise.py - :lines: 15-22 + :lines: 18-23 Solution: :download:`../../auto_examples/exercises/plot_iris_exercise.py` - - - diff --git a/doc/tutorial/statistical_inference/unsupervised_learning.rst b/doc/tutorial/statistical_inference/unsupervised_learning.rst index 1ef89dfcec676..1b66f2d2780ae 100644 --- a/doc/tutorial/statistical_inference/unsupervised_learning.rst +++ b/doc/tutorial/statistical_inference/unsupervised_learning.rst @@ -9,7 +9,7 @@ Clustering: grouping observations together Given the iris dataset, if we knew that there were 3 types of iris, but did not have access to a taxonomist to label them: we could try a - **clustering task**: split the observations in well-separated group + **clustering task**: split the observations into well-separated group called *clusters*. .. @@ -20,11 +20,11 @@ Clustering: grouping observations together K-means clustering ------------------- -Note that their exists a lot of different clustering criteria and associated -algorithms. The simplest clustering algorithm is the +Note that there exist a lot of different clustering criteria and associated +algorithms. The simplest clustering algorithm is :ref:`k_means`. -.. image:: ../../auto_examples/cluster/images/plot_cluster_iris_2.png +.. image:: ../../auto_examples/cluster/images/plot_cluster_iris_002.png :target: ../../auto_examples/cluster/plot_cluster_iris.html :scale: 70 :align: right @@ -40,30 +40,29 @@ algorithms. The simplest clustering algorithm is the >>> k_means = cluster.KMeans(n_clusters=3) >>> k_means.fit(X_iris) # doctest: +ELLIPSIS KMeans(copy_x=True, init='k-means++', ... - >>> print k_means.labels_[::10] + >>> print(k_means.labels_[::10]) [1 1 1 1 1 0 0 0 0 0 2 2 2 2 2] - >>> print y_iris[::10] + >>> print(y_iris[::10]) [0 0 0 0 0 1 1 1 1 1 2 2 2 2 2] -.. |k_means_iris_bad_init| image:: ../../auto_examples/cluster/images/plot_cluster_iris_3.png +.. |k_means_iris_bad_init| image:: ../../auto_examples/cluster/images/plot_cluster_iris_003.png :target: ../../auto_examples/cluster/plot_cluster_iris.html :scale: 63 -.. |k_means_iris_8| image:: ../../auto_examples/cluster/images/plot_cluster_iris_1.png +.. |k_means_iris_8| image:: ../../auto_examples/cluster/images/plot_cluster_iris_001.png :target: ../../auto_examples/cluster/plot_cluster_iris.html :scale: 63 -.. |cluster_iris_truth| image:: ../../auto_examples/cluster/images/plot_cluster_iris_4.png +.. |cluster_iris_truth| image:: ../../auto_examples/cluster/images/plot_cluster_iris_004.png :target: ../../auto_examples/cluster/plot_cluster_iris.html :scale: 63 .. warning:: - There is absolutely no guarantee of recovering a ground truth. First + There is absolutely no guarantee of recovering a ground truth. First, choosing the right number of clusters is hard. Second, the algorithm - is sensitive to initialization, and can fall in local minima, - although in the `sklearn` package we play many tricks to mitigate this - issue. + is sensitive to initialization, and can fall into local minima, + although scikit-learn employs several tricks to mitigate this issue. .. list-table:: :class: centered @@ -86,27 +85,27 @@ algorithms. The simplest clustering algorithm is the **Don't over-interpret clustering results** -.. |lena| image:: ../../auto_examples/cluster/images/plot_lena_compress_1.png +.. |lena| image:: ../../auto_examples/cluster/images/plot_lena_compress_001.png :target: ../../auto_examples/cluster/plot_lena_compress.html :scale: 60 -.. |lena_regular| image:: ../../auto_examples/cluster/images/plot_lena_compress_2.png +.. |lena_regular| image:: ../../auto_examples/cluster/images/plot_lena_compress_002.png :target: ../../auto_examples/cluster/plot_lena_compress.html :scale: 60 -.. |lena_compressed| image:: ../../auto_examples/cluster/images/plot_lena_compress_3.png +.. |lena_compressed| image:: ../../auto_examples/cluster/images/plot_lena_compress_003.png :target: ../../auto_examples/cluster/plot_lena_compress.html :scale: 60 -.. |lena_histogram| image:: ../../auto_examples/cluster/images/plot_lena_compress_4.png +.. |lena_histogram| image:: ../../auto_examples/cluster/images/plot_lena_compress_004.png :target: ../../auto_examples/cluster/plot_lena_compress.html :scale: 60 .. topic:: **Application example: vector quantization** - Clustering in general and KMeans in particular, can be seen as a way - of choosing a small number of examplars to compress the information, - a problem sometimes known as + Clustering in general and KMeans, in particular, can be seen as a way + of choosing a small number of exemplars to compress the information. + The problem is sometimes known as `vector quantization `_. For instance, this can be used to posterize an image:: @@ -151,38 +150,40 @@ algorithms. The simplest clustering algorithm is the Hierarchical agglomerative clustering: Ward --------------------------------------------- -A :ref:`hierarchical_clustering` method is a type of cluster analysis +A :ref:`hierarchical_clustering` method is a type of cluster analysis that aims to build a hierarchy of clusters. In general, the various approaches of this technique are either: - * **Agglomerative** - `bottom-up` approaches, or - * **Divisive** - `top-down` approaches. + * **Agglomerative** - bottom-up approaches: each observation starts in its + own cluster, and clusters are iterativelly merged in such a way to + minimize a *linkage* criterion. This approach is particularly interesting + when the clusters of interest are made of only a few observations. When + the number of clusters is large, it is much more computationally efficient + than k-means. -For estimating a large number of clusters, top-down approaches are both -statisticaly ill-posed, and slow - due to it starting with all observations -as one cluster, which it splits recursively. Agglomerative -hierarchical-clustering is a bottom-up approach that successively merges -observations together and is particularly useful when the clusters of interest -are made of only a few observations. *Ward* clustering minimizes a criterion -similar to k-means in a bottom-up approach. When the number of clusters is large, -it is much more computationally efficient than k-means. + * **Divisive** - top-down approaches: all observations start in one + cluster, which is iteratively split as one moves down the hierarchy. + For estimating large numbers of clusters, this approach is both slow (due + to all observations starting as one cluster, which it splits recursively) + and statistically ill-posed. Connectivity-constrained clustering ..................................... -With Ward clustering, it is possible to specify which samples can be +With agglomerative clustering, it is possible to specify which samples can be clustered together by giving a connectivity graph. Graphs in the scikit -are represented by their adjacency matrix. Often a sparse matrix is used. -This can be useful for instance to retrieve connect regions when +are represented by their adjacency matrix. Often, a sparse matrix is used. +This can be useful, for instance, to retrieve connected regions (sometimes +also referred to as connected components) when clustering an image: -.. image:: ../../auto_examples/cluster/images/plot_lena_ward_segmentation_1.png +.. image:: ../../auto_examples/cluster/images/plot_lena_ward_segmentation_001.png :target: ../../auto_examples/cluster/plot_lena_ward_segmentation.html :scale: 40 :align: right .. literalinclude:: ../../auto_examples/cluster/plot_lena_ward_segmentation.py - :lines: 24-44 + :lines: 21-45 .. >>> from sklearn.feature_extraction.image import grid_to_graph @@ -193,13 +194,13 @@ Feature agglomeration ...................... We have seen that sparsity could be used to mitigate the curse of -dimensionality, *i.e* the insufficience of observations compared to the +dimensionality, *i.e* an insufficient amount of observations compared to the number of features. Another approach is to merge together similar -features: **feature agglomeration**. This approach can be implementing by +features: **feature agglomeration**. This approach can be implemented by clustering in the feature direction, in other words clustering the transposed data. -.. image:: ../../auto_examples/cluster/images/plot_digits_agglomeration_1.png +.. image:: ../../auto_examples/cluster/images/plot_digits_agglomeration_001.png :target: ../../auto_examples/cluster/plot_digits_agglomeration.html :align: right :scale: 57 @@ -211,18 +212,18 @@ transposed data. >>> X = np.reshape(images, (len(images), -1)) >>> connectivity = grid_to_graph(*images[0].shape) - >>> agglo = cluster.WardAgglomeration(connectivity=connectivity, - ... n_clusters=32) + >>> agglo = cluster.FeatureAgglomeration(connectivity=connectivity, + ... n_clusters=32) >>> agglo.fit(X) # doctest: +ELLIPSIS - WardAgglomeration(compute_full_tree='auto',... + FeatureAgglomeration(affinity='euclidean', compute_full_tree='auto',... >>> X_reduced = agglo.transform(X) >>> X_approx = agglo.inverse_transform(X_reduced) >>> images_approx = np.reshape(X_approx, images.shape) -.. topic:: `transform` and `inverse_transform` methods +.. topic:: ``transform`` and ``inverse_transform`` methods - Some estimators expose a `transform` method, for instance to reduce + Some estimators expose a ``transform`` method, for instance to reduce the dimensionality of the dataset. Decompositions: from a signal to components and loadings @@ -230,8 +231,8 @@ Decompositions: from a signal to components and loadings .. topic:: **Components and loadings** - If X is our multivariate data, the problem that we are trying to solve - is to rewrite it on a different observation basis: we want to learn + If X is our multivariate data, then the problem that we are trying to solve + is to rewrite it on a different observational basis: we want to learn loadings L and a set of components C such that *X = L C*. Different criteria exist to choose the components @@ -241,11 +242,11 @@ Principal component analysis: PCA :ref:`PCA` selects the successive components that explain the maximum variance in the signal. -.. |pca_3d_axis| image:: ../../auto_examples/decomposition/images/plot_pca_3d_1.png +.. |pca_3d_axis| image:: ../../auto_examples/decomposition/images/plot_pca_3d_001.png :target: ../../auto_examples/decomposition/plot_pca_3d.html :scale: 70 -.. |pca_3d_aligned| image:: ../../auto_examples/decomposition/images/plot_pca_3d_2.png +.. |pca_3d_aligned| image:: ../../auto_examples/decomposition/images/plot_pca_3d_002.png :target: ../../auto_examples/decomposition/plot_pca_3d.html :scale: 70 @@ -254,8 +255,8 @@ explain the maximum variance in the signal. |pca_3d_axis| |pca_3d_aligned| The point cloud spanned by the observations above is very flat in one -direction: one of the 3 univariate features can almost be exactly -computed using the 2 other. PCA finds the directions in which the data is +direction: one of the three univariate features can almost be exactly +computed using the other two. PCA finds the directions in which the data is not *flat* When used to *transform* data, PCA can reduce the dimensionality of the @@ -275,7 +276,7 @@ data by projecting on a principal subspace. >>> pca = decomposition.PCA() >>> pca.fit(X) PCA(copy=True, n_components=None, whiten=False) - >>> print pca.explained_variance_ # doctest: +SKIP + >>> print(pca.explained_variance_) # doctest: +SKIP [ 2.18565811e+00 1.19346747e+00 8.43026679e-32] >>> # As we can see, only the 2 first components are useful @@ -293,7 +294,7 @@ Independent Component Analysis: ICA a maximum amount of independent information. It is able to recover **non-Gaussian** independent signals: -.. image:: ../../auto_examples/decomposition/images/plot_ica_blind_source_separation_1.png +.. image:: ../../auto_examples/decomposition/images/plot_ica_blind_source_separation_001.png :target: ../../auto_examples/decomposition/plot_ica_blind_source_separation.html :scale: 70 :align: center @@ -315,8 +316,8 @@ a maximum amount of independent information. It is able to recover >>> # Compute ICA >>> ica = decomposition.FastICA() - >>> S_ = ica.fit(X).transform(X) # Get the estimated sources - >>> A_ = ica.get_mixing_matrix() # Get estimated mixing matrix - >>> np.allclose(X, np.dot(S_, A_.T)) + >>> S_ = ica.fit_transform(X) # Get the estimated sources + >>> A_ = ica.mixing_.T + >>> np.allclose(X, np.dot(S_, A_) + ica.mean_) True diff --git a/doc/tutorial/text_analytics/.gitignore b/doc/tutorial/text_analytics/.gitignore new file mode 100644 index 0000000000000..54c78634d9dd1 --- /dev/null +++ b/doc/tutorial/text_analytics/.gitignore @@ -0,0 +1,25 @@ +# cruft +.*.swp +*.pyc +.DS_Store +*.pdf + +# folder to be used for working on the exercises +workspace + +# output of the sphinx build of the documentation +tutorial/_build + +# datasets to be fetched from the web and cached locally +data/twenty_newsgroups/20news-bydate.tar.gz +data/twenty_newsgroups/20news-bydate-train +data/twenty_newsgroups/20news-bydate-test + +data/movie_reviews/txt_sentoken +data/movie_reviews/poldata.README.2.0 + +data/languages/paragraphs +data/languages/short_paragraphs +data/languages/html + +data/labeled_faces_wild/lfw_preprocessed/ diff --git a/doc/tutorial/text_analytics/data/languages/fetch_data.py b/doc/tutorial/text_analytics/data/languages/fetch_data.py new file mode 100644 index 0000000000000..2abef7425fb5f --- /dev/null +++ b/doc/tutorial/text_analytics/data/languages/fetch_data.py @@ -0,0 +1,105 @@ + +# simple python script to collect text paragraphs from various languages on the +# same topic namely the Wikipedia encyclopedia itself + +import os +try: + # Python 2 compat + from urllib2 import Request, build_opener +except ImportError: + # Python 3 + from urllib.request import Request, build_opener + +import lxml.html +from lxml.etree import ElementTree +import numpy as np + +pages = { + u'ar': u'http://ar.wikipedia.org/wiki/%D9%88%D9%8A%D9%83%D9%8A%D8%A8%D9%8A%D8%AF%D9%8A%D8%A7', + u'de': u'http://de.wikipedia.org/wiki/Wikipedia', + u'en': u'http://en.wikipedia.org/wiki/Wikipedia', + u'es': u'http://es.wikipedia.org/wiki/Wikipedia', + u'fr': u'http://fr.wikipedia.org/wiki/Wikip%C3%A9dia', + u'it': u'http://it.wikipedia.org/wiki/Wikipedia', + u'ja': u'http://ja.wikipedia.org/wiki/Wikipedia', + u'nl': u'http://nl.wikipedia.org/wiki/Wikipedia', + u'pl': u'http://pl.wikipedia.org/wiki/Wikipedia', + u'pt': u'http://pt.wikipedia.org/wiki/Wikip%C3%A9dia', + u'ru': u'http://ru.wikipedia.org/wiki/%D0%92%D0%B8%D0%BA%D0%B8%D0%BF%D0%B5%D0%B4%D0%B8%D1%8F', +# u'zh': u'http://zh.wikipedia.org/wiki/Wikipedia', +} + +html_folder = u'html' +text_folder = u'paragraphs' +short_text_folder = u'short_paragraphs' +n_words_per_short_text = 5 + + +if not os.path.exists(html_folder): + os.makedirs(html_folder) + +for lang, page in pages.items(): + + text_lang_folder = os.path.join(text_folder, lang) + if not os.path.exists(text_lang_folder): + os.makedirs(text_lang_folder) + + short_text_lang_folder = os.path.join(short_text_folder, lang) + if not os.path.exists(short_text_lang_folder): + os.makedirs(short_text_lang_folder) + + opener = build_opener() + html_filename = os.path.join(html_folder, lang + '.html') + if not os.path.exists(html_filename): + print("Downloading %s" % page) + request = Request(page) + # change the User Agent to avoid being blocked by Wikipedia + # downloading a couple of articles ones should not be abusive + request.add_header('User-Agent', 'OpenAnything/1.0') + html_content = opener.open(request).read() + open(html_filename, 'wb').write(html_content) + + # decode the payload explicitly as UTF-8 since lxml is confused for some + # reason + html_content = open(html_filename).read() + if hasattr(html_content, 'decode'): + html_content = html_content.decode('utf-8') + tree = ElementTree(lxml.html.document_fromstring(html_content)) + i = 0 + j = 0 + for p in tree.findall('//p'): + content = p.text_content() + if len(content) < 100: + # skip paragraphs that are too short - probably too noisy and not + # representative of the actual language + continue + + text_filename = os.path.join(text_lang_folder, + '%s_%04d.txt' % (lang, i)) + print("Writing %s" % text_filename) + open(text_filename, 'wb').write(content.encode('utf-8', 'ignore')) + i += 1 + + # split the paragraph into fake smaller paragraphs to make the + # problem harder e.g. more similar to tweets + if lang in ('zh', 'ja'): + # FIXME: whitespace tokenizing does not work on chinese and japanese + continue + words = content.split() + n_groups = len(words) / n_words_per_short_text + if n_groups < 1: + continue + groups = np.array_split(words, n_groups) + + for group in groups: + small_content = u" ".join(group) + + short_text_filename = os.path.join(short_text_lang_folder, + '%s_%04d.txt' % (lang, j)) + print("Writing %s" % short_text_filename) + open(short_text_filename, 'wb').write( + small_content.encode('utf-8', 'ignore')) + j += 1 + if j >= 1000: + break + diff --git a/doc/tutorial/text_analytics/data/movie_reviews/fetch_data.py b/doc/tutorial/text_analytics/data/movie_reviews/fetch_data.py new file mode 100644 index 0000000000000..4593108ffc370 --- /dev/null +++ b/doc/tutorial/text_analytics/data/movie_reviews/fetch_data.py @@ -0,0 +1,27 @@ +"""Script to download the movie review dataset""" + +import os +import tarfile +try: + from urllib import urlopen +except ImportError: + from urllib.request import urlopen + + +URL = ("http://www.cs.cornell.edu/people/pabo/" + "movie-review-data/review_polarity.tar.gz") + +ARCHIVE_NAME = URL.rsplit('/', 1)[1] +DATA_FOLDER = "txt_sentoken" + + +if not os.path.exists(DATA_FOLDER): + + if not os.path.exists(ARCHIVE_NAME): + print("Downloading dataset from %s (3 MB)" % URL) + opener = urlopen(URL) + open(ARCHIVE_NAME, 'wb').write(opener.read()) + + print("Decompressing %s" % ARCHIVE_NAME) + tarfile.open(ARCHIVE_NAME, "r:gz").extractall(path='.') + os.remove(ARCHIVE_NAME) diff --git a/doc/tutorial/text_analytics/data/twenty_newsgroups/fetch_data.py b/doc/tutorial/text_analytics/data/twenty_newsgroups/fetch_data.py new file mode 100644 index 0000000000000..45fd38b0cae58 --- /dev/null +++ b/doc/tutorial/text_analytics/data/twenty_newsgroups/fetch_data.py @@ -0,0 +1,29 @@ +"""Script to download the 20 newsgroups text classification set""" + +import os +import tarfile + +try: + from urllib import urlopen +except ImportError: + from urllib.request import urlopen + +URL = ("http://people.csail.mit.edu/jrennie/" + "20Newsgroups/20news-bydate.tar.gz") + +ARCHIVE_NAME = URL.rsplit('/', 1)[1] +TRAIN_FOLDER = "20news-bydate-train" +TEST_FOLDER = "20news-bydate-test" + + +if not os.path.exists(TRAIN_FOLDER) or not os.path.exists(TEST_FOLDER): + + if not os.path.exists(ARCHIVE_NAME): + print("Downloading dataset from %s (14 MB)" % URL) + opener = urlopen(URL) + open(ARCHIVE_NAME, 'wb').write(opener.read()) + + print("Decompressing %s" % ARCHIVE_NAME) + tarfile.open(ARCHIVE_NAME, "r:gz").extractall(path='.') + os.remove(ARCHIVE_NAME) + diff --git a/doc/tutorial/text_analytics/placeholder.txt b/doc/tutorial/text_analytics/placeholder.txt deleted file mode 100644 index 454e154d4fd51..0000000000000 --- a/doc/tutorial/text_analytics/placeholder.txt +++ /dev/null @@ -1 +0,0 @@ -placeholder for ogrisel's tutorial diff --git a/doc/tutorial/text_analytics/skeletons/exercise_01_language_train_model.py b/doc/tutorial/text_analytics/skeletons/exercise_01_language_train_model.py new file mode 100644 index 0000000000000..fe2cde6e3f8fb --- /dev/null +++ b/doc/tutorial/text_analytics/skeletons/exercise_01_language_train_model.py @@ -0,0 +1,62 @@ +"""Build a language detector model + +The goal of this exercise is to train a linear classifier on text features +that represent sequences of up to 3 consecutive characters so as to be +recognize natural languages by using the frequencies of short character +sequences as 'fingerprints'. + +""" +# Author: Olivier Grisel +# License: Simplified BSD + +import sys + +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.linear_model import Perceptron +from sklearn.pipeline import Pipeline +from sklearn.datasets import load_files +from sklearn.cross_validation import train_test_split +from sklearn import metrics + + +# The training data folder must be passed as first argument +languages_data_folder = sys.argv[1] +dataset = load_files(languages_data_folder) + +# Split the dataset in training and test set: +docs_train, docs_test, y_train, y_test = train_test_split( + dataset.data, dataset.target, test_size=0.5) + + +# TASK: Build a an vectorizer that splits strings into sequence of 1 to 3 +# characters instead of word tokens + +# TASK: Build a vectorizer / classifier pipeline using the previous analyzer +# the pipeline instance should stored in a variable named clf + +# TASK: Fit the pipeline on the training set + +# TASK: Predict the outcome on the testing set in a variable named y_predicted + +# Print the classification report +print(metrics.classification_report(y_test, y_predicted, + target_names=dataset.target_names)) + +# Plot the confusion matrix +cm = metrics.confusion_matrix(y_test, y_predicted) +print(cm) + +#import pylab as pl +#pl.matshow(cm, cmap=pl.cm.jet) +#pl.show() + +# Predict the result on some short new sentences: +sentences = [ + u'This is a language detection test.', + u'Ceci est un test de d\xe9tection de la langue.', + u'Dies ist ein Test, um die Sprache zu erkennen.', +] +predicted = clf.predict(sentences) + +for s, p in zip(sentences, predicted): + print(u'The language of "%s" is "%s"' % (s, dataset.target_names[p])) diff --git a/doc/tutorial/text_analytics/skeletons/exercise_02_sentiment.py b/doc/tutorial/text_analytics/skeletons/exercise_02_sentiment.py new file mode 100644 index 0000000000000..bd2b44a506226 --- /dev/null +++ b/doc/tutorial/text_analytics/skeletons/exercise_02_sentiment.py @@ -0,0 +1,63 @@ +"""Build a sentiment analysis / polarity model + +Sentiment analysis can be casted as a binary text classification problem, +that is fitting a linear classifier on features extracted from the text +of the user messages so as to guess wether the opinion of the author is +positive or negative. + +In this examples we will use a movie review dataset. + +""" +# Author: Olivier Grisel +# License: Simplified BSD + +import sys +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.svm import LinearSVC +from sklearn.pipeline import Pipeline +from sklearn.grid_search import GridSearchCV +from sklearn.datasets import load_files +from sklearn.cross_validation import train_test_split +from sklearn import metrics + + +if __name__ == "__main__": + # NOTE: we put the following in a 'if __name__ == "__main__"' protected + # block to be able to use a multi-core grid search that also works under + # Windows, see: http://docs.python.org/library/multiprocessing.html#windows + # The multiprocessing module is used as the backend of joblib.Parallel + # that is used when n_jobs != 1 in GridSearchCV + + # the training data folder must be passed as first argument + movie_reviews_data_folder = sys.argv[1] + dataset = load_files(movie_reviews_data_folder, shuffle=False) + print("n_samples: %d" % len(dataset.data)) + + # split the dataset in training and test set: + docs_train, docs_test, y_train, y_test = train_test_split( + dataset.data, dataset.target, test_size=0.25, random_state=None) + + # TASK: Build a vectorizer / classifier pipeline that filters out tokens + # that are too rare or too frequent + + # TASK: Build a grid search to find out whether unigrams or bigrams are + # more useful. + # Fit the pipeline on the training set using grid search for the parameters + + # TASK: print the cross-validated scores for the each parameters set + # explored by the grid search + + # TASK: Predict the outcome on the testing set and store it in a variable + # named y_predicted + + # Print the classification report + print(metrics.classification_report(y_test, y_predicted, + target_names=dataset.target_names)) + + # Print and plot the confusion matrix + cm = metrics.confusion_matrix(y_test, y_predicted) + print(cm) + + # import matplotlib.pyplot as plt + # plt.matshow(cm) + # plt.show() diff --git a/doc/tutorial/text_analytics/solutions/exercise_01_language_train_model.py b/doc/tutorial/text_analytics/solutions/exercise_01_language_train_model.py new file mode 100644 index 0000000000000..2de33948bec58 --- /dev/null +++ b/doc/tutorial/text_analytics/solutions/exercise_01_language_train_model.py @@ -0,0 +1,70 @@ +"""Build a language detector model + +The goal of this exercise is to train a linear classifier on text features +that represent sequences of up to 3 consecutive characters so as to be +recognize natural languages by using the frequencies of short character +sequences as 'fingerprints'. + +""" +# Author: Olivier Grisel +# License: Simplified BSD + +import sys + +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.linear_model import Perceptron +from sklearn.pipeline import Pipeline +from sklearn.datasets import load_files +from sklearn.cross_validation import train_test_split +from sklearn import metrics + + +# The training data folder must be passed as first argument +languages_data_folder = sys.argv[1] +dataset = load_files(languages_data_folder) + +# Split the dataset in training and test set: +docs_train, docs_test, y_train, y_test = train_test_split( + dataset.data, dataset.target, test_size=0.5) + + +# TASK: Build a an vectorizer that splits strings into sequence of 1 to 3 +# characters instead of word tokens +vectorizer = TfidfVectorizer(ngram_range=(1, 3), analyzer='char', + use_idf=False) + +# TASK: Build a vectorizer / classifier pipeline using the previous analyzer +# the pipeline instance should stored in a variable named clf +clf = Pipeline([ + ('vec', vectorizer), + ('clf', Perceptron()), +]) + +# TASK: Fit the pipeline on the training set +clf.fit(docs_train, y_train) + +# TASK: Predict the outcome on the testing set in a variable named y_predicted +y_predicted = clf.predict(docs_test) + +# Print the classification report +print(metrics.classification_report(y_test, y_predicted, + target_names=dataset.target_names)) + +# Plot the confusion matrix +cm = metrics.confusion_matrix(y_test, y_predicted) +print(cm) + +#import pylab as pl +#pl.matshow(cm, cmap=pl.cm.jet) +#pl.show() + +# Predict the result on some short new sentences: +sentences = [ + u'This is a language detection test.', + u'Ceci est un test de d\xe9tection de la langue.', + u'Dies ist ein Test, um die Sprache zu erkennen.', +] +predicted = clf.predict(sentences) + +for s, p in zip(sentences, predicted): + print(u'The language of "%s" is "%s"' % (s, dataset.target_names[p])) diff --git a/doc/tutorial/text_analytics/solutions/exercise_02_sentiment.py b/doc/tutorial/text_analytics/solutions/exercise_02_sentiment.py new file mode 100644 index 0000000000000..c4dcba5da9f90 --- /dev/null +++ b/doc/tutorial/text_analytics/solutions/exercise_02_sentiment.py @@ -0,0 +1,74 @@ +"""Build a sentiment analysis / polarity model + +Sentiment analysis can be casted as a binary text classification problem, +that is fitting a linear classifier on features extracted from the text +of the user messages so as to guess wether the opinion of the author is +positive or negative. + +In this examples we will use a movie review dataset. + +""" +# Author: Olivier Grisel +# License: Simplified BSD + +import sys +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.svm import LinearSVC +from sklearn.pipeline import Pipeline +from sklearn.grid_search import GridSearchCV +from sklearn.datasets import load_files +from sklearn.cross_validation import train_test_split +from sklearn import metrics + + +if __name__ == "__main__": + # NOTE: we put the following in a 'if __name__ == "__main__"' protected + # block to be able to use a multi-core grid search that also works under + # Windows, see: http://docs.python.org/library/multiprocessing.html#windows + # The multiprocessing module is used as the backend of joblib.Parallel + # that is used when n_jobs != 1 in GridSearchCV + + # the training data folder must be passed as first argument + movie_reviews_data_folder = sys.argv[1] + dataset = load_files(movie_reviews_data_folder, shuffle=False) + print("n_samples: %d" % len(dataset.data)) + + # split the dataset in training and test set: + docs_train, docs_test, y_train, y_test = train_test_split( + dataset.data, dataset.target, test_size=0.25, random_state=None) + + # TASK: Build a vectorizer / classifier pipeline that filters out tokens + # that are too rare or too frequent + pipeline = Pipeline([ + ('vect', TfidfVectorizer(min_df=3, max_df=0.95)), + ('clf', LinearSVC(C=1000)), + ]) + + # TASK: Build a grid search to find out whether unigrams or bigrams are + # more useful. + # Fit the pipeline on the training set using grid search for the parameters + parameters = { + 'vect__ngram_range': [(1, 1), (1, 2)], + } + grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1) + grid_search.fit(docs_train, y_train) + + # TASK: print the cross-validated scores for the each parameters set + # explored by the grid search + print(grid_search.grid_scores_) + + # TASK: Predict the outcome on the testing set and store it in a variable + # named y_predicted + y_predicted = grid_search.predict(docs_test) + + # Print the classification report + print(metrics.classification_report(y_test, y_predicted, + target_names=dataset.target_names)) + + # Print and plot the confusion matrix + cm = metrics.confusion_matrix(y_test, y_predicted) + print(cm) + + # import matplotlib.pyplot as plt + # plt.matshow(cm) + # plt.show() diff --git a/doc/tutorial/text_analytics/solutions/generate_skeletons.py b/doc/tutorial/text_analytics/solutions/generate_skeletons.py new file mode 100644 index 0000000000000..4729b976530c7 --- /dev/null +++ b/doc/tutorial/text_analytics/solutions/generate_skeletons.py @@ -0,0 +1,38 @@ +"""Generate skeletons from the example code""" +import os + +exercise_dir = os.path.dirname(__file__) +if exercise_dir == '': + exercise_dir = '.' + +skeleton_dir = os.path.abspath(os.path.join(exercise_dir, '..', 'skeletons')) +if not os.path.exists(skeleton_dir): + os.makedirs(skeleton_dir) + +solutions = os.listdir(exercise_dir) + +for f in solutions: + if not f.endswith('.py'): + continue + + if f == os.path.basename(__file__): + continue + + print("Generating skeleton for %s" % f) + + input_file = open(os.path.join(exercise_dir, f)) + output_file = open(os.path.join(skeleton_dir, f), 'w') + + in_exercise_region = False + + for line in input_file: + linestrip = line.strip() + if len(linestrip) == 0: + in_exercise_region = False + elif linestrip.startswith('# TASK:'): + in_exercise_region = True + + if not in_exercise_region or linestrip.startswith('#'): + output_file.write(line) + + output_file.close() diff --git a/doc/tutorial/text_analytics/working_with_text_data.rst b/doc/tutorial/text_analytics/working_with_text_data.rst new file mode 100644 index 0000000000000..f842185ddc75a --- /dev/null +++ b/doc/tutorial/text_analytics/working_with_text_data.rst @@ -0,0 +1,565 @@ +.. _text_data_tutorial: + +====================== +Working With Text Data +====================== + +The goal of this guide is to explore some of the main ``scikit-learn`` +tools on a single practical task: analysing a collection of text +documents (newsgroups posts) on twenty different topics. + +In this section we will see how to: + + - load the file contents and the categories + + - extract feature vectors suitable for machine learning + + - train a linear model to perform categorization + + - use a grid search strategy to find a good configuration of both + the feature extraction components and the classifier + + + +Tutorial setup +-------------- + +To get started with this tutorial, you firstly must have the +*scikit-learn* and all of its required dependencies installed. + +Please refer to the :ref:`installation instructions ` +page for more information and for per-system instructions. + +The source of this tutorial can be found within your +scikit-learn folder:: + + scikit-learn/doc/tutorial/text_analytics/ + +The tutorial folder, should contain the following folders: + + * ``*.rst files`` - the source of the tutorial document written with sphinx + + * ``data`` - folder to put the datasets used during the tutorial + + * ``skeletons`` - sample incomplete scripts for the exercises + + * ``solutions`` - solutions of the exercises + + +You can already copy the skeletons into a new folder somewhere +on your hard-drive named ``sklearn_tut_workspace`` where you +will edit your own files for the exercises while keeping +the original skeletons intact:: + + % cp -r skeletons work_directory/sklearn_tut_workspace + +Machine Learning algorithms need data. Go to each ``$TUTORIAL_HOME/data`` +sub-folder and run the ``fetch_data.py`` script from there (after +having read them first). + +For instance:: + + % cd $TUTORIAL_HOME/data/languages + % less fetch_data.py + % python fetch_data.py + + +Loading the 20 newsgroups dataset +--------------------------------- + +The dataset is called "Twenty Newsgroups". Here is the official +description, quoted from the `website +`_: + + The 20 Newsgroups data set is a collection of approximately 20,000 + newsgroup documents, partitioned (nearly) evenly across 20 different + newsgroups. To the best of our knowledge, it was originally collected + by Ken Lang, probably for his paper "Newsweeder: Learning to filter + netnews," though he does not explicitly mention this collection. + The 20 newsgroups collection has become a popular data set for + experiments in text applications of machine learning techniques, + such as text classification and text clustering. + +In the following we will use the built-in dataset loader for 20 newsgroups +from scikit-learn. Alternatively, it is possible to download the dataset +manually from the web-site and use the :func:`sklearn.datasets.load_files` +function by pointing it to the ``20news-bydate-train`` subfolder of the +uncompressed archive folder. + +In order to get faster execution times for this first example we will +work on a partial dataset with only 4 categories out of the 20 available +in the dataset:: + + >>> categories = ['alt.atheism', 'soc.religion.christian', + ... 'comp.graphics', 'sci.med'] + +We can now load the list of files matching those categories as follows:: + + >>> from sklearn.datasets import fetch_20newsgroups + >>> twenty_train = fetch_20newsgroups(subset='train', + ... categories=categories, shuffle=True, random_state=42) + +The returned dataset is a ``scikit-learn`` "bunch": a simple holder +object with fields that can be both accessed as python ``dict`` +keys or ``object`` attributes for convenience, for instance the +``target_names`` holds the list of the requested category names:: + + >>> twenty_train.target_names + ['alt.atheism', 'comp.graphics', 'sci.med', 'soc.religion.christian'] + +The files themselves are loaded in memory in the ``data`` attribute. For +reference the filenames are also available:: + + >>> len(twenty_train.data) + 2257 + >>> len(twenty_train.filenames) + 2257 + +Let's print the first lines of the first loaded file:: + + >>> print("\n".join(twenty_train.data[0].split("\n")[:3])) + From: sd345@city.ac.uk (Michael Collier) + Subject: Converting images to HP LaserJet III? + Nntp-Posting-Host: hampton + + >>> print(twenty_train.target_names[twenty_train.target[0]]) + comp.graphics + +Supervised learning algorithms will require a category label for each +document in the training set. In this case the category is the name of the +newsgroup which also happens to be the name of the folder holding the +individual documents. + +For speed and space efficiency reasons ``scikit-learn`` loads the +target attribute as an array of integers that corresponds to the +index of the category name in the ``target_names`` list. The category +integer id of each sample is stored in the ``target`` attribute:: + + >>> twenty_train.target[:10] + array([1, 1, 3, 3, 3, 3, 3, 2, 2, 2]) + +It is possible to get back the category names as follows:: + + >>> for t in twenty_train.target[:10]: + ... print(twenty_train.target_names[t]) + ... + comp.graphics + comp.graphics + soc.religion.christian + soc.religion.christian + soc.religion.christian + soc.religion.christian + soc.religion.christian + sci.med + sci.med + sci.med + +You can notice that the samples have been shuffled randomly (with +a fixed RNG seed): this is useful if you select only the first +samples to quickly train a model and get a first idea of the results +before re-training on the complete dataset later. + + +Extracting features from text files +----------------------------------- + +In order to perform machine learning on text documents, we first need to +turn the text content into numerical feature vectors. + +.. currentmodule:: sklearn.feature_extraction.text + + +Bags of words +~~~~~~~~~~~~~ + +The most intuitive way to do so is the bags of words representation: + + 1. assign a fixed integer id to each word occurring in any document + of the training set (for instance by building a dictionary + from words to integer indices). + + 2. for each document ``#i``, count the number of occurrences of each + word ``w`` and store it in ``X[i, j]`` as the value of feature + ``#j`` where ``j`` is the index of word ``w`` in the dictionary + +The bags of words representation implies that ``n_features`` is +the number of distinct words in the corpus: this number is typically +larger that 100,000. + +If ``n_samples == 10000``, storing ``X`` as a numpy array of type +float32 would require 10000 x 100000 x 4 bytes = **4GB in RAM** which +is barely manageable on today's computers. + +Fortunately, **most values in X will be zeros** since for a given +document less than a couple thousands of distinct words will be +used. For this reason we say that bags of words are typically +**high-dimensional sparse datasets**. We can save a lot of memory by +only storing the non-zero parts of the feature vectors in memory. + +``scipy.sparse`` matrices are data structures that do exactly this, +and ``scikit-learn`` has built-in support for these structures. + + +Tokenizing text with ``scikit-learn`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Text preprocessing, tokenizing and filtering of stopwords are included in a high level component that is able to build a +dictionary of features and transform documents to feature vectors:: + + >>> from sklearn.feature_extraction.text import CountVectorizer + >>> count_vect = CountVectorizer() + >>> X_train_counts = count_vect.fit_transform(twenty_train.data) + >>> X_train_counts.shape + (2257, 35788) + +:class:`CountVectorizer` supports counts of N-grams of words or consequective characters. +Once fitted, the vectorizer has built a dictionary of feature indices:: + + >>> count_vect.vocabulary_.get(u'algorithm') + 4690 + +The index value of a word in the vocabulary is linked to its frequency +in the whole training corpus. + +.. note: + + The method ``count_vect.fit_transform`` performs two actions: + it learns the vocabulary and transforms the documents into count vectors. + It's possible to separate these steps by calling + ``count_vect.fit(twenty_train.data)`` followed by + ``X_train_counts = count_vect.transform(twenty_train.data)``, + but doing so would tokenize and vectorize each text file twice. + + +From occurrences to frequencies +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Occurrence count is a good start but there is an issue: longer +documents will have higher average count values than shorter documents, +even though they might talk about the same topics. + +To avoid these potential discrepancies it suffices to divide the +number of occurrences of each word in a document by the total number +of words in the document: these new features are called ``tf`` for Term +Frequencies. + +Another refinement on top of tf is to downscale weights for words +that occur in many documents in the corpus and are therefore less +informative than those that occur only in a smaller portion of the +corpus. + +This downscaling is called `tf–idf`_ for "Term Frequency times +Inverse Document Frequency". + +.. _`tf–idf`: http://en.wikipedia.org/wiki/Tf–idf + + +Both **tf** and **tf–idf** can be computed as follows:: + + >>> from sklearn.feature_extraction.text import TfidfTransformer + >>> tf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts) + >>> X_train_tf = tf_transformer.transform(X_train_counts) + >>> X_train_tf.shape + (2257, 35788) + +In the above example-code, we firstly use the ``fit(..)`` method to fit our +estimator to the data and secondly the ``transform(..)`` method to transform +our count-matrix to a tf-idf representation. +These two steps can be combined to achieve the same end result faster +by skipping redundant processing. This is done through using the +``fit_transform(..)`` method as shown below, and as mentioned in the note +in the previous section:: + + >>> tfidf_transformer = TfidfTransformer() + >>> X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) + >>> X_train_tfidf.shape + (2257, 35788) + + +Training a classifier +--------------------- + +Now that we have our features, we can train a classifier to try to predict +the category of a post. Let's start with a :ref:`naïve Bayes ` +classifier, which +provides a nice baseline for this task. ``scikit-learn`` includes several +variants of this classifier; the one most suitable for word counts is the +multinomial variant:: + + >>> from sklearn.naive_bayes import MultinomialNB + >>> clf = MultinomialNB().fit(X_train_tfidf, twenty_train.target) + +To try to predict the outcome on a new document we need to extract +the features using almost the same feature extracting chain as before. +The difference is that we call ``transform`` instead of ``fit_transform`` +on the transformers, since they have already been fit to the training set:: + + >>> docs_new = ['God is love', 'OpenGL on the GPU is fast'] + >>> X_new_counts = count_vect.transform(docs_new) + >>> X_new_tfidf = tfidf_transformer.transform(X_new_counts) + + >>> predicted = clf.predict(X_new_tfidf) + + >>> for doc, category in zip(docs_new, predicted): + ... print('%r => %s' % (doc, twenty_train.target_names[category])) + ... + 'God is love' => soc.religion.christian + 'OpenGL on the GPU is fast' => comp.graphics + + +Building a pipeline +------------------- + +In order to make the vectorizer => transformer => classifier easier +to work with, ``scikit-learn`` provides a ``Pipeline`` class that behaves +like a compound classifier:: + + >>> from sklearn.pipeline import Pipeline + >>> text_clf = Pipeline([('vect', CountVectorizer()), + ... ('tfidf', TfidfTransformer()), + ... ('clf', MultinomialNB()), + ... ]) + +The names ``vect``, ``tfidf`` and ``clf`` (classifier) are arbitrary. +We shall see their use in the section on grid search, below. +We can now train the model with a single command:: + + >>> text_clf = text_clf.fit(twenty_train.data, twenty_train.target) + + +Evaluation of the performance on the test set +--------------------------------------------- + +Evaluating the predictive accuracy of the model is equally easy:: + + >>> import numpy as np + >>> twenty_test = fetch_20newsgroups(subset='test', + ... categories=categories, shuffle=True, random_state=42) + >>> docs_test = twenty_test.data + >>> predicted = text_clf.predict(docs_test) + >>> np.mean(predicted == twenty_test.target) # doctest: +ELLIPSIS + 0.834... + +I.e., we achieved 83.4% accuracy. Let's see if we can do better with a +linear :ref:`support vector machine (SVM) `, +which is widely regarded as one of +the best text classification algorithms (although it's also a bit slower +than naïve Bayes). We can change the learner by just plugging a different +classifier object into our pipeline:: + + >>> from sklearn.linear_model import SGDClassifier + >>> text_clf = Pipeline([('vect', CountVectorizer()), + ... ('tfidf', TfidfTransformer()), + ... ('clf', SGDClassifier(loss='hinge', penalty='l2', + ... alpha=1e-3, n_iter=5, random_state=42)), + ... ]) + >>> _ = text_clf.fit(twenty_train.data, twenty_train.target) + >>> predicted = text_clf.predict(docs_test) + >>> np.mean(predicted == twenty_test.target) # doctest: +ELLIPSIS + 0.912... + +``scikit-learn`` further provides utilities for more detailed performance +analysis of the results:: + + >>> from sklearn import metrics + >>> print(metrics.classification_report(twenty_test.target, predicted, + ... target_names=twenty_test.target_names)) + ... # doctest: +NORMALIZE_WHITESPACE + precision recall f1-score support + + alt.atheism 0.95 0.81 0.87 319 + comp.graphics 0.88 0.97 0.92 389 + sci.med 0.94 0.90 0.92 396 + soc.religion.christian 0.90 0.95 0.93 398 + + avg / total 0.92 0.91 0.91 1502 + + + >>> metrics.confusion_matrix(twenty_test.target, predicted) + array([[258, 11, 15, 35], + [ 4, 379, 3, 3], + [ 5, 33, 355, 3], + [ 5, 10, 4, 379]]) + + +As expected the confusion matrix shows that posts from the newsgroups +on atheism and christian are more often confused for one another than +with computer graphics. + +.. note: + + SGD stands for Stochastic Gradient Descent. This is a simple + optimization algorithms that is known to be scalable when the dataset + has many samples. + + By setting ``loss="hinge"`` and ``penalty="l2"`` we are configuring + the classifier model to tune it's parameters for the linear Support + Vector Machine cost function. + + Alternatively we could have used ``sklearn.svm.LinearSVC`` (Linear + Support Vector Machine Classifier) that provides an alternative + optimizer for the same cost function based on the liblinear_ C++ + library. + +.. _liblinear: http://www.csie.ntu.edu.tw/~cjlin/liblinear/ + + +Parameter tuning using grid search +---------------------------------- + +We've already encountered some parameters such as ``use_idf`` in the +``TfidfTransformer``. Classifiers tend to have many parameters as well; +e.g., ``MultinomialNB`` includes a smoothing parameter ``alpha`` and +``SGDClassifier`` has a penalty parameter ``alpha`` and configurable loss +and penalty terms in the objective function (see the module documentation, +or use the Python ``help`` function, to get a description of these). + +Instead of tweaking the parameters of the various components of the +chain, it is possible to run an exhaustive search of the best +parameters on a grid of possible values. We try out all classifiers +on either words or bigrams, with or without idf, and with a penalty +parameter of either 0.01 or 0.001 for the linear SVM:: + + >>> from sklearn.grid_search import GridSearchCV + >>> parameters = {'vect__ngram_range': [(1, 1), (1, 2)], + ... 'tfidf__use_idf': (True, False), + ... 'clf__alpha': (1e-2, 1e-3), + ... } + +Obviously, such an exhaustive search can be expensive. If we have multiple +CPU cores at our disposal, we can tell the grid searcher to try these eight +parameter combinations in parallel with the ``n_jobs`` parameter. If we give +this parameter a value of ``-1``, grid search will detect how many cores +are installed and uses them all:: + + >>> gs_clf = GridSearchCV(text_clf, parameters, n_jobs=-1) + +The grid search instance behaves like a normal ``scikit-learn`` +model. Let's perform the search on a smaller subset of the training data +to speed up the computation:: + + >>> gs_clf = gs_clf.fit(twenty_train.data[:400], twenty_train.target[:400]) + +The result of calling ``fit`` on a ``GridSearchCV`` object is a classifier +that we can use to ``predict``:: + + >>> twenty_train.target_names[gs_clf.predict(['God is love'])] + 'soc.religion.christian' + +but otherwise, it's a pretty large and clumsy object. We can, however, get the +optimal parameters out by inspecting the object's ``grid_scores_`` attribute, +which is a list of parameters/score pairs. To get the best scoring attributes, +we can do:: + + >>> best_parameters, score, _ = max(gs_clf.grid_scores_, key=lambda x: x[1]) + >>> for param_name in sorted(parameters.keys()): + ... print("%s: %r" % (param_name, best_parameters[param_name])) + ... + clf__alpha: 0.001 + tfidf__use_idf: True + vect__ngram_range: (1, 1) + + >>> score # doctest: +ELLIPSIS + 0.900... + +.. note: + + A ``GridSearchCV`` object also stores the best classifier that it trained + as its ``best_estimator_`` attribute. In this case, that isn't much use as + we trained on a small, 400-document subset of our full training set. + + +Exercises +~~~~~~~~~ + +To do the exercises, copy the content of the 'skeletons' folder as +a new folder named 'workspace':: + + % cp -r skeletons workspace + +You can then edit the content of the workspace without fear of loosing +the original exercise instructions. + +Then fire an ipython shell and run the work-in-progress script with:: + + [1] %run workspace/exercise_XX_script.py arg1 arg2 arg3 + +If an exception is triggered, use ``%debug`` to fire-up a post +mortem ipdb session. + +Refine the implementation and iterate until the exercise is solved. + +**For each exercise, the skeleton file provides all the necessary import +statements, boilerplate code to load the data and sample code to evaluate +the predictive accurracy of the model.** + + +Exercise 1: Language identification +----------------------------------- + +- Write a text classification pipeline using a custom preprocessor and + ``CharNGramAnalyzer`` using data from Wikipedia articles as training set. + +- Evaluate the performance on some held out test set. + +ipython command line:: + + %run workspace/exercise_01_language_train_model.py data/languages/paragraphs/ + + +Exercise 2: Sentiment Analysis on movie reviews +----------------------------------------------- + +- Write a text classification pipeline to classify movie reviews as either + positive or negative. + +- Find a good set of parameters using grid search. + +- Evaluate the performance on a held out test set. + +ipython command line:: + + %run workspace/exercise_02_sentiment.py data/movie_reviews/txt_sentoken/ + + +Exercise 3: CLI text classification utility +------------------------------------------- + +Using the results of the previous exercises and the ``cPickle`` +module of the standard library, write a command line utility that +detects the language of some text provided on ``stdin`` and estimate +the polarity (positive or negative) if the text is written in +English. + +Bonus point if the utility is able to give a confidence level for its +predictions. + + +Where to from here +------------------ + +Here are a few suggestions to help further your scikit-learn intuition +upon the completion of this tutorial: + + +* Try playing around with the ``analyzer`` and ``token normalisation`` under + :class:`CountVectorizer` + +* If you don't have labels, try using + :ref:`Clustering ` + on your problem. + +* If you have multiple labels per document, e.g categories, have a look + at the :ref:`Multiclass and multilabel section ` + +* Try using :ref:`Truncated SVD ` for + `latent semantic analysis `_. + +* Have a look at using + :ref:`Out-of-core Classification + ` to + learn from data that would not fit into the computer main memory. + +* Have a look at the :ref:`Hashing Vectorizer ` + as a memory efficient alternative to :class:`CountVectorizer`. + diff --git a/doc/tutorial/text_analytics/working_with_text_data_fixture.py b/doc/tutorial/text_analytics/working_with_text_data_fixture.py new file mode 100644 index 0000000000000..c10f5c4f4d142 --- /dev/null +++ b/doc/tutorial/text_analytics/working_with_text_data_fixture.py @@ -0,0 +1,15 @@ +"""Fixture module to skip the datasets loading when offline + +The 20 newsgroups data is rather large and some CI workers such as travis are +stateless hence will not cache the dataset as regular sklearn users would do. + +The following will skip the execution of the working_with_text_data.rst doctests +if the proper environment variable is configured (see the source code of +check_skip_network for more details). + +""" +from sklearn.utils.testing import check_skip_network + + +def setup_module(): + check_skip_network() diff --git a/doc/unsupervised_learning.rst b/doc/unsupervised_learning.rst index cbdd172bd3552..c5a986d8cf295 100644 --- a/doc/unsupervised_learning.rst +++ b/doc/unsupervised_learning.rst @@ -10,9 +10,9 @@ Unsupervised learning modules/mixture modules/manifold modules/clustering + modules/biclustering modules/decomposition modules/covariance modules/outlier_detection - modules/hmm - - + modules/density + modules/neural_networks diff --git a/doc/user_guide.rst b/doc/user_guide.rst index 668a00d8b7093..83f749c1981b1 100644 --- a/doc/user_guide.rst +++ b/doc/user_guide.rst @@ -4,22 +4,21 @@ We are putting the title as a raw HTML so that it doesn't appear in the contents -.. raw:: html +.. _user_guide: -

User guide: contents

+.. include:: includes/big_toc_css.rst -.. _user_guide: +.. nice layout in the toc -.. include:: includes/bigger_toc_css.rst +.. include:: tune_toc.rst .. toctree:: :numbered: - install - tutorial/index.rst supervised_learning.rst unsupervised_learning.rst model_selection.rst data_transforms.rst Dataset loading utilities - Reference + modules/scaling_strategies.rst + modules/computational_performance.rst diff --git a/doc/whats_new.rst b/doc/whats_new.rst index 2f20068018d28..95e6b16e6355f 100644 --- a/doc/whats_new.rst +++ b/doc/whats_new.rst @@ -1,36 +1,1880 @@ .. currentmodule:: sklearn +.. _changes_0_17: + + +0.17 +==== + + +Changelog +--------- + +New features +............ + +Enhancements +............ + + - :class:`naive_bayes.GaussianNB` now supports fitting with ``sample_weights``. + By `Jan Hendrik Metzen`_. + +Bug fixes +......... + +API changes summary +------------------- + +.. _changes_0_16: + +0.16 +==== + + +Changelog +--------- + +New features +............ + + - The new :class:`neighbors.LSHForest` implements locality-sensitive hashing + for approximate nearest neighbors search. By `Maheshakya Wijewardena`_. + + - Added :class:`svm.LinearSVR`. This class uses the liblinear implementation + of Support Vector Regression which is much faster for large + sample sizes than :class:`svm.SVR` with linear kernel. By + `Fabian Pedregosa`_ and Qiang Luo. + + - Incremental fit for :class:`GaussianNB `. + + - Added ``sample_weight`` support to :class:`dummy.DummyClassifier` and + :class:`dummy.DummyRegressor`. By `Arnaud Joly`_. + + - Added the :func:`metrics.label_ranking_average_precision_score` metrics. + By `Arnaud Joly`_. + + - Add the :func:`metrics.coverage_error` metrics. By `Arnaud Joly`_. + + - Added :class:`linear_model.LogisticRegressionCV`. By + `Manoj Kumar`_, `Fabian Pedregosa`_, `Gael Varoquaux`_ + and `Alexandre Gramfort`_. + + - Added ``warm_start`` constructor parameter to make it possible for any + trained forest model to grow additional trees incrementally. By + `Laurent Direr`_. + + - Added ``sample_weight`` support to :class:`ensemble.GradientBoostingClassifier` and + :class:`ensemble.GradientBoostingRegressor`. By `Peter Prettenhofer`_. + + - Added :class:`decomposition.IncrementalPCA`, an implementation of the PCA + algorithm that supports out-of-core learning with a ``partial_fit`` + method. By `Kyle Kastner`_. + + - Averaged SGD for :class:`SGDClassifier ` + and :class:`SGDRegressor ` By + `Danny Sullivan`_. + + - Added :func:`cross_val_predict ` + function which computes cross-validated estimates. By `Luis Pedro Coelho`_ + + - Added :class:`linear_model.TheilSenRegressor`, a robust + generalized-median-based estimator. By `Florian Wilhelm`_. + + - Added :func:`metrics.median_absolute_error`, a robust metric. + By `Gael Varoquaux`_ and `Florian Wilhelm`_. + + - Add :class:`cluster.Birch`, an online clustering algorithm. By + `Manoj Kumar`_, `Alexandre Gramfort`_ and `Joel Nothman`_. + + - Added shrinkage support to :class:`lda.LDA` using two new solvers. By + `Clemens Brunner`_ and `Martin Billinger`_. + + - Added :class:`kernel_ridge.KernelRidge`, an implementation of + kernelized ridge regression. + By `Mathieu Blondel`_ and `Jan Hendrik Metzen`_. + + - All solvers in :class:`linear_model.Ridge` now support `sample_weight`. + By `Mathieu Blondel`_. + + - Added :class:`cross_validation.PredefinedSplit` cross-validation + for fixed user-provided cross-validation folds. + By `untom `_. + + - Added :class:`calibration.CalibratedClassifierCV`, an approach for + calibrating the predicted probabilities of a classifier. + By `Alexandre Gramfort`_, `Jan Hendrik Metzen`_, `Mathieu Blondel`_ + and `Balazs Kegl`_. + + +Enhancements +............ + + - Add option ``return_distance`` in :func:`hierarchical.ward_tree` + to return distances between nodes for both structured and unstructured + versions of the algorithm. By `Matteo Visconti di Oleggio Castello`_. + The same option was added in :func:`hierarchical.linkage_tree`. + By `Manoj Kumar`_ + + - Add support for sample weights in scorer objects. Metrics with sample + weight support will automatically benefit from it. By `Noel Dawe`_ and + `Vlad Niculae`_. + + - Added ``newton-cg`` and `lbfgs` solver support in + :class:`linear_model.LogisticRegression`. By `Manoj Kumar`_. + + - Add ``selection="random"`` parameter to implement stochastic coordinate + descent for :class:`linear_model.Lasso`, :class:`linear_model.ElasticNet` + and related. By `Manoj Kumar`_. + + - Add ``sample_weight`` parameter to + :func:`metrics.jaccard_similarity_score` and :func:`metrics.log_loss`. + By `Jatin Shah`_. + + - Support sparse multilabel indicator representation in + :class:`preprocessing.LabelBinarizer` and + :class:`multiclass.OneVsRestClassifier` (by `Hamzeh Alsalhi`_ with thanks + to Rohit Sivaprasad), as well as evaluation metrics (by + `Joel Nothman`_). + + - Add ``sample_weight`` parameter to `metrics.jaccard_similarity_score`. + By `Jatin Shah`. + + - Add support for multiclass in `metrics.hinge_loss`. Added ``labels=None`` + as optional paramter. By `Saurabh Jha`. + + - Add ``sample_weight`` parameter to `metrics.hinge_loss`. + By `Saurabh Jha`. + + - Add ``multi_class="multinomial"`` option in + :class:`linear_model.LogisticRegression` to implement a Logistic + Regression solver that minimizes the cross-entropy or multinomial loss + instead of the default One-vs-Rest setting. Supports `lbfgs` and + `newton-cg` solvers. By `Lars Buitinck`_ and `Manoj Kumar`_. Solver option + `newton-cg` by Simon Wu. + + - ``DictVectorizer`` can now perform ``fit_transform`` on an iterable in a + single pass, when giving the option ``sort=False``. By `Dan Blanchard`_. + + - :class:`GridSearchCV` and :class:`RandomizedSearchCV` can now be + configured to work with estimators that may fail and raise errors on + individual folds. This option is controlled by the `error_score` + parameter. This does not affect errors raised on re-fit. By + `Michal Romaniuk`_. + + - Add ``digits`` parameter to `metrics.classification_report` to allow + report to show different precision of floating point numbers. By + `Ian Gilmore`_. + + - Add a quantile prediction strategy to the :class:`dummy.DummyRegressor`. + By `Aaron Staple`_. + + - Add ``handle_unknown`` option to :class:`preprocessing.OneHotEncoder` to + handle unknown categorical features more gracefully during transform. + By `Manoj Kumar`_. + + - Added support for sparse input data to decision trees and their ensembles. + By `Fares Hedyati`_ and `Arnaud Joly`_. + + - Optimized :class:`cluster.AffinityPropagation` by reducing the number of + memory allocations of large temporary data-structures. By `Antony Lee`_. + + - Parellization of the computation of feature importances in random forest. + By `Olivier Grisel`_ and `Arnaud Joly`_. + + - Add ``n_iter_`` attribute to estimators that accept a ``max_iter`` attribute + in their constructor. By `Manoj Kumar`_. + + - Added decision function for :class:`multiclass.OneVsOneClassifier` + By `Raghav R V`_ and `Kyle Beauchamp`_. + + - :func:`neighbors.kneighbors_graph` and :func:`radius_neighbors_graph` + support non-Euclidean metrics. By `Manoj Kumar`_ + + - Parameter ``connectivity`` in :class:`cluster.AgglomerativeClustering` + and family now accept callables that return a connectivity matrix. + By `Manoj Kumar`_. + + - Sparse support for :func:`paired_distances`. By `Joel Nothman`_. + + - DBSCAN now supports sparse input and sample weights, and should be + faster in general. By `Joel Nothman`_. + + - Add ``class_weight`` parameter to automatically weight samples by class + frequency for :class:`ensemble.RandomForestClassifier`, + :class:`tree.DecisionTreeClassifier`, :class:`ensemble.ExtraTreesClassifier` + and :class:`tree.ExtraTreeClassifier`. By `Trevor Stephens`_. + + - :class:`grid_search.RandomizedSearchCV` now does sampling without + replacement if all parameters are given as lists. By `Andreas Müller`_. + + - Parallelized calculation of :func:`pairwise_distances` is now supported + for scipy metrics and custom callables. By `Joel Nothman`_. + + - Allow the fitting and scoring of all clustering algorithms in + :class:`pipeline.Pipeline`. By `Andreas Müller`_. + + - More robust seeding and improved error messages in :class:`cluster.MeanShift` + by `Andreas Müller`_. + + - Make the stopping criterion for :class:`mixture.GMM`, + :class:`mixture.DPGMM` and :class:`mixture.VBGMM` less dependent on the + number of samples by thresholding the average log-likelihood change + instead of its sum over all samples. By `Hervé Bredin`_. + + - The outcome of :func:`manifold.spectral_embedding` was made deterministic + by flipping the sign of eigen vectors. By `Hasil Sharma`_. + + +Documentation improvements +.......................... + + - Added example of using :class:`FeatureUnion` for heterogeneous input. + By `Matt Terry`_ + + - Documentation on scorers was improved, to highlight the handling of loss + functions. By `Matt Pico`_. + + - A discrepancy between liblinear output and scikit-learn's wrappers + is now noted. By `Manoj Kumar`_. + + - Improved documentation generation: examples referring to a class or + function are now shown in a gallery on the class/function's API reference + page. By `Joel Nothman`_. + + - More explicit documentation of sample generators and of data + transformation. By `Joel Nothman`_. + + - :class:`sklearn.neighbors.BallTree` and :class:`sklearn.neighbors.KDTree` + used to point to empty pages stating that they are aliases of BinaryTree. + This has been fixed to show the correct class docs. By `Manoj Kumar`_. + + - Added silhouette plots for analysis of KMeans clustering using + :func:`metrics.silhouette_samples` and :func:`metrics.silhouette_score`. + See :ref:`examples_cluster_plot_kmeans_silhouette_analysis.py` + +Bug fixes +......... + - Metaestimators now support ducktyping for the presence of ``decision_function``, + ``predict_proba`` and other methods. This fixes behavior of + :class:`grid_search.GridSearchCV`, + :class:`grid_search.RandomizedSearchCV`, :class:`pipeline.Pipeline`, + :class:`feature_selection.RFE`, :class:`feature_selection.RFECV` when nested. + By `Joel Nothman`_ + + - The ``scoring`` attribute of grid-search and cross-validation methods is no longer + ignored when a :class:`grid_search.GridSearchCV` is given as a base estimator or + the base estimator doesn't have predict. + + - The function :func:`hierarchical.ward_tree` now returns the children in + the same order for both the structured and unstructured versions. By + `Matteo Visconti di Oleggio Castello`_. + + - :class:`feature_selection.RFECV` now correctly handles cases when + ``step`` is not equal to 1. By `Nikolay Mayorov`_ + + - The :class:`decomposition.PCA` now undoes whitening in its + ``inverse_transform``. Also, its ``components_`` now always have unit + length. By Michael Eickenberg. + + - Fix incomplete download of the dataset when + :func:`datasets.download_20newsgroups` is called. By `Manoj Kumar`_. + + - Various fixes to the Gaussian processes subpackage by Vincent Dubourg + and Jan Hendrik Metzen. + + - Calling ``partial_fit`` with ``class_weight=='auto'`` throws an + appropriate error message and suggests a work around. + By `Danny Sullivan`_. + + - :class:`RBFSampler ` with ``gamma=g`` + formerly approximated :func:`rbf_kernel ` + with ``gamma=g/2.``; the definition of ``gamma`` is now consistent, + which may substantially change your results if you use a fixed value. + (If you cross-validated over ``gamma``, it probably doesn't matter + too much.) By `Dougal Sutherland`_. + + - Pipeline object delegate the ``classes_`` attribute to the underlying + estimator. It allows for instance to make bagging of a pipeline object. + By `Arnaud Joly`_ + + - :class:`neighbors.NearestCentroid` now uses the median as the centroid + when metric is set to ``manhattan``. It was using the mean before. + By `Manoj Kumar`_ + + - Fix numerical stability issues in :class:`linear_model.SGDClassifier` + and :class:`linear_model.SGDRegressor` by clipping large gradients and + ensuring that weight decay rescaling is always positive (for large + l2 regularization and large learning rate values). + By `Olivier Grisel`_ + + - When `compute_full_tree` is set to "auto", the full tree is + built when n_clusters is high and is early stopped when n_clusters is + low, while the behavior should be vice-versa in + :class:`cluster.AgglomerativeClustering` (and friends). + This has been fixed By `Manoj Kumar`_ + + - Fix lazy centering of data in :func:`linear_model.enet_path` and + :func:`linear_model.lasso_path`. It was centered around one. It has + been changed to be centered around the origin. By `Manoj Kumar`_ + + - Fix handling of precomputed affinity matrices in + :class:`cluster.AgglomerativeClustering` when using connectivity + constraints. By `Cathy Deng`_ + + - Correct ``partial_fit`` handling of ``class_prior`` for + :class:`sklearn.naive_bayes.MultinomialNB` and + :class:`sklearn.naive_bayes.BernoulliNB`. By `Trevor Stephens`_. + + - Fixed a crash in :func:`metrics.precision_recall_fscore_support` + when using unsorted ``labels`` in the multi-label setting. + By `Andreas Müller`_. + + - Avoid skipping the first nearest neighbor in the methods ``radius_neighbors``, + ``kneighbors``, ``kneighbors_graph`` and ``radius_neighbors_graph`` in + :class:`sklearn.neighbors.NearestNeighbors` and family, when the query + data is not the same as fit data. By `Manoj Kumar`_. + + - Fix log-density calculation in the :class:`mixture.GMM` with + tied covariance. By `Will Dawson`_ + + - Fixed a scaling error in :class:`feature_selection.SelectFdr` + where a factor ``n_features`` was missing. By `Andrew Tulloch`_ + + - Fix zero division in :class:`neighbors.KNeighborsRegressor` and related + classes when using distance weighting and having identical data points. + By `Garret-R `_. + + - Fixed round off errors with non positive-definite covariance matrices + in GMM. By `Alexis Mignon`_. + + - Fixed a error in the computation of conditional probabilities in + :class:`naive_bayes.BernoulliNB`. By `Hanna Wallach`_. + + - Make the method ``radius_neighbors`` of + :class:`neighbors.NearestNeighbors` return the samples lying on the + boundary for ``algorithm='brute'``. By `Yan Yi`_. + + - Flip sign of ``dual_coef_`` of :class:`svm.SVC` + to make it consistent with the documentation and + ``decision_function``. By Artem Sobolev. + + - Fixed handling of ties in :class:`isotonic.IsotonicRegression`. + We now use the weighted average of targets (secondary method). By + `Andreas Müller`_ and `Michael Bommarito `_. + +API changes summary +------------------- + + - :class:`GridSearchCV ` and + :func:`cross_val_score ` and other + meta-estimators don't convert pandas DataFrames into arrays any more, + allowing DataFrame specific operations in custom estimators. + + - :func:`multiclass.fit_ovr`, :func:`multiclass.predict_ovr`, + :func:`predict_proba_ovr`, + :func:`multiclass.fit_ovo`, :func:`multiclass.predict_ovo`, + :func:`multiclass.fit_ecoc` and :func:`multiclass.predict_ecoc` + are deprecated. Use the underlying estimators instead. + + - Nearest neighbors estimators used to take arbitrary keyword arguments + and pass these to their distance metric. This will no longer be supported + in scikit-learn 0.18; use the ``metric_params`` argument instead. + + - `n_jobs` parameter of the fit method shifted to the constructor of the + LinearRegression class. + + - The ``predict_proba`` method of :class:`multiclass.OneVsRestClassifier` + now returns two probabilities per sample in the multiclass case; this + is consistent with other estimators and with the method's documentation, + but previous versions accidentally returned only the positive + probability. Fixed by Will Lamond and `Lars Buitinck`_. + + - Change default value of precompute in :class:`ElasticNet` and :class:`Lasso` + to False. Setting precompute to "auto" was found to be slower when + n_samples > n_features since the computation of the Gram matrix is + computationally expensive and outweighs the benefit of fitting the Gram + for just one alpha. + ``precompute="auto"`` is now deprecated and will be removed in 0.18 + By `Manoj Kumar`_. + + - Expose ``positive`` option in :func:`linear_model.enet_path` and + :func:`linear_model.enet_path` which constrains coefficients to be + positive. By `Manoj Kumar`_. + + - Users should now supply an explicit ``average`` parameter to + :func:`sklearn.metrics.f1_score`, :func:`sklearn.metrics.fbeta_score`, + :func:`sklearn.metrics.recall_score` and + :func:`sklearn.metrics.precision_score` when performing multiclass + or multilabel (i.e. not binary) classification. By `Joel Nothman`_. + + - `scoring` parameter for cross validation now accepts `'f1_micro'`, + `'f1_macro'` or `'f1_weighted'`. `'f1'` is now for binary classification + only. Similar changes apply to `'precision'` and `'recall'`. + By `Joel Nothman`_. + + - The ``fit_intercept``, ``normalize`` and ``return_models`` parameters in + :func:`linear_model.enet_path` and :func:`linear_model.lasso_path` have + been removed. They were deprecated since 0.14 + + - From now onwards, all estimators will uniformly raise ``NotFittedError`` + (:class:`utils.validation.NotFittedError`), when any of the ``predict`` + like methods are called before the model is fit. By `Raghav R V`_. + + - Input data validation was refactored for more consistent input + validation. The ``check_arrays`` function was replaced by ``check_array`` + and ``check_X_y``. By `Andreas Müller`_. + + - Allow ``X=None`` in the methods ``radius_neighbors``, ``kneighbors``, + ``kneighbors_graph`` and ``radius_neighbors_graph`` in + :class:`sklearn.neighbors.NearestNeighbors` and family. If set to None, + then for every sample this avoids setting the sample itself as the + first nearest neighbor. By `Manoj Kumar`_. + + - Add parameter ``include_self`` in :func:`neighbors.kneighbors_graph` + and :func:`neighbors.radius_neighbors_graph` which has to be explicitly + set by the user. If set to True, then the sample itself is considered + as the first nearest neighbor. + + - `thresh` parameter is deprecated in favor of new `tol` parameter in + :class:`GMM`, :class:`DPGMM` and :class:`VBGMM`. See `Enhancements` + section for details. By `Hervé Bredin`_. + + - Estimators will treat input with dtype object as numeric when possible. + By `Andreas Müller`_ + + - Estimators now raise `ValueError` consistently when fitted on empty + data (less than 1 sample or less than 1 feature for 2D input). + By `Olivier Grisel`_. + + + - The ``shuffle`` option of :class:`.linear_model.SGDClassifier`, + :class:`linear_model.SGDRegressor`, :class:`linear_model.Perceptron`, + :class:`linear_model.PassiveAgressiveClassivier` and + :class:`linear_model.PassiveAgressiveRegressor` now defaults to ``True``. + + - :class:`cluster.DBSCAN` now uses a deterministic initialization. The + `random_state` parameter is deprecated. By `Eric Schubert`_. + +.. _changes_0_15_2: + +0.15.2 +====== + +Bug fixes +--------- + + - Fixed handling of the ``p`` parameter of the Minkowski distance that was + previously ignored in nearest neighbors models. By `Nikolay Mayorov`_. + + - Fixed duplicated alphas in :class:`linear_model.LassoLars` with early + stopping on 32 bit Python. By `Olivier Grisel`_ and `Fabian Pedregosa`_. + + - Fixed the build under Windows when scikit-learn is built with MSVC while + NumPy is built with MinGW. By `Olivier Grisel`_ and Federico Vaggi. + + - Fixed an array index overflow bug in the coordinate descent solver. By + `Gael Varoquaux`_. + + - Better handling of numpy 1.9 deprecation warnings. By `Gael Varoquaux`_. + + - Removed unnecessary data copy in :class:`cluster.KMeans`. + By `Gael Varoquaux`_. + + - Explicitly close open files to avoid ``ResourceWarnings`` under Python 3. + By Calvin Giles. + + - The ``transform`` of :class:`lda.LDA` now projects the input on the most + discriminant directions. By Martin Billinger. + + - Fixed potential overflow in ``_tree.safe_realloc`` by `Lars Buitinck`_. + + - Performance optimization in :class:`isotonic.IsotonicRegression`. + By Robert Bradshaw. + + - ``nose`` is non-longer a runtime dependency to import ``sklearn``, only for + running the tests. By `Joel Nothman`_. + + - Many documentation and website fixes by `Joel Nothman`_, `Lars Buitinck`_ + `Matt Pico`_, and others. + +.. _changes_0_15_1: + +0.15.1 +====== + +Bug fixes +--------- + + - Made :func:`cross_validation.cross_val_score` use + :class:`cross_validation.KFold` instead of + :class:`cross_validation.StratifiedKFold` on multi-output classification + problems. By `Nikolay Mayorov`_. + + - Support unseen labels :class:`preprocessing.LabelBinarizer` to restore + the default behavior of 0.14.1 for backward compatibility. By + `Hamzeh Alsalhi`_. + + - Fixed the :class:`cluster.KMeans` stopping criterion that prevented early + convergence detection. By Edward Raff and `Gael Varoquaux`_. + + - Fixed the behavior of :class:`multiclass.OneVsOneClassifier`. + in case of ties at the per-class vote level by computing the correct + per-class sum of prediction scores. By `Andreas Müller`_. + + - Made :func:`cross_validation.cross_val_score` and + :class:`grid_search.GridSearchCV` accept Python lists as input data. + This is especially useful for cross-validation and model selection of + text processing pipelines. By `Andreas Müller`_. + + - Fixed data input checks of most estimators to accept input data that + implements the NumPy ``__array__`` protocol. This is the case for + for ``pandas.Series`` and ``pandas.DataFrame`` in recent versions of + pandas. By `Gael Varoquaux`_. + + - Fixed a regression for :class:`linear_model.SGDClassifier` with + ``class_weight="auto"`` on data with non-contiguous labels. By + `Olivier Grisel`_. + + +.. _changes_0_15: + +0.15 +==== + +Highlights +----------- + + - Many speed and memory improvements all across the code + + - Huge speed and memory improvements to random forests (and extra + trees) that also benefit better from parallel computing. + + - Incremental fit to :class:`BernoulliRBM ` + + - Added :class:`cluster.AgglomerativeClustering` for hierarchical + agglomerative clustering with average linkage, complete linkage and + ward strategies. + + - Added :class:`linear_model.RANSACRegressor` for robust regression + models. + + - Added dimensionality reduction with :class:`manifold.TSNE` which can be + used to visualize high-dimensional data. + + +Changelog +--------- + +New features +............ + + - Added :class:`ensemble.BaggingClassifier` and + :class:`ensemble.BaggingRegressor` meta-estimators for ensembling + any kind of base estimator. See the :ref:`Bagging ` section of + the user guide for details and examples. By `Gilles Louppe`_. + + - New unsupervised feature selection algorithm + :class:`feature_selection.VarianceThreshold`, by `Lars Buitinck`_. + + - Added :class:`linear_model.RANSACRegressor` meta-estimator for the robust + fitting of regression models. By Johannes Schönberger. + + - Added :class:`cluster.AgglomerativeClustering` for hierarchical + agglomerative clustering with average linkage, complete linkage and + ward strategies, by `Nelle Varoquaux`_ and `Gael Varoquaux`_. + + - Shorthand constructors :func:`pipeline.make_pipeline` and + :func:`pipeline.make_union` were added by `Lars Buitinck`_. + + - Shuffle option for :class:`cross_validation.StratifiedKFold`. + By `Jeffrey Blackburne`_. + + - Incremental learning (``partial_fit``) for Gaussian Naive Bayes by + Imran Haque. + + - Added ``partial_fit`` to :class:`BernoulliRBM + ` + By `Danny Sullivan`_. + + - Added :func:`learning_curve ` utility to + chart performance with respect to training size. See + :ref:`example_model_selection_plot_learning_curve.py`. By Alexander Fabisch. + + - Add positive option in :class:`LassoCV ` and + :class:`ElasticNetCV `. + By Brian Wignall and `Alexandre Gramfort`_. + + - Added :class:`linear_model.MultiTaskElasticNetCV` and + :class:`linear_model.MultiTaskLassoCV`. By `Manoj Kumar`_. + + - Added :class:`manifold.TSNE`. By Alexander Fabisch. + +Enhancements +............ + + - Add sparse input support to :class:`ensemble.AdaBoostClassifier` and + :class:`ensemble.AdaBoostRegressor` meta-estimators. + By `Hamzeh Alsalhi`_. + + - Memory improvements of decision trees, by `Arnaud Joly`_. + + - Decision trees can now be built in best-first manner by using ``max_leaf_nodes`` + as the stopping criteria. Refactored the tree code to use either a + stack or a priority queue for tree building. + By `Peter Prettenhofer`_ and `Gilles Louppe`_. + + - Decision trees can now be fitted on fortran- and c-style arrays, and + non-continuous arrays without the need to make a copy. + If the input array has a different dtype than ``np.float32``, a fortran- + style copy will be made since fortran-style memory layout has speed + advantages. By `Peter Prettenhofer`_ and `Gilles Louppe`_. + + - Speed improvement of regression trees by optimizing the + the computation of the mean square error criterion. This lead + to speed improvement of the tree, forest and gradient boosting tree + modules. By `Arnaud Joly`_ + + - The ``img_to_graph`` and ``grid_tograph`` functions in + :mod:`sklearn.feature_extraction.image` now return ``np.ndarray`` + instead of ``np.matrix`` when ``return_as=np.ndarray``. See the + Notes section for more information on compatibility. + + - Changed the internal storage of decision trees to use a struct array. + This fixed some small bugs, while improving code and providing a small + speed gain. By `Joel Nothman`_. + + - Reduce memory usage and overhead when fitting and predicting with forests + of randomized trees in parallel with ``n_jobs != 1`` by leveraging new + threading backend of joblib 0.8 and releasing the GIL in the tree fitting + Cython code. By `Olivier Grisel`_ and `Gilles Louppe`_. + + - Speed improvement of the :mod:`sklearn.ensemble.gradient_boosting` module. + By `Gilles Louppe`_ and `Peter Prettenhofer`_. + + - Various enhancements to the :mod:`sklearn.ensemble.gradient_boosting` + module: a ``warm_start`` argument to fit additional trees, + a ``max_leaf_nodes`` argument to fit GBM style trees, + a ``monitor`` fit argument to inspect the estimator during training, and + refactoring of the verbose code. By `Peter Prettenhofer`_. + + - Faster :class:`sklearn.ensemble.ExtraTrees` by caching feature values. + By `Arnaud Joly`_. + + - Faster depth-based tree building algorithm such as decision tree, + random forest, extra trees or gradient tree boosting (with depth based + growing strategy) by avoiding trying to split on found constant features + in the sample subset. By `Arnaud Joly`_. + + - Add ``min_weight_fraction_leaf`` pre-pruning parameter to tree-based + methods: the minimum weighted fraction of the input samples required to be + at a leaf node. By `Noel Dawe`_. + + - Added :func:`metrics.pairwise_distances_argmin_min`, by Philippe Gervais. + + - Added predict method to :class:`cluster.AffinityPropagation` and + :class:`cluster.MeanShift`, by `Mathieu Blondel`_. + + - Vector and matrix multiplications have been optimised throughout the + library by `Denis Engemann`_, and `Alexandre Gramfort`_. + In particular, they should take less memory with older NumPy versions + (prior to 1.7.2). + + - Precision-recall and ROC examples now use train_test_split, and have more + explanation of why these metrics are useful. By `Kyle Kastner`_ + + - The training algorithm for :class:`decomposition.NMF` is faster for + sparse matrices and has much lower memory complexity, meaning it will + scale up gracefully to large datasets. By `Lars Buitinck`_. + + - Added svd_method option with default value to "randomized" to + :class:`decomposition.FactorAnalysis` to save memory and + significantly speedup computation by `Denis Engemann`_, and + `Alexandre Gramfort`_. + + - Changed :class:`cross_validation.StratifiedKFold` to try and + preserve as much of the original ordering of samples as possible so as + not to hide overfitting on datasets with a non-negligible level of + samples dependency. + By `Daniel Nouri`_ and `Olivier Grisel`_. + + - Add multi-output support to :class:`gaussian_process.GaussianProcess` + by John Novak. + + - Norm computations optimized for NumPy 1.6 and later versions by + `Lars Buitinck`_. In particular, the k-means algorithm no longer + needs a temporary data structure the size of its input. + + - :class:`dummy.DummyClassifier` can now be used to predict a constant + output value. By `Manoj Kumar`_. + + - :class:`dummy.DummyRegressor` has now a strategy parameter which allows + to predict the mean, the median of the training set or a constant + output value. By `Maheshakya Wijewardena`_. + + - Multi-label classification output in multilabel indicator format + is now supported by :func:`metrics.roc_auc_score` and + :func:`metrics.average_precision_score` by `Arnaud Joly`_. + + - Significant performance improvements (more than 100x speedup for + large problems) in :class:`isotonic.IsotonicRegression` by + `Andrew Tulloch`_. + + - Speed and memory usage improvements to the SGD algorithm for linear + models: it now uses threads, not separate processes, when ``n_jobs>1``. + By `Lars Buitinck`_. + + - Grid search and cross validation allow NaNs in the input arrays so that + preprocessors such as :class:`preprocessing.Imputer + ` can be trained within the cross validation loop, + avoiding potentially skewed results. + + - Ridge regression can now deal with sample weights in feature space + (only sample space until then). By `Michael Eickenberg`_. + Both solutions are provided by the Cholesky solver. + + - Several classification and regression metrics now support weighted + samples with the new ``sample_weight`` argument: + :func:`metrics.accuracy_score`, + :func:`metrics.zero_one_loss`, + :func:`metrics.precision_score`, + :func:`metrics.average_precision_score`, + :func:`metrics.f1_score`, + :func:`metrics.fbeta_score`, + :func:`metrics.recall_score`, + :func:`metrics.roc_auc_score`, + :func:`metrics.explained_variance_score`, + :func:`metrics.mean_squared_error`, + :func:`metrics.mean_absolute_error`, + :func:`metrics.r2_score`. + By `Noel Dawe`_. + + - Speed up of the sample generator + :func:`datasets.make_multilabel_classification`. By `Joel Nothman`_. + +Documentation improvements +........................... + + - The :ref:`Working With Text Data ` tutorial + has now been worked in to the main documentation's tutorial section. + Includes exercises and skeletons for tutorial presentation. + Original tutorial created by several authors including + `Olivier Grisel`_, Lars Buitinck and many others. + Tutorial integration into the scikit-learn documentation + by `Jaques Grobler`_ + + - Added :ref:`Computational Performance ` + documentation. Discussion and examples of prediction latency / throughput + and different factors that have influence over speed. Additional tips for + building faster models and choosing a relevant compromise between speed + and predictive power. + By `Eustache Diemert`_. + +Bug fixes +......... + + - Fixed bug in :class:`decomposition.MiniBatchDictionaryLearning` : + ``partial_fit`` was not working properly. + + - Fixed bug in :class:`linear_model.stochastic_gradient` : + ``l1_ratio`` was used as ``(1.0 - l1_ratio)`` . + + - Fixed bug in :class:`multiclass.OneVsOneClassifier` with string + labels + + - Fixed a bug in :class:`LassoCV ` and + :class:`ElasticNetCV `: they would not + pre-compute the Gram matrix with ``precompute=True`` or + ``precompute="auto"`` and ``n_samples > n_features``. By `Manoj Kumar`_. + + - Fixed incorrect estimation of the degrees of freedom in + :func:`feature_selection.f_regression` when variates are not centered. + By `Virgile Fritsch`_. + + - Fixed a race condition in parallel processing with + ``pre_dispatch != "all"`` (for instance in ``cross_val_score``). + By `Olivier Grisel`_. + + - Raise error in :class:`cluster.FeatureAgglomeration` and + :class:`cluster.WardAgglomeration` when no samples are given, + rather than returning meaningless clustering. + + - Fixed bug in :class:`gradient_boosting.GradientBoostingRegressor` with + ``loss='huber'``: ``gamma`` might have not been initialized. + + - Fixed feature importances as computed with a forest of randomized trees + when fit with ``sample_weight != None`` and/or with ``bootstrap=True``. + By `Gilles Louppe`_. + +API changes summary +------------------- + + - :mod:`sklearn.hmm` is deprecated. Its removal is planned + for the 0.17 release. + + - Use of :class:`covariance.EllipticEnvelop` has now been removed after + deprecation. + Please use :class:`covariance.EllipticEnvelope` instead. + + - :class:`cluster.Ward` is deprecated. Use + :class:`cluster.AgglomerativeClustering` instead. + + - :class:`cluster.WardClustering` is deprecated. Use + - :class:`cluster.AgglomerativeClustering` instead. + + - :class:`cross_validation.Bootstrap` is deprecated. + :class:`cross_validation.KFold` or + :class:`cross_validation.ShuffleSplit` are recommended instead. + + - Direct support for the sequence of sequences (or list of lists) multilabel + format is deprecated. To convert to and from the supported binary + indicator matrix format, use + :class:`MultiLabelBinarizer `. + By `Joel Nothman`_. + + - Add score method to :class:`PCA ` following the model of + probabilistic PCA and deprecate + :class:`ProbabilisticPCA ` model whose + score implementation is not correct. The computation now also exploits the + matrix inversion lemma for faster computation. By `Alexandre Gramfort`_. + + - The score method of :class:`FactorAnalysis ` + now returns the average log-likelihood of the samples. Use score_samples + to get log-likelihood of each sample. By `Alexandre Gramfort`_. + + - Generating boolean masks (the setting ``indices=False``) + from cross-validation generators is deprecated. + Support for masks will be removed in 0.17. + The generators have produced arrays of indices by default since 0.10. + By `Joel Nothman`_. + + - 1-d arrays containing strings with ``dtype=object`` (as used in Pandas) + are now considered valid classification targets. This fixes a regression + from version 0.13 in some classifiers. By `Joel Nothman`_. + + - Fix wrong ``explained_variance_ratio_`` attribute in + :class:`RandomizedPCA `. + By `Alexandre Gramfort`_. + + - Fit alphas for each ``l1_ratio`` instead of ``mean_l1_ratio`` in + :class:`linear_model.ElasticNetCV` and :class:`linear_model.LassoCV`. + This changes the shape of ``alphas_`` from ``(n_alphas,)`` to + ``(n_l1_ratio, n_alphas)`` if the ``l1_ratio`` provided is a 1-D array like + object of length greater than one. + By `Manoj Kumar`_. + + - Fix :class:`linear_model.ElasticNetCV` and :class:`linear_model.LassoCV` + when fitting intercept and input data is sparse. The automatic grid + of alphas was not computed correctly and the scaling with normalize + was wrong. By `Manoj Kumar`_. + + - Fix wrong maximal number of features drawn (``max_features``) at each split + for decision trees, random forests and gradient tree boosting. + Previously, the count for the number of drawn features started only after + one non constant features in the split. This bug fix will affect + computational and generalization performance of those algorithms in the + presence of constant features. To get back previous generalization + performance, you should modify the value of ``max_features``. + By `Arnaud Joly`_. + + - Fix wrong maximal number of features drawn (``max_features``) at each split + for :class:`ensemble.ExtraTreesClassifier` and + :class:`ensemble.ExtraTreesRegressor`. Previously, only non constant + features in the split was counted as drawn. Now constant features are + counted as drawn. Furthermore at least one feature must be non constant + in order to make a valid split. This bug fix will affect + computational and generalization performance of extra trees in the + presence of constant features. To get back previous generalization + performance, you should modify the value of ``max_features``. + By `Arnaud Joly`_. + + - Fix :func:`utils.compute_class_weight` when ``class_weight=="auto"``. + Previously it was broken for input of non-integer ``dtype`` and the + weighted array that was returned was wrong. By `Manoj Kumar`_. + + - Fix :class:`cross_validation.Bootstrap` to return ``ValueError`` + when ``n_train + n_test > n``. By `Ronald Phlypo`_. + + +People +------ + +List of contributors for release 0.15 by number of commits. + +* 312 Olivier Grisel +* 275 Lars Buitinck +* 221 Gael Varoquaux +* 148 Arnaud Joly +* 134 Johannes Schönberger +* 119 Gilles Louppe +* 113 Joel Nothman +* 111 Alexandre Gramfort +* 95 Jaques Grobler +* 89 Denis Engemann +* 83 Peter Prettenhofer +* 83 Alexander Fabisch +* 62 Mathieu Blondel +* 60 Eustache Diemert +* 60 Nelle Varoquaux +* 49 Michael Bommarito +* 45 Manoj-Kumar-S +* 28 Kyle Kastner +* 26 Andreas Mueller +* 22 Noel Dawe +* 21 Maheshakya Wijewardena +* 21 Brooke Osborn +* 21 Hamzeh Alsalhi +* 21 Jake VanderPlas +* 21 Philippe Gervais +* 19 Bala Subrahmanyam Varanasi +* 12 Ronald Phlypo +* 10 Mikhail Korobov +* 8 Thomas Unterthiner +* 8 Jeffrey Blackburne +* 8 eltermann +* 8 bwignall +* 7 Ankit Agrawal +* 7 CJ Carey +* 6 Daniel Nouri +* 6 Chen Liu +* 6 Michael Eickenberg +* 6 ugurthemaster +* 5 Aaron Schumacher +* 5 Baptiste Lagarde +* 5 Rajat Khanduja +* 5 Robert McGibbon +* 5 Sergio Pascual +* 4 Alexis Metaireau +* 4 Ignacio Rossi +* 4 Virgile Fritsch +* 4 Sebastian Saeger +* 4 Ilambharathi Kanniah +* 4 sdenton4 +* 4 Robert Layton +* 4 Alyssa +* 4 Amos Waterland +* 3 Andrew Tulloch +* 3 murad +* 3 Steven Maude +* 3 Karol Pysniak +* 3 Jacques Kvam +* 3 cgohlke +* 3 cjlin +* 3 Michael Becker +* 3 hamzeh +* 3 Eric Jacobsen +* 3 john collins +* 3 kaushik94 +* 3 Erwin Marsi +* 2 csytracy +* 2 LK +* 2 Vlad Niculae +* 2 Laurent Direr +* 2 Erik Shilts +* 2 Raul Garreta +* 2 Yoshiki Vázquez Baeza +* 2 Yung Siang Liau +* 2 abhishek thakur +* 2 James Yu +* 2 Rohit Sivaprasad +* 2 Roland Szabo +* 2 amormachine +* 2 Alexis Mignon +* 2 Oscar Carlsson +* 2 Nantas Nardelli +* 2 jess010 +* 2 kowalski87 +* 2 Andrew Clegg +* 2 Federico Vaggi +* 2 Simon Frid +* 2 Félix-Antoine Fortin +* 1 Ralf Gommers +* 1 t-aft +* 1 Ronan Amicel +* 1 Rupesh Kumar Srivastava +* 1 Ryan Wang +* 1 Samuel Charron +* 1 Samuel St-Jean +* 1 Fabian Pedregosa +* 1 Skipper Seabold +* 1 Stefan Walk +* 1 Stefan van der Walt +* 1 Stephan Hoyer +* 1 Allen Riddell +* 1 Valentin Haenel +* 1 Vijay Ramesh +* 1 Will Myers +* 1 Yaroslav Halchenko +* 1 Yoni Ben-Meshulam +* 1 Yury V. Zaytsev +* 1 adrinjalali +* 1 ai8rahim +* 1 alemagnani +* 1 alex +* 1 benjamin wilson +* 1 chalmerlowe +* 1 dzikie drożdże +* 1 jamestwebber +* 1 matrixorz +* 1 popo +* 1 samuela +* 1 François Boulogne +* 1 Alexander Measure +* 1 Ethan White +* 1 Guilherme Trein +* 1 Hendrik Heuer +* 1 IvicaJovic +* 1 Jan Hendrik Metzen +* 1 Jean Michel Rouly +* 1 Eduardo Ariño de la Rubia +* 1 Jelle Zijlstra +* 1 Eddy L O Jansson +* 1 Denis +* 1 John +* 1 John Schmidt +* 1 Jorge Cañardo Alastuey +* 1 Joseph Perla +* 1 Joshua Vredevoogd +* 1 José Ricardo +* 1 Julien Miotte +* 1 Kemal Eren +* 1 Kenta Sato +* 1 David Cournapeau +* 1 Kyle Kelley +* 1 Daniele Medri +* 1 Laurent Luce +* 1 Laurent Pierron +* 1 Luis Pedro Coelho +* 1 DanielWeitzenfeld +* 1 Craig Thompson +* 1 Chyi-Kwei Yau +* 1 Matthew Brett +* 1 Matthias Feurer +* 1 Max Linke +* 1 Chris Filo Gorgolewski +* 1 Charles Earl +* 1 Michael Hanke +* 1 Michele Orrù +* 1 Bryan Lunt +* 1 Brian Kearns +* 1 Paul Butler +* 1 Paweł Mandera +* 1 Peter +* 1 Andrew Ash +* 1 Pietro Zambelli +* 1 staubda + + +.. _changes_0_14: + +0.14 +======= + +Changelog +--------- + + - Missing values with sparse and dense matrices can be imputed with the + transformer :class:`preprocessing.Imputer` by `Nicolas Trésegnie`_. + + - The core implementation of decisions trees has been rewritten from + scratch, allowing for faster tree induction and lower memory + consumption in all tree-based estimators. By `Gilles Louppe`_. + + - Added :class:`ensemble.AdaBoostClassifier` and + :class:`ensemble.AdaBoostRegressor`, by `Noel Dawe`_ and + `Gilles Louppe`_. See the :ref:`AdaBoost ` section of the user + guide for details and examples. + + - Added :class:`grid_search.RandomizedSearchCV` and + :class:`grid_search.ParameterSampler` for randomized hyperparameter + optimization. By `Andreas Müller`_. + + - Added :ref:`biclustering ` algorithms + (:class:`sklearn.cluster.bicluster.SpectralCoclustering` and + :class:`sklearn.cluster.bicluster.SpectralBiclustering`), data + generation methods (:func:`sklearn.datasets.make_biclusters` and + :func:`sklearn.datasets.make_checkerboard`), and scoring metrics + (:func:`sklearn.metrics.consensus_score`). By `Kemal Eren`_. + + - Added :ref:`Restricted Boltzmann Machines` + (:class:`neural_network.BernoulliRBM`). By `Yann Dauphin`_. + + - Python 3 support by `Justin Vincent`_, `Lars Buitinck`_, + `Subhodeep Moitra`_ and `Olivier Grisel`_. All tests now pass under + Python 3.3. + + - Ability to pass one penalty (alpha value) per target in + :class:`linear_model.Ridge`, by @eickenberg and `Mathieu Blondel`_. + + - Fixed :mod:`sklearn.linear_model.stochastic_gradient.py` L2 regularization + issue (minor practical significance). + By `Norbert Crombach`_ and `Mathieu Blondel`_ . + + - Added an interactive version of `Andreas Müller`_'s + `Machine Learning Cheat Sheet (for scikit-learn) + `_ + to the documentation. See :ref:`Choosing the right estimator `. + By `Jaques Grobler`_. + + - :class:`grid_search.GridSearchCV` and + :func:`cross_validation.cross_val_score` now support the use of advanced + scoring function such as area under the ROC curve and f-beta scores. + See :ref:`scoring_parameter` for details. By `Andreas Müller`_ + and `Lars Buitinck`_. + Passing a function from :mod:`sklearn.metrics` as ``score_func`` is + deprecated. + + - Multi-label classification output is now supported by + :func:`metrics.accuracy_score`, :func:`metrics.zero_one_loss`, + :func:`metrics.f1_score`, :func:`metrics.fbeta_score`, + :func:`metrics.classification_report`, + :func:`metrics.precision_score` and :func:`metrics.recall_score` + by `Arnaud Joly`_. + + - Two new metrics :func:`metrics.hamming_loss` and + :func:`metrics.jaccard_similarity_score` + are added with multi-label support by `Arnaud Joly`_. + + - Speed and memory usage improvements in + :class:`feature_extraction.text.CountVectorizer` and + :class:`feature_extraction.text.TfidfVectorizer`, + by Jochen Wersdörfer and Roman Sinayev. + + - The ``min_df`` parameter in + :class:`feature_extraction.text.CountVectorizer` and + :class:`feature_extraction.text.TfidfVectorizer`, which used to be 2, + has been reset to 1 to avoid unpleasant surprises (empty vocabularies) + for novice users who try it out on tiny document collections. + A value of at least 2 is still recommended for practical use. + + - :class:`svm.LinearSVC`, :class:`linear_model.SGDClassifier` and + :class:`linear_model.SGDRegressor` now have a ``sparsify`` method that + converts their ``coef_`` into a sparse matrix, meaning stored models + trained using these estimators can be made much more compact. + + - :class:`linear_model.SGDClassifier` now produces multiclass probability + estimates when trained under log loss or modified Huber loss. + + - Hyperlinks to documentation in example code on the website by + `Martin Luessi`_. + + - Fixed bug in :class:`preprocessing.MinMaxScaler` causing incorrect scaling + of the features for non-default ``feature_range`` settings. By `Andreas + Müller`_. + + - ``max_features`` in :class:`tree.DecisionTreeClassifier`, + :class:`tree.DecisionTreeRegressor` and all derived ensemble estimators + now supports percentage values. By `Gilles Louppe`_. + + - Performance improvements in :class:`isotonic.IsotonicRegression` by + `Nelle Varoquaux`_. + + - :func:`metrics.accuracy_score` has an option normalize to return + the fraction or the number of correctly classified sample + by `Arnaud Joly`_. + + - Added :func:`metrics.log_loss` that computes log loss, aka cross-entropy + loss. By Jochen Wersdörfer and `Lars Buitinck`_. + + - A bug that caused :class:`ensemble.AdaBoostClassifier`'s to output + incorrect probabilities has been fixed. + + - Feature selectors now share a mixin providing consistent ``transform``, + ``inverse_transform`` and ``get_support`` methods. By `Joel Nothman`_. + + - A fitted :class:`grid_search.GridSearchCV` or + :class:`grid_search.RandomizedSearchCV` can now generally be pickled. + By `Joel Nothman`_. + + - Refactored and vectorized implementation of :func:`metrics.roc_curve` + and :func:`metrics.precision_recall_curve`. By `Joel Nothman`_. + + - The new estimator :class:`sklearn.decomposition.TruncatedSVD` + performs dimensionality reduction using SVD on sparse matrices, + and can be used for latent semantic analysis (LSA). + By `Lars Buitinck`_. + + - Added self-contained example of out-of-core learning on text data + :ref:`example_applications_plot_out_of_core_classification.py`. + By `Eustache Diemert`_. + + - The default number of components for + :class:`sklearn.decomposition.RandomizedPCA` is now correctly documented + to be ``n_features``. This was the default behavior, so programs using it + will continue to work as they did. + + - :class:`sklearn.cluster.KMeans` now fits several orders of magnitude + faster on sparse data (the speedup depends on the sparsity). By + `Lars Buitinck`_. + + - Reduce memory footprint of FastICA by `Denis Engemann`_ and + `Alexandre Gramfort`_. + + - Verbose output in :mod:`sklearn.ensemble.gradient_boosting` now uses + a column format and prints progress in decreasing frequency. + It also shows the remaining time. By `Peter Prettenhofer`_. + + - :mod:`sklearn.ensemble.gradient_boosting` provides out-of-bag improvement + :attr:`~sklearn.ensemble.GradientBoostingRegressor.oob_improvement_` + rather than the OOB score for model selection. An example that shows + how to use OOB estimates to select the number of trees was added. + By `Peter Prettenhofer`_. + + - Most metrics now support string labels for multiclass classification + by `Arnaud Joly`_ and `Lars Buitinck`_. + + - New OrthogonalMatchingPursuitCV class by `Alexandre Gramfort`_ + and `Vlad Niculae`_. + + - Fixed a bug in :class:`sklearn.covariance.GraphLassoCV`: the + 'alphas' parameter now works as expected when given a list of + values. By Philippe Gervais. + + - Fixed an important bug in :class:`sklearn.covariance.GraphLassoCV` + that prevented all folds provided by a CV object to be used (only + the first 3 were used). When providing a CV object, execution + time may thus increase significantly compared to the previous + version (bug results are correct now). By Philippe Gervais. + + - :class:`cross_validation.cross_val_score` and the :mod:`grid_search` + module is now tested with multi-output data by `Arnaud Joly`_. + + - :func:`datasets.make_multilabel_classification` can now return + the output in label indicator multilabel format by `Arnaud Joly`_. + + - K-nearest neighbors, :class:`neighbors.KNeighborsRegressor` + and :class:`neighbors.RadiusNeighborsRegressor`, + and radius neighbors, :class:`neighbors.RadiusNeighborsRegressor` and + :class:`neighbors.RadiusNeighborsClassifier` support multioutput data + by `Arnaud Joly`_. + + - Random state in LibSVM-based estimators (:class:`svm.SVC`, :class:`NuSVC`, + :class:`OneClassSVM`, :class:`svm.SVR`, :class:`svm.NuSVR`) can now be + controlled. This is useful to ensure consistency in the probability + estimates for the classifiers trained with ``probability=True``. By + `Vlad Niculae`_. + + - Out-of-core learning support for discrete naive Bayes classifiers + :class:`sklearn.naive_bayes.MultinomialNB` and + :class:`sklearn.naive_bayes.BernoulliNB` by adding the ``partial_fit`` + method by `Olivier Grisel`_. + + - New website design and navigation by `Gilles Louppe`_, `Nelle Varoquaux`_, + Vincent Michel and `Andreas Müller`_. + + - Improved documentation on :ref:`multi-class, multi-label and multi-output + classification ` by `Yannick Schwartz`_ and `Arnaud Joly`_. + + - Better input and error handling in the :mod:`metrics` module by + `Arnaud Joly`_ and `Joel Nothman`_. + + - Speed optimization of the :mod:`hmm` module by `Mikhail Korobov`_ + + - Significant speed improvements for :class:`sklearn.cluster.DBSCAN` + by `cleverless `_ + + +API changes summary +------------------- + + - The :func:`auc_score` was renamed :func:`roc_auc_score`. + + - Testing scikit-learn with ``sklearn.test()`` is deprecated. Use + ``nosetests sklearn`` from the command line. + + - Feature importances in :class:`tree.DecisionTreeClassifier`, + :class:`tree.DecisionTreeRegressor` and all derived ensemble estimators + are now computed on the fly when accessing the ``feature_importances_`` + attribute. Setting ``compute_importances=True`` is no longer required. + By `Gilles Louppe`_. + + - :class:`linear_model.lasso_path` and + :class:`linear_model.enet_path` can return its results in the same + format as that of :class:`linear_model.lars_path`. This is done by + setting the ``return_models`` parameter to ``False``. By + `Jaques Grobler`_ and `Alexandre Gramfort`_ + + - :class:`grid_search.IterGrid` was renamed to + :class:`grid_search.ParameterGrid`. + + - Fixed bug in :class:`KFold` causing imperfect class balance in some + cases. By `Alexandre Gramfort`_ and Tadej Janež. + + - :class:`sklearn.neighbors.BallTree` has been refactored, and a + :class:`sklearn.neighbors.KDTree` has been + added which shares the same interface. The Ball Tree now works with + a wide variety of distance metrics. Both classes have many new + methods, including single-tree and dual-tree queries, breadth-first + and depth-first searching, and more advanced queries such as + kernel density estimation and 2-point correlation functions. + By `Jake Vanderplas`_ + + - Support for scipy.spatial.cKDTree within neighbors queries has been + removed, and the functionality replaced with the new :class:`KDTree` + class. + + - :class:`sklearn.neighbors.KernelDensity` has been added, which performs + efficient kernel density estimation with a variety of kernels. + + - :class:`sklearn.decomposition.KernelPCA` now always returns output with + ``n_components`` components, unless the new parameter ``remove_zero_eig`` + is set to ``True``. This new behavior is consistent with the way + kernel PCA was always documented; previously, the removal of components + with zero eigenvalues was tacitly performed on all data. + + - ``gcv_mode="auto"`` no longer tries to perform SVD on a densified + sparse matrix in :class:`sklearn.linear_model.RidgeCV`. + + - Sparse matrix support in :class:`sklearn.decomposition.RandomizedPCA` + is now deprecated in favor of the new ``TruncatedSVD``. + + - :class:`cross_validation.KFold` and + :class:`cross_validation.StratifiedKFold` now enforce `n_folds >= 2` + otherwise a ``ValueError`` is raised. By `Olivier Grisel`_. + + - :func:`datasets.load_files`'s ``charset`` and ``charset_errors`` + parameters were renamed ``encoding`` and ``decode_errors``. + + - Attribute ``oob_score_`` in :class:`sklearn.ensemble.GradientBoostingRegressor` + and :class:`sklearn.ensemble.GradientBoostingClassifier` + is deprecated and has been replaced by ``oob_improvement_`` . + + - Attributes in OrthogonalMatchingPursuit have been deprecated + (copy_X, Gram, ...) and precompute_gram renamed precompute + for consistency. See #2224. + + - :class:`sklearn.preprocessing.StandardScaler` now converts integer input + to float, and raises a warning. Previously it rounded for dense integer + input. + + - :class:`sklearn.multiclass.OneVsRestClassifier` now has a + ``decision_function`` method. This will return the distance of each + sample from the decision boundary for each class, as long as the + underlying estimators implement the ``decision_function`` method. + By `Kyle Kastner`_. + + - Better input validation, warning on unexpected shapes for y. + +People +------ +List of contributors for release 0.14 by number of commits. + + * 277 Gilles Louppe + * 245 Lars Buitinck + * 187 Andreas Mueller + * 124 Arnaud Joly + * 112 Jaques Grobler + * 109 Gael Varoquaux + * 107 Olivier Grisel + * 102 Noel Dawe + * 99 Kemal Eren + * 79 Joel Nothman + * 75 Jake VanderPlas + * 73 Nelle Varoquaux + * 71 Vlad Niculae + * 65 Peter Prettenhofer + * 64 Alexandre Gramfort + * 54 Mathieu Blondel + * 38 Nicolas Trésegnie + * 35 eustache + * 27 Denis Engemann + * 25 Yann N. Dauphin + * 19 Justin Vincent + * 17 Robert Layton + * 15 Doug Coleman + * 14 Michael Eickenberg + * 13 Robert Marchman + * 11 Fabian Pedregosa + * 11 Philippe Gervais + * 10 Jim Holmström + * 10 Tadej Janež + * 10 syhw + * 9 Mikhail Korobov + * 9 Steven De Gryze + * 8 sergeyf + * 7 Ben Root + * 7 Hrishikesh Huilgolkar + * 6 Kyle Kastner + * 6 Martin Luessi + * 6 Rob Speer + * 5 Federico Vaggi + * 5 Raul Garreta + * 5 Rob Zinkov + * 4 Ken Geis + * 3 A. Flaxman + * 3 Denton Cockburn + * 3 Dougal Sutherland + * 3 Ian Ozsvald + * 3 Johannes Schönberger + * 3 Robert McGibbon + * 3 Roman Sinayev + * 3 Szabo Roland + * 2 Diego Molla + * 2 Imran Haque + * 2 Jochen Wersdörfer + * 2 Sergey Karayev + * 2 Yannick Schwartz + * 2 jamestwebber + * 1 Abhijeet Kolhe + * 1 Alexander Fabisch + * 1 Bastiaan van den Berg + * 1 Benjamin Peterson + * 1 Daniel Velkov + * 1 Fazlul Shahriar + * 1 Felix Brockherde + * 1 Félix-Antoine Fortin + * 1 Harikrishnan S + * 1 Jack Hale + * 1 JakeMick + * 1 James McDermott + * 1 John Benediktsson + * 1 John Zwinck + * 1 Joshua Vredevoogd + * 1 Justin Pati + * 1 Kevin Hughes + * 1 Kyle Kelley + * 1 Matthias Ekman + * 1 Miroslav Shubernetskiy + * 1 Naoki Orii + * 1 Norbert Crombach + * 1 Rafael Cunha de Almeida + * 1 Rolando Espinoza La fuente + * 1 Seamus Abshere + * 1 Sergey Feldman + * 1 Sergio Medina + * 1 Stefano Lattarini + * 1 Steve Koch + * 1 Sturla Molden + * 1 Thomas Jarosch + * 1 Yaroslav Halchenko + +.. _changes_0_13_1: + +0.13.1 +====== + +The 0.13.1 release only fixes some bugs and does not add any new functionality. + +Changelog +--------- + + - Fixed a testing error caused by the function :func:`cross_validation.train_test_split` being + interpreted as a test by `Yaroslav Halchenko`_. + + - Fixed a bug in the reassignment of small clusters in the :class:`cluster.MiniBatchKMeans` + by `Gael Varoquaux`_. + + - Fixed default value of ``gamma`` in :class:`decomposition.KernelPCA` by `Lars Buitinck`_. + + - Updated joblib to ``0.7.0d`` by `Gael Varoquaux`_. + + - Fixed scaling of the deviance in :class:`ensemble.GradientBoostingClassifier` by `Peter Prettenhofer`_. + + - Better tie-breaking in :class:`multiclass.OneVsOneClassifier` by `Andreas Müller`_. + + - Other small improvements to tests and documentation. + +People +------ +List of contributors for release 0.13.1 by number of commits. + * 16 `Lars Buitinck`_ + * 12 `Andreas Müller`_ + * 8 `Gael Varoquaux`_ + * 5 Robert Marchman + * 3 `Peter Prettenhofer`_ + * 2 Hrishikesh Huilgolkar + * 1 Bastiaan van den Berg + * 1 Diego Molla + * 1 `Gilles Louppe`_ + * 1 `Mathieu Blondel`_ + * 1 `Nelle Varoquaux`_ + * 1 Rafael Cunha de Almeida + * 1 Rolando Espinoza La fuente + * 1 `Vlad Niculae`_ + * 1 `Yaroslav Halchenko`_ + + .. _changes_0_13: 0.13 ==== +New Estimator Classes +--------------------- + + - :class:`dummy.DummyClassifier` and :class:`dummy.DummyRegressor`, two + data-independent predictors by `Mathieu Blondel`_. Useful to sanity-check + your estimators. See :ref:`dummy_estimators` in the user guide. + Multioutput support added by `Arnaud Joly`_. + + - :class:`decomposition.FactorAnalysis`, a transformer implementing the + classical factor analysis, by `Christian Osendorfer`_ and `Alexandre + Gramfort`_. See :ref:`FA` in the user guide. + + - :class:`feature_extraction.FeatureHasher`, a transformer implementing the + "hashing trick" for fast, low-memory feature extraction from string fields + by `Lars Buitinck`_ and :class:`feature_extraction.text.HashingVectorizer` + for text documents by `Olivier Grisel`_ See :ref:`feature_hashing` and + :ref:`hashing_vectorizer` for the documentation and sample usage. + + - :class:`pipeline.FeatureUnion`, a transformer that concatenates + results of several other transformers by `Andreas Müller`_. See + :ref:`feature_union` in the user guide. + + - :class:`random_projection.GaussianRandomProjection`, + :class:`random_projection.SparseRandomProjection` and the function + :func:`random_projection.johnson_lindenstrauss_min_dim`. The first two are + transformers implementing Gaussian and sparse random projection matrix + by `Olivier Grisel`_ and `Arnaud Joly`_. + See :ref:`random_projection` in the user guide. + + - :class:`kernel_approximation.Nystroem`, a transformer for approximating + arbitrary kernels by `Andreas Müller`_. See + :ref:`nystroem_kernel_approx` in the user guide. + + - :class:`preprocessing.OneHotEncoder`, a transformer that computes binary + encodings of categorical features by `Andreas Müller`_. See + :ref:`preprocessing_categorical_features` in the user guide. + + - :class:`linear_model.PassiveAggressiveClassifier` and + :class:`linear_model.PassiveAggressiveRegressor`, predictors implementing + an efficient stochastic optimization for linear models by `Rob Zinkov`_ and + `Mathieu Blondel`_. See :ref:`passive_aggressive` in the user + guide. + + - :class:`ensemble.RandomTreesEmbedding`, a transformer for creating high-dimensional + sparse representations using ensembles of totally random trees by `Andreas Müller`_. + See :ref:`random_trees_embedding` in the user guide. + + - :class:`manifold.SpectralEmbedding` and function + :func:`manifold.spectral_embedding`, implementing the "laplacian + eigenmaps" transformation for non-linear dimensionality reduction by Wei + Li. See :ref:`spectral_embedding` in the user guide. + + - :class:`isotonic.IsotonicRegression` by `Fabian Pedregosa`_, `Alexandre Gramfort`_ + and `Nelle Varoquaux`_, + + Changelog --------- + - :func:`metrics.zero_one_loss` (formerly ``metrics.zero_one``) now has + option for normalized output that reports the fraction of + misclassifications, rather than the raw number of misclassifications. By + Kyle Beauchamp. + + - :class:`tree.DecisionTreeClassifier` and all derived ensemble models now + support sample weighting, by `Noel Dawe`_ and `Gilles Louppe`_. + + - Speedup improvement when using bootstrap samples in forests of randomized + trees, by `Peter Prettenhofer`_ and `Gilles Louppe`_. + + - Partial dependence plots for :ref:`gradient_boosting` in + :func:`ensemble.partial_dependence.partial_dependence` by `Peter + Prettenhofer`_. See :ref:`example_ensemble_plot_partial_dependence.py` for an + example. + + - The table of contents on the website has now been made expandable by + `Jaques Grobler`_. + - :class:`feature_selection.SelectPercentile` now breaks ties deterministically instead of returning all equally ranked features. - - Ridge regression and ridge classification fitting no longer has - quadratic memory complexity. + - :class:`feature_selection.SelectKBest` and + :class:`feature_selection.SelectPercentile` are more numerically stable + since they use scores, rather than p-values, to rank results. This means + that they might sometimes select different features than they did + previously. + + - Ridge regression and ridge classification fitting with ``sparse_cg`` solver + no longer has quadratic memory complexity, by `Lars Buitinck`_ and + `Fabian Pedregosa`_. + + - Ridge regression and ridge classification now support a new fast solver + called ``lsqr``, by `Mathieu Blondel`_. - Speed up of :func:`metrics.precision_recall_curve` by Conrad Lee. + - Added support for reading/writing svmlight files with pairwise + preference attribute (qid in svmlight file format) in + :func:`datasets.dump_svmlight_file` and + :func:`datasets.load_svmlight_file` by `Fabian Pedregosa`_. + + - Faster and more robust :func:`metrics.confusion_matrix` and + :ref:`clustering_evaluation` by Wei Li. + + - :func:`cross_validation.cross_val_score` now works with precomputed kernels + and affinity matrices, by `Andreas Müller`_. + + - LARS algorithm made more numerically stable with heuristics to drop + regressors too correlated as well as to stop the path when + numerical noise becomes predominant, by `Gael Varoquaux`_. + + - Faster implementation of :func:`metrics.precision_recall_curve` by + Conrad Lee. + + - New kernel :class:`metrics.chi2_kernel` by `Andreas Müller`_, often used + in computer vision applications. + + - Fix of longstanding bug in :class:`naive_bayes.BernoulliNB` fixed by + Shaun Jackman. + + - Implemented ``predict_proba`` in :class:`multiclass.OneVsRestClassifier`, + by Andrew Winterman. + + - Improve consistency in gradient boosting: estimators + :class:`ensemble.GradientBoostingRegressor` and + :class:`ensemble.GradientBoostingClassifier` use the estimator + :class:`tree.DecisionTreeRegressor` instead of the + :class:`tree._tree.Tree` data structure by `Arnaud Joly`_. + + - Fixed a floating point exception in the :ref:`decision trees ` + module, by Seberg. + + - Fix :func:`metrics.roc_curve` fails when y_true has only one class + by Wei Li. + + - Add the :func:`metrics.mean_absolute_error` function which computes the + mean absolute error. The :func:`metrics.mean_squared_error`, + :func:`metrics.mean_absolute_error` and + :func:`metrics.r2_score` metrics support multioutput by `Arnaud Joly`_. + + - Fixed ``class_weight`` support in :class:`svm.LinearSVC` and + :class:`linear_model.LogisticRegression` by `Andreas Müller`_. The meaning + of ``class_weight`` was reversed as erroneously higher weight meant less + positives of a given class in earlier releases. + + - Improve narrative documentation and consistency in + :mod:`sklearn.metrics` for regression and classification metrics + by `Arnaud Joly`_. + + - Fixed a bug in :class:`sklearn.svm.SVC` when using csr-matrices with + unsorted indices by Xinfan Meng and `Andreas Müller`_. + + - :class:`MiniBatchKMeans`: Add random reassignment of cluster centers + with little observations attached to them, by `Gael Varoquaux`_. + + API changes summary ------------------- + - Renamed all occurrences of ``n_atoms`` to ``n_components`` for consistency. + This applies to :class:`decomposition.DictionaryLearning`, + :class:`decomposition.MiniBatchDictionaryLearning`, + :func:`decomposition.dict_learning`, :func:`decomposition.dict_learning_online`. + + - Renamed all occurrences of ``max_iters`` to ``max_iter`` for consistency. + This applies to :class:`semi_supervised.LabelPropagation` and + :class:`semi_supervised.label_propagation.LabelSpreading`. + + - Renamed all occurrences of ``learn_rate`` to ``learning_rate`` for + consistency in :class:`ensemble.BaseGradientBoosting` and + :class:`ensemble.GradientBoostingRegressor`. - The module ``sklearn.linear_model.sparse`` is gone. Sparse matrix support was already integrated into the "regular" linear models. - - ``sklearn.metrics.mean_square_error``, which incorrectly returned the - cumulated error, was removed. Use ``mean_squared_error`` instead. + - :func:`sklearn.metrics.mean_square_error`, which incorrectly returned the + accumulated error, was removed. Use ``mean_squared_error`` instead. - Passing ``class_weight`` parameters to ``fit`` methods is no longer - supported. Pass them to estimator constuctors instead. + supported. Pass them to estimator constructors instead. - GMMs no longer have ``decode`` and ``rvs`` methods. Use the ``score``, ``predict`` or ``sample`` methods instead. + - The ``solver`` fit option in Ridge regression and classification is now + deprecated and will be removed in v0.14. Use the constructor option + instead. + + - :class:`feature_extraction.text.DictVectorizer` now returns sparse + matrices in the CSR format, instead of COO. + + - Renamed ``k`` in :class:`cross_validation.KFold` and + :class:`cross_validation.StratifiedKFold` to ``n_folds``, renamed + ``n_bootstraps`` to ``n_iter`` in ``cross_validation.Bootstrap``. + + - Renamed all occurrences of ``n_iterations`` to ``n_iter`` for consistency. + This applies to :class:`cross_validation.ShuffleSplit`, + :class:`cross_validation.StratifiedShuffleSplit`, + :func:`utils.randomized_range_finder` and :func:`utils.randomized_svd`. + + - Replaced ``rho`` in :class:`linear_model.ElasticNet` and + :class:`linear_model.SGDClassifier` by ``l1_ratio``. The ``rho`` parameter + had different meanings; ``l1_ratio`` was introduced to avoid confusion. + It has the same meaning as previously ``rho`` in + :class:`linear_model.ElasticNet` and ``(1-rho)`` in + :class:`linear_model.SGDClassifier`. + + - :class:`linear_model.LassoLars` and :class:`linear_model.Lars` now + store a list of paths in the case of multiple targets, rather than + an array of paths. + + - The attribute ``gmm`` of :class:`hmm.GMMHMM` was renamed to ``gmm_`` + to adhere more strictly with the API. + + - :func:`cluster.spectral_embedding` was moved to + :func:`manifold.spectral_embedding`. + + - Renamed ``eig_tol`` in :func:`manifold.spectral_embedding`, + :class:`cluster.SpectralClustering` to ``eigen_tol``, renamed ``mode`` + to ``eigen_solver``. + + - Renamed ``mode`` in :func:`manifold.spectral_embedding` and + :class:`cluster.SpectralClustering` to ``eigen_solver``. + + - ``classes_`` and ``n_classes_`` attributes of + :class:`tree.DecisionTreeClassifier` and all derived ensemble models are + now flat in case of single output problems and nested in case of + multi-output problems. + + - The ``estimators_`` attribute of + :class:`ensemble.gradient_boosting.GradientBoostingRegressor` and + :class:`ensemble.gradient_boosting.GradientBoostingClassifier` is now an + array of :class:'tree.DecisionTreeRegressor'. + + - Renamed ``chunk_size`` to ``batch_size`` in + :class:`decomposition.MiniBatchDictionaryLearning` and + :class:`decomposition.MiniBatchSparsePCA` for consistency. + + - :class:`svm.SVC` and :class:`svm.NuSVC` now provide a ``classes_`` + attribute and support arbitrary dtypes for labels ``y``. + Also, the dtype returned by ``predict`` now reflects the dtype of + ``y`` during ``fit`` (used to be ``np.float``). + + - Changed default test_size in :func:`cross_validation.train_test_split` + to None, added possibility to infer ``test_size`` from ``train_size`` in + :class:`cross_validation.ShuffleSplit` and + :class:`cross_validation.StratifiedShuffleSplit`. + + - Renamed function :func:`sklearn.metrics.zero_one` to + :func:`sklearn.metrics.zero_one_loss`. Be aware that the default behavior + in :func:`sklearn.metrics.zero_one_loss` is different from + :func:`sklearn.metrics.zero_one`: ``normalize=False`` is changed to + ``normalize=True``. + + - Renamed function :func:`metrics.zero_one_score` to + :func:`metrics.accuracy_score`. + + - :func:`datasets.make_circles` now has the same number of inner and outer points. + + - In the Naive Bayes classifiers, the ``class_prior`` parameter was moved + from ``fit`` to ``__init__``. + +People +------ +List of contributors for release 0.13 by number of commits. + + * 364 `Andreas Müller`_ + * 143 `Arnaud Joly`_ + * 137 `Peter Prettenhofer`_ + * 131 `Gael Varoquaux`_ + * 117 `Mathieu Blondel`_ + * 108 `Lars Buitinck`_ + * 106 Wei Li + * 101 `Olivier Grisel`_ + * 65 `Vlad Niculae`_ + * 54 `Gilles Louppe`_ + * 40 `Jaques Grobler`_ + * 38 `Alexandre Gramfort`_ + * 30 `Rob Zinkov`_ + * 19 Aymeric Masurelle + * 18 Andrew Winterman + * 17 `Fabian Pedregosa`_ + * 17 Nelle Varoquaux + * 16 `Christian Osendorfer`_ + * 14 `Daniel Nouri`_ + * 13 `Virgile Fritsch`_ + * 13 syhw + * 12 `Satrajit Ghosh`_ + * 10 Corey Lynch + * 10 Kyle Beauchamp + * 9 Brian Cheung + * 9 Immanuel Bayer + * 9 mr.Shu + * 8 Conrad Lee + * 8 `James Bergstra`_ + * 7 Tadej Janež + * 6 Brian Cajes + * 6 `Jake Vanderplas`_ + * 6 Michael + * 6 Noel Dawe + * 6 Tiago Nunes + * 6 cow + * 5 Anze + * 5 Shiqiao Du + * 4 Christian Jauvin + * 4 Jacques Kvam + * 4 Richard T. Guy + * 4 `Robert Layton`_ + * 3 Alexandre Abraham + * 3 Doug Coleman + * 3 Scott Dickerson + * 2 ApproximateIdentity + * 2 John Benediktsson + * 2 Mark Veronda + * 2 Matti Lyra + * 2 Mikhail Korobov + * 2 Xinfan Meng + * 1 Alejandro Weinstein + * 1 `Alexandre Passos`_ + * 1 Christoph Deil + * 1 Eugene Nizhibitsky + * 1 Kenneth C. Arnold + * 1 Luis Pedro Coelho + * 1 Miroslav Batchkarov + * 1 Pavel + * 1 Sebastian Berg + * 1 Shaun Jackman + * 1 Subhodeep Moitra + * 1 bob + * 1 dengemann + * 1 emanuele + * 1 x006 + + +.. _changes_0_12.1: + +0.12.1 +======= + +The 0.12.1 release is a bug-fix release with no additional features, but is +instead a set of bug fixes + +Changelog +---------- + + - Improved numerical stability in spectral embedding by `Gael + Varoquaux`_ + + - Doctest under windows 64bit by `Gael Varoquaux`_ + + - Documentation fixes for elastic net by `Andreas Müller`_ and + `Alexandre Gramfort`_ + + - Proper behavior with fortran-ordered NumPy arrays by `Gael Varoquaux`_ + + - Make GridSearchCV work with non-CSR sparse matrix by `Lars Buitinck`_ + + - Fix parallel computing in MDS by `Gael Varoquaux`_ + + - Fix Unicode support in count vectorizer by `Andreas Müller`_ + + - Fix MinCovDet breaking with X.shape = (3, 1) by `Virgile Fritsch`_ + + - Fix clone of SGD objects by `Peter Prettenhofer`_ + + - Stabilize GMM by `Virgile Fritsch`_ + +People +------ + + * 14 `Peter Prettenhofer`_ + * 12 `Gael Varoquaux`_ + * 10 `Andreas Müller`_ + * 5 `Lars Buitinck`_ + * 3 `Virgile Fritsch`_ + * 1 `Alexandre Gramfort`_ + * 1 `Gilles Louppe`_ + * 1 `Mathieu Blondel`_ .. _changes_0_12: @@ -96,7 +1940,7 @@ Changelog by `Andreas Müller`_. - In :class:`feature_extraction.text.CountVectorizer`, added an option to - infrequent words, ``min_df`` by `Andreas Müller`_. + ignore infrequent words, ``min_df`` by `Andreas Müller`_. - Add support for multiple targets in some linear models (ElasticNet, Lasso and OrthogonalMatchingPursuit) by `Vlad Niculae`_ and @@ -150,12 +1994,12 @@ API changes summary - Grid of alphas used for fitting :class:`linear_model.LassoCV` and :class:`linear_model.ElasticNetCV` is now stored - in the attribute `alphas_` rather than overriding the init parameter - `alphas`. + in the attribute ``alphas_`` rather than overriding the init parameter + ``alphas``. - Linear models when alpha is estimated by cross-validation store - the estimated value in the `alpha_` attribute rather than just - `alpha` or `best_alpha`. + the estimated value in the ``alpha_`` attribute rather than just + ``alpha`` or ``best_alpha``. - :class:`ensemble.GradientBoostingClassifier` now supports :meth:`ensemble.GradientBoostingClassifier.staged_predict_proba`, and @@ -199,7 +2043,7 @@ People * 7 Marko Burjek * 5 `Nicolas Pinto`_ * 4 Alexandre Abraham - * 4 Jake VanderPlas + * 4 `Jake Vanderplas`_ * 3 `Brian Holt`_ * 3 `Edouard Duchesnay`_ * 3 Florian Hoenig @@ -274,10 +2118,10 @@ Other changes - Merged dense and sparse implementations of :ref:`sgd` module and exposed utility extension types for sequential - datasets `seq_dataset` and weight vectors `weight_vector` + datasets ``seq_dataset`` and weight vectors ``weight_vector`` by `Peter Prettenhofer`_. - - Added `partial_fit` (support for online/minibatch learning) and + - Added ``partial_fit`` (support for online/minibatch learning) and warm_start to the :ref:`sgd` module by `Mathieu Blondel`_. - Dense and sparse implementations of :ref:`svm` classes and @@ -290,27 +2134,27 @@ Other changes and :func:`metrics.pairwise.pairwise_kernels` for parallel computation, by `Mathieu Blondel`_. - - :ref:`k_means` can now be run in parallel, using the `n_jobs` argument + - :ref:`k_means` can now be run in parallel, using the ``n_jobs`` argument to either :ref:`k_means` or :class:`KMeans`, by `Robert Layton`_. - Improved :ref:`cross_validation` and :ref:`grid_search` documentation and introduced the new :func:`cross_validation.train_test_split` helper function by `Olivier Grisel`_ - - :class:`svm.SVC` members `coef_` and `intercept_` changed sign for consistency - with `decision_function`; for ``kernel==linear``, `coef_` was fixed - in the the one-vs-one case, by `Andreas Müller`_. + - :class:`svm.SVC` members ``coef_`` and ``intercept_`` changed sign for + consistency with ``decision_function``; for ``kernel==linear``, + ``coef_`` was fixed in the the one-vs-one case, by `Andreas Müller`_. - Performance improvements to efficient leave-one-out cross-validated Ridge regression, esp. for the ``n_samples > n_features`` case, in :class:`linear_model.RidgeCV`, by Reuben Fletcher-Costin. - - Refactoring and simplication of the :ref:`text_feature_extraction` + - Refactoring and simplification of the :ref:`text_feature_extraction` API and fixed a bug that caused possible negative IDF, by `Olivier Grisel`_. - Beam pruning option in :class:`_BaseHMM` module has been removed since it - is difficult to cythonize. If you are interested in contributing a cython + is difficult to Cythonize. If you are interested in contributing a Cython version, you can use the python version in the git history as a reference. - Classes in :ref:`neighbors` now support arbitrary Minkowski metric for @@ -322,7 +2166,7 @@ API changes summary - :class:`covariance.EllipticEnvelop` is now deprecated - Please use :class:`covariance.EllipticEnvelope` instead. - - `NeighborsClassifier` and `NeighborsRegressor` are gone in the module + - ``NeighborsClassifier`` and ``NeighborsRegressor`` are gone in the module :ref:`neighbors`. Use the classes :class:`KNeighborsClassifier`, :class:`RadiusNeighborsClassifier`, :class:`KNeighborsRegressor` and/or :class:`RadiusNeighborsRegressor` instead. @@ -333,15 +2177,15 @@ API changes summary parameters must be passed to an object when initialising it and not through ``fit``. Now ``fit`` will only accept the data as an input parameter. - - methods `rvs` and `decode` in :class:`GMM` module are now deprecated. - `sample` and `score` or `predict` should be used instead. + - methods ``rvs`` and ``decode`` in :class:`GMM` module are now deprecated. + ``sample`` and ``score`` or ``predict`` should be used instead. - - attribute `_scores` and `_pvalues` in univariate feature selection + - attribute ``_scores`` and ``_pvalues`` in univariate feature selection objects are now deprecated. - `scores_` or `pvalues_` should be used instead. + ``scores_`` or ``pvalues_`` should be used instead. - In :class:`LogisticRegression`, :class:`LinearSVC`, :class:`SVC` and - :class:`NuSVC`, the `class_weight` parameter is now an initialization + :class:`NuSVC`, the ``class_weight`` parameter is now an initialization parameter, not a parameter to fit. This makes grid searches over this parameter possible. @@ -349,11 +2193,12 @@ API changes summary consistent with the Olivetti faces dataset. Use ``images`` and ``pairs`` attribute to access the natural images shapes instead. - - In :class:`svm.LinearSVC`, the meaning of the `multi_class` parameter changed. - Options now are 'ovr' and 'crammer_singer', with 'ovr' being the default. - This does not change the default behavior but hopefully is less confusing. + - In :class:`svm.LinearSVC`, the meaning of the ``multi_class`` parameter + changed. Options now are ``'ovr'`` and ``'crammer_singer'``, with + ``'ovr'`` being the default. This does not change the default behavior + but hopefully is less confusing. - - Classs :class:`feature_selection.text.Vectorizer` is deprecated and + - Class :class:`feature_selection.text.Vectorizer` is deprecated and replaced by :class:`feature_selection.text.TfidfVectorizer`. - The preprocessor / analyzer nested structure for text feature @@ -363,7 +2208,7 @@ API changes summary :class:`feature_selection.text.CountVectorizer`, in particular the following parameters are now used: - - ``analyzer`` can be `'word'` or `'char'` to switch the default + - ``analyzer`` can be ``'word'`` or ``'char'`` to switch the default analysis scheme, or use a specific python callable (as previously). - ``tokenizer`` and ``preprocessor`` have been introduced to make it @@ -371,7 +2216,7 @@ API changes summary - ``input`` explicitly control how to interpret the sequence passed to ``fit`` and ``predict``: filenames, file objects or direct (byte or - unicode) strings. + Unicode) strings. - charset decoding is explicit and strict by default. @@ -383,8 +2228,8 @@ API changes summary from :class:`feature_selection.text.CountVectorizer` to make grid search trivial. - - methods `rvs` in :class:`_BaseHMM` module are now deprecated. - `sample` should be used instead. + - methods ``rvs`` in :class:`_BaseHMM` module are now deprecated. + ``sample`` should be used instead. - Beam pruning option in :class:`_BaseHMM` module is removed since it is difficult to be Cythonized. If you are interested, you can look in the @@ -449,7 +2294,7 @@ People * 1 `Edouard Duchesnay`_ * 1 Jan Hendrik Metzen * 1 Meng Xinfan - * 1 Rob Zinkov + * 1 `Rob Zinkov`_ * 1 Shiqiao * 1 Udi Weinsberg * 1 Virgile Fritsch @@ -521,7 +2366,7 @@ Changelog - :ref:`k_means` support for sparse matrices by `Mathieu Blondel`_. - Improved documentation for developers and for the :mod:`sklearn.utils` - module, by `Jake VanderPlas`_. + module, by `Jake Vanderplas`_. - Vectorized 20newsgroups dataset loader (:func:`sklearn.datasets.fetch_20newsgroups_vectorized`) by @@ -551,7 +2396,7 @@ Changelog API changes summary ------------------- -Here are the code migration instructions when updgrading from scikit-learn +Here are the code migration instructions when upgrading from scikit-learn version 0.9: - Some estimators that may overwrite their inputs to save memory previously @@ -718,7 +2563,7 @@ Changelog - Text feature extraction optimizations by Lars Buitinck - Chi-Square feature selection - (:func:`feature_selection.univariate_selection.chi2`) by `Lars Buitinck`. + (:func:`feature_selection.univariate_selection.chi2`) by `Lars Buitinck`_. - :ref:`sample_generators` module refactoring by `Gilles Louppe`_ @@ -734,7 +2579,7 @@ Changelog - Faster mean shift by Conrad Lee - - New :ref:`Bootstrap`, :ref:`ShuffleSplit` and various other + - New ``Bootstrap``, :ref:`ShuffleSplit` and various other improvements in cross validation schemes by `Olivier Grisel`_ and `Gael Varoquaux`_ @@ -742,7 +2587,7 @@ Changelog - Added :class:`Orthogonal Matching Pursuit ` by `Vlad Niculae`_ - - Added 2D-patch extractor utilites in the :ref:`feature_extraction` module by `Vlad Niculae`_ + - Added 2D-patch extractor utilities in the :ref:`feature_extraction` module by `Vlad Niculae`_ - Implementation of :class:`linear_model.LassoLarsCV` (cross-validated Lasso solver using the Lars algorithm) and @@ -765,7 +2610,7 @@ Changelog API changes summary ------------------- -Here are the code migration instructions when updgrading from scikit-learn +Here are the code migration instructions when upgrading from scikit-learn version 0.8: - The ``scikits.learn`` package was renamed ``sklearn``. There is @@ -779,7 +2624,7 @@ version 0.8: - Estimators no longer accept model parameters as ``fit`` arguments: instead all parameters must be only be passed as constructor - arguments or using the now public ``set_params`` method inhereted + arguments or using the now public ``set_params`` method inherited from :class:`base.BaseEstimator`. Some estimators can still accept keyword arguments on the ``fit`` @@ -834,7 +2679,7 @@ version 0.8: and by default returns the pairwise distance. For the component wise distance, set the parameter ``sum_over_features`` to ``False``. -Backward compatibilty package aliases and other deprecated classes and +Backward compatibility package aliases and other deprecated classes and functions will be removed in version 0.11. @@ -890,8 +2735,8 @@ scikit-learn 0.8 was released on May 2011, one month after the first "international" `scikit-learn coding sprint `_ and is marked by the inclusion of important modules: :ref:`hierarchical_clustering`, -:ref:`pls`, :ref:`NMF`, initial support for Python 3 and by important -enhacements and bug fixes. +:ref:`cross_decomposition`, :ref:`NMF`, initial support for Python 3 and by important +enhancements and bug fixes. Changelog @@ -906,7 +2751,7 @@ Several new modules where introduced during this release: - :ref:`labeled_faces_in_the_wild` by `Olivier Grisel`_. - - New :ref:`pls` module by `Edouard Duchesnay`_. + - New :ref:`cross_decomposition` module by `Edouard Duchesnay`_. - :ref:`NMF` module `Vlad Niculae`_ @@ -928,9 +2773,10 @@ Some other modules benefited from significant improvements or cleanups. - bug and style fixing in :ref:`k_means` algorithm by Jan Schlüter. - - Add attribute coverged to Gaussian Mixture Models by Vincent Schut. + - Add attribute converged to Gaussian Mixture Models by Vincent Schut. - - Implement `transform`, `predict_log_proba` in :class:`lda.LDA` by `Mathieu Blondel`_. + - Implemented ``transform``, ``predict_log_proba`` in :class:`lda.LDA` + By `Mathieu Blondel`_. - Refactoring in the :ref:`svm` module and bug fixes by `Fabian Pedregosa`_, `Gael Varoquaux`_ and Amit Aides. @@ -950,7 +2796,7 @@ Some other modules benefited from significant improvements or cleanups. People ------- -People that made this release possible preceeded by number of commits: +People that made this release possible preceded by number of commits: - 159 `Olivier Grisel`_ @@ -1019,7 +2865,7 @@ Changelog - Refactoring of :class:`neighbors.NeighborsClassifier` and :func:`neighbors.kneighbors_graph`: added different algorithms for the k-Nearest Neighbor Search and implemented a more stable - algorithm for finding barycenter weigths. Also added some + algorithm for finding barycenter weights. Also added some developer documentation for this module, see `notes_neighbors `_ for more information [`Fabian Pedregosa`_]. @@ -1050,7 +2896,7 @@ Changelog People ------ -People that made this release possible preceeded by number of commits: +People that made this release possible preceded by number of commits: - 85 `Fabian Pedregosa`_ - 67 `Mathieu Blondel`_ @@ -1076,7 +2922,7 @@ People that made this release possible preceeded by number of commits: 0.6 === -scikit-learn 0.6 was released on december 2010. It is marked by the +scikit-learn 0.6 was released on December 2010. It is marked by the inclusion of several new modules and a general renaming of old ones. It is also marked by the inclusion of new example, including applications to real-world datasets. @@ -1140,7 +2986,7 @@ Changelog People ------ -People that made this release possible preceeded by number of commits: +People that made this release possible preceded by number of commits: * 207 `Olivier Grisel`_ @@ -1166,7 +3012,7 @@ People that made this release possible preceeded by number of commits: * 2 Ronan Amicel - * 1 `Christian Osendorfer `_ + * 1 `Christian Osendorfer`_ @@ -1237,10 +3083,10 @@ Examples -------- - new examples using some of the mlcomp datasets: - :ref:`example_mlcomp_sparse_document_classification.py`, - :ref:`example_document_classification_20newsgroups.py` + ``example_mlcomp_sparse_document_classification.py`` (since removed) and + :ref:`example_text_document_classification_20newsgroups.py` - - Many more examaples. `See here + - Many more examples. `See here `_ the full list of examples. @@ -1248,7 +3094,7 @@ Examples External dependencies --------------------- - - Joblib is now a dependencie of this package, although it is + - Joblib is now a dependency of this package, although it is shipped with (sklearn.externals.joblib). Removed modules @@ -1267,7 +3113,7 @@ Misc Authors ------- -The following is a list of authors for this release, preceeded by +The following is a list of authors for this release, preceded by number of commits: * 262 Fabian Pedregosa @@ -1307,11 +3153,11 @@ Major changes in this release include: - feature_selection module redesign. - - Migration to GIT as content management system. + - Migration to GIT as version control system. - Removal of obsolete attrselect module. - - Rename of private compiled extensions (aded underscore). + - Rename of private compiled extensions (added underscore). - Removal of legacy unmaintained code. @@ -1341,6 +3187,11 @@ of commits): * 1 Chris Filo Gorgolewski +Earlier versions +================ + +Earlier versions included contributions by Fred Mailhot, David Cooke, +David Huard, Dave Morrill, Ed Schofield, Travis Oliphant, Pearu Peterson. .. _Olivier Grisel: http://twitter.com/ogrisel @@ -1350,7 +3201,7 @@ of commits): .. _Fabian Pedregosa: http://fseoane.net/blog/ -.. _Mathieu Blondel: http://www.mblondel.org/journal/ +.. _Mathieu Blondel: http://www.mblondel.org .. _James Bergstra: http://www-etud.iro.umontreal.ca/~bergstrj/ @@ -1402,3 +3253,120 @@ of commits): .. _@kernc: http://github.com/kernc +.. _Christian Osendorfer: http://osdf.github.com + +.. _Noel Dawe: http://noel.dawe.me + +.. _Arnaud Joly: http://www.ajoly.org + +.. _Rob Zinkov: http://zinkov.com + +.. _Martin Luessi: https://github.com/mluessi + +.. _Joel Nothman: http://joelnothman.com + +.. _Norbert Crombach: https://github.com/norbert + +.. _Eustache Diemert: https://github.com/oddskool + +.. _Justin Vincent: https://github.com/justinvf + +.. _Denis Engemann: https://github.com/dengemann + +.. _Nicolas Trésegnie : http://nicolastr.com/ + +.. _Kemal Eren: http://www.kemaleren.com + +.. _Yann Dauphin: http://ynd.github.io/ + +.. _Nelle Varoquaux: https://github.com/nellev + +.. _Subhodeep Moitra: https://github.com/smoitra87 + +.. _Yannick Schwartz: https://team.inria.fr/parietal/schwarty/ + +.. _Mikhail Korobov: http://kmike.ru/pages/about/ + +.. _Kyle Kastner: http://kastnerkyle.github.io + +.. _@FedericoV: https://github.com/FedericoV/ + +.. _Daniel Nouri: http://danielnouri.org + +.. _Johannes Schönberger: https://github.com/ahojnnes + +.. _Manoj Kumar: https://manojbits.wordpress.com + +.. _Maheshakya Wijewardena: https://github.com/maheshakya + +.. _Danny Sullivan: https://github.com/dsullivan7 + +.. _Michael Eickenberg: https://github.com/eickenberg + +.. _Jeffrey Blackburne: https://github.com/jblackburne + +.. _Hamzeh Alsalhi: https://github.com/hamsal + +.. _Ronald Phlypo: https://github.com/rphlypo + +.. _Laurent Direr: https://github.com/ldirer + +.. _Nikolay Mayorov: https://github.com/nmayorov + +.. _Jatin Shah: http://jatinshah.org/ + +.. _Dougal Sutherland: https://github.com/dougalsutherland + +.. _Michal Romaniuk: https://github.com/romaniukm + +.. _Ian Gilmore: https://github.com/agileminor + +.. _Aaron Staple: https://github.com/staple + +.. _Luis Pedro Coelho: http://luispedro.org + +.. _Florian Wilhelm: https://github.com/FlorianWilhelm + +.. _Fares Hedyati: https://github.com/fareshedyati + +.. _Matt Pico: https://github.com/MattpSoftware + +.. _Matt Terry: https://github.com/mrterry + +.. _Antony Lee: https://www.ocf.berkeley.edu/~antonyl/ + +.. _Clemens Brunner: https://github.com/cle1109 + +.. _Martin Billinger: https://github.com/kazemakase + +.. _Matteo Visconti di Oleggio Castello: http://www.mvdoc.me + +.. _Raghav R V: https://github.com/ragv + +.. _Trevor Stephens: http://trevorstephens.com/ + +.. _Jan Hendrik Metzen: https://jmetzen.github.io/ + +.. _Cathy Deng: https://github.com/cathydeng + +.. _Will Dawson: http://dawsonresearch.com + +.. _Balazs Kegl: https://github.com/kegl + +.. _Andrew Tulloch: http://tullo.ch/ + +.. _Alexis Mignon: https://github.com/AlexisMignon + +.. _Hasil Sharma: https://github.com/Hasil-Sharma + +.. _Hanna Wallach: http://dirichlet.net/ + +.. _Yan Yi: http://www.seowyanyi.org + +.. _Kyle Beauchamp: https://github.com/kyleabeauchamp + +.. _Hervé Bredin: http://herve.niderb.fr/ + +.. _Eric Schubert: https://github.com/kno10 + +.. _Dan Blanchard: https://github.com/dan-blanchard diff --git a/examples/applications/face_recognition.py b/examples/applications/face_recognition.py index 591d6d904f733..c261b979f9017 100644 --- a/examples/applications/face_recognition.py +++ b/examples/applications/face_recognition.py @@ -25,11 +25,11 @@ """ -print __doc__ +from __future__ import print_function from time import time import logging -import pylab as pl +import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split from sklearn.datasets import fetch_lfw_people @@ -39,6 +39,9 @@ from sklearn.decomposition import RandomizedPCA from sklearn.svm import SVC + +print(__doc__) + # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') @@ -51,7 +54,7 @@ # introspect the images arrays to find the shapes (for plotting) n_samples, h, w = lfw_people.images.shape -# fot machine learning we use the 2 data directly (as relative pixel +# for machine learning we use the 2 data directly (as relative pixel # positions info is ignored by this model) X = lfw_people.data n_features = X.shape[1] @@ -61,10 +64,10 @@ target_names = lfw_people.target_names n_classes = target_names.shape[0] -print "Total dataset size:" -print "n_samples: %d" % n_samples -print "n_features: %d" % n_features -print "n_classes: %d" % n_classes +print("Total dataset size:") +print("n_samples: %d" % n_samples) +print("n_features: %d" % n_features) +print("n_classes: %d" % n_classes) ############################################################################### @@ -72,7 +75,7 @@ # split into a training and testing set X_train, X_test, y_train, y_test = train_test_split( - X, y, test_fraction=0.25) + X, y, test_size=0.25) ############################################################################### @@ -80,47 +83,45 @@ # dataset): unsupervised feature extraction / dimensionality reduction n_components = 150 -print "Extracting the top %d eigenfaces from %d faces" % ( - n_components, X_train.shape[0]) +print("Extracting the top %d eigenfaces from %d faces" + % (n_components, X_train.shape[0])) t0 = time() pca = RandomizedPCA(n_components=n_components, whiten=True).fit(X_train) -print "done in %0.3fs" % (time() - t0) +print("done in %0.3fs" % (time() - t0)) eigenfaces = pca.components_.reshape((n_components, h, w)) -print "Projecting the input data on the eigenfaces orthonormal basis" +print("Projecting the input data on the eigenfaces orthonormal basis") t0 = time() X_train_pca = pca.transform(X_train) X_test_pca = pca.transform(X_test) -print "done in %0.3fs" % (time() - t0) +print("done in %0.3fs" % (time() - t0)) ############################################################################### # Train a SVM classification model -print "Fitting the classifier to the training set" +print("Fitting the classifier to the training set") t0 = time() -param_grid = { - 'C': [1e3, 5e3, 1e4, 5e4, 1e5], - 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], -} +param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5], + 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], } clf = GridSearchCV(SVC(kernel='rbf', class_weight='auto'), param_grid) clf = clf.fit(X_train_pca, y_train) -print "done in %0.3fs" % (time() - t0) -print "Best estimator found by grid search:" -print clf.best_estimator_ +print("done in %0.3fs" % (time() - t0)) +print("Best estimator found by grid search:") +print(clf.best_estimator_) ############################################################################### # Quantitative evaluation of the model quality on the test set -print "Predicting the people names on the testing set" +print("Predicting people's names on the test set") t0 = time() y_pred = clf.predict(X_test_pca) -print "done in %0.3fs" % (time() - t0) +print("done in %0.3fs" % (time() - t0)) -print classification_report(y_test, y_pred, target_names=target_names) -print confusion_matrix(y_test, y_pred, labels=range(n_classes)) +print(classification_report(y_test, y_pred, target_names=target_names)) +print(confusion_matrix(y_test, y_pred, labels=range(n_classes))) ############################################################################### @@ -128,14 +129,14 @@ def plot_gallery(images, titles, h, w, n_row=3, n_col=4): """Helper function to plot a gallery of portraits""" - pl.figure(figsize=(1.8 * n_col, 2.4 * n_row)) - pl.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35) + plt.figure(figsize=(1.8 * n_col, 2.4 * n_row)) + plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35) for i in range(n_row * n_col): - pl.subplot(n_row, n_col, i + 1) - pl.imshow(images[i].reshape((h, w)), cmap=pl.cm.gray) - pl.title(titles[i], size=12) - pl.xticks(()) - pl.yticks(()) + plt.subplot(n_row, n_col, i + 1) + plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray) + plt.title(titles[i], size=12) + plt.xticks(()) + plt.yticks(()) # plot the result of the prediction on a portion of the test set @@ -155,4 +156,4 @@ def title(y_pred, y_test, target_names, i): eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])] plot_gallery(eigenfaces, eigenface_titles, h, w) -pl.show() +plt.show() diff --git a/examples/applications/plot_model_complexity_influence.py b/examples/applications/plot_model_complexity_influence.py new file mode 100644 index 0000000000000..90fd5c718e78f --- /dev/null +++ b/examples/applications/plot_model_complexity_influence.py @@ -0,0 +1,169 @@ +""" +========================== +Model Complexity Influence +========================== + +Demonstrate how model complexity influences both prediction accuracy and +computational performance. + +The dataset is the Boston Housing dataset (resp. 20 Newsgroups) for +regression (resp. classification). + +For each class of models we make the model complexity vary through the choice +of relevant model parameters and measure the influence on both computational +performance (latency) and predictive power (MSE or Hamming Loss). +""" + +print(__doc__) + +# Author: Eustache Diemert +# License: BSD 3 clause + +import time +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.axes_grid1.parasite_axes import host_subplot +from mpl_toolkits.axisartist.axislines import Axes +from scipy.sparse.csr import csr_matrix + +from sklearn import datasets +from sklearn.utils import shuffle +from sklearn.metrics import mean_squared_error +from sklearn.svm.classes import NuSVR +from sklearn.ensemble.gradient_boosting import GradientBoostingRegressor +from sklearn.linear_model.stochastic_gradient import SGDClassifier +from sklearn.metrics import hamming_loss + +############################################################################### +# Routines + + +# initialize random generator +np.random.seed(0) + + +def generate_data(case, sparse=False): + """Generate regression/classification data.""" + bunch = None + if case == 'regression': + bunch = datasets.load_boston() + elif case == 'classification': + bunch = datasets.fetch_20newsgroups_vectorized(subset='all') + X, y = shuffle(bunch.data, bunch.target) + offset = int(X.shape[0] * 0.8) + X_train, y_train = X[:offset], y[:offset] + X_test, y_test = X[offset:], y[offset:] + if sparse: + X_train = csr_matrix(X_train) + X_test = csr_matrix(X_test) + else: + X_train = np.array(X_train) + X_test = np.array(X_test) + y_test = np.array(y_test) + y_train = np.array(y_train) + data = {'X_train': X_train, 'X_test': X_test, 'y_train': y_train, + 'y_test': y_test} + return data + + +def benchmark_influence(conf): + """ + Benchmark influence of :changing_param: on both MSE and latency. + """ + prediction_times = [] + prediction_powers = [] + complexities = [] + for param_value in conf['changing_param_values']: + conf['tuned_params'][conf['changing_param']] = param_value + estimator = conf['estimator'](**conf['tuned_params']) + print("Benchmarking %s" % estimator) + estimator.fit(conf['data']['X_train'], conf['data']['y_train']) + conf['postfit_hook'](estimator) + complexity = conf['complexity_computer'](estimator) + complexities.append(complexity) + start_time = time.time() + for _ in range(conf['n_samples']): + y_pred = estimator.predict(conf['data']['X_test']) + elapsed_time = (time.time() - start_time) / float(conf['n_samples']) + prediction_times.append(elapsed_time) + pred_score = conf['prediction_performance_computer']( + conf['data']['y_test'], y_pred) + prediction_powers.append(pred_score) + print("Complexity: %d | %s: %.4f | Pred. Time: %fs\n" % ( + complexity, conf['prediction_performance_label'], pred_score, + elapsed_time)) + return prediction_powers, prediction_times, complexities + + +def plot_influence(conf, mse_values, prediction_times, complexities): + """ + Plot influence of model complexity on both accuracy and latency. + """ + plt.figure(figsize=(12, 6)) + host = host_subplot(111, axes_class=Axes) + plt.subplots_adjust(right=0.75) + par1 = host.twinx() + host.set_xlabel('Model Complexity (%s)' % conf['complexity_label']) + y1_label = conf['prediction_performance_label'] + y2_label = "Time (s)" + host.set_ylabel(y1_label) + par1.set_ylabel(y2_label) + p1, = host.plot(complexities, mse_values, 'b-', label="prediction error") + p2, = par1.plot(complexities, prediction_times, 'r-', + label="latency") + host.legend(loc='upper right') + host.axis["left"].label.set_color(p1.get_color()) + par1.axis["right"].label.set_color(p2.get_color()) + plt.title('Influence of Model Complexity - %s' % conf['estimator'].__name__) + plt.show() + + +def _count_nonzero_coefficients(estimator): + a = estimator.coef_.toarray() + return np.count_nonzero(a) + +############################################################################### +# main code +regression_data = generate_data('regression') +classification_data = generate_data('classification', sparse=True) +configurations = [ + {'estimator': SGDClassifier, + 'tuned_params': {'penalty': 'elasticnet', 'alpha': 0.001, 'loss': + 'modified_huber', 'fit_intercept': True}, + 'changing_param': 'l1_ratio', + 'changing_param_values': [0.25, 0.5, 0.75, 0.9], + 'complexity_label': 'non_zero coefficients', + 'complexity_computer': _count_nonzero_coefficients, + 'prediction_performance_computer': hamming_loss, + 'prediction_performance_label': 'Hamming Loss (Misclassification Ratio)', + 'postfit_hook': lambda x: x.sparsify(), + 'data': classification_data, + 'n_samples': 30}, + {'estimator': NuSVR, + 'tuned_params': {'C': 1e3, 'gamma': 2 ** -15}, + 'changing_param': 'nu', + 'changing_param_values': [0.1, 0.25, 0.5, 0.75, 0.9], + 'complexity_label': 'n_support_vectors', + 'complexity_computer': lambda x: len(x.support_vectors_), + 'data': regression_data, + 'postfit_hook': lambda x: x, + 'prediction_performance_computer': mean_squared_error, + 'prediction_performance_label': 'MSE', + 'n_samples': 30}, + {'estimator': GradientBoostingRegressor, + 'tuned_params': {'loss': 'ls'}, + 'changing_param': 'n_estimators', + 'changing_param_values': [10, 50, 100, 200, 500], + 'complexity_label': 'n_trees', + 'complexity_computer': lambda x: x.n_estimators, + 'data': regression_data, + 'postfit_hook': lambda x: x, + 'prediction_performance_computer': mean_squared_error, + 'prediction_performance_label': 'MSE', + 'n_samples': 30}, +] +for conf in configurations: + prediction_performances, prediction_times, complexities = \ + benchmark_influence(conf) + plot_influence(conf, prediction_performances, prediction_times, + complexities) diff --git a/examples/applications/plot_out_of_core_classification.py b/examples/applications/plot_out_of_core_classification.py new file mode 100644 index 0000000000000..ab26429577a97 --- /dev/null +++ b/examples/applications/plot_out_of_core_classification.py @@ -0,0 +1,415 @@ +""" +====================================================== +Out-of-core classification of text documents +====================================================== + +This is an example showing how scikit-learn can be used for classification +using an out-of-core approach: learning from data that doesn't fit into main +memory. We make use of an online classifier, i.e., one that supports the +partial_fit method, that will be fed with batches of examples. To guarantee +that the features space remains the same over time we leverage a +HashingVectorizer that will project each example into the same feature space. +This is especially useful in the case of text classification where new +features (words) may appear in each batch. + +The dataset used in this example is Reuters-21578 as provided by the UCI ML +repository. It will be automatically downloaded and uncompressed on first run. + +The plot represents the learning curve of the classifier: the evolution +of classification accuracy over the course of the mini-batches. Accuracy is +measured on the first 1000 samples, held out as a validation set. + +To limit the memory consumption, we queue examples up to a fixed amount before +feeding them to the learner. +""" + +# Authors: Eustache Diemert +# @FedericoV +# License: BSD 3 clause + +from __future__ import print_function + +from glob import glob +import itertools +import os.path +import re +import tarfile +import time + +import numpy as np +import matplotlib.pyplot as plt +from matplotlib import rcParams + +from sklearn.externals.six.moves import html_parser +from sklearn.externals.six.moves import urllib +from sklearn.datasets import get_data_home +from sklearn.feature_extraction.text import HashingVectorizer +from sklearn.linear_model import SGDClassifier +from sklearn.linear_model import PassiveAggressiveClassifier +from sklearn.linear_model import Perceptron +from sklearn.naive_bayes import MultinomialNB + + +def _not_in_sphinx(): + # Hack to detect whether we are running by the sphinx builder + return '__file__' in globals() + + +############################################################################### +# Reuters Dataset related routines +############################################################################### + + +class ReutersParser(html_parser.HTMLParser): + """Utility class to parse a SGML file and yield documents one at a time.""" + + def __init__(self, encoding='latin-1'): + html_parser.HTMLParser.__init__(self) + self._reset() + self.encoding = encoding + + def handle_starttag(self, tag, attrs): + method = 'start_' + tag + getattr(self, method, lambda x: None)(attrs) + + def handle_endtag(self, tag): + method = 'end_' + tag + getattr(self, method, lambda: None)() + + def _reset(self): + self.in_title = 0 + self.in_body = 0 + self.in_topics = 0 + self.in_topic_d = 0 + self.title = "" + self.body = "" + self.topics = [] + self.topic_d = "" + + def parse(self, fd): + self.docs = [] + for chunk in fd: + self.feed(chunk.decode(self.encoding)) + for doc in self.docs: + yield doc + self.docs = [] + self.close() + + def handle_data(self, data): + if self.in_body: + self.body += data + elif self.in_title: + self.title += data + elif self.in_topic_d: + self.topic_d += data + + def start_reuters(self, attributes): + pass + + def end_reuters(self): + self.body = re.sub(r'\s+', r' ', self.body) + self.docs.append({'title': self.title, + 'body': self.body, + 'topics': self.topics}) + self._reset() + + def start_title(self, attributes): + self.in_title = 1 + + def end_title(self): + self.in_title = 0 + + def start_body(self, attributes): + self.in_body = 1 + + def end_body(self): + self.in_body = 0 + + def start_topics(self, attributes): + self.in_topics = 1 + + def end_topics(self): + self.in_topics = 0 + + def start_d(self, attributes): + self.in_topic_d = 1 + + def end_d(self): + self.in_topic_d = 0 + self.topics.append(self.topic_d) + self.topic_d = "" + + +def stream_reuters_documents(data_path=None): + """Iterate over documents of the Reuters dataset. + + The Reuters archive will automatically be downloaded and uncompressed if + the `data_path` directory does not exist. + + Documents are represented as dictionaries with 'body' (str), + 'title' (str), 'topics' (list(str)) keys. + + """ + + DOWNLOAD_URL = ('http://archive.ics.uci.edu/ml/machine-learning-databases/' + 'reuters21578-mld/reuters21578.tar.gz') + ARCHIVE_FILENAME = 'reuters21578.tar.gz' + + if data_path is None: + data_path = os.path.join(get_data_home(), "reuters") + if not os.path.exists(data_path): + """Download the dataset.""" + print("downloading dataset (once and for all) into %s" % + data_path) + os.mkdir(data_path) + + def progress(blocknum, bs, size): + total_sz_mb = '%.2f MB' % (size / 1e6) + current_sz_mb = '%.2f MB' % ((blocknum * bs) / 1e6) + if _not_in_sphinx(): + print('\rdownloaded %s / %s' % (current_sz_mb, total_sz_mb), + end='') + + archive_path = os.path.join(data_path, ARCHIVE_FILENAME) + urllib.request.urlretrieve(DOWNLOAD_URL, filename=archive_path, + reporthook=progress) + if _not_in_sphinx(): + print('\r', end='') + print("untarring Reuters dataset...") + tarfile.open(archive_path, 'r:gz').extractall(data_path) + print("done.") + + parser = ReutersParser() + for filename in glob(os.path.join(data_path, "*.sgm")): + for doc in parser.parse(open(filename, 'rb')): + yield doc + + +############################################################################### +# Main +############################################################################### +# Create the vectorizer and limit the number of features to a reasonable +# maximum +vectorizer = HashingVectorizer(decode_error='ignore', n_features=2 ** 18, + non_negative=True) + + +# Iterator over parsed Reuters SGML files. +data_stream = stream_reuters_documents() + +# We learn a binary classification between the "acq" class and all the others. +# "acq" was chosen as it is more or less evenly distributed in the Reuters +# files. For other datasets, one should take care of creating a test set with +# a realistic portion of positive instances. +all_classes = np.array([0, 1]) +positive_class = 'acq' + +# Here are some classifiers that support the `partial_fit` method +partial_fit_classifiers = { + 'SGD': SGDClassifier(), + 'Perceptron': Perceptron(), + 'NB Multinomial': MultinomialNB(alpha=0.01), + 'Passive-Aggressive': PassiveAggressiveClassifier(), +} + + +def get_minibatch(doc_iter, size, pos_class=positive_class): + """Extract a minibatch of examples, return a tuple X_text, y. + + Note: size is before excluding invalid docs with no topics assigned. + + """ + data = [(u'{title}\n\n{body}'.format(**doc), pos_class in doc['topics']) + for doc in itertools.islice(doc_iter, size) + if doc['topics']] + if not len(data): + return np.asarray([], dtype=int), np.asarray([], dtype=int) + X_text, y = zip(*data) + return X_text, np.asarray(y, dtype=int) + + +def iter_minibatches(doc_iter, minibatch_size): + """Generator of minibatches.""" + X_text, y = get_minibatch(doc_iter, minibatch_size) + while len(X_text): + yield X_text, y + X_text, y = get_minibatch(doc_iter, minibatch_size) + + +# test data statistics +test_stats = {'n_test': 0, 'n_test_pos': 0} + +# First we hold out a number of examples to estimate accuracy +n_test_documents = 1000 +tick = time.time() +X_test_text, y_test = get_minibatch(data_stream, 1000) +parsing_time = time.time() - tick +tick = time.time() +X_test = vectorizer.transform(X_test_text) +vectorizing_time = time.time() - tick +test_stats['n_test'] += len(y_test) +test_stats['n_test_pos'] += sum(y_test) +print("Test set is %d documents (%d positive)" % (len(y_test), sum(y_test))) + + +def progress(cls_name, stats): + """Report progress information, return a string.""" + duration = time.time() - stats['t0'] + s = "%20s classifier : \t" % cls_name + s += "%(n_train)6d train docs (%(n_train_pos)6d positive) " % stats + s += "%(n_test)6d test docs (%(n_test_pos)6d positive) " % test_stats + s += "accuracy: %(accuracy).3f " % stats + s += "in %.2fs (%5d docs/s)" % (duration, stats['n_train'] / duration) + return s + + +cls_stats = {} + +for cls_name in partial_fit_classifiers: + stats = {'n_train': 0, 'n_train_pos': 0, + 'accuracy': 0.0, 'accuracy_history': [(0, 0)], 't0': time.time(), + 'runtime_history': [(0, 0)], 'total_fit_time': 0.0} + cls_stats[cls_name] = stats + +get_minibatch(data_stream, n_test_documents) +# Discard test set + +# We will feed the classifier with mini-batches of 1000 documents; this means +# we have at most 1000 docs in memory at any time. The smaller the document +# batch, the bigger the relative overhead of the partial fit methods. +minibatch_size = 1000 + +# Create the data_stream that parses Reuters SGML files and iterates on +# documents as a stream. +minibatch_iterators = iter_minibatches(data_stream, minibatch_size) +total_vect_time = 0.0 + +# Main loop : iterate on mini-batchs of examples +for i, (X_train_text, y_train) in enumerate(minibatch_iterators): + + tick = time.time() + X_train = vectorizer.transform(X_train_text) + total_vect_time += time.time() - tick + + for cls_name, cls in partial_fit_classifiers.items(): + tick = time.time() + # update estimator with examples in the current mini-batch + cls.partial_fit(X_train, y_train, classes=all_classes) + + # accumulate test accuracy stats + cls_stats[cls_name]['total_fit_time'] += time.time() - tick + cls_stats[cls_name]['n_train'] += X_train.shape[0] + cls_stats[cls_name]['n_train_pos'] += sum(y_train) + tick = time.time() + cls_stats[cls_name]['accuracy'] = cls.score(X_test, y_test) + cls_stats[cls_name]['prediction_time'] = time.time() - tick + acc_history = (cls_stats[cls_name]['accuracy'], + cls_stats[cls_name]['n_train']) + cls_stats[cls_name]['accuracy_history'].append(acc_history) + run_history = (cls_stats[cls_name]['accuracy'], + total_vect_time + cls_stats[cls_name]['total_fit_time']) + cls_stats[cls_name]['runtime_history'].append(run_history) + + if i % 3 == 0: + print(progress(cls_name, cls_stats[cls_name])) + if i % 3 == 0: + print('\n') + + +############################################################################### +# Plot results +############################################################################### + + +def plot_accuracy(x, y, x_legend): + """Plot accuracy as a function of x.""" + x = np.array(x) + y = np.array(y) + plt.title('Classification accuracy as a function of %s' % x_legend) + plt.xlabel('%s' % x_legend) + plt.ylabel('Accuracy') + plt.grid(True) + plt.plot(x, y) + +rcParams['legend.fontsize'] = 10 +cls_names = list(sorted(cls_stats.keys())) + +# Plot accuracy evolution +plt.figure() +for _, stats in sorted(cls_stats.items()): + # Plot accuracy evolution with #examples + accuracy, n_examples = zip(*stats['accuracy_history']) + plot_accuracy(n_examples, accuracy, "training examples (#)") + ax = plt.gca() + ax.set_ylim((0.8, 1)) +plt.legend(cls_names, loc='best') + +plt.figure() +for _, stats in sorted(cls_stats.items()): + # Plot accuracy evolution with runtime + accuracy, runtime = zip(*stats['runtime_history']) + plot_accuracy(runtime, accuracy, 'runtime (s)') + ax = plt.gca() + ax.set_ylim((0.8, 1)) +plt.legend(cls_names, loc='best') + +# Plot fitting times +plt.figure() +fig = plt.gcf() +cls_runtime = [] +for cls_name, stats in sorted(cls_stats.items()): + cls_runtime.append(stats['total_fit_time']) + +cls_runtime.append(total_vect_time) +cls_names.append('Vectorization') +bar_colors = rcParams['axes.color_cycle'][:len(cls_names)] + +ax = plt.subplot(111) +rectangles = plt.bar(range(len(cls_names)), cls_runtime, width=0.5, + color=bar_colors) + +ax.set_xticks(np.linspace(0.25, len(cls_names) - 0.75, len(cls_names))) +ax.set_xticklabels(cls_names, fontsize=10) +ymax = max(cls_runtime) * 1.2 +ax.set_ylim((0, ymax)) +ax.set_ylabel('runtime (s)') +ax.set_title('Training Times') + + +def autolabel(rectangles): + """attach some text vi autolabel on rectangles.""" + for rect in rectangles: + height = rect.get_height() + ax.text(rect.get_x() + rect.get_width() / 2., + 1.05 * height, '%.4f' % height, + ha='center', va='bottom') + +autolabel(rectangles) +plt.show() + +# Plot prediction times +plt.figure() +#fig = plt.gcf() +cls_runtime = [] +cls_names = list(sorted(cls_stats.keys())) +for cls_name, stats in sorted(cls_stats.items()): + cls_runtime.append(stats['prediction_time']) +cls_runtime.append(parsing_time) +cls_names.append('Read/Parse\n+Feat.Extr.') +cls_runtime.append(vectorizing_time) +cls_names.append('Hashing\n+Vect.') +bar_colors = rcParams['axes.color_cycle'][:len(cls_names)] + +ax = plt.subplot(111) +rectangles = plt.bar(range(len(cls_names)), cls_runtime, width=0.5, + color=bar_colors) + +ax.set_xticks(np.linspace(0.25, len(cls_names) - 0.75, len(cls_names))) +ax.set_xticklabels(cls_names, fontsize=8) +plt.setp(plt.xticks()[1], rotation=30) +ymax = max(cls_runtime) * 1.2 +ax.set_ylim((0, ymax)) +ax.set_ylabel('runtime (s)') +ax.set_title('Prediction Times (%d instances)' % n_test_documents) +autolabel(rectangles) +plt.show() diff --git a/examples/applications/plot_outlier_detection_housing.py b/examples/applications/plot_outlier_detection_housing.py index a320e58dd2c49..0497d4b1a4bd7 100644 --- a/examples/applications/plot_outlier_detection_housing.py +++ b/examples/applications/plot_outlier_detection_housing.py @@ -7,9 +7,9 @@ on a real data set. It is useful both for outlier detection and for a better understanding of the data structure. -We selected two sets of two variables from the boston housing data set +We selected two sets of two variables from the Boston housing data set as an illustration of what kind of analysis can be done with several -outlier detection tools. For the purpose of vizualisation, we are working +outlier detection tools. For the purpose of visualization, we are working with two-dimensional examples, but one should be aware that things are not so trivial in high-dimension, as it will be pointed out. @@ -40,15 +40,15 @@ is hard to estimate due to the banana-shaped distribution. Anyway, we can get rid of some outlying observations. The One-Class SVM is able to capture the real data structure, but the -difficulty is to adjust its kernel bandwith parameter so as to obtain +difficulty is to adjust its kernel bandwidth parameter so as to obtain a good compromise between the shape of the data scatter matrix and the risk of over-fitting the data. """ -print __doc__ +print(__doc__) # Author: Virgile Fritsch -# License: BSD +# License: BSD 3 clause import numpy as np from sklearn.covariance import EllipticEnvelope @@ -64,9 +64,9 @@ # Define "classifiers" to be used classifiers = { "Empirical Covariance": EllipticEnvelope(support_fraction=1., - contamination=0.261), + contamination=0.261), "Robust Covariance (Minimum Covariance Determinant)": - EllipticEnvelope(contamination=0.261), + EllipticEnvelope(contamination=0.261), "OCSVM": OneClassSVM(nu=0.261, gamma=0.05)} colors = ['m', 'g', 'b'] legend1 = {} @@ -75,7 +75,7 @@ # Learn a frontier for outlier detection with several classifiers xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500)) xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 500)) -for i, (clf_name, clf) in enumerate(classifiers.iteritems()): +for i, (clf_name, clf) in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) @@ -89,6 +89,9 @@ legend2[clf_name] = plt.contour( xx2, yy2, Z2, levels=[0], linewidths=2, colors=colors[i]) +legend1_values_list = list( legend1.values() ) +legend1_keys_list = list( legend1.keys() ) + # Plot the results (= shape of the data points cloud) plt.figure(1) # two clusters plt.title("Outlier detection on a real data set (boston housing)") @@ -100,24 +103,27 @@ xytext=(13, 10), bbox=bbox_args, arrowprops=arrow_args) plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max())) -plt.legend((legend1.values()[0].collections[0], - legend1.values()[1].collections[0], - legend1.values()[2].collections[0]), - (legend1.keys()[0], legend1.keys()[1], legend1.keys()[2]), +plt.legend((legend1_values_list[0].collections[0], + legend1_values_list[1].collections[0], + legend1_values_list[2].collections[0]), + (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc="upper center", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel("accessibility to radial highways") plt.xlabel("pupil-teatcher ratio by town") +legend2_values_list = list( legend2.values() ) +legend2_keys_list = list( legend2.keys() ) + plt.figure(2) # "banana" shape plt.title("Outlier detection on a real data set (boston housing)") plt.scatter(X2[:, 0], X2[:, 1], color='black') plt.xlim((xx2.min(), xx2.max())) plt.ylim((yy2.min(), yy2.max())) -plt.legend((legend2.values()[0].collections[0], - legend2.values()[1].collections[0], - legend2.values()[2].collections[0]), - (legend2.keys()[0], legend2.keys()[1], legend2.keys()[2]), +plt.legend((legend2_values_list[0].collections[0], + legend2_values_list[1].collections[0], + legend2_values_list[2].collections[0]), + (legend2_values_list[0], legend2_values_list[1], legend2_values_list[2]), loc="upper center", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel("% lower status of the population") diff --git a/examples/applications/plot_prediction_latency.py b/examples/applications/plot_prediction_latency.py new file mode 100644 index 0000000000000..0d401b2f0ed34 --- /dev/null +++ b/examples/applications/plot_prediction_latency.py @@ -0,0 +1,312 @@ +""" +================== +Prediction Latency +================== + +This is an example showing the prediction latency of various scikit-learn +estimators. + +The goal is to measure the latency one can expect when doing predictions +either in bulk or atomic (i.e. one by one) mode. + +The plots represent the distribution of the prediction latency as a boxplot. + +""" + +# Authors: Eustache Diemert +# License: BSD 3 clause + +from __future__ import print_function +from collections import defaultdict + +import time +import gc +import numpy as np +import matplotlib.pyplot as plt + +from scipy.stats import scoreatpercentile +from sklearn.datasets.samples_generator import make_regression +from sklearn.ensemble.forest import RandomForestRegressor +from sklearn.linear_model.ridge import Ridge +from sklearn.linear_model.stochastic_gradient import SGDRegressor +from sklearn.svm.classes import SVR + + +def _not_in_sphinx(): + # Hack to detect whether we are running by the sphinx builder + return '__file__' in globals() + + +def atomic_benchmark_estimator(estimator, X_test, verbose=False): + """Measure runtime prediction of each instance.""" + n_instances = X_test.shape[0] + runtimes = np.zeros(n_instances, dtype=np.float) + for i in range(n_instances): + instance = X_test[i, :] + start = time.time() + estimator.predict(instance) + runtimes[i] = time.time() - start + if verbose: + print("atomic_benchmark runtimes:", min(runtimes), scoreatpercentile( + runtimes, 50), max(runtimes)) + return runtimes + + +def bulk_benchmark_estimator(estimator, X_test, n_bulk_repeats, verbose): + """Measure runtime prediction of the whole input.""" + n_instances = X_test.shape[0] + runtimes = np.zeros(n_bulk_repeats, dtype=np.float) + for i in range(n_bulk_repeats): + start = time.time() + estimator.predict(X_test) + runtimes[i] = time.time() - start + runtimes = np.array(list(map(lambda x: x / float(n_instances), runtimes))) + if verbose: + print("bulk_benchmark runtimes:", min(runtimes), scoreatpercentile( + runtimes, 50), max(runtimes)) + return runtimes + + +def benchmark_estimator(estimator, X_test, n_bulk_repeats=30, verbose=False): + """ + Measure runtimes of prediction in both atomic and bulk mode. + + Parameters + ---------- + estimator : already trained estimator supporting `predict()` + X_test : test input + n_bulk_repeats : how many times to repeat when evaluating bulk mode + + Returns + ------- + atomic_runtimes, bulk_runtimes : a pair of `np.array` which contain the + runtimes in seconds. + + """ + atomic_runtimes = atomic_benchmark_estimator(estimator, X_test, verbose) + bulk_runtimes = bulk_benchmark_estimator(estimator, X_test, n_bulk_repeats, + verbose) + return atomic_runtimes, bulk_runtimes + + +def generate_dataset(n_train, n_test, n_features, noise=0.1, verbose=False): + """Generate a regression dataset with the given parameters.""" + if verbose: + print("generating dataset...") + X, y, coef = make_regression(n_samples=n_train + n_test, + n_features=n_features, noise=noise, coef=True) + X_train = X[:n_train] + y_train = y[:n_train] + X_test = X[n_train:] + y_test = y[n_train:] + idx = np.arange(n_train) + np.random.seed(13) + np.random.shuffle(idx) + X_train = X_train[idx] + y_train = y_train[idx] + + std = X_train.std(axis=0) + mean = X_train.mean(axis=0) + X_train = (X_train - mean) / std + X_test = (X_test - mean) / std + + std = y_train.std(axis=0) + mean = y_train.mean(axis=0) + y_train = (y_train - mean) / std + y_test = (y_test - mean) / std + + gc.collect() + if verbose: + print("ok") + return X_train, y_train, X_test, y_test + + +def boxplot_runtimes(runtimes, pred_type, configuration): + """ + Plot a new `Figure` with boxplots of prediction runtimes. + + Parameters + ---------- + runtimes : list of `np.array` of latencies in micro-seconds + cls_names : list of estimator class names that generated the runtimes + pred_type : 'bulk' or 'atomic' + + """ + + fig, ax1 = plt.subplots(figsize=(10, 6)) + bp = plt.boxplot(runtimes, ) + + cls_infos = ['%s\n(%d %s)' % (estimator_conf['name'], + estimator_conf['complexity_computer']( + estimator_conf['instance']), + estimator_conf['complexity_label']) for + estimator_conf in configuration['estimators']] + plt.setp(ax1, xticklabels=cls_infos) + plt.setp(bp['boxes'], color='black') + plt.setp(bp['whiskers'], color='black') + plt.setp(bp['fliers'], color='red', marker='+') + + ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', + alpha=0.5) + + ax1.set_axisbelow(True) + ax1.set_title('Prediction Time per Instance - %s, %d feats.' % ( + pred_type.capitalize(), + configuration['n_features'])) + ax1.set_ylabel('Prediction Time (us)') + + plt.show() + + +def benchmark(configuration): + """Run the whole benchmark.""" + X_train, y_train, X_test, y_test = generate_dataset( + configuration['n_train'], configuration['n_test'], + configuration['n_features']) + + stats = {} + for estimator_conf in configuration['estimators']: + print("Benchmarking", estimator_conf['instance']) + estimator_conf['instance'].fit(X_train, y_train) + gc.collect() + a, b = benchmark_estimator(estimator_conf['instance'], X_test) + stats[estimator_conf['name']] = {'atomic': a, 'bulk': b} + + cls_names = [estimator_conf['name'] for estimator_conf in configuration[ + 'estimators']] + runtimes = [1e6 * stats[clf_name]['atomic'] for clf_name in cls_names] + boxplot_runtimes(runtimes, 'atomic', configuration) + runtimes = [1e6 * stats[clf_name]['bulk'] for clf_name in cls_names] + boxplot_runtimes(runtimes, 'bulk (%d)' % configuration['n_test'], + configuration) + + +def n_feature_influence(estimators, n_train, n_test, n_features, percentile): + """ + Estimate influence of the number of features on prediction time. + + Parameters + ---------- + + estimators : dict of (name (str), estimator) to benchmark + n_train : nber of training instances (int) + n_test : nber of testing instances (int) + n_features : list of feature-space dimensionality to test (int) + percentile : percentile at which to measure the speed (int [0-100]) + + Returns: + -------- + + percentiles : dict(estimator_name, + dict(n_features, percentile_perf_in_us)) + + """ + percentiles = defaultdict(defaultdict) + for n in n_features: + print("benchmarking with %d features" % n) + X_train, y_train, X_test, y_test = generate_dataset(n_train, n_test, n) + for cls_name, estimator in estimators.items(): + estimator.fit(X_train, y_train) + gc.collect() + runtimes = bulk_benchmark_estimator(estimator, X_test, 30, False) + percentiles[cls_name][n] = 1e6 * scoreatpercentile(runtimes, + percentile) + return percentiles + + +def plot_n_features_influence(percentiles, percentile): + fig, ax1 = plt.subplots(figsize=(10, 6)) + colors = ['r', 'g', 'b'] + for i, cls_name in enumerate(percentiles.keys()): + x = np.array(sorted([n for n in percentiles[cls_name].keys()])) + y = np.array([percentiles[cls_name][n] for n in x]) + plt.plot(x, y, color=colors[i], ) + ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', + alpha=0.5) + ax1.set_axisbelow(True) + ax1.set_title('Evolution of Prediction Time with #Features') + ax1.set_xlabel('#Features') + ax1.set_ylabel('Prediction Time at %d%%-ile (us)' % percentile) + plt.show() + + +def benchmark_throughputs(configuration, duration_secs=0.1): + """benchmark throughput for different estimators.""" + X_train, y_train, X_test, y_test = generate_dataset( + configuration['n_train'], configuration['n_test'], + configuration['n_features']) + throughputs = dict() + for estimator_config in configuration['estimators']: + estimator_config['instance'].fit(X_train, y_train) + start_time = time.time() + n_predictions = 0 + while (time.time() - start_time) < duration_secs: + estimator_config['instance'].predict(X_test[0]) + n_predictions += 1 + throughputs[estimator_config['name']] = n_predictions / duration_secs + return throughputs + + +def plot_benchmark_throughput(throughputs, configuration): + fig, ax = plt.subplots(figsize=(10, 6)) + colors = ['r', 'g', 'b'] + cls_infos = ['%s\n(%d %s)' % (estimator_conf['name'], + estimator_conf['complexity_computer']( + estimator_conf['instance']), + estimator_conf['complexity_label']) for + estimator_conf in configuration['estimators']] + cls_values = [throughputs[estimator_conf['name']] for estimator_conf in + configuration['estimators']] + plt.bar(range(len(throughputs)), cls_values, width=0.5, color=colors) + ax.set_xticks(np.linspace(0.25, len(throughputs) - 0.75, len(throughputs))) + ax.set_xticklabels(cls_infos, fontsize=10) + ymax = max(cls_values) * 1.2 + ax.set_ylim((0, ymax)) + ax.set_ylabel('Throughput (predictions/sec)') + ax.set_title('Prediction Throughput for different estimators (%d ' + 'features)' % configuration['n_features']) + plt.show() + + +############################################################################### +# main code + +start_time = time.time() + +# benchmark bulk/atomic prediction speed for various regressors +configuration = { + 'n_train': int(1e3), + 'n_test': int(1e2), + 'n_features': int(1e2), + 'estimators': [ + {'name': 'Linear Model', + 'instance': SGDRegressor(penalty='elasticnet', alpha=0.01, + l1_ratio=0.25, fit_intercept=True), + 'complexity_label': 'non-zero coefficients', + 'complexity_computer': lambda clf: np.count_nonzero(clf.coef_)}, + {'name': 'RandomForest', + 'instance': RandomForestRegressor(), + 'complexity_label': 'estimators', + 'complexity_computer': lambda clf: clf.n_estimators}, + {'name': 'SVR', + 'instance': SVR(kernel='rbf'), + 'complexity_label': 'support vectors', + 'complexity_computer': lambda clf: len(clf.support_vectors_)}, + ] +} +benchmark(configuration) + +# benchmark n_features influence on prediction speed +percentile = 90 +percentiles = n_feature_influence({'ridge': Ridge()}, + configuration['n_train'], + configuration['n_test'], + [100, 250, 500], percentile) +plot_n_features_influence(percentiles, percentile) + +# benchmark throughput +throughputs = benchmark_throughputs(configuration) +plot_benchmark_throughput(throughputs, configuration) + +stop_time = time.time() +print("example run in %.2fs" % (stop_time - start_time)) diff --git a/examples/applications/plot_species_distribution_modeling.py b/examples/applications/plot_species_distribution_modeling.py index ec6ac78df42c2..9e589d0c39c0e 100644 --- a/examples/applications/plot_species_distribution_modeling.py +++ b/examples/applications/plot_species_distribution_modeling.py @@ -36,16 +36,17 @@ 190:231-259, 2006. """ -# Authors: Peter Prettenhoer +# Authors: Peter Prettenhofer # Jake Vanderplas # -# License: BSD Style. +# License: BSD 3 clause +from __future__ import print_function from time import time import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.datasets.base import Bunch from sklearn.datasets import fetch_species_distributions @@ -60,23 +61,20 @@ except ImportError: basemap = False -print __doc__ +print(__doc__) -def create_species_bunch(species_name, - train, test, - coverages, xgrid, ygrid): - """ - create a bunch with information about a particular organism +def create_species_bunch(species_name, train, test, coverages, xgrid, ygrid): + """Create a bunch with information about a particular organism This will use the test/train record arrays to extract the data specific to the given species name. """ bunch = Bunch(name=' '.join(species_name.split("_")[:2])) - + species_name = species_name.encode('ascii') points = dict(test=test, train=train) - for label, pts in points.iteritems(): + for label, pts in points.items(): # choose points associated with the desired species pts = pts[pts['species'] == species_name] bunch['pts_%s' % label] = pts @@ -95,8 +93,8 @@ def plot_species_distribution(species=["bradypus_variegatus_0", Plot the species distribution. """ if len(species) > 2: - print ("Note: when more than two species are provided, only " - "the first two will be used") + print("Note: when more than two species are provided," + " only the first two will be used") t0 = time() @@ -130,8 +128,8 @@ def plot_species_distribution(species=["bradypus_variegatus_0", # Fit, predict, and plot for each species. for i, species in enumerate([BV_bunch, MM_bunch]): - print "_" * 80 - print "Modeling distribution of species '%s'" % species.name + print("_" * 80) + print("Modeling distribution of species '%s'" % species.name) # Standardize features mean = species.cov_train.mean(axis=0) @@ -139,29 +137,29 @@ def plot_species_distribution(species=["bradypus_variegatus_0", train_cover_std = (species.cov_train - mean) / std # Fit OneClassSVM - print " - fit OneClassSVM ... ", + print(" - fit OneClassSVM ... ", end='') clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.5) clf.fit(train_cover_std) - print "done. " + print("done.") # Plot map of South America - pl.subplot(1, 2, i + 1) + plt.subplot(1, 2, i + 1) if basemap: - print " - plot coastlines using basemap" + print(" - plot coastlines using basemap") m = Basemap(projection='cyl', llcrnrlat=Y.min(), urcrnrlat=Y.max(), llcrnrlon=X.min(), urcrnrlon=X.max(), resolution='c') m.drawcoastlines() m.drawcountries() else: - print " - plot coastlines from coverage" - pl.contour(X, Y, land_reference, - levels=[-9999], colors="k", - linestyles="solid") - pl.xticks([]) - pl.yticks([]) + print(" - plot coastlines from coverage") + plt.contour(X, Y, land_reference, + levels=[-9999], colors="k", + linestyles="solid") + plt.xticks([]) + plt.yticks([]) - print " - predict species distribution" + print(" - predict species distribution") # Predict species distribution using the training data Z = np.ones((data.Ny, data.Nx), dtype=np.float64) @@ -178,21 +176,21 @@ def plot_species_distribution(species=["bradypus_variegatus_0", Z[land_reference == -9999] = -9999 # plot contours of the prediction - pl.contourf(X, Y, Z, levels=levels, cmap=pl.cm.Reds) - pl.colorbar(format='%.2f') + plt.contourf(X, Y, Z, levels=levels, cmap=plt.cm.Reds) + plt.colorbar(format='%.2f') # scatter training/testing points - pl.scatter(species.pts_train['dd long'], species.pts_train['dd lat'], - s=2 ** 2, c='black', - marker='^', label='train') - pl.scatter(species.pts_test['dd long'], species.pts_test['dd lat'], - s=2 ** 2, c='black', - marker='x', label='test') - pl.legend() - pl.title(species.name) - pl.axis('equal') - - # Compute AUC w.r.t. background points + plt.scatter(species.pts_train['dd long'], species.pts_train['dd lat'], + s=2 ** 2, c='black', + marker='^', label='train') + plt.scatter(species.pts_test['dd long'], species.pts_test['dd lat'], + s=2 ** 2, c='black', + marker='x', label='test') + plt.legend() + plt.title(species.name) + plt.axis('equal') + + # Compute AUC with regards to background points pred_background = Z[background_points[0], background_points[1]] pred_test = clf.decision_function((species.cov_test - mean) / std)[:, 0] @@ -200,11 +198,11 @@ def plot_species_distribution(species=["bradypus_variegatus_0", y = np.r_[np.ones(pred_test.shape), np.zeros(pred_background.shape)] fpr, tpr, thresholds = metrics.roc_curve(y, scores) roc_auc = metrics.auc(fpr, tpr) - pl.text(-35, -70, "AUC: %.3f" % roc_auc, ha="right") - print "\n Area under the ROC curve : %f" % roc_auc + plt.text(-35, -70, "AUC: %.3f" % roc_auc, ha="right") + print("\n Area under the ROC curve : %f" % roc_auc) - print "\ntime elapsed: %.2fs" % (time() - t0) + print("\ntime elapsed: %.2fs" % (time() - t0)) plot_species_distribution() -pl.show() +plt.show() diff --git a/examples/applications/plot_stock_market.py b/examples/applications/plot_stock_market.py index d68ea340334b7..6d88cd17e31d8 100644 --- a/examples/applications/plot_stock_market.py +++ b/examples/applications/plot_stock_market.py @@ -1,7 +1,4 @@ """ - -.. _stock_market: - ======================================= Visualizing the stock market structure ======================================= @@ -12,6 +9,7 @@ The quantity that we use is the daily variation in quote price: quotes that are linked tend to cofluctuate during a day. +.. _stock_market: Learning a graph structure -------------------------- @@ -19,7 +17,7 @@ We use sparse inverse covariance estimation to find which quotes are correlated conditionally on the others. Specifically, sparse inverse covariance gives us a graph, that is a list of connection. For each -symbol, the symbols that it is connected too are those useful to expain +symbol, the symbols that it is connected too are those useful to explain its fluctuations. Clustering @@ -61,15 +59,15 @@ heuristic based on the direction of the nearest neighbor along each axis. """ -print __doc__ +print(__doc__) # Author: Gael Varoquaux gael.varoquaux@normalesup.org -# License: BSD +# License: BSD 3 clause import datetime import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from matplotlib import finance from matplotlib.collections import LineCollection @@ -80,74 +78,73 @@ # Choose a time period reasonnably calm (not too long ago so that we get # high-tech firms, and before the 2008 crash) -d1 = datetime.datetime(2003, 01, 01) -d2 = datetime.datetime(2008, 01, 01) +d1 = datetime.datetime(2003, 1, 1) +d2 = datetime.datetime(2008, 1, 1) +# kraft symbol has now changed from KFT to MDLZ in yahoo symbol_dict = { - 'TOT': 'Total', - 'XOM': 'Exxon', - 'CVX': 'Chevron', - 'COP': 'ConocoPhillips', - 'VLO': 'Valero Energy', - 'MSFT': 'Microsoft', - 'IBM': 'IBM', - 'TWX': 'Time Warner', - 'CMCSA': 'Comcast', - 'CVC': 'Cablevision', - 'YHOO': 'Yahoo', - 'DELL': 'Dell', - 'HPQ': 'HP', - 'AMZN': 'Amazon', - 'TM': 'Toyota', - 'CAJ': 'Canon', - 'MTU': 'Mitsubishi', - 'SNE': 'Sony', - 'F': 'Ford', - 'HMC': 'Honda', - 'NAV': 'Navistar', - 'NOC': 'Northrop Grumman', - 'BA': 'Boeing', - 'KO': 'Coca Cola', - 'MMM': '3M', - 'MCD': 'Mc Donalds', - 'PEP': 'Pepsi', - 'KFT': 'Kraft Foods', - 'K': 'Kellogg', - 'UN': 'Unilever', - 'MAR': 'Marriott', - 'PG': 'Procter Gamble', - 'CL': 'Colgate-Palmolive', - 'NWS': 'News Corp', - 'GE': 'General Electrics', - 'WFC': 'Wells Fargo', - 'JPM': 'JPMorgan Chase', - 'AIG': 'AIG', - 'AXP': 'American express', - 'BAC': 'Bank of America', - 'GS': 'Goldman Sachs', - 'AAPL': 'Apple', - 'SAP': 'SAP', - 'CSCO': 'Cisco', - 'TXN': 'Texas instruments', - 'XRX': 'Xerox', - 'LMT': 'Lookheed Martin', - 'WMT': 'Wal-Mart', - 'WAG': 'Walgreen', - 'HD': 'Home Depot', - 'GSK': 'GlaxoSmithKline', - 'PFE': 'Pfizer', - 'SNY': 'Sanofi-Aventis', - 'NVS': 'Novartis', - 'KMB': 'Kimberly-Clark', - 'R': 'Ryder', - 'GD': 'General Dynamics', - 'RTN': 'Raytheon', - 'CVS': 'CVS', - 'CAT': 'Caterpillar', - 'DD': 'DuPont de Nemours', - } - -symbols, names = np.array(symbol_dict.items()).T + 'TOT': 'Total', + 'XOM': 'Exxon', + 'CVX': 'Chevron', + 'COP': 'ConocoPhillips', + 'VLO': 'Valero Energy', + 'MSFT': 'Microsoft', + 'IBM': 'IBM', + 'TWX': 'Time Warner', + 'CMCSA': 'Comcast', + 'CVC': 'Cablevision', + 'YHOO': 'Yahoo', + 'DELL': 'Dell', + 'HPQ': 'HP', + 'AMZN': 'Amazon', + 'TM': 'Toyota', + 'CAJ': 'Canon', + 'MTU': 'Mitsubishi', + 'SNE': 'Sony', + 'F': 'Ford', + 'HMC': 'Honda', + 'NAV': 'Navistar', + 'NOC': 'Northrop Grumman', + 'BA': 'Boeing', + 'KO': 'Coca Cola', + 'MMM': '3M', + 'MCD': 'Mc Donalds', + 'PEP': 'Pepsi', + 'MDLZ': 'Kraft Foods', + 'K': 'Kellogg', + 'UN': 'Unilever', + 'MAR': 'Marriott', + 'PG': 'Procter Gamble', + 'CL': 'Colgate-Palmolive', + 'GE': 'General Electrics', + 'WFC': 'Wells Fargo', + 'JPM': 'JPMorgan Chase', + 'AIG': 'AIG', + 'AXP': 'American express', + 'BAC': 'Bank of America', + 'GS': 'Goldman Sachs', + 'AAPL': 'Apple', + 'SAP': 'SAP', + 'CSCO': 'Cisco', + 'TXN': 'Texas instruments', + 'XRX': 'Xerox', + 'LMT': 'Lookheed Martin', + 'WMT': 'Wal-Mart', + 'WAG': 'Walgreen', + 'HD': 'Home Depot', + 'GSK': 'GlaxoSmithKline', + 'PFE': 'Pfizer', + 'SNY': 'Sanofi-Aventis', + 'NVS': 'Novartis', + 'KMB': 'Kimberly-Clark', + 'R': 'Ryder', + 'GD': 'General Dynamics', + 'RTN': 'Raytheon', + 'CVS': 'CVS', + 'CAT': 'Caterpillar', + 'DD': 'DuPont de Nemours'} + +symbols, names = np.array(list(symbol_dict.items())).T quotes = [finance.quotes_historical_yahoo(symbol, d1, d2, asobject=True) for symbol in symbols] @@ -175,7 +172,7 @@ n_labels = labels.max() for i in range(n_labels + 1): - print 'Cluster %i: %s' % ((i + 1), ', '.join(names[labels == i])) + print('Cluster %i: %s' % ((i + 1), ', '.join(names[labels == i]))) ############################################################################### # Find a low-dimension embedding for visualization: find the best position of @@ -191,10 +188,10 @@ ############################################################################### # Visualization -pl.figure(1, facecolor='w', figsize=(10, 8)) -pl.clf() -ax = pl.axes([0., 0., 1., 1.]) -pl.axis('off') +plt.figure(1, facecolor='w', figsize=(10, 8)) +plt.clf() +ax = plt.axes([0., 0., 1., 1.]) +plt.axis('off') # Display a graph of the partial correlations partial_correlations = edge_model.precision_.copy() @@ -204,8 +201,8 @@ non_zero = (np.abs(np.triu(partial_correlations, k=1)) > 0.02) # Plot the nodes using the coordinates of our embedding -pl.scatter(embedding[0], embedding[1], s=100 * d ** 2, c=labels, - cmap=pl.cm.spectral) +plt.scatter(embedding[0], embedding[1], s=100 * d ** 2, c=labels, + cmap=plt.cm.spectral) # Plot the edges start_idx, end_idx = np.where(non_zero) @@ -215,8 +212,8 @@ for start, stop in zip(start_idx, end_idx)] values = np.abs(partial_correlations[non_zero]) lc = LineCollection(segments, - zorder=0, cmap=pl.cm.hot_r, - norm=pl.Normalize(0, .7 * values.max())) + zorder=0, cmap=plt.cm.hot_r, + norm=plt.Normalize(0, .7 * values.max())) lc.set_array(values) lc.set_linewidths(15 * values) ax.add_collection(lc) @@ -224,7 +221,7 @@ # Add a label to each node. The challenge here is that we want to # position the labels to avoid overlap with other labels for index, (name, label, (x, y)) in enumerate( - zip(names, labels, embedding.T)): + zip(names, labels, embedding.T)): dx = x - embedding[0] dx[index] = 1 @@ -244,16 +241,16 @@ else: verticalalignment = 'top' y = y - .002 - pl.text(x, y, name, size=10, - horizontalalignment=horizontalalignment, - verticalalignment=verticalalignment, - bbox=dict(facecolor='w', - edgecolor=pl.cm.spectral(label / float(n_labels)), - alpha=.6)) - -pl.xlim(embedding[0].min() - .15 * embedding[0].ptp(), - embedding[0].max() + .10 * embedding[0].ptp(),) -pl.ylim(embedding[1].min() - .03 * embedding[1].ptp(), - embedding[1].max() + .03 * embedding[1].ptp()) - -pl.show() + plt.text(x, y, name, size=10, + horizontalalignment=horizontalalignment, + verticalalignment=verticalalignment, + bbox=dict(facecolor='w', + edgecolor=plt.cm.spectral(label / float(n_labels)), + alpha=.6)) + +plt.xlim(embedding[0].min() - .15 * embedding[0].ptp(), + embedding[0].max() + .10 * embedding[0].ptp(),) +plt.ylim(embedding[1].min() - .03 * embedding[1].ptp(), + embedding[1].max() + .03 * embedding[1].ptp()) + +plt.show() diff --git a/examples/applications/plot_tomography_l1_reconstruction.py b/examples/applications/plot_tomography_l1_reconstruction.py index 7fd76dfa0434e..676b4cdedf863 100644 --- a/examples/applications/plot_tomography_l1_reconstruction.py +++ b/examples/applications/plot_tomography_l1_reconstruction.py @@ -35,10 +35,10 @@ class :class:`sklearn.linear_model.Lasso`, that uses the coordinate descent contributed to fewer projections than the central disk. """ -print __doc__ +print(__doc__) # Author: Emmanuelle Gouillart -# License: Simplified BSD +# License: BSD 3 clause import numpy as np from scipy import sparse diff --git a/examples/applications/svm_gui.py b/examples/applications/svm_gui.py index 9c9188bf6ef43..998dcb4ccb22a 100644 --- a/examples/applications/svm_gui.py +++ b/examples/applications/svm_gui.py @@ -13,13 +13,13 @@ If all examples are from the same class, it uses a one-class SVM. """ -from __future__ import division +from __future__ import division, print_function -print __doc__ +print(__doc__) # Author: Peter Prettenhoer # -# License: BSD Style. +# License: BSD 3 clause import matplotlib matplotlib.use('TkAgg') @@ -35,6 +35,7 @@ from sklearn import svm from sklearn.datasets import dump_svmlight_file +from sklearn.externals.six.moves import xrange y_min, y_max = -50, 50 x_min, x_max = -50, 50 @@ -81,7 +82,7 @@ def __init__(self, model): self.fitted = False def fit(self): - print "fit the model" + print("fit the model") train = np.array(self.model.data) X = train[:, 0:2] y = train[:, 2] @@ -93,14 +94,14 @@ def fit(self): kernel_map = {0: "linear", 1: "rbf", 2: "poly"} if len(np.unique(y)) == 1: clf = svm.OneClassSVM(kernel=kernel_map[self.kernel.get()], - gamma=gamma, coef0=coef0, degree=degree) + gamma=gamma, coef0=coef0, degree=degree) clf.fit(X) else: clf = svm.SVC(kernel=kernel_map[self.kernel.get()], C=C, gamma=gamma, coef0=coef0, degree=degree) clf.fit(X, y) if hasattr(clf, 'score'): - print "Accuracy:", clf.score(X, y) * 100 + print("Accuracy:", clf.score(X, y) * 100) X1, X2, Z = self.decision_surface(clf) self.model.clf = clf self.model.set_surface((X1, X2, Z)) @@ -233,11 +234,9 @@ def plot_decision_surface(self, surface, type): linestyles=linestyles)) elif type == 1: self.contours.append(self.ax.contourf(X1, X2, Z, 10, - cmap=matplotlib.cm.bone, - origin='lower', - alpha=0.85)) - self.contours.append(self.ax.contour(X1, X2, Z, [0.0], - colors='k', + cmap=matplotlib.cm.bone, + origin='lower', alpha=0.85)) + self.contours.append(self.ax.contour(X1, X2, Z, [0.0], colors='k', linestyles=['solid'])) else: raise ValueError("surface type unknown") @@ -308,8 +307,8 @@ def get_parser(): from optparse import OptionParser op = OptionParser() op.add_option("--output", - action="http://github.com/store", type="str", dest="output", - help="Path where to dump data.") + action="http://github.com/store", type="str", dest="output", + help="Path where to dump data.") return op diff --git a/examples/applications/topics_extraction_with_nmf.py b/examples/applications/topics_extraction_with_nmf.py index e15079216ae22..48cce50fe05e6 100644 --- a/examples/applications/topics_extraction_with_nmf.py +++ b/examples/applications/topics_extraction_with_nmf.py @@ -6,71 +6,57 @@ This is a proof of concept application of Non Negative Matrix Factorization of the term frequency matrix of a corpus of documents so as to extract an additive model of the topic structure of the corpus. +The output is a list of topics, each represented as a list of terms +(weights are not shown). The default parameters (n_samples / n_features / n_topics) should make the example runnable in a couple of tens of seconds. You can try to -increase the dimensions of the problem be ware than the time complexity +increase the dimensions of the problem, but be aware than the time complexity is polynomial. -Here are some sample extracted topics that look quite good: - -Topic #0: -god people bible israel jesus christian true moral think christians -believe don say human israeli church life children jewish - -Topic #1: -drive windows card drivers video scsi software pc thanks vga -graphics help disk uni dos file ide controller work - -Topic #2: -game team nhl games ca hockey players buffalo edu cc year play -university teams baseball columbia league player toronto - -Topic #3: -window manager application mit motif size display widget program -xlib windows user color event information use events x11r5 values - -Topic #4: -pitt gordon banks cs science pittsburgh univ computer soon disease -edu reply pain health david article medical medicine 16 """ # Author: Olivier Grisel -# License: Simplified BSD +# Lars Buitinck +# License: BSD 3 clause +from __future__ import print_function from time import time -from sklearn.feature_extraction import text -from sklearn import decomposition -from sklearn import datasets -n_samples = 1000 +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.decomposition import NMF +from sklearn.datasets import fetch_20newsgroups + +n_samples = 2000 n_features = 1000 n_topics = 10 n_top_words = 20 -# Load the 20 newsgroups dataset and vectorize it using the most common word -# frequency with TF-IDF weighting (without top 5% stop words) +# Load the 20 newsgroups dataset and vectorize it. We use a few heuristics +# to filter out useless terms early on: the posts are stripped of headers, +# footers and quoted replies, and common English words, words occurring in +# only one document or in at least 95% of the documents are removed. t0 = time() -print "Loading dataset and extracting TF-IDF features..." -dataset = datasets.fetch_20newsgroups(shuffle=True, random_state=1) +print("Loading dataset and extracting TF-IDF features...") +dataset = fetch_20newsgroups(shuffle=True, random_state=1, + remove=('headers', 'footers', 'quotes')) -vectorizer = text.CountVectorizer(max_df=0.95, max_features=n_features) -counts = vectorizer.fit_transform(dataset.data[:n_samples]) -tfidf = text.TfidfTransformer().fit_transform(counts) -print "done in %0.3fs." % (time() - t0) +vectorizer = TfidfVectorizer(max_df=0.95, min_df=2, max_features=n_features, + stop_words='english') +tfidf = vectorizer.fit_transform(dataset.data[:n_samples]) +print("done in %0.3fs." % (time() - t0)) # Fit the NMF model -print "Fitting the NMF model on with n_samples=%d and n_features=%d..." % ( - n_samples, n_features) -nmf = decomposition.NMF(n_components=n_topics).fit(tfidf) -print "done in %0.3fs." % (time() - t0) +print("Fitting the NMF model with n_samples=%d and n_features=%d..." + % (n_samples, n_features)) +nmf = NMF(n_components=n_topics, random_state=1).fit(tfidf) +print("done in %0.3fs." % (time() - t0)) -# Inverse the vectorizer vocabulary to be able feature_names = vectorizer.get_feature_names() for topic_idx, topic in enumerate(nmf.components_): - print "Topic #%d:" % topic_idx - print " ".join([feature_names[i] - for i in topic.argsort()[:-n_top_words - 1:-1]]) - print + print("Topic #%d:" % topic_idx) + print(" ".join([feature_names[i] + for i in topic.argsort()[:-n_top_words - 1:-1]])) + print() diff --git a/examples/applications/wikipedia_principal_eigenvector.py b/examples/applications/wikipedia_principal_eigenvector.py index 0d7bebe6912c1..951e07ab7638a 100644 --- a/examples/applications/wikipedia_principal_eigenvector.py +++ b/examples/applications/wikipedia_principal_eigenvector.py @@ -23,15 +23,16 @@ http://en.wikipedia.org/wiki/Power_iteration Here the computation is achieved thanks to Martinsson's Randomized SVD -algoritm implemented in the scikit. +algorithm implemented in the scikit. The graph data is fetched from the DBpedia dumps. DBpedia is an extraction of the latent structured data of the Wikipedia content. """ -print __doc__ # Author: Olivier Grisel -# License: Simplified BSD +# License: BSD 3 clause + +from __future__ import print_function from bz2 import BZ2File import os @@ -43,10 +44,12 @@ from scipy import sparse -from sklearn.utils.extmath import randomized_svd +from sklearn.decomposition import randomized_svd from sklearn.externals.joblib import Memory +print(__doc__) + ############################################################################### # Where to download the data, if not already on disk redirects_url = "http://downloads.dbpedia.org/3.5.1/en/redirects_en.nt.bz2" @@ -63,10 +66,10 @@ for url, filename in resources: if not os.path.exists(filename): import urllib - print "Downloading data from '%s', please wait..." % url + print("Downloading data from '%s', please wait..." % url) opener = urllib.urlopen(url) open(filename, 'wb').write(opener.read()) - print + print() ############################################################################### @@ -93,18 +96,18 @@ def short_name(nt_uri): def get_redirects(redirects_filename): """Parse the redirections and build a transitively closed map out of it""" redirects = {} - print "Parsing the NT redirect file" + print("Parsing the NT redirect file") for l, line in enumerate(BZ2File(redirects_filename)): split = line.split() if len(split) != 4: - print "ignoring malformed line: " + line + print("ignoring malformed line: " + line) continue redirects[short_name(split[0])] = short_name(split[2]) if l % 1000000 == 0: - print "[%s] line: %08d" % (datetime.now().isoformat(), l) + print("[%s] line: %08d" % (datetime.now().isoformat(), l)) # compute the transitive closure - print "Computing the transitive closure of the redirect relation" + print("Computing the transitive closure of the redirect relation") for l, source in enumerate(redirects.keys()): transitive_target = None target = redirects[source] @@ -117,7 +120,7 @@ def get_redirects(redirects_filename): seen.add(target) redirects[source] = transitive_target if l % 1000000 == 0: - print "[%s] line: %08d" % (datetime.now().isoformat(), l) + print("[%s] line: %08d" % (datetime.now().isoformat(), l)) return redirects @@ -134,34 +137,34 @@ def get_adjacency_matrix(redirects_filename, page_links_filename, limit=None): from article names to python int (article indexes). """ - print "Computing the redirect map" + print("Computing the redirect map") redirects = get_redirects(redirects_filename) - print "Computing the integer index map" + print("Computing the integer index map") index_map = dict() links = list() for l, line in enumerate(BZ2File(page_links_filename)): split = line.split() if len(split) != 4: - print "ignoring malformed line: " + line + print("ignoring malformed line: " + line) continue i = index(redirects, index_map, short_name(split[0])) j = index(redirects, index_map, short_name(split[2])) links.append((i, j)) if l % 1000000 == 0: - print "[%s] line: %08d" % (datetime.now().isoformat(), l) + print("[%s] line: %08d" % (datetime.now().isoformat(), l)) if limit is not None and l >= limit - 1: break - print "Computing the adjacency matrix" + print("Computing the adjacency matrix") X = sparse.lil_matrix((len(index_map), len(index_map)), dtype=np.float32) for i, j in links: X[i, j] = 1.0 del links - print "Converting to CSR representation" + print("Converting to CSR representation") X = X.tocsr() - print "CSR conversion done" + print("CSR conversion done") return X, redirects, index_map @@ -170,14 +173,14 @@ def get_adjacency_matrix(redirects_filename, page_links_filename, limit=None): redirects_filename, page_links_filename, limit=5000000) names = dict((i, name) for name, i in index_map.iteritems()) -print "Computing the principal singular vectors using randomized_svd" +print("Computing the principal singular vectors using randomized_svd") t0 = time() -U, s, V = randomized_svd(X, 5, n_iterations=3) -print "done in %0.3fs" % (time() - t0) +U, s, V = randomized_svd(X, 5, n_iter=3) +print("done in %0.3fs" % (time() - t0)) # print the names of the wikipedia related strongest compenents of the the # principal singular vector which should be similar to the highest eigenvector -print "Top wikipedia pages according to principal singular vectors" +print("Top wikipedia pages according to principal singular vectors") pprint([names[i] for i in np.abs(U.T[0]).argsort()[-10:]]) pprint([names[i] for i in np.abs(V[0]).argsort()[-10:]]) @@ -197,14 +200,14 @@ def centrality_scores(X, alpha=0.85, max_iter=100, tol=1e-10): X = X.copy() incoming_counts = np.asarray(X.sum(axis=1)).ravel() - print "Normalizing the graph" + print("Normalizing the graph") for i in incoming_counts.nonzero()[0]: X.data[X.indptr[i]:X.indptr[i + 1]] *= 1.0 / incoming_counts[i] dangle = np.asarray(np.where(X.sum(axis=1) == 0, 1.0 / n, 0)).ravel() scores = np.ones(n, dtype=np.float32) / n # initial guess for i in range(max_iter): - print "power iteration #%d" % i + print("power iteration #%d" % i) prev_scores = scores scores = (alpha * (scores * X + np.dot(dangle, prev_scores)) + (1 - alpha) * prev_scores.sum() / n) @@ -213,14 +216,14 @@ def centrality_scores(X, alpha=0.85, max_iter=100, tol=1e-10): if scores_max == 0.0: scores_max = 1.0 err = np.abs(scores - prev_scores).max() / scores_max - print "error: %0.6f" % err + print("error: %0.6f" % err) if err < n * tol: return scores return scores -print "Computing principal eigenvector score using a power iteration method" +print("Computing principal eigenvector score using a power iteration method") t0 = time() scores = centrality_scores(X, max_iter=100, tol=1e-10) -print "done in %0.3fs" % (time() - t0) +print("done in %0.3fs" % (time() - t0)) pprint([names[i] for i in np.abs(scores).argsort()[-10:]]) diff --git a/examples/bicluster/README.txt b/examples/bicluster/README.txt new file mode 100644 index 0000000000000..468e2524eb310 --- /dev/null +++ b/examples/bicluster/README.txt @@ -0,0 +1,6 @@ +.. _bicluster_examples: + +Biclustering +------------ + +Examples concerning the :mod:`sklearn.cluster.bicluster` module. diff --git a/examples/bicluster/bicluster_newsgroups.py b/examples/bicluster/bicluster_newsgroups.py new file mode 100644 index 0000000000000..45a9f2406e2fb --- /dev/null +++ b/examples/bicluster/bicluster_newsgroups.py @@ -0,0 +1,182 @@ +""" +================================================================ +Biclustering documents with the Spectral Co-clustering algorithm +================================================================ + +This example demonstrates the Spectral Co-clustering algorithm on the +twenty newsgroups dataset. The 'comp.os.ms-windows.misc' category is +excluded because it contains many posts containing nothing but data. + +The TF-IDF vectorized posts form a word frequency matrix, which is +then biclustered using Dhillon's Spectral Co-Clustering algorithm. The +resulting document-word biclusters indicate subsets words used more +often in those subsets documents. + +For a few of the best biclusters, its most common document categories +and its ten most important words get printed. The best biclusters are +determined by their normalized cut. The best words are determined by +comparing their sums inside and outside the bicluster. + +For comparison, the documents are also clustered using +MiniBatchKMeans. The document clusters derived from the biclusters +achieve a better V-measure than clusters found by MiniBatchKMeans. + +Output:: + + Vectorizing... + Coclustering... + Done in 9.53s. V-measure: 0.4455 + MiniBatchKMeans... + Done in 12.00s. V-measure: 0.3309 + + Best biclusters: + ---------------- + bicluster 0 : 1951 documents, 4373 words + categories : 23% talk.politics.guns, 19% talk.politics.misc, 14% sci.med + words : gun, guns, geb, banks, firearms, drugs, gordon, clinton, cdt, amendment + + bicluster 1 : 1165 documents, 3304 words + categories : 29% talk.politics.mideast, 26% soc.religion.christian, 25% alt.atheism + words : god, jesus, christians, atheists, kent, sin, morality, belief, resurrection, marriage + + bicluster 2 : 2219 documents, 2830 words + categories : 18% comp.sys.mac.hardware, 16% comp.sys.ibm.pc.hardware, 16% comp.graphics + words : voltage, dsp, board, receiver, circuit, shipping, packages, stereo, compression, package + + bicluster 3 : 1860 documents, 2745 words + categories : 26% rec.motorcycles, 23% rec.autos, 13% misc.forsale + words : bike, car, dod, engine, motorcycle, ride, honda, cars, bmw, bikes + + bicluster 4 : 12 documents, 155 words + categories : 100% rec.sport.hockey + words : scorer, unassisted, reichel, semak, sweeney, kovalenko, ricci, audette, momesso, nedved + +""" +from __future__ import print_function + +print(__doc__) + +from collections import defaultdict +import operator +import re +from time import time + +import numpy as np + +from sklearn.cluster.bicluster import SpectralCoclustering +from sklearn.cluster import MiniBatchKMeans +from sklearn.externals import six +from sklearn.datasets.twenty_newsgroups import fetch_20newsgroups +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.metrics.cluster import v_measure_score + + +def number_aware_tokenizer(doc): + """ Tokenizer that maps all numeric tokens to a placeholder. + + For many applications, tokens that begin with a number are not directly + useful, but the fact that such a token exists can be relevant. By applying + this form of dimensionality reduction, some methods may perform better. + """ + token_pattern = re.compile(u'(?u)\\b\\w\\w+\\b') + tokens = token_pattern.findall(doc) + tokens = ["#NUMBER" if token[0] in "0123456789_" else token + for token in tokens] + return tokens + +# exclude 'comp.os.ms-windows.misc' +categories = ['alt.atheism', 'comp.graphics', + 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', + 'comp.windows.x', 'misc.forsale', 'rec.autos', + 'rec.motorcycles', 'rec.sport.baseball', + 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', + 'sci.med', 'sci.space', 'soc.religion.christian', + 'talk.politics.guns', 'talk.politics.mideast', + 'talk.politics.misc', 'talk.religion.misc'] +newsgroups = fetch_20newsgroups(categories=categories) +y_true = newsgroups.target + +vectorizer = TfidfVectorizer(stop_words='english', min_df=5, + tokenizer=number_aware_tokenizer) +cocluster = SpectralCoclustering(n_clusters=len(categories), + svd_method='arpack', random_state=0) +kmeans = MiniBatchKMeans(n_clusters=len(categories), batch_size=20000, + random_state=0) + +print("Vectorizing...") +X = vectorizer.fit_transform(newsgroups.data) + +print("Coclustering...") +start_time = time() +cocluster.fit(X) +y_cocluster = cocluster.row_labels_ +print("Done in {:.2f}s. V-measure: {:.4f}".format( + time() - start_time, + v_measure_score(y_cocluster, y_true))) + +print("MiniBatchKMeans...") +start_time = time() +y_kmeans = kmeans.fit_predict(X) +print("Done in {:.2f}s. V-measure: {:.4f}".format( + time() - start_time, + v_measure_score(y_kmeans, y_true))) + +feature_names = vectorizer.get_feature_names() +document_names = list(newsgroups.target_names[i] for i in newsgroups.target) + + +def bicluster_ncut(i): + rows, cols = cocluster.get_indices(i) + if not (np.any(rows) and np.any(cols)): + import sys + return sys.float_info.max + row_complement = np.nonzero(np.logical_not(cocluster.rows_[i]))[0] + col_complement = np.nonzero(np.logical_not(cocluster.columns_[i]))[0] + weight = X[rows[:, np.newaxis], cols].sum() + cut = (X[row_complement[:, np.newaxis], cols].sum() + + X[rows[:, np.newaxis], col_complement].sum()) + return cut / weight + + +def most_common(d): + """Items of a defaultdict(int) with the highest values. + + Like Counter.most_common in Python >=2.7. + """ + return sorted(six.iteritems(d), key=operator.itemgetter(1), reverse=True) + + +bicluster_ncuts = list(bicluster_ncut(i) + for i in xrange(len(newsgroups.target_names))) +best_idx = np.argsort(bicluster_ncuts)[:5] + +print() +print("Best biclusters:") +print("----------------") +for idx, cluster in enumerate(best_idx): + n_rows, n_cols = cocluster.get_shape(cluster) + cluster_docs, cluster_words = cocluster.get_indices(cluster) + if not len(cluster_docs) or not len(cluster_words): + continue + + # categories + counter = defaultdict(int) + for i in cluster_docs: + counter[document_names[i]] += 1 + cat_string = ", ".join("{:.0f}% {}".format(float(c) / n_rows * 100, name) + for name, c in most_common(counter)[:3]) + + # words + out_of_cluster_docs = cocluster.row_labels_ != cluster + out_of_cluster_docs = np.where(out_of_cluster_docs)[0] + word_col = X[:, cluster_words] + word_scores = np.array(word_col[cluster_docs, :].sum(axis=0) - + word_col[out_of_cluster_docs, :].sum(axis=0)) + word_scores = word_scores.ravel() + important_words = list(feature_names[cluster_words[i]] + for i in word_scores.argsort()[:-11:-1]) + + print("bicluster {} : {} documents, {} words".format( + idx, n_rows, n_cols)) + print("categories : {}".format(cat_string)) + print("words : {}\n".format(', '.join(important_words))) diff --git a/examples/bicluster/plot_spectral_biclustering.py b/examples/bicluster/plot_spectral_biclustering.py new file mode 100644 index 0000000000000..fdcbfcdcf7fc5 --- /dev/null +++ b/examples/bicluster/plot_spectral_biclustering.py @@ -0,0 +1,62 @@ +""" +============================================= +A demo of the Spectral Biclustering algorithm +============================================= + +This example demonstrates how to generate a checkerboard dataset and +bicluster it using the Spectral Biclustering algorithm. + +The data is generated with the ``make_checkerboard`` function, then +shuffled and passed to the Spectral Biclustering algorithm. The rows +and columns of the shuffled matrix are rearranged to show the +biclusters found by the algorithm. + +The outer product of the row and column label vectors shows a +representation of the checkerboard structure. + +""" +print(__doc__) + +# Author: Kemal Eren +# License: BSD 3 clause + +import numpy as np +from matplotlib import pyplot as plt + +from sklearn.datasets import make_checkerboard +from sklearn.datasets import samples_generator as sg +from sklearn.cluster.bicluster import SpectralBiclustering +from sklearn.metrics import consensus_score + +n_clusters = (4, 3) +data, rows, columns = make_checkerboard( + shape=(300, 300), n_clusters=n_clusters, noise=10, + shuffle=False, random_state=0) + +plt.matshow(data, cmap=plt.cm.Blues) +plt.title("Original dataset") + +data, row_idx, col_idx = sg._shuffle(data, random_state=0) +plt.matshow(data, cmap=plt.cm.Blues) +plt.title("Shuffled dataset") + +model = SpectralBiclustering(n_clusters=n_clusters, method='log', + random_state=0) +model.fit(data) +score = consensus_score(model.biclusters_, + (rows[:, row_idx], columns[:, col_idx])) + +print("consensus score: {:.1f}".format(score)) + +fit_data = data[np.argsort(model.row_labels_)] +fit_data = fit_data[:, np.argsort(model.column_labels_)] + +plt.matshow(fit_data, cmap=plt.cm.Blues) +plt.title("After biclustering; rearranged to show biclusters") + +plt.matshow(np.outer(np.sort(model.row_labels_) + 1, + np.sort(model.column_labels_) + 1), + cmap=plt.cm.Blues) +plt.title("Checkerboard structure of rearranged data") + +plt.show() diff --git a/examples/bicluster/plot_spectral_coclustering.py b/examples/bicluster/plot_spectral_coclustering.py new file mode 100644 index 0000000000000..dbf53f269835e --- /dev/null +++ b/examples/bicluster/plot_spectral_coclustering.py @@ -0,0 +1,54 @@ +""" +============================================== +A demo of the Spectral Co-Clustering algorithm +============================================== + +This example demonstrates how to generate a dataset and bicluster it +using the the Spectral Co-Clustering algorithm. + +The dataset is generated using the ``make_biclusters`` function, which +creates a matrix of small values and implants bicluster with large +values. The rows and columns are then shuffled and passed to the +Spectral Co-Clustering algorithm. Rearranging the shuffled matrix to +make biclusters contiguous shows how accurately the algorithm found +the biclusters. + +""" +print(__doc__) + +# Author: Kemal Eren +# License: BSD 3 clause + +import numpy as np +from matplotlib import pyplot as plt + +from sklearn.datasets import make_biclusters +from sklearn.datasets import samples_generator as sg +from sklearn.cluster.bicluster import SpectralCoclustering +from sklearn.metrics import consensus_score + +data, rows, columns = make_biclusters( + shape=(300, 300), n_clusters=5, noise=5, + shuffle=False, random_state=0) + +plt.matshow(data, cmap=plt.cm.Blues) +plt.title("Original dataset") + +data, row_idx, col_idx = sg._shuffle(data, random_state=0) +plt.matshow(data, cmap=plt.cm.Blues) +plt.title("Shuffled dataset") + +model = SpectralCoclustering(n_clusters=5, random_state=0) +model.fit(data) +score = consensus_score(model.biclusters_, + (rows[:, row_idx], columns[:, col_idx])) + +print("consensus score: {:.3f}".format(score)) + +fit_data = data[np.argsort(model.row_labels_)] +fit_data = fit_data[:, np.argsort(model.column_labels_)] + +plt.matshow(fit_data, cmap=plt.cm.Blues) +plt.title("After biclustering; rearranged to show biclusters") + +plt.show() diff --git a/examples/calibration/README.txt b/examples/calibration/README.txt new file mode 100644 index 0000000000000..5e4a31b966b50 --- /dev/null +++ b/examples/calibration/README.txt @@ -0,0 +1,6 @@ +.. _calibration_examples: + +Calibration +----------------------- + +Examples illustrating the calibration of predicted probabilities of classifiers. diff --git a/examples/calibration/plot_calibration.py b/examples/calibration/plot_calibration.py new file mode 100644 index 0000000000000..2267f02dd0022 --- /dev/null +++ b/examples/calibration/plot_calibration.py @@ -0,0 +1,116 @@ +""" +====================================== +Probability calibration of classifiers +====================================== + +When performing classification you often want to predict not only +the class label, but also the associated probability. This probability +gives you some kind of confidence on the prediction. However, not all +classifiers provide well-calibrated probabilities, some being over-confident +while others being under-confident. Thus, a separate calibration of predicted +probabilities is often desirable as a postprocessing. This example illustrates +two different methods for this calibration and evaluates the quality of the +returned probabilities using Brier's score +(see http://en.wikipedia.org/wiki/Brier_score). + +Compared are the estimated probability using a Gaussian naive Bayes classifier +without calibration, with a sigmoid calibration, and with a non-parametric +isotonic calibration. One can observe that only the non-parametric model is able +to provide a probability calibration that returns probabilities close to the +expected 0.5 for most of the samples belonging to the middle cluster with +heterogeneous labels. This results in a significantly improved Brier score. +""" +print(__doc__) + +# Author: Mathieu Blondel +# Alexandre Gramfort +# Balazs Kegl +# Jan Hendrik Metzen +# License: BSD Style. + +import numpy as np +import matplotlib.pyplot as plt +from matplotlib import cm + +from sklearn.datasets import make_blobs +from sklearn.naive_bayes import GaussianNB +from sklearn.metrics import brier_score_loss +from sklearn.calibration import CalibratedClassifierCV +from sklearn.cross_validation import train_test_split + + +n_samples = 50000 +n_bins = 3 # use 3 bins for calibration_curve as we have 3 clusters here + +# Generate 3 blobs with 2 classes where the second blob contains +# half positive samples and half negative samples. Probability in this +# blob is therefore 0.5. +centers = [(-5, -5), (0, 0), (5, 5)] +X, y = make_blobs(n_samples=n_samples, n_features=2, cluster_std=1.0, + centers=centers, shuffle=False, random_state=42) + +y[:n_samples // 2] = 0 +y[n_samples // 2:] = 1 +sample_weight = np.random.RandomState(42).rand(y.shape[0]) + +# split train, test for calibration +X_train, X_test, y_train, y_test, sw_train, sw_test = \ + train_test_split(X, y, sample_weight, test_size=0.9, random_state=42) + +# Gaussian Naive-Bayes with no calibration +clf = GaussianNB() +clf.fit(X_train, y_train) # GaussianNB itself does not support sample-weights +prob_pos_clf = clf.predict_proba(X_test)[:, 1] + +# Gaussian Naive-Bayes with isotonic calibration +clf_isotonic = CalibratedClassifierCV(clf, cv=2, method='isotonic') +clf_isotonic.fit(X_train, y_train, sw_train) +prob_pos_isotonic = clf_isotonic.predict_proba(X_test)[:, 1] + +# Gaussian Naive-Bayes with sigmoid calibration +clf_sigmoid = CalibratedClassifierCV(clf, cv=2, method='sigmoid') +clf_sigmoid.fit(X_train, y_train, sw_train) +prob_pos_sigmoid = clf_sigmoid.predict_proba(X_test)[:, 1] + +print("Brier scores: (the smaller the better)") + +clf_score = brier_score_loss(y_test, prob_pos_clf, sw_test) +print("No calibration: %1.3f" % clf_score) + +clf_isotonic_score = brier_score_loss(y_test, prob_pos_isotonic, sw_test) +print("With isotonic calibration: %1.3f" % clf_isotonic_score) + +clf_sigmoid_score = brier_score_loss(y_test, prob_pos_sigmoid, sw_test) +print("With sigmoid calibration: %1.3f" % clf_sigmoid_score) + +############################################################################### +# Plot the data and the predicted probabilities +plt.figure() +y_unique = np.unique(y) +colors = cm.rainbow(np.linspace(0.0, 1.0, y_unique.size)) +for this_y, color in zip(y_unique, colors): + this_X = X_train[y_train == this_y] + this_sw = sw_train[y_train == this_y] + plt.scatter(this_X[:, 0], this_X[:, 1], s=this_sw * 50, c=color, alpha=0.5, + label="Class %s" % this_y) +plt.legend(loc="best") +plt.title("Data") + +plt.figure() +order = np.lexsort((prob_pos_clf, )) +plt.plot(prob_pos_clf[order], 'r', label='No calibration (%1.3f)' % clf_score) +plt.plot(prob_pos_isotonic[order], 'g', linewidth=3, + label='Isotonic calibration (%1.3f)' % clf_isotonic_score) +plt.plot(prob_pos_sigmoid[order], 'b', linewidth=3, + label='Sigmoid calibration (%1.3f)' % clf_sigmoid_score) +plt.plot(np.linspace(0, y_test.size, 51)[1::2], + y_test[order].reshape(25, -1).mean(1), + 'k', linewidth=3, label=r'Empirical') +plt.ylim([-0.05, 1.05]) +plt.xlabel("Instances sorted according to predicted probability " + "(uncalibrated GNB)") +plt.ylabel("P(y=1)") +plt.legend(loc="upper left") +plt.title("Gaussian naive Bayes probabilities") + +plt.show() diff --git a/examples/calibration/plot_calibration_curve.py b/examples/calibration/plot_calibration_curve.py new file mode 100644 index 0000000000000..42dc8473e6c30 --- /dev/null +++ b/examples/calibration/plot_calibration_curve.py @@ -0,0 +1,134 @@ +""" +============================== +Probability Calibration curves +============================== + +When performing classification one often wants to predict not only the class +label, but also the associated probability. This probability gives some +kind of confidence on the prediction. This example demonstrates how to display +how well calibrated the predicted probabilities are and how to calibrate an +uncalibrated classifier. + +The experiment is performed on an artificial dataset for binary classification +with 100.000 samples (1.000 of them are used for model fitting) with 20 +features. Of the 20 features, only 2 are informative and 10 are redundant. The +first figure shows the estimated probabilities obtained with logistic +regression, Gaussian naive Bayes, and Gaussian naive Bayes with both isotonic +calibration and sigmoid calibration. The calibration performance is evaluated +with Brier score, reported in the legend (the smaller the better). One can +observe here that logistic regression is well calibrated while raw Gaussian +naive Bayes performs very badly. This is because of the redundant features +which violate the assumption of feature-independence and result in an overly +confident classifier, which is indicated by the typical transposed-sigmoid +curve. + +Calibration of the probabilities of Gaussian naive Bayes with isotonic +regression can fix this issue as can be seen from the nearly diagonal +calibration curve. Sigmoid calibration also improves the brier score slightly, +albeit not as strongly as the non-parametric isotonic regression. This can be +attributed to the fact that we have plenty of calibration data such that the +greater flexibility of the non-parametric model can be exploited. + +The second figure shows the calibration curve of a linear support-vector +classifier (LinearSVC). LinearSVC shows the opposite behavior as Gaussian +naive Bayes: the calibration curve has a sigmoid curve, which is typical for +an under-confident classifier. In the case of LinearSVC, this is caused by the +margin property of the hinge loss, which lets the model focus on hard samples +that are close to the decision boundary (the support vectors). + +Both kinds of calibration can fix this issue and yield nearly identical +results. This shows that sigmoid calibration can deal with situations where +the calibration curve of the base classifier is sigmoid (e.g., for LinearSVC) +but not where it is transposed-sigmoid (e.g., Gaussian naive Bayes). +""" +print(__doc__) + +# Author: Alexandre Gramfort +# Jan Hendrik Metzen +# License: BSD Style. + +import matplotlib.pyplot as plt + +from sklearn import datasets +from sklearn.naive_bayes import GaussianNB +from sklearn.svm import LinearSVC +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import (brier_score_loss, precision_score, recall_score, + f1_score) +from sklearn.calibration import CalibratedClassifierCV, calibration_curve +from sklearn.cross_validation import train_test_split + + +# Create dataset of classification task with many redundant and few +# informative features +X, y = datasets.make_classification(n_samples=100000, n_features=20, + n_informative=2, n_redundant=10, + random_state=42) + +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.99, + random_state=42) + + +def plot_calibration_curve(est, name, fig_index): + """Plot calibration curve for est w/o and with calibration. """ + # Calibrated with isotonic calibration + isotonic = CalibratedClassifierCV(est, cv=2, method='isotonic') + + # Calibrated with sigmoid calibration + sigmoid = CalibratedClassifierCV(est, cv=2, method='sigmoid') + + # Logistic regression with no calibration as baseline + lr = LogisticRegression(C=1., solver='lbfgs') + + fig = plt.figure(fig_index, figsize=(10, 10)) + ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2) + ax2 = plt.subplot2grid((3, 1), (2, 0)) + + ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") + for clf, name in [(lr, 'Logistic'), + (est, name), + (isotonic, name + ' + Isotonic'), + (sigmoid, name + ' + Sigmoid')]: + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + if hasattr(clf, "predict_proba"): + prob_pos = clf.predict_proba(X_test)[:, 1] + else: # use decision function + prob_pos = clf.decision_function(X_test) + prob_pos = \ + (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min()) + + clf_score = brier_score_loss(y_test, prob_pos, pos_label=y.max()) + print("%s:" % name) + print("\tBrier: %1.3f" % (clf_score)) + print("\tPrecision: %1.3f" % precision_score(y_test, y_pred)) + print("\tRecall: %1.3f" % recall_score(y_test, y_pred)) + print("\tF1: %1.3f\n" % f1_score(y_test, y_pred)) + + fraction_of_positives, mean_predicted_value = \ + calibration_curve(y_test, prob_pos, n_bins=10) + + ax1.plot(mean_predicted_value, fraction_of_positives, "s-", + label="%s (%1.3f)" % (name, clf_score)) + + ax2.hist(prob_pos, range=(0, 1), bins=10, label=name, + histtype="step", lw=2) + + ax1.set_ylabel("Fraction of positives") + ax1.set_ylim([-0.05, 1.05]) + ax1.legend(loc="lower right") + ax1.set_title('Calibration plots (reliability curve)') + + ax2.set_xlabel("Mean predicted value") + ax2.set_ylabel("Count") + ax2.legend(loc="upper center", ncol=2) + + plt.tight_layout() + +# Plot calibration cuve for Gaussian Naive Bayes +plot_calibration_curve(GaussianNB(), "Naive Bayes", 1) + +# Plot calibration cuve for Linear SVC +plot_calibration_curve(LinearSVC(), "SVC", 2) + +plt.show() diff --git a/examples/calibration/plot_calibration_multiclass.py b/examples/calibration/plot_calibration_multiclass.py new file mode 100644 index 0000000000000..7843b84fa35cb --- /dev/null +++ b/examples/calibration/plot_calibration_multiclass.py @@ -0,0 +1,168 @@ +""" +================================================== +Probability Calibration for 3-class classification +================================================== + +This example illustrates how sigmoid calibration changes predicted +probabilities for a 3-class classification problem. Illustrated is the +standard 2-simplex, where the three corners correspond to the three classes. +Arrows point from the probability vectors predicted by an uncalibrated +classifier to the probability vectors predicted by the same classifier after +sigmoid calibration on a hold-out validation set. Colors indicate the true +class of an instance (red: class 1, green: class 2, blue: class 3). + +The base classifier is a random forest classifier with 25 base estimators +(trees). If this classifier is trained on all 800 training datapoints, it is +overly confident in its predictions and thus incurs a large log-loss. +Calibrating an identical classifier, which was trained on 600 datapoints, with +method='sigmoid' on the remaining 200 datapoints reduces the confidence of the +predictions, i.e., moves the probability vectors from the edges of the simplex +towards the center. This calibration results in a lower log-loss. Note that an +alternative would have been to increase the number of base estimators which +would have resulted in a similar decrease in log-loss. +""" +print(__doc__) + +# Author: Jan Hendrik Metzen +# License: BSD Style. + + +import matplotlib.pyplot as plt + +import numpy as np + +from sklearn.datasets import make_blobs +from sklearn.ensemble import RandomForestClassifier +from sklearn.calibration import CalibratedClassifierCV +from sklearn.metrics import log_loss + +np.random.seed(0) + +# Generate data +X, y = make_blobs(n_samples=1000, n_features=2, random_state=42, + cluster_std=5.0) +X_train, y_train = X[:600], y[:600] +X_valid, y_valid = X[600:800], y[600:800] +X_train_valid, y_train_valid = X[:800], y[:800] +X_test, y_test = X[800:], y[800:] + +# Train uncalibrated random forest classifier on whole train and validation +# data and evaluate on test data +clf = RandomForestClassifier(n_estimators=25) +clf.fit(X_train_valid, y_train_valid) +clf_probs = clf.predict_proba(X_test) +score = log_loss(y_test, clf_probs) + +# Train random forest classifier, calibrate on validation data and evaluate +# on test data +clf = RandomForestClassifier(n_estimators=25) +clf.fit(X_train, y_train) +clf_probs = clf.predict_proba(X_test) +sig_clf = CalibratedClassifierCV(clf, method="sigmoid", cv="prefit") +sig_clf.fit(X_valid, y_valid) +sig_clf_probs = sig_clf.predict_proba(X_test) +sig_score = log_loss(y_test, sig_clf_probs) + +# Plot changes in predicted probabilities via arrows +plt.figure(0) +colors = ["r", "g", "b"] +for i in range(clf_probs.shape[0]): + plt.arrow(clf_probs[i, 0], clf_probs[i, 1], + sig_clf_probs[i, 0] - clf_probs[i, 0], + sig_clf_probs[i, 1] - clf_probs[i, 1], + color=colors[y_test[i]], head_width=1e-2) + +# Plot perfect predictions +plt.plot([1.0], [0.0], 'ro', ms=20, label="Class 1") +plt.plot([0.0], [1.0], 'go', ms=20, label="Class 2") +plt.plot([0.0], [0.0], 'bo', ms=20, label="Class 3") + +# Plot boundaries of unit simplex +plt.plot([0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], 'k', label="Simplex") + +# Annotate points on the simplex +plt.annotate(r'($\frac{1}{3}$, $\frac{1}{3}$, $\frac{1}{3}$)', + xy=(1.0/3, 1.0/3), xytext=(1.0/3, .23), xycoords='data', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='center', verticalalignment='center') +plt.plot([1.0/3], [1.0/3], 'ko', ms=5) +plt.annotate(r'($\frac{1}{2}$, $0$, $\frac{1}{2}$)', + xy=(.5, .0), xytext=(.5, .1), xycoords='data', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='center', verticalalignment='center') +plt.annotate(r'($0$, $\frac{1}{2}$, $\frac{1}{2}$)', + xy=(.0, .5), xytext=(.1, .5), xycoords='data', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='center', verticalalignment='center') +plt.annotate(r'($\frac{1}{2}$, $\frac{1}{2}$, $0$)', + xy=(.5, .5), xytext=(.6, .6), xycoords='data', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='center', verticalalignment='center') +plt.annotate(r'($0$, $0$, $1$)', + xy=(0, 0), xytext=(.1, .1), xycoords='data', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='center', verticalalignment='center') +plt.annotate(r'($1$, $0$, $0$)', + xy=(1, 0), xytext=(1, .1), xycoords='data', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='center', verticalalignment='center') +plt.annotate(r'($0$, $1$, $0$)', + xy=(0, 1), xytext=(.1, 1), xycoords='data', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='center', verticalalignment='center') +# Add grid +plt.grid("off") +for x in [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]: + plt.plot([0, x], [x, 0], 'k', alpha=0.2) + plt.plot([0, 0 + (1-x)/2], [x, x + (1-x)/2], 'k', alpha=0.2) + plt.plot([x, x + (1-x)/2], [0, 0 + (1-x)/2], 'k', alpha=0.2) + +plt.title("Change of predicted probabilities after sigmoid calibration") +plt.xlabel("Probability class 1") +plt.ylabel("Probability class 2") +plt.xlim(-0.05, 1.05) +plt.ylim(-0.05, 1.05) +plt.legend(loc="best") + +print("Log-loss of") +print(" * uncalibrated classifier trained on 800 datapoints: %.3f " + % score) +print(" * classifier trained on 600 datapoints and calibrated on " + "200 datapoint: %.3f" % sig_score) + +# Illustrate calibrator +plt.figure(1) +# generate grid over 2-simplex +p1d = np.linspace(0, 1, 20) +p0, p1 = np.meshgrid(p1d, p1d) +p2 = 1 - p0 - p1 +p = np.c_[p0.ravel(), p1.ravel(), p2.ravel()] +p = p[p[:, 2] >= 0] + +calibrated_classifier = sig_clf.calibrated_classifiers_[0] +prediction = np.vstack([calibrator.predict(this_p) + for calibrator, this_p in + zip(calibrated_classifier.calibrators_, p.T)]).T +prediction /= prediction.sum(axis=1)[:, None] + +# Ploit modifications of calibrator +for i in range(prediction.shape[0]): + plt.arrow(p[i, 0], p[i, 1], + prediction[i, 0] - p[i, 0], prediction[i, 1] - p[i, 1], + head_width=1e-2, color=colors[np.argmax(p[i])]) +# Plot boundaries of unit simplex +plt.plot([0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], 'k', label="Simplex") + +plt.grid("off") +for x in [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]: + plt.plot([0, x], [x, 0], 'k', alpha=0.2) + plt.plot([0, 0 + (1-x)/2], [x, x + (1-x)/2], 'k', alpha=0.2) + plt.plot([x, x + (1-x)/2], [0, 0 + (1-x)/2], 'k', alpha=0.2) + +plt.title("Illustration of sigmoid calibrator") +plt.xlabel("Probability class 1") +plt.ylabel("Probability class 2") +plt.xlim(-0.05, 1.05) +plt.ylim(-0.05, 1.05) + +plt.show() diff --git a/examples/calibration/plot_compare_calibration.py b/examples/calibration/plot_compare_calibration.py new file mode 100644 index 0000000000000..fb6bcd283e228 --- /dev/null +++ b/examples/calibration/plot_compare_calibration.py @@ -0,0 +1,122 @@ +""" +======================================== +Comparison of Calibration of Classifiers +======================================== + +Well calibrated classifiers are probabilistic classifiers for which the output +of the predict_proba method can be directly interpreted as a confidence level. +For instance a well calibrated (binary) classifier should classify the samples +such that among the samples to which it gave a predict_proba value close to +0.8, approx. 80% actually belong to the positive class. + +LogisticRegression returns well calibrated predictions as it directly +optimizes log-loss. In contrast, the other methods return biased probilities, +with different biases per method: + +* GaussianNaiveBayes tends to push probabilties to 0 or 1 (note the counts in + the histograms). This is mainly because it makes the assumption that features + are conditionally independent given the class, which is not the case in this + dataset which contains 2 redundant features. + +* RandomForestClassifier shows the opposite behavior: the histograms show + peaks at approx. 0.2 and 0.9 probability, while probabilities close to 0 or 1 + are very rare. An explanation for this is given by Niculescu-Mizil and Caruana + [1]: "Methods such as bagging and random forests that average predictions from + a base set of models can have difficulty making predictions near 0 and 1 + because variance in the underlying base models will bias predictions that + should be near zero or one away from these values. Because predictions are + restricted to the interval [0,1], errors caused by variance tend to be one- + sided near zero and one. For example, if a model should predict p = 0 for a + case, the only way bagging can achieve this is if all bagged trees predict + zero. If we add noise to the trees that bagging is averaging over, this noise + will cause some trees to predict values larger than 0 for this case, thus + moving the average prediction of the bagged ensemble away from 0. We observe + this effect most strongly with random forests because the base-level trees + trained with random forests have relatively high variance due to feature + subseting." As a result, the calibration curve shows a characteristic sigmoid + shape, indicating that the classifier could trust its "intuition" more and + return probabilties closer to 0 or 1 typically. + +* Support Vector Classification (SVC) shows an even more sigmoid curve as + the RandomForestClassifier, which is typical for maximum-margin methods + (compare Niculescu-Mizil and Caruana [1]), which focus on hard samples + that are close to the decision boundary (the support vectors). + +.. topic:: References: + + .. [1] Predicting Good Probabilities with Supervised Learning, + A. Niculescu-Mizil & R. Caruana, ICML 2005 +""" +print(__doc__) + +# Author: Jan Hendrik Metzen +# License: BSD Style. + +import numpy as np +np.random.seed(0) + +import matplotlib.pyplot as plt + +from sklearn import datasets +from sklearn.naive_bayes import GaussianNB +from sklearn.linear_model import LogisticRegression +from sklearn.ensemble import RandomForestClassifier +from sklearn.svm import LinearSVC +from sklearn.calibration import calibration_curve + +X, y = datasets.make_classification(n_samples=100000, n_features=20, + n_informative=2, n_redundant=2) + +train_samples = 100 # Samples used for training the models + +X_train = X[:train_samples] +X_test = X[train_samples:] +y_train = y[:train_samples] +y_test = y[train_samples:] + +# Create classifiers +lr = LogisticRegression() +gnb = GaussianNB() +svc = LinearSVC(C=1.0) +rfc = RandomForestClassifier(n_estimators=100) + + +############################################################################### +# Plot calibration plots + +plt.figure(figsize=(10, 10)) +ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2) +ax2 = plt.subplot2grid((3, 1), (2, 0)) + +ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") +for clf, name in [(lr, 'Logistic'), + (gnb, 'Naive Bayes'), + (svc, 'Support Vector Classification'), + (rfc, 'Random Forest')]: + clf.fit(X_train, y_train) + if hasattr(clf, "predict_proba"): + prob_pos = clf.predict_proba(X_test)[:, 1] + else: # use decision function + prob_pos = clf.decision_function(X_test) + prob_pos = \ + (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min()) + fraction_of_positives, mean_predicted_value = \ + calibration_curve(y_test, prob_pos, n_bins=10) + + ax1.plot(mean_predicted_value, fraction_of_positives, "s-", + label="%s" % (name, )) + + ax2.hist(prob_pos, range=(0, 1), bins=10, label=name, + histtype="step", lw=2) + +ax1.set_ylabel("Fraction of positives") +ax1.set_ylim([-0.05, 1.05]) +ax1.legend(loc="lower right") +ax1.set_title('Calibration plots (reliability curve)') + +ax2.set_xlabel("Mean predicted value") +ax2.set_ylabel("Count") +ax2.legend(loc="upper center", ncol=2) + +plt.tight_layout() +plt.show() diff --git a/examples/classification/README.txt b/examples/classification/README.txt new file mode 100644 index 0000000000000..17743d52b2f5a --- /dev/null +++ b/examples/classification/README.txt @@ -0,0 +1,6 @@ +.. _classification_examples: + +Classification +----------------------- + +General examples about classification algorithms. diff --git a/examples/classification/plot_classification_probability.py b/examples/classification/plot_classification_probability.py new file mode 100644 index 0000000000000..1b768535e4391 --- /dev/null +++ b/examples/classification/plot_classification_probability.py @@ -0,0 +1,81 @@ +""" +=============================== +Plot classification probability +=============================== + +Plot the classification probability for different classifiers. We use a 3 +class dataset, and we classify it with a Support Vector classifier, L1 +and L2 penalized logistic regression with either a One-Vs-Rest or multinomial +setting. + +The logistic regression is not a multiclass classifier out of the box. As +a result it can identify only the first class. +""" +print(__doc__) + +# Author: Alexandre Gramfort +# License: BSD 3 clause + +import matplotlib.pyplot as plt +import numpy as np + +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC +from sklearn import datasets + +iris = datasets.load_iris() +X = iris.data[:, 0:2] # we only take the first two features for visualization +y = iris.target + +n_features = X.shape[1] + +C = 1.0 + +# Create different classifiers. The logistic regression cannot do +# multiclass out of the box. +classifiers = {'L1 logistic': LogisticRegression(C=C, penalty='l1'), + 'L2 logistic (OvR)': LogisticRegression(C=C, penalty='l2'), + 'Linear SVC': SVC(kernel='linear', C=C, probability=True, + random_state=0), + 'L2 logistic (Multinomial)': LogisticRegression( + C=C, solver='lbfgs', multi_class='multinomial' + )} + +n_classifiers = len(classifiers) + +plt.figure(figsize=(3 * 2, n_classifiers * 2)) +plt.subplots_adjust(bottom=.2, top=.95) + +xx = np.linspace(3, 9, 100) +yy = np.linspace(1, 5, 100).T +xx, yy = np.meshgrid(xx, yy) +Xfull = np.c_[xx.ravel(), yy.ravel()] + +for index, (name, classifier) in enumerate(classifiers.items()): + classifier.fit(X, y) + + y_pred = classifier.predict(X) + classif_rate = np.mean(y_pred.ravel() == y.ravel()) * 100 + print("classif_rate for %s : %f " % (name, classif_rate)) + + # View probabilities= + probas = classifier.predict_proba(Xfull) + n_classes = np.unique(y_pred).size + for k in range(n_classes): + plt.subplot(n_classifiers, n_classes, index * n_classes + k + 1) + plt.title("Class %d" % k) + if k == 0: + plt.ylabel(name) + imshow_handle = plt.imshow(probas[:, k].reshape((100, 100)), + extent=(3, 9, 1, 5), origin='lower') + plt.xticks(()) + plt.yticks(()) + idx = (y_pred == k) + if idx.any(): + plt.scatter(X[idx, 0], X[idx, 1], marker='o', c='k') + +ax = plt.axes([0.15, 0.04, 0.7, 0.05]) +plt.title("Probability") +plt.colorbar(imshow_handle, cax=ax, orientation='horizontal') + +plt.show() diff --git a/examples/classification/plot_classifier_comparison.py b/examples/classification/plot_classifier_comparison.py new file mode 100644 index 0000000000000..7be3c0cacad9f --- /dev/null +++ b/examples/classification/plot_classifier_comparison.py @@ -0,0 +1,132 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +===================== +Classifier comparison +===================== + +A comparison of a several classifiers in scikit-learn on synthetic datasets. +The point of this example is to illustrate the nature of decision boundaries +of different classifiers. +This should be taken with a grain of salt, as the intuition conveyed by +these examples does not necessarily carry over to real datasets. + +Particularly in high-dimensional spaces, data can more easily be separated +linearly and the simplicity of classifiers such as naive Bayes and linear SVMs +might lead to better generalization than is achieved by other classifiers. + +The plots show training points in solid colors and testing points +semi-transparent. The lower right shows the classification accuracy on the test +set. +""" +print(__doc__) + + +# Code source: Gaël Varoquaux +# Andreas Müller +# Modified for documentation by Jaques Grobler +# License: BSD 3 clause + +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.colors import ListedColormap +from sklearn.cross_validation import train_test_split +from sklearn.preprocessing import StandardScaler +from sklearn.datasets import make_moons, make_circles, make_classification +from sklearn.neighbors import KNeighborsClassifier +from sklearn.svm import SVC +from sklearn.tree import DecisionTreeClassifier +from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier +from sklearn.naive_bayes import GaussianNB +from sklearn.lda import LDA +from sklearn.qda import QDA + +h = .02 # step size in the mesh + +names = ["Nearest Neighbors", "Linear SVM", "RBF SVM", "Decision Tree", + "Random Forest", "AdaBoost", "Naive Bayes", "LDA", "QDA"] +classifiers = [ + KNeighborsClassifier(3), + SVC(kernel="linear", C=0.025), + SVC(gamma=2, C=1), + DecisionTreeClassifier(max_depth=5), + RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1), + AdaBoostClassifier(), + GaussianNB(), + LDA(), + QDA()] + +X, y = make_classification(n_features=2, n_redundant=0, n_informative=2, + random_state=1, n_clusters_per_class=1) +rng = np.random.RandomState(2) +X += 2 * rng.uniform(size=X.shape) +linearly_separable = (X, y) + +datasets = [make_moons(noise=0.3, random_state=0), + make_circles(noise=0.2, factor=0.5, random_state=1), + linearly_separable + ] + +figure = plt.figure(figsize=(27, 9)) +i = 1 +# iterate over datasets +for ds in datasets: + # preprocess dataset, split into training and test part + X, y = ds + X = StandardScaler().fit_transform(X) + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4) + + x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 + y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 + xx, yy = np.meshgrid(np.arange(x_min, x_max, h), + np.arange(y_min, y_max, h)) + + # just plot the dataset first + cm = plt.cm.RdBu + cm_bright = ListedColormap(['#FF0000', '#0000FF']) + ax = plt.subplot(len(datasets), len(classifiers) + 1, i) + # Plot the training points + ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright) + # and testing points + ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6) + ax.set_xlim(xx.min(), xx.max()) + ax.set_ylim(yy.min(), yy.max()) + ax.set_xticks(()) + ax.set_yticks(()) + i += 1 + + # iterate over classifiers + for name, clf in zip(names, classifiers): + ax = plt.subplot(len(datasets), len(classifiers) + 1, i) + clf.fit(X_train, y_train) + score = clf.score(X_test, y_test) + + # Plot the decision boundary. For that, we will assign a color to each + # point in the mesh [x_min, m_max]x[y_min, y_max]. + if hasattr(clf, "decision_function"): + Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) + else: + Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1] + + # Put the result into a color plot + Z = Z.reshape(xx.shape) + ax.contourf(xx, yy, Z, cmap=cm, alpha=.8) + + # Plot also the training points + ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright) + # and testing points + ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, + alpha=0.6) + + ax.set_xlim(xx.min(), xx.max()) + ax.set_ylim(yy.min(), yy.max()) + ax.set_xticks(()) + ax.set_yticks(()) + ax.set_title(name) + ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'), + size=15, horizontalalignment='right') + i += 1 + +figure.subplots_adjust(left=.02, right=.98) +plt.show() diff --git a/examples/classification/plot_digits_classification.py b/examples/classification/plot_digits_classification.py new file mode 100644 index 0000000000000..55062006b5bea --- /dev/null +++ b/examples/classification/plot_digits_classification.py @@ -0,0 +1,66 @@ +""" +================================ +Recognizing hand-written digits +================================ + +An example showing how the scikit-learn can be used to recognize images of +hand-written digits. + +This example is commented in the +:ref:`tutorial section of the user manual `. + +""" +print(__doc__) + +# Author: Gael Varoquaux +# License: BSD 3 clause + +# Standard scientific Python imports +import matplotlib.pyplot as plt + +# Import datasets, classifiers and performance metrics +from sklearn import datasets, svm, metrics + +# The digits dataset +digits = datasets.load_digits() + +# The data that we are interested in is made of 8x8 images of digits, let's +# have a look at the first 3 images, stored in the `images` attribute of the +# dataset. If we were working from image files, we could load them using +# pylab.imread. Note that each image must have the same size. For these +# images, we know which digit they represent: it is given in the 'target' of +# the dataset. +images_and_labels = list(zip(digits.images, digits.target)) +for index, (image, label) in enumerate(images_and_labels[:4]): + plt.subplot(2, 4, index + 1) + plt.axis('off') + plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') + plt.title('Training: %i' % label) + +# To apply a classifier on this data, we need to flatten the image, to +# turn the data in a (samples, feature) matrix: +n_samples = len(digits.images) +data = digits.images.reshape((n_samples, -1)) + +# Create a classifier: a support vector classifier +classifier = svm.SVC(gamma=0.001) + +# We learn the digits on the first half of the digits +classifier.fit(data[:n_samples / 2], digits.target[:n_samples / 2]) + +# Now predict the value of the digit on the second half: +expected = digits.target[n_samples / 2:] +predicted = classifier.predict(data[n_samples / 2:]) + +print("Classification report for classifier %s:\n%s\n" + % (classifier, metrics.classification_report(expected, predicted))) +print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted)) + +images_and_predictions = list(zip(digits.images[n_samples / 2:], predicted)) +for index, (image, prediction) in enumerate(images_and_predictions[:4]): + plt.subplot(2, 4, index + 5) + plt.axis('off') + plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') + plt.title('Prediction: %i' % prediction) + +plt.show() diff --git a/examples/classification/plot_lda.py b/examples/classification/plot_lda.py new file mode 100644 index 0000000000000..42b404c45784c --- /dev/null +++ b/examples/classification/plot_lda.py @@ -0,0 +1,70 @@ +""" +==================================================================== +Normal and Shrinkage Linear Discriminant Analysis for classification +==================================================================== + +Shows how shrinkage improves classification. +""" + +from __future__ import division + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.datasets import make_blobs +from sklearn.lda import LDA + + +n_train = 20 # samples for training +n_test = 200 # samples for testing +n_averages = 50 # how often to repeat classification +n_features_max = 75 # maximum number of features +step = 4 # step size for the calculation + + +def generate_data(n_samples, n_features): + """Generate random blob-ish data with noisy features. + + This returns an array of input data with shape `(n_samples, n_features)` + and an array of `n_samples` target labels. + + Only one feature contains discriminative information, the other features + contain only noise. + """ + X, y = make_blobs(n_samples=n_samples, n_features=1, centers=[[-2], [2]]) + + # add non-discriminative features + if n_features > 1: + X = np.hstack([X, np.random.randn(n_samples, n_features - 1)]) + return X, y + +acc_clf1, acc_clf2 = [], [] +n_features_range = range(1, n_features_max + 1, step) +for n_features in n_features_range: + score_clf1, score_clf2 = 0, 0 + for _ in range(n_averages): + X, y = generate_data(n_train, n_features) + + clf1 = LDA(solver='lsqr', shrinkage='auto').fit(X, y) + clf2 = LDA(solver='lsqr', shrinkage=None).fit(X, y) + + X, y = generate_data(n_test, n_features) + score_clf1 += clf1.score(X, y) + score_clf2 += clf2.score(X, y) + + acc_clf1.append(score_clf1 / n_averages) + acc_clf2.append(score_clf2 / n_averages) + +features_samples_ratio = np.array(n_features_range) / n_train + +plt.plot(features_samples_ratio, acc_clf1, linewidth=2, + label="LDA with shrinkage", color='r') +plt.plot(features_samples_ratio, acc_clf2, linewidth=2, + label="LDA", color='g') + +plt.xlabel('n_features / n_samples') +plt.ylabel('Classification accuracy') + +plt.legend(loc=1, prop={'size': 12}) +plt.suptitle('LDA vs. shrinkage LDA (1 discriminative feature)') +plt.show() diff --git a/examples/plot_lda_qda.py b/examples/classification/plot_lda_qda.py similarity index 70% rename from examples/plot_lda_qda.py rename to examples/classification/plot_lda_qda.py index ad9f88ff9d992..c22f38e2a47e2 100644 --- a/examples/plot_lda_qda.py +++ b/examples/classification/plot_lda_qda.py @@ -5,11 +5,11 @@ Plot the confidence ellipsoids of each class and decision boundary """ -print __doc__ +print(__doc__) from scipy import linalg import numpy as np -import pylab as pl +import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib import colors @@ -18,11 +18,12 @@ ############################################################################### # colormap -cmap = colors.LinearSegmentedColormap('red_blue_classes', +cmap = colors.LinearSegmentedColormap( + 'red_blue_classes', {'red': [(0, 1, 1), (1, 0.7, 0.7)], 'green': [(0, 0.7, 0.7), (1, 0.7, 0.7)], 'blue': [(0, 0.7, 0.7), (1, 1, 1)]}) -pl.cm.register_cmap(cmap=cmap) +plt.cm.register_cmap(cmap=cmap) ############################################################################### @@ -52,48 +53,48 @@ def dataset_cov(): ############################################################################### # plot functions def plot_data(lda, X, y, y_pred, fig_index): - splot = pl.subplot(2, 2, fig_index) + splot = plt.subplot(2, 2, fig_index) if fig_index == 1: - pl.title('Linear Discriminant Analysis') - pl.ylabel('Data with fixed covariance') + plt.title('Linear Discriminant Analysis') + plt.ylabel('Data with fixed covariance') elif fig_index == 2: - pl.title('Quadratic Discriminant Analysis') + plt.title('Quadratic Discriminant Analysis') elif fig_index == 3: - pl.ylabel('Data with varying covariances') + plt.ylabel('Data with varying covariances') tp = (y == y_pred) # True Positive tp0, tp1 = tp[y == 0], tp[y == 1] X0, X1 = X[y == 0], X[y == 1] - X0_tp, X0_fp = X0[tp0], X0[tp0 != True] - X1_tp, X1_fp = X1[tp1], X1[tp1 != True] + X0_tp, X0_fp = X0[tp0], X0[~tp0] + X1_tp, X1_fp = X1[tp1], X1[~tp1] xmin, xmax = X[:, 0].min(), X[:, 0].max() ymin, ymax = X[:, 1].min(), X[:, 1].max() # class 0: dots - pl.plot(X0_tp[:, 0], X0_tp[:, 1], 'o', color='red') - pl.plot(X0_fp[:, 0], X0_fp[:, 1], '.', color='#990000') # dark red + plt.plot(X0_tp[:, 0], X0_tp[:, 1], 'o', color='red') + plt.plot(X0_fp[:, 0], X0_fp[:, 1], '.', color='#990000') # dark red # class 1: dots - pl.plot(X1_tp[:, 0], X1_tp[:, 1], 'o', color='blue') - pl.plot(X1_fp[:, 0], X1_fp[:, 1], '.', color='#000099') # dark blue + plt.plot(X1_tp[:, 0], X1_tp[:, 1], 'o', color='blue') + plt.plot(X1_fp[:, 0], X1_fp[:, 1], '.', color='#000099') # dark blue # class 0 and 1 : areas nx, ny = 200, 100 - x_min, x_max = pl.xlim() - y_min, y_max = pl.ylim() + x_min, x_max = plt.xlim() + y_min, y_max = plt.ylim() xx, yy = np.meshgrid(np.linspace(x_min, x_max, nx), np.linspace(y_min, y_max, ny)) Z = lda.predict_proba(np.c_[xx.ravel(), yy.ravel()]) Z = Z[:, 1].reshape(xx.shape) - pl.pcolormesh(xx, yy, Z, cmap='red_blue_classes', - norm=colors.Normalize(0., 1.)) - pl.contour(xx, yy, Z, [0.5], linewidths=2., colors='k') + plt.pcolormesh(xx, yy, Z, cmap='red_blue_classes', + norm=colors.Normalize(0., 1.)) + plt.contour(xx, yy, Z, [0.5], linewidths=2., colors='k') # means - pl.plot(lda.means_[0][0], lda.means_[0][1], - 'o', color='black', markersize=10) - pl.plot(lda.means_[1][0], lda.means_[1][1], - 'o', color='black', markersize=10) + plt.plot(lda.means_[0][0], lda.means_[0][1], + 'o', color='black', markersize=10) + plt.plot(lda.means_[1][0], lda.means_[1][1], + 'o', color='black', markersize=10) return splot @@ -103,9 +104,9 @@ def plot_ellipse(splot, mean, cov, color): u = w[0] / linalg.norm(w[0]) angle = np.arctan(u[1] / u[0]) angle = 180 * angle / np.pi # convert to degrees - # filled gaussian at 2 standard deviation + # filled Gaussian at 2 standard deviation ell = mpl.patches.Ellipse(mean, 2 * v[0] ** 0.5, 2 * v[1] ** 0.5, - 180 + angle, color=color) + 180 + angle, color=color) ell.set_clip_box(splot.bbox) ell.set_alpha(0.5) splot.add_artist(ell) @@ -125,17 +126,17 @@ def plot_qda_cov(qda, splot): ############################################################################### for i, (X, y) in enumerate([dataset_fixed_cov(), dataset_cov()]): # LDA - lda = LDA() - y_pred = lda.fit(X, y, store_covariance=True).predict(X) + lda = LDA(solver="svd", store_covariance=True) + y_pred = lda.fit(X, y).predict(X) splot = plot_data(lda, X, y, y_pred, fig_index=2 * i + 1) plot_lda_cov(lda, splot) - pl.axis('tight') + plt.axis('tight') # QDA qda = QDA() y_pred = qda.fit(X, y, store_covariances=True).predict(X) splot = plot_data(qda, X, y, y_pred, fig_index=2 * i + 2) plot_qda_cov(qda, splot) - pl.axis('tight') -pl.suptitle('LDA vs QDA') -pl.show() + plt.axis('tight') +plt.suptitle('LDA vs QDA') +plt.show() diff --git a/examples/cluster/README.txt b/examples/cluster/README.txt index ea95bec9f6249..13f62220d6b23 100644 --- a/examples/cluster/README.txt +++ b/examples/cluster/README.txt @@ -3,4 +3,4 @@ Clustering ---------- -Examples concerning the :mod:`sklearn.cluster` package. +Examples concerning the :mod:`sklearn.cluster` module. diff --git a/examples/cluster/plot_adjusted_for_chance_measures.py b/examples/cluster/plot_adjusted_for_chance_measures.py index f2d8510968ebf..66298d3c5ba96 100644 --- a/examples/cluster/plot_adjusted_for_chance_measures.py +++ b/examples/cluster/plot_adjusted_for_chance_measures.py @@ -8,7 +8,7 @@ Non-adjusted measures such as the V-Measure show a dependency between the number of clusters and the number of samples: the mean V-Measure -of random labeling increases signicantly as the number of clusters is +of random labeling increases significantly as the number of clusters is closer to the total number of samples used to compute the measure. Adjusted for chance measure such as ARI display some random variations @@ -20,13 +20,13 @@ value of k on various overlapping sub-samples of the dataset. """ -print __doc__ +print(__doc__) # Author: Olivier Grisel -# License: Simplified BSD +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from time import time from sklearn import metrics @@ -39,7 +39,7 @@ def uniform_labelings_scores(score_func, n_samples, n_clusters_range, possible value in ``n_clusters_range``. When fixed_n_classes is not None the first labeling is considered a ground - truth class assignement with fixed number of classes. + truth class assignment with fixed number of classes. """ random_labels = np.random.RandomState(seed).random_integers scores = np.zeros((len(n_clusters_range), n_runs)) @@ -68,27 +68,27 @@ def uniform_labelings_scores(score_func, n_samples, n_clusters_range, n_samples = 100 n_clusters_range = np.linspace(2, n_samples, 10).astype(np.int) -pl.figure(1) +plt.figure(1) plots = [] names = [] for score_func in score_funcs: - print "Computing %s for %d values of n_clusters and n_samples=%d" % ( - score_func.__name__, len(n_clusters_range), n_samples) + print("Computing %s for %d values of n_clusters and n_samples=%d" + % (score_func.__name__, len(n_clusters_range), n_samples)) t0 = time() scores = uniform_labelings_scores(score_func, n_samples, n_clusters_range) - print "done in %0.3fs" % (time() - t0) - plots.append(pl.errorbar( + print("done in %0.3fs" % (time() - t0)) + plots.append(plt.errorbar( n_clusters_range, np.median(scores, axis=1), scores.std(axis=1))[0]) names.append(score_func.__name__) -pl.title("Clustering measures for 2 random uniform labelings\n" - "with equal number of clusters") -pl.xlabel('Number of clusters (Number of samples is fixed to %d)' % n_samples) -pl.ylabel('Score value') -pl.legend(plots, names) -pl.ylim(ymin=-0.05, ymax=1.05) +plt.title("Clustering measures for 2 random uniform labelings\n" + "with equal number of clusters") +plt.xlabel('Number of clusters (Number of samples is fixed to %d)' % n_samples) +plt.ylabel('Score value') +plt.legend(plots, names) +plt.ylim(ymin=-0.05, ymax=1.05) # Random labeling with varying n_clusters against ground class labels @@ -98,26 +98,26 @@ def uniform_labelings_scores(score_func, n_samples, n_clusters_range, n_clusters_range = np.linspace(2, 100, 10).astype(np.int) n_classes = 10 -pl.figure(2) +plt.figure(2) plots = [] names = [] for score_func in score_funcs: - print "Computing %s for %d values of n_clusters and n_samples=%d" % ( - score_func.__name__, len(n_clusters_range), n_samples) + print("Computing %s for %d values of n_clusters and n_samples=%d" + % (score_func.__name__, len(n_clusters_range), n_samples)) t0 = time() scores = uniform_labelings_scores(score_func, n_samples, n_clusters_range, fixed_n_classes=n_classes) - print "done in %0.3fs" % (time() - t0) - plots.append(pl.errorbar( + print("done in %0.3fs" % (time() - t0)) + plots.append(plt.errorbar( n_clusters_range, scores.mean(axis=1), scores.std(axis=1))[0]) names.append(score_func.__name__) -pl.title("Clustering measures for random uniform labeling\n" - "against reference assignement with %d classes" % n_classes) -pl.xlabel('Number of clusters (Number of samples is fixed to %d)' % n_samples) -pl.ylabel('Score value') -pl.ylim(ymin=-0.05, ymax=1.05) -pl.legend(plots, names) -pl.show() +plt.title("Clustering measures for random uniform labeling\n" + "against reference assignment with %d classes" % n_classes) +plt.xlabel('Number of clusters (Number of samples is fixed to %d)' % n_samples) +plt.ylabel('Score value') +plt.ylim(ymin=-0.05, ymax=1.05) +plt.legend(plots, names) +plt.show() diff --git a/examples/cluster/plot_affinity_propagation.py b/examples/cluster/plot_affinity_propagation.py index 69b9fbf185b7a..0d6c395a4e4bf 100644 --- a/examples/cluster/plot_affinity_propagation.py +++ b/examples/cluster/plot_affinity_propagation.py @@ -8,7 +8,7 @@ Between Data Points", Science Feb. 2007 """ -print __doc__ +print(__doc__) from sklearn.cluster import AffinityPropagation from sklearn import metrics @@ -18,7 +18,7 @@ # Generate sample data centers = [[1, 1], [-1, -1], [1, -1]] X, labels_true = make_blobs(n_samples=300, centers=centers, cluster_std=0.5, - random_state=0) + random_state=0) ############################################################################## # Compute Affinity Propagation @@ -28,35 +28,35 @@ n_clusters_ = len(cluster_centers_indices) -print 'Estimated number of clusters: %d' % n_clusters_ -print "Homogeneity: %0.3f" % metrics.homogeneity_score(labels_true, labels) -print "Completeness: %0.3f" % metrics.completeness_score(labels_true, labels) -print "V-measure: %0.3f" % metrics.v_measure_score(labels_true, labels) -print "Adjusted Rand Index: %0.3f" % \ - metrics.adjusted_rand_score(labels_true, labels) -print "Adjusted Mutual Information: %0.3f" % \ - metrics.adjusted_mutual_info_score(labels_true, labels) -print ("Silhouette Coefficient: %0.3f" % - metrics.silhouette_score(X, labels, metric='sqeuclidean')) +print('Estimated number of clusters: %d' % n_clusters_) +print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels_true, labels)) +print("Completeness: %0.3f" % metrics.completeness_score(labels_true, labels)) +print("V-measure: %0.3f" % metrics.v_measure_score(labels_true, labels)) +print("Adjusted Rand Index: %0.3f" + % metrics.adjusted_rand_score(labels_true, labels)) +print("Adjusted Mutual Information: %0.3f" + % metrics.adjusted_mutual_info_score(labels_true, labels)) +print("Silhouette Coefficient: %0.3f" + % metrics.silhouette_score(X, labels, metric='sqeuclidean')) ############################################################################## # Plot result -import pylab as pl +import matplotlib.pyplot as plt from itertools import cycle -pl.close('all') -pl.figure(1) -pl.clf() +plt.close('all') +plt.figure(1) +plt.clf() colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') for k, col in zip(range(n_clusters_), colors): class_members = labels == k cluster_center = X[cluster_centers_indices[k]] - pl.plot(X[class_members, 0], X[class_members, 1], col + '.') - pl.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, - markeredgecolor='k', markersize=14) + plt.plot(X[class_members, 0], X[class_members, 1], col + '.') + plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, + markeredgecolor='k', markersize=14) for x in X[class_members]: - pl.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col) + plt.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col) -pl.title('Estimated number of clusters: %d' % n_clusters_) -pl.show() +plt.title('Estimated number of clusters: %d' % n_clusters_) +plt.show() diff --git a/examples/cluster/plot_agglomerative_clustering.py b/examples/cluster/plot_agglomerative_clustering.py new file mode 100644 index 0000000000000..dfb27d17d1a89 --- /dev/null +++ b/examples/cluster/plot_agglomerative_clustering.py @@ -0,0 +1,76 @@ +""" +Agglomerative clustering with and without structure +=================================================== + +This example shows the effect of imposing a connectivity graph to capture +local structure in the data. The graph is simply the graph of 20 nearest +neighbors. + +Two consequences of imposing a connectivity can be seen. First clustering +with a connectivity matrix is much faster. + +Second, when using a connectivity matrix, average and complete linkage are +unstable and tend to create a few clusters that grow very quickly. Indeed, +average and complete linkage fight this percolation behavior by considering all +the distances between two clusters when merging them. The connectivity +graph breaks this mechanism. This effect is more pronounced for very +sparse graphs (try decreasing the number of neighbors in +kneighbors_graph) and with complete linkage. In particular, having a very +small number of neighbors in the graph, imposes a geometry that is +close to that of single linkage, which is well known to have this +percolation instability. +""" +# Authors: Gael Varoquaux, Nelle Varoquaux +# License: BSD 3 clause + +import time +import matplotlib.pyplot as plt +import numpy as np + +from sklearn.cluster import AgglomerativeClustering +from sklearn.neighbors import kneighbors_graph + +# Generate sample data +n_samples = 1500 +np.random.seed(0) +t = 1.5 * np.pi * (1 + 3 * np.random.rand(1, n_samples)) +x = t * np.cos(t) +y = t * np.sin(t) + + +X = np.concatenate((x, y)) +X += .7 * np.random.randn(2, n_samples) +X = X.T + +# Create a graph capturing local connectivity. Larger number of neighbors +# will give more homogeneous clusters to the cost of computation +# time. A very large number of neighbors gives more evenly distributed +# cluster sizes, but may not impose the local manifold structure of +# the data +knn_graph = kneighbors_graph(X, 30, include_self=False) + +for connectivity in (None, knn_graph): + for n_clusters in (30, 3): + plt.figure(figsize=(10, 4)) + for index, linkage in enumerate(('average', 'complete', 'ward')): + plt.subplot(1, 3, index + 1) + model = AgglomerativeClustering(linkage=linkage, + connectivity=connectivity, + n_clusters=n_clusters) + t0 = time.time() + model.fit(X) + elapsed_time = time.time() - t0 + plt.scatter(X[:, 0], X[:, 1], c=model.labels_, + cmap=plt.cm.spectral) + plt.title('linkage=%s (time %.2fs)' % (linkage, elapsed_time), + fontdict=dict(verticalalignment='top')) + plt.axis('equal') + plt.axis('off') + + plt.subplots_adjust(bottom=0, top=.89, wspace=0, + left=0, right=1) + plt.suptitle('n_cluster=%i, connectivity=%r' % + (n_clusters, connectivity is not None), size=17) + + +plt.show() diff --git a/examples/cluster/plot_agglomerative_clustering_metrics.py b/examples/cluster/plot_agglomerative_clustering_metrics.py new file mode 100644 index 0000000000000..be3bbad36764e --- /dev/null +++ b/examples/cluster/plot_agglomerative_clustering_metrics.py @@ -0,0 +1,129 @@ +""" +Agglomerative clustering with different metrics +=============================================== + +Demonstrates the effect of different metrics on the hierarchical clustering. + +The example is engineered to show the effect of the choice of different +metrics. It is applied to waveforms, which can be seen as +high-dimensional vector. Indeed, the difference between metrics is +usually more pronounced in high dimension (in particular for euclidean +and cityblock). + +We generate data from three groups of waveforms. Two of the waveforms +(waveform 1 and waveform 2) are proportional one to the other. The cosine +distance is invariant to a scaling of the data, as a result, it cannot +distinguish these two waveforms. Thus even with no noise, clustering +using this distance will not separate out waveform 1 and 2. + +We add observation noise to these waveforms. We generate very sparse +noise: only 6% of the time points contain noise. As a result, the +l1 norm of this noise (ie "cityblock" distance) is much smaller than it's +l2 norm ("euclidean" distance). This can be seen on the inter-class +distance matrices: the values on the diagonal, that characterize the +spread of the class, are much bigger for the Euclidean distance than for +the cityblock distance. + +When we apply clustering to the data, we find that the clustering +reflects what was in the distance matrices. Indeed, for the Euclidean +distance, the classes are ill-separated because of the noise, and thus +the clustering does not separate the waveforms. For the cityblock +distance, the separation is good and the waveform classes are recovered. +Finally, the cosine distance does not separate at all waveform 1 and 2, +thus the clustering puts them in the same cluster. +""" +# Author: Gael Varoquaux +# License: BSD 3-Clause or CC-0 + +import matplotlib.pyplot as plt +import numpy as np + +from sklearn.cluster import AgglomerativeClustering +from sklearn.metrics import pairwise_distances + +np.random.seed(0) + +# Generate waveform data +n_features = 2000 +t = np.pi * np.linspace(0, 1, n_features) + + +def sqr(x): + return np.sign(np.cos(x)) + +X = list() +y = list() +for i, (phi, a) in enumerate([(.5, .15), (.5, .6), (.3, .2)]): + for _ in range(30): + phase_noise = .01 * np.random.normal() + amplitude_noise = .04 * np.random.normal() + additional_noise = 1 - 2 * np.random.rand(n_features) + # Make the noise sparse + additional_noise[np.abs(additional_noise) < .997] = 0 + + X.append(12 * ((a + amplitude_noise) + * (sqr(6 * (t + phi + phase_noise))) + + additional_noise)) + y.append(i) + +X = np.array(X) +y = np.array(y) + +n_clusters = 3 + +labels = ('Waveform 1', 'Waveform 2', 'Waveform 3') + +# Plot the ground-truth labelling +plt.figure() +plt.axes([0, 0, 1, 1]) +for l, c, n in zip(range(n_clusters), 'rgb', + labels): + lines = plt.plot(X[y == l].T, c=c, alpha=.5) + lines[0].set_label(n) + +plt.legend(loc='best') + +plt.axis('tight') +plt.axis('off') +plt.suptitle("Ground truth", size=20) + + +# Plot the distances +for index, metric in enumerate(["cosine", "euclidean", "cityblock"]): + avg_dist = np.zeros((n_clusters, n_clusters)) + plt.figure(figsize=(5, 4.5)) + for i in range(n_clusters): + for j in range(n_clusters): + avg_dist[i, j] = pairwise_distances(X[y == i], X[y == j], + metric=metric).mean() + avg_dist /= avg_dist.max() + for i in range(n_clusters): + for j in range(n_clusters): + plt.text(i, j, '%5.3f' % avg_dist[i, j], + verticalalignment='center', + horizontalalignment='center') + + plt.imshow(avg_dist, interpolation='nearest', cmap=plt.cm.gnuplot2, + vmin=0) + plt.xticks(range(n_clusters), labels, rotation=45) + plt.yticks(range(n_clusters), labels) + plt.colorbar() + plt.suptitle("Interclass %s distances" % metric, size=18) + plt.tight_layout() + + +# Plot clustering results +for index, metric in enumerate(["cosine", "euclidean", "cityblock"]): + model = AgglomerativeClustering(n_clusters=n_clusters, + linkage="average", affinity=metric) + model.fit(X) + plt.figure() + plt.axes([0, 0, 1, 1]) + for l, c in zip(np.arange(model.n_clusters), 'rgbk'): + plt.plot(X[model.labels_ == l].T, c=c, alpha=.5) + plt.axis('tight') + plt.axis('off') + plt.suptitle("AgglomerativeClustering(affinity=%s)" % metric, size=20) + + +plt.show() diff --git a/examples/cluster/plot_birch_vs_minibatchkmeans.py b/examples/cluster/plot_birch_vs_minibatchkmeans.py new file mode 100644 index 0000000000000..b12d6c412b0ad --- /dev/null +++ b/examples/cluster/plot_birch_vs_minibatchkmeans.py @@ -0,0 +1,103 @@ +""" +================================= +Compare BIRCH and MiniBatchKMeans +================================= + +This example compares the timing of Birch (with and without the global +clustering step) and MiniBatchKMeans on a synthetic dataset having +100,000 samples and 2 features generated using make_blobs. + +If ``n_clusters`` is set to None, the data is reduced from 100,000 +samples to a set of 158 clusters. This can be viewed as a preprocessing +step before the final (global) clustering step that further reduces these +158 clusters to 100 clusters. +""" + +# Authors: Manoj Kumar +# License: BSD 3 clause + +print(__doc__) + +from itertools import cycle +from time import time +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.colors as colors + +from sklearn.preprocessing import StandardScaler +from sklearn.cluster import Birch, MiniBatchKMeans +from sklearn.datasets.samples_generator import make_blobs + + +# Generate centers for the blobs so that it forms a 10 X 10 grid. +xx = np.linspace(-22, 22, 10) +yy = np.linspace(-22, 22, 10) +xx, yy = np.meshgrid(xx, yy) +n_centres = np.hstack((np.ravel(xx)[:, np.newaxis], + np.ravel(yy)[:, np.newaxis])) + +# Generate blobs to do a comparison between MiniBatchKMeans and Birch. +X, y = make_blobs(n_samples=100000, centers=n_centres, random_state=0) + + +# Use all colors that matplotlib provides by default. +colors_ = cycle(colors.cnames.keys()) + +fig = plt.figure(figsize=(12, 4)) +fig.subplots_adjust(left=0.04, right=0.98, bottom=0.1, top=0.9) + +# Compute clustering with Birch with and without the final clustering step +# and plot. +birch_models = [Birch(threshold=1.7, n_clusters=None), + Birch(threshold=1.7, n_clusters=100)] +final_step = ['without global clustering', 'with global clustering'] + +for ind, (birch_model, info) in enumerate(zip(birch_models, final_step)): + t = time() + birch_model.fit(X) + time_ = time() - t + print("Birch %s as the final step took %0.2f seconds" % ( + info, (time() - t))) + + # Plot result + labels = birch_model.labels_ + centroids = birch_model.subcluster_centers_ + n_clusters = np.unique(labels).size + print("n_clusters : %d" % n_clusters) + + ax = fig.add_subplot(1, 3, ind + 1) + for this_centroid, k, col in zip(centroids, range(n_clusters), colors_): + mask = labels == k + ax.plot(X[mask, 0], X[mask, 1], 'w', + markerfacecolor=col, marker='.') + if birch_model.n_clusters is None: + ax.plot(this_centroid[0], this_centroid[1], '+', markerfacecolor=col, + markeredgecolor='k', markersize=5) + ax.set_ylim([-25, 25]) + ax.set_xlim([-25, 25]) + ax.set_autoscaley_on(False) + ax.set_title('Birch %s' % info) + +# Compute clustering with MiniBatchKMeans. +mbk = MiniBatchKMeans(init='k-means++', n_clusters=100, batch_size=100, + n_init=10, max_no_improvement=10, verbose=0, + random_state=0) +t0 = time() +mbk.fit(X) +t_mini_batch = time() - t0 +print("Time taken to run MiniBatchKMeans %0.2f seconds" % t_mini_batch) +mbk_means_labels_unique = np.unique(mbk.labels_) + +ax = fig.add_subplot(1, 3, 3) +for this_centroid, k, col in zip(mbk.cluster_centers_, + range(n_clusters), colors_): + mask = mbk.labels_ == k + ax.plot(X[mask, 0], X[mask, 1], 'w', markerfacecolor=col, marker='.') + ax.plot(this_centroid[0], this_centroid[1], '+', markeredgecolor='k', + markersize=5) +ax.set_xlim([-25, 25]) +ax.set_ylim([-25, 25]) +ax.set_title("MiniBatchKMeans") +ax.set_autoscaley_on(False) +plt.show() diff --git a/examples/cluster/plot_cluster_comparison.py b/examples/cluster/plot_cluster_comparison.py index 9e10e51935a73..2e624714a2bfc 100644 --- a/examples/cluster/plot_cluster_comparison.py +++ b/examples/cluster/plot_cluster_comparison.py @@ -20,15 +20,14 @@ (damping and per-point preference) were set to to mitigate this behavior. """ -print __doc__ +print(__doc__) import time import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import cluster, datasets -from sklearn.metrics import euclidean_distances from sklearn.neighbors import kneighbors_graph from sklearn.preprocessing import StandardScaler @@ -46,13 +45,20 @@ colors = np.array([x for x in 'bgrcmykbgrcmykbgrcmykbgrcmyk']) colors = np.hstack([colors] * 20) -pl.figure(figsize=(14, 9.5)) -pl.subplots_adjust(left=.001, right=.999, bottom=.001, top=.96, wspace=.05, - hspace=.01) +clustering_names = [ + 'MiniBatchKMeans', 'AffinityPropagation', 'MeanShift', + 'SpectralClustering', 'Ward', 'AgglomerativeClustering', + 'DBSCAN', 'Birch' + ] + +plt.figure(figsize=(len(clustering_names) * 2 + 3, 9.5)) +plt.subplots_adjust(left=.02, right=.98, bottom=.001, top=.96, wspace=.05, + hspace=.01) plot_num = 1 -for i_dataset, dataset in enumerate([noisy_circles, noisy_moons, blobs, - no_structure]): + +datasets = [noisy_circles, noisy_moons, blobs, no_structure] +for i_dataset, dataset in enumerate(datasets): X, y = dataset # normalize dataset for easier parameter selection X = StandardScaler().fit_transform(X) @@ -65,22 +71,29 @@ # make connectivity symmetric connectivity = 0.5 * (connectivity + connectivity.T) - # Compute distances - #distances = np.exp(-euclidean_distances(X)) - distances = euclidean_distances(X) - # create clustering estimators ms = cluster.MeanShift(bandwidth=bandwidth, bin_seeding=True) two_means = cluster.MiniBatchKMeans(n_clusters=2) - ward_five = cluster.Ward(n_clusters=2, connectivity=connectivity) - spectral = cluster.SpectralClustering(n_clusters=2, mode='arpack', - affinity="nearest_neighbors") + ward = cluster.AgglomerativeClustering(n_clusters=2, linkage='ward', + connectivity=connectivity) + spectral = cluster.SpectralClustering(n_clusters=2, + eigen_solver='arpack', + affinity="nearest_neighbors") dbscan = cluster.DBSCAN(eps=.2) affinity_propagation = cluster.AffinityPropagation(damping=.9, - preference=-200) + preference=-200) + + average_linkage = cluster.AgglomerativeClustering(linkage="average", + affinity="cityblock", n_clusters=2, + connectivity=connectivity) + + birch = cluster.Birch(n_clusters=2) + clustering_algorithms = [ + two_means, affinity_propagation, ms, spectral, ward, average_linkage, + dbscan, birch + ] - for algorithm in [two_means, affinity_propagation, ms, spectral, - ward_five, dbscan]: + for name, algorithm in zip(clustering_names, clustering_algorithms): # predict cluster memberships t0 = time.time() algorithm.fit(X) @@ -91,22 +104,22 @@ y_pred = algorithm.predict(X) # plot - pl.subplot(4, 6, plot_num) + plt.subplot(4, len(clustering_algorithms), plot_num) if i_dataset == 0: - pl.title(str(algorithm).split('(')[0], size=18) - pl.scatter(X[:, 0], X[:, 1], color=colors[y_pred].tolist(), s=10) + plt.title(name, size=18) + plt.scatter(X[:, 0], X[:, 1], color=colors[y_pred].tolist(), s=10) if hasattr(algorithm, 'cluster_centers_'): centers = algorithm.cluster_centers_ center_colors = colors[:len(centers)] - pl.scatter(centers[:, 0], centers[:, 1], s=100, c=center_colors) - pl.xlim(-2, 2) - pl.ylim(-2, 2) - pl.xticks(()) - pl.yticks(()) - pl.text(.99, .01, ('%.2fs' % (t1 - t0)).lstrip('0'), - transform=pl.gca().transAxes, size=15, - horizontalalignment='right') + plt.scatter(centers[:, 0], centers[:, 1], s=100, c=center_colors) + plt.xlim(-2, 2) + plt.ylim(-2, 2) + plt.xticks(()) + plt.yticks(()) + plt.text(.99, .01, ('%.2fs' % (t1 - t0)).lstrip('0'), + transform=plt.gca().transAxes, size=15, + horizontalalignment='right') plot_num += 1 -pl.show() +plt.show() diff --git a/examples/cluster/plot_cluster_iris.py b/examples/cluster/plot_cluster_iris.py index 060aa7d7e6758..b837d53887f15 100644 --- a/examples/cluster/plot_cluster_iris.py +++ b/examples/cluster/plot_cluster_iris.py @@ -16,15 +16,15 @@ and finally the ground truth. """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD +# Code source: Gaël Varoquaux +# Modified for documentation by Jaques Grobler +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D @@ -41,17 +41,16 @@ estimators = {'k_means_iris_3': KMeans(n_clusters=3), 'k_means_iris_8': KMeans(n_clusters=8), 'k_means_iris_bad_init': KMeans(n_clusters=3, n_init=1, - init='random'), - } + init='random')} fignum = 1 -for name, est in estimators.iteritems(): - fig = pl.figure(fignum, figsize=(4, 3)) - pl.clf() +for name, est in estimators.items(): + fig = plt.figure(fignum, figsize=(4, 3)) + plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) - pl.cla() + plt.cla() est.fit(X) labels = est.labels_ @@ -66,11 +65,11 @@ fignum = fignum + 1 # Plot the ground truth -fig = pl.figure(fignum, figsize=(4, 3)) -pl.clf() +fig = plt.figure(fignum, figsize=(4, 3)) +plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) -pl.cla() +plt.cla() for name, label in [('Setosa', 0), ('Versicolour', 1), @@ -79,8 +78,7 @@ X[y == label, 0].mean() + 1.5, X[y == label, 2].mean(), name, horizontalalignment='center', - bbox=dict(alpha=.5, edgecolor='w', facecolor='w'), - ) + bbox=dict(alpha=.5, edgecolor='w', facecolor='w')) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(np.float) ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=y) @@ -91,4 +89,4 @@ ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length') -pl.show() +plt.show() diff --git a/examples/cluster/plot_color_quantization.py b/examples/cluster/plot_color_quantization.py index 88cd93fef2841..428e05093eea8 100644 --- a/examples/cluster/plot_color_quantization.py +++ b/examples/cluster/plot_color_quantization.py @@ -22,13 +22,13 @@ # Olivier Grisel # Mathieu Blondel # -# License: BSD +# License: BSD 3 clause -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.cluster import KMeans -from sklearn.metrics import euclidean_distances +from sklearn.metrics import pairwise_distances_argmin from sklearn.datasets import load_sample_image from sklearn.utils import shuffle from time import time @@ -39,7 +39,7 @@ china = load_sample_image("china.jpg") # Convert to floats instead of the default 8 bits integer coding. Dividing by -# 255 is important so that pl.imshow behaves works well on foat data (need to +# 255 is important so that plt.imshow behaves works well on float data (need to # be in the range [0-1] china = np.array(china, dtype=np.float64) / 255 @@ -48,25 +48,26 @@ assert d == 3 image_array = np.reshape(china, (w * h, d)) -print "Fitting estimator on a small sub-sample of the data" +print("Fitting model on a small sub-sample of the data") t0 = time() image_array_sample = shuffle(image_array, random_state=0)[:1000] kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array_sample) -print "done in %0.3fs." % (time() - t0) +print("done in %0.3fs." % (time() - t0)) # Get labels for all points -print "Predicting color indices on the full image (k-means)" +print("Predicting color indices on the full image (k-means)") t0 = time() labels = kmeans.predict(image_array) -print "done in %0.3fs." % (time() - t0) +print("done in %0.3fs." % (time() - t0)) codebook_random = shuffle(image_array, random_state=0)[:n_colors + 1] -print "Predicting color indices on the full image (random)" +print("Predicting color indices on the full image (random)") t0 = time() -dist = euclidean_distances(codebook_random, image_array, squared=True) -labels_random = dist.argmin(axis=0) -print "done in %0.3fs." % (time() - t0) +labels_random = pairwise_distances_argmin(codebook_random, + image_array, + axis=0) +print("done in %0.3fs." % (time() - t0)) def recreate_image(codebook, labels, w, h): @@ -81,24 +82,24 @@ def recreate_image(codebook, labels, w, h): return image # Display all results, alongside original image -pl.figure(1) -pl.clf() -ax = pl.axes([0, 0, 1, 1]) -pl.axis('off') -pl.title('Original image (96,615 colors)') -pl.imshow(china) - -pl.figure(2) -pl.clf() -ax = pl.axes([0, 0, 1, 1]) -pl.axis('off') -pl.title('Quantized image (64 colors, K-Means)') -pl.imshow(recreate_image(kmeans.cluster_centers_, labels, w, h)) - -pl.figure(3) -pl.clf() -ax = pl.axes([0, 0, 1, 1]) -pl.axis('off') -pl.title('Quantized image (64 colors, Random)') -pl.imshow(recreate_image(codebook_random, labels_random, w, h)) -pl.show() +plt.figure(1) +plt.clf() +ax = plt.axes([0, 0, 1, 1]) +plt.axis('off') +plt.title('Original image (96,615 colors)') +plt.imshow(china) + +plt.figure(2) +plt.clf() +ax = plt.axes([0, 0, 1, 1]) +plt.axis('off') +plt.title('Quantized image (64 colors, K-Means)') +plt.imshow(recreate_image(kmeans.cluster_centers_, labels, w, h)) + +plt.figure(3) +plt.clf() +ax = plt.axes([0, 0, 1, 1]) +plt.axis('off') +plt.title('Quantized image (64 colors, Random)') +plt.imshow(recreate_image(codebook_random, labels_random, w, h)) +plt.show() diff --git a/examples/cluster/plot_dbscan.py b/examples/cluster/plot_dbscan.py index 8e7eaf27ae04f..46e315835a048 100644 --- a/examples/cluster/plot_dbscan.py +++ b/examples/cluster/plot_dbscan.py @@ -7,72 +7,66 @@ Finds core samples of high density and expands clusters from them. """ -print __doc__ +print(__doc__) import numpy as np -from scipy.spatial import distance + from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs +from sklearn.preprocessing import StandardScaler ############################################################################## # Generate sample data centers = [[1, 1], [-1, -1], [1, -1]] -X, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4) +X, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4, + random_state=0) -############################################################################## -# Compute similarities -D = distance.squareform(distance.pdist(X)) -S = 1 - (D / np.max(D)) +X = StandardScaler().fit_transform(X) ############################################################################## # Compute DBSCAN -db = DBSCAN(eps=0.95, min_samples=10).fit(S) -core_samples = db.core_sample_indices_ +db = DBSCAN(eps=0.3, min_samples=10).fit(X) +core_samples_mask = np.zeros_like(db.labels_, dtype=bool) +core_samples_mask[db.core_sample_indices_] = True labels = db.labels_ # Number of clusters in labels, ignoring noise if present. n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) -print 'Estimated number of clusters: %d' % n_clusters_ -print "Homogeneity: %0.3f" % metrics.homogeneity_score(labels_true, labels) -print "Completeness: %0.3f" % metrics.completeness_score(labels_true, labels) -print "V-measure: %0.3f" % metrics.v_measure_score(labels_true, labels) -print "Adjusted Rand Index: %0.3f" % \ - metrics.adjusted_rand_score(labels_true, labels) -print "Adjusted Mutual Information: %0.3f" % \ - metrics.adjusted_mutual_info_score(labels_true, labels) -print ("Silhouette Coefficient: %0.3f" % - metrics.silhouette_score(D, labels, metric='precomputed')) +print('Estimated number of clusters: %d' % n_clusters_) +print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels_true, labels)) +print("Completeness: %0.3f" % metrics.completeness_score(labels_true, labels)) +print("V-measure: %0.3f" % metrics.v_measure_score(labels_true, labels)) +print("Adjusted Rand Index: %0.3f" + % metrics.adjusted_rand_score(labels_true, labels)) +print("Adjusted Mutual Information: %0.3f" + % metrics.adjusted_mutual_info_score(labels_true, labels)) +print("Silhouette Coefficient: %0.3f" + % metrics.silhouette_score(X, labels)) ############################################################################## # Plot result -import pylab as pl -from itertools import cycle - -pl.close('all') -pl.figure(1) -pl.clf() +import matplotlib.pyplot as plt # Black removed and is used for noise instead. -colors = cycle('bgrcmybgrcmybgrcmybgrcmy') -for k, col in zip(set(labels), colors): +unique_labels = set(labels) +colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels))) +for k, col in zip(unique_labels, colors): if k == -1: # Black used for noise. col = 'k' - markersize = 6 - class_members = [index[0] for index in np.argwhere(labels == k)] - cluster_core_samples = [index for index in core_samples - if labels[index] == k] - for index in class_members: - x = X[index] - if index in core_samples and k != -1: - markersize = 14 - else: - markersize = 6 - pl.plot(x[0], x[1], 'o', markerfacecolor=col, - markeredgecolor='k', markersize=markersize) - -pl.title('Estimated number of clusters: %d' % n_clusters_) -pl.show() + + class_member_mask = (labels == k) + + xy = X[class_member_mask & core_samples_mask] + plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, + markeredgecolor='k', markersize=14) + + xy = X[class_member_mask & ~core_samples_mask] + plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, + markeredgecolor='k', markersize=6) + +plt.title('Estimated number of clusters: %d' % n_clusters_) +plt.show() diff --git a/examples/cluster/plot_dict_face_patches.py b/examples/cluster/plot_dict_face_patches.py new file mode 100644 index 0000000000000..7fb125ed735e9 --- /dev/null +++ b/examples/cluster/plot_dict_face_patches.py @@ -0,0 +1,84 @@ +""" +Online learning of a dictionary of parts of faces +================================================== + +This example uses a large dataset of faces to learn a set of 20 x 20 +images patches that constitute faces. + +From the programming standpoint, it is interesting because it shows how +to use the online API of the scikit-learn to process a very large +dataset by chunks. The way we proceed is that we load an image at a time +and extract randomly 50 patches from this image. Once we have accumulated +500 of these patches (using 10 images), we run the `partial_fit` method +of the online KMeans object, MiniBatchKMeans. + +The verbose setting on the MiniBatchKMeans enables us to see that some +clusters are reassigned during the successive calls to +partial-fit. This is because the number of patches that they represent +has become too low, and it is better to choose a random new +cluster. +""" +print(__doc__) + +import time + +import matplotlib.pyplot as plt +import numpy as np + + +from sklearn import datasets +from sklearn.cluster import MiniBatchKMeans +from sklearn.feature_extraction.image import extract_patches_2d + +faces = datasets.fetch_olivetti_faces() + +############################################################################### +# Learn the dictionary of images + +print('Learning the dictionary... ') +rng = np.random.RandomState(0) +kmeans = MiniBatchKMeans(n_clusters=81, random_state=rng, verbose=True) +patch_size = (20, 20) + +buffer = [] +index = 1 +t0 = time.time() + +# The online learning part: cycle over the whole dataset 6 times +index = 0 +for _ in range(6): + for img in faces.images: + data = extract_patches_2d(img, patch_size, max_patches=50, + random_state=rng) + data = np.reshape(data, (len(data), -1)) + buffer.append(data) + index += 1 + if index % 10 == 0: + data = np.concatenate(buffer, axis=0) + data -= np.mean(data, axis=0) + data /= np.std(data, axis=0) + kmeans.partial_fit(data) + buffer = [] + if index % 100 == 0: + print('Partial fit of %4i out of %i' + % (index, 6 * len(faces.images))) + +dt = time.time() - t0 +print('done in %.2fs.' % dt) + +############################################################################### +# Plot the results +plt.figure(figsize=(4.2, 4)) +for i, patch in enumerate(kmeans.cluster_centers_): + plt.subplot(9, 9, i + 1) + plt.imshow(patch.reshape(patch_size), cmap=plt.cm.gray, + interpolation='nearest') + plt.xticks(()) + plt.yticks(()) + + +plt.suptitle('Patches of faces\nTrain time %.1fs on %d patches' % + (dt, 8 * len(faces.images)), fontsize=16) +plt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23) + +plt.show() diff --git a/examples/cluster/plot_digits_agglomeration.py b/examples/cluster/plot_digits_agglomeration.py index 6cbce5d544042..31d8094e1cf2d 100644 --- a/examples/cluster/plot_digits_agglomeration.py +++ b/examples/cluster/plot_digits_agglomeration.py @@ -6,17 +6,17 @@ Feature agglomeration ========================================================= -These images how similiar features are merged together using +These images how similar features are merged together using feature agglomeration. """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD +# Code source: Gaël Varoquaux +# Modified for documentation by Jaques Grobler +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import datasets, cluster from sklearn.feature_extraction.image import grid_to_graph @@ -26,37 +26,36 @@ X = np.reshape(images, (len(images), -1)) connectivity = grid_to_graph(*images[0].shape) -agglo = cluster.WardAgglomeration(connectivity=connectivity, - n_clusters=32) +agglo = cluster.FeatureAgglomeration(connectivity=connectivity, + n_clusters=32) agglo.fit(X) X_reduced = agglo.transform(X) X_restored = agglo.inverse_transform(X_reduced) images_restored = np.reshape(X_restored, images.shape) -pl.figure(1, figsize=(4, 3.5)) -pl.clf() -pl.subplots_adjust(left=.01, right=.99, bottom=.01, top=.91) +plt.figure(1, figsize=(4, 3.5)) +plt.clf() +plt.subplots_adjust(left=.01, right=.99, bottom=.01, top=.91) for i in range(4): - pl.subplot(3, 4, i + 1) - pl.imshow(images[i], cmap=pl.cm.gray, - vmax=16, interpolation='nearest') - pl.xticks(()) - pl.yticks(()) + plt.subplot(3, 4, i + 1) + plt.imshow(images[i], cmap=plt.cm.gray, vmax=16, interpolation='nearest') + plt.xticks(()) + plt.yticks(()) if i == 1: - pl.title('Original data') - pl.subplot(3, 4, 4 + i + 1) - pl.imshow(images_restored[i], - cmap=pl.cm.gray, vmax=16, interpolation='nearest') + plt.title('Original data') + plt.subplot(3, 4, 4 + i + 1) + plt.imshow(images_restored[i], cmap=plt.cm.gray, vmax=16, + interpolation='nearest') if i == 1: - pl.title('Agglomerated data') - pl.xticks(()) - pl.yticks(()) - -pl.subplot(3, 4, 10) -pl.imshow(np.reshape(agglo.labels_, images[0].shape), - interpolation='nearest', cmap=pl.cm.spectral) -pl.xticks(()) -pl.yticks(()) -pl.title('Labels') -pl.show() + plt.title('Agglomerated data') + plt.xticks(()) + plt.yticks(()) + +plt.subplot(3, 4, 10) +plt.imshow(np.reshape(agglo.labels_, images[0].shape), + interpolation='nearest', cmap=plt.cm.spectral) +plt.xticks(()) +plt.yticks(()) +plt.title('Labels') +plt.show() diff --git a/examples/cluster/plot_digits_linkage.py b/examples/cluster/plot_digits_linkage.py new file mode 100644 index 0000000000000..f1fe1783c10e5 --- /dev/null +++ b/examples/cluster/plot_digits_linkage.py @@ -0,0 +1,91 @@ +""" +============================================================================= +Various Agglomerative Clustering on a 2D embedding of digits +============================================================================= + +An illustration of various linkage option for agglomerative clustering on +a 2D embedding of the digits dataset. + +The goal of this example is to show intuitively how the metrics behave, and +not to find good clusters for the digits. This is why the example works on a +2D embedding. + +What this example shows us is the behavior "rich getting richer" of +agglomerative clustering that tends to create uneven cluster sizes. +This behavior is especially pronounced for the average linkage strategy, +that ends up with a couple of singleton clusters. +""" + +# Authors: Gael Varoquaux +# License: BSD 3 clause (C) INRIA 2014 + +print(__doc__) +from time import time + +import numpy as np +from scipy import ndimage +from matplotlib import pyplot as plt + +from sklearn import manifold, datasets + +digits = datasets.load_digits(n_class=10) +X = digits.data +y = digits.target +n_samples, n_features = X.shape + +np.random.seed(0) + +def nudge_images(X, y): + # Having a larger dataset shows more clearly the behavior of the + # methods, but we multiply the size of the dataset only by 2, as the + # cost of the hierarchical clustering methods are strongly + # super-linear in n_samples + shift = lambda x: ndimage.shift(x.reshape((8, 8)), + .3 * np.random.normal(size=2), + mode='constant', + ).ravel() + X = np.concatenate([X, np.apply_along_axis(shift, 1, X)]) + Y = np.concatenate([y, y], axis=0) + return X, Y + + +X, y = nudge_images(X, y) + + +#---------------------------------------------------------------------- +# Visualize the clustering +def plot_clustering(X_red, X, labels, title=None): + x_min, x_max = np.min(X_red, axis=0), np.max(X_red, axis=0) + X_red = (X_red - x_min) / (x_max - x_min) + + plt.figure(figsize=(6, 4)) + for i in range(X_red.shape[0]): + plt.text(X_red[i, 0], X_red[i, 1], str(y[i]), + color=plt.cm.spectral(labels[i] / 10.), + fontdict={'weight': 'bold', 'size': 9}) + + plt.xticks([]) + plt.yticks([]) + if title is not None: + plt.title(title, size=17) + plt.axis('off') + plt.tight_layout() + +#---------------------------------------------------------------------- +# 2D embedding of the digits dataset +print("Computing embedding") +X_red = manifold.SpectralEmbedding(n_components=2).fit_transform(X) +print("Done.") + +from sklearn.cluster import AgglomerativeClustering + +for linkage in ('ward', 'average', 'complete'): + clustering = AgglomerativeClustering(linkage=linkage, n_clusters=10) + t0 = time() + clustering.fit(X_red) + print("%s : %.2fs" % (linkage, time() - t0)) + + plot_clustering(X_red, X, clustering.labels_, "%s linkage" % linkage) + + +plt.show() diff --git a/examples/cluster/plot_feature_agglomeration_vs_univariate_selection.py b/examples/cluster/plot_feature_agglomeration_vs_univariate_selection.py index 5a201fa1e2f42..a56a45e6d20dc 100644 --- a/examples/cluster/plot_feature_agglomeration_vs_univariate_selection.py +++ b/examples/cluster/plot_feature_agglomeration_vs_univariate_selection.py @@ -14,20 +14,20 @@ """ # Author: Alexandre Gramfort -# License: BSD Style. +# License: BSD 3 clause -print __doc__ +print(__doc__) import shutil import tempfile import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from scipy import linalg, ndimage from sklearn.feature_extraction.image import grid_to_graph from sklearn import feature_selection -from sklearn.cluster import WardAgglomeration +from sklearn.cluster import FeatureAgglomeration from sklearn.linear_model import BayesianRidge from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV @@ -66,9 +66,9 @@ mem = Memory(cachedir=cachedir, verbose=1) # Ward agglomeration followed by BayesianRidge -A = grid_to_graph(n_x=size, n_y=size) -ward = WardAgglomeration(n_clusters=10, connectivity=A, memory=mem, - n_components=1) +connectivity = grid_to_graph(n_x=size, n_y=size) +ward = FeatureAgglomeration(n_clusters=10, connectivity=connectivity, + memory=mem, n_components=1) clf = Pipeline([('ward', ward), ('ridge', ridge)]) # Select the optimal number of parcels with grid search clf = GridSearchCV(clf, {'ward__n_clusters': [10, 20, 30]}, n_jobs=1, cv=cv) @@ -90,19 +90,19 @@ ############################################################################### # Inverse the transformation to plot the results on an image -pl.close('all') -pl.figure(figsize=(7.3, 2.7)) -pl.subplot(1, 3, 1) -pl.imshow(coef, interpolation="nearest", cmap=pl.cm.RdBu_r) -pl.title("True weights") -pl.subplot(1, 3, 2) -pl.imshow(coef_selection_, interpolation="nearest", cmap=pl.cm.RdBu_r) -pl.title("Feature Selection") -pl.subplot(1, 3, 3) -pl.imshow(coef_agglomeration_, interpolation="nearest", cmap=pl.cm.RdBu_r) -pl.title("Feature Agglomeration") -pl.subplots_adjust(0.04, 0.0, 0.98, 0.94, 0.16, 0.26) -pl.show() +plt.close('all') +plt.figure(figsize=(7.3, 2.7)) +plt.subplot(1, 3, 1) +plt.imshow(coef, interpolation="nearest", cmap=plt.cm.RdBu_r) +plt.title("True weights") +plt.subplot(1, 3, 2) +plt.imshow(coef_selection_, interpolation="nearest", cmap=plt.cm.RdBu_r) +plt.title("Feature Selection") +plt.subplot(1, 3, 3) +plt.imshow(coef_agglomeration_, interpolation="nearest", cmap=plt.cm.RdBu_r) +plt.title("Feature Agglomeration") +plt.subplots_adjust(0.04, 0.0, 0.98, 0.94, 0.16, 0.26) +plt.show() # Attempt to remove the temporary cachedir, but don't worry if it fails shutil.rmtree(cachedir, ignore_errors=True) diff --git a/examples/cluster/plot_kmeans_digits.py b/examples/cluster/plot_kmeans_digits.py index 3b5db32379d07..cdd5073937efd 100644 --- a/examples/cluster/plot_kmeans_digits.py +++ b/examples/cluster/plot_kmeans_digits.py @@ -3,7 +3,7 @@ A demo of K-Means clustering on the handwritten digits data =========================================================== -In this example with compare the various initialization strategies for +In this example we compare the various initialization strategies for K-means in terms of runtime and quality of the results. As the ground truth is known here, we also apply different cluster @@ -25,11 +25,11 @@ =========== ======================================================== """ -print __doc__ +print(__doc__) from time import time import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import metrics from sklearn.cluster import KMeans @@ -48,29 +48,28 @@ sample_size = 300 -print "n_digits: %d, \t n_samples %d, \t n_features %d" % (n_digits, - n_samples, n_features) +print("n_digits: %d, \t n_samples %d, \t n_features %d" + % (n_digits, n_samples, n_features)) -print 79 * '_' -print ('% 9s' % 'init' - ' time inertia homo compl v-meas ARI AMI silhouette') +print(79 * '_') +print('% 9s' % 'init' + ' time inertia homo compl v-meas ARI AMI silhouette') def bench_k_means(estimator, name, data): t0 = time() estimator.fit(data) - print '% 9s %.2fs %i %.3f %.3f %.3f %.3f %.3f %.3f' % ( - name, (time() - t0), estimator.inertia_, - metrics.homogeneity_score(labels, estimator.labels_), - metrics.completeness_score(labels, estimator.labels_), - metrics.v_measure_score(labels, estimator.labels_), - metrics.adjusted_rand_score(labels, estimator.labels_), - metrics.adjusted_mutual_info_score(labels, estimator.labels_), - metrics.silhouette_score(data, estimator.labels_, - metric='euclidean', - sample_size=sample_size), - ) + print('% 9s %.2fs %i %.3f %.3f %.3f %.3f %.3f %.3f' + % (name, (time() - t0), estimator.inertia_, + metrics.homogeneity_score(labels, estimator.labels_), + metrics.completeness_score(labels, estimator.labels_), + metrics.v_measure_score(labels, estimator.labels_), + metrics.adjusted_rand_score(labels, estimator.labels_), + metrics.adjusted_mutual_info_score(labels, estimator.labels_), + metrics.silhouette_score(data, estimator.labels_, + metric='euclidean', + sample_size=sample_size))) bench_k_means(KMeans(init='k-means++', n_clusters=n_digits, n_init=10), name="k-means++", data=data) @@ -84,7 +83,7 @@ def bench_k_means(estimator, name, data): bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1), name="PCA-based", data=data) -print 79 * '_' +print(79 * '_') ############################################################################### # Visualize the results on PCA-reduced data @@ -96,7 +95,7 @@ def bench_k_means(estimator, name, data): # Step size of the mesh. Decrease to increase the quality of the VQ. h = .02 # point in the mesh [x_min, m_max]x[y_min, y_max]. -# Plot the decision boundary. For that, we will asign a color to each +# Plot the decision boundary. For that, we will assign a color to each x_min, x_max = reduced_data[:, 0].min() + 1, reduced_data[:, 0].max() - 1 y_min, y_max = reduced_data[:, 1].min() + 1, reduced_data[:, 1].max() - 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) @@ -106,23 +105,23 @@ def bench_k_means(estimator, name, data): # Put the result into a color plot Z = Z.reshape(xx.shape) -pl.figure(1) -pl.clf() -pl.imshow(Z, interpolation='nearest', - extent=(xx.min(), xx.max(), yy.min(), yy.max()), - cmap=pl.cm.Paired, - aspect='auto', origin='lower') - -pl.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2) +plt.figure(1) +plt.clf() +plt.imshow(Z, interpolation='nearest', + extent=(xx.min(), xx.max(), yy.min(), yy.max()), + cmap=plt.cm.Paired, + aspect='auto', origin='lower') + +plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2) # Plot the centroids as a white X centroids = kmeans.cluster_centers_ -pl.scatter(centroids[:, 0], centroids[:, 1], - marker='x', s=169, linewidths=3, - color='w', zorder=10) -pl.title('K-means clustering on the digits dataset (PCA-reduced data)\n' - 'Centroids are marked with white cross') -pl.xlim(x_min, x_max) -pl.ylim(y_min, y_max) -pl.xticks(()) -pl.yticks(()) -pl.show() +plt.scatter(centroids[:, 0], centroids[:, 1], + marker='x', s=169, linewidths=3, + color='w', zorder=10) +plt.title('K-means clustering on the digits dataset (PCA-reduced data)\n' + 'Centroids are marked with white cross') +plt.xlim(x_min, x_max) +plt.ylim(y_min, y_max) +plt.xticks(()) +plt.yticks(()) +plt.show() diff --git a/examples/cluster/plot_kmeans_silhouette_analysis.py b/examples/cluster/plot_kmeans_silhouette_analysis.py new file mode 100644 index 0000000000000..ed29ef7734529 --- /dev/null +++ b/examples/cluster/plot_kmeans_silhouette_analysis.py @@ -0,0 +1,141 @@ +""" +=============================================================================== +Selecting the number of clusters with silhouette analysis on KMeans clustering +=============================================================================== + +Silhouette analysis can be used to study the separation distance between the +resulting clusters. The silhouette plot displays a measure of how close each +point in one cluster is to points in the neighboring clusters and thus provides +a way to assess parameters like number of clusters visually. This measure has a +range of [-1, 1]. + +Silhoette coefficients (as these values are referred to as) near +1 indicate +that the sample is far away from the neighboring clusters. A value of 0 +indicates that the sample is on or very close to the decision boundary between +two neighboring clusters and negative values indicate that those samples might +have been assigned to the wrong cluster. + +In this example the silhouette analysis is used to choose an optimal value for +``n_clusters``. The silhouette plot shows that the ``n_clusters`` value of 3, 5 +and 6 are a bad pick for the given data due to the presence of clusters with +below average silhouette scores and also due to wide fluctuations in the size +of the silhouette plots. Silhouette analysis is more ambivalent in deciding +between 2 and 4. + +Also from the thickness of the silhouette plot the cluster size can be +visualized. The silhouette plot for cluster 0 when ``n_clusters`` is equal to +2, is bigger in size owing to the grouping of the 3 sub clusters into one big +cluster. However when the ``n_clusters`` is equal to 4, all the plots are more +or less of similar thickness and hence are of similar sizes as can be also +verified from the labelled scatter plot on the right. +""" + +from __future__ import print_function + +from sklearn.datasets import make_blobs +from sklearn.cluster import KMeans +from sklearn.metrics import silhouette_samples, silhouette_score + +import matplotlib.pyplot as plt +import matplotlib.cm as cm +import numpy as np + +print(__doc__) + +# Generating the sample data from make_blobs +# This particular setting has one distict cluster and 3 clusters placed close +# together. +X, y = make_blobs(n_samples=500, + n_features=2, + centers=4, + cluster_std=1, + center_box=(-10.0, 10.0), + shuffle=True, + random_state=1) # For reproducibility + +range_n_clusters = [2, 3, 4, 5, 6] + +for n_clusters in range_n_clusters: + # Create a subplot with 1 row and 2 columns + fig, (ax1, ax2) = plt.subplots(1, 2) + fig.set_size_inches(18, 7) + + # The 1st subplot is the silhouette plot + # The silhouette coefficient can range from -1, 1 but in this example all + # lie within [-0.1, 1] + ax1.set_xlim([-0.1, 1]) + # The (n_clusters+1)*10 is for inserting blank space between silhouette + # plots of individual clusters, to demarcate them clearly. + ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10]) + + # Initialize the clusterer with n_clusters value and a random generator + # seed of 10 for reproducibility. + clusterer = KMeans(n_clusters=n_clusters, random_state=10) + cluster_labels = clusterer.fit_predict(X) + + # The silhouette_score gives the average value for all the samples. + # This gives a perspective into the density and separation of the formed + # clusters + silhouette_avg = silhouette_score(X, cluster_labels) + print("For n_clusters =", n_clusters, + "The average silhouette_score is :", silhouette_avg) + + # Compute the silhouette scores for each sample + sample_silhouette_values = silhouette_samples(X, cluster_labels) + + y_lower = 10 + for i in range(n_clusters): + # Aggregate the silhouette scores for samples belonging to + # cluster i, and sort them + ith_cluster_silhouette_values = \ + sample_silhouette_values[cluster_labels == i] + + ith_cluster_silhouette_values.sort() + + size_cluster_i = ith_cluster_silhouette_values.shape[0] + y_upper = y_lower + size_cluster_i + + color = cm.spectral(float(i) / n_clusters) + ax1.fill_betweenx(np.arange(y_lower, y_upper), + 0, ith_cluster_silhouette_values, + facecolor=color, edgecolor=color, alpha=0.7) + + # Label the silhouette plots with their cluster numbers at the middle + ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i)) + + # Compute the new y_lower for next plot + y_lower = y_upper + 10 # 10 for the 0 samples + + ax1.set_title("The silhouette plot for the various clusters.") + ax1.set_xlabel("The silhouette coefficient values") + ax1.set_ylabel("Cluster label") + + # The vertical line for average silhoutte score of all the values + ax1.axvline(x=silhouette_avg, color="red", linestyle="--") + + ax1.set_yticks([]) # Clear the yaxis labels / ticks + ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1]) + + # 2nd Plot showing the actual clusters formed + colors = cm.spectral(cluster_labels.astype(float) / n_clusters) + ax2.scatter(X[:, 0], X[:, 1], marker='.', s=30, lw=0, alpha=0.7, + c=colors) + + # Labeling the clusters + centers = clusterer.cluster_centers_ + # Draw white circles at cluster centers + ax2.scatter(centers[:, 0], centers[:, 1], + marker='o', c="white", alpha=1, s=200) + + for i, c in enumerate(centers): + ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1, s=50) + + ax2.set_title("The visualization of the clustered data.") + ax2.set_xlabel("Feature space for the 1st feature") + ax2.set_ylabel("Feature space for the 2nd feature") + + plt.suptitle(("Silhouette analysis for KMeans clustering on sample data " + "with n_clusters = %d" % n_clusters), + fontsize=14, fontweight='bold') + + plt.show() diff --git a/examples/cluster/plot_kmeans_stability_low_dim_dense.py b/examples/cluster/plot_kmeans_stability_low_dim_dense.py index d6d9a8f9fdf52..b5d4326c5c713 100644 --- a/examples/cluster/plot_kmeans_stability_low_dim_dense.py +++ b/examples/cluster/plot_kmeans_stability_low_dim_dense.py @@ -15,19 +15,19 @@ The second plot demonstrate one single run of the ``MiniBatchKMeans`` estimator using a ``init="random"`` and ``n_init=1``. This run leads to -a bad convergence (local optimum) with estimated centers between stucked +a bad convergence (local optimum) with estimated centers stuck between ground truth clusters. -The dataset used for evaluation is a 2D grid of isotropic gaussian +The dataset used for evaluation is a 2D grid of isotropic Gaussian clusters widely spaced. """ -print __doc__ +print(__doc__) # Author: Olivier Grisel -# License: Simplified BSD +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt import matplotlib.cm as cm from sklearn.utils import shuffle @@ -57,7 +57,7 @@ def make_data(random_state, n_samples_per_center, grid_size, scale): centers = np.array([[i, j] for i in range(grid_size) for j in range(grid_size)]) - n_clusters_true, n_featues = centers.shape + n_clusters_true, n_features = centers.shape noise = random_state.normal( scale=scale, size=(n_samples_per_center, centers.shape[1])) @@ -69,7 +69,7 @@ def make_data(random_state, n_samples_per_center, grid_size, scale): # Part 1: Quantitative evaluation of various init methods -fig = pl.figure() +fig = plt.figure() plots = [] legends = [] @@ -81,23 +81,23 @@ def make_data(random_state, n_samples_per_center, grid_size, scale): ] for factory, init, params in cases: - print "Evaluation of %s with %s init" % (factory.__name__, init) + print("Evaluation of %s with %s init" % (factory.__name__, init)) inertia = np.empty((len(n_init_range), n_runs)) for run_id in range(n_runs): X, y = make_data(run_id, n_samples_per_center, grid_size, scale) for i, n_init in enumerate(n_init_range): km = factory(n_clusters=n_clusters, init=init, random_state=run_id, - n_init=n_init, **params).fit(X) + n_init=n_init, **params).fit(X) inertia[i, run_id] = km.inertia_ - p = pl.errorbar(n_init_range, inertia.mean(axis=1), inertia.std(axis=1)) + p = plt.errorbar(n_init_range, inertia.mean(axis=1), inertia.std(axis=1)) plots.append(p[0]) legends.append("%s with %s init" % (factory.__name__, init)) -pl.xlabel('n_init') -pl.ylabel('inertia') -pl.legend(plots, legends) -pl.title("Mean inertia for various k-means init across %d runs" % n_runs) +plt.xlabel('n_init') +plt.ylabel('inertia') +plt.legend(plots, legends) +plt.title("Mean inertia for various k-means init across %d runs" % n_runs) # Part 2: Qualitative visual inspection of the convergence @@ -105,15 +105,15 @@ def make_data(random_state, n_samples_per_center, grid_size, scale): km = MiniBatchKMeans(n_clusters=n_clusters, init='random', n_init=1, random_state=random_state).fit(X) -fig = pl.figure() +fig = plt.figure() for k in range(n_clusters): my_members = km.labels_ == k color = cm.spectral(float(k) / n_clusters, 1) - pl.plot(X[my_members, 0], X[my_members, 1], 'o', marker='.', c=color) + plt.plot(X[my_members, 0], X[my_members, 1], 'o', marker='.', c=color) cluster_center = km.cluster_centers_[k] - pl.plot(cluster_center[0], cluster_center[1], 'o', - markerfacecolor=color, markeredgecolor='k', markersize=6) - pl.title("Example cluster allocation with a single random init\n" - "with MiniBatchKMeans") + plt.plot(cluster_center[0], cluster_center[1], 'o', + markerfacecolor=color, markeredgecolor='k', markersize=6) + plt.title("Example cluster allocation with a single random init\n" + "with MiniBatchKMeans") -pl.show() +plt.show() diff --git a/examples/cluster/plot_lena_compress.py b/examples/cluster/plot_lena_compress.py index c2381388a530f..209d77265ef4d 100644 --- a/examples/cluster/plot_lena_compress.py +++ b/examples/cluster/plot_lena_compress.py @@ -5,21 +5,22 @@ ========================================================= Vector Quantization Example ========================================================= + The classic image processing example, Lena, an 8-bit grayscale bit-depth, 512 x 512 sized image, is used here to illustrate how `k`-means is used for vector quantization. """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD +# Code source: Gaël Varoquaux +# Modified for documentation by Jaques Grobler +# License: BSD 3 clause import numpy as np import scipy as sp -import pylab as pl +import matplotlib.pyplot as plt from sklearn import cluster @@ -46,12 +47,12 @@ vmax = lena.max() # original lena -pl.figure(1, figsize=(3, 2.2)) -pl.imshow(lena, cmap=pl.cm.gray, vmin=vmin, vmax=256) +plt.figure(1, figsize=(3, 2.2)) +plt.imshow(lena, cmap=plt.cm.gray, vmin=vmin, vmax=256) # compressed lena -pl.figure(2, figsize=(3, 2.2)) -pl.imshow(lena_compressed, cmap=pl.cm.gray, vmin=vmin, vmax=vmax) +plt.figure(2, figsize=(3, 2.2)) +plt.imshow(lena_compressed, cmap=plt.cm.gray, vmin=vmin, vmax=vmax) # equal bins lena regular_values = np.linspace(0, 256, n_clusters + 1) @@ -59,21 +60,21 @@ regular_values = .5 * (regular_values[1:] + regular_values[:-1]) # mean regular_lena = np.choose(regular_labels.ravel(), regular_values) regular_lena.shape = lena.shape -pl.figure(3, figsize=(3, 2.2)) -pl.imshow(regular_lena, cmap=pl.cm.gray, vmin=vmin, vmax=vmax) +plt.figure(3, figsize=(3, 2.2)) +plt.imshow(regular_lena, cmap=plt.cm.gray, vmin=vmin, vmax=vmax) # histogram -pl.figure(4, figsize=(3, 2.2)) -pl.clf() -pl.axes([.01, .01, .98, .98]) -pl.hist(X, bins=256, color='.5', edgecolor='.5') -pl.yticks(()) -pl.xticks(regular_values) +plt.figure(4, figsize=(3, 2.2)) +plt.clf() +plt.axes([.01, .01, .98, .98]) +plt.hist(X, bins=256, color='.5', edgecolor='.5') +plt.yticks(()) +plt.xticks(regular_values) values = np.sort(values) for center_1, center_2 in zip(values[:-1], values[1:]): - pl.axvline(.5 * (center_1 + center_2), color='b') + plt.axvline(.5 * (center_1 + center_2), color='b') for center_1, center_2 in zip(regular_values[:-1], regular_values[1:]): - pl.axvline(.5 * (center_1 + center_2), color='b', linestyle='--') + plt.axvline(.5 * (center_1 + center_2), color='b', linestyle='--') -pl.show() +plt.show() diff --git a/examples/cluster/plot_lena_segmentation.py b/examples/cluster/plot_lena_segmentation.py index de9666cc29afd..0a7ffe09e9ad6 100644 --- a/examples/cluster/plot_lena_segmentation.py +++ b/examples/cluster/plot_lena_segmentation.py @@ -5,19 +5,28 @@ This example uses :ref:`spectral_clustering` on a graph created from voxel-to-voxel difference on an image to break this image into multiple -partly-homogenous regions. +partly-homogeneous regions. This procedure (spectral clustering on an image) is an efficient approximate solution for finding normalized graph cuts. + +There are two options to assign labels: + +* with 'kmeans' spectral clustering will cluster samples in the embedding space + using a kmeans algorithm +* whereas 'discrete' will iteratively search for the closest partition + space to the embedding space. """ -print __doc__ +print(__doc__) + +# Author: Gael Varoquaux , Brian Cheung +# License: BSD 3 clause -# Author: Gael Varoquaux -# License: BSD +import time import numpy as np import scipy as sp -import pylab as pl +import matplotlib.pyplot as plt from sklearn.feature_extraction import image from sklearn.cluster import spectral_clustering @@ -41,16 +50,25 @@ # Apply spectral clustering (this step goes much faster if you have pyamg # installed) N_REGIONS = 11 -labels = spectral_clustering(graph, n_clusters=N_REGIONS) -labels = labels.reshape(lena.shape) ############################################################################### # Visualize the resulting regions -pl.figure(figsize=(5, 5)) -pl.imshow(lena, cmap=pl.cm.gray) -for l in range(N_REGIONS): - pl.contour(labels == l, contours=1, - colors=[pl.cm.spectral(l / float(N_REGIONS)), ]) -pl.xticks(()) -pl.yticks(()) -pl.show() + +for assign_labels in ('kmeans', 'discretize'): + t0 = time.time() + labels = spectral_clustering(graph, n_clusters=N_REGIONS, + assign_labels=assign_labels, + random_state=1) + t1 = time.time() + labels = labels.reshape(lena.shape) + + plt.figure(figsize=(5, 5)) + plt.imshow(lena, cmap=plt.cm.gray) + for l in range(N_REGIONS): + plt.contour(labels == l, contours=1, + colors=[plt.cm.spectral(l / float(N_REGIONS)), ]) + plt.xticks(()) + plt.yticks(()) + plt.title('Spectral clustering: %s, %.2fs' % (assign_labels, (t1 - t0))) + +plt.show() diff --git a/examples/cluster/plot_lena_ward_segmentation.py b/examples/cluster/plot_lena_ward_segmentation.py index bbe81a2492e28..2d31325588895 100644 --- a/examples/cluster/plot_lena_ward_segmentation.py +++ b/examples/cluster/plot_lena_ward_segmentation.py @@ -10,16 +10,16 @@ # Author : Vincent Michel, 2010 # Alexandre Gramfort, 2011 -# License: BSD Style. +# License: BSD 3 clause -print __doc__ +print(__doc__) import time as time import numpy as np import scipy as sp -import pylab as pl +import matplotlib.pyplot as plt from sklearn.feature_extraction.image import grid_to_graph -from sklearn.cluster import Ward +from sklearn.cluster import AgglomerativeClustering ############################################################################### # Generate data @@ -34,22 +34,23 @@ ############################################################################### # Compute clustering -print "Compute structured hierarchical clustering..." +print("Compute structured hierarchical clustering...") st = time.time() n_clusters = 15 # number of regions -ward = Ward(n_clusters=n_clusters, connectivity=connectivity).fit(X) +ward = AgglomerativeClustering(n_clusters=n_clusters, + linkage='ward', connectivity=connectivity).fit(X) label = np.reshape(ward.labels_, lena.shape) -print "Elaspsed time: ", time.time() - st -print "Number of pixels: ", label.size -print "Number of clusters: ", np.unique(label).size +print("Elapsed time: ", time.time() - st) +print("Number of pixels: ", label.size) +print("Number of clusters: ", np.unique(label).size) ############################################################################### # Plot the results on an image -pl.figure(figsize=(5, 5)) -pl.imshow(lena, cmap=pl.cm.gray) +plt.figure(figsize=(5, 5)) +plt.imshow(lena, cmap=plt.cm.gray) for l in range(n_clusters): - pl.contour(label == l, contours=1, - colors=[pl.cm.spectral(l / float(n_clusters)), ]) -pl.xticks(()) -pl.yticks(()) -pl.show() + plt.contour(label == l, contours=1, + colors=[plt.cm.spectral(l / float(n_clusters)), ]) +plt.xticks(()) +plt.yticks(()) +plt.show() diff --git a/examples/cluster/plot_mean_shift.py b/examples/cluster/plot_mean_shift.py index b310378a940d3..775cd98e59527 100644 --- a/examples/cluster/plot_mean_shift.py +++ b/examples/cluster/plot_mean_shift.py @@ -10,7 +10,7 @@ Machine Intelligence. 2002. pp. 603-619. """ -print __doc__ +print(__doc__) import numpy as np from sklearn.cluster import MeanShift, estimate_bandwidth @@ -35,22 +35,22 @@ labels_unique = np.unique(labels) n_clusters_ = len(labels_unique) -print "number of estimated clusters : %d" % n_clusters_ +print("number of estimated clusters : %d" % n_clusters_) ############################################################################### # Plot result -import pylab as pl +import matplotlib.pyplot as plt from itertools import cycle -pl.figure(1) -pl.clf() +plt.figure(1) +plt.clf() colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') for k, col in zip(range(n_clusters_), colors): my_members = labels == k cluster_center = cluster_centers[k] - pl.plot(X[my_members, 0], X[my_members, 1], col + '.') - pl.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, - markeredgecolor='k', markersize=14) -pl.title('Estimated number of clusters: %d' % n_clusters_) -pl.show() + plt.plot(X[my_members, 0], X[my_members, 1], col + '.') + plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, + markeredgecolor='k', markersize=14) +plt.title('Estimated number of clusters: %d' % n_clusters_) +plt.show() diff --git a/examples/cluster/plot_mini_batch_kmeans.py b/examples/cluster/plot_mini_batch_kmeans.py index 3fb509efc0623..ed4afcf995794 100644 --- a/examples/cluster/plot_mini_batch_kmeans.py +++ b/examples/cluster/plot_mini_batch_kmeans.py @@ -1,7 +1,7 @@ """ -===================================================== -A demo of the K Means clustering algorithm -===================================================== +==================================================================== +Comparison of the K-Means and MiniBatchKMeans clustering algorithms +==================================================================== We want to compare the performance of the MiniBatchKMeans and KMeans: the MiniBatchKMeans is faster, but gives slightly different results (see @@ -12,15 +12,15 @@ We will also plot the points that are labelled differently between the two algorithms. """ -print __doc__ +print(__doc__) import time import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.cluster import MiniBatchKMeans, KMeans -from sklearn.metrics.pairwise import euclidean_distances +from sklearn.metrics.pairwise import pairwise_distances_argmin from sklearn.datasets.samples_generator import make_blobs ############################################################################## @@ -58,7 +58,7 @@ ############################################################################## # Plot result -fig = pl.figure(figsize=(8, 3)) +fig = plt.figure(figsize=(8, 3)) fig.subplots_adjust(left=0.02, right=0.98, bottom=0.05, top=0.9) colors = ['#4EACC5', '#FF9C34', '#4E9A06'] @@ -66,10 +66,8 @@ # MiniBatchKMeans and the KMeans algorithm. Let's pair the cluster centers per # closest one. -distance = euclidean_distances(k_means_cluster_centers, - mbk_means_cluster_centers, - squared=True) -order = distance.argmin(axis=1) +order = pairwise_distances_argmin(k_means_cluster_centers, + mbk_means_cluster_centers) # KMeans ax = fig.add_subplot(1, 3, 1) @@ -79,11 +77,11 @@ ax.plot(X[my_members, 0], X[my_members, 1], 'w', markerfacecolor=col, marker='.') ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, - markeredgecolor='k', markersize=6) + markeredgecolor='k', markersize=6) ax.set_title('KMeans') ax.set_xticks(()) ax.set_yticks(()) -pl.text(-3.5, 1.8, 'train time: %.2fs\ninertia: %f' % ( +plt.text(-3.5, 1.8, 'train time: %.2fs\ninertia: %f' % ( t_batch, k_means.inertia_)) # MiniBatchKMeans @@ -94,12 +92,12 @@ ax.plot(X[my_members, 0], X[my_members, 1], 'w', markerfacecolor=col, marker='.') ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, - markeredgecolor='k', markersize=6) + markeredgecolor='k', markersize=6) ax.set_title('MiniBatchKMeans') ax.set_xticks(()) ax.set_yticks(()) -pl.text(-3.5, 1.8, 'train time: %.2fs\ninertia: %f' % - (t_mini_batch, mbk.inertia_)) +plt.text(-3.5, 1.8, 'train time: %.2fs\ninertia: %f' % + (t_mini_batch, mbk.inertia_)) # Initialise the different array to all False different = (mbk_means_labels == 4) @@ -117,4 +115,4 @@ ax.set_xticks(()) ax.set_yticks(()) -pl.show() +plt.show() diff --git a/examples/cluster/plot_segmentation_toy.py b/examples/cluster/plot_segmentation_toy.py index ce0acccd8e715..fec049d183656 100644 --- a/examples/cluster/plot_segmentation_toy.py +++ b/examples/cluster/plot_segmentation_toy.py @@ -4,9 +4,9 @@ =========================================== In this example, an image with connected circles is generated and -:ref:`spectral_clustering` is used to separate the circles. +spectral clustering is used to separate the circles. -In these settings, the spectral clustering approach solves the problem +In these settings, the :ref:`spectral_clustering` approach solves the problem know as 'normalized graph cuts': the image is seen as a graph of connected voxels, and the spectral clustering algorithm amounts to choosing graph cuts defining regions while minimizing the ratio of the @@ -24,14 +24,14 @@ outline of the objects. In this example, we are interested in separating the objects one from the other, and not from the background. """ -print __doc__ +print(__doc__) # Authors: Emmanuelle Gouillart # Gael Varoquaux -# License: BSD +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.feature_extraction import image from sklearn.cluster import spectral_clustering @@ -65,17 +65,17 @@ graph = image.img_to_graph(img, mask=mask) # Take a decreasing function of the gradient: we take it weakly -# dependant from the gradient the segmentation is close to a voronoi +# dependent from the gradient the segmentation is close to a voronoi graph.data = np.exp(-graph.data / graph.data.std()) # Force the solver to be arpack, since amg is numerically # unstable on this example -labels = spectral_clustering(graph, n_clusters=4, mode='arpack') +labels = spectral_clustering(graph, n_clusters=4, eigen_solver='arpack') label_im = -np.ones(mask.shape) label_im[mask] = labels -pl.matshow(img) -pl.matshow(label_im) +plt.matshow(img) +plt.matshow(label_im) ############################################################################### # 2 circles @@ -88,11 +88,11 @@ graph = image.img_to_graph(img, mask=mask) graph.data = np.exp(-graph.data / graph.data.std()) -labels = spectral_clustering(graph, n_clusters=2, mode='arpack') +labels = spectral_clustering(graph, n_clusters=2, eigen_solver='arpack') label_im = -np.ones(mask.shape) label_im[mask] = labels -pl.matshow(img) -pl.matshow(label_im) +plt.matshow(img) +plt.matshow(label_im) -pl.show() +plt.show() diff --git a/examples/cluster/plot_ward_structured_vs_unstructured.py b/examples/cluster/plot_ward_structured_vs_unstructured.py index 95c37277b8c7c..e2be1b0953948 100644 --- a/examples/cluster/plot_ward_structured_vs_unstructured.py +++ b/examples/cluster/plot_ward_structured_vs_unstructured.py @@ -4,12 +4,14 @@ =========================================================== Example builds a swiss roll dataset and runs -:ref:`hierarchical_clustering` on their position. +hierarchical clustering on their position. -In a first step, the hierarchical clustering without connectivity -constraints on structure, solely based on distance, whereas in a second -step clustering restricted to the k-Nearest Neighbors graph: it's a -hierarchical clustering with structure prior. +For more information, see :ref:`hierarchical_clustering`. + +In a first step, the hierarchical clustering is performed without connectivity +constraints on the structure and is solely based on distance, whereas in +a second step the clustering is restricted to the k-Nearest Neighbors +graph: it's a hierarchical clustering with structure prior. Some of the clusters learned without connectivity constraints do not respect the structure of the swiss roll and extend across different folds of @@ -20,20 +22,20 @@ # Authors : Vincent Michel, 2010 # Alexandre Gramfort, 2010 # Gael Varoquaux, 2010 -# License: BSD +# License: BSD 3 clause -print __doc__ +print(__doc__) import time as time import numpy as np -import pylab as pl +import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 -from sklearn.cluster import Ward +from sklearn.cluster import AgglomerativeClustering from sklearn.datasets.samples_generator import make_swiss_roll ############################################################################### # Generate data (swiss roll dataset) -n_samples = 1000 +n_samples = 1500 noise = 0.05 X, _ = make_swiss_roll(n_samples, noise) # Make it thinner @@ -41,22 +43,23 @@ ############################################################################### # Compute clustering -print "Compute unstructured hierarchical clustering..." +print("Compute unstructured hierarchical clustering...") st = time.time() -ward = Ward(n_clusters=6).fit(X) +ward = AgglomerativeClustering(n_clusters=6, linkage='ward').fit(X) +elapsed_time = time.time() - st label = ward.labels_ -print "Elapsed time: ", time.time() - st -print "Number of points: ", label.size +print("Elapsed time: %.2fs" % elapsed_time) +print("Number of points: %i" % label.size) ############################################################################### # Plot result -fig = pl.figure() +fig = plt.figure() ax = p3.Axes3D(fig) ax.view_init(7, -80) for l in np.unique(label): ax.plot3D(X[label == l, 0], X[label == l, 1], X[label == l, 2], - 'o', color=pl.cm.jet(np.float(l) / np.max(label + 1))) -pl.title('Without connectivity constraints') + 'o', color=plt.cm.jet(np.float(l) / np.max(label + 1))) +plt.title('Without connectivity constraints (time %.2fs)' % elapsed_time) ############################################################################### @@ -66,21 +69,23 @@ ############################################################################### # Compute clustering -print "Compute structured hierarchical clustering..." +print("Compute structured hierarchical clustering...") st = time.time() -ward = Ward(n_clusters=6, connectivity=connectivity).fit(X) +ward = AgglomerativeClustering(n_clusters=6, connectivity=connectivity, + linkage='ward').fit(X) +elapsed_time = time.time() - st label = ward.labels_ -print "Elapsed time: ", time.time() - st -print "Number of points: ", label.size +print("Elapsed time: %.2fs" % elapsed_time) +print("Number of points: %i" % label.size) ############################################################################### # Plot result -fig = pl.figure() +fig = plt.figure() ax = p3.Axes3D(fig) ax.view_init(7, -80) for l in np.unique(label): ax.plot3D(X[label == l, 0], X[label == l, 1], X[label == l, 2], - 'o', color=pl.cm.jet(float(l) / np.max(label + 1))) -pl.title('With connectivity constraints') + 'o', color=plt.cm.jet(float(l) / np.max(label + 1))) +plt.title('With connectivity constraints (time %.2fs)' % elapsed_time) -pl.show() +plt.show() diff --git a/examples/covariance/README.txt b/examples/covariance/README.txt index 8fe1c89787ba5..283f01590b7f1 100644 --- a/examples/covariance/README.txt +++ b/examples/covariance/README.txt @@ -3,4 +3,4 @@ Covariance estimation --------------------- -Examples concerning the :mod:`sklearn.covariance` package. +Examples concerning the :mod:`sklearn.covariance` module. diff --git a/examples/covariance/plot_covariance_estimation.py b/examples/covariance/plot_covariance_estimation.py index f6d334452eaff..85e26705b03e9 100644 --- a/examples/covariance/plot_covariance_estimation.py +++ b/examples/covariance/plot_covariance_estimation.py @@ -1,36 +1,61 @@ """ -=========================================== -Ledoit-Wolf vs Covariance simple estimation -=========================================== - -The usual covariance maximum likelihood estimate can be regularized -using shrinkage. Ledoit and Wolf proposed a close formula to compute -the asymptotical optimal shrinkage parameter (minimizing a MSE -criterion), yielding the Ledoit-Wolf covariance estimate. - -Chen et al. proposed an improvement of the Ledoit-Wolf shrinkage -parameter, the OAS coefficient, whose convergence is significantly -better under the assumption that the data are gaussian. - -In this example, we compute the likelihood of unseen data for -different values of the shrinkage parameter, highlighting the LW and -OAS estimates. The Ledoit-Wolf estimate stays close to the likelihood -criterion optimal value, which is an artifact of the method since it -is asymptotic and we are working with a small number of observations. -The OAS estimate deviates from the likelihood criterion optimal value -but better approximate the MSE optimal value, especially for a small -number a observations. +======================================================================= +Shrinkage covariance estimation: LedoitWolf vs OAS and max-likelihood +======================================================================= + +When working with covariance estimation, the usual approach is to use +a maximum likelihood estimator, such as the +:class:`sklearn.covariance.EmpiricalCovariance`. It is unbiased, i.e. it +converges to the true (population) covariance when given many +observations. However, it can also be beneficial to regularize it, in +order to reduce its variance; this, in turn, introduces some bias. This +example illustrates the simple regularization used in +:ref:`shrunk_covariance` estimators. In particular, it focuses on how to +set the amount of regularization, i.e. how to choose the bias-variance +trade-off. + +Here we compare 3 approaches: + +* Setting the parameter by cross-validating the likelihood on three folds + according to a grid of potential shrinkage parameters. + +* A close formula proposed by Ledoit and Wolf to compute + the asymptotically optimal regularization parameter (minimizing a MSE + criterion), yielding the :class:`sklearn.covariance.LedoitWolf` + covariance estimate. + +* An improvement of the Ledoit-Wolf shrinkage, the + :class:`sklearn.covariance.OAS`, proposed by Chen et al. Its + convergence is significantly better under the assumption that the data + are Gaussian, in particular for small samples. + +To quantify estimation error, we plot the likelihood of unseen data for +different values of the shrinkage parameter. We also show the choices by +cross-validation, or with the LedoitWolf and OAS estimates. + +Note that the maximum likelihood estimate corresponds to no shrinkage, +and thus performs poorly. The Ledoit-Wolf estimate performs really well, +as it is close to the optimal and is computational not costly. In this +example, the OAS estimate is a bit further away. Interestingly, both +approaches outperform cross-validation, which is significantly most +computationally costly. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from scipy import linalg +from sklearn.covariance import LedoitWolf, OAS, ShrunkCovariance, \ + log_likelihood, empirical_covariance +from sklearn.grid_search import GridSearchCV + + ############################################################################### # Generate sample data -n_features, n_samples = 30, 20 +n_features, n_samples = 40, 20 +np.random.seed(42) base_X_train = np.random.normal(size=(n_samples, n_features)) base_X_test = np.random.normal(size=(n_samples, n_features)) @@ -40,10 +65,26 @@ X_test = np.dot(base_X_test, coloring_matrix) ############################################################################### -# Compute Ledoit-Wolf and Covariances on a grid of shrinkages +# Compute the likelihood on test data -from sklearn.covariance import LedoitWolf, OAS, ShrunkCovariance, \ - log_likelihood, empirical_covariance +# spanning a range of possible shrinkage coefficient values +shrinkages = np.logspace(-2, 0, 30) +negative_logliks = [-ShrunkCovariance(shrinkage=s).fit(X_train).score(X_test) + for s in shrinkages] + +# under the ground-truth model, which we would not have access to in real +# settings +real_cov = np.dot(coloring_matrix.T, coloring_matrix) +emp_cov = empirical_covariance(X_train) +loglik_real = -log_likelihood(emp_cov, linalg.inv(real_cov)) + +############################################################################### +# Compare different approaches to setting the parameter + +# GridSearch for an optimal shrinkage coefficient +tuned_parameters = [{'shrinkage': shrinkages}] +cv = GridSearchCV(ShrunkCovariance(), tuned_parameters) +cv.fit(X_train) # Ledoit-Wolf optimal shrinkage coefficient estimate lw = LedoitWolf() @@ -53,45 +94,38 @@ oa = OAS() loglik_oa = oa.fit(X_train).score(X_test) -# spanning a range of possible shrinkage coefficient values -shrinkages = np.logspace(-3, 0, 30) -negative_logliks = [-ShrunkCovariance(shrinkage=s).fit(X_train).score(X_test) - for s in shrinkages] - -# getting the likelihood under the real model -real_cov = np.dot(coloring_matrix.T, coloring_matrix) -emp_cov = empirical_covariance(X_train) -loglik_real = -log_likelihood(emp_cov, linalg.inv(real_cov)) - ############################################################################### # Plot results -pl.figure() -pl.title("Regularized covariance: likelihood and shrinkage coefficient") -pl.xlabel('Shrinkage') -pl.ylabel('Negative log-likelihood') +fig = plt.figure() +plt.title("Regularized covariance: likelihood and shrinkage coefficient") +plt.xlabel('Regularizaton parameter: shrinkage coefficient') +plt.ylabel('Error: negative log-likelihood on test data') # range shrinkage curve -pl.loglog(shrinkages, negative_logliks) +plt.loglog(shrinkages, negative_logliks, label="Negative log-likelihood") -# real likelihood reference -# BUG: hlines(..., linestyle='--') breaks on some older versions of matplotlib -#pl.hlines(loglik_real, pl.xlim()[0], pl.xlim()[1], color='red', -# label="real covariance likelihood", linestyle='--') -pl.plot(pl.xlim(), 2 * [loglik_real], '--r', - label="real covariance likelihood") +plt.plot(plt.xlim(), 2 * [loglik_real], '--r', + label="Real covariance likelihood") # adjust view lik_max = np.amax(negative_logliks) lik_min = np.amin(negative_logliks) -ylim0 = lik_min - 5. * np.log((pl.ylim()[1] - pl.ylim()[0])) -ylim1 = lik_max + 10. * np.log(lik_max - lik_min) +ymin = lik_min - 6. * np.log((plt.ylim()[1] - plt.ylim()[0])) +ymax = lik_max + 10. * np.log(lik_max - lik_min) +xmin = shrinkages[0] +xmax = shrinkages[-1] # LW likelihood -pl.vlines(lw.shrinkage_, ylim0, -loglik_lw, color='g', - linewidth=3, label='Ledoit-Wolf estimate') +plt.vlines(lw.shrinkage_, ymin, -loglik_lw, color='magenta', + linewidth=3, label='Ledoit-Wolf estimate') # OAS likelihood -pl.vlines(oa.shrinkage_, ylim0, -loglik_oa, color='orange', - linewidth=3, label='OAS estimate') - -pl.ylim(ylim0, ylim1) -pl.xlim(shrinkages[0], shrinkages[-1]) -pl.legend() -pl.show() +plt.vlines(oa.shrinkage_, ymin, -loglik_oa, color='purple', + linewidth=3, label='OAS estimate') +# best CV estimator likelihood +plt.vlines(cv.best_estimator_.shrinkage, ymin, + -cv.best_estimator_.score(X_test), color='cyan', + linewidth=3, label='Cross-validation best estimate') + +plt.ylim(ymin, ymax) +plt.xlim(xmin, xmax) +plt.legend() + +plt.show() diff --git a/examples/covariance/plot_lw_vs_oas.py b/examples/covariance/plot_lw_vs_oas.py index c22aceea4b2c3..59b6536e83d89 100644 --- a/examples/covariance/plot_lw_vs_oas.py +++ b/examples/covariance/plot_lw_vs_oas.py @@ -5,25 +5,25 @@ The usual covariance maximum likelihood estimate can be regularized using shrinkage. Ledoit and Wolf proposed a close formula to compute -the asymptotical optimal shrinkage parameter (minimizing a MSE +the asymptotically optimal shrinkage parameter (minimizing a MSE criterion), yielding the Ledoit-Wolf covariance estimate. Chen et al. proposed an improvement of the Ledoit-Wolf shrinkage parameter, the OAS coefficient, whose convergence is significantly -better under the assumption that the data are gaussian. +better under the assumption that the data are Gaussian. This example, inspired from Chen's publication [1], shows a comparison -of the estimated MSE of the LW and OAS methods, using gaussian +of the estimated MSE of the LW and OAS methods, using Gaussian distributed data. [1] "Shrinkage Algorithms for MMSE Covariance Estimation" Chen et al., IEEE Trans. on Sign. Proc., Volume 58, Issue 10, October 2010. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from scipy.linalg import toeplitz, cholesky from sklearn.covariance import LedoitWolf, OAS @@ -58,26 +58,26 @@ oa_shrinkage[i, j] = oa.shrinkage_ # plot MSE -pl.subplot(2, 1, 1) -pl.errorbar(n_samples_range, lw_mse.mean(1), yerr=lw_mse.std(1), - label='Ledoit-Wolf', color='g') -pl.errorbar(n_samples_range, oa_mse.mean(1), yerr=oa_mse.std(1), - label='OAS', color='r') -pl.ylabel("Squared error") -pl.legend(loc="upper right") -pl.title("Comparison of covariance estimators") -pl.xlim(5, 31) +plt.subplot(2, 1, 1) +plt.errorbar(n_samples_range, lw_mse.mean(1), yerr=lw_mse.std(1), + label='Ledoit-Wolf', color='g') +plt.errorbar(n_samples_range, oa_mse.mean(1), yerr=oa_mse.std(1), + label='OAS', color='r') +plt.ylabel("Squared error") +plt.legend(loc="upper right") +plt.title("Comparison of covariance estimators") +plt.xlim(5, 31) # plot shrinkage coefficient -pl.subplot(2, 1, 2) -pl.errorbar(n_samples_range, lw_shrinkage.mean(1), yerr=lw_shrinkage.std(1), - label='Ledoit-Wolf', color='g') -pl.errorbar(n_samples_range, oa_shrinkage.mean(1), yerr=oa_shrinkage.std(1), - label='OAS', color='r') -pl.xlabel("n_samples") -pl.ylabel("Shrinkage") -pl.legend(loc="lower right") -pl.ylim(pl.ylim()[0], 1. + (pl.ylim()[1] - pl.ylim()[0]) / 10.) -pl.xlim(5, 31) +plt.subplot(2, 1, 2) +plt.errorbar(n_samples_range, lw_shrinkage.mean(1), yerr=lw_shrinkage.std(1), + label='Ledoit-Wolf', color='g') +plt.errorbar(n_samples_range, oa_shrinkage.mean(1), yerr=oa_shrinkage.std(1), + label='OAS', color='r') +plt.xlabel("n_samples") +plt.ylabel("Shrinkage") +plt.legend(loc="lower right") +plt.ylim(plt.ylim()[0], 1. + (plt.ylim()[1] - plt.ylim()[0]) / 10.) +plt.xlim(5, 31) -pl.show() +plt.show() diff --git a/examples/covariance/plot_mahalanobis_distances.py b/examples/covariance/plot_mahalanobis_distances.py index 00e62570fa60b..53329aa71b80f 100644 --- a/examples/covariance/plot_mahalanobis_distances.py +++ b/examples/covariance/plot_mahalanobis_distances.py @@ -1,29 +1,33 @@ -""" +r""" ================================================================ Robust covariance estimation and Mahalanobis distances relevance ================================================================ -For Gaussian ditributed data, the distance of an observation +An example to show covariance estimation with the Mahalanobis +distances on Gaussian distributed data. + +For Gaussian distributed data, the distance of an observation :math:`x_i` to the mode of the distribution can be computed using its Mahalanobis distance: :math:`d_{(\mu,\Sigma)}(x_i)^2 = (x_i - \mu)'\Sigma^{-1}(x_i - \mu)` where :math:`\mu` and :math:`\Sigma` are -the location and the covariance of the underlying gaussian +the location and the covariance of the underlying Gaussian distribution. In practice, :math:`\mu` and :math:`\Sigma` are replaced by some estimates. The usual covariance maximum likelihood estimate is very sensitive to the presence of outliers in the data set and therefor, the corresponding Mahalanobis distances are. One would better have to -use a robust estimator of covariance to garanty that the estimation is -resistant to "errorneous" observations in the data set and that the +use a robust estimator of covariance to guarantee that the estimation is +resistant to "erroneous" observations in the data set and that the associated Mahalanobis distances accurately reflect the true organisation of the observations. The Minimum Covariance Determinant estimator is a robust, high-breakdown point (i.e. it can be used to estimate the covariance matrix of highly contaminated datasets, up to -:math:`\frac{n_samples-n_features-1}{2}` outliers) estimator of -covariance. The idea is to find :math:`\frac{n_samples+n_features+1}{2}` +:math:`\frac{n_\text{samples}-n_\text{features}-1}{2}` outliers) +estimator of covariance. The idea is to find +:math:`\frac{n_\text{samples}+n_\text{features}+1}{2}` observations whose empirical covariance has the smallest determinant, yielding a "pure" subset of observations from which to compute standards estimates of location and covariance. @@ -33,12 +37,12 @@ This example illustrates how the Mahalanobis distances are affected by outlying data: observations drawn from a contaminating distribution -are not distinguishable from the observations comming from the real, +are not distinguishable from the observations coming from the real, Gaussian distribution that one may want to work with. Using MCD-based Mahalanobis distances, the two populations become distinguishable. Associated applications are outliers detection, observations ranking, clustering, ... -For vizualisation purpose, the cubique root of the Mahalanobis distances +For visualization purpose, the cubic root of the Mahalanobis distances are represented in the boxplot, as Wilson and Hilferty suggest [2] [1] P. J. Rousseeuw. Least median of squares regression. J. Am @@ -48,10 +52,10 @@ of America, 17, 684-688. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.covariance import EmpiricalCovariance, MinCovDet @@ -76,11 +80,11 @@ ############################################################################### # Display results -fig = pl.figure() -pl.subplots_adjust(hspace=-.1, wspace=.4, top=.95, bottom=.05) +fig = plt.figure() +plt.subplots_adjust(hspace=-.1, wspace=.4, top=.95, bottom=.05) # Show data set -subfig1 = pl.subplot(3, 1, 1) +subfig1 = plt.subplot(3, 1, 1) inlier_plot = subfig1.scatter(X[:, 0], X[:, 1], color='black', label='inliers') outlier_plot = subfig1.scatter(X[:, 0][-n_outliers:], X[:, 1][-n_outliers:], @@ -89,32 +93,31 @@ subfig1.set_title("Mahalanobis distances of a contaminated data set:") # Show contours of the distance functions -xx, yy = np.meshgrid(np.linspace(pl.xlim()[0], pl.xlim()[1], 100), - np.linspace(pl.ylim()[0], pl.ylim()[1], 100)) +xx, yy = np.meshgrid(np.linspace(plt.xlim()[0], plt.xlim()[1], 100), + np.linspace(plt.ylim()[0], plt.ylim()[1], 100)) zz = np.c_[xx.ravel(), yy.ravel()] mahal_emp_cov = emp_cov.mahalanobis(zz) mahal_emp_cov = mahal_emp_cov.reshape(xx.shape) emp_cov_contour = subfig1.contour(xx, yy, np.sqrt(mahal_emp_cov), - cmap=pl.cm.PuBu_r, + cmap=plt.cm.PuBu_r, linestyles='dashed') mahal_robust_cov = robust_cov.mahalanobis(zz) mahal_robust_cov = mahal_robust_cov.reshape(xx.shape) robust_contour = subfig1.contour(xx, yy, np.sqrt(mahal_robust_cov), - cmap=pl.cm.YlOrBr_r, - linestyles='dotted') + cmap=plt.cm.YlOrBr_r, linestyles='dotted') -subfig1.legend([emp_cov_contour.collections[1], - robust_contour.collections[1], inlier_plot, outlier_plot], - ['MLE dist', 'robust dist', 'inliers', 'outliers'], - loc="upper right", borderaxespad=0) -pl.xticks(()) -pl.yticks(()) +subfig1.legend([emp_cov_contour.collections[1], robust_contour.collections[1], + inlier_plot, outlier_plot], + ['MLE dist', 'robust dist', 'inliers', 'outliers'], + loc="upper right", borderaxespad=0) +plt.xticks(()) +plt.yticks(()) # Plot the scores for each point emp_mahal = emp_cov.mahalanobis(X - np.mean(X, 0)) ** (0.33) -subfig2 = pl.subplot(2, 2, 3) +subfig2 = plt.subplot(2, 2, 3) subfig2.boxplot([emp_mahal[:-n_outliers], emp_mahal[-n_outliers:]], widths=.25) subfig2.plot(1.26 * np.ones(n_samples - n_outliers), emp_mahal[:-n_outliers], '+k', markeredgewidth=1) @@ -123,10 +126,10 @@ subfig2.axes.set_xticklabels(('inliers', 'outliers'), size=15) subfig2.set_ylabel(r"$\sqrt[3]{\rm{(Mahal. dist.)}}$", size=16) subfig2.set_title("1. from non-robust estimates\n(Maximum Likelihood)") -pl.yticks(()) +plt.yticks(()) robust_mahal = robust_cov.mahalanobis(X - robust_cov.location_) ** (0.33) -subfig3 = pl.subplot(2, 2, 4) +subfig3 = plt.subplot(2, 2, 4) subfig3.boxplot([robust_mahal[:-n_outliers], robust_mahal[-n_outliers:]], widths=.25) subfig3.plot(1.26 * np.ones(n_samples - n_outliers), @@ -136,6 +139,6 @@ subfig3.axes.set_xticklabels(('inliers', 'outliers'), size=15) subfig3.set_ylabel(r"$\sqrt[3]{\rm{(Mahal. dist.)}}$", size=16) subfig3.set_title("2. from robust estimates\n(Minimum Covariance Determinant)") -pl.yticks(()) +plt.yticks(()) -pl.show() +plt.show() diff --git a/examples/covariance/plot_outlier_detection.py b/examples/covariance/plot_outlier_detection.py index 0db8cdb73519d..fefa666fe00f4 100644 --- a/examples/covariance/plot_outlier_detection.py +++ b/examples/covariance/plot_outlier_detection.py @@ -3,8 +3,8 @@ Outlier detection with several methods. ========================================== -This example illustrates two ways of performing :ref:`outlier_detection` -when the amount of contamination is known: +When the amount of contamination is known, this example illustrates two +different ways of performing :ref:`outlier_detection`: - based on a robust estimator of covariance, which is assuming that the data are Gaussian distributed and performs better than the One-Class SVM @@ -15,7 +15,7 @@ non-Gaussian, i.e. with two well-separated clusters; The ground truth about inliers and outliers is given by the points colors -while the orange-filled area indicates which points are reported as outliers +while the orange-filled area indicates which points are reported as inliers by each method. Here, we assume that we know the fraction of outliers in the datasets. @@ -23,10 +23,10 @@ threshold on the decision_function to separate out the corresponding fraction. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt import matplotlib.font_manager from scipy import stats @@ -42,8 +42,7 @@ classifiers = { "One-Class SVM": svm.OneClassSVM(nu=0.95 * outliers_fraction + 0.05, kernel="rbf", gamma=0.1), - "robust covariance estimator": EllipticEnvelope(contamination=.1), - } + "robust covariance estimator": EllipticEnvelope(contamination=.1)} # Compare given classifiers under given settings xx, yy = np.meshgrid(np.linspace(-7, 7, 500), np.linspace(-7, 7, 500)) @@ -63,8 +62,8 @@ X = np.r_[X, np.random.uniform(low=-6, high=6, size=(n_outliers, 2))] # Fit the model with the One-Class SVM - pl.figure(figsize=(10, 5)) - for i, (clf_name, clf) in enumerate(classifiers.iteritems()): + plt.figure(figsize=(10, 5)) + for i, (clf_name, clf) in enumerate(classifiers.items()): # fit the data and tag outliers clf.fit(X) y_pred = clf.decision_function(X).ravel() @@ -75,10 +74,10 @@ # plot the levels lines and the points Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) - subplot = pl.subplot(1, 2, i + 1) + subplot = plt.subplot(1, 2, i + 1) subplot.set_title("Outlier detection") subplot.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7), - cmap=pl.cm.Blues_r) + cmap=plt.cm.Blues_r) a = subplot.contour(xx, yy, Z, levels=[threshold], linewidths=2, colors='red') subplot.contourf(xx, yy, Z, levels=[threshold, Z.max()], @@ -93,6 +92,6 @@ subplot.set_xlabel("%d. %s (errors: %d)" % (i + 1, clf_name, n_errors)) subplot.set_xlim((-7, 7)) subplot.set_ylim((-7, 7)) - pl.subplots_adjust(0.04, 0.1, 0.96, 0.94, 0.1, 0.26) + plt.subplots_adjust(0.04, 0.1, 0.96, 0.94, 0.1, 0.26) -pl.show() +plt.show() diff --git a/examples/covariance/plot_robust_vs_empirical_covariance.py b/examples/covariance/plot_robust_vs_empirical_covariance.py index d12c572c79d76..3a412d96d1fa8 100644 --- a/examples/covariance/plot_robust_vs_empirical_covariance.py +++ b/examples/covariance/plot_robust_vs_empirical_covariance.py @@ -1,50 +1,60 @@ -""" +r""" ======================================= Robust vs Empirical covariance estimate ======================================= -The usual covariance maximum likelihood estimate is very sensitive to -the presence of outliers in the data set. In such a case, one would -have better to use a robust estimator of covariance to garanty that -the estimation is resistant to "errorneous" observations in the data -set. - -The Minimum Covariance Determinant estimator is a robust, -high-breakdown point (i.e. it can be used to estimate the covariance -matrix of highly contaminated datasets, up to -:math:`\frac{n_samples-n_features-1}{2}` outliers) estimator of -covariance. The idea is to find :math:`\frac{n_samples+n_features+1}{2}` -observations whose empirical covariance has the smallest determinant, -yielding a "pure" subset of observations from which to compute -standards estimates of location and covariance. After a correction -step aiming at compensating the fact the the estimates were learnt -from only a portion of the initial data, we end up with robust -estimates of the data set location and covariance. - -The Minimum Covariance Determinant estimator (MCD) has been introduced -by P.J.Rousseuw in [1]. - -In this example, we compare the estimation errors that are made when -using three types of location and covariance estimates on contaminated -gaussian distributed data sets: +The usual covariance maximum likelihood estimate is very sensitive to the +presence of outliers in the data set. In such a case, it would be better to +use a robust estimator of covariance to guarantee that the estimation is +resistant to "erroneous" observations in the data set. + +Minimum Covariance Determinant Estimator +---------------------------------------- +The Minimum Covariance Determinant estimator is a robust, high-breakdown point +(i.e. it can be used to estimate the covariance matrix of highly contaminated +datasets, up to +:math:`\frac{n_\text{samples} - n_\text{features}-1}{2}` outliers) estimator of +covariance. The idea is to find +:math:`\frac{n_\text{samples} + n_\text{features}+1}{2}` +observations whose empirical covariance has the smallest determinant, yielding +a "pure" subset of observations from which to compute standards estimates of +location and covariance. After a correction step aiming at compensating the +fact that the estimates were learned from only a portion of the initial data, +we end up with robust estimates of the data set location and covariance. + +The Minimum Covariance Determinant estimator (MCD) has been introduced by +P.J.Rousseuw in [1]_. + +Evaluation +---------- +In this example, we compare the estimation errors that are made when using +various types of location and covariance estimates on contaminated Gaussian +distributed data sets: - The mean and the empirical covariance of the full dataset, which break down as soon as there are outliers in the data set -- The robust MCD, that has a low error provided n_samples > 5 * n_features +- The robust MCD, that has a low error provided + :math:`n_\text{samples} > 5n_\text{features}` - The mean and the empirical covariance of the observations that are known to be good ones. This can be considered as a "perfect" MCD estimation, so one can trust our implementation by comparing to this case. -[1] P. J. Rousseeuw. Least median of squares regression. J. Am + +References +---------- +.. [1] P. J. Rousseeuw. Least median of squares regression. J. Am Stat Ass, 79:871, 1984. -[2] Johanna Hardin, David M Rocke. Journal of Computational and +.. [2] Johanna Hardin, David M Rocke. Journal of Computational and Graphical Statistics. December 1, 2005, 14(4): 928-946. +.. [3] Zoubir A., Koivunen V., Chakhchoukh Y. and Muma M. (2012). Robust + estimation in signal processing: A tutorial-style treatment of + fundamental concepts. IEEE Signal Processing Magazine 29(4), 61-80. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt import matplotlib.font_manager from sklearn.covariance import EmpiricalCovariance, MinCovDet @@ -69,10 +79,13 @@ # computation for i, n_outliers in enumerate(range_n_outliers): for j in range(repeat): + + rng = np.random.RandomState(i * j) + # generate data - X = np.random.randn(n_samples, n_features) + X = rng.randn(n_samples, n_features) # add some outliers - outliers_index = np.random.permutation(n_samples)[:n_outliers] + outliers_index = rng.permutation(n_samples)[:n_outliers] outliers_offset = 10. * \ (np.random.randint(2, size=(n_outliers, n_features)) - 0.5) X[outliers_index] += outliers_offset @@ -80,16 +93,19 @@ inliers_mask[outliers_index] = False # fit a Minimum Covariance Determinant (MCD) robust estimator to data - S = MinCovDet().fit(X) + mcd = MinCovDet().fit(X) # compare raw robust estimates with the true location and covariance - err_loc_mcd[i, j] = np.sum(S.location_ ** 2) - err_cov_mcd[i, j] = S.error_norm(np.eye(n_features)) - # compare estimators learnt from the full data set with true parameters + err_loc_mcd[i, j] = np.sum(mcd.location_ ** 2) + err_cov_mcd[i, j] = mcd.error_norm(np.eye(n_features)) + + # compare estimators learned from the full data set with true + # parameters err_loc_emp_full[i, j] = np.sum(X.mean(0) ** 2) err_cov_emp_full[i, j] = EmpiricalCovariance().fit(X).error_norm( np.eye(n_features)) - # compare with an empirical covariance learnt from a pure data set - # (i.e. "perfect" MCD) + + # compare with an empirical covariance learned from a pure data set + # (i.e. "perfect" mcd) pure_X = X[inliers_mask] pure_location = pure_X.mean(0) pure_emp_cov = EmpiricalCovariance().fit(pure_X) @@ -98,38 +114,38 @@ # Display results font_prop = matplotlib.font_manager.FontProperties(size=11) -pl.subplot(2, 1, 1) -pl.errorbar(range_n_outliers, err_loc_mcd.mean(1), - yerr=err_loc_mcd.std(1) / np.sqrt(repeat), - label="Robust location", color='m') -pl.errorbar(range_n_outliers, err_loc_emp_full.mean(1), - yerr=err_loc_emp_full.std(1) / np.sqrt(repeat), - label="Full data set mean", color='green') -pl.errorbar(range_n_outliers, err_loc_emp_pure.mean(1), - yerr=err_loc_emp_pure.std(1) / np.sqrt(repeat), - label="Pure data set mean", color='black') -pl.title("Influence of outliers on the location estimation") -pl.ylabel(r"Error ($||\mu - \hat{\mu}||_2^2$)") -pl.legend(loc="upper left", prop=font_prop) - -pl.subplot(2, 1, 2) +plt.subplot(2, 1, 1) +plt.errorbar(range_n_outliers, err_loc_mcd.mean(1), + yerr=err_loc_mcd.std(1) / np.sqrt(repeat), + label="Robust location", color='m') +plt.errorbar(range_n_outliers, err_loc_emp_full.mean(1), + yerr=err_loc_emp_full.std(1) / np.sqrt(repeat), + label="Full data set mean", color='green') +plt.errorbar(range_n_outliers, err_loc_emp_pure.mean(1), + yerr=err_loc_emp_pure.std(1) / np.sqrt(repeat), + label="Pure data set mean", color='black') +plt.title("Influence of outliers on the location estimation") +plt.ylabel(r"Error ($||\mu - \hat{\mu}||_2^2$)") +plt.legend(loc="upper left", prop=font_prop) + +plt.subplot(2, 1, 2) x_size = range_n_outliers.size -pl.errorbar(range_n_outliers, err_cov_mcd.mean(1), - yerr=err_cov_mcd.std(1), - label="Robust covariance (MCD)", color='m') -pl.errorbar(range_n_outliers[:(x_size / 5 + 1)], - err_cov_emp_full.mean(1)[:(x_size / 5 + 1)], - yerr=err_cov_emp_full.std(1)[:(x_size / 5 + 1)], - label="Full data set empirical covariance", color='green') -pl.plot(range_n_outliers[(x_size / 5):(x_size / 2 - 1)], - err_cov_emp_full.mean(1)[(x_size / 5):(x_size / 2 - 1)], - color='green', ls='--') -pl.errorbar(range_n_outliers, err_cov_emp_pure.mean(1), - yerr=err_cov_emp_pure.std(1), - label="Pure data set empirical covariance", color='black') -pl.title("Influence of outliers on the covariance estimation") -pl.xlabel("Amount of contamination (%)") -pl.ylabel("RMSE") -pl.legend(loc="upper center", prop=font_prop) - -pl.show() +plt.errorbar(range_n_outliers, err_cov_mcd.mean(1), + yerr=err_cov_mcd.std(1), + label="Robust covariance (mcd)", color='m') +plt.errorbar(range_n_outliers[:(x_size / 5 + 1)], + err_cov_emp_full.mean(1)[:(x_size / 5 + 1)], + yerr=err_cov_emp_full.std(1)[:(x_size / 5 + 1)], + label="Full data set empirical covariance", color='green') +plt.plot(range_n_outliers[(x_size / 5):(x_size / 2 - 1)], + err_cov_emp_full.mean(1)[(x_size / 5):(x_size / 2 - 1)], color='green', + ls='--') +plt.errorbar(range_n_outliers, err_cov_emp_pure.mean(1), + yerr=err_cov_emp_pure.std(1), + label="Pure data set empirical covariance", color='black') +plt.title("Influence of outliers on the covariance estimation") +plt.xlabel("Amount of contamination (%)") +plt.ylabel("RMSE") +plt.legend(loc="upper center", prop=font_prop) + +plt.show() diff --git a/examples/covariance/plot_sparse_cov.py b/examples/covariance/plot_sparse_cov.py index 27a6538972e06..664e974b331cf 100644 --- a/examples/covariance/plot_sparse_cov.py +++ b/examples/covariance/plot_sparse_cov.py @@ -39,8 +39,8 @@ zero: because of the penalty, they are all smaller than the corresponding ground truth value, as can be seen on the figure. -Note that, the color range of the precision matrices is tweeked to -improve readibility of the figure. The full range of values of the +Note that, the color range of the precision matrices is tweaked to +improve readability of the figure. The full range of values of the empirical precision is not displayed. The alpha parameter of the GraphLasso setting the sparsity of the model is @@ -48,16 +48,16 @@ seen on figure 2, the grid to compute the cross-validation score is iteratively refined in the neighborhood of the maximum. """ -print __doc__ +print(__doc__) # author: Gael Varoquaux -# License: BSD Style +# License: BSD 3 clause # Copyright: INRIA import numpy as np from scipy import linalg from sklearn.datasets import make_sparse_spd_matrix from sklearn.covariance import GraphLassoCV, ledoit_wolf -import pylab as pl +import matplotlib.pyplot as plt ############################################################################## # Generate the data @@ -93,20 +93,20 @@ ############################################################################## # Plot the results -pl.figure(figsize=(10, 6)) -pl.subplots_adjust(left=0.02, right=0.98) +plt.figure(figsize=(10, 6)) +plt.subplots_adjust(left=0.02, right=0.98) # plot the covariances covs = [('Empirical', emp_cov), ('Ledoit-Wolf', lw_cov_), ('GraphLasso', cov_), ('True', cov)] vmax = cov_.max() for i, (name, this_cov) in enumerate(covs): - pl.subplot(2, 4, i + 1) - pl.imshow(this_cov, interpolation='nearest', vmin=-vmax, vmax=vmax, - cmap=pl.cm.RdBu_r) - pl.xticks(()) - pl.yticks(()) - pl.title('%s covariance' % name) + plt.subplot(2, 4, i + 1) + plt.imshow(this_cov, interpolation='nearest', vmin=-vmax, vmax=vmax, + cmap=plt.cm.RdBu_r) + plt.xticks(()) + plt.yticks(()) + plt.title('%s covariance' % name) # plot the precisions @@ -114,22 +114,22 @@ ('GraphLasso', prec_), ('True', prec)] vmax = .9 * prec_.max() for i, (name, this_prec) in enumerate(precs): - ax = pl.subplot(2, 4, i + 5) - pl.imshow(np.ma.masked_equal(this_prec, 0), - interpolation='nearest', vmin=-vmax, vmax=vmax, - cmap=pl.cm.RdBu_r) - pl.xticks(()) - pl.yticks(()) - pl.title('%s precision' % name) + ax = plt.subplot(2, 4, i + 5) + plt.imshow(np.ma.masked_equal(this_prec, 0), + interpolation='nearest', vmin=-vmax, vmax=vmax, + cmap=plt.cm.RdBu_r) + plt.xticks(()) + plt.yticks(()) + plt.title('%s precision' % name) ax.set_axis_bgcolor('.7') # plot the model selection metric -pl.figure(figsize=(4, 3)) -pl.axes([.2, .15, .75, .7]) -pl.plot(model.cv_alphas_, np.mean(model.cv_scores, axis=1), 'o-') -pl.axvline(model.alpha_, color='.5') -pl.title('Model selection') -pl.ylabel('Cross-validation score') -pl.xlabel('alpha') - -pl.show() +plt.figure(figsize=(4, 3)) +plt.axes([.2, .15, .75, .7]) +plt.plot(model.cv_alphas_, np.mean(model.grid_scores, axis=1), 'o-') +plt.axvline(model.alpha_, color='.5') +plt.title('Model selection') +plt.ylabel('Cross-validation score') +plt.xlabel('alpha') + +plt.show() diff --git a/examples/cross_decomposition/README.txt b/examples/cross_decomposition/README.txt new file mode 100644 index 0000000000000..07649ffbb6960 --- /dev/null +++ b/examples/cross_decomposition/README.txt @@ -0,0 +1,7 @@ +.. _cross_decomposition_examples: + +Cross decomposition +------------------- + +Examples concerning the :mod:`sklearn.cross_decomposition` module. + diff --git a/examples/plot_pls.py b/examples/cross_decomposition/plot_compare_cross_decomposition.py similarity index 60% rename from examples/plot_pls.py rename to examples/cross_decomposition/plot_compare_cross_decomposition.py index b22be3bd2d0fe..f582be9e00048 100644 --- a/examples/plot_pls.py +++ b/examples/cross_decomposition/plot_compare_cross_decomposition.py @@ -1,9 +1,9 @@ """ -========================= -PLS Partial Least Squares -========================= +=================================== +Compare cross decomposition methods +=================================== -Simple usage of various PLS flavor: +Simple usage of various cross decomposition algorithms: - PLSCanonical - PLSRegression, with multivariate response, a.k.a. PLS2 - PLSRegression, with univariate response, a.k.a. PLS1 @@ -13,16 +13,16 @@ PLS extracts the 'directions of covariance', i.e. the components of each datasets that explain the most shared variance between both datasets. This is apparent on the **scatterplot matrix** display: components 1 in -dataset X and dataset Y are maximaly correlated (points lie around the +dataset X and dataset Y are maximally correlated (points lie around the first diagonal). This is also true for components 2 in both dataset, however, the correlation across datasets for different components is weak: the point cloud is very spherical. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl -from sklearn.pls import PLSCanonical, PLSRegression, CCA +import matplotlib.pyplot as plt +from sklearn.cross_decomposition import PLSCanonical, PLSRegression, CCA ############################################################################### # Dataset based latent variables model @@ -47,7 +47,7 @@ print(np.round(np.corrcoef(Y.T), 2)) ############################################################################### -# Canonical (symetric) PLS +# Canonical (symmetric) PLS # Transform data # ~~~~~~~~~~~~~~ @@ -59,52 +59,52 @@ # Scatter plot of scores # ~~~~~~~~~~~~~~~~~~~~~~ # 1) On diagonal plot X vs Y scores on each components -pl.figure(figsize=(12, 8)) -pl.subplot(221) -pl.plot(X_train_r[:, 0], Y_train_r[:, 0], "ob", label="train") -pl.plot(X_test_r[:, 0], Y_test_r[:, 0], "or", label="test") -pl.xlabel("x scores") -pl.ylabel("y scores") -pl.title('Comp. 1: X vs Y (test corr = %.2f)' % - np.corrcoef(X_test_r[:, 0], Y_test_r[:, 0])[0, 1]) -pl.xticks(()) -pl.yticks(()) -pl.legend(loc="best") - -pl.subplot(224) -pl.plot(X_train_r[:, 1], Y_train_r[:, 1], "ob", label="train") -pl.plot(X_test_r[:, 1], Y_test_r[:, 1], "or", label="test") -pl.xlabel("x scores") -pl.ylabel("y scores") -pl.title('Comp. 2: X vs Y (test corr = %.2f)' % - np.corrcoef(X_test_r[:, 1], Y_test_r[:, 1])[0, 1]) -pl.xticks(()) -pl.yticks(()) -pl.legend(loc="best") +plt.figure(figsize=(12, 8)) +plt.subplot(221) +plt.plot(X_train_r[:, 0], Y_train_r[:, 0], "ob", label="train") +plt.plot(X_test_r[:, 0], Y_test_r[:, 0], "or", label="test") +plt.xlabel("x scores") +plt.ylabel("y scores") +plt.title('Comp. 1: X vs Y (test corr = %.2f)' % + np.corrcoef(X_test_r[:, 0], Y_test_r[:, 0])[0, 1]) +plt.xticks(()) +plt.yticks(()) +plt.legend(loc="best") + +plt.subplot(224) +plt.plot(X_train_r[:, 1], Y_train_r[:, 1], "ob", label="train") +plt.plot(X_test_r[:, 1], Y_test_r[:, 1], "or", label="test") +plt.xlabel("x scores") +plt.ylabel("y scores") +plt.title('Comp. 2: X vs Y (test corr = %.2f)' % + np.corrcoef(X_test_r[:, 1], Y_test_r[:, 1])[0, 1]) +plt.xticks(()) +plt.yticks(()) +plt.legend(loc="best") # 2) Off diagonal plot components 1 vs 2 for X and Y -pl.subplot(222) -pl.plot(X_train_r[:, 0], X_train_r[:, 1], "*b", label="train") -pl.plot(X_test_r[:, 0], X_test_r[:, 1], "*r", label="test") -pl.xlabel("X comp. 1") -pl.ylabel("X comp. 2") -pl.title('X comp. 1 vs X comp. 2 (test corr = %.2f)' % \ - np.corrcoef(X_test_r[:, 0], X_test_r[:, 1])[0, 1]) -pl.legend(loc="best") -pl.xticks(()) -pl.yticks(()) - -pl.subplot(223) -pl.plot(Y_train_r[:, 0], Y_train_r[:, 1], "*b", label="train") -pl.plot(Y_test_r[:, 0], Y_test_r[:, 1], "*r", label="test") -pl.xlabel("Y comp. 1") -pl.ylabel("Y comp. 2") -pl.title('Y comp. 1 vs Y comp. 2 , (test corr = %.2f)' % \ - np.corrcoef(Y_test_r[:, 0], Y_test_r[:, 1])[0, 1]) -pl.legend(loc="best") -pl.xticks(()) -pl.yticks(()) -pl.show() +plt.subplot(222) +plt.plot(X_train_r[:, 0], X_train_r[:, 1], "*b", label="train") +plt.plot(X_test_r[:, 0], X_test_r[:, 1], "*r", label="test") +plt.xlabel("X comp. 1") +plt.ylabel("X comp. 2") +plt.title('X comp. 1 vs X comp. 2 (test corr = %.2f)' + % np.corrcoef(X_test_r[:, 0], X_test_r[:, 1])[0, 1]) +plt.legend(loc="best") +plt.xticks(()) +plt.yticks(()) + +plt.subplot(223) +plt.plot(Y_train_r[:, 0], Y_train_r[:, 1], "*b", label="train") +plt.plot(Y_test_r[:, 0], Y_test_r[:, 1], "*r", label="test") +plt.xlabel("Y comp. 1") +plt.ylabel("Y comp. 2") +plt.title('Y comp. 1 vs Y comp. 2 , (test corr = %.2f)' + % np.corrcoef(Y_test_r[:, 0], Y_test_r[:, 1])[0, 1]) +plt.legend(loc="best") +plt.xticks(()) +plt.yticks(()) +plt.show() ############################################################################### # PLS regression, with multivariate response, a.k.a. PLS2 @@ -140,7 +140,7 @@ print(np.round(pls1.coefs, 1)) ############################################################################### -# CCA (PLS mode B with symetric deflation) +# CCA (PLS mode B with symmetric deflation) cca = CCA(n_components=2) cca.fit(X_train, Y_train) diff --git a/examples/datasets/README.txt b/examples/datasets/README.txt index 1afa9ed132c1b..cd3354d7e9d5c 100644 --- a/examples/datasets/README.txt +++ b/examples/datasets/README.txt @@ -3,4 +3,4 @@ Dataset examples ----------------------- -Examples concerning the :mod:`sklearn.datasets` package. +Examples concerning the :mod:`sklearn.datasets` module. diff --git a/examples/datasets/plot_digits_last_image.py b/examples/datasets/plot_digits_last_image.py index ad6793c3cacad..f08f06888a8f3 100644 --- a/examples/datasets/plot_digits_last_image.py +++ b/examples/datasets/plot_digits_last_image.py @@ -5,30 +5,31 @@ ========================================================= The Digit Dataset ========================================================= + This dataset is made up of 1797 8x8 images. Each image, like the one shown below, is of a hand-written digit. -In order to ultilise an 8x8 figure like this, we'd have to -first transform it into a feature vector with lengh 64. +In order to utilize an 8x8 figure like this, we'd have to +first transform it into a feature vector with length 64. See `here `_ for more information about this dataset. """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD +# Code source: Gaël Varoquaux +# Modified for documentation by Jaques Grobler +# License: BSD 3 clause from sklearn import datasets -import pylab as pl +import matplotlib.pyplot as plt #Load the digits dataset digits = datasets.load_digits() #Display the first digit -pl.figure(1, figsize=(3, 3)) -pl.imshow(digits.images[-1], cmap=pl.cm.gray_r, interpolation='nearest') -pl.show() +plt.figure(1, figsize=(3, 3)) +plt.imshow(digits.images[-1], cmap=plt.cm.gray_r, interpolation='nearest') +plt.show() diff --git a/examples/datasets/plot_iris_dataset.py b/examples/datasets/plot_iris_dataset.py index 308696efc1f67..2436dac67253c 100644 --- a/examples/datasets/plot_iris_dataset.py +++ b/examples/datasets/plot_iris_dataset.py @@ -16,14 +16,14 @@ See `here `_ for more information on this dataset. """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD +# Code source: Gaël Varoquaux +# Modified for documentation by Jaques Grobler +# License: BSD 3 clause -import pylab as pl +import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import datasets from sklearn.decomposition import PCA @@ -36,32 +36,32 @@ x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 -pl.figure(2, figsize=(8, 6)) -pl.clf() +plt.figure(2, figsize=(8, 6)) +plt.clf() # Plot the training points -pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired) -pl.xlabel('Sepal length') -pl.ylabel('Sepal width') +plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired) +plt.xlabel('Sepal length') +plt.ylabel('Sepal width') -pl.xlim(x_min, x_max) -pl.ylim(y_min, y_max) -pl.xticks(()) -pl.yticks(()) +plt.xlim(x_min, x_max) +plt.ylim(y_min, y_max) +plt.xticks(()) +plt.yticks(()) # To getter a better understanding of interaction of the dimensions # plot the first three PCA dimensions -fig = pl.figure(1, figsize=(8, 6)) +fig = plt.figure(1, figsize=(8, 6)) ax = Axes3D(fig, elev=-150, azim=110) X_reduced = PCA(n_components=3).fit_transform(iris.data) ax.scatter(X_reduced[:, 0], X_reduced[:, 1], X_reduced[:, 2], c=Y, - cmap=pl.cm.Paired) + cmap=plt.cm.Paired) ax.set_title("First three PCA directions") ax.set_xlabel("1st eigenvector") -ax.set_xticks(()) +ax.w_xaxis.set_ticklabels([]) ax.set_ylabel("2nd eigenvector") -ax.set_yticks(()) +ax.w_yaxis.set_ticklabels([]) ax.set_zlabel("3rd eigenvector") -ax.set_zticks(()) +ax.w_zaxis.set_ticklabels([]) -pl.show() +plt.show() diff --git a/examples/datasets/plot_random_dataset.py b/examples/datasets/plot_random_dataset.py index 5b19f31a41913..d1802ce8f8e0e 100644 --- a/examples/datasets/plot_random_dataset.py +++ b/examples/datasets/plot_random_dataset.py @@ -4,46 +4,58 @@ ============================================== Plot several randomly generated 2D classification datasets. -This example illustrates the `datasets.make_classification` -function. +This example illustrates the :func:`datasets.make_classification` +:func:`datasets.make_blobs` and :func:`datasets.make_gaussian_quantiles` +functions. -Three binary and two multi-class classification datasets -are generated, with different numbers of informative -features and clusters per class. -""" +For ``make_classification``, three binary and two multi-class classification +datasets are generated, with different numbers of informative features and +clusters per class. """ -print __doc__ +print(__doc__) -import pylab as pl +import matplotlib.pyplot as plt from sklearn.datasets import make_classification +from sklearn.datasets import make_blobs +from sklearn.datasets import make_gaussian_quantiles -pl.figure(figsize=(8, 6)) -pl.subplots_adjust(bottom=.05, top=.9, left=.05, right=.95) +plt.figure(figsize=(8, 8)) +plt.subplots_adjust(bottom=.05, top=.9, left=.05, right=.95) -pl.subplot(221) -pl.title("One informative feature, one cluster", fontsize='small') +plt.subplot(321) +plt.title("One informative feature, one cluster per class", fontsize='small') X1, Y1 = make_classification(n_features=2, n_redundant=0, n_informative=1, - n_clusters_per_class=1) -pl.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1) + n_clusters_per_class=1) +plt.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1) -pl.subplot(222) -pl.title("Two informative features, one cluster", fontsize='small') +plt.subplot(322) +plt.title("Two informative features, one cluster per class", fontsize='small') X1, Y1 = make_classification(n_features=2, n_redundant=0, n_informative=2, - n_clusters_per_class=1) -pl.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1) + n_clusters_per_class=1) +plt.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1) -pl.subplot(223) -pl.title("Two informative features, two clusters", fontsize='small') +plt.subplot(323) +plt.title("Two informative features, two clusters per class", fontsize='small') X2, Y2 = make_classification(n_features=2, n_redundant=0, n_informative=2) -pl.scatter(X2[:, 0], X2[:, 1], marker='o', c=Y2) +plt.scatter(X2[:, 0], X2[:, 1], marker='o', c=Y2) -pl.subplot(224) -pl.title("Multi-class, two informative features, one cluster", - fontsize='small') +plt.subplot(324) +plt.title("Multi-class, two informative features, one cluster", + fontsize='small') X1, Y1 = make_classification(n_features=2, n_redundant=0, n_informative=2, - n_clusters_per_class=1, n_classes=3) -pl.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1) + n_clusters_per_class=1, n_classes=3) +plt.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1) + +plt.subplot(325) +plt.title("Three blobs", fontsize='small') +X1, Y1 = make_blobs(n_features=2, centers=3) +plt.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1) + +plt.subplot(326) +plt.title("Gaussian divided into three quantiles", fontsize='small') +X1, Y1 = make_gaussian_quantiles(n_features=2, n_classes=3) +plt.scatter(X1[:, 0], X1[:, 1], marker='o', c=Y1) -pl.show() +plt.show() diff --git a/examples/datasets/plot_random_multilabel_dataset.py b/examples/datasets/plot_random_multilabel_dataset.py new file mode 100644 index 0000000000000..4137a79bf5630 --- /dev/null +++ b/examples/datasets/plot_random_multilabel_dataset.py @@ -0,0 +1,96 @@ +""" +============================================== +Plot randomly generated multilabel dataset +============================================== + +This illustrates the `datasets.make_multilabel_classification` dataset +generator. Each sample consists of counts of two features (up to 50 in +total), which are differently distributed in each of two classes. + +Points are labeled as follows, where Y means the class is present: + + ===== ===== ===== ====== + 1 2 3 Color + ===== ===== ===== ====== + Y N N Red + N Y N Blue + N N Y Yellow + Y Y N Purple + Y N Y Orange + Y Y N Green + Y Y Y Brown + ===== ===== ===== ====== + +A star marks the expected sample for each class; its size reflects the +probability of selecting that class label. + +The left and right examples highlight the ``n_labels`` parameter: +more of the samples in the right plot have 2 or 3 labels. + +Note that this two-dimensional example is very degenerate: +generally the number of features would be much greater than the +"document length", while here we have much larger documents than vocabulary. +Similarly, with ``n_classes > n_features``, it is much less likely that a +feature distinguishes a particular class. +""" + +from __future__ import print_function +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.datasets import make_multilabel_classification as make_ml_clf + +print(__doc__) + +COLORS = np.array(['!', + '#FF3333', # red + '#0198E1', # blue + '#BF5FFF', # purple + '#FCD116', # yellow + '#FF7216', # orange + '#4DBD33', # green + '#87421F' # brown + ]) + +# Use same random seed for multiple calls to make_multilabel_classification to +# ensure same distributions +RANDOM_SEED = np.random.randint(2 ** 10) + + +def plot_2d(ax, n_labels=1, n_classes=3, length=50): + X, Y, p_c, p_w_c = make_ml_clf(n_samples=150, n_features=2, + n_classes=n_classes, n_labels=n_labels, + length=length, allow_unlabeled=False, + return_indicator=True, + return_distributions=True, + random_state=RANDOM_SEED) + + ax.scatter(X[:, 0], X[:, 1], color=COLORS.take((Y * [1, 2, 4] + ).sum(axis=1)), + marker='.') + ax.scatter(p_w_c[0] * length, p_w_c[1] * length, + marker='*', linewidth=.5, edgecolor='black', + s=20 + 1500 * p_c ** 2, + color=COLORS.take([1, 2, 4])) + ax.set_xlabel('Feature 0 count') + return p_c, p_w_c + + +_, (ax1, ax2) = plt.subplots(1, 2, sharex='row', sharey='row', figsize=(8, 4)) +plt.subplots_adjust(bottom=.15) + +p_c, p_w_c = plot_2d(ax1, n_labels=1) +ax1.set_title('n_labels=1, length=50') +ax1.set_ylabel('Feature 1 count') + +plot_2d(ax2, n_labels=3) +ax2.set_title('n_labels=3, length=50') +ax2.set_xlim(left=0, auto=True) +ax2.set_ylim(bottom=0, auto=True) + +plt.show() + +print('The data was generated from (random_state=%d):' % RANDOM_SEED) +print('Class', 'P(C)', 'P(w0|C)', 'P(w1|C)', sep='\t') +for k, p, p_w in zip(['red', 'blue', 'yellow'], p_c, p_w_c.T): + print('%s\t%0.2f\t%0.2f\t%0.2f' % (k, p, p_w[0], p_w[1])) diff --git a/examples/decomposition/README.txt b/examples/decomposition/README.txt index 3fbad80cd5e62..73014f768ff9f 100644 --- a/examples/decomposition/README.txt +++ b/examples/decomposition/README.txt @@ -3,5 +3,5 @@ Decomposition ------------- -Examples concerning the :mod:`sklearn.decomposition` package. +Examples concerning the :mod:`sklearn.decomposition` module. diff --git a/examples/decomposition/plot_faces_decomposition.py b/examples/decomposition/plot_faces_decomposition.py index fc01b3839bc43..e85da1b952253 100644 --- a/examples/decomposition/plot_faces_decomposition.py +++ b/examples/decomposition/plot_faces_decomposition.py @@ -9,16 +9,16 @@ :ref:`decompositions`) . """ -print __doc__ +print(__doc__) # Authors: Vlad Niculae, Alexandre Gramfort -# License: BSD +# License: BSD 3 clause import logging from time import time from numpy.random import RandomState -import pylab as pl +import matplotlib.pyplot as plt from sklearn.datasets import fetch_olivetti_faces from sklearn.cluster import MiniBatchKMeans @@ -45,22 +45,22 @@ # local centering faces_centered -= faces_centered.mean(axis=1).reshape(n_samples, -1) -print "Dataset consists of %d faces" % n_samples +print("Dataset consists of %d faces" % n_samples) ############################################################################### -def plot_gallery(title, images): - pl.figure(figsize=(2. * n_col, 2.26 * n_row)) - pl.suptitle(title, size=16) +def plot_gallery(title, images, n_col=n_col, n_row=n_row): + plt.figure(figsize=(2. * n_col, 2.26 * n_row)) + plt.suptitle(title, size=16) for i, comp in enumerate(images): - pl.subplot(n_row, n_col, i + 1) + plt.subplot(n_row, n_col, i + 1) vmax = max(comp.max(), -comp.min()) - pl.imshow(comp.reshape(image_shape), cmap=pl.cm.gray, - interpolation='nearest', - vmin=-vmax, vmax=vmax) - pl.xticks(()) - pl.yticks(()) - pl.subplots_adjust(0.01, 0.05, 0.99, 0.93, 0.04, 0.) + plt.imshow(comp.reshape(image_shape), cmap=plt.cm.gray, + interpolation='nearest', + vmin=-vmax, vmax=vmax) + plt.xticks(()) + plt.yticks(()) + plt.subplots_adjust(0.01, 0.05, 0.99, 0.93, 0.04, 0.) ############################################################################### # List of the different estimators, whether to center and transpose the @@ -76,28 +76,32 @@ def plot_gallery(title, images): False), ('Independent components - FastICA', - decomposition.FastICA(n_components=n_components, whiten=True, - max_iter=10), + decomposition.FastICA(n_components=n_components, whiten=True), True), ('Sparse comp. - MiniBatchSparsePCA', decomposition.MiniBatchSparsePCA(n_components=n_components, alpha=0.8, - n_iter=100, chunk_size=3, + n_iter=100, batch_size=3, random_state=rng), True), ('MiniBatchDictionaryLearning', - decomposition.MiniBatchDictionaryLearning(n_atoms=15, alpha=0.1, - n_iter=50, chunk_size=3, - random_state=rng), + decomposition.MiniBatchDictionaryLearning(n_components=15, alpha=0.1, + n_iter=50, batch_size=3, + random_state=rng), True), ('Cluster centers - MiniBatchKMeans', - MiniBatchKMeans(n_clusters=n_components, tol=1e-3, batch_size=20, - max_iter=50, random_state=rng), - True) + MiniBatchKMeans(n_clusters=n_components, tol=1e-3, batch_size=20, + max_iter=50, random_state=rng), + True), + + ('Factor Analysis components - FA', + decomposition.FactorAnalysis(n_components=n_components, max_iter=2), + True), ] + ############################################################################### # Plot a sample of the input data @@ -107,19 +111,23 @@ def plot_gallery(title, images): # Do the estimation and plot it for name, estimator, center in estimators: - print "Extracting the top %d %s..." % (n_components, name) + print("Extracting the top %d %s..." % (n_components, name)) t0 = time() data = faces if center: data = faces_centered estimator.fit(data) train_time = (time() - t0) - print "done in %0.3fs" % train_time + print("done in %0.3fs" % train_time) if hasattr(estimator, 'cluster_centers_'): components_ = estimator.cluster_centers_ else: components_ = estimator.components_ + if hasattr(estimator, 'noise_variance_'): + plot_gallery("Pixelwise variance", + estimator.noise_variance_.reshape(1, -1), n_col=1, + n_row=1) plot_gallery('%s - Train time %.1fs' % (name, train_time), components_[:n_components]) -pl.show() +plt.show() diff --git a/examples/decomposition/plot_ica_blind_source_separation.py b/examples/decomposition/plot_ica_blind_source_separation.py index c864f6c180a56..9ba5a1523a3c6 100644 --- a/examples/decomposition/plot_ica_blind_source_separation.py +++ b/examples/decomposition/plot_ica_blind_source_separation.py @@ -3,49 +3,71 @@ Blind source separation using FastICA ===================================== +An example of estimating sources from noisy data. + :ref:`ICA` is used to estimate sources given noisy measurements. -Imagine 2 instruments playing simultaneously and 2 microphones +Imagine 3 instruments playing simultaneously and 3 microphones recording the mixed signals. ICA is used to recover the sources -ie. what is played by each instrument. +ie. what is played by each instrument. Importantly, PCA fails +at recovering our `instruments` since the related signals reflect +non-Gaussian processes. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl -from sklearn.decomposition import FastICA +import matplotlib.pyplot as plt +from scipy import signal + +from sklearn.decomposition import FastICA, PCA ############################################################################### # Generate sample data np.random.seed(0) n_samples = 2000 -time = np.linspace(0, 10, n_samples) +time = np.linspace(0, 8, n_samples) + s1 = np.sin(2 * time) # Signal 1 : sinusoidal signal s2 = np.sign(np.sin(3 * time)) # Signal 2 : square signal -S = np.c_[s1, s2] +s3 = signal.sawtooth(2 * np.pi * time) # Signal 3: saw tooth signal + +S = np.c_[s1, s2, s3] S += 0.2 * np.random.normal(size=S.shape) # Add noise S /= S.std(axis=0) # Standardize data # Mix data -A = np.array([[1, 1], [0.5, 2]]) # Mixing matrix +A = np.array([[1, 1, 1], [0.5, 2, 1.0], [1.5, 1.0, 2.0]]) # Mixing matrix X = np.dot(S, A.T) # Generate observations + # Compute ICA -ica = FastICA() -S_ = ica.fit(X).transform(X) # Get the estimated sources -A_ = ica.get_mixing_matrix() # Get estimated mixing matrix -assert np.allclose(X, np.dot(S_, A_.T)) +ica = FastICA(n_components=3) +S_ = ica.fit_transform(X) # Reconstruct signals +A_ = ica.mixing_ # Get estimated mixing matrix + +# We can `prove` that the ICA model applies by reverting the unmixing. +assert np.allclose(X, np.dot(S_, A_.T) + ica.mean_) + +# For comparison, compute PCA +pca = PCA(n_components=3) +H = pca.fit_transform(X) # Reconstruct signals based on orthogonal components ############################################################################### # Plot results -pl.figure() -pl.subplot(3, 1, 1) -pl.plot(S) -pl.title('True Sources') -pl.subplot(3, 1, 2) -pl.plot(X) -pl.title('Observations (mixed signal)') -pl.subplot(3, 1, 3) -pl.plot(S_) -pl.title('ICA estimated sources') -pl.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.36) -pl.show() + +plt.figure() + +models = [X, S, S_, H] +names = ['Observations (mixed signal)', + 'True Sources', + 'ICA recovered signals', + 'PCA recovered signals'] +colors = ['red', 'steelblue', 'orange'] + +for ii, (model, name) in enumerate(zip(models, names), 1): + plt.subplot(4, 1, ii) + plt.title(name) + for sig, color in zip(model.T, colors): + plt.plot(sig, color=color) + +plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.46) +plt.show() diff --git a/examples/decomposition/plot_ica_vs_pca.py b/examples/decomposition/plot_ica_vs_pca.py index 741ed06c043f7..b53230f3fdcf4 100644 --- a/examples/decomposition/plot_ica_vs_pca.py +++ b/examples/decomposition/plot_ica_vs_pca.py @@ -3,8 +3,10 @@ FastICA on 2D point clouds ========================== -Illustrate visually the results of :ref:`ICA` vs :ref:`PCA` in the -feature space. +This example illustrates visually in the feature space a comparison by +results using two different component analysis techniques. + +:ref:`ICA` vs :ref:`PCA`. Representing ICA in the feature space gives the view of 'geometric ICA': ICA is an algorithm that finds directions in the feature space @@ -20,18 +22,18 @@ process, 2 student T with a low number of degrees of freedom (top left figure). We mix them to create observations (top right figure). In this raw observation space, directions identified by PCA are -represented by green vectors. We represent the signal in the PCA space, +represented by orange vectors. We represent the signal in the PCA space, after whitening by the variance corresponding to the PCA vectors (lower left). Running ICA corresponds to finding a rotation in this space to identify the directions of largest non-Gaussianity (lower right). """ -print __doc__ +print(__doc__) # Authors: Alexandre Gramfort, Gael Varoquaux -# License: BSD +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.decomposition import PCA, FastICA @@ -59,43 +61,45 @@ # Plot results def plot_samples(S, axis_list=None): - pl.scatter(S[:, 0], S[:, 1], s=2, marker='o', linewidths=0, zorder=10) + plt.scatter(S[:, 0], S[:, 1], s=2, marker='o', linewidths=0, zorder=10, + color='steelblue', alpha=0.5) if axis_list is not None: - colors = [(0, 0.6, 0), (0.6, 0, 0)] + colors = ['orange', 'red'] for color, axis in zip(colors, axis_list): axis /= axis.std() x_axis, y_axis = axis # Trick to get legend to work - pl.plot(0.1 * x_axis, 0.1 * y_axis, linewidth=2, color=color) - # pl.quiver(x_axis, y_axis, x_axis, y_axis, zorder=11, width=0.01, - pl.quiver(0, 0, x_axis, y_axis, zorder=11, width=0.01, - scale=6, color=color) - - pl.hlines(0, -3, 3) - pl.vlines(0, -3, 3) - pl.xlim(-3, 3) - pl.ylim(-3, 3) - pl.xlabel('x') - pl.ylabel('y') - -pl.subplot(2, 2, 1) + plt.plot(0.1 * x_axis, 0.1 * y_axis, linewidth=2, color=color) + plt.quiver(0, 0, x_axis, y_axis, zorder=11, width=0.01, scale=6, + color=color) + + plt.hlines(0, -3, 3) + plt.vlines(0, -3, 3) + plt.xlim(-3, 3) + plt.ylim(-3, 3) + plt.xlabel('x') + plt.ylabel('y') + +plt.figure() +plt.subplot(2, 2, 1) plot_samples(S / S.std()) -pl.title('True Independent Sources') +plt.title('True Independent Sources') -axis_list = [pca.components_.T, ica.get_mixing_matrix()] -pl.subplot(2, 2, 2) +axis_list = [pca.components_.T, ica.mixing_] +plt.subplot(2, 2, 2) plot_samples(X / np.std(X), axis_list=axis_list) -pl.legend(['PCA', 'ICA'], loc='upper left') -pl.title('Observations') +legend = plt.legend(['PCA', 'ICA'], loc='upper right') +legend.set_zorder(100) + +plt.title('Observations') -pl.subplot(2, 2, 3) +plt.subplot(2, 2, 3) plot_samples(S_pca_ / np.std(S_pca_, axis=0)) -pl.title('PCA scores') +plt.title('PCA recovered signals') -pl.subplot(2, 2, 4) +plt.subplot(2, 2, 4) plot_samples(S_ica_ / np.std(S_ica_)) -pl.title('ICA estimated sources') - -pl.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.26) +plt.title('ICA recovered signals') -pl.show() +plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.36) +plt.show() diff --git a/examples/decomposition/plot_image_denoising.py b/examples/decomposition/plot_image_denoising.py index cd857598536e0..09bf83c006c5d 100644 --- a/examples/decomposition/plot_image_denoising.py +++ b/examples/decomposition/plot_image_denoising.py @@ -4,14 +4,18 @@ ========================================= An example comparing the effect of reconstructing noisy fragments -of Lena using online :ref:`DictionaryLearning` and various transform methods. +of the Lena image using firstly online :ref:`DictionaryLearning` and +various transform methods. -The dictionary is fitted on the non-distorted left half of the image, and -subsequently used to reconstruct the right half. +The dictionary is fitted on the distorted left half of the image, and +subsequently used to reconstruct the right half. Note that even better +performance could be achieved by fitting to an undistorted (i.e. +noiseless) image, but here we start from the assumption that it is not +available. A common practice for evaluating the results of image denoising is by looking at the difference between the reconstruction and the original image. If the -reconstruction is perfect this will look like gaussian noise. +reconstruction is perfect this will look like Gaussian noise. It can be seen from the plots that the results of :ref:`omp` with two non-zero coefficients is a bit less biased than when keeping only one @@ -27,11 +31,11 @@ necessarily related to visualisation. """ -print __doc__ +print(__doc__) from time import time -import pylab as pl +import matplotlib.pyplot as plt import numpy as np from scipy.misc import lena @@ -51,41 +55,41 @@ height, width = lena.shape # Distort the right half of the image -print 'Distorting image...' +print('Distorting image...') distorted = lena.copy() -distorted[:, height / 2:] += 0.075 * np.random.randn(width, height / 2) +distorted[:, height // 2:] += 0.075 * np.random.randn(width, height // 2) -# Extract all clean patches from the left half of the image -print 'Extracting clean patches...' +# Extract all reference patches from the left half of the image +print('Extracting reference patches...') t0 = time() patch_size = (7, 7) -data = extract_patches_2d(distorted[:, :height / 2], patch_size) +data = extract_patches_2d(distorted[:, :height // 2], patch_size) data = data.reshape(data.shape[0], -1) data -= np.mean(data, axis=0) data /= np.std(data, axis=0) -print 'done in %.2fs.' % (time() - t0) +print('done in %.2fs.' % (time() - t0)) ############################################################################### -# Learn the dictionary from clean patches +# Learn the dictionary from reference patches -print 'Learning the dictionary... ' +print('Learning the dictionary...') t0 = time() -dico = MiniBatchDictionaryLearning(n_atoms=100, alpha=1, n_iter=500) +dico = MiniBatchDictionaryLearning(n_components=100, alpha=1, n_iter=500) V = dico.fit(data).components_ dt = time() - t0 -print 'done in %.2fs.' % dt +print('done in %.2fs.' % dt) -pl.figure(figsize=(4.2, 4)) +plt.figure(figsize=(4.2, 4)) for i, comp in enumerate(V[:100]): - pl.subplot(10, 10, i + 1) - pl.imshow(comp.reshape(patch_size), cmap=pl.cm.gray_r, - interpolation='nearest') - pl.xticks(()) - pl.yticks(()) -pl.suptitle('Dictionary learned from Lena patches\n' + - 'Train time %.1fs on %d patches' % (dt, len(data)), - fontsize=16) -pl.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23) + plt.subplot(10, 10, i + 1) + plt.imshow(comp.reshape(patch_size), cmap=plt.cm.gray_r, + interpolation='nearest') + plt.xticks(()) + plt.yticks(()) +plt.suptitle('Dictionary learned from Lena patches\n' + + 'Train time %.1fs on %d patches' % (dt, len(data)), + fontsize=16) +plt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23) ############################################################################### @@ -93,35 +97,35 @@ def show_with_diff(image, reference, title): """Helper function to display denoising""" - pl.figure(figsize=(5, 3.3)) - pl.subplot(1, 2, 1) - pl.title('Image') - pl.imshow(image, vmin=0, vmax=1, cmap=pl.cm.gray, interpolation='nearest') - pl.xticks(()) - pl.yticks(()) - pl.subplot(1, 2, 2) + plt.figure(figsize=(5, 3.3)) + plt.subplot(1, 2, 1) + plt.title('Image') + plt.imshow(image, vmin=0, vmax=1, cmap=plt.cm.gray, interpolation='nearest') + plt.xticks(()) + plt.yticks(()) + plt.subplot(1, 2, 2) difference = image - reference - pl.title('Difference (norm: %.2f)' % np.sqrt(np.sum(difference ** 2))) - pl.imshow(difference, vmin=-0.5, vmax=0.5, cmap=pl.cm.PuOr, - interpolation='nearest') - pl.xticks(()) - pl.yticks(()) - pl.suptitle(title, size=16) - pl.subplots_adjust(0.02, 0.02, 0.98, 0.79, 0.02, 0.2) + plt.title('Difference (norm: %.2f)' % np.sqrt(np.sum(difference ** 2))) + plt.imshow(difference, vmin=-0.5, vmax=0.5, cmap=plt.cm.PuOr, + interpolation='nearest') + plt.xticks(()) + plt.yticks(()) + plt.suptitle(title, size=16) + plt.subplots_adjust(0.02, 0.02, 0.98, 0.79, 0.02, 0.2) show_with_diff(distorted, lena, 'Distorted image') ############################################################################### # Extract noisy patches and reconstruct them using the dictionary -print 'Extracting noisy patches... ' +print('Extracting noisy patches... ') t0 = time() -data = extract_patches_2d(distorted[:, height / 2:], patch_size) +data = extract_patches_2d(distorted[:, height // 2:], patch_size) data = data.reshape(data.shape[0], -1) intercept = np.mean(data, axis=0) data -= intercept -print 'done in %.2fs.' % (time() - t0) +print('done in %.2fs.' % (time() - t0)) transform_algorithms = [ ('Orthogonal Matching Pursuit\n1 atom', 'omp', @@ -129,12 +133,12 @@ def show_with_diff(image, reference, title): ('Orthogonal Matching Pursuit\n2 atoms', 'omp', {'transform_n_nonzero_coefs': 2}), ('Least-angle regression\n5 atoms', 'lars', - {'transform_n_nonzero_coefs': 5}), + {'transform_n_nonzero_coefs': 5}), ('Thresholding\n alpha=0.1', 'threshold', {'transform_alpha': .1})] reconstructions = {} for title, transform_algorithm, kwargs in transform_algorithms: - print title, '... ' + print(title + '...') reconstructions[title] = lena.copy() t0 = time() dico.set_params(transform_algorithm=transform_algorithm, **kwargs) @@ -150,11 +154,11 @@ def show_with_diff(image, reference, title): if transform_algorithm == 'threshold': patches -= patches.min() patches /= patches.max() - reconstructions[title][:, height / 2:] = reconstruct_from_patches_2d( - patches, (width, height / 2)) + reconstructions[title][:, height // 2:] = reconstruct_from_patches_2d( + patches, (width, height // 2)) dt = time() - t0 - print 'done in %.2fs.' % dt + print('done in %.2fs.' % dt) show_with_diff(reconstructions[title], lena, title + ' (time: %.1fs)' % dt) -pl.show() +plt.show() diff --git a/examples/decomposition/plot_incremental_pca.py b/examples/decomposition/plot_incremental_pca.py new file mode 100644 index 0000000000000..899ae6ce1cff0 --- /dev/null +++ b/examples/decomposition/plot_incremental_pca.py @@ -0,0 +1,58 @@ +""" + +=============== +Incremental PCA +=============== + +Incremental principal component analysis (IPCA) is typically used as a +replacement for principal component analysis (PCA) when the dataset to be +decomposed is too large to fit in memory. IPCA builds a low-rank approximation +for the input data using an amount of memory which is independent of the +number of input data samples. It is still dependent on the input data features, +but changing the batch size allows for control of memory usage. + +This example serves as a visual check that IPCA is able to find a similar +projection of the data to PCA (to a sign flip), while only processing a +few samples at a time. This can be considered a "toy example", as IPCA is +intended for large datasets which do not fit in main memory, requiring +incremental approaches. + +""" +print(__doc__) + +# Authors: Kyle Kastner +# License: BSD 3 clause + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.datasets import load_iris +from sklearn.decomposition import PCA, IncrementalPCA + +iris = load_iris() +X = iris.data +y = iris.target + +n_components = 2 +ipca = IncrementalPCA(n_components=n_components, batch_size=10) +X_ipca = ipca.fit_transform(X) + +pca = PCA(n_components=n_components) +X_pca = pca.fit_transform(X) + +for X_transformed, title in [(X_ipca, "Incremental PCA"), (X_pca, "PCA")]: + plt.figure(figsize=(8, 8)) + for c, i, target_name in zip("rgb", [0, 1, 2], iris.target_names): + plt.scatter(X_transformed[y == i, 0], X_transformed[y == i, 1], + c=c, label=target_name) + + if "Incremental" in title: + err = np.abs(np.abs(X_pca) - np.abs(X_ipca)).mean() + plt.title(title + " of iris dataset\nMean absolute unsigned error " + "%.6f" % err) + else: + plt.title(title + " of iris dataset") + plt.legend(loc="best") + plt.axis([-4, 4, -1.5, 1.5]) + +plt.show() diff --git a/examples/decomposition/plot_kernel_pca.py b/examples/decomposition/plot_kernel_pca.py index 202786302b3ba..070c489e9f970 100644 --- a/examples/decomposition/plot_kernel_pca.py +++ b/examples/decomposition/plot_kernel_pca.py @@ -6,14 +6,14 @@ This example shows that Kernel PCA is able to find a projection of the data that makes data linearly separable. """ -print __doc__ +print(__doc__) # Authors: Mathieu Blondel # Andreas Mueller -# License: BSD +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.decomposition import PCA, KernelPCA from sklearn.datasets import make_circles @@ -30,44 +30,44 @@ # Plot results -pl.figure() -pl.subplot(2, 2, 1, aspect='equal') -pl.title("Original space") +plt.figure() +plt.subplot(2, 2, 1, aspect='equal') +plt.title("Original space") reds = y == 0 blues = y == 1 -pl.plot(X[reds, 0], X[reds, 1], "ro") -pl.plot(X[blues, 0], X[blues, 1], "bo") -pl.xlabel("$x_1$") -pl.ylabel("$x_2$") +plt.plot(X[reds, 0], X[reds, 1], "ro") +plt.plot(X[blues, 0], X[blues, 1], "bo") +plt.xlabel("$x_1$") +plt.ylabel("$x_2$") X1, X2 = np.meshgrid(np.linspace(-1.5, 1.5, 50), np.linspace(-1.5, 1.5, 50)) X_grid = np.array([np.ravel(X1), np.ravel(X2)]).T # projection on the first principal component (in the phi space) Z_grid = kpca.transform(X_grid)[:, 0].reshape(X1.shape) -pl.contour(X1, X2, Z_grid, colors='grey', linewidths=1, origin='lower') - -pl.subplot(2, 2, 2, aspect='equal') -pl.plot(X_pca[reds, 0], X_pca[reds, 1], "ro") -pl.plot(X_pca[blues, 0], X_pca[blues, 1], "bo") -pl.title("Projection by PCA") -pl.xlabel("1st principal component") -pl.ylabel("2nd component") - -pl.subplot(2, 2, 3, aspect='equal') -pl.plot(X_kpca[reds, 0], X_kpca[reds, 1], "ro") -pl.plot(X_kpca[blues, 0], X_kpca[blues, 1], "bo") -pl.title("Projection by KPCA") -pl.xlabel("1st principal component in space induced by $\phi$") -pl.ylabel("2nd component") - -pl.subplot(2, 2, 4, aspect='equal') -pl.plot(X_back[reds, 0], X_back[reds, 1], "ro") -pl.plot(X_back[blues, 0], X_back[blues, 1], "bo") -pl.title("Original space after inverse transform") -pl.xlabel("$x_1$") -pl.ylabel("$x_2$") - -pl.subplots_adjust(0.02, 0.10, 0.98, 0.94, 0.04, 0.35) - -pl.show() +plt.contour(X1, X2, Z_grid, colors='grey', linewidths=1, origin='lower') + +plt.subplot(2, 2, 2, aspect='equal') +plt.plot(X_pca[reds, 0], X_pca[reds, 1], "ro") +plt.plot(X_pca[blues, 0], X_pca[blues, 1], "bo") +plt.title("Projection by PCA") +plt.xlabel("1st principal component") +plt.ylabel("2nd component") + +plt.subplot(2, 2, 3, aspect='equal') +plt.plot(X_kpca[reds, 0], X_kpca[reds, 1], "ro") +plt.plot(X_kpca[blues, 0], X_kpca[blues, 1], "bo") +plt.title("Projection by KPCA") +plt.xlabel("1st principal component in space induced by $\phi$") +plt.ylabel("2nd component") + +plt.subplot(2, 2, 4, aspect='equal') +plt.plot(X_back[reds, 0], X_back[reds, 1], "ro") +plt.plot(X_back[blues, 0], X_back[blues, 1], "bo") +plt.title("Original space after inverse transform") +plt.xlabel("$x_1$") +plt.ylabel("$x_2$") + +plt.subplots_adjust(0.02, 0.10, 0.98, 0.94, 0.04, 0.35) + +plt.show() diff --git a/examples/decomposition/plot_pca_3d.py b/examples/decomposition/plot_pca_3d.py index efe7e82fd71fd..f26d5d9d1c9bb 100644 --- a/examples/decomposition/plot_pca_3d.py +++ b/examples/decomposition/plot_pca_3d.py @@ -3,24 +3,31 @@ """ ========================================================= -Principal Component Analysis +Principal components analysis (PCA) ========================================================= -These figures aid in illustrating how a the point cloud -can be very flad in one direction - which is where PCA -would come in to choose a direction that is not flat. +These figures aid in illustrating how a point cloud +can be very flat in one direction--which is where PCA +comes in to choose a direction that is not flat. """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD +# Authors: Gael Varoquaux +# Jaques Grobler +# Kevin Hughes +# License: BSD 3 clause -import pylab as pl +from sklearn.decomposition import PCA + +from mpl_toolkits.mplot3d import Axes3D import numpy as np +import matplotlib.pyplot as plt from scipy import stats -from mpl_toolkits.mplot3d import Axes3D + + +############################################################################### +# Create the data e = np.exp(1) np.random.seed(4) @@ -28,7 +35,7 @@ def pdf(x): return 0.5 * (stats.norm(scale=0.25 / e).pdf(x) - + stats.norm(scale=4 / e).pdf(x)) + + stats.norm(scale=4 / e).pdf(x)) y = np.random.normal(scale=0.5, size=(30000)) x = np.random.normal(scale=0.5, size=(30000)) @@ -51,14 +58,21 @@ def pdf(x): ############################################################################### # Plot the figures def plot_figs(fig_num, elev, azim): - fig = pl.figure(fig_num, figsize=(4, 3)) - pl.clf() + fig = plt.figure(fig_num, figsize=(4, 3)) + plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=elev, azim=azim) - ax.scatter(a[::10], b[::10], c[::10], c=density, marker='+', - alpha=.4) + ax.scatter(a[::10], b[::10], c[::10], c=density[::10], marker='+', alpha=.4) Y = np.c_[a, b, c] - U, pca_score, V = np.linalg.svd(Y, full_matrices=False) + + # Using SciPy's SVD, this would be: + # _, pca_score, V = scipy.linalg.svd(Y, full_matrices=False) + + pca = PCA(n_components=3) + pca.fit(Y) + pca_score = pca.explained_variance_ratio_ + V = pca.components_ + x_pca_axis, y_pca_axis, z_pca_axis = V.T * pca_score / pca_score.min() x_pca_axis, y_pca_axis, z_pca_axis = 3 * V.T @@ -82,4 +96,4 @@ def plot_figs(fig_num, elev, azim): azim = 20 plot_figs(2, elev, azim) -pl.show() +plt.show() diff --git a/examples/decomposition/plot_pca_iris.py b/examples/decomposition/plot_pca_iris.py index e982b1c828036..98e9c966fb283 100644 --- a/examples/decomposition/plot_pca_iris.py +++ b/examples/decomposition/plot_pca_iris.py @@ -6,15 +6,20 @@ PCA example with Iris Data-set ========================================================= +Principal Component Analysis applied to the Iris dataset. + +See `here `_ for more +information on this dataset. + """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# License: BSD +# Code source: Gaël Varoquaux +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D @@ -28,11 +33,11 @@ X = iris.data y = iris.target -fig = pl.figure(1, figsize=(4, 3)) -pl.clf() +fig = plt.figure(1, figsize=(4, 3)) +plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) -pl.cla() +plt.cla() pca = decomposition.PCA(n_components=3) pca.fit(X) X = pca.transform(X) @@ -42,11 +47,10 @@ X[y == label, 1].mean() + 1.5, X[y == label, 2].mean(), name, horizontalalignment='center', - bbox=dict(alpha=.5, edgecolor='w', facecolor='w'), - ) + bbox=dict(alpha=.5, edgecolor='w', facecolor='w')) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(np.float) -ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=pl.cm.spectral) +ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=plt.cm.spectral) x_surf = [X[:, 0].min(), X[:, 0].max(), X[:, 0].min(), X[:, 0].max()] @@ -63,4 +67,4 @@ ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) -pl.show() +plt.show() diff --git a/examples/decomposition/plot_pca_vs_fa_model_selection.py b/examples/decomposition/plot_pca_vs_fa_model_selection.py new file mode 100755 index 0000000000000..ec01d91cb1407 --- /dev/null +++ b/examples/decomposition/plot_pca_vs_fa_model_selection.py @@ -0,0 +1,126 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +================================================================= +Model selection with Probabilistic (PCA) and Factor Analysis (FA) +================================================================= + +Probabilistic PCA and Factor Analysis are probabilistic models. +The consequence is that the likelihood of new data can be used +for model selection and covariance estimation. +Here we compare PCA and FA with cross-validation on low rank data corrupted +with homoscedastic noise (noise variance +is the same for each feature) or heteroscedastic noise (noise variance +is the different for each feature). In a second step we compare the model +likelihood to the likelihoods obtained from shrinkage covariance estimators. + +One can observe that with homoscedastic noise both FA and PCA succeed +in recovering the size of the low rank subspace. The likelihood with PCA +is higher than FA in this case. However PCA fails and overestimates +the rank when heteroscedastic noise is present. Under appropriate +circumstances the low rank models are more likely than shrinkage models. + +The automatic estimation from +Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604 +by Thomas P. Minka is also compared. + +""" +print(__doc__) + +# Authors: Alexandre Gramfort +# Denis A. Engemann +# License: BSD 3 clause + +import numpy as np +import matplotlib.pyplot as plt +from scipy import linalg + +from sklearn.decomposition import PCA, FactorAnalysis +from sklearn.covariance import ShrunkCovariance, LedoitWolf +from sklearn.cross_validation import cross_val_score +from sklearn.grid_search import GridSearchCV + +############################################################################### +# Create the data + +n_samples, n_features, rank = 1000, 50, 10 +sigma = 1. +rng = np.random.RandomState(42) +U, _, _ = linalg.svd(rng.randn(n_features, n_features)) +X = np.dot(rng.randn(n_samples, rank), U[:, :rank].T) + +# Adding homoscedastic noise +X_homo = X + sigma * rng.randn(n_samples, n_features) + +# Adding heteroscedastic noise +sigmas = sigma * rng.rand(n_features) + sigma / 2. +X_hetero = X + rng.randn(n_samples, n_features) * sigmas + +############################################################################### +# Fit the models + +n_components = np.arange(0, n_features, 5) # options for n_components + + +def compute_scores(X): + pca = PCA() + fa = FactorAnalysis() + + pca_scores, fa_scores = [], [] + for n in n_components: + pca.n_components = n + fa.n_components = n + pca_scores.append(np.mean(cross_val_score(pca, X))) + fa_scores.append(np.mean(cross_val_score(fa, X))) + + return pca_scores, fa_scores + + +def shrunk_cov_score(X): + shrinkages = np.logspace(-2, 0, 30) + cv = GridSearchCV(ShrunkCovariance(), {'shrinkage': shrinkages}) + return np.mean(cross_val_score(cv.fit(X).best_estimator_, X)) + + +def lw_score(X): + return np.mean(cross_val_score(LedoitWolf(), X)) + + +for X, title in [(X_homo, 'Homoscedastic Noise'), + (X_hetero, 'Heteroscedastic Noise')]: + pca_scores, fa_scores = compute_scores(X) + n_components_pca = n_components[np.argmax(pca_scores)] + n_components_fa = n_components[np.argmax(fa_scores)] + + pca = PCA(n_components='mle') + pca.fit(X) + n_components_pca_mle = pca.n_components_ + + print("best n_components by PCA CV = %d" % n_components_pca) + print("best n_components by FactorAnalysis CV = %d" % n_components_fa) + print("best n_components by PCA MLE = %d" % n_components_pca_mle) + + plt.figure() + plt.plot(n_components, pca_scores, 'b', label='PCA scores') + plt.plot(n_components, fa_scores, 'r', label='FA scores') + plt.axvline(rank, color='g', label='TRUTH: %d' % rank, linestyle='-') + plt.axvline(n_components_pca, color='b', + label='PCA CV: %d' % n_components_pca, linestyle='--') + plt.axvline(n_components_fa, color='r', + label='FactorAnalysis CV: %d' % n_components_fa, linestyle='--') + plt.axvline(n_components_pca_mle, color='k', + label='PCA MLE: %d' % n_components_pca_mle, linestyle='--') + + # compare with other covariance estimators + plt.axhline(shrunk_cov_score(X), color='violet', + label='Shrunk Covariance MLE', linestyle='-.') + plt.axhline(lw_score(X), color='orange', + label='LedoitWolf MLE' % n_components_pca_mle, linestyle='-.') + + plt.xlabel('nb of components') + plt.ylabel('CV scores') + plt.legend(loc='lower right') + plt.title(title) + +plt.show() diff --git a/examples/decomposition/plot_pca_vs_lda.py b/examples/decomposition/plot_pca_vs_lda.py index 963bb47e958b5..b51683535aba3 100644 --- a/examples/decomposition/plot_pca_vs_lda.py +++ b/examples/decomposition/plot_pca_vs_lda.py @@ -14,11 +14,11 @@ Linear Discriminant Analysis (LDA) tries to identify attributes that account for the most variance *between classes*. In particular, -LDA, in constrast to PCA, is a supervised method, using known class labels. +LDA, in contrast to PCA, is a supervised method, using known class labels. """ -print __doc__ +print(__doc__) -import pylab as pl +import matplotlib.pyplot as plt from sklearn import datasets from sklearn.decomposition import PCA @@ -37,19 +37,19 @@ X_r2 = lda.fit(X, y).transform(X) # Percentage of variance explained for each components -print 'explained variance ratio (first two components):', \ - pca.explained_variance_ratio_ +print('explained variance ratio (first two components): %s' + % str(pca.explained_variance_ratio_)) -pl.figure() +plt.figure() for c, i, target_name in zip("rgb", [0, 1, 2], target_names): - pl.scatter(X_r[y == i, 0], X_r[y == i, 1], c=c, label=target_name) -pl.legend() -pl.title('PCA of IRIS dataset') + plt.scatter(X_r[y == i, 0], X_r[y == i, 1], c=c, label=target_name) +plt.legend() +plt.title('PCA of IRIS dataset') -pl.figure() +plt.figure() for c, i, target_name in zip("rgb", [0, 1, 2], target_names): - pl.scatter(X_r2[y == i, 0], X_r2[y == i, 1], c=c, label=target_name) -pl.legend() -pl.title('LDA of IRIS dataset') + plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], c=c, label=target_name) +plt.legend() +plt.title('LDA of IRIS dataset') -pl.show() +plt.show() diff --git a/examples/decomposition/plot_sparse_coding.py b/examples/decomposition/plot_sparse_coding.py index 9f8c3c10832d9..e0e0fe1a73624 100644 --- a/examples/decomposition/plot_sparse_coding.py +++ b/examples/decomposition/plot_sparse_coding.py @@ -6,7 +6,7 @@ Transform a signal as a sparse combination of Ricker wavelets. This example visually compares different sparse coding methods using the :class:`sklearn.decomposition.SparseCoder` estimator. The Ricker (also known -as mexican hat or the second derivative of a gaussian) is not a particularily +as Mexican hat or the second derivative of a Gaussian) is not a particularly good kernel to represent piecewise constant signals like this one. It can therefore be seen how much adding different widths of atoms matters and it therefore motivates learning the dictionary to best fit your type of signals. @@ -14,7 +14,7 @@ The richer dictionary on the right is not larger in size, heavier subsampling is performed in order to stay on the same order of magnitude. """ -print __doc__ +print(__doc__) import numpy as np import matplotlib.pylab as pl @@ -23,18 +23,18 @@ def ricker_function(resolution, center, width): - """Discrete sub-sampled Ricker (mexican hat) wavelet""" + """Discrete sub-sampled Ricker (Mexican hat) wavelet""" x = np.linspace(0, resolution - 1, resolution) - x = (2 / ((np.sqrt(3 * width) * np.pi ** 1 / 4))) * ( - 1 - ((x - center) ** 2 / width ** 2)) * np.exp( - (-(x - center) ** 2) / (2 * width ** 2)) + x = ((2 / ((np.sqrt(3 * width) * np.pi ** 1 / 4))) + * (1 - ((x - center) ** 2 / width ** 2)) + * np.exp((-(x - center) ** 2) / (2 * width ** 2))) return x -def ricker_matrix(width, resolution, n_atoms): - """Dictionary of Ricker (mexican hat) wavelets""" - centers = np.linspace(0, resolution - 1, n_atoms) - D = np.empty((n_atoms, resolution)) +def ricker_matrix(width, resolution, n_components): + """Dictionary of Ricker (Mexican hat) wavelets""" + centers = np.linspace(0, resolution - 1, n_components) + D = np.empty((n_components, resolution)) for i, center in enumerate(centers): D[i] = ricker_function(resolution, center, width) D /= np.sqrt(np.sum(D ** 2, axis=1))[:, np.newaxis] @@ -44,13 +44,14 @@ def ricker_matrix(width, resolution, n_atoms): resolution = 1024 subsampling = 3 # subsampling factor width = 100 -n_atoms = resolution / subsampling +n_components = resolution / subsampling # Compute a wavelet dictionary -D_fixed = ricker_matrix(width=width, resolution=resolution, n_atoms=n_atoms) +D_fixed = ricker_matrix(width=width, resolution=resolution, + n_components=n_components) D_multi = np.r_[tuple(ricker_matrix(width=w, resolution=resolution, - n_atoms=np.floor(n_atoms / 5)) - for w in (10, 50, 100, 500, 1000))] + n_components=np.floor(n_components / 5)) + for w in (10, 50, 100, 500, 1000))] # Generate a signal y = np.linspace(0, resolution - 1, resolution) @@ -60,9 +61,7 @@ def ricker_matrix(width, resolution, n_atoms): # List the different sparse coding methods in the following format: # (title, transform_algorithm, transform_alpha, transform_n_nozero_coefs) -estimators = [('OMP', 'omp', None, 15), - ('Lasso', 'lasso_cd', 2, None), -] +estimators = [('OMP', 'omp', None, 15), ('Lasso', 'lasso_cd', 2, None), ] pl.figure(figsize=(13, 6)) for subplot, (D, title) in enumerate(zip((D_fixed, D_multi), @@ -78,8 +77,8 @@ def ricker_matrix(width, resolution, n_atoms): density = len(np.flatnonzero(x)) x = np.ravel(np.dot(x, D)) squared_error = np.sum((y - x) ** 2) - pl.plot(x, label='%s: %s nonzero coefs,\n%.2f error' % - (title, density, squared_error)) + pl.plot(x, label='%s: %s nonzero coefs,\n%.2f error' + % (title, density, squared_error)) # Soft thresholding debiasing coder = SparseCoder(dictionary=D, transform_algorithm='threshold', diff --git a/examples/document_classification_20newsgroups.py b/examples/document_classification_20newsgroups.py deleted file mode 100644 index b0f483dd35ce7..0000000000000 --- a/examples/document_classification_20newsgroups.py +++ /dev/null @@ -1,270 +0,0 @@ -""" -====================================================== -Classification of text documents using sparse features -====================================================== - -This is an example showing how scikit-learn can be used to classify documents -by topics using a bag-of-words approach. This example uses a scipy.sparse -matrix to store the features and demonstrates various classifiers that can -efficiently handle sparse matrices. - -The dataset used in this example is the 20 newsgroups dataset. It will be -automatically downloaded, then cached. - -The bar plot indicates the accuracy, training time (normalized) and test time -(normalized) of each classifier. - -""" - -# Author: Peter Prettenhofer -# Olivier Grisel -# Mathieu Blondel -# Lars Buitinck -# License: Simplified BSD - -import logging -import numpy as np -from optparse import OptionParser -import sys -from time import time -import pylab as pl - -from sklearn.datasets import fetch_20newsgroups -from sklearn.feature_extraction.text import TfidfVectorizer -from sklearn.feature_selection import SelectKBest, chi2 -from sklearn.linear_model import RidgeClassifier -from sklearn.svm import LinearSVC -from sklearn.linear_model import SGDClassifier -from sklearn.linear_model import Perceptron -from sklearn.naive_bayes import BernoulliNB, MultinomialNB -from sklearn.neighbors import KNeighborsClassifier -from sklearn.neighbors import NearestCentroid -from sklearn.utils.extmath import density -from sklearn import metrics - - -# Display progress logs on stdout -logging.basicConfig(level=logging.INFO, - format='%(asctime)s %(levelname)s %(message)s') - - -# parse commandline arguments -op = OptionParser() -op.add_option("--report", - action="http://github.com/store_true", dest="print_report", - help="Print a detailed classification report.") -op.add_option("--chi2_select", - action="http://github.com/store", type="int", dest="select_chi2", - help="Select some number of features using a chi-squared test") -op.add_option("--confusion_matrix", - action="http://github.com/store_true", dest="print_cm", - help="Print the confusion matrix.") -op.add_option("--top10", - action="http://github.com/store_true", dest="print_top10", - help="Print ten most discriminative terms per class" - " for every classifier.") -op.add_option("--all_categories", - action="http://github.com/store_true", dest="all_categories", - help="Whether to use all categories or not.") - -(opts, args) = op.parse_args() -if len(args) > 0: - op.error("this script takes no arguments.") - sys.exit(1) - -print __doc__ -op.print_help() -print - - -############################################################################### -# Load some categories from the training set -if opts.all_categories: - categories = None -else: - categories = [ - 'alt.atheism', - 'talk.religion.misc', - 'comp.graphics', - 'sci.space', - ] - -print "Loading 20 newsgroups dataset for categories:" -print categories if categories else "all" - -data_train = fetch_20newsgroups(subset='train', categories=categories, - shuffle=True, random_state=42) - -data_test = fetch_20newsgroups(subset='test', categories=categories, - shuffle=True, random_state=42) -print 'data loaded' - -categories = data_train.target_names # for case categories == None - -print "%d documents (training set)" % len(data_train.data) -print "%d documents (testing set)" % len(data_test.data) -print "%d categories" % len(categories) -print - -# split a training set and a test set -y_train, y_test = data_train.target, data_test.target - -print "Extracting features from the training dataset using a sparse vectorizer" -t0 = time() -vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, - stop_words='english') -X_train = vectorizer.fit_transform(data_train.data) -print "done in %fs" % (time() - t0) -print "n_samples: %d, n_features: %d" % X_train.shape -print - -print "Extracting features from the test dataset using the same vectorizer" -t0 = time() -X_test = vectorizer.transform(data_test.data) -print "done in %fs" % (time() - t0) -print "n_samples: %d, n_features: %d" % X_test.shape -print - -if opts.select_chi2: - print ("Extracting %d best features by a chi-squared test" % - opts.select_chi2) - t0 = time() - ch2 = SelectKBest(chi2, k=opts.select_chi2) - X_train = ch2.fit_transform(X_train, y_train) - X_test = ch2.transform(X_test) - print "done in %fs" % (time() - t0) - print - - -def trim(s): - """Trim string to fit on terminal (assuming 80-column display)""" - return s if len(s) <= 80 else s[:77] + "..." - - -# mapping from integer feature name to original token string -feature_names = np.asarray(vectorizer.get_feature_names()) - - -############################################################################### -# Benchmark classifiers -def benchmark(clf): - print 80 * '_' - print "Training: " - print clf - t0 = time() - clf.fit(X_train, y_train) - train_time = time() - t0 - print "train time: %0.3fs" % train_time - - t0 = time() - pred = clf.predict(X_test) - test_time = time() - t0 - print "test time: %0.3fs" % test_time - - score = metrics.f1_score(y_test, pred) - print "f1-score: %0.3f" % score - - if hasattr(clf, 'coef_'): - print "dimensionality: %d" % clf.coef_.shape[1] - print "density: %f" % density(clf.coef_) - - if opts.print_top10: - print "top 10 keywords per class:" - for i, category in enumerate(categories): - top10 = np.argsort(clf.coef_[i])[-10:] - print trim("%s: %s" % ( - category, " ".join(feature_names[top10]))) - print - - if opts.print_report: - print "classification report:" - print metrics.classification_report(y_test, pred, - target_names=categories) - - if opts.print_cm: - print "confusion matrix:" - print metrics.confusion_matrix(y_test, pred) - - print - clf_descr = str(clf).split('(')[0] - return clf_descr, score, train_time, test_time - - -results = [] -for clf, name in ((RidgeClassifier(tol=1e-1), "Ridge Classifier"), - (Perceptron(n_iter=50), "Perceptron"), - (KNeighborsClassifier(n_neighbors=10), "kNN")): - print 80 * '=' - print name - results.append(benchmark(clf)) - -for penalty in ["l2", "l1"]: - print 80 * '=' - print "%s penalty" % penalty.upper() - # Train Liblinear model - results.append(benchmark(LinearSVC(loss='l2', penalty=penalty, - dual=False, tol=1e-3))) - - # Train SGD model - results.append(benchmark(SGDClassifier(alpha=.0001, n_iter=50, - penalty=penalty))) - -# Train SGD with Elastic Net penalty -print 80 * '=' -print "Elastic-Net penalty" -results.append(benchmark(SGDClassifier(alpha=.0001, n_iter=50, - penalty="elasticnet"))) - -# Train NearestCentroid without threshold -print 80 * '=' -print "NearestCentroid (aka Rocchio classifier)" -results.append(benchmark(NearestCentroid())) - -# Train sparse Naive Bayes classifiers -print 80 * '=' -print "Naive Bayes" -results.append(benchmark(MultinomialNB(alpha=.01))) -results.append(benchmark(BernoulliNB(alpha=.01))) - - -class L1LinearSVC(LinearSVC): - - def fit(self, X, y): - # The smaller C, the stronger the regularization. - # The more regularization, the more sparsity. - self.transformer_ = LinearSVC(penalty="l1", - dual=False, tol=1e-3) - X = self.transformer_.fit_transform(X, y) - return LinearSVC.fit(self, X, y) - - def predict(self, X): - X = self.transformer_.transform(X) - return LinearSVC.predict(self, X) - -print 80 * '=' -print "LinearSVC with L1-based feature selection" -results.append(benchmark(L1LinearSVC())) - - -# make some plots - -indices = np.arange(len(results)) - -results = [[x[i] for x in results] for i in xrange(4)] - -clf_names, score, training_time, test_time = results -training_time = np.array(training_time) / np.max(training_time) -test_time = np.array(test_time) / np.max(test_time) - -pl.title("Score") -pl.barh(indices, score, .2, label="score", color='r') -pl.barh(indices + .3, training_time, .2, label="training time", color='g') -pl.barh(indices + .6, test_time, .2, label="test time", color='b') -pl.yticks(()) -pl.legend(loc='best') -pl.subplots_adjust(left=.25) - -for i, c in zip(indices, clf_names): - pl.text(-.3, i, c) - -pl.show() diff --git a/examples/document_clustering.py b/examples/document_clustering.py deleted file mode 100644 index ddb68d1763dc9..0000000000000 --- a/examples/document_clustering.py +++ /dev/null @@ -1,112 +0,0 @@ -""" -======================================= -Clustering text documents using k-means -======================================= - -This is an example showing how the scikit-learn can be used to cluster -documents by topics using a bag-of-words approach. This example uses -a scipy.sparse matrix to store the features instead of standard numpy arrays. - -Two algorithms are demoed: ordinary k-means and its faster cousin minibatch -k-means. - -""" - -# Author: Peter Prettenhofer -# Lars Buitinck -# License: Simplified BSD - -from sklearn.datasets import fetch_20newsgroups -from sklearn.feature_extraction.text import TfidfVectorizer -from sklearn import metrics - -from sklearn.cluster import KMeans, MiniBatchKMeans - -import logging -from optparse import OptionParser -import sys -from time import time - -import numpy as np - - -# Display progress logs on stdout -logging.basicConfig(level=logging.INFO, - format='%(asctime)s %(levelname)s %(message)s') - -# parse commandline arguments -op = OptionParser() -op.add_option("--no-minibatch", - action="http://github.com/store_false", dest="minibatch", default=True, - help="Use ordinary k-means algorithm.") - -print __doc__ -op.print_help() - -(opts, args) = op.parse_args() -if len(args) > 0: - op.error("this script takes no arguments.") - sys.exit(1) - - -############################################################################### -# Load some categories from the training set -categories = [ - 'alt.atheism', - 'talk.religion.misc', - 'comp.graphics', - 'sci.space', -] -# Uncomment the following to do the analysis on all the categories -#categories = None - -print "Loading 20 newsgroups dataset for categories:" -print categories - -dataset = fetch_20newsgroups(subset='all', categories=categories, - shuffle=True, random_state=42) - -print "%d documents" % len(dataset.data) -print "%d categories" % len(dataset.target_names) -print - -labels = dataset.target -true_k = np.unique(labels).shape[0] - -print "Extracting features from the training dataset using a sparse vectorizer" -t0 = time() -vectorizer = TfidfVectorizer(max_df=0.5, max_features=10000, - stop_words='english') -X = vectorizer.fit_transform(dataset.data) - -print "done in %fs" % (time() - t0) -print "n_samples: %d, n_features: %d" % X.shape -print - - -############################################################################### -# Do the actual clustering - -if opts.minibatch: - km = MiniBatchKMeans(n_clusters=true_k, init='k-means++', n_init=1, - init_size=1000, - batch_size=1000, verbose=1) -else: - km = KMeans(n_clusters=true_k, init='random', max_iter=100, n_init=1, - verbose=1) - -print "Clustering sparse data with %s" % km -t0 = time() -km.fit(X) -print "done in %0.3fs" % (time() - t0) -print - -print "Homogeneity: %0.3f" % metrics.homogeneity_score(labels, km.labels_) -print "Completeness: %0.3f" % metrics.completeness_score(labels, km.labels_) -print "V-measure: %0.3f" % metrics.v_measure_score(labels, km.labels_) -print "Adjusted Rand-Index: %.3f" % \ - metrics.adjusted_rand_score(labels, km.labels_) -print "Silhouette Coefficient: %0.3f" % metrics.silhouette_score( - X, labels, sample_size=1000) - -print diff --git a/examples/ensemble/README.txt b/examples/ensemble/README.txt index 086d323985b0f..267211b5bbf67 100644 --- a/examples/ensemble/README.txt +++ b/examples/ensemble/README.txt @@ -3,4 +3,4 @@ Ensemble methods ---------------- -Examples concerning the :mod:`sklearn.ensemble` package. +Examples concerning the :mod:`sklearn.ensemble` module. diff --git a/examples/ensemble/plot_adaboost_hastie_10_2.py b/examples/ensemble/plot_adaboost_hastie_10_2.py new file mode 100644 index 0000000000000..b27636956ef26 --- /dev/null +++ b/examples/ensemble/plot_adaboost_hastie_10_2.py @@ -0,0 +1,112 @@ +""" +============================= +Discrete versus Real AdaBoost +============================= + +This example is based on Figure 10.2 from Hastie et al 2009 [1] and illustrates +the difference in performance between the discrete SAMME [2] boosting +algorithm and real SAMME.R boosting algorithm. Both algorithms are evaluated +on a binary classification task where the target Y is a non-linear function +of 10 input features. + +Discrete SAMME AdaBoost adapts based on errors in predicted class labels +whereas real SAMME.R uses the predicted class probabilities. + +.. [1] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical + Learning Ed. 2", Springer, 2009. + +.. [2] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009. + +""" +print(__doc__) + +# Author: Peter Prettenhofer , +# Noel Dawe +# +# License: BSD 3 clause + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn import datasets +from sklearn.tree import DecisionTreeClassifier +from sklearn.metrics import zero_one_loss +from sklearn.ensemble import AdaBoostClassifier + + +n_estimators = 400 +# A learning rate of 1. may not be optimal for both SAMME and SAMME.R +learning_rate = 1. + +X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1) + +X_test, y_test = X[2000:], y[2000:] +X_train, y_train = X[:2000], y[:2000] + +dt_stump = DecisionTreeClassifier(max_depth=1, min_samples_leaf=1) +dt_stump.fit(X_train, y_train) +dt_stump_err = 1.0 - dt_stump.score(X_test, y_test) + +dt = DecisionTreeClassifier(max_depth=9, min_samples_leaf=1) +dt.fit(X_train, y_train) +dt_err = 1.0 - dt.score(X_test, y_test) + +ada_discrete = AdaBoostClassifier( + base_estimator=dt_stump, + learning_rate=learning_rate, + n_estimators=n_estimators, + algorithm="SAMME") +ada_discrete.fit(X_train, y_train) + +ada_real = AdaBoostClassifier( + base_estimator=dt_stump, + learning_rate=learning_rate, + n_estimators=n_estimators, + algorithm="SAMME.R") +ada_real.fit(X_train, y_train) + +fig = plt.figure() +ax = fig.add_subplot(111) + +ax.plot([1, n_estimators], [dt_stump_err] * 2, 'k-', + label='Decision Stump Error') +ax.plot([1, n_estimators], [dt_err] * 2, 'k--', + label='Decision Tree Error') + +ada_discrete_err = np.zeros((n_estimators,)) +for i, y_pred in enumerate(ada_discrete.staged_predict(X_test)): + ada_discrete_err[i] = zero_one_loss(y_pred, y_test) + +ada_discrete_err_train = np.zeros((n_estimators,)) +for i, y_pred in enumerate(ada_discrete.staged_predict(X_train)): + ada_discrete_err_train[i] = zero_one_loss(y_pred, y_train) + +ada_real_err = np.zeros((n_estimators,)) +for i, y_pred in enumerate(ada_real.staged_predict(X_test)): + ada_real_err[i] = zero_one_loss(y_pred, y_test) + +ada_real_err_train = np.zeros((n_estimators,)) +for i, y_pred in enumerate(ada_real.staged_predict(X_train)): + ada_real_err_train[i] = zero_one_loss(y_pred, y_train) + +ax.plot(np.arange(n_estimators) + 1, ada_discrete_err, + label='Discrete AdaBoost Test Error', + color='red') +ax.plot(np.arange(n_estimators) + 1, ada_discrete_err_train, + label='Discrete AdaBoost Train Error', + color='blue') +ax.plot(np.arange(n_estimators) + 1, ada_real_err, + label='Real AdaBoost Test Error', + color='orange') +ax.plot(np.arange(n_estimators) + 1, ada_real_err_train, + label='Real AdaBoost Train Error', + color='green') + +ax.set_ylim((0.0, 0.5)) +ax.set_xlabel('n_estimators') +ax.set_ylabel('error rate') + +leg = ax.legend(loc='upper right', fancybox=True) +leg.get_frame().set_alpha(0.7) + +plt.show() diff --git a/examples/ensemble/plot_adaboost_multiclass.py b/examples/ensemble/plot_adaboost_multiclass.py new file mode 100644 index 0000000000000..39e7cdcb8ef4d --- /dev/null +++ b/examples/ensemble/plot_adaboost_multiclass.py @@ -0,0 +1,120 @@ +""" +===================================== +Multi-class AdaBoosted Decision Trees +===================================== + +This example reproduces Figure 1 of Zhu et al [1] and shows how boosting can +improve prediction accuracy on a multi-class problem. The classification +dataset is constructed by taking a ten-dimensional standard normal distribution +and defining three classes separated by nested concentric ten-dimensional +spheres such that roughly equal numbers of samples are in each class (quantiles +of the :math:`\chi^2` distribution). + +The performance of the SAMME and SAMME.R [1] algorithms are compared. SAMME.R +uses the probability estimates to update the additive model, while SAMME uses +the classifications only. As the example illustrates, the SAMME.R algorithm +typically converges faster than SAMME, achieving a lower test error with fewer +boosting iterations. The error of each algorithm on the test set after each +boosting iteration is shown on the left, the classification error on the test +set of each tree is shown in the middle, and the boost weight of each tree is +shown on the right. All trees have a weight of one in the SAMME.R algorithm and +therefore are not shown. + +.. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009. + +""" +print(__doc__) + +# Author: Noel Dawe +# +# License: BSD 3 clause + +from sklearn.externals.six.moves import zip + +import matplotlib.pyplot as plt + +from sklearn.datasets import make_gaussian_quantiles +from sklearn.ensemble import AdaBoostClassifier +from sklearn.metrics import accuracy_score +from sklearn.tree import DecisionTreeClassifier + + +X, y = make_gaussian_quantiles(n_samples=13000, n_features=10, + n_classes=3, random_state=1) + +n_split = 3000 + +X_train, X_test = X[:n_split], X[n_split:] +y_train, y_test = y[:n_split], y[n_split:] + +bdt_real = AdaBoostClassifier( + DecisionTreeClassifier(max_depth=2), + n_estimators=600, + learning_rate=1) + +bdt_discrete = AdaBoostClassifier( + DecisionTreeClassifier(max_depth=2), + n_estimators=600, + learning_rate=1.5, + algorithm="SAMME") + +bdt_real.fit(X_train, y_train) +bdt_discrete.fit(X_train, y_train) + +real_test_errors = [] +discrete_test_errors = [] + +for real_test_predict, discrete_train_predict in zip( + bdt_real.staged_predict(X_test), bdt_discrete.staged_predict(X_test)): + real_test_errors.append( + 1. - accuracy_score(real_test_predict, y_test)) + discrete_test_errors.append( + 1. - accuracy_score(discrete_train_predict, y_test)) + +n_trees_discrete = len(bdt_discrete) +n_trees_real = len(bdt_real) + +# Boosting might terminate early, but the following arrays are always +# n_estimators long. We crop them to the actual number of trees here: +discrete_estimator_errors = bdt_discrete.estimator_errors_[:n_trees_discrete] +real_estimator_errors = bdt_real.estimator_errors_[:n_trees_real] +discrete_estimator_weights = bdt_discrete.estimator_weights_[:n_trees_discrete] + +plt.figure(figsize=(15, 5)) + +plt.subplot(131) +plt.plot(range(1, n_trees_discrete + 1), + discrete_test_errors, c='black', label='SAMME') +plt.plot(range(1, n_trees_real + 1), + real_test_errors, c='black', + linestyle='dashed', label='SAMME.R') +plt.legend() +plt.ylim(0.18, 0.62) +plt.ylabel('Test Error') +plt.xlabel('Number of Trees') + +plt.subplot(132) +plt.plot(range(1, n_trees_discrete + 1), discrete_estimator_errors, + "b", label='SAMME', alpha=.5) +plt.plot(range(1, n_trees_real + 1), real_estimator_errors, + "r", label='SAMME.R', alpha=.5) +plt.legend() +plt.ylabel('Error') +plt.xlabel('Number of Trees') +plt.ylim((.2, + max(real_estimator_errors.max(), + discrete_estimator_errors.max()) * 1.2)) +plt.xlim((-20, len(bdt_discrete) + 20)) + +plt.subplot(133) +plt.plot(range(1, n_trees_discrete + 1), discrete_estimator_weights, + "b", label='SAMME') +plt.legend() +plt.ylabel('Weight') +plt.xlabel('Number of Trees') +plt.ylim((0, discrete_estimator_weights.max() * 1.2)) +plt.xlim((-20, n_trees_discrete + 20)) + +# prevent overlapping y-axis labels +plt.subplots_adjust(wspace=0.25) +plt.show() diff --git a/examples/ensemble/plot_adaboost_regression.py b/examples/ensemble/plot_adaboost_regression.py new file mode 100644 index 0000000000000..3b0149e07df34 --- /dev/null +++ b/examples/ensemble/plot_adaboost_regression.py @@ -0,0 +1,54 @@ +""" +====================================== +Decision Tree Regression with AdaBoost +====================================== + +A decision tree is boosted using the AdaBoost.R2 [1] algorithm on a 1D +sinusoidal dataset with a small amount of Gaussian noise. +299 boosts (300 decision trees) is compared with a single decision tree +regressor. As the number of boosts is increased the regressor can fit more +detail. + +.. [1] H. Drucker, "Improving Regressors using Boosting Techniques", 1997. + +""" +print(__doc__) + +# Author: Noel Dawe +# +# License: BSD 3 clause + +# importing necessary libraries +import numpy as np +import matplotlib.pyplot as plt +from sklearn.tree import DecisionTreeRegressor +from sklearn.ensemble import AdaBoostRegressor + +# Create the dataset +rng = np.random.RandomState(1) +X = np.linspace(0, 6, 100)[:, np.newaxis] +y = np.sin(X).ravel() + np.sin(6 * X).ravel() + rng.normal(0, 0.1, X.shape[0]) + +# Fit regression model +clf_1 = DecisionTreeRegressor(max_depth=4) + +clf_2 = AdaBoostRegressor(DecisionTreeRegressor(max_depth=4), + n_estimators=300, random_state=rng) + +clf_1.fit(X, y) +clf_2.fit(X, y) + +# Predict +y_1 = clf_1.predict(X) +y_2 = clf_2.predict(X) + +# Plot the results +plt.figure() +plt.scatter(X, y, c="k", label="training samples") +plt.plot(X, y_1, c="g", label="n_estimators=1", linewidth=2) +plt.plot(X, y_2, c="r", label="n_estimators=300", linewidth=2) +plt.xlabel("data") +plt.ylabel("target") +plt.title("Boosted Decision Tree Regression") +plt.legend() +plt.show() diff --git a/examples/ensemble/plot_adaboost_twoclass.py b/examples/ensemble/plot_adaboost_twoclass.py new file mode 100644 index 0000000000000..b20d71eb6e0c1 --- /dev/null +++ b/examples/ensemble/plot_adaboost_twoclass.py @@ -0,0 +1,101 @@ +""" +================== +Two-class AdaBoost +================== + +This example fits an AdaBoosted decision stump on a non-linearly separable +classification dataset composed of two "Gaussian quantiles" clusters +(see :func:`sklearn.datasets.make_gaussian_quantiles`) and plots the decision +boundary and decision scores. The distributions of decision scores are shown +separately for samples of class A and B. The predicted class label for each +sample is determined by the sign of the decision score. Samples with decision +scores greater than zero are classified as B, and are otherwise classified +as A. The magnitude of a decision score determines the degree of likeness with +the predicted class label. Additionally, a new dataset could be constructed +containing a desired purity of class B, for example, by only selecting samples +with a decision score above some value. + +""" +print(__doc__) + +# Author: Noel Dawe +# +# License: BSD 3 clause + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.ensemble import AdaBoostClassifier +from sklearn.tree import DecisionTreeClassifier +from sklearn.datasets import make_gaussian_quantiles + + +# Construct dataset +X1, y1 = make_gaussian_quantiles(cov=2., + n_samples=200, n_features=2, + n_classes=2, random_state=1) +X2, y2 = make_gaussian_quantiles(mean=(3, 3), cov=1.5, + n_samples=300, n_features=2, + n_classes=2, random_state=1) +X = np.concatenate((X1, X2)) +y = np.concatenate((y1, - y2 + 1)) + +# Create and fit an AdaBoosted decision tree +bdt = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1), + algorithm="SAMME", + n_estimators=200) + +bdt.fit(X, y) + +plot_colors = "br" +plot_step = 0.02 +class_names = "AB" + +plt.figure(figsize=(10, 5)) + +# Plot the decision boundaries +plt.subplot(121) +x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 +y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 +xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step), + np.arange(y_min, y_max, plot_step)) + +Z = bdt.predict(np.c_[xx.ravel(), yy.ravel()]) +Z = Z.reshape(xx.shape) +cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired) +plt.axis("tight") + +# Plot the training points +for i, n, c in zip(range(2), class_names, plot_colors): + idx = np.where(y == i) + plt.scatter(X[idx, 0], X[idx, 1], + c=c, cmap=plt.cm.Paired, + label="Class %s" % n) +plt.xlim(x_min, x_max) +plt.ylim(y_min, y_max) +plt.legend(loc='upper right') +plt.xlabel('x') +plt.ylabel('y') +plt.title('Decision Boundary') + +# Plot the two-class decision scores +twoclass_output = bdt.decision_function(X) +plot_range = (twoclass_output.min(), twoclass_output.max()) +plt.subplot(122) +for i, n, c in zip(range(2), class_names, plot_colors): + plt.hist(twoclass_output[y == i], + bins=10, + range=plot_range, + facecolor=c, + label='Class %s' % n, + alpha=.5) +x1, x2, y1, y2 = plt.axis() +plt.axis((x1, x2, y1, y2 * 1.2)) +plt.legend(loc='upper right') +plt.ylabel('Samples') +plt.xlabel('Score') +plt.title('Decision Scores') + +plt.tight_layout() +plt.subplots_adjust(wspace=0.35) +plt.show() diff --git a/examples/ensemble/plot_bias_variance.py b/examples/ensemble/plot_bias_variance.py new file mode 100644 index 0000000000000..8d88f99df1668 --- /dev/null +++ b/examples/ensemble/plot_bias_variance.py @@ -0,0 +1,184 @@ +""" +============================================================ +Single estimator versus bagging: bias-variance decomposition +============================================================ + +This example illustrates and compares the bias-variance decomposition of the +expected mean squared error of a single estimator against a bagging ensemble. + +In regression, the expected mean squared error of an estimator can be +decomposed in terms of bias, variance and noise. On average over datasets of +the regression problem, the bias term measures the average amount by which the +predictions of the estimator differ from the predictions of the best possible +estimator for the problem (i.e., the Bayes model). The variance term measures +the variability of the predictions of the estimator when fit over different +instances LS of the problem. Finally, the noise measures the irreducible part +of the error which is due the variability in the data. + +The upper left figure illustrates the predictions (in dark red) of a single +decision tree trained over a random dataset LS (the blue dots) of a toy 1d +regression problem. It also illustrates the predictions (in light red) of other +single decision trees trained over other (and different) randomly drawn +instances LS of the problem. Intuitively, the variance term here corresponds to +the width of the beam of predictions (in light red) of the individual +estimators. The larger the variance, the more sensitive are the predictions for +`x` to small changes in the training set. The bias term corresponds to the +difference between the average prediction of the estimator (in cyan) and the +best possible model (in dark blue). On this problem, we can thus observe that +the bias is quite low (both the cyan and the blue curves are close to each +other) while the variance is large (the red beam is rather wide). + +The lower left figure plots the pointwise decomposition of the expected mean +squared error of a single decision tree. It confirms that the bias term (in +blue) is low while the variance is large (in green). It also illustrates the +noise part of the error which, as expected, appears to be constant and around +`0.01`. + +The right figures correspond to the same plots but using instead a bagging +ensemble of decision trees. In both figures, we can observe that the bias term +is larger than in the previous case. In the upper right figure, the difference +between the average prediction (in cyan) and the best possible model is larger +(e.g., notice the offset around `x=2`). In the lower right figure, the bias +curve is also slightly higher than in the lower left figure. In terms of +variance however, the beam of predictions is narrower, which suggests that the +variance is lower. Indeed, as the lower right figure confirms, the variance +term (in green) is lower than for single decision trees. Overall, the bias- +variance decomposition is therefore no longer the same. The tradeoff is better +for bagging: averaging several decision trees fit on bootstrap copies of the +dataset slightly increases the bias term but allows for a larger reduction of +the variance, which results in a lower overall mean squared error (compare the +red curves int the lower figures). The script output also confirms this +intuition. The total error of the bagging ensemble is lower than the total +error of a single decision tree, and this difference indeed mainly stems from a +reduced variance. + +For further details on bias-variance decomposition, see section 7.3 of [1]_. + +References +---------- + +.. [1] T. Hastie, R. Tibshirani and J. Friedman, + "Elements of Statistical Learning", Springer, 2009. + +""" +print(__doc__) + +# Author: Gilles Louppe +# License: BSD 3 clause + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.ensemble import BaggingRegressor +from sklearn.tree import DecisionTreeRegressor + +# Settings +n_repeat = 50 # Number of iterations for computing expectations +n_train = 50 # Size of the training set +n_test = 1000 # Size of the test set +noise = 0.1 # Standard deviation of the noise +np.random.seed(0) + +# Change this for exploring the bias-variance decomposition of other +# estimators. This should work well for estimators with high variance (e.g., +# decision trees or KNN), but poorly for estimators with low variance (e.g., +# linear models). +estimators = [("Tree", DecisionTreeRegressor()), + ("Bagging(Tree)", BaggingRegressor(DecisionTreeRegressor()))] + +n_estimators = len(estimators) + +# Generate data +def f(x): + x = x.ravel() + + return np.exp(-x ** 2) + 1.5 * np.exp(-(x - 2) ** 2) + +def generate(n_samples, noise, n_repeat=1): + X = np.random.rand(n_samples) * 10 - 5 + X = np.sort(X) + + if n_repeat == 1: + y = f(X) + np.random.normal(0.0, noise, n_samples) + else: + y = np.zeros((n_samples, n_repeat)) + + for i in range(n_repeat): + y[:, i] = f(X) + np.random.normal(0.0, noise, n_samples) + + X = X.reshape((n_samples, 1)) + + return X, y + +X_train = [] +y_train = [] + +for i in range(n_repeat): + X, y = generate(n_samples=n_train, noise=noise) + X_train.append(X) + y_train.append(y) + +X_test, y_test = generate(n_samples=n_test, noise=noise, n_repeat=n_repeat) + +# Loop over estimators to compare +for n, (name, estimator) in enumerate(estimators): + # Compute predictions + y_predict = np.zeros((n_test, n_repeat)) + + for i in range(n_repeat): + estimator.fit(X_train[i], y_train[i]) + y_predict[:, i] = estimator.predict(X_test) + + # Bias^2 + Variance + Noise decomposition of the mean squared error + y_error = np.zeros(n_test) + + for i in range(n_repeat): + for j in range(n_repeat): + y_error += (y_test[:, j] - y_predict[:, i]) ** 2 + + y_error /= (n_repeat * n_repeat) + + y_noise = np.var(y_test, axis=1) + y_bias = (f(X_test) - np.mean(y_predict, axis=1)) ** 2 + y_var = np.var(y_predict, axis=1) + + print("{0}: {1:.4f} (error) = {2:.4f} (bias^2) " + " + {3:.4f} (var) + {4:.4f} (noise)".format(name, + np.mean(y_error), + np.mean(y_bias), + np.mean(y_var), + np.mean(y_noise))) + + # Plot figures + plt.subplot(2, n_estimators, n + 1) + plt.plot(X_test, f(X_test), "b", label="$f(x)$") + plt.plot(X_train[0], y_train[0], ".b", label="LS ~ $y = f(x)+noise$") + + for i in range(n_repeat): + if i == 0: + plt.plot(X_test, y_predict[:, i], "r", label="$\^y(x)$") + else: + plt.plot(X_test, y_predict[:, i], "r", alpha=0.05) + + plt.plot(X_test, np.mean(y_predict, axis=1), "c", + label="$\mathbb{E}_{LS} \^y(x)$") + + plt.xlim([-5, 5]) + plt.title(name) + + if n == 0: + plt.legend(loc="upper left", prop={"size": 11}) + + plt.subplot(2, n_estimators, n_estimators + n + 1) + plt.plot(X_test, y_error, "r", label="$error(x)$") + plt.plot(X_test, y_bias, "b", label="$bias^2(x)$"), + plt.plot(X_test, y_var, "g", label="$variance(x)$"), + plt.plot(X_test, y_noise, "c", label="$noise(x)$") + + plt.xlim([-5, 5]) + plt.ylim([0, 0.1]) + + if n == 0: + plt.legend(loc="upper left", prop={"size": 11}) + +plt.show() diff --git a/examples/ensemble/plot_forest_importances.py b/examples/ensemble/plot_forest_importances.py index 7f5bbff577a83..7c84cf716d369 100644 --- a/examples/ensemble/plot_forest_importances.py +++ b/examples/ensemble/plot_forest_importances.py @@ -4,15 +4,16 @@ ========================================= This examples shows the use of forests of trees to evaluate the importance of -features on an artifical classification task. The red bars are the feature +features on an artificial classification task. The red bars are the feature importances of the forest, along with their inter-trees variability. As expected, the plot suggests that 3 features are informative, while the remaining are not. """ -print __doc__ +print(__doc__) import numpy as np +import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.ensemble import ExtraTreesClassifier @@ -29,7 +30,6 @@ # Build a forest and compute the feature importances forest = ExtraTreesClassifier(n_estimators=250, - compute_importances=True, random_state=0) forest.fit(X, y) @@ -39,17 +39,16 @@ indices = np.argsort(importances)[::-1] # Print the feature ranking -print "Feature ranking:" +print("Feature ranking:") -for f in xrange(10): - print "%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]) +for f in range(10): + print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]])) # Plot the feature importances of the forest -import pylab as pl -pl.figure() -pl.title("Feature importances") -pl.bar(xrange(10), importances[indices], +plt.figure() +plt.title("Feature importances") +plt.bar(range(10), importances[indices], color="r", yerr=std[indices], align="center") -pl.xticks(xrange(10), indices) -pl.xlim([-1, 10]) -pl.show() +plt.xticks(range(10), indices) +plt.xlim([-1, 10]) +plt.show() diff --git a/examples/ensemble/plot_forest_importances_faces.py b/examples/ensemble/plot_forest_importances_faces.py index 60ebaec1bb8fe..6b6fdbb797bfa 100644 --- a/examples/ensemble/plot_forest_importances_faces.py +++ b/examples/ensemble/plot_forest_importances_faces.py @@ -10,10 +10,10 @@ The code below also illustrates how the construction and the computation of the predictions can be parallelized within multiple jobs. """ -print __doc__ +print(__doc__) from time import time -import pylab as pl +import matplotlib.pyplot as plt from sklearn.datasets import fetch_olivetti_faces from sklearn.ensemble import ExtraTreesClassifier @@ -31,20 +31,19 @@ y = y[mask] # Build a forest and compute the pixel importances -print "Fitting ExtraTreesClassifier on faces data with %d cores..." % n_jobs +print("Fitting ExtraTreesClassifier on faces data with %d cores..." % n_jobs) t0 = time() forest = ExtraTreesClassifier(n_estimators=1000, max_features=128, - compute_importances=True, n_jobs=n_jobs, random_state=0) forest.fit(X, y) -print "done in %0.3fs" % (time() - t0) +print("done in %0.3fs" % (time() - t0)) importances = forest.feature_importances_ importances = importances.reshape(data.images[0].shape) # Plot pixel importances -pl.matshow(importances, cmap=pl.cm.hot) -pl.title("Pixel importances with forests of trees") -pl.show() +plt.matshow(importances, cmap=plt.cm.hot) +plt.title("Pixel importances with forests of trees") +plt.show() diff --git a/examples/ensemble/plot_forest_iris.py b/examples/ensemble/plot_forest_iris.py index 99185e9b518be..96efdab2d05a3 100644 --- a/examples/ensemble/plot_forest_iris.py +++ b/examples/ensemble/plot_forest_iris.py @@ -7,45 +7,78 @@ features of the iris dataset. This plot compares the decision surfaces learned by a decision tree classifier -(first column), by a random forest classifier (second column) and by an extra- -trees classifier (third column). +(first column), by a random forest classifier (second column), by an extra- +trees classifier (third column) and by an AdaBoost classifier (fourth column). In the first row, the classifiers are built using the sepal width and the sepal length features only, on the second row using the petal length and sepal length only, and on the third row using the petal width and the petal length only. + +In descending order of quality, when trained (outside of this example) on all +4 features using 30 estimators and scored using 10 fold cross validation, we see:: + + ExtraTreesClassifier() # 0.95 score + RandomForestClassifier() # 0.94 score + AdaBoost(DecisionTree(max_depth=3)) # 0.94 score + DecisionTree(max_depth=None) # 0.94 score + +Increasing `max_depth` for AdaBoost lowers the standard deviation of the scores (but +the average score does not improve). + +See the console's output for further details about each model. + +In this example you might try to: + +1) vary the ``max_depth`` for the ``DecisionTreeClassifier`` and + ``AdaBoostClassifier``, perhaps try ``max_depth=3`` for the + ``DecisionTreeClassifier`` or ``max_depth=None`` for ``AdaBoostClassifier`` +2) vary ``n_estimators`` + +It is worth noting that RandomForests and ExtraTrees can be fitted in parallel +on many cores as each tree is built independently of the others. AdaBoost's +samples are built sequentially and so do not use multiple cores. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import clone from sklearn.datasets import load_iris -from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier +from sklearn.ensemble import (RandomForestClassifier, ExtraTreesClassifier, + AdaBoostClassifier) +from sklearn.externals.six.moves import xrange from sklearn.tree import DecisionTreeClassifier # Parameters n_classes = 3 n_estimators = 30 -plot_colors = "bry" -plot_step = 0.02 +plot_colors = "ryb" +cmap = plt.cm.RdYlBu +plot_step = 0.02 # fine step width for decision surface contours +plot_step_coarser = 0.5 # step widths for coarse classifier guesses +RANDOM_SEED = 13 # fix the seed on each iteration # Load data iris = load_iris() plot_idx = 1 +models = [DecisionTreeClassifier(max_depth=None), + RandomForestClassifier(n_estimators=n_estimators), + ExtraTreesClassifier(n_estimators=n_estimators), + AdaBoostClassifier(DecisionTreeClassifier(max_depth=3), + n_estimators=n_estimators)] + for pair in ([0, 1], [0, 2], [2, 3]): - for model in (DecisionTreeClassifier(), - RandomForestClassifier(n_estimators=n_estimators), - ExtraTreesClassifier(n_estimators=n_estimators)): - # We only take the two corresponding features + for model in models: + # We only take the two corresponding features X = iris.data[:, pair] y = iris.target # Shuffle idx = np.arange(X.shape[0]) - np.random.seed(13) + np.random.seed(RANDOM_SEED) np.random.shuffle(idx) X = X[idx] y = y[idx] @@ -59,36 +92,61 @@ clf = clone(model) clf = model.fit(X, y) - # Plot the decision boundary - pl.subplot(3, 3, plot_idx) - + scores = clf.score(X, y) + # Create a title for each column and the console by using str() and + # slicing away useless parts of the string + model_title = str(type(model)).split(".")[-1][:-2][:-len("Classifier")] + model_details = model_title + if hasattr(model, "estimators_"): + model_details += " with {} estimators".format(len(model.estimators_)) + print( model_details + " with features", pair, "has a score of", scores ) + + plt.subplot(3, 4, plot_idx) + if plot_idx <= len(models): + # Add a title at the top of each column + plt.title(model_title) + + # Now plot the decision boundary using a fine mesh as input to a + # filled contour plot x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step), np.arange(y_min, y_max, plot_step)) + # Plot either a single DecisionTreeClassifier or alpha blend the + # decision surfaces of the ensemble of classifiers if isinstance(model, DecisionTreeClassifier): Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) - cs = pl.contourf(xx, yy, Z, cmap=pl.cm.Paired) + cs = plt.contourf(xx, yy, Z, cmap=cmap) else: + # Choose alpha blend level with respect to the number of estimators + # that are in use (noting that AdaBoost can use fewer estimators + # than its maximum if it achieves a good enough fit early on) + estimator_alpha = 1.0 / len(model.estimators_) for tree in model.estimators_: Z = tree.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) - cs = pl.contourf(xx, yy, Z, alpha=0.1, cmap=pl.cm.Paired) - - pl.axis("tight") - - # Plot the training points + cs = plt.contourf(xx, yy, Z, alpha=estimator_alpha, cmap=cmap) + + # Build a coarser grid to plot a set of ensemble classifications + # to show how these are different to what we see in the decision + # surfaces. These points are regularly space and do not have a black outline + xx_coarser, yy_coarser = np.meshgrid(np.arange(x_min, x_max, plot_step_coarser), + np.arange(y_min, y_max, plot_step_coarser)) + Z_points_coarser = model.predict(np.c_[xx_coarser.ravel(), yy_coarser.ravel()]).reshape(xx_coarser.shape) + cs_points = plt.scatter(xx_coarser, yy_coarser, s=15, c=Z_points_coarser, cmap=cmap, edgecolors="none") + + # Plot the training points, these are clustered together and have a + # black outline for i, c in zip(xrange(n_classes), plot_colors): idx = np.where(y == i) - pl.scatter(X[idx, 0], X[idx, 1], c=c, label=iris.target_names[i], - cmap=pl.cm.Paired) + plt.scatter(X[idx, 0], X[idx, 1], c=c, label=iris.target_names[i], + cmap=cmap) - pl.axis("tight") + plot_idx += 1 # move on to the next plot in sequence - plot_idx += 1 +plt.suptitle("Classifiers on feature subsets of the Iris dataset") +plt.axis("tight") -pl.suptitle("Decision surfaces of a decision tree, of a random forest, and of " - "an extra-trees classifier") -pl.show() +plt.show() diff --git a/examples/ensemble/plot_forest_multioutput.py b/examples/ensemble/plot_forest_multioutput.py deleted file mode 100644 index e7eb0d63e192f..0000000000000 --- a/examples/ensemble/plot_forest_multioutput.py +++ /dev/null @@ -1,69 +0,0 @@ -""" -========================================= -Face completion with multi-output forests -========================================= - -This example shows the use of multi-output forests to complete images. -The goal is to predict the lower half of a face given its upper half. - -The first row of images shows true faces. The second half illustrates -how the forest completes the lower half of those faces. - -""" -print __doc__ - -import numpy as np -import pylab as pl - -from sklearn.datasets import fetch_olivetti_faces -from sklearn.ensemble import ExtraTreesRegressor - - -# Load the faces datasets -data = fetch_olivetti_faces() -targets = data.target - -data = data.images.reshape((len(data.images), -1)) -train = data[targets < 30] -test = data[targets >= 30] # Test on independent people -n_pixels = data.shape[1] - -X_train = train[:, :int(0.5 * n_pixels)] # Upper half of the faces -Y_train = train[:, int(0.5 * n_pixels):] # Lower half of the faces -X_test = test[:, :int(0.5 * n_pixels)] -Y_test = test[:, int(0.5 * n_pixels):] - -# Build a multi-output forest -forest = ExtraTreesRegressor(n_estimators=10, - max_features=32, - random_state=0) - -forest.fit(X_train, Y_train) -Y_test_predict = forest.predict(X_test) - -# Plot the completed faces -n_faces = 5 -image_shape = (64, 64) - -pl.figure(figsize=(2. * n_faces, 2.26 * 2)) -pl.suptitle("Face completion with multi-output forests", size=16) - -for i in xrange(1, 1 + n_faces): - face_id = np.random.randint(X_test.shape[0]) - - true_face = np.hstack((X_test[face_id], Y_test[face_id])) - completed_face = np.hstack((X_test[face_id], Y_test_predict[face_id])) - - pl.subplot(2, n_faces, i) - pl.axis("off") - pl.imshow(true_face.reshape(image_shape), - cmap=pl.cm.gray, - interpolation="nearest") - - pl.subplot(2, n_faces, n_faces + i) - pl.axis("off") - pl.imshow(completed_face.reshape(image_shape), - cmap=pl.cm.gray, - interpolation="nearest") - -pl.show() diff --git a/examples/ensemble/plot_gradient_boosting_oob.py b/examples/ensemble/plot_gradient_boosting_oob.py new file mode 100644 index 0000000000000..a39f709d36979 --- /dev/null +++ b/examples/ensemble/plot_gradient_boosting_oob.py @@ -0,0 +1,136 @@ +""" +====================================== +Gradient Boosting Out-of-Bag estimates +====================================== + +Out-of-bag (OOB) estimates can be a useful heuristic to estimate +the "optimal" number of boosting iterations. +OOB estimates are almost identical to cross-validation estimates but +they can be computed on-the-fly without the need for repeated model +fitting. +OOB estimates are only available for Stochastic Gradient Boosting +(i.e. ``subsample < 1.0``), the estimates are derived from the improvement +in loss based on the examples not included in the bootstrap sample +(the so-called out-of-bag examples). +The OOB estimator is a pessimistic estimator of the true +test loss, but remains a fairly good approximation for a small number of trees. + +The figure shows the cumulative sum of the negative OOB improvements +as a function of the boosting iteration. As you can see, it tracks the test +loss for the first hundred iterations but then diverges in a +pessimistic way. +The figure also shows the performance of 3-fold cross validation which +usually gives a better estimate of the test loss +but is computationally more demanding. +""" +print(__doc__) + +# Author: Peter Prettenhofer +# +# License: BSD 3 clause + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn import ensemble +from sklearn.cross_validation import KFold +from sklearn.cross_validation import train_test_split + + +# Generate data (adapted from G. Ridgeway's gbm example) +n_samples = 1000 +random_state = np.random.RandomState(13) +x1 = random_state.uniform(size=n_samples) +x2 = random_state.uniform(size=n_samples) +x3 = random_state.randint(0, 4, size=n_samples) + +p = 1 / (1.0 + np.exp(-(np.sin(3 * x1) - 4 * x2 + x3))) +y = random_state.binomial(1, p, size=n_samples) + +X = np.c_[x1, x2, x3] + +X = X.astype(np.float32) +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, + random_state=9) + +# Fit classifier with out-of-bag estimates +params = {'n_estimators': 1200, 'max_depth': 3, 'subsample': 0.5, + 'learning_rate': 0.01, 'min_samples_leaf': 1, 'random_state': 3} +clf = ensemble.GradientBoostingClassifier(**params) + +clf.fit(X_train, y_train) +acc = clf.score(X_test, y_test) +print("Accuracy: {:.4f}".format(acc)) + +n_estimators = params['n_estimators'] +x = np.arange(n_estimators) + 1 + + +def heldout_score(clf, X_test, y_test): + """compute deviance scores on ``X_test`` and ``y_test``. """ + score = np.zeros((n_estimators,), dtype=np.float64) + for i, y_pred in enumerate(clf.staged_decision_function(X_test)): + score[i] = clf.loss_(y_test, y_pred) + return score + + +def cv_estimate(n_folds=3): + cv = KFold(n=X_train.shape[0], n_folds=n_folds) + cv_clf = ensemble.GradientBoostingClassifier(**params) + val_scores = np.zeros((n_estimators,), dtype=np.float64) + for train, test in cv: + cv_clf.fit(X_train[train], y_train[train]) + val_scores += heldout_score(cv_clf, X_train[test], y_train[test]) + val_scores /= n_folds + return val_scores + + +# Estimate best n_estimator using cross-validation +cv_score = cv_estimate(3) + +# Compute best n_estimator for test data +test_score = heldout_score(clf, X_test, y_test) + +# negative cumulative sum of oob improvements +cumsum = -np.cumsum(clf.oob_improvement_) + +# min loss according to OOB +oob_best_iter = x[np.argmin(cumsum)] + +# min loss according to test (normalize such that first loss is 0) +test_score -= test_score[0] +test_best_iter = x[np.argmin(test_score)] + +# min loss according to cv (normalize such that first loss is 0) +cv_score -= cv_score[0] +cv_best_iter = x[np.argmin(cv_score)] + +# color brew for the three curves +oob_color = list(map(lambda x: x / 256.0, (190, 174, 212))) +test_color = list(map(lambda x: x / 256.0, (127, 201, 127))) +cv_color = list(map(lambda x: x / 256.0, (253, 192, 134))) + +# plot curves and vertical lines for best iterations +plt.plot(x, cumsum, label='OOB loss', color=oob_color) +plt.plot(x, test_score, label='Test loss', color=test_color) +plt.plot(x, cv_score, label='CV loss', color=cv_color) +plt.axvline(x=oob_best_iter, color=oob_color) +plt.axvline(x=test_best_iter, color=test_color) +plt.axvline(x=cv_best_iter, color=cv_color) + +# add three vertical lines to xticks +xticks = plt.xticks() +xticks_pos = np.array(xticks[0].tolist() + + [oob_best_iter, cv_best_iter, test_best_iter]) +xticks_label = np.array(list(map(lambda t: int(t), xticks[0])) + + ['OOB', 'CV', 'Test']) +ind = np.argsort(xticks_pos) +xticks_pos = xticks_pos[ind] +xticks_label = xticks_label[ind] +plt.xticks(xticks_pos, xticks_label) + +plt.legend(loc='upper right') +plt.ylabel('normalized loss') +plt.xlabel('number of iterations') + +plt.show() diff --git a/examples/ensemble/plot_gradient_boosting_quantile.py b/examples/ensemble/plot_gradient_boosting_quantile.py index e1f6be6420d2d..6fb2731a513ec 100644 --- a/examples/ensemble/plot_gradient_boosting_quantile.py +++ b/examples/ensemble/plot_gradient_boosting_quantile.py @@ -8,9 +8,9 @@ """ import numpy as np -import pylab as pl -from sklearn.ensemble import GradientBoostingRegressor +import matplotlib.pyplot as plt +from sklearn.ensemble import GradientBoostingRegressor np.random.seed(1) @@ -41,7 +41,7 @@ def f(x): clf = GradientBoostingRegressor(loss='quantile', alpha=alpha, n_estimators=250, max_depth=3, - learn_rate=.1, min_samples_leaf=9, + learning_rate=.1, min_samples_leaf=9, min_samples_split=9) clf.fit(X, y) @@ -61,19 +61,19 @@ def f(x): # Make the prediction on the meshed x-axis y_pred = clf.predict(xx) -# Plot the function, the prediction and the 95% confidence interval based on +# Plot the function, the prediction and the 90% confidence interval based on # the MSE -fig = pl.figure() -pl.plot(xx, f(xx), 'g:', label=u'$f(x) = x\,\sin(x)$') -pl.plot(X, y, 'b.', markersize=10, label=u'Observations') -pl.plot(xx, y_pred, 'r-', label=u'Prediction') -pl.plot(xx, y_upper, 'k-') -pl.plot(xx, y_lower, 'k-') -pl.fill(np.concatenate([xx, xx[::-1]]), - np.concatenate([y_upper, y_lower[::-1]]), - alpha=.5, fc='b', ec='None', label='95% prediction interval') -pl.xlabel('$x$') -pl.ylabel('$f(x)$') -pl.ylim(-10, 20) -pl.legend(loc='upper left') -pl.show() +fig = plt.figure() +plt.plot(xx, f(xx), 'g:', label=u'$f(x) = x\,\sin(x)$') +plt.plot(X, y, 'b.', markersize=10, label=u'Observations') +plt.plot(xx, y_pred, 'r-', label=u'Prediction') +plt.plot(xx, y_upper, 'k-') +plt.plot(xx, y_lower, 'k-') +plt.fill(np.concatenate([xx, xx[::-1]]), + np.concatenate([y_upper, y_lower[::-1]]), + alpha=.5, fc='b', ec='None', label='90% prediction interval') +plt.xlabel('$x$') +plt.ylabel('$f(x)$') +plt.ylim(-10, 20) +plt.legend(loc='upper left') +plt.show() diff --git a/examples/ensemble/plot_gradient_boosting_regression.py b/examples/ensemble/plot_gradient_boosting_regression.py index 5f7469cf3bfb9..f9eff53611f63 100644 --- a/examples/ensemble/plot_gradient_boosting_regression.py +++ b/examples/ensemble/plot_gradient_boosting_regression.py @@ -3,19 +3,20 @@ Gradient Boosting regression ============================ -Demonstrate Gradient Boosting on the boston housing dataset. +Demonstrate Gradient Boosting on the Boston housing dataset. This example fits a Gradient Boosting model with least squares loss and 500 regression trees of depth 4. """ -print __doc__ +print(__doc__) # Author: Peter Prettenhofer # -# License: BSD +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt + from sklearn import ensemble from sklearn import datasets from sklearn.utils import shuffle @@ -33,7 +34,7 @@ ############################################################################### # Fit regression model params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 1, - 'learn_rate': 0.01, 'loss': 'ls'} + 'learning_rate': 0.01, 'loss': 'ls'} clf = ensemble.GradientBoostingRegressor(**params) clf.fit(X_train, y_train) @@ -49,16 +50,16 @@ for i, y_pred in enumerate(clf.staged_decision_function(X_test)): test_score[i] = clf.loss_(y_test, y_pred) -pl.figure(figsize=(12, 6)) -pl.subplot(1, 2, 1) -pl.title('Deviance') -pl.plot(np.arange(params['n_estimators']) + 1, clf.train_score_, 'b-', - label='Training Set Deviance') -pl.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-', - label='Test Set Deviance') -pl.legend(loc='upper right') -pl.xlabel('Boosting Iterations') -pl.ylabel('Deviance') +plt.figure(figsize=(12, 6)) +plt.subplot(1, 2, 1) +plt.title('Deviance') +plt.plot(np.arange(params['n_estimators']) + 1, clf.train_score_, 'b-', + label='Training Set Deviance') +plt.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-', + label='Test Set Deviance') +plt.legend(loc='upper right') +plt.xlabel('Boosting Iterations') +plt.ylabel('Deviance') ############################################################################### # Plot feature importance @@ -67,9 +68,9 @@ feature_importance = 100.0 * (feature_importance / feature_importance.max()) sorted_idx = np.argsort(feature_importance) pos = np.arange(sorted_idx.shape[0]) + .5 -pl.subplot(1, 2, 2) -pl.barh(pos, feature_importance[sorted_idx], align='center') -pl.yticks(pos, boston.feature_names[sorted_idx]) -pl.xlabel('Relative Importance') -pl.title('Variable Importance') -pl.show() +plt.subplot(1, 2, 2) +plt.barh(pos, feature_importance[sorted_idx], align='center') +plt.yticks(pos, boston.feature_names[sorted_idx]) +plt.xlabel('Relative Importance') +plt.title('Variable Importance') +plt.show() diff --git a/examples/ensemble/plot_gradient_boosting_regularization.py b/examples/ensemble/plot_gradient_boosting_regularization.py index 496767eddfc31..e5a01240ccdb0 100644 --- a/examples/ensemble/plot_gradient_boosting_regularization.py +++ b/examples/ensemble/plot_gradient_boosting_regularization.py @@ -7,7 +7,7 @@ for Gradient Boosting. The example is taken from Hastie et al 2009. The loss function used is binomial deviance. Regularization via -shrinkage (``learn_rate < 1.0``) improves performance considerably. +shrinkage (``learning_rate < 1.0``) improves performance considerably. In combination with shrinkage, stochastic gradient boosting (``subsample < 1.0``) can produce more accurate models by reducing the variance via bagging. @@ -19,14 +19,15 @@ .. [1] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical Learning Ed. 2", Springer, 2009. """ -print __doc__ +print(__doc__) # Author: Peter Prettenhofer # -# License: BSD +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt + from sklearn import ensemble from sklearn import datasets @@ -34,24 +35,27 @@ X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1) X = X.astype(np.float32) +# map labels from {-1, 1} to {0, 1} +labels, y = np.unique(y, return_inverse=True) + X_train, X_test = X[:2000], X[2000:] y_train, y_test = y[:2000], y[2000:] -original_params = {'n_estimators': 1000, 'max_depth': 2, 'random_state': 1, +original_params = {'n_estimators': 1000, 'max_leaf_nodes': 4, 'max_depth': None, 'random_state': 2, 'min_samples_split': 5} -pl.figure() +plt.figure() for label, color, setting in [('No shrinkage', 'orange', - {'learn_rate': 1.0, 'subsample': 1.0}), - ('learn_rate=0.1', 'turquoise', - {'learn_rate': 0.1, 'subsample': 1.0}), + {'learning_rate': 1.0, 'subsample': 1.0}), + ('learning_rate=0.1', 'turquoise', + {'learning_rate': 0.1, 'subsample': 1.0}), ('subsample=0.5', 'blue', - {'learn_rate': 1.0, 'subsample': 0.5}), - ('learn_rate=0.1, subsample=0.5', 'gray', - {'learn_rate': 0.1, 'subsample': 0.5}), - ('learn_rate=0.1, max_features=2', 'magenta', - {'learn_rate': 0.1, 'max_features': 2})]: + {'learning_rate': 1.0, 'subsample': 0.5}), + ('learning_rate=0.1, subsample=0.5', 'gray', + {'learning_rate': 0.1, 'subsample': 0.5}), + ('learning_rate=0.1, max_features=2', 'magenta', + {'learning_rate': 0.1, 'max_features': 2})]: params = dict(original_params) params.update(setting) @@ -62,13 +66,14 @@ test_deviance = np.zeros((params['n_estimators'],), dtype=np.float64) for i, y_pred in enumerate(clf.staged_decision_function(X_test)): + # clf.loss_ assumes that y_test[i] in {0, 1} test_deviance[i] = clf.loss_(y_test, y_pred) - pl.plot((np.arange(test_deviance.shape[0]) + 1)[::5], test_deviance[::5], - '-', color=color, label=label) + plt.plot((np.arange(test_deviance.shape[0]) + 1)[::5], test_deviance[::5], + '-', color=color, label=label) -pl.legend(loc='upper left') -pl.xlabel('Boosting Iterations') -pl.ylabel('Test Set Deviance') +plt.legend(loc='upper left') +plt.xlabel('Boosting Iterations') +plt.ylabel('Test Set Deviance') -pl.show() +plt.show() diff --git a/examples/ensemble/plot_partial_dependence.py b/examples/ensemble/plot_partial_dependence.py new file mode 100644 index 0000000000000..b480e228d3ca3 --- /dev/null +++ b/examples/ensemble/plot_partial_dependence.py @@ -0,0 +1,111 @@ +""" +======================== +Partial Dependence Plots +======================== + +Partial dependence plots show the dependence between the target function [1]_ +and a set of 'target' features, marginalizing over the +values of all other features (the complement features). Due to the limits +of human perception the size of the target feature set must be small (usually, +one or two) thus the target features are usually chosen among the most +important features +(see :attr:`~sklearn.ensemble.GradientBoostingRegressor.feature_importances_`). + +This example shows how to obtain partial dependence plots from a +:class:`~sklearn.ensemble.GradientBoostingRegressor` trained on the California +housing dataset. The example is taken from [HTF2009]_. + +The plot shows four one-way and one two-way partial dependence plots. +The target variables for the one-way PDP are: +median income (`MedInc`), avg. occupants per household (`AvgOccup`), +median house age (`HouseAge`), and avg. rooms per household (`AveRooms`). + +We can clearly see that the median house price shows a linear relationship +with the median income (top left) and that the house price drops when the +avg. occupants per household increases (top middle). +The top right plot shows that the house age in a district does not have +a strong influence on the (median) house price; so does the average rooms +per household. +The tick marks on the x-axis represent the deciles of the feature values +in the training data. + +Partial dependence plots with two target features enable us to visualize +interactions among them. The two-way partial dependence plot shows the +dependence of median house price on joint values of house age and avg. +occupants per household. We can clearly see an interaction between the +two features: +For an avg. occupancy greater than two, the house price is nearly independent +of the house age, whereas for values less than two there is a strong dependence +on age. + +.. [HTF2009] T. Hastie, R. Tibshirani and J. Friedman, + "Elements of Statistical Learning Ed. 2", Springer, 2009. + +.. [1] For classification you can think of it as the regression score before + the link function. +""" +print(__doc__) + +import numpy as np +import matplotlib.pyplot as plt + +from mpl_toolkits.mplot3d import Axes3D + +from sklearn.cross_validation import train_test_split +from sklearn.ensemble import GradientBoostingRegressor +from sklearn.ensemble.partial_dependence import plot_partial_dependence +from sklearn.ensemble.partial_dependence import partial_dependence +from sklearn.datasets.california_housing import fetch_california_housing + +# fetch California housing dataset +cal_housing = fetch_california_housing() + +# split 80/20 train-test +X_train, X_test, y_train, y_test = train_test_split(cal_housing.data, + cal_housing.target, + test_size=0.2, + random_state=1) +names = cal_housing.feature_names + +print('_' * 80) +print("Training GBRT...") +clf = GradientBoostingRegressor(n_estimators=100, max_depth=4, + learning_rate=0.1, loss='huber', + random_state=1) +clf.fit(X_train, y_train) +print("done.") + +print('_' * 80) +print('Convenience plot with ``partial_dependence_plots``') +print + +features = [0, 5, 1, 2, (5, 1)] +fig, axs = plot_partial_dependence(clf, X_train, features, feature_names=names, + n_jobs=3, grid_resolution=50) +fig.suptitle('Partial dependence of house value on nonlocation features\n' + 'for the California housing dataset') +plt.subplots_adjust(top=0.9) # tight_layout causes overlap with suptitle + +print('_' * 80) +print('Custom 3d plot via ``partial_dependence``') +print +fig = plt.figure() + +target_feature = (1, 5) +pdp, (x_axis, y_axis) = partial_dependence(clf, target_feature, + X=X_train, grid_resolution=50) +XX, YY = np.meshgrid(x_axis, y_axis) +Z = pdp.T.reshape(XX.shape).T +ax = Axes3D(fig) +surf = ax.plot_surface(XX, YY, Z, rstride=1, cstride=1, cmap=plt.cm.BuPu) +ax.set_xlabel(names[target_feature[0]]) +ax.set_ylabel(names[target_feature[1]]) +ax.set_zlabel('Partial dependence') +# pretty init view +ax.view_init(elev=22, azim=122) +plt.colorbar(surf) +plt.suptitle('Partial dependence of house value on median age and ' + 'average occupancy') +plt.subplots_adjust(top=0.9) + +plt.show() diff --git a/examples/ensemble/plot_random_forest_embedding.py b/examples/ensemble/plot_random_forest_embedding.py new file mode 100644 index 0000000000000..ba6329d72905b --- /dev/null +++ b/examples/ensemble/plot_random_forest_embedding.py @@ -0,0 +1,105 @@ +""" +========================================================= +Hashing feature transformation using Totally Random Trees +========================================================= + +RandomTreesEmbedding provides a way to map data to a +very high-dimensional, sparse representation, which might +be beneficial for classification. +The mapping is completely unsupervised and very efficient. + +This example visualizes the partitions given by several +trees and shows how the transformation can also be used for +non-linear dimensionality reduction or non-linear classification. + +Points that are neighboring often share the same leaf of a tree and therefore +share large parts of their hashed representation. This allows to +separate two concentric circles simply based on the principal components of the +transformed data. + +In high-dimensional spaces, linear classifiers often achieve +excellent accuracy. For sparse binary data, BernoulliNB +is particularly well-suited. The bottom row compares the +decision boundary obtained by BernoulliNB in the transformed +space with an ExtraTreesClassifier forests learned on the +original data. +""" +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.datasets import make_circles +from sklearn.ensemble import RandomTreesEmbedding, ExtraTreesClassifier +from sklearn.decomposition import TruncatedSVD +from sklearn.naive_bayes import BernoulliNB + +# make a synthetic dataset +X, y = make_circles(factor=0.5, random_state=0, noise=0.05) + +# use RandomTreesEmbedding to transform data +hasher = RandomTreesEmbedding(n_estimators=10, random_state=0, max_depth=3) +X_transformed = hasher.fit_transform(X) + +# Visualize result using PCA +pca = TruncatedSVD(n_components=2) +X_reduced = pca.fit_transform(X_transformed) + +# Learn a Naive Bayes classifier on the transformed data +nb = BernoulliNB() +nb.fit(X_transformed, y) + + +# Learn an ExtraTreesClassifier for comparison +trees = ExtraTreesClassifier(max_depth=3, n_estimators=10, random_state=0) +trees.fit(X, y) + + +# scatter plot of original and reduced data +fig = plt.figure(figsize=(9, 8)) + +ax = plt.subplot(221) +ax.scatter(X[:, 0], X[:, 1], c=y, s=50) +ax.set_title("Original Data (2d)") +ax.set_xticks(()) +ax.set_yticks(()) + +ax = plt.subplot(222) +ax.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, s=50) +ax.set_title("PCA reduction (2d) of transformed data (%dd)" % + X_transformed.shape[1]) +ax.set_xticks(()) +ax.set_yticks(()) + +# Plot the decision in original space. For that, we will assign a color to each +# point in the mesh [x_min, m_max] x [y_min, y_max]. +h = .01 +x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 +y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 +xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) + +# transform grid using RandomTreesEmbedding +transformed_grid = hasher.transform(np.c_[xx.ravel(), yy.ravel()]) +y_grid_pred = nb.predict_proba(transformed_grid)[:, 1] + +ax = plt.subplot(223) +ax.set_title("Naive Bayes on Transformed data") +ax.pcolormesh(xx, yy, y_grid_pred.reshape(xx.shape)) +ax.scatter(X[:, 0], X[:, 1], c=y, s=50) +ax.set_ylim(-1.4, 1.4) +ax.set_xlim(-1.4, 1.4) +ax.set_xticks(()) +ax.set_yticks(()) + +# transform grid using ExtraTreesClassifier +y_grid_pred = trees.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1] + +ax = plt.subplot(224) +ax.set_title("ExtraTrees predictions") +ax.pcolormesh(xx, yy, y_grid_pred.reshape(xx.shape)) +ax.scatter(X[:, 0], X[:, 1], c=y, s=50) +ax.set_ylim(-1.4, 1.4) +ax.set_xlim(-1.4, 1.4) +ax.set_xticks(()) +ax.set_yticks(()) + +plt.tight_layout() +plt.show() diff --git a/examples/exercises/plot_digits_classification_exercise.py b/examples/exercises/digits_classification_exercise.py similarity index 69% rename from examples/exercises/plot_digits_classification_exercise.py rename to examples/exercises/digits_classification_exercise.py index 1a7e6bd5a26ac..a1f0b84fd1fd2 100644 --- a/examples/exercises/plot_digits_classification_exercise.py +++ b/examples/exercises/digits_classification_exercise.py @@ -3,11 +3,14 @@ Digits Classification Exercise ================================ +A tutorial exercise regarding the use of classification techniques on +the Digits dataset. + This exercise is used in the :ref:`clf_tut` part of the :ref:`supervised_learning_tut` section of the :ref:`stat_learn_tut_index`. """ -print __doc__ +print(__doc__) from sklearn import datasets, neighbors, linear_model @@ -25,7 +28,6 @@ knn = neighbors.KNeighborsClassifier() logistic = linear_model.LogisticRegression() -print('KNN score: %f' % - knn.fit(X_train, y_train).score(X_test, y_test)) -print('LogisticRegression score: %f' % - logistic.fit(X_train, y_train).score(X_test, y_test)) +print('KNN score: %f' % knn.fit(X_train, y_train).score(X_test, y_test)) +print('LogisticRegression score: %f' + % logistic.fit(X_train, y_train).score(X_test, y_test)) diff --git a/examples/exercises/plot_cv_diabetes.py b/examples/exercises/plot_cv_diabetes.py index e4ccee0fa0747..424c037a5547e 100644 --- a/examples/exercises/plot_cv_diabetes.py +++ b/examples/exercises/plot_cv_diabetes.py @@ -3,23 +3,25 @@ Cross-validation on diabetes Dataset Exercise =============================================== +A tutorial exercise which uses cross-validation with linear models. + This exercise is used in the :ref:`cv_estimators_tut` part of the :ref:`model_selection_tut` section of the :ref:`stat_learn_tut_index`. """ -print __doc__ +from __future__ import print_function +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import cross_validation, datasets, linear_model diabetes = datasets.load_diabetes() -X = diabetes.data -y = diabetes.target +X = diabetes.data[:150] +y = diabetes.target[:150] lasso = linear_model.Lasso() - -alphas = np.logspace(-4, -1, 20) +alphas = np.logspace(-4, -.5, 30) scores = list() scores_std = list() @@ -30,19 +32,40 @@ scores.append(np.mean(this_scores)) scores_std.append(np.std(this_scores)) -pl.figure(1, figsize=(2.5, 2)) -pl.clf() -pl.axes([.1, .25, .8, .7]) -pl.semilogx(alphas, scores) -pl.semilogx(alphas, np.array(scores) + np.array(scores_std) / 20, 'b--') -pl.semilogx(alphas, np.array(scores) - np.array(scores_std) / 20, 'b--') -pl.yticks(()) -pl.ylabel('CV score') -pl.xlabel('alpha') -pl.axhline(np.max(scores), linestyle='--', color='.5') -pl.text(2e-4, np.max(scores) + 1e-4, '.489') +plt.figure(figsize=(4, 3)) +plt.semilogx(alphas, scores) +# plot error lines showing +/- std. errors of the scores +plt.semilogx(alphas, np.array(scores) + np.array(scores_std) / np.sqrt(len(X)), + 'b--') +plt.semilogx(alphas, np.array(scores) - np.array(scores_std) / np.sqrt(len(X)), + 'b--') +plt.ylabel('CV score') +plt.xlabel('alpha') +plt.axhline(np.max(scores), linestyle='--', color='.5') ############################################################################## # Bonus: how much can you trust the selection of alpha? + +# To answer this question we use the LassoCV object that sets its alpha +# parameter automatically from the data by internal cross-validation (i.e. it +# performs cross-validation on the training data it receives). +# We use external cross-validation to see how much the automatically obtained +# alphas differ across different cross-validation folds. +lasso_cv = linear_model.LassoCV(alphas=alphas) k_fold = cross_validation.KFold(len(X), 3) -print [lasso.fit(X[train], y[train]).alpha for train, _ in k_fold] + +print("Answer to the bonus question:", + "how much can you trust the selection of alpha?") +print() +print("Alpha parameters maximising the generalization score on different") +print("subsets of the data:") +for k, (train, test) in enumerate(k_fold): + lasso_cv.fit(X[train], y[train]) + print("[fold {0}] alpha: {1:.5f}, score: {2:.5f}". + format(k, lasso_cv.alpha_, lasso_cv.score(X[test], y[test]))) +print() +print("Answer: Not very much since we obtained different alphas for different") +print("subsets of the data and moreover, the scores for these alphas differ") +print("quite substantially.") + +plt.show() diff --git a/examples/exercises/plot_cv_digits.py b/examples/exercises/plot_cv_digits.py index d124056964584..92f04a935cc5a 100644 --- a/examples/exercises/plot_cv_digits.py +++ b/examples/exercises/plot_cv_digits.py @@ -3,10 +3,12 @@ Cross-validation on Digits Dataset Exercise ============================================= +A tutorial exercise using Cross-validation with an SVM on the Digits dataset. + This exercise is used in the :ref:`cv_generators_tut` part of the :ref:`model_selection_tut` section of the :ref:`stat_learn_tut_index`. """ -print __doc__ +print(__doc__) import numpy as np @@ -16,8 +18,8 @@ X = digits.data y = digits.target -svc = svm.SVC() -C_s = np.logspace(-3, 3, 10) +svc = svm.SVC(kernel='linear') +C_s = np.logspace(-10, 0, 10) scores = list() scores_std = list() @@ -27,18 +29,16 @@ scores.append(np.mean(this_scores)) scores_std.append(np.std(this_scores)) -import pylab as pl -pl.figure(1, figsize=(2.5, 2)) -pl.clf() -pl.axes([.1, .25, .8, .7]) -pl.semilogx(C_s, scores) -pl.semilogx(C_s, np.array(scores) + np.array(scores_std), 'b--') -pl.semilogx(C_s, np.array(scores) - np.array(scores_std), 'b--') -pl.yticks(()) -pl.ylabel('CV score') -pl.xlabel('Parameter C') -pl.ylim(0, 1.1) -#pl.axhline(np.max(scores), linestyle='--', color='.5') -pl.text(C_s[np.argmax(scores)], .9 * np.max(scores), '%.3f' % np.max(scores), - verticalalignment='top', horizontalalignment='center',) -pl.show() +# Do the plotting +import matplotlib.pyplot as plt +plt.figure(1, figsize=(4, 3)) +plt.clf() +plt.semilogx(C_s, scores) +plt.semilogx(C_s, np.array(scores) + np.array(scores_std), 'b--') +plt.semilogx(C_s, np.array(scores) - np.array(scores_std), 'b--') +locs, labels = plt.yticks() +plt.yticks(locs, list(map(lambda x: "%g" % x, locs))) +plt.ylabel('CV score') +plt.xlabel('Parameter C') +plt.ylim(0, 1.1) +plt.show() diff --git a/examples/exercises/plot_iris_exercise.py b/examples/exercises/plot_iris_exercise.py index 9c976b3c246b7..cf1da9109aaaf 100644 --- a/examples/exercises/plot_iris_exercise.py +++ b/examples/exercises/plot_iris_exercise.py @@ -3,14 +3,16 @@ SVM Exercise ================================ +A tutorial exercise for using different SVM kernels. + This exercise is used in the :ref:`using_kernels_tut` part of the :ref:`supervised_learning_tut` section of the :ref:`stat_learn_tut_index`. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import datasets, svm iris = datasets.load_iris() @@ -37,15 +39,14 @@ clf = svm.SVC(kernel=kernel, gamma=10) clf.fit(X_train, y_train) - pl.figure(fig_num) - pl.clf() - pl.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap=pl.cm.Paired) + plt.figure(fig_num) + plt.clf() + plt.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap=plt.cm.Paired) # Circle out the test data - pl.scatter(X_test[:, 0], X_test[:, 1], - s=80, facecolors='none', zorder=10) + plt.scatter(X_test[:, 0], X_test[:, 1], s=80, facecolors='none', zorder=10) - pl.axis('tight') + plt.axis('tight') x_min = X[:, 0].min() x_max = X[:, 0].max() y_min = X[:, 1].min() @@ -56,10 +57,9 @@ # Put the result into a color plot Z = Z.reshape(XX.shape) - pl.pcolormesh(XX, YY, Z > 0, cmap=pl.cm.Paired) - pl.contour(XX, YY, Z, colors=['k', 'k', 'k'], - linestyles=['--', '-', '--'], - levels=[-.5, 0, .5]) + plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired) + plt.contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'], + levels=[-.5, 0, .5]) - pl.title(kernel) -pl.show() + plt.title(kernel) +plt.show() diff --git a/examples/feature_selection/README.txt b/examples/feature_selection/README.txt new file mode 100644 index 0000000000000..53f5df42d0ccb --- /dev/null +++ b/examples/feature_selection/README.txt @@ -0,0 +1,6 @@ +.. _feature_selection_examples: + +Feature Selection +----------------------- + +Examples concerning the :mod:`sklearn.feature_selection` module. diff --git a/examples/feature_selection_pipeline.py b/examples/feature_selection/feature_selection_pipeline.py similarity index 73% rename from examples/feature_selection_pipeline.py rename to examples/feature_selection/feature_selection_pipeline.py index 2bb4f6ba7049d..59edd941faa3d 100644 --- a/examples/feature_selection_pipeline.py +++ b/examples/feature_selection/feature_selection_pipeline.py @@ -6,17 +6,17 @@ Simple usage of Pipeline that runs successively a univariate feature selection with anova and then a C-SVM of the selected features. """ -print __doc__ +print(__doc__) from sklearn import svm from sklearn.datasets import samples_generator from sklearn.feature_selection import SelectKBest, f_regression -from sklearn.pipeline import Pipeline +from sklearn.pipeline import make_pipeline # import some data to play with X, y = samples_generator.make_classification( - n_features=20, n_informative=3, n_redundant=0, - n_classes=4, n_clusters_per_class=2) + n_features=20, n_informative=3, n_redundant=0, n_classes=4, + n_clusters_per_class=2) # ANOVA SVM-C # 1) anova filter, take 3 best ranked features @@ -24,6 +24,6 @@ # 2) svm clf = svm.SVC(kernel='linear') -anova_svm = Pipeline([('anova', anova_filter), ('svm', clf)]) +anova_svm = make_pipeline(anova_filter, clf) anova_svm.fit(X, y) anova_svm.predict(X) diff --git a/examples/plot_feature_selection.py b/examples/feature_selection/plot_feature_selection.py similarity index 80% rename from examples/plot_feature_selection.py rename to examples/feature_selection/plot_feature_selection.py index b4e8446d1ee12..9361791ce81d1 100644 --- a/examples/plot_feature_selection.py +++ b/examples/feature_selection/plot_feature_selection.py @@ -19,10 +19,10 @@ increases the SVM weight attributed to the significant features, and will thus improve classification. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import datasets, svm from sklearn.feature_selection import SelectPercentile, f_classif @@ -41,8 +41,8 @@ y = iris.target ############################################################################### -pl.figure(1) -pl.clf() +plt.figure(1) +plt.clf() X_indices = np.arange(X.shape[-1]) @@ -53,9 +53,8 @@ selector.fit(X, y) scores = -np.log10(selector.pvalues_) scores /= scores.max() -pl.bar(X_indices - .45, scores, width=.2, - label=r'Univariate score ($-Log(p_{value})$)', - color='g') +plt.bar(X_indices - .45, scores, width=.2, + label=r'Univariate score ($-Log(p_{value})$)', color='g') ############################################################################### # Compare to the weights of an SVM @@ -65,8 +64,7 @@ svm_weights = (clf.coef_ ** 2).sum(axis=0) svm_weights /= svm_weights.max() -pl.bar(X_indices - .25, svm_weights, width=.2, label='SVM weight', - color='r') +plt.bar(X_indices - .25, svm_weights, width=.2, label='SVM weight', color='r') clf_selected = svm.SVC(kernel='linear') clf_selected.fit(selector.transform(X), y) @@ -74,13 +72,13 @@ svm_weights_selected = (clf_selected.coef_ ** 2).sum(axis=0) svm_weights_selected /= svm_weights_selected.max() -pl.bar(X_indices[selector.get_support()] - .05, svm_weights_selected, width=.2, - label='SVM weights after selection', color='b') +plt.bar(X_indices[selector.get_support()] - .05, svm_weights_selected, + width=.2, label='SVM weights after selection', color='b') -pl.title("Comparing feature selection") -pl.xlabel('Feature number') -pl.yticks(()) -pl.axis('tight') -pl.legend(loc='upper right') -pl.show() +plt.title("Comparing feature selection") +plt.xlabel('Feature number') +plt.yticks(()) +plt.axis('tight') +plt.legend(loc='upper right') +plt.show() diff --git a/examples/plot_permutation_test_for_classification.py b/examples/feature_selection/plot_permutation_test_for_classification.py similarity index 65% rename from examples/plot_permutation_test_for_classification.py rename to examples/feature_selection/plot_permutation_test_for_classification.py index c05de6d0c319a..4df102578c9da 100644 --- a/examples/plot_permutation_test_for_classification.py +++ b/examples/feature_selection/plot_permutation_test_for_classification.py @@ -12,17 +12,16 @@ """ # Author: Alexandre Gramfort -# License: BSD +# License: BSD 3 clause -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.cross_validation import StratifiedKFold, permutation_test_score from sklearn import datasets -from sklearn.metrics import zero_one_score ############################################################################## @@ -42,28 +41,27 @@ svm = SVC(kernel='linear') cv = StratifiedKFold(y, 2) -score, permutation_scores, pvalue = permutation_test_score(svm, X, y, - zero_one_score, cv=cv, - n_permutations=100, n_jobs=1) +score, permutation_scores, pvalue = permutation_test_score( + svm, X, y, scoring="accuracy", cv=cv, n_permutations=100, n_jobs=1) -print "Classification score %s (pvalue : %s)" % (score, pvalue) +print("Classification score %s (pvalue : %s)" % (score, pvalue)) ############################################################################### # View histogram of permutation scores -pl.hist(permutation_scores, 20, label='Permutation scores') -ylim = pl.ylim() +plt.hist(permutation_scores, 20, label='Permutation scores') +ylim = plt.ylim() # BUG: vlines(..., linestyle='--') fails on older versions of matplotlib -#pl.vlines(score, ylim[0], ylim[1], linestyle='--', +#plt.vlines(score, ylim[0], ylim[1], linestyle='--', # color='g', linewidth=3, label='Classification Score' # ' (pvalue %s)' % pvalue) -#pl.vlines(1.0 / n_classes, ylim[0], ylim[1], linestyle='--', +#plt.vlines(1.0 / n_classes, ylim[0], ylim[1], linestyle='--', # color='k', linewidth=3, label='Luck') -pl.plot(2 * [score], ylim, '--g', linewidth=3, - label='Classification Score' - ' (pvalue %s)' % pvalue) -pl.plot(2 * [1. / n_classes], ylim, '--k', linewidth=3, label='Luck') +plt.plot(2 * [score], ylim, '--g', linewidth=3, + label='Classification Score' + ' (pvalue %s)' % pvalue) +plt.plot(2 * [1. / n_classes], ylim, '--k', linewidth=3, label='Luck') -pl.ylim(ylim) -pl.legend() -pl.xlabel('Score') -pl.show() +plt.ylim(ylim) +plt.legend() +plt.xlabel('Score') +plt.show() diff --git a/examples/plot_rfe_digits.py b/examples/feature_selection/plot_rfe_digits.py similarity index 74% rename from examples/plot_rfe_digits.py rename to examples/feature_selection/plot_rfe_digits.py index 2c1b84f71ac3d..bcbf28c7d78ca 100644 --- a/examples/plot_rfe_digits.py +++ b/examples/feature_selection/plot_rfe_digits.py @@ -5,12 +5,18 @@ A recursive feature elimination example showing the relevance of pixels in a digit classification task. + +.. note:: + + See also :ref:`example_feature_selection_plot_rfe_with_cross_validation.py` + """ -print __doc__ +print(__doc__) from sklearn.svm import SVC from sklearn.datasets import load_digits from sklearn.feature_selection import RFE +import matplotlib.pyplot as plt # Load the digits dataset digits = load_digits() @@ -24,8 +30,7 @@ ranking = rfe.ranking_.reshape(digits.images[0].shape) # Plot pixel ranking -import pylab as pl -pl.matshow(ranking) -pl.colorbar() -pl.title("Ranking of pixels with RFE") -pl.show() +plt.matshow(ranking) +plt.colorbar() +plt.title("Ranking of pixels with RFE") +plt.show() diff --git a/examples/plot_rfe_with_cross_validation.py b/examples/feature_selection/plot_rfe_with_cross_validation.py similarity index 59% rename from examples/plot_rfe_with_cross_validation.py rename to examples/feature_selection/plot_rfe_with_cross_validation.py index e5fd1a0694a9e..232aa115c2d77 100644 --- a/examples/plot_rfe_with_cross_validation.py +++ b/examples/feature_selection/plot_rfe_with_cross_validation.py @@ -6,31 +6,32 @@ A recursive feature elimination example with automatic tuning of the number of features selected with cross-validation. """ -print __doc__ +print(__doc__) +import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.cross_validation import StratifiedKFold from sklearn.feature_selection import RFECV from sklearn.datasets import make_classification -from sklearn.metrics import zero_one # Build a classification task using 3 informative features X, y = make_classification(n_samples=1000, n_features=25, n_informative=3, - n_redundant=2, n_repeated=0, n_classes=8, n_clusters_per_class=1, - random_state=0) + n_redundant=2, n_repeated=0, n_classes=8, + n_clusters_per_class=1, random_state=0) # Create the RFE object and compute a cross-validated score. svc = SVC(kernel="linear") +# The "accuracy" scoring is proportional to the number of correct +# classifications rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(y, 2), - loss_func=zero_one) + scoring='accuracy') rfecv.fit(X, y) -print "Optimal number of features : %d" % rfecv.n_features_ +print("Optimal number of features : %d" % rfecv.n_features_) # Plot number of features VS. cross-validation scores -import pylab as pl -pl.figure() -pl.xlabel("Number of features selected") -pl.ylabel("Cross validation score (nb of misclassifications)") -pl.plot(xrange(1, len(rfecv.cv_scores_) + 1), rfecv.cv_scores_) -pl.show() +plt.figure() +plt.xlabel("Number of features selected") +plt.ylabel("Cross validation score (nb of correct classifications)") +plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_) +plt.show() diff --git a/examples/feature_stacker.py b/examples/feature_stacker.py new file mode 100644 index 0000000000000..d1f9453e28e58 --- /dev/null +++ b/examples/feature_stacker.py @@ -0,0 +1,58 @@ +""" +================================================= +Concatenating multiple feature extraction methods +================================================= + +In many real-world examples, there are many ways to extract features from a +dataset. Often it is beneficial to combine several methods to obtain good +performance. This example shows how to use ``FeatureUnion`` to combine +features obtained by PCA and univariate selection. + +Combining features using this transformer has the benefit that it allows +cross validation and grid searches over the whole process. + +The combination used in this example is not particularly helpful on this +dataset and is only used to illustrate the usage of FeatureUnion. +""" + +# Author: Andreas Mueller +# +# License: BSD 3 clause + +from sklearn.pipeline import Pipeline, FeatureUnion +from sklearn.grid_search import GridSearchCV +from sklearn.svm import SVC +from sklearn.datasets import load_iris +from sklearn.decomposition import PCA +from sklearn.feature_selection import SelectKBest + +iris = load_iris() + +X, y = iris.data, iris.target + +# This dataset is way to high-dimensional. Better do PCA: +pca = PCA(n_components=2) + +# Maybe some original features where good, too? +selection = SelectKBest(k=1) + +# Build estimator from PCA and Univariate selection: + +combined_features = FeatureUnion([("pca", pca), ("univ_select", selection)]) + +# Use combined features to transform dataset: +X_features = combined_features.fit(X, y).transform(X) + +svm = SVC(kernel="linear") + +# Do grid search over k, n_components and C: + +pipeline = Pipeline([("features", combined_features), ("svm", svm)]) + +param_grid = dict(features__pca__n_components=[1, 2, 3], + features__univ_select__k=[1, 2], + svm__C=[0.1, 1, 10]) + +grid_search = GridSearchCV(pipeline, param_grid=param_grid, verbose=10) +grid_search.fit(X, y) +print(grid_search.best_estimator_) diff --git a/examples/gaussian_process/README.txt b/examples/gaussian_process/README.txt index c892678e89d8b..5ee038e015639 100644 --- a/examples/gaussian_process/README.txt +++ b/examples/gaussian_process/README.txt @@ -3,5 +3,5 @@ Gaussian Process for Machine Learning ------------------------------------- -Examples concerning the :mod:`sklearn.gaussian_process` package. +Examples concerning the :mod:`sklearn.gaussian_process` module. diff --git a/examples/gaussian_process/gp_diabetes_dataset.py b/examples/gaussian_process/gp_diabetes_dataset.py index 4ea4c4b0d99c6..9baaeccf17d6d 100644 --- a/examples/gaussian_process/gp_diabetes_dataset.py +++ b/examples/gaussian_process/gp_diabetes_dataset.py @@ -6,22 +6,22 @@ Gaussian Processes regression: goodness-of-fit on the 'diabetes' dataset ======================================================================== -This example consists in fitting a Gaussian Process model onto the diabetes +In this example, we fit a Gaussian Process model onto the diabetes dataset. -The correlation parameters are determined by means of maximum likelihood -estimation (MLE). An anisotropic squared exponential correlation model with a -constant regression model are assumed. We also used a nugget = 1e-2 in order to -account for the (strong) noise in the targets. +We determine the correlation parameters with maximum likelihood +estimation (MLE). We use an anisotropic squared exponential +correlation model with a constant regression model. We also use a +nugget of 1e-2 to account for the (strong) noise in the targets. -We compute then compute a cross-validation estimate of the coefficient of +We compute a cross-validation estimate of the coefficient of determination (R2) without reperforming MLE, using the set of correlation parameters found on the whole dataset. """ -print __doc__ +print(__doc__) # Author: Vincent Dubourg -# License: BSD style +# Licence: BSD 3 clause from sklearn import datasets from sklearn.gaussian_process import GaussianProcess @@ -40,7 +40,7 @@ gp.fit(X, y) # Deactivate maximum likelihood estimation for the cross-validation loop -gp.theta0 = gp.theta # Given correlation parameter = MLE +gp.theta0 = gp.theta_ # Given correlation parameter = MLE gp.thetaL, gp.thetaU = None, None # None bounds deactivate MLE # Perform a cross-validation estimate of the coefficient of determination using @@ -48,4 +48,4 @@ K = 20 # folds R2 = cross_val_score(gp, X, y=y, cv=KFold(y.size, K), n_jobs=1).mean() print("The %d-Folds estimate of the coefficient of determination is R2 = %s" - % (K, R2)) + % (K, R2)) diff --git a/examples/gaussian_process/plot_gp_probabilistic_classification_after_regression.py b/examples/gaussian_process/plot_gp_probabilistic_classification_after_regression.py index 3ab6cba276ae4..3c9887aa66852 100644 --- a/examples/gaussian_process/plot_gp_probabilistic_classification_after_regression.py +++ b/examples/gaussian_process/plot_gp_probabilistic_classification_after_regression.py @@ -14,10 +14,10 @@ corresponds to the 95% confidence interval on the prediction of the zero level set. """ -print __doc__ +print(__doc__) # Author: Vincent Dubourg -# License: BSD style +# Licence: BSD 3 clause import numpy as np from scipy import stats @@ -60,7 +60,7 @@ def g(x): # Evaluate real function, the prediction and its MSE on a grid res = 50 -x1, x2 = np.meshgrid(np.linspace(- lim, lim, res), \ +x1, x2 = np.meshgrid(np.linspace(- lim, lim, res), np.linspace(- lim, lim, res)) xx = np.vstack([x1.reshape(x1.size), x2.reshape(x2.size)]).T @@ -84,7 +84,7 @@ def g(x): pl.xlabel('$x_1$') pl.ylabel('$x_2$') -cax = pl.imshow(np.flipud(PHI(- y_pred / sigma)), cmap=cm.gray_r, alpha=0.8, \ +cax = pl.imshow(np.flipud(PHI(- y_pred / sigma)), cmap=cm.gray_r, alpha=0.8, extent=(- lim, lim, - lim, lim)) norm = pl.matplotlib.colors.Normalize(vmin=0., vmax=0.9) cb = pl.colorbar(cax, ticks=[0., 0.2, 0.4, 0.6, 0.8, 1.], norm=norm) @@ -94,18 +94,17 @@ def g(x): pl.plot(X[y > 0, 0], X[y > 0, 1], 'b.', markersize=12) -cs = pl.contour(x1, x2, y_true, [0.], colors='k', \ - linestyles='dashdot') +cs = pl.contour(x1, x2, y_true, [0.], colors='k', linestyles='dashdot') -cs = pl.contour(x1, x2, PHI(- y_pred / sigma), [0.025], colors='b', \ +cs = pl.contour(x1, x2, PHI(- y_pred / sigma), [0.025], colors='b', linestyles='solid') pl.clabel(cs, fontsize=11) -cs = pl.contour(x1, x2, PHI(- y_pred / sigma), [0.5], colors='k', \ +cs = pl.contour(x1, x2, PHI(- y_pred / sigma), [0.5], colors='k', linestyles='dashed') pl.clabel(cs, fontsize=11) -cs = pl.contour(x1, x2, PHI(- y_pred / sigma), [0.975], colors='r', \ +cs = pl.contour(x1, x2, PHI(- y_pred / sigma), [0.975], colors='r', linestyles='solid') pl.clabel(cs, fontsize=11) diff --git a/examples/gaussian_process/plot_gp_regression.py b/examples/gaussian_process/plot_gp_regression.py index 92f9d926b4ca5..33b78750d1fe4 100644 --- a/examples/gaussian_process/plot_gp_regression.py +++ b/examples/gaussian_process/plot_gp_regression.py @@ -27,11 +27,11 @@ \mathrm{nugget}_i = \left[\frac{\sigma_i}{y_i}\right]^2 """ -print __doc__ +print(__doc__) # Author: Vincent Dubourg # Jake Vanderplas -# License: BSD style +# Licence: BSD 3 clause import numpy as np from sklearn.gaussian_process import GaussianProcess @@ -56,7 +56,7 @@ def f(x): x = np.atleast_2d(np.linspace(0, 10, 1000)).T # Instanciate a Gaussian Process model -gp = GaussianProcess(corr='cubic', theta0=1e-2, thetaL=1e-4, thetaU=1e-1, \ +gp = GaussianProcess(corr='cubic', theta0=1e-2, thetaL=1e-4, thetaU=1e-1, random_start=100) # Fit to data using Maximum Likelihood Estimation of the parameters @@ -72,9 +72,9 @@ def f(x): pl.plot(x, f(x), 'r:', label=u'$f(x) = x\,\sin(x)$') pl.plot(X, y, 'r.', markersize=10, label=u'Observations') pl.plot(x, y_pred, 'b-', label=u'Prediction') -pl.fill(np.concatenate([x, x[::-1]]), \ +pl.fill(np.concatenate([x, x[::-1]]), np.concatenate([y_pred - 1.9600 * sigma, - (y_pred + 1.9600 * sigma)[::-1]]), \ + (y_pred + 1.9600 * sigma)[::-1]]), alpha=.5, fc='b', ec='None', label='95% confidence interval') pl.xlabel('$x$') pl.ylabel('$f(x)$') @@ -115,9 +115,9 @@ def f(x): pl.plot(x, f(x), 'r:', label=u'$f(x) = x\,\sin(x)$') pl.errorbar(X.ravel(), y, dy, fmt='r.', markersize=10, label=u'Observations') pl.plot(x, y_pred, 'b-', label=u'Prediction') -pl.fill(np.concatenate([x, x[::-1]]), \ +pl.fill(np.concatenate([x, x[::-1]]), np.concatenate([y_pred - 1.9600 * sigma, - (y_pred + 1.9600 * sigma)[::-1]]), \ + (y_pred + 1.9600 * sigma)[::-1]]), alpha=.5, fc='b', ec='None', label='95% confidence interval') pl.xlabel('$x$') pl.ylabel('$f(x)$') diff --git a/examples/hetero_feature_union.py b/examples/hetero_feature_union.py new file mode 100644 index 0000000000000..9a2c6742f3946 --- /dev/null +++ b/examples/hetero_feature_union.py @@ -0,0 +1,181 @@ +""" +============================================= +Feature Union with Heterogeneous Data Sources +============================================= + +Datasets can often contain components of that require different feature +extraction and processing pipelines. This scenario might occur when: + +1. Your dataset consists of heterogeneous data types (e.g. raster images and + text captions) +2. Your dataset is stored in a Pandas DataFrame and different columns + require different processing pipelines. + +This example demonstrates how to use +:class:`sklearn.feature_extraction.FeatureUnion` on a dataset containing +different types of features. We use the 20-newsgroups dataset and compute +standard bag-of-words features for the subject line and body in separate +pipelines as well as ad hoc features on the body. We combine them (with +weights) using a FeatureUnion and finally train a classifier on the combined +set of features. + +The choice of features is not particularly helpful, but serves to illustrate +the technique. +""" + +# Author: Matt Terry +# +# License: BSD 3 clause +from __future__ import print_function + +import numpy as np + +from sklearn.base import BaseEstimator, TransformerMixin +from sklearn.datasets import fetch_20newsgroups +from sklearn.datasets.twenty_newsgroups import strip_newsgroup_footer +from sklearn.datasets.twenty_newsgroups import strip_newsgroup_quoting +from sklearn.decomposition import TruncatedSVD +from sklearn.feature_extraction import DictVectorizer +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.metrics import classification_report +from sklearn.pipeline import FeatureUnion +from sklearn.pipeline import Pipeline +from sklearn.svm import SVC + + +class ItemSelector(BaseEstimator, TransformerMixin): + """For data grouped by feature, select subset of data at a provided key. + + The data is expected to be stored in a 2D data structure, where the first + index is over features and the second is over samples. i.e. + + >> len(data[key]) == n_samples + + Please note that this is the opposite convention to sklearn feature + matrixes (where the first index corresponds to sample). + + ItemSelector only requires that the collection implement getitem + (data[key]). Examples include: a dict of lists, 2D numpy array, Pandas + DataFrame, numpy record array, etc. + + >> data = {'a': [1, 5, 2, 5, 2, 8], + 'b': [9, 4, 1, 4, 1, 3]} + >> ds = ItemSelector(key='a') + >> data['a'] == ds.transform(data) + + ItemSelector is not designed to handle data grouped by sample. (e.g. a + list of dicts). If your data is structured this way, consider a + transformer along the lines of `sklearn.feature_extraction.DictVectorizer`. + + Parameters + ---------- + key : hashable, required + The key corresponding to the desired value in a mappable. + """ + def __init__(self, key): + self.key = key + + def fit(self, x, y=None): + return self + + def transform(self, data_dict): + return data_dict[self.key] + + +class TextStats(BaseEstimator, TransformerMixin): + """Extract features from each document for DictVectorizer""" + + def fit(self, x, y=None): + return self + + def transform(self, posts): + return [{'length': len(text), + 'num_sentences': text.count('.')} + for text in posts] + + +class SubjectBodyExtractor(BaseEstimator, TransformerMixin): + """Extract the subject & body from a usenet post in a single pass. + + Takes a sequence of strings and produces a dict of sequences. Keys are + `subject` and `body`. + """ + def fit(self, x, y=None): + return self + + def transform(self, posts): + features = np.recarray(shape=(len(posts),), + dtype=[('subject', object), ('body', object)]) + for i, text in enumerate(posts): + headers, _, bod = text.partition('\n\n') + bod = strip_newsgroup_footer(bod) + bod = strip_newsgroup_quoting(bod) + features['body'][i] = bod + + prefix = 'Subject:' + sub = '' + for line in headers.split('\n'): + if line.startswith(prefix): + sub = line[len(prefix):] + break + features['subject'][i] = sub + + return features + + +pipeline = Pipeline([ + # Extract the subject & body + ('subjectbody', SubjectBodyExtractor()), + + # Use FeatureUnion to combine the features from subject and body + ('union', FeatureUnion( + transformer_list=[ + + # Pipeline for pulling features from the post's subject line + ('subject', Pipeline([ + ('selector', ItemSelector(key='subject')), + ('tfidf', TfidfVectorizer(min_df=50)), + ])), + + # Pipeline for standard bag-of-words model for body + ('body_bow', Pipeline([ + ('selector', ItemSelector(key='body')), + ('tfidf', TfidfVectorizer()), + ('best', TruncatedSVD(n_components=50)), + ])), + + # Pipeline for pulling ad hoc features from post's body + ('body_stats', Pipeline([ + ('selector', ItemSelector(key='body')), + ('stats', TextStats()), # returns a list of dicts + ('vect', DictVectorizer()), # list of dicts -> feature matrix + ])), + + ], + + # weight components in FeatureUnion + transformer_weights={ + 'subject': 0.8, + 'body_bow': 0.5, + 'body_stats': 1.0, + }, + )), + + # Use a SVC classifier on the combined features + ('svc', SVC(kernel='linear')), +]) + +# limit the list of categories to make running this exmaple faster. +categories = ['alt.atheism', 'talk.religion.misc'] +train = fetch_20newsgroups(random_state=1, + subset='train', + categories=categories, + ) +test = fetch_20newsgroups(random_state=1, + subset='test', + categories=categories, + ) + +pipeline.fit(train.data, train.target) +y = pipeline.predict(test.data) +print(classification_report(y, test.target)) diff --git a/examples/linear_model/README.txt b/examples/linear_model/README.txt index 060f68e972819..08ca5a5e9aaf2 100644 --- a/examples/linear_model/README.txt +++ b/examples/linear_model/README.txt @@ -3,4 +3,4 @@ Generalized Linear Models ------------------------- -Examples concerning the :mod:`sklearn.linear_model` package. +Examples concerning the :mod:`sklearn.linear_model` module. diff --git a/examples/linear_model/lasso_dense_vs_sparse_data.py b/examples/linear_model/lasso_dense_vs_sparse_data.py index 6a69aaae0262d..bc8df42a8490e 100644 --- a/examples/linear_model/lasso_dense_vs_sparse_data.py +++ b/examples/linear_model/lasso_dense_vs_sparse_data.py @@ -7,7 +7,7 @@ data and that in the case of sparse data the speed is improved. """ -print __doc__ +print(__doc__) from time import time from scipy import sparse @@ -19,7 +19,7 @@ ############################################################################### # The two Lasso implementations on Dense data -print "--- Dense matrices" +print("--- Dense matrices") X, y = make_regression(n_samples=200, n_features=5000, random_state=0) X_sp = sparse.coo_matrix(X) @@ -30,25 +30,25 @@ t0 = time() sparse_lasso.fit(X_sp, y) -print "Sparse Lasso done in %fs" % (time() - t0) +print("Sparse Lasso done in %fs" % (time() - t0)) t0 = time() dense_lasso.fit(X, y) -print "Dense Lasso done in %fs" % (time() - t0) +print("Dense Lasso done in %fs" % (time() - t0)) -print "Distance between coefficients : %s" % linalg.norm(sparse_lasso.coef_ - - dense_lasso.coef_) +print("Distance between coefficients : %s" + % linalg.norm(sparse_lasso.coef_ - dense_lasso.coef_)) ############################################################################### # The two Lasso implementations on Sparse data -print "--- Sparse matrices" +print("--- Sparse matrices") Xs = X.copy() Xs[Xs < 2.5] = 0.0 Xs = sparse.coo_matrix(Xs) Xs = Xs.tocsc() -print "Matrix density : %s %%" % (Xs.nnz / float(X.size) * 100) +print("Matrix density : %s %%" % (Xs.nnz / float(X.size) * 100)) alpha = 0.1 sparse_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=10000) @@ -56,11 +56,11 @@ t0 = time() sparse_lasso.fit(Xs, y) -print "Sparse Lasso done in %fs" % (time() - t0) +print("Sparse Lasso done in %fs" % (time() - t0)) t0 = time() -dense_lasso.fit(Xs.todense(), y) -print "Dense Lasso done in %fs" % (time() - t0) +dense_lasso.fit(Xs.toarray(), y) +print("Dense Lasso done in %fs" % (time() - t0)) -print "Distance between coefficients : %s" % linalg.norm(sparse_lasso.coef_ - - dense_lasso.coef_) +print("Distance between coefficients : %s" + % linalg.norm(sparse_lasso.coef_ - dense_lasso.coef_)) diff --git a/examples/linear_model/plot_ard.py b/examples/linear_model/plot_ard.py index 283380286d018..7fb2ff787029b 100644 --- a/examples/linear_model/plot_ard.py +++ b/examples/linear_model/plot_ard.py @@ -3,10 +3,12 @@ Automatic Relevance Determination Regression (ARD) ================================================== -Fit regression model with :ref:`bayesian_ridge_regression`. +Fit regression model with Bayesian Ridge Regression. + +See :ref:`bayesian_ridge_regression` for more information on the regressor. Compared to the OLS (ordinary least squares) estimator, the coefficient -weights are slightly shifted toward zeros, wich stabilises them. +weights are slightly shifted toward zeros, which stabilises them. The histogram of the estimated weights is very peaked, as a sparsity-inducing prior is implied on the weights. @@ -14,21 +16,21 @@ The estimation of the model is done by iteratively maximizing the marginal log-likelihood of the observations. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from scipy import stats from sklearn.linear_model import ARDRegression, LinearRegression ############################################################################### -# Generating simulated data with Gaussian weigthts +# Generating simulated data with Gaussian weights # Parameters of the example np.random.seed(0) n_samples, n_features = 100, 100 -# Create gaussian data +# Create Gaussian data X = np.random.randn(n_samples, n_features) # Create weigts with a precision lambda_ of 4. lambda_ = 4. @@ -54,27 +56,27 @@ ############################################################################### # Plot the true weights, the estimated weights and the histogram of the # weights -pl.figure(figsize=(6, 5)) -pl.title("Weights of the model") -pl.plot(clf.coef_, 'b-', label="ARD estimate") -pl.plot(ols.coef_, 'r--', label="OLS estimate") -pl.plot(w, 'g-', label="Ground truth") -pl.xlabel("Features") -pl.ylabel("Values of the weights") -pl.legend(loc=1) +plt.figure(figsize=(6, 5)) +plt.title("Weights of the model") +plt.plot(clf.coef_, 'b-', label="ARD estimate") +plt.plot(ols.coef_, 'r--', label="OLS estimate") +plt.plot(w, 'g-', label="Ground truth") +plt.xlabel("Features") +plt.ylabel("Values of the weights") +plt.legend(loc=1) -pl.figure(figsize=(6, 5)) -pl.title("Histogram of the weights") -pl.hist(clf.coef_, bins=n_features, log=True) -pl.plot(clf.coef_[relevant_features], 5 * np.ones(len(relevant_features)), +plt.figure(figsize=(6, 5)) +plt.title("Histogram of the weights") +plt.hist(clf.coef_, bins=n_features, log=True) +plt.plot(clf.coef_[relevant_features], 5 * np.ones(len(relevant_features)), 'ro', label="Relevant features") -pl.ylabel("Features") -pl.xlabel("Values of the weights") -pl.legend(loc=1) +plt.ylabel("Features") +plt.xlabel("Values of the weights") +plt.legend(loc=1) -pl.figure(figsize=(6, 5)) -pl.title("Marginal log-likelihood") -pl.plot(clf.scores_) -pl.ylabel("Score") -pl.xlabel("Iterations") -pl.show() +plt.figure(figsize=(6, 5)) +plt.title("Marginal log-likelihood") +plt.plot(clf.scores_) +plt.ylabel("Score") +plt.xlabel("Iterations") +plt.show() diff --git a/examples/linear_model/plot_bayesian_ridge.py b/examples/linear_model/plot_bayesian_ridge.py index 49f066d271035..1442a143cda65 100644 --- a/examples/linear_model/plot_bayesian_ridge.py +++ b/examples/linear_model/plot_bayesian_ridge.py @@ -3,10 +3,12 @@ Bayesian Ridge Regression ========================= -Computes a :ref:`bayesian_ridge_regression` on a synthetic dataset. +Computes a Bayesian Ridge Regression on a synthetic dataset. + +See :ref:`bayesian_ridge_regression` for more information on the regressor. Compared to the OLS (ordinary least squares) estimator, the coefficient -weights are slightly shifted toward zeros, wich stabilises them. +weights are slightly shifted toward zeros, which stabilises them. As the prior on the weights is a Gaussian prior, the histogram of the estimated weights is Gaussian. @@ -14,10 +16,10 @@ The estimation of the model is done by iteratively maximizing the marginal log-likelihood of the observations. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from scipy import stats from sklearn.linear_model import BayesianRidge, LinearRegression @@ -26,7 +28,7 @@ # Generating simulated data with Gaussian weigthts np.random.seed(0) n_samples, n_features = 100, 100 -X = np.random.randn(n_samples, n_features) # Create gaussian data +X = np.random.randn(n_samples, n_features) # Create Gaussian data # Create weigts with a precision lambda_ of 4. lambda_ = 4. w = np.zeros(n_features) @@ -50,27 +52,27 @@ ############################################################################### # Plot true weights, estimated weights and histogram of the weights -pl.figure(figsize=(6, 5)) -pl.title("Weights of the model") -pl.plot(clf.coef_, 'b-', label="Bayesian Ridge estimate") -pl.plot(w, 'g-', label="Ground truth") -pl.plot(ols.coef_, 'r--', label="OLS estimate") -pl.xlabel("Features") -pl.ylabel("Values of the weights") -pl.legend(loc="best", prop=dict(size=12)) +plt.figure(figsize=(6, 5)) +plt.title("Weights of the model") +plt.plot(clf.coef_, 'b-', label="Bayesian Ridge estimate") +plt.plot(w, 'g-', label="Ground truth") +plt.plot(ols.coef_, 'r--', label="OLS estimate") +plt.xlabel("Features") +plt.ylabel("Values of the weights") +plt.legend(loc="best", prop=dict(size=12)) -pl.figure(figsize=(6, 5)) -pl.title("Histogram of the weights") -pl.hist(clf.coef_, bins=n_features, log=True) -pl.plot(clf.coef_[relevant_features], 5 * np.ones(len(relevant_features)), - 'ro', label="Relevant features") -pl.ylabel("Features") -pl.xlabel("Values of the weights") -pl.legend(loc="lower left") +plt.figure(figsize=(6, 5)) +plt.title("Histogram of the weights") +plt.hist(clf.coef_, bins=n_features, log=True) +plt.plot(clf.coef_[relevant_features], 5 * np.ones(len(relevant_features)), + 'ro', label="Relevant features") +plt.ylabel("Features") +plt.xlabel("Values of the weights") +plt.legend(loc="lower left") -pl.figure(figsize=(6, 5)) -pl.title("Marginal log-likelihood") -pl.plot(clf.scores_) -pl.ylabel("Score") -pl.xlabel("Iterations") -pl.show() +plt.figure(figsize=(6, 5)) +plt.title("Marginal log-likelihood") +plt.plot(clf.scores_) +plt.ylabel("Score") +plt.xlabel("Iterations") +plt.show() diff --git a/examples/linear_model/plot_iris_logistic.py b/examples/linear_model/plot_iris_logistic.py index cfaecba343693..4cd705dc32df3 100644 --- a/examples/linear_model/plot_iris_logistic.py +++ b/examples/linear_model/plot_iris_logistic.py @@ -5,20 +5,21 @@ ========================================================= Logistic Regression 3-class Classifier ========================================================= + Show below is a logistic-regression classifiers decision boundaries on the `iris `_ dataset. The datapoints are colored according to their labels. """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD +# Code source: Gaël Varoquaux +# Modified for documentation by Jaques Grobler +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import linear_model, datasets # import some data to play with @@ -33,7 +34,7 @@ # we create an instance of Neighbours Classifier and fit the data. logreg.fit(X, Y) -# Plot the decision boundary. For that, we will asign a color to each +# Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 @@ -42,17 +43,17 @@ # Put the result into a color plot Z = Z.reshape(xx.shape) -pl.figure(1, figsize=(4, 3)) -pl.pcolormesh(xx, yy, Z, cmap=pl.cm.Paired) +plt.figure(1, figsize=(4, 3)) +plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) # Plot also the training points -pl.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=pl.cm.Paired) -pl.xlabel('Sepal length') -pl.ylabel('Sepal width') +plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired) +plt.xlabel('Sepal length') +plt.ylabel('Sepal width') -pl.xlim(xx.min(), xx.max()) -pl.ylim(yy.min(), yy.max()) -pl.xticks(()) -pl.yticks(()) +plt.xlim(xx.min(), xx.max()) +plt.ylim(yy.min(), yy.max()) +plt.xticks(()) +plt.yticks(()) -pl.show() +plt.show() diff --git a/examples/linear_model/plot_lasso_and_elasticnet.py b/examples/linear_model/plot_lasso_and_elasticnet.py index 38558fcd558da..c9a1fbb2c3196 100644 --- a/examples/linear_model/plot_lasso_and_elasticnet.py +++ b/examples/linear_model/plot_lasso_and_elasticnet.py @@ -3,11 +3,15 @@ Lasso and Elastic Net for Sparse Signals ======================================== +Estimates Lasso and Elastic-Net regression models on a manually generated +sparse signal corrupted with an additive noise. Estimated coefficients are +compared with the ground-truth. + """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.metrics import r2_score @@ -40,24 +44,24 @@ y_pred_lasso = lasso.fit(X_train, y_train).predict(X_test) r2_score_lasso = r2_score(y_test, y_pred_lasso) -print lasso -print "r^2 on test data : %f" % r2_score_lasso +print(lasso) +print("r^2 on test data : %f" % r2_score_lasso) ############################################################################### # ElasticNet from sklearn.linear_model import ElasticNet -enet = ElasticNet(alpha=alpha, rho=0.7) +enet = ElasticNet(alpha=alpha, l1_ratio=0.7) y_pred_enet = enet.fit(X_train, y_train).predict(X_test) r2_score_enet = r2_score(y_test, y_pred_enet) -print enet -print "r^2 on test data : %f" % r2_score_enet - -pl.plot(enet.coef_, label='Elastic net coefficients') -pl.plot(lasso.coef_, label='Lasso coefficients') -pl.plot(coef, '--', label='original coefficients') -pl.legend(loc='best') -pl.title("Lasso R^2: %f, Elastic Net R^2: %f" % (r2_score_lasso, - r2_score_enet)) -pl.show() +print(enet) +print("r^2 on test data : %f" % r2_score_enet) + +plt.plot(enet.coef_, label='Elastic net coefficients') +plt.plot(lasso.coef_, label='Lasso coefficients') +plt.plot(coef, '--', label='original coefficients') +plt.legend(loc='best') +plt.title("Lasso R^2: %f, Elastic Net R^2: %f" + % (r2_score_lasso, r2_score_enet)) +plt.show() diff --git a/examples/linear_model/plot_lasso_coordinate_descent_path.py b/examples/linear_model/plot_lasso_coordinate_descent_path.py index 48e137ba30955..d4c1bd79f7f8a 100644 --- a/examples/linear_model/plot_lasso_coordinate_descent_path.py +++ b/examples/linear_model/plot_lasso_coordinate_descent_path.py @@ -8,13 +8,13 @@ The coefficients can be forced to be positive. """ -print __doc__ +print(__doc__) # Author: Alexandre Gramfort -# License: BSD Style. +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.linear_model import lasso_path, enet_path from sklearn import datasets @@ -23,72 +23,66 @@ X = diabetes.data y = diabetes.target -X /= X.std(0) # Standardize data (easier to set the rho parameter) +X /= X.std(axis=0) # Standardize data (easier to set the l1_ratio parameter) -############################################################################### # Compute paths eps = 5e-3 # the smaller it is the longer is the path -print "Computing regularization path using the lasso..." -models = lasso_path(X, y, eps=eps) -alphas_lasso = np.array([model.alpha for model in models]) -coefs_lasso = np.array([model.coef_ for model in models]) +print("Computing regularization path using the lasso...") +alphas_lasso, coefs_lasso, _ = lasso_path(X, y, eps, fit_intercept=False) -print "Computing regularization path using the positive lasso..." -models = lasso_path(X, y, eps=eps, positive=True) -alphas_positive_lasso = np.array([model.alpha for model in models]) -coefs_positive_lasso = np.array([model.coef_ for model in models]) +print("Computing regularization path using the positive lasso...") +alphas_positive_lasso, coefs_positive_lasso, _ = lasso_path( + X, y, eps, positive=True, fit_intercept=False) +print("Computing regularization path using the elastic net...") +alphas_enet, coefs_enet, _ = enet_path( + X, y, eps=eps, l1_ratio=0.8, fit_intercept=False) -print "Computing regularization path using the elastic net..." -models = enet_path(X, y, eps=eps, rho=0.8) -alphas_enet = np.array([model.alpha for model in models]) -coefs_enet = np.array([model.coef_ for model in models]) +print("Computing regularization path using the positve elastic net...") +alphas_positive_enet, coefs_positive_enet, _ = enet_path( + X, y, eps=eps, l1_ratio=0.8, positive=True, fit_intercept=False) -print "Computing regularization path using the positve elastic net..." -models = enet_path(X, y, eps=eps, rho=0.8, positive=True) -alphas_positive_enet = np.array([model.alpha for model in models]) -coefs_positive_enet = np.array([model.coef_ for model in models]) - -############################################################################### # Display results -pl.figure(1) -ax = pl.gca() +plt.figure(1) +ax = plt.gca() ax.set_color_cycle(2 * ['b', 'r', 'g', 'c', 'k']) -l1 = pl.plot(coefs_lasso) -l2 = pl.plot(coefs_enet, linestyle='--') +l1 = plt.plot(-np.log10(alphas_lasso), coefs_lasso.T) +l2 = plt.plot(-np.log10(alphas_enet), coefs_enet.T, linestyle='--') -pl.xlabel('-Log(lambda)') -pl.ylabel('weights') -pl.title('Lasso and Elastic-Net Paths') -pl.legend((l1[-1], l2[-1]), ('Lasso', 'Elastic-Net'), loc='lower left') -pl.axis('tight') +plt.xlabel('-Log(alpha)') +plt.ylabel('coefficients') +plt.title('Lasso and Elastic-Net Paths') +plt.legend((l1[-1], l2[-1]), ('Lasso', 'Elastic-Net'), loc='lower left') +plt.axis('tight') -pl.figure(2) -ax = pl.gca() +plt.figure(2) +ax = plt.gca() ax.set_color_cycle(2 * ['b', 'r', 'g', 'c', 'k']) -l1 = pl.plot(coefs_lasso) -l2 = pl.plot(coefs_positive_lasso, linestyle='--') +l1 = plt.plot(-np.log10(alphas_lasso), coefs_lasso.T) +l2 = plt.plot(-np.log10(alphas_positive_lasso), coefs_positive_lasso.T, + linestyle='--') -pl.xlabel('-Log(lambda)') -pl.ylabel('weights') -pl.title('Lasso and positive Lasso') -pl.legend((l1[-1], l2[-1]), ('Lasso', 'positive Lasso'), loc='lower left') -pl.axis('tight') +plt.xlabel('-Log(alpha)') +plt.ylabel('coefficients') +plt.title('Lasso and positive Lasso') +plt.legend((l1[-1], l2[-1]), ('Lasso', 'positive Lasso'), loc='lower left') +plt.axis('tight') -pl.figure(3) -ax = pl.gca() +plt.figure(3) +ax = plt.gca() ax.set_color_cycle(2 * ['b', 'r', 'g', 'c', 'k']) -l1 = pl.plot(coefs_enet) -l2 = pl.plot(coefs_positive_enet, linestyle='--') - -pl.xlabel('-Log(lambda)') -pl.ylabel('weights') -pl.title('Elastic-Net and positive Elastic-Net') -pl.legend((l1[-1], l2[-1]), ('Elastic-Net', 'positive Elastic-Net'), +l1 = plt.plot(-np.log10(alphas_enet), coefs_enet.T) +l2 = plt.plot(-np.log10(alphas_positive_enet), coefs_positive_enet.T, + linestyle='--') + +plt.xlabel('-Log(alpha)') +plt.ylabel('coefficients') +plt.title('Elastic-Net and positive Elastic-Net') +plt.legend((l1[-1], l2[-1]), ('Elastic-Net', 'positive Elastic-Net'), loc='lower left') -pl.axis('tight') -pl.show() +plt.axis('tight') +plt.show() diff --git a/examples/linear_model/plot_lasso_lars.py b/examples/linear_model/plot_lasso_lars.py index f868669433301..dde26ee0347dd 100644 --- a/examples/linear_model/plot_lasso_lars.py +++ b/examples/linear_model/plot_lasso_lars.py @@ -5,19 +5,19 @@ ===================== Computes Lasso Path along the regularization parameter using the LARS -algorithm on the diabetest dataset. Each color represents a different +algorithm on the diabetes dataset. Each color represents a different feature of the coefficient vector, and this is displayed as a function of the regularization parameter. """ -print __doc__ +print(__doc__) # Author: Fabian Pedregosa # Alexandre Gramfort -# License: BSD Style. +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import linear_model from sklearn import datasets @@ -26,17 +26,17 @@ X = diabetes.data y = diabetes.target -print "Computing regularization path using the LARS ..." +print("Computing regularization path using the LARS ...") alphas, _, coefs = linear_model.lars_path(X, y, method='lasso', verbose=True) xx = np.sum(np.abs(coefs.T), axis=1) xx /= xx[-1] -pl.plot(xx, coefs.T) -ymin, ymax = pl.ylim() -pl.vlines(xx, ymin, ymax, linestyle='dashed') -pl.xlabel('|coef| / max|coef|') -pl.ylabel('Coefficients') -pl.title('LASSO Path') -pl.axis('tight') -pl.show() +plt.plot(xx, coefs.T) +ymin, ymax = plt.ylim() +plt.vlines(xx, ymin, ymax, linestyle='dashed') +plt.xlabel('|coef| / max|coef|') +plt.ylabel('Coefficients') +plt.title('LASSO Path') +plt.axis('tight') +plt.show() diff --git a/examples/linear_model/plot_lasso_model_selection.py b/examples/linear_model/plot_lasso_model_selection.py index 969eebc9d8a95..10bdc9b5f1d40 100644 --- a/examples/linear_model/plot_lasso_model_selection.py +++ b/examples/linear_model/plot_lasso_model_selection.py @@ -32,7 +32,7 @@ strategy can be interesting if the number of features is really large and there are enough samples to select a large amount. In terms of numerical errors, for heavily correlated variables, Lars will accumulate -more erros, while the coordinate descent algorithm will only sample the +more errors, while the coordinate descent algorithm will only sample the path on a grid. Note how the optimal value of alpha varies for each fold. This @@ -41,15 +41,15 @@ cross-validation: this choice of parameter may not be optimal for unseen data. """ -print __doc__ +print(__doc__) # Author: Olivier Grisel, Gael Varoquaux, Alexandre Gramfort -# License: BSD Style. +# License: BSD 3 clause import time import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.linear_model import LassoCV, LassoLarsCV, LassoLarsIC from sklearn import datasets @@ -82,25 +82,25 @@ def plot_ic_criterion(model, name, color): alpha_ = model.alpha_ alphas_ = model.alphas_ criterion_ = model.criterion_ - pl.plot(-np.log10(alphas_), criterion_, '--', color=color, - linewidth=3, label='%s criterion' % name) - pl.axvline(-np.log10(alpha_), color=color, - linewidth=3, label='alpha: %s estimate' % name) - pl.xlabel('-log(alpha)') - pl.ylabel('criterion') - -pl.figure() + plt.plot(-np.log10(alphas_), criterion_, '--', color=color, + linewidth=3, label='%s criterion' % name) + plt.axvline(-np.log10(alpha_), color=color, linewidth=3, + label='alpha: %s estimate' % name) + plt.xlabel('-log(alpha)') + plt.ylabel('criterion') + +plt.figure() plot_ic_criterion(model_aic, 'AIC', 'b') plot_ic_criterion(model_bic, 'BIC', 'r') -pl.legend() -pl.title('Information-criterion for model selection (training time %.3fs)' - % t_bic) +plt.legend() +plt.title('Information-criterion for model selection (training time %.3fs)' + % t_bic) ############################################################################## # LassoCV: coordinate descent # Compute paths -print "Computing regularization path using the coordinate descent lasso..." +print("Computing regularization path using the coordinate descent lasso...") t1 = time.time() model = LassoCV(cv=20).fit(X, y) t_lasso_cv = time.time() - t1 @@ -108,28 +108,28 @@ def plot_ic_criterion(model, name, color): # Display results m_log_alphas = -np.log10(model.alphas_) -pl.figure() +plt.figure() ymin, ymax = 2300, 3800 -pl.plot(m_log_alphas, model.mse_path_, ':') -pl.plot(m_log_alphas, model.mse_path_.mean(axis=-1), 'k', - label='Average across the folds', linewidth=2) -pl.axvline(-np.log10(model.alpha), linestyle='--', color='k', - label='alpha: CV estimate') +plt.plot(m_log_alphas, model.mse_path_, ':') +plt.plot(m_log_alphas, model.mse_path_.mean(axis=-1), 'k', + label='Average across the folds', linewidth=2) +plt.axvline(-np.log10(model.alpha_), linestyle='--', color='k', + label='alpha: CV estimate') -pl.legend() +plt.legend() -pl.xlabel('-log(alpha)') -pl.ylabel('Mean square error') -pl.title('Mean square error on each fold: coordinate descent ' - '(train time: %.2fs)' % t_lasso_cv) -pl.axis('tight') -pl.ylim(ymin, ymax) +plt.xlabel('-log(alpha)') +plt.ylabel('Mean square error') +plt.title('Mean square error on each fold: coordinate descent ' + '(train time: %.2fs)' % t_lasso_cv) +plt.axis('tight') +plt.ylim(ymin, ymax) ############################################################################## # LassoLarsCV: least angle regression # Compute paths -print "Computing regularization path using the Lars lasso..." +print("Computing regularization path using the Lars lasso...") t1 = time.time() model = LassoLarsCV(cv=20).fit(X, y) t_lasso_lars_cv = time.time() - t1 @@ -137,19 +137,19 @@ def plot_ic_criterion(model, name, color): # Display results m_log_alphas = -np.log10(model.cv_alphas_) -pl.figure() -pl.plot(m_log_alphas, model.cv_mse_path_, ':') -pl.plot(m_log_alphas, model.cv_mse_path_.mean(axis=-1), 'k', - label='Average across the folds', linewidth=2) -pl.axvline(-np.log10(model.alpha), linestyle='--', color='k', - label='alpha CV') -pl.legend() - -pl.xlabel('-log(alpha)') -pl.ylabel('Mean square error') -pl.title('Mean square error on each fold: Lars (train time: %.2fs)' % - t_lasso_lars_cv) -pl.axis('tight') -pl.ylim(ymin, ymax) - -pl.show() +plt.figure() +plt.plot(m_log_alphas, model.cv_mse_path_, ':') +plt.plot(m_log_alphas, model.cv_mse_path_.mean(axis=-1), 'k', + label='Average across the folds', linewidth=2) +plt.axvline(-np.log10(model.alpha_), linestyle='--', color='k', + label='alpha CV') +plt.legend() + +plt.xlabel('-log(alpha)') +plt.ylabel('Mean square error') +plt.title('Mean square error on each fold: Lars (train time: %.2fs)' + % t_lasso_lars_cv) +plt.axis('tight') +plt.ylim(ymin, ymax) + +plt.show() diff --git a/examples/linear_model/plot_logistic.py b/examples/linear_model/plot_logistic.py index 6e5089357a7de..cdb95a7cfa563 100644 --- a/examples/linear_model/plot_logistic.py +++ b/examples/linear_model/plot_logistic.py @@ -6,24 +6,25 @@ ========================================================= Logit function ========================================================= + Show in the plot is how the logistic regression would, in this synthetic dataset, classify values as either 0 or 1, i.e. class one or two, using the logit-curve. """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# License: BSD +# Code source: Gael Varoquaux +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import linear_model # this is our test set, it's just a straight line with some -# gaussian noise +# Gaussian noise xmin, xmax = -5, 5 n_samples = 100 np.random.seed(0) @@ -38,27 +39,27 @@ clf.fit(X, y) # and plot the result -pl.figure(1, figsize=(4, 3)) -pl.clf() -pl.scatter(X.ravel(), y, color='black', zorder=20) +plt.figure(1, figsize=(4, 3)) +plt.clf() +plt.scatter(X.ravel(), y, color='black', zorder=20) X_test = np.linspace(-5, 10, 300) def model(x): return 1 / (1 + np.exp(-x)) loss = model(X_test * clf.coef_ + clf.intercept_).ravel() -pl.plot(X_test, loss, color='blue', linewidth=3) +plt.plot(X_test, loss, color='blue', linewidth=3) ols = linear_model.LinearRegression() ols.fit(X, y) -pl.plot(X_test, ols.coef_ * X_test + ols.intercept_, linewidth=1) -pl.axhline(.5, color='.5') +plt.plot(X_test, ols.coef_ * X_test + ols.intercept_, linewidth=1) +plt.axhline(.5, color='.5') -pl.ylabel('y') -pl.xlabel('X') -pl.xticks(()) -pl.yticks(()) -pl.ylim(-.25, 1.25) -pl.xlim(-4, 10) +plt.ylabel('y') +plt.xlabel('X') +plt.xticks(()) +plt.yticks(()) +plt.ylim(-.25, 1.25) +plt.xlim(-4, 10) -pl.show() +plt.show() diff --git a/examples/linear_model/plot_logistic_l1_l2_sparsity.py b/examples/linear_model/plot_logistic_l1_l2_sparsity.py index 8a89204dddad6..be63b144c260a 100644 --- a/examples/linear_model/plot_logistic_l1_l2_sparsity.py +++ b/examples/linear_model/plot_logistic_l1_l2_sparsity.py @@ -13,15 +13,15 @@ The visualization shows coefficients of the models for varying C. """ -print __doc__ +print(__doc__) # Authors: Alexandre Gramfort # Mathieu Blondel # Andreas Mueller -# License: BSD Style. +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn import datasets @@ -37,7 +37,7 @@ # Set regularization parameter -for i, C in enumerate(10. ** np.arange(1, 4)): +for i, C in enumerate((100, 1, 0.01)): # turn down tolerance for short training time clf_l1_LR = LogisticRegression(C=C, penalty='l1', tol=0.01) clf_l2_LR = LogisticRegression(C=C, penalty='l2', tol=0.01) @@ -53,27 +53,27 @@ sparsity_l1_LR = np.mean(coef_l1_LR == 0) * 100 sparsity_l2_LR = np.mean(coef_l2_LR == 0) * 100 - print "C=%d" % C - print "Sparsity with L1 penalty: %.2f%%" % sparsity_l1_LR - print "score with L1 penalty: %.4f" % clf_l1_LR.score(X, y) - print "Sparsity with L2 penalty: %.2f%%" % sparsity_l2_LR - print "score with L2 penalty: %.4f" % clf_l2_LR.score(X, y) + print("C=%.2f" % C) + print("Sparsity with L1 penalty: %.2f%%" % sparsity_l1_LR) + print("score with L1 penalty: %.4f" % clf_l1_LR.score(X, y)) + print("Sparsity with L2 penalty: %.2f%%" % sparsity_l2_LR) + print("score with L2 penalty: %.4f" % clf_l2_LR.score(X, y)) - l1_plot = pl.subplot(3, 2, 2 * i + 1) - l2_plot = pl.subplot(3, 2, 2 * (i + 1)) + l1_plot = plt.subplot(3, 2, 2 * i + 1) + l2_plot = plt.subplot(3, 2, 2 * (i + 1)) if i == 0: l1_plot.set_title("L1 penalty") l2_plot.set_title("L2 penalty") l1_plot.imshow(np.abs(coef_l1_LR.reshape(8, 8)), interpolation='nearest', - cmap='binary', vmax=1, vmin=0) + cmap='binary', vmax=1, vmin=0) l2_plot.imshow(np.abs(coef_l2_LR.reshape(8, 8)), interpolation='nearest', - cmap='binary', vmax=1, vmin=0) - pl.text(-8, 3, "C = %d" % C) + cmap='binary', vmax=1, vmin=0) + plt.text(-8, 3, "C = %.2f" % C) l1_plot.set_xticks(()) l1_plot.set_yticks(()) l2_plot.set_xticks(()) l2_plot.set_yticks(()) -pl.show() +plt.show() diff --git a/examples/linear_model/plot_logistic_path.py b/examples/linear_model/plot_logistic_path.py index 8f108f013d84c..d1b17948c78e0 100644 --- a/examples/linear_model/plot_logistic_path.py +++ b/examples/linear_model/plot_logistic_path.py @@ -7,14 +7,14 @@ Computes path on IRIS dataset. """ -print __doc__ +print(__doc__) # Author: Alexandre Gramfort -# License: BSD Style. +# License: BSD 3 clause from datetime import datetime import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import linear_model from sklearn import datasets @@ -35,7 +35,7 @@ cs = l1_min_c(X, y, loss='log') * np.logspace(0, 3) -print "Computing regularization path ..." +print("Computing regularization path ...") start = datetime.now() clf = linear_model.LogisticRegression(C=1.0, penalty='l1', tol=1e-6) coefs_ = [] @@ -43,13 +43,13 @@ clf.set_params(C=c) clf.fit(X, y) coefs_.append(clf.coef_.ravel().copy()) -print "This took ", datetime.now() - start +print("This took ", datetime.now() - start) coefs_ = np.array(coefs_) -pl.plot(np.log10(cs), coefs_) -ymin, ymax = pl.ylim() -pl.xlabel('log(C)') -pl.ylabel('Coefficients') -pl.title('Logistic Regression Path') -pl.axis('tight') -pl.show() +plt.plot(np.log10(cs), coefs_) +ymin, ymax = plt.ylim() +plt.xlabel('log(C)') +plt.ylabel('Coefficients') +plt.title('Logistic Regression Path') +plt.axis('tight') +plt.show() diff --git a/examples/linear_model/plot_multi_task_lasso_support.py b/examples/linear_model/plot_multi_task_lasso_support.py index ab7cf6bc9e9c8..940282d678d5b 100644 --- a/examples/linear_model/plot_multi_task_lasso_support.py +++ b/examples/linear_model/plot_multi_task_lasso_support.py @@ -5,7 +5,7 @@ ============================================= The multi-task lasso allows to fit multiple regression problems -jointly enforcing the selected features to be the same accross +jointly enforcing the selected features to be the same across tasks. This example simulates sequential measurements, each task is a time instant, and the relevant features vary in amplitude over time while being the same. The multi-task lasso imposes that @@ -13,12 +13,12 @@ point. This makes feature selection by the Lasso more stable. """ -print __doc__ +print(__doc__) # Author: Alexandre Gramfort -# License: BSD Style. +# License: BSD 3 clause -import pylab as pl +import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import MultiTaskLasso, Lasso @@ -41,26 +41,26 @@ ############################################################################### # Plot support and time series -fig = pl.figure(figsize=(8, 5)) -pl.subplot(1, 2, 1) -pl.spy(coef_lasso_) -pl.xlabel('Feature') -pl.ylabel('Time (or Task)') -pl.text(10, 5, 'Lasso') -pl.subplot(1, 2, 2) -pl.spy(coef_multi_task_lasso_) -pl.xlabel('Feature') -pl.ylabel('Time (or Task)') -pl.text(10, 5, 'MultiTaskLasso') +fig = plt.figure(figsize=(8, 5)) +plt.subplot(1, 2, 1) +plt.spy(coef_lasso_) +plt.xlabel('Feature') +plt.ylabel('Time (or Task)') +plt.text(10, 5, 'Lasso') +plt.subplot(1, 2, 2) +plt.spy(coef_multi_task_lasso_) +plt.xlabel('Feature') +plt.ylabel('Time (or Task)') +plt.text(10, 5, 'MultiTaskLasso') fig.suptitle('Coefficient non-zero location') feature_to_plot = 0 -pl.figure() -pl.plot(coef[:, feature_to_plot], 'k', label='Ground truth') -pl.plot(coef_lasso_[:, feature_to_plot], 'g', label='Lasso') -pl.plot(coef_multi_task_lasso_[:, feature_to_plot], - 'r', label='MultiTaskLasso') -pl.legend(loc='upper center') -pl.axis('tight') -pl.ylim([-1.1, 1.1]) -pl.show() +plt.figure() +plt.plot(coef[:, feature_to_plot], 'k', label='Ground truth') +plt.plot(coef_lasso_[:, feature_to_plot], 'g', label='Lasso') +plt.plot(coef_multi_task_lasso_[:, feature_to_plot], + 'r', label='MultiTaskLasso') +plt.legend(loc='upper center') +plt.axis('tight') +plt.ylim([-1.1, 1.1]) +plt.show() diff --git a/examples/linear_model/plot_ols.py b/examples/linear_model/plot_ols.py index beb757c8f503f..39a03d1fa0ad4 100644 --- a/examples/linear_model/plot_ols.py +++ b/examples/linear_model/plot_ols.py @@ -16,14 +16,14 @@ calculated. """ -print __doc__ +print(__doc__) # Code source: Jaques Grobler -# License: BSD +# License: BSD 3 clause -import pylab as pl +import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model @@ -50,19 +50,19 @@ regr.fit(diabetes_X_train, diabetes_y_train) # The coefficients -print 'Coefficients: \n', regr.coef_ +print('Coefficients: \n', regr.coef_) # The mean square error -print ("Residual sum of squares: %.2f" % - np.mean((regr.predict(diabetes_X_test) - diabetes_y_test) ** 2)) +print("Residual sum of squares: %.2f" + % np.mean((regr.predict(diabetes_X_test) - diabetes_y_test) ** 2)) # Explained variance score: 1 is perfect prediction -print ('Variance score: %.2f' % regr.score(diabetes_X_test, diabetes_y_test)) +print('Variance score: %.2f' % regr.score(diabetes_X_test, diabetes_y_test)) # Plot outputs -pl.scatter(diabetes_X_test, diabetes_y_test, color='black') -pl.plot(diabetes_X_test, regr.predict(diabetes_X_test), color='blue', - linewidth=3) +plt.scatter(diabetes_X_test, diabetes_y_test, color='black') +plt.plot(diabetes_X_test, regr.predict(diabetes_X_test), color='blue', + linewidth=3) -pl.xticks(()) -pl.yticks(()) +plt.xticks(()) +plt.yticks(()) -pl.show() +plt.show() diff --git a/examples/linear_model/plot_ols_3d.py b/examples/linear_model/plot_ols_3d.py index 7d65107287223..23dfa01d60ecc 100644 --- a/examples/linear_model/plot_ols_3d.py +++ b/examples/linear_model/plot_ols_3d.py @@ -9,17 +9,17 @@ Features 1 and 2 of the diabetes-dataset are fitted and plotted below. It illustrates that although feature 2 has a strong coefficient on the full model, it does not -give us much regarding `y` when compared to just feautre 1 +give us much regarding `y` when compared to just feature 1 """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD +# Code source: Gaël Varoquaux +# Modified for documentation by Jaques Grobler +# License: BSD 3 clause -import pylab as pl +import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D @@ -40,8 +40,8 @@ ############################################################################### # Plot the figure def plot_figs(fig_num, elev, azim, X_train, clf): - fig = pl.figure(fig_num, figsize=(4, 3)) - pl.clf() + fig = plt.figure(fig_num, figsize=(4, 3)) + plt.clf() ax = Axes3D(fig, elev=elev, azim=azim) ax.scatter(X_train[:, 0], X_train[:, 1], y_train, c='k', marker='+') @@ -71,4 +71,4 @@ def plot_figs(fig_num, elev, azim, X_train, clf): azim = 90 plot_figs(3, elev, azim, X_train, ols) -pl.show() +plt.show() diff --git a/examples/linear_model/plot_ols_ridge_variance.py b/examples/linear_model/plot_ols_ridge_variance.py index 8024cf4507638..a68ed005aef4c 100644 --- a/examples/linear_model/plot_ols_ridge_variance.py +++ b/examples/linear_model/plot_ols_ridge_variance.py @@ -8,7 +8,7 @@ Due to the few points in each dimension and the straight line that linear regression uses to follow these points as well as it can, noise on the observations will cause -great variace as shown in the first plot. Every line's slope +great variance as shown in the first plot. Every line's slope can vary quite a bit for each prediction due to the noise induced in the observations. @@ -20,16 +20,16 @@ in the line itself is greatly reduced, in comparison to that of the standard linear regression """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD +# Code source: Gaël Varoquaux +# Modified for documentation by Jaques Grobler +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import linear_model @@ -39,16 +39,15 @@ np.random.seed(0) -classifiers = dict( - ols=linear_model.LinearRegression(), - ridge=linear_model.Ridge(alpha=.1) - ) +classifiers = dict(ols=linear_model.LinearRegression(), + ridge=linear_model.Ridge(alpha=.1)) fignum = 1 -for name, clf in classifiers.iteritems(): - fig = pl.figure(fignum, figsize=(4, 3)) - pl.clf() - ax = pl.axes([.12, .12, .8, .8]) +for name, clf in classifiers.items(): + fig = plt.figure(fignum, figsize=(4, 3)) + plt.clf() + plt.title(name) + ax = plt.axes([.12, .12, .8, .8]) for _ in range(6): this_X = .1 * np.random.normal(size=(2, 1)) + X_train @@ -69,4 +68,4 @@ ax.set_xlim(0, 2) fignum += 1 -pl.show() +plt.show() diff --git a/examples/linear_model/plot_omp.py b/examples/linear_model/plot_omp.py index 1f6e8073c17c8..f07b7d723340a 100644 --- a/examples/linear_model/plot_omp.py +++ b/examples/linear_model/plot_omp.py @@ -6,29 +6,30 @@ Using orthogonal matching pursuit for recovering a sparse signal from a noisy measurement encoded with a dictionary """ -print __doc__ +print(__doc__) -import pylab as pl +import matplotlib.pyplot as plt import numpy as np -from sklearn.linear_model import orthogonal_mp +from sklearn.linear_model import OrthogonalMatchingPursuit +from sklearn.linear_model import OrthogonalMatchingPursuitCV from sklearn.datasets import make_sparse_coded_signal n_components, n_features = 512, 100 -n_atoms = 17 +n_nonzero_coefs = 17 # generate the data ################### -# y = Dx -# |x|_0 = n_atoms +# y = Xw +# |x|_0 = n_nonzero_coefs -y, D, x = make_sparse_coded_signal(n_samples=1, +y, X, w = make_sparse_coded_signal(n_samples=1, n_components=n_components, n_features=n_features, - n_nonzero_coefs=n_atoms, + n_nonzero_coefs=n_nonzero_coefs, random_state=0) -idx, = x.nonzero() +idx, = w.nonzero() # distort the clean signal ########################## @@ -36,30 +37,46 @@ # plot the sparse signal ######################## -pl.subplot(3, 1, 1) -pl.xlim(0, 512) -pl.title("Sparse signal") -pl.stem(idx, x[idx]) +plt.figure(figsize=(7, 7)) +plt.subplot(4, 1, 1) +plt.xlim(0, 512) +plt.title("Sparse signal") +plt.stem(idx, w[idx]) # plot the noise-free reconstruction #################################### -x_r = orthogonal_mp(D, y, n_atoms) -idx_r, = x_r.nonzero() -pl.subplot(3, 1, 2) -pl.xlim(0, 512) -pl.title("Recovered signal from noise-free measurements") -pl.stem(idx_r, x_r[idx_r]) + +omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_nonzero_coefs) +omp.fit(X, y) +coef = omp.coef_ +idx_r, = coef.nonzero() +plt.subplot(4, 1, 2) +plt.xlim(0, 512) +plt.title("Recovered signal from noise-free measurements") +plt.stem(idx_r, coef[idx_r]) # plot the noisy reconstruction ############################### -x_r = orthogonal_mp(D, y_noisy, n_atoms) -idx_r, = x_r.nonzero() -pl.subplot(3, 1, 3) -pl.xlim(0, 512) -pl.title("Recovered signal from noisy measurements") -pl.stem(idx_r, x_r[idx_r]) +omp.fit(X, y_noisy) +coef = omp.coef_ +idx_r, = coef.nonzero() +plt.subplot(4, 1, 3) +plt.xlim(0, 512) +plt.title("Recovered signal from noisy measurements") +plt.stem(idx_r, coef[idx_r]) + +# plot the noisy reconstruction with number of non-zeros set by CV +################################################################## +omp_cv = OrthogonalMatchingPursuitCV() +omp_cv.fit(X, y_noisy) +coef = omp_cv.coef_ +idx_r, = coef.nonzero() +plt.subplot(4, 1, 4) +plt.xlim(0, 512) +plt.title("Recovered signal from noisy measurements with CV") +plt.stem(idx_r, coef[idx_r]) -pl.subplots_adjust(0.06, 0.04, 0.94, 0.90, 0.20, 0.38) -pl.suptitle('Sparse signal recovery with Orthogonal Matching Pursuit', - fontsize=16) -pl.show() +plt.subplots_adjust(0.06, 0.04, 0.94, 0.90, 0.20, 0.38) +plt.suptitle('Sparse signal recovery with Orthogonal Matching Pursuit', + fontsize=16) +plt.show() diff --git a/examples/linear_model/plot_polynomial_interpolation.py b/examples/linear_model/plot_polynomial_interpolation.py index 86c800238e1e7..0327fed59208e 100644 --- a/examples/linear_model/plot_polynomial_interpolation.py +++ b/examples/linear_model/plot_polynomial_interpolation.py @@ -18,24 +18,28 @@ matrix induced by a polynomial kernel. This example shows that you can do non-linear regression with a linear model, -by manually adding non-linear features. Kernel methods extend this idea and can -induce very high (even infinite) dimensional feature spaces. +using a pipeline to add non-linear features. Kernel methods extend this idea +and can induce very high (even infinite) dimensional feature spaces. """ -print __doc__ +print(__doc__) # Author: Mathieu Blondel -# License: BSD Style. +# Jake Vanderplas +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.linear_model import Ridge +from sklearn.preprocessing import PolynomialFeatures +from sklearn.pipeline import make_pipeline def f(x): """ function to approximate by polynomial interpolation""" return x * np.sin(x) + # generate points used to plot x_plot = np.linspace(0, 10, 100) @@ -46,15 +50,19 @@ def f(x): x = np.sort(x[:20]) y = f(x) -pl.plot(x_plot, f(x_plot), label="ground truth") -pl.scatter(x, y, label="training points") +# create matrix versions of these arrays +X = x[:, np.newaxis] +X_plot = x_plot[:, np.newaxis] + +plt.plot(x_plot, f(x_plot), label="ground truth") +plt.scatter(x, y, label="training points") for degree in [3, 4, 5]: - ridge = Ridge() - ridge.fit(np.vander(x, degree + 1), y) - pl.plot(x_plot, ridge.predict(np.vander(x_plot, degree + 1)), - label="degree %d" % degree) + model = make_pipeline(PolynomialFeatures(degree), Ridge()) + model.fit(X, y) + y_plot = model.predict(X_plot) + plt.plot(x_plot, y_plot, label="degree %d" % degree) -pl.legend(loc='lower left') +plt.legend(loc='lower left') -pl.show() +plt.show() diff --git a/examples/linear_model/plot_ransac.py b/examples/linear_model/plot_ransac.py new file mode 100644 index 0000000000000..5e93e55290bdb --- /dev/null +++ b/examples/linear_model/plot_ransac.py @@ -0,0 +1,53 @@ +""" +=========================================== +Robust linear model estimation using RANSAC +=========================================== + +In this example we see how to robustly fit a linear model to faulty data using +the RANSAC algorithm. + +""" +import numpy as np +from matplotlib import pyplot as plt + +from sklearn import linear_model, datasets + + +n_samples = 1000 +n_outliers = 50 + + +X, y, coef = datasets.make_regression(n_samples=n_samples, n_features=1, + n_informative=1, noise=10, + coef=True, random_state=0) + +# Add outlier data +np.random.seed(0) +X[:n_outliers] = 3 + 0.5 * np.random.normal(size=(n_outliers, 1)) +y[:n_outliers] = -3 + 10 * np.random.normal(size=n_outliers) + +# Fit line using all data +model = linear_model.LinearRegression() +model.fit(X, y) + +# Robustly fit linear model with RANSAC algorithm +model_ransac = linear_model.RANSACRegressor(linear_model.LinearRegression()) +model_ransac.fit(X, y) +inlier_mask = model_ransac.inlier_mask_ +outlier_mask = np.logical_not(inlier_mask) + +# Predict data of estimated models +line_X = np.arange(-5, 5) +line_y = model.predict(line_X[:, np.newaxis]) +line_y_ransac = model_ransac.predict(line_X[:, np.newaxis]) + +# Compare estimated coefficients +print("Estimated coefficients (true, normal, RANSAC):") +print(coef, model.coef_, model_ransac.estimator_.coef_) + +plt.plot(X[inlier_mask], y[inlier_mask], '.g', label='Inliers') +plt.plot(X[outlier_mask], y[outlier_mask], '.r', label='Outliers') +plt.plot(line_X, line_y, '-k', label='Linear regressor') +plt.plot(line_X, line_y_ransac, '-b', label='RANSAC regressor') +plt.legend(loc='lower right') +plt.show() diff --git a/examples/linear_model/plot_ridge_path.py b/examples/linear_model/plot_ridge_path.py index 10776dfc51f94..46e5e6036d2f6 100644 --- a/examples/linear_model/plot_ridge_path.py +++ b/examples/linear_model/plot_ridge_path.py @@ -3,10 +3,12 @@ Plot Ridge coefficients as a function of the regularization =========================================================== +Shows the effect of collinearity in the coefficients of an estimator. + .. currentmodule:: sklearn.linear_model -Shows the effect of collinearity in the coefficients or the -:class:`Ridge`. Each color represents a different feature of the +:class:`Ridge` Regression is the estimator used in this example. +Each color represents a different feature of the coefficient vector, and this is displayed as a function of the regularization parameter. @@ -16,12 +18,12 @@ """ # Author: Fabian Pedregosa -- -# License: BSD Style. +# License: BSD 3 clause -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import linear_model # X is the 10x10 Hilbert matrix @@ -44,14 +46,14 @@ ############################################################################### # Display results -ax = pl.gca() +ax = plt.gca() ax.set_color_cycle(['b', 'r', 'g', 'c', 'k', 'y', 'm']) ax.plot(alphas, coefs) ax.set_xscale('log') ax.set_xlim(ax.get_xlim()[::-1]) # reverse axis -pl.xlabel('alpha') -pl.ylabel('weights') -pl.title('Ridge coefficients as a function of the regularization') -pl.axis('tight') -pl.show() +plt.xlabel('alpha') +plt.ylabel('weights') +plt.title('Ridge coefficients as a function of the regularization') +plt.axis('tight') +plt.show() diff --git a/examples/linear_model/plot_robust_fit.py b/examples/linear_model/plot_robust_fit.py new file mode 100644 index 0000000000000..19b7b897c22cc --- /dev/null +++ b/examples/linear_model/plot_robust_fit.py @@ -0,0 +1,87 @@ +""" +Robust linear estimator fitting +=============================== + +Here a sine function is fit with a polynomial of order 3, for values +close to zero. + +Robust fitting is demoed in different situations: + +- No measurement errors, only modelling errors (fitting a sine with a + polynomial) + +- Measurement errors in X + +- Measurement errors in y + +The median absolute deviation to non corrupt new data is used to judge +the quality of the prediction. + +What we can see that: + +- RANSAC is good for strong outliers in the y direction + +- TheilSen is good for small outliers, both in direction X and y, but has + a break point above which it performs worst than OLS. + +""" + +from matplotlib import pyplot as plt +import numpy as np + +from sklearn import linear_model, metrics +from sklearn.preprocessing import PolynomialFeatures +from sklearn.pipeline import make_pipeline + +np.random.seed(42) + +X = np.random.normal(size=400) +y = np.sin(X) +# Make sure that it X is 2D +X = X[:, np.newaxis] + +X_test = np.random.normal(size=200) +y_test = np.sin(X_test) +X_test = X_test[:, np.newaxis] + +y_errors = y.copy() +y_errors[::3] = 3 + +X_errors = X.copy() +X_errors[::3] = 3 + +y_errors_large = y.copy() +y_errors_large[::3] = 10 + +X_errors_large = X.copy() +X_errors_large[::3] = 10 + +estimators = [('OLS', linear_model.LinearRegression()), + ('Theil-Sen', linear_model.TheilSenRegressor(random_state=42)), + ('RANSAC', linear_model.RANSACRegressor(random_state=42)), ] + +x_plot = np.linspace(X.min(), X.max()) + +for title, this_X, this_y in [ + ('Modeling errors only', X, y), + ('Corrupt X, small deviants', X_errors, y), + ('Corrupt y, small deviants', X, y_errors), + ('Corrupt X, large deviants', X_errors_large, y), + ('Corrupt y, large deviants', X, y_errors_large)]: + plt.figure(figsize=(5, 4)) + plt.plot(this_X[:, 0], this_y, 'k+') + + for name, estimator in estimators: + model = make_pipeline(PolynomialFeatures(3), estimator) + model.fit(this_X, this_y) + mse = metrics.mean_squared_error(model.predict(X_test), y_test) + y_plot = model.predict(x_plot[:, np.newaxis]) + plt.plot(x_plot, y_plot, + label='%s: error = %.3f' % (name, mse)) + + plt.legend(loc='best', frameon=False, + title='Error: mean absolute deviation\n to non corrupt data') + plt.xlim(-4, 10.2) + plt.ylim(-2, 10.2) + plt.title(title) +plt.show() diff --git a/examples/linear_model/plot_sgd_comparison.py b/examples/linear_model/plot_sgd_comparison.py new file mode 100644 index 0000000000000..123aff9f06a6b --- /dev/null +++ b/examples/linear_model/plot_sgd_comparison.py @@ -0,0 +1,55 @@ +""" +================================== +Comparing various online solvers +================================== + +An example showing how different online solvers perform +on the hand-written digits dataset. + +""" +# Author: Rob Zinkov +# License: BSD 3 clause + +import numpy as np +import matplotlib.pyplot as plt +from sklearn import datasets + +from sklearn.cross_validation import train_test_split +from sklearn.linear_model import SGDClassifier, Perceptron +from sklearn.linear_model import PassiveAggressiveClassifier + +heldout = [0.95, 0.90, 0.75, 0.50, 0.01] +rounds = 20 +digits = datasets.load_digits() +X, y = digits.data, digits.target + +classifiers = [ + ("SGD", SGDClassifier()), + ("ASGD", SGDClassifier(average=True)), + ("Perceptron", Perceptron()), + ("Passive-Aggressive I", PassiveAggressiveClassifier(loss='hinge', + C=1.0)), + ("Passive-Aggressive II", PassiveAggressiveClassifier(loss='squared_hinge', + C=1.0)), +] + +xx = 1. - np.array(heldout) + +for name, clf in classifiers: + rng = np.random.RandomState(42) + yy = [] + for i in heldout: + yy_ = [] + for r in range(rounds): + X_train, X_test, y_train, y_test = \ + train_test_split(X, y, test_size=i, random_state=rng) + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + yy_.append(1 - np.mean(y_pred == y_test)) + yy.append(np.mean(yy_)) + plt.plot(xx, yy, label=name) + +plt.legend(loc="upper right") +plt.xlabel("Proportion train") +plt.ylabel("Test Error Rate") +plt.show() diff --git a/examples/linear_model/plot_sgd_iris.py b/examples/linear_model/plot_sgd_iris.py index a5dab6ace6a36..cd2c8dd6b03f5 100644 --- a/examples/linear_model/plot_sgd_iris.py +++ b/examples/linear_model/plot_sgd_iris.py @@ -8,10 +8,10 @@ are represented by the dashed lines. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import datasets from sklearn.linear_model import SGDClassifier @@ -44,25 +44,25 @@ xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) -# Plot the decision boundary. For that, we will asign a color to each +# Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) -cs = pl.contourf(xx, yy, Z, cmap=pl.cm.Paired) -pl.axis('tight') +cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired) +plt.axis('tight') # Plot also the training points for i, color in zip(clf.classes_, colors): idx = np.where(y == i) - pl.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i], - cmap=pl.cm.Paired) -pl.title("Decision surface of multi-class SGD") -pl.axis('tight') + plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i], + cmap=plt.cm.Paired) +plt.title("Decision surface of multi-class SGD") +plt.axis('tight') # Plot the three one-against-all classifiers -xmin, xmax = pl.xlim() -ymin, ymax = pl.ylim() +xmin, xmax = plt.xlim() +ymin, ymax = plt.ylim() coef = clf.coef_ intercept = clf.intercept_ @@ -71,10 +71,10 @@ def plot_hyperplane(c, color): def line(x0): return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1] - pl.plot([xmin, xmax], [line(xmin), line(xmax)], - ls="--", color=color) + plt.plot([xmin, xmax], [line(xmin), line(xmax)], + ls="--", color=color) for i, color in zip(clf.classes_, colors): plot_hyperplane(i, color) -pl.legend() -pl.show() +plt.legend() +plt.show() diff --git a/examples/linear_model/plot_sgd_loss_functions.py b/examples/linear_model/plot_sgd_loss_functions.py index 8d66b513f8cf7..c2668dd6d760b 100644 --- a/examples/linear_model/plot_sgd_loss_functions.py +++ b/examples/linear_model/plot_sgd_loss_functions.py @@ -1,41 +1,41 @@ """ ========================== -SGD: Convex Loss Functions +SGD: convex loss functions ========================== -Plot the convex loss functions supported by -`sklearn.linear_model.stochastic_gradient`. +A plot that compares the various convex loss functions supported by +:class:`sklearn.linear_model.SGDClassifier` . """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl -from sklearn.linear_model.sgd_fast import Hinge, \ - ModifiedHuber, SquaredLoss +import matplotlib.pyplot as plt -############################################################################### -# Define loss funcitons -xmin, xmax = -3, 3 -hinge = Hinge(1) -log_loss = lambda z, p: np.log2(1.0 + np.exp(-z)) -modified_huber = ModifiedHuber() -squared_loss = SquaredLoss() -############################################################################### -# Plot loss funcitons +def modified_huber_loss(y_true, y_pred): + z = y_pred * y_true + loss = -4 * z + loss[z >= -1] = (1 - z[z >= -1]) ** 2 + loss[z >= 1.] = 0 + return loss + + +xmin, xmax = -4, 4 xx = np.linspace(xmin, xmax, 100) -pl.plot([xmin, 0, 0, xmax], [1, 1, 0, 0], 'k-', - label="Zero-one loss") -pl.plot(xx, [hinge.loss(x, 1) for x in xx], 'g-', - label="Hinge loss") -pl.plot(xx, [log_loss(x, 1) for x in xx], 'r-', - label="Log loss") -pl.plot(xx, [modified_huber.loss(x, 1) for x in xx], 'y-', - label="Modified huber loss") -#pl.plot(xx, [2.0*squared_loss.loss(x, 1) for x in xx], 'c-', -# label="Squared loss") -pl.ylim((0, 5)) -pl.legend(loc="upper right") -pl.xlabel(r"$y \cdot f(x)$") -pl.ylabel("$L(y, f(x))$") -pl.show() +plt.plot([xmin, 0, 0, xmax], [1, 1, 0, 0], 'k-', + label="Zero-one loss") +plt.plot(xx, np.where(xx < 1, 1 - xx, 0), 'g-', + label="Hinge loss") +plt.plot(xx, -np.minimum(xx, 0), 'm-', + label="Perceptron loss") +plt.plot(xx, np.log2(1 + np.exp(-xx)), 'r-', + label="Log loss") +plt.plot(xx, np.where(xx < 1, 1 - xx, 0) ** 2, 'b-', + label="Squared hinge loss") +plt.plot(xx, modified_huber_loss(xx, 1), 'y--', + label="Modified Huber loss") +plt.ylim((0, 8)) +plt.legend(loc="upper right") +plt.xlabel(r"Decision function $f(x)$") +plt.ylabel("$L(y, f(x))$") +plt.show() diff --git a/examples/linear_model/plot_sgd_ols.py b/examples/linear_model/plot_sgd_ols.py deleted file mode 100644 index dcf3db8151db8..0000000000000 --- a/examples/linear_model/plot_sgd_ols.py +++ /dev/null @@ -1,29 +0,0 @@ -""" -=============================== -Ordinary Least Squares with SGD -=============================== - -Simple Ordinary Least Squares example with stochastic -gradient descent, we draw the linear least -squares solution for a random set of points in the plane. -""" -print __doc__ - -import pylab as pl - -from sklearn.linear_model import SGDRegressor -from sklearn.datasets.samples_generator import make_regression - -# this is our test set, it's just a straight line with some -# gaussian noise -X, Y = make_regression(n_samples=100, n_features=1, n_informative=1,\ - random_state=0, noise=35) - -# run the classifier -clf = SGDRegressor(alpha=0.1, n_iter=20) -clf.fit(X, Y) - -# and plot the result -pl.scatter(X, Y, color='black') -pl.plot(X, clf.predict(X), color='blue', linewidth=3) -pl.show() diff --git a/examples/linear_model/plot_sgd_penalties.py b/examples/linear_model/plot_sgd_penalties.py index 40617a13bfe71..077ee62823f3c 100644 --- a/examples/linear_model/plot_sgd_penalties.py +++ b/examples/linear_model/plot_sgd_penalties.py @@ -3,15 +3,17 @@ SGD: Penalties ============== -Plot the contours of the three penalties supported by -`sklearn.linear_model.stochastic_gradient`. +Plot the contours of the three penalties. + +All of the above are supported by +:class:`sklearn.linear_model.stochastic_gradient`. """ from __future__ import division -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt def l1(xs): @@ -33,8 +35,8 @@ def el(xs, z): def cross(ext): - pl.plot([-ext, ext], [0, 0], "k-") - pl.plot([0, 0], [-ext, ext], "k-") + plt.plot([-ext, ext], [0, 0], "k-") + plt.plot([0, 0], [-ext, ext], "k-") xs = np.linspace(0, 1, 100) @@ -42,24 +44,24 @@ def cross(ext): cross(1.2) -pl.plot(xs, l1(xs), "r-", label="L1") -pl.plot(xs, -1.0 * l1(xs), "r-") -pl.plot(-1 * xs, l1(xs), "r-") -pl.plot(-1 * xs, -1.0 * l1(xs), "r-") +plt.plot(xs, l1(xs), "r-", label="L1") +plt.plot(xs, -1.0 * l1(xs), "r-") +plt.plot(-1 * xs, l1(xs), "r-") +plt.plot(-1 * xs, -1.0 * l1(xs), "r-") -pl.plot(xs, l2(xs), "b-", label="L2") -pl.plot(xs, -1.0 * l2(xs), "b-") -pl.plot(-1 * xs, l2(xs), "b-") -pl.plot(-1 * xs, -1.0 * l2(xs), "b-") +plt.plot(xs, l2(xs), "b-", label="L2") +plt.plot(xs, -1.0 * l2(xs), "b-") +plt.plot(-1 * xs, l2(xs), "b-") +plt.plot(-1 * xs, -1.0 * l2(xs), "b-") -pl.plot(xs, el(xs, alpha), "y-", label="Elastic Net") -pl.plot(xs, -1.0 * el(xs, alpha), "y-") -pl.plot(-1 * xs, el(xs, alpha), "y-") -pl.plot(-1 * xs, -1.0 * el(xs, alpha), "y-") +plt.plot(xs, el(xs, alpha), "y-", label="Elastic Net") +plt.plot(xs, -1.0 * el(xs, alpha), "y-") +plt.plot(-1 * xs, el(xs, alpha), "y-") +plt.plot(-1 * xs, -1.0 * el(xs, alpha), "y-") -pl.xlabel(r"$w_0$") -pl.ylabel(r"$w_1$") -pl.legend() +plt.xlabel(r"$w_0$") +plt.ylabel(r"$w_1$") +plt.legend() -pl.axis("equal") -pl.show() +plt.axis("equal") +plt.show() diff --git a/examples/linear_model/plot_sgd_separating_hyperplane.py b/examples/linear_model/plot_sgd_separating_hyperplane.py index a61839b17f88e..f3a7d9a53bce2 100644 --- a/examples/linear_model/plot_sgd_separating_hyperplane.py +++ b/examples/linear_model/plot_sgd_separating_hyperplane.py @@ -7,10 +7,10 @@ separable dataset using a linear Support Vector Machines classifier trained using SGD. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.linear_model import SGDClassifier from sklearn.datasets.samples_generator import make_blobs @@ -35,8 +35,8 @@ levels = [-1.0, 0.0, 1.0] linestyles = ['dashed', 'solid', 'dashed'] colors = 'k' -pl.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles) -pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired) +plt.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles) +plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired) -pl.axis('tight') -pl.show() +plt.axis('tight') +plt.show() diff --git a/examples/linear_model/plot_sgd_weighted_classes.py b/examples/linear_model/plot_sgd_weighted_classes.py deleted file mode 100644 index 1896356f155a7..0000000000000 --- a/examples/linear_model/plot_sgd_weighted_classes.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -================================================ -SGD: Separating hyperplane with weighted classes -================================================ - -Fit linear SVMs with and without class weighting. -Allows to handle problems with unbalanced classes. - -""" -print __doc__ - -import numpy as np -import pylab as pl -from sklearn.linear_model import SGDClassifier - -# we create 40 separable points -np.random.seed(0) -n_samples_1 = 1000 -n_samples_2 = 100 -X = np.r_[1.5 * np.random.randn(n_samples_1, 2), - 0.5 * np.random.randn(n_samples_2, 2) + [2, 2]] -y = np.array([0] * (n_samples_1) + [1] * (n_samples_2), dtype=np.float64) -idx = np.arange(y.shape[0]) -np.random.shuffle(idx) -X = X[idx] -y = y[idx] -mean = X.mean(axis=0) -std = X.std(axis=0) -X = (X - mean) / std - -# fit the model and get the separating hyperplane -clf = SGDClassifier(n_iter=100, alpha=0.01) -clf.fit(X, y) - -w = clf.coef_.ravel() -a = -w[0] / w[1] -xx = np.linspace(-5, 5) -yy = a * xx - clf.intercept_ / w[1] - - -# get the separating hyperplane using weighted classes -wclf = SGDClassifier(n_iter=100, alpha=0.01, class_weight={1: 10}) -wclf.fit(X, y) - -ww = wclf.coef_.ravel() -wa = -ww[0] / ww[1] -wyy = wa * xx - wclf.intercept_ / ww[1] - -# plot separating hyperplanes and samples -h0 = pl.plot(xx, yy, 'k-', label='no weights') -h1 = pl.plot(xx, wyy, 'k--', label='with weights') -pl.scatter(X[:, 0], X[:, 1], c=y, cmap=pl.cm.Paired) -pl.legend() - -pl.axis('tight') -pl.show() diff --git a/examples/linear_model/plot_sgd_weighted_samples.py b/examples/linear_model/plot_sgd_weighted_samples.py index 086a5de528eb1..15dd72866f4df 100644 --- a/examples/linear_model/plot_sgd_weighted_samples.py +++ b/examples/linear_model/plot_sgd_weighted_samples.py @@ -6,10 +6,10 @@ Plot decision function of a weighted dataset, where the size of points is proportional to its weight. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import linear_model # we create 20 points @@ -22,27 +22,27 @@ # plot the weighted data points xx, yy = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500)) -pl.figure() -pl.scatter(X[:, 0], X[:, 1], c=y, s=sample_weight, alpha=0.9, - cmap=pl.cm.bone) +plt.figure() +plt.scatter(X[:, 0], X[:, 1], c=y, s=sample_weight, alpha=0.9, + cmap=plt.cm.bone) ## fit the unweighted model clf = linear_model.SGDClassifier(alpha=0.01, n_iter=100) clf.fit(X, y) Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) -no_weights = pl.contour(xx, yy, Z, levels=[0], linestyles=['solid']) +no_weights = plt.contour(xx, yy, Z, levels=[0], linestyles=['solid']) ## fit the weighted model clf = linear_model.SGDClassifier(alpha=0.01, n_iter=100) clf.fit(X, y, sample_weight=sample_weight) Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) -samples_weights = pl.contour(xx, yy, Z, levels=[0], linestyles=['dashed']) +samples_weights = plt.contour(xx, yy, Z, levels=[0], linestyles=['dashed']) -pl.legend([no_weights.collections[0], samples_weights.collections[0]], - ["no weights", "with weights"], loc="lower left") +plt.legend([no_weights.collections[0], samples_weights.collections[0]], + ["no weights", "with weights"], loc="lower left") -pl.xticks(()) -pl.yticks(()) -pl.show() +plt.xticks(()) +plt.yticks(()) +plt.show() diff --git a/examples/linear_model/plot_sparse_recovery.py b/examples/linear_model/plot_sparse_recovery.py index 05f62341b2d3e..00bb5cd7ef8ff 100644 --- a/examples/linear_model/plot_sparse_recovery.py +++ b/examples/linear_model/plot_sparse_recovery.py @@ -12,16 +12,16 @@ As detailed in :ref:`the compressive sensing notes `, the ability of L1-based approach to identify the relevant variables depends on the sparsity of the ground truth, the -number of samples, the number of features, the conditionning of the +number of samples, the number of features, the conditioning of the design matrix on the signal subspace, the amount of noise, and the absolute value of the smallest non-zero coefficient [Wainwright2006] (http://statistics.berkeley.edu/tech-reports/709.pdf). -Here we keep all parameters constant and vary the conditionning of the -design matrix. For a well-conditionned design matrix (small mutual +Here we keep all parameters constant and vary the conditioning of the +design matrix. For a well-conditioned design matrix (small mutual incoherence) we are exactly in compressive sensing conditions (i.i.d Gaussian sensing matrix), and L1-recovery with the Lasso performs very -well. For an ill-conditionned matrix (high mutual incoherence), +well. For an ill-conditioned matrix (high mutual incoherence), regressors are very correlated, and the Lasso randomly selects one. However, randomized-Lasso can recover the ground truth well. @@ -38,35 +38,36 @@ feature selection methods, using the area under curve (AUC) of the precision-recall. """ -print __doc__ +print(__doc__) # Author: Alexandre Gramfort and Gael Varoquaux -# License: BSD +# License: BSD 3 clause -import pylab as pl +import warnings + +import matplotlib.pyplot as plt import numpy as np from scipy import linalg -from sklearn.linear_model import RandomizedLasso, lasso_stability_path, \ - LassoLarsCV +from sklearn.linear_model import (RandomizedLasso, lasso_stability_path, + LassoLarsCV) from sklearn.feature_selection import f_regression from sklearn.preprocessing import StandardScaler from sklearn.metrics import auc, precision_recall_curve from sklearn.ensemble import ExtraTreesRegressor from sklearn.utils.extmath import pinvh +from sklearn.utils import ConvergenceWarning def mutual_incoherence(X_relevant, X_irelevant): """Mutual incoherence, as defined by formula (26a) of [Wainwright2006]. """ - projector = np.dot( - np.dot(X_irelevant.T, X_relevant), - pinvh(np.dot(X_relevant.T, X_relevant)) - ) + projector = np.dot(np.dot(X_irelevant.T, X_relevant), + pinvh(np.dot(X_relevant.T, X_relevant))) return np.max(np.abs(projector).sum(axis=1)) -for conditionning in (1, 1e-4): +for conditioning in (1, 1e-4): ########################################################################### # Simulate regression data with a correlated design n_features = 501 @@ -74,7 +75,7 @@ def mutual_incoherence(X_relevant, X_irelevant): noise_level = .2 coef_min = .2 # The Donoho-Tanner phase transition is around n_samples=25: below we - # will completely fail to recover in the well-conditionned case + # will completely fail to recover in the well-conditioned case n_samples = 25 block_size = n_relevant_features @@ -87,7 +88,7 @@ def mutual_incoherence(X_relevant, X_irelevant): # The correlation of our design: variables correlated by blocs of 3 corr = np.zeros((n_features, n_features)) for i in range(0, n_features, block_size): - corr[i:i + block_size, i:i + block_size] = 1 - conditionning + corr[i:i + block_size, i:i + block_size] = 1 - conditioning corr.flat[::n_features + 1] = 1 corr = linalg.cholesky(corr) @@ -96,7 +97,7 @@ def mutual_incoherence(X_relevant, X_irelevant): X = np.dot(X, corr) # Keep [Wainwright2006] (26c) constant X[:n_relevant_features] /= np.abs( - linalg.svdvals(X[:n_relevant_features])).max() + linalg.svdvals(X[:n_relevant_features])).max() X = StandardScaler().fit_transform(X.copy()) # The output variable @@ -111,58 +112,63 @@ def mutual_incoherence(X_relevant, X_irelevant): ########################################################################### # Plot stability selection path, using a high eps for early stopping # of the path, to save computation time - alpha_grid, scores_path = lasso_stability_path(X, y, - random_state=42, eps=0.05) + alpha_grid, scores_path = lasso_stability_path(X, y, random_state=42, + eps=0.05) - pl.figure() + plt.figure() # We plot the path as a function of alpha/alpha_max to the power 1/3: the # power 1/3 scales the path less brutally than the log, and enables to # see the progression along the path - hg = pl.plot(alpha_grid[1:] ** .333, scores_path[coef != 0].T[1:], 'r') - hb = pl.plot(alpha_grid[1:] ** .333, scores_path[coef == 0].T[1:], 'k') - ymin, ymax = pl.ylim() - pl.xlabel(r'$(\alpha / \alpha_{max})^{1/3}$') - pl.ylabel('Stability score: proportion of times selected') - pl.title('Stability Scores Path - Mutual incoherence: %.1f' % mi) - pl.axis('tight') - pl.legend((hg[0], hb[0]), ('relevant features', 'irrelevant features'), - loc='best') + hg = plt.plot(alpha_grid[1:] ** .333, scores_path[coef != 0].T[1:], 'r') + hb = plt.plot(alpha_grid[1:] ** .333, scores_path[coef == 0].T[1:], 'k') + ymin, ymax = plt.ylim() + plt.xlabel(r'$(\alpha / \alpha_{max})^{1/3}$') + plt.ylabel('Stability score: proportion of times selected') + plt.title('Stability Scores Path - Mutual incoherence: %.1f' % mi) + plt.axis('tight') + plt.legend((hg[0], hb[0]), ('relevant features', 'irrelevant features'), + loc='best') ########################################################################### # Plot the estimated stability scores for a given alpha # Use 6-fold cross-validation rather than the default 3-fold: it leads to # a better choice of alpha: - lars_cv = LassoLarsCV(cv=6).fit(X, y) + # Stop the user warnings outputs- they are not necessary for the example + # as it is specifically set up to be challenging. + with warnings.catch_warnings(): + warnings.simplefilter('ignore', UserWarning) + warnings.simplefilter('ignore', ConvergenceWarning) + lars_cv = LassoLarsCV(cv=6).fit(X, y) # Run the RandomizedLasso: we use a paths going down to .1*alpha_max # to avoid exploring the regime in which very noisy variables enter # the model alphas = np.linspace(lars_cv.alphas_[0], .1 * lars_cv.alphas_[0], 6) clf = RandomizedLasso(alpha=alphas, random_state=42).fit(X, y) - trees = ExtraTreesRegressor(100, compute_importances=True).fit(X, y) + trees = ExtraTreesRegressor(100).fit(X, y) # Compare with F-score F, _ = f_regression(X, y) - pl.figure() + plt.figure() for name, score in [('F-test', F), - ('Stability selection', clf.scores_), - ('Lasso coefs', np.abs(lars_cv.coef_)), - ('Trees', trees.feature_importances_), - ]: + ('Stability selection', clf.scores_), + ('Lasso coefs', np.abs(lars_cv.coef_)), + ('Trees', trees.feature_importances_), + ]: precision, recall, thresholds = precision_recall_curve(coef != 0, score) - pl.semilogy(np.maximum(score / np.max(score), 1e-4), - label="%s. AUC: %.3f" % (name, auc(recall, precision))) + plt.semilogy(np.maximum(score / np.max(score), 1e-4), + label="%s. AUC: %.3f" % (name, auc(recall, precision))) - pl.plot(np.where(coef != 0)[0], [2e-4] * n_relevant_features, 'mo', - label="Ground truth") - pl.xlabel("Features") - pl.ylabel("Score") + plt.plot(np.where(coef != 0)[0], [2e-4] * n_relevant_features, 'mo', + label="Ground truth") + plt.xlabel("Features") + plt.ylabel("Score") # Plot only the 100 first coefficients - pl.xlim(0, 100) - pl.legend(loc='best') - pl.title('Feature selection scores - Mutual incoherence: %.1f' - % mi) + plt.xlim(0, 100) + plt.legend(loc='best') + plt.title('Feature selection scores - Mutual incoherence: %.1f' + % mi) -pl.show() +plt.show() diff --git a/examples/linear_model/plot_theilsen.py b/examples/linear_model/plot_theilsen.py new file mode 100644 index 0000000000000..fc0ba571cc76f --- /dev/null +++ b/examples/linear_model/plot_theilsen.py @@ -0,0 +1,108 @@ +""" +==================== +Theil-Sen Regression +==================== + +Computes a Theil-Sen Regression on a synthetic dataset. + +See :ref:`theil_sen_regression` for more information on the regressor. + +Compared to the OLS (ordinary least squares) estimator, the Theil-Sen +estimator is robust against outliers. It has a breakdown point of about 29.3% +in case of a simple linear regression which means that it can tolerate +arbitrary corrupted data (outliers) of up to 29.3% in the two-dimensional +case. + +The estimation of the model is done by calculating the slopes and intercepts +of a subpopulation of all possible combinations of p subsample points. If an +intercept is fitted, p must be greater than or equal to n_features + 1. The +final slope and intercept is then defined as the spatial median of these +slopes and intercepts. + +In certain cases Theil-Sen performs better than :ref:`RANSAC +` which is also a robust method. This is illustrated in the +second example below where outliers with respect to the x-axis perturb RANSAC. +Tuning the ``residual_threshold`` parameter of RANSAC remedies this but in +general a priori knowledge about the data and the nature of the outliers is +needed. +Due to the computational complexity of Theil-Sen it is recommended to use it +only for small problems in terms of number of samples and features. For larger +problems the ``max_subpopulation`` parameter restricts the magnitude of all +possible combinations of p subsample points to a randomly chosen subset and +therefore also limits the runtime. Therefore, Theil-Sen is applicable to larger +problems with the drawback of losing some of its mathematical properties since +it then works on a random subset. +""" + +# Author: Florian Wilhelm -- +# License: BSD 3 clause + +import time +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression, TheilSenRegressor +from sklearn.linear_model import RANSACRegressor + +print(__doc__) + +estimators = [('OLS', LinearRegression()), + ('Theil-Sen', TheilSenRegressor(random_state=42)), + ('RANSAC', RANSACRegressor(random_state=42)), ] + +############################################################################## +# Outliers only in the y direction + +np.random.seed(0) +n_samples = 200 +# Linear model y = 3*x + N(2, 0.1**2) +x = np.random.randn(n_samples) +w = 3. +c = 2. +noise = 0.1 * np.random.randn(n_samples) +y = w * x + c + noise +# 10% outliers +y[-20:] += -20 * x[-20:] +X = x[:, np.newaxis] + +plt.plot(x, y, 'k+', mew=2, ms=8) +line_x = np.array([-3, 3]) +for name, estimator in estimators: + t0 = time.time() + estimator.fit(X, y) + elapsed_time = time.time() - t0 + y_pred = estimator.predict(line_x.reshape(2, 1)) + plt.plot(line_x, y_pred, + label='%s (fit time: %.2fs)' % (name, elapsed_time)) + +plt.axis('tight') +plt.legend(loc='upper left') + + +############################################################################## +# Outliers in the X direction + +np.random.seed(0) +# Linear model y = 3*x + N(2, 0.1**2) +x = np.random.randn(n_samples) +noise = 0.1 * np.random.randn(n_samples) +y = 3 * x + 2 + noise +# 10% outliers +x[-20:] = 9.9 +y[-20:] += 22 +X = x[:, np.newaxis] + +plt.figure() +plt.plot(x, y, 'k+', mew=2, ms=8) + +line_x = np.array([-3, 10]) +for name, estimator in estimators: + t0 = time.time() + estimator.fit(X, y) + elapsed_time = time.time() - t0 + y_pred = estimator.predict(line_x.reshape(2, 1)) + plt.plot(line_x, y_pred, + label='%s (fit time: %.2fs)' % (name, elapsed_time)) + +plt.axis('tight') +plt.legend(loc='upper left') +plt.show() diff --git a/examples/manifold/README.txt b/examples/manifold/README.txt index 2fc8b89aaf65e..bf12be84b21ab 100644 --- a/examples/manifold/README.txt +++ b/examples/manifold/README.txt @@ -3,5 +3,5 @@ Manifold learning ----------------------- -Examples concerning the :mod:`sklearn.manifold` package. +Examples concerning the :mod:`sklearn.manifold` module. diff --git a/examples/manifold/plot_compare_methods.py b/examples/manifold/plot_compare_methods.py index 97d6d63b25cea..08ae4082cc2e0 100644 --- a/examples/manifold/plot_compare_methods.py +++ b/examples/manifold/plot_compare_methods.py @@ -9,6 +9,9 @@ For a discussion and comparison of these algorithms, see the :ref:`manifold module page ` +For a similar example, where the methods are applied to a +sphere dataset, see :ref:`example_manifold_plot_manifold_sphere.py` + Note that the purpose of the MDS is to find a low-dimensional representation of the data (here 2D) in which the distances respect well the distances in the original high-dimensional space, unlike other @@ -18,37 +21,36 @@ # Author: Jake Vanderplas -- -print __doc__ +print(__doc__) from time import time -import pylab as pl +import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import NullFormatter from sklearn import manifold, datasets -from sklearn.metrics import euclidean_distances # Next line to silence pyflakes. This import is needed. Axes3D n_points = 1000 -X, color = datasets.samples_generator.make_s_curve(n_points) +X, color = datasets.samples_generator.make_s_curve(n_points, random_state=0) n_neighbors = 10 n_components = 2 -fig = pl.figure(figsize=(15, 8)) -pl.suptitle("Manifold Learning with %i points, %i neighbors" - % (1000, n_neighbors), fontsize=14) +fig = plt.figure(figsize=(15, 8)) +plt.suptitle("Manifold Learning with %i points, %i neighbors" + % (1000, n_neighbors), fontsize=14) try: # compatibility matplotlib < 1.0 - ax = fig.add_subplot(241, projection='3d') - ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=color, cmap=pl.cm.Spectral) + ax = fig.add_subplot(251, projection='3d') + ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=color, cmap=plt.cm.Spectral) ax.view_init(4, -72) except: - ax = fig.add_subplot(241, projection='3d') - pl.scatter(X[:, 0], X[:, 2], c=color, cmap=pl.cm.Spectral) + ax = fig.add_subplot(251, projection='3d') + plt.scatter(X[:, 0], X[:, 2], c=color, cmap=plt.cm.Spectral) methods = ['standard', 'ltsa', 'hessian', 'modified'] labels = ['LLE', 'LTSA', 'Hessian LLE', 'Modified LLE'] @@ -59,38 +61,63 @@ eigen_solver='auto', method=method).fit_transform(X) t1 = time() - print "%s: %.2g sec" % (methods[i], t1 - t0) + print("%s: %.2g sec" % (methods[i], t1 - t0)) - ax = fig.add_subplot(242 + i) - pl.scatter(Y[:, 0], Y[:, 1], c=color, cmap=pl.cm.Spectral) - pl.title("%s (%.2g sec)" % (labels[i], t1 - t0)) + ax = fig.add_subplot(252 + i) + plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) + plt.title("%s (%.2g sec)" % (labels[i], t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) - pl.axis('tight') + plt.axis('tight') t0 = time() Y = manifold.Isomap(n_neighbors, n_components).fit_transform(X) t1 = time() -print "Isomap: %.2g sec" % (t1 - t0) -ax = fig.add_subplot(246) -pl.scatter(Y[:, 0], Y[:, 1], c=color, cmap=pl.cm.Spectral) -pl.title("Isomap (%.2g sec)" % (t1 - t0)) +print("Isomap: %.2g sec" % (t1 - t0)) +ax = fig.add_subplot(257) +plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) +plt.title("Isomap (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) -pl.axis('tight') +plt.axis('tight') t0 = time() mds = manifold.MDS(n_components, max_iter=100, n_init=1) -Y = mds.fit_transform(euclidean_distances(X)) +Y = mds.fit_transform(X) t1 = time() -print "MDS: %.2g sec" % (t1 - t0) -ax = fig.add_subplot(247) -pl.scatter(Y[:, 0], Y[:, 1], c=color, cmap=pl.cm.Spectral) -pl.title("MDS (%.2g sec)" % (t1 - t0)) +print("MDS: %.2g sec" % (t1 - t0)) +ax = fig.add_subplot(258) +plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) +plt.title("MDS (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) -pl.axis('tight') +plt.axis('tight') + +t0 = time() +se = manifold.SpectralEmbedding(n_components=n_components, + n_neighbors=n_neighbors) +Y = se.fit_transform(X) +t1 = time() +print("SpectralEmbedding: %.2g sec" % (t1 - t0)) +ax = fig.add_subplot(259) +plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) +plt.title("SpectralEmbedding (%.2g sec)" % (t1 - t0)) +ax.xaxis.set_major_formatter(NullFormatter()) +ax.yaxis.set_major_formatter(NullFormatter()) +plt.axis('tight') + +t0 = time() +tsne = manifold.TSNE(n_components=n_components, init='pca', random_state=0) +Y = tsne.fit_transform(X) +t1 = time() +print("t-SNE: %.2g sec" % (t1 - t0)) +ax = fig.add_subplot(250) +plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) +plt.title("t-SNE (%.2g sec)" % (t1 - t0)) +ax.xaxis.set_major_formatter(NullFormatter()) +ax.yaxis.set_major_formatter(NullFormatter()) +plt.axis('tight') -pl.show() +plt.show() diff --git a/examples/manifold/plot_lle_digits.py b/examples/manifold/plot_lle_digits.py index 29b8aaba815c7..5f75e8582c221 100644 --- a/examples/manifold/plot_lle_digits.py +++ b/examples/manifold/plot_lle_digits.py @@ -4,22 +4,33 @@ ============================================================================= An illustration of various embeddings on the digits dataset. + +The RandomTreesEmbedding, from the :mod:`sklearn.ensemble` module, is not +technically a manifold embedding method, as it learn a high-dimensional +representation on which we apply a dimensionality reduction method. +However, it is often useful to cast a dataset into a representation in +which the classes are linearly-separable. + +t-SNE will be initialized with the embedding that is generated by PCA in +this example, which is not the default setting. It ensures global stability +of the embedding, i.e., the embedding does not depend on random +initialization. """ # Authors: Fabian Pedregosa # Olivier Grisel # Mathieu Blondel -# License: BSD, (C) INRIA 2011 +# Gael Varoquaux +# License: BSD 3 clause (C) INRIA 2011 -print __doc__ +print(__doc__) from time import time import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from matplotlib import offsetbox -from sklearn.utils.fixes import qr_economic -from sklearn import manifold, datasets, decomposition, lda -from sklearn.metrics import euclidean_distances +from sklearn import (manifold, datasets, decomposition, ensemble, lda, + random_projection) digits = datasets.load_digits(n_class=6) X = digits.data @@ -34,12 +45,12 @@ def plot_embedding(X, title=None): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) - pl.figure() - ax = pl.subplot(111) + plt.figure() + ax = plt.subplot(111) for i in range(X.shape[0]): - pl.text(X[i, 0], X[i, 1], str(digits.target[i]), - color=pl.cm.Set1(y[i] / 10.), - fontdict={'weight': 'bold', 'size': 9}) + plt.text(X[i, 0], X[i, 1], str(digits.target[i]), + color=plt.cm.Set1(y[i] / 10.), + fontdict={'weight': 'bold', 'size': 9}) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 @@ -51,132 +62,169 @@ def plot_embedding(X, title=None): continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( - offsetbox.OffsetImage(digits.images[i], cmap=pl.cm.gray_r), + offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) - pl.xticks([]), pl.yticks([]) + plt.xticks([]), plt.yticks([]) if title is not None: - pl.title(title) + plt.title(title) #---------------------------------------------------------------------- # Plot images of the digits -N = 20 -img = np.zeros((10 * N, 10 * N)) -for i in range(N): +n_img_per_row = 20 +img = np.zeros((10 * n_img_per_row, 10 * n_img_per_row)) +for i in range(n_img_per_row): ix = 10 * i + 1 - for j in range(N): + for j in range(n_img_per_row): iy = 10 * j + 1 - img[ix:ix + 8, iy:iy + 8] = X[i * N + j].reshape((8, 8)) -pl.imshow(img, cmap=pl.cm.binary) -pl.xticks([]) -pl.yticks([]) -pl.title('A selection from the 64-dimensional digits dataset') + img[ix:ix + 8, iy:iy + 8] = X[i * n_img_per_row + j].reshape((8, 8)) + +plt.imshow(img, cmap=plt.cm.binary) +plt.xticks([]) +plt.yticks([]) +plt.title('A selection from the 64-dimensional digits dataset') #---------------------------------------------------------------------- # Random 2D projection using a random unitary matrix -print "Computing random projection" -rng = np.random.RandomState(42) -Q, _ = qr_economic(rng.normal(size=(n_features, 2))) -X_projected = np.dot(Q.T, X.T).T +print("Computing random projection") +rp = random_projection.SparseRandomProjection(n_components=2, random_state=42) +X_projected = rp.fit_transform(X) plot_embedding(X_projected, "Random Projection of the digits") #---------------------------------------------------------------------- # Projection on to the first 2 principal components -print "Computing PCA projection" +print("Computing PCA projection") t0 = time() -X_pca = decomposition.RandomizedPCA(n_components=2).fit_transform(X) +X_pca = decomposition.TruncatedSVD(n_components=2).fit_transform(X) plot_embedding(X_pca, - "Principal Components projection of the digits (time %.2fs)" % - (time() - t0)) + "Principal Components projection of the digits (time %.2fs)" % + (time() - t0)) #---------------------------------------------------------------------- # Projection on to the first 2 linear discriminant components -print "Computing LDA projection" +print("Computing LDA projection") X2 = X.copy() X2.flat[::X.shape[1] + 1] += 0.01 # Make X invertible t0 = time() X_lda = lda.LDA(n_components=2).fit_transform(X2, y) plot_embedding(X_lda, - "Linear Discriminant projection of the digits (time %.2fs)" % - (time() - t0)) + "Linear Discriminant projection of the digits (time %.2fs)" % + (time() - t0)) #---------------------------------------------------------------------- # Isomap projection of the digits dataset -print "Computing Isomap embedding" +print("Computing Isomap embedding") t0 = time() X_iso = manifold.Isomap(n_neighbors, n_components=2).fit_transform(X) -print "Done." +print("Done.") plot_embedding(X_iso, - "Isomap projection of the digits (time %.2fs)" % - (time() - t0)) + "Isomap projection of the digits (time %.2fs)" % + (time() - t0)) #---------------------------------------------------------------------- # Locally linear embedding of the digits dataset -print "Computing LLE embedding" +print("Computing LLE embedding") clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2, method='standard') t0 = time() X_lle = clf.fit_transform(X) -print "Done. Reconstruction error: %g" % clf.reconstruction_error_ +print("Done. Reconstruction error: %g" % clf.reconstruction_error_) plot_embedding(X_lle, - "Locally Linear Embedding of the digits (time %.2fs)" % - (time() - t0)) + "Locally Linear Embedding of the digits (time %.2fs)" % + (time() - t0)) #---------------------------------------------------------------------- # Modified Locally linear embedding of the digits dataset -print "Computing modified LLE embedding" +print("Computing modified LLE embedding") clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2, method='modified') t0 = time() X_mlle = clf.fit_transform(X) -print "Done. Reconstruction error: %g" % clf.reconstruction_error_ +print("Done. Reconstruction error: %g" % clf.reconstruction_error_) plot_embedding(X_mlle, - "Modified Locally Linear Embedding of the digits (time %.2fs)" % - (time() - t0)) + "Modified Locally Linear Embedding of the digits (time %.2fs)" % + (time() - t0)) #---------------------------------------------------------------------- # HLLE embedding of the digits dataset -print "Computing Hessian LLE embedding" +print("Computing Hessian LLE embedding") clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2, method='hessian') t0 = time() X_hlle = clf.fit_transform(X) -print "Done. Reconstruction error: %g" % clf.reconstruction_error_ +print("Done. Reconstruction error: %g" % clf.reconstruction_error_) plot_embedding(X_hlle, - "Hessian Locally Linear Embedding of the digits (time %.2fs)" % - (time() - t0)) + "Hessian Locally Linear Embedding of the digits (time %.2fs)" % + (time() - t0)) #---------------------------------------------------------------------- # LTSA embedding of the digits dataset -print "Computing LTSA embedding" +print("Computing LTSA embedding") clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2, method='ltsa') t0 = time() X_ltsa = clf.fit_transform(X) -print "Done. Reconstruction error: %g" % clf.reconstruction_error_ +print("Done. Reconstruction error: %g" % clf.reconstruction_error_) plot_embedding(X_ltsa, - "Local Tangent Space Alignment of the digits (time %.2fs)" % - (time() - t0)) + "Local Tangent Space Alignment of the digits (time %.2fs)" % + (time() - t0)) #---------------------------------------------------------------------- # MDS embedding of the digits dataset -print "Computing MDS embedding" +print("Computing MDS embedding") clf = manifold.MDS(n_components=2, n_init=1, max_iter=100) t0 = time() -X_mds = clf.fit_transform(euclidean_distances(X)) -print "Done. Stress: %f" % clf.stress_ +X_mds = clf.fit_transform(X) +print("Done. Stress: %f" % clf.stress_) plot_embedding(X_mds, - "MDS embedding of the digits (time %.2fs)" % - (time() - t0)) + "MDS embedding of the digits (time %.2fs)" % + (time() - t0)) + +#---------------------------------------------------------------------- +# Random Trees embedding of the digits dataset +print("Computing Totally Random Trees embedding") +hasher = ensemble.RandomTreesEmbedding(n_estimators=200, random_state=0, + max_depth=5) +t0 = time() +X_transformed = hasher.fit_transform(X) +pca = decomposition.TruncatedSVD(n_components=2) +X_reduced = pca.fit_transform(X_transformed) + +plot_embedding(X_reduced, + "Random forest embedding of the digits (time %.2fs)" % + (time() - t0)) + +#---------------------------------------------------------------------- +# Spectral embedding of the digits dataset +print("Computing Spectral embedding") +embedder = manifold.SpectralEmbedding(n_components=2, random_state=0, + eigen_solver="arpack") +t0 = time() +X_se = embedder.fit_transform(X) + +plot_embedding(X_se, + "Spectral embedding of the digits (time %.2fs)" % + (time() - t0)) + +#---------------------------------------------------------------------- +# t-SNE embedding of the digits dataset +print("Computing t-SNE embedding") +tsne = manifold.TSNE(n_components=2, init='pca', random_state=0) +t0 = time() +X_tsne = tsne.fit_transform(X) + +plot_embedding(X_tsne, + "t-SNE embedding of the digits (time %.2fs)" % + (time() - t0)) -pl.show() +plt.show() diff --git a/examples/manifold/plot_manifold_sphere.py b/examples/manifold/plot_manifold_sphere.py new file mode 100644 index 0000000000000..23c2ea70da3b7 --- /dev/null +++ b/examples/manifold/plot_manifold_sphere.py @@ -0,0 +1,155 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +""" +============================================= +Manifold Learning methods on a severed sphere +============================================= + +An application of the different :ref:`manifold` techniques +on a spherical data-set. Here one can see the use of +dimensionality reduction in order to gain some intuition +regarding the manifold learning methods. Regarding the dataset, +the poles are cut from the sphere, as well as a thin slice down its +side. This enables the manifold learning techniques to +'spread it open' whilst projecting it onto two dimensions. + +For a similar example, where the methods are applied to the +S-curve dataset, see :ref:`example_manifold_plot_compare_methods.py` + +Note that the purpose of the :ref:`MDS ` is +to find a low-dimensional representation of the data (here 2D) in +which the distances respect well the distances in the original +high-dimensional space, unlike other manifold-learning algorithms, +it does not seeks an isotropic representation of the data in +the low-dimensional space. Here the manifold problem matches fairly +that of representing a flat map of the Earth, as with +`map projection `_ +""" + +# Author: Jaques Grobler +# License: BSD 3 clause + +print(__doc__) + +from time import time + +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D +from matplotlib.ticker import NullFormatter + +from sklearn import manifold +from sklearn.utils import check_random_state + +# Next line to silence pyflakes. +Axes3D + +# Variables for manifold learning. +n_neighbors = 10 +n_samples = 1000 + +# Create our sphere. +random_state = check_random_state(0) +p = random_state.rand(n_samples) * (2 * np.pi - 0.55) +t = random_state.rand(n_samples) * np.pi + +# Sever the poles from the sphere. +indices = ((t < (np.pi - (np.pi / 8))) & (t > ((np.pi / 8)))) +colors = p[indices] +x, y, z = np.sin(t[indices]) * np.cos(p[indices]), \ + np.sin(t[indices]) * np.sin(p[indices]), \ + np.cos(t[indices]) + +# Plot our dataset. +fig = plt.figure(figsize=(15, 8)) +plt.suptitle("Manifold Learning with %i points, %i neighbors" + % (1000, n_neighbors), fontsize=14) + +ax = fig.add_subplot(251, projection='3d') +ax.scatter(x, y, z, c=p[indices], cmap=plt.cm.rainbow) +try: + # compatibility matplotlib < 1.0 + ax.view_init(40, -10) +except: + pass + +sphere_data = np.array([x, y, z]).T + +# Perform Locally Linear Embedding Manifold learning +methods = ['standard', 'ltsa', 'hessian', 'modified'] +labels = ['LLE', 'LTSA', 'Hessian LLE', 'Modified LLE'] + +for i, method in enumerate(methods): + t0 = time() + trans_data = manifold\ + .LocallyLinearEmbedding(n_neighbors, 2, + method=method).fit_transform(sphere_data).T + t1 = time() + print("%s: %.2g sec" % (methods[i], t1 - t0)) + + ax = fig.add_subplot(252 + i) + plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) + plt.title("%s (%.2g sec)" % (labels[i], t1 - t0)) + ax.xaxis.set_major_formatter(NullFormatter()) + ax.yaxis.set_major_formatter(NullFormatter()) + plt.axis('tight') + +# Perform Isomap Manifold learning. +t0 = time() +trans_data = manifold.Isomap(n_neighbors, n_components=2)\ + .fit_transform(sphere_data).T +t1 = time() +print("%s: %.2g sec" % ('ISO', t1 - t0)) + +ax = fig.add_subplot(257) +plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) +plt.title("%s (%.2g sec)" % ('Isomap', t1 - t0)) +ax.xaxis.set_major_formatter(NullFormatter()) +ax.yaxis.set_major_formatter(NullFormatter()) +plt.axis('tight') + +# Perform Multi-dimensional scaling. +t0 = time() +mds = manifold.MDS(2, max_iter=100, n_init=1) +trans_data = mds.fit_transform(sphere_data).T +t1 = time() +print("MDS: %.2g sec" % (t1 - t0)) + +ax = fig.add_subplot(258) +plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) +plt.title("MDS (%.2g sec)" % (t1 - t0)) +ax.xaxis.set_major_formatter(NullFormatter()) +ax.yaxis.set_major_formatter(NullFormatter()) +plt.axis('tight') + +# Perform Spectral Embedding. +t0 = time() +se = manifold.SpectralEmbedding(n_components=2, + n_neighbors=n_neighbors) +trans_data = se.fit_transform(sphere_data).T +t1 = time() +print("Spectral Embedding: %.2g sec" % (t1 - t0)) + +ax = fig.add_subplot(259) +plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) +plt.title("Spectral Embedding (%.2g sec)" % (t1 - t0)) +ax.xaxis.set_major_formatter(NullFormatter()) +ax.yaxis.set_major_formatter(NullFormatter()) +plt.axis('tight') + +# Perform t-distributed stochastic neighbor embedding. +t0 = time() +tsne = manifold.TSNE(n_components=2, init='pca', random_state=0) +trans_data = tsne.fit_transform(sphere_data).T +t1 = time() +print("t-SNE: %.2g sec" % (t1 - t0)) + +ax = fig.add_subplot(250) +plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) +plt.title("t-SNE (%.2g sec)" % (t1 - t0)) +ax.xaxis.set_major_formatter(NullFormatter()) +ax.yaxis.set_major_formatter(NullFormatter()) +plt.axis('tight') + +plt.show() diff --git a/examples/manifold/plot_mds.py b/examples/manifold/plot_mds.py index 1cd88b5857668..bd35baa984428 100644 --- a/examples/manifold/plot_mds.py +++ b/examples/manifold/plot_mds.py @@ -12,7 +12,7 @@ # Author: Nelle Varoquaux # Licence: BSD -print __doc__ +print(__doc__) import numpy as np from matplotlib import pyplot as plt @@ -37,15 +37,18 @@ noise[np.arange(noise.shape[0]), np.arange(noise.shape[0])] = 0 similarities += noise -mds = manifold.MDS(n_components=2, max_iter=3000, - eps=1e-9, random_state=seed, - n_jobs=1) +mds = manifold.MDS(n_components=2, max_iter=3000, eps=1e-9, random_state=seed, + dissimilarity="precomputed", n_jobs=1) pos = mds.fit(similarities).embedding_ -nmds = manifold.MDS(n_components=2, metric=False, - max_iter=3000, - eps=1e-9, random_state=seed, n_jobs=1) -npos = mds.fit_transform(similarities) +nmds = manifold.MDS(n_components=2, metric=False, max_iter=3000, eps=1e-12, + dissimilarity="precomputed", random_state=seed, n_jobs=1, + n_init=1) +npos = nmds.fit_transform(similarities, init=pos) + +# Rescale the data +pos *= np.sqrt((X_true ** 2).sum()) / np.sqrt((pos ** 2).sum()) +npos *= np.sqrt((X_true ** 2).sum()) / np.sqrt((npos ** 2).sum()) # Rotate the data clf = PCA(n_components=2) @@ -53,14 +56,14 @@ pos = clf.fit_transform(pos) -npos = clf.fit_transform(pos) +npos = clf.fit_transform(npos) fig = plt.figure(1) ax = plt.axes([0., 0., 1., 1.]) plt.scatter(X_true[:, 0], X_true[:, 1], c='r', s=20) -plt.scatter(pos[:, 0] + 0.2, pos[:, 1] + 0.2, s=20, c='g') -plt.scatter(npos[:, 0] - 0.2, npos[:, 1] - 0.2, s=20, c='b') +plt.scatter(pos[:, 0], pos[:, 1], s=20, c='g') +plt.scatter(npos[:, 0], npos[:, 1], s=20, c='b') plt.legend(('True position', 'MDS', 'NMDS'), loc='best') similarities = similarities.max() / similarities * 100 @@ -70,7 +73,7 @@ start_idx, end_idx = np.where(pos) #a sequence of (*line0*, *line1*, *line2*), where:: # linen = (x0, y0), (x1, y1), ... (xm, ym) -segments = [[pos[i, :], pos[j, :]] +segments = [[X_true[i, :], X_true[j, :]] for i in range(len(pos)) for j in range(len(pos))] values = np.abs(similarities) lc = LineCollection(segments, diff --git a/examples/manifold/plot_swissroll.py b/examples/manifold/plot_swissroll.py index 71dfd1c8685cd..17c318cab7093 100644 --- a/examples/manifold/plot_swissroll.py +++ b/examples/manifold/plot_swissroll.py @@ -8,11 +8,11 @@ """ # Author: Fabian Pedregosa -- -# License: BSD, (C) INRIA 2011 +# License: BSD 3 clause (C) INRIA 2011 -print __doc__ +print(__doc__) -import pylab as pl +import matplotlib.pyplot as plt # This import is needed to modify the way figure behaves from mpl_toolkits.mplot3d import Axes3D @@ -24,27 +24,27 @@ from sklearn import manifold, datasets X, color = datasets.samples_generator.make_swiss_roll(n_samples=1500) -print "Computing LLE embedding" +print("Computing LLE embedding") X_r, err = manifold.locally_linear_embedding(X, n_neighbors=12, n_components=2) -print "Done. Reconstruction error: %g" % err +print("Done. Reconstruction error: %g" % err) #---------------------------------------------------------------------- # Plot result -fig = pl.figure() +fig = plt.figure() try: # compatibility matplotlib < 1.0 ax = fig.add_subplot(211, projection='3d') - ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=color, cmap=pl.cm.Spectral) + ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=color, cmap=plt.cm.Spectral) except: ax = fig.add_subplot(211) - ax.scatter(X[:, 0], X[:, 2], c=color, cmap=pl.cm.Spectral) + ax.scatter(X[:, 0], X[:, 2], c=color, cmap=plt.cm.Spectral) ax.set_title("Original data") ax = fig.add_subplot(212) -ax.scatter(X_r[:, 0], X_r[:, 1], c=color, cmap=pl.cm.Spectral) -pl.axis('tight') -pl.xticks([]), pl.yticks([]) -pl.title('Projected data') -pl.show() +ax.scatter(X_r[:, 0], X_r[:, 1], c=color, cmap=plt.cm.Spectral) +plt.axis('tight') +plt.xticks([]), plt.yticks([]) +plt.title('Projected data') +plt.show() diff --git a/examples/missing_values.py b/examples/missing_values.py new file mode 100644 index 0000000000000..59444b36490e3 --- /dev/null +++ b/examples/missing_values.py @@ -0,0 +1,72 @@ +""" +====================================================== +Imputing missing values before building an estimator +====================================================== + +This example shows that imputing the missing values can give better results +than discarding the samples containing any missing value. +Imputing does not always improve the predictions, so please check via cross-validation. +Sometimes dropping rows or using marker values is more effective. + +Missing values can be replaced by the mean, the median or the most frequent +value using the ``strategy`` hyper-parameter. +The median is a more robust estimator for data with high magnitude variables +which could dominate results (otherwise known as a 'long tail'). + +Script output:: + + Score with the entire dataset = 0.56 + Score without the samples containing missing values = 0.48 + Score after imputation of the missing values = 0.55 + +In this case, imputing helps the classifier get close to the original score. + +""" +import numpy as np + +from sklearn.datasets import load_boston +from sklearn.ensemble import RandomForestRegressor +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import Imputer +from sklearn.cross_validation import cross_val_score + +rng = np.random.RandomState(0) + +dataset = load_boston() +X_full, y_full = dataset.data, dataset.target +n_samples = X_full.shape[0] +n_features = X_full.shape[1] + +# Estimate the score on the entire dataset, with no missing values +estimator = RandomForestRegressor(random_state=0, n_estimators=100) +score = cross_val_score(estimator, X_full, y_full).mean() +print("Score with the entire dataset = %.2f" % score) + +# Add missing values in 75% of the lines +missing_rate = 0.75 +n_missing_samples = np.floor(n_samples * missing_rate) +missing_samples = np.hstack((np.zeros(n_samples - n_missing_samples, + dtype=np.bool), + np.ones(n_missing_samples, + dtype=np.bool))) +rng.shuffle(missing_samples) +missing_features = rng.randint(0, n_features, n_missing_samples) + +# Estimate the score without the lines containing missing values +X_filtered = X_full[~missing_samples, :] +y_filtered = y_full[~missing_samples] +estimator = RandomForestRegressor(random_state=0, n_estimators=100) +score = cross_val_score(estimator, X_filtered, y_filtered).mean() +print("Score without the samples containing missing values = %.2f" % score) + +# Estimate the score after imputation of the missing values +X_missing = X_full.copy() +X_missing[np.where(missing_samples)[0], missing_features] = 0 +y_missing = y_full.copy() +estimator = Pipeline([("imputer", Imputer(missing_values=0, + strategy="mean", + axis=0)), + ("forest", RandomForestRegressor(random_state=0, + n_estimators=100))]) +score = cross_val_score(estimator, X_missing, y_missing).mean() +print("Score after imputation of the missing values = %.2f" % score) diff --git a/examples/mixture/README.txt b/examples/mixture/README.txt index 70d3b872c5371..f872af051e575 100644 --- a/examples/mixture/README.txt +++ b/examples/mixture/README.txt @@ -3,4 +3,4 @@ Gaussian Mixture Models ----------------------- -Examples concerning the :mod:`sklearn.mixture` package. +Examples concerning the :mod:`sklearn.mixture` module. diff --git a/examples/mixture/plot_gmm.py b/examples/mixture/plot_gmm.py index 6ab6d7c64a09e..1ce272706778c 100644 --- a/examples/mixture/plot_gmm.py +++ b/examples/mixture/plot_gmm.py @@ -3,8 +3,8 @@ Gaussian Mixture Model Ellipsoids ================================= -Plot the confidence ellipsoids of a mixture of two gaussians with EM -and variational dirichlet process. +Plot the confidence ellipsoids of a mixture of two Gaussians with EM +and variational Dirichlet process. Both models have access to five components with which to fit the data. Note that the EM model will necessarily use all five components @@ -15,7 +15,7 @@ adapts it number of state automatically. This example doesn't show it, as we're in a low-dimensional space, but -another advantage of the dirichlet process model is that it can fit +another advantage of the Dirichlet process model is that it can fit full covariance matrices effectively even when there are less examples per cluster than there are dimensions in the data, due to regularization properties of the inference algorithm. @@ -24,7 +24,7 @@ import numpy as np from scipy import linalg -import pylab as pl +import matplotlib.pyplot as plt import matplotlib as mpl from sklearn import mixture @@ -38,11 +38,11 @@ X = np.r_[np.dot(np.random.randn(n_samples, 2), C), .7 * np.random.randn(n_samples, 2) + np.array([-6, 3])] -# Fit a mixture of gaussians with EM using five components +# Fit a mixture of Gaussians with EM using five components gmm = mixture.GMM(n_components=5, covariance_type='full') gmm.fit(X) -# Fit a dirichlet process mixture of gaussians using five components +# Fit a Dirichlet process mixture of Gaussians using five components dpgmm = mixture.DPGMM(n_components=5, covariance_type='full') dpgmm.fit(X) @@ -50,7 +50,7 @@ for i, (clf, title) in enumerate([(gmm, 'GMM'), (dpgmm, 'Dirichlet Process GMM')]): - splot = pl.subplot(2, 1, 1 + i) + splot = plt.subplot(2, 1, 1 + i) Y_ = clf.predict(X) for i, (mean, covar, color) in enumerate(zip( clf.means_, clf._get_covars(), color_iter)): @@ -61,7 +61,7 @@ # components. if not np.any(Y_ == i): continue - pl.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color) + plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color) # Plot an ellipse to show the Gaussian component angle = np.arctan(u[1] / u[0]) @@ -71,10 +71,10 @@ ell.set_alpha(0.5) splot.add_artist(ell) - pl.xlim(-10, 10) - pl.ylim(-3, 6) - pl.xticks(()) - pl.yticks(()) - pl.title(title) + plt.xlim(-10, 10) + plt.ylim(-3, 6) + plt.xticks(()) + plt.yticks(()) + plt.title(title) -pl.show() +plt.show() diff --git a/examples/mixture/plot_gmm_classifier.py b/examples/mixture/plot_gmm_classifier.py index 92f113bb44e82..cebbe36cada69 100644 --- a/examples/mixture/plot_gmm_classifier.py +++ b/examples/mixture/plot_gmm_classifier.py @@ -3,7 +3,9 @@ GMM classification ================== -Demonstration of :ref:`gmm` for classification. +Demonstration of Gaussian mixture models for classification. + +See :ref:`gmm` for more information on the estimator. Plots predicted labels on both training and held out test data using a variety of GMM classifiers on the iris dataset. @@ -19,19 +21,20 @@ dimensions are shown here, and thus some points are separated in other dimensions. """ -print __doc__ +print(__doc__) # Author: Ron Weiss , Gael Varoquaux -# License: BSD Style. +# License: BSD 3 clause # $Id$ -import pylab as pl +import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np from sklearn import datasets from sklearn.cross_validation import StratifiedKFold +from sklearn.externals.six.moves import xrange from sklearn.mixture import GMM @@ -52,7 +55,7 @@ def make_ellipses(gmm, ax): # Break up the dataset into non-overlapping training (75%) and testing # (25%) sets. -skf = StratifiedKFold(iris.target, k=4) +skf = StratifiedKFold(iris.target, n_folds=4) # Only take the first fold. train_index, test_index = next(iter(skf)) @@ -67,16 +70,16 @@ def make_ellipses(gmm, ax): # Try GMMs using different types of covariances. classifiers = dict((covar_type, GMM(n_components=n_classes, covariance_type=covar_type, init_params='wc', n_iter=20)) - for covar_type in ['spherical', 'diag', 'tied', 'full']) + for covar_type in ['spherical', 'diag', 'tied', 'full']) n_classifiers = len(classifiers) -pl.figure(figsize=(3 * n_classifiers / 2, 6)) -pl.subplots_adjust(bottom=.01, top=0.95, hspace=.15, wspace=.05, - left=.01, right=.99) +plt.figure(figsize=(3 * n_classifiers / 2, 6)) +plt.subplots_adjust(bottom=.01, top=0.95, hspace=.15, wspace=.05, + left=.01, right=.99) -for index, (name, classifier) in enumerate(classifiers.iteritems()): +for index, (name, classifier) in enumerate(classifiers.items()): # Since we have class labels for the training data, we can # initialize the GMM parameters in a supervised manner. classifier.means_ = np.array([X_train[y_train == i].mean(axis=0) @@ -85,33 +88,33 @@ def make_ellipses(gmm, ax): # Train the other parameters using the EM algorithm. classifier.fit(X_train) - h = pl.subplot(2, n_classifiers / 2, index + 1) + h = plt.subplot(2, n_classifiers / 2, index + 1) make_ellipses(classifier, h) for n, color in enumerate('rgb'): data = iris.data[iris.target == n] - pl.scatter(data[:, 0], data[:, 1], 0.8, color=color, + plt.scatter(data[:, 0], data[:, 1], 0.8, color=color, label=iris.target_names[n]) # Plot the test data with crosses for n, color in enumerate('rgb'): data = X_test[y_test == n] - pl.plot(data[:, 0], data[:, 1], 'x', color=color) + plt.plot(data[:, 0], data[:, 1], 'x', color=color) y_train_pred = classifier.predict(X_train) train_accuracy = np.mean(y_train_pred.ravel() == y_train.ravel()) * 100 - pl.text(0.05, 0.9, 'Train accuracy: %.1f' % train_accuracy, - transform=h.transAxes) + plt.text(0.05, 0.9, 'Train accuracy: %.1f' % train_accuracy, + transform=h.transAxes) y_test_pred = classifier.predict(X_test) test_accuracy = np.mean(y_test_pred.ravel() == y_test.ravel()) * 100 - pl.text(0.05, 0.8, 'Test accuracy: %.1f' % test_accuracy, - transform=h.transAxes) + plt.text(0.05, 0.8, 'Test accuracy: %.1f' % test_accuracy, + transform=h.transAxes) - pl.xticks(()) - pl.yticks(()) - pl.title(name) + plt.xticks(()) + plt.yticks(()) + plt.title(name) -pl.legend(loc='lower right', prop=dict(size=12)) +plt.legend(loc='lower right', prop=dict(size=12)) -pl.show() +plt.show() diff --git a/examples/mixture/plot_gmm_pdf.py b/examples/mixture/plot_gmm_pdf.py index d0ebe6a290c12..a1b7ea5de202f 100644 --- a/examples/mixture/plot_gmm_pdf.py +++ b/examples/mixture/plot_gmm_pdf.py @@ -3,36 +3,48 @@ Density Estimation for a mixture of Gaussians ============================================= -Plot the density estimation of a mixture of two gaussians. Data is -generated from two gaussians with different centers and covariance +Plot the density estimation of a mixture of two Gaussians. Data is +generated from two Gaussians with different centers and covariance matrices. """ import numpy as np -import pylab as pl +import matplotlib.pyplot as plt +from matplotlib.colors import LogNorm from sklearn import mixture n_samples = 300 # generate random sample, two components np.random.seed(0) + +# generate spherical data centered on (20, 20) +shifted_gaussian = np.random.randn(n_samples, 2) + np.array([20, 20]) + +# generate zero centered stretched Gaussian data C = np.array([[0., -0.7], [3.5, .7]]) -X_train = np.r_[np.dot(np.random.randn(n_samples, 2), C), - np.random.randn(n_samples, 2) + np.array([20, 20])] +stretched_gaussian = np.dot(np.random.randn(n_samples, 2), C) + +# concatenate the two datasets into the final training set +X_train = np.vstack([shifted_gaussian, stretched_gaussian]) +# fit a Gaussian Mixture Model with two components clf = mixture.GMM(n_components=2, covariance_type='full') clf.fit(X_train) +# display predicted scores by the model as a contour plot x = np.linspace(-20.0, 30.0) y = np.linspace(-20.0, 40.0) X, Y = np.meshgrid(x, y) -XX = np.c_[X.ravel(), Y.ravel()] -Z = np.log(-clf.eval(XX)[0]) +XX = np.array([X.ravel(), Y.ravel()]).T +Z = -clf.score_samples(XX)[0] Z = Z.reshape(X.shape) -CS = pl.contour(X, Y, Z) -CB = pl.colorbar(CS, shrink=0.8, extend='both') -pl.scatter(X_train[:, 0], X_train[:, 1], .8) +CS = plt.contour(X, Y, Z, norm=LogNorm(vmin=1.0, vmax=1000.0), + levels=np.logspace(0, 3, 10)) +CB = plt.colorbar(CS, shrink=0.8, extend='both') +plt.scatter(X_train[:, 0], X_train[:, 1], .8) -pl.axis('tight') -pl.show() +plt.title('Negative log-likelihood predicted by a GMM') +plt.axis('tight') +plt.show() diff --git a/examples/mixture/plot_gmm_selection.py b/examples/mixture/plot_gmm_selection.py index 4f9b46a95fad0..435c8da5c88a5 100644 --- a/examples/mixture/plot_gmm_selection.py +++ b/examples/mixture/plot_gmm_selection.py @@ -3,7 +3,7 @@ Gaussian Mixture Model Selection ================================= -This example shows that model selection can be perfomed with +This example shows that model selection can be performed with Gaussian Mixture Models using information-theoretic criteria (BIC). Model selection concerns both the covariance type and the number of components in the model. @@ -14,13 +14,13 @@ In that case, the model with 2 components and full covariance (which corresponds to the true generative model) is selected. """ -print __doc__ +print(__doc__) import itertools import numpy as np from scipy import linalg -import pylab as pl +import matplotlib.pyplot as plt import matplotlib as mpl from sklearn import mixture @@ -40,7 +40,7 @@ cv_types = ['spherical', 'tied', 'diag', 'full'] for cv_type in cv_types: for n_components in n_components_range: - # Fit a mixture of gaussians with EM + # Fit a mixture of Gaussians with EM gmm = mixture.GMM(n_components=n_components, covariance_type=cv_type) gmm.fit(X) bic.append(gmm.bic(X)) @@ -54,30 +54,30 @@ bars = [] # Plot the BIC scores -spl = pl.subplot(2, 1, 1) +spl = plt.subplot(2, 1, 1) for i, (cv_type, color) in enumerate(zip(cv_types, color_iter)): xpos = np.array(n_components_range) + .2 * (i - 2) - bars.append(pl.bar(xpos, bic[i * len(n_components_range): - (i + 1) * len(n_components_range)], - width=.2, color=color)) -pl.xticks(n_components_range) -pl.ylim([bic.min() * 1.01 - .01 * bic.max(), bic.max()]) -pl.title('BIC score per model') + bars.append(plt.bar(xpos, bic[i * len(n_components_range): + (i + 1) * len(n_components_range)], + width=.2, color=color)) +plt.xticks(n_components_range) +plt.ylim([bic.min() * 1.01 - .01 * bic.max(), bic.max()]) +plt.title('BIC score per model') xpos = np.mod(bic.argmin(), len(n_components_range)) + .65 +\ .2 * np.floor(bic.argmin() / len(n_components_range)) -pl.text(xpos, bic.min() * 0.97 + .03 * bic.max(), '*', fontsize=14) +plt.text(xpos, bic.min() * 0.97 + .03 * bic.max(), '*', fontsize=14) spl.set_xlabel('Number of components') spl.legend([b[0] for b in bars], cv_types) # Plot the winner -splot = pl.subplot(2, 1, 2) +splot = plt.subplot(2, 1, 2) Y_ = clf.predict(X) for i, (mean, covar, color) in enumerate(zip(clf.means_, clf.covars_, color_iter)): v, w = linalg.eigh(covar) if not np.any(Y_ == i): continue - pl.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color) + plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color) # Plot an ellipse to show the Gaussian component angle = np.arctan2(w[0][1], w[0][0]) @@ -88,10 +88,10 @@ ell.set_alpha(.5) splot.add_artist(ell) -pl.xlim(-10, 10) -pl.ylim(-3, 6) -pl.xticks(()) -pl.yticks(()) -pl.title('Selected GMM: full model, 2 components') -pl.subplots_adjust(hspace=.35, bottom=.02) -pl.show() +plt.xlim(-10, 10) +plt.ylim(-3, 6) +plt.xticks(()) +plt.yticks(()) +plt.title('Selected GMM: full model, 2 components') +plt.subplots_adjust(hspace=.35, bottom=.02) +plt.show() diff --git a/examples/mixture/plot_gmm_sin.py b/examples/mixture/plot_gmm_sin.py index 1890a948c262f..0fe87a3bd71e4 100644 --- a/examples/mixture/plot_gmm_sin.py +++ b/examples/mixture/plot_gmm_sin.py @@ -7,8 +7,8 @@ complexity control and dealing with sparse data. The dataset is formed by 100 points loosely spaced following a noisy sine curve. The fit by the GMM class, using the expectation-maximization algorithm to fit a -mixture of 10 gaussian components, finds too-small components and very -little structure. The fits by the dirichlet process, however, show +mixture of 10 Gaussian components, finds too-small components and very +little structure. The fits by the Dirichlet process, however, show that the model can either learn a global structure for the data (small alpha) or easily interpolate to finding relevant local structure (large alpha), never falling into the problems shown by the GMM class. @@ -18,10 +18,11 @@ import numpy as np from scipy import linalg -import pylab as pl +import matplotlib.pyplot as plt import matplotlib as mpl from sklearn import mixture +from sklearn.externals.six.moves import xrange # Number of samples per component n_samples = 100 @@ -41,18 +42,17 @@ for i, (clf, title) in enumerate([ - (mixture.GMM(n_components=10, covariance_type='full', n_iter=100), \ - "Expectation-maximization"), - (mixture.DPGMM(n_components=10, covariance_type='full', - alpha=0.01, n_iter=100), + (mixture.GMM(n_components=10, covariance_type='full', n_iter=100), + "Expectation-maximization"), + (mixture.DPGMM(n_components=10, covariance_type='full', alpha=0.01, + n_iter=100), "Dirichlet Process,alpha=0.01"), - (mixture.DPGMM(n_components=10, covariance_type='diag', - alpha=100., n_iter=100), - "Dirichlet Process,alpha=100.") - ]): + (mixture.DPGMM(n_components=10, covariance_type='diag', alpha=100., + n_iter=100), + "Dirichlet Process,alpha=100.")]): clf.fit(X) - splot = pl.subplot(3, 1, 1 + i) + splot = plt.subplot(3, 1, 1 + i) Y_ = clf.predict(X) for i, (mean, covar, color) in enumerate(zip( clf.means_, clf._get_covars(), color_iter)): @@ -63,7 +63,7 @@ # components. if not np.any(Y_ == i): continue - pl.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color) + plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color) # Plot an ellipse to show the Gaussian component angle = np.arctan(u[1] / u[0]) @@ -73,10 +73,10 @@ ell.set_alpha(0.5) splot.add_artist(ell) - pl.xlim(-6, 4 * np.pi - 6) - pl.ylim(-5, 5) - pl.title(title) - pl.xticks(()) - pl.yticks(()) + plt.xlim(-6, 4 * np.pi - 6) + plt.ylim(-5, 5) + plt.title(title) + plt.xticks(()) + plt.yticks(()) -pl.show() +plt.show() diff --git a/examples/model_selection/README.txt b/examples/model_selection/README.txt new file mode 100644 index 0000000000000..553c6e7d6498e --- /dev/null +++ b/examples/model_selection/README.txt @@ -0,0 +1,7 @@ +.. _model_selection_examples: + +Model Selection +----------------------- + +Examples concerning model selection, mostly contained in the +:mod:`sklearn.grid_search` and :mod:`sklearn.cross_validation` modules. diff --git a/examples/grid_search_digits.py b/examples/model_selection/grid_search_digits.py similarity index 50% rename from examples/grid_search_digits.py rename to examples/model_selection/grid_search_digits.py index e3c9d9c5c469a..c8aec1bab8c0f 100644 --- a/examples/grid_search_digits.py +++ b/examples/model_selection/grid_search_digits.py @@ -1,11 +1,11 @@ """ -===================================================================== -Parameter estimation using grid search with a nested cross-validation -===================================================================== +============================================================ +Parameter estimation using grid search with cross-validation +============================================================ -The classifier is optimized by "nested" cross-validation using the -:class:`sklearn.grid_search.GridSearchCV` object on a development set -that comprises only half of the available labeled data. +This examples shows how a classifier is optimized by cross-validation, +which is done using the :class:`sklearn.grid_search.GridSearchCV` object +on a development set that comprises only half of the available labeled data. The performance of the selected hyper-parameters and trained model is then measured on a dedicated evaluation set that was not used during @@ -15,16 +15,17 @@ sections on :ref:`cross_validation` and :ref:`grid_search`. """ -print __doc__ + +from __future__ import print_function from sklearn import datasets from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV from sklearn.metrics import classification_report -from sklearn.metrics import precision_score -from sklearn.metrics import recall_score from sklearn.svm import SVC +print(__doc__) + # Loading the Digits dataset digits = datasets.load_digits() @@ -36,44 +37,42 @@ # Split the dataset in two equal parts X_train, X_test, y_train, y_test = train_test_split( - X, y, test_fraction=0.5, random_state=0) + X, y, test_size=0.5, random_state=0) # Set the parameters by cross-validation tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000]}, {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}] -scores = [ - ('precision', precision_score), - ('recall', recall_score), -] +scores = ['precision', 'recall'] -for score_name, score_func in scores: - print "# Tuning hyper-parameters for %s" % score_name - print +for score in scores: + print("# Tuning hyper-parameters for %s" % score) + print() - clf = GridSearchCV(SVC(C=1), tuned_parameters, score_func=score_func) - clf.fit(X_train, y_train, cv=5) + clf = GridSearchCV(SVC(C=1), tuned_parameters, cv=5, + scoring='%s_weighted' % score) + clf.fit(X_train, y_train) - print "Best parameters set found on development set:" - print - print clf.best_estimator_ - print - print "Grid scores on development set:" - print + print("Best parameters set found on development set:") + print() + print(clf.best_params_) + print() + print("Grid scores on development set:") + print() for params, mean_score, scores in clf.grid_scores_: - print "%0.3f (+/-%0.03f) for %r" % ( - mean_score, scores.std() / 2, params) - print - - print "Detailed classification report:" - print - print "The model is trained on the full development set." - print "The scores are computed on the full evaluation set." - print + print("%0.3f (+/-%0.03f) for %r" + % (mean_score, scores.std() * 2, params)) + print() + + print("Detailed classification report:") + print() + print("The model is trained on the full development set.") + print("The scores are computed on the full evaluation set.") + print() y_true, y_pred = y_test, clf.predict(X_test) - print classification_report(y_true, y_pred) - print + print(classification_report(y_true, y_pred)) + print() # Note the problem is too easy: the hyperparameter plateau is too flat and the # output model is the same for precision and recall with ties in quality. diff --git a/examples/grid_search_text_feature_extraction.py b/examples/model_selection/grid_search_text_feature_extraction.py similarity index 78% rename from examples/grid_search_text_feature_extraction.py rename to examples/model_selection/grid_search_text_feature_extraction.py index 3d229f7f78d65..11b690d91e2ef 100644 --- a/examples/grid_search_text_feature_extraction.py +++ b/examples/model_selection/grid_search_text_feature_extraction.py @@ -7,7 +7,7 @@ automatically downloaded and then cached and reused for the document classification example. -You can adjust the number of categories by giving there name to the dataset +You can adjust the number of categories by giving their names to the dataset loader or setting them to None to get the 20 of them. Here is a sample output of a run on a quad-core machine:: @@ -40,12 +40,13 @@ vect__max_features: 50000 """ -print __doc__ # Author: Olivier Grisel # Peter Prettenhofer # Mathieu Blondel -# License: Simplified BSD +# License: BSD 3 clause + +from __future__ import print_function from pprint import pprint from time import time @@ -58,6 +59,8 @@ from sklearn.grid_search import GridSearchCV from sklearn.pipeline import Pipeline +print(__doc__) + # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') @@ -72,13 +75,13 @@ # Uncomment the following to do the analysis on all the categories #categories = None -print "Loading 20 newsgroups dataset for categories:" -print categories +print("Loading 20 newsgroups dataset for categories:") +print(categories) data = fetch_20newsgroups(subset='train', categories=categories) -print "%d documents" % len(data.filenames) -print "%d categories" % len(data.target_names) -print +print("%d documents" % len(data.filenames)) +print("%d categories" % len(data.target_names)) +print() ############################################################################### # define a pipeline combining a text feature extractor with a simple @@ -89,17 +92,17 @@ ('clf', SGDClassifier()), ]) -parameters = { # uncommenting more parameters will give better exploring power but will # increase processing time in a combinatorial way +parameters = { 'vect__max_df': (0.5, 0.75, 1.0), -# 'vect__max_features': (None, 5000, 10000, 50000), - 'vect__max_n': (1, 2), # words or bigrams -# 'tfidf__use_idf': (True, False), -# 'tfidf__norm': ('l1', 'l2'), + #'vect__max_features': (None, 5000, 10000, 50000), + 'vect__ngram_range': ((1, 1), (1, 2)), # unigrams or bigrams + #'tfidf__use_idf': (True, False), + #'tfidf__norm': ('l1', 'l2'), 'clf__alpha': (0.00001, 0.000001), 'clf__penalty': ('l2', 'elasticnet'), -# 'clf__n_iter': (10, 50, 80), + #'clf__n_iter': (10, 50, 80), } if __name__ == "__main__": @@ -110,17 +113,17 @@ # classifier grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=1) - print "Performing grid search..." - print "pipeline:", [name for name, _ in pipeline.steps] - print "parameters:" + print("Performing grid search...") + print("pipeline:", [name for name, _ in pipeline.steps]) + print("parameters:") pprint(parameters) t0 = time() grid_search.fit(data.data, data.target) - print "done in %0.3fs" % (time() - t0) - print + print("done in %0.3fs" % (time() - t0)) + print() - print "Best score: %0.3f" % grid_search.best_score_ - print "Best parameters set:" + print("Best score: %0.3f" % grid_search.best_score_) + print("Best parameters set:") best_parameters = grid_search.best_estimator_.get_params() for param_name in sorted(parameters.keys()): - print "\t%s: %r" % (param_name, best_parameters[param_name]) + print("\t%s: %r" % (param_name, best_parameters[param_name])) diff --git a/examples/model_selection/plot_confusion_matrix.py b/examples/model_selection/plot_confusion_matrix.py new file mode 100644 index 0000000000000..771d058e2a4a5 --- /dev/null +++ b/examples/model_selection/plot_confusion_matrix.py @@ -0,0 +1,78 @@ +""" +================ +Confusion matrix +================ + +Example of confusion matrix usage to evaluate the quality +of the output of a classifier on the iris data set. The +diagonal elements represent the number of points for which +the predicted label is equal to the true label, while +off-diagonal elements are those that are mislabeled by the +classifier. The higher the diagonal values of the confusion +matrix the better, indicating many correct predictions. + +The figures show the confusion matrix with and without +normalization by class support size (number of elements +in each class). This kind of normalization can be +interesting in case of class imbalance to have a more +visual interpretation of which class is being misclassified. + +Here the results are not as good as they could be as our +choice for the regularization parameter C was not the best. +In real life applications this parameter is usually chosen +using :ref:`grid_search`. + +""" + +print(__doc__) + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn import svm, datasets +from sklearn.cross_validation import train_test_split +from sklearn.metrics import confusion_matrix + +# import some data to play with +iris = datasets.load_iris() +X = iris.data +y = iris.target + +# Split the data into a training set and a test set +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + +# Run classifier, using a model that is too regularized (C too low) to see +# the impact on the results +classifier = svm.SVC(kernel='linear', C=0.01) +y_pred = classifier.fit(X_train, y_train).predict(X_test) + + +def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues): + plt.imshow(cm, interpolation='nearest', cmap=cmap) + plt.title(title) + plt.colorbar() + tick_marks = np.arange(len(iris.target_names)) + plt.xticks(tick_marks, iris.target_names, rotation=45) + plt.yticks(tick_marks, iris.target_names) + plt.tight_layout() + plt.ylabel('True label') + plt.xlabel('Predicted label') + + +# Compute confusion matrix +cm = confusion_matrix(y_test, y_pred) +np.set_printoptions(precision=2) +print('Confusion matrix, without normalization') +print(cm) +plt.figure() +plot_confusion_matrix(cm) + +# Normalize the confusion matrix by row (i.e by the number of samples +# in each class) +cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] +print('Normalized confusion matrix') +print(cm_normalized) +plt.figure() +plot_confusion_matrix(cm_normalized, title='Normalized confusion matrix') + +plt.show() diff --git a/examples/model_selection/plot_learning_curve.py b/examples/model_selection/plot_learning_curve.py new file mode 100644 index 0000000000000..7a47fd574635d --- /dev/null +++ b/examples/model_selection/plot_learning_curve.py @@ -0,0 +1,107 @@ +""" +======================== +Plotting Learning Curves +======================== + +On the left side the learning curve of a naive Bayes classifier is shown for +the digits dataset. Note that the training score and the cross-validation score +are both not very good at the end. However, the shape of the curve can be found +in more complex datasets very often: the training score is very high at the +beginning and decreases and the cross-validation score is very low at the +beginning and increases. On the right side we see the learning curve of an SVM +with RBF kernel. We can see clearly that the training score is still around +the maximum and the validation score could be increased with more training +samples. +""" +print(__doc__) + +import numpy as np +import matplotlib.pyplot as plt +from sklearn import cross_validation +from sklearn.naive_bayes import GaussianNB +from sklearn.svm import SVC +from sklearn.datasets import load_digits +from sklearn.learning_curve import learning_curve + + +def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, + n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): + """ + Generate a simple plot of the test and traning learning curve. + + Parameters + ---------- + estimator : object type that implements the "fit" and "predict" methods + An object of that type which is cloned for each validation. + + title : string + Title for the chart. + + X : array-like, shape (n_samples, n_features) + Training vector, where n_samples is the number of samples and + n_features is the number of features. + + y : array-like, shape (n_samples) or (n_samples, n_features), optional + Target relative to X for classification or regression; + None for unsupervised learning. + + ylim : tuple, shape (ymin, ymax), optional + Defines minimum and maximum yvalues plotted. + + cv : integer, cross-validation generator, optional + If an integer is passed, it is the number of folds (defaults to 3). + Specific cross-validation objects can be passed, see + sklearn.cross_validation module for the list of possible objects + + n_jobs : integer, optional + Number of jobs to run in parallel (default 1). + """ + plt.figure() + plt.title(title) + if ylim is not None: + plt.ylim(*ylim) + plt.xlabel("Training examples") + plt.ylabel("Score") + train_sizes, train_scores, test_scores = learning_curve( + estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) + train_scores_mean = np.mean(train_scores, axis=1) + train_scores_std = np.std(train_scores, axis=1) + test_scores_mean = np.mean(test_scores, axis=1) + test_scores_std = np.std(test_scores, axis=1) + plt.grid() + + plt.fill_between(train_sizes, train_scores_mean - train_scores_std, + train_scores_mean + train_scores_std, alpha=0.1, + color="r") + plt.fill_between(train_sizes, test_scores_mean - test_scores_std, + test_scores_mean + test_scores_std, alpha=0.1, color="g") + plt.plot(train_sizes, train_scores_mean, 'o-', color="r", + label="Training score") + plt.plot(train_sizes, test_scores_mean, 'o-', color="g", + label="Cross-validation score") + + plt.legend(loc="best") + return plt + + +digits = load_digits() +X, y = digits.data, digits.target + + +title = "Learning Curves (Naive Bayes)" +# Cross validation with 100 iterations to get smoother mean test and train +# score curves, each time with 20% data randomly selected as a validation set. +cv = cross_validation.ShuffleSplit(digits.data.shape[0], n_iter=100, + test_size=0.2, random_state=0) + +estimator = GaussianNB() +plot_learning_curve(estimator, title, X, y, ylim=(0.7, 1.01), cv=cv, n_jobs=4) + +title = "Learning Curves (SVM, RBF kernel, $\gamma=0.001$)" +# SVC is more expensive so we do a lower number of CV iterations: +cv = cross_validation.ShuffleSplit(digits.data.shape[0], n_iter=10, + test_size=0.2, random_state=0) +estimator = SVC(gamma=0.001) +plot_learning_curve(estimator, title, X, y, (0.7, 1.01), cv=cv, n_jobs=4) + +plt.show() diff --git a/examples/model_selection/plot_precision_recall.py b/examples/model_selection/plot_precision_recall.py new file mode 100644 index 0000000000000..6617a6b5d88fa --- /dev/null +++ b/examples/model_selection/plot_precision_recall.py @@ -0,0 +1,150 @@ +""" +================ +Precision-Recall +================ + +Example of Precision-Recall metric to evaluate classifier output quality. + +In information retrieval, precision is a measure of result relevancy, while +recall is a measure of how many truly relevant results are returned. A high +area under the curve represents both high recall and high precision, where high +precision relates to a low false positive rate, and high recall relates to a +low false negative rate. High scores for both show that the classifier is +returning accurate results (high precision), as well as returning a majority of +all positive results (high recall). + +A system with high recall but low precision returns many results, but most of +its predicted labels are incorrect when compared to the training labels. A +system with high precision but low recall is just the opposite, returning very +few results, but most of its predicted labels are correct when compared to the +training labels. An ideal system with high precision and high recall will +return many results, with all results labeled correctly. + +Precision (:math:`P`) is defined as the number of true positives (:math:`T_p`) +over the number of true positives plus the number of false positives +(:math:`F_p`). + +:math:`P = \\frac{T_p}{T_p+F_p}` + +Recall (:math:`R`) is defined as the number of true positives (:math:`T_p`) +over the number of true positives plus the number of false negatives +(:math:`F_n`). + +:math:`R = \\frac{T_p}{T_p + F_n}` + +These quantities are also related to the (:math:`F_1`) score, which is defined +as the harmonic mean of precision and recall. + +:math:`F1 = 2\\frac{P \\times R}{P+R}` + +It is important to note that the precision may not decrease with recall. The +definition of precision (:math:`\\frac{T_p}{T_p + F_p}`) shows that lowering +the threshold of a classifier may increase the denominator, by increasing the +number of results returned. If the threshold was previously set too high, the +new results may all be true positives, which will increase precision. If the +previous threshold was about right or too low, further lowering the threshold +will introduce false positives, decreasing precision. + +Recall is defined as :math:`\\frac{T_p}{T_p+F_n}`, where :math:`T_p+F_n` does +not depend on the classifier threshold. This means that lowering the classifier +threshold may increase recall, by increasing the number of true positive +results. It is also possible that lowering the threshold may leave recall +unchanged, while the precision fluctuates. + +The relationship between recall and precision can be observed in the +stairstep area of the plot - at the edges of these steps a small change +in the threshold considerably reduces precision, with only a minor gain in +recall. See the corner at recall = .59, precision = .8 for an example of this +phenomenon. + +Precision-recall curves are typically used in binary classification to study +the output of a classifier. In order to extend Precision-recall curve and +average precision to multi-class or multi-label classification, it is necessary +to binarize the output. One curve can be drawn per label, but one can also draw +a precision-recall curve by considering each element of the label indicator +matrix as a binary prediction (micro-averaging). + +.. note:: + + See also :func:`sklearn.metrics.average_precision_score`, + :func:`sklearn.metrics.recall_score`, + :func:`sklearn.metrics.precision_score`, + :func:`sklearn.metrics.f1_score` +""" +print(__doc__) + +import matplotlib.pyplot as plt +import numpy as np +from sklearn import svm, datasets +from sklearn.metrics import precision_recall_curve +from sklearn.metrics import average_precision_score +from sklearn.cross_validation import train_test_split +from sklearn.preprocessing import label_binarize +from sklearn.multiclass import OneVsRestClassifier + +# import some data to play with +iris = datasets.load_iris() +X = iris.data +y = iris.target + +# Binarize the output +y = label_binarize(y, classes=[0, 1, 2]) +n_classes = y.shape[1] + +# Add noisy features +random_state = np.random.RandomState(0) +n_samples, n_features = X.shape +X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] + +# Split into training and test +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, + random_state=random_state) + +# Run classifier +classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, + random_state=random_state)) +y_score = classifier.fit(X_train, y_train).decision_function(X_test) + +# Compute Precision-Recall and plot curve +precision = dict() +recall = dict() +average_precision = dict() +for i in range(n_classes): + precision[i], recall[i], _ = precision_recall_curve(y_test[:, i], + y_score[:, i]) + average_precision[i] = average_precision_score(y_test[:, i], y_score[:, i]) + +# Compute micro-average ROC curve and ROC area +precision["micro"], recall["micro"], _ = precision_recall_curve(y_test.ravel(), + y_score.ravel()) +average_precision["micro"] = average_precision_score(y_test, y_score, + average="micro") + +# Plot Precision-Recall curve +plt.clf() +plt.plot(recall[0], precision[0], label='Precision-Recall curve') +plt.xlabel('Recall') +plt.ylabel('Precision') +plt.ylim([0.0, 1.05]) +plt.xlim([0.0, 1.0]) +plt.title('Precision-Recall example: AUC={0:0.2f}'.format(average_precision[0])) +plt.legend(loc="lower left") +plt.show() + +# Plot Precision-Recall curve for each class +plt.clf() +plt.plot(recall["micro"], precision["micro"], + label='micro-average Precision-recall curve (area = {0:0.2f})' + ''.format(average_precision["micro"])) +for i in range(n_classes): + plt.plot(recall[i], precision[i], + label='Precision-recall curve of class {0} (area = {1:0.2f})' + ''.format(i, average_precision[i])) + +plt.xlim([0.0, 1.0]) +plt.ylim([0.0, 1.05]) +plt.xlabel('Recall') +plt.ylabel('Precision') +plt.title('Extension of Precision-Recall curve to multi-class') +plt.legend(loc="lower right") +plt.show() diff --git a/examples/model_selection/plot_roc.py b/examples/model_selection/plot_roc.py new file mode 100644 index 0000000000000..49ae4b5fe5ce7 --- /dev/null +++ b/examples/model_selection/plot_roc.py @@ -0,0 +1,104 @@ +""" +======================================= +Receiver Operating Characteristic (ROC) +======================================= + +Example of Receiver Operating Characteristic (ROC) metric to evaluate +classifier output quality. + +ROC curves typically feature true positive rate on the Y axis, and false +positive rate on the X axis. This means that the top left corner of the plot is +the "ideal" point - a false positive rate of zero, and a true positive rate of +one. This is not very realistic, but it does mean that a larger area under the +curve (AUC) is usually better. + +The "steepness" of ROC curves is also important, since it is ideal to maximize +the true positive rate while minimizing the false positive rate. + +ROC curves are typically used in binary classification to study the output of +a classifier. In order to extend ROC curve and ROC area to multi-class +or multi-label classification, it is necessary to binarize the output. One ROC +curve can be drawn per label, but one can also draw a ROC curve by considering +each element of the label indicator matrix as a binary prediction +(micro-averaging). + +.. note:: + + See also :func:`sklearn.metrics.roc_auc_score`, + :ref:`example_model_selection_plot_roc_crossval.py`. + +""" +print(__doc__) + +import numpy as np +import matplotlib.pyplot as plt +from sklearn import svm, datasets +from sklearn.metrics import roc_curve, auc +from sklearn.cross_validation import train_test_split +from sklearn.preprocessing import label_binarize +from sklearn.multiclass import OneVsRestClassifier + +# Import some data to play with +iris = datasets.load_iris() +X = iris.data +y = iris.target + +# Binarize the output +y = label_binarize(y, classes=[0, 1, 2]) +n_classes = y.shape[1] + +# Add noisy features to make the problem harder +random_state = np.random.RandomState(0) +n_samples, n_features = X.shape +X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] + +# shuffle and split training and test sets +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, + random_state=0) + +# Learn to predict each class against the other +classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, + random_state=random_state)) +y_score = classifier.fit(X_train, y_train).decision_function(X_test) + +# Compute ROC curve and ROC area for each class +fpr = dict() +tpr = dict() +roc_auc = dict() +for i in range(n_classes): + fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) + roc_auc[i] = auc(fpr[i], tpr[i]) + +# Compute micro-average ROC curve and ROC area +fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel()) +roc_auc["micro"] = auc(fpr["micro"], tpr["micro"]) + +# Plot of a ROC curve for a specific class +plt.figure() +plt.plot(fpr[2], tpr[2], label='ROC curve (area = %0.2f)' % roc_auc[2]) +plt.plot([0, 1], [0, 1], 'k--') +plt.xlim([0.0, 1.0]) +plt.ylim([0.0, 1.05]) +plt.xlabel('False Positive Rate') +plt.ylabel('True Positive Rate') +plt.title('Receiver operating characteristic example') +plt.legend(loc="lower right") +plt.show() + +# Plot ROC curve +plt.figure() +plt.plot(fpr["micro"], tpr["micro"], + label='micro-average ROC curve (area = {0:0.2f})' + ''.format(roc_auc["micro"])) +for i in range(n_classes): + plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})' + ''.format(i, roc_auc[i])) + +plt.plot([0, 1], [0, 1], 'k--') +plt.xlim([0.0, 1.0]) +plt.ylim([0.0, 1.05]) +plt.xlabel('False Positive Rate') +plt.ylabel('True Positive Rate') +plt.title('Some extension of Receiver operating characteristic to multi-class') +plt.legend(loc="lower right") +plt.show() diff --git a/examples/model_selection/plot_roc_crossval.py b/examples/model_selection/plot_roc_crossval.py new file mode 100644 index 0000000000000..0599813653640 --- /dev/null +++ b/examples/model_selection/plot_roc_crossval.py @@ -0,0 +1,91 @@ +""" +============================================================= +Receiver Operating Characteristic (ROC) with cross validation +============================================================= + +Example of Receiver Operating Characteristic (ROC) metric to evaluate +classifier output quality using cross-validation. + +ROC curves typically feature true positive rate on the Y axis, and false +positive rate on the X axis. This means that the top left corner of the plot is +the "ideal" point - a false positive rate of zero, and a true positive rate of +one. This is not very realistic, but it does mean that a larger area under the +curve (AUC) is usually better. + +The "steepness" of ROC curves is also important, since it is ideal to maximize +the true positive rate while minimizing the false positive rate. + +This example shows the ROC response of different datasets, created from K-fold +cross-validation. Taking all of these curves, it is possible to calculate the +mean area under curve, and see the variance of the curve when the +training set is split into different subsets. This roughly shows how the +classifier output is affected by changes in the training data, and how +different the splits generated by K-fold cross-validation are from one another. + +.. note:: + + See also :func:`sklearn.metrics.auc_score`, + :func:`sklearn.cross_validation.cross_val_score`, + :ref:`example_model_selection_plot_roc.py`, + +""" +print(__doc__) + +import numpy as np +from scipy import interp +import matplotlib.pyplot as plt + +from sklearn import svm, datasets +from sklearn.metrics import roc_curve, auc +from sklearn.cross_validation import StratifiedKFold + +############################################################################### +# Data IO and generation + +# import some data to play with +iris = datasets.load_iris() +X = iris.data +y = iris.target +X, y = X[y != 2], y[y != 2] +n_samples, n_features = X.shape + +# Add noisy features +random_state = np.random.RandomState(0) +X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] + +############################################################################### +# Classification and ROC analysis + +# Run classifier with cross-validation and plot ROC curves +cv = StratifiedKFold(y, n_folds=6) +classifier = svm.SVC(kernel='linear', probability=True, + random_state=random_state) + +mean_tpr = 0.0 +mean_fpr = np.linspace(0, 1, 100) +all_tpr = [] + +for i, (train, test) in enumerate(cv): + probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test]) + # Compute ROC curve and area the curve + fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1]) + mean_tpr += interp(mean_fpr, fpr, tpr) + mean_tpr[0] = 0.0 + roc_auc = auc(fpr, tpr) + plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc)) + +plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') + +mean_tpr /= len(cv) +mean_tpr[-1] = 1.0 +mean_auc = auc(mean_fpr, mean_tpr) +plt.plot(mean_fpr, mean_tpr, 'k--', + label='Mean ROC (area = %0.2f)' % mean_auc, lw=2) + +plt.xlim([-0.05, 1.05]) +plt.ylim([-0.05, 1.05]) +plt.xlabel('False Positive Rate') +plt.ylabel('True Positive Rate') +plt.title('Receiver operating characteristic example') +plt.legend(loc="lower right") +plt.show() diff --git a/examples/plot_train_error_vs_test_error.py b/examples/model_selection/plot_train_error_vs_test_error.py similarity index 72% rename from examples/plot_train_error_vs_test_error.py rename to examples/model_selection/plot_train_error_vs_test_error.py index 9fada7db4ed32..9002a0a3a5f30 100644 --- a/examples/plot_train_error_vs_test_error.py +++ b/examples/model_selection/plot_train_error_vs_test_error.py @@ -11,10 +11,10 @@ measured using the explained variance a.k.a. R^2. """ -print __doc__ +print(__doc__) # Author: Alexandre Gramfort -# License: BSD Style. +# License: BSD 3 clause import numpy as np from sklearn import linear_model @@ -35,7 +35,7 @@ ############################################################################### # Compute train and test errors alphas = np.logspace(-5, 1, 60) -enet = linear_model.ElasticNet(rho=0.7) +enet = linear_model.ElasticNet(l1_ratio=0.7) train_errors = list() test_errors = list() for alpha in alphas: @@ -46,7 +46,7 @@ i_alpha_optim = np.argmax(test_errors) alpha_optim = alphas[i_alpha_optim] -print "Optimal regularization parameter : %s" % alpha_optim +print("Optimal regularization parameter : %s" % alpha_optim) # Estimate the coef_ on full data with optimal regularization parameter enet.set_params(alpha=alpha_optim) @@ -55,21 +55,21 @@ ############################################################################### # Plot results functions -import pylab as pl -pl.subplot(2, 1, 1) -pl.semilogx(alphas, train_errors, label='Train') -pl.semilogx(alphas, test_errors, label='Test') -pl.vlines(alpha_optim, pl.ylim()[0], np.max(test_errors), - color='k', linewidth=3, label='Optimum on test') -pl.legend(loc='lower left') -pl.ylim([0, 1.2]) -pl.xlabel('Regularization parameter') -pl.ylabel('Performance') +import matplotlib.pyplot as plt +plt.subplot(2, 1, 1) +plt.semilogx(alphas, train_errors, label='Train') +plt.semilogx(alphas, test_errors, label='Test') +plt.vlines(alpha_optim, plt.ylim()[0], np.max(test_errors), color='k', + linewidth=3, label='Optimum on test') +plt.legend(loc='lower left') +plt.ylim([0, 1.2]) +plt.xlabel('Regularization parameter') +plt.ylabel('Performance') # Show estimated coef_ vs true coef -pl.subplot(2, 1, 2) -pl.plot(coef, label='True coef') -pl.plot(coef_, label='Estimated coef') -pl.legend() -pl.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.26) -pl.show() +plt.subplot(2, 1, 2) +plt.plot(coef, label='True coef') +plt.plot(coef_, label='Estimated coef') +plt.legend() +plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.26) +plt.show() diff --git a/examples/model_selection/plot_underfitting_overfitting.py b/examples/model_selection/plot_underfitting_overfitting.py new file mode 100644 index 0000000000000..f8958cbffe21b --- /dev/null +++ b/examples/model_selection/plot_underfitting_overfitting.py @@ -0,0 +1,68 @@ +""" +============================ +Underfitting vs. Overfitting +============================ + +This example demonstrates the problems of underfitting and overfitting and +how we can use linear regression with polynomial features to approximate +nonlinear functions. The plot shows the function that we want to approximate, +which is a part of the cosine function. In addition, the samples from the +real function and the approximations of different models are displayed. The +models have polynomial features of different degrees. We can see that a +linear function (polynomial with degree 1) is not sufficient to fit the +training samples. This is called **underfitting**. A polynomial of degree 4 +approximates the true function almost perfectly. However, for higher degrees +the model will **overfit** the training data, i.e. it learns the noise of the +training data. +We evaluate quantitatively **overfitting** / **underfitting** by using +cross-validation. We calculate the mean squared error (MSE) on the validation +set, the higher, the less likely the model generalizes correctly from the +training data. +""" + +print(__doc__) + +import numpy as np +import matplotlib.pyplot as plt +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import PolynomialFeatures +from sklearn.linear_model import LinearRegression +from sklearn import cross_validation + +np.random.seed(0) + +n_samples = 30 +degrees = [1, 4, 15] + +true_fun = lambda X: np.cos(1.5 * np.pi * X) +X = np.sort(np.random.rand(n_samples)) +y = true_fun(X) + np.random.randn(n_samples) * 0.1 + +plt.figure(figsize=(14, 5)) +for i in range(len(degrees)): + ax = plt.subplot(1, len(degrees), i + 1) + plt.setp(ax, xticks=(), yticks=()) + + polynomial_features = PolynomialFeatures(degree=degrees[i], + include_bias=False) + linear_regression = LinearRegression() + pipeline = Pipeline([("polynomial_features", polynomial_features), + ("linear_regression", linear_regression)]) + pipeline.fit(X[:, np.newaxis], y) + + # Evaluate the models using crossvalidation + scores = cross_validation.cross_val_score(pipeline, + X[:, np.newaxis], y, scoring="mean_squared_error", cv=10) + + X_test = np.linspace(0, 1, 100) + plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model") + plt.plot(X_test, true_fun(X_test), label="True function") + plt.scatter(X, y, label="Samples") + plt.xlabel("x") + plt.ylabel("y") + plt.xlim((0, 1)) + plt.ylim((-2, 2)) + plt.legend(loc="best") + plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( + degrees[i], -scores.mean(), scores.std())) +plt.show() diff --git a/examples/model_selection/plot_validation_curve.py b/examples/model_selection/plot_validation_curve.py new file mode 100644 index 0000000000000..336e0349eacbf --- /dev/null +++ b/examples/model_selection/plot_validation_curve.py @@ -0,0 +1,46 @@ +""" +========================== +Plotting Validation Curves +========================== + +In this plot you can see the training scores and validation scores of an SVM +for different values of the kernel parameter gamma. For very low values of +gamma, you can see that both the training score and the validation score are +low. This is called underfitting. Medium values of gamma will result in high +values for both scores, i.e. the classifier is performing fairly well. If gamma +is too high, the classifier will overfit, which means that the training score +is good but the validation score is poor. +""" +print(__doc__) + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.datasets import load_digits +from sklearn.svm import SVC +from sklearn.learning_curve import validation_curve + +digits = load_digits() +X, y = digits.data, digits.target + +param_range = np.logspace(-6, -1, 5) +train_scores, test_scores = validation_curve( + SVC(), X, y, param_name="gamma", param_range=param_range, + cv=10, scoring="accuracy", n_jobs=1) +train_scores_mean = np.mean(train_scores, axis=1) +train_scores_std = np.std(train_scores, axis=1) +test_scores_mean = np.mean(test_scores, axis=1) +test_scores_std = np.std(test_scores, axis=1) + +plt.title("Validation Curve with SVM") +plt.xlabel("$\gamma$") +plt.ylabel("Score") +plt.ylim(0.0, 1.1) +plt.semilogx(param_range, train_scores_mean, label="Training score", color="r") +plt.fill_between(param_range, train_scores_mean - train_scores_std, + train_scores_mean + train_scores_std, alpha=0.2, color="r") +plt.semilogx(param_range, test_scores_mean, label="Cross-validation score", + color="g") +plt.fill_between(param_range, test_scores_mean - test_scores_std, + test_scores_mean + test_scores_std, alpha=0.2, color="g") +plt.legend(loc="best") +plt.show() diff --git a/examples/model_selection/randomized_search.py b/examples/model_selection/randomized_search.py new file mode 100644 index 0000000000000..14a15139448d0 --- /dev/null +++ b/examples/model_selection/randomized_search.py @@ -0,0 +1,87 @@ +""" +========================================================================= +Comparing randomized search and grid search for hyperparameter estimation +========================================================================= + +Compare randomized search and grid search for optimizing hyperparameters of a +random forest. +All parameters that influence the learning are searched simultaneously +(except for the number of estimators, which poses a time / quality tradeoff). + +The randomized search and the grid search explore exactly the same space of +parameters. The result in parameter settings is quite similar, while the run +time for randomized search is drastically lower. + +The performance is slightly worse for the randomized search, though this +is most likely a noise effect and would not carry over to a held-out test set. + +Note that in practice, one would not search over this many different parameters +simultaneously using grid search, but pick only the ones deemed most important. +""" +print(__doc__) + +import numpy as np + +from time import time +from operator import itemgetter +from scipy.stats import randint as sp_randint + +from sklearn.grid_search import GridSearchCV, RandomizedSearchCV +from sklearn.datasets import load_digits +from sklearn.ensemble import RandomForestClassifier + +# get some data +iris = load_digits() +X, y = iris.data, iris.target + +# build a classifier +clf = RandomForestClassifier(n_estimators=20) + + +# Utility function to report best scores +def report(grid_scores, n_top=3): + top_scores = sorted(grid_scores, key=itemgetter(1), reverse=True)[:n_top] + for i, score in enumerate(top_scores): + print("Model with rank: {0}".format(i + 1)) + print("Mean validation score: {0:.3f} (std: {1:.3f})".format( + score.mean_validation_score, + np.std(score.cv_validation_scores))) + print("Parameters: {0}".format(score.parameters)) + print("") + + +# specify parameters and distributions to sample from +param_dist = {"max_depth": [3, None], + "max_features": sp_randint(1, 11), + "min_samples_split": sp_randint(1, 11), + "min_samples_leaf": sp_randint(1, 11), + "bootstrap": [True, False], + "criterion": ["gini", "entropy"]} + +# run randomized search +n_iter_search = 20 +random_search = RandomizedSearchCV(clf, param_distributions=param_dist, + n_iter=n_iter_search) + +start = time() +random_search.fit(X, y) +print("RandomizedSearchCV took %.2f seconds for %d candidates" + " parameter settings." % ((time() - start), n_iter_search)) +report(random_search.grid_scores_) + +# use a full grid over all parameters +param_grid = {"max_depth": [3, None], + "max_features": [1, 3, 10], + "min_samples_split": [1, 3, 10], + "min_samples_leaf": [1, 3, 10], + "bootstrap": [True, False], + "criterion": ["gini", "entropy"]} + +# run grid search +grid_search = GridSearchCV(clf, param_grid=param_grid) +start = time() +grid_search.fit(X, y) + +print("GridSearchCV took %.2f seconds for %d candidate parameter settings." + % (time() - start, len(grid_search.grid_scores_))) +report(grid_search.grid_scores_) diff --git a/examples/neighbors/README.txt b/examples/neighbors/README.txt index 346bcd8095df6..72716912581e5 100644 --- a/examples/neighbors/README.txt +++ b/examples/neighbors/README.txt @@ -3,4 +3,4 @@ Nearest Neighbors ----------------------- -Examples concerning the :mod:`sklearn.neighbors` package. +Examples concerning the :mod:`sklearn.neighbors` module. diff --git a/examples/neighbors/plot_approximate_nearest_neighbors_hyperparameters.py b/examples/neighbors/plot_approximate_nearest_neighbors_hyperparameters.py new file mode 100644 index 0000000000000..207e4e634c51b --- /dev/null +++ b/examples/neighbors/plot_approximate_nearest_neighbors_hyperparameters.py @@ -0,0 +1,132 @@ +""" +================================================= +Hyper-parameters of Approximate Nearest Neighbors +================================================= + +This example demonstrates the behaviour of the +accuracy of the nearest neighbor queries of Locality Sensitive Hashing +Forest as the number of candidates and the number of estimators (trees) +vary. + +In the first plot, accuracy is measured with the number of candidates. Here, +the term "number of candidates" refers to maximum bound for the number of +distinct points retrieved from each tree to calculate the distances. Nearest +neighbors are selected from this pool of candidates. Number of estimators is +maintained at three fixed levels (1, 5, 10). + +In the second plot, the number of candidates is fixed at 50. Number of trees +is varied and the accuracy is plotted against those values. To measure the +accuracy, the true nearest neighbors are required, therefore +:class:`sklearn.neighbors.NearestNeighbors` is used to compute the exact +neighbors. +""" +from __future__ import division +print(__doc__) + +# Author: Maheshakya Wijewardena +# +# License: BSD 3 clause + + +############################################################################### +import numpy as np +from sklearn.datasets.samples_generator import make_blobs +from sklearn.neighbors import LSHForest +from sklearn.neighbors import NearestNeighbors +import matplotlib.pyplot as plt + + +# Initialize size of the database, iterations and required neighbors. +n_samples = 10000 +n_features = 100 +n_queries = 30 +rng = np.random.RandomState(42) + +# Generate sample data +X, _ = make_blobs(n_samples=n_samples + n_queries, + n_features=n_features, centers=10, + random_state=0) +X_index = X[:n_samples] +X_query = X[n_samples:] +# Get exact neighbors +nbrs = NearestNeighbors(n_neighbors=1, algorithm='brute', + metric='cosine').fit(X_index) +neighbors_exact = nbrs.kneighbors(X_query, return_distance=False) + +# Set `n_candidate` values +n_candidates_values = np.linspace(10, 500, 5).astype(np.int) +n_estimators_for_candidate_value = [1, 5, 10] +n_iter = 10 +stds_accuracies = np.zeros((len(n_estimators_for_candidate_value), + n_candidates_values.shape[0]), + dtype=float) +accuracies_c = np.zeros((len(n_estimators_for_candidate_value), + n_candidates_values.shape[0]), dtype=float) + +# LSH Forest is a stochastic index: perform several iteration to estimate +# expected accuracy and standard deviation displayed as error bars in +# the plots +for j, value in enumerate(n_estimators_for_candidate_value): + for i, n_candidates in enumerate(n_candidates_values): + accuracy_c = [] + for seed in range(n_iter): + lshf = LSHForest(n_estimators=value, + n_candidates=n_candidates, n_neighbors=1, + random_state=seed) + # Build the LSH Forest index + lshf.fit(X_index) + # Get neighbors + neighbors_approx = lshf.kneighbors(X_query, + return_distance=False) + accuracy_c.append(np.sum(np.equal(neighbors_approx, + neighbors_exact)) / + n_queries) + + stds_accuracies[j, i] = np.std(accuracy_c) + accuracies_c[j, i] = np.mean(accuracy_c) + +# Set `n_estimators` values +n_estimators_values = [1, 5, 10, 20, 30, 40, 50] +accuracies_trees = np.zeros(len(n_estimators_values), dtype=float) + +# Calculate average accuracy for each value of `n_estimators` +for i, n_estimators in enumerate(n_estimators_values): + lshf = LSHForest(n_estimators=n_estimators, n_neighbors=1) + # Build the LSH Forest index + lshf.fit(X_index) + # Get neighbors + neighbors_approx = lshf.kneighbors(X_query, return_distance=False) + accuracies_trees[i] = np.sum(np.equal(neighbors_approx, + neighbors_exact))/n_queries + +############################################################################### +# Plot the accuracy variation with `n_candidates` +plt.figure() +colors = ['c', 'm', 'y'] +for i, n_estimators in enumerate(n_estimators_for_candidate_value): + label = 'n_estimators = %d ' % n_estimators + plt.plot(n_candidates_values, accuracies_c[i, :], + 'o-', c=colors[i], label=label) + plt.errorbar(n_candidates_values, accuracies_c[i, :], + stds_accuracies[i, :], c=colors[i]) + +plt.legend(loc='upper left', fontsize='small') +plt.ylim([0, 1.2]) +plt.xlim(min(n_candidates_values), max(n_candidates_values)) +plt.ylabel("Accuracy") +plt.xlabel("n_candidates") +plt.grid(which='both') +plt.title("Accuracy variation with n_candidates") + +# Plot the accuracy variation with `n_estimators` +plt.figure() +plt.scatter(n_estimators_values, accuracies_trees, c='k') +plt.plot(n_estimators_values, accuracies_trees, c='g') +plt.ylim([0, 1.2]) +plt.xlim(min(n_estimators_values), max(n_estimators_values)) +plt.ylabel("Accuracy") +plt.xlabel("n_estimators") +plt.grid(which='both') +plt.title("Accuracy variation with n_estimators") + +plt.show() diff --git a/examples/neighbors/plot_approximate_nearest_neighbors_scalability.py b/examples/neighbors/plot_approximate_nearest_neighbors_scalability.py new file mode 100644 index 0000000000000..00d8d8c91729e --- /dev/null +++ b/examples/neighbors/plot_approximate_nearest_neighbors_scalability.py @@ -0,0 +1,156 @@ +""" +============================================ +Scalability of Approximate Nearest Neighbors +============================================ + +This example studies the scalability profile of approximate 10-neighbors +queries using the LSHForest with ``n_estimators=20`` and ``n_candidates=200`` +when varying the number of samples in the dataset. + +The first plot demonstrates the relationship between query time and index size +of LSHForest. Query time is compared with the brute force method in exact +nearest neighbor search for the same index sizes. The brute force queries have a +very predictable linear scalability with the index (full scan). LSHForest index +have sub-linear scalability profile but can be slower for small datasets. + +The second plot shows the speedup when using approximate queries vs brute force +exact queries. The speedup tends to increase with the dataset size but should +reach a plateau typically when doing queries on datasets with millions of +samples and a few hundreds of dimensions. Higher dimensional datasets tends to +benefit more from LSHForest indexing. + +The break even point (speedup = 1) depends on the dimensionality and structure +of the indexed data and the parameters of the LSHForest index. + +The precision of approximate queries should decrease slowly with the dataset +size. The speed of the decrease depends mostly on the LSHForest parameters and +the dimensionality of the data. + +""" +from __future__ import division +print(__doc__) + +# Authors: Maheshakya Wijewardena +# Olivier Grisel +# +# License: BSD 3 clause + + +############################################################################### +import time +import numpy as np +from sklearn.datasets.samples_generator import make_blobs +from sklearn.neighbors import LSHForest +from sklearn.neighbors import NearestNeighbors +import matplotlib.pyplot as plt + +# Parameters of the study +n_samples_min = int(1e3) +n_samples_max = int(1e5) +n_features = 100 +n_centers = 100 +n_queries = 100 +n_steps = 6 +n_iter = 5 + +# Initialize the range of `n_samples` +n_samples_values = np.logspace(np.log10(n_samples_min), + np.log10(n_samples_max), + n_steps).astype(np.int) + +# Generate some structured data +rng = np.random.RandomState(42) +all_data, _ = make_blobs(n_samples=n_samples_max + n_queries, + n_features=n_features, centers=n_centers, shuffle=True, + random_state=0) +queries = all_data[:n_queries] +index_data = all_data[n_queries:] + +# Metrics to collect for the plots +average_times_exact = [] +average_times_approx = [] +std_times_approx = [] +accuracies = [] +std_accuracies = [] +average_speedups = [] +std_speedups = [] + +# Calculate the average query time +for n_samples in n_samples_values: + X = index_data[:n_samples] + # Initialize LSHForest for queries of a single neighbor + lshf = LSHForest(n_estimators=20, n_candidates=200, + n_neighbors=10).fit(X) + nbrs = NearestNeighbors(algorithm='brute', metric='cosine', + n_neighbors=10).fit(X) + time_approx = [] + time_exact = [] + accuracy = [] + + for i in range(n_iter): + # pick one query at random to study query time variability in LSHForest + query = queries[rng.randint(0, n_queries)] + + t0 = time.time() + exact_neighbors = nbrs.kneighbors(query, return_distance=False) + time_exact.append(time.time() - t0) + + t0 = time.time() + approx_neighbors = lshf.kneighbors(query, return_distance=False) + time_approx.append(time.time() - t0) + + accuracy.append(np.in1d(approx_neighbors, exact_neighbors).mean()) + + average_time_exact = np.mean(time_exact) + average_time_approx = np.mean(time_approx) + speedup = np.array(time_exact) / np.array(time_approx) + average_speedup = np.mean(speedup) + mean_accuracy = np.mean(accuracy) + std_accuracy = np.std(accuracy) + print("Index size: %d, exact: %0.3fs, LSHF: %0.3fs, speedup: %0.1f, " + "accuracy: %0.2f +/-%0.2f" % + (n_samples, average_time_exact, average_time_approx, average_speedup, + mean_accuracy, std_accuracy)) + + accuracies.append(mean_accuracy) + std_accuracies.append(std_accuracy) + average_times_exact.append(average_time_exact) + average_times_approx.append(average_time_approx) + std_times_approx.append(np.std(time_approx)) + average_speedups.append(average_speedup) + std_speedups.append(np.std(speedup)) + +# Plot average query time against n_samples +plt.figure() +plt.errorbar(n_samples_values, average_times_approx, yerr=std_times_approx, + fmt='o-', c='r', label='LSHForest') +plt.plot(n_samples_values, average_times_exact, c='b', + label="NearestNeighbors(algorithm='brute', metric='cosine')") +plt.legend(loc='upper left', fontsize='small') +plt.ylim(0, None) +plt.ylabel("Average query time in seconds") +plt.xlabel("n_samples") +plt.grid(which='both') +plt.title("Impact of index size on response time for first " + "nearest neighbors queries") + +# Plot average query speedup versus index size +plt.figure() +plt.errorbar(n_samples_values, average_speedups, yerr=std_speedups, + fmt='o-', c='r') +plt.ylim(0, None) +plt.ylabel("Average speedup") +plt.xlabel("n_samples") +plt.grid(which='both') +plt.title("Speedup of the approximate NN queries vs brute force") + +# Plot average precision versus index size +plt.figure() +plt.errorbar(n_samples_values, accuracies, std_accuracies, fmt='o-', c='c') +plt.ylim(0, 1.1) +plt.ylabel("precision@10") +plt.xlabel("n_samples") +plt.grid(which='both') +plt.title("precision of 10-nearest-neighbors queries with index size") + +plt.show() diff --git a/examples/neighbors/plot_classification.py b/examples/neighbors/plot_classification.py index 209820159b9ed..9bd7c92f51117 100644 --- a/examples/neighbors/plot_classification.py +++ b/examples/neighbors/plot_classification.py @@ -6,10 +6,10 @@ Sample usage of Nearest Neighbors classification. It will plot the decision boundaries for each class. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn import neighbors, datasets @@ -32,7 +32,7 @@ clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights) clf.fit(X, y) - # Plot the decision boundary. For that, we will asign a color to each + # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 @@ -42,13 +42,14 @@ # Put the result into a color plot Z = Z.reshape(xx.shape) - pl.figure() - pl.pcolormesh(xx, yy, Z, cmap=cmap_light) + plt.figure() + plt.pcolormesh(xx, yy, Z, cmap=cmap_light) # Plot also the training points - pl.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) - pl.title("3-Class classification (k = %i, weights = '%s')" - % (n_neighbors, weights)) - pl.axis('tight') + plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) + plt.xlim(xx.min(), xx.max()) + plt.ylim(yy.min(), yy.max()) + plt.title("3-Class classification (k = %i, weights = '%s')" + % (n_neighbors, weights)) -pl.show() +plt.show() diff --git a/examples/neighbors/plot_digits_kde_sampling.py b/examples/neighbors/plot_digits_kde_sampling.py new file mode 100644 index 0000000000000..4680a41780aed --- /dev/null +++ b/examples/neighbors/plot_digits_kde_sampling.py @@ -0,0 +1,62 @@ +""" +========================= +Kernel Density Estimation +========================= + +This example shows how kernel density estimation (KDE), a powerful +non-parametric density estimation technique, can be used to learn +a generative model for a dataset. With this generative model in place, +new samples can be drawn. These new samples reflect the underlying model +of the data. +""" + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.datasets import load_digits +from sklearn.neighbors import KernelDensity +from sklearn.decomposition import PCA +from sklearn.grid_search import GridSearchCV + +# load the data +digits = load_digits() +data = digits.data + +# project the 64-dimensional data to a lower dimension +pca = PCA(n_components=15, whiten=False) +data = pca.fit_transform(digits.data) + +# use grid search cross-validation to optimize the bandwidth +params = {'bandwidth': np.logspace(-1, 1, 20)} +grid = GridSearchCV(KernelDensity(), params) +grid.fit(data) + +print("best bandwidth: {0}".format(grid.best_estimator_.bandwidth)) + +# use the best estimator to compute the kernel density estimate +kde = grid.best_estimator_ + +# sample 44 new points from the data +new_data = kde.sample(44, random_state=0) +new_data = pca.inverse_transform(new_data) + +# turn data into a 4x11 grid +new_data = new_data.reshape((4, 11, -1)) +real_data = digits.data[:44].reshape((4, 11, -1)) + +# plot real digits and resampled digits +fig, ax = plt.subplots(9, 11, subplot_kw=dict(xticks=[], yticks=[])) +for j in range(11): + ax[4, j].set_visible(False) + for i in range(4): + im = ax[i, j].imshow(real_data[i, j].reshape((8, 8)), + cmap=plt.cm.binary, interpolation='nearest') + im.set_clim(0, 16) + im = ax[i + 5, j].imshow(new_data[i, j].reshape((8, 8)), + cmap=plt.cm.binary, interpolation='nearest') + im.set_clim(0, 16) + +ax[0, 5].set_title('Selection from the input data') +ax[5, 5].set_title('"New" digits drawn from the kernel density model') + +plt.show() diff --git a/examples/neighbors/plot_kde_1d.py b/examples/neighbors/plot_kde_1d.py new file mode 100644 index 0000000000000..d52c924c7ceb6 --- /dev/null +++ b/examples/neighbors/plot_kde_1d.py @@ -0,0 +1,144 @@ +""" +=================================== +Simple 1D Kernel Density Estimation +=================================== +This example uses the :class:`sklearn.neighbors.KernelDensity` class to +demonstrate the principles of Kernel Density Estimation in one dimension. + +The first plot shows one of the problems with using histograms to visualize +the density of points in 1D. Intuitively, a histogram can be thought of as a +scheme in which a unit "block" is stacked above each point on a regular grid. +As the top two panels show, however, the choice of gridding for these blocks +can lead to wildly divergent ideas about the underlying shape of the density +distribution. If we instead center each block on the point it represents, we +get the estimate shown in the bottom left panel. This is a kernel density +estimation with a "top hat" kernel. This idea can be generalized to other +kernel shapes: the bottom-right panel of the first figure shows a Gaussian +kernel density estimate over the same distribution. + +Scikit-learn implements efficient kernel density estimation using either +a Ball Tree or KD Tree structure, through the +:class:`sklearn.neighbors.KernelDensity` estimator. The available kernels +are shown in the second figure of this example. + +The third figure compares kernel density estimates for a distribution of 100 +samples in 1 dimension. Though this example uses 1D distributions, kernel +density estimation is easily and efficiently extensible to higher dimensions +as well. +""" +# Author: Jake Vanderplas +# +import numpy as np +import matplotlib.pyplot as plt +from scipy.stats import norm +from sklearn.neighbors import KernelDensity + + +#---------------------------------------------------------------------- +# Plot the progression of histograms to kernels +np.random.seed(1) +N = 20 +X = np.concatenate((np.random.normal(0, 1, 0.3 * N), + np.random.normal(5, 1, 0.7 * N)))[:, np.newaxis] +X_plot = np.linspace(-5, 10, 1000)[:, np.newaxis] +bins = np.linspace(-5, 10, 10) + +fig, ax = plt.subplots(2, 2, sharex=True, sharey=True) +fig.subplots_adjust(hspace=0.05, wspace=0.05) + +# histogram 1 +ax[0, 0].hist(X[:, 0], bins=bins, fc='#AAAAFF', normed=True) +ax[0, 0].text(-3.5, 0.31, "Histogram") + +# histogram 2 +ax[0, 1].hist(X[:, 0], bins=bins + 0.75, fc='#AAAAFF', normed=True) +ax[0, 1].text(-3.5, 0.31, "Histogram, bins shifted") + +# tophat KDE +kde = KernelDensity(kernel='tophat', bandwidth=0.75).fit(X) +log_dens = kde.score_samples(X_plot) +ax[1, 0].fill(X_plot[:, 0], np.exp(log_dens), fc='#AAAAFF') +ax[1, 0].text(-3.5, 0.31, "Tophat Kernel Density") + +# Gaussian KDE +kde = KernelDensity(kernel='gaussian', bandwidth=0.75).fit(X) +log_dens = kde.score_samples(X_plot) +ax[1, 1].fill(X_plot[:, 0], np.exp(log_dens), fc='#AAAAFF') +ax[1, 1].text(-3.5, 0.31, "Gaussian Kernel Density") + +for axi in ax.ravel(): + axi.plot(X[:, 0], np.zeros(X.shape[0]) - 0.01, '+k') + axi.set_xlim(-4, 9) + axi.set_ylim(-0.02, 0.34) + +for axi in ax[:, 0]: + axi.set_ylabel('Normalized Density') + +for axi in ax[1, :]: + axi.set_xlabel('x') + +#---------------------------------------------------------------------- +# Plot all available kernels +X_plot = np.linspace(-6, 6, 1000)[:, None] +X_src = np.zeros((1, 1)) + +fig, ax = plt.subplots(2, 3, sharex=True, sharey=True) +fig.subplots_adjust(left=0.05, right=0.95, hspace=0.05, wspace=0.05) + + +def format_func(x, loc): + if x == 0: + return '0' + elif x == 1: + return 'h' + elif x == -1: + return '-h' + else: + return '%ih' % x + +for i, kernel in enumerate(['gaussian', 'tophat', 'epanechnikov', + 'exponential', 'linear', 'cosine']): + axi = ax.ravel()[i] + log_dens = KernelDensity(kernel=kernel).fit(X_src).score_samples(X_plot) + axi.fill(X_plot[:, 0], np.exp(log_dens), '-k', fc='#AAAAFF') + axi.text(-2.6, 0.95, kernel) + + axi.xaxis.set_major_formatter(plt.FuncFormatter(format_func)) + axi.xaxis.set_major_locator(plt.MultipleLocator(1)) + axi.yaxis.set_major_locator(plt.NullLocator()) + + axi.set_ylim(0, 1.05) + axi.set_xlim(-2.9, 2.9) + +ax[0, 1].set_title('Available Kernels') + +#---------------------------------------------------------------------- +# Plot a 1D density example +N = 100 +np.random.seed(1) +X = np.concatenate((np.random.normal(0, 1, 0.3 * N), + np.random.normal(5, 1, 0.7 * N)))[:, np.newaxis] + +X_plot = np.linspace(-5, 10, 1000)[:, np.newaxis] + +true_dens = (0.3 * norm(0, 1).pdf(X_plot[:, 0]) + + 0.7 * norm(5, 1).pdf(X_plot[:, 0])) + +fig, ax = plt.subplots() +ax.fill(X_plot[:, 0], true_dens, fc='black', alpha=0.2, + label='input distribution') + +for kernel in ['gaussian', 'tophat', 'epanechnikov']: + kde = KernelDensity(kernel=kernel, bandwidth=0.5).fit(X) + log_dens = kde.score_samples(X_plot) + ax.plot(X_plot[:, 0], np.exp(log_dens), '-', + label="kernel = '{0}'".format(kernel)) + +ax.text(6, 0.38, "N={0} points".format(N)) + +ax.legend(loc='upper left') +ax.plot(X[:, 0], -0.005 - 0.01 * np.random.random(X.shape[0]), '+k') + +ax.set_xlim(-4, 9) +ax.set_ylim(-0.02, 0.4) +plt.show() diff --git a/examples/neighbors/plot_nearest_centroid.py b/examples/neighbors/plot_nearest_centroid.py index 1e7a2be935ceb..05d277db08f02 100644 --- a/examples/neighbors/plot_nearest_centroid.py +++ b/examples/neighbors/plot_nearest_centroid.py @@ -6,10 +6,10 @@ Sample usage of Nearest Centroid classification. It will plot the decision boundaries for each class. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn import datasets from sklearn.neighbors import NearestCentroid @@ -33,8 +33,8 @@ clf = NearestCentroid(shrink_threshold=shrinkage) clf.fit(X, y) y_pred = clf.predict(X) - print shrinkage, np.mean(y == y_pred) - # Plot the decision boundary. For that, we will asign a color to each + print(shrinkage, np.mean(y == y_pred)) + # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 @@ -44,13 +44,13 @@ # Put the result into a color plot Z = Z.reshape(xx.shape) - pl.figure() - pl.pcolormesh(xx, yy, Z, cmap=cmap_light) + plt.figure() + plt.pcolormesh(xx, yy, Z, cmap=cmap_light) # Plot also the training points - pl.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) - pl.title("3-Class classification (shrink_threshold=%r)" - % shrinkage) - pl.axis('tight') + plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) + plt.title("3-Class classification (shrink_threshold=%r)" + % shrinkage) + plt.axis('tight') -pl.show() +plt.show() diff --git a/examples/neighbors/plot_regression.py b/examples/neighbors/plot_regression.py index 0989be626024a..c664d7f173b0e 100644 --- a/examples/neighbors/plot_regression.py +++ b/examples/neighbors/plot_regression.py @@ -8,18 +8,18 @@ target using both barycenter and constant weights. """ -print __doc__ +print(__doc__) # Author: Alexandre Gramfort # Fabian Pedregosa # -# License: BSD, (C) INRIA +# License: BSD 3 clause (C) INRIA ############################################################################### # Generate sample data import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import neighbors np.random.seed(0) @@ -38,12 +38,12 @@ knn = neighbors.KNeighborsRegressor(n_neighbors, weights=weights) y_ = knn.fit(X, y).predict(T) - pl.subplot(2, 1, i + 1) - pl.scatter(X, y, c='k', label='data') - pl.plot(T, y_, c='g', label='prediction') - pl.axis('tight') - pl.legend() - pl.title("KNeighborsRegressor (k = %i, weights = '%s')" % (n_neighbors, - weights)) + plt.subplot(2, 1, i + 1) + plt.scatter(X, y, c='k', label='data') + plt.plot(T, y_, c='g', label='prediction') + plt.axis('tight') + plt.legend() + plt.title("KNeighborsRegressor (k = %i, weights = '%s')" % (n_neighbors, + weights)) -pl.show() +plt.show() diff --git a/examples/neighbors/plot_species_kde.py b/examples/neighbors/plot_species_kde.py new file mode 100644 index 0000000000000..95f4417ce1bca --- /dev/null +++ b/examples/neighbors/plot_species_kde.py @@ -0,0 +1,115 @@ +""" +================================================ +Kernel Density Estimate of Species Distributions +================================================ +This shows an example of a neighbors-based query (in particular a kernel +density estimate) on geospatial data, using a Ball Tree built upon the +Haversine distance metric -- i.e. distances over points in latitude/longitude. +The dataset is provided by Phillips et. al. (2006). +If available, the example uses +`basemap `_ +to plot the coast lines and national boundaries of South America. + +This example does not perform any learning over the data +(see :ref:`example_applications_plot_species_distribution_modeling.py` for +an example of classification based on the attributes in this dataset). It +simply shows the kernel density estimate of observed data points in +geospatial coordinates. + +The two species are: + + - `"Bradypus variegatus" + `_ , + the Brown-throated Sloth. + + - `"Microryzomys minutus" + `_ , + also known as the Forest Small Rice Rat, a rodent that lives in Peru, + Colombia, Ecuador, Peru, and Venezuela. + +References +---------- + + * `"Maximum entropy modeling of species geographic distributions" + `_ + S. J. Phillips, R. P. Anderson, R. E. Schapire - Ecological Modelling, + 190:231-259, 2006. +""" +# Author: Jake Vanderplas +# +# License: BSD 3 clause + +import numpy as np +import matplotlib.pyplot as plt +from sklearn.datasets import fetch_species_distributions +from sklearn.datasets.species_distributions import construct_grids +from sklearn.neighbors import KernelDensity + +# if basemap is available, we'll use it. +# otherwise, we'll improvise later... +try: + from mpl_toolkits.basemap import Basemap + basemap = True +except ImportError: + basemap = False + +# Get matrices/arrays of species IDs and locations +data = fetch_species_distributions() +species_names = ['Bradypus Variegatus', 'Microryzomys Minutus'] + +Xtrain = np.vstack([data['train']['dd lat'], + data['train']['dd long']]).T +ytrain = np.array([d.decode('ascii').startswith('micro') + for d in data['train']['species']], dtype='int') +Xtrain *= np.pi / 180. # Convert lat/long to radians + +# Set up the data grid for the contour plot +xgrid, ygrid = construct_grids(data) +X, Y = np.meshgrid(xgrid[::5], ygrid[::5][::-1]) +land_reference = data.coverages[6][::5, ::5] +land_mask = (land_reference > -9999).ravel() + +xy = np.vstack([Y.ravel(), X.ravel()]).T +xy = xy[land_mask] +xy *= np.pi / 180. + +# Plot map of South America with distributions of each species +fig = plt.figure() +fig.subplots_adjust(left=0.05, right=0.95, wspace=0.05) + +for i in range(2): + plt.subplot(1, 2, i + 1) + + # construct a kernel density estimate of the distribution + print(" - computing KDE in spherical coordinates") + kde = KernelDensity(bandwidth=0.04, metric='haversine', + kernel='gaussian', algorithm='ball_tree') + kde.fit(Xtrain[ytrain == i]) + + # evaluate only on the land: -9999 indicates ocean + Z = -9999 + np.zeros(land_mask.shape[0]) + Z[land_mask] = np.exp(kde.score_samples(xy)) + Z = Z.reshape(X.shape) + + # plot contours of the density + levels = np.linspace(0, Z.max(), 25) + plt.contourf(X, Y, Z, levels=levels, cmap=plt.cm.Reds) + + if basemap: + print(" - plot coastlines using basemap") + m = Basemap(projection='cyl', llcrnrlat=Y.min(), + urcrnrlat=Y.max(), llcrnrlon=X.min(), + urcrnrlon=X.max(), resolution='c') + m.drawcoastlines() + m.drawcountries() + else: + print(" - plot coastlines from coverage") + plt.contour(X, Y, land_reference, + levels=[-9999], colors="k", + linestyles="solid") + plt.xticks([]) + plt.yticks([]) + + plt.title(species_names[i]) + +plt.show() diff --git a/examples/neural_networks/README.txt b/examples/neural_networks/README.txt new file mode 100644 index 0000000000000..8b6ae8aecd735 --- /dev/null +++ b/examples/neural_networks/README.txt @@ -0,0 +1,6 @@ +.. _neural_network_examples: + +Neural Networks +----------------------- + +Examples concerning the :mod:`sklearn.neural_network` module. diff --git a/examples/neural_networks/plot_rbm_logistic_classification.py b/examples/neural_networks/plot_rbm_logistic_classification.py new file mode 100644 index 0000000000000..9f085036d2013 --- /dev/null +++ b/examples/neural_networks/plot_rbm_logistic_classification.py @@ -0,0 +1,141 @@ +""" +============================================================== +Restricted Boltzmann Machine features for digit classification +============================================================== + +For greyscale image data where pixel values can be interpreted as degrees of +blackness on a white background, like handwritten digit recognition, the +Bernoulli Restricted Boltzmann machine model (:class:`BernoulliRBM +`) can perform effective non-linear +feature extraction. + +In order to learn good latent representations from a small dataset, we +artificially generate more labeled data by perturbing the training data with +linear shifts of 1 pixel in each direction. + +This example shows how to build a classification pipeline with a BernoulliRBM +feature extractor and a :class:`LogisticRegression +` classifier. The hyperparameters +of the entire model (learning rate, hidden layer size, regularization) +were optimized by grid search, but the search is not reproduced here because +of runtime constraints. + +Logistic regression on raw pixel values is presented for comparison. The +example shows that the features extracted by the BernoulliRBM help improve the +classification accuracy. +""" + +from __future__ import print_function + +print(__doc__) + +# Authors: Yann N. Dauphin, Vlad Niculae, Gabriel Synnaeve +# License: BSD + +import numpy as np +import matplotlib.pyplot as plt + +from scipy.ndimage import convolve +from sklearn import linear_model, datasets, metrics +from sklearn.cross_validation import train_test_split +from sklearn.neural_network import BernoulliRBM +from sklearn.pipeline import Pipeline + + +############################################################################### +# Setting up + +def nudge_dataset(X, Y): + """ + This produces a dataset 5 times bigger than the original one, + by moving the 8x8 images in X around by 1px to left, right, down, up + """ + direction_vectors = [ + [[0, 1, 0], + [0, 0, 0], + [0, 0, 0]], + + [[0, 0, 0], + [1, 0, 0], + [0, 0, 0]], + + [[0, 0, 0], + [0, 0, 1], + [0, 0, 0]], + + [[0, 0, 0], + [0, 0, 0], + [0, 1, 0]]] + + shift = lambda x, w: convolve(x.reshape((8, 8)), mode='constant', + weights=w).ravel() + X = np.concatenate([X] + + [np.apply_along_axis(shift, 1, X, vector) + for vector in direction_vectors]) + Y = np.concatenate([Y for _ in range(5)], axis=0) + return X, Y + +# Load Data +digits = datasets.load_digits() +X = np.asarray(digits.data, 'float32') +X, Y = nudge_dataset(X, digits.target) +X = (X - np.min(X, 0)) / (np.max(X, 0) + 0.0001) # 0-1 scaling + +X_train, X_test, Y_train, Y_test = train_test_split(X, Y, + test_size=0.2, + random_state=0) + +# Models we will use +logistic = linear_model.LogisticRegression() +rbm = BernoulliRBM(random_state=0, verbose=True) + +classifier = Pipeline(steps=[('rbm', rbm), ('logistic', logistic)]) + +############################################################################### +# Training + +# Hyper-parameters. These were set by cross-validation, +# using a GridSearchCV. Here we are not performing cross-validation to +# save time. +rbm.learning_rate = 0.06 +rbm.n_iter = 20 +# More components tend to give better prediction performance, but larger +# fitting time +rbm.n_components = 100 +logistic.C = 6000.0 + +# Training RBM-Logistic Pipeline +classifier.fit(X_train, Y_train) + +# Training Logistic regression +logistic_classifier = linear_model.LogisticRegression(C=100.0) +logistic_classifier.fit(X_train, Y_train) + +############################################################################### +# Evaluation + +print() +print("Logistic regression using RBM features:\n%s\n" % ( + metrics.classification_report( + Y_test, + classifier.predict(X_test)))) + +print("Logistic regression using raw pixel features:\n%s\n" % ( + metrics.classification_report( + Y_test, + logistic_classifier.predict(X_test)))) + +############################################################################### +# Plotting + +plt.figure(figsize=(4.2, 4)) +for i, comp in enumerate(rbm.components_): + plt.subplot(10, 10, i + 1) + plt.imshow(comp.reshape((8, 8)), cmap=plt.cm.gray_r, + interpolation='nearest') + plt.xticks(()) + plt.yticks(()) +plt.suptitle('100 components extracted by RBM', fontsize=16) +plt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23) + +plt.show() diff --git a/examples/plot_classification_probability.py b/examples/plot_classification_probability.py deleted file mode 100644 index f66a7d3be81f7..0000000000000 --- a/examples/plot_classification_probability.py +++ /dev/null @@ -1,77 +0,0 @@ -""" -=============================== -Plot classification probability -=============================== - -Plot the classification probability for different classifiers. We use a 3 -class dataset, and we classify it with a Support Vector classifier, as -well as L1 and L2 penalized logistic regression. - -The logistic regression is not a multiclass classifier out of the box. As -a result it can identify only the first class. -""" -print __doc__ - -# Author: Alexandre Gramfort -# License: BSD Style. - -import pylab as pl -import numpy as np - -from sklearn.linear_model import LogisticRegression -from sklearn.svm import SVC -from sklearn import datasets - -iris = datasets.load_iris() -X = iris.data[:, 0:2] # we only take the first two features for visualization -y = iris.target - -n_features = X.shape[1] - -C = 1.0 - -# Create different classifiers. The logistic regression cannot do -# multiclass out of the box. -classifiers = { - 'L1 logistic': LogisticRegression(C=C, penalty='l1'), - 'L2 logistic': LogisticRegression(C=C, penalty='l2'), - 'Linear SVC': SVC(kernel='linear', C=C, probability=True), - } - -n_classifiers = len(classifiers) - -pl.figure(figsize=(3 * 2, n_classifiers * 2)) -pl.subplots_adjust(bottom=.2, top=.95) - -for index, (name, classifier) in enumerate(classifiers.iteritems()): - classifier.fit(X, y) - - y_pred = classifier.predict(X) - classif_rate = np.mean(y_pred.ravel() == y.ravel()) * 100 - print "classif_rate for %s : %f " % (name, classif_rate) - - # View probabilities= - xx = np.linspace(3, 9, 100) - yy = np.linspace(1, 5, 100).T - xx, yy = np.meshgrid(xx, yy) - Xfull = np.c_[xx.ravel(), yy.ravel()] - probas = classifier.predict_proba(Xfull) - n_classes = np.unique(y_pred).size - for k in range(n_classes): - pl.subplot(n_classifiers, n_classes, index * n_classes + k + 1) - pl.title("Class %d" % k) - if k == 0: - pl.ylabel(name) - imshow_handle = pl.imshow(probas[:, k].reshape((100, 100)), - extent=(3, 9, 1, 5), origin='lower') - pl.xticks(()) - pl.yticks(()) - idx = (y_pred == k) - if idx.any(): - pl.scatter(X[idx, 0], X[idx, 1], marker='o', c='k') - -ax = pl.axes([0.15, 0.04, 0.7, 0.05]) -pl.title("Probability") -pl.colorbar(imshow_handle, cax=ax, orientation='horizontal') - -pl.show() diff --git a/examples/plot_confusion_matrix.py b/examples/plot_confusion_matrix.py deleted file mode 100644 index e7ea0dc63b5ef..0000000000000 --- a/examples/plot_confusion_matrix.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -================ -Confusion matrix -================ - -Example of confusion matrix usage to evaluate the quality -of the output of a classifier. -""" -print __doc__ - -import random -import pylab as pl -from sklearn import svm, datasets -from sklearn.metrics import confusion_matrix - -# import some data to play with -iris = datasets.load_iris() -X = iris.data -y = iris.target -n_samples, n_features = X.shape -p = range(n_samples) -random.seed(0) -random.shuffle(p) -X, y = X[p], y[p] -half = int(n_samples / 2) - -# Run classifier -classifier = svm.SVC(kernel='linear') -y_ = classifier.fit(X[:half], y[:half]).predict(X[half:]) - -# Compute confusion matrix -cm = confusion_matrix(y[half:], y_) - -print cm - -# Show confusion matrix -pl.matshow(cm) -pl.title('Confusion matrix') -pl.colorbar() -pl.show() diff --git a/examples/plot_cv_predict.py b/examples/plot_cv_predict.py new file mode 100644 index 0000000000000..404099d861764 --- /dev/null +++ b/examples/plot_cv_predict.py @@ -0,0 +1,28 @@ +""" +==================================== +Plotting Cross-Validated Predictions +==================================== + +This example shows how to use `cross_val_predict` to visualize prediction +errors. + +""" +from sklearn import datasets +from sklearn.cross_validation import cross_val_predict +from sklearn import linear_model +import matplotlib.pyplot as plt + +lr = linear_model.LinearRegression() +boston = datasets.load_boston() +y = boston.target + +# cross_val_predict returns an array of the same size as `y` where each entry +# is a prediction obtained by cross validated: +predicted = cross_val_predict(lr, boston.data, y, cv=10) + +fig,ax = plt.subplots() +ax.scatter(y, predicted) +ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=4) +ax.set_xlabel('Measured') +ax.set_ylabel('Predicted') +fig.show() diff --git a/examples/plot_digits_classification.py b/examples/plot_digits_classification.py deleted file mode 100644 index 25081768700c2..0000000000000 --- a/examples/plot_digits_classification.py +++ /dev/null @@ -1,64 +0,0 @@ -""" -================================ -Recognizing hand-written digits -================================ - -An example showing how the scikit-learn can be used to recognize images of -hand-written digits. - -This example is commented in the -:ref:`tutorial section of the user manual `. - -""" -print __doc__ - -# Author: Gael Varoquaux -# License: Simplified BSD - -# Standard scientific Python imports -import pylab as pl - -# Import datasets, classifiers and performance metrics -from sklearn import datasets, svm, metrics - -# The digits dataset -digits = datasets.load_digits() - -# The data that we are interested in is made of 8x8 images of digits, -# let's have a look at the first 3 images, stored in the `images` -# attribute of the dataset. If we were working from image files, we -# could load them using pylab.imread. For these images know which -# digit they represent: it is given in the 'target' of the dataset. -for index, (image, label) in enumerate(zip(digits.images, digits.target)[:4]): - pl.subplot(2, 4, index + 1) - pl.axis('off') - pl.imshow(image, cmap=pl.cm.gray_r, interpolation='nearest') - pl.title('Training: %i' % label) - -# To apply an classifier on this data, we need to flatten the image, to -# turn the data in a (samples, feature) matrix: -n_samples = len(digits.images) -data = digits.images.reshape((n_samples, -1)) - -# Create a classifier: a support vector classifier -classifier = svm.SVC(gamma=0.001) - -# We learn the digits on the first half of the digits -classifier.fit(data[:n_samples / 2], digits.target[:n_samples / 2]) - -# Now predict the value of the digit on the second half: -expected = digits.target[n_samples / 2:] -predicted = classifier.predict(data[n_samples / 2:]) - -print "Classification report for classifier %s:\n%s\n" % ( - classifier, metrics.classification_report(expected, predicted)) -print "Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted) - -for index, (image, prediction) in enumerate( - zip(digits.images[n_samples / 2:], predicted)[:4]): - pl.subplot(2, 4, index + 5) - pl.axis('off') - pl.imshow(image, cmap=pl.cm.gray_r, interpolation='nearest') - pl.title('Prediction: %i' % prediction) - -pl.show() diff --git a/examples/plot_digits_pipe.py b/examples/plot_digits_pipe.py index 8c9f061720122..139ade15ba7c2 100644 --- a/examples/plot_digits_pipe.py +++ b/examples/plot_digits_pipe.py @@ -12,23 +12,24 @@ We use a GridSearchCV to set the dimensionality of the PCA """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD +# Code source: Gaël Varoquaux +# Modified for documentation by Jaques Grobler +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import linear_model, decomposition, datasets +from sklearn.pipeline import Pipeline +from sklearn.grid_search import GridSearchCV logistic = linear_model.LogisticRegression() pca = decomposition.PCA() -from sklearn.pipeline import Pipeline pipe = Pipeline(steps=[('pca', pca), ('logistic', logistic)]) digits = datasets.load_digits() @@ -39,19 +40,17 @@ # Plot the PCA spectrum pca.fit(X_digits) -pl.figure(1, figsize=(4, 3)) -pl.clf() -pl.axes([.2, .2, .7, .7]) -pl.plot(pca.explained_variance_, linewidth=2) -pl.axis('tight') -pl.xlabel('n_components') -pl.ylabel('explained_variance_') +plt.figure(1, figsize=(4, 3)) +plt.clf() +plt.axes([.2, .2, .7, .7]) +plt.plot(pca.explained_variance_, linewidth=2) +plt.axis('tight') +plt.xlabel('n_components') +plt.ylabel('explained_variance_') ############################################################################### # Prediction -from sklearn.grid_search import GridSearchCV - n_components = [20, 40, 64] Cs = np.logspace(-4, 4, 3) @@ -62,7 +61,7 @@ logistic__C=Cs)) estimator.fit(X_digits, y_digits) -pl.axvline(estimator.best_estimator_.named_steps['pca'].n_components, - linestyle=':', label='n_components chosen') -pl.legend(prop=dict(size=12)) -pl.show() +plt.axvline(estimator.best_estimator_.named_steps['pca'].n_components, + linestyle=':', label='n_components chosen') +plt.legend(prop=dict(size=12)) +plt.show() diff --git a/examples/plot_hmm_sampling.py b/examples/plot_hmm_sampling.py deleted file mode 100644 index afb26f4adda16..0000000000000 --- a/examples/plot_hmm_sampling.py +++ /dev/null @@ -1,61 +0,0 @@ -""" -================================== -Demonstration of sampling from HMM -================================== - -This script shows how to sample points from a Hiden Markov Model (HMM): -we use a 4-components with specified mean and covariance. - -The plot show the sequence of observations generated with the transitions -between them. We can see that, as specified by our transition matrix, -there are no transition between component 1 and 3. -""" - -import numpy as np -import matplotlib.pyplot as plt - -from sklearn import hmm - -############################################################## -# Prepare parameters for a 3-components HMM -# Initial population probability -start_prob = np.array([0.6, 0.3, 0.1, 0.0]) -# The transition matrix, note that there are no transitions possible -# between component 1 and 4 -trans_mat = np.array([[0.7, 0.2, 0.0, 0.1], - [0.3, 0.5, 0.2, 0.0], - [0.0, 0.3, 0.5, 0.2], - [0.2, 0.0, 0.2, 0.6]]) -# The means of each component -means = np.array([[0.0, 0.0], - [0.0, 11.0], - [9.0, 10.0], - [11.0, -1.0], - ]) -# The covariance of each component -covars = .5 * np.tile(np.identity(2), (4, 1, 1)) - -# Build an HMM instance and set parameters -model = hmm.GaussianHMM(4, "full", start_prob, trans_mat, - random_state=42) - -# Instead of fitting it from the data, we directly set the estimated -# parameters, the means and covariance of the components -model.means_ = means -model.covars_ = covars -############################################################### - -# Generate samples -X, Z = model.sample(500) - -# Plot the sampled data -plt.plot(X[:, 0], X[:, 1], "-o", label="observations", ms=6, - mfc="orange", alpha=0.7) - -# Indicate the component numbers -for i, m in enumerate(means): - plt.text(m[0], m[1], 'Component %i' % (i + 1), - size=17, horizontalalignment='center', - bbox=dict(alpha=.7, facecolor='w')) -plt.legend(loc='best') -plt.show() diff --git a/examples/plot_hmm_stock_analysis.py b/examples/plot_hmm_stock_analysis.py deleted file mode 100644 index 128e8c574f09a..0000000000000 --- a/examples/plot_hmm_stock_analysis.py +++ /dev/null @@ -1,96 +0,0 @@ -""" -========================== -Gaussian HMM of stock data -========================== - -This script shows how to use Gaussian HMM. -It uses stock price data, which can be obtained from yahoo finance. -For more information on how to get stock prices with matplotlib, please refer -to date_demo1.py of matplotlib. -""" -print __doc__ - -import datetime -import numpy as np -import pylab as pl -from matplotlib.finance import quotes_historical_yahoo -from matplotlib.dates import YearLocator, MonthLocator, DateFormatter -from sklearn.hmm import GaussianHMM - -############################################################################### -# Downloading the data -date1 = datetime.date(1995, 1, 1) # start date -date2 = datetime.date(2012, 1, 6) # end date -# get quotes from yahoo finance -quotes = quotes_historical_yahoo("INTC", date1, date2) -if len(quotes) == 0: - raise SystemExit - -# unpack quotes -dates = np.array([q[0] for q in quotes], dtype=int) -close_v = np.array([q[2] for q in quotes]) -volume = np.array([q[5] for q in quotes])[1:] - -# take diff of close value -# this makes len(diff) = len(close_t) - 1 -# therefore, others quantity also need to be shifted -diff = close_v[1:] - close_v[:-1] -dates = dates[1:] -close_v = close_v[1:] - -# pack diff and volume for training -X = np.column_stack([diff, volume]) - -############################################################################### -# Run Gaussian HMM -print "fitting to HMM and decoding ...", -n_components = 5 - -# make an HMM instance and execute fit -model = GaussianHMM(n_components, covariance_type="diag", n_iter=1000) - -model.fit([X]) - -# predict the optimal sequence of internal hidden state -hidden_states = model.predict(X) - -print "done\n" - -############################################################################### -# print trained parameters and plot -print "Transition matrix" -print model.transmat_ -print "" - -print "means and vars of each hidden state" -for i in xrange(n_components): - print "%dth hidden state" % i - print "mean = ", model.means_[i] - print "var = ", np.diag(model.covars_[i]) - print "" - -years = YearLocator() # every year -months = MonthLocator() # every month -yearsFmt = DateFormatter('%Y') -fig = pl.figure() -ax = fig.add_subplot(111) - -for i in xrange(n_components): - # use fancy indexing to plot data in each state - idx = (hidden_states == i) - ax.plot_date(dates[idx], close_v[idx], 'o', label="%dth hidden state" % i) -ax.legend() - -# format the ticks -ax.xaxis.set_major_locator(years) -ax.xaxis.set_major_formatter(yearsFmt) -ax.xaxis.set_minor_locator(months) -ax.autoscale_view() - -# format the coords message box -ax.fmt_xdata = DateFormatter('%Y-%m-%d') -ax.fmt_ydata = lambda x: '$%1.2f' % x -ax.grid(True) - -fig.autofmt_xdate() -pl.show() diff --git a/examples/plot_iris_classifiers.py b/examples/plot_iris_classifiers.py deleted file mode 100644 index 977ddfb3254ba..0000000000000 --- a/examples/plot_iris_classifiers.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -""" -========================================================= -Classifiers Comparison -========================================================= -A Comparison of a K-nearest-neighbours, Logistic Regression and a Linear SVC -classifying the `iris `_ -dataset. - -""" -print __doc__ - - -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD - -import numpy as np -import pylab as pl -from sklearn import neighbors, datasets, linear_model, svm - -# import some data to play with -iris = datasets.load_iris() -X = iris.data[:, :2] # we only take the first two features. -Y = iris.target - -h = .02 # step size in the mesh - -classifiers = dict( - knn=neighbors.KNeighborsClassifier(), - logistic=linear_model.LogisticRegression(C=1e5), - svm=svm.LinearSVC(C=1e5, loss='l1'), - ) - - -fignum = 1 -# we create an instance of Neighbours Classifier and fit the data. -for name, clf in classifiers.iteritems(): - clf.fit(X, Y) - - # Plot the decision boundary. For that, we will asign a color to each - # point in the mesh [x_min, m_max]x[y_min, y_max]. - x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 - y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 - xx, yy = np.meshgrid(np.arange(x_min, x_max, h), - np.arange(y_min, y_max, h)) - Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) - - # Put the result into a color plot - Z = Z.reshape(xx.shape) - pl.figure(fignum, figsize=(4, 3)) - pl.pcolormesh(xx, yy, Z, cmap=pl.cm.Paired) - - # Plot also the training points - pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired) - pl.xlabel('Sepal length') - pl.ylabel('Sepal width') - - pl.xlim(xx.min(), xx.max()) - pl.ylim(yy.min(), yy.max()) - pl.xticks(()) - pl.yticks(()) - fignum += 1 - -pl.show() diff --git a/examples/linear_model/plot_isotonic_regression.py b/examples/plot_isotonic_regression.py similarity index 75% rename from examples/linear_model/plot_isotonic_regression.py rename to examples/plot_isotonic_regression.py index 6bd5138b168e0..45a369e5b6e3e 100644 --- a/examples/linear_model/plot_isotonic_regression.py +++ b/examples/plot_isotonic_regression.py @@ -11,16 +11,18 @@ presented. """ +print(__doc__) # Author: Nelle Varoquaux # Alexandre Gramfort # Licence: BSD import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from matplotlib.collections import LineCollection -from sklearn.linear_model import IsotonicRegression, LinearRegression +from sklearn.linear_model import LinearRegression +from sklearn.isotonic import IsotonicRegression from sklearn.utils import check_random_state n = 100 @@ -32,6 +34,7 @@ # Fit IsotonicRegression and LinearRegression models ir = IsotonicRegression() + y_ = ir.fit_transform(x, y) lr = LinearRegression() @@ -45,11 +48,11 @@ lc.set_array(np.ones(len(y))) lc.set_linewidths(0.5 * np.ones(n)) -fig = pl.figure() -pl.plot(x, y, 'r.', markersize=12) -pl.plot(x, y_, 'g.-', markersize=12) -pl.plot(x, lr.predict(x[:, np.newaxis]), 'b-') -pl.gca().add_collection(lc) -pl.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right') -pl.title('Isotonic regression') -pl.show() +fig = plt.figure() +plt.plot(x, y, 'r.', markersize=12) +plt.plot(x, y_, 'g.-', markersize=12) +plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-') +plt.gca().add_collection(lc) +plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right') +plt.title('Isotonic regression') +plt.show() diff --git a/examples/plot_johnson_lindenstrauss_bound.py b/examples/plot_johnson_lindenstrauss_bound.py new file mode 100644 index 0000000000000..870c119b2b9a1 --- /dev/null +++ b/examples/plot_johnson_lindenstrauss_bound.py @@ -0,0 +1,197 @@ +""" +===================================================================== +The Johnson-Lindenstrauss bound for embedding with random projections +===================================================================== + + +The `Johnson-Lindenstrauss lemma`_ states that any high dimensional +dataset can be randomly projected into a lower dimensional Euclidean +space while controlling the distortion in the pairwise distances. + +.. _`Johnson-Lindenstrauss lemma`: http://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma + + +Theoretical bounds +================== + +The distortion introduced by a random projection `p` is asserted by +the fact that `p` is defining an eps-embedding with good probability +as defined by: + + (1 - eps) ||u - v||^2 < ||p(u) - p(v)||^2 < (1 + eps) ||u - v||^2 + +Where u and v are any rows taken from a dataset of shape [n_samples, +n_features] and p is a projection by a random Gaussian N(0, 1) matrix +with shape [n_components, n_features] (or a sparse Achlioptas matrix). + +The minimum number of components to guarantees the eps-embedding is +given by: + + n_components >= 4 log(n_samples) / (eps^2 / 2 - eps^3 / 3) + + +The first plot shows that with an increasing number of samples ``n_samples``, +the minimal number of dimensions ``n_components`` increased logarithmically +in order to guarantee an ``eps``-embedding. + +The second plot shows that an increase of the admissible +distortion ``eps`` allows to reduce drastically the minimal number of +dimensions ``n_components`` for a given number of samples ``n_samples`` + + +Empirical validation +==================== + +We validate the above bounds on the the digits dataset or on the 20 newsgroups +text document (TF-IDF word frequencies) dataset: + +- for the digits dataset, some 8x8 gray level pixels data for 500 + handwritten digits pictures are randomly projected to spaces for various + larger number of dimensions ``n_components``. + +- for the 20 newsgroups dataset some 500 documents with 100k + features in total are projected using a sparse random matrix to smaller + euclidean spaces with various values for the target number of dimensions + ``n_components``. + +The default dataset is the digits dataset. To run the example on the twenty +newsgroups dataset, pass the --twenty-newsgroups command line argument to this +script. + +For each value of ``n_components``, we plot: + +- 2D distribution of sample pairs with pairwise distances in original + and projected spaces as x and y axis respectively. + +- 1D histogram of the ratio of those distances (projected / original). + +We can see that for low values of ``n_components`` the distribution is wide +with many distorted pairs and a skewed distribution (due to the hard +limit of zero ratio on the left as distances are always positives) +while for larger values of n_components the distortion is controlled +and the distances are well preserved by the random projection. + + +Remarks +======= + +According to the JL lemma, projecting 500 samples without too much distortion +will require at least several thousands dimensions, irrespective of the +number of features of the original dataset. + +Hence using random projections on the digits dataset which only has 64 features +in the input space does not make sense: it does not allow for dimensionality +reduction in this case. + +On the twenty newsgroups on the other hand the dimensionality can be decreased +from 56436 down to 10000 while reasonably preserving pairwise distances. + +""" +print(__doc__) + +import sys +from time import time +import numpy as np +import matplotlib.pyplot as plt +from sklearn.random_projection import johnson_lindenstrauss_min_dim +from sklearn.random_projection import SparseRandomProjection +from sklearn.datasets import fetch_20newsgroups_vectorized +from sklearn.datasets import load_digits +from sklearn.metrics.pairwise import euclidean_distances + +# Part 1: plot the theoretical dependency between n_components_min and +# n_samples + +# range of admissible distortions +eps_range = np.linspace(0.1, 0.99, 5) +colors = plt.cm.Blues(np.linspace(0.3, 1.0, len(eps_range))) + +# range of number of samples (observation) to embed +n_samples_range = np.logspace(1, 9, 9) + +plt.figure() +for eps, color in zip(eps_range, colors): + min_n_components = johnson_lindenstrauss_min_dim(n_samples_range, eps=eps) + plt.loglog(n_samples_range, min_n_components, color=color) + +plt.legend(["eps = %0.1f" % eps for eps in eps_range], loc="lower right") +plt.xlabel("Number of observations to eps-embed") +plt.ylabel("Minimum number of dimensions") +plt.title("Johnson-Lindenstrauss bounds:\nn_samples vs n_components") + +# range of admissible distortions +eps_range = np.linspace(0.01, 0.99, 100) + +# range of number of samples (observation) to embed +n_samples_range = np.logspace(2, 6, 5) +colors = plt.cm.Blues(np.linspace(0.3, 1.0, len(n_samples_range))) + +plt.figure() +for n_samples, color in zip(n_samples_range, colors): + min_n_components = johnson_lindenstrauss_min_dim(n_samples, eps=eps_range) + plt.semilogy(eps_range, min_n_components, color=color) + +plt.legend(["n_samples = %d" % n for n in n_samples_range], loc="upper right") +plt.xlabel("Distortion eps") +plt.ylabel("Minimum number of dimensions") +plt.title("Johnson-Lindenstrauss bounds:\nn_components vs eps") + +# Part 2: perform sparse random projection of some digits images which are +# quite low dimensional and dense or documents of the 20 newsgroups dataset +# which is both high dimensional and sparse + +if '--twenty-newsgroups' in sys.argv: + # Need an internet connection hence not enabled by default + data = fetch_20newsgroups_vectorized().data[:500] +else: + data = load_digits().data[:500] + +n_samples, n_features = data.shape +print("Embedding %d samples with dim %d using various random projections" + % (n_samples, n_features)) + +n_components_range = np.array([300, 1000, 10000]) +dists = euclidean_distances(data, squared=True).ravel() + +# select only non-identical samples pairs +nonzero = dists != 0 +dists = dists[nonzero] + +for n_components in n_components_range: + t0 = time() + rp = SparseRandomProjection(n_components=n_components) + projected_data = rp.fit_transform(data) + print("Projected %d samples from %d to %d in %0.3fs" + % (n_samples, n_features, n_components, time() - t0)) + if hasattr(rp, 'components_'): + n_bytes = rp.components_.data.nbytes + n_bytes += rp.components_.indices.nbytes + print("Random matrix with size: %0.3fMB" % (n_bytes / 1e6)) + + projected_dists = euclidean_distances( + projected_data, squared=True).ravel()[nonzero] + + plt.figure() + plt.hexbin(dists, projected_dists, gridsize=100, cmap=plt.cm.PuBu) + plt.xlabel("Pairwise squared distances in original space") + plt.ylabel("Pairwise squared distances in projected space") + plt.title("Pairwise distances distribution for n_components=%d" % + n_components) + cb = plt.colorbar() + cb.set_label('Sample pairs counts') + + rates = projected_dists / dists + print("Mean distances rate: %0.2f (%0.2f)" + % (np.mean(rates), np.std(rates))) + + plt.figure() + plt.hist(rates, bins=50, normed=True, range=(0., 2.)) + plt.xlabel("Squared distances rate: projected / original") + plt.ylabel("Distribution of samples pairs") + plt.title("Histogram of pairwise distance rates for n_components=%d" % + n_components) + + # TODO: compute the expected value of eps and add them to the previous plot + # as vertical lines / region + +plt.show() diff --git a/examples/plot_kernel_approximation.py b/examples/plot_kernel_approximation.py index 0dbfef90eab3d..cbf78be4dfbc0 100644 --- a/examples/plot_kernel_approximation.py +++ b/examples/plot_kernel_approximation.py @@ -3,23 +3,32 @@ Explicit feature map approximation for RBF kernels ================================================== +An example illustrating the approximation of the feature map +of an RBF kernel. + .. currentmodule:: sklearn.kernel_approximation -An example shows how to use :class:`RBFSampler` to appoximate the feature map -of an RBF kernel for classification with an SVM on the digits dataset. Results -using a linear SVM in the original space, a linear SVM using the approximate -mapping and using a kernelized SVM are compared. Timings and accuracy for -varying amounts of Monte Carlo samplings for the approximate mapping are shown. +It shows how to use :class:`RBFSampler` and :class:`Nystroem` to +approximate the feature map of an RBF kernel for classification with an SVM on +the digits dataset. Results using a linear SVM in the original space, a linear +SVM using the approximate mappings and using a kernelized SVM are compared. +Timings and accuracy for varying amounts of Monte Carlo samplings (in the case +of :class:`RBFSampler`, which uses random Fourier features) and different sized +subsets of the training set (for :class:`Nystroem`) for the approximate mapping +are shown. + +Please note that the dataset here is not large enough to show the benefits +of kernel approximation, as the exact SVM is still reasonably fast. Sampling more dimensions clearly leads to better classification results, but comes at a greater cost. This means there is a tradeoff between runtime and -accuracy, given by the parameter n_components. Note that solving the Linear +accuracy, given by the parameter n_components. Note that solving the Linear SVM and also the approximate kernel SVM could be greatly accelerated by using stochastic gradient descent via :class:`sklearn.linear_model.SGDClassifier`. This is not easily possible for the case of the kernelized SVM. The second plot visualized the decision surfaces of the RBF kernel SVM and -the linear SVM with approximate kernel map. +the linear SVM with approximate kernel maps. The plot shows decision surfaces of the classifiers projected onto the first two principal components of the data. This visualization should be taken with a grain of salt since it is just an interesting slice through @@ -28,24 +37,25 @@ into the region it is lying in, since it will not lie on the plane that the first two principal components span. -The usage of :class:`RBFSampler` is described in detail in -:ref:`kernel_approximation`. +The usage of :class:`RBFSampler` and :class:`Nystroem` is described in detail +in :ref:`kernel_approximation`. """ -print __doc__ +print(__doc__) # Author: Gael Varoquaux -# modified Andreas Mueller -# License: Simplified BSD +# Andreas Mueller +# License: BSD 3 clause # Standard scientific Python imports -import pylab as pl +import matplotlib.pyplot as plt import numpy as np from time import time # Import datasets, classifiers and performance metrics from sklearn import datasets, svm, pipeline -from sklearn.kernel_approximation import RBFSampler +from sklearn.kernel_approximation import (RBFSampler, + Nystroem) from sklearn.decomposition import PCA # The digits dataset @@ -71,9 +81,13 @@ # create pipeline from kernel approximation # and linear svm -feature_map = RBFSampler(gamma=.2, random_state=1) -approx_kernel_svm = pipeline.Pipeline([("feature_map", feature_map), - ("svm", svm.LinearSVC())]) +feature_map_fourier = RBFSampler(gamma=.2, random_state=1) +feature_map_nystroem = Nystroem(gamma=.2, random_state=1) +fourier_approx_svm = pipeline.Pipeline([("feature_map", feature_map_fourier), + ("svm", svm.LinearSVC())]) + +nystroem_approx_svm = pipeline.Pipeline([("feature_map", feature_map_nystroem), + ("svm", svm.LinearSVC())]) # fit and predict using linear and kernel svm: @@ -87,37 +101,52 @@ linear_svm_score = linear_svm.score(data_test, targets_test) linear_svm_time = time() - linear_svm_time -sample_sizes = 50 * np.arange(1, 10) -approx_kernel_scores = [] -approx_kernel_times = [] +sample_sizes = 30 * np.arange(1, 10) +fourier_scores = [] +nystroem_scores = [] +fourier_times = [] +nystroem_times = [] for D in sample_sizes: - approx_kernel_svm.set_params(feature_map__n_components=D) - approx_kernel_timing = time() - approx_kernel_svm.fit(data_train, targets_train) - approx_kernel_times.append(time() - approx_kernel_timing) - score = approx_kernel_svm.score(data_test, targets_test) - approx_kernel_scores.append(score) + fourier_approx_svm.set_params(feature_map__n_components=D) + nystroem_approx_svm.set_params(feature_map__n_components=D) + start = time() + nystroem_approx_svm.fit(data_train, targets_train) + nystroem_times.append(time() - start) + + start = time() + fourier_approx_svm.fit(data_train, targets_train) + fourier_times.append(time() - start) + + fourier_score = fourier_approx_svm.score(data_test, targets_test) + nystroem_score = nystroem_approx_svm.score(data_test, targets_test) + nystroem_scores.append(nystroem_score) + fourier_scores.append(fourier_score) # plot the results: -accuracy = pl.subplot(211) +plt.figure(figsize=(8, 8)) +accuracy = plt.subplot(211) # second y axis for timeings -timescale = pl.subplot(212) +timescale = plt.subplot(212) + +accuracy.plot(sample_sizes, nystroem_scores, label="Nystroem approx. kernel") +timescale.plot(sample_sizes, nystroem_times, '--', + label='Nystroem approx. kernel') -accuracy.plot(sample_sizes, approx_kernel_scores, label="approx. kernel") -timescale.plot(sample_sizes, approx_kernel_times, '--', - label='approx. kernel') +accuracy.plot(sample_sizes, fourier_scores, label="Fourier approx. kernel") +timescale.plot(sample_sizes, fourier_times, '--', + label='Fourier approx. kernel') # horizontal lines for exact rbf and linear kernels: -accuracy.plot([sample_sizes[0], sample_sizes[-1]], [linear_svm_score, - linear_svm_score], label="linear svm") -timescale.plot([sample_sizes[0], sample_sizes[-1]], [linear_svm_time, - linear_svm_time], '--', label='linear svm') +accuracy.plot([sample_sizes[0], sample_sizes[-1]], + [linear_svm_score, linear_svm_score], label="linear svm") +timescale.plot([sample_sizes[0], sample_sizes[-1]], + [linear_svm_time, linear_svm_time], '--', label='linear svm') -accuracy.plot([sample_sizes[0], sample_sizes[-1]], [kernel_svm_score, - kernel_svm_score], label="rbf svm") -timescale.plot([sample_sizes[0], sample_sizes[-1]], [kernel_svm_time, - kernel_svm_time], '--', label='rbf svm') +accuracy.plot([sample_sizes[0], sample_sizes[-1]], + [kernel_svm_score, kernel_svm_score], label="rbf svm") +timescale.plot([sample_sizes[0], sample_sizes[-1]], + [kernel_svm_time, kernel_svm_time], '--', label='rbf svm') # vertical line for dataset dimensionality = 64 accuracy.plot([64, 64], [0.7, 1], label="n_features") @@ -127,7 +156,7 @@ timescale.set_title("Training times") accuracy.set_xlim(sample_sizes[0], sample_sizes[-1]) accuracy.set_xticks(()) -accuracy.set_ylim(np.min(approx_kernel_scores), 1) +accuracy.set_ylim(np.min(fourier_scores), 1) timescale.set_xlabel("Sampling steps = transformed feature dimension") accuracy.set_ylabel("Classification accuracy") timescale.set_ylabel("Training time in seconds") @@ -152,24 +181,30 @@ # title for the plots titles = ['SVC with rbf kernel', - 'SVC (linear kernel) with rbf feature map\n n_components=100'] + 'SVC (linear kernel)\n with Fourier rbf feature map\n' + 'n_components=100', + 'SVC (linear kernel)\n with Nystroem rbf feature map\n' + 'n_components=100'] -pl.figure(figsize=(12, 5)) +plt.tight_layout() +plt.figure(figsize=(12, 5)) # predict and plot -for i, clf in enumerate((kernel_svm, approx_kernel_svm)): - # Plot the decision boundary. For that, we will asign a color to each +for i, clf in enumerate((kernel_svm, nystroem_approx_svm, + fourier_approx_svm)): + # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. - pl.subplot(1, 2, i + 1) + plt.subplot(1, 3, i + 1) Z = clf.predict(flat_grid) # Put the result into a color plot Z = Z.reshape(grid.shape[:-1]) - pl.contourf(multiples, multiples, Z, cmap=pl.cm.Paired) - pl.axis('off') + plt.contourf(multiples, multiples, Z, cmap=plt.cm.Paired) + plt.axis('off') # Plot also the training points - pl.scatter(X[:, 0], X[:, 1], c=targets_train, cmap=pl.cm.Paired) + plt.scatter(X[:, 0], X[:, 1], c=targets_train, cmap=plt.cm.Paired) - pl.title(titles[i]) -pl.show() + plt.title(titles[i]) +plt.tight_layout() +plt.show() diff --git a/examples/plot_kernel_ridge_regression.py b/examples/plot_kernel_ridge_regression.py new file mode 100644 index 0000000000000..19aeece6658cc --- /dev/null +++ b/examples/plot_kernel_ridge_regression.py @@ -0,0 +1,170 @@ +""" +============================================= +Comparison of kernel ridge regression and SVR +============================================= + +Both kernel ridge regression (KRR) and SVR learn a non-linear function by +employing the kernel trick, i.e., they learn a linear function in the space +induced by the respective kernel which corresponds to a non-linear function in +the original space. They differ in the loss functions (ridge versus +epsilon-insensitive loss). In contrast to SVR, fitting a KRR can be done in +closed-form and is typically faster for medium-sized datasets. On the other +hand, the learned model is non-sparse and thus slower than SVR at +prediction-time. + +This example illustrates both methods on an artificial dataset, which +consists of a sinusoidal target function and strong noise added to every fifth +datapoint. The first figure compares the learned model of KRR and SVR when both +complexity/regularization and bandwidth of the RBF kernel are optimized using +grid-search. The learned functions are very similar; however, fitting KRR is +approx. seven times faster than fitting SVR (both with grid-search). However, +prediction of 100000 target values is more than tree times faster with SVR +since it has learned a sparse model using only approx. 1/3 of the 100 training +datapoints as support vectors. + +The next figure compares the time for fitting and prediction of KRR and SVR for +different sizes of the training set. Fitting KRR is faster than SVR for medium- +sized training sets (less than 1000 samples); however, for larger training sets +SVR scales better. With regard to prediction time, SVR is faster than +KRR for all sizes of the training set because of the learned sparse +solution. Note that the degree of sparsity and thus the prediction time depends +on the parameters epsilon and C of the SVR. +""" + +# Authors: Jan Hendrik Metzen +# License: BSD 3 clause + + +from __future__ import division +import time + +import numpy as np + +from sklearn.svm import SVR +from sklearn.grid_search import GridSearchCV +from sklearn.learning_curve import learning_curve +from sklearn.kernel_ridge import KernelRidge +import matplotlib.pyplot as plt + +rng = np.random.RandomState(0) + +############################################################################# +# Generate sample data +X = 5 * rng.rand(10000, 1) +y = np.sin(X).ravel() + +# Add noise to targets +y[::5] += 3 * (0.5 - rng.rand(X.shape[0]/5)) + +X_plot = np.linspace(0, 5, 100000)[:, None] + +############################################################################# +# Fit regression model +train_size = 100 +svr = GridSearchCV(SVR(kernel='rbf', gamma=0.1), cv=5, + param_grid={"C": [1e0, 1e1, 1e2, 1e3], + "gamma": np.logspace(-2, 2, 5)}) + +kr = GridSearchCV(KernelRidge(kernel='rbf', gamma=0.1), cv=5, + param_grid={"alpha": [1e0, 0.1, 1e-2, 1e-3], + "gamma": np.logspace(-2, 2, 5)}) + +t0 = time.time() +svr.fit(X[:train_size], y[:train_size]) +svr_fit = time.time() - t0 +print("SVR complexity and bandwidth selected and model fitted in %.3f s" + % svr_fit) + +t0 = time.time() +kr.fit(X[:train_size], y[:train_size]) +kr_fit = time.time() - t0 +print("KRR complexity and bandwidth selected and model fitted in %.3f s" + % kr_fit) + +sv_ratio = svr.best_estimator_.support_.shape[0] / train_size +print("Support vector ratio: %.3f" % sv_ratio) + +t0 = time.time() +y_svr = svr.predict(X_plot) +svr_predict = time.time() - t0 +print("SVR prediction for %d inputs in %.3f s" + % (X_plot.shape[0], svr_predict)) + +t0 = time.time() +y_kr = kr.predict(X_plot) +kr_predict = time.time() - t0 +print("KRR prediction for %d inputs in %.3f s" + % (X_plot.shape[0], kr_predict)) + + +############################################################################# +# look at the results +sv_ind = svr.best_estimator_.support_ +plt.scatter(X[sv_ind], y[sv_ind], c='r', s=50, label='SVR support vectors') +plt.scatter(X[:100], y[:100], c='k', label='data') +plt.hold('on') +plt.plot(X_plot, y_svr, c='r', + label='SVR (fit: %.3fs, predict: %.3fs)' % (svr_fit, svr_predict)) +plt.plot(X_plot, y_kr, c='g', + label='KRR (fit: %.3fs, predict: %.3fs)' % (kr_fit, kr_predict)) +plt.xlabel('data') +plt.ylabel('target') +plt.title('SVR versus Kernel Ridge') +plt.legend() + +# Visualize training and prediction time +plt.figure() + +# Generate sample data +X = 5 * rng.rand(10000, 1) +y = np.sin(X).ravel() +y[::5] += 3 * (0.5 - rng.rand(X.shape[0]/5)) +sizes = np.logspace(1, 4, 7) +for name, estimator in {"KRR": KernelRidge(kernel='rbf', alpha=0.1, + gamma=10), + "SVR": SVR(kernel='rbf', C=1e1, gamma=10)}.items(): + train_time = [] + test_time = [] + for train_test_size in sizes: + t0 = time.time() + estimator.fit(X[:train_test_size], y[:train_test_size]) + train_time.append(time.time() - t0) + + t0 = time.time() + estimator.predict(X_plot[:1000]) + test_time.append(time.time() - t0) + + plt.plot(sizes, train_time, 'o-', color="r" if name == "SVR" else "g", + label="%s (train)" % name) + plt.plot(sizes, test_time, 'o--', color="r" if name == "SVR" else "g", + label="%s (test)" % name) + +plt.xscale("log") +plt.yscale("log") +plt.xlabel("Train size") +plt.ylabel("Time (seconds)") +plt.title('Execution Time') +plt.legend(loc="best") + +# Visualize learning curves +plt.figure() + +svr = SVR(kernel='rbf', C=1e1, gamma=0.1) +kr = KernelRidge(kernel='rbf', alpha=0.1, gamma=0.1) +train_sizes, train_scores_svr, test_scores_svr = \ + learning_curve(svr, X[:100], y[:100], train_sizes=np.linspace(0.1, 1, 10), + scoring="mean_squared_error", cv=10) +train_sizes_abs, train_scores_kr, test_scores_kr = \ + learning_curve(kr, X[:100], y[:100], train_sizes=np.linspace(0.1, 1, 10), + scoring="mean_squared_error", cv=10) + +plt.plot(train_sizes, test_scores_svr.mean(1), 'o-', color="r", + label="SVR") +plt.plot(train_sizes, test_scores_kr.mean(1), 'o-', color="g", + label="KRR") +plt.xlabel("Train size") +plt.ylabel("Mean Squared Error") +plt.title('Learning curves') +plt.legend(loc="best") + +plt.show() diff --git a/examples/plot_multilabel.py b/examples/plot_multilabel.py index 4b30f4382974c..d6171ade8c511 100644 --- a/examples/plot_multilabel.py +++ b/examples/plot_multilabel.py @@ -1,5 +1,5 @@ # Authors: Vlad Niculae, Mathieu Blondel -# License: BSD +# License: BSD 3 clause """ ========================= Multilabel classification @@ -29,17 +29,17 @@ labels (as in semi-supervised learning) but that the samples simply do *not* have a label. """ -print __doc__ +print(__doc__) import numpy as np -import matplotlib.pylab as pl +import matplotlib.pyplot as plt from sklearn.datasets import make_multilabel_classification from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import SVC from sklearn.preprocessing import LabelBinarizer from sklearn.decomposition import PCA -from sklearn.pls import CCA +from sklearn.cross_decomposition import CCA def plot_hyperplane(clf, min_x, max_x, linestyle, label): @@ -48,55 +48,57 @@ def plot_hyperplane(clf, min_x, max_x, linestyle, label): a = -w[0] / w[1] xx = np.linspace(min_x - 5, max_x + 5) # make sure the line is long enough yy = a * xx - (clf.intercept_[0]) / w[1] - pl.plot(xx, yy, linestyle, label=label) + plt.plot(xx, yy, linestyle, label=label) def plot_subfigure(X, Y, subplot, title, transform): if transform == "pca": X = PCA(n_components=2).fit_transform(X) elif transform == "cca": - # Convert list of tuples to a class indicator matrix first - Y_indicator = LabelBinarizer().fit(Y).transform(Y) - X = CCA(n_components=2).fit(X, Y_indicator).transform(X) + X = CCA(n_components=2).fit(X, Y).transform(X) else: raise ValueError min_x = np.min(X[:, 0]) max_x = np.max(X[:, 0]) + min_y = np.min(X[:, 1]) + max_y = np.max(X[:, 1]) + classif = OneVsRestClassifier(SVC(kernel='linear')) classif.fit(X, Y) - pl.subplot(2, 2, subplot) - pl.title(title) + plt.subplot(2, 2, subplot) + plt.title(title) - zero_class = np.where([0 in y for y in Y]) - one_class = np.where([1 in y for y in Y]) - pl.scatter(X[:, 0], X[:, 1], s=40, c='gray') - pl.scatter(X[zero_class, 0], X[zero_class, 1], s=160, edgecolors='b', + zero_class = np.where(Y[:, 0]) + one_class = np.where(Y[:, 1]) + plt.scatter(X[:, 0], X[:, 1], s=40, c='gray') + plt.scatter(X[zero_class, 0], X[zero_class, 1], s=160, edgecolors='b', facecolors='none', linewidths=2, label='Class 1') - pl.scatter(X[one_class, 0], X[one_class, 1], s=80, edgecolors='orange', + plt.scatter(X[one_class, 0], X[one_class, 1], s=80, edgecolors='orange', facecolors='none', linewidths=2, label='Class 2') - pl.axis('tight') plot_hyperplane(classif.estimators_[0], min_x, max_x, 'k--', 'Boundary\nfor class 1') plot_hyperplane(classif.estimators_[1], min_x, max_x, 'k-.', 'Boundary\nfor class 2') - pl.xticks(()) - pl.yticks(()) + plt.xticks(()) + plt.yticks(()) + plt.xlim(min_x - .5 * max_x, max_x + .5 * max_x) + plt.ylim(min_y - .5 * max_y, max_y + .5 * max_y) if subplot == 2: - pl.xlim(min_x - 5, max_x) - pl.xlabel('First principal component') - pl.ylabel('Second principal component') - pl.legend(loc="upper left") + plt.xlabel('First principal component') + plt.ylabel('Second principal component') + plt.legend(loc="upper left") -pl.figure(figsize=(8, 6)) +plt.figure(figsize=(8, 6)) X, Y = make_multilabel_classification(n_classes=2, n_labels=1, allow_unlabeled=True, + return_indicator=True, random_state=1) plot_subfigure(X, Y, 1, "With unlabeled samples + CCA", "cca") @@ -104,10 +106,11 @@ def plot_subfigure(X, Y, subplot, title, transform): X, Y = make_multilabel_classification(n_classes=2, n_labels=1, allow_unlabeled=False, + return_indicator=True, random_state=1) plot_subfigure(X, Y, 3, "Without unlabeled samples + CCA", "cca") plot_subfigure(X, Y, 4, "Without unlabeled samples + PCA", "pca") -pl.subplots_adjust(.04, .02, .97, .94, .09, .2) -pl.show() +plt.subplots_adjust(.04, .02, .97, .94, .09, .2) +plt.show() diff --git a/examples/plot_multioutput_face_completion.py b/examples/plot_multioutput_face_completion.py new file mode 100644 index 0000000000000..7a218a6ecb9f9 --- /dev/null +++ b/examples/plot_multioutput_face_completion.py @@ -0,0 +1,98 @@ +""" +============================================== +Face completion with a multi-output estimators +============================================== + +This example shows the use of multi-output estimator to complete images. +The goal is to predict the lower half of a face given its upper half. + +The first column of images shows true faces. The next columns illustrate +how extremely randomized trees, k nearest neighbors, linear +regression and ridge regression complete the lower half of those faces. + +""" +print(__doc__) + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.datasets import fetch_olivetti_faces +from sklearn.utils.validation import check_random_state + +from sklearn.ensemble import ExtraTreesRegressor +from sklearn.neighbors import KNeighborsRegressor +from sklearn.linear_model import LinearRegression +from sklearn.linear_model import RidgeCV + +# Load the faces datasets +data = fetch_olivetti_faces() +targets = data.target + +data = data.images.reshape((len(data.images), -1)) +train = data[targets < 30] +test = data[targets >= 30] # Test on independent people + +# Test on a subset of people +n_faces = 5 +rng = check_random_state(4) +face_ids = rng.randint(test.shape[0], size=(n_faces, )) +test = test[face_ids, :] + +n_pixels = data.shape[1] +X_train = train[:, :np.ceil(0.5 * n_pixels)] # Upper half of the faces +y_train = train[:, np.floor(0.5 * n_pixels):] # Lower half of the faces +X_test = test[:, :np.ceil(0.5 * n_pixels)] +y_test = test[:, np.floor(0.5 * n_pixels):] + +# Fit estimators +ESTIMATORS = { + "Extra trees": ExtraTreesRegressor(n_estimators=10, max_features=32, + random_state=0), + "K-nn": KNeighborsRegressor(), + "Linear regression": LinearRegression(), + "Ridge": RidgeCV(), +} + +y_test_predict = dict() +for name, estimator in ESTIMATORS.items(): + estimator.fit(X_train, y_train) + y_test_predict[name] = estimator.predict(X_test) + +# Plot the completed faces +image_shape = (64, 64) + +n_cols = 1 + len(ESTIMATORS) +plt.figure(figsize=(2. * n_cols, 2.26 * n_faces)) +plt.suptitle("Face completion with multi-output estimators", size=16) + +for i in range(n_faces): + true_face = np.hstack((X_test[i], y_test[i])) + + if i: + sub = plt.subplot(n_faces, n_cols, i * n_cols + 1) + else: + sub = plt.subplot(n_faces, n_cols, i * n_cols + 1, + title="true faces") + + + sub.axis("off") + sub.imshow(true_face.reshape(image_shape), + cmap=plt.cm.gray, + interpolation="nearest") + + for j, est in enumerate(sorted(ESTIMATORS)): + completed_face = np.hstack((X_test[i], y_test_predict[est][i])) + + if i: + sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j) + + else: + sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j, + title=est) + + sub.axis("off") + sub.imshow(completed_face.reshape(image_shape), + cmap=plt.cm.gray, + interpolation="nearest") + +plt.show() diff --git a/examples/plot_precision_recall.py b/examples/plot_precision_recall.py deleted file mode 100644 index 532b0f6575e52..0000000000000 --- a/examples/plot_precision_recall.py +++ /dev/null @@ -1,51 +0,0 @@ -""" -================ -Precision-Recall -================ - -Example of Precision-Recall metric to evaluate the quality -of the output of a classifier. -""" -print __doc__ - -import random -import pylab as pl -import numpy as np -from sklearn import svm, datasets -from sklearn.metrics import precision_recall_curve -from sklearn.metrics import auc - -# import some data to play with -iris = datasets.load_iris() -X = iris.data -y = iris.target -X, y = X[y != 2], y[y != 2] # Keep also 2 classes (0 and 1) -n_samples, n_features = X.shape -p = range(n_samples) # Shuffle samples -random.seed(0) -random.shuffle(p) -X, y = X[p], y[p] -half = int(n_samples / 2) - -# Add noisy features -np.random.seed(0) -X = np.c_[X, np.random.randn(n_samples, 200 * n_features)] - -# Run classifier -classifier = svm.SVC(kernel='linear', probability=True) -probas_ = classifier.fit(X[:half], y[:half]).predict_proba(X[half:]) - -# Compute Precision-Recall and plot curve -precision, recall, thresholds = precision_recall_curve(y[half:], probas_[:, 1]) -area = auc(recall, precision) -print "Area Under Curve: %0.2f" % area - -pl.clf() -pl.plot(recall, precision, label='Precision-Recall curve') -pl.xlabel('Recall') -pl.ylabel('Precision') -pl.ylim([0.0, 1.05]) -pl.xlim([0.0, 1.0]) -pl.title('Precision-Recall example: AUC=%0.2f' % area) -pl.legend(loc="lower left") -pl.show() diff --git a/examples/plot_roc.py b/examples/plot_roc.py deleted file mode 100644 index 994c63856847b..0000000000000 --- a/examples/plot_roc.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -======================================= -Receiver operating characteristic (ROC) -======================================= - -Example of Receiver operating characteristic (ROC) metric to -evaluate the quality of the output of a classifier. -""" -print __doc__ - -import numpy as np -import pylab as pl -from sklearn import svm, datasets -from sklearn.utils import shuffle -from sklearn.metrics import roc_curve, auc - -random_state = np.random.RandomState(0) - -# Import some data to play with -iris = datasets.load_iris() -X = iris.data -y = iris.target - -# Make it a binary classification problem by removing the third class -X, y = X[y != 2], y[y != 2] -n_samples, n_features = X.shape - -# Add noisy features to make the problem harder -X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] - -# shuffle and split training and test sets -X, y = shuffle(X, y, random_state=random_state) -half = int(n_samples / 2) -X_train, X_test = X[:half], X[half:] -y_train, y_test = y[:half], y[half:] - -# Run classifier -classifier = svm.SVC(kernel='linear', probability=True) -probas_ = classifier.fit(X_train, y_train).predict_proba(X_test) - -# Compute ROC curve and area the curve -fpr, tpr, thresholds = roc_curve(y_test, probas_[:, 1]) -roc_auc = auc(fpr, tpr) -print "Area under the ROC curve : %f" % roc_auc - -# Plot ROC curve -pl.clf() -pl.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc) -pl.plot([0, 1], [0, 1], 'k--') -pl.xlim([0.0, 1.0]) -pl.ylim([0.0, 1.0]) -pl.xlabel('False Positive Rate') -pl.ylabel('True Positive Rate') -pl.title('Receiver operating characteristic example') -pl.legend(loc="lower right") -pl.show() diff --git a/examples/plot_roc_crossval.py b/examples/plot_roc_crossval.py deleted file mode 100644 index 9be522837678f..0000000000000 --- a/examples/plot_roc_crossval.py +++ /dev/null @@ -1,67 +0,0 @@ -""" -============================================================= -Receiver operating characteristic (ROC) with cross validation -============================================================= - -Example of Receiver operating characteristic (ROC) metric to -evaluate the quality of the output of a classifier using -cross-validation. -""" -print __doc__ - -import numpy as np -from scipy import interp -import pylab as pl - -from sklearn import svm, datasets -from sklearn.metrics import roc_curve, auc -from sklearn.cross_validation import StratifiedKFold - -############################################################################### -# Data IO and generation - -# import some data to play with -iris = datasets.load_iris() -X = iris.data -y = iris.target -X, y = X[y != 2], y[y != 2] -n_samples, n_features = X.shape - -# Add noisy features -X = np.c_[X, np.random.randn(n_samples, 200 * n_features)] - -############################################################################### -# Classification and ROC analysis - -# Run classifier with crossvalidation and plot ROC curves -cv = StratifiedKFold(y, k=6) -classifier = svm.SVC(kernel='linear', probability=True) - -mean_tpr = 0.0 -mean_fpr = np.linspace(0, 1, 100) -all_tpr = [] - -for i, (train, test) in enumerate(cv): - probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test]) - # Compute ROC curve and area the curve - fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1]) - mean_tpr += interp(mean_fpr, fpr, tpr) - mean_tpr[0] = 0.0 - roc_auc = auc(fpr, tpr) - pl.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc)) - -pl.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') - -mean_tpr /= len(cv) -mean_tpr[-1] = 1.0 -mean_auc = auc(mean_fpr, mean_tpr) -pl.plot(mean_fpr, mean_tpr, 'k--', - label='Mean ROC (area = %0.2f)' % mean_auc, lw=2) - -pl.xlim([-0.05, 1.05]) -pl.ylim([-0.05, 1.05]) -pl.xlabel('False Positive Rate') -pl.ylabel('True Positive Rate') -pl.title('Receiver operating characteristic example') -pl.legend(loc="lower right") -pl.show() diff --git a/examples/semi_supervised/README.txt b/examples/semi_supervised/README.txt index 0158b8b07d2d3..345a400676ae3 100644 --- a/examples/semi_supervised/README.txt +++ b/examples/semi_supervised/README.txt @@ -3,4 +3,4 @@ Semi Supervised Classification ------------------------------ -Examples concerning the :mod:`sklearn.semi_supervised` package. +Examples concerning the :mod:`sklearn.semi_supervised` module. diff --git a/examples/semi_supervised/plot_label_propagation_digits.py b/examples/semi_supervised/plot_label_propagation_digits.py index 465930a921bd9..9f2daa3a9c098 100644 --- a/examples/semi_supervised/plot_label_propagation_digits.py +++ b/examples/semi_supervised/plot_label_propagation_digits.py @@ -14,21 +14,20 @@ class will be very good. At the end, the top 10 most uncertain predictions will be shown. """ -print __doc__ +print(__doc__) # Authors: Clay Woolam # Licence: BSD import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from scipy import stats from sklearn import datasets from sklearn.semi_supervised import label_propagation -from sklearn.metrics import metrics -from sklearn.metrics.metrics import confusion_matrix +from sklearn.metrics import confusion_matrix, classification_report digits = datasets.load_digits() rng = np.random.RandomState(0) @@ -52,21 +51,20 @@ class will be very good. ############################################################################### # Learn with LabelSpreading -lp_model = label_propagation.LabelSpreading(gamma=0.25, max_iters=5) +lp_model = label_propagation.LabelSpreading(gamma=0.25, max_iter=5) lp_model.fit(X, y_train) predicted_labels = lp_model.transduction_[unlabeled_set] true_labels = y[unlabeled_set] -cm = confusion_matrix(true_labels, predicted_labels, - labels=lp_model.classes_) +cm = confusion_matrix(true_labels, predicted_labels, labels=lp_model.classes_) -print "Label Spreading model: %d labeled & %d unlabeled points (%d total)" % \ - (n_labeled_points, n_total_samples - n_labeled_points, n_total_samples) +print("Label Spreading model: %d labeled & %d unlabeled points (%d total)" % + (n_labeled_points, n_total_samples - n_labeled_points, n_total_samples)) -print metrics.classification_report(true_labels, predicted_labels) +print(classification_report(true_labels, predicted_labels)) -print "Confusion matrix" -print cm +print("Confusion matrix") +print(cm) # calculate uncertainty values for each transduced distribution pred_entropies = stats.distributions.entropy(lp_model.label_distributions_.T) @@ -76,16 +74,16 @@ class will be very good. ############################################################################### # plot -f = pl.figure(figsize=(7, 5)) +f = plt.figure(figsize=(7, 5)) for index, image_index in enumerate(uncertainty_index): image = images[image_index] sub = f.add_subplot(2, 5, index + 1) - sub.imshow(image, cmap=pl.cm.gray_r) - pl.xticks([]) - pl.yticks([]) + sub.imshow(image, cmap=plt.cm.gray_r) + plt.xticks([]) + plt.yticks([]) sub.set_title('predict: %i\ntrue: %i' % ( lp_model.transduction_[image_index], y[image_index])) f.suptitle('Learning with small amount of labeled data') -pl.show() +plt.show() diff --git a/examples/semi_supervised/plot_label_propagation_digits_active_learning.py b/examples/semi_supervised/plot_label_propagation_digits_active_learning.py index 05547b36b2aef..05329ed00b4ec 100644 --- a/examples/semi_supervised/plot_label_propagation_digits_active_learning.py +++ b/examples/semi_supervised/plot_label_propagation_digits_active_learning.py @@ -15,13 +15,13 @@ of training. These may or may not contain mistakes, but we will train the next model with their true labels. """ -print __doc__ +print(__doc__) # Authors: Clay Woolam # Licence: BSD import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from scipy import stats from sklearn import datasets @@ -41,38 +41,38 @@ n_labeled_points = 10 unlabeled_indices = np.arange(n_total_samples)[n_labeled_points:] -f = pl.figure() +f = plt.figure() for i in range(5): y_train = np.copy(y) y_train[unlabeled_indices] = -1 - lp_model = label_propagation.LabelSpreading(gamma=0.25, max_iters=5) + lp_model = label_propagation.LabelSpreading(gamma=0.25, max_iter=5) lp_model.fit(X, y_train) predicted_labels = lp_model.transduction_[unlabeled_indices] true_labels = y[unlabeled_indices] cm = confusion_matrix(true_labels, predicted_labels, - labels=lp_model.classes_) + labels=lp_model.classes_) - print ('Iteration %i ' + 70 * '_') % i - print "Label Spreading model: %d labeled & %d unlabeled (%d total)" %\ - (n_labeled_points, n_total_samples - n_labeled_points, n_total_samples) + print('Iteration %i %s' % (i, 70 * '_')) + print("Label Spreading model: %d labeled & %d unlabeled (%d total)" + % (n_labeled_points, n_total_samples - n_labeled_points, n_total_samples)) - print classification_report(true_labels, predicted_labels) + print(classification_report(true_labels, predicted_labels)) - print "Confusion matrix" - print cm + print("Confusion matrix") + print(cm) # compute the entropies of transduced label distributions pred_entropies = stats.distributions.entropy( - lp_model.label_distributions_.T) + lp_model.label_distributions_.T) # select five digit examples that the classifier is most uncertain about uncertainty_index = uncertainty_index = np.argsort(pred_entropies)[-5:] - # keep track of indicies that we get labels for + # keep track of indices that we get labels for delete_indices = np.array([]) f.text(.05, (1 - (i + 1) * .183), @@ -81,7 +81,7 @@ image = images[image_index] sub = f.add_subplot(5, 5, index + 1 + (5 * i)) - sub.imshow(image, cmap=pl.cm.gray_r) + sub.imshow(image, cmap=plt.cm.gray_r) sub.set_title('predict: %i\ntrue: %i' % ( lp_model.transduction_[image_index], y[image_index]), size=10) sub.axis('off') @@ -95,5 +95,5 @@ f.suptitle("Active learning with Label Propagation.\nRows show 5 most " "uncertain labels to learn with the next model.") -pl.subplots_adjust(0.12, 0.03, 0.9, 0.8, 0.2, 0.45) -pl.show() +plt.subplots_adjust(0.12, 0.03, 0.9, 0.8, 0.2, 0.45) +plt.show() diff --git a/examples/semi_supervised/plot_label_propagation_structure.py b/examples/semi_supervised/plot_label_propagation_structure.py index fb909e608c1ec..24ab31ba33d6d 100644 --- a/examples/semi_supervised/plot_label_propagation_structure.py +++ b/examples/semi_supervised/plot_label_propagation_structure.py @@ -9,14 +9,14 @@ lie inside their own distinct shape, we can see that the labels propagate correctly around the circle. """ -print __doc__ +print(__doc__) # Authors: Clay Woolam # Andreas Mueller # Licence: BSD import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.semi_supervised import label_propagation from sklearn.datasets import make_circles @@ -36,27 +36,27 @@ ############################################################################### # Plot output labels output_labels = label_spread.transduction_ -pl.figure(figsize=(8.5, 4)) -pl.subplot(1, 2, 1) -plot_outer_labeled, = pl.plot(X[labels == outer, 0], - X[labels == outer, 1], 'rs') -plot_unlabeled, = pl.plot(X[labels == -1, 0], X[labels == -1, 1], 'g.') -plot_inner_labeled, = pl.plot(X[labels == inner, 0], - X[labels == inner, 1], 'bs') -pl.legend((plot_outer_labeled, plot_inner_labeled, plot_unlabeled), - ('Outer Labeled', 'Inner Labeled', 'Unlabeled'), 'upper left', - numpoints=1, shadow=False) -pl.title("Raw data (2 classes=red and blue)") - -pl.subplot(1, 2, 2) +plt.figure(figsize=(8.5, 4)) +plt.subplot(1, 2, 1) +plot_outer_labeled, = plt.plot(X[labels == outer, 0], + X[labels == outer, 1], 'rs') +plot_unlabeled, = plt.plot(X[labels == -1, 0], X[labels == -1, 1], 'g.') +plot_inner_labeled, = plt.plot(X[labels == inner, 0], + X[labels == inner, 1], 'bs') +plt.legend((plot_outer_labeled, plot_inner_labeled, plot_unlabeled), + ('Outer Labeled', 'Inner Labeled', 'Unlabeled'), 'upper left', + numpoints=1, shadow=False) +plt.title("Raw data (2 classes=red and blue)") + +plt.subplot(1, 2, 2) output_label_array = np.asarray(output_labels) outer_numbers = np.where(output_label_array == outer)[0] inner_numbers = np.where(output_label_array == inner)[0] -plot_outer, = pl.plot(X[outer_numbers, 0], X[outer_numbers, 1], 'rs') -plot_inner, = pl.plot(X[inner_numbers, 0], X[inner_numbers, 1], 'bs') -pl.legend((plot_outer, plot_inner), ('Outer Learned', 'Inner Learned'), - 'upper left', numpoints=1, shadow=False) -pl.title("Labels learned with Label Spreading (KNN)") - -pl.subplots_adjust(left=0.07, bottom=0.07, right=0.93, top=0.92) -pl.show() +plot_outer, = plt.plot(X[outer_numbers, 0], X[outer_numbers, 1], 'rs') +plot_inner, = plt.plot(X[inner_numbers, 0], X[inner_numbers, 1], 'bs') +plt.legend((plot_outer, plot_inner), ('Outer Learned', 'Inner Learned'), + 'upper left', numpoints=1, shadow=False) +plt.title("Labels learned with Label Spreading (KNN)") + +plt.subplots_adjust(left=0.07, bottom=0.07, right=0.93, top=0.92) +plt.show() diff --git a/examples/semi_supervised/plot_label_propagation_versus_svm_iris.py b/examples/semi_supervised/plot_label_propagation_versus_svm_iris.py index eaf9ededea76b..399b04b642a45 100644 --- a/examples/semi_supervised/plot_label_propagation_versus_svm_iris.py +++ b/examples/semi_supervised/plot_label_propagation_versus_svm_iris.py @@ -10,13 +10,13 @@ even with a small amount of labeled data. """ -print __doc__ +print(__doc__) # Authors: Clay Woolam # Licence: BSD import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import datasets from sklearn import svm from sklearn.semi_supervised import label_propagation @@ -59,21 +59,21 @@ color_map = {-1: (1, 1, 1), 0: (0, 0, .9), 1: (1, 0, 0), 2: (.8, .6, 0)} for i, (clf, y_train) in enumerate((ls30, ls50, ls100, rbf_svc)): - # Plot the decision boundary. For that, we will asign a color to each + # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. - pl.subplot(2, 2, i + 1) + plt.subplot(2, 2, i + 1) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) - pl.contourf(xx, yy, Z, cmap=pl.cm.Paired) - pl.axis('off') + plt.contourf(xx, yy, Z, cmap=plt.cm.Paired) + plt.axis('off') # Plot also the training points colors = [color_map[y] for y in y_train] - pl.scatter(X[:, 0], X[:, 1], c=colors, cmap=pl.cm.Paired) + plt.scatter(X[:, 0], X[:, 1], c=colors, cmap=plt.cm.Paired) - pl.title(titles[i]) + plt.title(titles[i]) -pl.text(.90, 0, "Unlabeled points are colored white") -pl.show() +plt.text(.90, 0, "Unlabeled points are colored white") +plt.show() diff --git a/examples/svm/README.txt b/examples/svm/README.txt index 7a5cbd939ee2a..92ebb7401f7e1 100644 --- a/examples/svm/README.txt +++ b/examples/svm/README.txt @@ -3,4 +3,4 @@ Support Vector Machines ----------------------- -Examples concerning the :mod:`sklearn.svm` package. +Examples concerning the :mod:`sklearn.svm` module. diff --git a/examples/svm/plot_custom_kernel.py b/examples/svm/plot_custom_kernel.py index 97f192e908214..d36a48f561abf 100644 --- a/examples/svm/plot_custom_kernel.py +++ b/examples/svm/plot_custom_kernel.py @@ -7,10 +7,10 @@ plot the decision surface and the support vectors. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import svm, datasets # import some data to play with @@ -38,7 +38,7 @@ def my_kernel(x, y): clf = svm.SVC(kernel=my_kernel) clf.fit(X, Y) -# Plot the decision boundary. For that, we will asign a color to each +# Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 @@ -47,11 +47,11 @@ def my_kernel(x, y): # Put the result into a color plot Z = Z.reshape(xx.shape) -pl.pcolormesh(xx, yy, Z, cmap=pl.cm.Paired) +plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) # Plot also the training points -pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired) -pl.title('3-Class classification using Support Vector Machine with custom' - ' kernel') -pl.axis('tight') -pl.show() +plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired) +plt.title('3-Class classification using Support Vector Machine with custom' + ' kernel') +plt.axis('tight') +plt.show() diff --git a/examples/svm/plot_iris.py b/examples/svm/plot_iris.py index 6e97a651568a5..2fe6d64daca49 100644 --- a/examples/svm/plot_iris.py +++ b/examples/svm/plot_iris.py @@ -3,31 +3,57 @@ Plot different SVM classifiers in the iris dataset ================================================== -Comparison of different linear SVM classifiers on the iris dataset. It -will plot the decision surface for four different SVM classifiers. +Comparison of different linear SVM classifiers on a 2D projection of the iris +dataset. We only consider the first 2 features of this dataset: + +- Sepal length +- Sepal width + +This example shows how to plot the decision surface for four SVM classifiers +with different kernels. + +The linear models ``LinearSVC()`` and ``SVC(kernel='linear')`` yield slightly +different decision boundaries. This can be a consequence of the following +differences: + +- ``LinearSVC`` minimizes the squared hinge loss while ``SVC`` minimizes the + regular hinge loss. + +- ``LinearSVC`` uses the One-vs-All (also known as One-vs-Rest) multiclass + reduction while ``SVC`` uses the One-vs-One multiclass reduction. + +Both linear models have linear decision boundaries (intersecting hyperplanes) +while the non-linear kernel models (polynomial or Gaussian RBF) have more +flexible non-linear decision boundaries with shapes that depend on the kind of +kernel and its parameters. + +.. NOTE:: while plotting the decision function of classifiers for toy 2D + datasets can help get an intuitive understanding of their respective + expressive power, be aware that those intuitions don't always generalize to + more realistic high-dimensional problem. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import svm, datasets # import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. We could # avoid this ugly slicing by using a two-dim dataset -Y = iris.target +y = iris.target h = .02 # step size in the mesh # we create an instance of SVM and fit out data. We do not scale our # data since we want to plot the support vectors C = 1.0 # SVM regularization parameter -svc = svm.SVC(kernel='linear', C=C).fit(X, Y) -rbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X, Y) -poly_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, Y) -lin_svc = svm.LinearSVC(C=C).fit(X, Y) +svc = svm.SVC(kernel='linear', C=C).fit(X, y) +rbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X, y) +poly_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, y) +lin_svc = svm.LinearSVC(C=C).fit(X, y) # create a mesh to plot in x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 @@ -37,25 +63,31 @@ # title for the plots titles = ['SVC with linear kernel', + 'LinearSVC (linear kernel)', 'SVC with RBF kernel', - 'SVC with polynomial (degree 3) kernel', - 'LinearSVC (linear kernel)'] + 'SVC with polynomial (degree 3) kernel'] -for i, clf in enumerate((svc, rbf_svc, poly_svc, lin_svc)): - # Plot the decision boundary. For that, we will asign a color to each +for i, clf in enumerate((svc, lin_svc, rbf_svc, poly_svc)): + # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. - pl.subplot(2, 2, i + 1) + plt.subplot(2, 2, i + 1) + plt.subplots_adjust(wspace=0.4, hspace=0.4) + Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) - pl.contourf(xx, yy, Z, cmap=pl.cm.Paired) - pl.axis('off') + plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) # Plot also the training points - pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired) - - pl.title(titles[i]) + plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) + plt.xlabel('Sepal length') + plt.ylabel('Sepal width') + plt.xlim(xx.min(), xx.max()) + plt.ylim(yy.min(), yy.max()) + plt.xticks(()) + plt.yticks(()) + plt.title(titles[i]) -pl.show() +plt.show() diff --git a/examples/svm/plot_oneclass.py b/examples/svm/plot_oneclass.py index c7a19b4eaac5b..8c765673a63cd 100644 --- a/examples/svm/plot_oneclass.py +++ b/examples/svm/plot_oneclass.py @@ -3,14 +3,16 @@ One-class SVM with non-linear kernel (RBF) ========================================== +An example using a one-class SVM for novelty detection. + :ref:`One-class SVM ` is an unsupervised algorithm that learns a decision function for novelty detection: classifying new data as similar or different to the training set. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt import matplotlib.font_manager from sklearn import svm @@ -38,24 +40,24 @@ Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) -pl.title("Novelty Detection") -pl.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7), cmap=pl.cm.Blues_r) -a = pl.contour(xx, yy, Z, levels=[0], linewidths=2, colors='red') -pl.contourf(xx, yy, Z, levels=[0, Z.max()], colors='orange') - -b1 = pl.scatter(X_train[:, 0], X_train[:, 1], c='white') -b2 = pl.scatter(X_test[:, 0], X_test[:, 1], c='green') -c = pl.scatter(X_outliers[:, 0], X_outliers[:, 1], c='red') -pl.axis('tight') -pl.xlim((-5, 5)) -pl.ylim((-5, 5)) -pl.legend([a.collections[0], b1, b2, c], - ["learned frontier", "training observations", - "new regular observations", "new abnormal observations"], - loc="upper left", - prop=matplotlib.font_manager.FontProperties(size=11)) -pl.xlabel( - "error train: %d/200 ; errors novel regular: %d/20 ; " \ - "errors novel abnormal: %d/20" +plt.title("Novelty Detection") +plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7), cmap=plt.cm.Blues_r) +a = plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='red') +plt.contourf(xx, yy, Z, levels=[0, Z.max()], colors='orange') + +b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='white') +b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='green') +c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='red') +plt.axis('tight') +plt.xlim((-5, 5)) +plt.ylim((-5, 5)) +plt.legend([a.collections[0], b1, b2, c], + ["learned frontier", "training observations", + "new regular observations", "new abnormal observations"], + loc="upper left", + prop=matplotlib.font_manager.FontProperties(size=11)) +plt.xlabel( + "error train: %d/200 ; errors novel regular: %d/40 ; " + "errors novel abnormal: %d/40" % (n_error_train, n_error_test, n_error_outliers)) -pl.show() +plt.show() diff --git a/examples/svm/plot_rbf_parameters.py b/examples/svm/plot_rbf_parameters.py index 96865b65b3633..0d8c1eab85b7a 100644 --- a/examples/svm/plot_rbf_parameters.py +++ b/examples/svm/plot_rbf_parameters.py @@ -3,46 +3,111 @@ RBF SVM parameters ================== -This example illustrates the effect of the parameters `gamma` -and `C` of the rbf kernel SVM. - -Intuitively, the `gamma` parameter defines how far the influence -of a single training example reaches, with low values meaning 'far' -and high values meaning 'close'. -The `C` parameter trades off misclassification of training examples -against simplicity of the decision surface. A low C makes -the decision surface smooth, while a high C aims at classifying -all training examples correctly. - -Two plots are generated. The first is a visualization of the -decision function for a variety of parameter values, and the second -is a heatmap of the classifier's cross-validation accuracy as -a function of `C` and `gamma`. +This example illustrates the effect of the parameters ``gamma`` and ``C`` of +the Radius Basis Function (RBF) kernel SVM. + +Intuitively, the ``gamma`` parameter defines how far the influence of a single +training example reaches, with low values meaning 'far' and high values meaning +'close'. The ``gamma`` parameters can be seen as the inverse of the radius of +influence of samples selected by the model as support vectors. + +The ``C`` parameter trades off misclassification of training examples against +simplicity of the decision surface. A low ``C`` makes the decision surface +smooth, while a high ``C`` aims at classifying all training examples correctly +by give the model freedom to select more samples as support vectors. + +The first plot is a visualization of the decision function for a variety of +parameter values on simplified classification problem involving only 2 input +features and 2 possible target classes (binary classification). Note that this +kind of plot is not possible to do for problems with more features or target +classes. + +The second plot is a heatmap of the classifier's cross-validation accuracy as a +function of ``C`` and ``gamma``. For this example we explore a relatively large +grid for illustration purposes. In practice, a logarithmic grid from +:math:`10^{-3}` to :math:`10^3` is usually sufficient. If the best parameters +lie on the boundaries of the grid, it can be extended in that direction in a +subsequent search. + +Note that the heat map plot has a special colorbar with a midpoint value close +to the score values of the best performing models so as to make it easy to tell +them appart in the blink of an eye. + +The behavior of the model is very sensitive to the ``gamma`` parameter. If +``gamma`` is too large, the radius of the area of influence of the support +vectors only includes the support vector it-self and no amount of +regularization with ``C`` will be able to prevent of overfitting. + +When ``gamma`` is very small, the model is too constrained and cannot capture +the complexity or "shape" of the data. The region of influence of any selected +support vector would include the whole training set. The resulting model will +behave similarly to a linear model with a set of hyperplanes that separate the +centers of high density of any pair of two classes. + +For intermediate values, we can see on a the second plot that good models can +be found on a diagonal of ``C`` and ``gamma``. Smooth models (lower ``gamma`` +values) can be made more complex by selecting a larger number of support +vectors (larger ``C`` values) hence the diagonal of good performing models. + +Finally one can also observe that for some intermediate values of ``gamma`` we +get equally performing models when ``C`` becomes very large: it is not +necessary to regularize by limiting the number support vectors. The radius of +the RBF kernel alone acts as a good structural regularizer. In practice though +it might still be interesting to limit the number of support vectors with a +lower value of ``C`` so as to favor models that use less memory and that are +faster to predict. + +We should also note that small differences in scores results from the random +splits of the cross-validation procedure. Those spurious variations can +smoothed out by increasing the number of CV iterations ``n_iter`` at the +expense of compute time. Increasing the value number of ``C_range`` and +``gamma_range`` steps will increase the resolution of the hyper-parameter heat +map. + ''' -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt +from matplotlib.colors import Normalize from sklearn.svm import SVC from sklearn.preprocessing import StandardScaler from sklearn.datasets import load_iris -from sklearn.cross_validation import StratifiedKFold +from sklearn.cross_validation import StratifiedShuffleSplit from sklearn.grid_search import GridSearchCV + +# Utility function to move the midpoint of a colormap to be around +# the values of interest. + +class MidpointNormalize(Normalize): + + def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): + self.midpoint = midpoint + Normalize.__init__(self, vmin, vmax, clip) + + def __call__(self, value, clip=None): + x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] + return np.ma.masked_array(np.interp(value, x, y)) + ############################################################################## # Load and prepare data set # # dataset for grid search + iris = load_iris() X = iris.data -Y = iris.target +y = iris.target + +# Dataset for decision function visualization: we only keep the first two +# features in X and sub-sample the dataset to keep only 2 class to has +# to make it a binary classification problem. -# dataset for decision function visualization X_2d = X[:, :2] -X_2d = X_2d[Y > 0] -Y_2d = Y[Y > 0] -Y_2d -= 1 +X_2d = X_2d[y > 0] +y_2d = y[y > 0] +y_2d -= 1 # It is usually a good idea to scale the data for SVM training. # We are cheating a bit in this example in scaling all of the data, @@ -50,76 +115,85 @@ # just applying it on the test set. scaler = StandardScaler() - X = scaler.fit_transform(X) X_2d = scaler.fit_transform(X_2d) ############################################################################## -# Train classifier +# Train classifiers # # For an initial search, a logarithmic grid with basis # 10 is often helpful. Using a basis of 2, a finer # tuning can be achieved but at a much higher cost. -C_range = 10.0 ** np.arange(-2, 9) -gamma_range = 10.0 ** np.arange(-5, 4) +C_range = np.logspace(-2, 10, 13) +gamma_range = np.logspace(-9, 3, 13) param_grid = dict(gamma=gamma_range, C=C_range) +cv = StratifiedShuffleSplit(y, n_iter=5, test_size=0.2, random_state=42) +grid = GridSearchCV(SVC(), param_grid=param_grid, cv=cv) +grid.fit(X, y) -grid = GridSearchCV(SVC(), param_grid=param_grid, cv=StratifiedKFold(y=Y, k=3)) -grid.fit(X, Y) - -print("The best classifier is: ", grid.best_estimator_) +print("The best parameters are %s with a score of %0.2f" + % (grid.best_params_, grid.best_score_)) # Now we need to fit a classifier for all parameters in the 2d version # (we use a smaller set of parameters here because it takes a while to train) -C_2d_range = [1, 1e2, 1e4] + +C_2d_range = [1e-2, 1, 1e2] gamma_2d_range = [1e-1, 1, 1e1] classifiers = [] for C in C_2d_range: for gamma in gamma_2d_range: clf = SVC(C=C, gamma=gamma) - clf.fit(X_2d, Y_2d) + clf.fit(X_2d, y_2d) classifiers.append((C, gamma, clf)) ############################################################################## # visualization # # draw visualization of parameter effects -pl.figure(figsize=(8, 6)) -xx, yy = np.meshgrid(np.linspace(-5, 5, 200), np.linspace(-5, 5, 200)) + +plt.figure(figsize=(8, 6)) +xx, yy = np.meshgrid(np.linspace(-3, 3, 200), np.linspace(-3, 3, 200)) for (k, (C, gamma, clf)) in enumerate(classifiers): # evaluate decision function in a grid Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # visualize decision function for these parameters - pl.subplot(len(C_2d_range), len(gamma_2d_range), k + 1) - pl.title("gamma 10^%d, C 10^%d" % (np.log10(gamma), np.log10(C)), - size='medium') + plt.subplot(len(C_2d_range), len(gamma_2d_range), k + 1) + plt.title("gamma=10^%d, C=10^%d" % (np.log10(gamma), np.log10(C)), + size='medium') # visualize parameter's effect on decision function - pl.pcolormesh(xx, yy, -Z, cmap=pl.cm.jet) - pl.scatter(X_2d[:, 0], X_2d[:, 1], c=Y_2d, cmap=pl.cm.jet) - pl.xticks(()) - pl.yticks(()) - pl.axis('tight') + plt.pcolormesh(xx, yy, -Z, cmap=plt.cm.RdBu) + plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y_2d, cmap=plt.cm.RdBu_r) + plt.xticks(()) + plt.yticks(()) + plt.axis('tight') # plot the scores of the grid # grid_scores_ contains parameter settings and scores -score_dict = grid.grid_scores_ - # We extract just the scores -scores = [x[1] for x in score_dict] +scores = [x[1] for x in grid.grid_scores_] scores = np.array(scores).reshape(len(C_range), len(gamma_range)) -# draw heatmap of accuracy as a function of gamma and C -pl.figure(figsize=(8, 6)) -pl.subplots_adjust(left=0.05, right=0.95, bottom=0.15, top=0.95) -pl.imshow(scores, interpolation='nearest', cmap=pl.cm.spectral) -pl.xlabel('gamma') -pl.ylabel('C') -pl.colorbar() -pl.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45) -pl.yticks(np.arange(len(C_range)), C_range) - -pl.show() +# Draw heatmap of the validation accuracy as a function of gamma and C +# +# The score are encoded as colors with the hot colormap which varies from dark +# red to bright yellow. As the most interesting scores are all located in the +# 0.92 to 0.97 range we use a custom normalizer to set the mid-point to 0.92 so +# as to make it easier to visualize the small variations of score values in the +# interesting range while not brutally collapsing all the low score values to +# the same color. + +plt.figure(figsize=(8, 6)) +plt.subplots_adjust(left=.2, right=0.95, bottom=0.15, top=0.95) +plt.imshow(scores, interpolation='nearest', cmap=plt.cm.hot, + norm=MidpointNormalize(vmin=0.2, midpoint=0.92)) +plt.xlabel('gamma') +plt.ylabel('C') +plt.colorbar() +plt.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45) +plt.yticks(np.arange(len(C_range)), C_range) +plt.title('Validation accuracy') +plt.show() diff --git a/examples/svm/plot_separating_hyperplane.py b/examples/svm/plot_separating_hyperplane.py index 04014fee785ce..254368fb421d4 100644 --- a/examples/svm/plot_separating_hyperplane.py +++ b/examples/svm/plot_separating_hyperplane.py @@ -7,10 +7,10 @@ separable dataset using a Support Vector Machines classifier with linear kernel. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import svm # we create 40 separable points @@ -36,13 +36,13 @@ yy_up = a * xx + (b[1] - a * b[0]) # plot the line, the points, and the nearest vectors to the plane -pl.plot(xx, yy, 'k-') -pl.plot(xx, yy_down, 'k--') -pl.plot(xx, yy_up, 'k--') +plt.plot(xx, yy, 'k-') +plt.plot(xx, yy_down, 'k--') +plt.plot(xx, yy_up, 'k--') -pl.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], - s=80, facecolors='none') -pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired) +plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], + s=80, facecolors='none') +plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired) -pl.axis('tight') -pl.show() +plt.axis('tight') +plt.show() diff --git a/examples/svm/plot_separating_hyperplane_unbalanced.py b/examples/svm/plot_separating_hyperplane_unbalanced.py index 732738047570c..f7278004acfca 100644 --- a/examples/svm/plot_separating_hyperplane_unbalanced.py +++ b/examples/svm/plot_separating_hyperplane_unbalanced.py @@ -9,12 +9,27 @@ We first find the separating plane with a plain SVC and then plot (dashed) the separating hyperplane with automatically correction for unbalanced classes. + +.. currentmodule:: sklearn.linear_model + +.. note:: + + This example will also work by replacing ``SVC(kernel="linear")`` + with ``SGDClassifier(loss="hinge")``. Setting the ``loss`` parameter + of the :class:`SGDClassifier` equal to ``hinge`` will yield behaviour + such as that of a SVC with a linear kernel. + + For example try instead of the ``SVC``:: + + clf = SGDClassifier(n_iter=100, alpha=0.01) + """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import svm +#from sklearn.linear_model import SGDClassifier # we create 40 separable points rng = np.random.RandomState(0) @@ -43,10 +58,10 @@ wyy = wa * xx - wclf.intercept_[0] / ww[1] # plot separating hyperplanes and samples -h0 = pl.plot(xx, yy, 'k-', label='no weights') -h1 = pl.plot(xx, wyy, 'k--', label='with weights') -pl.scatter(X[:, 0], X[:, 1], c=y, cmap=pl.cm.Paired) -pl.legend() +h0 = plt.plot(xx, yy, 'k-', label='no weights') +h1 = plt.plot(xx, wyy, 'k--', label='with weights') +plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) +plt.legend() -pl.axis('tight') -pl.show() +plt.axis('tight') +plt.show() diff --git a/examples/svm/plot_svm_anova.py b/examples/svm/plot_svm_anova.py index e202fe57ad519..9ce225bf980e5 100644 --- a/examples/svm/plot_svm_anova.py +++ b/examples/svm/plot_svm_anova.py @@ -6,10 +6,10 @@ This example shows how to perform univariate feature before running a SVC (support vector classifier) to improve the classification scores. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import svm, datasets, feature_selection, cross_validation from sklearn.pipeline import Pipeline @@ -46,12 +46,12 @@ score_means.append(this_scores.mean()) score_stds.append(this_scores.std()) -pl.errorbar(percentiles, score_means, np.array(score_stds)) +plt.errorbar(percentiles, score_means, np.array(score_stds)) -pl.title( +plt.title( 'Performance of the SVM-Anova varying the percentile of features selected') -pl.xlabel('Percentile') -pl.ylabel('Prediction rate') +plt.xlabel('Percentile') +plt.ylabel('Prediction rate') -pl.axis('tight') -pl.show() +plt.axis('tight') +plt.show() diff --git a/examples/svm/plot_svm_iris.py b/examples/svm/plot_svm_iris.py deleted file mode 100644 index 59fde84b7595e..0000000000000 --- a/examples/svm/plot_svm_iris.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -""" -========================================================= -SVM-SVC (Support Vector Classification) -========================================================= -The classification application of the SVM is used below. The -`Iris `_ -dataset has been used for this example - -The decision boundaries, are shown with all the points in the training-set. - -""" -print __doc__ - - -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD - -import numpy as np -import pylab as pl -from sklearn import svm, datasets - -# import some data to play with -iris = datasets.load_iris() -X = iris.data[:, :2] # we only take the first two features. -Y = iris.target - -h = .02 # step size in the mesh - -clf = svm.SVC(C=1.0, kernel='linear') - -# we create an instance of SVM Classifier and fit the data. -clf.fit(X, Y) - -# Plot the decision boundary. For that, we will asign a color to each -# point in the mesh [x_min, m_max]x[y_min, y_max]. -x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 -y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 -xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) -Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) - -# Put the result into a color plot -Z = Z.reshape(xx.shape) -pl.figure(1, figsize=(4, 3)) -pl.pcolormesh(xx, yy, Z, cmap=pl.cm.Paired) - -# Plot also the training points -pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired) -pl.xlabel('Sepal length') -pl.ylabel('Sepal width') - -pl.xlim(xx.min(), xx.max()) -pl.ylim(yy.min(), yy.max()) -pl.xticks(()) -pl.yticks(()) - -pl.show() diff --git a/examples/svm/plot_svm_kernels.py b/examples/svm/plot_svm_kernels.py index 07fb87350d556..f0d06dd7968a6 100644 --- a/examples/svm/plot_svm_kernels.py +++ b/examples/svm/plot_svm_kernels.py @@ -5,20 +5,21 @@ ========================================================= SVM-Kernels ========================================================= + Three different types of SVM-Kernels are displayed below. The polynomial and RBF are especially useful when the -data-points are not linearly seperable. +data-points are not linearly separable. """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# License: BSD +# Code source: Gaël Varoquaux +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import svm @@ -39,8 +40,7 @@ (.5, -2.4), (.2, -2.3), (0, -2.7), - (1.3, 2.1), - ].T + (1.3, 2.1)].T Y = [0] * 8 + [1] * 8 # figure number @@ -52,14 +52,14 @@ clf.fit(X, Y) # plot the line, the points, and the nearest vectors to the plane - pl.figure(fignum, figsize=(4, 3)) - pl.clf() + plt.figure(fignum, figsize=(4, 3)) + plt.clf() - pl.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], - s=80, facecolors='none', zorder=10) - pl.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=pl.cm.Paired) + plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, + facecolors='none', zorder=10) + plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired) - pl.axis('tight') + plt.axis('tight') x_min = -3 x_max = 3 y_min = -3 @@ -70,16 +70,15 @@ # Put the result into a color plot Z = Z.reshape(XX.shape) - pl.figure(fignum, figsize=(4, 3)) - pl.pcolormesh(XX, YY, Z > 0, cmap=pl.cm.Paired) - pl.contour(XX, YY, Z, colors=['k', 'k', 'k'], - linestyles=['--', '-', '--'], - levels=[-.5, 0, .5]) + plt.figure(fignum, figsize=(4, 3)) + plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired) + plt.contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'], + levels=[-.5, 0, .5]) - pl.xlim(x_min, x_max) - pl.ylim(y_min, y_max) + plt.xlim(x_min, x_max) + plt.ylim(y_min, y_max) - pl.xticks(()) - pl.yticks(()) + plt.xticks(()) + plt.yticks(()) fignum = fignum + 1 -pl.show() +plt.show() diff --git a/examples/svm/plot_svm_margin.py b/examples/svm/plot_svm_margin.py index 80c98eff3c8f5..a999ea34d33e2 100644 --- a/examples/svm/plot_svm_margin.py +++ b/examples/svm/plot_svm_margin.py @@ -6,24 +6,24 @@ SVM Margins Example ========================================================= The plots below illustrate the effect the parameter `C` has -on the seperation line. A large value of `C` basically tells +on the separation line. A large value of `C` basically tells our model that we do not have that much faith in our data's -distrubution, and will only consider points close to line -of seperation. +distribution, and will only consider points close to line +of separation. A small value of `C` includes more/all the observations, allowing the margins to be calculated using all the data in the area. """ -print __doc__ +print(__doc__) -# Code source: Gael Varoqueux -# Modified for Documentation merge by Jaques Grobler -# License: BSD +# Code source: Gaël Varoquaux +# Modified for documentation by Jaques Grobler +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import svm # we create 40 separable points @@ -35,9 +35,9 @@ fignum = 1 # fit the model -for name, penality in (('unreg', 1), ('reg', 0.05)): +for name, penalty in (('unreg', 1), ('reg', 0.05)): - clf = svm.SVC(kernel='linear', C=penality) + clf = svm.SVC(kernel='linear', C=penalty) clf.fit(X, Y) # get the separating hyperplane @@ -53,17 +53,17 @@ yy_up = yy - a * margin # plot the line, the points, and the nearest vectors to the plane - pl.figure(fignum, figsize=(4, 3)) - pl.clf() - pl.plot(xx, yy, 'k-') - pl.plot(xx, yy_down, 'k--') - pl.plot(xx, yy_up, 'k--') + plt.figure(fignum, figsize=(4, 3)) + plt.clf() + plt.plot(xx, yy, 'k-') + plt.plot(xx, yy_down, 'k--') + plt.plot(xx, yy_up, 'k--') - pl.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], - s=80, facecolors='none', zorder=10) - pl.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=pl.cm.Paired) + plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, + facecolors='none', zorder=10) + plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired) - pl.axis('tight') + plt.axis('tight') x_min = -4.8 x_max = 4.2 y_min = -6 @@ -74,14 +74,14 @@ # Put the result into a color plot Z = Z.reshape(XX.shape) - pl.figure(fignum, figsize=(4, 3)) - pl.pcolormesh(XX, YY, Z, cmap=pl.cm.Paired) + plt.figure(fignum, figsize=(4, 3)) + plt.pcolormesh(XX, YY, Z, cmap=plt.cm.Paired) - pl.xlim(x_min, x_max) - pl.ylim(y_min, y_max) + plt.xlim(x_min, x_max) + plt.ylim(y_min, y_max) - pl.xticks(()) - pl.yticks(()) + plt.xticks(()) + plt.yticks(()) fignum = fignum + 1 -pl.show() +plt.show() diff --git a/examples/svm/plot_svm_nonlinear.py b/examples/svm/plot_svm_nonlinear.py index b9d84d00488a6..672a19d30705b 100644 --- a/examples/svm/plot_svm_nonlinear.py +++ b/examples/svm/plot_svm_nonlinear.py @@ -9,10 +9,10 @@ The color map illustrates the decision function learn by the SVC. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import svm xx, yy = np.meshgrid(np.linspace(-3, 3, 500), @@ -29,13 +29,13 @@ Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) -pl.imshow(Z, interpolation='nearest', - extent=(xx.min(), xx.max(), yy.min(), yy.max()), - aspect='auto', origin='lower', cmap=pl.cm.PuOr_r) -contours = pl.contour(xx, yy, Z, levels=[0], linewidths=2, - linetypes='--') -pl.scatter(X[:, 0], X[:, 1], s=30, c=Y, cmap=pl.cm.Paired) -pl.xticks(()) -pl.yticks(()) -pl.axis([-3, 3, -3, 3]) -pl.show() +plt.imshow(Z, interpolation='nearest', + extent=(xx.min(), xx.max(), yy.min(), yy.max()), aspect='auto', + origin='lower', cmap=plt.cm.PuOr_r) +contours = plt.contour(xx, yy, Z, levels=[0], linewidths=2, + linetypes='--') +plt.scatter(X[:, 0], X[:, 1], s=30, c=Y, cmap=plt.cm.Paired) +plt.xticks(()) +plt.yticks(()) +plt.axis([-3, 3, -3, 3]) +plt.show() diff --git a/examples/svm/plot_svm_regression.py b/examples/svm/plot_svm_regression.py index 58120eb3fddcb..a507bce38ec2a 100644 --- a/examples/svm/plot_svm_regression.py +++ b/examples/svm/plot_svm_regression.py @@ -3,16 +3,17 @@ Support Vector Regression (SVR) using linear and non-linear kernels =================================================================== -Toy example of 1D regression using linear, polynominial and RBF -kernels. +Toy example of 1D regression using linear, polynomial and RBF kernels. """ -print __doc__ +print(__doc__) -############################################################################### -# Generate sample data import numpy as np +from sklearn.svm import SVR +import matplotlib.pyplot as plt +############################################################################### +# Generate sample data X = np.sort(5 * np.random.rand(40, 1), axis=0) y = np.sin(X).ravel() @@ -22,8 +23,6 @@ ############################################################################### # Fit regression model -from sklearn.svm import SVR - svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1) svr_lin = SVR(kernel='linear', C=1e3) svr_poly = SVR(kernel='poly', C=1e3, degree=2) @@ -33,14 +32,13 @@ ############################################################################### # look at the results -import pylab as pl -pl.scatter(X, y, c='k', label='data') -pl.hold('on') -pl.plot(X, y_rbf, c='g', label='RBF model') -pl.plot(X, y_lin, c='r', label='Linear model') -pl.plot(X, y_poly, c='b', label='Polynomial model') -pl.xlabel('data') -pl.ylabel('target') -pl.title('Support Vector Regression') -pl.legend() -pl.show() +plt.scatter(X, y, c='k', label='data') +plt.hold('on') +plt.plot(X, y_rbf, c='g', label='RBF model') +plt.plot(X, y_lin, c='r', label='Linear model') +plt.plot(X, y_poly, c='b', label='Polynomial model') +plt.xlabel('data') +plt.ylabel('target') +plt.title('Support Vector Regression') +plt.legend() +plt.show() diff --git a/examples/svm/plot_svm_scale_c.py b/examples/svm/plot_svm_scale_c.py index 6b926c4cea8ab..c977d3d9b997d 100644 --- a/examples/svm/plot_svm_scale_c.py +++ b/examples/svm/plot_svm_scale_c.py @@ -1,7 +1,7 @@ """ -========================================================================= -Support Vector Classification (SVC): scaling the regularization parameter -========================================================================= +============================================== +Scaling the regularization parameter for SVCs +============================================== The following example illustrates the effect of scaling the regularization parameter when using :ref:`svm` for @@ -29,28 +29,28 @@ When using, for example, :ref:`cross validation `, to set the amount of regularization with `C`, there will be a different amount of samples between the main problem and the smaller problems -withing the folds of the cross validation. +within the folds of the cross validation. -Since our loss function is dependant on the amount of samples, the latter +Since our loss function is dependent on the amount of samples, the latter will influence the selected value of `C`. The question that arises is `How do we optimally adjust C to account for the different amount of training samples?` The figures below are used to illustrate the effect of scaling our `C` to compensate for the change in the number of samples, in the -case of using an `L1` penalty, as well as the `L2` penalty. +case of using an `l1` penalty, as well as the `l2` penalty. -L1-penalty case +l1-penalty case ----------------- -In the `L1` case, theory says that prediction consistency +In the `l1` case, theory says that prediction consistency (i.e. that under given hypothesis, the estimator learned predicts as well as a model knowing the true distribution) -is not possible because of the bias of the `L1`. It does say, however, +is not possible because of the bias of the `l1`. It does say, however, that model consistency, in terms of finding the right set of non-zero parameters as well as their signs, can be achieved by scaling `C1`. -L2-penalty case +l2-penalty case ----------------- The theory says that in order to achieve prediction consistency, the penalty parameter should be kept constant @@ -63,29 +63,29 @@ corresponding cross-validation scores on the `y-axis`, for several different fractions of a generated data-set. -In the `L1` penalty case, the cross-validation-error correlates best with +In the `l1` penalty case, the cross-validation-error correlates best with the test-error, when scaling our `C` with the number of samples, `n`, which can be seen in the first figure. -For the `L2` penalty case, the best result comes from the case where `C` +For the `l2` penalty case, the best result comes from the case where `C` is not scaled. .. topic:: Note: - Two seperate datasets are used for the two different plots. The reason - behind this is the `L1` case works better on sparse data, while `L2` + Two separate datasets are used for the two different plots. The reason + behind this is the `l1` case works better on sparse data, while `l2` is better suited to the non-sparse case. """ -print __doc__ +print(__doc__) # Author: Andreas Mueller # Jaques Grobler -# License: BSD +# License: BSD 3 clause import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.svm import LinearSVC from sklearn.cross_validation import ShuffleSplit @@ -100,19 +100,20 @@ n_samples = 100 n_features = 300 -# L1 data (only 5 informative features) +# l1 data (only 5 informative features) X_1, y_1 = datasets.make_classification(n_samples=n_samples, - n_features=n_features, n_informative=5, random_state=1) + n_features=n_features, n_informative=5, + random_state=1) -# L2 data: non sparse, but less features +# l2 data: non sparse, but less features y_2 = np.sign(.5 - rnd.rand(n_samples)) X_2 = rnd.randn(n_samples, n_features / 5) + y_2[:, np.newaxis] X_2 += 5 * rnd.randn(n_samples, n_features / 5) -clf_sets = [(LinearSVC(penalty='L1', loss='L2', dual=False, +clf_sets = [(LinearSVC(penalty='l1', loss='squared_hinge', dual=False, tol=1e-3), np.logspace(-2.3, -1.3, 10), X_1, y_1), - (LinearSVC(penalty='L2', loss='L2', dual=True, + (LinearSVC(penalty='l2', loss='squared_hinge', dual=True, tol=1e-4), np.logspace(-4.5, -2, 10), X_2, y_2)] @@ -120,15 +121,15 @@ for fignum, (clf, cs, X, y) in enumerate(clf_sets): # set up the plot for each regressor - pl.figure(fignum, figsize=(9, 10)) + plt.figure(fignum, figsize=(9, 10)) for k, train_size in enumerate(np.linspace(0.3, 0.7, 3)[::-1]): param_grid = dict(C=cs) # To get nice curve, we need a large number of iterations to # reduce the variance grid = GridSearchCV(clf, refit=False, param_grid=param_grid, - cv=ShuffleSplit(n=n_samples, train_size=train_size, - n_iterations=250, random_state=1)) + cv=ShuffleSplit(n=n_samples, train_size=train_size, + n_iter=250, random_state=1)) grid.fit(X, y) scores = [x[1] for x in grid.grid_scores_] @@ -137,14 +138,14 @@ ] for subplotnum, (scaler, name) in enumerate(scales): - pl.subplot(2, 1, subplotnum + 1) - pl.xlabel('C') - pl.ylabel('CV Score') + plt.subplot(2, 1, subplotnum + 1) + plt.xlabel('C') + plt.ylabel('CV Score') grid_cs = cs * float(scaler) # scale the C's - pl.semilogx(grid_cs, scores, label="fraction %.2f" % - train_size) - pl.title('scaling=%s, penalty=%s, loss=%s' % - (name, clf.penalty, clf.loss)) + plt.semilogx(grid_cs, scores, label="fraction %.2f" % + train_size) + plt.title('scaling=%s, penalty=%s, loss=%s' % + (name, clf.penalty, clf.loss)) - pl.legend(loc="best") -pl.show() + plt.legend(loc="best") +plt.show() diff --git a/examples/svm/plot_weighted_samples.py b/examples/svm/plot_weighted_samples.py index b013733820eed..ac9207838b034 100644 --- a/examples/svm/plot_weighted_samples.py +++ b/examples/svm/plot_weighted_samples.py @@ -5,34 +5,59 @@ Plot decision function of a weighted dataset, where the size of points is proportional to its weight. + +The sample weighting rescales the C parameter, which means that the classifier +puts more emphasis on getting these points right. The effect might often be +subtle. +To emphasis the effect here, we particularly weight outliers, making the +deformation of the decision boundary very visible. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn import svm + +def plot_decision_function(classifier, sample_weight, axis, title): + # plot the decision function + xx, yy = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500)) + + Z = classifier.decision_function(np.c_[xx.ravel(), yy.ravel()]) + Z = Z.reshape(xx.shape) + + # plot the line, the points, and the nearest vectors to the plane + axis.contourf(xx, yy, Z, alpha=0.75, cmap=plt.cm.bone) + axis.scatter(X[:, 0], X[:, 1], c=Y, s=100 * sample_weight, alpha=0.9, + cmap=plt.cm.bone) + + axis.axis('off') + axis.set_title(title) + + # we create 20 points np.random.seed(0) X = np.r_[np.random.randn(10, 2) + [1, 1], np.random.randn(10, 2)] Y = [1] * 10 + [-1] * 10 -sample_weight = 100 * np.abs(np.random.randn(20)) -# and assign a bigger weight to the last 10 samples -sample_weight[:10] *= 10 +sample_weight_last_ten = abs(np.random.randn(len(X))) +sample_weight_constant = np.ones(len(X)) +# and bigger weights to some outliers +sample_weight_last_ten[15:] *= 5 +sample_weight_last_ten[9] *= 15 -# # fit the model -clf = svm.SVC() -clf.fit(X, Y, sample_weight=sample_weight) +# for reference, first fit without class weights -# plot the decision function -xx, yy = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500)) +# fit the model +clf_weights = svm.SVC() +clf_weights.fit(X, Y, sample_weight=sample_weight_last_ten) -Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) -Z = Z.reshape(xx.shape) +clf_no_weights = svm.SVC() +clf_no_weights.fit(X, Y) -# plot the line, the points, and the nearest vectors to the plane -pl.contourf(xx, yy, Z, alpha=0.75, cmap=pl.cm.bone) -pl.scatter(X[:, 0], X[:, 1], c=Y, s=sample_weight, alpha=0.9, cmap=pl.cm.bone) +fig, axes = plt.subplots(1, 2, figsize=(14, 6)) +plot_decision_function(clf_no_weights, sample_weight_constant, axes[0], + "Constant weights") +plot_decision_function(clf_weights, sample_weight_last_ten, axes[1], + "Modified weights") -pl.axis('off') -pl.show() +plt.show() diff --git a/examples/text/README.txt b/examples/text/README.txt new file mode 100644 index 0000000000000..97626f818ec99 --- /dev/null +++ b/examples/text/README.txt @@ -0,0 +1,6 @@ +.. _text_examples: + +Working with text documents +---------------------------- + +Examples concerning the :mod:`sklearn.feature_extraction.text` module. diff --git a/examples/text/document_classification_20newsgroups.py b/examples/text/document_classification_20newsgroups.py new file mode 100644 index 0000000000000..94b21e1b52a49 --- /dev/null +++ b/examples/text/document_classification_20newsgroups.py @@ -0,0 +1,313 @@ +""" +====================================================== +Classification of text documents using sparse features +====================================================== + +This is an example showing how scikit-learn can be used to classify documents +by topics using a bag-of-words approach. This example uses a scipy.sparse +matrix to store the features and demonstrates various classifiers that can +efficiently handle sparse matrices. + +The dataset used in this example is the 20 newsgroups dataset. It will be +automatically downloaded, then cached. + +The bar plot indicates the accuracy, training time (normalized) and test time +(normalized) of each classifier. + +""" + +# Author: Peter Prettenhofer +# Olivier Grisel +# Mathieu Blondel +# Lars Buitinck +# License: BSD 3 clause + +from __future__ import print_function + +import logging +import numpy as np +from optparse import OptionParser +import sys +from time import time +import matplotlib.pyplot as plt + +from sklearn.datasets import fetch_20newsgroups +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.feature_extraction.text import HashingVectorizer +from sklearn.feature_selection import SelectKBest, chi2 +from sklearn.linear_model import RidgeClassifier +from sklearn.pipeline import Pipeline +from sklearn.svm import LinearSVC +from sklearn.linear_model import SGDClassifier +from sklearn.linear_model import Perceptron +from sklearn.linear_model import PassiveAggressiveClassifier +from sklearn.naive_bayes import BernoulliNB, MultinomialNB +from sklearn.neighbors import KNeighborsClassifier +from sklearn.neighbors import NearestCentroid +from sklearn.ensemble import RandomForestClassifier +from sklearn.utils.extmath import density +from sklearn import metrics + + +# Display progress logs on stdout +logging.basicConfig(level=logging.INFO, + format='%(asctime)s %(levelname)s %(message)s') + + +# parse commandline arguments +op = OptionParser() +op.add_option("--report", + action="http://github.com/store_true", dest="print_report", + help="Print a detailed classification report.") +op.add_option("--chi2_select", + action="http://github.com/store", type="int", dest="select_chi2", + help="Select some number of features using a chi-squared test") +op.add_option("--confusion_matrix", + action="http://github.com/store_true", dest="print_cm", + help="Print the confusion matrix.") +op.add_option("--top10", + action="http://github.com/store_true", dest="print_top10", + help="Print ten most discriminative terms per class" + " for every classifier.") +op.add_option("--all_categories", + action="http://github.com/store_true", dest="all_categories", + help="Whether to use all categories or not.") +op.add_option("--use_hashing", + action="http://github.com/store_true", + help="Use a hashing vectorizer.") +op.add_option("--n_features", + action="http://github.com/store", type=int, default=2 ** 16, + help="n_features when using the hashing vectorizer.") +op.add_option("--filtered", + action="http://github.com/store_true", + help="Remove newsgroup information that is easily overfit: " + "headers, signatures, and quoting.") + +(opts, args) = op.parse_args() +if len(args) > 0: + op.error("this script takes no arguments.") + sys.exit(1) + +print(__doc__) +op.print_help() +print() + + +############################################################################### +# Load some categories from the training set +if opts.all_categories: + categories = None +else: + categories = [ + 'alt.atheism', + 'talk.religion.misc', + 'comp.graphics', + 'sci.space', + ] + +if opts.filtered: + remove = ('headers', 'footers', 'quotes') +else: + remove = () + +print("Loading 20 newsgroups dataset for categories:") +print(categories if categories else "all") + +data_train = fetch_20newsgroups(subset='train', categories=categories, + shuffle=True, random_state=42, + remove=remove) + +data_test = fetch_20newsgroups(subset='test', categories=categories, + shuffle=True, random_state=42, + remove=remove) +print('data loaded') + +categories = data_train.target_names # for case categories == None + + +def size_mb(docs): + return sum(len(s.encode('utf-8')) for s in docs) / 1e6 + +data_train_size_mb = size_mb(data_train.data) +data_test_size_mb = size_mb(data_test.data) + +print("%d documents - %0.3fMB (training set)" % ( + len(data_train.data), data_train_size_mb)) +print("%d documents - %0.3fMB (test set)" % ( + len(data_test.data), data_test_size_mb)) +print("%d categories" % len(categories)) +print() + +# split a training set and a test set +y_train, y_test = data_train.target, data_test.target + +print("Extracting features from the training data using a sparse vectorizer") +t0 = time() +if opts.use_hashing: + vectorizer = HashingVectorizer(stop_words='english', non_negative=True, + n_features=opts.n_features) + X_train = vectorizer.transform(data_train.data) +else: + vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, + stop_words='english') + X_train = vectorizer.fit_transform(data_train.data) +duration = time() - t0 +print("done in %fs at %0.3fMB/s" % (duration, data_train_size_mb / duration)) +print("n_samples: %d, n_features: %d" % X_train.shape) +print() + +print("Extracting features from the test data using the same vectorizer") +t0 = time() +X_test = vectorizer.transform(data_test.data) +duration = time() - t0 +print("done in %fs at %0.3fMB/s" % (duration, data_test_size_mb / duration)) +print("n_samples: %d, n_features: %d" % X_test.shape) +print() + +# mapping from integer feature name to original token string +if opts.use_hashing: + feature_names = None +else: + feature_names = vectorizer.get_feature_names() + +if opts.select_chi2: + print("Extracting %d best features by a chi-squared test" % + opts.select_chi2) + t0 = time() + ch2 = SelectKBest(chi2, k=opts.select_chi2) + X_train = ch2.fit_transform(X_train, y_train) + X_test = ch2.transform(X_test) + if feature_names: + # keep selected feature names + feature_names = [feature_names[i] for i + in ch2.get_support(indices=True)] + print("done in %fs" % (time() - t0)) + print() + +if feature_names: + feature_names = np.asarray(feature_names) + + +def trim(s): + """Trim string to fit on terminal (assuming 80-column display)""" + return s if len(s) <= 80 else s[:77] + "..." + + +############################################################################### +# Benchmark classifiers +def benchmark(clf): + print('_' * 80) + print("Training: ") + print(clf) + t0 = time() + clf.fit(X_train, y_train) + train_time = time() - t0 + print("train time: %0.3fs" % train_time) + + t0 = time() + pred = clf.predict(X_test) + test_time = time() - t0 + print("test time: %0.3fs" % test_time) + + score = metrics.accuracy_score(y_test, pred) + print("accuracy: %0.3f" % score) + + if hasattr(clf, 'coef_'): + print("dimensionality: %d" % clf.coef_.shape[1]) + print("density: %f" % density(clf.coef_)) + + if opts.print_top10 and feature_names is not None: + print("top 10 keywords per class:") + for i, category in enumerate(categories): + top10 = np.argsort(clf.coef_[i])[-10:] + print(trim("%s: %s" + % (category, " ".join(feature_names[top10])))) + print() + + if opts.print_report: + print("classification report:") + print(metrics.classification_report(y_test, pred, + target_names=categories)) + + if opts.print_cm: + print("confusion matrix:") + print(metrics.confusion_matrix(y_test, pred)) + + print() + clf_descr = str(clf).split('(')[0] + return clf_descr, score, train_time, test_time + + +results = [] +for clf, name in ( + (RidgeClassifier(tol=1e-2, solver="lsqr"), "Ridge Classifier"), + (Perceptron(n_iter=50), "Perceptron"), + (PassiveAggressiveClassifier(n_iter=50), "Passive-Aggressive"), + (KNeighborsClassifier(n_neighbors=10), "kNN"), + (RandomForestClassifier(n_estimators=100), "Random forest")): + print('=' * 80) + print(name) + results.append(benchmark(clf)) + +for penalty in ["l2", "l1"]: + print('=' * 80) + print("%s penalty" % penalty.upper()) + # Train Liblinear model + results.append(benchmark(LinearSVC(loss='l2', penalty=penalty, + dual=False, tol=1e-3))) + + # Train SGD model + results.append(benchmark(SGDClassifier(alpha=.0001, n_iter=50, + penalty=penalty))) + +# Train SGD with Elastic Net penalty +print('=' * 80) +print("Elastic-Net penalty") +results.append(benchmark(SGDClassifier(alpha=.0001, n_iter=50, + penalty="elasticnet"))) + +# Train NearestCentroid without threshold +print('=' * 80) +print("NearestCentroid (aka Rocchio classifier)") +results.append(benchmark(NearestCentroid())) + +# Train sparse Naive Bayes classifiers +print('=' * 80) +print("Naive Bayes") +results.append(benchmark(MultinomialNB(alpha=.01))) +results.append(benchmark(BernoulliNB(alpha=.01))) + +print('=' * 80) +print("LinearSVC with L1-based feature selection") +# The smaller C, the stronger the regularization. +# The more regularization, the more sparsity. +results.append(benchmark(Pipeline([ + ('feature_selection', LinearSVC(penalty="l1", dual=False, tol=1e-3)), + ('classification', LinearSVC()) +]))) + +# make some plots + +indices = np.arange(len(results)) + +results = [[x[i] for x in results] for i in range(4)] + +clf_names, score, training_time, test_time = results +training_time = np.array(training_time) / np.max(training_time) +test_time = np.array(test_time) / np.max(test_time) + +plt.figure(figsize=(12, 8)) +plt.title("Score") +plt.barh(indices, score, .2, label="score", color='r') +plt.barh(indices + .3, training_time, .2, label="training time", color='g') +plt.barh(indices + .6, test_time, .2, label="test time", color='b') +plt.yticks(()) +plt.legend(loc='best') +plt.subplots_adjust(left=.25) +plt.subplots_adjust(top=.95) +plt.subplots_adjust(bottom=.05) + +for i, c in zip(indices, clf_names): + plt.text(-.3, i, c) + +plt.show() diff --git a/examples/text/document_clustering.py b/examples/text/document_clustering.py new file mode 100644 index 0000000000000..51ae37b6d5913 --- /dev/null +++ b/examples/text/document_clustering.py @@ -0,0 +1,210 @@ +""" +======================================= +Clustering text documents using k-means +======================================= + +This is an example showing how the scikit-learn can be used to cluster +documents by topics using a bag-of-words approach. This example uses +a scipy.sparse matrix to store the features instead of standard numpy arrays. + +Two feature extraction methods can be used in this example: + + - TfidfVectorizer uses a in-memory vocabulary (a python dict) to map the most + frequent words to features indices and hence compute a word occurrence + frequency (sparse) matrix. The word frequencies are then reweighted using + the Inverse Document Frequency (IDF) vector collected feature-wise over + the corpus. + + - HashingVectorizer hashes word occurrences to a fixed dimensional space, + possibly with collisions. The word count vectors are then normalized to + each have l2-norm equal to one (projected to the euclidean unit-ball) which + seems to be important for k-means to work in high dimensional space. + + HashingVectorizer does not provide IDF weighting as this is a stateless + model (the fit method does nothing). When IDF weighting is needed it can + be added by pipelining its output to a TfidfTransformer instance. + +Two algorithms are demoed: ordinary k-means and its more scalable cousin +minibatch k-means. + +It can be noted that k-means (and minibatch k-means) are very sensitive to +feature scaling and that in this case the IDF weighting helps improve the +quality of the clustering by quite a lot as measured against the "ground truth" +provided by the class label assignments of the 20 newsgroups dataset. + +This improvement is not visible in the Silhouette Coefficient which is small +for both as this measure seem to suffer from the phenomenon called +"Concentration of Measure" or "Curse of Dimensionality" for high dimensional +datasets such as text data. Other measures such as V-measure and Adjusted Rand +Index are information theoretic based evaluation scores: as they are only based +on cluster assignments rather than distances, hence not affected by the curse +of dimensionality. + +Note: as k-means is optimizing a non-convex objective function, it will likely +end up in a local optimum. Several runs with independent random init might be +necessary to get a good convergence. + +""" + +# Author: Peter Prettenhofer +# Lars Buitinck +# License: BSD 3 clause + +from __future__ import print_function + +from sklearn.datasets import fetch_20newsgroups +from sklearn.decomposition import TruncatedSVD +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.feature_extraction.text import HashingVectorizer +from sklearn.feature_extraction.text import TfidfTransformer +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import Normalizer +from sklearn import metrics + +from sklearn.cluster import KMeans, MiniBatchKMeans + +import logging +from optparse import OptionParser +import sys +from time import time + +import numpy as np + + +# Display progress logs on stdout +logging.basicConfig(level=logging.INFO, + format='%(asctime)s %(levelname)s %(message)s') + +# parse commandline arguments +op = OptionParser() +op.add_option("--lsa", + dest="n_components", type="int", + help="Preprocess documents with latent semantic analysis.") +op.add_option("--no-minibatch", + action="http://github.com/store_false", dest="minibatch", default=True, + help="Use ordinary k-means algorithm (in batch mode).") +op.add_option("--no-idf", + action="http://github.com/store_false", dest="use_idf", default=True, + help="Disable Inverse Document Frequency feature weighting.") +op.add_option("--use-hashing", + action="http://github.com/store_true", default=False, + help="Use a hashing feature vectorizer") +op.add_option("--n-features", type=int, default=10000, + help="Maximum number of features (dimensions)" + " to extract from text.") +op.add_option("--verbose", + action="http://github.com/store_true", dest="verbose", default=False, + help="Print progress reports inside k-means algorithm.") + +print(__doc__) +op.print_help() + +(opts, args) = op.parse_args() +if len(args) > 0: + op.error("this script takes no arguments.") + sys.exit(1) + + +############################################################################### +# Load some categories from the training set +categories = [ + 'alt.atheism', + 'talk.religion.misc', + 'comp.graphics', + 'sci.space', +] +# Uncomment the following to do the analysis on all the categories +#categories = None + +print("Loading 20 newsgroups dataset for categories:") +print(categories) + +dataset = fetch_20newsgroups(subset='all', categories=categories, + shuffle=True, random_state=42) + +print("%d documents" % len(dataset.data)) +print("%d categories" % len(dataset.target_names)) +print() + +labels = dataset.target +true_k = np.unique(labels).shape[0] + +print("Extracting features from the training dataset using a sparse vectorizer") +t0 = time() +if opts.use_hashing: + if opts.use_idf: + # Perform an IDF normalization on the output of HashingVectorizer + hasher = HashingVectorizer(n_features=opts.n_features, + stop_words='english', non_negative=True, + norm=None, binary=False) + vectorizer = make_pipeline(hasher, TfidfTransformer()) + else: + vectorizer = HashingVectorizer(n_features=opts.n_features, + stop_words='english', + non_negative=False, norm='l2', + binary=False) +else: + vectorizer = TfidfVectorizer(max_df=0.5, max_features=opts.n_features, + min_df=2, stop_words='english', + use_idf=opts.use_idf) +X = vectorizer.fit_transform(dataset.data) + +print("done in %fs" % (time() - t0)) +print("n_samples: %d, n_features: %d" % X.shape) +print() + +if opts.n_components: + print("Performing dimensionality reduction using LSA") + t0 = time() + # Vectorizer results are normalized, which makes KMeans behave as + # spherical k-means for better results. Since LSA/SVD results are + # not normalized, we have to redo the normalization. + svd = TruncatedSVD(opts.n_components) + lsa = make_pipeline(svd, Normalizer(copy=False)) + + X = lsa.fit_transform(X) + + print("done in %fs" % (time() - t0)) + + explained_variance = svd.explained_variance_ratio_.sum() + print("Explained variance of the SVD step: {}%".format( + int(explained_variance * 100))) + + print() + + +############################################################################### +# Do the actual clustering + +if opts.minibatch: + km = MiniBatchKMeans(n_clusters=true_k, init='k-means++', n_init=1, + init_size=1000, batch_size=1000, verbose=opts.verbose) +else: + km = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1, + verbose=opts.verbose) + +print("Clustering sparse data with %s" % km) +t0 = time() +km.fit(X) +print("done in %0.3fs" % (time() - t0)) +print() + +print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels, km.labels_)) +print("Completeness: %0.3f" % metrics.completeness_score(labels, km.labels_)) +print("V-measure: %0.3f" % metrics.v_measure_score(labels, km.labels_)) +print("Adjusted Rand-Index: %.3f" + % metrics.adjusted_rand_score(labels, km.labels_)) +print("Silhouette Coefficient: %0.3f" + % metrics.silhouette_score(X, km.labels_, sample_size=1000)) + +print() + +if not (opts.n_components or opts.use_hashing): + print("Top terms per cluster:") + order_centroids = km.cluster_centers_.argsort()[:, ::-1] + terms = vectorizer.get_feature_names() + for i in range(true_k): + print("Cluster %d:" % i, end='') + for ind in order_centroids[i, :10]: + print(' %s' % terms[ind], end='') + print() diff --git a/examples/text/hashing_vs_dict_vectorizer.py b/examples/text/hashing_vs_dict_vectorizer.py new file mode 100644 index 0000000000000..7981d7d2b9042 --- /dev/null +++ b/examples/text/hashing_vs_dict_vectorizer.py @@ -0,0 +1,111 @@ +""" +=========================================== +FeatureHasher and DictVectorizer Comparison +=========================================== + +Compares FeatureHasher and DictVectorizer by using both to vectorize +text documents. + +The example demonstrates syntax and speed only; it doesn't actually do +anything useful with the extracted vectors. See the example scripts +{document_classification_20newsgroups,clustering}.py for actual learning +on text documents. + +A discrepancy between the number of terms reported for DictVectorizer and +for FeatureHasher is to be expected due to hash collisions. +""" + +# Author: Lars Buitinck +# License: BSD 3 clause + +from __future__ import print_function +from collections import defaultdict +import re +import sys +from time import time + +import numpy as np + +from sklearn.datasets import fetch_20newsgroups +from sklearn.feature_extraction import DictVectorizer, FeatureHasher + + +def n_nonzero_columns(X): + """Returns the number of non-zero columns in a CSR matrix X.""" + return len(np.unique(X.nonzero()[1])) + + +def tokens(doc): + """Extract tokens from doc. + + This uses a simple regex to break strings into tokens. For a more + principled approach, see CountVectorizer or TfidfVectorizer. + """ + return (tok.lower() for tok in re.findall(r"\w+", doc)) + + +def token_freqs(doc): + """Extract a dict mapping tokens from doc to their frequencies.""" + freq = defaultdict(int) + for tok in tokens(doc): + freq[tok] += 1 + return freq + + +categories = [ + 'alt.atheism', + 'comp.graphics', + 'comp.sys.ibm.pc.hardware', + 'misc.forsale', + 'rec.autos', + 'sci.space', + 'talk.religion.misc', +] +# Uncomment the following line to use a larger set (11k+ documents) +#categories = None + +print(__doc__) +print("Usage: %s [n_features_for_hashing]" % sys.argv[0]) +print(" The default number of features is 2**18.") +print() + +try: + n_features = int(sys.argv[1]) +except IndexError: + n_features = 2 ** 18 +except ValueError: + print("not a valid number of features: %r" % sys.argv[1]) + sys.exit(1) + + +print("Loading 20 newsgroups training data") +raw_data = fetch_20newsgroups(subset='train', categories=categories).data +data_size_mb = sum(len(s.encode('utf-8')) for s in raw_data) / 1e6 +print("%d documents - %0.3fMB" % (len(raw_data), data_size_mb)) +print() + +print("DictVectorizer") +t0 = time() +vectorizer = DictVectorizer() +vectorizer.fit_transform(token_freqs(d) for d in raw_data) +duration = time() - t0 +print("done in %fs at %0.3fMB/s" % (duration, data_size_mb / duration)) +print("Found %d unique terms" % len(vectorizer.get_feature_names())) +print() + +print("FeatureHasher on frequency dicts") +t0 = time() +hasher = FeatureHasher(n_features=n_features) +X = hasher.transform(token_freqs(d) for d in raw_data) +duration = time() - t0 +print("done in %fs at %0.3fMB/s" % (duration, data_size_mb / duration)) +print("Found %d unique terms" % n_nonzero_columns(X)) +print() + +print("FeatureHasher on raw tokens") +t0 = time() +hasher = FeatureHasher(n_features=n_features, input_type="string") +X = hasher.transform(tokens(d) for d in raw_data) +duration = time() - t0 +print("done in %fs at %0.3fMB/s" % (duration, data_size_mb / duration)) +print("Found %d unique terms" % n_nonzero_columns(X)) diff --git a/examples/mlcomp_sparse_document_classification.py b/examples/text/mlcomp_sparse_document_classification.py similarity index 65% rename from examples/mlcomp_sparse_document_classification.py rename to examples/text/mlcomp_sparse_document_classification.py index 9744132d49c7a..c1d2631453d9c 100644 --- a/examples/mlcomp_sparse_document_classification.py +++ b/examples/text/mlcomp_sparse_document_classification.py @@ -33,10 +33,11 @@ % ipython examples/mlcomp_sparse_document_classification.py """ -print __doc__ # Author: Olivier Grisel -# License: Simplified BSD +# License: BSD 3 clause + +from __future__ import print_function from time import time import sys @@ -53,70 +54,71 @@ from sklearn.naive_bayes import MultinomialNB +print(__doc__) + if 'MLCOMP_DATASETS_HOME' not in os.environ: - print "MLCOMP_DATASETS_HOME not set; please follow the above instructions" + print("MLCOMP_DATASETS_HOME not set; please follow the above instructions") sys.exit(0) # Load the training set -print "Loading 20 newsgroups training set... " +print("Loading 20 newsgroups training set... ") news_train = load_mlcomp('20news-18828', 'train') -print news_train.DESCR -print "%d documents" % len(news_train.filenames) -print "%d categories" % len(news_train.target_names) +print(news_train.DESCR) +print("%d documents" % len(news_train.filenames)) +print("%d categories" % len(news_train.target_names)) -print "Extracting features from the dataset using a sparse vectorizer" +print("Extracting features from the dataset using a sparse vectorizer") t0 = time() -vectorizer = TfidfVectorizer(charset='latin1') +vectorizer = TfidfVectorizer(encoding='latin1') X_train = vectorizer.fit_transform((open(f).read() for f in news_train.filenames)) -print "done in %fs" % (time() - t0) -print "n_samples: %d, n_features: %d" % X_train.shape +print("done in %fs" % (time() - t0)) +print("n_samples: %d, n_features: %d" % X_train.shape) assert sp.issparse(X_train) y_train = news_train.target -print "Loading 20 newsgroups test set... " +print("Loading 20 newsgroups test set... ") news_test = load_mlcomp('20news-18828', 'test') t0 = time() -print "done in %fs" % (time() - t0) +print("done in %fs" % (time() - t0)) -print "Predicting the labels of the test set..." -print "%d documents" % len(news_test.filenames) -print "%d categories" % len(news_test.target_names) +print("Predicting the labels of the test set...") +print("%d documents" % len(news_test.filenames)) +print("%d categories" % len(news_test.target_names)) -print "Extracting features from the dataset using the same vectorizer" +print("Extracting features from the dataset using the same vectorizer") t0 = time() X_test = vectorizer.transform((open(f).read() for f in news_test.filenames)) y_test = news_test.target -print "done in %fs" % (time() - t0) -print "n_samples: %d, n_features: %d" % X_test.shape +print("done in %fs" % (time() - t0)) +print("n_samples: %d, n_features: %d" % X_test.shape) ############################################################################### # Benchmark classifiers def benchmark(clf_class, params, name): - print "parameters:", params + print("parameters:", params) t0 = time() clf = clf_class(**params).fit(X_train, y_train) - print "done in %fs" % (time() - t0) + print("done in %fs" % (time() - t0)) if hasattr(clf, 'coef_'): - print "Percentage of non zeros coef: %f" % ( - np.mean(clf.coef_ != 0) * 100) - - print "Predicting the outcomes of the testing set" + print("Percentage of non zeros coef: %f" + % (np.mean(clf.coef_ != 0) * 100)) + print("Predicting the outcomes of the testing set") t0 = time() pred = clf.predict(X_test) - print "done in %fs" % (time() - t0) + print("done in %fs" % (time() - t0)) - print "Classification report on test set for classifier:" - print clf - print - print classification_report(y_test, pred, - target_names=news_test.target_names) + print("Classification report on test set for classifier:") + print(clf) + print() + print(classification_report(y_test, pred, + target_names=news_test.target_names)) cm = confusion_matrix(y_test, pred) - print "Confusion matrix:" - print cm + print("Confusion matrix:") + print(cm) # Show confusion matrix pl.matshow(cm) @@ -124,7 +126,7 @@ def benchmark(clf_class, params, name): pl.colorbar() -print "Testbenching a linear classifier..." +print("Testbenching a linear classifier...") parameters = { 'loss': 'hinge', 'penalty': 'l2', @@ -135,7 +137,7 @@ def benchmark(clf_class, params, name): benchmark(SGDClassifier, parameters, 'SGD') -print "Testbenching a MultinomialNB classifier..." +print("Testbenching a MultinomialNB classifier...") parameters = {'alpha': 0.01} benchmark(MultinomialNB, parameters, 'MultinomialNB') diff --git a/examples/tree/README.txt b/examples/tree/README.txt index fca9087bf1d33..004ed09c066fe 100644 --- a/examples/tree/README.txt +++ b/examples/tree/README.txt @@ -3,4 +3,4 @@ Decision Trees -------------- -Examples concerning the :mod:`sklearn.tree` package. +Examples concerning the :mod:`sklearn.tree` module. diff --git a/examples/tree/plot_iris.py b/examples/tree/plot_iris.py index 43591ba301087..d30674b11b177 100644 --- a/examples/tree/plot_iris.py +++ b/examples/tree/plot_iris.py @@ -3,17 +3,19 @@ Plot the decision surface of a decision tree on the iris dataset ================================================================ -Plot the decision surface of a :ref:`decision tree ` trained on pairs +Plot the decision surface of a decision tree trained on pairs of features of the iris dataset. +See :ref:`decision tree ` for more information on the estimator. + For each pair of iris features, the decision tree learns decision boundaries made of combinations of simple thresholding rules inferred from the training samples. """ -print __doc__ +print(__doc__) import numpy as np -import pylab as pl +import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier @@ -28,7 +30,7 @@ for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]): - # We only take the two corresponding features + # We only take the two corresponding features X = iris.data[:, pair] y = iris.target @@ -48,7 +50,7 @@ clf = DecisionTreeClassifier().fit(X, y) # Plot the decision boundary - pl.subplot(2, 3, pairidx + 1) + plt.subplot(2, 3, pairidx + 1) x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 @@ -57,20 +59,20 @@ Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) - cs = pl.contourf(xx, yy, Z, cmap=pl.cm.Paired) + cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired) - pl.xlabel(iris.feature_names[pair[0]]) - pl.ylabel(iris.feature_names[pair[1]]) - pl.axis("tight") + plt.xlabel(iris.feature_names[pair[0]]) + plt.ylabel(iris.feature_names[pair[1]]) + plt.axis("tight") # Plot the training points - for i, color in zip(xrange(n_classes), plot_colors): + for i, color in zip(range(n_classes), plot_colors): idx = np.where(y == i) - pl.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i], - cmap=pl.cm.Paired) + plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i], + cmap=plt.cm.Paired) - pl.axis("tight") + plt.axis("tight") -pl.suptitle("Decision surface of a decision tree using paired features") -pl.legend() -pl.show() +plt.suptitle("Decision surface of a decision tree using paired features") +plt.legend() +plt.show() diff --git a/examples/tree/plot_tree_regression.py b/examples/tree/plot_tree_regression.py index c32369eebb409..c0f0cc5b0f513 100644 --- a/examples/tree/plot_tree_regression.py +++ b/examples/tree/plot_tree_regression.py @@ -3,17 +3,22 @@ Decision Tree Regression =================================================================== -1D regression with :ref:`decision trees `: the decision tree is +A 1D regression with decision tree. + +The :ref:`decision trees ` is used to fit a sine curve with addition noisy observation. As a result, it learns local linear regressions approximating the sine curve. -We can see that if the maximum depth of the tree (controled by the +We can see that if the maximum depth of the tree (controlled by the `max_depth` parameter) is set too high, the decision trees learn too fine details of the training data and learn from the noise, i.e. they overfit. """ -print __doc__ +print(__doc__) +# Import the necessary modules and libraries import numpy as np +from sklearn.tree import DecisionTreeRegressor +import matplotlib.pyplot as plt # Create a random dataset rng = np.random.RandomState(1) @@ -22,8 +27,6 @@ y[::5] += 3 * (0.5 - rng.rand(16)) # Fit regression model -from sklearn.tree import DecisionTreeRegressor - clf_1 = DecisionTreeRegressor(max_depth=2) clf_2 = DecisionTreeRegressor(max_depth=5) clf_1.fit(X, y) @@ -35,14 +38,12 @@ y_2 = clf_2.predict(X_test) # Plot the results -import pylab as pl - -pl.figure() -pl.scatter(X, y, c="k", label="data") -pl.plot(X_test, y_1, c="g", label="max_depth=2", linewidth=2) -pl.plot(X_test, y_2, c="r", label="max_depth=5", linewidth=2) -pl.xlabel("data") -pl.ylabel("target") -pl.title("Decision Tree Regression") -pl.legend() -pl.show() +plt.figure() +plt.scatter(X, y, c="k", label="data") +plt.plot(X_test, y_1, c="g", label="max_depth=2", linewidth=2) +plt.plot(X_test, y_2, c="r", label="max_depth=5", linewidth=2) +plt.xlabel("data") +plt.ylabel("target") +plt.title("Decision Tree Regression") +plt.legend() +plt.show() diff --git a/examples/tree/plot_tree_regression_multioutput.py b/examples/tree/plot_tree_regression_multioutput.py index 09750a0228b65..e3130e128dc56 100644 --- a/examples/tree/plot_tree_regression_multioutput.py +++ b/examples/tree/plot_tree_regression_multioutput.py @@ -3,7 +3,9 @@ Multi-output Decision Tree Regression =================================================================== -Multi-output regression with :ref:`decision trees `: the decision tree +An example to illustrate multi-output regression with decision tree. + +The :ref:`decision trees ` is used to predict simultaneously the noisy x and y observations of a circle given a single underlying feature. As a result, it learns local linear regressions approximating the circle. @@ -12,9 +14,11 @@ `max_depth` parameter) is set too high, the decision trees learn too fine details of the training data and learn from the noise, i.e. they overfit. """ -print __doc__ +print(__doc__) import numpy as np +import matplotlib.pyplot as plt +from sklearn.tree import DecisionTreeRegressor # Create a random dataset rng = np.random.RandomState(1) @@ -23,8 +27,6 @@ y[::5, :] += (0.5 - rng.rand(20, 2)) # Fit regression model -from sklearn.tree import DecisionTreeRegressor - clf_1 = DecisionTreeRegressor(max_depth=2) clf_2 = DecisionTreeRegressor(max_depth=5) clf_3 = DecisionTreeRegressor(max_depth=8) @@ -39,17 +41,15 @@ y_3 = clf_3.predict(X_test) # Plot the results -import pylab as pl - -pl.figure() -pl.scatter(y[:, 0], y[:, 1], c="k", label="data") -pl.scatter(y_1[:, 0], y_1[:, 1], c="g", label="max_depth=2") -pl.scatter(y_2[:, 0], y_2[:, 1], c="r", label="max_depth=5") -pl.scatter(y_3[:, 0], y_3[:, 1], c="b", label="max_depth=8") -pl.xlim([-6, 6]) -pl.ylim([-6, 6]) -pl.xlabel("data") -pl.ylabel("target") -pl.title("Multi-output Decision Tree Regression") -pl.legend() -pl.show() +plt.figure() +plt.scatter(y[:, 0], y[:, 1], c="k", label="data") +plt.scatter(y_1[:, 0], y_1[:, 1], c="g", label="max_depth=2") +plt.scatter(y_2[:, 0], y_2[:, 1], c="r", label="max_depth=5") +plt.scatter(y_3[:, 0], y_3[:, 1], c="b", label="max_depth=8") +plt.xlim([-6, 6]) +plt.ylim([-6, 6]) +plt.xlabel("data") +plt.ylabel("target") +plt.title("Multi-output Decision Tree Regression") +plt.legend() +plt.show() diff --git a/setup.cfg b/setup.cfg index 4acc064b3c202..377428127ca79 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,6 +4,37 @@ test = nosetests [nosetests] +# nosetests skips test files with the executable bit by default +# which can silently hide failing tests. +# There are no executable scripts within the scikit-learn project +# so let's turn the --exe flag on to avoid skipping tests by +# mistake. +exe = 1 +cover-html = 1 +cover-html-dir = coverage +cover-package = sklearn + detailed-errors = 1 with-doctest = 1 -cover-package = sklearn +doctest-tests = 1 +doctest-extension = rst +doctest-fixtures = _fixture +#doctest-options = +ELLIPSIS,+NORMALIZE_WHITESPACE + +[wheelhouse_uploader] +artifact_indexes= + # OSX wheels built by travis (only for specific tags): + # https://github.com/MacPython/scikit-learn-wheels + http://wheels.scipy.org + # Windows wheels buit by: + # https://ci.appveyor.com/project/sklearn-ci/scikit-learn/ + http://windows-wheels.scikit-learn.org/ + +# Uncomment the following under windows to build using: +# http://sourceforge.net/projects/mingw/ + +#[build_ext] +#compiler=mingw32 +# +#[build] +#compiler=mingw32 diff --git a/setup.py b/setup.py old mode 100644 new mode 100755 index 689f271c1ff45..de129757ac62b --- a/setup.py +++ b/setup.py @@ -2,12 +2,15 @@ # # Copyright (C) 2007-2009 Cournapeau David # 2010 Fabian Pedregosa +# License: 3-clause BSD descr = """A set of python modules for machine learning and data mining""" import sys import os import shutil +from distutils.command.clean import clean as Clean + if sys.version_info[0] < 3: import __builtin__ as builtins @@ -16,15 +19,19 @@ # This is a bit (!) hackish: we are setting a global variable so that the main # sklearn __init__ can detect if it is being loaded by the setup routine, to -# avoid attempting to load components that aren't built yet. +# avoid attempting to load components that aren't built yet: +# the numpy distutils extensions that are used by scikit-learn to recursively +# build the compiled extensions in sub-packages is based on the Python import +# machinery. builtins.__SKLEARN_SETUP__ = True DISTNAME = 'scikit-learn' DESCRIPTION = 'A set of python modules for machine learning and data mining' -LONG_DESCRIPTION = open('README.rst').read() -MAINTAINER = 'Fabian Pedregosa' -MAINTAINER_EMAIL = 'fabian.pedregosa@inria.fr' -URL = 'http://scikit-learn.sourceforge.net/' +with open('README.rst') as f: + LONG_DESCRIPTION = f.read() +MAINTAINER = 'Andreas Mueller' +MAINTAINER_EMAIL = 'amueller@ais.uni-bonn.de' +URL = 'http://scikit-learn.org/' LICENSE = 'new BSD' DOWNLOAD_URL = 'http://sourceforge.net/projects/scikit-learn/files/' @@ -33,26 +40,61 @@ import sklearn VERSION = sklearn.__version__ -############################################################################### + # Optional setuptools features # We need to import setuptools early, if we want setuptools features, # as it monkey-patches the 'setup' function - # For some commands, use setuptools -if len(set(('develop', 'release', 'bdist_egg', 'bdist_rpm', - 'bdist_wininst', 'install_egg_info', 'build_sphinx', - 'egg_info', 'easy_install', 'upload', - )).intersection(sys.argv)) > 0: +SETUPTOOLS_COMMANDS = set([ + 'develop', 'release', 'bdist_egg', 'bdist_rpm', + 'bdist_wininst', 'install_egg_info', 'build_sphinx', + 'egg_info', 'easy_install', 'upload', 'bdist_wheel', + '--single-version-externally-managed', +]) +if SETUPTOOLS_COMMANDS.intersection(sys.argv): import setuptools extra_setuptools_args = dict( - zip_safe=False, # the package can run out of an .egg file - include_package_data=True, - ) + zip_safe=False, # the package can run out of an .egg file + include_package_data=True, + ) else: extra_setuptools_args = dict() -############################################################################### -from numpy.distutils.core import setup + +# Custom clean command to remove build artifacts + +class CleanCommand(Clean): + description = "Remove build artifacts from the source tree" + + def run(self): + Clean.run(self) + if os.path.exists('build'): + shutil.rmtree('build') + for dirpath, dirnames, filenames in os.walk('sklearn'): + for filename in filenames: + if (filename.endswith('.so') or filename.endswith('.pyd') + or filename.endswith('.dll') + or filename.endswith('.pyc')): + os.unlink(os.path.join(dirpath, filename)) + for dirname in dirnames: + if dirname == '__pycache__': + shutil.rmtree(os.path.join(dirpath, dirname)) + +cmdclass = {'clean': CleanCommand} + + +# Optional wheelhouse-uploader features +# To automate release of binary packages for scikit-learn we need a tool +# to download the packages generated by travis and appveyor workers (with +# version number matching the current release) and upload them all at once +# to PyPI at release time. +# The URL of the artifact repositories are configured in the setup.cfg file. + +WHEELHOUSE_UPLOADER_COMMANDS = set(['fetch_artifacts', 'upload_all']) +if WHEELHOUSE_UPLOADER_COMMANDS.intersection(sys.argv): + import wheelhouse_uploader.cmd + cmdclass.update(vars(wheelhouse_uploader.cmd)) + def configuration(parent_package='', top_path=None): if os.path.exists('MANIFEST'): @@ -73,62 +115,59 @@ def configuration(parent_package='', top_path=None): return config -if __name__ == "__main__": - - old_path = os.getcwd() - local_path = os.path.dirname(os.path.abspath(sys.argv[0])) - # python 3 compatibility stuff. - # Simplified version of scipy strategy: copy files into - # build/py3k, and patch them using lib2to3. - if sys.version_info[0] == 3: +def setup_package(): + metadata = dict(name=DISTNAME, + maintainer=MAINTAINER, + maintainer_email=MAINTAINER_EMAIL, + description=DESCRIPTION, + license=LICENSE, + url=URL, + version=VERSION, + download_url=DOWNLOAD_URL, + long_description=LONG_DESCRIPTION, + classifiers=['Intended Audience :: Science/Research', + 'Intended Audience :: Developers', + 'License :: OSI Approved', + 'Programming Language :: C', + 'Programming Language :: Python', + 'Topic :: Software Development', + 'Topic :: Scientific/Engineering', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: POSIX', + 'Operating System :: Unix', + 'Operating System :: MacOS', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + ], + cmdclass=cmdclass, + **extra_setuptools_args) + + if (len(sys.argv) >= 2 + and ('--help' in sys.argv[1:] or sys.argv[1] + in ('--help-commands', 'egg_info', '--version', 'clean'))): + + # For these actions, NumPy is not required. + # + # They are required to succeed without Numpy for example when + # pip is used to install Scikit-learn when Numpy is not yet present in + # the system. try: - import lib2to3cache + from setuptools import setup except ImportError: - pass - local_path = os.path.join(local_path, 'build', 'py3k') - if os.path.exists(local_path): - shutil.rmtree(local_path) - print("Copying source tree into build/py3k for 2to3 transformation" - "...") - shutil.copytree(os.path.join(old_path, 'sklearn'), - os.path.join(local_path, 'sklearn')) - import lib2to3.main - from io import StringIO - print("Converting to Python3 via 2to3...") - _old_stdout = sys.stdout - try: - sys.stdout = StringIO() # supress noisy output - res = lib2to3.main.main("lib2to3.fixes", ['-x', 'import', '-w', local_path]) - finally: - sys.stdout = _old_stdout - - if res != 0: - raise Exception('2to3 failed, exiting ...') - - os.chdir(local_path) - sys.path.insert(0, local_path) - - setup(configuration=configuration, - name=DISTNAME, - maintainer=MAINTAINER, - maintainer_email=MAINTAINER_EMAIL, - description=DESCRIPTION, - license=LICENSE, - url=URL, - version=VERSION, - download_url=DOWNLOAD_URL, - long_description=LONG_DESCRIPTION, - classifiers=[ - 'Intended Audience :: Science/Research', - 'Intended Audience :: Developers', - 'License :: OSI Approved', - 'Programming Language :: C', - 'Programming Language :: Python', - 'Topic :: Software Development', - 'Topic :: Scientific/Engineering', - 'Operating System :: Microsoft :: Windows', - 'Operating System :: POSIX', - 'Operating System :: Unix', - 'Operating System :: MacOS' - ], - **extra_setuptools_args) + from distutils.core import setup + + metadata['version'] = VERSION + else: + from numpy.distutils.core import setup + + metadata['configuration'] = configuration + + setup(**metadata) + + +if __name__ == "__main__": + setup_package() diff --git a/sklearn/__check_build/__init__.py b/sklearn/__check_build/__init__.py index 51ee3b452f3be..6256b99408256 100644 --- a/sklearn/__check_build/__init__.py +++ b/sklearn/__check_build/__init__.py @@ -12,12 +12,13 @@ If you have used an installer, please check that it is suited for your Python version, your operating system and your platform.""" + def raise_build_error(e): # Raise a comprehensible error and list the contents of the # directory to help debugging on the mailing list. local_dir = os.path.split(__file__)[0] msg = STANDARD_MSG - if local_dir == "sklearn/check_build": + if local_dir == "sklearn/__check_build": # Picking up the local install: this will work only if the # install is an 'inplace build' msg = INPLACE_MSG @@ -27,8 +28,7 @@ def raise_build_error(e): dir_content.append(filename.ljust(26)) else: dir_content.append(filename + '\n') - raise ImportError( -"""%s + raise ImportError("""%s ___________________________________________________________________________ Contents of %s: %s diff --git a/sklearn/__check_build/setup.py b/sklearn/__check_build/setup.py index 9b93db895725e..c9a76db2b5cd7 100644 --- a/sklearn/__check_build/setup.py +++ b/sklearn/__check_build/setup.py @@ -1,5 +1,5 @@ # Author: Virgile Fritsch -# License: BSD Style. +# License: BSD 3 clause import numpy diff --git a/sklearn/__init__.py b/sklearn/__init__.py index 458cade1700a1..634129f8082d0 100644 --- a/sklearn/__init__.py +++ b/sklearn/__init__.py @@ -1,6 +1,6 @@ """ -Machine Learning module in python -================================= +Machine learning module for Python +================================== sklearn is a Python module integrating classical machine learning algorithms in the tightly-knit world of scientific Python @@ -10,10 +10,35 @@ that are accessible to everybody and reusable in various contexts: machine-learning as a versatile tool for science and engineering. -See http://scikit-learn.sourceforge.net for complete documentation. +See http://scikit-learn.org for complete documentation. """ import sys -__version__ = '0.13-git' +import re +import warnings + + +# Make sure that DeprecationWarning within this package always gets printed +warnings.filterwarnings('always', category=DeprecationWarning, + module='^{0}\.'.format(re.escape(__name__))) + +# PEP0440 compatible formatted version, see: +# https://www.python.org/dev/peps/pep-0440/ +# +# Generic release markers: +# X.Y +# X.Y.Z # For bugfix releases +# +# Admissible pre-release markers: +# X.YaN # Alpha release +# X.YbN # Beta release +# X.YrcN # Release Candidate +# X.Y # Final release +# +# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer. +# 'X.Y.dev0' is the canonical version of 'X.Y.dev' +# +__version__ = '0.17.dev0' + try: # This variable is injected in the __builtins__ by the build @@ -30,50 +55,24 @@ else: from . import __check_build from .base import clone + __check_build # avoid flakes unused variable error - try: - from numpy.testing import nosetester - - class _NoseTester(nosetester.NoseTester): - """ Subclass numpy's NoseTester to add doctests by default - """ - - def test(self, label='fast', verbose=1, extra_argv=['--exe'], - doctests=True, coverage=False): - """Run the full test suite - - Examples - -------- - This will run the test suite and stop at the first failing - example - >>> from sklearn import test - >>> test(extra_argv=['--exe', '-sx']) #doctest: +SKIP - """ - return super(_NoseTester, self).test(label=label, verbose=verbose, - extra_argv=extra_argv, - doctests=doctests, coverage=coverage) - - try: - test = _NoseTester(raise_warnings="release").test - except TypeError: - # Older versions of numpy do not have a raise_warnings argument - test = _NoseTester().test - del nosetester - except: - pass - - __all__ = ['cross_validation', 'cluster', 'covariance', - 'datasets', 'decomposition', 'feature_extraction', - 'feature_selection', 'semi_supervised', - 'gaussian_process', 'grid_search', 'hmm', 'lda', 'linear_model', - 'metrics', 'mixture', 'naive_bayes', 'neighbors', 'pipeline', - 'preprocessing', 'qda', 'svm', 'test', 'clone', 'pls'] + __all__ = ['calibration', 'cluster', 'covariance', 'cross_decomposition', + 'cross_validation', 'datasets', 'decomposition', 'dummy', + 'ensemble', 'externals', 'feature_extraction', + 'feature_selection', 'gaussian_process', 'grid_search', 'hmm', + 'isotonic', 'kernel_approximation', 'kernel_ridge', + 'lda', 'learning_curve', + 'linear_model', 'manifold', 'metrics', 'mixture', 'multiclass', + 'naive_bayes', 'neighbors', 'neural_network', 'pipeline', + 'preprocessing', 'qda', 'random_projection', 'semi_supervised', + 'svm', 'tree', + # Non-modules: + 'clone'] def setup_module(module): - """Fixture for the tests to assure globally controllable seeding of RNGs - """ - + """Fixture for the tests to assure globally controllable seeding of RNGs""" import os import numpy as np import random @@ -81,8 +80,8 @@ def setup_module(module): # It could have been provided in the environment _random_seed = os.environ.get('SKLEARN_SEED', None) if _random_seed is None: - _random_seed = np.random.uniform()*(2**31-1) + _random_seed = np.random.uniform() * (2 ** 31 - 1) _random_seed = int(_random_seed) - print "I: Seeding RNGs with %r" % _random_seed + print("I: Seeding RNGs with %r" % _random_seed) np.random.seed(_random_seed) random.seed(_random_seed) diff --git a/sklearn/_hmmc.c b/sklearn/_hmmc.c index 7e7d5d29190ac..8e3ccd7ea24d3 100644 --- a/sklearn/_hmmc.c +++ b/sklearn/_hmmc.c @@ -1,16 +1,28 @@ -/* Generated by Cython 0.15.1 on Mon Jan 9 21:06:13 2012 */ +/* Generated by Cython 0.19.1 on Sun Jul 28 01:04:40 2013 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. #else - #include /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -22,36 +34,47 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - -#if PY_VERSION_HEX < 0x02040000 - #define METH_COEXIST 0 - #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) - #define PyDict_Contains(d,o) PySequence_Contains(d,o) +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 #endif - #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -59,7 +82,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -73,7 +95,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -83,24 +104,47 @@ #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -108,7 +152,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -127,7 +170,14 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) +#endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -135,9 +185,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -154,11 +202,9 @@ #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - #if PY_VERSION_HEX < 0x03020000 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong @@ -167,16 +213,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -195,11 +231,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -209,7 +243,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -217,6 +250,49 @@ #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus @@ -232,11 +308,14 @@ #include #define __PYX_HAVE__sklearn___hmmc #define __PYX_HAVE_API__sklearn___hmmc +#include "math.h" +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" -#include "math.h" +#include "pythread.h" +#include "pystate.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -245,21 +324,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -267,31 +331,135 @@ # else # define CYTHON_UNUSED # endif -# elif defined(__ICC) || defined(__INTEL_COMPILER) +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif #ifdef __GNUC__ @@ -307,8 +475,9 @@ static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -317,7 +486,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -327,7 +495,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -335,18 +502,111 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { "_hmmc.pyx", "numpy.pxd", + "stringsource", + "type.pxd", }; +struct __pyx_memoryview_obj; +typedef struct { + struct __pyx_memoryview_obj *memview; + char *data; + Py_ssize_t shape[8]; + Py_ssize_t strides[8]; + Py_ssize_t suboffsets[8]; +} __Pyx_memviewslice; + +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __pyx_atomic_int_type int +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ + !defined(__i386__) + #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && MSC_VER + #include + #define __pyx_atomic_int_type LONG + #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using MSVC atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 + #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using Intel atomics" + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif +typedef volatile __pyx_atomic_int_type __pyx_atomic_int; +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview) \ + __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) +#else + #define __pyx_add_acquisition_count(memview) \ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif -/* "numpy.pxd":719 + +/* "numpy.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -355,7 +615,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "numpy.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -364,7 +624,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "numpy.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -373,7 +633,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "numpy.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -382,7 +642,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "numpy.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -391,7 +651,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "numpy.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -400,7 +660,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "numpy.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -409,7 +669,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "numpy.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -418,7 +678,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "numpy.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -427,7 +687,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "numpy.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -436,7 +696,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "numpy.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -445,7 +705,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "numpy.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -454,7 +714,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "numpy.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -463,7 +723,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "numpy.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -472,7 +732,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "numpy.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -481,7 +741,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "numpy.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -490,7 +750,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "numpy.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -499,7 +759,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "numpy.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -508,7 +768,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "numpy.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -517,7 +777,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "numpy.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -526,7 +786,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "numpy.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -535,15 +795,14 @@ typedef npy_double __pyx_t_5numpy_double_t; */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; -/* "sklearn/_hmmc.pyx":9 - * double log(double) +/* "sklearn/_hmmc.pyx":8 + * np.import_array() * * ctypedef np.float64_t dtype_t # <<<<<<<<<<<<<< * - * + * cdef dtype_t _NINF = -np.inf */ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5_hmmc_dtype_t; - #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -564,9 +823,14 @@ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5_hmmc_dtype_t; typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ +struct __pyx_memoryview_obj; +struct __pyx_MemviewEnum_obj; +struct __pyx_memoryviewslice_obj; +struct __pyx_array_obj; -/* "numpy.pxd":758 +/* "numpy.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -575,7 +839,7 @@ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5_hmmc_dtype_t; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "numpy.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -584,7 +848,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "numpy.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -593,7 +857,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "numpy.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -602,11 +866,119 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; */ typedef npy_cdouble __pyx_t_5numpy_complex_t; +/* "View.MemoryView":308 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ +struct __pyx_memoryview_obj { + PyObject_HEAD + struct __pyx_vtabstruct_memoryview *__pyx_vtab; + PyObject *obj; + PyObject *_size; + PyObject *_array_interface; + PyThread_type_lock lock; + __pyx_atomic_int acquisition_count[2]; + __pyx_atomic_int *acquisition_count_aligned_p; + Py_buffer view; + int flags; + int dtype_is_object; + __Pyx_TypeInfo *typeinfo; +}; + + +/* "View.MemoryView":275 + * + * @cname('__pyx_MemviewEnum') + * cdef class Enum(object): # <<<<<<<<<<<<<< + * cdef object name + * def __init__(self, name): + */ +struct __pyx_MemviewEnum_obj { + PyObject_HEAD + PyObject *name; +}; + + +/* "View.MemoryView":927 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ +struct __pyx_memoryviewslice_obj { + struct __pyx_memoryview_obj __pyx_base; + __Pyx_memviewslice from_slice; + PyObject *from_object; + PyObject *(*to_object_func)(char *); + int (*to_dtype_func)(char *, PyObject *); +}; + + +/* "View.MemoryView":96 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ +struct __pyx_array_obj { + PyObject_HEAD + char *data; + Py_ssize_t len; + char *format; + int ndim; + Py_ssize_t *_shape; + Py_ssize_t *_strides; + Py_ssize_t itemsize; + PyObject *mode; + PyObject *_format; + void (*callback_free_data)(void *); + int free_data; + int dtype_is_object; +}; + + + +/* "View.MemoryView":308 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ + +struct __pyx_vtabstruct_memoryview { + char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); + PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); +}; +static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; + + + +/* "View.MemoryView":927 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ +struct __pyx_vtabstruct__memoryviewslice { + struct __pyx_vtabstruct_memoryview __pyx_base; +}; +static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -619,8 +991,21 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -631,7 +1016,7 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -642,78 +1027,236 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d +#define __Pyx_MEMVIEW_DIRECT 1 +#define __Pyx_MEMVIEW_PTR 2 +#define __Pyx_MEMVIEW_FULL 4 +#define __Pyx_MEMVIEW_CONTIG 8 +#define __Pyx_MEMVIEW_STRIDED 16 +#define __Pyx_MEMVIEW_FOLLOW 32 +#define __Pyx_IS_C_CONTIG 1 +#define __Pyx_IS_F_CONTIG 2 +static int __Pyx_init_memviewslice( + struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference); +static CYTHON_INLINE int __pyx_add_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) +#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) +#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) +#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) +static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); /*proto*/ -/* Run-time type information about structs used with buffers */ -struct __Pyx_StructField_; +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ -typedef struct { - const char* name; /* for error messages only */ - struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ -} __Pyx_TypeInfo; - -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; - -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ +static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); #define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) - +#define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ - -static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ -#define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) #define __Pyx_BufPtrStrided3d(type, buf, i0, s0, i1, s1, i2, s2) (type)((char*)buf + i0 * s0 + i1 * s1 + i2 * s2) - -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); +#define __Pyx_GetItemInt(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Fast(o, i, is_list, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +#define __Pyx_GetItemInt_List(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_List_Fast(o, i, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, i, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +#define __Pyx_SetItemInt(o, i, v, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_SetItemInt_Fast(o, i, v, is_list, wraparound, boundscheck) : \ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v)) +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck); static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/ + +static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); /* proto */ + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) + +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +#include + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +static CYTHON_INLINE long __Pyx_div_long(long, long); /* proto */ + +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename); /*proto*/ + +static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + #if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); -static void __Pyx_ReleaseBuffer(Py_buffer *view); + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); #else -#define __Pyx_GetBuffer PyObject_GetBuffer -#define __Pyx_ReleaseBuffer PyBuffer_Release + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release #endif -Py_ssize_t __Pyx_zeros[] = {0, 0, 0}; -Py_ssize_t __Pyx_minusones[] = {-1, -1, -1}; -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); + +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5_hmmc_dtype_t(PyObject *); static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_long(npy_long); @@ -729,7 +1272,6 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_long(npy_long); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - #if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) @@ -816,6 +1358,24 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif +static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim); + +static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize); + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object); + +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ + static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); @@ -850,23 +1410,55 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject * static int __Pyx_check_binary_version(void); -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + +/* Module declarations from 'libc.math' */ + /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -877,380 +1469,639 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ -/* Module declarations from 'cython.cython.view' */ +/* Module declarations from 'cython.view' */ /* Module declarations from 'cython' */ /* Module declarations from 'sklearn._hmmc' */ -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t = { "dtype_t", NULL, sizeof(__pyx_t_7sklearn_5_hmmc_dtype_t), 'R' }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int_t = { "int_t", NULL, sizeof(__pyx_t_5numpy_int_t), 'I' }; +static PyTypeObject *__pyx_memoryview_type = 0; +static PyTypeObject *__pyx_MemviewEnum_type = 0; +static PyTypeObject *__pyx_memoryviewslice_type = 0; +static PyTypeObject *__pyx_array_type = 0; +static __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_v_7sklearn_5_hmmc__NINF; +static PyObject *generic = 0; +static PyObject *strided = 0; +static PyObject *indirect = 0; +static PyObject *contiguous = 0; +static PyObject *indirect_contiguous = 0; +static __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_f_7sklearn_5_hmmc__max(__Pyx_memviewslice); /*proto*/ +static __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_f_7sklearn_5_hmmc__logsum(__Pyx_memviewslice, int __pyx_skip_dispatch); /*proto*/ +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ +static void *__pyx_align_pointer(void *, size_t); /*proto*/ +static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ +static PyObject *_unellipsify(PyObject *, int); /*proto*/ +static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ +static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, int); /*proto*/ +static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ +static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ +static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ +static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ +static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ +static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ +static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t = { "dtype_t", NULL, sizeof(__pyx_t_7sklearn_5_hmmc_dtype_t), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int_t = { "int_t", NULL, sizeof(__pyx_t_5numpy_int_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_int_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_int_t), 0 }; #define __Pyx_MODULE_NAME "sklearn._hmmc" int __pyx_module_is_main_sklearn___hmmc = 0; /* Implementation of 'sklearn._hmmc' */ -static PyObject *__pyx_builtin_xrange; -static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; -static char __pyx_k_6[] = "ndarray is not C contiguous"; -static char __pyx_k_8[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_10[] = "Non-native byte order not supported"; -static char __pyx_k_12[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_13[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_16[] = "Format string allocated too short."; -static char __pyx_k_18[] = "sklearn._hmmc"; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_Ellipsis; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_xrange; +static PyObject *__pyx_builtin_id; +static PyObject *__pyx_builtin_IndexError; +static PyObject *__pyx_pf_7sklearn_5_hmmc__logsum(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X); /* proto */ +static PyObject *__pyx_pf_7sklearn_5_hmmc_2_forward(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_observations, int __pyx_v_n_components, PyArrayObject *__pyx_v_log_startprob, PyArrayObject *__pyx_v_log_transmat, PyArrayObject *__pyx_v_framelogprob, PyArrayObject *__pyx_v_fwdlattice); /* proto */ +static PyObject *__pyx_pf_7sklearn_5_hmmc_4_backward(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_observations, int __pyx_v_n_components, CYTHON_UNUSED PyArrayObject *__pyx_v_log_startprob, PyArrayObject *__pyx_v_log_transmat, PyArrayObject *__pyx_v_framelogprob, PyArrayObject *__pyx_v_bwdlattice); /* proto */ +static PyObject *__pyx_pf_7sklearn_5_hmmc_6_compute_lneta(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_observations, int __pyx_v_n_components, PyArrayObject *__pyx_v_fwdlattice, PyArrayObject *__pyx_v_log_transmat, PyArrayObject *__pyx_v_bwdlattice, PyArrayObject *__pyx_v_framelogprob, double __pyx_v_logprob, PyArrayObject *__pyx_v_lneta); /* proto */ +static PyObject *__pyx_pf_7sklearn_5_hmmc_8_viterbi(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_observations, int __pyx_v_n_components, PyArrayObject *__pyx_v_log_startprob, PyArrayObject *__pyx_v_log_transmat, PyArrayObject *__pyx_v_framelogprob); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_4[] = "ndarray is not C contiguous"; +static char __pyx_k_6[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_8[] = "Non-native byte order not supported"; +static char __pyx_k_10[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_11[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_14[] = "Format string allocated too short."; +static char __pyx_k_16[] = "Empty shape tuple for cython.array"; +static char __pyx_k_18[] = "itemsize <= 0 for cython.array"; +static char __pyx_k_21[] = "unable to allocate shape or strides."; +static char __pyx_k_23[] = "Invalid shape in axis %d: %d."; +static char __pyx_k_24[] = "Invalid mode, expected 'c' or 'fortran', got %s"; +static char __pyx_k_26[] = "unable to allocate array data."; +static char __pyx_k_28[] = "Can only create a buffer that is contiguous in memory."; +static char __pyx_k_30[] = "Unable to convert item to object"; +static char __pyx_k_32[] = "Buffer view does not expose strides"; +static char __pyx_k_34[] = ""; +static char __pyx_k_35[] = ""; +static char __pyx_k_38[] = "Cannot index with type '%s'"; +static char __pyx_k_40[] = "Indirect dimensions not supported"; +static char __pyx_k_42[] = "Index out of bounds (axis %d)"; +static char __pyx_k_43[] = "Step may not be zero (axis %d)"; +static char __pyx_k_44[] = "All dimensions preceding dimension %d must be indexed and not sliced"; +static char __pyx_k_45[] = "Out of bounds on buffer access (axis %d)"; +static char __pyx_k_46[] = "Cannot transpose memoryview with indirect dimensions"; +static char __pyx_k_47[] = "got differing extents in dimension %d (got %d and %d)"; +static char __pyx_k_48[] = "Dimension %d is not direct"; +static char __pyx_k_51[] = "/Users/ogrisel/code/scikit-learn/sklearn/_hmmc.pyx"; +static char __pyx_k_52[] = "sklearn._hmmc"; +static char __pyx_k_59[] = "getbuffer(obj, view, flags)"; +static char __pyx_k_60[] = ""; +static char __pyx_k_62[] = ""; +static char __pyx_k_64[] = ""; +static char __pyx_k_66[] = ""; +static char __pyx_k_68[] = ""; static char __pyx_k__B[] = "B"; static char __pyx_k__H[] = "H"; static char __pyx_k__I[] = "I"; static char __pyx_k__L[] = "L"; -static char __pyx_k__N[] = "N"; static char __pyx_k__O[] = "O"; static char __pyx_k__Q[] = "Q"; -static char __pyx_k__X[] = "X"; +static char __pyx_k__T[] = "T"; static char __pyx_k__b[] = "b"; +static char __pyx_k__c[] = "c"; static char __pyx_k__d[] = "d"; static char __pyx_k__f[] = "f"; static char __pyx_k__g[] = "g"; static char __pyx_k__h[] = "h"; static char __pyx_k__i[] = "i"; +static char __pyx_k__j[] = "j"; static char __pyx_k__l[] = "l"; static char __pyx_k__q[] = "q"; +static char __pyx_k__t[] = "t"; static char __pyx_k__Zd[] = "Zd"; static char __pyx_k__Zf[] = "Zf"; static char __pyx_k__Zg[] = "Zg"; +static char __pyx_k__id[] = "id"; static char __pyx_k__np[] = "np"; +static char __pyx_k__inf[] = "inf"; static char __pyx_k__int[] = "int"; static char __pyx_k__max[] = "max"; +static char __pyx_k__obj[] = "obj"; +static char __pyx_k__axis[] = "axis"; +static char __pyx_k__base[] = "base"; +static char __pyx_k__mode[] = "mode"; +static char __pyx_k__name[] = "name"; +static char __pyx_k__ndim[] = "ndim"; +static char __pyx_k__pack[] = "pack"; +static char __pyx_k__size[] = "size"; +static char __pyx_k__step[] = "step"; +static char __pyx_k__stop[] = "stop"; +static char __pyx_k__ASCII[] = "ASCII"; static char __pyx_k__dtype[] = "dtype"; +static char __pyx_k__empty[] = "empty"; +static char __pyx_k__error[] = "error"; +static char __pyx_k__flags[] = "flags"; static char __pyx_k__lneta[] = "lneta"; static char __pyx_k__numpy[] = "numpy"; static char __pyx_k__range[] = "range"; +static char __pyx_k__shape[] = "shape"; +static char __pyx_k__start[] = "start"; static char __pyx_k__zeros[] = "zeros"; static char __pyx_k__argmax[] = "argmax"; +static char __pyx_k__decode[] = "decode"; +static char __pyx_k__encode[] = "encode"; +static char __pyx_k__extend[] = "extend"; +static char __pyx_k__format[] = "format"; +static char __pyx_k__struct[] = "struct"; +static char __pyx_k__unpack[] = "unpack"; static char __pyx_k__xrange[] = "xrange"; -static char __pyx_k___logsum[] = "_logsum"; +static char __pyx_k__fortran[] = "fortran"; static char __pyx_k__logprob[] = "logprob"; +static char __pyx_k__max_pos[] = "max_pos"; +static char __pyx_k__memview[] = "memview"; +static char __pyx_k__Ellipsis[] = "Ellipsis"; static char __pyx_k____main__[] = "__main__"; +static char __pyx_k____name__[] = "__name__"; static char __pyx_k____test__[] = "__test__"; static char __pyx_k___forward[] = "_forward"; static char __pyx_k___viterbi[] = "_viterbi"; +static char __pyx_k__itemsize[] = "itemsize"; +static char __pyx_k__TypeError[] = "TypeError"; +static char __pyx_k____class__[] = "__class__"; static char __pyx_k___backward[] = "_backward"; +static char __pyx_k__enumerate[] = "enumerate"; +static char __pyx_k__IndexError[] = "IndexError"; static char __pyx_k__ValueError[] = "ValueError"; +static char __pyx_k____import__[] = "__import__"; static char __pyx_k__bwdlattice[] = "bwdlattice"; static char __pyx_k__fwdlattice[] = "fwdlattice"; +static char __pyx_k__MemoryError[] = "MemoryError"; +static char __pyx_k__work_buffer[] = "work_buffer"; static char __pyx_k__RuntimeError[] = "RuntimeError"; static char __pyx_k__framelogprob[] = "framelogprob"; static char __pyx_k__log_transmat[] = "log_transmat"; static char __pyx_k__n_components[] = "n_components"; static char __pyx_k__log_startprob[] = "log_startprob"; +static char __pyx_k____pyx_vtable__[] = "__pyx_vtable__"; static char __pyx_k___compute_lneta[] = "_compute_lneta"; static char __pyx_k__n_observations[] = "n_observations"; +static char __pyx_k__state_sequence[] = "state_sequence"; +static char __pyx_k____pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k__allocate_buffer[] = "allocate_buffer"; +static char __pyx_k__dtype_is_object[] = "dtype_is_object"; +static char __pyx_k__viterbi_lattice[] = "viterbi_lattice"; +static char __pyx_k____pyx_releasebuffer[] = "__pyx_releasebuffer"; static PyObject *__pyx_kp_u_10; -static PyObject *__pyx_kp_u_12; -static PyObject *__pyx_kp_u_13; -static PyObject *__pyx_kp_u_16; -static PyObject *__pyx_n_s_18; +static PyObject *__pyx_kp_u_11; +static PyObject *__pyx_kp_u_14; +static PyObject *__pyx_kp_s_16; +static PyObject *__pyx_kp_s_18; +static PyObject *__pyx_kp_s_21; +static PyObject *__pyx_kp_s_23; +static PyObject *__pyx_kp_s_24; +static PyObject *__pyx_kp_s_26; +static PyObject *__pyx_kp_s_28; +static PyObject *__pyx_kp_s_30; +static PyObject *__pyx_kp_s_32; +static PyObject *__pyx_kp_s_34; +static PyObject *__pyx_kp_s_35; +static PyObject *__pyx_kp_s_38; +static PyObject *__pyx_kp_u_4; +static PyObject *__pyx_kp_s_40; +static PyObject *__pyx_kp_s_45; +static PyObject *__pyx_kp_s_47; +static PyObject *__pyx_kp_s_51; +static PyObject *__pyx_n_s_52; static PyObject *__pyx_kp_u_6; +static PyObject *__pyx_kp_s_60; +static PyObject *__pyx_kp_s_62; +static PyObject *__pyx_kp_s_64; +static PyObject *__pyx_kp_s_66; +static PyObject *__pyx_kp_s_68; static PyObject *__pyx_kp_u_8; -static PyObject *__pyx_n_s__N; +static PyObject *__pyx_n_s__ASCII; +static PyObject *__pyx_n_s__Ellipsis; +static PyObject *__pyx_n_s__IndexError; +static PyObject *__pyx_n_s__MemoryError; +static PyObject *__pyx_n_b__O; static PyObject *__pyx_n_s__RuntimeError; +static PyObject *__pyx_n_s__T; +static PyObject *__pyx_n_s__TypeError; static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s__X; +static PyObject *__pyx_n_s____class__; +static PyObject *__pyx_n_s____import__; static PyObject *__pyx_n_s____main__; +static PyObject *__pyx_n_s____name__; +static PyObject *__pyx_n_s____pyx_getbuffer; +static PyObject *__pyx_n_s____pyx_releasebuffer; +static PyObject *__pyx_n_s____pyx_vtable__; static PyObject *__pyx_n_s____test__; static PyObject *__pyx_n_s___backward; static PyObject *__pyx_n_s___compute_lneta; static PyObject *__pyx_n_s___forward; -static PyObject *__pyx_n_s___logsum; static PyObject *__pyx_n_s___viterbi; +static PyObject *__pyx_n_s__allocate_buffer; static PyObject *__pyx_n_s__argmax; +static PyObject *__pyx_n_s__axis; +static PyObject *__pyx_n_s__base; static PyObject *__pyx_n_s__bwdlattice; +static PyObject *__pyx_n_b__c; +static PyObject *__pyx_n_s__c; +static PyObject *__pyx_n_u__c; +static PyObject *__pyx_n_s__decode; static PyObject *__pyx_n_s__dtype; +static PyObject *__pyx_n_s__dtype_is_object; +static PyObject *__pyx_n_s__empty; +static PyObject *__pyx_n_s__encode; +static PyObject *__pyx_n_s__enumerate; +static PyObject *__pyx_n_s__error; +static PyObject *__pyx_n_s__extend; +static PyObject *__pyx_n_s__flags; +static PyObject *__pyx_n_s__format; +static PyObject *__pyx_n_b__fortran; +static PyObject *__pyx_n_s__fortran; static PyObject *__pyx_n_s__framelogprob; static PyObject *__pyx_n_s__fwdlattice; +static PyObject *__pyx_n_s__i; +static PyObject *__pyx_n_s__id; +static PyObject *__pyx_n_s__inf; static PyObject *__pyx_n_s__int; +static PyObject *__pyx_n_s__itemsize; +static PyObject *__pyx_n_s__j; static PyObject *__pyx_n_s__lneta; static PyObject *__pyx_n_s__log_startprob; static PyObject *__pyx_n_s__log_transmat; static PyObject *__pyx_n_s__logprob; static PyObject *__pyx_n_s__max; +static PyObject *__pyx_n_s__max_pos; +static PyObject *__pyx_n_s__memview; +static PyObject *__pyx_n_s__mode; static PyObject *__pyx_n_s__n_components; static PyObject *__pyx_n_s__n_observations; +static PyObject *__pyx_n_s__name; +static PyObject *__pyx_n_s__ndim; static PyObject *__pyx_n_s__np; static PyObject *__pyx_n_s__numpy; +static PyObject *__pyx_n_s__obj; +static PyObject *__pyx_n_s__pack; static PyObject *__pyx_n_s__range; +static PyObject *__pyx_n_s__shape; +static PyObject *__pyx_n_s__size; +static PyObject *__pyx_n_s__start; +static PyObject *__pyx_n_s__state_sequence; +static PyObject *__pyx_n_s__step; +static PyObject *__pyx_n_s__stop; +static PyObject *__pyx_n_s__struct; +static PyObject *__pyx_n_s__t; +static PyObject *__pyx_n_s__unpack; +static PyObject *__pyx_n_s__viterbi_lattice; +static PyObject *__pyx_n_s__work_buffer; static PyObject *__pyx_n_s__xrange; static PyObject *__pyx_n_s__zeros; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_1; +static PyObject *__pyx_int_neg_1; static PyObject *__pyx_int_15; static PyObject *__pyx_k_slice_1; static PyObject *__pyx_k_slice_2; static PyObject *__pyx_k_slice_3; -static PyObject *__pyx_k_slice_4; -static PyObject *__pyx_k_slice_5; +static PyObject *__pyx_k_tuple_5; static PyObject *__pyx_k_tuple_7; static PyObject *__pyx_k_tuple_9; -static PyObject *__pyx_k_tuple_11; -static PyObject *__pyx_k_tuple_14; +static PyObject *__pyx_k_tuple_12; +static PyObject *__pyx_k_tuple_13; static PyObject *__pyx_k_tuple_15; static PyObject *__pyx_k_tuple_17; +static PyObject *__pyx_k_tuple_19; +static PyObject *__pyx_k_tuple_20; +static PyObject *__pyx_k_tuple_22; +static PyObject *__pyx_k_tuple_25; +static PyObject *__pyx_k_tuple_27; +static PyObject *__pyx_k_tuple_29; +static PyObject *__pyx_k_tuple_31; +static PyObject *__pyx_k_tuple_33; +static PyObject *__pyx_k_tuple_36; +static PyObject *__pyx_k_tuple_37; +static PyObject *__pyx_k_tuple_39; +static PyObject *__pyx_k_tuple_41; +static PyObject *__pyx_k_tuple_49; +static PyObject *__pyx_k_tuple_53; +static PyObject *__pyx_k_tuple_55; +static PyObject *__pyx_k_tuple_57; +static PyObject *__pyx_k_tuple_61; +static PyObject *__pyx_k_tuple_63; +static PyObject *__pyx_k_tuple_65; +static PyObject *__pyx_k_tuple_67; +static PyObject *__pyx_k_tuple_69; +static PyObject *__pyx_k_codeobj_50; +static PyObject *__pyx_k_codeobj_54; +static PyObject *__pyx_k_codeobj_56; +static PyObject *__pyx_k_codeobj_58; /* "sklearn/_hmmc.pyx":13 * * @cython.boundscheck(False) - * def _logsum(int N, np.ndarray[dtype_t, ndim=1] X): # <<<<<<<<<<<<<< - * cdef int i - * cdef double maxv, Xsum + * cdef dtype_t _max(dtype_t[:] values): # <<<<<<<<<<<<<< + * # find maximum value (builtin 'max' is unrolled for speed) + * cdef dtype_t value */ -static PyObject *__pyx_pf_7sklearn_5_hmmc__logsum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7sklearn_5_hmmc__logsum = {__Pyx_NAMESTR("_logsum"), (PyCFunction)__pyx_pf_7sklearn_5_hmmc__logsum, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; -static PyObject *__pyx_pf_7sklearn_5_hmmc__logsum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - int __pyx_v_N; - PyArrayObject *__pyx_v_X = 0; - int __pyx_v_i; - double __pyx_v_maxv; - double __pyx_v_Xsum; - Py_buffer __pyx_bstruct_X; - Py_ssize_t __pyx_bstride_0_X = 0; - Py_ssize_t __pyx_bshape_0_X = 0; - PyObject *__pyx_r = NULL; +static __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_f_7sklearn_5_hmmc__max(__Pyx_memviewslice __pyx_v_values) { + __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_v_value; + __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_v_vmax; + Py_ssize_t __pyx_v_i; + __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_r; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - double __pyx_t_3; + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__N,&__pyx_n_s__X,0}; - __Pyx_RefNannySetupContext("_logsum"); - __pyx_self = __pyx_self; - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__N); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_logsum", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "_logsum") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + __Pyx_RefNannySetupContext("_max", 0); + + /* "sklearn/_hmmc.pyx":16 + * # find maximum value (builtin 'max' is unrolled for speed) + * cdef dtype_t value + * cdef dtype_t vmax = _NINF # <<<<<<<<<<<<<< + * for i in range(values.shape[0]): + * value = values[i] + */ + __pyx_v_vmax = __pyx_v_7sklearn_5_hmmc__NINF; + + /* "sklearn/_hmmc.pyx":17 + * cdef dtype_t value + * cdef dtype_t vmax = _NINF + * for i in range(values.shape[0]): # <<<<<<<<<<<<<< + * value = values[i] + * if value > vmax: + */ + __pyx_t_1 = (__pyx_v_values.shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "sklearn/_hmmc.pyx":18 + * cdef dtype_t vmax = _NINF + * for i in range(values.shape[0]): + * value = values[i] # <<<<<<<<<<<<<< + * if value > vmax: + * vmax = value + */ + __pyx_t_3 = __pyx_v_i; + if (__pyx_t_3 < 0) __pyx_t_3 += __pyx_v_values.shape[0]; + __pyx_v_value = (*((__pyx_t_7sklearn_5_hmmc_dtype_t *) ( /* dim=0 */ (__pyx_v_values.data + __pyx_t_3 * __pyx_v_values.strides[0]) ))); + + /* "sklearn/_hmmc.pyx":19 + * for i in range(values.shape[0]): + * value = values[i] + * if value > vmax: # <<<<<<<<<<<<<< + * vmax = value + * return vmax + */ + __pyx_t_4 = ((__pyx_v_value > __pyx_v_vmax) != 0); + if (__pyx_t_4) { + + /* "sklearn/_hmmc.pyx":20 + * value = values[i] + * if value > vmax: + * vmax = value # <<<<<<<<<<<<<< + * return vmax + * + */ + __pyx_v_vmax = __pyx_v_value; + goto __pyx_L5; } - __pyx_v_N = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_N == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_X = ((PyArrayObject *)values[1]); + __pyx_L5:; } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_logsum", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn._hmmc._logsum", __pyx_clineno, __pyx_lineno, __pyx_filename); + + /* "sklearn/_hmmc.pyx":21 + * if value > vmax: + * vmax = value + * return vmax # <<<<<<<<<<<<<< + * + * @cython.boundscheck(False) + */ + __pyx_r = __pyx_v_vmax; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_X.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_X = __pyx_bstruct_X.strides[0]; - __pyx_bshape_0_X = __pyx_bstruct_X.shape[0]; + return __pyx_r; +} - /* "sklearn/_hmmc.pyx":16 - * cdef int i - * cdef double maxv, Xsum - * Xsum = 0.0 # <<<<<<<<<<<<<< - * maxv = X.max() - * for i in xrange(N): +/* "sklearn/_hmmc.pyx":24 + * + * @cython.boundscheck(False) + * cpdef dtype_t _logsum(dtype_t[:] X): # <<<<<<<<<<<<<< + * cdef dtype_t vmax = _max(X) + * cdef dtype_t power_sum = 0 */ - __pyx_v_Xsum = 0.0; - /* "sklearn/_hmmc.pyx":17 - * cdef double maxv, Xsum - * Xsum = 0.0 - * maxv = X.max() # <<<<<<<<<<<<<< - * for i in xrange(N): - * Xsum += exp(X[i] - maxv) +static PyObject *__pyx_pw_7sklearn_5_hmmc_1_logsum(PyObject *__pyx_self, PyObject *__pyx_arg_X); /*proto*/ +static __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_f_7sklearn_5_hmmc__logsum(__Pyx_memviewslice __pyx_v_X, CYTHON_UNUSED int __pyx_skip_dispatch) { + __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_v_vmax; + __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_v_power_sum; + Py_ssize_t __pyx_v_i; + __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __Pyx_RefNannySetupContext("_logsum", 0); + + /* "sklearn/_hmmc.pyx":25 + * @cython.boundscheck(False) + * cpdef dtype_t _logsum(dtype_t[:] X): + * cdef dtype_t vmax = _max(X) # <<<<<<<<<<<<<< + * cdef dtype_t power_sum = 0 + * */ - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_X), __pyx_n_s__max); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_3 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_maxv = __pyx_t_3; + __pyx_v_vmax = __pyx_f_7sklearn_5_hmmc__max(__pyx_v_X); - /* "sklearn/_hmmc.pyx":18 - * Xsum = 0.0 - * maxv = X.max() - * for i in xrange(N): # <<<<<<<<<<<<<< - * Xsum += exp(X[i] - maxv) - * return log(Xsum) + maxv + /* "sklearn/_hmmc.pyx":26 + * cpdef dtype_t _logsum(dtype_t[:] X): + * cdef dtype_t vmax = _max(X) + * cdef dtype_t power_sum = 0 # <<<<<<<<<<<<<< + * + * for i in range(X.shape[0]): */ - __pyx_t_4 = __pyx_v_N; - for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { - __pyx_v_i = __pyx_t_5; + __pyx_v_power_sum = 0.0; - /* "sklearn/_hmmc.pyx":19 - * maxv = X.max() - * for i in xrange(N): - * Xsum += exp(X[i] - maxv) # <<<<<<<<<<<<<< - * return log(Xsum) + maxv + /* "sklearn/_hmmc.pyx":28 + * cdef dtype_t power_sum = 0 * + * for i in range(X.shape[0]): # <<<<<<<<<<<<<< + * power_sum += exp(X[i]-vmax) + * + */ + __pyx_t_1 = (__pyx_v_X.shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "sklearn/_hmmc.pyx":29 + * + * for i in range(X.shape[0]): + * power_sum += exp(X[i]-vmax) # <<<<<<<<<<<<<< + * + * return log(power_sum) + vmax */ - __pyx_t_6 = __pyx_v_i; - if (__pyx_t_6 < 0) __pyx_t_6 += __pyx_bshape_0_X; - __pyx_v_Xsum = (__pyx_v_Xsum + exp(((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_X.buf, __pyx_t_6, __pyx_bstride_0_X)) - __pyx_v_maxv))); + __pyx_t_3 = __pyx_v_i; + if (__pyx_t_3 < 0) __pyx_t_3 += __pyx_v_X.shape[0]; + __pyx_v_power_sum = (__pyx_v_power_sum + exp(((*((__pyx_t_7sklearn_5_hmmc_dtype_t *) ( /* dim=0 */ (__pyx_v_X.data + __pyx_t_3 * __pyx_v_X.strides[0]) ))) - __pyx_v_vmax))); } - /* "sklearn/_hmmc.pyx":20 - * for i in xrange(N): - * Xsum += exp(X[i] - maxv) - * return log(Xsum) + maxv # <<<<<<<<<<<<<< + /* "sklearn/_hmmc.pyx":31 + * power_sum += exp(X[i]-vmax) + * + * return log(power_sum) + vmax # <<<<<<<<<<<<<< + * * + */ + __pyx_r = (log(__pyx_v_power_sum) + __pyx_v_vmax); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5_hmmc_1_logsum(PyObject *__pyx_self, PyObject *__pyx_arg_X); /*proto*/ +static PyObject *__pyx_pw_7sklearn_5_hmmc_1_logsum(PyObject *__pyx_self, PyObject *__pyx_arg_X) { + __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_logsum (wrapper)", 0); + assert(__pyx_arg_X); { + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5_hmmc_dtype_t(__pyx_arg_X); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn._hmmc._logsum", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5_hmmc__logsum(__pyx_self, __pyx_v_X); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/_hmmc.pyx":24 * + * @cython.boundscheck(False) + * cpdef dtype_t _logsum(dtype_t[:] X): # <<<<<<<<<<<<<< + * cdef dtype_t vmax = _max(X) + * cdef dtype_t power_sum = 0 */ + +static PyObject *__pyx_pf_7sklearn_5_hmmc__logsum(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_logsum", 0); __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyFloat_FromDouble((log(__pyx_v_Xsum) + __pyx_v_maxv)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; + if (unlikely(!__pyx_v_X.memview)) { __Pyx_RaiseUnboundLocalError("X"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_1 = PyFloat_FromDouble(__pyx_f_7sklearn_5_hmmc__logsum(__pyx_v_X, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn._hmmc._logsum", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; - goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); - __pyx_L2:; + __PYX_XDEC_MEMVIEW(&__pyx_v_X, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/_hmmc.pyx":24 - * - * @cython.boundscheck(False) - * def _forward(int n_observations, int n_components, \ # <<<<<<<<<<<<<< - * np.ndarray[dtype_t, ndim=1] log_startprob, \ - * np.ndarray[dtype_t, ndim=2] log_transmat, \ - */ - -static PyObject *__pyx_pf_7sklearn_5_hmmc_1_forward(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7sklearn_5_hmmc_1_forward = {__Pyx_NAMESTR("_forward"), (PyCFunction)__pyx_pf_7sklearn_5_hmmc_1_forward, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; -static PyObject *__pyx_pf_7sklearn_5_hmmc_1_forward(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5_hmmc_3_forward(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_5_hmmc_3_forward = {__Pyx_NAMESTR("_forward"), (PyCFunction)__pyx_pw_7sklearn_5_hmmc_3_forward, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_5_hmmc_3_forward(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_n_observations; int __pyx_v_n_components; PyArrayObject *__pyx_v_log_startprob = 0; PyArrayObject *__pyx_v_log_transmat = 0; PyArrayObject *__pyx_v_framelogprob = 0; PyArrayObject *__pyx_v_fwdlattice = 0; - int __pyx_v_t; - int __pyx_v_i; - int __pyx_v_j; - PyArrayObject *__pyx_v_work_buffer = 0; - Py_buffer __pyx_bstruct_log_transmat; - Py_ssize_t __pyx_bstride_0_log_transmat = 0; - Py_ssize_t __pyx_bstride_1_log_transmat = 0; - Py_ssize_t __pyx_bshape_0_log_transmat = 0; - Py_ssize_t __pyx_bshape_1_log_transmat = 0; - Py_buffer __pyx_bstruct_framelogprob; - Py_ssize_t __pyx_bstride_0_framelogprob = 0; - Py_ssize_t __pyx_bstride_1_framelogprob = 0; - Py_ssize_t __pyx_bshape_0_framelogprob = 0; - Py_ssize_t __pyx_bshape_1_framelogprob = 0; - Py_buffer __pyx_bstruct_fwdlattice; - Py_ssize_t __pyx_bstride_0_fwdlattice = 0; - Py_ssize_t __pyx_bstride_1_fwdlattice = 0; - Py_ssize_t __pyx_bshape_0_fwdlattice = 0; - Py_ssize_t __pyx_bshape_1_fwdlattice = 0; - Py_buffer __pyx_bstruct_work_buffer; - Py_ssize_t __pyx_bstride_0_work_buffer = 0; - Py_ssize_t __pyx_bshape_0_work_buffer = 0; - Py_buffer __pyx_bstruct_log_startprob; - Py_ssize_t __pyx_bstride_0_log_startprob = 0; - Py_ssize_t __pyx_bshape_0_log_startprob = 0; - PyObject *__pyx_r = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyArrayObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; - int __pyx_t_10; - long __pyx_t_11; - int __pyx_t_12; - long __pyx_t_13; - int __pyx_t_14; - int __pyx_t_15; - int __pyx_t_16; - int __pyx_t_17; - int __pyx_t_18; - long __pyx_t_19; - int __pyx_t_20; - int __pyx_t_21; - int __pyx_t_22; - int __pyx_t_23; - __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_t_24; - int __pyx_t_25; - int __pyx_t_26; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_observations,&__pyx_n_s__n_components,&__pyx_n_s__log_startprob,&__pyx_n_s__log_transmat,&__pyx_n_s__framelogprob,&__pyx_n_s__fwdlattice,0}; - __Pyx_RefNannySetupContext("_forward"); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("_forward (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_observations,&__pyx_n_s__n_components,&__pyx_n_s__log_startprob,&__pyx_n_s__log_transmat,&__pyx_n_s__framelogprob,&__pyx_n_s__fwdlattice,0}; PyObject* values[6] = {0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); @@ -1261,44 +2112,38 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_1_forward(PyObject *__pyx_self, PyObje default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_observations); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_observations)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_components); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_components)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_startprob); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_startprob)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_transmat); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_transmat)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__framelogprob); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__framelogprob)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__fwdlattice); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__fwdlattice)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "_forward") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_forward") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 6) { goto __pyx_L5_argtuple_error; @@ -1310,8 +2155,8 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_1_forward(PyObject *__pyx_self, PyObje values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); } - __pyx_v_n_observations = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_observations == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_n_components = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_n_components == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_observations = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_observations == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_components = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_n_components == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_log_startprob = ((PyArrayObject *)values[2]); __pyx_v_log_transmat = ((PyArrayObject *)values[3]); __pyx_v_framelogprob = ((PyArrayObject *)values[4]); @@ -1319,96 +2164,170 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_1_forward(PyObject *__pyx_self, PyObje } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_forward", 1, 6, 6, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn._hmmc._forward", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_work_buffer.buf = NULL; - __pyx_bstruct_log_startprob.buf = NULL; - __pyx_bstruct_log_transmat.buf = NULL; - __pyx_bstruct_framelogprob.buf = NULL; - __pyx_bstruct_fwdlattice.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_startprob), __pyx_ptype_5numpy_ndarray, 1, "log_startprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_transmat), __pyx_ptype_5numpy_ndarray, 1, "log_transmat", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_framelogprob), __pyx_ptype_5numpy_ndarray, 1, "framelogprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_fwdlattice), __pyx_ptype_5numpy_ndarray, 1, "fwdlattice", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_startprob), __pyx_ptype_5numpy_ndarray, 1, "log_startprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_transmat), __pyx_ptype_5numpy_ndarray, 1, "log_transmat", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_framelogprob), __pyx_ptype_5numpy_ndarray, 1, "framelogprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_fwdlattice), __pyx_ptype_5numpy_ndarray, 1, "fwdlattice", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5_hmmc_2_forward(__pyx_self, __pyx_v_n_observations, __pyx_v_n_components, __pyx_v_log_startprob, __pyx_v_log_transmat, __pyx_v_framelogprob, __pyx_v_fwdlattice); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/_hmmc.pyx":35 + * + * @cython.boundscheck(False) + * def _forward(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=1] log_startprob, + * np.ndarray[dtype_t, ndim=2] log_transmat, + */ + +static PyObject *__pyx_pf_7sklearn_5_hmmc_2_forward(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_observations, int __pyx_v_n_components, PyArrayObject *__pyx_v_log_startprob, PyArrayObject *__pyx_v_log_transmat, PyArrayObject *__pyx_v_framelogprob, PyArrayObject *__pyx_v_fwdlattice) { + int __pyx_v_t; + int __pyx_v_i; + int __pyx_v_j; + PyArrayObject *__pyx_v_work_buffer = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_framelogprob; + __Pyx_Buffer __pyx_pybuffer_framelogprob; + __Pyx_LocalBuf_ND __pyx_pybuffernd_fwdlattice; + __Pyx_Buffer __pyx_pybuffer_fwdlattice; + __Pyx_LocalBuf_ND __pyx_pybuffernd_log_startprob; + __Pyx_Buffer __pyx_pybuffer_log_startprob; + __Pyx_LocalBuf_ND __pyx_pybuffernd_log_transmat; + __Pyx_Buffer __pyx_pybuffer_log_transmat; + __Pyx_LocalBuf_ND __pyx_pybuffernd_work_buffer; + __Pyx_Buffer __pyx_pybuffer_work_buffer; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyArrayObject *__pyx_t_4 = NULL; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + int __pyx_t_10; + long __pyx_t_11; + int __pyx_t_12; + long __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + int __pyx_t_17; + int __pyx_t_18; + long __pyx_t_19; + int __pyx_t_20; + int __pyx_t_21; + int __pyx_t_22; + int __pyx_t_23; + __Pyx_memviewslice __pyx_t_24 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_t_25; + int __pyx_t_26; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_forward", 0); + __pyx_pybuffer_work_buffer.pybuffer.buf = NULL; + __pyx_pybuffer_work_buffer.refcount = 0; + __pyx_pybuffernd_work_buffer.data = NULL; + __pyx_pybuffernd_work_buffer.rcbuffer = &__pyx_pybuffer_work_buffer; + __pyx_pybuffer_log_startprob.pybuffer.buf = NULL; + __pyx_pybuffer_log_startprob.refcount = 0; + __pyx_pybuffernd_log_startprob.data = NULL; + __pyx_pybuffernd_log_startprob.rcbuffer = &__pyx_pybuffer_log_startprob; + __pyx_pybuffer_log_transmat.pybuffer.buf = NULL; + __pyx_pybuffer_log_transmat.refcount = 0; + __pyx_pybuffernd_log_transmat.data = NULL; + __pyx_pybuffernd_log_transmat.rcbuffer = &__pyx_pybuffer_log_transmat; + __pyx_pybuffer_framelogprob.pybuffer.buf = NULL; + __pyx_pybuffer_framelogprob.refcount = 0; + __pyx_pybuffernd_framelogprob.data = NULL; + __pyx_pybuffernd_framelogprob.rcbuffer = &__pyx_pybuffer_framelogprob; + __pyx_pybuffer_fwdlattice.pybuffer.buf = NULL; + __pyx_pybuffer_fwdlattice.refcount = 0; + __pyx_pybuffernd_fwdlattice.data = NULL; + __pyx_pybuffernd_fwdlattice.rcbuffer = &__pyx_pybuffer_fwdlattice; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_log_startprob, (PyObject*)__pyx_v_log_startprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_log_startprob.rcbuffer->pybuffer, (PyObject*)__pyx_v_log_startprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_log_startprob = __pyx_bstruct_log_startprob.strides[0]; - __pyx_bshape_0_log_startprob = __pyx_bstruct_log_startprob.shape[0]; + __pyx_pybuffernd_log_startprob.diminfo[0].strides = __pyx_pybuffernd_log_startprob.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_log_startprob.diminfo[0].shape = __pyx_pybuffernd_log_startprob.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_log_transmat, (PyObject*)__pyx_v_log_transmat, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer, (PyObject*)__pyx_v_log_transmat, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_log_transmat = __pyx_bstruct_log_transmat.strides[0]; __pyx_bstride_1_log_transmat = __pyx_bstruct_log_transmat.strides[1]; - __pyx_bshape_0_log_transmat = __pyx_bstruct_log_transmat.shape[0]; __pyx_bshape_1_log_transmat = __pyx_bstruct_log_transmat.shape[1]; + __pyx_pybuffernd_log_transmat.diminfo[0].strides = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_log_transmat.diminfo[0].shape = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_log_transmat.diminfo[1].strides = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_log_transmat.diminfo[1].shape = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_framelogprob, (PyObject*)__pyx_v_framelogprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer, (PyObject*)__pyx_v_framelogprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_framelogprob = __pyx_bstruct_framelogprob.strides[0]; __pyx_bstride_1_framelogprob = __pyx_bstruct_framelogprob.strides[1]; - __pyx_bshape_0_framelogprob = __pyx_bstruct_framelogprob.shape[0]; __pyx_bshape_1_framelogprob = __pyx_bstruct_framelogprob.shape[1]; + __pyx_pybuffernd_framelogprob.diminfo[0].strides = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_framelogprob.diminfo[0].shape = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_framelogprob.diminfo[1].strides = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_framelogprob.diminfo[1].shape = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_fwdlattice, (PyObject*)__pyx_v_fwdlattice, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer, (PyObject*)__pyx_v_fwdlattice, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_fwdlattice = __pyx_bstruct_fwdlattice.strides[0]; __pyx_bstride_1_fwdlattice = __pyx_bstruct_fwdlattice.strides[1]; - __pyx_bshape_0_fwdlattice = __pyx_bstruct_fwdlattice.shape[0]; __pyx_bshape_1_fwdlattice = __pyx_bstruct_fwdlattice.shape[1]; + __pyx_pybuffernd_fwdlattice.diminfo[0].strides = __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_fwdlattice.diminfo[0].shape = __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_fwdlattice.diminfo[1].strides = __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_fwdlattice.diminfo[1].shape = __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.shape[1]; - /* "sklearn/_hmmc.pyx":33 + /* "sklearn/_hmmc.pyx":44 * cdef double logprob * cdef np.ndarray[dtype_t, ndim = 1] work_buffer * work_buffer = np.zeros(n_components) # <<<<<<<<<<<<<< * - * for i in xrange(n_components): + * for i in range(n_components): */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromLong(__pyx_v_n_components); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyInt_FromLong(__pyx_v_n_components); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_work_buffer); - __pyx_t_5 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_work_buffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer); + __pyx_t_5 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); if (unlikely(__pyx_t_5 < 0)) { PyErr_Fetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_work_buffer, (PyObject*)__pyx_v_work_buffer, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer, (PyObject*)__pyx_v_work_buffer, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_6); Py_XDECREF(__pyx_t_7); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_6, __pyx_t_7, __pyx_t_8); } } - __pyx_bstride_0_work_buffer = __pyx_bstruct_work_buffer.strides[0]; - __pyx_bshape_0_work_buffer = __pyx_bstruct_work_buffer.shape[0]; - if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_pybuffernd_work_buffer.diminfo[0].strides = __pyx_pybuffernd_work_buffer.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_work_buffer.diminfo[0].shape = __pyx_pybuffernd_work_buffer.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_4 = 0; __pyx_v_work_buffer = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/_hmmc.pyx":35 + /* "sklearn/_hmmc.pyx":46 * work_buffer = np.zeros(n_components) * - * for i in xrange(n_components): # <<<<<<<<<<<<<< + * for i in range(n_components): # <<<<<<<<<<<<<< * fwdlattice[0, i] = log_startprob[i] + framelogprob[0, i] * */ @@ -1416,135 +2335,98 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_1_forward(PyObject *__pyx_self, PyObje for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_5; __pyx_t_9+=1) { __pyx_v_i = __pyx_t_9; - /* "sklearn/_hmmc.pyx":36 + /* "sklearn/_hmmc.pyx":47 * - * for i in xrange(n_components): + * for i in range(n_components): * fwdlattice[0, i] = log_startprob[i] + framelogprob[0, i] # <<<<<<<<<<<<<< * - * for t in xrange(1, n_observations): + * for t in range(1, n_observations): */ __pyx_t_10 = __pyx_v_i; - if (__pyx_t_10 < 0) __pyx_t_10 += __pyx_bshape_0_log_startprob; + if (__pyx_t_10 < 0) __pyx_t_10 += __pyx_pybuffernd_log_startprob.diminfo[0].shape; __pyx_t_11 = 0; __pyx_t_12 = __pyx_v_i; - if (__pyx_t_11 < 0) __pyx_t_11 += __pyx_bshape_0_framelogprob; - if (__pyx_t_12 < 0) __pyx_t_12 += __pyx_bshape_1_framelogprob; + if (__pyx_t_11 < 0) __pyx_t_11 += __pyx_pybuffernd_framelogprob.diminfo[0].shape; + if (__pyx_t_12 < 0) __pyx_t_12 += __pyx_pybuffernd_framelogprob.diminfo[1].shape; __pyx_t_13 = 0; __pyx_t_14 = __pyx_v_i; - if (__pyx_t_13 < 0) __pyx_t_13 += __pyx_bshape_0_fwdlattice; - if (__pyx_t_14 < 0) __pyx_t_14 += __pyx_bshape_1_fwdlattice; - *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_fwdlattice.buf, __pyx_t_13, __pyx_bstride_0_fwdlattice, __pyx_t_14, __pyx_bstride_1_fwdlattice) = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_log_startprob.buf, __pyx_t_10, __pyx_bstride_0_log_startprob)) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_framelogprob.buf, __pyx_t_11, __pyx_bstride_0_framelogprob, __pyx_t_12, __pyx_bstride_1_framelogprob))); + if (__pyx_t_13 < 0) __pyx_t_13 += __pyx_pybuffernd_fwdlattice.diminfo[0].shape; + if (__pyx_t_14 < 0) __pyx_t_14 += __pyx_pybuffernd_fwdlattice.diminfo[1].shape; + *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_fwdlattice.diminfo[0].strides, __pyx_t_14, __pyx_pybuffernd_fwdlattice.diminfo[1].strides) = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_log_startprob.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_log_startprob.diminfo[0].strides)) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_framelogprob.diminfo[0].strides, __pyx_t_12, __pyx_pybuffernd_framelogprob.diminfo[1].strides))); } - /* "sklearn/_hmmc.pyx":38 + /* "sklearn/_hmmc.pyx":49 * fwdlattice[0, i] = log_startprob[i] + framelogprob[0, i] * - * for t in xrange(1, n_observations): # <<<<<<<<<<<<<< - * for j in xrange(n_components): - * for i in xrange(n_components): + * for t in range(1, n_observations): # <<<<<<<<<<<<<< + * for j in range(n_components): + * for i in range(n_components): */ __pyx_t_5 = __pyx_v_n_observations; for (__pyx_t_9 = 1; __pyx_t_9 < __pyx_t_5; __pyx_t_9+=1) { __pyx_v_t = __pyx_t_9; - /* "sklearn/_hmmc.pyx":39 + /* "sklearn/_hmmc.pyx":50 * - * for t in xrange(1, n_observations): - * for j in xrange(n_components): # <<<<<<<<<<<<<< - * for i in xrange(n_components): + * for t in range(1, n_observations): + * for j in range(n_components): # <<<<<<<<<<<<<< + * for i in range(n_components): * work_buffer[i] = fwdlattice[t - 1, i] + log_transmat[i, j] */ __pyx_t_15 = __pyx_v_n_components; for (__pyx_t_16 = 0; __pyx_t_16 < __pyx_t_15; __pyx_t_16+=1) { __pyx_v_j = __pyx_t_16; - /* "sklearn/_hmmc.pyx":40 - * for t in xrange(1, n_observations): - * for j in xrange(n_components): - * for i in xrange(n_components): # <<<<<<<<<<<<<< + /* "sklearn/_hmmc.pyx":51 + * for t in range(1, n_observations): + * for j in range(n_components): + * for i in range(n_components): # <<<<<<<<<<<<<< * work_buffer[i] = fwdlattice[t - 1, i] + log_transmat[i, j] - * fwdlattice[t, j] = _logsum(n_components, work_buffer) \ + * fwdlattice[t, j] = _logsum(work_buffer) + framelogprob[t, j] */ __pyx_t_17 = __pyx_v_n_components; for (__pyx_t_18 = 0; __pyx_t_18 < __pyx_t_17; __pyx_t_18+=1) { __pyx_v_i = __pyx_t_18; - /* "sklearn/_hmmc.pyx":41 - * for j in xrange(n_components): - * for i in xrange(n_components): + /* "sklearn/_hmmc.pyx":52 + * for j in range(n_components): + * for i in range(n_components): * work_buffer[i] = fwdlattice[t - 1, i] + log_transmat[i, j] # <<<<<<<<<<<<<< - * fwdlattice[t, j] = _logsum(n_components, work_buffer) \ - * + framelogprob[t, j] + * fwdlattice[t, j] = _logsum(work_buffer) + framelogprob[t, j] + * */ __pyx_t_19 = (__pyx_v_t - 1); __pyx_t_20 = __pyx_v_i; - if (__pyx_t_19 < 0) __pyx_t_19 += __pyx_bshape_0_fwdlattice; - if (__pyx_t_20 < 0) __pyx_t_20 += __pyx_bshape_1_fwdlattice; + if (__pyx_t_19 < 0) __pyx_t_19 += __pyx_pybuffernd_fwdlattice.diminfo[0].shape; + if (__pyx_t_20 < 0) __pyx_t_20 += __pyx_pybuffernd_fwdlattice.diminfo[1].shape; __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_j; - if (__pyx_t_21 < 0) __pyx_t_21 += __pyx_bshape_0_log_transmat; - if (__pyx_t_22 < 0) __pyx_t_22 += __pyx_bshape_1_log_transmat; + if (__pyx_t_21 < 0) __pyx_t_21 += __pyx_pybuffernd_log_transmat.diminfo[0].shape; + if (__pyx_t_22 < 0) __pyx_t_22 += __pyx_pybuffernd_log_transmat.diminfo[1].shape; __pyx_t_23 = __pyx_v_i; - if (__pyx_t_23 < 0) __pyx_t_23 += __pyx_bshape_0_work_buffer; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_work_buffer.buf, __pyx_t_23, __pyx_bstride_0_work_buffer) = ((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_fwdlattice.buf, __pyx_t_19, __pyx_bstride_0_fwdlattice, __pyx_t_20, __pyx_bstride_1_fwdlattice)) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_log_transmat.buf, __pyx_t_21, __pyx_bstride_0_log_transmat, __pyx_t_22, __pyx_bstride_1_log_transmat))); + if (__pyx_t_23 < 0) __pyx_t_23 += __pyx_pybuffernd_work_buffer.diminfo[0].shape; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_work_buffer.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_work_buffer.diminfo[0].strides) = ((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_fwdlattice.diminfo[0].strides, __pyx_t_20, __pyx_pybuffernd_fwdlattice.diminfo[1].strides)) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_log_transmat.diminfo[0].strides, __pyx_t_22, __pyx_pybuffernd_log_transmat.diminfo[1].strides))); } - /* "sklearn/_hmmc.pyx":42 - * for i in xrange(n_components): - * work_buffer[i] = fwdlattice[t - 1, i] + log_transmat[i, j] - * fwdlattice[t, j] = _logsum(n_components, work_buffer) \ # <<<<<<<<<<<<<< - * + framelogprob[t, j] - * - */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s___logsum); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyInt_FromLong(__pyx_v_n_components); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_work_buffer)); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_work_buffer)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_work_buffer)); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - - /* "sklearn/_hmmc.pyx":43 + /* "sklearn/_hmmc.pyx":53 + * for i in range(n_components): * work_buffer[i] = fwdlattice[t - 1, i] + log_transmat[i, j] - * fwdlattice[t, j] = _logsum(n_components, work_buffer) \ - * + framelogprob[t, j] # <<<<<<<<<<<<<< + * fwdlattice[t, j] = _logsum(work_buffer) + framelogprob[t, j] # <<<<<<<<<<<<<< * * */ + __pyx_t_24 = __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5_hmmc_dtype_t(((PyObject *)__pyx_v_work_buffer)); + if (unlikely(!__pyx_t_24.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_17 = __pyx_v_t; __pyx_t_18 = __pyx_v_j; - if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_bshape_0_framelogprob; - if (__pyx_t_18 < 0) __pyx_t_18 += __pyx_bshape_1_framelogprob; - __pyx_t_2 = PyFloat_FromDouble((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_framelogprob.buf, __pyx_t_17, __pyx_bstride_0_framelogprob, __pyx_t_18, __pyx_bstride_1_framelogprob))); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Add(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_24 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_24 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "sklearn/_hmmc.pyx":42 - * for i in xrange(n_components): - * work_buffer[i] = fwdlattice[t - 1, i] + log_transmat[i, j] - * fwdlattice[t, j] = _logsum(n_components, work_buffer) \ # <<<<<<<<<<<<<< - * + framelogprob[t, j] - * - */ + if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_pybuffernd_framelogprob.diminfo[0].shape; + if (__pyx_t_18 < 0) __pyx_t_18 += __pyx_pybuffernd_framelogprob.diminfo[1].shape; __pyx_t_25 = __pyx_v_t; __pyx_t_26 = __pyx_v_j; - if (__pyx_t_25 < 0) __pyx_t_25 += __pyx_bshape_0_fwdlattice; - if (__pyx_t_26 < 0) __pyx_t_26 += __pyx_bshape_1_fwdlattice; - *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_fwdlattice.buf, __pyx_t_25, __pyx_bstride_0_fwdlattice, __pyx_t_26, __pyx_bstride_1_fwdlattice) = __pyx_t_24; + if (__pyx_t_25 < 0) __pyx_t_25 += __pyx_pybuffernd_fwdlattice.diminfo[0].shape; + if (__pyx_t_26 < 0) __pyx_t_26 += __pyx_pybuffernd_fwdlattice.diminfo[1].shape; + *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_fwdlattice.diminfo[0].strides, __pyx_t_26, __pyx_pybuffernd_fwdlattice.diminfo[1].strides) = (__pyx_f_7sklearn_5_hmmc__logsum(__pyx_t_24, 0) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_framelogprob.diminfo[0].strides, __pyx_t_18, __pyx_pybuffernd_framelogprob.diminfo[1].strides))); + __PYX_XDEC_MEMVIEW(&__pyx_t_24, 1); } } @@ -1554,23 +2436,24 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_1_forward(PyObject *__pyx_self, PyObje __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); + __PYX_XDEC_MEMVIEW(&__pyx_t_24, 1); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_transmat); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_framelogprob); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_fwdlattice); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_work_buffer); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_startprob); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_startprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn._hmmc._forward", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_transmat); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_framelogprob); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_fwdlattice); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_work_buffer); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_startprob); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_startprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_work_buffer); __Pyx_XGIVEREF(__pyx_r); @@ -1578,83 +2461,29 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_1_forward(PyObject *__pyx_self, PyObje return __pyx_r; } -/* "sklearn/_hmmc.pyx":47 - * - * @cython.boundscheck(False) - * def _backward(int n_observations, int n_components, \ # <<<<<<<<<<<<<< - * np.ndarray[dtype_t, ndim=1] log_startprob, \ - * np.ndarray[dtype_t, ndim=2] log_transmat, \ - */ - -static PyObject *__pyx_pf_7sklearn_5_hmmc_2_backward(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7sklearn_5_hmmc_2_backward = {__Pyx_NAMESTR("_backward"), (PyCFunction)__pyx_pf_7sklearn_5_hmmc_2_backward, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; -static PyObject *__pyx_pf_7sklearn_5_hmmc_2_backward(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5_hmmc_5_backward(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_5_hmmc_5_backward = {__Pyx_NAMESTR("_backward"), (PyCFunction)__pyx_pw_7sklearn_5_hmmc_5_backward, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_5_hmmc_5_backward(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_n_observations; int __pyx_v_n_components; - PyArrayObject *__pyx_v_log_startprob = 0; + CYTHON_UNUSED PyArrayObject *__pyx_v_log_startprob = 0; PyArrayObject *__pyx_v_log_transmat = 0; PyArrayObject *__pyx_v_framelogprob = 0; PyArrayObject *__pyx_v_bwdlattice = 0; - int __pyx_v_t; - int __pyx_v_i; - int __pyx_v_j; - PyArrayObject *__pyx_v_work_buffer = 0; - Py_buffer __pyx_bstruct_log_transmat; - Py_ssize_t __pyx_bstride_0_log_transmat = 0; - Py_ssize_t __pyx_bstride_1_log_transmat = 0; - Py_ssize_t __pyx_bshape_0_log_transmat = 0; - Py_ssize_t __pyx_bshape_1_log_transmat = 0; - Py_buffer __pyx_bstruct_framelogprob; - Py_ssize_t __pyx_bstride_0_framelogprob = 0; - Py_ssize_t __pyx_bstride_1_framelogprob = 0; - Py_ssize_t __pyx_bshape_0_framelogprob = 0; - Py_ssize_t __pyx_bshape_1_framelogprob = 0; - Py_buffer __pyx_bstruct_bwdlattice; - Py_ssize_t __pyx_bstride_0_bwdlattice = 0; - Py_ssize_t __pyx_bstride_1_bwdlattice = 0; - Py_ssize_t __pyx_bshape_0_bwdlattice = 0; - Py_ssize_t __pyx_bshape_1_bwdlattice = 0; - Py_buffer __pyx_bstruct_work_buffer; - Py_ssize_t __pyx_bstride_0_work_buffer = 0; - Py_ssize_t __pyx_bshape_0_work_buffer = 0; - Py_buffer __pyx_bstruct_log_startprob; - Py_ssize_t __pyx_bstride_0_log_startprob = 0; - Py_ssize_t __pyx_bshape_0_log_startprob = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyArrayObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; - long __pyx_t_10; - int __pyx_t_11; - int __pyx_t_12; - int __pyx_t_13; - int __pyx_t_14; - int __pyx_t_15; - int __pyx_t_16; - long __pyx_t_17; - int __pyx_t_18; - long __pyx_t_19; - int __pyx_t_20; - int __pyx_t_21; - __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_t_22; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_observations,&__pyx_n_s__n_components,&__pyx_n_s__log_startprob,&__pyx_n_s__log_transmat,&__pyx_n_s__framelogprob,&__pyx_n_s__bwdlattice,0}; - __Pyx_RefNannySetupContext("_backward"); - __pyx_self = __pyx_self; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_backward (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_observations,&__pyx_n_s__n_components,&__pyx_n_s__log_startprob,&__pyx_n_s__log_transmat,&__pyx_n_s__framelogprob,&__pyx_n_s__bwdlattice,0}; PyObject* values[6] = {0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); @@ -1665,44 +2494,38 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_2_backward(PyObject *__pyx_self, PyObj default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_observations); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_observations)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_components); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_components)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_startprob); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_startprob)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_transmat); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_transmat)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__framelogprob); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__framelogprob)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__bwdlattice); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__bwdlattice)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "_backward") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_backward") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 6) { goto __pyx_L5_argtuple_error; @@ -1714,8 +2537,8 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_2_backward(PyObject *__pyx_self, PyObj values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); } - __pyx_v_n_observations = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_observations == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_n_components = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_n_components == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_observations = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_observations == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_components = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_n_components == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_log_startprob = ((PyArrayObject *)values[2]); __pyx_v_log_transmat = ((PyArrayObject *)values[3]); __pyx_v_framelogprob = ((PyArrayObject *)values[4]); @@ -1723,96 +2546,166 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_2_backward(PyObject *__pyx_self, PyObj } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_backward", 1, 6, 6, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn._hmmc._backward", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_work_buffer.buf = NULL; - __pyx_bstruct_log_startprob.buf = NULL; - __pyx_bstruct_log_transmat.buf = NULL; - __pyx_bstruct_framelogprob.buf = NULL; - __pyx_bstruct_bwdlattice.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_startprob), __pyx_ptype_5numpy_ndarray, 1, "log_startprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_transmat), __pyx_ptype_5numpy_ndarray, 1, "log_transmat", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_framelogprob), __pyx_ptype_5numpy_ndarray, 1, "framelogprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_bwdlattice), __pyx_ptype_5numpy_ndarray, 1, "bwdlattice", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_startprob), __pyx_ptype_5numpy_ndarray, 1, "log_startprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_transmat), __pyx_ptype_5numpy_ndarray, 1, "log_transmat", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_framelogprob), __pyx_ptype_5numpy_ndarray, 1, "framelogprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_bwdlattice), __pyx_ptype_5numpy_ndarray, 1, "bwdlattice", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5_hmmc_4_backward(__pyx_self, __pyx_v_n_observations, __pyx_v_n_components, __pyx_v_log_startprob, __pyx_v_log_transmat, __pyx_v_framelogprob, __pyx_v_bwdlattice); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/_hmmc.pyx":57 + * + * @cython.boundscheck(False) + * def _backward(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=1] log_startprob, + * np.ndarray[dtype_t, ndim=2] log_transmat, + */ + +static PyObject *__pyx_pf_7sklearn_5_hmmc_4_backward(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_observations, int __pyx_v_n_components, CYTHON_UNUSED PyArrayObject *__pyx_v_log_startprob, PyArrayObject *__pyx_v_log_transmat, PyArrayObject *__pyx_v_framelogprob, PyArrayObject *__pyx_v_bwdlattice) { + int __pyx_v_t; + int __pyx_v_i; + int __pyx_v_j; + PyArrayObject *__pyx_v_work_buffer = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_bwdlattice; + __Pyx_Buffer __pyx_pybuffer_bwdlattice; + __Pyx_LocalBuf_ND __pyx_pybuffernd_framelogprob; + __Pyx_Buffer __pyx_pybuffer_framelogprob; + __Pyx_LocalBuf_ND __pyx_pybuffernd_log_startprob; + __Pyx_Buffer __pyx_pybuffer_log_startprob; + __Pyx_LocalBuf_ND __pyx_pybuffernd_log_transmat; + __Pyx_Buffer __pyx_pybuffer_log_transmat; + __Pyx_LocalBuf_ND __pyx_pybuffernd_work_buffer; + __Pyx_Buffer __pyx_pybuffer_work_buffer; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyArrayObject *__pyx_t_4 = NULL; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + long __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + long __pyx_t_17; + int __pyx_t_18; + long __pyx_t_19; + int __pyx_t_20; + int __pyx_t_21; + __Pyx_memviewslice __pyx_t_22 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_backward", 0); + __pyx_pybuffer_work_buffer.pybuffer.buf = NULL; + __pyx_pybuffer_work_buffer.refcount = 0; + __pyx_pybuffernd_work_buffer.data = NULL; + __pyx_pybuffernd_work_buffer.rcbuffer = &__pyx_pybuffer_work_buffer; + __pyx_pybuffer_log_startprob.pybuffer.buf = NULL; + __pyx_pybuffer_log_startprob.refcount = 0; + __pyx_pybuffernd_log_startprob.data = NULL; + __pyx_pybuffernd_log_startprob.rcbuffer = &__pyx_pybuffer_log_startprob; + __pyx_pybuffer_log_transmat.pybuffer.buf = NULL; + __pyx_pybuffer_log_transmat.refcount = 0; + __pyx_pybuffernd_log_transmat.data = NULL; + __pyx_pybuffernd_log_transmat.rcbuffer = &__pyx_pybuffer_log_transmat; + __pyx_pybuffer_framelogprob.pybuffer.buf = NULL; + __pyx_pybuffer_framelogprob.refcount = 0; + __pyx_pybuffernd_framelogprob.data = NULL; + __pyx_pybuffernd_framelogprob.rcbuffer = &__pyx_pybuffer_framelogprob; + __pyx_pybuffer_bwdlattice.pybuffer.buf = NULL; + __pyx_pybuffer_bwdlattice.refcount = 0; + __pyx_pybuffernd_bwdlattice.data = NULL; + __pyx_pybuffernd_bwdlattice.rcbuffer = &__pyx_pybuffer_bwdlattice; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_log_startprob, (PyObject*)__pyx_v_log_startprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_log_startprob.rcbuffer->pybuffer, (PyObject*)__pyx_v_log_startprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_log_startprob = __pyx_bstruct_log_startprob.strides[0]; - __pyx_bshape_0_log_startprob = __pyx_bstruct_log_startprob.shape[0]; + __pyx_pybuffernd_log_startprob.diminfo[0].strides = __pyx_pybuffernd_log_startprob.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_log_startprob.diminfo[0].shape = __pyx_pybuffernd_log_startprob.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_log_transmat, (PyObject*)__pyx_v_log_transmat, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer, (PyObject*)__pyx_v_log_transmat, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_log_transmat = __pyx_bstruct_log_transmat.strides[0]; __pyx_bstride_1_log_transmat = __pyx_bstruct_log_transmat.strides[1]; - __pyx_bshape_0_log_transmat = __pyx_bstruct_log_transmat.shape[0]; __pyx_bshape_1_log_transmat = __pyx_bstruct_log_transmat.shape[1]; + __pyx_pybuffernd_log_transmat.diminfo[0].strides = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_log_transmat.diminfo[0].shape = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_log_transmat.diminfo[1].strides = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_log_transmat.diminfo[1].shape = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_framelogprob, (PyObject*)__pyx_v_framelogprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer, (PyObject*)__pyx_v_framelogprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_framelogprob = __pyx_bstruct_framelogprob.strides[0]; __pyx_bstride_1_framelogprob = __pyx_bstruct_framelogprob.strides[1]; - __pyx_bshape_0_framelogprob = __pyx_bstruct_framelogprob.shape[0]; __pyx_bshape_1_framelogprob = __pyx_bstruct_framelogprob.shape[1]; + __pyx_pybuffernd_framelogprob.diminfo[0].strides = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_framelogprob.diminfo[0].shape = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_framelogprob.diminfo[1].strides = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_framelogprob.diminfo[1].shape = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_bwdlattice, (PyObject*)__pyx_v_bwdlattice, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer, (PyObject*)__pyx_v_bwdlattice, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_bwdlattice = __pyx_bstruct_bwdlattice.strides[0]; __pyx_bstride_1_bwdlattice = __pyx_bstruct_bwdlattice.strides[1]; - __pyx_bshape_0_bwdlattice = __pyx_bstruct_bwdlattice.shape[0]; __pyx_bshape_1_bwdlattice = __pyx_bstruct_bwdlattice.shape[1]; + __pyx_pybuffernd_bwdlattice.diminfo[0].strides = __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_bwdlattice.diminfo[0].shape = __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_bwdlattice.diminfo[1].strides = __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_bwdlattice.diminfo[1].shape = __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.shape[1]; - /* "sklearn/_hmmc.pyx":56 + /* "sklearn/_hmmc.pyx":66 * cdef double logprob * cdef np.ndarray[dtype_t, ndim = 1] work_buffer * work_buffer = np.zeros(n_components) # <<<<<<<<<<<<<< * - * for i in xrange(n_components): + * for i in range(n_components): */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromLong(__pyx_v_n_components); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyInt_FromLong(__pyx_v_n_components); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_work_buffer); - __pyx_t_5 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_work_buffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer); + __pyx_t_5 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); if (unlikely(__pyx_t_5 < 0)) { PyErr_Fetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_work_buffer, (PyObject*)__pyx_v_work_buffer, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer, (PyObject*)__pyx_v_work_buffer, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_6); Py_XDECREF(__pyx_t_7); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_6, __pyx_t_7, __pyx_t_8); } } - __pyx_bstride_0_work_buffer = __pyx_bstruct_work_buffer.strides[0]; - __pyx_bshape_0_work_buffer = __pyx_bstruct_work_buffer.shape[0]; - if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_pybuffernd_work_buffer.diminfo[0].strides = __pyx_pybuffernd_work_buffer.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_work_buffer.diminfo[0].shape = __pyx_pybuffernd_work_buffer.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_4 = 0; __pyx_v_work_buffer = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/_hmmc.pyx":58 + /* "sklearn/_hmmc.pyx":68 * work_buffer = np.zeros(n_components) * - * for i in xrange(n_components): # <<<<<<<<<<<<<< + * for i in range(n_components): # <<<<<<<<<<<<<< * bwdlattice[n_observations - 1, i] = 0.0 * */ @@ -1820,45 +2713,45 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_2_backward(PyObject *__pyx_self, PyObj for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_5; __pyx_t_9+=1) { __pyx_v_i = __pyx_t_9; - /* "sklearn/_hmmc.pyx":59 + /* "sklearn/_hmmc.pyx":69 * - * for i in xrange(n_components): + * for i in range(n_components): * bwdlattice[n_observations - 1, i] = 0.0 # <<<<<<<<<<<<<< * - * for t in xrange(n_observations - 2, -1, -1): + * for t in range(n_observations - 2, -1, -1): */ __pyx_t_10 = (__pyx_v_n_observations - 1); __pyx_t_11 = __pyx_v_i; - if (__pyx_t_10 < 0) __pyx_t_10 += __pyx_bshape_0_bwdlattice; - if (__pyx_t_11 < 0) __pyx_t_11 += __pyx_bshape_1_bwdlattice; - *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_bwdlattice.buf, __pyx_t_10, __pyx_bstride_0_bwdlattice, __pyx_t_11, __pyx_bstride_1_bwdlattice) = 0.0; + if (__pyx_t_10 < 0) __pyx_t_10 += __pyx_pybuffernd_bwdlattice.diminfo[0].shape; + if (__pyx_t_11 < 0) __pyx_t_11 += __pyx_pybuffernd_bwdlattice.diminfo[1].shape; + *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_bwdlattice.diminfo[0].strides, __pyx_t_11, __pyx_pybuffernd_bwdlattice.diminfo[1].strides) = 0.0; } - /* "sklearn/_hmmc.pyx":61 + /* "sklearn/_hmmc.pyx":71 * bwdlattice[n_observations - 1, i] = 0.0 * - * for t in xrange(n_observations - 2, -1, -1): # <<<<<<<<<<<<<< - * for i in xrange(n_components): - * for j in xrange(n_components): + * for t in range(n_observations - 2, -1, -1): # <<<<<<<<<<<<<< + * for i in range(n_components): + * for j in range(n_components): */ for (__pyx_t_5 = (__pyx_v_n_observations - 2); __pyx_t_5 > -1; __pyx_t_5-=1) { __pyx_v_t = __pyx_t_5; - /* "sklearn/_hmmc.pyx":62 + /* "sklearn/_hmmc.pyx":72 * - * for t in xrange(n_observations - 2, -1, -1): - * for i in xrange(n_components): # <<<<<<<<<<<<<< - * for j in xrange(n_components): + * for t in range(n_observations - 2, -1, -1): + * for i in range(n_components): # <<<<<<<<<<<<<< + * for j in range(n_components): * work_buffer[j] = log_transmat[i, j] + framelogprob[t + 1, j] \ */ __pyx_t_9 = __pyx_v_n_components; for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_9; __pyx_t_12+=1) { __pyx_v_i = __pyx_t_12; - /* "sklearn/_hmmc.pyx":63 - * for t in xrange(n_observations - 2, -1, -1): - * for i in xrange(n_components): - * for j in xrange(n_components): # <<<<<<<<<<<<<< + /* "sklearn/_hmmc.pyx":73 + * for t in range(n_observations - 2, -1, -1): + * for i in range(n_components): + * for j in range(n_components): # <<<<<<<<<<<<<< * work_buffer[j] = log_transmat[i, j] + framelogprob[t + 1, j] \ * + bwdlattice[t + 1, j] */ @@ -1866,76 +2759,61 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_2_backward(PyObject *__pyx_self, PyObj for (__pyx_t_14 = 0; __pyx_t_14 < __pyx_t_13; __pyx_t_14+=1) { __pyx_v_j = __pyx_t_14; - /* "sklearn/_hmmc.pyx":64 - * for i in xrange(n_components): - * for j in xrange(n_components): + /* "sklearn/_hmmc.pyx":74 + * for i in range(n_components): + * for j in range(n_components): * work_buffer[j] = log_transmat[i, j] + framelogprob[t + 1, j] \ # <<<<<<<<<<<<<< * + bwdlattice[t + 1, j] - * bwdlattice[t, i] = _logsum(n_components, work_buffer) + * bwdlattice[t, i] = _logsum(work_buffer) */ __pyx_t_15 = __pyx_v_i; __pyx_t_16 = __pyx_v_j; - if (__pyx_t_15 < 0) __pyx_t_15 += __pyx_bshape_0_log_transmat; - if (__pyx_t_16 < 0) __pyx_t_16 += __pyx_bshape_1_log_transmat; + if (__pyx_t_15 < 0) __pyx_t_15 += __pyx_pybuffernd_log_transmat.diminfo[0].shape; + if (__pyx_t_16 < 0) __pyx_t_16 += __pyx_pybuffernd_log_transmat.diminfo[1].shape; __pyx_t_17 = (__pyx_v_t + 1); __pyx_t_18 = __pyx_v_j; - if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_bshape_0_framelogprob; - if (__pyx_t_18 < 0) __pyx_t_18 += __pyx_bshape_1_framelogprob; + if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_pybuffernd_framelogprob.diminfo[0].shape; + if (__pyx_t_18 < 0) __pyx_t_18 += __pyx_pybuffernd_framelogprob.diminfo[1].shape; - /* "sklearn/_hmmc.pyx":65 - * for j in xrange(n_components): + /* "sklearn/_hmmc.pyx":75 + * for j in range(n_components): * work_buffer[j] = log_transmat[i, j] + framelogprob[t + 1, j] \ * + bwdlattice[t + 1, j] # <<<<<<<<<<<<<< - * bwdlattice[t, i] = _logsum(n_components, work_buffer) + * bwdlattice[t, i] = _logsum(work_buffer) * */ __pyx_t_19 = (__pyx_v_t + 1); __pyx_t_20 = __pyx_v_j; - if (__pyx_t_19 < 0) __pyx_t_19 += __pyx_bshape_0_bwdlattice; - if (__pyx_t_20 < 0) __pyx_t_20 += __pyx_bshape_1_bwdlattice; + if (__pyx_t_19 < 0) __pyx_t_19 += __pyx_pybuffernd_bwdlattice.diminfo[0].shape; + if (__pyx_t_20 < 0) __pyx_t_20 += __pyx_pybuffernd_bwdlattice.diminfo[1].shape; - /* "sklearn/_hmmc.pyx":64 - * for i in xrange(n_components): - * for j in xrange(n_components): + /* "sklearn/_hmmc.pyx":74 + * for i in range(n_components): + * for j in range(n_components): * work_buffer[j] = log_transmat[i, j] + framelogprob[t + 1, j] \ # <<<<<<<<<<<<<< * + bwdlattice[t + 1, j] - * bwdlattice[t, i] = _logsum(n_components, work_buffer) + * bwdlattice[t, i] = _logsum(work_buffer) */ __pyx_t_21 = __pyx_v_j; - if (__pyx_t_21 < 0) __pyx_t_21 += __pyx_bshape_0_work_buffer; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_work_buffer.buf, __pyx_t_21, __pyx_bstride_0_work_buffer) = (((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_log_transmat.buf, __pyx_t_15, __pyx_bstride_0_log_transmat, __pyx_t_16, __pyx_bstride_1_log_transmat)) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_framelogprob.buf, __pyx_t_17, __pyx_bstride_0_framelogprob, __pyx_t_18, __pyx_bstride_1_framelogprob))) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_bwdlattice.buf, __pyx_t_19, __pyx_bstride_0_bwdlattice, __pyx_t_20, __pyx_bstride_1_bwdlattice))); + if (__pyx_t_21 < 0) __pyx_t_21 += __pyx_pybuffernd_work_buffer.diminfo[0].shape; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_work_buffer.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_work_buffer.diminfo[0].strides) = (((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_log_transmat.diminfo[0].strides, __pyx_t_16, __pyx_pybuffernd_log_transmat.diminfo[1].strides)) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_framelogprob.diminfo[0].strides, __pyx_t_18, __pyx_pybuffernd_framelogprob.diminfo[1].strides))) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_bwdlattice.diminfo[0].strides, __pyx_t_20, __pyx_pybuffernd_bwdlattice.diminfo[1].strides))); } - /* "sklearn/_hmmc.pyx":66 + /* "sklearn/_hmmc.pyx":76 * work_buffer[j] = log_transmat[i, j] + framelogprob[t + 1, j] \ * + bwdlattice[t + 1, j] - * bwdlattice[t, i] = _logsum(n_components, work_buffer) # <<<<<<<<<<<<<< + * bwdlattice[t, i] = _logsum(work_buffer) # <<<<<<<<<<<<<< * * */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s___logsum); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyInt_FromLong(__pyx_v_n_components); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_work_buffer)); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_work_buffer)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_work_buffer)); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_22 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_22 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_22 = __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5_hmmc_dtype_t(((PyObject *)__pyx_v_work_buffer)); + if (unlikely(!__pyx_t_22.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_13 = __pyx_v_t; __pyx_t_14 = __pyx_v_i; - if (__pyx_t_13 < 0) __pyx_t_13 += __pyx_bshape_0_bwdlattice; - if (__pyx_t_14 < 0) __pyx_t_14 += __pyx_bshape_1_bwdlattice; - *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_bwdlattice.buf, __pyx_t_13, __pyx_bstride_0_bwdlattice, __pyx_t_14, __pyx_bstride_1_bwdlattice) = __pyx_t_22; + if (__pyx_t_13 < 0) __pyx_t_13 += __pyx_pybuffernd_bwdlattice.diminfo[0].shape; + if (__pyx_t_14 < 0) __pyx_t_14 += __pyx_pybuffernd_bwdlattice.diminfo[1].shape; + *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_bwdlattice.diminfo[0].strides, __pyx_t_14, __pyx_pybuffernd_bwdlattice.diminfo[1].strides) = __pyx_f_7sklearn_5_hmmc__logsum(__pyx_t_22, 0); + __PYX_XDEC_MEMVIEW(&__pyx_t_22, 1); } } @@ -1945,23 +2823,24 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_2_backward(PyObject *__pyx_self, PyObj __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); + __PYX_XDEC_MEMVIEW(&__pyx_t_22, 1); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_transmat); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_framelogprob); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_bwdlattice); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_work_buffer); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_startprob); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_startprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn._hmmc._backward", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_transmat); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_framelogprob); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_bwdlattice); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_work_buffer); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_startprob); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_startprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_work_buffer); __Pyx_XGIVEREF(__pyx_r); @@ -1969,17 +2848,10 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_2_backward(PyObject *__pyx_self, PyObj return __pyx_r; } -/* "sklearn/_hmmc.pyx":70 - * - * @cython.boundscheck(False) - * def _compute_lneta(int n_observations, int n_components, \ # <<<<<<<<<<<<<< - * np.ndarray[dtype_t, ndim=2] fwdlattice, \ - * np.ndarray[dtype_t, ndim=2] log_transmat, \ - */ - -static PyObject *__pyx_pf_7sklearn_5_hmmc_3_compute_lneta(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7sklearn_5_hmmc_3_compute_lneta = {__Pyx_NAMESTR("_compute_lneta"), (PyCFunction)__pyx_pf_7sklearn_5_hmmc_3_compute_lneta, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; -static PyObject *__pyx_pf_7sklearn_5_hmmc_3_compute_lneta(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5_hmmc_7_compute_lneta(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_5_hmmc_7_compute_lneta = {__Pyx_NAMESTR("_compute_lneta"), (PyCFunction)__pyx_pw_7sklearn_5_hmmc_7_compute_lneta, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_5_hmmc_7_compute_lneta(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_n_observations; int __pyx_v_n_components; PyArrayObject *__pyx_v_fwdlattice = 0; @@ -1988,66 +2860,19 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_3_compute_lneta(PyObject *__pyx_self, PyArrayObject *__pyx_v_framelogprob = 0; double __pyx_v_logprob; PyArrayObject *__pyx_v_lneta = 0; - int __pyx_v_i; - int __pyx_v_j; - int __pyx_v_t; - Py_buffer __pyx_bstruct_log_transmat; - Py_ssize_t __pyx_bstride_0_log_transmat = 0; - Py_ssize_t __pyx_bstride_1_log_transmat = 0; - Py_ssize_t __pyx_bshape_0_log_transmat = 0; - Py_ssize_t __pyx_bshape_1_log_transmat = 0; - Py_buffer __pyx_bstruct_framelogprob; - Py_ssize_t __pyx_bstride_0_framelogprob = 0; - Py_ssize_t __pyx_bstride_1_framelogprob = 0; - Py_ssize_t __pyx_bshape_0_framelogprob = 0; - Py_ssize_t __pyx_bshape_1_framelogprob = 0; - Py_buffer __pyx_bstruct_lneta; - Py_ssize_t __pyx_bstride_0_lneta = 0; - Py_ssize_t __pyx_bstride_1_lneta = 0; - Py_ssize_t __pyx_bstride_2_lneta = 0; - Py_ssize_t __pyx_bshape_0_lneta = 0; - Py_ssize_t __pyx_bshape_1_lneta = 0; - Py_ssize_t __pyx_bshape_2_lneta = 0; - Py_buffer __pyx_bstruct_bwdlattice; - Py_ssize_t __pyx_bstride_0_bwdlattice = 0; - Py_ssize_t __pyx_bstride_1_bwdlattice = 0; - Py_ssize_t __pyx_bshape_0_bwdlattice = 0; - Py_ssize_t __pyx_bshape_1_bwdlattice = 0; - Py_buffer __pyx_bstruct_fwdlattice; - Py_ssize_t __pyx_bstride_0_fwdlattice = 0; - Py_ssize_t __pyx_bstride_1_fwdlattice = 0; - Py_ssize_t __pyx_bshape_0_fwdlattice = 0; - Py_ssize_t __pyx_bshape_1_fwdlattice = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - long __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; - long __pyx_t_11; - int __pyx_t_12; - long __pyx_t_13; - int __pyx_t_14; - int __pyx_t_15; - int __pyx_t_16; - int __pyx_t_17; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_observations,&__pyx_n_s__n_components,&__pyx_n_s__fwdlattice,&__pyx_n_s__log_transmat,&__pyx_n_s__bwdlattice,&__pyx_n_s__framelogprob,&__pyx_n_s__logprob,&__pyx_n_s__lneta,0}; - __Pyx_RefNannySetupContext("_compute_lneta"); - __pyx_self = __pyx_self; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_compute_lneta (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_observations,&__pyx_n_s__n_components,&__pyx_n_s__fwdlattice,&__pyx_n_s__log_transmat,&__pyx_n_s__bwdlattice,&__pyx_n_s__framelogprob,&__pyx_n_s__logprob,&__pyx_n_s__lneta,0}; PyObject* values[8] = {0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); @@ -2060,56 +2885,48 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_3_compute_lneta(PyObject *__pyx_self, default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_observations); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_observations)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_components); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_components)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__fwdlattice); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__fwdlattice)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_transmat); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_transmat)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__bwdlattice); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__bwdlattice)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__framelogprob); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__framelogprob)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__logprob); - if (likely(values[6])) kw_args--; + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__logprob)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: - values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__lneta); - if (likely(values[7])) kw_args--; + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__lneta)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "_compute_lneta") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_compute_lneta") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 8) { goto __pyx_L5_argtuple_error; @@ -2123,90 +2940,154 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_3_compute_lneta(PyObject *__pyx_self, values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); } - __pyx_v_n_observations = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_observations == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_n_components = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_n_components == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_observations = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_observations == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_components = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_n_components == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_fwdlattice = ((PyArrayObject *)values[2]); __pyx_v_log_transmat = ((PyArrayObject *)values[3]); __pyx_v_bwdlattice = ((PyArrayObject *)values[4]); __pyx_v_framelogprob = ((PyArrayObject *)values[5]); - __pyx_v_logprob = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_logprob == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_logprob = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_logprob == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_lneta = ((PyArrayObject *)values[7]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_compute_lneta", 1, 8, 8, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn._hmmc._compute_lneta", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_fwdlattice.buf = NULL; - __pyx_bstruct_log_transmat.buf = NULL; - __pyx_bstruct_bwdlattice.buf = NULL; - __pyx_bstruct_framelogprob.buf = NULL; - __pyx_bstruct_lneta.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_fwdlattice), __pyx_ptype_5numpy_ndarray, 1, "fwdlattice", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_transmat), __pyx_ptype_5numpy_ndarray, 1, "log_transmat", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_bwdlattice), __pyx_ptype_5numpy_ndarray, 1, "bwdlattice", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_framelogprob), __pyx_ptype_5numpy_ndarray, 1, "framelogprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_lneta), __pyx_ptype_5numpy_ndarray, 1, "lneta", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_fwdlattice), __pyx_ptype_5numpy_ndarray, 1, "fwdlattice", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_transmat), __pyx_ptype_5numpy_ndarray, 1, "log_transmat", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_bwdlattice), __pyx_ptype_5numpy_ndarray, 1, "bwdlattice", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_framelogprob), __pyx_ptype_5numpy_ndarray, 1, "framelogprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_lneta), __pyx_ptype_5numpy_ndarray, 1, "lneta", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5_hmmc_6_compute_lneta(__pyx_self, __pyx_v_n_observations, __pyx_v_n_components, __pyx_v_fwdlattice, __pyx_v_log_transmat, __pyx_v_bwdlattice, __pyx_v_framelogprob, __pyx_v_logprob, __pyx_v_lneta); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/_hmmc.pyx":80 + * + * @cython.boundscheck(False) + * def _compute_lneta(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=2] fwdlattice, + * np.ndarray[dtype_t, ndim=2] log_transmat, + */ + +static PyObject *__pyx_pf_7sklearn_5_hmmc_6_compute_lneta(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_observations, int __pyx_v_n_components, PyArrayObject *__pyx_v_fwdlattice, PyArrayObject *__pyx_v_log_transmat, PyArrayObject *__pyx_v_bwdlattice, PyArrayObject *__pyx_v_framelogprob, double __pyx_v_logprob, PyArrayObject *__pyx_v_lneta) { + int __pyx_v_i; + int __pyx_v_j; + int __pyx_v_t; + __Pyx_LocalBuf_ND __pyx_pybuffernd_bwdlattice; + __Pyx_Buffer __pyx_pybuffer_bwdlattice; + __Pyx_LocalBuf_ND __pyx_pybuffernd_framelogprob; + __Pyx_Buffer __pyx_pybuffer_framelogprob; + __Pyx_LocalBuf_ND __pyx_pybuffernd_fwdlattice; + __Pyx_Buffer __pyx_pybuffer_fwdlattice; + __Pyx_LocalBuf_ND __pyx_pybuffernd_lneta; + __Pyx_Buffer __pyx_pybuffer_lneta; + __Pyx_LocalBuf_ND __pyx_pybuffernd_log_transmat; + __Pyx_Buffer __pyx_pybuffer_log_transmat; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + long __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + long __pyx_t_11; + int __pyx_t_12; + long __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + int __pyx_t_17; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_compute_lneta", 0); + __pyx_pybuffer_fwdlattice.pybuffer.buf = NULL; + __pyx_pybuffer_fwdlattice.refcount = 0; + __pyx_pybuffernd_fwdlattice.data = NULL; + __pyx_pybuffernd_fwdlattice.rcbuffer = &__pyx_pybuffer_fwdlattice; + __pyx_pybuffer_log_transmat.pybuffer.buf = NULL; + __pyx_pybuffer_log_transmat.refcount = 0; + __pyx_pybuffernd_log_transmat.data = NULL; + __pyx_pybuffernd_log_transmat.rcbuffer = &__pyx_pybuffer_log_transmat; + __pyx_pybuffer_bwdlattice.pybuffer.buf = NULL; + __pyx_pybuffer_bwdlattice.refcount = 0; + __pyx_pybuffernd_bwdlattice.data = NULL; + __pyx_pybuffernd_bwdlattice.rcbuffer = &__pyx_pybuffer_bwdlattice; + __pyx_pybuffer_framelogprob.pybuffer.buf = NULL; + __pyx_pybuffer_framelogprob.refcount = 0; + __pyx_pybuffernd_framelogprob.data = NULL; + __pyx_pybuffernd_framelogprob.rcbuffer = &__pyx_pybuffer_framelogprob; + __pyx_pybuffer_lneta.pybuffer.buf = NULL; + __pyx_pybuffer_lneta.refcount = 0; + __pyx_pybuffernd_lneta.data = NULL; + __pyx_pybuffernd_lneta.rcbuffer = &__pyx_pybuffer_lneta; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_fwdlattice, (PyObject*)__pyx_v_fwdlattice, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer, (PyObject*)__pyx_v_fwdlattice, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_fwdlattice = __pyx_bstruct_fwdlattice.strides[0]; __pyx_bstride_1_fwdlattice = __pyx_bstruct_fwdlattice.strides[1]; - __pyx_bshape_0_fwdlattice = __pyx_bstruct_fwdlattice.shape[0]; __pyx_bshape_1_fwdlattice = __pyx_bstruct_fwdlattice.shape[1]; + __pyx_pybuffernd_fwdlattice.diminfo[0].strides = __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_fwdlattice.diminfo[0].shape = __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_fwdlattice.diminfo[1].strides = __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_fwdlattice.diminfo[1].shape = __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_log_transmat, (PyObject*)__pyx_v_log_transmat, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer, (PyObject*)__pyx_v_log_transmat, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_log_transmat = __pyx_bstruct_log_transmat.strides[0]; __pyx_bstride_1_log_transmat = __pyx_bstruct_log_transmat.strides[1]; - __pyx_bshape_0_log_transmat = __pyx_bstruct_log_transmat.shape[0]; __pyx_bshape_1_log_transmat = __pyx_bstruct_log_transmat.shape[1]; + __pyx_pybuffernd_log_transmat.diminfo[0].strides = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_log_transmat.diminfo[0].shape = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_log_transmat.diminfo[1].strides = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_log_transmat.diminfo[1].shape = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_bwdlattice, (PyObject*)__pyx_v_bwdlattice, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer, (PyObject*)__pyx_v_bwdlattice, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_bwdlattice = __pyx_bstruct_bwdlattice.strides[0]; __pyx_bstride_1_bwdlattice = __pyx_bstruct_bwdlattice.strides[1]; - __pyx_bshape_0_bwdlattice = __pyx_bstruct_bwdlattice.shape[0]; __pyx_bshape_1_bwdlattice = __pyx_bstruct_bwdlattice.shape[1]; + __pyx_pybuffernd_bwdlattice.diminfo[0].strides = __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_bwdlattice.diminfo[0].shape = __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_bwdlattice.diminfo[1].strides = __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_bwdlattice.diminfo[1].shape = __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_framelogprob, (PyObject*)__pyx_v_framelogprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer, (PyObject*)__pyx_v_framelogprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_framelogprob = __pyx_bstruct_framelogprob.strides[0]; __pyx_bstride_1_framelogprob = __pyx_bstruct_framelogprob.strides[1]; - __pyx_bshape_0_framelogprob = __pyx_bstruct_framelogprob.shape[0]; __pyx_bshape_1_framelogprob = __pyx_bstruct_framelogprob.shape[1]; + __pyx_pybuffernd_framelogprob.diminfo[0].strides = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_framelogprob.diminfo[0].shape = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_framelogprob.diminfo[1].strides = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_framelogprob.diminfo[1].shape = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_lneta, (PyObject*)__pyx_v_lneta, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 3, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_lneta.rcbuffer->pybuffer, (PyObject*)__pyx_v_lneta, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 3, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_lneta = __pyx_bstruct_lneta.strides[0]; __pyx_bstride_1_lneta = __pyx_bstruct_lneta.strides[1]; __pyx_bstride_2_lneta = __pyx_bstruct_lneta.strides[2]; - __pyx_bshape_0_lneta = __pyx_bstruct_lneta.shape[0]; __pyx_bshape_1_lneta = __pyx_bstruct_lneta.shape[1]; __pyx_bshape_2_lneta = __pyx_bstruct_lneta.shape[2]; + __pyx_pybuffernd_lneta.diminfo[0].strides = __pyx_pybuffernd_lneta.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_lneta.diminfo[0].shape = __pyx_pybuffernd_lneta.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_lneta.diminfo[1].strides = __pyx_pybuffernd_lneta.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_lneta.diminfo[1].shape = __pyx_pybuffernd_lneta.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_lneta.diminfo[2].strides = __pyx_pybuffernd_lneta.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_lneta.diminfo[2].shape = __pyx_pybuffernd_lneta.rcbuffer->pybuffer.shape[2]; - /* "sklearn/_hmmc.pyx":79 + /* "sklearn/_hmmc.pyx":89 * * cdef int i, j, t - * for t in xrange(n_observations - 1): # <<<<<<<<<<<<<< - * for i in xrange(n_components): - * for j in xrange(n_components): + * for t in range(n_observations - 1): # <<<<<<<<<<<<<< + * for i in range(n_components): + * for j in range(n_components): */ __pyx_t_1 = (__pyx_v_n_observations - 1); for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_t = __pyx_t_2; - /* "sklearn/_hmmc.pyx":80 + /* "sklearn/_hmmc.pyx":90 * cdef int i, j, t - * for t in xrange(n_observations - 1): - * for i in xrange(n_components): # <<<<<<<<<<<<<< - * for j in xrange(n_components): + * for t in range(n_observations - 1): + * for i in range(n_components): # <<<<<<<<<<<<<< + * for j in range(n_components): * lneta[t, i, j] = fwdlattice[t, i] + log_transmat[i, j] \ */ __pyx_t_3 = __pyx_v_n_components; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; - /* "sklearn/_hmmc.pyx":81 - * for t in xrange(n_observations - 1): - * for i in xrange(n_components): - * for j in xrange(n_components): # <<<<<<<<<<<<<< + /* "sklearn/_hmmc.pyx":91 + * for t in range(n_observations - 1): + * for i in range(n_components): + * for j in range(n_components): # <<<<<<<<<<<<<< * lneta[t, i, j] = fwdlattice[t, i] + log_transmat[i, j] \ * + framelogprob[t + 1, j] + bwdlattice[t + 1, j] - logprob */ @@ -2214,24 +3095,24 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_3_compute_lneta(PyObject *__pyx_self, for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_j = __pyx_t_6; - /* "sklearn/_hmmc.pyx":82 - * for i in xrange(n_components): - * for j in xrange(n_components): + /* "sklearn/_hmmc.pyx":92 + * for i in range(n_components): + * for j in range(n_components): * lneta[t, i, j] = fwdlattice[t, i] + log_transmat[i, j] \ # <<<<<<<<<<<<<< * + framelogprob[t + 1, j] + bwdlattice[t + 1, j] - logprob * */ __pyx_t_7 = __pyx_v_t; __pyx_t_8 = __pyx_v_i; - if (__pyx_t_7 < 0) __pyx_t_7 += __pyx_bshape_0_fwdlattice; - if (__pyx_t_8 < 0) __pyx_t_8 += __pyx_bshape_1_fwdlattice; + if (__pyx_t_7 < 0) __pyx_t_7 += __pyx_pybuffernd_fwdlattice.diminfo[0].shape; + if (__pyx_t_8 < 0) __pyx_t_8 += __pyx_pybuffernd_fwdlattice.diminfo[1].shape; __pyx_t_9 = __pyx_v_i; __pyx_t_10 = __pyx_v_j; - if (__pyx_t_9 < 0) __pyx_t_9 += __pyx_bshape_0_log_transmat; - if (__pyx_t_10 < 0) __pyx_t_10 += __pyx_bshape_1_log_transmat; + if (__pyx_t_9 < 0) __pyx_t_9 += __pyx_pybuffernd_log_transmat.diminfo[0].shape; + if (__pyx_t_10 < 0) __pyx_t_10 += __pyx_pybuffernd_log_transmat.diminfo[1].shape; - /* "sklearn/_hmmc.pyx":83 - * for j in xrange(n_components): + /* "sklearn/_hmmc.pyx":93 + * for j in range(n_components): * lneta[t, i, j] = fwdlattice[t, i] + log_transmat[i, j] \ * + framelogprob[t + 1, j] + bwdlattice[t + 1, j] - logprob # <<<<<<<<<<<<<< * @@ -2239,16 +3120,16 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_3_compute_lneta(PyObject *__pyx_self, */ __pyx_t_11 = (__pyx_v_t + 1); __pyx_t_12 = __pyx_v_j; - if (__pyx_t_11 < 0) __pyx_t_11 += __pyx_bshape_0_framelogprob; - if (__pyx_t_12 < 0) __pyx_t_12 += __pyx_bshape_1_framelogprob; + if (__pyx_t_11 < 0) __pyx_t_11 += __pyx_pybuffernd_framelogprob.diminfo[0].shape; + if (__pyx_t_12 < 0) __pyx_t_12 += __pyx_pybuffernd_framelogprob.diminfo[1].shape; __pyx_t_13 = (__pyx_v_t + 1); __pyx_t_14 = __pyx_v_j; - if (__pyx_t_13 < 0) __pyx_t_13 += __pyx_bshape_0_bwdlattice; - if (__pyx_t_14 < 0) __pyx_t_14 += __pyx_bshape_1_bwdlattice; + if (__pyx_t_13 < 0) __pyx_t_13 += __pyx_pybuffernd_bwdlattice.diminfo[0].shape; + if (__pyx_t_14 < 0) __pyx_t_14 += __pyx_pybuffernd_bwdlattice.diminfo[1].shape; - /* "sklearn/_hmmc.pyx":82 - * for i in xrange(n_components): - * for j in xrange(n_components): + /* "sklearn/_hmmc.pyx":92 + * for i in range(n_components): + * for j in range(n_components): * lneta[t, i, j] = fwdlattice[t, i] + log_transmat[i, j] \ # <<<<<<<<<<<<<< * + framelogprob[t + 1, j] + bwdlattice[t + 1, j] - logprob * @@ -2256,10 +3137,10 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_3_compute_lneta(PyObject *__pyx_self, __pyx_t_15 = __pyx_v_t; __pyx_t_16 = __pyx_v_i; __pyx_t_17 = __pyx_v_j; - if (__pyx_t_15 < 0) __pyx_t_15 += __pyx_bshape_0_lneta; - if (__pyx_t_16 < 0) __pyx_t_16 += __pyx_bshape_1_lneta; - if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_bshape_2_lneta; - *__Pyx_BufPtrStrided3d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_lneta.buf, __pyx_t_15, __pyx_bstride_0_lneta, __pyx_t_16, __pyx_bstride_1_lneta, __pyx_t_17, __pyx_bstride_2_lneta) = (((((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_fwdlattice.buf, __pyx_t_7, __pyx_bstride_0_fwdlattice, __pyx_t_8, __pyx_bstride_1_fwdlattice)) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_log_transmat.buf, __pyx_t_9, __pyx_bstride_0_log_transmat, __pyx_t_10, __pyx_bstride_1_log_transmat))) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_framelogprob.buf, __pyx_t_11, __pyx_bstride_0_framelogprob, __pyx_t_12, __pyx_bstride_1_framelogprob))) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_bwdlattice.buf, __pyx_t_13, __pyx_bstride_0_bwdlattice, __pyx_t_14, __pyx_bstride_1_bwdlattice))) - __pyx_v_logprob); + if (__pyx_t_15 < 0) __pyx_t_15 += __pyx_pybuffernd_lneta.diminfo[0].shape; + if (__pyx_t_16 < 0) __pyx_t_16 += __pyx_pybuffernd_lneta.diminfo[1].shape; + if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_pybuffernd_lneta.diminfo[2].shape; + *__Pyx_BufPtrStrided3d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_lneta.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_lneta.diminfo[0].strides, __pyx_t_16, __pyx_pybuffernd_lneta.diminfo[1].strides, __pyx_t_17, __pyx_pybuffernd_lneta.diminfo[2].strides) = (((((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_fwdlattice.diminfo[0].strides, __pyx_t_8, __pyx_pybuffernd_fwdlattice.diminfo[1].strides)) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_log_transmat.diminfo[0].strides, __pyx_t_10, __pyx_pybuffernd_log_transmat.diminfo[1].strides))) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_framelogprob.diminfo[0].strides, __pyx_t_12, __pyx_pybuffernd_framelogprob.diminfo[1].strides))) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_bwdlattice.diminfo[0].strides, __pyx_t_14, __pyx_pybuffernd_bwdlattice.diminfo[1].strides))) - __pyx_v_logprob); } } } @@ -2269,116 +3150,49 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_3_compute_lneta(PyObject *__pyx_self, __pyx_L1_error:; { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_transmat); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_framelogprob); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_lneta); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_bwdlattice); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_fwdlattice); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_lneta.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn._hmmc._compute_lneta", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_transmat); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_framelogprob); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_lneta); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_bwdlattice); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_fwdlattice); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_bwdlattice.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_fwdlattice.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_lneta.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/_hmmc.pyx":87 - * - * @cython.boundscheck(False) - * def _viterbi(int n_observations, int n_components, \ # <<<<<<<<<<<<<< - * np.ndarray[dtype_t, ndim=1] log_startprob, \ - * np.ndarray[dtype_t, ndim=2] log_transmat, \ - */ - -static PyObject *__pyx_pf_7sklearn_5_hmmc_4_viterbi(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7sklearn_5_hmmc_4_viterbi = {__Pyx_NAMESTR("_viterbi"), (PyCFunction)__pyx_pf_7sklearn_5_hmmc_4_viterbi, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; -static PyObject *__pyx_pf_7sklearn_5_hmmc_4_viterbi(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5_hmmc_9_viterbi(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_5_hmmc_9_viterbi = {__Pyx_NAMESTR("_viterbi"), (PyCFunction)__pyx_pw_7sklearn_5_hmmc_9_viterbi, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_5_hmmc_9_viterbi(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_n_observations; int __pyx_v_n_components; PyArrayObject *__pyx_v_log_startprob = 0; PyArrayObject *__pyx_v_log_transmat = 0; PyArrayObject *__pyx_v_framelogprob = 0; - int __pyx_v_i; - int __pyx_v_j; - int __pyx_v_t; - int __pyx_v_max_pos; - PyArrayObject *__pyx_v_viterbi_lattice = 0; - PyArrayObject *__pyx_v_state_sequence = 0; - double __pyx_v_logprob; - PyArrayObject *__pyx_v_work_buffer = 0; - Py_buffer __pyx_bstruct_state_sequence; - Py_ssize_t __pyx_bstride_0_state_sequence = 0; - Py_ssize_t __pyx_bshape_0_state_sequence = 0; - Py_buffer __pyx_bstruct_log_transmat; - Py_ssize_t __pyx_bstride_0_log_transmat = 0; - Py_ssize_t __pyx_bstride_1_log_transmat = 0; - Py_ssize_t __pyx_bshape_0_log_transmat = 0; - Py_ssize_t __pyx_bshape_1_log_transmat = 0; - Py_buffer __pyx_bstruct_framelogprob; - Py_ssize_t __pyx_bstride_0_framelogprob = 0; - Py_ssize_t __pyx_bstride_1_framelogprob = 0; - Py_ssize_t __pyx_bshape_0_framelogprob = 0; - Py_ssize_t __pyx_bshape_1_framelogprob = 0; - Py_buffer __pyx_bstruct_viterbi_lattice; - Py_ssize_t __pyx_bstride_0_viterbi_lattice = 0; - Py_ssize_t __pyx_bstride_1_viterbi_lattice = 0; - Py_ssize_t __pyx_bshape_0_viterbi_lattice = 0; - Py_ssize_t __pyx_bshape_1_viterbi_lattice = 0; - Py_buffer __pyx_bstruct_work_buffer; - Py_ssize_t __pyx_bstride_0_work_buffer = 0; - Py_ssize_t __pyx_bshape_0_work_buffer = 0; - Py_buffer __pyx_bstruct_log_startprob; - Py_ssize_t __pyx_bstride_0_log_startprob = 0; - Py_ssize_t __pyx_bshape_0_log_startprob = 0; - PyObject *__pyx_r = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyArrayObject *__pyx_t_11 = NULL; - PyArrayObject *__pyx_t_12 = NULL; - int __pyx_t_13; - int __pyx_t_14; - long __pyx_t_15; - int __pyx_t_16; - long __pyx_t_17; - int __pyx_t_18; - int __pyx_t_19; - int __pyx_t_20; - int __pyx_t_21; - int __pyx_t_22; - __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_t_23; - int __pyx_t_24; - int __pyx_t_25; - long __pyx_t_26; - long __pyx_t_27; - long __pyx_t_28; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_observations,&__pyx_n_s__n_components,&__pyx_n_s__log_startprob,&__pyx_n_s__log_transmat,&__pyx_n_s__framelogprob,0}; - __Pyx_RefNannySetupContext("_viterbi"); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("_viterbi (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_observations,&__pyx_n_s__n_components,&__pyx_n_s__log_startprob,&__pyx_n_s__log_transmat,&__pyx_n_s__framelogprob,0}; PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); @@ -2388,38 +3202,33 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_4_viterbi(PyObject *__pyx_self, PyObje default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_observations); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_observations)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_components); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_components)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_viterbi", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_viterbi", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_startprob); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_startprob)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_viterbi", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_viterbi", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_transmat); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__log_transmat)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_viterbi", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_viterbi", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__framelogprob); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__framelogprob)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_viterbi", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_viterbi", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "_viterbi") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_viterbi") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { goto __pyx_L5_argtuple_error; @@ -2430,525 +3239,515 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_4_viterbi(PyObject *__pyx_self, PyObje values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); } - __pyx_v_n_observations = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_observations == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_n_components = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_n_components == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_observations = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_observations == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_components = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_n_components == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_log_startprob = ((PyArrayObject *)values[2]); __pyx_v_log_transmat = ((PyArrayObject *)values[3]); __pyx_v_framelogprob = ((PyArrayObject *)values[4]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_viterbi", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_viterbi", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn._hmmc._viterbi", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_viterbi_lattice.buf = NULL; - __pyx_bstruct_state_sequence.buf = NULL; - __pyx_bstruct_work_buffer.buf = NULL; - __pyx_bstruct_log_startprob.buf = NULL; - __pyx_bstruct_log_transmat.buf = NULL; - __pyx_bstruct_framelogprob.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_startprob), __pyx_ptype_5numpy_ndarray, 1, "log_startprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_transmat), __pyx_ptype_5numpy_ndarray, 1, "log_transmat", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_framelogprob), __pyx_ptype_5numpy_ndarray, 1, "framelogprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_startprob), __pyx_ptype_5numpy_ndarray, 1, "log_startprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_log_transmat), __pyx_ptype_5numpy_ndarray, 1, "log_transmat", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_framelogprob), __pyx_ptype_5numpy_ndarray, 1, "framelogprob", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5_hmmc_8_viterbi(__pyx_self, __pyx_v_n_observations, __pyx_v_n_components, __pyx_v_log_startprob, __pyx_v_log_transmat, __pyx_v_framelogprob); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/_hmmc.pyx":97 + * + * @cython.boundscheck(False) + * def _viterbi(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=1] log_startprob, + * np.ndarray[dtype_t, ndim=2] log_transmat, + */ + +static PyObject *__pyx_pf_7sklearn_5_hmmc_8_viterbi(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_observations, int __pyx_v_n_components, PyArrayObject *__pyx_v_log_startprob, PyArrayObject *__pyx_v_log_transmat, PyArrayObject *__pyx_v_framelogprob) { + int __pyx_v_t; + int __pyx_v_max_pos; + PyArrayObject *__pyx_v_viterbi_lattice = 0; + PyArrayObject *__pyx_v_state_sequence = 0; + __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_v_logprob; + PyArrayObject *__pyx_v_work_buffer = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_framelogprob; + __Pyx_Buffer __pyx_pybuffer_framelogprob; + __Pyx_LocalBuf_ND __pyx_pybuffernd_log_startprob; + __Pyx_Buffer __pyx_pybuffer_log_startprob; + __Pyx_LocalBuf_ND __pyx_pybuffernd_log_transmat; + __Pyx_Buffer __pyx_pybuffer_log_transmat; + __Pyx_LocalBuf_ND __pyx_pybuffernd_state_sequence; + __Pyx_Buffer __pyx_pybuffer_state_sequence; + __Pyx_LocalBuf_ND __pyx_pybuffernd_viterbi_lattice; + __Pyx_Buffer __pyx_pybuffer_viterbi_lattice; + __Pyx_LocalBuf_ND __pyx_pybuffernd_work_buffer; + __Pyx_Buffer __pyx_pybuffer_work_buffer; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyArrayObject *__pyx_t_11 = NULL; + int __pyx_t_12; + long __pyx_t_13; + PyArrayObject *__pyx_t_14 = NULL; + int __pyx_t_15; + long __pyx_t_16; + long __pyx_t_17; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_viterbi", 0); + __pyx_pybuffer_viterbi_lattice.pybuffer.buf = NULL; + __pyx_pybuffer_viterbi_lattice.refcount = 0; + __pyx_pybuffernd_viterbi_lattice.data = NULL; + __pyx_pybuffernd_viterbi_lattice.rcbuffer = &__pyx_pybuffer_viterbi_lattice; + __pyx_pybuffer_state_sequence.pybuffer.buf = NULL; + __pyx_pybuffer_state_sequence.refcount = 0; + __pyx_pybuffernd_state_sequence.data = NULL; + __pyx_pybuffernd_state_sequence.rcbuffer = &__pyx_pybuffer_state_sequence; + __pyx_pybuffer_work_buffer.pybuffer.buf = NULL; + __pyx_pybuffer_work_buffer.refcount = 0; + __pyx_pybuffernd_work_buffer.data = NULL; + __pyx_pybuffernd_work_buffer.rcbuffer = &__pyx_pybuffer_work_buffer; + __pyx_pybuffer_log_startprob.pybuffer.buf = NULL; + __pyx_pybuffer_log_startprob.refcount = 0; + __pyx_pybuffernd_log_startprob.data = NULL; + __pyx_pybuffernd_log_startprob.rcbuffer = &__pyx_pybuffer_log_startprob; + __pyx_pybuffer_log_transmat.pybuffer.buf = NULL; + __pyx_pybuffer_log_transmat.refcount = 0; + __pyx_pybuffernd_log_transmat.data = NULL; + __pyx_pybuffernd_log_transmat.rcbuffer = &__pyx_pybuffer_log_transmat; + __pyx_pybuffer_framelogprob.pybuffer.buf = NULL; + __pyx_pybuffer_framelogprob.refcount = 0; + __pyx_pybuffernd_framelogprob.data = NULL; + __pyx_pybuffernd_framelogprob.rcbuffer = &__pyx_pybuffer_framelogprob; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_log_startprob, (PyObject*)__pyx_v_log_startprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_log_startprob.rcbuffer->pybuffer, (PyObject*)__pyx_v_log_startprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_log_startprob = __pyx_bstruct_log_startprob.strides[0]; - __pyx_bshape_0_log_startprob = __pyx_bstruct_log_startprob.shape[0]; + __pyx_pybuffernd_log_startprob.diminfo[0].strides = __pyx_pybuffernd_log_startprob.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_log_startprob.diminfo[0].shape = __pyx_pybuffernd_log_startprob.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_log_transmat, (PyObject*)__pyx_v_log_transmat, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer, (PyObject*)__pyx_v_log_transmat, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_log_transmat = __pyx_bstruct_log_transmat.strides[0]; __pyx_bstride_1_log_transmat = __pyx_bstruct_log_transmat.strides[1]; - __pyx_bshape_0_log_transmat = __pyx_bstruct_log_transmat.shape[0]; __pyx_bshape_1_log_transmat = __pyx_bstruct_log_transmat.shape[1]; + __pyx_pybuffernd_log_transmat.diminfo[0].strides = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_log_transmat.diminfo[0].shape = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_log_transmat.diminfo[1].strides = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_log_transmat.diminfo[1].shape = __pyx_pybuffernd_log_transmat.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_framelogprob, (PyObject*)__pyx_v_framelogprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer, (PyObject*)__pyx_v_framelogprob, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_framelogprob = __pyx_bstruct_framelogprob.strides[0]; __pyx_bstride_1_framelogprob = __pyx_bstruct_framelogprob.strides[1]; - __pyx_bshape_0_framelogprob = __pyx_bstruct_framelogprob.shape[0]; __pyx_bshape_1_framelogprob = __pyx_bstruct_framelogprob.shape[1]; + __pyx_pybuffernd_framelogprob.diminfo[0].strides = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_framelogprob.diminfo[0].shape = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_framelogprob.diminfo[1].strides = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_framelogprob.diminfo[1].shape = __pyx_pybuffernd_framelogprob.rcbuffer->pybuffer.shape[1]; - /* "sklearn/_hmmc.pyx":99 + /* "sklearn/_hmmc.pyx":109 * - * # Initialize state_sequenceation - * state_sequence = np.zeros(n_observations, dtype=np.int) # <<<<<<<<<<<<<< - * work_buffer = np.zeros(n_components) + * # Initialization + * state_sequence = np.empty(n_observations, dtype=np.int) # <<<<<<<<<<<<<< * viterbi_lattice = np.zeros((n_observations, n_components)) + * viterbi_lattice[0] = log_startprob + framelogprob[0] */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromLong(__pyx_v_n_observations); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyInt_FromLong(__pyx_v_n_observations); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__int); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__int); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_state_sequence); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_state_sequence, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_state_sequence.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_state_sequence.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_state_sequence, (PyObject*)__pyx_v_state_sequence, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_state_sequence.rcbuffer->pybuffer, (PyObject*)__pyx_v_state_sequence, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); } } - __pyx_bstride_0_state_sequence = __pyx_bstruct_state_sequence.strides[0]; - __pyx_bshape_0_state_sequence = __pyx_bstruct_state_sequence.shape[0]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_pybuffernd_state_sequence.diminfo[0].strides = __pyx_pybuffernd_state_sequence.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_state_sequence.diminfo[0].shape = __pyx_pybuffernd_state_sequence.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_6 = 0; __pyx_v_state_sequence = ((PyArrayObject *)__pyx_t_5); __pyx_t_5 = 0; - /* "sklearn/_hmmc.pyx":100 - * # Initialize state_sequenceation - * state_sequence = np.zeros(n_observations, dtype=np.int) - * work_buffer = np.zeros(n_components) # <<<<<<<<<<<<<< - * viterbi_lattice = np.zeros((n_observations, n_components)) + /* "sklearn/_hmmc.pyx":110 + * # Initialization + * state_sequence = np.empty(n_observations, dtype=np.int) + * viterbi_lattice = np.zeros((n_observations, n_components)) # <<<<<<<<<<<<<< + * viterbi_lattice[0] = log_startprob + framelogprob[0] * */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyInt_FromLong(__pyx_v_n_components); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(__pyx_v_n_observations); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); + __pyx_t_3 = PyInt_FromLong(__pyx_v_n_components); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_2)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_11 = ((PyArrayObject *)__pyx_t_5); + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_work_buffer); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_work_buffer, (PyObject*)__pyx_t_11, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_viterbi_lattice.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_viterbi_lattice.rcbuffer->pybuffer, (PyObject*)__pyx_t_11, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack); if (unlikely(__pyx_t_7 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_work_buffer, (PyObject*)__pyx_v_work_buffer, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_viterbi_lattice.rcbuffer->pybuffer, (PyObject*)__pyx_v_viterbi_lattice, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); } } - __pyx_bstride_0_work_buffer = __pyx_bstruct_work_buffer.strides[0]; - __pyx_bshape_0_work_buffer = __pyx_bstruct_work_buffer.shape[0]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_pybuffernd_viterbi_lattice.diminfo[0].strides = __pyx_pybuffernd_viterbi_lattice.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_viterbi_lattice.diminfo[0].shape = __pyx_pybuffernd_viterbi_lattice.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_viterbi_lattice.diminfo[1].strides = __pyx_pybuffernd_viterbi_lattice.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_viterbi_lattice.diminfo[1].shape = __pyx_pybuffernd_viterbi_lattice.rcbuffer->pybuffer.shape[1]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_11 = 0; - __pyx_v_work_buffer = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; - - /* "sklearn/_hmmc.pyx":101 - * state_sequence = np.zeros(n_observations, dtype=np.int) - * work_buffer = np.zeros(n_components) - * viterbi_lattice = np.zeros((n_observations, n_components)) # <<<<<<<<<<<<<< - * - * # viterbi_lattice[0,:] = log_startprob[:] + framelogprob[0,:] - */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyInt_FromLong(__pyx_v_n_observations); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_1 = PyInt_FromLong(__pyx_v_n_components); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_5 = 0; - __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_12 = ((PyArrayObject *)__pyx_t_2); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_viterbi_lattice); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_viterbi_lattice, (PyObject*)__pyx_t_12, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_viterbi_lattice, (PyObject*)__pyx_v_viterbi_lattice, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); - } - } - __pyx_bstride_0_viterbi_lattice = __pyx_bstruct_viterbi_lattice.strides[0]; __pyx_bstride_1_viterbi_lattice = __pyx_bstruct_viterbi_lattice.strides[1]; - __pyx_bshape_0_viterbi_lattice = __pyx_bstruct_viterbi_lattice.shape[0]; __pyx_bshape_1_viterbi_lattice = __pyx_bstruct_viterbi_lattice.shape[1]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_12 = 0; __pyx_v_viterbi_lattice = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/_hmmc.pyx":104 - * - * # viterbi_lattice[0,:] = log_startprob[:] + framelogprob[0,:] - * for i in xrange(n_components): # <<<<<<<<<<<<<< - * viterbi_lattice[0, i] = log_startprob[i] + framelogprob[0, i] - * - */ - __pyx_t_7 = __pyx_v_n_components; - for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_7; __pyx_t_13+=1) { - __pyx_v_i = __pyx_t_13; - - /* "sklearn/_hmmc.pyx":105 - * # viterbi_lattice[0,:] = log_startprob[:] + framelogprob[0,:] - * for i in xrange(n_components): - * viterbi_lattice[0, i] = log_startprob[i] + framelogprob[0, i] # <<<<<<<<<<<<<< + /* "sklearn/_hmmc.pyx":111 + * state_sequence = np.empty(n_observations, dtype=np.int) + * viterbi_lattice = np.zeros((n_observations, n_components)) + * viterbi_lattice[0] = log_startprob + framelogprob[0] # <<<<<<<<<<<<<< * * # Induction */ - __pyx_t_14 = __pyx_v_i; - if (__pyx_t_14 < 0) __pyx_t_14 += __pyx_bshape_0_log_startprob; - __pyx_t_15 = 0; - __pyx_t_16 = __pyx_v_i; - if (__pyx_t_15 < 0) __pyx_t_15 += __pyx_bshape_0_framelogprob; - if (__pyx_t_16 < 0) __pyx_t_16 += __pyx_bshape_1_framelogprob; - __pyx_t_17 = 0; - __pyx_t_18 = __pyx_v_i; - if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_bshape_0_viterbi_lattice; - if (__pyx_t_18 < 0) __pyx_t_18 += __pyx_bshape_1_viterbi_lattice; - *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_viterbi_lattice.buf, __pyx_t_17, __pyx_bstride_0_viterbi_lattice, __pyx_t_18, __pyx_bstride_1_viterbi_lattice) = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_log_startprob.buf, __pyx_t_14, __pyx_bstride_0_log_startprob)) + (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_framelogprob.buf, __pyx_t_15, __pyx_bstride_0_framelogprob, __pyx_t_16, __pyx_bstride_1_framelogprob))); - } + __pyx_t_2 = __Pyx_GetItemInt(((PyObject *)__pyx_v_framelogprob), 0, sizeof(long), PyInt_FromLong, 0, 0, 0); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Add(((PyObject *)__pyx_v_log_startprob), __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemInt(((PyObject *)__pyx_v_viterbi_lattice), 0, __pyx_t_3, sizeof(long), PyInt_FromLong, 0, 0, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/_hmmc.pyx":108 + /* "sklearn/_hmmc.pyx":114 * * # Induction - * for t in xrange(1, n_observations): # <<<<<<<<<<<<<< - * for j in xrange(n_components): - * work_buffer[:] = viterbi_lattice[t - 1, :] + log_transmat[:, j] + * for t in range(1, n_observations): # <<<<<<<<<<<<<< + * work_buffer = viterbi_lattice[t-1] + log_transmat.T + * viterbi_lattice[t] = np.max(work_buffer, axis=1) + framelogprob[t] */ __pyx_t_7 = __pyx_v_n_observations; - for (__pyx_t_13 = 1; __pyx_t_13 < __pyx_t_7; __pyx_t_13+=1) { - __pyx_v_t = __pyx_t_13; + for (__pyx_t_12 = 1; __pyx_t_12 < __pyx_t_7; __pyx_t_12+=1) { + __pyx_v_t = __pyx_t_12; - /* "sklearn/_hmmc.pyx":109 + /* "sklearn/_hmmc.pyx":115 * # Induction - * for t in xrange(1, n_observations): - * for j in xrange(n_components): # <<<<<<<<<<<<<< - * work_buffer[:] = viterbi_lattice[t - 1, :] + log_transmat[:, j] - * viterbi_lattice[t, j] = np.max(work_buffer[:]) + framelogprob[t, j] - */ - __pyx_t_19 = __pyx_v_n_components; - for (__pyx_t_20 = 0; __pyx_t_20 < __pyx_t_19; __pyx_t_20+=1) { - __pyx_v_j = __pyx_t_20; - - /* "sklearn/_hmmc.pyx":110 - * for t in xrange(1, n_observations): - * for j in xrange(n_components): - * work_buffer[:] = viterbi_lattice[t - 1, :] + log_transmat[:, j] # <<<<<<<<<<<<<< - * viterbi_lattice[t, j] = np.max(work_buffer[:]) + framelogprob[t, j] - * - */ - __pyx_t_2 = PyInt_FromLong((__pyx_v_t - 1)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_INCREF(__pyx_k_slice_1); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_k_slice_1); - __Pyx_GIVEREF(__pyx_k_slice_1); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetItem(((PyObject *)__pyx_v_viterbi_lattice), ((PyObject *)__pyx_t_1)); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromLong(__pyx_v_j); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(__pyx_k_slice_2); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_k_slice_2); - __Pyx_GIVEREF(__pyx_k_slice_2); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_log_transmat), ((PyObject *)__pyx_t_3)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Add(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_v_work_buffer)) { __Pyx_RaiseUnboundLocalError("work_buffer"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} }if (__Pyx_PySequence_SetSlice(((PyObject *)__pyx_v_work_buffer), 0, PY_SSIZE_T_MAX, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "sklearn/_hmmc.pyx":111 - * for j in xrange(n_components): - * work_buffer[:] = viterbi_lattice[t - 1, :] + log_transmat[:, j] - * viterbi_lattice[t, j] = np.max(work_buffer[:]) + framelogprob[t, j] # <<<<<<<<<<<<<< + * for t in range(1, n_observations): + * work_buffer = viterbi_lattice[t-1] + log_transmat.T # <<<<<<<<<<<<<< + * viterbi_lattice[t] = np.max(work_buffer, axis=1) + framelogprob[t] * - * # observation traceback */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__max); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_GetSlice(((PyObject *)__pyx_v_work_buffer), 0, PY_SSIZE_T_MAX); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_21 = __pyx_v_t; - __pyx_t_22 = __pyx_v_j; - if (__pyx_t_21 < 0) __pyx_t_21 += __pyx_bshape_0_framelogprob; - if (__pyx_t_22 < 0) __pyx_t_22 += __pyx_bshape_1_framelogprob; - __pyx_t_2 = PyFloat_FromDouble((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_framelogprob.buf, __pyx_t_21, __pyx_bstride_0_framelogprob, __pyx_t_22, __pyx_bstride_1_framelogprob))); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Add(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_23 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_23 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_24 = __pyx_v_t; - __pyx_t_25 = __pyx_v_j; - if (__pyx_t_24 < 0) __pyx_t_24 += __pyx_bshape_0_viterbi_lattice; - if (__pyx_t_25 < 0) __pyx_t_25 += __pyx_bshape_1_viterbi_lattice; - *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_viterbi_lattice.buf, __pyx_t_24, __pyx_bstride_0_viterbi_lattice, __pyx_t_25, __pyx_bstride_1_viterbi_lattice) = __pyx_t_23; + __pyx_t_13 = (__pyx_v_t - 1); + __pyx_t_3 = __Pyx_GetItemInt(((PyObject *)__pyx_v_viterbi_lattice), __pyx_t_13, sizeof(long), PyInt_FromLong, 0, 1, 0); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_log_transmat), __pyx_n_s__T); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyNumber_Add(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer); + __pyx_t_15 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer, (PyObject*)__pyx_t_14, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_15 < 0)) { + PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer, (PyObject*)__pyx_v_work_buffer, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); + } + } + __pyx_pybuffernd_work_buffer.diminfo[0].strides = __pyx_pybuffernd_work_buffer.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_work_buffer.diminfo[0].shape = __pyx_pybuffernd_work_buffer.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_work_buffer.diminfo[1].strides = __pyx_pybuffernd_work_buffer.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_work_buffer.diminfo[1].shape = __pyx_pybuffernd_work_buffer.rcbuffer->pybuffer.shape[1]; + if (unlikely(__pyx_t_15 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_14 = 0; + __Pyx_XDECREF(((PyObject *)__pyx_v_work_buffer)); + __pyx_v_work_buffer = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/_hmmc.pyx":116 + * for t in range(1, n_observations): + * work_buffer = viterbi_lattice[t-1] + log_transmat.T + * viterbi_lattice[t] = np.max(work_buffer, axis=1) + framelogprob[t] # <<<<<<<<<<<<<< + * + * # Observation traceback + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__max); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_work_buffer)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_work_buffer)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_work_buffer)); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__axis), __pyx_int_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_GetItemInt(((PyObject *)__pyx_v_framelogprob), __pyx_v_t, sizeof(int), PyInt_FromLong, 0, 1, 0); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyNumber_Add(__pyx_t_5, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemInt(((PyObject *)__pyx_v_viterbi_lattice), __pyx_v_t, __pyx_t_1, sizeof(int), PyInt_FromLong, 0, 1, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } - /* "sklearn/_hmmc.pyx":114 + /* "sklearn/_hmmc.pyx":119 * - * # observation traceback + * # Observation traceback * max_pos = np.argmax(viterbi_lattice[n_observations - 1, :]) # <<<<<<<<<<<<<< * state_sequence[n_observations - 1] = max_pos * logprob = viterbi_lattice[n_observations - 1, max_pos] */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__argmax); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__argmax); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromLong((__pyx_v_n_observations - 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyInt_FromLong((__pyx_v_n_observations - 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); - __Pyx_INCREF(__pyx_k_slice_3); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_k_slice_3); - __Pyx_GIVEREF(__pyx_k_slice_3); + __Pyx_INCREF(__pyx_k_slice_1); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_k_slice_1); + __Pyx_GIVEREF(__pyx_k_slice_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_viterbi_lattice), ((PyObject *)__pyx_t_3)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_viterbi_lattice), ((PyObject *)__pyx_t_5)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_max_pos = __pyx_t_7; - /* "sklearn/_hmmc.pyx":115 - * # observation traceback + /* "sklearn/_hmmc.pyx":120 + * # Observation traceback * max_pos = np.argmax(viterbi_lattice[n_observations - 1, :]) * state_sequence[n_observations - 1] = max_pos # <<<<<<<<<<<<<< * logprob = viterbi_lattice[n_observations - 1, max_pos] * */ - __pyx_t_26 = (__pyx_v_n_observations - 1); - if (__pyx_t_26 < 0) __pyx_t_26 += __pyx_bshape_0_state_sequence; - *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_bstruct_state_sequence.buf, __pyx_t_26, __pyx_bstride_0_state_sequence) = __pyx_v_max_pos; + __pyx_t_13 = (__pyx_v_n_observations - 1); + if (__pyx_t_13 < 0) __pyx_t_13 += __pyx_pybuffernd_state_sequence.diminfo[0].shape; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_pybuffernd_state_sequence.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_state_sequence.diminfo[0].strides) = __pyx_v_max_pos; - /* "sklearn/_hmmc.pyx":116 + /* "sklearn/_hmmc.pyx":121 * max_pos = np.argmax(viterbi_lattice[n_observations - 1, :]) * state_sequence[n_observations - 1] = max_pos * logprob = viterbi_lattice[n_observations - 1, max_pos] # <<<<<<<<<<<<<< * - * for t in xrange(n_observations - 2, -1, -1): + * for t in range(n_observations - 2, -1, -1): */ - __pyx_t_27 = (__pyx_v_n_observations - 1); + __pyx_t_16 = (__pyx_v_n_observations - 1); __pyx_t_7 = __pyx_v_max_pos; - if (__pyx_t_27 < 0) __pyx_t_27 += __pyx_bshape_0_viterbi_lattice; - if (__pyx_t_7 < 0) __pyx_t_7 += __pyx_bshape_1_viterbi_lattice; - __pyx_v_logprob = (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_bstruct_viterbi_lattice.buf, __pyx_t_27, __pyx_bstride_0_viterbi_lattice, __pyx_t_7, __pyx_bstride_1_viterbi_lattice)); + if (__pyx_t_16 < 0) __pyx_t_16 += __pyx_pybuffernd_viterbi_lattice.diminfo[0].shape; + if (__pyx_t_7 < 0) __pyx_t_7 += __pyx_pybuffernd_viterbi_lattice.diminfo[1].shape; + __pyx_v_logprob = (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5_hmmc_dtype_t *, __pyx_pybuffernd_viterbi_lattice.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_viterbi_lattice.diminfo[0].strides, __pyx_t_7, __pyx_pybuffernd_viterbi_lattice.diminfo[1].strides)); - /* "sklearn/_hmmc.pyx":118 + /* "sklearn/_hmmc.pyx":123 * logprob = viterbi_lattice[n_observations - 1, max_pos] * - * for t in xrange(n_observations - 2, -1, -1): # <<<<<<<<<<<<<< + * for t in range(n_observations - 2, -1, -1): # <<<<<<<<<<<<<< * max_pos = np.argmax(viterbi_lattice[t, :] \ * + log_transmat[:, state_sequence[t + 1]]) */ - for (__pyx_t_13 = (__pyx_v_n_observations - 2); __pyx_t_13 > -1; __pyx_t_13-=1) { - __pyx_v_t = __pyx_t_13; + for (__pyx_t_12 = (__pyx_v_n_observations - 2); __pyx_t_12 > -1; __pyx_t_12-=1) { + __pyx_v_t = __pyx_t_12; - /* "sklearn/_hmmc.pyx":119 + /* "sklearn/_hmmc.pyx":124 * - * for t in xrange(n_observations - 2, -1, -1): + * for t in range(n_observations - 2, -1, -1): * max_pos = np.argmax(viterbi_lattice[t, :] \ # <<<<<<<<<<<<<< * + log_transmat[:, state_sequence[t + 1]]) * state_sequence[t] = max_pos */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__argmax); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__argmax); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/_hmmc.pyx":120 - * for t in xrange(n_observations - 2, -1, -1): + /* "sklearn/_hmmc.pyx":125 + * for t in range(n_observations - 2, -1, -1): * max_pos = np.argmax(viterbi_lattice[t, :] \ * + log_transmat[:, state_sequence[t + 1]]) # <<<<<<<<<<<<<< * state_sequence[t] = max_pos * */ - __pyx_t_1 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - /* "sklearn/_hmmc.pyx":119 + /* "sklearn/_hmmc.pyx":124 * - * for t in xrange(n_observations - 2, -1, -1): + * for t in range(n_observations - 2, -1, -1): * max_pos = np.argmax(viterbi_lattice[t, :] \ # <<<<<<<<<<<<<< * + log_transmat[:, state_sequence[t + 1]]) * state_sequence[t] = max_pos */ - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); - __Pyx_INCREF(__pyx_k_slice_4); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_k_slice_4); - __Pyx_GIVEREF(__pyx_k_slice_4); + __Pyx_INCREF(__pyx_k_slice_2); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_k_slice_2); + __Pyx_GIVEREF(__pyx_k_slice_2); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_viterbi_lattice), ((PyObject *)__pyx_t_2)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_viterbi_lattice), ((PyObject *)__pyx_t_3)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - /* "sklearn/_hmmc.pyx":120 - * for t in xrange(n_observations - 2, -1, -1): + /* "sklearn/_hmmc.pyx":125 + * for t in range(n_observations - 2, -1, -1): * max_pos = np.argmax(viterbi_lattice[t, :] \ * + log_transmat[:, state_sequence[t + 1]]) # <<<<<<<<<<<<<< * state_sequence[t] = max_pos * */ - __pyx_t_28 = (__pyx_v_t + 1); - if (__pyx_t_28 < 0) __pyx_t_28 += __pyx_bshape_0_state_sequence; - __pyx_t_2 = __Pyx_PyInt_to_py_npy_long((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_bstruct_state_sequence.buf, __pyx_t_28, __pyx_bstride_0_state_sequence))); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = (__pyx_v_t + 1); + if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_pybuffernd_state_sequence.diminfo[0].shape; + __pyx_t_3 = __Pyx_PyInt_to_py_npy_long((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_pybuffernd_state_sequence.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_state_sequence.diminfo[0].strides))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __Pyx_INCREF(__pyx_k_slice_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_k_slice_5); - __Pyx_GIVEREF(__pyx_k_slice_5); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetItem(((PyObject *)__pyx_v_log_transmat), ((PyObject *)__pyx_t_5)); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_k_slice_3); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_k_slice_3); + __Pyx_GIVEREF(__pyx_k_slice_3); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_log_transmat), ((PyObject *)__pyx_t_2)); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = PyNumber_Add(__pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Add(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_19 = __Pyx_PyInt_AsInt(__pyx_t_5); if (unlikely((__pyx_t_19 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_max_pos = __pyx_t_19; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_t_15 = __Pyx_PyInt_AsInt(__pyx_t_2); if (unlikely((__pyx_t_15 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_max_pos = __pyx_t_15; - /* "sklearn/_hmmc.pyx":121 + /* "sklearn/_hmmc.pyx":126 * max_pos = np.argmax(viterbi_lattice[t, :] \ * + log_transmat[:, state_sequence[t + 1]]) * state_sequence[t] = max_pos # <<<<<<<<<<<<<< * * return state_sequence, logprob */ - __pyx_t_19 = __pyx_v_t; - if (__pyx_t_19 < 0) __pyx_t_19 += __pyx_bshape_0_state_sequence; - *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_bstruct_state_sequence.buf, __pyx_t_19, __pyx_bstride_0_state_sequence) = __pyx_v_max_pos; + __pyx_t_15 = __pyx_v_t; + if (__pyx_t_15 < 0) __pyx_t_15 += __pyx_pybuffernd_state_sequence.diminfo[0].shape; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_pybuffernd_state_sequence.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_state_sequence.diminfo[0].strides) = __pyx_v_max_pos; } - /* "sklearn/_hmmc.pyx":123 + /* "sklearn/_hmmc.pyx":128 * state_sequence[t] = max_pos * * return state_sequence, logprob # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); - __pyx_t_5 = PyFloat_FromDouble(__pyx_v_logprob); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_logprob); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(((PyObject *)__pyx_v_state_sequence)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_state_sequence)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_state_sequence)); __Pyx_GIVEREF(((PyObject *)__pyx_v_state_sequence)); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_r = ((PyObject *)__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_3); + __pyx_t_3 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); @@ -2961,23 +3760,23 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_4_viterbi(PyObject *__pyx_self, PyObje __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_state_sequence); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_transmat); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_framelogprob); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_viterbi_lattice); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_work_buffer); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_startprob); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_startprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_state_sequence.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_viterbi_lattice.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn._hmmc._viterbi", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_state_sequence); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_transmat); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_framelogprob); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_viterbi_lattice); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_work_buffer); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_log_startprob); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_framelogprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_startprob.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_transmat.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_state_sequence.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_viterbi_lattice.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_work_buffer.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_viterbi_lattice); __Pyx_XDECREF((PyObject *)__pyx_v_state_sequence); @@ -2987,7 +3786,18 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_4_viterbi(PyObject *__pyx_self, PyObje return __pyx_r; } -/* "numpy.pxd":190 +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":194 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< @@ -2995,8 +3805,7 @@ static PyObject *__pyx_pf_7sklearn_5_hmmc_4_viterbi(PyObject *__pyx_self, PyObje * # requirements, and does not yet fullfill the PEP. */ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; @@ -3021,28 +3830,28 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__"); + __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":196 + /* "numpy.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ - __pyx_t_1 = (__pyx_v_info == NULL); + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":199 + /* "numpy.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -3051,7 +3860,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":200 + /* "numpy.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -3060,26 +3869,26 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":202 + /* "numpy.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":204 + /* "numpy.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":205 + /* "numpy.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -3087,11 +3896,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ * copy_shape = 0 */ __pyx_v_copy_shape = 1; - goto __pyx_L6; + goto __pyx_L4; } /*else*/ { - /* "numpy.pxd":207 + /* "numpy.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -3100,98 +3909,98 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_copy_shape = 0; } - __pyx_L6:; + __pyx_L4:; - /* "numpy.pxd":209 + /* "numpy.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_1) { - /* "numpy.pxd":210 + /* "numpy.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { - /* "numpy.pxd":211 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_7), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; } - __pyx_L7:; + __pyx_L5:; - /* "numpy.pxd":213 + /* "numpy.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_3) { - /* "numpy.pxd":214 + /* "numpy.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { - /* "numpy.pxd":215 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_7), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; } - __pyx_L8:; + __pyx_L6:; - /* "numpy.pxd":217 + /* "numpy.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":218 + /* "numpy.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -3200,16 +4009,17 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":219 + /* "numpy.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ - if (__pyx_v_copy_shape) { + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { - /* "numpy.pxd":222 + /* "numpy.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -3218,7 +4028,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":223 + /* "numpy.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -3227,7 +4037,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":224 + /* "numpy.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< @@ -3238,49 +4048,49 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "numpy.pxd":225 + /* "numpy.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":226 + /* "numpy.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } - goto __pyx_L9; + goto __pyx_L7; } /*else*/ { - /* "numpy.pxd":228 + /* "numpy.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":229 + /* "numpy.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } - __pyx_L9:; + __pyx_L7:; - /* "numpy.pxd":230 + /* "numpy.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -3289,25 +4099,25 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":231 + /* "numpy.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":232 + /* "numpy.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - /* "numpy.pxd":235 + /* "numpy.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -3316,17 +4126,19 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_f = NULL; - /* "numpy.pxd":236 + /* "numpy.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":240 + /* "numpy.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -3335,23 +4147,23 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":242 + /* "numpy.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; } if (__pyx_t_1) { - /* "numpy.pxd":244 + /* "numpy.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -3363,69 +4175,70 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; - goto __pyx_L12; + goto __pyx_L10; } /*else*/ { - /* "numpy.pxd":247 + /* "numpy.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } - __pyx_L12:; + __pyx_L10:; - /* "numpy.pxd":249 + /* "numpy.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { - /* "numpy.pxd":250 + /* "numpy.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; - /* "numpy.pxd":251 + /* "numpy.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; + __pyx_t_2 = (__pyx_v_little_endian != 0); } else { __pyx_t_2 = __pyx_t_1; } if (!__pyx_t_2) { - /* "numpy.pxd":252 + /* "numpy.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_7 = __pyx_t_3; } else { __pyx_t_7 = __pyx_t_1; @@ -3436,271 +4249,246 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (__pyx_t_1) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; } - __pyx_L14:; + __pyx_L12:; - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "numpy.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { + case NPY_BYTE: __pyx_v_f = __pyx_k__b; - goto __pyx_L15; - } + break; - /* "numpy.pxd":255 + /* "numpy.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { + case NPY_UBYTE: __pyx_v_f = __pyx_k__B; - goto __pyx_L15; - } + break; - /* "numpy.pxd":256 + /* "numpy.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { + case NPY_SHORT: __pyx_v_f = __pyx_k__h; - goto __pyx_L15; - } + break; - /* "numpy.pxd":257 + /* "numpy.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { + case NPY_USHORT: __pyx_v_f = __pyx_k__H; - goto __pyx_L15; - } + break; - /* "numpy.pxd":258 + /* "numpy.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { + case NPY_INT: __pyx_v_f = __pyx_k__i; - goto __pyx_L15; - } + break; - /* "numpy.pxd":259 + /* "numpy.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { + case NPY_UINT: __pyx_v_f = __pyx_k__I; - goto __pyx_L15; - } + break; - /* "numpy.pxd":260 + /* "numpy.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { + case NPY_LONG: __pyx_v_f = __pyx_k__l; - goto __pyx_L15; - } + break; - /* "numpy.pxd":261 + /* "numpy.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { + case NPY_ULONG: __pyx_v_f = __pyx_k__L; - goto __pyx_L15; - } + break; - /* "numpy.pxd":262 + /* "numpy.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { + case NPY_LONGLONG: __pyx_v_f = __pyx_k__q; - goto __pyx_L15; - } + break; - /* "numpy.pxd":263 + /* "numpy.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { + case NPY_ULONGLONG: __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; - } + break; - /* "numpy.pxd":264 + /* "numpy.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { + case NPY_FLOAT: __pyx_v_f = __pyx_k__f; - goto __pyx_L15; - } + break; - /* "numpy.pxd":265 + /* "numpy.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { + case NPY_DOUBLE: __pyx_v_f = __pyx_k__d; - goto __pyx_L15; - } + break; - /* "numpy.pxd":266 + /* "numpy.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { + case NPY_LONGDOUBLE: __pyx_v_f = __pyx_k__g; - goto __pyx_L15; - } + break; - /* "numpy.pxd":267 + /* "numpy.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { + case NPY_CFLOAT: __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; - } + break; - /* "numpy.pxd":268 + /* "numpy.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { + case NPY_CDOUBLE: __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; - } + break; - /* "numpy.pxd":269 + /* "numpy.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { + case NPY_CLONGDOUBLE: __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; - } + break; - /* "numpy.pxd":270 + /* "numpy.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { + case NPY_OBJECT: __pyx_v_f = __pyx_k__O; - goto __pyx_L15; - } - /*else*/ { + break; + default: - /* "numpy.pxd":272 + /* "numpy.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_12), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_10), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_8)); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L15:; - /* "numpy.pxd":273 + /* "numpy.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -3709,7 +4497,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":274 + /* "numpy.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -3718,57 +4506,57 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L13; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":276 + /* "numpy.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":277 + /* "numpy.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":278 + /* "numpy.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":281 + /* "numpy.pxd":285 * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string + * f[0] = c'\0' # Terminate format string * */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; - /* "numpy.pxd":282 + /* "numpy.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L13:; + __pyx_L11:; __pyx_r = 0; goto __pyx_L0; @@ -3793,31 +4581,39 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ return __pyx_r; } -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":288 + * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__"); + __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":285 + /* "numpy.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { - /* "numpy.pxd":286 + /* "numpy.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -3825,21 +4621,21 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * stdlib.free(info.strides) */ free(__pyx_v_info->format); - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":287 + /* "numpy.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":288 + /* "numpy.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -3847,14 +4643,14 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * */ free(__pyx_v_info->strides); - goto __pyx_L6; + goto __pyx_L4; } - __pyx_L6:; + __pyx_L4:; __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":764 +/* "numpy.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -3869,9 +4665,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":765 + /* "numpy.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -3879,7 +4675,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3897,7 +4693,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":767 +/* "numpy.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -3912,9 +4708,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":768 + /* "numpy.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -3922,7 +4718,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3940,7 +4736,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "numpy.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -3955,9 +4751,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":771 + /* "numpy.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -3965,7 +4761,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3983,7 +4779,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "numpy.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -3998,9 +4794,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":774 + /* "numpy.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -4008,7 +4804,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -4026,7 +4822,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "numpy.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -4041,9 +4837,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":777 + /* "numpy.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -4051,7 +4847,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -4069,7 +4865,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "numpy.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -4092,18 +4888,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; + PyObject *(*__pyx_t_6)(PyObject *); int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; + int __pyx_t_10; + long __pyx_t_11; + char *__pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring"); + __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":786 + /* "numpy.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -4112,7 +4909,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":787 + /* "numpy.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -4121,7 +4918,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":790 + /* "numpy.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< @@ -4129,31 +4926,36 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * child, new_offset = fields */ if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif __Pyx_XDECREF(__pyx_v_childname); __pyx_v_childname = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":791 + /* "numpy.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); __pyx_v_fields = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":792 + /* "numpy.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< @@ -4162,20 +4964,51 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); - } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_child)); __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; @@ -4183,99 +5016,98 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_v_new_offset = __pyx_t_4; __pyx_t_4 = 0; - /* "numpy.pxd":794 + /* "numpy.pxd":798 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":795 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; } - __pyx_L5:; + __pyx_L7:; - /* "numpy.pxd":797 + /* "numpy.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_7) { + __pyx_t_8 = (__pyx_v_little_endian != 0); } else { - __pyx_t_7 = __pyx_t_6; + __pyx_t_8 = __pyx_t_7; } - if (!__pyx_t_7) { + if (!__pyx_t_8) { - /* "numpy.pxd":798 + /* "numpy.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + __pyx_t_9 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_10 = __pyx_t_9; } else { - __pyx_t_9 = __pyx_t_6; + __pyx_t_10 = __pyx_t_7; } - __pyx_t_6 = __pyx_t_9; + __pyx_t_7 = __pyx_t_10; } else { - __pyx_t_6 = __pyx_t_7; + __pyx_t_7 = __pyx_t_8; } - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_13), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; } - __pyx_L6:; + __pyx_L8:; - /* "numpy.pxd":809 + /* "numpy.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -4283,16 +5115,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!__pyx_t_6) break; + if (!__pyx_t_7) break; - /* "numpy.pxd":810 + /* "numpy.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -4301,7 +5132,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":811 + /* "numpy.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -4310,430 +5141,413 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":812 + /* "numpy.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); } - /* "numpy.pxd":814 + /* "numpy.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); - /* "numpy.pxd":816 + /* "numpy.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); - if (__pyx_t_6) { + __pyx_t_7 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_7) { - /* "numpy.pxd":817 + /* "numpy.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XDECREF(__pyx_v_t); __pyx_v_t = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":818 + /* "numpy.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); - if (__pyx_t_6) { + __pyx_t_7 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_7) { - /* "numpy.pxd":819 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_17), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; } - __pyx_L10:; + __pyx_L12:; - /* "numpy.pxd":822 + /* "numpy.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 98; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":823 + /* "numpy.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 66; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":824 + /* "numpy.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 104; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":825 + /* "numpy.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 72; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":826 + /* "numpy.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 105; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":827 + /* "numpy.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 73; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":828 + /* "numpy.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 108; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":829 + /* "numpy.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 76; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":830 + /* "numpy.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 113; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":831 + /* "numpy.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 81; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":832 + /* "numpy.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 102; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":833 + /* "numpy.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 100; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":834 + /* "numpy.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 103; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":835 + /* "numpy.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":836 + /* "numpy.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":837 + /* "numpy.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":838 + /* "numpy.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 79; - goto __pyx_L11; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":840 + /* "numpy.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_12), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_10), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L11:; + __pyx_L13:; - /* "numpy.pxd":841 + /* "numpy.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -4741,25 +5555,25 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":845 + /* "numpy.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_12; } - __pyx_L9:; + __pyx_L11:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":846 + /* "numpy.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -4788,7 +5602,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":961 +/* "numpy.pxd":965 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -4800,9 +5614,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base"); + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":963 + /* "numpy.pxd":967 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -4810,9 +5625,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "numpy.pxd":964 + /* "numpy.pxd":968 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -4824,7 +5640,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":966 + /* "numpy.pxd":970 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -4833,7 +5649,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":967 + /* "numpy.pxd":971 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -4844,7 +5660,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":968 + /* "numpy.pxd":972 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -4853,7 +5669,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":969 + /* "numpy.pxd":973 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -4865,7 +5681,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":971 +/* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -4877,19 +5693,19 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base"); + __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":972 + /* "numpy.pxd":976 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { - /* "numpy.pxd":973 + /* "numpy.pxd":977 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -4904,7 +5720,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py } /*else*/ { - /* "numpy.pxd":975 + /* "numpy.pxd":979 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -4923,14 +5739,10757 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py return __pyx_r; } -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; +/* Python wrapper */ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_shape = 0; + Py_ssize_t __pyx_v_itemsize; + PyObject *__pyx_v_format = 0; + PyObject *__pyx_v_mode = 0; + int __pyx_v_allocate_buffer; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__shape,&__pyx_n_s__itemsize,&__pyx_n_s__format,&__pyx_n_s__mode,&__pyx_n_s__allocate_buffer,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[3] = ((PyObject *)__pyx_n_u__c); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shape)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__itemsize)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__format)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__mode); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__allocate_buffer); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_shape = ((PyObject*)values[0]); + __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_format = values[2]; + __pyx_v_mode = values[3]; + if (values[4]) { + __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { -#if PY_MAJOR_VERSION >= 3 -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - __Pyx_NAMESTR("_hmmc"), + /* "View.MemoryView":114 + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, + * mode=u"c", bint allocate_buffer=True): # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_v_allocate_buffer = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { + PyErr_Format(PyExc_TypeError, "Argument 'format' must not be None"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_r = __pyx_array_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":113 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode=u"c", bint allocate_buffer=True): + * + */ + +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { + int __pyx_v_idx; + Py_ssize_t __pyx_v_i; + PyObject **__pyx_v_p; + PyObject *__pyx_v_encode = NULL; + PyObject *__pyx_v_dim = NULL; + char __pyx_v_order; + PyObject *__pyx_v_decode = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_INCREF(__pyx_v_format); + __Pyx_INCREF(__pyx_v_mode); + + /* "View.MemoryView":120 + * cdef PyObject **p + * + * self.ndim = len(shape) # <<<<<<<<<<<<<< + * self.itemsize = itemsize + * + */ + if (unlikely(((PyObject *)__pyx_v_shape) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = PyTuple_GET_SIZE(((PyObject *)__pyx_v_shape)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->ndim = __pyx_t_1; + + /* "View.MemoryView":121 + * + * self.ndim = len(shape) + * self.itemsize = itemsize # <<<<<<<<<<<<<< + * + * if not self.ndim: + */ + __pyx_v_self->itemsize = __pyx_v_itemsize; + + /* "View.MemoryView":123 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ + __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":124 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if self.itemsize <= 0: + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_17), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":126 + * raise ValueError("Empty shape tuple for cython.array") + * + * if self.itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ + __pyx_t_2 = ((__pyx_v_self->itemsize <= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":127 + * + * if self.itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * encode = getattr(format, 'encode', None) + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_19), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":129 + * raise ValueError("itemsize <= 0 for cython.array") + * + * encode = getattr(format, 'encode', None) # <<<<<<<<<<<<<< + * if encode: + * format = encode('ASCII') + */ + __pyx_t_3 = __Pyx_GetAttr3(__pyx_v_format, ((PyObject *)__pyx_n_s__encode), Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_encode = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":130 + * + * encode = getattr(format, 'encode', None) + * if encode: # <<<<<<<<<<<<<< + * format = encode('ASCII') + * self._format = format + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_encode); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":131 + * encode = getattr(format, 'encode', None) + * if encode: + * format = encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format + * self.format = self._format + */ + __pyx_t_3 = PyObject_Call(__pyx_v_encode, ((PyObject *)__pyx_k_tuple_20), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_format); + __pyx_v_format = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":132 + * if encode: + * format = encode('ASCII') + * self._format = format # <<<<<<<<<<<<<< + * self.format = self._format + * + */ + if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_format); + __Pyx_GIVEREF(__pyx_v_format); + __Pyx_GOTREF(__pyx_v_self->_format); + __Pyx_DECREF(((PyObject *)__pyx_v_self->_format)); + __pyx_v_self->_format = ((PyObject*)__pyx_v_format); + + /* "View.MemoryView":133 + * format = encode('ASCII') + * self._format = format + * self.format = self._format # <<<<<<<<<<<<<< + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) + */ + __pyx_t_4 = __Pyx_PyObject_AsString(((PyObject *)__pyx_v_self->_format)); if (unlikely((!__pyx_t_4) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->format = __pyx_t_4; + + /* "View.MemoryView":135 + * self.format = self._format + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<< + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) + * + */ + __pyx_v_self->_shape = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim))); + + /* "View.MemoryView":136 + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<< + * + * if not self._shape or not self._strides: + */ + __pyx_v_self->_strides = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim))); + + /* "View.MemoryView":138 + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) + * + * if not self._shape or not self._strides: # <<<<<<<<<<<<<< + * free(self._shape) + * free(self._strides) + */ + __pyx_t_2 = ((!(__pyx_v_self->_shape != 0)) != 0); + if (!__pyx_t_2) { + __pyx_t_5 = ((!(__pyx_v_self->_strides != 0)) != 0); + __pyx_t_6 = __pyx_t_5; + } else { + __pyx_t_6 = __pyx_t_2; + } + if (__pyx_t_6) { + + /* "View.MemoryView":139 + * + * if not self._shape or not self._strides: + * free(self._shape) # <<<<<<<<<<<<<< + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") + */ + free(__pyx_v_self->_shape); + + /* "View.MemoryView":140 + * if not self._shape or not self._strides: + * free(self._shape) + * free(self._strides) # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape or strides.") + * + */ + free(__pyx_v_self->_strides); + + /* "View.MemoryView":141 + * free(self._shape) + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_22), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":144 + * + * + * idx = 0 # <<<<<<<<<<<<<< + * for idx, dim in enumerate(shape): + * if dim <= 0: + */ + __pyx_v_idx = 0; + + /* "View.MemoryView":145 + * + * idx = 0 + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + __pyx_t_7 = 0; + __pyx_t_3 = ((PyObject *)__pyx_v_shape); __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; + for (;;) { + if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_8 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_8); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_8 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF(__pyx_v_dim); + __pyx_v_dim = __pyx_t_8; + __pyx_t_8 = 0; + __pyx_v_idx = __pyx_t_7; + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":146 + * idx = 0 + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * + */ + __pyx_t_8 = PyObject_RichCompare(__pyx_v_dim, __pyx_int_0, Py_LE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (__pyx_t_6) { + + /* "View.MemoryView":147 + * for idx, dim in enumerate(shape): + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< + * + * self._shape[idx] = dim + */ + __pyx_t_8 = PyInt_FromLong(__pyx_v_idx); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_dim); + PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_dim); + __Pyx_GIVEREF(__pyx_v_dim); + __pyx_t_8 = 0; + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_23), ((PyObject *)__pyx_t_9)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":149 + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * + * self._shape[idx] = dim # <<<<<<<<<<<<<< + * idx += 1 + * + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_dim); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_t_10; + + /* "View.MemoryView":150 + * + * self._shape[idx] = dim + * idx += 1 # <<<<<<<<<<<<<< + * + * if mode not in ("fortran", "c"): + */ + __pyx_v_idx = (__pyx_v_idx + 1); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":152 + * idx += 1 + * + * if mode not in ("fortran", "c"): # <<<<<<<<<<<<<< + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + * + */ + __Pyx_INCREF(__pyx_v_mode); + __pyx_t_3 = __pyx_v_mode; + __pyx_t_8 = PyObject_RichCompare(__pyx_t_3, ((PyObject *)__pyx_n_s__fortran), Py_NE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (((int)__pyx_t_6)) { + __pyx_t_8 = PyObject_RichCompare(__pyx_t_3, ((PyObject *)__pyx_n_s__c), Py_NE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_5 = ((int)__pyx_t_2); + } else { + __pyx_t_5 = ((int)__pyx_t_6); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = (__pyx_t_5 != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":153 + * + * if mode not in ("fortran", "c"): + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< + * + * cdef char order + */ + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_24), __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":156 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = 'F' + * else: + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_mode, ((PyObject *)__pyx_n_s__fortran), Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + + /* "View.MemoryView":157 + * cdef char order + * if mode == 'fortran': + * order = 'F' # <<<<<<<<<<<<<< + * else: + * order = 'C' + */ + __pyx_v_order = 'F'; + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":159 + * order = 'F' + * else: + * order = 'C' # <<<<<<<<<<<<<< + * + * self.len = fill_contig_strides_array(self._shape, self._strides, + */ + __pyx_v_order = 'C'; + } + __pyx_L11:; + + /* "View.MemoryView":161 + * order = 'C' + * + * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< + * itemsize, self.ndim, order) + * + */ + __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); + + /* "View.MemoryView":164 + * itemsize, self.ndim, order) + * + * decode = getattr(mode, 'decode', None) # <<<<<<<<<<<<<< + * if decode: + * mode = decode('ASCII') + */ + __pyx_t_3 = __Pyx_GetAttr3(__pyx_v_mode, ((PyObject *)__pyx_n_s__decode), Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_decode = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":165 + * + * decode = getattr(mode, 'decode', None) + * if decode: # <<<<<<<<<<<<<< + * mode = decode('ASCII') + * self.mode = mode + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_decode); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":166 + * decode = getattr(mode, 'decode', None) + * if decode: + * mode = decode('ASCII') # <<<<<<<<<<<<<< + * self.mode = mode + * + */ + __pyx_t_3 = PyObject_Call(__pyx_v_decode, ((PyObject *)__pyx_k_tuple_25), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_mode); + __pyx_v_mode = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":167 + * if decode: + * mode = decode('ASCII') + * self.mode = mode # <<<<<<<<<<<<<< + * + * self.free_data = allocate_buffer + */ + if (!(likely(PyUnicode_CheckExact(__pyx_v_mode))||((__pyx_v_mode) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected unicode, got %.200s", Py_TYPE(__pyx_v_mode)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_mode); + __Pyx_GIVEREF(__pyx_v_mode); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(((PyObject *)__pyx_v_self->mode)); + __pyx_v_self->mode = ((PyObject*)__pyx_v_mode); + + /* "View.MemoryView":169 + * self.mode = mode + * + * self.free_data = allocate_buffer # <<<<<<<<<<<<<< + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + */ + __pyx_v_self->free_data = __pyx_v_allocate_buffer; + + /* "View.MemoryView":170 + * + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< + * if allocate_buffer: + * self.data = malloc(self.len) + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_format, ((PyObject *)__pyx_n_b__O), Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_6; + + /* "View.MemoryView":171 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * self.data = malloc(self.len) + * if not self.data: + */ + __pyx_t_6 = (__pyx_v_allocate_buffer != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":172 + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + * self.data = malloc(self.len) # <<<<<<<<<<<<<< + * if not self.data: + * raise MemoryError("unable to allocate array data.") + */ + __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); + + /* "View.MemoryView":173 + * if allocate_buffer: + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ + __pyx_t_6 = ((!(__pyx_v_self->data != 0)) != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":174 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_27), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":176 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ + __pyx_t_6 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":177 + * + * if self.dtype_is_object: + * p = self.data # <<<<<<<<<<<<<< + * for i in range(self.len / itemsize): + * p[i] = Py_None + */ + __pyx_v_p = ((PyObject **)__pyx_v_self->data); + + /* "View.MemoryView":178 + * if self.dtype_is_object: + * p = self.data + * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< + * p[i] = Py_None + * Py_INCREF(Py_None) + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_1; __pyx_t_10+=1) { + __pyx_v_i = __pyx_t_10; + + /* "View.MemoryView":179 + * p = self.data + * for i in range(self.len / itemsize): + * p[i] = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + (__pyx_v_p[__pyx_v_i]) = Py_None; + + /* "View.MemoryView":180 + * for i in range(self.len / itemsize): + * p[i] = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + Py_INCREF(Py_None); + } + goto __pyx_L15; + } + __pyx_L15:; + goto __pyx_L13; + } + __pyx_L13:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_encode); + __Pyx_XDECREF(__pyx_v_dim); + __Pyx_XDECREF(__pyx_v_decode); + __Pyx_XDECREF(__pyx_v_format); + __Pyx_XDECREF(__pyx_v_mode); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":183 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == b"c": + */ + +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_bufmode; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + Py_ssize_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":184 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 # <<<<<<<<<<<<<< + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = -1; + + /* "View.MemoryView":185 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == b"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": + */ + __pyx_t_1 = (__Pyx_PyUnicode_Equals(((PyObject *)__pyx_v_self->mode), ((PyObject *)__pyx_n_b__c), Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":186 + * cdef int bufmode = -1 + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + + /* "View.MemoryView":187 + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ + __pyx_t_2 = (__Pyx_PyUnicode_Equals(((PyObject *)__pyx_v_self->mode), ((PyObject *)__pyx_n_b__fortran), Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":188 + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + */ + __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":189 + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ + __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":190 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_29), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":191 + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data # <<<<<<<<<<<<<< + * info.len = self.len + * info.ndim = self.ndim + */ + __pyx_t_4 = __pyx_v_self->data; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":192 + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + * info.len = self.len # <<<<<<<<<<<<<< + * info.ndim = self.ndim + * info.shape = self._shape + */ + __pyx_t_5 = __pyx_v_self->len; + __pyx_v_info->len = __pyx_t_5; + + /* "View.MemoryView":193 + * info.buf = self.data + * info.len = self.len + * info.ndim = self.ndim # <<<<<<<<<<<<<< + * info.shape = self._shape + * info.strides = self._strides + */ + __pyx_t_6 = __pyx_v_self->ndim; + __pyx_v_info->ndim = __pyx_t_6; + + /* "View.MemoryView":194 + * info.len = self.len + * info.ndim = self.ndim + * info.shape = self._shape # <<<<<<<<<<<<<< + * info.strides = self._strides + * info.suboffsets = NULL + */ + __pyx_t_7 = __pyx_v_self->_shape; + __pyx_v_info->shape = __pyx_t_7; + + /* "View.MemoryView":195 + * info.ndim = self.ndim + * info.shape = self._shape + * info.strides = self._strides # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = self.itemsize + */ + __pyx_t_7 = __pyx_v_self->_strides; + __pyx_v_info->strides = __pyx_t_7; + + /* "View.MemoryView":196 + * info.shape = self._shape + * info.strides = self._strides + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = self.itemsize + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; + + /* "View.MemoryView":197 + * info.strides = self._strides + * info.suboffsets = NULL + * info.itemsize = self.itemsize # <<<<<<<<<<<<<< + * info.readonly = 0 + * + */ + __pyx_t_5 = __pyx_v_self->itemsize; + __pyx_v_info->itemsize = __pyx_t_5; + + /* "View.MemoryView":198 + * info.suboffsets = NULL + * info.itemsize = self.itemsize + * info.readonly = 0 # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":200 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":201 + * + * if flags & PyBUF_FORMAT: + * info.format = self.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_4 = __pyx_v_self->format; + __pyx_v_info->format = __pyx_t_4; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":203 + * info.format = self.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.obj = self + */ + __pyx_v_info->format = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":205 + * info.format = NULL + * + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_array_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":209 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":210 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ + __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":211 + * def __dealloc__(array self): + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) # <<<<<<<<<<<<<< + * elif self.free_data: + * if self.dtype_is_object: + */ + __pyx_v_self->callback_free_data(__pyx_v_self->data); + goto __pyx_L3; + } + + /* "View.MemoryView":212 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ + __pyx_t_1 = (__pyx_v_self->free_data != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":213 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":215 + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) # <<<<<<<<<<<<<< + * free(self.data) + * + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":216 + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + * free(self.data) # <<<<<<<<<<<<<< + * + * free(self._strides) + */ + free(__pyx_v_self->data); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":218 + * free(self.data) + * + * free(self._strides) # <<<<<<<<<<<<<< + * free(self._shape) + * + */ + free(__pyx_v_self->_strides); + + /* "View.MemoryView":219 + * + * free(self._strides) + * free(self._shape) # <<<<<<<<<<<<<< + * + * property memview: + */ + free(__pyx_v_self->_shape); + + __Pyx_RefNannyFinishContext(); +} + +/* Python wrapper */ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = get_memview_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":223 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":225 + * def __get__(self): + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< + * return memoryview(self, flags, self.dtype_is_object) + * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":226 + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromLong(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":229 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":230 + * + * def __getattr__(self, attr): + * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * + * def __getitem__(self, item): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":232 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":233 + * + * def __getitem__(self, item): + * return self.memview[item] # <<<<<<<<<<<<<< + * + * def __setitem__(self, item, value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (!__pyx_t_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":235 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "View.MemoryView":236 + * + * def __setitem__(self, item, value): + * self.memview[item] = value # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":240 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + +static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { + struct __pyx_array_obj *__pyx_v_result = 0; + struct __pyx_array_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("array_cwrapper", 0); + + /* "View.MemoryView":244 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":245 + * + * if buf == NULL: + * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_shape)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 2, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + PyTuple_SET_ITEM(__pyx_t_5, 3, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":247 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_shape)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + PyTuple_SET_ITEM(__pyx_t_2, 3, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + + /* "View.MemoryView":248 + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) # <<<<<<<<<<<<<< + * result.data = buf + * + */ + __pyx_t_5 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 248; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__allocate_buffer), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":249 + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) + * result.data = buf # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->data = __pyx_v_buf; + } + __pyx_L3:; + + /* "View.MemoryView":251 + * result.data = buf + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + __pyx_r = ((struct __pyx_array_obj *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_name = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__name,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__name)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_name = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":277 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "View.MemoryView":278 + * cdef object name + * def __init__(self, name): + * self.name = name # <<<<<<<<<<<<<< + * def __repr__(self): + * return self.name + */ + __Pyx_INCREF(__pyx_v_name); + __Pyx_GIVEREF(__pyx_v_name); + __Pyx_GOTREF(__pyx_v_self->name); + __Pyx_DECREF(__pyx_v_self->name); + __pyx_v_self->name = __pyx_v_name; + + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":279 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":280 + * self.name = name + * def __repr__(self): + * return self.name # <<<<<<<<<<<<<< + * + * cdef generic = Enum("") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->name); + __pyx_r = __pyx_v_self->name; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":294 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + +static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { + Py_intptr_t __pyx_v_aligned_p; + size_t __pyx_v_offset; + void *__pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":296 + * cdef void *align_pointer(void *memory, size_t alignment) nogil: + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< + * cdef size_t offset + * + */ + __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + + /* "View.MemoryView":300 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":302 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + __pyx_t_1 = ((__pyx_v_offset > 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":303 + * + * if offset > 0: + * aligned_p += alignment - offset # <<<<<<<<<<<<<< + * + * return aligned_p + */ + __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":305 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview') + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_obj = 0; + int __pyx_v_flags; + int __pyx_v_dtype_is_object; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__obj,&__pyx_n_s__flags,&__pyx_n_s__dtype_is_object,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__obj)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__flags)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dtype_is_object); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_obj = values[0]; + __pyx_v_flags = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[2]) { + __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "View.MemoryView":323 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + __pyx_v_dtype_is_object = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_memoryview_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "View.MemoryView":324 + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj # <<<<<<<<<<<<<< + * self.flags = flags + * if type(self) is memoryview or obj is not None: + */ + __Pyx_INCREF(__pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __Pyx_GOTREF(__pyx_v_self->obj); + __Pyx_DECREF(__pyx_v_self->obj); + __pyx_v_self->obj = __pyx_v_obj; + + /* "View.MemoryView":325 + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj + * self.flags = flags # <<<<<<<<<<<<<< + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + */ + __pyx_v_self->flags = __pyx_v_flags; + + /* "View.MemoryView":326 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ + __pyx_t_1 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type))); + if (!(__pyx_t_1 != 0)) { + __pyx_t_2 = (__pyx_v_obj != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + } else { + __pyx_t_3 = (__pyx_t_1 != 0); + } + if (__pyx_t_3) { + + /* "View.MemoryView":327 + * self.flags = flags + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + */ + __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":328 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_t_3 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":329 + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; + + /* "View.MemoryView":330 + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * self.lock = PyThread_allocate_lock() + */ + Py_INCREF(Py_None); + goto __pyx_L4; + } + __pyx_L4:; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":332 + * Py_INCREF(Py_None) + * + * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< + * if self.lock == NULL: + * raise MemoryError + */ + __pyx_v_self->lock = PyThread_allocate_lock(); + + /* "View.MemoryView":333 + * + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + __pyx_t_3 = ((__pyx_v_self->lock == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":334 + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":336 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = self.view.format == b'O' + * else: + */ + __pyx_t_3 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":337 + * + * if flags & PyBUF_FORMAT: + * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< + * else: + * self.dtype_is_object = dtype_is_object + */ + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_6 = PyObject_RichCompare(((PyObject *)__pyx_t_5), ((PyObject *)__pyx_n_b__O), Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":339 + * self.dtype_is_object = self.view.format == b'O' + * else: + * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + */ + __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; + } + __pyx_L6:; + + /* "View.MemoryView":341 + * self.dtype_is_object = dtype_is_object + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL + */ + __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); + + /* "View.MemoryView":343 + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(memoryview self): + */ + __pyx_v_self->typeinfo = NULL; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":345 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":346 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< + * __Pyx_ReleaseBuffer(&self.view) + * + */ + __pyx_t_1 = (__pyx_v_self->obj != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":347 + * def __dealloc__(memoryview self): + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< + * + * if self.lock != NULL: + */ + __Pyx_ReleaseBuffer((&__pyx_v_self->view)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":349 + * __Pyx_ReleaseBuffer(&self.view) + * + * if self.lock != NULL: # <<<<<<<<<<<<<< + * PyThread_free_lock(self.lock) + * + */ + __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":350 + * + * if self.lock != NULL: + * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + */ + PyThread_free_lock(__pyx_v_self->lock); + goto __pyx_L4; + } + __pyx_L4:; + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":352 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + Py_ssize_t __pyx_v_dim; + char *__pyx_v_itemp; + PyObject *__pyx_v_idx = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_item_pointer", 0); + + /* "View.MemoryView":354 + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< + * + * for dim, idx in enumerate(index): + */ + __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); + + /* "View.MemoryView":356 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + __pyx_t_1 = 0; + if (PyList_CheckExact(__pyx_v_index) || PyTuple_CheckExact(__pyx_v_index)) { + __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; + } + for (;;) { + if (!__pyx_t_4 && PyList_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_4 && PyTuple_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF(__pyx_v_idx); + __pyx_v_idx = __pyx_t_5; + __pyx_t_5 = 0; + __pyx_v_dim = __pyx_t_1; + __pyx_t_1 = (__pyx_t_1 + 1); + + /* "View.MemoryView":357 + * + * for dim, idx in enumerate(index): + * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< + * + * return itemp + */ + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_7; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":359 + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + * return itemp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_itemp; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":362 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_indices = NULL; + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *(*__pyx_t_7)(PyObject *); + char *__pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":363 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":364 + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: + * return self # <<<<<<<<<<<<<< + * + * have_slices, indices = _unellipsify(index, self.view.ndim) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __pyx_r = ((PyObject *)__pyx_v_self); + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":366 + * return self + * + * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * cdef char *itemp + */ + __pyx_t_3 = ((PyObject *)_unellipsify(__pyx_v_index, __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (likely(PyTuple_CheckExact(__pyx_t_3))) { + PyObject* sequence = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_6 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = Py_TYPE(__pyx_t_6)->tp_iternext; + index = 0; __pyx_t_4 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_4)) goto __pyx_L4_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + index = 1; __pyx_t_5 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_5)) goto __pyx_L4_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_6), 2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = NULL; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L5_unpacking_done; + __pyx_L4_unpacking_failed:; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_7 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L5_unpacking_done:; + } + __pyx_v_have_slices = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; + + /* "View.MemoryView":369 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":370 + * cdef char *itemp + * if have_slices: + * return memview_slice(self, indices) # <<<<<<<<<<<<<< + * else: + * itemp = self.get_item_pointer(indices) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":372 + * return memview_slice(self, indices) + * else: + * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< + * return self.convert_item_to_object(itemp) + * + */ + __pyx_t_8 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_8 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_8; + + /* "View.MemoryView":373 + * else: + * itemp = self.get_item_pointer(indices) + * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< + * + * def __setitem__(memoryview self, object index, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + __pyx_L6:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":375 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_obj = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *(*__pyx_t_5)(PyObject *); + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_INCREF(__pyx_v_index); + + /* "View.MemoryView":376 + * + * def __setitem__(memoryview self, object index, object value): + * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * if have_slices: + */ + __pyx_t_1 = ((PyObject *)_unellipsify(__pyx_v_index, __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (likely(PyTuple_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_3 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = NULL; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L4_unpacking_done:; + } + __pyx_v_have_slices = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_v_index); + __pyx_v_index = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":378 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":379 + * + * if have_slices: + * obj = self.is_slice(value) # <<<<<<<<<<<<<< + * if obj: + * self.setitem_slice_assignment(self[index], obj) + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_obj = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":380 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":381 + * obj = self.is_slice(value) + * if obj: + * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< + * else: + * self.setitem_slice_assign_scalar(self[index], value) + */ + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (!__pyx_t_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":383 + * self.setitem_slice_assignment(self[index], obj) + * else: + * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< + * else: + * self.setitem_indexed(index, value) + */ + __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (!__pyx_t_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":385 + * self.setitem_slice_assign_scalar(self[index], value) + * else: + * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< + * + * cdef is_slice(self, obj): + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L5:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":387 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_slice", 0); + __Pyx_INCREF(__pyx_v_obj); + + /* "View.MemoryView":388 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type)); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":389 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + { + __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + /*try:*/ { + + /* "View.MemoryView":390 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_6 = PyInt_FromLong((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":391 + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * except TypeError: + * return None + */ + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_7 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_v_obj); + __pyx_v_obj = __pyx_t_7; + __pyx_t_7 = 0; + } + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L11_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":392 + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + * except TypeError: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":393 + * self.dtype_is_object) + * except TypeError: + * return None # <<<<<<<<<<<<<< + * + * return obj + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L7_except_return; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L5_exception_handled; + } + __pyx_L6_except_error:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L1_error; + __pyx_L7_except_return:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L0; + __pyx_L5_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + __pyx_L11_try_end:; + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":395 + * return None + * + * return obj # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assignment(self, dst, src): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_obj); + __pyx_r = __pyx_v_obj; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":397 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { + __Pyx_memviewslice __pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_src_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); + + /* "View.MemoryView":401 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":402 + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< + * src.ndim, dst.ndim, self.dtype_is_object) + * + */ + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":403 + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s__ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s__ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":405 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { + int __pyx_v_array[128]; + void *__pyx_v_tmp; + void *__pyx_v_item; + __Pyx_memviewslice __pyx_v_tmp_slice; + __Pyx_memviewslice *__pyx_v_dst_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); + + /* "View.MemoryView":407 + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + * cdef int array[128] + * cdef void *tmp = NULL # <<<<<<<<<<<<<< + * cdef void *item + * + */ + __pyx_v_tmp = NULL; + + /* "View.MemoryView":411 + * + * cdef __Pyx_memviewslice tmp_slice, *dst_slice + * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< + * + * if self.view.itemsize > sizeof(array): + */ + __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); + + /* "View.MemoryView":413 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: + */ + __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":414 + * + * if self.view.itemsize > sizeof(array): + * tmp = malloc(self.view.itemsize) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError + */ + __pyx_v_tmp = malloc(__pyx_v_self->view.itemsize); + + /* "View.MemoryView":415 + * if self.view.itemsize > sizeof(array): + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":416 + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * item = tmp + * else: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":417 + * if tmp == NULL: + * raise MemoryError + * item = tmp # <<<<<<<<<<<<<< + * else: + * item = array + */ + __pyx_v_item = __pyx_v_tmp; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":419 + * item = tmp + * else: + * item = array # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_v_item = ((void *)__pyx_v_array); + } + __pyx_L3:; + + /* "View.MemoryView":421 + * item = array + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":422 + * + * if self.dtype_is_object: + * ( item)[0] = value # <<<<<<<<<<<<<< + * else: + * try: + */ + (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":424 + * ( item)[0] = value + * else: + * try: # <<<<<<<<<<<<<< + * self.assign_item_from_object( item, value) + * except: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":425 + * else: + * try: + * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< + * except: + * free(tmp) + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L13_try_end; + __pyx_L6_error:; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":426 + * try: + * self.assign_item_from_object( item, value) + * except: # <<<<<<<<<<<<<< + * free(tmp) + * raise + */ + /*except:*/ { + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 426; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":427 + * self.assign_item_from_object( item, value) + * except: + * free(tmp) # <<<<<<<<<<<<<< + * raise + * + */ + free(__pyx_v_tmp); + + /* "View.MemoryView":428 + * except: + * free(tmp) + * raise # <<<<<<<<<<<<<< + * + * + */ + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_7); + __Pyx_ErrRestore(__pyx_t_5, __pyx_t_6, __pyx_t_7); + __pyx_t_5 = 0; __pyx_t_6 = 0; __pyx_t_7 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 428; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L7_exception_handled; + } + __pyx_L8_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L7_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L13_try_end:; + } + } + __pyx_L5:; + + /* "View.MemoryView":432 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":433 + * + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + */ + __pyx_t_7 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":435 + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) # <<<<<<<<<<<<<< + * free(tmp) + * + */ + __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); + + /* "View.MemoryView":436 + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + * free(tmp) # <<<<<<<<<<<<<< + * + * cdef setitem_indexed(self, index, value): + */ + free(__pyx_v_tmp); + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":438 + * free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_indexed", 0); + + /* "View.MemoryView":439 + * + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< + * self.assign_item_from_object(itemp, value) + * + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_1; + + /* "View.MemoryView":440 + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":442 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_v_struct = NULL; + PyObject *__pyx_v_bytesitem = 0; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":445 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef bytes bytesitem + * + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__struct), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":448 + * cdef bytes bytesitem + * + * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< + * try: + * result = struct.unpack(self.view.format, bytesitem) + */ + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":449 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":450 + * bytesitem = itemp[:self.view.itemsize] + * try: + * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< + * except struct.error: + * raise ValueError("Unable to convert item to object") + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__unpack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __Pyx_INCREF(((PyObject *)__pyx_v_bytesitem)); + PyTuple_SET_ITEM(__pyx_t_6, 1, ((PyObject *)__pyx_v_bytesitem)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_bytesitem)); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + } + /*else:*/ { + + /* "View.MemoryView":454 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + __pyx_t_7 = strlen(__pyx_v_self->view.format); + __pyx_t_8 = ((__pyx_t_7 == 1) != 0); + if (__pyx_t_8) { + + /* "View.MemoryView":455 + * else: + * if len(self.view.format) == 1: + * return result[0] # <<<<<<<<<<<<<< + * return result + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_result, 0, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_5) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L6_except_return; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":456 + * if len(self.view.format) == 1: + * return result[0] + * return result # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L6_except_return; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L10_try_end; + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":451 + * try: + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: # <<<<<<<<<<<<<< + * raise ValueError("Unable to convert item to object") + * else: + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__error); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_1); + + /* "View.MemoryView":452 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_t_10 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_31), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L4_exception_handled; + } + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L6_except_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + __pyx_L4_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L10_try_end:; + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesitem); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":458 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_v_struct = NULL; + char __pyx_v_c; + PyObject *__pyx_v_bytesvalue = 0; + Py_ssize_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + char *__pyx_t_10; + char *__pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":461 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef char c + * cdef bytes bytesvalue + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__struct), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":466 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + __pyx_t_2 = PyTuple_Check(__pyx_v_value); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":467 + * + * if isinstance(value, tuple): + * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< + * else: + * bytesvalue = struct.pack(self.view.format, value) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = 0; + __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_6 = PyNumber_Add(((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":469 + * bytesvalue = struct.pack(self.view.format, *value) + * else: + * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< + * + * for i, c in enumerate(bytesvalue): + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__pack); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_6)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_6)); + __Pyx_INCREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + __pyx_t_6 = 0; + __pyx_t_6 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_6)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":471 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = 0; + if (unlikely(((PyObject *)__pyx_v_bytesvalue) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_INCREF(((PyObject *)__pyx_v_bytesvalue)); + __pyx_t_8 = __pyx_v_bytesvalue; + __pyx_t_10 = PyBytes_AS_STRING(__pyx_t_8); + __pyx_t_11 = (__pyx_t_10 + PyBytes_GET_SIZE(__pyx_t_8)); + for (__pyx_t_12 = __pyx_t_10; __pyx_t_12 < __pyx_t_11; __pyx_t_12++) { + __pyx_t_9 = __pyx_t_12; + __pyx_v_c = (__pyx_t_9[0]); + + /* "View.MemoryView":472 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + __pyx_v_i = __pyx_t_7; + + /* "View.MemoryView":471 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":472 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; + } + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(((PyObject *)__pyx_t_8)); + __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":475 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + char *__pyx_t_3; + void *__pyx_t_4; + int __pyx_t_5; + Py_ssize_t __pyx_t_6; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":476 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":477 + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape # <<<<<<<<<<<<<< + * else: + * info.shape = NULL + */ + __pyx_t_2 = __pyx_v_self->view.shape; + __pyx_v_info->shape = __pyx_t_2; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":479 + * info.shape = self.view.shape + * else: + * info.shape = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_STRIDES: + */ + __pyx_v_info->shape = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":481 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":482 + * + * if flags & PyBUF_STRIDES: + * info.strides = self.view.strides # <<<<<<<<<<<<<< + * else: + * info.strides = NULL + */ + __pyx_t_2 = __pyx_v_self->view.strides; + __pyx_v_info->strides = __pyx_t_2; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":484 + * info.strides = self.view.strides + * else: + * info.strides = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_INDIRECT: + */ + __pyx_v_info->strides = NULL; + } + __pyx_L4:; + + /* "View.MemoryView":486 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":487 + * + * if flags & PyBUF_INDIRECT: + * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< + * else: + * info.suboffsets = NULL + */ + __pyx_t_2 = __pyx_v_self->view.suboffsets; + __pyx_v_info->suboffsets = __pyx_t_2; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":489 + * info.suboffsets = self.view.suboffsets + * else: + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->suboffsets = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":491 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":492 + * + * if flags & PyBUF_FORMAT: + * info.format = self.view.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_3 = __pyx_v_self->view.format; + __pyx_v_info->format = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":494 + * info.format = self.view.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.buf = self.view.buf + */ + __pyx_v_info->format = NULL; + } + __pyx_L6:; + + /* "View.MemoryView":496 + * info.format = NULL + * + * info.buf = self.view.buf # <<<<<<<<<<<<<< + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + */ + __pyx_t_4 = __pyx_v_self->view.buf; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":497 + * + * info.buf = self.view.buf + * info.ndim = self.view.ndim # <<<<<<<<<<<<<< + * info.itemsize = self.view.itemsize + * info.len = self.view.len + */ + __pyx_t_5 = __pyx_v_self->view.ndim; + __pyx_v_info->ndim = __pyx_t_5; + + /* "View.MemoryView":498 + * info.buf = self.view.buf + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< + * info.len = self.view.len + * info.readonly = 0 + */ + __pyx_t_6 = __pyx_v_self->view.itemsize; + __pyx_v_info->itemsize = __pyx_t_6; + + /* "View.MemoryView":499 + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + * info.len = self.view.len # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.obj = self + */ + __pyx_t_6 = __pyx_v_self->view.len; + __pyx_v_info->len = __pyx_t_6; + + /* "View.MemoryView":500 + * info.itemsize = self.view.itemsize + * info.len = self.view.len + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.obj = self + * + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":501 + * info.len = self.view.len + * info.readonly = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + __pyx_r = 0; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":508 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":509 + * @cname('__pyx_memoryview_transpose') + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< + * transpose_memslice(&result.from_slice) + * return result + */ + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":510 + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":511 + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + * return result # <<<<<<<<<<<<<< + * + * property base: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":515 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":516 + * @cname('__pyx_memoryview__get__base') + * def __get__(self): + * return self.obj # <<<<<<<<<<<<<< + * + * property shape: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->obj); + __pyx_r = __pyx_v_self->obj; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":520 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":521 + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property strides: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_v_self->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->view.shape[__pyx_v_i])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __pyx_t_4 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_1))); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_r = ((PyObject *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":525 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":526 + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":528 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_33), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":530 + * raise ValueError("Buffer view does not expose strides") + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property suboffsets: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.strides[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_2))); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_5); + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":534 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":535 + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return [-1] * self.view.ndim + * + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":536 + * def __get__(self): + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(1 * ((__pyx_v_self->view.ndim<0) ? 0:__pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_self->view.ndim; __pyx_temp++) { + __Pyx_INCREF(__pyx_int_neg_1); + PyList_SET_ITEM(__pyx_t_2, __pyx_temp, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + } + } + __pyx_r = ((PyObject *)__pyx_t_2); + __pyx_t_2 = 0; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":538 + * return [-1] * self.view.ndim + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property ndim: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.suboffsets[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_2))); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_5); + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":542 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":543 + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): + * return self.view.ndim # <<<<<<<<<<<<<< + * + * property itemsize: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromLong(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":547 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":548 + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): + * return self.view.itemsize # <<<<<<<<<<<<<< + * + * property nbytes: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":552 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":553 + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): + * return self.size * self.view.itemsize # <<<<<<<<<<<<<< + * + * property size: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":557 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":558 + * @cname('__pyx_memoryview_get_size') + * def __get__(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + __pyx_t_1 = (__pyx_v_self->_size == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":559 + * def __get__(self): + * if self._size is None: + * result = 1 # <<<<<<<<<<<<<< + * + * for length in self.shape: + */ + __Pyx_INCREF(__pyx_int_1); + __pyx_v_result = __pyx_int_1; + + /* "View.MemoryView":561 + * result = 1 + * + * for length in self.shape: # <<<<<<<<<<<<<< + * result *= length + * + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyList_CheckExact(__pyx_t_3) || PyTuple_CheckExact(__pyx_t_3)) { + __pyx_t_4 = __pyx_t_3; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_3 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_3)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF(__pyx_v_length); + __pyx_v_length = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":562 + * + * for length in self.shape: + * result *= length # <<<<<<<<<<<<<< + * + * self._size = result + */ + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_result); + __pyx_v_result = __pyx_t_3; + __pyx_t_3 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "View.MemoryView":564 + * result *= length + * + * self._size = result # <<<<<<<<<<<<<< + * + * return self._size + */ + __Pyx_INCREF(__pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __Pyx_GOTREF(__pyx_v_self->_size); + __Pyx_DECREF(__pyx_v_self->_size); + __pyx_v_self->_size = __pyx_v_result; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":566 + * self._size = result + * + * return self._size # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->_size); + __pyx_r = __pyx_v_self->_size; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":568 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__len__", 0); + + /* "View.MemoryView":569 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":570 + * def __len__(self): + * if self.view.ndim >= 1: + * return self.view.shape[0] # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_r = (__pyx_v_self->view.shape[0]); + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":572 + * return self.view.shape[0] + * + * return 0 # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":574 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":575 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s____class__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s____name__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":576 + * def __repr__(self): + * return "" % (self.base.__class__.__name__, + * id(self)) # <<<<<<<<<<<<<< + * + * def __str__(self): + */ + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __pyx_t_3 = PyObject_Call(__pyx_builtin_id, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_34), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":578 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__str__", 0); + + /* "View.MemoryView":579 + * + * def __str__(self): + * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s____class__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s____name__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_35), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":582 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_c_contig", 0); + + /* "View.MemoryView":584 + * def is_c_contig(self): + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":585 + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< + * + * def is_f_contig(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":587 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_f_contig", 0); + + /* "View.MemoryView":589 + * def is_f_contig(self): + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":590 + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< + * + * def copy(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":592 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_mslice; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "View.MemoryView":594 + * def copy(self): + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &mslice) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); + + /* "View.MemoryView":596 + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + * + * slice_copy(self, &mslice) # <<<<<<<<<<<<<< + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); + + /* "View.MemoryView":600 + * self.view.itemsize, + * flags|PyBUF_C_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * + * return memoryview_copy_from_slice(self, &mslice) + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k__c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":602 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< + * + * def copy_fortran(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":604 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy_fortran", 0); + + /* "View.MemoryView":606 + * def copy_fortran(self): + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &src) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); + + /* "View.MemoryView":608 + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + * + * slice_copy(self, &src) # <<<<<<<<<<<<<< + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); + + /* "View.MemoryView":612 + * self.view.itemsize, + * flags|PyBUF_F_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * + * return memoryview_copy_from_slice(self, &dst) + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k__fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dst = __pyx_t_1; + + /* "View.MemoryView":614 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":618 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + +static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { + struct __pyx_memoryview_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); + + /* "View.MemoryView":619 + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< + * result.typeinfo = typeinfo + * return result + */ + __pyx_t_1 = PyInt_FromLong(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); + __Pyx_GIVEREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":620 + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_v_result->typeinfo = __pyx_v_typeinfo; + + /* "View.MemoryView":621 + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_check') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":624 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("memoryview_check", 0); + + /* "View.MemoryView":625 + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): + * return isinstance(o, memoryview) # <<<<<<<<<<<<<< + * + * cdef tuple _unellipsify(object index, int ndim): + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type)); + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":627 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + +static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { + PyObject *__pyx_v_tup = NULL; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_have_slices = NULL; + int __pyx_v_seen_ellipsis; + CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_item = NULL; + PyObject *__pyx_v_nslices = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + Py_ssize_t __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_unellipsify", 0); + + /* "View.MemoryView":632 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + __pyx_t_1 = PyTuple_Check(__pyx_v_index); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":633 + * """ + * if not isinstance(index, tuple): + * tup = (index,) # <<<<<<<<<<<<<< + * else: + * tup = index + */ + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 633; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_index); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); + __Pyx_GIVEREF(__pyx_v_index); + __pyx_v_tup = ((PyObject *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":635 + * tup = (index,) + * else: + * tup = index # <<<<<<<<<<<<<< + * + * result = [] + */ + __Pyx_INCREF(__pyx_v_index); + __pyx_v_tup = __pyx_v_index; + } + __pyx_L3:; + + /* "View.MemoryView":637 + * tup = index + * + * result = [] # <<<<<<<<<<<<<< + * have_slices = False + * seen_ellipsis = False + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_result = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":638 + * + * result = [] + * have_slices = False # <<<<<<<<<<<<<< + * seen_ellipsis = False + * for idx, item in enumerate(tup): + */ + __pyx_t_3 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_have_slices = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":639 + * result = [] + * have_slices = False + * seen_ellipsis = False # <<<<<<<<<<<<<< + * for idx, item in enumerate(tup): + * if item is Ellipsis: + */ + __pyx_v_seen_ellipsis = 0; + + /* "View.MemoryView":640 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_3 = __pyx_int_0; + if (PyList_CheckExact(__pyx_v_tup) || PyTuple_CheckExact(__pyx_v_tup)) { + __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_7 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_7)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_XDECREF(__pyx_v_item); + __pyx_v_item = __pyx_t_7; + __pyx_t_7 = 0; + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_v_idx); + __pyx_v_idx = __pyx_t_3; + __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_t_7; + __pyx_t_7 = 0; + + /* "View.MemoryView":641 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ + __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":642 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ + __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":643 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_result), __pyx_n_s__extend); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_36), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_9) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_9) + 1))); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_9) + 1); __pyx_temp++) { + __Pyx_INCREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_10, __pyx_temp, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + } + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_10)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_10)); + __pyx_t_10 = 0; + __pyx_t_10 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + + /* "View.MemoryView":644 + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True # <<<<<<<<<<<<<< + * else: + * result.append(slice(None)) + */ + __pyx_v_seen_ellipsis = 1; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":646 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_t_10 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_37), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_result, __pyx_t_10); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + } + __pyx_L7:; + + /* "View.MemoryView":647 + * else: + * result.append(slice(None)) + * have_slices = True # <<<<<<<<<<<<<< + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + */ + __pyx_t_10 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_v_have_slices); + __pyx_v_have_slices = __pyx_t_10; + __pyx_t_10 = 0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":649 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ + __pyx_t_1 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_1 = ((!(__Pyx_PyIndex_Check(__pyx_v_item) != 0)) != 0); + __pyx_t_12 = __pyx_t_1; + } else { + __pyx_t_12 = __pyx_t_2; + } + if (__pyx_t_12) { + + /* "View.MemoryView":650 + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< + * + * have_slices = have_slices or isinstance(item, slice) + */ + __pyx_t_10 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_38), ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_10)); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_10)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_10)); + __pyx_t_10 = 0; + __pyx_t_10 = PyObject_Call(__pyx_builtin_TypeError, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":652 + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< + * result.append(item) + * + */ + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_12) { + __pyx_t_12 = PySlice_Check(__pyx_v_item); + __pyx_t_10 = __Pyx_PyBool_FromLong(__pyx_t_12); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_8 = __pyx_t_10; + __pyx_t_10 = 0; + } else { + __Pyx_INCREF(__pyx_v_have_slices); + __pyx_t_8 = __pyx_v_have_slices; + } + __Pyx_DECREF(__pyx_v_have_slices); + __pyx_v_have_slices = __pyx_t_8; + __pyx_t_8 = 0; + + /* "View.MemoryView":653 + * + * have_slices = have_slices or isinstance(item, slice) + * result.append(item) # <<<<<<<<<<<<<< + * + * nslices = ndim - len(result) + */ + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":655 + * result.append(item) + * + * nslices = ndim - len(result) # <<<<<<<<<<<<<< + * if nslices: + * result.extend([slice(None)] * nslices) + */ + __pyx_t_5 = PyList_GET_SIZE(((PyObject *)__pyx_v_result)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_ndim - __pyx_t_5)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_nslices = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":656 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_nslices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_12) { + + /* "View.MemoryView":657 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_result), __pyx_n_s__extend); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_39), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyList_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_8, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + { PyObject* __pyx_temp = PyNumber_InPlaceMultiply(__pyx_t_8, __pyx_v_nslices); if (unlikely(!__pyx_temp)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_temp); + __Pyx_DECREF(__pyx_t_8); + __pyx_t_8 = __pyx_temp; + } + __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":659 + * result.extend([slice(None)] * nslices) + * + * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_12) { + __Pyx_INCREF(__pyx_v_nslices); + __pyx_t_8 = __pyx_v_nslices; + } else { + __Pyx_INCREF(__pyx_v_have_slices); + __pyx_t_8 = __pyx_v_have_slices; + } + __pyx_t_4 = ((PyObject *)PyList_AsTuple(__pyx_v_result)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_8 = 0; + __pyx_t_4 = 0; + __pyx_r = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = ((PyObject*)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_tup); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_item); + __Pyx_XDECREF(__pyx_v_nslices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":661 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + +static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); + + /* "View.MemoryView":663 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * cdef int i + * for i in range(ndim): # <<<<<<<<<<<<<< + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":664 + * cdef int i + * for i in range(ndim): + * if suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ + __pyx_t_3 = (((__pyx_v_suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":665 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_41), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":672 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { + int __pyx_v_new_ndim; + int __pyx_v_suboffset_dim; + int __pyx_v_dim; + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + __Pyx_memviewslice *__pyx_v_p_src; + struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; + __Pyx_memviewslice *__pyx_v_p_dst; + int *__pyx_v_p_suboffset_dim; + Py_ssize_t __pyx_v_start; + Py_ssize_t __pyx_v_stop; + Py_ssize_t __pyx_v_step; + int __pyx_v_have_start; + int __pyx_v_have_stop; + int __pyx_v_have_step; + PyObject *__pyx_v_index = NULL; + struct __pyx_memoryview_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + struct __pyx_memoryview_obj *__pyx_t_3; + char *__pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + PyObject *__pyx_t_12 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memview_slice", 0); + + /* "View.MemoryView":673 + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): + * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< + * cdef bint negative_step + * cdef __Pyx_memviewslice src, dst + */ + __pyx_v_new_ndim = 0; + __pyx_v_suboffset_dim = -1; + + /* "View.MemoryView":680 + * + * + * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< + * + * cdef _memoryviewslice memviewsliceobj + */ + memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); + + /* "View.MemoryView":684 + * cdef _memoryviewslice memviewsliceobj + * + * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 684; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #endif + + /* "View.MemoryView":686 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":687 + * + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview # <<<<<<<<<<<<<< + * p_src = &memviewsliceobj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(((PyObject *)__pyx_v_memview)); + __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview); + + /* "View.MemoryView":688 + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, &src) + */ + __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":690 + * p_src = &memviewsliceobj.from_slice + * else: + * slice_copy(memview, &src) # <<<<<<<<<<<<<< + * p_src = &src + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); + + /* "View.MemoryView":691 + * else: + * slice_copy(memview, &src) + * p_src = &src # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_src = (&__pyx_v_src); + } + __pyx_L3:; + + /* "View.MemoryView":697 + * + * + * dst.memview = p_src.memview # <<<<<<<<<<<<<< + * dst.data = p_src.data + * + */ + __pyx_t_3 = __pyx_v_p_src->memview; + __pyx_v_dst.memview = __pyx_t_3; + + /* "View.MemoryView":698 + * + * dst.memview = p_src.memview + * dst.data = p_src.data # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = __pyx_v_p_src->data; + __pyx_v_dst.data = __pyx_t_4; + + /* "View.MemoryView":703 + * + * + * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< + * cdef int *p_suboffset_dim = &suboffset_dim + * cdef Py_ssize_t start, stop, step + */ + __pyx_v_p_dst = (&__pyx_v_dst); + + /* "View.MemoryView":704 + * + * cdef __Pyx_memviewslice *p_dst = &dst + * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< + * cdef Py_ssize_t start, stop, step + * cdef bint have_start, have_stop, have_step + */ + __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); + + /* "View.MemoryView":708 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + __pyx_t_5 = 0; + if (PyList_CheckExact(__pyx_v_indices) || PyTuple_CheckExact(__pyx_v_indices)) { + __pyx_t_6 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_6); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = Py_TYPE(__pyx_t_6)->tp_iternext; + } + for (;;) { + if (!__pyx_t_8 && PyList_CheckExact(__pyx_t_6)) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_6)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_6, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_6, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_8 && PyTuple_CheckExact(__pyx_t_6)) { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_6)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_6, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_9 = __pyx_t_8(__pyx_t_6); + if (unlikely(!__pyx_t_9)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_9); + } + __Pyx_XDECREF(__pyx_v_index); + __pyx_v_index = __pyx_t_9; + __pyx_t_9 = 0; + __pyx_v_dim = __pyx_t_5; + __pyx_t_5 = (__pyx_t_5 + 1); + + /* "View.MemoryView":709 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ + __pyx_t_2 = (__Pyx_PyIndex_Check(__pyx_v_index) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":713 + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< + * 0, 0, 0, # have_{start,stop,step} + * False) + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":715 + * index, 0, 0, # start, stop, step + * 0, 0, 0, # have_{start,stop,step} + * False) # <<<<<<<<<<<<<< + * elif index is None: + * p_dst.shape[new_ndim] = 1 + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 710; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + + /* "View.MemoryView":716 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ + __pyx_t_2 = (__pyx_v_index == Py_None); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":717 + * False) + * elif index is None: + * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + */ + (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; + + /* "View.MemoryView":718 + * elif index is None: + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 + */ + (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; + + /* "View.MemoryView":719 + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< + * new_ndim += 1 + * else: + */ + (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1; + + /* "View.MemoryView":720 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 # <<<<<<<<<<<<<< + * else: + * start = index.start or 0 + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":722 + * new_ndim += 1 + * else: + * start = index.start or 0 # <<<<<<<<<<<<<< + * stop = index.stop or 0 + * step = index.step or 0 + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_start = __pyx_t_10; + + /* "View.MemoryView":723 + * else: + * start = index.start or 0 + * stop = index.stop or 0 # <<<<<<<<<<<<<< + * step = index.step or 0 + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_12); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_9 = __pyx_int_0; + } else { + __pyx_t_9 = __pyx_t_12; + __pyx_t_12 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_stop = __pyx_t_10; + + /* "View.MemoryView":724 + * start = index.start or 0 + * stop = index.stop or 0 + * step = index.step or 0 # <<<<<<<<<<<<<< + * + * have_start = index.start is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_step = __pyx_t_10; + + /* "View.MemoryView":726 + * step = index.step or 0 + * + * have_start = index.start is not None # <<<<<<<<<<<<<< + * have_stop = index.stop is not None + * have_step = index.step is not None + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__start); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 726; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_start = __pyx_t_1; + + /* "View.MemoryView":727 + * + * have_start = index.start is not None + * have_stop = index.stop is not None # <<<<<<<<<<<<<< + * have_step = index.step is not None + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 727; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_stop = __pyx_t_1; + + /* "View.MemoryView":728 + * have_start = index.start is not None + * have_stop = index.stop is not None + * have_step = index.step is not None # <<<<<<<<<<<<<< + * + * slice_memviewslice( + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__step); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_step = __pyx_t_1; + + /* "View.MemoryView":735 + * start, stop, step, + * have_start, have_stop, have_step, + * True) # <<<<<<<<<<<<<< + * new_ndim += 1 + * + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 730; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":736 + * have_start, have_stop, have_step, + * True) + * new_ndim += 1 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "View.MemoryView":738 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":739 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":740 + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 740; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":742 + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + */ + __pyx_t_6 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_6); + __pyx_t_6 = 0; + goto __pyx_L0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":744 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":745 + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_6 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 744; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 744; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_6); + __pyx_t_6 = 0; + goto __pyx_L0; + } + __pyx_L7:; + + __pyx_r = ((struct __pyx_memoryview_obj *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":769 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { + Py_ssize_t __pyx_v_new_shape; + int __pyx_v_negative_step; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":789 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":791 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + __pyx_t_1 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":792 + * + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":793 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + __pyx_t_1 = (0 <= __pyx_v_start); + if (__pyx_t_1) { + __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); + } + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":794 + * start += shape + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< + * else: + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_42, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":797 + * else: + * + * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< + * + * if have_step and step == 0: + */ + __pyx_t_2 = (__pyx_v_have_step != 0); + if (__pyx_t_2) { + __pyx_t_1 = (__pyx_v_step < 0); + __pyx_t_4 = __pyx_t_1; + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_v_negative_step = __pyx_t_4; + + /* "View.MemoryView":799 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + if ((__pyx_v_have_step != 0)) { + __pyx_t_4 = (__pyx_v_step == 0); + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = (__pyx_v_have_step != 0); + } + if (__pyx_t_2) { + + /* "View.MemoryView":800 + * + * if have_step and step == 0: + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_43, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":803 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + __pyx_t_2 = (__pyx_v_have_start != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":804 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":805 + * if have_start: + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if start < 0: + * start = 0 + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":806 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":807 + * start += shape + * if start < 0: + * start = 0 # <<<<<<<<<<<<<< + * elif start >= shape: + * if negative_step: + */ + __pyx_v_start = 0; + goto __pyx_L9; + } + __pyx_L9:; + goto __pyx_L8; + } + + /* "View.MemoryView":808 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":809 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":810 + * elif start >= shape: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = shape + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L10; + } + /*else*/ { + + /* "View.MemoryView":812 + * start = shape - 1 + * else: + * start = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_start = __pyx_v_shape; + } + __pyx_L10:; + goto __pyx_L8; + } + __pyx_L8:; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":814 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":815 + * else: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = 0 + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":817 + * start = shape - 1 + * else: + * start = 0 # <<<<<<<<<<<<<< + * + * if have_stop: + */ + __pyx_v_start = 0; + } + __pyx_L11:; + } + __pyx_L7:; + + /* "View.MemoryView":819 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + __pyx_t_2 = (__pyx_v_have_stop != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":820 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":821 + * if have_stop: + * if stop < 0: + * stop += shape # <<<<<<<<<<<<<< + * if stop < 0: + * stop = 0 + */ + __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); + + /* "View.MemoryView":822 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":823 + * stop += shape + * if stop < 0: + * stop = 0 # <<<<<<<<<<<<<< + * elif stop > shape: + * stop = shape + */ + __pyx_v_stop = 0; + goto __pyx_L14; + } + __pyx_L14:; + goto __pyx_L13; + } + + /* "View.MemoryView":824 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":825 + * stop = 0 + * elif stop > shape: + * stop = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_stop = __pyx_v_shape; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L12; + } + /*else*/ { + + /* "View.MemoryView":827 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":828 + * else: + * if negative_step: + * stop = -1 # <<<<<<<<<<<<<< + * else: + * stop = shape + */ + __pyx_v_stop = -1; + goto __pyx_L15; + } + /*else*/ { + + /* "View.MemoryView":830 + * stop = -1 + * else: + * stop = shape # <<<<<<<<<<<<<< + * + * if not have_step: + */ + __pyx_v_stop = __pyx_v_shape; + } + __pyx_L15:; + } + __pyx_L12:; + + /* "View.MemoryView":832 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":833 + * + * if not have_step: + * step = 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_step = 1; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":837 + * + * with cython.cdivision(True): + * new_shape = (stop - start) // step # <<<<<<<<<<<<<< + * + * if (stop - start) - step * new_shape: + */ + __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); + + /* "View.MemoryView":839 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":840 + * + * if (stop - start) - step * new_shape: + * new_shape += 1 # <<<<<<<<<<<<<< + * + * if new_shape < 0: + */ + __pyx_v_new_shape = (__pyx_v_new_shape + 1); + goto __pyx_L17; + } + __pyx_L17:; + + /* "View.MemoryView":842 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":843 + * + * if new_shape < 0: + * new_shape = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_new_shape = 0; + goto __pyx_L18; + } + __pyx_L18:; + + /* "View.MemoryView":846 + * + * + * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset + */ + (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); + + /* "View.MemoryView":847 + * + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< + * dst.suboffsets[new_ndim] = suboffset + * + */ + (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; + + /* "View.MemoryView":848 + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; + } + __pyx_L3:; + + /* "View.MemoryView":851 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":852 + * + * if suboffset_dim[0] < 0: + * dst.data += start * stride # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride + */ + __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); + goto __pyx_L19; + } + /*else*/ { + + /* "View.MemoryView":854 + * dst.data += start * stride + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< + * + * if suboffset >= 0: + */ + __pyx_t_3 = (__pyx_v_suboffset_dim[0]); + (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); + } + __pyx_L19:; + + /* "View.MemoryView":856 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":857 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":858 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":859 + * if not is_slice: + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + */ + __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); + goto __pyx_L22; + } + /*else*/ { + + /* "View.MemoryView":862 + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< + * else: + * suboffset_dim[0] = new_ndim + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_44, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L22:; + goto __pyx_L21; + } + /*else*/ { + + /* "View.MemoryView":864 + * "must be indexed and not sliced", dim) + * else: + * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< + * + * return 0 + */ + (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; + } + __pyx_L21:; + goto __pyx_L20; + } + __pyx_L20:; + + /* "View.MemoryView":866 + * suboffset_dim[0] = new_ndim + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":872 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + +static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, int __pyx_v_dim) { + Py_ssize_t __pyx_v_shape; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_suboffset; + Py_ssize_t __pyx_v_itemsize; + char *__pyx_v_resultp; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pybuffer_index", 0); + + /* "View.MemoryView":874 + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< + * cdef Py_ssize_t itemsize = view.itemsize + * cdef char *resultp + */ + __pyx_v_suboffset = -1; + + /* "View.MemoryView":875 + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< + * cdef char *resultp + * + */ + __pyx_t_1 = __pyx_v_view->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":878 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":879 + * + * if view.ndim == 0: + * shape = view.len / itemsize # <<<<<<<<<<<<<< + * stride = itemsize + * else: + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 879; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 879; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); + + /* "View.MemoryView":880 + * if view.ndim == 0: + * shape = view.len / itemsize + * stride = itemsize # <<<<<<<<<<<<<< + * else: + * shape = view.shape[dim] + */ + __pyx_v_stride = __pyx_v_itemsize; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":882 + * stride = itemsize + * else: + * shape = view.shape[dim] # <<<<<<<<<<<<<< + * stride = view.strides[dim] + * if view.suboffsets != NULL: + */ + __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); + + /* "View.MemoryView":883 + * else: + * shape = view.shape[dim] + * stride = view.strides[dim] # <<<<<<<<<<<<<< + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] + */ + __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); + + /* "View.MemoryView":884 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":885 + * stride = view.strides[dim] + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< + * + * if index < 0: + */ + __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); + goto __pyx_L4; + } + __pyx_L4:; + } + __pyx_L3:; + + /* "View.MemoryView":887 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":888 + * + * if index < 0: + * index += view.shape[dim] # <<<<<<<<<<<<<< + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + */ + __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); + + /* "View.MemoryView":889 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":890 + * index += view.shape[dim] + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * if index >= shape: + */ + __pyx_t_3 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_45), __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_builtin_IndexError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":892 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":893 + * + * if index >= shape: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * resultp = bufp + index * stride + */ + __pyx_t_4 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_45), __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_IndexError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + + /* "View.MemoryView":895 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * resultp = bufp + index * stride # <<<<<<<<<<<<<< + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset + */ + __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); + + /* "View.MemoryView":896 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":897 + * resultp = bufp + index * stride + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< + * + * return resultp + */ + __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":899 + * resultp = ( resultp)[0] + suboffset + * + * return resultp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_resultp; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":905 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + +static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { + int __pyx_v_ndim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + int __pyx_v_i; + int __pyx_v_j; + int __pyx_r; + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + long __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":906 + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: + * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< + * + * cdef Py_ssize_t *shape = memslice.shape + */ + __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; + __pyx_v_ndim = __pyx_t_1; + + /* "View.MemoryView":908 + * cdef int ndim = memslice.memview.view.ndim + * + * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< + * cdef Py_ssize_t *strides = memslice.strides + * + */ + __pyx_t_2 = __pyx_v_memslice->shape; + __pyx_v_shape = __pyx_t_2; + + /* "View.MemoryView":909 + * + * cdef Py_ssize_t *shape = memslice.shape + * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_v_memslice->strides; + __pyx_v_strides = __pyx_t_2; + + /* "View.MemoryView":913 + * + * cdef int i, j + * for i in range(ndim / 2): # <<<<<<<<<<<<<< + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + */ + __pyx_t_3 = __Pyx_div_long(__pyx_v_ndim, 2); + for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":914 + * cdef int i, j + * for i in range(ndim / 2): + * j = ndim - 1 - i # <<<<<<<<<<<<<< + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] + */ + __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); + + /* "View.MemoryView":915 + * for i in range(ndim / 2): + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< + * shape[i], shape[j] = shape[j], shape[i] + * + */ + __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); + __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); + (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; + (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; + + /* "View.MemoryView":916 + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + */ + __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); + __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); + (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; + (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; + + /* "View.MemoryView":918 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + __pyx_t_6 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); + if (!__pyx_t_6) { + __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); + __pyx_t_8 = __pyx_t_7; + } else { + __pyx_t_8 = __pyx_t_6; + } + if (__pyx_t_8) { + + /* "View.MemoryView":919 + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< + * + * return 1 + */ + __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_46); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 919; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "View.MemoryView":921 + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + * return 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 1; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":938 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":939 + * + * def __dealloc__(self): + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":941 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":942 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":943 + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) # <<<<<<<<<<<<<< + * else: + * return memoryview.convert_item_to_object(self, itemp) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":945 + * return self.to_object_func(itemp) + * else: + * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_vtabptr_memoryview->convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 945; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":947 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":948 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":949 + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< + * else: + * memoryview.assign_item_from_object(self, itemp, value) + */ + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":951 + * self.to_dtype_func(itemp, value) + * else: + * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< + * + * property base: + */ + __pyx_t_3 = __pyx_vtabptr_memoryview->assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 951; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":955 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":956 + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): + * return self.from_object # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->from_object); + __pyx_r = __pyx_v_self->from_object; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":962 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_TypeInfo *__pyx_t_4; + Py_buffer __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_fromslice", 0); + + /* "View.MemoryView":971 + * cdef int i + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":972 + * + * if memviewslice.memview == Py_None: + * return None # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":977 + * + * + * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< + * + * result.from_slice = memviewslice + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":979 + * result = _memoryviewslice(None, 0, dtype_is_object) + * + * result.from_slice = memviewslice # <<<<<<<<<<<<<< + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + */ + __pyx_v_result->from_slice = __pyx_v_memviewslice; + + /* "View.MemoryView":980 + * + * result.from_slice = memviewslice + * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< + * + * result.from_object = ( memviewslice.memview).base + */ + __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); + + /* "View.MemoryView":982 + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< + * result.typeinfo = memviewslice.memview.typeinfo + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s__base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 982; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_result->from_object); + __Pyx_DECREF(__pyx_v_result->from_object); + __pyx_v_result->from_object = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":983 + * + * result.from_object = ( memviewslice.memview).base + * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< + * + * result.view = memviewslice.memview.view + */ + __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; + __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; + + /* "View.MemoryView":985 + * result.typeinfo = memviewslice.memview.typeinfo + * + * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + */ + __pyx_t_5 = __pyx_v_memviewslice.memview->view; + __pyx_v_result->__pyx_base.view = __pyx_t_5; + + /* "View.MemoryView":986 + * + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + */ + __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); + + /* "View.MemoryView":987 + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data + * result.view.ndim = ndim # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; + + /* "View.MemoryView":988 + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; + + /* "View.MemoryView":989 + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * result.flags = PyBUF_RECORDS + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":991 + * Py_INCREF(Py_None) + * + * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< + * + * result.view.shape = result.from_slice.shape + */ + __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; + + /* "View.MemoryView":993 + * result.flags = PyBUF_RECORDS + * + * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets + */ + __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); + + /* "View.MemoryView":994 + * + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * + */ + __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); + + /* "View.MemoryView":995 + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + * + * result.view.len = result.view.itemsize + */ + __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + + /* "View.MemoryView":997 + * result.view.suboffsets = result.from_slice.suboffsets + * + * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< + * for i in range(ndim): + * result.view.len *= result.view.shape[i] + */ + __pyx_t_6 = __pyx_v_result->__pyx_base.view.itemsize; + __pyx_v_result->__pyx_base.view.len = __pyx_t_6; + + /* "View.MemoryView":998 + * + * result.view.len = result.view.itemsize + * for i in range(ndim): # <<<<<<<<<<<<<< + * result.view.len *= result.view.shape[i] + * + */ + __pyx_t_7 = __pyx_v_ndim; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "View.MemoryView":999 + * result.view.len = result.view.itemsize + * for i in range(ndim): + * result.view.len *= result.view.shape[i] # <<<<<<<<<<<<<< + * + * result.to_object_func = to_object_func + */ + __pyx_v_result->__pyx_base.view.len = (__pyx_v_result->__pyx_base.view.len * (__pyx_v_result->__pyx_base.view.shape[__pyx_v_i])); + } + + /* "View.MemoryView":1001 + * result.view.len *= result.view.shape[i] + * + * result.to_object_func = to_object_func # <<<<<<<<<<<<<< + * result.to_dtype_func = to_dtype_func + * + */ + __pyx_v_result->to_object_func = __pyx_v_to_object_func; + + /* "View.MemoryView":1002 + * + * result.to_object_func = to_object_func + * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; + + /* "View.MemoryView":1004 + * result.to_dtype_func = to_dtype_func + * + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1007 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { + struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; + __Pyx_memviewslice *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_slice_from_memview", 0); + + /* "View.MemoryView":1010 + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1011 + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): + * obj = memview # <<<<<<<<<<<<<< + * return &obj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1011; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(((PyObject *)__pyx_v_memview)); + __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview); + + /* "View.MemoryView":1012 + * if isinstance(memview, _memoryviewslice): + * obj = memview + * return &obj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, mslice) + */ + __pyx_r = (&__pyx_v_obj->from_slice); + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1014 + * return &obj.from_slice + * else: + * slice_copy(memview, mslice) # <<<<<<<<<<<<<< + * return mslice + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); + + /* "View.MemoryView":1015 + * else: + * slice_copy(memview, mslice) + * return mslice # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_copy') + */ + __pyx_r = __pyx_v_mslice; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_obj); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1018 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef Py_ssize_t *shape, *strides, *suboffsets + */ + +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { + int __pyx_v_dim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + Py_ssize_t *__pyx_v_suboffsets; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + __Pyx_RefNannySetupContext("slice_copy", 0); + + /* "View.MemoryView":1022 + * cdef Py_ssize_t *shape, *strides, *suboffsets + * + * shape = memview.view.shape # <<<<<<<<<<<<<< + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets + */ + __pyx_t_1 = __pyx_v_memview->view.shape; + __pyx_v_shape = __pyx_t_1; + + /* "View.MemoryView":1023 + * + * shape = memview.view.shape + * strides = memview.view.strides # <<<<<<<<<<<<<< + * suboffsets = memview.view.suboffsets + * + */ + __pyx_t_1 = __pyx_v_memview->view.strides; + __pyx_v_strides = __pyx_t_1; + + /* "View.MemoryView":1024 + * shape = memview.view.shape + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< + * + * dst.memview = <__pyx_memoryview *> memview + */ + __pyx_t_1 = __pyx_v_memview->view.suboffsets; + __pyx_v_suboffsets = __pyx_t_1; + + /* "View.MemoryView":1026 + * suboffsets = memview.view.suboffsets + * + * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< + * dst.data = memview.view.buf + * + */ + __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); + + /* "View.MemoryView":1027 + * + * dst.memview = <__pyx_memoryview *> memview + * dst.data = memview.view.buf # <<<<<<<<<<<<<< + * + * for dim in range(memview.view.ndim): + */ + __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); + + /* "View.MemoryView":1029 + * dst.data = memview.view.buf + * + * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + */ + __pyx_t_2 = __pyx_v_memview->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_dim = __pyx_t_3; + + /* "View.MemoryView":1030 + * + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + */ + (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); + + /* "View.MemoryView":1031 + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 + */ + (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); + + /* "View.MemoryView":1032 + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: # <<<<<<<<<<<<<< + * dst.suboffsets[dim] = -1 + * else: + */ + __pyx_t_4 = ((__pyx_v_suboffsets == NULL) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":1033 + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[dim] = suboffsets[dim] + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = -1; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1035 + * dst.suboffsets[dim] = -1 + * else: + * dst.suboffsets[dim] = suboffsets[dim] # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object') + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = (__pyx_v_suboffsets[__pyx_v_dim]); + } + __pyx_L5:; + } + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1038 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { + __Pyx_memviewslice __pyx_v_memviewslice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy", 0); + + /* "View.MemoryView":1041 + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< + * return memoryview_copy_from_slice(memview, &memviewslice) + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); + + /* "View.MemoryView":1042 + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) + * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object_from_slice') + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1042; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1045 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { + PyObject *(*__pyx_v_to_object_func)(char *); + int (*__pyx_v_to_dtype_func)(char *, PyObject *); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *(*__pyx_t_3)(char *); + int (*__pyx_t_4)(char *, PyObject *); + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); + + /* "View.MemoryView":1052 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1053 + * + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + */ + __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; + __pyx_v_to_object_func = __pyx_t_3; + + /* "View.MemoryView":1054 + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< + * else: + * to_object_func = NULL + */ + __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; + __pyx_v_to_dtype_func = __pyx_t_4; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1056 + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + * to_object_func = NULL # <<<<<<<<<<<<<< + * to_dtype_func = NULL + * + */ + __pyx_v_to_object_func = NULL; + + /* "View.MemoryView":1057 + * else: + * to_object_func = NULL + * to_dtype_func = NULL # <<<<<<<<<<<<<< + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + */ + __pyx_v_to_dtype_func = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":1059 + * to_dtype_func = NULL + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< + * to_object_func, to_dtype_func, + * memview.dtype_is_object) + */ + __Pyx_XDECREF(__pyx_r); + + /* "View.MemoryView":1061 + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + * to_object_func, to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1067 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + +static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { + Py_ssize_t __pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":1068 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + __pyx_t_1 = ((__pyx_v_arg < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1069 + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: + * return -arg # <<<<<<<<<<<<<< + * else: + * return arg + */ + __pyx_r = (-__pyx_v_arg); + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1071 + * return -arg + * else: + * return arg # <<<<<<<<<<<<<< + * + * @cname('__pyx_get_best_slice_order') + */ + __pyx_r = __pyx_v_arg; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1074 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + +static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_c_stride; + Py_ssize_t __pyx_v_f_stride; + char __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1079 + * """ + * cdef int i + * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t f_stride = 0 + * + */ + __pyx_v_c_stride = 0; + + /* "View.MemoryView":1080 + * cdef int i + * cdef Py_ssize_t c_stride = 0 + * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_f_stride = 0; + + /* "View.MemoryView":1082 + * cdef Py_ssize_t f_stride = 0 + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1083 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1084 + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1085 + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + goto __pyx_L4_break; + goto __pyx_L5; + } + __pyx_L5:; + } + __pyx_L4_break:; + + /* "View.MemoryView":1087 + * break + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1088 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1089 + * for i in range(ndim): + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1090 + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + */ + goto __pyx_L7_break; + goto __pyx_L8; + } + __pyx_L8:; + } + __pyx_L7_break:; + + /* "View.MemoryView":1092 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1093 + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + * return 'C' # <<<<<<<<<<<<<< + * else: + * return 'F' + */ + __pyx_r = 'C'; + goto __pyx_L0; + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1095 + * return 'C' + * else: + * return 'F' # <<<<<<<<<<<<<< + * + * @cython.cdivision(True) + */ + __pyx_r = 'F'; + goto __pyx_L0; + } + __pyx_L9:; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1098 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + +static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; + Py_ssize_t __pyx_v_dst_extent; + Py_ssize_t __pyx_v_src_stride; + Py_ssize_t __pyx_v_dst_stride; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + + /* "View.MemoryView":1105 + * + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + */ + __pyx_v_src_extent = (__pyx_v_src_shape[0]); + + /* "View.MemoryView":1106 + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] + */ + __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); + + /* "View.MemoryView":1107 + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + */ + __pyx_v_src_stride = (__pyx_v_src_strides[0]); + + /* "View.MemoryView":1108 + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); + + /* "View.MemoryView":1110 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1111 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + __pyx_t_1 = ((__pyx_v_src_stride > 0) != 0); + if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1112 + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + */ + __pyx_t_3 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); + if (__pyx_t_3) { + __pyx_t_3 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); + } + __pyx_t_4 = (__pyx_t_3 != 0); + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = __pyx_t_1; + } + if (__pyx_t_2) { + + /* "View.MemoryView":1113 + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":1115 + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1116 + * else: + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); + + /* "View.MemoryView":1117 + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * else: + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1118 + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1120 + * dst_data += dst_stride + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * _copy_strided_to_strided(src_data, src_strides + 1, + * dst_data, dst_strides + 1, + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1124 + * dst_data, dst_strides + 1, + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); + + /* "View.MemoryView":1125 + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1126 + * ndim - 1, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L3:; + +} + +/* "View.MemoryView":1128 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + +static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + + /* "View.MemoryView":1132 + * int ndim, size_t itemsize) nogil: + * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, + * src.shape, dst.shape, ndim, itemsize) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_get_size') + */ + _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); + +} + +/* "View.MemoryView":1135 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_size; + Py_ssize_t __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1138 + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_size = __pyx_t_1; + + /* "View.MemoryView":1140 + * cdef Py_ssize_t size = src.memview.view.itemsize + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * size *= src.shape[i] + * + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1141 + * + * for i in range(ndim): + * size *= src.shape[i] # <<<<<<<<<<<<<< + * + * return size + */ + __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); + } + + /* "View.MemoryView":1143 + * size *= src.shape[i] + * + * return size # <<<<<<<<<<<<<< + * + * @cname('__pyx_fill_contig_strides_array') + */ + __pyx_r = __pyx_v_size; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1146 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { + int __pyx_v_idx; + Py_ssize_t __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1155 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + __pyx_t_1 = ((__pyx_v_order == 'F') != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1156 + * + * if order == 'F': + * for idx in range(ndim): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_idx = __pyx_t_3; + + /* "View.MemoryView":1157 + * if order == 'F': + * for idx in range(ndim): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * else: + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1158 + * for idx in range(ndim): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * else: + * for idx in range(ndim - 1, -1, -1): + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1160 + * stride = stride * shape[idx] + * else: + * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { + __pyx_v_idx = __pyx_t_2; + + /* "View.MemoryView":1161 + * else: + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1162 + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * + * return stride + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + } + __pyx_L3:; + + /* "View.MemoryView":1164 + * stride = stride * shape[idx] + * + * return stride # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_data_to_temp') + */ + __pyx_r = __pyx_v_stride; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1167 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { + int __pyx_v_i; + void *__pyx_v_result; + size_t __pyx_v_itemsize; + size_t __pyx_v_size; + void *__pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + struct __pyx_memoryview_obj *__pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1178 + * cdef void *result + * + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef size_t size = slice_get_size(src, ndim) + * + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1179 + * + * cdef size_t itemsize = src.memview.view.itemsize + * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< + * + * result = malloc(size) + */ + __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); + + /* "View.MemoryView":1181 + * cdef size_t size = slice_get_size(src, ndim) + * + * result = malloc(size) # <<<<<<<<<<<<<< + * if not result: + * _err(MemoryError, NULL) + */ + __pyx_v_result = malloc(__pyx_v_size); + + /* "View.MemoryView":1182 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1183 + * result = malloc(size) + * if not result: + * _err(MemoryError, NULL) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1186 + * + * + * tmpslice.data = result # <<<<<<<<<<<<<< + * tmpslice.memview = src.memview + * for i in range(ndim): + */ + __pyx_v_tmpslice->data = ((char *)__pyx_v_result); + + /* "View.MemoryView":1187 + * + * tmpslice.data = result + * tmpslice.memview = src.memview # <<<<<<<<<<<<<< + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + */ + __pyx_t_4 = __pyx_v_src->memview; + __pyx_v_tmpslice->memview = __pyx_t_4; + + /* "View.MemoryView":1188 + * tmpslice.data = result + * tmpslice.memview = src.memview + * for i in range(ndim): # <<<<<<<<<<<<<< + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1189 + * tmpslice.memview = src.memview + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< + * tmpslice.suboffsets[i] = -1 + * + */ + (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); + + /* "View.MemoryView":1190 + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + */ + (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1193 + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + * ndim, order) # <<<<<<<<<<<<<< + * + * + */ + __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); + + /* "View.MemoryView":1196 + * + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1197 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1198 + * for i in range(ndim): + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< + * + * if slice_is_contig(src, order, ndim): + */ + (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1200 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1201 + * + * if slice_is_contig(src, order, ndim): + * memcpy(result, src.data, size) # <<<<<<<<<<<<<< + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + */ + memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1203 + * memcpy(result, src.data, size) + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< + * + * return result + */ + copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); + } + __pyx_L9:; + + /* "View.MemoryView":1205 + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = NULL; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1210 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + +static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_extents", 0); + + /* "View.MemoryView":1213 + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + * (i, extent1, extent2)) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err_dim') + */ + __pyx_t_1 = PyInt_FromLong(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_47), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1216 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + +static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_dim", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1217 + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: + * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err') + */ + __pyx_t_1 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_2 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_t_1), __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_v_error, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1220 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + +static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1221 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ + __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1222 + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: + * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< + * else: + * raise error + */ + __pyx_t_2 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_2)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_v_error, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1224 + * raise error(msg.decode('ascii')) + * else: + * raise error # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_contents') + */ + __Pyx_Raise(__pyx_v_error, 0, 0, 0); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1227 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { + void *__pyx_v_tmpdata; + size_t __pyx_v_itemsize; + int __pyx_v_i; + char __pyx_v_order; + int __pyx_v_broadcasting; + int __pyx_v_direct_copy; + __Pyx_memviewslice __pyx_v_tmp; + int __pyx_v_ndim; + int __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + void *__pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1235 + * Check for overlapping memory and verify the shapes. + * """ + * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + */ + __pyx_v_tmpdata = NULL; + + /* "View.MemoryView":1236 + * """ + * cdef void *tmpdata = NULL + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + */ + __pyx_t_1 = __pyx_v_src.memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1238 + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< + * cdef bint broadcasting = False + * cdef bint direct_copy = False + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); + + /* "View.MemoryView":1239 + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False # <<<<<<<<<<<<<< + * cdef bint direct_copy = False + * cdef __Pyx_memviewslice tmp + */ + __pyx_v_broadcasting = 0; + + /* "View.MemoryView":1240 + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False + * cdef bint direct_copy = False # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice tmp + * + */ + __pyx_v_direct_copy = 0; + + /* "View.MemoryView":1243 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ + __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1244 + * + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); + goto __pyx_L3; + } + + /* "View.MemoryView":1245 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ + __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1246 + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< + * + * cdef int ndim = max(src_ndim, dst_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1248 + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_3 = __pyx_v_dst_ndim; + __pyx_t_4 = __pyx_v_src_ndim; + if (((__pyx_t_3 > __pyx_t_4) != 0)) { + __pyx_t_5 = __pyx_t_3; + } else { + __pyx_t_5 = __pyx_t_4; + } + __pyx_v_ndim = __pyx_t_5; + + /* "View.MemoryView":1250 + * cdef int ndim = max(src_ndim, dst_ndim) + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1251 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1252 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1253 + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + * broadcasting = True # <<<<<<<<<<<<<< + * src.strides[i] = 0 + * else: + */ + __pyx_v_broadcasting = 1; + + /* "View.MemoryView":1254 + * if src.shape[i] == 1: + * broadcasting = True + * src.strides[i] = 0 # <<<<<<<<<<<<<< + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) + */ + (__pyx_v_src.strides[__pyx_v_i]) = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":1256 + * src.strides[i] = 0 + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< + * + * if src.suboffsets[i] >= 0: + */ + __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":1258 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ + __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1259 + * + * if src.suboffsets[i] >= 0: + * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< + * + * if slices_overlap(&src, &dst, ndim, itemsize): + */ + __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_48, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1259; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1261 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(&src, order, ndim): + */ + __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1263 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1264 + * + * if not slice_is_contig(&src, order, ndim): + * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":1266 + * order = get_best_order(&dst, ndim) + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< + * src = tmp + * + */ + __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_tmpdata = __pyx_t_6; + + /* "View.MemoryView":1267 + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + * src = tmp # <<<<<<<<<<<<<< + * + * if not broadcasting: + */ + __pyx_v_src = __pyx_v_tmp; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":1269 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1272 + * + * + * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1273 + * + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); + goto __pyx_L12; + } + + /* "View.MemoryView":1274 + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1275 + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< + * + * if direct_copy: + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":1277 + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_2 = (__pyx_v_direct_copy != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1279 + * if direct_copy: + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1280 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * return 0 + */ + memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); + + /* "View.MemoryView":1281 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1282 + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + * return 0 # <<<<<<<<<<<<<< + * + * if order == 'F' == get_best_order(&dst, ndim): + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":1284 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = (__pyx_v_order == 'F'); + if (__pyx_t_2) { + __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); + } + __pyx_t_7 = (__pyx_t_2 != 0); + if (__pyx_t_7) { + + /* "View.MemoryView":1287 + * + * + * transpose_memslice(&src) # <<<<<<<<<<<<<< + * transpose_memslice(&dst) + * + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1288 + * + * transpose_memslice(&src) + * transpose_memslice(&dst) # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":1290 + * transpose_memslice(&dst) + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1291 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + */ + copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1292 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * free(tmpdata) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1294 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1295 + * + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_broadcast_leading') + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1298 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice, int __pyx_v_ndim, int __pyx_v_ndim_other) { + int __pyx_v_i; + int __pyx_v_offset; + int __pyx_t_1; + int __pyx_t_2; + + /* "View.MemoryView":1302 + * int ndim_other) nogil: + * cdef int i + * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); + + /* "View.MemoryView":1304 + * cdef int offset = ndim_other - ndim + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1305 + * + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] # <<<<<<<<<<<<<< + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] + */ + (__pyx_v_slice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->shape[__pyx_v_i]); + + /* "View.MemoryView":1306 + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] # <<<<<<<<<<<<<< + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + */ + (__pyx_v_slice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->strides[__pyx_v_i]); + + /* "View.MemoryView":1307 + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] # <<<<<<<<<<<<<< + * + * for i in range(offset): + */ + (__pyx_v_slice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->suboffsets[__pyx_v_i]); + } + + /* "View.MemoryView":1309 + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + * for i in range(offset): # <<<<<<<<<<<<<< + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + */ + __pyx_t_1 = __pyx_v_offset; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1310 + * + * for i in range(offset): + * slice.shape[i] = 1 # <<<<<<<<<<<<<< + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 + */ + (__pyx_v_slice->shape[__pyx_v_i]) = 1; + + /* "View.MemoryView":1311 + * for i in range(offset): + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] # <<<<<<<<<<<<<< + * slice.suboffsets[i] = -1 + * + */ + (__pyx_v_slice->strides[__pyx_v_i]) = (__pyx_v_slice->strides[0]); + + /* "View.MemoryView":1312 + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_slice->suboffsets[__pyx_v_i]) = -1; + } + +} + +/* "View.MemoryView":1320 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { + int __pyx_t_1; + + /* "View.MemoryView":1324 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + __pyx_t_1 = (__pyx_v_dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1326 + * if dtype_is_object: + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + */ + __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); + goto __pyx_L3; + } + __pyx_L3:; + +} + +/* "View.MemoryView":1329 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + __Pyx_RefNannyDeclarations + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); + + /* "View.MemoryView":1332 + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); + + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif +} + +/* "View.MemoryView":1335 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + +static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); + + /* "View.MemoryView":1339 + * cdef Py_ssize_t i + * + * for i in range(shape[0]): # <<<<<<<<<<<<<< + * if ndim == 1: + * if inc: + */ + __pyx_t_1 = (__pyx_v_shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1340 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1341 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + __pyx_t_3 = (__pyx_v_inc != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1342 + * if ndim == 1: + * if inc: + * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * Py_DECREF(( data)[0]) + */ + Py_INCREF((((PyObject **)__pyx_v_data)[0])); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":1344 + * Py_INCREF(( data)[0]) + * else: + * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + */ + Py_DECREF((((PyObject **)__pyx_v_data)[0])); + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1347 + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + * ndim - 1, inc) # <<<<<<<<<<<<<< + * + * data += strides[0] + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); + } + __pyx_L5:; + + /* "View.MemoryView":1349 + * ndim - 1, inc) + * + * data += strides[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); + } + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1355 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { + + /* "View.MemoryView":1358 + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1360 + * refcount_copying(dst, dtype_is_object, ndim, False) + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) # <<<<<<<<<<<<<< + * refcount_copying(dst, dtype_is_object, ndim, True) + * + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1361 + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + +} + +/* "View.MemoryView":1365 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + +static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_extent; + int __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + + /* "View.MemoryView":1369 + * size_t itemsize, void *item) nogil: + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t extent = shape[0] + * + */ + __pyx_v_stride = (__pyx_v_strides[0]); + + /* "View.MemoryView":1370 + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] + * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_extent = (__pyx_v_shape[0]); + + /* "View.MemoryView":1372 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1373 + * + * if ndim == 1: + * for i in range(extent): # <<<<<<<<<<<<<< + * memcpy(data, item, itemsize) + * data += stride + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1374 + * if ndim == 1: + * for i in range(extent): + * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< + * data += stride + * else: + */ + memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); + + /* "View.MemoryView":1375 + * for i in range(extent): + * memcpy(data, item, itemsize) + * data += stride # <<<<<<<<<<<<<< + * else: + * for i in range(extent): + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1377 + * data += stride + * else: + * for i in range(extent): # <<<<<<<<<<<<<< + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1379 + * for i in range(extent): + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) # <<<<<<<<<<<<<< + * data += stride + * + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1380 + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + * data += stride # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + } + __pyx_L3:; + +} +static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; + +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryview_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryview_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_memoryview; + p->obj = Py_None; Py_INCREF(Py_None); + p->_size = Py_None; Py_INCREF(Py_None); + p->_array_interface = Py_None; Py_INCREF(Py_None); + p->view.obj = NULL; + if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryview___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->obj); + Py_CLEAR(p->_size); + Py_CLEAR(p->_array_interface); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + if (p->obj) { + e = (*v)(p->obj, a); if (e) return e; + } + if (p->_size) { + e = (*v)(p->_size, a); if (e) return e; + } + if (p->_array_interface) { + e = (*v)(p->_array_interface, a); if (e) return e; + } + if (p->view.obj) { + e = (*v)(p->view.obj, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->obj); + p->obj = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_size); + p->_size = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_array_interface); + p->_array_interface = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + Py_CLEAR(p->view.obj); + return 0; +} +static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_memoryview___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_transpose(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview__get__base(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_shape(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_strides(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_suboffsets(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_ndim(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_itemsize(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_nbytes(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_size(o); +} + +static PyMethodDef __pyx_methods_memoryview[] = { + {__Pyx_NAMESTR("is_c_contig"), (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("is_f_contig"), (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy"), (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy_fortran"), (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_memoryview[] = { + {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, + {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, + {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, + {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, + {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, + {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, + {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, + {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_memoryview = { + __pyx_memoryview___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_memoryview, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_memoryview = { + __pyx_memoryview___len__, /*mp_length*/ + __pyx_memoryview___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_memoryview = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_memoryview_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_memoryview = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn._hmmc.memoryview"), /*tp_name*/ + sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_memoryview___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_memoryview___str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_memoryview, /*tp_traverse*/ + __pyx_tp_clear_memoryview, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_memoryview, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_memoryview, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_memoryview, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_MemviewEnum_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_MemviewEnum_obj *)o); + p->name = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + PyObject_GC_UnTrack(o); + Py_CLEAR(p->name); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + if (p->name) { + e = (*v)(p->name, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->name); + p->name = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_Enum[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_MemviewEnum = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn._hmmc.Enum"), /*tp_name*/ + sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_Enum, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_MemviewEnum___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_Enum, /*tp_traverse*/ + __pyx_tp_clear_Enum, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_Enum, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_MemviewEnum___init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_Enum, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; + +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryviewslice_obj *p; + PyObject *o = __pyx_tp_new_memoryview(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryviewslice_obj *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; + p->from_object = Py_None; Py_INCREF(Py_None); + p->from_slice.memview = NULL; + return o; +} + +static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryviewslice___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->from_object); + PyObject_GC_Track(o); + __pyx_tp_dealloc_memoryview(o); +} + +static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; + if (p->from_object) { + e = (*v)(p->from_object, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + PyObject* tmp; + __pyx_tp_clear_memoryview(o); + tmp = ((PyObject*)p->from_object); + p->from_object = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + __PYX_XDEC_MEMVIEW(&p->from_slice, 1); + return 0; +} + +static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryviewslice__get__base(o); +} + +static PyMethodDef __pyx_methods__memoryviewslice[] = { + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { + {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_memoryviewslice = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn._hmmc._memoryviewslice"), /*tp_name*/ + sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___repr__, /*tp_repr*/ + #else + 0, /*tp_repr*/ + #endif + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___str__, /*tp_str*/ + #else + 0, /*tp_str*/ + #endif + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Internal class for passing memoryview slices to Python"), /*tp_doc*/ + __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ + __pyx_tp_clear__memoryviewslice, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods__memoryviewslice, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets__memoryviewslice, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new__memoryviewslice, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_array_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_array_obj *)o); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_array___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->mode); + Py_CLEAR(p->_format); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_array(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + if (p->mode) { + e = (*v)(p->mode, a); if (e) return e; + } + if (p->_format) { + e = (*v)(p->_format, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->mode); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_format); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} +static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_array___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { + PyObject *v = PyObject_GenericGetAttr(o, n); + if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + v = __pyx_array___getattr__(o, n); + } + return v; +} + +static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { + return get_memview(o); +} + +static PyMethodDef __pyx_methods_array[] = { + {__Pyx_NAMESTR("__getattr__"), (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_array[] = { + {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_array = { + 0, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_array, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_array = { + 0, /*mp_length*/ + __pyx_array___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_array = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_array_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_array = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn._hmmc.array"), /*tp_name*/ + sizeof(struct __pyx_array_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_array, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + __pyx_tp_getattro_array, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_array, /*tp_traverse*/ + __pyx_tp_clear_array, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_array, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_array, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_array, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {__Pyx_NAMESTR("_logsum"), (PyCFunction)__pyx_pw_7sklearn_5_hmmc_1_logsum, METH_O, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + __Pyx_NAMESTR("_hmmc"), 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, @@ -4943,52 +16502,129 @@ static struct PyModuleDef __pyx_moduledef = { static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_u_10, __pyx_k_10, sizeof(__pyx_k_10), 0, 1, 0, 0}, - {&__pyx_kp_u_12, __pyx_k_12, sizeof(__pyx_k_12), 0, 1, 0, 0}, - {&__pyx_kp_u_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 1, 0, 0}, - {&__pyx_kp_u_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 1, 0, 0}, - {&__pyx_n_s_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 0, 1, 1}, + {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, + {&__pyx_kp_u_14, __pyx_k_14, sizeof(__pyx_k_14), 0, 1, 0, 0}, + {&__pyx_kp_s_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 1, 0}, + {&__pyx_kp_s_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 0, 1, 0}, + {&__pyx_kp_s_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 1, 0}, + {&__pyx_kp_s_23, __pyx_k_23, sizeof(__pyx_k_23), 0, 0, 1, 0}, + {&__pyx_kp_s_24, __pyx_k_24, sizeof(__pyx_k_24), 0, 0, 1, 0}, + {&__pyx_kp_s_26, __pyx_k_26, sizeof(__pyx_k_26), 0, 0, 1, 0}, + {&__pyx_kp_s_28, __pyx_k_28, sizeof(__pyx_k_28), 0, 0, 1, 0}, + {&__pyx_kp_s_30, __pyx_k_30, sizeof(__pyx_k_30), 0, 0, 1, 0}, + {&__pyx_kp_s_32, __pyx_k_32, sizeof(__pyx_k_32), 0, 0, 1, 0}, + {&__pyx_kp_s_34, __pyx_k_34, sizeof(__pyx_k_34), 0, 0, 1, 0}, + {&__pyx_kp_s_35, __pyx_k_35, sizeof(__pyx_k_35), 0, 0, 1, 0}, + {&__pyx_kp_s_38, __pyx_k_38, sizeof(__pyx_k_38), 0, 0, 1, 0}, + {&__pyx_kp_u_4, __pyx_k_4, sizeof(__pyx_k_4), 0, 1, 0, 0}, + {&__pyx_kp_s_40, __pyx_k_40, sizeof(__pyx_k_40), 0, 0, 1, 0}, + {&__pyx_kp_s_45, __pyx_k_45, sizeof(__pyx_k_45), 0, 0, 1, 0}, + {&__pyx_kp_s_47, __pyx_k_47, sizeof(__pyx_k_47), 0, 0, 1, 0}, + {&__pyx_kp_s_51, __pyx_k_51, sizeof(__pyx_k_51), 0, 0, 1, 0}, + {&__pyx_n_s_52, __pyx_k_52, sizeof(__pyx_k_52), 0, 0, 1, 1}, {&__pyx_kp_u_6, __pyx_k_6, sizeof(__pyx_k_6), 0, 1, 0, 0}, + {&__pyx_kp_s_60, __pyx_k_60, sizeof(__pyx_k_60), 0, 0, 1, 0}, + {&__pyx_kp_s_62, __pyx_k_62, sizeof(__pyx_k_62), 0, 0, 1, 0}, + {&__pyx_kp_s_64, __pyx_k_64, sizeof(__pyx_k_64), 0, 0, 1, 0}, + {&__pyx_kp_s_66, __pyx_k_66, sizeof(__pyx_k_66), 0, 0, 1, 0}, + {&__pyx_kp_s_68, __pyx_k_68, sizeof(__pyx_k_68), 0, 0, 1, 0}, {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, - {&__pyx_n_s__N, __pyx_k__N, sizeof(__pyx_k__N), 0, 0, 1, 1}, + {&__pyx_n_s__ASCII, __pyx_k__ASCII, sizeof(__pyx_k__ASCII), 0, 0, 1, 1}, + {&__pyx_n_s__Ellipsis, __pyx_k__Ellipsis, sizeof(__pyx_k__Ellipsis), 0, 0, 1, 1}, + {&__pyx_n_s__IndexError, __pyx_k__IndexError, sizeof(__pyx_k__IndexError), 0, 0, 1, 1}, + {&__pyx_n_s__MemoryError, __pyx_k__MemoryError, sizeof(__pyx_k__MemoryError), 0, 0, 1, 1}, + {&__pyx_n_b__O, __pyx_k__O, sizeof(__pyx_k__O), 0, 0, 0, 1}, {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s__T, __pyx_k__T, sizeof(__pyx_k__T), 0, 0, 1, 1}, + {&__pyx_n_s__TypeError, __pyx_k__TypeError, sizeof(__pyx_k__TypeError), 0, 0, 1, 1}, {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, + {&__pyx_n_s____class__, __pyx_k____class__, sizeof(__pyx_k____class__), 0, 0, 1, 1}, + {&__pyx_n_s____import__, __pyx_k____import__, sizeof(__pyx_k____import__), 0, 0, 1, 1}, {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, + {&__pyx_n_s____name__, __pyx_k____name__, sizeof(__pyx_k____name__), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_getbuffer, __pyx_k____pyx_getbuffer, sizeof(__pyx_k____pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_releasebuffer, __pyx_k____pyx_releasebuffer, sizeof(__pyx_k____pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_vtable__, __pyx_k____pyx_vtable__, sizeof(__pyx_k____pyx_vtable__), 0, 0, 1, 1}, {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, {&__pyx_n_s___backward, __pyx_k___backward, sizeof(__pyx_k___backward), 0, 0, 1, 1}, {&__pyx_n_s___compute_lneta, __pyx_k___compute_lneta, sizeof(__pyx_k___compute_lneta), 0, 0, 1, 1}, {&__pyx_n_s___forward, __pyx_k___forward, sizeof(__pyx_k___forward), 0, 0, 1, 1}, - {&__pyx_n_s___logsum, __pyx_k___logsum, sizeof(__pyx_k___logsum), 0, 0, 1, 1}, {&__pyx_n_s___viterbi, __pyx_k___viterbi, sizeof(__pyx_k___viterbi), 0, 0, 1, 1}, + {&__pyx_n_s__allocate_buffer, __pyx_k__allocate_buffer, sizeof(__pyx_k__allocate_buffer), 0, 0, 1, 1}, {&__pyx_n_s__argmax, __pyx_k__argmax, sizeof(__pyx_k__argmax), 0, 0, 1, 1}, + {&__pyx_n_s__axis, __pyx_k__axis, sizeof(__pyx_k__axis), 0, 0, 1, 1}, + {&__pyx_n_s__base, __pyx_k__base, sizeof(__pyx_k__base), 0, 0, 1, 1}, {&__pyx_n_s__bwdlattice, __pyx_k__bwdlattice, sizeof(__pyx_k__bwdlattice), 0, 0, 1, 1}, + {&__pyx_n_b__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 0, 0, 1}, + {&__pyx_n_s__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 0, 1, 1}, + {&__pyx_n_u__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 1, 0, 1}, + {&__pyx_n_s__decode, __pyx_k__decode, sizeof(__pyx_k__decode), 0, 0, 1, 1}, {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, + {&__pyx_n_s__dtype_is_object, __pyx_k__dtype_is_object, sizeof(__pyx_k__dtype_is_object), 0, 0, 1, 1}, + {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, + {&__pyx_n_s__encode, __pyx_k__encode, sizeof(__pyx_k__encode), 0, 0, 1, 1}, + {&__pyx_n_s__enumerate, __pyx_k__enumerate, sizeof(__pyx_k__enumerate), 0, 0, 1, 1}, + {&__pyx_n_s__error, __pyx_k__error, sizeof(__pyx_k__error), 0, 0, 1, 1}, + {&__pyx_n_s__extend, __pyx_k__extend, sizeof(__pyx_k__extend), 0, 0, 1, 1}, + {&__pyx_n_s__flags, __pyx_k__flags, sizeof(__pyx_k__flags), 0, 0, 1, 1}, + {&__pyx_n_s__format, __pyx_k__format, sizeof(__pyx_k__format), 0, 0, 1, 1}, + {&__pyx_n_b__fortran, __pyx_k__fortran, sizeof(__pyx_k__fortran), 0, 0, 0, 1}, + {&__pyx_n_s__fortran, __pyx_k__fortran, sizeof(__pyx_k__fortran), 0, 0, 1, 1}, {&__pyx_n_s__framelogprob, __pyx_k__framelogprob, sizeof(__pyx_k__framelogprob), 0, 0, 1, 1}, {&__pyx_n_s__fwdlattice, __pyx_k__fwdlattice, sizeof(__pyx_k__fwdlattice), 0, 0, 1, 1}, + {&__pyx_n_s__i, __pyx_k__i, sizeof(__pyx_k__i), 0, 0, 1, 1}, + {&__pyx_n_s__id, __pyx_k__id, sizeof(__pyx_k__id), 0, 0, 1, 1}, + {&__pyx_n_s__inf, __pyx_k__inf, sizeof(__pyx_k__inf), 0, 0, 1, 1}, {&__pyx_n_s__int, __pyx_k__int, sizeof(__pyx_k__int), 0, 0, 1, 1}, + {&__pyx_n_s__itemsize, __pyx_k__itemsize, sizeof(__pyx_k__itemsize), 0, 0, 1, 1}, + {&__pyx_n_s__j, __pyx_k__j, sizeof(__pyx_k__j), 0, 0, 1, 1}, {&__pyx_n_s__lneta, __pyx_k__lneta, sizeof(__pyx_k__lneta), 0, 0, 1, 1}, {&__pyx_n_s__log_startprob, __pyx_k__log_startprob, sizeof(__pyx_k__log_startprob), 0, 0, 1, 1}, {&__pyx_n_s__log_transmat, __pyx_k__log_transmat, sizeof(__pyx_k__log_transmat), 0, 0, 1, 1}, {&__pyx_n_s__logprob, __pyx_k__logprob, sizeof(__pyx_k__logprob), 0, 0, 1, 1}, {&__pyx_n_s__max, __pyx_k__max, sizeof(__pyx_k__max), 0, 0, 1, 1}, + {&__pyx_n_s__max_pos, __pyx_k__max_pos, sizeof(__pyx_k__max_pos), 0, 0, 1, 1}, + {&__pyx_n_s__memview, __pyx_k__memview, sizeof(__pyx_k__memview), 0, 0, 1, 1}, + {&__pyx_n_s__mode, __pyx_k__mode, sizeof(__pyx_k__mode), 0, 0, 1, 1}, {&__pyx_n_s__n_components, __pyx_k__n_components, sizeof(__pyx_k__n_components), 0, 0, 1, 1}, {&__pyx_n_s__n_observations, __pyx_k__n_observations, sizeof(__pyx_k__n_observations), 0, 0, 1, 1}, + {&__pyx_n_s__name, __pyx_k__name, sizeof(__pyx_k__name), 0, 0, 1, 1}, + {&__pyx_n_s__ndim, __pyx_k__ndim, sizeof(__pyx_k__ndim), 0, 0, 1, 1}, {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, + {&__pyx_n_s__obj, __pyx_k__obj, sizeof(__pyx_k__obj), 0, 0, 1, 1}, + {&__pyx_n_s__pack, __pyx_k__pack, sizeof(__pyx_k__pack), 0, 0, 1, 1}, {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, + {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, + {&__pyx_n_s__size, __pyx_k__size, sizeof(__pyx_k__size), 0, 0, 1, 1}, + {&__pyx_n_s__start, __pyx_k__start, sizeof(__pyx_k__start), 0, 0, 1, 1}, + {&__pyx_n_s__state_sequence, __pyx_k__state_sequence, sizeof(__pyx_k__state_sequence), 0, 0, 1, 1}, + {&__pyx_n_s__step, __pyx_k__step, sizeof(__pyx_k__step), 0, 0, 1, 1}, + {&__pyx_n_s__stop, __pyx_k__stop, sizeof(__pyx_k__stop), 0, 0, 1, 1}, + {&__pyx_n_s__struct, __pyx_k__struct, sizeof(__pyx_k__struct), 0, 0, 1, 1}, + {&__pyx_n_s__t, __pyx_k__t, sizeof(__pyx_k__t), 0, 0, 1, 1}, + {&__pyx_n_s__unpack, __pyx_k__unpack, sizeof(__pyx_k__unpack), 0, 0, 1, 1}, + {&__pyx_n_s__viterbi_lattice, __pyx_k__viterbi_lattice, sizeof(__pyx_k__viterbi_lattice), 0, 0, 1, 1}, + {&__pyx_n_s__work_buffer, __pyx_k__work_buffer, sizeof(__pyx_k__work_buffer), 0, 0, 1, 1}, {&__pyx_n_s__xrange, __pyx_k__xrange, sizeof(__pyx_k__xrange), 0, 0, 1, 1}, {&__pyx_n_s__zeros, __pyx_k__zeros, sizeof(__pyx_k__zeros), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s__MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s__enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s__Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s__TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if PY_MAJOR_VERSION >= 3 - __pyx_builtin_xrange = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else - __pyx_builtin_xrange = __Pyx_GetName(__pyx_b, __pyx_n_s__xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s__id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s__IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -4996,138 +16632,352 @@ static int __Pyx_InitCachedBuiltins(void) { static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); - - /* "sklearn/_hmmc.pyx":110 - * for t in xrange(1, n_observations): - * for j in xrange(n_components): - * work_buffer[:] = viterbi_lattice[t - 1, :] + log_transmat[:, j] # <<<<<<<<<<<<<< - * viterbi_lattice[t, j] = np.max(work_buffer[:]) + framelogprob[t, j] - * - */ - __pyx_k_slice_1 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_k_slice_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_slice_1); - __Pyx_GIVEREF(__pyx_k_slice_1); - __pyx_k_slice_2 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_k_slice_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_slice_2); - __Pyx_GIVEREF(__pyx_k_slice_2); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "sklearn/_hmmc.pyx":114 + /* "sklearn/_hmmc.pyx":119 * - * # observation traceback + * # Observation traceback * max_pos = np.argmax(viterbi_lattice[n_observations - 1, :]) # <<<<<<<<<<<<<< * state_sequence[n_observations - 1] = max_pos * logprob = viterbi_lattice[n_observations - 1, max_pos] */ - __pyx_k_slice_3 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_k_slice_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_slice_3); - __Pyx_GIVEREF(__pyx_k_slice_3); + __pyx_k_slice_1 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_k_slice_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_slice_1); + __Pyx_GIVEREF(__pyx_k_slice_1); - /* "sklearn/_hmmc.pyx":119 + /* "sklearn/_hmmc.pyx":124 * - * for t in xrange(n_observations - 2, -1, -1): + * for t in range(n_observations - 2, -1, -1): * max_pos = np.argmax(viterbi_lattice[t, :] \ # <<<<<<<<<<<<<< * + log_transmat[:, state_sequence[t + 1]]) * state_sequence[t] = max_pos */ - __pyx_k_slice_4 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_k_slice_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_slice_4); - __Pyx_GIVEREF(__pyx_k_slice_4); + __pyx_k_slice_2 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_k_slice_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_slice_2); + __Pyx_GIVEREF(__pyx_k_slice_2); - /* "sklearn/_hmmc.pyx":120 - * for t in xrange(n_observations - 2, -1, -1): + /* "sklearn/_hmmc.pyx":125 + * for t in range(n_observations - 2, -1, -1): * max_pos = np.argmax(viterbi_lattice[t, :] \ * + log_transmat[:, state_sequence[t + 1]]) # <<<<<<<<<<<<<< * state_sequence[t] = max_pos * */ - __pyx_k_slice_5 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_k_slice_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_slice_5); - __Pyx_GIVEREF(__pyx_k_slice_5); + __pyx_k_slice_3 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_k_slice_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_slice_3); + __Pyx_GIVEREF(__pyx_k_slice_3); - /* "numpy.pxd":211 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_7 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_7)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_6)); - PyTuple_SET_ITEM(__pyx_k_tuple_7, 0, ((PyObject *)__pyx_kp_u_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); + __pyx_k_tuple_5 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_4)); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_5); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); - /* "numpy.pxd":215 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_9)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); + __pyx_k_tuple_7 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_6)); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_7); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_11 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_11)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_10)); - PyTuple_SET_ITEM(__pyx_k_tuple_11, 0, ((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); + __pyx_k_tuple_9 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_8)); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_9); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); - /* "numpy.pxd":795 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_14 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_14)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_13)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, ((PyObject *)__pyx_kp_u_13)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_13)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + __pyx_k_tuple_12 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_11)); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_12); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_15 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_15)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_10)); - PyTuple_SET_ITEM(__pyx_k_tuple_15, 0, ((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); + __pyx_k_tuple_13 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_8)); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_13); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); - /* "numpy.pxd":819 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * - * # Until ticket #99 is fixed, use integers to avoid warnings + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_k_tuple_15 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_14)); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_15); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); + + /* "View.MemoryView":124 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if self.itemsize <= 0: + */ + __pyx_k_tuple_17 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_16)); if (unlikely(!__pyx_k_tuple_17)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_17); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_17)); + + /* "View.MemoryView":127 + * + * if self.itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * encode = getattr(format, 'encode', None) + */ + __pyx_k_tuple_19 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_18)); if (unlikely(!__pyx_k_tuple_19)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_19); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_19)); + + /* "View.MemoryView":131 + * encode = getattr(format, 'encode', None) + * if encode: + * format = encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format + * self.format = self._format + */ + __pyx_k_tuple_20 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__ASCII)); if (unlikely(!__pyx_k_tuple_20)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_20); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_20)); + + /* "View.MemoryView":141 + * free(self._shape) + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_22 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_21)); if (unlikely(!__pyx_k_tuple_22)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_22); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_22)); + + /* "View.MemoryView":166 + * decode = getattr(mode, 'decode', None) + * if decode: + * mode = decode('ASCII') # <<<<<<<<<<<<<< + * self.mode = mode + * + */ + __pyx_k_tuple_25 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__ASCII)); if (unlikely(!__pyx_k_tuple_25)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_25); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_25)); + + /* "View.MemoryView":174 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_k_tuple_27 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_26)); if (unlikely(!__pyx_k_tuple_27)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_27); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_27)); + + /* "View.MemoryView":190 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_k_tuple_29 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_28)); if (unlikely(!__pyx_k_tuple_29)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_29); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_29)); + + /* "View.MemoryView":452 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_k_tuple_31 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_30)); if (unlikely(!__pyx_k_tuple_31)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_31); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_31)); + + /* "View.MemoryView":528 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_k_tuple_33 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_32)); if (unlikely(!__pyx_k_tuple_33)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_33); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_33)); + + /* "View.MemoryView":643 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_k_tuple_36 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_36)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_36); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_36)); + + /* "View.MemoryView":646 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_k_tuple_37 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_37)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_37); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_37)); + + /* "View.MemoryView":657 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_k_tuple_39 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_39)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_39); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_39)); + + /* "View.MemoryView":665 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_41 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_40)); if (unlikely(!__pyx_k_tuple_41)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_41); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_41)); + + /* "sklearn/_hmmc.pyx":35 + * + * @cython.boundscheck(False) + * def _forward(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=1] log_startprob, + * np.ndarray[dtype_t, ndim=2] log_transmat, + */ + __pyx_k_tuple_49 = PyTuple_Pack(11, ((PyObject *)__pyx_n_s__n_observations), ((PyObject *)__pyx_n_s__n_components), ((PyObject *)__pyx_n_s__log_startprob), ((PyObject *)__pyx_n_s__log_transmat), ((PyObject *)__pyx_n_s__framelogprob), ((PyObject *)__pyx_n_s__fwdlattice), ((PyObject *)__pyx_n_s__t), ((PyObject *)__pyx_n_s__i), ((PyObject *)__pyx_n_s__j), ((PyObject *)__pyx_n_s__logprob), ((PyObject *)__pyx_n_s__work_buffer)); if (unlikely(!__pyx_k_tuple_49)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_49); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_49)); + __pyx_k_codeobj_50 = (PyObject*)__Pyx_PyCode_New(6, 0, 11, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_49, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_51, __pyx_n_s___forward, 35, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_50)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/_hmmc.pyx":57 + * + * @cython.boundscheck(False) + * def _backward(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=1] log_startprob, + * np.ndarray[dtype_t, ndim=2] log_transmat, + */ + __pyx_k_tuple_53 = PyTuple_Pack(11, ((PyObject *)__pyx_n_s__n_observations), ((PyObject *)__pyx_n_s__n_components), ((PyObject *)__pyx_n_s__log_startprob), ((PyObject *)__pyx_n_s__log_transmat), ((PyObject *)__pyx_n_s__framelogprob), ((PyObject *)__pyx_n_s__bwdlattice), ((PyObject *)__pyx_n_s__t), ((PyObject *)__pyx_n_s__i), ((PyObject *)__pyx_n_s__j), ((PyObject *)__pyx_n_s__logprob), ((PyObject *)__pyx_n_s__work_buffer)); if (unlikely(!__pyx_k_tuple_53)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_53); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_53)); + __pyx_k_codeobj_54 = (PyObject*)__Pyx_PyCode_New(6, 0, 11, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_53, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_51, __pyx_n_s___backward, 57, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_54)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/_hmmc.pyx":80 + * + * @cython.boundscheck(False) + * def _compute_lneta(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=2] fwdlattice, + * np.ndarray[dtype_t, ndim=2] log_transmat, + */ + __pyx_k_tuple_55 = PyTuple_Pack(11, ((PyObject *)__pyx_n_s__n_observations), ((PyObject *)__pyx_n_s__n_components), ((PyObject *)__pyx_n_s__fwdlattice), ((PyObject *)__pyx_n_s__log_transmat), ((PyObject *)__pyx_n_s__bwdlattice), ((PyObject *)__pyx_n_s__framelogprob), ((PyObject *)__pyx_n_s__logprob), ((PyObject *)__pyx_n_s__lneta), ((PyObject *)__pyx_n_s__i), ((PyObject *)__pyx_n_s__j), ((PyObject *)__pyx_n_s__t)); if (unlikely(!__pyx_k_tuple_55)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_55); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_55)); + __pyx_k_codeobj_56 = (PyObject*)__Pyx_PyCode_New(8, 0, 11, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_55, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_51, __pyx_n_s___compute_lneta, 80, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_56)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/_hmmc.pyx":97 + * + * @cython.boundscheck(False) + * def _viterbi(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=1] log_startprob, + * np.ndarray[dtype_t, ndim=2] log_transmat, + */ + __pyx_k_tuple_57 = PyTuple_Pack(11, ((PyObject *)__pyx_n_s__n_observations), ((PyObject *)__pyx_n_s__n_components), ((PyObject *)__pyx_n_s__log_startprob), ((PyObject *)__pyx_n_s__log_transmat), ((PyObject *)__pyx_n_s__framelogprob), ((PyObject *)__pyx_n_s__t), ((PyObject *)__pyx_n_s__max_pos), ((PyObject *)__pyx_n_s__viterbi_lattice), ((PyObject *)__pyx_n_s__state_sequence), ((PyObject *)__pyx_n_s__logprob), ((PyObject *)__pyx_n_s__work_buffer)); if (unlikely(!__pyx_k_tuple_57)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_57); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_57)); + __pyx_k_codeobj_58 = (PyObject*)__Pyx_PyCode_New(5, 0, 11, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_57, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_51, __pyx_n_s___viterbi, 97, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_58)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":282 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_k_tuple_61 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_60)); if (unlikely(!__pyx_k_tuple_61)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_61); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_61)); + + /* "View.MemoryView":283 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_k_tuple_63 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_62)); if (unlikely(!__pyx_k_tuple_63)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_63); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_63)); + + /* "View.MemoryView":284 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_65 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_64)); if (unlikely(!__pyx_k_tuple_65)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_65); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_65)); + + /* "View.MemoryView":287 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_k_tuple_67 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_66)); if (unlikely(!__pyx_k_tuple_67)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_67); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_67)); + + /* "View.MemoryView":288 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * */ - __pyx_k_tuple_17 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_17)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_17)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_16)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 0, ((PyObject *)__pyx_kp_u_16)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_16)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_17)); + __pyx_k_tuple_69 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_68)); if (unlikely(!__pyx_k_tuple_69)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_69); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_69)); __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -5137,6 +16987,9 @@ static int __Pyx_InitCachedConstants(void) { static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; return 0; __pyx_L1_error:; @@ -5152,6 +17005,11 @@ PyMODINIT_FUNC PyInit__hmmc(void) #endif { PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + __pyx_t_7sklearn_5_hmmc_dtype_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -5162,12 +17020,18 @@ PyMODINIT_FUNC PyInit__hmmc(void) Py_FatalError("failed to import 'refnanny' module"); } #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__hmmc(void)"); + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__hmmc(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __pyx_binding_PyCFunctionType_USED - if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -5178,19 +17042,31 @@ PyMODINIT_FUNC PyInit__hmmc(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_hmmc"), __pyx_methods, 0, 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_hmmc"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn._hmmc")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn._hmmc", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif if (__pyx_module_is_main_sklearn___hmmc) { if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } @@ -5199,109 +17075,276 @@ PyMODINIT_FUNC PyInit__hmmc(void) /*--- Constants init code ---*/ if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Global init code ---*/ + generic = Py_None; Py_INCREF(Py_None); + strided = Py_None; Py_INCREF(Py_None); + indirect = Py_None; Py_INCREF(Py_None); + contiguous = Py_None; Py_INCREF(Py_None); + indirect_contiguous = Py_None; Py_INCREF(Py_None); /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ + __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; + __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; + __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; + __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; + __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; + __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; + __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; + __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; + if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryview_type = &__pyx_type___pyx_memoryview; + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; + __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; + __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; + __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; + __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; + __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 927; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 927; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; + if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_array_type = &__pyx_type___pyx_array; /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ - /* "sklearn/_hmmc.pyx":1 + /* "sklearn/_hmmc.pyx":2 + * from libc.math cimport exp, log * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np * cimport cython */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/_hmmc.pyx":13 + /* "sklearn/_hmmc.pyx":6 + * cimport cython + * + * np.import_array() # <<<<<<<<<<<<<< + * + * ctypedef np.float64_t dtype_t + */ + import_array(); + + /* "sklearn/_hmmc.pyx":10 + * ctypedef np.float64_t dtype_t + * + * cdef dtype_t _NINF = -np.inf # <<<<<<<<<<<<<< * * @cython.boundscheck(False) - * def _logsum(int N, np.ndarray[dtype_t, ndim=1] X): # <<<<<<<<<<<<<< - * cdef int i - * cdef double maxv, Xsum */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5_hmmc__logsum, NULL, __pyx_n_s_18); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Negative(__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___logsum, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_3 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_7sklearn_5_hmmc__NINF = __pyx_t_3; - /* "sklearn/_hmmc.pyx":24 + /* "sklearn/_hmmc.pyx":35 * * @cython.boundscheck(False) - * def _forward(int n_observations, int n_components, \ # <<<<<<<<<<<<<< - * np.ndarray[dtype_t, ndim=1] log_startprob, \ - * np.ndarray[dtype_t, ndim=2] log_transmat, \ + * def _forward(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=1] log_startprob, + * np.ndarray[dtype_t, ndim=2] log_transmat, */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5_hmmc_1_forward, NULL, __pyx_n_s_18); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5_hmmc_3_forward, NULL, __pyx_n_s_52); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___forward, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s___forward, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/_hmmc.pyx":47 + /* "sklearn/_hmmc.pyx":57 * * @cython.boundscheck(False) - * def _backward(int n_observations, int n_components, \ # <<<<<<<<<<<<<< - * np.ndarray[dtype_t, ndim=1] log_startprob, \ - * np.ndarray[dtype_t, ndim=2] log_transmat, \ + * def _backward(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=1] log_startprob, + * np.ndarray[dtype_t, ndim=2] log_transmat, */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5_hmmc_2_backward, NULL, __pyx_n_s_18); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5_hmmc_5_backward, NULL, __pyx_n_s_52); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___backward, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s___backward, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/_hmmc.pyx":70 + /* "sklearn/_hmmc.pyx":80 * * @cython.boundscheck(False) - * def _compute_lneta(int n_observations, int n_components, \ # <<<<<<<<<<<<<< - * np.ndarray[dtype_t, ndim=2] fwdlattice, \ - * np.ndarray[dtype_t, ndim=2] log_transmat, \ + * def _compute_lneta(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=2] fwdlattice, + * np.ndarray[dtype_t, ndim=2] log_transmat, */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5_hmmc_3_compute_lneta, NULL, __pyx_n_s_18); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5_hmmc_7_compute_lneta, NULL, __pyx_n_s_52); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___compute_lneta, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s___compute_lneta, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/_hmmc.pyx":87 + /* "sklearn/_hmmc.pyx":97 * * @cython.boundscheck(False) - * def _viterbi(int n_observations, int n_components, \ # <<<<<<<<<<<<<< - * np.ndarray[dtype_t, ndim=1] log_startprob, \ - * np.ndarray[dtype_t, ndim=2] log_transmat, \ + * def _viterbi(int n_observations, int n_components, # <<<<<<<<<<<<<< + * np.ndarray[dtype_t, ndim=1] log_startprob, + * np.ndarray[dtype_t, ndim=2] log_transmat, */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5_hmmc_4_viterbi, NULL, __pyx_n_s_18); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5_hmmc_9_viterbi, NULL, __pyx_n_s_52); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___viterbi, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s___viterbi, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "sklearn/_hmmc.pyx":1 - * import numpy as np # <<<<<<<<<<<<<< + * from libc.math cimport exp, log # <<<<<<<<<<<<<< + * import numpy as np * cimport numpy as np - * cimport cython */ __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - /* "numpy.pxd":971 - * arr.base = baseptr + /* "View.MemoryView":207 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * def __dealloc__(array self): + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_59); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_array_type); + + /* "View.MemoryView":282 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_61), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(generic); + __Pyx_DECREF(generic); + __Pyx_GIVEREF(__pyx_t_1); + generic = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":283 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_63), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(strided); + __Pyx_DECREF(strided); + __Pyx_GIVEREF(__pyx_t_1); + strided = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":284 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_65), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(indirect); + __Pyx_DECREF(indirect); + __Pyx_GIVEREF(__pyx_t_1); + indirect = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":287 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_67), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(contiguous); + __Pyx_DECREF(contiguous); + __Pyx_GIVEREF(__pyx_t_1); + contiguous = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":288 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_69), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(indirect_contiguous); + __Pyx_DECREF(indirect_contiguous); + __Pyx_GIVEREF(__pyx_t_1); + indirect_contiguous = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":503 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_59); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_memoryview_type); + + /* "View.MemoryView":958 + * return self.from_object + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * if arr.base is NULL: - * return None + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_59); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 958; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 958; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_memoryviewslice_type); + + /* "View.MemoryView":1365 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: */ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { __Pyx_AddTraceback("init sklearn._hmmc", __pyx_clineno, __pyx_lineno, __pyx_filename); Py_DECREF(__pyx_m); __pyx_m = 0; @@ -5318,7 +17361,6 @@ PyMODINIT_FUNC PyInit__hmmc(void) } /* Runtime support code */ - #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; @@ -5335,175 +17377,27 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { } #endif /* CYTHON_REFNANNY */ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%s' is not defined", PyString_AS_STRING(name)); +#endif } return result; } -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); - #endif -} - -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { - values[name-argnames] = value; - } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - } - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact) -{ - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; - } - if (none_allowed && obj == Py_None) return 1; - else if (exact) { - if (Py_TYPE(obj) == type) return 1; - } - else { - if (PyObject_TypeCheck(obj, type)) return 1; - } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); } static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } - -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; -} __Pyx_BufFmt_Context; - static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { @@ -5522,6 +17416,8 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; @@ -5529,7 +17425,6 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, type = type->fields->type; } } - static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; @@ -5545,15 +17440,21 @@ static int __Pyx_BufFmt_ParseNumber(const char** ts) { *ts = t; return count; } - +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } - static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { - case 'b': return "'char'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; @@ -5569,14 +17470,14 @@ static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; + case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } - static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; @@ -5592,10 +17493,9 @@ static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { return 0; } } - static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'B': return 1; + case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); @@ -5612,7 +17512,6 @@ static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { } } } - typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; @@ -5623,10 +17522,9 @@ typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif - -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); @@ -5642,21 +17540,59 @@ static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { return 0; } } - +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'h': case 'i': case 'l': case 'q': return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; - case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); - case 'O': return 'O'; - case 'P': return 'P'; + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } - static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; @@ -5680,17 +17616,38 @@ static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), parent->type->name, field->name); } -} - -static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { - char group; - size_t size, offset; - if (ctx->enc_type == 0) return 0; +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { @@ -5702,35 +17659,35 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); } - if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { - /* special case -- treat as struct rather than complex number */ size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } - - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } - offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } - ctx->fmt_offset += size; - + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; /* Consume from buffer string */ - - /* Done checking, move to next field, pushing or popping struct stack if needed */ while (1) { if (field == &ctx->root) { ctx->head = NULL; @@ -5762,7 +17719,48 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ctx->is_complex = 0; return 0; } - +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + if (isspace(*ts)) + continue; + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { @@ -5777,7 +17775,7 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } - return ts; + return ts; case ' ': case 10: case 13: @@ -5809,12 +17807,17 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { @@ -5822,10 +17825,19 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha if (!ts_after_sub) return NULL; } ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': /* end of substruct; either repeat or move on */ - ++ts; + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; @@ -5846,13 +17858,11 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': - case 'O': + case 'O': case 's': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { - /* Continue pooling same type */ ctx->enc_count += ctx->new_count; } else { - /* New type */ if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; @@ -5868,20 +17878,18 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha while(*ts != ':') ++ts; ++ts; break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; default: { - int number = __Pyx_BufFmt_ParseNumber(&ts); - if (number == -1) { /* First char was not a digit */ - PyErr_Format(PyExc_ValueError, - "Does not understand character buffer dtype format string ('%c')", *ts); - return NULL; - } - ctx->new_count = (size_t)number; + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; } } } } - static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; @@ -5889,8 +17897,10 @@ static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; @@ -5910,7 +17920,7 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* ob } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; @@ -5921,17 +17931,344 @@ fail:; __Pyx_ZeroBuffer(buf); return -1; } - static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } +static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (!buf) { + PyErr_SetString(PyExc_ValueError, + "buf is NULL."); + goto fail; + } else if (memviewslice->memview || memviewslice->data) { + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); + } + retval = 0; + goto no_fail; +fail: + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} +static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { + va_list vargs; + char msg[200]; + va_start(vargs, fmt); +#ifdef HAVE_STDARG_PROTOTYPES + va_start(vargs, fmt); +#else + va_start(vargs); +#endif + vsnprintf(msg, 200, fmt, vargs); + Py_FatalError(msg); + va_end(vargs); +} +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) +{ + int first_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview || (PyObject *) memview == Py_None) + return; /* allow uninitialized memoryview assignment */ + if (__pyx_get_slice_count(memview) < 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + first_time = __pyx_add_acquisition_count(memview) == 0; + if (first_time) { + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); + } + } +} +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, + int have_gil, int lineno) { + int last_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview ) { + return; + } else if ((PyObject *) memview == Py_None) { + memslice->memview = NULL; + return; + } + if (__pyx_get_slice_count(memview) <= 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; + if (last_time) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } + } else { + memslice->memview = NULL; + } +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (!type) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (Py_TYPE(obj) == type) return 1; + } + else { + if (PyObject_TypeCheck(obj, type)) return 1; + } + PyErr_Format(PyExc_TypeError, + "Argument '%s' has incorrect type (expected %s, got %s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); + return 0; +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static void __Pyx_RaiseBufferFallbackError(void) { + PyErr_Format(PyExc_ValueError, + "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +} + static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; @@ -5941,100 +18278,207 @@ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyOb Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif } - static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif } - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif } - -static void __Pyx_RaiseBufferFallbackError(void) { - PyErr_Format(PyExc_ValueError, - "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); } - -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { - PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { + int r; + if (!j) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { + PyObject* old = PyList_GET_ITEM(o, n); + Py_INCREF(v); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 1; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return -1; + } + } + return m->sq_ass_item(o, i, v); + } + } +#else +#if CYTHON_COMPILING_IN_PYPY + if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) { +#else + if (is_list || PySequence_Check(o)) { +#endif + return PySequence_SetItem(o, i, v); + } +#endif + return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); } #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) + if (PyClass_Check(type)) { #else - if (!PyType_Check(type)) + if (PyType_Check(type)) { #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - /* Normalize to raise , */ - Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } #endif } - __Pyx_ErrRestore(type, value, tb); return; raise_error: @@ -6043,10 +18487,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tb); return; } - #else /* Python 3+ */ - static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -6056,7 +18499,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } if (value == Py_None) value = 0; - if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, @@ -6065,37 +18507,58 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } - +#if PY_VERSION_HEX >= 0x03030000 if (cause) { +#else + if (cause && cause != Py_None) { +#endif PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; - } - else if (PyExceptionInstance_Check(cause)) { + } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; @@ -6105,73 +18568,356 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tmp_tb); } } - bad: + Py_XDECREF(owned_instance); return; } #endif -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", + index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +#if CYTHON_COMPILING_IN_CPYTHON +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) +#else + if (likely(PyString_Check(n))) +#endif + return __Pyx_PyObject_GetAttrStr(o, n); +#endif + return PyObject_GetAttr(o, n); +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r = __Pyx_GetAttr(o, n); + if (!r) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + goto bad; + PyErr_Clear(); + r = d; + Py_INCREF(d); + } + return r; +bad: + return NULL; +} + +static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { + Py_ssize_t q = a / b; + Py_ssize_t r = a - q*b; + q -= ((r != 0) & ((r ^ b) < 0)); + return q; +} + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyUnicode_CheckExact(s1) & PyUnicode_CheckExact(s2)) { + #if CYTHON_PEP393_ENABLED + if ((PyUnicode_READY(s1) < 0) || (PyUnicode_READY(s2) < 0)) + return -1; + if (PyUnicode_GET_LENGTH(s1) != PyUnicode_GET_LENGTH(s2)) { + return (equals == Py_NE); + } else if (PyUnicode_GET_LENGTH(s1) == 1) { + Py_UCS4 ch1 = PyUnicode_READ_CHAR(s1, 0); + Py_UCS4 ch2 = PyUnicode_READ_CHAR(s2, 0); + return (equals == Py_EQ) ? (ch1 == ch2) : (ch1 != ch2); + #else + if (PyUnicode_GET_SIZE(s1) != PyUnicode_GET_SIZE(s2)) { + return (equals == Py_NE); + } else if (PyUnicode_GET_SIZE(s1) == 1) { + Py_UNICODE ch1 = PyUnicode_AS_UNICODE(s1)[0]; + Py_UNICODE ch2 = PyUnicode_AS_UNICODE(s2)[0]; + return (equals == Py_EQ) ? (ch1 == ch2) : (ch1 != ch2); + #endif + } else { + int result = PyUnicode_Compare(s1, s2); + if ((result == -1) && unlikely(PyErr_Occurred())) + return -1; + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyUnicode_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyUnicode_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + length = strlen(cstring); + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + #endif + Py_INCREF(local_type); + Py_INCREF(local_value); + Py_INCREF(local_tb); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + /* Make sure tstate is in a consistent state when we XDECREF + these objects (DECREF may run arbitrary code). */ + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +static CYTHON_INLINE long __Pyx_div_long(long a, long b) { + long q = a / b; + long r = a - q*b; + q -= ((r != 0) & ((r ^ b) < 0)); + return q; +} + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); } else { - __Pyx_RaiseTooManyValuesError(index); + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); } } +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s____pyx_vtable__, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); - else { - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } } + #endif + PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; } - static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject* obj = view->obj; - if (obj) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;} - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray_1__releasebuffer__(obj, view); + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: Py_DECREF(obj); view->obj = NULL; - } } +#endif /* PY_MAJOR_VERSION < 3 */ -#endif -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s____import__); if (!py_import) goto bad; + #endif if (from_list) list = from_list; else { @@ -6180,34 +18926,309 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { goto bad; list = empty_list; } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - #if PY_VERSION_HEX >= 0x02050000 - { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +static int +__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) +{ + int i; + if (!a || !b) + return 0; + if (a == b) + return 1; + if (a->size != b->size || a->typegroup != b->typegroup || + a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { + if (a->typegroup == 'H' || b->typegroup == 'H') { + return a->size == b->size; + } else { + return 0; + } + } + if (a->ndim) { + for (i = 0; i < a->ndim; i++) + if (a->arraysize[i] != b->arraysize[i]) + return 0; + } + if (a->typegroup == 'S') { + if (a->flags != b->flags) + return 0; + if (a->fields || b->fields) { + if (!(a->fields && b->fields)) + return 0; + for (i = 0; a->fields[i].type && b->fields[i].type; i++) { + __Pyx_StructField *field_a = a->fields + i; + __Pyx_StructField *field_b = b->fields + i; + if (field_a->offset != field_b->offset || + !__pyx_typeinfo_cmp(field_a->type, field_b->type)) + return 0; + } + return !a->fields[i].type && !b->fields[i].type; + } + } + return 1; +} + +static int +__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) +{ + if (buf->shape[dim] <= 1) + return 1; + if (buf->strides) { + if (spec & __Pyx_MEMVIEW_CONTIG) { + if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { + if (buf->strides[dim] != sizeof(void *)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly contiguous " + "in dimension %d.", dim); + goto fail; + } + } else if (buf->strides[dim] != buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_FOLLOW) { + Py_ssize_t stride = buf->strides[dim]; + if (stride < 0) + stride = -stride; + if (stride < buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + } else { + if (spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not contiguous in " + "dimension %d", dim); + goto fail; + } else if (spec & (__Pyx_MEMVIEW_PTR)) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not indirect in " + "dimension %d", dim); + goto fail; + } else if (buf->suboffsets) { + PyErr_SetString(PyExc_ValueError, + "Buffer exposes suboffsets but no strides"); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) +{ + if (spec & __Pyx_MEMVIEW_DIRECT) { + if (buf->suboffsets && buf->suboffsets[dim] >= 0) { + PyErr_Format(PyExc_ValueError, + "Buffer not compatible with direct access " + "in dimension %d.", dim); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_PTR) { + if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly accessisble " + "in dimension %d.", dim); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) +{ + int i; + if (c_or_f_flag & __Pyx_IS_F_CONTIG) { + Py_ssize_t stride = 1; + for (i = 0; i < ndim; i++) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) + { + PyErr_SetString(PyExc_ValueError, + "Buffer not fortran contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { + Py_ssize_t stride = 1; + for (i = ndim - 1; i >- 1; i--) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) { + PyErr_SetString(PyExc_ValueError, + "Buffer not C contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } + return 1; +fail: + return 0; +} +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj) +{ + struct __pyx_memoryview_obj *memview, *new_memview; + __Pyx_RefNannyDeclarations + Py_buffer *buf; + int i, spec = 0, retval = -1; + __Pyx_BufFmt_Context ctx; + int from_memoryview = __pyx_memoryview_check(original_obj); + __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); + if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) + original_obj)->typeinfo)) { + memview = (struct __pyx_memoryview_obj *) original_obj; + new_memview = NULL; + } else { + memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + original_obj, buf_flags, 0, dtype); + new_memview = memview; + if (unlikely(!memview)) + goto fail; } - #else - if (level>0) { - PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); - goto bad; + buf = &memview->view; + if (buf->ndim != ndim) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + ndim, buf->ndim); + goto fail; } - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, NULL); - #endif -bad: - Py_XDECREF(empty_list); - Py_XDECREF(py_import); - Py_XDECREF(empty_dict); - return module; + if (new_memview) { + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned) buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " + "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", + buf->itemsize, + (buf->itemsize > 1) ? "s" : "", + dtype->name, + dtype->size, + (dtype->size > 1) ? "s" : ""); + goto fail; + } + for (i = 0; i < ndim; i++) { + spec = axes_specs[i]; + if (!__pyx_check_strides(buf, i, ndim, spec)) + goto fail; + if (!__pyx_check_suboffsets(buf, i, ndim, spec)) + goto fail; + } + if (buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, + new_memview != NULL) == -1)) { + goto fail; + } + retval = 0; + goto no_fail; +fail: + Py_XDECREF(new_memview); + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5_hmmc_dtype_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS, 1, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5_hmmc_dtype_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; } static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_long(npy_long val) { @@ -6475,6 +19496,172 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_long(npy_long val) { #endif #endif +static int +__pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim) +{ + int i, index, step, start; + Py_ssize_t itemsize = mvs->memview->view.itemsize; + if (order == 'F') { + step = 1; + start = 0; + } else { + step = -1; + start = ndim - 1; + } + for (i = 0; i < ndim; i++) { + index = start + step * i; + if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) + return 0; + itemsize *= mvs->shape[index]; + } + return 1; +} + +static void +__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + start = end = slice->data; + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + if (extent == 0) { + *out_start = *out_end = start; + return; + } else { + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); + } + } + *out_start = start; + *out_end = end + itemsize; +} +static int +__pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize) +{ + void *start1, *end1, *start2, *end2; + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + return (start1 < end2) && (start2 < end1); +} + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + for (i = 0; i < ndim; i++) { + if (from_mvs->suboffsets[i] >= 0) { + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; + } + } + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; + } + __Pyx_GOTREF(shape_tuple); + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromLong(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; + } else { + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; + } + } + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + goto no_fail; +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; +} + +static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) +{ + PyObject *cobj; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); +#endif + return cobj; +} + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +#else + PyErr_GetExcInfo(type, value, tb); +#endif +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(type, value, tb); +#endif +} + static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { const unsigned char neg_one = (unsigned char)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; @@ -6665,10 +19852,15 @@ static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { return (int)__Pyx_PyInt_AsLong(x); } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { const unsigned long neg_one = (unsigned long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6681,6 +19873,16 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); @@ -6688,6 +19890,17 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { } return (unsigned long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (unsigned long)PyLong_AsLong(x); } } else { @@ -6700,10 +19913,15 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6716,6 +19934,16 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned PY_LONG_LONG"); @@ -6723,6 +19951,17 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje } return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -6735,10 +19974,15 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { const long neg_one = (long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6751,6 +19995,16 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); @@ -6758,6 +20012,17 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { } return (long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (long)PyLong_AsLong(x); } } else { @@ -6770,10 +20035,15 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6786,6 +20056,16 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to PY_LONG_LONG"); @@ -6793,6 +20073,17 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { } return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -6805,10 +20096,15 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { const signed long neg_one = (signed long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6821,6 +20117,16 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed long"); @@ -6828,6 +20134,17 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { } return (signed long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (signed long)PyLong_AsLong(x); } } else { @@ -6840,10 +20157,15 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6856,6 +20178,16 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed PY_LONG_LONG"); @@ -6863,6 +20195,17 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* } return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (signed PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -6894,6 +20237,23 @@ static int __Pyx_check_binary_version(void) { return 0; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -6903,15 +20263,14 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(class_name); - #else - py_name = PyUnicode_FromString(class_name); - #endif + py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); @@ -6927,7 +20286,19 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -6937,7 +20308,7 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%s.%s has the wrong size, try recompiling", module_name, class_name); @@ -6951,51 +20322,105 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(name); - #else - py_name = PyUnicode_FromString(name); - #endif - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); } -#endif #include "compile.h" #include "frameobject.h" #include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); + py_srcfile = PyString_FromString(filename); #else - py_srcfile = PyUnicode_FromString(__pyx_filename); + py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; - if (__pyx_clineno) { + if (c_line) { #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { @@ -7006,28 +20431,45 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, #endif } if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_code = PyCode_New( + py_code = __Pyx_PyCode_New( 0, /*int argcount,*/ - #if PY_MAJOR_VERSION >= 3 0, /*int kwonlyargcount,*/ - #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ + py_line, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); - if (!py_code) goto bad; + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ @@ -7035,11 +20477,9 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; + py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); } @@ -7074,26 +20514,82 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (r < 0) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -7109,7 +20605,7 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { @@ -7127,7 +20623,6 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject* x = PyNumber_Index(b); @@ -7136,7 +20631,6 @@ static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) @@ -7150,14 +20644,12 @@ static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); #endif } - static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); + if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); return (size_t)-1; } return (size_t)val; diff --git a/sklearn/_hmmc.pyx b/sklearn/_hmmc.pyx index b0c8218d2d5cc..4aacc0319c56c 100644 --- a/sklearn/_hmmc.pyx +++ b/sklearn/_hmmc.pyx @@ -1,30 +1,41 @@ +from libc.math cimport exp, log import numpy as np cimport numpy as np cimport cython -cdef extern from "math.h": - double exp(double) - double log(double) +np.import_array() ctypedef np.float64_t dtype_t +cdef dtype_t _NINF = -np.inf @cython.boundscheck(False) -def _logsum(int N, np.ndarray[dtype_t, ndim=1] X): - cdef int i - cdef double maxv, Xsum - Xsum = 0.0 - maxv = X.max() - for i in xrange(N): - Xsum += exp(X[i] - maxv) - return log(Xsum) + maxv +cdef dtype_t _max(dtype_t[:] values): + # find maximum value (builtin 'max' is unrolled for speed) + cdef dtype_t value + cdef dtype_t vmax = _NINF + for i in range(values.shape[0]): + value = values[i] + if value > vmax: + vmax = value + return vmax + +@cython.boundscheck(False) +cpdef dtype_t _logsum(dtype_t[:] X): + cdef dtype_t vmax = _max(X) + cdef dtype_t power_sum = 0 + + for i in range(X.shape[0]): + power_sum += exp(X[i]-vmax) + + return log(power_sum) + vmax @cython.boundscheck(False) -def _forward(int n_observations, int n_components, \ - np.ndarray[dtype_t, ndim=1] log_startprob, \ - np.ndarray[dtype_t, ndim=2] log_transmat, \ - np.ndarray[dtype_t, ndim=2] framelogprob, \ +def _forward(int n_observations, int n_components, + np.ndarray[dtype_t, ndim=1] log_startprob, + np.ndarray[dtype_t, ndim=2] log_transmat, + np.ndarray[dtype_t, ndim=2] framelogprob, np.ndarray[dtype_t, ndim=2] fwdlattice): cdef int t, i, j @@ -32,22 +43,21 @@ def _forward(int n_observations, int n_components, \ cdef np.ndarray[dtype_t, ndim = 1] work_buffer work_buffer = np.zeros(n_components) - for i in xrange(n_components): + for i in range(n_components): fwdlattice[0, i] = log_startprob[i] + framelogprob[0, i] - for t in xrange(1, n_observations): - for j in xrange(n_components): - for i in xrange(n_components): + for t in range(1, n_observations): + for j in range(n_components): + for i in range(n_components): work_buffer[i] = fwdlattice[t - 1, i] + log_transmat[i, j] - fwdlattice[t, j] = _logsum(n_components, work_buffer) \ - + framelogprob[t, j] + fwdlattice[t, j] = _logsum(work_buffer) + framelogprob[t, j] @cython.boundscheck(False) -def _backward(int n_observations, int n_components, \ - np.ndarray[dtype_t, ndim=1] log_startprob, \ - np.ndarray[dtype_t, ndim=2] log_transmat, \ - np.ndarray[dtype_t, ndim=2] framelogprob, \ +def _backward(int n_observations, int n_components, + np.ndarray[dtype_t, ndim=1] log_startprob, + np.ndarray[dtype_t, ndim=2] log_transmat, + np.ndarray[dtype_t, ndim=2] framelogprob, np.ndarray[dtype_t, ndim=2] bwdlattice): cdef int t, i, j @@ -55,67 +65,62 @@ def _backward(int n_observations, int n_components, \ cdef np.ndarray[dtype_t, ndim = 1] work_buffer work_buffer = np.zeros(n_components) - for i in xrange(n_components): + for i in range(n_components): bwdlattice[n_observations - 1, i] = 0.0 - for t in xrange(n_observations - 2, -1, -1): - for i in xrange(n_components): - for j in xrange(n_components): + for t in range(n_observations - 2, -1, -1): + for i in range(n_components): + for j in range(n_components): work_buffer[j] = log_transmat[i, j] + framelogprob[t + 1, j] \ + bwdlattice[t + 1, j] - bwdlattice[t, i] = _logsum(n_components, work_buffer) + bwdlattice[t, i] = _logsum(work_buffer) @cython.boundscheck(False) -def _compute_lneta(int n_observations, int n_components, \ - np.ndarray[dtype_t, ndim=2] fwdlattice, \ - np.ndarray[dtype_t, ndim=2] log_transmat, \ - np.ndarray[dtype_t, ndim=2] bwdlattice, \ - np.ndarray[dtype_t, ndim=2] framelogprob, \ - double logprob, \ +def _compute_lneta(int n_observations, int n_components, + np.ndarray[dtype_t, ndim=2] fwdlattice, + np.ndarray[dtype_t, ndim=2] log_transmat, + np.ndarray[dtype_t, ndim=2] bwdlattice, + np.ndarray[dtype_t, ndim=2] framelogprob, + double logprob, np.ndarray[dtype_t, ndim=3] lneta): cdef int i, j, t - for t in xrange(n_observations - 1): - for i in xrange(n_components): - for j in xrange(n_components): + for t in range(n_observations - 1): + for i in range(n_components): + for j in range(n_components): lneta[t, i, j] = fwdlattice[t, i] + log_transmat[i, j] \ + framelogprob[t + 1, j] + bwdlattice[t + 1, j] - logprob @cython.boundscheck(False) -def _viterbi(int n_observations, int n_components, \ - np.ndarray[dtype_t, ndim=1] log_startprob, \ - np.ndarray[dtype_t, ndim=2] log_transmat, \ +def _viterbi(int n_observations, int n_components, + np.ndarray[dtype_t, ndim=1] log_startprob, + np.ndarray[dtype_t, ndim=2] log_transmat, np.ndarray[dtype_t, ndim=2] framelogprob): - cdef int i, j, t, max_pos + cdef int t, max_pos cdef np.ndarray[dtype_t, ndim = 2] viterbi_lattice cdef np.ndarray[np.int_t, ndim = 1] state_sequence - cdef double logprob - cdef np.ndarray[dtype_t, ndim = 1] work_buffer + cdef dtype_t logprob + cdef np.ndarray[dtype_t, ndim = 2] work_buffer - # Initialize state_sequenceation - state_sequence = np.zeros(n_observations, dtype=np.int) - work_buffer = np.zeros(n_components) + # Initialization + state_sequence = np.empty(n_observations, dtype=np.int) viterbi_lattice = np.zeros((n_observations, n_components)) - - # viterbi_lattice[0,:] = log_startprob[:] + framelogprob[0,:] - for i in xrange(n_components): - viterbi_lattice[0, i] = log_startprob[i] + framelogprob[0, i] + viterbi_lattice[0] = log_startprob + framelogprob[0] # Induction - for t in xrange(1, n_observations): - for j in xrange(n_components): - work_buffer[:] = viterbi_lattice[t - 1, :] + log_transmat[:, j] - viterbi_lattice[t, j] = np.max(work_buffer[:]) + framelogprob[t, j] + for t in range(1, n_observations): + work_buffer = viterbi_lattice[t-1] + log_transmat.T + viterbi_lattice[t] = np.max(work_buffer, axis=1) + framelogprob[t] - # observation traceback + # Observation traceback max_pos = np.argmax(viterbi_lattice[n_observations - 1, :]) state_sequence[n_observations - 1] = max_pos logprob = viterbi_lattice[n_observations - 1, max_pos] - - for t in xrange(n_observations - 2, -1, -1): + + for t in range(n_observations - 2, -1, -1): max_pos = np.argmax(viterbi_lattice[t, :] \ + log_transmat[:, state_sequence[t + 1]]) state_sequence[t] = max_pos diff --git a/sklearn/_isotonic.c b/sklearn/_isotonic.c new file mode 100644 index 0000000000000..f22b951d402af --- /dev/null +++ b/sklearn/_isotonic.c @@ -0,0 +1,6817 @@ +/* Generated by Cython 0.21.1 */ + +#define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) + #error Cython requires Python 2.6+ or Python 3.2+. +#else +#define CYTHON_ABI "0_21_1" +#include +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 +#define Py_OptimizeFlag 0 +#endif +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) + #define __Pyx_PyFrozenSet_Size(s) PyObject_Size(s) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) + #define __Pyx_PyFrozenSet_Size(s) PySet_Size(s) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY + #ifndef PyUnicode_InternFromString + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) + #endif +#endif +#if PY_VERSION_HEX < 0x030200A4 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#else + #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) +#endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#ifdef __cplusplus +template +void __Pyx_call_destructor(T* x) { + x->~T(); +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn___isotonic +#define __PYX_HAVE_API__sklearn___isotonic +#include "string.h" +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "sklearn/_isotonic.pyx", + "__init__.pxd", + "type.pxd", +}; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; + struct __Pyx_StructField_* fields; + size_t size; + size_t arraysize[8]; + int ndim; + char typegroup; + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":723 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":724 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":725 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":726 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":730 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":731 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":732 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":733 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":737 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":738 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":747 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":748 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":749 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":751 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":752 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":753 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":755 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":756 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":758 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":759 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":760 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; + +/* "sklearn/_isotonic.pyx":11 + * cimport cython + * + * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< + * + * np.import_array() + */ +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_9_isotonic_DOUBLE; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":762 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":763 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":764 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":766 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); + +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); + +static int __Pyx_check_binary_version(void); + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); + + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'cython' */ + +/* Module declarations from 'sklearn._isotonic' */ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_9_isotonic_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_9_isotonic_DOUBLE), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t = { "float64_t", NULL, sizeof(__pyx_t_5numpy_float64_t), { 0 }, 0, 'R', 0, 0 }; +#define __Pyx_MODULE_NAME "sklearn._isotonic" +int __pyx_module_is_main_sklearn___isotonic = 0; + +/* Implementation of 'sklearn._isotonic' */ +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_pf_7sklearn_9_isotonic__isotonic_regression(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_weight, PyArrayObject *__pyx_v_solution); /* proto */ +static PyObject *__pyx_pf_7sklearn_9_isotonic_2_make_unique(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_weights); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static char __pyx_k_B[] = "B"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_X[] = "X"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_j[] = "j"; +static char __pyx_k_k[] = "k"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_n[] = "n"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_x[] = "x"; +static char __pyx_k_y[] = "y"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_empty[] = "empty"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_ratio[] = "ratio"; +static char __pyx_k_x_out[] = "x_out"; +static char __pyx_k_y_old[] = "y_old"; +static char __pyx_k_y_out[] = "y_out"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_pooled[] = "pooled"; +static char __pyx_k_unique[] = "unique"; +static char __pyx_k_weight[] = "weight"; +static char __pyx_k_solution[] = "solution"; +static char __pyx_k_current_x[] = "current_x"; +static char __pyx_k_current_y[] = "current_y"; +static char __pyx_k_n_samples[] = "n_samples"; +static char __pyx_k_numerator[] = "numerator"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_denominator[] = "denominator"; +static char __pyx_k_make_unique[] = "_make_unique"; +static char __pyx_k_weights_out[] = "weights_out"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_current_count[] = "current_count"; +static char __pyx_k_unique_values[] = "unique_values"; +static char __pyx_k_current_weight[] = "current_weight"; +static char __pyx_k_sample_weights[] = "sample_weights"; +static char __pyx_k_sklearn__isotonic[] = "sklearn._isotonic"; +static char __pyx_k_isotonic_regression[] = "_isotonic_regression"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_home_andy_checkout_scikit_learn[] = "/home/andy/checkout/scikit-learn/sklearn/_isotonic.pyx"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_n_s_current_count; +static PyObject *__pyx_n_s_current_weight; +static PyObject *__pyx_n_s_current_x; +static PyObject *__pyx_n_s_current_y; +static PyObject *__pyx_n_s_denominator; +static PyObject *__pyx_n_s_empty; +static PyObject *__pyx_kp_s_home_andy_checkout_scikit_learn; +static PyObject *__pyx_n_s_i; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_isotonic_regression; +static PyObject *__pyx_n_s_j; +static PyObject *__pyx_n_s_k; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_make_unique; +static PyObject *__pyx_n_s_n; +static PyObject *__pyx_n_s_n_samples; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numerator; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_pooled; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_ratio; +static PyObject *__pyx_n_s_sample_weights; +static PyObject *__pyx_n_s_sklearn__isotonic; +static PyObject *__pyx_n_s_solution; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_n_s_unique; +static PyObject *__pyx_n_s_unique_values; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_weight; +static PyObject *__pyx_n_s_weights_out; +static PyObject *__pyx_n_s_x; +static PyObject *__pyx_n_s_x_out; +static PyObject *__pyx_n_s_y; +static PyObject *__pyx_n_s_y_old; +static PyObject *__pyx_n_s_y_out; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_codeobj__8; +static PyObject *__pyx_codeobj__10; + +/* "sklearn/_isotonic.pyx":19 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _isotonic_regression(np.ndarray[DOUBLE, ndim=1] y, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=1] weight, + * np.ndarray[DOUBLE, ndim=1] solution): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9_isotonic_1_isotonic_regression(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_9_isotonic_1_isotonic_regression = {"_isotonic_regression", (PyCFunction)__pyx_pw_7sklearn_9_isotonic_1_isotonic_regression, METH_VARARGS|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_7sklearn_9_isotonic_1_isotonic_regression(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_y = 0; + PyArrayObject *__pyx_v_weight = 0; + PyArrayObject *__pyx_v_solution = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_isotonic_regression (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_y,&__pyx_n_s_weight,&__pyx_n_s_solution,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_weight)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_isotonic_regression", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_solution)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_isotonic_regression", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_isotonic_regression") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v_y = ((PyArrayObject *)values[0]); + __pyx_v_weight = ((PyArrayObject *)values[1]); + __pyx_v_solution = ((PyArrayObject *)values[2]); + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_isotonic_regression", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn._isotonic._isotonic_regression", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weight), __pyx_ptype_5numpy_ndarray, 1, "weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_solution), __pyx_ptype_5numpy_ndarray, 1, "solution", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_9_isotonic__isotonic_regression(__pyx_self, __pyx_v_y, __pyx_v_weight, __pyx_v_solution); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9_isotonic__isotonic_regression(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_weight, PyArrayObject *__pyx_v_solution) { + __pyx_t_7sklearn_9_isotonic_DOUBLE __pyx_v_numerator; + __pyx_t_7sklearn_9_isotonic_DOUBLE __pyx_v_denominator; + __pyx_t_7sklearn_9_isotonic_DOUBLE __pyx_v_ratio; + Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_pooled; + Py_ssize_t __pyx_v_n; + Py_ssize_t __pyx_v_k; + Py_ssize_t __pyx_v_j; + __Pyx_LocalBuf_ND __pyx_pybuffernd_solution; + __Pyx_Buffer __pyx_pybuffer_solution; + __Pyx_LocalBuf_ND __pyx_pybuffernd_weight; + __Pyx_Buffer __pyx_pybuffer_weight; + __Pyx_LocalBuf_ND __pyx_pybuffernd_y; + __Pyx_Buffer __pyx_pybuffer_y; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + Py_ssize_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + Py_ssize_t __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_isotonic_regression", 0); + __pyx_pybuffer_y.pybuffer.buf = NULL; + __pyx_pybuffer_y.refcount = 0; + __pyx_pybuffernd_y.data = NULL; + __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; + __pyx_pybuffer_weight.pybuffer.buf = NULL; + __pyx_pybuffer_weight.refcount = 0; + __pyx_pybuffernd_weight.data = NULL; + __pyx_pybuffernd_weight.rcbuffer = &__pyx_pybuffer_weight; + __pyx_pybuffer_solution.pybuffer.buf = NULL; + __pyx_pybuffer_solution.refcount = 0; + __pyx_pybuffernd_solution.data = NULL; + __pyx_pybuffernd_solution.rcbuffer = &__pyx_pybuffer_solution; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9_isotonic_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_weight, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9_isotonic_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_weight.diminfo[0].strides = __pyx_pybuffernd_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weight.diminfo[0].shape = __pyx_pybuffernd_weight.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_solution.rcbuffer->pybuffer, (PyObject*)__pyx_v_solution, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9_isotonic_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_solution.diminfo[0].strides = __pyx_pybuffernd_solution.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_solution.diminfo[0].shape = __pyx_pybuffernd_solution.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/_isotonic.pyx":26 + * Py_ssize_t i, pooled, n, k + * + * n = y.shape[0] # <<<<<<<<<<<<<< + * # The algorithm proceeds by iteratively updating the solution + * # array. + */ + __pyx_v_n = (__pyx_v_y->dimensions[0]); + + /* "sklearn/_isotonic.pyx":32 + * # TODO - should we just pass in a pre-copied solution + * # array and mutate that? + * for i in range(n): # <<<<<<<<<<<<<< + * solution[i] = y[i] + * + */ + __pyx_t_1 = __pyx_v_n; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "sklearn/_isotonic.pyx":33 + * # array and mutate that? + * for i in range(n): + * solution[i] = y[i] # <<<<<<<<<<<<<< + * + * if n <= 1: + */ + __pyx_t_3 = __pyx_v_i; + __pyx_t_4 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_9_isotonic_DOUBLE *, __pyx_pybuffernd_solution.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_solution.diminfo[0].strides) = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_9_isotonic_DOUBLE *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_y.diminfo[0].strides)); + } + + /* "sklearn/_isotonic.pyx":35 + * solution[i] = y[i] + * + * if n <= 1: # <<<<<<<<<<<<<< + * return solution + * + */ + __pyx_t_5 = ((__pyx_v_n <= 1) != 0); + if (__pyx_t_5) { + + /* "sklearn/_isotonic.pyx":36 + * + * if n <= 1: + * return solution # <<<<<<<<<<<<<< + * + * n -= 1 + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_solution)); + __pyx_r = ((PyObject *)__pyx_v_solution); + goto __pyx_L0; + } + + /* "sklearn/_isotonic.pyx":38 + * return solution + * + * n -= 1 # <<<<<<<<<<<<<< + * while 1: + * # repeat until there are no more adjacent violators. + */ + __pyx_v_n = (__pyx_v_n - 1); + + /* "sklearn/_isotonic.pyx":39 + * + * n -= 1 + * while 1: # <<<<<<<<<<<<<< + * # repeat until there are no more adjacent violators. + * i = 0 + */ + while (1) { + + /* "sklearn/_isotonic.pyx":41 + * while 1: + * # repeat until there are no more adjacent violators. + * i = 0 # <<<<<<<<<<<<<< + * pooled = 0 + * while i < n: + */ + __pyx_v_i = 0; + + /* "sklearn/_isotonic.pyx":42 + * # repeat until there are no more adjacent violators. + * i = 0 + * pooled = 0 # <<<<<<<<<<<<<< + * while i < n: + * k = i + */ + __pyx_v_pooled = 0; + + /* "sklearn/_isotonic.pyx":43 + * i = 0 + * pooled = 0 + * while i < n: # <<<<<<<<<<<<<< + * k = i + * while k < n and solution[k] >= solution[k + 1]: + */ + while (1) { + __pyx_t_5 = ((__pyx_v_i < __pyx_v_n) != 0); + if (!__pyx_t_5) break; + + /* "sklearn/_isotonic.pyx":44 + * pooled = 0 + * while i < n: + * k = i # <<<<<<<<<<<<<< + * while k < n and solution[k] >= solution[k + 1]: + * k += 1 + */ + __pyx_v_k = __pyx_v_i; + + /* "sklearn/_isotonic.pyx":45 + * while i < n: + * k = i + * while k < n and solution[k] >= solution[k + 1]: # <<<<<<<<<<<<<< + * k += 1 + * if solution[i] != solution[k]: + */ + while (1) { + __pyx_t_6 = ((__pyx_v_k < __pyx_v_n) != 0); + if (__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L12_bool_binop_done; + } + __pyx_t_1 = __pyx_v_k; + __pyx_t_2 = (__pyx_v_k + 1); + __pyx_t_6 = (((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_9_isotonic_DOUBLE *, __pyx_pybuffernd_solution.rcbuffer->pybuffer.buf, __pyx_t_1, __pyx_pybuffernd_solution.diminfo[0].strides)) >= (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_9_isotonic_DOUBLE *, __pyx_pybuffernd_solution.rcbuffer->pybuffer.buf, __pyx_t_2, __pyx_pybuffernd_solution.diminfo[0].strides))) != 0); + __pyx_t_5 = __pyx_t_6; + __pyx_L12_bool_binop_done:; + if (!__pyx_t_5) break; + + /* "sklearn/_isotonic.pyx":46 + * k = i + * while k < n and solution[k] >= solution[k + 1]: + * k += 1 # <<<<<<<<<<<<<< + * if solution[i] != solution[k]: + * # solution[i:k + 1] is a decreasing subsequence, so + */ + __pyx_v_k = (__pyx_v_k + 1); + } + + /* "sklearn/_isotonic.pyx":47 + * while k < n and solution[k] >= solution[k + 1]: + * k += 1 + * if solution[i] != solution[k]: # <<<<<<<<<<<<<< + * # solution[i:k + 1] is a decreasing subsequence, so + * # replace each point in the subsequence with the + */ + __pyx_t_7 = __pyx_v_i; + __pyx_t_8 = __pyx_v_k; + __pyx_t_5 = (((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_9_isotonic_DOUBLE *, __pyx_pybuffernd_solution.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_solution.diminfo[0].strides)) != (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_9_isotonic_DOUBLE *, __pyx_pybuffernd_solution.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_solution.diminfo[0].strides))) != 0); + if (__pyx_t_5) { + + /* "sklearn/_isotonic.pyx":57 + * # Theoretically should reduce running time, though + * # initial experiments weren't promising. + * numerator = 0.0 # <<<<<<<<<<<<<< + * denominator = 0.0 + * for j in range(i, k + 1): + */ + __pyx_v_numerator = 0.0; + + /* "sklearn/_isotonic.pyx":58 + * # initial experiments weren't promising. + * numerator = 0.0 + * denominator = 0.0 # <<<<<<<<<<<<<< + * for j in range(i, k + 1): + * numerator += solution[j] * weight[j] + */ + __pyx_v_denominator = 0.0; + + /* "sklearn/_isotonic.pyx":59 + * numerator = 0.0 + * denominator = 0.0 + * for j in range(i, k + 1): # <<<<<<<<<<<<<< + * numerator += solution[j] * weight[j] + * denominator += weight[j] + */ + __pyx_t_9 = (__pyx_v_k + 1); + for (__pyx_t_10 = __pyx_v_i; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { + __pyx_v_j = __pyx_t_10; + + /* "sklearn/_isotonic.pyx":60 + * denominator = 0.0 + * for j in range(i, k + 1): + * numerator += solution[j] * weight[j] # <<<<<<<<<<<<<< + * denominator += weight[j] + * ratio = numerator / denominator + */ + __pyx_t_11 = __pyx_v_j; + __pyx_t_12 = __pyx_v_j; + __pyx_v_numerator = (__pyx_v_numerator + ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_9_isotonic_DOUBLE *, __pyx_pybuffernd_solution.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_solution.diminfo[0].strides)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_9_isotonic_DOUBLE *, __pyx_pybuffernd_weight.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_weight.diminfo[0].strides)))); + + /* "sklearn/_isotonic.pyx":61 + * for j in range(i, k + 1): + * numerator += solution[j] * weight[j] + * denominator += weight[j] # <<<<<<<<<<<<<< + * ratio = numerator / denominator + * for j in range(i, k + 1): + */ + __pyx_t_13 = __pyx_v_j; + __pyx_v_denominator = (__pyx_v_denominator + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_9_isotonic_DOUBLE *, __pyx_pybuffernd_weight.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_weight.diminfo[0].strides))); + } + + /* "sklearn/_isotonic.pyx":62 + * numerator += solution[j] * weight[j] + * denominator += weight[j] + * ratio = numerator / denominator # <<<<<<<<<<<<<< + * for j in range(i, k + 1): + * solution[j] = ratio + */ + __pyx_v_ratio = (__pyx_v_numerator / __pyx_v_denominator); + + /* "sklearn/_isotonic.pyx":63 + * denominator += weight[j] + * ratio = numerator / denominator + * for j in range(i, k + 1): # <<<<<<<<<<<<<< + * solution[j] = ratio + * pooled = 1 + */ + __pyx_t_9 = (__pyx_v_k + 1); + for (__pyx_t_10 = __pyx_v_i; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { + __pyx_v_j = __pyx_t_10; + + /* "sklearn/_isotonic.pyx":64 + * ratio = numerator / denominator + * for j in range(i, k + 1): + * solution[j] = ratio # <<<<<<<<<<<<<< + * pooled = 1 + * i = k + 1 + */ + __pyx_t_14 = __pyx_v_j; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_9_isotonic_DOUBLE *, __pyx_pybuffernd_solution.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_solution.diminfo[0].strides) = __pyx_v_ratio; + } + + /* "sklearn/_isotonic.pyx":65 + * for j in range(i, k + 1): + * solution[j] = ratio + * pooled = 1 # <<<<<<<<<<<<<< + * i = k + 1 + * # Check for convergence + */ + __pyx_v_pooled = 1; + goto __pyx_L14; + } + __pyx_L14:; + + /* "sklearn/_isotonic.pyx":66 + * solution[j] = ratio + * pooled = 1 + * i = k + 1 # <<<<<<<<<<<<<< + * # Check for convergence + * if pooled == 0: + */ + __pyx_v_i = (__pyx_v_k + 1); + } + + /* "sklearn/_isotonic.pyx":68 + * i = k + 1 + * # Check for convergence + * if pooled == 0: # <<<<<<<<<<<<<< + * break + * + */ + __pyx_t_5 = ((__pyx_v_pooled == 0) != 0); + if (__pyx_t_5) { + + /* "sklearn/_isotonic.pyx":69 + * # Check for convergence + * if pooled == 0: + * break # <<<<<<<<<<<<<< + * + * return solution + */ + goto __pyx_L7_break; + } + } + __pyx_L7_break:; + + /* "sklearn/_isotonic.pyx":71 + * break + * + * return solution # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_solution)); + __pyx_r = ((PyObject *)__pyx_v_solution); + goto __pyx_L0; + + /* "sklearn/_isotonic.pyx":19 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _isotonic_regression(np.ndarray[DOUBLE, ndim=1] y, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=1] weight, + * np.ndarray[DOUBLE, ndim=1] solution): + */ + + /* function exit code */ + __pyx_L1_error:; + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_solution.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn._isotonic._isotonic_regression", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_solution.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/_isotonic.pyx":77 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _make_unique(np.ndarray[dtype=np.float64_t] X, # <<<<<<<<<<<<<< + * np.ndarray[dtype=np.float64_t] y, + * np.ndarray[dtype=np.float64_t] sample_weights): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9_isotonic_3_make_unique(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9_isotonic_2_make_unique[] = "Average targets for duplicate X, drop duplicates.\n\n Aggregates duplicate X values into a single X value where\n the target y is a (sample_weighted) average of the individual\n targets.\n\n Assumes that X is ordered, so that all duplicates follow each other.\n "; +static PyMethodDef __pyx_mdef_7sklearn_9_isotonic_3_make_unique = {"_make_unique", (PyCFunction)__pyx_pw_7sklearn_9_isotonic_3_make_unique, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_9_isotonic_2_make_unique}; +static PyObject *__pyx_pw_7sklearn_9_isotonic_3_make_unique(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_X = 0; + PyArrayObject *__pyx_v_y = 0; + PyArrayObject *__pyx_v_sample_weights = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_make_unique (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_y,&__pyx_n_s_sample_weights,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_make_unique", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sample_weights)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_make_unique", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_make_unique") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v_X = ((PyArrayObject *)values[0]); + __pyx_v_y = ((PyArrayObject *)values[1]); + __pyx_v_sample_weights = ((PyArrayObject *)values[2]); + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_make_unique", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn._isotonic._make_unique", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weights), __pyx_ptype_5numpy_ndarray, 1, "sample_weights", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_9_isotonic_2_make_unique(__pyx_self, __pyx_v_X, __pyx_v_y, __pyx_v_sample_weights); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9_isotonic_2_make_unique(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_weights) { + Py_ssize_t __pyx_v_unique_values; + PyArrayObject *__pyx_v_y_out = 0; + PyArrayObject *__pyx_v_x_out = 0; + PyArrayObject *__pyx_v_weights_out = 0; + float __pyx_v_current_x; + float __pyx_v_current_y; + float __pyx_v_current_weight; + CYTHON_UNUSED float __pyx_v_y_old; + int __pyx_v_i; + int __pyx_v_current_count; + int __pyx_v_j; + float __pyx_v_x; + int __pyx_v_n_samples; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_LocalBuf_ND __pyx_pybuffernd_sample_weights; + __Pyx_Buffer __pyx_pybuffer_sample_weights; + __Pyx_LocalBuf_ND __pyx_pybuffernd_weights_out; + __Pyx_Buffer __pyx_pybuffer_weights_out; + __Pyx_LocalBuf_ND __pyx_pybuffernd_x_out; + __Pyx_Buffer __pyx_pybuffer_x_out; + __Pyx_LocalBuf_ND __pyx_pybuffernd_y; + __Pyx_Buffer __pyx_pybuffer_y; + __Pyx_LocalBuf_ND __pyx_pybuffernd_y_out; + __Pyx_Buffer __pyx_pybuffer_y_out; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyArrayObject *__pyx_t_8 = NULL; + PyArrayObject *__pyx_t_9 = NULL; + PyArrayObject *__pyx_t_10 = NULL; + long __pyx_t_11; + int __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + int __pyx_t_17; + int __pyx_t_18; + int __pyx_t_19; + int __pyx_t_20; + int __pyx_t_21; + int __pyx_t_22; + int __pyx_t_23; + int __pyx_t_24; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_make_unique", 0); + __pyx_pybuffer_y_out.pybuffer.buf = NULL; + __pyx_pybuffer_y_out.refcount = 0; + __pyx_pybuffernd_y_out.data = NULL; + __pyx_pybuffernd_y_out.rcbuffer = &__pyx_pybuffer_y_out; + __pyx_pybuffer_x_out.pybuffer.buf = NULL; + __pyx_pybuffer_x_out.refcount = 0; + __pyx_pybuffernd_x_out.data = NULL; + __pyx_pybuffernd_x_out.rcbuffer = &__pyx_pybuffer_x_out; + __pyx_pybuffer_weights_out.pybuffer.buf = NULL; + __pyx_pybuffer_weights_out.refcount = 0; + __pyx_pybuffernd_weights_out.data = NULL; + __pyx_pybuffernd_weights_out.rcbuffer = &__pyx_pybuffer_weights_out; + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + __pyx_pybuffer_y.pybuffer.buf = NULL; + __pyx_pybuffer_y.refcount = 0; + __pyx_pybuffernd_y.data = NULL; + __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; + __pyx_pybuffer_sample_weights.pybuffer.buf = NULL; + __pyx_pybuffer_sample_weights.refcount = 0; + __pyx_pybuffernd_sample_weights.data = NULL; + __pyx_pybuffernd_sample_weights.rcbuffer = &__pyx_pybuffer_sample_weights; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weights.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weights, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_sample_weights.diminfo[0].strides = __pyx_pybuffernd_sample_weights.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weights.diminfo[0].shape = __pyx_pybuffernd_sample_weights.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/_isotonic.pyx":88 + * Assumes that X is ordered, so that all duplicates follow each other. + * """ + * unique_values = len(np.unique(X)) # <<<<<<<<<<<<<< + * if unique_values == len(X): + * return X, y, sample_weights + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_unique); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (!__pyx_t_2) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, ((PyObject *)__pyx_v_X)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = NULL; + __Pyx_INCREF(((PyObject *)__pyx_v_X)); + PyTuple_SET_ITEM(__pyx_t_4, 0+1, ((PyObject *)__pyx_v_X)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_X)); + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = PyObject_Length(__pyx_t_1); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_unique_values = __pyx_t_5; + + /* "sklearn/_isotonic.pyx":89 + * """ + * unique_values = len(np.unique(X)) + * if unique_values == len(X): # <<<<<<<<<<<<<< + * return X, y, sample_weights + * cdef np.ndarray[dtype=np.float64_t] y_out = np.empty(unique_values) + */ + __pyx_t_5 = PyObject_Length(((PyObject *)__pyx_v_X)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((__pyx_v_unique_values == __pyx_t_5) != 0); + if (__pyx_t_6) { + + /* "sklearn/_isotonic.pyx":90 + * unique_values = len(np.unique(X)) + * if unique_values == len(X): + * return X, y, sample_weights # <<<<<<<<<<<<<< + * cdef np.ndarray[dtype=np.float64_t] y_out = np.empty(unique_values) + * cdef np.ndarray[dtype=np.float64_t] x_out = np.empty(unique_values) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_X)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_X)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_X)); + __Pyx_INCREF(((PyObject *)__pyx_v_y)); + PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_y)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); + __Pyx_INCREF(((PyObject *)__pyx_v_sample_weights)); + PyTuple_SET_ITEM(__pyx_t_1, 2, ((PyObject *)__pyx_v_sample_weights)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_sample_weights)); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + } + + /* "sklearn/_isotonic.pyx":91 + * if unique_values == len(X): + * return X, y, sample_weights + * cdef np.ndarray[dtype=np.float64_t] y_out = np.empty(unique_values) # <<<<<<<<<<<<<< + * cdef np.ndarray[dtype=np.float64_t] x_out = np.empty(unique_values) + * cdef np.ndarray[dtype=np.float64_t] weights_out = np.empty(unique_values) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_unique_values); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + } + } + if (!__pyx_t_2) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_7 = PyTuple_New(1+1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = NULL; + PyTuple_SET_ITEM(__pyx_t_7, 0+1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_y_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_y_out.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_y_out.diminfo[0].strides = __pyx_pybuffernd_y_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y_out.diminfo[0].shape = __pyx_pybuffernd_y_out.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_8 = 0; + __pyx_v_y_out = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/_isotonic.pyx":92 + * return X, y, sample_weights + * cdef np.ndarray[dtype=np.float64_t] y_out = np.empty(unique_values) + * cdef np.ndarray[dtype=np.float64_t] x_out = np.empty(unique_values) # <<<<<<<<<<<<<< + * cdef np.ndarray[dtype=np.float64_t] weights_out = np.empty(unique_values) + * + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_unique_values); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_7); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_7, function); + } + } + if (!__pyx_t_3) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_2 = PyTuple_New(1+1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = NULL; + PyTuple_SET_ITEM(__pyx_t_2, 0+1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_9, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_x_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_x_out.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_x_out.diminfo[0].strides = __pyx_pybuffernd_x_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x_out.diminfo[0].shape = __pyx_pybuffernd_x_out.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_9 = 0; + __pyx_v_x_out = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/_isotonic.pyx":93 + * cdef np.ndarray[dtype=np.float64_t] y_out = np.empty(unique_values) + * cdef np.ndarray[dtype=np.float64_t] x_out = np.empty(unique_values) + * cdef np.ndarray[dtype=np.float64_t] weights_out = np.empty(unique_values) # <<<<<<<<<<<<<< + * + * cdef float current_x = X[0] + */ + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyInt_FromSsize_t(__pyx_v_unique_values); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (!__pyx_t_4) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_7); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_3 = PyTuple_New(1+1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + PyTuple_SET_ITEM(__pyx_t_3, 0+1, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weights_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_weights_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_weights_out.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_weights_out.diminfo[0].strides = __pyx_pybuffernd_weights_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weights_out.diminfo[0].shape = __pyx_pybuffernd_weights_out.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_10 = 0; + __pyx_v_weights_out = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/_isotonic.pyx":95 + * cdef np.ndarray[dtype=np.float64_t] weights_out = np.empty(unique_values) + * + * cdef float current_x = X[0] # <<<<<<<<<<<<<< + * cdef float current_y = 0 + * cdef float current_weight = 0 + */ + __pyx_t_11 = 0; + __pyx_v_current_x = (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_X.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_X.diminfo[0].strides)); + + /* "sklearn/_isotonic.pyx":96 + * + * cdef float current_x = X[0] + * cdef float current_y = 0 # <<<<<<<<<<<<<< + * cdef float current_weight = 0 + * cdef float y_old = 0 + */ + __pyx_v_current_y = 0.0; + + /* "sklearn/_isotonic.pyx":97 + * cdef float current_x = X[0] + * cdef float current_y = 0 + * cdef float current_weight = 0 # <<<<<<<<<<<<<< + * cdef float y_old = 0 + * cdef int i = 0 + */ + __pyx_v_current_weight = 0.0; + + /* "sklearn/_isotonic.pyx":98 + * cdef float current_y = 0 + * cdef float current_weight = 0 + * cdef float y_old = 0 # <<<<<<<<<<<<<< + * cdef int i = 0 + * cdef int current_count = 0 + */ + __pyx_v_y_old = 0.0; + + /* "sklearn/_isotonic.pyx":99 + * cdef float current_weight = 0 + * cdef float y_old = 0 + * cdef int i = 0 # <<<<<<<<<<<<<< + * cdef int current_count = 0 + * cdef int j + */ + __pyx_v_i = 0; + + /* "sklearn/_isotonic.pyx":100 + * cdef float y_old = 0 + * cdef int i = 0 + * cdef int current_count = 0 # <<<<<<<<<<<<<< + * cdef int j + * cdef float x + */ + __pyx_v_current_count = 0; + + /* "sklearn/_isotonic.pyx":103 + * cdef int j + * cdef float x + * cdef int n_samples = len(X) # <<<<<<<<<<<<<< + * for j in range(n_samples): + * x = X[j] + */ + __pyx_t_5 = PyObject_Length(((PyObject *)__pyx_v_X)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_n_samples = __pyx_t_5; + + /* "sklearn/_isotonic.pyx":104 + * cdef float x + * cdef int n_samples = len(X) + * for j in range(n_samples): # <<<<<<<<<<<<<< + * x = X[j] + * if x != current_x: + */ + __pyx_t_12 = __pyx_v_n_samples; + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_j = __pyx_t_13; + + /* "sklearn/_isotonic.pyx":105 + * cdef int n_samples = len(X) + * for j in range(n_samples): + * x = X[j] # <<<<<<<<<<<<<< + * if x != current_x: + * # next unique value + */ + __pyx_t_14 = __pyx_v_j; + __pyx_v_x = (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_X.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_X.diminfo[0].strides)); + + /* "sklearn/_isotonic.pyx":106 + * for j in range(n_samples): + * x = X[j] + * if x != current_x: # <<<<<<<<<<<<<< + * # next unique value + * x_out[i] = current_x + */ + __pyx_t_6 = ((__pyx_v_x != __pyx_v_current_x) != 0); + if (__pyx_t_6) { + + /* "sklearn/_isotonic.pyx":108 + * if x != current_x: + * # next unique value + * x_out[i] = current_x # <<<<<<<<<<<<<< + * weights_out[i] = current_weight / current_count + * y_out[i] = current_y / current_weight + */ + __pyx_t_15 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_x_out.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_x_out.diminfo[0].strides) = __pyx_v_current_x; + + /* "sklearn/_isotonic.pyx":109 + * # next unique value + * x_out[i] = current_x + * weights_out[i] = current_weight / current_count # <<<<<<<<<<<<<< + * y_out[i] = current_y / current_weight + * i += 1 + */ + __pyx_t_16 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_weights_out.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_weights_out.diminfo[0].strides) = (__pyx_v_current_weight / __pyx_v_current_count); + + /* "sklearn/_isotonic.pyx":110 + * x_out[i] = current_x + * weights_out[i] = current_weight / current_count + * y_out[i] = current_y / current_weight # <<<<<<<<<<<<<< + * i += 1 + * current_x = x + */ + __pyx_t_17 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y_out.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_y_out.diminfo[0].strides) = (__pyx_v_current_y / __pyx_v_current_weight); + + /* "sklearn/_isotonic.pyx":111 + * weights_out[i] = current_weight / current_count + * y_out[i] = current_y / current_weight + * i += 1 # <<<<<<<<<<<<<< + * current_x = x + * current_weight = sample_weights[j] + */ + __pyx_v_i = (__pyx_v_i + 1); + + /* "sklearn/_isotonic.pyx":112 + * y_out[i] = current_y / current_weight + * i += 1 + * current_x = x # <<<<<<<<<<<<<< + * current_weight = sample_weights[j] + * current_y = y[j] * sample_weights[j] + */ + __pyx_v_current_x = __pyx_v_x; + + /* "sklearn/_isotonic.pyx":113 + * i += 1 + * current_x = x + * current_weight = sample_weights[j] # <<<<<<<<<<<<<< + * current_y = y[j] * sample_weights[j] + * current_count = 1 + */ + __pyx_t_18 = __pyx_v_j; + __pyx_v_current_weight = (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_sample_weights.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_sample_weights.diminfo[0].strides)); + + /* "sklearn/_isotonic.pyx":114 + * current_x = x + * current_weight = sample_weights[j] + * current_y = y[j] * sample_weights[j] # <<<<<<<<<<<<<< + * current_count = 1 + * else: + */ + __pyx_t_19 = __pyx_v_j; + __pyx_t_20 = __pyx_v_j; + __pyx_v_current_y = ((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_y.diminfo[0].strides)) * (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_sample_weights.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_sample_weights.diminfo[0].strides))); + + /* "sklearn/_isotonic.pyx":115 + * current_weight = sample_weights[j] + * current_y = y[j] * sample_weights[j] + * current_count = 1 # <<<<<<<<<<<<<< + * else: + * current_weight += sample_weights[j] + */ + __pyx_v_current_count = 1; + goto __pyx_L6; + } + /*else*/ { + + /* "sklearn/_isotonic.pyx":117 + * current_count = 1 + * else: + * current_weight += sample_weights[j] # <<<<<<<<<<<<<< + * current_y += y[j] * sample_weights[j] + * current_count += 1 + */ + __pyx_t_21 = __pyx_v_j; + __pyx_v_current_weight = (__pyx_v_current_weight + (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_sample_weights.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_sample_weights.diminfo[0].strides))); + + /* "sklearn/_isotonic.pyx":118 + * else: + * current_weight += sample_weights[j] + * current_y += y[j] * sample_weights[j] # <<<<<<<<<<<<<< + * current_count += 1 + * + */ + __pyx_t_22 = __pyx_v_j; + __pyx_t_23 = __pyx_v_j; + __pyx_v_current_y = (__pyx_v_current_y + ((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_y.diminfo[0].strides)) * (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_sample_weights.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_sample_weights.diminfo[0].strides)))); + + /* "sklearn/_isotonic.pyx":119 + * current_weight += sample_weights[j] + * current_y += y[j] * sample_weights[j] + * current_count += 1 # <<<<<<<<<<<<<< + * + * x_out[i] = current_x + */ + __pyx_v_current_count = (__pyx_v_current_count + 1); + } + __pyx_L6:; + } + + /* "sklearn/_isotonic.pyx":121 + * current_count += 1 + * + * x_out[i] = current_x # <<<<<<<<<<<<<< + * weights_out[i] = current_weight / current_count + * y_out[i] = current_y / current_weight + */ + __pyx_t_12 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_x_out.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_x_out.diminfo[0].strides) = __pyx_v_current_x; + + /* "sklearn/_isotonic.pyx":122 + * + * x_out[i] = current_x + * weights_out[i] = current_weight / current_count # <<<<<<<<<<<<<< + * y_out[i] = current_y / current_weight + * return x_out, y_out, weights_out + */ + __pyx_t_13 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_weights_out.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_weights_out.diminfo[0].strides) = (__pyx_v_current_weight / __pyx_v_current_count); + + /* "sklearn/_isotonic.pyx":123 + * x_out[i] = current_x + * weights_out[i] = current_weight / current_count + * y_out[i] = current_y / current_weight # <<<<<<<<<<<<<< + * return x_out, y_out, weights_out + */ + __pyx_t_24 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y_out.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_y_out.diminfo[0].strides) = (__pyx_v_current_y / __pyx_v_current_weight); + + /* "sklearn/_isotonic.pyx":124 + * weights_out[i] = current_weight / current_count + * y_out[i] = current_y / current_weight + * return x_out, y_out, weights_out # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_x_out)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_x_out)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_x_out)); + __Pyx_INCREF(((PyObject *)__pyx_v_y_out)); + PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_y_out)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_y_out)); + __Pyx_INCREF(((PyObject *)__pyx_v_weights_out)); + PyTuple_SET_ITEM(__pyx_t_1, 2, ((PyObject *)__pyx_v_weights_out)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_weights_out)); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/_isotonic.pyx":77 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _make_unique(np.ndarray[dtype=np.float64_t] X, # <<<<<<<<<<<<<< + * np.ndarray[dtype=np.float64_t] y, + * np.ndarray[dtype=np.float64_t] sample_weights): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_weights.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weights_out.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_out.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y_out.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn._isotonic._make_unique", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_weights.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weights_out.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_out.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y_out.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_y_out); + __Pyx_XDECREF((PyObject *)__pyx_v_x_out); + __Pyx_XDECREF((PyObject *)__pyx_v_weights_out); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L6_bool_binop_done; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L6_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L9_bool_binop_done; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L9_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_1 = (__pyx_v_copy_shape != 0); + if (__pyx_t_1) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_4 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L11; + } + /*else*/ { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L11:; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L15_bool_binop_done; + } + __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L15_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L14; + } + /*else*/ { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":251 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L14:; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_4 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_4; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); + if (!__pyx_t_2) { + goto __pyx_L20_next_or; + } else { + } + __pyx_t_2 = (__pyx_v_little_endian != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_L20_next_or:; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L19_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< + * info.format + _buffer_format_string_len, + * &offset) + */ + __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_7; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + long __pyx_t_8; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); + __pyx_t_3 = 0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); + __pyx_t_4 = 0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":798 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); + if (__pyx_t_6) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (!__pyx_t_7) { + goto __pyx_L8_next_or; + } else { + } + __pyx_t_7 = (__pyx_v_little_endian != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_L8_next_or:; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L7_bool_binop_done:; + if (__pyx_t_6) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":813 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_6) break; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_6) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":821 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_6) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L15; + } + /*else*/ { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L15:; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + /*else*/ { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + } + __pyx_L13:; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":968 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":971 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":972 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":973 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":974 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":977 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":978 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + /*else*/ { + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":980 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + "_isotonic", + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_n_s_current_count, __pyx_k_current_count, sizeof(__pyx_k_current_count), 0, 0, 1, 1}, + {&__pyx_n_s_current_weight, __pyx_k_current_weight, sizeof(__pyx_k_current_weight), 0, 0, 1, 1}, + {&__pyx_n_s_current_x, __pyx_k_current_x, sizeof(__pyx_k_current_x), 0, 0, 1, 1}, + {&__pyx_n_s_current_y, __pyx_k_current_y, sizeof(__pyx_k_current_y), 0, 0, 1, 1}, + {&__pyx_n_s_denominator, __pyx_k_denominator, sizeof(__pyx_k_denominator), 0, 0, 1, 1}, + {&__pyx_n_s_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 0, 0, 1, 1}, + {&__pyx_kp_s_home_andy_checkout_scikit_learn, __pyx_k_home_andy_checkout_scikit_learn, sizeof(__pyx_k_home_andy_checkout_scikit_learn), 0, 0, 1, 0}, + {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_isotonic_regression, __pyx_k_isotonic_regression, sizeof(__pyx_k_isotonic_regression), 0, 0, 1, 1}, + {&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, + {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_make_unique, __pyx_k_make_unique, sizeof(__pyx_k_make_unique), 0, 0, 1, 1}, + {&__pyx_n_s_n, __pyx_k_n, sizeof(__pyx_k_n), 0, 0, 1, 1}, + {&__pyx_n_s_n_samples, __pyx_k_n_samples, sizeof(__pyx_k_n_samples), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numerator, __pyx_k_numerator, sizeof(__pyx_k_numerator), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_pooled, __pyx_k_pooled, sizeof(__pyx_k_pooled), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_ratio, __pyx_k_ratio, sizeof(__pyx_k_ratio), 0, 0, 1, 1}, + {&__pyx_n_s_sample_weights, __pyx_k_sample_weights, sizeof(__pyx_k_sample_weights), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn__isotonic, __pyx_k_sklearn__isotonic, sizeof(__pyx_k_sklearn__isotonic), 0, 0, 1, 1}, + {&__pyx_n_s_solution, __pyx_k_solution, sizeof(__pyx_k_solution), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_unique, __pyx_k_unique, sizeof(__pyx_k_unique), 0, 0, 1, 1}, + {&__pyx_n_s_unique_values, __pyx_k_unique_values, sizeof(__pyx_k_unique_values), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_weight, __pyx_k_weight, sizeof(__pyx_k_weight), 0, 0, 1, 1}, + {&__pyx_n_s_weights_out, __pyx_k_weights_out, sizeof(__pyx_k_weights_out), 0, 0, 1, 1}, + {&__pyx_n_s_x, __pyx_k_x, sizeof(__pyx_k_x), 0, 0, 1, 1}, + {&__pyx_n_s_x_out, __pyx_k_x_out, sizeof(__pyx_k_x_out), 0, 0, 1, 1}, + {&__pyx_n_s_y, __pyx_k_y, sizeof(__pyx_k_y), 0, 0, 1, 1}, + {&__pyx_n_s_y_old, __pyx_k_y_old, sizeof(__pyx_k_y_old), 0, 0, 1, 1}, + {&__pyx_n_s_y_out, __pyx_k_y_out, sizeof(__pyx_k_y_out), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + + /* "sklearn/_isotonic.pyx":19 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _isotonic_regression(np.ndarray[DOUBLE, ndim=1] y, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=1] weight, + * np.ndarray[DOUBLE, ndim=1] solution): + */ + __pyx_tuple__7 = PyTuple_Pack(11, __pyx_n_s_y, __pyx_n_s_weight, __pyx_n_s_solution, __pyx_n_s_numerator, __pyx_n_s_denominator, __pyx_n_s_ratio, __pyx_n_s_i, __pyx_n_s_pooled, __pyx_n_s_n, __pyx_n_s_k, __pyx_n_s_j); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + __pyx_codeobj__8 = (PyObject*)__Pyx_PyCode_New(3, 0, 11, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__7, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_andy_checkout_scikit_learn, __pyx_n_s_isotonic_regression, 19, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/_isotonic.pyx":77 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _make_unique(np.ndarray[dtype=np.float64_t] X, # <<<<<<<<<<<<<< + * np.ndarray[dtype=np.float64_t] y, + * np.ndarray[dtype=np.float64_t] sample_weights): + */ + __pyx_tuple__9 = PyTuple_Pack(16, __pyx_n_s_X, __pyx_n_s_y, __pyx_n_s_sample_weights, __pyx_n_s_unique_values, __pyx_n_s_y_out, __pyx_n_s_x_out, __pyx_n_s_weights_out, __pyx_n_s_current_x, __pyx_n_s_current_y, __pyx_n_s_current_weight, __pyx_n_s_y_old, __pyx_n_s_i, __pyx_n_s_current_count, __pyx_n_s_j, __pyx_n_s_x, __pyx_n_s_n_samples); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + __pyx_codeobj__10 = (PyObject*)__Pyx_PyCode_New(3, 0, 16, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__9, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_andy_checkout_scikit_learn, __pyx_n_s_make_unique, 77, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC init_isotonic(void); /*proto*/ +PyMODINIT_FUNC init_isotonic(void) +#else +PyMODINIT_FUNC PyInit__isotonic(void); /*proto*/ +PyMODINIT_FUNC PyInit__isotonic(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__isotonic(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4("_isotonic", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn___isotonic) { + if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn._isotonic")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn._isotonic", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/_isotonic.pyx":7 + * # pool at each step. + * + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * cimport cython + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/_isotonic.pyx":13 + * ctypedef np.float64_t DOUBLE + * + * np.import_array() # <<<<<<<<<<<<<< + * + * + */ + import_array(); + + /* "sklearn/_isotonic.pyx":19 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _isotonic_regression(np.ndarray[DOUBLE, ndim=1] y, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=1] weight, + * np.ndarray[DOUBLE, ndim=1] solution): + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9_isotonic_1_isotonic_regression, NULL, __pyx_n_s_sklearn__isotonic); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_isotonic_regression, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/_isotonic.pyx":77 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _make_unique(np.ndarray[dtype=np.float64_t] X, # <<<<<<<<<<<<<< + * np.ndarray[dtype=np.float64_t] y, + * np.ndarray[dtype=np.float64_t] sample_weights): + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9_isotonic_3_make_unique, NULL, __pyx_n_s_sklearn__isotonic); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_make_unique, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/_isotonic.pyx":1 + * # Author: Nelle Varoquaux, Andrew Tulloch # <<<<<<<<<<<<<< + * + * # Uses the pool adjacent violators algorithm (PAVA), with the + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "../../../.local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + if (__pyx_m) { + if (__pyx_d) { + __Pyx_AddTraceback("init sklearn._isotonic", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn._isotonic"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(PyObject_TypeCheck(obj, type))) return 1; + } + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case '\r': + case '\n': + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; + } + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (likely(result)) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = PyCFunction_GET_FUNCTION(func); + self = PyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *result; + PyObject *args = PyTuple_New(1); + if (unlikely(!args)) return NULL; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, arg); + result = __Pyx_PyObject_Call(func, args, NULL); + Py_DECREF(args); + return result; +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { +#ifdef __Pyx_CyFunction_USED + if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { +#else + if (likely(PyCFunction_Check(func))) { +#endif + if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { + return __Pyx_PyObject_CallMethO(func, arg); + } + } + return __Pyx__PyObject_CallOneArg(func, arg); +} +#else +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject* args = PyTuple_Pack(1, arg); + return (likely(args)) ? __Pyx_PyObject_Call(func, args, NULL) : NULL; +} +#endif + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + if (PyType_Check(type)) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if CYTHON_COMPILING_IN_PYPY + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(tmp_type, tmp_value, tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#else + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + Py_DECREF(obj); + view->obj = NULL; +} +#endif + + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } +} + +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ + { \ + func_type value = func_value; \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + if (is_unsigned && unlikely(value < zero)) \ + goto raise_neg_overflow; \ + else \ + goto raise_overflow; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong(x)) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); + } +} + +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong(x)) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + return PyErr_WarnEx(NULL, message, 1); + } + return 0; +} + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + } + else if ((size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else + if (__Pyx_PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif + } else +#endif +#if !CYTHON_COMPILING_IN_PYPY + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_MAJOR_VERSION < 3 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%.4s__ returned non-%.4s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { + return PyInt_FromSize_t(ival); +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/_isotonic.pyx b/sklearn/_isotonic.pyx new file mode 100644 index 0000000000000..ca3f85b1aeb6c --- /dev/null +++ b/sklearn/_isotonic.pyx @@ -0,0 +1,124 @@ +# Author: Nelle Varoquaux, Andrew Tulloch + +# Uses the pool adjacent violators algorithm (PAVA), with the +# enhancement of searching for the longest decreasing subsequence to +# pool at each step. + +import numpy as np +cimport numpy as np +cimport cython + +ctypedef np.float64_t DOUBLE + +np.import_array() + + +@cython.boundscheck(False) +@cython.wraparound(False) +@cython.cdivision(True) +def _isotonic_regression(np.ndarray[DOUBLE, ndim=1] y, + np.ndarray[DOUBLE, ndim=1] weight, + np.ndarray[DOUBLE, ndim=1] solution): + cdef: + DOUBLE numerator, denominator, ratio + Py_ssize_t i, pooled, n, k + + n = y.shape[0] + # The algorithm proceeds by iteratively updating the solution + # array. + + # TODO - should we just pass in a pre-copied solution + # array and mutate that? + for i in range(n): + solution[i] = y[i] + + if n <= 1: + return solution + + n -= 1 + while 1: + # repeat until there are no more adjacent violators. + i = 0 + pooled = 0 + while i < n: + k = i + while k < n and solution[k] >= solution[k + 1]: + k += 1 + if solution[i] != solution[k]: + # solution[i:k + 1] is a decreasing subsequence, so + # replace each point in the subsequence with the + # weighted average of the subsequence. + + # TODO: explore replacing each subsequence with a + # _single_ weighted point, and reconstruct the whole + # sequence from the sequence of collapsed points. + # Theoretically should reduce running time, though + # initial experiments weren't promising. + numerator = 0.0 + denominator = 0.0 + for j in range(i, k + 1): + numerator += solution[j] * weight[j] + denominator += weight[j] + ratio = numerator / denominator + for j in range(i, k + 1): + solution[j] = ratio + pooled = 1 + i = k + 1 + # Check for convergence + if pooled == 0: + break + + return solution + + +@cython.boundscheck(False) +@cython.wraparound(False) +@cython.cdivision(True) +def _make_unique(np.ndarray[dtype=np.float64_t] X, + np.ndarray[dtype=np.float64_t] y, + np.ndarray[dtype=np.float64_t] sample_weights): + """Average targets for duplicate X, drop duplicates. + + Aggregates duplicate X values into a single X value where + the target y is a (sample_weighted) average of the individual + targets. + + Assumes that X is ordered, so that all duplicates follow each other. + """ + unique_values = len(np.unique(X)) + if unique_values == len(X): + return X, y, sample_weights + cdef np.ndarray[dtype=np.float64_t] y_out = np.empty(unique_values) + cdef np.ndarray[dtype=np.float64_t] x_out = np.empty(unique_values) + cdef np.ndarray[dtype=np.float64_t] weights_out = np.empty(unique_values) + + cdef float current_x = X[0] + cdef float current_y = 0 + cdef float current_weight = 0 + cdef float y_old = 0 + cdef int i = 0 + cdef int current_count = 0 + cdef int j + cdef float x + cdef int n_samples = len(X) + for j in range(n_samples): + x = X[j] + if x != current_x: + # next unique value + x_out[i] = current_x + weights_out[i] = current_weight / current_count + y_out[i] = current_y / current_weight + i += 1 + current_x = x + current_weight = sample_weights[j] + current_y = y[j] * sample_weights[j] + current_count = 1 + else: + current_weight += sample_weights[j] + current_y += y[j] * sample_weights[j] + current_count += 1 + + x_out[i] = current_x + weights_out[i] = current_weight / current_count + y_out[i] = current_y / current_weight + return x_out, y_out, weights_out diff --git a/sklearn/base.py b/sklearn/base.py index 6524736a3e966..c77e5fb969506 100644 --- a/sklearn/base.py +++ b/sklearn/base.py @@ -1,13 +1,14 @@ -"""Base class for all estimators.""" +"""Base classes for all estimators.""" # Author: Gael Varoquaux -# License: BSD Style +# License: BSD 3 clause import copy import inspect +import warnings + import numpy as np from scipy import sparse - -from .metrics import r2_score +from .externals import six ############################################################################### @@ -37,12 +38,12 @@ def clone(estimator, safe=True): return copy.deepcopy(estimator) else: raise TypeError("Cannot clone object '%s' (type %s): " - "it does not seem to be a scikit-learn estimator as " - "it does not implement a 'get_params' methods." - % (repr(estimator), type(estimator))) + "it does not seem to be a scikit-learn estimator " + "it does not implement a 'get_params' methods." + % (repr(estimator), type(estimator))) klass = estimator.__class__ new_object_params = estimator.get_params(deep=False) - for name, param in new_object_params.iteritems(): + for name, param in six.iteritems(new_object_params): new_object_params[name] = clone(param, safe=False) new_object = klass(**new_object_params) params_set = new_object.get_params(deep=False) @@ -91,7 +92,8 @@ def clone(estimator, safe=True): equality_test = new_object_params[name] == params_set[name] if not equality_test: raise RuntimeError('Cannot clone object %s, as the constructor ' - 'does not seem to set parameter %s' % (estimator, name)) + 'does not seem to set parameter %s' % + (estimator, name)) return new_object @@ -119,7 +121,7 @@ def _pprint(params, offset=0, printer=repr): params_list = list() this_line_length = offset line_sep = ',\n' + (1 + offset // 2) * ' ' - for i, (k, v) in enumerate(sorted(params.iteritems())): + for i, (k, v) in enumerate(sorted(six.iteritems(params))): if type(v) is float: # use str for representing floating point numbers # this way we get consistent representation across @@ -131,8 +133,7 @@ def _pprint(params, offset=0, printer=repr): if len(this_repr) > 500: this_repr = this_repr[:300] + '...' + this_repr[-100:] if i > 0: - if (this_line_length + len(this_repr) >= 75 - or '\n' in this_repr): + if (this_line_length + len(this_repr) >= 75 or '\n' in this_repr): params_list.append(line_sep) this_line_length = len(line_sep) else: @@ -155,47 +156,67 @@ class BaseEstimator(object): Notes ----- All estimators should specify all the parameters that can be set - at the class level in their __init__ as explicit keyword - arguments (no *args, **kwargs). + at the class level in their ``__init__`` as explicit keyword + arguments (no ``*args`` or ``**kwargs``). """ @classmethod def _get_param_names(cls): """Get parameter names for the estimator""" - try: - # fetch the constructor or the original constructor before - # deprecation wrapping if any - init = getattr(cls.__init__, 'deprecated_original', cls.__init__) - - # introspect the constructor arguments to find the model parameters - # to represent - args, varargs, kw, default = inspect.getargspec(init) - if not varargs is None: - raise RuntimeError('scikit learn estimators should always ' - 'specify their parameters in the signature of ' - 'their init (no varargs).') - # Remove 'self' - # XXX: This is going to fail if the init is a staticmethod, but - # who would do this? - args.pop(0) - except TypeError: - # No explicit __init__ - args = [] + # fetch the constructor or the original constructor before + # deprecation wrapping if any + init = getattr(cls.__init__, 'deprecated_original', cls.__init__) + if init is object.__init__: + # No explicit constructor to introspect + return [] + + # introspect the constructor arguments to find the model parameters + # to represent + args, varargs, kw, default = inspect.getargspec(init) + if varargs is not None: + raise RuntimeError("scikit-learn estimators should always " + "specify their parameters in the signature" + " of their __init__ (no varargs)." + " %s doesn't follow this convention." + % (cls, )) + # Remove 'self' + # XXX: This is going to fail if the init is a staticmethod, but + # who would do this? + args.pop(0) args.sort() return args def get_params(self, deep=True): - """Get parameters for the estimator + """Get parameters for this estimator. Parameters ---------- deep: boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. + + Returns + ------- + params : mapping of string to any + Parameter names mapped to their values. """ out = dict() for key in self._get_param_names(): - value = getattr(self, key, None) + # We need deprecation warnings to always be on in order to + # catch deprecated param values. + # This is set in utils/__init__.py but it gets overwritten + # when running under python3 somehow. + warnings.simplefilter("always", DeprecationWarning) + try: + with warnings.catch_warnings(record=True) as w: + value = getattr(self, key, None) + if len(w) and w[0].category == DeprecationWarning: + # if the parameter is deprecated, don't show it + continue + finally: + warnings.filters.pop(0) + + # XXX: should we rather test if instance of estimator? if deep and hasattr(value, 'get_params'): deep_items = value.get_params().items() out.update((key + '__' + k, val) for k, val in deep_items) @@ -203,7 +224,7 @@ def get_params(self, deep=True): return out def set_params(self, **params): - """Set the parameters of the estimator. + """Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as pipelines). The former have parameters of the form @@ -216,110 +237,103 @@ def set_params(self, **params): """ if not params: # Simple optimisation to gain speed (inspect is slow) - return + return self valid_params = self.get_params(deep=True) - for key, value in params.iteritems(): + for key, value in six.iteritems(params): split = key.split('__', 1) if len(split) > 1: # nested objects case name, sub_name = split if not name in valid_params: - raise ValueError('Invalid parameter %s for estimator %s' - % (name, self)) + raise ValueError('Invalid parameter %s for estimator %s' % + (name, self)) sub_object = valid_params[name] - if not hasattr(sub_object, 'get_params'): - raise TypeError( - 'Parameter %s of %s is not an estimator, cannot set ' - 'sub parameter %s' % - (sub_name, self.__class__.__name__, sub_name) - ) sub_object.set_params(**{sub_name: value}) else: # simple objects case if not key in valid_params: raise ValueError('Invalid parameter %s ' 'for estimator %s' - % (key, self.__class__.__name__)) + % (key, self.__class__.__name__)) setattr(self, key, value) return self def __repr__(self): class_name = self.__class__.__name__ - return '%s(%s)' % ( - class_name, - _pprint(self.get_params(deep=False), - offset=len(class_name), - ), - ) - - def __str__(self): - class_name = self.__class__.__name__ - return '%s(%s)' % ( - class_name, - _pprint(self.get_params(deep=True), - offset=len(class_name), - printer=str, - ), - ) + return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False), + offset=len(class_name),),) ############################################################################### class ClassifierMixin(object): - """Mixin class for all classifiers in scikit-learn""" + """Mixin class for all classifiers in scikit-learn.""" - def score(self, X, y): + def score(self, X, y, sample_weight=None): """Returns the mean accuracy on the given test data and labels. + In multi-label classification, this is the subset accuracy + which is a harsh metric since you require for each sample that + each label set be correctly predicted. + Parameters ---------- - X : array-like, shape = [n_samples, n_features] - Training set. + X : array-like, shape = (n_samples, n_features) + Test samples. + + y : array-like, shape = (n_samples) or (n_samples, n_outputs) + True labels for X. - y : array-like, shape = [n_samples] - Labels for X. + sample_weight : array-like, shape = [n_samples], optional + Sample weights. Returns ------- - z : float + score : float + Mean accuracy of self.predict(X) wrt. y. """ - return np.mean(self.predict(X) == y) + from .metrics import accuracy_score + return accuracy_score(y, self.predict(X), sample_weight=sample_weight) ############################################################################### class RegressorMixin(object): - """Mixin class for all regression estimators in scikit-learn""" + """Mixin class for all regression estimators in scikit-learn.""" - def score(self, X, y): + def score(self, X, y, sample_weight=None): """Returns the coefficient of determination R^2 of the prediction. - The coefficient R^2 is defined as (1 - u/v), where u is the - regression sum of squares ((y - y_pred) ** 2).sum() and v is the - residual sum of squares ((y_true - y_true.mean()) ** 2).sum(). + The coefficient R^2 is defined as (1 - u/v), where u is the regression + sum of squares ((y_true - y_pred) ** 2).sum() and v is the residual + sum of squares ((y_true - y_true.mean()) ** 2).sum(). Best possible score is 1.0, lower values are worse. - Parameters ---------- - X : array-like, shape = [n_samples, n_features] - Training set. + X : array-like, shape = (n_samples, n_features) + Test samples. + + y : array-like, shape = (n_samples) or (n_samples, n_outputs) + True values for X. - y : array-like, shape = [n_samples] + sample_weight : array-like, shape = [n_samples], optional + Sample weights. Returns ------- - z : float + score : float + R^2 of self.predict(X) wrt. y. """ - return r2_score(y, self.predict(X)) + + from .metrics import r2_score + return r2_score(y, self.predict(X), sample_weight=sample_weight) ############################################################################### class ClusterMixin(object): - """Mixin class for all cluster estimators in scikit-learn""" + """Mixin class for all cluster estimators in scikit-learn.""" def fit_predict(self, X, y=None): """Performs clustering on X and returns cluster labels. - This is a non-optimized default implementation. - Parameters ---------- X : ndarray, shape (n_samples, n_features) @@ -330,16 +344,70 @@ def fit_predict(self, X, y=None): y : ndarray, shape (n_samples,) cluster labels """ + # non-optimized default implementation; override when a better + # method is possible for a given clustering algorithm self.fit(X) return self.labels_ +class BiclusterMixin(object): + """Mixin class for all bicluster estimators in scikit-learn""" + + @property + def biclusters_(self): + """Convenient way to get row and column indicators together. + + Returns the ``rows_`` and ``columns_`` members. + """ + return self.rows_, self.columns_ + + def get_indices(self, i): + """Row and column indices of the i'th bicluster. + + Only works if ``rows_`` and ``columns_`` attributes exist. + + Returns + ------- + row_ind : np.array, dtype=np.intp + Indices of rows in the dataset that belong to the bicluster. + col_ind : np.array, dtype=np.intp + Indices of columns in the dataset that belong to the bicluster. + + """ + rows = self.rows_[i] + columns = self.columns_[i] + return np.nonzero(rows)[0], np.nonzero(columns)[0] + + def get_shape(self, i): + """Shape of the i'th bicluster. + + Returns + ------- + shape : (int, int) + Number of rows and columns (resp.) in the bicluster. + """ + indices = self.get_indices(i) + return tuple(len(i) for i in indices) + + def get_submatrix(self, i, data): + """Returns the submatrix corresponding to bicluster `i`. + + Works with sparse matrices. Only works if ``rows_`` and + ``columns_`` attributes exist. + + """ + from .utils.validation import check_array + data = check_array(data, accept_sparse='csr') + row_ind, col_ind = self.get_indices(i) + return data[row_ind[:, np.newaxis], col_ind] + + ############################################################################### class TransformerMixin(object): - """Mixin class for all transformers in scikit-learn""" + """Mixin class for all transformers in scikit-learn.""" def fit_transform(self, X, y=None, **fit_params): - """Fit to data, then transform it + """Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. @@ -357,13 +425,9 @@ def fit_transform(self, X, y=None, **fit_params): X_new : numpy array of shape [n_samples, n_features_new] Transformed array. - Notes - ----- - This method just calls fit and transform consecutively, i.e., it is not - an optimized implementation of fit_transform, unlike other transformers - such as PCA. - """ + # non-optimized default implementation; override when a better + # method is possible for a given clustering algorithm if y is None: # fit method of arity 1 (unsupervised transformation) return self.fit(X, **fit_params).transform(X) @@ -374,7 +438,7 @@ def fit_transform(self, X, y=None, **fit_params): ############################################################################### class MetaEstimatorMixin(object): - """Mixin class for all meta estimators in scikit-learn""" + """Mixin class for all meta estimators in scikit-learn.""" # this is just a tag for the moment diff --git a/sklearn/calibration.py b/sklearn/calibration.py new file mode 100644 index 0000000000000..91be2764bb9a8 --- /dev/null +++ b/sklearn/calibration.py @@ -0,0 +1,530 @@ +"""Calibration of predicted probabilities.""" + +# Author: Alexandre Gramfort +# Balazs Kegl +# Jan Hendrik Metzen +# Mathieu Blondel +# +# License: BSD 3 clause + +from __future__ import division +import inspect +import warnings + +from math import log +import numpy as np + +from scipy.optimize import fmin_bfgs + +from .base import BaseEstimator, ClassifierMixin, RegressorMixin, clone +from .preprocessing import LabelBinarizer +from .utils import check_X_y, check_array, indexable, column_or_1d +from .utils.validation import check_is_fitted +from .isotonic import IsotonicRegression +from .svm import LinearSVC +from .cross_validation import _check_cv +from .metrics.classification import _check_binary_probabilistic_predictions + + +class CalibratedClassifierCV(BaseEstimator, ClassifierMixin): + """Probability calibration with isotonic regression or sigmoid. + + With this class, the base_estimator is fit on the train set of the + cross-validation generator and the test set is used for calibration. + The probabilities for each of the folds are then averaged + for prediction. In case that cv="prefit" is passed to __init__, + it is it is assumed that base_estimator has been + fitted already and all data is used for calibration. Note that + data for fitting the classifier and for calibrating it must be disjpint. + + Parameters + ---------- + base_estimator : instance BaseEstimator + The classifier whose output decision function needs to be calibrated + to offer more accurate predict_proba outputs. If cv=prefit, the + classifier must have been fit already on data. + + method : 'sigmoid' | 'isotonic' + The method to use for calibration. Can be 'sigmoid' which + corresponds to Platt's method or 'isotonic' which is a + non-parameteric approach. It is not advised to use isotonic calibration + with too few calibration samples (<<1000) since it tends to overfit. + Use sigmoids (Platt's calibration) in this case. + + cv : integer or cross-validation generator or "prefit", optional + If an integer is passed, it is the number of folds (default 3). + Specific cross-validation objects can be passed, see + sklearn.cross_validation module for the list of possible objects. + If "prefit" is passed, it is assumed that base_estimator has been + fitted already and all data is used for calibration. + + Attributes + ---------- + classes_ : array, shape (n_classes) + The class labels. + + calibrated_classifiers_: list (len() equal to cv or 1 if cv == "prefit") + The list of calibrated classifiers, one for each crossvalidation fold, + which has been fitted on all but the validation fold and calibrated + on the validation fold. + + References + ---------- + .. [1] Obtaining calibrated probability estimates from decision trees + and naive Bayesian classifiers, B. Zadrozny & C. Elkan, ICML 2001 + + .. [2] Transforming Classifier Scores into Accurate Multiclass + Probability Estimates, B. Zadrozny & C. Elkan, (KDD 2002) + + .. [3] Probabilistic Outputs for Support Vector Machines and Comparisons to + Regularized Likelihood Methods, J. Platt, (1999) + + .. [4] Predicting Good Probabilities with Supervised Learning, + A. Niculescu-Mizil & R. Caruana, ICML 2005 + """ + def __init__(self, base_estimator=None, method='sigmoid', cv=3): + self.base_estimator = base_estimator + self.method = method + self.cv = cv + + def fit(self, X, y, sample_weight=None): + """Fit the calibrated model + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data. + + y : array-like, shape (n_samples,) + Target values. + + sample_weight : array-like, shape = [n_samples] or None + Sample weights. If None, then samples are equally weighted. + + Returns + ------- + self : object + Returns an instance of self. + """ + X, y = check_X_y(X, y, accept_sparse=['csc', 'csr', 'coo']) + X, y = indexable(X, y) + lb = LabelBinarizer().fit(y) + self.classes_ = lb.classes_ + + # Check that we each cross-validation fold can have at least one + # example per class + n_folds = self.cv if isinstance(self.cv, int) \ + else self.cv.n_folds if hasattr(self.cv, "n_folds") else None + if n_folds and \ + np.any([np.sum(y == class_) < n_folds for class_ in self.classes_]): + raise ValueError("Requesting %d-fold cross-validation but provided" + " less than %d examples for at least one class." + % (n_folds, n_folds)) + + self.calibrated_classifiers_ = [] + if self.base_estimator is None: + base_estimator = LinearSVC() + else: + base_estimator = self.base_estimator + + if self.cv == "prefit": + calibrated_classifier = _CalibratedClassifier( + base_estimator, method=self.method) + if sample_weight is not None: + calibrated_classifier.fit(X, y, sample_weight) + else: + calibrated_classifier.fit(X, y) + self.calibrated_classifiers_.append(calibrated_classifier) + else: + cv = _check_cv(self.cv, X, y, classifier=True) + arg_names = inspect.getargspec(base_estimator.fit)[0] + estimator_name = type(base_estimator).__name__ + if (sample_weight is not None + and "sample_weight" not in arg_names): + warnings.warn("%s does not support sample_weight. Samples" + " weights are only used for the calibration" + " itself." % estimator_name) + base_estimator_sample_weight = None + else: + base_estimator_sample_weight = sample_weight + for train, test in cv: + this_estimator = clone(base_estimator) + if base_estimator_sample_weight is not None: + this_estimator.fit( + X[train], y[train], + sample_weight=base_estimator_sample_weight[train]) + else: + this_estimator.fit(X[train], y[train]) + + calibrated_classifier = _CalibratedClassifier( + this_estimator, method=self.method) + if sample_weight is not None: + calibrated_classifier.fit(X[test], y[test], + sample_weight[test]) + else: + calibrated_classifier.fit(X[test], y[test]) + self.calibrated_classifiers_.append(calibrated_classifier) + + return self + + def predict_proba(self, X): + """Posterior probabilities of classification + + This function returns posterior probabilities of classification + according to each class on an array of test vectors X. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + The samples. + + Returns + ------- + C : array, shape (n_samples, n_classes) + The predicted probas. + """ + check_is_fitted(self, ["classes_", "calibrated_classifiers_"]) + X = check_array(X, accept_sparse=['csc', 'csr', 'coo']) + # Compute the arithmetic mean of the predictions of the calibrated + # classfiers + mean_proba = np.zeros((X.shape[0], len(self.classes_))) + for calibrated_classifier in self.calibrated_classifiers_: + proba = calibrated_classifier.predict_proba(X) + mean_proba += proba + + mean_proba /= len(self.calibrated_classifiers_) + + return mean_proba + + def predict(self, X): + """Predict the target of new samples. Can be different from the + prediction of the uncalibrated classifier. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + The samples. + + Returns + ------- + C : array, shape (n_samples,) + The predicted class. + """ + check_is_fitted(self, ["classes_", "calibrated_classifiers_"]) + return self.classes_[np.argmax(self.predict_proba(X), axis=1)] + + +class _CalibratedClassifier(object): + """Probability calibration with isotonic regression or sigmoid. + + It assumes that base_estimator has already been fit, and trains the + calibration on the input set of the fit function. Note that this class + should not be used as an estimator directly. Use CalibratedClassifierCV + with cv="prefit" instead. + + Parameters + ---------- + base_estimator : instance BaseEstimator + The classifier whose output decision function needs to be calibrated + to offer more accurate predict_proba outputs. No default value since + it has to be an already fitted estimator. + + method : 'sigmoid' | 'isotonic' + The method to use for calibration. Can be 'sigmoid' which + corresponds to Platt's method or 'isotonic' which is a + non-parameteric approach based on isotonic regression. + + References + ---------- + .. [1] Obtaining calibrated probability estimates from decision trees + and naive Bayesian classifiers, B. Zadrozny & C. Elkan, ICML 2001 + + .. [2] Transforming Classifier Scores into Accurate Multiclass + Probability Estimates, B. Zadrozny & C. Elkan, (KDD 2002) + + .. [3] Probabilistic Outputs for Support Vector Machines and Comparisons to + Regularized Likelihood Methods, J. Platt, (1999) + + .. [4] Predicting Good Probabilities with Supervised Learning, + A. Niculescu-Mizil & R. Caruana, ICML 2005 + """ + def __init__(self, base_estimator, method='sigmoid'): + self.base_estimator = base_estimator + self.method = method + + def _preproc(self, X): + n_classes = len(self.classes_) + if hasattr(self.base_estimator, "decision_function"): + df = self.base_estimator.decision_function(X) + if df.ndim == 1: + df = df[:, np.newaxis] + elif hasattr(self.base_estimator, "predict_proba"): + df = self.base_estimator.predict_proba(X) + if n_classes == 2: + df = df[:, 1:] + else: + raise RuntimeError('classifier has no decision_function or ' + 'predict_proba method.') + + idx_pos_class = np.arange(df.shape[1]) + + return df, idx_pos_class + + def fit(self, X, y, sample_weight=None): + """Calibrate the fitted model + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data. + + y : array-like, shape (n_samples,) + Target values. + + sample_weight : array-like, shape = [n_samples] or None + Sample weights. If None, then samples are equally weighted. + + Returns + ------- + self : object + Returns an instance of self. + """ + lb = LabelBinarizer() + Y = lb.fit_transform(y) + self.classes_ = lb.classes_ + + df, idx_pos_class = self._preproc(X) + self.calibrators_ = [] + + for k, this_df in zip(idx_pos_class, df.T): + if self.method == 'isotonic': + calibrator = IsotonicRegression(out_of_bounds='clip') + elif self.method == 'sigmoid': + calibrator = _SigmoidCalibration() + else: + raise ValueError('method should be "sigmoid" or ' + '"isotonic". Got %s.' % self.method) + calibrator.fit(this_df, Y[:, k], sample_weight) + self.calibrators_.append(calibrator) + + return self + + def predict_proba(self, X): + """Posterior probabilities of classification + + This function returns posterior probabilities of classification + according to each class on an array of test vectors X. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + The samples. + + Returns + ------- + C : array, shape (n_samples, n_classes) + The predicted probas. Can be exact zeros. + """ + n_classes = len(self.classes_) + proba = np.zeros((X.shape[0], n_classes)) + + df, idx_pos_class = self._preproc(X) + + for k, this_df, calibrator in \ + zip(idx_pos_class, df.T, self.calibrators_): + if n_classes == 2: + k += 1 + proba[:, k] = calibrator.predict(this_df) + + # Normalize the probabilities + if n_classes == 2: + proba[:, 0] = 1. - proba[:, 1] + else: + proba /= np.sum(proba, axis=1)[:, np.newaxis] + + # XXX : for some reason all probas can be 0 + proba[np.isnan(proba)] = 1. / n_classes + + # Deal with cases where the predicted probability minimally exceeds 1.0 + proba[(1.0 < proba) & (proba <= 1.0 + 1e-5)] = 1.0 + + return proba + + +def _sigmoid_calibration(df, y, sample_weight=None): + """Probability Calibration with sigmoid method (Platt 2000) + + Parameters + ---------- + df : ndarray, shape (n_samples,) + The decision function or predict proba for the samples. + + y : ndarray, shape (n_samples,) + The targets. + + sample_weight : array-like, shape = [n_samples] or None + Sample weights. If None, then samples are equally weighted. + + Returns + ------- + a : float + The slope. + + b : float + The intercept. + + References + ---------- + Platt, "Probabilistic Outputs for Support Vector Machines" + """ + df = column_or_1d(df) + y = column_or_1d(y) + + F = df # F follows Platt's notations + tiny = np.finfo(np.float).tiny # to avoid division by 0 warning + + # Bayesian priors (see Platt end of section 2.2) + prior0 = float(np.sum(y <= 0)) + prior1 = y.shape[0] - prior0 + T = np.zeros(y.shape) + T[y > 0] = (prior1 + 1.) / (prior1 + 2.) + T[y <= 0] = 1. / (prior0 + 2.) + T1 = 1. - T + + def objective(AB): + # From Platt (beginning of Section 2.2) + E = np.exp(AB[0] * F + AB[1]) + P = 1. / (1. + E) + l = -(T * np.log(P + tiny) + T1 * np.log(1. - P + tiny)) + if sample_weight is not None: + return (sample_weight * l).sum() + else: + return l.sum() + + def grad(AB): + # gradient of the objective function + E = np.exp(AB[0] * F + AB[1]) + P = 1. / (1. + E) + TEP_minus_T1P = P * (T * E - T1) + if sample_weight is not None: + TEP_minus_T1P *= sample_weight + dA = np.dot(TEP_minus_T1P, F) + dB = np.sum(TEP_minus_T1P) + return np.array([dA, dB]) + + AB0 = np.array([0., log((prior0 + 1.) / (prior1 + 1.))]) + AB_ = fmin_bfgs(objective, AB0, fprime=grad, disp=False) + return AB_[0], AB_[1] + + +class _SigmoidCalibration(BaseEstimator, RegressorMixin): + """Sigmoid regression model. + + Attributes + ---------- + `a_` : float + The slope. + + `b_` : float + The intercept. + """ + def fit(self, X, y, sample_weight=None): + """Fit the model using X, y as training data. + + Parameters + ---------- + X : array-like, shape (n_samples,) + Training data. + + y : array-like, shape (n_samples,) + Training target. + + sample_weight : array-like, shape = [n_samples] or None + Sample weights. If None, then samples are equally weighted. + + Returns + ------- + self : object + Returns an instance of self. + """ + X = column_or_1d(X) + y = column_or_1d(y) + X, y = indexable(X, y) + + self.a_, self.b_ = _sigmoid_calibration(X, y, sample_weight) + return self + + def predict(self, T): + """Predict new data by linear interpolation. + + Parameters + ---------- + T : array-like, shape (n_samples,) + Data to predict from. + + Returns + ------- + `T_` : array, shape (n_samples,) + The predicted data. + """ + T = column_or_1d(T) + return 1. / (1. + np.exp(self.a_ * T + self.b_)) + + +def calibration_curve(y_true, y_prob, normalize=False, n_bins=5): + """Compute true and predicted probabilities for a calibration curve. + + Parameters + ---------- + y_true : array, shape (n_samples,) + True targets. + + y_prob : array, shape (n_samples,) + Probabilities of the positive class. + + normalize : bool, optional, default=False + Whether y_prob needs to be normalized into the bin [0, 1], i.e. is not + a proper probability. If True, the smallest value in y_prob is mapped + onto 0 and the largest one onto 1. + + n_bins : int + Number of bins. A bigger number requires more data. + + Returns + ------- + prob_true : array, shape (n_bins,) + The true probability in each bin (fraction of positives). + + prob_pred : array, shape (n_bins,) + The mean predicted probability in each bin. + + References + ---------- + Alexandru Niculescu-Mizil and Rich Caruana (2005) Predicting Good + Probabilities With Supervised Learning, in Proceedings of the 22nd + International Conference on Machine Learning (ICML). + See section 4 (Qualitative Analysis of Predictions). + """ + y_true = column_or_1d(y_true) + y_prob = column_or_1d(y_prob) + + if normalize: # Normalize predicted values into interval [0, 1] + y_prob = (y_prob - y_prob.min()) / (y_prob.max() - y_prob.min()) + elif y_prob.min() < 0 or y_prob.max() > 1: + raise ValueError("y_prob has values outside [0, 1] and normalize is " + "set to False.") + + y_true = _check_binary_probabilistic_predictions(y_true, y_prob) + + bins = np.linspace(0., 1. + 1e-8, n_bins + 1) + binids = np.digitize(y_prob, bins) - 1 + + bin_sums = np.bincount(binids, weights=y_prob, minlength=len(bins)) + bin_true = np.bincount(binids, weights=y_true, minlength=len(bins)) + bin_total = np.bincount(binids, minlength=len(bins)) + + nonzero = bin_total != 0 + prob_true = (bin_true[nonzero] / bin_total[nonzero]) + prob_pred = (bin_sums[nonzero] / bin_total[nonzero]) + + return prob_true, prob_pred diff --git a/sklearn/cluster/__init__.py b/sklearn/cluster/__init__.py index 1de07e10534a7..16f43d374e510 100644 --- a/sklearn/cluster/__init__.py +++ b/sklearn/cluster/__init__.py @@ -4,16 +4,23 @@ """ from .spectral import spectral_clustering, SpectralClustering -from .mean_shift_ import mean_shift, MeanShift, estimate_bandwidth, \ - get_bin_seeds +from .mean_shift_ import (mean_shift, MeanShift, + estimate_bandwidth, get_bin_seeds) from .affinity_propagation_ import affinity_propagation, AffinityPropagation -from .hierarchical import ward_tree, Ward, WardAgglomeration +from .hierarchical import (ward_tree, Ward, WardAgglomeration, + AgglomerativeClustering, linkage_tree, + FeatureAgglomeration) from .k_means_ import k_means, KMeans, MiniBatchKMeans from .dbscan_ import dbscan, DBSCAN +from .bicluster import SpectralBiclustering, SpectralCoclustering +from .birch import Birch __all__ = ['AffinityPropagation', + 'AgglomerativeClustering', + 'Birch', 'DBSCAN', 'KMeans', + 'FeatureAgglomeration', 'MeanShift', 'MiniBatchKMeans', 'SpectralClustering', @@ -24,6 +31,9 @@ 'estimate_bandwidth', 'get_bin_seeds', 'k_means', + 'linkage_tree', 'mean_shift', 'spectral_clustering', - 'ward_tree'] + 'ward_tree', + 'SpectralBiclustering', + 'SpectralCoclustering'] diff --git a/sklearn/cluster/_feature_agglomeration.py b/sklearn/cluster/_feature_agglomeration.py index 3da49ed5071b0..4e22075f69129 100644 --- a/sklearn/cluster/_feature_agglomeration.py +++ b/sklearn/cluster/_feature_agglomeration.py @@ -8,7 +8,10 @@ import numpy as np from ..base import TransformerMixin -from ..utils import array2d +from ..utils import check_array +from ..utils.validation import check_is_fitted + +import warnings ############################################################################### @@ -19,25 +22,42 @@ class AgglomerationTransform(TransformerMixin): A class for feature agglomeration via the transform interface """ - def transform(self, X, pooling_func=np.mean): + pooling_func = np.mean + + def transform(self, X, pooling_func=None): """ Transform a new matrix using the built clustering Parameters - --------- - X : array-like, shape = [n_samples, n_features] + ---------- + X : array-like, shape = [n_samples, n_features] or [n_features] A M by N array of M observations in N dimensions or a length M array of M one-dimensional observations. - pooling_func : a function that takes an array of shape = [M, N] and - return an array of value of size M. - Defaut is np.mean + pooling_func : callable, default=np.mean + This combines the values of agglomerated features into a single + value, and should accept an array of shape [M, N] and the keyword + argument `axis=1`, and reduce it to an array of size [M]. + + Returns + ------- + Y : array, shape = [n_samples, n_clusters] or [n_clusters] + The pooled values for each feature cluster. """ - X = np.asarray(X) + check_is_fitted(self, "labels_") + + if pooling_func is not None: + warnings.warn("The pooling_func parameter is deprecated since 0.15 " + "and will be removed in 0.18. " + "Pass it to the constructor instead.", + DeprecationWarning) + else: + pooling_func = self.pooling_func + X = check_array(X) nX = [] if len(self.labels_) != X.shape[1]: raise ValueError("X has a different number of features than " - "during fitting.") + "during fitting.") for l in np.unique(self.labels_): nX.append(pooling_func(X[:, self.labels_ == l], axis=1)) @@ -51,25 +71,16 @@ def inverse_transform(self, Xred): Parameters ---------- - Xred : array of size k + Xred : array-like, shape=[n_samples, n_clusters] or [n_clusters,] The values to be assigned to each cluster of samples Returns ------- - X : array of size nb_samples - A vector of size nb_samples with the values of Xred assigned to + X : array, shape=[n_samples, n_features] or [n_features] + A vector of size n_samples with the values of Xred assigned to each of the cluster of samples. """ - if np.size((Xred.shape)) == 1: - X = np.zeros([self.labels_.shape[0]]) - else: - X = np.zeros([Xred.shape[0], self.labels_.shape[0]]) - unil = np.unique(self.labels_) - for i in range(len(unil)): - if np.size((Xred.shape)) == 1: - X[self.labels_ == unil[i]] = Xred[i] - else: - ncol = np.sum(self.labels_ == unil[i]) - X[:, self.labels_ == unil[i]] = np.tile(array2d(Xred[:, i]).T, - ncol) - return X + check_is_fitted(self, "labels_") + + unil, inverse = np.unique(self.labels_, return_inverse=True) + return Xred[..., inverse] diff --git a/sklearn/cluster/_hierarchical.cpp b/sklearn/cluster/_hierarchical.cpp new file mode 100644 index 0000000000000..c25e3723bb2c5 --- /dev/null +++ b/sklearn/cluster/_hierarchical.cpp @@ -0,0 +1,21636 @@ +/* Generated by Cython 0.19.1 on Mon Feb 17 15:12:38 2014 */ + +#define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_VERSION_HEX < 0x03020000 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__cluster___hierarchical +#define __PYX_HAVE_API__sklearn__cluster___hierarchical +#include "string.h" +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#include +#include "ios" +#include "new" +#include "stdexcept" +#include "typeinfo" +#include +#include "pythread.h" +#include "pystate.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +#ifdef __GNUC__ + /* Test for GCC > 2.95 */ + #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) + #else /* __GNUC__ > 2 ... */ + #define likely(x) (x) + #define unlikely(x) (x) + #endif /* __GNUC__ > 2 ... */ +#else /* __GNUC__ */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "_hierarchical.pyx", + "numpy.pxd", + "stringsource", + "type.pxd", + "fast_dict.pxd", +}; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + +struct __pyx_memoryview_obj; +typedef struct { + struct __pyx_memoryview_obj *memview; + char *data; + Py_ssize_t shape[8]; + Py_ssize_t strides[8]; + Py_ssize_t suboffsets[8]; +} __Pyx_memviewslice; + +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __pyx_atomic_int_type int +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ + !defined(__i386__) + #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && MSC_VER + #include + #define __pyx_atomic_int_type LONG + #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using MSVC atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 + #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using Intel atomics" + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif +typedef volatile __pyx_atomic_int_type __pyx_atomic_int; +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview) \ + __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) +#else + #define __pyx_add_acquisition_count(memview) \ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif + + +/* "numpy.pxd":723 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "numpy.pxd":724 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "numpy.pxd":725 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "numpy.pxd":726 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "numpy.pxd":730 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "numpy.pxd":731 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "numpy.pxd":732 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "numpy.pxd":733 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "numpy.pxd":737 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "numpy.pxd":738 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "numpy.pxd":747 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "numpy.pxd":748 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "numpy.pxd":749 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "numpy.pxd":751 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "numpy.pxd":752 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "numpy.pxd":753 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "numpy.pxd":755 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "numpy.pxd":756 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "numpy.pxd":758 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "numpy.pxd":759 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "numpy.pxd":760 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; + +/* "sklearn/utils/fast_dict.pxd":14 + * + * DTYPE = np.float64 + * ctypedef np.float64_t DTYPE_t # <<<<<<<<<<<<<< + * + * ITYPE = np.intp + */ +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t; + +/* "sklearn/utils/fast_dict.pxd":17 + * + * ITYPE = np.intp + * ctypedef np.intp_t ITYPE_t # <<<<<<<<<<<<<< + * + * ############################################################################### + */ +typedef __pyx_t_5numpy_intp_t __pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t; + +/* "sklearn/cluster/_hierarchical.pyx":7 + * cimport cython + * + * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< + * ctypedef np.npy_intp INTP + * ctypedef np.int8_t INT8 + */ +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE; + +/* "sklearn/cluster/_hierarchical.pyx":8 + * + * ctypedef np.float64_t DOUBLE + * ctypedef np.npy_intp INTP # <<<<<<<<<<<<<< + * ctypedef np.int8_t INT8 + * + */ +typedef npy_intp __pyx_t_7sklearn_7cluster_13_hierarchical_INTP; + +/* "sklearn/cluster/_hierarchical.pyx":9 + * ctypedef np.float64_t DOUBLE + * ctypedef np.npy_intp INTP + * ctypedef np.int8_t INT8 # <<<<<<<<<<<<<< + * + * # Numpy must be initialized. When using numpy from C or Cython you must + */ +typedef __pyx_t_5numpy_int8_t __pyx_t_7sklearn_7cluster_13_hierarchical_INT8; + +/* "sklearn/cluster/_hierarchical.pyx":23 + * + * DTYPE = np.float64 + * ctypedef np.float64_t DTYPE_t # <<<<<<<<<<<<<< + * + * ITYPE = np.intp + */ +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t; + +/* "sklearn/cluster/_hierarchical.pyx":26 + * + * ITYPE = np.intp + * ctypedef np.intp_t ITYPE_t # <<<<<<<<<<<<<< + * + * # Reimplementation for MSVC support + */ +typedef __pyx_t_5numpy_intp_t __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ +struct __pyx_MemviewEnum_obj; +struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge; +struct __pyx_memoryview_obj; +struct __pyx_memoryviewslice_obj; +struct __pyx_array_obj; +struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict; + +/* "numpy.pxd":762 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "numpy.pxd":763 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "numpy.pxd":764 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "numpy.pxd":766 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; + +/* "View.MemoryView":275 + * + * @cname('__pyx_MemviewEnum') + * cdef class Enum(object): # <<<<<<<<<<<<<< + * cdef object name + * def __init__(self, name): + */ +struct __pyx_MemviewEnum_obj { + PyObject_HEAD + PyObject *name; +}; + + +/* "sklearn/cluster/_hierarchical.pyx":295 + * # An edge object for fast comparisons + * + * cdef class WeightedEdge: # <<<<<<<<<<<<<< + * cdef public ITYPE_t a + * cdef public ITYPE_t b + */ +struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge { + PyObject_HEAD + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t a; + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t b; + __pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t weight; +}; + + +/* "View.MemoryView":308 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ +struct __pyx_memoryview_obj { + PyObject_HEAD + struct __pyx_vtabstruct_memoryview *__pyx_vtab; + PyObject *obj; + PyObject *_size; + PyObject *_array_interface; + PyThread_type_lock lock; + __pyx_atomic_int acquisition_count[2]; + __pyx_atomic_int *acquisition_count_aligned_p; + Py_buffer view; + int flags; + int dtype_is_object; + __Pyx_TypeInfo *typeinfo; +}; + + +/* "View.MemoryView":927 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ +struct __pyx_memoryviewslice_obj { + struct __pyx_memoryview_obj __pyx_base; + __Pyx_memviewslice from_slice; + PyObject *from_object; + PyObject *(*to_object_func)(char *); + int (*to_dtype_func)(char *, PyObject *); +}; + + +/* "View.MemoryView":96 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ +struct __pyx_array_obj { + PyObject_HEAD + char *data; + Py_ssize_t len; + char *format; + int ndim; + Py_ssize_t *_shape; + Py_ssize_t *_strides; + Py_ssize_t itemsize; + PyObject *mode; + PyObject *_format; + void (*callback_free_data)(void *); + int free_data; + int dtype_is_object; +}; + + +/* "sklearn/utils/fast_dict.pxd":22 + * # An object to be used in Python + * + * cdef class IntFloatDict: # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t] my_map + * cdef _to_arrays(self, ITYPE_t [:] keys, DTYPE_t [:] values) + */ +struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_vtab; + std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t> my_map; +}; + + + +/* "View.MemoryView":308 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ + +struct __pyx_vtabstruct_memoryview { + char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); + PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); +}; +static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; + + +/* "View.MemoryView":927 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ + +struct __pyx_vtabstruct__memoryviewslice { + struct __pyx_vtabstruct_memoryview __pyx_base; +}; +static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; + + +/* "sklearn/utils/fast_dict.pxd":22 + * # An object to be used in Python + * + * cdef class IntFloatDict: # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t] my_map + * cdef _to_arrays(self, ITYPE_t [:] keys, DTYPE_t [:] values) + */ + +struct __pyx_vtabstruct_7sklearn_5utils_9fast_dict_IntFloatDict { + PyObject *(*_to_arrays)(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *, __Pyx_memviewslice, __Pyx_memviewslice); +}; +static struct __pyx_vtabstruct_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_vtabptr_7sklearn_5utils_9fast_dict_IntFloatDict; + +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); /*proto*/ + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +#define __Pyx_BufPtrCContig1d(type, buf, i0, s0) ((type)buf + i0) +#define __Pyx_BufPtrCContig2d(type, buf, i0, s0, i1, s1) ((type)((char*)buf + i0 * s0) + i1) +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static PyObject* __Pyx_PyObject_CallMethodTuple(PyObject* obj, PyObject* method_name, PyObject* args) { + PyObject *method, *result = NULL; + if (unlikely(!args)) return NULL; + method = __Pyx_PyObject_GetAttrStr(obj, method_name); + if (unlikely(!method)) goto bad; + result = PyObject_Call(method, args, NULL); + Py_DECREF(method); +bad: + Py_DECREF(args); + return result; +} +#define __Pyx_PyObject_CallMethod3(obj, name, arg1, arg2, arg3) \ + __Pyx_PyObject_CallMethodTuple(obj, name, PyTuple_Pack(3, arg1, arg2, arg3)) +#define __Pyx_PyObject_CallMethod2(obj, name, arg1, arg2) \ + __Pyx_PyObject_CallMethodTuple(obj, name, PyTuple_Pack(2, arg1, arg2)) +#define __Pyx_PyObject_CallMethod1(obj, name, arg1) \ + __Pyx_PyObject_CallMethodTuple(obj, name, PyTuple_Pack(1, arg1)) +#define __Pyx_PyObject_CallMethod0(obj, name) \ + __Pyx_PyObject_CallMethodTuple(obj, name, (Py_INCREF(__pyx_empty_tuple), __pyx_empty_tuple)) + +static CYTHON_INLINE PyObject* __Pyx_PyObject_Pop(PyObject* L); /*proto*/ + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +#define __Pyx_GetItemInt(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Fast(o, i, is_list, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +#define __Pyx_GetItemInt_List(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_List_Fast(o, i, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, i, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ + +#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) +static CYTHON_INLINE PyObject* __Pyx_PyObject_Append(PyObject* L, PyObject* x); /*proto*/ + +#define __Pyx_tp_new(type_obj, args) __Pyx_tp_new_kwargs(type_obj, args, NULL) +static CYTHON_INLINE PyObject* __Pyx_tp_new_kwargs(PyObject* type_obj, PyObject* args, PyObject* kwargs) { + return (PyObject*) (((PyTypeObject*)type_obj)->tp_new((PyTypeObject*)type_obj, args, kwargs)); +} + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/ + +static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); /* proto */ + +#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) + +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +#include + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); + +static CYTHON_INLINE long __Pyx_div_long(long, long); /* proto */ + +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename); /*proto*/ + +static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ + +static void* __Pyx_GetVtable(PyObject *dict); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t); + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_from_py_Py_intptr_t(PyObject *); + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +#include + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d +#define __Pyx_MEMVIEW_DIRECT 1 +#define __Pyx_MEMVIEW_PTR 2 +#define __Pyx_MEMVIEW_FULL 4 +#define __Pyx_MEMVIEW_CONTIG 8 +#define __Pyx_MEMVIEW_STRIDED 16 +#define __Pyx_MEMVIEW_FOLLOW 32 +#define __Pyx_IS_C_CONTIG 1 +#define __Pyx_IS_F_CONTIG 2 +static int __Pyx_init_memviewslice( + struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference); +static CYTHON_INLINE int __pyx_add_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) +#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) +#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) +#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) +static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); + +static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim); + +static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize); + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object); + +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); + +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); + +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); + +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); + +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); + +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); + +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); + +static int __Pyx_check_binary_version(void); + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'cython.view' */ + +/* Module declarations from 'cython' */ + +/* Module declarations from 'libcpp.utility' */ + +/* Module declarations from 'libcpp.map' */ + +/* Module declarations from 'sklearn.utils.fast_dict' */ +static PyTypeObject *__pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict = 0; + +/* Module declarations from 'sklearn.cluster._hierarchical' */ +static PyTypeObject *__pyx_memoryview_type = 0; +static PyTypeObject *__pyx_array_type = 0; +static PyTypeObject *__pyx_memoryviewslice_type = 0; +static PyTypeObject *__pyx_MemviewEnum_type = 0; +static PyTypeObject *__pyx_ptype_7sklearn_7cluster_13_hierarchical_WeightedEdge = 0; +static PyObject *generic = 0; +static PyObject *strided = 0; +static PyObject *indirect = 0; +static PyObject *contiguous = 0; +static PyObject *indirect_contiguous = 0; +static CYTHON_INLINE double __pyx_f_7sklearn_7cluster_13_hierarchical_fmax(double, double); /*proto*/ +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ +static void *__pyx_align_pointer(void *, size_t); /*proto*/ +static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ +static PyObject *_unellipsify(PyObject *, int); /*proto*/ +static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ +static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, int); /*proto*/ +static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ +static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ +static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ +static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ +static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ +static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ +static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INTP = { "INTP", NULL, sizeof(__pyx_t_7sklearn_7cluster_13_hierarchical_INTP), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_7cluster_13_hierarchical_INTP) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_7cluster_13_hierarchical_INTP), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INT8 = { "INT8", NULL, sizeof(__pyx_t_7sklearn_7cluster_13_hierarchical_INT8), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_7cluster_13_hierarchical_INT8) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_7cluster_13_hierarchical_INT8), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t = { "ITYPE_t", NULL, sizeof(__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t), 0 }; +#define __Pyx_MODULE_NAME "sklearn.cluster._hierarchical" +int __pyx_module_is_main_sklearn__cluster___hierarchical = 0; + +/* Implementation of 'sklearn.cluster._hierarchical' */ +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_Ellipsis; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_xrange; +static PyObject *__pyx_builtin_id; +static PyObject *__pyx_builtin_IndexError; +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_compute_ward_dist(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_m_1, PyArrayObject *__pyx_v_m_2, PyArrayObject *__pyx_v_coord_row, PyArrayObject *__pyx_v_coord_col, PyArrayObject *__pyx_v_res); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_2_hc_get_descendent(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_node, PyObject *__pyx_v_children, __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_n_leaves); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_4hc_get_heads(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_parents, PyObject *__pyx_v_copy); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_6_get_parents(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_nodes, PyObject *__pyx_v_heads, PyArrayObject *__pyx_v_parents, PyArrayObject *__pyx_v_not_visited); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_8max_merge(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_a, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_b, PyArrayObject *__pyx_v_mask, CYTHON_UNUSED __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_a, CYTHON_UNUSED __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_b); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_10average_merge(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_a, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_b, PyArrayObject *__pyx_v_mask, __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_a, __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_b); /* proto */ +static int __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge___init__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self, __pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t __pyx_v_weight, __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_a, __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_b); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_2__richcmp__(PyObject *__pyx_v_self, struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_other, int __pyx_v_op); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_4__repr__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a___get__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a_2__set__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b___get__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b_2__set__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight___get__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight_2__set__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_7cluster_13_hierarchical_WeightedEdge(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_2[] = "%s(weight=%f, a=%i, b=%i)"; +static char __pyx_k_3[] = "ndarray is not C contiguous"; +static char __pyx_k_5[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_7[] = "Non-native byte order not supported"; +static char __pyx_k_9[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_10[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_13[] = "Format string allocated too short."; +static char __pyx_k_15[] = "Empty shape tuple for cython.array"; +static char __pyx_k_17[] = "itemsize <= 0 for cython.array"; +static char __pyx_k_20[] = "unable to allocate shape or strides."; +static char __pyx_k_22[] = "Invalid shape in axis %d: %d."; +static char __pyx_k_23[] = "Invalid mode, expected 'c' or 'fortran', got %s"; +static char __pyx_k_25[] = "unable to allocate array data."; +static char __pyx_k_27[] = "Can only create a buffer that is contiguous in memory."; +static char __pyx_k_29[] = "Unable to convert item to object"; +static char __pyx_k_31[] = "Buffer view does not expose strides"; +static char __pyx_k_33[] = ""; +static char __pyx_k_34[] = ""; +static char __pyx_k_37[] = "Cannot index with type '%s'"; +static char __pyx_k_39[] = "Indirect dimensions not supported"; +static char __pyx_k_41[] = "Index out of bounds (axis %d)"; +static char __pyx_k_42[] = "Step may not be zero (axis %d)"; +static char __pyx_k_43[] = "All dimensions preceding dimension %d must be indexed and not sliced"; +static char __pyx_k_44[] = "Out of bounds on buffer access (axis %d)"; +static char __pyx_k_45[] = "Cannot transpose memoryview with indirect dimensions"; +static char __pyx_k_46[] = "got differing extents in dimension %d (got %d and %d)"; +static char __pyx_k_47[] = "Dimension %d is not direct"; +static char __pyx_k_50[] = "/home/varoquau/dev/scikit-learn/sklearn/cluster/_hierarchical.pyx"; +static char __pyx_k_51[] = "sklearn.cluster._hierarchical"; +static char __pyx_k_62[] = "getbuffer(obj, view, flags)"; +static char __pyx_k_63[] = ""; +static char __pyx_k_65[] = ""; +static char __pyx_k_67[] = ""; +static char __pyx_k_69[] = ""; +static char __pyx_k_71[] = ""; +static char __pyx_k__B[] = "B"; +static char __pyx_k__H[] = "H"; +static char __pyx_k__I[] = "I"; +static char __pyx_k__L[] = "L"; +static char __pyx_k__O[] = "O"; +static char __pyx_k__Q[] = "Q"; +static char __pyx_k__a[] = "a"; +static char __pyx_k__b[] = "b"; +static char __pyx_k__c[] = "c"; +static char __pyx_k__d[] = "d"; +static char __pyx_k__f[] = "f"; +static char __pyx_k__g[] = "g"; +static char __pyx_k__h[] = "h"; +static char __pyx_k__i[] = "i"; +static char __pyx_k__j[] = "j"; +static char __pyx_k__l[] = "l"; +static char __pyx_k__n[] = "n"; +static char __pyx_k__q[] = "q"; +static char __pyx_k__Zd[] = "Zd"; +static char __pyx_k__Zf[] = "Zf"; +static char __pyx_k__Zg[] = "Zg"; +static char __pyx_k__id[] = "id"; +static char __pyx_k__np[] = "np"; +static char __pyx_k__pa[] = "pa"; +static char __pyx_k__col[] = "col"; +static char __pyx_k__ind[] = "ind"; +static char __pyx_k__key[] = "key"; +static char __pyx_k__m_1[] = "m_1"; +static char __pyx_k__m_2[] = "m_2"; +static char __pyx_k__n_a[] = "n_a"; +static char __pyx_k__n_b[] = "n_b"; +static char __pyx_k__obj[] = "obj"; +static char __pyx_k__pop[] = "pop"; +static char __pyx_k__res[] = "res"; +static char __pyx_k__row[] = "row"; +static char __pyx_k__a_it[] = "a_it"; +static char __pyx_k__b_it[] = "b_it"; +static char __pyx_k__base[] = "base"; +static char __pyx_k__copy[] = "copy"; +static char __pyx_k__intp[] = "intp"; +static char __pyx_k__mask[] = "mask"; +static char __pyx_k__mode[] = "mode"; +static char __pyx_k__name[] = "name"; +static char __pyx_k__ndim[] = "ndim"; +static char __pyx_k__node[] = "node"; +static char __pyx_k__pack[] = "pack"; +static char __pyx_k__size[] = "size"; +static char __pyx_k__step[] = "step"; +static char __pyx_k__stop[] = "stop"; +static char __pyx_k__ASCII[] = "ASCII"; +static char __pyx_k__DTYPE[] = "DTYPE"; +static char __pyx_k__ITYPE[] = "ITYPE"; +static char __pyx_k__a_end[] = "a_end"; +static char __pyx_k__b_end[] = "b_end"; +static char __pyx_k__error[] = "error"; +static char __pyx_k__flags[] = "flags"; +static char __pyx_k__heads[] = "heads"; +static char __pyx_k__n_out[] = "n_out"; +static char __pyx_k__node0[] = "node0"; +static char __pyx_k__nodes[] = "nodes"; +static char __pyx_k__numpy[] = "numpy"; +static char __pyx_k__range[] = "range"; +static char __pyx_k__shape[] = "shape"; +static char __pyx_k__start[] = "start"; +static char __pyx_k__value[] = "value"; +static char __pyx_k__append[] = "append"; +static char __pyx_k__decode[] = "decode"; +static char __pyx_k__encode[] = "encode"; +static char __pyx_k__extend[] = "extend"; +static char __pyx_k__format[] = "format"; +static char __pyx_k__out_it[] = "out_it"; +static char __pyx_k__parent[] = "parent"; +static char __pyx_k__struct[] = "struct"; +static char __pyx_k__unpack[] = "unpack"; +static char __pyx_k__weight[] = "weight"; +static char __pyx_k__xrange[] = "xrange"; +static char __pyx_k__float64[] = "float64"; +static char __pyx_k__fortran[] = "fortran"; +static char __pyx_k__memview[] = "memview"; +static char __pyx_k__out_end[] = "out_end"; +static char __pyx_k__out_obj[] = "out_obj"; +static char __pyx_k__parents[] = "parents"; +static char __pyx_k__Ellipsis[] = "Ellipsis"; +static char __pyx_k____main__[] = "__main__"; +static char __pyx_k____name__[] = "__name__"; +static char __pyx_k____test__[] = "__test__"; +static char __pyx_k__children[] = "children"; +static char __pyx_k__itemsize[] = "itemsize"; +static char __pyx_k__n_leaves[] = "n_leaves"; +static char __pyx_k__size_max[] = "size_max"; +static char __pyx_k__TypeError[] = "TypeError"; +static char __pyx_k____class__[] = "__class__"; +static char __pyx_k__coord_col[] = "coord_col"; +static char __pyx_k__coord_row[] = "coord_row"; +static char __pyx_k__enumerate[] = "enumerate"; +static char __pyx_k__max_merge[] = "max_merge"; +static char __pyx_k__n_indices[] = "n_indices"; +static char __pyx_k__IndexError[] = "IndexError"; +static char __pyx_k__ValueError[] = "ValueError"; +static char __pyx_k____import__[] = "__import__"; +static char __pyx_k__descendent[] = "descendent"; +static char __pyx_k__n_features[] = "n_features"; +static char __pyx_k__MemoryError[] = "MemoryError"; +static char __pyx_k__not_visited[] = "not_visited"; +static char __pyx_k__RuntimeError[] = "RuntimeError"; +static char __pyx_k___get_parents[] = "_get_parents"; +static char __pyx_k__hc_get_heads[] = "hc_get_heads"; +static char __pyx_k__average_merge[] = "average_merge"; +static char __pyx_k____pyx_vtable__[] = "__pyx_vtable__"; +static char __pyx_k____pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k__allocate_buffer[] = "allocate_buffer"; +static char __pyx_k__dtype_is_object[] = "dtype_is_object"; +static char __pyx_k__compute_ward_dist[] = "compute_ward_dist"; +static char __pyx_k___hc_get_descendent[] = "_hc_get_descendent"; +static char __pyx_k____pyx_releasebuffer[] = "__pyx_releasebuffer"; +static PyObject *__pyx_kp_u_10; +static PyObject *__pyx_kp_u_13; +static PyObject *__pyx_kp_s_15; +static PyObject *__pyx_kp_s_17; +static PyObject *__pyx_kp_s_2; +static PyObject *__pyx_kp_s_20; +static PyObject *__pyx_kp_s_22; +static PyObject *__pyx_kp_s_23; +static PyObject *__pyx_kp_s_25; +static PyObject *__pyx_kp_s_27; +static PyObject *__pyx_kp_s_29; +static PyObject *__pyx_kp_u_3; +static PyObject *__pyx_kp_s_31; +static PyObject *__pyx_kp_s_33; +static PyObject *__pyx_kp_s_34; +static PyObject *__pyx_kp_s_37; +static PyObject *__pyx_kp_s_39; +static PyObject *__pyx_kp_s_44; +static PyObject *__pyx_kp_s_46; +static PyObject *__pyx_kp_u_5; +static PyObject *__pyx_kp_s_50; +static PyObject *__pyx_n_s_51; +static PyObject *__pyx_kp_s_63; +static PyObject *__pyx_kp_s_65; +static PyObject *__pyx_kp_s_67; +static PyObject *__pyx_kp_s_69; +static PyObject *__pyx_kp_u_7; +static PyObject *__pyx_kp_s_71; +static PyObject *__pyx_kp_u_9; +static PyObject *__pyx_n_s__ASCII; +static PyObject *__pyx_n_s__DTYPE; +static PyObject *__pyx_n_s__Ellipsis; +static PyObject *__pyx_n_s__ITYPE; +static PyObject *__pyx_n_s__IndexError; +static PyObject *__pyx_n_s__MemoryError; +static PyObject *__pyx_n_b__O; +static PyObject *__pyx_n_s__RuntimeError; +static PyObject *__pyx_n_s__TypeError; +static PyObject *__pyx_n_s__ValueError; +static PyObject *__pyx_n_s____class__; +static PyObject *__pyx_n_s____import__; +static PyObject *__pyx_n_s____main__; +static PyObject *__pyx_n_s____name__; +static PyObject *__pyx_n_s____pyx_getbuffer; +static PyObject *__pyx_n_s____pyx_releasebuffer; +static PyObject *__pyx_n_s____pyx_vtable__; +static PyObject *__pyx_n_s____test__; +static PyObject *__pyx_n_s___get_parents; +static PyObject *__pyx_n_s___hc_get_descendent; +static PyObject *__pyx_n_s__a; +static PyObject *__pyx_n_s__a_end; +static PyObject *__pyx_n_s__a_it; +static PyObject *__pyx_n_s__allocate_buffer; +static PyObject *__pyx_n_s__append; +static PyObject *__pyx_n_s__average_merge; +static PyObject *__pyx_n_s__b; +static PyObject *__pyx_n_s__b_end; +static PyObject *__pyx_n_s__b_it; +static PyObject *__pyx_n_s__base; +static PyObject *__pyx_n_b__c; +static PyObject *__pyx_n_s__c; +static PyObject *__pyx_n_u__c; +static PyObject *__pyx_n_s__children; +static PyObject *__pyx_n_s__col; +static PyObject *__pyx_n_s__compute_ward_dist; +static PyObject *__pyx_n_s__coord_col; +static PyObject *__pyx_n_s__coord_row; +static PyObject *__pyx_n_s__copy; +static PyObject *__pyx_n_s__decode; +static PyObject *__pyx_n_s__descendent; +static PyObject *__pyx_n_s__dtype_is_object; +static PyObject *__pyx_n_s__encode; +static PyObject *__pyx_n_s__enumerate; +static PyObject *__pyx_n_s__error; +static PyObject *__pyx_n_s__extend; +static PyObject *__pyx_n_s__flags; +static PyObject *__pyx_n_s__float64; +static PyObject *__pyx_n_s__format; +static PyObject *__pyx_n_b__fortran; +static PyObject *__pyx_n_s__fortran; +static PyObject *__pyx_n_s__hc_get_heads; +static PyObject *__pyx_n_s__heads; +static PyObject *__pyx_n_s__i; +static PyObject *__pyx_n_s__id; +static PyObject *__pyx_n_s__ind; +static PyObject *__pyx_n_s__intp; +static PyObject *__pyx_n_s__itemsize; +static PyObject *__pyx_n_s__j; +static PyObject *__pyx_n_s__key; +static PyObject *__pyx_n_s__m_1; +static PyObject *__pyx_n_s__m_2; +static PyObject *__pyx_n_s__mask; +static PyObject *__pyx_n_s__max_merge; +static PyObject *__pyx_n_s__memview; +static PyObject *__pyx_n_s__mode; +static PyObject *__pyx_n_s__n; +static PyObject *__pyx_n_s__n_a; +static PyObject *__pyx_n_s__n_b; +static PyObject *__pyx_n_s__n_features; +static PyObject *__pyx_n_s__n_indices; +static PyObject *__pyx_n_s__n_leaves; +static PyObject *__pyx_n_s__n_out; +static PyObject *__pyx_n_s__name; +static PyObject *__pyx_n_s__ndim; +static PyObject *__pyx_n_s__node; +static PyObject *__pyx_n_s__node0; +static PyObject *__pyx_n_s__nodes; +static PyObject *__pyx_n_s__not_visited; +static PyObject *__pyx_n_s__np; +static PyObject *__pyx_n_s__numpy; +static PyObject *__pyx_n_s__obj; +static PyObject *__pyx_n_s__out_end; +static PyObject *__pyx_n_s__out_it; +static PyObject *__pyx_n_s__out_obj; +static PyObject *__pyx_n_s__pa; +static PyObject *__pyx_n_s__pack; +static PyObject *__pyx_n_s__parent; +static PyObject *__pyx_n_s__parents; +static PyObject *__pyx_n_s__pop; +static PyObject *__pyx_n_s__range; +static PyObject *__pyx_n_s__res; +static PyObject *__pyx_n_s__row; +static PyObject *__pyx_n_s__shape; +static PyObject *__pyx_n_s__size; +static PyObject *__pyx_n_s__size_max; +static PyObject *__pyx_n_s__start; +static PyObject *__pyx_n_s__step; +static PyObject *__pyx_n_s__stop; +static PyObject *__pyx_n_s__struct; +static PyObject *__pyx_n_s__unpack; +static PyObject *__pyx_n_s__value; +static PyObject *__pyx_n_s__weight; +static PyObject *__pyx_n_s__xrange; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_1; +static PyObject *__pyx_int_neg_1; +static PyObject *__pyx_int_15; +static PyObject *__pyx_k_1; +static PyObject *__pyx_k_tuple_4; +static PyObject *__pyx_k_tuple_6; +static PyObject *__pyx_k_tuple_8; +static PyObject *__pyx_k_tuple_11; +static PyObject *__pyx_k_tuple_12; +static PyObject *__pyx_k_tuple_14; +static PyObject *__pyx_k_tuple_16; +static PyObject *__pyx_k_tuple_18; +static PyObject *__pyx_k_tuple_19; +static PyObject *__pyx_k_tuple_21; +static PyObject *__pyx_k_tuple_24; +static PyObject *__pyx_k_tuple_26; +static PyObject *__pyx_k_tuple_28; +static PyObject *__pyx_k_tuple_30; +static PyObject *__pyx_k_tuple_32; +static PyObject *__pyx_k_tuple_35; +static PyObject *__pyx_k_tuple_36; +static PyObject *__pyx_k_tuple_38; +static PyObject *__pyx_k_tuple_40; +static PyObject *__pyx_k_tuple_48; +static PyObject *__pyx_k_tuple_52; +static PyObject *__pyx_k_tuple_54; +static PyObject *__pyx_k_tuple_56; +static PyObject *__pyx_k_tuple_58; +static PyObject *__pyx_k_tuple_60; +static PyObject *__pyx_k_tuple_64; +static PyObject *__pyx_k_tuple_66; +static PyObject *__pyx_k_tuple_68; +static PyObject *__pyx_k_tuple_70; +static PyObject *__pyx_k_tuple_72; +static PyObject *__pyx_k_codeobj_49; +static PyObject *__pyx_k_codeobj_53; +static PyObject *__pyx_k_codeobj_55; +static PyObject *__pyx_k_codeobj_57; +static PyObject *__pyx_k_codeobj_59; +static PyObject *__pyx_k_codeobj_61; + +/* "sklearn/cluster/_hierarchical.pyx":29 + * + * # Reimplementation for MSVC support + * cdef inline double fmax(double a, double b): # <<<<<<<<<<<<<< + * return max(a, b) + * + */ + +static CYTHON_INLINE double __pyx_f_7sklearn_7cluster_13_hierarchical_fmax(double __pyx_v_a, double __pyx_v_b) { + double __pyx_r; + __Pyx_RefNannyDeclarations + double __pyx_t_1; + double __pyx_t_2; + double __pyx_t_3; + __Pyx_RefNannySetupContext("fmax", 0); + + /* "sklearn/cluster/_hierarchical.pyx":30 + * # Reimplementation for MSVC support + * cdef inline double fmax(double a, double b): + * return max(a, b) # <<<<<<<<<<<<<< + * + * ############################################################################### + */ + __pyx_t_1 = __pyx_v_b; + __pyx_t_2 = __pyx_v_a; + if (((__pyx_t_1 > __pyx_t_2) != 0)) { + __pyx_t_3 = __pyx_t_1; + } else { + __pyx_t_3 = __pyx_t_2; + } + __pyx_r = __pyx_t_3; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_1compute_ward_dist(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_7cluster_13_hierarchical_1compute_ward_dist = {__Pyx_NAMESTR("compute_ward_dist"), (PyCFunction)__pyx_pw_7sklearn_7cluster_13_hierarchical_1compute_ward_dist, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_1compute_ward_dist(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_m_1 = 0; + PyArrayObject *__pyx_v_m_2 = 0; + PyArrayObject *__pyx_v_coord_row = 0; + PyArrayObject *__pyx_v_coord_col = 0; + PyArrayObject *__pyx_v_res = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("compute_ward_dist (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__m_1,&__pyx_n_s__m_2,&__pyx_n_s__coord_row,&__pyx_n_s__coord_col,&__pyx_n_s__res,0}; + PyObject* values[5] = {0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__m_1)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__m_2)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("compute_ward_dist", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coord_row)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("compute_ward_dist", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coord_col)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("compute_ward_dist", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__res)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("compute_ward_dist", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "compute_ward_dist") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + } + __pyx_v_m_1 = ((PyArrayObject *)values[0]); + __pyx_v_m_2 = ((PyArrayObject *)values[1]); + __pyx_v_coord_row = ((PyArrayObject *)values[2]); + __pyx_v_coord_col = ((PyArrayObject *)values[3]); + __pyx_v_res = ((PyArrayObject *)values[4]); + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("compute_ward_dist", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.cluster._hierarchical.compute_ward_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_m_1), __pyx_ptype_5numpy_ndarray, 1, "m_1", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_m_2), __pyx_ptype_5numpy_ndarray, 1, "m_2", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_coord_row), __pyx_ptype_5numpy_ndarray, 1, "coord_row", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_coord_col), __pyx_ptype_5numpy_ndarray, 1, "coord_col", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 1, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_compute_ward_dist(__pyx_self, __pyx_v_m_1, __pyx_v_m_2, __pyx_v_coord_row, __pyx_v_coord_col, __pyx_v_res); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":38 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def compute_ward_dist(np.ndarray[DOUBLE, ndim=1, mode='c'] m_1, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=2, mode='c'] m_2, + * np.ndarray[INTP, ndim=1, mode='c'] coord_row, + */ + +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_compute_ward_dist(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_m_1, PyArrayObject *__pyx_v_m_2, PyArrayObject *__pyx_v_coord_row, PyArrayObject *__pyx_v_coord_col, PyArrayObject *__pyx_v_res) { + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_size_max; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_n_features; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_i; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_j; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_row; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_col; + __pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE __pyx_v_pa; + __pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE __pyx_v_n; + __Pyx_LocalBuf_ND __pyx_pybuffernd_coord_col; + __Pyx_Buffer __pyx_pybuffer_coord_col; + __Pyx_LocalBuf_ND __pyx_pybuffernd_coord_row; + __Pyx_Buffer __pyx_pybuffer_coord_row; + __Pyx_LocalBuf_ND __pyx_pybuffernd_m_1; + __Pyx_Buffer __pyx_pybuffer_m_1; + __Pyx_LocalBuf_ND __pyx_pybuffernd_m_2; + __Pyx_Buffer __pyx_pybuffer_m_2; + __Pyx_LocalBuf_ND __pyx_pybuffernd_res; + __Pyx_Buffer __pyx_pybuffer_res; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_1; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_2; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_3; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_4; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_5; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_6; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_7; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_8; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_9; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_10; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_11; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_12; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_13; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_14; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_15; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_16; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("compute_ward_dist", 0); + __pyx_pybuffer_m_1.pybuffer.buf = NULL; + __pyx_pybuffer_m_1.refcount = 0; + __pyx_pybuffernd_m_1.data = NULL; + __pyx_pybuffernd_m_1.rcbuffer = &__pyx_pybuffer_m_1; + __pyx_pybuffer_m_2.pybuffer.buf = NULL; + __pyx_pybuffer_m_2.refcount = 0; + __pyx_pybuffernd_m_2.data = NULL; + __pyx_pybuffernd_m_2.rcbuffer = &__pyx_pybuffer_m_2; + __pyx_pybuffer_coord_row.pybuffer.buf = NULL; + __pyx_pybuffer_coord_row.refcount = 0; + __pyx_pybuffernd_coord_row.data = NULL; + __pyx_pybuffernd_coord_row.rcbuffer = &__pyx_pybuffer_coord_row; + __pyx_pybuffer_coord_col.pybuffer.buf = NULL; + __pyx_pybuffer_coord_col.refcount = 0; + __pyx_pybuffernd_coord_col.data = NULL; + __pyx_pybuffernd_coord_col.rcbuffer = &__pyx_pybuffer_coord_col; + __pyx_pybuffer_res.pybuffer.buf = NULL; + __pyx_pybuffer_res.refcount = 0; + __pyx_pybuffernd_res.data = NULL; + __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_m_1.rcbuffer->pybuffer, (PyObject*)__pyx_v_m_1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_m_1.diminfo[0].strides = __pyx_pybuffernd_m_1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_m_1.diminfo[0].shape = __pyx_pybuffernd_m_1.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_m_2.rcbuffer->pybuffer, (PyObject*)__pyx_v_m_2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_m_2.diminfo[0].strides = __pyx_pybuffernd_m_2.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_m_2.diminfo[0].shape = __pyx_pybuffernd_m_2.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_m_2.diminfo[1].strides = __pyx_pybuffernd_m_2.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_m_2.diminfo[1].shape = __pyx_pybuffernd_m_2.rcbuffer->pybuffer.shape[1]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_coord_row.rcbuffer->pybuffer, (PyObject*)__pyx_v_coord_row, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INTP, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_coord_row.diminfo[0].strides = __pyx_pybuffernd_coord_row.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_coord_row.diminfo[0].shape = __pyx_pybuffernd_coord_row.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_coord_col.rcbuffer->pybuffer, (PyObject*)__pyx_v_coord_col, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INTP, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_coord_col.diminfo[0].strides = __pyx_pybuffernd_coord_col.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_coord_col.diminfo[0].shape = __pyx_pybuffernd_coord_col.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/cluster/_hierarchical.pyx":43 + * np.ndarray[INTP, ndim=1, mode='c'] coord_col, + * np.ndarray[DOUBLE, ndim=1, mode='c'] res): + * cdef INTP size_max = coord_row.shape[0] # <<<<<<<<<<<<<< + * cdef INTP n_features = m_2.shape[1] + * cdef INTP i, j, row, col + */ + __pyx_v_size_max = (__pyx_v_coord_row->dimensions[0]); + + /* "sklearn/cluster/_hierarchical.pyx":44 + * np.ndarray[DOUBLE, ndim=1, mode='c'] res): + * cdef INTP size_max = coord_row.shape[0] + * cdef INTP n_features = m_2.shape[1] # <<<<<<<<<<<<<< + * cdef INTP i, j, row, col + * cdef DOUBLE pa, n + */ + __pyx_v_n_features = (__pyx_v_m_2->dimensions[1]); + + /* "sklearn/cluster/_hierarchical.pyx":48 + * cdef DOUBLE pa, n + * + * for i in range(size_max): # <<<<<<<<<<<<<< + * row = coord_row[i] + * col = coord_col[i] + */ + __pyx_t_1 = __pyx_v_size_max; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "sklearn/cluster/_hierarchical.pyx":49 + * + * for i in range(size_max): + * row = coord_row[i] # <<<<<<<<<<<<<< + * col = coord_col[i] + * n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) + */ + __pyx_t_3 = __pyx_v_i; + __pyx_v_row = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INTP *, __pyx_pybuffernd_coord_row.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_coord_row.diminfo[0].strides)); + + /* "sklearn/cluster/_hierarchical.pyx":50 + * for i in range(size_max): + * row = coord_row[i] + * col = coord_col[i] # <<<<<<<<<<<<<< + * n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) + * pa = 0. + */ + __pyx_t_4 = __pyx_v_i; + __pyx_v_col = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INTP *, __pyx_pybuffernd_coord_col.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_coord_col.diminfo[0].strides)); + + /* "sklearn/cluster/_hierarchical.pyx":51 + * row = coord_row[i] + * col = coord_col[i] + * n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) # <<<<<<<<<<<<<< + * pa = 0. + * for j in range(n_features): + */ + __pyx_t_5 = __pyx_v_row; + __pyx_t_6 = __pyx_v_col; + __pyx_t_7 = __pyx_v_row; + __pyx_t_8 = __pyx_v_col; + __pyx_v_n = (((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_m_1.diminfo[0].strides)) * (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_m_1.diminfo[0].strides))) / ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_m_1.diminfo[0].strides)) + (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_m_1.diminfo[0].strides)))); + + /* "sklearn/cluster/_hierarchical.pyx":52 + * col = coord_col[i] + * n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) + * pa = 0. # <<<<<<<<<<<<<< + * for j in range(n_features): + * pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col]) ** 2 + */ + __pyx_v_pa = 0.; + + /* "sklearn/cluster/_hierarchical.pyx":53 + * n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) + * pa = 0. + * for j in range(n_features): # <<<<<<<<<<<<<< + * pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col]) ** 2 + * res[i] = pa * n + */ + __pyx_t_9 = __pyx_v_n_features; + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { + __pyx_v_j = __pyx_t_10; + + /* "sklearn/cluster/_hierarchical.pyx":54 + * pa = 0. + * for j in range(n_features): + * pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col]) ** 2 # <<<<<<<<<<<<<< + * res[i] = pa * n + * return res + */ + __pyx_t_11 = __pyx_v_row; + __pyx_t_12 = __pyx_v_j; + __pyx_t_13 = __pyx_v_row; + __pyx_t_14 = __pyx_v_col; + __pyx_t_15 = __pyx_v_j; + __pyx_t_16 = __pyx_v_col; + __pyx_v_pa = (__pyx_v_pa + pow((((*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_2.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_m_2.diminfo[0].strides, __pyx_t_12, __pyx_pybuffernd_m_2.diminfo[1].strides)) / (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_m_1.diminfo[0].strides))) - ((*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_2.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_m_2.diminfo[0].strides, __pyx_t_15, __pyx_pybuffernd_m_2.diminfo[1].strides)) / (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_m_1.diminfo[0].strides)))), 2.0)); + } + + /* "sklearn/cluster/_hierarchical.pyx":55 + * for j in range(n_features): + * pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col]) ** 2 + * res[i] = pa * n # <<<<<<<<<<<<<< + * return res + * + */ + __pyx_t_9 = __pyx_v_i; + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_res.diminfo[0].strides) = (__pyx_v_pa * __pyx_v_n); + } + + /* "sklearn/cluster/_hierarchical.pyx":56 + * pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col]) ** 2 + * res[i] = pa * n + * return res # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_res)); + __pyx_r = ((PyObject *)__pyx_v_res); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_coord_col.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_coord_row.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_m_1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_m_2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.cluster._hierarchical.compute_ward_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_coord_col.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_coord_row.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_m_1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_m_2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_3_hc_get_descendent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7cluster_13_hierarchical_2_hc_get_descendent[] = "\n Function returning all the descendent leaves of a set of nodes in the tree.\n\n Parameters\n ----------\n node : integer\n The node for which we want the descendents.\n\n children : list of pairs, length n_nodes\n The children of each non-leaf node. Values less than `n_samples` refer\n to leaves of the tree. A greater value `i` indicates a node with\n children `children[i - n_samples]`.\n\n n_leaves : integer\n Number of leaves.\n\n Returns\n -------\n descendent : list of int\n "; +static PyMethodDef __pyx_mdef_7sklearn_7cluster_13_hierarchical_3_hc_get_descendent = {__Pyx_NAMESTR("_hc_get_descendent"), (PyCFunction)__pyx_pw_7sklearn_7cluster_13_hierarchical_3_hc_get_descendent, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_13_hierarchical_2_hc_get_descendent)}; +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_3_hc_get_descendent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_node; + PyObject *__pyx_v_children = 0; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_n_leaves; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_hc_get_descendent (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__node,&__pyx_n_s__children,&__pyx_n_s__n_leaves,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__node)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__children)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_hc_get_descendent", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_leaves)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_hc_get_descendent", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_hc_get_descendent") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v_node = __Pyx_PyInt_from_py_Py_intptr_t(values[0]); if (unlikely((__pyx_v_node == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_children = values[1]; + __pyx_v_n_leaves = __Pyx_PyInt_from_py_Py_intptr_t(values[2]); if (unlikely((__pyx_v_n_leaves == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_hc_get_descendent", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.cluster._hierarchical._hc_get_descendent", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_2_hc_get_descendent(__pyx_self, __pyx_v_node, __pyx_v_children, __pyx_v_n_leaves); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":62 + * # Utilities for cutting and exploring a hierarchical tree + * + * def _hc_get_descendent(INTP node, children, INTP n_leaves): # <<<<<<<<<<<<<< + * """ + * Function returning all the descendent leaves of a set of nodes in the tree. + */ + +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_2_hc_get_descendent(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_node, PyObject *__pyx_v_children, __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_n_leaves) { + PyObject *__pyx_v_ind = NULL; + PyObject *__pyx_v_descendent = NULL; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_i; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_n_indices; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_hc_get_descendent", 0); + + /* "sklearn/cluster/_hierarchical.pyx":83 + * descendent : list of int + * """ + * ind = [node] # <<<<<<<<<<<<<< + * if node < n_leaves: + * return ind + */ + __pyx_t_1 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_node); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_v_ind = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":84 + * """ + * ind = [node] + * if node < n_leaves: # <<<<<<<<<<<<<< + * return ind + * descendent = [] + */ + __pyx_t_3 = ((__pyx_v_node < __pyx_v_n_leaves) != 0); + if (__pyx_t_3) { + + /* "sklearn/cluster/_hierarchical.pyx":85 + * ind = [node] + * if node < n_leaves: + * return ind # <<<<<<<<<<<<<< + * descendent = [] + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_ind)); + __pyx_r = ((PyObject *)__pyx_v_ind); + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/cluster/_hierarchical.pyx":86 + * if node < n_leaves: + * return ind + * descendent = [] # <<<<<<<<<<<<<< + * + * # It is actually faster to do the accounting of the number of + */ + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_descendent = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":91 + * # elements is the list ourselves: len is a lengthy operation on a + * # chained list + * cdef INTP i, n_indices = 1 # <<<<<<<<<<<<<< + * + * while n_indices: + */ + __pyx_v_n_indices = 1; + + /* "sklearn/cluster/_hierarchical.pyx":93 + * cdef INTP i, n_indices = 1 + * + * while n_indices: # <<<<<<<<<<<<<< + * i = ind.pop() + * if i < n_leaves: + */ + while (1) { + __pyx_t_3 = (__pyx_v_n_indices != 0); + if (!__pyx_t_3) break; + + /* "sklearn/cluster/_hierarchical.pyx":94 + * + * while n_indices: + * i = ind.pop() # <<<<<<<<<<<<<< + * if i < n_leaves: + * descendent.append(i) + */ + __pyx_t_2 = __Pyx_PyObject_Pop(((PyObject *)__pyx_v_ind)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyInt_from_py_Py_intptr_t(__pyx_t_2); if (unlikely((__pyx_t_4 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_i = __pyx_t_4; + + /* "sklearn/cluster/_hierarchical.pyx":95 + * while n_indices: + * i = ind.pop() + * if i < n_leaves: # <<<<<<<<<<<<<< + * descendent.append(i) + * n_indices -= 1 + */ + __pyx_t_3 = ((__pyx_v_i < __pyx_v_n_leaves) != 0); + if (__pyx_t_3) { + + /* "sklearn/cluster/_hierarchical.pyx":96 + * i = ind.pop() + * if i < n_leaves: + * descendent.append(i) # <<<<<<<<<<<<<< + * n_indices -= 1 + * else: + */ + __pyx_t_2 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_i); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyList_Append(__pyx_v_descendent, __pyx_t_2); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":97 + * if i < n_leaves: + * descendent.append(i) + * n_indices -= 1 # <<<<<<<<<<<<<< + * else: + * ind.extend(children[i - n_leaves]) + */ + __pyx_v_n_indices = (__pyx_v_n_indices - 1); + goto __pyx_L6; + } + /*else*/ { + + /* "sklearn/cluster/_hierarchical.pyx":99 + * n_indices -= 1 + * else: + * ind.extend(children[i - n_leaves]) # <<<<<<<<<<<<<< + * n_indices += 1 + * return descendent + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_ind), __pyx_n_s__extend); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = (__pyx_v_i - __pyx_v_n_leaves); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_children, __pyx_t_6, sizeof(int), PyInt_FromLong, 0, 1, 1); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":100 + * else: + * ind.extend(children[i - n_leaves]) + * n_indices += 1 # <<<<<<<<<<<<<< + * return descendent + * + */ + __pyx_v_n_indices = (__pyx_v_n_indices + 1); + } + __pyx_L6:; + } + + /* "sklearn/cluster/_hierarchical.pyx":101 + * ind.extend(children[i - n_leaves]) + * n_indices += 1 + * return descendent # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_descendent)); + __pyx_r = ((PyObject *)__pyx_v_descendent); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("sklearn.cluster._hierarchical._hc_get_descendent", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_ind); + __Pyx_XDECREF(__pyx_v_descendent); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_5hc_get_heads(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7cluster_13_hierarchical_4hc_get_heads[] = "Returns the heads of the forest, as defined by parents.\n\n Parameters\n ----------\n parents : array of integers\n The parent structure defining the forest (ensemble of trees)\n copy : boolean\n If copy is False, the input 'parents' array is modified inplace\n\n Returns\n -------\n heads : array of integers of same shape as parents\n The indices in the 'parents' of the tree heads\n\n "; +static PyMethodDef __pyx_mdef_7sklearn_7cluster_13_hierarchical_5hc_get_heads = {__Pyx_NAMESTR("hc_get_heads"), (PyCFunction)__pyx_pw_7sklearn_7cluster_13_hierarchical_5hc_get_heads, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_13_hierarchical_4hc_get_heads)}; +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_5hc_get_heads(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_parents = 0; + PyObject *__pyx_v_copy = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("hc_get_heads (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__parents,&__pyx_n_s__copy,0}; + PyObject* values[2] = {0,0}; + values[1] = __pyx_k_1; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__parents)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__copy); + if (value) { values[1] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "hc_get_heads") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_parents = ((PyArrayObject *)values[0]); + __pyx_v_copy = values[1]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("hc_get_heads", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.cluster._hierarchical.hc_get_heads", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_parents), __pyx_ptype_5numpy_ndarray, 1, "parents", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_4hc_get_heads(__pyx_self, __pyx_v_parents, __pyx_v_copy); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":106 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def hc_get_heads(np.ndarray[INTP, ndim=1] parents, copy=True): # <<<<<<<<<<<<<< + * """Returns the heads of the forest, as defined by parents. + * + */ + +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_4hc_get_heads(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_parents, PyObject *__pyx_v_copy) { + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_parent; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_node0; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_node; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_size; + __Pyx_LocalBuf_ND __pyx_pybuffernd_parents; + __Pyx_Buffer __pyx_pybuffer_parents; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyArrayObject *__pyx_t_5 = NULL; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_10; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_11; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_12; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_13; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("hc_get_heads", 0); + __Pyx_INCREF((PyObject *)__pyx_v_parents); + __pyx_pybuffer_parents.pybuffer.buf = NULL; + __pyx_pybuffer_parents.refcount = 0; + __pyx_pybuffernd_parents.data = NULL; + __pyx_pybuffernd_parents.rcbuffer = &__pyx_pybuffer_parents; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_parents.rcbuffer->pybuffer, (PyObject*)__pyx_v_parents, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INTP, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_parents.diminfo[0].strides = __pyx_pybuffernd_parents.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_parents.diminfo[0].shape = __pyx_pybuffernd_parents.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/cluster/_hierarchical.pyx":123 + * """ + * cdef INTP parent, node0, node, size + * if copy: # <<<<<<<<<<<<<< + * parents = np.copy(parents) + * size = parents.size + */ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_copy); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "sklearn/cluster/_hierarchical.pyx":124 + * cdef INTP parent, node0, node, size + * if copy: + * parents = np.copy(parents) # <<<<<<<<<<<<<< + * size = parents.size + * + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__copy); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_parents)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_parents)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_parents)); + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_parents.rcbuffer->pybuffer); + __pyx_t_6 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_parents.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INTP, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_6 < 0)) { + PyErr_Fetch(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_parents.rcbuffer->pybuffer, (PyObject*)__pyx_v_parents, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INTP, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_7); Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_7, __pyx_t_8, __pyx_t_9); + } + } + __pyx_pybuffernd_parents.diminfo[0].strides = __pyx_pybuffernd_parents.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_parents.diminfo[0].shape = __pyx_pybuffernd_parents.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_v_parents)); + __pyx_v_parents = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/cluster/_hierarchical.pyx":125 + * if copy: + * parents = np.copy(parents) + * size = parents.size # <<<<<<<<<<<<<< + * + * # Start from the top of the tree and go down + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_parents), __pyx_n_s__size); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_10 = __Pyx_PyInt_from_py_Py_intptr_t(__pyx_t_4); if (unlikely((__pyx_t_10 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_size = __pyx_t_10; + + /* "sklearn/cluster/_hierarchical.pyx":128 + * + * # Start from the top of the tree and go down + * for node0 in range(size - 1, -1, -1): # <<<<<<<<<<<<<< + * node = node0 + * parent = parents[node] + */ + for (__pyx_t_10 = (__pyx_v_size - 1); __pyx_t_10 > -1; __pyx_t_10-=1) { + __pyx_v_node0 = __pyx_t_10; + + /* "sklearn/cluster/_hierarchical.pyx":129 + * # Start from the top of the tree and go down + * for node0 in range(size - 1, -1, -1): + * node = node0 # <<<<<<<<<<<<<< + * parent = parents[node] + * while parent != node: + */ + __pyx_v_node = __pyx_v_node0; + + /* "sklearn/cluster/_hierarchical.pyx":130 + * for node0 in range(size - 1, -1, -1): + * node = node0 + * parent = parents[node] # <<<<<<<<<<<<<< + * while parent != node: + * parents[node0] = parent + */ + __pyx_t_11 = __pyx_v_node; + __pyx_v_parent = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INTP *, __pyx_pybuffernd_parents.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_parents.diminfo[0].strides)); + + /* "sklearn/cluster/_hierarchical.pyx":131 + * node = node0 + * parent = parents[node] + * while parent != node: # <<<<<<<<<<<<<< + * parents[node0] = parent + * node = parent + */ + while (1) { + __pyx_t_1 = ((__pyx_v_parent != __pyx_v_node) != 0); + if (!__pyx_t_1) break; + + /* "sklearn/cluster/_hierarchical.pyx":132 + * parent = parents[node] + * while parent != node: + * parents[node0] = parent # <<<<<<<<<<<<<< + * node = parent + * parent = parents[node] + */ + __pyx_t_12 = __pyx_v_node0; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INTP *, __pyx_pybuffernd_parents.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_parents.diminfo[0].strides) = __pyx_v_parent; + + /* "sklearn/cluster/_hierarchical.pyx":133 + * while parent != node: + * parents[node0] = parent + * node = parent # <<<<<<<<<<<<<< + * parent = parents[node] + * return parents + */ + __pyx_v_node = __pyx_v_parent; + + /* "sklearn/cluster/_hierarchical.pyx":134 + * parents[node0] = parent + * node = parent + * parent = parents[node] # <<<<<<<<<<<<<< + * return parents + * + */ + __pyx_t_13 = __pyx_v_node; + __pyx_v_parent = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INTP *, __pyx_pybuffernd_parents.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_parents.diminfo[0].strides)); + } + } + + /* "sklearn/cluster/_hierarchical.pyx":135 + * node = parent + * parent = parents[node] + * return parents # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_parents)); + __pyx_r = ((PyObject *)__pyx_v_parents); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_parents.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.cluster._hierarchical.hc_get_heads", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_parents.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_parents); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_7_get_parents(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7cluster_13_hierarchical_6_get_parents[] = "Returns the heads of the given nodes, as defined by parents.\n\n Modifies 'heads' and 'not_visited' in-place.\n\n Parameters\n ----------\n nodes : list of integers\n The nodes to start from\n heads : list of integers\n A list to hold the results (modified inplace)\n parents : array of integers\n The parent structure defining the tree\n not_visited\n The tree nodes to consider (modified inplace)\n\n "; +static PyMethodDef __pyx_mdef_7sklearn_7cluster_13_hierarchical_7_get_parents = {__Pyx_NAMESTR("_get_parents"), (PyCFunction)__pyx_pw_7sklearn_7cluster_13_hierarchical_7_get_parents, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_13_hierarchical_6_get_parents)}; +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_7_get_parents(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_nodes = 0; + PyObject *__pyx_v_heads = 0; + PyArrayObject *__pyx_v_parents = 0; + PyArrayObject *__pyx_v_not_visited = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_get_parents (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__nodes,&__pyx_n_s__heads,&__pyx_n_s__parents,&__pyx_n_s__not_visited,0}; + PyObject* values[4] = {0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nodes)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__heads)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_get_parents", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__parents)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_get_parents", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__not_visited)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_get_parents", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_get_parents") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + } + __pyx_v_nodes = values[0]; + __pyx_v_heads = values[1]; + __pyx_v_parents = ((PyArrayObject *)values[2]); + __pyx_v_not_visited = ((PyArrayObject *)values[3]); + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_get_parents", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.cluster._hierarchical._get_parents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_parents), __pyx_ptype_5numpy_ndarray, 1, "parents", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_not_visited), __pyx_ptype_5numpy_ndarray, 1, "not_visited", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_6_get_parents(__pyx_self, __pyx_v_nodes, __pyx_v_heads, __pyx_v_parents, __pyx_v_not_visited); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":140 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def _get_parents(nodes, heads, np.ndarray[INTP, ndim=1] parents, # <<<<<<<<<<<<<< + * np.ndarray[INT8, ndim=1, mode='c'] not_visited): + * """Returns the heads of the given nodes, as defined by parents. + */ + +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_6_get_parents(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_nodes, PyObject *__pyx_v_heads, PyArrayObject *__pyx_v_parents, PyArrayObject *__pyx_v_not_visited) { + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_parent; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_v_node; + __Pyx_LocalBuf_ND __pyx_pybuffernd_not_visited; + __Pyx_Buffer __pyx_pybuffer_not_visited; + __Pyx_LocalBuf_ND __pyx_pybuffernd_parents; + __Pyx_Buffer __pyx_pybuffer_parents; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *(*__pyx_t_3)(PyObject *); + PyObject *__pyx_t_4 = NULL; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_5; + int __pyx_t_6; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_7; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_8; + __pyx_t_7sklearn_7cluster_13_hierarchical_INTP __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_get_parents", 0); + __pyx_pybuffer_parents.pybuffer.buf = NULL; + __pyx_pybuffer_parents.refcount = 0; + __pyx_pybuffernd_parents.data = NULL; + __pyx_pybuffernd_parents.rcbuffer = &__pyx_pybuffer_parents; + __pyx_pybuffer_not_visited.pybuffer.buf = NULL; + __pyx_pybuffer_not_visited.refcount = 0; + __pyx_pybuffernd_not_visited.data = NULL; + __pyx_pybuffernd_not_visited.rcbuffer = &__pyx_pybuffer_not_visited; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_parents.rcbuffer->pybuffer, (PyObject*)__pyx_v_parents, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INTP, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_parents.diminfo[0].strides = __pyx_pybuffernd_parents.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_parents.diminfo[0].shape = __pyx_pybuffernd_parents.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_not_visited.rcbuffer->pybuffer, (PyObject*)__pyx_v_not_visited, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INT8, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_not_visited.diminfo[0].strides = __pyx_pybuffernd_not_visited.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_not_visited.diminfo[0].shape = __pyx_pybuffernd_not_visited.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/cluster/_hierarchical.pyx":160 + * cdef INTP parent, node + * + * for node in nodes: # <<<<<<<<<<<<<< + * parent = parents[node] + * while parent != node: + */ + if (PyList_CheckExact(__pyx_v_nodes) || PyTuple_CheckExact(__pyx_v_nodes)) { + __pyx_t_1 = __pyx_v_nodes; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + __pyx_t_3 = NULL; + } else { + __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_nodes); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = Py_TYPE(__pyx_t_1)->tp_iternext; + } + for (;;) { + if (!__pyx_t_3 && PyList_CheckExact(__pyx_t_1)) { + if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_4 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_3 && PyTuple_CheckExact(__pyx_t_1)) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_4 = __pyx_t_3(__pyx_t_1); + if (unlikely(!__pyx_t_4)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_4); + } + __pyx_t_5 = __Pyx_PyInt_from_py_Py_intptr_t(__pyx_t_4); if (unlikely((__pyx_t_5 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_node = __pyx_t_5; + + /* "sklearn/cluster/_hierarchical.pyx":161 + * + * for node in nodes: + * parent = parents[node] # <<<<<<<<<<<<<< + * while parent != node: + * node = parent + */ + __pyx_t_5 = __pyx_v_node; + __pyx_v_parent = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INTP *, __pyx_pybuffernd_parents.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_parents.diminfo[0].strides)); + + /* "sklearn/cluster/_hierarchical.pyx":162 + * for node in nodes: + * parent = parents[node] + * while parent != node: # <<<<<<<<<<<<<< + * node = parent + * parent = parents[node] + */ + while (1) { + __pyx_t_6 = ((__pyx_v_parent != __pyx_v_node) != 0); + if (!__pyx_t_6) break; + + /* "sklearn/cluster/_hierarchical.pyx":163 + * parent = parents[node] + * while parent != node: + * node = parent # <<<<<<<<<<<<<< + * parent = parents[node] + * if not_visited[node]: + */ + __pyx_v_node = __pyx_v_parent; + + /* "sklearn/cluster/_hierarchical.pyx":164 + * while parent != node: + * node = parent + * parent = parents[node] # <<<<<<<<<<<<<< + * if not_visited[node]: + * not_visited[node] = 0 + */ + __pyx_t_7 = __pyx_v_node; + __pyx_v_parent = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INTP *, __pyx_pybuffernd_parents.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_parents.diminfo[0].strides)); + } + + /* "sklearn/cluster/_hierarchical.pyx":165 + * node = parent + * parent = parents[node] + * if not_visited[node]: # <<<<<<<<<<<<<< + * not_visited[node] = 0 + * heads.append(node) + */ + __pyx_t_8 = __pyx_v_node; + __pyx_t_6 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INT8 *, __pyx_pybuffernd_not_visited.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_not_visited.diminfo[0].strides)) != 0); + if (__pyx_t_6) { + + /* "sklearn/cluster/_hierarchical.pyx":166 + * parent = parents[node] + * if not_visited[node]: + * not_visited[node] = 0 # <<<<<<<<<<<<<< + * heads.append(node) + * return heads + */ + __pyx_t_9 = __pyx_v_node; + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INT8 *, __pyx_pybuffernd_not_visited.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_not_visited.diminfo[0].strides) = 0; + + /* "sklearn/cluster/_hierarchical.pyx":167 + * if not_visited[node]: + * not_visited[node] = 0 + * heads.append(node) # <<<<<<<<<<<<<< + * return heads + * + */ + __pyx_t_4 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_node); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_10 = __Pyx_PyObject_Append(__pyx_v_heads, __pyx_t_4); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + goto __pyx_L7; + } + __pyx_L7:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":168 + * not_visited[node] = 0 + * heads.append(node) + * return heads # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_heads); + __pyx_r = __pyx_v_heads; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_10); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_not_visited.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_parents.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.cluster._hierarchical._get_parents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_not_visited.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_parents.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_9max_merge(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7cluster_13_hierarchical_8max_merge[] = "Merge two IntFloatDicts with the max strategy: when the same key is\n present in the two dicts, the max of the two values is used.\n\n Parameters\n ==========\n a, b : IntFloatDict object\n The IntFloatDicts to merge\n mask : ndarray array of dtype integer and of dimension 1\n a mask for keys to ignore: if not mask[key] the corresponding key\n is skipped in the output dictionnary\n n_a, n_b : float\n n_a and n_b are weights for a and b for the merge strategy.\n They are not used in the case of a max merge.\n\n Returns\n =======\n out : IntFloatDict object\n The IntFloatDict resulting from the merge\n "; +static PyMethodDef __pyx_mdef_7sklearn_7cluster_13_hierarchical_9max_merge = {__Pyx_NAMESTR("max_merge"), (PyCFunction)__pyx_pw_7sklearn_7cluster_13_hierarchical_9max_merge, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_13_hierarchical_8max_merge)}; +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_9max_merge(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_a = 0; + struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_b = 0; + PyArrayObject *__pyx_v_mask = 0; + CYTHON_UNUSED __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_a; + CYTHON_UNUSED __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_b; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("max_merge (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__a,&__pyx_n_s__b,&__pyx_n_s__mask,&__pyx_n_s__n_a,&__pyx_n_s__n_b,0}; + PyObject* values[5] = {0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__a)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__b)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("max_merge", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__mask)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("max_merge", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_a)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("max_merge", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_b)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("max_merge", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "max_merge") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + } + __pyx_v_a = ((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)values[0]); + __pyx_v_b = ((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)values[1]); + __pyx_v_mask = ((PyArrayObject *)values[2]); + __pyx_v_n_a = __Pyx_PyInt_from_py_Py_intptr_t(values[3]); if (unlikely((__pyx_v_n_a == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_b = __Pyx_PyInt_from_py_Py_intptr_t(values[4]); if (unlikely((__pyx_v_n_b == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("max_merge", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.cluster._hierarchical.max_merge", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_a), __pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict, 1, "a", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_b), __pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict, 1, "b", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_mask), __pyx_ptype_5numpy_ndarray, 1, "mask", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_8max_merge(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_mask, __pyx_v_n_a, __pyx_v_n_b); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":181 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def max_merge(IntFloatDict a, IntFloatDict b, # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1] mask, + * ITYPE_t n_a, ITYPE_t n_b): + */ + +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_8max_merge(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_a, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_b, PyArrayObject *__pyx_v_mask, CYTHON_UNUSED __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_a, CYTHON_UNUSED __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_b) { + struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_out_obj = 0; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_a_it; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_a_end; + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_key; + __pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t __pyx_v_value; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_out_it; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_out_end; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_b_it; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_b_end; + __Pyx_LocalBuf_ND __pyx_pybuffernd_mask; + __Pyx_Buffer __pyx_pybuffer_mask; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_t_3; + __pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t __pyx_t_4; + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("max_merge", 0); + __pyx_pybuffer_mask.pybuffer.buf = NULL; + __pyx_pybuffer_mask.refcount = 0; + __pyx_pybuffernd_mask.data = NULL; + __pyx_pybuffernd_mask.rcbuffer = &__pyx_pybuffer_mask; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_mask.rcbuffer->pybuffer, (PyObject*)__pyx_v_mask, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_mask.diminfo[0].strides = __pyx_pybuffernd_mask.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_mask.diminfo[0].shape = __pyx_pybuffernd_mask.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/cluster/_hierarchical.pyx":203 + * The IntFloatDict resulting from the merge + * """ + * cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_it = a.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_end = a.my_map.end() + */ + __pyx_t_1 = __Pyx_tp_new(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict)), __pyx_empty_tuple); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict)))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_out_obj = ((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":204 + * """ + * cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_it = a.my_map.begin() # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_end = a.my_map.end() + * cdef ITYPE_t key + */ + __pyx_v_a_it = __pyx_v_a->my_map.begin(); + + /* "sklearn/cluster/_hierarchical.pyx":205 + * cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_it = a.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_end = a.my_map.end() # <<<<<<<<<<<<<< + * cdef ITYPE_t key + * cdef DTYPE_t value + */ + __pyx_v_a_end = __pyx_v_a->my_map.end(); + + /* "sklearn/cluster/_hierarchical.pyx":209 + * cdef DTYPE_t value + * # First copy a into out + * while a_it != a_end: # <<<<<<<<<<<<<< + * key = deref(a_it).first + * if mask[key]: + */ + while (1) { + __pyx_t_2 = ((__pyx_v_a_it != __pyx_v_a_end) != 0); + if (!__pyx_t_2) break; + + /* "sklearn/cluster/_hierarchical.pyx":210 + * # First copy a into out + * while a_it != a_end: + * key = deref(a_it).first # <<<<<<<<<<<<<< + * if mask[key]: + * out_obj.my_map[key] = deref(a_it).second + */ + __pyx_t_3 = (*__pyx_v_a_it).first; + __pyx_v_key = __pyx_t_3; + + /* "sklearn/cluster/_hierarchical.pyx":211 + * while a_it != a_end: + * key = deref(a_it).first + * if mask[key]: # <<<<<<<<<<<<<< + * out_obj.my_map[key] = deref(a_it).second + * inc(a_it) + */ + __pyx_t_3 = __pyx_v_key; + __pyx_t_2 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t *, __pyx_pybuffernd_mask.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_mask.diminfo[0].strides)) != 0); + if (__pyx_t_2) { + + /* "sklearn/cluster/_hierarchical.pyx":212 + * key = deref(a_it).first + * if mask[key]: + * out_obj.my_map[key] = deref(a_it).second # <<<<<<<<<<<<<< + * inc(a_it) + * + */ + __pyx_t_4 = (*__pyx_v_a_it).second; + (__pyx_v_out_obj->my_map[__pyx_v_key]) = __pyx_t_4; + goto __pyx_L5; + } + __pyx_L5:; + + /* "sklearn/cluster/_hierarchical.pyx":213 + * if mask[key]: + * out_obj.my_map[key] = deref(a_it).second + * inc(a_it) # <<<<<<<<<<<<<< + * + * # Then merge b into out + */ + (++__pyx_v_a_it); + } + + /* "sklearn/cluster/_hierarchical.pyx":216 + * + * # Then merge b into out + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_it = out_obj.my_map.begin() # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_end = out_obj.my_map.end() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() + */ + __pyx_v_out_it = __pyx_v_out_obj->my_map.begin(); + + /* "sklearn/cluster/_hierarchical.pyx":217 + * # Then merge b into out + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_it = out_obj.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_end = out_obj.my_map.end() # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() + */ + __pyx_v_out_end = __pyx_v_out_obj->my_map.end(); + + /* "sklearn/cluster/_hierarchical.pyx":218 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_it = out_obj.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_end = out_obj.my_map.end() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() + * while b_it != b_end: + */ + __pyx_v_b_it = __pyx_v_b->my_map.begin(); + + /* "sklearn/cluster/_hierarchical.pyx":219 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_end = out_obj.my_map.end() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() # <<<<<<<<<<<<<< + * while b_it != b_end: + * key = deref(b_it).first + */ + __pyx_v_b_end = __pyx_v_b->my_map.end(); + + /* "sklearn/cluster/_hierarchical.pyx":220 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() + * while b_it != b_end: # <<<<<<<<<<<<<< + * key = deref(b_it).first + * value = deref(b_it).second + */ + while (1) { + __pyx_t_2 = ((__pyx_v_b_it != __pyx_v_b_end) != 0); + if (!__pyx_t_2) break; + + /* "sklearn/cluster/_hierarchical.pyx":221 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() + * while b_it != b_end: + * key = deref(b_it).first # <<<<<<<<<<<<<< + * value = deref(b_it).second + * if mask[key]: + */ + __pyx_t_5 = (*__pyx_v_b_it).first; + __pyx_v_key = __pyx_t_5; + + /* "sklearn/cluster/_hierarchical.pyx":222 + * while b_it != b_end: + * key = deref(b_it).first + * value = deref(b_it).second # <<<<<<<<<<<<<< + * if mask[key]: + * out_it = out_obj.my_map.find(key) + */ + __pyx_t_4 = (*__pyx_v_b_it).second; + __pyx_v_value = __pyx_t_4; + + /* "sklearn/cluster/_hierarchical.pyx":223 + * key = deref(b_it).first + * value = deref(b_it).second + * if mask[key]: # <<<<<<<<<<<<<< + * out_it = out_obj.my_map.find(key) + * if out_it == out_end: + */ + __pyx_t_5 = __pyx_v_key; + __pyx_t_2 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t *, __pyx_pybuffernd_mask.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_mask.diminfo[0].strides)) != 0); + if (__pyx_t_2) { + + /* "sklearn/cluster/_hierarchical.pyx":224 + * value = deref(b_it).second + * if mask[key]: + * out_it = out_obj.my_map.find(key) # <<<<<<<<<<<<<< + * if out_it == out_end: + * # Key not found + */ + __pyx_v_out_it = __pyx_v_out_obj->my_map.find(__pyx_v_key); + + /* "sklearn/cluster/_hierarchical.pyx":225 + * if mask[key]: + * out_it = out_obj.my_map.find(key) + * if out_it == out_end: # <<<<<<<<<<<<<< + * # Key not found + * out_obj.my_map[key] = value + */ + __pyx_t_2 = ((__pyx_v_out_it == __pyx_v_out_end) != 0); + if (__pyx_t_2) { + + /* "sklearn/cluster/_hierarchical.pyx":227 + * if out_it == out_end: + * # Key not found + * out_obj.my_map[key] = value # <<<<<<<<<<<<<< + * else: + * deref(out_it).second = fmax(deref(out_it).second, value) + */ + (__pyx_v_out_obj->my_map[__pyx_v_key]) = __pyx_v_value; + goto __pyx_L9; + } + /*else*/ { + + /* "sklearn/cluster/_hierarchical.pyx":229 + * out_obj.my_map[key] = value + * else: + * deref(out_it).second = fmax(deref(out_it).second, value) # <<<<<<<<<<<<<< + * inc(b_it) + * return out_obj + */ + (*__pyx_v_out_it).second = __pyx_f_7sklearn_7cluster_13_hierarchical_fmax((*__pyx_v_out_it).second, __pyx_v_value); + } + __pyx_L9:; + goto __pyx_L8; + } + __pyx_L8:; + + /* "sklearn/cluster/_hierarchical.pyx":230 + * else: + * deref(out_it).second = fmax(deref(out_it).second, value) + * inc(b_it) # <<<<<<<<<<<<<< + * return out_obj + * + */ + (++__pyx_v_b_it); + } + + /* "sklearn/cluster/_hierarchical.pyx":231 + * deref(out_it).second = fmax(deref(out_it).second, value) + * inc(b_it) + * return out_obj # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_out_obj)); + __pyx_r = ((PyObject *)__pyx_v_out_obj); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mask.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.cluster._hierarchical.max_merge", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mask.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_out_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_11average_merge(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7cluster_13_hierarchical_10average_merge[] = "Merge two IntFloatDicts with the average strategy: when the \n same key is present in the two dicts, the weighted average of the two \n values is used.\n\n Parameters\n ==========\n a, b : IntFloatDict object\n The IntFloatDicts to merge\n mask : ndarray array of dtype integer and of dimension 1\n a mask for keys to ignore: if not mask[key] the corresponding key\n is skipped in the output dictionnary\n n_a, n_b : float\n n_a and n_b are weights for a and b for the merge strategy.\n They are used for a weighted mean.\n\n Returns\n =======\n out : IntFloatDict object\n The IntFloatDict resulting from the merge\n "; +static PyMethodDef __pyx_mdef_7sklearn_7cluster_13_hierarchical_11average_merge = {__Pyx_NAMESTR("average_merge"), (PyCFunction)__pyx_pw_7sklearn_7cluster_13_hierarchical_11average_merge, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_13_hierarchical_10average_merge)}; +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_11average_merge(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_a = 0; + struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_b = 0; + PyArrayObject *__pyx_v_mask = 0; + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_a; + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_b; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("average_merge (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__a,&__pyx_n_s__b,&__pyx_n_s__mask,&__pyx_n_s__n_a,&__pyx_n_s__n_b,0}; + PyObject* values[5] = {0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__a)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__b)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_merge", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__mask)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_merge", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_a)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_merge", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_b)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_merge", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "average_merge") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + } + __pyx_v_a = ((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)values[0]); + __pyx_v_b = ((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)values[1]); + __pyx_v_mask = ((PyArrayObject *)values[2]); + __pyx_v_n_a = __Pyx_PyInt_from_py_Py_intptr_t(values[3]); if (unlikely((__pyx_v_n_a == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_b = __Pyx_PyInt_from_py_Py_intptr_t(values[4]); if (unlikely((__pyx_v_n_b == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("average_merge", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.cluster._hierarchical.average_merge", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_a), __pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict, 1, "a", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_b), __pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict, 1, "b", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_mask), __pyx_ptype_5numpy_ndarray, 1, "mask", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 237; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_10average_merge(__pyx_self, __pyx_v_a, __pyx_v_b, __pyx_v_mask, __pyx_v_n_a, __pyx_v_n_b); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":236 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def average_merge(IntFloatDict a, IntFloatDict b, # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1] mask, + * ITYPE_t n_a, ITYPE_t n_b): + */ + +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_10average_merge(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_a, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_b, PyArrayObject *__pyx_v_mask, __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_a, __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_n_b) { + struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_out_obj = 0; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_a_it; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_a_end; + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_key; + __pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t __pyx_v_value; + __pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t __pyx_v_n_out; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_out_it; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_out_end; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_b_it; + std::map<__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t,__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t>::iterator __pyx_v_b_end; + __Pyx_LocalBuf_ND __pyx_pybuffernd_mask; + __Pyx_Buffer __pyx_pybuffer_mask; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_t_3; + __pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t __pyx_t_4; + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("average_merge", 0); + __pyx_pybuffer_mask.pybuffer.buf = NULL; + __pyx_pybuffer_mask.refcount = 0; + __pyx_pybuffernd_mask.data = NULL; + __pyx_pybuffernd_mask.rcbuffer = &__pyx_pybuffer_mask; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_mask.rcbuffer->pybuffer, (PyObject*)__pyx_v_mask, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_mask.diminfo[0].strides = __pyx_pybuffernd_mask.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_mask.diminfo[0].shape = __pyx_pybuffernd_mask.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/cluster/_hierarchical.pyx":259 + * The IntFloatDict resulting from the merge + * """ + * cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_it = a.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_end = a.my_map.end() + */ + __pyx_t_1 = __Pyx_tp_new(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict)), __pyx_empty_tuple); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 259; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict)))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 259; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_out_obj = ((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":260 + * """ + * cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_it = a.my_map.begin() # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_end = a.my_map.end() + * cdef ITYPE_t key + */ + __pyx_v_a_it = __pyx_v_a->my_map.begin(); + + /* "sklearn/cluster/_hierarchical.pyx":261 + * cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_it = a.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_end = a.my_map.end() # <<<<<<<<<<<<<< + * cdef ITYPE_t key + * cdef DTYPE_t value + */ + __pyx_v_a_end = __pyx_v_a->my_map.end(); + + /* "sklearn/cluster/_hierarchical.pyx":264 + * cdef ITYPE_t key + * cdef DTYPE_t value + * cdef DTYPE_t n_out = (n_a + n_b) # <<<<<<<<<<<<<< + * # First copy a into out + * while a_it != a_end: + */ + __pyx_v_n_out = ((__pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t)(__pyx_v_n_a + __pyx_v_n_b)); + + /* "sklearn/cluster/_hierarchical.pyx":266 + * cdef DTYPE_t n_out = (n_a + n_b) + * # First copy a into out + * while a_it != a_end: # <<<<<<<<<<<<<< + * key = deref(a_it).first + * if mask[key]: + */ + while (1) { + __pyx_t_2 = ((__pyx_v_a_it != __pyx_v_a_end) != 0); + if (!__pyx_t_2) break; + + /* "sklearn/cluster/_hierarchical.pyx":267 + * # First copy a into out + * while a_it != a_end: + * key = deref(a_it).first # <<<<<<<<<<<<<< + * if mask[key]: + * out_obj.my_map[key] = deref(a_it).second + */ + __pyx_t_3 = (*__pyx_v_a_it).first; + __pyx_v_key = __pyx_t_3; + + /* "sklearn/cluster/_hierarchical.pyx":268 + * while a_it != a_end: + * key = deref(a_it).first + * if mask[key]: # <<<<<<<<<<<<<< + * out_obj.my_map[key] = deref(a_it).second + * inc(a_it) + */ + __pyx_t_3 = __pyx_v_key; + __pyx_t_2 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t *, __pyx_pybuffernd_mask.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_mask.diminfo[0].strides)) != 0); + if (__pyx_t_2) { + + /* "sklearn/cluster/_hierarchical.pyx":269 + * key = deref(a_it).first + * if mask[key]: + * out_obj.my_map[key] = deref(a_it).second # <<<<<<<<<<<<<< + * inc(a_it) + * + */ + __pyx_t_4 = (*__pyx_v_a_it).second; + (__pyx_v_out_obj->my_map[__pyx_v_key]) = __pyx_t_4; + goto __pyx_L5; + } + __pyx_L5:; + + /* "sklearn/cluster/_hierarchical.pyx":270 + * if mask[key]: + * out_obj.my_map[key] = deref(a_it).second + * inc(a_it) # <<<<<<<<<<<<<< + * + * # Then merge b into out + */ + (++__pyx_v_a_it); + } + + /* "sklearn/cluster/_hierarchical.pyx":273 + * + * # Then merge b into out + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_it = out_obj.my_map.begin() # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_end = out_obj.my_map.end() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() + */ + __pyx_v_out_it = __pyx_v_out_obj->my_map.begin(); + + /* "sklearn/cluster/_hierarchical.pyx":274 + * # Then merge b into out + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_it = out_obj.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_end = out_obj.my_map.end() # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() + */ + __pyx_v_out_end = __pyx_v_out_obj->my_map.end(); + + /* "sklearn/cluster/_hierarchical.pyx":275 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_it = out_obj.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_end = out_obj.my_map.end() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() + * while b_it != b_end: + */ + __pyx_v_b_it = __pyx_v_b->my_map.begin(); + + /* "sklearn/cluster/_hierarchical.pyx":276 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_end = out_obj.my_map.end() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() # <<<<<<<<<<<<<< + * while b_it != b_end: + * key = deref(b_it).first + */ + __pyx_v_b_end = __pyx_v_b->my_map.end(); + + /* "sklearn/cluster/_hierarchical.pyx":277 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() + * while b_it != b_end: # <<<<<<<<<<<<<< + * key = deref(b_it).first + * value = deref(b_it).second + */ + while (1) { + __pyx_t_2 = ((__pyx_v_b_it != __pyx_v_b_end) != 0); + if (!__pyx_t_2) break; + + /* "sklearn/cluster/_hierarchical.pyx":278 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() + * while b_it != b_end: + * key = deref(b_it).first # <<<<<<<<<<<<<< + * value = deref(b_it).second + * if mask[key]: + */ + __pyx_t_5 = (*__pyx_v_b_it).first; + __pyx_v_key = __pyx_t_5; + + /* "sklearn/cluster/_hierarchical.pyx":279 + * while b_it != b_end: + * key = deref(b_it).first + * value = deref(b_it).second # <<<<<<<<<<<<<< + * if mask[key]: + * out_it = out_obj.my_map.find(key) + */ + __pyx_t_4 = (*__pyx_v_b_it).second; + __pyx_v_value = __pyx_t_4; + + /* "sklearn/cluster/_hierarchical.pyx":280 + * key = deref(b_it).first + * value = deref(b_it).second + * if mask[key]: # <<<<<<<<<<<<<< + * out_it = out_obj.my_map.find(key) + * if out_it == out_end: + */ + __pyx_t_5 = __pyx_v_key; + __pyx_t_2 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t *, __pyx_pybuffernd_mask.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_mask.diminfo[0].strides)) != 0); + if (__pyx_t_2) { + + /* "sklearn/cluster/_hierarchical.pyx":281 + * value = deref(b_it).second + * if mask[key]: + * out_it = out_obj.my_map.find(key) # <<<<<<<<<<<<<< + * if out_it == out_end: + * # Key not found + */ + __pyx_v_out_it = __pyx_v_out_obj->my_map.find(__pyx_v_key); + + /* "sklearn/cluster/_hierarchical.pyx":282 + * if mask[key]: + * out_it = out_obj.my_map.find(key) + * if out_it == out_end: # <<<<<<<<<<<<<< + * # Key not found + * out_obj.my_map[key] = value + */ + __pyx_t_2 = ((__pyx_v_out_it == __pyx_v_out_end) != 0); + if (__pyx_t_2) { + + /* "sklearn/cluster/_hierarchical.pyx":284 + * if out_it == out_end: + * # Key not found + * out_obj.my_map[key] = value # <<<<<<<<<<<<<< + * else: + * deref(out_it).second = (n_a * deref(out_it).second + */ + (__pyx_v_out_obj->my_map[__pyx_v_key]) = __pyx_v_value; + goto __pyx_L9; + } + /*else*/ { + + /* "sklearn/cluster/_hierarchical.pyx":287 + * else: + * deref(out_it).second = (n_a * deref(out_it).second + * + n_b * value) / n_out # <<<<<<<<<<<<<< + * inc(b_it) + * return out_obj + */ + __pyx_t_4 = ((__pyx_v_n_a * (*__pyx_v_out_it).second) + (__pyx_v_n_b * __pyx_v_value)); + if (unlikely(__pyx_v_n_out == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_ZeroDivisionError, "float division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/cluster/_hierarchical.pyx":286 + * out_obj.my_map[key] = value + * else: + * deref(out_it).second = (n_a * deref(out_it).second # <<<<<<<<<<<<<< + * + n_b * value) / n_out + * inc(b_it) + */ + (*__pyx_v_out_it).second = (__pyx_t_4 / __pyx_v_n_out); + } + __pyx_L9:; + goto __pyx_L8; + } + __pyx_L8:; + + /* "sklearn/cluster/_hierarchical.pyx":288 + * deref(out_it).second = (n_a * deref(out_it).second + * + n_b * value) / n_out + * inc(b_it) # <<<<<<<<<<<<<< + * return out_obj + * + */ + (++__pyx_v_b_it); + } + + /* "sklearn/cluster/_hierarchical.pyx":289 + * + n_b * value) / n_out + * inc(b_it) + * return out_obj # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_out_obj)); + __pyx_r = ((PyObject *)__pyx_v_out_obj); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mask.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.cluster._hierarchical.average_merge", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mask.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_out_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t __pyx_v_weight; + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_a; + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_b; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__weight,&__pyx_n_s__a,&__pyx_n_s__b,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__a)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__b)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v_weight = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_weight == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_a = __Pyx_PyInt_from_py_Py_intptr_t(values[1]); if (unlikely((__pyx_v_a == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_b = __Pyx_PyInt_from_py_Py_intptr_t(values[2]); if (unlikely((__pyx_v_b == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.cluster._hierarchical.WeightedEdge.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge___init__(((struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *)__pyx_v_self), __pyx_v_weight, __pyx_v_a, __pyx_v_b); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":300 + * cdef public DTYPE_t weight + * + * def __init__(self, DTYPE_t weight, ITYPE_t a, ITYPE_t b): # <<<<<<<<<<<<<< + * self.weight = weight + * self.a = a + */ + +static int __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge___init__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self, __pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t __pyx_v_weight, __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_a, __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_v_b) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/cluster/_hierarchical.pyx":301 + * + * def __init__(self, DTYPE_t weight, ITYPE_t a, ITYPE_t b): + * self.weight = weight # <<<<<<<<<<<<<< + * self.a = a + * self.b = b + */ + __pyx_v_self->weight = __pyx_v_weight; + + /* "sklearn/cluster/_hierarchical.pyx":302 + * def __init__(self, DTYPE_t weight, ITYPE_t a, ITYPE_t b): + * self.weight = weight + * self.a = a # <<<<<<<<<<<<<< + * self.b = b + * + */ + __pyx_v_self->a = __pyx_v_a; + + /* "sklearn/cluster/_hierarchical.pyx":303 + * self.weight = weight + * self.a = a + * self.b = b # <<<<<<<<<<<<<< + * + * @cython.nonecheck(False) + */ + __pyx_v_self->b = __pyx_v_b; + + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_3__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, int __pyx_v_op); /*proto*/ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_3__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, int __pyx_v_op) { + CYTHON_UNUSED int __pyx_lineno = 0; + CYTHON_UNUSED const char *__pyx_filename = NULL; + CYTHON_UNUSED int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__richcmp__ (wrapper)", 0); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_other), __pyx_ptype_7sklearn_7cluster_13_hierarchical_WeightedEdge, 1, "other", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 306; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_2__richcmp__(((PyObject *)__pyx_v_self), ((struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *)__pyx_v_other), ((int)__pyx_v_op)); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":306 + * + * @cython.nonecheck(False) + * def __richcmp__(self, WeightedEdge other, int op): # <<<<<<<<<<<<<< + * """Cython-specific comparison method. + * + */ + +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_2__richcmp__(PyObject *__pyx_v_self, struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_other, int __pyx_v_op) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__richcmp__", 0); + + /* "sklearn/cluster/_hierarchical.pyx":327 + * elif op == 4: + * return self.weight > other.weight + * elif op == 5: # <<<<<<<<<<<<<< + * return self.weight >= other.weight + * + */ + switch (__pyx_v_op) { + + /* "sklearn/cluster/_hierarchical.pyx":317 + * >= 5 + * """ + * if op == 0: # <<<<<<<<<<<<<< + * return self.weight < other.weight + * elif op == 1: + */ + case 0: + + /* "sklearn/cluster/_hierarchical.pyx":318 + * """ + * if op == 0: + * return self.weight < other.weight # <<<<<<<<<<<<<< + * elif op == 1: + * return self.weight <= other.weight + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__weight); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 318; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_other->weight); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 318; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_1, __pyx_t_2, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 318; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + break; + + /* "sklearn/cluster/_hierarchical.pyx":319 + * if op == 0: + * return self.weight < other.weight + * elif op == 1: # <<<<<<<<<<<<<< + * return self.weight <= other.weight + * elif op == 2: + */ + case 1: + + /* "sklearn/cluster/_hierarchical.pyx":320 + * return self.weight < other.weight + * elif op == 1: + * return self.weight <= other.weight # <<<<<<<<<<<<<< + * elif op == 2: + * return self.weight == other.weight + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__weight); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_other->weight); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyObject_RichCompare(__pyx_t_3, __pyx_t_2, Py_LE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + break; + + /* "sklearn/cluster/_hierarchical.pyx":321 + * elif op == 1: + * return self.weight <= other.weight + * elif op == 2: # <<<<<<<<<<<<<< + * return self.weight == other.weight + * elif op == 3: + */ + case 2: + + /* "sklearn/cluster/_hierarchical.pyx":322 + * return self.weight <= other.weight + * elif op == 2: + * return self.weight == other.weight # <<<<<<<<<<<<<< + * elif op == 3: + * return self.weight != other.weight + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__weight); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_other->weight); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_1, __pyx_t_2, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + break; + + /* "sklearn/cluster/_hierarchical.pyx":323 + * elif op == 2: + * return self.weight == other.weight + * elif op == 3: # <<<<<<<<<<<<<< + * return self.weight != other.weight + * elif op == 4: + */ + case 3: + + /* "sklearn/cluster/_hierarchical.pyx":324 + * return self.weight == other.weight + * elif op == 3: + * return self.weight != other.weight # <<<<<<<<<<<<<< + * elif op == 4: + * return self.weight > other.weight + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__weight); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_other->weight); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyObject_RichCompare(__pyx_t_3, __pyx_t_2, Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + break; + + /* "sklearn/cluster/_hierarchical.pyx":325 + * elif op == 3: + * return self.weight != other.weight + * elif op == 4: # <<<<<<<<<<<<<< + * return self.weight > other.weight + * elif op == 5: + */ + case 4: + + /* "sklearn/cluster/_hierarchical.pyx":326 + * return self.weight != other.weight + * elif op == 4: + * return self.weight > other.weight # <<<<<<<<<<<<<< + * elif op == 5: + * return self.weight >= other.weight + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__weight); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_other->weight); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_1, __pyx_t_2, Py_GT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + break; + + /* "sklearn/cluster/_hierarchical.pyx":327 + * elif op == 4: + * return self.weight > other.weight + * elif op == 5: # <<<<<<<<<<<<<< + * return self.weight >= other.weight + * + */ + case 5: + + /* "sklearn/cluster/_hierarchical.pyx":328 + * return self.weight > other.weight + * elif op == 5: + * return self.weight >= other.weight # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__weight); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_other->weight); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyObject_RichCompare(__pyx_t_3, __pyx_t_2, Py_GE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + break; + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.cluster._hierarchical.WeightedEdge.__richcmp__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_5__repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_5__repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_4__repr__(((struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":330 + * return self.weight >= other.weight + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "%s(weight=%f, a=%i, b=%i)" % (self.__class__.__name__, + * self.weight, + */ + +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_4__repr__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "sklearn/cluster/_hierarchical.pyx":331 + * + * def __repr__(self): + * return "%s(weight=%f, a=%i, b=%i)" % (self.__class__.__name__, # <<<<<<<<<<<<<< + * self.weight, + * self.a, self.b) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s____class__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s____name__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":332 + * def __repr__(self): + * return "%s(weight=%f, a=%i, b=%i)" % (self.__class__.__name__, + * self.weight, # <<<<<<<<<<<<<< + * self.a, self.b) + * + */ + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->weight); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 332; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "sklearn/cluster/_hierarchical.pyx":333 + * return "%s(weight=%f, a=%i, b=%i)" % (self.__class__.__name__, + * self.weight, + * self.a, self.b) # <<<<<<<<<<<<<< + * + */ + __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_self->a); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 333; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_self->b); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 333; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_2), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_r = ((PyObject *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("sklearn.cluster._hierarchical.WeightedEdge.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a___get__(((struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":296 + * + * cdef class WeightedEdge: + * cdef public ITYPE_t a # <<<<<<<<<<<<<< + * cdef public ITYPE_t b + * cdef public DTYPE_t weight + */ + +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a___get__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_self->a); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.cluster._hierarchical.WeightedEdge.a.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a_2__set__(((struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a_2__set__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyInt_from_py_Py_intptr_t(__pyx_v_value); if (unlikely((__pyx_t_1 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->a = __pyx_t_1; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.cluster._hierarchical.WeightedEdge.a.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b___get__(((struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":297 + * cdef class WeightedEdge: + * cdef public ITYPE_t a + * cdef public ITYPE_t b # <<<<<<<<<<<<<< + * cdef public DTYPE_t weight + * + */ + +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b___get__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_self->b); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.cluster._hierarchical.WeightedEdge.b.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b_2__set__(((struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b_2__set__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_7cluster_13_hierarchical_ITYPE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyInt_from_py_Py_intptr_t(__pyx_v_value); if (unlikely((__pyx_t_1 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->b = __pyx_t_1; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.cluster._hierarchical.WeightedEdge.b.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight___get__(((struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/cluster/_hierarchical.pyx":298 + * cdef public ITYPE_t a + * cdef public ITYPE_t b + * cdef public DTYPE_t weight # <<<<<<<<<<<<<< + * + * def __init__(self, DTYPE_t weight, ITYPE_t a, ITYPE_t b): + */ + +static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight___get__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->weight); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.cluster._hierarchical.WeightedEdge.weight.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight_2__set__(((struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight_2__set__(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_7cluster_13_hierarchical_DTYPE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __pyx_PyFloat_AsDouble(__pyx_v_value); if (unlikely((__pyx_t_1 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->weight = __pyx_t_1; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.cluster._hierarchical.WeightedEdge.weight.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "numpy.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "numpy.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "numpy.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "numpy.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "numpy.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "numpy.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_3) { + + /* "numpy.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "numpy.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "numpy.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "numpy.pxd":222 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "numpy.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { + + /* "numpy.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "numpy.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "numpy.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "numpy.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "numpy.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "numpy.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "numpy.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "numpy.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "numpy.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "numpy.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "numpy.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "numpy.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "numpy.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "numpy.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "numpy.pxd":251 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "numpy.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; + + /* "numpy.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); + if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "numpy.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_1) { + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "numpy.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k__b; + break; + + /* "numpy.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k__B; + break; + + /* "numpy.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k__h; + break; + + /* "numpy.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k__H; + break; + + /* "numpy.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k__i; + break; + + /* "numpy.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k__I; + break; + + /* "numpy.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k__l; + break; + + /* "numpy.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k__L; + break; + + /* "numpy.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k__q; + break; + + /* "numpy.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k__Q; + break; + + /* "numpy.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k__f; + break; + + /* "numpy.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k__d; + break; + + /* "numpy.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k__g; + break; + + /* "numpy.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k__Zf; + break; + + /* "numpy.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k__Zd; + break; + + /* "numpy.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k__Zg; + break; + + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k__O; + break; + default: + + /* "numpy.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_9), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "numpy.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "numpy.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "numpy.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "numpy.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "numpy.pxd":285 + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + * &offset) # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "numpy.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + __pyx_L11:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "numpy.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "numpy.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "numpy.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "numpy.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "numpy.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "numpy.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + long __pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "numpy.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF(__pyx_v_childname); + __pyx_v_childname = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); + __pyx_v_fields = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "numpy.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { + PyObject* sequence = ((PyObject *)__pyx_v_fields); + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_child)); + __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_v_new_offset); + __pyx_v_new_offset = __pyx_t_4; + __pyx_t_4 = 0; + + /* "numpy.pxd":798 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + + /* "numpy.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + + /* "numpy.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_7) { + __pyx_t_8 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_8 = __pyx_t_7; + } + if (!__pyx_t_8) { + + /* "numpy.pxd":802 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + __pyx_t_9 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_10 = __pyx_t_9; + } else { + __pyx_t_10 = __pyx_t_7; + } + __pyx_t_7 = __pyx_t_10; + } else { + __pyx_t_7 = __pyx_t_8; + } + if (__pyx_t_7) { + + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + + /* "numpy.pxd":813 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_7) break; + + /* "numpy.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "numpy.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "numpy.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); + } + + /* "numpy.pxd":818 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); + + /* "numpy.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_7 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_7) { + + /* "numpy.pxd":821 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_v_t); + __pyx_v_t = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_7 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_7) { + + /* "numpy.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 98; + goto __pyx_L13; + } + + /* "numpy.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 66; + goto __pyx_L13; + } + + /* "numpy.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 104; + goto __pyx_L13; + } + + /* "numpy.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 72; + goto __pyx_L13; + } + + /* "numpy.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 105; + goto __pyx_L13; + } + + /* "numpy.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 73; + goto __pyx_L13; + } + + /* "numpy.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 108; + goto __pyx_L13; + } + + /* "numpy.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 76; + goto __pyx_L13; + } + + /* "numpy.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 113; + goto __pyx_L13; + } + + /* "numpy.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 81; + goto __pyx_L13; + } + + /* "numpy.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 102; + goto __pyx_L13; + } + + /* "numpy.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 100; + goto __pyx_L13; + } + + /* "numpy.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 103; + goto __pyx_L13; + } + + /* "numpy.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 79; + goto __pyx_L13; + } + /*else*/ { + + /* "numpy.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_9), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L13:; + + /* "numpy.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_12; + } + __pyx_L11:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "numpy.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":965 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "numpy.pxd":967 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "numpy.pxd":968 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":970 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "numpy.pxd":971 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "numpy.pxd":972 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "numpy.pxd":973 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":975 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "numpy.pxd":976 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":977 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":979 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_shape = 0; + Py_ssize_t __pyx_v_itemsize; + PyObject *__pyx_v_format = 0; + PyObject *__pyx_v_mode = 0; + int __pyx_v_allocate_buffer; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__shape,&__pyx_n_s__itemsize,&__pyx_n_s__format,&__pyx_n_s__mode,&__pyx_n_s__allocate_buffer,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[3] = ((PyObject *)__pyx_n_u__c); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shape)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__itemsize)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__format)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__mode); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__allocate_buffer); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_shape = ((PyObject*)values[0]); + __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_format = values[2]; + __pyx_v_mode = values[3]; + if (values[4]) { + __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "View.MemoryView":114 + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, + * mode=u"c", bint allocate_buffer=True): # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_v_allocate_buffer = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { + PyErr_Format(PyExc_TypeError, "Argument 'format' must not be None"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_r = __pyx_array_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":113 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode=u"c", bint allocate_buffer=True): + * + */ + +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { + int __pyx_v_idx; + Py_ssize_t __pyx_v_i; + PyObject **__pyx_v_p; + PyObject *__pyx_v_encode = NULL; + PyObject *__pyx_v_dim = NULL; + char __pyx_v_order; + PyObject *__pyx_v_decode = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_INCREF(__pyx_v_format); + __Pyx_INCREF(__pyx_v_mode); + + /* "View.MemoryView":120 + * cdef PyObject **p + * + * self.ndim = len(shape) # <<<<<<<<<<<<<< + * self.itemsize = itemsize + * + */ + if (unlikely(((PyObject *)__pyx_v_shape) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = PyTuple_GET_SIZE(((PyObject *)__pyx_v_shape)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->ndim = __pyx_t_1; + + /* "View.MemoryView":121 + * + * self.ndim = len(shape) + * self.itemsize = itemsize # <<<<<<<<<<<<<< + * + * if not self.ndim: + */ + __pyx_v_self->itemsize = __pyx_v_itemsize; + + /* "View.MemoryView":123 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ + __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":124 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if self.itemsize <= 0: + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":126 + * raise ValueError("Empty shape tuple for cython.array") + * + * if self.itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ + __pyx_t_2 = ((__pyx_v_self->itemsize <= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":127 + * + * if self.itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * encode = getattr(format, 'encode', None) + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_18), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":129 + * raise ValueError("itemsize <= 0 for cython.array") + * + * encode = getattr(format, 'encode', None) # <<<<<<<<<<<<<< + * if encode: + * format = encode('ASCII') + */ + __pyx_t_3 = __Pyx_GetAttr3(__pyx_v_format, ((PyObject *)__pyx_n_s__encode), Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_encode = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":130 + * + * encode = getattr(format, 'encode', None) + * if encode: # <<<<<<<<<<<<<< + * format = encode('ASCII') + * self._format = format + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_encode); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":131 + * encode = getattr(format, 'encode', None) + * if encode: + * format = encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format + * self.format = self._format + */ + __pyx_t_3 = PyObject_Call(__pyx_v_encode, ((PyObject *)__pyx_k_tuple_19), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_format); + __pyx_v_format = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":132 + * if encode: + * format = encode('ASCII') + * self._format = format # <<<<<<<<<<<<<< + * self.format = self._format + * + */ + if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_format); + __Pyx_GIVEREF(__pyx_v_format); + __Pyx_GOTREF(__pyx_v_self->_format); + __Pyx_DECREF(((PyObject *)__pyx_v_self->_format)); + __pyx_v_self->_format = ((PyObject*)__pyx_v_format); + + /* "View.MemoryView":133 + * format = encode('ASCII') + * self._format = format + * self.format = self._format # <<<<<<<<<<<<<< + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) + */ + __pyx_t_4 = __Pyx_PyObject_AsString(((PyObject *)__pyx_v_self->_format)); if (unlikely((!__pyx_t_4) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->format = __pyx_t_4; + + /* "View.MemoryView":135 + * self.format = self._format + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<< + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) + * + */ + __pyx_v_self->_shape = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim))); + + /* "View.MemoryView":136 + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<< + * + * if not self._shape or not self._strides: + */ + __pyx_v_self->_strides = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim))); + + /* "View.MemoryView":138 + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) + * + * if not self._shape or not self._strides: # <<<<<<<<<<<<<< + * free(self._shape) + * free(self._strides) + */ + __pyx_t_2 = ((!(__pyx_v_self->_shape != 0)) != 0); + if (!__pyx_t_2) { + __pyx_t_5 = ((!(__pyx_v_self->_strides != 0)) != 0); + __pyx_t_6 = __pyx_t_5; + } else { + __pyx_t_6 = __pyx_t_2; + } + if (__pyx_t_6) { + + /* "View.MemoryView":139 + * + * if not self._shape or not self._strides: + * free(self._shape) # <<<<<<<<<<<<<< + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") + */ + free(__pyx_v_self->_shape); + + /* "View.MemoryView":140 + * if not self._shape or not self._strides: + * free(self._shape) + * free(self._strides) # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape or strides.") + * + */ + free(__pyx_v_self->_strides); + + /* "View.MemoryView":141 + * free(self._shape) + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_21), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":144 + * + * + * idx = 0 # <<<<<<<<<<<<<< + * for idx, dim in enumerate(shape): + * if dim <= 0: + */ + __pyx_v_idx = 0; + + /* "View.MemoryView":145 + * + * idx = 0 + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + __pyx_t_7 = 0; + __pyx_t_3 = ((PyObject *)__pyx_v_shape); __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; + for (;;) { + if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_8 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_8); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_8 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF(__pyx_v_dim); + __pyx_v_dim = __pyx_t_8; + __pyx_t_8 = 0; + __pyx_v_idx = __pyx_t_7; + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":146 + * idx = 0 + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * + */ + __pyx_t_8 = PyObject_RichCompare(__pyx_v_dim, __pyx_int_0, Py_LE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (__pyx_t_6) { + + /* "View.MemoryView":147 + * for idx, dim in enumerate(shape): + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< + * + * self._shape[idx] = dim + */ + __pyx_t_8 = PyInt_FromLong(__pyx_v_idx); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_dim); + PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_dim); + __Pyx_GIVEREF(__pyx_v_dim); + __pyx_t_8 = 0; + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_22), ((PyObject *)__pyx_t_9)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":149 + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * + * self._shape[idx] = dim # <<<<<<<<<<<<<< + * idx += 1 + * + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_dim); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_t_10; + + /* "View.MemoryView":150 + * + * self._shape[idx] = dim + * idx += 1 # <<<<<<<<<<<<<< + * + * if mode not in ("fortran", "c"): + */ + __pyx_v_idx = (__pyx_v_idx + 1); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":152 + * idx += 1 + * + * if mode not in ("fortran", "c"): # <<<<<<<<<<<<<< + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + * + */ + __Pyx_INCREF(__pyx_v_mode); + __pyx_t_3 = __pyx_v_mode; + __pyx_t_8 = PyObject_RichCompare(__pyx_t_3, ((PyObject *)__pyx_n_s__fortran), Py_NE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (((int)__pyx_t_6)) { + __pyx_t_8 = PyObject_RichCompare(__pyx_t_3, ((PyObject *)__pyx_n_s__c), Py_NE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_5 = ((int)__pyx_t_2); + } else { + __pyx_t_5 = ((int)__pyx_t_6); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = (__pyx_t_5 != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":153 + * + * if mode not in ("fortran", "c"): + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< + * + * cdef char order + */ + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_23), __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":156 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = 'F' + * else: + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_mode, ((PyObject *)__pyx_n_s__fortran), Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + + /* "View.MemoryView":157 + * cdef char order + * if mode == 'fortran': + * order = 'F' # <<<<<<<<<<<<<< + * else: + * order = 'C' + */ + __pyx_v_order = 'F'; + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":159 + * order = 'F' + * else: + * order = 'C' # <<<<<<<<<<<<<< + * + * self.len = fill_contig_strides_array(self._shape, self._strides, + */ + __pyx_v_order = 'C'; + } + __pyx_L11:; + + /* "View.MemoryView":161 + * order = 'C' + * + * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< + * itemsize, self.ndim, order) + * + */ + __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); + + /* "View.MemoryView":164 + * itemsize, self.ndim, order) + * + * decode = getattr(mode, 'decode', None) # <<<<<<<<<<<<<< + * if decode: + * mode = decode('ASCII') + */ + __pyx_t_3 = __Pyx_GetAttr3(__pyx_v_mode, ((PyObject *)__pyx_n_s__decode), Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_decode = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":165 + * + * decode = getattr(mode, 'decode', None) + * if decode: # <<<<<<<<<<<<<< + * mode = decode('ASCII') + * self.mode = mode + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_decode); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":166 + * decode = getattr(mode, 'decode', None) + * if decode: + * mode = decode('ASCII') # <<<<<<<<<<<<<< + * self.mode = mode + * + */ + __pyx_t_3 = PyObject_Call(__pyx_v_decode, ((PyObject *)__pyx_k_tuple_24), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_mode); + __pyx_v_mode = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":167 + * if decode: + * mode = decode('ASCII') + * self.mode = mode # <<<<<<<<<<<<<< + * + * self.free_data = allocate_buffer + */ + if (!(likely(PyUnicode_CheckExact(__pyx_v_mode))||((__pyx_v_mode) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected unicode, got %.200s", Py_TYPE(__pyx_v_mode)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_mode); + __Pyx_GIVEREF(__pyx_v_mode); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(((PyObject *)__pyx_v_self->mode)); + __pyx_v_self->mode = ((PyObject*)__pyx_v_mode); + + /* "View.MemoryView":169 + * self.mode = mode + * + * self.free_data = allocate_buffer # <<<<<<<<<<<<<< + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + */ + __pyx_v_self->free_data = __pyx_v_allocate_buffer; + + /* "View.MemoryView":170 + * + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< + * if allocate_buffer: + * self.data = malloc(self.len) + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_format, ((PyObject *)__pyx_n_b__O), Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_6; + + /* "View.MemoryView":171 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * self.data = malloc(self.len) + * if not self.data: + */ + __pyx_t_6 = (__pyx_v_allocate_buffer != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":172 + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + * self.data = malloc(self.len) # <<<<<<<<<<<<<< + * if not self.data: + * raise MemoryError("unable to allocate array data.") + */ + __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); + + /* "View.MemoryView":173 + * if allocate_buffer: + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ + __pyx_t_6 = ((!(__pyx_v_self->data != 0)) != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":174 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_26), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":176 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ + __pyx_t_6 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":177 + * + * if self.dtype_is_object: + * p = self.data # <<<<<<<<<<<<<< + * for i in range(self.len / itemsize): + * p[i] = Py_None + */ + __pyx_v_p = ((PyObject **)__pyx_v_self->data); + + /* "View.MemoryView":178 + * if self.dtype_is_object: + * p = self.data + * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< + * p[i] = Py_None + * Py_INCREF(Py_None) + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_1; __pyx_t_10+=1) { + __pyx_v_i = __pyx_t_10; + + /* "View.MemoryView":179 + * p = self.data + * for i in range(self.len / itemsize): + * p[i] = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + (__pyx_v_p[__pyx_v_i]) = Py_None; + + /* "View.MemoryView":180 + * for i in range(self.len / itemsize): + * p[i] = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + Py_INCREF(Py_None); + } + goto __pyx_L15; + } + __pyx_L15:; + goto __pyx_L13; + } + __pyx_L13:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_encode); + __Pyx_XDECREF(__pyx_v_dim); + __Pyx_XDECREF(__pyx_v_decode); + __Pyx_XDECREF(__pyx_v_format); + __Pyx_XDECREF(__pyx_v_mode); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":183 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == b"c": + */ + +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_bufmode; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + Py_ssize_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":184 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 # <<<<<<<<<<<<<< + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = -1; + + /* "View.MemoryView":185 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == b"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": + */ + __pyx_t_1 = (__Pyx_PyUnicode_Equals(((PyObject *)__pyx_v_self->mode), ((PyObject *)__pyx_n_b__c), Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":186 + * cdef int bufmode = -1 + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + + /* "View.MemoryView":187 + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ + __pyx_t_2 = (__Pyx_PyUnicode_Equals(((PyObject *)__pyx_v_self->mode), ((PyObject *)__pyx_n_b__fortran), Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":188 + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + */ + __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":189 + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ + __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":190 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_28), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":191 + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data # <<<<<<<<<<<<<< + * info.len = self.len + * info.ndim = self.ndim + */ + __pyx_t_4 = __pyx_v_self->data; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":192 + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + * info.len = self.len # <<<<<<<<<<<<<< + * info.ndim = self.ndim + * info.shape = self._shape + */ + __pyx_t_5 = __pyx_v_self->len; + __pyx_v_info->len = __pyx_t_5; + + /* "View.MemoryView":193 + * info.buf = self.data + * info.len = self.len + * info.ndim = self.ndim # <<<<<<<<<<<<<< + * info.shape = self._shape + * info.strides = self._strides + */ + __pyx_t_6 = __pyx_v_self->ndim; + __pyx_v_info->ndim = __pyx_t_6; + + /* "View.MemoryView":194 + * info.len = self.len + * info.ndim = self.ndim + * info.shape = self._shape # <<<<<<<<<<<<<< + * info.strides = self._strides + * info.suboffsets = NULL + */ + __pyx_t_7 = __pyx_v_self->_shape; + __pyx_v_info->shape = __pyx_t_7; + + /* "View.MemoryView":195 + * info.ndim = self.ndim + * info.shape = self._shape + * info.strides = self._strides # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = self.itemsize + */ + __pyx_t_7 = __pyx_v_self->_strides; + __pyx_v_info->strides = __pyx_t_7; + + /* "View.MemoryView":196 + * info.shape = self._shape + * info.strides = self._strides + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = self.itemsize + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; + + /* "View.MemoryView":197 + * info.strides = self._strides + * info.suboffsets = NULL + * info.itemsize = self.itemsize # <<<<<<<<<<<<<< + * info.readonly = 0 + * + */ + __pyx_t_5 = __pyx_v_self->itemsize; + __pyx_v_info->itemsize = __pyx_t_5; + + /* "View.MemoryView":198 + * info.suboffsets = NULL + * info.itemsize = self.itemsize + * info.readonly = 0 # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":200 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":201 + * + * if flags & PyBUF_FORMAT: + * info.format = self.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_4 = __pyx_v_self->format; + __pyx_v_info->format = __pyx_t_4; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":203 + * info.format = self.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.obj = self + */ + __pyx_v_info->format = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":205 + * info.format = NULL + * + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_array_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":209 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":210 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ + __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":211 + * def __dealloc__(array self): + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) # <<<<<<<<<<<<<< + * elif self.free_data: + * if self.dtype_is_object: + */ + __pyx_v_self->callback_free_data(__pyx_v_self->data); + goto __pyx_L3; + } + + /* "View.MemoryView":212 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ + __pyx_t_1 = (__pyx_v_self->free_data != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":213 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":215 + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) # <<<<<<<<<<<<<< + * free(self.data) + * + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":216 + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + * free(self.data) # <<<<<<<<<<<<<< + * + * free(self._strides) + */ + free(__pyx_v_self->data); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":218 + * free(self.data) + * + * free(self._strides) # <<<<<<<<<<<<<< + * free(self._shape) + * + */ + free(__pyx_v_self->_strides); + + /* "View.MemoryView":219 + * + * free(self._strides) + * free(self._shape) # <<<<<<<<<<<<<< + * + * property memview: + */ + free(__pyx_v_self->_shape); + + __Pyx_RefNannyFinishContext(); +} + +/* Python wrapper */ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = get_memview_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":223 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":225 + * def __get__(self): + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< + * return memoryview(self, flags, self.dtype_is_object) + * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":226 + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromLong(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":229 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":230 + * + * def __getattr__(self, attr): + * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * + * def __getitem__(self, item): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":232 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":233 + * + * def __getitem__(self, item): + * return self.memview[item] # <<<<<<<<<<<<<< + * + * def __setitem__(self, item, value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (!__pyx_t_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":235 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "View.MemoryView":236 + * + * def __setitem__(self, item, value): + * self.memview[item] = value # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":240 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + +static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { + struct __pyx_array_obj *__pyx_v_result = 0; + struct __pyx_array_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("array_cwrapper", 0); + + /* "View.MemoryView":244 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":245 + * + * if buf == NULL: + * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_shape)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 2, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + PyTuple_SET_ITEM(__pyx_t_5, 3, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":247 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_shape)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + PyTuple_SET_ITEM(__pyx_t_2, 3, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + + /* "View.MemoryView":248 + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) # <<<<<<<<<<<<<< + * result.data = buf + * + */ + __pyx_t_5 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 248; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__allocate_buffer), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":249 + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) + * result.data = buf # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->data = __pyx_v_buf; + } + __pyx_L3:; + + /* "View.MemoryView":251 + * result.data = buf + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + __pyx_r = ((struct __pyx_array_obj *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_name = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__name,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__name)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_name = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":277 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "View.MemoryView":278 + * cdef object name + * def __init__(self, name): + * self.name = name # <<<<<<<<<<<<<< + * def __repr__(self): + * return self.name + */ + __Pyx_INCREF(__pyx_v_name); + __Pyx_GIVEREF(__pyx_v_name); + __Pyx_GOTREF(__pyx_v_self->name); + __Pyx_DECREF(__pyx_v_self->name); + __pyx_v_self->name = __pyx_v_name; + + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":279 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":280 + * self.name = name + * def __repr__(self): + * return self.name # <<<<<<<<<<<<<< + * + * cdef generic = Enum("") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->name); + __pyx_r = __pyx_v_self->name; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":294 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + +static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { + Py_intptr_t __pyx_v_aligned_p; + size_t __pyx_v_offset; + void *__pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":296 + * cdef void *align_pointer(void *memory, size_t alignment) nogil: + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< + * cdef size_t offset + * + */ + __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + + /* "View.MemoryView":300 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":302 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + __pyx_t_1 = ((__pyx_v_offset > 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":303 + * + * if offset > 0: + * aligned_p += alignment - offset # <<<<<<<<<<<<<< + * + * return aligned_p + */ + __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":305 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview') + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_obj = 0; + int __pyx_v_flags; + int __pyx_v_dtype_is_object; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__obj,&__pyx_n_s__flags,&__pyx_n_s__dtype_is_object,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__obj)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__flags)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dtype_is_object); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_obj = values[0]; + __pyx_v_flags = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[2]) { + __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "View.MemoryView":323 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + __pyx_v_dtype_is_object = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_memoryview_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "View.MemoryView":324 + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj # <<<<<<<<<<<<<< + * self.flags = flags + * if type(self) is memoryview or obj is not None: + */ + __Pyx_INCREF(__pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __Pyx_GOTREF(__pyx_v_self->obj); + __Pyx_DECREF(__pyx_v_self->obj); + __pyx_v_self->obj = __pyx_v_obj; + + /* "View.MemoryView":325 + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj + * self.flags = flags # <<<<<<<<<<<<<< + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + */ + __pyx_v_self->flags = __pyx_v_flags; + + /* "View.MemoryView":326 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ + __pyx_t_1 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type))); + if (!(__pyx_t_1 != 0)) { + __pyx_t_2 = (__pyx_v_obj != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + } else { + __pyx_t_3 = (__pyx_t_1 != 0); + } + if (__pyx_t_3) { + + /* "View.MemoryView":327 + * self.flags = flags + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + */ + __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":328 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_t_3 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":329 + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; + + /* "View.MemoryView":330 + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * self.lock = PyThread_allocate_lock() + */ + Py_INCREF(Py_None); + goto __pyx_L4; + } + __pyx_L4:; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":332 + * Py_INCREF(Py_None) + * + * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< + * if self.lock == NULL: + * raise MemoryError + */ + __pyx_v_self->lock = PyThread_allocate_lock(); + + /* "View.MemoryView":333 + * + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + __pyx_t_3 = ((__pyx_v_self->lock == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":334 + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":336 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = self.view.format == b'O' + * else: + */ + __pyx_t_3 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":337 + * + * if flags & PyBUF_FORMAT: + * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< + * else: + * self.dtype_is_object = dtype_is_object + */ + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_6 = PyObject_RichCompare(((PyObject *)__pyx_t_5), ((PyObject *)__pyx_n_b__O), Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":339 + * self.dtype_is_object = self.view.format == b'O' + * else: + * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + */ + __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; + } + __pyx_L6:; + + /* "View.MemoryView":341 + * self.dtype_is_object = dtype_is_object + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL + */ + __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); + + /* "View.MemoryView":343 + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(memoryview self): + */ + __pyx_v_self->typeinfo = NULL; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":345 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":346 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< + * __Pyx_ReleaseBuffer(&self.view) + * + */ + __pyx_t_1 = (__pyx_v_self->obj != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":347 + * def __dealloc__(memoryview self): + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< + * + * if self.lock != NULL: + */ + __Pyx_ReleaseBuffer((&__pyx_v_self->view)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":349 + * __Pyx_ReleaseBuffer(&self.view) + * + * if self.lock != NULL: # <<<<<<<<<<<<<< + * PyThread_free_lock(self.lock) + * + */ + __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":350 + * + * if self.lock != NULL: + * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + */ + PyThread_free_lock(__pyx_v_self->lock); + goto __pyx_L4; + } + __pyx_L4:; + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":352 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + Py_ssize_t __pyx_v_dim; + char *__pyx_v_itemp; + PyObject *__pyx_v_idx = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_item_pointer", 0); + + /* "View.MemoryView":354 + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< + * + * for dim, idx in enumerate(index): + */ + __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); + + /* "View.MemoryView":356 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + __pyx_t_1 = 0; + if (PyList_CheckExact(__pyx_v_index) || PyTuple_CheckExact(__pyx_v_index)) { + __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; + } + for (;;) { + if (!__pyx_t_4 && PyList_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_4 && PyTuple_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF(__pyx_v_idx); + __pyx_v_idx = __pyx_t_5; + __pyx_t_5 = 0; + __pyx_v_dim = __pyx_t_1; + __pyx_t_1 = (__pyx_t_1 + 1); + + /* "View.MemoryView":357 + * + * for dim, idx in enumerate(index): + * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< + * + * return itemp + */ + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_7; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":359 + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + * return itemp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_itemp; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":362 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_indices = NULL; + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *(*__pyx_t_7)(PyObject *); + char *__pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":363 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":364 + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: + * return self # <<<<<<<<<<<<<< + * + * have_slices, indices = _unellipsify(index, self.view.ndim) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __pyx_r = ((PyObject *)__pyx_v_self); + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":366 + * return self + * + * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * cdef char *itemp + */ + __pyx_t_3 = ((PyObject *)_unellipsify(__pyx_v_index, __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (likely(PyTuple_CheckExact(__pyx_t_3))) { + PyObject* sequence = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_6 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = Py_TYPE(__pyx_t_6)->tp_iternext; + index = 0; __pyx_t_4 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_4)) goto __pyx_L4_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + index = 1; __pyx_t_5 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_5)) goto __pyx_L4_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_6), 2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = NULL; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L5_unpacking_done; + __pyx_L4_unpacking_failed:; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_7 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L5_unpacking_done:; + } + __pyx_v_have_slices = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; + + /* "View.MemoryView":369 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":370 + * cdef char *itemp + * if have_slices: + * return memview_slice(self, indices) # <<<<<<<<<<<<<< + * else: + * itemp = self.get_item_pointer(indices) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":372 + * return memview_slice(self, indices) + * else: + * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< + * return self.convert_item_to_object(itemp) + * + */ + __pyx_t_8 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_8 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_8; + + /* "View.MemoryView":373 + * else: + * itemp = self.get_item_pointer(indices) + * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< + * + * def __setitem__(memoryview self, object index, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + __pyx_L6:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":375 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_obj = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *(*__pyx_t_5)(PyObject *); + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_INCREF(__pyx_v_index); + + /* "View.MemoryView":376 + * + * def __setitem__(memoryview self, object index, object value): + * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * if have_slices: + */ + __pyx_t_1 = ((PyObject *)_unellipsify(__pyx_v_index, __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (likely(PyTuple_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_3 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = NULL; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L4_unpacking_done:; + } + __pyx_v_have_slices = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_v_index); + __pyx_v_index = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":378 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":379 + * + * if have_slices: + * obj = self.is_slice(value) # <<<<<<<<<<<<<< + * if obj: + * self.setitem_slice_assignment(self[index], obj) + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_obj = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":380 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":381 + * obj = self.is_slice(value) + * if obj: + * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< + * else: + * self.setitem_slice_assign_scalar(self[index], value) + */ + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (!__pyx_t_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":383 + * self.setitem_slice_assignment(self[index], obj) + * else: + * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< + * else: + * self.setitem_indexed(index, value) + */ + __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (!__pyx_t_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":385 + * self.setitem_slice_assign_scalar(self[index], value) + * else: + * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< + * + * cdef is_slice(self, obj): + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L5:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":387 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_slice", 0); + __Pyx_INCREF(__pyx_v_obj); + + /* "View.MemoryView":388 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type)); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":389 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + { + __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + /*try:*/ { + + /* "View.MemoryView":390 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_6 = PyInt_FromLong((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":391 + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * except TypeError: + * return None + */ + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_7 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_v_obj); + __pyx_v_obj = __pyx_t_7; + __pyx_t_7 = 0; + } + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L11_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":392 + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + * except TypeError: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":393 + * self.dtype_is_object) + * except TypeError: + * return None # <<<<<<<<<<<<<< + * + * return obj + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L7_except_return; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L5_exception_handled; + } + __pyx_L6_except_error:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L1_error; + __pyx_L7_except_return:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L0; + __pyx_L5_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + __pyx_L11_try_end:; + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":395 + * return None + * + * return obj # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assignment(self, dst, src): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_obj); + __pyx_r = __pyx_v_obj; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":397 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { + __Pyx_memviewslice __pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_src_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); + + /* "View.MemoryView":401 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":402 + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< + * src.ndim, dst.ndim, self.dtype_is_object) + * + */ + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":403 + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s__ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s__ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":405 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { + int __pyx_v_array[128]; + void *__pyx_v_tmp; + void *__pyx_v_item; + __Pyx_memviewslice __pyx_v_tmp_slice; + __Pyx_memviewslice *__pyx_v_dst_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); + + /* "View.MemoryView":407 + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + * cdef int array[128] + * cdef void *tmp = NULL # <<<<<<<<<<<<<< + * cdef void *item + * + */ + __pyx_v_tmp = NULL; + + /* "View.MemoryView":411 + * + * cdef __Pyx_memviewslice tmp_slice, *dst_slice + * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< + * + * if self.view.itemsize > sizeof(array): + */ + __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); + + /* "View.MemoryView":413 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: + */ + __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":414 + * + * if self.view.itemsize > sizeof(array): + * tmp = malloc(self.view.itemsize) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError + */ + __pyx_v_tmp = malloc(__pyx_v_self->view.itemsize); + + /* "View.MemoryView":415 + * if self.view.itemsize > sizeof(array): + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":416 + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * item = tmp + * else: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":417 + * if tmp == NULL: + * raise MemoryError + * item = tmp # <<<<<<<<<<<<<< + * else: + * item = array + */ + __pyx_v_item = __pyx_v_tmp; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":419 + * item = tmp + * else: + * item = array # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_v_item = ((void *)__pyx_v_array); + } + __pyx_L3:; + + /* "View.MemoryView":421 + * item = array + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":422 + * + * if self.dtype_is_object: + * ( item)[0] = value # <<<<<<<<<<<<<< + * else: + * try: + */ + (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":424 + * ( item)[0] = value + * else: + * try: # <<<<<<<<<<<<<< + * self.assign_item_from_object( item, value) + * except: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":425 + * else: + * try: + * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< + * except: + * free(tmp) + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L13_try_end; + __pyx_L6_error:; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":426 + * try: + * self.assign_item_from_object( item, value) + * except: # <<<<<<<<<<<<<< + * free(tmp) + * raise + */ + /*except:*/ { + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 426; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":427 + * self.assign_item_from_object( item, value) + * except: + * free(tmp) # <<<<<<<<<<<<<< + * raise + * + */ + free(__pyx_v_tmp); + + /* "View.MemoryView":428 + * except: + * free(tmp) + * raise # <<<<<<<<<<<<<< + * + * + */ + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_7); + __Pyx_ErrRestore(__pyx_t_5, __pyx_t_6, __pyx_t_7); + __pyx_t_5 = 0; __pyx_t_6 = 0; __pyx_t_7 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 428; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L7_exception_handled; + } + __pyx_L8_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L7_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L13_try_end:; + } + } + __pyx_L5:; + + /* "View.MemoryView":432 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":433 + * + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + */ + __pyx_t_7 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":435 + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) # <<<<<<<<<<<<<< + * free(tmp) + * + */ + __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); + + /* "View.MemoryView":436 + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + * free(tmp) # <<<<<<<<<<<<<< + * + * cdef setitem_indexed(self, index, value): + */ + free(__pyx_v_tmp); + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":438 + * free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_indexed", 0); + + /* "View.MemoryView":439 + * + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< + * self.assign_item_from_object(itemp, value) + * + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_1; + + /* "View.MemoryView":440 + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":442 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_v_struct = NULL; + PyObject *__pyx_v_bytesitem = 0; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":445 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef bytes bytesitem + * + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__struct), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":448 + * cdef bytes bytesitem + * + * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< + * try: + * result = struct.unpack(self.view.format, bytesitem) + */ + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":449 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":450 + * bytesitem = itemp[:self.view.itemsize] + * try: + * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< + * except struct.error: + * raise ValueError("Unable to convert item to object") + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__unpack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __Pyx_INCREF(((PyObject *)__pyx_v_bytesitem)); + PyTuple_SET_ITEM(__pyx_t_6, 1, ((PyObject *)__pyx_v_bytesitem)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_bytesitem)); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + } + /*else:*/ { + + /* "View.MemoryView":454 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + __pyx_t_7 = strlen(__pyx_v_self->view.format); + __pyx_t_8 = ((__pyx_t_7 == 1) != 0); + if (__pyx_t_8) { + + /* "View.MemoryView":455 + * else: + * if len(self.view.format) == 1: + * return result[0] # <<<<<<<<<<<<<< + * return result + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_result, 0, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_5) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L6_except_return; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":456 + * if len(self.view.format) == 1: + * return result[0] + * return result # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L6_except_return; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L10_try_end; + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":451 + * try: + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: # <<<<<<<<<<<<<< + * raise ValueError("Unable to convert item to object") + * else: + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__error); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_1); + + /* "View.MemoryView":452 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_t_10 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_30), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L4_exception_handled; + } + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L6_except_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + __pyx_L4_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L10_try_end:; + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesitem); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":458 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_v_struct = NULL; + char __pyx_v_c; + PyObject *__pyx_v_bytesvalue = 0; + Py_ssize_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + char *__pyx_t_10; + char *__pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":461 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef char c + * cdef bytes bytesvalue + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__struct), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":466 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + __pyx_t_2 = PyTuple_Check(__pyx_v_value); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":467 + * + * if isinstance(value, tuple): + * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< + * else: + * bytesvalue = struct.pack(self.view.format, value) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = 0; + __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_6 = PyNumber_Add(((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":469 + * bytesvalue = struct.pack(self.view.format, *value) + * else: + * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< + * + * for i, c in enumerate(bytesvalue): + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__pack); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_6)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_6)); + __Pyx_INCREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + __pyx_t_6 = 0; + __pyx_t_6 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_6)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":471 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = 0; + if (unlikely(((PyObject *)__pyx_v_bytesvalue) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_INCREF(((PyObject *)__pyx_v_bytesvalue)); + __pyx_t_8 = __pyx_v_bytesvalue; + __pyx_t_10 = PyBytes_AS_STRING(__pyx_t_8); + __pyx_t_11 = (__pyx_t_10 + PyBytes_GET_SIZE(__pyx_t_8)); + for (__pyx_t_12 = __pyx_t_10; __pyx_t_12 < __pyx_t_11; __pyx_t_12++) { + __pyx_t_9 = __pyx_t_12; + __pyx_v_c = (__pyx_t_9[0]); + + /* "View.MemoryView":472 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + __pyx_v_i = __pyx_t_7; + + /* "View.MemoryView":471 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":472 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; + } + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(((PyObject *)__pyx_t_8)); + __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":475 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + char *__pyx_t_3; + void *__pyx_t_4; + int __pyx_t_5; + Py_ssize_t __pyx_t_6; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":476 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":477 + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape # <<<<<<<<<<<<<< + * else: + * info.shape = NULL + */ + __pyx_t_2 = __pyx_v_self->view.shape; + __pyx_v_info->shape = __pyx_t_2; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":479 + * info.shape = self.view.shape + * else: + * info.shape = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_STRIDES: + */ + __pyx_v_info->shape = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":481 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":482 + * + * if flags & PyBUF_STRIDES: + * info.strides = self.view.strides # <<<<<<<<<<<<<< + * else: + * info.strides = NULL + */ + __pyx_t_2 = __pyx_v_self->view.strides; + __pyx_v_info->strides = __pyx_t_2; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":484 + * info.strides = self.view.strides + * else: + * info.strides = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_INDIRECT: + */ + __pyx_v_info->strides = NULL; + } + __pyx_L4:; + + /* "View.MemoryView":486 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":487 + * + * if flags & PyBUF_INDIRECT: + * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< + * else: + * info.suboffsets = NULL + */ + __pyx_t_2 = __pyx_v_self->view.suboffsets; + __pyx_v_info->suboffsets = __pyx_t_2; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":489 + * info.suboffsets = self.view.suboffsets + * else: + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->suboffsets = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":491 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":492 + * + * if flags & PyBUF_FORMAT: + * info.format = self.view.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_3 = __pyx_v_self->view.format; + __pyx_v_info->format = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":494 + * info.format = self.view.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.buf = self.view.buf + */ + __pyx_v_info->format = NULL; + } + __pyx_L6:; + + /* "View.MemoryView":496 + * info.format = NULL + * + * info.buf = self.view.buf # <<<<<<<<<<<<<< + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + */ + __pyx_t_4 = __pyx_v_self->view.buf; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":497 + * + * info.buf = self.view.buf + * info.ndim = self.view.ndim # <<<<<<<<<<<<<< + * info.itemsize = self.view.itemsize + * info.len = self.view.len + */ + __pyx_t_5 = __pyx_v_self->view.ndim; + __pyx_v_info->ndim = __pyx_t_5; + + /* "View.MemoryView":498 + * info.buf = self.view.buf + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< + * info.len = self.view.len + * info.readonly = 0 + */ + __pyx_t_6 = __pyx_v_self->view.itemsize; + __pyx_v_info->itemsize = __pyx_t_6; + + /* "View.MemoryView":499 + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + * info.len = self.view.len # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.obj = self + */ + __pyx_t_6 = __pyx_v_self->view.len; + __pyx_v_info->len = __pyx_t_6; + + /* "View.MemoryView":500 + * info.itemsize = self.view.itemsize + * info.len = self.view.len + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.obj = self + * + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":501 + * info.len = self.view.len + * info.readonly = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + __pyx_r = 0; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":508 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":509 + * @cname('__pyx_memoryview_transpose') + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< + * transpose_memslice(&result.from_slice) + * return result + */ + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":510 + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":511 + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + * return result # <<<<<<<<<<<<<< + * + * property base: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":515 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":516 + * @cname('__pyx_memoryview__get__base') + * def __get__(self): + * return self.obj # <<<<<<<<<<<<<< + * + * property shape: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->obj); + __pyx_r = __pyx_v_self->obj; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":520 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":521 + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property strides: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_v_self->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->view.shape[__pyx_v_i])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __pyx_t_4 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_1))); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_r = ((PyObject *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":525 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":526 + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":528 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_32), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":530 + * raise ValueError("Buffer view does not expose strides") + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property suboffsets: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.strides[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_2))); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_5); + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":534 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":535 + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return [-1] * self.view.ndim + * + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":536 + * def __get__(self): + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(1 * ((__pyx_v_self->view.ndim<0) ? 0:__pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_self->view.ndim; __pyx_temp++) { + __Pyx_INCREF(__pyx_int_neg_1); + PyList_SET_ITEM(__pyx_t_2, __pyx_temp, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + } + } + __pyx_r = ((PyObject *)__pyx_t_2); + __pyx_t_2 = 0; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":538 + * return [-1] * self.view.ndim + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property ndim: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.suboffsets[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_2))); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_5); + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":542 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":543 + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): + * return self.view.ndim # <<<<<<<<<<<<<< + * + * property itemsize: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromLong(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":547 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":548 + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): + * return self.view.itemsize # <<<<<<<<<<<<<< + * + * property nbytes: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":552 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":553 + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): + * return self.size * self.view.itemsize # <<<<<<<<<<<<<< + * + * property size: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":557 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":558 + * @cname('__pyx_memoryview_get_size') + * def __get__(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + __pyx_t_1 = (__pyx_v_self->_size == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":559 + * def __get__(self): + * if self._size is None: + * result = 1 # <<<<<<<<<<<<<< + * + * for length in self.shape: + */ + __Pyx_INCREF(__pyx_int_1); + __pyx_v_result = __pyx_int_1; + + /* "View.MemoryView":561 + * result = 1 + * + * for length in self.shape: # <<<<<<<<<<<<<< + * result *= length + * + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyList_CheckExact(__pyx_t_3) || PyTuple_CheckExact(__pyx_t_3)) { + __pyx_t_4 = __pyx_t_3; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_3 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_3)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF(__pyx_v_length); + __pyx_v_length = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":562 + * + * for length in self.shape: + * result *= length # <<<<<<<<<<<<<< + * + * self._size = result + */ + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_result); + __pyx_v_result = __pyx_t_3; + __pyx_t_3 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "View.MemoryView":564 + * result *= length + * + * self._size = result # <<<<<<<<<<<<<< + * + * return self._size + */ + __Pyx_INCREF(__pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __Pyx_GOTREF(__pyx_v_self->_size); + __Pyx_DECREF(__pyx_v_self->_size); + __pyx_v_self->_size = __pyx_v_result; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":566 + * self._size = result + * + * return self._size # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->_size); + __pyx_r = __pyx_v_self->_size; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":568 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__len__", 0); + + /* "View.MemoryView":569 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":570 + * def __len__(self): + * if self.view.ndim >= 1: + * return self.view.shape[0] # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_r = (__pyx_v_self->view.shape[0]); + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":572 + * return self.view.shape[0] + * + * return 0 # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":574 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":575 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s____class__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s____name__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":576 + * def __repr__(self): + * return "" % (self.base.__class__.__name__, + * id(self)) # <<<<<<<<<<<<<< + * + * def __str__(self): + */ + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __pyx_t_3 = PyObject_Call(__pyx_builtin_id, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_33), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":578 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__str__", 0); + + /* "View.MemoryView":579 + * + * def __str__(self): + * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s____class__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s____name__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_34), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":582 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_c_contig", 0); + + /* "View.MemoryView":584 + * def is_c_contig(self): + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":585 + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< + * + * def is_f_contig(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":587 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_f_contig", 0); + + /* "View.MemoryView":589 + * def is_f_contig(self): + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":590 + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< + * + * def copy(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":592 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_mslice; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "View.MemoryView":594 + * def copy(self): + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &mslice) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); + + /* "View.MemoryView":596 + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + * + * slice_copy(self, &mslice) # <<<<<<<<<<<<<< + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); + + /* "View.MemoryView":600 + * self.view.itemsize, + * flags|PyBUF_C_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * + * return memoryview_copy_from_slice(self, &mslice) + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k__c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":602 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< + * + * def copy_fortran(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":604 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy_fortran", 0); + + /* "View.MemoryView":606 + * def copy_fortran(self): + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &src) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); + + /* "View.MemoryView":608 + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + * + * slice_copy(self, &src) # <<<<<<<<<<<<<< + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); + + /* "View.MemoryView":612 + * self.view.itemsize, + * flags|PyBUF_F_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * + * return memoryview_copy_from_slice(self, &dst) + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k__fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dst = __pyx_t_1; + + /* "View.MemoryView":614 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":618 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + +static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { + struct __pyx_memoryview_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); + + /* "View.MemoryView":619 + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< + * result.typeinfo = typeinfo + * return result + */ + __pyx_t_1 = PyInt_FromLong(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); + __Pyx_GIVEREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":620 + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_v_result->typeinfo = __pyx_v_typeinfo; + + /* "View.MemoryView":621 + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_check') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":624 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("memoryview_check", 0); + + /* "View.MemoryView":625 + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): + * return isinstance(o, memoryview) # <<<<<<<<<<<<<< + * + * cdef tuple _unellipsify(object index, int ndim): + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type)); + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":627 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + +static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { + PyObject *__pyx_v_tup = NULL; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_have_slices = NULL; + int __pyx_v_seen_ellipsis; + CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_item = NULL; + PyObject *__pyx_v_nslices = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + Py_ssize_t __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_unellipsify", 0); + + /* "View.MemoryView":632 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + __pyx_t_1 = PyTuple_Check(__pyx_v_index); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":633 + * """ + * if not isinstance(index, tuple): + * tup = (index,) # <<<<<<<<<<<<<< + * else: + * tup = index + */ + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 633; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_index); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); + __Pyx_GIVEREF(__pyx_v_index); + __pyx_v_tup = ((PyObject *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":635 + * tup = (index,) + * else: + * tup = index # <<<<<<<<<<<<<< + * + * result = [] + */ + __Pyx_INCREF(__pyx_v_index); + __pyx_v_tup = __pyx_v_index; + } + __pyx_L3:; + + /* "View.MemoryView":637 + * tup = index + * + * result = [] # <<<<<<<<<<<<<< + * have_slices = False + * seen_ellipsis = False + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_result = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":638 + * + * result = [] + * have_slices = False # <<<<<<<<<<<<<< + * seen_ellipsis = False + * for idx, item in enumerate(tup): + */ + __pyx_t_3 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_have_slices = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":639 + * result = [] + * have_slices = False + * seen_ellipsis = False # <<<<<<<<<<<<<< + * for idx, item in enumerate(tup): + * if item is Ellipsis: + */ + __pyx_v_seen_ellipsis = 0; + + /* "View.MemoryView":640 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_3 = __pyx_int_0; + if (PyList_CheckExact(__pyx_v_tup) || PyTuple_CheckExact(__pyx_v_tup)) { + __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_7 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_7)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_XDECREF(__pyx_v_item); + __pyx_v_item = __pyx_t_7; + __pyx_t_7 = 0; + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_v_idx); + __pyx_v_idx = __pyx_t_3; + __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_t_7; + __pyx_t_7 = 0; + + /* "View.MemoryView":641 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ + __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":642 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ + __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":643 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_result), __pyx_n_s__extend); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_35), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_9) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_9) + 1))); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_9) + 1); __pyx_temp++) { + __Pyx_INCREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_10, __pyx_temp, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + } + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_10)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_10)); + __pyx_t_10 = 0; + __pyx_t_10 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + + /* "View.MemoryView":644 + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True # <<<<<<<<<<<<<< + * else: + * result.append(slice(None)) + */ + __pyx_v_seen_ellipsis = 1; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":646 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_t_10 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_36), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_result, __pyx_t_10); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + } + __pyx_L7:; + + /* "View.MemoryView":647 + * else: + * result.append(slice(None)) + * have_slices = True # <<<<<<<<<<<<<< + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + */ + __pyx_t_10 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_v_have_slices); + __pyx_v_have_slices = __pyx_t_10; + __pyx_t_10 = 0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":649 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ + __pyx_t_1 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_1 = ((!(__Pyx_PyIndex_Check(__pyx_v_item) != 0)) != 0); + __pyx_t_12 = __pyx_t_1; + } else { + __pyx_t_12 = __pyx_t_2; + } + if (__pyx_t_12) { + + /* "View.MemoryView":650 + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< + * + * have_slices = have_slices or isinstance(item, slice) + */ + __pyx_t_10 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_37), ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_10)); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_10)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_10)); + __pyx_t_10 = 0; + __pyx_t_10 = PyObject_Call(__pyx_builtin_TypeError, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":652 + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< + * result.append(item) + * + */ + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_12) { + __pyx_t_12 = PySlice_Check(__pyx_v_item); + __pyx_t_10 = __Pyx_PyBool_FromLong(__pyx_t_12); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_8 = __pyx_t_10; + __pyx_t_10 = 0; + } else { + __Pyx_INCREF(__pyx_v_have_slices); + __pyx_t_8 = __pyx_v_have_slices; + } + __Pyx_DECREF(__pyx_v_have_slices); + __pyx_v_have_slices = __pyx_t_8; + __pyx_t_8 = 0; + + /* "View.MemoryView":653 + * + * have_slices = have_slices or isinstance(item, slice) + * result.append(item) # <<<<<<<<<<<<<< + * + * nslices = ndim - len(result) + */ + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":655 + * result.append(item) + * + * nslices = ndim - len(result) # <<<<<<<<<<<<<< + * if nslices: + * result.extend([slice(None)] * nslices) + */ + __pyx_t_5 = PyList_GET_SIZE(((PyObject *)__pyx_v_result)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_ndim - __pyx_t_5)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_nslices = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":656 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_nslices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_12) { + + /* "View.MemoryView":657 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_result), __pyx_n_s__extend); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_38), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyList_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_8, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + { PyObject* __pyx_temp = PyNumber_InPlaceMultiply(__pyx_t_8, __pyx_v_nslices); if (unlikely(!__pyx_temp)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_temp); + __Pyx_DECREF(__pyx_t_8); + __pyx_t_8 = __pyx_temp; + } + __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":659 + * result.extend([slice(None)] * nslices) + * + * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_12) { + __Pyx_INCREF(__pyx_v_nslices); + __pyx_t_8 = __pyx_v_nslices; + } else { + __Pyx_INCREF(__pyx_v_have_slices); + __pyx_t_8 = __pyx_v_have_slices; + } + __pyx_t_4 = ((PyObject *)PyList_AsTuple(__pyx_v_result)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_8 = 0; + __pyx_t_4 = 0; + __pyx_r = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = ((PyObject*)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_tup); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_item); + __Pyx_XDECREF(__pyx_v_nslices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":661 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + +static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); + + /* "View.MemoryView":663 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * cdef int i + * for i in range(ndim): # <<<<<<<<<<<<<< + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":664 + * cdef int i + * for i in range(ndim): + * if suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ + __pyx_t_3 = (((__pyx_v_suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":665 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_40), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":672 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { + int __pyx_v_new_ndim; + int __pyx_v_suboffset_dim; + int __pyx_v_dim; + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + __Pyx_memviewslice *__pyx_v_p_src; + struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; + __Pyx_memviewslice *__pyx_v_p_dst; + int *__pyx_v_p_suboffset_dim; + Py_ssize_t __pyx_v_start; + Py_ssize_t __pyx_v_stop; + Py_ssize_t __pyx_v_step; + int __pyx_v_have_start; + int __pyx_v_have_stop; + int __pyx_v_have_step; + PyObject *__pyx_v_index = NULL; + struct __pyx_memoryview_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + struct __pyx_memoryview_obj *__pyx_t_3; + char *__pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + PyObject *__pyx_t_12 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memview_slice", 0); + + /* "View.MemoryView":673 + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): + * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< + * cdef bint negative_step + * cdef __Pyx_memviewslice src, dst + */ + __pyx_v_new_ndim = 0; + __pyx_v_suboffset_dim = -1; + + /* "View.MemoryView":680 + * + * + * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< + * + * cdef _memoryviewslice memviewsliceobj + */ + memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); + + /* "View.MemoryView":684 + * cdef _memoryviewslice memviewsliceobj + * + * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 684; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #endif + + /* "View.MemoryView":686 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":687 + * + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview # <<<<<<<<<<<<<< + * p_src = &memviewsliceobj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(((PyObject *)__pyx_v_memview)); + __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview); + + /* "View.MemoryView":688 + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, &src) + */ + __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":690 + * p_src = &memviewsliceobj.from_slice + * else: + * slice_copy(memview, &src) # <<<<<<<<<<<<<< + * p_src = &src + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); + + /* "View.MemoryView":691 + * else: + * slice_copy(memview, &src) + * p_src = &src # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_src = (&__pyx_v_src); + } + __pyx_L3:; + + /* "View.MemoryView":697 + * + * + * dst.memview = p_src.memview # <<<<<<<<<<<<<< + * dst.data = p_src.data + * + */ + __pyx_t_3 = __pyx_v_p_src->memview; + __pyx_v_dst.memview = __pyx_t_3; + + /* "View.MemoryView":698 + * + * dst.memview = p_src.memview + * dst.data = p_src.data # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = __pyx_v_p_src->data; + __pyx_v_dst.data = __pyx_t_4; + + /* "View.MemoryView":703 + * + * + * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< + * cdef int *p_suboffset_dim = &suboffset_dim + * cdef Py_ssize_t start, stop, step + */ + __pyx_v_p_dst = (&__pyx_v_dst); + + /* "View.MemoryView":704 + * + * cdef __Pyx_memviewslice *p_dst = &dst + * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< + * cdef Py_ssize_t start, stop, step + * cdef bint have_start, have_stop, have_step + */ + __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); + + /* "View.MemoryView":708 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + __pyx_t_5 = 0; + if (PyList_CheckExact(__pyx_v_indices) || PyTuple_CheckExact(__pyx_v_indices)) { + __pyx_t_6 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_6); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = Py_TYPE(__pyx_t_6)->tp_iternext; + } + for (;;) { + if (!__pyx_t_8 && PyList_CheckExact(__pyx_t_6)) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_6)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_6, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_6, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_8 && PyTuple_CheckExact(__pyx_t_6)) { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_6)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_6, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_9 = __pyx_t_8(__pyx_t_6); + if (unlikely(!__pyx_t_9)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_9); + } + __Pyx_XDECREF(__pyx_v_index); + __pyx_v_index = __pyx_t_9; + __pyx_t_9 = 0; + __pyx_v_dim = __pyx_t_5; + __pyx_t_5 = (__pyx_t_5 + 1); + + /* "View.MemoryView":709 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ + __pyx_t_2 = (__Pyx_PyIndex_Check(__pyx_v_index) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":713 + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< + * 0, 0, 0, # have_{start,stop,step} + * False) + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":715 + * index, 0, 0, # start, stop, step + * 0, 0, 0, # have_{start,stop,step} + * False) # <<<<<<<<<<<<<< + * elif index is None: + * p_dst.shape[new_ndim] = 1 + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 710; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + + /* "View.MemoryView":716 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ + __pyx_t_2 = (__pyx_v_index == Py_None); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":717 + * False) + * elif index is None: + * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + */ + (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; + + /* "View.MemoryView":718 + * elif index is None: + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 + */ + (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; + + /* "View.MemoryView":719 + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< + * new_ndim += 1 + * else: + */ + (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1; + + /* "View.MemoryView":720 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 # <<<<<<<<<<<<<< + * else: + * start = index.start or 0 + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":722 + * new_ndim += 1 + * else: + * start = index.start or 0 # <<<<<<<<<<<<<< + * stop = index.stop or 0 + * step = index.step or 0 + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_start = __pyx_t_10; + + /* "View.MemoryView":723 + * else: + * start = index.start or 0 + * stop = index.stop or 0 # <<<<<<<<<<<<<< + * step = index.step or 0 + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_12); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_9 = __pyx_int_0; + } else { + __pyx_t_9 = __pyx_t_12; + __pyx_t_12 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_stop = __pyx_t_10; + + /* "View.MemoryView":724 + * start = index.start or 0 + * stop = index.stop or 0 + * step = index.step or 0 # <<<<<<<<<<<<<< + * + * have_start = index.start is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_step = __pyx_t_10; + + /* "View.MemoryView":726 + * step = index.step or 0 + * + * have_start = index.start is not None # <<<<<<<<<<<<<< + * have_stop = index.stop is not None + * have_step = index.step is not None + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__start); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 726; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_start = __pyx_t_1; + + /* "View.MemoryView":727 + * + * have_start = index.start is not None + * have_stop = index.stop is not None # <<<<<<<<<<<<<< + * have_step = index.step is not None + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 727; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_stop = __pyx_t_1; + + /* "View.MemoryView":728 + * have_start = index.start is not None + * have_stop = index.stop is not None + * have_step = index.step is not None # <<<<<<<<<<<<<< + * + * slice_memviewslice( + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__step); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_step = __pyx_t_1; + + /* "View.MemoryView":735 + * start, stop, step, + * have_start, have_stop, have_step, + * True) # <<<<<<<<<<<<<< + * new_ndim += 1 + * + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 730; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":736 + * have_start, have_stop, have_step, + * True) + * new_ndim += 1 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "View.MemoryView":738 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":739 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":740 + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 740; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":742 + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + */ + __pyx_t_6 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_6); + __pyx_t_6 = 0; + goto __pyx_L0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":744 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":745 + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_6 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 744; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 744; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_6); + __pyx_t_6 = 0; + goto __pyx_L0; + } + __pyx_L7:; + + __pyx_r = ((struct __pyx_memoryview_obj *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":769 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { + Py_ssize_t __pyx_v_new_shape; + int __pyx_v_negative_step; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":789 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":791 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + __pyx_t_1 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":792 + * + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":793 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + __pyx_t_1 = (0 <= __pyx_v_start); + if (__pyx_t_1) { + __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); + } + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":794 + * start += shape + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< + * else: + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_41, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":797 + * else: + * + * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< + * + * if have_step and step == 0: + */ + __pyx_t_2 = (__pyx_v_have_step != 0); + if (__pyx_t_2) { + __pyx_t_1 = (__pyx_v_step < 0); + __pyx_t_4 = __pyx_t_1; + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_v_negative_step = __pyx_t_4; + + /* "View.MemoryView":799 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + if ((__pyx_v_have_step != 0)) { + __pyx_t_4 = (__pyx_v_step == 0); + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = (__pyx_v_have_step != 0); + } + if (__pyx_t_2) { + + /* "View.MemoryView":800 + * + * if have_step and step == 0: + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_42, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":803 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + __pyx_t_2 = (__pyx_v_have_start != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":804 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":805 + * if have_start: + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if start < 0: + * start = 0 + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":806 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":807 + * start += shape + * if start < 0: + * start = 0 # <<<<<<<<<<<<<< + * elif start >= shape: + * if negative_step: + */ + __pyx_v_start = 0; + goto __pyx_L9; + } + __pyx_L9:; + goto __pyx_L8; + } + + /* "View.MemoryView":808 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":809 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":810 + * elif start >= shape: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = shape + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L10; + } + /*else*/ { + + /* "View.MemoryView":812 + * start = shape - 1 + * else: + * start = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_start = __pyx_v_shape; + } + __pyx_L10:; + goto __pyx_L8; + } + __pyx_L8:; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":814 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":815 + * else: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = 0 + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":817 + * start = shape - 1 + * else: + * start = 0 # <<<<<<<<<<<<<< + * + * if have_stop: + */ + __pyx_v_start = 0; + } + __pyx_L11:; + } + __pyx_L7:; + + /* "View.MemoryView":819 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + __pyx_t_2 = (__pyx_v_have_stop != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":820 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":821 + * if have_stop: + * if stop < 0: + * stop += shape # <<<<<<<<<<<<<< + * if stop < 0: + * stop = 0 + */ + __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); + + /* "View.MemoryView":822 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":823 + * stop += shape + * if stop < 0: + * stop = 0 # <<<<<<<<<<<<<< + * elif stop > shape: + * stop = shape + */ + __pyx_v_stop = 0; + goto __pyx_L14; + } + __pyx_L14:; + goto __pyx_L13; + } + + /* "View.MemoryView":824 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":825 + * stop = 0 + * elif stop > shape: + * stop = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_stop = __pyx_v_shape; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L12; + } + /*else*/ { + + /* "View.MemoryView":827 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":828 + * else: + * if negative_step: + * stop = -1 # <<<<<<<<<<<<<< + * else: + * stop = shape + */ + __pyx_v_stop = -1; + goto __pyx_L15; + } + /*else*/ { + + /* "View.MemoryView":830 + * stop = -1 + * else: + * stop = shape # <<<<<<<<<<<<<< + * + * if not have_step: + */ + __pyx_v_stop = __pyx_v_shape; + } + __pyx_L15:; + } + __pyx_L12:; + + /* "View.MemoryView":832 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":833 + * + * if not have_step: + * step = 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_step = 1; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":837 + * + * with cython.cdivision(True): + * new_shape = (stop - start) // step # <<<<<<<<<<<<<< + * + * if (stop - start) - step * new_shape: + */ + __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); + + /* "View.MemoryView":839 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":840 + * + * if (stop - start) - step * new_shape: + * new_shape += 1 # <<<<<<<<<<<<<< + * + * if new_shape < 0: + */ + __pyx_v_new_shape = (__pyx_v_new_shape + 1); + goto __pyx_L17; + } + __pyx_L17:; + + /* "View.MemoryView":842 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":843 + * + * if new_shape < 0: + * new_shape = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_new_shape = 0; + goto __pyx_L18; + } + __pyx_L18:; + + /* "View.MemoryView":846 + * + * + * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset + */ + (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); + + /* "View.MemoryView":847 + * + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< + * dst.suboffsets[new_ndim] = suboffset + * + */ + (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; + + /* "View.MemoryView":848 + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; + } + __pyx_L3:; + + /* "View.MemoryView":851 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":852 + * + * if suboffset_dim[0] < 0: + * dst.data += start * stride # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride + */ + __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); + goto __pyx_L19; + } + /*else*/ { + + /* "View.MemoryView":854 + * dst.data += start * stride + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< + * + * if suboffset >= 0: + */ + __pyx_t_3 = (__pyx_v_suboffset_dim[0]); + (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); + } + __pyx_L19:; + + /* "View.MemoryView":856 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":857 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":858 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":859 + * if not is_slice: + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + */ + __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); + goto __pyx_L22; + } + /*else*/ { + + /* "View.MemoryView":862 + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< + * else: + * suboffset_dim[0] = new_ndim + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_43, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L22:; + goto __pyx_L21; + } + /*else*/ { + + /* "View.MemoryView":864 + * "must be indexed and not sliced", dim) + * else: + * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< + * + * return 0 + */ + (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; + } + __pyx_L21:; + goto __pyx_L20; + } + __pyx_L20:; + + /* "View.MemoryView":866 + * suboffset_dim[0] = new_ndim + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":872 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + +static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, int __pyx_v_dim) { + Py_ssize_t __pyx_v_shape; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_suboffset; + Py_ssize_t __pyx_v_itemsize; + char *__pyx_v_resultp; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pybuffer_index", 0); + + /* "View.MemoryView":874 + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< + * cdef Py_ssize_t itemsize = view.itemsize + * cdef char *resultp + */ + __pyx_v_suboffset = -1; + + /* "View.MemoryView":875 + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< + * cdef char *resultp + * + */ + __pyx_t_1 = __pyx_v_view->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":878 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":879 + * + * if view.ndim == 0: + * shape = view.len / itemsize # <<<<<<<<<<<<<< + * stride = itemsize + * else: + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 879; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 879; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); + + /* "View.MemoryView":880 + * if view.ndim == 0: + * shape = view.len / itemsize + * stride = itemsize # <<<<<<<<<<<<<< + * else: + * shape = view.shape[dim] + */ + __pyx_v_stride = __pyx_v_itemsize; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":882 + * stride = itemsize + * else: + * shape = view.shape[dim] # <<<<<<<<<<<<<< + * stride = view.strides[dim] + * if view.suboffsets != NULL: + */ + __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); + + /* "View.MemoryView":883 + * else: + * shape = view.shape[dim] + * stride = view.strides[dim] # <<<<<<<<<<<<<< + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] + */ + __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); + + /* "View.MemoryView":884 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":885 + * stride = view.strides[dim] + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< + * + * if index < 0: + */ + __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); + goto __pyx_L4; + } + __pyx_L4:; + } + __pyx_L3:; + + /* "View.MemoryView":887 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":888 + * + * if index < 0: + * index += view.shape[dim] # <<<<<<<<<<<<<< + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + */ + __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); + + /* "View.MemoryView":889 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":890 + * index += view.shape[dim] + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * if index >= shape: + */ + __pyx_t_3 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_44), __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_builtin_IndexError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":892 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":893 + * + * if index >= shape: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * resultp = bufp + index * stride + */ + __pyx_t_4 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_44), __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_IndexError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + + /* "View.MemoryView":895 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * resultp = bufp + index * stride # <<<<<<<<<<<<<< + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset + */ + __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); + + /* "View.MemoryView":896 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":897 + * resultp = bufp + index * stride + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< + * + * return resultp + */ + __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":899 + * resultp = ( resultp)[0] + suboffset + * + * return resultp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_resultp; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":905 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + +static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { + int __pyx_v_ndim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + int __pyx_v_i; + int __pyx_v_j; + int __pyx_r; + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + long __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":906 + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: + * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< + * + * cdef Py_ssize_t *shape = memslice.shape + */ + __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; + __pyx_v_ndim = __pyx_t_1; + + /* "View.MemoryView":908 + * cdef int ndim = memslice.memview.view.ndim + * + * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< + * cdef Py_ssize_t *strides = memslice.strides + * + */ + __pyx_t_2 = __pyx_v_memslice->shape; + __pyx_v_shape = __pyx_t_2; + + /* "View.MemoryView":909 + * + * cdef Py_ssize_t *shape = memslice.shape + * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_v_memslice->strides; + __pyx_v_strides = __pyx_t_2; + + /* "View.MemoryView":913 + * + * cdef int i, j + * for i in range(ndim / 2): # <<<<<<<<<<<<<< + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + */ + __pyx_t_3 = __Pyx_div_long(__pyx_v_ndim, 2); + for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":914 + * cdef int i, j + * for i in range(ndim / 2): + * j = ndim - 1 - i # <<<<<<<<<<<<<< + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] + */ + __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); + + /* "View.MemoryView":915 + * for i in range(ndim / 2): + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< + * shape[i], shape[j] = shape[j], shape[i] + * + */ + __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); + __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); + (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; + (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; + + /* "View.MemoryView":916 + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + */ + __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); + __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); + (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; + (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; + + /* "View.MemoryView":918 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + __pyx_t_6 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); + if (!__pyx_t_6) { + __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); + __pyx_t_8 = __pyx_t_7; + } else { + __pyx_t_8 = __pyx_t_6; + } + if (__pyx_t_8) { + + /* "View.MemoryView":919 + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< + * + * return 1 + */ + __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_45); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 919; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "View.MemoryView":921 + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + * return 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 1; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":938 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":939 + * + * def __dealloc__(self): + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":941 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":942 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":943 + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) # <<<<<<<<<<<<<< + * else: + * return memoryview.convert_item_to_object(self, itemp) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":945 + * return self.to_object_func(itemp) + * else: + * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_vtabptr_memoryview->convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 945; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":947 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":948 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":949 + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< + * else: + * memoryview.assign_item_from_object(self, itemp, value) + */ + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":951 + * self.to_dtype_func(itemp, value) + * else: + * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< + * + * property base: + */ + __pyx_t_3 = __pyx_vtabptr_memoryview->assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 951; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":955 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":956 + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): + * return self.from_object # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->from_object); + __pyx_r = __pyx_v_self->from_object; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":962 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_TypeInfo *__pyx_t_4; + Py_buffer __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_fromslice", 0); + + /* "View.MemoryView":971 + * cdef int i + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":972 + * + * if memviewslice.memview == Py_None: + * return None # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":977 + * + * + * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< + * + * result.from_slice = memviewslice + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":979 + * result = _memoryviewslice(None, 0, dtype_is_object) + * + * result.from_slice = memviewslice # <<<<<<<<<<<<<< + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + */ + __pyx_v_result->from_slice = __pyx_v_memviewslice; + + /* "View.MemoryView":980 + * + * result.from_slice = memviewslice + * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< + * + * result.from_object = ( memviewslice.memview).base + */ + __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); + + /* "View.MemoryView":982 + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< + * result.typeinfo = memviewslice.memview.typeinfo + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s__base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 982; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_result->from_object); + __Pyx_DECREF(__pyx_v_result->from_object); + __pyx_v_result->from_object = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":983 + * + * result.from_object = ( memviewslice.memview).base + * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< + * + * result.view = memviewslice.memview.view + */ + __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; + __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; + + /* "View.MemoryView":985 + * result.typeinfo = memviewslice.memview.typeinfo + * + * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + */ + __pyx_t_5 = __pyx_v_memviewslice.memview->view; + __pyx_v_result->__pyx_base.view = __pyx_t_5; + + /* "View.MemoryView":986 + * + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + */ + __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); + + /* "View.MemoryView":987 + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data + * result.view.ndim = ndim # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; + + /* "View.MemoryView":988 + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; + + /* "View.MemoryView":989 + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * result.flags = PyBUF_RECORDS + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":991 + * Py_INCREF(Py_None) + * + * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< + * + * result.view.shape = result.from_slice.shape + */ + __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; + + /* "View.MemoryView":993 + * result.flags = PyBUF_RECORDS + * + * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets + */ + __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); + + /* "View.MemoryView":994 + * + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * + */ + __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); + + /* "View.MemoryView":995 + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + * + * result.view.len = result.view.itemsize + */ + __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + + /* "View.MemoryView":997 + * result.view.suboffsets = result.from_slice.suboffsets + * + * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< + * for i in range(ndim): + * result.view.len *= result.view.shape[i] + */ + __pyx_t_6 = __pyx_v_result->__pyx_base.view.itemsize; + __pyx_v_result->__pyx_base.view.len = __pyx_t_6; + + /* "View.MemoryView":998 + * + * result.view.len = result.view.itemsize + * for i in range(ndim): # <<<<<<<<<<<<<< + * result.view.len *= result.view.shape[i] + * + */ + __pyx_t_7 = __pyx_v_ndim; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "View.MemoryView":999 + * result.view.len = result.view.itemsize + * for i in range(ndim): + * result.view.len *= result.view.shape[i] # <<<<<<<<<<<<<< + * + * result.to_object_func = to_object_func + */ + __pyx_v_result->__pyx_base.view.len = (__pyx_v_result->__pyx_base.view.len * (__pyx_v_result->__pyx_base.view.shape[__pyx_v_i])); + } + + /* "View.MemoryView":1001 + * result.view.len *= result.view.shape[i] + * + * result.to_object_func = to_object_func # <<<<<<<<<<<<<< + * result.to_dtype_func = to_dtype_func + * + */ + __pyx_v_result->to_object_func = __pyx_v_to_object_func; + + /* "View.MemoryView":1002 + * + * result.to_object_func = to_object_func + * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; + + /* "View.MemoryView":1004 + * result.to_dtype_func = to_dtype_func + * + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1007 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { + struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; + __Pyx_memviewslice *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_slice_from_memview", 0); + + /* "View.MemoryView":1010 + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1011 + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): + * obj = memview # <<<<<<<<<<<<<< + * return &obj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1011; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(((PyObject *)__pyx_v_memview)); + __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview); + + /* "View.MemoryView":1012 + * if isinstance(memview, _memoryviewslice): + * obj = memview + * return &obj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, mslice) + */ + __pyx_r = (&__pyx_v_obj->from_slice); + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1014 + * return &obj.from_slice + * else: + * slice_copy(memview, mslice) # <<<<<<<<<<<<<< + * return mslice + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); + + /* "View.MemoryView":1015 + * else: + * slice_copy(memview, mslice) + * return mslice # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_copy') + */ + __pyx_r = __pyx_v_mslice; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_obj); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1018 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef Py_ssize_t *shape, *strides, *suboffsets + */ + +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { + int __pyx_v_dim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + Py_ssize_t *__pyx_v_suboffsets; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + __Pyx_RefNannySetupContext("slice_copy", 0); + + /* "View.MemoryView":1022 + * cdef Py_ssize_t *shape, *strides, *suboffsets + * + * shape = memview.view.shape # <<<<<<<<<<<<<< + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets + */ + __pyx_t_1 = __pyx_v_memview->view.shape; + __pyx_v_shape = __pyx_t_1; + + /* "View.MemoryView":1023 + * + * shape = memview.view.shape + * strides = memview.view.strides # <<<<<<<<<<<<<< + * suboffsets = memview.view.suboffsets + * + */ + __pyx_t_1 = __pyx_v_memview->view.strides; + __pyx_v_strides = __pyx_t_1; + + /* "View.MemoryView":1024 + * shape = memview.view.shape + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< + * + * dst.memview = <__pyx_memoryview *> memview + */ + __pyx_t_1 = __pyx_v_memview->view.suboffsets; + __pyx_v_suboffsets = __pyx_t_1; + + /* "View.MemoryView":1026 + * suboffsets = memview.view.suboffsets + * + * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< + * dst.data = memview.view.buf + * + */ + __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); + + /* "View.MemoryView":1027 + * + * dst.memview = <__pyx_memoryview *> memview + * dst.data = memview.view.buf # <<<<<<<<<<<<<< + * + * for dim in range(memview.view.ndim): + */ + __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); + + /* "View.MemoryView":1029 + * dst.data = memview.view.buf + * + * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + */ + __pyx_t_2 = __pyx_v_memview->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_dim = __pyx_t_3; + + /* "View.MemoryView":1030 + * + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + */ + (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); + + /* "View.MemoryView":1031 + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 + */ + (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); + + /* "View.MemoryView":1032 + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: # <<<<<<<<<<<<<< + * dst.suboffsets[dim] = -1 + * else: + */ + __pyx_t_4 = ((__pyx_v_suboffsets == NULL) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":1033 + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[dim] = suboffsets[dim] + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = -1; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1035 + * dst.suboffsets[dim] = -1 + * else: + * dst.suboffsets[dim] = suboffsets[dim] # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object') + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = (__pyx_v_suboffsets[__pyx_v_dim]); + } + __pyx_L5:; + } + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1038 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { + __Pyx_memviewslice __pyx_v_memviewslice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy", 0); + + /* "View.MemoryView":1041 + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< + * return memoryview_copy_from_slice(memview, &memviewslice) + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); + + /* "View.MemoryView":1042 + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) + * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object_from_slice') + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1042; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1045 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { + PyObject *(*__pyx_v_to_object_func)(char *); + int (*__pyx_v_to_dtype_func)(char *, PyObject *); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *(*__pyx_t_3)(char *); + int (*__pyx_t_4)(char *, PyObject *); + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); + + /* "View.MemoryView":1052 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1053 + * + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + */ + __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; + __pyx_v_to_object_func = __pyx_t_3; + + /* "View.MemoryView":1054 + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< + * else: + * to_object_func = NULL + */ + __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; + __pyx_v_to_dtype_func = __pyx_t_4; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1056 + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + * to_object_func = NULL # <<<<<<<<<<<<<< + * to_dtype_func = NULL + * + */ + __pyx_v_to_object_func = NULL; + + /* "View.MemoryView":1057 + * else: + * to_object_func = NULL + * to_dtype_func = NULL # <<<<<<<<<<<<<< + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + */ + __pyx_v_to_dtype_func = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":1059 + * to_dtype_func = NULL + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< + * to_object_func, to_dtype_func, + * memview.dtype_is_object) + */ + __Pyx_XDECREF(__pyx_r); + + /* "View.MemoryView":1061 + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + * to_object_func, to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1067 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + +static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { + Py_ssize_t __pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":1068 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + __pyx_t_1 = ((__pyx_v_arg < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1069 + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: + * return -arg # <<<<<<<<<<<<<< + * else: + * return arg + */ + __pyx_r = (-__pyx_v_arg); + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1071 + * return -arg + * else: + * return arg # <<<<<<<<<<<<<< + * + * @cname('__pyx_get_best_slice_order') + */ + __pyx_r = __pyx_v_arg; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1074 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + +static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_c_stride; + Py_ssize_t __pyx_v_f_stride; + char __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1079 + * """ + * cdef int i + * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t f_stride = 0 + * + */ + __pyx_v_c_stride = 0; + + /* "View.MemoryView":1080 + * cdef int i + * cdef Py_ssize_t c_stride = 0 + * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_f_stride = 0; + + /* "View.MemoryView":1082 + * cdef Py_ssize_t f_stride = 0 + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1083 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1084 + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1085 + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + goto __pyx_L4_break; + goto __pyx_L5; + } + __pyx_L5:; + } + __pyx_L4_break:; + + /* "View.MemoryView":1087 + * break + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1088 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1089 + * for i in range(ndim): + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1090 + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + */ + goto __pyx_L7_break; + goto __pyx_L8; + } + __pyx_L8:; + } + __pyx_L7_break:; + + /* "View.MemoryView":1092 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1093 + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + * return 'C' # <<<<<<<<<<<<<< + * else: + * return 'F' + */ + __pyx_r = 'C'; + goto __pyx_L0; + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1095 + * return 'C' + * else: + * return 'F' # <<<<<<<<<<<<<< + * + * @cython.cdivision(True) + */ + __pyx_r = 'F'; + goto __pyx_L0; + } + __pyx_L9:; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1098 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + +static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; + Py_ssize_t __pyx_v_dst_extent; + Py_ssize_t __pyx_v_src_stride; + Py_ssize_t __pyx_v_dst_stride; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + + /* "View.MemoryView":1105 + * + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + */ + __pyx_v_src_extent = (__pyx_v_src_shape[0]); + + /* "View.MemoryView":1106 + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] + */ + __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); + + /* "View.MemoryView":1107 + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + */ + __pyx_v_src_stride = (__pyx_v_src_strides[0]); + + /* "View.MemoryView":1108 + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); + + /* "View.MemoryView":1110 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1111 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + __pyx_t_1 = ((__pyx_v_src_stride > 0) != 0); + if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1112 + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + */ + __pyx_t_3 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); + if (__pyx_t_3) { + __pyx_t_3 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); + } + __pyx_t_4 = (__pyx_t_3 != 0); + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = __pyx_t_1; + } + if (__pyx_t_2) { + + /* "View.MemoryView":1113 + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":1115 + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1116 + * else: + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); + + /* "View.MemoryView":1117 + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * else: + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1118 + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1120 + * dst_data += dst_stride + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * _copy_strided_to_strided(src_data, src_strides + 1, + * dst_data, dst_strides + 1, + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1124 + * dst_data, dst_strides + 1, + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); + + /* "View.MemoryView":1125 + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1126 + * ndim - 1, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L3:; + +} + +/* "View.MemoryView":1128 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + +static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + + /* "View.MemoryView":1132 + * int ndim, size_t itemsize) nogil: + * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, + * src.shape, dst.shape, ndim, itemsize) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_get_size') + */ + _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); + +} + +/* "View.MemoryView":1135 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_size; + Py_ssize_t __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1138 + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_size = __pyx_t_1; + + /* "View.MemoryView":1140 + * cdef Py_ssize_t size = src.memview.view.itemsize + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * size *= src.shape[i] + * + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1141 + * + * for i in range(ndim): + * size *= src.shape[i] # <<<<<<<<<<<<<< + * + * return size + */ + __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); + } + + /* "View.MemoryView":1143 + * size *= src.shape[i] + * + * return size # <<<<<<<<<<<<<< + * + * @cname('__pyx_fill_contig_strides_array') + */ + __pyx_r = __pyx_v_size; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1146 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { + int __pyx_v_idx; + Py_ssize_t __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1155 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + __pyx_t_1 = ((__pyx_v_order == 'F') != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1156 + * + * if order == 'F': + * for idx in range(ndim): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_idx = __pyx_t_3; + + /* "View.MemoryView":1157 + * if order == 'F': + * for idx in range(ndim): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * else: + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1158 + * for idx in range(ndim): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * else: + * for idx in range(ndim - 1, -1, -1): + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1160 + * stride = stride * shape[idx] + * else: + * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { + __pyx_v_idx = __pyx_t_2; + + /* "View.MemoryView":1161 + * else: + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1162 + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * + * return stride + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + } + __pyx_L3:; + + /* "View.MemoryView":1164 + * stride = stride * shape[idx] + * + * return stride # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_data_to_temp') + */ + __pyx_r = __pyx_v_stride; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1167 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { + int __pyx_v_i; + void *__pyx_v_result; + size_t __pyx_v_itemsize; + size_t __pyx_v_size; + void *__pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + struct __pyx_memoryview_obj *__pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1178 + * cdef void *result + * + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef size_t size = slice_get_size(src, ndim) + * + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1179 + * + * cdef size_t itemsize = src.memview.view.itemsize + * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< + * + * result = malloc(size) + */ + __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); + + /* "View.MemoryView":1181 + * cdef size_t size = slice_get_size(src, ndim) + * + * result = malloc(size) # <<<<<<<<<<<<<< + * if not result: + * _err(MemoryError, NULL) + */ + __pyx_v_result = malloc(__pyx_v_size); + + /* "View.MemoryView":1182 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1183 + * result = malloc(size) + * if not result: + * _err(MemoryError, NULL) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1186 + * + * + * tmpslice.data = result # <<<<<<<<<<<<<< + * tmpslice.memview = src.memview + * for i in range(ndim): + */ + __pyx_v_tmpslice->data = ((char *)__pyx_v_result); + + /* "View.MemoryView":1187 + * + * tmpslice.data = result + * tmpslice.memview = src.memview # <<<<<<<<<<<<<< + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + */ + __pyx_t_4 = __pyx_v_src->memview; + __pyx_v_tmpslice->memview = __pyx_t_4; + + /* "View.MemoryView":1188 + * tmpslice.data = result + * tmpslice.memview = src.memview + * for i in range(ndim): # <<<<<<<<<<<<<< + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1189 + * tmpslice.memview = src.memview + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< + * tmpslice.suboffsets[i] = -1 + * + */ + (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); + + /* "View.MemoryView":1190 + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + */ + (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1193 + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + * ndim, order) # <<<<<<<<<<<<<< + * + * + */ + __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); + + /* "View.MemoryView":1196 + * + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1197 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1198 + * for i in range(ndim): + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< + * + * if slice_is_contig(src, order, ndim): + */ + (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1200 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1201 + * + * if slice_is_contig(src, order, ndim): + * memcpy(result, src.data, size) # <<<<<<<<<<<<<< + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + */ + memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1203 + * memcpy(result, src.data, size) + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< + * + * return result + */ + copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); + } + __pyx_L9:; + + /* "View.MemoryView":1205 + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = NULL; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1210 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + +static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_extents", 0); + + /* "View.MemoryView":1213 + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + * (i, extent1, extent2)) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err_dim') + */ + __pyx_t_1 = PyInt_FromLong(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_46), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1216 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + +static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_dim", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1217 + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: + * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err') + */ + __pyx_t_1 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_2 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_t_1), __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_v_error, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1220 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + +static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1221 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ + __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1222 + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: + * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< + * else: + * raise error + */ + __pyx_t_2 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_2)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_v_error, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1224 + * raise error(msg.decode('ascii')) + * else: + * raise error # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_contents') + */ + __Pyx_Raise(__pyx_v_error, 0, 0, 0); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1227 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { + void *__pyx_v_tmpdata; + size_t __pyx_v_itemsize; + int __pyx_v_i; + char __pyx_v_order; + int __pyx_v_broadcasting; + int __pyx_v_direct_copy; + __Pyx_memviewslice __pyx_v_tmp; + int __pyx_v_ndim; + int __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + void *__pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1235 + * Check for overlapping memory and verify the shapes. + * """ + * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + */ + __pyx_v_tmpdata = NULL; + + /* "View.MemoryView":1236 + * """ + * cdef void *tmpdata = NULL + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + */ + __pyx_t_1 = __pyx_v_src.memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1238 + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< + * cdef bint broadcasting = False + * cdef bint direct_copy = False + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); + + /* "View.MemoryView":1239 + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False # <<<<<<<<<<<<<< + * cdef bint direct_copy = False + * cdef __Pyx_memviewslice tmp + */ + __pyx_v_broadcasting = 0; + + /* "View.MemoryView":1240 + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False + * cdef bint direct_copy = False # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice tmp + * + */ + __pyx_v_direct_copy = 0; + + /* "View.MemoryView":1243 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ + __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1244 + * + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); + goto __pyx_L3; + } + + /* "View.MemoryView":1245 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ + __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1246 + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< + * + * cdef int ndim = max(src_ndim, dst_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1248 + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_3 = __pyx_v_dst_ndim; + __pyx_t_4 = __pyx_v_src_ndim; + if (((__pyx_t_3 > __pyx_t_4) != 0)) { + __pyx_t_5 = __pyx_t_3; + } else { + __pyx_t_5 = __pyx_t_4; + } + __pyx_v_ndim = __pyx_t_5; + + /* "View.MemoryView":1250 + * cdef int ndim = max(src_ndim, dst_ndim) + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1251 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1252 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1253 + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + * broadcasting = True # <<<<<<<<<<<<<< + * src.strides[i] = 0 + * else: + */ + __pyx_v_broadcasting = 1; + + /* "View.MemoryView":1254 + * if src.shape[i] == 1: + * broadcasting = True + * src.strides[i] = 0 # <<<<<<<<<<<<<< + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) + */ + (__pyx_v_src.strides[__pyx_v_i]) = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":1256 + * src.strides[i] = 0 + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< + * + * if src.suboffsets[i] >= 0: + */ + __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":1258 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ + __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1259 + * + * if src.suboffsets[i] >= 0: + * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< + * + * if slices_overlap(&src, &dst, ndim, itemsize): + */ + __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_47, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1259; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1261 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(&src, order, ndim): + */ + __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1263 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1264 + * + * if not slice_is_contig(&src, order, ndim): + * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":1266 + * order = get_best_order(&dst, ndim) + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< + * src = tmp + * + */ + __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_tmpdata = __pyx_t_6; + + /* "View.MemoryView":1267 + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + * src = tmp # <<<<<<<<<<<<<< + * + * if not broadcasting: + */ + __pyx_v_src = __pyx_v_tmp; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":1269 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1272 + * + * + * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1273 + * + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); + goto __pyx_L12; + } + + /* "View.MemoryView":1274 + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1275 + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< + * + * if direct_copy: + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":1277 + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_2 = (__pyx_v_direct_copy != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1279 + * if direct_copy: + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1280 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * return 0 + */ + memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); + + /* "View.MemoryView":1281 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1282 + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + * return 0 # <<<<<<<<<<<<<< + * + * if order == 'F' == get_best_order(&dst, ndim): + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":1284 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = (__pyx_v_order == 'F'); + if (__pyx_t_2) { + __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); + } + __pyx_t_7 = (__pyx_t_2 != 0); + if (__pyx_t_7) { + + /* "View.MemoryView":1287 + * + * + * transpose_memslice(&src) # <<<<<<<<<<<<<< + * transpose_memslice(&dst) + * + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1288 + * + * transpose_memslice(&src) + * transpose_memslice(&dst) # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":1290 + * transpose_memslice(&dst) + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1291 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + */ + copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1292 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * free(tmpdata) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1294 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1295 + * + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_broadcast_leading') + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1298 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice, int __pyx_v_ndim, int __pyx_v_ndim_other) { + int __pyx_v_i; + int __pyx_v_offset; + int __pyx_t_1; + int __pyx_t_2; + + /* "View.MemoryView":1302 + * int ndim_other) nogil: + * cdef int i + * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); + + /* "View.MemoryView":1304 + * cdef int offset = ndim_other - ndim + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1305 + * + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] # <<<<<<<<<<<<<< + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] + */ + (__pyx_v_slice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->shape[__pyx_v_i]); + + /* "View.MemoryView":1306 + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] # <<<<<<<<<<<<<< + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + */ + (__pyx_v_slice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->strides[__pyx_v_i]); + + /* "View.MemoryView":1307 + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] # <<<<<<<<<<<<<< + * + * for i in range(offset): + */ + (__pyx_v_slice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->suboffsets[__pyx_v_i]); + } + + /* "View.MemoryView":1309 + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + * for i in range(offset): # <<<<<<<<<<<<<< + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + */ + __pyx_t_1 = __pyx_v_offset; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1310 + * + * for i in range(offset): + * slice.shape[i] = 1 # <<<<<<<<<<<<<< + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 + */ + (__pyx_v_slice->shape[__pyx_v_i]) = 1; + + /* "View.MemoryView":1311 + * for i in range(offset): + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] # <<<<<<<<<<<<<< + * slice.suboffsets[i] = -1 + * + */ + (__pyx_v_slice->strides[__pyx_v_i]) = (__pyx_v_slice->strides[0]); + + /* "View.MemoryView":1312 + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_slice->suboffsets[__pyx_v_i]) = -1; + } + +} + +/* "View.MemoryView":1320 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { + int __pyx_t_1; + + /* "View.MemoryView":1324 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + __pyx_t_1 = (__pyx_v_dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1326 + * if dtype_is_object: + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + */ + __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); + goto __pyx_L3; + } + __pyx_L3:; + +} + +/* "View.MemoryView":1329 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + __Pyx_RefNannyDeclarations + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); + + /* "View.MemoryView":1332 + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); + + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif +} + +/* "View.MemoryView":1335 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + +static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); + + /* "View.MemoryView":1339 + * cdef Py_ssize_t i + * + * for i in range(shape[0]): # <<<<<<<<<<<<<< + * if ndim == 1: + * if inc: + */ + __pyx_t_1 = (__pyx_v_shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1340 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1341 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + __pyx_t_3 = (__pyx_v_inc != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1342 + * if ndim == 1: + * if inc: + * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * Py_DECREF(( data)[0]) + */ + Py_INCREF((((PyObject **)__pyx_v_data)[0])); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":1344 + * Py_INCREF(( data)[0]) + * else: + * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + */ + Py_DECREF((((PyObject **)__pyx_v_data)[0])); + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1347 + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + * ndim - 1, inc) # <<<<<<<<<<<<<< + * + * data += strides[0] + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); + } + __pyx_L5:; + + /* "View.MemoryView":1349 + * ndim - 1, inc) + * + * data += strides[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); + } + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1355 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { + + /* "View.MemoryView":1358 + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1360 + * refcount_copying(dst, dtype_is_object, ndim, False) + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) # <<<<<<<<<<<<<< + * refcount_copying(dst, dtype_is_object, ndim, True) + * + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1361 + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + +} + +/* "View.MemoryView":1365 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + +static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_extent; + int __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + + /* "View.MemoryView":1369 + * size_t itemsize, void *item) nogil: + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t extent = shape[0] + * + */ + __pyx_v_stride = (__pyx_v_strides[0]); + + /* "View.MemoryView":1370 + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] + * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_extent = (__pyx_v_shape[0]); + + /* "View.MemoryView":1372 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1373 + * + * if ndim == 1: + * for i in range(extent): # <<<<<<<<<<<<<< + * memcpy(data, item, itemsize) + * data += stride + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1374 + * if ndim == 1: + * for i in range(extent): + * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< + * data += stride + * else: + */ + memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); + + /* "View.MemoryView":1375 + * for i in range(extent): + * memcpy(data, item, itemsize) + * data += stride # <<<<<<<<<<<<<< + * else: + * for i in range(extent): + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1377 + * data += stride + * else: + * for i in range(extent): # <<<<<<<<<<<<<< + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1379 + * for i in range(extent): + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) # <<<<<<<<<<<<<< + * data += stride + * + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1380 + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + * data += stride # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + } + __pyx_L3:; + +} +static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; + +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryview_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryview_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_memoryview; + p->obj = Py_None; Py_INCREF(Py_None); + p->_size = Py_None; Py_INCREF(Py_None); + p->_array_interface = Py_None; Py_INCREF(Py_None); + p->view.obj = NULL; + if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryview___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->obj); + Py_CLEAR(p->_size); + Py_CLEAR(p->_array_interface); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + if (p->obj) { + e = (*v)(p->obj, a); if (e) return e; + } + if (p->_size) { + e = (*v)(p->_size, a); if (e) return e; + } + if (p->_array_interface) { + e = (*v)(p->_array_interface, a); if (e) return e; + } + if (p->view.obj) { + e = (*v)(p->view.obj, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->obj); + p->obj = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_size); + p->_size = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_array_interface); + p->_array_interface = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + Py_CLEAR(p->view.obj); + return 0; +} +static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_memoryview___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_transpose(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview__get__base(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_shape(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_strides(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_suboffsets(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_ndim(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_itemsize(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_nbytes(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_size(o); +} + +static PyMethodDef __pyx_methods_memoryview[] = { + {__Pyx_NAMESTR("is_c_contig"), (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("is_f_contig"), (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy"), (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy_fortran"), (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_memoryview[] = { + {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, + {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, + {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, + {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, + {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, + {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, + {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, + {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_memoryview = { + __pyx_memoryview___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_memoryview, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_memoryview = { + __pyx_memoryview___len__, /*mp_length*/ + __pyx_memoryview___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_memoryview = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_memoryview_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_memoryview = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.cluster._hierarchical.memoryview"), /*tp_name*/ + sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_memoryview___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_memoryview___str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_memoryview, /*tp_traverse*/ + __pyx_tp_clear_memoryview, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_memoryview, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_memoryview, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_memoryview, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_array_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_array_obj *)o); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_array___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->mode); + Py_CLEAR(p->_format); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_array(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + if (p->mode) { + e = (*v)(p->mode, a); if (e) return e; + } + if (p->_format) { + e = (*v)(p->_format, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->mode); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_format); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} +static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_array___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { + PyObject *v = PyObject_GenericGetAttr(o, n); + if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + v = __pyx_array___getattr__(o, n); + } + return v; +} + +static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { + return get_memview(o); +} + +static PyMethodDef __pyx_methods_array[] = { + {__Pyx_NAMESTR("__getattr__"), (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_array[] = { + {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_array = { + 0, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_array, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_array = { + 0, /*mp_length*/ + __pyx_array___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_array = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_array_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_array = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.cluster._hierarchical.array"), /*tp_name*/ + sizeof(struct __pyx_array_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_array, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + __pyx_tp_getattro_array, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_array, /*tp_traverse*/ + __pyx_tp_clear_array, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_array, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_array, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_array, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; + +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryviewslice_obj *p; + PyObject *o = __pyx_tp_new_memoryview(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryviewslice_obj *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; + p->from_object = Py_None; Py_INCREF(Py_None); + p->from_slice.memview = NULL; + return o; +} + +static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryviewslice___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->from_object); + PyObject_GC_Track(o); + __pyx_tp_dealloc_memoryview(o); +} + +static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; + if (p->from_object) { + e = (*v)(p->from_object, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + PyObject* tmp; + __pyx_tp_clear_memoryview(o); + tmp = ((PyObject*)p->from_object); + p->from_object = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + __PYX_XDEC_MEMVIEW(&p->from_slice, 1); + return 0; +} + +static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryviewslice__get__base(o); +} + +static PyMethodDef __pyx_methods__memoryviewslice[] = { + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { + {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_memoryviewslice = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.cluster._hierarchical._memoryviewslice"), /*tp_name*/ + sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___repr__, /*tp_repr*/ + #else + 0, /*tp_repr*/ + #endif + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___str__, /*tp_str*/ + #else + 0, /*tp_str*/ + #endif + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Internal class for passing memoryview slices to Python"), /*tp_doc*/ + __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ + __pyx_tp_clear__memoryviewslice, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods__memoryviewslice, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets__memoryviewslice, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new__memoryviewslice, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_MemviewEnum_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_MemviewEnum_obj *)o); + p->name = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + PyObject_GC_UnTrack(o); + Py_CLEAR(p->name); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + if (p->name) { + e = (*v)(p->name, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->name); + p->name = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_Enum[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_MemviewEnum = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.cluster._hierarchical.Enum"), /*tp_name*/ + sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_Enum, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_MemviewEnum___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_Enum, /*tp_traverse*/ + __pyx_tp_clear_Enum, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_Enum, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_MemviewEnum___init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_Enum, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static PyObject *__pyx_tp_new_7sklearn_7cluster_13_hierarchical_WeightedEdge(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + return o; +} + +static void __pyx_tp_dealloc_7sklearn_7cluster_13_hierarchical_WeightedEdge(PyObject *o) { + (*Py_TYPE(o)->tp_free)(o); +} + +static PyObject *__pyx_getprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_a(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a_1__get__(o); +} + +static int __pyx_setprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_a(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1a_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_b(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b_1__get__(o); +} + +static int __pyx_setprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_b(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1b_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_weight(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight_1__get__(o); +} + +static int __pyx_setprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_weight(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_6weight_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyMethodDef __pyx_methods_7sklearn_7cluster_13_hierarchical_WeightedEdge[] = { + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_7sklearn_7cluster_13_hierarchical_WeightedEdge[] = { + {(char *)"a", __pyx_getprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_a, __pyx_setprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_a, 0, 0}, + {(char *)"b", __pyx_getprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_b, __pyx_setprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_b, 0, 0}, + {(char *)"weight", __pyx_getprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_weight, __pyx_setprop_7sklearn_7cluster_13_hierarchical_12WeightedEdge_weight, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_7cluster_13_hierarchical_WeightedEdge = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.cluster._hierarchical.WeightedEdge"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_7cluster_13_hierarchical_WeightedEdge), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_7cluster_13_hierarchical_WeightedEdge, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_5__repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_3__richcmp__, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_7cluster_13_hierarchical_WeightedEdge, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_7sklearn_7cluster_13_hierarchical_WeightedEdge, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_7cluster_13_hierarchical_12WeightedEdge_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_7cluster_13_hierarchical_WeightedEdge, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + __Pyx_NAMESTR("_hierarchical"), + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_u_10, __pyx_k_10, sizeof(__pyx_k_10), 0, 1, 0, 0}, + {&__pyx_kp_u_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 1, 0, 0}, + {&__pyx_kp_s_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 0, 1, 0}, + {&__pyx_kp_s_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 0, 1, 0}, + {&__pyx_kp_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 0}, + {&__pyx_kp_s_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 1, 0}, + {&__pyx_kp_s_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 1, 0}, + {&__pyx_kp_s_23, __pyx_k_23, sizeof(__pyx_k_23), 0, 0, 1, 0}, + {&__pyx_kp_s_25, __pyx_k_25, sizeof(__pyx_k_25), 0, 0, 1, 0}, + {&__pyx_kp_s_27, __pyx_k_27, sizeof(__pyx_k_27), 0, 0, 1, 0}, + {&__pyx_kp_s_29, __pyx_k_29, sizeof(__pyx_k_29), 0, 0, 1, 0}, + {&__pyx_kp_u_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 1, 0, 0}, + {&__pyx_kp_s_31, __pyx_k_31, sizeof(__pyx_k_31), 0, 0, 1, 0}, + {&__pyx_kp_s_33, __pyx_k_33, sizeof(__pyx_k_33), 0, 0, 1, 0}, + {&__pyx_kp_s_34, __pyx_k_34, sizeof(__pyx_k_34), 0, 0, 1, 0}, + {&__pyx_kp_s_37, __pyx_k_37, sizeof(__pyx_k_37), 0, 0, 1, 0}, + {&__pyx_kp_s_39, __pyx_k_39, sizeof(__pyx_k_39), 0, 0, 1, 0}, + {&__pyx_kp_s_44, __pyx_k_44, sizeof(__pyx_k_44), 0, 0, 1, 0}, + {&__pyx_kp_s_46, __pyx_k_46, sizeof(__pyx_k_46), 0, 0, 1, 0}, + {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, + {&__pyx_kp_s_50, __pyx_k_50, sizeof(__pyx_k_50), 0, 0, 1, 0}, + {&__pyx_n_s_51, __pyx_k_51, sizeof(__pyx_k_51), 0, 0, 1, 1}, + {&__pyx_kp_s_63, __pyx_k_63, sizeof(__pyx_k_63), 0, 0, 1, 0}, + {&__pyx_kp_s_65, __pyx_k_65, sizeof(__pyx_k_65), 0, 0, 1, 0}, + {&__pyx_kp_s_67, __pyx_k_67, sizeof(__pyx_k_67), 0, 0, 1, 0}, + {&__pyx_kp_s_69, __pyx_k_69, sizeof(__pyx_k_69), 0, 0, 1, 0}, + {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, + {&__pyx_kp_s_71, __pyx_k_71, sizeof(__pyx_k_71), 0, 0, 1, 0}, + {&__pyx_kp_u_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 1, 0, 0}, + {&__pyx_n_s__ASCII, __pyx_k__ASCII, sizeof(__pyx_k__ASCII), 0, 0, 1, 1}, + {&__pyx_n_s__DTYPE, __pyx_k__DTYPE, sizeof(__pyx_k__DTYPE), 0, 0, 1, 1}, + {&__pyx_n_s__Ellipsis, __pyx_k__Ellipsis, sizeof(__pyx_k__Ellipsis), 0, 0, 1, 1}, + {&__pyx_n_s__ITYPE, __pyx_k__ITYPE, sizeof(__pyx_k__ITYPE), 0, 0, 1, 1}, + {&__pyx_n_s__IndexError, __pyx_k__IndexError, sizeof(__pyx_k__IndexError), 0, 0, 1, 1}, + {&__pyx_n_s__MemoryError, __pyx_k__MemoryError, sizeof(__pyx_k__MemoryError), 0, 0, 1, 1}, + {&__pyx_n_b__O, __pyx_k__O, sizeof(__pyx_k__O), 0, 0, 0, 1}, + {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s__TypeError, __pyx_k__TypeError, sizeof(__pyx_k__TypeError), 0, 0, 1, 1}, + {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, + {&__pyx_n_s____class__, __pyx_k____class__, sizeof(__pyx_k____class__), 0, 0, 1, 1}, + {&__pyx_n_s____import__, __pyx_k____import__, sizeof(__pyx_k____import__), 0, 0, 1, 1}, + {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, + {&__pyx_n_s____name__, __pyx_k____name__, sizeof(__pyx_k____name__), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_getbuffer, __pyx_k____pyx_getbuffer, sizeof(__pyx_k____pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_releasebuffer, __pyx_k____pyx_releasebuffer, sizeof(__pyx_k____pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_vtable__, __pyx_k____pyx_vtable__, sizeof(__pyx_k____pyx_vtable__), 0, 0, 1, 1}, + {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, + {&__pyx_n_s___get_parents, __pyx_k___get_parents, sizeof(__pyx_k___get_parents), 0, 0, 1, 1}, + {&__pyx_n_s___hc_get_descendent, __pyx_k___hc_get_descendent, sizeof(__pyx_k___hc_get_descendent), 0, 0, 1, 1}, + {&__pyx_n_s__a, __pyx_k__a, sizeof(__pyx_k__a), 0, 0, 1, 1}, + {&__pyx_n_s__a_end, __pyx_k__a_end, sizeof(__pyx_k__a_end), 0, 0, 1, 1}, + {&__pyx_n_s__a_it, __pyx_k__a_it, sizeof(__pyx_k__a_it), 0, 0, 1, 1}, + {&__pyx_n_s__allocate_buffer, __pyx_k__allocate_buffer, sizeof(__pyx_k__allocate_buffer), 0, 0, 1, 1}, + {&__pyx_n_s__append, __pyx_k__append, sizeof(__pyx_k__append), 0, 0, 1, 1}, + {&__pyx_n_s__average_merge, __pyx_k__average_merge, sizeof(__pyx_k__average_merge), 0, 0, 1, 1}, + {&__pyx_n_s__b, __pyx_k__b, sizeof(__pyx_k__b), 0, 0, 1, 1}, + {&__pyx_n_s__b_end, __pyx_k__b_end, sizeof(__pyx_k__b_end), 0, 0, 1, 1}, + {&__pyx_n_s__b_it, __pyx_k__b_it, sizeof(__pyx_k__b_it), 0, 0, 1, 1}, + {&__pyx_n_s__base, __pyx_k__base, sizeof(__pyx_k__base), 0, 0, 1, 1}, + {&__pyx_n_b__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 0, 0, 1}, + {&__pyx_n_s__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 0, 1, 1}, + {&__pyx_n_u__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 1, 0, 1}, + {&__pyx_n_s__children, __pyx_k__children, sizeof(__pyx_k__children), 0, 0, 1, 1}, + {&__pyx_n_s__col, __pyx_k__col, sizeof(__pyx_k__col), 0, 0, 1, 1}, + {&__pyx_n_s__compute_ward_dist, __pyx_k__compute_ward_dist, sizeof(__pyx_k__compute_ward_dist), 0, 0, 1, 1}, + {&__pyx_n_s__coord_col, __pyx_k__coord_col, sizeof(__pyx_k__coord_col), 0, 0, 1, 1}, + {&__pyx_n_s__coord_row, __pyx_k__coord_row, sizeof(__pyx_k__coord_row), 0, 0, 1, 1}, + {&__pyx_n_s__copy, __pyx_k__copy, sizeof(__pyx_k__copy), 0, 0, 1, 1}, + {&__pyx_n_s__decode, __pyx_k__decode, sizeof(__pyx_k__decode), 0, 0, 1, 1}, + {&__pyx_n_s__descendent, __pyx_k__descendent, sizeof(__pyx_k__descendent), 0, 0, 1, 1}, + {&__pyx_n_s__dtype_is_object, __pyx_k__dtype_is_object, sizeof(__pyx_k__dtype_is_object), 0, 0, 1, 1}, + {&__pyx_n_s__encode, __pyx_k__encode, sizeof(__pyx_k__encode), 0, 0, 1, 1}, + {&__pyx_n_s__enumerate, __pyx_k__enumerate, sizeof(__pyx_k__enumerate), 0, 0, 1, 1}, + {&__pyx_n_s__error, __pyx_k__error, sizeof(__pyx_k__error), 0, 0, 1, 1}, + {&__pyx_n_s__extend, __pyx_k__extend, sizeof(__pyx_k__extend), 0, 0, 1, 1}, + {&__pyx_n_s__flags, __pyx_k__flags, sizeof(__pyx_k__flags), 0, 0, 1, 1}, + {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, + {&__pyx_n_s__format, __pyx_k__format, sizeof(__pyx_k__format), 0, 0, 1, 1}, + {&__pyx_n_b__fortran, __pyx_k__fortran, sizeof(__pyx_k__fortran), 0, 0, 0, 1}, + {&__pyx_n_s__fortran, __pyx_k__fortran, sizeof(__pyx_k__fortran), 0, 0, 1, 1}, + {&__pyx_n_s__hc_get_heads, __pyx_k__hc_get_heads, sizeof(__pyx_k__hc_get_heads), 0, 0, 1, 1}, + {&__pyx_n_s__heads, __pyx_k__heads, sizeof(__pyx_k__heads), 0, 0, 1, 1}, + {&__pyx_n_s__i, __pyx_k__i, sizeof(__pyx_k__i), 0, 0, 1, 1}, + {&__pyx_n_s__id, __pyx_k__id, sizeof(__pyx_k__id), 0, 0, 1, 1}, + {&__pyx_n_s__ind, __pyx_k__ind, sizeof(__pyx_k__ind), 0, 0, 1, 1}, + {&__pyx_n_s__intp, __pyx_k__intp, sizeof(__pyx_k__intp), 0, 0, 1, 1}, + {&__pyx_n_s__itemsize, __pyx_k__itemsize, sizeof(__pyx_k__itemsize), 0, 0, 1, 1}, + {&__pyx_n_s__j, __pyx_k__j, sizeof(__pyx_k__j), 0, 0, 1, 1}, + {&__pyx_n_s__key, __pyx_k__key, sizeof(__pyx_k__key), 0, 0, 1, 1}, + {&__pyx_n_s__m_1, __pyx_k__m_1, sizeof(__pyx_k__m_1), 0, 0, 1, 1}, + {&__pyx_n_s__m_2, __pyx_k__m_2, sizeof(__pyx_k__m_2), 0, 0, 1, 1}, + {&__pyx_n_s__mask, __pyx_k__mask, sizeof(__pyx_k__mask), 0, 0, 1, 1}, + {&__pyx_n_s__max_merge, __pyx_k__max_merge, sizeof(__pyx_k__max_merge), 0, 0, 1, 1}, + {&__pyx_n_s__memview, __pyx_k__memview, sizeof(__pyx_k__memview), 0, 0, 1, 1}, + {&__pyx_n_s__mode, __pyx_k__mode, sizeof(__pyx_k__mode), 0, 0, 1, 1}, + {&__pyx_n_s__n, __pyx_k__n, sizeof(__pyx_k__n), 0, 0, 1, 1}, + {&__pyx_n_s__n_a, __pyx_k__n_a, sizeof(__pyx_k__n_a), 0, 0, 1, 1}, + {&__pyx_n_s__n_b, __pyx_k__n_b, sizeof(__pyx_k__n_b), 0, 0, 1, 1}, + {&__pyx_n_s__n_features, __pyx_k__n_features, sizeof(__pyx_k__n_features), 0, 0, 1, 1}, + {&__pyx_n_s__n_indices, __pyx_k__n_indices, sizeof(__pyx_k__n_indices), 0, 0, 1, 1}, + {&__pyx_n_s__n_leaves, __pyx_k__n_leaves, sizeof(__pyx_k__n_leaves), 0, 0, 1, 1}, + {&__pyx_n_s__n_out, __pyx_k__n_out, sizeof(__pyx_k__n_out), 0, 0, 1, 1}, + {&__pyx_n_s__name, __pyx_k__name, sizeof(__pyx_k__name), 0, 0, 1, 1}, + {&__pyx_n_s__ndim, __pyx_k__ndim, sizeof(__pyx_k__ndim), 0, 0, 1, 1}, + {&__pyx_n_s__node, __pyx_k__node, sizeof(__pyx_k__node), 0, 0, 1, 1}, + {&__pyx_n_s__node0, __pyx_k__node0, sizeof(__pyx_k__node0), 0, 0, 1, 1}, + {&__pyx_n_s__nodes, __pyx_k__nodes, sizeof(__pyx_k__nodes), 0, 0, 1, 1}, + {&__pyx_n_s__not_visited, __pyx_k__not_visited, sizeof(__pyx_k__not_visited), 0, 0, 1, 1}, + {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, + {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, + {&__pyx_n_s__obj, __pyx_k__obj, sizeof(__pyx_k__obj), 0, 0, 1, 1}, + {&__pyx_n_s__out_end, __pyx_k__out_end, sizeof(__pyx_k__out_end), 0, 0, 1, 1}, + {&__pyx_n_s__out_it, __pyx_k__out_it, sizeof(__pyx_k__out_it), 0, 0, 1, 1}, + {&__pyx_n_s__out_obj, __pyx_k__out_obj, sizeof(__pyx_k__out_obj), 0, 0, 1, 1}, + {&__pyx_n_s__pa, __pyx_k__pa, sizeof(__pyx_k__pa), 0, 0, 1, 1}, + {&__pyx_n_s__pack, __pyx_k__pack, sizeof(__pyx_k__pack), 0, 0, 1, 1}, + {&__pyx_n_s__parent, __pyx_k__parent, sizeof(__pyx_k__parent), 0, 0, 1, 1}, + {&__pyx_n_s__parents, __pyx_k__parents, sizeof(__pyx_k__parents), 0, 0, 1, 1}, + {&__pyx_n_s__pop, __pyx_k__pop, sizeof(__pyx_k__pop), 0, 0, 1, 1}, + {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, + {&__pyx_n_s__res, __pyx_k__res, sizeof(__pyx_k__res), 0, 0, 1, 1}, + {&__pyx_n_s__row, __pyx_k__row, sizeof(__pyx_k__row), 0, 0, 1, 1}, + {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, + {&__pyx_n_s__size, __pyx_k__size, sizeof(__pyx_k__size), 0, 0, 1, 1}, + {&__pyx_n_s__size_max, __pyx_k__size_max, sizeof(__pyx_k__size_max), 0, 0, 1, 1}, + {&__pyx_n_s__start, __pyx_k__start, sizeof(__pyx_k__start), 0, 0, 1, 1}, + {&__pyx_n_s__step, __pyx_k__step, sizeof(__pyx_k__step), 0, 0, 1, 1}, + {&__pyx_n_s__stop, __pyx_k__stop, sizeof(__pyx_k__stop), 0, 0, 1, 1}, + {&__pyx_n_s__struct, __pyx_k__struct, sizeof(__pyx_k__struct), 0, 0, 1, 1}, + {&__pyx_n_s__unpack, __pyx_k__unpack, sizeof(__pyx_k__unpack), 0, 0, 1, 1}, + {&__pyx_n_s__value, __pyx_k__value, sizeof(__pyx_k__value), 0, 0, 1, 1}, + {&__pyx_n_s__weight, __pyx_k__weight, sizeof(__pyx_k__weight), 0, 0, 1, 1}, + {&__pyx_n_s__xrange, __pyx_k__xrange, sizeof(__pyx_k__xrange), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s__MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s__enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s__Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s__TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s__id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s__IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "numpy.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_k_tuple_4 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_3)); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_4); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); + + /* "numpy.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_k_tuple_6 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_5)); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_6); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); + + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_k_tuple_8 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_7)); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_8); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); + + /* "numpy.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_k_tuple_11 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_10)); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_11); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); + + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_k_tuple_12 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_7)); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_12); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + + /* "numpy.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_k_tuple_14 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_13)); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_14); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + + /* "View.MemoryView":124 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if self.itemsize <= 0: + */ + __pyx_k_tuple_16 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_15)); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_16); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); + + /* "View.MemoryView":127 + * + * if self.itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * encode = getattr(format, 'encode', None) + */ + __pyx_k_tuple_18 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_17)); if (unlikely(!__pyx_k_tuple_18)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_18); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_18)); + + /* "View.MemoryView":131 + * encode = getattr(format, 'encode', None) + * if encode: + * format = encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format + * self.format = self._format + */ + __pyx_k_tuple_19 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__ASCII)); if (unlikely(!__pyx_k_tuple_19)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_19); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_19)); + + /* "View.MemoryView":141 + * free(self._shape) + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_21 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_20)); if (unlikely(!__pyx_k_tuple_21)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_21); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_21)); + + /* "View.MemoryView":166 + * decode = getattr(mode, 'decode', None) + * if decode: + * mode = decode('ASCII') # <<<<<<<<<<<<<< + * self.mode = mode + * + */ + __pyx_k_tuple_24 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__ASCII)); if (unlikely(!__pyx_k_tuple_24)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_24); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_24)); + + /* "View.MemoryView":174 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_k_tuple_26 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_25)); if (unlikely(!__pyx_k_tuple_26)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_26); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_26)); + + /* "View.MemoryView":190 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_k_tuple_28 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_27)); if (unlikely(!__pyx_k_tuple_28)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_28); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_28)); + + /* "View.MemoryView":452 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_k_tuple_30 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_29)); if (unlikely(!__pyx_k_tuple_30)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_30); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_30)); + + /* "View.MemoryView":528 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_k_tuple_32 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_31)); if (unlikely(!__pyx_k_tuple_32)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_32); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_32)); + + /* "View.MemoryView":643 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_k_tuple_35 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_35)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_35); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_35)); + + /* "View.MemoryView":646 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_k_tuple_36 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_36)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_36); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_36)); + + /* "View.MemoryView":657 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_k_tuple_38 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_38)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_38); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_38)); + + /* "View.MemoryView":665 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_40 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_39)); if (unlikely(!__pyx_k_tuple_40)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_40); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_40)); + + /* "sklearn/cluster/_hierarchical.pyx":38 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def compute_ward_dist(np.ndarray[DOUBLE, ndim=1, mode='c'] m_1, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=2, mode='c'] m_2, + * np.ndarray[INTP, ndim=1, mode='c'] coord_row, + */ + __pyx_k_tuple_48 = PyTuple_Pack(13, ((PyObject *)__pyx_n_s__m_1), ((PyObject *)__pyx_n_s__m_2), ((PyObject *)__pyx_n_s__coord_row), ((PyObject *)__pyx_n_s__coord_col), ((PyObject *)__pyx_n_s__res), ((PyObject *)__pyx_n_s__size_max), ((PyObject *)__pyx_n_s__n_features), ((PyObject *)__pyx_n_s__i), ((PyObject *)__pyx_n_s__j), ((PyObject *)__pyx_n_s__row), ((PyObject *)__pyx_n_s__col), ((PyObject *)__pyx_n_s__pa), ((PyObject *)__pyx_n_s__n)); if (unlikely(!__pyx_k_tuple_48)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_48); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_48)); + __pyx_k_codeobj_49 = (PyObject*)__Pyx_PyCode_New(5, 0, 13, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_48, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_50, __pyx_n_s__compute_ward_dist, 38, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_49)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/cluster/_hierarchical.pyx":62 + * # Utilities for cutting and exploring a hierarchical tree + * + * def _hc_get_descendent(INTP node, children, INTP n_leaves): # <<<<<<<<<<<<<< + * """ + * Function returning all the descendent leaves of a set of nodes in the tree. + */ + __pyx_k_tuple_52 = PyTuple_Pack(7, ((PyObject *)__pyx_n_s__node), ((PyObject *)__pyx_n_s__children), ((PyObject *)__pyx_n_s__n_leaves), ((PyObject *)__pyx_n_s__ind), ((PyObject *)__pyx_n_s__descendent), ((PyObject *)__pyx_n_s__i), ((PyObject *)__pyx_n_s__n_indices)); if (unlikely(!__pyx_k_tuple_52)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_52); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_52)); + __pyx_k_codeobj_53 = (PyObject*)__Pyx_PyCode_New(3, 0, 7, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_52, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_50, __pyx_n_s___hc_get_descendent, 62, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_53)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/cluster/_hierarchical.pyx":106 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def hc_get_heads(np.ndarray[INTP, ndim=1] parents, copy=True): # <<<<<<<<<<<<<< + * """Returns the heads of the forest, as defined by parents. + * + */ + __pyx_k_tuple_54 = PyTuple_Pack(6, ((PyObject *)__pyx_n_s__parents), ((PyObject *)__pyx_n_s__copy), ((PyObject *)__pyx_n_s__parent), ((PyObject *)__pyx_n_s__node0), ((PyObject *)__pyx_n_s__node), ((PyObject *)__pyx_n_s__size)); if (unlikely(!__pyx_k_tuple_54)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_54); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_54)); + __pyx_k_codeobj_55 = (PyObject*)__Pyx_PyCode_New(2, 0, 6, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_54, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_50, __pyx_n_s__hc_get_heads, 106, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_55)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/cluster/_hierarchical.pyx":140 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def _get_parents(nodes, heads, np.ndarray[INTP, ndim=1] parents, # <<<<<<<<<<<<<< + * np.ndarray[INT8, ndim=1, mode='c'] not_visited): + * """Returns the heads of the given nodes, as defined by parents. + */ + __pyx_k_tuple_56 = PyTuple_Pack(6, ((PyObject *)__pyx_n_s__nodes), ((PyObject *)__pyx_n_s__heads), ((PyObject *)__pyx_n_s__parents), ((PyObject *)__pyx_n_s__not_visited), ((PyObject *)__pyx_n_s__parent), ((PyObject *)__pyx_n_s__node)); if (unlikely(!__pyx_k_tuple_56)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_56); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_56)); + __pyx_k_codeobj_57 = (PyObject*)__Pyx_PyCode_New(4, 0, 6, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_56, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_50, __pyx_n_s___get_parents, 140, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_57)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/cluster/_hierarchical.pyx":181 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def max_merge(IntFloatDict a, IntFloatDict b, # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1] mask, + * ITYPE_t n_a, ITYPE_t n_b): + */ + __pyx_k_tuple_58 = PyTuple_Pack(14, ((PyObject *)__pyx_n_s__a), ((PyObject *)__pyx_n_s__b), ((PyObject *)__pyx_n_s__mask), ((PyObject *)__pyx_n_s__n_a), ((PyObject *)__pyx_n_s__n_b), ((PyObject *)__pyx_n_s__out_obj), ((PyObject *)__pyx_n_s__a_it), ((PyObject *)__pyx_n_s__a_end), ((PyObject *)__pyx_n_s__key), ((PyObject *)__pyx_n_s__value), ((PyObject *)__pyx_n_s__out_it), ((PyObject *)__pyx_n_s__out_end), ((PyObject *)__pyx_n_s__b_it), ((PyObject *)__pyx_n_s__b_end)); if (unlikely(!__pyx_k_tuple_58)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_58); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_58)); + __pyx_k_codeobj_59 = (PyObject*)__Pyx_PyCode_New(5, 0, 14, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_58, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_50, __pyx_n_s__max_merge, 181, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_59)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/cluster/_hierarchical.pyx":236 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def average_merge(IntFloatDict a, IntFloatDict b, # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1] mask, + * ITYPE_t n_a, ITYPE_t n_b): + */ + __pyx_k_tuple_60 = PyTuple_Pack(15, ((PyObject *)__pyx_n_s__a), ((PyObject *)__pyx_n_s__b), ((PyObject *)__pyx_n_s__mask), ((PyObject *)__pyx_n_s__n_a), ((PyObject *)__pyx_n_s__n_b), ((PyObject *)__pyx_n_s__out_obj), ((PyObject *)__pyx_n_s__a_it), ((PyObject *)__pyx_n_s__a_end), ((PyObject *)__pyx_n_s__key), ((PyObject *)__pyx_n_s__value), ((PyObject *)__pyx_n_s__n_out), ((PyObject *)__pyx_n_s__out_it), ((PyObject *)__pyx_n_s__out_end), ((PyObject *)__pyx_n_s__b_it), ((PyObject *)__pyx_n_s__b_end)); if (unlikely(!__pyx_k_tuple_60)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_60); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_60)); + __pyx_k_codeobj_61 = (PyObject*)__Pyx_PyCode_New(5, 0, 15, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_60, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_50, __pyx_n_s__average_merge, 236, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_61)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":282 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_k_tuple_64 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_63)); if (unlikely(!__pyx_k_tuple_64)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_64); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_64)); + + /* "View.MemoryView":283 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_k_tuple_66 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_65)); if (unlikely(!__pyx_k_tuple_66)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_66); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_66)); + + /* "View.MemoryView":284 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_68 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_67)); if (unlikely(!__pyx_k_tuple_68)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_68); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_68)); + + /* "View.MemoryView":287 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_k_tuple_70 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_69)); if (unlikely(!__pyx_k_tuple_70)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_70); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_70)); + + /* "View.MemoryView":288 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_72 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_71)); if (unlikely(!__pyx_k_tuple_72)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_72); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_72)); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC init_hierarchical(void); /*proto*/ +PyMODINIT_FUNC init_hierarchical(void) +#else +PyMODINIT_FUNC PyInit__hierarchical(void); /*proto*/ +PyMODINIT_FUNC PyInit__hierarchical(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__hierarchical(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_hierarchical"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.cluster._hierarchical")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.cluster._hierarchical", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__cluster___hierarchical) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + generic = Py_None; Py_INCREF(Py_None); + strided = Py_None; Py_INCREF(Py_None); + indirect = Py_None; Py_INCREF(Py_None); + contiguous = Py_None; Py_INCREF(Py_None); + indirect_contiguous = Py_None; Py_INCREF(Py_None); + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; + __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; + __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; + __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; + __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; + __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; + __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; + __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; + if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryview_type = &__pyx_type___pyx_memoryview; + if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_array_type = &__pyx_type___pyx_array; + __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; + __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; + __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; + __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; + __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 927; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 927; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; + if (PyType_Ready(&__pyx_type_7sklearn_7cluster_13_hierarchical_WeightedEdge) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 295; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "WeightedEdge", (PyObject *)&__pyx_type_7sklearn_7cluster_13_hierarchical_WeightedEdge) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 295; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_7cluster_13_hierarchical_WeightedEdge = &__pyx_type_7sklearn_7cluster_13_hierarchical_WeightedEdge; + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict = __Pyx_ImportType("sklearn.utils.fast_dict", "IntFloatDict", sizeof(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict), 1); if (unlikely(!__pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_5utils_9fast_dict_IntFloatDict = (struct __pyx_vtabstruct_7sklearn_5utils_9fast_dict_IntFloatDict*)__Pyx_GetVtable(__pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_5utils_9fast_dict_IntFloatDict)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/cluster/_hierarchical.pyx":3 + * # Author: Gael Varoquaux + * + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * cimport cython + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":14 + * # _always_ do that, or you will have segfaults + * + * np.import_array() # <<<<<<<<<<<<<< + * + * from sklearn.utils.fast_dict cimport IntFloatDict + */ + import_array(); + + /* "sklearn/cluster/_hierarchical.pyx":22 + * from libcpp.map cimport map as cpp_map + * + * DTYPE = np.float64 # <<<<<<<<<<<<<< + * ctypedef np.float64_t DTYPE_t + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__float64); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s__DTYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":25 + * ctypedef np.float64_t DTYPE_t + * + * ITYPE = np.intp # <<<<<<<<<<<<<< + * ctypedef np.intp_t ITYPE_t + * + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__intp); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s__ITYPE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":38 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def compute_ward_dist(np.ndarray[DOUBLE, ndim=1, mode='c'] m_1, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=2, mode='c'] m_2, + * np.ndarray[INTP, ndim=1, mode='c'] coord_row, + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_13_hierarchical_1compute_ward_dist, NULL, __pyx_n_s_51); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__compute_ward_dist, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":62 + * # Utilities for cutting and exploring a hierarchical tree + * + * def _hc_get_descendent(INTP node, children, INTP n_leaves): # <<<<<<<<<<<<<< + * """ + * Function returning all the descendent leaves of a set of nodes in the tree. + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_13_hierarchical_3_hc_get_descendent, NULL, __pyx_n_s_51); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s___hc_get_descendent, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":106 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def hc_get_heads(np.ndarray[INTP, ndim=1] parents, copy=True): # <<<<<<<<<<<<<< + * """Returns the heads of the forest, as defined by parents. + * + */ + __pyx_t_1 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_k_1 = __pyx_t_1; + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_13_hierarchical_5hc_get_heads, NULL, __pyx_n_s_51); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__hc_get_heads, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":140 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def _get_parents(nodes, heads, np.ndarray[INTP, ndim=1] parents, # <<<<<<<<<<<<<< + * np.ndarray[INT8, ndim=1, mode='c'] not_visited): + * """Returns the heads of the given nodes, as defined by parents. + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_13_hierarchical_7_get_parents, NULL, __pyx_n_s_51); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s___get_parents, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":181 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def max_merge(IntFloatDict a, IntFloatDict b, # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1] mask, + * ITYPE_t n_a, ITYPE_t n_b): + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_13_hierarchical_9max_merge, NULL, __pyx_n_s_51); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__max_merge, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":236 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def average_merge(IntFloatDict a, IntFloatDict b, # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1] mask, + * ITYPE_t n_a, ITYPE_t n_b): + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_13_hierarchical_11average_merge, NULL, __pyx_n_s_51); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__average_merge, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_hierarchical.pyx":1 + * # Author: Gael Varoquaux # <<<<<<<<<<<<<< + * + * import numpy as np + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + + /* "View.MemoryView":207 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * def __dealloc__(array self): + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_62); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_array_type); + + /* "View.MemoryView":282 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_64), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(generic); + __Pyx_DECREF(generic); + __Pyx_GIVEREF(__pyx_t_1); + generic = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":283 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_66), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(strided); + __Pyx_DECREF(strided); + __Pyx_GIVEREF(__pyx_t_1); + strided = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":284 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_68), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(indirect); + __Pyx_DECREF(indirect); + __Pyx_GIVEREF(__pyx_t_1); + indirect = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":287 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_70), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(contiguous); + __Pyx_DECREF(contiguous); + __Pyx_GIVEREF(__pyx_t_1); + contiguous = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":288 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_72), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(indirect_contiguous); + __Pyx_DECREF(indirect_contiguous); + __Pyx_GIVEREF(__pyx_t_1); + indirect_contiguous = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":503 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_62); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_memoryview_type); + + /* "View.MemoryView":958 + * return self.from_object + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_62); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 958; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 958; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_memoryviewslice_type); + + /* "View.MemoryView":1365 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.cluster._hierarchical", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.cluster._hierarchical"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (!type) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (Py_TYPE(obj) == type) return 1; + } + else { + if (PyObject_TypeCheck(obj, type)) return 1; + } + PyErr_Format(PyExc_TypeError, + "Argument '%s' has incorrect type (expected %s, got %s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; /* Consume from buffer string */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + if (isspace(*ts)) + continue; + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case 10: + case 13: + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } /* fall through */ + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 's': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + } else { + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + } + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +static CYTHON_INLINE PyObject* __Pyx_PyObject_Pop(PyObject* L) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x02040000 + if (likely(PyList_CheckExact(L)) + && likely(PyList_GET_SIZE(L) > (((PyListObject*)L)->allocated >> 1))) { + Py_SIZE(L) -= 1; + return PyList_GET_ITEM(L, PyList_GET_SIZE(L)); + } +#if PY_VERSION_HEX >= 0x02050000 + else if (Py_TYPE(L) == (&PySet_Type)) { + return PySet_Pop(L); + } +#endif +#endif + return __Pyx_PyObject_CallMethod0(L, __pyx_n_s__pop); +} + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static void __Pyx_RaiseBufferFallbackError(void) { + PyErr_Format(PyExc_ValueError, + "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +} + +static CYTHON_INLINE PyObject* __Pyx_PyObject_Append(PyObject* L, PyObject* x) { + if (likely(PyList_CheckExact(L))) { + if (unlikely(__Pyx_PyList_Append(L, x) < 0)) return NULL; + Py_INCREF(Py_None); + return Py_None; /* this is just to have an accurate signature */ + } else { + return __Pyx_PyObject_CallMethod1(L, __pyx_n_s__append, x); + } +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { + #endif +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +#if CYTHON_COMPILING_IN_CPYTHON +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) +#else + if (likely(PyString_Check(n))) +#endif + return __Pyx_PyObject_GetAttrStr(o, n); +#endif + return PyObject_GetAttr(o, n); +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r = __Pyx_GetAttr(o, n); + if (!r) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + goto bad; + PyErr_Clear(); + r = d; + Py_INCREF(d); + } + return r; +bad: + return NULL; +} + +static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { + Py_ssize_t q = a / b; + Py_ssize_t r = a - q*b; + q -= ((r != 0) & ((r ^ b) < 0)); + return q; +} + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyUnicode_CheckExact(s1) & PyUnicode_CheckExact(s2)) { + #if CYTHON_PEP393_ENABLED + if ((PyUnicode_READY(s1) < 0) || (PyUnicode_READY(s2) < 0)) + return -1; + if (PyUnicode_GET_LENGTH(s1) != PyUnicode_GET_LENGTH(s2)) { + return (equals == Py_NE); + } else if (PyUnicode_GET_LENGTH(s1) == 1) { + Py_UCS4 ch1 = PyUnicode_READ_CHAR(s1, 0); + Py_UCS4 ch2 = PyUnicode_READ_CHAR(s2, 0); + return (equals == Py_EQ) ? (ch1 == ch2) : (ch1 != ch2); + #else + if (PyUnicode_GET_SIZE(s1) != PyUnicode_GET_SIZE(s2)) { + return (equals == Py_NE); + } else if (PyUnicode_GET_SIZE(s1) == 1) { + Py_UNICODE ch1 = PyUnicode_AS_UNICODE(s1)[0]; + Py_UNICODE ch2 = PyUnicode_AS_UNICODE(s2)[0]; + return (equals == Py_EQ) ? (ch1 == ch2) : (ch1 != ch2); + #endif + } else { + int result = PyUnicode_Compare(s1, s2); + if ((result == -1) && unlikely(PyErr_Occurred())) + return -1; + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyUnicode_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyUnicode_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + length = strlen(cstring); + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + #endif + Py_INCREF(local_type); + Py_INCREF(local_value); + Py_INCREF(local_tb); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + /* Make sure tstate is in a consistent state when we XDECREF + these objects (DECREF may run arbitrary code). */ + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +static CYTHON_INLINE long __Pyx_div_long(long a, long b) { + long q = a / b; + long r = a - q*b; + q -= ((r != 0) & ((r ^ b) < 0)); + return q; +} + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s____pyx_vtable__, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +static void* __Pyx_GetVtable(PyObject *dict) { + void* ptr; + PyObject *ob = PyObject_GetItem(dict, __pyx_n_s____pyx_vtable__); + if (!ob) + goto bad; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + ptr = PyCapsule_GetPointer(ob, 0); +#else + ptr = PyCObject_AsVoidPtr(ob); +#endif + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t val) { + const Py_intptr_t neg_one = (Py_intptr_t)-1, const_zero = (Py_intptr_t)0; + const int is_unsigned = const_zero < neg_one; + if ((sizeof(Py_intptr_t) == sizeof(char)) || + (sizeof(Py_intptr_t) == sizeof(short))) { + return PyInt_FromLong((long)val); + } else if ((sizeof(Py_intptr_t) == sizeof(int)) || + (sizeof(Py_intptr_t) == sizeof(long))) { + if (is_unsigned) + return PyLong_FromUnsignedLong((unsigned long)val); + else + return PyInt_FromLong((long)val); + } else if (sizeof(Py_intptr_t) == sizeof(PY_LONG_LONG)) { + if (is_unsigned) + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); + else + return PyLong_FromLongLong((PY_LONG_LONG)val); + } else { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); + } +} + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_from_py_Py_intptr_t(PyObject* x) { + const Py_intptr_t neg_one = (Py_intptr_t)-1, const_zero = (Py_intptr_t)0; + const int is_unsigned = const_zero < neg_one; + if (sizeof(Py_intptr_t) == sizeof(char)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedChar(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedChar(x); + } else if (sizeof(Py_intptr_t) == sizeof(short)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedShort(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedShort(x); + } else if (sizeof(Py_intptr_t) == sizeof(int)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedInt(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedInt(x); + } else if (sizeof(Py_intptr_t) == sizeof(long)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedLong(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedLong(x); + } else if (sizeof(Py_intptr_t) == sizeof(PY_LONG_LONG)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedLongLong(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedLongLong(x); + } else { + #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); + #else + Py_intptr_t val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } + #endif + return (Py_intptr_t)-1; + } +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } + } + #endif + PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: + Py_DECREF(obj); + view->obj = NULL; +} +#endif /* PY_MAJOR_VERSION < 3 */ + + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s____import__); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (!buf) { + PyErr_SetString(PyExc_ValueError, + "buf is NULL."); + goto fail; + } else if (memviewslice->memview || memviewslice->data) { + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); + } + retval = 0; + goto no_fail; +fail: + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} +static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { + va_list vargs; + char msg[200]; + va_start(vargs, fmt); +#ifdef HAVE_STDARG_PROTOTYPES + va_start(vargs, fmt); +#else + va_start(vargs); +#endif + vsnprintf(msg, 200, fmt, vargs); + Py_FatalError(msg); + va_end(vargs); +} +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) +{ + int first_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview || (PyObject *) memview == Py_None) + return; /* allow uninitialized memoryview assignment */ + if (__pyx_get_slice_count(memview) < 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + first_time = __pyx_add_acquisition_count(memview) == 0; + if (first_time) { + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); + } + } +} +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, + int have_gil, int lineno) { + int last_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview ) { + return; + } else if ((PyObject *) memview == Py_None) { + memslice->memview = NULL; + return; + } + if (__pyx_get_slice_count(memview) <= 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; + if (last_time) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } + } else { + memslice->memview = NULL; + } +} + +static int +__pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim) +{ + int i, index, step, start; + Py_ssize_t itemsize = mvs->memview->view.itemsize; + if (order == 'F') { + step = 1; + start = 0; + } else { + step = -1; + start = ndim - 1; + } + for (i = 0; i < ndim; i++) { + index = start + step * i; + if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) + return 0; + itemsize *= mvs->shape[index]; + } + return 1; +} + +static void +__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + start = end = slice->data; + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + if (extent == 0) { + *out_start = *out_end = start; + return; + } else { + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); + } + } + *out_start = start; + *out_end = end + itemsize; +} +static int +__pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize) +{ + void *start1, *end1, *start2, *end2; + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + return (start1 < end2) && (start2 < end1); +} + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + for (i = 0; i < ndim; i++) { + if (from_mvs->suboffsets[i] >= 0) { + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; + } + } + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; + } + __Pyx_GOTREF(shape_tuple); + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromLong(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; + } else { + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; + } + } + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + goto no_fail; +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; +} + +static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) +{ + PyObject *cobj; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); +#endif + return cobj; +} + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +#else + PyErr_GetExcInfo(type, value, tb); +#endif +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(type, value, tb); +#endif +} + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { + const unsigned char neg_one = (unsigned char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned char" : + "value too large to convert to unsigned char"); + } + return (unsigned char)-1; + } + return (unsigned char)val; + } + return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { + const unsigned short neg_one = (unsigned short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned short" : + "value too large to convert to unsigned short"); + } + return (unsigned short)-1; + } + return (unsigned short)val; + } + return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { + const unsigned int neg_one = (unsigned int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned int" : + "value too large to convert to unsigned int"); + } + return (unsigned int)-1; + } + return (unsigned int)val; + } + return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { + const char neg_one = (char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to char" : + "value too large to convert to char"); + } + return (char)-1; + } + return (char)val; + } + return (char)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { + const short neg_one = (short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to short" : + "value too large to convert to short"); + } + return (short)-1; + } + return (short)val; + } + return (short)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { + const signed char neg_one = (signed char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed char" : + "value too large to convert to signed char"); + } + return (signed char)-1; + } + return (signed char)val; + } + return (signed char)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { + const signed short neg_one = (signed short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed short" : + "value too large to convert to signed short"); + } + return (signed short)-1; + } + return (signed short)val; + } + return (signed short)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { + const signed int neg_one = (signed int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed int" : + "value too large to convert to signed int"); + } + return (signed int)-1; + } + return (signed int)val; + } + return (signed int)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { + const unsigned long neg_one = (unsigned long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (unsigned long)PyLong_AsLong(x); + } + } else { + unsigned long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned long)-1; + val = __Pyx_PyInt_AsUnsignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { + const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + unsigned PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsUnsignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { + const long neg_one = (long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (long)PyLong_AsLong(x); + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long)-1; + val = __Pyx_PyInt_AsLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { + const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { + const signed long neg_one = (signed long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (signed long)PyLong_AsLong(x); + } + } else { + signed long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed long)-1; + val = __Pyx_PyInt_AsSignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { + const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + signed PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsSignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%s.%s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + #if PY_VERSION_HEX < 0x02050000 + if (PyErr_Warn(NULL, warning) < 0) goto bad; + #else + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + #endif + } + else if ((size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%s.%s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (r < 0) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_MAJOR_VERSION < 3 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%s__ returned non-%s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject* x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { + unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); + if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); + return (size_t)-1; + } + return (size_t)val; +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/cluster/_hierarchical.pyx b/sklearn/cluster/_hierarchical.pyx index 90443084e25c7..41daffd2b14c1 100644 --- a/sklearn/cluster/_hierarchical.pyx +++ b/sklearn/cluster/_hierarchical.pyx @@ -1,63 +1,95 @@ +# Author: Gael Varoquaux + import numpy as np cimport numpy as np cimport cython + ctypedef np.float64_t DOUBLE -ctypedef np.int_t INT +ctypedef np.npy_intp INTP ctypedef np.int8_t INT8 +# Numpy must be initialized. When using numpy from C or Cython you must +# _always_ do that, or you will have segfaults + +np.import_array() + +from sklearn.utils.fast_dict cimport IntFloatDict + +# C++ +from cython.operator cimport dereference as deref, preincrement as inc +from libcpp.map cimport map as cpp_map + +DTYPE = np.float64 +ctypedef np.float64_t DTYPE_t + +ITYPE = np.intp +ctypedef np.intp_t ITYPE_t + +# Reimplementation for MSVC support +cdef inline double fmax(double a, double b): + return max(a, b) + +############################################################################### +# Utilities for computing the ward momentum @cython.boundscheck(False) @cython.wraparound(False) @cython.cdivision(True) -def compute_ward_dist(np.ndarray[DOUBLE, ndim=1] m_1,\ - np.ndarray[DOUBLE, ndim=2] m_2,\ - np.ndarray[INT, ndim=1] coord_row, - np.ndarray[INT, ndim=1] coord_col,\ - np.ndarray[DOUBLE, ndim=1] res): - cdef int size_max = coord_row.shape[0] - cdef int n_features = m_2.shape[1] - cdef int i, j, row, col +def compute_ward_dist(np.ndarray[DOUBLE, ndim=1, mode='c'] m_1, + np.ndarray[DOUBLE, ndim=2, mode='c'] m_2, + np.ndarray[INTP, ndim=1, mode='c'] coord_row, + np.ndarray[INTP, ndim=1, mode='c'] coord_col, + np.ndarray[DOUBLE, ndim=1, mode='c'] res): + cdef INTP size_max = coord_row.shape[0] + cdef INTP n_features = m_2.shape[1] + cdef INTP i, j, row, col cdef DOUBLE pa, n + for i in range(size_max): row = coord_row[i] col = coord_col[i] n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) pa = 0. for j in range(n_features): - pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col])**2 + pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col]) ** 2 res[i] = pa * n return res -def _hc_get_descendent(int node, children, int n_leaves): +############################################################################### +# Utilities for cutting and exploring a hierarchical tree + +def _hc_get_descendent(INTP node, children, INTP n_leaves): """ Function returning all the descendent leaves of a set of nodes in the tree. Parameters ---------- - node : int + node : integer The node for which we want the descendents. - children : list of pairs. Length of n_nodes - List of the children of each nodes. - This is not defined for leaves. + children : list of pairs, length n_nodes + The children of each non-leaf node. Values less than `n_samples` refer + to leaves of the tree. A greater value `i` indicates a node with + children `children[i - n_samples]`. - n_leaves : int + n_leaves : integer Number of leaves. - Return - ------ + Returns + ------- descendent : list of int """ ind = [node] if node < n_leaves: return ind descendent = [] + # It is actually faster to do the accounting of the number of # elements is the list ourselves: len is a lengthy operation on a # chained list - cdef int n_indices = 1 - cdef int i + cdef INTP i, n_indices = 1 + while n_indices: i = ind.pop() if i < n_leaves: @@ -71,29 +103,29 @@ def _hc_get_descendent(int node, children, int n_leaves): @cython.boundscheck(False) @cython.wraparound(False) -def hc_get_heads(np.ndarray[INT, ndim=1] parents, copy=True): - """ Return the heads of the forest, as defined by parents - +def hc_get_heads(np.ndarray[INTP, ndim=1] parents, copy=True): + """Returns the heads of the forest, as defined by parents. + Parameters - =========== - parents: array of integers + ---------- + parents : array of integers The parent structure defining the forest (ensemble of trees) - copy: boolean + copy : boolean If copy is False, the input 'parents' array is modified inplace Returns - ======= - heads: array of integers of same shape as parents + ------- + heads : array of integers of same shape as parents The indices in the 'parents' of the tree heads """ - cdef unsigned int parent, node0, node, size + cdef INTP parent, node0, node, size if copy: parents = np.copy(parents) size = parents.size - for node0 in range(size): - # Start from the top of the tree and go down - node0 = size - node0 - 1 + + # Start from the top of the tree and go down + for node0 in range(size - 1, -1, -1): node = node0 parent = parents[node] while parent != node: @@ -105,25 +137,26 @@ def hc_get_heads(np.ndarray[INT, ndim=1] parents, copy=True): @cython.boundscheck(False) @cython.wraparound(False) -def _get_parents(nodes, heads, np.ndarray[INT, ndim=1] parents, - np.ndarray[INT8, ndim=1] not_visited): - """ Return the heads of the given nodes, as defined by parents - - Modifies in-place 'heads' and 'not_visited' +def _get_parents(nodes, heads, np.ndarray[INTP, ndim=1] parents, + np.ndarray[INT8, ndim=1, mode='c'] not_visited): + """Returns the heads of the given nodes, as defined by parents. + + Modifies 'heads' and 'not_visited' in-place. Parameters - =========== - nodes: list of integers + ---------- + nodes : list of integers The nodes to start from - heads: list of integers + heads : list of integers A list to hold the results (modified inplace) - parents: array of integers + parents : array of integers The parent structure defining the tree - not_visited: + not_visited The tree nodes to consider (modified inplace) """ - cdef unsigned int parent, node + cdef INTP parent, node + for node in nodes: parent = parents[node] while parent != node: @@ -133,3 +166,169 @@ def _get_parents(nodes, heads, np.ndarray[INT, ndim=1] parents, not_visited[node] = 0 heads.append(node) return heads + + +############################################################################### +# merge strategies implemented on IntFloatDicts + +# These are used in the hierarchical clustering code, to implement +# merging between two clusters, defined as a dict containing node number +# as keys and edge weights as values. + + +@cython.boundscheck(False) +@cython.wraparound(False) +def max_merge(IntFloatDict a, IntFloatDict b, + np.ndarray[ITYPE_t, ndim=1] mask, + ITYPE_t n_a, ITYPE_t n_b): + """Merge two IntFloatDicts with the max strategy: when the same key is + present in the two dicts, the max of the two values is used. + + Parameters + ========== + a, b : IntFloatDict object + The IntFloatDicts to merge + mask : ndarray array of dtype integer and of dimension 1 + a mask for keys to ignore: if not mask[key] the corresponding key + is skipped in the output dictionnary + n_a, n_b : float + n_a and n_b are weights for a and b for the merge strategy. + They are not used in the case of a max merge. + + Returns + ======= + out : IntFloatDict object + The IntFloatDict resulting from the merge + """ + cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) + cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_it = a.my_map.begin() + cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_end = a.my_map.end() + cdef ITYPE_t key + cdef DTYPE_t value + # First copy a into out + while a_it != a_end: + key = deref(a_it).first + if mask[key]: + out_obj.my_map[key] = deref(a_it).second + inc(a_it) + + # Then merge b into out + cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_it = out_obj.my_map.begin() + cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_end = out_obj.my_map.end() + cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() + cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() + while b_it != b_end: + key = deref(b_it).first + value = deref(b_it).second + if mask[key]: + out_it = out_obj.my_map.find(key) + if out_it == out_end: + # Key not found + out_obj.my_map[key] = value + else: + deref(out_it).second = fmax(deref(out_it).second, value) + inc(b_it) + return out_obj + + +@cython.boundscheck(False) +@cython.wraparound(False) +def average_merge(IntFloatDict a, IntFloatDict b, + np.ndarray[ITYPE_t, ndim=1] mask, + ITYPE_t n_a, ITYPE_t n_b): + """Merge two IntFloatDicts with the average strategy: when the + same key is present in the two dicts, the weighted average of the two + values is used. + + Parameters + ========== + a, b : IntFloatDict object + The IntFloatDicts to merge + mask : ndarray array of dtype integer and of dimension 1 + a mask for keys to ignore: if not mask[key] the corresponding key + is skipped in the output dictionnary + n_a, n_b : float + n_a and n_b are weights for a and b for the merge strategy. + They are used for a weighted mean. + + Returns + ======= + out : IntFloatDict object + The IntFloatDict resulting from the merge + """ + cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) + cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_it = a.my_map.begin() + cdef cpp_map[ITYPE_t, DTYPE_t].iterator a_end = a.my_map.end() + cdef ITYPE_t key + cdef DTYPE_t value + cdef DTYPE_t n_out = (n_a + n_b) + # First copy a into out + while a_it != a_end: + key = deref(a_it).first + if mask[key]: + out_obj.my_map[key] = deref(a_it).second + inc(a_it) + + # Then merge b into out + cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_it = out_obj.my_map.begin() + cdef cpp_map[ITYPE_t, DTYPE_t].iterator out_end = out_obj.my_map.end() + cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_it = b.my_map.begin() + cdef cpp_map[ITYPE_t, DTYPE_t].iterator b_end = b.my_map.end() + while b_it != b_end: + key = deref(b_it).first + value = deref(b_it).second + if mask[key]: + out_it = out_obj.my_map.find(key) + if out_it == out_end: + # Key not found + out_obj.my_map[key] = value + else: + deref(out_it).second = (n_a * deref(out_it).second + + n_b * value) / n_out + inc(b_it) + return out_obj + + +############################################################################### +# An edge object for fast comparisons + +cdef class WeightedEdge: + cdef public ITYPE_t a + cdef public ITYPE_t b + cdef public DTYPE_t weight + + def __init__(self, DTYPE_t weight, ITYPE_t a, ITYPE_t b): + self.weight = weight + self.a = a + self.b = b + + @cython.nonecheck(False) + def __richcmp__(self, WeightedEdge other, int op): + """Cython-specific comparison method. + + op is the comparison code:: + < 0 + == 2 + > 4 + <= 1 + != 3 + >= 5 + """ + if op == 0: + return self.weight < other.weight + elif op == 1: + return self.weight <= other.weight + elif op == 2: + return self.weight == other.weight + elif op == 3: + return self.weight != other.weight + elif op == 4: + return self.weight > other.weight + elif op == 5: + return self.weight >= other.weight + + def __repr__(self): + return "%s(weight=%f, a=%i, b=%i)" % (self.__class__.__name__, + self.weight, + self.a, self.b) + diff --git a/sklearn/cluster/_k_means.c b/sklearn/cluster/_k_means.c index b0cc819cfce78..a250f3e33c771 100644 --- a/sklearn/cluster/_k_means.c +++ b/sklearn/cluster/_k_means.c @@ -1,16 +1,29 @@ -/* Generated by Cython 0.15.1 on Wed Mar 14 15:56:03 2012 */ +/* Generated by Cython 0.21.2 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) + #error Cython requires Python 2.6+ or Python 3.2+. #else - -#include /* For offsetof */ +#define CYTHON_ABI "0_21_2" +#include #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -22,85 +35,84 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - -#if PY_VERSION_HEX < 0x02040000 - #define METH_COEXIST 0 - #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) - #define PyDict_Contains(d,o) PySequence_Contains(d,o) +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL #endif - -#if PY_VERSION_HEX < 0x02050000 - typedef int Py_ssize_t; - #define PY_SSIZE_T_MAX INT_MAX - #define PY_SSIZE_T_MIN INT_MIN - #define PY_FORMAT_SIZE_T "" - #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) - #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 #endif - -#if PY_VERSION_HEX < 0x02060000 - #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) - #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) - #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) - #define PyVarObject_HEAD_INIT(type, size) \ - PyObject_HEAD_INIT(type) size, - #define PyType_Modified(t) - - typedef struct { - void *buf; - PyObject *obj; - Py_ssize_t len; - Py_ssize_t itemsize; - int readonly; - int ndim; - char *format; - Py_ssize_t *shape; - Py_ssize_t *strides; - Py_ssize_t *suboffsets; - void *internal; - } Py_buffer; - - #define PyBUF_SIMPLE 0 - #define PyBUF_WRITABLE 0x0001 - #define PyBUF_FORMAT 0x0004 - #define PyBUF_ND 0x0008 - #define PyBUF_STRIDES (0x0010 | PyBUF_ND) - #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) - #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) - #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) - #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 +#define Py_OptimizeFlag 0 #endif - +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 -#endif - -#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) + #define __Pyx_PyFrozenSet_Size(s) PyObject_Size(s) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) + #define __Pyx_PyFrozenSet_Size(s) PySet_Size(s) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -108,36 +120,17 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - -#if PY_VERSION_HEX < 0x02060000 - #define PyBytesObject PyStringObject - #define PyBytes_Type PyString_Type - #define PyBytes_Check PyString_Check - #define PyBytes_CheckExact PyString_CheckExact - #define PyBytes_FromString PyString_FromString - #define PyBytes_FromStringAndSize PyString_FromStringAndSize - #define PyBytes_FromFormat PyString_FromFormat - #define PyBytes_DecodeEscape PyString_DecodeEscape - #define PyBytes_AsString PyString_AsString - #define PyBytes_AsStringAndSize PyString_AsStringAndSize - #define PyBytes_Size PyString_Size - #define PyBytes_AS_STRING PyString_AS_STRING - #define PyBytes_GET_SIZE PyString_GET_SIZE - #define PyBytes_Repr PyString_Repr - #define PyBytes_Concat PyString_Concat - #define PyBytes_ConcatAndDel PyString_ConcatAndDel -#endif - -#if PY_VERSION_HEX < 0x02060000 - #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) - #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -153,13 +146,17 @@ #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - -#if PY_VERSION_HEX < 0x03020000 +#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY + #ifndef PyUnicode_InternFromString + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) + #endif +#endif +#if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong @@ -167,55 +164,59 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - #if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) + #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) + #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif - -#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) - #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) - #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) -#else - #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) - #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif #endif - -#if PY_MAJOR_VERSION >= 3 - #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif #endif - -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#ifdef NAN +#define __PYX_NAN() ((float) NAN) #else - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#ifdef __cplusplus +template +void __Pyx_call_destructor(T* x) { + x->~T(); +} #endif -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_NAMESTR(n) ((char *)(n)) - #define __Pyx_DOCSTR(n) ((char *)(n)) + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else - #define __Pyx_NAMESTR(n) (n) - #define __Pyx_DOCSTR(n) (n) + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C @@ -232,11 +233,12 @@ #include #define __PYX_HAVE__sklearn__cluster___k_means #define __PYX_HAVE_API__sklearn__cluster___k_means +#include "math.h" +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" -#include "math.h" #include "cblas.h" #ifdef _OPENMP #include @@ -246,21 +248,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -268,48 +255,163 @@ # else # define CYTHON_UNUSED # endif -# elif defined(__ICC) || defined(__INTEL_COMPILER) +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif -#ifdef __GNUC__ - /* Test for GCC > 2.95 */ - #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) - #else /* __GNUC__ > 2 ... */ - #define likely(x) (x) - #define unlikely(x) (x) - #endif /* __GNUC__ > 2 ... */ -#else /* __GNUC__ */ +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -318,7 +420,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -328,7 +429,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -336,18 +436,54 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { - "_k_means.pyx", - "numpy.pxd", + "sklearn/cluster/_k_means.pyx", + "__init__.pxd", + "type.pxd", }; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; + struct __Pyx_StructField_* fields; + size_t size; + size_t arraysize[8]; + int ndim; + char typegroup; + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; -/* "numpy.pxd":719 + +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -356,7 +492,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -365,7 +501,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -374,7 +510,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -383,7 +519,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -392,7 +528,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -401,7 +537,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -410,7 +546,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -419,7 +555,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -428,7 +564,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -437,7 +573,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -446,7 +582,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -455,7 +591,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -464,7 +600,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -473,7 +609,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -482,7 +618,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -491,7 +627,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -500,7 +636,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -509,7 +645,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -518,7 +654,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -527,7 +663,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -536,8 +672,8 @@ typedef npy_double __pyx_t_5numpy_double_t; */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; -/* "sklearn/cluster/_k_means.pyx":15 - * cimport cython +/* "sklearn/cluster/_k_means.pyx":21 + * from sklearn.utils.fixes import bincount * * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< * ctypedef np.int32_t INT @@ -545,15 +681,14 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; */ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE; -/* "sklearn/cluster/_k_means.pyx":16 +/* "sklearn/cluster/_k_means.pyx":22 * * ctypedef np.float64_t DOUBLE * ctypedef np.int32_t INT # <<<<<<<<<<<<<< * - * + * cdef extern from "cblas.h": */ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_7cluster_8_k_means_INT; - #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -574,9 +709,10 @@ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_7cluster_8_k_means_INT; typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ -/* "numpy.pxd":758 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -585,7 +721,7 @@ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_7cluster_8_k_means_INT; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -594,7 +730,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -603,7 +739,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -611,12 +747,9 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; - - #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -627,10 +760,23 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -641,7 +787,7 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -651,238 +797,277 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) -#endif /* CYTHON_REFNANNY */ +#endif +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); #ifndef CYTHON_PROFILE #define CYTHON_PROFILE 1 #endif - +#ifndef CYTHON_TRACE + #define CYTHON_TRACE 0 +#endif +#if CYTHON_TRACE + #undef CYTHON_PROFILE_REUSE_FRAME +#endif #ifndef CYTHON_PROFILE_REUSE_FRAME #define CYTHON_PROFILE_REUSE_FRAME 0 #endif - -#if CYTHON_PROFILE - +#if CYTHON_PROFILE || CYTHON_TRACE #include "compile.h" #include "frameobject.h" #include "traceback.h" - #if CYTHON_PROFILE_REUSE_FRAME #define CYTHON_FRAME_MODIFIER static #define CYTHON_FRAME_DEL #else #define CYTHON_FRAME_MODIFIER - #define CYTHON_FRAME_DEL Py_DECREF(__pyx_frame) + #define CYTHON_FRAME_DEL Py_CLEAR(__pyx_frame) #endif - - #define __Pyx_TraceDeclarations \ + #define __Pyx_TraceDeclarations \ static PyCodeObject *__pyx_frame_code = NULL; \ CYTHON_FRAME_MODIFIER PyFrameObject *__pyx_frame = NULL; \ int __Pyx_use_tracing = 0; - #define __Pyx_TraceCall(funcname, srcfile, firstlineno) \ - if (unlikely(PyThreadState_GET()->use_tracing && PyThreadState_GET()->c_profilefunc)) { \ + if (unlikely(PyThreadState_GET()->use_tracing && \ + (PyThreadState_GET()->c_profilefunc || (CYTHON_TRACE && PyThreadState_GET()->c_tracefunc)))) { \ __Pyx_use_tracing = __Pyx_TraceSetupAndCall(&__pyx_frame_code, &__pyx_frame, funcname, srcfile, firstlineno); \ } - #define __Pyx_TraceException() \ - if (unlikely(__Pyx_use_tracing( && PyThreadState_GET()->use_tracing && PyThreadState_GET()->c_profilefunc) { \ + if (unlikely(__Pyx_use_tracing) && PyThreadState_GET()->use_tracing && \ + (PyThreadState_GET()->c_profilefunc || (CYTHON_TRACE && PyThreadState_GET()->c_tracefunc))) { \ + PyThreadState* tstate = PyThreadState_GET(); \ + tstate->use_tracing = 0; \ PyObject *exc_info = __Pyx_GetExceptionTuple(); \ if (exc_info) { \ - PyThreadState_GET()->c_profilefunc( \ - PyThreadState_GET()->c_profileobj, __pyx_frame, PyTrace_EXCEPTION, exc_info); \ + if (CYTHON_TRACE && tstate->c_tracefunc) \ + tstate->c_tracefunc( \ + tstate->c_traceobj, __pyx_frame, PyTrace_EXCEPTION, exc_info); \ + tstate->c_profilefunc( \ + tstate->c_profileobj, __pyx_frame, PyTrace_EXCEPTION, exc_info); \ Py_DECREF(exc_info); \ } \ + tstate->use_tracing = 1; \ } - #define __Pyx_TraceReturn(result) \ - if (unlikely(__Pyx_use_tracing) && PyThreadState_GET()->use_tracing && PyThreadState_GET()->c_profilefunc) { \ - PyThreadState_GET()->c_profilefunc( \ - PyThreadState_GET()->c_profileobj, __pyx_frame, PyTrace_RETURN, (PyObject*)result); \ - CYTHON_FRAME_DEL; \ + if (unlikely(__Pyx_use_tracing) && PyThreadState_GET()->use_tracing) { \ + PyThreadState* tstate = PyThreadState_GET(); \ + tstate->use_tracing = 0; \ + if (CYTHON_TRACE && tstate->c_tracefunc) \ + tstate->c_tracefunc( \ + tstate->c_traceobj, __pyx_frame, PyTrace_RETURN, (PyObject*)result); \ + if (tstate->c_profilefunc) \ + tstate->c_profilefunc( \ + tstate->c_profileobj, __pyx_frame, PyTrace_RETURN, (PyObject*)result); \ + CYTHON_FRAME_DEL; \ + tstate->use_tracing = 1; \ } - - static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno); /*proto*/ - static int __Pyx_TraceSetupAndCall(PyCodeObject** code, PyFrameObject** frame, const char *funcname, const char *srcfile, int firstlineno); /*proto*/ - + static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno); + static int __Pyx_TraceSetupAndCall(PyCodeObject** code, PyFrameObject** frame, const char *funcname, const char *srcfile, int firstlineno); #else - #define __Pyx_TraceDeclarations #define __Pyx_TraceCall(funcname, srcfile, firstlineno) #define __Pyx_TraceException() #define __Pyx_TraceReturn(result) +#endif +#if CYTHON_TRACE + #define __Pyx_TraceLine(lineno) \ + if (unlikely(__Pyx_use_tracing) && unlikely(PyThreadState_GET()->use_tracing && PyThreadState_GET()->c_tracefunc)) { \ + PyThreadState* tstate = PyThreadState_GET(); \ + __pyx_frame->f_lineno = lineno; \ + tstate->use_tracing = 0; \ + tstate->c_tracefunc(tstate->c_traceobj, __pyx_frame, PyTrace_LINE, NULL); \ + tstate->use_tracing = 1; \ + } +#else + #define __Pyx_TraceLine(lineno) +#endif -#endif /* CYTHON_PROFILE */ - -/* Run-time type information about structs used with buffers */ -struct __Pyx_StructField_; - -typedef struct { - const char* name; /* for error messages only */ - struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ -} __Pyx_TypeInfo; - -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ #define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) #define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename, + int full_traceback); static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ - -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); + +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); + +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +#define __Pyx_PyObject_DelSlice(obj, cstart, cstop, py_start, py_stop, py_slice, has_cstart, has_cstop, wraparound) \ + __Pyx_PyObject_SetSlice(obj, (PyObject*)NULL, cstart, cstop, py_start, py_stop, py_slice, has_cstart, has_cstop, wraparound) +static CYTHON_INLINE int __Pyx_PyObject_SetSlice( + PyObject* obj, PyObject* value, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); + +#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) : \ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck); + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); +#else +#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) +#endif +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} +static void __Pyx_RaiseBufferFallbackError(void); +static void __Pyx_RaiseBufferIndexError(int axis); -#define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_List_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +#define __Pyx_BufPtrCContig1d(type, buf, i0, s0) ((type)buf + i0) +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); -#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Tuple_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); -#define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { - PyObject *r; - if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) { - r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - } - else if (PyTuple_CheckExact(o) && ((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - } - else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0))) { - r = PySequence_GetItem(o, i); - } - else { - r = __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); - } - return r; -} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); -#define __Pyx_SetItemInt(o, i, v, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_SetItemInt_Fast(o, i, v) : \ - __Pyx_SetItemInt_Generic(o, to_py_func(i), v)) +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; -static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { - int r; - if (!j) return -1; - r = PyObject_SetItem(o, j, v); - Py_DECREF(j); - return r; -} +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v) { - if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) { - Py_INCREF(v); - Py_DECREF(PyList_GET_ITEM(o, i)); - PyList_SET_ITEM(o, i, v); - return 1; - } - else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && (likely(i >= 0))) - return PySequence_SetItem(o, i, v); - else { - PyObject *j = PyInt_FromSsize_t(i); - return __Pyx_SetItemInt_Generic(o, j, v); - } -} -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ -#if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); -static void __Pyx_ReleaseBuffer(Py_buffer *view); -#else -#define __Pyx_GetBuffer PyObject_GetBuffer -#define __Pyx_ReleaseBuffer PyBuffer_Release -#endif +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); -Py_ssize_t __Pyx_zeros[] = {0, 0}; -Py_ssize_t __Pyx_minusones[] = {-1, -1}; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_int32(npy_int32 value); -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *); #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -896,8 +1081,7 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - -#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else @@ -983,60 +1167,44 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); +static int __Pyx_check_binary_version(void); -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename); /*proto*/ +static PyObject *__Pyx_ImportModule(const char *name); -static int __Pyx_check_binary_version(void); +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ +/* Module declarations from 'libc.math' */ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -1047,129 +1215,212 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ - -/* Module declarations from 'cython.cython.view' */ /* Module declarations from 'cython' */ +/* Module declarations from 'sklearn.utils.sparsefuncs_fast' */ +static void (*__pyx_f_7sklearn_5utils_16sparsefuncs_fast_add_row_csr)(PyArrayObject *, PyArrayObject *, PyArrayObject *, int, PyArrayObject *); /*proto*/ + /* Module declarations from 'sklearn.cluster._k_means' */ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_means__assign_labels_array(PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, int __pyx_skip_dispatch); /*proto*/ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_means__assign_labels_csr(PyObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, int __pyx_skip_dispatch); /*proto*/ -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE), 'R' }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT = { "INT", NULL, sizeof(__pyx_t_7sklearn_7cluster_8_k_means_INT), 'I' }; -static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), 'I' }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT = { "INT", NULL, sizeof(__pyx_t_7sklearn_7cluster_8_k_means_INT), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_7cluster_8_k_means_INT) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_7cluster_8_k_means_INT), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn_npy_intp = { "npy_intp", NULL, sizeof(npy_intp), { 0 }, 0, IS_UNSIGNED(npy_intp) ? 'U' : 'I', IS_UNSIGNED(npy_intp), 0 }; #define __Pyx_MODULE_NAME "sklearn.cluster._k_means" int __pyx_module_is_main_sklearn__cluster___k_means = 0; /* Implementation of 'sklearn.cluster._k_means' */ static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_enumerate; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; -static char __pyx_k_1[] = "compute_squared_diff"; -static char __pyx_k_3[] = "ndarray is not C contiguous"; -static char __pyx_k_5[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_7[] = "Non-native byte order not supported"; -static char __pyx_k_9[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_10[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_13[] = "Format string allocated too short."; -static char __pyx_k_15[] = "utils.extmath"; -static char __pyx_k_16[] = "sklearn.cluster._k_means"; -static char __pyx_k_17[] = "_mini_batch_update_csr"; -static char __pyx_k__B[] = "B"; -static char __pyx_k__H[] = "H"; -static char __pyx_k__I[] = "I"; -static char __pyx_k__L[] = "L"; -static char __pyx_k__O[] = "O"; -static char __pyx_k__Q[] = "Q"; -static char __pyx_k__X[] = "X"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__d[] = "d"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__g[] = "g"; -static char __pyx_k__h[] = "h"; -static char __pyx_k__i[] = "i"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__q[] = "q"; -static char __pyx_k__Zd[] = "Zd"; -static char __pyx_k__Zf[] = "Zf"; -static char __pyx_k__Zg[] = "Zg"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__data[] = "data"; -static char __pyx_k__norm[] = "norm"; -static char __pyx_k__dtype[] = "dtype"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__range[] = "range"; -static char __pyx_k__shape[] = "shape"; -static char __pyx_k__zeros[] = "zeros"; -static char __pyx_k__counts[] = "counts"; -static char __pyx_k__indptr[] = "indptr"; -static char __pyx_k__labels[] = "labels"; -static char __pyx_k__centers[] = "centers"; -static char __pyx_k__float64[] = "float64"; -static char __pyx_k__indices[] = "indices"; -static char __pyx_k__squared[] = "squared"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__distances[] = "distances"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__old_center[] = "old_center"; -static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k__nearest_center[] = "nearest_center"; -static char __pyx_k__csr_row_norm_l2[] = "csr_row_norm_l2"; -static char __pyx_k__x_squared_norms[] = "x_squared_norms"; -static PyObject *__pyx_n_s_1; -static PyObject *__pyx_kp_u_10; -static PyObject *__pyx_kp_u_13; -static PyObject *__pyx_n_s_15; -static PyObject *__pyx_n_s_16; -static PyObject *__pyx_n_s_17; -static PyObject *__pyx_kp_u_3; -static PyObject *__pyx_kp_u_5; -static PyObject *__pyx_kp_u_7; -static PyObject *__pyx_kp_u_9; -static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s__X; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__centers; -static PyObject *__pyx_n_s__counts; -static PyObject *__pyx_n_s__csr_row_norm_l2; -static PyObject *__pyx_n_s__data; -static PyObject *__pyx_n_s__distances; -static PyObject *__pyx_n_s__dtype; -static PyObject *__pyx_n_s__float64; -static PyObject *__pyx_n_s__indices; -static PyObject *__pyx_n_s__indptr; -static PyObject *__pyx_n_s__labels; -static PyObject *__pyx_n_s__nearest_center; -static PyObject *__pyx_n_s__norm; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__old_center; -static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__shape; -static PyObject *__pyx_n_s__squared; -static PyObject *__pyx_n_s__x_squared_norms; -static PyObject *__pyx_n_s__zeros; -static PyObject *__pyx_int_15; -static PyObject *__pyx_k_2; -static PyObject *__pyx_k_tuple_4; -static PyObject *__pyx_k_tuple_6; -static PyObject *__pyx_k_tuple_8; -static PyObject *__pyx_k_tuple_11; -static PyObject *__pyx_k_tuple_12; -static PyObject *__pyx_k_tuple_14; - -/* "sklearn/cluster/_k_means.pyx":30 +static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means__assign_labels_array(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_x_squared_norms, PyArrayObject *__pyx_v_centers, PyArrayObject *__pyx_v_labels, PyArrayObject *__pyx_v_distances); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_assign_labels_csr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_x_squared_norms, PyArrayObject *__pyx_v_centers, PyArrayObject *__pyx_v_labels, PyArrayObject *__pyx_v_distances); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_4_mini_batch_update_csr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, CYTHON_UNUSED PyArrayObject *__pyx_v_x_squared_norms, PyArrayObject *__pyx_v_centers, PyArrayObject *__pyx_v_counts, PyArrayObject *__pyx_v_nearest_center, PyArrayObject *__pyx_v_old_center, int __pyx_v_compute_squared_diff); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_6_centers_dense(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_labels, int __pyx_v_n_clusters, PyArrayObject *__pyx_v_distances); /* proto */ +static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_8_centers_sparse(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_labels, PyObject *__pyx_v_n_clusters, PyArrayObject *__pyx_v_distances); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static char __pyx_k_B[] = "B"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_X[] = "X"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_c[] = "c"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_j[] = "j"; +static char __pyx_k_k[] = "k"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_sp[] = "sp"; +static char __pyx_k__12[] = "*"; +static char __pyx_k_data[] = "data"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_norm[] = "norm"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_shape[] = "shape"; +static char __pyx_k_where[] = "where"; +static char __pyx_k_zeros[] = "zeros"; +static char __pyx_k_X_data[] = "X_data"; +static char __pyx_k_counts[] = "counts"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_indptr[] = "indptr"; +static char __pyx_k_labels[] = "labels"; +static char __pyx_k_argsort[] = "argsort"; +static char __pyx_k_centers[] = "centers"; +static char __pyx_k_float64[] = "float64"; +static char __pyx_k_indices[] = "indices"; +static char __pyx_k_newaxis[] = "newaxis"; +static char __pyx_k_X_indptr[] = "X_indptr"; +static char __pyx_k_bincount[] = "bincount"; +static char __pyx_k_X_indices[] = "X_indices"; +static char __pyx_k_distances[] = "distances"; +static char __pyx_k_enumerate[] = "enumerate"; +static char __pyx_k_minlength[] = "minlength"; +static char __pyx_k_n_samples[] = "n_samples"; +static char __pyx_k_new_count[] = "new_count"; +static char __pyx_k_old_count[] = "old_count"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_center_idx[] = "center_idx"; +static char __pyx_k_cluster_id[] = "cluster_id"; +static char __pyx_k_n_clusters[] = "n_clusters"; +static char __pyx_k_n_features[] = "n_features"; +static char __pyx_k_new_center[] = "new_center"; +static char __pyx_k_old_center[] = "old_center"; +static char __pyx_k_sample_idx[] = "sample_idx"; +static char __pyx_k_center_diff[] = "center_diff"; +static char __pyx_k_feature_idx[] = "feature_idx"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_scipy_sparse[] = "scipy.sparse"; +static char __pyx_k_squared_diff[] = "squared_diff"; +static char __pyx_k_centers_dense[] = "_centers_dense"; +static char __pyx_k_utils_extmath[] = "utils.extmath"; +static char __pyx_k_centers_sparse[] = "_centers_sparse"; +static char __pyx_k_empty_clusters[] = "empty_clusters"; +static char __pyx_k_nearest_center[] = "nearest_center"; +static char __pyx_k_x_squared_norms[] = "x_squared_norms"; +static char __pyx_k_far_from_centers[] = "far_from_centers"; +static char __pyx_k_sklearn_utils_fixes[] = "sklearn.utils.fixes"; +static char __pyx_k_compute_squared_diff[] = "compute_squared_diff"; +static char __pyx_k_n_samples_in_cluster[] = "n_samples_in_cluster"; +static char __pyx_k_mini_batch_update_csr[] = "_mini_batch_update_csr"; +static char __pyx_k_sklearn_cluster__k_means[] = "sklearn.cluster._k_means"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_home_lesteve_dev_scikit_learn_s[] = "/home/lesteve/dev/scikit-learn/sklearn/cluster/_k_means.pyx"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_n_s_X_data; +static PyObject *__pyx_n_s_X_indices; +static PyObject *__pyx_n_s_X_indptr; +static PyObject *__pyx_n_s__12; +static PyObject *__pyx_n_s_argsort; +static PyObject *__pyx_n_s_bincount; +static PyObject *__pyx_n_s_c; +static PyObject *__pyx_n_s_center_diff; +static PyObject *__pyx_n_s_center_idx; +static PyObject *__pyx_n_s_centers; +static PyObject *__pyx_n_s_centers_dense; +static PyObject *__pyx_n_s_centers_sparse; +static PyObject *__pyx_n_s_cluster_id; +static PyObject *__pyx_n_s_compute_squared_diff; +static PyObject *__pyx_n_s_counts; +static PyObject *__pyx_n_s_data; +static PyObject *__pyx_n_s_distances; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_empty_clusters; +static PyObject *__pyx_n_s_enumerate; +static PyObject *__pyx_n_s_far_from_centers; +static PyObject *__pyx_n_s_feature_idx; +static PyObject *__pyx_n_s_float64; +static PyObject *__pyx_kp_s_home_lesteve_dev_scikit_learn_s; +static PyObject *__pyx_n_s_i; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_indices; +static PyObject *__pyx_n_s_indptr; +static PyObject *__pyx_n_s_j; +static PyObject *__pyx_n_s_k; +static PyObject *__pyx_n_s_labels; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_mini_batch_update_csr; +static PyObject *__pyx_n_s_minlength; +static PyObject *__pyx_n_s_n_clusters; +static PyObject *__pyx_n_s_n_features; +static PyObject *__pyx_n_s_n_samples; +static PyObject *__pyx_n_s_n_samples_in_cluster; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_nearest_center; +static PyObject *__pyx_n_s_new_center; +static PyObject *__pyx_n_s_new_count; +static PyObject *__pyx_n_s_newaxis; +static PyObject *__pyx_n_s_norm; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_old_center; +static PyObject *__pyx_n_s_old_count; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_sample_idx; +static PyObject *__pyx_n_s_scipy_sparse; +static PyObject *__pyx_n_s_shape; +static PyObject *__pyx_n_s_sklearn_cluster__k_means; +static PyObject *__pyx_n_s_sklearn_utils_fixes; +static PyObject *__pyx_n_s_sp; +static PyObject *__pyx_n_s_squared_diff; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_utils_extmath; +static PyObject *__pyx_n_s_where; +static PyObject *__pyx_n_s_x_squared_norms; +static PyObject *__pyx_n_s_zeros; +static PyObject *__pyx_float_0_; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_1; +static PyObject *__pyx_int_neg_1; +static PyObject *__pyx_slice_; +static PyObject *__pyx_slice__2; +static PyObject *__pyx_slice__3; +static PyObject *__pyx_slice__4; +static PyObject *__pyx_slice__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__8; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_tuple__10; +static PyObject *__pyx_tuple__11; +static PyObject *__pyx_tuple__13; +static PyObject *__pyx_tuple__15; +static PyObject *__pyx_tuple__17; +static PyObject *__pyx_codeobj__14; +static PyObject *__pyx_codeobj__16; +static PyObject *__pyx_codeobj__18; + +/* "sklearn/cluster/_k_means.pyx":33 * @cython.wraparound(False) * @cython.cdivision(True) * cpdef DOUBLE _assign_labels_array(np.ndarray[DOUBLE, ndim=2] X, # <<<<<<<<<<<<<< @@ -1177,8 +1428,8 @@ static PyObject *__pyx_k_tuple_14; * np.ndarray[DOUBLE, ndim=2] centers, */ -static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means__assign_labels_array(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_means__assign_labels_array(PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_x_squared_norms, PyArrayObject *__pyx_v_centers, PyArrayObject *__pyx_v_labels, PyArrayObject *__pyx_v_distances, int __pyx_skip_dispatch) { +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_1_assign_labels_array(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_means__assign_labels_array(PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_x_squared_norms, PyArrayObject *__pyx_v_centers, PyArrayObject *__pyx_v_labels, PyArrayObject *__pyx_v_distances, CYTHON_UNUSED int __pyx_skip_dispatch) { unsigned int __pyx_v_n_clusters; unsigned int __pyx_v_n_features; unsigned int __pyx_v_n_samples; @@ -1189,28 +1440,18 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_v_min_dist; __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_v_dist; PyArrayObject *__pyx_v_center_squared_norms = 0; - Py_buffer __pyx_bstruct_distances; - Py_ssize_t __pyx_bstride_0_distances = 0; - Py_ssize_t __pyx_bshape_0_distances = 0; - Py_buffer __pyx_bstruct_center_squared_norms; - Py_ssize_t __pyx_bstride_0_center_squared_norms = 0; - Py_ssize_t __pyx_bshape_0_center_squared_norms = 0; - Py_buffer __pyx_bstruct_labels; - Py_ssize_t __pyx_bstride_0_labels = 0; - Py_ssize_t __pyx_bshape_0_labels = 0; - Py_buffer __pyx_bstruct_centers; - Py_ssize_t __pyx_bstride_0_centers = 0; - Py_ssize_t __pyx_bstride_1_centers = 0; - Py_ssize_t __pyx_bshape_0_centers = 0; - Py_ssize_t __pyx_bshape_1_centers = 0; - Py_buffer __pyx_bstruct_X; - Py_ssize_t __pyx_bstride_0_X = 0; - Py_ssize_t __pyx_bstride_1_X = 0; - Py_ssize_t __pyx_bshape_0_X = 0; - Py_ssize_t __pyx_bshape_1_X = 0; - Py_buffer __pyx_bstruct_x_squared_norms; - Py_ssize_t __pyx_bstride_0_x_squared_norms = 0; - Py_ssize_t __pyx_bshape_0_x_squared_norms = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_LocalBuf_ND __pyx_pybuffernd_center_squared_norms; + __Pyx_Buffer __pyx_pybuffer_center_squared_norms; + __Pyx_LocalBuf_ND __pyx_pybuffernd_centers; + __Pyx_Buffer __pyx_pybuffer_centers; + __Pyx_LocalBuf_ND __pyx_pybuffernd_distances; + __Pyx_Buffer __pyx_pybuffer_distances; + __Pyx_LocalBuf_ND __pyx_pybuffernd_labels; + __Pyx_Buffer __pyx_pybuffer_labels; + __Pyx_LocalBuf_ND __pyx_pybuffernd_x_squared_norms; + __Pyx_Buffer __pyx_pybuffer_x_squared_norms; __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -1236,52 +1477,64 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ unsigned int __pyx_t_21; unsigned int __pyx_t_22; int __pyx_t_23; - int __pyx_t_24; - unsigned int __pyx_t_25; + unsigned int __pyx_t_24; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("_assign_labels_array"); - __Pyx_TraceCall("_assign_labels_array", __pyx_f[0], 30); - __pyx_bstruct_center_squared_norms.buf = NULL; - __pyx_bstruct_X.buf = NULL; - __pyx_bstruct_x_squared_norms.buf = NULL; - __pyx_bstruct_centers.buf = NULL; - __pyx_bstruct_labels.buf = NULL; - __pyx_bstruct_distances.buf = NULL; + __Pyx_RefNannySetupContext("_assign_labels_array", 0); + __Pyx_TraceCall("_assign_labels_array", __pyx_f[0], 33); + __pyx_pybuffer_center_squared_norms.pybuffer.buf = NULL; + __pyx_pybuffer_center_squared_norms.refcount = 0; + __pyx_pybuffernd_center_squared_norms.data = NULL; + __pyx_pybuffernd_center_squared_norms.rcbuffer = &__pyx_pybuffer_center_squared_norms; + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + __pyx_pybuffer_x_squared_norms.pybuffer.buf = NULL; + __pyx_pybuffer_x_squared_norms.refcount = 0; + __pyx_pybuffernd_x_squared_norms.data = NULL; + __pyx_pybuffernd_x_squared_norms.rcbuffer = &__pyx_pybuffer_x_squared_norms; + __pyx_pybuffer_centers.pybuffer.buf = NULL; + __pyx_pybuffer_centers.refcount = 0; + __pyx_pybuffernd_centers.data = NULL; + __pyx_pybuffernd_centers.rcbuffer = &__pyx_pybuffer_centers; + __pyx_pybuffer_labels.pybuffer.buf = NULL; + __pyx_pybuffer_labels.refcount = 0; + __pyx_pybuffernd_labels.data = NULL; + __pyx_pybuffernd_labels.rcbuffer = &__pyx_pybuffer_labels; + __pyx_pybuffer_distances.pybuffer.buf = NULL; + __pyx_pybuffer_distances.refcount = 0; + __pyx_pybuffernd_distances.data = NULL; + __pyx_pybuffernd_distances.rcbuffer = &__pyx_pybuffer_distances; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_X = __pyx_bstruct_X.strides[0]; __pyx_bstride_1_X = __pyx_bstruct_X.strides[1]; - __pyx_bshape_0_X = __pyx_bstruct_X.shape[0]; __pyx_bshape_1_X = __pyx_bstruct_X.shape[1]; + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_x_squared_norms, (PyObject*)__pyx_v_x_squared_norms, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer, (PyObject*)__pyx_v_x_squared_norms, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_x_squared_norms = __pyx_bstruct_x_squared_norms.strides[0]; - __pyx_bshape_0_x_squared_norms = __pyx_bstruct_x_squared_norms.shape[0]; + __pyx_pybuffernd_x_squared_norms.diminfo[0].strides = __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x_squared_norms.diminfo[0].shape = __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_centers, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_centers.rcbuffer->pybuffer, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_centers = __pyx_bstruct_centers.strides[0]; __pyx_bstride_1_centers = __pyx_bstruct_centers.strides[1]; - __pyx_bshape_0_centers = __pyx_bstruct_centers.shape[0]; __pyx_bshape_1_centers = __pyx_bstruct_centers.shape[1]; + __pyx_pybuffernd_centers.diminfo[0].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_centers.diminfo[0].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_centers.diminfo[1].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_centers.diminfo[1].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_labels, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_labels = __pyx_bstruct_labels.strides[0]; - __pyx_bshape_0_labels = __pyx_bstruct_labels.shape[0]; + __pyx_pybuffernd_labels.diminfo[0].strides = __pyx_pybuffernd_labels.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_labels.diminfo[0].shape = __pyx_pybuffernd_labels.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_distances, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_distances.rcbuffer->pybuffer, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_distances = __pyx_bstruct_distances.strides[0]; - __pyx_bshape_0_distances = __pyx_bstruct_distances.shape[0]; + __pyx_pybuffernd_distances.diminfo[0].strides = __pyx_pybuffernd_distances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_distances.diminfo[0].shape = __pyx_pybuffernd_distances.rcbuffer->pybuffer.shape[0]; - /* "sklearn/cluster/_k_means.pyx":40 + /* "sklearn/cluster/_k_means.pyx":43 * """ * cdef: * unsigned int n_clusters = centers.shape[0] # <<<<<<<<<<<<<< @@ -1290,7 +1543,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_n_clusters = (__pyx_v_centers->dimensions[0]); - /* "sklearn/cluster/_k_means.pyx":41 + /* "sklearn/cluster/_k_means.pyx":44 * cdef: * unsigned int n_clusters = centers.shape[0] * unsigned int n_features = centers.shape[1] # <<<<<<<<<<<<<< @@ -1299,7 +1552,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_n_features = (__pyx_v_centers->dimensions[1]); - /* "sklearn/cluster/_k_means.pyx":42 + /* "sklearn/cluster/_k_means.pyx":45 * unsigned int n_clusters = centers.shape[0] * unsigned int n_features = centers.shape[1] * unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< @@ -1308,7 +1561,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_n_samples = (__pyx_v_X->dimensions[0]); - /* "sklearn/cluster/_k_means.pyx":44 + /* "sklearn/cluster/_k_means.pyx":47 * unsigned int n_samples = X.shape[0] * unsigned int sample_idx, center_idx, feature_idx * unsigned int store_distances = 0 # <<<<<<<<<<<<<< @@ -1317,7 +1570,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_store_distances = 0; - /* "sklearn/cluster/_k_means.pyx":46 + /* "sklearn/cluster/_k_means.pyx":49 * unsigned int store_distances = 0 * unsigned int k * DOUBLE inertia = 0.0 # <<<<<<<<<<<<<< @@ -1326,89 +1579,96 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_inertia = 0.0; - /* "sklearn/cluster/_k_means.pyx":49 + /* "sklearn/cluster/_k_means.pyx":52 * DOUBLE min_dist * DOUBLE dist * np.ndarray[DOUBLE, ndim=1] center_squared_norms = np.zeros( # <<<<<<<<<<<<<< * n_clusters, dtype=np.float64) * */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/cluster/_k_means.pyx":50 + /* "sklearn/cluster/_k_means.pyx":53 * DOUBLE dist * np.ndarray[DOUBLE, ndim=1] center_squared_norms = np.zeros( * n_clusters, dtype=np.float64) # <<<<<<<<<<<<<< * * if n_samples == distances.shape[0]: */ - __pyx_t_1 = PyLong_FromUnsignedLong(__pyx_v_n_clusters); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_clusters); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - /* "sklearn/cluster/_k_means.pyx":49 + /* "sklearn/cluster/_k_means.pyx":52 * DOUBLE min_dist * DOUBLE dist * np.ndarray[DOUBLE, ndim=1] center_squared_norms = np.zeros( # <<<<<<<<<<<<<< * n_clusters, dtype=np.float64) * */ - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); - /* "sklearn/cluster/_k_means.pyx":50 + /* "sklearn/cluster/_k_means.pyx":53 * DOUBLE dist * np.ndarray[DOUBLE, ndim=1] center_squared_norms = np.zeros( * n_clusters, dtype=np.float64) # <<<<<<<<<<<<<< * * if n_samples == distances.shape[0]: */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/cluster/_k_means.pyx":52 + * DOUBLE min_dist + * DOUBLE dist + * np.ndarray[DOUBLE, ndim=1] center_squared_norms = np.zeros( # <<<<<<<<<<<<<< + * n_clusters, dtype=np.float64) + * + */ + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_center_squared_norms, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_center_squared_norms = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_center_squared_norms.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_center_squared_norms = __pyx_bstruct_center_squared_norms.strides[0]; - __pyx_bshape_0_center_squared_norms = __pyx_bstruct_center_squared_norms.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_center_squared_norms = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_center_squared_norms.diminfo[0].strides = __pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_center_squared_norms.diminfo[0].shape = __pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer.shape[0]; } } __pyx_t_6 = 0; __pyx_v_center_squared_norms = ((PyArrayObject *)__pyx_t_5); __pyx_t_5 = 0; - /* "sklearn/cluster/_k_means.pyx":52 + /* "sklearn/cluster/_k_means.pyx":55 * n_clusters, dtype=np.float64) * * if n_samples == distances.shape[0]: # <<<<<<<<<<<<<< * store_distances = 1 * */ - __pyx_t_7 = (__pyx_v_n_samples == (__pyx_v_distances->dimensions[0])); + __pyx_t_7 = ((__pyx_v_n_samples == (__pyx_v_distances->dimensions[0])) != 0); if (__pyx_t_7) { - /* "sklearn/cluster/_k_means.pyx":53 + /* "sklearn/cluster/_k_means.pyx":56 * * if n_samples == distances.shape[0]: * store_distances = 1 # <<<<<<<<<<<<<< @@ -1420,7 +1680,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ } __pyx_L3:; - /* "sklearn/cluster/_k_means.pyx":55 + /* "sklearn/cluster/_k_means.pyx":58 * store_distances = 1 * * for center_idx in range(n_clusters): # <<<<<<<<<<<<<< @@ -1431,7 +1691,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { __pyx_v_center_idx = __pyx_t_9; - /* "sklearn/cluster/_k_means.pyx":57 + /* "sklearn/cluster/_k_means.pyx":60 * for center_idx in range(n_clusters): * center_squared_norms[center_idx] = ddot( * n_features, ¢ers[center_idx, 0], 1, ¢ers[center_idx, 0], 1) # <<<<<<<<<<<<<< @@ -1443,7 +1703,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ __pyx_t_12 = __pyx_v_center_idx; __pyx_t_13 = 0; - /* "sklearn/cluster/_k_means.pyx":56 + /* "sklearn/cluster/_k_means.pyx":59 * * for center_idx in range(n_clusters): * center_squared_norms[center_idx] = ddot( # <<<<<<<<<<<<<< @@ -1451,10 +1711,10 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ * */ __pyx_t_14 = __pyx_v_center_idx; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_center_squared_norms.buf, __pyx_t_14, __pyx_bstride_0_center_squared_norms) = cblas_ddot(__pyx_v_n_features, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_centers.buf, __pyx_t_10, __pyx_bstride_0_centers, __pyx_t_11, __pyx_bstride_1_centers))), 1, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_centers.buf, __pyx_t_12, __pyx_bstride_0_centers, __pyx_t_13, __pyx_bstride_1_centers))), 1); + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_center_squared_norms.diminfo[0].strides) = cblas_ddot(__pyx_v_n_features, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_centers.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_centers.diminfo[0].strides, __pyx_t_11, __pyx_pybuffernd_centers.diminfo[1].strides))), 1, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_centers.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_centers.diminfo[0].strides, __pyx_t_13, __pyx_pybuffernd_centers.diminfo[1].strides))), 1); } - /* "sklearn/cluster/_k_means.pyx":59 + /* "sklearn/cluster/_k_means.pyx":62 * n_features, ¢ers[center_idx, 0], 1, ¢ers[center_idx, 0], 1) * * for sample_idx in range(n_samples): # <<<<<<<<<<<<<< @@ -1465,7 +1725,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { __pyx_v_sample_idx = __pyx_t_9; - /* "sklearn/cluster/_k_means.pyx":60 + /* "sklearn/cluster/_k_means.pyx":63 * * for sample_idx in range(n_samples): * min_dist = -1 # <<<<<<<<<<<<<< @@ -1474,7 +1734,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_min_dist = -1.0; - /* "sklearn/cluster/_k_means.pyx":61 + /* "sklearn/cluster/_k_means.pyx":64 * for sample_idx in range(n_samples): * min_dist = -1 * for center_idx in range(n_clusters): # <<<<<<<<<<<<<< @@ -1485,7 +1745,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ for (__pyx_t_16 = 0; __pyx_t_16 < __pyx_t_15; __pyx_t_16+=1) { __pyx_v_center_idx = __pyx_t_16; - /* "sklearn/cluster/_k_means.pyx":62 + /* "sklearn/cluster/_k_means.pyx":65 * min_dist = -1 * for center_idx in range(n_clusters): * dist = 0.0 # <<<<<<<<<<<<<< @@ -1494,7 +1754,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_dist = 0.0; - /* "sklearn/cluster/_k_means.pyx":65 + /* "sklearn/cluster/_k_means.pyx":68 * # hardcoded: minimize euclidean distance to cluster center: * # ||a - b||^2 = ||a||^2 + ||b||^2 -2 * dist += ddot(n_features, &X[sample_idx, 0], 1, # <<<<<<<<<<<<<< @@ -1504,7 +1764,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ __pyx_t_17 = __pyx_v_sample_idx; __pyx_t_18 = 0; - /* "sklearn/cluster/_k_means.pyx":66 + /* "sklearn/cluster/_k_means.pyx":69 * # ||a - b||^2 = ||a||^2 + ||b||^2 -2 * dist += ddot(n_features, &X[sample_idx, 0], 1, * ¢ers[center_idx, 0], 1) # <<<<<<<<<<<<<< @@ -1513,9 +1773,17 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_t_19 = __pyx_v_center_idx; __pyx_t_20 = 0; - __pyx_v_dist = (__pyx_v_dist + cblas_ddot(__pyx_v_n_features, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_X.buf, __pyx_t_17, __pyx_bstride_0_X, __pyx_t_18, __pyx_bstride_1_X))), 1, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_centers.buf, __pyx_t_19, __pyx_bstride_0_centers, __pyx_t_20, __pyx_bstride_1_centers))), 1)); - /* "sklearn/cluster/_k_means.pyx":67 + /* "sklearn/cluster/_k_means.pyx":68 + * # hardcoded: minimize euclidean distance to cluster center: + * # ||a - b||^2 = ||a||^2 + ||b||^2 -2 + * dist += ddot(n_features, &X[sample_idx, 0], 1, # <<<<<<<<<<<<<< + * ¢ers[center_idx, 0], 1) + * dist *= -2 + */ + __pyx_v_dist = (__pyx_v_dist + cblas_ddot(__pyx_v_n_features, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_X.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_X.diminfo[0].strides, __pyx_t_18, __pyx_pybuffernd_X.diminfo[1].strides))), 1, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_centers.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_centers.diminfo[0].strides, __pyx_t_20, __pyx_pybuffernd_centers.diminfo[1].strides))), 1)); + + /* "sklearn/cluster/_k_means.pyx":70 * dist += ddot(n_features, &X[sample_idx, 0], 1, * ¢ers[center_idx, 0], 1) * dist *= -2 # <<<<<<<<<<<<<< @@ -1524,7 +1792,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_dist = (__pyx_v_dist * -2.0); - /* "sklearn/cluster/_k_means.pyx":68 + /* "sklearn/cluster/_k_means.pyx":71 * ¢ers[center_idx, 0], 1) * dist *= -2 * dist += center_squared_norms[center_idx] # <<<<<<<<<<<<<< @@ -1532,9 +1800,9 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ * if min_dist == -1 or dist < min_dist: */ __pyx_t_21 = __pyx_v_center_idx; - __pyx_v_dist = (__pyx_v_dist + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_center_squared_norms.buf, __pyx_t_21, __pyx_bstride_0_center_squared_norms))); + __pyx_v_dist = (__pyx_v_dist + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_center_squared_norms.diminfo[0].strides))); - /* "sklearn/cluster/_k_means.pyx":69 + /* "sklearn/cluster/_k_means.pyx":72 * dist *= -2 * dist += center_squared_norms[center_idx] * dist += x_squared_norms[sample_idx] # <<<<<<<<<<<<<< @@ -1542,25 +1810,27 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ * min_dist = dist */ __pyx_t_22 = __pyx_v_sample_idx; - __pyx_v_dist = (__pyx_v_dist + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_x_squared_norms.buf, __pyx_t_22, __pyx_bstride_0_x_squared_norms))); + __pyx_v_dist = (__pyx_v_dist + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_x_squared_norms.diminfo[0].strides))); - /* "sklearn/cluster/_k_means.pyx":70 + /* "sklearn/cluster/_k_means.pyx":73 * dist += center_squared_norms[center_idx] * dist += x_squared_norms[sample_idx] * if min_dist == -1 or dist < min_dist: # <<<<<<<<<<<<<< * min_dist = dist * labels[sample_idx] = center_idx */ - __pyx_t_7 = (__pyx_v_min_dist == -1.0); - if (!__pyx_t_7) { - __pyx_t_23 = (__pyx_v_dist < __pyx_v_min_dist); - __pyx_t_24 = __pyx_t_23; + __pyx_t_23 = ((__pyx_v_min_dist == -1.0) != 0); + if (!__pyx_t_23) { } else { - __pyx_t_24 = __pyx_t_7; + __pyx_t_7 = __pyx_t_23; + goto __pyx_L11_bool_binop_done; } - if (__pyx_t_24) { + __pyx_t_23 = ((__pyx_v_dist < __pyx_v_min_dist) != 0); + __pyx_t_7 = __pyx_t_23; + __pyx_L11_bool_binop_done:; + if (__pyx_t_7) { - /* "sklearn/cluster/_k_means.pyx":71 + /* "sklearn/cluster/_k_means.pyx":74 * dist += x_squared_norms[sample_idx] * if min_dist == -1 or dist < min_dist: * min_dist = dist # <<<<<<<<<<<<<< @@ -1569,30 +1839,31 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_min_dist = __pyx_v_dist; - /* "sklearn/cluster/_k_means.pyx":72 + /* "sklearn/cluster/_k_means.pyx":75 * if min_dist == -1 or dist < min_dist: * min_dist = dist * labels[sample_idx] = center_idx # <<<<<<<<<<<<<< * * if store_distances: */ - __pyx_t_25 = __pyx_v_sample_idx; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_bstruct_labels.buf, __pyx_t_25, __pyx_bstride_0_labels) = __pyx_v_center_idx; + __pyx_t_24 = __pyx_v_sample_idx; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_pybuffernd_labels.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_labels.diminfo[0].strides) = __pyx_v_center_idx; goto __pyx_L10; } __pyx_L10:; } - /* "sklearn/cluster/_k_means.pyx":74 + /* "sklearn/cluster/_k_means.pyx":77 * labels[sample_idx] = center_idx * * if store_distances: # <<<<<<<<<<<<<< * distances[sample_idx] = min_dist * inertia += min_dist */ - if (__pyx_v_store_distances) { + __pyx_t_7 = (__pyx_v_store_distances != 0); + if (__pyx_t_7) { - /* "sklearn/cluster/_k_means.pyx":75 + /* "sklearn/cluster/_k_means.pyx":78 * * if store_distances: * distances[sample_idx] = min_dist # <<<<<<<<<<<<<< @@ -1600,12 +1871,12 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ * */ __pyx_t_15 = __pyx_v_sample_idx; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_distances.buf, __pyx_t_15, __pyx_bstride_0_distances) = __pyx_v_min_dist; - goto __pyx_L11; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_distances.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_distances.diminfo[0].strides) = __pyx_v_min_dist; + goto __pyx_L13; } - __pyx_L11:; + __pyx_L13:; - /* "sklearn/cluster/_k_means.pyx":76 + /* "sklearn/cluster/_k_means.pyx":79 * if store_distances: * distances[sample_idx] = min_dist * inertia += min_dist # <<<<<<<<<<<<<< @@ -1615,7 +1886,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ __pyx_v_inertia = (__pyx_v_inertia + __pyx_v_min_dist); } - /* "sklearn/cluster/_k_means.pyx":78 + /* "sklearn/cluster/_k_means.pyx":81 * inertia += min_dist * * return inertia # <<<<<<<<<<<<<< @@ -1625,8 +1896,15 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ __pyx_r = __pyx_v_inertia; goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; + /* "sklearn/cluster/_k_means.pyx":33 + * @cython.wraparound(False) + * @cython.cdivision(True) + * cpdef DOUBLE _assign_labels_array(np.ndarray[DOUBLE, ndim=2] X, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=1] x_squared_norms, + * np.ndarray[DOUBLE, ndim=2] centers, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); @@ -1635,23 +1913,23 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_center_squared_norms); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_labels); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_centers); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_x_squared_norms); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_WriteUnraisable("sklearn.cluster._k_means._assign_labels_array", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_WriteUnraisable("sklearn.cluster._k_means._assign_labels_array", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); __pyx_r = 0; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_center_squared_norms); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_labels); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_centers); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_x_squared_norms); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_center_squared_norms); __Pyx_TraceReturn(Py_None); @@ -1659,57 +1937,28 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ return __pyx_r; } -/* "sklearn/cluster/_k_means.pyx":30 - * @cython.wraparound(False) - * @cython.cdivision(True) - * cpdef DOUBLE _assign_labels_array(np.ndarray[DOUBLE, ndim=2] X, # <<<<<<<<<<<<<< - * np.ndarray[DOUBLE, ndim=1] x_squared_norms, - * np.ndarray[DOUBLE, ndim=2] centers, - */ - -static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means__assign_labels_array(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_7cluster_8_k_means__assign_labels_array[] = "Compute label assignement and inertia for a dense array\n\n Return the inertia (sum of squared distances to the centers).\n "; -static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means__assign_labels_array(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_1_assign_labels_array(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7cluster_8_k_means__assign_labels_array[] = "Compute label assignment and inertia for a dense array\n\n Return the inertia (sum of squared distances to the centers).\n "; +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_1_assign_labels_array(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_X = 0; PyArrayObject *__pyx_v_x_squared_norms = 0; PyArrayObject *__pyx_v_centers = 0; PyArrayObject *__pyx_v_labels = 0; PyArrayObject *__pyx_v_distances = 0; - Py_buffer __pyx_bstruct_X; - Py_ssize_t __pyx_bstride_0_X = 0; - Py_ssize_t __pyx_bstride_1_X = 0; - Py_ssize_t __pyx_bshape_0_X = 0; - Py_ssize_t __pyx_bshape_1_X = 0; - Py_buffer __pyx_bstruct_labels; - Py_ssize_t __pyx_bstride_0_labels = 0; - Py_ssize_t __pyx_bshape_0_labels = 0; - Py_buffer __pyx_bstruct_distances; - Py_ssize_t __pyx_bstride_0_distances = 0; - Py_ssize_t __pyx_bshape_0_distances = 0; - Py_buffer __pyx_bstruct_x_squared_norms; - Py_ssize_t __pyx_bstride_0_x_squared_norms = 0; - Py_ssize_t __pyx_bshape_0_x_squared_norms = 0; - Py_buffer __pyx_bstruct_centers; - Py_ssize_t __pyx_bstride_0_centers = 0; - Py_ssize_t __pyx_bstride_1_centers = 0; - Py_ssize_t __pyx_bshape_0_centers = 0; - Py_ssize_t __pyx_bshape_1_centers = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__x_squared_norms,&__pyx_n_s__centers,&__pyx_n_s__labels,&__pyx_n_s__distances,0}; - __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("_assign_labels_array"); - __Pyx_TraceCall("_assign_labels_array", __pyx_f[0], 30); - __pyx_self = __pyx_self; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_assign_labels_array (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_x_squared_norms,&__pyx_n_s_centers,&__pyx_n_s_labels,&__pyx_n_s_distances,0}; PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); @@ -1719,38 +1968,33 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means__assign_labels_array(PyObj default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__x_squared_norms); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x_squared_norms)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_assign_labels_array", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_assign_labels_array", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__centers); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_centers)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_assign_labels_array", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_assign_labels_array", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__labels); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_labels)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_assign_labels_array", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_assign_labels_array", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__distances); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_distances)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_assign_labels_array", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_assign_labels_array", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "_assign_labels_array") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_assign_labels_array") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { goto __pyx_L5_argtuple_error; @@ -1769,80 +2013,120 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means__assign_labels_array(PyObj } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_assign_labels_array", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_assign_labels_array", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.cluster._k_means._assign_labels_array", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_X.buf = NULL; - __pyx_bstruct_x_squared_norms.buf = NULL; - __pyx_bstruct_centers.buf = NULL; - __pyx_bstruct_labels.buf = NULL; - __pyx_bstruct_distances.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x_squared_norms), __pyx_ptype_5numpy_ndarray, 1, "x_squared_norms", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_centers), __pyx_ptype_5numpy_ndarray, 1, "centers", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_labels), __pyx_ptype_5numpy_ndarray, 1, "labels", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_distances), __pyx_ptype_5numpy_ndarray, 1, "distances", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x_squared_norms), __pyx_ptype_5numpy_ndarray, 1, "x_squared_norms", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_centers), __pyx_ptype_5numpy_ndarray, 1, "centers", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_labels), __pyx_ptype_5numpy_ndarray, 1, "labels", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_distances), __pyx_ptype_5numpy_ndarray, 1, "distances", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_7cluster_8_k_means__assign_labels_array(__pyx_self, __pyx_v_X, __pyx_v_x_squared_norms, __pyx_v_centers, __pyx_v_labels, __pyx_v_distances); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means__assign_labels_array(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_x_squared_norms, PyArrayObject *__pyx_v_centers, PyArrayObject *__pyx_v_labels, PyArrayObject *__pyx_v_distances) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_LocalBuf_ND __pyx_pybuffernd_centers; + __Pyx_Buffer __pyx_pybuffer_centers; + __Pyx_LocalBuf_ND __pyx_pybuffernd_distances; + __Pyx_Buffer __pyx_pybuffer_distances; + __Pyx_LocalBuf_ND __pyx_pybuffernd_labels; + __Pyx_Buffer __pyx_pybuffer_labels; + __Pyx_LocalBuf_ND __pyx_pybuffernd_x_squared_norms; + __Pyx_Buffer __pyx_pybuffer_x_squared_norms; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceDeclarations + __Pyx_RefNannySetupContext("_assign_labels_array", 0); + __Pyx_TraceCall("_assign_labels_array", __pyx_f[0], 33); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + __pyx_pybuffer_x_squared_norms.pybuffer.buf = NULL; + __pyx_pybuffer_x_squared_norms.refcount = 0; + __pyx_pybuffernd_x_squared_norms.data = NULL; + __pyx_pybuffernd_x_squared_norms.rcbuffer = &__pyx_pybuffer_x_squared_norms; + __pyx_pybuffer_centers.pybuffer.buf = NULL; + __pyx_pybuffer_centers.refcount = 0; + __pyx_pybuffernd_centers.data = NULL; + __pyx_pybuffernd_centers.rcbuffer = &__pyx_pybuffer_centers; + __pyx_pybuffer_labels.pybuffer.buf = NULL; + __pyx_pybuffer_labels.refcount = 0; + __pyx_pybuffernd_labels.data = NULL; + __pyx_pybuffernd_labels.rcbuffer = &__pyx_pybuffer_labels; + __pyx_pybuffer_distances.pybuffer.buf = NULL; + __pyx_pybuffer_distances.refcount = 0; + __pyx_pybuffernd_distances.data = NULL; + __pyx_pybuffernd_distances.rcbuffer = &__pyx_pybuffer_distances; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_X = __pyx_bstruct_X.strides[0]; __pyx_bstride_1_X = __pyx_bstruct_X.strides[1]; - __pyx_bshape_0_X = __pyx_bstruct_X.shape[0]; __pyx_bshape_1_X = __pyx_bstruct_X.shape[1]; + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_x_squared_norms, (PyObject*)__pyx_v_x_squared_norms, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer, (PyObject*)__pyx_v_x_squared_norms, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_x_squared_norms = __pyx_bstruct_x_squared_norms.strides[0]; - __pyx_bshape_0_x_squared_norms = __pyx_bstruct_x_squared_norms.shape[0]; + __pyx_pybuffernd_x_squared_norms.diminfo[0].strides = __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x_squared_norms.diminfo[0].shape = __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_centers, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_centers.rcbuffer->pybuffer, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_centers = __pyx_bstruct_centers.strides[0]; __pyx_bstride_1_centers = __pyx_bstruct_centers.strides[1]; - __pyx_bshape_0_centers = __pyx_bstruct_centers.shape[0]; __pyx_bshape_1_centers = __pyx_bstruct_centers.shape[1]; + __pyx_pybuffernd_centers.diminfo[0].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_centers.diminfo[0].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_centers.diminfo[1].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_centers.diminfo[1].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_labels, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_labels = __pyx_bstruct_labels.strides[0]; - __pyx_bshape_0_labels = __pyx_bstruct_labels.shape[0]; + __pyx_pybuffernd_labels.diminfo[0].strides = __pyx_pybuffernd_labels.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_labels.diminfo[0].shape = __pyx_pybuffernd_labels.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_distances, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_distances.rcbuffer->pybuffer, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_distances = __pyx_bstruct_distances.strides[0]; - __pyx_bshape_0_distances = __pyx_bstruct_distances.shape[0]; + __pyx_pybuffernd_distances.diminfo[0].strides = __pyx_pybuffernd_distances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_distances.diminfo[0].shape = __pyx_pybuffernd_distances.rcbuffer->pybuffer.shape[0]; __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(__pyx_f_7sklearn_7cluster_8_k_means__assign_labels_array(__pyx_v_X, __pyx_v_x_squared_norms, __pyx_v_centers, __pyx_v_labels, __pyx_v_distances, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyFloat_FromDouble(__pyx_f_7sklearn_7cluster_8_k_means__assign_labels_array(__pyx_v_X, __pyx_v_x_squared_norms, __pyx_v_centers, __pyx_v_labels, __pyx_v_distances, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_labels); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_x_squared_norms); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_centers); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.cluster._k_means._assign_labels_array", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_labels); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_x_squared_norms); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_centers); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XGIVEREF(__pyx_r); __Pyx_TraceReturn(__pyx_r); @@ -1850,7 +2134,7 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means__assign_labels_array(PyObj return __pyx_r; } -/* "sklearn/cluster/_k_means.pyx":84 +/* "sklearn/cluster/_k_means.pyx":87 * @cython.wraparound(False) * @cython.cdivision(True) * cpdef DOUBLE _assign_labels_csr(X, np.ndarray[DOUBLE, ndim=1] x_squared_norms, # <<<<<<<<<<<<<< @@ -1858,8 +2142,8 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means__assign_labels_array(PyObj * np.ndarray[INT, ndim=1] labels, */ -static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_1_assign_labels_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_means__assign_labels_csr(PyObject *__pyx_v_X, PyArrayObject *__pyx_v_x_squared_norms, PyArrayObject *__pyx_v_centers, PyArrayObject *__pyx_v_labels, PyArrayObject *__pyx_v_distances, int __pyx_skip_dispatch) { +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_3_assign_labels_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_means__assign_labels_csr(PyObject *__pyx_v_X, PyArrayObject *__pyx_v_x_squared_norms, PyArrayObject *__pyx_v_centers, PyArrayObject *__pyx_v_labels, PyArrayObject *__pyx_v_distances, CYTHON_UNUSED int __pyx_skip_dispatch) { PyArrayObject *__pyx_v_X_data = 0; PyArrayObject *__pyx_v_X_indices = 0; PyArrayObject *__pyx_v_X_indptr = 0; @@ -1874,32 +2158,22 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_v_min_dist; __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_v_dist; PyArrayObject *__pyx_v_center_squared_norms = 0; - Py_buffer __pyx_bstruct_distances; - Py_ssize_t __pyx_bstride_0_distances = 0; - Py_ssize_t __pyx_bshape_0_distances = 0; - Py_buffer __pyx_bstruct_center_squared_norms; - Py_ssize_t __pyx_bstride_0_center_squared_norms = 0; - Py_ssize_t __pyx_bshape_0_center_squared_norms = 0; - Py_buffer __pyx_bstruct_labels; - Py_ssize_t __pyx_bstride_0_labels = 0; - Py_ssize_t __pyx_bshape_0_labels = 0; - Py_buffer __pyx_bstruct_centers; - Py_ssize_t __pyx_bstride_0_centers = 0; - Py_ssize_t __pyx_bstride_1_centers = 0; - Py_ssize_t __pyx_bshape_0_centers = 0; - Py_ssize_t __pyx_bshape_1_centers = 0; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_x_squared_norms; - Py_ssize_t __pyx_bstride_0_x_squared_norms = 0; - Py_ssize_t __pyx_bshape_0_x_squared_norms = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_data; + __Pyx_Buffer __pyx_pybuffer_X_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indices; + __Pyx_Buffer __pyx_pybuffer_X_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indptr; + __Pyx_Buffer __pyx_pybuffer_X_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_center_squared_norms; + __Pyx_Buffer __pyx_pybuffer_center_squared_norms; + __Pyx_LocalBuf_ND __pyx_pybuffernd_centers; + __Pyx_Buffer __pyx_pybuffer_centers; + __Pyx_LocalBuf_ND __pyx_pybuffernd_distances; + __Pyx_Buffer __pyx_pybuffer_distances; + __Pyx_LocalBuf_ND __pyx_pybuffernd_labels; + __Pyx_Buffer __pyx_pybuffer_labels; + __Pyx_LocalBuf_ND __pyx_pybuffernd_x_squared_norms; + __Pyx_Buffer __pyx_pybuffer_x_squared_norms; __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -1931,121 +2205,137 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ unsigned int __pyx_t_27; unsigned int __pyx_t_28; int __pyx_t_29; - int __pyx_t_30; + unsigned int __pyx_t_30; unsigned int __pyx_t_31; - unsigned int __pyx_t_32; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("_assign_labels_csr"); - __Pyx_TraceCall("_assign_labels_csr", __pyx_f[0], 84); - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; - __pyx_bstruct_center_squared_norms.buf = NULL; - __pyx_bstruct_x_squared_norms.buf = NULL; - __pyx_bstruct_centers.buf = NULL; - __pyx_bstruct_labels.buf = NULL; - __pyx_bstruct_distances.buf = NULL; + __Pyx_RefNannySetupContext("_assign_labels_csr", 0); + __Pyx_TraceCall("_assign_labels_csr", __pyx_f[0], 87); + __pyx_pybuffer_X_data.pybuffer.buf = NULL; + __pyx_pybuffer_X_data.refcount = 0; + __pyx_pybuffernd_X_data.data = NULL; + __pyx_pybuffernd_X_data.rcbuffer = &__pyx_pybuffer_X_data; + __pyx_pybuffer_X_indices.pybuffer.buf = NULL; + __pyx_pybuffer_X_indices.refcount = 0; + __pyx_pybuffernd_X_indices.data = NULL; + __pyx_pybuffernd_X_indices.rcbuffer = &__pyx_pybuffer_X_indices; + __pyx_pybuffer_X_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_X_indptr.refcount = 0; + __pyx_pybuffernd_X_indptr.data = NULL; + __pyx_pybuffernd_X_indptr.rcbuffer = &__pyx_pybuffer_X_indptr; + __pyx_pybuffer_center_squared_norms.pybuffer.buf = NULL; + __pyx_pybuffer_center_squared_norms.refcount = 0; + __pyx_pybuffernd_center_squared_norms.data = NULL; + __pyx_pybuffernd_center_squared_norms.rcbuffer = &__pyx_pybuffer_center_squared_norms; + __pyx_pybuffer_x_squared_norms.pybuffer.buf = NULL; + __pyx_pybuffer_x_squared_norms.refcount = 0; + __pyx_pybuffernd_x_squared_norms.data = NULL; + __pyx_pybuffernd_x_squared_norms.rcbuffer = &__pyx_pybuffer_x_squared_norms; + __pyx_pybuffer_centers.pybuffer.buf = NULL; + __pyx_pybuffer_centers.refcount = 0; + __pyx_pybuffernd_centers.data = NULL; + __pyx_pybuffernd_centers.rcbuffer = &__pyx_pybuffer_centers; + __pyx_pybuffer_labels.pybuffer.buf = NULL; + __pyx_pybuffer_labels.refcount = 0; + __pyx_pybuffernd_labels.data = NULL; + __pyx_pybuffernd_labels.rcbuffer = &__pyx_pybuffer_labels; + __pyx_pybuffer_distances.pybuffer.buf = NULL; + __pyx_pybuffer_distances.refcount = 0; + __pyx_pybuffernd_distances.data = NULL; + __pyx_pybuffernd_distances.rcbuffer = &__pyx_pybuffer_distances; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_x_squared_norms, (PyObject*)__pyx_v_x_squared_norms, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer, (PyObject*)__pyx_v_x_squared_norms, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_x_squared_norms = __pyx_bstruct_x_squared_norms.strides[0]; - __pyx_bshape_0_x_squared_norms = __pyx_bstruct_x_squared_norms.shape[0]; + __pyx_pybuffernd_x_squared_norms.diminfo[0].strides = __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x_squared_norms.diminfo[0].shape = __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_centers, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_centers.rcbuffer->pybuffer, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_centers = __pyx_bstruct_centers.strides[0]; __pyx_bstride_1_centers = __pyx_bstruct_centers.strides[1]; - __pyx_bshape_0_centers = __pyx_bstruct_centers.shape[0]; __pyx_bshape_1_centers = __pyx_bstruct_centers.shape[1]; + __pyx_pybuffernd_centers.diminfo[0].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_centers.diminfo[0].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_centers.diminfo[1].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_centers.diminfo[1].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_labels, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_labels = __pyx_bstruct_labels.strides[0]; - __pyx_bshape_0_labels = __pyx_bstruct_labels.shape[0]; + __pyx_pybuffernd_labels.diminfo[0].strides = __pyx_pybuffernd_labels.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_labels.diminfo[0].shape = __pyx_pybuffernd_labels.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_distances, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_distances.rcbuffer->pybuffer, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_distances = __pyx_bstruct_distances.strides[0]; - __pyx_bshape_0_distances = __pyx_bstruct_distances.shape[0]; + __pyx_pybuffernd_distances.diminfo[0].strides = __pyx_pybuffernd_distances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_distances.diminfo[0].shape = __pyx_pybuffernd_distances.rcbuffer->pybuffer.shape[0]; - /* "sklearn/cluster/_k_means.pyx":93 + /* "sklearn/cluster/_k_means.pyx":96 * """ * cdef: * np.ndarray[DOUBLE, ndim=1] X_data = X.data # <<<<<<<<<<<<<< * np.ndarray[INT, ndim=1] X_indices = X.indices * np.ndarray[INT, ndim=1] X_indptr = X.indptr */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_2 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_t_2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_data.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer, (PyObject*)__pyx_t_2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_data.diminfo[0].strides = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_data.diminfo[0].shape = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.shape[0]; } } __pyx_t_2 = 0; __pyx_v_X_data = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/cluster/_k_means.pyx":94 + /* "sklearn/cluster/_k_means.pyx":97 * cdef: * np.ndarray[DOUBLE, ndim=1] X_data = X.data * np.ndarray[INT, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< * np.ndarray[INT, ndim=1] X_indptr = X.indptr * unsigned int n_clusters = centers.shape[0] */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_3 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_t_3, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indices.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer, (PyObject*)__pyx_t_3, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indices.diminfo[0].strides = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indices.diminfo[0].shape = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.shape[0]; } } __pyx_t_3 = 0; __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/cluster/_k_means.pyx":95 + /* "sklearn/cluster/_k_means.pyx":98 * np.ndarray[DOUBLE, ndim=1] X_data = X.data * np.ndarray[INT, ndim=1] X_indices = X.indices * np.ndarray[INT, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< * unsigned int n_clusters = centers.shape[0] * unsigned int n_features = centers.shape[1] */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indptr.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indptr.diminfo[0].strides = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indptr.diminfo[0].shape = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.shape[0]; } } __pyx_t_4 = 0; __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/cluster/_k_means.pyx":96 + /* "sklearn/cluster/_k_means.pyx":99 * np.ndarray[INT, ndim=1] X_indices = X.indices * np.ndarray[INT, ndim=1] X_indptr = X.indptr * unsigned int n_clusters = centers.shape[0] # <<<<<<<<<<<<<< @@ -2054,7 +2344,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_n_clusters = (__pyx_v_centers->dimensions[0]); - /* "sklearn/cluster/_k_means.pyx":97 + /* "sklearn/cluster/_k_means.pyx":100 * np.ndarray[INT, ndim=1] X_indptr = X.indptr * unsigned int n_clusters = centers.shape[0] * unsigned int n_features = centers.shape[1] # <<<<<<<<<<<<<< @@ -2063,23 +2353,23 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_n_features = (__pyx_v_centers->dimensions[1]); - /* "sklearn/cluster/_k_means.pyx":98 + /* "sklearn/cluster/_k_means.pyx":101 * unsigned int n_clusters = centers.shape[0] * unsigned int n_features = centers.shape[1] * unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< * unsigned int store_distances = 0 * unsigned int sample_idx, center_idx, feature_idx */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_5); if (unlikely((__pyx_t_6 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyInt_As_unsigned_int(__pyx_t_5); if (unlikely((__pyx_t_6 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_n_samples = __pyx_t_6; - /* "sklearn/cluster/_k_means.pyx":99 + /* "sklearn/cluster/_k_means.pyx":102 * unsigned int n_features = centers.shape[1] * unsigned int n_samples = X.shape[0] * unsigned int store_distances = 0 # <<<<<<<<<<<<<< @@ -2088,7 +2378,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_store_distances = 0; - /* "sklearn/cluster/_k_means.pyx":102 + /* "sklearn/cluster/_k_means.pyx":105 * unsigned int sample_idx, center_idx, feature_idx * unsigned int k * DOUBLE inertia = 0.0 # <<<<<<<<<<<<<< @@ -2097,89 +2387,96 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_inertia = 0.0; - /* "sklearn/cluster/_k_means.pyx":105 + /* "sklearn/cluster/_k_means.pyx":108 * DOUBLE min_dist * DOUBLE dist * np.ndarray[DOUBLE, ndim=1] center_squared_norms = np.zeros( # <<<<<<<<<<<<<< * n_clusters, dtype=np.float64) * */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - /* "sklearn/cluster/_k_means.pyx":106 + /* "sklearn/cluster/_k_means.pyx":109 * DOUBLE dist * np.ndarray[DOUBLE, ndim=1] center_squared_norms = np.zeros( * n_clusters, dtype=np.float64) # <<<<<<<<<<<<<< * * if n_samples == distances.shape[0]: */ - __pyx_t_5 = PyLong_FromUnsignedLong(__pyx_v_n_clusters); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_clusters); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - /* "sklearn/cluster/_k_means.pyx":105 + /* "sklearn/cluster/_k_means.pyx":108 * DOUBLE min_dist * DOUBLE dist * np.ndarray[DOUBLE, ndim=1] center_squared_norms = np.zeros( # <<<<<<<<<<<<<< * n_clusters, dtype=np.float64) * */ - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); - /* "sklearn/cluster/_k_means.pyx":106 + /* "sklearn/cluster/_k_means.pyx":109 * DOUBLE dist * np.ndarray[DOUBLE, ndim=1] center_squared_norms = np.zeros( * n_clusters, dtype=np.float64) # <<<<<<<<<<<<<< * * if n_samples == distances.shape[0]: */ - __pyx_t_8 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); - __pyx_t_9 = PyObject_GetAttr(__pyx_t_8, __pyx_n_s__float64); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_float64); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/cluster/_k_means.pyx":108 + * DOUBLE min_dist + * DOUBLE dist + * np.ndarray[DOUBLE, ndim=1] center_squared_norms = np.zeros( # <<<<<<<<<<<<<< + * n_clusters, dtype=np.float64) + * + */ + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_7, __pyx_t_5); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_9) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_9, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_9) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_9, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_10 = ((PyArrayObject *)__pyx_t_9); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_center_squared_norms, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_center_squared_norms = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_center_squared_norms.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_center_squared_norms = __pyx_bstruct_center_squared_norms.strides[0]; - __pyx_bshape_0_center_squared_norms = __pyx_bstruct_center_squared_norms.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_center_squared_norms = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_center_squared_norms.diminfo[0].strides = __pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_center_squared_norms.diminfo[0].shape = __pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer.shape[0]; } } __pyx_t_10 = 0; __pyx_v_center_squared_norms = ((PyArrayObject *)__pyx_t_9); __pyx_t_9 = 0; - /* "sklearn/cluster/_k_means.pyx":108 + /* "sklearn/cluster/_k_means.pyx":111 * n_clusters, dtype=np.float64) * * if n_samples == distances.shape[0]: # <<<<<<<<<<<<<< * store_distances = 1 * */ - __pyx_t_11 = (__pyx_v_n_samples == (__pyx_v_distances->dimensions[0])); + __pyx_t_11 = ((__pyx_v_n_samples == (__pyx_v_distances->dimensions[0])) != 0); if (__pyx_t_11) { - /* "sklearn/cluster/_k_means.pyx":109 + /* "sklearn/cluster/_k_means.pyx":112 * * if n_samples == distances.shape[0]: * store_distances = 1 # <<<<<<<<<<<<<< @@ -2191,7 +2488,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ } __pyx_L3:; - /* "sklearn/cluster/_k_means.pyx":111 + /* "sklearn/cluster/_k_means.pyx":114 * store_distances = 1 * * for center_idx in range(n_clusters): # <<<<<<<<<<<<<< @@ -2202,7 +2499,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_6; __pyx_t_12+=1) { __pyx_v_center_idx = __pyx_t_12; - /* "sklearn/cluster/_k_means.pyx":113 + /* "sklearn/cluster/_k_means.pyx":116 * for center_idx in range(n_clusters): * center_squared_norms[center_idx] = ddot( * n_features, ¢ers[center_idx, 0], 1, ¢ers[center_idx, 0], 1) # <<<<<<<<<<<<<< @@ -2214,7 +2511,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ __pyx_t_15 = __pyx_v_center_idx; __pyx_t_16 = 0; - /* "sklearn/cluster/_k_means.pyx":112 + /* "sklearn/cluster/_k_means.pyx":115 * * for center_idx in range(n_clusters): * center_squared_norms[center_idx] = ddot( # <<<<<<<<<<<<<< @@ -2222,10 +2519,10 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ * */ __pyx_t_17 = __pyx_v_center_idx; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_center_squared_norms.buf, __pyx_t_17, __pyx_bstride_0_center_squared_norms) = cblas_ddot(__pyx_v_n_features, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_centers.buf, __pyx_t_13, __pyx_bstride_0_centers, __pyx_t_14, __pyx_bstride_1_centers))), 1, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_centers.buf, __pyx_t_15, __pyx_bstride_0_centers, __pyx_t_16, __pyx_bstride_1_centers))), 1); + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_center_squared_norms.diminfo[0].strides) = cblas_ddot(__pyx_v_n_features, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_centers.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_centers.diminfo[0].strides, __pyx_t_14, __pyx_pybuffernd_centers.diminfo[1].strides))), 1, (&(*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_centers.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_centers.diminfo[0].strides, __pyx_t_16, __pyx_pybuffernd_centers.diminfo[1].strides))), 1); } - /* "sklearn/cluster/_k_means.pyx":115 + /* "sklearn/cluster/_k_means.pyx":118 * n_features, ¢ers[center_idx, 0], 1, ¢ers[center_idx, 0], 1) * * for sample_idx in range(n_samples): # <<<<<<<<<<<<<< @@ -2236,7 +2533,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_6; __pyx_t_12+=1) { __pyx_v_sample_idx = __pyx_t_12; - /* "sklearn/cluster/_k_means.pyx":116 + /* "sklearn/cluster/_k_means.pyx":119 * * for sample_idx in range(n_samples): * min_dist = -1 # <<<<<<<<<<<<<< @@ -2245,7 +2542,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_min_dist = -1.0; - /* "sklearn/cluster/_k_means.pyx":117 + /* "sklearn/cluster/_k_means.pyx":120 * for sample_idx in range(n_samples): * min_dist = -1 * for center_idx in range(n_clusters): # <<<<<<<<<<<<<< @@ -2256,7 +2553,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ for (__pyx_t_19 = 0; __pyx_t_19 < __pyx_t_18; __pyx_t_19+=1) { __pyx_v_center_idx = __pyx_t_19; - /* "sklearn/cluster/_k_means.pyx":118 + /* "sklearn/cluster/_k_means.pyx":121 * min_dist = -1 * for center_idx in range(n_clusters): * dist = 0.0 # <<<<<<<<<<<<<< @@ -2265,7 +2562,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_dist = 0.0; - /* "sklearn/cluster/_k_means.pyx":121 + /* "sklearn/cluster/_k_means.pyx":124 * # hardcoded: minimize euclidean distance to cluster center: * # ||a - b||^2 = ||a||^2 + ||b||^2 -2 * for k in range(X_indptr[sample_idx], X_indptr[sample_idx + 1]): # <<<<<<<<<<<<<< @@ -2273,12 +2570,12 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ * dist *= -2 */ __pyx_t_20 = (__pyx_v_sample_idx + 1); - __pyx_t_21 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_bstruct_X_indptr.buf, __pyx_t_20, __pyx_bstride_0_X_indptr)); + __pyx_t_21 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); __pyx_t_22 = __pyx_v_sample_idx; - for (__pyx_t_23 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_bstruct_X_indptr.buf, __pyx_t_22, __pyx_bstride_0_X_indptr)); __pyx_t_23 < __pyx_t_21; __pyx_t_23+=1) { + for (__pyx_t_23 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); __pyx_t_23 < __pyx_t_21; __pyx_t_23+=1) { __pyx_v_k = __pyx_t_23; - /* "sklearn/cluster/_k_means.pyx":122 + /* "sklearn/cluster/_k_means.pyx":125 * # ||a - b||^2 = ||a||^2 + ||b||^2 -2 * for k in range(X_indptr[sample_idx], X_indptr[sample_idx + 1]): * dist += centers[center_idx, X_indices[k]] * X_data[k] # <<<<<<<<<<<<<< @@ -2287,12 +2584,12 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_t_24 = __pyx_v_k; __pyx_t_25 = __pyx_v_center_idx; - __pyx_t_26 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_bstruct_X_indices.buf, __pyx_t_24, __pyx_bstride_0_X_indices)); + __pyx_t_26 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_X_indices.diminfo[0].strides)); __pyx_t_27 = __pyx_v_k; - __pyx_v_dist = (__pyx_v_dist + ((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_centers.buf, __pyx_t_25, __pyx_bstride_0_centers, __pyx_t_26, __pyx_bstride_1_centers)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_27, __pyx_bstride_0_X_data)))); + __pyx_v_dist = (__pyx_v_dist + ((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_centers.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_centers.diminfo[0].strides, __pyx_t_26, __pyx_pybuffernd_centers.diminfo[1].strides)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_X_data.diminfo[0].strides)))); } - /* "sklearn/cluster/_k_means.pyx":123 + /* "sklearn/cluster/_k_means.pyx":126 * for k in range(X_indptr[sample_idx], X_indptr[sample_idx + 1]): * dist += centers[center_idx, X_indices[k]] * X_data[k] * dist *= -2 # <<<<<<<<<<<<<< @@ -2301,7 +2598,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_dist = (__pyx_v_dist * -2.0); - /* "sklearn/cluster/_k_means.pyx":124 + /* "sklearn/cluster/_k_means.pyx":127 * dist += centers[center_idx, X_indices[k]] * X_data[k] * dist *= -2 * dist += center_squared_norms[center_idx] # <<<<<<<<<<<<<< @@ -2309,9 +2606,9 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ * if min_dist == -1 or dist < min_dist: */ __pyx_t_23 = __pyx_v_center_idx; - __pyx_v_dist = (__pyx_v_dist + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_center_squared_norms.buf, __pyx_t_23, __pyx_bstride_0_center_squared_norms))); + __pyx_v_dist = (__pyx_v_dist + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_center_squared_norms.diminfo[0].strides))); - /* "sklearn/cluster/_k_means.pyx":125 + /* "sklearn/cluster/_k_means.pyx":128 * dist *= -2 * dist += center_squared_norms[center_idx] * dist += x_squared_norms[sample_idx] # <<<<<<<<<<<<<< @@ -2319,25 +2616,27 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ * min_dist = dist */ __pyx_t_28 = __pyx_v_sample_idx; - __pyx_v_dist = (__pyx_v_dist + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_x_squared_norms.buf, __pyx_t_28, __pyx_bstride_0_x_squared_norms))); + __pyx_v_dist = (__pyx_v_dist + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.buf, __pyx_t_28, __pyx_pybuffernd_x_squared_norms.diminfo[0].strides))); - /* "sklearn/cluster/_k_means.pyx":126 + /* "sklearn/cluster/_k_means.pyx":129 * dist += center_squared_norms[center_idx] * dist += x_squared_norms[sample_idx] * if min_dist == -1 or dist < min_dist: # <<<<<<<<<<<<<< * min_dist = dist * labels[sample_idx] = center_idx */ - __pyx_t_11 = (__pyx_v_min_dist == -1.0); - if (!__pyx_t_11) { - __pyx_t_29 = (__pyx_v_dist < __pyx_v_min_dist); - __pyx_t_30 = __pyx_t_29; + __pyx_t_29 = ((__pyx_v_min_dist == -1.0) != 0); + if (!__pyx_t_29) { } else { - __pyx_t_30 = __pyx_t_11; + __pyx_t_11 = __pyx_t_29; + goto __pyx_L13_bool_binop_done; } - if (__pyx_t_30) { + __pyx_t_29 = ((__pyx_v_dist < __pyx_v_min_dist) != 0); + __pyx_t_11 = __pyx_t_29; + __pyx_L13_bool_binop_done:; + if (__pyx_t_11) { - /* "sklearn/cluster/_k_means.pyx":127 + /* "sklearn/cluster/_k_means.pyx":130 * dist += x_squared_norms[sample_idx] * if min_dist == -1 or dist < min_dist: * min_dist = dist # <<<<<<<<<<<<<< @@ -2346,43 +2645,44 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ */ __pyx_v_min_dist = __pyx_v_dist; - /* "sklearn/cluster/_k_means.pyx":128 + /* "sklearn/cluster/_k_means.pyx":131 * if min_dist == -1 or dist < min_dist: * min_dist = dist * labels[sample_idx] = center_idx # <<<<<<<<<<<<<< * if store_distances: * distances[sample_idx] = dist */ - __pyx_t_31 = __pyx_v_sample_idx; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_bstruct_labels.buf, __pyx_t_31, __pyx_bstride_0_labels) = __pyx_v_center_idx; + __pyx_t_30 = __pyx_v_sample_idx; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_pybuffernd_labels.rcbuffer->pybuffer.buf, __pyx_t_30, __pyx_pybuffernd_labels.diminfo[0].strides) = __pyx_v_center_idx; - /* "sklearn/cluster/_k_means.pyx":129 + /* "sklearn/cluster/_k_means.pyx":132 * min_dist = dist * labels[sample_idx] = center_idx * if store_distances: # <<<<<<<<<<<<<< * distances[sample_idx] = dist * inertia += min_dist */ - if (__pyx_v_store_distances) { + __pyx_t_11 = (__pyx_v_store_distances != 0); + if (__pyx_t_11) { - /* "sklearn/cluster/_k_means.pyx":130 + /* "sklearn/cluster/_k_means.pyx":133 * labels[sample_idx] = center_idx * if store_distances: * distances[sample_idx] = dist # <<<<<<<<<<<<<< * inertia += min_dist * */ - __pyx_t_32 = __pyx_v_sample_idx; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_distances.buf, __pyx_t_32, __pyx_bstride_0_distances) = __pyx_v_dist; - goto __pyx_L13; + __pyx_t_31 = __pyx_v_sample_idx; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_distances.rcbuffer->pybuffer.buf, __pyx_t_31, __pyx_pybuffernd_distances.diminfo[0].strides) = __pyx_v_dist; + goto __pyx_L15; } - __pyx_L13:; + __pyx_L15:; goto __pyx_L12; } __pyx_L12:; } - /* "sklearn/cluster/_k_means.pyx":131 + /* "sklearn/cluster/_k_means.pyx":134 * if store_distances: * distances[sample_idx] = dist * inertia += min_dist # <<<<<<<<<<<<<< @@ -2392,7 +2692,7 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ __pyx_v_inertia = (__pyx_v_inertia + __pyx_v_min_dist); } - /* "sklearn/cluster/_k_means.pyx":133 + /* "sklearn/cluster/_k_means.pyx":136 * inertia += min_dist * * return inertia # <<<<<<<<<<<<<< @@ -2402,8 +2702,15 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ __pyx_r = __pyx_v_inertia; goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; + /* "sklearn/cluster/_k_means.pyx":87 + * @cython.wraparound(False) + * @cython.cdivision(True) + * cpdef DOUBLE _assign_labels_csr(X, np.ndarray[DOUBLE, ndim=1] x_squared_norms, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=2] centers, + * np.ndarray[INT, ndim=1] labels, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_5); @@ -2412,27 +2719,27 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ __Pyx_XDECREF(__pyx_t_9); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_center_squared_norms); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_labels); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_centers); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_x_squared_norms); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_WriteUnraisable("sklearn.cluster._k_means._assign_labels_csr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_WriteUnraisable("sklearn.cluster._k_means._assign_labels_csr", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); __pyx_r = 0; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_center_squared_norms); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_labels); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_centers); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_x_squared_norms); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_center_squared_norms.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_X_data); __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); @@ -2443,52 +2750,28 @@ static __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_f_7sklearn_7cluster_8_k_ return __pyx_r; } -/* "sklearn/cluster/_k_means.pyx":84 - * @cython.wraparound(False) - * @cython.cdivision(True) - * cpdef DOUBLE _assign_labels_csr(X, np.ndarray[DOUBLE, ndim=1] x_squared_norms, # <<<<<<<<<<<<<< - * np.ndarray[DOUBLE, ndim=2] centers, - * np.ndarray[INT, ndim=1] labels, - */ - -static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_1_assign_labels_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_7cluster_8_k_means_1_assign_labels_csr[] = "Compute label assignement and inertia for a CSR input\n\n Return the inertia (sum of squared distances to the centers).\n "; -static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_1_assign_labels_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_3_assign_labels_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7cluster_8_k_means_2_assign_labels_csr[] = "Compute label assignment and inertia for a CSR input\n\n Return the inertia (sum of squared distances to the centers).\n "; +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_3_assign_labels_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_X = 0; PyArrayObject *__pyx_v_x_squared_norms = 0; PyArrayObject *__pyx_v_centers = 0; PyArrayObject *__pyx_v_labels = 0; PyArrayObject *__pyx_v_distances = 0; - Py_buffer __pyx_bstruct_labels; - Py_ssize_t __pyx_bstride_0_labels = 0; - Py_ssize_t __pyx_bshape_0_labels = 0; - Py_buffer __pyx_bstruct_distances; - Py_ssize_t __pyx_bstride_0_distances = 0; - Py_ssize_t __pyx_bshape_0_distances = 0; - Py_buffer __pyx_bstruct_x_squared_norms; - Py_ssize_t __pyx_bstride_0_x_squared_norms = 0; - Py_ssize_t __pyx_bshape_0_x_squared_norms = 0; - Py_buffer __pyx_bstruct_centers; - Py_ssize_t __pyx_bstride_0_centers = 0; - Py_ssize_t __pyx_bstride_1_centers = 0; - Py_ssize_t __pyx_bshape_0_centers = 0; - Py_ssize_t __pyx_bshape_1_centers = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__x_squared_norms,&__pyx_n_s__centers,&__pyx_n_s__labels,&__pyx_n_s__distances,0}; - __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("_assign_labels_csr"); - __Pyx_TraceCall("_assign_labels_csr", __pyx_f[0], 84); - __pyx_self = __pyx_self; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_assign_labels_csr (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_x_squared_norms,&__pyx_n_s_centers,&__pyx_n_s_labels,&__pyx_n_s_distances,0}; PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); @@ -2498,38 +2781,33 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_1_assign_labels_csr(PyObje default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__x_squared_norms); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x_squared_norms)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_assign_labels_csr", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_assign_labels_csr", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__centers); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_centers)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_assign_labels_csr", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_assign_labels_csr", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__labels); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_labels)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_assign_labels_csr", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_assign_labels_csr", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__distances); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_distances)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_assign_labels_csr", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_assign_labels_csr", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "_assign_labels_csr") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_assign_labels_csr") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { goto __pyx_L5_argtuple_error; @@ -2548,70 +2826,106 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_1_assign_labels_csr(PyObje } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_assign_labels_csr", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_assign_labels_csr", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.cluster._k_means._assign_labels_csr", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_x_squared_norms.buf = NULL; - __pyx_bstruct_centers.buf = NULL; - __pyx_bstruct_labels.buf = NULL; - __pyx_bstruct_distances.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x_squared_norms), __pyx_ptype_5numpy_ndarray, 1, "x_squared_norms", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_centers), __pyx_ptype_5numpy_ndarray, 1, "centers", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_labels), __pyx_ptype_5numpy_ndarray, 1, "labels", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_distances), __pyx_ptype_5numpy_ndarray, 1, "distances", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x_squared_norms), __pyx_ptype_5numpy_ndarray, 1, "x_squared_norms", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_centers), __pyx_ptype_5numpy_ndarray, 1, "centers", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_labels), __pyx_ptype_5numpy_ndarray, 1, "labels", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_distances), __pyx_ptype_5numpy_ndarray, 1, "distances", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_7cluster_8_k_means_2_assign_labels_csr(__pyx_self, __pyx_v_X, __pyx_v_x_squared_norms, __pyx_v_centers, __pyx_v_labels, __pyx_v_distances); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_assign_labels_csr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_x_squared_norms, PyArrayObject *__pyx_v_centers, PyArrayObject *__pyx_v_labels, PyArrayObject *__pyx_v_distances) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_centers; + __Pyx_Buffer __pyx_pybuffer_centers; + __Pyx_LocalBuf_ND __pyx_pybuffernd_distances; + __Pyx_Buffer __pyx_pybuffer_distances; + __Pyx_LocalBuf_ND __pyx_pybuffernd_labels; + __Pyx_Buffer __pyx_pybuffer_labels; + __Pyx_LocalBuf_ND __pyx_pybuffernd_x_squared_norms; + __Pyx_Buffer __pyx_pybuffer_x_squared_norms; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceDeclarations + __Pyx_RefNannySetupContext("_assign_labels_csr", 0); + __Pyx_TraceCall("_assign_labels_csr", __pyx_f[0], 87); + __pyx_pybuffer_x_squared_norms.pybuffer.buf = NULL; + __pyx_pybuffer_x_squared_norms.refcount = 0; + __pyx_pybuffernd_x_squared_norms.data = NULL; + __pyx_pybuffernd_x_squared_norms.rcbuffer = &__pyx_pybuffer_x_squared_norms; + __pyx_pybuffer_centers.pybuffer.buf = NULL; + __pyx_pybuffer_centers.refcount = 0; + __pyx_pybuffernd_centers.data = NULL; + __pyx_pybuffernd_centers.rcbuffer = &__pyx_pybuffer_centers; + __pyx_pybuffer_labels.pybuffer.buf = NULL; + __pyx_pybuffer_labels.refcount = 0; + __pyx_pybuffernd_labels.data = NULL; + __pyx_pybuffernd_labels.rcbuffer = &__pyx_pybuffer_labels; + __pyx_pybuffer_distances.pybuffer.buf = NULL; + __pyx_pybuffer_distances.refcount = 0; + __pyx_pybuffernd_distances.data = NULL; + __pyx_pybuffernd_distances.rcbuffer = &__pyx_pybuffer_distances; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_x_squared_norms, (PyObject*)__pyx_v_x_squared_norms, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer, (PyObject*)__pyx_v_x_squared_norms, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_x_squared_norms = __pyx_bstruct_x_squared_norms.strides[0]; - __pyx_bshape_0_x_squared_norms = __pyx_bstruct_x_squared_norms.shape[0]; + __pyx_pybuffernd_x_squared_norms.diminfo[0].strides = __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x_squared_norms.diminfo[0].shape = __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_centers, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_centers.rcbuffer->pybuffer, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_centers = __pyx_bstruct_centers.strides[0]; __pyx_bstride_1_centers = __pyx_bstruct_centers.strides[1]; - __pyx_bshape_0_centers = __pyx_bstruct_centers.shape[0]; __pyx_bshape_1_centers = __pyx_bstruct_centers.shape[1]; + __pyx_pybuffernd_centers.diminfo[0].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_centers.diminfo[0].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_centers.diminfo[1].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_centers.diminfo[1].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_labels, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_labels = __pyx_bstruct_labels.strides[0]; - __pyx_bshape_0_labels = __pyx_bstruct_labels.shape[0]; + __pyx_pybuffernd_labels.diminfo[0].strides = __pyx_pybuffernd_labels.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_labels.diminfo[0].shape = __pyx_pybuffernd_labels.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_distances, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_distances.rcbuffer->pybuffer, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_distances = __pyx_bstruct_distances.strides[0]; - __pyx_bshape_0_distances = __pyx_bstruct_distances.shape[0]; + __pyx_pybuffernd_distances.diminfo[0].strides = __pyx_pybuffernd_distances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_distances.diminfo[0].shape = __pyx_pybuffernd_distances.rcbuffer->pybuffer.shape[0]; __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(__pyx_f_7sklearn_7cluster_8_k_means__assign_labels_csr(__pyx_v_X, __pyx_v_x_squared_norms, __pyx_v_centers, __pyx_v_labels, __pyx_v_distances, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyFloat_FromDouble(__pyx_f_7sklearn_7cluster_8_k_means__assign_labels_csr(__pyx_v_X, __pyx_v_x_squared_norms, __pyx_v_centers, __pyx_v_labels, __pyx_v_distances, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_labels); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_x_squared_norms); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_centers); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.cluster._k_means._assign_labels_csr", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_labels); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_x_squared_norms); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_centers); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XGIVEREF(__pyx_r); __Pyx_TraceReturn(__pyx_r); @@ -2619,7 +2933,7 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_1_assign_labels_csr(PyObje return __pyx_r; } -/* "sklearn/cluster/_k_means.pyx":139 +/* "sklearn/cluster/_k_means.pyx":142 * @cython.wraparound(False) * @cython.cdivision(True) * def _mini_batch_update_csr(X, np.ndarray[DOUBLE, ndim=1] x_squared_norms, # <<<<<<<<<<<<<< @@ -2627,96 +2941,31 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_1_assign_labels_csr(PyObje * np.ndarray[INT, ndim=1] counts, */ -static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr[] = "Incremental update of the centers for sparse MiniBatchKMeans.\n\n Parameters\n ----------\n\n X: CSR matrix, dtype float64\n The complete (pre allocated) training set as a CSR matrix.\n\n centers: array, shape (n_clusters, n_features)\n The cluster centers\n\n counts: array, shape (n_clusters,)\n The vector in which we keep track of the numbers of elements in a\n cluster\n\n Returns\n -------\n inertia: float\n The inertia of the batch prior to centers update, i.e. the sum\n distances to the closest center for each sample. This is the objective\n function being minimized by the k-means algorithm.\n\n squared_diff: float\n The sum of squared update (squared norm of the centers position\n change). If compute_squared_diff is 0, this computation is skipped and\n 0.0 is returned instead.\n\n Both squared diff and inertia are commonly used to monitor the convergence\n of the algorithm.\n "; -static PyMethodDef __pyx_mdef_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr = {__Pyx_NAMESTR("_mini_batch_update_csr"), (PyCFunction)__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr)}; -static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_5_mini_batch_update_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7cluster_8_k_means_4_mini_batch_update_csr[] = "Incremental update of the centers for sparse MiniBatchKMeans.\n\n Parameters\n ----------\n\n X: CSR matrix, dtype float64\n The complete (pre allocated) training set as a CSR matrix.\n\n centers: array, shape (n_clusters, n_features)\n The cluster centers\n\n counts: array, shape (n_clusters,)\n The vector in which we keep track of the numbers of elements in a\n cluster\n\n Returns\n -------\n inertia: float\n The inertia of the batch prior to centers update, i.e. the sum\n distances to the closest center for each sample. This is the objective\n function being minimized by the k-means algorithm.\n\n squared_diff: float\n The sum of squared update (squared norm of the centers position\n change). If compute_squared_diff is 0, this computation is skipped and\n 0.0 is returned instead.\n\n Both squared diff and inertia are commonly used to monitor the convergence\n of the algorithm.\n "; +static PyMethodDef __pyx_mdef_7sklearn_7cluster_8_k_means_5_mini_batch_update_csr = {"_mini_batch_update_csr", (PyCFunction)__pyx_pw_7sklearn_7cluster_8_k_means_5_mini_batch_update_csr, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_7cluster_8_k_means_4_mini_batch_update_csr}; +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_5_mini_batch_update_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_X = 0; - PyArrayObject *__pyx_v_x_squared_norms = 0; + CYTHON_UNUSED PyArrayObject *__pyx_v_x_squared_norms = 0; PyArrayObject *__pyx_v_centers = 0; PyArrayObject *__pyx_v_counts = 0; PyArrayObject *__pyx_v_nearest_center = 0; PyArrayObject *__pyx_v_old_center = 0; int __pyx_v_compute_squared_diff; - PyArrayObject *__pyx_v_X_data = 0; - PyArrayObject *__pyx_v_X_indices = 0; - PyArrayObject *__pyx_v_X_indptr = 0; - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_clusters; - unsigned int __pyx_v_n_features; - unsigned int __pyx_v_sample_idx; - unsigned int __pyx_v_center_idx; - unsigned int __pyx_v_feature_idx; - unsigned int __pyx_v_k; - int __pyx_v_old_count; - int __pyx_v_new_count; - __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_v_squared_diff; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_old_center; - Py_ssize_t __pyx_bstride_0_old_center = 0; - Py_ssize_t __pyx_bshape_0_old_center = 0; - Py_buffer __pyx_bstruct_centers; - Py_ssize_t __pyx_bstride_0_centers = 0; - Py_ssize_t __pyx_bstride_1_centers = 0; - Py_ssize_t __pyx_bshape_0_centers = 0; - Py_ssize_t __pyx_bshape_1_centers = 0; - Py_buffer __pyx_bstruct_nearest_center; - Py_ssize_t __pyx_bstride_0_nearest_center = 0; - Py_ssize_t __pyx_bshape_0_nearest_center = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; - Py_buffer __pyx_bstruct_counts; - Py_ssize_t __pyx_bstride_0_counts = 0; - Py_ssize_t __pyx_bshape_0_counts = 0; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_x_squared_norms; - Py_ssize_t __pyx_bstride_0_x_squared_norms = 0; - Py_ssize_t __pyx_bshape_0_x_squared_norms = 0; - PyObject *__pyx_r = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyArrayObject *__pyx_t_2 = NULL; - PyArrayObject *__pyx_t_3 = NULL; - PyArrayObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - unsigned int __pyx_t_6; - unsigned int __pyx_t_7; - unsigned int __pyx_t_8; - unsigned int __pyx_t_9; - unsigned int __pyx_t_10; - unsigned int __pyx_t_11; - int __pyx_t_12; - PyObject *__pyx_t_13 = NULL; - unsigned int __pyx_t_14; - long __pyx_t_15; - int __pyx_t_16; - unsigned int __pyx_t_17; - unsigned int __pyx_t_18; - unsigned int __pyx_t_19; - unsigned int __pyx_t_20; - unsigned int __pyx_t_21; - int __pyx_t_22; - unsigned int __pyx_t_23; - unsigned int __pyx_t_24; - unsigned int __pyx_t_25; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__x_squared_norms,&__pyx_n_s__centers,&__pyx_n_s__counts,&__pyx_n_s__nearest_center,&__pyx_n_s__old_center,&__pyx_n_s_1,0}; - __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("_mini_batch_update_csr"); - __Pyx_TraceCall("_mini_batch_update_csr", __pyx_f[0], 139); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("_mini_batch_update_csr (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_x_squared_norms,&__pyx_n_s_centers,&__pyx_n_s_counts,&__pyx_n_s_nearest_center,&__pyx_n_s_old_center,&__pyx_n_s_compute_squared_diff,0}; PyObject* values[7] = {0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); @@ -2728,50 +2977,43 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__x_squared_norms); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x_squared_norms)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__centers); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_centers)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__counts); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_counts)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nearest_center); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_nearest_center)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__old_center); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_old_center)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_1); - if (likely(values[6])) kw_args--; + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_compute_squared_diff)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "_mini_batch_update_csr") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_mini_batch_update_csr") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 7) { goto __pyx_L5_argtuple_error; @@ -2790,149 +3032,239 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py __pyx_v_counts = ((PyArrayObject *)values[3]); __pyx_v_nearest_center = ((PyArrayObject *)values[4]); __pyx_v_old_center = ((PyArrayObject *)values[5]); - __pyx_v_compute_squared_diff = __Pyx_PyInt_AsInt(values[6]); if (unlikely((__pyx_v_compute_squared_diff == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_compute_squared_diff = __Pyx_PyInt_As_int(values[6]); if (unlikely((__pyx_v_compute_squared_diff == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_mini_batch_update_csr", 1, 7, 7, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.cluster._k_means._mini_batch_update_csr", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; - __pyx_bstruct_x_squared_norms.buf = NULL; - __pyx_bstruct_centers.buf = NULL; - __pyx_bstruct_counts.buf = NULL; - __pyx_bstruct_nearest_center.buf = NULL; - __pyx_bstruct_old_center.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x_squared_norms), __pyx_ptype_5numpy_ndarray, 1, "x_squared_norms", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_centers), __pyx_ptype_5numpy_ndarray, 1, "centers", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_counts), __pyx_ptype_5numpy_ndarray, 1, "counts", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nearest_center), __pyx_ptype_5numpy_ndarray, 1, "nearest_center", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_old_center), __pyx_ptype_5numpy_ndarray, 1, "old_center", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x_squared_norms), __pyx_ptype_5numpy_ndarray, 1, "x_squared_norms", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_centers), __pyx_ptype_5numpy_ndarray, 1, "centers", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_counts), __pyx_ptype_5numpy_ndarray, 1, "counts", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nearest_center), __pyx_ptype_5numpy_ndarray, 1, "nearest_center", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_old_center), __pyx_ptype_5numpy_ndarray, 1, "old_center", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_7cluster_8_k_means_4_mini_batch_update_csr(__pyx_self, __pyx_v_X, __pyx_v_x_squared_norms, __pyx_v_centers, __pyx_v_counts, __pyx_v_nearest_center, __pyx_v_old_center, __pyx_v_compute_squared_diff); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_4_mini_batch_update_csr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, CYTHON_UNUSED PyArrayObject *__pyx_v_x_squared_norms, PyArrayObject *__pyx_v_centers, PyArrayObject *__pyx_v_counts, PyArrayObject *__pyx_v_nearest_center, PyArrayObject *__pyx_v_old_center, int __pyx_v_compute_squared_diff) { + PyArrayObject *__pyx_v_X_data = 0; + PyArrayObject *__pyx_v_X_indices = 0; + PyArrayObject *__pyx_v_X_indptr = 0; + unsigned int __pyx_v_n_samples; + unsigned int __pyx_v_n_clusters; + unsigned int __pyx_v_n_features; + unsigned int __pyx_v_sample_idx; + unsigned int __pyx_v_center_idx; + unsigned int __pyx_v_feature_idx; + unsigned int __pyx_v_k; + int __pyx_v_old_count; + int __pyx_v_new_count; + __pyx_t_7sklearn_7cluster_8_k_means_DOUBLE __pyx_v_squared_diff; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_data; + __Pyx_Buffer __pyx_pybuffer_X_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indices; + __Pyx_Buffer __pyx_pybuffer_X_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indptr; + __Pyx_Buffer __pyx_pybuffer_X_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_centers; + __Pyx_Buffer __pyx_pybuffer_centers; + __Pyx_LocalBuf_ND __pyx_pybuffernd_counts; + __Pyx_Buffer __pyx_pybuffer_counts; + __Pyx_LocalBuf_ND __pyx_pybuffernd_nearest_center; + __Pyx_Buffer __pyx_pybuffer_nearest_center; + __Pyx_LocalBuf_ND __pyx_pybuffernd_old_center; + __Pyx_Buffer __pyx_pybuffer_old_center; + __Pyx_LocalBuf_ND __pyx_pybuffernd_x_squared_norms; + __Pyx_Buffer __pyx_pybuffer_x_squared_norms; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyArrayObject *__pyx_t_2 = NULL; + PyArrayObject *__pyx_t_3 = NULL; + PyArrayObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + unsigned int __pyx_t_6; + unsigned int __pyx_t_7; + unsigned int __pyx_t_8; + unsigned int __pyx_t_9; + unsigned int __pyx_t_10; + unsigned int __pyx_t_11; + int __pyx_t_12; + PyObject *__pyx_t_13 = NULL; + unsigned int __pyx_t_14; + long __pyx_t_15; + int __pyx_t_16; + unsigned int __pyx_t_17; + unsigned int __pyx_t_18; + unsigned int __pyx_t_19; + unsigned int __pyx_t_20; + unsigned int __pyx_t_21; + int __pyx_t_22; + unsigned int __pyx_t_23; + unsigned int __pyx_t_24; + unsigned int __pyx_t_25; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceDeclarations + __Pyx_RefNannySetupContext("_mini_batch_update_csr", 0); + __Pyx_TraceCall("_mini_batch_update_csr", __pyx_f[0], 142); + __pyx_pybuffer_X_data.pybuffer.buf = NULL; + __pyx_pybuffer_X_data.refcount = 0; + __pyx_pybuffernd_X_data.data = NULL; + __pyx_pybuffernd_X_data.rcbuffer = &__pyx_pybuffer_X_data; + __pyx_pybuffer_X_indices.pybuffer.buf = NULL; + __pyx_pybuffer_X_indices.refcount = 0; + __pyx_pybuffernd_X_indices.data = NULL; + __pyx_pybuffernd_X_indices.rcbuffer = &__pyx_pybuffer_X_indices; + __pyx_pybuffer_X_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_X_indptr.refcount = 0; + __pyx_pybuffernd_X_indptr.data = NULL; + __pyx_pybuffernd_X_indptr.rcbuffer = &__pyx_pybuffer_X_indptr; + __pyx_pybuffer_x_squared_norms.pybuffer.buf = NULL; + __pyx_pybuffer_x_squared_norms.refcount = 0; + __pyx_pybuffernd_x_squared_norms.data = NULL; + __pyx_pybuffernd_x_squared_norms.rcbuffer = &__pyx_pybuffer_x_squared_norms; + __pyx_pybuffer_centers.pybuffer.buf = NULL; + __pyx_pybuffer_centers.refcount = 0; + __pyx_pybuffernd_centers.data = NULL; + __pyx_pybuffernd_centers.rcbuffer = &__pyx_pybuffer_centers; + __pyx_pybuffer_counts.pybuffer.buf = NULL; + __pyx_pybuffer_counts.refcount = 0; + __pyx_pybuffernd_counts.data = NULL; + __pyx_pybuffernd_counts.rcbuffer = &__pyx_pybuffer_counts; + __pyx_pybuffer_nearest_center.pybuffer.buf = NULL; + __pyx_pybuffer_nearest_center.refcount = 0; + __pyx_pybuffernd_nearest_center.data = NULL; + __pyx_pybuffernd_nearest_center.rcbuffer = &__pyx_pybuffer_nearest_center; + __pyx_pybuffer_old_center.pybuffer.buf = NULL; + __pyx_pybuffer_old_center.refcount = 0; + __pyx_pybuffernd_old_center.data = NULL; + __pyx_pybuffernd_old_center.rcbuffer = &__pyx_pybuffer_old_center; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_x_squared_norms, (PyObject*)__pyx_v_x_squared_norms, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer, (PyObject*)__pyx_v_x_squared_norms, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_x_squared_norms = __pyx_bstruct_x_squared_norms.strides[0]; - __pyx_bshape_0_x_squared_norms = __pyx_bstruct_x_squared_norms.shape[0]; + __pyx_pybuffernd_x_squared_norms.diminfo[0].strides = __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x_squared_norms.diminfo[0].shape = __pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_centers, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_centers.rcbuffer->pybuffer, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_centers = __pyx_bstruct_centers.strides[0]; __pyx_bstride_1_centers = __pyx_bstruct_centers.strides[1]; - __pyx_bshape_0_centers = __pyx_bstruct_centers.shape[0]; __pyx_bshape_1_centers = __pyx_bstruct_centers.shape[1]; + __pyx_pybuffernd_centers.diminfo[0].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_centers.diminfo[0].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_centers.diminfo[1].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_centers.diminfo[1].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_counts, (PyObject*)__pyx_v_counts, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_counts.rcbuffer->pybuffer, (PyObject*)__pyx_v_counts, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_counts = __pyx_bstruct_counts.strides[0]; - __pyx_bshape_0_counts = __pyx_bstruct_counts.shape[0]; + __pyx_pybuffernd_counts.diminfo[0].strides = __pyx_pybuffernd_counts.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_counts.diminfo[0].shape = __pyx_pybuffernd_counts.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_nearest_center, (PyObject*)__pyx_v_nearest_center, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nearest_center.rcbuffer->pybuffer, (PyObject*)__pyx_v_nearest_center, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_nearest_center = __pyx_bstruct_nearest_center.strides[0]; - __pyx_bshape_0_nearest_center = __pyx_bstruct_nearest_center.shape[0]; + __pyx_pybuffernd_nearest_center.diminfo[0].strides = __pyx_pybuffernd_nearest_center.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_nearest_center.diminfo[0].shape = __pyx_pybuffernd_nearest_center.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_old_center, (PyObject*)__pyx_v_old_center, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_old_center.rcbuffer->pybuffer, (PyObject*)__pyx_v_old_center, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_old_center = __pyx_bstruct_old_center.strides[0]; - __pyx_bshape_0_old_center = __pyx_bstruct_old_center.shape[0]; + __pyx_pybuffernd_old_center.diminfo[0].strides = __pyx_pybuffernd_old_center.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_old_center.diminfo[0].shape = __pyx_pybuffernd_old_center.rcbuffer->pybuffer.shape[0]; - /* "sklearn/cluster/_k_means.pyx":176 + /* "sklearn/cluster/_k_means.pyx":179 * """ * cdef: * np.ndarray[DOUBLE, ndim=1] X_data = X.data # <<<<<<<<<<<<<< * np.ndarray[int, ndim=1] X_indices = X.indices * np.ndarray[int, ndim=1] X_indptr = X.indptr */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_2 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_t_2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_data.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer, (PyObject*)__pyx_t_2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_data.diminfo[0].strides = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_data.diminfo[0].shape = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.shape[0]; } } __pyx_t_2 = 0; __pyx_v_X_data = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/cluster/_k_means.pyx":177 + /* "sklearn/cluster/_k_means.pyx":180 * cdef: * np.ndarray[DOUBLE, ndim=1] X_data = X.data * np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< * np.ndarray[int, ndim=1] X_indptr = X.indptr * unsigned int n_samples = X.shape[0] */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_3 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_t_3, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indices.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer, (PyObject*)__pyx_t_3, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indices.diminfo[0].strides = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indices.diminfo[0].shape = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.shape[0]; } } __pyx_t_3 = 0; __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/cluster/_k_means.pyx":178 + /* "sklearn/cluster/_k_means.pyx":181 * np.ndarray[DOUBLE, ndim=1] X_data = X.data * np.ndarray[int, ndim=1] X_indices = X.indices * np.ndarray[int, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< * unsigned int n_samples = X.shape[0] * unsigned int n_clusters = centers.shape[0] */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indptr.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indptr.diminfo[0].strides = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indptr.diminfo[0].shape = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.shape[0]; } } __pyx_t_4 = 0; __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/cluster/_k_means.pyx":179 + /* "sklearn/cluster/_k_means.pyx":182 * np.ndarray[int, ndim=1] X_indices = X.indices * np.ndarray[int, ndim=1] X_indptr = X.indptr * unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< * unsigned int n_clusters = centers.shape[0] * unsigned int n_features = centers.shape[1] */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_5); if (unlikely((__pyx_t_6 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyInt_As_unsigned_int(__pyx_t_5); if (unlikely((__pyx_t_6 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_n_samples = __pyx_t_6; - /* "sklearn/cluster/_k_means.pyx":180 + /* "sklearn/cluster/_k_means.pyx":183 * np.ndarray[int, ndim=1] X_indptr = X.indptr * unsigned int n_samples = X.shape[0] * unsigned int n_clusters = centers.shape[0] # <<<<<<<<<<<<<< @@ -2941,7 +3273,7 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py */ __pyx_v_n_clusters = (__pyx_v_centers->dimensions[0]); - /* "sklearn/cluster/_k_means.pyx":181 + /* "sklearn/cluster/_k_means.pyx":184 * unsigned int n_samples = X.shape[0] * unsigned int n_clusters = centers.shape[0] * unsigned int n_features = centers.shape[1] # <<<<<<<<<<<<<< @@ -2950,7 +3282,7 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py */ __pyx_v_n_features = (__pyx_v_centers->dimensions[1]); - /* "sklearn/cluster/_k_means.pyx":187 + /* "sklearn/cluster/_k_means.pyx":190 * int old_count, new_count * DOUBLE center_diff * DOUBLE squared_diff = 0.0 # <<<<<<<<<<<<<< @@ -2959,7 +3291,7 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py */ __pyx_v_squared_diff = 0.0; - /* "sklearn/cluster/_k_means.pyx":190 + /* "sklearn/cluster/_k_means.pyx":193 * * # move centers to the mean of both old and newly assigned samples * for center_idx in range(n_clusters): # <<<<<<<<<<<<<< @@ -2970,7 +3302,7 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { __pyx_v_center_idx = __pyx_t_7; - /* "sklearn/cluster/_k_means.pyx":191 + /* "sklearn/cluster/_k_means.pyx":194 * # move centers to the mean of both old and newly assigned samples * for center_idx in range(n_clusters): * old_count = counts[center_idx] # <<<<<<<<<<<<<< @@ -2978,9 +3310,9 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py * */ __pyx_t_8 = __pyx_v_center_idx; - __pyx_v_old_count = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_bstruct_counts.buf, __pyx_t_8, __pyx_bstride_0_counts)); + __pyx_v_old_count = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_pybuffernd_counts.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_counts.diminfo[0].strides)); - /* "sklearn/cluster/_k_means.pyx":192 + /* "sklearn/cluster/_k_means.pyx":195 * for center_idx in range(n_clusters): * old_count = counts[center_idx] * new_count = old_count # <<<<<<<<<<<<<< @@ -2989,7 +3321,7 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py */ __pyx_v_new_count = __pyx_v_old_count; - /* "sklearn/cluster/_k_means.pyx":195 + /* "sklearn/cluster/_k_means.pyx":198 * * # count the number of samples assigned to this center * for sample_idx in range(n_samples): # <<<<<<<<<<<<<< @@ -3000,7 +3332,7 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { __pyx_v_sample_idx = __pyx_t_10; - /* "sklearn/cluster/_k_means.pyx":196 + /* "sklearn/cluster/_k_means.pyx":199 * # count the number of samples assigned to this center * for sample_idx in range(n_samples): * if nearest_center[sample_idx] == center_idx: # <<<<<<<<<<<<<< @@ -3008,10 +3340,10 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py * */ __pyx_t_11 = __pyx_v_sample_idx; - __pyx_t_12 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_bstruct_nearest_center.buf, __pyx_t_11, __pyx_bstride_0_nearest_center)) == __pyx_v_center_idx); + __pyx_t_12 = (((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_pybuffernd_nearest_center.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_nearest_center.diminfo[0].strides)) == __pyx_v_center_idx) != 0); if (__pyx_t_12) { - /* "sklearn/cluster/_k_means.pyx":197 + /* "sklearn/cluster/_k_means.pyx":200 * for sample_idx in range(n_samples): * if nearest_center[sample_idx] == center_idx: * new_count += 1 # <<<<<<<<<<<<<< @@ -3019,58 +3351,57 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py * if new_count == old_count: */ __pyx_v_new_count = (__pyx_v_new_count + 1); - goto __pyx_L10; + goto __pyx_L7; } - __pyx_L10:; + __pyx_L7:; } - /* "sklearn/cluster/_k_means.pyx":199 + /* "sklearn/cluster/_k_means.pyx":202 * new_count += 1 * * if new_count == old_count: # <<<<<<<<<<<<<< * # no new sample: leave this center as it stands * continue */ - __pyx_t_12 = (__pyx_v_new_count == __pyx_v_old_count); + __pyx_t_12 = ((__pyx_v_new_count == __pyx_v_old_count) != 0); if (__pyx_t_12) { - /* "sklearn/cluster/_k_means.pyx":201 + /* "sklearn/cluster/_k_means.pyx":204 * if new_count == old_count: * # no new sample: leave this center as it stands * continue # <<<<<<<<<<<<<< * - * # rescale the old center to reflect it previous accumulated + * # rescale the old center to reflect it previous accumulated weight */ - goto __pyx_L6_continue; - goto __pyx_L11; + goto __pyx_L3_continue; } - __pyx_L11:; - /* "sklearn/cluster/_k_means.pyx":205 - * # rescale the old center to reflect it previous accumulated - * # weight w.r.t. the new data that will be incrementally contributed + /* "sklearn/cluster/_k_means.pyx":208 + * # rescale the old center to reflect it previous accumulated weight + * # with regards to the new data that will be incrementally contributed * if compute_squared_diff: # <<<<<<<<<<<<<< * old_center[:] = centers[center_idx] * centers[center_idx] *= old_count */ - if (__pyx_v_compute_squared_diff) { + __pyx_t_12 = (__pyx_v_compute_squared_diff != 0); + if (__pyx_t_12) { - /* "sklearn/cluster/_k_means.pyx":206 - * # weight w.r.t. the new data that will be incrementally contributed + /* "sklearn/cluster/_k_means.pyx":209 + * # with regards to the new data that will be incrementally contributed * if compute_squared_diff: * old_center[:] = centers[center_idx] # <<<<<<<<<<<<<< * centers[center_idx] *= old_count * */ - __pyx_t_5 = __Pyx_GetItemInt(((PyObject *)__pyx_v_centers), __pyx_v_center_idx, sizeof(unsigned int)+1, PyLong_FromUnsignedLong); if (!__pyx_t_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetItemInt(((PyObject *)__pyx_v_centers), __pyx_v_center_idx, unsigned int, 0, __Pyx_PyInt_From_unsigned_int, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_5); - if (__Pyx_PySequence_SetSlice(((PyObject *)__pyx_v_old_center), 0, PY_SSIZE_T_MAX, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_PyObject_SetSlice(((PyObject *)__pyx_v_old_center), __pyx_t_5, 0, 0, NULL, NULL, &__pyx_slice_, 0, 0, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L12; + goto __pyx_L9; } - __pyx_L12:; + __pyx_L9:; - /* "sklearn/cluster/_k_means.pyx":207 + /* "sklearn/cluster/_k_means.pyx":210 * if compute_squared_diff: * old_center[:] = centers[center_idx] * centers[center_idx] *= old_count # <<<<<<<<<<<<<< @@ -3078,18 +3409,18 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py * # iterate of over samples assigned to this cluster to move the center */ __pyx_t_9 = __pyx_v_center_idx; - __pyx_t_5 = __Pyx_GetItemInt(((PyObject *)__pyx_v_centers), __pyx_t_9, sizeof(unsigned int)+1, PyLong_FromUnsignedLong); if (!__pyx_t_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetItemInt(((PyObject *)__pyx_v_centers), __pyx_t_9, unsigned int, 0, __Pyx_PyInt_From_unsigned_int, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_5); - __pyx_t_1 = PyInt_FromLong(__pyx_v_old_count); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_old_count); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_13 = PyNumber_InPlaceMultiply(__pyx_t_5, __pyx_t_1); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = PyNumber_InPlaceMultiply(__pyx_t_5, __pyx_t_1); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_13); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__Pyx_SetItemInt(((PyObject *)__pyx_v_centers), __pyx_t_9, __pyx_t_13, sizeof(unsigned int)+1, PyLong_FromUnsignedLong) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_SetItemInt(((PyObject *)__pyx_v_centers), __pyx_t_9, __pyx_t_13, unsigned int, 0, __Pyx_PyInt_From_unsigned_int, 0, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - /* "sklearn/cluster/_k_means.pyx":211 + /* "sklearn/cluster/_k_means.pyx":214 * # iterate of over samples assigned to this cluster to move the center * # location by inplace summation * for sample_idx in range(n_samples): # <<<<<<<<<<<<<< @@ -3100,7 +3431,7 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { __pyx_v_sample_idx = __pyx_t_10; - /* "sklearn/cluster/_k_means.pyx":212 + /* "sklearn/cluster/_k_means.pyx":215 * # location by inplace summation * for sample_idx in range(n_samples): * if nearest_center[sample_idx] != center_idx: # <<<<<<<<<<<<<< @@ -3108,22 +3439,20 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py * */ __pyx_t_14 = __pyx_v_sample_idx; - __pyx_t_12 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_bstruct_nearest_center.buf, __pyx_t_14, __pyx_bstride_0_nearest_center)) != __pyx_v_center_idx); + __pyx_t_12 = (((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_pybuffernd_nearest_center.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_nearest_center.diminfo[0].strides)) != __pyx_v_center_idx) != 0); if (__pyx_t_12) { - /* "sklearn/cluster/_k_means.pyx":213 + /* "sklearn/cluster/_k_means.pyx":216 * for sample_idx in range(n_samples): * if nearest_center[sample_idx] != center_idx: * continue # <<<<<<<<<<<<<< * * # inplace sum with new samples that are members of this cluster */ - goto __pyx_L13_continue; - goto __pyx_L15; + goto __pyx_L10_continue; } - __pyx_L15:; - /* "sklearn/cluster/_k_means.pyx":218 + /* "sklearn/cluster/_k_means.pyx":221 * # and update of the incremental squared difference update of the * # center position * for k in range(X_indptr[sample_idx], X_indptr[sample_idx + 1]): # <<<<<<<<<<<<<< @@ -3131,12 +3460,12 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py * */ __pyx_t_15 = (__pyx_v_sample_idx + 1); - __pyx_t_16 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_15, __pyx_bstride_0_X_indptr)); + __pyx_t_16 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); __pyx_t_17 = __pyx_v_sample_idx; - for (__pyx_t_18 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_17, __pyx_bstride_0_X_indptr)); __pyx_t_18 < __pyx_t_16; __pyx_t_18+=1) { + for (__pyx_t_18 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); __pyx_t_18 < __pyx_t_16; __pyx_t_18+=1) { __pyx_v_k = __pyx_t_18; - /* "sklearn/cluster/_k_means.pyx":219 + /* "sklearn/cluster/_k_means.pyx":222 * # center position * for k in range(X_indptr[sample_idx], X_indptr[sample_idx + 1]): * centers[center_idx, X_indices[k]] += X_data[k] # <<<<<<<<<<<<<< @@ -3146,23 +3475,23 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py __pyx_t_19 = __pyx_v_k; __pyx_t_20 = __pyx_v_k; __pyx_t_21 = __pyx_v_center_idx; - __pyx_t_22 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indices.buf, __pyx_t_20, __pyx_bstride_0_X_indices)); - *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_centers.buf, __pyx_t_21, __pyx_bstride_0_centers, __pyx_t_22, __pyx_bstride_1_centers) += (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_19, __pyx_bstride_0_X_data)); + __pyx_t_22 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_X_indices.diminfo[0].strides)); + *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_centers.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_centers.diminfo[0].strides, __pyx_t_22, __pyx_pybuffernd_centers.diminfo[1].strides) += (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_X_data.diminfo[0].strides)); } - __pyx_L13_continue:; + __pyx_L10_continue:; } - /* "sklearn/cluster/_k_means.pyx":222 + /* "sklearn/cluster/_k_means.pyx":225 * * # inplace rescale center with updated count * if new_count > old_count: # <<<<<<<<<<<<<< * # update the count statistics for this center * counts[center_idx] = new_count */ - __pyx_t_12 = (__pyx_v_new_count > __pyx_v_old_count); + __pyx_t_12 = ((__pyx_v_new_count > __pyx_v_old_count) != 0); if (__pyx_t_12) { - /* "sklearn/cluster/_k_means.pyx":224 + /* "sklearn/cluster/_k_means.pyx":227 * if new_count > old_count: * # update the count statistics for this center * counts[center_idx] = new_count # <<<<<<<<<<<<<< @@ -3170,9 +3499,9 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py * # re-scale the updated center with the total new counts */ __pyx_t_9 = __pyx_v_center_idx; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_bstruct_counts.buf, __pyx_t_9, __pyx_bstride_0_counts) = __pyx_v_new_count; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_pybuffernd_counts.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_counts.diminfo[0].strides) = __pyx_v_new_count; - /* "sklearn/cluster/_k_means.pyx":227 + /* "sklearn/cluster/_k_means.pyx":230 * * # re-scale the updated center with the total new counts * centers[center_idx] /= new_count # <<<<<<<<<<<<<< @@ -3180,27 +3509,28 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py * # update the incremental computation of the squared total */ __pyx_t_10 = __pyx_v_center_idx; - __pyx_t_13 = __Pyx_GetItemInt(((PyObject *)__pyx_v_centers), __pyx_t_10, sizeof(unsigned int)+1, PyLong_FromUnsignedLong); if (!__pyx_t_13) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = __Pyx_GetItemInt(((PyObject *)__pyx_v_centers), __pyx_t_10, unsigned int, 0, __Pyx_PyInt_From_unsigned_int, 0, 0, 0); if (unlikely(__pyx_t_13 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_13); - __pyx_t_1 = PyInt_FromLong(__pyx_v_new_count); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_new_count); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = __Pyx_PyNumber_InPlaceDivide(__pyx_t_13, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyNumber_InPlaceDivide(__pyx_t_13, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__Pyx_SetItemInt(((PyObject *)__pyx_v_centers), __pyx_t_10, __pyx_t_5, sizeof(unsigned int)+1, PyLong_FromUnsignedLong) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_SetItemInt(((PyObject *)__pyx_v_centers), __pyx_t_10, __pyx_t_5, unsigned int, 0, __Pyx_PyInt_From_unsigned_int, 0, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - /* "sklearn/cluster/_k_means.pyx":231 + /* "sklearn/cluster/_k_means.pyx":234 * # update the incremental computation of the squared total * # centers position change * if compute_squared_diff: # <<<<<<<<<<<<<< * for feature_idx in range(n_features): * squared_diff += (old_center[feature_idx] */ - if (__pyx_v_compute_squared_diff) { + __pyx_t_12 = (__pyx_v_compute_squared_diff != 0); + if (__pyx_t_12) { - /* "sklearn/cluster/_k_means.pyx":232 + /* "sklearn/cluster/_k_means.pyx":235 * # centers position change * if compute_squared_diff: * for feature_idx in range(n_features): # <<<<<<<<<<<<<< @@ -3211,7 +3541,7 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py for (__pyx_t_18 = 0; __pyx_t_18 < __pyx_t_10; __pyx_t_18+=1) { __pyx_v_feature_idx = __pyx_t_18; - /* "sklearn/cluster/_k_means.pyx":233 + /* "sklearn/cluster/_k_means.pyx":236 * if compute_squared_diff: * for feature_idx in range(n_features): * squared_diff += (old_center[feature_idx] # <<<<<<<<<<<<<< @@ -3220,7 +3550,7 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py */ __pyx_t_23 = __pyx_v_feature_idx; - /* "sklearn/cluster/_k_means.pyx":234 + /* "sklearn/cluster/_k_means.pyx":237 * for feature_idx in range(n_features): * squared_diff += (old_center[feature_idx] * - centers[center_idx, feature_idx]) ** 2 # <<<<<<<<<<<<<< @@ -3229,18 +3559,26 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py */ __pyx_t_24 = __pyx_v_center_idx; __pyx_t_25 = __pyx_v_feature_idx; - __pyx_v_squared_diff = (__pyx_v_squared_diff + pow(((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_old_center.buf, __pyx_t_23, __pyx_bstride_0_old_center)) - (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_centers.buf, __pyx_t_24, __pyx_bstride_0_centers, __pyx_t_25, __pyx_bstride_1_centers))), 2.0)); + + /* "sklearn/cluster/_k_means.pyx":236 + * if compute_squared_diff: + * for feature_idx in range(n_features): + * squared_diff += (old_center[feature_idx] # <<<<<<<<<<<<<< + * - centers[center_idx, feature_idx]) ** 2 + * + */ + __pyx_v_squared_diff = (__pyx_v_squared_diff + pow(((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_old_center.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_old_center.diminfo[0].strides)) - (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_centers.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_centers.diminfo[0].strides, __pyx_t_25, __pyx_pybuffernd_centers.diminfo[1].strides))), 2.0)); } - goto __pyx_L19; + goto __pyx_L16; } - __pyx_L19:; - goto __pyx_L18; + __pyx_L16:; + goto __pyx_L15; } - __pyx_L18:; - __pyx_L6_continue:; + __pyx_L15:; + __pyx_L3_continue:; } - /* "sklearn/cluster/_k_means.pyx":236 + /* "sklearn/cluster/_k_means.pyx":239 * - centers[center_idx, feature_idx]) ** 2 * * return squared_diff # <<<<<<<<<<<<<< @@ -3248,41 +3586,48 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_5 = PyFloat_FromDouble(__pyx_v_squared_diff); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_v_squared_diff); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/cluster/_k_means.pyx":142 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _mini_batch_update_csr(X, np.ndarray[DOUBLE, ndim=1] x_squared_norms, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=2] centers, + * np.ndarray[INT, ndim=1] counts, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_13); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_old_center); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_centers); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_nearest_center); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_counts); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_x_squared_norms); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_counts.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nearest_center.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_old_center.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.cluster._k_means._mini_batch_update_csr", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_old_center); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_centers); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_nearest_center); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_counts); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_x_squared_norms); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_counts.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nearest_center.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_old_center.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_squared_norms.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_X_data); __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); @@ -3293,522 +3638,1485 @@ static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr(Py return __pyx_r; } -/* "sklearn/cluster/_k_means.pyx":242 +/* "sklearn/cluster/_k_means.pyx":245 * @cython.wraparound(False) * @cython.cdivision(True) - * def csr_row_norm_l2(X, squared=True): # <<<<<<<<<<<<<< - * """Get L2 norm of each row in CSR matrix X. - * + * def _centers_dense(np.ndarray[DOUBLE, ndim=2] X, # <<<<<<<<<<<<<< + * np.ndarray[INT, ndim=1] labels, int n_clusters, + * np.ndarray[DOUBLE, ndim=1] distances): */ -static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_3csr_row_norm_l2(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_7cluster_8_k_means_3csr_row_norm_l2[] = "Get L2 norm of each row in CSR matrix X.\n\n TODO: refactor me in the sklearn.utils.sparsefuncs module once the CSR\n sklearn.preprocessing.Scaler has been refactored as well.\n "; -static PyMethodDef __pyx_mdef_7sklearn_7cluster_8_k_means_3csr_row_norm_l2 = {__Pyx_NAMESTR("csr_row_norm_l2"), (PyCFunction)__pyx_pf_7sklearn_7cluster_8_k_means_3csr_row_norm_l2, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_8_k_means_3csr_row_norm_l2)}; -static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_3csr_row_norm_l2(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_X = 0; - PyObject *__pyx_v_squared = 0; - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - PyArrayObject *__pyx_v_norms = 0; - PyArrayObject *__pyx_v_X_data = 0; - PyArrayObject *__pyx_v_X_indices = 0; - PyArrayObject *__pyx_v_X_indptr = 0; - unsigned int __pyx_v_i; - unsigned int __pyx_v_j; - double __pyx_v_sum_; - int __pyx_v_with_sqrt; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; - Py_buffer __pyx_bstruct_norms; - Py_ssize_t __pyx_bstride_0_norms = 0; - Py_ssize_t __pyx_bshape_0_norms = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - unsigned int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyArrayObject *__pyx_t_7 = NULL; - PyArrayObject *__pyx_t_8 = NULL; - PyArrayObject *__pyx_t_9 = NULL; - PyArrayObject *__pyx_t_10 = NULL; - int __pyx_t_11; - unsigned int __pyx_t_12; - long __pyx_t_13; - int __pyx_t_14; - unsigned int __pyx_t_15; - unsigned int __pyx_t_16; - unsigned int __pyx_t_17; - unsigned int __pyx_t_18; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_7_centers_dense(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7cluster_8_k_means_6_centers_dense[] = "M step of the K-means EM algorithm\n\n Computation of cluster centers / means.\n\n Parameters\n ----------\n X: array-like, shape (n_samples, n_features)\n\n labels: array of integers, shape (n_samples)\n Current label assignment\n\n n_clusters: int\n Number of desired clusters\n\n distances: array-like, shape (n_samples)\n Distance to closest cluster for each sample.\n\n Returns\n -------\n centers: array, shape (n_clusters, n_features)\n The resulting centers\n "; +static PyMethodDef __pyx_mdef_7sklearn_7cluster_8_k_means_7_centers_dense = {"_centers_dense", (PyCFunction)__pyx_pw_7sklearn_7cluster_8_k_means_7_centers_dense, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_7cluster_8_k_means_6_centers_dense}; +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_7_centers_dense(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_X = 0; + PyArrayObject *__pyx_v_labels = 0; + int __pyx_v_n_clusters; + PyArrayObject *__pyx_v_distances = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__squared,0}; - __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("csr_row_norm_l2"); - __Pyx_TraceCall("csr_row_norm_l2", __pyx_f[0], 242); - __pyx_self = __pyx_self; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_centers_dense (wrapper)", 0); { - PyObject* values[2] = {0,0}; - values[1] = __pyx_k_2; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_labels,&__pyx_n_s_n_clusters,&__pyx_n_s_distances,0}; + PyObject* values[4] = {0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__squared); - if (value) { values[1] = value; kw_args--; } + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_labels)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_centers_dense", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_clusters)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_centers_dense", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_distances)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_centers_dense", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "csr_row_norm_l2") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_centers_dense") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } + } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { + goto __pyx_L5_argtuple_error; } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); } - __pyx_v_X = values[0]; - __pyx_v_squared = values[1]; + __pyx_v_X = ((PyArrayObject *)values[0]); + __pyx_v_labels = ((PyArrayObject *)values[1]); + __pyx_v_n_clusters = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_n_clusters == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 246; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_distances = ((PyArrayObject *)values[3]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("csr_row_norm_l2", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_centers_dense", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.cluster._k_means.csr_row_norm_l2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.cluster._k_means._centers_dense", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_norms.buf = NULL; - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_labels), __pyx_ptype_5numpy_ndarray, 1, "labels", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_distances), __pyx_ptype_5numpy_ndarray, 1, "distances", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_7cluster_8_k_means_6_centers_dense(__pyx_self, __pyx_v_X, __pyx_v_labels, __pyx_v_n_clusters, __pyx_v_distances); - /* "sklearn/cluster/_k_means.pyx":249 - * """ - * cdef: - * unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< - * unsigned int n_features = X.shape[1] - * np.ndarray[DOUBLE, ndim=1] norms = np.zeros((n_samples,), - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_n_samples = __pyx_t_3; + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/cluster/_k_means.pyx":250 - * cdef: - * unsigned int n_samples = X.shape[0] - * unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< - * np.ndarray[DOUBLE, ndim=1] norms = np.zeros((n_samples,), - * dtype=np.float64) +static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_6_centers_dense(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_labels, int __pyx_v_n_clusters, PyArrayObject *__pyx_v_distances) { + int __pyx_v_n_samples; + int __pyx_v_n_features; + int __pyx_v_i; + int __pyx_v_j; + PyArrayObject *__pyx_v_centers = 0; + PyObject *__pyx_v_n_samples_in_cluster = NULL; + PyObject *__pyx_v_empty_clusters = NULL; + PyObject *__pyx_v_far_from_centers = NULL; + PyObject *__pyx_v_cluster_id = NULL; + PyObject *__pyx_v_new_center = NULL; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_LocalBuf_ND __pyx_pybuffernd_centers; + __Pyx_Buffer __pyx_pybuffer_centers; + __Pyx_LocalBuf_ND __pyx_pybuffernd_distances; + __Pyx_Buffer __pyx_pybuffer_distances; + __Pyx_LocalBuf_ND __pyx_pybuffernd_labels; + __Pyx_Buffer __pyx_pybuffer_labels; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + PyObject *(*__pyx_t_10)(PyObject *); + int __pyx_t_11; + int __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + __pyx_t_7sklearn_7cluster_8_k_means_INT __pyx_t_17; + int __pyx_t_18; + PyObject *__pyx_t_19 = NULL; + PyObject *__pyx_t_20 = NULL; + PyObject *__pyx_t_21 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceDeclarations + __Pyx_RefNannySetupContext("_centers_dense", 0); + __Pyx_TraceCall("_centers_dense", __pyx_f[0], 245); + __pyx_pybuffer_centers.pybuffer.buf = NULL; + __pyx_pybuffer_centers.refcount = 0; + __pyx_pybuffernd_centers.data = NULL; + __pyx_pybuffernd_centers.rcbuffer = &__pyx_pybuffer_centers; + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + __pyx_pybuffer_labels.pybuffer.buf = NULL; + __pyx_pybuffer_labels.refcount = 0; + __pyx_pybuffernd_labels.data = NULL; + __pyx_pybuffernd_labels.rcbuffer = &__pyx_pybuffer_labels; + __pyx_pybuffer_distances.pybuffer.buf = NULL; + __pyx_pybuffer_distances.refcount = 0; + __pyx_pybuffernd_distances.data = NULL; + __pyx_pybuffernd_distances.rcbuffer = &__pyx_pybuffer_distances; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_labels.diminfo[0].strides = __pyx_pybuffernd_labels.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_labels.diminfo[0].shape = __pyx_pybuffernd_labels.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_distances.rcbuffer->pybuffer, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_distances.diminfo[0].strides = __pyx_pybuffernd_distances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_distances.diminfo[0].shape = __pyx_pybuffernd_distances.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/cluster/_k_means.pyx":272 + * ## TODO: add support for CSR input + * cdef int n_samples, n_features + * n_samples = X.shape[0] # <<<<<<<<<<<<<< + * n_features = X.shape[1] + * cdef int i, j, c */ - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_n_features = __pyx_t_3; + __pyx_v_n_samples = (__pyx_v_X->dimensions[0]); - /* "sklearn/cluster/_k_means.pyx":251 - * unsigned int n_samples = X.shape[0] - * unsigned int n_features = X.shape[1] - * np.ndarray[DOUBLE, ndim=1] norms = np.zeros((n_samples,), # <<<<<<<<<<<<<< - * dtype=np.float64) - * np.ndarray[DOUBLE, ndim=1] X_data = X.data + /* "sklearn/cluster/_k_means.pyx":273 + * cdef int n_samples, n_features + * n_samples = X.shape[0] + * n_features = X.shape[1] # <<<<<<<<<<<<<< + * cdef int i, j, c + * cdef np.ndarray[DOUBLE, ndim=2] centers = np.zeros((n_clusters, n_features)) */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyLong_FromUnsignedLong(__pyx_v_n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); - __pyx_t_4 = 0; - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_v_n_features = (__pyx_v_X->dimensions[1]); - /* "sklearn/cluster/_k_means.pyx":252 - * unsigned int n_features = X.shape[1] - * np.ndarray[DOUBLE, ndim=1] norms = np.zeros((n_samples,), - * dtype=np.float64) # <<<<<<<<<<<<<< - * np.ndarray[DOUBLE, ndim=1] X_data = X.data - * np.ndarray[int, ndim=1] X_indices = X.indices + /* "sklearn/cluster/_k_means.pyx":275 + * n_features = X.shape[1] + * cdef int i, j, c + * cdef np.ndarray[DOUBLE, ndim=2] centers = np.zeros((n_clusters, n_features)) # <<<<<<<<<<<<<< + * n_samples_in_cluster = bincount(labels, minlength=n_clusters) + * empty_clusters = np.where(n_samples_in_cluster == 0)[0] */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = ((PyArrayObject *)__pyx_t_6); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_norms, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_norms = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_norms.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_norms = __pyx_bstruct_norms.strides[0]; - __pyx_bshape_0_norms = __pyx_bstruct_norms.shape[0]; + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_n_clusters); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_n_features); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); } } - __pyx_t_7 = 0; - __pyx_v_norms = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; - - /* "sklearn/cluster/_k_means.pyx":253 - * np.ndarray[DOUBLE, ndim=1] norms = np.zeros((n_samples,), - * dtype=np.float64) - * np.ndarray[DOUBLE, ndim=1] X_data = X.data # <<<<<<<<<<<<<< - * np.ndarray[int, ndim=1] X_indices = X.indices - * np.ndarray[int, ndim=1] X_indptr = X.indptr - */ - __pyx_t_6 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__data); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_8 = ((PyArrayObject *)__pyx_t_6); + if (!__pyx_t_4) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_2 = PyTuple_New(1+1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + PyTuple_SET_ITEM(__pyx_t_2, 0+1, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_data.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_centers.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) { + __pyx_v_centers = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_centers.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_centers.diminfo[0].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_centers.diminfo[0].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_centers.diminfo[1].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_centers.diminfo[1].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[1]; } } - __pyx_t_8 = 0; - __pyx_v_X_data = ((PyArrayObject *)__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_centers = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/cluster/_k_means.pyx":254 - * dtype=np.float64) - * np.ndarray[DOUBLE, ndim=1] X_data = X.data - * np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< - * np.ndarray[int, ndim=1] X_indptr = X.indptr + /* "sklearn/cluster/_k_means.pyx":276 + * cdef int i, j, c + * cdef np.ndarray[DOUBLE, ndim=2] centers = np.zeros((n_clusters, n_features)) + * n_samples_in_cluster = bincount(labels, minlength=n_clusters) # <<<<<<<<<<<<<< + * empty_clusters = np.where(n_samples_in_cluster == 0)[0] + * # maybe also relocate small clusters? + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_bincount); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_labels)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_labels)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_labels)); + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_n_clusters); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_minlength, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_n_samples_in_cluster = __pyx_t_5; + __pyx_t_5 = 0; + + /* "sklearn/cluster/_k_means.pyx":277 + * cdef np.ndarray[DOUBLE, ndim=2] centers = np.zeros((n_clusters, n_features)) + * n_samples_in_cluster = bincount(labels, minlength=n_clusters) + * empty_clusters = np.where(n_samples_in_cluster == 0)[0] # <<<<<<<<<<<<<< + * # maybe also relocate small clusters? * */ - __pyx_t_6 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indices); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_9 = ((PyArrayObject *)__pyx_t_6); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_t_9, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indices.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_where); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_RichCompare(__pyx_v_n_samples_in_cluster, __pyx_int_0, Py_EQ); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); } } - __pyx_t_9 = 0; - __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; + if (!__pyx_t_1) { + __pyx_t_5 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_GOTREF(__pyx_t_5); + } else { + __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = NULL; + PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_5, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_empty_clusters = __pyx_t_3; + __pyx_t_3 = 0; - /* "sklearn/cluster/_k_means.pyx":255 - * np.ndarray[DOUBLE, ndim=1] X_data = X.data - * np.ndarray[int, ndim=1] X_indices = X.indices - * np.ndarray[int, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< + /* "sklearn/cluster/_k_means.pyx":280 + * # maybe also relocate small clusters? * - * unsigned int i + * if len(empty_clusters): # <<<<<<<<<<<<<< + * # find points to reassign empty clusters to + * far_from_centers = distances.argsort()[::-1] */ - __pyx_t_6 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indptr); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = ((PyArrayObject *)__pyx_t_6); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indptr.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; + __pyx_t_7 = PyObject_Length(__pyx_v_empty_clusters); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = (__pyx_t_7 != 0); + if (__pyx_t_8) { + + /* "sklearn/cluster/_k_means.pyx":282 + * if len(empty_clusters): + * # find points to reassign empty clusters to + * far_from_centers = distances.argsort()[::-1] # <<<<<<<<<<<<<< + * + * for i, cluster_id in enumerate(empty_clusters): + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_distances), __pyx_n_s_argsort); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_5); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_5, function); + } + } + if (__pyx_t_4) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_GetItem(__pyx_t_3, __pyx_slice__2); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_far_from_centers = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; } - __pyx_t_10 = 0; - __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; + __pyx_L3:; - /* "sklearn/cluster/_k_means.pyx":260 - * unsigned int j - * double sum_ - * int with_sqrt = not squared # <<<<<<<<<<<<<< + /* "sklearn/cluster/_k_means.pyx":284 + * far_from_centers = distances.argsort()[::-1] * - * for i in range(n_samples): + * for i, cluster_id in enumerate(empty_clusters): # <<<<<<<<<<<<<< + * # XXX two relocated clusters could be close to each other + * new_center = X[far_from_centers[i]] */ - __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_v_squared); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_with_sqrt = (!__pyx_t_11); + __pyx_t_9 = 0; + if (likely(PyList_CheckExact(__pyx_v_empty_clusters)) || PyTuple_CheckExact(__pyx_v_empty_clusters)) { + __pyx_t_5 = __pyx_v_empty_clusters; __Pyx_INCREF(__pyx_t_5); __pyx_t_7 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_5 = PyObject_GetIter(__pyx_v_empty_clusters); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_10 = Py_TYPE(__pyx_t_5)->tp_iternext; if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_5))) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_5)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_5, __pyx_t_7); __Pyx_INCREF(__pyx_t_3); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_5, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_5)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_5, __pyx_t_7); __Pyx_INCREF(__pyx_t_3); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_5, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } + } else { + __pyx_t_3 = __pyx_t_10(__pyx_t_5); + if (unlikely(!__pyx_t_3)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF_SET(__pyx_v_cluster_id, __pyx_t_3); + __pyx_t_3 = 0; + __pyx_v_i = __pyx_t_9; + __pyx_t_9 = (__pyx_t_9 + 1); + + /* "sklearn/cluster/_k_means.pyx":286 + * for i, cluster_id in enumerate(empty_clusters): + * # XXX two relocated clusters could be close to each other + * new_center = X[far_from_centers[i]] # <<<<<<<<<<<<<< + * centers[cluster_id] = new_center + * n_samples_in_cluster[cluster_id] = 1 + */ + if (unlikely(!__pyx_v_far_from_centers)) { __Pyx_RaiseUnboundLocalError("far_from_centers"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_far_from_centers, __pyx_v_i, int, 1, __Pyx_PyInt_From_int, 0, 0, 0); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_GetItem(((PyObject *)__pyx_v_X), __pyx_t_3); if (unlikely(__pyx_t_4 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_center, __pyx_t_4); + __pyx_t_4 = 0; - /* "sklearn/cluster/_k_means.pyx":262 - * int with_sqrt = not squared - * - * for i in range(n_samples): # <<<<<<<<<<<<<< - * sum_ = 0.0 + /* "sklearn/cluster/_k_means.pyx":287 + * # XXX two relocated clusters could be close to each other + * new_center = X[far_from_centers[i]] + * centers[cluster_id] = new_center # <<<<<<<<<<<<<< + * n_samples_in_cluster[cluster_id] = 1 * */ - __pyx_t_3 = __pyx_v_n_samples; - for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_3; __pyx_t_12+=1) { - __pyx_v_i = __pyx_t_12; + if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_centers), __pyx_v_cluster_id, __pyx_v_new_center) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/cluster/_k_means.pyx":263 + /* "sklearn/cluster/_k_means.pyx":288 + * new_center = X[far_from_centers[i]] + * centers[cluster_id] = new_center + * n_samples_in_cluster[cluster_id] = 1 # <<<<<<<<<<<<<< * * for i in range(n_samples): - * sum_ = 0.0 # <<<<<<<<<<<<<< - * - * for j in range(X_indptr[i], X_indptr[i + 1]): */ - __pyx_v_sum_ = 0.0; + if (unlikely(PyObject_SetItem(__pyx_v_n_samples_in_cluster, __pyx_v_cluster_id, __pyx_int_1) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/cluster/_k_means.pyx":265 - * sum_ = 0.0 - * - * for j in range(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< - * sum_ += X_data[j] * X_data[j] + /* "sklearn/cluster/_k_means.pyx":284 + * far_from_centers = distances.argsort()[::-1] * + * for i, cluster_id in enumerate(empty_clusters): # <<<<<<<<<<<<<< + * # XXX two relocated clusters could be close to each other + * new_center = X[far_from_centers[i]] */ - __pyx_t_13 = (__pyx_v_i + 1); - __pyx_t_14 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_13, __pyx_bstride_0_X_indptr)); - __pyx_t_15 = __pyx_v_i; - for (__pyx_t_16 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_15, __pyx_bstride_0_X_indptr)); __pyx_t_16 < __pyx_t_14; __pyx_t_16+=1) { - __pyx_v_j = __pyx_t_16; + } + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - /* "sklearn/cluster/_k_means.pyx":266 - * - * for j in range(X_indptr[i], X_indptr[i + 1]): - * sum_ += X_data[j] * X_data[j] # <<<<<<<<<<<<<< + /* "sklearn/cluster/_k_means.pyx":290 + * n_samples_in_cluster[cluster_id] = 1 * - * if with_sqrt: + * for i in range(n_samples): # <<<<<<<<<<<<<< + * for j in range(n_features): + * centers[labels[i], j] += X[i, j] */ - __pyx_t_17 = __pyx_v_j; - __pyx_t_18 = __pyx_v_j; - __pyx_v_sum_ = (__pyx_v_sum_ + ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_17, __pyx_bstride_0_X_data)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_18, __pyx_bstride_0_X_data)))); - } + __pyx_t_9 = __pyx_v_n_samples; + for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { + __pyx_v_i = __pyx_t_11; - /* "sklearn/cluster/_k_means.pyx":268 - * sum_ += X_data[j] * X_data[j] + /* "sklearn/cluster/_k_means.pyx":291 * - * if with_sqrt: # <<<<<<<<<<<<<< - * sum_ = sqrt(sum_) + * for i in range(n_samples): + * for j in range(n_features): # <<<<<<<<<<<<<< + * centers[labels[i], j] += X[i, j] * */ - if (__pyx_v_with_sqrt) { + __pyx_t_12 = __pyx_v_n_features; + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_j = __pyx_t_13; - /* "sklearn/cluster/_k_means.pyx":269 - * - * if with_sqrt: - * sum_ = sqrt(sum_) # <<<<<<<<<<<<<< + /* "sklearn/cluster/_k_means.pyx":292 + * for i in range(n_samples): + * for j in range(n_features): + * centers[labels[i], j] += X[i, j] # <<<<<<<<<<<<<< * - * norms[i] = sum_ + * centers /= n_samples_in_cluster[:, np.newaxis] */ - __pyx_v_sum_ = sqrt(__pyx_v_sum_); - goto __pyx_L10; + __pyx_t_14 = __pyx_v_i; + __pyx_t_15 = __pyx_v_j; + __pyx_t_16 = __pyx_v_i; + __pyx_t_17 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_pybuffernd_labels.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_labels.diminfo[0].strides)); + __pyx_t_18 = __pyx_v_j; + *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_centers.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_centers.diminfo[0].strides, __pyx_t_18, __pyx_pybuffernd_centers.diminfo[1].strides) += (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_pybuffernd_X.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_X.diminfo[0].strides, __pyx_t_15, __pyx_pybuffernd_X.diminfo[1].strides)); } - __pyx_L10:; + } - /* "sklearn/cluster/_k_means.pyx":271 - * sum_ = sqrt(sum_) + /* "sklearn/cluster/_k_means.pyx":294 + * centers[labels[i], j] += X[i, j] * - * norms[i] = sum_ # <<<<<<<<<<<<<< - * return norms + * centers /= n_samples_in_cluster[:, np.newaxis] # <<<<<<<<<<<<<< + * + * return centers */ - __pyx_t_16 = __pyx_v_i; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_DOUBLE *, __pyx_bstruct_norms.buf, __pyx_t_16, __pyx_bstride_0_norms) = __pyx_v_sum_; + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_newaxis); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_slice__3); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_slice__3); + __Pyx_GIVEREF(__pyx_slice__3); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_GetItem(__pyx_v_n_samples_in_cluster, __pyx_t_5); if (unlikely(__pyx_t_4 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyNumber_InPlaceDivide(((PyObject *)__pyx_v_centers), __pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_centers.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_9 < 0)) { + PyErr_Fetch(&__pyx_t_19, &__pyx_t_20, &__pyx_t_21); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_centers.rcbuffer->pybuffer, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_19); Py_XDECREF(__pyx_t_20); Py_XDECREF(__pyx_t_21); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_19, __pyx_t_20, __pyx_t_21); + } + } + __pyx_pybuffernd_centers.diminfo[0].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_centers.diminfo[0].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_centers.diminfo[1].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_centers.diminfo[1].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[1]; + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_6 = 0; + __Pyx_DECREF_SET(__pyx_v_centers, ((PyArrayObject *)__pyx_t_5)); + __pyx_t_5 = 0; - /* "sklearn/cluster/_k_means.pyx":272 + /* "sklearn/cluster/_k_means.pyx":296 + * centers /= n_samples_in_cluster[:, np.newaxis] + * + * return centers # <<<<<<<<<<<<<< + * * - * norms[i] = sum_ - * return norms # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_norms)); - __pyx_r = ((PyObject *)__pyx_v_norms); + __Pyx_INCREF(((PyObject *)__pyx_v_centers)); + __pyx_r = ((PyObject *)__pyx_v_centers); goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/cluster/_k_means.pyx":245 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _centers_dense(np.ndarray[DOUBLE, ndim=2] X, # <<<<<<<<<<<<<< + * np.ndarray[INT, ndim=1] labels, int n_clusters, + * np.ndarray[DOUBLE, ndim=1] distances): + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_norms); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.cluster._k_means.csr_row_norm_l2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.cluster._k_means._centers_dense", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_norms); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_norms); - __Pyx_XDECREF((PyObject *)__pyx_v_X_data); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indptr); + __Pyx_XDECREF((PyObject *)__pyx_v_centers); + __Pyx_XDECREF(__pyx_v_n_samples_in_cluster); + __Pyx_XDECREF(__pyx_v_empty_clusters); + __Pyx_XDECREF(__pyx_v_far_from_centers); + __Pyx_XDECREF(__pyx_v_cluster_id); + __Pyx_XDECREF(__pyx_v_new_center); __Pyx_XGIVEREF(__pyx_r); __Pyx_TraceReturn(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":190 - * # experimental exception made for __getbuffer__ and __releasebuffer__ - * # -- the details of this may change. - * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< - * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP. +/* "sklearn/cluster/_k_means.pyx":299 + * + * + * def _centers_sparse(X, np.ndarray[INT, ndim=1] labels, n_clusters, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=1] distances): + * """M step of the K-means EM algorithm */ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_v_copy_shape; - int __pyx_v_i; - int __pyx_v_ndim; - int __pyx_v_endian_detector; - int __pyx_v_little_endian; - int __pyx_v_t; - char *__pyx_v_f; - PyArray_Descr *__pyx_v_descr = 0; - int __pyx_v_offset; - int __pyx_v_hasfields; - int __pyx_r; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_9_centers_sparse(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7cluster_8_k_means_8_centers_sparse[] = "M step of the K-means EM algorithm\n\n Computation of cluster centers / means.\n\n Parameters\n ----------\n X: scipy.sparse.csr_matrix, shape (n_samples, n_features)\n\n labels: array of integers, shape (n_samples)\n Current label assignment\n\n n_clusters: int\n Number of desired clusters\n\n distances: array-like, shape (n_samples)\n Distance to closest cluster for each sample.\n\n Returns\n -------\n centers: array, shape (n_clusters, n_features)\n The resulting centers\n "; +static PyMethodDef __pyx_mdef_7sklearn_7cluster_8_k_means_9_centers_sparse = {"_centers_sparse", (PyCFunction)__pyx_pw_7sklearn_7cluster_8_k_means_9_centers_sparse, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_7cluster_8_k_means_8_centers_sparse}; +static PyObject *__pyx_pw_7sklearn_7cluster_8_k_means_9_centers_sparse(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_X = 0; + PyArrayObject *__pyx_v_labels = 0; + PyObject *__pyx_v_n_clusters = 0; + PyArrayObject *__pyx_v_distances = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; + __Pyx_RefNannySetupContext("_centers_sparse (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_labels,&__pyx_n_s_n_clusters,&__pyx_n_s_distances,0}; + PyObject* values[4] = {0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_labels)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_centers_sparse", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_clusters)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_centers_sparse", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_distances)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_centers_sparse", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_centers_sparse") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + } + __pyx_v_X = values[0]; + __pyx_v_labels = ((PyArrayObject *)values[1]); + __pyx_v_n_clusters = values[2]; + __pyx_v_distances = ((PyArrayObject *)values[3]); + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_centers_sparse", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.cluster._k_means._centers_sparse", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_labels), __pyx_ptype_5numpy_ndarray, 1, "labels", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_distances), __pyx_ptype_5numpy_ndarray, 1, "distances", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_7cluster_8_k_means_8_centers_sparse(__pyx_self, __pyx_v_X, __pyx_v_labels, __pyx_v_n_clusters, __pyx_v_distances); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_7cluster_8_k_means_8_centers_sparse(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_labels, PyObject *__pyx_v_n_clusters, PyArrayObject *__pyx_v_distances) { + PyObject *__pyx_v_n_features = NULL; + npy_intp __pyx_v_cluster_id; + PyArrayObject *__pyx_v_data = 0; + PyArrayObject *__pyx_v_indices = 0; + PyArrayObject *__pyx_v_indptr = 0; + PyArrayObject *__pyx_v_centers = 0; + PyArrayObject *__pyx_v_far_from_centers = 0; + PyArrayObject *__pyx_v_n_samples_in_cluster = 0; + PyArrayObject *__pyx_v_empty_clusters = 0; + npy_intp __pyx_v_i; + __Pyx_LocalBuf_ND __pyx_pybuffernd_centers; + __Pyx_Buffer __pyx_pybuffer_centers; + __Pyx_LocalBuf_ND __pyx_pybuffernd_data; + __Pyx_Buffer __pyx_pybuffer_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_distances; + __Pyx_Buffer __pyx_pybuffer_distances; + __Pyx_LocalBuf_ND __pyx_pybuffernd_empty_clusters; + __Pyx_Buffer __pyx_pybuffer_empty_clusters; + __Pyx_LocalBuf_ND __pyx_pybuffernd_far_from_centers; + __Pyx_Buffer __pyx_pybuffer_far_from_centers; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices; + __Pyx_Buffer __pyx_pybuffer_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr; + __Pyx_Buffer __pyx_pybuffer_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_labels; + __Pyx_Buffer __pyx_pybuffer_labels; + __Pyx_LocalBuf_ND __pyx_pybuffernd_n_samples_in_cluster; + __Pyx_Buffer __pyx_pybuffer_n_samples_in_cluster; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyArrayObject *__pyx_t_3 = NULL; + PyArrayObject *__pyx_t_4 = NULL; + PyArrayObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; - char *__pyx_t_9; + PyArrayObject *__pyx_t_9 = NULL; + PyArrayObject *__pyx_t_10 = NULL; + PyArrayObject *__pyx_t_11 = NULL; + int __pyx_t_12; + PyArrayObject *__pyx_t_13 = NULL; + int __pyx_t_14; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + PyObject *__pyx_t_17 = NULL; + npy_intp __pyx_t_18; + npy_intp __pyx_t_19; + npy_intp __pyx_t_20; + npy_intp __pyx_t_21; + npy_intp __pyx_t_22; + npy_intp __pyx_t_23; + __pyx_t_7sklearn_7cluster_8_k_means_INT __pyx_t_24; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("__getbuffer__"); - if (__pyx_v_info != NULL) { - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); + __Pyx_RefNannySetupContext("_centers_sparse", 0); + __Pyx_TraceCall("_centers_sparse", __pyx_f[0], 299); + __pyx_pybuffer_data.pybuffer.buf = NULL; + __pyx_pybuffer_data.refcount = 0; + __pyx_pybuffernd_data.data = NULL; + __pyx_pybuffernd_data.rcbuffer = &__pyx_pybuffer_data; + __pyx_pybuffer_indices.pybuffer.buf = NULL; + __pyx_pybuffer_indices.refcount = 0; + __pyx_pybuffernd_indices.data = NULL; + __pyx_pybuffernd_indices.rcbuffer = &__pyx_pybuffer_indices; + __pyx_pybuffer_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_indptr.refcount = 0; + __pyx_pybuffernd_indptr.data = NULL; + __pyx_pybuffernd_indptr.rcbuffer = &__pyx_pybuffer_indptr; + __pyx_pybuffer_centers.pybuffer.buf = NULL; + __pyx_pybuffer_centers.refcount = 0; + __pyx_pybuffernd_centers.data = NULL; + __pyx_pybuffernd_centers.rcbuffer = &__pyx_pybuffer_centers; + __pyx_pybuffer_far_from_centers.pybuffer.buf = NULL; + __pyx_pybuffer_far_from_centers.refcount = 0; + __pyx_pybuffernd_far_from_centers.data = NULL; + __pyx_pybuffernd_far_from_centers.rcbuffer = &__pyx_pybuffer_far_from_centers; + __pyx_pybuffer_n_samples_in_cluster.pybuffer.buf = NULL; + __pyx_pybuffer_n_samples_in_cluster.refcount = 0; + __pyx_pybuffernd_n_samples_in_cluster.data = NULL; + __pyx_pybuffernd_n_samples_in_cluster.rcbuffer = &__pyx_pybuffer_n_samples_in_cluster; + __pyx_pybuffer_empty_clusters.pybuffer.buf = NULL; + __pyx_pybuffer_empty_clusters.refcount = 0; + __pyx_pybuffernd_empty_clusters.data = NULL; + __pyx_pybuffernd_empty_clusters.rcbuffer = &__pyx_pybuffer_empty_clusters; + __pyx_pybuffer_labels.pybuffer.buf = NULL; + __pyx_pybuffer_labels.refcount = 0; + __pyx_pybuffernd_labels.data = NULL; + __pyx_pybuffernd_labels.rcbuffer = &__pyx_pybuffer_labels; + __pyx_pybuffer_distances.pybuffer.buf = NULL; + __pyx_pybuffer_distances.refcount = 0; + __pyx_pybuffernd_distances.data = NULL; + __pyx_pybuffernd_distances.rcbuffer = &__pyx_pybuffer_distances; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __Pyx_TraceCall("__getbuffer__", __pyx_f[1], 190); - - /* "numpy.pxd":196 - * # of flags - * - * if info == NULL: return # <<<<<<<<<<<<<< - * - * cdef int copy_shape, i, ndim - */ - __pyx_t_1 = (__pyx_v_info == NULL); - if (__pyx_t_1) { - __pyx_r = 0; - goto __pyx_L0; - goto __pyx_L5; + __pyx_pybuffernd_labels.diminfo[0].strides = __pyx_pybuffernd_labels.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_labels.diminfo[0].shape = __pyx_pybuffernd_labels.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_distances.rcbuffer->pybuffer, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L5:; + __pyx_pybuffernd_distances.diminfo[0].strides = __pyx_pybuffernd_distances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_distances.diminfo[0].shape = __pyx_pybuffernd_distances.rcbuffer->pybuffer.shape[0]; - /* "numpy.pxd":199 - * - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) + /* "sklearn/cluster/_k_means.pyx":323 + * The resulting centers + * """ + * n_features = X.shape[1] # <<<<<<<<<<<<<< * + * cdef np.npy_intp cluster_id */ - __pyx_v_endian_detector = 1; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_n_features = __pyx_t_2; + __pyx_t_2 = 0; - /* "numpy.pxd":200 - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + /* "sklearn/cluster/_k_means.pyx":327 + * cdef np.npy_intp cluster_id * - * ndim = PyArray_NDIM(self) + * cdef np.ndarray[DOUBLE, ndim=1] data = X.data # <<<<<<<<<<<<<< + * cdef np.ndarray[int, ndim=1] indices = X.indices + * cdef np.ndarray[int, ndim=1] indptr = X.indptr */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyArrayObject *)__pyx_t_2); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_data.rcbuffer->pybuffer, (PyObject*)__pyx_t_3, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_data.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_data.diminfo[0].strides = __pyx_pybuffernd_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_data.diminfo[0].shape = __pyx_pybuffernd_data.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_3 = 0; + __pyx_v_data = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; - /* "numpy.pxd":202 - * cdef bint little_endian = ((&endian_detector)[0] != 0) + /* "sklearn/cluster/_k_means.pyx":328 * - * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * cdef np.ndarray[DOUBLE, ndim=1] data = X.data + * cdef np.ndarray[int, ndim=1] indices = X.indices # <<<<<<<<<<<<<< + * cdef np.ndarray[int, ndim=1] indptr = X.indptr * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = ((PyArrayObject *)__pyx_t_2); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices.rcbuffer->pybuffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_indices.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_indices.diminfo[0].strides = __pyx_pybuffernd_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices.diminfo[0].shape = __pyx_pybuffernd_indices.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_4 = 0; + __pyx_v_indices = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; - /* "numpy.pxd":204 - * ndim = PyArray_NDIM(self) + /* "sklearn/cluster/_k_means.pyx":329 + * cdef np.ndarray[DOUBLE, ndim=1] data = X.data + * cdef np.ndarray[int, ndim=1] indices = X.indices + * cdef np.ndarray[int, ndim=1] indptr = X.indptr # <<<<<<<<<<<<<< * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * copy_shape = 1 - * else: + * cdef np.ndarray[DOUBLE, ndim=2, mode="c"] centers = \ */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); - if (__pyx_t_1) { + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = ((PyArrayObject *)__pyx_t_2); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_indptr.diminfo[0].strides = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr.diminfo[0].shape = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_5 = 0; + __pyx_v_indptr = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; - /* "numpy.pxd":205 + /* "sklearn/cluster/_k_means.pyx":332 * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * cdef np.ndarray[DOUBLE, ndim=2, mode="c"] centers = \ + * np.zeros((n_clusters, n_features)) # <<<<<<<<<<<<<< + * cdef np.ndarray[np.npy_intp, ndim=1] far_from_centers + * cdef np.ndarray[np.npy_intp, ndim=1, mode="c"] n_samples_in_cluster = \ + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 332; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 332; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 332; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_n_clusters); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_n_clusters); + __Pyx_GIVEREF(__pyx_v_n_clusters); + __Pyx_INCREF(__pyx_v_n_features); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_n_features); + __Pyx_GIVEREF(__pyx_v_n_features); + __pyx_t_7 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_6); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_6, function); + } + } + if (!__pyx_t_7) { + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_6, __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 332; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_GOTREF(__pyx_t_2); + } else { + __pyx_t_8 = PyTuple_New(1+1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 332; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); __pyx_t_7 = NULL; + PyTuple_SET_ITEM(__pyx_t_8, 0+1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 332; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 332; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = ((PyArrayObject *)__pyx_t_2); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_centers.rcbuffer->pybuffer, (PyObject*)__pyx_t_9, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { + __pyx_v_centers = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_centers.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_centers.diminfo[0].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_centers.diminfo[0].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_centers.diminfo[1].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_centers.diminfo[1].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[1]; + } + } + __pyx_t_9 = 0; + __pyx_v_centers = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/cluster/_k_means.pyx":335 + * cdef np.ndarray[np.npy_intp, ndim=1] far_from_centers + * cdef np.ndarray[np.npy_intp, ndim=1, mode="c"] n_samples_in_cluster = \ + * bincount(labels, minlength=n_clusters) # <<<<<<<<<<<<<< + * cdef np.ndarray[np.npy_intp, ndim=1, mode="c"] empty_clusters = \ + * np.where(n_samples_in_cluster == 0)[0] + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_bincount); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_INCREF(((PyObject *)__pyx_v_labels)); + PyTuple_SET_ITEM(__pyx_t_6, 0, ((PyObject *)__pyx_v_labels)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_labels)); + __pyx_t_8 = PyDict_New(); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_t_8, __pyx_n_s_minlength, __pyx_v_n_clusters) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_6, __pyx_t_8); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_n_samples_in_cluster.rcbuffer->pybuffer, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn_npy_intp, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_n_samples_in_cluster = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_n_samples_in_cluster.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_n_samples_in_cluster.diminfo[0].strides = __pyx_pybuffernd_n_samples_in_cluster.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_n_samples_in_cluster.diminfo[0].shape = __pyx_pybuffernd_n_samples_in_cluster.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_10 = 0; + __pyx_v_n_samples_in_cluster = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/cluster/_k_means.pyx":337 + * bincount(labels, minlength=n_clusters) + * cdef np.ndarray[np.npy_intp, ndim=1, mode="c"] empty_clusters = \ + * np.where(n_samples_in_cluster == 0)[0] # <<<<<<<<<<<<<< + * + * # maybe also relocate small clusters? + */ + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_where); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyObject_RichCompare(((PyObject *)__pyx_v_n_samples_in_cluster), __pyx_int_0, Py_EQ); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_6); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_6, function); + } + } + if (!__pyx_t_2) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_6, __pyx_t_8); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_7 = PyTuple_New(1+1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = NULL; + PyTuple_SET_ITEM(__pyx_t_7, 0+1, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = ((PyArrayObject *)__pyx_t_6); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_empty_clusters.rcbuffer->pybuffer, (PyObject*)__pyx_t_11, &__Pyx_TypeInfo_nn_npy_intp, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_empty_clusters = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_empty_clusters.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 336; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_empty_clusters.diminfo[0].strides = __pyx_pybuffernd_empty_clusters.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_empty_clusters.diminfo[0].shape = __pyx_pybuffernd_empty_clusters.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_11 = 0; + __pyx_v_empty_clusters = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; + + /* "sklearn/cluster/_k_means.pyx":341 + * # maybe also relocate small clusters? + * + * if empty_clusters.shape[0] > 0: # <<<<<<<<<<<<<< + * # find points to reassign empty clusters to + * far_from_centers = distances.argsort()[::-1] + */ + __pyx_t_12 = (((__pyx_v_empty_clusters->dimensions[0]) > 0) != 0); + if (__pyx_t_12) { + + /* "sklearn/cluster/_k_means.pyx":343 + * if empty_clusters.shape[0] > 0: + * # find points to reassign empty clusters to + * far_from_centers = distances.argsort()[::-1] # <<<<<<<<<<<<<< + * + * for i in range(empty_clusters.shape[0]): + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_distances), __pyx_n_s_argsort); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_1); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_1, function); + } + } + if (__pyx_t_7) { + __pyx_t_6 = __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_7); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + } else { + __pyx_t_6 = __Pyx_PyObject_CallNoArg(__pyx_t_1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetItem(__pyx_t_6, __pyx_slice__4); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_far_from_centers.rcbuffer->pybuffer); + __pyx_t_14 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_far_from_centers.rcbuffer->pybuffer, (PyObject*)__pyx_t_13, &__Pyx_TypeInfo_nn_npy_intp, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_14 < 0)) { + PyErr_Fetch(&__pyx_t_15, &__pyx_t_16, &__pyx_t_17); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_far_from_centers.rcbuffer->pybuffer, (PyObject*)__pyx_v_far_from_centers, &__Pyx_TypeInfo_nn_npy_intp, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_15); Py_XDECREF(__pyx_t_16); Py_XDECREF(__pyx_t_17); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_15, __pyx_t_16, __pyx_t_17); + } + } + __pyx_pybuffernd_far_from_centers.diminfo[0].strides = __pyx_pybuffernd_far_from_centers.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_far_from_centers.diminfo[0].shape = __pyx_pybuffernd_far_from_centers.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_14 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_13 = 0; + __pyx_v_far_from_centers = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/cluster/_k_means.pyx":345 + * far_from_centers = distances.argsort()[::-1] + * + * for i in range(empty_clusters.shape[0]): # <<<<<<<<<<<<<< + * cluster_id = empty_clusters[i] + * + */ + __pyx_t_18 = (__pyx_v_empty_clusters->dimensions[0]); + for (__pyx_t_19 = 0; __pyx_t_19 < __pyx_t_18; __pyx_t_19+=1) { + __pyx_v_i = __pyx_t_19; + + /* "sklearn/cluster/_k_means.pyx":346 + * + * for i in range(empty_clusters.shape[0]): + * cluster_id = empty_clusters[i] # <<<<<<<<<<<<<< + * + * # XXX two relocated clusters could be close to each other + */ + __pyx_t_20 = __pyx_v_i; + __pyx_t_14 = -1; + if (__pyx_t_20 < 0) { + __pyx_t_20 += __pyx_pybuffernd_empty_clusters.diminfo[0].shape; + if (unlikely(__pyx_t_20 < 0)) __pyx_t_14 = 0; + } else if (unlikely(__pyx_t_20 >= __pyx_pybuffernd_empty_clusters.diminfo[0].shape)) __pyx_t_14 = 0; + if (unlikely(__pyx_t_14 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_14); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 346; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_cluster_id = (*__Pyx_BufPtrCContig1d(npy_intp *, __pyx_pybuffernd_empty_clusters.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_empty_clusters.diminfo[0].strides)); + + /* "sklearn/cluster/_k_means.pyx":349 + * + * # XXX two relocated clusters could be close to each other + * centers[cluster_id] = 0. # <<<<<<<<<<<<<< + * add_row_csr(data, indices, indptr, far_from_centers[i], + * centers[cluster_id]) + */ + if (unlikely(__Pyx_SetItemInt(((PyObject *)__pyx_v_centers), __pyx_v_cluster_id, __pyx_float_0_, npy_intp, 1, __Pyx_PyInt_From_Py_intptr_t, 0, 1, 1) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/cluster/_k_means.pyx":350 + * # XXX two relocated clusters could be close to each other + * centers[cluster_id] = 0. + * add_row_csr(data, indices, indptr, far_from_centers[i], # <<<<<<<<<<<<<< + * centers[cluster_id]) + * n_samples_in_cluster[cluster_id] = 1 + */ + __pyx_t_21 = __pyx_v_i; + __pyx_t_14 = -1; + if (__pyx_t_21 < 0) { + __pyx_t_21 += __pyx_pybuffernd_far_from_centers.diminfo[0].shape; + if (unlikely(__pyx_t_21 < 0)) __pyx_t_14 = 0; + } else if (unlikely(__pyx_t_21 >= __pyx_pybuffernd_far_from_centers.diminfo[0].shape)) __pyx_t_14 = 0; + if (unlikely(__pyx_t_14 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_14); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/cluster/_k_means.pyx":351 + * centers[cluster_id] = 0. + * add_row_csr(data, indices, indptr, far_from_centers[i], + * centers[cluster_id]) # <<<<<<<<<<<<<< + * n_samples_in_cluster[cluster_id] = 1 + * + */ + __pyx_t_1 = __Pyx_GetItemInt(((PyObject *)__pyx_v_centers), __pyx_v_cluster_id, npy_intp, 1, __Pyx_PyInt_From_Py_intptr_t, 0, 1, 1); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/cluster/_k_means.pyx":350 + * # XXX two relocated clusters could be close to each other + * centers[cluster_id] = 0. + * add_row_csr(data, indices, indptr, far_from_centers[i], # <<<<<<<<<<<<<< + * centers[cluster_id]) + * n_samples_in_cluster[cluster_id] = 1 + */ + __pyx_f_7sklearn_5utils_16sparsefuncs_fast_add_row_csr(((PyArrayObject *)__pyx_v_data), ((PyArrayObject *)__pyx_v_indices), ((PyArrayObject *)__pyx_v_indptr), (*__Pyx_BufPtrStrided1d(npy_intp *, __pyx_pybuffernd_far_from_centers.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_far_from_centers.diminfo[0].strides)), ((PyArrayObject *)__pyx_t_1)); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/cluster/_k_means.pyx":352 + * add_row_csr(data, indices, indptr, far_from_centers[i], + * centers[cluster_id]) + * n_samples_in_cluster[cluster_id] = 1 # <<<<<<<<<<<<<< + * + * for i in range(labels.shape[0]): + */ + __pyx_t_22 = __pyx_v_cluster_id; + __pyx_t_14 = -1; + if (__pyx_t_22 < 0) { + __pyx_t_22 += __pyx_pybuffernd_n_samples_in_cluster.diminfo[0].shape; + if (unlikely(__pyx_t_22 < 0)) __pyx_t_14 = 0; + } else if (unlikely(__pyx_t_22 >= __pyx_pybuffernd_n_samples_in_cluster.diminfo[0].shape)) __pyx_t_14 = 0; + if (unlikely(__pyx_t_14 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_14); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(npy_intp *, __pyx_pybuffernd_n_samples_in_cluster.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_n_samples_in_cluster.diminfo[0].strides) = 1; + } + + /* "sklearn/cluster/_k_means.pyx":354 + * n_samples_in_cluster[cluster_id] = 1 + * + * for i in range(labels.shape[0]): # <<<<<<<<<<<<<< + * add_row_csr(data, indices, indptr, i, centers[labels[i]]) + * + */ + __pyx_t_18 = (__pyx_v_labels->dimensions[0]); + for (__pyx_t_19 = 0; __pyx_t_19 < __pyx_t_18; __pyx_t_19+=1) { + __pyx_v_i = __pyx_t_19; + + /* "sklearn/cluster/_k_means.pyx":355 + * + * for i in range(labels.shape[0]): + * add_row_csr(data, indices, indptr, i, centers[labels[i]]) # <<<<<<<<<<<<<< + * + * centers /= n_samples_in_cluster[:, np.newaxis] + */ + __pyx_t_23 = __pyx_v_i; + __pyx_t_14 = -1; + if (__pyx_t_23 < 0) { + __pyx_t_23 += __pyx_pybuffernd_labels.diminfo[0].shape; + if (unlikely(__pyx_t_23 < 0)) __pyx_t_14 = 0; + } else if (unlikely(__pyx_t_23 >= __pyx_pybuffernd_labels.diminfo[0].shape)) __pyx_t_14 = 0; + if (unlikely(__pyx_t_14 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_14); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_24 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_8_k_means_INT *, __pyx_pybuffernd_labels.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_labels.diminfo[0].strides)); + __pyx_t_1 = __Pyx_GetItemInt(((PyObject *)__pyx_v_centers), __pyx_t_24, __pyx_t_7sklearn_7cluster_8_k_means_INT, 1, __Pyx_PyInt_From_npy_int32, 0, 1, 1); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_f_7sklearn_5utils_16sparsefuncs_fast_add_row_csr(((PyArrayObject *)__pyx_v_data), ((PyArrayObject *)__pyx_v_indices), ((PyArrayObject *)__pyx_v_indptr), __pyx_v_i, ((PyArrayObject *)__pyx_t_1)); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "sklearn/cluster/_k_means.pyx":357 + * add_row_csr(data, indices, indptr, i, centers[labels[i]]) + * + * centers /= n_samples_in_cluster[:, np.newaxis] # <<<<<<<<<<<<<< + * + * return centers + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_newaxis); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_slice__5); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_slice__5); + __Pyx_GIVEREF(__pyx_slice__5); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyObject_GetItem(((PyObject *)__pyx_v_n_samples_in_cluster), __pyx_t_1); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyNumber_InPlaceDivide(((PyObject *)__pyx_v_centers), __pyx_t_6); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __pyx_t_14 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_centers.rcbuffer->pybuffer, (PyObject*)__pyx_t_9, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_14 < 0)) { + PyErr_Fetch(&__pyx_t_17, &__pyx_t_16, &__pyx_t_15); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_centers.rcbuffer->pybuffer, (PyObject*)__pyx_v_centers, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_8_k_means_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_17); Py_XDECREF(__pyx_t_16); Py_XDECREF(__pyx_t_15); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_17, __pyx_t_16, __pyx_t_15); + } + } + __pyx_pybuffernd_centers.diminfo[0].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_centers.diminfo[0].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_centers.diminfo[1].strides = __pyx_pybuffernd_centers.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_centers.diminfo[1].shape = __pyx_pybuffernd_centers.rcbuffer->pybuffer.shape[1]; + if (unlikely(__pyx_t_14 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_9 = 0; + __Pyx_DECREF_SET(__pyx_v_centers, ((PyArrayObject *)__pyx_t_1)); + __pyx_t_1 = 0; + + /* "sklearn/cluster/_k_means.pyx":359 + * centers /= n_samples_in_cluster[:, np.newaxis] + * + * return centers # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_centers)); + __pyx_r = ((PyObject *)__pyx_v_centers); + goto __pyx_L0; + + /* "sklearn/cluster/_k_means.pyx":299 + * + * + * def _centers_sparse(X, np.ndarray[INT, ndim=1] labels, n_clusters, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=1] distances): + * """M step of the K-means EM algorithm + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_empty_clusters.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_far_from_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_n_samples_in_cluster.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.cluster._k_means._centers_sparse", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_empty_clusters.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_far_from_centers.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_n_samples_in_cluster.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF(__pyx_v_n_features); + __Pyx_XDECREF((PyObject *)__pyx_v_data); + __Pyx_XDECREF((PyObject *)__pyx_v_indices); + __Pyx_XDECREF((PyObject *)__pyx_v_indptr); + __Pyx_XDECREF((PyObject *)__pyx_v_centers); + __Pyx_XDECREF((PyObject *)__pyx_v_far_from_centers); + __Pyx_XDECREF((PyObject *)__pyx_v_n_samples_in_cluster); + __Pyx_XDECREF((PyObject *)__pyx_v_empty_clusters); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_TraceReturn(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceDeclarations + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + __Pyx_TraceCall("__getbuffer__", __pyx_f[1], 194); + + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + } + + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< * else: * copy_shape = 0 */ __pyx_v_copy_shape = 1; - goto __pyx_L6; + goto __pyx_L4; } /*else*/ { - /* "numpy.pxd":207 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -3817,98 +5125,98 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_copy_shape = 0; } - __pyx_L6:; + __pyx_L4:; - /* "numpy.pxd":209 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); - if (__pyx_t_1) { + __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L6_bool_binop_done; + } - /* "numpy.pxd":210 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); - __pyx_t_3 = __pyx_t_2; - } else { - __pyx_t_3 = __pyx_t_1; - } - if (__pyx_t_3) { + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L6_bool_binop_done:; + if (__pyx_t_1) { - /* "numpy.pxd":211 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L7:; - /* "numpy.pxd":213 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); - if (__pyx_t_3) { + __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L9_bool_binop_done; + } - /* "numpy.pxd":214 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); - __pyx_t_2 = __pyx_t_1; - } else { - __pyx_t_2 = __pyx_t_3; - } - if (__pyx_t_2) { + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L9_bool_binop_done:; + if (__pyx_t_1) { - /* "numpy.pxd":215 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L8:; - /* "numpy.pxd":217 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":218 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -3917,16 +5225,17 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":219 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ - if (__pyx_v_copy_shape) { + __pyx_t_1 = (__pyx_v_copy_shape != 0); + if (__pyx_t_1) { - /* "numpy.pxd":222 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -3935,7 +5244,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":223 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -3944,60 +5253,60 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":224 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] */ - __pyx_t_5 = __pyx_v_ndim; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; + __pyx_t_4 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; - /* "numpy.pxd":225 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":226 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } - goto __pyx_L9; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":228 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":229 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } - __pyx_L9:; + __pyx_L11:; - /* "numpy.pxd":230 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -4006,25 +5315,25 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":231 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":232 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - /* "numpy.pxd":235 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -4033,17 +5342,19 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_f = NULL; - /* "numpy.pxd":236 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; - /* "numpy.pxd":240 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -4052,23 +5363,25 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":242 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); - __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; + goto __pyx_L15_bool_binop_done; } + __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L15_bool_binop_done:; if (__pyx_t_1) { - /* "numpy.pxd":244 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -4080,344 +5393,321 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; - goto __pyx_L12; + goto __pyx_L14; } /*else*/ { - /* "numpy.pxd":247 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } - __pyx_L12:; + __pyx_L14:; - /* "numpy.pxd":249 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { - /* "numpy.pxd":250 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_4 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_4; - /* "numpy.pxd":251 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); - if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; + __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); + if (!__pyx_t_2) { + goto __pyx_L20_next_or; } else { - __pyx_t_2 = __pyx_t_1; } + __pyx_t_2 = (__pyx_v_little_endian != 0); if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_L20_next_or:; - /* "numpy.pxd":252 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); - if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); - __pyx_t_7 = __pyx_t_3; - } else { - __pyx_t_7 = __pyx_t_1; - } - __pyx_t_1 = __pyx_t_7; + __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; } + __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L19_bool_binop_done:; if (__pyx_t_1) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L14:; - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__b; - goto __pyx_L15; - } + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; - /* "numpy.pxd":255 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__B; - goto __pyx_L15; - } + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; - /* "numpy.pxd":256 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__h; - goto __pyx_L15; - } + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; - /* "numpy.pxd":257 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__H; - goto __pyx_L15; - } + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; - /* "numpy.pxd":258 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__i; - goto __pyx_L15; - } + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; - /* "numpy.pxd":259 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__I; - goto __pyx_L15; - } + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; - /* "numpy.pxd":260 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__l; - goto __pyx_L15; - } + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; - /* "numpy.pxd":261 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__L; - goto __pyx_L15; - } + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; - /* "numpy.pxd":262 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__q; - goto __pyx_L15; - } + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; - /* "numpy.pxd":263 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; - } + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; - /* "numpy.pxd":264 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__f; - goto __pyx_L15; - } + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; - /* "numpy.pxd":265 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__d; - goto __pyx_L15; - } + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; - /* "numpy.pxd":266 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__g; - goto __pyx_L15; - } + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; - /* "numpy.pxd":267 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; - } + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; - /* "numpy.pxd":268 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; - } + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; - /* "numpy.pxd":269 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; - } + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; - /* "numpy.pxd":270 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L15; - } - /*else*/ { + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: - /* "numpy.pxd":272 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_9), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); - __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L15:; - /* "numpy.pxd":273 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -4426,7 +5716,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":274 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -4435,63 +5725,70 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":276 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":277 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":278 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":281 - * f = _util_dtypestring(descr, info.format + 1, + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, - * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string - * + * &offset) */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_9; + __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_7; - /* "numpy.pxd":282 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L13:; + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { @@ -4511,33 +5808,43 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ return __pyx_r; } -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("__releasebuffer__"); - __Pyx_TraceCall("__releasebuffer__", __pyx_f[1], 284); + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + __Pyx_TraceCall("__releasebuffer__", __pyx_f[1], 288); - /* "numpy.pxd":285 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { - /* "numpy.pxd":286 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -4545,21 +5852,21 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * stdlib.free(info.strides) */ free(__pyx_v_info->format); - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":287 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":288 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -4567,15 +5874,24 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * */ free(__pyx_v_info->strides); - goto __pyx_L6; + goto __pyx_L4; } - __pyx_L6:; + __pyx_L4:; + + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + /* function exit code */ __Pyx_TraceReturn(Py_None); __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":764 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -4591,10 +5907,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); - __Pyx_TraceCall("PyArray_MultiIterNew1", __pyx_f[1], 764); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + __Pyx_TraceCall("PyArray_MultiIterNew1", __pyx_f[1], 768); - /* "numpy.pxd":765 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -4602,14 +5918,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -4621,7 +5944,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":767 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -4637,10 +5960,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); - __Pyx_TraceCall("PyArray_MultiIterNew2", __pyx_f[1], 767); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + __Pyx_TraceCall("PyArray_MultiIterNew2", __pyx_f[1], 771); - /* "numpy.pxd":768 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -4648,14 +5971,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -4667,7 +5997,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -4683,10 +6013,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); - __Pyx_TraceCall("PyArray_MultiIterNew3", __pyx_f[1], 770); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + __Pyx_TraceCall("PyArray_MultiIterNew3", __pyx_f[1], 774); - /* "numpy.pxd":771 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -4694,14 +6024,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -4713,7 +6050,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -4729,10 +6066,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); - __Pyx_TraceCall("PyArray_MultiIterNew4", __pyx_f[1], 773); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + __Pyx_TraceCall("PyArray_MultiIterNew4", __pyx_f[1], 777); - /* "numpy.pxd":774 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -4740,14 +6077,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -4759,7 +6103,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -4775,10 +6119,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); - __Pyx_TraceCall("PyArray_MultiIterNew5", __pyx_f[1], 776); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + __Pyx_TraceCall("PyArray_MultiIterNew5", __pyx_f[1], 780); - /* "numpy.pxd":777 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -4786,14 +6130,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -4805,7 +6156,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -4827,21 +6178,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; + int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; + long __pyx_t_8; + char *__pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("_util_dtypestring"); - __Pyx_TraceCall("_util_dtypestring", __pyx_f[1], 779); + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + __Pyx_TraceCall("_util_dtypestring", __pyx_f[1], 783); - /* "numpy.pxd":786 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -4850,7 +6199,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":787 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -4859,161 +6208,164 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":790 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ - if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":791 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; - /* "numpy.pxd":792 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * - * if (end - f) - (new_offset - offset[0]) < 15: - */ - if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { - PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; - /* "numpy.pxd":794 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { - /* "numpy.pxd":795 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L5:; - /* "numpy.pxd":797 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (!__pyx_t_7) { + goto __pyx_L8_next_or; } else { - __pyx_t_7 = __pyx_t_6; } - if (!__pyx_t_7) { + __pyx_t_7 = (__pyx_v_little_endian != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_L8_next_or:; - /* "numpy.pxd":798 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; - } else { - __pyx_t_9 = __pyx_t_6; - } - __pyx_t_6 = __pyx_t_9; + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; } + __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L7_bool_binop_done:; if (__pyx_t_6) { - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; - /* "numpy.pxd":809 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -5021,16 +6373,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; - /* "numpy.pxd":810 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -5039,7 +6390,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":811 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -5048,430 +6399,410 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":812 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); } - /* "numpy.pxd":814 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); - /* "numpy.pxd":816 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { - /* "numpy.pxd":817 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":818 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { - /* "numpy.pxd":819 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L10:; - /* "numpy.pxd":822 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":823 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":824 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 104; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":825 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":826 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 105; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":827 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":828 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 108; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":829 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":830 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 113; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":831 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":832 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 102; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":833 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 100; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":834 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 103; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":835 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":836 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":837 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":838 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; - goto __pyx_L11; + goto __pyx_L15; } /*else*/ { - /* "numpy.pxd":840 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_9), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L11:; + __pyx_L15:; - /* "numpy.pxd":841 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -5479,25 +6810,33 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":845 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; } - __pyx_L9:; + __pyx_L13:; + + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":846 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -5507,13 +6846,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_r = __pyx_v_f; goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -5527,7 +6872,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":961 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -5539,11 +6884,12 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; + int __pyx_t_2; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("set_array_base"); - __Pyx_TraceCall("set_array_base", __pyx_f[1], 961); + __Pyx_RefNannySetupContext("set_array_base", 0); + __Pyx_TraceCall("set_array_base", __pyx_f[1], 966); - /* "numpy.pxd":963 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -5551,9 +6897,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "numpy.pxd":964 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -5565,7 +6912,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":966 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":971 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -5574,7 +6921,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":967 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":972 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -5585,7 +6932,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":968 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":973 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -5594,7 +6941,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":969 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":974 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -5603,11 +6950,20 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ __pyx_v_arr->base = __pyx_v_baseptr; + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ __Pyx_TraceReturn(Py_None); __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":971 +/* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -5620,20 +6976,20 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_TraceDeclarations - __Pyx_RefNannySetupContext("get_array_base"); - __Pyx_TraceCall("get_array_base", __pyx_f[1], 971); + __Pyx_RefNannySetupContext("get_array_base", 0); + __Pyx_TraceCall("get_array_base", __pyx_f[1], 976); - /* "numpy.pxd":972 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { - /* "numpy.pxd":973 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":978 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -5644,11 +7000,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "numpy.pxd":975 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -5658,9 +7013,16 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } - __pyx_L3:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_TraceReturn(__pyx_r); @@ -5669,15 +7031,19 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py } static PyMethodDef __pyx_methods[] = { - {__Pyx_NAMESTR("_assign_labels_array"), (PyCFunction)__pyx_pf_7sklearn_7cluster_8_k_means__assign_labels_array, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_8_k_means__assign_labels_array)}, - {__Pyx_NAMESTR("_assign_labels_csr"), (PyCFunction)__pyx_pf_7sklearn_7cluster_8_k_means_1_assign_labels_csr, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_8_k_means_1_assign_labels_csr)}, + {"_assign_labels_array", (PyCFunction)__pyx_pw_7sklearn_7cluster_8_k_means_1_assign_labels_array, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_7cluster_8_k_means__assign_labels_array}, + {"_assign_labels_csr", (PyCFunction)__pyx_pw_7sklearn_7cluster_8_k_means_3_assign_labels_csr, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_7cluster_8_k_means_2_assign_labels_csr}, {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else PyModuleDef_HEAD_INIT, - __Pyx_NAMESTR("_k_means"), + #endif + "_k_means", 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, @@ -5689,47 +7055,82 @@ static struct PyModuleDef __pyx_moduledef = { #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_n_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 1}, - {&__pyx_kp_u_10, __pyx_k_10, sizeof(__pyx_k_10), 0, 1, 0, 0}, - {&__pyx_kp_u_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 1, 0, 0}, - {&__pyx_n_s_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 0, 1, 1}, - {&__pyx_n_s_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 1, 1}, - {&__pyx_n_s_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 0, 1, 1}, - {&__pyx_kp_u_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 1, 0, 0}, - {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, - {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, - {&__pyx_kp_u_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 1, 0, 0}, - {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__centers, __pyx_k__centers, sizeof(__pyx_k__centers), 0, 0, 1, 1}, - {&__pyx_n_s__counts, __pyx_k__counts, sizeof(__pyx_k__counts), 0, 0, 1, 1}, - {&__pyx_n_s__csr_row_norm_l2, __pyx_k__csr_row_norm_l2, sizeof(__pyx_k__csr_row_norm_l2), 0, 0, 1, 1}, - {&__pyx_n_s__data, __pyx_k__data, sizeof(__pyx_k__data), 0, 0, 1, 1}, - {&__pyx_n_s__distances, __pyx_k__distances, sizeof(__pyx_k__distances), 0, 0, 1, 1}, - {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, - {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, - {&__pyx_n_s__indices, __pyx_k__indices, sizeof(__pyx_k__indices), 0, 0, 1, 1}, - {&__pyx_n_s__indptr, __pyx_k__indptr, sizeof(__pyx_k__indptr), 0, 0, 1, 1}, - {&__pyx_n_s__labels, __pyx_k__labels, sizeof(__pyx_k__labels), 0, 0, 1, 1}, - {&__pyx_n_s__nearest_center, __pyx_k__nearest_center, sizeof(__pyx_k__nearest_center), 0, 0, 1, 1}, - {&__pyx_n_s__norm, __pyx_k__norm, sizeof(__pyx_k__norm), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__old_center, __pyx_k__old_center, sizeof(__pyx_k__old_center), 0, 0, 1, 1}, - {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, - {&__pyx_n_s__squared, __pyx_k__squared, sizeof(__pyx_k__squared), 0, 0, 1, 1}, - {&__pyx_n_s__x_squared_norms, __pyx_k__x_squared_norms, sizeof(__pyx_k__x_squared_norms), 0, 0, 1, 1}, - {&__pyx_n_s__zeros, __pyx_k__zeros, sizeof(__pyx_k__zeros), 0, 0, 1, 1}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_n_s_X_data, __pyx_k_X_data, sizeof(__pyx_k_X_data), 0, 0, 1, 1}, + {&__pyx_n_s_X_indices, __pyx_k_X_indices, sizeof(__pyx_k_X_indices), 0, 0, 1, 1}, + {&__pyx_n_s_X_indptr, __pyx_k_X_indptr, sizeof(__pyx_k_X_indptr), 0, 0, 1, 1}, + {&__pyx_n_s__12, __pyx_k__12, sizeof(__pyx_k__12), 0, 0, 1, 1}, + {&__pyx_n_s_argsort, __pyx_k_argsort, sizeof(__pyx_k_argsort), 0, 0, 1, 1}, + {&__pyx_n_s_bincount, __pyx_k_bincount, sizeof(__pyx_k_bincount), 0, 0, 1, 1}, + {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, + {&__pyx_n_s_center_diff, __pyx_k_center_diff, sizeof(__pyx_k_center_diff), 0, 0, 1, 1}, + {&__pyx_n_s_center_idx, __pyx_k_center_idx, sizeof(__pyx_k_center_idx), 0, 0, 1, 1}, + {&__pyx_n_s_centers, __pyx_k_centers, sizeof(__pyx_k_centers), 0, 0, 1, 1}, + {&__pyx_n_s_centers_dense, __pyx_k_centers_dense, sizeof(__pyx_k_centers_dense), 0, 0, 1, 1}, + {&__pyx_n_s_centers_sparse, __pyx_k_centers_sparse, sizeof(__pyx_k_centers_sparse), 0, 0, 1, 1}, + {&__pyx_n_s_cluster_id, __pyx_k_cluster_id, sizeof(__pyx_k_cluster_id), 0, 0, 1, 1}, + {&__pyx_n_s_compute_squared_diff, __pyx_k_compute_squared_diff, sizeof(__pyx_k_compute_squared_diff), 0, 0, 1, 1}, + {&__pyx_n_s_counts, __pyx_k_counts, sizeof(__pyx_k_counts), 0, 0, 1, 1}, + {&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1}, + {&__pyx_n_s_distances, __pyx_k_distances, sizeof(__pyx_k_distances), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_empty_clusters, __pyx_k_empty_clusters, sizeof(__pyx_k_empty_clusters), 0, 0, 1, 1}, + {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, + {&__pyx_n_s_far_from_centers, __pyx_k_far_from_centers, sizeof(__pyx_k_far_from_centers), 0, 0, 1, 1}, + {&__pyx_n_s_feature_idx, __pyx_k_feature_idx, sizeof(__pyx_k_feature_idx), 0, 0, 1, 1}, + {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 0, 0, 1, 1}, + {&__pyx_kp_s_home_lesteve_dev_scikit_learn_s, __pyx_k_home_lesteve_dev_scikit_learn_s, sizeof(__pyx_k_home_lesteve_dev_scikit_learn_s), 0, 0, 1, 0}, + {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_indices, __pyx_k_indices, sizeof(__pyx_k_indices), 0, 0, 1, 1}, + {&__pyx_n_s_indptr, __pyx_k_indptr, sizeof(__pyx_k_indptr), 0, 0, 1, 1}, + {&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, + {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1}, + {&__pyx_n_s_labels, __pyx_k_labels, sizeof(__pyx_k_labels), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_mini_batch_update_csr, __pyx_k_mini_batch_update_csr, sizeof(__pyx_k_mini_batch_update_csr), 0, 0, 1, 1}, + {&__pyx_n_s_minlength, __pyx_k_minlength, sizeof(__pyx_k_minlength), 0, 0, 1, 1}, + {&__pyx_n_s_n_clusters, __pyx_k_n_clusters, sizeof(__pyx_k_n_clusters), 0, 0, 1, 1}, + {&__pyx_n_s_n_features, __pyx_k_n_features, sizeof(__pyx_k_n_features), 0, 0, 1, 1}, + {&__pyx_n_s_n_samples, __pyx_k_n_samples, sizeof(__pyx_k_n_samples), 0, 0, 1, 1}, + {&__pyx_n_s_n_samples_in_cluster, __pyx_k_n_samples_in_cluster, sizeof(__pyx_k_n_samples_in_cluster), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_nearest_center, __pyx_k_nearest_center, sizeof(__pyx_k_nearest_center), 0, 0, 1, 1}, + {&__pyx_n_s_new_center, __pyx_k_new_center, sizeof(__pyx_k_new_center), 0, 0, 1, 1}, + {&__pyx_n_s_new_count, __pyx_k_new_count, sizeof(__pyx_k_new_count), 0, 0, 1, 1}, + {&__pyx_n_s_newaxis, __pyx_k_newaxis, sizeof(__pyx_k_newaxis), 0, 0, 1, 1}, + {&__pyx_n_s_norm, __pyx_k_norm, sizeof(__pyx_k_norm), 0, 0, 1, 1}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_old_center, __pyx_k_old_center, sizeof(__pyx_k_old_center), 0, 0, 1, 1}, + {&__pyx_n_s_old_count, __pyx_k_old_count, sizeof(__pyx_k_old_count), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_sample_idx, __pyx_k_sample_idx, sizeof(__pyx_k_sample_idx), 0, 0, 1, 1}, + {&__pyx_n_s_scipy_sparse, __pyx_k_scipy_sparse, sizeof(__pyx_k_scipy_sparse), 0, 0, 1, 1}, + {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_cluster__k_means, __pyx_k_sklearn_cluster__k_means, sizeof(__pyx_k_sklearn_cluster__k_means), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_utils_fixes, __pyx_k_sklearn_utils_fixes, sizeof(__pyx_k_sklearn_utils_fixes), 0, 0, 1, 1}, + {&__pyx_n_s_sp, __pyx_k_sp, sizeof(__pyx_k_sp), 0, 0, 1, 1}, + {&__pyx_n_s_squared_diff, __pyx_k_squared_diff, sizeof(__pyx_k_squared_diff), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_utils_extmath, __pyx_k_utils_extmath, sizeof(__pyx_k_utils_extmath), 0, 0, 1, 1}, + {&__pyx_n_s_where, __pyx_k_where, sizeof(__pyx_k_where), 0, 0, 1, 1}, + {&__pyx_n_s_x_squared_norms, __pyx_k_x_squared_norms, sizeof(__pyx_k_x_squared_norms), 0, 0, 1, 1}, + {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -5737,91 +7138,164 @@ static int __Pyx_InitCachedBuiltins(void) { static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "sklearn/cluster/_k_means.pyx":209 + * # with regards to the new data that will be incrementally contributed + * if compute_squared_diff: + * old_center[:] = centers[center_idx] # <<<<<<<<<<<<<< + * centers[center_idx] *= old_count + * + */ + __pyx_slice_ = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice_); + __Pyx_GIVEREF(__pyx_slice_); + + /* "sklearn/cluster/_k_means.pyx":282 + * if len(empty_clusters): + * # find points to reassign empty clusters to + * far_from_centers = distances.argsort()[::-1] # <<<<<<<<<<<<<< + * + * for i, cluster_id in enumerate(empty_clusters): + */ + __pyx_slice__2 = PySlice_New(Py_None, Py_None, __pyx_int_neg_1); if (unlikely(!__pyx_slice__2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice__2); + __Pyx_GIVEREF(__pyx_slice__2); - /* "numpy.pxd":211 + /* "sklearn/cluster/_k_means.pyx":294 + * centers[labels[i], j] += X[i, j] + * + * centers /= n_samples_in_cluster[:, np.newaxis] # <<<<<<<<<<<<<< + * + * return centers + */ + __pyx_slice__3 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice__3); + __Pyx_GIVEREF(__pyx_slice__3); + + /* "sklearn/cluster/_k_means.pyx":343 + * if empty_clusters.shape[0] > 0: + * # find points to reassign empty clusters to + * far_from_centers = distances.argsort()[::-1] # <<<<<<<<<<<<<< + * + * for i in range(empty_clusters.shape[0]): + */ + __pyx_slice__4 = PySlice_New(Py_None, Py_None, __pyx_int_neg_1); if (unlikely(!__pyx_slice__4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice__4); + __Pyx_GIVEREF(__pyx_slice__4); + + /* "sklearn/cluster/_k_means.pyx":357 + * add_row_csr(data, indices, indptr, i, centers[labels[i]]) + * + * centers /= n_samples_in_cluster[:, np.newaxis] # <<<<<<<<<<<<<< + * + * return centers + */ + __pyx_slice__5 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice__5); + __Pyx_GIVEREF(__pyx_slice__5); + + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_4)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_3)); - PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_u_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); - /* "numpy.pxd":215 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_6)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_8 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_8)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_7)); - PyTuple_SET_ITEM(__pyx_k_tuple_8, 0, ((PyObject *)__pyx_kp_u_7)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_7)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); - /* "numpy.pxd":795 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_11 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_11)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_10)); - PyTuple_SET_ITEM(__pyx_k_tuple_11, 0, ((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); + __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_12)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_7)); - PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_7)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_7)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); - /* "numpy.pxd":819 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_14 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_14)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_13)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, ((PyObject *)__pyx_kp_u_13)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_13)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__11); + __Pyx_GIVEREF(__pyx_tuple__11); + + /* "sklearn/cluster/_k_means.pyx":142 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _mini_batch_update_csr(X, np.ndarray[DOUBLE, ndim=1] x_squared_norms, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=2] centers, + * np.ndarray[INT, ndim=1] counts, + */ + __pyx_tuple__13 = PyTuple_Pack(21, __pyx_n_s_X, __pyx_n_s_x_squared_norms, __pyx_n_s_centers, __pyx_n_s_counts, __pyx_n_s_nearest_center, __pyx_n_s_old_center, __pyx_n_s_compute_squared_diff, __pyx_n_s_X_data, __pyx_n_s_X_indices, __pyx_n_s_X_indptr, __pyx_n_s_n_samples, __pyx_n_s_n_clusters, __pyx_n_s_n_features, __pyx_n_s_sample_idx, __pyx_n_s_center_idx, __pyx_n_s_feature_idx, __pyx_n_s_k, __pyx_n_s_old_count, __pyx_n_s_new_count, __pyx_n_s_center_diff, __pyx_n_s_squared_diff); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__13); + __Pyx_GIVEREF(__pyx_tuple__13); + __pyx_codeobj__14 = (PyObject*)__Pyx_PyCode_New(7, 0, 21, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__13, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_lesteve_dev_scikit_learn_s, __pyx_n_s_mini_batch_update_csr, 142, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/cluster/_k_means.pyx":245 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def _centers_dense(np.ndarray[DOUBLE, ndim=2] X, # <<<<<<<<<<<<<< + * np.ndarray[INT, ndim=1] labels, int n_clusters, + * np.ndarray[DOUBLE, ndim=1] distances): + */ + __pyx_tuple__15 = PyTuple_Pack(15, __pyx_n_s_X, __pyx_n_s_labels, __pyx_n_s_n_clusters, __pyx_n_s_distances, __pyx_n_s_n_samples, __pyx_n_s_n_features, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_c, __pyx_n_s_centers, __pyx_n_s_n_samples_in_cluster, __pyx_n_s_empty_clusters, __pyx_n_s_far_from_centers, __pyx_n_s_cluster_id, __pyx_n_s_new_center); if (unlikely(!__pyx_tuple__15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__15); + __Pyx_GIVEREF(__pyx_tuple__15); + __pyx_codeobj__16 = (PyObject*)__Pyx_PyCode_New(4, 0, 15, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__15, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_lesteve_dev_scikit_learn_s, __pyx_n_s_centers_dense, 245, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/cluster/_k_means.pyx":299 + * + * + * def _centers_sparse(X, np.ndarray[INT, ndim=1] labels, n_clusters, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=1] distances): + * """M step of the K-means EM algorithm + */ + __pyx_tuple__17 = PyTuple_Pack(14, __pyx_n_s_X, __pyx_n_s_labels, __pyx_n_s_n_clusters, __pyx_n_s_distances, __pyx_n_s_n_features, __pyx_n_s_cluster_id, __pyx_n_s_data, __pyx_n_s_indices, __pyx_n_s_indptr, __pyx_n_s_centers, __pyx_n_s_far_from_centers, __pyx_n_s_n_samples_in_cluster, __pyx_n_s_empty_clusters, __pyx_n_s_i); if (unlikely(!__pyx_tuple__17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__17); + __Pyx_GIVEREF(__pyx_tuple__17); + __pyx_codeobj__18 = (PyObject*)__Pyx_PyCode_New(4, 0, 14, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__17, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_lesteve_dev_scikit_learn_s, __pyx_n_s_centers_sparse, 299, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -5831,7 +7305,10 @@ static int __Pyx_InitCachedConstants(void) { static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_float_0_ = PyFloat_FromDouble(0.); if (unlikely(!__pyx_float_0_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -5847,6 +7324,10 @@ PyMODINIT_FUNC PyInit__k_means(void) { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -5857,12 +7338,18 @@ PyMODINIT_FUNC PyInit__k_means(void) Py_FatalError("failed to import 'refnanny' module"); } #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__k_means(void)"); + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__k_means(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __pyx_binding_PyCFunctionType_USED - if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -5873,22 +7360,34 @@ PyMODINIT_FUNC PyInit__k_means(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_k_means"), __pyx_methods, 0, 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4("_k_means", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif if (__pyx_module_is_main_sklearn__cluster___k_means) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.cluster._k_means")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.cluster._k_means", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } } + #endif /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ @@ -5898,100 +7397,171 @@ PyMODINIT_FUNC PyInit__k_means(void) /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ + __pyx_t_1 = __Pyx_ImportModule("sklearn.utils.sparsefuncs_fast"); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_ImportFunction(__pyx_t_1, "add_row_csr", (void (**)(void))&__pyx_f_7sklearn_5utils_16sparsefuncs_fast_add_row_csr, "void (PyArrayObject *, PyArrayObject *, PyArrayObject *, int, PyArrayObject *)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; /*--- Execution code ---*/ - /* "sklearn/cluster/_k_means.pyx":10 - * # License: BSD Style. + /* "sklearn/cluster/_k_means.pyx":12 * + * from libc.math cimport sqrt * import numpy as np # <<<<<<<<<<<<<< - * from ..utils.extmath import norm + * import scipy.sparse as sp * cimport numpy as np */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_2 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/cluster/_k_means.pyx":11 - * + /* "sklearn/cluster/_k_means.pyx":13 + * from libc.math cimport sqrt * import numpy as np - * from ..utils.extmath import norm # <<<<<<<<<<<<<< + * import scipy.sparse as sp # <<<<<<<<<<<<<< * cimport numpy as np * cimport cython */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__norm)); - PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s__norm)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__norm)); - __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s_15), ((PyObject *)__pyx_t_1), 2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__norm); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__norm, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_INCREF(__pyx_n_s__12); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s__12); + __Pyx_GIVEREF(__pyx_n_s__12); + __pyx_t_3 = __Pyx_Import(__pyx_n_s_scipy_sparse, __pyx_t_2, -1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_sp, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "sklearn/cluster/_k_means.pyx":17 + * cimport cython + * + * from ..utils.extmath import norm # <<<<<<<<<<<<<< + * from sklearn.utils.sparsefuncs_fast cimport add_row_csr + * from sklearn.utils.fixes import bincount + */ + __pyx_t_3 = PyList_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_n_s_norm); + PyList_SET_ITEM(__pyx_t_3, 0, __pyx_n_s_norm); + __Pyx_GIVEREF(__pyx_n_s_norm); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_utils_extmath, __pyx_t_3, 2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_norm); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_norm, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/cluster/_k_means.pyx":19 + * from ..utils.extmath import norm + * from sklearn.utils.sparsefuncs_fast cimport add_row_csr + * from sklearn.utils.fixes import bincount # <<<<<<<<<<<<<< + * + * ctypedef np.float64_t DOUBLE + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_bincount); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_bincount); + __Pyx_GIVEREF(__pyx_n_s_bincount); + __pyx_t_3 = __Pyx_Import(__pyx_n_s_sklearn_utils_fixes, __pyx_t_2, -1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_bincount); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_bincount, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/cluster/_k_means.pyx":139 + /* "sklearn/cluster/_k_means.pyx":27 + * double ddot "cblas_ddot"(int N, double *X, int incX, double *Y, int incY) + * + * np.import_array() # <<<<<<<<<<<<<< + * + * + */ + import_array(); + + /* "sklearn/cluster/_k_means.pyx":142 * @cython.wraparound(False) * @cython.cdivision(True) * def _mini_batch_update_csr(X, np.ndarray[DOUBLE, ndim=1] x_squared_norms, # <<<<<<<<<<<<<< * np.ndarray[DOUBLE, ndim=2] centers, * np.ndarray[INT, ndim=1] counts, */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_8_k_means_2_mini_batch_update_csr, NULL, __pyx_n_s_16); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_17, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_8_k_means_5_mini_batch_update_csr, NULL, __pyx_n_s_sklearn_cluster__k_means); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_mini_batch_update_csr, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/cluster/_k_means.pyx":242 + /* "sklearn/cluster/_k_means.pyx":245 * @cython.wraparound(False) * @cython.cdivision(True) - * def csr_row_norm_l2(X, squared=True): # <<<<<<<<<<<<<< - * """Get L2 norm of each row in CSR matrix X. + * def _centers_dense(np.ndarray[DOUBLE, ndim=2] X, # <<<<<<<<<<<<<< + * np.ndarray[INT, ndim=1] labels, int n_clusters, + * np.ndarray[DOUBLE, ndim=1] distances): + */ + __pyx_t_3 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_8_k_means_7_centers_dense, NULL, __pyx_n_s_sklearn_cluster__k_means); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_centers_dense, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "sklearn/cluster/_k_means.pyx":299 + * * + * def _centers_sparse(X, np.ndarray[INT, ndim=1] labels, n_clusters, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=1] distances): + * """M step of the K-means EM algorithm */ - __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_k_2 = __pyx_t_2; - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_8_k_means_3csr_row_norm_l2, NULL, __pyx_n_s_16); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__csr_row_norm_l2, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_8_k_means_9_centers_sparse, NULL, __pyx_n_s_sklearn_cluster__k_means); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_centers_sparse, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "sklearn/cluster/_k_means.pyx":1 * # cython: profile=True # <<<<<<<<<<<<<< * # Profiling is enabled by default as the overhead does not seem to be measurable * # on this specific use case. */ - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":971 + /* "../../anaconda/envs/scratch/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ + + /*--- Wrapped vars code ---*/ + goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); if (__pyx_m) { - __Pyx_AddTraceback("init sklearn.cluster._k_means", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__pyx_d) { + __Pyx_AddTraceback("init sklearn.cluster._k_means", __pyx_clineno, __pyx_lineno, __pyx_filename); + } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init sklearn.cluster._k_means"); @@ -6006,7 +7576,6 @@ PyMODINIT_FUNC PyInit__k_means(void) } /* Runtime support code */ - #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; @@ -6021,55 +7590,68 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } -#endif /* CYTHON_REFNANNY */ +#endif -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif } return result; } - #if CYTHON_PROFILE - static int __Pyx_TraceSetupAndCall(PyCodeObject** code, PyFrameObject** frame, const char *funcname, const char *srcfile, int firstlineno) { + int retval; + PyThreadState* tstate = PyThreadState_GET(); if (*frame == NULL || !CYTHON_PROFILE_REUSE_FRAME) { if (*code == NULL) { *code = __Pyx_createFrameCodeObject(funcname, srcfile, firstlineno); if (*code == NULL) return 0; } *frame = PyFrame_New( - PyThreadState_GET(), /*PyThreadState *tstate*/ - *code, /*PyCodeObject *code*/ - PyModule_GetDict(__pyx_m), /*PyObject *globals*/ - 0 /*PyObject *locals*/ + tstate, /*PyThreadState *tstate*/ + *code, /*PyCodeObject *code*/ + __pyx_d, /*PyObject *globals*/ + 0 /*PyObject *locals*/ ); if (*frame == NULL) return 0; + if (CYTHON_TRACE && (*frame)->f_trace == NULL) { + Py_INCREF(Py_None); + (*frame)->f_trace = Py_None; + } +#if PY_VERSION_HEX < 0x030400B1 + } else { + (*frame)->f_tstate = tstate; +#endif } - else { - (*frame)->f_tstate = PyThreadState_GET(); - } - return PyThreadState_GET()->c_profilefunc(PyThreadState_GET()->c_profileobj, *frame, PyTrace_CALL, NULL) == 0; + (*frame)->f_lineno = firstlineno; + tstate->use_tracing = 0; + #if CYTHON_TRACE + if (tstate->c_tracefunc) + tstate->c_tracefunc(tstate->c_traceobj, *frame, PyTrace_CALL, NULL); + if (!tstate->c_profilefunc) + retval = 1; + else + #endif + retval = tstate->c_profilefunc(tstate->c_profileobj, *frame, PyTrace_CALL, NULL) == 0; + tstate->use_tracing = (tstate->c_profilefunc || + (CYTHON_TRACE && tstate->c_tracefunc)); + return tstate->use_tracing && retval; } - static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno) { PyObject *py_srcfile = 0; PyObject *py_funcname = 0; PyCodeObject *py_code = 0; - #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); py_srcfile = PyString_FromString(srcfile); @@ -6078,52 +7660,36 @@ static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const cha py_srcfile = PyUnicode_FromString(srcfile); #endif if (!py_funcname | !py_srcfile) goto bad; - py_code = PyCode_New( - 0, /*int argcount,*/ + 0, #if PY_MAJOR_VERSION >= 3 - 0, /*int kwonlyargcount,*/ + 0, #endif - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ - 0, /*int flags,*/ - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ - firstlineno, /*int firstlineno,*/ - __pyx_empty_bytes /*PyObject *lnotab*/ + firstlineno, + __pyx_empty_bytes /*PyObject *lnotab*/ ); - bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); - return py_code; } - -#endif /* CYTHON_PROFILE */ +#endif static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } - -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; -} __Pyx_BufFmt_Context; - static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { @@ -6142,6 +7708,8 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; @@ -6149,7 +7717,6 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, type = type->fields->type; } } - static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; @@ -6165,15 +7732,21 @@ static int __Pyx_BufFmt_ParseNumber(const char** ts) { *ts = t; return count; } - +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } - static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { - case 'b': return "'char'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; @@ -6189,14 +7762,14 @@ static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; + case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } - static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; @@ -6212,10 +7785,9 @@ static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { return 0; } } - static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'B': return 1; + case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); @@ -6232,7 +7804,6 @@ static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { } } } - typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; @@ -6243,10 +7814,9 @@ typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif - -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); @@ -6262,21 +7832,59 @@ static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { return 0; } } - +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'h': case 'i': case 'l': case 'q': return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; - case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); - case 'O': return 'O'; - case 'P': return 'P'; + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } - static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; @@ -6301,16 +7909,37 @@ static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { parent->type->name, field->name); } } - static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; - size_t size, offset; + size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { @@ -6322,35 +7951,35 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); } - if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { - /* special case -- treat as struct rather than complex number */ size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } - - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } - offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } - ctx->fmt_offset += size; - - --ctx->enc_count; /* Consume from buffer string */ - - /* Done checking, move to next field, pushing or popping struct stack if needed */ + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; while (1) { if (field == &ctx->root) { ctx->head = NULL; @@ -6358,7 +7987,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } - break; /* breaks both loops as ctx->enc_count == 0 */ + break; } ctx->head->field = ++field; if (field->type == NULL) { @@ -6367,7 +7996,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { continue; } else if (field->type->typegroup == 'S') { size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; /* empty struct */ + if (field->type->fields->type == NULL) continue; field = field->type->fields; ++ctx->head; ctx->head->field = field; @@ -6382,7 +8011,50 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ctx->is_complex = 0; return 0; } - +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { @@ -6399,8 +8071,8 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha } return ts; case ' ': - case 10: - case 13: + case '\r': + case '\n': ++ts; break; case '<': @@ -6425,16 +8097,21 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha case '^': ctx->new_packmode = *ts++; break; - case 'T': /* substruct */ + case 'T': { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + ctx->enc_count = 0; + ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { @@ -6442,10 +8119,19 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha if (!ts_after_sub) return NULL; } ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; - case '}': /* end of substruct; either repeat or move on */ - ++ts; + case '}': + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; @@ -6462,23 +8148,25 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha if (*ts != 'f' && *ts != 'd' && *ts != 'g') { __Pyx_BufFmt_RaiseUnexpectedChar('Z'); return NULL; - } /* fall through */ + } case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': - case 'O': + case 'O': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { - /* Continue pooling same type */ ctx->enc_count += ctx->new_count; - } else { - /* New type */ - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; } + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; ++ts; ctx->new_count = 1; got_Z = 0; @@ -6488,20 +8176,18 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha while(*ts != ':') ++ts; ++ts; break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; default: { - int number = __Pyx_BufFmt_ParseNumber(&ts); - if (number == -1) { /* First char was not a digit */ - PyErr_Format(PyExc_ValueError, - "Does not understand character buffer dtype format string ('%c')", *ts); - return NULL; - } - ctx->new_count = (size_t)number; + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; } } } } - static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; @@ -6509,8 +8195,10 @@ static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; @@ -6530,7 +8218,7 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* ob } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; @@ -6541,16 +8229,51 @@ fail:; __Pyx_ZeroBuffer(buf); return -1; } - static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (likely(result)) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); + PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) @@ -6561,9 +8284,9 @@ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { } static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; @@ -6573,19 +8296,50 @@ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyOb Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif } - static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif } +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, + int full_traceback) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + if (full_traceback) { + Py_XINCREF(old_exc); + Py_XINCREF(old_val); + Py_XINCREF(old_tb); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + PyErr_PrintEx(1); + } + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} static void __Pyx_RaiseArgtupleInvalid( const char* func_name, @@ -6596,7 +8350,6 @@ static void __Pyx_RaiseArgtupleInvalid( { Py_ssize_t num_expected; const char *more_or_less; - if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; @@ -6608,7 +8361,7 @@ static void __Pyx_RaiseArgtupleInvalid( more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } @@ -6622,7 +8375,7 @@ static void __Pyx_RaiseDoubleKeywordsError( "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); + PyString_AsString(kw_name)); #endif } @@ -6638,64 +8391,86 @@ static int __Pyx_ParseOptionalKeywords( Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { values[name-argnames] = value; - } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; } } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; } } return 0; arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); + __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); + "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", + "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", @@ -6705,86 +8480,375 @@ static int __Pyx_ParseOptionalKeywords( return -1; } -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact) -{ - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(PyObject_TypeCheck(obj, type))) return 1; + } + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); + return 0; +} + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static CYTHON_INLINE int __Pyx_PyObject_SetSlice( + PyObject* obj, PyObject* value, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { +#if CYTHON_COMPILING_IN_CPYTHON + PyMappingMethods* mp; +#if PY_MAJOR_VERSION < 3 + PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; + if (likely(ms && ms->sq_ass_slice)) { + if (!has_cstart) { + if (_py_start && (*_py_start != Py_None)) { + cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); + if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstart = 0; + } + if (!has_cstop) { + if (_py_stop && (*_py_stop != Py_None)) { + cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); + if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstop = PY_SSIZE_T_MAX; + } + if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { + Py_ssize_t l = ms->sq_length(obj); + if (likely(l >= 0)) { + if (cstop < 0) { + cstop += l; + if (cstop < 0) cstop = 0; + } + if (cstart < 0) { + cstart += l; + if (cstart < 0) cstart = 0; + } + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + goto bad; + } + } + return ms->sq_ass_slice(obj, cstart, cstop, value); + } +#endif + mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_ass_subscript)) +#endif + { + int result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyInt_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyInt_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_COMPILING_IN_CPYTHON + result = mp->mp_ass_subscript(obj, py_slice, value); +#else + result = value ? PyObject_SetItem(obj, py_slice, value) : PyObject_DelItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } + PyErr_Format(PyExc_TypeError, + "'%.200s' object does not support slice %.10s", + Py_TYPE(obj)->tp_name, value ? "assignment" : "deletion"); +bad: + return -1; +} + +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { + int r; + if (!j) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { + PyObject* old = PyList_GET_ITEM(o, n); + Py_INCREF(v); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 1; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return -1; + } + } + return m->sq_ass_item(o, i, v); + } + } +#else +#if CYTHON_COMPILING_IN_PYPY + if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) { +#else + if (is_list || PySequence_Check(o)) { +#endif + return PySequence_SetItem(o, i, v); + } +#endif + return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = PyCFunction_GET_FUNCTION(func); + self = PyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); } - if (none_allowed && obj == Py_None) return 1; - else if (exact) { - if (Py_TYPE(obj) == type) return 1; + return result; +} +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *result; + PyObject *args = PyTuple_New(1); + if (unlikely(!args)) return NULL; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, arg); + result = __Pyx_PyObject_Call(func, args, NULL); + Py_DECREF(args); + return result; +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { +#ifdef __Pyx_CyFunction_USED + if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { +#else + if (likely(PyCFunction_Check(func))) { +#endif + if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { + return __Pyx_PyObject_CallMethO(func, arg); + } } - else { - if (PyObject_TypeCheck(obj, type)) return 1; + return __Pyx__PyObject_CallOneArg(func, arg); +} +#else +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject* args = PyTuple_Pack(1, arg); + return (likely(args)) ? __Pyx_PyObject_Call(func, args, NULL) : NULL; +} +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { +#ifdef __Pyx_CyFunction_USED + if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { +#else + if (likely(PyCFunction_Check(func))) { +#endif + if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { + return __Pyx_PyObject_CallMethO(func, NULL); + } } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; + return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); +} +#endif + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); } +static void __Pyx_RaiseBufferFallbackError(void) { + PyErr_SetString(PyExc_ValueError, + "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +} +static void __Pyx_RaiseBufferIndexError(int axis) { + PyErr_Format(PyExc_IndexError, + "Out of bounds on buffer access (axis %d)", axis); +} #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } - #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) - #else - if (!PyType_Check(type)) - #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { + if (PyType_Check(type)) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - /* Normalize to raise , */ - Py_DECREF(value); value = type; - #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - #endif + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } } - __Pyx_ErrRestore(type, value, tb); return; raise_error: @@ -6793,10 +8857,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tb); return; } - -#else /* Python 3+ */ - +#else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -6806,7 +8869,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } if (value == Py_None) value = 0; - if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, @@ -6815,38 +8877,79 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } - +#if PY_VERSION_HEX >= 0x03030000 if (cause) { +#else + if (cause && cause != Py_None) { +#endif PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; - } - else if (PyExceptionInstance_Check(cause)) { + } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { +#if CYTHON_COMPILING_IN_PYPY + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(tmp_type, tmp_value, tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#else PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { @@ -6854,137 +8957,731 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } - } - -bad: - return; -} #endif - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); -} - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); -} - -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif + } + return value; +} + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + Py_DECREF(obj); + view->obj = NULL; +} +#endif + + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ + { \ + func_type value = func_value; \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + if (is_unsigned && unlikely(value < zero)) \ + goto raise_neg_overflow; \ + else \ + goto raise_overflow; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong(x)) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value) { + const unsigned int neg_one = (unsigned int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(unsigned int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(unsigned int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(unsigned int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } } else { - __Pyx_RaiseTooManyValuesError(index); + if (sizeof(unsigned int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(unsigned int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(unsigned int), + little, !is_unsigned); } } +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) { + const unsigned int neg_one = (unsigned int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); - else { - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; + if (likely(PyInt_Check(x))) { + if (sizeof(unsigned int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (unsigned int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(unsigned int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(unsigned int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(unsigned int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(unsigned int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyLong_AsLong(x)) + } else if (sizeof(unsigned int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + unsigned int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (unsigned int) -1; + } + } else { + unsigned int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned int) -1; + val = __Pyx_PyInt_As_unsigned_int(tmp); + Py_DECREF(tmp); + return val; } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to unsigned int"); + return (unsigned int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned int"); + return (unsigned int) -1; } -static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject* obj = view->obj; - if (obj) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;} - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray_1__releasebuffer__(obj, view); - Py_DECREF(obj); - view->obj = NULL; - } +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); + } } -#endif - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); - if (!py_import) - goto bad; - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_int32(npy_int32 value) { + const npy_int32 neg_one = (npy_int32) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(npy_int32) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(npy_int32) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(npy_int32) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(npy_int32) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(npy_int32) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - #if PY_VERSION_HEX >= 0x02050000 { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(npy_int32), + little, !is_unsigned); } - #else - if (level>0) { - PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); - goto bad; +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); } - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, NULL); - #endif -bad: - Py_XDECREF(empty_list); - Py_XDECREF(py_import); - Py_XDECREF(empty_dict); - return module; } -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32 val) { - const npy_int32 neg_one = (npy_int32)-1, const_zero = (npy_int32)0; - const int is_unsigned = const_zero < neg_one; - if ((sizeof(npy_int32) == sizeof(char)) || - (sizeof(npy_int32) == sizeof(short))) { - return PyInt_FromLong((long)val); - } else if ((sizeof(npy_int32) == sizeof(int)) || - (sizeof(npy_int32) == sizeof(long))) { - if (is_unsigned) - return PyLong_FromUnsignedLong((unsigned long)val); - else - return PyInt_FromLong((long)val); - } else if (sizeof(npy_int32) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); - else - return PyLong_FromLongLong((PY_LONG_LONG)val); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } } else { + if (sizeof(Py_intptr_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - return _PyLong_FromByteArray(bytes, sizeof(npy_int32), + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), little, !is_unsigned); } } +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *x) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (Py_intptr_t) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(Py_intptr_t) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyLong_AsLong(x)) + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + Py_intptr_t val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (Py_intptr_t) -1; + } + } else { + Py_intptr_t val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (Py_intptr_t) -1; + val = __Pyx_PyInt_As_Py_intptr_t(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to Py_intptr_t"); + return (Py_intptr_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; +} + #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { @@ -7213,435 +9910,111 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32 val) { theta = 0; } else { r = __Pyx_c_abs(a); - theta = atan2(a.imag, a.real); - } - lnr = log(r); - z_r = exp(lnr * b.real - theta * b.imag); - z_theta = theta * b.real + lnr * b.imag; - z.real = z_r * cos(z_theta); - z.imag = z_r * sin(z_theta); - return z; - } - #endif -#endif - -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; - } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; - } - return (unsigned short)val; - } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; - } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; - } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; - } - return (short)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; - } - return (signed char)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; - } - return (signed short)val; - } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; - } - return (signed int)val; - } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; + theta = atan2(a.imag, a.real); } - return (unsigned long)PyLong_AsUnsignedLong(x); - } else { - return (unsigned long)PyLong_AsLong(x); - } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; } - return (unsigned PY_LONG_LONG)val; - } else + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; } - return (long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, ((PyLongObject*)x)->ob_digit[0]); } - return (long)PyLong_AsUnsignedLong(x); - } else { - return (long)PyLong_AsLong(x); - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)val; - } else + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; + goto raise_neg_overflow; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong(x)) } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { - return (PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)val; - } else +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong(x)) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong(x)) } - return (signed long)PyLong_AsUnsignedLong(x); - } else { - return (signed long)PyLong_AsLong(x); - } - } else { - signed long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; } - return (signed PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; } } else { - signed PY_LONG_LONG val; + long val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } -} - -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename) { - PyObject *old_exc, *old_val, *old_tb; - PyObject *ctx; - __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); - #if PY_MAJOR_VERSION < 3 - ctx = PyString_FromString(name); - #else - ctx = PyUnicode_FromString(name); - #endif - __Pyx_ErrRestore(old_exc, old_val, old_tb); - if (!ctx) { - PyErr_WriteUnraisable(Py_None); - } else { - PyErr_WriteUnraisable(ctx); - Py_DECREF(ctx); - } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; } static int __Pyx_check_binary_version(void) { @@ -7654,15 +10027,28 @@ static int __Pyx_check_binary_version(void) { "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); - #if PY_VERSION_HEX < 0x02050000 - return PyErr_Warn(NULL, message); - #else return PyErr_WarnEx(NULL, message, 1); - #endif } return 0; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -7672,15 +10058,14 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(class_name); - #else - py_name = PyUnicode_FromString(class_name); - #endif + py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); @@ -7692,23 +10077,31 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", + "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); - #if PY_VERSION_HEX < 0x02050000 - if (PyErr_Warn(NULL, warning) < 0) goto bad; - #else if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", + "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } @@ -7720,98 +10113,58 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(name); - #else - py_name = PyUnicode_FromString(name); - #endif - if (!py_name) +#ifndef __PYX_HAVE_RT_ImportFunction +#define __PYX_HAVE_RT_ImportFunction +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); + if (!d) + goto bad; + cobj = PyDict_GetItemString(d, funcname); + if (!cobj) { + PyErr_Format(PyExc_ImportError, + "%.200s does not export expected C function %.200s", + PyModule_GetName(module), funcname); goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; -} -#endif - -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); - #else - py_srcfile = PyUnicode_FromString(__pyx_filename); - #endif - if (!py_srcfile) goto bad; - if (__pyx_clineno) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); - #endif } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif +#if PY_VERSION_HEX >= 0x02070000 + if (!PyCapsule_IsValid(cobj, sig)) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); + goto bad; } - if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_code = PyCode_New( - 0, /*int argcount,*/ - #if PY_MAJOR_VERSION >= 3 - 0, /*int kwonlyargcount,*/ - #endif - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ - 0, /*int flags,*/ - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - if (!py_code) goto bad; - py_frame = PyFrame_New( - PyThreadState_GET(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - py_globals, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; - PyTraceBack_Here(py_frame); + tmp.p = PyCapsule_GetPointer(cobj, sig); +#else + {const char *desc, *s1, *s2; + desc = (const char *)PyCObject_GetDesc(cobj); + if (!desc) + goto bad; + s1 = desc; s2 = sig; + while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } + if (*s1 != *s2) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, desc); + goto bad; + } + tmp.p = PyCObject_AsVoidPtr(cobj);} +#endif + *f = tmp.fp; + if (!(*f)) + goto bad; + Py_DECREF(d); + return 0; bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - Py_XDECREF(py_code); - Py_XDECREF(py_frame); + Py_XDECREF(d); + return -1; } +#endif static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { @@ -7823,7 +10176,7 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } - #else /* Python 3+ has unicode identifiers */ + #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); @@ -7843,26 +10196,88 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else + if (__Pyx_PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif + } else +#endif +#if !CYTHON_COMPILING_IN_PYPY + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -7878,13 +10293,13 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", + "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; @@ -7896,40 +10311,33 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { -#if PY_VERSION_HEX < 0x02050000 - if (ival <= LONG_MAX) - return PyInt_FromLong((long)ival); - else { - unsigned char *bytes = (unsigned char *) &ival; - int one = 1; int little = (int)*(unsigned char*)&one; - return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); - } -#else - return PyInt_FromSize_t(ival); -#endif -} - -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; + return PyInt_FromSize_t(ival); } diff --git a/sklearn/cluster/_k_means.pyx b/sklearn/cluster/_k_means.pyx index db94273427859..e76f09448b5c5 100644 --- a/sklearn/cluster/_k_means.pyx +++ b/sklearn/cluster/_k_means.pyx @@ -4,25 +4,28 @@ # Author: Peter Prettenhofer # Olivier Grisel +# Lars Buitinck # -# License: BSD Style. +# Licence: BSD 3 clause +from libc.math cimport sqrt import numpy as np -from ..utils.extmath import norm +import scipy.sparse as sp cimport numpy as np cimport cython +from ..utils.extmath import norm +from sklearn.utils.sparsefuncs_fast cimport add_row_csr +from sklearn.utils.fixes import bincount + ctypedef np.float64_t DOUBLE ctypedef np.int32_t INT - -cdef extern from "math.h": - double sqrt(double f) - - cdef extern from "cblas.h": double ddot "cblas_ddot"(int N, double *X, int incX, double *Y, int incY) +np.import_array() + @cython.boundscheck(False) @cython.wraparound(False) @@ -32,7 +35,7 @@ cpdef DOUBLE _assign_labels_array(np.ndarray[DOUBLE, ndim=2] X, np.ndarray[DOUBLE, ndim=2] centers, np.ndarray[INT, ndim=1] labels, np.ndarray[DOUBLE, ndim=1] distances): - """Compute label assignement and inertia for a dense array + """Compute label assignment and inertia for a dense array Return the inertia (sum of squared distances to the centers). """ @@ -85,7 +88,7 @@ cpdef DOUBLE _assign_labels_csr(X, np.ndarray[DOUBLE, ndim=1] x_squared_norms, np.ndarray[DOUBLE, ndim=2] centers, np.ndarray[INT, ndim=1] labels, np.ndarray[DOUBLE, ndim=1] distances): - """Compute label assignement and inertia for a CSR input + """Compute label assignment and inertia for a CSR input Return the inertia (sum of squared distances to the centers). """ @@ -200,8 +203,8 @@ def _mini_batch_update_csr(X, np.ndarray[DOUBLE, ndim=1] x_squared_norms, # no new sample: leave this center as it stands continue - # rescale the old center to reflect it previous accumulated - # weight w.r.t. the new data that will be incrementally contributed + # rescale the old center to reflect it previous accumulated weight + # with regards to the new data that will be incrementally contributed if compute_squared_diff: old_center[:] = centers[center_idx] centers[center_idx] *= old_count @@ -239,34 +242,118 @@ def _mini_batch_update_csr(X, np.ndarray[DOUBLE, ndim=1] x_squared_norms, @cython.boundscheck(False) @cython.wraparound(False) @cython.cdivision(True) -def csr_row_norm_l2(X, squared=True): - """Get L2 norm of each row in CSR matrix X. +def _centers_dense(np.ndarray[DOUBLE, ndim=2] X, + np.ndarray[INT, ndim=1] labels, int n_clusters, + np.ndarray[DOUBLE, ndim=1] distances): + """M step of the K-means EM algorithm - TODO: refactor me in the sklearn.utils.sparsefuncs module once the CSR - sklearn.preprocessing.StandardScaler has been refactored as well. - """ - cdef: - unsigned int n_samples = X.shape[0] - unsigned int n_features = X.shape[1] - np.ndarray[DOUBLE, ndim=1] norms = np.zeros((n_samples,), - dtype=np.float64) - np.ndarray[DOUBLE, ndim=1] X_data = X.data - np.ndarray[int, ndim=1] X_indices = X.indices - np.ndarray[int, ndim=1] X_indptr = X.indptr + Computation of cluster centers / means. + + Parameters + ---------- + X: array-like, shape (n_samples, n_features) + + labels: array of integers, shape (n_samples) + Current label assignment + + n_clusters: int + Number of desired clusters - unsigned int i - unsigned int j - double sum_ - int with_sqrt = not squared + distances: array-like, shape (n_samples) + Distance to closest cluster for each sample. + + Returns + ------- + centers: array, shape (n_clusters, n_features) + The resulting centers + """ + ## TODO: add support for CSR input + cdef int n_samples, n_features + n_samples = X.shape[0] + n_features = X.shape[1] + cdef int i, j, c + cdef np.ndarray[DOUBLE, ndim=2] centers = np.zeros((n_clusters, n_features)) + n_samples_in_cluster = bincount(labels, minlength=n_clusters) + empty_clusters = np.where(n_samples_in_cluster == 0)[0] + # maybe also relocate small clusters? + + if len(empty_clusters): + # find points to reassign empty clusters to + far_from_centers = distances.argsort()[::-1] + + for i, cluster_id in enumerate(empty_clusters): + # XXX two relocated clusters could be close to each other + new_center = X[far_from_centers[i]] + centers[cluster_id] = new_center + n_samples_in_cluster[cluster_id] = 1 for i in range(n_samples): - sum_ = 0.0 + for j in range(n_features): + centers[labels[i], j] += X[i, j] + + centers /= n_samples_in_cluster[:, np.newaxis] + + return centers + + +def _centers_sparse(X, np.ndarray[INT, ndim=1] labels, n_clusters, + np.ndarray[DOUBLE, ndim=1] distances): + """M step of the K-means EM algorithm + + Computation of cluster centers / means. + + Parameters + ---------- + X: scipy.sparse.csr_matrix, shape (n_samples, n_features) + + labels: array of integers, shape (n_samples) + Current label assignment + + n_clusters: int + Number of desired clusters + + distances: array-like, shape (n_samples) + Distance to closest cluster for each sample. + + Returns + ------- + centers: array, shape (n_clusters, n_features) + The resulting centers + """ + n_features = X.shape[1] + + cdef np.npy_intp cluster_id + + cdef np.ndarray[DOUBLE, ndim=1] data = X.data + cdef np.ndarray[int, ndim=1] indices = X.indices + cdef np.ndarray[int, ndim=1] indptr = X.indptr + + cdef np.ndarray[DOUBLE, ndim=2, mode="c"] centers = \ + np.zeros((n_clusters, n_features)) + cdef np.ndarray[np.npy_intp, ndim=1] far_from_centers + cdef np.ndarray[np.npy_intp, ndim=1, mode="c"] n_samples_in_cluster = \ + bincount(labels, minlength=n_clusters) + cdef np.ndarray[np.npy_intp, ndim=1, mode="c"] empty_clusters = \ + np.where(n_samples_in_cluster == 0)[0] + + # maybe also relocate small clusters? + + if empty_clusters.shape[0] > 0: + # find points to reassign empty clusters to + far_from_centers = distances.argsort()[::-1] + + for i in range(empty_clusters.shape[0]): + cluster_id = empty_clusters[i] + + # XXX two relocated clusters could be close to each other + centers[cluster_id] = 0. + add_row_csr(data, indices, indptr, far_from_centers[i], + centers[cluster_id]) + n_samples_in_cluster[cluster_id] = 1 - for j in range(X_indptr[i], X_indptr[i + 1]): - sum_ += X_data[j] * X_data[j] + for i in range(labels.shape[0]): + add_row_csr(data, indices, indptr, i, centers[labels[i]]) - if with_sqrt: - sum_ = sqrt(sum_) + centers /= n_samples_in_cluster[:, np.newaxis] - norms[i] = sum_ - return norms + return centers diff --git a/sklearn/cluster/affinity_propagation_.py b/sklearn/cluster/affinity_propagation_.py index d75bbde8b149f..3f3745b657101 100644 --- a/sklearn/cluster/affinity_propagation_.py +++ b/sklearn/cluster/affinity_propagation_.py @@ -5,28 +5,29 @@ # Author: Alexandre Gramfort alexandre.gramfort@inria.fr # Gael Varoquaux gael.varoquaux@normalesup.org -# License: BSD +# License: BSD 3 clause import numpy as np -import warnings from ..base import BaseEstimator, ClusterMixin -from ..utils import as_float_array +from ..utils import as_float_array, check_array +from ..utils.validation import check_is_fitted from ..metrics import euclidean_distances +from ..metrics import pairwise_distances_argmin -def affinity_propagation(S, preference=None, p=None, convergence_iter=15, - convit=None, max_iter=200, - damping=0.5, copy=True, verbose=False): +def affinity_propagation(S, preference=None, convergence_iter=15, max_iter=200, + damping=0.5, copy=True, verbose=False, + return_n_iter=False): """Perform Affinity Propagation Clustering of data Parameters ---------- - S: array [n_samples, n_samples] + S : array-like, shape (n_samples, n_samples) Matrix of similarities between points - preference: array [n_samples,] or float, optional, default: None + preference : array-like, shape (n_samples,) or float, optional Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, i.e. of clusters, is influenced by the input preferences @@ -35,35 +36,42 @@ def affinity_propagation(S, preference=None, p=None, convergence_iter=15, number of clusters). For a smaller amount of clusters, this can be set to the minimum value of the similarities. - convergence_iter: int, optional, default: 15 + convergence_iter : int, optional, default: 15 Number of iterations with no change in the number of estimated clusters that stops the convergence. - max_iter: int, optional, default: 200 + max_iter : int, optional, default: 200 Maximum number of iterations - damping: float, optional, default: 200 + damping : float, optional, default: 0.5 Damping factor between 0.5 and 1. - copy: boolean, optional, default: True + copy : boolean, optional, default: True If copy is False, the affinity matrix is modified inplace by the algorithm, for memory efficiency - verbose: boolean, optional, default: False + verbose : boolean, optional, default: False The verbosity level + return_n_iter : bool, default False + Whether or not to return the number of iterations. + Returns ------- - cluster_centers_indices: array [n_clusters] + cluster_centers_indices : array, shape (n_clusters,) index of clusters centers - labels : array [n_samples] + labels : array, shape (n_samples,) cluster labels for each point + n_iter : int + number of iterations run. Returned only if `return_n_iter` is + set to True. + Notes ----- - See examples/plot_affinity_propagation.py for an example. + See examples/cluster/plot_affinity_propagation.py for an example. References ---------- @@ -71,25 +79,13 @@ def affinity_propagation(S, preference=None, p=None, convergence_iter=15, Between Data Points", Science Feb. 2007 """ S = as_float_array(S, copy=copy) - if convit is not None: - warnings.warn("``convit`` is deprecated and will be removed in" - "version 0.14. Use ``convergence_iter`` instead", - DeprecationWarning) - convergence_iter = convit - n_samples = S.shape[0] if S.shape[0] != S.shape[1]: - raise ValueError("S must be a square array (shape=%r)" % S.shape) - - if not p is None: - warnings.warn("p is deprecated and will be removed in version 0.14." - " Use ``preference`` instead.", DeprecationWarning) - preference = p + raise ValueError("S must be a square array (shape=%s)" % repr(S.shape)) if preference is None: preference = np.median(S) - if damping < 0.5 or damping >= 1: raise ValueError('damping must be >= 0.5 and < 1') @@ -100,10 +96,12 @@ def affinity_propagation(S, preference=None, p=None, convergence_iter=15, A = np.zeros((n_samples, n_samples)) R = np.zeros((n_samples, n_samples)) # Initialize messages + # Intermediate results + tmp = np.zeros((n_samples, n_samples)) # Remove degeneracies - S += (np.finfo(np.double).eps * S + np.finfo(np.double).tiny * 100) * \ - random_state.randn(n_samples, n_samples) + S += ((np.finfo(np.double).eps * S + np.finfo(np.double).tiny * 100) * + random_state.randn(n_samples, n_samples)) # Execute parallel affinity propagation updates e = np.zeros((n_samples, convergence_iter)) @@ -111,35 +109,36 @@ def affinity_propagation(S, preference=None, p=None, convergence_iter=15, ind = np.arange(n_samples) for it in range(max_iter): - # Compute responsibilities - Rold = R.copy() - AS = A + S - - I = np.argmax(AS, axis=1) - Y = AS[np.arange(n_samples), I] # np.max(AS, axis=1) - - AS[ind, I[ind]] = - np.finfo(np.double).max - - Y2 = np.max(AS, axis=1) - R = S - Y[:, np.newaxis] - - R[ind, I[ind]] = S[ind, I[ind]] - Y2[ind] - - R = (1 - damping) * R + damping * Rold # Damping - - # Compute availabilities - Aold = A - Rp = np.maximum(R, 0) - Rp.flat[::n_samples + 1] = R.flat[::n_samples + 1] - - A = np.sum(Rp, axis=0)[np.newaxis, :] - Rp - - dA = np.diag(A) - A = np.minimum(A, 0) - - A.flat[::n_samples + 1] = dA - - A = (1 - damping) * A + damping * Aold # Damping + # tmp = A + S; compute responsibilities + np.add(A, S, tmp) + I = np.argmax(tmp, axis=1) + Y = tmp[ind, I] # np.max(A + S, axis=1) + tmp[ind, I] = -np.inf + Y2 = np.max(tmp, axis=1) + + # tmp = Rnew + np.subtract(S, Y[:, None], tmp) + tmp[ind, I] = S[ind, I] - Y2 + + # Damping + tmp *= 1 - damping + R *= damping + R += tmp + + # tmp = Rp; compute availabilities + np.maximum(R, 0, tmp) + tmp.flat[::n_samples + 1] = R.flat[::n_samples + 1] + + # tmp = -Anew + tmp -= np.sum(tmp, axis=0) + dA = np.diag(tmp).copy() + tmp.clip(0, np.inf, tmp) + tmp.flat[::n_samples + 1] = dA + + # Damping + tmp *= 1 - damping + A *= damping + A -= tmp # Check for convergence E = (np.diag(A) + np.diag(R)) > 0 @@ -148,15 +147,15 @@ def affinity_propagation(S, preference=None, p=None, convergence_iter=15, if it >= convergence_iter: se = np.sum(e, axis=1) - unconverged = np.sum((se == convergence_iter) +\ - (se == 0)) != n_samples + unconverged = (np.sum((se == convergence_iter) + (se == 0)) + != n_samples) if (not unconverged and (K > 0)) or (it == max_iter): if verbose: - print "Converged after %d iterations." % it + print("Converged after %d iterations." % it) break else: if verbose: - print "Did not converged" + print("Did not converge") I = np.where(np.diag(A + R) > 0)[0] K = I.size # Identify exemplars @@ -181,59 +180,68 @@ def affinity_propagation(S, preference=None, p=None, convergence_iter=15, cluster_centers_indices = None labels.fill(np.nan) - return cluster_centers_indices, labels + if return_n_iter: + return cluster_centers_indices, labels, it + 1 + else: + return cluster_centers_indices, labels ############################################################################### class AffinityPropagation(BaseEstimator, ClusterMixin): - """Perform Affinity Propagation Clustering of data + """Perform Affinity Propagation Clustering of data. Parameters ---------- - damping: float, optional, default: 0.5 + damping : float, optional, default: 0.5 Damping factor between 0.5 and 1. - convergence_iter: int, optional, default: 15 + convergence_iter : int, optional, default: 15 Number of iterations with no change in the number of estimated clusters that stops the convergence. - max_iter: int, optional, default: 200 - Maximum number of iterations + max_iter : int, optional, default: 200 + Maximum number of iterations. - copy: boolean, optional, default: True + copy : boolean, optional, default: True Make a copy of input data. - preference: array [n_samples,] or float, optional, default: None + preference : array-like, shape (n_samples,) or float, optional Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, ie of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities. - affinity: string, optional, default=``euclidean`` + affinity : string, optional, default=``euclidean`` Which affinity to use. At the moment ``precomputed`` and ``euclidean`` are supported. ``euclidean`` uses the negative squared euclidean distance between points. - verbose: boolean, optional, default: False + verbose : boolean, optional, default: False Whether to be verbose. Attributes ---------- - `cluster_centers_indices_` : array, [n_clusters] + cluster_centers_indices_ : array, shape (n_clusters,) Indices of cluster centers - `labels_` : array, [n_samples] + cluster_centers_ : array, shape (n_clusters, n_features) + Cluster centers (if affinity != ``precomputed``). + + labels_ : array, shape (n_samples,) Labels of each point - `affinity_matrix_` : array-like, [n_samples, n_samples] + affinity_matrix_ : array, shape (n_samples, n_samples) Stores the affinity matrix used in ``fit``. + n_iter_ : int + Number of iterations taken to converge. + Notes ----- - See examples/plot_affinity_propagation.py for an example. + See examples/cluster/plot_affinity_propagation.py for an example. The algorithmic complexity of affinity propagation is quadratic in the number of points. @@ -246,60 +254,69 @@ class AffinityPropagation(BaseEstimator, ClusterMixin): """ def __init__(self, damping=.5, max_iter=200, convergence_iter=15, - convit=None, copy=True, - preference=None, p=None, affinity='euclidean', verbose=False): - - if convit is not None: - warnings.warn("``convit`` is deprectaed and will be removed in " - "version 0.14. Use ``convergence_iter`` " - "instead", DeprecationWarning) - convergence_iter = convit + copy=True, preference=None, affinity='euclidean', + verbose=False): self.damping = damping self.max_iter = max_iter self.convergence_iter = convergence_iter self.copy = copy self.verbose = verbose - if not p is None: - warnings.warn("p is deprecated and will be removed in version 0.14" - ". Use ``preference`` instead.", DeprecationWarning) - preference = p - self.preference = preference self.affinity = affinity @property def _pairwise(self): - return self.affinity is "precomputed" + return self.affinity == "precomputed" - def fit(self, X): + def fit(self, X, y=None): """ Create affinity matrix from negative euclidean distances, then apply affinity propagation clustering. Parameters ---------- - X: array [n_samples, n_features] or [n_samples, n_samples] + X: array-like, shape (n_samples, n_features) or (n_samples, n_samples) Data matrix or, if affinity is ``precomputed``, matrix of similarities / affinities. """ - - if X.shape[0] == X.shape[1] and not self._pairwise: - warnings.warn("The API of AffinityPropagation has changed." - "Now ``fit`` constructs an affinity matrix from the data." - "To use a custom affinity matrix, set " - "``affinity=precomputed``.") - if self.affinity is "precomputed": + X = check_array(X, accept_sparse='csr') + if self.affinity == "precomputed": self.affinity_matrix_ = X - elif self.affinity is "euclidean": + elif self.affinity == "euclidean": self.affinity_matrix_ = -euclidean_distances(X, squared=True) else: raise ValueError("Affinity must be 'precomputed' or " - "'euclidean'. Got %s instead" % str(self.affinity)) + "'euclidean'. Got %s instead" + % str(self.affinity)) + + self.cluster_centers_indices_, self.labels_, self.n_iter_ = \ + affinity_propagation( + self.affinity_matrix_, self.preference, max_iter=self.max_iter, + convergence_iter=self.convergence_iter, damping=self.damping, + copy=self.copy, verbose=self.verbose, return_n_iter=True) + + if self.affinity != "precomputed": + self.cluster_centers_ = X[self.cluster_centers_indices_].copy() - self.cluster_centers_indices_, self.labels_ = affinity_propagation( - self.affinity_matrix_, self.preference, - max_iter=self.max_iter, - convergence_iter=self.convergence_iter, - damping=self.damping, copy=self.copy, verbose=self.verbose) return self + + def predict(self, X): + """Predict the closest cluster each sample in X belongs to. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + New data to predict. + + Returns + ------- + labels : array, shape (n_samples,) + Index of the cluster each sample belongs to. + """ + check_is_fitted(self, "cluster_centers_indices_") + if not hasattr(self, "cluster_centers_"): + raise ValueError("Predict method is not supported when " + "affinity='precomputed'.") + + return pairwise_distances_argmin(X, self.cluster_centers_) diff --git a/sklearn/cluster/bicluster.py b/sklearn/cluster/bicluster.py new file mode 100644 index 0000000000000..7a32764a6cd1e --- /dev/null +++ b/sklearn/cluster/bicluster.py @@ -0,0 +1,490 @@ +"""Spectral biclustering algorithms. + +Authors : Kemal Eren +License: BSD 3 clause + +""" +from abc import ABCMeta, abstractmethod + +import numpy as np + +from scipy.sparse import dia_matrix +from scipy.sparse import issparse + +from . import KMeans, MiniBatchKMeans +from ..base import BaseEstimator, BiclusterMixin +from ..externals import six +from ..utils.arpack import eigsh, svds + +from ..utils.extmath import (make_nonnegative, norm, randomized_svd, + safe_sparse_dot) + +from ..utils.validation import assert_all_finite, check_array + + +__all__ = ['SpectralCoclustering', + 'SpectralBiclustering'] + + +def _scale_normalize(X): + """Normalize ``X`` by scaling rows and columns independently. + + Returns the normalized matrix and the row and column scaling + factors. + + """ + X = make_nonnegative(X) + row_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=1))).squeeze() + col_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=0))).squeeze() + row_diag = np.where(np.isnan(row_diag), 0, row_diag) + col_diag = np.where(np.isnan(col_diag), 0, col_diag) + if issparse(X): + n_rows, n_cols = X.shape + r = dia_matrix((row_diag, [0]), shape=(n_rows, n_rows)) + c = dia_matrix((col_diag, [0]), shape=(n_cols, n_cols)) + an = r * X * c + else: + an = row_diag[:, np.newaxis] * X * col_diag + return an, row_diag, col_diag + + +def _bistochastic_normalize(X, max_iter=1000, tol=1e-5): + """Normalize rows and columns of ``X`` simultaneously so that all + rows sum to one constant and all columns sum to a different + constant. + + """ + # According to paper, this can also be done more efficiently with + # deviation reduction and balancing algorithms. + X = make_nonnegative(X) + X_scaled = X + dist = None + for _ in range(max_iter): + X_new, _, _ = _scale_normalize(X_scaled) + if issparse(X): + dist = norm(X_scaled.data - X.data) + else: + dist = norm(X_scaled - X_new) + X_scaled = X_new + if dist is not None and dist < tol: + break + return X_scaled + + +def _log_normalize(X): + """Normalize ``X`` according to Kluger's log-interactions scheme.""" + X = make_nonnegative(X, min_value=1) + if issparse(X): + raise ValueError("Cannot compute log of a sparse matrix," + " because log(x) diverges to -infinity as x" + " goes to 0.") + L = np.log(X) + row_avg = L.mean(axis=1)[:, np.newaxis] + col_avg = L.mean(axis=0) + avg = L.mean() + return L - row_avg - col_avg + avg + + +class BaseSpectral(six.with_metaclass(ABCMeta, BaseEstimator, + BiclusterMixin)): + """Base class for spectral biclustering.""" + + @abstractmethod + def __init__(self, n_clusters=3, svd_method="randomized", + n_svd_vecs=None, mini_batch=False, init="k-means++", + n_init=10, n_jobs=1, random_state=None): + self.n_clusters = n_clusters + self.svd_method = svd_method + self.n_svd_vecs = n_svd_vecs + self.mini_batch = mini_batch + self.init = init + self.n_init = n_init + self.n_jobs = n_jobs + self.random_state = random_state + + def _check_parameters(self): + legal_svd_methods = ('randomized', 'arpack') + if self.svd_method not in legal_svd_methods: + raise ValueError("Unknown SVD method: '{0}'. svd_method must be" + " one of {1}.".format(self.svd_method, + legal_svd_methods)) + + def fit(self, X): + """Creates a biclustering for X. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + + """ + X = check_array(X, accept_sparse='csr', dtype=np.float64) + self._check_parameters() + self._fit(X) + + def _svd(self, array, n_components, n_discard): + """Returns first `n_components` left and right singular + vectors u and v, discarding the first `n_discard`. + + """ + if self.svd_method == 'randomized': + kwargs = {} + if self.n_svd_vecs is not None: + kwargs['n_oversamples'] = self.n_svd_vecs + u, _, vt = randomized_svd(array, n_components, + random_state=self.random_state, + **kwargs) + + elif self.svd_method == 'arpack': + u, _, vt = svds(array, k=n_components, ncv=self.n_svd_vecs) + if np.any(np.isnan(vt)): + # some eigenvalues of A * A.T are negative, causing + # sqrt() to be np.nan. This causes some vectors in vt + # to be np.nan. + _, v = eigsh(safe_sparse_dot(array.T, array), + ncv=self.n_svd_vecs) + vt = v.T + if np.any(np.isnan(u)): + _, u = eigsh(safe_sparse_dot(array, array.T), + ncv=self.n_svd_vecs) + + assert_all_finite(u) + assert_all_finite(vt) + u = u[:, n_discard:] + vt = vt[n_discard:] + return u, vt.T + + def _k_means(self, data, n_clusters): + if self.mini_batch: + model = MiniBatchKMeans(n_clusters, + init=self.init, + n_init=self.n_init, + random_state=self.random_state) + else: + model = KMeans(n_clusters, init=self.init, + n_init=self.n_init, n_jobs=self.n_jobs, + random_state=self.random_state) + model.fit(data) + centroid = model.cluster_centers_ + labels = model.labels_ + return centroid, labels + + +class SpectralCoclustering(BaseSpectral): + """Spectral Co-Clustering algorithm (Dhillon, 2001). + + Clusters rows and columns of an array `X` to solve the relaxed + normalized cut of the bipartite graph created from `X` as follows: + the edge between row vertex `i` and column vertex `j` has weight + `X[i, j]`. + + The resulting bicluster structure is block-diagonal, since each + row and each column belongs to exactly one bicluster. + + Supports sparse matrices, as long as they are nonnegative. + + Parameters + ---------- + n_clusters : integer, optional, default: 3 + The number of biclusters to find. + + svd_method : string, optional, default: 'randomized' + Selects the algorithm for finding singular vectors. May be + 'randomized' or 'arpack'. If 'randomized', use + :func:`sklearn.utils.extmath.randomized_svd`, which may be faster + for large matrices. If 'arpack', use + :func:`sklearn.utils.arpack.svds`, which is more accurate, but + possibly slower in some cases. + + n_svd_vecs : int, optional, default: None + Number of vectors to use in calculating the SVD. Corresponds + to `ncv` when `svd_method=arpack` and `n_oversamples` when + `svd_method` is 'randomized`. + + mini_batch : bool, optional, default: False + Whether to use mini-batch k-means, which is faster but may get + different results. + + init : {'k-means++', 'random' or an ndarray} + Method for initialization of k-means algorithm; defaults to + 'k-means++'. + + n_init : int, optional, default: 10 + Number of random initializations that are tried with the + k-means algorithm. + + If mini-batch k-means is used, the best initialization is + chosen and the algorithm runs once. Otherwise, the algorithm + is run for each initialization and the best solution chosen. + + n_jobs : int, optional, default: 1 + The number of jobs to use for the computation. This works by breaking + down the pairwise matrix into n_jobs even slices and computing them in + parallel. + + If -1 all CPUs are used. If 1 is given, no parallel computing code is + used at all, which is useful for debugging. For n_jobs below -1, + (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one + are used. + + random_state : int seed, RandomState instance, or None (default) + A pseudo random number generator used by the K-Means + initialization. + + Attributes + ---------- + rows_ : array-like, shape (n_row_clusters, n_rows) + Results of the clustering. `rows[i, r]` is True if + cluster `i` contains row `r`. Available only after calling ``fit``. + + columns_ : array-like, shape (n_column_clusters, n_columns) + Results of the clustering, like `rows`. + + row_labels_ : array-like, shape (n_rows,) + The bicluster label of each row. + + column_labels_ : array-like, shape (n_cols,) + The bicluster label of each column. + + References + ---------- + + * Dhillon, Inderjit S, 2001. `Co-clustering documents and words using + bipartite spectral graph partitioning + `__. + + """ + def __init__(self, n_clusters=3, svd_method='randomized', + n_svd_vecs=None, mini_batch=False, init='k-means++', + n_init=10, n_jobs=1, random_state=None): + super(SpectralCoclustering, self).__init__(n_clusters, + svd_method, + n_svd_vecs, + mini_batch, + init, + n_init, + n_jobs, + random_state) + + def _fit(self, X): + normalized_data, row_diag, col_diag = _scale_normalize(X) + n_sv = 1 + int(np.ceil(np.log2(self.n_clusters))) + u, v = self._svd(normalized_data, n_sv, n_discard=1) + z = np.vstack((row_diag[:, np.newaxis] * u, + col_diag[:, np.newaxis] * v)) + + _, labels = self._k_means(z, self.n_clusters) + + n_rows = X.shape[0] + self.row_labels_ = labels[:n_rows] + self.column_labels_ = labels[n_rows:] + + self.rows_ = np.vstack(self.row_labels_ == c + for c in range(self.n_clusters)) + self.columns_ = np.vstack(self.column_labels_ == c + for c in range(self.n_clusters)) + + +class SpectralBiclustering(BaseSpectral): + """Spectral biclustering (Kluger, 2003). + + Partitions rows and columns under the assumption that the data has + an underlying checkerboard structure. For instance, if there are + two row partitions and three column partitions, each row will + belong to three biclusters, and each column will belong to two + biclusters. The outer product of the corresponding row and column + label vectors gives this checkerboard structure. + + Parameters + ---------- + n_clusters : integer or tuple (n_row_clusters, n_column_clusters) + The number of row and column clusters in the checkerboard + structure. + + method : string, optional, default: 'bistochastic' + Method of normalizing and converting singular vectors into + biclusters. May be one of 'scale', 'bistochastic', or 'log'. + The authors recommend using 'log'. If the data is sparse, + however, log normalization will not work, which is why the + default is 'bistochastic'. CAUTION: if `method='log'`, the + data must not be sparse. + + n_components : integer, optional, default: 6 + Number of singular vectors to check. + + n_best : integer, optional, default: 3 + Number of best singular vectors to which to project the data + for clustering. + + svd_method : string, optional, default: 'randomized' + Selects the algorithm for finding singular vectors. May be + 'randomized' or 'arpack'. If 'randomized', uses + `sklearn.utils.extmath.randomized_svd`, which may be faster + for large matrices. If 'arpack', uses + `sklearn.utils.arpack.svds`, which is more accurate, but + possibly slower in some cases. + + n_svd_vecs : int, optional, default: None + Number of vectors to use in calculating the SVD. Corresponds + to `ncv` when `svd_method=arpack` and `n_oversamples` when + `svd_method` is 'randomized`. + + mini_batch : bool, optional, default: False + Whether to use mini-batch k-means, which is faster but may get + different results. + + init : {'k-means++', 'random' or an ndarray} + Method for initialization of k-means algorithm; defaults to + 'k-means++'. + + n_init : int, optional, default: 10 + Number of random initializations that are tried with the + k-means algorithm. + + If mini-batch k-means is used, the best initialization is + chosen and the algorithm runs once. Otherwise, the algorithm + is run for each initialization and the best solution chosen. + + n_jobs : int, optional, default: 1 + The number of jobs to use for the computation. This works by breaking + down the pairwise matrix into n_jobs even slices and computing them in + parallel. + + If -1 all CPUs are used. If 1 is given, no parallel computing code is + used at all, which is useful for debugging. For n_jobs below -1, + (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one + are used. + + random_state : int seed, RandomState instance, or None (default) + A pseudo random number generator used by the K-Means + initialization. + + Attributes + ---------- + rows_ : array-like, shape (n_row_clusters, n_rows) + Results of the clustering. `rows[i, r]` is True if + cluster `i` contains row `r`. Available only after calling ``fit``. + + columns_ : array-like, shape (n_column_clusters, n_columns) + Results of the clustering, like `rows`. + + row_labels_ : array-like, shape (n_rows,) + Row partition labels. + + column_labels_ : array-like, shape (n_cols,) + Column partition labels. + + References + ---------- + + * Kluger, Yuval, et. al., 2003. `Spectral biclustering of microarray + data: coclustering genes and conditions + `__. + + """ + def __init__(self, n_clusters=3, method='bistochastic', + n_components=6, n_best=3, svd_method='randomized', + n_svd_vecs=None, mini_batch=False, init='k-means++', + n_init=10, n_jobs=1, random_state=None): + super(SpectralBiclustering, self).__init__(n_clusters, + svd_method, + n_svd_vecs, + mini_batch, + init, + n_init, + n_jobs, + random_state) + self.method = method + self.n_components = n_components + self.n_best = n_best + + def _check_parameters(self): + super(SpectralBiclustering, self)._check_parameters() + legal_methods = ('bistochastic', 'scale', 'log') + if self.method not in legal_methods: + raise ValueError("Unknown method: '{0}'. method must be" + " one of {1}.".format(self.method, legal_methods)) + try: + int(self.n_clusters) + except TypeError: + try: + r, c = self.n_clusters + int(r) + int(c) + except (ValueError, TypeError): + raise ValueError("Incorrect parameter n_clusters has value:" + " {}. It should either be a single integer" + " or an iterable with two integers:" + " (n_row_clusters, n_column_clusters)") + if self.n_components < 1: + raise ValueError("Parameter n_components must be greater than 0," + " but its value is {}".format(self.n_components)) + if self.n_best < 1: + raise ValueError("Parameter n_best must be greater than 0," + " but its value is {}".format(self.n_best)) + if self.n_best > self.n_components: + raise ValueError("n_best cannot be larger than" + " n_components, but {} > {}" + "".format(self.n_best, self.n_components)) + + def _fit(self, X): + n_sv = self.n_components + if self.method == 'bistochastic': + normalized_data = _bistochastic_normalize(X) + n_sv += 1 + elif self.method == 'scale': + normalized_data, _, _ = _scale_normalize(X) + n_sv += 1 + elif self.method == 'log': + normalized_data = _log_normalize(X) + n_discard = 0 if self.method == 'log' else 1 + u, v = self._svd(normalized_data, n_sv, n_discard) + ut = u.T + vt = v.T + + try: + n_row_clusters, n_col_clusters = self.n_clusters + except TypeError: + n_row_clusters = n_col_clusters = self.n_clusters + + best_ut = self._fit_best_piecewise(ut, self.n_best, + n_row_clusters) + + best_vt = self._fit_best_piecewise(vt, self.n_best, + n_col_clusters) + + self.row_labels_ = self._project_and_cluster(X, best_vt.T, + n_row_clusters) + + self.column_labels_ = self._project_and_cluster(X.T, best_ut.T, + n_col_clusters) + + self.rows_ = np.vstack(self.row_labels_ == label + for label in range(n_row_clusters) + for _ in range(n_col_clusters)) + self.columns_ = np.vstack(self.column_labels_ == label + for _ in range(n_row_clusters) + for label in range(n_col_clusters)) + + def _fit_best_piecewise(self, vectors, n_best, n_clusters): + """Find the ``n_best`` vectors that are best approximated by piecewise + constant vectors. + + The piecewise vectors are found by k-means; the best is chosen + according to Euclidean distance. + + """ + def make_piecewise(v): + centroid, labels = self._k_means(v.reshape(-1, 1), n_clusters) + return centroid[labels].ravel() + piecewise_vectors = np.apply_along_axis(make_piecewise, + axis=1, arr=vectors) + dists = np.apply_along_axis(norm, axis=1, + arr=(vectors - piecewise_vectors)) + result = vectors[np.argsort(dists)[:n_best]] + return result + + def _project_and_cluster(self, data, vectors, n_clusters): + """Project ``data`` to ``vectors`` and cluster the result.""" + projected = safe_sparse_dot(data, vectors) + _, labels = self._k_means(projected, n_clusters) + return labels diff --git a/sklearn/cluster/birch.py b/sklearn/cluster/birch.py new file mode 100644 index 0000000000000..1da1a747065f6 --- /dev/null +++ b/sklearn/cluster/birch.py @@ -0,0 +1,608 @@ +# Authors: Manoj Kumar +# Alexandre Gramfort +# Joel Nothman +# License: BSD 3 clause +from __future__ import division + +import warnings +import numpy as np +from scipy import sparse +from math import sqrt + +from ..metrics.pairwise import euclidean_distances +from ..base import TransformerMixin, ClusterMixin, BaseEstimator +from ..externals.six.moves import xrange +from ..utils import check_array +from ..utils.extmath import row_norms, safe_sparse_dot +from ..utils.validation import NotFittedError, check_is_fitted +from .hierarchical import AgglomerativeClustering + + +def _iterate_sparse_X(X): + """This little hack returns a densified row when iterating over a sparse + matrix, insted of constructing a sparse matrix for every row that is + expensive. + """ + n_samples = X.shape[0] + X_indices = X.indices + X_data = X.data + X_indptr = X.indptr + + for i in xrange(n_samples): + row = np.zeros(X.shape[1]) + startptr, endptr = X_indptr[i], X_indptr[i + 1] + nonzero_indices = X_indices[startptr:endptr] + row[nonzero_indices] = X_data[startptr:endptr] + yield row + + +def _split_node(node, threshold, branching_factor): + """The node has to be split if there is no place for a new subcluster + in the node. + 1. Two empty nodes and two empty subclusters are initialized. + 2. The pair of distant subclusters are found. + 3. The properties of the empty subclusters and nodes are updated + according to the nearest distance between the subclusters to the + pair of distant subclusters. + 4. The two nodes are set as children to the two subclusters. + """ + new_subcluster1 = _CFSubcluster() + new_subcluster2 = _CFSubcluster() + new_node1 = _CFNode( + threshold, branching_factor, is_leaf=node.is_leaf, + n_features=node.n_features) + new_node2 = _CFNode( + threshold, branching_factor, is_leaf=node.is_leaf, + n_features=node.n_features) + new_subcluster1.child_ = new_node1 + new_subcluster2.child_ = new_node2 + + if node.is_leaf: + if node.prev_leaf_ is not None: + node.prev_leaf_.next_leaf_ = new_node1 + new_node1.prev_leaf_ = node.prev_leaf_ + new_node1.next_leaf_ = new_node2 + new_node2.prev_leaf_ = new_node1 + new_node2.next_leaf_ = node.next_leaf_ + if node.next_leaf_ is not None: + node.next_leaf_.prev_leaf_ = new_node2 + + dist = euclidean_distances( + node.centroids_, Y_norm_squared=node.squared_norm_, squared=True) + n_clusters = dist.shape[0] + + farthest_idx = np.unravel_index( + dist.argmax(), (n_clusters, n_clusters)) + node1_dist, node2_dist = dist[[farthest_idx]] + + node1_closer = node1_dist < node2_dist + for idx, subcluster in enumerate(node.subclusters_): + if node1_closer[idx]: + new_node1.append_subcluster(subcluster) + new_subcluster1.update(subcluster) + else: + new_node2.append_subcluster(subcluster) + new_subcluster2.update(subcluster) + return new_subcluster1, new_subcluster2 + + +class _CFNode(object): + """Each node in a CFTree is called a CFNode. + + The CFNode can have a maximum of branching_factor + number of CFSubclusters. + + Parameters + ---------- + threshold : float + Threshold needed for a new subcluster to enter a CFSubcluster. + + branching_factor : int + Maximum number of CF subclusters in each node. + + is_leaf : bool + We need to know if the CFNode is a leaf or not, in order to + retrieve the final subclusters. + + n_features : int + The number of features. + + Attributes + ---------- + subclusters_ : array-like + list of subclusters for a particular CFNode. + + prev_leaf_ : _CFNode + prev_leaf. Useful only if is_leaf is True. + + next_leaf_ : _CFNode + next_leaf. Useful only if is_leaf is True. + the final subclusters. + + init_centroids_ : ndarray, shape (branching_factor + 1, n_features) + manipulate ``init_centroids_`` throughout rather than centroids_ since + the centroids are just a view of the ``init_centroids_`` . + + init_sq_norm_ : ndarray, shape (branching_factor + 1,) + manipulate init_sq_norm_ throughout. similar to ``init_centroids_``. + + centroids_ : ndarray + view of ``init_centroids_``. + + squared_norm_ : ndarray + view of ``init_sq_norm_``. + + """ + def __init__(self, threshold, branching_factor, is_leaf, n_features): + self.threshold = threshold + self.branching_factor = branching_factor + self.is_leaf = is_leaf + self.n_features = n_features + + # The list of subclusters, centroids and squared norms + # to manipulate throughout. + self.subclusters_ = [] + self.init_centroids_ = np.zeros((branching_factor + 1, n_features)) + self.init_sq_norm_ = np.zeros((branching_factor + 1)) + self.squared_norm_ = [] + self.prev_leaf_ = None + self.next_leaf_ = None + + def append_subcluster(self, subcluster): + n_samples = len(self.subclusters_) + self.subclusters_.append(subcluster) + self.init_centroids_[n_samples] = subcluster.centroid_ + self.init_sq_norm_[n_samples] = subcluster.sq_norm_ + + # Keep centroids and squared norm as views. In this way + # if we change init_centroids and init_sq_norm_, it is + # sufficient, + self.centroids_ = self.init_centroids_[:n_samples + 1, :] + self.squared_norm_ = self.init_sq_norm_[:n_samples + 1] + + def update_split_subclusters(self, subcluster, + new_subcluster1, new_subcluster2): + """Remove a subcluster from a node and update it with the + split subclusters. + """ + ind = self.subclusters_.index(subcluster) + self.subclusters_[ind] = new_subcluster1 + self.init_centroids_[ind] = new_subcluster1.centroid_ + self.init_sq_norm_[ind] = new_subcluster1.sq_norm_ + self.append_subcluster(new_subcluster2) + + def insert_cf_subcluster(self, subcluster): + """Insert a new subcluster into the node.""" + if not self.subclusters_: + self.append_subcluster(subcluster) + return False + + threshold = self.threshold + branching_factor = self.branching_factor + # We need to find the closest subcluster among all the + # subclusters so that we can insert our new subcluster. + dist_matrix = np.dot(self.centroids_, subcluster.centroid_) + dist_matrix *= -2. + dist_matrix += self.squared_norm_ + closest_index = np.argmin(dist_matrix) + closest_subcluster = self.subclusters_[closest_index] + + # If the subcluster has a child, we need a recursive strategy. + if closest_subcluster.child_ is not None: + split_child = closest_subcluster.child_.insert_cf_subcluster( + subcluster) + + if not split_child: + # If it is determined that the child need not be split, we + # can just update the closest_subcluster + closest_subcluster.update(subcluster) + self.init_centroids_[closest_index] = \ + self.subclusters_[closest_index].centroid_ + self.init_sq_norm_[closest_index] = \ + self.subclusters_[closest_index].sq_norm_ + return False + + # things not too good. we need to redistribute the subclusters in + # our child node, and add a new subcluster in the parent + # subcluster to accomodate the new child. + else: + new_subcluster1, new_subcluster2 = _split_node( + closest_subcluster.child_, threshold, branching_factor) + self.update_split_subclusters( + closest_subcluster, new_subcluster1, new_subcluster2) + + if len(self.subclusters_) > self.branching_factor: + return True + return False + + # good to go! + else: + merged = closest_subcluster.merge_subcluster( + subcluster, self.threshold) + if merged: + self.init_centroids_[closest_index] = \ + closest_subcluster.centroid_ + self.init_sq_norm_[closest_index] = \ + closest_subcluster.sq_norm_ + return False + + # not close to any other subclusters, and we still + # have space, so add. + elif len(self.subclusters_) < self.branching_factor: + self.append_subcluster(subcluster) + return False + + # We do not have enough space nor is it closer to an + # other subcluster. We need to split. + else: + self.append_subcluster(subcluster) + return True + + +class _CFSubcluster(object): + """Each subcluster in a CFNode is called a CFSubcluster. + + A CFSubcluster can have a CFNode has its child. + + Parameters + ---------- + linear_sum : ndarray, shape (n_features,), optional + Sample. This is kept optional to allow initialization of empty + subclusters. + + Attributes + ---------- + n_samples_ : int + Number of samples that belong to each subcluster. + + linear_sum_ : ndarray + Linear sum of all the samples in a subcluster. Prevents holding + all sample data in memory. + + squared_sum_ : float + Sum of the squared l2 norms of all samples belonging to a subcluster. + + centroid_ : ndarray + Centroid of the subcluster. Prevent recomputing of centroids when + ``CFNode.centroids_`` is called. + + child_ : _CFNode + Child Node of the subcluster. Once a given _CFNode is set as the child + of the _CFNode, it is set to ``self.child_``. + + sq_norm_ : ndarray + Squared norm of the subcluster. Used to prevent recomputing when + pairwise minimum distances are computed. + """ + def __init__(self, linear_sum=None): + if linear_sum is None: + self.n_samples_ = 0 + self.squared_sum_ = 0.0 + self.linear_sum_ = 0 + else: + self.n_samples_ = 1 + self.centroid_ = self.linear_sum_ = linear_sum + self.squared_sum_ = self.sq_norm_ = np.dot( + self.linear_sum_, self.linear_sum_) + self.child_ = None + + def update(self, subcluster): + self.n_samples_ += subcluster.n_samples_ + self.linear_sum_ += subcluster.linear_sum_ + self.squared_sum_ += subcluster.squared_sum_ + self.centroid_ = self.linear_sum_ / self.n_samples_ + self.sq_norm_ = np.dot(self.centroid_, self.centroid_) + + def merge_subcluster(self, nominee_cluster, threshold): + """Check if a cluster is worthy enough to be merged. If + yes then merge. + """ + new_ss = self.squared_sum_ + nominee_cluster.squared_sum_ + new_ls = self.linear_sum_ + nominee_cluster.linear_sum_ + new_n = self.n_samples_ + nominee_cluster.n_samples_ + new_centroid = (1 / new_n) * new_ls + new_norm = np.dot(new_centroid, new_centroid) + dot_product = (-2 * new_n) * new_norm + sq_radius = (new_ss + dot_product) / new_n + new_norm + if sq_radius <= threshold ** 2: + (self.n_samples_, self.linear_sum_, self.squared_sum_, + self.centroid_, self.sq_norm_) = \ + new_n, new_ls, new_ss, new_centroid, new_norm + return True + return False + + @property + def radius(self): + """Return radius of the subcluster""" + dot_product = -2 * np.dot(self.linear_sum_, self.centroid_) + return sqrt( + ((self.squared_sum_ + dot_product) / self.n_samples_) + + self.sq_norm_) + + +class Birch(BaseEstimator, TransformerMixin, ClusterMixin): + """Implements the Birch clustering algorithm. + + Every new sample is inserted into the root of the Clustering Feature + Tree. It is then clubbed together with the subcluster that has the + centroid closest to the new sample. This is done recursively till it + ends up at the subcluster of the leaf of the tree has the closest centroid. + + Parameters + ---------- + threshold : float, default 0.5 + The radius of the subcluster obtained by merging a new sample and the + closest subcluster should be lesser than the threshold. Otherwise a new + subcluster is started. + + branching_factor : int, default 50 + Maximum number of CF subclusters in each node. If a new samples enters + such that the number of subclusters exceed the branching_factor then + the node has to be split. The corresponding parent also has to be + split and if the number of subclusters in the parent is greater than + the branching factor, then it has to be split recursively. + + n_clusters : int, instance of sklearn.cluster model, default None + Number of clusters after the final clustering step, which treats the + subclusters from the leaves as new samples. By default, this final + clustering step is not performed and the subclusters are returned + as they are. If a model is provided, the model is fit treating + the subclusters as new samples and the initial data is mapped to the + label of the closest subcluster. If an int is provided, the model + fit is AgglomerativeClustering with n_clusters set to the int. + + compute_labels : bool, default True + Whether or not to compute labels for each fit. + + copy : bool, default True + Whether or not to make a copy of the given data. If set to False, + the initial data will be overwritten. + + Attributes + ---------- + root_ : _CFNode + Root of the CFTree. + + dummy_leaf_ : _CFNode + Start pointer to all the leaves. + + subcluster_centers_ : ndarray, + Centroids of all subclusters read directly from the leaves. + + subcluster_labels_ : ndarray, + Labels assigned to the centroids of the subclusters after + they are clustered globally. + + labels_ : ndarray, shape (n_samples,) + Array of labels assigned to the input data. + if partial_fit is used instead of fit, they are assigned to the + last batch of data. + + Examples + -------- + >>> from sklearn.cluster import Birch + >>> X = [[0, 1], [0.3, 1], [-0.3, 1], [0, -1], [0.3, -1], [-0.3, -1]] + >>> brc = Birch(branching_factor=50, n_clusters=None, threshold=0.5, + ... compute_labels=True) + >>> brc.fit(X) + Birch(branching_factor=50, compute_labels=True, copy=True, n_clusters=None, + threshold=0.5) + >>> brc.predict(X) + array([0, 0, 0, 1, 1, 1]) + + References + ---------- + * Tian Zhang, Raghu Ramakrishnan, Maron Livny + BIRCH: An efficient data clustering method for large databases. + http://www.cs.sfu.ca/CourseCentral/459/han/papers/zhang96.pdf + + * Roberto Perdisci + JBirch - Java implementation of BIRCH clustering algorithm + https://code.google.com/p/jbirch/ + """ + + def __init__(self, threshold=0.5, branching_factor=50, n_clusters=3, + compute_labels=True, copy=True): + self.threshold = threshold + self.branching_factor = branching_factor + self.n_clusters = n_clusters + self.compute_labels = compute_labels + self.copy = copy + + def fit(self, X, y=None): + """ + Build a CF Tree for the input data. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Input data. + """ + self.fit_, self.partial_fit_ = True, False + return self._fit(X) + + def _fit(self, X): + X = check_array(X, accept_sparse='csr', copy=self.copy) + threshold = self.threshold + branching_factor = self.branching_factor + + if branching_factor <= 1: + raise ValueError("Branching_factor should be greater than one.") + n_samples, n_features = X.shape + + # If partial_fit is called for the first time or fit is called, we + # start a new tree. + partial_fit = getattr(self, 'partial_fit_') + has_root = getattr(self, 'root_', None) + if getattr(self, 'fit_') or (partial_fit and not has_root): + # The first root is the leaf. Manipulate this object throughout. + self.root_ = _CFNode(threshold, branching_factor, is_leaf=True, + n_features=n_features) + + # To enable getting back subclusters. + self.dummy_leaf_ = _CFNode(threshold, branching_factor, + is_leaf=True, n_features=n_features) + self.dummy_leaf_.next_leaf_ = self.root_ + self.root_.prev_leaf_ = self.dummy_leaf_ + + # Cannot vectorize. Enough to convince to use cython. + if not sparse.issparse(X): + iter_func = iter + else: + iter_func = _iterate_sparse_X + + for sample in iter_func(X): + subcluster = _CFSubcluster(linear_sum=sample) + split = self.root_.insert_cf_subcluster(subcluster) + + if split: + new_subcluster1, new_subcluster2 = _split_node( + self.root_, threshold, branching_factor) + del self.root_ + self.root_ = _CFNode(threshold, branching_factor, + is_leaf=False, + n_features=n_features) + self.root_.append_subcluster(new_subcluster1) + self.root_.append_subcluster(new_subcluster2) + + centroids = np.concatenate([ + leaf.centroids_ for leaf in self._get_leaves()]) + self.subcluster_centers_ = centroids + + self._global_clustering(X) + return self + + def _get_leaves(self): + """ + Retrieve the leaves of the CF Node. + + Returns + ------- + leaves: array-like + List of the leaf nodes. + """ + leaf_ptr = self.dummy_leaf_.next_leaf_ + leaves = [] + while leaf_ptr is not None: + leaves.append(leaf_ptr) + leaf_ptr = leaf_ptr.next_leaf_ + return leaves + + def partial_fit(self, X=None, y=None): + """ + Online learning. Prevents rebuilding of CFTree from scratch. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features), None + Input data. If X is not provided, only the global clustering + step is done. + """ + self.partial_fit_, self.fit_ = True, False + if X is None: + # Perform just the final global clustering step. + self._global_clustering() + return self + else: + self._check_fit(X) + return self._fit(X) + + def _check_fit(self, X): + is_fitted = hasattr(self, 'subcluster_centers_') + + # Called by partial_fit, before fitting. + has_partial_fit = hasattr(self, 'partial_fit_') + + # Should raise an error if one does not fit before predicting. + if not (is_fitted or has_partial_fit): + raise NotFittedError("Fit training data before predicting") + + if is_fitted and X.shape[1] != self.subcluster_centers_.shape[1]: + raise ValueError( + "Training data and predicted data do " + "not have same number of features.") + + def predict(self, X): + """ + Predict data using the ``centroids_`` of subclusters. + + Avoid computation of the row norms of X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Input data. + + Returns + ------- + labels: ndarray, shape(n_samples) + Labelled data. + """ + X = check_array(X, accept_sparse='csr') + self._check_fit(X) + reduced_distance = safe_sparse_dot(X, self.subcluster_centers_.T) + reduced_distance *= -2 + reduced_distance += self._subcluster_norms + return self.subcluster_labels_[np.argmin(reduced_distance, axis=1)] + + def transform(self, X, y=None): + """ + Transform X into subcluster centroids dimension. + + Each dimension represents the distance from the sample point to each + cluster centroid. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Input data. + + Returns + ------- + X_trans : {array-like, sparse matrix}, shape (n_samples, n_clusters) + Transformed data. + """ + check_is_fitted(self, 'subcluster_centers_') + return euclidean_distances(X, self.subcluster_centers_) + + def _global_clustering(self, X=None): + """ + Global clustering for the subclusters obtained after fitting + """ + clusterer = self.n_clusters + centroids = self.subcluster_centers_ + compute_labels = (X is not None) and self.compute_labels + + # Preprocessing for the global clustering. + not_enough_centroids = False + if isinstance(clusterer, int): + clusterer = AgglomerativeClustering( + n_clusters=self.n_clusters) + # There is no need to perform the global clustering step. + if len(centroids) < self.n_clusters: + not_enough_centroids = True + elif (clusterer is not None and not + hasattr(clusterer, 'fit_predict')): + raise ValueError("n_clusters should be an instance of " + "ClusterMixin or an int") + + # To use in predict to avoid recalculation. + self._subcluster_norms = row_norms( + self.subcluster_centers_, squared=True) + + if clusterer is None or not_enough_centroids: + self.subcluster_labels_ = np.arange(len(centroids)) + if not_enough_centroids: + warnings.warn( + "Number of subclusters found (%d) by Birch is less " + "than (%d). Decrease the threshold." + % (len(centroids), self.n_clusters)) + else: + # The global clustering step that clusters the subclusters of + # the leaves. It assumes the centroids of the subclusters as + # samples and finds the final centroids. + self.subcluster_labels_ = clusterer.fit_predict( + self.subcluster_centers_) + + if compute_labels: + self.labels_ = self.predict(X) diff --git a/sklearn/cluster/dbscan_.py b/sklearn/cluster/dbscan_.py index ab7c736814c85..980764959ff1e 100644 --- a/sklearn/cluster/dbscan_.py +++ b/sklearn/cluster/dbscan_.py @@ -4,46 +4,76 @@ """ # Author: Robert Layton +# Joel Nothman # -# License: BSD +# License: BSD 3 clause import warnings + import numpy as np from ..base import BaseEstimator, ClusterMixin from ..metrics import pairwise_distances -from ..utils import check_random_state +from ..utils import check_array, check_consistent_length +from ..neighbors import NearestNeighbors -def dbscan(X, eps=0.5, min_samples=5, metric='euclidean', +def dbscan(X, eps=0.5, min_samples=5, metric='minkowski', + algorithm='auto', leaf_size=30, p=2, sample_weight=None, random_state=None): """Perform DBSCAN clustering from vector array or distance matrix. Parameters ---------- - X: array [n_samples, n_samples] or [n_samples, n_features] - Array of distances between samples, or a feature array. - The array is treated as a feature array unless the metric is given as - 'precomputed'. - eps: float, optional + X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ + array of shape (n_samples, n_samples) + A feature array, or array of distances between samples if + ``metric='precomputed'``. + + eps : float, optional The maximum distance between two samples for them to be considered as in the same neighborhood. - min_samples: int, optional - The number of samples in a neighborhood for a point to be considered - as a core point. - metric: string, or callable + + min_samples : int, optional + The number of samples (or total weight) in a neighborhood for a point + to be considered as a core point. This includes the point itself. + + metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of - the options allowed by metrics.pairwise.calculate_distance for its + the options allowed by metrics.pairwise.pairwise_distances for its metric parameter. If metric is "precomputed", X is assumed to be a distance matrix and must be square. + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional + The algorithm to be used by the NearestNeighbors module + to compute pointwise distances and find nearest neighbors. + See NearestNeighbors module documentation for details. + + leaf_size : int, optional (default = 30) + Leaf size passed to BallTree or cKDTree. This can affect the speed + of the construction and query, as well as the memory required + to store the tree. The optimal value depends + on the nature of the problem. + + p : float, optional + The power of the Minkowski metric to be used to calculate distance + between points. + + sample_weight : array, shape (n_samples,), optional + Weight of each sample, such that a sample with a weight of at least + ``min_samples`` is by itself a core sample; a sample with negative + weight may inhibit its eps-neighbor from being core. + Note that weights are absolute, and default to 1. + random_state: numpy.RandomState, optional - The generator used to initialize the centers. Defaults to numpy.random. + Deprecated and ignored as of version 0.16, will be removed in version + 0.18. DBSCAN does not use random initialization. Returns ------- - core_samples: array [n_core_samples] + core_samples : array [n_core_samples] Indices of core samples. labels : array [n_samples] @@ -51,58 +81,84 @@ def dbscan(X, eps=0.5, min_samples=5, metric='euclidean', Notes ----- - See examples/plot_dbscan.py for an example. + See examples/cluster/plot_dbscan.py for an example. + + This implementation bulk-computes all neighborhood queries, which increases + the memory complexity to O(n.d) where d is the average number of neighbors, + while original DBSCAN had memory complexity O(n). References ---------- - Ester, M., H. P. Kriegel, J. Sander, and X. Xu, “A Density-Based - Algorithm for Discovering Clusters in Large Spatial Databases with Noise”. + Ester, M., H. P. Kriegel, J. Sander, and X. Xu, "A Density-Based + Algorithm for Discovering Clusters in Large Spatial Databases with Noise". In: Proceedings of the 2nd International Conference on Knowledge Discovery - and Data Mining, Portland, OR, AAAI Press, pp. 226–231. 1996 + and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 """ - X = np.asarray(X) - n = X.shape[0] - # If index order not given, create random order. - random_state = check_random_state(random_state) - index_order = np.arange(n) - random_state.shuffle(index_order) - D = pairwise_distances(X, metric=metric) + if not eps > 0.0: + raise ValueError("eps must be positive.") + if random_state is not None: + warnings.warn("The parameter random_state is deprecated in 0.16 " + "and will be removed in version 0.18. " + "DBSCAN is deterministic except for rare border cases.", + category=DeprecationWarning) + + X = check_array(X, accept_sparse='csr') + if sample_weight is not None: + sample_weight = np.asarray(sample_weight) + check_consistent_length(X, sample_weight) + # Calculate neighborhood for all samples. This leaves the original point - # in, which needs to be considered later (i.e. point i is the + # in, which needs to be considered later (i.e. point i is in the # neighborhood of point i. While True, its useless information) - neighborhoods = [np.where(x <= eps)[0] for x in D] + if metric == 'precomputed': + D = pairwise_distances(X, metric=metric) + neighborhoods = [np.where(x <= eps)[0] for x in D] + else: + neighbors_model = NearestNeighbors(radius=eps, algorithm=algorithm, + leaf_size=leaf_size, + metric=metric, p=p) + neighbors_model.fit(X) + # This has worst case O(n^2) memory complexity + neighborhoods = neighbors_model.radius_neighbors(X, eps, + return_distance=False) + neighborhoods = np.array(neighborhoods) + if sample_weight is None: + n_neighbors = np.array([len(neighbors) for neighbors in neighborhoods]) + else: + n_neighbors = np.array([np.sum(sample_weight[neighbors]) + for neighbors in neighborhoods]) + # Initially, all samples are noise. - labels = -np.ones(n) + labels = -np.ones(X.shape[0], dtype=np.int) + # A list of all core samples found. - core_samples = [] + core_samples = np.flatnonzero(n_neighbors >= min_samples) + # label_num is the label given to the new cluster label_num = 0 + # Look at all samples and determine if they are core. # If they are then build a new cluster from them. - for index in index_order: - if labels[index] != -1 or len(neighborhoods[index]) < min_samples: - # This point is already classified, or not enough for a core point. + for index in core_samples: + # Already classified + if labels[index] != -1: continue - core_samples.append(index) + labels[index] = label_num + # candidates for new core samples in the cluster. candidates = [index] while len(candidates) > 0: - new_candidates = [] + # The tolist() is needed for NumPy 1.6. + cand_neighbors = np.concatenate(np.take(neighborhoods, candidates, + axis=0).tolist()) + cand_neighbors = np.unique(cand_neighbors) + noise = cand_neighbors[labels.take(cand_neighbors) == -1] + labels[noise] = label_num # A candidate is a core point in the current cluster that has # not yet been used to expand the current cluster. - for c in candidates: - noise = np.where(labels[neighborhoods[c]] == -1)[0] - noise = neighborhoods[c][noise] - labels[noise] = label_num - for neighbor in noise: - # check if its a core point as well - if len(neighborhoods[neighbor]) >= min_samples: - # is new core point - new_candidates.append(neighbor) - core_samples.append(neighbor) - # Update candidates for next round of cluster expansion. - candidates = new_candidates + candidates = np.intersect1d(noise, core_samples, + assume_unique=True) # Current cluster finished. # Next core point found will start a new cluster. label_num += 1 @@ -122,8 +178,8 @@ class DBSCAN(BaseEstimator, ClusterMixin): The maximum distance between two samples for them to be considered as in the same neighborhood. min_samples : int, optional - The number of samples in a neighborhood for a point to be considered - as a core point. + The number of samples (or total weight) in a neighborhood for a point + to be considered as a core point. This includes the point itself. metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of @@ -131,58 +187,102 @@ class DBSCAN(BaseEstimator, ClusterMixin): metric parameter. If metric is "precomputed", X is assumed to be a distance matrix and must be square. - random_state : numpy.RandomState, optional - The generator used to initialize the centers. Defaults to numpy.random. + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional + The algorithm to be used by the NearestNeighbors module + to compute pointwise distances and find nearest neighbors. + See NearestNeighbors module documentation for details. + leaf_size : int, optional (default = 30) + Leaf size passed to BallTree or cKDTree. This can affect the speed + of the construction and query, as well as the memory required + to store the tree. The optimal value depends + on the nature of the problem. + random_state: numpy.RandomState, optional + Deprecated and ignored as of version 0.16, will be removed in version + 0.18. DBSCAN does not use random initialization. Attributes ---------- - `core_sample_indices_` : array, shape = [n_core_samples] + core_sample_indices_ : array, shape = [n_core_samples] Indices of core samples. - `components_` : array, shape = [n_core_samples, n_features] + components_ : array, shape = [n_core_samples, n_features] Copy of each core sample found by training. - `labels_` : array, shape = [n_samples] + labels_ : array, shape = [n_samples] Cluster labels for each point in the dataset given to fit(). Noisy samples are given the label -1. Notes ----- - See examples/plot_dbscan.py for an example. + See examples/cluster/plot_dbscan.py for an example. + + This implementation bulk-computes all neighborhood queries, which increases + the memory complexity to O(n.d) where d is the average number of neighbors, + while original DBSCAN had memory complexity O(n). References ---------- - Ester, M., H. P. Kriegel, J. Sander, and X. Xu, “A Density-Based - Algorithm for Discovering Clusters in Large Spatial Databases with Noise”. + Ester, M., H. P. Kriegel, J. Sander, and X. Xu, "A Density-Based + Algorithm for Discovering Clusters in Large Spatial Databases with Noise". In: Proceedings of the 2nd International Conference on Knowledge Discovery - and Data Mining, Portland, OR, AAAI Press, pp. 226–231. 1996 + and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 """ def __init__(self, eps=0.5, min_samples=5, metric='euclidean', - random_state=None): + algorithm='auto', leaf_size=30, p=None, random_state=None): self.eps = eps self.min_samples = min_samples self.metric = metric - self.random_state = check_random_state(random_state) + self.algorithm = algorithm + self.leaf_size = leaf_size + self.p = p + self.random_state = random_state - def fit(self, X, **params): - """Perform DBSCAN clustering from vector array or distance matrix. + def fit(self, X, y=None, sample_weight=None): + """Perform DBSCAN clustering from features or distance matrix. Parameters ---------- - X: array [n_samples, n_samples] or [n_samples, n_features] - Array of distances between samples, or a feature array. - The array is treated as a feature array unless the metric is - given as 'precomputed'. - params: dict - Overwrite keywords from __init__. + X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ + array of shape (n_samples, n_samples) + A feature array, or array of distances between samples if + ``metric='precomputed'``. + sample_weight : array, shape (n_samples,), optional + Weight of each sample, such that a sample with a weight of at least + ``min_samples`` is by itself a core sample; a sample with negative + weight may inhibit its eps-neighbor from being core. + Note that weights are absolute, and default to 1. """ - if params: - warnings.warn('Passing parameters to fit methods is ' - 'deprecated and will be removed in 0.14', - DeprecationWarning, stacklevel=2) - self.set_params(**params) - self.core_sample_indices_, self.labels_ = dbscan(X, - **self.get_params()) - self.components_ = X[self.core_sample_indices_].copy() + X = check_array(X, accept_sparse='csr') + clust = dbscan(X, sample_weight=sample_weight, **self.get_params()) + self.core_sample_indices_, self.labels_ = clust + if len(self.core_sample_indices_): + # fix for scipy sparse indexing issue + self.components_ = X[self.core_sample_indices_].copy() + else: + # no core samples + self.components_ = np.empty((0, X.shape[1])) return self + + def fit_predict(self, X, y=None, sample_weight=None): + """Performs clustering on X and returns cluster labels. + + Parameters + ---------- + X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ + array of shape (n_samples, n_samples) + A feature array, or array of distances between samples if + ``metric='precomputed'``. + sample_weight : array, shape (n_samples,), optional + Weight of each sample, such that a sample with a weight of at least + ``min_samples`` is by itself a core sample; a sample with negative + weight may inhibit its eps-neighbor from being core. + Note that weights are absolute, and default to 1. + + Returns + ------- + y : ndarray, shape (n_samples,) + cluster labels + """ + self.fit(X, sample_weight=sample_weight) + return self.labels_ diff --git a/sklearn/cluster/hierarchical.py b/sklearn/cluster/hierarchical.py index 15b8b5cadbd87..a7ff170d126cf 100644 --- a/sklearn/cluster/hierarchical.py +++ b/sklearn/cluster/hierarchical.py @@ -1,7 +1,7 @@ """Hierarchical Agglomerative Clustering -These routines perform some hierachical agglomerative clustering of some -input data. Currently, only Ward's algorithm is implemented. +These routines perform some hierarchical agglomerative clustering of some +input data. Authors : Vincent Michel, Bertrand Thirion, Alexandre Gramfort, Gael Varoquaux @@ -9,39 +9,102 @@ """ from heapq import heapify, heappop, heappush, heappushpop import warnings +import sys import numpy as np from scipy import sparse -from scipy.cluster import hierarchy from ..base import BaseEstimator, ClusterMixin -from ..utils._csgraph import cs_graph_components from ..externals.joblib import Memory -from ..metrics import euclidean_distances +from ..externals import six +from ..metrics.pairwise import paired_distances, pairwise_distances +from ..utils import check_array +from ..utils.sparsetools import connected_components from . import _hierarchical from ._feature_agglomeration import AgglomerationTransform +from ..utils.fast_dict import IntFloatDict +if sys.version_info[0] > 2: + xrange = range ############################################################################### -# Ward's algorithm +# For non fully-connected graphs + + +def _fix_connectivity(X, connectivity, n_components=None, + affinity="euclidean"): + """ + Fixes the connectivity matrix + + - copies it + - makes it symmetric + - converts it to LIL if necessary + - completes it if necessary + """ + n_samples = X.shape[0] + if (connectivity.shape[0] != n_samples or + connectivity.shape[1] != n_samples): + raise ValueError('Wrong shape for connectivity matrix: %s ' + 'when X is %s' % (connectivity.shape, X.shape)) + + # Make the connectivity matrix symmetric: + connectivity = connectivity + connectivity.T + + # Convert connectivity matrix to LIL + if not sparse.isspmatrix_lil(connectivity): + if not sparse.isspmatrix(connectivity): + connectivity = sparse.lil_matrix(connectivity) + else: + connectivity = connectivity.tolil() + + # Compute the number of nodes + n_components, labels = connected_components(connectivity) -def ward_tree(X, connectivity=None, n_components=None, copy=True, - n_clusters=None): + if n_components > 1: + warnings.warn("the number of connected components of the " + "connectivity matrix is %d > 1. Completing it to avoid " + "stopping the tree early." % n_components, + stacklevel=2) + # XXX: Can we do without completing the matrix? + for i in xrange(n_components): + idx_i = np.where(labels == i)[0] + Xi = X[idx_i] + for j in xrange(i): + idx_j = np.where(labels == j)[0] + Xj = X[idx_j] + D = pairwise_distances(Xi, Xj, metric=affinity) + ii, jj = np.where(D == np.min(D)) + ii = ii[0] + jj = jj[0] + connectivity[idx_i[ii], idx_j[jj]] = True + connectivity[idx_j[jj], idx_i[ii]] = True + + return connectivity, n_components + + +############################################################################### +# Hierarchical tree building functions + +def ward_tree(X, connectivity=None, n_components=None, n_clusters=None, + return_distance=False): """Ward clustering based on a Feature matrix. + Recursively merges the pair of clusters that minimally increases + within-cluster variance. + The inertia matrix uses a Heapq-based representation. - This is the structured version, that takes into account a some topological + This is the structured version, that takes into account some topological structure between samples. Parameters ---------- - X : array of shape (n_samples, n_features) + X : array, shape (n_samples, n_features) feature matrix representing n_samples samples to be clustered - connectivity : sparse matrix. - connectivity matrix. Defines for each sample the neigbhoring samples + connectivity : sparse matrix (optional). + connectivity matrix. Defines for each sample the neighboring samples following a given structure of the data. The matrix is assumed to be symmetric and only the upper triangular half is used. Default is None, i.e, the Ward algorithm is unstructured. @@ -49,10 +112,8 @@ def ward_tree(X, connectivity=None, n_components=None, copy=True, n_components : int (optional) Number of connected components. If None the number of connected components is estimated from the connectivity matrix. - - copy : bool (optional) - Make a copy of connectivity or work inplace. If connectivity - is not of LIL type there will be a copy in any case. + NOTE: This parameter is now directly determined directly + from the connectivity matrix and will be removed in 0.18 n_clusters : int (optional) Stop early the construction of the tree at n_clusters. This is @@ -62,13 +123,20 @@ def ward_tree(X, connectivity=None, n_components=None, copy=True, limited use, and the 'parents' output should rather be used. This option is valid only when specifying a connectivity matrix. + return_distance: bool (optional) + If True, return the distance between the clusters. + Returns ------- - children : 2D array, shape (n_nodes, 2) - list of the children of each nodes. - Leaves of the tree have empty list of children. - - n_components : sparse matrix. + children : 2D array, shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i` + + n_components : int The number of connected components in the graph. n_leaves : int @@ -77,6 +145,32 @@ def ward_tree(X, connectivity=None, n_components=None, copy=True, parents : 1D array, shape (n_nodes, ) or None The parent of each node. Only returned when a connectivity matrix is specified, elsewhere 'None' is returned. + + distances : 1D array, shape (n_nodes-1, ) + Only returned if return_distance is set to True (for compatibility). + The distances between the centers of the nodes. `distances[i]` + corresponds to a weighted euclidean distance between + the nodes `children[i, 1]` and `children[i, 2]`. If the nodes refer to + leaves of the tree, then `distances[i]` is their unweighted euclidean + distance. Distances are updated in the following way + (from scipy.hierarchy.linkage): + + The new entry :math:`d(u,v)` is computed as follows, + + .. math:: + + d(u,v) = \\sqrt{\\frac{|v|+|s|} + {T}d(v,s)^2 + + \\frac{|v|+|t|} + {T}d(v,t)^2 + - \\frac{|v|} + {T}d(s,t)^2} + + where :math:`u` is the newly joined cluster consisting of + clusters :math:`s` and :math:`t`, :math:`v` is an unused + cluster in the forest, :math:`T=|v|+|s|+|t|`, and + :math:`|*|` is the cardinality of its argument. This is also + known as the incremental algorithm. """ X = np.asarray(X) if X.ndim == 1: @@ -84,46 +178,40 @@ def ward_tree(X, connectivity=None, n_components=None, copy=True, n_samples, n_features = X.shape if connectivity is None: + from scipy.cluster import hierarchy # imports PIL + if n_clusters is not None: - warnings.warn('Early stopping is implemented only for ' - 'structured Ward clustering (i.e. with ' - 'explicit connectivity.', stacklevel=2) + warnings.warn('Partial build of the tree is implemented ' + 'only for structured clustering (i.e. with ' + 'explicit connectivity). The algorithm ' + 'will build the full tree and only ' + 'retain the lower branches required ' + 'for the specified number of clusters', + stacklevel=2) out = hierarchy.ward(X) - children_ = out[:, :2].astype(np.int) - return children_, 1, n_samples, None - - # Compute the number of nodes - if n_components is None: - n_components, labels = cs_graph_components(connectivity) - - # Convert connectivity matrix to LIL with a copy if needed - if sparse.isspmatrix_lil(connectivity) and copy: - connectivity = connectivity.copy() - elif not sparse.isspmatrix(connectivity): - connectivity = sparse.lil_matrix(connectivity) - else: - connectivity = connectivity.tolil() - - if n_components > 1: - warnings.warn("the number of connected components of the" - " connectivity matrix is %d > 1. Completing it to avoid" - " stopping the tree early." - % n_components) - connectivity = _fix_connectivity(X, connectivity, - n_components, labels) - n_components = 1 + children_ = out[:, :2].astype(np.intp) + if return_distance: + distances = out[:, 2] + return children_, 1, n_samples, None, distances + else: + return children_, 1, n_samples, None + + if n_components is not None: + warnings.warn( + "n_components is now directly calculated from the connectivity " + "matrix and will be removed in 0.18", + DeprecationWarning) + connectivity, n_components = _fix_connectivity(X, connectivity) if n_clusters is None: - n_nodes = 2 * n_samples - n_components + n_nodes = 2 * n_samples - 1 else: - assert n_clusters <= n_samples + if n_clusters > n_samples: + raise ValueError('Cannot provide more clusters than samples. ' + '%i n_clusters was asked, and there are %i samples.' + % (n_clusters, n_samples)) n_nodes = 2 * n_samples - n_clusters - if (connectivity.shape[0] != n_samples or - connectivity.shape[1] != n_samples): - raise ValueError('Wrong shape for connectivity matrix: %s ' - 'when X is %s' % (connectivity.shape, X.shape)) - # create inertia matrix coord_row = [] coord_col = [] @@ -136,38 +224,41 @@ def ward_tree(X, connectivity=None, n_components=None, copy=True, coord_row.extend(len(row) * [ind, ]) coord_col.extend(row) - coord_row = np.array(coord_row, dtype=np.int) - coord_col = np.array(coord_col, dtype=np.int) + coord_row = np.array(coord_row, dtype=np.intp, order='C') + coord_col = np.array(coord_col, dtype=np.intp, order='C') # build moments as a list - moments_1 = np.zeros(n_nodes) + moments_1 = np.zeros(n_nodes, order='C') moments_1[:n_samples] = 1 - moments_2 = np.zeros((n_nodes, n_features)) + moments_2 = np.zeros((n_nodes, n_features), order='C') moments_2[:n_samples] = X - inertia = np.empty(len(coord_row), dtype=np.float) - _hierarchical.compute_ward_dist(moments_1, moments_2, - coord_row, coord_col, inertia) - inertia = zip(inertia, coord_row, coord_col) + inertia = np.empty(len(coord_row), dtype=np.float, order='C') + _hierarchical.compute_ward_dist(moments_1, moments_2, coord_row, coord_col, + inertia) + inertia = list(six.moves.zip(inertia, coord_row, coord_col)) heapify(inertia) # prepare the main fields - parent = np.arange(n_nodes, dtype=np.int) - heights = np.zeros(n_nodes) + parent = np.arange(n_nodes, dtype=np.intp) used_node = np.ones(n_nodes, dtype=bool) children = [] + if return_distance: + distances = np.empty(n_nodes - n_samples) - not_visited = np.empty(n_nodes, dtype=np.int8) + not_visited = np.empty(n_nodes, dtype=np.int8, order='C') # recursive merge loop - for k in xrange(n_samples, n_nodes): + for k in range(n_samples, n_nodes): # identify the merge while True: inert, i, j = heappop(inertia) if used_node[i] and used_node[j]: break - parent[i], parent[j], heights[k] = k, k, inert - children.append([i, j]) + parent[i], parent[j] = k, k + children.append((i, j)) used_node[i] = used_node[j] = False + if return_distance: # store inertia value + distances[k - n_samples] = inert # update the moments moments_1[k] = moments_1[i] + moments_1[j] @@ -182,50 +273,288 @@ def ward_tree(X, connectivity=None, n_components=None, copy=True, # List comprehension is faster than a for loop [A[l].append(k) for l in coord_col] A.append(coord_col) - coord_col = np.array(coord_col, dtype=np.int) - coord_row = np.empty_like(coord_col) + coord_col = np.array(coord_col, dtype=np.intp, order='C') + coord_row = np.empty(coord_col.shape, dtype=np.intp, order='C') coord_row.fill(k) n_additions = len(coord_row) - ini = np.empty(n_additions, dtype=np.float) + ini = np.empty(n_additions, dtype=np.float, order='C') _hierarchical.compute_ward_dist(moments_1, moments_2, coord_row, coord_col, ini) + # List comprehension is faster than a for loop [heappush(inertia, (ini[idx], k, coord_col[idx])) - for idx in xrange(n_additions)] + for idx in range(n_additions)] # Separate leaves in children (empty lists up to now) n_leaves = n_samples + # sort children to get consistent output with unstructured version + children = [c[::-1] for c in children] children = np.array(children) # return numpy array for efficient caching - return children, n_components, n_leaves, parent + if return_distance: + # 2 is scaling factor to compare w/ unstructured version + distances = np.sqrt(2. * distances) + return children, n_components, n_leaves, parent, distances + else: + return children, n_components, n_leaves, parent -############################################################################### -# For non fully-connected graphs +# average and complete linkage +def linkage_tree(X, connectivity=None, n_components=None, + n_clusters=None, linkage='complete', affinity="euclidean", + return_distance=False): + """Linkage agglomerative clustering based on a Feature matrix. -def _fix_connectivity(X, connectivity, n_components, labels): - """ - Warning: modifies connectivity in place + The inertia matrix uses a Heapq-based representation. + + This is the structured version, that takes into account some topological + structure between samples. + + Parameters + ---------- + X : array, shape (n_samples, n_features) + feature matrix representing n_samples samples to be clustered + + connectivity : sparse matrix (optional). + connectivity matrix. Defines for each sample the neighboring samples + following a given structure of the data. The matrix is assumed to + be symmetric and only the upper triangular half is used. + Default is None, i.e, the Ward algorithm is unstructured. + + n_components : int (optional) + Number of connected components. If None the number of connected + components is estimated from the connectivity matrix. + NOTE: This parameter is now directly determined directly + from the connectivity matrix and will be removed in 0.18 + + n_clusters : int (optional) + Stop early the construction of the tree at n_clusters. This is + useful to decrease computation time if the number of clusters is + not small compared to the number of samples. In this case, the + complete tree is not computed, thus the 'children' output is of + limited use, and the 'parents' output should rather be used. + This option is valid only when specifying a connectivity matrix. + + linkage : {"average", "complete"}, optional, default: "complete" + Which linkage critera to use. The linkage criterion determines which + distance to use between sets of observation. + - average uses the average of the distances of each observation of + the two sets + - complete or maximum linkage uses the maximum distances between + all observations of the two sets. + + affinity : string or callable, optional, default: "euclidean". + which metric to use. Can be "euclidean", "manhattan", or any + distance know to paired distance (see metric.pairwise) + + return_distance : bool, default False + whether or not to return the distances between the clusters. + + Returns + ------- + children : 2D array, shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i` + + n_components : int + The number of connected components in the graph. + + n_leaves : int + The number of leaves in the tree. + + parents : 1D array, shape (n_nodes, ) or None + The parent of each node. Only returned when a connectivity matrix + is specified, elsewhere 'None' is returned. + + distances : ndarray, shape (n_nodes-1,) + Returned when return_distance is set to True. + + distances[i] refers to the distance between children[i][0] and + children[i][1] when they are merged. + + See also + -------- + ward_tree : hierarchical clustering with ward linkage """ - for i in range(n_components): - idx_i = np.where(labels == i)[0] - Xi = X[idx_i] - for j in range(i): - idx_j = np.where(labels == j)[0] - Xj = X[idx_j] - D = euclidean_distances(Xi, Xj) - ii, jj = np.where(D == np.min(D)) - ii = ii[0] - jj = jj[0] - connectivity[idx_i[ii], idx_j[jj]] = True - connectivity[idx_j[jj], idx_i[ii]] = True - return connectivity + X = np.asarray(X) + if X.ndim == 1: + X = np.reshape(X, (-1, 1)) + n_samples, n_features = X.shape + + linkage_choices = {'complete': _hierarchical.max_merge, + 'average': _hierarchical.average_merge, + } + try: + join_func = linkage_choices[linkage] + except KeyError: + raise ValueError( + 'Unknown linkage option, linkage should be one ' + 'of %s, but %s was given' % (linkage_choices.keys(), linkage)) + + if connectivity is None: + from scipy.cluster import hierarchy # imports PIL + + if n_clusters is not None: + warnings.warn('Partial build of the tree is implemented ' + 'only for structured clustering (i.e. with ' + 'explicit connectivity). The algorithm ' + 'will build the full tree and only ' + 'retain the lower branches required ' + 'for the specified number of clusters', + stacklevel=2) + + if affinity == 'precomputed': + # for the linkage function of hierarchy to work on precomputed + # data, provide as first argument an ndarray of the shape returned + # by pdist: it is a flat array containing the upper triangular of + # the distance matrix. + i, j = np.triu_indices(X.shape[0], k=1) + X = X[i, j] + elif affinity == 'l2': + # Translate to something understood by scipy + affinity = 'euclidean' + elif affinity in ('l1', 'manhattan'): + affinity = 'cityblock' + elif callable(affinity): + X = affinity(X) + i, j = np.triu_indices(X.shape[0], k=1) + X = X[i, j] + out = hierarchy.linkage(X, method=linkage, metric=affinity) + children_ = out[:, :2].astype(np.int) + + if return_distance: + distances = out[:, 2] + return children_, 1, n_samples, None, distances + return children_, 1, n_samples, None + + if n_components is not None: + warnings.warn( + "n_components is now directly calculated from the connectivity " + "matrix and will be removed in 0.18", + DeprecationWarning) + connectivity, n_components = _fix_connectivity(X, connectivity) + + connectivity = connectivity.tocoo() + # Put the diagonal to zero + diag_mask = (connectivity.row != connectivity.col) + connectivity.row = connectivity.row[diag_mask] + connectivity.col = connectivity.col[diag_mask] + connectivity.data = connectivity.data[diag_mask] + del diag_mask + + if affinity == 'precomputed': + distances = X[connectivity.row, connectivity.col] + else: + # FIXME We compute all the distances, while we could have only computed + # the "interesting" distances + distances = paired_distances(X[connectivity.row], + X[connectivity.col], + metric=affinity) + connectivity.data = distances + + if n_clusters is None: + n_nodes = 2 * n_samples - 1 + else: + assert n_clusters <= n_samples + n_nodes = 2 * n_samples - n_clusters + + if return_distance: + distances = np.empty(n_nodes - n_samples) + # create inertia heap and connection matrix + A = np.empty(n_nodes, dtype=object) + inertia = list() + + # LIL seems to the best format to access the rows quickly, + # without the numpy overhead of slicing CSR indices and data. + connectivity = connectivity.tolil() + # We are storing the graph in a list of IntFloatDict + for ind, (data, row) in enumerate(zip(connectivity.data, + connectivity.rows)): + A[ind] = IntFloatDict(np.asarray(row, dtype=np.intp), + np.asarray(data, dtype=np.float64)) + # We keep only the upper triangular for the heap + # Generator expressions are faster than arrays on the following + inertia.extend(_hierarchical.WeightedEdge(d, ind, r) + for r, d in zip(row, data) if r < ind) + del connectivity + + heapify(inertia) + + # prepare the main fields + parent = np.arange(n_nodes, dtype=np.intp) + used_node = np.ones(n_nodes, dtype=np.intp) + children = [] + + # recursive merge loop + for k in xrange(n_samples, n_nodes): + # identify the merge + while True: + edge = heappop(inertia) + if used_node[edge.a] and used_node[edge.b]: + break + i = edge.a + j = edge.b + + if return_distance: + # store distances + distances[k - n_samples] = edge.weight + + parent[i] = parent[j] = k + children.append((i, j)) + # Keep track of the number of elements per cluster + n_i = used_node[i] + n_j = used_node[j] + used_node[k] = n_i + n_j + used_node[i] = used_node[j] = False + + # update the structure matrix A and the inertia matrix + # a clever 'min', or 'max' operation between A[i] and A[j] + coord_col = join_func(A[i], A[j], used_node, n_i, n_j) + for l, d in coord_col: + A[l].append(k, d) + # Here we use the information from coord_col (containing the + # distances) to update the heap + heappush(inertia, _hierarchical.WeightedEdge(d, k, l)) + A[k] = coord_col + # Clear A[i] and A[j] to save memory + A[i] = A[j] = 0 + + # Separate leaves in children (empty lists up to now) + n_leaves = n_samples + + # # return numpy array for efficient caching + children = np.array(children)[:, ::-1] + + if return_distance: + return children, n_components, n_leaves, parent, distances + return children, n_components, n_leaves, parent + +# Matching names to tree-building strategies +def _complete_linkage(*args, **kwargs): + kwargs['linkage'] = 'complete' + return linkage_tree(*args, **kwargs) + + +def _average_linkage(*args, **kwargs): + kwargs['linkage'] = 'average' + return linkage_tree(*args, **kwargs) + + +_TREE_BUILDERS = dict( + ward=ward_tree, + complete=_complete_linkage, + average=_average_linkage, + ) + ############################################################################### # Functions for cutting hierarchical clustering tree - def _hc_cut(n_clusters, children, n_leaves): """Function cutting the ward tree for a given number of clusters. @@ -235,8 +564,9 @@ def _hc_cut(n_clusters, children, n_leaves): The number of clusters to form. children : list of pairs. Length of n_nodes - List of the children of each nodes. - Leaves have empty list of children and are not stored. + The children of each non-leaf node. Values less than `n_samples` refer + to leaves of the tree. A greater value `i` indicates a node with + children `children[i - n_samples]`. n_leaves : int Number of leaves of the tree. @@ -249,89 +579,124 @@ def _hc_cut(n_clusters, children, n_leaves): """ if n_clusters > n_leaves: raise ValueError('Cannot extract more clusters than samples: ' - '%s clusters where given for a tree with %s leaves.' - % (n_clusters, n_leaves)) + '%s clusters where given for a tree with %s leaves.' + % (n_clusters, n_leaves)) # In this function, we store nodes as a heap to avoid recomputing # the max of the nodes: the first element is always the smallest # We use negated indices as heaps work on smallest elements, and we # are interested in largest elements # children[-1] is the root of the tree nodes = [-(max(children[-1]) + 1)] - for i in range(n_clusters - 1): + for i in xrange(n_clusters - 1): # As we have a heap, nodes[0] is the smallest element these_children = children[-nodes[0] - n_leaves] # Insert the 2 children and remove the largest node heappush(nodes, -these_children[0]) heappushpop(nodes, -these_children[1]) - label = np.zeros(n_leaves, dtype=np.int) + label = np.zeros(n_leaves, dtype=np.intp) for i, node in enumerate(nodes): - label[_hierarchical._hc_get_descendent(-node, - children, n_leaves)] = i + label[_hierarchical._hc_get_descendent(-node, children, n_leaves)] = i return label ############################################################################### -# Class for Ward hierarchical clustering -class Ward(BaseEstimator, ClusterMixin): - """Ward hierarchical clustering: constructs a tree and cuts it. +class AgglomerativeClustering(BaseEstimator, ClusterMixin): + """ + Agglomerative Clustering + + Recursively merges the pair of clusters that minimally increases + a given linkage distance. Parameters ---------- - n_clusters : int or ndarray + n_clusters : int, default=2 The number of clusters to find. - connectivity : sparse matrix. - Connectivity matrix. Defines for each sample the neigbhoring + connectivity : array-like or callable, optional + Connectivity matrix. Defines for each sample the neighboring samples following a given structure of the data. - Default is None, i.e, the hiearchical clustering algorithm is - unstructured. + This can be a connectivity matrix itself or a callable that transforms + the data into a connectivity matrix, such as derived from + kneighbors_graph. Default is None, i.e, the + hierarchical clustering algorithm is unstructured. + + affinity : string or callable, default: "euclidean" + Metric used to compute the linkage. Can be "euclidean", "l1", "l2", + "manhattan", "cosine", or 'precomputed'. + If linkage is "ward", only "euclidean" is accepted. - memory : Instance of joblib.Memory or string + memory : Instance of joblib.Memory or string (optional) Used to cache the output of the computation of the tree. By default, no caching is done. If a string is given, it is the path to the caching directory. - copy : bool - Copy the connectivity matrix or work inplace. - n_components : int (optional) - The number of connected components in the graph defined by the \ - connectivity matrix. If not set, it is estimated. + Number of connected components. If None the number of connected + components is estimated from the connectivity matrix. + NOTE: This parameter is now directly determined from the connectivity + matrix and will be removed in 0.18 - compute_full_tree: bool or 'auto' (optional) + compute_full_tree : bool or 'auto' (optional) Stop early the construction of the tree at n_clusters. This is useful to decrease computation time if the number of clusters is not small compared to the number of samples. This option is useful only when specifying a connectivity matrix. Note also that - when varying the number of cluster and using caching, it may + when varying the number of clusters and using caching, it may be advantageous to compute the full tree. + linkage : {"ward", "complete", "average"}, optional, default: "ward" + Which linkage criterion to use. The linkage criterion determines which + distance to use between sets of observation. The algorithm will merge + the pairs of cluster that minimize this criterion. + + - ward minimizes the variance of the clusters being merged. + - average uses the average of the distances of each observation of + the two sets. + - complete or maximum linkage uses the maximum distances between + all observations of the two sets. + + pooling_func : callable, default=np.mean + This combines the values of agglomerated features into a single + value, and should accept an array of shape [M, N] and the keyword + argument ``axis=1``, and reduce it to an array of size [M]. Attributes ---------- - `children_` : array-like, shape = [n_nodes, 2] - List of the children of each nodes. Leaves of the tree do not appear. - - `labels_` : array [n_samples] + labels_ : array [n_samples] cluster labels for each point - `n_leaves_` : int - Number of leaves in the hiearchical tree. + n_leaves_ : int + Number of leaves in the hierarchical tree. + + n_components_ : int + The estimated number of connected components in the graph. + + children_ : array-like, shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i` """ - def __init__(self, n_clusters=2, memory=Memory(cachedir=None, verbose=0), - connectivity=None, copy=True, n_components=None, - compute_full_tree='auto'): + def __init__(self, n_clusters=2, affinity="euclidean", + memory=Memory(cachedir=None, verbose=0), + connectivity=None, n_components=None, + compute_full_tree='auto', linkage='ward', + pooling_func=np.mean): self.n_clusters = n_clusters self.memory = memory - self.copy = copy self.n_components = n_components self.connectivity = connectivity self.compute_full_tree = compute_full_tree + self.linkage = linkage + self.affinity = affinity + self.pooling_func = pooling_func - def fit(self, X): + def fit(self, X, y=None): """Fit the hierarchical clustering on the data Parameters @@ -343,19 +708,28 @@ def fit(self, X): ------- self """ + X = check_array(X) memory = self.memory - if isinstance(memory, basestring): - memory = Memory(cachedir=memory) - - if not self.connectivity is None: - if not sparse.issparse(self.connectivity): - raise TypeError("`connectivity` should be a sparse matrix or " - "None, got: %r" % type(self.connectivity)) - - if (self.connectivity.shape[0] != X.shape[0] or - self.connectivity.shape[1] != X.shape[0]): - raise ValueError("`connectivity` does not have shape " - "(n_samples, n_samples)") + if isinstance(memory, six.string_types): + memory = Memory(cachedir=memory, verbose=0) + + if self.linkage == "ward" and self.affinity != "euclidean": + raise ValueError("%s was provided as affinity. Ward can only " + "work with euclidean distances." % + (self.affinity, )) + + if self.linkage not in _TREE_BUILDERS: + raise ValueError("Unknown linkage type %s." + "Valid options are %s" % (self.linkage, + _TREE_BUILDERS.keys())) + tree_builder = _TREE_BUILDERS[self.linkage] + + connectivity = self.connectivity + if self.connectivity is not None: + if callable(self.connectivity): + connectivity = self.connectivity(X) + connectivity = check_array( + connectivity, accept_sparse=['csr', 'coo', 'lil']) n_samples = len(X) compute_full_tree = self.compute_full_tree @@ -365,16 +739,21 @@ def fit(self, X): # Early stopping is likely to give a speed up only for # a large number of clusters. The actual threshold # implemented here is heuristic - compute_full_tree = self.n_clusters > max(100, .02 * n_samples) + compute_full_tree = self.n_clusters < max(100, .02 * n_samples) n_clusters = self.n_clusters if compute_full_tree: n_clusters = None # Construct the tree - self.children_, self.n_components, self.n_leaves_, parents = \ - memory.cache(ward_tree)(X, self.connectivity, - n_components=self.n_components, - copy=self.copy, n_clusters=n_clusters) + kwargs = {} + if self.linkage != 'ward': + kwargs['linkage'] = self.linkage + kwargs['affinity'] = self.affinity + self.children_, self.n_components_, self.n_leaves_, parents = \ + memory.cache(tree_builder)(X, connectivity, + n_components=self.n_components, + n_clusters=n_clusters, + **kwargs) # Cut the tree if compute_full_tree: self.labels_ = _hc_cut(self.n_clusters, self.children_, @@ -388,8 +767,183 @@ def fit(self, X): return self +class FeatureAgglomeration(AgglomerativeClustering, AgglomerationTransform): + """Agglomerate features. + + Similar to AgglomerativeClustering, but recursively merges features + instead of samples. + + Parameters + ---------- + n_clusters : int, default 2 + The number of clusters to find. + + connectivity : array-like or callable, optional + Connectivity matrix. Defines for each feature the neighboring + features following a given structure of the data. + This can be a connectivity matrix itself or a callable that transforms + the data into a connectivity matrix, such as derived from + kneighbors_graph. Default is None, i.e, the + hierarchical clustering algorithm is unstructured. + + affinity : string or callable, default "euclidean" + Metric used to compute the linkage. Can be "euclidean", "l1", "l2", + "manhattan", "cosine", or 'precomputed'. + If linkage is "ward", only "euclidean" is accepted. + + memory : Instance of joblib.Memory or string, optional + Used to cache the output of the computation of the tree. + By default, no caching is done. If a string is given, it is the + path to the caching directory. + + n_components : int (optional) + Number of connected components. If None the number of connected + components is estimated from the connectivity matrix. + NOTE: This parameter is now directly determined from the connectivity + matrix and will be removed in 0.18 + + compute_full_tree : bool or 'auto', optional, default "auto" + Stop early the construction of the tree at n_clusters. This is + useful to decrease computation time if the number of clusters is + not small compared to the number of features. This option is + useful only when specifying a connectivity matrix. Note also that + when varying the number of clusters and using caching, it may + be advantageous to compute the full tree. + + linkage : {"ward", "complete", "average"}, optional, default "ward" + Which linkage criterion to use. The linkage criterion determines which + distance to use between sets of features. The algorithm will merge + the pairs of cluster that minimize this criterion. + + - ward minimizes the variance of the clusters being merged. + - average uses the average of the distances of each feature of + the two sets. + - complete or maximum linkage uses the maximum distances between + all features of the two sets. + + pooling_func : callable, default np.mean + This combines the values of agglomerated features into a single + value, and should accept an array of shape [M, N] and the keyword + argument `axis=1`, and reduce it to an array of size [M]. + + Attributes + ---------- + labels_ : array-like, (n_features,) + cluster labels for each feature. + + n_leaves_ : int + Number of leaves in the hierarchical tree. + + n_components_ : int + The estimated number of connected components in the graph. + + children_ : array-like, shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_features` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_features` is a non-leaf + node and has children `children_[i - n_features]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_features + i` + """ + + def fit(self, X, y=None, **params): + """Fit the hierarchical clustering on the data + + Parameters + ---------- + X : array-like, shape = [n_samples, n_features] + The data + + Returns + ------- + self + """ + X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) + if not (len(X.shape) == 2 and X.shape[0] > 0): + raise ValueError('At least one sample is required to fit the ' + 'model. A data matrix of shape %s was given.' + % (X.shape, )) + return AgglomerativeClustering.fit(self, X.T, **params) + + @property + def fit_predict(self): + raise AttributeError + ############################################################################### -# Ward-based feature agglomeration +# Backward compatibility: class for Ward hierarchical clustering + +class Ward(AgglomerativeClustering): + """Ward hierarchical clustering: constructs a tree and cuts it. + + Recursively merges the pair of clusters that minimally increases + within-cluster variance. + + Parameters + ---------- + n_clusters : int or ndarray + The number of clusters to find. + + connectivity : sparse matrix (optional) + Connectivity matrix. Defines for each sample the neighboring + samples following a given structure of the data. + Default is None, i.e, the hierarchical clustering algorithm is + unstructured. + + memory : Instance of joblib.Memory or string (optional) + Used to cache the output of the computation of the tree. + By default, no caching is done. If a string is given, it is the + path to the caching directory. + + n_components : int (optional) + The number of connected components in the graph defined by the + connectivity matrix. If not set, it is estimated. + + compute_full_tree : bool or 'auto' (optional) + Stop early the construction of the tree at n_clusters. This is + useful to decrease computation time if the number of clusters is + not small compared to the number of samples. This option is + useful only when specifying a connectivity matrix. Note also that + when varying the number of clusters and using caching, it may + be advantageous to compute the full tree. + + Attributes + ---------- + labels_ : array [n_features] + cluster labels for each feature + + n_leaves_ : int + Number of leaves in the hierarchical tree. + + n_components_ : int + The estimated number of connected components in the graph. + + children_ : array-like, shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + refer to leaves of the tree. A greater value `i` indicates a node with + children `children_[i - n_samples]`. + + + See also + -------- + AgglomerativeClustering : agglomerative hierarchical clustering + """ + linkage = 'ward' + + def __init__(self, n_clusters=2, memory=Memory(cachedir=None, verbose=0), + connectivity=None, n_components=None, + compute_full_tree='auto', pooling_func=np.mean): + + warnings.warn("The Ward class is deprecated since 0.14 and will be " + "removed in 0.17. Use the AgglomerativeClustering " + "instead.", DeprecationWarning) + self.n_clusters = n_clusters + self.memory = memory + self.n_components = n_components + self.connectivity = connectivity + self.compute_full_tree = compute_full_tree + self.affinity = "euclidean" + self.pooling_func = pooling_func + class WardAgglomeration(AgglomerationTransform, Ward): """Feature agglomeration based on Ward hierarchical clustering @@ -399,25 +953,24 @@ class WardAgglomeration(AgglomerationTransform, Ward): n_clusters : int or ndarray The number of clusters. - connectivity : sparse matrix - connectivity matrix. Defines for each feature the neigbhoring - features following a given structure of the data. - Default is None, i.e, the hiearchical agglomeration algorithm is - unstructured. + connectivity : array-like or callable, optional + Connectivity matrix. Defines for each sample the neighboring + samples following a given structure of the data. + This can be a connectivity matrix itself or a callable that transforms + the data into a connectivity matrix, such as derived from + kneighbors_graph. Default is None, i.e, the + hierarchical clustering algorithm is unstructured. - memory : Instance of joblib.Memory or string + memory : Instance of joblib.Memory or string, optional Used to cache the output of the computation of the tree. By default, no caching is done. If a string is given, it is the path to the caching directory. - copy : bool - Copy the connectivity matrix or work inplace. - n_components : int (optional) The number of connected components in the graph defined by the connectivity matrix. If not set, it is estimated. - compute_full_tree: bool or 'auto' (optional) + compute_full_tree : bool or 'auto' (optional) Stop early the construction of the tree at n_clusters. This is useful to decrease computation time if the number of clusters is not small compared to the number of samples. This option is @@ -425,18 +978,29 @@ class WardAgglomeration(AgglomerationTransform, Ward): when varying the number of cluster and using caching, it may be advantageous to compute the full tree. + pooling_func : callable, default=np.mean + This combines the values of agglomerated features into a single + value, and should accept an array of shape [M, N] and the keyword + argument `axis=1`, and reduce it to an array of size [M]. Attributes ---------- - `children_` : array-like, shape = [n_nodes, 2] - List of the children of each nodes. - Leaves of the tree do not appear. + children_ : array-like, shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_features` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_features` is a non-leaf + node and has children `children_[i - n_features]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_features + i` - `labels_` : array [n_samples] - cluster labels for each point + labels_ : array [n_features] + cluster labels for each feature + + n_leaves_ : int + Number of leaves in the hierarchical tree. - `n_leaves_` : int - Number of leaves in the hiearchical tree. + n_components_ : int + The estimated number of connected components in the graph. """ @@ -452,4 +1016,9 @@ def fit(self, X, y=None, **params): ------- self """ + X = check_array(X) return Ward.fit(self, X.T, **params) + + @property + def fit_predict(self): + raise AttributeError diff --git a/sklearn/cluster/k_means_.py b/sklearn/cluster/k_means_.py index ce8292c9c110a..43a4d80a024fc 100644 --- a/sklearn/cluster/k_means_.py +++ b/sklearn/cluster/k_means_.py @@ -9,20 +9,25 @@ # Olivier Grisel # Mathieu Blondel # Robert Layton -# License: BSD +# License: BSD 3 clause import warnings import numpy as np import scipy.sparse as sp -from ..base import BaseEstimator, ClusterMixin +from ..base import BaseEstimator, ClusterMixin, TransformerMixin from ..metrics.pairwise import euclidean_distances -from ..utils.sparsefuncs import mean_variance_axis0 -from ..utils import check_arrays +from ..utils.extmath import row_norms, squared_norm +from ..utils.sparsefuncs_fast import assign_rows_csr +from ..utils.sparsefuncs import mean_variance_axis +from ..utils.fixes import astype +from ..utils import check_array from ..utils import check_random_state -from ..utils import atleast2d_or_csr from ..utils import as_float_array +from ..utils import gen_batches +from ..utils.validation import check_is_fitted +from ..utils.random import choice from ..externals.joblib import Parallel from ..externals.joblib import delayed @@ -33,8 +38,7 @@ # Initialization heuristic -def _k_init(X, n_clusters, n_local_trials=None, random_state=None, - x_squared_norms=None): +def _k_init(X, n_clusters, x_squared_norms, random_state, n_local_trials=None): """Init n_clusters seeds according to k-means++ Parameters @@ -46,21 +50,18 @@ def _k_init(X, n_clusters, n_local_trials=None, random_state=None, n_clusters: integer The number of seeds to choose + x_squared_norms: array, shape (n_samples,) + Squared Euclidean norm of each data point. + + random_state: numpy.RandomState + The generator used to initialize the centers. + n_local_trials: integer, optional The number of seeding trials for each center (except the first), of which the one reducing inertia the most is greedily chosen. Set to None to make the number of trials depend logarithmically on the number of seeds (2+log(k)); this is the default. - random_state: integer or numpy.RandomState, optional - The generator used to initialize the centers. If an integer is - given, it fixes the seed. Defaults to the global numpy random - number generator. - - x_squared_norms: array, shape (n_samples,), optional - Squared euclidean norm of each data point. Pass it if you have it at - hands already to avoid it being recomputed here. Default: None - Notes ----- Selects initial cluster centers for k-mean clustering in a smart way @@ -72,10 +73,11 @@ def _k_init(X, n_clusters, n_local_trials=None, random_state=None, which is the implementation used in the aforementioned paper. """ n_samples, n_features = X.shape - random_state = check_random_state(random_state) centers = np.empty((n_clusters, n_features)) + assert x_squared_norms is not None, 'x_squared_norms None in _k_init' + # Set the number of local seeding trials if none is given if n_local_trials is None: # This is what Arthur/Vassilvitskii tried, but did not report @@ -91,14 +93,12 @@ def _k_init(X, n_clusters, n_local_trials=None, random_state=None, centers[0] = X[center_id] # Initialize list of closest distances and calculate current potential - if x_squared_norms is None: - x_squared_norms = _squared_norms(X) closest_dist_sq = euclidean_distances( centers[0], X, Y_norm_squared=x_squared_norms, squared=True) current_pot = closest_dist_sq.sum() # Pick the remaining n_clusters-1 points - for c in xrange(1, n_clusters): + for c in range(1, n_clusters): # Choose center candidates by sampling with probability proportional # to the squared distance to the closest existing center rand_vals = random_state.random_sample(n_local_trials) * current_pot @@ -112,7 +112,7 @@ def _k_init(X, n_clusters, n_local_trials=None, random_state=None, best_candidate = None best_pot = None best_dist_sq = None - for trial in xrange(n_local_trials): + for trial in range(n_local_trials): # Compute potential when including center candidate new_dist_sq = np.minimum(closest_dist_sq, distance_to_candidates[trial]) @@ -142,35 +142,36 @@ def _k_init(X, n_clusters, n_local_trials=None, random_state=None, def _tolerance(X, tol): """Return a tolerance which is independent of the dataset""" if sp.issparse(X): - variances = mean_variance_axis0(X)[1] + variances = mean_variance_axis(X, axis=0)[1] else: variances = np.var(X, axis=0) return np.mean(variances) * tol -def k_means(X, n_clusters, init='k-means++', precompute_distances=True, +def k_means(X, n_clusters, init='k-means++', precompute_distances='auto', n_init=10, max_iter=300, verbose=False, - tol=1e-4, random_state=None, copy_x=True, n_jobs=1, k=None): + tol=1e-4, random_state=None, copy_x=True, n_jobs=1, + return_n_iter=False): """K-means clustering algorithm. Parameters ---------- - X: array-like of floats, shape (n_samples, n_features) + X : array-like or sparse matrix, shape (n_samples, n_features) The observations to cluster. - n_clusters: int + n_clusters : int The number of clusters to form as well as the number of centroids to generate. - max_iter: int, optional, default 300 + max_iter : int, optional, default 300 Maximum number of iterations of the k-means algorithm to run. - n_init: int, optional, default: 10 + n_init : int, optional, default: 10 Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia. - init: {'k-means++', 'random', or ndarray, or a callable}, optional + init : {'k-means++', 'random', or ndarray, or a callable}, optional Method for initialization, default to 'k-means++': 'k-means++' : selects initial cluster centers for k-mean @@ -186,79 +187,107 @@ def k_means(X, n_clusters, init='k-means++', precompute_distances=True, If a callable is passed, it should take arguments X, k and and a random state and return an initialization. - tol: float, optional + precompute_distances : {'auto', True, False} + Precompute distances (faster but takes more memory). + + 'auto' : do not precompute distances if n_samples * n_clusters > 12 + million. This corresponds to about 100MB overhead per job using + double precision. + + True : always precompute distances + + False : never precompute distances + + tol : float, optional The relative increment in the results before declaring convergence. - verbose: boolean, optional - Verbosity mode + verbose : boolean, optional + Verbosity mode. - random_state: integer or numpy.RandomState, optional + random_state : integer or numpy.RandomState, optional The generator used to initialize the centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. - copy_x: boolean, optional + copy_x : boolean, optional When pre-computing distances it is more numerically accurate to center the data first. If copy_x is True, then the original data is not modified. If False, the original data is modified, and put back before the function returns, but small numerical differences may be introduced by subtracting and then adding the data mean. - n_jobs: int - The number of jobs to use for the computation. This works by breaking - down the pairwise matrix into n_jobs even slices and computing them in - parallel. + n_jobs : int + The number of jobs to use for the computation. This works by computing + each of the n_init runs in parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is - used at all, which is useful for debuging. For n_jobs below -1, - (n_cpus + 1 - n_jobs) are used. Thus for n_jobs = -2, all CPUs but one + used at all, which is useful for debugging. For n_jobs below -1, + (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. + return_n_iter : bool, optional + Whether or not to return the number of iterations. + Returns ------- - centroid: float ndarray with shape (k, n_features) + centroid : float ndarray with shape (k, n_features) Centroids found at the last iteration of k-means. - label: integer ndarray with shape (n_samples,) + label : integer ndarray with shape (n_samples,) label[i] is the code or index of the centroid the i'th observation is closest to. - inertia: float + inertia : float The final value of the inertia criterion (sum of squared distances to the closest centroid for all observations in the training set). + best_n_iter: int + Number of iterations corresponding to the best results. + Returned only if `return_n_iter` is set to True. + """ + if n_init <= 0: + raise ValueError("Invalid number of initializations." + " n_init=%d must be bigger than zero." % n_init) random_state = check_random_state(random_state) - if not k is None: - n_clusters = k - warnings.warn("Parameter k was renamed to n_clusters", - DeprecationWarning) - best_inertia = np.infty X = as_float_array(X, copy=copy_x) tol = _tolerance(X, tol) + # If the distances are precomputed every job will create a matrix of shape + # (n_clusters, n_samples). To stop KMeans from eating up memory we only + # activate this if the created matrix is guaranteed to be under 100MB. 12 + # million entries consume a little under 100MB if they are of type double. + if precompute_distances == 'auto': + n_samples = X.shape[0] + precompute_distances = (n_clusters * n_samples) < 12e6 + elif isinstance(precompute_distances, bool): + pass + else: + raise ValueError("precompute_distances should be 'auto' or True/False" + ", but a value of %r was passed" % + precompute_distances) + # subtract of mean of x for more accurate distance computations if not sp.issparse(X) or hasattr(init, '__array__'): X_mean = X.mean(axis=0) if not sp.issparse(X): - if copy_x: - X = X.copy() + # The copy was already done above X -= X_mean if hasattr(init, '__array__'): init = np.asarray(init).copy() init -= X_mean - if not n_init == 1: + if n_init != 1: warnings.warn( 'Explicit initial center position passed: ' - 'performing only one init in the k-means instead of %d' + 'performing only one init in k-means instead of n_init=%d' % n_init, RuntimeWarning, stacklevel=2) n_init = 1 # precompute squared norms of data points - x_squared_norms = _squared_norms(X) + x_squared_norms = row_norms(X, squared=True) best_labels, best_inertia, best_centers = None, None, None if n_jobs == 1: @@ -266,7 +295,7 @@ def k_means(X, n_clusters, init='k-means++', precompute_distances=True, # of the best results (as opposed to one set per run per thread). for it in range(n_init): # run a k-means once - labels, inertia, centers = _kmeans_single( + labels, inertia, centers, n_iter_ = _kmeans_single( X, n_clusters, max_iter=max_iter, init=init, verbose=verbose, precompute_distances=precompute_distances, tol=tol, x_squared_norms=x_squared_norms, random_state=random_state) @@ -275,34 +304,40 @@ def k_means(X, n_clusters, init='k-means++', precompute_distances=True, best_labels = labels.copy() best_centers = centers.copy() best_inertia = inertia + best_n_iter = n_iter_ else: # parallelisation of k-means runs seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init) results = Parallel(n_jobs=n_jobs, verbose=0)( delayed(_kmeans_single)(X, n_clusters, max_iter=max_iter, - init=init, verbose=verbose, tol=tol, - precompute_distances=precompute_distances, - x_squared_norms=x_squared_norms, + init=init, verbose=verbose, tol=tol, + precompute_distances=precompute_distances, + x_squared_norms=x_squared_norms, # Change seed to ensure variety random_state=seed) for seed in seeds) # Get results with the lowest inertia - labels, inertia, centers = zip(*results) + labels, inertia, centers, n_iters = zip(*results) best = np.argmin(inertia) best_labels = labels[best] best_inertia = inertia[best] best_centers = centers[best] + best_n_iter = n_iters[best] + if not sp.issparse(X): if not copy_x: X += X_mean best_centers += X_mean - return best_centers, best_labels, best_inertia + if return_n_iter: + return best_centers, best_labels, best_inertia, best_n_iter + else: + return best_centers, best_labels, best_inertia -def _kmeans_single(X, n_clusters, max_iter=300, init='k-means++', - verbose=False, x_squared_norms=None, random_state=None, tol=1e-4, - precompute_distances=True): +def _kmeans_single(X, n_clusters, x_squared_norms, max_iter=300, + init='k-means++', verbose=False, random_state=None, + tol=1e-4, precompute_distances=True): """A single run of k-means, assumes preparation completed prior. Parameters @@ -310,7 +345,7 @@ def _kmeans_single(X, n_clusters, max_iter=300, init='k-means++', X: array-like of floats, shape (n_samples, n_features) The observations to cluster. - k: int + n_clusters: int The number of clusters to form as well as the number of centroids to generate. @@ -339,8 +374,11 @@ def _kmeans_single(X, n_clusters, max_iter=300, init='k-means++', verbose: boolean, optional Verbosity mode - x_squared_norms: array, optional - Precomputed x_squared_norms. Calculated if not given. + x_squared_norms: array + Precomputed x_squared_norms. + + precompute_distances : boolean, default: True + Precompute distances (faster but takes more memory). random_state: integer or numpy.RandomState, optional The generator used to initialize the centers. If an integer is @@ -359,16 +397,18 @@ def _kmeans_single(X, n_clusters, max_iter=300, init='k-means++', inertia: float The final value of the inertia criterion (sum of squared distances to the closest centroid for all observations in the training set). + + n_iter : int + Number of iterations run. """ random_state = check_random_state(random_state) - if x_squared_norms is None: - x_squared_norms = _squared_norms(X) + best_labels, best_inertia, best_centers = None, None, None # init centers = _init_centroids(X, n_clusters, init, random_state=random_state, x_squared_norms=x_squared_norms) if verbose: - print 'Initialization complete' + print("Initialization complete") # Allocate memory to store the distances for each sample to its # closer center for reallocation in case of ties @@ -377,62 +417,87 @@ def _kmeans_single(X, n_clusters, max_iter=300, init='k-means++', # iterations for i in range(max_iter): centers_old = centers.copy() - # labels assignement is also called the E-step of EM + # labels assignment is also called the E-step of EM labels, inertia = \ - _labels_inertia(X, x_squared_norms, centers, - precompute_distances=precompute_distances, - distances=distances) + _labels_inertia(X, x_squared_norms, centers, + precompute_distances=precompute_distances, + distances=distances) # computation of the means is also called the M-step of EM - centers = _centers(X, labels, n_clusters, distances) + if sp.issparse(X): + centers = _k_means._centers_sparse(X, labels, n_clusters, + distances) + else: + centers = _k_means._centers_dense(X, labels, n_clusters, distances) if verbose: - print 'Iteration %i, inertia %s' % (i, inertia) + print("Iteration %2d, inertia %.3f" % (i, inertia)) if best_inertia is None or inertia < best_inertia: best_labels = labels.copy() best_centers = centers.copy() best_inertia = inertia - if np.sum((centers_old - centers) ** 2) < tol: + if squared_norm(centers_old - centers) <= tol: if verbose: - print 'Converged to similar centers at iteration', i + print("Converged at iteration %d" % i) break - return best_labels, best_inertia, best_centers + return best_labels, best_inertia, best_centers, i + 1 -def _squared_norms(X): - """Compute the squared euclidean norms of the rows of X""" - if sp.issparse(X): - return _k_means.csr_row_norm_l2(X, squared=True) - else: - # TODO: implement a cython version to avoid the memory copy of the - # input data - return (X ** 2).sum(axis=1) +def _labels_inertia_precompute_dense(X, x_squared_norms, centers, distances): + """Compute labels and inertia using a full distance matrix. + + This will overwrite the 'distances' array in-place. + + Parameters + ---------- + X : numpy array, shape (n_sample, n_features) + Input data. + + x_squared_norms : numpy array, shape (n_samples,) + Precomputed squared norms of X. + + centers : numpy array, shape (n_clusters, n_features) + Cluster centers which data is assigned to. + distances : numpy array, shape (n_samples,) + Pre-allocated array in which distances are stored. + + Returns + ------- + labels : numpy array, dtype=np.int, shape (n_samples,) + Indices of clusters that samples are assigned to. -def _labels_inertia_precompute_dense(X, x_squared_norms, centers): + inertia : float + Sum of distances of samples to their closest cluster center. + + """ n_samples = X.shape[0] k = centers.shape[0] - distances = euclidean_distances(centers, X, x_squared_norms, - squared=True) - labels = np.empty(n_samples, dtype=np.int) + all_distances = euclidean_distances(centers, X, x_squared_norms, + squared=True) + labels = np.empty(n_samples, dtype=np.int32) labels.fill(-1) mindist = np.empty(n_samples) mindist.fill(np.infty) for center_id in range(k): - dist = distances[center_id] + dist = all_distances[center_id] labels[dist < mindist] = center_id mindist = np.minimum(dist, mindist) + if n_samples == distances.shape[0]: + # distances will be changed in-place + distances[:] = mindist inertia = mindist.sum() return labels, inertia def _labels_inertia(X, x_squared_norms, centers, precompute_distances=True, distances=None): - """E step of the K-means EM algorithm + """E step of the K-means EM algorithm. - Compute the labels and the inertia of the given samples and centers + Compute the labels and the inertia of the given samples and centers. + This will compute the distances in-place. Parameters ---------- @@ -446,82 +511,40 @@ def _labels_inertia(X, x_squared_norms, centers, centers: float64 array, shape (k, n_features) The cluster centers. + precompute_distances : boolean, default: True + Precompute distances (faster but takes more memory). + distances: float64 array, shape (n_samples,) - Distances for each sample to its closest center. + Pre-allocated array to be filled in with each sample's distance + to the closest center. Returns ------- labels: int array of shape(n) The resulting assignment - inertia: float - The value of the inertia criterion with the assignment + inertia : float + Sum of distances of samples to their closest cluster center. """ n_samples = X.shape[0] # set the default value of centers to -1 to be able to detect any anomaly # easily - labels = - np.ones(n_samples, np.int32) + labels = -np.ones(n_samples, np.int32) if distances is None: distances = np.zeros(shape=(0,), dtype=np.float64) + # distances will be changed in-place if sp.issparse(X): inertia = _k_means._assign_labels_csr( X, x_squared_norms, centers, labels, distances=distances) else: if precompute_distances: return _labels_inertia_precompute_dense(X, x_squared_norms, - centers) + centers, distances) inertia = _k_means._assign_labels_array( X, x_squared_norms, centers, labels, distances=distances) return labels, inertia -def _centers(X, labels, n_clusters, distances): - """M step of the K-means EM algorithm - - Computation of cluster centers / means. - - Parameters - ---------- - X: array, shape (n_samples, n_features) - - labels: array of integers, shape (n_samples) - Current label assignment - - n_clusters: int - Number of desired clusters - - Returns - ------- - centers: array, shape (n_clusters, n_features) - The resulting centers - """ - # TODO: add support for CSR input - n_features = X.shape[1] - - # TODO: explicit dtype handling - centers = np.empty((n_clusters, n_features)) - far_from_centers = None - reallocated_idx = 0 - sparse_X = sp.issparse(X) - - for center_id in range(n_clusters): - center_mask = labels == center_id - if sparse_X: - center_mask = np.arange(len(labels))[center_mask] - if not np.any(center_mask): - # Reassign empty cluster center to sample far from any cluster - if far_from_centers is None: - far_from_centers = distances.argsort()[::-1] - new_centers = X[far_from_centers[reallocated_idx]] - if sparse_X: - new_centers = new_centers.todense().ravel() - centers[center_id] = new_centers - reallocated_idx += 1 - else: - centers[center_id] = X[center_mask].mean(axis=0) - return centers - - def _init_centroids(X, k, init, random_state=None, x_squared_norms=None, init_size=None): """Compute the initial centroids @@ -548,7 +571,7 @@ def _init_centroids(X, k, init, random_state=None, x_squared_norms=None, init_size : int, optional Number of samples to randomly sample for speeding up the - initialization (sometimes at the expense of accurracy): the + initialization (sometimes at the expense of accuracy): the only algorithm is initialized by running a batch KMeans on a random subset of the data. This needs to be larger than k. @@ -567,18 +590,17 @@ def _init_centroids(X, k, init, random_state=None, x_squared_norms=None, RuntimeWarning, stacklevel=2) init_size = 3 * k init_indices = random_state.random_integers( - 0, n_samples - 1, init_size) + 0, n_samples - 1, init_size) X = X[init_indices] x_squared_norms = x_squared_norms[init_indices] n_samples = X.shape[0] elif n_samples < k: - raise ValueError( - "n_samples=%d should be larger than k=%d" % (init_size, k)) + raise ValueError( + "n_samples=%d should be larger than k=%d" % (n_samples, k)) if init == 'k-means++': - centers = _k_init(X, k, - random_state=random_state, - x_squared_norms=x_squared_norms) + centers = _k_init(X, k, random_state=random_state, + x_squared_norms=x_squared_norms) elif init == 'random': seeds = random_state.permutation(n_samples)[:k] centers = X[seeds] @@ -588,15 +610,21 @@ def _init_centroids(X, k, init, random_state=None, x_squared_norms=None, centers = init(X, k, random_state=random_state) else: raise ValueError("the init parameter for the k-means should " - "be 'k-means++' or 'random' or an ndarray, " - "'%s' (type '%s') was passed." % (init, type(init))) + "be 'k-means++' or 'random' or an ndarray, " + "'%s' (type '%s') was passed." % (init, type(init))) if sp.issparse(centers): centers = centers.toarray() + + if len(centers) != k: + raise ValueError('The shape of the initial centers (%s) ' + 'does not match the number of clusters %i' + % (centers.shape, k)) + return centers -class KMeans(BaseEstimator, ClusterMixin): +class KMeans(BaseEstimator, ClusterMixin, TransformerMixin): """K-Means clustering Parameters @@ -606,11 +634,11 @@ class KMeans(BaseEstimator, ClusterMixin): The number of clusters to form as well as the number of centroids to generate. - max_iter : int + max_iter : int, default: 300 Maximum number of iterations of the k-means algorithm for a single run. - n_init: int, optional, default: 10 + n_init : int, default: 10 Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia. @@ -628,38 +656,55 @@ class KMeans(BaseEstimator, ClusterMixin): If an ndarray is passed, it should be of shape (n_clusters, n_features) and gives the initial centers. - precompute_distances : boolean + precompute_distances : {'auto', True, False} Precompute distances (faster but takes more memory). - tol: float, optional default: 1e-4 - Relative tolerance w.r.t. inertia to declare convergence + 'auto' : do not precompute distances if n_samples * n_clusters > 12 + million. This corresponds to about 100MB overhead per job using + double precision. + + True : always precompute distances - n_jobs: int + False : never precompute distances + + tol : float, default: 1e-4 + Relative tolerance with regards to inertia to declare convergence + + n_jobs : int, default: 1 The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is - used at all, which is useful for debuging. For n_jobs below -1, - (n_cpus + 1 - n_jobs) are used. Thus for n_jobs = -2, all CPUs but one + used at all, which is useful for debugging. For n_jobs below -1, + (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. - random_state: integer or numpy.RandomState, optional + random_state : integer or numpy.RandomState, optional The generator used to initialize the centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. + verbose : int, default 0 + Verbosity mode. + + copy_x : boolean, default True + When pre-computing distances it is more numerically accurate to center + the data first. If copy_x is True, then the original data is not + modified. If False, the original data is modified, and put back before + the function returns, but small numerical differences may be introduced + by subtracting and then adding the data mean. + Attributes ---------- - `cluster_centers_`: array, [n_clusters, n_features] + cluster_centers_ : array, [n_clusters, n_features] Coordinates of cluster centers - `labels_`: + labels_ : Labels of each point - `inertia_`: float - The value of the inertia criterion associated with the chosen - partition. + inertia_ : float + Sum of distances of samples to their closest cluster center. Notes ------ @@ -688,15 +733,14 @@ class KMeans(BaseEstimator, ClusterMixin): """ def __init__(self, n_clusters=8, init='k-means++', n_init=10, max_iter=300, - tol=1e-4, precompute_distances=True, - verbose=0, random_state=None, copy_x=True, n_jobs=1, k=None): + tol=1e-4, precompute_distances='auto', + verbose=0, random_state=None, copy_x=True, n_jobs=1): if hasattr(init, '__array__'): n_clusters = init.shape[0] - init = np.asanyarray(init, dtype=np.float64) + init = np.asarray(init, dtype=np.float64) self.n_clusters = n_clusters - self.k = k self.init = init self.max_iter = max_iter self.tol = tol @@ -709,55 +753,49 @@ def __init__(self, n_clusters=8, init='k-means++', n_init=10, max_iter=300, def _check_fit_data(self, X): """Verify that the number of samples given is larger than k""" - X = atleast2d_or_csr(X, dtype=np.float64) + X = check_array(X, accept_sparse='csr', dtype=np.float64) if X.shape[0] < self.n_clusters: raise ValueError("n_samples=%d should be >= n_clusters=%d" % ( X.shape[0], self.n_clusters)) return X def _check_test_data(self, X): - X = atleast2d_or_csr(X) + X = check_array(X, accept_sparse='csr') n_samples, n_features = X.shape expected_n_features = self.cluster_centers_.shape[1] if not n_features == expected_n_features: raise ValueError("Incorrect number of features. " "Got %d features, expected %d" % ( n_features, expected_n_features)) - if not X.dtype.kind is 'f': + if X.dtype.kind != 'f': warnings.warn("Got data type %s, converted to float " - "to avoid overflows" % X.dtype, - RuntimeWarning, stacklevel=2) + "to avoid overflows" % X.dtype, + RuntimeWarning, stacklevel=2) X = X.astype(np.float) return X - def _check_fitted(self): - if not hasattr(self, "cluster_centers_"): - raise AttributeError("Model has not been trained yet.") - def fit(self, X, y=None): - """Compute k-means""" - - if not self.k is None: - n_clusters = self.k - warnings.warn("Parameter k was renamed to n_clusters", - DeprecationWarning, stacklevel=2) - self.n_clusters = n_clusters - else: - n_clusters = self.n_clusters + """Compute k-means clustering. - self.random_state = check_random_state(self.random_state) + Parameters + ---------- + X : array-like or sparse matrix, shape=(n_samples, n_features) + """ + random_state = check_random_state(self.random_state) X = self._check_fit_data(X) - self.cluster_centers_, self.labels_, self.inertia_ = k_means( - X, n_clusters=n_clusters, init=self.init, n_init=self.n_init, - max_iter=self.max_iter, verbose=self.verbose, - precompute_distances=self.precompute_distances, - tol=self.tol, random_state=self.random_state, copy_x=self.copy_x, - n_jobs=self.n_jobs) + self.cluster_centers_, self.labels_, self.inertia_, self.n_iter_ = \ + k_means( + X, n_clusters=self.n_clusters, init=self.init, + n_init=self.n_init, max_iter=self.max_iter, + verbose=self.verbose, return_n_iter=True, + precompute_distances=self.precompute_distances, + tol=self.tol, random_state=random_state, copy_x=self.copy_x, + n_jobs=self.n_jobs) return self - def fit_predict(self, X): + def fit_predict(self, X, y=None): """Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by @@ -765,8 +803,20 @@ def fit_predict(self, X): """ return self.fit(X).labels_ + def fit_transform(self, X, y=None): + """Compute clustering and transform X to cluster-distance space. + + Equivalent to fit(X).transform(X), but more efficiently implemented. + """ + # Currently, this just skips a copy of the data if it is not in + # np.array or CSR format already. + # XXX This skips _check_test_data, which may change the dtype; + # we should refactor the input validation. + X = self._check_fit_data(X) + return self.fit(X)._transform(X) + def transform(self, X, y=None): - """Transform the data to a cluster-distance space + """Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by @@ -774,7 +824,7 @@ def transform(self, X, y=None): Parameters ---------- - X: {array-like, sparse matrix}, shape = [n_samples, n_features] + X : {array-like, sparse matrix}, shape = [n_samples, n_features] New data to transform. Returns @@ -782,8 +832,13 @@ def transform(self, X, y=None): X_new : array, shape [n_samples, k] X transformed in the new space. """ - self._check_fitted() + check_is_fitted(self, 'cluster_centers_') + X = self._check_test_data(X) + return self._transform(X) + + def _transform(self, X): + """guts of transform method; no input validation""" return euclidean_distances(X, self.cluster_centers_) def predict(self, X): @@ -795,68 +850,136 @@ def predict(self, X): Parameters ---------- - X: {array-like, sparse matrix}, shape = [n_samples, n_features] + X : {array-like, sparse matrix}, shape = [n_samples, n_features] New data to predict. Returns ------- - Y : array, shape [n_samples,] - Index of the closest center each sample belongs to. + labels : array, shape [n_samples,] + Index of the cluster each sample belongs to. """ - self._check_fitted() + check_is_fitted(self, 'cluster_centers_') + X = self._check_test_data(X) - x_squared_norms = _squared_norms(X) + x_squared_norms = row_norms(X, squared=True) return _labels_inertia(X, x_squared_norms, self.cluster_centers_)[0] - def score(self, X): + def score(self, X, y=None): """Opposite of the value of X on the K-means objective. Parameters ---------- - X: {array-like, sparse matrix}, shape = [n_samples, n_features] + X : {array-like, sparse matrix}, shape = [n_samples, n_features] New data. Returns ------- - score: float + score : float Opposite of the value of X on the K-means objective. """ - self._check_fitted() + check_is_fitted(self, 'cluster_centers_') + X = self._check_test_data(X) - x_squared_norms = _squared_norms(X) + x_squared_norms = row_norms(X, squared=True) return -_labels_inertia(X, x_squared_norms, self.cluster_centers_)[1] def _mini_batch_step(X, x_squared_norms, centers, counts, old_center_buffer, compute_squared_diff, - distances=None): - """Incremental update of the centers for the Minibatch K-Means algorithm + distances, random_reassign=False, + random_state=None, reassignment_ratio=.01, + verbose=False): + """Incremental update of the centers for the Minibatch K-Means algorithm. Parameters ---------- - X: array, shape (n_samples, n_features) + X : array, shape (n_samples, n_features) The original data array. - x_squared_norms: array, shape (n_samples,) + x_squared_norms : array, shape (n_samples,) Squared euclidean norm of each data point. - centers: array, shape (k, n_features) + centers : array, shape (k, n_features) The cluster centers. This array is MODIFIED IN PLACE - counts: array, shape (k,) + counts : array, shape (k,) The vector in which we keep track of the numbers of elements in a cluster. This array is MODIFIED IN PLACE - distances: array, dtype float64, shape (n_samples), optional + distances : array, dtype float64, shape (n_samples), optional If not None, should be a pre-allocated array that will be used to store - the distances of each sample to it's closest center. + the distances of each sample to its closest center. + May not be None when random_reassign is True. + + random_state : integer or numpy.RandomState, optional + The generator used to initialize the centers. If an integer is + given, it fixes the seed. Defaults to the global numpy random + number generator. + + random_reassign : boolean, optional + If True, centers with very low counts are randomly reassigned + to observations. + + reassignment_ratio : float, optional + Control the fraction of the maximum number of counts for a + center to be reassigned. A higher value means that low count + centers are more likely to be reassigned, which means that the + model will take longer to converge, but should converge in a + better clustering. + + verbose : bool, optional, default False + Controls the verbosity. + + compute_squared_diff : bool + If set to False, the squared diff computation is skipped. + + old_center_buffer : int + Copy of old centers for monitoring convergence. + + Returns + ------- + inertia : float + Sum of distances of samples to their closest cluster center. + + squared_diff : numpy array, shape (n_clusters,) + Squared distances between previous and updated cluster centers. + """ - # Perform label assignement to nearest centers + # Perform label assignment to nearest centers nearest_center, inertia = _labels_inertia(X, x_squared_norms, centers, distances=distances) - # implementation for the sparse CSR reprensation completely written in + if random_reassign and reassignment_ratio > 0: + random_state = check_random_state(random_state) + # Reassign clusters that have very low counts + to_reassign = counts < reassignment_ratio * counts.max() + # pick at most .5 * batch_size samples as new centers + if to_reassign.sum() > .5 * X.shape[0]: + indices_dont_reassign = np.argsort(counts)[int(.5 * X.shape[0]):] + to_reassign[indices_dont_reassign] = False + n_reassigns = to_reassign.sum() + if n_reassigns: + # Pick new clusters amongst observations with uniform probability + new_centers = choice(X.shape[0], replace=False, size=n_reassigns, + random_state=random_state) + if verbose: + print("[MiniBatchKMeans] Reassigning %i cluster centers." + % n_reassigns) + + if sp.issparse(X) and not sp.issparse(centers): + assign_rows_csr(X, + astype(new_centers, np.intp), + astype(np.where(to_reassign)[0], np.intp), + centers) + else: + centers[to_reassign] = X[new_centers] + # reset counts of reassigned centers, but don't reset them too small + # to avoid instant reassignment. This is a pretty dirty hack as it + # also modifies the learning rates. + counts[to_reassign] = np.min(counts[~to_reassign]) + + # implementation for the sparse CSR representation completely written in # cython if sp.issparse(X): return inertia, _k_means._mini_batch_update_csr( @@ -889,13 +1012,13 @@ def _mini_batch_step(X, x_squared_norms, centers, counts, # update the squared diff if necessary if compute_squared_diff: - squared_diff += np.sum( - (centers[center_idx] - old_center_buffer) ** 2) + diff = centers[center_idx].ravel() - old_center_buffer.ravel() + squared_diff += np.dot(diff, diff) return inertia, squared_diff -def _mini_batch_convergence(model, iteration_idx, n_iterations, tol, +def _mini_batch_convergence(model, iteration_idx, n_iter, tol, n_samples, centers_squared_diff, batch_inertia, context, verbose=0): """Helper function to encapsulte the early stopping logic""" @@ -923,37 +1046,37 @@ def _mini_batch_convergence(model, iteration_idx, n_iterations, tol, if verbose: progress_msg = ( 'Minibatch iteration %d/%d:' - 'mean batch inertia: %f, ewa inertia: %f ' % ( - iteration_idx + 1, n_iterations, batch_inertia, + ' mean batch inertia: %f, ewa inertia: %f ' % ( + iteration_idx + 1, n_iter, batch_inertia, ewa_inertia)) - print progress_msg + print(progress_msg) # Early stopping based on absolute tolerance on squared change of - # centers postion (using EWA smoothing) - if tol > 0.0 and ewa_diff < tol: + # centers position (using EWA smoothing) + if tol > 0.0 and ewa_diff <= tol: if verbose: - print 'Converged (small centers change) at iteration %d/%d' % ( - iteration_idx + 1, n_iterations) + print('Converged (small centers change) at iteration %d/%d' + % (iteration_idx + 1, n_iter)) return True # Early stopping heuristic due to lack of improvement on smoothed inertia ewa_inertia_min = context.get('ewa_inertia_min') no_improvement = context.get('no_improvement', 0) - if (ewa_inertia_min is None or ewa_inertia < ewa_inertia_min): + if ewa_inertia_min is None or ewa_inertia < ewa_inertia_min: no_improvement = 0 ewa_inertia_min = ewa_inertia else: no_improvement += 1 if (model.max_no_improvement is not None - and no_improvement >= model.max_no_improvement): + and no_improvement >= model.max_no_improvement): if verbose: - print ('Converged (lack of improvement in inertia)' - ' at iteration %d/%d' % ( - iteration_idx + 1, n_iterations)) + print('Converged (lack of improvement in inertia)' + ' at iteration %d/%d' + % (iteration_idx + 1, n_iter)) return True - # update the convergence context to maintain state across sucessive calls: + # update the convergence context to maintain state across successive calls: context['ewa_diff'] = ewa_diff context['ewa_inertia'] = ewa_inertia context['ewa_inertia_min'] = ewa_inertia_min @@ -975,14 +1098,14 @@ class MiniBatchKMeans(KMeans): Maximum number of iterations over the complete dataset before stopping independently of any early stopping criterion heuristics. - max_no_improvement : int, optional + max_no_improvement : int, default: 10 Control early stopping based on the consecutive number of mini batches that does not yield an improvement on the smoothed inertia. To disable convergence detection based on inertia, set max_no_improvement to None. - tol : float, optional + tol : float, default: 0.0 Control early stopping based on the relative center changes as measured by a smoothed, variance-normalized of the mean center squared position changes. This early stopping heuristics is @@ -993,16 +1116,16 @@ class MiniBatchKMeans(KMeans): To disable convergence detection based on normalized center change, set tol to 0.0 (default). - batch_size: int, optional, default: 100 + batch_size : int, optional, default: 100 Size of the mini batches. - init_size: int, optional, default: 3 * batch_size + init_size : int, optional, default: 3 * batch_size Number of samples to randomly sample for speeding up the - initialization (sometimes at the expense of accurracy): the + initialization (sometimes at the expense of accuracy): the only algorithm is initialized by running a batch KMeans on a - random subset of the data. This needs to be larger than k. + random subset of the data. This needs to be larger than n_clusters. - init : {'k-means++', 'random' or an ndarray} + init : {'k-means++', 'random' or an ndarray}, default: 'k-means++' Method for initialization, defaults to 'k-means++': 'k-means++' : selects initial cluster centers for k-mean @@ -1012,29 +1135,43 @@ class MiniBatchKMeans(KMeans): 'random': choose k observations (rows) at random from data for the initial centroids. - If an ndarray is passed, it should be of shape (n_clusters, n_features) and gives the initial centers. - compute_labels: boolean - Compute label assignements and inertia for the complete dataset + n_init : int, default=3 + Number of random initializations that are tried. + In contrast to KMeans, the algorithm is only run once, using the + best of the ``n_init`` initializations as measured by inertia. + + compute_labels : boolean, default=True + Compute label assignment and inertia for the complete dataset once the minibatch optimization has converged in fit. - random_state: integer or numpy.RandomState, optional + random_state : integer or numpy.RandomState, optional The generator used to initialize the centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. + reassignment_ratio : float, default: 0.01 + Control the fraction of the maximum number of counts for a + center to be reassigned. A higher value means that low count + centers are more easily reassigned, which means that the + model will take longer to converge, but should converge in a + better clustering. + + verbose : boolean, optional + Verbosity mode. + Attributes ---------- - `cluster_centers_`: array, [n_clusters, n_features] + cluster_centers_ : array, [n_clusters, n_features] Coordinates of cluster centers - `labels_`: + labels_ : Labels of each point (if compute_labels is set to True). - `inertia_`: float + inertia_ : float The value of the inertia criterion associated with the chosen partition (if compute_labels is set to True). The inertia is defined as the sum of square distances of samples to their nearest @@ -1048,37 +1185,45 @@ class MiniBatchKMeans(KMeans): def __init__(self, n_clusters=8, init='k-means++', max_iter=100, batch_size=100, verbose=0, compute_labels=True, random_state=None, tol=0.0, max_no_improvement=10, - init_size=None, n_init=3, k=None): + init_size=None, n_init=3, reassignment_ratio=0.01): - super(MiniBatchKMeans, self).__init__(n_clusters=n_clusters, init=init, - max_iter=max_iter, verbose=verbose, random_state=random_state, - tol=tol, n_init=n_init, k=k) + super(MiniBatchKMeans, self).__init__( + n_clusters=n_clusters, init=init, max_iter=max_iter, + verbose=verbose, random_state=random_state, tol=tol, n_init=n_init) self.max_no_improvement = max_no_improvement self.batch_size = batch_size self.compute_labels = compute_labels self.init_size = init_size + self.reassignment_ratio = reassignment_ratio def fit(self, X, y=None): """Compute the centroids on X by chunking it into mini-batches. Parameters ---------- - X: array-like, shape = [n_samples, n_features] + X : array-like, shape = [n_samples, n_features] Coordinates of the data points to cluster """ - self.random_state = check_random_state(self.random_state) - X = check_arrays(X, sparse_format="csr", copy=False, - check_ccontiguous=True, dtype=np.float64)[0] + random_state = check_random_state(self.random_state) + X = check_array(X, accept_sparse="csr", order='C', dtype=np.float64) n_samples, n_features = X.shape if n_samples < self.n_clusters: - raise ValueError("Number of samples smaller than number "\ + raise ValueError("Number of samples smaller than number " "of clusters.") + n_init = self.n_init if hasattr(self.init, '__array__'): self.init = np.ascontiguousarray(self.init, dtype=np.float64) + if n_init != 1: + warnings.warn( + 'Explicit initial center position passed: ' + 'performing only one init in MiniBatchKMeans instead of ' + 'n_init=%d' + % self.n_init, RuntimeWarning, stacklevel=2) + n_init = 1 - x_squared_norms = _squared_norms(X) + x_squared_norms = row_norms(X, squared=True) if self.tol > 0.0: tol = _tolerance(X, self.tol) @@ -1095,7 +1240,7 @@ def fit(self, X, y=None): distances = np.zeros(self.batch_size, dtype=np.float64) n_batches = int(np.ceil(float(n_samples) / self.batch_size)) - n_iterations = int(self.max_iter * n_batches) + n_iter = int(self.max_iter * n_batches) init_size = self.init_size if init_size is None: @@ -1104,17 +1249,17 @@ def fit(self, X, y=None): init_size = n_samples self.init_size_ = init_size - validation_indices = self.random_state.random_integers( - 0, n_samples - 1, init_size) + validation_indices = random_state.random_integers( + 0, n_samples - 1, init_size) X_valid = X[validation_indices] x_squared_norms_valid = x_squared_norms[validation_indices] # perform several inits with random sub-sets best_inertia = None - for init_idx in range(self.n_init): + for init_idx in range(n_init): if self.verbose: - print "Init %d/%d with method: %s" % ( - init_idx + 1, self.n_init, self.init) + print("Init %d/%d with method: %s" + % (init_idx + 1, n_init, self.init)) counts = np.zeros(self.n_clusters, dtype=np.int32) # TODO: once the `k_means` function works with sparse input we @@ -1124,23 +1269,23 @@ def fit(self, X, y=None): # expect n_samples to be very large when using MiniBatchKMeans cluster_centers = _init_centroids( X, self.n_clusters, self.init, - random_state=self.random_state, + random_state=random_state, x_squared_norms=x_squared_norms, init_size=init_size) - # Compute the label assignement on the init dataset + # Compute the label assignment on the init dataset batch_inertia, centers_squared_diff = _mini_batch_step( X_valid, x_squared_norms[validation_indices], cluster_centers, counts, old_center_buffer, False, - distances=distances) + distances=None, verbose=self.verbose) # Keep only the best cluster centers across independent inits on # the common validation set _, inertia = _labels_inertia(X_valid, x_squared_norms_valid, cluster_centers) if self.verbose: - print "Inertia for init %d/%d: %f" % ( - init_idx + 1, self.n_init, inertia) + print("Inertia for init %d/%d: %f" + % (init_idx + 1, n_init, inertia)) if best_inertia is None or inertia < best_inertia: self.cluster_centers_ = cluster_centers self.counts_ = counts @@ -1149,46 +1294,81 @@ def fit(self, X, y=None): # Empty context to be used inplace by the convergence check routine convergence_context = {} - # Perform the iterative optimization untill the final convergence + # Perform the iterative optimization until the final convergence # criterion - for iteration_idx in xrange(n_iterations): - - # Sample the minibatch from the full dataset - minibatch_indices = self.random_state.random_integers( + for iteration_idx in range(n_iter): + # Sample a minibatch from the full dataset + minibatch_indices = random_state.random_integers( 0, n_samples - 1, self.batch_size) # Perform the actual update step on the minibatch data batch_inertia, centers_squared_diff = _mini_batch_step( X[minibatch_indices], x_squared_norms[minibatch_indices], self.cluster_centers_, self.counts_, - old_center_buffer, tol > 0.0, distances=distances) - - # Monitor the convergence and do early stopping if necessary + old_center_buffer, tol > 0.0, distances=distances, + # Here we randomly choose whether to perform + # random reassignment: the choice is done as a function + # of the iteration index, and the minimum number of + # counts, in order to force this reassignment to happen + # every once in a while + random_reassign=((iteration_idx + 1) + % (10 + self.counts_.min()) == 0), + random_state=random_state, + reassignment_ratio=self.reassignment_ratio, + verbose=self.verbose) + + # Monitor convergence and do early stopping if necessary if _mini_batch_convergence( - self, iteration_idx, n_iterations, tol, n_samples, - centers_squared_diff, batch_inertia, convergence_context, - verbose=self.verbose): + self, iteration_idx, n_iter, tol, n_samples, + centers_squared_diff, batch_inertia, convergence_context, + verbose=self.verbose): break + self.n_iter_ = iteration_idx + 1 + if self.compute_labels: - if self.verbose: - print 'Computing label assignements and total inertia' - self.labels_, self.inertia_ = _labels_inertia( - X, x_squared_norms, self.cluster_centers_) + self.labels_, self.inertia_ = self._labels_inertia_minibatch(X) return self + def _labels_inertia_minibatch(self, X): + """Compute labels and inertia using mini batches. + + This is slightly slower than doing everything at once but preventes + memory errors / segfaults. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Input data. + + Returns + ------- + labels : array, shap (n_samples,) + Cluster labels for each point. + + inertia : float + Sum of squared distances of points to nearest cluster. + """ + if self.verbose: + print('Computing label assignment and total inertia') + x_squared_norms = row_norms(X, squared=True) + slices = gen_batches(X.shape[0], self.batch_size) + results = [_labels_inertia(X[s], x_squared_norms[s], + self.cluster_centers_) for s in slices] + labels, inertia = zip(*results) + return np.hstack(labels), np.sum(inertia) + def partial_fit(self, X, y=None): """Update k means estimate on a single mini-batch X. Parameters ---------- - X: array-like, shape = [n_samples, n_features] + X : array-like, shape = [n_samples, n_features] Coordinates of the data points to cluster. """ - self.random_state = check_random_state(self.random_state) - X = check_arrays(X, sparse_format="csr", copy=False)[0] + X = check_array(X, accept_sparse="csr") n_samples, n_features = X.shape if hasattr(self.init, '__array__'): self.init = np.ascontiguousarray(self.init, dtype=np.float64) @@ -1196,23 +1376,60 @@ def partial_fit(self, X, y=None): if n_samples == 0: return self - x_squared_norms = _squared_norms(X) - + x_squared_norms = row_norms(X, squared=True) + self.random_state_ = getattr(self, "random_state_", + check_random_state(self.random_state)) if (not hasattr(self, 'counts_') - or not hasattr(self, 'cluster_centers_')): + or not hasattr(self, 'cluster_centers_')): # this is the first call partial_fit on this object: # initialize the cluster centers self.cluster_centers_ = _init_centroids( - X, self.n_clusters, self.init, random_state=self.random_state, + X, self.n_clusters, self.init, + random_state=self.random_state_, x_squared_norms=x_squared_norms, init_size=self.init_size) self.counts_ = np.zeros(self.n_clusters, dtype=np.int32) + random_reassign = False + distances = None + else: + # The lower the minimum count is, the more we do random + # reassignment, however, we don't want to do random + # reassignment too often, to allow for building up counts + random_reassign = self.random_state_.randint( + 10 * (1 + self.counts_.min())) == 0 + distances = np.zeros(X.shape[0], dtype=np.float64) _mini_batch_step(X, x_squared_norms, self.cluster_centers_, - self.counts_, np.zeros(0, np.double), 0) + self.counts_, np.zeros(0, np.double), 0, + random_reassign=random_reassign, distances=distances, + random_state=self.random_state_, + reassignment_ratio=self.reassignment_ratio, + verbose=self.verbose) if self.compute_labels: self.labels_, self.inertia_ = _labels_inertia( X, x_squared_norms, self.cluster_centers_) return self + + def predict(self, X): + """Predict the closest cluster each sample in X belongs to. + + In the vector quantization literature, `cluster_centers_` is called + the code book and each value returned by `predict` is the index of + the closest code in the code book. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + New data to predict. + + Returns + ------- + labels : array, shape [n_samples,] + Index of the cluster each sample belongs to. + """ + check_is_fitted(self, 'cluster_centers_') + + X = self._check_test_data(X) + return self._labels_inertia_minibatch(X)[0] diff --git a/sklearn/cluster/mean_shift_.py b/sklearn/cluster/mean_shift_.py index 04c5995e6ea41..0c2ebb03e75ed 100644 --- a/sklearn/cluster/mean_shift_.py +++ b/sklearn/cluster/mean_shift_.py @@ -1,40 +1,55 @@ -"""Meanshift clustering. +"""Mean shift clustering algorithm. -Authors: Conrad Lee conradlee@gmail.com - Alexandre Gramfort alexandre.gramfort@inria.fr - Gael Varoquaux gael.varoquaux@normalesup.org +Mean shift clustering aims to discover *blobs* in a smooth density of +samples. It is a centroid based algorithm, which works by updating candidates +for centroids to be the mean of the points within a given region. These +candidates are then filtered in a post-processing stage to eliminate +near-duplicates to form the final set of centroids. + +Seeding is performed using a binning technique for scalability. """ -from collections import defaultdict +# Authors: Conrad Lee +# Alexandre Gramfort +# Gael Varoquaux + import numpy as np +import warnings -from ..utils import extmath, check_random_state +from collections import defaultdict +from ..externals import six +from ..utils.validation import check_is_fitted +from ..utils import extmath, check_random_state, gen_batches, check_array from ..base import BaseEstimator, ClusterMixin from ..neighbors import NearestNeighbors +from ..metrics.pairwise import pairwise_distances_argmin def estimate_bandwidth(X, quantile=0.3, n_samples=None, random_state=0): - """Estimate the bandwith to use with MeanShift algorithm + """Estimate the bandwidth to use with the mean-shift algorithm. + + That this function takes time at least quadratic in n_samples. For large + datasets, it's wise to set that parameter to a small value. Parameters ---------- - X: array [n_samples, n_features] - Input points + X : array-like, shape=[n_samples, n_features] + Input points. - quantile: float, default 0.3 + quantile : float, default 0.3 should be between [0, 1] - 0.5 means that the median is all pairwise distances is used + 0.5 means that the median of all pairwise distances is used. - n_samples: int - The number of samples to use. If None, all samples are used. + n_samples : int, optional + The number of samples to use. If not given, all samples are used. - random_state: int or RandomState - Pseudo number generator state used for random sampling. + random_state : int or RandomState + Pseudo-random number generator state used for random sampling. Returns ------- - bandwidth: float - The bandwidth parameter + bandwidth : float + The bandwidth parameter. """ random_state = check_random_state(random_state) if n_samples is not None: @@ -42,64 +57,89 @@ def estimate_bandwidth(X, quantile=0.3, n_samples=None, random_state=0): X = X[idx] nbrs = NearestNeighbors(n_neighbors=int(X.shape[0] * quantile)) nbrs.fit(X) - d, _ = nbrs.kneighbors(X, return_distance=True) - bandwidth = np.mean(np.max(d, axis=1)) - return bandwidth + bandwidth = 0. + for batch in gen_batches(len(X), 500): + d, _ = nbrs.kneighbors(X[batch, :], return_distance=True) + bandwidth += np.max(d, axis=1).sum() + return bandwidth / X.shape[0] -def mean_shift(X, bandwidth=None, seeds=None, bin_seeding=False, - cluster_all=True, max_iterations=300): - """Perform MeanShift Clustering of data using a flat kernel - Seed using a binning technique for scalability. +def mean_shift(X, bandwidth=None, seeds=None, bin_seeding=False, + min_bin_freq=1, cluster_all=True, max_iter=300, + max_iterations=None): + """Perform mean shift clustering of data using a flat kernel. Parameters ---------- - X : array [n_samples, n_features] - Input points + X : array-like, shape=[n_samples, n_features] + Input data. bandwidth : float, optional - kernel bandwidth - If bandwidth is not defined, it is set using - a heuristic given by the median of all pairwise distances + Kernel bandwidth. - seeds: array [n_seeds, n_features] - point used as initial kernel locations + If bandwidth is not given, it is determined using a heuristic based on + the median of all pairwise distances. This will take quadratic time in + the number of samples. The sklearn.cluster.estimate_bandwidth function + can be used to do this more efficiently. - bin_seeding: boolean + seeds : array-like, shape=[n_seeds, n_features] or None + Point used as initial kernel locations. If None and bin_seeding=False, + each data point is used as a seed. If None and bin_seeding=True, + see bin_seeding. + + bin_seeding : boolean, default=False If true, initial kernel locations are not locations of all points, but rather the location of the discretized version of points, where points are binned onto a grid whose coarseness corresponds to the bandwidth. Setting this option to True will speed up the algorithm because fewer seeds will be initialized. - default value: False - Ignored if seeds argument is not None + Ignored if seeds argument is not None. - min_bin_freq: int, optional + min_bin_freq : int, default=1 To speed up the algorithm, accept only those bins with at least - min_bin_freq points as seeds. If not defined, set to 1. + min_bin_freq points as seeds. + + cluster_all : boolean, default True + If true, then all points are clustered, even those orphans that are + not within any kernel. Orphans are assigned to the nearest kernel. + If false, then orphans are given cluster label -1. + + max_iter : int, default 300 + Maximum number of iterations, per seed point before the clustering + operation terminates (for that seed point), if has not converged yet. Returns ------- - cluster_centers : array [n_clusters, n_features] - Coordinates of cluster centers + cluster_centers : array, shape=[n_clusters, n_features] + Coordinates of cluster centers. - labels : array [n_samples] - cluster labels for each point + labels : array, shape=[n_samples] + Cluster labels for each point. Notes ----- - See examples/plot_meanshift.py for an example. + See examples/cluster/plot_meanshift.py for an example. """ + # FIXME To be removed in 0.18 + if max_iterations is not None: + warnings.warn("The `max_iterations` parameter has been renamed to " + "`max_iter` from version 0.16. The `max_iterations` " + "parameter will be removed in 0.18", DeprecationWarning) + max_iter = max_iterations + if bandwidth is None: bandwidth = estimate_bandwidth(X) + elif bandwidth <= 0: + raise ValueError("bandwidth needs to be greater than zero or None, got %f" % + bandwidth) if seeds is None: if bin_seeding: - seeds = get_bin_seeds(X, bandwidth) + seeds = get_bin_seeds(X, bandwidth, min_bin_freq) else: seeds = X n_samples, n_features = X.shape @@ -107,7 +147,7 @@ def mean_shift(X, bandwidth=None, seeds=None, bin_seeding=False, center_intensity_dict = {} nbrs = NearestNeighbors(radius=bandwidth).fit(X) - # For each seed, climb gradient until convergence or max_iterations + # For each seed, climb gradient until convergence or max_iter for my_mean in seeds: completed_iterations = 0 while True: @@ -119,13 +159,19 @@ def mean_shift(X, bandwidth=None, seeds=None, bin_seeding=False, break # Depending on seeding strategy this condition may occur my_old_mean = my_mean # save the old mean my_mean = np.mean(points_within, axis=0) - # If converged or at max_iterations, addS the cluster - if extmath.norm(my_mean - my_old_mean) < stop_thresh or \ - completed_iterations == max_iterations: + # If converged or at max_iter, adds the cluster + if (extmath.norm(my_mean - my_old_mean) < stop_thresh or + completed_iterations == max_iter): center_intensity_dict[tuple(my_mean)] = len(points_within) break completed_iterations += 1 + if not center_intensity_dict: + # nothing near seeds + raise ValueError("No point was within bandwidth=%f of any seed." + " Try a different seeding strategy or increase the bandwidth." + % bandwidth) + # POST PROCESSING: remove near duplicate points # If the distance between two kernels is less than the bandwidth, # then we have to remove one because it is a duplicate. Remove the @@ -157,7 +203,7 @@ def mean_shift(X, bandwidth=None, seeds=None, bin_seeding=False, def get_bin_seeds(X, bin_size, min_bin_freq=1): - """Finds seeds for mean_shift + """Finds seeds for mean_shift. Finds seeds by first binning data onto a grid whose lines are spaced bin_size apart, and then choosing those bins with at least @@ -166,67 +212,94 @@ def get_bin_seeds(X, bin_size, min_bin_freq=1): Parameters ---------- - X : array [n_samples, n_features] - Input points, the same points that will be used in mean_shift + X : array-like, shape=[n_samples, n_features] + Input points, the same points that will be used in mean_shift. - bin_size: float + bin_size : float Controls the coarseness of the binning. Smaller values lead to more seeding (which is computationally more expensive). If you're not sure how to set this, set it to the value of the bandwidth used - in clustering.mean_shift + in clustering.mean_shift. - min_bin_freq: integer, default 1 + min_bin_freq : integer, optional Only bins with at least min_bin_freq will be selected as seeds. Raising this value decreases the number of seeds found, which makes mean_shift computationally cheaper. Returns ------- - bin_seeds : array [n_samples, n_features] - points used as initial kernel posistions in clustering.mean_shift + bin_seeds : array-like, shape=[n_samples, n_features] + Points used as initial kernel positions in clustering.mean_shift. """ # Bin points bin_sizes = defaultdict(int) for point in X: - binned_point = np.cast[np.int32](point / bin_size) + binned_point = np.round(point / bin_size) bin_sizes[tuple(binned_point)] += 1 # Select only those bins as seeds which have enough members - bin_seeds = np.array([point for point, freq in bin_sizes.iteritems() if \ + bin_seeds = np.array([point for point, freq in six.iteritems(bin_sizes) if freq >= min_bin_freq], dtype=np.float32) + if len(bin_seeds) == len(X): + warnings.warn("Binning data failed with provided bin_size=%f, using data" + " points as seeds." % bin_size) + return X bin_seeds = bin_seeds * bin_size return bin_seeds class MeanShift(BaseEstimator, ClusterMixin): - """MeanShift clustering + """Mean shift clustering using a flat kernel. + + Mean shift clustering aims to discover "blobs" in a smooth density of + samples. It is a centroid-based algorithm, which works by updating + candidates for centroids to be the mean of the points within a given + region. These candidates are then filtered in a post-processing stage to + eliminate near-duplicates to form the final set of centroids. + + Seeding is performed using a binning technique for scalability. Parameters ---------- - bandwidth: float, optional - Bandwith used in the RBF kernel - If not set, the bandwidth is estimated. - See clustering.estimate_bandwidth + bandwidth : float, optional + Bandwidth used in the RBF kernel. + + If not given, the bandwidth is estimated using + sklearn.cluster.estimate_bandwidth; see the documentation for that + function for hints on scalability (see also the Notes, below). - seeds: array [n_samples, n_features], optional + seeds : array, shape=[n_samples, n_features], optional Seeds used to initialize kernels. If not set, the seeds are calculated by clustering.get_bin_seeds with bandwidth as the grid size and default values for other parameters. - cluster_all: boolean, default True + bin_seeding : boolean, optional + If true, initial kernel locations are not locations of all + points, but rather the location of the discretized version of + points, where points are binned onto a grid whose coarseness + corresponds to the bandwidth. Setting this option to True will speed + up the algorithm because fewer seeds will be initialized. + default value: False + Ignored if seeds argument is not None. + + min_bin_freq : int, optional + To speed up the algorithm, accept only those bins with at least + min_bin_freq points as seeds. If not defined, set to 1. + + cluster_all : boolean, default True If true, then all points are clustered, even those orphans that are not within any kernel. Orphans are assigned to the nearest kernel. If false, then orphans are given cluster label -1. Attributes ---------- - `cluster_centers_` : array, [n_clusters, n_features] - Coordinates of cluster centers + cluster_centers_ : array, [n_clusters, n_features] + Coordinates of cluster centers. - `labels_` : - Labels of each point + labels_ : + Labels of each point. Notes ----- @@ -239,11 +312,11 @@ class MeanShift(BaseEstimator, ClusterMixin): and T the number of points. In higher dimensions the complexity will tend towards O(T*n^2). - Scalability can be boosted by using fewer seeds, for examply by using + Scalability can be boosted by using fewer seeds, for example by using a higher value of min_bin_freq in the get_bin_seeds function. - Note that the estimate_bandwidth function is much less scalable than - the mean shift algorithm and will be the bottleneck if it is used. + Note that the estimate_bandwidth function is much less scalable than the + mean shift algorithm and will be the bottleneck if it is used. References ---------- @@ -254,26 +327,42 @@ class MeanShift(BaseEstimator, ClusterMixin): """ def __init__(self, bandwidth=None, seeds=None, bin_seeding=False, - cluster_all=True): + min_bin_freq=1, cluster_all=True): self.bandwidth = bandwidth self.seeds = seeds self.bin_seeding = bin_seeding self.cluster_all = cluster_all - self.cluster_centers_ = None - self.labels_ = None + self.min_bin_freq = min_bin_freq - def fit(self, X): - """ Compute MeanShift + def fit(self, X, y=None): + """Perform clustering. Parameters ----------- - X : array [n_samples, n_features] - Input points + X : array-like, shape=[n_samples, n_features] + Samples to cluster. """ + X = check_array(X) self.cluster_centers_, self.labels_ = \ - mean_shift(X, - bandwidth=self.bandwidth, - seeds=self.seeds, - bin_seeding=self.bin_seeding, - cluster_all=self.cluster_all) + mean_shift(X, bandwidth=self.bandwidth, seeds=self.seeds, + min_bin_freq=self.min_bin_freq, + bin_seeding=self.bin_seeding, + cluster_all=self.cluster_all) return self + + def predict(self, X): + """Predict the closest cluster each sample in X belongs to. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape=[n_samples, n_features] + New data to predict. + + Returns + ------- + labels : array, shape [n_samples,] + Index of the cluster each sample belongs to. + """ + check_is_fitted(self, "cluster_centers_") + + return pairwise_distances_argmin(X, self.cluster_centers_) diff --git a/sklearn/cluster/setup.py b/sklearn/cluster/setup.py index 34a7298820d36..90fc4111df243 100644 --- a/sklearn/cluster/setup.py +++ b/sklearn/cluster/setup.py @@ -1,5 +1,5 @@ # Author: Alexandre Gramfort -# License: BSD Style. +# License: BSD 3 clause import os from os.path import join @@ -20,7 +20,8 @@ def configuration(parent_package='', top_path=None): config = Configuration('cluster', parent_package, top_path) config.add_extension('_hierarchical', - sources=['_hierarchical.c'], + sources=['_hierarchical.cpp'], + language="c++", include_dirs=[numpy.get_include()], libraries=libraries) @@ -34,6 +35,7 @@ def configuration(parent_package='', top_path=None): extra_compile_args=blas_info.pop('extra_compile_args', []), **blas_info ) + return config if __name__ == '__main__': diff --git a/sklearn/cluster/spectral.py b/sklearn/cluster/spectral.py index 496e29a9fa8e1..39475929ebd0a 100644 --- a/sklearn/cluster/spectral.py +++ b/sklearn/cluster/spectral.py @@ -1,148 +1,165 @@ +# -*- coding: utf-8 -*- """Algorithms for spectral clustering""" # Author: Gael Varoquaux gael.varoquaux@normalesup.org -# License: BSD +# Brian Cheung +# Wei LI +# License: BSD 3 clause import warnings import numpy as np - from ..base import BaseEstimator, ClusterMixin -from ..utils import check_random_state -from ..utils.graph import graph_laplacian -from ..metrics.pairwise import rbf_kernel +from ..utils import check_random_state, as_float_array +from ..utils.validation import check_array +from ..utils.extmath import norm +from ..metrics.pairwise import pairwise_kernels from ..neighbors import kneighbors_graph +from ..manifold import spectral_embedding from .k_means_ import k_means -def spectral_embedding(adjacency, n_components=8, mode=None, - random_state=None): - """Project the sample on the first eigen vectors of the graph Laplacian - - The adjacency matrix is used to compute a normalized graph Laplacian - whose spectrum (especially the eigen vectors associated to the - smallest eigen values) has an interpretation in terms of minimal - number of cuts necessary to split the graph into comparably sized - components. - - This embedding can also 'work' even if the ``adjacency`` variable is - not strictly the adjacency matrix of a graph but more generally - an affinity or similarity matrix between samples (for instance the - heat kernel of a euclidean distance matrix or a k-NN matrix). - - However care must taken to always make the affinity matrix symmetric - so that the eigen vector decomposition works as expected. +def discretize(vectors, copy=True, max_svd_restarts=30, n_iter_max=20, + random_state=None): + """Search for a partition matrix (clustering) which is closest to the + eigenvector embedding. Parameters - ----------- - adjacency: array-like or sparse matrix, shape: (n_samples, n_samples) - The adjacency matrix of the graph to embed. + ---------- + vectors : array-like, shape: (n_samples, n_clusters) + The embedding space of the samples. - n_components: integer, optional - The dimension of the projection subspace. + copy : boolean, optional, default: True + Whether to copy vectors, or perform in-place normalization. - mode: {None, 'arpack' or 'amg'} - The eigenvalue decomposition strategy to use. AMG requires pyamg - to be installed. It can be faster on very large, sparse problems, - but may also lead to instabilities + max_svd_restarts : int, optional, default: 30 + Maximum number of attempts to restart SVD if convergence fails + + n_iter_max : int, optional, default: 30 + Maximum number of iterations to attempt in rotation and partition + matrix search if machine precision convergence is not reached random_state: int seed, RandomState instance, or None (default) A pseudo random number generator used for the initialization of the - lobpcg eigen vectors decomposition when mode == 'amg'. By default - arpack is used. + of the rotation matrix Returns - -------- - embedding: array, shape: (n_samples, n_components) - The reduced samples + ------- + labels : array of integers, shape: n_samples + The labels of the clusters. + + References + ---------- + + - Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + http://www1.icsi.berkeley.edu/~stellayu/publication/doc/2003kwayICCV.pdf Notes - ------ - The graph should contain only one connected component, elsewhere the - results make little sense. + ----- + + The eigenvector embedding is used to iteratively search for the + closest discrete partition. First, the eigenvector embedding is + normalized to the space of partition matrices. An optimal discrete + partition matrix closest to this normalized embedding multiplied by + an initial rotation is calculated. Fixing this discrete partition + matrix, an optimal rotation matrix is calculated. These two + calculations are performed until convergence. The discrete partition + matrix is returned as the clustering solution. Used in spectral + clustering, this method tends to be faster and more robust to random + initialization than k-means. + """ - from scipy import sparse - from ..utils.arpack import eigsh - from scipy.sparse.linalg import lobpcg - try: - from pyamg import smoothed_aggregation_solver - except ImportError: - if mode == "amg": - raise ValueError("The mode was set to 'amg', but pyamg is " - "not available.") + from scipy.sparse import csc_matrix + from scipy.linalg import LinAlgError random_state = check_random_state(random_state) - n_nodes = adjacency.shape[0] - # XXX: Should we check that the matrices given is symmetric - if mode is None: - mode = 'arpack' - laplacian, dd = graph_laplacian(adjacency, - normed=True, return_diag=True) - if (mode == 'arpack' - or not sparse.isspmatrix(laplacian) - or n_nodes < 5 * n_components): - # lobpcg used with mode='amg' has bugs for low number of nodes - - # We need to put the diagonal at zero - if not sparse.isspmatrix(laplacian): - laplacian.flat[::n_nodes + 1] = 0 - else: - laplacian = laplacian.tocoo() - diag_idx = (laplacian.row == laplacian.col) - laplacian.data[diag_idx] = 0 - # If the matrix has a small number of diagonals (as in the - # case of structured matrices comming from images), the - # dia format might be best suited for matvec products: - n_diags = np.unique(laplacian.row - laplacian.col).size - if n_diags <= 7: - # 3 or less outer diagonals on each side - laplacian = laplacian.todia() + vectors = as_float_array(vectors, copy=copy) + + eps = np.finfo(float).eps + n_samples, n_components = vectors.shape + + # Normalize the eigenvectors to an equal length of a vector of ones. + # Reorient the eigenvectors to point in the negative direction with respect + # to the first element. This may have to do with constraining the + # eigenvectors to lie in a specific quadrant to make the discretization + # search easier. + norm_ones = np.sqrt(n_samples) + for i in range(vectors.shape[1]): + vectors[:, i] = (vectors[:, i] / norm(vectors[:, i])) \ + * norm_ones + if vectors[0, i] != 0: + vectors[:, i] = -1 * vectors[:, i] * np.sign(vectors[0, i]) + + # Normalize the rows of the eigenvectors. Samples should lie on the unit + # hypersphere centered at the origin. This transforms the samples in the + # embedding space to the space of partition matrices. + vectors = vectors / np.sqrt((vectors ** 2).sum(axis=1))[:, np.newaxis] + + svd_restarts = 0 + has_converged = False + + # If there is an exception we try to randomize and rerun SVD again + # do this max_svd_restarts times. + while (svd_restarts < max_svd_restarts) and not has_converged: + + # Initialize first column of rotation matrix with a row of the + # eigenvectors + rotation = np.zeros((n_components, n_components)) + rotation[:, 0] = vectors[random_state.randint(n_samples), :].T + + # To initialize the rest of the rotation matrix, find the rows + # of the eigenvectors that are as orthogonal to each other as + # possible + c = np.zeros(n_samples) + for j in range(1, n_components): + # Accumulate c to ensure row is as orthogonal as possible to + # previous picks as well as current one + c += np.abs(np.dot(vectors, rotation[:, j - 1])) + rotation[:, j] = vectors[c.argmin(), :].T + + last_objective_value = 0.0 + n_iter = 0 + + while not has_converged: + n_iter += 1 + + t_discrete = np.dot(vectors, rotation) + + labels = t_discrete.argmax(axis=1) + vectors_discrete = csc_matrix( + (np.ones(len(labels)), (np.arange(0, n_samples), labels)), + shape=(n_samples, n_components)) + + t_svd = vectors_discrete.T * vectors + + try: + U, S, Vh = np.linalg.svd(t_svd) + svd_restarts += 1 + except LinAlgError: + print("SVD did not converge, randomizing and trying again") + break + + ncut_value = 2.0 * (n_samples - S.sum()) + if ((abs(ncut_value - last_objective_value) < eps) or + (n_iter > n_iter_max)): + has_converged = True else: - # csr has the fastest matvec and is thus best suited to - # arpack - laplacian = laplacian.tocsr() - - # Here we'll use shift-invert mode for fast eigenvalues - # (see http://docs.scipy.org/doc/scipy/reference/tutorial/arpack.html - # for a short explanation of what this means) - # Because the normalized Laplacian has eigenvalues between 0 and 2, - # I - L has eigenvalues between -1 and 1. ARPACK is most efficient - # when finding eigenvalues of largest magnitude (keyword which='LM') - # and when these eigenvalues are very large compared to the rest. - # For very large, very sparse graphs, I - L can have many, many - # eigenvalues very near 1.0. This leads to slow convergence. So - # instead, we'll use ARPACK's shift-invert mode, asking for the - # eigenvalues near 1.0. This effectively spreads-out the spectrum - # near 1.0 and leads to much faster convergence: potentially an - # orders-of-magnitude speedup over simply using keyword which='LA' - # in standard mode. - lambdas, diffusion_map = eigsh(-laplacian, k=n_components, - sigma=1.0, which='LM') - embedding = diffusion_map.T[::-1] * dd - elif mode == 'amg': - # Use AMG to get a preconditioner and speed up the eigenvalue - # problem. - laplacian = laplacian.astype(np.float) # lobpcg needs native floats - ml = smoothed_aggregation_solver(laplacian.tocsr()) - X = random_state.rand(laplacian.shape[0], n_components) - X[:, 0] = 1. / dd.ravel() - M = ml.aspreconditioner() - lambdas, diffusion_map = lobpcg(laplacian, X, M=M, tol=1.e-12, - largest=False) - embedding = diffusion_map.T * dd - if embedding.shape[0] == 1: - raise ValueError - else: - raise ValueError("Unknown value for mode: '%s'." - "Should be 'amg' or 'arpack'" % mode) - return embedding + # otherwise calculate rotation and continue + last_objective_value = ncut_value + rotation = np.dot(Vh.T, U.T) + + if not has_converged: + raise LinAlgError('SVD did not converge') + return labels -def spectral_clustering(affinity, n_clusters=8, n_components=None, mode=None, - random_state=None, n_init=10, k=None): - """Apply k-means to a projection to the normalized laplacian +def spectral_clustering(affinity, n_clusters=8, n_components=None, + eigen_solver=None, random_state=None, n_init=10, + eigen_tol=0.0, assign_labels='kmeans'): + """Apply clustering to a projection to the normalized laplacian. In practice Spectral Clustering is very useful when the structure of the individual clusters is highly non-convex or more generally when @@ -155,39 +172,52 @@ def spectral_clustering(affinity, n_clusters=8, n_components=None, mode=None, Parameters ----------- - affinity: array-like or sparse matrix, shape: (n_samples, n_samples) + affinity : array-like or sparse matrix, shape: (n_samples, n_samples) The affinity matrix describing the relationship of the samples to - embed. **Must be symetric**. + embed. **Must be symmetric**. Possible examples: - adjacency matrix of a graph, - heat kernel of the pairwise distance matrix of the samples, - - symmetic k-nearest neighbours connectivity matrix of the samples. + - symmetric k-nearest neighbours connectivity matrix of the samples. - n_clusters: integer, optional + n_clusters : integer, optional Number of clusters to extract. - n_components: integer, optional, default is k + n_components : integer, optional, default is n_clusters Number of eigen vectors to use for the spectral embedding - mode: {None, 'arpack' or 'amg'} + eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'} The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities - random_state: int seed, RandomState instance, or None (default) + random_state : int seed, RandomState instance, or None (default) A pseudo random number generator used for the initialization - of the lobpcg eigen vectors decomposition when mode == 'amg' + of the lobpcg eigen vectors decomposition when eigen_solver == 'amg' and by the K-Means initialization. - n_init: int, optional, default: 10 + n_init : int, optional, default: 10 Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia. + eigen_tol : float, optional, default: 0.0 + Stopping criterion for eigendecomposition of the Laplacian matrix + when using arpack eigen_solver. + + assign_labels : {'kmeans', 'discretize'}, default: 'kmeans' + The strategy to use to assign labels in the embedding + space. There are two ways to assign labels after the laplacian + embedding. k-means can be applied and is a popular choice. But it can + also be sensitive to initialization. Discretization is another + approach which is less sensitive to random initialization. See + the 'Multiclass spectral clustering' paper referenced below for + more details on the discretization approach. + Returns ------- - labels: array of integers, shape: n_samples + labels : array of integers, shape: n_samples The labels of the clusters. References @@ -201,6 +231,10 @@ def spectral_clustering(affinity, n_clusters=8, n_components=None, mode=None, Ulrike von Luxburg http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323 + - Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + http://www1.icsi.berkeley.edu/~stellayu/publication/doc/2003kwayICCV.pdf + Notes ------ The graph should contain only one connect component, elsewhere @@ -209,21 +243,29 @@ def spectral_clustering(affinity, n_clusters=8, n_components=None, mode=None, This algorithm solves the normalized cut for k=2: it is a normalized spectral clustering. """ - if not k is None: - warnings.warn("'k' was renamed to n_clusters", DeprecationWarning) - n_clusters = k + if assign_labels not in ('kmeans', 'discretize'): + raise ValueError("The 'assign_labels' parameter should be " + "'kmeans' or 'discretize', but '%s' was given" + % assign_labels) + random_state = check_random_state(random_state) n_components = n_clusters if n_components is None else n_components maps = spectral_embedding(affinity, n_components=n_components, - mode=mode, random_state=random_state) - maps = maps[1:] - _, labels, _ = k_means(maps.T, n_clusters, random_state=random_state, - n_init=n_init) + eigen_solver=eigen_solver, + random_state=random_state, + eigen_tol=eigen_tol, drop_first=False) + + if assign_labels == 'kmeans': + _, labels, _ = k_means(maps, n_clusters, random_state=random_state, + n_init=n_init) + else: + labels = discretize(maps, random_state=random_state) + return labels class SpectralClustering(BaseEstimator, ClusterMixin): - """Apply k-means to a projection to the normalized laplacian + """Apply clustering to a projection to the normalized laplacian. In practice Spectral Clustering is very useful when the structure of the individual clusters is highly non-convex or more generally when @@ -234,8 +276,9 @@ class SpectralClustering(BaseEstimator, ClusterMixin): If affinity is the adjacency matrix of a graph, this method can be used to find normalized graph cuts. - When calling ``fit``, an affinity matrix is constructed using either the - Gaussian (aka RBF) kernel of the euclidean distanced ``d(X, X)``:: + When calling ``fit``, an affinity matrix is constructed using either + kernel function such the Gaussian (aka RBF) kernel of the euclidean + distanced ``d(X, X)``:: np.exp(-gamma * d(X,X) ** 2) @@ -249,24 +292,39 @@ class SpectralClustering(BaseEstimator, ClusterMixin): n_clusters : integer, optional The dimension of the projection subspace. - affinity: string, 'nearest_neighbors', 'rbf' or 'precomputed' + affinity : string, array-like or callable, default 'rbf' + If a string, this may be one of 'nearest_neighbors', 'precomputed', + 'rbf' or one of the kernels supported by + `sklearn.metrics.pairwise_kernels`. - gamma: float - Scaling factor of Gaussian (rbf) affinity kernel. Ignored for + Only kernels that produce similarity scores (non-negative values that + increase with similarity) should be used. This property is not checked + by the clustering algorithm. + + gamma : float + Scaling factor of RBF, polynomial, exponential chi^2 and + sigmoid affinity kernel. Ignored for ``affinity='nearest_neighbors'``. - n_neighbors: integer + degree : float, default=3 + Degree of the polynomial kernel. Ignored by other kernels. + + coef0 : float, default=1 + Zero coefficient for polynomial and sigmoid kernels. + Ignored by other kernels. + + n_neighbors : integer Number of neighbors to use when constructing the affinity matrix using the nearest neighbors method. Ignored for ``affinity='rbf'``. - mode: {None, 'arpack' or 'amg'} + eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'} The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities random_state : int seed, RandomState instance, or None (default) A pseudo random number generator used for the initialization - of the lobpcg eigen vectors decomposition when mode == 'amg' + of the lobpcg eigen vectors decomposition when eigen_solver == 'amg' and by the K-Means initialization. n_init : int, optional, default: 10 @@ -274,14 +332,28 @@ class SpectralClustering(BaseEstimator, ClusterMixin): centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia. + eigen_tol : float, optional, default: 0.0 + Stopping criterion for eigendecomposition of the Laplacian matrix + when using arpack eigen_solver. + + assign_labels : {'kmeans', 'discretize'}, default: 'kmeans' + The strategy to use to assign labels in the embedding + space. There are two ways to assign labels after the laplacian + embedding. k-means can be applied and is a popular choice. But it can + also be sensitive to initialization. Discretization is another approach + which is less sensitive to random initialization. + + kernel_params : dictionary of string to any, optional + Parameters (keyword arguments) and values for kernel passed as + callable object. Ignored by other kernels. Attributes ---------- - `affinity_matrix_` : array-like, shape (n_samples, n_samples) + affinity_matrix_ : array-like, shape (n_samples, n_samples) Affinity matrix used for clustering. Available only if after calling ``fit``. - `labels_` : + labels_ : Labels of each point Notes @@ -310,23 +382,30 @@ class SpectralClustering(BaseEstimator, ClusterMixin): - A Tutorial on Spectral Clustering, 2007 Ulrike von Luxburg http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323 + + - Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + http://www1.icsi.berkeley.edu/~stellayu/publication/doc/2003kwayICCV.pdf """ - def __init__(self, n_clusters=8, mode=None, random_state=None, n_init=10, - gamma=1., affinity='rbf', n_neighbors=10, k=None, - precomputed=False): - if not k is None: - warnings.warn("'k' was renamed to n_clusters", DeprecationWarning) - n_clusters = k + def __init__(self, n_clusters=8, eigen_solver=None, random_state=None, + n_init=10, gamma=1., affinity='rbf', n_neighbors=10, + eigen_tol=0.0, assign_labels='kmeans', degree=3, coef0=1, + kernel_params=None): self.n_clusters = n_clusters - self.mode = mode + self.eigen_solver = eigen_solver self.random_state = random_state self.n_init = n_init self.gamma = gamma self.affinity = affinity self.n_neighbors = n_neighbors + self.eigen_tol = eigen_tol + self.assign_labels = assign_labels + self.degree = degree + self.coef0 = coef0 + self.kernel_params = kernel_params - def fit(self, X): + def fit(self, X, y=None): """Creates an affinity matrix for X using the selected affinity, then applies spectral clustering to this affinity matrix. @@ -336,28 +415,39 @@ def fit(self, X): OR, if affinity==`precomputed`, a precomputed affinity matrix of shape (n_samples, n_samples) """ + X = check_array(X, accept_sparse=['csr', 'csc', 'coo'], + dtype=np.float64) if X.shape[0] == X.shape[1] and self.affinity != "precomputed": warnings.warn("The spectral clustering API has changed. ``fit``" - "now constructs an affinity matrix from data. To use " - "a custom affinity matrix, set ``affinity=precomputed``.") + "now constructs an affinity matrix from data. To use" + " a custom affinity matrix, " + "set ``affinity=precomputed``.") - if self.affinity == 'rbf': - self.affinity_matrix_ = rbf_kernel(X, gamma=self.gamma) - - elif self.affinity == 'nearest_neighbors': - connectivity = kneighbors_graph(X, n_neighbors=self.n_neighbors) + if self.affinity == 'nearest_neighbors': + connectivity = kneighbors_graph(X, n_neighbors=self.n_neighbors, include_self=True) self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T) elif self.affinity == 'precomputed': self.affinity_matrix_ = X else: - raise ValueError("Invalid 'affinity'. Expected 'rbf', " - "'nearest_neighbors' or 'precomputed', got '%s'." - % self.affinity_matrix) - - self.random_state = check_random_state(self.random_state) + params = self.kernel_params + if params is None: + params = {} + if not callable(self.affinity): + params['gamma'] = self.gamma + params['degree'] = self.degree + params['coef0'] = self.coef0 + self.affinity_matrix_ = pairwise_kernels(X, metric=self.affinity, + filter_params=True, + **params) + + random_state = check_random_state(self.random_state) self.labels_ = spectral_clustering(self.affinity_matrix_, - n_clusters=self.n_clusters, mode=self.mode, - random_state=self.random_state, n_init=self.n_init) + n_clusters=self.n_clusters, + eigen_solver=self.eigen_solver, + random_state=random_state, + n_init=self.n_init, + eigen_tol=self.eigen_tol, + assign_labels=self.assign_labels) return self @property diff --git a/sklearn/cluster/tests/common.py b/sklearn/cluster/tests/common.py index ae5ff6c44d05a..957ebcf186596 100644 --- a/sklearn/cluster/tests/common.py +++ b/sklearn/cluster/tests/common.py @@ -14,12 +14,12 @@ def generate_clustered_data(seed=0, n_clusters=3, n_features=2, prng = np.random.RandomState(seed) # the data is voluntary shifted away from zero to check clustering - # algorithm robustness w.r.t. non centered data - means = np.array([[1, 1, 1, 0], + # algorithm robustness with regards to non centered data + means = np.array([[1, 1, 1, 0], [-1, -1, 0, 1], [1, -1, 1, 1], [-1, 1, 1, 0], - ]) + 10 + ]) + 10 X = np.empty((0, n_features)) for i in range(n_clusters): diff --git a/sklearn/cluster/tests/test_affinity_propagation.py b/sklearn/cluster/tests/test_affinity_propagation.py index 3d3157c3f6845..c823f0c3dcd10 100644 --- a/sklearn/cluster/tests/test_affinity_propagation.py +++ b/sklearn/cluster/tests/test_affinity_propagation.py @@ -4,10 +4,13 @@ """ import numpy as np -from numpy.testing import assert_equal, assert_array_equal -from sklearn.cluster.affinity_propagation_ import AffinityPropagation, \ - affinity_propagation +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_raises + +from sklearn.cluster.affinity_propagation_ import AffinityPropagation +from sklearn.cluster.affinity_propagation_ import affinity_propagation from sklearn.datasets.samples_generator import make_blobs from sklearn.metrics import euclidean_distances @@ -18,14 +21,13 @@ def test_affinity_propagation(): - """Affinity Propagation algorithm - """ + """Affinity Propagation algorithm """ # Compute similarities S = -euclidean_distances(X, squared=True) preference = np.median(S) * 10 # Compute Affinity Propagation - cluster_centers_indices, labels = affinity_propagation(S, - preference=preference) + cluster_centers_indices, labels = affinity_propagation( + S, preference=preference) n_clusters_ = len(cluster_centers_indices) @@ -34,7 +36,7 @@ def test_affinity_propagation(): af = AffinityPropagation(preference=preference, affinity="precomputed") labels_precomputed = af.fit(S).labels_ - af = AffinityPropagation(preference=preference) + af = AffinityPropagation(preference=preference, verbose=True) labels = af.fit(X).labels_ assert_array_equal(labels, labels_precomputed) @@ -47,5 +49,32 @@ def test_affinity_propagation(): # Test also with no copy _, labels_no_copy = affinity_propagation(S, preference=preference, - copy=False) + copy=False) assert_array_equal(labels, labels_no_copy) + + # Test input validation + assert_raises(ValueError, affinity_propagation, S[:, :-1]) + assert_raises(ValueError, affinity_propagation, S, damping=0) + af = AffinityPropagation(affinity="unknown") + assert_raises(ValueError, af.fit, X) + + +def test_affinity_propagation_predict(): + """Test AffinityPropagation.predict""" + af = AffinityPropagation(affinity="euclidean") + labels = af.fit_predict(X) + labels2 = af.predict(X) + assert_array_equal(labels, labels2) + + +def test_affinity_propagation_predict_error(): + """Test exception in AffinityPropagation.predict""" + # Not fitted. + af = AffinityPropagation(affinity="euclidean") + assert_raises(ValueError, af.predict, X) + + # Predict not supported when affinity="precomputed". + S = np.dot(X, X.T) + af = AffinityPropagation(affinity="precomputed") + af.fit(S) + assert_raises(ValueError, af.predict, X) diff --git a/sklearn/cluster/tests/test_bicluster.py b/sklearn/cluster/tests/test_bicluster.py new file mode 100644 index 0000000000000..31513bfdfc641 --- /dev/null +++ b/sklearn/cluster/tests/test_bicluster.py @@ -0,0 +1,264 @@ +"""Testing for Spectral Biclustering methods""" + +import numpy as np +from scipy.sparse import csr_matrix, issparse + +from sklearn.grid_search import ParameterGrid + +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import SkipTest + +from sklearn.base import BaseEstimator, BiclusterMixin + +from sklearn.cluster.bicluster import SpectralCoclustering +from sklearn.cluster.bicluster import SpectralBiclustering +from sklearn.cluster.bicluster import _scale_normalize +from sklearn.cluster.bicluster import _bistochastic_normalize +from sklearn.cluster.bicluster import _log_normalize + +from sklearn.metrics import consensus_score + +from sklearn.datasets import make_biclusters, make_checkerboard + + +class MockBiclustering(BaseEstimator, BiclusterMixin): + # Mock object for testing get_submatrix. + def __init__(self): + pass + + def get_indices(self, i): + # Overridden to reproduce old get_submatrix test. + return (np.where([True, True, False, False, True])[0], + np.where([False, False, True, True])[0]) + + +def test_get_submatrix(): + data = np.arange(20).reshape(5, 4) + model = MockBiclustering() + + for X in (data, csr_matrix(data), data.tolist()): + submatrix = model.get_submatrix(0, X) + if issparse(submatrix): + submatrix = submatrix.toarray() + assert_array_equal(submatrix, [[2, 3], + [6, 7], + [18, 19]]) + submatrix[:] = -1 + if issparse(X): + X = X.toarray() + assert_true(np.all(X != -1)) + + +def _test_shape_indices(model): + """Test get_shape and get_indices on fitted model.""" + for i in range(model.n_clusters): + m, n = model.get_shape(i) + i_ind, j_ind = model.get_indices(i) + assert_equal(len(i_ind), m) + assert_equal(len(j_ind), n) + + +def test_spectral_coclustering(): + """Test Dhillon's Spectral CoClustering on a simple problem.""" + param_grid = {'svd_method': ['randomized', 'arpack'], + 'n_svd_vecs': [None, 20], + 'mini_batch': [False, True], + 'init': ['k-means++'], + 'n_init': [10], + 'n_jobs': [1]} + random_state = 0 + S, rows, cols = make_biclusters((30, 30), 3, noise=0.5, + random_state=random_state) + S -= S.min() # needs to be nonnegative before making it sparse + S = np.where(S < 1, 0, S) # threshold some values + for mat in (S, csr_matrix(S)): + for kwargs in ParameterGrid(param_grid): + model = SpectralCoclustering(n_clusters=3, + random_state=random_state, + **kwargs) + model.fit(mat) + + assert_equal(model.rows_.shape, (3, 30)) + assert_array_equal(model.rows_.sum(axis=0), np.ones(30)) + assert_array_equal(model.columns_.sum(axis=0), np.ones(30)) + assert_equal(consensus_score(model.biclusters_, + (rows, cols)), 1) + + _test_shape_indices(model) + + +def test_spectral_biclustering(): + """Test Kluger methods on a checkerboard dataset.""" + S, rows, cols = make_checkerboard((30, 30), 3, noise=0.5, + random_state=0) + + non_default_params = {'method': ['scale', 'log'], + 'svd_method': ['arpack'], + 'n_svd_vecs': [20], + 'mini_batch': [True]} + + for mat in (S, csr_matrix(S)): + for param_name, param_values in non_default_params.items(): + for param_value in param_values: + + model = SpectralBiclustering( + n_clusters=3, + n_init=3, + init='k-means++', + random_state=0, + ) + model.set_params(**dict([(param_name, param_value)])) + + if issparse(mat) and model.get_params().get('method') == 'log': + # cannot take log of sparse matrix + assert_raises(ValueError, model.fit, mat) + continue + else: + model.fit(mat) + + assert_equal(model.rows_.shape, (9, 30)) + assert_equal(model.columns_.shape, (9, 30)) + assert_array_equal(model.rows_.sum(axis=0), + np.repeat(3, 30)) + assert_array_equal(model.columns_.sum(axis=0), + np.repeat(3, 30)) + assert_equal(consensus_score(model.biclusters_, + (rows, cols)), 1) + + _test_shape_indices(model) + + +def _do_scale_test(scaled): + """Check that rows sum to one constant, and columns to another.""" + row_sum = scaled.sum(axis=1) + col_sum = scaled.sum(axis=0) + if issparse(scaled): + row_sum = np.asarray(row_sum).squeeze() + col_sum = np.asarray(col_sum).squeeze() + assert_array_almost_equal(row_sum, np.tile(row_sum.mean(), 100), + decimal=1) + assert_array_almost_equal(col_sum, np.tile(col_sum.mean(), 100), + decimal=1) + + +def _do_bistochastic_test(scaled): + """Check that rows and columns sum to the same constant.""" + _do_scale_test(scaled) + assert_almost_equal(scaled.sum(axis=0).mean(), + scaled.sum(axis=1).mean(), + decimal=1) + + +def test_scale_normalize(): + generator = np.random.RandomState(0) + X = generator.rand(100, 100) + for mat in (X, csr_matrix(X)): + scaled, _, _ = _scale_normalize(mat) + _do_scale_test(scaled) + if issparse(mat): + assert issparse(scaled) + + +def test_bistochastic_normalize(): + generator = np.random.RandomState(0) + X = generator.rand(100, 100) + for mat in (X, csr_matrix(X)): + scaled = _bistochastic_normalize(mat) + _do_bistochastic_test(scaled) + if issparse(mat): + assert issparse(scaled) + + +def test_log_normalize(): + # adding any constant to a log-scaled matrix should make it + # bistochastic + generator = np.random.RandomState(0) + mat = generator.rand(100, 100) + scaled = _log_normalize(mat) + 1 + _do_bistochastic_test(scaled) + + +def test_fit_best_piecewise(): + model = SpectralBiclustering(random_state=0) + vectors = np.array([[0, 0, 0, 1, 1, 1], + [2, 2, 2, 3, 3, 3], + [0, 1, 2, 3, 4, 5]]) + best = model._fit_best_piecewise(vectors, n_best=2, n_clusters=2) + assert_array_equal(best, vectors[:2]) + + +def test_project_and_cluster(): + model = SpectralBiclustering(random_state=0) + data = np.array([[1, 1, 1], + [1, 1, 1], + [3, 6, 3], + [3, 6, 3]]) + vectors = np.array([[1, 0], + [0, 1], + [0, 0]]) + for mat in (data, csr_matrix(data)): + labels = model._project_and_cluster(data, vectors, + n_clusters=2) + assert_array_equal(labels, [0, 0, 1, 1]) + + +def test_perfect_checkerboard(): + raise SkipTest("This test is failing on the buildbot, but cannot" + " reproduce. Temporarily disabling it until it can be" + " reproduced and fixed.") + model = SpectralBiclustering(3, svd_method="arpack", random_state=0) + + S, rows, cols = make_checkerboard((30, 30), 3, noise=0, + random_state=0) + model.fit(S) + assert_equal(consensus_score(model.biclusters_, + (rows, cols)), 1) + + S, rows, cols = make_checkerboard((40, 30), 3, noise=0, + random_state=0) + model.fit(S) + assert_equal(consensus_score(model.biclusters_, + (rows, cols)), 1) + + S, rows, cols = make_checkerboard((30, 40), 3, noise=0, + random_state=0) + model.fit(S) + assert_equal(consensus_score(model.biclusters_, + (rows, cols)), 1) + + +def test_errors(): + data = np.arange(25).reshape((5, 5)) + + model = SpectralBiclustering(n_clusters=(3, 3, 3)) + assert_raises(ValueError, model.fit, data) + + model = SpectralBiclustering(n_clusters='abc') + assert_raises(ValueError, model.fit, data) + + model = SpectralBiclustering(n_clusters=(3, 'abc')) + assert_raises(ValueError, model.fit, data) + + model = SpectralBiclustering(method='unknown') + assert_raises(ValueError, model.fit, data) + + model = SpectralBiclustering(svd_method='unknown') + assert_raises(ValueError, model.fit, data) + + model = SpectralBiclustering(n_components=0) + assert_raises(ValueError, model.fit, data) + + model = SpectralBiclustering(n_best=0) + assert_raises(ValueError, model.fit, data) + + model = SpectralBiclustering(n_components=3, n_best=4) + assert_raises(ValueError, model.fit, data) + + model = SpectralBiclustering() + data = np.arange(27).reshape((3, 3, 3)) + assert_raises(ValueError, model.fit, data) diff --git a/sklearn/cluster/tests/test_birch.py b/sklearn/cluster/tests/test_birch.py new file mode 100644 index 0000000000000..3f51769482df3 --- /dev/null +++ b/sklearn/cluster/tests/test_birch.py @@ -0,0 +1,160 @@ +""" +Tests for the birch clustering algorithm. +""" + +from scipy import sparse +import numpy as np + +from sklearn.cluster.tests.common import generate_clustered_data +from sklearn.cluster.birch import Birch +from sklearn.cluster.hierarchical import AgglomerativeClustering +from sklearn.datasets import make_blobs +from sklearn.linear_model import ElasticNet +from sklearn.metrics import pairwise_distances_argmin, v_measure_score + +from sklearn.utils.testing import assert_greater_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_warns + + +def test_n_samples_leaves_roots(): + """Sanity check for the number of samples in leaves and roots""" + X, y = make_blobs(n_samples=10) + brc = Birch() + brc.fit(X) + n_samples_root = sum([sc.n_samples_ for sc in brc.root_.subclusters_]) + n_samples_leaves = sum([sc.n_samples_ for leaf in brc._get_leaves() + for sc in leaf.subclusters_]) + assert_equal(n_samples_leaves, X.shape[0]) + assert_equal(n_samples_root, X.shape[0]) + + +def test_partial_fit(): + """Test that fit is equivalent to calling partial_fit multiple times""" + X, y = make_blobs(n_samples=100) + brc = Birch(n_clusters=3) + brc.fit(X) + brc_partial = Birch(n_clusters=None) + brc_partial.partial_fit(X[:50]) + brc_partial.partial_fit(X[50:]) + assert_array_equal(brc_partial.subcluster_centers_, + brc.subcluster_centers_) + + # Test that same global labels are obtained after calling partial_fit + # with None + brc_partial.set_params(n_clusters=3) + brc_partial.partial_fit(None) + assert_array_equal(brc_partial.subcluster_labels_, brc.subcluster_labels_) + + +def test_birch_predict(): + """Test the predict method predicts the nearest centroid.""" + rng = np.random.RandomState(0) + X = generate_clustered_data(n_clusters=3, n_features=3, + n_samples_per_cluster=10) + + # n_samples * n_samples_per_cluster + shuffle_indices = np.arange(30) + rng.shuffle(shuffle_indices) + X_shuffle = X[shuffle_indices, :] + brc = Birch(n_clusters=4, threshold=1.) + brc.fit(X_shuffle) + centroids = brc.subcluster_centers_ + assert_array_equal(brc.labels_, brc.predict(X_shuffle)) + nearest_centroid = pairwise_distances_argmin(X_shuffle, centroids) + assert_almost_equal(v_measure_score(nearest_centroid, brc.labels_), 1.0) + + +def test_n_clusters(): + """Test that n_clusters param works properly""" + X, y = make_blobs(n_samples=100, centers=10) + brc1 = Birch(n_clusters=10) + brc1.fit(X) + assert_greater(len(brc1.subcluster_centers_), 10) + assert_equal(len(np.unique(brc1.labels_)), 10) + + # Test that n_clusters = Agglomerative Clustering gives + # the same results. + gc = AgglomerativeClustering(n_clusters=10) + brc2 = Birch(n_clusters=gc) + brc2.fit(X) + assert_array_equal(brc1.subcluster_labels_, brc2.subcluster_labels_) + assert_array_equal(brc1.labels_, brc2.labels_) + + # Test that the wrong global clustering step raises an Error. + clf = ElasticNet() + brc3 = Birch(n_clusters=clf) + assert_raises(ValueError, brc3.fit, X) + + # Test that a small number of clusters raises a warning. + brc4 = Birch(threshold=10000.) + assert_warns(UserWarning, brc4.fit, X) + + +def test_sparse_X(): + """Test that sparse and dense data give same results""" + X, y = make_blobs(n_samples=100, centers=10) + brc = Birch(n_clusters=10) + brc.fit(X) + + csr = sparse.csr_matrix(X) + brc_sparse = Birch(n_clusters=10) + brc_sparse.fit(csr) + + assert_array_equal(brc.labels_, brc_sparse.labels_) + assert_array_equal(brc.subcluster_centers_, + brc_sparse.subcluster_centers_) + + +def check_branching_factor(node, branching_factor): + subclusters = node.subclusters_ + assert_greater_equal(branching_factor, len(subclusters)) + for cluster in subclusters: + if cluster.child_: + check_branching_factor(cluster.child_, branching_factor) + + +def test_branching_factor(): + """Test that nodes have at max branching_factor number of subclusters""" + X, y = make_blobs() + branching_factor = 9 + + # Purposefully set a low threshold to maximize the subclusters. + brc = Birch(n_clusters=None, branching_factor=branching_factor, + threshold=0.01) + brc.fit(X) + check_branching_factor(brc.root_, branching_factor) + brc = Birch(n_clusters=3, branching_factor=branching_factor, + threshold=0.01) + brc.fit(X) + check_branching_factor(brc.root_, branching_factor) + + # Raises error when branching_factor is set to one. + brc = Birch(n_clusters=None, branching_factor=1, threshold=0.01) + assert_raises(ValueError, brc.fit, X) + + +def check_threshold(birch_instance, threshold): + """Use the leaf linked list for traversal""" + current_leaf = birch_instance.dummy_leaf_.next_leaf_ + while current_leaf: + subclusters = current_leaf.subclusters_ + for sc in subclusters: + assert_greater_equal(threshold, sc.radius) + current_leaf = current_leaf.next_leaf_ + + +def test_threshold(): + """Test that the leaf subclusters have a threshold lesser than radius""" + X, y = make_blobs(n_samples=80, centers=4) + brc = Birch(threshold=0.5, n_clusters=None) + brc.fit(X) + check_threshold(brc, 0.5) + + brc = Birch(threshold=5.0, n_clusters=None) + brc.fit(X) + check_threshold(brc, 5.) diff --git a/sklearn/cluster/tests/test_dbscan.py b/sklearn/cluster/tests/test_dbscan.py index 89f1b13f1579d..808c4027328aa 100644 --- a/sklearn/cluster/tests/test_dbscan.py +++ b/sklearn/cluster/tests/test_dbscan.py @@ -5,11 +5,19 @@ import pickle import numpy as np -from numpy.testing import assert_equal + from scipy.spatial import distance +from scipy import sparse -from sklearn.cluster.dbscan_ import DBSCAN, dbscan -from .common import generate_clustered_data +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_in +from sklearn.utils.testing import assert_not_in +from sklearn.cluster.dbscan_ import DBSCAN +from sklearn.cluster.dbscan_ import dbscan +from sklearn.cluster.tests.common import generate_clustered_data +from sklearn.metrics.pairwise import pairwise_distances n_clusters = 3 @@ -25,8 +33,8 @@ def test_dbscan_similarity(): D = distance.squareform(distance.pdist(X)) D /= np.max(D) # Compute DBSCAN - core_samples, labels = dbscan(D, metric="precomputed", - eps=eps, min_samples=min_samples) + core_samples, labels = dbscan(D, metric="precomputed", eps=eps, + min_samples=min_samples) # number of clusters, ignoring noise if present n_clusters_1 = len(set(labels)) - (1 if -1 in labels else 0) @@ -48,8 +56,8 @@ def test_dbscan_feature(): metric = 'euclidean' # Compute DBSCAN # parameters chosen for task - core_samples, labels = dbscan(X, metric=metric, - eps=eps, min_samples=min_samples) + core_samples, labels = dbscan(X, metric=metric, eps=eps, + min_samples=min_samples) # number of clusters, ignoring noise if present n_clusters_1 = len(set(labels)) - int(-1 in labels) @@ -62,6 +70,26 @@ def test_dbscan_feature(): assert_equal(n_clusters_2, n_clusters) +def test_dbscan_sparse(): + core_sparse, labels_sparse = dbscan(sparse.lil_matrix(X), eps=.8, + min_samples=10) + core_dense, labels_dense = dbscan(X, eps=.8, min_samples=10) + assert_array_equal(core_dense, core_sparse) + assert_array_equal(labels_dense, labels_sparse) + + +def test_dbscan_no_core_samples(): + rng = np.random.RandomState(0) + X = rng.rand(40, 10) + X[X < .8] = 0 + + for X_ in [X, sparse.csr_matrix(X)]: + db = DBSCAN(min_samples=6).fit(X_) + assert_array_equal(db.components_, np.empty((0, X_.shape[1]))) + assert_array_equal(db.labels_, -1) + assert_equal(db.core_sample_indices_.shape, (0,)) + + def test_dbscan_callable(): """Tests the DBSCAN algorithm with a callable metric.""" # Parameters chosen specifically for this task. @@ -72,21 +100,162 @@ def test_dbscan_callable(): metric = distance.euclidean # Compute DBSCAN # parameters chosen for task - core_samples, labels = dbscan(X, metric=metric, - eps=eps, min_samples=min_samples) + core_samples, labels = dbscan(X, metric=metric, eps=eps, + min_samples=min_samples, + algorithm='ball_tree') # number of clusters, ignoring noise if present n_clusters_1 = len(set(labels)) - int(-1 in labels) assert_equal(n_clusters_1, n_clusters) - db = DBSCAN(metric=metric, eps=eps, min_samples=min_samples) + db = DBSCAN(metric=metric, eps=eps, min_samples=min_samples, + algorithm='ball_tree') labels = db.fit(X).labels_ n_clusters_2 = len(set(labels)) - int(-1 in labels) assert_equal(n_clusters_2, n_clusters) +def test_dbscan_balltree(): + """Tests the DBSCAN algorithm with balltree for neighbor calculation.""" + eps = 0.8 + min_samples = 10 + + D = pairwise_distances(X) + core_samples, labels = dbscan(D, metric="precomputed", eps=eps, + min_samples=min_samples) + + # number of clusters, ignoring noise if present + n_clusters_1 = len(set(labels)) - int(-1 in labels) + assert_equal(n_clusters_1, n_clusters) + + db = DBSCAN(p=2.0, eps=eps, min_samples=min_samples, algorithm='ball_tree') + labels = db.fit(X).labels_ + + n_clusters_2 = len(set(labels)) - int(-1 in labels) + assert_equal(n_clusters_2, n_clusters) + + db = DBSCAN(p=2.0, eps=eps, min_samples=min_samples, algorithm='kd_tree') + labels = db.fit(X).labels_ + + n_clusters_3 = len(set(labels)) - int(-1 in labels) + assert_equal(n_clusters_3, n_clusters) + + db = DBSCAN(p=1.0, eps=eps, min_samples=min_samples, algorithm='ball_tree') + labels = db.fit(X).labels_ + + n_clusters_4 = len(set(labels)) - int(-1 in labels) + assert_equal(n_clusters_4, n_clusters) + + db = DBSCAN(leaf_size=20, eps=eps, min_samples=min_samples, + algorithm='ball_tree') + labels = db.fit(X).labels_ + + n_clusters_5 = len(set(labels)) - int(-1 in labels) + assert_equal(n_clusters_5, n_clusters) + + +def test_input_validation(): + """DBSCAN.fit should accept a list of lists.""" + X = [[1., 2.], [3., 4.]] + DBSCAN().fit(X) # must not raise exception + + +def test_dbscan_badargs(): + """Test bad argument values: these should all raise ValueErrors""" + assert_raises(ValueError, + dbscan, + X, eps=-1.0) + assert_raises(ValueError, + dbscan, + X, algorithm='blah') + assert_raises(ValueError, + dbscan, + X, metric='blah') + assert_raises(ValueError, + dbscan, + X, leaf_size=-1) + assert_raises(ValueError, + dbscan, + X, p=-1) + + def test_pickle(): obj = DBSCAN() s = pickle.dumps(obj) assert_equal(type(pickle.loads(s)), obj.__class__) + + +def test_boundaries(): + # ensure min_samples is inclusive of core point + core, _ = dbscan([[0], [1]], eps=2, min_samples=2) + assert_in(0, core) + # ensure eps is inclusive of circumference + core, _ = dbscan([[0], [1], [1]], eps=1, min_samples=2) + assert_in(0, core) + core, _ = dbscan([[0], [1], [1]], eps=.99, min_samples=2) + assert_not_in(0, core) + + +def test_weighted_dbscan(): + # ensure sample_weight is validated + assert_raises(ValueError, dbscan, [[0], [1]], sample_weight=[2]) + assert_raises(ValueError, dbscan, [[0], [1]], sample_weight=[2, 3, 4]) + + # ensure sample_weight has an effect + assert_array_equal([], dbscan([[0], [1]], sample_weight=None, + min_samples=6)[0]) + assert_array_equal([], dbscan([[0], [1]], sample_weight=[5, 5], + min_samples=6)[0]) + assert_array_equal([0], dbscan([[0], [1]], sample_weight=[6, 5], + min_samples=6)[0]) + assert_array_equal([0, 1], dbscan([[0], [1]], sample_weight=[6, 6], + min_samples=6)[0]) + + # points within eps of each other: + assert_array_equal([0, 1], dbscan([[0], [1]], eps=1.5, + sample_weight=[5, 1], min_samples=6)[0]) + # and effect of non-positive and non-integer sample_weight: + assert_array_equal([], dbscan([[0], [1]], sample_weight=[5, 0], + eps=1.5, min_samples=6)[0]) + assert_array_equal([0, 1], dbscan([[0], [1]], sample_weight=[5.9, 0.1], + eps=1.5, min_samples=6)[0]) + assert_array_equal([0, 1], dbscan([[0], [1]], sample_weight=[6, 0], + eps=1.5, min_samples=6)[0]) + assert_array_equal([], dbscan([[0], [1]], sample_weight=[6, -1], + eps=1.5, min_samples=6)[0]) + + # for non-negative sample_weight, cores should be identical to repetition + rng = np.random.RandomState(42) + sample_weight = rng.randint(0, 5, X.shape[0]) + core1, label1 = dbscan(X, sample_weight=sample_weight) + assert_equal(len(label1), len(X)) + + X_repeated = np.repeat(X, sample_weight, axis=0) + core_repeated, label_repeated = dbscan(X_repeated) + core_repeated_mask = np.zeros(X_repeated.shape[0], dtype=bool) + core_repeated_mask[core_repeated] = True + core_mask = np.zeros(X.shape[0], dtype=bool) + core_mask[core1] = True + assert_array_equal(np.repeat(core_mask, sample_weight), core_repeated_mask) + + # sample_weight should work with precomputed distance matrix + D = pairwise_distances(X) + core3, label3 = dbscan(D, sample_weight=sample_weight, + metric='precomputed') + assert_array_equal(core1, core3) + assert_array_equal(label1, label3) + + # sample_weight should work with estimator + est = DBSCAN().fit(X, sample_weight=sample_weight) + core4 = est.core_sample_indices_ + label4 = est.labels_ + assert_array_equal(core1, core4) + assert_array_equal(label1, label4) + + est = DBSCAN() + label5 = est.fit_predict(X, sample_weight=sample_weight) + core5 = est.core_sample_indices_ + assert_array_equal(core1, core5) + assert_array_equal(label1, label5) + assert_array_equal(label1, est.labels_) diff --git a/sklearn/cluster/tests/test_hierarchical.py b/sklearn/cluster/tests/test_hierarchical.py index 47791dfb16599..7c921377024a5 100644 --- a/sklearn/cluster/tests/test_hierarchical.py +++ b/sklearn/cluster/tests/test_hierarchical.py @@ -2,116 +2,243 @@ Several basic tests for hierarchical clustering procedures """ -# Authors: Vincent Michel, 2010, Gael Varoquaux 2012 -# License: BSD-like -import warnings - -from nose.tools import assert_true, assert_raises, assert_equal +# Authors: Vincent Michel, 2010, Gael Varoquaux 2012, +# Matteo Visconti di Oleggio Castello 2014 +# License: BSD 3 clause +from tempfile import mkdtemp +import shutil +from functools import partial import numpy as np from scipy import sparse from scipy.cluster import hierarchy +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import ignore_warnings + from sklearn.cluster import Ward, WardAgglomeration, ward_tree -from sklearn.cluster.hierarchical import _hc_cut +from sklearn.cluster import AgglomerativeClustering, FeatureAgglomeration +from sklearn.cluster.hierarchical import (_hc_cut, _TREE_BUILDERS, + linkage_tree) from sklearn.feature_extraction.image import grid_to_graph +from sklearn.metrics.pairwise import PAIRED_DISTANCES, cosine_distances,\ + manhattan_distances, pairwise_distances +from sklearn.metrics.cluster import normalized_mutual_info_score +from sklearn.neighbors.graph import kneighbors_graph +from sklearn.cluster._hierarchical import average_merge, max_merge +from sklearn.utils.fast_dict import IntFloatDict +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_warns + + +def test_linkage_misc(): + # Misc tests on linkage + rng = np.random.RandomState(42) + X = rng.normal(size=(5, 5)) + assert_raises(ValueError, AgglomerativeClustering(linkage='foo').fit, X) + assert_raises(ValueError, linkage_tree, X, linkage='foo') + assert_raises(ValueError, linkage_tree, X, connectivity=np.ones((4, 4))) + + # Smoke test FeatureAgglomeration + FeatureAgglomeration().fit(X) + + # Deprecation of Ward class + assert_warns(DeprecationWarning, Ward).fit(X) + + # test hiearchical clustering on a precomputed distances matrix + dis = cosine_distances(X) + + res = linkage_tree(dis, affinity="precomputed") + assert_array_equal(res[0], linkage_tree(X, affinity="cosine")[0]) + + # test hiearchical clustering on a precomputed distances matrix + res = linkage_tree(X, affinity=manhattan_distances) + assert_array_equal(res[0], linkage_tree(X, affinity="manhattan")[0]) -def test_structured_ward_tree(): +def test_structured_linkage_tree(): """ - Check that we obtain the correct solution for structured ward tree. + Check that we obtain the correct solution for structured linkage trees. """ - rnd = np.random.RandomState(0) + rng = np.random.RandomState(0) mask = np.ones([10, 10], dtype=np.bool) # Avoiding a mask with only 'True' entries mask[4:7, 4:7] = 0 - X = rnd.randn(50, 100) + X = rng.randn(50, 100) connectivity = grid_to_graph(*mask.shape) - children, n_components, n_leaves, parent = ward_tree(X.T, connectivity) - n_nodes = 2 * X.shape[1] - 1 - assert_true(len(children) + n_leaves == n_nodes) - # Check that ward_tree raises a ValueError with a connectivity matrix - # of the wrong shape - assert_raises(ValueError, ward_tree, X.T, np.ones((4, 4))) + for tree_builder in _TREE_BUILDERS.values(): + children, n_components, n_leaves, parent = \ + tree_builder(X.T, connectivity) + n_nodes = 2 * X.shape[1] - 1 + assert_true(len(children) + n_leaves == n_nodes) + # Check that ward_tree raises a ValueError with a connectivity matrix + # of the wrong shape + assert_raises(ValueError, + tree_builder, X.T, np.ones((4, 4))) + # Check that fitting with no samples raises an error + assert_raises(ValueError, + tree_builder, X.T[:0], connectivity) -def test_unstructured_ward_tree(): +def test_unstructured_linkage_tree(): """ - Check that we obtain the correct solution for unstructured ward tree. + Check that we obtain the correct solution for unstructured linkage trees. """ - rnd = np.random.RandomState(0) - X = rnd.randn(50, 100) + rng = np.random.RandomState(0) + X = rng.randn(50, 100) for this_X in (X, X[0]): - with warnings.catch_warnings(record=True) as warning_list: - warnings.simplefilter("always", UserWarning) - # With specified a number of clusters just for the sake of - # raising a warning and testing the warning code - children, n_nodes, n_leaves, parent = ward_tree(this_X.T, - n_clusters=10) - assert_equal(len(warning_list), 1) + # With specified a number of clusters just for the sake of + # raising a warning and testing the warning code + with ignore_warnings(): + children, n_nodes, n_leaves, parent = assert_warns( + UserWarning, ward_tree, this_X.T, n_clusters=10) n_nodes = 2 * X.shape[1] - 1 assert_equal(len(children) + n_leaves, n_nodes) + for tree_builder in _TREE_BUILDERS.values(): + for this_X in (X, X[0]): + with ignore_warnings(): + children, n_nodes, n_leaves, parent = assert_warns( + UserWarning, tree_builder, this_X.T, n_clusters=10) + + n_nodes = 2 * X.shape[1] - 1 + assert_equal(len(children) + n_leaves, n_nodes) + -def test_height_ward_tree(): +def test_height_linkage_tree(): """ - Check that the height of ward tree is sorted. + Check that the height of the results of linkage tree is sorted. """ - rnd = np.random.RandomState(0) + rng = np.random.RandomState(0) mask = np.ones([10, 10], dtype=np.bool) - X = rnd.randn(50, 100) + X = rng.randn(50, 100) connectivity = grid_to_graph(*mask.shape) - children, n_nodes, n_leaves, parent = ward_tree(X.T, connectivity) - n_nodes = 2 * X.shape[1] - 1 - assert_true(len(children) + n_leaves == n_nodes) + for linkage_func in _TREE_BUILDERS.values(): + children, n_nodes, n_leaves, parent = linkage_func(X.T, connectivity) + n_nodes = 2 * X.shape[1] - 1 + assert_true(len(children) + n_leaves == n_nodes) -def test_ward_clustering(): +def test_agglomerative_clustering(): """ - Check that we obtain the correct number of clusters with Ward clustering. + Check that we obtain the correct number of clusters with + agglomerative clustering. """ - rnd = np.random.RandomState(0) + rng = np.random.RandomState(0) mask = np.ones([10, 10], dtype=np.bool) - X = rnd.randn(100, 50) + n_samples = 100 + X = rng.randn(n_samples, 50) connectivity = grid_to_graph(*mask.shape) - clustering = Ward(n_clusters=10, connectivity=connectivity) - clustering.fit(X) - labels = clustering.labels_ - assert_true(np.size(np.unique(labels)) == 10) - # Check that we obtain the same solution with early-stopping of the - # tree building - clustering.compute_full_tree = False - clustering.fit(X) - np.testing.assert_array_equal(clustering.labels_, labels) - clustering.connectivity = None - clustering.fit(X) - assert_true(np.size(np.unique(clustering.labels_)) == 10) - # Check that we raise a TypeError on dense matrices - clustering = Ward(n_clusters=10, - connectivity=connectivity.todense()) - assert_raises(TypeError, clustering.fit, X) - clustering = Ward(n_clusters=10, - connectivity=sparse.lil_matrix( - connectivity.todense()[:10, :10])) + for linkage in ("ward", "complete", "average"): + clustering = AgglomerativeClustering(n_clusters=10, + connectivity=connectivity, + linkage=linkage) + clustering.fit(X) + # test caching + try: + tempdir = mkdtemp() + clustering = AgglomerativeClustering( + n_clusters=10, connectivity=connectivity, + memory=tempdir, + linkage=linkage) + clustering.fit(X) + labels = clustering.labels_ + assert_true(np.size(np.unique(labels)) == 10) + finally: + shutil.rmtree(tempdir) + # Turn caching off now + clustering = AgglomerativeClustering( + n_clusters=10, connectivity=connectivity, linkage=linkage) + # Check that we obtain the same solution with early-stopping of the + # tree building + clustering.compute_full_tree = False + clustering.fit(X) + assert_almost_equal(normalized_mutual_info_score(clustering.labels_, + labels), 1) + clustering.connectivity = None + clustering.fit(X) + assert_true(np.size(np.unique(clustering.labels_)) == 10) + # Check that we raise a TypeError on dense matrices + clustering = AgglomerativeClustering( + n_clusters=10, + connectivity=sparse.lil_matrix( + connectivity.toarray()[:10, :10]), + linkage=linkage) + assert_raises(ValueError, clustering.fit, X) + + # Test that using ward with another metric than euclidean raises an + # exception + clustering = AgglomerativeClustering( + n_clusters=10, + connectivity=connectivity.toarray(), + affinity="manhattan", + linkage="ward") assert_raises(ValueError, clustering.fit, X) + # Test using another metric than euclidean works with linkage complete + for affinity in PAIRED_DISTANCES.keys(): + # Compare our (structured) implementation to scipy + clustering = AgglomerativeClustering( + n_clusters=10, + connectivity=np.ones((n_samples, n_samples)), + affinity=affinity, + linkage="complete") + clustering.fit(X) + clustering2 = AgglomerativeClustering( + n_clusters=10, + connectivity=None, + affinity=affinity, + linkage="complete") + clustering2.fit(X) + assert_almost_equal(normalized_mutual_info_score(clustering2.labels_, + clustering.labels_), + 1) + + # Test that using a distance matrix (affinity = 'precomputed') has same + # results (with connectivity constraints) + clustering = AgglomerativeClustering(n_clusters=10, + connectivity=connectivity, + linkage="complete") + clustering.fit(X) + X_dist = pairwise_distances(X) + clustering2 = AgglomerativeClustering(n_clusters=10, + connectivity=connectivity, + affinity='precomputed', + linkage="complete") + clustering2.fit(X_dist) + assert_array_equal(clustering.labels_, clustering2.labels_) + def test_ward_agglomeration(): """ Check that we obtain the correct solution in a simplistic case """ - rnd = np.random.RandomState(0) + rng = np.random.RandomState(0) mask = np.ones([10, 10], dtype=np.bool) - X = rnd.randn(50, 100) + X = rng.randn(50, 100) connectivity = grid_to_graph(*mask.shape) - ward = WardAgglomeration(n_clusters=5, connectivity=connectivity) - ward.fit(X) - assert_true(np.size(np.unique(ward.labels_)) == 5) + assert_warns(DeprecationWarning, WardAgglomeration) + + with ignore_warnings(): + ward = WardAgglomeration(n_clusters=5, connectivity=connectivity) + ward.fit(X) + agglo = FeatureAgglomeration(n_clusters=5, connectivity=connectivity) + agglo.fit(X) + assert_array_equal(agglo.labels_, ward.labels_) + assert_true(np.size(np.unique(agglo.labels_)) == 5) + + X_red = agglo.transform(X) + assert_true(X_red.shape[1] == 5) + X_full = agglo.inverse_transform(X_red) + assert_true(np.unique(X_full[0]).size == 5) + assert_array_almost_equal(agglo.transform(X_full), X_red) - Xred = ward.transform(X) - assert_true(Xred.shape[1] == 5) - Xfull = ward.inverse_transform(Xred) - assert_true(np.unique(Xfull[0]).size == 5) + # Check that fitting with no samples raises a ValueError + assert_raises(ValueError, agglo.fit, X[:0]) def assess_same_labelling(cut1, cut2): @@ -127,52 +254,181 @@ def assess_same_labelling(cut1, cut2): def test_scikit_vs_scipy(): - """Test scikit ward with full connectivity (i.e. unstructured) vs scipy + """Test scikit linkage with full connectivity (i.e. unstructured) vs scipy """ - from scipy.sparse import lil_matrix n, p, k = 10, 5, 3 - rnd = np.random.RandomState(0) + rng = np.random.RandomState(0) - connectivity = lil_matrix(np.ones((n, n))) - for i in range(5): - X = .1 * rnd.normal(size=(n, p)) - X -= 4 * np.arange(n)[:, np.newaxis] - X -= X.mean(axis=1)[:, np.newaxis] + # Not using a lil_matrix here, just to check that non sparse + # matrices are well handled + connectivity = np.ones((n, n)) + for linkage in _TREE_BUILDERS.keys(): + for i in range(5): + X = .1 * rng.normal(size=(n, p)) + X -= 4. * np.arange(n)[:, np.newaxis] + X -= X.mean(axis=1)[:, np.newaxis] - out = hierarchy.ward(X) + out = hierarchy.linkage(X, method=linkage) - children_ = out[:, :2].astype(np.int) - children, _, n_leaves, _ = ward_tree(X, connectivity) + children_ = out[:, :2].astype(np.int) + children, _, n_leaves, _ = _TREE_BUILDERS[linkage](X, connectivity) - cut = _hc_cut(k, children, n_leaves) - cut_ = _hc_cut(k, children_, n_leaves) - assess_same_labelling(cut, cut_) + cut = _hc_cut(k, children, n_leaves) + cut_ = _hc_cut(k, children_, n_leaves) + assess_same_labelling(cut, cut_) # Test error management in _hc_cut assert_raises(ValueError, _hc_cut, n_leaves + 1, children, n_leaves) -def test_connectivity_popagation(): +def test_connectivity_propagation(): """ Check that connectivity in the ward tree is propagated correctly during merging. """ - from sklearn.neighbors import NearestNeighbors - X = np.array([(.014, .120), (.014, .099), (.014, .097), (.017, .153), (.017, .153), (.018, .153), (.018, .153), (.018, .153), (.018, .153), (.018, .153), (.018, .153), (.018, .153), (.018, .152), (.018, .149), (.018, .144), ]) - nn = NearestNeighbors(n_neighbors=10, warn_on_equidistant=False).fit(X) - connectivity = nn.kneighbors_graph(X) - ward = Ward(n_clusters=4, connectivity=connectivity) + connectivity = kneighbors_graph(X, 10) + ward = AgglomerativeClustering( + n_clusters=4, connectivity=connectivity, linkage='ward') # If changes are not propagated correctly, fit crashes with an # IndexError ward.fit(X) +def test_ward_tree_children_order(): + """ + Check that children are ordered in the same way for both structured and + unstructured versions of ward_tree. + """ + + # test on five random datasets + n, p = 10, 5 + rng = np.random.RandomState(0) + + connectivity = np.ones((n, n)) + for i in range(5): + X = .1 * rng.normal(size=(n, p)) + X -= 4. * np.arange(n)[:, np.newaxis] + X -= X.mean(axis=1)[:, np.newaxis] + + out_unstructured = ward_tree(X) + out_structured = ward_tree(X, connectivity=connectivity) + + assert_array_equal(out_unstructured[0], out_structured[0]) + + +def test_ward_linkage_tree_return_distance(): + """Test return_distance option on linkage and ward trees""" + + # test that return_distance when set true, gives same + # output on both structured and unstructured clustering. + n, p = 10, 5 + rng = np.random.RandomState(0) + + connectivity = np.ones((n, n)) + for i in range(5): + X = .1 * rng.normal(size=(n, p)) + X -= 4. * np.arange(n)[:, np.newaxis] + X -= X.mean(axis=1)[:, np.newaxis] + + out_unstructured = ward_tree(X, return_distance=True) + out_structured = ward_tree(X, connectivity=connectivity, + return_distance=True) + + # get children + children_unstructured = out_unstructured[0] + children_structured = out_structured[0] + + # check if we got the same clusters + assert_array_equal(children_unstructured, children_structured) + + # check if the distances are the same + dist_unstructured = out_unstructured[-1] + dist_structured = out_structured[-1] + + assert_array_almost_equal(dist_unstructured, dist_structured) + + for linkage in ['average', 'complete']: + structured_items = linkage_tree( + X, connectivity=connectivity, linkage=linkage, + return_distance=True)[-1] + unstructured_items = linkage_tree( + X, linkage=linkage, return_distance=True)[-1] + structured_dist = structured_items[-1] + unstructured_dist = unstructured_items[-1] + structured_children = structured_items[0] + unstructured_children = unstructured_items[0] + assert_array_almost_equal(structured_dist, unstructured_dist) + assert_array_almost_equal( + structured_children, unstructured_children) + + # test on the following dataset where we know the truth + # taken from scipy/cluster/tests/hierarchy_test_data.py + X = np.array([[1.43054825, -7.5693489], + [6.95887839, 6.82293382], + [2.87137846, -9.68248579], + [7.87974764, -6.05485803], + [8.24018364, -6.09495602], + [7.39020262, 8.54004355]]) + # truth + linkage_X_ward = np.array([[3., 4., 0.36265956, 2.], + [1., 5., 1.77045373, 2.], + [0., 2., 2.55760419, 2.], + [6., 8., 9.10208346, 4.], + [7., 9., 24.7784379, 6.]]) + + linkage_X_complete = np.array( + [[3., 4., 0.36265956, 2.], + [1., 5., 1.77045373, 2.], + [0., 2., 2.55760419, 2.], + [6., 8., 6.96742194, 4.], + [7., 9., 18.77445997, 6.]]) + + linkage_X_average = np.array( + [[3., 4., 0.36265956, 2.], + [1., 5., 1.77045373, 2.], + [0., 2., 2.55760419, 2.], + [6., 8., 6.55832839, 4.], + [7., 9., 15.44089605, 6.]]) + + n_samples, n_features = np.shape(X) + connectivity_X = np.ones((n_samples, n_samples)) + + out_X_unstructured = ward_tree(X, return_distance=True) + out_X_structured = ward_tree(X, connectivity=connectivity_X, + return_distance=True) + + # check that the labels are the same + assert_array_equal(linkage_X_ward[:, :2], out_X_unstructured[0]) + assert_array_equal(linkage_X_ward[:, :2], out_X_structured[0]) + + # check that the distances are correct + assert_array_almost_equal(linkage_X_ward[:, 2], out_X_unstructured[4]) + assert_array_almost_equal(linkage_X_ward[:, 2], out_X_structured[4]) + + linkage_options = ['complete', 'average'] + X_linkage_truth = [linkage_X_complete, linkage_X_average] + for (linkage, X_truth) in zip(linkage_options, X_linkage_truth): + out_X_unstructured = linkage_tree( + X, return_distance=True, linkage=linkage) + out_X_structured = linkage_tree( + X, connectivity=connectivity_X, linkage=linkage, + return_distance=True) + + # check that the labels are the same + assert_array_equal(X_truth[:, :2], out_X_unstructured[0]) + assert_array_equal(X_truth[:, :2], out_X_structured[0]) + + # check that the distances are correct + assert_array_almost_equal(X_truth[:, 2], out_X_unstructured[4]) + assert_array_almost_equal(X_truth[:, 2], out_X_structured[4]) + + def test_connectivity_fixing_non_lil(): """ Check non regression of a bug if a non item assignable connectivity is @@ -183,9 +439,76 @@ def test_connectivity_fixing_non_lil(): # create a mask with several components to force connectivity fixing m = np.array([[True, False], [False, True]]) c = grid_to_graph(n_x=2, n_y=2, mask=m) - w = Ward(connectivity=c) - with warnings.catch_warnings(record=True): - w.fit(x) + w = AgglomerativeClustering(connectivity=c, linkage='ward') + assert_warns(UserWarning, w.fit, x) + + +def test_int_float_dict(): + rng = np.random.RandomState(0) + keys = np.unique(rng.randint(100, size=10).astype(np.intp)) + values = rng.rand(len(keys)) + + d = IntFloatDict(keys, values) + for key, value in zip(keys, values): + assert d[key] == value + + other_keys = np.arange(50).astype(np.intp)[::2] + other_values = 0.5 * np.ones(50)[::2] + other = IntFloatDict(other_keys, other_values) + # Complete smoke test + max_merge(d, other, mask=np.ones(100, dtype=np.intp), n_a=1, n_b=1) + average_merge(d, other, mask=np.ones(100, dtype=np.intp), n_a=1, n_b=1) + + +def test_connectivity_callable(): + rng = np.random.RandomState(0) + X = rng.rand(20, 5) + connectivity = kneighbors_graph(X, 3) + aglc1 = AgglomerativeClustering(connectivity=connectivity) + aglc2 = AgglomerativeClustering( + connectivity=partial(kneighbors_graph, n_neighbors=3)) + aglc1.fit(X) + aglc2.fit(X) + assert_array_equal(aglc1.labels_, aglc2.labels_) + + +def test_compute_full_tree(): + """Test that the full tree is computed if n_clusters is small""" + rng = np.random.RandomState(0) + X = rng.randn(10, 2) + connectivity = kneighbors_graph(X, 5) + + # When n_clusters is less, the full tree should be built + # that is the number of merges should be n_samples - 1 + agc = AgglomerativeClustering(n_clusters=2, connectivity=connectivity) + agc.fit(X) + n_samples = X.shape[0] + n_nodes = agc.children_.shape[0] + assert_equal(n_nodes, n_samples - 1) + + # When n_clusters is large, greater than max of 100 and 0.02 * n_samples. + # we should stop when there are n_clusters. + n_clusters = 101 + X = rng.randn(200, 2) + connectivity = kneighbors_graph(X, 10) + agc = AgglomerativeClustering(n_clusters=n_clusters, + connectivity=connectivity) + agc.fit(X) + n_samples = X.shape[0] + n_nodes = agc.children_.shape[0] + assert_equal(n_nodes, n_samples - n_clusters) + + +def test_n_components(): + """Test n_components returned by linkage, average and ward tree""" + rng = np.random.RandomState(0) + X = rng.rand(5, 5) + + # Connectivity matrix having five components. + connectivity = np.eye(5) + + for linkage_func in _TREE_BUILDERS.values(): + assert_equal(ignore_warnings(linkage_func)(X, connectivity)[1], 5) if __name__ == '__main__': diff --git a/sklearn/cluster/tests/test_k_means.py b/sklearn/cluster/tests/test_k_means.py index 2e18b01b27049..75015bd678e1f 100644 --- a/sklearn/cluster/tests/test_k_means.py +++ b/sklearn/cluster/tests/test_k_means.py @@ -1,26 +1,30 @@ """Testing for K-means""" +import sys import numpy as np -import warnings from scipy import sparse as sp -from numpy.testing import assert_equal -from numpy.testing import assert_array_equal -from numpy.testing import assert_array_almost_equal -from nose import SkipTest -from nose.tools import assert_almost_equal -from nose.tools import assert_raises -from nose.tools import assert_true +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import SkipTest +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_raises_regexp +from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_less -from sklearn.utils.fixes import unique +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import if_not_mac_os + +from sklearn.utils.extmath import row_norms from sklearn.metrics.cluster import v_measure_score -from sklearn.cluster import KMeans +from sklearn.cluster import KMeans, k_means from sklearn.cluster import MiniBatchKMeans from sklearn.cluster.k_means_ import _labels_inertia from sklearn.cluster.k_means_ import _mini_batch_step -from sklearn.cluster._k_means import csr_row_norm_l2 from sklearn.datasets.samples_generator import make_blobs +from sklearn.externals.six.moves import cStringIO as StringIO # non centered, sparse centers to check the @@ -36,24 +40,16 @@ X_csr = sp.csr_matrix(X) -def test_square_norms(): - x_squared_norms = (X ** 2).sum(axis=1) - x_squared_norms_from_csr = csr_row_norm_l2(X_csr) - assert_array_almost_equal(x_squared_norms, - x_squared_norms_from_csr, 5) - - def test_kmeans_dtype(): rnd = np.random.RandomState(0) X = rnd.normal(size=(40, 2)) X = (X * 10).astype(np.uint8) km = KMeans(n_init=1).fit(X) - with warnings.catch_warnings(record=True) as w: - assert_array_equal(km.labels_, km.predict(X)) - assert_equal(len(w), 1) + pred_x = assert_warns(RuntimeWarning, km.predict, X) + assert_array_equal(km.labels_, pred_x) -def test_labels_assignement_and_inertia(): +def test_labels_assignment_and_inertia(): # pure numpy implementation as easily auditable reference gold # implementation rng = np.random.RandomState(42) @@ -69,15 +65,15 @@ def test_labels_assignement_and_inertia(): assert_true((mindist >= 0.0).all()) assert_true((labels_gold != -1).all()) - # perform label assignement using the dense array input + # perform label assignment using the dense array input x_squared_norms = (X ** 2).sum(axis=1) labels_array, inertia_array = _labels_inertia( X, x_squared_norms, noisy_centers) assert_array_almost_equal(inertia_array, inertia_gold) assert_array_equal(labels_array, labels_gold) - # perform label assignement using the sparse CSR input - x_squared_norms_from_csr = csr_row_norm_l2(X_csr) + # perform label assignment using the sparse CSR input + x_squared_norms_from_csr = row_norms(X_csr, squared=True) labels_csr, inertia_csr = _labels_inertia( X_csr, x_squared_norms_from_csr, noisy_centers) assert_array_almost_equal(inertia_csr, inertia_gold) @@ -96,7 +92,7 @@ def test_minibatch_update_consistency(): counts_csr = np.zeros(new_centers.shape[0], dtype=np.int32) x_squared_norms = (X ** 2).sum(axis=1) - x_squared_norms_csr = csr_row_norm_l2(X_csr, squared=True) + x_squared_norms_csr = row_norms(X_csr, squared=True) buffer = np.zeros(centers.shape[1], dtype=np.double) buffer_csr = np.zeros(centers.shape[1], dtype=np.double) @@ -110,7 +106,7 @@ def test_minibatch_update_consistency(): # step 1: compute the dense minibatch update old_inertia, incremental_diff = _mini_batch_step( X_mb, x_mb_squared_norms, new_centers, counts, - buffer, 1) + buffer, 1, None, random_reassign=False) assert_greater(old_inertia, 0.0) # compute the new inertia on the same batch to check that it decreased @@ -127,7 +123,7 @@ def test_minibatch_update_consistency(): # step 2: compute the sparse minibatch update old_inertia_csr, incremental_diff_csr = _mini_batch_step( X_mb_csr, x_mb_squared_norms_csr, new_centers_csr, counts_csr, - buffer_csr, 1) + buffer_csr, 1, None, random_reassign=False) assert_greater(old_inertia_csr, 0.0) # compute the new inertia on the same batch to check that it decreased @@ -158,7 +154,7 @@ def _check_fitted_model(km): labels = km.labels_ assert_equal(np.unique(labels).shape[0], n_clusters) - # check that the labels assignements are perfect (up to a permutation) + # check that the labels assignment are perfect (up to a permutation) assert_equal(v_measure_score(true_labels, labels), 1.0) assert_greater(km.inertia_, 0.0) @@ -167,9 +163,9 @@ def _check_fitted_model(km): def test_k_means_plus_plus_init(): - k_means = KMeans(init="k-means++", n_clusters=n_clusters, - random_state=42).fit(X) - _check_fitted_model(k_means) + km = KMeans(init="k-means++", n_clusters=n_clusters, + random_state=42).fit(X) + _check_fitted_model(km) def test_k_means_new_centers(): @@ -181,9 +177,9 @@ def test_k_means_new_centers(): [0, 0, 0, 0], [0, 1, 0, 0]]) labels = [0, 1, 2, 1, 1, 2] - bad_centers = np.array([[+0, 1, 0, 0], - [.2, 0, .2, .2], - [+0, 0, 0, 0]]) + bad_centers = np.array([[+0, 1, 0, 0], + [.2, 0, .2, .2], + [+0, 0, 0, 0]]) km = KMeans(n_clusters=3, init=bad_centers, n_init=1, max_iter=10, random_state=1) @@ -192,62 +188,77 @@ def test_k_means_new_centers(): this_labels = km.labels_ # Reorder the labels so that the first instance is in cluster 0, # the second in cluster 1, ... - this_labels = unique(this_labels, - return_index=True)[1][this_labels] + this_labels = np.unique(this_labels, return_index=True)[1][this_labels] np.testing.assert_array_equal(this_labels, labels) -def _get_mac_os_version(): - import platform - mac_version, _, _ = platform.mac_ver() - if mac_version: - # turn something like '10.7.3' into '10.7' - return '.'.join(mac_version.split('.')[:2]) +def _has_blas_lib(libname): + from numpy.distutils.system_info import get_info + return libname in get_info('blas_opt').get('libraries', []) +@if_not_mac_os() def test_k_means_plus_plus_init_2_jobs(): - if _get_mac_os_version() == '10.7': - raise SkipTest('Multi-process bug in Mac OS X Lion (see issue #636)') - k_means = KMeans(init="k-means++", n_clusters=n_clusters, n_jobs=2, - random_state=42).fit(X) - _check_fitted_model(k_means) + if _has_blas_lib('openblas'): + raise SkipTest('Multi-process bug with OpenBLAS (see issue #636)') + + km = KMeans(init="k-means++", n_clusters=n_clusters, n_jobs=2, + random_state=42).fit(X) + _check_fitted_model(km) + + +def test_k_means_precompute_distances_flag(): + # check that a warning is raised if the precompute_distances flag is not + # supported + km = KMeans(precompute_distances="wrong") + assert_raises(ValueError, km.fit, X) def test_k_means_plus_plus_init_sparse(): - k_means = KMeans(init="k-means++", n_clusters=n_clusters, random_state=42) - k_means.fit(X_csr) - _check_fitted_model(k_means) + km = KMeans(init="k-means++", n_clusters=n_clusters, random_state=42) + km.fit(X_csr) + _check_fitted_model(km) def test_k_means_random_init(): - k_means = KMeans(init="random", n_clusters=n_clusters, random_state=42) - k_means.fit(X) - _check_fitted_model(k_means) + km = KMeans(init="random", n_clusters=n_clusters, random_state=42) + km.fit(X) + _check_fitted_model(km) def test_k_means_random_init_sparse(): - k_means = KMeans(init="random", n_clusters=n_clusters, random_state=42) - k_means.fit(X_csr) - _check_fitted_model(k_means) + km = KMeans(init="random", n_clusters=n_clusters, random_state=42) + km.fit(X_csr) + _check_fitted_model(km) def test_k_means_plus_plus_init_not_precomputed(): - k_means = KMeans(init="k-means++", n_clusters=n_clusters, random_state=42, - precompute_distances=False).fit(X) - _check_fitted_model(k_means) + km = KMeans(init="k-means++", n_clusters=n_clusters, random_state=42, + precompute_distances=False).fit(X) + _check_fitted_model(km) def test_k_means_random_init_not_precomputed(): - k_means = KMeans(init="random", n_clusters=n_clusters, random_state=42, - precompute_distances=False).fit(X) - _check_fitted_model(k_means) + km = KMeans(init="random", n_clusters=n_clusters, random_state=42, + precompute_distances=False).fit(X) + _check_fitted_model(km) def test_k_means_perfect_init(): - k_means = KMeans(init=centers.copy(), n_clusters=n_clusters, - random_state=42, n_init=1) - k_means.fit(X) - _check_fitted_model(k_means) + km = KMeans(init=centers.copy(), n_clusters=n_clusters, random_state=42, + n_init=1) + km.fit(X) + _check_fitted_model(km) + + +def test_k_means_n_init(): + rnd = np.random.RandomState(0) + X = rnd.normal(size=(40, 2)) + + # two regression tests on bad n_init argument + # previous bug: n_init <= 0 threw non-informative TypeError (#3858) + assert_raises_regexp(ValueError, "n_init", KMeans(n_init=0).fit, X) + assert_raises_regexp(ValueError, "n_init", KMeans(n_init=-1).fit, X) def test_mb_k_means_plus_plus_init_dense_array(): @@ -257,6 +268,17 @@ def test_mb_k_means_plus_plus_init_dense_array(): _check_fitted_model(mb_k_means) +def test_mb_kmeans_verbose(): + mb_k_means = MiniBatchKMeans(init="k-means++", n_clusters=n_clusters, + random_state=42, verbose=1) + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + mb_k_means.fit(X) + finally: + sys.stdout = old_stdout + + def test_mb_k_means_plus_plus_init_sparse_matrix(): mb_k_means = MiniBatchKMeans(init="k-means++", n_clusters=n_clusters, random_state=42) @@ -268,10 +290,7 @@ def test_minibatch_init_with_large_k(): mb_k_means = MiniBatchKMeans(init='k-means++', init_size=10, n_clusters=20) # Check that a warning is raised, as the number clusters is larger # than the init_size - with warnings.catch_warnings(record=True) as warn_queue: - mb_k_means.fit(X) - - assert_equal(len(warn_queue), 1) + assert_warns(RuntimeWarning, mb_k_means.fit, X) def test_minibatch_k_means_random_init_dense_array(): @@ -290,22 +309,128 @@ def test_minibatch_k_means_random_init_sparse_csr(): def test_minibatch_k_means_perfect_init_dense_array(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, - random_state=42).fit(X) + random_state=42, n_init=1).fit(X) _check_fitted_model(mb_k_means) +def test_minibatch_k_means_init_multiple_runs_with_explicit_centers(): + mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, + random_state=42, n_init=10) + assert_warns(RuntimeWarning, mb_k_means.fit, X) + + def test_minibatch_k_means_perfect_init_sparse_csr(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, - random_state=42).fit(X_csr) + random_state=42, n_init=1).fit(X_csr) _check_fitted_model(mb_k_means) +def test_minibatch_sensible_reassign_fit(): + # check if identical initial clusters are reassigned + # also a regression test for when there are more desired reassignments than + # samples. + zeroed_X, true_labels = make_blobs(n_samples=100, centers=5, + cluster_std=1., random_state=42) + zeroed_X[::2, :] = 0 + mb_k_means = MiniBatchKMeans(n_clusters=20, batch_size=10, random_state=42, + init="random") + mb_k_means.fit(zeroed_X) + # there should not be too many exact zero cluster centers + assert_greater(mb_k_means.cluster_centers_.any(axis=1).sum(), 10) + + # do the same with batch-size > X.shape[0] (regression test) + mb_k_means = MiniBatchKMeans(n_clusters=20, batch_size=201, + random_state=42, init="random") + mb_k_means.fit(zeroed_X) + # there should not be too many exact zero cluster centers + assert_greater(mb_k_means.cluster_centers_.any(axis=1).sum(), 10) + + +def test_minibatch_sensible_reassign_partial_fit(): + zeroed_X, true_labels = make_blobs(n_samples=n_samples, centers=5, + cluster_std=1., random_state=42) + zeroed_X[::2, :] = 0 + mb_k_means = MiniBatchKMeans(n_clusters=20, random_state=42, init="random") + for i in range(100): + mb_k_means.partial_fit(zeroed_X) + # there should not be too many exact zero cluster centers + assert_greater(mb_k_means.cluster_centers_.any(axis=1).sum(), 10) + + +def test_minibatch_reassign(): + # Give a perfect initialization, but a large reassignment_ratio, + # as a result all the centers should be reassigned and the model + # should not longer be good + for this_X in (X, X_csr): + mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, batch_size=100, + random_state=42) + mb_k_means.fit(this_X) + + score_before = mb_k_means.score(this_X) + try: + old_stdout = sys.stdout + sys.stdout = StringIO() + # Turn on verbosity to smoke test the display code + _mini_batch_step(this_X, (X ** 2).sum(axis=1), + mb_k_means.cluster_centers_, + mb_k_means.counts_, + np.zeros(X.shape[1], np.double), + False, distances=np.zeros(X.shape[0]), + random_reassign=True, random_state=42, + reassignment_ratio=1, verbose=True) + finally: + sys.stdout = old_stdout + assert_greater(score_before, mb_k_means.score(this_X)) + + # Give a perfect initialization, with a small reassignment_ratio, + # no center should be reassigned + for this_X in (X, X_csr): + mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, batch_size=100, + init=centers.copy(), + random_state=42, n_init=1) + mb_k_means.fit(this_X) + clusters_before = mb_k_means.cluster_centers_ + # Turn on verbosity to smoke test the display code + _mini_batch_step(this_X, (X ** 2).sum(axis=1), + mb_k_means.cluster_centers_, + mb_k_means.counts_, + np.zeros(X.shape[1], np.double), + False, distances=np.zeros(X.shape[0]), + random_reassign=True, random_state=42, + reassignment_ratio=1e-15) + assert_array_almost_equal(clusters_before, mb_k_means.cluster_centers_) + + +def test_minibatch_with_many_reassignments(): + # Test for the case that the number of clusters to reassign is bigger + # than the batch_size + n_samples = 550 + rnd = np.random.RandomState(42) + X = rnd.uniform(size=(n_samples, 10)) + # Check that the fit works if n_clusters is bigger than the batch_size. + # Run the test with 550 clusters and 550 samples, because it turned out + # that this values ensure that the number of clusters to reassign + # is always bigger than the batch_size + n_clusters = 550 + MiniBatchKMeans(n_clusters=n_clusters, + batch_size=100, + init_size=n_samples, + random_state=42).fit(X) + + def test_sparse_mb_k_means_callable_init(): def test_init(X, k, random_state): return centers - mb_k_means = MiniBatchKMeans(init=test_init, random_state=42).fit(X_csr) + # Small test to check that giving the wrong number of centers + # raises a meaningful error + assert_raises(ValueError, + MiniBatchKMeans(init=test_init, random_state=42).fit, X_csr) + + # Now check that the fit actually works + mb_k_means = MiniBatchKMeans(n_clusters=3, init=test_init, + random_state=42).fit(X_csr) _check_fitted_model(mb_k_means) @@ -323,35 +448,43 @@ def test_mini_batch_k_means_random_init_partial_fit(): def test_minibatch_default_init_size(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, - batch_size=10, random_state=42).fit(X) + batch_size=10, random_state=42, + n_init=1).fit(X) assert_equal(mb_k_means.init_size_, 3 * mb_k_means.batch_size) _check_fitted_model(mb_k_means) +def test_minibatch_tol(): + mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, batch_size=10, + random_state=42, tol=.01).fit(X) + _check_fitted_model(mb_k_means) + + def test_minibatch_set_init_size(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, - init_size=666, random_state=42).fit(X) + init_size=666, random_state=42, + n_init=1).fit(X) assert_equal(mb_k_means.init_size, 666) assert_equal(mb_k_means.init_size_, n_samples) _check_fitted_model(mb_k_means) def test_k_means_invalid_init(): - k_means = KMeans(init="invalid", n_init=1, n_clusters=n_clusters) - assert_raises(ValueError, k_means.fit, X) + km = KMeans(init="invalid", n_init=1, n_clusters=n_clusters) + assert_raises(ValueError, km.fit, X) def test_mini_match_k_means_invalid_init(): - k_means = MiniBatchKMeans(init="invalid", n_init=1, n_clusters=n_clusters) - assert_raises(ValueError, k_means.fit, X) + km = MiniBatchKMeans(init="invalid", n_init=1, n_clusters=n_clusters) + assert_raises(ValueError, km.fit, X) def test_k_means_copyx(): """Check if copy_x=False returns nearly equal X after de-centering.""" my_X = X.copy() - k_means = KMeans(copy_x=False, n_clusters=n_clusters, random_state=42) - k_means.fit(my_X) - _check_fitted_model(k_means) + km = KMeans(copy_x=False, n_clusters=n_clusters, random_state=42) + km.fit(my_X) + _check_fitted_model(km) # check if my_X is centered assert_array_almost_equal(my_X, X) @@ -367,34 +500,34 @@ def test_k_means_non_collapsed(): """ my_X = np.array([[1.1, 1.1], [0.9, 1.1], [1.1, 0.9], [0.9, 1.1]]) array_init = np.array([[1.0, 1.0], [5.0, 5.0], [-5.0, -5.0]]) - k_means = KMeans(init=array_init, n_clusters=3, random_state=42, n_init=1) - k_means.fit(my_X) + km = KMeans(init=array_init, n_clusters=3, random_state=42, n_init=1) + km.fit(my_X) # centers must not been collapsed - assert_equal(len(np.unique(k_means.labels_)), 3) + assert_equal(len(np.unique(km.labels_)), 3) - centers = k_means.cluster_centers_ + centers = km.cluster_centers_ assert_true(np.linalg.norm(centers[0] - centers[1]) >= 0.1) assert_true(np.linalg.norm(centers[0] - centers[2]) >= 0.1) assert_true(np.linalg.norm(centers[1] - centers[2]) >= 0.1) def test_predict(): - k_means = KMeans(n_clusters=n_clusters, random_state=42) + km = KMeans(n_clusters=n_clusters, random_state=42) - k_means.fit(X) + km.fit(X) # sanity check: predict centroid labels - pred = k_means.predict(k_means.cluster_centers_) + pred = km.predict(km.cluster_centers_) assert_array_equal(pred, np.arange(n_clusters)) # sanity check: re-predict labeling for training set samples - pred = k_means.predict(X) - assert_array_equal(pred, k_means.labels_) + pred = km.predict(X) + assert_array_equal(pred, km.labels_) # re-predict labels for training set using fit_predict - pred = k_means.fit_predict(X) - assert_array_equal(pred, k_means.labels_) + pred = km.fit_predict(X) + assert_array_equal(pred, km.labels_) def test_score(): @@ -465,10 +598,12 @@ def test_input_dtypes(): MiniBatchKMeans(n_clusters=2, n_init=10, batch_size=2).fit(X_list), MiniBatchKMeans(n_clusters=2, n_init=10, batch_size=2).fit(X_int), MiniBatchKMeans(n_clusters=2, n_init=10, batch_size=2).fit(X_int_csr), - MiniBatchKMeans(n_clusters=2, batch_size=2, init=init_int).fit(X_list), - MiniBatchKMeans(n_clusters=2, batch_size=2, init=init_int).fit(X_int), MiniBatchKMeans(n_clusters=2, batch_size=2, - init=init_int).fit(X_int_csr), + init=init_int, n_init=1).fit(X_list), + MiniBatchKMeans(n_clusters=2, batch_size=2, + init=init_int, n_init=1).fit(X_int), + MiniBatchKMeans(n_clusters=2, batch_size=2, + init=init_int, n_init=1).fit(X_int_csr), ] expected_labels = [0, 1, 1, 0, 0, 1] scores = np.array([v_measure_score(expected_labels, km.labels_) @@ -477,9 +612,9 @@ def test_input_dtypes(): def test_transform(): - k_means = KMeans(n_clusters=n_clusters) - k_means.fit(X) - X_new = k_means.transform(k_means.cluster_centers_) + km = KMeans(n_clusters=n_clusters) + km.fit(X) + X_new = km.transform(km.cluster_centers_) for c in range(n_clusters): assert_equal(X_new[c, c], 0) @@ -488,6 +623,12 @@ def test_transform(): assert_greater(X_new[c, c2], 0) +def test_fit_transform(): + X1 = KMeans(n_clusters=3, random_state=51).fit(X).transform(X) + X2 = KMeans(n_clusters=3, random_state=51).fit_transform(X) + assert_array_equal(X1, X2) + + def test_n_init(): """Check that increasing the number of init increases the quality""" n_runs = 5 @@ -504,3 +645,31 @@ def test_n_init(): " when n_init is increasing.") % list(inertia) for i in range(len(n_init_range) - 1): assert_true(inertia[i] >= inertia[i + 1], failure_msg) + + +def test_k_means_function(): + # test calling the k_means function directly + # catch output + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + cluster_centers, labels, inertia = k_means(X, n_clusters=n_clusters, + verbose=True) + finally: + sys.stdout = old_stdout + centers = cluster_centers + assert_equal(centers.shape, (n_clusters, n_features)) + + labels = labels + assert_equal(np.unique(labels).shape[0], n_clusters) + + # check that the labels assignment are perfect (up to a permutation) + assert_equal(v_measure_score(true_labels, labels), 1.0) + assert_greater(inertia, 0.0) + + # check warning when centers are passed + assert_warns(RuntimeWarning, k_means, X, n_clusters=n_clusters, + init=centers) + + # to many clusters desired + assert_raises(ValueError, k_means, X, n_clusters=X.shape[0] + 1) diff --git a/sklearn/cluster/tests/test_mean_shift.py b/sklearn/cluster/tests/test_mean_shift.py index 397c23fba89c0..736952d0f181a 100644 --- a/sklearn/cluster/tests/test_mean_shift.py +++ b/sklearn/cluster/tests/test_mean_shift.py @@ -4,29 +4,38 @@ """ import numpy as np -from numpy.testing import assert_equal -from nose.tools import assert_true +import warnings -from .. import MeanShift, mean_shift, estimate_bandwidth, get_bin_seeds -from ...datasets.samples_generator import make_blobs +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_raise_message + +from sklearn.cluster import MeanShift +from sklearn.cluster import mean_shift +from sklearn.cluster import estimate_bandwidth +from sklearn.cluster import get_bin_seeds +from sklearn.datasets.samples_generator import make_blobs n_clusters = 3 centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10 -X, _ = make_blobs(n_samples=500, n_features=2, centers=centers, - cluster_std=0.4, shuffle=True, random_state=0) +X, _ = make_blobs(n_samples=300, n_features=2, centers=centers, + cluster_std=0.4, shuffle=True, random_state=11) + + +def test_estimate_bandwidth(): + """Test estimate_bandwidth""" + bandwidth = estimate_bandwidth(X, n_samples=200) + assert_true(0.9 <= bandwidth <= 1.5) def test_mean_shift(): - """ Test MeanShift algorithm - """ + """ Test MeanShift algorithm """ bandwidth = 1.2 - bandwidth_ = estimate_bandwidth(X, n_samples=300) - assert_true(0.9 <= bandwidth_ <= 1.5) - ms = MeanShift(bandwidth=bandwidth) labels = ms.fit(X).labels_ - cluster_centers = ms.cluster_centers_ labels_unique = np.unique(labels) n_clusters_ = len(labels_unique) assert_equal(n_clusters_, n_clusters) @@ -37,13 +46,35 @@ def test_mean_shift(): assert_equal(n_clusters_, n_clusters) +def test_meanshift_predict(): + """Test MeanShift.predict""" + ms = MeanShift(bandwidth=1.2) + labels = ms.fit_predict(X) + labels2 = ms.predict(X) + assert_array_equal(labels, labels2) + + +def test_meanshift_all_orphans(): + # init away from the data, crash with a sensible warning + ms = MeanShift(bandwidth=0.1, seeds=[[-9, -9], [-10, -10]]) + msg = "No point was within bandwidth=0.1" + assert_raise_message(ValueError, msg, ms.fit, X,) + + +def test_unfitted(): + """Non-regression: before fit, there should be not fitted attributes.""" + ms = MeanShift() + assert_false(hasattr(ms, "cluster_centers_")) + assert_false(hasattr(ms, "labels_")) + + def test_bin_seeds(): """ Test the bin seeding technique which can be used in the mean shift algorithm """ # Data is just 6 points in the plane - X = np.array([[1., 1.], [1.5, 1.5], [1.8, 1.2], + X = np.array([[1., 1.], [1.4, 1.4], [1.8, 1.2], [2., 1.], [2.1, 1.1], [0., 0.]]) # With a bin coarseness of 1.0 and min_bin_freq of 1, 3 bins should be @@ -61,6 +92,13 @@ def test_bin_seeds(): assert_true(len(ground_truth.symmetric_difference(test_result)) == 0) # With a bin size of 0.01 and min_bin_freq of 1, 6 bins should be found - test_bins = get_bin_seeds(X, 0.01, 1) - test_result = set([tuple(p) for p in test_bins]) - assert_true(len(test_result) == 6) + # we bail and use the whole data here. + with warnings.catch_warnings(record=True): + test_bins = get_bin_seeds(X, 0.01, 1) + assert_array_equal(test_bins, X) + + # tight clusters around [0, 0] and [1, 1], only get two bins + X, _ = make_blobs(n_samples=100, n_features=2, centers=[[0, 0], [1, 1]], + cluster_std=0.1, random_state=0) + test_bins = get_bin_seeds(X, 1) + assert_array_equal(test_bins, [[0, 0], [1, 1]]) diff --git a/sklearn/cluster/tests/test_spectral.py b/sklearn/cluster/tests/test_spectral.py index 8f2dcecaf4a11..412f0a0211353 100644 --- a/sklearn/cluster/tests/test_spectral.py +++ b/sklearn/cluster/tests/test_spectral.py @@ -1,45 +1,55 @@ """Testing for Spectral Clustering methods""" -from cPickle import dumps, loads -import nose +from sklearn.externals.six.moves import cPickle + +dumps, loads = cPickle.dumps, cPickle.loads import numpy as np -from numpy.testing import assert_equal -from nose.tools import assert_raises from scipy import sparse -from sklearn.datasets.samples_generator import make_blobs + +from sklearn.utils import check_random_state +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_warns_message from sklearn.cluster import SpectralClustering, spectral_clustering from sklearn.cluster.spectral import spectral_embedding -from sklearn.metrics import pairwise_distances, adjusted_rand_score +from sklearn.cluster.spectral import discretize +from sklearn.metrics import pairwise_distances +from sklearn.metrics import adjusted_rand_score +from sklearn.metrics.pairwise import kernel_metrics, rbf_kernel +from sklearn.datasets.samples_generator import make_blobs def test_spectral_clustering(): - S = np.array([[1, 5, 2, 1, 0, 0, 0], - [5, 1, 3, 1, 0, 0, 0], - [2, 3, 1, 1, 0, 0, 0], - [1, 1, 1, 1, 2, 1, 1], - [0, 0, 0, 2, 2, 3, 2], - [0, 0, 0, 1, 3, 1, 4], - [0, 0, 0, 1, 2, 4, 1], - ]) - - for mat in (S, sparse.csr_matrix(S)): - model = SpectralClustering(random_state=0, n_clusters=2, - affinity='precomputed').fit(mat) - labels = model.labels_ - if labels[0] == 0: - labels = 1 - labels - - assert_equal(labels, [1, 1, 1, 0, 0, 0, 0]) - - model_copy = loads(dumps(model)) - assert_equal(model_copy.n_clusters, model.n_clusters) - assert_equal(model_copy.mode, model.mode) - assert_equal(model_copy.random_state.get_state(), - model.random_state.get_state()) - assert_equal(model_copy.labels_, model.labels_) + S = np.array([[1.0, 1.0, 1.0, 0.2, 0.0, 0.0, 0.0], + [1.0, 1.0, 1.0, 0.2, 0.0, 0.0, 0.0], + [1.0, 1.0, 1.0, 0.2, 0.0, 0.0, 0.0], + [0.2, 0.2, 0.2, 1.0, 1.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]]) + + for eigen_solver in ('arpack', 'lobpcg'): + for assign_labels in ('kmeans', 'discretize'): + for mat in (S, sparse.csr_matrix(S)): + model = SpectralClustering(random_state=0, n_clusters=2, + affinity='precomputed', + eigen_solver=eigen_solver, + assign_labels=assign_labels + ).fit(mat) + labels = model.labels_ + if labels[0] == 0: + labels = 1 - labels + + assert_array_equal(labels, [1, 1, 1, 0, 0, 0, 0]) + + model_copy = loads(dumps(model)) + assert_equal(model_copy.n_clusters, model.n_clusters) + assert_equal(model_copy.eigen_solver, model.eigen_solver) + assert_array_equal(model_copy.labels_, model.labels_) def test_spectral_amg_mode(): @@ -56,18 +66,20 @@ def test_spectral_amg_mode(): S = sparse.coo_matrix(S) try: from pyamg import smoothed_aggregation_solver + amg_loaded = True except ImportError: amg_loaded = False if amg_loaded: labels = spectral_clustering(S, n_clusters=len(centers), - random_state=0, mode="amg") + random_state=0, eigen_solver="amg") # We don't care too much that it's good, just that it *worked*. # There does have to be some lower limit on the performance though. assert_greater(np.mean(labels == true_labels), .3) else: assert_raises(ValueError, spectral_embedding, S, - n_components=len(centers), random_state=0, mode="amg") + n_components=len(centers), + random_state=0, eigen_solver="amg") def test_spectral_unknown_mode(): @@ -83,44 +95,102 @@ def test_spectral_unknown_mode(): S = np.max(D) - D # Similarity matrix S = sparse.coo_matrix(S) assert_raises(ValueError, spectral_clustering, S, n_clusters=2, - random_state=0, mode="") + random_state=0, eigen_solver="") + + +def test_spectral_unknown_assign_labels(): + # Test that SpectralClustering fails with an unknown assign_labels set. + centers = np.array([ + [0., 0., 0.], + [10., 10., 10.], + [20., 20., 20.], + ]) + X, true_labels = make_blobs(n_samples=100, centers=centers, + cluster_std=1., random_state=42) + D = pairwise_distances(X) # Distance matrix + S = np.max(D) - D # Similarity matrix + S = sparse.coo_matrix(S) + assert_raises(ValueError, spectral_clustering, S, n_clusters=2, + random_state=0, assign_labels="") def test_spectral_clustering_sparse(): - # We need a large matrice, or the lobpcg solver will fallback to its - # non-sparse and buggy mode - raise nose.SkipTest("XFailed Test") - S = np.array([[1, 5, 2, 2, 1, 0, 0, 0, 0, 0], - [5, 1, 3, 2, 1, 0, 0, 0, 0, 0], - [2, 3, 1, 1, 1, 0, 0, 0, 0, 0], - [2, 2, 1, 1, 1, 0, 0, 0, 0, 0], - [1, 1, 1, 1, 1, 1, 2, 1, 1, 1], - [0, 0, 0, 0, 1, 2, 2, 3, 3, 2], - [0, 0, 0, 0, 2, 2, 3, 3, 3, 4], - [0, 0, 0, 0, 1, 3, 3, 1, 2, 4], - [0, 0, 0, 0, 1, 3, 3, 2, 1, 4], - [0, 0, 0, 0, 1, 2, 4, 4, 4, 1], - ]) + X, y = make_blobs(n_samples=20, random_state=0, + centers=[[1, 1], [-1, -1]], cluster_std=0.01) + S = rbf_kernel(X, gamma=1) + S = np.maximum(S - 1e-4, 0) S = sparse.coo_matrix(S) labels = SpectralClustering(random_state=0, n_clusters=2, - affinity='precomputed').fit(S).labels_ - if labels[0] == 0: - labels = 1 - labels - - assert_greater(np.mean(labels == [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]), .9) + affinity='precomputed').fit(S).labels_ + assert_equal(adjusted_rand_score(y, labels), 1) def test_affinities(): - X, y = make_blobs(n_samples=40, random_state=1, centers=[[1, 1], [-1, -1]], - cluster_std=0.4) + # Note: in the following, random_state has been selected to have + # a dataset that yields a stable eigen decomposition both when built + # on OSX and Linux + X, y = make_blobs(n_samples=20, random_state=0, + centers=[[1, 1], [-1, -1]], cluster_std=0.01 + ) # nearest neighbors affinity sp = SpectralClustering(n_clusters=2, affinity='nearest_neighbors', - random_state=0) - labels = sp.fit(X).labels_ - assert_equal(adjusted_rand_score(y, labels), 1) + random_state=0) + assert_warns_message(UserWarning, 'not fully connected', sp.fit, X) + assert_equal(adjusted_rand_score(y, sp.labels_), 1) sp = SpectralClustering(n_clusters=2, gamma=2, random_state=0) labels = sp.fit(X).labels_ assert_equal(adjusted_rand_score(y, labels), 1) + + X = check_random_state(10).rand(10, 5) * 10 + + kernels_available = kernel_metrics() + for kern in kernels_available: + # Additive chi^2 gives a negative similarity matrix which + # doesn't make sense for spectral clustering + if kern != 'additive_chi2': + sp = SpectralClustering(n_clusters=2, affinity=kern, + random_state=0) + labels = sp.fit(X).labels_ + assert_equal((X.shape[0],), labels.shape) + + sp = SpectralClustering(n_clusters=2, affinity=lambda x, y: 1, + random_state=0) + labels = sp.fit(X).labels_ + assert_equal((X.shape[0],), labels.shape) + + def histogram(x, y, **kwargs): + """Histogram kernel implemented as a callable.""" + assert_equal(kwargs, {}) # no kernel_params that we didn't ask for + return np.minimum(x, y).sum() + + sp = SpectralClustering(n_clusters=2, affinity=histogram, random_state=0) + labels = sp.fit(X).labels_ + assert_equal((X.shape[0],), labels.shape) + + # raise error on unknown affinity + sp = SpectralClustering(n_clusters=2, affinity='') + assert_raises(ValueError, sp.fit, X) + + +def test_discretize(seed=8): + # Test the discretize using a noise assignment matrix + random_state = np.random.RandomState(seed) + for n_samples in [50, 100, 150, 500]: + for n_class in range(2, 10): + # random class labels + y_true = random_state.random_integers(0, n_class, n_samples) + y_true = np.array(y_true, np.float) + # noise class assignment matrix + y_indicator = sparse.coo_matrix((np.ones(n_samples), + (np.arange(n_samples), + y_true)), + shape=(n_samples, + n_class + 1)) + y_true_noisy = (y_indicator.toarray() + + 0.1 * random_state.randn(n_samples, + n_class + 1)) + y_pred = discretize(y_true_noisy, random_state) + assert_greater(adjusted_rand_score(y_true, y_pred), 0.8) diff --git a/sklearn/covariance/__init__.py b/sklearn/covariance/__init__.py index af400d5ecfb86..502d6f65d7424 100644 --- a/sklearn/covariance/__init__.py +++ b/sklearn/covariance/__init__.py @@ -9,13 +9,14 @@ from .empirical_covariance_ import empirical_covariance, EmpiricalCovariance, \ log_likelihood from .shrunk_covariance_ import shrunk_covariance, ShrunkCovariance, \ - ledoit_wolf, ledoit_wolf_shrinkage, LedoitWolf, oas, OAS + ledoit_wolf, ledoit_wolf_shrinkage, \ + LedoitWolf, oas, OAS from .robust_covariance import fast_mcd, MinCovDet from .graph_lasso_ import graph_lasso, GraphLasso, GraphLassoCV -from .outlier_detection import EllipticEnvelope, EllipticEnvelop +from .outlier_detection import EllipticEnvelope -__all__ = ['EllipticEnvelop', - 'EllipticEnvelope', + +__all__ = ['EllipticEnvelope', 'EmpiricalCovariance', 'GraphLasso', 'GraphLassoCV', diff --git a/sklearn/covariance/empirical_covariance_.py b/sklearn/covariance/empirical_covariance_.py index b71bfb660ed0c..9259c3bd111a3 100644 --- a/sklearn/covariance/empirical_covariance_.py +++ b/sklearn/covariance/empirical_covariance_.py @@ -7,7 +7,7 @@ # Gael Varoquaux # Virgile Fritsch # -# License: BSD Style. +# License: BSD 3 clause # avoid division truncation from __future__ import division @@ -16,33 +16,46 @@ from scipy import linalg from ..base import BaseEstimator -from ..utils import array2d +from ..utils import check_array from ..utils.extmath import fast_logdet, pinvh def log_likelihood(emp_cov, precision): - """Computes the log_likelihood of the data + """Computes the sample mean of the log_likelihood under a covariance model - Params - ------ - emp_cov: 2D ndarray (n_features, n_features) - Maximum Likelihood Estimator of covariance - precision: 2D ndarray (n_features, n_features) - The precision matrix of the covariance model to be tested + computes the empirical expected log-likelihood (accounting for the + normalization terms and scaling), allowing for universal comparison (beyond + this software package) + Parameters + ---------- + emp_cov : 2D ndarray (n_features, n_features) + Maximum Likelihood Estimator of covariance + + precision : 2D ndarray (n_features, n_features) + The precision matrix of the covariance model to be tested + + Returns + ------- + sample mean of the log-likelihood """ - return -np.sum(emp_cov * precision) + fast_logdet(precision) + p = precision.shape[0] + log_likelihood_ = - np.sum(emp_cov * precision) + fast_logdet(precision) + log_likelihood_ -= p * np.log(2 * np.pi) + log_likelihood_ /= 2. + return log_likelihood_ def empirical_covariance(X, assume_centered=False): """Computes the Maximum likelihood covariance estimator + Parameters ---------- - X: 2D ndarray, shape (n_samples, n_features) + X : ndarray, shape (n_samples, n_features) Data from which to compute the covariance estimate - assume_centered: Boolean + assume_centered : Boolean If True, data are not centered before computation. Useful when working with data whose mean is almost, but not exactly zero. @@ -50,15 +63,16 @@ def empirical_covariance(X, assume_centered=False): Returns ------- - covariance: 2D ndarray, shape (n_features, n_features) - Empirical covariance (Maximum Likelihood Estimator) + covariance : 2D ndarray, shape (n_features, n_features) + Empirical covariance (Maximum Likelihood Estimator). """ X = np.asarray(X) if X.ndim == 1: X = np.reshape(X, (1, -1)) - warnings.warn("Only one sample available. " \ - "You may want to reshape your data array") + if X.shape[0] == 1: + warnings.warn("Only one sample available. " + "You may want to reshape your data array") if assume_centered: covariance = np.dot(X.T, X) / X.shape[0] @@ -74,8 +88,9 @@ class EmpiricalCovariance(BaseEstimator): Parameters ---------- store_precision : bool - Specifies if the estimated precision is stored - assume_centered: bool + Specifies if the estimated precision is stored. + + assume_centered : bool If True, data are not centered before computation. Useful when working with data whose mean is almost, but not exactly zero. @@ -83,10 +98,10 @@ class EmpiricalCovariance(BaseEstimator): Attributes ---------- - `covariance_` : 2D ndarray, shape (n_features, n_features) + covariance_ : 2D ndarray, shape (n_features, n_features) Estimated covariance matrix - `precision_` : 2D ndarray, shape (n_features, n_features) + precision_ : 2D ndarray, shape (n_features, n_features) Estimated pseudo-inverse matrix. (stored only if store_precision is True) @@ -101,14 +116,14 @@ def _set_covariance(self, covariance): Storage is done accordingly to `self.store_precision`. Precision stored only if invertible. - Params - ------ - covariance: 2D ndarray, shape (n_features, n_features) - Estimated covariance matrix to be stored, and from which precision - is computed. + Parameters + ---------- + covariance : 2D ndarray, shape (n_features, n_features) + Estimated covariance matrix to be stored, and from which precision + is computed. """ - covariance = array2d(covariance) + covariance = check_array(covariance) # set covariance self.covariance_ = covariance # set precision @@ -122,8 +137,8 @@ def get_precision(self): Returns ------- - precision_: array-like, - The precision matrix associated to the current covariance object. + precision_ : array-like, + The precision matrix associated to the current covariance object. """ if self.store_precision: @@ -132,15 +147,17 @@ def get_precision(self): precision = pinvh(self.covariance_) return precision - def fit(self, X): + def fit(self, X, y=None): """Fits the Maximum Likelihood Estimator covariance model according to the given training data and parameters. Parameters ---------- X : array-like, shape = [n_samples, n_features] - Training data, where n_samples is the number of samples and - n_features is the number of features. + Training data, where n_samples is the number of samples and + n_features is the number of features. + + y : not used, present for API consistence purpose. Returns ------- @@ -148,6 +165,7 @@ def fit(self, X): Returns self. """ + X = check_array(X) if self.assume_centered: self.location_ = np.zeros(X.shape[1]) else: @@ -158,23 +176,25 @@ def fit(self, X): return self - def score(self, X_test): - """Computes the log-likelihood of a gaussian data set with + def score(self, X_test, y=None): + """Computes the log-likelihood of a Gaussian data set with `self.covariance_` as an estimator of its covariance matrix. Parameters ---------- X_test : array-like, shape = [n_samples, n_features] - Test data of which we compute the likelihood, where n_samples is - the number of samples and n_features is the number of features. - X_test is assumed to be drawn from the same distribution than - tha data used in fit (including centering). + Test data of which we compute the likelihood, where n_samples is + the number of samples and n_features is the number of features. + X_test is assumed to be drawn from the same distribution than + the data used in fit (including centering). + + y : not used, present for API consistence purpose. Returns ------- res : float - The likelihood of the data set with `self.covariance_` as an - estimator of its covariance matrix. + The likelihood of the data set with `self.covariance_` as an + estimator of its covariance matrix. """ # compute empirical covariance of the test set @@ -188,21 +208,24 @@ def score(self, X_test): def error_norm(self, comp_cov, norm='frobenius', scaling=True, squared=True): """Computes the Mean Squared Error between two covariance estimators. - (In the sense of the Frobenius norm) + (In the sense of the Frobenius norm). Parameters ---------- - comp_cov: array-like, shape = [n_features, n_features] + comp_cov : array-like, shape = [n_features, n_features] The covariance to compare with. - norm: str + + norm : str The type of norm used to compute the error. Available error types: - 'frobenius' (default): sqrt(tr(A^t.A)) - 'spectral': sqrt(max(eigenvalues(A^t.A)) where A is the error ``(comp_cov - self.covariance_)``. - scaling: bool + + scaling : bool If True (default), the squared error norm is divided by n_features. If False, the squared error norm is not rescaled. - squared: bool + + squared : bool Whether to compute the squared error norm or the error norm. If True (default), the squared error norm is returned. If False, the error norm is returned. @@ -235,22 +258,19 @@ def error_norm(self, comp_cov, norm='frobenius', scaling=True, return result def mahalanobis(self, observations): - """Computes the mahalanobis distances of given observations. - - The provided observations are assumed to be centered. One may want to - center them using a location estimate first. + """Computes the squared Mahalanobis distances of given observations. Parameters ---------- - observations: array-like, shape = [n_observations, n_features] - The observations, the Mahalanobis distances of the which we compute. - Observations are assumed to be drawn from the same distribution than - tha data used in fit (including centering). + observations : array-like, shape = [n_observations, n_features] + The observations, the Mahalanobis distances of the which we + compute. Observations are assumed to be drawn from the same + distribution than the data used in fit. Returns ------- - mahalanobis_distance: array, shape = [n_observations,] - Mahalanobis distances of the observations. + mahalanobis_distance : array, shape = [n_observations,] + Squared Mahalanobis distances of the observations. """ precision = self.get_precision() diff --git a/sklearn/covariance/graph_lasso_.py b/sklearn/covariance/graph_lasso_.py index df0b89eaad5d9..05e4e33ce6d95 100644 --- a/sklearn/covariance/graph_lasso_.py +++ b/sklearn/covariance/graph_lasso_.py @@ -3,7 +3,7 @@ """ # Author: Gael Varoquaux -# License: BSD Style +# License: BSD 3 clause # Copyright: INRIA import warnings import operator @@ -13,22 +13,30 @@ import numpy as np from scipy import linalg -from .empirical_covariance_ import empirical_covariance, \ - EmpiricalCovariance, log_likelihood +from .empirical_covariance_ import (empirical_covariance, EmpiricalCovariance, + log_likelihood) from ..utils import ConvergenceWarning from ..utils.extmath import pinvh +from ..utils.validation import check_random_state, check_array from ..linear_model import lars_path from ..linear_model import cd_fast -from ..cross_validation import check_cv, cross_val_score +from ..cross_validation import _check_cv as check_cv, cross_val_score from ..externals.joblib import Parallel, delayed +import collections -############################################################################### # Helper functions to compute the objective and dual objective functions # of the l1-penalized estimator def _objective(mle, precision_, alpha): - cost = -log_likelihood(mle, precision_) + """Evaluation of the graph-lasso objective function + + the objective function is made of a shifted scaled version of the + normalized log-likelihood (i.e. its empirical mean over the samples) and a + penalisation term to promote sparsity + """ + p = precision_.shape[0] + cost = - 2. * log_likelihood(mle, precision_) + p * np.log(2 * np.pi) cost += alpha * (np.abs(precision_).sum() - np.abs(np.diag(precision_)).sum()) return cost @@ -52,7 +60,7 @@ def alpha_max(emp_cov): Parameters ---------- - emp_cov: 2D array, (n_features, n_features) + emp_cov : 2D array, (n_features, n_features) The sample covariance matrix Notes @@ -60,59 +68,75 @@ def alpha_max(emp_cov): This results from the bound for the all the Lasso that are solved in GraphLasso: each time, the row of cov corresponds to Xy. As the - bound for alpha is given by max(abs(Xy)), the result follows. + bound for alpha is given by `max(abs(Xy))`, the result follows. + """ A = np.copy(emp_cov) A.flat[::A.shape[0] + 1] = 0 return np.max(np.abs(A)) -############################################################################### # The g-lasso algorithm def graph_lasso(emp_cov, alpha, cov_init=None, mode='cd', tol=1e-4, max_iter=100, verbose=False, return_costs=False, - eps=np.finfo(np.float).eps): + eps=np.finfo(np.float).eps, return_n_iter=False): """l1-penalized covariance estimator Parameters ---------- - emp_cov: 2D ndarray, shape (n_features, n_features) - Empirical covariance from which to compute the covariance estimate - alpha: positive float + emp_cov : 2D ndarray, shape (n_features, n_features) + Empirical covariance from which to compute the covariance estimate. + + alpha : positive float The regularization parameter: the higher alpha, the more - regularization, the sparser the inverse covariance - cov_init: 2D array (n_features, n_features), optional - The initial guess for the covariance - mode: {'cd', 'lars'} + regularization, the sparser the inverse covariance. + + cov_init : 2D array (n_features, n_features), optional + The initial guess for the covariance. + + mode : {'cd', 'lars'} The Lasso solver to use: coordinate descent or LARS. Use LARS for very sparse underlying graphs, where p > n. Elsewhere prefer cd which is more numerically stable. - tol: positive float, optional + + tol : positive float, optional The tolerance to declare convergence: if the dual gap goes below - this value, iterations are stopped - max_iter: integer, optional - The maximum number of iterations - verbose: boolean, optional + this value, iterations are stopped. + + max_iter : integer, optional + The maximum number of iterations. + + verbose : boolean, optional If verbose is True, the objective function and dual gap are - printed at each iteration - return_costs: boolean, optional + printed at each iteration. + + return_costs : boolean, optional If return_costs is True, the objective function and dual gap - at each iteration are returned - eps: float, optional + at each iteration are returned. + + eps : float, optional The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. + return_n_iter : bool, optional + Whether or not to return the number of iterations. + Returns ------- covariance : 2D ndarray, shape (n_features, n_features) - The estimated covariance matrix + The estimated covariance matrix. + precision : 2D ndarray, shape (n_features, n_features) - The estimated (sparse) precision matrix + The estimated (sparse) precision matrix. + costs : list of (objective, dual_gap) pairs The list of values of the objective function and the dual gap at - each iteration. Returned only if return_costs is True + each iteration. Returned only if return_costs is True. + + n_iter : int + Number of iterations. Returned only if `return_n_iter` is set to True. See Also -------- @@ -120,17 +144,30 @@ def graph_lasso(emp_cov, alpha, cov_init=None, mode='cd', tol=1e-4, Notes ----- - The algorithm employed to solve this problem is the GLasso algorithm, from the Friedman 2008 Biostatistics paper. It is the same algorithm as in the R `glasso` package. One possible difference with the `glasso` R package is that the diagonal coefficients are not penalized. + """ _, n_features = emp_cov.shape if alpha == 0: - return emp_cov, linalg.inv(emp_cov) + if return_costs: + precision_ = linalg.inv(emp_cov) + cost = - 2. * log_likelihood(emp_cov, precision_) + cost += n_features * np.log(2 * np.pi) + d_gap = np.sum(emp_cov * precision_) - n_features + if return_n_iter: + return emp_cov, precision_, (cost, d_gap), 0 + else: + return emp_cov, precision_, (cost, d_gap) + else: + if return_n_iter: + return emp_cov, linalg.inv(emp_cov), 0 + else: + return emp_cov, linalg.inv(emp_cov) if cov_init is None: covariance_ = emp_cov.copy() else: @@ -154,61 +191,71 @@ def graph_lasso(emp_cov, alpha, cov_init=None, mode='cd', tol=1e-4, else: errors = dict(invalid='raise') try: - for i in xrange(max_iter): - for idx in xrange(n_features): + # be robust to the max_iter=0 edge case, see: + # https://github.com/scikit-learn/scikit-learn/issues/4134 + d_gap = np.inf + for i in range(max_iter): + for idx in range(n_features): sub_covariance = covariance_[indices != idx].T[indices != idx] row = emp_cov[idx, indices != idx] with np.errstate(**errors): if mode == 'cd': # Use coordinate descent coefs = -(precision_[indices != idx, idx] - / (precision_[idx, idx] + 1000 * eps)) - coefs, _, _ = cd_fast.enet_coordinate_descent_gram( - coefs, alpha, 0, sub_covariance, - row, row, max_iter, tol) + / (precision_[idx, idx] + 1000 * eps)) + coefs, _, _, _ = cd_fast.enet_coordinate_descent_gram( + coefs, alpha, 0, sub_covariance, row, row, + max_iter, tol, check_random_state(None), False) else: # Use LARS - _, _, coefs = lars_path(sub_covariance, row, - Xy=row, Gram=sub_covariance, - alpha_min=alpha / (n_features - 1), - copy_Gram=True, - method='lars') + _, _, coefs = lars_path( + sub_covariance, row, Xy=row, Gram=sub_covariance, + alpha_min=alpha / (n_features - 1), copy_Gram=True, + method='lars') coefs = coefs[:, -1] # Update the precision matrix - precision_[idx, idx] = 1. / (covariance_[idx, idx] - - np.dot(covariance_[indices != idx, idx], coefs)) - precision_[indices != idx, idx] = \ - - precision_[idx, idx] * coefs - precision_[idx, indices != idx] = \ - - precision_[idx, idx] * coefs + precision_[idx, idx] = ( + 1. / (covariance_[idx, idx] + - np.dot(covariance_[indices != idx, idx], coefs))) + precision_[indices != idx, idx] = (- precision_[idx, idx] + * coefs) + precision_[idx, indices != idx] = (- precision_[idx, idx] + * coefs) coefs = np.dot(sub_covariance, coefs) covariance_[idx, indices != idx] = coefs covariance_[indices != idx, idx] = coefs d_gap = _dual_gap(emp_cov, precision_, alpha) cost = _objective(emp_cov, precision_, alpha) if verbose: - print ( + print( '[graph_lasso] Iteration % 3i, cost % 3.2e, dual gap %.3e' - % (i, cost, d_gap)) + % (i, cost, d_gap)) if return_costs: costs.append((cost, d_gap)) if np.abs(d_gap) < tol: break if not np.isfinite(cost) and i > 0: raise FloatingPointError('Non SPD result: the system is ' - 'too ill-conditioned for this solver') + 'too ill-conditioned for this solver') else: warnings.warn('graph_lasso: did not converge after %i iteration:' - 'dual gap: %.3e' % (max_iter, d_gap), - ConvergenceWarning) + ' dual gap: %.3e' % (max_iter, d_gap), + ConvergenceWarning) except FloatingPointError as e: e.args = (e.args[0] - + '. The system is too ill-conditioned for this solver', - ) + + '. The system is too ill-conditioned for this solver',) raise e + if return_costs: - return covariance_, precision_, costs - return covariance_, precision_ + if return_n_iter: + return covariance_, precision_, costs, i + 1 + else: + return covariance_, precision_, costs + else: + if return_n_iter: + return covariance_, precision_, i + 1 + else: + return covariance_, precision_ class GraphLasso(EmpiricalCovariance): @@ -216,91 +263,115 @@ class GraphLasso(EmpiricalCovariance): Parameters ---------- - alpha: positive float, optional + alpha : positive float, default 0.01 The regularization parameter: the higher alpha, the more - regularization, the sparser the inverse covariance - cov_init: 2D array (n_features, n_features), optional - The initial guess for the covariance - mode: {'cd', 'lars'} + regularization, the sparser the inverse covariance. + + mode : {'cd', 'lars'}, default 'cd' The Lasso solver to use: coordinate descent or LARS. Use LARS for very sparse underlying graphs, where p > n. Elsewhere prefer cd which is more numerically stable. - tol: positive float, optional + + tol : positive float, default 1e-4 The tolerance to declare convergence: if the dual gap goes below - this value, iterations are stopped - max_iter: integer, optional - The maximum number of iterations - verbose: boolean, optional + this value, iterations are stopped. + + max_iter : integer, default 100 + The maximum number of iterations. + + verbose : boolean, default False If verbose is True, the objective function and dual gap are - plotted at each iteration + plotted at each iteration. + + assume_centered : boolean, default False + If True, data are not centered before computation. + Useful when working with data whose mean is almost, but not exactly + zero. + If False, data are centered before computation. Attributes ---------- - `covariance_` : array-like, shape (n_features, n_features) + covariance_ : array-like, shape (n_features, n_features) Estimated covariance matrix - `precision_` : array-like, shape (n_features, n_features) + precision_ : array-like, shape (n_features, n_features) Estimated pseudo inverse matrix. + n_iter_ : int + Number of iterations run. + See Also -------- graph_lasso, GraphLassoCV """ def __init__(self, alpha=.01, mode='cd', tol=1e-4, max_iter=100, - verbose=False): + verbose=False, assume_centered=False): self.alpha = alpha self.mode = mode self.tol = tol self.max_iter = max_iter self.verbose = verbose + self.assume_centered = assume_centered # The base class needs this for the score method self.store_precision = True def fit(self, X, y=None): - emp_cov = empirical_covariance(X) - self.covariance_, self.precision_ = graph_lasso(emp_cov, - alpha=self.alpha, mode=self.mode, - tol=self.tol, max_iter=self.max_iter, - verbose=self.verbose, - ) + X = check_array(X) + if self.assume_centered: + self.location_ = np.zeros(X.shape[1]) + else: + self.location_ = X.mean(0) + emp_cov = empirical_covariance( + X, assume_centered=self.assume_centered) + self.covariance_, self.precision_, self.n_iter_ = graph_lasso( + emp_cov, alpha=self.alpha, mode=self.mode, tol=self.tol, + max_iter=self.max_iter, verbose=self.verbose, + return_n_iter=True) return self -############################################################################### # Cross-validation with GraphLasso def graph_lasso_path(X, alphas, cov_init=None, X_test=None, mode='cd', - tol=1e-4, max_iter=100, verbose=False): + tol=1e-4, max_iter=100, verbose=False): """l1-penalized covariance estimator along a path of decreasing alphas Parameters ---------- - X: 2D ndarray, shape (n_samples, n_features) - Data from which to compute the covariance estimate - alphas: list of positive floats - The list of regularization parameters, decreasing order - X_test: 2D array, shape (n_test_samples, n_features), optional - Optional test matrix to measure generalisation error - mode: {'cd', 'lars'} + X : 2D ndarray, shape (n_samples, n_features) + Data from which to compute the covariance estimate. + + alphas : list of positive floats + The list of regularization parameters, decreasing order. + + X_test : 2D array, shape (n_test_samples, n_features), optional + Optional test matrix to measure generalisation error. + + mode : {'cd', 'lars'} The Lasso solver to use: coordinate descent or LARS. Use LARS for very sparse underlying graphs, where p > n. Elsewhere prefer cd which is more numerically stable. - tol: positive float, optional + + tol : positive float, optional The tolerance to declare convergence: if the dual gap goes below - this value, iterations are stopped - max_iter: integer, optional - The maximum number of iterations - verbose: integer, optional + this value, iterations are stopped. + + max_iter : integer, optional + The maximum number of iterations. + + verbose : integer, optional The higher the verbosity flag, the more information is printed during the fitting. Returns ------- - covariances_: List of 2D ndarray, shape (n_features, n_features) - The estimated covariance matrices - precisions_: List of 2D ndarray, shape (n_features, n_features) - The estimated (sparse) precision matrices - scores_: List of float + covariances_ : List of 2D ndarray, shape (n_features, n_features) + The estimated covariance matrices. + + precisions_ : List of 2D ndarray, shape (n_features, n_features) + The estimated (sparse) precision matrices. + + scores_ : List of float The generalisation error (log-likelihood) on the test data. Returned only if test data is passed. """ @@ -315,13 +386,13 @@ def graph_lasso_path(X, alphas, cov_init=None, X_test=None, mode='cd', scores_ = list() if X_test is not None: test_emp_cov = empirical_covariance(X_test) + for alpha in alphas: try: # Capture the errors, and move on - covariance_, precision_ = graph_lasso(emp_cov, alpha=alpha, - cov_init=covariance_, mode=mode, tol=tol, - max_iter=max_iter, - verbose=inner_verbose) + covariance_, precision_ = graph_lasso( + emp_cov, alpha=alpha, cov_init=covariance_, mode=mode, tol=tol, + max_iter=max_iter, verbose=inner_verbose) covariances_.append(covariance_) precisions_.append(precision_) if X_test is not None: @@ -336,64 +407,82 @@ def graph_lasso_path(X, alphas, cov_init=None, X_test=None, mode='cd', scores_.append(this_score) if verbose == 1: sys.stderr.write('.') - elif verbose: + elif verbose > 1: if X_test is not None: - print '[graph_lasso_path] alpha: %.2e, score: %.2e' % (alpha, - this_score) + print('[graph_lasso_path] alpha: %.2e, score: %.2e' + % (alpha, this_score)) else: - print '[graph_lasso_path] alpha: %.2e' % alpha + print('[graph_lasso_path] alpha: %.2e' % alpha) if X_test is not None: return covariances_, precisions_, scores_ return covariances_, precisions_ class GraphLassoCV(GraphLasso): - """Sparse inverse covariance w/ cross-validated choice of the l1 penality + """Sparse inverse covariance w/ cross-validated choice of the l1 penalty Parameters ---------- - alphas: integer, or list positive float, optional + alphas : integer, or list positive float, optional If an integer is given, it fixes the number of points on the grids of alpha to be used. If a list is given, it gives the grid to be used. See the notes in the class docstring for more details. + n_refinements: strictly positive integer - The number of time the grid is refined. Not used if explicit + The number of times the grid is refined. Not used if explicit values of alphas are passed. - cv : crossvalidation generator, optional - see sklearn.cross_validation module. If None is passed, default to + + cv : cross-validation generator, optional + see sklearn.cross_validation module. If None is passed, defaults to a 3-fold strategy + tol: positive float, optional The tolerance to declare convergence: if the dual gap goes below - this value, iterations are stopped + this value, iterations are stopped. + max_iter: integer, optional - The maximum number of iterations + Maximum number of iterations. + mode: {'cd', 'lars'} The Lasso solver to use: coordinate descent or LARS. Use LARS for - very sparse underlying graphs, where p > n. Elsewhere prefer cd - which is more numerically stable. + very sparse underlying graphs, where number of features is greater + than number of samples. Elsewhere prefer cd which is more numerically + stable. + n_jobs: int, optional - number of jobs to run in parallel (default 1) + number of jobs to run in parallel (default 1). + verbose: boolean, optional - If verbose is True, the objective function and dual gap are - print at each iteration + If verbose is True, the objective function and duality gap are + printed at each iteration. + + assume_centered : Boolean + If True, data are not centered before computation. + Useful when working with data whose mean is almost, but not exactly + zero. + If False, data are centered before computation. + Attributes ---------- - `covariance_` : array-like, shape (n_features, n_features) - Estimated covariance matrix + covariance_ : numpy.ndarray, shape (n_features, n_features) + Estimated covariance matrix. - `precision_` : array-like, shape (n_features, n_features) + precision_ : numpy.ndarray, shape (n_features, n_features) Estimated precision matrix (inverse covariance). - `alpha_`: float - Penalization parameter selected + alpha_ : float + Penalization parameter selected. + + cv_alphas_ : list of float + All penalization parameters explored. - `cv_alphas_`: list of float - All the penalization parameters explored + `grid_scores`: 2D numpy.ndarray (n_alphas, n_folds) + Log-likelihood score on left-out data across folds. - `cv_scores`: 2D array (n_alphas, n_folds) - The log-likelihood score on left-out data across the folds. + n_iter_ : int + Number of iterations run for the optimal alpha. See Also -------- @@ -401,18 +490,20 @@ class GraphLassoCV(GraphLasso): Notes ----- - The search for the optimal alpha is done on an iteratively refined - grid: first the cross-validated scores on a grid are computed, then - a new refined grid is center around the maximum... + The search for the optimal penalization parameter (alpha) is done on an + iteratively refined grid: first the cross-validated scores on a grid are + computed, then a new refined grid is centered around the maximum, and so + on. - One of the challenges that we have to face is that the solvers can + One of the challenges which is faced here is that the solvers can fail to converge to a well-conditioned estimate. The corresponding values of alpha then come out as missing values, but the optimum may be close to these missing values. """ def __init__(self, alphas=4, n_refinements=4, cv=None, tol=1e-4, - max_iter=100, mode='cd', n_jobs=1, verbose=False): + max_iter=100, mode='cd', n_jobs=1, verbose=False, + assume_centered=False): self.alphas = alphas self.n_refinements = n_refinements self.mode = mode @@ -421,12 +512,25 @@ def __init__(self, alphas=4, n_refinements=4, cv=None, tol=1e-4, self.verbose = verbose self.cv = cv self.n_jobs = n_jobs + self.assume_centered = assume_centered # The base class needs this for the score method self.store_precision = True def fit(self, X, y=None): - X = np.asarray(X) - emp_cov = empirical_covariance(X) + """Fits the GraphLasso covariance model to X. + + Parameters + ---------- + X : ndarray, shape (n_samples, n_features) + Data from which to compute the covariance estimate + """ + X = check_array(X) + if self.assume_centered: + self.location_ = np.zeros(X.shape[1]) + else: + self.location_ = X.mean(0) + emp_cov = empirical_covariance( + X, assume_centered=self.assume_centered) cv = check_cv(self.cv, X, y, classifier=False) @@ -435,17 +539,15 @@ def fit(self, X, y=None): n_alphas = self.alphas inner_verbose = max(0, self.verbose - 1) - if operator.isSequenceType(n_alphas): + if isinstance(n_alphas, collections.Sequence): alphas = self.alphas n_refinements = 1 else: n_refinements = self.n_refinements alpha_1 = alpha_max(emp_cov) alpha_0 = 1e-2 * alpha_1 - alphas = np.logspace(np.log10(alpha_0), - np.log10(alpha_1), - n_alphas)[::-1] - covs_init = (None, None, None) + alphas = np.logspace(np.log10(alpha_0), np.log10(alpha_1), + n_alphas)[::-1] t0 = time.time() for i in range(n_refinements): @@ -453,18 +555,23 @@ def fit(self, X, y=None): # No need to see the convergence warnings on this grid: # they will always be points that will not converge # during the cross-validation - warnings.simplefilter('ignore', ConvergenceWarning) + warnings.simplefilter('ignore', ConvergenceWarning) # Compute the cross-validated loss on the current grid + + # NOTE: Warm-restarting graph_lasso_path has been tried, and + # this did not allow to gain anything (same execution time with + # or without). this_path = Parallel( n_jobs=self.n_jobs, - verbose=self.verbose)( - delayed(graph_lasso_path)( - X[train], alphas=alphas, - X_test=X[test], mode=self.mode, - tol=self.tol, - max_iter=int(.1 * self.max_iter), - verbose=inner_verbose) - for (train, test), cov_init in zip(cv, covs_init)) + verbose=self.verbose + )( + delayed(graph_lasso_path)( + X[train], alphas=alphas, + X_test=X[test], mode=self.mode, + tol=self.tol, + max_iter=int(.1 * self.max_iter), + verbose=inner_verbose) + for train, test in cv) # Little danse to transform the list in what we need covs, _, scores = zip(*this_path) @@ -473,9 +580,9 @@ def fit(self, X, y=None): path.extend(zip(alphas, scores, covs)) path = sorted(path, key=operator.itemgetter(0), reverse=True) - # Find the maximum (we avoid using built in 'max' function to + # Find the maximum (avoid using built in 'max' function to # have a fully-reproducible selection of the smallest alpha - # is case of equality) + # in case of equality) best_score = -np.inf last_finite_idx = 0 for index, (alpha, scores, _) in enumerate(path): @@ -488,51 +595,51 @@ def fit(self, X, y=None): best_score = this_score best_index = index - # Refine our grid + # Refine the grid if best_index == 0: - # We do not need to go back: we have choosen + # We do not need to go back: we have chosen # the highest value of alpha for which there are # non-zero coefficients alpha_1 = path[0][0] alpha_0 = path[1][0] - covs_init = path[0][-1] elif (best_index == last_finite_idx - and not best_index == len(path) - 1): + and not best_index == len(path) - 1): # We have non-converged models on the upper bound of the # grid, we need to refine the grid there alpha_1 = path[best_index][0] alpha_0 = path[best_index + 1][0] - covs_init = path[best_index][-1] elif best_index == len(path) - 1: alpha_1 = path[best_index][0] alpha_0 = 0.01 * path[best_index][0] - covs_init = path[best_index][-1] else: alpha_1 = path[best_index - 1][0] alpha_0 = path[best_index + 1][0] - covs_init = path[best_index - 1][-1] - alphas = np.logspace(np.log10(alpha_1), np.log10(alpha_0), - n_alphas + 2) - alphas = alphas[1:-1] + + if not isinstance(n_alphas, collections.Sequence): + alphas = np.logspace(np.log10(alpha_1), np.log10(alpha_0), + n_alphas + 2) + alphas = alphas[1:-1] + if self.verbose and n_refinements > 1: - print '[GraphLassoCV] Done refinement % 2i out of %i: % 3is'\ - % (i + 1, n_refinements, time.time() - t0) + print('[GraphLassoCV] Done refinement % 2i out of %i: % 3is' + % (i + 1, n_refinements, time.time() - t0)) - path = zip(*path) - cv_scores = list(path[1]) + path = list(zip(*path)) + grid_scores = list(path[1]) alphas = list(path[0]) # Finally, compute the score with alpha = 0 alphas.append(0) - cv_scores.append(cross_val_score(EmpiricalCovariance(), X, - cv=cv, n_jobs=self.n_jobs, - verbose=inner_verbose)) - self.cv_scores = np.array(cv_scores) + grid_scores.append(cross_val_score(EmpiricalCovariance(), X, + cv=cv, n_jobs=self.n_jobs, + verbose=inner_verbose)) + self.grid_scores = np.array(grid_scores) best_alpha = alphas[best_index] self.alpha_ = best_alpha self.cv_alphas_ = alphas # Finally fit the model with the selected alpha - self.covariance_, self.precision_ = graph_lasso(emp_cov, - alpha=best_alpha, mode=self.mode, tol=self.tol, - max_iter=self.max_iter, verbose=inner_verbose) + self.covariance_, self.precision_, self.n_iter_ = graph_lasso( + emp_cov, alpha=best_alpha, mode=self.mode, tol=self.tol, + max_iter=self.max_iter, verbose=inner_verbose, + return_n_iter=True) return self diff --git a/sklearn/covariance/outlier_detection.py b/sklearn/covariance/outlier_detection.py index a2d27a4b00611..6015e09da9dca 100644 --- a/sklearn/covariance/outlier_detection.py +++ b/sklearn/covariance/outlier_detection.py @@ -10,13 +10,14 @@ """ # Author: Virgile Fritsch # -# License: BSD Style. +# License: BSD 3 clause +import warnings import numpy as np -import scipy as sp +import scipy as sp from . import MinCovDet -from ..utils import deprecated from ..base import ClassifierMixin +from ..utils.validation import check_is_fitted class OutlierDetectionMixin(object): @@ -24,7 +25,7 @@ class OutlierDetectionMixin(object): Parameters ---------- - contamination: float, 0. < contamination < 0.5 + contamination : float, 0. < contamination < 0.5 The amount of contamination of the data set, i.e. the proportion of outliers in the data set. @@ -37,23 +38,22 @@ class OutlierDetectionMixin(object): """ def __init__(self, contamination=0.1): self.contamination = contamination - self.threshold = None def decision_function(self, X, raw_values=False): """Compute the decision function of the given observations. Parameters ---------- - X: array-like, shape (n_samples, n_features) + X : array-like, shape (n_samples, n_features) - raw_values: bool + raw_values : bool Whether or not to consider raw Mahalanobis distances as the decision function. Must be False (default) for compatibility with the others outlier detection tools. Returns ------- - decision: array-like, shape (n_samples, ) + decision : array-like, shape (n_samples, ) The values of the decision function for each observations. It is equal to the Mahalanobis distances if `raw_values` is True. By default (``raw_values=True``), it is equal @@ -63,14 +63,14 @@ def decision_function(self, X, raw_values=False): such as the One-Class SVM. """ + check_is_fitted(self, 'threshold_') mahal_dist = self.mahalanobis(X) if raw_values: decision = mahal_dist else: - if self.threshold is None: - raise Exception("Please fit data before predicting") + check_is_fitted(self, 'threshold_') transformed_mahal_dist = mahal_dist ** 0.33 - decision = self.threshold ** 0.33 - transformed_mahal_dist + decision = self.threshold_ ** 0.33 - transformed_mahal_dist return decision @@ -79,57 +79,65 @@ def predict(self, X): Parameters ---------- - X: array-like, shape = (n_samples, n_features) + X : array-like, shape = (n_samples, n_features) Returns ------- - is_outliers: array, shape = (n_samples, ), dtype = bool + is_outliers : array, shape = (n_samples, ), dtype = bool For each observations, tells whether or not it should be considered as an outlier according to the fitted model. - threshold: float, + + threshold : float, The values of the less outlying point's decision function. """ - if self.threshold is None: - raise Exception("Please fit data before predicting") + check_is_fitted(self, 'threshold_') is_inlier = -np.ones(X.shape[0], dtype=int) if self.contamination is not None: values = self.decision_function(X, raw_values=True) - is_inlier[values <= self.threshold] = 1 + is_inlier[values <= self.threshold_] = 1 else: - raise NotImplemented("You must provide a contamination rate.") + raise NotImplementedError("You must provide a contamination rate.") return is_inlier + @property + def threshold(self): + warnings.warn(("The threshold attribute is renamed to threshold_ from " + "0.16 onwards and will be removed in 0.18"), + DeprecationWarning, stacklevel=1) + return getattr(self, 'threshold_', None) + class EllipticEnvelope(ClassifierMixin, OutlierDetectionMixin, MinCovDet): """An object for detecting outliers in a Gaussian distributed dataset. Attributes ---------- - `contamination`: float, 0. < contamination < 0.5 + `contamination` : float, 0. < contamination < 0.5 The amount of contamination of the data set, i.e. the proportion of \ outliers in the data set. - `location_`: array-like, shape (n_features,) + location_ : array-like, shape (n_features,) Estimated robust location - `covariance_`: array-like, shape (n_features, n_features) + covariance_ : array-like, shape (n_features, n_features) Estimated robust covariance matrix - `precision_`: array-like, shape (n_features, n_features) + precision_ : array-like, shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) - `support_`: array-like, shape (n_samples,) + support_ : array-like, shape (n_samples,) A mask of the observations that have been used to compute the robust estimates of location and shape. Parameters ---------- - store_precision: bool - Specify if the estimated precision is stored - assume_centered: Boolean + store_precision : bool + Specify if the estimated precision is stored. + + assume_centered : Boolean If True, the support of robust location and covariance estimates is computed, and a covariance estimate is recomputed from it, without centering the data. @@ -137,12 +145,14 @@ class EllipticEnvelope(ClassifierMixin, OutlierDetectionMixin, MinCovDet): zero but is not exactly zero. If False, the robust location and covariance are directly computed with the FastMCD algorithm without additional treatment. - support_fraction: float, 0 < support_fraction < 1 + + support_fraction : float, 0 < support_fraction < 1 The proportion of points to be included in the support of the raw MCD estimate. Default is ``None``, which implies that the minimum value of support_fraction will be used within the algorithm: - [n_sample + n_features + 1] / 2 - contamination: float, 0. < contamination < 0.5 + `[n_sample + n_features + 1] / 2`. + + contamination : float, 0. < contamination < 0.5 The amount of contamination of the data set, i.e. the proportion of outliers in the data set. @@ -163,23 +173,16 @@ class EllipticEnvelope(ClassifierMixin, OutlierDetectionMixin, MinCovDet): """ def __init__(self, store_precision=True, assume_centered=False, - support_fraction=None, contamination=0.1): + support_fraction=None, contamination=0.1, + random_state=None): MinCovDet.__init__(self, store_precision=store_precision, assume_centered=assume_centered, - support_fraction=support_fraction) + support_fraction=support_fraction, + random_state=random_state) OutlierDetectionMixin.__init__(self, contamination=contamination) - def fit(self, X): - """ - """ + def fit(self, X, y=None): MinCovDet.fit(self, X) - self.threshold = sp.stats.scoreatpercentile( + self.threshold_ = sp.stats.scoreatpercentile( self.dist_, 100. * (1. - self.contamination)) - return self - - -# Deprecated classes -@deprecated("Use EllipticEnvelope instead. To be removed in 0.13.") -class EllipticEnvelop(EllipticEnvelope): - pass diff --git a/sklearn/covariance/robust_covariance.py b/sklearn/covariance/robust_covariance.py index a7ba04d2f0f8c..afacb1fa4a690 100644 --- a/sklearn/covariance/robust_covariance.py +++ b/sklearn/covariance/robust_covariance.py @@ -6,80 +6,100 @@ """ # Author: Virgile Fritsch # -# License: BSD Style. +# License: BSD 3 clause import warnings +import numbers import numpy as np from scipy import linalg from scipy.stats import chi2 from . import empirical_covariance, EmpiricalCovariance from ..utils.extmath import fast_logdet, pinvh -from ..utils import check_random_state +from ..utils import check_random_state, check_array -############################################################################### -### Minimum Covariance Determinant +# Minimum Covariance Determinant # Implementing of an algorithm by Rousseeuw & Van Driessen described in # (A Fast Algorithm for the Minimum Covariance Determinant Estimator, # 1999, American Statistical Association and the American Society # for Quality, TECHNOMETRICS) -############################################################################### +# XXX Is this really a public function? It's not listed in the docs or +# exported by sklearn.covariance. Deprecate? def c_step(X, n_support, remaining_iterations=30, initial_estimates=None, verbose=False, cov_computation_method=empirical_covariance, random_state=None): - """C_step procedure described in [Rouseeuw1984] aiming at computing the MCD + """C_step procedure described in [Rouseeuw1984]_ aiming at computing MCD. Parameters ---------- - X: array-like, shape (n_samples, n_features) - Data set in which we look for the n_support observations whose - scatter matrix has minimum determinant - n_support: int, > n_samples / 2 - Number of observations to compute the robust estimates of location - and covariance from. - remaining_iterations: int - Number of iterations to perform. - According to [Rouseeuw1999], two iterations are sufficient to get close - to the minimum, and we never need more than 30 to reach convergence. - initial_estimates: 2-tuple - Initial estimates of location and shape from which to run the c_step - procedure: - - initial_estimates[0]: an initial location estimate - - initial_estimates[1]: an initial covariance estimate - verbose: boolean - Verbose mode - random_state: integer or numpy.RandomState, optional + X : array-like, shape (n_samples, n_features) + Data set in which we look for the n_support observations whose + scatter matrix has minimum determinant. + + n_support : int, > n_samples / 2 + Number of observations to compute the robust estimates of location + and covariance from. + + remaining_iterations : int, optional + Number of iterations to perform. + According to [Rouseeuw1999]_, two iterations are sufficient to get + close to the minimum, and we never need more than 30 to reach + convergence. + + initial_estimates : 2-tuple, optional + Initial estimates of location and shape from which to run the c_step + procedure: + - initial_estimates[0]: an initial location estimate + - initial_estimates[1]: an initial covariance estimate + + verbose : boolean, optional + Verbose mode. + + random_state : integer or numpy.RandomState, optional The random generator used. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. + cov_computation_method : callable, default empirical_covariance + The function which will be used to compute the covariance. + Must return shape (n_features, n_features) + Returns ------- - location: array-like, shape (n_features,) - Robust location estimates - covariance: array-like, shape (n_features, n_features) - Robust covariance estimates - support: array-like, shape (n_samples,) - A mask for the `n_support` observations whose scatter matrix has - minimum determinant + location : array-like, shape (n_features,) + Robust location estimates. + + covariance : array-like, shape (n_features, n_features) + Robust covariance estimates. + + support : array-like, shape (n_samples,) + A mask for the `n_support` observations whose scatter matrix has + minimum determinant. References ---------- - .. [Rouseeuw1999] A Fast Algorithm for the Minimum Covariance Determinant - Estimator, 1999, American Statistical Association and the American - Society for Quality, TECHNOMETRICS + Estimator, 1999, American Statistical Association and the American + Society for Quality, TECHNOMETRICS """ + X = np.asarray(X) random_state = check_random_state(random_state) + return _c_step(X, n_support, remaining_iterations=remaining_iterations, + initial_estimates=initial_estimates, verbose=verbose, + cov_computation_method=cov_computation_method, + random_state=random_state) + + +def _c_step(X, n_support, random_state, remaining_iterations=30, + initial_estimates=None, verbose=False, + cov_computation_method=empirical_covariance): n_samples, n_features = X.shape # Initialisation + support = np.zeros(n_samples, dtype=bool) if initial_estimates is None: # compute initial robust estimates from a random subset - support = np.zeros(n_samples).astype(bool) support[random_state.permutation(n_samples)[:n_support]] = True - location = X[support].mean(0) - covariance = cov_computation_method(X[support]) else: # get initial robust estimates from the function parameters location = initial_estimates[0] @@ -89,14 +109,15 @@ def c_step(X, n_support, remaining_iterations=30, initial_estimates=None, X_centered = X - location dist = (np.dot(X_centered, precision) * X_centered).sum(1) # compute new estimates - support = np.zeros(n_samples).astype(bool) support[np.argsort(dist)[:n_support]] = True - location = X[support].mean(0) - covariance = cov_computation_method(X[support]) - previous_det = np.inf + + X_support = X[support] + location = X_support.mean(0) + covariance = cov_computation_method(X_support) # Iterative procedure for Minimum Covariance Determinant computation det = fast_logdet(covariance) + previous_det = np.inf while (det < previous_det) and (remaining_iterations > 0): # save old estimates values previous_location = location @@ -108,42 +129,43 @@ def c_step(X, n_support, remaining_iterations=30, initial_estimates=None, X_centered = X - location dist = (np.dot(X_centered, precision) * X_centered).sum(axis=1) # compute new estimates - support = np.zeros(n_samples).astype(bool) + support = np.zeros(n_samples, dtype=bool) support[np.argsort(dist)[:n_support]] = True - location = X[support].mean(axis=0) - covariance = cov_computation_method(X[support]) + X_support = X[support] + location = X_support.mean(axis=0) + covariance = cov_computation_method(X_support) det = fast_logdet(covariance) # update remaining iterations for early stopping remaining_iterations -= 1 previous_dist = dist - dist = (np.dot(X - location, precision) \ - * (X - location)).sum(axis=1) + dist = (np.dot(X - location, precision) * (X - location)).sum(axis=1) # Catch computation errors if np.isinf(det): raise ValueError( "Singular covariance matrix. " "Please check that the covariance matrix corresponding " - "to the dataset is full rank.") + "to the dataset is full rank and that MinCovDet is used with " + "Gaussian-distributed data (or at least data drawn from a " + "unimodal, symmetric distribution.") # Check convergence if np.allclose(det, previous_det): # c_step procedure converged if verbose: - print "Optimal couple (location, covariance) found before" \ - "ending iterations (%d left)" % (remaining_iterations) + print("Optimal couple (location, covariance) found before" + " ending iterations (%d left)" % (remaining_iterations)) results = location, covariance, det, support, dist elif det > previous_det: # determinant has increased (should not happen) - warnings.warn("Warning! det > previous_det (%.15f > %.15f)" \ - % (det, previous_det), RuntimeWarning) + warnings.warn("Warning! det > previous_det (%.15f > %.15f)" + % (det, previous_det), RuntimeWarning) results = previous_location, previous_covariance, \ previous_det, previous_support, previous_dist # Check early stopping if remaining_iterations == 0: if verbose: - print 'Maximum number of iterations reached' - det = fast_logdet(covariance) + print('Maximum number of iterations reached') results = location, covariance, det, support, dist return results @@ -164,66 +186,81 @@ def select_candidates(X, n_support, n_trials, select=1, n_iter=30, Starting from a random support, the pure data set is found by the c_step procedure introduced by Rousseeuw and Van Driessen in - [Rouseeuw1999]. + [Rouseeuw1999]_. Parameters ---------- - X: array-like, shape (n_samples, n_features) - Data (sub)set in which we look for the n_support purest observations - n_support: int, [(n + p + 1)/2] < n_support < n - The number of samples the pure data set must contain. - select: int, int > 0 - Number of best candidates results to return. - n_trials: int, nb_trials > 0 or 2-tuple - Number of different initial sets of observations from which to - run the algorithm. - Instead of giving a number of trials to perform, one can provide a - list of initial estimates that will be used to iteratively run - c_step procedures. In this case: - - n_trials[0]: array-like, shape (n_trials, n_features) - is the list of `n_trials` initial location estimates - - n_trials[1]: array-like, shape (n_trials, n_features, n_features) - is the list of `n_trials` initial covariances estimates - n_iter: int, nb_iter > 0 - Maximum number of iterations for the c_step procedure. - (2 is enough to be close to the final solution. "Never" exceeds 20) - random_state: integer or numpy.RandomState, optional + X : array-like, shape (n_samples, n_features) + Data (sub)set in which we look for the n_support purest observations. + + n_support : int, [(n + p + 1)/2] < n_support < n + The number of samples the pure data set must contain. + + select : int, int > 0 + Number of best candidates results to return. + + n_trials : int, nb_trials > 0 or 2-tuple + Number of different initial sets of observations from which to + run the algorithm. + Instead of giving a number of trials to perform, one can provide a + list of initial estimates that will be used to iteratively run + c_step procedures. In this case: + - n_trials[0]: array-like, shape (n_trials, n_features) + is the list of `n_trials` initial location estimates + - n_trials[1]: array-like, shape (n_trials, n_features, n_features) + is the list of `n_trials` initial covariances estimates + + n_iter : int, nb_iter > 0 + Maximum number of iterations for the c_step procedure. + (2 is enough to be close to the final solution. "Never" exceeds 20). + + random_state : integer or numpy.RandomState, default None The random generator used. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. + cov_computation_method : callable, default empirical_covariance + The function which will be used to compute the covariance. + Must return shape (n_features, n_features) + + verbose : boolean, default False + Control the output verbosity. + See Also --------- - `c_step` function + c_step Returns ------- - best_locations: array-like, shape (select, n_features) - The `select` location estimates computed from the `select` best - supports found in the data set (`X`) - best_covariances: array-like, shape (select, n_features, n_features) - The `select` covariance estimates computed from the `select` - best supports found in the data set (`X`) - best_supports: array-like, shape (select, n_samples) - The `select` best supports found in the data set (`X`) + best_locations : array-like, shape (select, n_features) + The `select` location estimates computed from the `select` best + supports found in the data set (`X`). + + best_covariances : array-like, shape (select, n_features, n_features) + The `select` covariance estimates computed from the `select` + best supports found in the data set (`X`). + + best_supports : array-like, shape (select, n_samples) + The `select` best supports found in the data set (`X`). References ---------- .. [Rouseeuw1999] A Fast Algorithm for the Minimum Covariance Determinant - Estimator, 1999, American Statistical Association and the American - Society for Quality, TECHNOMETRICS + Estimator, 1999, American Statistical Association and the American + Society for Quality, TECHNOMETRICS """ random_state = check_random_state(random_state) n_samples, n_features = X.shape - if isinstance(n_trials, (int, np.integer)): + if isinstance(n_trials, numbers.Integral): run_from_estimates = False elif isinstance(n_trials, tuple): run_from_estimates = True estimates_list = n_trials n_trials = estimates_list[0].shape[0] else: - raise Exception("Bad 'n_trials' parameter (wrong type)") + raise TypeError("Invalid 'n_trials' parameter, expected tuple or " + " integer, got %s (%s)" % (n_trials, type(n_trials))) # compute `n_trials` location and shape estimates candidates in the subset all_estimates = [] @@ -231,7 +268,7 @@ def select_candidates(X, n_support, n_trials, select=1, n_iter=30, # perform `n_trials` computations from random initial supports for j in range(n_trials): all_estimates.append( - c_step( + _c_step( X, n_support, remaining_iterations=n_iter, verbose=verbose, cov_computation_method=cov_computation_method, random_state=random_state)) @@ -239,11 +276,11 @@ def select_candidates(X, n_support, n_trials, select=1, n_iter=30, # perform computations from every given initial estimates for j in range(n_trials): initial_estimates = (estimates_list[0][j], estimates_list[1][j]) - all_estimates.append(c_step( - X, n_support, remaining_iterations=n_iter, - initial_estimates=initial_estimates, verbose=verbose, - cov_computation_method=cov_computation_method, - random_state=random_state)) + all_estimates.append(_c_step( + X, n_support, remaining_iterations=n_iter, + initial_estimates=initial_estimates, verbose=verbose, + cov_computation_method=cov_computation_method, + random_state=random_state)) all_locs_sub, all_covs_sub, all_dets_sub, all_supports_sub, all_ds_sub = \ zip(*all_estimates) # find the `n_best` best results among the `n_trials` ones @@ -263,18 +300,24 @@ def fast_mcd(X, support_fraction=None, Parameters ---------- - X: array-like, shape (n_samples, n_features) + X : array-like, shape (n_samples, n_features) The data matrix, with p features and n samples. - support_fraction: float, 0 < support_fraction < 1 + + support_fraction : float, 0 < support_fraction < 1 The proportion of points to be included in the support of the raw MCD estimate. Default is None, which implies that the minimum value of support_fraction will be used within the algorithm: - [n_sample + n_features + 1] / 2 - random_state: integer or numpy.RandomState, optional + `[n_sample + n_features + 1] / 2`. + + random_state : integer or numpy.RandomState, optional The generator used to randomly subsample. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. + cov_computation_method : callable, default empirical_covariance + The function which will be used to compute the covariance. + Must return shape (n_features, n_features) + Notes ----- The FastMCD algorithm has been introduced by Rousseuw and Van Driessen @@ -286,39 +329,41 @@ def fast_mcd(X, support_fraction=None, Depending on the size of the initial sample, we have one, two or three such computation levels. - Note that only raw estimates are returned. If one is intersted in - the correction and reweighting steps described in [Rouseeuw1999], + Note that only raw estimates are returned. If one is interested in + the correction and reweighting steps described in [Rouseeuw1999]_, see the MinCovDet object. References ---------- .. [Rouseeuw1999] A Fast Algorithm for the Minimum Covariance - Determinant Estimator, 1999, American Statistical Association - and the American Society for Quality, TECHNOMETRICS + Determinant Estimator, 1999, American Statistical Association + and the American Society for Quality, TECHNOMETRICS .. [Butler1993] R. W. Butler, P. L. Davies and M. Jhun, - Asymptotics For The Minimum Covariance Determinant Estimator, - The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400 + Asymptotics For The Minimum Covariance Determinant Estimator, + The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400 Returns ------- - location: array-like, shape (n_features,) - Robust location of the data - covariance: array-like, shape (n_features, n_features) - Robust covariance of the features - support: array-like, type boolean, shape (n_samples,) - a mask of the observations that have been used to compute - the robust location and covariance estimates of the data set + location : array-like, shape (n_features,) + Robust location of the data. + + covariance : array-like, shape (n_features, n_features) + Robust covariance of the features. + + support : array-like, type boolean, shape (n_samples,) + A mask of the observations that have been used to compute + the robust location and covariance estimates of the data set. """ random_state = check_random_state(random_state) - X = np.asanyarray(X) + X = np.asarray(X) if X.ndim == 1: X = np.reshape(X, (1, -1)) - warnings.warn("Only one sample available. " \ - "You may want to reshape your data array") + warnings.warn("Only one sample available. " + "You may want to reshape your data array") n_samples, n_features = X.shape # minimum breakdown value @@ -341,13 +386,12 @@ def fast_mcd(X, support_fraction=None, + X_sorted[halves_start]).mean() support = np.zeros(n_samples, dtype=bool) X_centered = X - location - support[np.argsort(np.abs(X - location), 0)[:n_support]] = True + support[np.argsort(np.abs(X_centered), 0)[:n_support]] = True covariance = np.asarray([[np.var(X[support])]]) location = np.array([location]) # get precision matrix in an optimized way precision = pinvh(covariance) - dist = (np.dot(X_centered, precision) \ - * (X_centered)).sum(axis=1) + dist = (np.dot(X_centered, precision) * (X_centered)).sum(axis=1) else: support = np.ones(n_samples, dtype=bool) covariance = np.asarray([[np.var(X)]]) @@ -355,17 +399,16 @@ def fast_mcd(X, support_fraction=None, X_centered = X - location # get precision matrix in an optimized way precision = pinvh(covariance) - dist = (np.dot(X_centered, precision) \ - * (X_centered)).sum(axis=1) - - ### Starting FastMCD algorithm for p-dimensional case + dist = (np.dot(X_centered, precision) * (X_centered)).sum(axis=1) +# Starting FastMCD algorithm for p-dimensional case if (n_samples > 500) and (n_features > 1): - ## 1. Find candidate supports on subsets + # 1. Find candidate supports on subsets # a. split the set in subsets of size ~ 300 n_subsets = n_samples // 300 n_samples_subsets = n_samples // n_subsets samples_shuffle = random_state.permutation(n_samples) - h_subset = np.ceil(n_samples_subsets * (n_support / float(n_samples))) + h_subset = int(np.ceil(n_samples_subsets * + (n_support / float(n_samples)))) # b. perform a total of 500 trials n_trials_tot = 500 # c. select 10 best (location, covariance) for each subset @@ -373,7 +416,16 @@ def fast_mcd(X, support_fraction=None, n_trials = max(10, n_trials_tot // n_subsets) n_best_tot = n_subsets * n_best_sub all_best_locations = np.zeros((n_best_tot, n_features)) - all_best_covariances = np.zeros((n_best_tot, n_features, n_features)) + try: + all_best_covariances = np.zeros((n_best_tot, n_features, + n_features)) + except MemoryError: + # The above is too big. Let's try with something much small + # (and less optimal) + all_best_covariances = np.zeros((n_best_tot, n_features, + n_features)) + n_best_tot = 10 + n_best_sub = 2 for i in range(n_subsets): low_bound = i * n_samples_subsets high_bound = low_bound + n_samples_subsets @@ -386,10 +438,11 @@ def fast_mcd(X, support_fraction=None, subset_slice = np.arange(i * n_best_sub, (i + 1) * n_best_sub) all_best_locations[subset_slice] = best_locations_sub all_best_covariances[subset_slice] = best_covariances_sub - ## 2. Pool the candidate supports into a merged set - ## (possibly the full dataset) + # 2. Pool the candidate supports into a merged set + # (possibly the full dataset) n_samples_merged = min(1500, n_samples) - h_merged = np.ceil(n_samples_merged * (n_support / float(n_samples))) + h_merged = int(np.ceil(n_samples_merged * + (n_support / float(n_samples)))) if n_samples > 1500: n_best_merged = 10 else: @@ -403,7 +456,7 @@ def fast_mcd(X, support_fraction=None, select=n_best_merged, cov_computation_method=cov_computation_method, random_state=random_state) - ## 3. Finally get the overall best (locations, covariance) couple + # 3. Finally get the overall best (locations, covariance) couple if n_samples < 1500: # directly get the best couple (location, covariance) location = locations_merged[0] @@ -426,15 +479,15 @@ def fast_mcd(X, support_fraction=None, support = supports_full[0] dist = d[0] elif n_features > 1: - ## 1. Find the 10 best couples (location, covariance) - ## considering two iterations + # 1. Find the 10 best couples (location, covariance) + # considering two iterations n_trials = 30 n_best = 10 locations_best, covariances_best, _, _ = select_candidates( X, n_support, n_trials=n_trials, select=n_best, n_iter=2, cov_computation_method=cov_computation_method, random_state=random_state) - ## 2. Select the best couple on the full dataset amongst the 10 + # 2. Select the best couple on the full dataset amongst the 10 locations_full, covariances_full, supports_full, d = select_candidates( X, n_support, n_trials=(locations_best, covariances_best), select=1, cov_computation_method=cov_computation_method, @@ -448,57 +501,68 @@ def fast_mcd(X, support_fraction=None, class MinCovDet(EmpiricalCovariance): - """Minimum Covariance Determinant (MCD): robust estimator of covariance + """Minimum Covariance Determinant (MCD): robust estimator of covariance. + + The Minimum Covariance Determinant covariance estimator is to be applied + on Gaussian-distributed data, but could still be relevant on data + drawn from a unimodal, symmetric distribution. It is not meant to be used + with multi-modal data (the algorithm used to fit a MinCovDet object is + likely to fail in such a case). + One should consider projection pursuit methods to deal with multi-modal + datasets. Parameters ---------- - store_precision: bool - Specify if the estimated precision is stored - assume_centered: Boolean - If True, the support of robust location and covariance estimates - is computed, and a covariance estimate is recomputed from it, - without centering the data. - Useful to work with data whose mean is significantly equal to - zero but is not exactly zero. - If False, the robust location and covariance are directly computed - with the FastMCD algorithm without additional treatment. - support_fraction: float, 0 < support_fraction < 1 - The proportion of points to be included in the support of the raw - MCD estimate. Default is None, which implies that the minimum - value of support_fraction will be used within the algorithm: - [n_sample + n_features + 1] / 2 - random_state: integer or numpy.RandomState, optional + store_precision : bool + Specify if the estimated precision is stored. + + assume_centered : Boolean + If True, the support of the robust location and the covariance + estimates is computed, and a covariance estimate is recomputed from + it, without centering the data. + Useful to work with data whose mean is significantly equal to + zero but is not exactly zero. + If False, the robust location and covariance are directly computed + with the FastMCD algorithm without additional treatment. + + support_fraction : float, 0 < support_fraction < 1 + The proportion of points to be included in the support of the raw + MCD estimate. Default is None, which implies that the minimum + value of support_fraction will be used within the algorithm: + [n_sample + n_features + 1] / 2 + + random_state : integer or numpy.RandomState, optional The random generator used. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. Attributes ---------- - `raw_location_`: array-like, shape (n_features,) - The raw robust estimated location before correction and reweighting + raw_location_ : array-like, shape (n_features,) + The raw robust estimated location before correction and re-weighting. - `raw_covariance_`: array-like, shape (n_features, n_features) - The raw robust estimated covariance before correction and reweighting + raw_covariance_ : array-like, shape (n_features, n_features) + The raw robust estimated covariance before correction and re-weighting. - `raw_support_`: array-like, shape (n_samples,) + raw_support_ : array-like, shape (n_samples,) A mask of the observations that have been used to compute the raw robust estimates of location and shape, before correction - and reweighting. + and re-weighting. - `location_`: array-like, shape (n_features,) + location_ : array-like, shape (n_features,) Estimated robust location - `covariance_`: array-like, shape (n_features, n_features) + covariance_ : array-like, shape (n_features, n_features) Estimated robust covariance matrix - `precision_`: array-like, shape (n_features, n_features) + precision_ : array-like, shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) - `support_`: array-like, shape (n_samples,) + support_ : array-like, shape (n_samples,) A mask of the observations that have been used to compute the robust estimates of location and shape. - `dist_`: array-like, shape (n_samples,) + dist_ : array-like, shape (n_samples,) Mahalanobis distances of the training set (on which `fit` is called) observations. @@ -506,13 +570,13 @@ class MinCovDet(EmpiricalCovariance): ---------- .. [Rouseeuw1984] `P. J. Rousseeuw. Least median of squares regression. - J. Am Stat Ass, 79:871, 1984.` + J. Am Stat Ass, 79:871, 1984.` .. [Rouseeuw1999] `A Fast Algorithm for the Minimum Covariance Determinant - Estimator, 1999, American Statistical Association and the American - Society for Quality, TECHNOMETRICS` + Estimator, 1999, American Statistical Association and the American + Society for Quality, TECHNOMETRICS` .. [Butler1993] `R. W. Butler, P. L. Davies and M. Jhun, - Asymptotics For The Minimum Covariance Determinant Estimator, - The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400` + Asymptotics For The Minimum Covariance Determinant Estimator, + The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400` """ _nonrobust_covariance = staticmethod(empirical_covariance) @@ -524,36 +588,39 @@ def __init__(self, store_precision=True, assume_centered=False, self.support_fraction = support_fraction self.random_state = random_state - def fit(self, X): + def fit(self, X, y=None): """Fits a Minimum Covariance Determinant with the FastMCD algorithm. Parameters ---------- - X: array-like, shape = [n_samples, n_features] - Training data, where n_samples is the number of samples - and n_features is the number of features. + X : array-like, shape = [n_samples, n_features] + Training data, where n_samples is the number of samples + and n_features is the number of features. + + y : not used, present for API consistence purpose. Returns ------- - self: object - Returns self. + self : object + Returns self. """ - self.random_state = check_random_state(self.random_state) + X = check_array(X) + random_state = check_random_state(self.random_state) n_samples, n_features = X.shape # check that the empirical covariance is full rank if (linalg.svdvals(np.dot(X.T, X)) > 1e-8).sum() != n_features: - warnings.warn("The covariance matrix associated to your dataset " \ - "is not full rank") + warnings.warn("The covariance matrix associated to your dataset " + "is not full rank") # compute and store raw estimates raw_location, raw_covariance, raw_support, raw_dist = fast_mcd( - X, support_fraction=self.support_fraction, - cov_computation_method=self._nonrobust_covariance, - random_state=self.random_state) + X, support_fraction=self.support_fraction, + cov_computation_method=self._nonrobust_covariance, + random_state=random_state) if self.assume_centered: raw_location = np.zeros(n_features) - raw_covariance = self._nonrobust_covariance( - X[raw_support], assume_centered=True) + raw_covariance = self._nonrobust_covariance(X[raw_support], + assume_centered=True) # get precision matrix in an optimized way precision = pinvh(raw_covariance) raw_dist = np.sum(np.dot(X, precision) * X, 1) @@ -565,7 +632,7 @@ def fit(self, X): self.dist_ = raw_dist # obtain consistency at normal models self.correct_covariance(X) - # reweight estimator + # re-weight estimator self.reweight_covariance(X) return self @@ -578,15 +645,15 @@ def correct_covariance(self, data): Parameters ---------- - data: array-like, shape (n_samples, n_features) - The data matrix, with p features and n samples. - The data set must be the one which was used to compute - the raw estimates. + data : array-like, shape (n_samples, n_features) + The data matrix, with p features and n samples. + The data set must be the one which was used to compute + the raw estimates. Returns ------- - covariance_corrected: array-like, shape (n_features, n_features) - Corrected robust covariance estimate. + covariance_corrected : array-like, shape (n_features, n_features) + Corrected robust covariance estimate. """ correction = np.median(self.dist_) / chi2(data.shape[1]).isf(0.5) @@ -595,28 +662,30 @@ def correct_covariance(self, data): return covariance_corrected def reweight_covariance(self, data): - """Reweight raw Minimum Covariance Determinant estimates. + """Re-weight raw Minimum Covariance Determinant estimates. - Reweight observations using Rousseeuw's method (equivalent to + Re-weight observations using Rousseeuw's method (equivalent to deleting outlying observations from the data set before computing location and covariance estimates). [Rouseeuw1984]_ Parameters ---------- - data: array-like, shape (n_samples, n_features) - The data matrix, with p features and n samples. - The data set must be the one which was used to compute - the raw estimates. + data : array-like, shape (n_samples, n_features) + The data matrix, with p features and n samples. + The data set must be the one which was used to compute + the raw estimates. Returns ------- - location_reweighted: array-like, shape (n_features, ) - Reweighted robust location estimate. - covariance_reweighted: array-like, shape (n_features, n_features) - Reweighted robust covariance estimate. - support_reweighted: array-like, type boolean, shape (n_samples,) - A mask of the observations that have been used to compute - the reweighted robust location and covariance estimates. + location_reweighted : array-like, shape (n_features, ) + Re-weighted robust location estimate. + + covariance_reweighted : array-like, shape (n_features, n_features) + Re-weighted robust covariance estimate. + + support_reweighted : array-like, type boolean, shape (n_samples,) + A mask of the observations that have been used to compute + the re-weighted robust location and covariance estimates. """ n_samples, n_features = data.shape @@ -627,7 +696,7 @@ def reweight_covariance(self, data): location_reweighted = data[mask].mean(0) covariance_reweighted = self._nonrobust_covariance( data[mask], assume_centered=self.assume_centered) - support_reweighted = np.zeros(n_samples).astype(bool) + support_reweighted = np.zeros(n_samples, dtype=bool) support_reweighted[mask] = True self._set_covariance(covariance_reweighted) self.location_ = location_reweighted diff --git a/sklearn/covariance/shrunk_covariance_.py b/sklearn/covariance/shrunk_covariance_.py index 4398420fcba7e..ff28d83a29b48 100644 --- a/sklearn/covariance/shrunk_covariance_.py +++ b/sklearn/covariance/shrunk_covariance_.py @@ -10,7 +10,7 @@ # Gael Varoquaux # Virgile Fritsch # -# License: BSD Style. +# License: BSD 3 clause # avoid division truncation from __future__ import division @@ -18,10 +18,10 @@ import numpy as np from .empirical_covariance_ import empirical_covariance, EmpiricalCovariance -from ..utils import array2d +from ..externals.six.moves import xrange +from ..utils import check_array -############################################################################### # ShrunkCovariance estimator def shrunk_covariance(emp_cov, shrinkage=0.1): @@ -29,17 +29,17 @@ def shrunk_covariance(emp_cov, shrinkage=0.1): Parameters ---------- - emp_cov: array-like, shape (n_features, n_features) - Covariance matrix to be shrunk + emp_cov : array-like, shape (n_features, n_features) + Covariance matrix to be shrunk - shrinkage: float, 0 <= shrinkage <= 1 - coefficient in the convex combination used for the computation - of the shrunk estimate. + shrinkage : float, 0 <= shrinkage <= 1 + Coefficient in the convex combination used for the computation + of the shrunk estimate. Returns ------- - shrunk_cov: array-like - shrunk covariance + shrunk_cov : array-like + Shrunk covariance. Notes ----- @@ -51,7 +51,7 @@ def shrunk_covariance(emp_cov, shrinkage=0.1): where mu = trace(cov) / n_features """ - emp_cov = array2d(emp_cov) + emp_cov = check_array(emp_cov) n_features = emp_cov.shape[0] mu = np.trace(emp_cov) / n_features @@ -66,25 +66,31 @@ class ShrunkCovariance(EmpiricalCovariance): Parameters ---------- - store_precision : bool - Specify if the estimated precision is stored + store_precision : boolean, default True + Specify if the estimated precision is stored - shrinkage: float, 0 <= shrinkage <= 1 - coefficient in the convex combination used for the computation - of the shrunk estimate. + shrinkage : float, 0 <= shrinkage <= 1, default 0.1 + Coefficient in the convex combination used for the computation + of the shrunk estimate. + + assume_centered : boolean, default False + If True, data are not centered before computation. + Useful when working with data whose mean is almost, but not exactly + zero. + If False, data are centered before computation. Attributes ---------- - `covariance_` : array-like, shape (n_features, n_features) + covariance_ : array-like, shape (n_features, n_features) Estimated covariance matrix - `precision_` : array-like, shape (n_features, n_features) + precision_ : array-like, shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) - `shrinkage`: float, 0 <= shrinkage <= 1 - coefficient in the convex combination used for the computation - of the shrunk estimate. + `shrinkage` : float, 0 <= shrinkage <= 1 + Coefficient in the convex combination used for the computation + of the shrunk estimate. Notes ----- @@ -102,21 +108,17 @@ def __init__(self, store_precision=True, assume_centered=False, assume_centered=assume_centered) self.shrinkage = shrinkage - def fit(self, X): + def fit(self, X, y=None): """ Fits the shrunk covariance model according to the given training data and parameters. Parameters ---------- X : array-like, shape = [n_samples, n_features] - Training data, where n_samples is the number of samples - and n_features is the number of features. + Training data, where n_samples is the number of samples + and n_features is the number of features. - assume_centered: Boolean - If True, data are not centered before computation. - Useful to work with data whose mean is significantly equal to - zero but is not exactly zero. - If False, data are centered before computation. + y : not used, present for API consistence purpose. Returns ------- @@ -124,21 +126,21 @@ def fit(self, X): Returns self. """ + X = check_array(X) # Not calling the parent object to fit, to avoid a potential # matrix inversion when setting the precision if self.assume_centered: self.location_ = np.zeros(X.shape[1]) else: self.location_ = X.mean(0) - covariance = empirical_covariance(X, - assume_centered=self.assume_centered) + covariance = empirical_covariance( + X, assume_centered=self.assume_centered) covariance = shrunk_covariance(covariance, self.shrinkage) self._set_covariance(covariance) return self -############################################################################### # Ledoit-Wolf estimator def ledoit_wolf_shrinkage(X, assume_centered=False, block_size=1000): @@ -146,23 +148,23 @@ def ledoit_wolf_shrinkage(X, assume_centered=False, block_size=1000): Parameters ---------- - X: array-like, shape (n_samples, n_features) - Data from which to compute the Ledoit-Wolf shrunk covariance shrinkage + X : array-like, shape (n_samples, n_features) + Data from which to compute the Ledoit-Wolf shrunk covariance shrinkage. - assume_centered: Boolean - If True, data are not centered before computation. - Useful to work with data whose mean is significantly equal to - zero but is not exactly zero. - If False, data are centered before computation. + assume_centered : Boolean + If True, data are not centered before computation. + Useful to work with data whose mean is significantly equal to + zero but is not exactly zero. + If False, data are centered before computation. - block_size: int, - Size of the blocks into which the covariance matrix will be split. + block_size : int + Size of the blocks into which the covariance matrix will be split. Returns ------- shrinkage: float - Coefficient in the convex combination used for the computation - of the shrunk estimate. + Coefficient in the convex combination used for the computation + of the shrunk estimate. Notes ----- @@ -180,12 +182,11 @@ def ledoit_wolf_shrinkage(X, assume_centered=False, block_size=1000): return 0. if X.ndim == 1: X = np.reshape(X, (1, -1)) - warnings.warn("Only one sample available. " \ - "You may want to reshape your data array") - n_samples = 1 - n_features = X.size - else: - n_samples, n_features = X.shape + + if X.shape[0] == 1: + warnings.warn("Only one sample available. " + "You may want to reshape your data array") + n_samples, n_features = X.shape # optionaly center data if not assume_centered: @@ -217,8 +218,8 @@ def ledoit_wolf_shrinkage(X, assume_centered=False, block_size=1000): delta_ += np.sum(np.dot(X.T[block_size * n_splits:], X[:, block_size * n_splits:]) ** 2) delta_ /= n_samples ** 2 - beta_ += np.sum(np.dot( - X2.T[block_size * n_splits:], X2[:, block_size * n_splits:])) + beta_ += np.sum(np.dot(X2.T[block_size * n_splits:], + X2[:, block_size * n_splits:])) # use delta_ to compute beta beta = 1. / (n_features * n_samples) * (beta_ / n_samples - delta_) # delta is the sum of the squared coefficients of ( - mu*Id) / p @@ -227,8 +228,7 @@ def ledoit_wolf_shrinkage(X, assume_centered=False, block_size=1000): # get final beta as the min between beta and delta beta = min(beta, delta) # finally get shrinkage - shrinkage = beta / delta - + shrinkage = 0 if beta == 0 else beta / delta return shrinkage @@ -237,29 +237,29 @@ def ledoit_wolf(X, assume_centered=False, block_size=1000): Parameters ---------- - X: array-like, shape (n_samples, n_features) - Data from which to compute the covariance estimate + X : array-like, shape (n_samples, n_features) + Data from which to compute the covariance estimate - assume_centered: Boolean - If True, data are not centered before computation. - Usefull to work with data whose mean is significantly equal to - zero but is not exactly zero. - If False, data are centered before computation. + assume_centered : Boolean + If True, data are not centered before computation. + Useful to work with data whose mean is significantly equal to + zero but is not exactly zero. + If False, data are centered before computation. - block_size: int, - Size of the blocks into which the covariance matrix will be split. - If n_features > `block_size`, an error will be raised since the - shrunk covariance matrix will be considered as too large regarding - the available memory. + block_size : int, + Size of the blocks into which the covariance matrix will be split. + If n_features > `block_size`, an error will be raised since the + shrunk covariance matrix will be considered as too large regarding + the available memory. Returns ------- - shrunk_cov: array-like, shape (n_features, n_features) - Shrunk covariance. + shrunk_cov : array-like, shape (n_features, n_features) + Shrunk covariance. - shrinkage: float - Coefficient in the convex combination used for the computation - of the shrunk estimate. + shrinkage : float + Coefficient in the convex combination used for the computation + of the shrunk estimate. Notes ----- @@ -279,8 +279,8 @@ def ledoit_wolf(X, assume_centered=False, block_size=1000): return np.atleast_2d((X ** 2).mean()), 0. if X.ndim == 1: X = np.reshape(X, (1, -1)) - warnings.warn("Only one sample available. " \ - "You may want to reshape your data array") + warnings.warn("Only one sample available. " + "You may want to reshape your data array") n_samples = 1 n_features = X.size else: @@ -313,13 +313,15 @@ class LedoitWolf(EmpiricalCovariance): Parameters ---------- store_precision : bool - Specify if the estimated precision is stored - assume_centered: bool + Specify if the estimated precision is stored. + + assume_centered : bool If True, data are not centered before computation. Useful when working with data whose mean is almost, but not exactly zero. If False (default), data are centered before computation. - block_size: int, + + block_size : int, Size of the blocks into which the covariance matrix will be split during its Ledoit-Wolf estimation. If n_features > `block_size`, an error will be raised since the @@ -328,16 +330,16 @@ class LedoitWolf(EmpiricalCovariance): Attributes ---------- - `covariance_` : array-like, shape (n_features, n_features) + covariance_ : array-like, shape (n_features, n_features) Estimated covariance matrix - `precision_` : array-like, shape (n_features, n_features) + precision_ : array-like, shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) - `shrinkage_`: float, 0 <= shrinkage <= 1 - coefficient in the convex combination used for the computation - of the shrunk estimate. + shrinkage_ : float, 0 <= shrinkage <= 1 + Coefficient in the convex combination used for the computation + of the shrunk estimate. Notes ----- @@ -347,7 +349,7 @@ class LedoitWolf(EmpiricalCovariance): + shrinkage*mu*np.identity(n_features) where mu = trace(cov) / n_features - and shinkage is given by the Ledoit and Wolf formula (see References) + and shrinkage is given by the Ledoit and Wolf formula (see References) References ---------- @@ -362,15 +364,16 @@ def __init__(self, store_precision=True, assume_centered=False, assume_centered=assume_centered) self.block_size = block_size - def fit(self, X): + def fit(self, X, y=None): """ Fits the Ledoit-Wolf shrunk covariance model according to the given training data and parameters. Parameters ---------- X : array-like, shape = [n_samples, n_features] - Training data, where n_samples is the number of samples - and n_features is the number of features. + Training data, where n_samples is the number of samples + and n_features is the number of features. + y : not used, present for API consistence purpose. Returns ------- @@ -380,19 +383,20 @@ def fit(self, X): """ # Not calling the parent object to fit, to avoid computing the # covariance matrix (and potentially the precision) + X = check_array(X) if self.assume_centered: self.location_ = np.zeros(X.shape[1]) else: self.location_ = X.mean(0) covariance, shrinkage = ledoit_wolf(X - self.location_, - assume_centered=True, block_size=self.block_size) + assume_centered=True, + block_size=self.block_size) self.shrinkage_ = shrinkage self._set_covariance(covariance) return self -############################################################################### # OAS estimator def oas(X, assume_centered=False): @@ -400,10 +404,10 @@ def oas(X, assume_centered=False): Parameters ---------- - X: array-like, shape (n_samples, n_features) - Data from which to compute the covariance estimate + X : array-like, shape (n_samples, n_features) + Data from which to compute the covariance estimate. - assume_centered: boolean + assume_centered : boolean If True, data are not centered before computation. Useful to work with data whose mean is significantly equal to zero but is not exactly zero. @@ -411,12 +415,12 @@ def oas(X, assume_centered=False): Returns ------- - shrunk_cov: array-like, shape (n_features, n_features) - Shrunk covariance + shrunk_cov : array-like, shape (n_features, n_features) + Shrunk covariance. - shrinkage: float - coefficient in the convex combination used for the computation - of the shrunk estimate. + shrinkage : float + Coefficient in the convex combination used for the computation + of the shrunk estimate. Notes ----- @@ -427,6 +431,11 @@ def oas(X, assume_centered=False): where mu = trace(cov) / n_features + The formula we used to implement the OAS + does not correspond to the one given in the article. It has been taken + from the MATLAB program available from the author's webpage + (https://tbayes.eecs.umich.edu/yilun/covestimation). + """ X = np.asarray(X) # for only one feature, the result is the same whatever the shrinkage @@ -436,8 +445,8 @@ def oas(X, assume_centered=False): return np.atleast_2d((X ** 2).mean()), 0. if X.ndim == 1: X = np.reshape(X, (1, -1)) - warnings.warn("Only one sample available. " \ - "You may want to reshape your data array") + warnings.warn("Only one sample available. " + "You may want to reshape your data array") n_samples = 1 n_features = X.size else: @@ -451,7 +460,7 @@ def oas(X, assume_centered=False): num = alpha + mu ** 2 den = (n_samples + 1.) * (alpha - (mu ** 2) / n_features) - shrinkage = min(num / den, 1.) + shrinkage = 1. if den == 0 else min(num / den, 1.) shrunk_cov = (1. - shrinkage) * emp_cov shrunk_cov.flat[::n_features + 1] += shrinkage * mu @@ -459,8 +468,7 @@ def oas(X, assume_centered=False): class OAS(EmpiricalCovariance): - """ - Oracle Approximating Shrinkage Estimator + """Oracle Approximating Shrinkage Estimator OAS is a particular form of shrinkage described in "Shrinkage Algorithms for MMSE Covariance Estimation" @@ -474,6 +482,7 @@ class OAS(EmpiricalCovariance): ---------- store_precision : bool Specify if the estimated precision is stored. + assume_centered: bool If True, data are not centered before computation. Useful when working with data whose mean is almost, but not exactly @@ -482,14 +491,14 @@ class OAS(EmpiricalCovariance): Attributes ---------- - `covariance_` : array-like, shape (n_features, n_features) - Estimated covariance matrix + covariance_ : array-like, shape (n_features, n_features) + Estimated covariance matrix. - `precision_` : array-like, shape (n_features, n_features) + precision_ : array-like, shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) - `shrinkage_`: float, 0 <= shrinkage <= 1 + shrinkage_ : float, 0 <= shrinkage <= 1 coefficient in the convex combination used for the computation of the shrunk estimate. @@ -501,7 +510,7 @@ class OAS(EmpiricalCovariance): + shrinkage*mu*np.identity(n_features) where mu = trace(cov) / n_features - and shinkage is given by the OAS formula (see References) + and shrinkage is given by the OAS formula (see References) References ---------- @@ -509,22 +518,25 @@ class OAS(EmpiricalCovariance): Chen et al., IEEE Trans. on Sign. Proc., Volume 58, Issue 10, October 2010. """ - def fit(self, X): + + def fit(self, X, y=None): """ Fits the Oracle Approximating Shrinkage covariance model according to the given training data and parameters. Parameters ---------- X : array-like, shape = [n_samples, n_features] - Training data, where n_samples is the number of samples - and n_features is the number of features. + Training data, where n_samples is the number of samples + and n_features is the number of features. + y : not used, present for API consistence purpose. Returns ------- - self : object + self: object Returns self. """ + X = check_array(X) # Not calling the parent object to fit, to avoid computing the # covariance matrix (and potentially the precision) if self.assume_centered: diff --git a/sklearn/covariance/tests/test_covariance.py b/sklearn/covariance/tests/test_covariance.py index 508418087fc6e..e2888fe99228e 100644 --- a/sklearn/covariance/tests/test_covariance.py +++ b/sklearn/covariance/tests/test_covariance.py @@ -2,13 +2,15 @@ # Gael Varoquaux # Virgile Fritsch # -# License: BSD Style. - -from numpy.testing import assert_almost_equal, assert_array_almost_equal, \ - assert_equal, assert_raises +# License: BSD 3 clause import numpy as np -import warnings + +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_warns from sklearn import datasets from sklearn.covariance import empirical_covariance, EmpiricalCovariance, \ @@ -42,7 +44,7 @@ def test_covariance(): cov.error_norm, emp_cov, norm='foo') # Mahalanobis distances computation test mahal_dist = cov.mahalanobis(X) - print np.amin(mahal_dist), np.amax(mahal_dist) + print(np.amin(mahal_dist), np.amax(mahal_dist)) assert(np.amin(mahal_dist) > 0) # test with n_features = 1 @@ -55,10 +57,12 @@ def test_covariance(): cov.error_norm(empirical_covariance(X_1d), norm='spectral'), 0) # test with one sample + # FIXME I don't know what this test does X_1sample = np.arange(5) cov = EmpiricalCovariance() - with warnings.catch_warnings(record=True): - cov.fit(X_1sample) + assert_warns(UserWarning, cov.fit, X_1sample) + assert_array_almost_equal(cov.covariance_, + np.zeros(shape=(5, 5), dtype=np.float64)) # test integer type X_integer = np.asarray([[0, 1], [1, 0]]) @@ -68,7 +72,7 @@ def test_covariance(): # test centered case cov = EmpiricalCovariance(assume_centered=True) cov.fit(X) - assert_equal(cov.location_, np.zeros(X.shape[1])) + assert_array_equal(cov.location_, np.zeros(X.shape[1])) def test_shrunk_covariance(): @@ -118,12 +122,12 @@ def test_ledoit_wolf(): assert_almost_equal(ledoit_wolf_shrinkage(X_centered, assume_centered=True), shrinkage_) - assert_almost_equal(ledoit_wolf_shrinkage(X_centered, - assume_centered=True, block_size=6), + assert_almost_equal(ledoit_wolf_shrinkage(X_centered, assume_centered=True, + block_size=6), shrinkage_) # compare shrunk covariance obtained from data and from MLE estimate lw_cov_from_mle, lw_shinkrage_from_mle = ledoit_wolf(X_centered, - assume_centered=True) + assume_centered=True) assert_array_almost_equal(lw_cov_from_mle, lw.covariance_, 4) assert_almost_equal(lw_shinkrage_from_mle, lw.shrinkage_) # compare estimates given by LW and ShrunkCovariance @@ -178,10 +182,12 @@ def test_ledoit_wolf(): assert_array_almost_equal(empirical_covariance(X_1d), lw.covariance_, 4) # test with one sample + # FIXME I don't know what this test does X_1sample = np.arange(5) lw = LedoitWolf() - with warnings.catch_warnings(record=True): - lw.fit(X_1sample) + assert_warns(UserWarning, lw.fit, X_1sample) + assert_array_almost_equal(lw.covariance_, + np.zeros(shape=(5, 5), dtype=np.float64)) # test shrinkage coeff on a simple data set (without saving precision) lw = LedoitWolf(store_precision=False) @@ -250,10 +256,12 @@ def test_oas(): assert_array_almost_equal(empirical_covariance(X_1d), oa.covariance_, 4) # test with one sample + # FIXME I don't know what this test does X_1sample = np.arange(5) oa = OAS() - with warnings.catch_warnings(record=True): - oa.fit(X_1sample) + assert_warns(UserWarning, oa.fit, X_1sample) + assert_array_almost_equal(oa.covariance_, + np.zeros(shape=(5, 5), dtype=np.float64)) # test shrinkage coeff on a simple data set (without saving precision) oa = OAS(store_precision=False) diff --git a/sklearn/covariance/tests/test_graph_lasso.py b/sklearn/covariance/tests/test_graph_lasso.py index 12448f1e17833..50377cc830fc2 100644 --- a/sklearn/covariance/tests/test_graph_lasso.py +++ b/sklearn/covariance/tests/test_graph_lasso.py @@ -1,14 +1,17 @@ """ Test the graph_lasso module. """ import sys -from StringIO import StringIO import numpy as np from scipy import linalg -from sklearn.covariance import graph_lasso, GraphLasso, GraphLassoCV, \ - empirical_covariance +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_array_less + +from sklearn.covariance import (graph_lasso, GraphLasso, GraphLassoCV, + empirical_covariance) from sklearn.datasets.samples_generator import make_sparse_spd_matrix +from sklearn.externals.six.moves import StringIO from sklearn.utils import check_random_state @@ -23,20 +26,33 @@ def test_graph_lasso(random_state=0): X = random_state.multivariate_normal(np.zeros(dim), cov, size=n_samples) emp_cov = empirical_covariance(X) - for alpha in (.1, .01): + for alpha in (0., .01, .1): covs = dict() for method in ('cd', 'lars'): - cov_, _, costs = graph_lasso(emp_cov, alpha=.1, return_costs=True) + cov_, _, costs = graph_lasso(emp_cov, alpha=alpha, + return_costs=True) covs[method] = cov_ costs, dual_gap = np.array(costs).T - # Check that the costs always decrease - np.testing.assert_array_less(np.diff(costs), 0) + # Check that the costs always decrease (doesn't hold if alpha == 0) + if not alpha == 0: + assert_array_less(np.diff(costs), 0) # Check that the 2 approaches give similar results - np.testing.assert_array_almost_equal(covs['cd'], covs['lars']) + assert_array_almost_equal(covs['cd'], covs['lars']) # Smoke test the estimator model = GraphLasso(alpha=.1).fit(X) - np.testing.assert_array_almost_equal(model.covariance_, covs['cd']) + model.score(X) + assert_array_almost_equal(model.covariance_, covs['cd']) + assert_array_almost_equal(model.covariance_, covs['lars']) + + # For a centered matrix, assume_centered could be chosen True or False + # Check that this returns indeed the same result for centered data + Z = X - X.mean(0) + precs = list() + for assume_centered in (False, True): + prec_ = GraphLasso(assume_centered=assume_centered).fit(Z).precision_ + precs.append(prec_) + assert_array_almost_equal(precs[0], precs[1]) def test_graph_lasso_cv(random_state=1): @@ -53,6 +69,9 @@ def test_graph_lasso_cv(random_state=1): try: sys.stdout = StringIO() # We need verbose very high so that Parallel prints on stdout - GraphLassoCV(verbose=100, alphas=3).fit(X) + GraphLassoCV(verbose=100, alphas=3, tol=1e-1).fit(X) finally: sys.stdout = orig_stdout + + # Smoke test with specified alphas + GraphLassoCV(alphas=[0.8, 0.5], tol=1e-1, n_jobs=1).fit(X) diff --git a/sklearn/covariance/tests/test_robust_covariance.py b/sklearn/covariance/tests/test_robust_covariance.py index 75c8e1bff0647..d08c6291a9695 100644 --- a/sklearn/covariance/tests/test_robust_covariance.py +++ b/sklearn/covariance/tests/test_robust_covariance.py @@ -2,13 +2,15 @@ # Gael Varoquaux # Virgile Fritsch # -# License: BSD Style. - -from numpy.testing import assert_almost_equal, assert_array_almost_equal, \ - assert_raises +# License: BSD 3 clause import numpy as np +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.validation import NotFittedError + from sklearn import datasets from sklearn.covariance import empirical_covariance, MinCovDet, \ EllipticEnvelope @@ -40,8 +42,8 @@ def test_mcd(): launch_mcd_on_dataset(500, 1, 100, 0.001, 0.001, 350) -def launch_mcd_on_dataset( - n_samples, n_features, n_outliers, tol_loc, tol_cov, tol_support): +def launch_mcd_on_dataset(n_samples, n_features, n_outliers, tol_loc, tol_cov, + tol_support): rand_gen = np.random.RandomState(0) data = rand_gen.randn(n_samples, n_features) @@ -81,9 +83,8 @@ def test_outlier_detection(): rnd = np.random.RandomState(0) X = rnd.randn(100, 10) clf = EllipticEnvelope(contamination=0.1) - print clf.threshold - assert_raises(Exception, clf.predict, X) - assert_raises(Exception, clf.decision_function, X) + assert_raises(NotFittedError, clf.predict, X) + assert_raises(NotFittedError, clf.decision_function, X) clf.fit(X) y_pred = clf.predict(X) decision = clf.decision_function(X, raw_values=True) diff --git a/sklearn/cross_decomposition/__init__.py b/sklearn/cross_decomposition/__init__.py new file mode 100644 index 0000000000000..836b685163b72 --- /dev/null +++ b/sklearn/cross_decomposition/__init__.py @@ -0,0 +1,2 @@ +from .pls_ import * +from .cca_ import * diff --git a/sklearn/cross_decomposition/cca_.py b/sklearn/cross_decomposition/cca_.py new file mode 100644 index 0000000000000..19ee9cefb9a47 --- /dev/null +++ b/sklearn/cross_decomposition/cca_.py @@ -0,0 +1,105 @@ +from .pls_ import _PLS + +__all__ = ['CCA'] + + +class CCA(_PLS): + """CCA Canonical Correlation Analysis. + + CCA inherits from PLS with mode="B" and deflation_mode="canonical". + + Parameters + ---------- + n_components : int, (default 2). + number of components to keep. + + scale : boolean, (default True) + whether to scale the data? + + max_iter : an integer, (default 500) + the maximum number of iterations of the NIPALS inner loop + + tol : non-negative real, default 1e-06. + the tolerance used in the iterative algorithm + + copy : boolean + Whether the deflation be done on a copy. Let the default value + to True unless you don't care about side effects + + Attributes + ---------- + x_weights_ : array, [p, n_components] + X block weights vectors. + + y_weights_ : array, [q, n_components] + Y block weights vectors. + + x_loadings_ : array, [p, n_components] + X block loadings vectors. + + y_loadings_ : array, [q, n_components] + Y block loadings vectors. + + x_scores_ : array, [n_samples, n_components] + X scores. + + y_scores_ : array, [n_samples, n_components] + Y scores. + + x_rotations_ : array, [p, n_components] + X block to latents rotations. + + y_rotations_ : array, [q, n_components] + Y block to latents rotations. + + n_iter_ : array-like + Number of iterations of the NIPALS inner loop for each + component. + + Notes + ----- + For each component k, find the weights u, v that maximizes + max corr(Xk u, Yk v), such that ``|u| = |v| = 1`` + + Note that it maximizes only the correlations between the scores. + + The residual matrix of X (Xk+1) block is obtained by the deflation on the + current X score: x_score. + + The residual matrix of Y (Yk+1) block is obtained by deflation on the + current Y score. + + Examples + -------- + >>> from sklearn.cross_decomposition import CCA + >>> X = [[0., 0., 1.], [1.,0.,0.], [2.,2.,2.], [3.,5.,4.]] + >>> Y = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]] + >>> cca = CCA(n_components=1) + >>> cca.fit(X, Y) + ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + CCA(copy=True, max_iter=500, n_components=1, scale=True, tol=1e-06) + >>> X_c, Y_c = cca.transform(X, Y) + + References + ---------- + + Jacob A. Wegelin. A survey of Partial Least Squares (PLS) methods, with + emphasis on the two-block case. Technical Report 371, Department of + Statistics, University of Washington, Seattle, 2000. + + In french but still a reference: + Tenenhaus, M. (1998). La regression PLS: theorie et pratique. Paris: + Editions Technic. + + See also + -------- + PLSCanonical + PLSSVD + """ + + def __init__(self, n_components=2, scale=True, + max_iter=500, tol=1e-06, copy=True): + _PLS.__init__(self, n_components=n_components, scale=scale, + deflation_mode="canonical", mode="B", + norm_y_weights=True, algorithm="nipals", + max_iter=max_iter, tol=tol, copy=copy) diff --git a/sklearn/pls.py b/sklearn/cross_decomposition/pls_.py similarity index 65% rename from sklearn/pls.py rename to sklearn/cross_decomposition/pls_.py index 8bc7d16e9514d..d9c1566a7f072 100644 --- a/sklearn/pls.py +++ b/sklearn/cross_decomposition/pls_.py @@ -3,25 +3,30 @@ """ # Author: Edouard Duchesnay -# License: BSD Style. +# License: BSD 3 clause -from .base import BaseEstimator, RegressorMixin, TransformerMixin -from .utils import check_arrays +from ..base import BaseEstimator, RegressorMixin, TransformerMixin +from ..utils import check_array, check_consistent_length +from ..externals import six import warnings +from abc import ABCMeta, abstractmethod import numpy as np from scipy import linalg +from ..utils import arpack +from ..utils.validation import check_is_fitted -__all__ = ['CCA', 'PLSCanonical', 'PLSRegression', 'PLSSVD'] +__all__ = ['PLSCanonical', 'PLSRegression', 'PLSSVD'] def _nipals_twoblocks_inner_loop(X, Y, mode="A", max_iter=500, tol=1e-06, - norm_y_weights=False): - """Inner loop of the iterative NIPALS algorithm. Provides an alternative - to the svd(X'Y); returns the first left and rigth singular vectors of X'Y. - See PLS for the meaning of the parameters. - It is similar to the Power method for determining the eigenvectors and - eigenvalues of a X'Y + norm_y_weights=False): + """Inner loop of the iterative NIPALS algorithm. + + Provides an alternative to the svd(X'Y); returns the first left and right + singular vectors of X'Y. See PLS for the meaning of the parameters. It is + similar to the Power method for determining the eigenvectors and + eigenvalues of a X'Y. """ y_score = Y[:, [0]] x_weights_old = 0 @@ -35,7 +40,7 @@ def _nipals_twoblocks_inner_loop(X, Y, mode="A", max_iter=500, tol=1e-06, X_pinv = linalg.pinv(X) # compute once pinv(X) x_weights = np.dot(X_pinv, y_score) else: # mode A - # Mode A regress each X column on y_score + # Mode A regress each X column on y_score x_weights = np.dot(X.T, y_score) / np.dot(y_score.T, y_score) # 1.2 Normalize u x_weights /= np.sqrt(np.dot(x_weights.T, x_weights)) @@ -63,7 +68,7 @@ def _nipals_twoblocks_inner_loop(X, Y, mode="A", max_iter=500, tol=1e-06, break x_weights_old = x_weights ite += 1 - return x_weights, y_weights + return x_weights, y_weights, ite def _svd_cross_product(X, Y): @@ -76,6 +81,7 @@ def _svd_cross_product(X, Y): def _center_scale_xy(X, Y, scale=True): """ Center X, Y and scale if the scale parameter==True + Returns ------- X, Y, x_mean, y_mean, x_std, y_std @@ -99,39 +105,30 @@ def _center_scale_xy(X, Y, scale=True): return X, Y, x_mean, y_mean, x_std, y_std -class _PLS(BaseEstimator, TransformerMixin, RegressorMixin): +class _PLS(six.with_metaclass(ABCMeta), BaseEstimator, TransformerMixin, + RegressorMixin): """Partial Least Squares (PLS) This class implements the generic PLS algorithm, constructors' parameters allow to obtain a specific implementation such as: - PLS2 regression, i.e., PLS 2 blocks, mode A, with asymmetric deflation - and unnormlized y weights such as defined by [Tenenhaus 1998] p. 132. + and unnormalized y weights such as defined by [Tenenhaus 1998] p. 132. With univariate response it implements PLS1. - - PLS canonical, i.e., PLS 2 blocks, mode A, with symetric deflation and - normlized y weights such as defined by [Tenenhaus 1998] (p. 132) and + - PLS canonical, i.e., PLS 2 blocks, mode A, with symmetric deflation and + normalized y weights such as defined by [Tenenhaus 1998] (p. 132) and [Wegelin et al. 2000]. This parametrization implements the original Wold algorithm. We use the terminology defined by [Wegelin et al. 2000]. This implementation uses the PLS Wold 2 blocks algorithm based on two nested loops: - (i) The outer loop iterate over components. + (i) The outer loop iterate over components. (ii) The inner loop estimates the weights vectors. This can be done with two algo. (a) the inner loop of the original NIPALS algo. or (b) a SVD on residuals cross-covariance matrices. - Parameters - ---------- - X : array-like of predictors, shape = [n_samples, p] - Training vectors, where n_samples in the number of samples and - p is the number of predictors. - - Y : array-like of response, shape = [n_samples, q] - Training vectors, where n_samples in the number of samples and - q is the number of response variables. - n_components : int, number of components to keep. (default 2). scale : boolean, scale data? (default True) @@ -152,38 +149,42 @@ class _PLS(BaseEstimator, TransformerMixin, RegressorMixin): tol : non-negative real, default 1e-06 The tolerance used in the iterative algorithm. - copy : boolean + copy : boolean, default True Whether the deflation should be done on a copy. Let the default value to True unless you don't care about side effects. Attributes ---------- - `x_weights_` : array, [p, n_components] + x_weights_ : array, [p, n_components] X block weights vectors. - `y_weights_` : array, [q, n_components] + y_weights_ : array, [q, n_components] Y block weights vectors. - `x_loadings_` : array, [p, n_components] + x_loadings_ : array, [p, n_components] X block loadings vectors. - `y_loadings_` : array, [q, n_components] + y_loadings_ : array, [q, n_components] Y block loadings vectors. - `x_scores_` : array, [n_samples, n_components] + x_scores_ : array, [n_samples, n_components] X scores. - `y_scores_` : array, [n_samples, n_components] + y_scores_ : array, [n_samples, n_components] Y scores. - `x_rotations_` : array, [p, n_components] + x_rotations_ : array, [p, n_components] X block to latents rotations. - `y_rotations_` : array, [q, n_components] + y_rotations_ : array, [q, n_components] Y block to latents rotations. - coefs: array, [p, q] - The coefficients of the linear model: Y = X coefs + Err + coef_: array, [p, q] + The coefficients of the linear model: ``Y = X coef_ + Err`` + + n_iter_ : array-like + Number of iterations of the NIPALS inner loop for each + component. Not useful if the algorithm given is "svd". References ---------- @@ -204,6 +205,7 @@ class _PLS(BaseEstimator, TransformerMixin, RegressorMixin): PLS_SVD """ + @abstractmethod def __init__(self, n_components=2, scale=True, deflation_mode="regression", mode="A", algorithm="nipals", norm_y_weights=False, max_iter=500, tol=1e-06, copy=True): @@ -218,25 +220,30 @@ def __init__(self, n_components=2, scale=True, deflation_mode="regression", self.copy = copy def fit(self, X, Y): - # copy since this will contains the residuals (deflated) matrices - X, Y = check_arrays(X, Y, dtype=np.float, copy=self.copy, - sparse_format='dense') + """Fit model to data. + + Parameters + ---------- + X : array-like, shape = [n_samples, n_features] + Training vectors, where n_samples in the number of samples and + n_features is the number of predictors. - if X.ndim != 2: - raise ValueError('X must be a 2D array') + Y : array-like of response, shape = [n_samples, n_targets] + Target vectors, where n_samples in the number of samples and + n_targets is the number of response variables. + """ + + # copy since this will contains the residuals (deflated) matrices + check_consistent_length(X, Y) + X = check_array(X, dtype=np.float, copy=self.copy) + Y = check_array(Y, dtype=np.float, copy=self.copy, ensure_2d=False) if Y.ndim == 1: - Y = Y.reshape((Y.size, 1)) - if Y.ndim != 2: - raise ValueError('Y must be a 1D or a 2D array') + Y = Y[:, None] n = X.shape[0] p = X.shape[1] q = Y.shape[1] - if n != Y.shape[0]: - raise ValueError( - 'Incompatible shapes: X has %s samples, while Y ' - 'has %s' % (X.shape[0], Y.shape[0])) if self.n_components < 1 or self.n_components > p: raise ValueError('invalid number of components') if self.algorithm not in ("svd", "nipals"): @@ -245,7 +252,7 @@ def fit(self, X, Y): if self.algorithm == "svd" and self.mode == "B": raise ValueError('Incompatible configuration: mode B is not ' 'implemented with svd algorithm') - if not self.deflation_mode in ["canonical", "regression"]: + if self.deflation_mode not in ["canonical", "regression"]: raise ValueError('The deflation mode is unknown') # Scale (in place) X, Y, self.x_mean_, self.y_mean_, self.x_std_, self.y_std_\ @@ -260,16 +267,18 @@ def fit(self, X, Y): self.y_weights_ = np.zeros((q, self.n_components)) self.x_loadings_ = np.zeros((p, self.n_components)) self.y_loadings_ = np.zeros((q, self.n_components)) + self.n_iter_ = [] # NIPALS algo: outer loop, over components - for k in xrange(self.n_components): + for k in range(self.n_components): #1) weights estimation (inner loop) # ----------------------------------- if self.algorithm == "nipals": - x_weights, y_weights = _nipals_twoblocks_inner_loop( - X=Xk, Y=Yk, mode=self.mode, - max_iter=self.max_iter, tol=self.tol, - norm_y_weights=self.norm_y_weights) + x_weights, y_weights, n_iter_ = \ + _nipals_twoblocks_inner_loop( + X=Xk, Y=Yk, mode=self.mode, max_iter=self.max_iter, + tol=self.tol, norm_y_weights=self.norm_y_weights) + self.n_iter_.append(n_iter_) elif self.algorithm == "svd": x_weights, y_weights = _svd_cross_product(X=Xk, Y=Yk) # compute scores @@ -286,22 +295,22 @@ def fit(self, X, Y): # ---------------------- # Possible memory footprint reduction may done here: in order to # avoid the allocation of a data chunk for the rank-one - # approximations matrix which is then substracted to Xk, we suggest + # approximations matrix which is then subtracted to Xk, we suggest # to perform a column-wise deflation. # # - regress Xk's on x_score x_loadings = np.dot(Xk.T, x_scores) / np.dot(x_scores.T, x_scores) - # - substract rank-one approximations to obtain remainder matrix + # - subtract rank-one approximations to obtain remainder matrix Xk -= np.dot(x_scores, x_loadings.T) if self.deflation_mode == "canonical": - # - regress Yk's on y_score, then substract rank-one approx. - y_loadings = np.dot(Yk.T, y_scores) \ - / np.dot(y_scores.T, y_scores) + # - regress Yk's on y_score, then subtract rank-one approx. + y_loadings = (np.dot(Yk.T, y_scores) + / np.dot(y_scores.T, y_scores)) Yk -= np.dot(y_scores, y_loadings.T) if self.deflation_mode == "regression": - # - regress Yk's on x_score, then substract rank-one approx. - y_loadings = np.dot(Yk.T, x_scores) \ - / np.dot(x_scores.T, x_scores) + # - regress Yk's on x_score, then subtract rank-one approx. + y_loadings = (np.dot(Yk.T, x_scores) + / np.dot(x_scores.T, x_scores)) Yk -= np.dot(x_scores, y_loadings.T) # 3) Store weights, scores and loadings # Notation: self.x_scores_[:, k] = x_scores.ravel() # T @@ -315,11 +324,13 @@ def fit(self, X, Y): # 4) rotations from input space to transformed space (scores) # T = X W(P'W)^-1 = XW* (W* : p x k matrix) # U = Y C(Q'C)^-1 = YC* (W* : q x k matrix) - self.x_rotations_ = np.dot(self.x_weights_, - linalg.inv(np.dot(self.x_loadings_.T, self.x_weights_))) + self.x_rotations_ = np.dot( + self.x_weights_, + linalg.pinv(np.dot(self.x_loadings_.T, self.x_weights_))) if Y.shape[1] > 1: - self.y_rotations_ = np.dot(self.y_weights_, - linalg.inv(np.dot(self.y_loadings_.T, self.y_weights_))) + self.y_rotations_ = np.dot( + self.y_weights_, + linalg.pinv(np.dot(self.y_loadings_.T, self.y_weights_))) else: self.y_rotations_ = np.ones(1) @@ -330,9 +341,9 @@ def fit(self, X, Y): # Then express in function of X # Y = X W(P'W)^-1Q' + Err = XB + Err # => B = W*Q' (p x q) - self.coefs = np.dot(self.x_rotations_, self.y_loadings_.T) - self.coefs = 1. / self.x_std_.reshape((p, 1)) * \ - self.coefs * self.y_std_ + self.coef_ = np.dot(self.x_rotations_, self.y_loadings_.T) + self.coef_ = (1. / self.x_std_.reshape((p, 1)) * self.coef_ * + self.y_std_) return self def transform(self, X, Y=None, copy=True): @@ -348,13 +359,14 @@ def transform(self, X, Y=None, copy=True): Training vectors, where n_samples in the number of samples and q is the number of response variables. - copy : boolean + copy : boolean, default True Whether to copy X and Y, or perform in-place normalization. Returns ------- x_scores if Y is not given, (x_scores, y_scores) otherwise. """ + check_is_fitted(self, 'x_mean_') # Normalize if copy: Xc = (np.asarray(X) - self.x_mean_) / self.x_std_ @@ -385,14 +397,15 @@ def predict(self, X, copy=True): Training vectors, where n_samples in the number of samples and p is the number of predictors. - copy : boolean + copy : boolean, default True Whether to copy X and Y, or perform in-place normalization. Notes ----- - This call require the estimation of a p x q matrix, which may + This call requires the estimation of a p x q matrix, which may be an issue in high dimensional space. """ + check_is_fitted(self, 'x_mean_') # Normalize if copy: Xc = (np.asarray(X) - self.x_mean_) @@ -400,7 +413,7 @@ def predict(self, X, copy=True): X = np.asarray(X) Xc -= self.x_mean_ Xc /= self.x_std_ - Ypred = np.dot(Xc, self.coefs) + Ypred = np.dot(Xc, self.coef_) return Ypred + self.y_mean_ def fit_transform(self, X, y=None, **fit_params): @@ -416,13 +429,14 @@ def fit_transform(self, X, y=None, **fit_params): Training vectors, where n_samples in the number of samples and q is the number of response variables. - copy : boolean + copy : boolean, default True Whether to copy X and Y, or perform in-place normalization. Returns ------- x_scores if Y is not given, (x_scores, y_scores) otherwise. """ + check_is_fitted(self, 'x_mean_') return self.fit(X, y, **fit_params).transform(X, y) @@ -436,14 +450,6 @@ class PLSRegression(_PLS): Parameters ---------- - X : array-like of predictors, shape = [n_samples, p] - Training vectors, where n_samples in the number of samples and - p is the number of predictors. - - Y : array-like of response, shape = [n_samples, q] - Training vectors, where n_samples in the number of samples and - q is the number of response variables. - n_components : int, (default 2) Number of components to keep. @@ -463,32 +469,36 @@ class PLSRegression(_PLS): Attributes ---------- - `x_weights_` : array, [p, n_components] + x_weights_ : array, [p, n_components] X block weights vectors. - `y_weights_` : array, [q, n_components] + y_weights_ : array, [q, n_components] Y block weights vectors. - `x_loadings_` : array, [p, n_components] + x_loadings_ : array, [p, n_components] X block loadings vectors. - `y_loadings_` : array, [q, n_components] + y_loadings_ : array, [q, n_components] Y block loadings vectors. - `x_scores_` : array, [n_samples, n_components] + x_scores_ : array, [n_samples, n_components] X scores. - `y_scores_` : array, [n_samples, n_components] + y_scores_ : array, [n_samples, n_components] Y scores. - `x_rotations_` : array, [p, n_components] + x_rotations_ : array, [p, n_components] X block to latents rotations. - `y_rotations_` : array, [q, n_components] + y_rotations_ : array, [q, n_components] Y block to latents rotations. - coefs: array, [p, q] - The coeficients of the linear model: Y = X coefs + Err + coef_: array, [p, q] + The coefficients of the linear model: ``Y = X coef_ + Err`` + + n_iter_ : array-like + Number of iterations of the NIPALS inner loop for each + component. Notes ----- @@ -514,7 +524,7 @@ class PLSRegression(_PLS): Examples -------- - >>> from sklearn.pls import PLSCanonical, PLSRegression, CCA + >>> from sklearn.cross_decomposition import PLSRegression >>> X = [[0., 0., 1.], [1.,0.,0.], [2.,2.,2.], [2.,5.,4.]] >>> Y = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]] >>> pls2 = PLSRegression(n_components=2) @@ -539,14 +549,21 @@ class PLSRegression(_PLS): def __init__(self, n_components=2, scale=True, max_iter=500, tol=1e-06, copy=True): _PLS.__init__(self, n_components=n_components, scale=scale, - deflation_mode="regression", mode="A", - norm_y_weights=False, - max_iter=max_iter, tol=tol, copy=copy) + deflation_mode="regression", mode="A", + norm_y_weights=False, max_iter=max_iter, tol=tol, + copy=copy) + + @property + def coefs(self): + check_is_fitted(self, 'coef_') + DeprecationWarning("``coefs`` attribute has been deprecated and will be " + "removed in version 0.17. Use ``coef_`` instead") + return self.coef_ class PLSCanonical(_PLS): """ PLSCanonical implements the 2 blocks canonical PLS of the original Wold - algorithm [Tenenhaus 1998] p.204, refered as PLS-C2A in [Wegelin 2000]. + algorithm [Tenenhaus 1998] p.204, referred as PLS-C2A in [Wegelin 2000]. This class inherits from PLS with mode="A" and deflation_mode="canonical", norm_y_weights=True and algorithm="nipals", but svd should provide similar @@ -554,16 +571,6 @@ class PLSCanonical(_PLS): Parameters ---------- - X : array-like of predictors, shape = [n_samples, p] - Training vectors, where n_samples in the number of samples and - p is the number of predictors. - - Y : array-like of response, shape = [n_samples, q] - Training vectors, where n_samples in the number of samples and - q is the number of response variables. - - n_components : int, number of components to keep. (default 2). - scale : boolean, scale data? (default True) algorithm : string, "nipals" or "svd" @@ -581,32 +588,38 @@ class PLSCanonical(_PLS): Whether the deflation should be done on a copy. Let the default value to True unless you don't care about side effect + n_components : int, number of components to keep. (default 2). + Attributes ---------- - `x_weights_` : array, shape = [p, n_components] + x_weights_ : array, shape = [p, n_components] X block weights vectors. - `y_weights_` : array, shape = [q, n_components] + y_weights_ : array, shape = [q, n_components] Y block weights vectors. - `x_loadings_` : array, shape = [p, n_components] + x_loadings_ : array, shape = [p, n_components] X block loadings vectors. - `y_loadings_` : array, shape = [q, n_components] + y_loadings_ : array, shape = [q, n_components] Y block loadings vectors. - `x_scores_` : array, shape = [n_samples, n_components] + x_scores_ : array, shape = [n_samples, n_components] X scores. - `y_scores_` : array, shape = [n_samples, n_components] + y_scores_ : array, shape = [n_samples, n_components] Y scores. - `x_rotations_` : array, shape = [p, n_components] + x_rotations_ : array, shape = [p, n_components] X block to latents rotations. - `y_rotations_` : array, shape = [q, n_components] + y_rotations_ : array, shape = [q, n_components] Y block to latents rotations. + n_iter_ : array-like + Number of iterations of the NIPALS inner loop for each + component. Not useful if the algorithm provided is "svd". + Notes ----- For each component k, find weights u, v that optimize:: @@ -619,20 +632,20 @@ class PLSCanonical(_PLS): current X score: x_score. The residual matrix of Y (Yk+1) block is obtained by deflation on the - current Y score. This performs a canonical symetric version of the PLS - regression. But slightly different than the CCA. This is mode mostly used + current Y score. This performs a canonical symmetric version of the PLS + regression. But slightly different than the CCA. This is mostly used for modeling. This implementation provides the same results that the "plspm" package provided in the R language (R-project), using the function plsca(X, Y). - Results are equal or colinear with the function + Results are equal or collinear with the function ``pls(..., mode = "canonical")`` of the "mixOmics" package. The difference - relies in the fact that mixOmics implmentation does not exactly implement + relies in the fact that mixOmics implementation does not exactly implement the Wold algorithm since it does not normalize y_weights to one. Examples -------- - >>> from sklearn.pls import PLSCanonical, PLSRegression, CCA + >>> from sklearn.cross_decomposition import PLSCanonical >>> X = [[0., 0., 1.], [1.,0.,0.], [2.,2.,2.], [2.,5.,4.]] >>> Y = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]] >>> plsca = PLSCanonical(n_components=2) @@ -661,152 +674,40 @@ class PLSCanonical(_PLS): def __init__(self, n_components=2, scale=True, algorithm="nipals", max_iter=500, tol=1e-06, copy=True): _PLS.__init__(self, n_components=n_components, scale=scale, - deflation_mode="canonical", mode="A", - norm_y_weights=True, algorithm=algorithm, - max_iter=max_iter, tol=tol, copy=copy) - - -class CCA(_PLS): - """CCA Canonical Correlation Analysis. CCA inherits from PLS with - mode="B" and deflation_mode="canonical". - - Parameters - ---------- - X : array-like of predictors, shape = [n_samples, p] - Training vectors, where n_samples in the number of samples and - p is the number of predictors. - - Y : array-like of response, shape = [n_samples, q] - Training vectors, where n_samples in the number of samples and - q is the number of response variables. - - n_components : int, (default 2). - number of components to keep. - - scale : boolean, (default True) - whether to scale the data? - - max_iter : an integer, (default 500) - the maximum number of iterations of the NIPALS inner loop (used - only if algorithm="nipals") - - tol : non-negative real, default 1e-06. - the tolerance used in the iterative algorithm - - copy : boolean - Whether the deflation be done on a copy. Let the default value - to True unless you don't care about side effects - - Attributes - ---------- - `x_weights_` : array, [p, n_components] - X block weights vectors. - - `y_weights_` : array, [q, n_components] - Y block weights vectors. - - `x_loadings_` : array, [p, n_components] - X block loadings vectors. - - `y_loadings_` : array, [q, n_components] - Y block loadings vectors. - - `x_scores_` : array, [n_samples, n_components] - X scores. - - `y_scores_` : array, [n_samples, n_components] - Y scores. - - `x_rotations_` : array, [p, n_components] - X block to latents rotations. - - `y_rotations_` : array, [q, n_components] - Y block to latents rotations. - - Notes - ----- - For each component k, find the weights u, v that maximizes - max corr(Xk u, Yk v), such that ``|u| = |v| = 1`` - - Note that it maximizes only the correlations between the scores. - - The residual matrix of X (Xk+1) block is obtained by the deflation on the - current X score: x_score. - - The residual matrix of Y (Yk+1) block is obtained by deflation on the - current Y score. - - Examples - -------- - >>> from sklearn.pls import PLSCanonical, PLSRegression, CCA - >>> X = [[0., 0., 1.], [1.,0.,0.], [2.,2.,2.], [3.,5.,4.]] - >>> Y = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]] - >>> cca = CCA(n_components=1) - >>> cca.fit(X, Y) - ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE - CCA(copy=True, max_iter=500, n_components=1, scale=True, tol=1e-06) - >>> X_c, Y_c = cca.transform(X, Y) - - References - ---------- - - Jacob A. Wegelin. A survey of Partial Least Squares (PLS) methods, with - emphasis on the two-block case. Technical Report 371, Department of - Statistics, University of Washington, Seattle, 2000. - - In french but still a reference: - Tenenhaus, M. (1998). La regression PLS: theorie et pratique. Paris: - Editions Technic. - - See also - -------- - PLSCanonical - PLSSVD - """ - - def __init__(self, n_components=2, scale=True, - max_iter=500, tol=1e-06, copy=True): - _PLS.__init__(self, n_components=n_components, scale=scale, - deflation_mode="canonical", mode="B", - norm_y_weights=True, algorithm="nipals", - max_iter=max_iter, tol=tol, copy=copy) + deflation_mode="canonical", mode="A", + norm_y_weights=True, algorithm=algorithm, + max_iter=max_iter, tol=tol, copy=copy) class PLSSVD(BaseEstimator, TransformerMixin): """Partial Least Square SVD Simply perform a svd on the crosscovariance matrix: X'Y - The are no iterative deflation here. + There are no iterative deflation here. Parameters ---------- - X : array-like of predictors, shape = [n_samples, p] - Training vector, where n_samples in the number of samples and - p is the number of predictors. X will be centered before any analysis. - - Y : array-like of response, shape = [n_samples, q] - Training vector, where n_samples in the number of samples and - q is the number of response variables. X will be centered before any - analysis. + n_components : int, default 2 + Number of components to keep. - n_components : int, (default 2). - number of components to keep. + scale : boolean, default True + Whether to scale X and Y. - scale : boolean, (default True) - scale X and Y + copy : boolean, default True + Whether to copy X and Y, or perform in-place computations. Attributes ---------- - `x_weights_` : array, [p, n_components] + x_weights_ : array, [p, n_components] X block weights vectors. - `y_weights_` : array, [q, n_components] + y_weights_ : array, [q, n_components] Y block weights vectors. - `x_scores_` : array, [n_samples, n_components] + x_scores_ : array, [n_samples, n_components] X scores. - `y_scores_` : array, [n_samples, n_components] + y_scores_ : array, [n_samples, n_components] Y scores. See also @@ -822,20 +723,12 @@ def __init__(self, n_components=2, scale=True, copy=True): def fit(self, X, Y): # copy since this will contains the centered data - X, Y = check_arrays(X, Y, dtype=np.float, copy=self.copy, - sparse_format='dense') + check_consistent_length(X, Y) + X = check_array(X, dtype=np.float, copy=self.copy) + Y = check_array(Y, dtype=np.float, copy=self.copy) - n = X.shape[0] p = X.shape[1] - if X.ndim != 2: - raise ValueError('X must be a 2D array') - - if n != Y.shape[0]: - raise ValueError( - 'Incompatible shapes: X has %s samples, while Y ' - 'has %s' % (X.shape[0], Y.shape[0])) - if self.n_components < 1 or self.n_components > p: raise ValueError('invalid number of components') @@ -844,7 +737,15 @@ def fit(self, X, Y): _center_scale_xy(X, Y, self.scale) # svd(X'Y) C = np.dot(X.T, Y) - U, s, V = linalg.svd(C, full_matrices=False) + + # The arpack svds solver only works if the number of extracted + # components is smaller than rank(X) - 1. Hence, if we want to extract + # all the components (C.shape[1]), we have to use another one. Else, + # let's use arpacks to compute only the interesting components. + if self.n_components == C.shape[1]: + U, s, V = linalg.svd(C, full_matrices=False) + else: + U, s, V = arpack.svds(C, k=self.n_components) V = V.T self.x_scores_ = np.dot(X, U) self.y_scores_ = np.dot(Y, V) @@ -854,6 +755,7 @@ def fit(self, X, Y): def transform(self, X, Y=None): """Apply the dimension reduction learned on the train data.""" + check_is_fitted(self, 'x_mean_') Xr = (X - self.x_mean_) / self.x_std_ x_scores = np.dot(Xr, self.x_weights_) if Y is not None: diff --git a/sklearn/tests/test_pls.py b/sklearn/cross_decomposition/tests/test_pls.py similarity index 80% rename from sklearn/tests/test_pls.py rename to sklearn/cross_decomposition/tests/test_pls.py index dbfb5b764b144..9efd4732206f9 100644 --- a/sklearn/tests/test_pls.py +++ b/sklearn/cross_decomposition/tests/test_pls.py @@ -1,20 +1,21 @@ import numpy as np -from numpy.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_array_almost_equal from sklearn.datasets import load_linnerud -from sklearn import pls +from sklearn.cross_decomposition import pls_ +from nose.tools import assert_equal def test_pls(): d = load_linnerud() X = d.data Y = d.target - # 1) Canonical (symetric) PLS (PLS 2 blocks canonical mode A) + # 1) Canonical (symmetric) PLS (PLS 2 blocks canonical mode A) # =========================================================== # Compare 2 algo.: nipals vs. svd # ------------------------------ - pls_bynipals = pls.PLSCanonical(n_components=X.shape[1]) + pls_bynipals = pls_.PLSCanonical(n_components=X.shape[1]) pls_bynipals.fit(X, Y) - pls_bysvd = pls.PLSCanonical(algorithm="svd", n_components=X.shape[1]) + pls_bysvd = pls_.PLSCanonical(algorithm="svd", n_components=X.shape[1]) pls_bysvd.fit(X, Y) # check equalities of loading (up to the sign of the second column) assert_array_almost_equal( @@ -29,7 +30,7 @@ def test_pls(): # Check PLS properties (with n_components=X.shape[1]) # --------------------------------------------------- - plsca = pls.PLSCanonical(n_components=X.shape[1]) + plsca = pls_.PLSCanonical(n_components=X.shape[1]) plsca.fit(X, Y) T = plsca.x_scores_ P = plsca.x_loadings_ @@ -56,27 +57,25 @@ def check_ortho(M, err_msg): # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # center scale X, Y Xc, Yc, x_mean, y_mean, x_std, y_std =\ - pls._center_scale_xy(X.copy(), Y.copy(), scale=True) - assert_array_almost_equal(Xc, np.dot(T, P.T), - err_msg="X != TP'") - assert_array_almost_equal(Yc, np.dot(U, Q.T), - err_msg="Y != UQ'") + pls_._center_scale_xy(X.copy(), Y.copy(), scale=True) + assert_array_almost_equal(Xc, np.dot(T, P.T), err_msg="X != TP'") + assert_array_almost_equal(Yc, np.dot(U, Q.T), err_msg="Y != UQ'") # Check that rotations on training data lead to scores # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Xr = plsca.transform(X) assert_array_almost_equal(Xr, plsca.x_scores_, - err_msg="rotation on X failed") + err_msg="rotation on X failed") Xr, Yr = plsca.transform(X, Y) assert_array_almost_equal(Xr, plsca.x_scores_, - err_msg="rotation on X failed") + err_msg="rotation on X failed") assert_array_almost_equal(Yr, plsca.y_scores_, - err_msg="rotation on Y failed") + err_msg="rotation on Y failed") # "Non regression test" on canonical PLS # -------------------------------------- # The results were checked against the R-package plspm - pls_ca = pls.PLSCanonical(n_components=X.shape[1]) + pls_ca = pls_.PLSCanonical(n_components=X.shape[1]) pls_ca.fit(X, Y) x_weights = np.array( @@ -106,7 +105,7 @@ def check_ortho(M, err_msg): # 2) Regression PLS (PLS2): "Non regression test" # =============================================== # The results were checked against the R-packages plspm, misOmics and pls - pls_2 = pls.PLSRegression(n_components=X.shape[1]) + pls_2 = pls_.PLSRegression(n_components=X.shape[1]) pls_2.fit(X, Y) x_weights = np.array( @@ -146,12 +145,12 @@ def check_ortho(M, err_msg): latents = np.array([l1, l1, l2, l2]).T X = latents + np.random.normal(size=4 * n).reshape((n, 4)) Y = latents + np.random.normal(size=4 * n).reshape((n, 4)) - X = np.concatenate((X, - np.random.normal(size=p_noise * n).reshape(n, p_noise)), axis=1) - Y = np.concatenate((Y, - np.random.normal(size=q_noise * n).reshape(n, q_noise)), axis=1) + X = np.concatenate( + (X, np.random.normal(size=p_noise * n).reshape(n, p_noise)), axis=1) + Y = np.concatenate( + (Y, np.random.normal(size=q_noise * n).reshape(n, q_noise)), axis=1) np.random.seed(None) - pls_ca = pls.PLSCanonical(n_components=3) + pls_ca = pls_.PLSCanonical(n_components=3) pls_ca.fit(X, Y) x_weights = np.array( @@ -223,6 +222,32 @@ def check_ortho(M, err_msg): check_ortho(pls_ca.y_scores_, "y scores are not orthogonal") +def test_PLSSVD(): + # Let's check the PLSSVD doesn't return all possible component but just + # the specificied number + d = load_linnerud() + X = d.data + Y = d.target + n_components = 2 + for clf in [pls_.PLSSVD, pls_.PLSRegression, pls_.PLSCanonical]: + pls = clf(n_components=n_components) + pls.fit(X, Y) + assert_equal(n_components, pls.y_scores_.shape[1]) + + +def test_univariate_pls_regression(): + """Ensure 1d Y is correctly interpreted""" + d = load_linnerud() + X = d.data + Y = d.target + + clf = pls_.PLSRegression() + # Compare 1d to column vector + model1 = clf.fit(X, Y[:, 0]).coef_ + model2 = clf.fit(X, Y[:, :1]).coef_ + assert_array_almost_equal(model1, model2) + + def test_scale(): d = load_linnerud() X = d.data @@ -231,7 +256,7 @@ def test_scale(): # causes X[:, -1].std() to be zero X[:, -1] = 1.0 - for clf in [pls.PLSCanonical(), pls.PLSRegression(), - pls.CCA(), pls.PLSSVD()]: + for clf in [pls_.PLSCanonical(), pls_.PLSRegression(), + pls_.PLSSVD()]: clf.set_params(scale=True) clf.fit(X, Y) diff --git a/sklearn/cross_validation.py b/sklearn/cross_validation.py index 6e4783ab2da37..441004648620d 100644 --- a/sklearn/cross_validation.py +++ b/sklearn/cross_validation.py @@ -6,21 +6,31 @@ # Author: Alexandre Gramfort , # Gael Varoquaux , # Olivier Grisel -# License: BSD Style. +# License: BSD 3 clause from __future__ import print_function +from __future__ import division -from itertools import combinations +import warnings +from itertools import chain, combinations from math import ceil, floor, factorial -import operator +import numbers +import time +from abc import ABCMeta, abstractmethod import numpy as np import scipy.sparse as sp from .base import is_classifier, clone -from .utils import check_arrays, check_random_state -from .utils.fixes import unique -from .externals.joblib import Parallel, delayed +from .utils import indexable, check_random_state, safe_indexing +from .utils.validation import (_is_arraylike, _num_samples, + check_array, column_or_1d) +from .utils.multiclass import type_of_target +from .externals.joblib import Parallel, delayed, logger +from .externals.six import with_metaclass +from .externals.six.moves import zip +from .metrics.scorer import check_scoring +from .utils.fixes import bincount __all__ = ['Bootstrap', 'KFold', @@ -31,19 +41,85 @@ 'ShuffleSplit', 'StratifiedKFold', 'StratifiedShuffleSplit', + 'PredefinedSplit', 'check_cv', 'cross_val_score', + 'cross_val_predict', 'permutation_test_score', 'train_test_split'] -class LeaveOneOut(object): +class _PartitionIterator(with_metaclass(ABCMeta)): + """Base class for CV iterators where train_mask = ~test_mask + + Implementations must define `_iter_test_masks` or `_iter_test_indices`. + + Parameters + ---------- + n : int + Total number of elements in dataset. + """ + + def __init__(self, n, indices=None): + if indices is None: + indices = True + else: + warnings.warn("The indices parameter is deprecated and will be " + "removed (assumed True) in 0.17", DeprecationWarning, + stacklevel=1) + if abs(n - int(n)) >= np.finfo('f').eps: + raise ValueError("n must be an integer") + self.n = int(n) + self._indices = indices + + @property + def indices(self): + warnings.warn("The indices attribute is deprecated and will be " + "removed (assumed True) in 0.17", DeprecationWarning, + stacklevel=1) + return self._indices + + def __iter__(self): + indices = self._indices + if indices: + ind = np.arange(self.n) + for test_index in self._iter_test_masks(): + train_index = np.logical_not(test_index) + if indices: + train_index = ind[train_index] + test_index = ind[test_index] + yield train_index, test_index + + # Since subclasses must implement either _iter_test_masks or + # _iter_test_indices, neither can be abstract. + def _iter_test_masks(self): + """Generates boolean masks corresponding to test sets. + + By default, delegates to _iter_test_indices() + """ + for test_index in self._iter_test_indices(): + test_mask = self._empty_mask() + test_mask[test_index] = True + yield test_mask + + def _iter_test_indices(self): + """Generates integer indices corresponding to test sets.""" + raise NotImplementedError + + def _empty_mask(self): + return np.zeros(self.n, dtype=np.bool) + + +class LeaveOneOut(_PartitionIterator): """Leave-One-Out cross validation iterator. Provides train/test indices to split data in train test sets. Each sample is used once as a test set (singleton) while the remaining samples form the training set. + Note: ``LeaveOneOut(n)`` is equivalent to ``KFold(n, n_folds=n)`` and + ``LeavePOut(n, p=1)``. + Due to the high number of test sets (which is the same as the number of samples) this cross validation method can be very costly. For large datasets one should favor KFold, StratifiedKFold or @@ -51,13 +127,8 @@ class LeaveOneOut(object): Parameters ---------- - n: int - Total number of elements - - indices: boolean, optional (default True) - Return train/test split as arrays of indices, rather than a boolean - mask array. Integer indices are required when dealing with sparse - matrices, since those cannot be indexed by boolean masks. + n : int + Total number of elements in dataset. Examples -------- @@ -70,36 +141,23 @@ class LeaveOneOut(object): >>> print(loo) sklearn.cross_validation.LeaveOneOut(n=2) >>> for train_index, test_index in loo: - ... print("TRAIN: %s TEST: %s" % (train_index, test_index)) + ... print("TRAIN:", train_index, "TEST:", test_index) ... X_train, X_test = X[train_index], X[test_index] ... y_train, y_test = y[train_index], y[test_index] - ... print("%s %s %s %s" % (X_train, X_test, y_train, y_test)) + ... print(X_train, X_test, y_train, y_test) TRAIN: [1] TEST: [0] [[3 4]] [[1 2]] [2] [1] TRAIN: [0] TEST: [1] [[1 2]] [[3 4]] [1] [2] See also - ======== + -------- LeaveOneLabelOut for splitting the data according to explicit, domain-specific stratification of the dataset. """ - def __init__(self, n, indices=True): - self.n = n - self.indices = indices - - def __iter__(self): - n = self.n - for i in xrange(n): - test_index = np.zeros(n, dtype=np.bool) - test_index[i] = True - train_index = np.logical_not(test_index) - if self.indices: - ind = np.arange(n) - train_index = ind[train_index] - test_index = ind[test_index] - yield train_index, test_index + def _iter_test_indices(self): + return range(self.n) def __repr__(self): return '%s.%s(n=%i)' % ( @@ -112,29 +170,27 @@ def __len__(self): return self.n -class LeavePOut(object): +class LeavePOut(_PartitionIterator): """Leave-P-Out cross validation iterator - Provides train/test indices to split data in train test sets. The - test set is built using p samples while the remaining samples form - the training set. + Provides train/test indices to split data in train test sets. This results + in testing on all distinct samples of size p, while the remaining n - p + samples form the training set in each iteration. + + Note: ``LeavePOut(n, p)`` is NOT equivalent to ``KFold(n, n_folds=n // p)`` + which creates non-overlapping test sets. - Due to the high number of iterations which grows with the number of - samples this cross validation method can be very costly. For large - datasets one should favor KFold, StratifiedKFold or ShuffleSplit. + Due to the high number of iterations which grows combinatorically with the + number of samples this cross validation method can be very costly. For + large datasets one should favor KFold, StratifiedKFold or ShuffleSplit. Parameters ---------- - n: int - Total number of elements - - p: int - Size of the test sets + n : int + Total number of elements in dataset. - indices: boolean, optional (default True) - Return train/test split as arrays of indices, rather than a boolean - mask array. Integer indices are required when dealing with sparse - matrices, since those cannot be indexed by boolean masks. + p : int + Size of the test sets. Examples -------- @@ -147,7 +203,7 @@ class LeavePOut(object): >>> print(lpo) sklearn.cross_validation.LeavePOut(n=4, p=2) >>> for train_index, test_index in lpo: - ... print("TRAIN: %s TEST: %s" % (train_index, test_index)) + ... print("TRAIN:", train_index, "TEST:", test_index) ... X_train, X_test = X[train_index], X[test_index] ... y_train, y_test = y[train_index], y[test_index] TRAIN: [2 3] TEST: [0 1] @@ -158,24 +214,13 @@ class LeavePOut(object): TRAIN: [0 1] TEST: [2 3] """ - def __init__(self, n, p, indices=True): - self.n = n + def __init__(self, n, p, indices=None): + super(LeavePOut, self).__init__(n, indices) self.p = p - self.indices = indices - def __iter__(self): - n = self.n - p = self.p - comb = combinations(range(n), p) - for idx in comb: - test_index = np.zeros(n, dtype=np.bool) - test_index[np.array(idx)] = True - train_index = np.logical_not(test_index) - if self.indices: - ind = np.arange(n) - train_index = ind[train_index] - test_index = ind[test_index] - yield train_index, test_index + def _iter_test_indices(self): + for comb in combinations(range(self.n), self.p): + yield np.array(comb) def __repr__(self): return '%s.%s(n=%i, p=%i)' % ( @@ -187,19 +232,39 @@ def __repr__(self): def __len__(self): return int(factorial(self.n) / factorial(self.n - self.p) - / factorial(self.p)) + / factorial(self.p)) + +class _BaseKFold(with_metaclass(ABCMeta, _PartitionIterator)): + """Base class to validate KFold approaches""" -def _validate_kfold(k, n_samples): - if k <= 0: - raise ValueError("Cannot have number of folds k below 1.") - if k > n_samples: - raise ValueError("Cannot have number of folds k=%d greater than" - " the number of samples: %d." % (k, n_samples)) + @abstractmethod + def __init__(self, n, n_folds, indices, shuffle, random_state): + super(_BaseKFold, self).__init__(n, indices) + if abs(n_folds - int(n_folds)) >= np.finfo('f').eps: + raise ValueError("n_folds must be an integer") + self.n_folds = n_folds = int(n_folds) + + if n_folds <= 1: + raise ValueError( + "k-fold cross validation requires at least one" + " train / test split by setting n_folds=2 or more," + " got n_folds={0}.".format(n_folds)) + if n_folds > self.n: + raise ValueError( + ("Cannot have number of folds n_folds={0} greater" + " than the number of samples: {1}.").format(n_folds, n)) + + if not isinstance(shuffle, bool): + raise TypeError("shuffle must be True or False;" + " got {0}".format(shuffle)) + self.shuffle = shuffle + self.random_state = random_state -class KFold(object): - """K-Folds cross validation iterator + +class KFold(_BaseKFold): + """K-Folds cross validation iterator. Provides train/test indices to split data in train test sets. Split dataset into k consecutive folds (without shuffling). @@ -209,35 +274,32 @@ class KFold(object): Parameters ---------- - n: int - Total number of elements - - k: int - Number of folds + n : int + Total number of elements. - indices: boolean, optional (default True) - Return train/test split as arrays of indices, rather than a boolean - mask array. Integer indices are required when dealing with sparse - matrices, since those cannot be indexed by boolean masks. + n_folds : int, default=3 + Number of folds. Must be at least 2. - shuffle: boolean, optional - whether to shuffle the data before splitting into batches + shuffle : boolean, optional + Whether to shuffle the data before splitting into batches. - random_state: int or RandomState - Pseudo number generator state used for random sampling. + random_state : None, int or RandomState + Pseudo-random number generator state used for random + sampling. If None, use default numpy RNG for shuffling Examples -------- >>> from sklearn import cross_validation >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) >>> y = np.array([1, 2, 3, 4]) - >>> kf = cross_validation.KFold(4, k=2) + >>> kf = cross_validation.KFold(4, n_folds=2) >>> len(kf) 2 - >>> print(kf) - sklearn.cross_validation.KFold(n=4, k=2) + >>> print(kf) # doctest: +NORMALIZE_WHITESPACE + sklearn.cross_validation.KFold(n=4, n_folds=2, shuffle=False, + random_state=None) >>> for train_index, test_index in kf: - ... print("TRAIN: %s TEST: %s" % (train_index, test_index)) + ... print("TRAIN:", train_index, "TEST:", test_index) ... X_train, X_test = X[train_index], X[test_index] ... y_train, y_test = y[train_index], y[test_index] TRAIN: [2 3] TEST: [0 1] @@ -245,8 +307,8 @@ class KFold(object): Notes ----- - All the folds have size trunc(n_samples / n_folds), the last one has the - complementary. + The first n % n_folds folds have size n // n_folds + 1, other folds have + size n // n_folds. See also -------- @@ -255,84 +317,77 @@ class KFold(object): classification tasks). """ - def __init__(self, n, k, indices=True, shuffle=False, random_state=None): - _validate_kfold(k, n) - random_state = check_random_state(random_state) - - if abs(n - int(n)) >= np.finfo('f').eps: - raise ValueError("n must be an integer") - self.n = int(n) - if abs(k - int(k)) >= np.finfo('f').eps: - raise ValueError("k must be an integer") - self.k = int(k) - self.indices = indices + def __init__(self, n, n_folds=3, indices=None, shuffle=False, + random_state=None): + super(KFold, self).__init__(n, n_folds, indices, shuffle, random_state) self.idxs = np.arange(n) if shuffle: - random_state.shuffle(self.idxs) + rng = check_random_state(self.random_state) + rng.shuffle(self.idxs) - def __iter__(self): + def _iter_test_indices(self): n = self.n - k = self.k - fold_size = n // k - - for i in xrange(k): - test_index = np.zeros(n, dtype=np.bool) - if i < k - 1: - test_index[self.idxs[i * fold_size:(i + 1) * fold_size]] = True - else: - test_index[self.idxs[i * fold_size:]] = True - train_index = np.logical_not(test_index) - if self.indices: - train_index = self.idxs[train_index] - test_index = self.idxs[test_index] - yield train_index, test_index + n_folds = self.n_folds + fold_sizes = (n // n_folds) * np.ones(n_folds, dtype=np.int) + fold_sizes[:n % n_folds] += 1 + current = 0 + for fold_size in fold_sizes: + start, stop = current, current + fold_size + yield self.idxs[start:stop] + current = stop def __repr__(self): - return '%s.%s(n=%i, k=%i)' % ( + return '%s.%s(n=%i, n_folds=%i, shuffle=%s, random_state=%s)' % ( self.__class__.__module__, self.__class__.__name__, self.n, - self.k, + self.n_folds, + self.shuffle, + self.random_state, ) def __len__(self): - return self.k + return self.n_folds -class StratifiedKFold(object): +class StratifiedKFold(_BaseKFold): """Stratified K-Folds cross validation iterator Provides train/test indices to split data in train test sets. - This cross-validation object is a variation of KFold, which + This cross-validation object is a variation of KFold that returns stratified folds. The folds are made by preserving the percentage of samples for each class. Parameters ---------- - y: array, [n_samples] - Samples to split in K folds + y : array-like, [n_samples] + Samples to split in K folds. - k: int - Number of folds + n_folds : int, default=3 + Number of folds. Must be at least 2. - indices: boolean, optional (default True) - Return train/test split as arrays of indices, rather than a boolean - mask array. Integer indices are required when dealing with sparse - matrices, since those cannot be indexed by boolean masks. + shuffle : boolean, optional + Whether to shuffle each stratification of the data before splitting + into batches. + + random_state : None, int or RandomState + Pseudo-random number generator state used for random + sampling. If None, use default numpy RNG for shuffling Examples -------- >>> from sklearn import cross_validation >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) >>> y = np.array([0, 0, 1, 1]) - >>> skf = cross_validation.StratifiedKFold(y, k=2) + >>> skf = cross_validation.StratifiedKFold(y, n_folds=2) >>> len(skf) 2 - >>> print(skf) - sklearn.cross_validation.StratifiedKFold(labels=[0 0 1 1], k=2) + >>> print(skf) # doctest: +NORMALIZE_WHITESPACE + sklearn.cross_validation.StratifiedKFold(labels=[0 0 1 1], n_folds=2, + shuffle=False, random_state=None) >>> for train_index, test_index in skf: - ... print("TRAIN: %s TEST: %s" % (train_index, test_index)) + ... print("TRAIN:", train_index, "TEST:", test_index) ... X_train, X_test = X[train_index], X[test_index] ... y_train, y_test = y[train_index], y[test_index] TRAIN: [1 3] TEST: [0 2] @@ -342,52 +397,73 @@ class StratifiedKFold(object): ----- All the folds have size trunc(n_samples / n_folds), the last one has the complementary. + """ - def __init__(self, y, k, indices=True): + def __init__(self, y, n_folds=3, indices=None, shuffle=False, + random_state=None): + super(StratifiedKFold, self).__init__( + len(y), n_folds, indices, shuffle, random_state) y = np.asarray(y) - n = y.shape[0] - _validate_kfold(k, n) - _, y_sorted = unique(y, return_inverse=True) - min_labels = np.min(np.bincount(y_sorted)) - if k > min_labels: - raise ValueError("The least populated class in y has only %d" - " members, which is too few. The minimum" - " number of labels for any class cannot" - " be less than k=%d." % (min_labels, k)) + n_samples = y.shape[0] + unique_labels, y_inversed = np.unique(y, return_inverse=True) + label_counts = bincount(y_inversed) + min_labels = np.min(label_counts) + if self.n_folds > min_labels: + warnings.warn(("The least populated class in y has only %d" + " members, which is too few. The minimum" + " number of labels for any class cannot" + " be less than n_folds=%d." + % (min_labels, self.n_folds)), Warning) + + # don't want to use the same seed in each label's shuffle + if self.shuffle: + rng = check_random_state(self.random_state) + else: + rng = self.random_state + + # pre-assign each sample to a test fold index using individual KFold + # splitting strategies for each label so as to respect the + # balance of labels + per_label_cvs = [ + KFold(max(c, self.n_folds), self.n_folds, shuffle=self.shuffle, + random_state=rng) for c in label_counts] + test_folds = np.zeros(n_samples, dtype=np.int) + for test_fold_idx, per_label_splits in enumerate(zip(*per_label_cvs)): + for label, (_, test_split) in zip(unique_labels, per_label_splits): + label_test_folds = test_folds[y == label] + # the test split can be too big because we used + # KFold(max(c, self.n_folds), self.n_folds) instead of + # KFold(c, self.n_folds) to make it possible to not crash even + # if the data is not 100% stratifiable for all the labels + # (we use a warning instead of raising an exception) + # If this is the case, let's trim it: + test_split = test_split[test_split < len(label_test_folds)] + label_test_folds[test_split] = test_fold_idx + test_folds[y == label] = label_test_folds + + self.test_folds = test_folds self.y = y - self.k = k - self.indices = indices - def __iter__(self): - y = self.y.copy() - k = self.k - n = y.size - idx = np.argsort(y) - - for i in xrange(k): - test_index = np.zeros(n, dtype=np.bool) - test_index[idx[i::k]] = True - train_index = np.logical_not(test_index) - if self.indices: - ind = np.arange(n) - train_index = ind[train_index] - test_index = ind[test_index] - yield train_index, test_index + def _iter_test_masks(self): + for i in range(self.n_folds): + yield self.test_folds == i def __repr__(self): - return '%s.%s(labels=%s, k=%i)' % ( + return '%s.%s(labels=%s, n_folds=%i, shuffle=%s, random_state=%s)' % ( self.__class__.__module__, self.__class__.__name__, self.y, - self.k, + self.n_folds, + self.shuffle, + self.random_state, ) def __len__(self): - return self.k + return self.n_folds -class LeaveOneLabelOut(object): +class LeaveOneLabelOut(_PartitionIterator): """Leave-One-Label_Out cross-validation iterator Provides train/test indices to split data according to a third-party @@ -403,11 +479,6 @@ class LeaveOneLabelOut(object): Arbitrary domain-specific stratification of the data to be used to draw the splits. - indices: boolean, optional (default True) - Return train/test split as arrays of indices, rather than a boolean - mask array. Integer indices are required when dealing with sparse - matrices, since those cannot be indexed by boolean masks. - Examples -------- >>> from sklearn import cross_validation @@ -420,10 +491,10 @@ class LeaveOneLabelOut(object): >>> print(lol) sklearn.cross_validation.LeaveOneLabelOut(labels=[1 1 2 2]) >>> for train_index, test_index in lol: - ... print("TRAIN: %s TEST: %s" % (train_index, test_index)) + ... print("TRAIN:", train_index, "TEST:", test_index) ... X_train, X_test = X[train_index], X[test_index] ... y_train, y_test = y[train_index], y[test_index] - ... print("%s %s %s %s" % (X_train, X_test, y_train, y_test)) + ... print(X_train, X_test, y_train, y_test) TRAIN: [2 3] TEST: [0 1] [[5 6] [7 8]] [[1 2] @@ -435,23 +506,16 @@ class LeaveOneLabelOut(object): """ - def __init__(self, labels, indices=True): - self.labels = labels - self.n_unique_labels = unique(labels).size - self.indices = indices + def __init__(self, labels, indices=None): + super(LeaveOneLabelOut, self).__init__(len(labels), indices) + # We make a copy of labels to avoid side-effects during iteration + self.labels = np.array(labels, copy=True) + self.unique_labels = np.unique(labels) + self.n_unique_labels = len(self.unique_labels) - def __iter__(self): - # We make a copy here to avoid side-effects during iteration - labels = np.array(self.labels, copy=True) - for i in unique(labels): - test_index = np.zeros(len(labels), dtype=np.bool) - test_index[labels == i] = True - train_index = np.logical_not(test_index) - if self.indices: - ind = np.arange(len(labels)) - train_index = ind[train_index] - test_index = ind[test_index] - yield train_index, test_index + def _iter_test_masks(self): + for i in self.unique_labels: + yield self.labels == i def __repr__(self): return '%s.%s(labels=%s)' % ( @@ -464,7 +528,7 @@ def __len__(self): return self.n_unique_labels -class LeavePLabelOut(object): +class LeavePLabelOut(_PartitionIterator): """Leave-P-Label_Out cross-validation iterator Provides train/test indices to split data according to a third-party @@ -488,11 +552,6 @@ class LeavePLabelOut(object): p : int Number of samples to leave out in the test split. - indices: boolean, optional (default True) - Return train/test split as arrays of indices, rather than a boolean - mask array. Integer indices are required when dealing with sparse - matrices, since those cannot be indexed by boolean masks. - Examples -------- >>> from sklearn import cross_validation @@ -505,10 +564,10 @@ class LeavePLabelOut(object): >>> print(lpl) sklearn.cross_validation.LeavePLabelOut(labels=[1 2 3], p=2) >>> for train_index, test_index in lpl: - ... print("TRAIN: %s TEST: %s" % (train_index, test_index)) + ... print("TRAIN:", train_index, "TEST:", test_index) ... X_train, X_test = X[train_index], X[test_index] ... y_train, y_test = y[train_index], y[test_index] - ... print("%s %s %s %s" % (X_train, X_test, y_train, y_test)) + ... print(X_train, X_test, y_train, y_test) TRAIN: [2] TEST: [0 1] [[5 6]] [[1 2] [3 4]] [1] [1 2] @@ -520,30 +579,22 @@ class LeavePLabelOut(object): [5 6]] [1] [2 1] """ - def __init__(self, labels, p, indices=True): - self.labels = labels - self.unique_labels = unique(self.labels) - self.n_unique_labels = self.unique_labels.size + def __init__(self, labels, p, indices=None): + # We make a copy of labels to avoid side-effects during iteration + super(LeavePLabelOut, self).__init__(len(labels), indices) + self.labels = np.array(labels, copy=True) + self.unique_labels = np.unique(labels) + self.n_unique_labels = len(self.unique_labels) self.p = p - self.indices = indices - def __iter__(self): - # We make a copy here to avoid side-effects during iteration - labels = np.array(self.labels, copy=True) - unique_labels = unique(labels) + def _iter_test_masks(self): comb = combinations(range(self.n_unique_labels), self.p) - for idx in comb: - test_index = np.zeros(labels.size, dtype=np.bool) + test_index = self._empty_mask() idx = np.array(idx) - for l in unique_labels[idx]: - test_index[labels == l] = True - train_index = np.logical_not(test_index) - if self.indices: - ind = np.arange(labels.size) - train_index = ind[train_index] - test_index = ind[test_index] - yield train_index, test_index + for l in self.unique_labels[idx]: + test_index[self.labels == l] = True + yield test_index def __repr__(self): return '%s.%s(labels=%s, p=%s)' % ( @@ -555,15 +606,15 @@ def __repr__(self): def __len__(self): return int(factorial(self.n_unique_labels) / - factorial(self.n_unique_labels - self.p) / - factorial(self.p)) + factorial(self.n_unique_labels - self.p) / + factorial(self.p)) class Bootstrap(object): """Random sampling with replacement cross-validation iterator Provides train/test indices to split data in train test sets - while resampling the input n_bootstraps times: each time a new + while resampling the input n_iter times: each time a new random split of the data is performed and then samples are drawn (with replacement) on each side of the split to build the training and test sets. @@ -581,7 +632,7 @@ class Bootstrap(object): n : int Total number of elements in the dataset. - n_bootstraps : int (default is 3) + n_iter : int (default is 3) Number of bootstrapping iterations train_size : int or float (default is 0.5) @@ -612,9 +663,9 @@ class Bootstrap(object): >>> len(bs) 3 >>> print(bs) - Bootstrap(9, n_bootstraps=3, train_size=5, test_size=4, random_state=0) + Bootstrap(9, n_iter=3, train_size=5, test_size=4, random_state=0) >>> for train_index, test_index in bs: - ... print("TRAIN: %s TEST: %s" % (train_index, test_index)) + ... print("TRAIN:", train_index, "TEST:", test_index) ... TRAIN: [1 8 7 7 8] TEST: [0 3 0 5] TRAIN: [5 4 2 4 2] TEST: [6 7 1 0] @@ -628,15 +679,20 @@ class Bootstrap(object): # Static marker to be able to introspect the CV type indices = True - def __init__(self, n, n_bootstraps=3, train_size=.5, test_size=None, + def __init__(self, n, n_iter=3, train_size=.5, test_size=None, random_state=None): + # See, e.g., http://youtu.be/BzHz0J9a6k0?t=9m38s for a motivation + # behind this deprecation + warnings.warn("Bootstrap will no longer be supported as a " + + "cross-validation method as of version 0.15 and " + + "will be removed in 0.17", DeprecationWarning) self.n = n - self.n_bootstraps = n_bootstraps - if (isinstance(train_size, (float, np.floating)) and train_size >= 0.0 - and train_size <= 1.0): - self.train_size = ceil(train_size * n) - elif isinstance(train_size, (int, np.integer)): + self.n_iter = n_iter + if isinstance(train_size, numbers.Integral): self.train_size = train_size + elif (isinstance(train_size, numbers.Real) and train_size >= 0.0 + and train_size <= 1.0): + self.train_size = int(ceil(train_size * n)) else: raise ValueError("Invalid value for train_size: %r" % train_size) @@ -644,24 +700,24 @@ def __init__(self, n, n_bootstraps=3, train_size=.5, test_size=None, raise ValueError("train_size=%d should not be larger than n=%d" % (self.train_size, n)) - if (isinstance(test_size, (float, np.floating)) and test_size >= 0.0 - and test_size <= 1.0): - self.test_size = ceil(test_size * n) - elif isinstance(test_size, (int, np.integer)): + if isinstance(test_size, numbers.Integral): self.test_size = test_size + elif isinstance(test_size, numbers.Real) and 0.0 <= test_size <= 1.0: + self.test_size = int(ceil(test_size * n)) elif test_size is None: self.test_size = self.n - self.train_size else: raise ValueError("Invalid value for test_size: %r" % test_size) - if self.test_size > n: - raise ValueError("test_size=%d should not be larger than n=%d" % - (self.test_size, n)) + if self.test_size > n - self.train_size: + raise ValueError(("test_size + train_size=%d, should not be " + + "larger than n=%d") % + (self.test_size + self.train_size, n)) self.random_state = random_state def __iter__(self): rng = check_random_state(self.random_state) - for i in range(self.n_bootstraps): + for i in range(self.n_iter): # random partition permutation = rng.permutation(self.n) ind_train = permutation[:self.train_size] @@ -672,25 +728,73 @@ def __iter__(self): train = rng.randint(0, self.train_size, size=(self.train_size,)) test = rng.randint(0, self.test_size, - size=(self.test_size,)) + size=(self.test_size,)) yield ind_train[train], ind_test[test] def __repr__(self): - return ('%s(%d, n_bootstraps=%d, train_size=%d, test_size=%d, ' - 'random_state=%d)' % ( + return ('%s(%d, n_iter=%d, train_size=%d, test_size=%d, ' + 'random_state=%s)' % ( self.__class__.__name__, self.n, - self.n_bootstraps, + self.n_iter, self.train_size, self.test_size, self.random_state, )) def __len__(self): - return self.n_bootstraps + return self.n_iter -class ShuffleSplit(object): +class BaseShuffleSplit(with_metaclass(ABCMeta)): + """Base class for ShuffleSplit and StratifiedShuffleSplit""" + + def __init__(self, n, n_iter=10, test_size=0.1, train_size=None, + indices=None, random_state=None, n_iterations=None): + if indices is None: + indices = True + else: + warnings.warn("The indices parameter is deprecated and will be " + "removed (assumed True) in 0.17", DeprecationWarning) + self.n = n + self.n_iter = n_iter + if n_iterations is not None: # pragma: no cover + warnings.warn("n_iterations was renamed to n_iter for consistency " + " and will be removed in 0.16.") + self.n_iter = n_iterations + self.test_size = test_size + self.train_size = train_size + self.random_state = random_state + self._indices = indices + self.n_train, self.n_test = _validate_shuffle_split(n, + test_size, + train_size) + + @property + def indices(self): + warnings.warn("The indices attribute is deprecated and will be " + "removed (assumed True) in 0.17", DeprecationWarning, + stacklevel=1) + return self._indices + + def __iter__(self): + if self._indices: + for train, test in self._iter_indices(): + yield train, test + return + for train, test in self._iter_indices(): + train_m = np.zeros(self.n, dtype=bool) + test_m = np.zeros(self.n, dtype=bool) + train_m[train] = True + test_m[test] = True + yield train_m, test_m + + @abstractmethod + def _iter_indices(self): + """Generate (train, test) indices""" + + +class ShuffleSplit(BaseShuffleSplit): """Random permutation cross-validation iterator. Yields indices to split data into training and test sets. @@ -704,24 +808,20 @@ class ShuffleSplit(object): n : int Total number of elements in the dataset. - n_iterations : int (default 10) + n_iter : int (default 10) Number of re-shuffling & splitting iterations. - test_size : float (default 0.1) or int + test_size : float (default 0.1), int, or None If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If - int, represents the absolute number of test samples. + int, represents the absolute number of test samples. If None, + the value is automatically set to the complement of the train size. train_size : float, int, or None (default is None) If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, - the value is automatically set to the complement of the test fraction. - - indices : boolean, optional (default True) - Return train/test split as arrays of indices, rather than a boolean - mask array. Integer indices are required when dealing with sparse - matrices, since those cannot be indexed by boolean masks. + the value is automatically set to the complement of the test size. random_state : int or RandomState Pseudo-random number generator state used for random sampling. @@ -729,24 +829,24 @@ class ShuffleSplit(object): Examples -------- >>> from sklearn import cross_validation - >>> rs = cross_validation.ShuffleSplit(4, n_iterations=3, + >>> rs = cross_validation.ShuffleSplit(4, n_iter=3, ... test_size=.25, random_state=0) >>> len(rs) 3 >>> print(rs) ... # doctest: +ELLIPSIS - ShuffleSplit(4, n_iterations=3, test_size=0.25, indices=True, ...) + ShuffleSplit(4, n_iter=3, test_size=0.25, ...) >>> for train_index, test_index in rs: - ... print("TRAIN: %s TEST: %s" % (train_index, test_index)) + ... print("TRAIN:", train_index, "TEST:", test_index) ... TRAIN: [3 1 0] TEST: [2] TRAIN: [2 1 3] TEST: [0] TRAIN: [0 2 1] TEST: [3] - >>> rs = cross_validation.ShuffleSplit(4, n_iterations=3, + >>> rs = cross_validation.ShuffleSplit(4, n_iter=3, ... train_size=0.5, test_size=.25, random_state=0) >>> for train_index, test_index in rs: - ... print("TRAIN: %s TEST: %s" % (train_index, test_index)) + ... print("TRAIN:", train_index, "TEST:", test_index) ... TRAIN: [3 1] TEST: [2] TRAIN: [2 1] TEST: [0] @@ -757,64 +857,47 @@ class ShuffleSplit(object): Bootstrap: cross-validation using re-sampling with replacement. """ - def __init__(self, n, n_iterations=10, test_size=0.1, - train_size=None, indices=True, random_state=None): - self.n = n - self.n_iterations = n_iterations - self.test_size = test_size - self.train_size = train_size - self.random_state = random_state - self.indices = indices - - self.n_train, self.n_test = _validate_shuffle_split(n, - test_size, - train_size) - - def __iter__(self): + def _iter_indices(self): rng = check_random_state(self.random_state) - for i in range(self.n_iterations): + for i in range(self.n_iter): # random partition permutation = rng.permutation(self.n) ind_test = permutation[:self.n_test] ind_train = permutation[self.n_test:self.n_test + self.n_train] - - if self.indices: - yield ind_train, ind_test - else: - train_mask = np.zeros(self.n, dtype=np.bool) - train_mask[ind_train] = True - test_mask = np.zeros(self.n, dtype=np.bool) - test_mask[ind_test] = True - yield train_mask, test_mask + yield ind_train, ind_test def __repr__(self): - return ('%s(%d, n_iterations=%d, test_size=%s, indices=%s, ' + return ('%s(%d, n_iter=%d, test_size=%s, ' 'random_state=%s)' % ( self.__class__.__name__, self.n, - self.n_iterations, + self.n_iter, str(self.test_size), - self.indices, self.random_state, )) def __len__(self): - return self.n_iterations + return self.n_iter def _validate_shuffle_split(n, test_size, train_size): - if np.asarray(test_size).dtype.kind == 'f': - if test_size >= 1.: - raise ValueError( - 'test_size=%f should be smaller ' - 'than 1.0 or be an integer' % test_size) - elif np.asarray(test_size).dtype.kind == 'i': - if test_size >= n: - raise ValueError( - 'test_size=%d should be smaller ' - 'than the number of samples %d' % (test_size, n)) - else: - raise ValueError("Invalid value for test_size: %r" % test_size) + if test_size is None and train_size is None: + raise ValueError( + 'test_size and train_size can not both be None') + + if test_size is not None: + if np.asarray(test_size).dtype.kind == 'f': + if test_size >= 1.: + raise ValueError( + 'test_size=%f should be smaller ' + 'than 1.0 or be an integer' % test_size) + elif np.asarray(test_size).dtype.kind == 'i': + if test_size >= n: + raise ValueError( + 'test_size=%d should be smaller ' + 'than the number of samples %d' % (test_size, n)) + else: + raise ValueError("Invalid value for test_size: %r" % test_size) if train_size is not None: if np.asarray(train_size).dtype.kind == 'f': @@ -837,7 +920,7 @@ def _validate_shuffle_split(n, test_size, train_size): if np.asarray(test_size).dtype.kind == 'f': n_test = ceil(test_size * n) - else: + elif np.asarray(test_size).dtype.kind == 'i': n_test = float(test_size) if train_size is None: @@ -848,40 +931,19 @@ def _validate_shuffle_split(n, test_size, train_size): else: n_train = float(train_size) + if test_size is None: + n_test = n - n_train + if n_train + n_test > n: raise ValueError('The sum of train_size and test_size = %d, ' 'should be smaller than the number of ' 'samples %d. Reduce test_size and/or ' 'train_size.' % (n_train + n_test, n)) - return n_train, n_test - - -def _validate_stratified_shuffle_split(y, test_size, train_size): - classes, y = unique(y, return_inverse=True) - n_cls = classes.shape[0] - - if np.min(np.bincount(y)) < 2: - raise ValueError("The least populated class in y has only 1" - " member, which is too few. The minimum" - " number of labels for any class cannot" - " be less than 2.") - - n_train, n_test = _validate_shuffle_split(y.size, test_size, train_size) + return int(n_train), int(n_test) - if n_train < n_cls: - raise ValueError('The train_size = %d should be greater or ' - 'equal to the number of classes = %d' % - (n_train, n_cls)) - if n_test < n_cls: - raise ValueError('The test_size = %d should be greater or ' - 'equal to the number of classes = %d' % - (n_test, n_cls)) - return n_train, n_test, classes, y - - -class StratifiedShuffleSplit(object): +class StratifiedShuffleSplit(BaseShuffleSplit): """Stratified ShuffleSplit cross validation iterator Provides train/test indices to split data in train test sets. @@ -896,27 +958,26 @@ class StratifiedShuffleSplit(object): Parameters ---------- - y: array, [n_samples] + y : array, [n_samples] Labels of samples. - n_iterations : int (default 10) + n_iter : int (default 10) Number of re-shuffling & splitting iterations. - test_size : float (default 0.1) or int + test_size : float (default 0.1), int, or None If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If - int, represents the absolute number of test samples. + int, represents the absolute number of test samples. If None, + the value is automatically set to the complement of the train size. train_size : float, int, or None (default is None) If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, - the value is automatically set to the complement of the test fraction. + the value is automatically set to the complement of the test size. - indices: boolean, optional (default True) - Return train/test split as arrays of indices, rather than a boolean - mask array. Integer indices are required when dealing with sparse - matrices, since those cannot be indexed by boolean masks. + random_state : int or RandomState + Pseudo-random number generator state used for random sampling. Examples -------- @@ -927,9 +988,9 @@ class StratifiedShuffleSplit(object): >>> len(sss) 3 >>> print(sss) # doctest: +ELLIPSIS - StratifiedShuffleSplit(labels=[0 0 1 1], n_iterations=3, ...) + StratifiedShuffleSplit(labels=[0 0 1 1], n_iter=3, ...) >>> for train_index, test_index in sss: - ... print("TRAIN: %s TEST: %s" % (train_index, test_index)) + ... print("TRAIN:", train_index, "TEST:", test_index) ... X_train, X_test = X[train_index], X[test_index] ... y_train, y_test = y[train_index], y[test_index] TRAIN: [1 2] TEST: [3 0] @@ -937,164 +998,562 @@ class StratifiedShuffleSplit(object): TRAIN: [0 2] TEST: [3 1] """ - def __init__(self, y, n_iterations=10, test_size=0.1, - train_size=None, indices=True, random_state=None): + def __init__(self, y, n_iter=10, test_size=0.1, train_size=None, + indices=None, random_state=None, n_iterations=None): + super(StratifiedShuffleSplit, self).__init__( + len(y), n_iter, test_size, train_size, indices, random_state, + n_iterations) self.y = np.array(y) - self.n = self.y.size - self.n_iterations = n_iterations - self.test_size = test_size - self.train_size = train_size - self.random_state = random_state - self.indices = indices - self.n_train, self.n_test, self.classes, self.y_indices = \ - _validate_stratified_shuffle_split(y, test_size, train_size) + self.classes, self.y_indices = np.unique(y, return_inverse=True) + n_cls = self.classes.shape[0] - def __iter__(self): + if np.min(bincount(self.y_indices)) < 2: + raise ValueError("The least populated class in y has only 1" + " member, which is too few. The minimum" + " number of labels for any class cannot" + " be less than 2.") + + if self.n_train < n_cls: + raise ValueError('The train_size = %d should be greater or ' + 'equal to the number of classes = %d' % + (self.n_train, n_cls)) + if self.n_test < n_cls: + raise ValueError('The test_size = %d should be greater or ' + 'equal to the number of classes = %d' % + (self.n_test, n_cls)) + + def _iter_indices(self): rng = check_random_state(self.random_state) - cls_count = np.bincount(self.y_indices) + cls_count = bincount(self.y_indices) p_i = cls_count / float(self.n) n_i = np.round(self.n_train * p_i).astype(int) t_i = np.minimum(cls_count - n_i, np.round(self.n_test * p_i).astype(int)) - for n in range(self.n_iterations): + for n in range(self.n_iter): train = [] test = [] for i, cls in enumerate(self.classes): - permutation = rng.permutation(n_i[i] + t_i[i]) + permutation = rng.permutation(cls_count[i]) cls_i = np.where((self.y == cls))[0][permutation] train.extend(cls_i[:n_i[i]]) test.extend(cls_i[n_i[i]:n_i[i] + t_i[i]]) + # Because of rounding issues (as n_train and n_test are not + # dividers of the number of elements per class), we may end + # up here with less samples in train and test than asked for. + if len(train) < self.n_train or len(test) < self.n_test: + # We complete by affecting randomly the missing indexes + missing_idx = np.where(bincount(train + test, + minlength=len(self.y)) == 0, + )[0] + missing_idx = rng.permutation(missing_idx) + train.extend(missing_idx[:(self.n_train - len(train))]) + test.extend(missing_idx[-(self.n_test - len(test)):]) + train = rng.permutation(train) test = rng.permutation(test) - if self.indices: - yield train, test - else: - train_m = np.zeros(self.n, dtype=bool) - test_m = np.zeros(self.n, dtype=bool) - train_m[train] = True - test_m[test] = True - - yield train_m, test_m + yield train, test def __repr__(self): - return ('%s(labels=%s, n_iterations=%d, test_size=%s, indices=%s, ' + return ('%s(labels=%s, n_iter=%d, test_size=%s, ' 'random_state=%s)' % ( self.__class__.__name__, self.y, - self.n_iterations, + self.n_iter, str(self.test_size), - self.indices, self.random_state, )) def __len__(self): - return self.n_iterations + return self.n_iter + + +class PredefinedSplit(_PartitionIterator): + """Predefined split cross validation iterator + + Splits the data into training/test set folds according to a predefined + scheme. Each sample can be assigned to at most one test set fold, as + specified by the user through the ``test_fold`` parameter. + + Parameters + ---------- + test_fold : "array-like, shape (n_samples,) + test_fold[i] gives the test set fold of sample i. A value of -1 + indicates that the corresponding sample is not part of any test set + folds, but will instead always be put into the training fold. + + Examples + -------- + >>> from sklearn.cross_validation import PredefinedSplit + >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) + >>> y = np.array([0, 0, 1, 1]) + >>> ps = PredefinedSplit(test_fold=[0, 1, -1, 1]) + >>> len(ps) + 2 + >>> print(ps) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + sklearn.cross_validation.PredefinedSplit(test_fold=[ 0 1 -1 1]) + >>> for train_index, test_index in ps: + ... print("TRAIN:", train_index, "TEST:", test_index) + ... X_train, X_test = X[train_index], X[test_index] + ... y_train, y_test = y[train_index], y[test_index] + TRAIN: [1 2 3] TEST: [0] + TRAIN: [0 2] TEST: [1 3] + """ + + def __init__(self, test_fold, indices=None): + super(PredefinedSplit, self).__init__(len(test_fold), indices) + self.test_fold = np.array(test_fold, dtype=np.int) + self.test_fold = column_or_1d(self.test_fold) + self.unique_folds = np.unique(self.test_fold) + self.unique_folds = self.unique_folds[self.unique_folds != -1] + + def _iter_test_indices(self): + for f in self.unique_folds: + yield np.where(self.test_fold == f)[0] + + def __repr__(self): + return '%s.%s(test_fold=%s)' % ( + self.__class__.__module__, + self.__class__.__name__, + self.test_fold) + + def __len__(self): + return len(self.unique_folds) ############################################################################## +def _index_param_value(X, v, indices): + """Private helper function for parameter value indexing.""" + if not _is_arraylike(v) or _num_samples(v) != _num_samples(X): + # pass through: skip indexing + return v + if sp.issparse(v): + v = v.tocsr() + return safe_indexing(v, indices) -def _cross_val_score(estimator, X, y, score_func, train, test, verbose, - fit_params): - """Inner loop for cross validation""" - n_samples = X.shape[0] if sp.issparse(X) else len(X) - fit_params = dict([(k, np.asarray(v)[train] - if hasattr(v, '__len__') and len(v) == n_samples else v) - for k, v in fit_params.items()]) - if y is None: - estimator.fit(X[train], **fit_params) - if score_func is None: - score = estimator.score(X[test]) - else: - score = score_func(X[test]) + +def cross_val_predict(estimator, X, y=None, cv=None, n_jobs=1, + verbose=0, fit_params=None, pre_dispatch='2*n_jobs'): + """Generate cross-validated estimates for each input data point + + Parameters + ---------- + estimator : estimator object implementing 'fit' and 'predict' + The object to use to fit the data. + + X : array-like + The data to fit. Can be, for example a list, or an array at least 2d. + + y : array-like, optional, default: None + The target variable to try to predict in the case of + supervised learning. + + cv : cross-validation generator or int, optional, default: None + A cross-validation generator to use. If int, determines + the number of folds in StratifiedKFold if y is binary + or multiclass and estimator is a classifier, or the number + of folds in KFold otherwise. If None, it is equivalent to cv=3. + This generator must include all elements in the test set exactly once. + Otherwise, a ValueError is raised. + + n_jobs : integer, optional + The number of CPUs to use to do the computation. -1 means + 'all CPUs'. + + verbose : integer, optional + The verbosity level. + + fit_params : dict, optional + Parameters to pass to the fit method of the estimator. + + pre_dispatch : int, or string, optional + Controls the number of jobs that get dispatched during parallel + execution. Reducing this number can be useful to avoid an + explosion of memory consumption when more jobs get dispatched + than CPUs can process. This parameter can be: + + - None, in which case all the jobs are immediately + created and spawned. Use this for lightweight and + fast-running jobs, to avoid delays due to on-demand + spawning of the jobs + + - An int, giving the exact number of total jobs that are + spawned + + - A string, giving an expression as a function of n_jobs, + as in '2*n_jobs' + + Returns + ------- + preds : ndarray + This is the result of calling 'predict' + """ + X, y = indexable(X, y) + + cv = _check_cv(cv, X, y, classifier=is_classifier(estimator)) + # We clone the estimator to make sure that all the folds are + # independent, and that it is pickle-able. + parallel = Parallel(n_jobs=n_jobs, verbose=verbose, + pre_dispatch=pre_dispatch) + preds_blocks = parallel(delayed(_fit_and_predict)(clone(estimator), X, y, + train, test, verbose, + fit_params) + for train, test in cv) + p = np.concatenate([p for p, _ in preds_blocks]) + locs = np.concatenate([loc for _, loc in preds_blocks]) + if not _check_is_partition(locs, X.shape[0]): + raise ValueError('cross_val_predict only works for partitions') + preds = p.copy() + preds[locs] = p + return preds + + +def _fit_and_predict(estimator, X, y, train, test, verbose, fit_params): + """Fit estimator and predict values for a given dataset split. + + Parameters + ---------- + estimator : estimator object implementing 'fit' and 'predict' + The object to use to fit the data. + + X : array-like of shape at least 2D + The data to fit. + + y : array-like, optional, default: None + The target variable to try to predict in the case of + supervised learning. + + train : array-like, shape (n_train_samples,) + Indices of training samples. + + test : array-like, shape (n_test_samples,) + Indices of test samples. + + verbose : integer + The verbosity level. + + fit_params : dict or None + Parameters that will be passed to ``estimator.fit``. + + Returns + ------- + preds : sequence + Result of calling 'estimator.predict' + + test : array-like + This is the value of the test parameter + """ + # Adjust length of sample weights + fit_params = fit_params if fit_params is not None else {} + fit_params = dict([(k, _index_param_value(X, v, train)) + for k, v in fit_params.items()]) + + X_train, y_train = _safe_split(estimator, X, y, train) + X_test, _ = _safe_split(estimator, X, y, test, train) + + if y_train is None: + estimator.fit(X_train, **fit_params) else: - estimator.fit(X[train], y[train], **fit_params) - if score_func is None: - score = estimator.score(X[test], y[test]) - else: - score = score_func(y[test], estimator.predict(X[test])) - if verbose > 1: - print("score: %f" % score) - return score + estimator.fit(X_train, y_train, **fit_params) + preds = estimator.predict(X_test) + return preds, test + + +def _check_is_partition(locs, n): + """Check whether locs is a reordering of the array np.arange(n) + + Parameters + ---------- + locs : ndarray + integer array to test + n : int + number of expected elements + + Returns + ------- + is_partition : bool + True iff sorted(locs) is range(n) + """ + if len(locs) != n: + return False + hit = np.zeros(n, bool) + hit[locs] = True + if not np.all(hit): + return False + return True -def cross_val_score(estimator, X, y=None, score_func=None, cv=None, n_jobs=1, - verbose=0, fit_params=None): +def cross_val_score(estimator, X, y=None, scoring=None, cv=None, n_jobs=1, + verbose=0, fit_params=None, pre_dispatch='2*n_jobs'): """Evaluate a score by cross-validation Parameters ---------- - estimator: estimator object implementing 'fit' - The object to use to fit the data + estimator : estimator object implementing 'fit' + The object to use to fit the data. - X: array-like of shape at least 2D - The data to fit. + X : array-like + The data to fit. Can be, for example a list, or an array at least 2d. - y: array-like, optional + y : array-like, optional, default: None The target variable to try to predict in the case of supervised learning. - score_func: callable, optional - callable, has priority over the score function in the estimator. - In a non-supervised setting, where y is None, it takes the test - data (X_test) as its only argument. In a supervised setting it takes - the test target (y_true) and the test prediction (y_pred) as arguments. + scoring : string, callable or None, optional, default: None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. - cv: cross-validation generator, optional - A cross-validation generator. If None, a 3-fold cross - validation is used or 3-fold stratified cross-validation - when y is supplied and estimator is a classifier. + cv : cross-validation generator or int, optional, default: None + A cross-validation generator to use. If int, determines + the number of folds in StratifiedKFold if y is binary + or multiclass and estimator is a classifier, or the number + of folds in KFold otherwise. If None, it is equivalent to cv=3. - n_jobs: integer, optional + n_jobs : integer, optional The number of CPUs to use to do the computation. -1 means 'all CPUs'. - verbose: integer, optional - The verbosity level + verbose : integer, optional + The verbosity level. fit_params : dict, optional - parameters to pass to the fit method + Parameters to pass to the fit method of the estimator. + + pre_dispatch : int, or string, optional + Controls the number of jobs that get dispatched during parallel + execution. Reducing this number can be useful to avoid an + explosion of memory consumption when more jobs get dispatched + than CPUs can process. This parameter can be: + + - None, in which case all the jobs are immediately + created and spawned. Use this for lightweight and + fast-running jobs, to avoid delays due to on-demand + spawning of the jobs + + - An int, giving the exact number of total jobs that are + spawned + + - A string, giving an expression as a function of n_jobs, + as in '2*n_jobs' + + Returns + ------- + scores : array of float, shape=(len(list(cv)),) + Array of scores of the estimator for each run of the cross validation. """ - X, y = check_arrays(X, y, sparse_format='csr') - cv = check_cv(cv, X, y, classifier=is_classifier(estimator)) - if score_func is None: - if not hasattr(estimator, 'score'): - raise TypeError( - "If no score_func is specified, the estimator passed " - "should have a 'score' method. The estimator %s " - "does not." % estimator) + X, y = indexable(X, y) + + cv = _check_cv(cv, X, y, classifier=is_classifier(estimator)) + scorer = check_scoring(estimator, scoring=scoring) # We clone the estimator to make sure that all the folds are # independent, and that it is pickle-able. + parallel = Parallel(n_jobs=n_jobs, verbose=verbose, + pre_dispatch=pre_dispatch) + scores = parallel(delayed(_fit_and_score)(clone(estimator), X, y, scorer, + train, test, verbose, None, + fit_params) + for train, test in cv) + return np.array(scores)[:, 0] + + +class FitFailedWarning(RuntimeWarning): + pass + + +def _fit_and_score(estimator, X, y, scorer, train, test, verbose, + parameters, fit_params, return_train_score=False, + return_parameters=False, error_score='raise'): + """Fit estimator and compute scores for a given dataset split. + + Parameters + ---------- + estimator : estimator object implementing 'fit' + The object to use to fit the data. + + X : array-like of shape at least 2D + The data to fit. + + y : array-like, optional, default: None + The target variable to try to predict in the case of + supervised learning. + + scorer : callable + A scorer callable object / function with signature + ``scorer(estimator, X, y)``. + + train : array-like, shape (n_train_samples,) + Indices of training samples. + + test : array-like, shape (n_test_samples,) + Indices of test samples. + + verbose : integer + The verbosity level. + + error_score : 'raise' (default) or numeric + Value to assign to the score if an error occurs in estimator fitting. + If set to 'raise', the error is raised. If a numeric value is given, + FitFailedWarning is raised. This parameter does not affect the refit + step, which will always raise the error. + + parameters : dict or None + Parameters to be set on the estimator. + + fit_params : dict or None + Parameters that will be passed to ``estimator.fit``. + + return_train_score : boolean, optional, default: False + Compute and return score on training set. + + return_parameters : boolean, optional, default: False + Return parameters that has been used for the estimator. + + Returns + ------- + train_score : float, optional + Score on training set, returned only if `return_train_score` is `True`. + + test_score : float + Score on test set. + + n_test_samples : int + Number of test samples. + + scoring_time : float + Time spent for fitting and scoring in seconds. + + parameters : dict or None, optional + The parameters that have been evaluated. + """ + if verbose > 1: + if parameters is None: + msg = "no parameters to be set" + else: + msg = '%s' % (', '.join('%s=%s' % (k, v) + for k, v in parameters.items())) + print("[CV] %s %s" % (msg, (64 - len(msg)) * '.')) + + # Adjust length of sample weights fit_params = fit_params if fit_params is not None else {} - scores = Parallel(n_jobs=n_jobs, verbose=verbose)( - delayed(_cross_val_score)(clone(estimator), X, y, score_func, - train, test, verbose, fit_params) - for train, test in cv) - return np.array(scores) + fit_params = dict([(k, _index_param_value(X, v, train)) + for k, v in fit_params.items()]) + + if parameters is not None: + estimator.set_params(**parameters) + + start_time = time.time() + + X_train, y_train = _safe_split(estimator, X, y, train) + X_test, y_test = _safe_split(estimator, X, y, test, train) + + try: + if y_train is None: + estimator.fit(X_train, **fit_params) + else: + estimator.fit(X_train, y_train, **fit_params) + + except Exception as e: + if error_score == 'raise': + raise + elif isinstance(error_score, numbers.Number): + test_score = error_score + if return_train_score: + train_score = error_score + warnings.warn("Classifier fit failed. The score on this train-test" + " partition for these parameters will be set to %f. " + "Details: \n%r" % (error_score, e), FitFailedWarning) + else: + raise ValueError("error_score must be the string 'raise' or a" + " numeric value. (Hint: if using 'raise', please" + " make sure that it has been spelled correctly.)" + ) + + else: + test_score = _score(estimator, X_test, y_test, scorer) + if return_train_score: + train_score = _score(estimator, X_train, y_train, scorer) + + scoring_time = time.time() - start_time + + if verbose > 2: + msg += ", score=%f" % test_score + if verbose > 1: + end_msg = "%s -%s" % (msg, logger.short_format_time(scoring_time)) + print("[CV] %s %s" % ((64 - len(end_msg)) * '.', end_msg)) + + ret = [train_score] if return_train_score else [] + ret.extend([test_score, _num_samples(X_test), scoring_time]) + if return_parameters: + ret.append(parameters) + return ret + + +def _safe_split(estimator, X, y, indices, train_indices=None): + """Create subset of dataset and properly handle kernels.""" + if hasattr(estimator, 'kernel') and callable(estimator.kernel): + # cannot compute the kernel values with custom function + raise ValueError("Cannot use a custom kernel function. " + "Precompute the kernel matrix instead.") + + if not hasattr(X, "shape"): + if getattr(estimator, "_pairwise", False): + raise ValueError("Precomputed kernels or affinity matrices have " + "to be passed as arrays or sparse matrices.") + X_subset = [X[idx] for idx in indices] + else: + if getattr(estimator, "_pairwise", False): + # X is a precomputed square kernel matrix + if X.shape[0] != X.shape[1]: + raise ValueError("X should be a square kernel matrix") + if train_indices is None: + X_subset = X[np.ix_(indices, indices)] + else: + X_subset = X[np.ix_(indices, train_indices)] + else: + X_subset = safe_indexing(X, indices) + + if y is not None: + y_subset = safe_indexing(y, indices) + else: + y_subset = None + + return X_subset, y_subset -def _permutation_test_score(estimator, X, y, cv, score_func): - """Auxilary function for permutation_test_score""" +def _score(estimator, X_test, y_test, scorer): + """Compute the score of an estimator on a given test set.""" + if y_test is None: + score = scorer(estimator, X_test) + else: + score = scorer(estimator, X_test, y_test) + if not isinstance(score, numbers.Number): + raise ValueError("scoring must return a number, got %s (%s) instead." + % (str(score), type(score))) + return score + + +def _permutation_test_score(estimator, X, y, cv, scorer): + """Auxiliary function for permutation_test_score""" avg_score = [] for train, test in cv: - avg_score.append(score_func(y[test], - estimator.fit(X[train], - y[train]).predict(X[test]))) + estimator.fit(X[train], y[train]) + avg_score.append(scorer(estimator, X[test], y[test])) return np.mean(avg_score) def _shuffle(y, labels, random_state): """Return a shuffled copy of y eventually shuffle among same labels.""" if labels is None: - ind = random_state.permutation(y.size) + ind = random_state.permutation(len(y)) else: - ind = np.arange(labels.size) - for label in unique(labels): + ind = np.arange(len(labels)) + for label in np.unique(labels): this_mask = (labels == label) ind[this_mask] = random_state.permutation(ind[this_mask]) return y[ind] @@ -1105,96 +1564,117 @@ def check_cv(cv, X=None, y=None, classifier=False): Parameters ---------- - cv: an integer, a cv generator instance, or None + cv : int, a cv generator instance, or None The input specifying which cv generator to use. It can be an integer, in which case it is the number of folds in a KFold, None, in which case 3 fold is used, or another object, that will then be used as a cv generator. - X: 2D ndarray - the data the cross-val object will be applied on + X : array-like + The data the cross-val object will be applied on. - y: 1D ndarray - the target variable for a supervised learning problem + y : array-like + The target variable for a supervised learning problem. - classifier: boolean optional - whether the task is a classification task, in which case + classifier : boolean optional + Whether the task is a classification task, in which case stratified KFold will be used. + + Returns + ------- + checked_cv: a cross-validation generator instance. + The return value is guaranteed to be a cv generator instance, whatever + the input type. """ + return _check_cv(cv, X=X, y=y, classifier=classifier, warn_mask=True) + + +def _check_cv(cv, X=None, y=None, classifier=False, warn_mask=False): + # This exists for internal use while indices is being deprecated. is_sparse = sp.issparse(X) + needs_indices = is_sparse or not hasattr(X, "shape") if cv is None: cv = 3 - if operator.isNumberType(cv): + if isinstance(cv, numbers.Integral): + if warn_mask and not needs_indices: + warnings.warn('check_cv will return indices instead of boolean ' + 'masks from 0.17', DeprecationWarning) + else: + needs_indices = None if classifier: - cv = StratifiedKFold(y, cv, indices=is_sparse) + if type_of_target(y) in ['binary', 'multiclass']: + cv = StratifiedKFold(y, cv, indices=needs_indices) + else: + cv = KFold(_num_samples(y), cv, indices=needs_indices) else: if not is_sparse: n_samples = len(X) else: n_samples = X.shape[0] - cv = KFold(n_samples, cv, indices=is_sparse) - if is_sparse and not getattr(cv, "indices", True): - raise ValueError("Sparse data require indices-based cross validation" - " generator, got: %r", cv) + cv = KFold(n_samples, cv, indices=needs_indices) + if needs_indices and not getattr(cv, "_indices", True): + raise ValueError("Sparse data and lists require indices-based cross" + " validation generator, got: %r", cv) return cv -def permutation_test_score(estimator, X, y, score_func, cv=None, - n_permutations=100, n_jobs=1, labels=None, - random_state=0, verbose=0): +def permutation_test_score(estimator, X, y, cv=None, + n_permutations=100, n_jobs=1, labels=None, + random_state=0, verbose=0, scoring=None): """Evaluate the significance of a cross-validated score with permutations Parameters ---------- - estimator: estimator object implementing 'fit' - The object to use to fit the data + estimator : estimator object implementing 'fit' + The object to use to fit the data. - X: array-like of shape at least 2D + X : array-like of shape at least 2D The data to fit. - y: array-like + y : array-like The target variable to try to predict in the case of supervised learning. - score_func: callable - Callable taking as arguments the test targets (y_test) and - the predicted targets (y_pred) and returns a float. The score - functions are expected to return a bigger value for a better result - otherwise the returned value does not correspond to a p-value (see - Returns below for further details). + scoring : string, callable or None, optional, default: None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. - cv : integer or crossvalidation generator, optional + cv : integer or cross-validation generator, optional If an integer is passed, it is the number of fold (default 3). - Specific crossvalidation objects can be passed, see - sklearn.cross_validation module for the list of possible objects + Specific cross-validation objects can be passed, see + sklearn.cross_validation module for the list of possible objects. + + n_permutations : integer, optional + Number of times to permute ``y``. - n_jobs: integer, optional + n_jobs : integer, optional The number of CPUs to use to do the computation. -1 means 'all CPUs'. - labels: array-like of shape [n_samples] (optional) + labels : array-like of shape [n_samples] (optional) Labels constrain the permutation among groups of samples with a same label. - random_state: RandomState or an int seed (0 by default) + random_state : RandomState or an int seed (0 by default) A random number generator instance to define the state of the random permutations generator. - verbose: integer, optional - The verbosity level + verbose : integer, optional + The verbosity level. Returns ------- - score: float + score : float The true score without permuting targets. - permutation_scores : array, shape = [n_permutations] + permutation_scores : array, shape (n_permutations,) The scores obtained for each permutations. - pvalue: float - The returned value equals p-value if `score_func` returns bigger - numbers for better scores (e.g., zero_one). If `score_func` is rather a - loss function (i.e. when lower is better such as with + pvalue : float + The returned value equals p-value if `scoring` returns bigger + numbers for better scores (e.g., accuracy_score). If `scoring` is + rather a loss function (i.e. when lower is better such as with `mean_squared_error`) then this is actually the complement of the p-value: 1 - p-value. @@ -1207,19 +1687,19 @@ def permutation_test_score(estimator, X, y, score_func, cv=None, vol. 11 """ - X, y = check_arrays(X, y, sparse_format='csr') - cv = check_cv(cv, X, y, classifier=is_classifier(estimator)) - + X, y = indexable(X, y) + cv = _check_cv(cv, X, y, classifier=is_classifier(estimator)) + scorer = check_scoring(estimator, scoring=scoring) random_state = check_random_state(random_state) # We clone the estimator to make sure that all the folds are # independent, and that it is pickle-able. - score = _permutation_test_score(clone(estimator), X, y, cv, score_func) + score = _permutation_test_score(clone(estimator), X, y, cv, scorer) permutation_scores = Parallel(n_jobs=n_jobs, verbose=verbose)( - delayed(_permutation_test_score)(clone(estimator), X, - _shuffle(y, labels, random_state), - cv, score_func) - for _ in range(n_permutations)) + delayed(_permutation_test_score)( + clone(estimator), X, _shuffle(y, labels, random_state), cv, + scorer) + for _ in range(n_permutations)) permutation_scores = np.array(permutation_scores) pvalue = (np.sum(permutation_scores >= score) + 1.0) / (n_permutations + 1) return score, permutation_scores, pvalue @@ -1231,7 +1711,7 @@ def permutation_test_score(estimator, X, y, score_func, cv=None, def train_test_split(*arrays, **options): """Split arrays or matrices into random train and test subsets - Quick utility that wraps calls to ``check_arrays`` and + Quick utility that wraps input validation and ``next(iter(ShuffleSplit(n_samples)))`` and application to input data into a single call for splitting (and optionally subsampling) data in a oneliner. @@ -1242,22 +1722,26 @@ def train_test_split(*arrays, **options): Python lists or tuples occurring in arrays are converted to 1D numpy arrays. - test_size : float (default 0.25) or int + test_size : float, int, or None (default is None) If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If - int, represents the absolute number of test samples. + int, represents the absolute number of test samples. If None, + the value is automatically set to the complement of the train size. + If train size is also None, test size is set to 0.25. train_size : float, int, or None (default is None) If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, - the value is automatically set to the complement of the test fraction. + the value is automatically set to the complement of the test size. random_state : int or RandomState Pseudo-random number generator state used for random sampling. - dtype : a numpy dtype instance, None by default - Enforce a specific dtype. + Returns + ------- + splitting : list of arrays, length=2 * len(arrays) + List containing train-test split of input array. Examples -------- @@ -1281,32 +1765,55 @@ def train_test_split(*arrays, **options): [0, 1], [6, 7]]) >>> b_train - array([2, 0, 3]) + [2, 0, 3] >>> a_test array([[2, 3], [8, 9]]) >>> b_test - array([1, 4]) + [1, 4] """ n_arrays = len(arrays) if n_arrays == 0: raise ValueError("At least one array required as input") - test_size = options.pop('test_size', 0.1) + test_size = options.pop('test_size', None) train_size = options.pop('train_size', None) random_state = options.pop('random_state', None) - options['sparse_format'] = 'csr' - - arrays = check_arrays(*arrays, **options) - n_samples = arrays[0].shape[0] + dtype = options.pop('dtype', None) + if dtype is not None: + warnings.warn("dtype option is ignored and will be removed in 0.18.", + DeprecationWarning) + + allow_nd = options.pop('allow_nd', None) + allow_lists = options.pop('allow_lists', None) + + if allow_lists is not None: + warnings.warn("The allow_lists option is deprecated and will be " + "assumed True in 0.18 and removed.", DeprecationWarning) + + if options: + raise TypeError("Invalid parameters passed: %s" % str(options)) + if allow_nd is not None: + warnings.warn("The allow_nd option is deprecated and will be " + "assumed True in 0.18 and removed.", DeprecationWarning) + if allow_lists is False or allow_nd is False: + arrays = [check_array(x, 'csr', allow_nd=allow_nd, + force_all_finite=False, ensure_2d=False) + if x is not None else x + for x in arrays] + + if test_size is None and train_size is None: + test_size = 0.25 + arrays = indexable(*arrays) + n_samples = _num_samples(arrays[0]) cv = ShuffleSplit(n_samples, test_size=test_size, train_size=train_size, - random_state=random_state, - indices=True) + random_state=random_state) + train, test = next(iter(cv)) - splitted = [] - for a in arrays: - splitted.append(a[train]) - splitted.append(a[test]) - return splitted + return list(chain.from_iterable((safe_indexing(a, train), + safe_indexing(a, test)) for a in arrays)) + + +train_test_split.__test__ = False # to avoid a pb with nosetests diff --git a/sklearn/datasets/DATASET_PROPOSAL.txt b/sklearn/datasets/DATASET_PROPOSAL.txt index 7389c4d446295..0fefb901fc6b3 100644 --- a/sklearn/datasets/DATASET_PROPOSAL.txt +++ b/sklearn/datasets/DATASET_PROPOSAL.txt @@ -108,7 +108,7 @@ I see mainly two big problems: we want to avoid loading all the data in memory ? Can we use memory mapped arrays ? - Missing data: I thought about subclassing both record arrays and - masked arrays classes, but I don't know if this is feasable, or even + masked arrays classes, but I don't know if this is feasible, or even makes sense. I have the feeling that some Data mining software use Nan (for example, weka seems to use float internally), but this prevents them from representing integer data. diff --git a/sklearn/datasets/__init__.py b/sklearn/datasets/__init__.py index 51bae48adfff9..4b041675a2a85 100644 --- a/sklearn/datasets/__init__.py +++ b/sklearn/datasets/__init__.py @@ -14,6 +14,7 @@ from .base import clear_data_home from .base import load_sample_images from .base import load_sample_image +from .covtype import fetch_covtype from .mlcomp import load_mlcomp from .lfw import load_lfw_pairs from .lfw import load_lfw_people @@ -39,12 +40,15 @@ from .samples_generator import make_swiss_roll from .samples_generator import make_s_curve from .samples_generator import make_sparse_spd_matrix +from .samples_generator import make_gaussian_quantiles +from .samples_generator import make_biclusters +from .samples_generator import make_checkerboard from .svmlight_format import load_svmlight_file from .svmlight_format import load_svmlight_files from .svmlight_format import dump_svmlight_file from .olivetti_faces import fetch_olivetti_faces from .species_distributions import fetch_species_distributions -from ..utils import deprecated +from .california_housing import fetch_california_housing __all__ = ['clear_data_home', 'dump_svmlight_file', @@ -55,12 +59,12 @@ 'fetch_mldata', 'fetch_olivetti_faces', 'fetch_species_distributions', + 'fetch_california_housing', + 'fetch_covtype', 'get_data_home', - 'load_20newsgroups', 'load_boston', 'load_diabetes', 'load_digits', - 'load_filenames', 'load_files', 'load_iris', 'load_lfw_pairs', @@ -71,12 +75,15 @@ 'load_sample_images', 'load_svmlight_file', 'load_svmlight_files', + 'make_biclusters', 'make_blobs', 'make_circles', 'make_classification', + 'make_checkerboard', 'make_friedman1', 'make_friedman2', 'make_friedman3', + 'make_gaussian_quantiles', 'make_hastie_10_2', 'make_low_rank_matrix', 'make_moons', @@ -88,13 +95,4 @@ 'make_sparse_uncorrelated', 'make_spd_matrix', 'make_swiss_roll', - 'mldata_filename', - 'samples_generator'] - - -# backward compatibility -@deprecated("to be removed in 0.9;" - " use sklearn.datasets.load_files instead") -def load_filenames(*args, **kwargs): - """Deprecated, use ``sklearn.datasets.load_files`` instead""" - return load_files(*args, **kwargs) + 'mldata_filename'] diff --git a/sklearn/datasets/_svmlight_format.c b/sklearn/datasets/_svmlight_format.c index e4e4348ffe4f9..369115985aebc 100644 --- a/sklearn/datasets/_svmlight_format.c +++ b/sklearn/datasets/_svmlight_format.c @@ -1,6 +1,18 @@ -/* Generated by Cython 0.17 on Sat Sep 15 14:47:34 2012 */ +/* Generated by Cython 0.19.2 on Sun Jan 5 22:08:38 2014 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. @@ -53,12 +65,15 @@ (PyErr_Format(PyExc_TypeError, \ "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ (PyObject*)0)) - #define PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && !PyComplex_Check(o)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) #define __PYX_BUILD_PY_SSIZE_T "i" #else #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) @@ -113,6 +128,9 @@ #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ @@ -152,6 +170,14 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) +#endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -224,6 +250,40 @@ #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif #if PY_MAJOR_VERSION >= 3 @@ -250,6 +310,7 @@ #define __PYX_HAVE_API__sklearn__datasets___svmlight_format #include "string.h" #include "stdio.h" +#include "pythread.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" @@ -261,21 +322,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -289,30 +335,130 @@ # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - #if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + #ifdef __GNUC__ /* Test for GCC > 2.95 */ @@ -327,8 +473,9 @@ static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -361,8 +508,11 @@ static const char *__pyx_filename; static const char *__pyx_f[] = { "_svmlight_format.pyx", + "array.pxd", "numpy.pxd", "type.pxd", + "bool.pxd", + "complex.pxd", }; /* "numpy.pxd":723 @@ -575,6 +725,10 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; /*--- Type declarations ---*/ +#ifndef _ARRAYARRAY_H +struct arrayobject; +typedef struct arrayobject arrayobject; +#endif /* "numpy.pxd":762 * ctypedef npy_longdouble longdouble_t @@ -662,10 +816,33 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ @@ -676,94 +853,35 @@ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ const char* function_name); /*proto*/ -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -#define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_List_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { -#if CYTHON_COMPILING_IN_CPYTHON - if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Tuple_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { -#if CYTHON_COMPILING_IN_CPYTHON - if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -#define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { -#if CYTHON_COMPILING_IN_CPYTHON - if (PyList_CheckExact(o)) { - Py_ssize_t n = (likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if (likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = (likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if (likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { /* inlined PySequence_GetItem() */ - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (unlikely(l < 0)) return NULL; - i += l; - } - return m->sq_item(o, i); - } - } -#else - if (PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +#define __Pyx_GetItemInt(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Fast(o, i, is_list, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +#define __Pyx_GetItemInt_List(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_List_Fast(o, i, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, i, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); #if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len)) { @@ -775,7 +893,7 @@ static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { return PyList_Append(list, x); } #else -#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) #endif static double __Pyx__PyObject_AsDouble(PyObject* obj); /* proto */ @@ -790,20 +908,53 @@ static double __Pyx__PyObject_AsDouble(PyObject* obj); /* proto */ PyFloat_AS_DOUBLE(obj) : __Pyx__PyObject_AsDouble(obj)) #endif -static CYTHON_INLINE PyObject* __Pyx_PyObject_Append(PyObject* L, PyObject* x) { - if (likely(PyList_CheckExact(L))) { - if (unlikely(PyList_Append(L, x) < 0)) return NULL; - Py_INCREF(Py_None); - return Py_None; /* this is just to have an accurate signature */ - } else { - PyObject *r, *m; - m = __Pyx_GetAttrString(L, "append"); - if (!m) return NULL; - r = PyObject_CallFunctionObjArgs(m, x, NULL); - Py_DECREF(m); - return r; +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +static PyObject* __Pyx_PyObject_CallMethodTuple(PyObject* obj, PyObject* method_name, PyObject* args) { + PyObject *method, *result = NULL; + if (unlikely(!args)) return NULL; + method = __Pyx_PyObject_GetAttrStr(obj, method_name); + if (unlikely(!method)) goto bad; + result = PyObject_Call(method, args, NULL); + Py_DECREF(method); +bad: + Py_DECREF(args); + return result; } +#define __Pyx_PyObject_CallMethod3(obj, name, arg1, arg2, arg3) \ + __Pyx_PyObject_CallMethodTuple(obj, name, PyTuple_Pack(3, arg1, arg2, arg3)) +#define __Pyx_PyObject_CallMethod2(obj, name, arg1, arg2) \ + __Pyx_PyObject_CallMethodTuple(obj, name, PyTuple_Pack(2, arg1, arg2)) +#define __Pyx_PyObject_CallMethod1(obj, name, arg1) \ + __Pyx_PyObject_CallMethodTuple(obj, name, PyTuple_Pack(1, arg1)) +#define __Pyx_PyObject_CallMethod0(obj, name) \ + __Pyx_PyObject_CallMethodTuple(obj, name, (Py_INCREF(__pyx_empty_tuple), __pyx_empty_tuple)) + +static CYTHON_INLINE PyObject* __Pyx_PyObject_Append(PyObject* L, PyObject* x); /*proto*/ + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +#define __Pyx_SetItemInt(o, i, v, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_SetItemInt_Fast(o, i, v, is_list, wraparound, boundscheck) : \ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v)) +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck); static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); @@ -813,6 +964,8 @@ static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ +static PyObject* __Pyx_PyObject_PopIndex(PyObject* L, Py_ssize_t ix); /*proto*/ + static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ @@ -820,15 +973,117 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ - -static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name); - -static CYTHON_INLINE npy_int32 __Pyx_PyInt_from_py_npy_int32(PyObject *); +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /*proto*/ + +#ifndef _ARRAYARRAY_H +#define _ARRAYARRAY_H +typedef struct arraydescr { + int typecode; + int itemsize; + PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); + int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); +#if PY_VERSION_HEX >= 0x03000000 + char *formats; +#endif +} arraydescr; +struct arrayobject { + PyObject_HEAD + Py_ssize_t ob_size; + union { + char *ob_item; + float *as_floats; + double *as_doubles; + int *as_ints; + unsigned int *as_uints; + unsigned char *as_uchars; + signed char *as_schars; + char *as_chars; + unsigned long *as_ulongs; + long *as_longs; + short *as_shorts; + unsigned short *as_ushorts; + Py_UNICODE *as_pyunicodes; + void *as_voidptr; + } data; + Py_ssize_t allocated; + struct arraydescr *ob_descr; + PyObject *weakreflist; /* List of weak references */ +#if PY_VERSION_HEX >= 0x03000000 + int ob_exports; /* Number of exported buffers */ +#endif +}; +#ifndef NO_NEWARRAY_INLINE +static CYTHON_INLINE PyObject * newarrayobject(PyTypeObject *type, Py_ssize_t size, + struct arraydescr *descr) { + arrayobject *op; + size_t nbytes; + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } + nbytes = size * descr->itemsize; + if (nbytes / descr->itemsize != (size_t)size) { + return PyErr_NoMemory(); + } + op = (arrayobject *) type->tp_alloc(type, 0); + if (op == NULL) { + return NULL; + } + op->ob_descr = descr; + op->allocated = size; + op->weakreflist = NULL; + op->ob_size = size; + if (size <= 0) { + op->data.ob_item = NULL; + } + else { + op->data.ob_item = PyMem_NEW(char, nbytes); + if (op->data.ob_item == NULL) { + Py_DECREF(op); + return PyErr_NoMemory(); + } + } + return (PyObject *) op; +} +#else +PyObject* newarrayobject(PyTypeObject *type, Py_ssize_t size, + struct arraydescr *descr); +#endif /* ifndef NO_NEWARRAY_INLINE */ +static CYTHON_INLINE int resize(arrayobject *self, Py_ssize_t n) { + void *items = (void*) self->data.ob_item; + PyMem_Resize(items, char, (size_t)(n * self->ob_descr->itemsize)); + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->data.ob_item = (char*) items; + self->ob_size = n; + self->allocated = n; + return 0; +} +static CYTHON_INLINE int resize_smart(arrayobject *self, Py_ssize_t n) { + void *items = (void*) self->data.ob_item; + Py_ssize_t newsize; + if (n < self->allocated) { + if (n*4 > self->allocated) { + self->ob_size = n; + return 0; + } + } + newsize = n * 3 / 2 + 1; + PyMem_Resize(items, char, (size_t)(newsize * self->ob_descr->itemsize)); + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->data.ob_item = (char*) items; + self->ob_size = n; + self->allocated = newsize; + return 0; +} +#endif -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32); +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -994,23 +1249,101 @@ static void __Pyx_AddTraceback(const char *funcname, int c_line, static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ -/* Module declarations from 'libc.string' */ - -/* Module declarations from 'cpython.buffer' */ +/* Module declarations from 'cpython.version' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'cpython.exc' */ + +/* Module declarations from 'cpython.module' */ + +/* Module declarations from 'cpython.mem' */ + +/* Module declarations from 'cpython.tuple' */ + +/* Module declarations from 'cpython.list' */ + +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from 'cpython.sequence' */ + +/* Module declarations from 'cpython.mapping' */ + +/* Module declarations from 'cpython.iterator' */ + /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.type' */ static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; +/* Module declarations from 'cpython.number' */ + +/* Module declarations from 'cpython.int' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.bool' */ +static PyTypeObject *__pyx_ptype_7cpython_4bool_bool = 0; + +/* Module declarations from 'cpython.long' */ + +/* Module declarations from 'cpython.float' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.complex' */ +static PyTypeObject *__pyx_ptype_7cpython_7complex_complex = 0; + +/* Module declarations from 'cpython.string' */ + +/* Module declarations from 'cpython.unicode' */ + +/* Module declarations from 'cpython.dict' */ + +/* Module declarations from 'cpython.instance' */ + +/* Module declarations from 'cpython.function' */ + +/* Module declarations from 'cpython.method' */ + +/* Module declarations from 'cpython.weakref' */ + +/* Module declarations from 'cpython.getargs' */ + +/* Module declarations from 'cpython.pythread' */ + +/* Module declarations from 'cpython.pystate' */ + +/* Module declarations from 'cpython.cobject' */ + +/* Module declarations from 'cpython.oldbuffer' */ + +/* Module declarations from 'cpython.set' */ + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.bytes' */ + +/* Module declarations from 'cpython.pycapsule' */ + +/* Module declarations from 'cpython' */ + /* Module declarations from 'libc.stdlib' */ +/* Module declarations from 'libc' */ + +/* Module declarations from 'array' */ + +/* Module declarations from 'cpython.array' */ +static PyTypeObject *__pyx_ptype_7cpython_5array_array = 0; +static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *, char *, Py_ssize_t); /*proto*/ + +/* Module declarations from 'cython' */ + /* Module declarations from 'numpy' */ /* Module declarations from 'numpy' */ @@ -1032,30 +1365,33 @@ static PyObject *__pyx_builtin_xrange; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_RuntimeError; -static PyObject *__pyx_pf_7sklearn_8datasets_16_svmlight_format__load_svmlight_file(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_f, PyObject *__pyx_v_dtype, int __pyx_v_multilabel, int __pyx_v_zero_based); /* proto */ +static PyObject *__pyx_pf_7sklearn_8datasets_16_svmlight_format__load_svmlight_file(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_f, PyObject *__pyx_v_dtype, int __pyx_v_multilabel, int __pyx_v_zero_based, int __pyx_v_query_id); /* proto */ +static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags); /* proto */ +static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ -static char __pyx_k_1[] = "Invalid index %d in SVMlight/LibSVM data file."; -static char __pyx_k_2[] = "Feature ndices in SVMlight/LibSVM data file should be sorted and unique."; -static char __pyx_k_4[] = "ndarray is not C contiguous"; -static char __pyx_k_6[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_8[] = "Non-native byte order not supported"; -static char __pyx_k_10[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_11[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_14[] = "Format string allocated too short."; -static char __pyx_k_16[] = "scipy.sparse"; -static char __pyx_k_17[] = "*"; -static char __pyx_k_18[] = "utils.arraybuilder"; -static char __pyx_k_20[] = ","; -static char __pyx_k_21[] = ":"; -static char __pyx_k_24[] = "/home/lars/src/scikit-learn/sklearn/datasets/_svmlight_format.pyx"; -static char __pyx_k_25[] = "sklearn.datasets._svmlight_format"; +static char __pyx_k_8[] = "Invalid index %d in SVMlight/LibSVM data file."; +static char __pyx_k_9[] = "Feature indices in SVMlight/LibSVM data file should be sorted and unique."; +static char __pyx_k_11[] = "ndarray is not C contiguous"; +static char __pyx_k_13[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_15[] = "Non-native byte order not supported"; +static char __pyx_k_17[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_18[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_21[] = "Format string allocated too short."; +static char __pyx_k_23[] = "scipy.sparse"; +static char __pyx_k_24[] = "*"; +static char __pyx_k_25[] = "externals.six"; +static char __pyx_k_26[] = ","; +static char __pyx_k_27[] = ":"; +static char __pyx_k_30[] = "/home/lars/src/scikit-learn/sklearn/datasets/_svmlight_format.pyx"; +static char __pyx_k_31[] = "sklearn.datasets._svmlight_format"; static char __pyx_k__B[] = "B"; static char __pyx_k__H[] = "H"; static char __pyx_k__I[] = "I"; static char __pyx_k__L[] = "L"; static char __pyx_k__O[] = "O"; static char __pyx_k__Q[] = "Q"; +static char __pyx_k___[] = "_"; static char __pyx_k__b[] = "b"; static char __pyx_k__d[] = "d"; static char __pyx_k__f[] = "f"; @@ -1070,91 +1406,102 @@ static char __pyx_k__Zf[] = "Zf"; static char __pyx_k__Zg[] = "Zg"; static char __pyx_k__np[] = "np"; static char __pyx_k__sp[] = "sp"; -static char __pyx_k__get[] = "get"; static char __pyx_k__idx[] = "idx"; +static char __pyx_k__pop[] = "pop"; +static char __pyx_k__qid[] = "qid"; static char __pyx_k__data[] = "data"; static char __pyx_k__line[] = "line"; static char __pyx_k__sort[] = "sort"; +static char __pyx_k__array[] = "array"; static char __pyx_k__dtype[] = "dtype"; static char __pyx_k__idx_s[] = "idx_s"; -static char __pyx_k__int32[] = "int32"; static char __pyx_k__numpy[] = "numpy"; +static char __pyx_k__query[] = "query"; static char __pyx_k__range[] = "range"; static char __pyx_k__split[] = "split"; static char __pyx_k__value[] = "value"; -static char __pyx_k__double[] = "double"; +static char __pyx_k__append[] = "append"; static char __pyx_k__indptr[] = "indptr"; static char __pyx_k__labels[] = "labels"; static char __pyx_k__target[] = "target"; static char __pyx_k__xrange[] = "xrange"; +static char __pyx_k__float32[] = "float32"; +static char __pyx_k__float64[] = "float64"; static char __pyx_k__indices[] = "indices"; static char __pyx_k____main__[] = "__main__"; static char __pyx_k____test__[] = "__test__"; static char __pyx_k__features[] = "features"; static char __pyx_k__hash_ptr[] = "hash_ptr"; static char __pyx_k__prev_idx[] = "prev_idx"; -static char __pyx_k___temp_csr[] = "_temp_csr"; +static char __pyx_k__query_id[] = "query_id"; static char __pyx_k__line_cstr[] = "line_cstr"; static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__csr_matrix[] = "csr_matrix"; +static char __pyx_k____import__[] = "__import__"; static char __pyx_k__line_parts[] = "line_parts"; static char __pyx_k__multilabel[] = "multilabel"; +static char __pyx_k__n_features[] = "n_features"; +static char __pyx_k__qid_prefix[] = "qid_prefix"; +static char __pyx_k__startswith[] = "startswith"; static char __pyx_k__zero_based[] = "zero_based"; -static char __pyx_k__ArrayBuilder[] = "ArrayBuilder"; static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k___INDPTR_DTYPE[] = "_INDPTR_DTYPE"; -static char __pyx_k___INDICES_DTYPE[] = "_INDICES_DTYPE"; static char __pyx_k___load_svmlight_file[] = "_load_svmlight_file"; -static PyObject *__pyx_kp_s_1; -static PyObject *__pyx_kp_u_10; static PyObject *__pyx_kp_u_11; -static PyObject *__pyx_kp_u_14; -static PyObject *__pyx_n_s_16; -static PyObject *__pyx_n_s_17; -static PyObject *__pyx_n_s_18; -static PyObject *__pyx_kp_s_2; -static PyObject *__pyx_kp_b_20; -static PyObject *__pyx_kp_b_21; -static PyObject *__pyx_kp_s_24; +static PyObject *__pyx_kp_u_13; +static PyObject *__pyx_kp_u_15; +static PyObject *__pyx_kp_u_17; +static PyObject *__pyx_kp_u_18; +static PyObject *__pyx_kp_u_21; +static PyObject *__pyx_n_s_23; +static PyObject *__pyx_n_s_24; static PyObject *__pyx_n_s_25; -static PyObject *__pyx_kp_u_4; -static PyObject *__pyx_kp_u_6; -static PyObject *__pyx_kp_u_8; -static PyObject *__pyx_n_s__ArrayBuilder; +static PyObject *__pyx_kp_b_26; +static PyObject *__pyx_kp_b_27; +static PyObject *__pyx_kp_s_30; +static PyObject *__pyx_n_s_31; +static PyObject *__pyx_kp_s_8; +static PyObject *__pyx_kp_s_9; static PyObject *__pyx_n_s__RuntimeError; static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s___INDICES_DTYPE; -static PyObject *__pyx_n_s___INDPTR_DTYPE; +static PyObject *__pyx_n_s___; +static PyObject *__pyx_n_s____import__; static PyObject *__pyx_n_s____main__; static PyObject *__pyx_n_s____test__; static PyObject *__pyx_n_s___load_svmlight_file; -static PyObject *__pyx_n_s___temp_csr; -static PyObject *__pyx_n_s__csr_matrix; +static PyObject *__pyx_n_s__append; +static PyObject *__pyx_n_s__array; +static PyObject *__pyx_n_s__b; +static PyObject *__pyx_n_s__d; static PyObject *__pyx_n_s__data; -static PyObject *__pyx_n_s__double; static PyObject *__pyx_n_s__dtype; static PyObject *__pyx_n_s__f; static PyObject *__pyx_n_s__features; -static PyObject *__pyx_n_s__get; +static PyObject *__pyx_n_s__float32; +static PyObject *__pyx_n_s__float64; static PyObject *__pyx_n_s__hash_ptr; static PyObject *__pyx_n_s__i; static PyObject *__pyx_n_s__idx; static PyObject *__pyx_n_s__idx_s; static PyObject *__pyx_n_s__indices; static PyObject *__pyx_n_s__indptr; -static PyObject *__pyx_n_s__int32; static PyObject *__pyx_n_s__labels; static PyObject *__pyx_n_s__line; static PyObject *__pyx_n_s__line_cstr; static PyObject *__pyx_n_s__line_parts; static PyObject *__pyx_n_s__multilabel; +static PyObject *__pyx_n_s__n_features; static PyObject *__pyx_n_s__np; static PyObject *__pyx_n_s__numpy; +static PyObject *__pyx_n_s__pop; static PyObject *__pyx_n_s__prev_idx; +static PyObject *__pyx_n_s__qid; +static PyObject *__pyx_n_s__qid_prefix; +static PyObject *__pyx_n_s__query; +static PyObject *__pyx_n_s__query_id; static PyObject *__pyx_n_s__range; static PyObject *__pyx_n_s__sort; static PyObject *__pyx_n_s__sp; static PyObject *__pyx_n_s__split; +static PyObject *__pyx_n_s__startswith; static PyObject *__pyx_n_s__target; static PyObject *__pyx_n_s__value; static PyObject *__pyx_n_s__xrange; @@ -1163,16 +1510,22 @@ static PyObject *__pyx_n_s__zero_based; static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_15; +static PyObject *__pyx_k_slice_7; +static PyObject *__pyx_k_tuple_1; +static PyObject *__pyx_k_tuple_2; static PyObject *__pyx_k_tuple_3; +static PyObject *__pyx_k_tuple_4; static PyObject *__pyx_k_tuple_5; -static PyObject *__pyx_k_tuple_7; -static PyObject *__pyx_k_tuple_9; +static PyObject *__pyx_k_tuple_6; +static PyObject *__pyx_k_tuple_10; static PyObject *__pyx_k_tuple_12; -static PyObject *__pyx_k_tuple_13; -static PyObject *__pyx_k_tuple_15; +static PyObject *__pyx_k_tuple_14; +static PyObject *__pyx_k_tuple_16; static PyObject *__pyx_k_tuple_19; +static PyObject *__pyx_k_tuple_20; static PyObject *__pyx_k_tuple_22; -static PyObject *__pyx_k_codeobj_23; +static PyObject *__pyx_k_tuple_28; +static PyObject *__pyx_k_codeobj_29; /* Python wrapper */ static PyObject *__pyx_pw_7sklearn_8datasets_16_svmlight_format_1_load_svmlight_file(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ @@ -1182,16 +1535,21 @@ static PyObject *__pyx_pw_7sklearn_8datasets_16_svmlight_format_1_load_svmlight_ PyObject *__pyx_v_dtype = 0; int __pyx_v_multilabel; int __pyx_v_zero_based; + int __pyx_v_query_id; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("_load_svmlight_file (wrapper)", 0); { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__f,&__pyx_n_s__dtype,&__pyx_n_s__multilabel,&__pyx_n_s__zero_based,0}; - PyObject* values[4] = {0,0,0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__f,&__pyx_n_s__dtype,&__pyx_n_s__multilabel,&__pyx_n_s__zero_based,&__pyx_n_s__query_id,0}; + PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); @@ -1207,269 +1565,335 @@ static PyObject *__pyx_pw_7sklearn_8datasets_16_svmlight_format_1_load_svmlight_ case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dtype)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_load_svmlight_file", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_load_svmlight_file", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__multilabel)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_load_svmlight_file", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_load_svmlight_file", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__zero_based)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_load_svmlight_file", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_load_svmlight_file", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__query_id)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_load_svmlight_file", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_load_svmlight_file") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); } __pyx_v_f = values[0]; __pyx_v_dtype = values[1]; __pyx_v_multilabel = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_multilabel == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_zero_based = __Pyx_PyObject_IsTrue(values[3]); if (unlikely((__pyx_v_zero_based == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_query_id = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_query_id == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_load_svmlight_file", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_load_svmlight_file", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.datasets._svmlight_format._load_svmlight_file", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7sklearn_8datasets_16_svmlight_format__load_svmlight_file(__pyx_self, __pyx_v_f, __pyx_v_dtype, __pyx_v_multilabel, __pyx_v_zero_based); + __pyx_r = __pyx_pf_7sklearn_8datasets_16_svmlight_format__load_svmlight_file(__pyx_self, __pyx_v_f, __pyx_v_dtype, __pyx_v_multilabel, __pyx_v_zero_based, __pyx_v_query_id); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "sklearn/datasets/_svmlight_format.pyx":28 - * - * - * def _load_svmlight_file(f, dtype, bint multilabel, bint zero_based): # <<<<<<<<<<<<<< - * cdef bytes line - * cdef char *hash_ptr, *line_cstr - */ - -static PyObject *__pyx_pf_7sklearn_8datasets_16_svmlight_format__load_svmlight_file(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_f, PyObject *__pyx_v_dtype, int __pyx_v_multilabel, int __pyx_v_zero_based) { + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def _load_svmlight_file(f, dtype, bint multilabel, bint zero_based, # <<<<<<<<<<<<<< + * bint query_id): + * cdef array.array data, indices, indptr, query + */ + +static PyObject *__pyx_pf_7sklearn_8datasets_16_svmlight_format__load_svmlight_file(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_f, PyObject *__pyx_v_dtype, int __pyx_v_multilabel, int __pyx_v_zero_based, int __pyx_v_query_id) { + arrayobject *__pyx_v_data = 0; + arrayobject *__pyx_v_indices = 0; + arrayobject *__pyx_v_indptr = 0; + arrayobject *__pyx_v_query = 0; PyObject *__pyx_v_line = 0; char *__pyx_v_hash_ptr; char *__pyx_v_line_cstr; - __pyx_t_5numpy_int32_t __pyx_v_idx; - __pyx_t_5numpy_int32_t __pyx_v_prev_idx; + int __pyx_v_idx; + int __pyx_v_prev_idx; Py_ssize_t __pyx_v_i; - PyObject *__pyx_v_data = NULL; - PyObject *__pyx_v_indptr = NULL; - PyObject *__pyx_v_indices = NULL; + PyObject *__pyx_v_qid_prefix = 0; + Py_ssize_t __pyx_v_n_features; PyObject *__pyx_v_labels = NULL; PyObject *__pyx_v_line_parts = NULL; PyObject *__pyx_v_target = NULL; - CYTHON_UNUSED PyObject *__pyx_v_features = NULL; - PyObject *__pyx_v_idx_s = NULL; + PyObject *__pyx_v_features = NULL; + CYTHON_UNUSED PyObject *__pyx_v__ = NULL; PyObject *__pyx_v_value = NULL; + PyObject *__pyx_v_idx_s = NULL; PyObject *__pyx_v_y = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - Py_ssize_t __pyx_t_5; - PyObject *(*__pyx_t_6)(PyObject *); - char *__pyx_t_7; - int __pyx_t_8; - Py_ssize_t __pyx_t_9; + int __pyx_t_3; + Py_ssize_t __pyx_t_4; + PyObject *(*__pyx_t_5)(PyObject *); + char *__pyx_t_6; + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; PyObject *(*__pyx_t_11)(PyObject *); double __pyx_t_12; - Py_ssize_t __pyx_t_13; - PyObject *(*__pyx_t_14)(PyObject *); - __pyx_t_5numpy_int32_t __pyx_t_15; - int __pyx_t_16; + int __pyx_t_13; + Py_ssize_t __pyx_t_14; + int __pyx_t_15; + PyObject *(*__pyx_t_16)(PyObject *); int __pyx_t_17; int __pyx_t_18; + Py_ssize_t __pyx_t_19; + Py_ssize_t __pyx_t_20; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_load_svmlight_file", 0); + __Pyx_INCREF(__pyx_v_dtype); - /* "sklearn/datasets/_svmlight_format.pyx":34 + /* "sklearn/datasets/_svmlight_format.pyx":35 + * cdef int idx, prev_idx * cdef Py_ssize_t i + * cdef bytes qid_prefix = b('qid') # <<<<<<<<<<<<<< + * cdef Py_ssize_t n_features * - * data = ArrayBuilder(dtype=dtype) # <<<<<<<<<<<<<< - * indptr = ArrayBuilder(dtype=_INDPTR_DTYPE) - * indices = ArrayBuilder(dtype=_INDICES_DTYPE) */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ArrayBuilder); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__b); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_v_dtype) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_1), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_v_data = __pyx_t_3; - __pyx_t_3 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_2))||((__pyx_t_2) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_2)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_qid_prefix = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/datasets/_svmlight_format.pyx":40 + * # Special-case float32 but use float64 for everything else; + * # the Python code will do further conversions. + * if dtype == np.float32: # <<<<<<<<<<<<<< + * data = array.array("f") + * else: + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float32); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_RichCompare(__pyx_v_dtype, __pyx_t_1, Py_EQ); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_3) { - /* "sklearn/datasets/_svmlight_format.pyx":35 + /* "sklearn/datasets/_svmlight_format.pyx":41 + * # the Python code will do further conversions. + * if dtype == np.float32: + * data = array.array("f") # <<<<<<<<<<<<<< + * else: + * dtype = np.float64 + */ + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7cpython_5array_array)), ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_data = ((arrayobject *)__pyx_t_2); + __pyx_t_2 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/datasets/_svmlight_format.pyx":43 + * data = array.array("f") + * else: + * dtype = np.float64 # <<<<<<<<<<<<<< + * data = array.array("d") + * indices = array.array("i") + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_dtype, __pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/datasets/_svmlight_format.pyx":44 + * else: + * dtype = np.float64 + * data = array.array("d") # <<<<<<<<<<<<<< + * indices = array.array("i") + * indptr = array.array("i", [0]) + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7cpython_5array_array)), ((PyObject *)__pyx_k_tuple_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_data = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + } + __pyx_L3:; + + /* "sklearn/datasets/_svmlight_format.pyx":45 + * dtype = np.float64 + * data = array.array("d") + * indices = array.array("i") # <<<<<<<<<<<<<< + * indptr = array.array("i", [0]) + * query = array.array("i") + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7cpython_5array_array)), ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_indices = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/datasets/_svmlight_format.pyx":46 + * data = array.array("d") + * indices = array.array("i") + * indptr = array.array("i", [0]) # <<<<<<<<<<<<<< + * query = array.array("i") * - * data = ArrayBuilder(dtype=dtype) - * indptr = ArrayBuilder(dtype=_INDPTR_DTYPE) # <<<<<<<<<<<<<< - * indices = ArrayBuilder(dtype=_INDICES_DTYPE) - * if multilabel: */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__ArrayBuilder); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s___INDPTR_DTYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_int_0); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_n_s__i)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_n_s__i)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i)); + PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_t_1)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_1)); + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7cpython_5array_array)), ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_v_indptr = __pyx_t_1; + __pyx_v_indptr = ((arrayobject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":36 - * data = ArrayBuilder(dtype=dtype) - * indptr = ArrayBuilder(dtype=_INDPTR_DTYPE) - * indices = ArrayBuilder(dtype=_INDICES_DTYPE) # <<<<<<<<<<<<<< + /* "sklearn/datasets/_svmlight_format.pyx":47 + * indices = array.array("i") + * indptr = array.array("i", [0]) + * query = array.array("i") # <<<<<<<<<<<<<< + * * if multilabel: - * labels = [] */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ArrayBuilder); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7cpython_5array_array)), ((PyObject *)__pyx_k_tuple_5), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s___INDICES_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_v_indices = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_v_query = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":37 - * indptr = ArrayBuilder(dtype=_INDPTR_DTYPE) - * indices = ArrayBuilder(dtype=_INDICES_DTYPE) + /* "sklearn/datasets/_svmlight_format.pyx":49 + * query = array.array("i") + * * if multilabel: # <<<<<<<<<<<<<< * labels = [] * else: */ - if (__pyx_v_multilabel) { + __pyx_t_3 = (__pyx_v_multilabel != 0); + if (__pyx_t_3) { - /* "sklearn/datasets/_svmlight_format.pyx":38 - * indices = ArrayBuilder(dtype=_INDICES_DTYPE) + /* "sklearn/datasets/_svmlight_format.pyx":50 + * * if multilabel: * labels = [] # <<<<<<<<<<<<<< * else: - * labels = ArrayBuilder(dtype=np.double) + * labels = array.array("d") */ - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_labels = ((PyObject *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L3; + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_labels = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L4; } /*else*/ { - /* "sklearn/datasets/_svmlight_format.pyx":40 + /* "sklearn/datasets/_svmlight_format.pyx":52 * labels = [] * else: - * labels = ArrayBuilder(dtype=np.double) # <<<<<<<<<<<<<< + * labels = array.array("d") # <<<<<<<<<<<<<< * * for line in f: */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__ArrayBuilder); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7cpython_5array_array)), ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__double); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_v_labels = __pyx_t_4; - __pyx_t_4 = 0; + __pyx_v_labels = __pyx_t_1; + __pyx_t_1 = 0; } - __pyx_L3:; + __pyx_L4:; - /* "sklearn/datasets/_svmlight_format.pyx":42 - * labels = ArrayBuilder(dtype=np.double) + /* "sklearn/datasets/_svmlight_format.pyx":54 + * labels = array.array("d") * * for line in f: # <<<<<<<<<<<<<< * # skip comments * line_cstr = line */ if (PyList_CheckExact(__pyx_v_f) || PyTuple_CheckExact(__pyx_v_f)) { - __pyx_t_4 = __pyx_v_f; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; - __pyx_t_6 = NULL; + __pyx_t_1 = __pyx_v_f; __Pyx_INCREF(__pyx_t_1); __pyx_t_4 = 0; + __pyx_t_5 = NULL; } else { - __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_f); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + __pyx_t_4 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_f); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = Py_TYPE(__pyx_t_1)->tp_iternext; } for (;;) { - if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { - if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + if (!__pyx_t_5 && PyList_CheckExact(__pyx_t_1)) { + if (__pyx_t_4 >= PyList_GET_SIZE(__pyx_t_1)) break; #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_2 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_4); __Pyx_INCREF(__pyx_t_2); __pyx_t_4++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif - } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { - if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + } else if (!__pyx_t_5 && PyTuple_CheckExact(__pyx_t_1)) { + if (__pyx_t_4 >= PyTuple_GET_SIZE(__pyx_t_1)) break; #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_4); __Pyx_INCREF(__pyx_t_2); __pyx_t_4++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif } else { - __pyx_t_2 = __pyx_t_6(__pyx_t_4); + __pyx_t_2 = __pyx_t_5(__pyx_t_1); if (unlikely(!__pyx_t_2)) { if (PyErr_Occurred()) { if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } break; } __Pyx_GOTREF(__pyx_t_2); } - if (!(likely(PyBytes_CheckExact(__pyx_t_2))||((__pyx_t_2) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_2)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_line)); - __pyx_v_line = ((PyObject*)__pyx_t_2); + if (!(likely(PyBytes_CheckExact(__pyx_t_2))||((__pyx_t_2) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_2)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_line, ((PyObject*)__pyx_t_2)); __pyx_t_2 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":44 + /* "sklearn/datasets/_svmlight_format.pyx":56 * for line in f: * # skip comments * line_cstr = line # <<<<<<<<<<<<<< * hash_ptr = strchr(line_cstr, '#') * if hash_ptr != NULL: */ - __pyx_t_7 = PyBytes_AsString(((PyObject *)__pyx_v_line)); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_line_cstr = __pyx_t_7; + __pyx_t_6 = __Pyx_PyObject_AsString(((PyObject *)__pyx_v_line)); if (unlikely((!__pyx_t_6) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_line_cstr = __pyx_t_6; - /* "sklearn/datasets/_svmlight_format.pyx":45 + /* "sklearn/datasets/_svmlight_format.pyx":57 * # skip comments * line_cstr = line * hash_ptr = strchr(line_cstr, '#') # <<<<<<<<<<<<<< @@ -1478,281 +1902,461 @@ static PyObject *__pyx_pf_7sklearn_8datasets_16_svmlight_format__load_svmlight_f */ __pyx_v_hash_ptr = strchr(__pyx_v_line_cstr, '#'); - /* "sklearn/datasets/_svmlight_format.pyx":46 + /* "sklearn/datasets/_svmlight_format.pyx":58 * line_cstr = line * hash_ptr = strchr(line_cstr, '#') * if hash_ptr != NULL: # <<<<<<<<<<<<<< * line = line[:hash_ptr - line_cstr] * */ - __pyx_t_8 = (__pyx_v_hash_ptr != NULL); - if (__pyx_t_8) { + __pyx_t_3 = ((__pyx_v_hash_ptr != NULL) != 0); + if (__pyx_t_3) { - /* "sklearn/datasets/_svmlight_format.pyx":47 + /* "sklearn/datasets/_svmlight_format.pyx":59 * hash_ptr = strchr(line_cstr, '#') * if hash_ptr != NULL: * line = line[:hash_ptr - line_cstr] # <<<<<<<<<<<<<< * * line_parts = line.split() */ - __pyx_t_2 = __Pyx_PySequence_GetSlice(((PyObject *)__pyx_v_line), 0, (__pyx_v_hash_ptr - __pyx_v_line_cstr)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(((PyObject *)__pyx_v_line) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_2 = __Pyx_PySequence_GetSlice(((PyObject *)__pyx_v_line), 0, (__pyx_v_hash_ptr - __pyx_v_line_cstr)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_DECREF(((PyObject *)__pyx_v_line)); - __pyx_v_line = __pyx_t_2; + __Pyx_DECREF_SET(__pyx_v_line, ((PyObject*)__pyx_t_2)); __pyx_t_2 = 0; - goto __pyx_L6; + goto __pyx_L7; } - __pyx_L6:; + __pyx_L7:; - /* "sklearn/datasets/_svmlight_format.pyx":49 + /* "sklearn/datasets/_svmlight_format.pyx":61 * line = line[:hash_ptr - line_cstr] * * line_parts = line.split() # <<<<<<<<<<<<<< * if len(line_parts) == 0: * continue */ - __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_line), __pyx_n_s__split); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_line), __pyx_n_s__split); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_v_line_parts); - __pyx_v_line_parts = __pyx_t_3; - __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_line_parts, __pyx_t_7); + __pyx_t_7 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":50 + /* "sklearn/datasets/_svmlight_format.pyx":62 * * line_parts = line.split() * if len(line_parts) == 0: # <<<<<<<<<<<<<< * continue * */ - __pyx_t_9 = PyObject_Length(__pyx_v_line_parts); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_8 = (__pyx_t_9 == 0); - if (__pyx_t_8) { + __pyx_t_8 = PyObject_Length(__pyx_v_line_parts); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((__pyx_t_8 == 0) != 0); + if (__pyx_t_3) { - /* "sklearn/datasets/_svmlight_format.pyx":51 + /* "sklearn/datasets/_svmlight_format.pyx":63 * line_parts = line.split() * if len(line_parts) == 0: * continue # <<<<<<<<<<<<<< * * target, features = line_parts[0], line_parts[1:] */ - goto __pyx_L4_continue; - goto __pyx_L7; + goto __pyx_L5_continue; + goto __pyx_L8; } - __pyx_L7:; + __pyx_L8:; - /* "sklearn/datasets/_svmlight_format.pyx":53 + /* "sklearn/datasets/_svmlight_format.pyx":65 * continue * * target, features = line_parts[0], line_parts[1:] # <<<<<<<<<<<<<< * if multilabel: * target = [float(y) for y in target.split(COMMA)] */ - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_line_parts, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PySequence_GetSlice(__pyx_v_line_parts, 1, PY_SSIZE_T_MAX); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_GetItemInt(__pyx_v_line_parts, 0, sizeof(long), PyInt_FromLong, 0, 0, 0); if (!__pyx_t_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_v_line_parts, 1, 0, NULL, NULL, &__pyx_k_slice_7, 1, 0, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_v_target); - __pyx_v_target = __pyx_t_3; - __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_features); - __pyx_v_features = __pyx_t_2; + __Pyx_XDECREF_SET(__pyx_v_target, __pyx_t_7); + __pyx_t_7 = 0; + __Pyx_XDECREF_SET(__pyx_v_features, __pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":54 + /* "sklearn/datasets/_svmlight_format.pyx":66 * * target, features = line_parts[0], line_parts[1:] * if multilabel: # <<<<<<<<<<<<<< * target = [float(y) for y in target.split(COMMA)] * target.sort() */ - if (__pyx_v_multilabel) { + __pyx_t_3 = (__pyx_v_multilabel != 0); + if (__pyx_t_3) { - /* "sklearn/datasets/_svmlight_format.pyx":55 + /* "sklearn/datasets/_svmlight_format.pyx":67 * target, features = line_parts[0], line_parts[1:] * if multilabel: * target = [float(y) for y in target.split(COMMA)] # <<<<<<<<<<<<<< * target.sort() * labels.append(tuple(target)) */ - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_v_target, __pyx_n_s__split); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_target, __pyx_n_s__split); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); __Pyx_INCREF(((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COMMA)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COMMA)); + PyTuple_SET_ITEM(__pyx_t_9, 0, ((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COMMA)); __Pyx_GIVEREF(((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COMMA)); - __pyx_t_10 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; if (PyList_CheckExact(__pyx_t_10) || PyTuple_CheckExact(__pyx_t_10)) { - __pyx_t_1 = __pyx_t_10; __Pyx_INCREF(__pyx_t_1); __pyx_t_9 = 0; + __pyx_t_9 = __pyx_t_10; __Pyx_INCREF(__pyx_t_9); __pyx_t_8 = 0; __pyx_t_11 = NULL; } else { - __pyx_t_9 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_t_10); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_11 = Py_TYPE(__pyx_t_1)->tp_iternext; + __pyx_t_8 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_11 = Py_TYPE(__pyx_t_9)->tp_iternext; } __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; for (;;) { - if (!__pyx_t_11 && PyList_CheckExact(__pyx_t_1)) { - if (__pyx_t_9 >= PyList_GET_SIZE(__pyx_t_1)) break; + if (!__pyx_t_11 && PyList_CheckExact(__pyx_t_9)) { + if (__pyx_t_8 >= PyList_GET_SIZE(__pyx_t_9)) break; #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_10 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_9); __Pyx_INCREF(__pyx_t_10); __pyx_t_9++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyList_GET_ITEM(__pyx_t_9, __pyx_t_8); __Pyx_INCREF(__pyx_t_10); __pyx_t_8++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else - __pyx_t_10 = PySequence_ITEM(__pyx_t_1, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PySequence_ITEM(__pyx_t_9, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif - } else if (!__pyx_t_11 && PyTuple_CheckExact(__pyx_t_1)) { - if (__pyx_t_9 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + } else if (!__pyx_t_11 && PyTuple_CheckExact(__pyx_t_9)) { + if (__pyx_t_8 >= PyTuple_GET_SIZE(__pyx_t_9)) break; #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_10 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_9); __Pyx_INCREF(__pyx_t_10); __pyx_t_9++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_8); __Pyx_INCREF(__pyx_t_10); __pyx_t_8++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else - __pyx_t_10 = PySequence_ITEM(__pyx_t_1, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PySequence_ITEM(__pyx_t_9, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif } else { - __pyx_t_10 = __pyx_t_11(__pyx_t_1); + __pyx_t_10 = __pyx_t_11(__pyx_t_9); if (unlikely(!__pyx_t_10)) { if (PyErr_Occurred()) { if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } break; } __Pyx_GOTREF(__pyx_t_10); } - __Pyx_XDECREF(__pyx_v_y); - __pyx_v_y = __pyx_t_10; + __Pyx_XDECREF_SET(__pyx_v_y, __pyx_t_10); __pyx_t_10 = 0; - __pyx_t_12 = __Pyx_PyObject_AsDouble(__pyx_v_y); if (unlikely(__pyx_t_12 == ((double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = PyFloat_FromDouble(__pyx_t_12); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = __Pyx_PyObject_AsDouble(__pyx_v_y); if (unlikely(__pyx_t_12 == ((double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyFloat_FromDouble(__pyx_t_12); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_10); - if (unlikely(__Pyx_PyList_Append(__pyx_t_2, (PyObject*)__pyx_t_10))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_10))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_INCREF(((PyObject *)__pyx_t_2)); - __Pyx_DECREF(__pyx_v_target); - __pyx_v_target = ((PyObject *)__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF_SET(__pyx_v_target, ((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":56 + /* "sklearn/datasets/_svmlight_format.pyx":68 * if multilabel: * target = [float(y) for y in target.split(COMMA)] * target.sort() # <<<<<<<<<<<<<< * labels.append(tuple(target)) * else: */ - __pyx_t_2 = PyObject_GetAttr(__pyx_v_target, __pyx_n_s__sort); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_target, __pyx_n_s__sort); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __pyx_t_9 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":57 + /* "sklearn/datasets/_svmlight_format.pyx":69 * target = [float(y) for y in target.split(COMMA)] * target.sort() * labels.append(tuple(target)) # <<<<<<<<<<<<<< * else: - * labels.append(float(target)) + * array.resize_smart(labels, len(labels) + 1) */ - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); __Pyx_INCREF(__pyx_v_target); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_target); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_v_target); __Pyx_GIVEREF(__pyx_v_target); - __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject*)(&PyTuple_Type))), ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject*)(&PyTuple_Type))), ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Append(__pyx_v_labels, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_Append(__pyx_v_labels, __pyx_t_2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L8; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L9; } /*else*/ { - /* "sklearn/datasets/_svmlight_format.pyx":59 + /* "sklearn/datasets/_svmlight_format.pyx":71 * labels.append(tuple(target)) * else: - * labels.append(float(target)) # <<<<<<<<<<<<<< - * indptr.append(len(data)) + * array.resize_smart(labels, len(labels) + 1) # <<<<<<<<<<<<<< + * labels[len(labels) - 1] = float(target) * */ - __pyx_t_12 = __Pyx_PyObject_AsDouble(__pyx_v_target); if (unlikely(__pyx_t_12 == ((double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = PyFloat_FromDouble(__pyx_t_12); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_Append(__pyx_v_labels, __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_L8:; + if (!(likely(__Pyx_TypeTest(__pyx_v_labels, __pyx_ptype_7cpython_5array_array)))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Length(__pyx_v_labels); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = resize_smart(((arrayobject *)__pyx_v_labels), (__pyx_t_8 + 1)); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/datasets/_svmlight_format.pyx":60 + /* "sklearn/datasets/_svmlight_format.pyx":72 * else: - * labels.append(float(target)) - * indptr.append(len(data)) # <<<<<<<<<<<<<< + * array.resize_smart(labels, len(labels) + 1) + * labels[len(labels) - 1] = float(target) # <<<<<<<<<<<<<< * * prev_idx = -1 */ - __pyx_t_9 = PyObject_Length(__pyx_v_data); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = PyInt_FromSsize_t(__pyx_t_9); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyObject_Append(__pyx_v_indptr, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_12 = __Pyx_PyObject_AsDouble(__pyx_v_target); if (unlikely(__pyx_t_12 == ((double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = PyFloat_FromDouble(__pyx_t_12); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_8 = PyObject_Length(__pyx_v_labels); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = (__pyx_t_8 - 1); + if (__Pyx_SetItemInt(__pyx_v_labels, __pyx_t_14, __pyx_t_9, sizeof(Py_ssize_t), PyInt_FromSsize_t, 0, 0, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + __pyx_L9:; - /* "sklearn/datasets/_svmlight_format.pyx":62 - * indptr.append(len(data)) + /* "sklearn/datasets/_svmlight_format.pyx":74 + * labels[len(labels) - 1] = float(target) * * prev_idx = -1 # <<<<<<<<<<<<<< - * for i in xrange(1, len(line_parts)): - * idx_s, value = line_parts[i].split(COLON, 1) + * n_features = len(features) + * if n_features and line_parts[1].startswith(qid_prefix): */ __pyx_v_prev_idx = -1; - /* "sklearn/datasets/_svmlight_format.pyx":63 + /* "sklearn/datasets/_svmlight_format.pyx":75 * * prev_idx = -1 - * for i in xrange(1, len(line_parts)): # <<<<<<<<<<<<<< - * idx_s, value = line_parts[i].split(COLON, 1) - * idx = np.int32(idx_s) + * n_features = len(features) # <<<<<<<<<<<<<< + * if n_features and line_parts[1].startswith(qid_prefix): + * _, value = line_parts[1].split(COLON, 1) */ - __pyx_t_9 = PyObject_Length(__pyx_v_line_parts); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - for (__pyx_t_13 = 1; __pyx_t_13 < __pyx_t_9; __pyx_t_13+=1) { - __pyx_v_i = __pyx_t_13; + __pyx_t_14 = PyObject_Length(__pyx_v_features); if (unlikely(__pyx_t_14 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_n_features = __pyx_t_14; - /* "sklearn/datasets/_svmlight_format.pyx":64 + /* "sklearn/datasets/_svmlight_format.pyx":76 * prev_idx = -1 - * for i in xrange(1, len(line_parts)): + * n_features = len(features) + * if n_features and line_parts[1].startswith(qid_prefix): # <<<<<<<<<<<<<< + * _, value = line_parts[1].split(COLON, 1) + * if query_id: + */ + if ((__pyx_v_n_features != 0)) { + __pyx_t_9 = __Pyx_GetItemInt(__pyx_v_line_parts, 1, sizeof(long), PyInt_FromLong, 0, 0, 0); if (!__pyx_t_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_n_s__startswith); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_INCREF(((PyObject *)__pyx_v_qid_prefix)); + PyTuple_SET_ITEM(__pyx_t_9, 0, ((PyObject *)__pyx_v_qid_prefix)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_qid_prefix)); + __pyx_t_10 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_15 = __pyx_t_3; + } else { + __pyx_t_15 = (__pyx_v_n_features != 0); + } + if (__pyx_t_15) { + + /* "sklearn/datasets/_svmlight_format.pyx":77 + * n_features = len(features) + * if n_features and line_parts[1].startswith(qid_prefix): + * _, value = line_parts[1].split(COLON, 1) # <<<<<<<<<<<<<< + * if query_id: + * array.resize_smart(query, len(query) + 1) + */ + __pyx_t_10 = __Pyx_GetItemInt(__pyx_v_line_parts, 1, sizeof(long), PyInt_FromLong, 0, 0, 0); if (!__pyx_t_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_10, __pyx_n_s__split); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_INCREF(((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COLON)); + PyTuple_SET_ITEM(__pyx_t_10, 0, ((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COLON)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COLON)); + __Pyx_INCREF(__pyx_int_1); + PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_int_1); + __Pyx_GIVEREF(__pyx_int_1); + __pyx_t_2 = PyObject_Call(__pyx_t_9, ((PyObject *)__pyx_t_10), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_10)); __pyx_t_10 = 0; + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_10 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_9 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_10 = PyList_GET_ITEM(sequence, 0); + __pyx_t_9 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_10); + __Pyx_INCREF(__pyx_t_9); + #else + __pyx_t_10 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_9 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else + { + Py_ssize_t index = -1; + __pyx_t_7 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_16 = Py_TYPE(__pyx_t_7)->tp_iternext; + index = 0; __pyx_t_10 = __pyx_t_16(__pyx_t_7); if (unlikely(!__pyx_t_10)) goto __pyx_L13_unpacking_failed; + __Pyx_GOTREF(__pyx_t_10); + index = 1; __pyx_t_9 = __pyx_t_16(__pyx_t_7); if (unlikely(!__pyx_t_9)) goto __pyx_L13_unpacking_failed; + __Pyx_GOTREF(__pyx_t_9); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_16(__pyx_t_7), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_16 = NULL; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L14_unpacking_done; + __pyx_L13_unpacking_failed:; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_16 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L14_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v__, __pyx_t_10); + __pyx_t_10 = 0; + __Pyx_XDECREF_SET(__pyx_v_value, __pyx_t_9); + __pyx_t_9 = 0; + + /* "sklearn/datasets/_svmlight_format.pyx":78 + * if n_features and line_parts[1].startswith(qid_prefix): + * _, value = line_parts[1].split(COLON, 1) + * if query_id: # <<<<<<<<<<<<<< + * array.resize_smart(query, len(query) + 1) + * query[len(query) - 1] = int(value) + */ + __pyx_t_15 = (__pyx_v_query_id != 0); + if (__pyx_t_15) { + + /* "sklearn/datasets/_svmlight_format.pyx":79 + * _, value = line_parts[1].split(COLON, 1) + * if query_id: + * array.resize_smart(query, len(query) + 1) # <<<<<<<<<<<<<< + * query[len(query) - 1] = int(value) + * line_parts.pop(1) + */ + __pyx_t_14 = Py_SIZE(((PyObject *)__pyx_v_query)); if (unlikely(__pyx_t_14 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = resize_smart(__pyx_v_query, (__pyx_t_14 + 1)); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/datasets/_svmlight_format.pyx":80 + * if query_id: + * array.resize_smart(query, len(query) + 1) + * query[len(query) - 1] = int(value) # <<<<<<<<<<<<<< + * line_parts.pop(1) + * n_features -= 1 + */ + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + __pyx_t_9 = PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_14 = Py_SIZE(((PyObject *)__pyx_v_query)); if (unlikely(__pyx_t_14 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = (__pyx_t_14 - 1); + if (__Pyx_SetItemInt(((PyObject *)__pyx_v_query), __pyx_t_8, __pyx_t_9, sizeof(Py_ssize_t), PyInt_FromSsize_t, 0, 0, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L15; + } + __pyx_L15:; + + /* "sklearn/datasets/_svmlight_format.pyx":81 + * array.resize_smart(query, len(query) + 1) + * query[len(query) - 1] = int(value) + * line_parts.pop(1) # <<<<<<<<<<<<<< + * n_features -= 1 + * + */ + __pyx_t_9 = __Pyx_PyObject_PopIndex(__pyx_v_line_parts, 1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "sklearn/datasets/_svmlight_format.pyx":82 + * query[len(query) - 1] = int(value) + * line_parts.pop(1) + * n_features -= 1 # <<<<<<<<<<<<<< + * + * for i in xrange(1, n_features + 1): + */ + __pyx_v_n_features = (__pyx_v_n_features - 1); + goto __pyx_L12; + } + __pyx_L12:; + + /* "sklearn/datasets/_svmlight_format.pyx":84 + * n_features -= 1 + * + * for i in xrange(1, n_features + 1): # <<<<<<<<<<<<<< + * idx_s, value = line_parts[i].split(COLON, 1) + * idx = int(idx_s) + */ + __pyx_t_8 = (__pyx_v_n_features + 1); + for (__pyx_t_14 = 1; __pyx_t_14 < __pyx_t_8; __pyx_t_14+=1) { + __pyx_v_i = __pyx_t_14; + + /* "sklearn/datasets/_svmlight_format.pyx":85 + * + * for i in xrange(1, n_features + 1): * idx_s, value = line_parts[i].split(COLON, 1) # <<<<<<<<<<<<<< - * idx = np.int32(idx_s) + * idx = int(idx_s) * if idx < 0 or not zero_based and idx == 0: */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_line_parts, __pyx_v_i, sizeof(Py_ssize_t), PyInt_FromSsize_t); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__split); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_GetItemInt(__pyx_v_line_parts, __pyx_v_i, sizeof(Py_ssize_t), PyInt_FromSsize_t, 0, 0, 0); if (!__pyx_t_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_n_s__split); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); __Pyx_INCREF(((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COLON)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COLON)); + PyTuple_SET_ITEM(__pyx_t_9, 0, ((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COLON)); __Pyx_GIVEREF(((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COLON)); __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_1); + PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_int_1); __Pyx_GIVEREF(__pyx_int_1); - __pyx_t_10 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_10); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; if ((likely(PyTuple_CheckExact(__pyx_t_10))) || (PyList_CheckExact(__pyx_t_10))) { PyObject* sequence = __pyx_t_10; #if CYTHON_COMPILING_IN_CPYTHON @@ -1763,311 +2367,259 @@ static PyObject *__pyx_pf_7sklearn_8datasets_16_svmlight_format__load_svmlight_f if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #if CYTHON_COMPILING_IN_CPYTHON if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_9 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); + __pyx_t_9 = PyList_GET_ITEM(sequence, 0); __pyx_t_2 = PyList_GET_ITEM(sequence, 1); } - __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_9); __Pyx_INCREF(__pyx_t_2); #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); #endif __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; } else { Py_ssize_t index = -1; - __pyx_t_3 = PyObject_GetIter(__pyx_t_10); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = PyObject_GetIter(__pyx_t_10); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_14 = Py_TYPE(__pyx_t_3)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_14(__pyx_t_3); if (unlikely(!__pyx_t_1)) goto __pyx_L13_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_14(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L13_unpacking_failed; + __pyx_t_16 = Py_TYPE(__pyx_t_7)->tp_iternext; + index = 0; __pyx_t_9 = __pyx_t_16(__pyx_t_7); if (unlikely(!__pyx_t_9)) goto __pyx_L18_unpacking_failed; + __Pyx_GOTREF(__pyx_t_9); + index = 1; __pyx_t_2 = __pyx_t_16(__pyx_t_7); if (unlikely(!__pyx_t_2)) goto __pyx_L18_unpacking_failed; __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_14(__pyx_t_3), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_14 = NULL; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L14_unpacking_done; - __pyx_L13_unpacking_failed:; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_14 = NULL; + if (__Pyx_IternextUnpackEndCheck(__pyx_t_16(__pyx_t_7), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_16 = NULL; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L19_unpacking_done; + __pyx_L18_unpacking_failed:; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_16 = NULL; if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_L14_unpacking_done:; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L19_unpacking_done:; } - __Pyx_XDECREF(__pyx_v_idx_s); - __pyx_v_idx_s = __pyx_t_1; - __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_v_value); - __pyx_v_value = __pyx_t_2; + __Pyx_XDECREF_SET(__pyx_v_idx_s, __pyx_t_9); + __pyx_t_9 = 0; + __Pyx_XDECREF_SET(__pyx_v_value, __pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":65 - * for i in xrange(1, len(line_parts)): + /* "sklearn/datasets/_svmlight_format.pyx":86 + * for i in xrange(1, n_features + 1): * idx_s, value = line_parts[i].split(COLON, 1) - * idx = np.int32(idx_s) # <<<<<<<<<<<<<< + * idx = int(idx_s) # <<<<<<<<<<<<<< * if idx < 0 or not zero_based and idx == 0: * raise ValueError( */ - __pyx_t_10 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_10, __pyx_n_s__int32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_10); __Pyx_INCREF(__pyx_v_idx_s); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_v_idx_s); __Pyx_GIVEREF(__pyx_v_idx_s); - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_10), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), ((PyObject *)__pyx_t_10), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(((PyObject *)__pyx_t_10)); __pyx_t_10 = 0; - __pyx_t_15 = __Pyx_PyInt_from_py_npy_int32(__pyx_t_1); if (unlikely((__pyx_t_15 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_idx = __pyx_t_15; + __pyx_t_13 = __Pyx_PyInt_AsInt(__pyx_t_2); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_idx = __pyx_t_13; - /* "sklearn/datasets/_svmlight_format.pyx":66 + /* "sklearn/datasets/_svmlight_format.pyx":87 * idx_s, value = line_parts[i].split(COLON, 1) - * idx = np.int32(idx_s) + * idx = int(idx_s) * if idx < 0 or not zero_based and idx == 0: # <<<<<<<<<<<<<< * raise ValueError( * "Invalid index %d in SVMlight/LibSVM data file." % idx) */ - __pyx_t_8 = (__pyx_v_idx < 0); - if (!__pyx_t_8) { - __pyx_t_16 = (!__pyx_v_zero_based); - if (__pyx_t_16) { - __pyx_t_17 = (__pyx_v_idx == 0); + __pyx_t_15 = ((__pyx_v_idx < 0) != 0); + if (!__pyx_t_15) { + __pyx_t_3 = ((!(__pyx_v_zero_based != 0)) != 0); + if (__pyx_t_3) { + __pyx_t_17 = ((__pyx_v_idx == 0) != 0); __pyx_t_18 = __pyx_t_17; } else { - __pyx_t_18 = __pyx_t_16; + __pyx_t_18 = __pyx_t_3; } - __pyx_t_16 = __pyx_t_18; + __pyx_t_3 = __pyx_t_18; } else { - __pyx_t_16 = __pyx_t_8; + __pyx_t_3 = __pyx_t_15; } - if (__pyx_t_16) { + if (__pyx_t_3) { - /* "sklearn/datasets/_svmlight_format.pyx":68 + /* "sklearn/datasets/_svmlight_format.pyx":89 * if idx < 0 or not zero_based and idx == 0: * raise ValueError( * "Invalid index %d in SVMlight/LibSVM data file." % idx) # <<<<<<<<<<<<<< * if idx <= prev_idx: - * raise ValueError("Feature ndices in SVMlight/LibSVM data " + * raise ValueError("Feature indices in SVMlight/LibSVM data " */ - __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_idx); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_10 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_1), __pyx_t_1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyInt_FromLong(__pyx_v_idx); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_10 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_8), __pyx_t_2); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_10)); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_10)); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_10)); __Pyx_GIVEREF(((PyObject *)__pyx_t_10)); __pyx_t_10 = 0; - __pyx_t_10 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; __Pyx_Raise(__pyx_t_10, 0, 0, 0); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L15; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L20; } - __pyx_L15:; + __pyx_L20:; - /* "sklearn/datasets/_svmlight_format.pyx":69 + /* "sklearn/datasets/_svmlight_format.pyx":90 * raise ValueError( * "Invalid index %d in SVMlight/LibSVM data file." % idx) * if idx <= prev_idx: # <<<<<<<<<<<<<< - * raise ValueError("Feature ndices in SVMlight/LibSVM data " + * raise ValueError("Feature indices in SVMlight/LibSVM data " * "file should be sorted and unique.") */ - __pyx_t_16 = (__pyx_v_idx <= __pyx_v_prev_idx); - if (__pyx_t_16) { + __pyx_t_3 = ((__pyx_v_idx <= __pyx_v_prev_idx) != 0); + if (__pyx_t_3) { - /* "sklearn/datasets/_svmlight_format.pyx":70 + /* "sklearn/datasets/_svmlight_format.pyx":91 * "Invalid index %d in SVMlight/LibSVM data file." % idx) * if idx <= prev_idx: - * raise ValueError("Feature ndices in SVMlight/LibSVM data " # <<<<<<<<<<<<<< + * raise ValueError("Feature indices in SVMlight/LibSVM data " # <<<<<<<<<<<<<< * "file should be sorted and unique.") - * indices.append(idx) + * */ - __pyx_t_10 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_3), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_10); __Pyx_Raise(__pyx_t_10, 0, 0, 0); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L16; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L21; } - __pyx_L16:; - - /* "sklearn/datasets/_svmlight_format.pyx":72 - * raise ValueError("Feature ndices in SVMlight/LibSVM data " - * "file should be sorted and unique.") - * indices.append(idx) # <<<<<<<<<<<<<< - * data.append(dtype(value)) - * prev_idx = idx - */ - __pyx_t_10 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_idx); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_1 = __Pyx_PyObject_Append(__pyx_v_indices, __pyx_t_10); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_L21:; - /* "sklearn/datasets/_svmlight_format.pyx":73 + /* "sklearn/datasets/_svmlight_format.pyx":94 * "file should be sorted and unique.") - * indices.append(idx) - * data.append(dtype(value)) # <<<<<<<<<<<<<< - * prev_idx = idx * - */ - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_value); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - __pyx_t_10 = PyObject_Call(__pyx_v_dtype, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Append(__pyx_v_data, __pyx_t_10); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "sklearn/datasets/_svmlight_format.pyx":74 - * indices.append(idx) - * data.append(dtype(value)) - * prev_idx = idx # <<<<<<<<<<<<<< + * array.resize_smart(indices, len(indices) + 1) # <<<<<<<<<<<<<< + * indices[len(indices) - 1] = idx * - * indptr.append(len(data)) */ - __pyx_v_prev_idx = __pyx_v_idx; - } - __pyx_L4_continue:; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_19 = Py_SIZE(((PyObject *)__pyx_v_indices)); if (unlikely(__pyx_t_19 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = resize_smart(__pyx_v_indices, (__pyx_t_19 + 1)); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/datasets/_svmlight_format.pyx":76 - * prev_idx = idx + /* "sklearn/datasets/_svmlight_format.pyx":95 * - * indptr.append(len(data)) # <<<<<<<<<<<<<< + * array.resize_smart(indices, len(indices) + 1) + * indices[len(indices) - 1] = idx # <<<<<<<<<<<<<< * - * indptr = indptr.get() + * array.resize_smart(data, len(data) + 1) */ - __pyx_t_5 = PyObject_Length(__pyx_v_data); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PyInt_FromSsize_t(__pyx_t_5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_Append(__pyx_v_indptr, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_10 = PyInt_FromLong(__pyx_v_idx); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_19 = Py_SIZE(((PyObject *)__pyx_v_indices)); if (unlikely(__pyx_t_19 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_20 = (__pyx_t_19 - 1); + if (__Pyx_SetItemInt(((PyObject *)__pyx_v_indices), __pyx_t_20, __pyx_t_10, sizeof(Py_ssize_t), PyInt_FromSsize_t, 0, 0, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":78 - * indptr.append(len(data)) + /* "sklearn/datasets/_svmlight_format.pyx":97 + * indices[len(indices) - 1] = idx + * + * array.resize_smart(data, len(data) + 1) # <<<<<<<<<<<<<< + * data[len(data) - 1] = float(value) * - * indptr = indptr.get() # <<<<<<<<<<<<<< - * data = data.get() - * indices = indices.get() */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_indptr, __pyx_n_s__get); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_v_indptr); - __pyx_v_indptr = __pyx_t_4; - __pyx_t_4 = 0; + __pyx_t_20 = Py_SIZE(((PyObject *)__pyx_v_data)); if (unlikely(__pyx_t_20 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = resize_smart(__pyx_v_data, (__pyx_t_20 + 1)); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/datasets/_svmlight_format.pyx":79 + /* "sklearn/datasets/_svmlight_format.pyx":98 * - * indptr = indptr.get() - * data = data.get() # <<<<<<<<<<<<<< - * indices = indices.get() + * array.resize_smart(data, len(data) + 1) + * data[len(data) - 1] = float(value) # <<<<<<<<<<<<<< * + * prev_idx = idx */ - __pyx_t_4 = PyObject_GetAttr(__pyx_v_data, __pyx_n_s__get); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_v_data); - __pyx_v_data = __pyx_t_1; - __pyx_t_1 = 0; + __pyx_t_12 = __Pyx_PyObject_AsDouble(__pyx_v_value); if (unlikely(__pyx_t_12 == ((double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyFloat_FromDouble(__pyx_t_12); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_20 = Py_SIZE(((PyObject *)__pyx_v_data)); if (unlikely(__pyx_t_20 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_19 = (__pyx_t_20 - 1); + if (__Pyx_SetItemInt(((PyObject *)__pyx_v_data), __pyx_t_19, __pyx_t_10, sizeof(Py_ssize_t), PyInt_FromSsize_t, 0, 0, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":80 - * indptr = indptr.get() - * data = data.get() - * indices = indices.get() # <<<<<<<<<<<<<< + /* "sklearn/datasets/_svmlight_format.pyx":100 + * data[len(data) - 1] = float(value) + * + * prev_idx = idx # <<<<<<<<<<<<<< * - * if not multilabel: + * array.resize_smart(indptr, len(indptr) + 1) */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_indices, __pyx_n_s__get); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_v_indices); - __pyx_v_indices = __pyx_t_4; - __pyx_t_4 = 0; + __pyx_v_prev_idx = __pyx_v_idx; + } - /* "sklearn/datasets/_svmlight_format.pyx":82 - * indices = indices.get() + /* "sklearn/datasets/_svmlight_format.pyx":102 + * prev_idx = idx * - * if not multilabel: # <<<<<<<<<<<<<< - * labels = labels.get() + * array.resize_smart(indptr, len(indptr) + 1) # <<<<<<<<<<<<<< + * indptr[len(indptr) - 1] = len(data) * */ - __pyx_t_16 = (!__pyx_v_multilabel); - if (__pyx_t_16) { + __pyx_t_8 = Py_SIZE(((PyObject *)__pyx_v_indptr)); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = resize_smart(__pyx_v_indptr, (__pyx_t_8 + 1)); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/datasets/_svmlight_format.pyx":83 + /* "sklearn/datasets/_svmlight_format.pyx":103 * - * if not multilabel: - * labels = labels.get() # <<<<<<<<<<<<<< + * array.resize_smart(indptr, len(indptr) + 1) + * indptr[len(indptr) - 1] = len(data) # <<<<<<<<<<<<<< * - * return data, indices, indptr, labels + * return (dtype, data, indices, indptr, labels, query) */ - __pyx_t_4 = PyObject_GetAttr(__pyx_v_labels, __pyx_n_s__get); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_v_labels); - __pyx_v_labels = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L17; + __pyx_t_8 = Py_SIZE(((PyObject *)__pyx_v_data)); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyInt_FromSsize_t(__pyx_t_8); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_8 = Py_SIZE(((PyObject *)__pyx_v_indptr)); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = (__pyx_t_8 - 1); + if (__Pyx_SetItemInt(((PyObject *)__pyx_v_indptr), __pyx_t_14, __pyx_t_10, sizeof(Py_ssize_t), PyInt_FromSsize_t, 0, 0, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_L5_continue:; } - __pyx_L17:; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":85 - * labels = labels.get() + /* "sklearn/datasets/_svmlight_format.pyx":105 + * indptr[len(indptr) - 1] = len(data) * - * return data, indices, indptr, labels # <<<<<<<<<<<<<< + * return (dtype, data, indices, indptr, labels, query) # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyTuple_New(6); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_data); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_data); - __Pyx_GIVEREF(__pyx_v_data); - __Pyx_INCREF(__pyx_v_indices); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_indices); - __Pyx_GIVEREF(__pyx_v_indices); - __Pyx_INCREF(__pyx_v_indptr); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_indptr); - __Pyx_GIVEREF(__pyx_v_indptr); + __Pyx_INCREF(__pyx_v_dtype); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_dtype); + __Pyx_GIVEREF(__pyx_v_dtype); + __Pyx_INCREF(((PyObject *)__pyx_v_data)); + PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_data)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_data)); + __Pyx_INCREF(((PyObject *)__pyx_v_indices)); + PyTuple_SET_ITEM(__pyx_t_1, 2, ((PyObject *)__pyx_v_indices)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_indices)); + __Pyx_INCREF(((PyObject *)__pyx_v_indptr)); + PyTuple_SET_ITEM(__pyx_t_1, 3, ((PyObject *)__pyx_v_indptr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_indptr)); __Pyx_INCREF(__pyx_v_labels); - PyTuple_SET_ITEM(__pyx_t_1, 3, __pyx_v_labels); + PyTuple_SET_ITEM(__pyx_t_1, 4, __pyx_v_labels); __Pyx_GIVEREF(__pyx_v_labels); + __Pyx_INCREF(((PyObject *)__pyx_v_query)); + PyTuple_SET_ITEM(__pyx_t_1, 5, ((PyObject *)__pyx_v_query)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_query)); __pyx_r = ((PyObject *)__pyx_t_1); __pyx_t_1 = 0; goto __pyx_L0; @@ -2077,31 +2629,541 @@ static PyObject *__pyx_pf_7sklearn_8datasets_16_svmlight_format__load_svmlight_f __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); __Pyx_XDECREF(__pyx_t_10); __Pyx_AddTraceback("sklearn.datasets._svmlight_format._load_svmlight_file", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_data); + __Pyx_XDECREF((PyObject *)__pyx_v_indices); + __Pyx_XDECREF((PyObject *)__pyx_v_indptr); + __Pyx_XDECREF((PyObject *)__pyx_v_query); __Pyx_XDECREF(__pyx_v_line); - __Pyx_XDECREF(__pyx_v_data); - __Pyx_XDECREF(__pyx_v_indptr); - __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XDECREF(__pyx_v_qid_prefix); __Pyx_XDECREF(__pyx_v_labels); __Pyx_XDECREF(__pyx_v_line_parts); __Pyx_XDECREF(__pyx_v_target); __Pyx_XDECREF(__pyx_v_features); - __Pyx_XDECREF(__pyx_v_idx_s); + __Pyx_XDECREF(__pyx_v__); __Pyx_XDECREF(__pyx_v_value); + __Pyx_XDECREF(__pyx_v_idx_s); __Pyx_XDECREF(__pyx_v_y); + __Pyx_XDECREF(__pyx_v_dtype); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* Python wrapper */ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +static CYTHON_UNUSED int __pyx_pw_7cpython_5array_5array_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_7cpython_5array_5array_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_7cpython_5array_5array___getbuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":91 + * __data_union data + * + * def __getbuffer__(array self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags) { + CYTHON_UNUSED unsigned int __pyx_v_itemsize; + int __pyx_r; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "array.pxd":98 + * cdef unsigned rows, columns, itemsize + * + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.buf = self.data.as_chars + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; + + /* "array.pxd":99 + * + * info.suboffsets = NULL + * info.buf = self.data.as_chars # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.ndim = 1 + */ + __pyx_t_1 = __pyx_v_self->data.as_chars; + __pyx_v_info->buf = __pyx_t_1; + + /* "array.pxd":100 + * info.suboffsets = NULL + * info.buf = self.data.as_chars + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.ndim = 1 + * info.itemsize = itemsize = self.ob_descr.itemsize # e.g. sizeof(float) + */ + __pyx_v_info->readonly = 0; + + /* "array.pxd":101 + * info.buf = self.data.as_chars + * info.readonly = 0 + * info.ndim = 1 # <<<<<<<<<<<<<< + * info.itemsize = itemsize = self.ob_descr.itemsize # e.g. sizeof(float) + * + */ + __pyx_v_info->ndim = 1; + + /* "array.pxd":102 + * info.readonly = 0 + * info.ndim = 1 + * info.itemsize = itemsize = self.ob_descr.itemsize # e.g. sizeof(float) # <<<<<<<<<<<<<< + * + * info.strides = \ + */ + __pyx_v_info->itemsize = __pyx_v_self->ob_descr->itemsize; + __pyx_v_itemsize = __pyx_v_self->ob_descr->itemsize; + + /* "array.pxd":104 + * info.itemsize = itemsize = self.ob_descr.itemsize # e.g. sizeof(float) + * + * info.strides = \ # <<<<<<<<<<<<<< + * stdlib.malloc(sizeof(Py_ssize_t) * info.ndim * 2 + 2) + * info.shape = info.strides + 1 + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc(((((sizeof(Py_ssize_t)) * __pyx_v_info->ndim) * 2) + 2))); + + /* "array.pxd":106 + * info.strides = \ + * stdlib.malloc(sizeof(Py_ssize_t) * info.ndim * 2 + 2) + * info.shape = info.strides + 1 # <<<<<<<<<<<<<< + * info.shape[0] = Py_SIZE(self) # number of items + * info.strides[0] = info.itemsize + */ + __pyx_v_info->shape = (__pyx_v_info->strides + 1); + + /* "array.pxd":107 + * stdlib.malloc(sizeof(Py_ssize_t) * info.ndim * 2 + 2) + * info.shape = info.strides + 1 + * info.shape[0] = Py_SIZE(self) # number of items # <<<<<<<<<<<<<< + * info.strides[0] = info.itemsize + * + */ + (__pyx_v_info->shape[0]) = Py_SIZE(((PyObject *)__pyx_v_self)); + + /* "array.pxd":108 + * info.shape = info.strides + 1 + * info.shape[0] = Py_SIZE(self) # number of items + * info.strides[0] = info.itemsize # <<<<<<<<<<<<<< + * + * info.format = (info.strides + 2 * info.ndim) + */ + __pyx_t_2 = __pyx_v_info->itemsize; + (__pyx_v_info->strides[0]) = __pyx_t_2; + + /* "array.pxd":110 + * info.strides[0] = info.itemsize + * + * info.format = (info.strides + 2 * info.ndim) # <<<<<<<<<<<<<< + * info.format[0] = self.ob_descr.typecode + * info.format[1] = 0 + */ + __pyx_v_info->format = ((char *)(__pyx_v_info->strides + (2 * __pyx_v_info->ndim))); + + /* "array.pxd":111 + * + * info.format = (info.strides + 2 * info.ndim) + * info.format[0] = self.ob_descr.typecode # <<<<<<<<<<<<<< + * info.format[1] = 0 + * info.obj = self + */ + __pyx_t_3 = __pyx_v_self->ob_descr->typecode; + (__pyx_v_info->format[0]) = __pyx_t_3; + + /* "array.pxd":112 + * info.format = (info.strides + 2 * info.ndim) + * info.format[0] = self.ob_descr.typecode + * info.format[1] = 0 # <<<<<<<<<<<<<< + * info.obj = self + * + */ + (__pyx_v_info->format[1]) = 0; + + /* "array.pxd":113 + * info.format[0] = self.ob_descr.typecode + * info.format[1] = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * def __releasebuffer__(array self, Py_buffer* info): + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + __pyx_r = 0; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_7cpython_5array_5array_2__releasebuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "array.pxd":115 + * info.obj = self + * + * def __releasebuffer__(array self, Py_buffer* info): # <<<<<<<<<<<<<< + * #if PyArray_HASFIELDS(self): + * # stdlib.free(info.format) + */ + +static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "array.pxd":119 + * # stdlib.free(info.format) + * #if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * + * array newarrayobject(PyTypeObject* type, Py_ssize_t size, arraydescr *descr) + */ + free(__pyx_v_info->strides); + + __Pyx_RefNannyFinishContext(); +} + +/* "array.pxd":130 + * + * + * cdef inline array clone(array template, Py_ssize_t length, bint zero): # <<<<<<<<<<<<<< + * """ fast creation of a new array, given a template array. + * type will be same as template. + */ + +static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_clone(arrayobject *__pyx_v_template, Py_ssize_t __pyx_v_length, int __pyx_v_zero) { + arrayobject *__pyx_v_op = 0; + arrayobject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("clone", 0); + + /* "array.pxd":135 + * if zero is true, new array will be initialized with zeroes.""" + * cdef array op + * op = newarrayobject(Py_TYPE(template), length, template.ob_descr) # <<<<<<<<<<<<<< + * if zero and op is not None: + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) + */ + __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_template)), __pyx_v_length, __pyx_v_template->ob_descr)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_op = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "array.pxd":136 + * cdef array op + * op = newarrayobject(Py_TYPE(template), length, template.ob_descr) + * if zero and op is not None: # <<<<<<<<<<<<<< + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) + * return op + */ + if ((__pyx_v_zero != 0)) { + __pyx_t_2 = (((PyObject *)__pyx_v_op) != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + } else { + __pyx_t_3 = (__pyx_v_zero != 0); + } + if (__pyx_t_3) { + + /* "array.pxd":137 + * op = newarrayobject(Py_TYPE(template), length, template.ob_descr) + * if zero and op is not None: + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) # <<<<<<<<<<<<<< + * return op + * + */ + memset(__pyx_v_op->data.as_chars, 0, (__pyx_v_length * __pyx_v_op->ob_descr->itemsize)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "array.pxd":138 + * if zero and op is not None: + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) + * return op # <<<<<<<<<<<<<< + * + * cdef inline array copy(array self): + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_op)); + __pyx_r = __pyx_v_op; + goto __pyx_L0; + + __pyx_r = ((arrayobject *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("cpython.array.clone", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_op); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":140 + * return op + * + * cdef inline array copy(array self): # <<<<<<<<<<<<<< + * """ make a copy of an array. """ + * cdef array op + */ + +static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_copy(arrayobject *__pyx_v_self) { + arrayobject *__pyx_v_op = 0; + arrayobject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "array.pxd":143 + * """ make a copy of an array. """ + * cdef array op + * op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) # <<<<<<<<<<<<<< + * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) + * return op + */ + __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_self)), Py_SIZE(((PyObject *)__pyx_v_self)), __pyx_v_self->ob_descr)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_op = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "array.pxd":144 + * cdef array op + * op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) + * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) # <<<<<<<<<<<<<< + * return op + * + */ + memcpy(__pyx_v_op->data.as_chars, __pyx_v_self->data.as_chars, (Py_SIZE(((PyObject *)__pyx_v_op)) * __pyx_v_op->ob_descr->itemsize)); + + /* "array.pxd":145 + * op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) + * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) + * return op # <<<<<<<<<<<<<< + * + * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_op)); + __pyx_r = __pyx_v_op; + goto __pyx_L0; + + __pyx_r = ((arrayobject *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("cpython.array.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_op); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":147 + * return op + * + * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: # <<<<<<<<<<<<<< + * """ efficent appending of new stuff of same type + * (e.g. of same array type) + */ + +static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *__pyx_v_self, char *__pyx_v_stuff, Py_ssize_t __pyx_v_n) { + Py_ssize_t __pyx_v_itemsize; + Py_ssize_t __pyx_v_orgsize; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("extend_buffer", 0); + + /* "array.pxd":151 + * (e.g. of same array type) + * n: number of elements (not number of bytes!) """ + * cdef Py_ssize_t itemsize = self.ob_descr.itemsize # <<<<<<<<<<<<<< + * cdef Py_ssize_t orgsize = Py_SIZE(self) + * resize_smart(self, orgsize + n) + */ + __pyx_t_1 = __pyx_v_self->ob_descr->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "array.pxd":152 + * n: number of elements (not number of bytes!) """ + * cdef Py_ssize_t itemsize = self.ob_descr.itemsize + * cdef Py_ssize_t orgsize = Py_SIZE(self) # <<<<<<<<<<<<<< + * resize_smart(self, orgsize + n) + * memcpy(self.data.as_chars + orgsize * itemsize, stuff, n * itemsize) + */ + __pyx_v_orgsize = Py_SIZE(((PyObject *)__pyx_v_self)); + + /* "array.pxd":153 + * cdef Py_ssize_t itemsize = self.ob_descr.itemsize + * cdef Py_ssize_t orgsize = Py_SIZE(self) + * resize_smart(self, orgsize + n) # <<<<<<<<<<<<<< + * memcpy(self.data.as_chars + orgsize * itemsize, stuff, n * itemsize) + * return 0 + */ + __pyx_t_1 = resize_smart(__pyx_v_self, (__pyx_v_orgsize + __pyx_v_n)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "array.pxd":154 + * cdef Py_ssize_t orgsize = Py_SIZE(self) + * resize_smart(self, orgsize + n) + * memcpy(self.data.as_chars + orgsize * itemsize, stuff, n * itemsize) # <<<<<<<<<<<<<< + * return 0 + * + */ + memcpy((__pyx_v_self->data.as_chars + (__pyx_v_orgsize * __pyx_v_itemsize)), __pyx_v_stuff, (__pyx_v_n * __pyx_v_itemsize)); + + /* "array.pxd":155 + * resize_smart(self, orgsize + n) + * memcpy(self.data.as_chars + orgsize * itemsize, stuff, n * itemsize) + * return 0 # <<<<<<<<<<<<<< + * + * cdef inline int extend(array self, array other) except -1: + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("cpython.array.extend_buffer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":157 + * return 0 + * + * cdef inline int extend(array self, array other) except -1: # <<<<<<<<<<<<<< + * """ extend array with data from another array; types must match. """ + * if self.ob_descr.typecode != other.ob_descr.typecode: + */ + +static CYTHON_INLINE int __pyx_f_7cpython_5array_extend(arrayobject *__pyx_v_self, arrayobject *__pyx_v_other) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("extend", 0); + + /* "array.pxd":159 + * cdef inline int extend(array self, array other) except -1: + * """ extend array with data from another array; types must match. """ + * if self.ob_descr.typecode != other.ob_descr.typecode: # <<<<<<<<<<<<<< + * PyErr_BadArgument() + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) + */ + __pyx_t_1 = ((__pyx_v_self->ob_descr->typecode != __pyx_v_other->ob_descr->typecode) != 0); + if (__pyx_t_1) { + + /* "array.pxd":160 + * """ extend array with data from another array; types must match. """ + * if self.ob_descr.typecode != other.ob_descr.typecode: + * PyErr_BadArgument() # <<<<<<<<<<<<<< + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) + * + */ + __pyx_t_2 = PyErr_BadArgument(); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "array.pxd":161 + * if self.ob_descr.typecode != other.ob_descr.typecode: + * PyErr_BadArgument() + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) # <<<<<<<<<<<<<< + * + * cdef inline void zero(array op): + */ + __pyx_t_2 = __pyx_f_7cpython_5array_extend_buffer(__pyx_v_self, __pyx_v_other->data.as_chars, Py_SIZE(((PyObject *)__pyx_v_other))); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("cpython.array.extend", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":163 + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) + * + * cdef inline void zero(array op): # <<<<<<<<<<<<<< + * """ set all elements of array to zero. """ + * memset(op.data.as_chars, 0, Py_SIZE(op) * op.ob_descr.itemsize) + */ + +static CYTHON_INLINE void __pyx_f_7cpython_5array_zero(arrayobject *__pyx_v_op) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("zero", 0); + + /* "array.pxd":165 + * cdef inline void zero(array op): + * """ set all elements of array to zero. """ + * memset(op.data.as_chars, 0, Py_SIZE(op) * op.ob_descr.itemsize) # <<<<<<<<<<<<<< + */ + memset(__pyx_v_op->data.as_chars, 0, (Py_SIZE(((PyObject *)__pyx_v_op)) * __pyx_v_op->ob_descr->itemsize)); + + __Pyx_RefNannyFinishContext(); +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); @@ -2156,7 +3218,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * * cdef int copy_shape, i, ndim */ - __pyx_t_1 = (__pyx_v_info == NULL); + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; @@ -2198,7 +3260,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * copy_shape = 1 * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "numpy.pxd":209 @@ -2231,7 +3293,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_1) { /* "numpy.pxd":214 @@ -2241,7 +3303,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS)); + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; @@ -2255,11 +3317,11 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; @@ -2271,7 +3333,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_3) { /* "numpy.pxd":218 @@ -2281,7 +3343,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS)); + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; @@ -2295,11 +3357,11 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_7), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; @@ -2329,7 +3391,8 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ - if (__pyx_v_copy_shape) { + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { /* "numpy.pxd":226 * # Allocate new buffer for strides and shape info. @@ -2427,7 +3490,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); /* "numpy.pxd":239 * @@ -2445,8 +3508,10 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)__pyx_v_self->descr)); - __pyx_v_descr = __pyx_v_self->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; /* "numpy.pxd":244 * cdef int offset @@ -2464,9 +3529,9 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * # do not call releasebuffer * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; @@ -2511,7 +3576,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { /* "numpy.pxd":254 @@ -2521,7 +3586,8 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; /* "numpy.pxd":255 * if not hasfields: @@ -2530,9 +3596,9 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; + __pyx_t_2 = (__pyx_v_little_endian != 0); } else { __pyx_t_2 = __pyx_t_1; } @@ -2545,9 +3611,9 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_7 = __pyx_t_3; } else { __pyx_t_7 = __pyx_t_1; @@ -2565,236 +3631,211 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L12; } __pyx_L12:; - /* "numpy.pxd":258 + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "numpy.pxd":258 * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { + case NPY_BYTE: __pyx_v_f = __pyx_k__b; - goto __pyx_L13; - } + break; - /* "numpy.pxd":259 + /* "numpy.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { + case NPY_UBYTE: __pyx_v_f = __pyx_k__B; - goto __pyx_L13; - } + break; - /* "numpy.pxd":260 + /* "numpy.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { + case NPY_SHORT: __pyx_v_f = __pyx_k__h; - goto __pyx_L13; - } + break; - /* "numpy.pxd":261 + /* "numpy.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { + case NPY_USHORT: __pyx_v_f = __pyx_k__H; - goto __pyx_L13; - } + break; - /* "numpy.pxd":262 + /* "numpy.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { + case NPY_INT: __pyx_v_f = __pyx_k__i; - goto __pyx_L13; - } + break; - /* "numpy.pxd":263 + /* "numpy.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { + case NPY_UINT: __pyx_v_f = __pyx_k__I; - goto __pyx_L13; - } + break; - /* "numpy.pxd":264 + /* "numpy.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { + case NPY_LONG: __pyx_v_f = __pyx_k__l; - goto __pyx_L13; - } + break; - /* "numpy.pxd":265 + /* "numpy.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { + case NPY_ULONG: __pyx_v_f = __pyx_k__L; - goto __pyx_L13; - } + break; - /* "numpy.pxd":266 + /* "numpy.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { + case NPY_LONGLONG: __pyx_v_f = __pyx_k__q; - goto __pyx_L13; - } + break; - /* "numpy.pxd":267 + /* "numpy.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { + case NPY_ULONGLONG: __pyx_v_f = __pyx_k__Q; - goto __pyx_L13; - } + break; - /* "numpy.pxd":268 + /* "numpy.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { + case NPY_FLOAT: __pyx_v_f = __pyx_k__f; - goto __pyx_L13; - } + break; - /* "numpy.pxd":269 + /* "numpy.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { + case NPY_DOUBLE: __pyx_v_f = __pyx_k__d; - goto __pyx_L13; - } + break; - /* "numpy.pxd":270 + /* "numpy.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { + case NPY_LONGDOUBLE: __pyx_v_f = __pyx_k__g; - goto __pyx_L13; - } + break; - /* "numpy.pxd":271 + /* "numpy.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { + case NPY_CFLOAT: __pyx_v_f = __pyx_k__Zf; - goto __pyx_L13; - } + break; - /* "numpy.pxd":272 + /* "numpy.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { + case NPY_CDOUBLE: __pyx_v_f = __pyx_k__Zd; - goto __pyx_L13; - } + break; - /* "numpy.pxd":273 + /* "numpy.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { + case NPY_CLONGDOUBLE: __pyx_v_f = __pyx_k__Zg; - goto __pyx_L13; - } + break; - /* "numpy.pxd":274 + /* "numpy.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { + case NPY_OBJECT: __pyx_v_f = __pyx_k__O; - goto __pyx_L13; - } - /*else*/ { + break; + default: /* "numpy.pxd":276 * elif t == NPY_OBJECT: f = "O" @@ -2803,24 +3844,24 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_10), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_17), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_8)); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L13:; /* "numpy.pxd":277 * else: @@ -2878,7 +3919,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P * f[0] = c'\0' # Terminate format string * */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; /* "numpy.pxd":286 @@ -2916,8 +3957,8 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /* Python wrapper */ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); @@ -2944,7 +3985,7 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { /* "numpy.pxd":290 @@ -2966,7 +4007,7 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "numpy.pxd":292 @@ -3009,7 +4050,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3052,7 +4093,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3095,7 +4136,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3138,7 +4179,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3181,7 +4222,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3261,18 +4302,17 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; /* "numpy.pxd":795 @@ -3282,11 +4322,10 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; /* "numpy.pxd":796 @@ -3306,7 +4345,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); @@ -3314,22 +4353,24 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); #endif } else if (1) { - __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } else { Py_ssize_t index = -1; - __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; __Pyx_GOTREF(__pyx_t_3); index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; __Pyx_GOTREF(__pyx_t_4); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = NULL; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; goto __pyx_L6_unpacking_done; @@ -3337,15 +4378,13 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = NULL; if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_L6_unpacking_done:; } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; /* "numpy.pxd":798 @@ -3355,20 +4394,20 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { @@ -3379,11 +4418,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_19), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; @@ -3395,9 +4434,9 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_7 = (__pyx_v_child->byteorder == '>'); + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); if (__pyx_t_7) { - __pyx_t_8 = __pyx_v_little_endian; + __pyx_t_8 = (__pyx_v_little_endian != 0); } else { __pyx_t_8 = __pyx_t_7; } @@ -3410,9 +4449,9 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_7 = (__pyx_v_child->byteorder == '<'); + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_7) { - __pyx_t_9 = (!__pyx_v_little_endian); + __pyx_t_9 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_10 = __pyx_t_9; } else { __pyx_t_10 = __pyx_t_7; @@ -3430,11 +4469,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_13), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_20), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L8; } __pyx_L8:; @@ -3447,11 +4486,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!__pyx_t_7) break; @@ -3501,7 +4540,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * t = child.type_num * if end - f < 5: */ - __pyx_t_7 = (!PyDataType_HASFIELDS(__pyx_v_child)); + __pyx_t_7 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_7) { /* "numpy.pxd":821 @@ -3511,10 +4550,9 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_3); __pyx_t_3 = 0; /* "numpy.pxd":822 @@ -3524,7 +4562,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_7 = ((__pyx_v_end - __pyx_v_f) < 5); + __pyx_t_7 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_7) { /* "numpy.pxd":823 @@ -3534,11 +4572,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_22), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L12; } __pyx_L12:; @@ -3550,11 +4588,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 98; @@ -3568,11 +4606,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 66; @@ -3586,11 +4624,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 104; @@ -3604,11 +4642,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 72; @@ -3622,11 +4660,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 105; @@ -3640,11 +4678,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 73; @@ -3658,11 +4696,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 108; @@ -3676,11 +4714,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 76; @@ -3694,11 +4732,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 113; @@ -3712,11 +4750,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 81; @@ -3730,11 +4768,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 102; @@ -3748,11 +4786,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 100; @@ -3766,11 +4804,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 103; @@ -3784,11 +4822,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 90; @@ -3804,11 +4842,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 90; @@ -3824,11 +4862,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 90; @@ -3844,11 +4882,11 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 79; @@ -3863,19 +4901,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_10), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_17), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L13:; @@ -3898,7 +4936,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * return f * */ - __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_12; } __pyx_L11:; @@ -3946,6 +4984,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; + int __pyx_t_2; __Pyx_RefNannySetupContext("set_array_base", 0); /* "numpy.pxd":967 @@ -3956,7 +4995,8 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { /* "numpy.pxd":968 * cdef PyObject* baseptr @@ -4032,7 +5072,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py * return None * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { /* "numpy.pxd":977 @@ -4075,7 +5115,11 @@ static PyMethodDef __pyx_methods[] = { #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else PyModuleDef_HEAD_INIT, + #endif __Pyx_NAMESTR("_svmlight_format"), 0, /* m_doc */ -1, /* m_size */ @@ -4088,56 +5132,63 @@ static struct PyModuleDef __pyx_moduledef = { #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 0}, - {&__pyx_kp_u_10, __pyx_k_10, sizeof(__pyx_k_10), 0, 1, 0, 0}, {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, - {&__pyx_kp_u_14, __pyx_k_14, sizeof(__pyx_k_14), 0, 1, 0, 0}, - {&__pyx_n_s_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 1, 1}, - {&__pyx_n_s_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 0, 1, 1}, - {&__pyx_n_s_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 0, 1, 1}, - {&__pyx_kp_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 0}, - {&__pyx_kp_b_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 0, 0}, - {&__pyx_kp_b_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 0, 0}, - {&__pyx_kp_s_24, __pyx_k_24, sizeof(__pyx_k_24), 0, 0, 1, 0}, + {&__pyx_kp_u_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 1, 0, 0}, + {&__pyx_kp_u_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 1, 0, 0}, + {&__pyx_kp_u_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 1, 0, 0}, + {&__pyx_kp_u_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 1, 0, 0}, + {&__pyx_kp_u_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 1, 0, 0}, + {&__pyx_n_s_23, __pyx_k_23, sizeof(__pyx_k_23), 0, 0, 1, 1}, + {&__pyx_n_s_24, __pyx_k_24, sizeof(__pyx_k_24), 0, 0, 1, 1}, {&__pyx_n_s_25, __pyx_k_25, sizeof(__pyx_k_25), 0, 0, 1, 1}, - {&__pyx_kp_u_4, __pyx_k_4, sizeof(__pyx_k_4), 0, 1, 0, 0}, - {&__pyx_kp_u_6, __pyx_k_6, sizeof(__pyx_k_6), 0, 1, 0, 0}, - {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, - {&__pyx_n_s__ArrayBuilder, __pyx_k__ArrayBuilder, sizeof(__pyx_k__ArrayBuilder), 0, 0, 1, 1}, + {&__pyx_kp_b_26, __pyx_k_26, sizeof(__pyx_k_26), 0, 0, 0, 0}, + {&__pyx_kp_b_27, __pyx_k_27, sizeof(__pyx_k_27), 0, 0, 0, 0}, + {&__pyx_kp_s_30, __pyx_k_30, sizeof(__pyx_k_30), 0, 0, 1, 0}, + {&__pyx_n_s_31, __pyx_k_31, sizeof(__pyx_k_31), 0, 0, 1, 1}, + {&__pyx_kp_s_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 0, 1, 0}, + {&__pyx_kp_s_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 0, 1, 0}, {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s___INDICES_DTYPE, __pyx_k___INDICES_DTYPE, sizeof(__pyx_k___INDICES_DTYPE), 0, 0, 1, 1}, - {&__pyx_n_s___INDPTR_DTYPE, __pyx_k___INDPTR_DTYPE, sizeof(__pyx_k___INDPTR_DTYPE), 0, 0, 1, 1}, + {&__pyx_n_s___, __pyx_k___, sizeof(__pyx_k___), 0, 0, 1, 1}, + {&__pyx_n_s____import__, __pyx_k____import__, sizeof(__pyx_k____import__), 0, 0, 1, 1}, {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, {&__pyx_n_s___load_svmlight_file, __pyx_k___load_svmlight_file, sizeof(__pyx_k___load_svmlight_file), 0, 0, 1, 1}, - {&__pyx_n_s___temp_csr, __pyx_k___temp_csr, sizeof(__pyx_k___temp_csr), 0, 0, 1, 1}, - {&__pyx_n_s__csr_matrix, __pyx_k__csr_matrix, sizeof(__pyx_k__csr_matrix), 0, 0, 1, 1}, + {&__pyx_n_s__append, __pyx_k__append, sizeof(__pyx_k__append), 0, 0, 1, 1}, + {&__pyx_n_s__array, __pyx_k__array, sizeof(__pyx_k__array), 0, 0, 1, 1}, + {&__pyx_n_s__b, __pyx_k__b, sizeof(__pyx_k__b), 0, 0, 1, 1}, + {&__pyx_n_s__d, __pyx_k__d, sizeof(__pyx_k__d), 0, 0, 1, 1}, {&__pyx_n_s__data, __pyx_k__data, sizeof(__pyx_k__data), 0, 0, 1, 1}, - {&__pyx_n_s__double, __pyx_k__double, sizeof(__pyx_k__double), 0, 0, 1, 1}, {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, {&__pyx_n_s__f, __pyx_k__f, sizeof(__pyx_k__f), 0, 0, 1, 1}, {&__pyx_n_s__features, __pyx_k__features, sizeof(__pyx_k__features), 0, 0, 1, 1}, - {&__pyx_n_s__get, __pyx_k__get, sizeof(__pyx_k__get), 0, 0, 1, 1}, + {&__pyx_n_s__float32, __pyx_k__float32, sizeof(__pyx_k__float32), 0, 0, 1, 1}, + {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, {&__pyx_n_s__hash_ptr, __pyx_k__hash_ptr, sizeof(__pyx_k__hash_ptr), 0, 0, 1, 1}, {&__pyx_n_s__i, __pyx_k__i, sizeof(__pyx_k__i), 0, 0, 1, 1}, {&__pyx_n_s__idx, __pyx_k__idx, sizeof(__pyx_k__idx), 0, 0, 1, 1}, {&__pyx_n_s__idx_s, __pyx_k__idx_s, sizeof(__pyx_k__idx_s), 0, 0, 1, 1}, {&__pyx_n_s__indices, __pyx_k__indices, sizeof(__pyx_k__indices), 0, 0, 1, 1}, {&__pyx_n_s__indptr, __pyx_k__indptr, sizeof(__pyx_k__indptr), 0, 0, 1, 1}, - {&__pyx_n_s__int32, __pyx_k__int32, sizeof(__pyx_k__int32), 0, 0, 1, 1}, {&__pyx_n_s__labels, __pyx_k__labels, sizeof(__pyx_k__labels), 0, 0, 1, 1}, {&__pyx_n_s__line, __pyx_k__line, sizeof(__pyx_k__line), 0, 0, 1, 1}, {&__pyx_n_s__line_cstr, __pyx_k__line_cstr, sizeof(__pyx_k__line_cstr), 0, 0, 1, 1}, {&__pyx_n_s__line_parts, __pyx_k__line_parts, sizeof(__pyx_k__line_parts), 0, 0, 1, 1}, {&__pyx_n_s__multilabel, __pyx_k__multilabel, sizeof(__pyx_k__multilabel), 0, 0, 1, 1}, + {&__pyx_n_s__n_features, __pyx_k__n_features, sizeof(__pyx_k__n_features), 0, 0, 1, 1}, {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, + {&__pyx_n_s__pop, __pyx_k__pop, sizeof(__pyx_k__pop), 0, 0, 1, 1}, {&__pyx_n_s__prev_idx, __pyx_k__prev_idx, sizeof(__pyx_k__prev_idx), 0, 0, 1, 1}, + {&__pyx_n_s__qid, __pyx_k__qid, sizeof(__pyx_k__qid), 0, 0, 1, 1}, + {&__pyx_n_s__qid_prefix, __pyx_k__qid_prefix, sizeof(__pyx_k__qid_prefix), 0, 0, 1, 1}, + {&__pyx_n_s__query, __pyx_k__query, sizeof(__pyx_k__query), 0, 0, 1, 1}, + {&__pyx_n_s__query_id, __pyx_k__query_id, sizeof(__pyx_k__query_id), 0, 0, 1, 1}, {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, {&__pyx_n_s__sort, __pyx_k__sort, sizeof(__pyx_k__sort), 0, 0, 1, 1}, {&__pyx_n_s__sp, __pyx_k__sp, sizeof(__pyx_k__sp), 0, 0, 1, 1}, {&__pyx_n_s__split, __pyx_k__split, sizeof(__pyx_k__split), 0, 0, 1, 1}, + {&__pyx_n_s__startswith, __pyx_k__startswith, sizeof(__pyx_k__startswith), 0, 0, 1, 1}, {&__pyx_n_s__target, __pyx_k__target, sizeof(__pyx_k__target), 0, 0, 1, 1}, {&__pyx_n_s__value, __pyx_k__value, sizeof(__pyx_k__value), 0, 0, 1, 1}, {&__pyx_n_s__xrange, __pyx_k__xrange, sizeof(__pyx_k__xrange), 0, 0, 1, 1}, @@ -4147,13 +5198,13 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { }; static int __Pyx_InitCachedBuiltins(void) { #if PY_MAJOR_VERSION >= 3 - __pyx_builtin_xrange = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else - __pyx_builtin_xrange = __Pyx_GetName(__pyx_b, __pyx_n_s__xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -4163,19 +5214,93 @@ static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "sklearn/datasets/_svmlight_format.pyx":70 + /* "sklearn/datasets/_svmlight_format.pyx":35 + * cdef int idx, prev_idx + * cdef Py_ssize_t i + * cdef bytes qid_prefix = b('qid') # <<<<<<<<<<<<<< + * cdef Py_ssize_t n_features + * + */ + __pyx_k_tuple_1 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__qid)); if (unlikely(!__pyx_k_tuple_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_1); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_1)); + + /* "sklearn/datasets/_svmlight_format.pyx":41 + * # the Python code will do further conversions. + * if dtype == np.float32: + * data = array.array("f") # <<<<<<<<<<<<<< + * else: + * dtype = np.float64 + */ + __pyx_k_tuple_2 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__f)); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_2); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); + + /* "sklearn/datasets/_svmlight_format.pyx":44 + * else: + * dtype = np.float64 + * data = array.array("d") # <<<<<<<<<<<<<< + * indices = array.array("i") + * indptr = array.array("i", [0]) + */ + __pyx_k_tuple_3 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__d)); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_3); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_3)); + + /* "sklearn/datasets/_svmlight_format.pyx":45 + * dtype = np.float64 + * data = array.array("d") + * indices = array.array("i") # <<<<<<<<<<<<<< + * indptr = array.array("i", [0]) + * query = array.array("i") + */ + __pyx_k_tuple_4 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__i)); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_4); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); + + /* "sklearn/datasets/_svmlight_format.pyx":47 + * indices = array.array("i") + * indptr = array.array("i", [0]) + * query = array.array("i") # <<<<<<<<<<<<<< + * + * if multilabel: + */ + __pyx_k_tuple_5 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__i)); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_5); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); + + /* "sklearn/datasets/_svmlight_format.pyx":52 + * labels = [] + * else: + * labels = array.array("d") # <<<<<<<<<<<<<< + * + * for line in f: + */ + __pyx_k_tuple_6 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__d)); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_6); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); + + /* "sklearn/datasets/_svmlight_format.pyx":65 + * continue + * + * target, features = line_parts[0], line_parts[1:] # <<<<<<<<<<<<<< + * if multilabel: + * target = [float(y) for y in target.split(COMMA)] + */ + __pyx_k_slice_7 = PySlice_New(__pyx_int_1, Py_None, Py_None); if (unlikely(!__pyx_k_slice_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_slice_7); + __Pyx_GIVEREF(__pyx_k_slice_7); + + /* "sklearn/datasets/_svmlight_format.pyx":91 * "Invalid index %d in SVMlight/LibSVM data file." % idx) * if idx <= prev_idx: - * raise ValueError("Feature ndices in SVMlight/LibSVM data " # <<<<<<<<<<<<<< + * raise ValueError("Feature indices in SVMlight/LibSVM data " # <<<<<<<<<<<<<< * "file should be sorted and unique.") - * indices.append(idx) + * */ - __pyx_k_tuple_3 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_3); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_2)); - PyTuple_SET_ITEM(__pyx_k_tuple_3, 0, ((PyObject *)__pyx_kp_s_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_3)); + __pyx_k_tuple_10 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_9)); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_10); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) @@ -4184,12 +5309,9 @@ static int __Pyx_InitCachedConstants(void) { * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_5 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_5); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_4)); - PyTuple_SET_ITEM(__pyx_k_tuple_5, 0, ((PyObject *)__pyx_kp_u_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); + __pyx_k_tuple_12 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_11)); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_12); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) @@ -4198,12 +5320,9 @@ static int __Pyx_InitCachedConstants(void) { * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_7 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_7); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_6)); - PyTuple_SET_ITEM(__pyx_k_tuple_7, 0, ((PyObject *)__pyx_kp_u_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); + __pyx_k_tuple_14 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_13)); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_14); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); /* "numpy.pxd":257 * if ((descr.byteorder == c'>' and little_endian) or @@ -4212,12 +5331,9 @@ static int __Pyx_InitCachedConstants(void) { * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_9); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); + __pyx_k_tuple_16 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_15)); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_16); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); /* "numpy.pxd":799 * @@ -4226,12 +5342,9 @@ static int __Pyx_InitCachedConstants(void) { * * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_12); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); - PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + __pyx_k_tuple_19 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_18)); if (unlikely(!__pyx_k_tuple_19)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_19); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_19)); /* "numpy.pxd":803 * if ((child.byteorder == c'>' and little_endian) or @@ -4240,12 +5353,9 @@ static int __Pyx_InitCachedConstants(void) { * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_13 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_13); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 0, ((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); + __pyx_k_tuple_20 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_15)); if (unlikely(!__pyx_k_tuple_20)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_20); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_20)); /* "numpy.pxd":823 * t = child.type_num @@ -4254,98 +5364,21 @@ static int __Pyx_InitCachedConstants(void) { * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_15 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_15); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_14)); - PyTuple_SET_ITEM(__pyx_k_tuple_15, 0, ((PyObject *)__pyx_kp_u_14)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_14)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); - - /* "sklearn/datasets/_svmlight_format.pyx":18 - * # csr_matrix.indices and .indptr's dtypes are undocumented. We derive them - * # empirically. - * _temp_csr = sp.csr_matrix(0) # <<<<<<<<<<<<<< - * _INDICES_DTYPE = _temp_csr.indices.dtype - * _INDPTR_DTYPE = _temp_csr.indptr.dtype - */ - __pyx_k_tuple_19 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_19); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_19, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_19)); - - /* "sklearn/datasets/_svmlight_format.pyx":28 - * - * - * def _load_svmlight_file(f, dtype, bint multilabel, bint zero_based): # <<<<<<<<<<<<<< - * cdef bytes line - * cdef char *hash_ptr, *line_cstr - */ - __pyx_k_tuple_22 = PyTuple_New(20); if (unlikely(!__pyx_k_tuple_22)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_22 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_21)); if (unlikely(!__pyx_k_tuple_22)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_22); - __Pyx_INCREF(((PyObject *)__pyx_n_s__f)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 0, ((PyObject *)__pyx_n_s__f)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__f)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__dtype)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 1, ((PyObject *)__pyx_n_s__dtype)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__dtype)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__multilabel)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 2, ((PyObject *)__pyx_n_s__multilabel)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__multilabel)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__zero_based)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 3, ((PyObject *)__pyx_n_s__zero_based)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__zero_based)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__line)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 4, ((PyObject *)__pyx_n_s__line)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__line)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__hash_ptr)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 5, ((PyObject *)__pyx_n_s__hash_ptr)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__hash_ptr)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__line_cstr)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 6, ((PyObject *)__pyx_n_s__line_cstr)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__line_cstr)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__idx)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 7, ((PyObject *)__pyx_n_s__idx)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__idx)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__prev_idx)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 8, ((PyObject *)__pyx_n_s__prev_idx)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__prev_idx)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__i)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 9, ((PyObject *)__pyx_n_s__i)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__data)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 10, ((PyObject *)__pyx_n_s__data)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__data)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__indptr)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 11, ((PyObject *)__pyx_n_s__indptr)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__indptr)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__indices)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 12, ((PyObject *)__pyx_n_s__indices)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__indices)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__labels)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 13, ((PyObject *)__pyx_n_s__labels)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__labels)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__line_parts)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 14, ((PyObject *)__pyx_n_s__line_parts)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__line_parts)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__target)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 15, ((PyObject *)__pyx_n_s__target)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__target)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__features)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 16, ((PyObject *)__pyx_n_s__features)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__features)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__idx_s)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 17, ((PyObject *)__pyx_n_s__idx_s)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__idx_s)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__value)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 18, ((PyObject *)__pyx_n_s__value)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__value)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__y)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 19, ((PyObject *)__pyx_n_s__y)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__y)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_22)); - __pyx_k_codeobj_23 = (PyObject*)__Pyx_PyCode_New(4, 0, 20, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_22, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_24, __pyx_n_s___load_svmlight_file, 28, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/datasets/_svmlight_format.pyx":28 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def _load_svmlight_file(f, dtype, bint multilabel, bint zero_based, # <<<<<<<<<<<<<< + * bint query_id): + * cdef array.array data, indices, indptr, query + */ + __pyx_k_tuple_28 = PyTuple_Pack(25, ((PyObject *)__pyx_n_s__f), ((PyObject *)__pyx_n_s__dtype), ((PyObject *)__pyx_n_s__multilabel), ((PyObject *)__pyx_n_s__zero_based), ((PyObject *)__pyx_n_s__query_id), ((PyObject *)__pyx_n_s__data), ((PyObject *)__pyx_n_s__indices), ((PyObject *)__pyx_n_s__indptr), ((PyObject *)__pyx_n_s__query), ((PyObject *)__pyx_n_s__line), ((PyObject *)__pyx_n_s__hash_ptr), ((PyObject *)__pyx_n_s__line_cstr), ((PyObject *)__pyx_n_s__idx), ((PyObject *)__pyx_n_s__prev_idx), ((PyObject *)__pyx_n_s__i), ((PyObject *)__pyx_n_s__qid_prefix), ((PyObject *)__pyx_n_s__n_features), ((PyObject *)__pyx_n_s__labels), ((PyObject *)__pyx_n_s__line_parts), ((PyObject *)__pyx_n_s__target), ((PyObject *)__pyx_n_s__features), ((PyObject *)__pyx_n_s___), ((PyObject *)__pyx_n_s__value), ((PyObject *)__pyx_n_s__idx_s), ((PyObject *)__pyx_n_s__y)); if (unlikely(!__pyx_k_tuple_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_28); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_28)); + __pyx_k_codeobj_29 = (PyObject*)__Pyx_PyCode_New(5, 0, 25, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_28, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_30, __pyx_n_s___load_svmlight_file, 28, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -4373,6 +5406,9 @@ PyMODINIT_FUNC PyInit__svmlight_format(void) { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -4410,6 +5446,16 @@ PyMODINIT_FUNC PyInit__svmlight_format(void) __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.datasets._svmlight_format")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.datasets._svmlight_format", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); @@ -4417,6 +5463,9 @@ PyMODINIT_FUNC PyInit__svmlight_format(void) if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif if (__pyx_module_is_main_sklearn__datasets___svmlight_format) { if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } @@ -4437,172 +5486,127 @@ PyMODINIT_FUNC PyInit__svmlight_format(void) #else sizeof(PyHeapTypeObject), #endif - 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), 0); if (unlikely(!__pyx_ptype_7cpython_4bool_bool)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), 0); if (unlikely(!__pyx_ptype_7cpython_7complex_complex)) {__pyx_filename = __pyx_f[5]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_5array_array = __Pyx_ImportType("array", "array", sizeof(arrayobject), 0); if (unlikely(!__pyx_ptype_7cpython_5array_array)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ - /* "sklearn/datasets/_svmlight_format.pyx":10 - * from libc.string cimport strchr + /* "sklearn/datasets/_svmlight_format.pyx":8 + * # License: BSD 3 clause + * + * import array # <<<<<<<<<<<<<< + * from cpython cimport array + * cimport cython + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__array), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__array, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/datasets/_svmlight_format.pyx":14 + * * cimport numpy as np * import numpy as np # <<<<<<<<<<<<<< * import scipy.sparse as sp * */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":11 + /* "sklearn/datasets/_svmlight_format.pyx":15 * cimport numpy as np * import numpy as np * import scipy.sparse as sp # <<<<<<<<<<<<<< * - * from ..utils.arraybuilder import ArrayBuilder + * from ..externals.six import b */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)__pyx_n_s_17)); - PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s_17)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s_17)); - __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s_16), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(((PyObject *)__pyx_n_s_24)); + PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s_24)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s_24)); + __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s_23), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__sp, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s__sp, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/datasets/_svmlight_format.pyx":13 + /* "sklearn/datasets/_svmlight_format.pyx":17 * import scipy.sparse as sp * - * from ..utils.arraybuilder import ArrayBuilder # <<<<<<<<<<<<<< - * + * from ..externals.six import b # <<<<<<<<<<<<<< * + * np.import_array() */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_n_s__ArrayBuilder)); - PyList_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_n_s__ArrayBuilder)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__ArrayBuilder)); - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s_18), ((PyObject *)__pyx_t_2), 2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(((PyObject *)__pyx_n_s__b)); + PyList_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_n_s__b)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__b)); + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s_25), ((PyObject *)__pyx_t_2), 2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__ArrayBuilder); - if (__pyx_t_2 == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__ArrayBuilder); - if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__ArrayBuilder, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "sklearn/datasets/_svmlight_format.pyx":18 - * # csr_matrix.indices and .indptr's dtypes are undocumented. We derive them - * # empirically. - * _temp_csr = sp.csr_matrix(0) # <<<<<<<<<<<<<< - * _INDICES_DTYPE = _temp_csr.indices.dtype - * _INDPTR_DTYPE = _temp_csr.indptr.dtype - */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__sp); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__csr_matrix); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s__b); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_k_tuple_19), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__b, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___temp_csr, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "sklearn/datasets/_svmlight_format.pyx":19 - * # empirically. - * _temp_csr = sp.csr_matrix(0) - * _INDICES_DTYPE = _temp_csr.indices.dtype # <<<<<<<<<<<<<< - * _INDPTR_DTYPE = _temp_csr.indptr.dtype - * del _temp_csr - */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s___temp_csr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__indices); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___INDICES_DTYPE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "sklearn/datasets/_svmlight_format.pyx":20 - * _temp_csr = sp.csr_matrix(0) - * _INDICES_DTYPE = _temp_csr.indices.dtype - * _INDPTR_DTYPE = _temp_csr.indptr.dtype # <<<<<<<<<<<<<< - * del _temp_csr + * from ..externals.six import b * - */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s___temp_csr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__indptr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___INDPTR_DTYPE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "sklearn/datasets/_svmlight_format.pyx":21 - * _INDICES_DTYPE = _temp_csr.indices.dtype - * _INDPTR_DTYPE = _temp_csr.indptr.dtype - * del _temp_csr # <<<<<<<<<<<<<< + * np.import_array() # <<<<<<<<<<<<<< * * */ - if (__Pyx_DelAttrString(__pyx_m, "_temp_csr") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + import_array(); - /* "sklearn/datasets/_svmlight_format.pyx":24 + /* "sklearn/datasets/_svmlight_format.pyx":22 * * * cdef bytes COMMA = u','.encode('ascii') # <<<<<<<<<<<<<< * cdef bytes COLON = u':'.encode('ascii') * */ - if (!(likely(PyBytes_CheckExact(((PyObject *)__pyx_kp_b_20)))||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(((PyObject *)__pyx_kp_b_20))->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_INCREF(__pyx_kp_b_20); + if (!(likely(PyBytes_CheckExact(((PyObject *)__pyx_kp_b_26)))||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(((PyObject *)__pyx_kp_b_26))->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_kp_b_26); __Pyx_XGOTREF(((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COMMA)); - __Pyx_DECREF(((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COMMA)); - __Pyx_GIVEREF(__pyx_kp_b_20); - __pyx_v_7sklearn_8datasets_16_svmlight_format_COMMA = ((PyObject*)__pyx_kp_b_20); + __Pyx_DECREF_SET(__pyx_v_7sklearn_8datasets_16_svmlight_format_COMMA, ((PyObject*)__pyx_kp_b_26)); + __Pyx_GIVEREF(__pyx_kp_b_26); - /* "sklearn/datasets/_svmlight_format.pyx":25 + /* "sklearn/datasets/_svmlight_format.pyx":23 * * cdef bytes COMMA = u','.encode('ascii') * cdef bytes COLON = u':'.encode('ascii') # <<<<<<<<<<<<<< * * */ - if (!(likely(PyBytes_CheckExact(((PyObject *)__pyx_kp_b_21)))||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(((PyObject *)__pyx_kp_b_21))->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_INCREF(__pyx_kp_b_21); + if (!(likely(PyBytes_CheckExact(((PyObject *)__pyx_kp_b_27)))||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(((PyObject *)__pyx_kp_b_27))->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_kp_b_27); __Pyx_XGOTREF(((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COLON)); - __Pyx_DECREF(((PyObject *)__pyx_v_7sklearn_8datasets_16_svmlight_format_COLON)); - __Pyx_GIVEREF(__pyx_kp_b_21); - __pyx_v_7sklearn_8datasets_16_svmlight_format_COLON = ((PyObject*)__pyx_kp_b_21); + __Pyx_DECREF_SET(__pyx_v_7sklearn_8datasets_16_svmlight_format_COLON, ((PyObject*)__pyx_kp_b_27)); + __Pyx_GIVEREF(__pyx_kp_b_27); /* "sklearn/datasets/_svmlight_format.pyx":28 - * - * - * def _load_svmlight_file(f, dtype, bint multilabel, bint zero_based): # <<<<<<<<<<<<<< - * cdef bytes line - * cdef char *hash_ptr, *line_cstr + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def _load_svmlight_file(f, dtype, bint multilabel, bint zero_based, # <<<<<<<<<<<<<< + * bint query_id): + * cdef array.array data, indices, indptr, query */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_8datasets_16_svmlight_format_1_load_svmlight_file, NULL, __pyx_n_s_25); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_8datasets_16_svmlight_format_1_load_svmlight_file, NULL, __pyx_n_s_31); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___load_svmlight_file, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s___load_svmlight_file, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "sklearn/datasets/_svmlight_format.pyx":1 @@ -4612,7 +5616,7 @@ PyMODINIT_FUNC PyInit__svmlight_format(void) */ __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; /* "numpy.pxd":975 @@ -4658,17 +5662,15 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { } #endif /* CYTHON_REFNANNY */ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%s' is not defined", PyString_AS_STRING(name)); +#endif } return result; } @@ -4767,49 +5769,241 @@ static int __Pyx_ParseOptionalKeywords( values[name-argnames] = value; break; } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { +#if CYTHON_COMPILING_IN_CPYTHON + PyMappingMethods* mp; +#if PY_MAJOR_VERSION < 3 + PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; + if (likely(ms && ms->sq_slice)) { + if (!has_cstart) { + if (_py_start && (*_py_start != Py_None)) { + cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); + if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstart = 0; + } + if (!has_cstop) { + if (_py_stop && (*_py_stop != Py_None)) { + cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); + if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstop = PY_SSIZE_T_MAX; + } + if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { + Py_ssize_t l = ms->sq_length(obj); + if (likely(l >= 0)) { + if (cstop < 0) { + cstop += l; + if (cstop < 0) cstop = 0; + } + if (cstart < 0) { + cstart += l; + if (cstart < 0) cstart = 0; } + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + goto bad; } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } + return ms->sq_slice(obj, cstart, cstop); + } +#endif + mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_subscript)) +#endif + { + PyObject* result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; } else { - goto invalid_keyword; + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyInt_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyInt_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_COMPILING_IN_CPYTHON + result = mp->mp_subscript(obj, py_slice); +#else + result = PyObject_GetItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); } + return result; } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - goto bad; -invalid_keyword: PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif + "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); bad: - return -1; + return NULL; } static double __Pyx__PyObject_AsDouble(PyObject* obj) { @@ -4817,8 +6011,16 @@ static double __Pyx__PyObject_AsDouble(PyObject* obj) { #if CYTHON_COMPILING_IN_PYPY float_value = PyNumber_Float(obj); #else - if (Py_TYPE(obj)->tp_as_number && Py_TYPE(obj)->tp_as_number->nb_float) { - return PyFloat_AsDouble(obj); + PyNumberMethods *nb = Py_TYPE(obj)->tp_as_number; + if (likely(nb) && likely(nb->nb_float)) { + float_value = nb->nb_float(obj); + if (likely(float_value) && unlikely(!PyFloat_Check(float_value))) { + PyErr_Format(PyExc_TypeError, + "__float__ returned non-float (type %.200s)", + Py_TYPE(float_value)->tp_name); + Py_DECREF(float_value); + goto bad; + } } else if (PyUnicode_CheckExact(obj) || PyBytes_CheckExact(obj)) { #if PY_MAJOR_VERSION >= 3 float_value = PyFloat_FromString(obj); @@ -4843,6 +6045,76 @@ static double __Pyx__PyObject_AsDouble(PyObject* obj) { return (double)-1; } +static CYTHON_INLINE PyObject* __Pyx_PyObject_Append(PyObject* L, PyObject* x) { + if (likely(PyList_CheckExact(L))) { + if (unlikely(__Pyx_PyList_Append(L, x) < 0)) return NULL; + Py_INCREF(Py_None); + return Py_None; /* this is just to have an accurate signature */ + } else { + return __Pyx_PyObject_CallMethod1(L, __pyx_n_s__append, x); + } +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { + int r; + if (!j) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { + PyObject* old = PyList_GET_ITEM(o, n); + Py_INCREF(v); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 1; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return -1; + } + } + return m->sq_ass_item(o, i, v); + } + } +#else +#if CYTHON_COMPILING_IN_PYPY + if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) { +#else + if (is_list || PySequence_Check(o)) { +#endif + return PySequence_SetItem(o, i, v); + } +#endif + return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); +} + static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); @@ -4899,6 +6171,33 @@ static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { return 0; } +static PyObject* __Pyx_PyObject_PopIndex(PyObject* L, Py_ssize_t ix) { + PyObject *r, *py_ix; +#if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyList_CheckExact(L))) { + Py_ssize_t size = PyList_GET_SIZE(L); + if (likely(size > (((PyListObject*)L)->allocated >> 1))) { + Py_ssize_t cix = ix; + if (cix < 0) { + cix += size; + } + if (likely(0 <= cix && cix < size)) { + PyObject* v = PyList_GET_ITEM(L, cix); + Py_SIZE(L) -= 1; + size -= 1; + memmove(&PyList_GET_ITEM(L, cix), &PyList_GET_ITEM(L, cix+1), (size-cix)*sizeof(PyObject*)); + return v; + } + } + } +#endif + py_ix = PyInt_FromSsize_t(ix); + if (!py_ix) return NULL; + r = __Pyx_PyObject_CallMethod1(L, __pyx_n_s__pop, py_ix); + Py_DECREF(py_ix); + return r; +} + static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { #if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; @@ -4968,24 +6267,23 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, } value = type; #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } #endif } __Pyx_ErrRestore(type, value, tb); @@ -5023,8 +6321,7 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; - } - else + } else args = PyTuple_Pack(1, value); if (!args) goto bad; @@ -5045,18 +6342,22 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject "raise: exception class must be a subclass of BaseException"); goto bad; } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else if (cause && cause != Py_None) { +#endif PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; - } - else if (PyExceptionInstance_Check(cause)) { + } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); @@ -5084,28 +6385,31 @@ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; + return value; } -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s____import__); if (!py_import) goto bad; + #endif if (from_list) list = from_list; else { @@ -5125,13 +6429,17 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { - /* try package relative import first */ + #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(1); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; @@ -5142,12 +6450,17 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { } #endif if (!module) { + #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif } } #else @@ -5159,98 +6472,14 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { name, global_dict, empty_dict, list, NULL); #endif bad: - Py_XDECREF(empty_list); + #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } -static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name) { -#if PY_MAJOR_VERSION < 3 - PyErr_Format(PyExc_ImportError, "cannot import name %.230s", - PyString_AsString(name)); -#else - PyErr_Format(PyExc_ImportError, "cannot import name %S", name); -#endif -} - -static CYTHON_INLINE npy_int32 __Pyx_PyInt_from_py_npy_int32(PyObject* x) { - const npy_int32 neg_one = (npy_int32)-1, const_zero = (npy_int32)0; - const int is_unsigned = const_zero < neg_one; - if (sizeof(npy_int32) == sizeof(char)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedChar(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedChar(x); - } else if (sizeof(npy_int32) == sizeof(short)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedShort(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedShort(x); - } else if (sizeof(npy_int32) == sizeof(int)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedInt(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedInt(x); - } else if (sizeof(npy_int32) == sizeof(long)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedLong(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedLong(x); - } else if (sizeof(npy_int32) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedLongLong(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedLongLong(x); - } else { - npy_int32 val; - PyObject *v = __Pyx_PyNumber_Int(x); - #if PY_VERSION_HEX < 0x03000000 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } - return (npy_int32)-1; - } -} - -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32 val) { - const npy_int32 neg_one = (npy_int32)-1, const_zero = (npy_int32)0; - const int is_unsigned = const_zero < neg_one; - if ((sizeof(npy_int32) == sizeof(char)) || - (sizeof(npy_int32) == sizeof(short))) { - return PyInt_FromLong((long)val); - } else if ((sizeof(npy_int32) == sizeof(int)) || - (sizeof(npy_int32) == sizeof(long))) { - if (is_unsigned) - return PyLong_FromUnsignedLong((unsigned long)val); - else - return PyInt_FromLong((long)val); - } else if (sizeof(npy_int32) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); - else - return PyLong_FromLongLong((PY_LONG_LONG)val); - } else { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - return _PyLong_FromByteArray(bytes, sizeof(npy_int32), - little, !is_unsigned); - } -} - #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { @@ -5681,10 +6910,15 @@ static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { return (int)__Pyx_PyInt_AsLong(x); } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { const unsigned long neg_one = (unsigned long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -5697,6 +6931,16 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); @@ -5704,6 +6948,17 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { } return (unsigned long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (unsigned long)PyLong_AsLong(x); } } else { @@ -5716,10 +6971,15 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -5732,6 +6992,16 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned PY_LONG_LONG"); @@ -5739,6 +7009,17 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje } return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -5751,10 +7032,15 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { const long neg_one = (long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -5767,6 +7053,16 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); @@ -5774,6 +7070,17 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { } return (long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (long)PyLong_AsLong(x); } } else { @@ -5786,10 +7093,15 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -5802,6 +7114,16 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to PY_LONG_LONG"); @@ -5809,6 +7131,17 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { } return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -5821,10 +7154,15 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { const signed long neg_one = (signed long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -5837,6 +7175,16 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed long"); @@ -5844,6 +7192,17 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { } return (signed long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (signed long)PyLong_AsLong(x); } } else { @@ -5856,10 +7215,15 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -5872,6 +7236,16 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed PY_LONG_LONG"); @@ -5879,6 +7253,17 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* } return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (signed PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -5936,6 +7321,10 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; @@ -5955,7 +7344,19 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class module_name, class_name); goto bad; } - if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -5965,7 +7366,7 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%s.%s has the wrong size, try recompiling", module_name, class_name); @@ -6171,27 +7572,82 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } - -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (r < 0) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -6207,7 +7663,7 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { @@ -6225,7 +7681,6 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject* x = PyNumber_Index(b); @@ -6234,7 +7689,6 @@ static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) @@ -6248,14 +7702,12 @@ static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); #endif } - static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); + if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); return (size_t)-1; } return (size_t)val; diff --git a/sklearn/datasets/_svmlight_format.pyx b/sklearn/datasets/_svmlight_format.pyx index 4908c2a36cb32..9f8bb3e697207 100644 --- a/sklearn/datasets/_svmlight_format.pyx +++ b/sklearn/datasets/_svmlight_format.pyx @@ -3,41 +3,53 @@ # Authors: Mathieu Blondel # Lars Buitinck # Olivier Grisel -# License: Simple BSD. +# License: BSD 3 clause +import array +from cpython cimport array +cimport cython from libc.string cimport strchr + cimport numpy as np import numpy as np import scipy.sparse as sp -from ..utils.arraybuilder import ArrayBuilder - +from ..externals.six import b -# csr_matrix.indices and .indptr's dtypes are undocumented. We derive them -# empirically. -_temp_csr = sp.csr_matrix(0) -_INDICES_DTYPE = _temp_csr.indices.dtype -_INDPTR_DTYPE = _temp_csr.indptr.dtype -del _temp_csr +np.import_array() cdef bytes COMMA = u','.encode('ascii') cdef bytes COLON = u':'.encode('ascii') -def _load_svmlight_file(f, dtype, bint multilabel, bint zero_based): +@cython.boundscheck(False) +@cython.wraparound(False) +def _load_svmlight_file(f, dtype, bint multilabel, bint zero_based, + bint query_id): + cdef array.array data, indices, indptr, query cdef bytes line cdef char *hash_ptr, *line_cstr - cdef np.int32_t idx, prev_idx + cdef int idx, prev_idx cdef Py_ssize_t i + cdef bytes qid_prefix = b('qid') + cdef Py_ssize_t n_features + + # Special-case float32 but use float64 for everything else; + # the Python code will do further conversions. + if dtype == np.float32: + data = array.array("f") + else: + dtype = np.float64 + data = array.array("d") + indices = array.array("i") + indptr = array.array("i", [0]) + query = array.array("i") - data = ArrayBuilder(dtype=dtype) - indptr = ArrayBuilder(dtype=_INDPTR_DTYPE) - indices = ArrayBuilder(dtype=_INDICES_DTYPE) if multilabel: labels = [] else: - labels = ArrayBuilder(dtype=np.double) + labels = array.array("d") for line in f: # skip comments @@ -56,32 +68,38 @@ def _load_svmlight_file(f, dtype, bint multilabel, bint zero_based): target.sort() labels.append(tuple(target)) else: - labels.append(float(target)) - indptr.append(len(data)) + array.resize_smart(labels, len(labels) + 1) + labels[len(labels) - 1] = float(target) prev_idx = -1 - for i in xrange(1, len(line_parts)): + n_features = len(features) + if n_features and line_parts[1].startswith(qid_prefix): + _, value = line_parts[1].split(COLON, 1) + if query_id: + array.resize_smart(query, len(query) + 1) + query[len(query) - 1] = int(value) + line_parts.pop(1) + n_features -= 1 + + for i in xrange(1, n_features + 1): idx_s, value = line_parts[i].split(COLON, 1) - # XXX if we replace int with np.int32 in the line below, this - # function becomes twice as slow. idx = int(idx_s) if idx < 0 or not zero_based and idx == 0: raise ValueError( "Invalid index %d in SVMlight/LibSVM data file." % idx) if idx <= prev_idx: - raise ValueError("Feature ndices in SVMlight/LibSVM data " + raise ValueError("Feature indices in SVMlight/LibSVM data " "file should be sorted and unique.") - indices.append(idx) - data.append(dtype(value)) - prev_idx = idx - indptr.append(len(data)) + array.resize_smart(indices, len(indices) + 1) + indices[len(indices) - 1] = idx + + array.resize_smart(data, len(data) + 1) + data[len(data) - 1] = float(value) - indptr = indptr.get() - data = data.get() - indices = indices.get() + prev_idx = idx - if not multilabel: - labels = labels.get() + array.resize_smart(indptr, len(indptr) + 1) + indptr[len(indptr) - 1] = len(data) - return data, indices, indptr, labels + return (dtype, data, indices, indptr, labels, query) diff --git a/sklearn/datasets/base.py b/sklearn/datasets/base.py index 82c1f21242fb0..0afdd09a47bcb 100644 --- a/sklearn/datasets/base.py +++ b/sklearn/datasets/base.py @@ -5,7 +5,7 @@ # Copyright (c) 2007 David Cournapeau # 2010 Fabian Pedregosa # 2010 Olivier Grisel -# License: Simplified BSD +# License: BSD 3 clause import os import csv @@ -43,14 +43,14 @@ def get_data_home(data_home=None): in the user home folder. Alternatively, it can be set by the 'SCIKIT_LEARN_DATA' environment - variable or programatically by giving an explit folder path. The + variable or programmatically by giving an explicit folder path. The '~' symbol is expanded to the user home folder. If the folder does not already exist, it is automatically created. """ if data_home is None: data_home = environ.get('SCIKIT_LEARN_DATA', - join('~', 'scikit_learn_data')) + join('~', 'scikit_learn_data')) data_home = expanduser(data_home) if not exists(data_home): makedirs(data_home) @@ -64,8 +64,8 @@ def clear_data_home(data_home=None): def load_files(container_path, description=None, categories=None, - load_content=True, shuffle=True, charset=None, - charse_error='strict', random_state=0): + load_content=True, shuffle=True, encoding=None, + decode_error='strict', random_state=0): """Load text files with categories as subfolder names. Individual samples are assumed to be files stored a two levels folder @@ -82,19 +82,25 @@ def load_files(container_path, description=None, categories=None, file_44.txt ... - The folder names are used has supervised signal label names. The indivial - file names are not important. + The folder names are used as supervised signal label names. The + individual file names are not important. This function does not try to extract features into a numpy array or scipy sparse matrix. In addition, if load_content is false it does not try to load the files in memory. - To use utf-8 text files in a scikit-learn classification or clustering - algorithm you will first need to use the `sklearn.features.text` + To use text files in a scikit-learn classification or clustering + algorithm, you will need to use the `sklearn.feature_extraction.text` module to build a feature extraction transformer that suits your problem. - Similar feature extractors should be build for other kind of unstructured + If you set load_content=True, you should also specify the encoding of + the text using the 'encoding' parameter. For many modern text files, + 'utf-8' will be the correct encoding. If you leave encoding equal to None, + then the content will be made of bytes instead of Unicode, and you will + not be able to use most functions in `sklearn.feature_extraction.text`. + + Similar feature extractors should be built for other kind of unstructured data input such as images, audio, video, ... Parameters @@ -116,17 +122,16 @@ def load_files(container_path, description=None, categories=None, in the data structure returned. If not, a filenames attribute gives the path to the files. - charset : string or None (default is None) + encoding : string or None (default is None) If None, do not try to decode the content of the files (e.g. for images or other non-text content). - If not None, charset to use to decode text files if load_content is - True. + If not None, encoding to use to decode text files to Unicode if + load_content is True. - charset_error: {'strict', 'ignore', 'replace'} + decode_error: {'strict', 'ignore', 'replace'}, optional Instruction on what to do if a byte sequence is given to analyze that - contains characters not of the given `charset`. By default, it is - 'strict', meaning that a UnicodeDecodeError will be raised. Other - values are 'ignore' and 'replace'. + contains characters not of the given `encoding`. Passed as keyword + argument 'errors' to bytes.decode. shuffle : bool, optional (default=True) Whether or not to shuffle the data: might be important for models that @@ -178,9 +183,12 @@ def load_files(container_path, description=None, categories=None, target = target[indices] if load_content: - data = [open(filename).read() for filename in filenames] - if charset is not None: - data = [d.decode(charset, charse_error) for d in data] + data = [] + for filename in filenames: + with open(filename, 'rb') as f: + data.append(f.read()) + if encoding is not None: + data = [d.decode(encoding, decode_error) for d in data] return Bunch(data=data, filenames=filenames, target_names=target_names, @@ -229,22 +237,25 @@ def load_iris(): ['setosa', 'versicolor', 'virginica'] """ module_path = dirname(__file__) - data_file = csv.reader(open(join(module_path, 'data', 'iris.csv'))) - fdescr = open(join(module_path, 'descr', 'iris.rst')) - temp = next(data_file) - n_samples = int(temp[0]) - n_features = int(temp[1]) - target_names = np.array(temp[2:]) - data = np.empty((n_samples, n_features)) - target = np.empty((n_samples,), dtype=np.int) - - for i, ir in enumerate(data_file): - data[i] = np.asarray(ir[:-1], dtype=np.float) - target[i] = np.asarray(ir[-1], dtype=np.int) + with open(join(module_path, 'data', 'iris.csv')) as csv_file: + data_file = csv.reader(csv_file) + temp = next(data_file) + n_samples = int(temp[0]) + n_features = int(temp[1]) + target_names = np.array(temp[2:]) + data = np.empty((n_samples, n_features)) + target = np.empty((n_samples,), dtype=np.int) + + for i, ir in enumerate(data_file): + data[i] = np.asarray(ir[:-1], dtype=np.float) + target[i] = np.asarray(ir[-1], dtype=np.int) + + with open(join(module_path, 'descr', 'iris.rst')) as rst_file: + fdescr = rst_file.read() return Bunch(data=data, target=target, target_names=target_names, - DESCR=fdescr.read(), + DESCR=fdescr, feature_names=['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']) @@ -283,7 +294,7 @@ def load_digits(n_class=10): >>> from sklearn.datasets import load_digits >>> digits = load_digits() - >>> digits.data.shape + >>> print(digits.data.shape) (1797, 64) >>> import pylab as pl #doctest: +SKIP >>> pl.gray() #doctest: +SKIP @@ -293,7 +304,8 @@ def load_digits(n_class=10): module_path = dirname(__file__) data = np.loadtxt(join(module_path, 'data', 'digits.csv.gz'), delimiter=',') - descr = open(join(module_path, 'descr', 'digits.rst')).read() + with open(join(module_path, 'descr', 'digits.rst')) as f: + descr = f.read() target = data[:, -1] flat_data = data[:, :-1] images = flat_data.view() @@ -384,36 +396,41 @@ def load_boston(): data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to learn, 'target', the regression targets, - 'target_names', the meaning of the labels, and 'DESCR', the - full description of the dataset. + and 'DESCR', the full description of the dataset. Examples -------- >>> from sklearn.datasets import load_boston >>> boston = load_boston() - >>> boston.data.shape + >>> print(boston.data.shape) (506, 13) """ module_path = dirname(__file__) - data_file = csv.reader(open(join(module_path, 'data', - 'boston_house_prices.csv'))) - fdescr = open(join(module_path, 'descr', 'boston_house_prices.rst')) - temp = data_file.next() - n_samples = int(temp[0]) - n_features = int(temp[1]) - data = np.empty((n_samples, n_features)) - target = np.empty((n_samples,)) - temp = data_file.next() # names of features - feature_names = np.array(temp) - - for i, d in enumerate(data_file): - data[i] = np.asarray(d[:-1], dtype=np.float) - target[i] = np.asarray(d[-1], dtype=np.float) + + fdescr_name = join(module_path, 'descr', 'boston_house_prices.rst') + with open(fdescr_name) as f: + descr_text = f.read() + + data_file_name = join(module_path, 'data', 'boston_house_prices.csv') + with open(data_file_name) as f: + data_file = csv.reader(f) + temp = next(data_file) + n_samples = int(temp[0]) + n_features = int(temp[1]) + data = np.empty((n_samples, n_features)) + target = np.empty((n_samples,)) + temp = next(data_file) # names of features + feature_names = np.array(temp) + + for i, d in enumerate(data_file): + data[i] = np.asarray(d[:-1], dtype=np.float) + target[i] = np.asarray(d[-1], dtype=np.float) return Bunch(data=data, target=target, - feature_names=feature_names, - DESCR=fdescr.read()) + # last column is target value + feature_names=feature_names[:-1], + DESCR=descr_text) def load_sample_images(): diff --git a/sklearn/datasets/california_housing.py b/sklearn/datasets/california_housing.py new file mode 100644 index 0000000000000..f1c1ac28248b7 --- /dev/null +++ b/sklearn/datasets/california_housing.py @@ -0,0 +1,124 @@ +"""California housing dataset. + +The original database is available from StatLib + + http://lib.stat.cmu.edu/ + +The data contains 20,640 observations on 9 variables. + +This dataset contains the average house value as target variable +and the following input variables (features): average income, +housing average age, average rooms, average bedrooms, population, +average occupation, latitude, and longitude in that order. + +References +---------- + +Pace, R. Kelley and Ronald Barry, Sparse Spatial Autoregressions, +Statistics and Probability Letters, 33 (1997) 291-297. + +""" +# Authors: Peter Prettenhofer +# License: BSD 3 clause + +from io import BytesIO +from os.path import join, exists +from os import makedirs +from zipfile import ZipFile +try: + # Python 2 + from urllib2 import urlopen +except ImportError: + # Python 3+ + from urllib.request import urlopen + +import numpy as np + +from .base import get_data_home, Bunch +from ..externals import joblib + + +DATA_URL = "http://lib.stat.cmu.edu/modules.php?op=modload&name=Downloads&"\ + "file=index&req=getit&lid=83" +TARGET_FILENAME = "cal_housing.pkz" + +# Grab the module-level docstring to use as a description of the +# dataset +MODULE_DOCS = __doc__ + + +def fetch_california_housing(data_home=None, download_if_missing=True): + """Loader for the California housing dataset from StatLib. + + Parameters + ---------- + data_home : optional, default: None + Specify another download and cache folder for the datasets. By default + all scikit learn data is stored in '~/scikit_learn_data' subfolders. + + download_if_missing: optional, True by default + If False, raise a IOError if the data is not locally available + instead of trying to download the data from the source site. + + Returns + ------- + dataset : dict-like object with the following attributes: + + dataset.data : ndarray, shape [20640, 8] + Each row corresponding to the 8 feature values in order. + + dataset.target : numpy array of shape (20640,) + Each value corresponds to the average house value in units of 100,000. + + dataset.feature_names : array of length 8 + Array of ordered feature names used in the dataset. + + dataset.DESCR : string + Description of the California housing dataset. + + Notes + ------ + + This dataset consists of 20,640 samples and 9 features. + """ + data_home = get_data_home(data_home=data_home) + if not exists(data_home): + makedirs(data_home) + if not exists(join(data_home, TARGET_FILENAME)): + print('downloading Cal. housing from %s to %s' % (DATA_URL, data_home)) + fhandle = urlopen(DATA_URL) + buf = BytesIO(fhandle.read()) + zip_file = ZipFile(buf) + try: + cadata_fd = zip_file.open('cadata.txt', 'r') + cadata = BytesIO(cadata_fd.read()) + # skip the first 27 lines (documentation) + cal_housing = np.loadtxt(cadata, skiprows=27) + joblib.dump(cal_housing, join(data_home, TARGET_FILENAME), + compress=6) + finally: + zip_file.close() + else: + cal_housing = joblib.load(join(data_home, TARGET_FILENAME)) + + feature_names = ["MedInc", "HouseAge", "AveRooms", "AveBedrms", + "Population", "AveOccup", "Latitude", "Longitude"] + + target, data = cal_housing[:, 0], cal_housing[:, 1:] + + # avg rooms = total rooms / households + data[:, 2] /= data[:, 5] + + # avg bed rooms = total bed rooms / households + data[:, 3] /= data[:, 5] + + # avg occupancy = population / housholds + data[:, 5] = data[:, 4] / data[:, 5] + + # target in units of 100,000 + target = target / 100000.0 + + return Bunch(data=data, + target=target, + feature_names=feature_names, + DESCR=MODULE_DOCS) diff --git a/sklearn/datasets/covtype.py b/sklearn/datasets/covtype.py new file mode 100644 index 0000000000000..7c37939b04e9b --- /dev/null +++ b/sklearn/datasets/covtype.py @@ -0,0 +1,134 @@ +"""Forest covertype dataset. + +A classic dataset for classification benchmarks, featuring categorical and +real-valued features. + +The dataset page is available from UCI Machine Learning Repository + + http://archive.ics.uci.edu/ml/datasets/Covertype + +Courtesy of Jock A. Blackard and Colorado State University. +""" + +# Author: Lars Buitinck +# Peter Prettenhofer +# License: BSD 3 clause + +import sys +import errno +from gzip import GzipFile +from io import BytesIO +import logging +import os +from os.path import exists, join +try: + from urllib2 import urlopen +except ImportError: + from urllib.request import urlopen + +import numpy as np + +from .base import get_data_home +from .base import Bunch +from ..externals import joblib +from ..utils import check_random_state + + +URL = ('http://archive.ics.uci.edu/ml/' + 'machine-learning-databases/covtype/covtype.data.gz') + + +logger = logging.getLogger() + + +def fetch_covtype(data_home=None, download_if_missing=True, + random_state=None, shuffle=False): + """Load the covertype dataset, downloading it if necessary. + + Parameters + ---------- + data_home : string, optional + Specify another download and cache folder for the datasets. By default + all scikit learn data is stored in '~/scikit_learn_data' subfolders. + + download_if_missing : boolean, default=True + If False, raise a IOError if the data is not locally available + instead of trying to download the data from the source site. + + random_state : int, RandomState instance or None, optional (default=None) + Random state for shuffling the dataset. + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + shuffle : bool, default=False + Whether to shuffle dataset. + + Returns + ------- + dataset : dict-like object with the following attributes: + + dataset.data : numpy array of shape (581012, 54) + Each row corresponds to the 54 features in the dataset. + + dataset.target : numpy array of shape (581012,) + Each value corresponds to one of the 7 forest covertypes with values + ranging between 1 to 7. + + dataset.DESCR : string + Description of the forest covertype dataset. + + """ + + data_home = get_data_home(data_home=data_home) + if sys.version_info[0] == 3: + # The zlib compression format use by joblib is not compatible when + # switching from Python 2 to Python 3, let us use a separate folder + # under Python 3: + dir_suffix = "-py3" + else: + # Backward compat for Python 2 users + dir_suffix = "" + covtype_dir = join(data_home, "covertype" + dir_suffix) + samples_path = join(covtype_dir, "samples") + targets_path = join(covtype_dir, "targets") + available = exists(samples_path) + + if download_if_missing and not available: + _mkdirp(covtype_dir) + logger.warning("Downloading %s" % URL) + f = BytesIO(urlopen(URL).read()) + Xy = np.genfromtxt(GzipFile(fileobj=f), delimiter=',') + + X = Xy[:, :-1] + y = Xy[:, -1].astype(np.int32) + + joblib.dump(X, samples_path, compress=9) + joblib.dump(y, targets_path, compress=9) + + try: + X, y + except NameError: + X = joblib.load(samples_path) + y = joblib.load(targets_path) + + if shuffle: + ind = np.arange(X.shape[0]) + rng = check_random_state(random_state) + rng.shuffle(ind) + X = X[ind] + y = y[ind] + + return Bunch(data=X, target=y, DESCR=__doc__) + + +def _mkdirp(d): + """Ensure directory d exists (like mkdir -p on Unix) + No guarantee that the directory is writable. + """ + try: + os.makedirs(d) + except OSError as e: + if e.errno != errno.EEXIST: + raise diff --git a/sklearn/datasets/lfw.py b/sklearn/datasets/lfw.py index c836231a9524b..29c743aaaa142 100644 --- a/sklearn/datasets/lfw.py +++ b/sklearn/datasets/lfw.py @@ -11,7 +11,7 @@ An alternative task, Face Recognition or Face Identification is: given the picture of the face of an unknown person, identify the name -of the person by refering to a gallery of previously seen pictures of +of the person by referring to a gallery of previously seen pictures of identified persons. Both Face Verification and Face Recognition are tasks that are typically @@ -21,18 +21,23 @@ detector from various online websites. """ # Copyright (c) 2011 Olivier Grisel -# License: Simplified BSD +# License: BSD 3 clause from os import listdir, makedirs, remove from os.path import join, exists, isdir import logging import numpy as np -import urllib + +try: + import urllib.request as urllib #for backwards compatibility +except ImportError: + import urllib from .base import get_data_home, Bunch from ..externals.joblib import Memory +from ..externals.six import b logger = logging.getLogger(__name__) @@ -117,7 +122,7 @@ def _load_imgs(file_paths, slice_, color, resize): from scipy.misc import imresize except ImportError: raise ImportError("The Python Imaging Library (PIL)" - "is required to load data from jpeg files") + " is required to load data from jpeg files") # compute the portion of the images to load to respect the slice_ parameter # given by the caller @@ -167,7 +172,7 @@ def _load_imgs(file_paths, slice_, color, resize): # def _fetch_lfw_people(data_folder_path, slice_=None, color=False, resize=None, - min_faces_per_person=0): + min_faces_per_person=0): """Perform the actual data loading for the lfw people dataset This operation is meant to be cached by a joblib wrapper. @@ -208,9 +213,9 @@ def _fetch_lfw_people(data_folder_path, slice_=None, color=False, resize=None, def fetch_lfw_people(data_home=None, funneled=True, resize=0.5, - min_faces_per_person=None, color=False, - slice_=(slice(70, 195), slice(78, 172)), - download_if_missing=True): + min_faces_per_person=0, color=False, + slice_=(slice(70, 195), slice(78, 172)), + download_if_missing=True): """Loader for the Labeled Faces in the Wild (LFW) people dataset This dataset is a collection of JPEG pictures of famous people @@ -255,6 +260,25 @@ def fetch_lfw_people(data_home=None, funneled=True, resize=0.5, download_if_missing: optional, True by default If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. + + Returns + ------- + dataset : dict-like object with the following attributes: + + dataset.data : numpy array of shape (13233, 2914) + Each row corresponds to a ravelled face image of original size 62 x 47 + pixels. + + dataset.images : numpy array of shape (13233, 62, 47) + Each row is a face image corresponding to one of the 5749 people in + the dataset. + + dataset.target : numpy array of shape (13233,) + Labels associated to each face image. Those labels range from 0-5748 + and correspond to the person IDs. + + dataset.DESCR : string + Description of the Labeled Faces in the Wild (LFW) dataset. """ lfw_home, data_folder_path = check_fetch_lfw( data_home=data_home, funneled=funneled, @@ -283,7 +307,7 @@ def fetch_lfw_people(data_home=None, funneled=True, resize=0.5, def _fetch_lfw_pairs(index_file_path, data_folder_path, slice_=None, - color=False, resize=None): + color=False, resize=None): """Perform the actual data loading for the LFW pairs dataset This operation is meant to be cached by a joblib wrapper. @@ -291,7 +315,7 @@ def _fetch_lfw_pairs(index_file_path, data_folder_path, slice_=None, # parse the index file to find the number of pairs to be able to allocate # the right amount of memory before starting to decode the jpeg files with open(index_file_path, 'rb') as index_file: - split_lines = [ln.strip().split('\t') for ln in index_file] + split_lines = [ln.strip().split(b('\t')) for ln in index_file] pair_specs = [sl for sl in split_lines if len(sl) > 2] n_pairs = len(pair_specs) @@ -315,7 +339,10 @@ def _fetch_lfw_pairs(index_file_path, data_folder_path, slice_=None, else: raise ValueError("invalid line %d: %r" % (i + 1, components)) for j, (name, idx) in enumerate(pair): - person_folder = join(data_folder_path, name) + try: + person_folder = join(data_folder_path, name) + except TypeError: + person_folder = join(data_folder_path, str(name, 'UTF-8')) filenames = list(sorted(listdir(person_folder))) file_path = join(person_folder, filenames[idx]) file_paths.append(file_path) @@ -339,7 +366,7 @@ def load_lfw_people(download_if_missing=False, **kwargs): def fetch_lfw_pairs(subset='train', data_home=None, funneled=True, resize=0.5, - color=False, slice_=(slice(70, 195), slice(78, 172)), + color=False, slice_=(slice(70, 195), slice(78, 172)), download_if_missing=True): """Loader for the Labeled Faces in the Wild (LFW) pairs dataset @@ -394,6 +421,26 @@ def fetch_lfw_pairs(subset='train', data_home=None, funneled=True, resize=0.5, download_if_missing: optional, True by default If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. + + Returns + ------- + The data is returned as a Bunch object with the following attributes: + + data : numpy array of shape (2200, 5828) + Each row corresponds to 2 ravel'd face images of original size 62 x 67 + pixels. + + pairs : numpy array of shape (2200, 2, 62, 67) + Each row has 2 face images corresponding to same or different person + from the dataset containing 5749 people. + + target : numpy array of shape (13233,) + Labels associated to each pair of images. The two label values being + different persons or the same person. + + DESCR : string + Description of the Labeled Faces in the Wild (LFW) dataset. + """ lfw_home, data_folder_path = check_fetch_lfw( data_home=data_home, funneled=funneled, diff --git a/sklearn/datasets/mlcomp.py b/sklearn/datasets/mlcomp.py index 54a38647fe129..315faa34f77ff 100644 --- a/sklearn/datasets/mlcomp.py +++ b/sklearn/datasets/mlcomp.py @@ -1,9 +1,9 @@ # Copyright (c) 2010 Olivier Grisel -# License: Simplified BSD +# License: BSD 3 clause """Glue code to load http://mlcomp.org data as a scikit.learn dataset""" import os -import numpy as np +import numbers from sklearn.datasets.base import load_files @@ -67,7 +67,7 @@ def load_mlcomp(name_or_id, set_="raw", mlcomp_root=None, **kwargs): raise ValueError("Could not find folder: " + mlcomp_root) # dataset lookup - if isinstance(name_or_id, (int, np.integer)): + if isinstance(name_or_id, numbers.Integral): # id lookup dataset_path = os.path.join(mlcomp_root, str(name_or_id)) else: @@ -78,10 +78,11 @@ def load_mlcomp(name_or_id, set_="raw", mlcomp_root=None, **kwargs): metadata_file = os.path.join(mlcomp_root, dataset, 'metadata') if not os.path.exists(metadata_file): continue - for line in file(metadata_file): - if line.strip() == expected_name_line: - dataset_path = os.path.join(mlcomp_root, dataset) - break + with open(metadata_file) as f: + for line in f: + if line.strip() == expected_name_line: + dataset_path = os.path.join(mlcomp_root, dataset) + break if dataset_path is None: raise ValueError("Could not find dataset with metadata line: " + expected_name_line) @@ -91,10 +92,11 @@ def load_mlcomp(name_or_id, set_="raw", mlcomp_root=None, **kwargs): metadata_file = os.path.join(dataset_path, 'metadata') if not os.path.exists(metadata_file): raise ValueError(dataset_path + ' is not a valid MLComp dataset') - for line in file(metadata_file): - if ":" in line: - key, value = line.split(":", 1) - metadata[key.strip()] = value.strip() + with open(metadata_file) as f: + for line in f: + if ":" in line: + key, value = line.split(":", 1) + metadata[key.strip()] = value.strip() format = metadata.get('format', 'unknow') loader = LOADERS.get(format) diff --git a/sklearn/datasets/mldata.py b/sklearn/datasets/mldata.py index c912e28cea1ae..3768435fe489b 100644 --- a/sklearn/datasets/mldata.py +++ b/sklearn/datasets/mldata.py @@ -1,16 +1,27 @@ """Automatically download MLdata datasets.""" # Copyright (c) 2011 Pietro Berkes -# License: Simplified BSD +# License: BSD 3 clause import os from os.path import join, exists import re +import numbers +try: + # Python 2 + from urllib2 import HTTPError + from urllib2 import quote + from urllib2 import urlopen +except ImportError: + # Python 3+ + from urllib.error import HTTPError + from urllib.parse import quote + from urllib.request import urlopen + import numpy as np import scipy as sp from scipy import io from shutil import copyfileobj -import urllib2 from .base import get_data_home, Bunch @@ -80,25 +91,36 @@ def fetch_mldata(dataname, target_name='label', data_name='data', Examples -------- Load the 'iris' dataset from mldata.org: + >>> from sklearn.datasets.mldata import fetch_mldata - >>> iris = fetch_mldata('iris') - >>> iris.target[0] - 1 - >>> print(iris.data[0]) - [-0.555556 0.25 -0.864407 -0.916667] + >>> import tempfile + >>> test_data_home = tempfile.mkdtemp() + + >>> iris = fetch_mldata('iris', data_home=test_data_home) + >>> iris.target.shape + (150,) + >>> iris.data.shape + (150, 4) Load the 'leukemia' dataset from mldata.org, which needs to be transposed to respects the sklearn axes convention: - >>> leuk = fetch_mldata('leukemia', transpose_data=True) - >>> print(leuk.data.shape[0]) - 72 + + >>> leuk = fetch_mldata('leukemia', transpose_data=True, + ... data_home=test_data_home) + >>> leuk.data.shape + (72, 7129) Load an alternative 'iris' dataset, which has different names for the columns: + >>> iris2 = fetch_mldata('datasets-UCI iris', target_name=1, - ... data_name=0) + ... data_name=0, data_home=test_data_home) >>> iris3 = fetch_mldata('datasets-UCI iris', - ... target_name='class', data_name='double0') + ... target_name='class', data_name='double0', + ... data_home=test_data_home) + + >>> import shutil + >>> shutil.rmtree(test_data_home) """ # normalize dataset name @@ -115,10 +137,10 @@ def fetch_mldata(dataname, target_name='label', data_name='data', # if the file does not exist, download it if not exists(filename): - urlname = MLDATA_BASE_URL % urllib2.quote(dataname) + urlname = MLDATA_BASE_URL % quote(dataname) try: - mldata_url = urllib2.urlopen(urlname) - except urllib2.HTTPError as e: + mldata_url = urlopen(urlname) + except HTTPError as e: if e.code == 404: e.msg = "Dataset '%s' not found on mldata.org." % dataname raise @@ -142,9 +164,9 @@ def fetch_mldata(dataname, target_name='label', data_name='data', for descr in matlab_dict['mldata_descr_ordering'][0]] # if target or data names are indices, transform then into names - if isinstance(target_name, (int, np.integer)): + if isinstance(target_name, numbers.Integral): target_name = col_names[target_name] - if isinstance(data_name, (int, np.integer)): + if isinstance(data_name, numbers.Integral): data_name = col_names[data_name] # rules for making sense of the mldata.org data format @@ -191,3 +213,28 @@ def fetch_mldata(dataname, target_name='label', data_name='data', dataset['target'] = dataset['target'].squeeze() return Bunch(**dataset) + + +# The following is used by nosetests to setup the docstring tests fixture + +def setup_module(module): + # setup mock urllib2 module to avoid downloading from mldata.org + from sklearn.utils.testing import install_mldata_mock + install_mldata_mock({ + 'iris': { + 'data': np.empty((150, 4)), + 'label': np.empty(150), + }, + 'datasets-uci-iris': { + 'double0': np.empty((150, 4)), + 'class': np.empty((150,)), + }, + 'leukemia': { + 'data': np.empty((72, 7129)), + }, + }) + + +def teardown_module(module): + from sklearn.utils.testing import uninstall_mldata_mock + uninstall_mldata_mock() diff --git a/sklearn/datasets/olivetti_faces.py b/sklearn/datasets/olivetti_faces.py index a6171dfb1cd2a..408a36bd576e1 100644 --- a/sklearn/datasets/olivetti_faces.py +++ b/sklearn/datasets/olivetti_faces.py @@ -20,12 +20,19 @@ consists of 64x64 images. """ # Copyright (c) 2011 David Warde-Farley -# License: Simplified BSD +# License: BSD 3 clause +from io import BytesIO from os.path import join, exists from os import makedirs -from cStringIO import StringIO -import urllib2 +try: + # Python 2 + import urllib2 + urlopen = urllib2.urlopen +except ImportError: + # Python 3 + import urllib.request + urlopen = urllib.request.urlopen import numpy as np from scipy.io.matlab import loadmat @@ -65,6 +72,22 @@ def fetch_olivetti_faces(data_home=None, shuffle=False, random_state=0, The seed or the random number generator used to shuffle the data. + Returns + ------- + An object with the following attributes: + + data : numpy array of shape (400, 4096) + Each row corresponds to a ravelled face image of original size 64 x 64 pixels. + + images : numpy array of shape (400, 64, 64) + Each row is a face image corresponding to one of the 40 subjects of the dataset. + + target : numpy array of shape (400, ) + Labels associated to each face image. Those labels are ranging from 0-39 and correspond to the Subject IDs. + + DESCR : string + Description of the modified Olivetti Faces Dataset. + Notes ------ @@ -83,10 +106,10 @@ def fetch_olivetti_faces(data_home=None, shuffle=False, random_state=0, if not exists(data_home): makedirs(data_home) if not exists(join(data_home, TARGET_FILENAME)): - print 'downloading Olivetti faces from %s to %s' % (DATA_URL, - data_home) - fhandle = urllib2.urlopen(DATA_URL) - buf = StringIO(fhandle.read()) + print('downloading Olivetti faces from %s to %s' + % (DATA_URL, data_home)) + fhandle = urlopen(DATA_URL) + buf = BytesIO(fhandle.read()) mfile = loadmat(buf) faces = mfile['faces'].T.copy() joblib.dump(faces, join(data_home, TARGET_FILENAME), compress=6) diff --git a/sklearn/datasets/samples_generator.py b/sklearn/datasets/samples_generator.py index 2da437461afee..58e2dfbefccb5 100644 --- a/sklearn/datasets/samples_generator.py +++ b/sklearn/datasets/samples_generator.py @@ -3,15 +3,37 @@ """ # Authors: B. Thirion, G. Varoquaux, A. Gramfort, V. Michel, O. Grisel, -# G. Louppe +# G. Louppe, J. Nothman # License: BSD 3 clause -from itertools import product +import numbers +import warnings +import array import numpy as np from scipy import linalg +import scipy.sparse as sp -from ..utils import array2d, check_random_state +from ..preprocessing import MultiLabelBinarizer +from ..utils import check_array, check_random_state from ..utils import shuffle as util_shuffle +from ..utils.fixes import astype +from ..utils.random import sample_without_replacement +from ..externals import six +map = six.moves.map +zip = six.moves.zip + + +def _generate_hypercube(samples, dimensions, rng): + """Returns distinct binary samples of length dimensions + """ + if dimensions > 30: + return np.hstack([_generate_hypercube(samples, dimensions - 30, rng), + _generate_hypercube(samples, 30, rng)]) + out = astype(sample_without_replacement(2 ** dimensions, samples, + random_state=rng), + dtype='>u4', copy=False) + out = np.unpackbits(out.view('>u1')).reshape((-1, 32))[:, -dimensions:] + return out def make_classification(n_samples=100, n_features=20, n_informative=2, @@ -21,6 +43,15 @@ def make_classification(n_samples=100, n_features=20, n_informative=2, shuffle=True, random_state=None): """Generate a random n-class classification problem. + This initially creates clusters of points normally distributed (std=1) + about vertices of a `2 * class_sep`-sided hypercube, and assigns an equal + number of clusters to each class. It introduces interdependence between + these features and adds various types of further noise to the data. + + Prior to shuffling, `X` stacks a number of these primary "informative" + features, "redundant" linear combinations of these, "repeated" duplicates + of sampled features, and arbitrary noise for and remaining features. + Parameters ---------- n_samples : int, optional (default=100) @@ -29,7 +60,7 @@ def make_classification(n_samples=100, n_features=20, n_informative=2, n_features : int, optional (default=20) The total number of features. These comprise `n_informative` informative features, `n_redundant` redundant features, `n_repeated` - dupplicated features and `n_features-n_informative-n_redundant- + duplicated features and `n_features-n_informative-n_redundant- n_repeated` useless features drawn at random. n_informative : int, optional (default=2) @@ -37,15 +68,16 @@ def make_classification(n_samples=100, n_features=20, n_informative=2, of gaussian clusters each located around the vertices of a hypercube in a subspace of dimension `n_informative`. For each cluster, informative features are drawn independently from N(0, 1) and then - randomly linearly combined in order to add covariance. The clusters - are then placed on the vertices of the hypercube. + randomly linearly combined within each cluster in order to add + covariance. The clusters are then placed on the vertices of the + hypercube. n_redundant : int, optional (default=2) The number of redundant features. These features are generated as random linear combinations of the informative features. - n_repeated : int, optional (default=2) - The number of dupplicated features, drawn randomly from the informative + n_repeated : int, optional (default=0) + The number of duplicated features, drawn randomly from the informative and the redundant features. n_classes : int, optional (default=2) @@ -58,6 +90,8 @@ def make_classification(n_samples=100, n_features=20, n_informative=2, The proportions of samples assigned to each class. If None, then classes are balanced. Note that if `len(weights) == n_classes - 1`, then the last class weight is automatically inferred. + More than `n_samples` samples may be returned if the sum of `weights` + exceeds 1. flip_y : float, optional (default=0.01) The fraction of samples whose class are randomly exchanged. @@ -69,12 +103,12 @@ def make_classification(n_samples=100, n_features=20, n_informative=2, If True, the clusters are put on the vertices of a hypercube. If False, the clusters are put on the vertices of a random polytope. - shift : float or None, optional (default=0.0) - Shift all features by the specified value. If None, then features + shift : float, array of shape [n_features] or None, optional (default=0.0) + Shift features by the specified value. If None, then features are shifted by a random value drawn in [-class_sep, class_sep]. - scale : float or None, optional (default=1.0) - Multiply all features by the specified value. If None, then features + scale : float, array of shape [n_features] or None, optional (default=1.0) + Multiply features by the specified value. If None, then features are scaled by a random value drawn in [1, 100]. Note that scaling happens after shifting. @@ -102,22 +136,27 @@ def make_classification(n_samples=100, n_features=20, n_informative=2, References ---------- - .. [1] I. Guyon, "Design of experiments for the NIPS 2003 variable selection benchmark", 2003. + + See also + -------- + make_blobs: simplified variant + make_multilabel_classification: unrelated generator for multilabel tasks """ generator = check_random_state(random_state) # Count features, clusters and samples if n_informative + n_redundant + n_repeated > n_features: raise ValueError("Number of informative, redundant and repeated " - "features must sum to less than the number of total features") + "features must sum to less than the number of total" + " features") if 2 ** n_informative < n_classes * n_clusters_per_class: raise ValueError("n_classes * n_clusters_per_class must" - "be smaller or equal 2 ** n_informative") + " be smaller or equal 2 ** n_informative") if weights and len(weights) not in [n_classes, n_classes - 1]: raise ValueError("Weights specified but incompatible with number " - "of classes.") + "of classes.") n_useless = n_features - n_informative - n_redundant - n_repeated n_clusters = n_classes * n_clusters_per_class @@ -129,98 +168,78 @@ def make_classification(n_samples=100, n_features=20, n_informative=2, weights = [1.0 / n_classes] * n_classes weights[-1] = 1.0 - sum(weights[:-1]) + # Distribute samples among clusters by weight n_samples_per_cluster = [] - - for k in xrange(n_clusters): + for k in range(n_clusters): n_samples_per_cluster.append(int(n_samples * weights[k % n_classes] / n_clusters_per_class)) - - for i in xrange(n_samples - sum(n_samples_per_cluster)): + for i in range(n_samples - sum(n_samples_per_cluster)): n_samples_per_cluster[i % n_clusters] += 1 # Intialize X and y X = np.zeros((n_samples, n_features)) - y = np.zeros(n_samples) - - # Build the polytope - C = np.array(list(product([-class_sep, class_sep], repeat=n_informative))) + y = np.zeros(n_samples, dtype=np.int) + # Build the polytope whose vertices become cluster centroids + centroids = _generate_hypercube(n_clusters, n_informative, + generator).astype(float) + centroids *= 2 * class_sep + centroids -= class_sep if not hypercube: - for k in xrange(n_clusters): - C[k, :] *= generator.rand() - - for f in xrange(n_informative): - C[:, f] *= generator.rand() - - generator.shuffle(C) + centroids *= generator.rand(n_clusters, 1) + centroids *= generator.rand(1, n_informative) - # Loop over all clusters - pos = 0 - pos_end = 0 + # Initially draw informative features from the standard normal + X[:, :n_informative] = generator.randn(n_samples, n_informative) - for k in xrange(n_clusters): - # Number of samples in cluster k - n_samples_k = n_samples_per_cluster[k] + # Create each cluster; a variant of make_blobs + stop = 0 + for k, centroid in enumerate(centroids): + start, stop = stop, stop + n_samples_per_cluster[k] + y[start:stop] = k % n_classes # assign labels + X_k = X[start:stop, :n_informative] # slice a view of the cluster - # Define the range of samples - pos = pos_end - pos_end = pos + n_samples_k - - # Assign labels - y[pos:pos_end] = k % n_classes - - # Draw features at random - X[pos:pos_end, :n_informative] = generator.randn(n_samples_k, - n_informative) - - # Multiply by a random matrix to create co-variance of the features A = 2 * generator.rand(n_informative, n_informative) - 1 - X[pos:pos_end, :n_informative] = np.dot(X[pos:pos_end, :n_informative], - A) + X_k[...] = np.dot(X_k, A) # introduce random covariance - # Shift the cluster to a vertice - X[pos:pos_end, :n_informative] += np.tile(C[k, :], (n_samples_k, 1)) + X_k += centroid # shift the cluster to a vertex # Create redundant features if n_redundant > 0: B = 2 * generator.rand(n_informative, n_redundant) - 1 X[:, n_informative:n_informative + n_redundant] = \ - np.dot(X[:, :n_informative], B) + np.dot(X[:, :n_informative], B) # Repeat some features if n_repeated > 0: n = n_informative + n_redundant - indices = ((n - 1) * generator.rand(n_repeated) + 0.5).astype(np.int) + indices = ((n - 1) * generator.rand(n_repeated) + 0.5).astype(np.intp) X[:, n:n + n_repeated] = X[:, indices] # Fill useless features - X[:, n_features - n_useless:] = generator.randn(n_samples, n_useless) + if n_useless > 0: + X[:, -n_useless:] = generator.randn(n_samples, n_useless) - # Randomly flip labels + # Randomly replace labels if flip_y >= 0.0: - for i in xrange(n_samples): - if generator.rand() < flip_y: - y[i] = generator.randint(n_classes) + flip_mask = generator.rand(n_samples) < flip_y + y[flip_mask] = generator.randint(n_classes, size=flip_mask.sum()) # Randomly shift and scale - constant_shift = shift is not None - constant_scale = scale is not None + if shift is None: + shift = (2 * generator.rand(n_features) - 1) * class_sep + X += shift - for f in xrange(n_features): - if not constant_shift: - shift = (2 * generator.rand() - 1) * class_sep + if scale is None: + scale = 1 + 100 * generator.rand(n_features) + X *= scale - if not constant_scale: - scale = 1 + 100 * generator.rand() - - X[:, f] += shift - X[:, f] *= scale - - # Randomly permute samples and features if shuffle: + # Randomly permute samples X, y = util_shuffle(X, y, random_state=generator) - indices = range(n_features) + # Randomly permute features + indices = np.arange(n_features) generator.shuffle(indices) X[:, :] = X[:, indices] @@ -228,8 +247,10 @@ def make_classification(n_samples=100, n_features=20, n_informative=2, def make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, - n_labels=2, length=50, - allow_unlabeled=True, random_state=None): + n_labels=2, length=50, allow_unlabeled=True, + sparse=False, return_indicator=False, + return_distributions=False, + random_state=None): """Generate a random multilabel classification problem. For each sample, the generative process is: @@ -254,15 +275,31 @@ def make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, The number of classes of the classification problem. n_labels : int, optional (default=2) - The average number of labels per instance. Number of labels follows - a Poisson distribution that never takes the value 0. + The average number of labels per instance. More precisely, the number + of labels per sample is drawn from a Poisson distribution with + ``n_labels`` as its expected value, but samples are bounded (using + rejection sampling) by ``n_classes``, and must be nonzero if + ``allow_unlabeled`` is False. length : int, optional (default=50) - Sum of the features (number of words if documents). + The sum of the features (number of words if documents) is drawn from + a Poisson distribution with this expected value. allow_unlabeled : bool, optional (default=True) If ``True``, some instances might not belong to any class. + sparse : bool, optional (default=False) + If ``True``, return a sparse feature matrix + + return_indicator : bool, optional (default=False), + If ``True``, return ``Y`` in the binary indicator format, else + return a tuple of lists of labels. + + return_distributions : bool, optional (default=False) + If ``True``, return the prior class probability and conditional + probabilities of features given classes, from which the data was + drawn. + random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; @@ -271,15 +308,25 @@ def make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, Returns ------- - X : array of shape [n_samples, n_features] + X : array or sparse CSR matrix of shape [n_samples, n_features] The generated samples. - Y : list of tuples + Y : tuple of lists or array of shape [n_samples, n_classes] The label sets. + + p_c : array, shape [n_classes] + The probability of each class being drawn. Only returned if + ``return_distributions=True``. + + p_w_c : array, shape [n_features, n_classes] + The probability of each feature being drawn given each class. + Only returned if ``return_distributions=True``. + """ generator = check_random_state(random_state) p_c = generator.rand(n_classes) p_c /= p_c.sum() + cumulative_p_c = np.cumsum(p_c) p_w_c = generator.rand(n_features, n_classes) p_w_c /= np.sum(p_w_c, axis=0) @@ -287,40 +334,65 @@ def sample_example(): _, n_classes = p_w_c.shape # pick a nonzero number of labels per document by rejection sampling - n = n_classes + 1 - while (not allow_unlabeled and n == 0) or n > n_classes: - n = generator.poisson(n_labels) + y_size = n_classes + 1 + while (not allow_unlabeled and y_size == 0) or y_size > n_classes: + y_size = generator.poisson(n_labels) # pick n classes - y = [] - while len(y) != n: + y = set() + while len(y) != y_size: # pick a class with probability P(c) - c = generator.multinomial(1, p_c).argmax() - - if not c in y: - y.append(c) + c = np.searchsorted(cumulative_p_c, + generator.rand(y_size - len(y))) + y.update(c) + y = list(y) # pick a non-zero document length by rejection sampling - k = 0 - while k == 0: - k = generator.poisson(length) - - # generate a document of length k words - x = np.zeros(n_features, dtype=int) - for i in range(k): - if len(y) == 0: - # if sample does not belong to any class, generate noise word - w = generator.randint(n_features) - else: - # pick a class and generate an appropriate word - c = y[generator.randint(len(y))] - w = generator.multinomial(1, p_w_c[:, c]).argmax() - x[w] += 1 - - return x, y + n_words = 0 + while n_words == 0: + n_words = generator.poisson(length) + + # generate a document of length n_words + if len(y) == 0: + # if sample does not belong to any class, generate noise word + words = generator.randint(n_features, size=n_words) + return words, y + + # sample words with replacement from selected classes + cumulative_p_w_sample = p_w_c.take(y, axis=1).sum(axis=1).cumsum() + cumulative_p_w_sample /= cumulative_p_w_sample[-1] + words = np.searchsorted(cumulative_p_w_sample, generator.rand(n_words)) + return words, y + + X_indices = array.array('i') + X_indptr = array.array('i', [0]) + Y = [] + for i in range(n_samples): + words, y = sample_example() + X_indices.extend(words) + X_indptr.append(len(X_indices)) + Y.append(y) + X_data = np.ones(len(X_indices), dtype=np.float64) + X = sp.csr_matrix((X_data, X_indices, X_indptr), + shape=(n_samples, n_features)) + X.sum_duplicates() + if not sparse: + X = X.toarray() + + if return_indicator: + lb = MultiLabelBinarizer() + Y = lb.fit([range(n_classes)]).transform(Y) + else: + warnings.warn('Support for the sequence of sequences multilabel ' + 'representation is being deprecated and replaced with ' + 'a sparse indicator matrix. ' + 'return_indicator will default to True from version ' + '0.17.', + DeprecationWarning) - X, Y = zip(*[sample_example() for i in range(n_samples)]) - return np.array(X, dtype=np.float64), Y + if return_distributions: + return X, Y, p_c, p_w_c + return X, Y def make_hastie_10_2(n_samples=12000, random_state=None): @@ -330,12 +402,13 @@ def make_hastie_10_2(n_samples=12000, random_state=None): The ten features are standard independent Gaussian and the target ``y`` is defined by:: - y[i] = 1 if np.sum(X[i] > 9.34 else -1 + y[i] = 1 if np.sum(X[i] ** 2) > 9.34 else -1 Parameters ---------- n_samples : int, optional (default=12000) The number of samples. + random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; @@ -350,16 +423,22 @@ def make_hastie_10_2(n_samples=12000, random_state=None): y : array of shape [n_samples] The output values. - **References**: - + References + ---------- .. [1] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical - Learning Ed. 2", Springer, 2009. + Learning Ed. 2", Springer, 2009. + + See also + -------- + make_gaussian_quantiles: a generalization of this dataset approach """ rs = check_random_state(random_state) + shape = (n_samples, 10) X = rs.normal(size=shape).reshape(shape) y = ((X ** 2.0).sum(axis=1) > 9.34).astype(np.float64) y[y == 0.0] = -1.0 + return X, y @@ -370,7 +449,7 @@ def make_regression(n_samples=100, n_features=100, n_informative=10, """Generate a random regression problem. The input set can either be well conditioned (by default) or have a low - rank-fat tail singular profile. See the `make_low_rank_matrix` for + rank-fat tail singular profile. See :func:`make_low_rank_matrix` for more details. The output is generated by applying a (potentially biased) random linear @@ -438,6 +517,7 @@ def make_regression(n_samples=100, n_features=100, n_informative=10, The coefficient of the underlying linear model. It is returned only if coef is True. """ + n_informative = min(n_features, n_informative) generator = check_random_state(random_state) if effective_rank is None: @@ -469,7 +549,7 @@ def make_regression(n_samples=100, n_features=100, n_informative=10, if shuffle: X, y = util_shuffle(X, y, random_state=generator) - indices = range(n_features) + indices = np.arange(n_features) generator.shuffle(indices) X[:, :] = X[:, indices] ground_truth = ground_truth[indices] @@ -484,8 +564,8 @@ def make_regression(n_samples=100, n_features=100, n_informative=10, def make_circles(n_samples=100, shuffle=True, noise=None, random_state=None, - factor=.8): - """Make a large circle containing a smaller circle in 2di + factor=.8): + """Make a large circle containing a smaller circle in 2d. A simple toy dataset to visualize clustering and classification algorithms. @@ -503,36 +583,39 @@ def make_circles(n_samples=100, shuffle=True, noise=None, random_state=None, factor : double < 1 (default=.8) Scale factor between inner and outer circle. + + Returns + ------- + X : array of shape [n_samples, 2] + The generated samples. + + y : array of shape [n_samples] + The integer labels (0 or 1) for class membership of each sample. """ if factor > 1 or factor < 0: raise ValueError("'factor' has to be between 0 and 1.") - n_samples_out = int(n_samples / float(1 + factor)) - n_samples_in = n_samples - n_samples_out - generator = check_random_state(random_state) - # so as not to have the first point = last point, we add one and then # remove it. - n_samples_out, n_samples_in = n_samples_out + 1, n_samples_in + 1 - outer_circ_x = np.cos(np.linspace(0, 2 * np.pi, n_samples_out)[:-1]) - outer_circ_y = np.sin(np.linspace(0, 2 * np.pi, n_samples_out)[:-1]) - inner_circ_x = (np.cos(np.linspace(0, 2 * np.pi, n_samples_in)[:-1]) - * factor) - inner_circ_y = (np.sin(np.linspace(0, 2 * np.pi, n_samples_in)[:-1]) - * factor) - - X = np.vstack((np.append(outer_circ_x, inner_circ_x),\ - np.append(outer_circ_y, inner_circ_y))).T - y = np.hstack([np.zeros(n_samples_out - 1), np.ones(n_samples_in - 1)]) + linspace = np.linspace(0, 2 * np.pi, n_samples // 2 + 1)[:-1] + outer_circ_x = np.cos(linspace) + outer_circ_y = np.sin(linspace) + inner_circ_x = outer_circ_x * factor + inner_circ_y = outer_circ_y * factor + + X = np.vstack((np.append(outer_circ_x, inner_circ_x), + np.append(outer_circ_y, inner_circ_y))).T + y = np.hstack([np.zeros(n_samples // 2, dtype=np.intp), + np.ones(n_samples // 2, dtype=np.intp)]) if shuffle: X, y = util_shuffle(X, y, random_state=generator) if not noise is None: X += generator.normal(scale=noise, size=X.shape) - return X, y.astype(np.int) + return X, y def make_moons(n_samples=100, shuffle=True, noise=None, random_state=None): @@ -552,9 +635,16 @@ def make_moons(n_samples=100, shuffle=True, noise=None, random_state=None): noise : double or None (default=None) Standard deviation of Gaussian noise added to the data. + Returns + ------- + X : array of shape [n_samples, 2] + The generated samples. + + y : array of shape [n_samples] + The integer labels (0 or 1) for class membership of each sample. """ - n_samples_out = n_samples / 2 + n_samples_out = n_samples // 2 n_samples_in = n_samples - n_samples_out generator = check_random_state(random_state) @@ -564,9 +654,10 @@ def make_moons(n_samples=100, shuffle=True, noise=None, random_state=None): inner_circ_x = 1 - np.cos(np.linspace(0, np.pi, n_samples_in)) inner_circ_y = 1 - np.sin(np.linspace(0, np.pi, n_samples_in)) - .5 - X = np.vstack((np.append(outer_circ_x, inner_circ_x),\ - np.append(outer_circ_y, inner_circ_y))).T - y = np.hstack([np.zeros(n_samples_in), np.ones(n_samples_out)]) + X = np.vstack((np.append(outer_circ_x, inner_circ_x), + np.append(outer_circ_y, inner_circ_y))).T + y = np.hstack([np.zeros(n_samples_in, dtype=np.intp), + np.ones(n_samples_out, dtype=np.intp)]) if shuffle: X, y = util_shuffle(X, y, random_state=generator) @@ -574,7 +665,7 @@ def make_moons(n_samples=100, shuffle=True, noise=None, random_state=None): if not noise is None: X += generator.normal(scale=noise, size=X.shape) - return X, y.astype(np.int) + return X, y def make_blobs(n_samples=100, n_features=2, centers=3, cluster_std=1.0, @@ -622,18 +713,22 @@ def make_blobs(n_samples=100, n_features=2, centers=3, cluster_std=1.0, >>> from sklearn.datasets.samples_generator import make_blobs >>> X, y = make_blobs(n_samples=10, centers=3, n_features=2, ... random_state=0) - >>> X.shape + >>> print(X.shape) (10, 2) >>> y array([0, 0, 1, 0, 2, 2, 2, 1, 1, 0]) + + See also + -------- + make_classification: a more intricate variant """ generator = check_random_state(random_state) - if isinstance(centers, (int, np.integer)): + if isinstance(centers, numbers.Integral): centers = generator.uniform(center_box[0], center_box[1], size=(centers, n_features)) else: - centers = array2d(centers) + centers = check_array(centers) n_features = centers.shape[1] X = [] @@ -642,7 +737,7 @@ def make_blobs(n_samples=100, n_features=2, centers=3, cluster_std=1.0, n_centers = centers.shape[0] n_samples_per_center = [int(n_samples // n_centers)] * n_centers - for i in xrange(n_samples % n_centers): + for i in range(n_samples % n_centers): n_samples_per_center[i] += 1 for i, n in enumerate(n_samples_per_center): @@ -663,7 +758,7 @@ def make_blobs(n_samples=100, n_features=2, centers=3, cluster_std=1.0, def make_friedman1(n_samples=100, n_features=10, noise=0.0, random_state=None): - """Generate the "Friedman #1" regression problem + """Generate the "Friedman \#1" regression problem This dataset is described in Friedman [1] and Breiman [2]. @@ -705,7 +800,6 @@ def make_friedman1(n_samples=100, n_features=10, noise=0.0, random_state=None): References ---------- - .. [1] J. Friedman, "Multivariate adaptive regression splines", The Annals of Statistics 19 (1), pages 1-67, 1991. @@ -725,7 +819,7 @@ def make_friedman1(n_samples=100, n_features=10, noise=0.0, random_state=None): def make_friedman2(n_samples=100, noise=0.0, random_state=None): - """Generate the "Friedman #2" regression problem + """Generate the "Friedman \#2" regression problem This dataset is described in Friedman [1] and Breiman [2]. @@ -766,7 +860,6 @@ def make_friedman2(n_samples=100, noise=0.0, random_state=None): References ---------- - .. [1] J. Friedman, "Multivariate adaptive regression splines", The Annals of Statistics 19 (1), pages 1-67, 1991. @@ -783,14 +876,14 @@ def make_friedman2(n_samples=100, noise=0.0, random_state=None): X[:, 3] += 1 y = (X[:, 0] ** 2 - + (X[:, 1] * X[:, 2] - 1 / (X[:, 1] * X[:, 3])) ** 2) ** 0.5 \ + + (X[:, 1] * X[:, 2] - 1 / (X[:, 1] * X[:, 3])) ** 2) ** 0.5 \ + noise * generator.randn(n_samples) return X, y def make_friedman3(n_samples=100, noise=0.0, random_state=None): - """Generate the "Friedman #3" regression problem + """Generate the "Friedman \#3" regression problem This dataset is described in Friedman [1] and Breiman [2]. @@ -831,7 +924,6 @@ def make_friedman3(n_samples=100, noise=0.0, random_state=None): References ---------- - .. [1] J. Friedman, "Multivariate adaptive regression splines", The Annals of Statistics 19 (1), pages 1-67, 1991. @@ -906,16 +998,15 @@ def make_low_rank_matrix(n_samples=100, n_features=100, effective_rank=10, n = min(n_samples, n_features) # Random (ortho normal) vectors - from ..utils.fixes import qr_economic - u, _ = qr_economic(generator.randn(n_samples, n)) - v, _ = qr_economic(generator.randn(n_features, n)) + u, _ = linalg.qr(generator.randn(n_samples, n), mode='economic') + v, _ = linalg.qr(generator.randn(n_features, n), mode='economic') # Index of the singular values singular_ind = np.arange(n, dtype=np.float64) # Build the singular profile by assembling signal and noise components - low_rank = (1 - tail_strength) * \ - np.exp(-1.0 * (singular_ind / effective_rank) ** 2) + low_rank = ((1 - tail_strength) * + np.exp(-1.0 * (singular_ind / effective_rank) ** 2)) tail = tail_strength * np.exp(-0.1 * singular_ind / effective_rank) s = np.identity(n) * (low_rank + tail) @@ -968,7 +1059,7 @@ def make_sparse_coded_signal(n_samples, n_components, n_features, # generate code X = np.zeros((n_components, n_samples)) - for i in xrange(n_samples): + for i in range(n_samples): idx = np.arange(n_components) generator.shuffle(idx) idx = idx[:n_nonzero_coefs] @@ -1015,7 +1106,6 @@ def make_sparse_uncorrelated(n_samples=100, n_features=10, random_state=None): References ---------- - .. [1] G. Celeux, M. El Anbari, J.-M. Marin, C. P. Robert, "Regularization in regression: comparing Bayesian and frequentist methods in a poorly informative situation", 2009. @@ -1049,6 +1139,10 @@ def make_spd_matrix(n_dim, random_state=None): ------- X : array of shape [n_dim, n_dim] The random symmetric, positive-definite matrix. + + See also + -------- + make_sparse_spd_matrix """ generator = check_random_state(random_state) @@ -1062,12 +1156,12 @@ def make_spd_matrix(n_dim, random_state=None): def make_sparse_spd_matrix(dim=1, alpha=0.95, norm_diag=False, smallest_coef=.1, largest_coef=.9, random_state=None): - """Generate a sparse symetric definite positive matrix. + """Generate a sparse symmetric definite positive matrix. Parameters ---------- dim: integer, optional (default=1) - The size of the random (matrix to generate. + The size of the random matrix to generate. alpha: float between 0 and 1, optional (default=0.95) The probability that a coefficient is non zero (see notes). @@ -1078,15 +1172,30 @@ def make_sparse_spd_matrix(dim=1, alpha=0.95, norm_diag=False, If None, the random number generator is the RandomState instance used by `np.random`. + largest_coef : float between 0 and 1, optional (default=0.9) + The value of the largest coefficient. + + smallest_coef : float between 0 and 1, optional (default=0.1) + The value of the smallest coefficient. + + norm_diag : boolean, optional (default=False) + Whether to normalize the output matrix to make the leading diagonal + elements all 1 + Returns ------- - prec: array of shape = [dim, dim] + prec : sparse matrix of shape (dim, dim) + The generated matrix. Notes ----- The sparsity is actually imposed on the cholesky factor of the matrix. Thus alpha does not translate directly into the filling fraction of the matrix itself. + + See also + -------- + make_spd_matrix """ random_state = check_random_state(random_state) @@ -1095,10 +1204,10 @@ def make_sparse_spd_matrix(dim=1, alpha=0.95, norm_diag=False, aux[aux < alpha] = 0 aux[aux > alpha] = (smallest_coef + (largest_coef - smallest_coef) - * random_state.rand(np.sum(aux > alpha))) + * random_state.rand(np.sum(aux > alpha))) aux = np.tril(aux, k=-1) - # Permute the lines: we don't want to have assymetries in the final + # Permute the lines: we don't want to have asymmetries in the final # SPD matrix permutation = random_state.permutation(dim) aux = aux[permutation].T[permutation] @@ -1106,10 +1215,12 @@ def make_sparse_spd_matrix(dim=1, alpha=0.95, norm_diag=False, prec = np.dot(chol.T, chol) if norm_diag: - d = np.diag(prec) + # Form the diagonal vector into a row matrix + d = np.diag(prec).reshape(1, prec.shape[0]) d = 1. / np.sqrt(d) - prec *= d - prec *= d[:, np.newaxis] + + prec *= d + prec *= d.T return prec @@ -1146,8 +1257,7 @@ def make_swiss_roll(n_samples=100, noise=0.0, random_state=None): References ---------- - - .. [1] S. Marsland, "Machine Learning: An Algorithmic Perpsective", + .. [1] S. Marsland, "Machine Learning: An Algorithmic Perspective", Chapter 10, 2009. http://www-ist.massey.ac.nz/smarsland/Code/10/lle.py """ @@ -1205,3 +1315,286 @@ def make_s_curve(n_samples=100, noise=0.0, random_state=None): t = np.squeeze(t) return X, t + + +def make_gaussian_quantiles(mean=None, cov=1., n_samples=100, + n_features=2, n_classes=3, + shuffle=True, random_state=None): + """Generate isotropic Gaussian and label samples by quantile + + This classification dataset is constructed by taking a multi-dimensional + standard normal distribution and defining classes separated by nested + concentric multi-dimensional spheres such that roughly equal numbers of + samples are in each class (quantiles of the :math:`\chi^2` distribution). + + Parameters + ---------- + mean : array of shape [n_features], optional (default=None) + The mean of the multi-dimensional normal distribution. + If None then use the origin (0, 0, ...). + + cov : float, optional (default=1.) + The covariance matrix will be this value times the unit matrix. This + dataset only produces symmetric normal distributions. + + n_samples : int, optional (default=100) + The total number of points equally divided among classes. + + n_features : int, optional (default=2) + The number of features for each sample. + + n_classes : int, optional (default=3) + The number of classes + + shuffle : boolean, optional (default=True) + Shuffle the samples. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + Returns + ------- + X : array of shape [n_samples, n_features] + The generated samples. + + y : array of shape [n_samples] + The integer labels for quantile membership of each sample. + + Notes + ----- + The dataset is from Zhu et al [1]. + + References + ---------- + .. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009. + + """ + if n_samples < n_classes: + raise ValueError("n_samples must be at least n_classes") + + generator = check_random_state(random_state) + + if mean is None: + mean = np.zeros(n_features) + else: + mean = np.array(mean) + + # Build multivariate normal distribution + X = generator.multivariate_normal(mean, cov * np.identity(n_features), + (n_samples,)) + + # Sort by distance from origin + idx = np.argsort(np.sum((X - mean[np.newaxis, :]) ** 2, axis=1)) + X = X[idx, :] + + # Label by quantile + step = n_samples // n_classes + + y = np.hstack([np.repeat(np.arange(n_classes), step), + np.repeat(n_classes - 1, n_samples - step * n_classes)]) + + if shuffle: + X, y = util_shuffle(X, y, random_state=generator) + + return X, y + + +def _shuffle(data, random_state=None): + generator = check_random_state(random_state) + n_rows, n_cols = data.shape + row_idx = generator.permutation(n_rows) + col_idx = generator.permutation(n_cols) + result = data[row_idx][:, col_idx] + return result, row_idx, col_idx + + +def make_biclusters(shape, n_clusters, noise=0.0, minval=10, + maxval=100, shuffle=True, random_state=None): + """Generate an array with constant block diagonal structure for + biclustering. + + Parameters + ---------- + shape : iterable (n_rows, n_cols) + The shape of the result. + + n_clusters : integer + The number of biclusters. + + noise : float, optional (default=0.0) + The standard deviation of the gaussian noise. + + minval : int, optional (default=10) + Minimum value of a bicluster. + + maxval : int, optional (default=100) + Maximum value of a bicluster. + + shuffle : boolean, optional (default=True) + Shuffle the samples. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + Returns + ------- + X : array of shape `shape` + The generated array. + + rows : array of shape (n_clusters, X.shape[0],) + The indicators for cluster membership of each row. + + cols : array of shape (n_clusters, X.shape[1],) + The indicators for cluster membership of each column. + + References + ---------- + + .. [1] Dhillon, I. S. (2001, August). Co-clustering documents and + words using bipartite spectral graph partitioning. In Proceedings + of the seventh ACM SIGKDD international conference on Knowledge + discovery and data mining (pp. 269-274). ACM. + + See also + -------- + make_checkerboard + """ + generator = check_random_state(random_state) + n_rows, n_cols = shape + consts = generator.uniform(minval, maxval, n_clusters) + + # row and column clusters of approximately equal sizes + row_sizes = generator.multinomial(n_rows, + np.repeat(1.0 / n_clusters, + n_clusters)) + col_sizes = generator.multinomial(n_cols, + np.repeat(1.0 / n_clusters, + n_clusters)) + + row_labels = np.hstack(list(np.repeat(val, rep) for val, rep in + zip(range(n_clusters), row_sizes))) + col_labels = np.hstack(list(np.repeat(val, rep) for val, rep in + zip(range(n_clusters), col_sizes))) + + result = np.zeros(shape, dtype=np.float64) + for i in range(n_clusters): + selector = np.outer(row_labels == i, col_labels == i) + result[selector] += consts[i] + + if noise > 0: + result += generator.normal(scale=noise, size=result.shape) + + if shuffle: + result, row_idx, col_idx = _shuffle(result, random_state) + row_labels = row_labels[row_idx] + col_labels = col_labels[col_idx] + + rows = np.vstack(row_labels == c for c in range(n_clusters)) + cols = np.vstack(col_labels == c for c in range(n_clusters)) + + return result, rows, cols + + +def make_checkerboard(shape, n_clusters, noise=0.0, minval=10, + maxval=100, shuffle=True, random_state=None): + """Generate an array with block checkerboard structure for + biclustering. + + Parameters + ---------- + shape : iterable (n_rows, n_cols) + The shape of the result. + + n_clusters : integer or iterable (n_row_clusters, n_column_clusters) + The number of row and column clusters. + + noise : float, optional (default=0.0) + The standard deviation of the gaussian noise. + + minval : int, optional (default=10) + Minimum value of a bicluster. + + maxval : int, optional (default=100) + Maximum value of a bicluster. + + shuffle : boolean, optional (default=True) + Shuffle the samples. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + Returns + ------- + X : array of shape `shape` + The generated array. + + rows : array of shape (n_clusters, X.shape[0],) + The indicators for cluster membership of each row. + + cols : array of shape (n_clusters, X.shape[1],) + The indicators for cluster membership of each column. + + + References + ---------- + + .. [1] Kluger, Y., Basri, R., Chang, J. T., & Gerstein, M. (2003). + Spectral biclustering of microarray data: coclustering genes + and conditions. Genome research, 13(4), 703-716. + + See also + -------- + make_biclusters + """ + generator = check_random_state(random_state) + + if hasattr(n_clusters, "__len__"): + n_row_clusters, n_col_clusters = n_clusters + else: + n_row_clusters = n_col_clusters = n_clusters + + # row and column clusters of approximately equal sizes + n_rows, n_cols = shape + row_sizes = generator.multinomial(n_rows, + np.repeat(1.0 / n_row_clusters, + n_row_clusters)) + col_sizes = generator.multinomial(n_cols, + np.repeat(1.0 / n_col_clusters, + n_col_clusters)) + + row_labels = np.hstack(list(np.repeat(val, rep) for val, rep in + zip(range(n_row_clusters), row_sizes))) + col_labels = np.hstack(list(np.repeat(val, rep) for val, rep in + zip(range(n_col_clusters), col_sizes))) + + result = np.zeros(shape, dtype=np.float64) + for i in range(n_row_clusters): + for j in range(n_col_clusters): + selector = np.outer(row_labels == i, col_labels == j) + result[selector] += generator.uniform(minval, maxval) + + if noise > 0: + result += generator.normal(scale=noise, size=result.shape) + + if shuffle: + result, row_idx, col_idx = _shuffle(result, random_state) + row_labels = row_labels[row_idx] + col_labels = col_labels[col_idx] + + rows = np.vstack(row_labels == label + for label in range(n_row_clusters) + for _ in range(n_col_clusters)) + cols = np.vstack(col_labels == label + for _ in range(n_row_clusters) + for label in range(n_col_clusters)) + + return result, rows, cols diff --git a/sklearn/datasets/setup.py b/sklearn/datasets/setup.py index 4899306cb6377..5fea622758a95 100644 --- a/sklearn/datasets/setup.py +++ b/sklearn/datasets/setup.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python import numpy import os diff --git a/sklearn/datasets/species_distributions.py b/sklearn/datasets/species_distributions.py index 2cb234cc66516..daf3e42a982e2 100644 --- a/sklearn/datasets/species_distributions.py +++ b/sklearn/datasets/species_distributions.py @@ -33,15 +33,21 @@ # Authors: Peter Prettenhofer # Jake Vanderplas # -# License: Simplified BSD - -from cStringIO import StringIO +# License: BSD 3 clause +from io import BytesIO from os import makedirs from os.path import join from os.path import exists -import urllib2 +try: + # Python 2 + from urllib2 import urlopen + PY2 = True +except ImportError: + # Python 3 + from urllib.request import urlopen + PY2 = False import numpy as np @@ -56,24 +62,19 @@ DATA_ARCHIVE_NAME = "species_coverage.pkz" -def _load_coverage(F, header_length=6, - dtype=np.int16): - """ - load a coverage file. +def _load_coverage(F, header_length=6, dtype=np.int16): + """Load a coverage file from an open file object. + This will return a numpy array of the given dtype """ - try: - header = [F.readline() for i in range(header_length)] - except: - F = open(F) - header = [F.readline() for i in range(header_length)] - + header = [F.readline() for i in range(header_length)] make_tuple = lambda t: (t.split()[0], float(t.split()[1])) header = dict([make_tuple(line) for line in header]) M = np.loadtxt(F, dtype=dtype) - nodata = header['NODATA_value'] + nodata = header[b'NODATA_value'] if nodata != -9999: + print(nodata) M[nodata] = -9999 return M @@ -81,26 +82,24 @@ def _load_coverage(F, header_length=6, def _load_csv(F): """Load csv file. - Paramters - --------- - F : string or file object - file object or name of file + Parameters + ---------- + F : file object + CSV file open in byte mode. Returns ------- rec : np.ndarray record array representing the data """ - try: + if PY2: + # Numpy recarray wants Python 2 str but not unicode names = F.readline().strip().split(',') - except: - F = open(F) - names = F.readline().strip().split(',') - - rec = np.loadtxt(F, skiprows=1, delimiter=',', - dtype='a22,f4,f4') + else: + # Numpy recarray wants Python 3 str but not bytes... + names = F.readline().decode('ascii').strip().split(',') + rec = np.loadtxt(F, skiprows=0, delimiter=',', dtype='a22,f4,f4') rec.dtype.names = names - return rec @@ -145,23 +144,8 @@ def fetch_species_distributions(data_home=None, If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. - Notes - ------ - - This dataset represents the geographic distribution of species. - The dataset is provided by Phillips et. al. (2006). - - The two species are: - - - `"Bradypus variegatus" - `_ , - the Brown-throated Sloth. - - - `"Microryzomys minutus" - `_ , - also known as the Forest Small Rice Rat, a rodent that lives in Peru, - Colombia, Ecuador, Peru, and Venezuela. - + Returns + -------- The data is returned as a Bunch object with the following attributes: coverages : array, shape = [14, 1592, 1212] @@ -188,6 +172,23 @@ def fetch_species_distributions(data_home=None, grid_size : float The spacing between points of the grid, in degrees + Notes + ------ + + This dataset represents the geographic distribution of species. + The dataset is provided by Phillips et. al. (2006). + + The two species are: + + - `"Bradypus variegatus" + `_ , + the Brown-throated Sloth. + + - `"Microryzomys minutus" + `_ , + also known as the Forest Small Rice Rat, a rodent that lives in Peru, + Colombia, Ecuador, Peru, and Venezuela. + References ---------- @@ -218,29 +219,28 @@ def fetch_species_distributions(data_home=None, dtype = np.int16 if not exists(join(data_home, DATA_ARCHIVE_NAME)): - print 'Downloading species data from %s to %s' % (SAMPLES_URL, - data_home) - X = np.load(StringIO(urllib2.urlopen(SAMPLES_URL).read())) + print('Downloading species data from %s to %s' % (SAMPLES_URL, + data_home)) + X = np.load(BytesIO(urlopen(SAMPLES_URL).read())) for f in X.files: - fhandle = StringIO(X[f]) + fhandle = BytesIO(X[f]) if 'train' in f: train = _load_csv(fhandle) if 'test' in f: test = _load_csv(fhandle) - print 'Downloading coverage data from %s to %s' % (COVERAGES_URL, - data_home) + print('Downloading coverage data from %s to %s' % (COVERAGES_URL, + data_home)) - X = np.load(StringIO(urllib2.urlopen(COVERAGES_URL).read())) + X = np.load(BytesIO(urlopen(COVERAGES_URL).read())) coverages = [] for f in X.files: - fhandle = StringIO(X[f]) - print ' - converting', f + fhandle = BytesIO(X[f]) + print(' - converting', f) coverages.append(_load_coverage(fhandle)) - coverages = np.asarray(coverages, - dtype=dtype) + coverages = np.asarray(coverages, dtype=dtype) bunch = Bunch(coverages=coverages, test=test, diff --git a/sklearn/datasets/svmlight_format.py b/sklearn/datasets/svmlight_format.py index 34ca99ee5002f..47cd7448077e8 100644 --- a/sklearn/datasets/svmlight_format.py +++ b/sklearn/datasets/svmlight_format.py @@ -13,11 +13,9 @@ # Authors: Mathieu Blondel # Lars Buitinck # Olivier Grisel -# License: Simple BSD. +# License: BSD 3 clause -from bz2 import BZ2File from contextlib import closing -import gzip import io import os.path @@ -26,11 +24,15 @@ from ._svmlight_format import _load_svmlight_file from .. import __version__ -from ..utils import atleast2d_or_csr +from ..externals import six +from ..externals.six import u, b +from ..externals.six.moves import range, zip +from ..utils import check_array +from ..utils.fixes import frombuffer_empty def load_svmlight_file(f, n_features=None, dtype=np.float64, - multilabel=False, zero_based="auto"): + multilabel=False, zero_based="auto", query_id=False): """Load datasets in the svmlight / libsvm format into sparse CSR matrix This format is a text-based format, with one sample per line. It does @@ -48,80 +50,130 @@ def load_svmlight_file(f, n_features=None, dtype=np.float64, CSR results of the first call and benefit from the near instantaneous loading of memmapped structures for the subsequent calls. - This implementation is naive: it does allocate too much memory and - is slow since written in python. On large datasets it is recommended - to use an optimized loader such as: + In case the file contains a pairwise preference constraint (known + as "qid" in the svmlight format) these are ignored unless the + query_id parameter is set to True. These pairwise preference + constraints can be used to constraint the combination of samples + when using pairwise loss functions (as is the case in some + learning to rank problems) so that only pairs with the same + query_id value are considered. + + This implementation is written in Cython and is reasonably fast. + However, a faster API-compatible loader is also available at: https://github.com/mblondel/svmlight-loader Parameters ---------- - f: {str, file-like, int} + f : {str, file-like, int} (Path to) a file to load. If a path ends in ".gz" or ".bz2", it will be uncompressed on the fly. If an integer is passed, it is assumed to be a file descriptor. A file-like or file descriptor will not be closed by this function. A file-like object must be opened in binary mode. - n_features: int or None + n_features : int or None The number of features to use. If None, it will be inferred. This argument is useful to load several files that are subsets of a - bigger sliced dataset: each subset might not have example of + bigger sliced dataset: each subset might not have examples of every feature, hence the inferred shape might vary from one slice to another. - multilabel: boolean, optional + multilabel : boolean, optional, default False Samples may have several labels each (see http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multilabel.html) - zero_based: boolean or "auto", optional + zero_based : boolean or "auto", optional, default "auto" Whether column indices in f are zero-based (True) or one-based - (False). If set to "auto", a heuristic check is applied to determine - this from the file contents. Both kinds of files occur "in the wild", - but they are unfortunately not self-identifying. Using "auto" or True - should always be safe. + (False). If column indices are one-based, they are transformed to + zero-based to match Python/NumPy conventions. + If set to "auto", a heuristic check is applied to determine this from + the file contents. Both kinds of files occur "in the wild", but they + are unfortunately not self-identifying. Using "auto" or True should + always be safe. + + query_id : boolean, default False + If True, will return the query_id array for each file. + + dtype : numpy data type, default np.float64 + Data type of dataset to be loaded. This will be the data type of the + output numpy arrays ``X`` and ``y``. Returns ------- - (X, y) + X: scipy.sparse matrix of shape (n_samples, n_features) + + y: ndarray of shape (n_samples,), or, in the multilabel a list of + tuples of length n_samples. - where X is a scipy.sparse matrix of shape (n_samples, n_features), - y is a ndarray of shape (n_samples,), or, in the multilabel case, - a list of tuples of length n_samples. + query_id: array of shape (n_samples,) + query_id for each sample. Only returned when query_id is set to + True. See also -------- load_svmlight_files: similar function for loading multiple files in this format, enforcing the same number of features/columns on all of them. + + Examples + -------- + To use joblib.Memory to cache the svmlight file:: + + from sklearn.externals.joblib import Memory + from sklearn.datasets import load_svmlight_file + mem = Memory("./mycache") + + @mem.cache + def get_data(): + data = load_svmlight_file("mysvmlightfile") + return data[0], data[1] + + X, y = get_data() """ return tuple(load_svmlight_files([f], n_features, dtype, multilabel, - zero_based)) + zero_based, query_id)) def _gen_open(f): if isinstance(f, int): # file descriptor return io.open(f, "rb", closefd=False) - elif not isinstance(f, basestring): + elif not isinstance(f, six.string_types): raise TypeError("expected {str, int, file-like}, got %s" % type(f)) _, ext = os.path.splitext(f) if ext == ".gz": + import gzip return gzip.open(f, "rb") elif ext == ".bz2": + from bz2 import BZ2File return BZ2File(f, "rb") else: return open(f, "rb") -def _open_and_load(f, dtype, multilabel, zero_based): +def _open_and_load(f, dtype, multilabel, zero_based, query_id): if hasattr(f, "read"): - return _load_svmlight_file(f, dtype, multilabel, zero_based) + actual_dtype, data, ind, indptr, labels, query = \ + _load_svmlight_file(f, dtype, multilabel, zero_based, query_id) # XXX remove closing when Python 2.7+/3.1+ required - with closing(_gen_open(f)) as f: - return _load_svmlight_file(f, dtype, multilabel, zero_based) + else: + with closing(_gen_open(f)) as f: + actual_dtype, data, ind, indptr, labels, query = \ + _load_svmlight_file(f, dtype, multilabel, zero_based, query_id) + + # convert from array.array, give data the right dtype + if not multilabel: + labels = frombuffer_empty(labels, np.float64) + data = frombuffer_empty(data, actual_dtype) + indices = frombuffer_empty(ind, np.intc) + indptr = np.frombuffer(indptr, dtype=np.intc) # never empty + query = frombuffer_empty(query, np.intc) + + data = np.asarray(data, dtype=dtype) # no-op for float{32,64} + return data, indices, indptr, labels, query def load_svmlight_files(files, n_features=None, dtype=np.float64, - multilabel=False, zero_based="auto"): + multilabel=False, zero_based="auto", query_id=False): """Load dataset from multiple files in SVMlight format This function is equivalent to mapping load_svmlight_file over a list of @@ -129,6 +181,14 @@ def load_svmlight_files(files, n_features=None, dtype=np.float64, and the samples vectors are constrained to all have the same number of features. + In case the file contains a pairwise preference constraint (known + as "qid" in the svmlight format) these are ignored unless the + query_id parameter is set to True. These pairwise preference + constraints can be used to constraint the combination of samples + when using pairwise loss functions (as is the case in some + learning to rank problems) so that only pairs with the same + query_id value are considered. + Parameters ---------- files : iterable over {str, file-like, int} @@ -142,25 +202,41 @@ def load_svmlight_files(files, n_features=None, dtype=np.float64, The number of features to use. If None, it will be inferred from the maximum column index occurring in any of the files. + This can be set to a higher value than the actual number of features + in any of the input files, but setting it to a lower value will cause + an exception to be raised. + multilabel: boolean, optional Samples may have several labels each (see http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multilabel.html) zero_based: boolean or "auto", optional - Whether column indices in files are zero-based (True) or one-based - (False). If set to "auto", a heuristic check is applied to determine - this from the files' contents. Both kinds of files occur "in the wild", - but they are unfortunately not self-identifying. Using "auto" or True - should always be safe. - + Whether column indices in f are zero-based (True) or one-based + (False). If column indices are one-based, they are transformed to + zero-based to match Python/NumPy conventions. + If set to "auto", a heuristic check is applied to determine this from + the file contents. Both kinds of files occur "in the wild", but they + are unfortunately not self-identifying. Using "auto" or True should + always be safe. + + query_id: boolean, defaults to False + If True, will return the query_id array for each file. + + dtype : numpy data type, default np.float64 + Data type of dataset to be loaded. This will be the data type of the + output numpy arrays ``X`` and ``y``. + Returns ------- [X1, y1, ..., Xn, yn] - where each (Xi, yi) pair is the result from load_svmlight_file(files[i]). - Rationale - --------- + If query_id is set to True, this will return instead [X1, y1, q1, + ..., Xn, yn, qn] where (Xi, yi, qi) is the result from + load_svmlight_file(files[i]) + + Notes + ----- When fitting a model to a matrix X_train and evaluating it against a matrix X_test, it is essential that X_train and X_test have the same number of features (X_train.shape[1] == X_test.shape[1]). This may not @@ -170,52 +246,77 @@ def load_svmlight_files(files, n_features=None, dtype=np.float64, -------- load_svmlight_file """ - r = [_open_and_load(f, dtype, multilabel, bool(zero_based)) for f in files] + r = [_open_and_load(f, dtype, multilabel, bool(zero_based), bool(query_id)) + for f in files] - if zero_based is False \ - or zero_based == "auto" and all(np.min(indices) > 0 - for _, indices, _, _ in r): - for _, indices, _, _ in r: + if (zero_based is False + or zero_based == "auto" and all(np.min(tmp[1]) > 0 for tmp in r)): + for ind in r: + indices = ind[1] indices -= 1 + n_f = max(ind[1].max() for ind in r) + 1 if n_features is None: - n_features = max(indices.max() for _, indices, _, _ in r) + 1 + n_features = n_f + elif n_features < n_f: + raise ValueError("n_features was set to {}," + " but input file contains {} features" + .format(n_features, n_f)) result = [] - for data, indices, indptr, y in r: + for data, indices, indptr, y, query_values in r: shape = (indptr.shape[0] - 1, n_features) - result += sp.csr_matrix((data, indices, indptr), shape), y + X = sp.csr_matrix((data, indices, indptr), shape) + X.sort_indices() + result += X, y + if query_id: + result.append(query_values) return result -def _dump_svmlight(X, y, f, one_based, comment): +def _dump_svmlight(X, y, f, one_based, comment, query_id): is_sp = int(hasattr(X, "tocsr")) - if X.dtype == np.float64: - value_pattern = u"%d:%0.16e" + if X.dtype.kind == 'i': + value_pattern = u("%d:%d") else: - value_pattern = u"%d:%f" + value_pattern = u("%d:%.16g") if y.dtype.kind == 'i': - line_pattern = u"%d %s\n" + line_pattern = u("%d") else: - line_pattern = u"%f %s\n" + line_pattern = u("%.16g") - f.write("# Generated by dump_svmlight_file from scikit-learn %s\n" - % __version__) - f.write("# Column indices are %s-based\n" % ["zero", "one"][one_based]) + if query_id is not None: + line_pattern += u(" qid:%d") + line_pattern += u(" %s\n") if comment: - f.write("#\n") - f.writelines("# %s\n" % line for line in comment) + f.write(b("# Generated by dump_svmlight_file from scikit-learn %s\n" + % __version__)) + f.write(b("# Column indices are %s-based\n" + % ["zero", "one"][one_based])) + + f.write(b("#\n")) + f.writelines(b("# %s\n" % line) for line in comment.splitlines()) + + for i in range(X.shape[0]): + if is_sp: + span = slice(X.indptr[i], X.indptr[i + 1]) + row = zip(X.indices[span], X.data[span]) + else: + nz = X[i] != 0 + row = zip(np.where(nz)[0], X[i, nz]) - for i in xrange(X.shape[0]): - s = u" ".join([value_pattern % (j + one_based, X[i, j]) - for j in X[i].nonzero()[is_sp]]) - f.write((line_pattern % (y[i], s)).encode('ascii')) + s = " ".join(value_pattern % (j + one_based, x) for j, x in row) + if query_id is not None: + feat = (y[i], query_id[i], s) + else: + feat = (y[i], s) + f.write((line_pattern % feat).encode('ascii')) -def dump_svmlight_file(X, y, f, zero_based=True, comment=None): +def dump_svmlight_file(X, y, f, zero_based=True, comment=None, query_id=None): """Dump the dataset in svmlight / libsvm file format. This format is a text-based format, with one sample per line. It does @@ -246,6 +347,13 @@ def dump_svmlight_file(X, y, f, zero_based=True, comment=None): Comment to insert at the top of the file. This should be either a Unicode string, which will be encoded as UTF-8, or an ASCII byte string. + If a comment is given, then it will be preceded by one that identifies + the file as having been dumped by scikit-learn. Note that not all + tools grok comments in SVMlight files. + + query_id : array-like, shape = [n_samples] + Array containing pairwise preference constraints (qid in svmlight + format). """ if comment is not None: # Convert comment string to list of lines in UTF-8. @@ -256,23 +364,39 @@ def dump_svmlight_file(X, y, f, zero_based=True, comment=None): comment.decode("ascii") # just for the exception else: comment = comment.encode("utf-8") - if "\0" in comment: + if six.b("\0") in comment: raise ValueError("comment string contains NUL byte") - comment = comment.splitlines() y = np.asarray(y) if y.ndim != 1: - raise ValueError("expected y of shape [n_samples], got %r" % y) + raise ValueError("expected y of shape (n_samples,), got %r" + % (y.shape,)) + + Xval = check_array(X, accept_sparse='csr') + if Xval.shape[0] != y.shape[0]: + raise ValueError("X.shape[0] and y.shape[0] should be the same, got" + " %r and %r instead." % (Xval.shape[0], y.shape[0])) + + # We had some issues with CSR matrices with unsorted indices (e.g. #1501), + # so sort them here, but first make sure we don't modify the user's X. + # TODO We can do this cheaper; sorted_indices copies the whole matrix. + if Xval is X and hasattr(Xval, "sorted_indices"): + X = Xval.sorted_indices() + else: + X = Xval + if hasattr(X, "sort_indices"): + X.sort_indices() - X = atleast2d_or_csr(X) - if X.shape[0] != y.shape[0]: - raise ValueError("X.shape[0] and y.shape[0] should be the same, " - "got: %r and %r instead." % (X.shape[0], y.shape[0])) + if query_id is not None: + query_id = np.asarray(query_id) + if query_id.shape[0] != y.shape[0]: + raise ValueError("expected query_id of shape (n_samples,), got %r" + % (query_id.shape,)) one_based = not zero_based if hasattr(f, "write"): - _dump_svmlight(X, y, f, one_based, comment) + _dump_svmlight(X, y, f, one_based, comment, query_id) else: with open(f, "wb") as f: - _dump_svmlight(X, y, f, one_based, comment) + _dump_svmlight(X, y, f, one_based, comment, query_id) diff --git a/sklearn/datasets/tests/test_20news.py b/sklearn/datasets/tests/test_20news.py index 1b77d7d3219ce..6365ccdbc7ddb 100644 --- a/sklearn/datasets/tests/test_20news.py +++ b/sklearn/datasets/tests/test_20news.py @@ -1,25 +1,24 @@ """Test the 20news downloader, if the data is available.""" import numpy as np import scipy.sparse as sp -from nose.tools import assert_equal -from nose.tools import assert_true -from nose.plugins.skip import SkipTest + +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import SkipTest from sklearn import datasets def test_20news(): try: - data = datasets.fetch_20newsgroups(subset='all', - download_if_missing=False, - shuffle=False) + data = datasets.fetch_20newsgroups( + subset='all', download_if_missing=False, shuffle=False) except IOError: raise SkipTest("Download 20 newsgroups to run this test") # Extract a reduced dataset - data2cats = datasets.fetch_20newsgroups(subset='all', - categories=data.target_names[-1:-3:-1], - shuffle=False) + data2cats = datasets.fetch_20newsgroups( + subset='all', categories=data.target_names[-1:-3:-1], shuffle=False) # Check that the ordering of the target_names is the same # as the ordering in the full dataset assert_equal(data2cats.target_names, @@ -42,7 +41,7 @@ def test_20news(): def test_20news_vectorized(): # This test is slow. - raise SkipTest + raise SkipTest("Test too slow.") bunch = datasets.fetch_20newsgroups_vectorized(subset="train") assert_true(sp.isspmatrix_csr(bunch.data)) diff --git a/sklearn/datasets/tests/test_base.py b/sklearn/datasets/tests/test_base.py index f8dfae333dbdf..1725fb2518ffc 100644 --- a/sklearn/datasets/tests/test_base.py +++ b/sklearn/datasets/tests/test_base.py @@ -1,28 +1,66 @@ import os import shutil import tempfile +import warnings +import nose +import numpy from sklearn.datasets import get_data_home from sklearn.datasets import clear_data_home +from sklearn.datasets import load_files +from sklearn.datasets import load_sample_images +from sklearn.datasets import load_sample_image +from sklearn.datasets import load_digits +from sklearn.datasets import load_diabetes +from sklearn.datasets import load_linnerud +from sklearn.datasets import load_iris +from sklearn.datasets import load_boston -from nose.tools import assert_false -from nose.tools import assert_true -from nose.tools import assert_equals +from sklearn.externals.six import b, u + +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_raises DATA_HOME = tempfile.mkdtemp(prefix="scikit_learn_data_home_test_") +LOAD_FILES_ROOT = tempfile.mkdtemp(prefix="scikit_learn_load_files_test_") +TEST_CATEGORY_DIR1 = "" +TEST_CATEGORY_DIR2 = "" + + +def _remove_dir(path): + if os.path.isdir(path): + shutil.rmtree(path) def teardown_module(): """Test fixture (clean up) run once after all tests of this module""" - if os.path.isdir(DATA_HOME): - shutil.rmtree(DATA_HOME) + for path in [DATA_HOME, LOAD_FILES_ROOT]: + _remove_dir(path) + + +def setup_load_files(): + global TEST_CATEGORY_DIR1 + global TEST_CATEGORY_DIR2 + TEST_CATEGORY_DIR1 = tempfile.mkdtemp(dir=LOAD_FILES_ROOT) + TEST_CATEGORY_DIR2 = tempfile.mkdtemp(dir=LOAD_FILES_ROOT) + sample_file = tempfile.NamedTemporaryFile(dir=TEST_CATEGORY_DIR1, + delete=False) + sample_file.write(b("Hello World!\n")) + sample_file.close() + + +def teardown_load_files(): + _remove_dir(TEST_CATEGORY_DIR1) + _remove_dir(TEST_CATEGORY_DIR2) def test_data_home(): # get_data_home will point to a pre-existing folder data_home = get_data_home(data_home=DATA_HOME) - assert_equals(data_home, DATA_HOME) + assert_equal(data_home, DATA_HOME) assert_true(os.path.exists(data_home)) # clear_data_home will delete both the content and the folder it-self @@ -32,3 +70,116 @@ def test_data_home(): # if the folder is missing it will be created again data_home = get_data_home(data_home=DATA_HOME) assert_true(os.path.exists(data_home)) + + +def test_default_empty_load_files(): + res = load_files(LOAD_FILES_ROOT) + assert_equal(len(res.filenames), 0) + assert_equal(len(res.target_names), 0) + assert_equal(res.DESCR, None) + + +@nose.tools.with_setup(setup_load_files, teardown_load_files) +def test_default_load_files(): + res = load_files(LOAD_FILES_ROOT) + assert_equal(len(res.filenames), 1) + assert_equal(len(res.target_names), 2) + assert_equal(res.DESCR, None) + assert_equal(res.data, [b("Hello World!\n")]) + + +@nose.tools.with_setup(setup_load_files, teardown_load_files) +def test_load_files_w_categories_desc_and_encoding(): + category = os.path.abspath(TEST_CATEGORY_DIR1).split('/').pop() + res = load_files(LOAD_FILES_ROOT, description="test", + categories=category, encoding="utf-8") + assert_equal(len(res.filenames), 1) + assert_equal(len(res.target_names), 1) + assert_equal(res.DESCR, "test") + assert_equal(res.data, [u("Hello World!\n")]) + + +@nose.tools.with_setup(setup_load_files, teardown_load_files) +def test_load_files_wo_load_content(): + res = load_files(LOAD_FILES_ROOT, load_content=False) + assert_equal(len(res.filenames), 1) + assert_equal(len(res.target_names), 2) + assert_equal(res.DESCR, None) + assert_equal(res.get('data'), None) + + +def test_load_sample_images(): + try: + res = load_sample_images() + assert_equal(len(res.images), 2) + assert_equal(len(res.filenames), 2) + assert_true(res.DESCR) + except ImportError: + warnings.warn("Could not load sample images, PIL is not available.") + + +def test_load_digits(): + digits = load_digits() + assert_equal(digits.data.shape, (1797, 64)) + assert_equal(numpy.unique(digits.target).size, 10) + + +def test_load_digits_n_class_lt_10(): + digits = load_digits(9) + assert_equal(digits.data.shape, (1617, 64)) + assert_equal(numpy.unique(digits.target).size, 9) + + +def test_load_sample_image(): + try: + china = load_sample_image('china.jpg') + assert_equal(china.dtype, 'uint8') + assert_equal(china.shape, (427, 640, 3)) + except ImportError: + warnings.warn("Could not load sample images, PIL is not available.") + + +def test_load_missing_sample_image_error(): + have_PIL = True + try: + try: + from scipy.misc import imread + except ImportError: + from scipy.misc.pilutil import imread + except ImportError: + have_PIL = False + if have_PIL: + assert_raises(AttributeError, load_sample_image, + 'blop.jpg') + else: + warnings.warn("Could not load sample images, PIL is not available.") + + +def test_load_diabetes(): + res = load_diabetes() + assert_equal(res.data.shape, (442, 10)) + assert_true(res.target.size, 442) + + +def test_load_linnerud(): + res = load_linnerud() + assert_equal(res.data.shape, (20, 3)) + assert_equal(res.target.shape, (20, 3)) + assert_equal(len(res.target_names), 3) + assert_true(res.DESCR) + + +def test_load_iris(): + res = load_iris() + assert_equal(res.data.shape, (150, 4)) + assert_equal(res.target.size, 150) + assert_equal(res.target_names.size, 3) + assert_true(res.DESCR) + + +def test_load_boston(): + res = load_boston() + assert_equal(res.data.shape, (506, 13)) + assert_equal(res.target.size, 506) + assert_equal(res.feature_names.size, 13) + assert_true(res.DESCR) diff --git a/sklearn/datasets/tests/test_covtype.py b/sklearn/datasets/tests/test_covtype.py new file mode 100644 index 0000000000000..f32511d7c9aa8 --- /dev/null +++ b/sklearn/datasets/tests/test_covtype.py @@ -0,0 +1,32 @@ +"""Test the covtype loader. + +Skipped if covtype is not already downloaded to data_home. +""" + +import errno +from sklearn.datasets import fetch_covtype +from sklearn.utils.testing import assert_equal, SkipTest + + +def fetch(*args, **kwargs): + return fetch_covtype(*args, download_if_missing=False, **kwargs) + + +def test_fetch(): + try: + data1 = fetch(shuffle=True, random_state=42) + except IOError as e: + if e.errno == errno.ENOENT: + raise SkipTest("Covertype dataset can not be loaded.") + + data2 = fetch(shuffle=True, random_state=37) + + X1, X2 = data1['data'], data2['data'] + assert_equal((581012, 54), X1.shape) + assert_equal(X1.shape, X2.shape) + + assert_equal(X1.sum(), X2.sum()) + + y1, y2 = data1['target'], data2['target'] + assert_equal((X1.shape[0],), y1.shape) + assert_equal((X1.shape[0],), y2.shape) diff --git a/sklearn/datasets/tests/test_lfw.py b/sklearn/datasets/tests/test_lfw.py index 39d0c1ffdd647..5e4788d3bfbae 100644 --- a/sklearn/datasets/tests/test_lfw.py +++ b/sklearn/datasets/tests/test_lfw.py @@ -1,6 +1,6 @@ """This test for the LFW require medium-size data dowloading and processing -If the data has not been already downloaded by runnning the examples, +If the data has not been already downloaded by running the examples, the tests won't run (skipped). If the test are run, the first execution will be long (typically a bit @@ -13,6 +13,7 @@ import shutil import tempfile import numpy as np +from sklearn.externals import six try: try: from scipy.misc import imsave @@ -24,10 +25,10 @@ from sklearn.datasets import load_lfw_pairs from sklearn.datasets import load_lfw_people -from numpy.testing import assert_array_equal -from numpy.testing import assert_equal -from nose import SkipTest -from nose.tools import raises +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import SkipTest +from sklearn.utils.testing import raises SCIKIT_LEARN_DATA = tempfile.mkdtemp(prefix="scikit_learn_lfw_test_") @@ -48,7 +49,7 @@ def setup_module(): """Test fixture run once and common to all tests of this module""" if imsave is None: - raise SkipTest + raise SkipTest("PIL not installed.") if not os.path.exists(LFW_HOME): os.makedirs(LFW_HOME) @@ -71,35 +72,34 @@ def setup_module(): try: imsave(file_path, uniface) except ImportError: - # PIL is not properly installed, skip those tests - raise SkipTest + raise SkipTest("PIL not installed") # add some random file pollution to test robustness with open(os.path.join(LFW_HOME, 'lfw_funneled', '.test.swp'), 'wb') as f: - f.write('Text file to be ignored by the dataset loader.') + f.write(six.b('Text file to be ignored by the dataset loader.')) # generate some pairing metadata files using the same format as LFW with open(os.path.join(LFW_HOME, 'pairsDevTrain.txt'), 'wb') as f: - f.write("10\n") - more_than_two = [name for name, count in counts.iteritems() + f.write(six.b("10\n")) + more_than_two = [name for name, count in six.iteritems(counts) if count >= 2] for i in range(5): name = random_state.choice(more_than_two) first, second = random_state.sample(range(counts[name]), 2) - f.write('%s\t%d\t%d\n' % (name, first, second)) + f.write(six.b('%s\t%d\t%d\n' % (name, first, second))) for i in range(5): first_name, second_name = random_state.sample(FAKE_NAMES, 2) - first_index = random_state.choice(range(counts[first_name])) - second_index = random_state.choice(range(counts[second_name])) - f.write('%s\t%d\t%s\t%d\n' % (first_name, first_index, - second_name, second_index)) + first_index = random_state.choice(np.arange(counts[first_name])) + second_index = random_state.choice(np.arange(counts[second_name])) + f.write(six.b('%s\t%d\t%s\t%d\n' % (first_name, first_index, + second_name, second_index))) with open(os.path.join(LFW_HOME, 'pairsDevTest.txt'), 'wb') as f: - f.write("Fake place holder that won't be tested") + f.write(six.b("Fake place holder that won't be tested")) with open(os.path.join(LFW_HOME, 'pairs.txt'), 'wb') as f: - f.write("Fake place holder that won't be tested") + f.write(six.b("Fake place holder that won't be tested")) def teardown_module(): @@ -141,8 +141,8 @@ def test_load_fake_lfw_people(): assert_array_equal(lfw_people.target, [0, 0, 1, 6, 5, 6, 3, 6, 0, 3, 6, 1, 2, 4, 5, 1, 2]) assert_array_equal(lfw_people.target_names, - ['Abdelatif Smith', 'Abhati Kepler', 'Camara Alvaro', - 'Chen Dupont', 'John Lee', 'Lin Bauman', 'Onur Lopez']) + ['Abdelatif Smith', 'Abhati Kepler', 'Camara Alvaro', + 'Chen Dupont', 'John Lee', 'Lin Bauman', 'Onur Lopez']) @raises(ValueError) diff --git a/sklearn/datasets/tests/test_mldata.py b/sklearn/datasets/tests/test_mldata.py index a9771f1f64f20..1ce22079bdd11 100644 --- a/sklearn/datasets/tests/test_mldata.py +++ b/sklearn/datasets/tests/test_mldata.py @@ -1,16 +1,22 @@ """Test functionality of mldata fetching utilities.""" -from sklearn import datasets -from sklearn.datasets import mldata_filename, fetch_mldata -from sklearn.utils.testing import assert_in, assert_not_in, mock_urllib2 -from nose.tools import assert_equal, assert_raises -from nose import with_setup -from numpy.testing import assert_array_equal import os import shutil import tempfile import scipy as sp +from sklearn import datasets +from sklearn.datasets import mldata_filename, fetch_mldata + +from sklearn.utils.testing import assert_in +from sklearn.utils.testing import assert_not_in +from sklearn.utils.testing import mock_mldata_urlopen +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import with_setup +from sklearn.utils.testing import assert_array_equal + + tmpdir = None @@ -41,10 +47,13 @@ def test_mldata_filename(): def test_download(): """Test that fetch_mldata is able to download and cache a data set.""" - _urllib2_ref = datasets.mldata.urllib2 - datasets.mldata.urllib2 = mock_urllib2({'mock': - {'label': sp.ones((150,)), - 'data': sp.ones((150, 4))}}) + _urlopen_ref = datasets.mldata.urlopen + datasets.mldata.urlopen = mock_mldata_urlopen({ + 'mock': { + 'label': sp.ones((150,)), + 'data': sp.ones((150, 4)), + }, + }) try: mock = fetch_mldata('mock', data_home=tmpdir) for n in ["COL_NAMES", "DESCR", "target", "data"]: @@ -53,20 +62,20 @@ def test_download(): assert_equal(mock.target.shape, (150,)) assert_equal(mock.data.shape, (150, 4)) - assert_raises(datasets.mldata.urllib2.HTTPError, + assert_raises(datasets.mldata.HTTPError, fetch_mldata, 'not_existing_name') finally: - datasets.mldata.urllib2 = _urllib2_ref + datasets.mldata.urlopen = _urlopen_ref @with_setup(setup_tmpdata, teardown_tmpdata) def test_fetch_one_column(): - _urllib2_ref = datasets.mldata.urllib2 + _urlopen_ref = datasets.mldata.urlopen try: dataname = 'onecol' # create fake data set in cache x = sp.arange(6).reshape(2, 3) - datasets.mldata.urllib2 = mock_urllib2({dataname: {'x': x}}) + datasets.mldata.urlopen = mock_mldata_urlopen({dataname: {'x': x}}) dset = fetch_mldata(dataname, data_home=tmpdir) for n in ["COL_NAMES", "DESCR", "data"]: @@ -80,12 +89,12 @@ def test_fetch_one_column(): dset = fetch_mldata(dataname, transpose_data=False, data_home=tmpdir) assert_equal(dset.data.shape, (3, 2)) finally: - datasets.mldata.urllib2 = _urllib2_ref + datasets.mldata.urlopen = _urlopen_ref @with_setup(setup_tmpdata, teardown_tmpdata) def test_fetch_multiple_column(): - _urllib2_ref = datasets.mldata.urllib2 + _urlopen_ref = datasets.mldata.urlopen try: # create fake data set in cache x = sp.arange(6).reshape(2, 3) @@ -94,11 +103,16 @@ def test_fetch_multiple_column(): # by default dataname = 'threecol-default' - datasets.mldata.urllib2 = mock_urllib2({dataname: - ({'label': y, - 'data': x, - 'z': z}, - ['z', 'data', 'label'])}) + datasets.mldata.urlopen = mock_mldata_urlopen({ + dataname: ( + { + 'label': y, + 'data': x, + 'z': z, + }, + ['z', 'data', 'label'], + ), + }) dset = fetch_mldata(dataname, data_home=tmpdir) for n in ["COL_NAMES", "DESCR", "target", "data", "z"]: @@ -112,11 +126,9 @@ def test_fetch_multiple_column(): # by order dataname = 'threecol-order' - datasets.mldata.urllib2 = mock_urllib2({dataname: - ({'y': y, - 'x': x, - 'z': z}, - ['y', 'x', 'z'])}) + datasets.mldata.urlopen = mock_mldata_urlopen({ + dataname: ({'y': y, 'x': x, 'z': z}, + ['y', 'x', 'z']), }) dset = fetch_mldata(dataname, data_home=tmpdir) for n in ["COL_NAMES", "DESCR", "target", "data", "z"]: @@ -130,11 +142,10 @@ def test_fetch_multiple_column(): # by number dataname = 'threecol-number' - datasets.mldata.urllib2 = mock_urllib2({dataname: - ({'y': y, - 'x': x, - 'z': z}, - ['z', 'x', 'y'])}) + datasets.mldata.urlopen = mock_mldata_urlopen({ + dataname: ({'y': y, 'x': x, 'z': z}, + ['z', 'x', 'y']), + }) dset = fetch_mldata(dataname, target_name=2, data_name=0, data_home=tmpdir) @@ -155,4 +166,4 @@ def test_fetch_multiple_column(): assert_not_in("z", dset) finally: - datasets.mldata.urllib2 = _urllib2_ref + datasets.mldata.urlopen = _urlopen_ref diff --git a/sklearn/datasets/tests/test_samples_generator.py b/sklearn/datasets/tests/test_samples_generator.py index 1cf5079065fa4..b6c5dac64e55c 100644 --- a/sklearn/datasets/tests/test_samples_generator.py +++ b/sklearn/datasets/tests/test_samples_generator.py @@ -1,24 +1,38 @@ +from __future__ import division + +from collections import defaultdict +from functools import partial + import numpy as np -from numpy.testing import assert_equal, assert_approx_equal, \ - assert_array_almost_equal -from nose.tools import assert_true +from sklearn.externals.six.moves import zip +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_less - -from .. import make_classification -from .. import make_multilabel_classification -from .. import make_hastie_10_2 -from .. import make_regression -from .. import make_blobs -from .. import make_friedman1 -from .. import make_friedman2 -from .. import make_friedman3 -from .. import make_low_rank_matrix -from .. import make_sparse_coded_signal -from .. import make_sparse_uncorrelated -from .. import make_spd_matrix -from .. import make_swiss_roll -from .. import make_s_curve +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_warns + +from sklearn.datasets import make_classification +from sklearn.datasets import make_multilabel_classification +from sklearn.datasets import make_hastie_10_2 +from sklearn.datasets import make_regression +from sklearn.datasets import make_blobs +from sklearn.datasets import make_friedman1 +from sklearn.datasets import make_friedman2 +from sklearn.datasets import make_friedman3 +from sklearn.datasets import make_low_rank_matrix +from sklearn.datasets import make_sparse_coded_signal +from sklearn.datasets import make_sparse_uncorrelated +from sklearn.datasets import make_spd_matrix +from sklearn.datasets import make_swiss_roll +from sklearn.datasets import make_s_curve +from sklearn.datasets import make_biclusters +from sklearn.datasets import make_checkerboard + +from sklearn.utils.validation import assert_all_finite def test_make_classification(): @@ -36,11 +50,93 @@ def test_make_classification(): assert_equal(sum(y == 2), 65, "Unexpected number of samples in class #2") -def test_make_multilabel_classification(): +def test_make_classification_informative_features(): + """Test the construction of informative features in make_classification + + Also tests `n_clusters_per_class`, `n_classes`, `hypercube` and + fully-specified `weights`. + """ + # Create very separate clusters; check that vertices are unique and + # correspond to classes + class_sep = 1e6 + make = partial(make_classification, class_sep=class_sep, n_redundant=0, + n_repeated=0, flip_y=0, shift=0, scale=1, shuffle=False) + + for n_informative, weights, n_clusters_per_class in [(2, [1], 1), + (2, [1/3] * 3, 1), + (2, [1/4] * 4, 1), + (2, [1/2] * 2, 2), + (2, [3/4, 1/4], 2), + (10, [1/3] * 3, 10) + ]: + n_classes = len(weights) + n_clusters = n_classes * n_clusters_per_class + n_samples = n_clusters * 50 + + for hypercube in (False, True): + X, y = make(n_samples=n_samples, n_classes=n_classes, + weights=weights, n_features=n_informative, + n_informative=n_informative, + n_clusters_per_class=n_clusters_per_class, + hypercube=hypercube, random_state=0) + + assert_equal(X.shape, (n_samples, n_informative)) + assert_equal(y.shape, (n_samples,)) + + # Cluster by sign, viewed as strings to allow uniquing + signs = np.sign(X) + signs = signs.view(dtype='|S{0}'.format(signs.strides[0])) + unique_signs, cluster_index = np.unique(signs, + return_inverse=True) + + assert_equal(len(unique_signs), n_clusters, + "Wrong number of clusters, or not in distinct " + "quadrants") + + clusters_by_class = defaultdict(set) + for cluster, cls in zip(cluster_index, y): + clusters_by_class[cls].add(cluster) + for clusters in clusters_by_class.values(): + assert_equal(len(clusters), n_clusters_per_class, + "Wrong number of clusters per class") + assert_equal(len(clusters_by_class), n_classes, + "Wrong number of classes") + + assert_array_almost_equal(np.bincount(y) / len(y) // weights, + [1] * n_classes, + err_msg="Wrong number of samples " + "per class") + + # Ensure on vertices of hypercube + for cluster in range(len(unique_signs)): + centroid = X[cluster_index == cluster].mean(axis=0) + if hypercube: + assert_array_almost_equal(np.abs(centroid), + [class_sep] * n_informative, + decimal=0, + err_msg="Clusters are not " + "centered on hypercube " + "vertices") + else: + assert_raises(AssertionError, + assert_array_almost_equal, + np.abs(centroid), + [class_sep] * n_informative, + decimal=0, + err_msg="Clusters should not be cenetered " + "on hypercube vertices") + + assert_raises(ValueError, make, n_features=2, n_informative=2, n_classes=5, + n_clusters_per_class=1) + assert_raises(ValueError, make, n_features=2, n_informative=2, n_classes=3, + n_clusters_per_class=2) + + +def test_make_multilabel_classification_return_sequences(): for allow_unlabeled, min_length in zip((True, False), (0, 1)): - X, Y = make_multilabel_classification(n_samples=100, n_features=20, - n_classes=3, random_state=0, - allow_unlabeled=allow_unlabeled) + X, Y = assert_warns(DeprecationWarning, make_multilabel_classification, + n_samples=100, n_features=20, n_classes=3, + random_state=0, allow_unlabeled=allow_unlabeled) assert_equal(X.shape, (100, 20), "X shape mismatch") if not allow_unlabeled: assert_equal(max([max(y) for y in Y]), 2) @@ -48,6 +144,30 @@ def test_make_multilabel_classification(): assert_true(max([len(y) for y in Y]) <= 3) +def test_make_multilabel_classification_return_indicator(): + for allow_unlabeled, min_length in zip((True, False), (0, 1)): + X, Y = make_multilabel_classification(n_samples=25, n_features=20, + n_classes=3, random_state=0, + return_indicator=True, + allow_unlabeled=allow_unlabeled) + assert_equal(X.shape, (25, 20), "X shape mismatch") + assert_equal(Y.shape, (25, 3), "Y shape mismatch") + assert_true(np.all(np.sum(Y, axis=0) > min_length)) + + # Also test return_distributions + X2, Y2, p_c, p_w_c = make_multilabel_classification( + n_samples=25, n_features=20, n_classes=3, random_state=0, + return_indicator=True, allow_unlabeled=allow_unlabeled, + return_distributions=True) + + assert_array_equal(X, X2) + assert_array_equal(Y, Y2) + assert_equal(p_c.shape, (3,)) + assert_almost_equal(p_c.sum(), 1) + assert_equal(p_w_c.shape, (20, 3)) + assert_almost_equal(p_w_c.sum(axis=0), [1] * 3) + + def test_make_hastie_10_2(): X, y = make_hastie_10_2(n_samples=100, random_state=0) assert_equal(X.shape, (100, 10), "X shape mismatch") @@ -65,8 +185,12 @@ def test_make_regression(): assert_equal(c.shape, (10,), "coef shape mismatch") assert_equal(sum(c != 0.0), 3, "Unexpected number of informative features") - # Test that y ~= np.dot(X, c) + bias + N(0, 1.0) - assert_approx_equal(np.std(y - np.dot(X, c)), 1.0, significant=2) + # Test that y ~= np.dot(X, c) + bias + N(0, 1.0). + assert_almost_equal(np.std(y - np.dot(X, c)), 1.0, decimal=1) + + # Test with small number of features. + X, y = make_regression(n_samples=100, n_features=1) # n_informative=3 + assert_equal(X.shape, (100, 1)) def test_make_regression_multitarget(): @@ -76,10 +200,11 @@ def test_make_regression_multitarget(): assert_equal(X.shape, (100, 10), "X shape mismatch") assert_equal(y.shape, (100, 3), "y shape mismatch") assert_equal(c.shape, (10, 3), "coef shape mismatch") - assert_equal(sum(c != 0.0), 3, "Unexpected number of informative features") + assert_array_equal(sum(c != 0.0), 3, + "Unexpected number of informative features") # Test that y ~= np.dot(X, c) + bias + N(0, 1.0) - assert_approx_equal(np.std(y - np.dot(X, c)), 1.0, significant=2) + assert_almost_equal(np.std(y - np.dot(X, c)), 1.0, decimal=1) def test_make_blobs(): @@ -99,9 +224,10 @@ def test_make_friedman1(): assert_equal(X.shape, (5, 10), "X shape mismatch") assert_equal(y.shape, (5,), "y shape mismatch") - assert_array_almost_equal(y, 10 * np.sin(np.pi * X[:, 0] * X[:, 1]) - + 20 * (X[:, 2] - 0.5) ** 2 \ - + 10 * X[:, 3] + 5 * X[:, 4]) + assert_array_almost_equal(y, + 10 * np.sin(np.pi * X[:, 0] * X[:, 1]) + + 20 * (X[:, 2] - 0.5) ** 2 + + 10 * X[:, 3] + 5 * X[:, 4]) def test_make_friedman2(): @@ -110,9 +236,10 @@ def test_make_friedman2(): assert_equal(X.shape, (5, 4), "X shape mismatch") assert_equal(y.shape, (5,), "y shape mismatch") - assert_array_almost_equal(y, (X[:, 0] ** 2 - + (X[:, 1] * X[:, 2] - - 1 / (X[:, 1] * X[:, 3])) ** 2) ** 0.5) + assert_array_almost_equal(y, + (X[:, 0] ** 2 + + (X[:, 1] * X[:, 2] - 1 + / (X[:, 1] * X[:, 3])) ** 2) ** 0.5) def test_make_friedman3(): @@ -139,14 +266,14 @@ def test_make_low_rank_matrix(): def test_make_sparse_coded_signal(): Y, D, X = make_sparse_coded_signal(n_samples=5, n_components=8, - n_features=10, n_nonzero_coefs=3, - random_state=0) + n_features=10, n_nonzero_coefs=3, + random_state=0) assert_equal(Y.shape, (10, 5), "Y shape mismatch") assert_equal(D.shape, (10, 8), "D shape mismatch") assert_equal(X.shape, (8, 5), "X shape mismatch") for col in X.T: assert_equal(len(np.flatnonzero(col)), 3, 'Non-zero coefs mismatch') - assert_equal(np.dot(D, X), Y) + assert_array_almost_equal(np.dot(D, X), Y) assert_array_almost_equal(np.sqrt((D ** 2).sum(axis=0)), np.ones(D.shape[1])) @@ -166,8 +293,8 @@ def test_make_spd_matrix(): from numpy.linalg import eig eigenvalues, _ = eig(X) - assert_equal(eigenvalues > 0, np.array([True] * 5), - "X is not positive-definite") + assert_array_equal(eigenvalues > 0, np.array([True] * 5), + "X is not positive-definite") def test_make_swiss_roll(): @@ -175,8 +302,8 @@ def test_make_swiss_roll(): assert_equal(X.shape, (5, 3), "X shape mismatch") assert_equal(t.shape, (5,), "t shape mismatch") - assert_equal(X[:, 0], t * np.cos(t)) - assert_equal(X[:, 2], t * np.sin(t)) + assert_array_almost_equal(X[:, 0], t * np.cos(t)) + assert_array_almost_equal(X[:, 2], t * np.sin(t)) def test_make_s_curve(): @@ -184,5 +311,41 @@ def test_make_s_curve(): assert_equal(X.shape, (5, 3), "X shape mismatch") assert_equal(t.shape, (5,), "t shape mismatch") - assert_equal(X[:, 0], np.sin(t)) - assert_equal(X[:, 2], np.sign(t) * (np.cos(t) - 1)) + assert_array_almost_equal(X[:, 0], np.sin(t)) + assert_array_almost_equal(X[:, 2], np.sign(t) * (np.cos(t) - 1)) + + +def test_make_biclusters(): + X, rows, cols = make_biclusters( + shape=(100, 100), n_clusters=4, shuffle=True, random_state=0) + assert_equal(X.shape, (100, 100), "X shape mismatch") + assert_equal(rows.shape, (4, 100), "rows shape mismatch") + assert_equal(cols.shape, (4, 100,), "columns shape mismatch") + assert_all_finite(X) + assert_all_finite(rows) + assert_all_finite(cols) + + X2, _, _ = make_biclusters(shape=(100, 100), n_clusters=4, + shuffle=True, random_state=0) + assert_array_almost_equal(X, X2) + + +def test_make_checkerboard(): + X, rows, cols = make_checkerboard( + shape=(100, 100), n_clusters=(20, 5), + shuffle=True, random_state=0) + assert_equal(X.shape, (100, 100), "X shape mismatch") + assert_equal(rows.shape, (100, 100), "rows shape mismatch") + assert_equal(cols.shape, (100, 100,), "columns shape mismatch") + + X, rows, cols = make_checkerboard( + shape=(100, 100), n_clusters=2, shuffle=True, random_state=0) + assert_all_finite(X) + assert_all_finite(rows) + assert_all_finite(cols) + + X1, _, _ = make_checkerboard(shape=(100, 100), n_clusters=2, + shuffle=True, random_state=0) + X2, _, _ = make_checkerboard(shape=(100, 100), n_clusters=2, + shuffle=True, random_state=0) + assert_array_equal(X1, X2) diff --git a/sklearn/datasets/tests/test_svmlight_format.py b/sklearn/datasets/tests/test_svmlight_format.py index 275f4e54e7269..19fca2cbaea8b 100644 --- a/sklearn/datasets/tests/test_svmlight_format.py +++ b/sklearn/datasets/tests/test_svmlight_format.py @@ -4,17 +4,20 @@ import numpy as np import os import shutil -import tempfile +from tempfile import NamedTemporaryFile -from numpy.testing import assert_equal -from numpy.testing import assert_array_equal -from numpy.testing import assert_array_almost_equal -from nose.tools import assert_raises, raises +from sklearn.externals.six import b + +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import raises +from sklearn.utils.testing import assert_in import sklearn from sklearn.datasets import (load_svmlight_file, load_svmlight_files, dump_svmlight_file) -from sklearn.utils.testing import assert_in currdir = os.path.dirname(os.path.abspath(__file__)) datafile = os.path.join(currdir, "data", "svmlight_classification.txt") @@ -61,8 +64,8 @@ def test_load_svmlight_file_fd(): fd = os.open(datafile, os.O_RDONLY) try: X2, y2 = load_svmlight_file(fd) - assert_equal(X1.data, X2.data) - assert_equal(y1, y2) + assert_array_equal(X1.data, X2.data) + assert_array_equal(y1, y2) finally: os.close(fd) @@ -88,12 +91,12 @@ def test_load_svmlight_files(): def test_load_svmlight_file_n_features(): - X, y = load_svmlight_file(datafile, n_features=20) + X, y = load_svmlight_file(datafile, n_features=22) # test X'shape assert_equal(X.indptr.shape[0], 7) assert_equal(X.shape[0], 6) - assert_equal(X.shape[1], 20) + assert_equal(X.shape[1], 22) # test X's non-zero values for i, j, val in ((0, 2, 2.5), (0, 10, -5.2), @@ -101,27 +104,34 @@ def test_load_svmlight_file_n_features(): assert_equal(X[i, j], val) + # 21 features in file + assert_raises(ValueError, load_svmlight_file, datafile, n_features=20) + def test_load_compressed(): X, y = load_svmlight_file(datafile) - try: - tempdir = tempfile.mkdtemp(prefix="sklearn-test") - - tmpgz = os.path.join(tempdir, "datafile.gz") - shutil.copyfileobj(open(datafile, "rb"), gzip.open(tmpgz, "wb")) - Xgz, ygz = load_svmlight_file(tmpgz) - assert_array_equal(X.toarray(), Xgz.toarray()) - assert_array_equal(y, ygz) - - tmpbz = os.path.join(tempdir, "datafile.bz2") - shutil.copyfileobj(open(datafile, "rb"), BZ2File(tmpbz, "wb")) - Xbz, ybz = load_svmlight_file(tmpgz) - assert_array_equal(X.toarray(), Xbz.toarray()) - assert_array_equal(y, ybz) - except: - shutil.rmtree(tempdir) - raise + with NamedTemporaryFile(prefix="sklearn-test", suffix=".gz") as tmp: + tmp.close() # necessary under windows + with open(datafile, "rb") as f: + shutil.copyfileobj(f, gzip.open(tmp.name, "wb")) + Xgz, ygz = load_svmlight_file(tmp.name) + # because we "close" it manually and write to it, + # we need to remove it manually. + os.remove(tmp.name) + assert_array_equal(X.toarray(), Xgz.toarray()) + assert_array_equal(y, ygz) + + with NamedTemporaryFile(prefix="sklearn-test", suffix=".bz2") as tmp: + tmp.close() # necessary under windows + with open(datafile, "rb") as f: + shutil.copyfileobj(f, BZ2File(tmp.name, "wb")) + Xbz, ybz = load_svmlight_file(tmp.name) + # because we "close" it manually and write to it, + # we need to remove it manually. + os.remove(tmp.name) + assert_array_equal(X.toarray(), Xbz.toarray()) + assert_array_equal(y, ybz) @raises(ValueError) @@ -136,13 +146,13 @@ def test_load_invalid_order_file(): @raises(ValueError) def test_load_zero_based(): - f = BytesIO("-1 4:1.\n1 0:1\n") + f = BytesIO(b("-1 4:1.\n1 0:1\n")) load_svmlight_file(f, zero_based=False) def test_load_zero_based_auto(): - data1 = "-1 1:1 2:2 3:3\n" - data2 = "-1 0:0 1:1\n" + data1 = b("-1 1:1 2:2 3:3\n") + data2 = b("-1 0:0 1:1\n") f1 = BytesIO(data1) X, y = load_svmlight_file(f1, zero_based="auto") @@ -155,6 +165,23 @@ def test_load_zero_based_auto(): assert_equal(X2.shape, (1, 4)) +def test_load_with_qid(): + # load svmfile with qid attribute + data = b(""" + 3 qid:1 1:0.53 2:0.12 + 2 qid:1 1:0.13 2:0.1 + 7 qid:2 1:0.87 2:0.12""") + X, y = load_svmlight_file(BytesIO(data), query_id=False) + assert_array_equal(y, [3, 2, 7]) + assert_array_equal(X.toarray(), [[.53, .12], [.13, .1], [.87, .12]]) + res1 = load_svmlight_files([BytesIO(data)], query_id=True) + res2 = load_svmlight_file(BytesIO(data), query_id=True) + for X, y, qid in (res1, res2): + assert_array_equal(y, [3, 2, 7]) + assert_array_equal(qid, [1, 1, 2]) + assert_array_equal(X.toarray(), [[.53, .12], [.13, .1], [.87, .12]]) + + @raises(ValueError) def test_load_invalid_file2(): load_svmlight_files([datafile, invalidfile, datafile]) @@ -176,22 +203,41 @@ def test_dump(): Xs, y = load_svmlight_file(datafile) Xd = Xs.toarray() - for X in (Xs, Xd): + # slicing a csr_matrix can unsort its .indices, so test that we sort + # those correctly + Xsliced = Xs[np.arange(Xs.shape[0])] + + for X in (Xs, Xd, Xsliced): for zero_based in (True, False): - for dtype in [np.float32, np.float64]: + for dtype in [np.float32, np.float64, np.int32]: f = BytesIO() - dump_svmlight_file(X.astype(dtype), y, f, + # we need to pass a comment to get the version info in; + # LibSVM doesn't grok comments so they're not put in by + # default anymore. + dump_svmlight_file(X.astype(dtype), y, f, comment="test", zero_based=zero_based) f.seek(0) comment = f.readline() + try: + comment = str(comment, "utf-8") + except TypeError: # fails in Python 2.x + pass + assert_in("scikit-learn %s" % sklearn.__version__, comment) + comment = f.readline() + try: + comment = str(comment, "utf-8") + except TypeError: # fails in Python 2.x + pass + assert_in(["one", "zero"][zero_based] + "-based", comment) X2, y2 = load_svmlight_file(f, dtype=dtype, zero_based=zero_based) assert_equal(X2.dtype, dtype) + assert_array_equal(X2.sorted_indices().indices, X2.indices) if dtype == np.float32: assert_array_almost_equal( # allow a rounding error at the last decimal place @@ -203,6 +249,36 @@ def test_dump(): assert_array_equal(y, y2) +def test_dump_concise(): + one = 1 + two = 2.1 + three = 3.01 + exact = 1.000000000000001 + # loses the last decimal place + almost = 1.0000000000000001 + X = [[one, two, three, exact, almost], + [1e9, 2e18, 3e27, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]] + y = [one, two, three, exact, almost] + f = BytesIO() + dump_svmlight_file(X, y, f) + f.seek(0) + # make sure it's using the most concise format possible + assert_equal(f.readline(), + b("1 0:1 1:2.1 2:3.01 3:1.000000000000001 4:1\n")) + assert_equal(f.readline(), b("2.1 0:1000000000 1:2e+18 2:3e+27\n")) + assert_equal(f.readline(), b("3.01 \n")) + assert_equal(f.readline(), b("1.000000000000001 \n")) + assert_equal(f.readline(), b("1 \n")) + f.seek(0) + # make sure it's correct too :) + X2, y2 = load_svmlight_file(f) + assert_array_almost_equal(X, X2.toarray()) + assert_array_equal(y, y2) + + def test_dump_comment(): X, y = load_svmlight_file(datafile) X = X.toarray() @@ -217,7 +293,7 @@ def test_dump_comment(): assert_array_equal(y, y2) # XXX we have to update this to support Python 3.x - utf8_comment = "It is true that\n\xc2\xbd\xc2\xb2 = \xc2\xbc" + utf8_comment = b("It is true that\n\xc2\xbd\xc2\xb2 = \xc2\xbc") f = BytesIO() assert_raises(UnicodeDecodeError, dump_svmlight_file, X, y, f, comment=utf8_comment) @@ -245,3 +321,18 @@ def test_dump_invalid(): f = BytesIO() assert_raises(ValueError, dump_svmlight_file, X, y[:-1], f) + + +def test_dump_query_id(): + # test dumping a file with query_id + X, y = load_svmlight_file(datafile) + X = X.toarray() + query_id = np.arange(X.shape[0]) // 2 + f = BytesIO() + dump_svmlight_file(X, y, f, query_id=query_id, zero_based=True) + + f.seek(0) + X1, y1, query_id1 = load_svmlight_file(f, query_id=True, zero_based=True) + assert_array_almost_equal(X, X1.toarray()) + assert_array_almost_equal(y, y1) + assert_array_almost_equal(query_id, query_id1) diff --git a/sklearn/datasets/twenty_newsgroups.py b/sklearn/datasets/twenty_newsgroups.py index 43fe443e4192f..c325aa9c5204a 100644 --- a/sklearn/datasets/twenty_newsgroups.py +++ b/sklearn/datasets/twenty_newsgroups.py @@ -33,14 +33,15 @@ """ # Copyright (c) 2011 Olivier Grisel -# License: Simplified BSD +# License: BSD 3 clause import os -import urllib import logging import tarfile import pickle import shutil +import re +import codecs import numpy as np import scipy.sparse as sp @@ -49,17 +50,21 @@ from .base import Bunch from .base import load_files from ..utils import check_random_state -from ..utils.fixes import in1d from ..feature_extraction.text import CountVectorizer from ..preprocessing import normalize -from ..externals import joblib +from ..externals import joblib, six + +if six.PY3: + from urllib.request import urlopen +else: + from urllib2 import urlopen logger = logging.getLogger(__name__) URL = ("http://people.csail.mit.edu/jrennie/" - "20Newsgroups/20news-bydate.tar.gz") + "20Newsgroups/20news-bydate.tar.gz") ARCHIVE_NAME = "20news-bydate.tar.gz" CACHE_NAME = "20news-bydate.pkz" TRAIN_FOLDER = "20news-bydate-train" @@ -75,28 +80,79 @@ def download_20newsgroups(target_dir, cache_path): if not os.path.exists(target_dir): os.makedirs(target_dir) - if not os.path.exists(archive_path): - logger.warn("Downloading dataset from %s (14 MB)", URL) - opener = urllib.urlopen(URL) - open(archive_path, 'wb').write(opener.read()) + if os.path.exists(archive_path): + # Download is not complete as the .tar.gz file is removed after + # download. + logger.warn("Download was incomplete, downloading again.") + os.remove(archive_path) + + logger.warn("Downloading dataset from %s (14 MB)", URL) + opener = urlopen(URL) + open(archive_path, 'wb').write(opener.read()) logger.info("Decompressing %s", archive_path) tarfile.open(archive_path, "r:gz").extractall(path=target_dir) os.remove(archive_path) # Store a zipped pickle - cache = dict( - train=load_files(train_path, charset='latin1'), - test=load_files(test_path, charset='latin1') - ) - open(cache_path, 'wb').write(pickle.dumps(cache).encode('zip')) + cache = dict(train=load_files(train_path, encoding='latin1'), + test=load_files(test_path, encoding='latin1')) + compressed_content = codecs.encode(pickle.dumps(cache), 'zlib_codec') + open(cache_path, 'wb').write(compressed_content) + shutil.rmtree(target_dir) return cache +def strip_newsgroup_header(text): + """ + Given text in "news" format, strip the headers, by removing everything + before the first blank line. + """ + _before, _blankline, after = text.partition('\n\n') + return after + + +_QUOTE_RE = re.compile(r'(writes in|writes:|wrote:|says:|said:' + r'|^In article|^Quoted from|^\||^>)') + + +def strip_newsgroup_quoting(text): + """ + Given text in "news" format, strip lines beginning with the quote + characters > or |, plus lines that often introduce a quoted section + (for example, because they contain the string 'writes:'.) + """ + good_lines = [line for line in text.split('\n') + if not _QUOTE_RE.search(line)] + return '\n'.join(good_lines) + + +def strip_newsgroup_footer(text): + """ + Given text in "news" format, attempt to remove a signature block. + + As a rough heuristic, we assume that signatures are set apart by either + a blank line or a line made of hyphens, and that it is the last such line + in the file (disregarding blank lines at the end). + """ + lines = text.strip().split('\n') + for line_num in range(len(lines) - 1, -1, -1): + line = lines[line_num] + if line.strip().strip('-') == '': + break + + if line_num > 0: + return '\n'.join(lines[:line_num]) + else: + return text + + def fetch_20newsgroups(data_home=None, subset='train', categories=None, - shuffle=True, random_state=42, download_if_missing=True): - """Load the filenames of the 20 newsgroups dataset. + shuffle=True, random_state=42, + remove=(), + download_if_missing=True): + """Load the filenames and data from the 20 newsgroups dataset. Parameters ---------- @@ -124,6 +180,19 @@ def fetch_20newsgroups(data_home=None, subset='train', categories=None, download_if_missing: optional, True by default If False, raise an IOError if the data is not locally available instead of trying to download the data from the source site. + + remove: tuple + May contain any subset of ('headers', 'footers', 'quotes'). Each of + these are kinds of text that will be detected and removed from the + newsgroup posts, preventing classifiers from overfitting on + metadata. + + 'headers' removes newsgroup headers, 'footers' removes blocks at the + ends of posts that look like signatures, and 'quotes' removes lines + that appear to be quoting another post. + + 'headers' follows an exact standard; the other filters are not always + correct. """ data_home = get_data_home(data_home=data_home) @@ -132,12 +201,16 @@ def fetch_20newsgroups(data_home=None, subset='train', categories=None, cache = None if os.path.exists(cache_path): try: - cache = pickle.loads(open(cache_path, 'rb').read().decode('zip')) + with open(cache_path, 'rb') as f: + compressed_content = f.read() + uncompressed_content = codecs.decode( + compressed_content, 'zlib_codec') + cache = pickle.loads(uncompressed_content) except Exception as e: - print 80 * '_' - print 'Cache loading failed' - print 80 * '_' - print e + print(80 * '_') + print('Cache loading failed') + print(80 * '_') + print(e) if cache is None: if download_if_missing: @@ -166,12 +239,19 @@ def fetch_20newsgroups(data_home=None, subset='train', categories=None, raise ValueError( "subset can only be 'train', 'test' or 'all', got '%s'" % subset) + if 'headers' in remove: + data.data = [strip_newsgroup_header(text) for text in data.data] + if 'footers' in remove: + data.data = [strip_newsgroup_footer(text) for text in data.data] + if 'quotes' in remove: + data.data = [strip_newsgroup_quoting(text) for text in data.data] + if categories is not None: labels = [(data.target_names.index(cat), cat) for cat in categories] # Sort the categories to have the ordering of the labels labels.sort() labels, categories = zip(*labels) - mask = in1d(data.target, labels) + mask = np.in1d(data.target, labels) data.filenames = data.filenames[mask] data.target = data.target[mask] # searchsorted to have continuous labels @@ -196,7 +276,7 @@ def fetch_20newsgroups(data_home=None, subset='train', categories=None, return data -def fetch_20newsgroups_vectorized(subset="train", data_home=None): +def fetch_20newsgroups_vectorized(subset="train", remove=(), data_home=None): """Load the 20 newsgroups dataset and transform it into tf-idf vectors. This is a convenience function; the tf-idf transformation is done using the @@ -215,6 +295,16 @@ def fetch_20newsgroups_vectorized(subset="train", data_home=None): Specify an download and cache folder for the datasets. If None, all scikit-learn data is stored in '~/scikit_learn_data' subfolders. + remove: tuple + May contain any subset of ('headers', 'footers', 'quotes'). Each of + these are kinds of text that will be detected and removed from the + newsgroup posts, preventing classifiers from overfitting on + metadata. + + 'headers' removes newsgroup headers, 'footers' removes blocks at the + ends of posts that look like signatures, and 'quotes' removes lines + that appear to be quoting another post. + Returns ------- @@ -224,20 +314,25 @@ def fetch_20newsgroups_vectorized(subset="train", data_home=None): bunch.target_names: list, length [n_classes] """ data_home = get_data_home(data_home=data_home) - target_file = os.path.join(data_home, "20newsgroup_vectorized.pk") + filebase = '20newsgroup_vectorized' + if remove: + filebase += 'remove-' + ('-'.join(remove)) + target_file = os.path.join(data_home, filebase + ".pk") # we shuffle but use a fixed seed for the memoization data_train = fetch_20newsgroups(data_home=data_home, subset='train', categories=None, shuffle=True, - random_state=12) + random_state=12, + remove=remove) data_test = fetch_20newsgroups(data_home=data_home, subset='test', categories=None, shuffle=True, - random_state=12) + random_state=12, + remove=remove) if os.path.exists(target_file): X_train, X_test = joblib.load(target_file) diff --git a/sklearn/decomposition/__init__.py b/sklearn/decomposition/__init__.py index f1a15b7d85043..6b88a86f9bb5f 100644 --- a/sklearn/decomposition/__init__.py +++ b/sklearn/decomposition/__init__.py @@ -5,22 +5,26 @@ """ from .nmf import NMF, ProjectedGradientNMF -from .pca import PCA, RandomizedPCA, ProbabilisticPCA +from .pca import PCA, RandomizedPCA +from .incremental_pca import IncrementalPCA from .kernel_pca import KernelPCA from .sparse_pca import SparsePCA, MiniBatchSparsePCA +from .truncated_svd import TruncatedSVD from .fastica_ import FastICA, fastica -from .dict_learning import dict_learning, dict_learning_online, sparse_encode,\ - DictionaryLearning, MiniBatchDictionaryLearning,\ - SparseCoder +from .dict_learning import (dict_learning, dict_learning_online, sparse_encode, + DictionaryLearning, MiniBatchDictionaryLearning, + SparseCoder) +from .factor_analysis import FactorAnalysis +from ..utils.extmath import randomized_svd __all__ = ['DictionaryLearning', 'FastICA', + 'IncrementalPCA', 'KernelPCA', 'MiniBatchDictionaryLearning', 'MiniBatchSparsePCA', 'NMF', 'PCA', - 'ProbabilisticPCA', 'ProjectedGradientNMF', 'RandomizedPCA', 'SparseCoder', @@ -28,4 +32,7 @@ 'dict_learning', 'dict_learning_online', 'fastica', - 'sparse_encode'] + 'randomized_svd', + 'sparse_encode', + 'FactorAnalysis', + 'TruncatedSVD'] diff --git a/sklearn/decomposition/base.py b/sklearn/decomposition/base.py new file mode 100644 index 0000000000000..2d44da74e9be3 --- /dev/null +++ b/sklearn/decomposition/base.py @@ -0,0 +1,162 @@ +"""Principal Component Analysis Base Classes""" + +# Author: Alexandre Gramfort +# Olivier Grisel +# Mathieu Blondel +# Denis A. Engemann +# Kyle Kastner +# +# License: BSD 3 clause + +import numpy as np +from scipy import linalg + +from ..base import BaseEstimator, TransformerMixin +from ..utils import check_array +from ..utils.extmath import fast_dot +from ..utils.validation import check_is_fitted +from ..externals import six +from abc import ABCMeta, abstractmethod + + +class _BasePCA(six.with_metaclass(ABCMeta, BaseEstimator, TransformerMixin)): + """Base class for PCA methods. + + Warning: This class should not be used directly. + Use derived classes instead. + """ + def get_covariance(self): + """Compute data covariance with the generative model. + + ``cov = components_.T * S**2 * components_ + sigma2 * eye(n_features)`` + where S**2 contains the explained variances, and sigma2 contains the + noise variances. + + Returns + ------- + cov : array, shape=(n_features, n_features) + Estimated covariance of data. + """ + components_ = self.components_ + exp_var = self.explained_variance_ + if self.whiten: + components_ = components_ * np.sqrt(exp_var[:, np.newaxis]) + exp_var_diff = np.maximum(exp_var - self.noise_variance_, 0.) + cov = np.dot(components_.T * exp_var_diff, components_) + cov.flat[::len(cov) + 1] += self.noise_variance_ # modify diag inplace + return cov + + def get_precision(self): + """Compute data precision matrix with the generative model. + + Equals the inverse of the covariance but computed with + the matrix inversion lemma for efficiency. + + Returns + ------- + precision : array, shape=(n_features, n_features) + Estimated precision of data. + """ + n_features = self.components_.shape[1] + + # handle corner cases first + if self.n_components_ == 0: + return np.eye(n_features) / self.noise_variance_ + if self.n_components_ == n_features: + return linalg.inv(self.get_covariance()) + + # Get precision using matrix inversion lemma + components_ = self.components_ + exp_var = self.explained_variance_ + if self.whiten: + components_ = components_ * np.sqrt(exp_var[:, np.newaxis]) + exp_var_diff = np.maximum(exp_var - self.noise_variance_, 0.) + precision = np.dot(components_, components_.T) / self.noise_variance_ + precision.flat[::len(precision) + 1] += 1. / exp_var_diff + precision = np.dot(components_.T, + np.dot(linalg.inv(precision), components_)) + precision /= -(self.noise_variance_ ** 2) + precision.flat[::len(precision) + 1] += 1. / self.noise_variance_ + return precision + + @abstractmethod + def fit(X, y=None): + """Placeholder for fit. Subclasses should implement this method! + + Fit the model with X. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data, where n_samples is the number of samples and + n_features is the number of features. + + Returns + ------- + self : object + Returns the instance itself. + """ + + + def transform(self, X, y=None): + """Apply dimensionality reduction to X. + + X is projected on the first principal components previously extracted + from a training set. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + New data, where n_samples is the number of samples + and n_features is the number of features. + + Returns + ------- + X_new : array-like, shape (n_samples, n_components) + + Examples + -------- + + >>> import numpy as np + >>> from sklearn.decomposition import IncrementalPCA + >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) + >>> ipca = IncrementalPCA(n_components=2, batch_size=3) + >>> ipca.fit(X) + IncrementalPCA(batch_size=3, copy=True, n_components=2, whiten=False) + >>> ipca.transform(X) # doctest: +SKIP + """ + check_is_fitted(self, ['mean_', 'components_'], all_or_any=all) + + X = check_array(X) + if self.mean_ is not None: + X = X - self.mean_ + X_transformed = fast_dot(X, self.components_.T) + if self.whiten: + X_transformed /= np.sqrt(self.explained_variance_) + return X_transformed + + def inverse_transform(self, X, y=None): + """Transform data back to its original space. + + In other words, return an input X_original whose transform would be X. + + Parameters + ---------- + X : array-like, shape (n_samples, n_components) + New data, where n_samples is the number of samples + and n_components is the number of components. + + Returns + ------- + X_original array-like, shape (n_samples, n_features) + + Notes + ----- + If whitening is enabled, inverse_transform will compute the + exact inverse operation, which includes reversing whitening. + """ + if self.whiten: + return fast_dot(X, np.sqrt(self.explained_variance_[:, np.newaxis]) * + self.components_) + self.mean_ + else: + return fast_dot(X, self.components_) + self.mean_ diff --git a/sklearn/decomposition/dict_learning.py b/sklearn/decomposition/dict_learning.py index 5750ac3a902ea..3e58bac5fa827 100644 --- a/sklearn/decomposition/dict_learning.py +++ b/sklearn/decomposition/dict_learning.py @@ -1,7 +1,8 @@ """ Dictionary learning """ +from __future__ import print_function # Author: Vlad Niculae, Gael Varoquaux, Alexandre Gramfort -# License: BSD +# License: BSD 3 clause import time import sys @@ -15,8 +16,10 @@ from ..base import BaseEstimator, TransformerMixin from ..externals.joblib import Parallel, delayed, cpu_count -from ..utils import array2d, check_random_state, gen_even_slices -from ..utils.extmath import randomized_svd +from ..externals.six.moves import zip +from ..utils import check_array, check_random_state, gen_even_slices +from ..utils.extmath import randomized_svd, row_norms +from ..utils.validation import check_is_fitted from ..linear_model import Lasso, orthogonal_mp_gram, LassoLars, Lars @@ -32,15 +35,15 @@ def _sparse_encode(X, dictionary, gram, cov=None, algorithm='lasso_lars', X: array of shape (n_samples, n_features) Data matrix. - dictionary: array of shape (n_atoms, n_features) + dictionary: array of shape (n_components, n_features) The dictionary matrix against which to solve the sparse coding of the data. Some of the algorithms assume normalized rows. - gram: None | array, shape=(n_atoms, n_atoms) + gram: None | array, shape=(n_components, n_components) Precomputed Gram matrix, dictionary * dictionary' gram can be None if method is 'threshold'. - cov: array, shape=(n_atoms, n_samples) + cov: array, shape=(n_components, n_samples) Precomputed covariance, dictionary * X' algorithm: {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'} @@ -58,7 +61,7 @@ def _sparse_encode(X, dictionary, gram, cov=None, algorithm='lasso_lars', algorithm is 'lasso_lars', 'lasso_cd' or 'threshold'. Otherwise it corresponds to n_nonzero_coefs. - init: array of shape (n_samples, n_atoms) + init: array of shape (n_samples, n_components) Initialization value of the sparse code. Only used if `algorithm='lasso_cd'`. @@ -94,8 +97,8 @@ def _sparse_encode(X, dictionary, gram, cov=None, algorithm='lasso_lars', try: err_mgt = np.seterr(all='ignore') lasso_lars = LassoLars(alpha=alpha, fit_intercept=False, - verbose=False, normalize=False, precompute=gram, - fit_path=False) + verbose=False, normalize=False, + precompute=gram, fit_path=False) lasso_lars.fit(dictionary.T, X.T, Xy=cov) new_code = lasso_lars.coef_ finally: @@ -104,8 +107,9 @@ def _sparse_encode(X, dictionary, gram, cov=None, algorithm='lasso_lars', elif algorithm == 'lasso_cd': alpha = float(regularization) / n_features # account for scaling clf = Lasso(alpha=alpha, fit_intercept=False, precompute=gram, - max_iter=max_iter) - clf.fit(dictionary.T, X.T, Xy=cov, coef_init=init) + max_iter=max_iter, warm_start=True) + clf.coef_ = init + clf.fit(dictionary.T, X.T) new_code = clf.coef_ elif algorithm == 'lars': @@ -124,19 +128,20 @@ def _sparse_encode(X, dictionary, gram, cov=None, algorithm='lasso_lars', np.maximum(np.abs(cov) - regularization, 0)).T) elif algorithm == 'omp': - norms_squared = np.sum((X ** 2), axis=1) new_code = orthogonal_mp_gram(gram, cov, regularization, None, - norms_squared, copy_Xy=copy_cov).T + row_norms(X, squared=True), + copy_Xy=copy_cov).T else: - raise NotImplemented('Sparse coding method %s not implemented' % - algorithm) + raise ValueError('Sparse coding method must be "lasso_lars" ' + '"lasso_cd", "lasso", "threshold" or "omp", got %s.' + % algorithm) return new_code # XXX : could be moved to the linear_model module def sparse_encode(X, dictionary, gram=None, cov=None, algorithm='lasso_lars', - n_nonzero_coefs=None, alpha=None, copy_cov=True, init=None, - max_iter=1000, n_jobs=1): + n_nonzero_coefs=None, alpha=None, copy_cov=True, init=None, + max_iter=1000, n_jobs=1): """Sparse coding Each row of the result is the solution to a sparse coding problem. @@ -149,15 +154,15 @@ def sparse_encode(X, dictionary, gram=None, cov=None, algorithm='lasso_lars', X: array of shape (n_samples, n_features) Data matrix - dictionary: array of shape (n_atoms, n_features) + dictionary: array of shape (n_components, n_features) The dictionary matrix against which to solve the sparse coding of the data. Some of the algorithms assume normalized rows for meaningful output. - gram: array, shape=(n_atoms, n_atoms) + gram: array, shape=(n_components, n_components) Precomputed Gram matrix, dictionary * dictionary' - cov: array, shape=(n_atoms, n_samples) + cov: array, shape=(n_components, n_samples) Precomputed covariance, dictionary' * X algorithm: {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'} @@ -184,7 +189,7 @@ def sparse_encode(X, dictionary, gram=None, cov=None, algorithm='lasso_lars', the reconstruction error targeted. In this case, it overrides `n_nonzero_coefs`. - init: array of shape (n_samples, n_atoms) + init: array of shape (n_samples, n_components) Initialization value of the sparse codes. Only used if `algorithm='lasso_cd'`. @@ -200,7 +205,7 @@ def sparse_encode(X, dictionary, gram=None, cov=None, algorithm='lasso_lars', Returns ------- - code: array of shape (n_samples, n_atoms) + code: array of shape (n_samples, n_components) The sparse codes See also @@ -210,10 +215,10 @@ def sparse_encode(X, dictionary, gram=None, cov=None, algorithm='lasso_lars', sklearn.linear_model.Lasso SparseCoder """ - dictionary = array2d(dictionary) - X = array2d(X) + dictionary = check_array(dictionary) + X = check_array(X) n_samples, n_features = X.shape - n_atoms = dictionary.shape[0] + n_components = dictionary.shape[0] if gram is None and algorithm != 'threshold': gram = np.dot(dictionary, dictionary.T) @@ -224,7 +229,7 @@ def sparse_encode(X, dictionary, gram=None, cov=None, algorithm='lasso_lars', if algorithm in ('lars', 'omp'): regularization = n_nonzero_coefs if regularization is None: - regularization = max(n_features / 10, 1) + regularization = min(max(n_features / 10, 1), n_components) else: regularization = alpha if regularization is None: @@ -232,26 +237,21 @@ def sparse_encode(X, dictionary, gram=None, cov=None, algorithm='lasso_lars', if n_jobs == 1 or algorithm == 'threshold': return _sparse_encode(X, dictionary, gram, cov=cov, - algorithm=algorithm, regularization=regularization, - copy_cov=copy_cov, init=init, max_iter=max_iter) + algorithm=algorithm, + regularization=regularization, copy_cov=copy_cov, + init=init, max_iter=max_iter) # Enter parallel code block - code = np.empty((n_samples, n_atoms)) + code = np.empty((n_samples, n_components)) slices = list(gen_even_slices(n_samples, n_jobs)) - if cov is None: - # We cannot keep cov to None: it needs to be slicable - class StupidSliceable(object): - def __getitem__(self, anything): - return None - cov = StupidSliceable() code_views = Parallel(n_jobs=n_jobs)( - delayed(_sparse_encode)(X[this_slice], dictionary, gram, - cov[:, this_slice], algorithm, - regularization=regularization, copy_cov=copy_cov, - init=init[this_slice] if init is not None else None, - max_iter=max_iter) - for this_slice in slices) + delayed(_sparse_encode)( + X[this_slice], dictionary, gram, cov[:, this_slice], algorithm, + regularization=regularization, copy_cov=copy_cov, + init=init[this_slice] if init is not None else None, + max_iter=max_iter) + for this_slice in slices) for this_slice, this_view in zip(slices, code_views): code[this_slice] = this_view return code @@ -263,13 +263,13 @@ def _update_dict(dictionary, Y, code, verbose=False, return_r2=False, Parameters ---------- - dictionary: array of shape (n_features, n_atoms) + dictionary: array of shape (n_features, n_components) Value of the dictionary at the previous iteration. Y: array of shape (n_features, n_samples) Data matrix. - code: array of shape (n_atoms, n_samples) + code: array of shape (n_components, n_samples) Sparse coding of the data against which to optimize the dictionary. verbose: @@ -284,11 +284,11 @@ def _update_dict(dictionary, Y, code, verbose=False, return_r2=False, Returns ------- - dictionary: array of shape (n_features, n_atoms) + dictionary: array of shape (n_features, n_components) Updated dictionary. """ - n_atoms = len(code) + n_components = len(code) n_samples = Y.shape[0] random_state = check_random_state(random_state) # Residuals, computed 'in-place' for efficiency @@ -296,7 +296,7 @@ def _update_dict(dictionary, Y, code, verbose=False, return_r2=False, R += Y R = np.asfortranarray(R) ger, = linalg.get_blas_funcs(('ger',), (dictionary, code)) - for k in xrange(n_atoms): + for k in range(n_components): # R <- 1.0 * U_k * V_k^T + R R = ger(1.0, dictionary[:, k], code[k, :], a=R, overwrite_a=True) dictionary[:, k] = np.dot(R, code[k, :].T) @@ -307,7 +307,7 @@ def _update_dict(dictionary, Y, code, verbose=False, return_r2=False, sys.stdout.write("+") sys.stdout.flush() elif verbose: - print "Adding new random atom" + print("Adding new random atom") dictionary[:, k] = random_state.randn(n_samples) # Setting corresponding coefs to 0 code[k, :] = 0.0 @@ -329,9 +329,10 @@ def _update_dict(dictionary, Y, code, verbose=False, return_r2=False, return dictionary -def dict_learning(X, n_atoms, alpha, max_iter=100, tol=1e-8, +def dict_learning(X, n_components, alpha, max_iter=100, tol=1e-8, method='lars', n_jobs=1, dict_init=None, code_init=None, - callback=None, verbose=False, random_state=None): + callback=None, verbose=False, random_state=None, + return_n_iter=False): """Solves a dictionary learning matrix factorization problem. Finds the best dictionary and the corresponding sparse code for @@ -339,7 +340,7 @@ def dict_learning(X, n_atoms, alpha, max_iter=100, tol=1e-8, (U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1 (U,V) - with || V_k ||_2 = 1 for all 0 <= k < n_atoms + with || V_k ||_2 = 1 for all 0 <= k < n_components where V is the dictionary and U is the sparse code. @@ -348,7 +349,7 @@ def dict_learning(X, n_atoms, alpha, max_iter=100, tol=1e-8, X: array of shape (n_samples, n_features) Data matrix. - n_atoms: int, + n_components: int, Number of dictionary atoms to extract. alpha: int, @@ -370,10 +371,10 @@ def dict_learning(X, n_atoms, alpha, max_iter=100, tol=1e-8, n_jobs: int, Number of parallel jobs to run, or -1 to autodetect. - dict_init: array of shape (n_atoms, n_features), + dict_init: array of shape (n_components, n_features), Initial value for the dictionary for warm restart scenarios. - code_init: array of shape (n_samples, n_atoms), + code_init: array of shape (n_samples, n_components), Initial value for the sparse code for warm restart scenarios. callback: @@ -385,17 +386,24 @@ def dict_learning(X, n_atoms, alpha, max_iter=100, tol=1e-8, random_state: int or RandomState Pseudo number generator state used for random sampling. + return_n_iter : bool + Whether or not to return the number of iterations. + Returns ------- - code: array of shape (n_samples, n_atoms) + code: array of shape (n_samples, n_components) The sparse code factor in the matrix factorization. - dictionary: array of shape (n_atoms, n_features), + dictionary: array of shape (n_components, n_features), The dictionary factor in the matrix factorization. errors: array Vector of errors at each iteration. + n_iter : int + Number of iterations run. Returned only if `return_n_iter` is + set to True. + See also -------- dict_learning_online @@ -405,7 +413,8 @@ def dict_learning(X, n_atoms, alpha, max_iter=100, tol=1e-8, MiniBatchSparsePCA """ if method not in ('lars', 'cd'): - raise ValueError('Coding method not supported as a fit algorithm.') + raise ValueError('Coding method %r not supported as a fit algorithm.' + % method) method = 'lasso_' + method t0 = time.time() @@ -425,13 +434,13 @@ def dict_learning(X, n_atoms, alpha, max_iter=100, tol=1e-8, code, S, dictionary = linalg.svd(X, full_matrices=False) dictionary = S[:, np.newaxis] * dictionary r = len(dictionary) - if n_atoms <= r: # True even if n_atoms=None - code = code[:, :n_atoms] - dictionary = dictionary[:n_atoms, :] + if n_components <= r: # True even if n_components=None + code = code[:, :n_components] + dictionary = dictionary[:n_components, :] else: - code = np.c_[code, np.zeros((len(code), n_atoms - r))] + code = np.c_[code, np.zeros((len(code), n_components - r))] dictionary = np.r_[dictionary, - np.zeros((n_atoms - r, dictionary.shape[1]))] + np.zeros((n_components - r, dictionary.shape[1]))] # Fortran-order dict, as we are going to access its row vectors dictionary = np.array(dictionary, order='F') @@ -442,17 +451,20 @@ def dict_learning(X, n_atoms, alpha, max_iter=100, tol=1e-8, current_cost = np.nan if verbose == 1: - print '[dict_learning]', + print('[dict_learning]', end=' ') + + # If max_iter is 0, number of iterations returned should be zero + ii = -1 - for ii in xrange(max_iter): + for ii in range(max_iter): dt = (time.time() - t0) if verbose == 1: sys.stdout.write(".") sys.stdout.flush() elif verbose: print ("Iteration % 3i " - "(elapsed time: % 3is, % 4.1fmn, current cost % 7.3f)" % - (ii, dt, dt / 60, current_cost)) + "(elapsed time: % 3is, % 4.1fmn, current cost % 7.3f)" + % (ii, dt, dt / 60, current_cost)) # Update code code = sparse_encode(X, dictionary, algorithm=method, alpha=alpha, @@ -473,20 +485,25 @@ def dict_learning(X, n_atoms, alpha, max_iter=100, tol=1e-8, if dE < tol * errors[-1]: if verbose == 1: # A line return - print "" + print("") elif verbose: - print "--- Convergence reached after %d iterations" % ii + print("--- Convergence reached after %d iterations" % ii) break if ii % 5 == 0 and callback is not None: callback(locals()) - return code, dictionary, errors + if return_n_iter: + return code, dictionary, errors, ii + 1 + else: + return code, dictionary, errors -def dict_learning_online(X, n_atoms, alpha, n_iter=100, return_code=True, - dict_init=None, callback=None, chunk_size=3, - verbose=False, shuffle=True, n_jobs=1, - method='lars', iter_offset=0, random_state=None): +def dict_learning_online(X, n_components=2, alpha=1, n_iter=100, + return_code=True, dict_init=None, callback=None, + batch_size=3, verbose=False, shuffle=True, n_jobs=1, + method='lars', iter_offset=0, random_state=None, + return_inner_stats=False, inner_stats=None, + return_n_iter=False): """Solves a dictionary learning matrix factorization problem online. Finds the best dictionary and the corresponding sparse code for @@ -494,7 +511,7 @@ def dict_learning_online(X, n_atoms, alpha, n_iter=100, return_code=True, (U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1 (U,V) - with || V_k ||_2 = 1 for all 0 <= k < n_atoms + with || V_k ||_2 = 1 for all 0 <= k < n_components where V is the dictionary and U is the sparse code. This is accomplished by repeatedly iterating over mini-batches by slicing @@ -503,60 +520,80 @@ def dict_learning_online(X, n_atoms, alpha, n_iter=100, return_code=True, Parameters ---------- X: array of shape (n_samples, n_features) - data matrix + Data matrix. - n_atoms: int, - number of dictionary atoms to extract + n_components : int, + Number of dictionary atoms to extract. - alpha: int, - sparsity controlling parameter + alpha : float, + Sparsity controlling parameter. - n_iter: int, - number of iterations to perform + n_iter : int, + Number of iterations to perform. - return_code: boolean, - whether to also return the code U or just the dictionary V + return_code : boolean, + Whether to also return the code U or just the dictionary V. - dict_init: array of shape (n_atoms, n_features), - initial value for the dictionary for warm restart scenarios + dict_init : array of shape (n_components, n_features), + Initial value for the dictionary for warm restart scenarios. - callback: - callable that gets invoked every five iterations + callback : + Callable that gets invoked every five iterations. - chunk_size: int, - the number of samples to take in each batch + batch_size : int, + The number of samples to take in each batch. - verbose: - degree of output the procedure will print + verbose : + Degree of output the procedure will print. - shuffle: boolean, - whether to shuffle the data before splitting it in batches + shuffle : boolean, + Whether to shuffle the data before splitting it in batches. - n_jobs: int, - number of parallel jobs to run, or -1 to autodetect. + n_jobs : int, + Number of parallel jobs to run, or -1 to autodetect. - method: {'lars', 'cd'} + method : {'lars', 'cd'} lars: uses the least angle regression method to solve the lasso problem (linear_model.lars_path) cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse. - iter_offset: int, default 0 - number of previous iterations completed on the dictionary used for - initialization + iter_offset : int, default 0 + Number of previous iterations completed on the dictionary used for + initialization. - random_state: int or RandomState + random_state : int or RandomState Pseudo number generator state used for random sampling. + return_inner_stats : boolean, optional + Return the inner statistics A (dictionary covariance) and B + (data approximation). Useful to restart the algorithm in an + online setting. If return_inner_stats is True, return_code is + ignored + + inner_stats : tuple of (A, B) ndarrays + Inner sufficient statistics that are kept by the algorithm. + Passing them at initialization is useful in online settings, to + avoid loosing the history of the evolution. + A (n_components, n_components) is the dictionary covariance matrix. + B (n_features, n_components) is the data approximation matrix + + return_n_iter : bool + Whether or not to return the number of iterations. + Returns ------- - code: array of shape (n_samples, n_atoms), + code : array of shape (n_samples, n_components), the sparse code (only returned if `return_code=True`) - dictionary: array of shape (n_atoms, n_features), + dictionary : array of shape (n_components, n_features), the solutions to the dictionary learning problem + n_iter : int + Number of iterations run. Returned only if `return_n_iter` is + set to `True`. + See also -------- dict_learning @@ -566,6 +603,9 @@ def dict_learning_online(X, n_atoms, alpha, n_iter=100, return_code=True, MiniBatchSparsePCA """ + if n_components is None: + n_components = X.shape[1] + if method not in ('lars', 'cd'): raise ValueError('Coding method not supported as a fit algorithm.') method = 'lasso_' + method @@ -583,20 +623,20 @@ def dict_learning_online(X, n_atoms, alpha, n_iter=100, return_code=True, if dict_init is not None: dictionary = dict_init else: - _, S, dictionary = randomized_svd(X, n_atoms) + _, S, dictionary = randomized_svd(X, n_components) dictionary = S[:, np.newaxis] * dictionary r = len(dictionary) - if n_atoms <= r: - dictionary = dictionary[:n_atoms, :] + if n_components <= r: + dictionary = dictionary[:n_components, :] else: dictionary = np.r_[dictionary, - np.zeros((n_atoms - r, dictionary.shape[1]))] + np.zeros((n_components - r, dictionary.shape[1]))] dictionary = np.ascontiguousarray(dictionary.T) if verbose == 1: - print '[dict_learning]', + print('[dict_learning]', end=' ') - n_batches = floor(float(len(X)) / chunk_size) + n_batches = floor(float(len(X)) / batch_size) if shuffle: X_train = X.copy() random_state.shuffle(X_train) @@ -606,30 +646,36 @@ def dict_learning_online(X, n_atoms, alpha, n_iter=100, return_code=True, batches = itertools.cycle(batches) # The covariance of the dictionary - A = np.zeros((n_atoms, n_atoms)) - # The data approximation - B = np.zeros((n_features, n_atoms)) + if inner_stats is None: + A = np.zeros((n_components, n_components)) + # The data approximation + B = np.zeros((n_features, n_components)) + else: + A = inner_stats[0].copy() + B = inner_stats[1].copy() - for ii, this_X in itertools.izip(xrange(iter_offset, iter_offset + n_iter), - batches): + # If n_iter is zero, we need to return zero. + ii = iter_offset - 1 + + for ii, this_X in zip(range(iter_offset, iter_offset + n_iter), batches): dt = (time.time() - t0) if verbose == 1: sys.stdout.write(".") sys.stdout.flush() elif verbose: if verbose > 10 or ii % ceil(100. / verbose) == 0: - print ("Iteration % 3i (elapsed time: % 3is, % 4.1fmn)" % - (ii, dt, dt / 60)) + print ("Iteration % 3i (elapsed time: % 3is, % 4.1fmn)" + % (ii, dt, dt / 60)) this_code = sparse_encode(this_X, dictionary.T, algorithm=method, - alpha=alpha).T + alpha=alpha, n_jobs=n_jobs).T # Update the auxiliary variables - if ii < chunk_size - 1: - theta = float((ii + 1) * chunk_size) + if ii < batch_size - 1: + theta = float((ii + 1) * batch_size) else: - theta = float(chunk_size ** 2 + ii + 1 - chunk_size) - beta = (theta + 1 - chunk_size) / (theta + 1) + theta = float(batch_size ** 2 + ii + 1 - batch_size) + beta = (theta + 1 - batch_size) / (theta + 1) A *= beta A += np.dot(this_code, this_code.T) @@ -646,29 +692,41 @@ def dict_learning_online(X, n_atoms, alpha, n_iter=100, return_code=True, if callback is not None: callback(locals()) + if return_inner_stats: + if return_n_iter: + return dictionary.T, (A, B), ii - iter_offset + 1 + else: + return dictionary.T, (A, B) if return_code: if verbose > 1: - print 'Learning code...', + print('Learning code...', end=' ') elif verbose == 1: - print '|', + print('|', end=' ') code = sparse_encode(X, dictionary.T, algorithm=method, alpha=alpha, n_jobs=n_jobs) if verbose > 1: dt = (time.time() - t0) - print 'done (total time: % 3is, % 4.1fmn)' % (dt, dt / 60) - return code, dictionary.T + print('done (total time: % 3is, % 4.1fmn)' % (dt, dt / 60)) + if return_n_iter: + return code, dictionary.T, ii - iter_offset + 1 + else: + return code, dictionary.T - return dictionary.T + if return_n_iter: + return dictionary.T, ii - iter_offset + 1 + else: + return dictionary.T class SparseCodingMixin(TransformerMixin): """Sparse coding mixin""" - def _set_sparse_coding_params(self, n_atoms, transform_algorithm='omp', + def _set_sparse_coding_params(self, n_components, + transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, split_sign=False, n_jobs=1): - self.n_atoms = n_atoms + self.n_components = n_components self.transform_algorithm = transform_algorithm self.transform_n_nonzero_coefs = transform_n_nonzero_coefs self.transform_alpha = transform_alpha @@ -693,8 +751,10 @@ def transform(self, X, y=None): Transformed data """ + check_is_fitted(self, 'components_') + # XXX : kwargs is not documented - X = array2d(X) + X = check_array(X) n_samples, n_features = X.shape code = sparse_encode( @@ -726,7 +786,7 @@ class SparseCoder(BaseEstimator, SparseCodingMixin): Parameters ---------- - dictionary : array, [n_atoms, n_features] + dictionary : array, [n_components, n_features] The dictionary atoms used for sparse coding. Lines are assumed to be normalized to unit norm. @@ -766,7 +826,7 @@ class SparseCoder(BaseEstimator, SparseCodingMixin): Attributes ---------- - `components_` : array, [n_atoms, n_features] + components_ : array, [n_components, n_features] The unchanged dictionary atoms See also @@ -806,14 +866,14 @@ class DictionaryLearning(BaseEstimator, SparseCodingMixin): (U^*,V^*) = argmin 0.5 || Y - U V ||_2^2 + alpha * || U ||_1 (U,V) - with || V_k ||_2 = 1 for all 0 <= k < n_atoms + with || V_k ||_2 = 1 for all 0 <= k < n_components Parameters ---------- - n_atoms : int, + n_components : int, number of dictionary elements to extract - alpha : int, + alpha : float, sparsity controlling parameter max_iter : int, @@ -863,10 +923,10 @@ class DictionaryLearning(BaseEstimator, SparseCodingMixin): n_jobs : int, number of parallel jobs to run - code_init : array of shape (n_samples, n_atoms), + code_init : array of shape (n_samples, n_components), initial value for the code, for warm restart - dict_init : array of shape (n_atoms, n_features), + dict_init : array of shape (n_components, n_features), initial values for the dictionary, for warm restart verbose : @@ -877,12 +937,15 @@ class DictionaryLearning(BaseEstimator, SparseCodingMixin): Attributes ---------- - `components_` : array, [n_atoms, n_features] + components_ : array, [n_components, n_features] dictionary atoms extracted from the data - `error_` : array + error_ : array vector of errors at each iteration + n_iter_ : int + Number of iterations run. + Notes ----- **References:** @@ -897,12 +960,13 @@ class DictionaryLearning(BaseEstimator, SparseCodingMixin): SparsePCA MiniBatchSparsePCA """ - def __init__(self, n_atoms=None, alpha=1, max_iter=1000, tol=1e-8, + def __init__(self, n_components=None, alpha=1, max_iter=1000, tol=1e-8, fit_algorithm='lars', transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, n_jobs=1, code_init=None, dict_init=None, verbose=False, split_sign=False, random_state=None): - self._set_sparse_coding_params(n_atoms, transform_algorithm, + + self._set_sparse_coding_params(n_components, transform_algorithm, transform_n_nonzero_coefs, transform_alpha, split_sign, n_jobs) self.alpha = alpha @@ -928,21 +992,24 @@ def fit(self, X, y=None): self: object Returns the object itself """ - self.random_state = check_random_state(self.random_state) - X = array2d(X) - if self.n_atoms is None: - n_atoms = X.shape[1] + random_state = check_random_state(self.random_state) + X = check_array(X) + if self.n_components is None: + n_components = X.shape[1] else: - n_atoms = self.n_atoms - - V, U, E = dict_learning(X, n_atoms, self.alpha, - tol=self.tol, max_iter=self.max_iter, - method=self.fit_algorithm, - n_jobs=self.n_jobs, - code_init=self.code_init, - dict_init=self.dict_init, - verbose=self.verbose, - random_state=self.random_state) + n_components = self.n_components + + V, U, E, self.n_iter_ = dict_learning( + X, n_components, self.alpha, + tol=self.tol, max_iter=self.max_iter, + method=self.fit_algorithm, + n_jobs=self.n_jobs, + code_init=self.code_init, + dict_init=self.dict_init, + verbose=self.verbose, + random_state=random_state, + return_n_iter=True + ) self.components_ = U self.error_ = E return self @@ -958,14 +1025,14 @@ class MiniBatchDictionaryLearning(BaseEstimator, SparseCodingMixin): (U^*,V^*) = argmin 0.5 || Y - U V ||_2^2 + alpha * || U ||_1 (U,V) - with || V_k ||_2 = 1 for all 0 <= k < n_atoms + with || V_k ||_2 = 1 for all 0 <= k < n_components Parameters ---------- - n_atoms : int, + n_components : int, number of dictionary elements to extract - alpha : int, + alpha : float, sparsity controlling parameter n_iter : int, @@ -1012,13 +1079,13 @@ class MiniBatchDictionaryLearning(BaseEstimator, SparseCodingMixin): n_jobs : int, number of parallel jobs to run - dict_init : array of shape (n_atoms, n_features), + dict_init : array of shape (n_components, n_features), initial value of the dictionary for warm restart scenarios verbose : degree of verbosity of the printed output - chunk_size : int, + batch_size : int, number of samples in each mini-batch shuffle : bool, @@ -1029,9 +1096,20 @@ class MiniBatchDictionaryLearning(BaseEstimator, SparseCodingMixin): Attributes ---------- - `components_` : array, [n_atoms, n_features] + components_ : array, [n_components, n_features] components extracted from the data + inner_stats_ : tuple of (A, B) ndarrays + Internal sufficient statistics that are kept by the algorithm. + Keeping them is useful in online settings, to avoid loosing the + history of the evolution, but they shouldn't have any use for the + end user. + A (n_components, n_components) is the dictionary covariance matrix. + B (n_features, n_components) is the data approximation matrix + + n_iter_ : int + Number of iterations run. + Notes ----- **References:** @@ -1047,13 +1125,13 @@ class MiniBatchDictionaryLearning(BaseEstimator, SparseCodingMixin): MiniBatchSparsePCA """ - def __init__(self, n_atoms=None, alpha=1, n_iter=1000, - fit_algorithm='lars', n_jobs=1, chunk_size=3, + def __init__(self, n_components=None, alpha=1, n_iter=1000, + fit_algorithm='lars', n_jobs=1, batch_size=3, shuffle=True, dict_init=None, transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, verbose=False, split_sign=False, random_state=None): - self._set_sparse_coding_params(n_atoms, transform_algorithm, + self._set_sparse_coding_params(n_components, transform_algorithm, transform_n_nonzero_coefs, transform_alpha, split_sign, n_jobs) self.alpha = alpha @@ -1062,7 +1140,7 @@ def __init__(self, n_atoms=None, alpha=1, n_iter=1000, self.dict_init = dict_init self.verbose = verbose self.shuffle = shuffle - self.chunk_size = chunk_size + self.batch_size = batch_size self.split_sign = split_sign self.random_state = random_state @@ -1080,25 +1158,27 @@ def fit(self, X, y=None): self : object Returns the instance itself. """ - self.random_state = check_random_state(self.random_state) - X = array2d(X) - if self.n_atoms is None: - n_atoms = X.shape[1] - else: - n_atoms = self.n_atoms - - U = dict_learning_online(X, n_atoms, self.alpha, - n_iter=self.n_iter, return_code=False, - method=self.fit_algorithm, - n_jobs=self.n_jobs, - dict_init=self.dict_init, - chunk_size=self.chunk_size, - shuffle=self.shuffle, verbose=self.verbose, - random_state=self.random_state) + random_state = check_random_state(self.random_state) + X = check_array(X) + + U, (A, B), self.n_iter_ = dict_learning_online( + X, self.n_components, self.alpha, + n_iter=self.n_iter, return_code=False, + method=self.fit_algorithm, + n_jobs=self.n_jobs, dict_init=self.dict_init, + batch_size=self.batch_size, shuffle=self.shuffle, + verbose=self.verbose, random_state=random_state, + return_inner_stats=True, + return_n_iter=True + ) self.components_ = U + # Keep track of the state of the algorithm to be able to do + # some online fitting (partial_fit) + self.inner_stats_ = (A, B) + self.iter_offset_ = self.n_iter return self - def partial_fit(self, X, y=None, iter_offset=0): + def partial_fit(self, X, y=None, iter_offset=None): """Updates the model using the data in X as a mini-batch. Parameters @@ -1107,24 +1187,40 @@ def partial_fit(self, X, y=None, iter_offset=0): Training vector, where n_samples in the number of samples and n_features is the number of features. + iter_offset: integer, optional + The number of iteration on data batches that has been + performed before this call to partial_fit. This is optional: + if no number is passed, the memory of the object is + used. + Returns ------- self : object Returns the instance itself. """ - self.random_state = check_random_state(self.random_state) - X = array2d(X) + if not hasattr(self, 'random_state_'): + self.random_state_ = check_random_state(self.random_state) + X = check_array(X) if hasattr(self, 'components_'): dict_init = self.components_ else: dict_init = self.dict_init - U = dict_learning_online(X, self.n_atoms, self.alpha, - n_iter=self.n_iter, - method=self.fit_algorithm, - n_jobs=self.n_jobs, dict_init=dict_init, - chunk_size=len(X), shuffle=False, - verbose=self.verbose, return_code=False, - iter_offset=iter_offset, - random_state=self.random_state) + inner_stats = getattr(self, 'inner_stats_', None) + if iter_offset is None: + iter_offset = getattr(self, 'iter_offset_', 0) + U, (A, B) = dict_learning_online( + X, self.n_components, self.alpha, + n_iter=self.n_iter, method=self.fit_algorithm, + n_jobs=self.n_jobs, dict_init=dict_init, + batch_size=len(X), shuffle=False, + verbose=self.verbose, return_code=False, + iter_offset=iter_offset, random_state=self.random_state_, + return_inner_stats=True, inner_stats=inner_stats, + ) self.components_ = U + + # Keep track of the state of the algorithm to be able to do + # some online fitting (partial_fit) + self.inner_stats_ = (A, B) + self.iter_offset_ = iter_offset + self.n_iter return self diff --git a/sklearn/decomposition/factor_analysis.py b/sklearn/decomposition/factor_analysis.py new file mode 100644 index 0000000000000..40deb0d25f294 --- /dev/null +++ b/sklearn/decomposition/factor_analysis.py @@ -0,0 +1,342 @@ +"""Factor Analysis. + +A latent linear variable model. + +FactorAnalysis is similar to probabilistic PCA implemented by PCA.score +While PCA assumes Gaussian noise with the same variance for each +feature, the FactorAnalysis model assumes different variances for +each of them. + +This implementation is based on David Barber's Book, +Bayesian Reasoning and Machine Learning, +http://www.cs.ucl.ac.uk/staff/d.barber/brml, +Algorithm 21.1 +""" + +# Author: Christian Osendorfer +# Alexandre Gramfort +# Denis A. Engemann + +# Licence: BSD3 + +import warnings +from math import sqrt, log +import numpy as np +from scipy import linalg + + +from ..base import BaseEstimator, TransformerMixin +from ..externals.six.moves import xrange +from ..utils import check_array, check_random_state +from ..utils.extmath import fast_logdet, fast_dot, randomized_svd, squared_norm +from ..utils.validation import check_is_fitted +from ..utils import ConvergenceWarning + + +class FactorAnalysis(BaseEstimator, TransformerMixin): + """Factor Analysis (FA) + + A simple linear generative model with Gaussian latent variables. + + The observations are assumed to be caused by a linear transformation of + lower dimensional latent factors and added Gaussian noise. + Without loss of generality the factors are distributed according to a + Gaussian with zero mean and unit covariance. The noise is also zero mean + and has an arbitrary diagonal covariance matrix. + + If we would restrict the model further, by assuming that the Gaussian + noise is even isotropic (all diagonal entries are the same) we would obtain + :class:`PPCA`. + + FactorAnalysis performs a maximum likelihood estimate of the so-called + `loading` matrix, the transformation of the latent variables to the + observed ones, using expectation-maximization (EM). + + Parameters + ---------- + n_components : int | None + Dimensionality of latent space, the number of components + of ``X`` that are obtained after ``transform``. + If None, n_components is set to the number of features. + + tol : float + Stopping tolerance for EM algorithm. + + copy : bool + Whether to make a copy of X. If ``False``, the input X gets overwritten + during fitting. + + max_iter : int + Maximum number of iterations. + + noise_variance_init : None | array, shape=(n_features,) + The initial guess of the noise variance for each feature. + If None, it defaults to np.ones(n_features) + + svd_method : {'lapack', 'randomized'} + Which SVD method to use. If 'lapack' use standard SVD from + scipy.linalg, if 'randomized' use fast ``randomized_svd`` function. + Defaults to 'randomized'. For most applications 'randomized' will + be sufficiently precise while providing significant speed gains. + Accuracy can also be improved by setting higher values for + `iterated_power`. If this is not sufficient, for maximum precision + you should choose 'lapack'. + + iterated_power : int, optional + Number of iterations for the power method. 3 by default. Only used + if ``svd_method`` equals 'randomized' + + random_state : int or RandomState + Pseudo number generator state used for random sampling. Only used + if ``svd_method`` equals 'randomized' + + Attributes + ---------- + components_ : array, [n_components, n_features] + Components with maximum variance. + + loglike_ : list, [n_iterations] + The log likelihood at each iteration. + + noise_variance_ : array, shape=(n_features,) + The estimated noise variance for each feature. + + n_iter_ : int + Number of iterations run. + + References + ---------- + .. David Barber, Bayesian Reasoning and Machine Learning, + Algorithm 21.1 + + .. Christopher M. Bishop: Pattern Recognition and Machine Learning, + Chapter 12.2.4 + + See also + -------- + PCA: Principal component analysis is also a latent linear variable model + which however assumes equal noise variance for each feature. + This extra assumption makes probabilistic PCA faster as it can be + computed in closed form. + FastICA: Independent component analysis, a latent variable model with + non-Gaussian latent variables. + """ + def __init__(self, n_components=None, tol=1e-2, copy=True, max_iter=1000, + noise_variance_init=None, svd_method='randomized', + iterated_power=3, random_state=0): + self.n_components = n_components + self.copy = copy + self.tol = tol + self.max_iter = max_iter + if svd_method not in ['lapack', 'randomized']: + raise ValueError('SVD method %s is not supported. Please consider' + ' the documentation' % svd_method) + self.svd_method = svd_method + + self.noise_variance_init = noise_variance_init + self.iterated_power = iterated_power + self.random_state = random_state + + def fit(self, X, y=None): + """Fit the FactorAnalysis model to X using EM + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data. + + Returns + ------- + self + """ + X = check_array(X, copy=self.copy, dtype=np.float) + + n_samples, n_features = X.shape + n_components = self.n_components + if n_components is None: + n_components = n_features + self.mean_ = np.mean(X, axis=0) + X -= self.mean_ + + # some constant terms + nsqrt = sqrt(n_samples) + llconst = n_features * log(2. * np.pi) + n_components + var = np.var(X, axis=0) + + if self.noise_variance_init is None: + psi = np.ones(n_features, dtype=X.dtype) + else: + if len(self.noise_variance_init) != n_features: + raise ValueError("noise_variance_init dimension does not " + "with number of features : %d != %d" % + (len(self.noise_variance_init), n_features)) + psi = np.array(self.noise_variance_init) + + loglike = [] + old_ll = -np.inf + SMALL = 1e-12 + + # we'll modify svd outputs to return unexplained variance + # to allow for unified computation of loglikelihood + if self.svd_method == 'lapack': + def my_svd(X): + _, s, V = linalg.svd(X, full_matrices=False) + return (s[:n_components], V[:n_components], + squared_norm(s[n_components:])) + elif self.svd_method == 'randomized': + random_state = check_random_state(self.random_state) + + def my_svd(X): + _, s, V = randomized_svd(X, n_components, + random_state=random_state, + n_iter=self.iterated_power) + return s, V, squared_norm(X) - squared_norm(s) + else: + raise ValueError('SVD method %s is not supported. Please consider' + ' the documentation' % self.svd_method) + + for i in xrange(self.max_iter): + # SMALL helps numerics + sqrt_psi = np.sqrt(psi) + SMALL + s, V, unexp_var = my_svd(X / (sqrt_psi * nsqrt)) + s **= 2 + # Use 'maximum' here to avoid sqrt problems. + W = np.sqrt(np.maximum(s - 1., 0.))[:, np.newaxis] * V + del V + W *= sqrt_psi + + # loglikelihood + ll = llconst + np.sum(np.log(s)) + ll += unexp_var + np.sum(np.log(psi)) + ll *= -n_samples / 2. + loglike.append(ll) + if (ll - old_ll) < self.tol: + break + old_ll = ll + + psi = np.maximum(var - np.sum(W ** 2, axis=0), SMALL) + else: + warnings.warn('FactorAnalysis did not converge.' + + ' You might want' + + ' to increase the number of iterations.', + ConvergenceWarning) + + self.components_ = W + self.noise_variance_ = psi + self.loglike_ = loglike + self.n_iter_ = i + 1 + return self + + def transform(self, X): + """Apply dimensionality reduction to X using the model. + + Compute the expected mean of the latent variables. + See Barber, 21.2.33 (or Bishop, 12.66). + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data. + + Returns + ------- + X_new : array-like, shape (n_samples, n_components) + The latent variables of X. + """ + check_is_fitted(self, 'components_') + + X = check_array(X) + Ih = np.eye(len(self.components_)) + + X_transformed = X - self.mean_ + + Wpsi = self.components_ / self.noise_variance_ + cov_z = linalg.inv(Ih + np.dot(Wpsi, self.components_.T)) + tmp = fast_dot(X_transformed, Wpsi.T) + X_transformed = fast_dot(tmp, cov_z) + + return X_transformed + + def get_covariance(self): + """Compute data covariance with the FactorAnalysis model. + + ``cov = components_.T * components_ + diag(noise_variance)`` + + Returns + ------- + cov : array, shape (n_features, n_features) + Estimated covariance of data. + """ + check_is_fitted(self, 'components_') + + cov = np.dot(self.components_.T, self.components_) + cov.flat[::len(cov) + 1] += self.noise_variance_ # modify diag inplace + return cov + + def get_precision(self): + """Compute data precision matrix with the FactorAnalysis model. + + Returns + ------- + precision : array, shape (n_features, n_features) + Estimated precision of data. + """ + check_is_fitted(self, 'components_') + + n_features = self.components_.shape[1] + + # handle corner cases first + if self.n_components == 0: + return np.diag(1. / self.noise_variance_) + if self.n_components == n_features: + return linalg.inv(self.get_covariance()) + + # Get precision using matrix inversion lemma + components_ = self.components_ + precision = np.dot(components_ / self.noise_variance_, components_.T) + precision.flat[::len(precision) + 1] += 1. + precision = np.dot(components_.T, + np.dot(linalg.inv(precision), components_)) + precision /= self.noise_variance_[:, np.newaxis] + precision /= -self.noise_variance_[np.newaxis, :] + precision.flat[::len(precision) + 1] += 1. / self.noise_variance_ + return precision + + def score_samples(self, X): + """Compute the log-likelihood of each sample + + Parameters + ---------- + X: array, shape (n_samples, n_features) + The data + + Returns + ------- + ll: array, shape (n_samples,) + Log-likelihood of each sample under the current model + """ + check_is_fitted(self, 'components_') + + Xr = X - self.mean_ + precision = self.get_precision() + n_features = X.shape[1] + log_like = np.zeros(X.shape[0]) + log_like = -.5 * (Xr * (np.dot(Xr, precision))).sum(axis=1) + log_like -= .5 * (n_features * log(2. * np.pi) + - fast_logdet(precision)) + return log_like + + def score(self, X, y=None): + """Compute the average log-likelihood of the samples + + Parameters + ---------- + X: array, shape (n_samples, n_features) + The data + + Returns + ------- + ll: float + Average log-likelihood of the samples under the current model + """ + return np.mean(self.score_samples(X)) diff --git a/sklearn/decomposition/fastica_.py b/sklearn/decomposition/fastica_.py index da9686dabd5f4..68a22815ed2c5 100644 --- a/sklearn/decomposition/fastica_.py +++ b/sklearn/decomposition/fastica_.py @@ -5,15 +5,19 @@ Independent Component Analysis, by Hyvarinen et al. """ -# Author: Pierre Lafaye de Micheaux, Stefan van der Walt, Gael Varoquaux, -# Bertrand Thirion, Alexandre Gramfort +# Authors: Pierre Lafaye de Micheaux, Stefan van der Walt, Gael Varoquaux, +# Bertrand Thirion, Alexandre Gramfort, Denis A. Engemann # License: BSD 3 clause import warnings import numpy as np from scipy import linalg from ..base import BaseEstimator, TransformerMixin -from ..utils import array2d, as_float_array, check_random_state, deprecated +from ..externals import six +from ..externals.six import moves +from ..utils import check_array, as_float_array, check_random_state +from ..utils.extmath import fast_dot +from ..utils.validation import check_is_fitted __all__ = ['fastica', 'FastICA'] @@ -24,13 +28,19 @@ def _gs_decorrelation(w, W, j): Parameters ---------- - w: array of shape(n), to be orthogonalized - W: array of shape(p, n), null space definition - j: int < p + w : ndarray of shape(n) + Array to be orthogonalized - caveats - ------- - assumes that W is orthogonal + W : ndarray of shape(p, n) + Null space definition + + j : int < p + The no of (from the first) rows of Null space W wrt which w is + orthogonalized. + + Notes + ----- + Assumes that W is orthogonal w changed in place """ w -= np.dot(np.dot(w, W[:j].T), W[:j]) @@ -41,42 +51,29 @@ def _sym_decorrelation(W): """ Symmetric decorrelation i.e. W <- (W * W.T) ^{-1/2} * W """ - K = np.dot(W, W.T) - s, u = linalg.eigh(K) + s, u = linalg.eigh(np.dot(W, W.T)) # u (resp. s) contains the eigenvectors (resp. square roots of # the eigenvalues) of W * W.T - W = np.dot(np.dot(np.dot(u, np.diag(1.0 / np.sqrt(s))), u.T), W) - return W + return np.dot(np.dot(u * (1. / np.sqrt(s)), u.T), W) -def _ica_def(X, tol, g, gprime, fun_args, max_iter, w_init): +def _ica_def(X, tol, g, fun_args, max_iter, w_init): """Deflationary FastICA using fun approx to neg-entropy function Used internally by FastICA. """ n_components = w_init.shape[0] - W = np.zeros((n_components, n_components), dtype=float) + W = np.zeros((n_components, n_components), dtype=X.dtype) + n_iter = [] # j is the index of the extracted component for j in range(n_components): w = w_init[j, :].copy() w /= np.sqrt((w ** 2).sum()) - n_iterations = 0 - # we set lim to tol+1 to be sure to enter at least once in next while - lim = tol + 1 - while ((lim > tol) & (n_iterations < (max_iter - 1))): - wtx = np.dot(w.T, X) - nonlin = g(wtx, fun_args) - if isinstance(nonlin, tuple): - gwtx, g_wtx = nonlin - else: - warnings.warn("Passing g and gprime separately is deprecated " - "and will be removed in 0.14.", - DeprecationWarning, stacklevel=2) - gwtx = nonlin - g_wtx = gprime(wtx, fun_args) + for i in moves.xrange(max_iter): + gwtx, g_wtx = g(fast_dot(w.T, X), fun_args) w1 = (X * gwtx).mean(axis=1) - g_wtx.mean() * w @@ -86,116 +83,158 @@ def _ica_def(X, tol, g, gprime, fun_args, max_iter, w_init): lim = np.abs(np.abs((w1 * w).sum()) - 1) w = w1 - n_iterations = n_iterations + 1 + if lim < tol: + break + n_iter.append(i + 1) W[j, :] = w - return W + return W, max(n_iter) -def _ica_par(X, tol, g, gprime, fun_args, max_iter, w_init): +def _ica_par(X, tol, g, fun_args, max_iter, w_init): """Parallel FastICA. Used internally by FastICA --main loop """ - n, p = X.shape - W = _sym_decorrelation(w_init) + del w_init + p_ = float(X.shape[1]) + for ii in moves.xrange(max_iter): + gwtx, g_wtx = g(fast_dot(W, X), fun_args) + W1 = _sym_decorrelation(fast_dot(gwtx, X.T) / p_ + - g_wtx[:, np.newaxis] * W) + del gwtx, g_wtx + # builtin max, abs are faster than numpy counter parts. + lim = max(abs(abs(np.diag(fast_dot(W1, W.T))) - 1)) + W = W1 + if lim < tol: + break + else: + warnings.warn('FastICA did not converge.' + + ' You might want' + + ' to increase the number of iterations.') - # we set lim to tol+1 to be sure to enter at least once in next while - lim = tol + 1 - it = 0 - while ((lim > tol) and (it < (max_iter - 1))): - wtx = np.dot(W, X) + return W, ii + 1 - nonlin = g(wtx, fun_args) - if isinstance(nonlin, tuple): - gwtx, g_wtx = nonlin - else: - warnings.warn("Passing g and gprime separately is deprecated " - "and will be removed in 0.14.", - DeprecationWarning, stacklevel=2) - gwtx = nonlin - g_wtx = gprime(wtx, fun_args) - W1 = np.dot(gwtx, X.T) / float(p) \ - - np.dot(np.diag(g_wtx.mean(axis=1)), W) +# Some standard non-linear functions. +# XXX: these should be optimized, as they can be a bottleneck. +def _logcosh(x, fun_args=None): + alpha = fun_args.get('alpha', 1.0) # comment it out? - W1 = _sym_decorrelation(W1) + x *= alpha + gx = np.tanh(x, x) # apply the tanh inplace + g_x = np.empty(x.shape[0]) + # XXX compute in chunks to avoid extra allocation + for i, gx_i in enumerate(gx): # please don't vectorize. + g_x[i] = (alpha * (1 - gx_i ** 2)).mean() + return gx, g_x + + +def _exp(x, fun_args): + exp = np.exp(-(x ** 2) / 2) + gx = x * exp + g_x = (1 - x ** 2) * exp + return gx, g_x.mean(axis=-1) - lim = max(abs(abs(np.diag(np.dot(W1, W.T))) - 1)) - W = W1 - it += 1 - return W +def _cube(x, fun_args): + return x ** 3, (3 * x ** 2).mean(axis=-1) def fastica(X, n_components=None, algorithm="parallel", whiten=True, - fun="logcosh", fun_prime='', fun_args={}, max_iter=200, - tol=1e-04, w_init=None, random_state=None): + fun="logcosh", fun_args=None, max_iter=200, tol=1e-04, w_init=None, + random_state=None, return_X_mean=False, compute_sources=True, + return_n_iter=False): """Perform Fast Independent Component Analysis. Parameters ---------- - X : array-like, shape = [n_samples, n_features] + X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. + n_components : int, optional Number of components to extract. If None no dimension reduction is performed. + algorithm : {'parallel', 'deflation'}, optional Apply a parallel or deflational FASTICA algorithm. - whiten: boolean, optional + + whiten : boolean, optional If True perform an initial whitening of the data. If False, the data is assumed to have already been preprocessed: it should be centered, normed and white. Otherwise you will get incorrect results. In this case the parameter n_components will be ignored. + fun : string or function, optional. Default: 'logcosh' The functional form of the G function used in the approximation to neg-entropy. Could be either 'logcosh', 'exp', or 'cube'. You can also provide your own function. It should return a tuple containing the value of the function, and of its derivative, in the - point. Supplying the derivative through the `fun_prime` attribute is - still supported, but deprecated. - fun_prime : empty string ('') or function, optional, deprecated. - See fun. - fun_args: dictionary, optional + point. Example: + + def my_g(x): + return x ** 3, 3 * x ** 2 + + fun_args : dictionary, optional Arguments to send to the functional form. - If empty and if fun='logcosh', fun_args will take value + If empty or None and if fun='logcosh', fun_args will take value {'alpha' : 1.0} - max_iter: int, optional - Maximum number of iterations to perform + + max_iter : int, optional + Maximum number of iterations to perform. + tol: float, optional A positive scalar giving the tolerance at which the - un-mixing matrix is considered to have converged - w_init: (n_components, n_components) array, optional + un-mixing matrix is considered to have converged. + + w_init : (n_components, n_components) array, optional Initial un-mixing array of dimension (n.comp,n.comp). - If None (default) then an array of normal r.v.'s is used - source_only: boolean, optional - If True, only the sources matrix is returned. - random_state: int or RandomState + If None (default) then an array of normal r.v.'s is used. + + random_state : int or RandomState Pseudo number generator state used for random sampling. + return_X_mean : bool, optional + If True, X_mean is returned too. + + compute_sources : bool, optional + If False, sources are not computed, but only the rotation matrix. + This can save memory when working with big data. Defaults to True. + + return_n_iter : bool, optional + Whether or not to return the number of iterations. + Returns ------- - K: (n_components, p) array or None. + K : array, shape (n_components, n_features) | None. If whiten is 'True', K is the pre-whitening matrix that projects data - onto the first n.comp principal components. If whiten is 'False', K is - 'None'. + onto the first n_components principal components. If whiten is 'False', + K is 'None'. - W: (n_components, n_components) array - estimated un-mixing matrix + W : array, shape (n_components, n_components) + Estimated un-mixing matrix. The mixing matrix can be obtained by:: w = np.dot(W, K.T) A = w.T * (w * w.T).I - S: (n_components, n) array - estimated source matrix + S : array, shape (n_components, n_samples) | None + Estimated source matrix + + X_mean : array, shape (n_features, ) + The mean over features. Returned only if return_X_mean is True. + n_iter : int + If the algorithm is "deflation", n_iter is the + maximum number of iterations run across all components. Else + they are just the number of iterations taken to converge. This is + returned only when return_n_iter is set to `True`. Notes ----- @@ -218,51 +257,33 @@ def fastica(X, n_components=None, algorithm="parallel", whiten=True, """ random_state = check_random_state(random_state) + fun_args = {} if fun_args is None else fun_args # make interface compatible with other decompositions - X = array2d(X).T + # a copy is required only for non whitened data + X = check_array(X, copy=whiten).T alpha = fun_args.get('alpha', 1.0) - if (alpha < 1) or (alpha > 2): - raise ValueError("alpha must be in [1,2]") - - gprime = None - if isinstance(fun, str): - # Some standard nonlinear functions - # XXX: these should be optimized, as they can be a bottleneck. - if fun == 'logcosh': - def g(x, fun_args): - alpha = fun_args.get('alpha', 1.0) # comment it out? - gx = np.tanh(alpha * x) - g_x = alpha * (1 - gx ** 2) - return gx, g_x - - elif fun == 'exp': - def g(x, fun_args): - exp = np.exp(-(x ** 2) / 2) - gx = x * exp - g_x = (1 - x ** 2) * exp - return gx, g_x - - elif fun == 'cube': - def g(x, fun_args): - return x ** 3, 3 * x ** 2 - - else: - raise ValueError( - 'fun argument should be one of logcosh, exp or cube') + if not 1 <= alpha <= 2: + raise ValueError('alpha must be in [1,2]') + + if fun == 'logcosh': + g = _logcosh + elif fun == 'exp': + g = _exp + elif fun == 'cube': + g = _cube elif callable(fun): def g(x, fun_args): return fun(x, **fun_args) - - def gprime(x, fun_args): - return fun_prime(x, **fun_args) else: - raise ValueError('fun argument should be either a string ' - '(one of logcosh, exp or cube) or a function') + exc = ValueError if isinstance(fun, six.string_types) else TypeError + raise exc("Unknown function %r;" + " should be one of 'logcosh', 'exp', 'cube' or callable" + % fun) n, p = X.shape - if whiten == False and n_components is not None: + if not whiten and n_components is not None: n_components = None warnings.warn('Ignoring n_components with whiten=False.') @@ -274,7 +295,8 @@ def gprime(x, fun_args): if whiten: # Centering the columns (ie the variables) - X = X - X.mean(axis=-1)[:, np.newaxis] + X_mean = X.mean(axis=-1) + X -= X_mean[:, np.newaxis] # Whitening and preprocessing by PCA u, d, _ = linalg.svd(X, full_matrices=False) @@ -289,133 +311,259 @@ def gprime(x, fun_args): else: # X must be casted to floats to avoid typing issues with numpy # 2.0 and the line below - X1 = as_float_array(X, copy=True) + X1 = as_float_array(X, copy=False) # copy has been taken care of if w_init is None: - w_init = random_state.normal(size=(n_components, n_components)) + w_init = np.asarray(random_state.normal(size=(n_components, + n_components)), dtype=X1.dtype) + else: w_init = np.asarray(w_init) if w_init.shape != (n_components, n_components): - raise ValueError("w_init has invalid shape -- should be %(shape)s" + raise ValueError('w_init has invalid shape -- should be %(shape)s' % {'shape': (n_components, n_components)}) kwargs = {'tol': tol, 'g': g, - 'gprime': gprime, 'fun_args': fun_args, 'max_iter': max_iter, 'w_init': w_init} if algorithm == 'parallel': - W = _ica_par(X1, **kwargs) + W, n_iter = _ica_par(X1, **kwargs) elif algorithm == 'deflation': - W = _ica_def(X1, **kwargs) + W, n_iter = _ica_def(X1, **kwargs) else: - raise ValueError('Invalid algorithm: must be either `parallel` or' + + raise ValueError('Invalid algorithm: must be either `parallel` or' ' `deflation`.') del X1 if whiten: - S = np.dot(np.dot(W, K), X) - return K, W, S.T + if compute_sources: + S = fast_dot(fast_dot(W, K), X).T + else: + S = None + if return_X_mean: + if return_n_iter: + return K, W, S, X_mean, n_iter + else: + return K, W, S, X_mean + else: + if return_n_iter: + return K, W, S, n_iter + else: + return K, W, S + else: - S = np.dot(W, X) - return None, W, S.T + if compute_sources: + S = fast_dot(W, X).T + else: + S = None + if return_X_mean: + if return_n_iter: + return None, W, S, None, n_iter + else: + return None, W, S, None + else: + if return_n_iter: + return None, W, S, n_iter + else: + return None, W, S class FastICA(BaseEstimator, TransformerMixin): - """FastICA; a fast algorithm for Independent Component Analysis + """FastICA: a fast algorithm for Independent Component Analysis. Parameters ---------- n_components : int, optional Number of components to use. If none is passed, all are used. + algorithm : {'parallel', 'deflation'} - Apply parallel or deflational algorithm for FastICA + Apply parallel or deflational algorithm for FastICA. + whiten : boolean, optional If whiten is false, the data is already considered to be whitened, and no whitening is performed. + fun : string or function, optional. Default: 'logcosh' The functional form of the G function used in the approximation to neg-entropy. Could be either 'logcosh', 'exp', or 'cube'. You can also provide your own function. It should return a tuple containing the value of the function, and of its derivative, in the - point. Supplying the derivative through the `fun_prime` attribute is - still supported, but deprecated. - fun_prime : empty string ('') or function, optional, deprecated. - See fun. - fun_args: dictionary, optional + point. Example: + + def my_g(x): + return x ** 3, 3 * x ** 2 + + fun_args : dictionary, optional Arguments to send to the functional form. If empty and if fun='logcosh', fun_args will take value - {'alpha' : 1.0} + {'alpha' : 1.0}. + max_iter : int, optional - Maximum number of iterations during fit + Maximum number of iterations during fit. + tol : float, optional - Tolerance on update at each iteration + Tolerance on update at each iteration. + w_init : None of an (n_components, n_components) ndarray The mixing matrix to be used to initialize the algorithm. - random_state: int or RandomState + + random_state : int or RandomState Pseudo number generator state used for random sampling. Attributes ---------- - `components_` : 2D array, [n_components, n_features] - The unmixing matrix - `sources_`: 2D array, [n_samples, n_components] - The estimated latent sources of the data. + components_ : 2D array, shape (n_components, n_features) + The unmixing matrix. + + mixing_ : array, shape (n_features, n_components) + The mixing matrix. + + n_iter_ : int + If the algorithm is "deflation", n_iter is the + maximum number of iterations run across all components. Else + they are just the number of iterations taken to converge. Notes ----- - Implementation based on `A. Hyvarinen and E. Oja, Independent Component Analysis: Algorithms and Applications, Neural Networks, 13(4-5), 2000, pp. 411-430` """ - def __init__(self, n_components=None, algorithm='parallel', whiten=True, - fun='logcosh', fun_prime='', fun_args=None, max_iter=200, - tol=1e-4, w_init=None, random_state=None): + fun='logcosh', fun_args=None, max_iter=200, tol=1e-4, + w_init=None, random_state=None): super(FastICA, self).__init__() self.n_components = n_components self.algorithm = algorithm self.whiten = whiten self.fun = fun - self.fun_prime = fun_prime - self.fun_args = {} if fun_args is None else fun_args + self.fun_args = fun_args self.max_iter = max_iter self.tol = tol self.w_init = w_init self.random_state = random_state - def fit(self, X, y=None): - whitening_, unmixing_, sources_ = fastica(X, self.n_components, - self.algorithm, self.whiten, - self.fun, self.fun_prime, self.fun_args, self.max_iter, - self.tol, self.w_init, - random_state=self.random_state) - if self.whiten == True: - self.components_ = np.dot(unmixing_, whitening_) + def _fit(self, X, compute_sources=False): + """Fit the model + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data, where n_samples is the number of samples + and n_features is the number of features. + + compute_sources : bool + If False, sources are not computes but only the rotation matrix. + This can save memory when working with big data. Defaults to False. + + Returns + ------- + X_new : array-like, shape (n_samples, n_components) + """ + fun_args = {} if self.fun_args is None else self.fun_args + whitening, unmixing, sources, X_mean, self.n_iter_ = fastica( + X=X, n_components=self.n_components, algorithm=self.algorithm, + whiten=self.whiten, fun=self.fun, fun_args=fun_args, + max_iter=self.max_iter, tol=self.tol, w_init=self.w_init, + random_state=self.random_state, return_X_mean=True, + compute_sources=compute_sources, return_n_iter=True) + + if self.whiten: + self.components_ = np.dot(unmixing, whitening) + self.mean_ = X_mean + self.whitening_ = whitening else: - self.components_ = unmixing_ - self.sources_ = sources_ + self.components_ = unmixing + + self.mixing_ = linalg.pinv(self.components_) + + if compute_sources: + self.__sources = sources + + return sources + + def fit_transform(self, X, y=None): + """Fit the model and recover the sources from X. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data, where n_samples is the number of samples + and n_features is the number of features. + + Returns + ------- + X_new : array-like, shape (n_samples, n_components) + """ + return self._fit(X, compute_sources=True) + + def fit(self, X, y=None): + """Fit the model to X. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data, where n_samples is the number of samples + and n_features is the number of features. + + Returns + ------- + self + """ + self._fit(X, compute_sources=False) return self - def transform(self, X, y=None): - """Apply un-mixing matrix "W" to X to recover the sources + def transform(self, X, y=None, copy=True): + """Recover the sources from X (apply the unmixing matrix). + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Data to transform, where n_samples is the number of samples + and n_features is the number of features. + + copy : bool (optional) + If False, data passed to fit are overwritten. Defaults to True. - S = X * W.T + Returns + ------- + X_new : array-like, shape (n_samples, n_components) """ - return np.dot(X, self.components_.T) + check_is_fitted(self, 'mixing_') - def get_mixing_matrix(self): - """Compute the mixing matrix + X = check_array(X, copy=copy) + if self.whiten: + X -= self.mean_ + + return fast_dot(X, self.components_.T) + + def inverse_transform(self, X, copy=True): + """Transform the sources back to the mixed data (apply mixing matrix). + + Parameters + ---------- + X : array-like, shape (n_samples, n_components) + Sources, where n_samples is the number of samples + and n_components is the number of components. + copy : bool (optional) + If False, data passed to fit are overwritten. Defaults to True. + + Returns + ------- + X_new : array-like, shape (n_samples, n_features) """ - return linalg.pinv(self.components_) + check_is_fitted(self, 'mixing_') + + if copy: + X = X.copy() + X = fast_dot(X, self.mixing_.T) + if self.whiten: + X += self.mean_ - @property - @deprecated("Renamed to ``components_``. This will be removed in 0.14.") - def unmixing_matrix_(self): - return self.components_ + return X diff --git a/sklearn/decomposition/incremental_pca.py b/sklearn/decomposition/incremental_pca.py new file mode 100644 index 0000000000000..9b5ccff00af22 --- /dev/null +++ b/sklearn/decomposition/incremental_pca.py @@ -0,0 +1,253 @@ +"""Incremental Principal Components Analysis.""" + +# Author: Kyle Kastner +# License: BSD 3 clause + +import numpy as np +from scipy import linalg + +from .base import _BasePCA +from ..utils import check_array, gen_batches +from ..utils.extmath import svd_flip, _batch_mean_variance_update + + +class IncrementalPCA(_BasePCA): + """Incremental principal components analysis (IPCA). + + Linear dimensionality reduction using Singular Value Decomposition of + centered data, keeping only the most significant singular vectors to + project the data to a lower dimensional space. + + Depending on the size of the input data, this algorithm can be much more + memory efficient than a PCA. + + This algorithm has constant memory complexity, on the order + of ``batch_size``, enabling use of np.memmap files without loading the + entire file into memory. + + The computational overhead of each SVD is + ``O(batch_size * n_features ** 2)``, but only 2 * batch_size samples + remain in memory at a time. There will be ``n_samples / batch_size`` SVD + computations to get the principal components, versus 1 large SVD of + complexity ``O(n_samples * n_features ** 2)`` for PCA. + + Parameters + ---------- + n_components : int or None, (default=None) + Number of components to keep. If ``n_components `` is ``None``, + then ``n_components`` is set to ``min(n_samples, n_features)``. + + batch_size : int or None, (default=None) + The number of samples to use for each batch. Only used when calling + ``fit``. If ``batch_size`` is ``None``, then ``batch_size`` + is inferred from the data and set to ``5 * n_features``, to provide a + balance between approximation accuracy and memory consumption. + + copy : bool, (default=True) + If False, X will be overwritten. ``copy=False`` can be used to + save memory but is unsafe for general use. + + whiten : bool, optional + When True (False by default) the ``components_`` vectors are divided + by ``n_samples`` times ``components_`` to ensure uncorrelated outputs + with unit component-wise variances. + + Whitening will remove some information from the transformed signal + (the relative variance scales of the components) but can sometimes + improve the predictive accuracy of the downstream estimators by + making data respect some hard-wired assumptions. + + Attributes + ---------- + components_ : array, shape (n_components, n_features) + Components with maximum variance. + + explained_variance_ : array, shape (n_components,) + Variance explained by each of the selected components. + + explained_variance_ratio_ : array, shape (n_components,) + Percentage of variance explained by each of the selected components. + If all components are stored, the sum of explained variances is equal + to 1.0 + + mean_ : array, shape (n_features,) + Per-feature empirical mean, aggregate over calls to ``partial_fit``. + + var_ : array, shape (n_features,) + Per-feature empirical variance, aggregate over calls to ``partial_fit``. + + noise_variance_ : float + The estimated noise covariance following the Probabilistic PCA model + from Tipping and Bishop 1999. See "Pattern Recognition and + Machine Learning" by C. Bishop, 12.2.1 p. 574 or + http://www.miketipping.com/papers/met-mppca.pdf. + + n_components_ : int + The estimated number of components. Relevant when ``n_components=None``. + + n_samples_seen_ : int + The number of samples processed by the estimator. Will be reset on + new calls to fit, but increments across ``partial_fit`` calls. + + Notes + ----- + Implements the incremental PCA model from: + `D. Ross, J. Lim, R. Lin, M. Yang, Incremental Learning for Robust Visual + Tracking, International Journal of Computer Vision, Volume 77, Issue 1-3, + pp. 125-141, May 2008.` + See http://www.cs.toronto.edu/~dross/ivt/RossLimLinYang_ijcv.pdf + + This model is an extension of the Sequential Karhunen-Loeve Transform from: + `A. Levy and M. Lindenbaum, Sequential Karhunen-Loeve Basis Extraction and + its Application to Images, IEEE Transactions on Image Processing, Volume 9, + Number 8, pp. 1371-1374, August 2000.` + See http://www.cs.technion.ac.il/~mic/doc/skl-ip.pdf + + We have specifically abstained from an optimization used by authors of both + papers, a QR decomposition used in specific situations to reduce the + algorithmic complexity of the SVD. The source for this technique is + `Matrix Computations, Third Edition, G. Holub and C. Van Loan, Chapter 5, + section 5.4.4, pp 252-253.`. This technique has been omitted because it is + advantageous only when decomposing a matrix with ``n_samples`` (rows) + >= 5/3 * ``n_features`` (columns), and hurts the readability of the + implemented algorithm. This would be a good opportunity for future + optimization, if it is deemed necessary. + + References + ---------- + D. Ross, J. Lim, R. Lin, M. Yang. Incremental Learning for Robust Visual + Tracking, International Journal of Computer Vision, Volume 77, + Issue 1-3, pp. 125-141, May 2008. + + G. Golub and C. Van Loan. Matrix Computations, Third Edition, Chapter 5, + Section 5.4.4, pp. 252-253. + + See also + -------- + PCA + RandomizedPCA + KernelPCA + SparsePCA + TruncatedSVD + """ + + def __init__(self, n_components=None, whiten=False, copy=True, + batch_size=None): + self.n_components = n_components + self.whiten = whiten + self.copy = copy + self.batch_size = batch_size + + def fit(self, X, y=None): + """Fit the model with X, using minibatches of size batch_size. + + Parameters + ---------- + X: array-like, shape (n_samples, n_features) + Training data, where n_samples is the number of samples and + n_features is the number of features. + + y: Passthrough for ``Pipeline`` compatibility. + + Returns + ------- + self: object + Returns the instance itself. + """ + self.components_ = None + self.mean_ = None + self.singular_values_ = None + self.explained_variance_ = None + self.explained_variance_ratio_ = None + self.noise_variance_ = None + self.var_ = None + self.n_samples_seen_ = 0 + X = check_array(X, dtype=np.float) + n_samples, n_features = X.shape + + if self.batch_size is None: + self.batch_size_ = 5 * n_features + else: + self.batch_size_ = self.batch_size + + for batch in gen_batches(n_samples, self.batch_size_): + self.partial_fit(X[batch]) + return self + + def partial_fit(self, X, y=None): + """Incremental fit with X. All of X is processed as a single batch. + + Parameters + ---------- + X: array-like, shape (n_samples, n_features) + Training data, where n_samples is the number of samples and + n_features is the number of features. + + Returns + ------- + self: object + Returns the instance itself. + """ + X = check_array(X, copy=self.copy, dtype=np.float) + n_samples, n_features = X.shape + if not hasattr(self, 'components_'): + self.components_ = None + + if self.n_components is None: + self.n_components_ = n_features + elif not 1 <= self.n_components <= n_features: + raise ValueError("n_components=%r invalid for n_features=%d, need " + "more rows than columns for IncrementalPCA " + "processing" % (self.n_components, n_features)) + else: + self.n_components_ = self.n_components + + if (self.components_ is not None) and (self.components_.shape[0] + != self.n_components_): + raise ValueError("Number of input features has changed from %i " + "to %i between calls to partial_fit! Try " + "setting n_components to a fixed value." % ( + self.components_.shape[0], self.n_components_)) + + if self.components_ is None: + # This is the first pass through partial_fit + self.n_samples_seen_ = 0 + col_var = X.var(axis=0) + col_mean = X.mean(axis=0) + X -= col_mean + U, S, V = linalg.svd(X, full_matrices=False) + U, V = svd_flip(U, V, u_based_decision=False) + explained_variance = S ** 2 / n_samples + explained_variance_ratio = S ** 2 / np.sum(col_var * + n_samples) + else: + col_batch_mean = X.mean(axis=0) + col_mean, col_var, n_total_samples = _batch_mean_variance_update( + X, self.mean_, self.var_, self.n_samples_seen_) + X -= col_batch_mean + # Build matrix of combined previous basis and new data + mean_correction = np.sqrt((self.n_samples_seen_ * n_samples) / + n_total_samples) * (self.mean_ - + col_batch_mean) + X_combined = np.vstack((self.singular_values_.reshape((-1, 1)) * + self.components_, X, + mean_correction)) + U, S, V = linalg.svd(X_combined, full_matrices=False) + U, V = svd_flip(U, V, u_based_decision=False) + explained_variance = S ** 2 / n_total_samples + explained_variance_ratio = S ** 2 / np.sum(col_var * + n_total_samples) + self.n_samples_seen_ += n_samples + self.components_ = V[:self.n_components_] + self.singular_values_ = S[:self.n_components_] + self.mean_ = col_mean + self.var_ = col_var + self.explained_variance_ = explained_variance[:self.n_components_] + self.explained_variance_ratio_ = \ + explained_variance_ratio[:self.n_components_] + if self.n_components_ < n_features: + self.noise_variance_ = \ + explained_variance[self.n_components_:].mean() + else: + self.noise_variance_ = 0. + return self diff --git a/sklearn/decomposition/kernel_pca.py b/sklearn/decomposition/kernel_pca.py index 0ff5965cad14d..f447e47934e17 100644 --- a/sklearn/decomposition/kernel_pca.py +++ b/sklearn/decomposition/kernel_pca.py @@ -1,12 +1,13 @@ """Kernel Principal Components Analysis""" # Author: Mathieu Blondel -# License: BSD Style. +# License: BSD 3 clause import numpy as np from scipy import linalg from ..utils.arpack import eigsh +from ..utils.validation import check_is_fitted, NotFittedError from ..base import BaseEstimator, TransformerMixin from ..preprocessing import KernelCenterer from ..metrics.pairwise import pairwise_kernels @@ -15,27 +16,32 @@ class KernelPCA(BaseEstimator, TransformerMixin): """Kernel Principal component analysis (KPCA) - Non-linear dimensionality reduction through the use of kernels. + Non-linear dimensionality reduction through the use of kernels (see + :ref:`metrics`). Parameters ---------- n_components: int or None Number of components. If None, all non-zero components are kept. - kernel: "linear" | "poly" | "rbf" | "sigmoid" | "precomputed" + kernel: "linear" | "poly" | "rbf" | "sigmoid" | "cosine" | "precomputed" Kernel. Default: "linear" - degree : int, optional - Degree for poly, rbf and sigmoid kernels. - Default: 3. + degree : int, default=3 + Degree for poly kernels. Ignored by other kernels. gamma : float, optional - Kernel coefficient for rbf and poly kernels. - Default: 1/n_features. + Kernel coefficient for rbf and poly kernels. Default: 1/n_features. + Ignored by other kernels. coef0 : float, optional Independent term in poly and sigmoid kernels. + Ignored by other kernels. + + kernel_params : mapping of string to any, optional + Parameters (keyword arguments) and values for kernel passed as + callable object. Ignored by other kernels. alpha: int Hyperparameter of the ridge regression that learns the @@ -60,65 +66,76 @@ class KernelPCA(BaseEstimator, TransformerMixin): maximum number of iterations for arpack Default: None (optimal value will be chosen by arpack) + remove_zero_eig : boolean, default=True + If True, then all components with zero eigenvalues are removed, so + that the number of components in the output may be < n_components + (and sometimes even zero due to numerical instability). + When n_components is None, this parameter is ignored and components + with zero eigenvalues are removed regardless. + Attributes ---------- - `lambdas_`, `alphas_`: - Eigenvalues and eigenvectors of the centered kernel matrix + lambdas_ : + Eigenvalues of the centered kernel matrix + + alphas_ : + Eigenvectors of the centered kernel matrix - `dual_coef_`: + dual_coef_ : Inverse transform matrix - `X_transformed_fit_`: + X_transformed_fit_ : Projection of the fitted data on the kernel principal components References ---------- - Kernel PCA was intoduced in: + Kernel PCA was introduced in: Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999. Kernel principal component analysis. In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352. """ - def __init__(self, n_components=None, kernel="linear", gamma=0, degree=3, - coef0=1, alpha=1.0, fit_inverse_transform=False, - eigen_solver='auto', tol=0, max_iter=None): + def __init__(self, n_components=None, kernel="linear", + gamma=None, degree=3, coef0=1, kernel_params=None, + alpha=1.0, fit_inverse_transform=False, eigen_solver='auto', + tol=0, max_iter=None, remove_zero_eig=False): if fit_inverse_transform and kernel == 'precomputed': raise ValueError( "Cannot fit_inverse_transform with a precomputed kernel.") self.n_components = n_components - self.kernel = kernel.lower() + self.kernel = kernel + self.kernel_params = kernel_params self.gamma = gamma self.degree = degree self.coef0 = coef0 self.alpha = alpha self.fit_inverse_transform = fit_inverse_transform self.eigen_solver = eigen_solver + self.remove_zero_eig = remove_zero_eig self.tol = tol self.max_iter = max_iter - self.centerer = KernelCenterer() + self._centerer = KernelCenterer() @property def _pairwise(self): return self.kernel == "precomputed" def _get_kernel(self, X, Y=None): - params = {"gamma": self.gamma, - "degree": self.degree, - "coef0": self.coef0} - try: - return pairwise_kernels(X, Y, metric=self.kernel, - filter_params=True, **params) - except AttributeError: - raise ValueError("%s is not a valid kernel. Valid kernels are: " - "rbf, poly, sigmoid, linear and precomputed." - % self.kernel) + if callable(self.kernel): + params = self.kernel_params or {} + else: + params = {"gamma": self.gamma, + "degree": self.degree, + "coef0": self.coef0} + return pairwise_kernels(X, Y, metric=self.kernel, + filter_params=True, **params) def _fit_transform(self, K): """ Fit's using kernel K""" # center kernel - K = self.centerer.fit_transform(K) + K = self._centerer.fit_transform(K) if self.n_components is None: n_components = K.shape[0] @@ -143,14 +160,15 @@ def _fit_transform(self, K): tol=self.tol, maxiter=self.max_iter) - # sort eignenvectors in descending order + # sort eigenvectors in descending order indices = self.lambdas_.argsort()[::-1] self.lambdas_ = self.lambdas_[indices] self.alphas_ = self.alphas_[:, indices] # remove eigenvectors with a zero eigenvalue - self.alphas_ = self.alphas_[:, self.lambdas_ > 0] - self.lambdas_ = self.lambdas_[self.lambdas_ > 0] + if self.remove_zero_eig or self.n_components is None: + self.alphas_ = self.alphas_[:, self.lambdas_ > 0] + self.lambdas_ = self.lambdas_[self.lambdas_ > 0] return K @@ -223,7 +241,9 @@ def transform(self, X): ------- X_new: array-like, shape (n_samples, n_components) """ - K = self.centerer.transform(self._get_kernel(X, self.X_fit_)) + check_is_fitted(self, 'X_fit_') + + K = self._centerer.transform(self._get_kernel(X, self.X_fit_)) return np.dot(K, self.alphas_ / np.sqrt(self.lambdas_)) def inverse_transform(self, X): @@ -242,7 +262,9 @@ def inverse_transform(self, X): "Learning to Find Pre-Images", G BakIr et al, 2004. """ if not self.fit_inverse_transform: - raise ValueError("Inverse transform was not fitted!") + raise NotFittedError("The fit_inverse_transform parameter was not" + " set to True when instantiating and hence " + "the inverse transform is not available.") K = self._get_kernel(X, self.X_transformed_fit_) diff --git a/sklearn/decomposition/nmf.py b/sklearn/decomposition/nmf.py index 038be7f718c38..7afc0b3ab029d 100644 --- a/sklearn/decomposition/nmf.py +++ b/sklearn/decomposition/nmf.py @@ -5,31 +5,29 @@ # Author: Chih-Jen Lin, National Taiwan University (original projected gradient # NMF implementation) # Author: Anthony Di Franco (original Python and NumPy port) -# License: BSD +# License: BSD 3 clause from __future__ import division -from ..base import BaseEstimator, TransformerMixin -from ..utils import atleast2d_or_csr, check_random_state -from ..utils.extmath import randomized_svd, safe_sparse_dot +from math import sqrt +import warnings import numpy as np -from scipy.optimize import nnls import scipy.sparse as sp -import warnings - +from scipy.optimize import nnls -def _pos(x): - """Positive part of a vector / matrix""" - return (x >= 0) * x +from ..base import BaseEstimator, TransformerMixin +from ..utils import check_random_state, check_array +from ..utils.extmath import randomized_svd, safe_sparse_dot, squared_norm +from ..utils.validation import check_is_fitted -def _neg(x): - """Negative part of a vector / matrix""" - neg_x = -x - neg_x *= x < 0 - return neg_x +def safe_vstack(Xs): + if any(sp.issparse(X) for X in Xs): + return sp.vstack(Xs) + else: + return np.vstack(Xs) def norm(x): @@ -37,8 +35,12 @@ def norm(x): See: http://fseoane.net/blog/2011/computing-the-vector-norm/ """ - x = x.ravel() - return np.sqrt(np.dot(x.T, x)) + return sqrt(squared_norm(x)) + + +def trace_dot(X, Y): + """Trace of np.dot(X, Y.T).""" + return np.dot(X.ravel(), Y.ravel()) def _sparseness(x): @@ -63,14 +65,13 @@ def _initialize_nmf(X, n_components, variant=None, eps=1e-6, Parameters ---------- - X: array, [n_samples, n_features] + X : array, [n_samples, n_features] The data matrix to be decomposed. - n_components: - The number of components desired in the - approximation. + n_components : array, [n_components, n_features] + The number of components desired in the approximation. - variant: None | 'a' | 'ar' + variant : None | 'a' | 'ar' The variant of the NNDSVD algorithm. Accepts None, 'a', 'ar' None: leaves the zero entries as zero @@ -78,29 +79,26 @@ def _initialize_nmf(X, n_components, variant=None, eps=1e-6, 'ar': Fills the zero entries with standard normal random variates. Default: None - eps: + eps: float Truncate all values less then this in output to zero. - random_state: numpy.RandomState | int, optional + random_state : numpy.RandomState | int, optional The generator used to fill in the zeros, when using variant='ar' Default: numpy.random Returns ------- - (W, H): + (W, H) : Initial guesses for solving X ~= WH such that the number of columns in W is n_components. - Remarks - ------- - - This implements the algorithm described in - C. Boutsidis, E. Gallopoulos: SVD based - initialization: A head start for nonnegative - matrix factorization - Pattern Recognition, 2008 + References + ---------- + C. Boutsidis, E. Gallopoulos: SVD based initialization: A head start for + nonnegative matrix factorization - Pattern Recognition, 2008 - http://www.cs.rpi.edu/~boutsc/files/nndsvd.pdf + http://tinyurl.com/nndsvd """ check_non_negative(X, "NMF initialization") if variant not in (None, 'a', 'ar'): @@ -114,12 +112,12 @@ def _initialize_nmf(X, n_components, variant=None, eps=1e-6, W[:, 0] = np.sqrt(S[0]) * np.abs(U[:, 0]) H[0, :] = np.sqrt(S[0]) * np.abs(V[0, :]) - for j in xrange(1, n_components): + for j in range(1, n_components): x, y = U[:, j], V[j, :] # extract positive and negative parts of column vectors - x_p, y_p = _pos(x), _pos(y) - x_n, y_n = _neg(x), _neg(y) + x_p, y_p = np.maximum(x, 0), np.maximum(y, 0) + x_n, y_n = np.abs(np.minimum(x, 0)), np.abs(np.minimum(y, 0)) # and their norms x_p_nrm, y_p_nrm = norm(x_p), norm(y_p) @@ -157,7 +155,7 @@ def _initialize_nmf(X, n_components, variant=None, eps=1e-6, return W, H -def _nls_subproblem(V, W, H_init, tol, max_iter): +def _nls_subproblem(V, W, H, tol, max_iter, sigma=0.01, beta=0.1): """Non-negative least square solver Solves a non-negative least squares subproblem using the @@ -166,59 +164,76 @@ def _nls_subproblem(V, W, H_init, tol, max_iter): Parameters ---------- - V, W: - Constant matrices + V, W : array-like + Constant matrices. - H_init: - Initial guess for the solution + H : array-like + Initial guess for the solution. - tol: + tol : float Tolerance of the stopping condition. - max_iter: - Maximum number of iterations before - timing out. + max_iter : int + Maximum number of iterations before timing out. + + sigma : float + Constant used in the sufficient decrease condition checked by the line + search. Smaller values lead to a looser sufficient decrease condition, + thus reducing the time taken by the line search, but potentially + increasing the number of iterations of the projected gradient + procedure. 0.01 is a commonly used value in the optimization + literature. + + beta : float + Factor by which the step size is decreased (resp. increased) until + (resp. as long as) the sufficient decrease condition is satisfied. + Larger values allow to find a better step size but lead to longer line + search. 0.1 is a commonly used value in the optimization literature. Returns ------- - H: - Solution to the non-negative least squares problem + H : array-like + Solution to the non-negative least squares problem. - grad: + grad : array-like The gradient. - n_iter: + n_iter : int The number of iterations done by the algorithm. - """ - if (H_init < 0).any(): - raise ValueError("Negative values in H_init passed to NLS solver.") + References + ---------- + C.-J. Lin. Projected gradient methods for non-negative matrix factorization. + Neural Computation, 19(2007), 2756-2779. + http://www.csie.ntu.edu.tw/~cjlin/nmf/ - H = H_init - WtV = safe_sparse_dot(W.T, V, dense_output=True) - WtW = safe_sparse_dot(W.T, W, dense_output=True) + """ + WtV = safe_sparse_dot(W.T, V) + WtW = np.dot(W.T, W) # values justified in the paper alpha = 1 - beta = 0.1 - for n_iter in xrange(1, max_iter + 1): + for n_iter in range(1, max_iter + 1): grad = np.dot(WtW, H) - WtV - proj_gradient = norm(grad[np.logical_or(grad < 0, H > 0)]) - if proj_gradient < tol: + + # The following multiplication with a boolean array is more than twice + # as fast as indexing into grad. + if norm(grad * np.logical_or(grad < 0, H > 0)) < tol: break - for inner_iter in xrange(1, 20): + Hp = H + + for inner_iter in range(19): + # Gradient step. Hn = H - alpha * grad - # Hn = np.where(Hn > 0, Hn, 0) - Hn = _pos(Hn) + # Projection step. + Hn *= Hn > 0 d = Hn - H - gradd = np.sum(grad * d) - dQd = np.sum(np.dot(WtW, d) * d) - # magic numbers whoa - suff_decr = 0.99 * gradd + 0.5 * dQd < 0 - if inner_iter == 1: + gradd = np.dot(grad.ravel(), d.ravel()) + dQd = np.dot(np.dot(WtW, d).ravel(), d.ravel()) + suff_decr = (1 - sigma) * gradd + 0.5 * dQd < 0 + if inner_iter == 0: decr_alpha = not suff_decr - Hp = H if decr_alpha: if suff_decr: @@ -244,14 +259,11 @@ class ProjectedGradientNMF(BaseEstimator, TransformerMixin): Parameters ---------- - X: {array-like, sparse matrix}, shape = [n_samples, n_features] - Data the model will be fit to. - - n_components: int or None + n_components : int or None Number of components, if n_components is not set all components are kept - init: 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'random' + init : 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'random' Method used to initialize the procedure. Default: 'nndsvdar' if n_components < n_features, otherwise random. Valid options:: @@ -265,24 +277,24 @@ class ProjectedGradientNMF(BaseEstimator, TransformerMixin): for when sparsity is not desired) 'random': non-negative random matrices - sparseness: 'data' | 'components' | None, default: None + sparseness : 'data' | 'components' | None, default: None Where to enforce sparsity in the model. - beta: double, default: 1 + beta : double, default: 1 Degree of sparseness, if sparseness is not None. Larger values mean more sparseness. - eta: double, default: 0.1 - Degree of correctness to mantain, if sparsity is not None. Smaller + eta : double, default: 0.1 + Degree of correctness to maintain, if sparsity is not None. Smaller values mean larger error. - tol: double, default: 1e-4 + tol : double, default: 1e-4 Tolerance value used in stopping conditions. - max_iter: int, default: 200 + max_iter : int, default: 200 Number of iterations to compute. - nls_max_iter: int, default: 2000 + nls_max_iter : int, default: 2000 Number of iterations in NLS subproblem. random_state : int or RandomState @@ -290,15 +302,16 @@ class ProjectedGradientNMF(BaseEstimator, TransformerMixin): Attributes ---------- - `components_` : array, [n_components, n_features] - Non-negative components of the data + components_ : array, [n_components, n_features] + Non-negative components of the data. - `reconstruction_err_` : number - Frobenius norm of the matrix difference between the - training data and the reconstructed data from the - fit produced by the model. ``|| X - WH ||_2`` - Not computed for sparse input matrices because it is - too expensive in terms of memory. + reconstruction_err_ : number + Frobenius norm of the matrix difference between + the training data and the reconstructed data from + the fit produced by the model. ``|| X - WH ||_2`` + + n_iter_ : int + Number of iterations run. Examples -------- @@ -325,12 +338,12 @@ class ProjectedGradientNMF(BaseEstimator, TransformerMixin): sparseness='components', tol=0.0001) >>> model.components_ array([[ 1.67481991, 0.29614922], - [-0. , 0.4681982 ]]) + [ 0. , 0.4681982 ]]) >>> model.reconstruction_err_ #doctest: +ELLIPSIS 0.513... - Notes - ----- + References + ---------- This implements C.-J. Lin. Projected gradient methods @@ -347,13 +360,12 @@ class ProjectedGradientNMF(BaseEstimator, TransformerMixin): C. Boutsidis, E. Gallopoulos: SVD based initialization: A head start for nonnegative matrix factorization - Pattern Recognition, 2008 - http://www.cs.rpi.edu/~boutsc/files/nndsvd.pdf - + http://tinyurl.com/nndsvd """ def __init__(self, n_components=None, init=None, sparseness=None, beta=1, - eta=0.1, tol=1e-4, max_iter=200, nls_max_iter=2000, - random_state=None): + eta=0.1, tol=1e-4, max_iter=200, nls_max_iter=2000, + random_state=None): self.n_components = n_components self.init = init self.tol = tol @@ -372,34 +384,27 @@ def _init(self, X): n_samples, n_features = X.shape init = self.init if init is None: - if self.n_components < n_features: + if self.n_components_ < n_features: init = 'nndsvd' else: init = 'random' - if isinstance(init, (int, np.integer, np.random.RandomState)): - random_state = check_random_state(init) - init = "random" - warnings.warn("Passing a random seed or generator as init " - "is deprecated and will be removed in 0.15. Use " - "init='random' and random_state instead.", DeprecationWarning) - else: - random_state = self.random_state + random_state = self.random_state if init == 'nndsvd': - W, H = _initialize_nmf(X, self.n_components) + W, H = _initialize_nmf(X, self.n_components_) elif init == 'nndsvda': - W, H = _initialize_nmf(X, self.n_components, variant='a') + W, H = _initialize_nmf(X, self.n_components_, variant='a') elif init == 'nndsvdar': - W, H = _initialize_nmf(X, self.n_components, variant='ar') + W, H = _initialize_nmf(X, self.n_components_, variant='ar') elif init == "random": rng = check_random_state(random_state) - W = rng.randn(n_samples, self.n_components) + W = rng.randn(n_samples, self.n_components_) # we do not write np.abs(W, out=W) to stay compatible with # numpy 1.5 and earlier where the 'out' keyword is not # supported as a kwarg on ufuncs np.abs(W, W) - H = rng.randn(self.n_components, n_features) + H = rng.randn(self.n_components_, n_features) np.abs(H, H) else: raise ValueError( @@ -410,42 +415,44 @@ def _init(self, X): def _update_W(self, X, H, W, tolW): n_samples, n_features = X.shape - if self.sparseness == None: + if self.sparseness is None: W, gradW, iterW = _nls_subproblem(X.T, H.T, W.T, tolW, self.nls_max_iter) elif self.sparseness == 'data': W, gradW, iterW = _nls_subproblem( - np.r_[X.T, np.zeros((1, n_samples))], - np.r_[H.T, np.sqrt(self.beta) * - np.ones((1, self.n_components))], - W.T, tolW, self.nls_max_iter) + safe_vstack([X.T, np.zeros((1, n_samples))]), + safe_vstack([H.T, np.sqrt(self.beta) * np.ones((1, + self.n_components_))]), + W.T, tolW, self.nls_max_iter) elif self.sparseness == 'components': W, gradW, iterW = _nls_subproblem( - np.r_[X.T, np.zeros((self.n_components, n_samples))], - np.r_[H.T, np.sqrt(self.eta) * - np.eye(self.n_components)], - W.T, tolW, self.nls_max_iter) + safe_vstack([X.T, + np.zeros((self.n_components_, n_samples))]), + safe_vstack([H.T, + np.sqrt(self.eta) * np.eye(self.n_components_)]), + W.T, tolW, self.nls_max_iter) - return W, gradW, iterW + return W.T, gradW.T, iterW def _update_H(self, X, H, W, tolH): n_samples, n_features = X.shape - if self.sparseness == None: + if self.sparseness is None: H, gradH, iterH = _nls_subproblem(X, W, H, tolH, self.nls_max_iter) elif self.sparseness == 'data': H, gradH, iterH = _nls_subproblem( - np.r_[X, np.zeros((self.n_components, n_features))], - np.r_[W, np.sqrt(self.eta) * - np.eye(self.n_components)], - H, tolH, self.nls_max_iter) + safe_vstack([X, np.zeros((self.n_components_, n_features))]), + safe_vstack([W, + np.sqrt(self.eta) * np.eye(self.n_components_)]), + H, tolH, self.nls_max_iter) elif self.sparseness == 'components': H, gradH, iterH = _nls_subproblem( - np.r_[X, np.zeros((1, n_features))], - np.r_[W, np.sqrt(self.beta) * - np.ones((1, self.n_components))], - H, tolH, self.nls_max_iter) + safe_vstack([X, np.zeros((1, n_features))]), + safe_vstack([W, + np.sqrt(self.beta) + * np.ones((1, self.n_components_))]), + H, tolH, self.nls_max_iter) return H, gradH, iterH @@ -465,13 +472,15 @@ def fit_transform(self, X, y=None): data: array, [n_samples, n_components] Transformed data """ - X = atleast2d_or_csr(X) + X = check_array(X, accept_sparse='csr') check_non_negative(X, "NMF.fit") n_samples, n_features = X.shape if not self.n_components: - self.n_components = n_features + self.n_components_ = n_features + else: + self.n_components_ = self.n_components W, H = self._init(X) @@ -483,39 +492,47 @@ def fit_transform(self, X, y=None): tolW = max(0.001, self.tol) * init_grad # why max? tolH = tolW - for n_iter in xrange(1, self.max_iter + 1): + tol = self.tol * init_grad + + for n_iter in range(1, self.max_iter + 1): # stopping condition # as discussed in paper proj_norm = norm(np.r_[gradW[np.logical_or(gradW < 0, W > 0)], gradH[np.logical_or(gradH < 0, H > 0)]]) - if proj_norm < self.tol * init_grad: + if proj_norm < tol: break # update W W, gradW, iterW = self._update_W(X, H, W, tolW) - - W = W.T - gradW = gradW.T if iterW == 1: tolW = 0.1 * tolW # update H H, gradH, iterH = self._update_H(X, H, W, tolH) - if iterH == 1: tolH = 0.1 * tolH - self.comp_sparseness_ = _sparseness(H.ravel()) - self.data_sparseness_ = _sparseness(W.ravel()) + if not sp.issparse(X): + error = norm(X - np.dot(W, H)) + else: + sqnorm_X = np.dot(X.data, X.data) + norm_WHT = trace_dot(np.dot(np.dot(W.T, W), H), H) + cross_prod = trace_dot((X * H.T), W) + error = sqrt(sqnorm_X + norm_WHT - 2. * cross_prod) - if not sp.issparse(X): - self.reconstruction_err_ = norm(X - np.dot(W, H)) + self.reconstruction_err_ = error - self.components_ = H + self.comp_sparseness_ = _sparseness(H.ravel()) + self.data_sparseness_ = _sparseness(W.ravel()) + + H[H == 0] = 0 # fix up negative zeros + self.components_ = H if n_iter == self.max_iter: - warnings.warn("Iteration limit reached during fit") + warnings.warn("Iteration limit reached during fit. Solving for W exactly.") + return self.transform(X) + self.n_iter_ = n_iter return W def fit(self, X, y=None, **params): @@ -548,11 +565,20 @@ def transform(self, X): data: array, [n_samples, n_components] Transformed data """ - X = atleast2d_or_csr(X) - H = np.zeros((X.shape[0], self.n_components)) - for j in xrange(0, X.shape[0]): - H[j, :], _ = nnls(self.components_.T, X[j, :]) - return H + check_is_fitted(self, 'n_components_') + + X = check_array(X, accept_sparse='csc') + Wt = np.zeros((self.n_components_, X.shape[0])) + check_non_negative(X, "ProjectedGradientNMF.transform") + + if sp.issparse(X): + Wt, _, _ = _nls_subproblem(X.T, self.components_.T, Wt, + tol=self.tol, + max_iter=self.nls_max_iter) + else: + for j in range(0, X.shape[0]): + Wt[:, j], _ = nnls(self.components_.T, X[j, :]) + return Wt.T class NMF(ProjectedGradientNMF): diff --git a/sklearn/decomposition/pca.py b/sklearn/decomposition/pca.py index 57c559139611f..fd733c6ceaf76 100644 --- a/sklearn/decomposition/pca.py +++ b/sklearn/decomposition/pca.py @@ -4,18 +4,22 @@ # Author: Alexandre Gramfort # Olivier Grisel # Mathieu Blondel -# License: BSD Style. +# Denis A. Engemann +# Michael Eickenberg +# +# License: BSD 3 clause + +from math import log, sqrt import numpy as np -import warnings from scipy import linalg -from math import log +from scipy.special import gammaln from ..base import BaseEstimator, TransformerMixin -from ..utils import array2d, check_random_state, as_float_array -from ..utils.extmath import fast_logdet -from ..utils.extmath import safe_sparse_dot -from ..utils.extmath import randomized_svd +from ..utils import check_random_state, as_float_array +from ..utils import check_array +from ..utils.extmath import fast_dot, fast_logdet, randomized_svd +from ..utils.validation import check_is_fitted def _assess_dimension_(spectrum, rank, n_samples, n_features): @@ -27,13 +31,13 @@ def _assess_dimension_(spectrum, rank, n_samples, n_features): Parameters ---------- spectrum: array of shape (n) - data spectrum - rank: int, - tested rank value - n_samples: int, - number of samples - dim: int, - embedding/empirical dimension + Data spectrum. + rank: int + Tested rank value. + n_samples: int + Number of samples. + n_features: int + Number of features. Returns ------- @@ -47,37 +51,35 @@ def _assess_dimension_(spectrum, rank, n_samples, n_features): """ if rank > len(spectrum): raise ValueError("The tested rank cannot exceed the rank of the" - " dataset") - from scipy.special import gammaln + " dataset") - pu = -rank * np.log(2) + pu = -rank * log(2.) for i in range(rank): - pu += (gammaln((n_features - i) / 2) - - np.log(np.pi) * (n_features - i) / 2) + pu += (gammaln((n_features - i) / 2.) + - log(np.pi) * (n_features - i) / 2.) pl = np.sum(np.log(spectrum[:rank])) - pl = -pl * n_samples / 2 + pl = -pl * n_samples / 2. if rank == n_features: pv = 0 v = 1 else: v = np.sum(spectrum[rank:]) / (n_features - rank) - pv = -np.log(v) * n_samples * (n_features - rank) / 2 + pv = -np.log(v) * n_samples * (n_features - rank) / 2. - m = n_features * rank - rank * (rank + 1) / 2 - pp = np.log(2 * np.pi) * (m + rank + 1) / 2 + m = n_features * rank - rank * (rank + 1.) / 2. + pp = log(2. * np.pi) * (m + rank + 1.) / 2. - pa = 0 + pa = 0. spectrum_ = spectrum.copy() spectrum_[rank:n_features] = v for i in range(rank): for j in range(i + 1, len(spectrum)): - pa += (np.log((spectrum[i] - spectrum[j]) - * (1. / spectrum_[j] - 1. / spectrum_[i])) - + np.log(n_samples)) + pa += log((spectrum[i] - spectrum[j]) * + (1. / spectrum_[j] - 1. / spectrum_[i])) + log(n_samples) - ll = pu + pl + pv + pp - pa / 2 - rank * np.log(n_samples) / 2 + ll = pu + pl + pv + pp - pa / 2. - rank * log(n_samples) / 2. return ll @@ -87,10 +89,10 @@ def _infer_dimension_(spectrum, n_samples, n_features): The dataset is described by its spectrum `spectrum`. """ - ll = [] - for rank in range(len(spectrum)): - ll.append(_assess_dimension_(spectrum, rank, n_samples, n_features)) - ll = np.array(ll) + n_spectrum = len(spectrum) + ll = np.empty(n_spectrum) + for rank in range(n_spectrum): + ll[rank] = _assess_dimension_(spectrum, rank, n_samples, n_features) return ll.argmax() @@ -122,7 +124,9 @@ class PCA(BaseEstimator, TransformerMixin): percentage specified by n_components copy : bool - If False, data passed to fit are overwritten + If False, data passed to fit are overwritten and running + fit(X).transform(X) will not yield the expected results, + use fit_transform(X) instead. whiten : bool, optional When True (False by default) the `components_` vectors are divided @@ -136,19 +140,40 @@ class PCA(BaseEstimator, TransformerMixin): Attributes ---------- - `components_` : array, [n_components, n_features] + components_ : array, [n_components, n_features] Components with maximum variance. - `explained_variance_ratio_` : array, [n_components] + explained_variance_ratio_ : array, [n_components] Percentage of variance explained by each of the selected components. \ k is not set then all components are stored and the sum of explained \ variances is equal to 1.0 + mean_ : array, [n_features] + Per-feature empirical mean, estimated from the training set. + + n_components_ : int + The estimated number of components. Relevant when n_components is set + to 'mle' or a number between 0 and 1 to select using explained + variance. + + noise_variance_ : float + The estimated noise covariance following the Probabilistic PCA model + from Tipping and Bishop 1999. See "Pattern Recognition and + Machine Learning" by C. Bishop, 12.2.1 p. 574 or + http://www.miketipping.com/papers/met-mppca.pdf. It is required to + computed the estimated data covariance and score samples. + Notes ----- For n_components='mle', this class uses the method of `Thomas P. Minka: Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604` + Implements the probabilistic PCA model from: + M. Tipping and C. Bishop, Probabilistic Principal Component Analysis, + Journal of the Royal Statistical Society, Series B, 61, Part 3, pp. 611-622 + via the score and score_samples methods. + See http://www.miketipping.com/papers/met-mppca.pdf + Due to implementation subtleties of the Singular Value Decomposition (SVD), which is used in this implementation, running fit twice on the same matrix can lead to principal components with signs flipped (change in direction). @@ -169,17 +194,17 @@ class PCA(BaseEstimator, TransformerMixin): See also -------- - ProbabilisticPCA RandomizedPCA KernelPCA SparsePCA + TruncatedSVD """ def __init__(self, n_components=None, copy=True, whiten=False): self.n_components = n_components self.copy = copy self.whiten = whiten - def fit(self, X, y=None, **params): + def fit(self, X, y=None): """Fit the model with X. Parameters @@ -193,16 +218,16 @@ def fit(self, X, y=None, **params): self : object Returns the instance itself. """ - self._fit(X, **params) + self._fit(X) return self - def fit_transform(self, X, y=None, **params): + def fit_transform(self, X, y=None): """Fit the model with X and apply the dimensionality reduction on X. Parameters ---------- X : array-like, shape (n_samples, n_features) - Training data, where n_samples in the number of samples + Training data, where n_samples is the number of samples and n_features is the number of features. Returns @@ -210,66 +235,145 @@ def fit_transform(self, X, y=None, **params): X_new : array-like, shape (n_samples, n_components) """ - U, S, V = self._fit(X, **params) - U = U[:, :self.n_components] + U, S, V = self._fit(X) + U = U[:, :self.n_components_] if self.whiten: # X_new = X * V / S * sqrt(n_samples) = U * sqrt(n_samples) - U *= np.sqrt(X.shape[0]) + U *= sqrt(X.shape[0]) else: # X_new = X * V = U * S * V^T * V = U * S - U *= S[:self.n_components] + U *= S[:self.n_components_] return U def _fit(self, X): - X = array2d(X) + """Fit the model on X + + Parameters + ---------- + X: array-like, shape (n_samples, n_features) + Training vector, where n_samples in the number of samples and + n_features is the number of features. + + Returns + ------- + U, s, V : ndarrays + The SVD of the input data, copied and centered when + requested. + """ + X = check_array(X) n_samples, n_features = X.shape X = as_float_array(X, copy=self.copy) # Center data self.mean_ = np.mean(X, axis=0) X -= self.mean_ U, S, V = linalg.svd(X, full_matrices=False) - self.explained_variance_ = (S ** 2) / n_samples - self.explained_variance_ratio_ = self.explained_variance_ / \ - self.explained_variance_.sum() + explained_variance_ = (S ** 2) / n_samples + explained_variance_ratio_ = (explained_variance_ / + explained_variance_.sum()) - if self.whiten: - self.components_ = V / S[:, np.newaxis] * np.sqrt(n_samples) - else: - self.components_ = V + components_ = V - if self.n_components == 'mle': + n_components = self.n_components + if n_components is None: + n_components = n_features + elif n_components == 'mle': if n_samples < n_features: raise ValueError("n_components='mle' is only supported " - "if n_samples >= n_features") - self.n_components = _infer_dimension_(self.explained_variance_, - n_samples, n_features) + "if n_samples >= n_features") + + n_components = _infer_dimension_(explained_variance_, + n_samples, n_features) + elif not 0 <= n_components <= n_features: + raise ValueError("n_components=%r invalid for n_features=%d" + % (n_components, n_features)) - elif (self.n_components is not None - and 0 < self.n_components - and self.n_components < 1.0): + if 0 < n_components < 1.0: # number of components for which the cumulated explained variance # percentage is superior to the desired threshold - ratio_cumsum = self.explained_variance_ratio_.cumsum() - self.n_components = np.sum(ratio_cumsum < self.n_components) + 1 + ratio_cumsum = explained_variance_ratio_.cumsum() + n_components = np.sum(ratio_cumsum < n_components) + 1 - if self.n_components is not None: - self.components_ = self.components_[:self.n_components, :] - self.explained_variance_ = \ - self.explained_variance_[:self.n_components] - self.explained_variance_ratio_ = \ - self.explained_variance_ratio_[:self.n_components] + # Compute noise covariance using Probabilistic PCA model + # The sigma2 maximum likelihood (cf. eq. 12.46) + if n_components < n_features: + self.noise_variance_ = explained_variance_[n_components:].mean() + else: + self.noise_variance_ = 0. + + # store n_samples to revert whitening when getting covariance + self.n_samples_ = n_samples + + self.components_ = components_[:n_components] + self.explained_variance_ = explained_variance_[:n_components] + explained_variance_ratio_ = explained_variance_ratio_[:n_components] + self.explained_variance_ratio_ = explained_variance_ratio_ + self.n_components_ = n_components return (U, S, V) + def get_covariance(self): + """Compute data covariance with the generative model. + + ``cov = components_.T * S**2 * components_ + sigma2 * eye(n_features)`` + where S**2 contains the explained variances. + + Returns + ------- + cov : array, shape=(n_features, n_features) + Estimated covariance of data. + """ + components_ = self.components_ + exp_var = self.explained_variance_ + if self.whiten: + components_ = components_ * np.sqrt(exp_var[:, np.newaxis]) + exp_var_diff = np.maximum(exp_var - self.noise_variance_, 0.) + cov = np.dot(components_.T * exp_var_diff, components_) + cov.flat[::len(cov) + 1] += self.noise_variance_ # modify diag inplace + return cov + + def get_precision(self): + """Compute data precision matrix with the generative model. + + Equals the inverse of the covariance but computed with + the matrix inversion lemma for efficiency. + + Returns + ------- + precision : array, shape=(n_features, n_features) + Estimated precision of data. + """ + n_features = self.components_.shape[1] + + # handle corner cases first + if self.n_components_ == 0: + return np.eye(n_features) / self.noise_variance_ + if self.n_components_ == n_features: + return linalg.inv(self.get_covariance()) + + # Get precision using matrix inversion lemma + components_ = self.components_ + exp_var = self.explained_variance_ + exp_var_diff = np.maximum(exp_var - self.noise_variance_, 0.) + precision = np.dot(components_, components_.T) / self.noise_variance_ + precision.flat[::len(precision) + 1] += 1. / exp_var_diff + precision = np.dot(components_.T, + np.dot(linalg.inv(precision), components_)) + precision /= -(self.noise_variance_ ** 2) + precision.flat[::len(precision) + 1] += 1. / self.noise_variance_ + return precision + def transform(self, X): """Apply the dimensionality reduction on X. + X is projected on the first principal components previous extracted + from a training set. + Parameters ---------- X : array-like, shape (n_samples, n_features) - New data, where n_samples in the number of samples + New data, where n_samples is the number of samples and n_features is the number of features. Returns @@ -277,8 +381,14 @@ def transform(self, X): X_new : array-like, shape (n_samples, n_components) """ - X_transformed = X - self.mean_ - X_transformed = np.dot(X_transformed, self.components_.T) + check_is_fitted(self, 'mean_') + + X = check_array(X) + if self.mean_ is not None: + X = X - self.mean_ + X_transformed = fast_dot(X, self.components_.T) + if self.whiten: + X_transformed /= np.sqrt(self.explained_variance_) return X_transformed def inverse_transform(self, X): @@ -288,87 +398,71 @@ def inverse_transform(self, X): Parameters ---------- X : array-like, shape (n_samples, n_components) - New data, where n_samples in the number of samples + New data, where n_samples is the number of samples and n_components is the number of components. Returns ------- X_original array-like, shape (n_samples, n_features) - - Notes - ----- - If whitening is enabled, inverse_transform does not compute the - exact inverse operation as transform. """ - return np.dot(X, self.components_) + self.mean_ + check_is_fitted(self, 'mean_') + + if self.whiten: + return fast_dot( + X, + np.sqrt(self.explained_variance_[:, np.newaxis]) * + self.components_) + self.mean_ + else: + return fast_dot(X, self.components_) + self.mean_ -class ProbabilisticPCA(PCA): - """Additional layer on top of PCA that adds a probabilistic evaluation""" - __doc__ += PCA.__doc__ + def score_samples(self, X): + """Return the log-likelihood of each sample - def fit(self, X, y=None, homoscedastic=True): - """Additionally to PCA.fit, learns a covariance model + See. "Pattern Recognition and Machine Learning" + by C. Bishop, 12.2.1 p. 574 + or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- - X : array of shape(n_samples, n_features) - The data to fit + X: array, shape(n_samples, n_features) + The data. - homoscedastic : bool, optional, - If True, average variance across remaining dimensions + Returns + ------- + ll: array, shape (n_samples,) + Log-likelihood of each sample under the current model """ - PCA.fit(self, X) - n_features = X.shape[1] - self._dim = n_features - Xr = X - self.mean_ - Xr -= np.dot(np.dot(Xr, self.components_.T), self.components_) - n_samples = X.shape[0] - if n_features <= self.n_components: - delta = np.zeros(n_features) - elif homoscedastic: - delta = (Xr ** 2).sum() * np.ones(n_features) \ - / (n_samples * n_features) - else: - delta = (Xr ** 2).mean(0) / (n_features - self.n_components) - self.covariance_ = np.diag(delta) - n_components = self.n_components - if n_components is None: - n_components = self.dim - for k in range(n_components): - add_cov = np.outer(self.components_[k], self.components_[k]) - self.covariance_ += self.explained_variance_[k] * add_cov - return self + check_is_fitted(self, 'mean_') - @property - def dim(self): - warnings.warn("Using dim is deprecated" - "since version 0.12, and backward compatibility " - "won't be maintained from version 0.14 onward. ", - DeprecationWarning, stacklevel=2) - return self._dim + X = check_array(X) + Xr = X - self.mean_ + n_features = X.shape[1] + log_like = np.zeros(X.shape[0]) + precision = self.get_precision() + log_like = -.5 * (Xr * (np.dot(Xr, precision))).sum(axis=1) + log_like -= .5 * (n_features * log(2. * np.pi) + - fast_logdet(precision)) + return log_like def score(self, X, y=None): - """Return a score associated to new data + """Return the average log-likelihood of all samples + + See. "Pattern Recognition and Machine Learning" + by C. Bishop, 12.2.1 p. 574 + or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- - X: array of shape(n_samples, n_features) - The data to test + X: array, shape(n_samples, n_features) + The data. Returns ------- - ll: array of shape (n_samples), - log-likelihood of each row of X under the current model + ll: float + Average log-likelihood of the samples under the current model """ - Xr = X - self.mean_ - n_features = X.shape[1] - log_like = np.zeros(X.shape[0]) - self.precision_ = linalg.inv(self.covariance_) - log_like = -.5 * (Xr * (np.dot(Xr, self.precision_))).sum(axis=1) - log_like -= .5 * (fast_logdet(self.covariance_) + \ - n_features * log(2 * np.pi)) - return log_like + return np.mean(self.score_samples(X)) class RandomizedPCA(BaseEstimator, TransformerMixin): @@ -378,19 +472,19 @@ class RandomizedPCA(BaseEstimator, TransformerMixin): Decomposition of the data and keeping only the most significant singular vectors to project the data to a lower dimensional space. - This implementation uses a randomized SVD implementation and can - handle both scipy.sparse and numpy dense arrays as input. - Parameters ---------- - n_components : int - Maximum number of components to keep: default is 50. + n_components : int, optional + Maximum number of components to keep. When not given or None, this + is set to n_features (the second dimension of the training data). copy : bool - If False, data passed to fit are overwritten + If False, data passed to fit are overwritten and running + fit(X).transform(X) will not yield the expected results, + use fit_transform(X) instead. iterated_power : int, optional - Number of iteration for the power method. 3 by default. + Number of iterations for the power method. 3 by default. whiten : bool, optional When True (False by default) the `components_` vectors are divided @@ -408,14 +502,17 @@ class RandomizedPCA(BaseEstimator, TransformerMixin): Attributes ---------- - `components_` : array, [n_components, n_features] + components_ : array, [n_components, n_features] Components with maximum variance. - `explained_variance_ratio_` : array, [n_components] + explained_variance_ratio_ : array, [n_components] Percentage of variance explained by each of the selected components. \ k is not set then all components are stored and the sum of explained \ variances is equal to 1.0 + mean_ : array, [n_features] + Per-feature empirical mean, estimated from the training set. + Examples -------- >>> import numpy as np @@ -424,14 +521,14 @@ class RandomizedPCA(BaseEstimator, TransformerMixin): >>> pca = RandomizedPCA(n_components=2) >>> pca.fit(X) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE RandomizedPCA(copy=True, iterated_power=3, n_components=2, - random_state=, whiten=False) + random_state=None, whiten=False) >>> print(pca.explained_variance_ratio_) # doctest: +ELLIPSIS [ 0.99244... 0.00755...] See also -------- PCA - ProbabilisticPCA + TruncatedSVD References ---------- @@ -446,65 +543,81 @@ class RandomizedPCA(BaseEstimator, TransformerMixin): """ def __init__(self, n_components=None, copy=True, iterated_power=3, - whiten=False, random_state=None): + whiten=False, random_state=None): self.n_components = n_components self.copy = copy self.iterated_power = iterated_power self.whiten = whiten - self.mean_ = None self.random_state = random_state def fit(self, X, y=None): + """Fit the model with X by extracting the first principal components. + + Parameters + ---------- + X: array-like, shape (n_samples, n_features) + Training data, where n_samples in the number of samples + and n_features is the number of features. + + Returns + ------- + self : object + Returns the instance itself. + """ + self._fit(check_array(X)) + return self + + def _fit(self, X): """Fit the model to the data X. Parameters ---------- - X: array-like or scipy.sparse matrix, shape (n_samples, n_features) + X: array-like, shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. Returns ------- - self : object - Returns the instance itself. + X : ndarray, shape (n_samples, n_features) + The input data, copied, centered and whitened when requested. """ - self.random_state = check_random_state(self.random_state) - if not hasattr(X, 'todense'): - # not a sparse matrix, ensure this is a 2D array - X = np.atleast_2d(as_float_array(X, copy=self.copy)) + random_state = check_random_state(self.random_state) + X = np.atleast_2d(as_float_array(X, copy=self.copy)) n_samples = X.shape[0] - if not hasattr(X, 'todense'): - # Center data - self.mean_ = np.mean(X, axis=0) - X -= self.mean_ + # Center data + self.mean_ = np.mean(X, axis=0) + X -= self.mean_ if self.n_components is None: n_components = X.shape[1] else: n_components = self.n_components U, S, V = randomized_svd(X, n_components, - n_iterations=self.iterated_power, - random_state=self.random_state) + n_iter=self.iterated_power, + random_state=random_state) self.explained_variance_ = exp_var = (S ** 2) / n_samples - self.explained_variance_ratio_ = exp_var / exp_var.sum() + full_var = np.var(X, axis=0).sum() + self.explained_variance_ratio_ = exp_var / full_var if self.whiten: - n = X.shape[0] - self.components_ = V / S[:, np.newaxis] * np.sqrt(n) + self.components_ = V / S[:, np.newaxis] * sqrt(n_samples) else: self.components_ = V - return self + return X - def transform(self, X): + def transform(self, X, y=None): """Apply dimensionality reduction on X. + X is projected on the first principal components previous extracted + from a training set. + Parameters ---------- - X : array-like or scipy.sparse matrix, shape (n_samples, n_features) + X : array-like, shape (n_samples, n_features) New data, where n_samples in the number of samples and n_features is the number of features. @@ -513,20 +626,41 @@ def transform(self, X): X_new : array-like, shape (n_samples, n_components) """ + check_is_fitted(self, 'mean_') + + X = check_array(X) if self.mean_ is not None: X = X - self.mean_ - X = safe_sparse_dot(X, self.components_.T) + X = fast_dot(X, self.components_.T) return X - def inverse_transform(self, X): + def fit_transform(self, X, y=None): + """Fit the model with X and apply the dimensionality reduction on X. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + New data, where n_samples in the number of samples + and n_features is the number of features. + + Returns + ------- + X_new : array-like, shape (n_samples, n_components) + + """ + X = check_array(X) + X = self._fit(X) + return fast_dot(X, self.components_.T) + + def inverse_transform(self, X, y=None): """Transform data back to its original space. Returns an array X_original whose transform would be X. Parameters ---------- - X : array-like or scipy.sparse matrix, shape (n_samples, n_components) + X : array-like, shape (n_samples, n_components) New data, where n_samples in the number of samples and n_components is the number of components. @@ -539,7 +673,9 @@ def inverse_transform(self, X): If whitening is enabled, inverse_transform does not compute the exact inverse operation of transform. """ - X_original = safe_sparse_dot(X, self.components_) + check_is_fitted(self, 'mean_') + + X_original = fast_dot(X, self.components_) if self.mean_ is not None: X_original = X_original + self.mean_ return X_original diff --git a/sklearn/decomposition/sparse_pca.py b/sklearn/decomposition/sparse_pca.py index c7c6060d0625b..38f8e2e3209d4 100644 --- a/sklearn/decomposition/sparse_pca.py +++ b/sklearn/decomposition/sparse_pca.py @@ -1,10 +1,11 @@ """Matrix factorization with Sparse PCA""" # Author: Vlad Niculae, Gael Varoquaux, Alexandre Gramfort -# License: BSD +# License: BSD 3 clause import numpy as np -from ..utils import check_random_state, array2d +from ..utils import check_random_state, check_array +from ..utils.validation import check_is_fitted from ..linear_model import ridge_regression from ..base import BaseEstimator, TransformerMixin from .dict_learning import dict_learning, dict_learning_online @@ -46,10 +47,10 @@ class SparsePCA(BaseEstimator, TransformerMixin): n_jobs : int, Number of parallel jobs to run. - U_init : array of shape (n_samples, n_atoms), + U_init : array of shape (n_samples, n_components), Initial values for the loadings for warm restart scenarios. - V_init : array of shape (n_atoms, n_features), + V_init : array of shape (n_components, n_features), Initial values for the components for warm restart scenarios. verbose : @@ -60,12 +61,15 @@ class SparsePCA(BaseEstimator, TransformerMixin): Attributes ---------- - `components_` : array, [n_components, n_features] + components_ : array, [n_components, n_features] Sparse components extracted from the data. - `error_` : array + error_ : array Vector of errors at each iteration. + n_iter_ : int + Number of iterations run. + See also -------- PCA @@ -73,8 +77,8 @@ class SparsePCA(BaseEstimator, TransformerMixin): DictionaryLearning """ def __init__(self, n_components=None, alpha=1, ridge_alpha=0.01, - max_iter=1000, tol=1e-8, method='lars', n_jobs=1, U_init=None, - V_init=None, verbose=False, random_state=None): + max_iter=1000, tol=1e-8, method='lars', n_jobs=1, U_init=None, + V_init=None, verbose=False, random_state=None): self.n_components = n_components self.alpha = alpha self.ridge_alpha = ridge_alpha @@ -101,21 +105,25 @@ def fit(self, X, y=None): self : object Returns the instance itself. """ - self.random_state = check_random_state(self.random_state) - X = array2d(X) + random_state = check_random_state(self.random_state) + X = check_array(X) if self.n_components is None: n_components = X.shape[1] else: n_components = self.n_components code_init = self.V_init.T if self.V_init is not None else None dict_init = self.U_init.T if self.U_init is not None else None - Vt, _, E = dict_learning(X.T, n_components, self.alpha, - tol=self.tol, max_iter=self.max_iter, - method=self.method, n_jobs=self.n_jobs, - verbose=self.verbose, - random_state=self.random_state, - code_init=code_init, - dict_init=dict_init) + Vt, _, E, self.n_iter_ = dict_learning(X.T, n_components, self.alpha, + tol=self.tol, + max_iter=self.max_iter, + method=self.method, + n_jobs=self.n_jobs, + verbose=self.verbose, + random_state=random_state, + code_init=code_init, + dict_init=dict_init, + return_n_iter=True + ) self.components_ = Vt.T self.error_ = E return self @@ -145,9 +153,12 @@ def transform(self, X, ridge_alpha=None): X_new array, shape (n_samples, n_components) Transformed data. """ + check_is_fitted(self, 'components_') + + X = check_array(X) ridge_alpha = self.ridge_alpha if ridge_alpha is None else ridge_alpha U = ridge_regression(self.components_.T, X.T, ridge_alpha, - solver='dense_cholesky') + solver='cholesky') s = np.sqrt((U ** 2).sum(axis=0)) s[s == 0] = 1 U /= s @@ -180,7 +191,7 @@ class MiniBatchSparsePCA(SparsePCA): callback : callable, callable that gets invoked every five iterations - chunk_size : int, + batch_size : int, the number of features to take in each mini batch verbose : @@ -204,12 +215,15 @@ class MiniBatchSparsePCA(SparsePCA): Attributes ---------- - `components_` : array, [n_components, n_features] + components_ : array, [n_components, n_features] Sparse components extracted from the data. - `error_` : array + error_ : array Vector of errors at each iteration. + n_iter_ : int + Number of iterations run. + See also -------- PCA @@ -217,14 +231,15 @@ class MiniBatchSparsePCA(SparsePCA): DictionaryLearning """ def __init__(self, n_components=None, alpha=1, ridge_alpha=0.01, - n_iter=100, callback=None, chunk_size=3, verbose=False, - shuffle=True, n_jobs=1, method='lars', random_state=None): + n_iter=100, callback=None, batch_size=3, verbose=False, + shuffle=True, n_jobs=1, method='lars', random_state=None): + self.n_components = n_components self.alpha = alpha self.ridge_alpha = ridge_alpha self.n_iter = n_iter self.callback = callback - self.chunk_size = chunk_size + self.batch_size = batch_size self.verbose = verbose self.shuffle = shuffle self.n_jobs = n_jobs @@ -245,19 +260,22 @@ def fit(self, X, y=None): self : object Returns the instance itself. """ - self.random_state = check_random_state(self.random_state) - X = array2d(X) + random_state = check_random_state(self.random_state) + X = check_array(X) if self.n_components is None: n_components = X.shape[1] else: n_components = self.n_components - Vt, _ = dict_learning_online(X.T, n_components, alpha=self.alpha, - n_iter=self.n_iter, return_code=True, - dict_init=None, verbose=self.verbose, - callback=self.callback, - chunk_size=self.chunk_size, - shuffle=self.shuffle, - n_jobs=self.n_jobs, method=self.method, - random_state=self.random_state) + Vt, _, self.n_iter_ = dict_learning_online( + X.T, n_components, alpha=self.alpha, + n_iter=self.n_iter, return_code=True, + dict_init=None, verbose=self.verbose, + callback=self.callback, + batch_size=self.batch_size, + shuffle=self.shuffle, + n_jobs=self.n_jobs, method=self.method, + random_state=random_state, + return_n_iter=True + ) self.components_ = Vt.T return self diff --git a/sklearn/decomposition/tests/test_dict_learning.py b/sklearn/decomposition/tests/test_dict_learning.py index 3c1c42aef611a..f0bb6bb281b27 100644 --- a/sklearn/decomposition/tests/test_dict_learning.py +++ b/sklearn/decomposition/tests/test_dict_learning.py @@ -1,36 +1,40 @@ import numpy as np -from numpy.testing import assert_array_almost_equal, assert_array_equal, \ - assert_equal -from nose import SkipTest -from nose.tools import assert_true +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import ignore_warnings -from .. import DictionaryLearning, MiniBatchDictionaryLearning, SparseCoder, \ - dict_learning_online, sparse_encode +from sklearn.decomposition import DictionaryLearning +from sklearn.decomposition import MiniBatchDictionaryLearning +from sklearn.decomposition import SparseCoder +from sklearn.decomposition import dict_learning_online +from sklearn.decomposition import sparse_encode -rng = np.random.RandomState(0) +rng_global = np.random.RandomState(0) n_samples, n_features = 10, 8 -X = rng.randn(n_samples, n_features) +X = rng_global.randn(n_samples, n_features) def test_dict_learning_shapes(): - n_atoms = 5 - dico = DictionaryLearning(n_atoms).fit(X) - assert_true(dico.components_.shape == (n_atoms, n_features)) + n_components = 5 + dico = DictionaryLearning(n_components, random_state=0).fit(X) + assert_true(dico.components_.shape == (n_components, n_features)) def test_dict_learning_overcomplete(): - n_atoms = 12 - X = rng.randn(n_samples, n_features) - dico = DictionaryLearning(n_atoms).fit(X) - assert_true(dico.components_.shape == (n_atoms, n_features)) + n_components = 12 + dico = DictionaryLearning(n_components, random_state=0).fit(X) + assert_true(dico.components_.shape == (n_components, n_features)) def test_dict_learning_reconstruction(): - n_atoms = 12 - dico = DictionaryLearning(n_atoms, transform_algorithm='omp', + n_components = 12 + dico = DictionaryLearning(n_components, transform_algorithm='omp', transform_alpha=0.001, random_state=0) code = dico.fit(X).transform(X) assert_array_almost_equal(np.dot(code, dico.components_), X) @@ -44,8 +48,8 @@ def test_dict_learning_reconstruction(): def test_dict_learning_nonzero_coefs(): - n_atoms = 4 - dico = DictionaryLearning(n_atoms, transform_algorithm='lars', + n_components = 4 + dico = DictionaryLearning(n_components, transform_algorithm='lars', transform_n_nonzero_coefs=3, random_state=0) code = dico.fit(X).transform(X[1]) assert_true(len(np.flatnonzero(code)) == 3) @@ -55,88 +59,144 @@ def test_dict_learning_nonzero_coefs(): assert_equal(len(np.flatnonzero(code)), 3) +def test_dict_learning_unknown_fit_algorithm(): + n_components = 5 + dico = DictionaryLearning(n_components, fit_algorithm='') + assert_raises(ValueError, dico.fit, X) + + def test_dict_learning_split(): - n_atoms = 5 - dico = DictionaryLearning(n_atoms, transform_algorithm='threshold') + n_components = 5 + dico = DictionaryLearning(n_components, transform_algorithm='threshold', + random_state=0) code = dico.fit(X).transform(X) dico.split_sign = True split_code = dico.transform(X) - assert_array_equal(split_code[:, :n_atoms] - split_code[:, n_atoms:], code) + assert_array_equal(split_code[:, :n_components] - + split_code[:, n_components:], code) def test_dict_learning_online_shapes(): -# rng = np.random.RandomState(0) -# X = rng.randn(12, 10) - n_atoms = 8 - code, dictionary = dict_learning_online(X, n_atoms=n_atoms, alpha=1, - random_state=rng) - assert_equal(code.shape, (n_samples, n_atoms)) - assert_equal(dictionary.shape, (n_atoms, n_features)) + rng = np.random.RandomState(0) + n_components = 8 + code, dictionary = dict_learning_online(X, n_components=n_components, + alpha=1, random_state=rng) + assert_equal(code.shape, (n_samples, n_components)) + assert_equal(dictionary.shape, (n_components, n_features)) assert_equal(np.dot(code, dictionary).shape, X.shape) +def test_dict_learning_online_verbosity(): + n_components = 5 + # test verbosity + from sklearn.externals.six.moves import cStringIO as StringIO + import sys + + old_stdout = sys.stdout + try: + sys.stdout = StringIO() + dico = MiniBatchDictionaryLearning(n_components, n_iter=20, verbose=1, + random_state=0) + dico.fit(X) + dico = MiniBatchDictionaryLearning(n_components, n_iter=20, verbose=2, + random_state=0) + dico.fit(X) + dict_learning_online(X, n_components=n_components, alpha=1, verbose=1, + random_state=0) + dict_learning_online(X, n_components=n_components, alpha=1, verbose=2, + random_state=0) + finally: + sys.stdout = old_stdout + + assert_true(dico.components_.shape == (n_components, n_features)) + + def test_dict_learning_online_estimator_shapes(): - n_atoms = 5 - dico = MiniBatchDictionaryLearning(n_atoms, n_iter=20).fit(X) - assert_true(dico.components_.shape == (n_atoms, n_features)) + n_components = 5 + dico = MiniBatchDictionaryLearning(n_components, n_iter=20, random_state=0) + dico.fit(X) + assert_true(dico.components_.shape == (n_components, n_features)) def test_dict_learning_online_overcomplete(): - n_atoms = 12 - dico = MiniBatchDictionaryLearning(n_atoms, n_iter=20).fit(X) - assert_true(dico.components_.shape == (n_atoms, n_features)) + n_components = 12 + dico = MiniBatchDictionaryLearning(n_components, n_iter=20, + random_state=0).fit(X) + assert_true(dico.components_.shape == (n_components, n_features)) def test_dict_learning_online_initialization(): - n_atoms = 12 - V = rng.randn(n_atoms, n_features) - dico = MiniBatchDictionaryLearning(n_atoms, n_iter=0, dict_init=V).fit(X) + n_components = 12 + rng = np.random.RandomState(0) + V = rng.randn(n_components, n_features) + dico = MiniBatchDictionaryLearning(n_components, n_iter=0, + dict_init=V, random_state=0).fit(X) assert_array_equal(dico.components_, V) def test_dict_learning_online_partial_fit(): - # this test was not actually passing before! - raise SkipTest - n_atoms = 12 - V = rng.randn(n_atoms, n_features) # random init + n_components = 12 + rng = np.random.RandomState(0) + V = rng.randn(n_components, n_features) # random init V /= np.sum(V ** 2, axis=1)[:, np.newaxis] - rng1 = np.random.RandomState(0) - rng2 = np.random.RandomState(0) - dico1 = MiniBatchDictionaryLearning(n_atoms, n_iter=10, chunk_size=1, - shuffle=False, dict_init=V, - random_state=rng1).fit(X) - dico2 = MiniBatchDictionaryLearning(n_atoms, n_iter=1, dict_init=V, - random_state=rng2) - for ii, sample in enumerate(X): - dico2.partial_fit(sample, iter_offset=ii * dico2.n_iter) - # if ii == 1: break - assert_true(not np.all(sparse_encode(X, dico1.components_, alpha=100) == - 0)) - assert_array_equal(dico1.components_, dico2.components_) + dict1 = MiniBatchDictionaryLearning(n_components, n_iter=10*len(X), + batch_size=1, + alpha=1, shuffle=False, dict_init=V, + random_state=0).fit(X) + dict2 = MiniBatchDictionaryLearning(n_components, alpha=1, + n_iter=1, dict_init=V, + random_state=0) + for i in range(10): + for sample in X: + dict2.partial_fit(sample) + + assert_true(not np.all(sparse_encode(X, dict1.components_, alpha=1) == + 0)) + assert_array_almost_equal(dict1.components_, dict2.components_, + decimal=2) def test_sparse_encode_shapes(): - n_atoms = 12 - V = rng.randn(n_atoms, n_features) # random init + n_components = 12 + rng = np.random.RandomState(0) + V = rng.randn(n_components, n_features) # random init V /= np.sum(V ** 2, axis=1)[:, np.newaxis] for algo in ('lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'): code = sparse_encode(X, V, algorithm=algo) - assert_equal(code.shape, (n_samples, n_atoms)) + assert_equal(code.shape, (n_samples, n_components)) def test_sparse_encode_error(): - n_atoms = 12 - V = rng.randn(n_atoms, n_features) # random init + n_components = 12 + rng = np.random.RandomState(0) + V = rng.randn(n_components, n_features) # random init V /= np.sum(V ** 2, axis=1)[:, np.newaxis] code = sparse_encode(X, V, alpha=0.001) assert_true(not np.all(code == 0)) assert_less(np.sqrt(np.sum((np.dot(code, V) - X) ** 2)), 0.1) +def test_sparse_encode_error_default_sparsity(): + rng = np.random.RandomState(0) + X = rng.randn(100, 64) + D = rng.randn(2, 64) + code = ignore_warnings(sparse_encode)(X, D, algorithm='omp', + n_nonzero_coefs=None) + assert_equal(code.shape, (100, 2)) + + +def test_unknown_method(): + n_components = 12 + rng = np.random.RandomState(0) + V = rng.randn(n_components, n_features) # random init + assert_raises(ValueError, sparse_encode, X, V, algorithm="") + + def test_sparse_coder_estimator(): - n_atoms = 12 - V = rng.randn(n_atoms, n_features) # random init + n_components = 12 + rng = np.random.RandomState(0) + V = rng.randn(n_components, n_features) # random init V /= np.sum(V ** 2, axis=1)[:, np.newaxis] code = SparseCoder(dictionary=V, transform_algorithm='lasso_lars', transform_alpha=0.001).transform(X) diff --git a/sklearn/decomposition/tests/test_factor_analysis.py b/sklearn/decomposition/tests/test_factor_analysis.py new file mode 100644 index 0000000000000..f1c7e2dab1090 --- /dev/null +++ b/sklearn/decomposition/tests/test_factor_analysis.py @@ -0,0 +1,83 @@ +# Author: Christian Osendorfer +# Alexandre Gramfort +# Licence: BSD3 + +import numpy as np + +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils import ConvergenceWarning +from sklearn.decomposition import FactorAnalysis + + +def test_factor_analysis(): + """Test FactorAnalysis ability to recover the data covariance structure + """ + rng = np.random.RandomState(0) + n_samples, n_features, n_components = 20, 5, 3 + + # Some random settings for the generative model + W = rng.randn(n_components, n_features) + # latent variable of dim 3, 20 of it + h = rng.randn(n_samples, n_components) + # using gamma to model different noise variance + # per component + noise = rng.gamma(1, size=n_features) * rng.randn(n_samples, n_features) + + # generate observations + # wlog, mean is 0 + X = np.dot(h, W) + noise + + assert_raises(ValueError, FactorAnalysis, svd_method='foo') + fa_fail = FactorAnalysis() + fa_fail.svd_method = 'foo' + assert_raises(ValueError, fa_fail.fit, X) + fas = [] + for method in ['randomized', 'lapack']: + fa = FactorAnalysis(n_components=n_components, svd_method=method) + fa.fit(X) + fas.append(fa) + + X_t = fa.transform(X) + assert_equal(X_t.shape, (n_samples, n_components)) + + assert_almost_equal(fa.loglike_[-1], fa.score_samples(X).sum()) + assert_almost_equal(fa.score_samples(X).mean(), fa.score(X)) + + diff = np.all(np.diff(fa.loglike_)) + assert_greater(diff, 0., 'Log likelihood dif not increase') + + # Sample Covariance + scov = np.cov(X, rowvar=0., bias=1.) + + # Model Covariance + mcov = fa.get_covariance() + diff = np.sum(np.abs(scov - mcov)) / W.size + assert_less(diff, 0.1, "Mean absolute difference is %f" % diff) + fa = FactorAnalysis(n_components=n_components, + noise_variance_init=np.ones(n_features)) + assert_raises(ValueError, fa.fit, X[:, :2]) + + f = lambda x, y: np.abs(getattr(x, y)) # sign will not be equal + fa1, fa2 = fas + for attr in ['loglike_', 'components_', 'noise_variance_']: + assert_almost_equal(f(fa1, attr), f(fa2, attr)) + + fa1.max_iter = 1 + fa1.verbose = True + assert_warns(ConvergenceWarning, fa1.fit, X) + + # Test get_covariance and get_precision with n_components == n_features + # with n_components < n_features and with n_components == 0 + for n_components in [0, 2, X.shape[1]]: + fa.n_components = n_components + fa.fit(X) + cov = fa.get_covariance() + precision = fa.get_precision() + assert_array_almost_equal(np.dot(cov, precision), + np.eye(X.shape[1]), 12) diff --git a/sklearn/decomposition/tests/test_fastica.py b/sklearn/decomposition/tests/test_fastica.py index 09a95082f0e3d..0bd7c83d1b5fc 100644 --- a/sklearn/decomposition/tests/test_fastica.py +++ b/sklearn/decomposition/tests/test_fastica.py @@ -1,18 +1,24 @@ """ Test the fastica algorithm. """ +import itertools import warnings -import numpy as np -from numpy.testing import assert_almost_equal -from nose.tools import assert_true +import numpy as np from scipy import stats -import itertools +from nose.tools import assert_raises + +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_warns -from .. import FastICA, fastica, PCA -from ..fastica_ import _gs_decorrelation +from sklearn.decomposition import FastICA, fastica, PCA +from sklearn.decomposition.fastica_ import _gs_decorrelation +from sklearn.externals.six import moves def center_and_norm(x, axis=-1): @@ -47,11 +53,12 @@ def test_gs(): assert_less((tmp[:5] ** 2).sum(), 1.e-10) -def test_fastica(add_noise=False): +def test_fastica_simple(add_noise=False): """ Test the FastICA algorithm on very simple data. """ - # scipy.stats uses the global RNG: rng = np.random.RandomState(0) + # scipy.stats uses the global RNG: + np.random.seed(0) n_samples = 1000 # Generate two sources: s1 = (2 * np.sin(np.linspace(0, 100, n_samples)) > 0) - 1 @@ -62,7 +69,7 @@ def test_fastica(add_noise=False): # Mixing angle phi = 0.6 - mixing = np.array([[np.cos(phi), np.sin(phi)], + mixing = np.array([[np.cos(phi), np.sin(phi)], [np.sin(phi), -np.cos(phi)]]) m = np.dot(mixing, s) @@ -71,16 +78,23 @@ def test_fastica(add_noise=False): center_and_norm(m) + # function as fun arg + def g_test(x): + return x ** 3, (3 * x ** 2).mean(axis=-1) + algos = ['parallel', 'deflation'] - nls = ['logcosh', 'exp', 'cube'] + nls = ['logcosh', 'exp', 'cube', g_test] whitening = [True, False] for algo, nl, whiten in itertools.product(algos, nls, whitening): if whiten: k_, mixing_, s_ = fastica(m.T, fun=nl, algorithm=algo) + assert_raises(ValueError, fastica, m.T, fun=np.tanh, + algorithm=algo) else: X = PCA(n_components=2, whiten=True).fit_transform(m.T) - k_, mixing_, s_ = fastica(X, fun=nl, algorithm=algo, - whiten=False) + k_, mixing_, s_ = fastica(X, fun=nl, algorithm=algo, whiten=False) + assert_raises(ValueError, fastica, X, fun=np.tanh, + algorithm=algo) s_ = s_.T # Check that the mixing model described in the docstring holds: if whiten: @@ -96,7 +110,7 @@ def test_fastica(add_noise=False): s2_ *= np.sign(np.dot(s2_, s2)) # Check that we have estimated the original sources - if add_noise == False: + if not add_noise: assert_almost_equal(np.dot(s1_, s1) / n_samples, 1, decimal=2) assert_almost_equal(np.dot(s2_, s2) / n_samples, 1, decimal=2) else: @@ -104,25 +118,31 @@ def test_fastica(add_noise=False): assert_almost_equal(np.dot(s2_, s2) / n_samples, 1, decimal=1) # Test FastICA class + _, _, sources_fun = fastica(m.T, fun=nl, algorithm=algo, random_state=0) ica = FastICA(fun=nl, algorithm=algo, random_state=0) - ica.fit(m.T) - ica.get_mixing_matrix() - assert_true(ica.components_.shape == (2, 2)) - assert_true(ica.sources_.shape == (1000, 2)) + sources = ica.fit_transform(m.T) + assert_equal(ica.components_.shape, (2, 2)) + assert_equal(sources.shape, (1000, 2)) + + assert_array_almost_equal(sources_fun, sources) + assert_array_almost_equal(sources, ica.transform(m.T)) + + assert_equal(ica.mixing_.shape, (2, 2)) + + for fn in [np.tanh, "exp(-.5(x^2))"]: + ica = FastICA(fun=fn, algorithm=algo, random_state=0) + assert_raises(ValueError, ica.fit, m.T) + + assert_raises(TypeError, FastICA(fun=moves.xrange(10)).fit, m.T) def test_fastica_nowhiten(): m = [[0, 1], [1, 0]] - ica = FastICA(whiten=False, random_state=0) - ica.fit(m) - ica.get_mixing_matrix() # test for issue #697 - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always") - ica = FastICA(n_components=1, whiten=False, random_state=0) - ica.fit(m) # should raise warning - assert_true(len(w) == 1) # 1 warning should be raised + ica = FastICA(n_components=1, whiten=False, random_state=0) + assert_warns(UserWarning, ica.fit, m) + assert_true(hasattr(ica, 'mixing_')) def test_non_square_fastica(add_noise=False): @@ -164,11 +184,62 @@ def test_non_square_fastica(add_noise=False): s2_ *= np.sign(np.dot(s2_, s2)) # Check that we have estimated the original sources - if add_noise == False: + if not add_noise: assert_almost_equal(np.dot(s1_, s1) / n_samples, 1, decimal=3) assert_almost_equal(np.dot(s2_, s2) / n_samples, 1, decimal=3) +def test_fit_transform(): + """Test FastICA.fit_transform""" + rng = np.random.RandomState(0) + X = rng.random_sample((100, 10)) + for whiten, n_components in [[True, 5], [False, None]]: + n_components_ = (n_components if n_components is not None else + X.shape[1]) + + ica = FastICA(n_components=n_components, whiten=whiten, random_state=0) + Xt = ica.fit_transform(X) + assert_equal(ica.components_.shape, (n_components_, 10)) + assert_equal(Xt.shape, (100, n_components_)) + + ica = FastICA(n_components=n_components, whiten=whiten, random_state=0) + ica.fit(X) + assert_equal(ica.components_.shape, (n_components_, 10)) + Xt2 = ica.transform(X) + + assert_array_almost_equal(Xt, Xt2) + + +def test_inverse_transform(): + """Test FastICA.inverse_transform""" + n_features = 10 + n_samples = 100 + n1, n2 = 5, 10 + rng = np.random.RandomState(0) + X = rng.random_sample((n_samples, n_features)) + expected = {(True, n1): (n_features, n1), + (True, n2): (n_features, n2), + (False, n1): (n_features, n2), + (False, n2): (n_features, n2)} + for whiten in [True, False]: + for n_components in [n1, n2]: + n_components_ = (n_components if n_components is not None else + X.shape[1]) + ica = FastICA(n_components=n_components, random_state=rng, + whiten=whiten) + with warnings.catch_warnings(record=True): + # catch "n_components ignored" warning + Xt = ica.fit_transform(X) + expected_shape = expected[(whiten, n_components_)] + assert_equal(ica.mixing_.shape, expected_shape) + X2 = ica.inverse_transform(Xt) + assert_equal(X.shape, X2.shape) + + # reversibility test in non-reduction case + if n_components == X.shape[1]: + assert_array_almost_equal(X, X2) + + if __name__ == '__main__': import nose nose.run(argv=['', __file__]) diff --git a/sklearn/decomposition/tests/test_incremental_pca.py b/sklearn/decomposition/tests/test_incremental_pca.py new file mode 100644 index 0000000000000..db75dfe7f9960 --- /dev/null +++ b/sklearn/decomposition/tests/test_incremental_pca.py @@ -0,0 +1,224 @@ +"""Tests for Incremental PCA.""" +import numpy as np + +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_raises + +from sklearn import datasets +from sklearn.decomposition import PCA, IncrementalPCA + +iris = datasets.load_iris() + + +def test_incremental_pca(): + """Incremental PCA on dense arrays.""" + X = iris.data + batch_size = X.shape[0] // 3 + ipca = IncrementalPCA(n_components=2, batch_size=batch_size) + pca = PCA(n_components=2) + pca.fit_transform(X) + + X_transformed = ipca.fit_transform(X) + + np.testing.assert_equal(X_transformed.shape, (X.shape[0], 2)) + assert_almost_equal(ipca.explained_variance_ratio_.sum(), + pca.explained_variance_ratio_.sum(), 1) + + for n_components in [1, 2, X.shape[1]]: + ipca = IncrementalPCA(n_components, batch_size=batch_size) + ipca.fit(X) + cov = ipca.get_covariance() + precision = ipca.get_precision() + assert_array_almost_equal(np.dot(cov, precision), + np.eye(X.shape[1])) + + +def test_incremental_pca_check_projection(): + """Test that the projection of data is correct.""" + rng = np.random.RandomState(1999) + n, p = 100, 3 + X = rng.randn(n, p) * .1 + X[:10] += np.array([3, 4, 5]) + Xt = 0.1 * rng.randn(1, p) + np.array([3, 4, 5]) + + # Get the reconstruction of the generated data X + # Note that Xt has the same "components" as X, just separated + # This is what we want to ensure is recreated correctly + Yt = IncrementalPCA(n_components=2).fit(X).transform(Xt) + + # Normalize + Yt /= np.sqrt((Yt ** 2).sum()) + + # Make sure that the first element of Yt is ~1, this means + # the reconstruction worked as expected + assert_almost_equal(np.abs(Yt[0][0]), 1., 1) + + +def test_incremental_pca_inverse(): + """Test that the projection of data can be inverted.""" + rng = np.random.RandomState(1999) + n, p = 50, 3 + X = rng.randn(n, p) # spherical data + X[:, 1] *= .00001 # make middle component relatively small + X += [5, 4, 3] # make a large mean + + # same check that we can find the original data from the transformed + # signal (since the data is almost of rank n_components) + ipca = IncrementalPCA(n_components=2, batch_size=10).fit(X) + Y = ipca.transform(X) + Y_inverse = ipca.inverse_transform(Y) + assert_almost_equal(X, Y_inverse, decimal=3) + + +def test_incremental_pca_validation(): + """Test that n_components is >=1 and <= n_features.""" + X = [[0, 1], [1, 0]] + for n_components in [-1, 0, .99, 3]: + assert_raises(ValueError, IncrementalPCA(n_components, + batch_size=10).fit, X) + + +def test_incremental_pca_set_params(): + """Test that components_ sign is stable over batch sizes.""" + rng = np.random.RandomState(1999) + n_samples = 100 + n_features = 20 + X = rng.randn(n_samples, n_features) + X2 = rng.randn(n_samples, n_features) + X3 = rng.randn(n_samples, n_features) + ipca = IncrementalPCA(n_components=20) + ipca.fit(X) + # Decreasing number of components + ipca.set_params(n_components=10) + assert_raises(ValueError, ipca.partial_fit, X2) + # Increasing number of components + ipca.set_params(n_components=15) + assert_raises(ValueError, ipca.partial_fit, X3) + # Returning to original setting + ipca.set_params(n_components=20) + ipca.partial_fit(X) + + +def test_incremental_pca_num_features_change(): + """Test that changing n_components will raise an error.""" + rng = np.random.RandomState(1999) + n_samples = 100 + X = rng.randn(n_samples, 20) + X2 = rng.randn(n_samples, 50) + ipca = IncrementalPCA(n_components=None) + ipca.fit(X) + assert_raises(ValueError, ipca.partial_fit, X2) + + +def test_incremental_pca_batch_signs(): + """Test that components_ sign is stable over batch sizes.""" + rng = np.random.RandomState(1999) + n_samples = 100 + n_features = 3 + X = rng.randn(n_samples, n_features) + all_components = [] + batch_sizes = np.arange(10, 20) + for batch_size in batch_sizes: + ipca = IncrementalPCA(n_components=None, batch_size=batch_size).fit(X) + all_components.append(ipca.components_) + + for i, j in zip(all_components[:-1], all_components[1:]): + assert_almost_equal(np.sign(i), np.sign(j), decimal=6) + + +def test_incremental_pca_batch_values(): + """Test that components_ values are stable over batch sizes.""" + rng = np.random.RandomState(1999) + n_samples = 100 + n_features = 3 + X = rng.randn(n_samples, n_features) + all_components = [] + batch_sizes = np.arange(20, 40, 3) + for batch_size in batch_sizes: + ipca = IncrementalPCA(n_components=None, batch_size=batch_size).fit(X) + all_components.append(ipca.components_) + + for i, j in zip(all_components[:-1], all_components[1:]): + assert_almost_equal(i, j, decimal=1) + + +def test_incremental_pca_partial_fit(): + """Test that fit and partial_fit get equivalent results.""" + rng = np.random.RandomState(1999) + n, p = 50, 3 + X = rng.randn(n, p) # spherical data + X[:, 1] *= .00001 # make middle component relatively small + X += [5, 4, 3] # make a large mean + + # same check that we can find the original data from the transformed + # signal (since the data is almost of rank n_components) + batch_size = 10 + ipca = IncrementalPCA(n_components=2, batch_size=batch_size).fit(X) + pipca = IncrementalPCA(n_components=2, batch_size=batch_size) + # Add one to make sure endpoint is included + batch_itr = np.arange(0, n + 1, batch_size) + for i, j in zip(batch_itr[:-1], batch_itr[1:]): + pipca.partial_fit(X[i:j, :]) + assert_almost_equal(ipca.components_, pipca.components_, decimal=3) + + +def test_incremental_pca_against_pca_iris(): + """Test that IncrementalPCA and PCA are approximate (to a sign flip).""" + X = iris.data + + Y_pca = PCA(n_components=2).fit_transform(X) + Y_ipca = IncrementalPCA(n_components=2, batch_size=25).fit_transform(X) + + assert_almost_equal(np.abs(Y_pca), np.abs(Y_ipca), 1) + + +def test_incremental_pca_against_pca_random_data(): + """Test that IncrementalPCA and PCA are approximate (to a sign flip).""" + rng = np.random.RandomState(1999) + n_samples = 100 + n_features = 3 + X = rng.randn(n_samples, n_features) + 5 * rng.rand(1, n_features) + + Y_pca = PCA(n_components=3).fit_transform(X) + Y_ipca = IncrementalPCA(n_components=3, batch_size=25).fit_transform(X) + + assert_almost_equal(np.abs(Y_pca), np.abs(Y_ipca), 1) + + +def test_explained_variances(): + """Test that PCA and IncrementalPCA calculations match""" + X = datasets.make_low_rank_matrix(1000, 100, tail_strength=0., + effective_rank=10, random_state=1999) + prec = 3 + n_samples, n_features = X.shape + for nc in [None, 99]: + pca = PCA(n_components=nc).fit(X) + ipca = IncrementalPCA(n_components=nc, batch_size=100).fit(X) + assert_almost_equal(pca.explained_variance_, ipca.explained_variance_, + decimal=prec) + assert_almost_equal(pca.explained_variance_ratio_, + ipca.explained_variance_ratio_, decimal=prec) + assert_almost_equal(pca.noise_variance_, ipca.noise_variance_, + decimal=prec) + + +def test_whitening(): + """Test that PCA and IncrementalPCA transforms match to sign flip.""" + X = datasets.make_low_rank_matrix(1000, 10, tail_strength=0., + effective_rank=2, random_state=1999) + prec = 3 + n_samples, n_features = X.shape + for nc in [None, 9]: + pca = PCA(whiten=True, n_components=nc).fit(X) + ipca = IncrementalPCA(whiten=True, n_components=nc, + batch_size=250).fit(X) + + Xt_pca = pca.transform(X) + Xt_ipca = ipca.transform(X) + assert_almost_equal(np.abs(Xt_pca), np.abs(Xt_ipca), decimal=prec) + Xinv_ipca = ipca.inverse_transform(Xt_ipca) + Xinv_pca = pca.inverse_transform(Xt_pca) + assert_almost_equal(X, Xinv_ipca, decimal=prec) + assert_almost_equal(X, Xinv_pca, decimal=prec) + assert_almost_equal(Xinv_pca, Xinv_ipca, decimal=prec) diff --git a/sklearn/decomposition/tests/test_kernel_pca.py b/sklearn/decomposition/tests/test_kernel_pca.py index bf28241681445..a86c33a9e9937 100644 --- a/sklearn/decomposition/tests/test_kernel_pca.py +++ b/sklearn/decomposition/tests/test_kernel_pca.py @@ -1,14 +1,13 @@ import numpy as np import scipy.sparse as sp -from numpy.testing import assert_array_almost_equal -from nose.tools import assert_equal -from nose.tools import assert_raises +from sklearn.utils.testing import (assert_array_almost_equal, assert_less, + assert_equal, assert_not_equal, + assert_raises) from sklearn.decomposition import PCA, KernelPCA from sklearn.datasets import make_circles from sklearn.linear_model import Perceptron -from sklearn.utils.testing import assert_less from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.metrics.pairwise import rbf_kernel @@ -19,24 +18,38 @@ def test_kernel_pca(): X_fit = rng.random_sample((5, 4)) X_pred = rng.random_sample((2, 4)) + def histogram(x, y, **kwargs): + """Histogram kernel implemented as a callable.""" + assert_equal(kwargs, {}) # no kernel_params that we didn't ask for + return np.minimum(x, y).sum() + for eigen_solver in ("auto", "dense", "arpack"): - for kernel in ("linear", "rbf", "poly"): + for kernel in ("linear", "rbf", "poly", histogram): + # histogram kernel produces singular matrix inside linalg.solve + # XXX use a least-squares approximation? + inv = not callable(kernel) + # transform fit data kpca = KernelPCA(4, kernel=kernel, eigen_solver=eigen_solver, - fit_inverse_transform=True) + fit_inverse_transform=inv) X_fit_transformed = kpca.fit_transform(X_fit) X_fit_transformed2 = kpca.fit(X_fit).transform(X_fit) assert_array_almost_equal(np.abs(X_fit_transformed), np.abs(X_fit_transformed2)) + # non-regression test: previously, gamma would be 0 by default, + # forcing all eigenvalues to 0 under the poly kernel + assert_not_equal(X_fit_transformed, []) + # transform new data X_pred_transformed = kpca.transform(X_pred) assert_equal(X_pred_transformed.shape[1], X_fit_transformed.shape[1]) # inverse transform - X_pred2 = kpca.inverse_transform(X_pred_transformed) - assert_equal(X_pred2.shape, X_pred.shape) + if inv: + X_pred2 = kpca.inverse_transform(X_pred_transformed) + assert_equal(X_pred2.shape, X_pred.shape) def test_invalid_parameters(): @@ -62,7 +75,7 @@ def test_kernel_pca_sparse(): # transform new data X_pred_transformed = kpca.transform(X_pred) assert_equal(X_pred_transformed.shape[1], - X_fit_transformed.shape[1]) + X_fit_transformed.shape[1]) # inverse transform #X_pred2 = kpca.inverse_transform(X_pred_transformed) @@ -96,6 +109,23 @@ def test_kernel_pca_n_components(): assert_equal(shape, (2, c)) +def test_remove_zero_eig(): + X = np.array([[1 - 1e-30, 1], [1, 1], [1, 1 - 1e-20]]) + + # n_components=None (default) => remove_zero_eig is True + kpca = KernelPCA() + Xt = kpca.fit_transform(X) + assert_equal(Xt.shape, (3, 0)) + + kpca = KernelPCA(n_components=2) + Xt = kpca.fit_transform(X) + assert_equal(Xt.shape, (3, 2)) + + kpca = KernelPCA(n_components=2, remove_zero_eig=True) + Xt = kpca.fit_transform(X) + assert_equal(Xt.shape, (3, 0)) + + def test_kernel_pca_precomputed(): rng = np.random.RandomState(0) X_fit = rng.random_sample((5, 4)) @@ -104,15 +134,16 @@ def test_kernel_pca_precomputed(): for eigen_solver in ("dense", "arpack"): X_kpca = KernelPCA(4, eigen_solver=eigen_solver).\ fit(X_fit).transform(X_pred) - X_kpca2 = KernelPCA(4, eigen_solver=eigen_solver, - kernel='precomputed').fit(np.dot(X_fit, - X_fit.T)).transform(np.dot(X_pred, X_fit.T)) + X_kpca2 = KernelPCA( + 4, eigen_solver=eigen_solver, kernel='precomputed').fit( + np.dot(X_fit, X_fit.T)).transform(np.dot(X_pred, X_fit.T)) - X_kpca_train = KernelPCA(4, eigen_solver=eigen_solver, - kernel='precomputed').fit_transform(np.dot(X_fit, X_fit.T)) - X_kpca_train2 = KernelPCA(4, eigen_solver=eigen_solver, - kernel='precomputed').fit(np.dot(X_fit, - X_fit.T)).transform(np.dot(X_fit, X_fit.T)) + X_kpca_train = KernelPCA( + 4, eigen_solver=eigen_solver, + kernel='precomputed').fit_transform(np.dot(X_fit, X_fit.T)) + X_kpca_train2 = KernelPCA( + 4, eigen_solver=eigen_solver, kernel='precomputed').fit( + np.dot(X_fit, X_fit.T)).transform(np.dot(X_fit, X_fit.T)) assert_array_almost_equal(np.abs(X_kpca), np.abs(X_kpca2)) @@ -135,7 +166,7 @@ def test_gridsearch_pipeline(): random_state=0) kpca = KernelPCA(kernel="rbf", n_components=2) pipeline = Pipeline([("kernel_pca", kpca), ("Perceptron", Perceptron())]) - param_grid = dict(kernel_pca__gamma=10. ** np.arange(-2, 2)) + param_grid = dict(kernel_pca__gamma=2. ** np.arange(-2, 2)) grid_search = GridSearchCV(pipeline, cv=3, param_grid=param_grid) grid_search.fit(X, y) assert_equal(grid_search.best_score_, 1) @@ -150,7 +181,7 @@ def test_gridsearch_pipeline_precomputed(): pipeline = Pipeline([("kernel_pca", kpca), ("Perceptron", Perceptron())]) param_grid = dict(Perceptron__n_iter=np.arange(1, 5)) grid_search = GridSearchCV(pipeline, cv=3, param_grid=param_grid) - X_kernel = rbf_kernel(X, gamma=10) + X_kernel = rbf_kernel(X, gamma=2.) grid_search.fit(X_kernel, y) assert_equal(grid_search.best_score_, 1) @@ -170,7 +201,7 @@ def test_nested_circles(): # and the gamma value has to be updated, the Kernel PCA example will # have to be updated too. kpca = KernelPCA(kernel="rbf", n_components=2, - fit_inverse_transform=True, gamma=10.) + fit_inverse_transform=True, gamma=2.) X_kpca = kpca.fit_transform(X) # The data is perfectly linearly separable in that space diff --git a/sklearn/decomposition/tests/test_nmf.py b/sklearn/decomposition/tests/test_nmf.py index 6a4830ca80443..8476e7e313007 100644 --- a/sklearn/decomposition/tests/test_nmf.py +++ b/sklearn/decomposition/tests/test_nmf.py @@ -1,9 +1,14 @@ import numpy as np +from scipy import linalg from sklearn.decomposition import nmf -from nose.tools import assert_true, assert_false, raises -from numpy.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import raises +from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_less + random_state = np.random.mtrand.RandomState(0) @@ -18,7 +23,7 @@ def test_initialize_nn_output(): """Test that NNDSVD does not return negative values""" data = np.abs(random_state.randn(10, 10)) for var in (None, 'a', 'ar'): - W, H = nmf._initialize_nmf(data, 10) + W, H = nmf._initialize_nmf(data, 10, random_state=0) assert_false((W < 0).any() or (H < 0).any()) @@ -30,8 +35,8 @@ def test_initialize_close(): """ A = np.abs(random_state.randn(10, 10)) W, H = nmf._initialize_nmf(A, 10) - error = np.linalg.norm(np.dot(W, H) - A) - sdev = np.linalg.norm(A - A.mean()) + error = linalg.norm(np.dot(W, H) - A) + sdev = linalg.norm(A - A.mean()) assert_true(error <= sdev) @@ -44,7 +49,7 @@ def test_initialize_variants(): data = np.abs(random_state.randn(10, 10)) W0, H0 = nmf._initialize_nmf(data, 10, variant=None) Wa, Ha = nmf._initialize_nmf(data, 10, variant='a') - War, Har = nmf._initialize_nmf(data, 10, variant='ar') + War, Har = nmf._initialize_nmf(data, 10, variant='ar', random_state=0) for ref, evl in ((W0, Wa), (W0, War), (H0, Ha), (H0, Har)): assert_true(np.allclose(evl[ref != 0], ref[ref != 0])) @@ -54,16 +59,17 @@ def test_initialize_variants(): def test_projgrad_nmf_fit_nn_input(): """Test model fit behaviour on negative input""" A = -np.ones((2, 2)) - m = nmf.ProjectedGradientNMF(n_components=2, init=None) + m = nmf.ProjectedGradientNMF(n_components=2, init=None, random_state=0) m.fit(A) def test_projgrad_nmf_fit_nn_output(): """Test that the decomposition does not contain negative values""" - A = np.c_[5 * np.ones(5) - xrange(1, 6), - 5 * np.ones(5) + xrange(1, 6)] + A = np.c_[5 * np.ones(5) - np.arange(1, 6), + 5 * np.ones(5) + np.arange(1, 6)] for init in (None, 'nndsvd', 'nndsvda', 'nndsvdar'): - model = nmf.ProjectedGradientNMF(n_components=2, init=init) + model = nmf.ProjectedGradientNMF(n_components=2, init=init, + random_state=0) transf = model.fit_transform(A) assert_false((model.components_ < 0).any() or (transf < 0).any()) @@ -71,27 +77,21 @@ def test_projgrad_nmf_fit_nn_output(): def test_projgrad_nmf_fit_close(): """Test that the fit is not too far away""" - assert_true(nmf.ProjectedGradientNMF(5, init='nndsvda').fit(np.abs( - random_state.randn(6, 5))).reconstruction_err_ < 0.05) - - -@raises(ValueError) -def test_nls_nn_input(): - """Test NLS solver's behaviour on negative input""" - A = np.ones((2, 2)) - nmf._nls_subproblem(A, A, -A, 0.001, 20) + pnmf = nmf.ProjectedGradientNMF(5, init='nndsvda', random_state=0) + X = np.abs(random_state.randn(6, 5)) + assert_less(pnmf.fit(X).reconstruction_err_, 0.05) def test_nls_nn_output(): """Test that NLS solver doesn't return negative values""" - A = np.atleast_2d(range(1, 5)) + A = np.arange(1, 5).reshape(1, -1) Ap, _, _ = nmf._nls_subproblem(np.dot(A.T, -A), A.T, A, 0.001, 100) assert_false((Ap < 0).any()) def test_nls_close(): """Test that the NLS results should be close""" - A = np.atleast_2d(range(1, 5)) + A = np.arange(1, 5).reshape(1, -1) Ap, _, _ = nmf._nls_subproblem(np.dot(A.T, A), A.T, np.zeros_like(A), 0.001, 100) assert_true((np.abs(Ap - A) < 0.01).all()) @@ -103,7 +103,7 @@ def test_projgrad_nmf_transform(): (transform uses scipy.optimize.nnls for now) """ A = np.abs(random_state.randn(6, 5)) - m = nmf.ProjectedGradientNMF(n_components=5, init='nndsvd') + m = nmf.ProjectedGradientNMF(n_components=5, init='nndsvd', random_state=0) transf = m.fit_transform(A) assert_true(np.allclose(transf, m.transform(A), atol=1e-2, rtol=0)) @@ -111,40 +111,68 @@ def test_projgrad_nmf_transform(): def test_n_components_greater_n_features(): """Smoke test for the case of more components than features.""" A = np.abs(random_state.randn(30, 10)) - nmf.ProjectedGradientNMF(n_components=15, sparseness='data').fit(A) + nmf.ProjectedGradientNMF(n_components=15, sparseness='data', + random_state=0).fit(A) def test_projgrad_nmf_sparseness(): """Test sparseness - Test that sparsity contraints actually increase sparseness in the + Test that sparsity constraints actually increase sparseness in the part where they are applied. """ - A = np.abs(random_state.randn(10, 10)) - m = nmf.ProjectedGradientNMF(n_components=5).fit(A) - data_sp = nmf.ProjectedGradientNMF(n_components=5, - sparseness='data').fit(A).data_sparseness_ - comp_sp = nmf.ProjectedGradientNMF(n_components=5, - sparseness='components').fit(A).comp_sparseness_ + m = nmf.ProjectedGradientNMF(n_components=5, random_state=0).fit(A) + data_sp = nmf.ProjectedGradientNMF(n_components=5, sparseness='data', + random_state=0).fit(A).data_sparseness_ + comp_sp = nmf.ProjectedGradientNMF(n_components=5, sparseness='components', + random_state=0).fit(A).comp_sparseness_ assert_greater(data_sp, m.data_sparseness_) assert_greater(comp_sp, m.comp_sparseness_) def test_sparse_input(): """Test that sparse matrices are accepted as input""" - from scipy.sparse import csr_matrix + from scipy.sparse import csc_matrix A = np.abs(random_state.randn(10, 10)) A[:, 2 * np.arange(5)] = 0 T1 = nmf.ProjectedGradientNMF(n_components=5, init='random', random_state=999).fit_transform(A) - A = csr_matrix(A) - T2 = nmf.ProjectedGradientNMF(n_components=5, init='random', - random_state=999).fit_transform(A) + A_sparse = csc_matrix(A) + pg_nmf = nmf.ProjectedGradientNMF(n_components=5, init='random', + random_state=999) + T2 = pg_nmf.fit_transform(A_sparse) + assert_array_almost_equal(pg_nmf.reconstruction_err_, + linalg.norm(A - np.dot(T2, pg_nmf.components_), + 'fro')) assert_array_almost_equal(T1, T2) + # same with sparseness + + T2 = nmf.ProjectedGradientNMF( + n_components=5, init='random', sparseness='data', + random_state=999).fit_transform(A_sparse) + T1 = nmf.ProjectedGradientNMF( + n_components=5, init='random', sparseness='data', + random_state=999).fit_transform(A) + + +def test_sparse_transform(): + """Test that transform works on sparse data. Issue #2124""" + from scipy.sparse import csc_matrix + + A = np.abs(random_state.randn(5, 4)) + A[A > 1.0] = 0 + A = csc_matrix(A) + + model = nmf.NMF() + A_fit_tr = model.fit_transform(A) + A_tr = model.transform(A) + # This solver seems pretty inconsistent + assert_array_almost_equal(A_fit_tr, A_tr, decimal=2) + if __name__ == '__main__': import nose diff --git a/sklearn/decomposition/tests/test_pca.py b/sklearn/decomposition/tests/test_pca.py index e4f148fe3662e..b31ca4d680404 100644 --- a/sklearn/decomposition/tests/test_pca.py +++ b/sklearn/decomposition/tests/test_pca.py @@ -1,18 +1,17 @@ import numpy as np -from nose.tools import assert_true -from nose.tools import assert_equal -from scipy.sparse import csr_matrix -from numpy.testing import assert_almost_equal, assert_array_almost_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_raises -from sklearn.utils.testing import assert_less, assert_greater - -from ... import datasets -from .. import PCA -from .. import ProbabilisticPCA -from .. import RandomizedPCA -from ..pca import _assess_dimension_ -from ..pca import _infer_dimension_ +from sklearn import datasets +from sklearn.decomposition import PCA +from sklearn.decomposition import RandomizedPCA +from sklearn.decomposition.pca import _assess_dimension_ +from sklearn.decomposition.pca import _infer_dimension_ iris = datasets.load_iris() @@ -36,6 +35,16 @@ def test_pca(): assert_array_almost_equal(X_r, X_r2) + # Test get_covariance and get_precision with n_components == n_features + # with n_components < n_features and with n_components == 0 + for n_components in [0, 2, X.shape[1]]: + pca.n_components = n_components + pca.fit(X) + cov = pca.get_covariance() + precision = pca.get_precision() + assert_array_almost_equal(np.dot(cov, precision), + np.eye(X.shape[1]), 12) + def test_whitening(): """Check that PCA output has unit-variance""" @@ -58,26 +67,54 @@ def test_whitening(): # the component-wise variance is thus highly varying: assert_almost_equal(X.std(axis=0).std(), 43.9, 1) - # whiten the data while projecting to the lower dim subspace - pca = PCA(n_components=n_components, whiten=True) + for this_PCA, copy in [(x, y) for x in (PCA, RandomizedPCA) + for y in (True, False)]: + # whiten the data while projecting to the lower dim subspace + X_ = X.copy() # make sure we keep an original across iterations. + pca = this_PCA(n_components=n_components, whiten=True, copy=copy) + # test fit_transform + X_whitened = pca.fit_transform(X_.copy()) + assert_equal(X_whitened.shape, (n_samples, n_components)) + X_whitened2 = pca.transform(X_) + assert_array_almost_equal(X_whitened, X_whitened2) - # test fit_transform - X_whitened = pca.fit_transform(X) - assert_equal(X_whitened.shape, (n_samples, n_components)) - X_whitened2 = pca.transform(X) - assert_array_almost_equal(X_whitened, X_whitened2) + assert_almost_equal(X_whitened.std(axis=0), np.ones(n_components)) + assert_almost_equal(X_whitened.mean(axis=0), np.zeros(n_components)) - # all output component have unit variances - assert_almost_equal(X_whitened.std(axis=0), np.ones(n_components)) + X_ = X.copy() + pca = this_PCA(n_components=n_components, whiten=False, + copy=copy).fit(X_) + X_unwhitened = pca.transform(X_) + assert_equal(X_unwhitened.shape, (n_samples, n_components)) - # is possible to project on the low dim space without scaling by the - # singular values - pca = PCA(n_components=n_components, whiten=False).fit(X) - X_unwhitened = pca.transform(X) - assert_equal(X_unwhitened.shape, (n_samples, n_components)) + # in that case the output components still have varying variances + assert_almost_equal(X_unwhitened.std(axis=0).std(), 74.1, 1) + # we always center, so no test for non-centering. - # in that case the output components still have varying variances - assert_almost_equal(X_unwhitened.std(axis=0).std(), 74.1, 1) + +def test_explained_variance(): + """Check that PCA output has unit-variance""" + rng = np.random.RandomState(0) + n_samples = 100 + n_features = 80 + + X = rng.randn(n_samples, n_features) + + pca = PCA(n_components=2).fit(X) + rpca = RandomizedPCA(n_components=2, random_state=42).fit(X) + assert_array_almost_equal(pca.explained_variance_, + rpca.explained_variance_, 1) + assert_array_almost_equal(pca.explained_variance_ratio_, + rpca.explained_variance_ratio_, 3) + + # compare to empirical variances + X_pca = pca.transform(X) + assert_array_almost_equal(pca.explained_variance_, + np.var(X_pca, axis=0)) + + X_rpca = rpca.transform(X) + assert_array_almost_equal(rpca.explained_variance_, + np.var(X_rpca, axis=0)) def test_pca_check_projection(): @@ -114,8 +151,13 @@ def test_pca_inverse(): pca.fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) - relative_max_delta = (np.abs(X - Y_inverse) / np.abs(X).mean()).max() - assert_almost_equal(relative_max_delta, 0.11, decimal=2) + assert_almost_equal(X, Y_inverse, decimal=3) + + +def test_pca_validation(): + X = [[0, 1], [1, 0]] + for n_components in [-1, 3]: + assert_raises(ValueError, PCA(n_components).fit, X) def test_randomized_pca_check_projection(): @@ -135,8 +177,8 @@ def test_randomized_pca_check_projection(): def test_randomized_pca_check_list(): """Test that the projection by RandomizedPCA on list data is correct""" X = [[1.0, 0.0], [0.0, 1.0]] - X_transformed = RandomizedPCA(n_components=1, random_state=0 - ).fit(X).transform(X) + X_transformed = RandomizedPCA(n_components=1, + random_state=0).fit(X).transform(X) assert_equal(X_transformed.shape, (2, 1)) assert_almost_equal(X_transformed.mean(), 0.00, 2) assert_almost_equal(X_transformed.std(), 0.71, 2) @@ -166,50 +208,6 @@ def test_randomized_pca_inverse(): assert_almost_equal(relative_max_delta, 0.11, decimal=2) -def test_sparse_randomized_pca_check_projection(): - """Test that the projection by RandomizedPCA on sparse data is correct""" - rng = np.random.RandomState(0) - n, p = 100, 3 - X = rng.randn(n, p) * .1 - X[:10] += np.array([3, 4, 5]) - X = csr_matrix(X) - Xt = 0.1 * rng.randn(1, p) + np.array([3, 4, 5]) - Xt = csr_matrix(Xt) - - Yt = RandomizedPCA(n_components=2, random_state=0).fit(X).transform(Xt) - Yt /= np.sqrt((Yt ** 2).sum()) - - np.testing.assert_almost_equal(np.abs(Yt[0][0]), 1., 1) - - -def test_sparse_randomized_pca_inverse(): - """Test that RandomizedPCA is inversible on sparse data""" - rng = np.random.RandomState(0) - n, p = 50, 3 - X = rng.randn(n, p) # spherical data - X[:, 1] *= .00001 # make middle component relatively small - # no large means because the sparse version of randomized pca does not do - # centering to avoid breaking the sparsity - X = csr_matrix(X) - - # same check that we can find the original data from the transformed signal - # (since the data is almost of rank n_components) - pca = RandomizedPCA(n_components=2, random_state=0).fit(X) - Y = pca.transform(X) - Y_inverse = pca.inverse_transform(Y) - assert_almost_equal(X.todense(), Y_inverse, decimal=2) - - # same as above with whitening (approximate reconstruction) - pca = RandomizedPCA(n_components=2, whiten=True, - random_state=0).fit(X) - Y = pca.transform(X) - Y_inverse = pca.inverse_transform(Y) - relative_max_delta = (np.abs(X.todense() - Y_inverse) - / np.abs(X).mean()).max() - # XXX: this does not seam to work as expected: - assert_almost_equal(relative_max_delta, 0.91, decimal=2) - - def test_pca_dim(): """Check automated dimensionality setting""" rng = np.random.RandomState(0) @@ -217,7 +215,8 @@ def test_pca_dim(): X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5, 1, 2]) pca = PCA(n_components='mle').fit(X) - assert_equal(pca.n_components, 1) + assert_equal(pca.n_components, 'mle') + assert_equal(pca.n_components_, 1) def test_infer_dim_1(): @@ -227,8 +226,8 @@ def test_infer_dim_1(): """ n, p = 1000, 5 rng = np.random.RandomState(0) - X = rng.randn(n, p) * .1 + rng.randn(n, 1) * np.array([3, 4, 5, 1, 2]) \ - + np.array([1, 0, 7, 4, 6]) + X = (rng.randn(n, p) * .1 + rng.randn(n, 1) * np.array([3, 4, 5, 1, 2]) + + np.array([1, 0, 7, 4, 6])) pca = PCA(n_components=p) pca.fit(X) spect = pca.explained_variance_ @@ -274,60 +273,54 @@ def test_infer_dim_by_explained_variance(): X = iris.data pca = PCA(n_components=0.95) pca.fit(X) - assert_equal(pca.n_components, 2) + assert_equal(pca.n_components, 0.95) + assert_equal(pca.n_components_, 2) pca = PCA(n_components=0.01) pca.fit(X) - assert_equal(pca.n_components, 1) + assert_equal(pca.n_components, 0.01) + assert_equal(pca.n_components_, 1) rng = np.random.RandomState(0) # more features than samples X = rng.rand(5, 20) pca = PCA(n_components=.5).fit(X) - assert_equal(pca.n_components, 2) + assert_equal(pca.n_components, 0.5) + assert_equal(pca.n_components_, 2) -def test_probabilistic_pca_1(): - """Test that probabilistic PCA yields a reasonable score""" +def test_pca_score(): + """Test that probabilistic PCA scoring yields a reasonable score""" n, p = 1000, 3 rng = np.random.RandomState(0) X = rng.randn(n, p) * .1 + np.array([3, 4, 5]) - ppca = ProbabilisticPCA(n_components=2) - ppca.fit(X) - ll1 = ppca.score(X) + pca = PCA(n_components=2) + pca.fit(X) + ll1 = pca.score(X) h = -0.5 * np.log(2 * np.pi * np.exp(1) * 0.1 ** 2) * p - np.testing.assert_almost_equal(ll1.mean() / h, 1, 0) + np.testing.assert_almost_equal(ll1 / h, 1, 0) -def test_probabilistic_pca_2(): +def test_pca_score2(): """Test that probabilistic PCA correctly separated different datasets""" n, p = 100, 3 rng = np.random.RandomState(0) X = rng.randn(n, p) * .1 + np.array([3, 4, 5]) - ppca = ProbabilisticPCA(n_components=2) - ppca.fit(X) - ll1 = ppca.score(X) - ll2 = ppca.score(rng.randn(n, p) * .2 + np.array([3, 4, 5])) - assert_greater(ll1.mean(), ll2.mean()) - + pca = PCA(n_components=2) + pca.fit(X) + ll1 = pca.score(X) + ll2 = pca.score(rng.randn(n, p) * .2 + np.array([3, 4, 5])) + assert_greater(ll1, ll2) -def test_probabilistic_pca_3(): - """The homoscedastic model should work slightly worth - than the heteroscedastic one in over-fitting condition - """ - n, p = 100, 3 - rng = np.random.RandomState(0) - X = rng.randn(n, p) * .1 + np.array([3, 4, 5]) - ppca = ProbabilisticPCA(n_components=2) - ppca.fit(X) - ll1 = ppca.score(X) - ppca.fit(X, homoscedastic=False) - ll2 = ppca.score(X) - assert_less(ll1.mean(), ll2.mean()) + # Test that it gives the same scores if whiten=True + pca = PCA(n_components=2, whiten=True) + pca.fit(X) + ll2 = pca.score(X) + assert_almost_equal(ll1, ll2) -def test_probabilistic_pca_4(): - """Check that ppca select the right model""" +def test_pca_score3(): + """Check that probabilistic PCA selects the right model""" n, p = 200, 3 rng = np.random.RandomState(0) Xl = (rng.randn(n, p) + rng.randn(n, 1) * np.array([3, 4, 5]) @@ -336,9 +329,9 @@ def test_probabilistic_pca_4(): + np.array([1, 0, 7])) ll = np.zeros(p) for k in range(p): - ppca = ProbabilisticPCA(n_components=k) - ppca.fit(Xl) - ll[k] = ppca.score(Xt).mean() + pca = PCA(n_components=k) + pca.fit(Xl) + ll[k] = pca.score(Xt) assert_true(ll.argmax() == 1) diff --git a/sklearn/decomposition/tests/test_sparse_pca.py b/sklearn/decomposition/tests/test_sparse_pca.py index e694a2ff74f8a..96cee5a690331 100644 --- a/sklearn/decomposition/tests/test_sparse_pca.py +++ b/sklearn/decomposition/tests/test_sparse_pca.py @@ -1,28 +1,32 @@ # Author: Vlad Niculae -# License: BSD +# License: BSD 3 clause import sys import numpy as np -from numpy.testing import assert_array_almost_equal, assert_equal -from nose import SkipTest -from nose.tools import assert_true, assert_false +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import SkipTest +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import if_not_mac_os -from .. import SparsePCA, MiniBatchSparsePCA -from ...utils import check_random_state +from sklearn.decomposition import SparsePCA, MiniBatchSparsePCA +from sklearn.utils import check_random_state -def generate_toy_data(n_atoms, n_samples, image_size, random_state=None): +def generate_toy_data(n_components, n_samples, image_size, random_state=None): n_features = image_size[0] * image_size[1] rng = check_random_state(random_state) - U = rng.randn(n_samples, n_atoms) - V = rng.randn(n_atoms, n_features) + U = rng.randn(n_samples, n_components) + V = rng.randn(n_components, n_features) centers = [(3, 3), (6, 7), (8, 1)] sz = [1, 2, 1] - for k in range(n_atoms): + for k in range(n_components): img = np.zeros(image_size) xmin, xmax = centers[k][0] - sz[k], centers[k][0] + sz[k] ymin, ymax = centers[k][1] - sz[k], centers[k][1] + sz[k] @@ -59,24 +63,7 @@ def test_fit_transform(): spca_lars = SparsePCA(n_components=3, method='lars', alpha=alpha, random_state=0) spca_lars.fit(Y) - U1 = spca_lars.transform(Y) - # Test multiple CPUs - if sys.platform == 'win32': # fake parallelism for win32 - import sklearn.externals.joblib.parallel as joblib_par - _mp = joblib_par.multiprocessing - joblib_par.multiprocessing = None - try: - spca = SparsePCA(n_components=3, n_jobs=2, random_state=0, - alpha=alpha).fit(Y) - U2 = spca.transform(Y) - finally: - joblib_par.multiprocessing = _mp - else: # we can efficiently use parallelism - spca = SparsePCA(n_components=3, n_jobs=2, method='lars', alpha=alpha, - random_state=0).fit(Y) - U2 = spca.transform(Y) - assert_true(not np.all(spca_lars.components_ == 0)) - assert_array_almost_equal(U1, U2) + # Test that CD gives similar results spca_lasso = SparsePCA(n_components=3, method='cd', random_state=0, alpha=alpha) @@ -84,6 +71,23 @@ def test_fit_transform(): assert_array_almost_equal(spca_lasso.components_, spca_lars.components_) +@if_not_mac_os() +def test_fit_transform_parallel(): + alpha = 1 + rng = np.random.RandomState(0) + Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array + spca_lars = SparsePCA(n_components=3, method='lars', alpha=alpha, + random_state=0) + spca_lars.fit(Y) + U1 = spca_lars.transform(Y) + # Test multiple CPUs + spca = SparsePCA(n_components=3, n_jobs=2, method='lars', alpha=alpha, + random_state=0).fit(Y) + U2 = spca.transform(Y) + assert_true(not np.all(spca_lars.components_ == 0)) + assert_array_almost_equal(U1, U2) + + def test_transform_nan(): """ Test that SparsePCA won't return NaN when there is 0 feature in all @@ -114,7 +118,7 @@ def test_initialization(): model = SparsePCA(n_components=3, U_init=U_init, V_init=V_init, max_iter=0, random_state=rng) model.fit(rng.randn(5, 4)) - assert_equal(model.components_, V_init) + assert_array_equal(model.components_, V_init) def test_mini_batch_correct_shapes(): @@ -132,7 +136,7 @@ def test_mini_batch_correct_shapes(): def test_mini_batch_fit_transform(): - raise SkipTest + raise SkipTest("skipping mini_batch_fit_transform.") alpha = 1 rng = np.random.RandomState(0) Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array diff --git a/sklearn/decomposition/tests/test_truncated_svd.py b/sklearn/decomposition/tests/test_truncated_svd.py new file mode 100644 index 0000000000000..c9e2c2e2c3f84 --- /dev/null +++ b/sklearn/decomposition/tests/test_truncated_svd.py @@ -0,0 +1,164 @@ +"""Test truncated SVD transformer.""" + +import numpy as np +import scipy.sparse as sp + +from sklearn.decomposition import TruncatedSVD +from sklearn.utils import check_random_state +from sklearn.utils.testing import (assert_array_almost_equal, assert_equal, + assert_raises, assert_greater, + assert_array_less) + + +# Make an X that looks somewhat like a small tf-idf matrix. +# XXX newer versions of SciPy have scipy.sparse.rand for this. +shape = 60, 55 +n_samples, n_features = shape +rng = check_random_state(42) +X = rng.randint(-100, 20, np.product(shape)).reshape(shape) +X = sp.csr_matrix(np.maximum(X, 0), dtype=np.float64) +X.data[:] = 1 + np.log(X.data) +Xdense = X.A + + +def test_algorithms(): + svd_a = TruncatedSVD(30, algorithm="arpack") + svd_r = TruncatedSVD(30, algorithm="randomized", random_state=42) + + Xa = svd_a.fit_transform(X)[:, :6] + Xr = svd_r.fit_transform(X)[:, :6] + assert_array_almost_equal(Xa, Xr) + + comp_a = np.abs(svd_a.components_) + comp_r = np.abs(svd_r.components_) + # All elements are equal, but some elements are more equal than others. + assert_array_almost_equal(comp_a[:9], comp_r[:9]) + assert_array_almost_equal(comp_a[9:], comp_r[9:], decimal=3) + + +def test_attributes(): + for n_components in (10, 25, 41): + tsvd = TruncatedSVD(n_components).fit(X) + assert_equal(tsvd.n_components, n_components) + assert_equal(tsvd.components_.shape, (n_components, n_features)) + + +def test_too_many_components(): + for algorithm in ["arpack", "randomized"]: + for n_components in (n_features, n_features+1): + tsvd = TruncatedSVD(n_components=n_components, algorithm=algorithm) + assert_raises(ValueError, tsvd.fit, X) + + +def test_sparse_formats(): + for fmt in ("array", "csr", "csc", "coo", "lil"): + Xfmt = Xdense if fmt == "dense" else getattr(X, "to" + fmt)() + tsvd = TruncatedSVD(n_components=11) + Xtrans = tsvd.fit_transform(Xfmt) + assert_equal(Xtrans.shape, (n_samples, 11)) + Xtrans = tsvd.transform(Xfmt) + assert_equal(Xtrans.shape, (n_samples, 11)) + + +def test_inverse_transform(): + for algo in ("arpack", "randomized"): + # We need a lot of components for the reconstruction to be "almost + # equal" in all positions. XXX Test means or sums instead? + tsvd = TruncatedSVD(n_components=52, random_state=42) + Xt = tsvd.fit_transform(X) + Xinv = tsvd.inverse_transform(Xt) + assert_array_almost_equal(Xinv, Xdense, decimal=1) + + +def test_integers(): + Xint = X.astype(np.int64) + tsvd = TruncatedSVD(n_components=6) + Xtrans = tsvd.fit_transform(Xint) + assert_equal(Xtrans.shape, (n_samples, tsvd.n_components)) + + +def test_explained_variance(): + # Test sparse data + svd_a_10_sp = TruncatedSVD(10, algorithm="arpack") + svd_r_10_sp = TruncatedSVD(10, algorithm="randomized", random_state=42) + svd_a_20_sp = TruncatedSVD(20, algorithm="arpack") + svd_r_20_sp = TruncatedSVD(20, algorithm="randomized", random_state=42) + X_trans_a_10_sp = svd_a_10_sp.fit_transform(X) + X_trans_r_10_sp = svd_r_10_sp.fit_transform(X) + X_trans_a_20_sp = svd_a_20_sp.fit_transform(X) + X_trans_r_20_sp = svd_r_20_sp.fit_transform(X) + + # Test dense data + svd_a_10_de = TruncatedSVD(10, algorithm="arpack") + svd_r_10_de = TruncatedSVD(10, algorithm="randomized", random_state=42) + svd_a_20_de = TruncatedSVD(20, algorithm="arpack") + svd_r_20_de = TruncatedSVD(20, algorithm="randomized", random_state=42) + X_trans_a_10_de = svd_a_10_de.fit_transform(X.toarray()) + X_trans_r_10_de = svd_r_10_de.fit_transform(X.toarray()) + X_trans_a_20_de = svd_a_20_de.fit_transform(X.toarray()) + X_trans_r_20_de = svd_r_20_de.fit_transform(X.toarray()) + + # helper arrays for tests below + svds = (svd_a_10_sp, svd_r_10_sp, svd_a_20_sp, svd_r_20_sp, svd_a_10_de, + svd_r_10_de, svd_a_20_de, svd_r_20_de) + svds_trans = ( + (svd_a_10_sp, X_trans_a_10_sp), + (svd_r_10_sp, X_trans_r_10_sp), + (svd_a_20_sp, X_trans_a_20_sp), + (svd_r_20_sp, X_trans_r_20_sp), + (svd_a_10_de, X_trans_a_10_de), + (svd_r_10_de, X_trans_r_10_de), + (svd_a_20_de, X_trans_a_20_de), + (svd_r_20_de, X_trans_r_20_de), + ) + svds_10_v_20 = ( + (svd_a_10_sp, svd_a_20_sp), + (svd_r_10_sp, svd_r_20_sp), + (svd_a_10_de, svd_a_20_de), + (svd_r_10_de, svd_r_20_de), + ) + svds_sparse_v_dense = ( + (svd_a_10_sp, svd_a_10_de), + (svd_a_20_sp, svd_a_20_de), + (svd_r_10_sp, svd_r_10_de), + (svd_r_20_sp, svd_r_20_de), + ) + + # Assert the 1st component is equal + for svd_10, svd_20 in svds_10_v_20: + assert_array_almost_equal( + svd_10.explained_variance_ratio_, + svd_20.explained_variance_ratio_[:10], + decimal=5, + ) + + # Assert that 20 components has higher explained variance than 10 + for svd_10, svd_20 in svds_10_v_20: + assert_greater( + svd_20.explained_variance_ratio_.sum(), + svd_10.explained_variance_ratio_.sum(), + ) + + # Assert that all the values are greater than 0 + for svd in svds: + assert_array_less(0.0, svd.explained_variance_ratio_) + + # Assert that total explained variance is less than 1 + for svd in svds: + assert_array_less(svd.explained_variance_ratio_.sum(), 1.0) + + # Compare sparse vs. dense + for svd_sparse, svd_dense in svds_sparse_v_dense: + assert_array_almost_equal(svd_sparse.explained_variance_ratio_, + svd_dense.explained_variance_ratio_) + + # Test that explained_variance is correct + for svd, transformed in svds_trans: + total_variance = np.var(X.toarray(), axis=0).sum() + variances = np.var(transformed, axis=0) + true_explained_variance_ratio = variances / total_variance + + assert_array_almost_equal( + svd.explained_variance_ratio_, + true_explained_variance_ratio, + ) diff --git a/sklearn/decomposition/truncated_svd.py b/sklearn/decomposition/truncated_svd.py new file mode 100644 index 0000000000000..3b2033204e505 --- /dev/null +++ b/sklearn/decomposition/truncated_svd.py @@ -0,0 +1,217 @@ +"""Truncated SVD for sparse matrices, aka latent semantic analysis (LSA). +""" + +# Author: Lars Buitinck +# Olivier Grisel +# Michael Becker +# License: 3-clause BSD. + +import numpy as np +import scipy.sparse as sp + +try: + from scipy.sparse.linalg import svds +except ImportError: + from ..utils.arpack import svds + +from ..base import BaseEstimator, TransformerMixin +from ..utils import check_array, as_float_array, check_random_state +from ..utils.extmath import randomized_svd, safe_sparse_dot, svd_flip +from ..utils.sparsefuncs import mean_variance_axis + +__all__ = ["TruncatedSVD"] + + +class TruncatedSVD(BaseEstimator, TransformerMixin): + """Dimensionality reduction using truncated SVD (aka LSA). + + This transformer performs linear dimensionality reduction by means of + truncated singular value decomposition (SVD). It is very similar to PCA, + but operates on sample vectors directly, instead of on a covariance matrix. + This means it can work with scipy.sparse matrices efficiently. + + In particular, truncated SVD works on term count/tf-idf matrices as + returned by the vectorizers in sklearn.feature_extraction.text. In that + context, it is known as latent semantic analysis (LSA). + + This estimator supports two algorithm: a fast randomized SVD solver, and + a "naive" algorithm that uses ARPACK as an eigensolver on (X * X.T) or + (X.T * X), whichever is more efficient. + + Parameters + ---------- + n_components : int, default = 2 + Desired dimensionality of output data. + Must be strictly less than the number of features. + The default value is useful for visualisation. For LSA, a value of + 100 is recommended. + + algorithm : string, default = "randomized" + SVD solver to use. Either "arpack" for the ARPACK wrapper in SciPy + (scipy.sparse.linalg.svds), or "randomized" for the randomized + algorithm due to Halko (2009). + + n_iter : int, optional + Number of iterations for randomized SVD solver. Not used by ARPACK. + + random_state : int or RandomState, optional + (Seed for) pseudo-random number generator. If not given, the + numpy.random singleton is used. + + tol : float, optional + Tolerance for ARPACK. 0 means machine precision. Ignored by randomized + SVD solver. + + Attributes + ---------- + components_ : array, shape (n_components, n_features) + + explained_variance_ratio_ : array, [n_components] + Percentage of variance explained by each of the selected components. + + explained_variance_ : array, [n_components] + The variance of the training samples transformed by a projection to + each component. + + Examples + -------- + >>> from sklearn.decomposition import TruncatedSVD + >>> from sklearn.random_projection import sparse_random_matrix + >>> X = sparse_random_matrix(100, 100, density=0.01, random_state=42) + >>> svd = TruncatedSVD(n_components=5, random_state=42) + >>> svd.fit(X) # doctest: +NORMALIZE_WHITESPACE + TruncatedSVD(algorithm='randomized', n_components=5, n_iter=5, + random_state=42, tol=0.0) + >>> print(svd.explained_variance_ratio_) # doctest: +ELLIPSIS + [ 0.07825... 0.05528... 0.05445... 0.04997... 0.04134...] + >>> print(svd.explained_variance_ratio_.sum()) # doctest: +ELLIPSIS + 0.27930... + + See also + -------- + PCA + RandomizedPCA + + References + ---------- + Finding structure with randomness: Stochastic algorithms for constructing + approximate matrix decompositions + Halko, et al., 2009 (arXiv:909) http://arxiv.org/pdf/0909.4061 + + Notes + ----- + SVD suffers from a problem called "sign indeterminancy", which means the + sign of the ``components_`` and the output from transform depend on the + algorithm and random state. To work around this, fit instances of this + class to data once, then keep the instance around to do transformations. + + """ + def __init__(self, n_components=2, algorithm="randomized", n_iter=5, + random_state=None, tol=0.): + self.algorithm = algorithm + self.n_components = n_components + self.n_iter = n_iter + self.random_state = random_state + self.tol = tol + + def fit(self, X, y=None): + """Fit LSI model on training data X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + Returns + ------- + self : object + Returns the transformer object. + """ + self.fit_transform(X) + return self + + def fit_transform(self, X, y=None): + """Fit LSI model to X and perform dimensionality reduction on X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + Returns + ------- + X_new : array, shape (n_samples, n_components) + Reduced version of X. This will always be a dense array. + """ + X = as_float_array(X, copy=False) + random_state = check_random_state(self.random_state) + + # If sparse and not csr or csc, convert to csr + if sp.issparse(X) and X.getformat() not in ["csr", "csc"]: + X = X.tocsr() + + if self.algorithm == "arpack": + U, Sigma, VT = svds(X, k=self.n_components, tol=self.tol) + # svds doesn't abide by scipy.linalg.svd/randomized_svd + # conventions, so reverse its outputs. + Sigma = Sigma[::-1] + U, VT = svd_flip(U[:, ::-1], VT[::-1]) + + elif self.algorithm == "randomized": + k = self.n_components + n_features = X.shape[1] + if k >= n_features: + raise ValueError("n_components must be < n_features;" + " got %d >= %d" % (k, n_features)) + U, Sigma, VT = randomized_svd(X, self.n_components, + n_iter=self.n_iter, + random_state=random_state) + else: + raise ValueError("unknown algorithm %r" % self.algorithm) + + self.components_ = VT + + # Calculate explained variance & explained variance ratio + X_transformed = np.dot(U, np.diag(Sigma)) + self.explained_variance_ = exp_var = np.var(X_transformed, axis=0) + if sp.issparse(X): + _, full_var = mean_variance_axis(X, axis=0) + full_var = full_var.sum() + else: + full_var = np.var(X, axis=0).sum() + self.explained_variance_ratio_ = exp_var / full_var + return X_transformed + + def transform(self, X): + """Perform dimensionality reduction on X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + New data. + + Returns + ------- + X_new : array, shape (n_samples, n_components) + Reduced version of X. This will always be a dense array. + """ + X = check_array(X, accept_sparse='csr') + return safe_sparse_dot(X, self.components_.T) + + def inverse_transform(self, X): + """Transform X back to its original space. + + Returns an array X_original whose transform would be X. + + Parameters + ---------- + X : array-like, shape (n_samples, n_components) + New data. + + Returns + ------- + X_original : array, shape (n_samples, n_features) + Note that this is always a dense array. + """ + X = check_array(X) + return np.dot(X, self.components_) diff --git a/sklearn/dummy.py b/sklearn/dummy.py new file mode 100644 index 0000000000000..2bb4fdb94ca53 --- /dev/null +++ b/sklearn/dummy.py @@ -0,0 +1,476 @@ +# Author: Mathieu Blondel +# Arnaud Joly +# Maheshakya Wijewardena +# License: BSD 3 clause +from __future__ import division + +import warnings +import numpy as np +import scipy.sparse as sp + +from .base import BaseEstimator, ClassifierMixin, RegressorMixin +from .utils import check_random_state +from .utils.validation import check_array +from .utils.validation import check_consistent_length +from .utils import deprecated +from .utils.random import random_choice_csc +from .utils.stats import _weighted_percentile +from .utils.multiclass import class_distribution + + +class DummyClassifier(BaseEstimator, ClassifierMixin): + """ + DummyClassifier is a classifier that makes predictions using simple rules. + + This classifier is useful as a simple baseline to compare with other + (real) classifiers. Do not use it for real problems. + + Parameters + ---------- + strategy : str + Strategy to use to generate predictions. + + * "stratified": generates predictions by respecting the training + set's class distribution. + * "most_frequent": always predicts the most frequent label in the + training set. + * "uniform": generates predictions uniformly at random. + * "constant": always predicts a constant label that is provided by + the user. This is useful for metrics that evaluate a non-majority + class + + random_state : int seed, RandomState instance, or None (default) + The seed of the pseudo random number generator to use. + + constant : int or str or array of shape = [n_outputs] + The explicit constant as predicted by the "constant" strategy. This + parameter is useful only for the "constant" strategy. + + Attributes + ---------- + classes_ : array or list of array of shape = [n_classes] + Class labels for each output. + + n_classes_ : array or list of array of shape = [n_classes] + Number of label for each output. + + class_prior_ : array or list of array of shape = [n_classes] + Probability of each class for each output. + + n_outputs_ : int, + Number of outputs. + + outputs_2d_ : bool, + True if the output at fit is 2d, else false. + + `sparse_output_` : bool, + True if the array returned from predict is to be in sparse CSC format. + Is automatically set to True if the input y is passed in sparse format. + + """ + + def __init__(self, strategy="stratified", random_state=None, + constant=None): + self.strategy = strategy + self.random_state = random_state + self.constant = constant + + def fit(self, X, y, sample_weight=None): + """Fit the random classifier. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Training vectors, where n_samples is the number of samples + and n_features is the number of features. + + y : array-like, shape = [n_samples] or [n_samples, n_outputs] + Target values. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + self : object + Returns self. + """ + if self.strategy not in ("most_frequent", "stratified", "uniform", + "constant"): + raise ValueError("Unknown strategy type.") + + if self.strategy == "uniform" and sp.issparse(y): + y = y.toarray() + warnings.warn('A local copy of the target data has been converted ' + 'to a numpy array. Predicting on sparse target data ' + 'with the uniform strategy would not save memory ' + 'and would be slower.', + UserWarning) + + self.sparse_output_ = sp.issparse(y) + + if not self.sparse_output_: + y = np.atleast_1d(y) + + self.output_2d_ = y.ndim == 2 + if y.ndim == 1: + y = np.reshape(y, (-1, 1)) + + self.n_outputs_ = y.shape[1] + + if self.strategy == "constant": + if self.constant is None: + raise ValueError("Constant target value has to be specified " + "when the constant strategy is used.") + else: + constant = np.reshape(np.atleast_1d(self.constant), (-1, 1)) + if constant.shape[0] != self.n_outputs_: + raise ValueError("Constant target value should have " + "shape (%d, 1)." % self.n_outputs_) + + (self.classes_, + self.n_classes_, + self.class_prior_) = class_distribution(y, sample_weight) + + if (self.strategy == "constant" and + any(constant[k] not in self.classes_[k] + for k in range(self.n_outputs_))): + # Checking in case of constant strategy if the constant + # provided by the user is in y. + raise ValueError("The constant target value must be " + "present in training data") + + if self.n_outputs_ == 1 and not self.output_2d_: + self.n_classes_ = self.n_classes_[0] + self.classes_ = self.classes_[0] + self.class_prior_ = self.class_prior_[0] + + return self + + def predict(self, X): + """ + Perform classification on test vectors X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Input vectors, where n_samples is the number of samples + and n_features is the number of features. + + Returns + ------- + y : array, shape = [n_samples] or [n_samples, n_outputs] + Predicted target values for X. + """ + if not hasattr(self, "classes_"): + raise ValueError("DummyClassifier not fitted.") + + X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) + # numpy random_state expects Python int and not long as size argument + # under Windows + n_samples = int(X.shape[0]) + rs = check_random_state(self.random_state) + + n_classes_ = self.n_classes_ + classes_ = self.classes_ + class_prior_ = self.class_prior_ + constant = self.constant + if self.n_outputs_ == 1: + # Get same type even for self.n_outputs_ == 1 + n_classes_ = [n_classes_] + classes_ = [classes_] + class_prior_ = [class_prior_] + constant = [constant] + # Compute probability only once + if self.strategy == "stratified": + proba = self.predict_proba(X) + if self.n_outputs_ == 1: + proba = [proba] + + if self.sparse_output_: + class_prob = None + if self.strategy == "most_frequent": + classes_ = [np.array([cp.argmax()]) for cp in class_prior_] + + elif self.strategy == "stratified": + class_prob = class_prior_ + + elif self.strategy == "uniform": + raise ValueError("Sparse target prediction is not " + "supported with the uniform strategy") + + elif self.strategy == "constant": + classes_ = [np.array([c]) for c in constant] + + y = random_choice_csc(n_samples, classes_, class_prob, + self.random_state) + else: + if self.strategy == "most_frequent": + y = np.tile([classes_[k][class_prior_[k].argmax()] for + k in range(self.n_outputs_)], [n_samples, 1]) + + elif self.strategy == "stratified": + y = np.vstack(classes_[k][proba[k].argmax(axis=1)] for + k in range(self.n_outputs_)).T + + elif self.strategy == "uniform": + ret = [classes_[k][rs.randint(n_classes_[k], size=n_samples)] + for k in range(self.n_outputs_)] + y = np.vstack(ret).T + + elif self.strategy == "constant": + y = np.tile(self.constant, (n_samples, 1)) + + if self.n_outputs_ == 1 and not self.output_2d_: + y = np.ravel(y) + + return y + + def predict_proba(self, X): + """ + Return probability estimates for the test vectors X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Input vectors, where n_samples is the number of samples + and n_features is the number of features. + + Returns + ------- + P : array-like or list of array-lke of shape = [n_samples, n_classes] + Returns the probability of the sample for each class in + the model, where classes are ordered arithmetically, for each + output. + """ + if not hasattr(self, "classes_"): + raise ValueError("DummyClassifier not fitted.") + + X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) + # numpy random_state expects Python int and not long as size argument + # under Windows + n_samples = int(X.shape[0]) + rs = check_random_state(self.random_state) + + n_classes_ = self.n_classes_ + classes_ = self.classes_ + class_prior_ = self.class_prior_ + constant = self.constant + if self.n_outputs_ == 1 and not self.output_2d_: + # Get same type even for self.n_outputs_ == 1 + n_classes_ = [n_classes_] + classes_ = [classes_] + class_prior_ = [class_prior_] + constant = [constant] + + P = [] + for k in range(self.n_outputs_): + if self.strategy == "most_frequent": + ind = np.ones(n_samples, dtype=int) * class_prior_[k].argmax() + out = np.zeros((n_samples, n_classes_[k]), dtype=np.float64) + out[:, ind] = 1.0 + + elif self.strategy == "stratified": + out = rs.multinomial(1, class_prior_[k], size=n_samples) + + elif self.strategy == "uniform": + out = np.ones((n_samples, n_classes_[k]), dtype=np.float64) + out /= n_classes_[k] + + elif self.strategy == "constant": + ind = np.where(classes_[k] == constant[k]) + out = np.zeros((n_samples, n_classes_[k]), dtype=np.float64) + out[:, ind] = 1.0 + + P.append(out) + + if self.n_outputs_ == 1 and not self.output_2d_: + P = P[0] + + return P + + def predict_log_proba(self, X): + """ + Return log probability estimates for the test vectors X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Input vectors, where n_samples is the number of samples + and n_features is the number of features. + + Returns + ------- + P : array-like or list of array-like of shape = [n_samples, n_classes] + Returns the log probability of the sample for each class in + the model, where classes are ordered arithmetically for each + output. + """ + proba = self.predict_proba(X) + if self.n_outputs_ == 1: + return np.log(proba) + else: + return [np.log(p) for p in proba] + + +class DummyRegressor(BaseEstimator, RegressorMixin): + """ + DummyRegressor is a regressor that makes predictions using + simple rules. + + This regressor is useful as a simple baseline to compare with other + (real) regressors. Do not use it for real problems. + + Parameters + ---------- + strategy : str + Strategy to use to generate predictions. + + * "mean": always predicts the mean of the training set + * "median": always predicts the median of the training set + * "quantile": always predicts a specified quantile of the training set, + provided with the quantile parameter. + * "constant": always predicts a constant value that is provided by + the user. + + constant : int or float or array of shape = [n_outputs] + The explicit constant as predicted by the "constant" strategy. This + parameter is useful only for the "constant" strategy. + + quantile : float in [0.0, 1.0] + The quantile to predict using the "quantile" strategy. A quantile of + 0.5 corresponds to the median, while 0.0 to the minimum and 1.0 to the + maximum. + + Attributes + ---------- + constant_ : float or array of shape [n_outputs] + Mean or median or quantile of the training targets or constant value + given by the user. + + n_outputs_ : int, + Number of outputs. + + outputs_2d_ : bool, + True if the output at fit is 2d, else false. + """ + + def __init__(self, strategy="mean", constant=None, quantile=None): + self.strategy = strategy + self.constant = constant + self.quantile = quantile + + @property + @deprecated('This will be removed in version 0.17') + def y_mean_(self): + if self.strategy == 'mean': + return self.constant_ + raise AttributeError + + def fit(self, X, y, sample_weight=None): + """Fit the random regressor. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Training vectors, where n_samples is the number of samples + and n_features is the number of features. + + y : array-like, shape = [n_samples] or [n_samples, n_outputs] + Target values. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + self : object + Returns self. + """ + + if self.strategy not in ("mean", "median", "quantile", "constant"): + raise ValueError("Unknown strategy type: %s, expected " + "'mean', 'median', 'quantile' or 'constant'" + % self.strategy) + + y = check_array(y, ensure_2d=False) + if len(y) == 0: + raise ValueError("y must not be empty.") + + self.output_2d_ = y.ndim == 2 + if y.ndim == 1: + y = np.reshape(y, (-1, 1)) + self.n_outputs_ = y.shape[1] + + check_consistent_length(X, y, sample_weight) + + if self.strategy == "mean": + self.constant_ = np.average(y, axis=0, weights=sample_weight) + + elif self.strategy == "median": + if sample_weight is None: + self.constant_ = np.median(y, axis=0) + else: + self.constant_ = [_weighted_percentile(y[:, k], sample_weight, + percentile=50.) + for k in range(self.n_outputs_)] + + elif self.strategy == "quantile": + if self.quantile is None or not np.isscalar(self.quantile): + raise ValueError("Quantile must be a scalar in the range " + "[0.0, 1.0], but got %s." % self.quantile) + + percentile = self.quantile * 100.0 + if sample_weight is None: + self.constant_ = np.percentile(y, axis=0, q=percentile) + else: + self.constant_ = [_weighted_percentile(y[:, k], sample_weight, + percentile=percentile) + for k in range(self.n_outputs_)] + + elif self.strategy == "constant": + if self.constant is None: + raise TypeError("Constant target value has to be specified " + "when the constant strategy is used.") + + self.constant = check_array(self.constant, + accept_sparse=['csr', 'csc', 'coo'], + ensure_2d=False, ensure_min_samples=0) + + if self.output_2d_ and self.constant.shape[0] != y.shape[1]: + raise ValueError( + "Constant target value should have " + "shape (%d, 1)." % y.shape[1]) + + self.constant_ = self.constant + + self.constant_ = np.reshape(self.constant_, (1, -1)) + return self + + def predict(self, X): + """ + Perform classification on test vectors X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Input vectors, where n_samples is the number of samples + and n_features is the number of features. + + Returns + ------- + y : array, shape = [n_samples] or [n_samples, n_outputs] + Predicted target values for X. + """ + if not hasattr(self, "constant_"): + raise ValueError("DummyRegressor not fitted.") + + X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) + n_samples = X.shape[0] + + y = np.ones((n_samples, 1)) * self.constant_ + + if self.n_outputs_ == 1 and not self.output_2d_: + y = np.ravel(y) + + return y diff --git a/sklearn/ensemble/__init__.py b/sklearn/ensemble/__init__.py index d76405cf0e827..b7cb51f59920b 100644 --- a/sklearn/ensemble/__init__.py +++ b/sklearn/ensemble/__init__.py @@ -6,7 +6,27 @@ from .base import BaseEnsemble from .forest import RandomForestClassifier from .forest import RandomForestRegressor +from .forest import RandomTreesEmbedding from .forest import ExtraTreesClassifier from .forest import ExtraTreesRegressor +from .bagging import BaggingClassifier +from .bagging import BaggingRegressor +from .weight_boosting import AdaBoostClassifier +from .weight_boosting import AdaBoostRegressor from .gradient_boosting import GradientBoostingClassifier from .gradient_boosting import GradientBoostingRegressor + +from . import bagging +from . import forest +from . import weight_boosting +from . import gradient_boosting +from . import partial_dependence + +__all__ = ["BaseEnsemble", + "RandomForestClassifier", "RandomForestRegressor", + "RandomTreesEmbedding", "ExtraTreesClassifier", + "ExtraTreesRegressor", "BaggingClassifier", + "BaggingRegressor", "GradientBoostingClassifier", + "GradientBoostingRegressor", "AdaBoostClassifier", + "AdaBoostRegressor", "bagging", "forest", "gradient_boosting", + "partial_dependence", "weight_boosting"] diff --git a/sklearn/ensemble/_gradient_boosting.c b/sklearn/ensemble/_gradient_boosting.c index bc1c819b0e68b..8eab76a3d3dbc 100644 --- a/sklearn/ensemble/_gradient_boosting.c +++ b/sklearn/ensemble/_gradient_boosting.c @@ -1,17 +1,29 @@ -/* Generated by Cython 0.16 on Sat Jul 21 15:55:06 2012 */ +/* Generated by Cython 0.22 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02040000 - #error Cython requires Python 2.4+. +#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) + #error Cython requires Python 2.6+ or Python 3.2+. #else -#include /* For offsetof */ +#define CYTHON_ABI "0_22" +#include #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -23,22 +35,18 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif - #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 @@ -46,100 +54,65 @@ #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif - -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyCFunction_Call PyObject_Call -#else - #define __Pyx_PyCFunction_Call PyCFunction_Call -#endif - -#if PY_VERSION_HEX < 0x02050000 - typedef int Py_ssize_t; - #define PY_SSIZE_T_MAX INT_MAX - #define PY_SSIZE_T_MIN INT_MIN - #define PY_FORMAT_SIZE_T "" - #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) - #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) - #define __PYX_BUILD_PY_SSIZE_T "i" -#else - #define __PYX_BUILD_PY_SSIZE_T "n" -#endif - -#if PY_VERSION_HEX < 0x02060000 - #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) - #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) - #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) - #define PyVarObject_HEAD_INIT(type, size) \ - PyObject_HEAD_INIT(type) size, - #define PyType_Modified(t) - - typedef struct { - void *buf; - PyObject *obj; - Py_ssize_t len; - Py_ssize_t itemsize; - int readonly; - int ndim; - char *format; - Py_ssize_t *shape; - Py_ssize_t *strides; - Py_ssize_t *suboffsets; - void *internal; - } Py_buffer; - - #define PyBUF_SIMPLE 0 - #define PyBUF_WRITABLE 0x0001 - #define PyBUF_FORMAT 0x0004 - #define PyBUF_ND 0x0008 - #define PyBUF_STRIDES (0x0010 | PyBUF_ND) - #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) - #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) - #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) - #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) - #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) - - typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); - typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) +#define Py_OptimizeFlag 0 #endif - +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ - PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type #endif - -#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 - #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") -#endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 -#endif - -#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - - -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_GET_LENGTH) +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #else #define CYTHON_PEP393_ENABLED 0 - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) + #define __Pyx_PyFrozenSet_Size(s) PyObject_Size(s) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) + #define __Pyx_PyFrozenSet_Size(s) PySet_Size(s) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif - #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -147,36 +120,17 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - -#if PY_VERSION_HEX < 0x02060000 - #define PyBytesObject PyStringObject - #define PyBytes_Type PyString_Type - #define PyBytes_Check PyString_Check - #define PyBytes_CheckExact PyString_CheckExact - #define PyBytes_FromString PyString_FromString - #define PyBytes_FromStringAndSize PyString_FromStringAndSize - #define PyBytes_FromFormat PyString_FromFormat - #define PyBytes_DecodeEscape PyString_DecodeEscape - #define PyBytes_AsString PyString_AsString - #define PyBytes_AsStringAndSize PyString_AsStringAndSize - #define PyBytes_Size PyString_Size - #define PyBytes_AS_STRING PyString_AS_STRING - #define PyBytes_GET_SIZE PyString_GET_SIZE - #define PyBytes_Repr PyString_Repr - #define PyBytes_Concat PyString_Concat - #define PyBytes_ConcatAndDel PyString_ConcatAndDel -#endif - -#if PY_VERSION_HEX < 0x02060000 - #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) - #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -192,13 +146,17 @@ #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - -#if PY_VERSION_HEX < 0x03020000 +#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY + #ifndef PyUnicode_InternFromString + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) + #endif +#endif +#if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong @@ -206,48 +164,64 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - -#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) - #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) - #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else - #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) - #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif - -#if PY_MAJOR_VERSION >= 3 - #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif #endif - -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) -#else - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif #endif - -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_NAMESTR(n) ((char *)(n)) - #define __Pyx_DOCSTR(n) ((char *)(n)) +#ifdef NAN +#define __PYX_NAN() ((float) NAN) #else - #define __Pyx_NAMESTR(n) (n) - #define __Pyx_DOCSTR(n) (n) +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#define __Pyx_void_to_None(void_result) (void_result, Py_INCREF(Py_None), Py_None) +#ifdef __cplusplus +template +void __Pyx_call_destructor(T* x) { + x->~T(); +} +template +class __Pyx_FakeReference { + public: + __Pyx_FakeReference() : ptr(NULL) { } + __Pyx_FakeReference(T& ref) : ptr(&ref) { } + T *operator->() { return ptr; } + operator T&() { return *ptr; } + private: + T *ptr; +}; #endif + #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) @@ -270,10 +244,13 @@ #include #define __PYX_HAVE__sklearn__ensemble___gradient_boosting #define __PYX_HAVE_API__sklearn__ensemble___gradient_boosting +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" +#include "pythread.h" +#include "pystate.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -282,21 +259,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -310,42 +272,157 @@ # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + -#ifdef __GNUC__ - /* Test for GCC > 2.95 */ - #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) - #else /* __GNUC__ > 2 ... */ - #define likely(x) (x) - #define unlikely(x) (x) - #endif /* __GNUC__ > 2 ... */ -#else /* __GNUC__ */ +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -377,20 +454,22 @@ static const char *__pyx_filename; static const char *__pyx_f[] = { - "_gradient_boosting.pyx", - "numpy.pxd", - "_tree.pxd", + "sklearn/ensemble/_gradient_boosting.pyx", + "__init__.pxd", + "sklearn/ensemble/stringsource", + "type.pxd", + "sklearn/tree/_tree.pxd", }; #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { - const char* name; /* for error messages only */ + const char* name; struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - size_t arraysize[8]; /* length of array in each dimension */ + size_t size; + size_t arraysize[8]; int ndim; - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ + char typegroup; char is_unsigned; int flags; } __Pyx_TypeInfo; @@ -416,8 +495,64 @@ typedef struct { char is_valid_array; } __Pyx_BufFmt_Context; +struct __pyx_memoryview_obj; +typedef struct { + struct __pyx_memoryview_obj *memview; + char *data; + Py_ssize_t shape[8]; + Py_ssize_t strides[8]; + Py_ssize_t suboffsets[8]; +} __Pyx_memviewslice; + +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __pyx_atomic_int_type int +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ + !defined(__i386__) + #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && MSC_VER + #include + #define __pyx_atomic_int_type LONG + #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using MSVC atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 + #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using Intel atomics" + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif +typedef volatile __pyx_atomic_int_type __pyx_atomic_int; +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview) \ + __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) +#else + #define __pyx_add_acquisition_count(memview) \ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif + -/* "numpy.pxd":722 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":726 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -426,7 +561,7 @@ typedef struct { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":723 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":727 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -435,7 +570,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":724 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":728 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -444,7 +579,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":725 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":729 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -453,7 +588,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":729 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":733 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -462,7 +597,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":730 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":734 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -471,7 +606,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":731 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":735 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -480,7 +615,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":732 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":736 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -489,7 +624,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":736 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":740 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -498,7 +633,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":737 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":741 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -507,7 +642,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":746 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":750 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -516,7 +651,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":747 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":751 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -525,7 +660,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":748 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":752 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -534,7 +669,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":750 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":754 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -543,7 +678,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":751 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":755 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -552,7 +687,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":752 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":756 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -561,7 +696,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":754 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -570,7 +705,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":755 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -579,7 +714,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":757 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":761 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -588,7 +723,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":758 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":762 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -597,7 +732,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":759 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":763 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -606,41 +741,95 @@ typedef npy_double __pyx_t_5numpy_double_t; */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; -/* "sklearn/tree/_tree.pxd":8 +/* "sklearn/tree/_tree.pxd":14 * cimport numpy as np * - * ctypedef np.float32_t DTYPE_t # <<<<<<<<<<<<<< - * ctypedef np.float64_t DOUBLE_t - * ctypedef np.int8_t BOOL_t + * ctypedef np.npy_float32 DTYPE_t # Type of X # <<<<<<<<<<<<<< + * ctypedef np.npy_float64 DOUBLE_t # Type of y, sample_weight + * ctypedef np.npy_intp SIZE_t # Type for indices and counters */ -typedef __pyx_t_5numpy_float32_t __pyx_t_7sklearn_4tree_5_tree_DTYPE_t; +typedef npy_float32 __pyx_t_7sklearn_4tree_5_tree_DTYPE_t; -/* "sklearn/tree/_tree.pxd":9 +/* "sklearn/tree/_tree.pxd":15 * - * ctypedef np.float32_t DTYPE_t - * ctypedef np.float64_t DOUBLE_t # <<<<<<<<<<<<<< - * ctypedef np.int8_t BOOL_t + * ctypedef np.npy_float32 DTYPE_t # Type of X + * ctypedef np.npy_float64 DOUBLE_t # Type of y, sample_weight # <<<<<<<<<<<<<< + * ctypedef np.npy_intp SIZE_t # Type for indices and counters + * ctypedef np.npy_int32 INT32_t # Signed 32 bit integer + */ +typedef npy_float64 __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t; + +/* "sklearn/tree/_tree.pxd":16 + * ctypedef np.npy_float32 DTYPE_t # Type of X + * ctypedef np.npy_float64 DOUBLE_t # Type of y, sample_weight + * ctypedef np.npy_intp SIZE_t # Type for indices and counters # <<<<<<<<<<<<<< + * ctypedef np.npy_int32 INT32_t # Signed 32 bit integer + * ctypedef np.npy_uint32 UINT32_t # Unsigned 32 bit integer + */ +typedef npy_intp __pyx_t_7sklearn_4tree_5_tree_SIZE_t; + +/* "sklearn/tree/_tree.pxd":17 + * ctypedef np.npy_float64 DOUBLE_t # Type of y, sample_weight + * ctypedef np.npy_intp SIZE_t # Type for indices and counters + * ctypedef np.npy_int32 INT32_t # Signed 32 bit integer # <<<<<<<<<<<<<< + * ctypedef np.npy_uint32 UINT32_t # Unsigned 32 bit integer * */ -typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t; +typedef npy_int32 __pyx_t_7sklearn_4tree_5_tree_INT32_t; -/* "sklearn/tree/_tree.pxd":10 - * ctypedef np.float32_t DTYPE_t - * ctypedef np.float64_t DOUBLE_t - * ctypedef np.int8_t BOOL_t # <<<<<<<<<<<<<< +/* "sklearn/tree/_tree.pxd":18 + * ctypedef np.npy_intp SIZE_t # Type for indices and counters + * ctypedef np.npy_int32 INT32_t # Signed 32 bit integer + * ctypedef np.npy_uint32 UINT32_t # Unsigned 32 bit integer # <<<<<<<<<<<<<< + * + * + */ +typedef npy_uint32 __pyx_t_7sklearn_4tree_5_tree_UINT32_t; + +/* "sklearn/ensemble/_gradient_boosting.pyx":17 + * from sklearn.tree._tree cimport Tree, Node + * + * ctypedef np.int32_t int32 # <<<<<<<<<<<<<< + * ctypedef np.float64_t float64 + * ctypedef np.uint8_t uint8 + */ +typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32; + +/* "sklearn/ensemble/_gradient_boosting.pyx":18 * + * ctypedef np.int32_t int32 + * ctypedef np.float64_t float64 # <<<<<<<<<<<<<< + * ctypedef np.uint8_t uint8 * */ -typedef __pyx_t_5numpy_int8_t __pyx_t_7sklearn_4tree_5_tree_BOOL_t; +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_8ensemble_18_gradient_boosting_float64; /* "sklearn/ensemble/_gradient_boosting.pyx":19 + * ctypedef np.int32_t int32 + * ctypedef np.float64_t float64 + * ctypedef np.uint8_t uint8 # <<<<<<<<<<<<<< + * + * # no namespace lookup for numpy dtype and array creation + */ +typedef __pyx_t_5numpy_uint8_t __pyx_t_7sklearn_8ensemble_18_gradient_boosting_uint8; + +/* "sklearn/ensemble/_gradient_boosting.pyx":30 * # Define a datatype for the data array * DTYPE = np.float32 * ctypedef np.float32_t DTYPE_t # <<<<<<<<<<<<<< - * + * ctypedef np.npy_intp SIZE_t * */ typedef __pyx_t_5numpy_float32_t __pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t; + +/* "sklearn/ensemble/_gradient_boosting.pyx":31 + * DTYPE = np.float32 + * ctypedef np.float32_t DTYPE_t + * ctypedef np.npy_intp SIZE_t # <<<<<<<<<<<<<< + * + * + */ +typedef npy_intp __pyx_t_7sklearn_8ensemble_18_gradient_boosting_SIZE_t; #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -663,10 +852,16 @@ typedef __pyx_t_5numpy_float32_t __pyx_t_7sklearn_8ensemble_18_gradient_boosting /*--- Type declarations ---*/ -struct __pyx_obj_7sklearn_4tree_5_tree_Tree; struct __pyx_obj_7sklearn_4tree_5_tree_Criterion; +struct __pyx_obj_7sklearn_4tree_5_tree_Splitter; +struct __pyx_obj_7sklearn_4tree_5_tree_Tree; +struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder; +struct __pyx_array_obj; +struct __pyx_MemviewEnum_obj; +struct __pyx_memoryview_obj; +struct __pyx_memoryviewslice_obj; -/* "numpy.pxd":761 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":765 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -675,7 +870,7 @@ struct __pyx_obj_7sklearn_4tree_5_tree_Criterion; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":762 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":766 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -684,7 +879,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":763 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":767 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -693,7 +888,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":765 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":769 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -701,173 +896,400 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; -struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_resize; -struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_build; +struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord; +struct __pyx_t_7sklearn_4tree_5_tree_Node; +struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c; struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances; +struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build; -/* "sklearn/tree/_tree.pxd":68 +/* "sklearn/tree/_tree.pxd":67 + * # ============================================================================= * - * # Methods - * cdef void resize(self, int capacity=*) # <<<<<<<<<<<<<< - * - * cpdef build(self, np.ndarray X, np.ndarray y, + * cdef struct SplitRecord: # <<<<<<<<<<<<<< + * # Data to track sample split + * SIZE_t feature # Which feature to split on. */ -struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_resize { - int __pyx_n; - int capacity; +struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t feature; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t pos; + double threshold; + double improvement; + double impurity_left; + double impurity_right; }; -/* "sklearn/tree/_tree.pxd":70 - * cdef void resize(self, int capacity=*) +/* "sklearn/tree/_tree.pxd":146 + * # ============================================================================= * - * cpdef build(self, np.ndarray X, np.ndarray y, # <<<<<<<<<<<<<< - * np.ndarray sample_mask=*, np.ndarray X_argsorted=*) + * cdef struct Node: # <<<<<<<<<<<<<< + * # Base storage structure for the nodes in a Tree object * */ -struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_build { +struct __pyx_t_7sklearn_4tree_5_tree_Node { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t left_child; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t right_child; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t feature; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t threshold; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t impurity; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_node_samples; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t weighted_n_node_samples; +}; + +/* "sklearn/tree/_tree.pxd":184 + * double weighted_n_samples) nogil + * cdef void _resize(self, SIZE_t capacity) except * + * cdef int _resize_c(self, SIZE_t capacity=*) nogil # <<<<<<<<<<<<<< + * + * cdef np.ndarray _get_value_ndarray(self) + */ +struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c { int __pyx_n; - PyArrayObject *sample_mask; - PyArrayObject *X_argsorted; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t capacity; }; -/* "sklearn/tree/_tree.pxd":119 - * cpdef apply(self, np.ndarray[DTYPE_t, ndim=2] X) +/* "sklearn/tree/_tree.pxd":194 + * cdef np.ndarray _apply_sparse_csr(self, object X) + * + * cpdef compute_feature_importances(self, normalize=*) # <<<<<<<<<<<<<< * - * cpdef compute_feature_importances(self, method=*) # <<<<<<<<<<<<<< * - * cdef inline double _compute_feature_importances_gini(self, int node) */ struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances { int __pyx_n; - PyObject *method; + PyObject *normalize; +}; + +/* "sklearn/tree/_tree.pxd":216 + * cdef SIZE_t max_depth # Maximal tree depth + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=*) + * cdef _check_input(self, object X, np.ndarray y, np.ndarray sample_weight) + */ +struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build { + int __pyx_n; + PyArrayObject *sample_weight; +}; + +/* "sklearn/tree/_tree.pxd":25 + * # ============================================================================= + * + * cdef class Criterion: # <<<<<<<<<<<<<< + * # The criterion computes the impurity of a node and the reduction of + * # impurity of a split on that node. It also computes the output statistics + */ +struct __pyx_obj_7sklearn_4tree_5_tree_Criterion { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *__pyx_vtab; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *y; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t y_stride; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *sample_weight; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t pos; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t end; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_node_samples; + double weighted_n_samples; + double weighted_n_node_samples; + double weighted_n_left; + double weighted_n_right; +}; + + +/* "sklearn/tree/_tree.pxd":79 + * + * + * cdef class Splitter: # <<<<<<<<<<<<<< + * # The splitter searches in the input space for a feature and a threshold + * # to split the samples samples[start:end]. + */ +struct __pyx_obj_7sklearn_4tree_5_tree_Splitter { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *__pyx_vtab; + struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *criterion; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t max_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t min_samples_leaf; + double min_weight_leaf; + PyObject *random_state; + __pyx_t_7sklearn_4tree_5_tree_UINT32_t rand_r_state; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_samples; + double weighted_n_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *constant_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_features; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *feature_values; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t end; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *y; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t y_stride; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *sample_weight; }; -/* "sklearn/tree/_tree.pxd":36 - * # ============================================================================== + +/* "sklearn/tree/_tree.pxd":158 + * * * cdef class Tree: # <<<<<<<<<<<<<< - * # Input/Output layout - * cdef public int n_features + * # The Tree object is a binary tree structure constructed by the + * # TreeBuilder. The tree structure is used for predictions and */ struct __pyx_obj_7sklearn_4tree_5_tree_Tree { PyObject_HEAD struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *__pyx_vtab; - int n_features; - int *n_classes; - int n_outputs; - int max_n_classes; - int value_stride; - struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *criterion; - double max_depth; - int min_samples_split; - int min_samples_leaf; - double min_density; - int max_features; - int find_split_algorithm; - PyObject *random_state; - int node_count; - int capacity; - int *children_left; - int *children_right; - int *feature; - double *threshold; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t max_n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t max_depth; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t node_count; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t capacity; + struct __pyx_t_7sklearn_4tree_5_tree_Node *nodes; double *value; - double *best_error; - double *init_error; - int *n_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t value_stride; }; -/* "sklearn/tree/_tree.pxd":17 - * # ============================================================================== +/* "sklearn/tree/_tree.pxd":201 + * # ============================================================================= * - * cdef class Criterion: # <<<<<<<<<<<<<< - * # Methods - * cdef void init(self, DOUBLE_t* y, int y_stride, BOOL_t* sample_mask, + * cdef class TreeBuilder: # <<<<<<<<<<<<<< + * # The TreeBuilder recursively builds a Tree object from training samples, + * # using a Splitter object for splitting internal nodes and assigning */ -struct __pyx_obj_7sklearn_4tree_5_tree_Criterion { +struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder { PyObject_HEAD - struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *__pyx_vtab; + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder *__pyx_vtab; + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *splitter; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t min_samples_split; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t min_samples_leaf; + double min_weight_leaf; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t max_depth; }; +/* "View.MemoryView":99 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ +struct __pyx_array_obj { + PyObject_HEAD + char *data; + Py_ssize_t len; + char *format; + int ndim; + Py_ssize_t *_shape; + Py_ssize_t *_strides; + Py_ssize_t itemsize; + PyObject *mode; + PyObject *_format; + void (*callback_free_data)(void *); + int free_data; + int dtype_is_object; +}; + -/* "sklearn/tree/_tree.pxd":36 - * # ============================================================================== +/* "View.MemoryView":269 * - * cdef class Tree: # <<<<<<<<<<<<<< - * # Input/Output layout - * cdef public int n_features + * @cname('__pyx_MemviewEnum') + * cdef class Enum(object): # <<<<<<<<<<<<<< + * cdef object name + * def __init__(self, name): */ +struct __pyx_MemviewEnum_obj { + PyObject_HEAD + PyObject *name; +}; -struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree { - void (*resize)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_resize *__pyx_optional_args); - PyObject *(*build)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_build *__pyx_optional_args); - void (*recursive_partition)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, int, int, int, int, double *); - int (*add_split_node)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int, int, int, double, double *, double, double, int); - int (*add_leaf)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int, int, double *, double, int); - void (*find_split)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, int, int *, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int, int *, double *, double *, double *); - void (*find_best_split)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, int, int *, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int, int *, double *, double *, double *); - void (*find_random_split)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, int, int *, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int, int *, double *, double *, double *); - PyObject *(*predict)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, int __pyx_skip_dispatch); - PyObject *(*apply)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, int __pyx_skip_dispatch); - PyObject *(*compute_feature_importances)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances *__pyx_optional_args); - double (*_compute_feature_importances_gini)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int); - double (*_compute_feature_importances_squared)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int); + +/* "View.MemoryView":302 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ +struct __pyx_memoryview_obj { + PyObject_HEAD + struct __pyx_vtabstruct_memoryview *__pyx_vtab; + PyObject *obj; + PyObject *_size; + PyObject *_array_interface; + PyThread_type_lock lock; + __pyx_atomic_int acquisition_count[2]; + __pyx_atomic_int *acquisition_count_aligned_p; + Py_buffer view; + int flags; + int dtype_is_object; + __Pyx_TypeInfo *typeinfo; }; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *__pyx_vtabptr_7sklearn_4tree_5_tree_Tree; -/* "sklearn/tree/_tree.pxd":17 - * # ============================================================================== +/* "View.MemoryView":921 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ +struct __pyx_memoryviewslice_obj { + struct __pyx_memoryview_obj __pyx_base; + __Pyx_memviewslice from_slice; + PyObject *from_object; + PyObject *(*to_object_func)(char *); + int (*to_dtype_func)(char *, PyObject *); +}; + + + +/* "sklearn/tree/_tree.pxd":25 + * # ============================================================================= * * cdef class Criterion: # <<<<<<<<<<<<<< - * # Methods - * cdef void init(self, DOUBLE_t* y, int y_stride, BOOL_t* sample_mask, + * # The criterion computes the impurity of a node and the reduction of + * # impurity of a split on that node. It also computes the output statistics */ struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion { - void (*init)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int); + void (*init)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, double, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); void (*reset)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *); - int (*update)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, int, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, int *, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *); - double (*eval)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *); - void (*init_value)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *); + void (*update)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); + double (*node_impurity)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *); + void (*children_impurity)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *, double *); + void (*node_value)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *); + double (*impurity_improvement)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double); }; static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *__pyx_vtabptr_7sklearn_4tree_5_tree_Criterion; -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil) \ - if (acquire_gil) { \ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ - PyGILState_Release(__pyx_gilstate_save); \ - } else { \ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil) \ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext() \ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + + +/* "sklearn/tree/_tree.pxd":79 + * + * + * cdef class Splitter: # <<<<<<<<<<<<<< + * # The splitter searches in the input space for a feature and a threshold + * # to split the samples samples[start:end]. + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter { + void (*init)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, PyObject *, PyArrayObject *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *); + void (*node_reset)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double *); + void (*node_split)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, double, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *); + void (*node_value)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, double *); + double (*node_impurity)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *); +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *__pyx_vtabptr_7sklearn_4tree_5_tree_Splitter; + + +/* "sklearn/tree/_tree.pxd":158 + * + * + * cdef class Tree: # <<<<<<<<<<<<<< + * # The Tree object is a binary tree structure constructed by the + * # TreeBuilder. The tree structure is used for predictions and + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t (*_add_node)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, int, int, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double, double, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double); + void (*_resize)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); + int (*_resize_c)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c *__pyx_optional_args); + PyArrayObject *(*_get_value_ndarray)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *); + PyArrayObject *(*_get_node_ndarray)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *); + PyArrayObject *(*predict)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *, int __pyx_skip_dispatch); + PyArrayObject *(*apply)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *, int __pyx_skip_dispatch); + PyArrayObject *(*_apply_dense)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *); + PyArrayObject *(*_apply_sparse_csr)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *); + PyObject *(*compute_feature_importances)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances *__pyx_optional_args); +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *__pyx_vtabptr_7sklearn_4tree_5_tree_Tree; + + +/* "sklearn/tree/_tree.pxd":201 + * # ============================================================================= + * + * cdef class TreeBuilder: # <<<<<<<<<<<<<< + * # The TreeBuilder recursively builds a Tree object from training samples, + * # using a Splitter object for splitting internal nodes and assigning + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder { + PyObject *(*build)(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *, PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build *__pyx_optional_args); + PyObject *(*_check_input)(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *, PyObject *, PyArrayObject *, PyArrayObject *); +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder *__pyx_vtabptr_7sklearn_4tree_5_tree_TreeBuilder; + + +/* "View.MemoryView":302 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ + +struct __pyx_vtabstruct_memoryview { + char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); + PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); +}; +static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; + + +/* "View.MemoryView":921 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ + +struct __pyx_vtabstruct__memoryviewslice { + struct __pyx_vtabstruct_memoryview __pyx_base; +}; +static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; + +/* --- Runtime support code (head) --- */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) @@ -884,43 +1306,268 @@ static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *__pyx_vtabptr_7s #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) -#endif /* CYTHON_REFNANNY */ +#endif +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ - const char* function_name); /*proto*/ + const char* function_name); -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact); /*proto*/ +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); #define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d +#define __Pyx_MEMVIEW_DIRECT 1 +#define __Pyx_MEMVIEW_PTR 2 +#define __Pyx_MEMVIEW_FULL 4 +#define __Pyx_MEMVIEW_CONTIG 8 +#define __Pyx_MEMVIEW_STRIDED 16 +#define __Pyx_MEMVIEW_FOLLOW 32 +#define __Pyx_IS_C_CONTIG 1 +#define __Pyx_IS_F_CONTIG 2 +static int __Pyx_init_memviewslice( + struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference); +static CYTHON_INLINE int __pyx_add_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) +#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) +#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) +#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) +static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +#define __Pyx_BufPtrCContig1d(type, buf, i0, s0) ((type)buf + i0) +#if PY_MAJOR_VERSION >= 3 +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { + PyObject *value; + value = PyDict_GetItemWithError(d, key); + if (unlikely(!value)) { + if (!PyErr_Occurred()) { + PyObject* args = PyTuple_Pack(1, key); + if (likely(args)) + PyErr_SetObject(PyExc_KeyError, args); + Py_XDECREF(args); + } + return NULL; + } + Py_INCREF(value); + return value; +} +#else + #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) +#endif static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +#include + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals +#else +#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals +#endif + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) + +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); + +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject* none = _PyList_Extend((PyListObject*)L, v); + if (unlikely(!none)) + return -1; + Py_DECREF(none); + return 0; +#else + return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); +#endif +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename, + int full_traceback); + +static int __Pyx_SetVtable(PyObject *dict, void *vtable); + +static void* __Pyx_GetVtable(PyObject *dict); + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); typedef struct { Py_ssize_t shape, strides, suboffsets; @@ -943,10 +1590,39 @@ typedef struct { #define __Pyx_ReleaseBuffer PyBuffer_Release #endif + static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); + +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_double(PyObject *); + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_int32(npy_int32 value); + +static CYTHON_INLINE npy_int32 __Pyx_PyInt_As_npy_int32(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -960,7 +1636,7 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif -#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else @@ -1046,37 +1722,28 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); +static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim); -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); +static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize); -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object); -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); static int __Pyx_check_binary_version(void); @@ -1088,31 +1755,23 @@ static int __Pyx_check_binary_version(void); #endif #endif -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ - -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ +static PyObject *__Pyx_ImportModule(const char *name); -static void* __Pyx_GetVtable(PyObject *dict); /*proto*/ - -typedef struct { - int code_line; - PyCodeObject* code_object; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); /*proto*/ +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto*/ +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj); /* proto*/ +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src); /* proto*/ +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value); /* proto*/ +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto*/ +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ +/* Module declarations from 'cython.view' */ /* Module declarations from 'cython' */ @@ -1120,10 +1779,17 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -1138,13 +1804,62 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, cha /* Module declarations from 'sklearn.tree._tree' */ static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_Criterion = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_Splitter = 0; static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_Tree = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_TreeBuilder = 0; /* Module declarations from 'sklearn.ensemble._gradient_boosting' */ -static void __pyx_f_7sklearn_8ensemble_18_gradient_boosting__predict_regression_tree_inplace_fast(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t *, int *, int *, int *, double *, double *, double, Py_ssize_t, Py_ssize_t, Py_ssize_t, Py_ssize_t, __pyx_t_5numpy_float64_t *); /*proto*/ +static PyTypeObject *__pyx_array_type = 0; +static PyTypeObject *__pyx_MemviewEnum_type = 0; +static PyTypeObject *__pyx_memoryview_type = 0; +static PyTypeObject *__pyx_memoryviewslice_type = 0; +static int __pyx_v_7sklearn_8ensemble_18_gradient_boosting_LEAF; +static PyObject *generic = 0; +static PyObject *strided = 0; +static PyObject *indirect = 0; +static PyObject *contiguous = 0; +static PyObject *indirect_contiguous = 0; +static void __pyx_f_7sklearn_8ensemble_18_gradient_boosting__predict_regression_tree_inplace_fast(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t *, struct __pyx_t_7sklearn_4tree_5_tree_Node *, double *, double, Py_ssize_t, Py_ssize_t, Py_ssize_t, Py_ssize_t, __pyx_t_7sklearn_8ensemble_18_gradient_boosting_float64 *); /*proto*/ +static CYTHON_INLINE int __pyx_f_7sklearn_8ensemble_18_gradient_boosting_array_index(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32, __Pyx_memviewslice); /*proto*/ +static PyObject *__pyx_f_7sklearn_8ensemble_18_gradient_boosting__partial_dependence_tree(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __Pyx_memviewslice, __Pyx_memviewslice, double, __Pyx_memviewslice, int __pyx_skip_dispatch); /*proto*/ +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ +static void *__pyx_align_pointer(void *, size_t); /*proto*/ +static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ +static PyObject *_unellipsify(PyObject *, int); /*proto*/ +static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ +static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ +static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ +static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ +static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ +static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ +static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ +static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_object = { "Python object", NULL, sizeof(PyObject *), { 0 }, 0, 'O', 0, 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t = { "float64_t", NULL, sizeof(__pyx_t_5numpy_float64_t), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_float64 = { "float64", NULL, sizeof(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_float64), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_uint8 = { "uint8", NULL, sizeof(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_uint8), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_uint8) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_uint8), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32 = { "int32", NULL, sizeof(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "sklearn.ensemble._gradient_boosting" int __pyx_module_is_main_sklearn__ensemble___gradient_boosting = 0; @@ -1152,238 +1867,462 @@ int __pyx_module_is_main_sklearn__ensemble___gradient_boosting = 0; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_Ellipsis; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_id; +static PyObject *__pyx_builtin_IndexError; static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_predict_stages(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_estimators, PyArrayObject *__pyx_v_X, double __pyx_v_scale, PyArrayObject *__pyx_v_out); /* proto */ static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_2predict_stage(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_estimators, int __pyx_v_stage, PyArrayObject *__pyx_v_X, double __pyx_v_scale, PyArrayObject *__pyx_v_out); /* proto */ +static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_4_partial_dependence_tree(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_target_feature, double __pyx_v_learn_rate, __Pyx_memviewslice __pyx_v_out); /* proto */ +static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_6_random_sample_mask(CYTHON_UNUSED PyObject *__pyx_self, npy_intp __pyx_v_n_total_samples, npy_intp __pyx_v_n_total_in_bag, PyObject *__pyx_v_random_state); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ -static char __pyx_k_1[] = "ndarray is not C contiguous"; -static char __pyx_k_3[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_5[] = "Non-native byte order not supported"; -static char __pyx_k_7[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_8[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_11[] = "Format string allocated too short."; -static char __pyx_k_15[] = "/home/pprett/workspace/scikit-learn/sklearn/ensemble/_gradient_boosting.pyx"; -static char __pyx_k_16[] = "sklearn.ensemble._gradient_boosting"; -static char __pyx_k__B[] = "B"; -static char __pyx_k__H[] = "H"; -static char __pyx_k__I[] = "I"; -static char __pyx_k__K[] = "K"; -static char __pyx_k__L[] = "L"; -static char __pyx_k__O[] = "O"; -static char __pyx_k__Q[] = "Q"; -static char __pyx_k__X[] = "X"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__d[] = "d"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__g[] = "g"; -static char __pyx_k__h[] = "h"; -static char __pyx_k__i[] = "i"; -static char __pyx_k__k[] = "k"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__q[] = "q"; -static char __pyx_k__Zd[] = "Zd"; -static char __pyx_k__Zf[] = "Zf"; -static char __pyx_k__Zg[] = "Zg"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__out[] = "out"; -static char __pyx_k__tree[] = "tree"; -static char __pyx_k__DTYPE[] = "DTYPE"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__range[] = "range"; -static char __pyx_k__scale[] = "scale"; -static char __pyx_k__stage[] = "stage"; -static char __pyx_k__float32[] = "float32"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__n_samples[] = "n_samples"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__estimators[] = "estimators"; -static char __pyx_k__n_features[] = "n_features"; -static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k__n_estimators[] = "n_estimators"; -static char __pyx_k__predict_stage[] = "predict_stage"; -static char __pyx_k__predict_stages[] = "predict_stages"; -static PyObject *__pyx_kp_u_1; -static PyObject *__pyx_kp_u_11; -static PyObject *__pyx_kp_s_15; -static PyObject *__pyx_n_s_16; -static PyObject *__pyx_kp_u_3; -static PyObject *__pyx_kp_u_5; -static PyObject *__pyx_kp_u_7; -static PyObject *__pyx_kp_u_8; -static PyObject *__pyx_n_s__DTYPE; -static PyObject *__pyx_n_s__K; -static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s__X; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__estimators; -static PyObject *__pyx_n_s__float32; -static PyObject *__pyx_n_s__i; -static PyObject *__pyx_n_s__k; -static PyObject *__pyx_n_s__n_estimators; -static PyObject *__pyx_n_s__n_features; -static PyObject *__pyx_n_s__n_samples; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__out; -static PyObject *__pyx_n_s__predict_stage; -static PyObject *__pyx_n_s__predict_stages; -static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__scale; -static PyObject *__pyx_n_s__stage; -static PyObject *__pyx_n_s__tree; -static PyObject *__pyx_int_15; -static PyObject *__pyx_k_tuple_2; -static PyObject *__pyx_k_tuple_4; -static PyObject *__pyx_k_tuple_6; -static PyObject *__pyx_k_tuple_9; -static PyObject *__pyx_k_tuple_10; -static PyObject *__pyx_k_tuple_12; -static PyObject *__pyx_k_tuple_13; -static PyObject *__pyx_k_tuple_17; -static PyObject *__pyx_k_codeobj_14; -static PyObject *__pyx_k_codeobj_18; - -/* "sklearn/ensemble/_gradient_boosting.pyx":22 - * +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ +static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ +static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ +static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_B[] = "B"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_K[] = "K"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_X[] = "X"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_c[] = "c"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_k[] = "k"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_id[] = "id"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_obj[] = "obj"; +static char __pyx_k_out[] = "out"; +static char __pyx_k_base[] = "base"; +static char __pyx_k_bool[] = "bool"; +static char __pyx_k_intp[] = "intp"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_mode[] = "mode"; +static char __pyx_k_name[] = "name"; +static char __pyx_k_ndim[] = "ndim"; +static char __pyx_k_ones[] = "ones"; +static char __pyx_k_pack[] = "pack"; +static char __pyx_k_rand[] = "rand"; +static char __pyx_k_size[] = "size"; +static char __pyx_k_step[] = "step"; +static char __pyx_k_stop[] = "stop"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_tree[] = "tree_"; +static char __pyx_k_DTYPE[] = "DTYPE"; +static char __pyx_k_class[] = "__class__"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_error[] = "error"; +static char __pyx_k_flags[] = "flags"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_scale[] = "scale"; +static char __pyx_k_shape[] = "shape"; +static char __pyx_k_stage[] = "stage"; +static char __pyx_k_start[] = "start"; +static char __pyx_k_zeros[] = "zeros"; +static char __pyx_k_format[] = "format"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_name_2[] = "__name__"; +static char __pyx_k_struct[] = "struct"; +static char __pyx_k_tree_2[] = "tree"; +static char __pyx_k_unpack[] = "unpack"; +static char __pyx_k_float32[] = "float32"; +static char __pyx_k_float64[] = "float64"; +static char __pyx_k_fortran[] = "fortran"; +static char __pyx_k_memview[] = "memview"; +static char __pyx_k_np_bool[] = "np_bool"; +static char __pyx_k_np_ones[] = "np_ones"; +static char __pyx_k_Ellipsis[] = "Ellipsis"; +static char __pyx_k_itemsize[] = "itemsize"; +static char __pyx_k_n_bagged[] = "n_bagged"; +static char __pyx_k_np_zeros[] = "np_zeros"; +static char __pyx_k_TypeError[] = "TypeError"; +static char __pyx_k_enumerate[] = "enumerate"; +static char __pyx_k_IndexError[] = "IndexError"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_estimators[] = "estimators"; +static char __pyx_k_learn_rate[] = "learn_rate"; +static char __pyx_k_np_float32[] = "np_float32"; +static char __pyx_k_np_float64[] = "np_float64"; +static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static char __pyx_k_MemoryError[] = "MemoryError"; +static char __pyx_k_sample_mask[] = "sample_mask"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_n_estimators[] = "n_estimators"; +static char __pyx_k_random_state[] = "random_state"; +static char __pyx_k_predict_stage[] = "predict_stage"; +static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k_n_total_in_bag[] = "n_total_in_bag"; +static char __pyx_k_predict_stages[] = "predict_stages"; +static char __pyx_k_target_feature[] = "target_feature"; +static char __pyx_k_allocate_buffer[] = "allocate_buffer"; +static char __pyx_k_dtype_is_object[] = "dtype_is_object"; +static char __pyx_k_n_total_samples[] = "n_total_samples"; +static char __pyx_k_random_sample_mask[] = "_random_sample_mask"; +static char __pyx_k_strided_and_direct[] = ""; +static char __pyx_k_strided_and_indirect[] = ""; +static char __pyx_k_contiguous_and_direct[] = ""; +static char __pyx_k_MemoryView_of_r_object[] = ""; +static char __pyx_k_MemoryView_of_r_at_0x_x[] = ""; +static char __pyx_k_contiguous_and_indirect[] = ""; +static char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; +static char __pyx_k_getbuffer_obj_view_flags[] = "getbuffer(obj, view, flags)"; +static char __pyx_k_Dimension_d_is_not_direct[] = "Dimension %d is not direct"; +static char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; +static char __pyx_k_Index_out_of_bounds_axis_d[] = "Index out of bounds (axis %d)"; +static char __pyx_k_Step_may_not_be_zero_axis_d[] = "Step may not be zero (axis %d)"; +static char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; +static char __pyx_k_strided_and_direct_or_indirect[] = ""; +static char __pyx_k_home_gilles_src_scikit_learn_sk[] = "/home/gilles/src/scikit-learn/sklearn/ensemble/_gradient_boosting.pyx"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_All_dimensions_preceding_dimensi[] = "All dimensions preceding dimension %d must be indexed and not sliced"; +static char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; +static char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; +static char __pyx_k_Cannot_transpose_memoryview_with[] = "Cannot transpose memoryview with indirect dimensions"; +static char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; +static char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; +static char __pyx_k_Total_weight_should_be_1_0_but_w[] = "Total weight should be 1.0 but was %.9f"; +static char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; +static char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; +static char __pyx_k_left_sample_frac_f_n_samples_cur[] = "left_sample_frac:%f, n_samples current: %d, n_samples left: %d"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_sklearn_ensemble__gradient_boost[] = "sklearn.ensemble._gradient_boosting"; +static char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; +static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; +static PyObject *__pyx_kp_s_Cannot_index_with_type_s; +static PyObject *__pyx_n_s_DTYPE; +static PyObject *__pyx_n_s_Ellipsis; +static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_n_s_IndexError; +static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; +static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; +static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; +static PyObject *__pyx_n_s_K; +static PyObject *__pyx_n_s_MemoryError; +static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; +static PyObject *__pyx_kp_s_MemoryView_of_r_object; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_b_O; +static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_kp_s_Total_weight_should_be_1_0_but_w; +static PyObject *__pyx_n_s_TypeError; +static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_n_s_allocate_buffer; +static PyObject *__pyx_n_s_base; +static PyObject *__pyx_n_s_bool; +static PyObject *__pyx_n_s_c; +static PyObject *__pyx_n_u_c; +static PyObject *__pyx_n_s_class; +static PyObject *__pyx_kp_s_contiguous_and_direct; +static PyObject *__pyx_kp_s_contiguous_and_indirect; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_dtype_is_object; +static PyObject *__pyx_n_s_enumerate; +static PyObject *__pyx_n_s_error; +static PyObject *__pyx_n_s_estimators; +static PyObject *__pyx_n_s_flags; +static PyObject *__pyx_n_s_float32; +static PyObject *__pyx_n_s_float64; +static PyObject *__pyx_n_s_format; +static PyObject *__pyx_n_s_fortran; +static PyObject *__pyx_n_u_fortran; +static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; +static PyObject *__pyx_kp_s_home_gilles_src_scikit_learn_sk; +static PyObject *__pyx_n_s_i; +static PyObject *__pyx_n_s_id; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_intp; +static PyObject *__pyx_n_s_itemsize; +static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; +static PyObject *__pyx_n_s_k; +static PyObject *__pyx_n_s_learn_rate; +static PyObject *__pyx_kp_s_left_sample_frac_f_n_samples_cur; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_memview; +static PyObject *__pyx_n_s_mode; +static PyObject *__pyx_n_s_n_bagged; +static PyObject *__pyx_n_s_n_estimators; +static PyObject *__pyx_n_s_n_total_in_bag; +static PyObject *__pyx_n_s_n_total_samples; +static PyObject *__pyx_n_s_name; +static PyObject *__pyx_n_s_name_2; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_ndim; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_np_bool; +static PyObject *__pyx_n_s_np_float32; +static PyObject *__pyx_n_s_np_float64; +static PyObject *__pyx_n_s_np_ones; +static PyObject *__pyx_n_s_np_zeros; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_obj; +static PyObject *__pyx_n_s_ones; +static PyObject *__pyx_n_s_out; +static PyObject *__pyx_n_s_pack; +static PyObject *__pyx_n_s_predict_stage; +static PyObject *__pyx_n_s_predict_stages; +static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_vtable; +static PyObject *__pyx_n_s_rand; +static PyObject *__pyx_n_s_random_sample_mask; +static PyObject *__pyx_n_s_random_state; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_sample_mask; +static PyObject *__pyx_n_s_scale; +static PyObject *__pyx_n_s_shape; +static PyObject *__pyx_n_s_size; +static PyObject *__pyx_n_s_sklearn_ensemble__gradient_boost; +static PyObject *__pyx_n_s_stage; +static PyObject *__pyx_n_s_start; +static PyObject *__pyx_n_s_step; +static PyObject *__pyx_n_s_stop; +static PyObject *__pyx_kp_s_strided_and_direct; +static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; +static PyObject *__pyx_kp_s_strided_and_indirect; +static PyObject *__pyx_n_s_struct; +static PyObject *__pyx_n_s_target_feature; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_n_s_tree; +static PyObject *__pyx_n_s_tree_2; +static PyObject *__pyx_kp_s_unable_to_allocate_array_data; +static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_unpack; +static PyObject *__pyx_n_s_zeros; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_1; +static PyObject *__pyx_int_neg_1; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__8; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_slice__15; +static PyObject *__pyx_slice__16; +static PyObject *__pyx_slice__17; +static PyObject *__pyx_tuple__10; +static PyObject *__pyx_tuple__11; +static PyObject *__pyx_tuple__12; +static PyObject *__pyx_tuple__13; +static PyObject *__pyx_tuple__14; +static PyObject *__pyx_tuple__18; +static PyObject *__pyx_tuple__19; +static PyObject *__pyx_tuple__21; +static PyObject *__pyx_tuple__23; +static PyObject *__pyx_tuple__25; +static PyObject *__pyx_tuple__26; +static PyObject *__pyx_tuple__27; +static PyObject *__pyx_tuple__28; +static PyObject *__pyx_tuple__29; +static PyObject *__pyx_codeobj__20; +static PyObject *__pyx_codeobj__22; +static PyObject *__pyx_codeobj__24; + +/* "sklearn/ensemble/_gradient_boosting.pyx":37 + * cdef int LEAF = -1 * * cdef void _predict_regression_tree_inplace_fast(DTYPE_t *X, # <<<<<<<<<<<<<< - * int *children_left, - * int *children_right, + * Node* root_node, + * double *value, */ -static void __pyx_f_7sklearn_8ensemble_18_gradient_boosting__predict_regression_tree_inplace_fast(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t *__pyx_v_X, int *__pyx_v_children_left, int *__pyx_v_children_right, int *__pyx_v_feature, double *__pyx_v_threshold, double *__pyx_v_value, double __pyx_v_scale, Py_ssize_t __pyx_v_k, Py_ssize_t __pyx_v_K, Py_ssize_t __pyx_v_n_samples, Py_ssize_t __pyx_v_n_features, __pyx_t_5numpy_float64_t *__pyx_v_out) { +static void __pyx_f_7sklearn_8ensemble_18_gradient_boosting__predict_regression_tree_inplace_fast(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t *__pyx_v_X, struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_root_node, double *__pyx_v_value, double __pyx_v_scale, Py_ssize_t __pyx_v_k, Py_ssize_t __pyx_v_K, Py_ssize_t __pyx_v_n_samples, Py_ssize_t __pyx_v_n_features, __pyx_t_7sklearn_8ensemble_18_gradient_boosting_float64 *__pyx_v_out) { Py_ssize_t __pyx_v_i; - __pyx_t_5numpy_int32_t __pyx_v_node_id; - __pyx_t_5numpy_int32_t __pyx_v_feature_idx; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_node; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; Py_ssize_t __pyx_t_2; int __pyx_t_3; int __pyx_t_4; - int __pyx_t_5; - Py_ssize_t __pyx_t_6; + Py_ssize_t __pyx_t_5; __Pyx_RefNannySetupContext("_predict_regression_tree_inplace_fast", 0); - /* "sklearn/ensemble/_gradient_boosting.pyx":82 - * cdef np.int32_t node_id - * cdef np.int32_t feature_idx + /* "sklearn/ensemble/_gradient_boosting.pyx":87 + * cdef int32 node_id + * cdef Node *node * for i in range(n_samples): # <<<<<<<<<<<<<< - * node_id = 0 - * # While node_id not a leaf + * node = root_node + * # While node not a leaf */ __pyx_t_1 = __pyx_v_n_samples; for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; - /* "sklearn/ensemble/_gradient_boosting.pyx":83 - * cdef np.int32_t feature_idx + /* "sklearn/ensemble/_gradient_boosting.pyx":88 + * cdef Node *node * for i in range(n_samples): - * node_id = 0 # <<<<<<<<<<<<<< - * # While node_id not a leaf - * while children_left[node_id] != -1 and \ + * node = root_node # <<<<<<<<<<<<<< + * # While node not a leaf + * while node.left_child != -1 and node.right_child != -1: */ - __pyx_v_node_id = 0; - - /* "sklearn/ensemble/_gradient_boosting.pyx":85 - * node_id = 0 - * # While node_id not a leaf - * while children_left[node_id] != -1 and \ # <<<<<<<<<<<<<< - * children_right[node_id] != -1: - * feature_idx = feature[node_id] + __pyx_v_node = __pyx_v_root_node; + + /* "sklearn/ensemble/_gradient_boosting.pyx":90 + * node = root_node + * # While node not a leaf + * while node.left_child != -1 and node.right_child != -1: # <<<<<<<<<<<<<< + * if X[i * n_features + node.feature] <= node.threshold: + * node = root_node + node.left_child */ while (1) { - __pyx_t_3 = ((__pyx_v_children_left[__pyx_v_node_id]) != -1); - if (__pyx_t_3) { - - /* "sklearn/ensemble/_gradient_boosting.pyx":86 - * # While node_id not a leaf - * while children_left[node_id] != -1 and \ - * children_right[node_id] != -1: # <<<<<<<<<<<<<< - * feature_idx = feature[node_id] - * if X[(i * n_features) + feature_idx] <= threshold[node_id]: - */ - __pyx_t_4 = ((__pyx_v_children_right[__pyx_v_node_id]) != -1); - __pyx_t_5 = __pyx_t_4; + __pyx_t_4 = ((__pyx_v_node->left_child != -1) != 0); + if (__pyx_t_4) { } else { - __pyx_t_5 = __pyx_t_3; + __pyx_t_3 = __pyx_t_4; + goto __pyx_L7_bool_binop_done; } - if (!__pyx_t_5) break; - - /* "sklearn/ensemble/_gradient_boosting.pyx":87 - * while children_left[node_id] != -1 and \ - * children_right[node_id] != -1: - * feature_idx = feature[node_id] # <<<<<<<<<<<<<< - * if X[(i * n_features) + feature_idx] <= threshold[node_id]: - * node_id = children_left[node_id] - */ - __pyx_v_feature_idx = (__pyx_v_feature[__pyx_v_node_id]); - - /* "sklearn/ensemble/_gradient_boosting.pyx":88 - * children_right[node_id] != -1: - * feature_idx = feature[node_id] - * if X[(i * n_features) + feature_idx] <= threshold[node_id]: # <<<<<<<<<<<<<< - * node_id = children_left[node_id] + __pyx_t_4 = ((__pyx_v_node->right_child != -1) != 0); + __pyx_t_3 = __pyx_t_4; + __pyx_L7_bool_binop_done:; + if (!__pyx_t_3) break; + + /* "sklearn/ensemble/_gradient_boosting.pyx":91 + * # While node not a leaf + * while node.left_child != -1 and node.right_child != -1: + * if X[i * n_features + node.feature] <= node.threshold: # <<<<<<<<<<<<<< + * node = root_node + node.left_child * else: */ - __pyx_t_5 = ((__pyx_v_X[((__pyx_v_i * __pyx_v_n_features) + __pyx_v_feature_idx)]) <= (__pyx_v_threshold[__pyx_v_node_id])); - if (__pyx_t_5) { + __pyx_t_3 = (((__pyx_v_X[((__pyx_v_i * __pyx_v_n_features) + __pyx_v_node->feature)]) <= __pyx_v_node->threshold) != 0); + if (__pyx_t_3) { - /* "sklearn/ensemble/_gradient_boosting.pyx":89 - * feature_idx = feature[node_id] - * if X[(i * n_features) + feature_idx] <= threshold[node_id]: - * node_id = children_left[node_id] # <<<<<<<<<<<<<< + /* "sklearn/ensemble/_gradient_boosting.pyx":92 + * while node.left_child != -1 and node.right_child != -1: + * if X[i * n_features + node.feature] <= node.threshold: + * node = root_node + node.left_child # <<<<<<<<<<<<<< * else: - * node_id = children_right[node_id] + * node = root_node + node.right_child */ - __pyx_v_node_id = (__pyx_v_children_left[__pyx_v_node_id]); - goto __pyx_L7; + __pyx_v_node = (__pyx_v_root_node + __pyx_v_node->left_child); + goto __pyx_L9; } /*else*/ { - /* "sklearn/ensemble/_gradient_boosting.pyx":91 - * node_id = children_left[node_id] + /* "sklearn/ensemble/_gradient_boosting.pyx":94 + * node = root_node + node.left_child * else: - * node_id = children_right[node_id] # <<<<<<<<<<<<<< - * out[(i * K) + k] += scale * value[node_id] + * node = root_node + node.right_child # <<<<<<<<<<<<<< + * out[i * K + k] += scale * value[node - root_node] * */ - __pyx_v_node_id = (__pyx_v_children_right[__pyx_v_node_id]); + __pyx_v_node = (__pyx_v_root_node + __pyx_v_node->right_child); } - __pyx_L7:; + __pyx_L9:; } - /* "sklearn/ensemble/_gradient_boosting.pyx":92 + /* "sklearn/ensemble/_gradient_boosting.pyx":95 * else: - * node_id = children_right[node_id] - * out[(i * K) + k] += scale * value[node_id] # <<<<<<<<<<<<<< + * node = root_node + node.right_child + * out[i * K + k] += scale * value[node - root_node] # <<<<<<<<<<<<<< * * */ - __pyx_t_6 = ((__pyx_v_i * __pyx_v_K) + __pyx_v_k); - (__pyx_v_out[__pyx_t_6]) = ((__pyx_v_out[__pyx_t_6]) + (__pyx_v_scale * (__pyx_v_value[__pyx_v_node_id]))); + __pyx_t_5 = ((__pyx_v_i * __pyx_v_K) + __pyx_v_k); + (__pyx_v_out[__pyx_t_5]) = ((__pyx_v_out[__pyx_t_5]) + (__pyx_v_scale * (__pyx_v_value[(__pyx_v_node - __pyx_v_root_node)]))); } + /* "sklearn/ensemble/_gradient_boosting.pyx":37 + * cdef int LEAF = -1 + * + * cdef void _predict_regression_tree_inplace_fast(DTYPE_t *X, # <<<<<<<<<<<<<< + * Node* root_node, + * double *value, + */ + + /* function exit code */ __Pyx_RefNannyFinishContext(); } +/* "sklearn/ensemble/_gradient_boosting.pyx":99 + * + * @cython.nonecheck(False) + * def predict_stages(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X, double scale, + * np.ndarray[float64, ndim=2] out): + */ + /* Python wrapper */ static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_1predict_stages(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_7sklearn_8ensemble_18_gradient_boosting_predict_stages[] = "Add predictions of ``estimators`` to ``out``.\n\n Each estimator is scaled by ``scale`` before its prediction\n is added to ``out``.\n "; -static PyMethodDef __pyx_mdef_7sklearn_8ensemble_18_gradient_boosting_1predict_stages = {__Pyx_NAMESTR("predict_stages"), (PyCFunction)__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_1predict_stages, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_8ensemble_18_gradient_boosting_predict_stages)}; +static PyMethodDef __pyx_mdef_7sklearn_8ensemble_18_gradient_boosting_1predict_stages = {"predict_stages", (PyCFunction)__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_1predict_stages, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_8ensemble_18_gradient_boosting_predict_stages}; static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_1predict_stages(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_estimators = 0; PyArrayObject *__pyx_v_X = 0; double __pyx_v_scale; PyArrayObject *__pyx_v_out = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__estimators,&__pyx_n_s__X,&__pyx_n_s__scale,&__pyx_n_s__out,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("predict_stages (wrapper)", 0); - __pyx_self = __pyx_self; { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_estimators,&__pyx_n_s_X,&__pyx_n_s_scale,&__pyx_n_s_out,0}; PyObject* values[4] = {0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; @@ -1399,30 +2338,26 @@ static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_1predict_stage kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__estimators); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_estimators)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_stages", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_stages", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_scale)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_stages", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_stages", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__out); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_stages", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_stages", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "predict_stages") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "predict_stages") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { goto __pyx_L5_argtuple_error; @@ -1434,21 +2369,23 @@ static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_1predict_stage } __pyx_v_estimators = ((PyArrayObject *)values[0]); __pyx_v_X = ((PyArrayObject *)values[1]); - __pyx_v_scale = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_scale == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_scale = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_scale == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_out = ((PyArrayObject *)values[3]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("predict_stages", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_stages", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.ensemble._gradient_boosting.predict_stages", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_estimators), __pyx_ptype_5numpy_ndarray, 1, "estimators", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_out), __pyx_ptype_5numpy_ndarray, 1, "out", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_estimators), __pyx_ptype_5numpy_ndarray, 1, "estimators", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_out), __pyx_ptype_5numpy_ndarray, 1, "out", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_7sklearn_8ensemble_18_gradient_boosting_predict_stages(__pyx_self, __pyx_v_estimators, __pyx_v_X, __pyx_v_scale, __pyx_v_out); + + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -1457,20 +2394,10 @@ static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_1predict_stage return __pyx_r; } -/* "sklearn/ensemble/_gradient_boosting.pyx":96 - * - * @cython.nonecheck(False) - * def predict_stages(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< - * np.ndarray[DTYPE_t, ndim=2, mode='c'] X, double scale, - * np.ndarray[np.float64_t, ndim=2] out): - */ - static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_predict_stages(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_estimators, PyArrayObject *__pyx_v_X, double __pyx_v_scale, PyArrayObject *__pyx_v_out) { Py_ssize_t __pyx_v_i; Py_ssize_t __pyx_v_k; Py_ssize_t __pyx_v_n_estimators; - Py_ssize_t __pyx_v_n_samples; - Py_ssize_t __pyx_v_n_features; Py_ssize_t __pyx_v_K; struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree = 0; __Pyx_LocalBuf_ND __pyx_pybuffernd_X; @@ -1488,6 +2415,7 @@ static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_predict_stages PyObject *__pyx_t_5 = NULL; Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; @@ -1506,109 +2434,103 @@ static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_predict_stages __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_estimators.rcbuffer->pybuffer, (PyObject*)__pyx_v_estimators, &__Pyx_TypeInfo_object, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_estimators.rcbuffer->pybuffer, (PyObject*)__pyx_v_estimators, &__Pyx_TypeInfo_object, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_estimators.diminfo[0].strides = __pyx_pybuffernd_estimators.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_estimators.diminfo[0].shape = __pyx_pybuffernd_estimators.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_estimators.diminfo[1].strides = __pyx_pybuffernd_estimators.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_estimators.diminfo[1].shape = __pyx_pybuffernd_estimators.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_v_out, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_v_out, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_float64, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_out.diminfo[1].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_out.diminfo[1].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[1]; - /* "sklearn/ensemble/_gradient_boosting.pyx":106 + /* "sklearn/ensemble/_gradient_boosting.pyx":109 * cdef Py_ssize_t i * cdef Py_ssize_t k * cdef Py_ssize_t n_estimators = estimators.shape[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t n_samples = X.shape[0] - * cdef Py_ssize_t n_features = X.shape[1] + * cdef Py_ssize_t K = estimators.shape[1] + * cdef Tree tree */ __pyx_v_n_estimators = (__pyx_v_estimators->dimensions[0]); - /* "sklearn/ensemble/_gradient_boosting.pyx":107 + /* "sklearn/ensemble/_gradient_boosting.pyx":110 * cdef Py_ssize_t k * cdef Py_ssize_t n_estimators = estimators.shape[0] - * cdef Py_ssize_t n_samples = X.shape[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t n_features = X.shape[1] - * cdef Py_ssize_t K = estimators.shape[1] - */ - __pyx_v_n_samples = (__pyx_v_X->dimensions[0]); - - /* "sklearn/ensemble/_gradient_boosting.pyx":108 - * cdef Py_ssize_t n_estimators = estimators.shape[0] - * cdef Py_ssize_t n_samples = X.shape[0] - * cdef Py_ssize_t n_features = X.shape[1] # <<<<<<<<<<<<<< - * cdef Py_ssize_t K = estimators.shape[1] - * cdef Tree tree - */ - __pyx_v_n_features = (__pyx_v_X->dimensions[1]); - - /* "sklearn/ensemble/_gradient_boosting.pyx":109 - * cdef Py_ssize_t n_samples = X.shape[0] - * cdef Py_ssize_t n_features = X.shape[1] * cdef Py_ssize_t K = estimators.shape[1] # <<<<<<<<<<<<<< * cdef Tree tree * */ __pyx_v_K = (__pyx_v_estimators->dimensions[1]); - /* "sklearn/ensemble/_gradient_boosting.pyx":112 + /* "sklearn/ensemble/_gradient_boosting.pyx":113 * cdef Tree tree * * for i in range(n_estimators): # <<<<<<<<<<<<<< * for k in range(K): - * tree = estimators[i, k] + * tree = estimators[i, k].tree_ */ __pyx_t_1 = __pyx_v_n_estimators; for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; - /* "sklearn/ensemble/_gradient_boosting.pyx":113 + /* "sklearn/ensemble/_gradient_boosting.pyx":114 * * for i in range(n_estimators): * for k in range(K): # <<<<<<<<<<<<<< - * tree = estimators[i, k] + * tree = estimators[i, k].tree_ * */ __pyx_t_3 = __pyx_v_K; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_k = __pyx_t_4; - /* "sklearn/ensemble/_gradient_boosting.pyx":114 + /* "sklearn/ensemble/_gradient_boosting.pyx":115 * for i in range(n_estimators): * for k in range(K): - * tree = estimators[i, k] # <<<<<<<<<<<<<< + * tree = estimators[i, k].tree_ # <<<<<<<<<<<<<< * * # avoid buffer validation by casting to ndarray */ __pyx_t_6 = __pyx_v_i; __pyx_t_7 = __pyx_v_k; - __pyx_t_5 = *__Pyx_BufPtrStrided2d(PyObject **, __pyx_pybuffernd_estimators.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_estimators.diminfo[0].strides, __pyx_t_7, __pyx_pybuffernd_estimators.diminfo[1].strides); + __pyx_t_5 = (PyObject *) *__Pyx_BufPtrStrided2d(PyObject **, __pyx_pybuffernd_estimators.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_estimators.diminfo[0].strides, __pyx_t_7, __pyx_pybuffernd_estimators.diminfo[1].strides); __Pyx_INCREF((PyObject*)__pyx_t_5); - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_7sklearn_4tree_5_tree_Tree))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_tree)); - __pyx_v_tree = ((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_t_5); - __pyx_t_5 = 0; + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_tree); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_8) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_8, __pyx_ptype_7sklearn_4tree_5_tree_Tree))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_tree, ((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_t_8)); + __pyx_t_8 = 0; - /* "sklearn/ensemble/_gradient_boosting.pyx":127 - * tree.value, - * scale, k, K, n_samples, n_features, - * ((out).data)) # <<<<<<<<<<<<<< - * - * + /* "sklearn/ensemble/_gradient_boosting.pyx":120 + * # and get data pointer + * # need brackets because of casting operator priority + * _predict_regression_tree_inplace_fast( # <<<<<<<<<<<<<< + * X.data, + * tree.nodes, tree.value, */ - __pyx_f_7sklearn_8ensemble_18_gradient_boosting__predict_regression_tree_inplace_fast(((__pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t *)__pyx_v_X->data), __pyx_v_tree->children_left, __pyx_v_tree->children_right, __pyx_v_tree->feature, __pyx_v_tree->threshold, __pyx_v_tree->value, __pyx_v_scale, __pyx_v_k, __pyx_v_K, __pyx_v_n_samples, __pyx_v_n_features, ((__pyx_t_5numpy_float64_t *)((PyArrayObject *)__pyx_v_out)->data)); + __pyx_f_7sklearn_8ensemble_18_gradient_boosting__predict_regression_tree_inplace_fast(((__pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t *)__pyx_v_X->data), __pyx_v_tree->nodes, __pyx_v_tree->value, __pyx_v_scale, __pyx_v_k, __pyx_v_K, (__pyx_v_X->dimensions[0]), (__pyx_v_X->dimensions[1]), ((__pyx_t_7sklearn_8ensemble_18_gradient_boosting_float64 *)((PyArrayObject *)__pyx_v_out)->data)); } } + /* "sklearn/ensemble/_gradient_boosting.pyx":99 + * + * @cython.nonecheck(False) + * def predict_stages(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X, double scale, + * np.ndarray[float64, ndim=2] out): + */ + + /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_8); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); @@ -1629,22 +2551,32 @@ static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_predict_stages return __pyx_r; } +/* "sklearn/ensemble/_gradient_boosting.pyx":129 + * + * @cython.nonecheck(False) + * def predict_stage(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< + * int stage, + * np.ndarray[DTYPE_t, ndim=2] X, double scale, + */ + /* Python wrapper */ static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_3predict_stage(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_7sklearn_8ensemble_18_gradient_boosting_2predict_stage[] = "Add predictions of ``estimators[stage]`` to ``out``.\n\n Each estimator in the stage is scaled by ``scale`` before\n its prediction is added to ``out``.\n "; -static PyMethodDef __pyx_mdef_7sklearn_8ensemble_18_gradient_boosting_3predict_stage = {__Pyx_NAMESTR("predict_stage"), (PyCFunction)__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_3predict_stage, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_8ensemble_18_gradient_boosting_2predict_stage)}; +static PyMethodDef __pyx_mdef_7sklearn_8ensemble_18_gradient_boosting_3predict_stage = {"predict_stage", (PyCFunction)__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_3predict_stage, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_8ensemble_18_gradient_boosting_2predict_stage}; static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_3predict_stage(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_estimators = 0; int __pyx_v_stage; PyArrayObject *__pyx_v_X = 0; double __pyx_v_scale; PyArrayObject *__pyx_v_out = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__estimators,&__pyx_n_s__stage,&__pyx_n_s__X,&__pyx_n_s__scale,&__pyx_n_s__out,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("predict_stage (wrapper)", 0); - __pyx_self = __pyx_self; { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_estimators,&__pyx_n_s_stage,&__pyx_n_s_X,&__pyx_n_s_scale,&__pyx_n_s_out,0}; PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; @@ -1661,36 +2593,31 @@ static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_3predict_stage kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__estimators); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_estimators)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__stage); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_stage)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_stage", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_stage", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_stage", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_stage", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_scale)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_stage", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_stage", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__out); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_stage", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_stage", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "predict_stage") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "predict_stage") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { goto __pyx_L5_argtuple_error; @@ -1702,23 +2629,25 @@ static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_3predict_stage values[4] = PyTuple_GET_ITEM(__pyx_args, 4); } __pyx_v_estimators = ((PyArrayObject *)values[0]); - __pyx_v_stage = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_stage == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_stage = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_stage == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_X = ((PyArrayObject *)values[2]); - __pyx_v_scale = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_scale == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_scale = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_scale == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_out = ((PyArrayObject *)values[4]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("predict_stage", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_stage", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.ensemble._gradient_boosting.predict_stage", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_estimators), __pyx_ptype_5numpy_ndarray, 1, "estimators", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_out), __pyx_ptype_5numpy_ndarray, 1, "out", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_estimators), __pyx_ptype_5numpy_ndarray, 1, "estimators", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_out), __pyx_ptype_5numpy_ndarray, 1, "out", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_7sklearn_8ensemble_18_gradient_boosting_2predict_stage(__pyx_self, __pyx_v_estimators, __pyx_v_stage, __pyx_v_X, __pyx_v_scale, __pyx_v_out); + + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -1727,21 +2656,7 @@ static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_3predict_stage return __pyx_r; } -/* "sklearn/ensemble/_gradient_boosting.pyx":131 - * - * @cython.nonecheck(False) - * def predict_stage(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< - * int stage, - * np.ndarray[DTYPE_t, ndim=2] X, double scale, - */ - static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_2predict_stage(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_estimators, int __pyx_v_stage, PyArrayObject *__pyx_v_X, double __pyx_v_scale, PyArrayObject *__pyx_v_out) { - Py_ssize_t __pyx_v_k; - CYTHON_UNUSED Py_ssize_t __pyx_v_n_estimators; - Py_ssize_t __pyx_v_n_samples; - Py_ssize_t __pyx_v_n_features; - Py_ssize_t __pyx_v_K; - struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree = 0; __Pyx_LocalBuf_ND __pyx_pybuffernd_X; __Pyx_Buffer __pyx_pybuffer_X; __Pyx_LocalBuf_ND __pyx_pybuffernd_estimators; @@ -1750,11 +2665,13 @@ static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_2predict_stage __Pyx_Buffer __pyx_pybuffer_out; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - Py_ssize_t __pyx_t_5; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; @@ -1773,96 +2690,87 @@ static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_2predict_stage __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_estimators.rcbuffer->pybuffer, (PyObject*)__pyx_v_estimators, &__Pyx_TypeInfo_object, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_estimators.rcbuffer->pybuffer, (PyObject*)__pyx_v_estimators, &__Pyx_TypeInfo_object, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_estimators.diminfo[0].strides = __pyx_pybuffernd_estimators.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_estimators.diminfo[0].shape = __pyx_pybuffernd_estimators.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_estimators.diminfo[1].strides = __pyx_pybuffernd_estimators.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_estimators.diminfo[1].shape = __pyx_pybuffernd_estimators.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_v_out, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_v_out, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_float64, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_out.diminfo[1].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_out.diminfo[1].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[1]; - /* "sklearn/ensemble/_gradient_boosting.pyx":142 - * cdef Py_ssize_t i - * cdef Py_ssize_t k - * cdef Py_ssize_t n_estimators = estimators.shape[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t n_samples = X.shape[0] - * cdef Py_ssize_t n_features = X.shape[1] - */ - __pyx_v_n_estimators = (__pyx_v_estimators->dimensions[0]); - - /* "sklearn/ensemble/_gradient_boosting.pyx":143 - * cdef Py_ssize_t k - * cdef Py_ssize_t n_estimators = estimators.shape[0] - * cdef Py_ssize_t n_samples = X.shape[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t n_features = X.shape[1] - * cdef Py_ssize_t K = estimators.shape[1] - */ - __pyx_v_n_samples = (__pyx_v_X->dimensions[0]); - - /* "sklearn/ensemble/_gradient_boosting.pyx":144 - * cdef Py_ssize_t n_estimators = estimators.shape[0] - * cdef Py_ssize_t n_samples = X.shape[0] - * cdef Py_ssize_t n_features = X.shape[1] # <<<<<<<<<<<<<< - * cdef Py_ssize_t K = estimators.shape[1] - * cdef Tree tree - */ - __pyx_v_n_features = (__pyx_v_X->dimensions[1]); - - /* "sklearn/ensemble/_gradient_boosting.pyx":145 - * cdef Py_ssize_t n_samples = X.shape[0] - * cdef Py_ssize_t n_features = X.shape[1] - * cdef Py_ssize_t K = estimators.shape[1] # <<<<<<<<<<<<<< - * cdef Tree tree - * for k in range(K): - */ - __pyx_v_K = (__pyx_v_estimators->dimensions[1]); - - /* "sklearn/ensemble/_gradient_boosting.pyx":147 - * cdef Py_ssize_t K = estimators.shape[1] - * cdef Tree tree - * for k in range(K): # <<<<<<<<<<<<<< - * tree = estimators[stage, k] + /* "sklearn/ensemble/_gradient_boosting.pyx":138 + * its prediction is added to ``out``. + * """ + * return predict_stages(estimators[stage:stage + 1], X, scale, out) # <<<<<<<<<<<<<< + * * */ - __pyx_t_1 = __pyx_v_K; - for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { - __pyx_v_k = __pyx_t_2; - - /* "sklearn/ensemble/_gradient_boosting.pyx":148 - * cdef Tree tree - * for k in range(K): - * tree = estimators[stage, k] # <<<<<<<<<<<<<< - * - * _predict_regression_tree_inplace_fast( - */ - __pyx_t_4 = __pyx_v_stage; - __pyx_t_5 = __pyx_v_k; - __pyx_t_3 = *__Pyx_BufPtrStrided2d(PyObject **, __pyx_pybuffernd_estimators.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_estimators.diminfo[0].strides, __pyx_t_5, __pyx_pybuffernd_estimators.diminfo[1].strides); - __Pyx_INCREF((PyObject*)__pyx_t_3); - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_7sklearn_4tree_5_tree_Tree))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_tree)); - __pyx_v_tree = ((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_t_3); - __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_predict_stages); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetSlice(((PyObject *)__pyx_v_estimators), __pyx_v_stage, (__pyx_v_stage + 1), NULL, NULL, NULL, 1, 1, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyFloat_FromDouble(__pyx_v_scale); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = NULL; + __pyx_t_6 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_6 = 1; + } + } + __pyx_t_7 = PyTuple_New(4+__pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (__pyx_t_5) { + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; + } + PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_X)); + PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, ((PyObject *)__pyx_v_X)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_X)); + PyTuple_SET_ITEM(__pyx_t_7, 2+__pyx_t_6, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_out)); + PyTuple_SET_ITEM(__pyx_t_7, 3+__pyx_t_6, ((PyObject *)__pyx_v_out)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_out)); + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; - /* "sklearn/ensemble/_gradient_boosting.pyx":158 - * tree.value, - * scale, k, K, n_samples, n_features, - * ((out).data)) # <<<<<<<<<<<<<< + /* "sklearn/ensemble/_gradient_boosting.pyx":129 * + * @cython.nonecheck(False) + * def predict_stage(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< + * int stage, + * np.ndarray[DTYPE_t, ndim=2] X, double scale, */ - __pyx_f_7sklearn_8ensemble_18_gradient_boosting__predict_regression_tree_inplace_fast(((__pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t *)__pyx_v_X->data), __pyx_v_tree->children_left, __pyx_v_tree->children_right, __pyx_v_tree->feature, __pyx_v_tree->threshold, __pyx_v_tree->value, __pyx_v_scale, __pyx_v_k, __pyx_v_K, __pyx_v_n_samples, __pyx_v_n_features, ((__pyx_t_5numpy_float64_t *)((PyArrayObject *)__pyx_v_out)->data)); - } - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); @@ -1877,3443 +2785,18037 @@ static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_2predict_stage __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_estimators.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_tree); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* Python wrapper */ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +/* "sklearn/ensemble/_gradient_boosting.pyx":141 + * + * + * cdef inline int array_index(int32 val, int32[::1] arr): # <<<<<<<<<<<<<< + * """Find index of ``val`` in array ``arr``. """ + * cdef int32 res = -1 + */ + +static CYTHON_INLINE int __pyx_f_7sklearn_8ensemble_18_gradient_boosting_array_index(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32 __pyx_v_val, __Pyx_memviewslice __pyx_v_arr) { + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32 __pyx_v_res; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32 __pyx_v_i; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32 __pyx_v_n; int __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32 __pyx_t_1; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32 __pyx_t_2; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32 __pyx_t_3; + int __pyx_t_4; + __Pyx_RefNannySetupContext("array_index", 0); + + /* "sklearn/ensemble/_gradient_boosting.pyx":143 + * cdef inline int array_index(int32 val, int32[::1] arr): + * """Find index of ``val`` in array ``arr``. """ + * cdef int32 res = -1 # <<<<<<<<<<<<<< + * cdef int32 i = 0 + * cdef int32 n = arr.shape[0] + */ + __pyx_v_res = -1; + + /* "sklearn/ensemble/_gradient_boosting.pyx":144 + * """Find index of ``val`` in array ``arr``. """ + * cdef int32 res = -1 + * cdef int32 i = 0 # <<<<<<<<<<<<<< + * cdef int32 n = arr.shape[0] + * for i in range(n): + */ + __pyx_v_i = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":145 + * cdef int32 res = -1 + * cdef int32 i = 0 + * cdef int32 n = arr.shape[0] # <<<<<<<<<<<<<< + * for i in range(n): + * if arr[i] == val: + */ + __pyx_v_n = (__pyx_v_arr.shape[0]); + + /* "sklearn/ensemble/_gradient_boosting.pyx":146 + * cdef int32 i = 0 + * cdef int32 n = arr.shape[0] + * for i in range(n): # <<<<<<<<<<<<<< + * if arr[i] == val: + * res = i + */ + __pyx_t_1 = __pyx_v_n; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "sklearn/ensemble/_gradient_boosting.pyx":147 + * cdef int32 n = arr.shape[0] + * for i in range(n): + * if arr[i] == val: # <<<<<<<<<<<<<< + * res = i + * break + */ + __pyx_t_3 = __pyx_v_i; + __pyx_t_4 = (((*((__pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32 *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32 *) __pyx_v_arr.data) + __pyx_t_3)) ))) == __pyx_v_val) != 0); + if (__pyx_t_4) { + + /* "sklearn/ensemble/_gradient_boosting.pyx":148 + * for i in range(n): + * if arr[i] == val: + * res = i # <<<<<<<<<<<<<< + * break + * return res + */ + __pyx_v_res = __pyx_v_i; + + /* "sklearn/ensemble/_gradient_boosting.pyx":149 + * if arr[i] == val: + * res = i + * break # <<<<<<<<<<<<<< + * return res + * + */ + goto __pyx_L4_break; + } + } + __pyx_L4_break:; + + /* "sklearn/ensemble/_gradient_boosting.pyx":150 + * res = i + * break + * return res # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_res; + goto __pyx_L0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":141 + * + * + * cdef inline int array_index(int32 val, int32[::1] arr): # <<<<<<<<<<<<<< + * """Find index of ``val`` in array ``arr``. """ + * cdef int32 res = -1 + */ + + /* function exit code */ + __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":193 - * # experimental exception made for __getbuffer__ and __releasebuffer__ - * # -- the details of this may change. - * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< - * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP. +/* "sklearn/ensemble/_gradient_boosting.pyx":153 + * + * + * cpdef _partial_dependence_tree(Tree tree, DTYPE_t[:, ::1] X, # <<<<<<<<<<<<<< + * int32[::1] target_feature, + * double learn_rate, */ -static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_v_copy_shape; - int __pyx_v_i; - int __pyx_v_ndim; - int __pyx_v_endian_detector; - int __pyx_v_little_endian; - int __pyx_v_t; - char *__pyx_v_f; - PyArray_Descr *__pyx_v_descr = 0; - int __pyx_v_offset; - int __pyx_v_hasfields; - int __pyx_r; +static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_5_partial_dependence_tree(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyObject *__pyx_f_7sklearn_8ensemble_18_gradient_boosting__partial_dependence_tree(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_target_feature, double __pyx_v_learn_rate, __Pyx_memviewslice __pyx_v_out, CYTHON_UNUSED int __pyx_skip_dispatch) { + Py_ssize_t __pyx_v_i; + CYTHON_UNUSED Py_ssize_t __pyx_v_n_features; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_root_node; + double *__pyx_v_value; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_SIZE_t __pyx_v_node_count; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_SIZE_t __pyx_v_stack_capacity; + struct __pyx_t_7sklearn_4tree_5_tree_Node **__pyx_v_node_stack; + __Pyx_memviewslice __pyx_v_weight_stack = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_SIZE_t __pyx_v_stack_size; + double __pyx_v_left_sample_frac; + double __pyx_v_current_weight; + double __pyx_v_total_weight; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_current_node; + PyObject *__pyx_v_underlying_stack = NULL; + int __pyx_v_feature_index; + PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_t_1; + double *__pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_3; PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - char *__pyx_t_9; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + __Pyx_memviewslice __pyx_t_8 = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + int __pyx_t_13; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_SIZE_t __pyx_t_14; + Py_ssize_t __pyx_t_15; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_SIZE_t __pyx_t_16; + Py_ssize_t __pyx_t_17; + int __pyx_t_18; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_SIZE_t __pyx_t_19; + int __pyx_t_20; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_SIZE_t __pyx_t_21; + __pyx_t_7sklearn_8ensemble_18_gradient_boosting_SIZE_t __pyx_t_22; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__", 0); - if (__pyx_v_info != NULL) { - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); - } + __Pyx_RefNannySetupContext("_partial_dependence_tree", 0); - /* "numpy.pxd":199 - * # of flags - * - * if info == NULL: return # <<<<<<<<<<<<<< - * - * cdef int copy_shape, i, ndim + /* "sklearn/ensemble/_gradient_boosting.pyx":188 + * point. + * """ + * cdef Py_ssize_t i = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t n_features = X.shape[1] + * cdef Node* root_node = tree.nodes */ - __pyx_t_1 = (__pyx_v_info == NULL); - if (__pyx_t_1) { - __pyx_r = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; + __pyx_v_i = 0; - /* "numpy.pxd":202 - * - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * + /* "sklearn/ensemble/_gradient_boosting.pyx":189 + * """ + * cdef Py_ssize_t i = 0 + * cdef Py_ssize_t n_features = X.shape[1] # <<<<<<<<<<<<<< + * cdef Node* root_node = tree.nodes + * cdef double *value = tree.value */ - __pyx_v_endian_detector = 1; + __pyx_v_n_features = (__pyx_v_X.shape[1]); - /* "numpy.pxd":203 - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< - * - * ndim = PyArray_NDIM(self) + /* "sklearn/ensemble/_gradient_boosting.pyx":190 + * cdef Py_ssize_t i = 0 + * cdef Py_ssize_t n_features = X.shape[1] + * cdef Node* root_node = tree.nodes # <<<<<<<<<<<<<< + * cdef double *value = tree.value + * cdef SIZE_t node_count = tree.node_count */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + __pyx_t_1 = __pyx_v_tree->nodes; + __pyx_v_root_node = __pyx_t_1; - /* "numpy.pxd":205 - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * - * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + /* "sklearn/ensemble/_gradient_boosting.pyx":191 + * cdef Py_ssize_t n_features = X.shape[1] + * cdef Node* root_node = tree.nodes + * cdef double *value = tree.value # <<<<<<<<<<<<<< + * cdef SIZE_t node_count = tree.node_count * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + __pyx_t_2 = __pyx_v_tree->value; + __pyx_v_value = __pyx_t_2; - /* "numpy.pxd":207 - * ndim = PyArray_NDIM(self) + /* "sklearn/ensemble/_gradient_boosting.pyx":192 + * cdef Node* root_node = tree.nodes + * cdef double *value = tree.value + * cdef SIZE_t node_count = tree.node_count # <<<<<<<<<<<<<< * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * copy_shape = 1 - * else: + * cdef SIZE_t stack_capacity = node_count * 2 */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); - if (__pyx_t_1) { + __pyx_t_3 = __pyx_v_tree->node_count; + __pyx_v_node_count = __pyx_t_3; - /* "numpy.pxd":208 + /* "sklearn/ensemble/_gradient_boosting.pyx":194 + * cdef SIZE_t node_count = tree.node_count * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * copy_shape = 1 # <<<<<<<<<<<<<< - * else: - * copy_shape = 0 + * cdef SIZE_t stack_capacity = node_count * 2 # <<<<<<<<<<<<<< + * cdef Node **node_stack + * cdef double[::1] weight_stack = np_ones((stack_capacity,), dtype=np_float64) */ - __pyx_v_copy_shape = 1; - goto __pyx_L4; - } - /*else*/ { + __pyx_v_stack_capacity = (__pyx_v_node_count * 2); + + /* "sklearn/ensemble/_gradient_boosting.pyx":196 + * cdef SIZE_t stack_capacity = node_count * 2 + * cdef Node **node_stack + * cdef double[::1] weight_stack = np_ones((stack_capacity,), dtype=np_float64) # <<<<<<<<<<<<<< + * cdef SIZE_t stack_size = 1 + * cdef double left_sample_frac + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np_ones); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_stack_capacity); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np_float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, __pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_8 = __Pyx_PyObject_to_MemoryviewSlice_dc_double(__pyx_t_7); + if (unlikely(!__pyx_t_8.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_weight_stack = __pyx_t_8; + __pyx_t_8.memview = NULL; + __pyx_t_8.data = NULL; + + /* "sklearn/ensemble/_gradient_boosting.pyx":197 + * cdef Node **node_stack + * cdef double[::1] weight_stack = np_ones((stack_capacity,), dtype=np_float64) + * cdef SIZE_t stack_size = 1 # <<<<<<<<<<<<<< + * cdef double left_sample_frac + * cdef double current_weight + */ + __pyx_v_stack_size = 1; + + /* "sklearn/ensemble/_gradient_boosting.pyx":200 + * cdef double left_sample_frac + * cdef double current_weight + * cdef double total_weight = 0.0 # <<<<<<<<<<<<<< + * cdef Node *current_node + * underlying_stack = np_zeros((stack_capacity,), dtype=np.intp) + */ + __pyx_v_total_weight = 0.0; - /* "numpy.pxd":210 - * copy_shape = 1 - * else: - * copy_shape = 0 # <<<<<<<<<<<<<< + /* "sklearn/ensemble/_gradient_boosting.pyx":202 + * cdef double total_weight = 0.0 + * cdef Node *current_node + * underlying_stack = np_zeros((stack_capacity,), dtype=np.intp) # <<<<<<<<<<<<<< + * node_stack = ( underlying_stack).data * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ - __pyx_v_copy_shape = 0; - } - __pyx_L4:; - - /* "numpy.pxd":212 - * copy_shape = 0 + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np_zeros); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_stack_capacity); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_intp); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_6, __pyx_t_5); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_underlying_stack = __pyx_t_9; + __pyx_t_9 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":203 + * cdef Node *current_node + * underlying_stack = np_zeros((stack_capacity,), dtype=np.intp) + * node_stack = ( underlying_stack).data # <<<<<<<<<<<<<< * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") + * for i in range(X.shape[0]): */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); - if (__pyx_t_1) { + __pyx_v_node_stack = ((struct __pyx_t_7sklearn_4tree_5_tree_Node **)((PyArrayObject *)__pyx_v_underlying_stack)->data); - /* "numpy.pxd":213 - * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not C contiguous") + /* "sklearn/ensemble/_gradient_boosting.pyx":205 + * node_stack = ( underlying_stack).data * + * for i in range(X.shape[0]): # <<<<<<<<<<<<<< + * # init stacks for new example + * stack_size = 1 */ - __pyx_t_2 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS)); - __pyx_t_3 = __pyx_t_2; - } else { - __pyx_t_3 = __pyx_t_1; - } - if (__pyx_t_3) { + __pyx_t_10 = (__pyx_v_X.shape[0]); + for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) { + __pyx_v_i = __pyx_t_11; + + /* "sklearn/ensemble/_gradient_boosting.pyx":207 + * for i in range(X.shape[0]): + * # init stacks for new example + * stack_size = 1 # <<<<<<<<<<<<<< + * node_stack[0] = root_node + * weight_stack[0] = 1.0 + */ + __pyx_v_stack_size = 1; + + /* "sklearn/ensemble/_gradient_boosting.pyx":208 + * # init stacks for new example + * stack_size = 1 + * node_stack[0] = root_node # <<<<<<<<<<<<<< + * weight_stack[0] = 1.0 + * total_weight = 0.0 + */ + (__pyx_v_node_stack[0]) = __pyx_v_root_node; - /* "numpy.pxd":214 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + /* "sklearn/ensemble/_gradient_boosting.pyx":209 + * stack_size = 1 + * node_stack[0] = root_node + * weight_stack[0] = 1.0 # <<<<<<<<<<<<<< + * total_weight = 0.0 * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; + __pyx_t_12 = 0; + *((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_weight_stack.data) + __pyx_t_12)) )) = 1.0; - /* "numpy.pxd":216 - * raise ValueError(u"ndarray is not C contiguous") + /* "sklearn/ensemble/_gradient_boosting.pyx":210 + * node_stack[0] = root_node + * weight_stack[0] = 1.0 + * total_weight = 0.0 # <<<<<<<<<<<<<< * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") + * while stack_size > 0: */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); - if (__pyx_t_3) { + __pyx_v_total_weight = 0.0; - /* "numpy.pxd":217 + /* "sklearn/ensemble/_gradient_boosting.pyx":212 + * total_weight = 0.0 * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not Fortran contiguous") + * while stack_size > 0: # <<<<<<<<<<<<<< + * # get top node on stack + * stack_size -= 1 + */ + while (1) { + __pyx_t_13 = ((__pyx_v_stack_size > 0) != 0); + if (!__pyx_t_13) break; + + /* "sklearn/ensemble/_gradient_boosting.pyx":214 + * while stack_size > 0: + * # get top node on stack + * stack_size -= 1 # <<<<<<<<<<<<<< + * current_node = node_stack[stack_size] * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS)); - __pyx_t_2 = __pyx_t_1; - } else { - __pyx_t_2 = __pyx_t_3; - } - if (__pyx_t_2) { + __pyx_v_stack_size = (__pyx_v_stack_size - 1); - /* "numpy.pxd":218 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + /* "sklearn/ensemble/_gradient_boosting.pyx":215 + * # get top node on stack + * stack_size -= 1 + * current_node = node_stack[stack_size] # <<<<<<<<<<<<<< * - * info.buf = PyArray_DATA(self) + * if current_node.left_child == LEAF: */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; + __pyx_v_current_node = (__pyx_v_node_stack[__pyx_v_stack_size]); - /* "numpy.pxd":220 - * raise ValueError(u"ndarray is not Fortran contiguous") + /* "sklearn/ensemble/_gradient_boosting.pyx":217 + * current_node = node_stack[stack_size] * - * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< - * info.ndim = ndim - * if copy_shape: + * if current_node.left_child == LEAF: # <<<<<<<<<<<<<< + * out[i] += weight_stack[stack_size] * value[current_node - root_node] * \ + * learn_rate */ - __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + __pyx_t_13 = ((__pyx_v_current_node->left_child == __pyx_v_7sklearn_8ensemble_18_gradient_boosting_LEAF) != 0); + if (__pyx_t_13) { - /* "numpy.pxd":221 + /* "sklearn/ensemble/_gradient_boosting.pyx":218 * - * info.buf = PyArray_DATA(self) - * info.ndim = ndim # <<<<<<<<<<<<<< - * if copy_shape: - * # Allocate new buffer for strides and shape info. - */ - __pyx_v_info->ndim = __pyx_v_ndim; - - /* "numpy.pxd":222 - * info.buf = PyArray_DATA(self) - * info.ndim = ndim - * if copy_shape: # <<<<<<<<<<<<<< - * # Allocate new buffer for strides and shape info. - * # This is allocated as one block, strides first. - */ - if (__pyx_v_copy_shape) { - - /* "numpy.pxd":225 - * # Allocate new buffer for strides and shape info. - * # This is allocated as one block, strides first. - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< - * info.shape = info.strides + ndim - * for i in range(ndim): - */ - __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - - /* "numpy.pxd":226 - * # This is allocated as one block, strides first. - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) - * info.shape = info.strides + ndim # <<<<<<<<<<<<<< - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] - */ - __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - - /* "numpy.pxd":227 - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) - * info.shape = info.strides + ndim - * for i in range(ndim): # <<<<<<<<<<<<<< - * info.strides[i] = PyArray_STRIDES(self)[i] - * info.shape[i] = PyArray_DIMS(self)[i] + * if current_node.left_child == LEAF: + * out[i] += weight_stack[stack_size] * value[current_node - root_node] * \ # <<<<<<<<<<<<<< + * learn_rate + * total_weight += weight_stack[stack_size] */ - __pyx_t_5 = __pyx_v_ndim; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; + __pyx_t_14 = __pyx_v_stack_size; - /* "numpy.pxd":228 - * info.shape = info.strides + ndim - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< - * info.shape[i] = PyArray_DIMS(self)[i] + /* "sklearn/ensemble/_gradient_boosting.pyx":219 + * if current_node.left_child == LEAF: + * out[i] += weight_stack[stack_size] * value[current_node - root_node] * \ + * learn_rate # <<<<<<<<<<<<<< + * total_weight += weight_stack[stack_size] * else: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + __pyx_t_15 = __pyx_v_i; + *((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_out.data) + __pyx_t_15)) )) += (((*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_weight_stack.data) + __pyx_t_14)) ))) * (__pyx_v_value[(__pyx_v_current_node - __pyx_v_root_node)])) * __pyx_v_learn_rate); - /* "numpy.pxd":229 - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] - * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + /* "sklearn/ensemble/_gradient_boosting.pyx":220 + * out[i] += weight_stack[stack_size] * value[current_node - root_node] * \ + * learn_rate + * total_weight += weight_stack[stack_size] # <<<<<<<<<<<<<< * else: - * info.strides = PyArray_STRIDES(self) + * # non-terminal node */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); - } - goto __pyx_L7; - } - /*else*/ { + __pyx_t_16 = __pyx_v_stack_size; + __pyx_v_total_weight = (__pyx_v_total_weight + (*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_weight_stack.data) + __pyx_t_16)) )))); + goto __pyx_L7; + } + /*else*/ { - /* "numpy.pxd":231 - * info.shape[i] = PyArray_DIMS(self)[i] + /* "sklearn/ensemble/_gradient_boosting.pyx":223 * else: - * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL + * # non-terminal node + * feature_index = array_index(current_node.feature, target_feature) # <<<<<<<<<<<<<< + * if feature_index != -1: + * # split feature in target set */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - - /* "numpy.pxd":232 - * else: - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) + __pyx_v_feature_index = __pyx_f_7sklearn_8ensemble_18_gradient_boosting_array_index(__pyx_v_current_node->feature, __pyx_v_target_feature); + + /* "sklearn/ensemble/_gradient_boosting.pyx":224 + * # non-terminal node + * feature_index = array_index(current_node.feature, target_feature) + * if feature_index != -1: # <<<<<<<<<<<<<< + * # split feature in target set + * # push left or right child on stack */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); - } - __pyx_L7:; - - /* "numpy.pxd":233 - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * info.itemsize = PyArray_ITEMSIZE(self) - * info.readonly = not PyArray_ISWRITEABLE(self) + __pyx_t_13 = ((__pyx_v_feature_index != -1) != 0); + if (__pyx_t_13) { + + /* "sklearn/ensemble/_gradient_boosting.pyx":227 + * # split feature in target set + * # push left or right child on stack + * if X[i, feature_index] <= current_node.threshold: # <<<<<<<<<<<<<< + * # left + * node_stack[stack_size] = (root_node + */ - __pyx_v_info->suboffsets = NULL; - - /* "numpy.pxd":234 - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< - * info.readonly = not PyArray_ISWRITEABLE(self) - * + __pyx_t_17 = __pyx_v_i; + __pyx_t_18 = __pyx_v_feature_index; + __pyx_t_13 = (((*((__pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t *) ( /* dim=0 */ (__pyx_v_X.data + __pyx_t_17 * __pyx_v_X.strides[0]) )) + __pyx_t_18)) ))) <= __pyx_v_current_node->threshold) != 0); + if (__pyx_t_13) { + + /* "sklearn/ensemble/_gradient_boosting.pyx":229 + * if X[i, feature_index] <= current_node.threshold: + * # left + * node_stack[stack_size] = (root_node + # <<<<<<<<<<<<<< + * current_node.left_child) + * else: */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + (__pyx_v_node_stack[__pyx_v_stack_size]) = (__pyx_v_root_node + __pyx_v_current_node->left_child); + goto __pyx_L9; + } + /*else*/ { + + /* "sklearn/ensemble/_gradient_boosting.pyx":233 + * else: + * # right + * node_stack[stack_size] = (root_node + # <<<<<<<<<<<<<< + * current_node.right_child) + * stack_size += 1 + */ + (__pyx_v_node_stack[__pyx_v_stack_size]) = (__pyx_v_root_node + __pyx_v_current_node->right_child); + } + __pyx_L9:; - /* "numpy.pxd":235 - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) - * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< - * - * cdef int t + /* "sklearn/ensemble/_gradient_boosting.pyx":235 + * node_stack[stack_size] = (root_node + + * current_node.right_child) + * stack_size += 1 # <<<<<<<<<<<<<< + * else: + * # split feature in complement set */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); + __pyx_v_stack_size = (__pyx_v_stack_size + 1); + goto __pyx_L8; + } + /*else*/ { - /* "numpy.pxd":238 + /* "sklearn/ensemble/_gradient_boosting.pyx":241 * - * cdef int t - * cdef char* f = NULL # <<<<<<<<<<<<<< - * cdef dtype descr = self.descr - * cdef list stack + * # push left child + * node_stack[stack_size] = root_node + current_node.left_child # <<<<<<<<<<<<<< + * current_weight = weight_stack[stack_size] + * left_sample_frac = root_node[current_node.left_child].n_node_samples / \ */ - __pyx_v_f = NULL; - - /* "numpy.pxd":239 - * cdef int t - * cdef char* f = NULL - * cdef dtype descr = self.descr # <<<<<<<<<<<<<< - * cdef list stack - * cdef int offset + (__pyx_v_node_stack[__pyx_v_stack_size]) = (__pyx_v_root_node + __pyx_v_current_node->left_child); + + /* "sklearn/ensemble/_gradient_boosting.pyx":242 + * # push left child + * node_stack[stack_size] = root_node + current_node.left_child + * current_weight = weight_stack[stack_size] # <<<<<<<<<<<<<< + * left_sample_frac = root_node[current_node.left_child].n_node_samples / \ + * current_node.n_node_samples */ - __Pyx_INCREF(((PyObject *)__pyx_v_self->descr)); - __pyx_v_descr = __pyx_v_self->descr; - - /* "numpy.pxd":243 - * cdef int offset - * - * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< - * - * if not hasfields and not copy_shape: + __pyx_t_19 = __pyx_v_stack_size; + __pyx_v_current_weight = (*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_weight_stack.data) + __pyx_t_19)) ))); + + /* "sklearn/ensemble/_gradient_boosting.pyx":243 + * node_stack[stack_size] = root_node + current_node.left_child + * current_weight = weight_stack[stack_size] + * left_sample_frac = root_node[current_node.left_child].n_node_samples / \ # <<<<<<<<<<<<<< + * current_node.n_node_samples + * if left_sample_frac <= 0.0 or left_sample_frac >= 1.0: */ - __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - - /* "numpy.pxd":245 - * cdef bint hasfields = PyDataType_HASFIELDS(descr) - * - * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< - * # do not call releasebuffer - * info.obj = None + __pyx_v_left_sample_frac = ((__pyx_v_root_node[__pyx_v_current_node->left_child]).n_node_samples / ((double)__pyx_v_current_node->n_node_samples)); + + /* "sklearn/ensemble/_gradient_boosting.pyx":245 + * left_sample_frac = root_node[current_node.left_child].n_node_samples / \ + * current_node.n_node_samples + * if left_sample_frac <= 0.0 or left_sample_frac >= 1.0: # <<<<<<<<<<<<<< + * raise ValueError("left_sample_frac:%f, " + * "n_samples current: %d, " */ - __pyx_t_2 = (!__pyx_v_hasfields); - if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); - __pyx_t_1 = __pyx_t_3; - } else { - __pyx_t_1 = __pyx_t_2; - } - if (__pyx_t_1) { - - /* "numpy.pxd":247 - * if not hasfields and not copy_shape: - * # do not call releasebuffer - * info.obj = None # <<<<<<<<<<<<<< - * else: - * # need to call releasebuffer + __pyx_t_20 = ((__pyx_v_left_sample_frac <= 0.0) != 0); + if (!__pyx_t_20) { + } else { + __pyx_t_13 = __pyx_t_20; + goto __pyx_L11_bool_binop_done; + } + __pyx_t_20 = ((__pyx_v_left_sample_frac >= 1.0) != 0); + __pyx_t_13 = __pyx_t_20; + __pyx_L11_bool_binop_done:; + if (__pyx_t_13) { + + /* "sklearn/ensemble/_gradient_boosting.pyx":249 + * "n_samples current: %d, " + * "n_samples left: %d" + * % (left_sample_frac, # <<<<<<<<<<<<<< + * current_node.n_node_samples, + * root_node[current_node.left_child].n_node_samples)) */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = Py_None; - goto __pyx_L10; - } - /*else*/ { + __pyx_t_9 = PyFloat_FromDouble(__pyx_v_left_sample_frac); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + + /* "sklearn/ensemble/_gradient_boosting.pyx":250 + * "n_samples left: %d" + * % (left_sample_frac, + * current_node.n_node_samples, # <<<<<<<<<<<<<< + * root_node[current_node.left_child].n_node_samples)) + * weight_stack[stack_size] = current_weight * left_sample_frac + */ + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_current_node->n_node_samples); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + + /* "sklearn/ensemble/_gradient_boosting.pyx":251 + * % (left_sample_frac, + * current_node.n_node_samples, + * root_node[current_node.left_child].n_node_samples)) # <<<<<<<<<<<<<< + * weight_stack[stack_size] = current_weight * left_sample_frac + * stack_size +=1 + */ + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_root_node[__pyx_v_current_node->left_child]).n_node_samples); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "sklearn/ensemble/_gradient_boosting.pyx":249 + * "n_samples current: %d, " + * "n_samples left: %d" + * % (left_sample_frac, # <<<<<<<<<<<<<< + * current_node.n_node_samples, + * root_node[current_node.left_child].n_node_samples)) + */ + __pyx_t_7 = PyTuple_New(3); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_7, 2, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_9 = 0; + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyString_Format(__pyx_kp_s_left_sample_frac_f_n_samples_cur, __pyx_t_7); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":246 + * current_node.n_node_samples + * if left_sample_frac <= 0.0 or left_sample_frac >= 1.0: + * raise ValueError("left_sample_frac:%f, " # <<<<<<<<<<<<<< + * "n_samples current: %d, " + * "n_samples left: %d" + */ + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "numpy.pxd":250 - * else: - * # need to call releasebuffer - * info.obj = self # <<<<<<<<<<<<<< + /* "sklearn/ensemble/_gradient_boosting.pyx":252 + * current_node.n_node_samples, + * root_node[current_node.left_child].n_node_samples)) + * weight_stack[stack_size] = current_weight * left_sample_frac # <<<<<<<<<<<<<< + * stack_size +=1 * - * if not hasfields: */ - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - } - __pyx_L10:; + __pyx_t_21 = __pyx_v_stack_size; + *((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_weight_stack.data) + __pyx_t_21)) )) = (__pyx_v_current_weight * __pyx_v_left_sample_frac); - /* "numpy.pxd":252 - * info.obj = self + /* "sklearn/ensemble/_gradient_boosting.pyx":253 + * root_node[current_node.left_child].n_node_samples)) + * weight_stack[stack_size] = current_weight * left_sample_frac + * stack_size +=1 # <<<<<<<<<<<<<< * - * if not hasfields: # <<<<<<<<<<<<<< - * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * # push right child */ - __pyx_t_1 = (!__pyx_v_hasfields); - if (__pyx_t_1) { + __pyx_v_stack_size = (__pyx_v_stack_size + 1); - /* "numpy.pxd":253 + /* "sklearn/ensemble/_gradient_boosting.pyx":256 * - * if not hasfields: - * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * # push right child + * node_stack[stack_size] = root_node + current_node.right_child # <<<<<<<<<<<<<< + * weight_stack[stack_size] = current_weight * \ + * (1.0 - left_sample_frac) */ - __pyx_v_t = __pyx_v_descr->type_num; - - /* "numpy.pxd":254 - * if not hasfields: - * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") + (__pyx_v_node_stack[__pyx_v_stack_size]) = (__pyx_v_root_node + __pyx_v_current_node->right_child); + + /* "sklearn/ensemble/_gradient_boosting.pyx":257 + * # push right child + * node_stack[stack_size] = root_node + current_node.right_child + * weight_stack[stack_size] = current_weight * \ # <<<<<<<<<<<<<< + * (1.0 - left_sample_frac) + * stack_size +=1 */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); - if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; - } else { - __pyx_t_2 = __pyx_t_1; - } - if (!__pyx_t_2) { + __pyx_t_22 = __pyx_v_stack_size; + *((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_weight_stack.data) + __pyx_t_22)) )) = (__pyx_v_current_weight * (1.0 - __pyx_v_left_sample_frac)); - /* "numpy.pxd":255 - * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" + /* "sklearn/ensemble/_gradient_boosting.pyx":259 + * weight_stack[stack_size] = current_weight * \ + * (1.0 - left_sample_frac) + * stack_size +=1 # <<<<<<<<<<<<<< + * + * if not (0.999 < total_weight < 1.001): */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); - if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); - __pyx_t_7 = __pyx_t_3; - } else { - __pyx_t_7 = __pyx_t_1; + __pyx_v_stack_size = (__pyx_v_stack_size + 1); + } + __pyx_L8:; } - __pyx_t_1 = __pyx_t_7; - } else { - __pyx_t_1 = __pyx_t_2; - } - if (__pyx_t_1) { - - /* "numpy.pxd":256 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L12; - } - __pyx_L12:; - - /* "numpy.pxd":257 - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" - */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__b; - goto __pyx_L13; + __pyx_L7:; } - /* "numpy.pxd":258 - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" + /* "sklearn/ensemble/_gradient_boosting.pyx":261 + * stack_size +=1 + * + * if not (0.999 < total_weight < 1.001): # <<<<<<<<<<<<<< + * raise ValueError("Total weight should be 1.0 but was %.9f" % + * total_weight) */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__B; - goto __pyx_L13; + __pyx_t_13 = (0.999 < __pyx_v_total_weight); + if (__pyx_t_13) { + __pyx_t_13 = (__pyx_v_total_weight < 1.001); } + __pyx_t_20 = ((!(__pyx_t_13 != 0)) != 0); + if (__pyx_t_20) { - /* "numpy.pxd":259 - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" + /* "sklearn/ensemble/_gradient_boosting.pyx":263 + * if not (0.999 < total_weight < 1.001): + * raise ValueError("Total weight should be 1.0 but was %.9f" % + * total_weight) # <<<<<<<<<<<<<< + * + * */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__h; - goto __pyx_L13; - } + __pyx_t_6 = PyFloat_FromDouble(__pyx_v_total_weight); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); - /* "numpy.pxd":260 - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" + /* "sklearn/ensemble/_gradient_boosting.pyx":262 + * + * if not (0.999 < total_weight < 1.001): + * raise ValueError("Total weight should be 1.0 but was %.9f" % # <<<<<<<<<<<<<< + * total_weight) + * */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__H; - goto __pyx_L13; + __pyx_t_7 = __Pyx_PyString_Format(__pyx_kp_s_Total_weight_should_be_1_0_but_w, __pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_6, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_Raise(__pyx_t_7, 0, 0, 0); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + } - /* "numpy.pxd":261 - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" + /* "sklearn/ensemble/_gradient_boosting.pyx":153 + * + * + * cpdef _partial_dependence_tree(Tree tree, DTYPE_t[:, ::1] X, # <<<<<<<<<<<<<< + * int32[::1] target_feature, + * double learn_rate, */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__i; - goto __pyx_L13; - } - /* "numpy.pxd":262 - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" - */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__I; - goto __pyx_L13; - } + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __PYX_XDEC_MEMVIEW(&__pyx_t_8, 1); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("sklearn.ensemble._gradient_boosting._partial_dependence_tree", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_weight_stack, 1); + __Pyx_XDECREF(__pyx_v_underlying_stack); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "numpy.pxd":263 - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" - */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__l; - goto __pyx_L13; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_5_partial_dependence_tree(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_8ensemble_18_gradient_boosting_4_partial_dependence_tree[] = "Partial dependence of the response on the ``target_feature`` set.\n\n For each row in ``X`` a tree traversal is performed.\n Each traversal starts from the root with weight 1.0.\n\n At each non-terminal node that splits on a target variable either\n the left child or the right child is visited based on the feature\n value of the current sample and the weight is not modified.\n At each non-terminal node that splits on a complementary feature\n both children are visited and the weight is multiplied by the fraction\n of training samples which went to each child.\n\n At each terminal node the value of the node is multiplied by the\n current weight (weights sum to 1 for all visited terminal nodes).\n\n Parameters\n ----------\n tree : sklearn.tree.Tree\n A regression tree; tree.values.shape[1] == 1\n X : memory view on 2d ndarray\n The grid points on which the partial dependence\n should be evaluated. X.shape[1] == target_feature.shape[0].\n target_feature : memory view on 1d ndarray\n The set of target features for which the partial dependence\n should be evaluated. X.shape[1] == target_feature.shape[0].\n learn_rate : double\n Constant scaling factor for the leaf predictions.\n out : memory view on 1d ndarray\n The value of the partial dependence function on each grid\n point.\n "; +static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_5_partial_dependence_tree(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree = 0; + __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_target_feature = { 0, 0, { 0 }, { 0 }, { 0 } }; + double __pyx_v_learn_rate; + __Pyx_memviewslice __pyx_v_out = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_partial_dependence_tree (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_tree_2,&__pyx_n_s_X,&__pyx_n_s_target_feature,&__pyx_n_s_learn_rate,&__pyx_n_s_out,0}; + PyObject* values[5] = {0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tree_2)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_partial_dependence_tree", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_target_feature)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_partial_dependence_tree", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_learn_rate)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_partial_dependence_tree", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_partial_dependence_tree", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_partial_dependence_tree") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); } + __pyx_v_tree = ((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)values[0]); + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t(values[1]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_target_feature = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32(values[2]); if (unlikely(!__pyx_v_target_feature.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_learn_rate = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_learn_rate == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dc_double(values[4]); if (unlikely(!__pyx_v_out.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_partial_dependence_tree", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.ensemble._gradient_boosting._partial_dependence_tree", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_tree), __pyx_ptype_7sklearn_4tree_5_tree_Tree, 1, "tree", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_8ensemble_18_gradient_boosting_4_partial_dependence_tree(__pyx_self, __pyx_v_tree, __pyx_v_X, __pyx_v_target_feature, __pyx_v_learn_rate, __pyx_v_out); - /* "numpy.pxd":264 - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" - */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__L; - goto __pyx_L13; - } + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "numpy.pxd":265 - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" +static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_4_partial_dependence_tree(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_target_feature, double __pyx_v_learn_rate, __Pyx_memviewslice __pyx_v_out) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_partial_dependence_tree", 0); + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_X.memview)) { __Pyx_RaiseUnboundLocalError("X"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + if (unlikely(!__pyx_v_target_feature.memview)) { __Pyx_RaiseUnboundLocalError("target_feature"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + if (unlikely(!__pyx_v_out.memview)) { __Pyx_RaiseUnboundLocalError("out"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_1 = __pyx_f_7sklearn_8ensemble_18_gradient_boosting__partial_dependence_tree(__pyx_v_tree, __pyx_v_X, __pyx_v_target_feature, __pyx_v_learn_rate, __pyx_v_out, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.ensemble._gradient_boosting._partial_dependence_tree", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_X, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_target_feature, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_out, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/ensemble/_gradient_boosting.pyx":266 + * + * + * def _random_sample_mask(np.npy_intp n_total_samples, # <<<<<<<<<<<<<< + * np.npy_intp n_total_in_bag, random_state): + * """Create a random sample mask where ``n_total_in_bag`` elements are set. */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__q; - goto __pyx_L13; + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_7_random_sample_mask(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_8ensemble_18_gradient_boosting_6_random_sample_mask[] = "Create a random sample mask where ``n_total_in_bag`` elements are set.\n\n Parameters\n ----------\n n_total_samples : int\n The length of the resulting mask.\n\n n_total_in_bag : int\n The number of elements in the sample mask which are set to 1.\n\n random_state : np.RandomState\n A numpy ``RandomState`` object.\n\n Returns\n -------\n sample_mask : np.ndarray, shape=[n_total_samples]\n An ndarray where ``n_total_in_bag`` elements are set to ``True``\n the others are ``False``.\n "; +static PyMethodDef __pyx_mdef_7sklearn_8ensemble_18_gradient_boosting_7_random_sample_mask = {"_random_sample_mask", (PyCFunction)__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_7_random_sample_mask, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_8ensemble_18_gradient_boosting_6_random_sample_mask}; +static PyObject *__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_7_random_sample_mask(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + npy_intp __pyx_v_n_total_samples; + npy_intp __pyx_v_n_total_in_bag; + PyObject *__pyx_v_random_state = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_random_sample_mask (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_n_total_samples,&__pyx_n_s_n_total_in_bag,&__pyx_n_s_random_state,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_total_samples)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_total_in_bag)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_random_sample_mask", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random_state)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_random_sample_mask", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_random_sample_mask") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } + __pyx_v_n_total_samples = __Pyx_PyInt_As_Py_intptr_t(values[0]); if (unlikely((__pyx_v_n_total_samples == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_total_in_bag = __Pyx_PyInt_As_Py_intptr_t(values[1]); if (unlikely((__pyx_v_n_total_in_bag == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_random_state = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_random_sample_mask", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.ensemble._gradient_boosting._random_sample_mask", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_8ensemble_18_gradient_boosting_6_random_sample_mask(__pyx_self, __pyx_v_n_total_samples, __pyx_v_n_total_in_bag, __pyx_v_random_state); - /* "numpy.pxd":266 - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_8ensemble_18_gradient_boosting_6_random_sample_mask(CYTHON_UNUSED PyObject *__pyx_self, npy_intp __pyx_v_n_total_samples, npy_intp __pyx_v_n_total_in_bag, PyObject *__pyx_v_random_state) { + PyArrayObject *__pyx_v_rand = 0; + PyArrayObject *__pyx_v_sample_mask = 0; + npy_intp __pyx_v_n_bagged; + npy_intp __pyx_v_i; + __Pyx_LocalBuf_ND __pyx_pybuffernd_rand; + __Pyx_Buffer __pyx_pybuffer_rand; + __Pyx_LocalBuf_ND __pyx_pybuffernd_sample_mask; + __Pyx_Buffer __pyx_pybuffer_sample_mask; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + PyArrayObject *__pyx_t_7 = NULL; + npy_intp __pyx_t_8; + npy_intp __pyx_t_9; + npy_intp __pyx_t_10; + int __pyx_t_11; + npy_intp __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_random_sample_mask", 0); + __pyx_pybuffer_rand.pybuffer.buf = NULL; + __pyx_pybuffer_rand.refcount = 0; + __pyx_pybuffernd_rand.data = NULL; + __pyx_pybuffernd_rand.rcbuffer = &__pyx_pybuffer_rand; + __pyx_pybuffer_sample_mask.pybuffer.buf = NULL; + __pyx_pybuffer_sample_mask.refcount = 0; + __pyx_pybuffernd_sample_mask.data = NULL; + __pyx_pybuffernd_sample_mask.rcbuffer = &__pyx_pybuffer_sample_mask; + + /* "sklearn/ensemble/_gradient_boosting.pyx":288 + * """ + * cdef np.ndarray[float64, ndim=1, mode="c"] rand = \ + * random_state.rand(n_total_samples) # <<<<<<<<<<<<<< + * cdef np.ndarray[uint8, ndim=1, mode="c", cast=True] sample_mask = \ + * np_zeros((n_total_samples,), dtype=np_bool) */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Q; - goto __pyx_L13; + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_random_state, __pyx_n_s_rand); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_total_samples); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (!__pyx_t_4) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_rand.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_float64, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_rand = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_rand.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_rand.diminfo[0].strides = __pyx_pybuffernd_rand.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_rand.diminfo[0].shape = __pyx_pybuffernd_rand.rcbuffer->pybuffer.shape[0]; } + } + __pyx_t_6 = 0; + __pyx_v_rand = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; - /* "numpy.pxd":267 - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" + /* "sklearn/ensemble/_gradient_boosting.pyx":290 + * random_state.rand(n_total_samples) + * cdef np.ndarray[uint8, ndim=1, mode="c", cast=True] sample_mask = \ + * np_zeros((n_total_samples,), dtype=np_bool) # <<<<<<<<<<<<<< + * + * cdef np.npy_intp n_bagged = 0 */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__f; - goto __pyx_L13; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np_zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_total_samples); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np_bool); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_2, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_3); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_mask.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_uint8, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 1, __pyx_stack) == -1)) { + __pyx_v_sample_mask = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_sample_mask.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_sample_mask.diminfo[0].strides = __pyx_pybuffernd_sample_mask.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_mask.diminfo[0].shape = __pyx_pybuffernd_sample_mask.rcbuffer->pybuffer.shape[0]; } + } + __pyx_t_7 = 0; + __pyx_v_sample_mask = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; - /* "numpy.pxd":268 - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" + /* "sklearn/ensemble/_gradient_boosting.pyx":292 + * np_zeros((n_total_samples,), dtype=np_bool) + * + * cdef np.npy_intp n_bagged = 0 # <<<<<<<<<<<<<< + * cdef np.npy_intp i = 0 + * */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__d; - goto __pyx_L13; - } + __pyx_v_n_bagged = 0; - /* "numpy.pxd":269 - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" + /* "sklearn/ensemble/_gradient_boosting.pyx":293 + * + * cdef np.npy_intp n_bagged = 0 + * cdef np.npy_intp i = 0 # <<<<<<<<<<<<<< + * + * for i in range(n_total_samples): */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__g; - goto __pyx_L13; - } + __pyx_v_i = 0; - /* "numpy.pxd":270 - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" + /* "sklearn/ensemble/_gradient_boosting.pyx":295 + * cdef np.npy_intp i = 0 + * + * for i in range(n_total_samples): # <<<<<<<<<<<<<< + * if rand[i] * (n_total_samples - i) < (n_total_in_bag - n_bagged): + * sample_mask[i] = 1 */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zf; - goto __pyx_L13; - } + __pyx_t_8 = __pyx_v_n_total_samples; + for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { + __pyx_v_i = __pyx_t_9; - /* "numpy.pxd":271 - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< - * elif t == NPY_CLONGDOUBLE: f = "Zg" - * elif t == NPY_OBJECT: f = "O" + /* "sklearn/ensemble/_gradient_boosting.pyx":296 + * + * for i in range(n_total_samples): + * if rand[i] * (n_total_samples - i) < (n_total_in_bag - n_bagged): # <<<<<<<<<<<<<< + * sample_mask[i] = 1 + * n_bagged += 1 */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zd; - goto __pyx_L13; - } + __pyx_t_10 = __pyx_v_i; + __pyx_t_11 = ((((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_float64 *, __pyx_pybuffernd_rand.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_rand.diminfo[0].strides)) * (__pyx_v_n_total_samples - __pyx_v_i)) < (__pyx_v_n_total_in_bag - __pyx_v_n_bagged)) != 0); + if (__pyx_t_11) { + + /* "sklearn/ensemble/_gradient_boosting.pyx":297 + * for i in range(n_total_samples): + * if rand[i] * (n_total_samples - i) < (n_total_in_bag - n_bagged): + * sample_mask[i] = 1 # <<<<<<<<<<<<<< + * n_bagged += 1 + * + */ + __pyx_t_12 = __pyx_v_i; + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_8ensemble_18_gradient_boosting_uint8 *, __pyx_pybuffernd_sample_mask.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_sample_mask.diminfo[0].strides) = 1; - /* "numpy.pxd":272 - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< - * elif t == NPY_OBJECT: f = "O" - * else: + /* "sklearn/ensemble/_gradient_boosting.pyx":298 + * if rand[i] * (n_total_samples - i) < (n_total_in_bag - n_bagged): + * sample_mask[i] = 1 + * n_bagged += 1 # <<<<<<<<<<<<<< + * + * return sample_mask */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zg; - goto __pyx_L13; + __pyx_v_n_bagged = (__pyx_v_n_bagged + 1); + goto __pyx_L5; } + __pyx_L5:; + } - /* "numpy.pxd":273 - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" - * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L13; - } - /*else*/ { - - /* "numpy.pxd":275 - * elif t == NPY_OBJECT: f = "O" - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< - * info.format = f - * return - */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); - __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L13:; - - /* "numpy.pxd":276 - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * info.format = f # <<<<<<<<<<<<<< - * return - * else: - */ - __pyx_v_info->format = __pyx_v_f; - - /* "numpy.pxd":277 - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * info.format = f - * return # <<<<<<<<<<<<<< - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) - */ - __pyx_r = 0; - goto __pyx_L0; - goto __pyx_L11; - } - /*else*/ { - - /* "numpy.pxd":279 - * return - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment - * offset = 0 - */ - __pyx_v_info->format = ((char *)malloc(255)); - - /* "numpy.pxd":280 - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< - * offset = 0 - * f = _util_dtypestring(descr, info.format + 1, - */ - (__pyx_v_info->format[0]) = '^'; - - /* "numpy.pxd":281 - * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment - * offset = 0 # <<<<<<<<<<<<<< - * f = _util_dtypestring(descr, info.format + 1, - * info.format + _buffer_format_string_len, - */ - __pyx_v_offset = 0; - - /* "numpy.pxd":284 - * f = _util_dtypestring(descr, info.format + 1, - * info.format + _buffer_format_string_len, - * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string + /* "sklearn/ensemble/_gradient_boosting.pyx":300 + * n_bagged += 1 * + * return sample_mask # <<<<<<<<<<<<<< */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_9; + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_sample_mask)); + __pyx_r = ((PyObject *)__pyx_v_sample_mask); + goto __pyx_L0; - /* "numpy.pxd":285 - * info.format + _buffer_format_string_len, - * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + /* "sklearn/ensemble/_gradient_boosting.pyx":266 * - * def __releasebuffer__(ndarray self, Py_buffer* info): + * + * def _random_sample_mask(np.npy_intp n_total_samples, # <<<<<<<<<<<<<< + * np.npy_intp n_total_in_bag, random_state): + * """Create a random sample mask where ``n_total_in_bag`` elements are set. */ - (__pyx_v_f[0]) = 0; - } - __pyx_L11:; - __pyx_r = 0; - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; - } + __Pyx_XDECREF(__pyx_t_5); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_rand.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_mask.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.ensemble._gradient_boosting._random_sample_mask", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { - __Pyx_GOTREF(Py_None); - __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; - } + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_rand.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_mask.rcbuffer->pybuffer); __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_XDECREF((PyObject *)__pyx_v_rand); + __Pyx_XDECREF((PyObject *)__pyx_v_sample_mask); + __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":197 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + /* Python wrapper */ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); - __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "numpy.pxd":287 - * f[0] = 0 # Terminate format string - * - * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) - */ - -static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__", 0); + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } - /* "numpy.pxd":288 + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":203 + * # of flags * - * def __releasebuffer__(ndarray self, Py_buffer* info): - * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< - * stdlib.free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim */ - __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + } - /* "numpy.pxd":289 - * def __releasebuffer__(ndarray self, Py_buffer* info): - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) # <<<<<<<<<<<<<< + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":206 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":207 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":209 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * stdlib.free(info.strides) */ - free(__pyx_v_info->format); - goto __pyx_L3; - } - __pyx_L3:; + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":290 - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":211 + * ndim = PyArray_NDIM(self) + * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * stdlib.free(info.strides) - * # info.shape was stored after info.strides in the same block + * copy_shape = 1 + * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":291 - * stdlib.free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * stdlib.free(info.strides) # <<<<<<<<<<<<<< - * # info.shape was stored after info.strides in the same block + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":212 * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 */ - free(__pyx_v_info->strides); + __pyx_v_copy_shape = 1; goto __pyx_L4; } - __pyx_L4:; - - __Pyx_RefNannyFinishContext(); -} + /*else*/ { -/* "numpy.pxd":767 - * ctypedef npy_cdouble complex_t - * - * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(1, a) + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":216 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L6_bool_binop_done; + } - /* "numpy.pxd":768 + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":217 * - * cdef inline object PyArray_MultiIterNew1(a): - * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") * - * cdef inline object PyArray_MultiIterNew2(a, b): */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L6_bool_binop_done:; + if (__pyx_t_1) { - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "numpy.pxd":770 - * return PyArray_MultiIterNew(1, a) - * - * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(2, a, b) + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":220 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L9_bool_binop_done; + } - /* "numpy.pxd":771 + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":221 * - * cdef inline object PyArray_MultiIterNew2(a, b): - * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") * - * cdef inline object PyArray_MultiIterNew3(a, b, c): */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L9_bool_binop_done:; + if (__pyx_t_1) { - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } -/* "numpy.pxd":773 - * return PyArray_MultiIterNew(2, a, b) + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":224 + * raise ValueError(u"ndarray is not Fortran contiguous") * - * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(3, a, b, c) + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":225 * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. */ + __pyx_v_info->ndim = __pyx_v_ndim; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_1 = (__pyx_v_copy_shape != 0); + if (__pyx_t_1) { - /* "numpy.pxd":774 - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): - * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":229 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":230 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); -/* "numpy.pxd":776 - * return PyArray_MultiIterNew(3, a, b, c) - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(4, a, b, c, d) - * + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":231 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] */ + __pyx_t_4 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":232 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":777 - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): - * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L11; + } + /*else*/ { - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); -/* "numpy.pxd":779 - * return PyArray_MultiIterNew(4, a, b, c, d) - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(5, a, b, c, d, e) - * + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":236 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L11:; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":237 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":780 - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): - * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":238 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) * - * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); -/* "numpy.pxd":782 - * return PyArray_MultiIterNew(5, a, b, c, d, e) + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * - * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< - * # Recursive utility function used in __getbuffer__ to get format - * # string. The new location in the format string is returned. + * cdef int t */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); -static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { - PyArray_Descr *__pyx_v_child = 0; - int __pyx_v_endian_detector; - int __pyx_v_little_endian; - PyObject *__pyx_v_fields = 0; - PyObject *__pyx_v_childname = NULL; - PyObject *__pyx_v_new_offset = NULL; - PyObject *__pyx_v_t = NULL; - char *__pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring", 0); + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":242 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; - /* "numpy.pxd":789 - * cdef int delta_offset - * cdef tuple i - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * cdef tuple fields + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":243 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset */ - __pyx_v_endian_detector = 1; + __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; - /* "numpy.pxd":790 - * cdef tuple i - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< - * cdef tuple fields + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":247 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< * + * if not hasfields and not copy_shape: */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":793 - * cdef tuple fields + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":249 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) * - * for childname in descr.names: # <<<<<<<<<<<<<< - * fields = descr.fields[childname] - * child, new_offset = fields + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None */ - if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L15_bool_binop_done; } - __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L15_bool_binop_done:; + if (__pyx_t_1) { - /* "numpy.pxd":794 - * - * for childname in descr.names: - * fields = descr.fields[childname] # <<<<<<<<<<<<<< - * child, new_offset = fields - * + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":251 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L14; + } + /*else*/ { - /* "numpy.pxd":795 - * for childname in descr.names: - * fields = descr.fields[childname] - * child, new_offset = fields # <<<<<<<<<<<<<< + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":254 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< * - * if (end - f) - (new_offset - offset[0]) < 15: + * if not hasfields: */ - if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { - PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); - __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; - __pyx_t_4 = 0; + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L14:; - /* "numpy.pxd":797 - * child, new_offset = fields - * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":256 + * info.obj = self * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { - /* "numpy.pxd":798 - * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 * - * if ((child.byteorder == '>' and little_endian) or + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; + __pyx_t_4 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_4; - /* "numpy.pxd":800 - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") - * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); + if (!__pyx_t_2) { + goto __pyx_L20_next_or; } else { - __pyx_t_7 = __pyx_t_6; } - if (!__pyx_t_7) { - - /* "numpy.pxd":801 - * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< - * raise ValueError(u"Non-native byte order not supported") - * # One could encode it in the format string and have Cython - */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; - } else { - __pyx_t_9 = __pyx_t_6; - } - __pyx_t_6 = __pyx_t_9; + __pyx_t_2 = (__pyx_v_little_endian != 0); + if (!__pyx_t_2) { } else { - __pyx_t_6 = __pyx_t_7; + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; } - if (__pyx_t_6) { + __pyx_L20_next_or:; - /* "numpy.pxd":802 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * # One could encode it in the format string and have Cython - * # complain instead, BUT: < and > in format strings also imply + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; } - __pyx_L6:; + __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L19_bool_binop_done:; + if (__pyx_t_1) { - /* "numpy.pxd":812 - * - * # Output padding bytes - * while offset[0] < new_offset: # <<<<<<<<<<<<<< - * f[0] = 120 # "x"; pad byte - * f += 1 + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" */ - while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!__pyx_t_6) break; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "numpy.pxd":813 - * # Output padding bytes - * while offset[0] < new_offset: - * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< - * f += 1 - * offset[0] += 1 + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - (__pyx_v_f[0]) = 120; + switch (__pyx_v_t) { - /* "numpy.pxd":814 - * while offset[0] < new_offset: - * f[0] = 120 # "x"; pad byte - * f += 1 # <<<<<<<<<<<<<< - * offset[0] += 1 - * + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":261 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" */ - __pyx_v_f = (__pyx_v_f + 1); + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; - /* "numpy.pxd":815 - * f[0] = 120 # "x"; pad byte - * f += 1 - * offset[0] += 1 # <<<<<<<<<<<<<< - * - * offset[0] += child.itemsize + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":262 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); - } + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; - /* "numpy.pxd":817 - * offset[0] += 1 - * - * offset[0] += child.itemsize # <<<<<<<<<<<<<< - * - * if not PyDataType_HASFIELDS(child): + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":263 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; - /* "numpy.pxd":819 - * offset[0] += child.itemsize - * - * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< - * t = child.type_num - * if end - f < 5: + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":264 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); - if (__pyx_t_6) { + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; - /* "numpy.pxd":820 - * - * if not PyDataType_HASFIELDS(child): - * t = child.type_num # <<<<<<<<<<<<<< - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 820; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; - __pyx_t_3 = 0; + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; - /* "numpy.pxd":821 - * if not PyDataType_HASFIELDS(child): - * t = child.type_num - * if end - f < 5: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short.") - * + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":266 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); - if (__pyx_t_6) { + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; - /* "numpy.pxd":822 - * t = child.type_num - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< - * - * # Until ticket #99 is fixed, use integers to avoid warnings + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":267 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; - } - __pyx_L10:; + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; - /* "numpy.pxd":825 - * - * # Until ticket #99 is fixed, use integers to avoid warnings - * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":268 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 98; - goto __pyx_L11; - } + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; - /* "numpy.pxd":826 - * # Until ticket #99 is fixed, use integers to avoid warnings - * if t == NPY_BYTE: f[0] = 98 #"b" - * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":269 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 66; - goto __pyx_L11; - } + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; - /* "numpy.pxd":827 - * if t == NPY_BYTE: f[0] = 98 #"b" - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 104; - goto __pyx_L11; - } + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; - /* "numpy.pxd":828 - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":271 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 72; - goto __pyx_L11; - } + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; - /* "numpy.pxd":829 - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 105; - goto __pyx_L11; - } + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; - /* "numpy.pxd":830 - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":273 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 73; - goto __pyx_L11; - } + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; - /* "numpy.pxd":831 - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 108; - goto __pyx_L11; - } + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; - /* "numpy.pxd":832 - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":275 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 76; - goto __pyx_L11; - } + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; - /* "numpy.pxd":833 - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 113; - goto __pyx_L11; - } + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; - /* "numpy.pxd":834 - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 81; - goto __pyx_L11; - } + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: - /* "numpy.pxd":835 - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":279 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 102; - goto __pyx_L11; - } - - /* "numpy.pxd":836 - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 100; - goto __pyx_L11; - } + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } - /* "numpy.pxd":837 - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 103; - goto __pyx_L11; - } + __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":838 - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":281 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 102; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; - } - - /* "numpy.pxd":839 - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg - * elif t == NPY_OBJECT: f[0] = 79 #"O" - */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 100; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; - } + __pyx_r = 0; + goto __pyx_L0; + } + /*else*/ { - /* "numpy.pxd":840 - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< - * elif t == NPY_OBJECT: f[0] = 79 #"O" + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 + * return * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 103; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; - } + __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":841 - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg - * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":284 * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 79; - goto __pyx_L11; - } - /*else*/ { + (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":843 - * elif t == NPY_OBJECT: f[0] = 79 #"O" - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< - * f += 1 - * else: + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":285 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L11:; + __pyx_v_offset = 0; - /* "numpy.pxd":844 - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * f += 1 # <<<<<<<<<<<<<< - * else: - * # Cython ignores struct boundary information ("T{...}"), + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":286 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< + * info.format + _buffer_format_string_len, + * &offset) */ - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; - } - /*else*/ { + __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_7; - /* "numpy.pxd":848 - * # Cython ignores struct boundary information ("T{...}"), - * # so don't output it - * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< - * return f + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":289 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * + * def __releasebuffer__(ndarray self, Py_buffer* info): */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 848; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; - } - __pyx_L9:; + (__pyx_v_f[0]) = '\x00'; } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":849 - * # so don't output it - * f = _util_dtypestring(child, f, end, offset) - * return f # <<<<<<<<<<<<<< - * - * + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":197 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. */ - __pyx_r = __pyx_v_f; - goto __pyx_L0; + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_child); - __Pyx_XDECREF(__pyx_v_fields); - __Pyx_XDECREF(__pyx_v_childname); - __Pyx_XDECREF(__pyx_v_new_offset); - __Pyx_XDECREF(__pyx_v_t); + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":964 - * +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 + * f[0] = c'\0' # Terminate format string * - * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< - * cdef PyObject* baseptr - * if base is None: + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) */ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { - PyObject *__pyx_v_baseptr; +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base", 0); + __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":966 - * cdef inline void set_array_base(ndarray arr, object base): - * cdef PyObject* baseptr - * if base is None: # <<<<<<<<<<<<<< - * baseptr = NULL - * else: + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { - /* "numpy.pxd":967 - * cdef PyObject* baseptr - * if base is None: - * baseptr = NULL # <<<<<<<<<<<<<< - * else: - * Py_INCREF(base) # important to do this before decref below! + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":293 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) */ - __pyx_v_baseptr = NULL; + free(__pyx_v_info->format); goto __pyx_L3; } - /*else*/ { - - /* "numpy.pxd":969 - * baseptr = NULL - * else: - * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< - * baseptr = base - * Py_XDECREF(arr.base) - */ - Py_INCREF(__pyx_v_base); + __pyx_L3:; - /* "numpy.pxd":970 - * else: - * Py_INCREF(base) # important to do this before decref below! - * baseptr = base # <<<<<<<<<<<<<< - * Py_XDECREF(arr.base) - * arr.base = baseptr + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":294 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block */ - __pyx_v_baseptr = ((PyObject *)__pyx_v_base); - } - __pyx_L3:; + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { - /* "numpy.pxd":971 - * Py_INCREF(base) # important to do this before decref below! - * baseptr = base - * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< - * arr.base = baseptr + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":295 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block * */ - Py_XDECREF(__pyx_v_arr->base); + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; - /* "numpy.pxd":972 - * baseptr = base - * Py_XDECREF(arr.base) - * arr.base = baseptr # <<<<<<<<<<<<<< + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 + * f[0] = c'\0' # Terminate format string * - * cdef inline object get_array_base(ndarray arr): + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) */ - __pyx_v_arr->base = __pyx_v_baseptr; + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":974 - * arr.base = baseptr +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * if arr.base is NULL: - * return None */ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base", 0); + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":975 + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":772 * - * cdef inline object get_array_base(ndarray arr): - * if arr.base is NULL: # <<<<<<<<<<<<<< - * return None - * else: + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); - if (__pyx_t_1) { + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; - /* "numpy.pxd":976 - * cdef inline object get_array_base(ndarray arr): - * if arr.base is NULL: - * return None # <<<<<<<<<<<<<< - * else: - * return arr.base + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_None); - __pyx_r = Py_None; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "numpy.pxd":978 - * return None - * else: - * return arr.base # <<<<<<<<<<<<<< - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); - __pyx_r = ((PyObject *)__pyx_v_arr->base); - goto __pyx_L0; - } - __pyx_L3:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - __Pyx_NAMESTR("_gradient_boosting"), - 0, /* m_doc */ - -1, /* m_size */ - __pyx_methods /* m_methods */, - NULL, /* m_reload */ - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_u_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 1, 0, 0}, - {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, - {&__pyx_kp_s_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 0, 1, 0}, - {&__pyx_n_s_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 1, 1}, - {&__pyx_kp_u_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 1, 0, 0}, - {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, - {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, - {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, - {&__pyx_n_s__DTYPE, __pyx_k__DTYPE, sizeof(__pyx_k__DTYPE), 0, 0, 1, 1}, - {&__pyx_n_s__K, __pyx_k__K, sizeof(__pyx_k__K), 0, 0, 1, 1}, - {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__estimators, __pyx_k__estimators, sizeof(__pyx_k__estimators), 0, 0, 1, 1}, - {&__pyx_n_s__float32, __pyx_k__float32, sizeof(__pyx_k__float32), 0, 0, 1, 1}, - {&__pyx_n_s__i, __pyx_k__i, sizeof(__pyx_k__i), 0, 0, 1, 1}, - {&__pyx_n_s__k, __pyx_k__k, sizeof(__pyx_k__k), 0, 0, 1, 1}, - {&__pyx_n_s__n_estimators, __pyx_k__n_estimators, sizeof(__pyx_k__n_estimators), 0, 0, 1, 1}, - {&__pyx_n_s__n_features, __pyx_k__n_features, sizeof(__pyx_k__n_features), 0, 0, 1, 1}, - {&__pyx_n_s__n_samples, __pyx_k__n_samples, sizeof(__pyx_k__n_samples), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__out, __pyx_k__out, sizeof(__pyx_k__out), 0, 0, 1, 1}, - {&__pyx_n_s__predict_stage, __pyx_k__predict_stage, sizeof(__pyx_k__predict_stage), 0, 0, 1, 1}, - {&__pyx_n_s__predict_stages, __pyx_k__predict_stages, sizeof(__pyx_k__predict_stages), 0, 0, 1, 1}, - {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__scale, __pyx_k__scale, sizeof(__pyx_k__scale), 0, 0, 1, 1}, - {&__pyx_n_s__stage, __pyx_k__stage, sizeof(__pyx_k__stage), 0, 0, 1, 1}, - {&__pyx_n_s__tree, __pyx_k__tree, sizeof(__pyx_k__tree), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - return 0; - __pyx_L1_error:; - return -1; -} +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ -static int __Pyx_InitCachedConstants(void) { +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":214 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":775 * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): */ - __pyx_k_tuple_2 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_2); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_1)); - PyTuple_SET_ITEM(__pyx_k_tuple_2, 0, ((PyObject *)__pyx_kp_u_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; - /* "numpy.pxd":218 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) * - * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_4); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_3)); - PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_u_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); - /* "numpy.pxd":256 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" - */ - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_6); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "numpy.pxd":798 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(2, a, b) * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) * - * if ((child.byteorder == '>' and little_endian) or */ - __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_9); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); - /* "numpy.pxd":802 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * # One could encode it in the format string and have Cython - * # complain instead, BUT: < and > in format strings also imply - */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_10); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":822 - * t = child.type_num - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":778 * - * # Until ticket #99 is fixed, use integers to avoid warnings + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_12); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); - PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; - /* "sklearn/ensemble/_gradient_boosting.pyx":96 + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(2, a, b) * - * @cython.nonecheck(False) - * def predict_stages(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< - * np.ndarray[DTYPE_t, ndim=2, mode='c'] X, double scale, - * np.ndarray[np.float64_t, ndim=2] out): - */ - __pyx_k_tuple_13 = PyTuple_New(11); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_13); - __Pyx_INCREF(((PyObject *)__pyx_n_s__estimators)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 0, ((PyObject *)__pyx_n_s__estimators)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__estimators)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__X)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 1, ((PyObject *)__pyx_n_s__X)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__X)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__scale)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 2, ((PyObject *)__pyx_n_s__scale)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__scale)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__out)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 3, ((PyObject *)__pyx_n_s__out)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__out)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__i)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 4, ((PyObject *)__pyx_n_s__i)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__k)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 5, ((PyObject *)__pyx_n_s__k)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__k)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_estimators)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 6, ((PyObject *)__pyx_n_s__n_estimators)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_estimators)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_samples)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 7, ((PyObject *)__pyx_n_s__n_samples)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_samples)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_features)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 8, ((PyObject *)__pyx_n_s__n_features)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_features)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__K)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 9, ((PyObject *)__pyx_n_s__K)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__K)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__tree)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 10, ((PyObject *)__pyx_n_s__tree)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__tree)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); - __pyx_k_codeobj_14 = (PyObject*)__Pyx_PyCode_New(4, 0, 11, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_13, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_15, __pyx_n_s__predict_stages, 96, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/ensemble/_gradient_boosting.pyx":131 + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) * - * @cython.nonecheck(False) - * def predict_stage(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< - * int stage, - * np.ndarray[DTYPE_t, ndim=2] X, double scale, */ - __pyx_k_tuple_17 = PyTuple_New(12); if (unlikely(!__pyx_k_tuple_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_17); - __Pyx_INCREF(((PyObject *)__pyx_n_s__estimators)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 0, ((PyObject *)__pyx_n_s__estimators)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__estimators)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__stage)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 1, ((PyObject *)__pyx_n_s__stage)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__stage)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__X)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 2, ((PyObject *)__pyx_n_s__X)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__X)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__scale)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 3, ((PyObject *)__pyx_n_s__scale)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__scale)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__out)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 4, ((PyObject *)__pyx_n_s__out)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__out)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__i)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 5, ((PyObject *)__pyx_n_s__i)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__k)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 6, ((PyObject *)__pyx_n_s__k)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__k)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_estimators)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 7, ((PyObject *)__pyx_n_s__n_estimators)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_estimators)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_samples)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 8, ((PyObject *)__pyx_n_s__n_samples)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_samples)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_features)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 9, ((PyObject *)__pyx_n_s__n_features)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_features)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__K)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 10, ((PyObject *)__pyx_n_s__K)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__K)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__tree)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 11, ((PyObject *)__pyx_n_s__tree)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__tree)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_17)); - __pyx_k_codeobj_18 = (PyObject*)__Pyx_PyCode_New(5, 0, 12, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_17, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_15, __pyx_n_s__predict_stage, 131, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_RefNannyFinishContext(); - return 0; + + /* function exit code */ __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); - return -1; + return __pyx_r; } -static int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - return 0; - __pyx_L1_error:; - return -1; -} +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ -#if PY_MAJOR_VERSION < 3 -PyMODINIT_FUNC init_gradient_boosting(void); /*proto*/ -PyMODINIT_FUNC init_gradient_boosting(void) -#else -PyMODINIT_FUNC PyInit__gradient_boosting(void); /*proto*/ -PyMODINIT_FUNC PyInit__gradient_boosting(void) -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations - #if CYTHON_REFNANNY - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); - if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); - } - #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__gradient_boosting(void)", 0); - if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __Pyx_CyFunction_USED - if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #endif - /*--- Module creation code ---*/ - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_gradient_boosting"), __pyx_methods, 0, 0, PYTHON_API_VERSION); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); - #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - /*--- Initialize various global constants etc. ---*/ - if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_module_is_main_sklearn__ensemble___gradient_boosting) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - } - /*--- Builtin init code ---*/ - if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Constants init code ---*/ - if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Global init code ---*/ - /*--- Variable export code ---*/ - /*--- Function export code ---*/ - /*--- Type init code ---*/ - /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_4tree_5_tree_Criterion = __Pyx_ImportType("sklearn.tree._tree", "Criterion", sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion), 1); if (unlikely(!__pyx_ptype_7sklearn_4tree_5_tree_Criterion)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_vtabptr_7sklearn_4tree_5_tree_Criterion = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__Pyx_GetVtable(__pyx_ptype_7sklearn_4tree_5_tree_Criterion->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_4tree_5_tree_Criterion)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_4tree_5_tree_Tree = __Pyx_ImportType("sklearn.tree._tree", "Tree", sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Tree), 1); if (unlikely(!__pyx_ptype_7sklearn_4tree_5_tree_Tree)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_vtabptr_7sklearn_4tree_5_tree_Tree = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree*)__Pyx_GetVtable(__pyx_ptype_7sklearn_4tree_5_tree_Tree->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_4tree_5_tree_Tree)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Variable import code ---*/ - /*--- Function import code ---*/ - /*--- Execution code ---*/ + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "sklearn/ensemble/_gradient_boosting.pyx":12 - * cimport cython + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":781 * - * import numpy as np # <<<<<<<<<<<<<< - * cimport numpy as np + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; - /* "sklearn/ensemble/_gradient_boosting.pyx":18 + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(3, a, b, c) * - * # Define a datatype for the data array - * DTYPE = np.float32 # <<<<<<<<<<<<<< - * ctypedef np.float32_t DTYPE_t + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) * */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__float32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__DTYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/ensemble/_gradient_boosting.pyx":96 + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(4, a, b, c, d) * - * @cython.nonecheck(False) - * def predict_stages(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< - * np.ndarray[DTYPE_t, ndim=2, mode='c'] X, double scale, - * np.ndarray[np.float64_t, ndim=2] out): - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_8ensemble_18_gradient_boosting_1predict_stages, NULL, __pyx_n_s_16); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__predict_stages, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "sklearn/ensemble/_gradient_boosting.pyx":131 + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) * - * @cython.nonecheck(False) - * def predict_stage(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< - * int stage, - * np.ndarray[DTYPE_t, ndim=2] X, double scale, */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_8ensemble_18_gradient_boosting_3predict_stage, NULL, __pyx_n_s_16); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__predict_stage, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/ensemble/_gradient_boosting.pyx":1 - * # encoding: utf-8 # <<<<<<<<<<<<<< - * # cython: cdivision=True - * # cython: boundscheck=False - */ - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":974 - * arr.base = baseptr + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":784 * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * if arr.base is NULL: - * return None + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 784; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - if (__pyx_m) { - __Pyx_AddTraceback("init sklearn.ensemble._gradient_boosting", __pyx_clineno, __pyx_lineno, __pyx_filename); - Py_DECREF(__pyx_m); __pyx_m = 0; - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init sklearn.ensemble._gradient_boosting"); - } + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); - #if PY_MAJOR_VERSION < 3 - return; - #else - return __pyx_m; - #endif + return __pyx_r; } -/* Runtime support code */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule((char *)modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif /* CYTHON_REFNANNY */ +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":786 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } - } - return result; -} +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + long __pyx_t_8; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":793 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); - #endif -} + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { - values[name-argnames] = value; - } else { - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - } - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":797 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif -bad: - return -1; -} + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); + __pyx_t_3 = 0; -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact) -{ - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; - } - if (none_allowed && obj == Py_None) return 1; - else if (exact) { - if (Py_TYPE(obj) == type) return 1; + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":798 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + if (unlikely(__pyx_v_descr->fields == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - else { - if (PyObject_TypeCheck(obj, type)) return 1; + __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; -} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); + __pyx_t_4 = 0; -static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":804 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (!__pyx_t_7) { + goto __pyx_L8_next_or; + } else { + } + __pyx_t_7 = (__pyx_v_little_endian != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_L8_next_or:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":805 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L7_bool_binop_done:; + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":806 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":816 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_6) break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":817 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":819 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":821 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":824 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":825 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":829 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":830 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":831 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":832 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":833 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":834 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":835 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":836 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":838 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":839 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":840 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":841 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":843 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":844 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":845 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L15; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":847 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L15:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":848 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":852 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 852; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + } + __pyx_L13:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":797 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":853 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":786 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":971 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":972 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":974 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":975 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":977 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":979 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":980 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":981 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":983 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":979 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + +/* Python wrapper */ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_shape = 0; + Py_ssize_t __pyx_v_itemsize; + PyObject *__pyx_v_format = 0; + PyObject *__pyx_v_mode = 0; + int __pyx_v_allocate_buffer; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[3] = ((PyObject *)__pyx_n_s_c); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mode); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_allocate_buffer); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_shape = ((PyObject*)values[0]); + __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_format = values[2]; + __pyx_v_mode = values[3]; + if (values[4]) { + __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "View.MemoryView":117 + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, + * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_v_allocate_buffer = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { + PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); + + /* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { + int __pyx_v_idx; + Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_dim; + PyObject **__pyx_v_p; + char __pyx_v_order; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + char *__pyx_t_5; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_INCREF(__pyx_v_format); + + /* "View.MemoryView":123 + * cdef PyObject **p + * + * self.ndim = len(shape) # <<<<<<<<<<<<<< + * self.itemsize = itemsize + * + */ + if (unlikely(__pyx_v_shape == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->ndim = ((int)__pyx_t_1); + + /* "View.MemoryView":124 + * + * self.ndim = len(shape) + * self.itemsize = itemsize # <<<<<<<<<<<<<< + * + * if not self.ndim: + */ + __pyx_v_self->itemsize = __pyx_v_itemsize; + + /* "View.MemoryView":126 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ + __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":127 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if itemsize <= 0: + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":129 + * raise ValueError("Empty shape tuple for cython.array") + * + * if itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ + __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":130 + * + * if itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * if isinstance(format, unicode): + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":132 + * raise ValueError("itemsize <= 0 for cython.array") + * + * if isinstance(format, unicode): # <<<<<<<<<<<<<< + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string + */ + __pyx_t_2 = PyUnicode_Check(__pyx_v_format); + __pyx_t_4 = (__pyx_t_2 != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":133 + * + * if isinstance(format, unicode): + * format = (format).encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format # keep a reference to the byte string + * self.format = self._format + */ + if (unlikely(__pyx_v_format == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", "encode"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = PyUnicode_AsASCIIString(((PyObject*)__pyx_v_format)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":134 + * if isinstance(format, unicode): + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< + * self.format = self._format + * + */ + if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_v_format; + __Pyx_INCREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->_format); + __Pyx_DECREF(__pyx_v_self->_format); + __pyx_v_self->_format = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":135 + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string + * self.format = self._format # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __Pyx_PyObject_AsString(__pyx_v_self->_format); if (unlikely((!__pyx_t_5) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->format = __pyx_t_5; + + /* "View.MemoryView":138 + * + * + * self._shape = PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< + * self._strides = self._shape + self.ndim + * + */ + __pyx_v_self->_shape = ((Py_ssize_t *)PyMem_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); + + /* "View.MemoryView":139 + * + * self._shape = PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) + * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< + * + * if not self._shape: + */ + __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); + + /* "View.MemoryView":141 + * self._strides = self._shape + self.ndim + * + * if not self._shape: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape and strides.") + * + */ + __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":142 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":145 + * + * + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + __pyx_t_6 = 0; + __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; + for (;;) { + if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_7); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_t_8 = __Pyx_PyIndex_AsSsize_t(__pyx_t_7); if (unlikely((__pyx_t_8 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_dim = __pyx_t_8; + __pyx_v_idx = __pyx_t_6; + __pyx_t_6 = (__pyx_t_6 + 1); + + /* "View.MemoryView":146 + * + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim + */ + __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":147 + * for idx, dim in enumerate(shape): + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< + * self._shape[idx] = dim + * + */ + __pyx_t_7 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_7 = 0; + __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_10, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":148 + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim # <<<<<<<<<<<<<< + * + * cdef char order + */ + (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; + + /* "View.MemoryView":145 + * + * + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":151 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = b'F' + * self.mode = u'fortran' + */ + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":152 + * cdef char order + * if mode == 'fortran': + * order = b'F' # <<<<<<<<<<<<<< + * self.mode = u'fortran' + * elif mode == 'c': + */ + __pyx_v_order = 'F'; + + /* "View.MemoryView":153 + * if mode == 'fortran': + * order = b'F' + * self.mode = u'fortran' # <<<<<<<<<<<<<< + * elif mode == 'c': + * order = b'C' + */ + __Pyx_INCREF(__pyx_n_u_fortran); + __Pyx_GIVEREF(__pyx_n_u_fortran); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(__pyx_v_self->mode); + __pyx_v_self->mode = __pyx_n_u_fortran; + goto __pyx_L10; + } + + /* "View.MemoryView":154 + * order = b'F' + * self.mode = u'fortran' + * elif mode == 'c': # <<<<<<<<<<<<<< + * order = b'C' + * self.mode = u'c' + */ + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":155 + * self.mode = u'fortran' + * elif mode == 'c': + * order = b'C' # <<<<<<<<<<<<<< + * self.mode = u'c' + * else: + */ + __pyx_v_order = 'C'; + + /* "View.MemoryView":156 + * elif mode == 'c': + * order = b'C' + * self.mode = u'c' # <<<<<<<<<<<<<< + * else: + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + */ + __Pyx_INCREF(__pyx_n_u_c); + __Pyx_GIVEREF(__pyx_n_u_c); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(__pyx_v_self->mode); + __pyx_v_self->mode = __pyx_n_u_c; + goto __pyx_L10; + } + /*else*/ { + + /* "View.MemoryView":158 + * self.mode = u'c' + * else: + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< + * + * self.len = fill_contig_strides_array(self._shape, self._strides, + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L10:; + + /* "View.MemoryView":160 + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + * + * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< + * itemsize, self.ndim, order) + * + */ + __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); + + /* "View.MemoryView":163 + * itemsize, self.ndim, order) + * + * self.free_data = allocate_buffer # <<<<<<<<<<<<<< + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + */ + __pyx_v_self->free_data = __pyx_v_allocate_buffer; + + /* "View.MemoryView":164 + * + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< + * if allocate_buffer: + * + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_4; + + /* "View.MemoryView":165 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = (__pyx_v_allocate_buffer != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":168 + * + * + * self.data = malloc(self.len) # <<<<<<<<<<<<<< + * if not self.data: + * raise MemoryError("unable to allocate array data.") + */ + __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); + + /* "View.MemoryView":169 + * + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ + __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":170 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":172 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ + __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":173 + * + * if self.dtype_is_object: + * p = self.data # <<<<<<<<<<<<<< + * for i in range(self.len / itemsize): + * p[i] = Py_None + */ + __pyx_v_p = ((PyObject **)__pyx_v_self->data); + + /* "View.MemoryView":174 + * if self.dtype_is_object: + * p = self.data + * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< + * p[i] = Py_None + * Py_INCREF(Py_None) + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = (__pyx_v_self->len / __pyx_v_itemsize); + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_1; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "View.MemoryView":175 + * p = self.data + * for i in range(self.len / itemsize): + * p[i] = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + (__pyx_v_p[__pyx_v_i]) = Py_None; + + /* "View.MemoryView":176 + * for i in range(self.len / itemsize): + * p[i] = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + Py_INCREF(Py_None); + } + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_format); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":179 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == u"c": + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_bufmode; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + Py_ssize_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":180 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 # <<<<<<<<<<<<<< + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = -1; + + /* "View.MemoryView":181 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == u"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + */ + __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":182 + * cdef int bufmode = -1 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + + /* "View.MemoryView":183 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ + __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":184 + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + */ + __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":185 + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ + __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":186 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":187 + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data # <<<<<<<<<<<<<< + * info.len = self.len + * info.ndim = self.ndim + */ + __pyx_t_4 = __pyx_v_self->data; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":188 + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + * info.len = self.len # <<<<<<<<<<<<<< + * info.ndim = self.ndim + * info.shape = self._shape + */ + __pyx_t_5 = __pyx_v_self->len; + __pyx_v_info->len = __pyx_t_5; + + /* "View.MemoryView":189 + * info.buf = self.data + * info.len = self.len + * info.ndim = self.ndim # <<<<<<<<<<<<<< + * info.shape = self._shape + * info.strides = self._strides + */ + __pyx_t_6 = __pyx_v_self->ndim; + __pyx_v_info->ndim = __pyx_t_6; + + /* "View.MemoryView":190 + * info.len = self.len + * info.ndim = self.ndim + * info.shape = self._shape # <<<<<<<<<<<<<< + * info.strides = self._strides + * info.suboffsets = NULL + */ + __pyx_t_7 = __pyx_v_self->_shape; + __pyx_v_info->shape = __pyx_t_7; + + /* "View.MemoryView":191 + * info.ndim = self.ndim + * info.shape = self._shape + * info.strides = self._strides # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = self.itemsize + */ + __pyx_t_7 = __pyx_v_self->_strides; + __pyx_v_info->strides = __pyx_t_7; + + /* "View.MemoryView":192 + * info.shape = self._shape + * info.strides = self._strides + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = self.itemsize + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; + + /* "View.MemoryView":193 + * info.strides = self._strides + * info.suboffsets = NULL + * info.itemsize = self.itemsize # <<<<<<<<<<<<<< + * info.readonly = 0 + * + */ + __pyx_t_5 = __pyx_v_self->itemsize; + __pyx_v_info->itemsize = __pyx_t_5; + + /* "View.MemoryView":194 + * info.suboffsets = NULL + * info.itemsize = self.itemsize + * info.readonly = 0 # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":196 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":197 + * + * if flags & PyBUF_FORMAT: + * info.format = self.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_4 = __pyx_v_self->format; + __pyx_v_info->format = __pyx_t_4; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":199 + * info.format = self.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.obj = self + */ + __pyx_v_info->format = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":201 + * info.format = NULL + * + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "View.MemoryView":179 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == u"c": + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":205 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + +/* Python wrapper */ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":206 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ + __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":207 + * def __dealloc__(array self): + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) # <<<<<<<<<<<<<< + * elif self.free_data: + * if self.dtype_is_object: + */ + __pyx_v_self->callback_free_data(__pyx_v_self->data); + goto __pyx_L3; + } + + /* "View.MemoryView":208 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ + __pyx_t_1 = (__pyx_v_self->free_data != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":209 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":210 + * elif self.free_data: + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< + * self._strides, self.ndim, False) + * free(self.data) + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":212 + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + * free(self.data) # <<<<<<<<<<<<<< + * PyMem_Free(self._shape) + * + */ + free(__pyx_v_self->data); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":213 + * self._strides, self.ndim, False) + * free(self.data) + * PyMem_Free(self._shape) # <<<<<<<<<<<<<< + * + * property memview: + */ + PyMem_Free(__pyx_v_self->_shape); + + /* "View.MemoryView":205 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":217 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + +/* Python wrapper */ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":219 + * def __get__(self): + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< + * return memoryview(self, flags, self.dtype_is_object) + * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":220 + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":217 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":223 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":224 + * + * def __getattr__(self, attr): + * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * + * def __getitem__(self, item): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":223 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":226 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":227 + * + * def __getitem__(self, item): + * return self.memview[item] # <<<<<<<<<<<<<< + * + * def __setitem__(self, item, value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":226 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":229 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + +/* Python wrapper */ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "View.MemoryView":230 + * + * def __setitem__(self, item, value): + * self.memview[item] = value # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":229 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":234 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + +static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { + struct __pyx_array_obj *__pyx_v_result = 0; + struct __pyx_array_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("array_cwrapper", 0); + + /* "View.MemoryView":238 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":239 + * + * if buf == NULL: + * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":241 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":242 + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) # <<<<<<<<<<<<<< + * result.data = buf + * + */ + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":241 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":243 + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) + * result.data = buf # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->data = __pyx_v_buf; + } + __pyx_L3:; + + /* "View.MemoryView":245 + * result.data = buf + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":234 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":271 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + +/* Python wrapper */ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_name = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_name = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "View.MemoryView":272 + * cdef object name + * def __init__(self, name): + * self.name = name # <<<<<<<<<<<<<< + * def __repr__(self): + * return self.name + */ + __Pyx_INCREF(__pyx_v_name); + __Pyx_GIVEREF(__pyx_v_name); + __Pyx_GOTREF(__pyx_v_self->name); + __Pyx_DECREF(__pyx_v_self->name); + __pyx_v_self->name = __pyx_v_name; + + /* "View.MemoryView":271 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":273 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + +/* Python wrapper */ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":274 + * self.name = name + * def __repr__(self): + * return self.name # <<<<<<<<<<<<<< + * + * cdef generic = Enum("") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->name); + __pyx_r = __pyx_v_self->name; + goto __pyx_L0; + + /* "View.MemoryView":273 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":288 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + +static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { + Py_intptr_t __pyx_v_aligned_p; + size_t __pyx_v_offset; + void *__pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":290 + * cdef void *align_pointer(void *memory, size_t alignment) nogil: + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< + * cdef size_t offset + * + */ + __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + + /* "View.MemoryView":294 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":296 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + __pyx_t_1 = ((__pyx_v_offset > 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":297 + * + * if offset > 0: + * aligned_p += alignment - offset # <<<<<<<<<<<<<< + * + * return aligned_p + */ + __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":299 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview') + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + /* "View.MemoryView":288 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":317 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + +/* Python wrapper */ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_obj = 0; + int __pyx_v_flags; + int __pyx_v_dtype_is_object; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dtype_is_object); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_obj = values[0]; + __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[2]) { + __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_dtype_is_object = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "View.MemoryView":318 + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj # <<<<<<<<<<<<<< + * self.flags = flags + * if type(self) is memoryview or obj is not None: + */ + __Pyx_INCREF(__pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __Pyx_GOTREF(__pyx_v_self->obj); + __Pyx_DECREF(__pyx_v_self->obj); + __pyx_v_self->obj = __pyx_v_obj; + + /* "View.MemoryView":319 + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj + * self.flags = flags # <<<<<<<<<<<<<< + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + */ + __pyx_v_self->flags = __pyx_v_flags; + + /* "View.MemoryView":320 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ + __pyx_t_2 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type))); + __pyx_t_3 = (__pyx_t_2 != 0); + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_3 = (__pyx_v_obj != Py_None); + __pyx_t_2 = (__pyx_t_3 != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L4_bool_binop_done:; + if (__pyx_t_1) { + + /* "View.MemoryView":321 + * self.flags = flags + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + */ + __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":322 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":323 + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; + + /* "View.MemoryView":324 + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * self.lock = PyThread_allocate_lock() + */ + Py_INCREF(Py_None); + goto __pyx_L6; + } + __pyx_L6:; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":326 + * Py_INCREF(Py_None) + * + * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< + * if self.lock == NULL: + * raise MemoryError + */ + __pyx_v_self->lock = PyThread_allocate_lock(); + + /* "View.MemoryView":327 + * + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":328 + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":330 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = self.view.format == b'O' + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":331 + * + * if flags & PyBUF_FORMAT: + * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< + * else: + * self.dtype_is_object = dtype_is_object + */ + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_5, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_1; + goto __pyx_L8; + } + /*else*/ { + + /* "View.MemoryView":333 + * self.dtype_is_object = self.view.format == b'O' + * else: + * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + */ + __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; + } + __pyx_L8:; + + /* "View.MemoryView":335 + * self.dtype_is_object = dtype_is_object + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL + */ + __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); + + /* "View.MemoryView":337 + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(memoryview self): + */ + __pyx_v_self->typeinfo = NULL; + + /* "View.MemoryView":317 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":339 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + +/* Python wrapper */ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":340 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< + * __Pyx_ReleaseBuffer(&self.view) + * + */ + __pyx_t_1 = (__pyx_v_self->obj != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":341 + * def __dealloc__(memoryview self): + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< + * + * if self.lock != NULL: + */ + __Pyx_ReleaseBuffer((&__pyx_v_self->view)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":343 + * __Pyx_ReleaseBuffer(&self.view) + * + * if self.lock != NULL: # <<<<<<<<<<<<<< + * PyThread_free_lock(self.lock) + * + */ + __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":344 + * + * if self.lock != NULL: + * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + */ + PyThread_free_lock(__pyx_v_self->lock); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":339 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":346 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + Py_ssize_t __pyx_v_dim; + char *__pyx_v_itemp; + PyObject *__pyx_v_idx = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_item_pointer", 0); + + /* "View.MemoryView":348 + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< + * + * for dim, idx in enumerate(index): + */ + __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); + + /* "View.MemoryView":350 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + __pyx_t_1 = 0; + if (likely(PyList_CheckExact(__pyx_v_index)) || PyTuple_CheckExact(__pyx_v_index)) { + __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + for (;;) { + if (likely(!__pyx_t_4)) { + if (likely(PyList_CheckExact(__pyx_t_2))) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); + __pyx_t_5 = 0; + __pyx_v_dim = __pyx_t_1; + __pyx_t_1 = (__pyx_t_1 + 1); + + /* "View.MemoryView":351 + * + * for dim, idx in enumerate(index): + * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< + * + * return itemp + */ + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_7; + + /* "View.MemoryView":350 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":353 + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + * return itemp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_itemp; + goto __pyx_L0; + + /* "View.MemoryView":346 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":356 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_indices = NULL; + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + char *__pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":357 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":358 + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: + * return self # <<<<<<<<<<<<<< + * + * have_slices, indices = _unellipsify(index, self.view.ndim) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __pyx_r = ((PyObject *)__pyx_v_self); + goto __pyx_L0; + } + + /* "View.MemoryView":360 + * return self + * + * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * cdef char *itemp + */ + __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (likely(__pyx_t_3 != Py_None)) { + PyObject* sequence = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_have_slices = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; + + /* "View.MemoryView":363 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":364 + * cdef char *itemp + * if have_slices: + * return memview_slice(self, indices) # <<<<<<<<<<<<<< + * else: + * itemp = self.get_item_pointer(indices) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 364; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":366 + * return memview_slice(self, indices) + * else: + * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< + * return self.convert_item_to_object(itemp) + * + */ + __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_6; + + /* "View.MemoryView":367 + * else: + * itemp = self.get_item_pointer(indices) + * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< + * + * def __setitem__(memoryview self, object index, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 367; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":356 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":369 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + +/* Python wrapper */ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_obj = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_INCREF(__pyx_v_index); + + /* "View.MemoryView":370 + * + * def __setitem__(memoryview self, object index, object value): + * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * if have_slices: + */ + __pyx_t_1 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (likely(__pyx_t_1 != Py_None)) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_have_slices = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":372 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":373 + * + * if have_slices: + * obj = self.is_slice(value) # <<<<<<<<<<<<<< + * if obj: + * self.setitem_slice_assignment(self[index], obj) + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_obj = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":374 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":375 + * obj = self.is_slice(value) + * if obj: + * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< + * else: + * self.setitem_slice_assign_scalar(self[index], value) + */ + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":377 + * self.setitem_slice_assignment(self[index], obj) + * else: + * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< + * else: + * self.setitem_indexed(index, value) + */ + __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":379 + * self.setitem_slice_assign_scalar(self[index], value) + * else: + * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< + * + * cdef is_slice(self, obj): + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":369 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":381 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_slice", 0); + __Pyx_INCREF(__pyx_v_obj); + + /* "View.MemoryView":382 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type)); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":383 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + { + __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + /*try:*/ { + + /* "View.MemoryView":384 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_6 = __Pyx_PyInt_From_int((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":385 + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * except TypeError: + * return None + */ + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":384 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); + __pyx_t_7 = 0; + } + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L11_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":386 + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + * except TypeError: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":387 + * self.dtype_is_object) + * except TypeError: + * return None # <<<<<<<<<<<<<< + * + * return obj + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L7_except_return; + } + goto __pyx_L6_except_error; + __pyx_L6_except_error:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L1_error; + __pyx_L7_except_return:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L0; + __pyx_L11_try_end:; + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":389 + * return None + * + * return obj # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assignment(self, dst, src): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_obj); + __pyx_r = __pyx_v_obj; + goto __pyx_L0; + + /* "View.MemoryView":381 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":391 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { + __Pyx_memviewslice __pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_src_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); + + /* "View.MemoryView":395 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":396 + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< + * src.ndim, dst.ndim, self.dtype_is_object) + * + */ + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":397 + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":395 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":391 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":399 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { + int __pyx_v_array[128]; + void *__pyx_v_tmp; + void *__pyx_v_item; + __Pyx_memviewslice *__pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_tmp_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + char const *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); + + /* "View.MemoryView":401 + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + * cdef int array[128] + * cdef void *tmp = NULL # <<<<<<<<<<<<<< + * cdef void *item + * + */ + __pyx_v_tmp = NULL; + + /* "View.MemoryView":406 + * cdef __Pyx_memviewslice *dst_slice + * cdef __Pyx_memviewslice tmp_slice + * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< + * + * if self.view.itemsize > sizeof(array): + */ + __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); + + /* "View.MemoryView":408 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + */ + __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":409 + * + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError + */ + __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); + + /* "View.MemoryView":410 + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":411 + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * item = tmp + * else: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":412 + * if tmp == NULL: + * raise MemoryError + * item = tmp # <<<<<<<<<<<<<< + * else: + * item = array + */ + __pyx_v_item = __pyx_v_tmp; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":414 + * item = tmp + * else: + * item = array # <<<<<<<<<<<<<< + * + * try: + */ + __pyx_v_item = ((void *)__pyx_v_array); + } + __pyx_L3:; + + /* "View.MemoryView":416 + * item = array + * + * try: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * ( item)[0] = value + */ + /*try:*/ { + + /* "View.MemoryView":417 + * + * try: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":418 + * try: + * if self.dtype_is_object: + * ( item)[0] = value # <<<<<<<<<<<<<< + * else: + * self.assign_item_from_object( item, value) + */ + (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); + goto __pyx_L8; + } + /*else*/ { + + /* "View.MemoryView":420 + * ( item)[0] = value + * else: + * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_L8:; + + /* "View.MemoryView":424 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":425 + * + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + */ + __pyx_t_2 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":426 + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< + * item, self.dtype_is_object) + * finally: + */ + __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); + } + + /* "View.MemoryView":429 + * item, self.dtype_is_object) + * finally: + * PyMem_Free(tmp) # <<<<<<<<<<<<<< + * + * cdef setitem_indexed(self, index, value): + */ + /*finally:*/ { + /*normal exit:*/{ + PyMem_Free(__pyx_v_tmp); + goto __pyx_L7; + } + /*exception exit:*/{ + __pyx_L6_error:; + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8) < 0)) __Pyx_ErrFetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_11); + __pyx_t_3 = __pyx_lineno; __pyx_t_4 = __pyx_clineno; __pyx_t_5 = __pyx_filename; + { + PyMem_Free(__pyx_v_tmp); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } + __Pyx_XGIVEREF(__pyx_t_6); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_ErrRestore(__pyx_t_6, __pyx_t_7, __pyx_t_8); + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __pyx_lineno = __pyx_t_3; __pyx_clineno = __pyx_t_4; __pyx_filename = __pyx_t_5; + goto __pyx_L1_error; + } + __pyx_L7:; + } + + /* "View.MemoryView":399 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":431 + * PyMem_Free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_indexed", 0); + + /* "View.MemoryView":432 + * + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< + * self.assign_item_from_object(itemp, value) + * + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_1; + + /* "View.MemoryView":433 + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":431 + * PyMem_Free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":435 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_v_struct = NULL; + PyObject *__pyx_v_bytesitem = 0; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + size_t __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":438 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef bytes bytesitem + * + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":441 + * cdef bytes bytesitem + * + * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< + * try: + * result = struct.unpack(self.view.format, bytesitem) + */ + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":442 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":443 + * bytesitem = itemp[:self.view.itemsize] + * try: + * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< + * except struct.error: + * raise ValueError("Unable to convert item to object") + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = NULL; + __pyx_t_8 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_5, function); + __pyx_t_8 = 1; + } + } + __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_9); + if (__pyx_t_7) { + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); __pyx_t_7 = NULL; + } + PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_INCREF(__pyx_v_bytesitem); + PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_bytesitem); + __Pyx_GIVEREF(__pyx_v_bytesitem); + __pyx_t_6 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_result = __pyx_t_1; + __pyx_t_1 = 0; + } + /*else:*/ { + + /* "View.MemoryView":447 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + __pyx_t_10 = strlen(__pyx_v_self->view.format); + __pyx_t_11 = ((__pyx_t_10 == 1) != 0); + if (__pyx_t_11) { + + /* "View.MemoryView":448 + * else: + * if len(self.view.format) == 1: + * return result[0] # <<<<<<<<<<<<<< + * return result + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L6_except_return; + } + + /* "View.MemoryView":449 + * if len(self.view.format) == 1: + * return result[0] + * return result # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L6_except_return; + } + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":444 + * try: + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: # <<<<<<<<<<<<<< + * raise ValueError("Unable to convert item to object") + * else: + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_12 = PyErr_ExceptionMatches(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_12) { + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_9); + + /* "View.MemoryView":445 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + } + goto __pyx_L5_except_error; + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L6_except_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + } + + /* "View.MemoryView":435 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesitem); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":451 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_v_struct = NULL; + char __pyx_v_c; + PyObject *__pyx_v_bytesvalue = 0; + Py_ssize_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + char *__pyx_t_10; + char *__pyx_t_11; + char *__pyx_t_12; + char *__pyx_t_13; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":454 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef char c + * cdef bytes bytesvalue + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":459 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + __pyx_t_2 = PyTuple_Check(__pyx_v_value); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":460 + * + * if isinstance(value, tuple): + * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< + * else: + * bytesvalue = struct.pack(self.view.format, value) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":462 + * bytesvalue = struct.pack(self.view.format, *value) + * else: + * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< + * + * for i, c in enumerate(bytesvalue): + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = NULL; + __pyx_t_7 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_6, function); + __pyx_t_7 = 1; + } + } + __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (__pyx_t_5) { + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; + } + PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + __pyx_t_1 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":464 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = 0; + if (unlikely(__pyx_v_bytesvalue == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_INCREF(__pyx_v_bytesvalue); + __pyx_t_9 = __pyx_v_bytesvalue; + __pyx_t_11 = PyBytes_AS_STRING(__pyx_t_9); + __pyx_t_12 = (__pyx_t_11 + PyBytes_GET_SIZE(__pyx_t_9)); + for (__pyx_t_13 = __pyx_t_11; __pyx_t_13 < __pyx_t_12; __pyx_t_13++) { + __pyx_t_10 = __pyx_t_13; + __pyx_v_c = (__pyx_t_10[0]); + + /* "View.MemoryView":465 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + __pyx_v_i = __pyx_t_7; + + /* "View.MemoryView":464 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":465 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; + } + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "View.MemoryView":451 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":468 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + char *__pyx_t_3; + void *__pyx_t_4; + int __pyx_t_5; + Py_ssize_t __pyx_t_6; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":469 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":470 + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape # <<<<<<<<<<<<<< + * else: + * info.shape = NULL + */ + __pyx_t_2 = __pyx_v_self->view.shape; + __pyx_v_info->shape = __pyx_t_2; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":472 + * info.shape = self.view.shape + * else: + * info.shape = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_STRIDES: + */ + __pyx_v_info->shape = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":474 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":475 + * + * if flags & PyBUF_STRIDES: + * info.strides = self.view.strides # <<<<<<<<<<<<<< + * else: + * info.strides = NULL + */ + __pyx_t_2 = __pyx_v_self->view.strides; + __pyx_v_info->strides = __pyx_t_2; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":477 + * info.strides = self.view.strides + * else: + * info.strides = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_INDIRECT: + */ + __pyx_v_info->strides = NULL; + } + __pyx_L4:; + + /* "View.MemoryView":479 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":480 + * + * if flags & PyBUF_INDIRECT: + * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< + * else: + * info.suboffsets = NULL + */ + __pyx_t_2 = __pyx_v_self->view.suboffsets; + __pyx_v_info->suboffsets = __pyx_t_2; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":482 + * info.suboffsets = self.view.suboffsets + * else: + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->suboffsets = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":484 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":485 + * + * if flags & PyBUF_FORMAT: + * info.format = self.view.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_3 = __pyx_v_self->view.format; + __pyx_v_info->format = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":487 + * info.format = self.view.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.buf = self.view.buf + */ + __pyx_v_info->format = NULL; + } + __pyx_L6:; + + /* "View.MemoryView":489 + * info.format = NULL + * + * info.buf = self.view.buf # <<<<<<<<<<<<<< + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + */ + __pyx_t_4 = __pyx_v_self->view.buf; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":490 + * + * info.buf = self.view.buf + * info.ndim = self.view.ndim # <<<<<<<<<<<<<< + * info.itemsize = self.view.itemsize + * info.len = self.view.len + */ + __pyx_t_5 = __pyx_v_self->view.ndim; + __pyx_v_info->ndim = __pyx_t_5; + + /* "View.MemoryView":491 + * info.buf = self.view.buf + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< + * info.len = self.view.len + * info.readonly = 0 + */ + __pyx_t_6 = __pyx_v_self->view.itemsize; + __pyx_v_info->itemsize = __pyx_t_6; + + /* "View.MemoryView":492 + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + * info.len = self.view.len # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.obj = self + */ + __pyx_t_6 = __pyx_v_self->view.len; + __pyx_v_info->len = __pyx_t_6; + + /* "View.MemoryView":493 + * info.itemsize = self.view.itemsize + * info.len = self.view.len + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.obj = self + * + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":494 + * info.len = self.view.len + * info.readonly = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "View.MemoryView":468 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + + /* function exit code */ + __pyx_r = 0; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":501 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":502 + * @cname('__pyx_memoryview_transpose') + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< + * transpose_memslice(&result.from_slice) + * return result + */ + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":503 + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":504 + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + * return result # <<<<<<<<<<<<<< + * + * property base: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":501 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":508 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":509 + * @cname('__pyx_memoryview__get__base') + * def __get__(self): + * return self.obj # <<<<<<<<<<<<<< + * + * property shape: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->obj); + __pyx_r = __pyx_v_self->obj; + goto __pyx_L0; + + /* "View.MemoryView":508 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":513 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([length for length in self.view.shape[:self.view.ndim]]) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_v_length; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t *__pyx_t_2; + Py_ssize_t *__pyx_t_3; + Py_ssize_t *__pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":514 + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): + * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< + * + * property strides: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); + for (__pyx_t_4 = __pyx_v_self->view.shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { + __pyx_t_2 = __pyx_t_4; + __pyx_v_length = (__pyx_t_2[0]); + __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_length); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":513 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([length for length in self.view.shape[:self.view.ndim]]) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":518 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_v_stride; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t *__pyx_t_3; + Py_ssize_t *__pyx_t_4; + Py_ssize_t *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":519 + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":521 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) + */ + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":523 + * raise ValueError("Buffer view does not expose strides") + * + * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< + * + * property suboffsets: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = (__pyx_v_self->view.strides + __pyx_v_self->view.ndim); + for (__pyx_t_5 = __pyx_v_self->view.strides; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { + __pyx_t_3 = __pyx_t_5; + __pyx_v_stride = (__pyx_t_3[0]); + __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_stride); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __pyx_t_6 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_6; + __pyx_t_6 = 0; + goto __pyx_L0; + + /* "View.MemoryView":518 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":527 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_v_suboffset; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + Py_ssize_t *__pyx_t_4; + Py_ssize_t *__pyx_t_5; + Py_ssize_t *__pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":528 + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return (-1,) * self.view.ndim + * + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":529 + * def __get__(self): + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__14, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":531 + * return (-1,) * self.view.ndim + * + * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< + * + * property ndim: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = (__pyx_v_self->view.suboffsets + __pyx_v_self->view.ndim); + for (__pyx_t_6 = __pyx_v_self->view.suboffsets; __pyx_t_6 < __pyx_t_5; __pyx_t_6++) { + __pyx_t_4 = __pyx_t_6; + __pyx_v_suboffset = (__pyx_t_4[0]); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_suboffset); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_t_2 = PyList_AsTuple(((PyObject*)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":527 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":535 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":536 + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): + * return self.view.ndim # <<<<<<<<<<<<<< + * + * property itemsize: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":535 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":540 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":541 + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): + * return self.view.itemsize # <<<<<<<<<<<<<< + * + * property nbytes: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 541; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":540 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":545 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":546 + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): + * return self.size * self.view.itemsize # <<<<<<<<<<<<<< + * + * property size: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":545 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":550 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + Py_ssize_t *__pyx_t_3; + Py_ssize_t *__pyx_t_4; + Py_ssize_t *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":551 + * @cname('__pyx_memoryview_get_size') + * def __get__(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + __pyx_t_1 = (__pyx_v_self->_size == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":552 + * def __get__(self): + * if self._size is None: + * result = 1 # <<<<<<<<<<<<<< + * + * for length in self.view.shape[:self.view.ndim]: + */ + __Pyx_INCREF(__pyx_int_1); + __pyx_v_result = __pyx_int_1; + + /* "View.MemoryView":554 + * result = 1 + * + * for length in self.view.shape[:self.view.ndim]: # <<<<<<<<<<<<<< + * result *= length + * + */ + __pyx_t_4 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); + for (__pyx_t_5 = __pyx_v_self->view.shape; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { + __pyx_t_3 = __pyx_t_5; + __pyx_t_6 = PyInt_FromSsize_t((__pyx_t_3[0])); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); + __pyx_t_6 = 0; + + /* "View.MemoryView":555 + * + * for length in self.view.shape[:self.view.ndim]: + * result *= length # <<<<<<<<<<<<<< + * + * self._size = result + */ + __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 555; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); + __pyx_t_6 = 0; + } + + /* "View.MemoryView":557 + * result *= length + * + * self._size = result # <<<<<<<<<<<<<< + * + * return self._size + */ + __Pyx_INCREF(__pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __Pyx_GOTREF(__pyx_v_self->_size); + __Pyx_DECREF(__pyx_v_self->_size); + __pyx_v_self->_size = __pyx_v_result; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":559 + * self._size = result + * + * return self._size # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->_size); + __pyx_r = __pyx_v_self->_size; + goto __pyx_L0; + + /* "View.MemoryView":550 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":561 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + +/* Python wrapper */ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__len__", 0); + + /* "View.MemoryView":562 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":563 + * def __len__(self): + * if self.view.ndim >= 1: + * return self.view.shape[0] # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_r = (__pyx_v_self->view.shape[0]); + goto __pyx_L0; + } + + /* "View.MemoryView":565 + * return self.view.shape[0] + * + * return 0 # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":561 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":567 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":568 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":569 + * def __repr__(self): + * return "" % (self.base.__class__.__name__, + * id(self)) # <<<<<<<<<<<<<< + * + * def __str__(self): + */ + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_id, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":568 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":567 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":571 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__str__", 0); + + /* "View.MemoryView":572 + * + * def __str__(self): + * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":571 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":575 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_c_contig", 0); + + /* "View.MemoryView":578 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":579 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< + * + * def is_f_contig(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":575 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":581 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_f_contig", 0); + + /* "View.MemoryView":584 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":585 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< + * + * def copy(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":581 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":587 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_mslice; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "View.MemoryView":589 + * def copy(self): + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &mslice) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); + + /* "View.MemoryView":591 + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + * + * slice_copy(self, &mslice) # <<<<<<<<<<<<<< + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); + + /* "View.MemoryView":592 + * + * slice_copy(self, &mslice) + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_C_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k_c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":597 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< + * + * def copy_fortran(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":587 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":599 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy_fortran", 0); + + /* "View.MemoryView":601 + * def copy_fortran(self): + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &src) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); + + /* "View.MemoryView":603 + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + * + * slice_copy(self, &src) # <<<<<<<<<<<<<< + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); + + /* "View.MemoryView":604 + * + * slice_copy(self, &src) + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_F_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k_fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dst = __pyx_t_1; + + /* "View.MemoryView":609 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":599 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":613 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + +static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { + struct __pyx_memoryview_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); + + /* "View.MemoryView":614 + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< + * result.typeinfo = typeinfo + * return result + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); + __Pyx_GIVEREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":615 + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_v_result->typeinfo = __pyx_v_typeinfo; + + /* "View.MemoryView":616 + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_check') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":613 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":619 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("memoryview_check", 0); + + /* "View.MemoryView":620 + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): + * return isinstance(o, memoryview) # <<<<<<<<<<<<<< + * + * cdef tuple _unellipsify(object index, int ndim): + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type)); + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + /* "View.MemoryView":619 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":622 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + +static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { + PyObject *__pyx_v_tup = NULL; + PyObject *__pyx_v_result = NULL; + int __pyx_v_have_slices; + int __pyx_v_seen_ellipsis; + CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_item = NULL; + Py_ssize_t __pyx_v_nslices; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_unellipsify", 0); + + /* "View.MemoryView":627 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + __pyx_t_1 = PyTuple_Check(__pyx_v_index); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":628 + * """ + * if not isinstance(index, tuple): + * tup = (index,) # <<<<<<<<<<<<<< + * else: + * tup = index + */ + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_index); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); + __Pyx_GIVEREF(__pyx_v_index); + __pyx_v_tup = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":630 + * tup = (index,) + * else: + * tup = index # <<<<<<<<<<<<<< + * + * result = [] + */ + __Pyx_INCREF(__pyx_v_index); + __pyx_v_tup = __pyx_v_index; + } + __pyx_L3:; + + /* "View.MemoryView":632 + * tup = index + * + * result = [] # <<<<<<<<<<<<<< + * have_slices = False + * seen_ellipsis = False + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_result = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":633 + * + * result = [] + * have_slices = False # <<<<<<<<<<<<<< + * seen_ellipsis = False + * for idx, item in enumerate(tup): + */ + __pyx_v_have_slices = 0; + + /* "View.MemoryView":634 + * result = [] + * have_slices = False + * seen_ellipsis = False # <<<<<<<<<<<<<< + * for idx, item in enumerate(tup): + * if item is Ellipsis: + */ + __pyx_v_seen_ellipsis = 0; + + /* "View.MemoryView":635 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_3 = __pyx_int_0; + if (likely(PyList_CheckExact(__pyx_v_tup)) || PyTuple_CheckExact(__pyx_v_tup)) { + __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_4))) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } + } else { + __pyx_t_7 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_7)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); + __pyx_t_7 = 0; + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); + __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_t_7; + __pyx_t_7 = 0; + + /* "View.MemoryView":636 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ + __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":637 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ + __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":638 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { + __Pyx_INCREF(__pyx_slice__15); + PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__15); + __Pyx_GIVEREF(__pyx_slice__15); + } + } + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":639 + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True # <<<<<<<<<<<<<< + * else: + * result.append(slice(None)) + */ + __pyx_v_seen_ellipsis = 1; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":641 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__16); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + + /* "View.MemoryView":642 + * else: + * result.append(slice(None)) + * have_slices = True # <<<<<<<<<<<<<< + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + */ + __pyx_v_have_slices = 1; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":644 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ + __pyx_t_2 = PySlice_Check(__pyx_v_item); + __pyx_t_10 = ((!(__pyx_t_2 != 0)) != 0); + if (__pyx_t_10) { + } else { + __pyx_t_1 = __pyx_t_10; + goto __pyx_L9_bool_binop_done; + } + __pyx_t_10 = ((!(PyIndex_Check(__pyx_v_item) != 0)) != 0); + __pyx_t_1 = __pyx_t_10; + __pyx_L9_bool_binop_done:; + if (__pyx_t_1) { + + /* "View.MemoryView":645 + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< + * + * have_slices = have_slices or isinstance(item, slice) + */ + __pyx_t_7 = __Pyx_PyString_Format(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_11 = PyTuple_New(1); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_11, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_Raise(__pyx_t_7, 0, 0, 0); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":647 + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< + * result.append(item) + * + */ + __pyx_t_10 = (__pyx_v_have_slices != 0); + if (!__pyx_t_10) { + } else { + __pyx_t_1 = __pyx_t_10; + goto __pyx_L11_bool_binop_done; + } + __pyx_t_10 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = (__pyx_t_10 != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L11_bool_binop_done:; + __pyx_v_have_slices = __pyx_t_1; + + /* "View.MemoryView":648 + * + * have_slices = have_slices or isinstance(item, slice) + * result.append(item) # <<<<<<<<<<<<<< + * + * nslices = ndim - len(result) + */ + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L6:; + + /* "View.MemoryView":635 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":650 + * result.append(item) + * + * nslices = ndim - len(result) # <<<<<<<<<<<<<< + * if nslices: + * result.extend([slice(None)] * nslices) + */ + __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); + + /* "View.MemoryView":651 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + __pyx_t_1 = (__pyx_v_nslices != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":652 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { + __Pyx_INCREF(__pyx_slice__17); + PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__17); + __Pyx_GIVEREF(__pyx_slice__17); + } + } + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L13; + } + __pyx_L13:; + + /* "View.MemoryView":654 + * result.extend([slice(None)] * nslices) + * + * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + */ + __Pyx_XDECREF(__pyx_r); + if (!__pyx_v_have_slices) { + } else { + __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L14_bool_binop_done; + } + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_L14_bool_binop_done:; + __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_r = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + goto __pyx_L0; + + /* "View.MemoryView":622 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_tup); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_item); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":656 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: + */ + +static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { + Py_ssize_t __pyx_v_suboffset; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + Py_ssize_t *__pyx_t_2; + Py_ssize_t *__pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); + + /* "View.MemoryView":657 + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * for suboffset in suboffsets[:ndim]: # <<<<<<<<<<<<<< + * if suboffset >= 0: + * raise ValueError("Indirect dimensions not supported") + */ + __pyx_t_2 = (__pyx_v_suboffsets + __pyx_v_ndim); + for (__pyx_t_3 = __pyx_v_suboffsets; __pyx_t_3 < __pyx_t_2; __pyx_t_3++) { + __pyx_t_1 = __pyx_t_3; + __pyx_v_suboffset = (__pyx_t_1[0]); + + /* "View.MemoryView":658 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ + __pyx_t_4 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":659 + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + + /* "View.MemoryView":656 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":666 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { + int __pyx_v_new_ndim; + int __pyx_v_suboffset_dim; + int __pyx_v_dim; + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + __Pyx_memviewslice *__pyx_v_p_src; + struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; + __Pyx_memviewslice *__pyx_v_p_dst; + int *__pyx_v_p_suboffset_dim; + Py_ssize_t __pyx_v_start; + Py_ssize_t __pyx_v_stop; + Py_ssize_t __pyx_v_step; + int __pyx_v_have_start; + int __pyx_v_have_stop; + int __pyx_v_have_step; + PyObject *__pyx_v_index = NULL; + struct __pyx_memoryview_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + struct __pyx_memoryview_obj *__pyx_t_4; + char *__pyx_t_5; + int __pyx_t_6; + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + Py_ssize_t __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memview_slice", 0); + + /* "View.MemoryView":667 + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): + * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< + * cdef bint negative_step + * cdef __Pyx_memviewslice src, dst + */ + __pyx_v_new_ndim = 0; + __pyx_v_suboffset_dim = -1; + + /* "View.MemoryView":674 + * + * + * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< + * + * cdef _memoryviewslice memviewsliceobj + */ + memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); + + /* "View.MemoryView":678 + * cdef _memoryviewslice memviewsliceobj + * + * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "View.MemoryView":680 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":681 + * + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview # <<<<<<<<<<<<<< + * p_src = &memviewsliceobj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 681; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":682 + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, &src) + */ + __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":684 + * p_src = &memviewsliceobj.from_slice + * else: + * slice_copy(memview, &src) # <<<<<<<<<<<<<< + * p_src = &src + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); + + /* "View.MemoryView":685 + * else: + * slice_copy(memview, &src) + * p_src = &src # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_src = (&__pyx_v_src); + } + __pyx_L3:; + + /* "View.MemoryView":691 + * + * + * dst.memview = p_src.memview # <<<<<<<<<<<<<< + * dst.data = p_src.data + * + */ + __pyx_t_4 = __pyx_v_p_src->memview; + __pyx_v_dst.memview = __pyx_t_4; + + /* "View.MemoryView":692 + * + * dst.memview = p_src.memview + * dst.data = p_src.data # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_v_p_src->data; + __pyx_v_dst.data = __pyx_t_5; + + /* "View.MemoryView":697 + * + * + * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< + * cdef int *p_suboffset_dim = &suboffset_dim + * cdef Py_ssize_t start, stop, step + */ + __pyx_v_p_dst = (&__pyx_v_dst); + + /* "View.MemoryView":698 + * + * cdef __Pyx_memviewslice *p_dst = &dst + * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< + * cdef Py_ssize_t start, stop, step + * cdef bint have_start, have_stop, have_step + */ + __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); + + /* "View.MemoryView":702 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + __pyx_t_6 = 0; + if (likely(PyList_CheckExact(__pyx_v_indices)) || PyTuple_CheckExact(__pyx_v_indices)) { + __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + for (;;) { + if (likely(!__pyx_t_8)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } + } else { + __pyx_t_9 = __pyx_t_8(__pyx_t_3); + if (unlikely(!__pyx_t_9)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_9); + } + __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); + __pyx_t_9 = 0; + __pyx_v_dim = __pyx_t_6; + __pyx_t_6 = (__pyx_t_6 + 1); + + /* "View.MemoryView":703 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ + __pyx_t_2 = (PyIndex_Check(__pyx_v_index) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":707 + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< + * 0, 0, 0, # have_{start,stop,step} + * False) + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 707; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":704 + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + + /* "View.MemoryView":710 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ + __pyx_t_2 = (__pyx_v_index == Py_None); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":711 + * False) + * elif index is None: + * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + */ + (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; + + /* "View.MemoryView":712 + * elif index is None: + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 + */ + (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; + + /* "View.MemoryView":713 + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< + * new_ndim += 1 + * else: + */ + (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1; + + /* "View.MemoryView":714 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 # <<<<<<<<<<<<<< + * else: + * start = index.start or 0 + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":716 + * new_ndim += 1 + * else: + * start = index.start or 0 # <<<<<<<<<<<<<< + * stop = index.stop or 0 + * step = index.step or 0 + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } else { + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_t_12; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L7_bool_binop_done; + } + __pyx_t_10 = 0; + __pyx_L7_bool_binop_done:; + __pyx_v_start = __pyx_t_10; + + /* "View.MemoryView":717 + * else: + * start = index.start or 0 + * stop = index.stop or 0 # <<<<<<<<<<<<<< + * step = index.step or 0 + * + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } else { + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_t_12; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L9_bool_binop_done; + } + __pyx_t_10 = 0; + __pyx_L9_bool_binop_done:; + __pyx_v_stop = __pyx_t_10; + + /* "View.MemoryView":718 + * start = index.start or 0 + * stop = index.stop or 0 + * step = index.step or 0 # <<<<<<<<<<<<<< + * + * have_start = index.start is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } else { + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_t_12; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L11_bool_binop_done; + } + __pyx_t_10 = 0; + __pyx_L11_bool_binop_done:; + __pyx_v_step = __pyx_t_10; + + /* "View.MemoryView":720 + * step = index.step or 0 + * + * have_start = index.start is not None # <<<<<<<<<<<<<< + * have_stop = index.stop is not None + * have_step = index.step is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 720; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = (__pyx_t_9 != Py_None); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_have_start = __pyx_t_1; + + /* "View.MemoryView":721 + * + * have_start = index.start is not None + * have_stop = index.stop is not None # <<<<<<<<<<<<<< + * have_step = index.step is not None + * + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 721; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = (__pyx_t_9 != Py_None); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_have_stop = __pyx_t_1; + + /* "View.MemoryView":722 + * have_start = index.start is not None + * have_stop = index.stop is not None + * have_step = index.step is not None # <<<<<<<<<<<<<< + * + * slice_memviewslice( + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = (__pyx_t_9 != Py_None); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_have_step = __pyx_t_1; + + /* "View.MemoryView":724 + * have_step = index.step is not None + * + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":730 + * have_start, have_stop, have_step, + * True) + * new_ndim += 1 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + } + __pyx_L6:; + + /* "View.MemoryView":702 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":732 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":733 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":734 + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 734; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":735 + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * else: + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 735; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":733 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 733; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 733; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":738 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":739 + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 738; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":738 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 738; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":666 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":763 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { + Py_ssize_t __pyx_v_new_shape; + int __pyx_v_negative_step; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":783 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":785 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + __pyx_t_1 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":786 + * + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":787 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + __pyx_t_1 = (0 <= __pyx_v_start); + if (__pyx_t_1) { + __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); + } + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":788 + * start += shape + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< + * else: + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_Index_out_of_bounds_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 788; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":791 + * else: + * + * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< + * + * if have_step and step == 0: + */ + __pyx_t_1 = ((__pyx_v_have_step != 0) != 0); + if (__pyx_t_1) { + } else { + __pyx_t_2 = __pyx_t_1; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_1 = ((__pyx_v_step < 0) != 0); + __pyx_t_2 = __pyx_t_1; + __pyx_L6_bool_binop_done:; + __pyx_v_negative_step = __pyx_t_2; + + /* "View.MemoryView":793 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + __pyx_t_1 = (__pyx_v_have_step != 0); + if (__pyx_t_1) { + } else { + __pyx_t_2 = __pyx_t_1; + goto __pyx_L9_bool_binop_done; + } + __pyx_t_1 = ((__pyx_v_step == 0) != 0); + __pyx_t_2 = __pyx_t_1; + __pyx_L9_bool_binop_done:; + if (__pyx_t_2) { + + /* "View.MemoryView":794 + * + * if have_step and step == 0: + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Step_may_not_be_zero_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":797 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + __pyx_t_2 = (__pyx_v_have_start != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":798 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":799 + * if have_start: + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if start < 0: + * start = 0 + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":800 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":801 + * start += shape + * if start < 0: + * start = 0 # <<<<<<<<<<<<<< + * elif start >= shape: + * if negative_step: + */ + __pyx_v_start = 0; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L12; + } + + /* "View.MemoryView":802 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":803 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":804 + * elif start >= shape: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = shape + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L14; + } + /*else*/ { + + /* "View.MemoryView":806 + * start = shape - 1 + * else: + * start = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_start = __pyx_v_shape; + } + __pyx_L14:; + goto __pyx_L12; + } + __pyx_L12:; + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":808 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":809 + * else: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = 0 + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L15; + } + /*else*/ { + + /* "View.MemoryView":811 + * start = shape - 1 + * else: + * start = 0 # <<<<<<<<<<<<<< + * + * if have_stop: + */ + __pyx_v_start = 0; + } + __pyx_L15:; + } + __pyx_L11:; + + /* "View.MemoryView":813 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + __pyx_t_2 = (__pyx_v_have_stop != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":814 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":815 + * if have_stop: + * if stop < 0: + * stop += shape # <<<<<<<<<<<<<< + * if stop < 0: + * stop = 0 + */ + __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); + + /* "View.MemoryView":816 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":817 + * stop += shape + * if stop < 0: + * stop = 0 # <<<<<<<<<<<<<< + * elif stop > shape: + * stop = shape + */ + __pyx_v_stop = 0; + goto __pyx_L18; + } + __pyx_L18:; + goto __pyx_L17; + } + + /* "View.MemoryView":818 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":819 + * stop = 0 + * elif stop > shape: + * stop = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_stop = __pyx_v_shape; + goto __pyx_L17; + } + __pyx_L17:; + goto __pyx_L16; + } + /*else*/ { + + /* "View.MemoryView":821 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":822 + * else: + * if negative_step: + * stop = -1 # <<<<<<<<<<<<<< + * else: + * stop = shape + */ + __pyx_v_stop = -1; + goto __pyx_L19; + } + /*else*/ { + + /* "View.MemoryView":824 + * stop = -1 + * else: + * stop = shape # <<<<<<<<<<<<<< + * + * if not have_step: + */ + __pyx_v_stop = __pyx_v_shape; + } + __pyx_L19:; + } + __pyx_L16:; + + /* "View.MemoryView":826 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":827 + * + * if not have_step: + * step = 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_step = 1; + goto __pyx_L20; + } + __pyx_L20:; + + /* "View.MemoryView":831 + * + * with cython.cdivision(True): + * new_shape = (stop - start) // step # <<<<<<<<<<<<<< + * + * if (stop - start) - step * new_shape: + */ + __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); + + /* "View.MemoryView":833 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":834 + * + * if (stop - start) - step * new_shape: + * new_shape += 1 # <<<<<<<<<<<<<< + * + * if new_shape < 0: + */ + __pyx_v_new_shape = (__pyx_v_new_shape + 1); + goto __pyx_L21; + } + __pyx_L21:; + + /* "View.MemoryView":836 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":837 + * + * if new_shape < 0: + * new_shape = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_new_shape = 0; + goto __pyx_L22; + } + __pyx_L22:; + + /* "View.MemoryView":840 + * + * + * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset + */ + (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); + + /* "View.MemoryView":841 + * + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< + * dst.suboffsets[new_ndim] = suboffset + * + */ + (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; + + /* "View.MemoryView":842 + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; + } + __pyx_L3:; + + /* "View.MemoryView":845 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":846 + * + * if suboffset_dim[0] < 0: + * dst.data += start * stride # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride + */ + __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); + goto __pyx_L23; + } + /*else*/ { + + /* "View.MemoryView":848 + * dst.data += start * stride + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< + * + * if suboffset >= 0: + */ + __pyx_t_3 = (__pyx_v_suboffset_dim[0]); + (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); + } + __pyx_L23:; + + /* "View.MemoryView":850 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":851 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":852 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":853 + * if not is_slice: + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + */ + __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); + goto __pyx_L26; + } + /*else*/ { + + /* "View.MemoryView":855 + * dst.data = ( dst.data)[0] + suboffset + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< + * "must be indexed and not sliced", dim) + * else: + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_All_dimensions_preceding_dimensi, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 855; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L26:; + goto __pyx_L25; + } + /*else*/ { + + /* "View.MemoryView":858 + * "must be indexed and not sliced", dim) + * else: + * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< + * + * return 0 + */ + (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; + } + __pyx_L25:; + goto __pyx_L24; + } + __pyx_L24:; + + /* "View.MemoryView":860 + * suboffset_dim[0] = new_ndim + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":763 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":866 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + +static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { + Py_ssize_t __pyx_v_shape; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_suboffset; + Py_ssize_t __pyx_v_itemsize; + char *__pyx_v_resultp; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pybuffer_index", 0); + + /* "View.MemoryView":868 + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< + * cdef Py_ssize_t itemsize = view.itemsize + * cdef char *resultp + */ + __pyx_v_suboffset = -1; + + /* "View.MemoryView":869 + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< + * cdef char *resultp + * + */ + __pyx_t_1 = __pyx_v_view->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":872 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":873 + * + * if view.ndim == 0: + * shape = view.len / itemsize # <<<<<<<<<<<<<< + * stride = itemsize + * else: + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 873; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 873; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_shape = (__pyx_v_view->len / __pyx_v_itemsize); + + /* "View.MemoryView":874 + * if view.ndim == 0: + * shape = view.len / itemsize + * stride = itemsize # <<<<<<<<<<<<<< + * else: + * shape = view.shape[dim] + */ + __pyx_v_stride = __pyx_v_itemsize; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":876 + * stride = itemsize + * else: + * shape = view.shape[dim] # <<<<<<<<<<<<<< + * stride = view.strides[dim] + * if view.suboffsets != NULL: + */ + __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); + + /* "View.MemoryView":877 + * else: + * shape = view.shape[dim] + * stride = view.strides[dim] # <<<<<<<<<<<<<< + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] + */ + __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); + + /* "View.MemoryView":878 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":879 + * stride = view.strides[dim] + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< + * + * if index < 0: + */ + __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); + goto __pyx_L4; + } + __pyx_L4:; + } + __pyx_L3:; + + /* "View.MemoryView":881 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":882 + * + * if index < 0: + * index += view.shape[dim] # <<<<<<<<<<<<<< + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + */ + __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); + + /* "View.MemoryView":883 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":884 + * index += view.shape[dim] + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * if index >= shape: + */ + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":886 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":887 + * + * if index >= shape: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * resultp = bufp + index * stride + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":889 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * resultp = bufp + index * stride # <<<<<<<<<<<<<< + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset + */ + __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); + + /* "View.MemoryView":890 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":891 + * resultp = bufp + index * stride + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< + * + * return resultp + */ + __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":893 + * resultp = ( resultp)[0] + suboffset + * + * return resultp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_resultp; + goto __pyx_L0; + + /* "View.MemoryView":866 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":899 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + +static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { + int __pyx_v_ndim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + int __pyx_v_i; + int __pyx_v_j; + int __pyx_r; + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + long __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":900 + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: + * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< + * + * cdef Py_ssize_t *shape = memslice.shape + */ + __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; + __pyx_v_ndim = __pyx_t_1; + + /* "View.MemoryView":902 + * cdef int ndim = memslice.memview.view.ndim + * + * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< + * cdef Py_ssize_t *strides = memslice.strides + * + */ + __pyx_t_2 = __pyx_v_memslice->shape; + __pyx_v_shape = __pyx_t_2; + + /* "View.MemoryView":903 + * + * cdef Py_ssize_t *shape = memslice.shape + * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_v_memslice->strides; + __pyx_v_strides = __pyx_t_2; + + /* "View.MemoryView":907 + * + * cdef int i, j + * for i in range(ndim / 2): # <<<<<<<<<<<<<< + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + */ + __pyx_t_3 = (__pyx_v_ndim / 2); + for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":908 + * cdef int i, j + * for i in range(ndim / 2): + * j = ndim - 1 - i # <<<<<<<<<<<<<< + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] + */ + __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); + + /* "View.MemoryView":909 + * for i in range(ndim / 2): + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< + * shape[i], shape[j] = shape[j], shape[i] + * + */ + __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); + __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); + (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; + (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; + + /* "View.MemoryView":910 + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + */ + __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); + __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); + (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; + (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; + + /* "View.MemoryView":912 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L6_bool_binop_done:; + if (__pyx_t_6) { + + /* "View.MemoryView":913 + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< + * + * return 1 + */ + __pyx_t_8 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_Cannot_transpose_memoryview_with); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 913; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "View.MemoryView":915 + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + * return 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 1; + goto __pyx_L0; + + /* "View.MemoryView":899 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":932 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + +/* Python wrapper */ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":933 + * + * def __dealloc__(self): + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); + + /* "View.MemoryView":932 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":935 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":936 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":937 + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) # <<<<<<<<<<<<<< + * else: + * return memoryview.convert_item_to_object(self, itemp) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 937; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":939 + * return self.to_object_func(itemp) + * else: + * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 939; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":935 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":941 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":942 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":943 + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< + * else: + * memoryview.assign_item_from_object(self, itemp, value) + */ + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":945 + * self.to_dtype_func(itemp, value) + * else: + * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< + * + * property base: + */ + __pyx_t_3 = __pyx_memoryview_assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 945; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":941 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":949 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":950 + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): + * return self.from_object # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->from_object); + __pyx_r = __pyx_v_self->from_object; + goto __pyx_L0; + + /* "View.MemoryView":949 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":956 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + Py_ssize_t __pyx_v_suboffset; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_TypeInfo *__pyx_t_4; + Py_buffer __pyx_t_5; + Py_ssize_t *__pyx_t_6; + Py_ssize_t *__pyx_t_7; + Py_ssize_t *__pyx_t_8; + Py_ssize_t __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_fromslice", 0); + + /* "View.MemoryView":964 + * cdef _memoryviewslice result + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":965 + * + * if memviewslice.memview == Py_None: + * return None # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + + /* "View.MemoryView":970 + * + * + * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< + * + * result.from_slice = memviewslice + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 970; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 970; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 970; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":972 + * result = _memoryviewslice(None, 0, dtype_is_object) + * + * result.from_slice = memviewslice # <<<<<<<<<<<<<< + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + */ + __pyx_v_result->from_slice = __pyx_v_memviewslice; + + /* "View.MemoryView":973 + * + * result.from_slice = memviewslice + * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< + * + * result.from_object = ( memviewslice.memview).base + */ + __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); + + /* "View.MemoryView":975 + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< + * result.typeinfo = memviewslice.memview.typeinfo + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 975; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_result->from_object); + __Pyx_DECREF(__pyx_v_result->from_object); + __pyx_v_result->from_object = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":976 + * + * result.from_object = ( memviewslice.memview).base + * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< + * + * result.view = memviewslice.memview.view + */ + __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; + __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; + + /* "View.MemoryView":978 + * result.typeinfo = memviewslice.memview.typeinfo + * + * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + */ + __pyx_t_5 = __pyx_v_memviewslice.memview->view; + __pyx_v_result->__pyx_base.view = __pyx_t_5; + + /* "View.MemoryView":979 + * + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + */ + __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); + + /* "View.MemoryView":980 + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data + * result.view.ndim = ndim # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; + + /* "View.MemoryView":981 + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; + + /* "View.MemoryView":982 + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * result.flags = PyBUF_RECORDS + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":984 + * Py_INCREF(Py_None) + * + * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< + * + * result.view.shape = result.from_slice.shape + */ + __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; + + /* "View.MemoryView":986 + * result.flags = PyBUF_RECORDS + * + * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< + * result.view.strides = result.from_slice.strides + * + */ + __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); + + /* "View.MemoryView":987 + * + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); + + /* "View.MemoryView":990 + * + * + * result.view.suboffsets = NULL # <<<<<<<<<<<<<< + * for suboffset in result.from_slice.suboffsets[:ndim]: + * if suboffset >= 0: + */ + __pyx_v_result->__pyx_base.view.suboffsets = NULL; + + /* "View.MemoryView":991 + * + * result.view.suboffsets = NULL + * for suboffset in result.from_slice.suboffsets[:ndim]: # <<<<<<<<<<<<<< + * if suboffset >= 0: + * result.view.suboffsets = result.from_slice.suboffsets + */ + __pyx_t_7 = (__pyx_v_result->from_slice.suboffsets + __pyx_v_ndim); + for (__pyx_t_8 = __pyx_v_result->from_slice.suboffsets; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { + __pyx_t_6 = __pyx_t_8; + __pyx_v_suboffset = (__pyx_t_6[0]); + + /* "View.MemoryView":992 + * result.view.suboffsets = NULL + * for suboffset in result.from_slice.suboffsets[:ndim]: + * if suboffset >= 0: # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * break + */ + __pyx_t_1 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":993 + * for suboffset in result.from_slice.suboffsets[:ndim]: + * if suboffset >= 0: + * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + + /* "View.MemoryView":994 + * if suboffset >= 0: + * result.view.suboffsets = result.from_slice.suboffsets + * break # <<<<<<<<<<<<<< + * + * result.view.len = result.view.itemsize + */ + goto __pyx_L5_break; + } + } + __pyx_L5_break:; + + /* "View.MemoryView":996 + * break + * + * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< + * for length in result.view.shape[:ndim]: + * result.view.len *= length + */ + __pyx_t_9 = __pyx_v_result->__pyx_base.view.itemsize; + __pyx_v_result->__pyx_base.view.len = __pyx_t_9; + + /* "View.MemoryView":997 + * + * result.view.len = result.view.itemsize + * for length in result.view.shape[:ndim]: # <<<<<<<<<<<<<< + * result.view.len *= length + * + */ + __pyx_t_7 = (__pyx_v_result->__pyx_base.view.shape + __pyx_v_ndim); + for (__pyx_t_8 = __pyx_v_result->__pyx_base.view.shape; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { + __pyx_t_6 = __pyx_t_8; + __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_6[0])); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":998 + * result.view.len = result.view.itemsize + * for length in result.view.shape[:ndim]: + * result.view.len *= length # <<<<<<<<<<<<<< + * + * result.to_object_func = to_object_func + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_result->__pyx_base.view.len); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_t_2, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result->__pyx_base.view.len = __pyx_t_9; + } + + /* "View.MemoryView":1000 + * result.view.len *= length + * + * result.to_object_func = to_object_func # <<<<<<<<<<<<<< + * result.to_dtype_func = to_dtype_func + * + */ + __pyx_v_result->to_object_func = __pyx_v_to_object_func; + + /* "View.MemoryView":1001 + * + * result.to_object_func = to_object_func + * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; + + /* "View.MemoryView":1003 + * result.to_dtype_func = to_dtype_func + * + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":956 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1006 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { + struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; + __Pyx_memviewslice *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_slice_from_memview", 0); + + /* "View.MemoryView":1009 + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1010 + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): + * obj = memview # <<<<<<<<<<<<<< + * return &obj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1010; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":1011 + * if isinstance(memview, _memoryviewslice): + * obj = memview + * return &obj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, mslice) + */ + __pyx_r = (&__pyx_v_obj->from_slice); + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1013 + * return &obj.from_slice + * else: + * slice_copy(memview, mslice) # <<<<<<<<<<<<<< + * return mslice + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); + + /* "View.MemoryView":1014 + * else: + * slice_copy(memview, mslice) + * return mslice # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_copy') + */ + __pyx_r = __pyx_v_mslice; + goto __pyx_L0; + } + + /* "View.MemoryView":1006 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_obj); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1017 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { + int __pyx_v_dim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + Py_ssize_t *__pyx_v_suboffsets; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + Py_ssize_t __pyx_t_4; + __Pyx_RefNannySetupContext("slice_copy", 0); + + /* "View.MemoryView":1021 + * cdef (Py_ssize_t*) shape, strides, suboffsets + * + * shape = memview.view.shape # <<<<<<<<<<<<<< + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets + */ + __pyx_t_1 = __pyx_v_memview->view.shape; + __pyx_v_shape = __pyx_t_1; + + /* "View.MemoryView":1022 + * + * shape = memview.view.shape + * strides = memview.view.strides # <<<<<<<<<<<<<< + * suboffsets = memview.view.suboffsets + * + */ + __pyx_t_1 = __pyx_v_memview->view.strides; + __pyx_v_strides = __pyx_t_1; + + /* "View.MemoryView":1023 + * shape = memview.view.shape + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< + * + * dst.memview = <__pyx_memoryview *> memview + */ + __pyx_t_1 = __pyx_v_memview->view.suboffsets; + __pyx_v_suboffsets = __pyx_t_1; + + /* "View.MemoryView":1025 + * suboffsets = memview.view.suboffsets + * + * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< + * dst.data = memview.view.buf + * + */ + __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); + + /* "View.MemoryView":1026 + * + * dst.memview = <__pyx_memoryview *> memview + * dst.data = memview.view.buf # <<<<<<<<<<<<<< + * + * for dim in range(memview.view.ndim): + */ + __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); + + /* "View.MemoryView":1028 + * dst.data = memview.view.buf + * + * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + */ + __pyx_t_2 = __pyx_v_memview->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_dim = __pyx_t_3; + + /* "View.MemoryView":1029 + * + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< + * dst.strides[dim] = strides[dim] + * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 + */ + (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); + + /* "View.MemoryView":1030 + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< + * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 + * + */ + (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); + + /* "View.MemoryView":1031 + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object') + */ + if ((__pyx_v_suboffsets != 0)) { + __pyx_t_4 = (__pyx_v_suboffsets[__pyx_v_dim]); + } else { + __pyx_t_4 = -1; + } + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_4; + } + + /* "View.MemoryView":1017 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1034 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { + __Pyx_memviewslice __pyx_v_memviewslice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy", 0); + + /* "View.MemoryView":1037 + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< + * return memoryview_copy_from_slice(memview, &memviewslice) + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); + + /* "View.MemoryView":1038 + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) + * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object_from_slice') + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1034 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1041 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { + PyObject *(*__pyx_v_to_object_func)(char *); + int (*__pyx_v_to_dtype_func)(char *, PyObject *); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *(*__pyx_t_3)(char *); + int (*__pyx_t_4)(char *, PyObject *); + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); + + /* "View.MemoryView":1048 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1049 + * + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + */ + __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; + __pyx_v_to_object_func = __pyx_t_3; + + /* "View.MemoryView":1050 + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< + * else: + * to_object_func = NULL + */ + __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; + __pyx_v_to_dtype_func = __pyx_t_4; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1052 + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + * to_object_func = NULL # <<<<<<<<<<<<<< + * to_dtype_func = NULL + * + */ + __pyx_v_to_object_func = NULL; + + /* "View.MemoryView":1053 + * else: + * to_object_func = NULL + * to_dtype_func = NULL # <<<<<<<<<<<<<< + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + */ + __pyx_v_to_dtype_func = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":1055 + * to_dtype_func = NULL + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< + * to_object_func, to_dtype_func, + * memview.dtype_is_object) + */ + __Pyx_XDECREF(__pyx_r); + + /* "View.MemoryView":1057 + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + * to_object_func, to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1055; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1041 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1063 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + +static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { + Py_ssize_t __pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":1064 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + __pyx_t_1 = ((__pyx_v_arg < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1065 + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: + * return -arg # <<<<<<<<<<<<<< + * else: + * return arg + */ + __pyx_r = (-__pyx_v_arg); + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1067 + * return -arg + * else: + * return arg # <<<<<<<<<<<<<< + * + * @cname('__pyx_get_best_slice_order') + */ + __pyx_r = __pyx_v_arg; + goto __pyx_L0; + } + + /* "View.MemoryView":1063 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1070 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + +static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_c_stride; + Py_ssize_t __pyx_v_f_stride; + char __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1075 + * """ + * cdef int i + * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t f_stride = 0 + * + */ + __pyx_v_c_stride = 0; + + /* "View.MemoryView":1076 + * cdef int i + * cdef Py_ssize_t c_stride = 0 + * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_f_stride = 0; + + /* "View.MemoryView":1078 + * cdef Py_ssize_t f_stride = 0 + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1079 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1080 + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1081 + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + goto __pyx_L4_break; + } + } + __pyx_L4_break:; + + /* "View.MemoryView":1083 + * break + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1084 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1085 + * for i in range(ndim): + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1086 + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + */ + goto __pyx_L7_break; + } + } + __pyx_L7_break:; + + /* "View.MemoryView":1088 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1089 + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + * return 'C' # <<<<<<<<<<<<<< + * else: + * return 'F' + */ + __pyx_r = 'C'; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1091 + * return 'C' + * else: + * return 'F' # <<<<<<<<<<<<<< + * + * @cython.cdivision(True) + */ + __pyx_r = 'F'; + goto __pyx_L0; + } + + /* "View.MemoryView":1070 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1094 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + +static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; + Py_ssize_t __pyx_v_dst_extent; + Py_ssize_t __pyx_v_src_stride; + Py_ssize_t __pyx_v_dst_stride; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + + /* "View.MemoryView":1101 + * + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + */ + __pyx_v_src_extent = (__pyx_v_src_shape[0]); + + /* "View.MemoryView":1102 + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] + */ + __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); + + /* "View.MemoryView":1103 + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + */ + __pyx_v_src_stride = (__pyx_v_src_strides[0]); + + /* "View.MemoryView":1104 + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); + + /* "View.MemoryView":1106 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1107 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + __pyx_t_2 = ((__pyx_v_src_stride > 0) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L5_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L5_bool_binop_done; + } + + /* "View.MemoryView":1108 + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + */ + __pyx_t_2 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); + if (__pyx_t_2) { + __pyx_t_2 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); + } + __pyx_t_3 = (__pyx_t_2 != 0); + __pyx_t_1 = __pyx_t_3; + __pyx_L5_bool_binop_done:; + if (__pyx_t_1) { + + /* "View.MemoryView":1109 + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":1111 + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + */ + __pyx_t_4 = __pyx_v_dst_extent; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1112 + * else: + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); + + /* "View.MemoryView":1113 + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * else: + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1114 + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1116 + * dst_data += dst_stride + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * _copy_strided_to_strided(src_data, src_strides + 1, + * dst_data, dst_strides + 1, + */ + __pyx_t_4 = __pyx_v_dst_extent; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1117 + * else: + * for i in range(dst_extent): + * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< + * dst_data, dst_strides + 1, + * src_shape + 1, dst_shape + 1, + */ + _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); + + /* "View.MemoryView":1121 + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1122 + * ndim - 1, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1094 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + + /* function exit code */ +} + +/* "View.MemoryView":1124 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + +static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + + /* "View.MemoryView":1127 + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< + * src.shape, dst.shape, ndim, itemsize) + * + */ + _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1124 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1131 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_size; + Py_ssize_t __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1134 + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_size = __pyx_t_1; + + /* "View.MemoryView":1136 + * cdef Py_ssize_t size = src.memview.view.itemsize + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * size *= src.shape[i] + * + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1137 + * + * for i in range(ndim): + * size *= src.shape[i] # <<<<<<<<<<<<<< + * + * return size + */ + __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); + } + + /* "View.MemoryView":1139 + * size *= src.shape[i] + * + * return size # <<<<<<<<<<<<<< + * + * @cname('__pyx_fill_contig_strides_array') + */ + __pyx_r = __pyx_v_size; + goto __pyx_L0; + + /* "View.MemoryView":1131 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1142 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { + int __pyx_v_idx; + Py_ssize_t __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1151 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + __pyx_t_1 = ((__pyx_v_order == 'F') != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1152 + * + * if order == 'F': + * for idx in range(ndim): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_idx = __pyx_t_3; + + /* "View.MemoryView":1153 + * if order == 'F': + * for idx in range(ndim): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * else: + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1154 + * for idx in range(ndim): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * else: + * for idx in range(ndim - 1, -1, -1): + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1156 + * stride = stride * shape[idx] + * else: + * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { + __pyx_v_idx = __pyx_t_2; + + /* "View.MemoryView":1157 + * else: + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1158 + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * + * return stride + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + } + __pyx_L3:; + + /* "View.MemoryView":1160 + * stride = stride * shape[idx] + * + * return stride # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_data_to_temp') + */ + __pyx_r = __pyx_v_stride; + goto __pyx_L0; + + /* "View.MemoryView":1142 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1163 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { + int __pyx_v_i; + void *__pyx_v_result; + size_t __pyx_v_itemsize; + size_t __pyx_v_size; + void *__pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + struct __pyx_memoryview_obj *__pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1174 + * cdef void *result + * + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef size_t size = slice_get_size(src, ndim) + * + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1175 + * + * cdef size_t itemsize = src.memview.view.itemsize + * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< + * + * result = malloc(size) + */ + __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); + + /* "View.MemoryView":1177 + * cdef size_t size = slice_get_size(src, ndim) + * + * result = malloc(size) # <<<<<<<<<<<<<< + * if not result: + * _err(MemoryError, NULL) + */ + __pyx_v_result = malloc(__pyx_v_size); + + /* "View.MemoryView":1178 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1179 + * result = malloc(size) + * if not result: + * _err(MemoryError, NULL) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1182 + * + * + * tmpslice.data = result # <<<<<<<<<<<<<< + * tmpslice.memview = src.memview + * for i in range(ndim): + */ + __pyx_v_tmpslice->data = ((char *)__pyx_v_result); + + /* "View.MemoryView":1183 + * + * tmpslice.data = result + * tmpslice.memview = src.memview # <<<<<<<<<<<<<< + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + */ + __pyx_t_4 = __pyx_v_src->memview; + __pyx_v_tmpslice->memview = __pyx_t_4; + + /* "View.MemoryView":1184 + * tmpslice.data = result + * tmpslice.memview = src.memview + * for i in range(ndim): # <<<<<<<<<<<<<< + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1185 + * tmpslice.memview = src.memview + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< + * tmpslice.suboffsets[i] = -1 + * + */ + (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); + + /* "View.MemoryView":1186 + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + */ + (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1188 + * tmpslice.suboffsets[i] = -1 + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< + * ndim, order) + * + */ + __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); + + /* "View.MemoryView":1192 + * + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1193 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1194 + * for i in range(ndim): + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< + * + * if slice_is_contig(src, order, ndim): + */ + (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1196 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1197 + * + * if slice_is_contig(src, order, ndim): + * memcpy(result, src.data, size) # <<<<<<<<<<<<<< + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + */ + memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1199 + * memcpy(result, src.data, size) + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< + * + * return result + */ + copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); + } + __pyx_L9:; + + /* "View.MemoryView":1201 + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":1163 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = NULL; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1206 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + +static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_extents", 0); + + /* "View.MemoryView":1209 + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + * (i, extent1, extent2)) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err_dim') + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + + /* "View.MemoryView":1208 + * cdef int _err_extents(int i, Py_ssize_t extent1, + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< + * (i, extent1, extent2)) + * + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1206 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1212 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + +static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_dim", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1213 + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: + * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err') + */ + __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_INCREF(__pyx_v_error); + __pyx_t_3 = __pyx_v_error; __pyx_t_2 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (!__pyx_t_2) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = NULL; + PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1212 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1216 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + +static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1217 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ + __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1218 + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: + * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< + * else: + * raise error + */ + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_error); + __pyx_t_4 = __pyx_v_error; __pyx_t_5 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + } + } + if (!__pyx_t_5) { + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_GOTREF(__pyx_t_2); + } else { + __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; + PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + /*else*/ { + + /* "View.MemoryView":1220 + * raise error(msg.decode('ascii')) + * else: + * raise error # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_contents') + */ + __Pyx_Raise(__pyx_v_error, 0, 0, 0); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":1216 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1223 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { + void *__pyx_v_tmpdata; + size_t __pyx_v_itemsize; + int __pyx_v_i; + char __pyx_v_order; + int __pyx_v_broadcasting; + int __pyx_v_direct_copy; + __Pyx_memviewslice __pyx_v_tmp; + int __pyx_v_ndim; + int __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + void *__pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1231 + * Check for overlapping memory and verify the shapes. + * """ + * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + */ + __pyx_v_tmpdata = NULL; + + /* "View.MemoryView":1232 + * """ + * cdef void *tmpdata = NULL + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + */ + __pyx_t_1 = __pyx_v_src.memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1234 + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< + * cdef bint broadcasting = False + * cdef bint direct_copy = False + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); + + /* "View.MemoryView":1235 + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False # <<<<<<<<<<<<<< + * cdef bint direct_copy = False + * cdef __Pyx_memviewslice tmp + */ + __pyx_v_broadcasting = 0; + + /* "View.MemoryView":1236 + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False + * cdef bint direct_copy = False # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice tmp + * + */ + __pyx_v_direct_copy = 0; + + /* "View.MemoryView":1239 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ + __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1240 + * + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); + goto __pyx_L3; + } + + /* "View.MemoryView":1241 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ + __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1242 + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< + * + * cdef int ndim = max(src_ndim, dst_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1244 + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_3 = __pyx_v_dst_ndim; + __pyx_t_4 = __pyx_v_src_ndim; + if (((__pyx_t_3 > __pyx_t_4) != 0)) { + __pyx_t_5 = __pyx_t_3; + } else { + __pyx_t_5 = __pyx_t_4; + } + __pyx_v_ndim = __pyx_t_5; + + /* "View.MemoryView":1246 + * cdef int ndim = max(src_ndim, dst_ndim) + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1247 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1248 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1249 + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + * broadcasting = True # <<<<<<<<<<<<<< + * src.strides[i] = 0 + * else: + */ + __pyx_v_broadcasting = 1; + + /* "View.MemoryView":1250 + * if src.shape[i] == 1: + * broadcasting = True + * src.strides[i] = 0 # <<<<<<<<<<<<<< + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) + */ + (__pyx_v_src.strides[__pyx_v_i]) = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":1252 + * src.strides[i] = 0 + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< + * + * if src.suboffsets[i] >= 0: + */ + __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":1254 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ + __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1255 + * + * if src.suboffsets[i] >= 0: + * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< + * + * if slices_overlap(&src, &dst, ndim, itemsize): + */ + __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Dimension_d_is_not_direct, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1257 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(&src, order, ndim): + */ + __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1259 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1260 + * + * if not slice_is_contig(&src, order, ndim): + * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":1262 + * order = get_best_order(&dst, ndim) + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< + * src = tmp + * + */ + __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_tmpdata = __pyx_t_6; + + /* "View.MemoryView":1263 + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + * src = tmp # <<<<<<<<<<<<<< + * + * if not broadcasting: + */ + __pyx_v_src = __pyx_v_tmp; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":1265 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1268 + * + * + * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1269 + * + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); + goto __pyx_L12; + } + + /* "View.MemoryView":1270 + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1271 + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< + * + * if direct_copy: + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":1273 + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_2 = (__pyx_v_direct_copy != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1275 + * if direct_copy: + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1276 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) + */ + memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); + + /* "View.MemoryView":1277 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * free(tmpdata) + * return 0 + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1278 + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1279 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * if order == 'F' == get_best_order(&dst, ndim): + */ + __pyx_r = 0; + goto __pyx_L0; + } + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":1281 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = (__pyx_v_order == 'F'); + if (__pyx_t_2) { + __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); + } + __pyx_t_7 = (__pyx_t_2 != 0); + if (__pyx_t_7) { + + /* "View.MemoryView":1284 + * + * + * transpose_memslice(&src) # <<<<<<<<<<<<<< + * transpose_memslice(&dst) + * + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1285 + * + * transpose_memslice(&src) + * transpose_memslice(&dst) # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":1287 + * transpose_memslice(&dst) + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1288 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + */ + copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1289 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * free(tmpdata) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1291 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1292 + * + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_broadcast_leading') + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":1223 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1295 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim, int __pyx_v_ndim_other) { + int __pyx_v_i; + int __pyx_v_offset; + int __pyx_t_1; + int __pyx_t_2; + + /* "View.MemoryView":1299 + * int ndim_other) nogil: + * cdef int i + * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); + + /* "View.MemoryView":1301 + * cdef int offset = ndim_other - ndim + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * mslice.shape[i + offset] = mslice.shape[i] + * mslice.strides[i + offset] = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1302 + * + * for i in range(ndim - 1, -1, -1): + * mslice.shape[i + offset] = mslice.shape[i] # <<<<<<<<<<<<<< + * mslice.strides[i + offset] = mslice.strides[i] + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] + */ + (__pyx_v_mslice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->shape[__pyx_v_i]); + + /* "View.MemoryView":1303 + * for i in range(ndim - 1, -1, -1): + * mslice.shape[i + offset] = mslice.shape[i] + * mslice.strides[i + offset] = mslice.strides[i] # <<<<<<<<<<<<<< + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] + * + */ + (__pyx_v_mslice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1304 + * mslice.shape[i + offset] = mslice.shape[i] + * mslice.strides[i + offset] = mslice.strides[i] + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] # <<<<<<<<<<<<<< + * + * for i in range(offset): + */ + (__pyx_v_mslice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->suboffsets[__pyx_v_i]); + } + + /* "View.MemoryView":1306 + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] + * + * for i in range(offset): # <<<<<<<<<<<<<< + * mslice.shape[i] = 1 + * mslice.strides[i] = mslice.strides[0] + */ + __pyx_t_1 = __pyx_v_offset; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1307 + * + * for i in range(offset): + * mslice.shape[i] = 1 # <<<<<<<<<<<<<< + * mslice.strides[i] = mslice.strides[0] + * mslice.suboffsets[i] = -1 + */ + (__pyx_v_mslice->shape[__pyx_v_i]) = 1; + + /* "View.MemoryView":1308 + * for i in range(offset): + * mslice.shape[i] = 1 + * mslice.strides[i] = mslice.strides[0] # <<<<<<<<<<<<<< + * mslice.suboffsets[i] = -1 + * + */ + (__pyx_v_mslice->strides[__pyx_v_i]) = (__pyx_v_mslice->strides[0]); + + /* "View.MemoryView":1309 + * mslice.shape[i] = 1 + * mslice.strides[i] = mslice.strides[0] + * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1295 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1317 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { + int __pyx_t_1; + + /* "View.MemoryView":1321 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + __pyx_t_1 = (__pyx_v_dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1322 + * + * if dtype_is_object: + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< + * dst.strides, ndim, inc) + * + */ + __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1317 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + + /* function exit code */ +} + +/* "View.MemoryView":1326 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + __Pyx_RefNannyDeclarations + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); + + /* "View.MemoryView":1329 + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); + + /* "View.MemoryView":1326 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif +} + +/* "View.MemoryView":1332 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + +static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); + + /* "View.MemoryView":1336 + * cdef Py_ssize_t i + * + * for i in range(shape[0]): # <<<<<<<<<<<<<< + * if ndim == 1: + * if inc: + */ + __pyx_t_1 = (__pyx_v_shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1337 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1338 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + __pyx_t_3 = (__pyx_v_inc != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1339 + * if ndim == 1: + * if inc: + * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * Py_DECREF(( data)[0]) + */ + Py_INCREF((((PyObject **)__pyx_v_data)[0])); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":1341 + * Py_INCREF(( data)[0]) + * else: + * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + */ + Py_DECREF((((PyObject **)__pyx_v_data)[0])); + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1343 + * Py_DECREF(( data)[0]) + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, inc) + * + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); + } + __pyx_L5:; + + /* "View.MemoryView":1346 + * ndim - 1, inc) + * + * data += strides[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); + } + + /* "View.MemoryView":1332 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1352 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { + + /* "View.MemoryView":1355 + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1356 + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1358 + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1352 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1362 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + +static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_extent; + int __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + + /* "View.MemoryView":1366 + * size_t itemsize, void *item) nogil: + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t extent = shape[0] + * + */ + __pyx_v_stride = (__pyx_v_strides[0]); + + /* "View.MemoryView":1367 + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] + * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_extent = (__pyx_v_shape[0]); + + /* "View.MemoryView":1369 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1370 + * + * if ndim == 1: + * for i in range(extent): # <<<<<<<<<<<<<< + * memcpy(data, item, itemsize) + * data += stride + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1371 + * if ndim == 1: + * for i in range(extent): + * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< + * data += stride + * else: + */ + memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); + + /* "View.MemoryView":1372 + * for i in range(extent): + * memcpy(data, item, itemsize) + * data += stride # <<<<<<<<<<<<<< + * else: + * for i in range(extent): + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1374 + * data += stride + * else: + * for i in range(extent): # <<<<<<<<<<<<<< + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1375 + * else: + * for i in range(extent): + * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, itemsize, item) + * data += stride + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1377 + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + * data += stride # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1362 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + + /* function exit code */ +} + +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_array_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_array_obj *)o); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_array___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->mode); + Py_CLEAR(p->_format); + (*Py_TYPE(o)->tp_free)(o); +} +static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_array___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { + PyObject *v = PyObject_GenericGetAttr(o, n); + if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + v = __pyx_array___getattr__(o, n); + } + return v; +} + +static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { + return get_memview(o); +} + +static PyMethodDef __pyx_methods_array[] = { + {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_array[] = { + {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_array = { + 0, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_array, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_array = { + 0, /*mp_length*/ + __pyx_array___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_array = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + __pyx_array_getbuffer, /*bf_getbuffer*/ + 0, /*bf_releasebuffer*/ +}; + +static PyTypeObject __pyx_type___pyx_array = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.ensemble._gradient_boosting.array", /*tp_name*/ + sizeof(struct __pyx_array_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_array, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + __pyx_tp_getattro_array, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_array, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_array, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_array, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_MemviewEnum_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_MemviewEnum_obj *)o); + p->name = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->name); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + if (p->name) { + e = (*v)(p->name, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_Enum(PyObject *o) { + PyObject* tmp; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + tmp = ((PyObject*)p->name); + p->name = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_Enum[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_MemviewEnum = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.ensemble._gradient_boosting.Enum", /*tp_name*/ + sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_Enum, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_MemviewEnum___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_Enum, /*tp_traverse*/ + __pyx_tp_clear_Enum, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_Enum, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_MemviewEnum___init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_Enum, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; + +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryview_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryview_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_memoryview; + p->obj = Py_None; Py_INCREF(Py_None); + p->_size = Py_None; Py_INCREF(Py_None); + p->_array_interface = Py_None; Py_INCREF(Py_None); + p->view.obj = NULL; + if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryview___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->obj); + Py_CLEAR(p->_size); + Py_CLEAR(p->_array_interface); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + if (p->obj) { + e = (*v)(p->obj, a); if (e) return e; + } + if (p->_size) { + e = (*v)(p->_size, a); if (e) return e; + } + if (p->_array_interface) { + e = (*v)(p->_array_interface, a); if (e) return e; + } + if (p->view.obj) { + e = (*v)(p->view.obj, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_memoryview(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + tmp = ((PyObject*)p->obj); + p->obj = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_size); + p->_size = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_array_interface); + p->_array_interface = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + Py_CLEAR(p->view.obj); + return 0; +} +static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_memoryview___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_transpose(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview__get__base(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_shape(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_strides(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_suboffsets(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_ndim(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_itemsize(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_nbytes(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_size(o); +} + +static PyMethodDef __pyx_methods_memoryview[] = { + {"is_c_contig", (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, 0}, + {"is_f_contig", (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, 0}, + {"copy", (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, 0}, + {"copy_fortran", (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_memoryview[] = { + {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, + {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, + {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, + {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, + {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, + {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, + {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, + {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_memoryview = { + __pyx_memoryview___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_memoryview, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_memoryview = { + __pyx_memoryview___len__, /*mp_length*/ + __pyx_memoryview___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_memoryview = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + __pyx_memoryview_getbuffer, /*bf_getbuffer*/ + 0, /*bf_releasebuffer*/ +}; + +static PyTypeObject __pyx_type___pyx_memoryview = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.ensemble._gradient_boosting.memoryview", /*tp_name*/ + sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_memoryview___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_memoryview___str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_memoryview, /*tp_traverse*/ + __pyx_tp_clear_memoryview, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_memoryview, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_memoryview, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_memoryview, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; + +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryviewslice_obj *p; + PyObject *o = __pyx_tp_new_memoryview(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryviewslice_obj *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; + p->from_object = Py_None; Py_INCREF(Py_None); + p->from_slice.memview = NULL; + return o; +} + +static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryviewslice___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->from_object); + PyObject_GC_Track(o); + __pyx_tp_dealloc_memoryview(o); +} + +static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; + if (p->from_object) { + e = (*v)(p->from_object, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear__memoryviewslice(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + __pyx_tp_clear_memoryview(o); + tmp = ((PyObject*)p->from_object); + p->from_object = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + __PYX_XDEC_MEMVIEW(&p->from_slice, 1); + return 0; +} + +static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryviewslice__get__base(o); +} + +static PyMethodDef __pyx_methods__memoryviewslice[] = { + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { + {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_memoryviewslice = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.ensemble._gradient_boosting._memoryviewslice", /*tp_name*/ + sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___repr__, /*tp_repr*/ + #else + 0, /*tp_repr*/ + #endif + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___str__, /*tp_str*/ + #else + 0, /*tp_str*/ + #endif + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + "Internal class for passing memoryview slices to Python", /*tp_doc*/ + __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ + __pyx_tp_clear__memoryviewslice, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods__memoryviewslice, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets__memoryviewslice, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new__memoryviewslice, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {"_partial_dependence_tree", (PyCFunction)__pyx_pw_7sklearn_8ensemble_18_gradient_boosting_5_partial_dependence_tree, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_8ensemble_18_gradient_boosting_4_partial_dependence_tree}, + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + "_gradient_boosting", + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, + {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, + {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, + {&__pyx_n_s_DTYPE, __pyx_k_DTYPE, sizeof(__pyx_k_DTYPE), 0, 0, 1, 1}, + {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, + {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, + {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, + {&__pyx_n_s_K, __pyx_k_K, sizeof(__pyx_k_K), 0, 0, 1, 1}, + {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, + {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, + {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, + {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_kp_s_Total_weight_should_be_1_0_but_w, __pyx_k_Total_weight_should_be_1_0_but_w, sizeof(__pyx_k_Total_weight_should_be_1_0_but_w), 0, 0, 1, 0}, + {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, + {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, + {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, + {&__pyx_n_s_bool, __pyx_k_bool, sizeof(__pyx_k_bool), 0, 0, 1, 1}, + {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, + {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, + {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, + {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, + {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, + {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, + {&__pyx_n_s_estimators, __pyx_k_estimators, sizeof(__pyx_k_estimators), 0, 0, 1, 1}, + {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, + {&__pyx_n_s_float32, __pyx_k_float32, sizeof(__pyx_k_float32), 0, 0, 1, 1}, + {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 0, 0, 1, 1}, + {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, + {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, + {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, + {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, + {&__pyx_kp_s_home_gilles_src_scikit_learn_sk, __pyx_k_home_gilles_src_scikit_learn_sk, sizeof(__pyx_k_home_gilles_src_scikit_learn_sk), 0, 0, 1, 0}, + {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, + {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_intp, __pyx_k_intp, sizeof(__pyx_k_intp), 0, 0, 1, 1}, + {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, + {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, + {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1}, + {&__pyx_n_s_learn_rate, __pyx_k_learn_rate, sizeof(__pyx_k_learn_rate), 0, 0, 1, 1}, + {&__pyx_kp_s_left_sample_frac_f_n_samples_cur, __pyx_k_left_sample_frac_f_n_samples_cur, sizeof(__pyx_k_left_sample_frac_f_n_samples_cur), 0, 0, 1, 0}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, + {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, + {&__pyx_n_s_n_bagged, __pyx_k_n_bagged, sizeof(__pyx_k_n_bagged), 0, 0, 1, 1}, + {&__pyx_n_s_n_estimators, __pyx_k_n_estimators, sizeof(__pyx_k_n_estimators), 0, 0, 1, 1}, + {&__pyx_n_s_n_total_in_bag, __pyx_k_n_total_in_bag, sizeof(__pyx_k_n_total_in_bag), 0, 0, 1, 1}, + {&__pyx_n_s_n_total_samples, __pyx_k_n_total_samples, sizeof(__pyx_k_n_total_samples), 0, 0, 1, 1}, + {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, + {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_np_bool, __pyx_k_np_bool, sizeof(__pyx_k_np_bool), 0, 0, 1, 1}, + {&__pyx_n_s_np_float32, __pyx_k_np_float32, sizeof(__pyx_k_np_float32), 0, 0, 1, 1}, + {&__pyx_n_s_np_float64, __pyx_k_np_float64, sizeof(__pyx_k_np_float64), 0, 0, 1, 1}, + {&__pyx_n_s_np_ones, __pyx_k_np_ones, sizeof(__pyx_k_np_ones), 0, 0, 1, 1}, + {&__pyx_n_s_np_zeros, __pyx_k_np_zeros, sizeof(__pyx_k_np_zeros), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, + {&__pyx_n_s_ones, __pyx_k_ones, sizeof(__pyx_k_ones), 0, 0, 1, 1}, + {&__pyx_n_s_out, __pyx_k_out, sizeof(__pyx_k_out), 0, 0, 1, 1}, + {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, + {&__pyx_n_s_predict_stage, __pyx_k_predict_stage, sizeof(__pyx_k_predict_stage), 0, 0, 1, 1}, + {&__pyx_n_s_predict_stages, __pyx_k_predict_stages, sizeof(__pyx_k_predict_stages), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_n_s_rand, __pyx_k_rand, sizeof(__pyx_k_rand), 0, 0, 1, 1}, + {&__pyx_n_s_random_sample_mask, __pyx_k_random_sample_mask, sizeof(__pyx_k_random_sample_mask), 0, 0, 1, 1}, + {&__pyx_n_s_random_state, __pyx_k_random_state, sizeof(__pyx_k_random_state), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_sample_mask, __pyx_k_sample_mask, sizeof(__pyx_k_sample_mask), 0, 0, 1, 1}, + {&__pyx_n_s_scale, __pyx_k_scale, sizeof(__pyx_k_scale), 0, 0, 1, 1}, + {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, + {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_ensemble__gradient_boost, __pyx_k_sklearn_ensemble__gradient_boost, sizeof(__pyx_k_sklearn_ensemble__gradient_boost), 0, 0, 1, 1}, + {&__pyx_n_s_stage, __pyx_k_stage, sizeof(__pyx_k_stage), 0, 0, 1, 1}, + {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, + {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, + {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, + {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, + {&__pyx_n_s_target_feature, __pyx_k_target_feature, sizeof(__pyx_k_target_feature), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_tree, __pyx_k_tree, sizeof(__pyx_k_tree), 0, 0, 1, 1}, + {&__pyx_n_s_tree_2, __pyx_k_tree_2, sizeof(__pyx_k_tree_2), 0, 0, 1, 1}, + {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, + {&__pyx_kp_s_unable_to_allocate_shape_and_str, __pyx_k_unable_to_allocate_shape_and_str, sizeof(__pyx_k_unable_to_allocate_shape_and_str), 0, 0, 1, 0}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, + {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 788; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":806 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + + /* "View.MemoryView":127 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if itemsize <= 0: + */ + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + + /* "View.MemoryView":130 + * + * if itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * if isinstance(format, unicode): + */ + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + + /* "View.MemoryView":142 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + + /* "View.MemoryView":170 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + + /* "View.MemoryView":186 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__11); + __Pyx_GIVEREF(__pyx_tuple__11); + + /* "View.MemoryView":445 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + + /* "View.MemoryView":521 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) + */ + __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__13); + __Pyx_GIVEREF(__pyx_tuple__13); + + /* "View.MemoryView":529 + * def __get__(self): + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) + */ + __pyx_tuple__14 = PyTuple_New(1); if (unlikely(!__pyx_tuple__14)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_INCREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_tuple__14, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_tuple__14); + + /* "View.MemoryView":638 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_slice__15 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__15)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice__15); + __Pyx_GIVEREF(__pyx_slice__15); + + /* "View.MemoryView":641 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_slice__16 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__16)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice__16); + __Pyx_GIVEREF(__pyx_slice__16); + + /* "View.MemoryView":652 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_slice__17 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__17)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice__17); + __Pyx_GIVEREF(__pyx_slice__17); + + /* "View.MemoryView":659 + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__18)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__18); + __Pyx_GIVEREF(__pyx_tuple__18); + + /* "sklearn/ensemble/_gradient_boosting.pyx":99 + * + * @cython.nonecheck(False) + * def predict_stages(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X, double scale, + * np.ndarray[float64, ndim=2] out): + */ + __pyx_tuple__19 = PyTuple_Pack(9, __pyx_n_s_estimators, __pyx_n_s_X, __pyx_n_s_scale, __pyx_n_s_out, __pyx_n_s_i, __pyx_n_s_k, __pyx_n_s_n_estimators, __pyx_n_s_K, __pyx_n_s_tree_2); if (unlikely(!__pyx_tuple__19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__19); + __Pyx_GIVEREF(__pyx_tuple__19); + __pyx_codeobj__20 = (PyObject*)__Pyx_PyCode_New(4, 0, 9, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__19, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_gilles_src_scikit_learn_sk, __pyx_n_s_predict_stages, 99, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/ensemble/_gradient_boosting.pyx":129 + * + * @cython.nonecheck(False) + * def predict_stage(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< + * int stage, + * np.ndarray[DTYPE_t, ndim=2] X, double scale, + */ + __pyx_tuple__21 = PyTuple_Pack(5, __pyx_n_s_estimators, __pyx_n_s_stage, __pyx_n_s_X, __pyx_n_s_scale, __pyx_n_s_out); if (unlikely(!__pyx_tuple__21)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__21); + __Pyx_GIVEREF(__pyx_tuple__21); + __pyx_codeobj__22 = (PyObject*)__Pyx_PyCode_New(5, 0, 5, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__21, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_gilles_src_scikit_learn_sk, __pyx_n_s_predict_stage, 129, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__22)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/ensemble/_gradient_boosting.pyx":266 + * + * + * def _random_sample_mask(np.npy_intp n_total_samples, # <<<<<<<<<<<<<< + * np.npy_intp n_total_in_bag, random_state): + * """Create a random sample mask where ``n_total_in_bag`` elements are set. + */ + __pyx_tuple__23 = PyTuple_Pack(7, __pyx_n_s_n_total_samples, __pyx_n_s_n_total_in_bag, __pyx_n_s_random_state, __pyx_n_s_rand, __pyx_n_s_sample_mask, __pyx_n_s_n_bagged, __pyx_n_s_i); if (unlikely(!__pyx_tuple__23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__23); + __Pyx_GIVEREF(__pyx_tuple__23); + __pyx_codeobj__24 = (PyObject*)__Pyx_PyCode_New(3, 0, 7, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__23, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_gilles_src_scikit_learn_sk, __pyx_n_s_random_sample_mask, 266, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":276 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_tuple__25 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__25)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__25); + __Pyx_GIVEREF(__pyx_tuple__25); + + /* "View.MemoryView":277 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_tuple__26 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__26)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__26); + __Pyx_GIVEREF(__pyx_tuple__26); + + /* "View.MemoryView":278 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__27 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__27)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__27); + __Pyx_GIVEREF(__pyx_tuple__27); + + /* "View.MemoryView":281 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_tuple__28 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__28)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__28); + __Pyx_GIVEREF(__pyx_tuple__28); + + /* "View.MemoryView":282 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__29 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__29)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__29); + __Pyx_GIVEREF(__pyx_tuple__29); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC init_gradient_boosting(void); /*proto*/ +PyMODINIT_FUNC init_gradient_boosting(void) +#else +PyMODINIT_FUNC PyInit__gradient_boosting(void); /*proto*/ +PyMODINIT_FUNC PyInit__gradient_boosting(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__gradient_boosting(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4("_gradient_boosting", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__ensemble___gradient_boosting) { + if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.ensemble._gradient_boosting")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.ensemble._gradient_boosting", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + generic = Py_None; Py_INCREF(Py_None); + strided = Py_None; Py_INCREF(Py_None); + indirect = Py_None; Py_INCREF(Py_None); + contiguous = Py_None; Py_INCREF(Py_None); + indirect_contiguous = Py_None; Py_INCREF(Py_None); + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_array.tp_print = 0; + __pyx_array_type = &__pyx_type___pyx_array; + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_MemviewEnum.tp_print = 0; + __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; + __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; + __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; + __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; + __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; + __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; + __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; + __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; + __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; + if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_memoryview.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryview_type = &__pyx_type___pyx_memoryview; + __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; + __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; + __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; + __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; + __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 921; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_memoryviewslice.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 921; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 864; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_Criterion = __Pyx_ImportType("sklearn.tree._tree", "Criterion", sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion), 1); if (unlikely(!__pyx_ptype_7sklearn_4tree_5_tree_Criterion)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_4tree_5_tree_Criterion = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__Pyx_GetVtable(__pyx_ptype_7sklearn_4tree_5_tree_Criterion->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_4tree_5_tree_Criterion)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_Splitter = __Pyx_ImportType("sklearn.tree._tree", "Splitter", sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter), 1); if (unlikely(!__pyx_ptype_7sklearn_4tree_5_tree_Splitter)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_4tree_5_tree_Splitter = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter*)__Pyx_GetVtable(__pyx_ptype_7sklearn_4tree_5_tree_Splitter->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_4tree_5_tree_Splitter)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_Tree = __Pyx_ImportType("sklearn.tree._tree", "Tree", sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Tree), 1); if (unlikely(!__pyx_ptype_7sklearn_4tree_5_tree_Tree)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_4tree_5_tree_Tree = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree*)__Pyx_GetVtable(__pyx_ptype_7sklearn_4tree_5_tree_Tree->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_4tree_5_tree_Tree)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_TreeBuilder = __Pyx_ImportType("sklearn.tree._tree", "TreeBuilder", sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder), 1); if (unlikely(!__pyx_ptype_7sklearn_4tree_5_tree_TreeBuilder)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_4tree_5_tree_TreeBuilder = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder*)__Pyx_GetVtable(__pyx_ptype_7sklearn_4tree_5_tree_TreeBuilder->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_4tree_5_tree_TreeBuilder)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/ensemble/_gradient_boosting.pyx":11 + * cimport cython + * + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * np.import_array() + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":13 + * import numpy as np + * cimport numpy as np + * np.import_array() # <<<<<<<<<<<<<< + * + * from sklearn.tree._tree cimport Tree, Node + */ + import_array(); + + /* "sklearn/ensemble/_gradient_boosting.pyx":22 + * + * # no namespace lookup for numpy dtype and array creation + * from numpy import zeros as np_zeros # <<<<<<<<<<<<<< + * from numpy import ones as np_ones + * from numpy import bool as np_bool + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s_zeros); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_zeros); + __Pyx_GIVEREF(__pyx_n_s_zeros); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_numpy, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np_zeros, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":23 + * # no namespace lookup for numpy dtype and array creation + * from numpy import zeros as np_zeros + * from numpy import ones as np_ones # <<<<<<<<<<<<<< + * from numpy import bool as np_bool + * from numpy import float32 as np_float32 + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_ones); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_ones); + __Pyx_GIVEREF(__pyx_n_s_ones); + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, __pyx_t_2, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_ones); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np_ones, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":24 + * from numpy import zeros as np_zeros + * from numpy import ones as np_ones + * from numpy import bool as np_bool # <<<<<<<<<<<<<< + * from numpy import float32 as np_float32 + * from numpy import float64 as np_float64 + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s_bool); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_bool); + __Pyx_GIVEREF(__pyx_n_s_bool); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_numpy, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_bool); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np_bool, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":25 + * from numpy import ones as np_ones + * from numpy import bool as np_bool + * from numpy import float32 as np_float32 # <<<<<<<<<<<<<< + * from numpy import float64 as np_float64 + * + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_float32); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_float32); + __Pyx_GIVEREF(__pyx_n_s_float32); + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, __pyx_t_2, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_float32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np_float32, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":26 + * from numpy import bool as np_bool + * from numpy import float32 as np_float32 + * from numpy import float64 as np_float64 # <<<<<<<<<<<<<< + * + * # Define a datatype for the data array + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s_float64); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_float64); + __Pyx_GIVEREF(__pyx_n_s_float64); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_numpy, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np_float64, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":29 + * + * # Define a datatype for the data array + * DTYPE = np.float32 # <<<<<<<<<<<<<< + * ctypedef np.float32_t DTYPE_t + * ctypedef np.npy_intp SIZE_t + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float32); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":35 + * + * # constant to mark tree leafs + * cdef int LEAF = -1 # <<<<<<<<<<<<<< + * + * cdef void _predict_regression_tree_inplace_fast(DTYPE_t *X, + */ + __pyx_v_7sklearn_8ensemble_18_gradient_boosting_LEAF = -1; + + /* "sklearn/ensemble/_gradient_boosting.pyx":99 + * + * @cython.nonecheck(False) + * def predict_stages(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X, double scale, + * np.ndarray[float64, ndim=2] out): + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_8ensemble_18_gradient_boosting_1predict_stages, NULL, __pyx_n_s_sklearn_ensemble__gradient_boost); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_predict_stages, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":129 + * + * @cython.nonecheck(False) + * def predict_stage(np.ndarray[object, ndim=2] estimators, # <<<<<<<<<<<<<< + * int stage, + * np.ndarray[DTYPE_t, ndim=2] X, double scale, + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_8ensemble_18_gradient_boosting_3predict_stage, NULL, __pyx_n_s_sklearn_ensemble__gradient_boost); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_predict_stage, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":266 + * + * + * def _random_sample_mask(np.npy_intp n_total_samples, # <<<<<<<<<<<<<< + * np.npy_intp n_total_in_bag, random_state): + * """Create a random sample mask where ``n_total_in_bag`` elements are set. + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_8ensemble_18_gradient_boosting_7_random_sample_mask, NULL, __pyx_n_s_sklearn_ensemble__gradient_boost); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_random_sample_mask, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/ensemble/_gradient_boosting.pyx":1 + * # cython: cdivision=True # <<<<<<<<<<<<<< + * # cython: boundscheck=False + * # cython: wraparound=False + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":203 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * def __dealloc__(array self): + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_array_type); + + /* "View.MemoryView":276 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__25, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(generic); + __Pyx_DECREF_SET(generic, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":277 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__26, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(strided); + __Pyx_DECREF_SET(strided, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":278 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__27, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(indirect); + __Pyx_DECREF_SET(indirect, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":281 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__28, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(contiguous); + __Pyx_DECREF_SET(contiguous, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":282 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__29, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(indirect_contiguous); + __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":496 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_memoryview_type); + + /* "View.MemoryView":952 + * return self.from_object + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 952; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 952; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_memoryviewslice_type); + + /* "View.MemoryView":1362 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + if (__pyx_d) { + __Pyx_AddTraceback("init sklearn.ensemble._gradient_boosting", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.ensemble._gradient_boosting"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* --- Runtime support code --- */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(PyObject_TypeCheck(obj, type))) return 1; + } + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type) { - stack[0].field = &ctx->root; - stack[0].parent_offset = 0; - ctx->root.type = type; - ctx->root.name = "buffer dtype"; - ctx->root.offset = 0; - ctx->head = stack; - ctx->head->field = &ctx->root; - ctx->fmt_offset = 0; - ctx->head->parent_offset = 0; - ctx->new_packmode = '@'; - ctx->enc_packmode = '@'; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->is_complex = 0; - ctx->is_valid_array = 0; - ctx->struct_alignment = 0; - while (type->typegroup == 'S') { - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = 0; - type = type->fields->type; - } +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case '\r': + case '\n': + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; + } + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (likely(result)) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { +#if CYTHON_COMPILING_IN_CPYTHON + PyMappingMethods* mp; +#if PY_MAJOR_VERSION < 3 + PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; + if (likely(ms && ms->sq_slice)) { + if (!has_cstart) { + if (_py_start && (*_py_start != Py_None)) { + cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); + if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstart = 0; + } + if (!has_cstop) { + if (_py_stop && (*_py_stop != Py_None)) { + cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); + if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstop = PY_SSIZE_T_MAX; + } + if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { + Py_ssize_t l = ms->sq_length(obj); + if (likely(l >= 0)) { + if (cstop < 0) { + cstop += l; + if (cstop < 0) cstop = 0; + } + if (cstart < 0) { + cstart += l; + if (cstart < 0) cstart = 0; + } + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + goto bad; + } + } + return ms->sq_slice(obj, cstart, cstop); + } +#endif + mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_subscript)) +#endif + { + PyObject* result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyInt_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyInt_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_COMPILING_IN_CPYTHON + result = mp->mp_subscript(obj, py_slice); +#else + result = PyObject_GetItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } + PyErr_Format(PyExc_TypeError, + "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); +bad: + return NULL; +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; } -static int __Pyx_BufFmt_ParseNumber(const char** ts) { - int count; - const char* t = *ts; - if (*t < '0' || *t > '9') { - return -1; +#endif + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + if (PyType_Check(type)) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); } else { - count = *t++ - '0'; - while (*t >= '0' && *t < '9') { - count *= 10; - count += *t++ - '0'; + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; } } - *ts = t; - return count; + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; } -static int __Pyx_BufFmt_ExpectNumber(const char **ts) { - int number = __Pyx_BufFmt_ParseNumber(ts); - if (number == -1) /* First char was not a digit */ - PyErr_Format(PyExc_ValueError,\ - "Does not understand character buffer dtype format string ('%c')", **ts); - return number; +#else +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if CYTHON_COMPILING_IN_PYPY + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(tmp_type, tmp_value, tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#else + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#endif + } +bad: + Py_XDECREF(owned_instance); + return; } -static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { - PyErr_Format(PyExc_ValueError, - "Unexpected format string character: '%c'", ch); +#endif + +static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (!buf) { + PyErr_SetString(PyExc_ValueError, + "buf is NULL."); + goto fail; + } else if (memviewslice->memview || memviewslice->data) { + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); + } + retval = 0; + goto no_fail; +fail: + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; } -static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { - switch (ch) { - case 'b': return "'char'"; - case 'B': return "'unsigned char'"; - case 'h': return "'short'"; - case 'H': return "'unsigned short'"; - case 'i': return "'int'"; - case 'I': return "'unsigned int'"; - case 'l': return "'long'"; - case 'L': return "'unsigned long'"; - case 'q': return "'long long'"; - case 'Q': return "'unsigned long long'"; - case 'f': return (is_complex ? "'complex float'" : "'float'"); - case 'd': return (is_complex ? "'complex double'" : "'double'"); - case 'g': return (is_complex ? "'complex long double'" : "'long double'"); - case 'T': return "a struct"; - case 'O': return "Python object"; - case 'P': return "a pointer"; - case 's': case 'p': return "a string"; - case 0: return "end"; - default: return "unparseable format string"; - } +static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { + va_list vargs; + char msg[200]; + va_start(vargs, fmt); +#ifdef HAVE_STDARG_PROTOTYPES + va_start(vargs, fmt); +#else + va_start(vargs); +#endif + vsnprintf(msg, 200, fmt, vargs); + Py_FatalError(msg); + va_end(vargs); +} +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) +{ + int first_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview || (PyObject *) memview == Py_None) + return; + if (__pyx_get_slice_count(memview) < 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + first_time = __pyx_add_acquisition_count(memview) == 0; + if (first_time) { + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); + } + } +} +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, + int have_gil, int lineno) { + int last_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview ) { + return; + } else if ((PyObject *) memview == Py_None) { + memslice->memview = NULL; + return; + } + if (__pyx_get_slice_count(memview) <= 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; + if (last_time) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } + } else { + memslice->memview = NULL; + } +} + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = PyCFunction_GET_FUNCTION(func); + self = PyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *result; + PyObject *args = PyTuple_New(1); + if (unlikely(!args)) return NULL; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, arg); + result = __Pyx_PyObject_Call(func, args, NULL); + Py_DECREF(args); + return result; +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { +#ifdef __Pyx_CyFunction_USED + if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { +#else + if (likely(PyCFunction_Check(func))) { +#endif + if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { + return __Pyx_PyObject_CallMethO(func, arg); + } + } + return __Pyx__PyObject_CallOneArg(func, arg); +} +#else +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject* args = PyTuple_Pack(1, arg); + return (likely(args)) ? __Pyx_PyObject_Call(func, args, NULL) : NULL; +} +#endif + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif } -static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return 2; - case 'i': case 'I': case 'l': case 'L': return 4; - case 'q': case 'Q': return 8; - case 'f': return (is_complex ? 8 : 4); - case 'd': return (is_complex ? 16 : 8); - case 'g': { - PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); - return 0; + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; } - case 'O': case 'P': return sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); } -} -static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { - switch (ch) { - case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(short); - case 'i': case 'I': return sizeof(int); - case 'l': case 'L': return sizeof(long); - #ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(PY_LONG_LONG); - #endif - case 'f': return sizeof(float) * (is_complex ? 2 : 1); - case 'd': return sizeof(double) * (is_complex ? 2 : 1); - case 'g': return sizeof(long double) * (is_complex ? 2 : 1); - case 'O': case 'P': return sizeof(void*); - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; } - } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif } -typedef struct { char c; short x; } __Pyx_st_short; -typedef struct { char c; int x; } __Pyx_st_int; -typedef struct { char c; long x; } __Pyx_st_long; -typedef struct { char c; float x; } __Pyx_st_float; -typedef struct { char c; double x; } __Pyx_st_double; -typedef struct { char c; long double x; } __Pyx_st_longdouble; -typedef struct { char c; void *x; } __Pyx_st_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +#if CYTHON_COMPILING_IN_CPYTHON +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) +#else + if (likely(PyString_Check(n))) #endif -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); + return __Pyx_PyObject_GetAttrStr(o, n); #endif - case 'f': return sizeof(__Pyx_st_float) - sizeof(float); - case 'd': return sizeof(__Pyx_st_double) - sizeof(double); - case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; + return PyObject_GetAttr(o, n); +} + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + length = strlen(cstring); + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); } } -/* These are for computing the padding at the end of the struct to align - on the first member of the struct. This will probably the same as above, - but we don't have any guarantees. - */ -typedef struct { short x; char c; } __Pyx_pad_short; -typedef struct { int x; char c; } __Pyx_pad_int; -typedef struct { long x; char c; } __Pyx_pad_long; -typedef struct { float x; char c; } __Pyx_pad_float; -typedef struct { double x; char c; } __Pyx_pad_double; -typedef struct { long double x; char c; } __Pyx_pad_longdouble; -typedef struct { void *x; char c; } __Pyx_pad_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +#else + PyErr_GetExcInfo(type, value, tb); #endif -static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(type, value, tb); #endif - case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); - case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); - case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; +} + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; } + #endif + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; } -static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { - switch (ch) { - case 'c': case 'b': case 'h': case 'i': - case 'l': case 'q': case 's': case 'p': - return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': - return 'U'; - case 'f': case 'd': case 'g': - return (is_complex ? 'C' : 'R'); - case 'O': - return 'O'; - case 'P': - return 'P'; - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; +#else + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); +#endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; } - } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif } -static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { - if (ctx->head == NULL || ctx->head->field == &ctx->root) { - const char* expected; - const char* quote; - if (ctx->head == NULL) { - expected = "end"; - quote = ""; - } else { - expected = ctx->head->field->type->name; - quote = "'"; +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; } - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected %s%s%s but got %s", - quote, expected, quote, - __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); - } else { - __Pyx_StructField* field = ctx->head->field; - __Pyx_StructField* parent = (ctx->head - 1)->field; - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", - field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), - parent->type->name, field->name); - } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif } -static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { - char group; - size_t size, offset, arraysize = 1; - if (ctx->enc_type == 0) return 0; - if (ctx->head->field->type->arraysize[0]) { - int i, ndim = 0; - if (ctx->enc_type == 's' || ctx->enc_type == 'p') { - ctx->is_valid_array = ctx->head->field->type->ndim == 1; - ndim = 1; - if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { - PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %zu", - ctx->head->field->type->arraysize[0], ctx->enc_count); - return -1; +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; } } - if (!ctx->is_valid_array) { - PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", - ctx->head->field->type->ndim, ndim); - return -1; - } - for (i = 0; i < ctx->head->field->type->ndim; i++) { - arraysize *= ctx->head->field->type->arraysize[i]; - } - ctx->is_valid_array = 0; - ctx->enc_count = 1; - } - group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); - do { - __Pyx_StructField* field = ctx->head->field; - __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { - size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } } else { - size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } } - if (ctx->enc_packmode == '@') { - size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); - size_t align_mod_offset; - if (align_at == 0) return -1; - align_mod_offset = ctx->fmt_offset % align_at; - if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; - if (ctx->struct_alignment == 0) - ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, - ctx->is_complex); +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, + int full_traceback) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + if (full_traceback) { + Py_XINCREF(old_exc); + Py_XINCREF(old_val); + Py_XINCREF(old_tb); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + PyErr_PrintEx(1); } - if (type->size != size || type->typegroup != group) { - if (type->typegroup == 'C' && type->fields != NULL) { - size_t parent_offset = ctx->head->parent_offset + field->offset; - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = parent_offset; - continue; - } - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); } - offset = ctx->head->parent_offset + field->offset; - if (ctx->fmt_offset != offset) { - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", - (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); - return -1; +} + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +static void* __Pyx_GetVtable(PyObject *dict) { + void* ptr; + PyObject *ob = PyObject_GetItem(dict, __pyx_n_s_pyx_vtable); + if (!ob) + goto bad; +#if PY_VERSION_HEX >= 0x02070000 + ptr = PyCapsule_GetPointer(ob, 0); +#else + ptr = PyCObject_AsVoidPtr(ob); +#endif + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif } - ctx->fmt_offset += size; - if (arraysize) - ctx->fmt_offset += (arraysize - 1) * size; - --ctx->enc_count; /* Consume from buffer string */ - while (1) { - if (field == &ctx->root) { - ctx->head = NULL; - if (ctx->enc_count != 0) { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + return value; +} + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; } - break; /* breaks both loops as ctx->enc_count == 0 */ - } - ctx->head->field = ++field; - if (field->type == NULL) { - --ctx->head; - field = ctx->head->field; - continue; - } else if (field->type->typegroup == 'S') { - size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; /* empty struct */ - field = field->type->fields; - ++ctx->head; - ctx->head->field = field; - ctx->head->parent_offset = parent_offset; - break; - } else { - break; - } } - } while (ctx->enc_count); - ctx->enc_type = 0; - ctx->is_complex = 0; - return 0; + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } } -static CYTHON_INLINE PyObject * -__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) -{ - const char *ts = *tsp; - int i = 0, number; - int ndim = ctx->head->field->type->ndim; -; - ++ts; - if (ctx->new_count != 1) { - PyErr_SetString(PyExc_ValueError, - "Cannot handle repeated arrays in format string"); +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - while (*ts && *ts != ')') { - if (isspace(*ts)) - continue; - number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) - return PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %d", - ctx->head->field->type->arraysize[i], number); - if (*ts != ',' && *ts != ')') - return PyErr_Format(PyExc_ValueError, - "Expected a comma in format string, got '%c'", *ts); - if (*ts == ',') ts++; - i++; - } - if (i != ndim) - return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", - ctx->head->field->type->ndim, i); - if (!*ts) { - PyErr_SetString(PyExc_ValueError, - "Unexpected end of format string, expected ')'"); + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } - ctx->is_valid_array = 1; - ctx->new_count = 1; - *tsp = ++ts; - return Py_None; + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; } -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { - int got_Z = 0; - while (1) { - switch(*ts) { - case 0: - if (ctx->enc_type != 0 && ctx->head == NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - if (ctx->head != NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - return ts; - case ' ': - case 10: - case 13: - ++ts; - break; - case '<': - if (!__Pyx_IsLittleEndian()) { - PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '>': - case '!': - if (__Pyx_IsLittleEndian()) { - PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '=': - case '@': - case '^': - ctx->new_packmode = *ts++; - break; - case 'T': /* substruct */ - { - const char* ts_after_sub; - size_t i, struct_count = ctx->new_count; - size_t struct_alignment = ctx->struct_alignment; - ctx->new_count = 1; - ++ts; - if (*ts != '{') { - PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; /* Erase processed last struct element */ - ctx->enc_count = 0; - ctx->struct_alignment = 0; - ++ts; - ts_after_sub = ts; - for (i = 0; i != struct_count; ++i) { - ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); - if (!ts_after_sub) return NULL; - } - ts = ts_after_sub; - if (struct_alignment) ctx->struct_alignment = struct_alignment; - } - break; - case '}': /* end of substruct; either repeat or move on */ - { - size_t alignment = ctx->struct_alignment; - ++ts; - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; /* Erase processed last struct element */ - if (alignment && ctx->fmt_offset % alignment) { - ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); - } - } - return ts; - case 'x': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->fmt_offset += ctx->new_count; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->enc_packmode = ctx->new_packmode; - ++ts; - break; - case 'Z': - got_Z = 1; - ++ts; - if (*ts != 'f' && *ts != 'd' && *ts != 'g') { - __Pyx_BufFmt_RaiseUnexpectedChar('Z'); - return NULL; - } /* fall through */ - case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': - case 'l': case 'L': case 'q': case 'Q': - case 'f': case 'd': case 'g': - case 'O': case 's': case 'p': - if (ctx->enc_type == *ts && got_Z == ctx->is_complex && - ctx->enc_packmode == ctx->new_packmode) { - ctx->enc_count += ctx->new_count; - } else { - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); } - ++ts; - ctx->new_count = 1; - got_Z = 0; - break; - case ':': - ++ts; - while(*ts != ':') ++ts; - ++ts; - break; - case '(': - if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; - break; - default: - { - int number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - ctx->new_count = (size_t)number; + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; } - } -} -static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { - buf->buf = NULL; - buf->obj = NULL; - buf->strides = __Pyx_zeros; - buf->shape = __Pyx_zeros; - buf->suboffsets = __Pyx_minusones; -} -static CYTHON_INLINE int __Pyx_GetBufferAndValidate( - Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, - int nd, int cast, __Pyx_BufFmt_StackElem* stack) -{ - if (obj == Py_None || obj == NULL) { - __Pyx_ZeroBuffer(buf); - return 0; - } - buf->buf = NULL; - if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; - if (buf->ndim != nd) { - PyErr_Format(PyExc_ValueError, - "Buffer has wrong number of dimensions (expected %d, got %d)", - nd, buf->ndim); - goto fail; - } - if (!cast) { - __Pyx_BufFmt_Context ctx; - __Pyx_BufFmt_Init(&ctx, stack, dtype); - if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; - } - if ((unsigned)buf->itemsize != dtype->size) { - PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", - buf->itemsize, (buf->itemsize > 1) ? "s" : "", - dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); - goto fail; - } - if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; - return 0; -fail:; - __Pyx_ZeroBuffer(buf); - return -1; -} -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { - if (info->buf == NULL) return; - if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; - __Pyx_ReleaseBuffer(info); + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); } -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); } -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_Restore(type, value, tb); -#endif +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + Py_DECREF(obj); + view->obj = NULL; } -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(type, value, tb); #endif + + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; } -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ + { \ + func_type value = func_value; \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + if (is_unsigned && unlikely(value < zero)) \ + goto raise_neg_overflow; \ + else \ + goto raise_overflow; \ + } \ + } \ + return (target_type) value; \ } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - if (value == NULL) { - value = Py_None; - Py_INCREF(value); - } - #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) - #else - if (!PyType_Check(type)) - #endif - { - if (value != Py_None) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; } - Py_DECREF(value); - value = type; - #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, ((PyLongObject*)x)->ob_digit[0]); } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; } - #else - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong(x)) } - #endif + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong(x)) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; } - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; } -#else /* Python 3+ */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; + +static int +__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) +{ + int i; + if (!a || !b) + return 0; + if (a == b) + return 1; + if (a->size != b->size || a->typegroup != b->typegroup || + a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { + if (a->typegroup == 'H' || b->typegroup == 'H') { + return a->size == b->size; + } else { + return 0; + } } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; + if (a->ndim) { + for (i = 0; i < a->ndim; i++) + if (a->arraysize[i] != b->arraysize[i]) + return 0; + } + if (a->typegroup == 'S') { + if (a->flags != b->flags) + return 0; + if (a->fields || b->fields) { + if (!(a->fields && b->fields)) + return 0; + for (i = 0; a->fields[i].type && b->fields[i].type; i++) { + __Pyx_StructField *field_a = a->fields + i; + __Pyx_StructField *field_b = b->fields + i; + if (field_a->offset != field_b->offset || + !__pyx_typeinfo_cmp(field_a->type, field_b->type)) + return 0; + } + return !a->fields[i].type && !b->fields[i].type; } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; } - if (cause) { - PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; + return 1; +} + +static int +__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) +{ + if (buf->shape[dim] <= 1) + return 1; + if (buf->strides) { + if (spec & __Pyx_MEMVIEW_CONTIG) { + if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { + if (buf->strides[dim] != sizeof(void *)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly contiguous " + "in dimension %d.", dim); + goto fail; + } + } else if (buf->strides[dim] != buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } } - else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); + if (spec & __Pyx_MEMVIEW_FOLLOW) { + Py_ssize_t stride = buf->strides[dim]; + if (stride < 0) + stride = -stride; + if (stride < buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } } - else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; + } else { + if (spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not contiguous in " + "dimension %d", dim); + goto fail; + } else if (spec & (__Pyx_MEMVIEW_PTR)) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not indirect in " + "dimension %d", dim); + goto fail; + } else if (buf->suboffsets) { + PyErr_SetString(PyExc_ValueError, + "Buffer exposes suboffsets but no strides"); + goto fail; } - if (!value) { - value = PyObject_CallObject(type, NULL); + } + return 1; +fail: + return 0; +} +static int +__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) +{ + if (spec & __Pyx_MEMVIEW_DIRECT) { + if (buf->suboffsets && buf->suboffsets[dim] >= 0) { + PyErr_Format(PyExc_ValueError, + "Buffer not compatible with direct access " + "in dimension %d.", dim); + goto fail; } - PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); + if (spec & __Pyx_MEMVIEW_PTR) { + if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly accessible " + "in dimension %d.", dim); + goto fail; } } -bad: - return; -} -#endif - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); -} - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); + return 1; +fail: + return 0; } - -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +static int +__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) +{ + int i; + if (c_or_f_flag & __Pyx_IS_F_CONTIG) { + Py_ssize_t stride = 1; + for (i = 0; i < ndim; i++) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) + { + PyErr_SetString(PyExc_ValueError, + "Buffer not fortran contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { + Py_ssize_t stride = 1; + for (i = ndim - 1; i >- 1; i--) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) { + PyErr_SetString(PyExc_ValueError, + "Buffer not C contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } + return 1; +fail: + return 0; } - -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj) +{ + struct __pyx_memoryview_obj *memview, *new_memview; + __Pyx_RefNannyDeclarations + Py_buffer *buf; + int i, spec = 0, retval = -1; + __Pyx_BufFmt_Context ctx; + int from_memoryview = __pyx_memoryview_check(original_obj); + __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); + if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) + original_obj)->typeinfo)) { + memview = (struct __pyx_memoryview_obj *) original_obj; + new_memview = NULL; } else { - __Pyx_RaiseTooManyValuesError(index); + memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + original_obj, buf_flags, 0, dtype); + new_memview = memview; + if (unlikely(!memview)) + goto fail; } -} - -#if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - PyObject *getbuffer_cobj; - - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - #endif - - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); - - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (getbuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_getbuffer"))) { - getbufferproc func; - - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (getbufferproc) PyCapsule_GetPointer(getbuffer_cobj, "getbuffer(obj, view, flags)"); - #else - func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); - #endif - Py_DECREF(getbuffer_cobj); - if (!func) + buf = &memview->view; + if (buf->ndim != ndim) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + ndim, buf->ndim); + goto fail; + } + if (new_memview) { + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned) buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " + "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", + buf->itemsize, + (buf->itemsize > 1) ? "s" : "", + dtype->name, + dtype->size, + (dtype->size > 1) ? "s" : ""); + goto fail; + } + for (i = 0; i < ndim; i++) { + spec = axes_specs[i]; + if (!__pyx_check_strides(buf, i, ndim, spec)) + goto fail; + if (!__pyx_check_suboffsets(buf, i, ndim, spec)) goto fail; - - return func(obj, view, flags); - } else { - PyErr_Clear(); } - #endif - - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - -#if PY_VERSION_HEX < 0x02060000 + if (buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, + new_memview != NULL) == -1)) { + goto fail; + } + retval = 0; + goto no_fail; fail: -#endif - - return -1; + Py_XDECREF(new_memview); + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; } -static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject *obj = view->obj; - PyObject *releasebuffer_cobj; - - if (!obj) return; - - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) { - PyBuffer_Release(view); - return; +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; } - #endif - - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } - - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (releasebuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_releasebuffer"))) { - releasebufferproc func; - - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (releasebufferproc) PyCapsule_GetPointer(releasebuffer_cobj, "releasebuffer(obj, view)"); - #else - func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); - #endif + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_DTYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} - Py_DECREF(releasebuffer_cobj); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_8ensemble_18_gradient_boosting_int32, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} - if (!func) - goto fail; +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_double(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_double, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} - func(obj, view); - return; +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *x) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (Py_intptr_t) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(Py_intptr_t) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyLong_AsLong(x)) + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + Py_intptr_t val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (Py_intptr_t) -1; + } } else { - PyErr_Clear(); + Py_intptr_t val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (Py_intptr_t) -1; + val = __Pyx_PyInt_As_Py_intptr_t(tmp); + Py_DECREF(tmp); + return val; } - #endif - - goto nofail; - -#if PY_VERSION_HEX < 0x02060000 -fail: -#endif - PyErr_WriteUnraisable(obj); - -nofail: - Py_DECREF(obj); - view->obj = NULL; +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to Py_intptr_t"); + return (Py_intptr_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; } -#endif /* PY_MAJOR_VERSION < 3 */ - - static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); - if (!py_import) - goto bad; - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_int32(npy_int32 value) { + const npy_int32 neg_one = (npy_int32) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(npy_int32) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(npy_int32) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(npy_int32) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(npy_int32) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(npy_int32) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - #if PY_VERSION_HEX >= 0x02050000 { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if (strchr(__Pyx_MODULE_NAME, '.')) { - /* try package relative import first */ - PyObject *py_level = PyInt_FromLong(1); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(npy_int32), + little, !is_unsigned); + } +} + +static CYTHON_INLINE npy_int32 __Pyx_PyInt_As_npy_int32(PyObject *x) { + const npy_int32 neg_one = (npy_int32) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(npy_int32) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; } - level = 0; /* try absolute import on failure */ + return (npy_int32) val; } - #endif - if (!module) { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_int32, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(npy_int32) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(npy_int32) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_int32, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(npy_int32, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(npy_int32) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, long, PyLong_AsLong(x)) + } else if (sizeof(npy_int32) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + npy_int32 val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (npy_int32) -1; } + } else { + npy_int32 val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (npy_int32) -1; + val = __Pyx_PyInt_As_npy_int32(tmp); + Py_DECREF(tmp); + return val; } - #else - if (level>0) { - PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); - goto bad; +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to npy_int32"); + return (npy_int32) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to npy_int32"); + return (npy_int32) -1; +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(Py_intptr_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); } - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, NULL); - #endif -bad: - Py_XDECREF(empty_list); - Py_XDECREF(py_import); - Py_XDECREF(empty_dict); - return module; } #if CYTHON_CCOMPLEX @@ -5556,404 +21058,381 @@ static void __Pyx_ReleaseBuffer(Py_buffer *view) { #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); } - return (unsigned short)val; } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); } -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; +static int +__pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim) +{ + int i, index, step, start; + Py_ssize_t itemsize = mvs->memview->view.itemsize; + if (order == 'F') { + step = 1; + start = 0; + } else { + step = -1; + start = ndim - 1; } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; + for (i = 0; i < ndim; i++) { + index = start + step * i; + if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) + return 0; + itemsize *= mvs->shape[index]; } - return (short)__Pyx_PyInt_AsLong(x); + return 1; } -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; +static void +__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + start = end = slice->data; + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + if (extent == 0) { + *out_start = *out_end = start; + return; + } else { + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); } - return (int)val; } - return (int)__Pyx_PyInt_AsLong(x); + *out_start = start; + *out_end = end + itemsize; } - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; - } - return (signed char)__Pyx_PyInt_AsSignedLong(x); +static int +__pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize) +{ + void *start1, *end1, *start2, *end2; + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + return (start1 < end2) && (start2 < end1); } -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + for (i = 0; i < ndim; i++) { + if (from_mvs->suboffsets[i] >= 0) { + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; } - return (signed short)val; } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; - } - return (signed int)val; + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; + __Pyx_GOTREF(shape_tuple); + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; + } else { + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; } - return (int)val; } - return (int)__Pyx_PyInt_AsLong(x); + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + goto no_fail; +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; } -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else +static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) +{ + PyObject *cobj; +#if PY_VERSION_HEX >= 0x02070000 + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)PyLong_AsUnsignedLong(x); - } else { - return (unsigned long)PyLong_AsLong(x); - } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; - } + return cobj; } -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); } } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); } } -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { + const char neg_one = (char) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; + if (sizeof(char) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (char) val; } - return (long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(char, digit, ((PyLongObject*)x)->ob_digit[0]); } - return (long)PyLong_AsUnsignedLong(x); - } else { - return (long)PyLong_AsLong(x); - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)val; - } else + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; + goto raise_neg_overflow; + } + if (sizeof(char) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(char) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long long, PyLong_AsUnsignedLongLong(x)) } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { - return (PY_LONG_LONG)PyLong_AsLongLong(x); +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(char, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(char) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyLong_AsLong(x)) + } else if (sizeof(char) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(char, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + char val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (char) -1; } } else { - PY_LONG_LONG val; + char val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); + if (!tmp) return (char) -1; + val = __Pyx_PyInt_As_char(tmp); Py_DECREF(tmp); return val; } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to char"); + return (char) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to char"); + return (char) -1; } -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; } - return (signed long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; + goto raise_neg_overflow; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong(x)) } - return (signed long)PyLong_AsUnsignedLong(x); } else { - return (signed long)PyLong_AsLong(x); - } - } else { - signed long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; - } - return (signed PY_LONG_LONG)val; - } else +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong(x)) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); +#endif + return (long) -1; } } else { - signed PY_LONG_LONG val; + long val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; } static int __Pyx_check_binary_version(void) { @@ -5966,15 +21445,28 @@ static int __Pyx_check_binary_version(void) { "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); - #if PY_VERSION_HEX < 0x02050000 - return PyErr_Warn(NULL, message); - #else return PyErr_WarnEx(NULL, message, 1); - #endif } return 0; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -5984,6 +21476,10 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; @@ -5999,23 +21495,31 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", + "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } - if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); - #if PY_VERSION_HEX < 0x02050000 - if (PyErr_Warn(NULL, warning) < 0) goto bad; - #else if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - #endif } - else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", + "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } @@ -6027,204 +21531,6 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - py_name = __Pyx_PyIdentifier_FromString(name); - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; -} -#endif - -static void* __Pyx_GetVtable(PyObject *dict) { - void* ptr; - PyObject *ob = PyMapping_GetItemString(dict, (char *)"__pyx_vtable__"); - if (!ob) - goto bad; -#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) - ptr = PyCapsule_GetPointer(ob, 0); -#else - ptr = PyCObject_AsVoidPtr(ob); -#endif - if (!ptr && !PyErr_Occurred()) - PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); - Py_DECREF(ob); - return ptr; -bad: - Py_XDECREF(ob); - return NULL; -} - -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = (start + end) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, /*int argcount,*/ - 0, /*int kwonlyargcount,*/ - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ - 0, /*int flags,*/ - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, /*int firstlineno,*/ - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_globals = 0; - PyFrameObject *py_frame = 0; - py_code = __pyx_find_code_object(c_line ? c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? c_line : py_line, py_code); - } - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_frame = PyFrame_New( - PyThreadState_GET(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - py_globals, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = py_line; - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 @@ -6235,7 +21541,7 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } - #else /* Python 3+ has unicode identifiers */ + #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); @@ -6255,27 +21561,88 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } - -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else + if (__Pyx_PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif + } else +#endif +#if !CYTHON_COMPILING_IN_PYPY + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -6291,13 +21658,13 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", + "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; @@ -6309,40 +21676,33 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { -#if PY_VERSION_HEX < 0x02050000 - if (ival <= LONG_MAX) - return PyInt_FromLong((long)ival); - else { - unsigned char *bytes = (unsigned char *) &ival; - int one = 1; int little = (int)*(unsigned char*)&one; - return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); - } -#else - return PyInt_FromSize_t(ival); -#endif -} - -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; + return PyInt_FromSize_t(ival); } diff --git a/sklearn/ensemble/_gradient_boosting.pyx b/sklearn/ensemble/_gradient_boosting.pyx index 78ff09756ab3d..634417b978571 100644 --- a/sklearn/ensemble/_gradient_boosting.pyx +++ b/sklearn/ensemble/_gradient_boosting.pyx @@ -1,36 +1,48 @@ -# encoding: utf-8 # cython: cdivision=True # cython: boundscheck=False # cython: wraparound=False # # Author: Peter Prettenhofer # -# License: BSD Style. +# Licence: BSD 3 clause cimport cython import numpy as np cimport numpy as np +np.import_array() -from sklearn.tree._tree cimport Tree +from sklearn.tree._tree cimport Tree, Node + +ctypedef np.int32_t int32 +ctypedef np.float64_t float64 +ctypedef np.uint8_t uint8 + +# no namespace lookup for numpy dtype and array creation +from numpy import zeros as np_zeros +from numpy import ones as np_ones +from numpy import bool as np_bool +from numpy import float32 as np_float32 +from numpy import float64 as np_float64 # Define a datatype for the data array DTYPE = np.float32 ctypedef np.float32_t DTYPE_t +ctypedef np.npy_intp SIZE_t + +# constant to mark tree leafs +cdef int LEAF = -1 cdef void _predict_regression_tree_inplace_fast(DTYPE_t *X, - int *children_left, - int *children_right, - int *feature, - double *threshold, + Node* root_node, double *value, double scale, Py_ssize_t k, Py_ssize_t K, Py_ssize_t n_samples, Py_ssize_t n_features, - np.float64_t *out): + float64 *out): """Predicts output for regression tree and stores it in ``out[i, k]``. This function operates directly on the data arrays of the tree @@ -45,15 +57,8 @@ cdef void _predict_regression_tree_inplace_fast(DTYPE_t *X, X : DTYPE_t pointer The pointer to the data array of the input ``X``. Assumes that the array is c-continuous. - children : np.int32_t pointer - The pointer to the data array of the ``children`` array attribute - of the :class:``sklearn.tree.Tree``. - feature : np.int32_t pointer - The pointer to the data array of the ``feature`` array attribute - of the :class:``sklearn.tree.Tree``. - threshold : np.float64_t pointer - The pointer to the data array of the ``threshold`` array attribute - of the :class:``sklearn.tree.Tree``. + root_node : tree Node pointer + Pointer to the main node array of the :class:``sklearn.tree.Tree``. value : np.float64_t pointer The pointer to the data array of the ``value`` array attribute of the :class:``sklearn.tree.Tree``. @@ -77,25 +82,23 @@ cdef void _predict_regression_tree_inplace_fast(DTYPE_t *X, shape ``(n_samples, K)``. """ cdef Py_ssize_t i - cdef np.int32_t node_id - cdef np.int32_t feature_idx + cdef int32 node_id + cdef Node *node for i in range(n_samples): - node_id = 0 - # While node_id not a leaf - while children_left[node_id] != -1 and \ - children_right[node_id] != -1: - feature_idx = feature[node_id] - if X[(i * n_features) + feature_idx] <= threshold[node_id]: - node_id = children_left[node_id] + node = root_node + # While node not a leaf + while node.left_child != -1 and node.right_child != -1: + if X[i * n_features + node.feature] <= node.threshold: + node = root_node + node.left_child else: - node_id = children_right[node_id] - out[(i * K) + k] += scale * value[node_id] + node = root_node + node.right_child + out[i * K + k] += scale * value[node - root_node] @cython.nonecheck(False) def predict_stages(np.ndarray[object, ndim=2] estimators, np.ndarray[DTYPE_t, ndim=2, mode='c'] X, double scale, - np.ndarray[np.float64_t, ndim=2] out): + np.ndarray[float64, ndim=2] out): """Add predictions of ``estimators`` to ``out``. Each estimator is scaled by ``scale`` before its prediction @@ -104,56 +107,194 @@ def predict_stages(np.ndarray[object, ndim=2] estimators, cdef Py_ssize_t i cdef Py_ssize_t k cdef Py_ssize_t n_estimators = estimators.shape[0] - cdef Py_ssize_t n_samples = X.shape[0] - cdef Py_ssize_t n_features = X.shape[1] cdef Py_ssize_t K = estimators.shape[1] cdef Tree tree for i in range(n_estimators): for k in range(K): - tree = estimators[i, k] + tree = estimators[i, k].tree_ # avoid buffer validation by casting to ndarray # and get data pointer # need brackets because of casting operator priority _predict_regression_tree_inplace_fast( - (X.data), - tree.children_left, - tree.children_right, - tree.feature, - tree.threshold, - tree.value, - scale, k, K, n_samples, n_features, - ((out).data)) + X.data, + tree.nodes, tree.value, + scale, k, K, X.shape[0], X.shape[1], + ( out).data) + ## out += scale * tree.predict(X).reshape((X.shape[0], 1)) @cython.nonecheck(False) def predict_stage(np.ndarray[object, ndim=2] estimators, int stage, np.ndarray[DTYPE_t, ndim=2] X, double scale, - np.ndarray[np.float64_t, ndim=2] out): + np.ndarray[float64, ndim=2] out): """Add predictions of ``estimators[stage]`` to ``out``. Each estimator in the stage is scaled by ``scale`` before its prediction is added to ``out``. """ - cdef Py_ssize_t i - cdef Py_ssize_t k - cdef Py_ssize_t n_estimators = estimators.shape[0] - cdef Py_ssize_t n_samples = X.shape[0] + return predict_stages(estimators[stage:stage + 1], X, scale, out) + + +cdef inline int array_index(int32 val, int32[::1] arr): + """Find index of ``val`` in array ``arr``. """ + cdef int32 res = -1 + cdef int32 i = 0 + cdef int32 n = arr.shape[0] + for i in range(n): + if arr[i] == val: + res = i + break + return res + + +cpdef _partial_dependence_tree(Tree tree, DTYPE_t[:, ::1] X, + int32[::1] target_feature, + double learn_rate, + double[::1] out): + """Partial dependence of the response on the ``target_feature`` set. + + For each row in ``X`` a tree traversal is performed. + Each traversal starts from the root with weight 1.0. + + At each non-terminal node that splits on a target variable either + the left child or the right child is visited based on the feature + value of the current sample and the weight is not modified. + At each non-terminal node that splits on a complementary feature + both children are visited and the weight is multiplied by the fraction + of training samples which went to each child. + + At each terminal node the value of the node is multiplied by the + current weight (weights sum to 1 for all visited terminal nodes). + + Parameters + ---------- + tree : sklearn.tree.Tree + A regression tree; tree.values.shape[1] == 1 + X : memory view on 2d ndarray + The grid points on which the partial dependence + should be evaluated. X.shape[1] == target_feature.shape[0]. + target_feature : memory view on 1d ndarray + The set of target features for which the partial dependence + should be evaluated. X.shape[1] == target_feature.shape[0]. + learn_rate : double + Constant scaling factor for the leaf predictions. + out : memory view on 1d ndarray + The value of the partial dependence function on each grid + point. + """ + cdef Py_ssize_t i = 0 cdef Py_ssize_t n_features = X.shape[1] - cdef Py_ssize_t K = estimators.shape[1] - cdef Tree tree - for k in range(K): - tree = estimators[stage, k] - - _predict_regression_tree_inplace_fast( - (X.data), - tree.children_left, - tree.children_right, - tree.feature, - tree.threshold, - tree.value, - scale, k, K, n_samples, n_features, - ((out).data)) + cdef Node* root_node = tree.nodes + cdef double *value = tree.value + cdef SIZE_t node_count = tree.node_count + + cdef SIZE_t stack_capacity = node_count * 2 + cdef Node **node_stack + cdef double[::1] weight_stack = np_ones((stack_capacity,), dtype=np_float64) + cdef SIZE_t stack_size = 1 + cdef double left_sample_frac + cdef double current_weight + cdef double total_weight = 0.0 + cdef Node *current_node + underlying_stack = np_zeros((stack_capacity,), dtype=np.intp) + node_stack = ( underlying_stack).data + + for i in range(X.shape[0]): + # init stacks for new example + stack_size = 1 + node_stack[0] = root_node + weight_stack[0] = 1.0 + total_weight = 0.0 + + while stack_size > 0: + # get top node on stack + stack_size -= 1 + current_node = node_stack[stack_size] + + if current_node.left_child == LEAF: + out[i] += weight_stack[stack_size] * value[current_node - root_node] * \ + learn_rate + total_weight += weight_stack[stack_size] + else: + # non-terminal node + feature_index = array_index(current_node.feature, target_feature) + if feature_index != -1: + # split feature in target set + # push left or right child on stack + if X[i, feature_index] <= current_node.threshold: + # left + node_stack[stack_size] = (root_node + + current_node.left_child) + else: + # right + node_stack[stack_size] = (root_node + + current_node.right_child) + stack_size += 1 + else: + # split feature in complement set + # push both children onto stack + + # push left child + node_stack[stack_size] = root_node + current_node.left_child + current_weight = weight_stack[stack_size] + left_sample_frac = root_node[current_node.left_child].n_node_samples / \ + current_node.n_node_samples + if left_sample_frac <= 0.0 or left_sample_frac >= 1.0: + raise ValueError("left_sample_frac:%f, " + "n_samples current: %d, " + "n_samples left: %d" + % (left_sample_frac, + current_node.n_node_samples, + root_node[current_node.left_child].n_node_samples)) + weight_stack[stack_size] = current_weight * left_sample_frac + stack_size +=1 + + # push right child + node_stack[stack_size] = root_node + current_node.right_child + weight_stack[stack_size] = current_weight * \ + (1.0 - left_sample_frac) + stack_size +=1 + + if not (0.999 < total_weight < 1.001): + raise ValueError("Total weight should be 1.0 but was %.9f" % + total_weight) + + +def _random_sample_mask(np.npy_intp n_total_samples, + np.npy_intp n_total_in_bag, random_state): + """Create a random sample mask where ``n_total_in_bag`` elements are set. + + Parameters + ---------- + n_total_samples : int + The length of the resulting mask. + + n_total_in_bag : int + The number of elements in the sample mask which are set to 1. + + random_state : np.RandomState + A numpy ``RandomState`` object. + + Returns + ------- + sample_mask : np.ndarray, shape=[n_total_samples] + An ndarray where ``n_total_in_bag`` elements are set to ``True`` + the others are ``False``. + """ + cdef np.ndarray[float64, ndim=1, mode="c"] rand = \ + random_state.rand(n_total_samples) + cdef np.ndarray[uint8, ndim=1, mode="c", cast=True] sample_mask = \ + np_zeros((n_total_samples,), dtype=np_bool) + + cdef np.npy_intp n_bagged = 0 + cdef np.npy_intp i = 0 + + for i in range(n_total_samples): + if rand[i] * (n_total_samples - i) < (n_total_in_bag - n_bagged): + sample_mask[i] = 1 + n_bagged += 1 + return sample_mask diff --git a/sklearn/ensemble/bagging.py b/sklearn/ensemble/bagging.py new file mode 100644 index 0000000000000..a847e2e4b41ea --- /dev/null +++ b/sklearn/ensemble/bagging.py @@ -0,0 +1,865 @@ +"""Bagging meta-estimator.""" + +# Author: Gilles Louppe +# License: BSD 3 clause + +from __future__ import division + +import itertools +import numbers +import numpy as np +from warnings import warn +from abc import ABCMeta, abstractmethod + +from ..base import ClassifierMixin, RegressorMixin +from ..externals.joblib import Parallel, delayed +from ..externals.six import with_metaclass +from ..externals.six.moves import zip +from ..metrics import r2_score, accuracy_score +from ..tree import DecisionTreeClassifier, DecisionTreeRegressor +from ..utils import check_random_state, check_X_y, check_array, column_or_1d +from ..utils.random import sample_without_replacement +from ..utils.validation import has_fit_parameter, check_is_fitted +from ..utils.fixes import bincount +from ..utils.metaestimators import if_delegate_has_method + +from .base import BaseEnsemble, _partition_estimators + + +__all__ = ["BaggingClassifier", + "BaggingRegressor"] + +MAX_INT = np.iinfo(np.int32).max + + +def _parallel_build_estimators(n_estimators, ensemble, X, y, sample_weight, + seeds, verbose): + """Private function used to build a batch of estimators within a job.""" + # Retrieve settings + n_samples, n_features = X.shape + max_samples = ensemble.max_samples + max_features = ensemble.max_features + + if (not isinstance(max_samples, (numbers.Integral, np.integer)) and + (0.0 < max_samples <= 1.0)): + max_samples = int(max_samples * n_samples) + + if (not isinstance(max_features, (numbers.Integral, np.integer)) and + (0.0 < max_features <= 1.0)): + max_features = int(max_features * n_features) + + bootstrap = ensemble.bootstrap + bootstrap_features = ensemble.bootstrap_features + support_sample_weight = has_fit_parameter(ensemble.base_estimator_, + "sample_weight") + + # Build estimators + estimators = [] + estimators_samples = [] + estimators_features = [] + + for i in range(n_estimators): + if verbose > 1: + print("building estimator %d of %d" % (i + 1, n_estimators)) + + random_state = check_random_state(seeds[i]) + seed = check_random_state(random_state.randint(MAX_INT)) + estimator = ensemble._make_estimator(append=False) + + try: # Not all estimator accept a random_state + estimator.set_params(random_state=seed) + except ValueError: + pass + + # Draw features + if bootstrap_features: + features = random_state.randint(0, n_features, max_features) + else: + features = sample_without_replacement(n_features, + max_features, + random_state=random_state) + + # Draw samples, using sample weights, and then fit + if support_sample_weight: + if sample_weight is None: + curr_sample_weight = np.ones((n_samples,)) + else: + curr_sample_weight = sample_weight.copy() + + if bootstrap: + indices = random_state.randint(0, n_samples, max_samples) + sample_counts = bincount(indices, minlength=n_samples) + curr_sample_weight *= sample_counts + + else: + not_indices = sample_without_replacement( + n_samples, + n_samples - max_samples, + random_state=random_state) + + curr_sample_weight[not_indices] = 0 + + estimator.fit(X[:, features], y, sample_weight=curr_sample_weight) + samples = curr_sample_weight > 0. + + # Draw samples, using a mask, and then fit + else: + if bootstrap: + indices = random_state.randint(0, n_samples, max_samples) + else: + indices = sample_without_replacement(n_samples, + max_samples, + random_state=random_state) + + sample_counts = bincount(indices, minlength=n_samples) + + estimator.fit((X[indices])[:, features], y[indices]) + samples = sample_counts > 0. + + estimators.append(estimator) + estimators_samples.append(samples) + estimators_features.append(features) + + return estimators, estimators_samples, estimators_features + + +def _parallel_predict_proba(estimators, estimators_features, X, n_classes): + """Private function used to compute (proba-)predictions within a job.""" + n_samples = X.shape[0] + proba = np.zeros((n_samples, n_classes)) + + for estimator, features in zip(estimators, estimators_features): + if hasattr(estimator, "predict_proba"): + proba_estimator = estimator.predict_proba(X[:, features]) + + if n_classes == len(estimator.classes_): + proba += proba_estimator + + else: + proba[:, estimator.classes_] += \ + proba_estimator[:, range(len(estimator.classes_))] + + else: + # Resort to voting + predictions = estimator.predict(X[:, features]) + + for i in range(n_samples): + proba[i, predictions[i]] += 1 + + return proba + + +def _parallel_predict_log_proba(estimators, estimators_features, X, n_classes): + """Private function used to compute log probabilities within a job.""" + n_samples = X.shape[0] + log_proba = np.empty((n_samples, n_classes)) + log_proba.fill(-np.inf) + all_classes = np.arange(n_classes, dtype=np.int) + + for estimator, features in zip(estimators, estimators_features): + log_proba_estimator = estimator.predict_log_proba(X[:, features]) + + if n_classes == len(estimator.classes_): + log_proba = np.logaddexp(log_proba, log_proba_estimator) + + else: + log_proba[:, estimator.classes_] = np.logaddexp( + log_proba[:, estimator.classes_], + log_proba_estimator[:, range(len(estimator.classes_))]) + + missing = np.setdiff1d(all_classes, estimator.classes_) + log_proba[:, missing] = np.logaddexp(log_proba[:, missing], + -np.inf) + + return log_proba + + +def _parallel_decision_function(estimators, estimators_features, X): + """Private function used to compute decisions within a job.""" + return sum(estimator.decision_function(X[:, features]) + for estimator, features in zip(estimators, + estimators_features)) + + +def _parallel_predict_regression(estimators, estimators_features, X): + """Private function used to compute predictions within a job.""" + return sum(estimator.predict(X[:, features]) + for estimator, features in zip(estimators, + estimators_features)) + + +class BaseBagging(with_metaclass(ABCMeta, BaseEnsemble)): + """Base class for Bagging meta-estimator. + + Warning: This class should not be used directly. Use derived classes + instead. + """ + + @abstractmethod + def __init__(self, + base_estimator=None, + n_estimators=10, + max_samples=1.0, + max_features=1.0, + bootstrap=True, + bootstrap_features=False, + oob_score=False, + n_jobs=1, + random_state=None, + verbose=0): + super(BaseBagging, self).__init__( + base_estimator=base_estimator, + n_estimators=n_estimators) + + self.max_samples = max_samples + self.max_features = max_features + self.bootstrap = bootstrap + self.bootstrap_features = bootstrap_features + self.oob_score = oob_score + self.n_jobs = n_jobs + self.random_state = random_state + self.verbose = verbose + + def fit(self, X, y, sample_weight=None): + """Build a Bagging ensemble of estimators from the training + set (X, y). + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrices are accepted only if + they are supported by the base estimator. + + y : array-like, shape = [n_samples] + The target values (class labels in classification, real numbers in + regression). + + sample_weight : array-like, shape = [n_samples] or None + Sample weights. If None, then samples are equally weighted. + Note that this is supported only if the base estimator supports + sample weighting. + + Returns + ------- + self : object + Returns self. + """ + random_state = check_random_state(self.random_state) + + # Convert data + X, y = check_X_y(X, y, ['csr', 'csc', 'coo']) + + # Remap output + n_samples, self.n_features_ = X.shape + y = self._validate_y(y) + + # Check parameters + self._validate_estimator() + + if isinstance(self.max_samples, (numbers.Integral, np.integer)): + max_samples = self.max_samples + else: # float + max_samples = int(self.max_samples * X.shape[0]) + + if not (0 < max_samples <= X.shape[0]): + raise ValueError("max_samples must be in (0, n_samples]") + + if isinstance(self.max_features, (numbers.Integral, np.integer)): + max_features = self.max_features + else: # float + max_features = int(self.max_features * self.n_features_) + + if not (0 < max_features <= self.n_features_): + raise ValueError("max_features must be in (0, n_features]") + + if not self.bootstrap and self.oob_score: + raise ValueError("Out of bag estimation only available" + " if bootstrap=True") + + # Free allocated memory, if any + self.estimators_ = None + + # Parallel loop + n_jobs, n_estimators, starts = _partition_estimators(self.n_estimators, + self.n_jobs) + seeds = random_state.randint(MAX_INT, size=self.n_estimators) + + all_results = Parallel(n_jobs=n_jobs, verbose=self.verbose)( + delayed(_parallel_build_estimators)( + n_estimators[i], + self, + X, + y, + sample_weight, + seeds[starts[i]:starts[i + 1]], + verbose=self.verbose) + for i in range(n_jobs)) + + # Reduce + self.estimators_ = list(itertools.chain.from_iterable( + t[0] for t in all_results)) + self.estimators_samples_ = list(itertools.chain.from_iterable( + t[1] for t in all_results)) + self.estimators_features_ = list(itertools.chain.from_iterable( + t[2] for t in all_results)) + + if self.oob_score: + self._set_oob_score(X, y) + + return self + + @abstractmethod + def _set_oob_score(self, X, y): + """Calculate out of bag predictions and score.""" + + def _validate_y(self, y): + # Default implementation + return column_or_1d(y, warn=True) + + +class BaggingClassifier(BaseBagging, ClassifierMixin): + """A Bagging classifier. + + A Bagging classifier is an ensemble meta-estimator that fits base + classifiers each on random subsets of the original dataset and then + aggregate their individual predictions (either by voting or by averaging) + to form a final prediction. Such a meta-estimator can typically be used as + a way to reduce the variance of a black-box estimator (e.g., a decision + tree), by introducing randomization into its construction procedure and + then making an ensemble out of it. + + This algorithm encompasses several works from the literature. When random + subsets of the dataset are drawn as random subsets of the samples, then + this algorithm is known as Pasting [1]_. If samples are drawn with + replacement, then the method is known as Bagging [2]_. When random subsets + of the dataset are drawn as random subsets of the features, then the method + is known as Random Subspaces [3]_. Finally, when base estimators are built + on subsets of both samples and features, then the method is known as + Random Patches [4]_. + + Parameters + ---------- + base_estimator : object or None, optional (default=None) + The base estimator to fit on random subsets of the dataset. + If None, then the base estimator is a decision tree. + + n_estimators : int, optional (default=10) + The number of base estimators in the ensemble. + + max_samples : int or float, optional (default=1.0) + The number of samples to draw from X to train each base estimator. + - If int, then draw `max_samples` samples. + - If float, then draw `max_samples * X.shape[0]` samples. + + max_features : int or float, optional (default=1.0) + The number of features to draw from X to train each base estimator. + - If int, then draw `max_features` features. + - If float, then draw `max_features * X.shape[1]` features. + + bootstrap : boolean, optional (default=True) + Whether samples are drawn with replacement. + + bootstrap_features : boolean, optional (default=False) + Whether features are drawn with replacement. + + oob_score : bool + Whether to use out-of-bag samples to estimate + the generalization error. + + n_jobs : int, optional (default=1) + The number of jobs to run in parallel for both `fit` and `predict`. + If -1, then the number of jobs is set to the number of cores. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + verbose : int, optional (default=0) + Controls the verbosity of the building process. + + Attributes + ---------- + base_estimator_ : list of estimators + The base estimator from which the ensemble is grown. + + estimators_ : list of estimators + The collection of fitted base estimators. + + estimators_samples_ : list of arrays + The subset of drawn samples (i.e., the in-bag samples) for each base + estimator. + + estimators_features_ : list of arrays + The subset of drawn features for each base estimator. + + classes_ : array of shape = [n_classes] + The classes labels. + + n_classes_ : int or list + The number of classes. + + oob_score_ : float + Score of the training dataset obtained using an out-of-bag estimate. + + oob_decision_function_ : array of shape = [n_samples, n_classes] + Decision function computed with out-of-bag estimate on the training + set. If n_estimators is small it might be possible that a data point + was never left out during the bootstrap. In this case, + `oob_decision_function_` might contain NaN. + + References + ---------- + + .. [1] L. Breiman, "Pasting small votes for classification in large + databases and on-line", Machine Learning, 36(1), 85-103, 1999. + + .. [2] L. Breiman, "Bagging predictors", Machine Learning, 24(2), 123-140, + 1996. + + .. [3] T. Ho, "The random subspace method for constructing decision + forests", Pattern Analysis and Machine Intelligence, 20(8), 832-844, + 1998. + + .. [4] G. Louppe and P. Geurts, "Ensembles on Random Patches", Machine + Learning and Knowledge Discovery in Databases, 346-361, 2012. + """ + def __init__(self, + base_estimator=None, + n_estimators=10, + max_samples=1.0, + max_features=1.0, + bootstrap=True, + bootstrap_features=False, + oob_score=False, + n_jobs=1, + random_state=None, + verbose=0): + + super(BaggingClassifier, self).__init__( + base_estimator, + n_estimators=n_estimators, + max_samples=max_samples, + max_features=max_features, + bootstrap=bootstrap, + bootstrap_features=bootstrap_features, + oob_score=oob_score, + n_jobs=n_jobs, + random_state=random_state, + verbose=verbose) + + def _validate_estimator(self): + """Check the estimator and set the base_estimator_ attribute.""" + super(BaggingClassifier, self)._validate_estimator( + default=DecisionTreeClassifier()) + + def _set_oob_score(self, X, y): + n_classes_ = self.n_classes_ + classes_ = self.classes_ + n_samples = y.shape[0] + + predictions = np.zeros((n_samples, n_classes_)) + + for estimator, samples, features in zip(self.estimators_, + self.estimators_samples_, + self.estimators_features_): + mask = np.ones(n_samples, dtype=np.bool) + mask[samples] = False + + if hasattr(estimator, "predict_proba"): + predictions[mask, :] += estimator.predict_proba( + (X[mask, :])[:, features]) + + else: + p = estimator.predict((X[mask, :])[:, features]) + j = 0 + + for i in range(n_samples): + if mask[i]: + predictions[i, p[j]] += 1 + j += 1 + + if (predictions.sum(axis=1) == 0).any(): + warn("Some inputs do not have OOB scores. " + "This probably means too few estimators were used " + "to compute any reliable oob estimates.") + + oob_decision_function = (predictions / + predictions.sum(axis=1)[:, np.newaxis]) + oob_score = accuracy_score(y, classes_.take(np.argmax(predictions, + axis=1))) + + self.oob_decision_function_ = oob_decision_function + self.oob_score_ = oob_score + + def _validate_y(self, y): + y = column_or_1d(y, warn=True) + self.classes_, y = np.unique(y, return_inverse=True) + self.n_classes_ = len(self.classes_) + + return y + + def predict(self, X): + """Predict class for X. + + The predicted class of an input sample is computed as the class with + the highest mean predicted probability. If base estimators do not + implement a ``predict_proba`` method, then it resorts to voting. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrices are accepted only if + they are supported by the base estimator. + + Returns + ------- + y : array of shape = [n_samples] + The predicted classes. + """ + predicted_probabilitiy = self.predict_proba(X) + return self.classes_.take((np.argmax(predicted_probabilitiy, axis=1)), + axis=0) + + def predict_proba(self, X): + """Predict class probabilities for X. + + The predicted class probabilities of an input sample is computed as + the mean predicted class probabilities of the base estimators in the + ensemble. If base estimators do not implement a ``predict_proba`` + method, then it resorts to voting and the predicted class probabilities + of a an input sample represents the proportion of estimators predicting + each class. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrices are accepted only if + they are supported by the base estimator. + + Returns + ------- + p : array of shape = [n_samples, n_classes] + The class probabilities of the input samples. The order of the + classes corresponds to that in the attribute `classes_`. + """ + check_is_fitted(self, "classes_") + # Check data + X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) + + if self.n_features_ != X.shape[1]: + raise ValueError("Number of features of the model must " + "match the input. Model n_features is {0} and " + "input n_features is {1}." + "".format(self.n_features_, X.shape[1])) + + # Parallel loop + n_jobs, n_estimators, starts = _partition_estimators(self.n_estimators, + self.n_jobs) + + all_proba = Parallel(n_jobs=n_jobs, verbose=self.verbose)( + delayed(_parallel_predict_proba)( + self.estimators_[starts[i]:starts[i + 1]], + self.estimators_features_[starts[i]:starts[i + 1]], + X, + self.n_classes_) + for i in range(n_jobs)) + + # Reduce + proba = sum(all_proba) / self.n_estimators + + return proba + + def predict_log_proba(self, X): + """Predict class log-probabilities for X. + + The predicted class log-probabilities of an input sample is computed as + the log of the mean predicted class probabilities of the base + estimators in the ensemble. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrices are accepted only if + they are supported by the base estimator. + + Returns + ------- + p : array of shape = [n_samples, n_classes] + The class log-probabilities of the input samples. The order of the + classes corresponds to that in the attribute `classes_`. + """ + check_is_fitted(self, "classes_") + if hasattr(self.base_estimator_, "predict_log_proba"): + # Check data + X = check_array(X) + + if self.n_features_ != X.shape[1]: + raise ValueError("Number of features of the model must " + "match the input. Model n_features is {0} " + "and input n_features is {1} " + "".format(self.n_features_, X.shape[1])) + + # Parallel loop + n_jobs, n_estimators, starts = _partition_estimators( + self.n_estimators, self.n_jobs) + + all_log_proba = Parallel(n_jobs=n_jobs, verbose=self.verbose)( + delayed(_parallel_predict_log_proba)( + self.estimators_[starts[i]:starts[i + 1]], + self.estimators_features_[starts[i]:starts[i + 1]], + X, + self.n_classes_) + for i in range(n_jobs)) + + # Reduce + log_proba = all_log_proba[0] + + for j in range(1, len(all_log_proba)): + log_proba = np.logaddexp(log_proba, all_log_proba[j]) + + log_proba -= np.log(self.n_estimators) + + return log_proba + + else: + return np.log(self.predict_proba(X)) + + @if_delegate_has_method(delegate='base_estimator') + def decision_function(self, X): + """Average of the decision functions of the base classifiers. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrices are accepted only if + they are supported by the base estimator. + + Returns + ------- + score : array, shape = [n_samples, k] + The decision function of the input samples. The columns correspond + to the classes in sorted order, as they appear in the attribute + ``classes_``. Regression and binary classification are special + cases with ``k == 1``, otherwise ``k==n_classes``. + + """ + check_is_fitted(self, "classes_") + + # Check data + X = check_array(X) + + if self.n_features_ != X.shape[1]: + raise ValueError("Number of features of the model must " + "match the input. Model n_features is {1} and " + "input n_features is {2} " + "".format(self.n_features_, X.shape[1])) + + # Parallel loop + n_jobs, n_estimators, starts = _partition_estimators(self.n_estimators, + self.n_jobs) + + all_decisions = Parallel(n_jobs=n_jobs, verbose=self.verbose)( + delayed(_parallel_decision_function)( + self.estimators_[starts[i]:starts[i + 1]], + self.estimators_features_[starts[i]:starts[i + 1]], + X) + for i in range(n_jobs)) + + # Reduce + decisions = sum(all_decisions) / self.n_estimators + + return decisions + + +class BaggingRegressor(BaseBagging, RegressorMixin): + """A Bagging regressor. + + A Bagging regressor is an ensemble meta-estimator that fits base + regressors each on random subsets of the original dataset and then + aggregate their individual predictions (either by voting or by averaging) + to form a final prediction. Such a meta-estimator can typically be used as + a way to reduce the variance of a black-box estimator (e.g., a decision + tree), by introducing randomization into its construction procedure and + then making an ensemble out of it. + + This algorithm encompasses several works from the literature. When random + subsets of the dataset are drawn as random subsets of the samples, then + this algorithm is known as Pasting [1]_. If samples are drawn with + replacement, then the method is known as Bagging [2]_. When random subsets + of the dataset are drawn as random subsets of the features, then the method + is known as Random Subspaces [3]_. Finally, when base estimators are built + on subsets of both samples and features, then the method is known as + Random Patches [4]_. + + Parameters + ---------- + base_estimator : object or None, optional (default=None) + The base estimator to fit on random subsets of the dataset. + If None, then the base estimator is a decision tree. + + n_estimators : int, optional (default=10) + The number of base estimators in the ensemble. + + max_samples : int or float, optional (default=1.0) + The number of samples to draw from X to train each base estimator. + - If int, then draw `max_samples` samples. + - If float, then draw `max_samples * X.shape[0]` samples. + + max_features : int or float, optional (default=1.0) + The number of features to draw from X to train each base estimator. + - If int, then draw `max_features` features. + - If float, then draw `max_features * X.shape[1]` features. + + bootstrap : boolean, optional (default=True) + Whether samples are drawn with replacement. + + bootstrap_features : boolean, optional (default=False) + Whether features are drawn with replacement. + + oob_score : bool + Whether to use out-of-bag samples to estimate + the generalization error. + + n_jobs : int, optional (default=1) + The number of jobs to run in parallel for both `fit` and `predict`. + If -1, then the number of jobs is set to the number of cores. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + verbose : int, optional (default=0) + Controls the verbosity of the building process. + + Attributes + ---------- + estimators_ : list of estimators + The collection of fitted sub-estimators. + + estimators_samples_ : list of arrays + The subset of drawn samples (i.e., the in-bag samples) for each base + estimator. + + estimators_features_ : list of arrays + The subset of drawn features for each base estimator. + + oob_score_ : float + Score of the training dataset obtained using an out-of-bag estimate. + + oob_prediction_ : array of shape = [n_samples] + Prediction computed with out-of-bag estimate on the training + set. If n_estimators is small it might be possible that a data point + was never left out during the bootstrap. In this case, + `oob_prediction_` might contain NaN. + + References + ---------- + + .. [1] L. Breiman, "Pasting small votes for classification in large + databases and on-line", Machine Learning, 36(1), 85-103, 1999. + + .. [2] L. Breiman, "Bagging predictors", Machine Learning, 24(2), 123-140, + 1996. + + .. [3] T. Ho, "The random subspace method for constructing decision + forests", Pattern Analysis and Machine Intelligence, 20(8), 832-844, + 1998. + + .. [4] G. Louppe and P. Geurts, "Ensembles on Random Patches", Machine + Learning and Knowledge Discovery in Databases, 346-361, 2012. + """ + + def __init__(self, + base_estimator=None, + n_estimators=10, + max_samples=1.0, + max_features=1.0, + bootstrap=True, + bootstrap_features=False, + oob_score=False, + n_jobs=1, + random_state=None, + verbose=0): + super(BaggingRegressor, self).__init__( + base_estimator, + n_estimators=n_estimators, + max_samples=max_samples, + max_features=max_features, + bootstrap=bootstrap, + bootstrap_features=bootstrap_features, + oob_score=oob_score, + n_jobs=n_jobs, + random_state=random_state, + verbose=verbose) + + def predict(self, X): + """Predict regression target for X. + + The predicted regression target of an input sample is computed as the + mean predicted regression targets of the estimators in the ensemble. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrices are accepted only if + they are supported by the base estimator. + + Returns + ------- + y : array of shape = [n_samples] + The predicted values. + """ + check_is_fitted(self, "estimators_features_") + # Check data + X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) + + # Parallel loop + n_jobs, n_estimators, starts = _partition_estimators(self.n_estimators, + self.n_jobs) + + all_y_hat = Parallel(n_jobs=n_jobs, verbose=self.verbose)( + delayed(_parallel_predict_regression)( + self.estimators_[starts[i]:starts[i + 1]], + self.estimators_features_[starts[i]:starts[i + 1]], + X) + for i in range(n_jobs)) + + # Reduce + y_hat = sum(all_y_hat) / self.n_estimators + + return y_hat + + def _validate_estimator(self): + """Check the estimator and set the base_estimator_ attribute.""" + super(BaggingRegressor, self)._validate_estimator( + default=DecisionTreeRegressor()) + + def _set_oob_score(self, X, y): + n_samples = y.shape[0] + + predictions = np.zeros((n_samples,)) + n_predictions = np.zeros((n_samples,)) + + for estimator, samples, features in zip(self.estimators_, + self.estimators_samples_, + self.estimators_features_): + mask = np.ones(n_samples, dtype=np.bool) + mask[samples] = False + + predictions[mask] += estimator.predict((X[mask, :])[:, features]) + n_predictions[mask] += 1 + + if (n_predictions == 0).any(): + warn("Some inputs do not have OOB scores. " + "This probably means too few estimators were used " + "to compute any reliable oob estimates.") + n_predictions[n_predictions == 0] = 1 + + predictions /= n_predictions + + self.oob_prediction_ = predictions + self.oob_score_ = r2_score(y, predictions) diff --git a/sklearn/ensemble/base.py b/sklearn/ensemble/base.py index 270d012f60327..eaa590b6d3092 100644 --- a/sklearn/ensemble/base.py +++ b/sklearn/ensemble/base.py @@ -3,11 +3,14 @@ """ # Authors: Gilles Louppe -# License: BSD 3 +# License: BSD 3 clause + +import numpy as np from ..base import clone from ..base import BaseEstimator from ..base import MetaEstimatorMixin +from ..utils import _get_n_jobs class BaseEnsemble(BaseEstimator, MetaEstimatorMixin): @@ -27,15 +30,18 @@ class BaseEnsemble(BaseEstimator, MetaEstimatorMixin): estimator_params : list of strings The list of attributes to use as parameters when instantiating a new base estimator. If none are given, default parameters are used. - """ - def __init__(self, base_estimator, n_estimators=10, estimator_params=[]): - # Check parameters - if not isinstance(base_estimator, BaseEstimator): - raise TypeError("estimator must be a subclass of BaseEstimator") - if n_estimators <= 0: - raise ValueError("n_estimators must be greater than zero.") + Attributes + ---------- + base_estimator_ : list of estimators + The base estimator from which the ensemble is grown. + estimators_ : list of estimators + The collection of fitted base estimators. + """ + + def __init__(self, base_estimator, n_estimators=10, + estimator_params=tuple()): # Set parameters self.base_estimator = base_estimator self.n_estimators = n_estimators @@ -46,13 +52,28 @@ def __init__(self, base_estimator, n_estimators=10, estimator_params=[]): # This needs to be filled by the derived classes. self.estimators_ = [] + def _validate_estimator(self, default=None): + """Check the estimator and the n_estimator attribute, set the + `base_estimator_` attribute.""" + if self.n_estimators <= 0: + raise ValueError("n_estimators must be greater than zero, " + "got {0}.".format(self.n_estimators)) + + if self.base_estimator is not None: + self.base_estimator_ = self.base_estimator + else: + self.base_estimator_ = default + + if self.base_estimator_ is None: + raise ValueError("base_estimator cannot be None") + def _make_estimator(self, append=True): - """Makes, configures and returns a copy of the base estimator. + """Make and configure a copy of the `base_estimator_` attribute. Warning: This method should be used to properly instantiate new sub-estimators. """ - estimator = clone(self.base_estimator) + estimator = clone(self.base_estimator_) estimator.set_params(**dict((p, getattr(self, p)) for p in self.estimator_params)) @@ -68,3 +89,21 @@ def __len__(self): def __getitem__(self, index): """Returns the index'th estimator in the ensemble.""" return self.estimators_[index] + + def __iter__(self): + """Returns iterator over estimators in the ensemble.""" + return iter(self.estimators_) + + +def _partition_estimators(n_estimators, n_jobs): + """Private function used to partition estimators between jobs.""" + # Compute the number of jobs + n_jobs = min(_get_n_jobs(n_jobs), n_estimators) + + # Partition estimators between jobs + n_estimators_per_job = (n_estimators // n_jobs) * np.ones(n_jobs, + dtype=np.int) + n_estimators_per_job[:n_estimators % n_jobs] += 1 + starts = np.cumsum(n_estimators_per_job) + + return n_jobs, n_estimators_per_job.tolist(), [0] + starts.tolist() diff --git a/sklearn/ensemble/forest.py b/sklearn/ensemble/forest.py index f597ce5246a13..d533c2e71007f 100644 --- a/sklearn/ensemble/forest.py +++ b/sklearn/ensemble/forest.py @@ -24,7 +24,7 @@ class calls the ``fit`` method of each sub-estimator on random samples - The ``ExtraTreesClassifier`` and ``ExtraTreesRegressor`` derived classes provide the user with concrete implementations of the - forest ensemble method using the extremly randomized trees + forest ensemble method using the extremely randomized trees ``ExtraTreeClassifier`` and ``ExtraTreeRegressor`` as sub-estimator implementations. @@ -32,377 +32,408 @@ class calls the ``fit`` method of each sub-estimator on random samples """ -# Authors: Gilles Louppe, Brian Holt -# License: BSD 3 +# Authors: Gilles Louppe +# Brian Holt +# Joly Arnaud +# Fares Hedayati +# +# License: BSD 3 clause + +from __future__ import division -import itertools -import numpy as np from warnings import warn from abc import ABCMeta, abstractmethod +import numpy as np +from scipy.sparse import issparse + from ..base import ClassifierMixin, RegressorMixin -from ..externals.joblib import Parallel, delayed, cpu_count -from ..feature_selection.selector_mixin import SelectorMixin -from ..tree import DecisionTreeClassifier, DecisionTreeRegressor, \ - ExtraTreeClassifier, ExtraTreeRegressor -from ..tree._tree import DTYPE, DOUBLE -from ..utils import array2d, check_random_state, check_arrays +from ..externals.joblib import Parallel, delayed +from ..externals import six +from ..feature_selection.from_model import _LearntSelectorMixin from ..metrics import r2_score - -from .base import BaseEnsemble +from ..preprocessing import OneHotEncoder +from ..tree import (DecisionTreeClassifier, DecisionTreeRegressor, + ExtraTreeClassifier, ExtraTreeRegressor) +from ..tree._tree import DTYPE, DOUBLE +from ..utils import check_random_state, check_array, compute_sample_weight +from ..utils.validation import DataConversionWarning, check_is_fitted +from .base import BaseEnsemble, _partition_estimators +from ..utils.fixes import bincount __all__ = ["RandomForestClassifier", "RandomForestRegressor", "ExtraTreesClassifier", - "ExtraTreesRegressor"] + "ExtraTreesRegressor", + "RandomTreesEmbedding"] MAX_INT = np.iinfo(np.int32).max -def _parallel_build_trees(n_trees, forest, X, y, - sample_mask, X_argsorted, seed, verbose): - """Private function used to build a batch of trees within a job.""" - random_state = check_random_state(seed) - trees = [] - - for i in xrange(n_trees): - if verbose > 1: - print("building tree %d of %d" % (i + 1, n_trees)) - seed = random_state.randint(MAX_INT) - - tree = forest._make_estimator(append=False) - tree.set_params(compute_importances=forest.compute_importances) - tree.set_params(random_state=check_random_state(seed)) - - if forest.bootstrap: - n_samples = X.shape[0] - indices = random_state.randint(0, n_samples, n_samples) - tree.fit(X[indices], y[indices], - sample_mask=sample_mask, X_argsorted=X_argsorted) - tree.indices_ = indices +def _parallel_build_trees(tree, forest, X, y, sample_weight, tree_idx, n_trees, + verbose=0, class_weight=None): + """Private function used to fit a single tree in parallel.""" + if verbose > 1: + print("building tree %d of %d" % (tree_idx + 1, n_trees)) + if forest.bootstrap: + n_samples = X.shape[0] + if sample_weight is None: + curr_sample_weight = np.ones((n_samples,), dtype=np.float64) else: - tree.fit(X, y, - sample_mask=sample_mask, X_argsorted=X_argsorted) - - trees.append(tree) - - return trees - - -def _parallel_predict_proba(trees, X, n_classes, n_outputs): - """Private function used to compute a batch of predictions within a job.""" - n_samples = X.shape[0] - p = [] - - for k in xrange(n_outputs): - p.append(np.zeros((n_samples, n_classes[k]))) - - for tree in trees: - p_tree = tree.predict_proba(X) - - if n_outputs == 1: - p_tree = [p_tree] - - for k in xrange(n_outputs): - if n_classes[k] == tree.n_classes_[k]: - p[k] += p_tree[k] - - else: - for j, c in enumerate(tree.classes_[k]): - p[k][:, c] += p_tree[k][:, j] - - return p - - -def _parallel_predict_regression(trees, X): - """Private function used to compute a batch of predictions within a job.""" - return sum(tree.predict(X) for tree in trees) - - -def _partition_trees(forest): - """Private function used to partition trees between jobs.""" - # Compute the number of jobs - if forest.n_jobs == -1: - n_jobs = min(cpu_count(), forest.n_estimators) - - else: - n_jobs = min(forest.n_jobs, forest.n_estimators) - - # Partition trees between jobs - n_trees = [int(forest.n_estimators / n_jobs)] * n_jobs - - for i in xrange(forest.n_estimators % n_jobs): - n_trees[i] += 1 - - starts = [0] * (n_jobs + 1) - - for i in xrange(1, n_jobs + 1): - starts[i] = starts[i - 1] + n_trees[i - 1] + curr_sample_weight = sample_weight.copy() - return n_jobs, n_trees, starts + random_state = check_random_state(tree.random_state) + indices = random_state.randint(0, n_samples, n_samples) + sample_counts = bincount(indices, minlength=n_samples) + curr_sample_weight *= sample_counts + if class_weight == 'subsample': + curr_sample_weight *= compute_sample_weight('auto', y, indices) -def _parallel_X_argsort(X): - """Private function used to sort the features of X.""" - return np.asarray(np.argsort(X.T, axis=1).T, dtype=np.int32, order="F") + tree.fit(X, y, sample_weight=curr_sample_weight, check_input=False) - -def _partition_features(forest, n_total_features): - """Private function used to partition features between jobs.""" - # Compute the number of jobs - if forest.n_jobs == -1: - n_jobs = min(cpu_count(), n_total_features) + tree.indices_ = sample_counts > 0. else: - n_jobs = min(forest.n_jobs, n_total_features) - - # Partition features between jobs - n_features = [n_total_features / n_jobs] * n_jobs + tree.fit(X, y, sample_weight=sample_weight, check_input=False) - for i in xrange(n_total_features % n_jobs): - n_features[i] += 1 + return tree - starts = [0] * (n_jobs + 1) - for i in xrange(1, n_jobs + 1): - starts[i] = starts[i - 1] + n_features[i - 1] +def _parallel_helper(obj, methodname, *args, **kwargs): + """Private helper to workaround Python 2 pickle limitations""" + return getattr(obj, methodname)(*args, **kwargs) - return n_jobs, n_features, starts - -class BaseForest(BaseEnsemble, SelectorMixin): +class BaseForest(six.with_metaclass(ABCMeta, BaseEnsemble, + _LearntSelectorMixin)): """Base class for forests of trees. Warning: This class should not be used directly. Use derived classes instead. """ - __metaclass__ = ABCMeta @abstractmethod - def __init__(self, base_estimator, - n_estimators=10, - estimator_params=[], - bootstrap=False, - compute_importances=False, - oob_score=False, - n_jobs=1, - random_state=None, - verbose=0): + def __init__(self, + base_estimator, + n_estimators=10, + estimator_params=tuple(), + bootstrap=False, + oob_score=False, + n_jobs=1, + random_state=None, + verbose=0, + warm_start=False, + class_weight=None): super(BaseForest, self).__init__( base_estimator=base_estimator, n_estimators=n_estimators, estimator_params=estimator_params) self.bootstrap = bootstrap - self.compute_importances = compute_importances self.oob_score = oob_score self.n_jobs = n_jobs self.random_state = random_state + self.verbose = verbose + self.warm_start = warm_start + self.class_weight = class_weight - self.n_features_ = None - self.n_outputs_ = None - self.classes_ = None - self.n_classes_ = None - self.feature_importances_ = None + def apply(self, X): + """Apply trees in the forest to X, return leaf indices. - self.verbose = verbose + Parameters + ---------- + X : array-like or sparse matrix, shape = [n_samples, n_features] + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Returns + ------- + X_leaves : array_like, shape = [n_samples, n_estimators] + For each datapoint x in X and for each tree in the forest, + return the index of the leaf x ends up in. + """ + check_is_fitted(self, 'n_outputs_') + + X = check_array(X, dtype=DTYPE, accept_sparse="csr") + results = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, + backend="threading")( + delayed(_parallel_helper)(tree.tree_, 'apply', X) + for tree in self.estimators_) - def fit(self, X, y): + return np.array(results).T + + def fit(self, X, y, sample_weight=None): """Build a forest of trees from the training set (X, y). Parameters ---------- - X : array-like of shape = [n_samples, n_features] - The training input samples. + X : array-like or sparse matrix of shape = [n_samples, n_features] + The training input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csc_matrix``. y : array-like, shape = [n_samples] or [n_samples, n_outputs] - The target values (integers that correspond to classes in - classification, real numbers in regression). + The target values (class labels in classification, real numbers in + regression). + + sample_weight : array-like, shape = [n_samples] or None + Sample weights. If None, then samples are equally weighted. Splits + that would create child nodes with net zero or negative weight are + ignored while searching for a split in each node. In the case of + classification, splits are also ignored if they would result in any + single class carrying a negative weight in either child node. Returns ------- self : object Returns self. """ - self.random_state = check_random_state(self.random_state) - - # Precompute some data - X, y = check_arrays(X, y, sparse_format="dense") - if getattr(X, "dtype", None) != DTYPE or \ - X.ndim != 2 or not X.flags.fortran: - X = array2d(X, dtype=DTYPE, order="F") - + # Validate or convert input data + X = check_array(X, dtype=DTYPE, accept_sparse="csc") + if issparse(X): + # Pre-sort indices to avoid that each individual tree of the + # ensemble sorts the indices. + X.sort_indices() + + # Remap output n_samples, self.n_features_ = X.shape - if self.bootstrap: - sample_mask = None - X_argsorted = None - - else: - if self.oob_score: - raise ValueError("Out of bag estimation only available" - " if bootstrap=True") + y = np.atleast_1d(y) + if y.ndim == 2 and y.shape[1] == 1: + warn("A column-vector y was passed when a 1d array was" + " expected. Please change the shape of y to " + "(n_samples,), for example using ravel().", + DataConversionWarning, stacklevel=2) - sample_mask = np.ones((n_samples,), dtype=np.bool) + if y.ndim == 1: + # reshape is necessary to preserve the data contiguity against vs + # [:, np.newaxis] that does not. + y = np.reshape(y, (-1, 1)) - n_jobs, _, starts = _partition_features(self, self.n_features_) + self.n_outputs_ = y.shape[1] - all_X_argsorted = Parallel(n_jobs=n_jobs, verbose=self.verbose)( - delayed(_parallel_X_argsort)( - X[:, starts[i]:starts[i + 1]]) - for i in xrange(n_jobs)) + y, expanded_class_weight = self._validate_y_class_weight(y) - X_argsorted = np.asfortranarray(np.hstack(all_X_argsorted)) + if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous: + y = np.ascontiguousarray(y, dtype=DOUBLE) - y = np.atleast_1d(y) - if y.ndim == 1: - y = y[:, np.newaxis] + if expanded_class_weight is not None: + if sample_weight is not None: + sample_weight = sample_weight * expanded_class_weight + else: + sample_weight = expanded_class_weight - self.classes_ = [] - self.n_classes_ = [] - self.n_outputs_ = y.shape[1] + # Check parameters + self._validate_estimator() - if isinstance(self.base_estimator, ClassifierMixin): - y = np.copy(y) + if not self.bootstrap and self.oob_score: + raise ValueError("Out of bag estimation only available" + " if bootstrap=True") - for k in xrange(self.n_outputs_): - unique = np.unique(y[:, k]) - self.classes_.append(unique) - self.n_classes_.append(unique.shape[0]) - y[:, k] = np.searchsorted(unique, y[:, k]) + random_state = check_random_state(self.random_state) - if getattr(y, "dtype", None) != DTYPE or not y.flags.contiguous: - y = np.ascontiguousarray(y, dtype=DOUBLE) + if not self.warm_start: + # Free allocated memory, if any + self.estimators_ = [] - # Assign chunk of trees to jobs - n_jobs, n_trees, _ = _partition_trees(self) + n_more_estimators = self.n_estimators - len(self.estimators_) - # Parallel loop - all_trees = Parallel(n_jobs=n_jobs, verbose=self.verbose)( - delayed(_parallel_build_trees)( - n_trees[i], - self, - X, - y, - sample_mask, - X_argsorted, - self.random_state.randint(MAX_INT), - verbose=self.verbose) - for i in xrange(n_jobs)) + if n_more_estimators < 0: + raise ValueError('n_estimators=%d must be larger or equal to ' + 'len(estimators_)=%d when warm_start==True' + % (self.n_estimators, len(self.estimators_))) - # Reduce - self.estimators_ = [tree for tree in itertools.chain(*all_trees)] + elif n_more_estimators == 0: + warn("Warm-start fitting without increasing n_estimators does not " + "fit new trees.") + else: + if self.warm_start and len(self.estimators_) > 0: + # We draw from the random state to get the random state we + # would have got if we hadn't used a warm_start. + random_state.randint(MAX_INT, size=len(self.estimators_)) + + trees = [] + for i in range(n_more_estimators): + tree = self._make_estimator(append=False) + tree.set_params(random_state=random_state.randint(MAX_INT)) + trees.append(tree) + + # Parallel loop: we use the threading backend as the Cython code + # for fitting the trees is internally releasing the Python GIL + # making threading always more efficient than multiprocessing in + # that case. + trees = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, + backend="threading")( + delayed(_parallel_build_trees)( + t, self, X, y, sample_weight, i, len(trees), + verbose=self.verbose, class_weight=self.class_weight) + for i, t in enumerate(trees)) + + # Collect newly grown trees + self.estimators_.extend(trees) - # Calculate out of bag predictions and score if self.oob_score: - if isinstance(self, ClassifierMixin): - self.oob_decision_function_ = [] - self.oob_score_ = 0.0 + self._set_oob_score(X, y) - predictions = [] - for k in xrange(self.n_outputs_): - predictions.append(np.zeros((n_samples, - self.n_classes_[k]))) + # Decapsulate classes_ attributes + if hasattr(self, "classes_") and self.n_outputs_ == 1: + self.n_classes_ = self.n_classes_[0] + self.classes_ = self.classes_[0] - for estimator in self.estimators_: - mask = np.ones(n_samples, dtype=np.bool) - mask[estimator.indices_] = False - - p_estimator = estimator.predict_proba(X[mask, :]) - if self.n_outputs_ == 1: - p_estimator = [p_estimator] + return self - for k in xrange(self.n_outputs_): - predictions[k][mask, :] += p_estimator[k] + @abstractmethod + def _set_oob_score(self, X, y): + """Calculate out of bag predictions and score.""" - for k in xrange(self.n_outputs_): - if (predictions[k].sum(axis=1) == 0).any(): - warn("Some inputs do not have OOB scores. " - "This probably means too few trees were used " - "to compute any reliable oob estimates.") - decision = predictions[k] \ - / predictions[k].sum(axis=1)[:, np.newaxis] - self.oob_decision_function_.append(decision) + def _validate_y_class_weight(self, y): + # Default implementation + return y, None - self.oob_score_ += np.mean(y[:, k] \ - == np.argmax(predictions[k], axis=1)) + @property + def feature_importances_(self): + """Return the feature importances (the higher, the more important the + feature). - if self.n_outputs_ == 1: - self.oob_decision_function_ = \ - self.oob_decision_function_[0] + Returns + ------- + feature_importances_ : array, shape = [n_features] + """ + check_is_fitted(self, 'n_outputs_') - self.oob_score_ /= self.n_outputs_ + if self.estimators_ is None or len(self.estimators_) == 0: + raise ValueError("Estimator not fitted, " + "call `fit` before `feature_importances_`.") - else: - # Regression: - predictions = np.zeros((n_samples, self.n_outputs_)) - n_predictions = np.zeros((n_samples, self.n_outputs_)) - - for estimator in self.estimators_: - mask = np.ones(n_samples, dtype=np.bool) - mask[estimator.indices_] = False - - p_estimator = estimator.predict(X[mask, :]) - if self.n_outputs_ == 1: - p_estimator = p_estimator[:, np.newaxis] - - predictions[mask, :] += p_estimator - n_predictions[mask, :] += 1 - if (n_predictions == 0).any(): - warn("Some inputs do not have OOB scores. " - "This probably means too few trees were used " - "to compute any reliable oob estimates.") - n_predictions[n_predictions == 0] = 1 - predictions /= n_predictions - - self.oob_prediction_ = predictions - if self.n_outputs_ == 1: - self.oob_prediction_ = \ - self.oob_prediction_.reshape((n_samples, )) - - self.oob_score_ = 0.0 - for k in xrange(self.n_outputs_): - self.oob_score_ += r2_score(y[:, k], predictions[:, k]) - self.oob_score_ /= self.n_outputs_ - - # Sum the importances - if self.compute_importances: - self.feature_importances_ = \ - sum(tree.feature_importances_ for tree in self.estimators_) \ - / self.n_estimators + all_importances = Parallel(n_jobs=self.n_jobs, backend="threading")( + delayed(getattr)(tree, 'feature_importances_') + for tree in self.estimators_) - return self + return sum(all_importances) / len(self.estimators_) -class ForestClassifier(BaseForest, ClassifierMixin): +class ForestClassifier(six.with_metaclass(ABCMeta, BaseForest, + ClassifierMixin)): """Base class for forest of trees-based classifiers. Warning: This class should not be used directly. Use derived classes instead. """ - __metaclass__ = ABCMeta @abstractmethod - def __init__(self, base_estimator, - n_estimators=10, - estimator_params=[], - bootstrap=False, - compute_importances=False, - oob_score=False, - n_jobs=1, - random_state=None, - verbose=0): + def __init__(self, + base_estimator, + n_estimators=10, + estimator_params=tuple(), + bootstrap=False, + oob_score=False, + n_jobs=1, + random_state=None, + verbose=0, + warm_start=False, + class_weight=None): + super(ForestClassifier, self).__init__( base_estimator, n_estimators=n_estimators, estimator_params=estimator_params, bootstrap=bootstrap, - compute_importances=compute_importances, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, - verbose=verbose) + verbose=verbose, + warm_start=warm_start, + class_weight=class_weight) + + def _set_oob_score(self, X, y): + """Compute out-of-bag score""" + n_classes_ = self.n_classes_ + n_samples = y.shape[0] + + oob_decision_function = [] + oob_score = 0.0 + predictions = [] + + for k in range(self.n_outputs_): + predictions.append(np.zeros((n_samples, n_classes_[k]))) + + sample_indices = np.arange(n_samples) + for estimator in self.estimators_: + mask = np.ones(n_samples, dtype=np.bool) + mask[estimator.indices_] = False + mask_indices = sample_indices[mask] + p_estimator = estimator.predict_proba(X[mask_indices, :]) + + if self.n_outputs_ == 1: + p_estimator = [p_estimator] + + for k in range(self.n_outputs_): + predictions[k][mask_indices, :] += p_estimator[k] + + for k in range(self.n_outputs_): + if (predictions[k].sum(axis=1) == 0).any(): + warn("Some inputs do not have OOB scores. " + "This probably means too few trees were used " + "to compute any reliable oob estimates.") + + decision = (predictions[k] / + predictions[k].sum(axis=1)[:, np.newaxis]) + oob_decision_function.append(decision) + oob_score += np.mean(y[:, k] == + np.argmax(predictions[k], axis=1), axis=0) + + if self.n_outputs_ == 1: + self.oob_decision_function_ = oob_decision_function[0] + else: + self.oob_decision_function_ = oob_decision_function + + self.oob_score_ = oob_score / self.n_outputs_ + + def _validate_y_class_weight(self, y): + y = np.copy(y) + expanded_class_weight = None + + if self.class_weight is not None: + y_original = np.copy(y) + + self.classes_ = [] + self.n_classes_ = [] + + for k in range(self.n_outputs_): + classes_k, y[:, k] = np.unique(y[:, k], return_inverse=True) + self.classes_.append(classes_k) + self.n_classes_.append(classes_k.shape[0]) + + if self.class_weight is not None: + valid_presets = ('auto', 'subsample') + if isinstance(self.class_weight, six.string_types): + if self.class_weight not in valid_presets: + raise ValueError('Valid presets for class_weight include ' + '"auto" and "subsample". Given "%s".' + % self.class_weight) + if self.warm_start: + warn('class_weight presets "auto" or "subsample" are ' + 'not recommended for warm_start if the fitted data ' + 'differs from the full dataset. In order to use ' + '"auto" weights, use compute_class_weight("auto", ' + 'classes, y). In place of y you can use a large ' + 'enough sample of the full training set target to ' + 'properly estimate the class frequency ' + 'distributions. Pass the resulting weights as the ' + 'class_weight parameter.') + + if self.class_weight != 'subsample' or not self.bootstrap: + if self.class_weight == 'subsample': + class_weight = 'auto' + else: + class_weight = self.class_weight + expanded_class_weight = compute_sample_weight(class_weight, + y_original) + + return y, expanded_class_weight def predict(self, X): """Predict class for X. @@ -412,98 +443,113 @@ def predict(self, X): Parameters ---------- - X : array-like of shape = [n_samples, n_features] - The input samples. + X : array-like or sparse matrix of shape = [n_samples, n_features] + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. Returns ------- y : array of shape = [n_samples] or [n_samples, n_outputs] The predicted classes. """ - n_samples = len(X) + check_is_fitted(self, 'n_outputs_') - P = self.predict_proba(X) - if self.n_outputs_ == 1: - P = [P] + # ensure_2d=False because there are actually unit test checking we fail + # for 1d. + X = check_array(X, ensure_2d=False, accept_sparse="csr") + proba = self.predict_proba(X) - predictions = np.zeros((n_samples, self.n_outputs_)) + if self.n_outputs_ == 1: + return self.classes_.take(np.argmax(proba, axis=1), axis=0) - for k in xrange(self.n_outputs_): - predictions[:, k] = self.classes_[k].take(np.argmax(P[k], axis=1), - axis=0) + else: + n_samples = proba[0].shape[0] + predictions = np.zeros((n_samples, self.n_outputs_)) - if self.n_outputs_ == 1: - predictions = predictions.reshape((n_samples, )) + for k in range(self.n_outputs_): + predictions[:, k] = self.classes_[k].take(np.argmax(proba[k], + axis=1), + axis=0) - return predictions + return predictions def predict_proba(self, X): """Predict class probabilities for X. The predicted class probabilities of an input sample is computed as - the mean predicted class probabilities of the trees in the forest. + the mean predicted class probabilities of the trees in the forest. The + class probability of a single tree is the fraction of samples of the same + class in a leaf. Parameters ---------- - X : array-like of shape = [n_samples, n_features] - The input samples. + X : array-like or sparse matrix of shape = [n_samples, n_features] + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. Returns ------- p : array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1. - The class probabilities of the input samples. Classes are - ordered by arithmetical order. + The class probabilities of the input samples. The order of the + classes corresponds to that in the attribute `classes_`. """ + check_is_fitted(self, 'n_outputs_') + # Check data - if getattr(X, "dtype", None) != DTYPE or X.ndim != 2: - X = array2d(X, dtype=DTYPE) + X = check_array(X, dtype=DTYPE, accept_sparse="csr") # Assign chunk of trees to jobs - n_jobs, n_trees, starts = _partition_trees(self) + n_jobs, n_trees, starts = _partition_estimators(self.n_estimators, + self.n_jobs) # Parallel loop - all_p = Parallel(n_jobs=n_jobs, verbose=self.verbose)( - delayed(_parallel_predict_proba)( - self.estimators_[starts[i]:starts[i + 1]], - X, - self.n_classes_, - self.n_outputs_) - for i in xrange(n_jobs)) + all_proba = Parallel(n_jobs=n_jobs, verbose=self.verbose, + backend="threading")( + delayed(_parallel_helper)(e, 'predict_proba', X) + for e in self.estimators_) # Reduce - p = all_p[0] - - for j in xrange(1, len(all_p)): - for k in xrange(self.n_outputs_): - p[k] += all_p[j][k] - - for k in xrange(self.n_outputs_): - p[k] /= self.n_estimators + proba = all_proba[0] if self.n_outputs_ == 1: - return p[0] + for j in range(1, len(all_proba)): + proba += all_proba[j] + + proba /= len(self.estimators_) else: - return p + for j in range(1, len(all_proba)): + for k in range(self.n_outputs_): + proba[k] += all_proba[j][k] + + for k in range(self.n_outputs_): + proba[k] /= self.n_estimators + + return proba def predict_log_proba(self, X): """Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as - the mean predicted class log-probabilities of the trees in the forest. + the log of the mean predicted class probabilities of the trees in the + forest. Parameters ---------- - X : array-like of shape = [n_samples, n_features] - The input samples. + X : array-like or sparse matrix of shape = [n_samples, n_features] + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. Returns ------- p : array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1. - The class log-probabilities of the input samples. Classes are - ordered by arithmetical order. + The class probabilities of the input samples. The order of the + classes corresponds to that in the attribute `classes_`. """ proba = self.predict_proba(X) @@ -511,40 +557,40 @@ def predict_log_proba(self, X): return np.log(proba) else: - for k in xrange(self.n_outputs_): + for k in range(self.n_outputs_): proba[k] = np.log(proba[k]) return proba -class ForestRegressor(BaseForest, RegressorMixin): +class ForestRegressor(six.with_metaclass(ABCMeta, BaseForest, RegressorMixin)): """Base class for forest of trees-based regressors. Warning: This class should not be used directly. Use derived classes instead. """ - __metaclass__ = ABCMeta @abstractmethod - def __init__(self, base_estimator, - n_estimators=10, - estimator_params=[], - bootstrap=False, - compute_importances=False, - oob_score=False, - n_jobs=1, - random_state=None, - verbose=0): + def __init__(self, + base_estimator, + n_estimators=10, + estimator_params=tuple(), + bootstrap=False, + oob_score=False, + n_jobs=1, + random_state=None, + verbose=0, + warm_start=False): super(ForestRegressor, self).__init__( base_estimator, n_estimators=n_estimators, estimator_params=estimator_params, bootstrap=bootstrap, - compute_importances=compute_importances, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, - verbose=verbose) + verbose=verbose, + warm_start=warm_start) def predict(self, X): """Predict regression target for X. @@ -554,39 +600,84 @@ def predict(self, X): Parameters ---------- - X : array-like of shape = [n_samples, n_features] - The input samples. + X : array-like or sparse matrix of shape = [n_samples, n_features] + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. Returns ------- - y: array of shape = [n_samples] or [n_samples, n_outputs] + y : array of shape = [n_samples] or [n_samples, n_outputs] The predicted values. """ + check_is_fitted(self, 'n_outputs_') + # Check data - if getattr(X, "dtype", None) != DTYPE or X.ndim != 2: - X = array2d(X, dtype=DTYPE) + X = check_array(X, dtype=DTYPE, accept_sparse="csr") # Assign chunk of trees to jobs - n_jobs, n_trees, starts = _partition_trees(self) + n_jobs, n_trees, starts = _partition_estimators(self.n_estimators, + self.n_jobs) # Parallel loop - all_y_hat = Parallel(n_jobs=n_jobs, verbose=self.verbose)( - delayed(_parallel_predict_regression)( - self.estimators_[starts[i]:starts[i + 1]], X) - for i in xrange(n_jobs)) + all_y_hat = Parallel(n_jobs=n_jobs, verbose=self.verbose, + backend="threading")( + delayed(_parallel_helper)(e, 'predict', X) + for e in self.estimators_) # Reduce - y_hat = sum(all_y_hat) / self.n_estimators + y_hat = sum(all_y_hat) / len(self.estimators_) return y_hat + def _set_oob_score(self, X, y): + """Compute out-of-bag scores""" + n_samples = y.shape[0] + + predictions = np.zeros((n_samples, self.n_outputs_)) + n_predictions = np.zeros((n_samples, self.n_outputs_)) + + sample_indices = np.arange(n_samples) + for estimator in self.estimators_: + mask = np.ones(n_samples, dtype=np.bool) + mask[estimator.indices_] = False + mask_indices = sample_indices[mask] + p_estimator = estimator.predict(X[mask_indices, :]) + + if self.n_outputs_ == 1: + p_estimator = p_estimator[:, np.newaxis] + + predictions[mask_indices, :] += p_estimator + n_predictions[mask_indices, :] += 1 + + if (n_predictions == 0).any(): + warn("Some inputs do not have OOB scores. " + "This probably means too few trees were used " + "to compute any reliable oob estimates.") + n_predictions[n_predictions == 0] = 1 + + predictions /= n_predictions + self.oob_prediction_ = predictions + + if self.n_outputs_ == 1: + self.oob_prediction_ = \ + self.oob_prediction_.reshape((n_samples, )) + + self.oob_score_ = 0.0 + + for k in range(self.n_outputs_): + self.oob_score_ += r2_score(y[:, k], + predictions[:, k]) + + self.oob_score_ /= self.n_outputs_ + class RandomForestClassifier(ForestClassifier): """A random forest classifier. - A random forest is a meta estimator that fits a number of classifical - decision trees on various sub-samples of the dataset and use averaging - to improve the predictive accuracy and control over-fitting. + A random forest is a meta estimator that fits a number of decision tree + classifiers on various sub-samples of the dataset and use averaging to + improve the predictive accuracy and control over-fitting. Parameters ---------- @@ -598,13 +689,31 @@ class RandomForestClassifier(ForestClassifier): "gini" for the Gini impurity and "entropy" for the information gain. Note: this parameter is tree-specific. + max_features : int, float, string or None, optional (default="auto") + The number of features to consider when looking for the best split: + + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a percentage and + `int(max_features * n_features)` features are considered at each + split. + - If "auto", then `max_features=sqrt(n_features)`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + Note: this parameter is tree-specific. + max_depth : integer or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. + Ignored if ``max_leaf_nodes`` is not None. Note: this parameter is tree-specific. - min_samples_split : integer, optional (default=1) + min_samples_split : integer, optional (default=2) The minimum number of samples required to split an internal node. Note: this parameter is tree-specific. @@ -614,42 +723,28 @@ class RandomForestClassifier(ForestClassifier): ``min_samples_leaf`` samples. Note: this parameter is tree-specific. - min_density : float, optional (default=0.1) - This parameter controls a trade-off in an optimization heuristic. It - controls the minimum density of the `sample_mask` (i.e. the - fraction of samples in the mask). If the density falls below this - threshold the mask is recomputed and the input data is packed - which results in data copying. If `min_density` equals to one, - the partitions are always represented as copies of the original - data. Otherwise, partitions are represented as bit masks (aka - sample masks). + min_weight_fraction_leaf : float, optional (default=0.) + The minimum weighted fraction of the input samples required to be at a + leaf node. Note: this parameter is tree-specific. - max_features : int, string or None, optional (default="auto") - The number of features to consider when looking for the best split: - - If "auto", then `max_features=sqrt(n_features)` on - classification tasks and `max_features=n_features` on regression - problems. - - If "sqrt", then `max_features=sqrt(n_features)`. - - If "log2", then `max_features=log2(n_features)`. - - If None, then `max_features=n_features`. - + max_leaf_nodes : int or None, optional (default=None) + Grow trees with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + If not None then ``max_depth`` will be ignored. Note: this parameter is tree-specific. bootstrap : boolean, optional (default=True) Whether bootstrap samples are used when building trees. - compute_importances : boolean, optional (default=True) - Whether feature importances are computed and stored into the - ``feature_importances_`` attribute when calling fit. - oob_score : bool Whether to use out-of-bag samples to estimate the generalization error. n_jobs : integer, optional (default=1) - The number of jobs to run in parallel. If -1, then the number of jobs - is set to the number of cores. + The number of jobs to run in parallel for both `fit` and `predict`. + If -1, then the number of jobs is set to the number of cores. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; @@ -658,23 +753,55 @@ class RandomForestClassifier(ForestClassifier): by `np.random`. verbose : int, optional (default=0) - Controlls the verbosity of the tree building process. + Controls the verbosity of the tree building process. + + warm_start : bool, optional (default=False) + When set to ``True``, reuse the solution of the previous call to fit + and add more estimators to the ensemble, otherwise, just fit a whole + new forest. + + class_weight : dict, list of dicts, "auto", "subsample" or None, optional + + Weights associated with classes in the form ``{class_label: weight}``. + If not given, all classes are supposed to have weight one. For + multi-output problems, a list of dicts can be provided in the same + order as the columns of y. + + The "auto" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data. + + The "subsample" mode is the same as "auto" except that weights are + computed based on the bootstrap sample for every tree grown. + + For multi-output, the weights of each column of y will be multiplied. + + Note that these weights will be multiplied with sample_weight (passed + through the fit method) if sample_weight is specified. Attributes ---------- - `estimators_`: list of DecisionTreeClassifier + estimators_ : list of DecisionTreeClassifier The collection of fitted sub-estimators. - `feature_importances_` : array, shape = [n_features] + classes_ : array of shape = [n_classes] or a list of such arrays + The classes labels (single output problem), or a list of arrays of + class labels (multi-output problem). + + n_classes_ : int or list + The number of classes (single output problem), or a list containing the + number of classes for each output (multi-output problem). + + feature_importances_ : array of shape = [n_features] The feature importances (the higher, the more important the feature). - `oob_score_` : float + oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. - `oob_decision_function_` : array, shape = [n_samples, n_classes] + oob_decision_function_ : array of shape = [n_samples, n_classes] Decision function computed with out-of-bag estimate on the training - set. - + set. If n_estimators is small it might be possible that a data point + was never left out during the bootstrap. In this case, + `oob_decision_function_` might contain NaN. References ---------- @@ -685,44 +812,50 @@ class RandomForestClassifier(ForestClassifier): -------- DecisionTreeClassifier, ExtraTreesClassifier """ - def __init__(self, n_estimators=10, - criterion="gini", - max_depth=None, - min_samples_split=1, - min_samples_leaf=1, - min_density=0.1, - max_features="auto", - bootstrap=True, - compute_importances=False, - oob_score=False, - n_jobs=1, - random_state=None, - verbose=0): + def __init__(self, + n_estimators=10, + criterion="gini", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0., + max_features="auto", + max_leaf_nodes=None, + bootstrap=True, + oob_score=False, + n_jobs=1, + random_state=None, + verbose=0, + warm_start=False, + class_weight=None): super(RandomForestClassifier, self).__init__( base_estimator=DecisionTreeClassifier(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", - "min_samples_leaf", "min_density", "max_features", - "random_state"), + "min_samples_leaf", "min_weight_fraction_leaf", + "max_features", "max_leaf_nodes", + "random_state"), bootstrap=bootstrap, - compute_importances=compute_importances, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, - verbose=verbose) + verbose=verbose, + warm_start=warm_start, + class_weight=class_weight) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf - self.min_density = min_density + self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features + self.max_leaf_nodes = max_leaf_nodes class RandomForestRegressor(ForestRegressor): """A random forest regressor. - A random forest is a meta estimator that fits a number of classifical + A random forest is a meta estimator that fits a number of classifying decision trees on various sub-samples of the dataset and use averaging to improve the predictive accuracy and control over-fitting. @@ -736,13 +869,31 @@ class RandomForestRegressor(ForestRegressor): criterion is "mse" for the mean squared error. Note: this parameter is tree-specific. + max_features : int, float, string or None, optional (default="auto") + The number of features to consider when looking for the best split: + + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a percentage and + `int(max_features * n_features)` features are considered at each + split. + - If "auto", then `max_features=n_features`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + Note: this parameter is tree-specific. + max_depth : integer or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. + Ignored if ``max_leaf_nodes`` is not None. Note: this parameter is tree-specific. - min_samples_split : integer, optional (default=1) + min_samples_split : integer, optional (default=2) The minimum number of samples required to split an internal node. Note: this parameter is tree-specific. @@ -752,42 +903,28 @@ class RandomForestRegressor(ForestRegressor): ``min_samples_leaf`` samples. Note: this parameter is tree-specific. - min_density : float, optional (default=0.1) - This parameter controls a trade-off in an optimization heuristic. It - controls the minimum density of the `sample_mask` (i.e. the - fraction of samples in the mask). If the density falls below this - threshold the mask is recomputed and the input data is packed - which results in data copying. If `min_density` equals to one, - the partitions are always represented as copies of the original - data. Otherwise, partitions are represented as bit masks (aka - sample masks). + min_weight_fraction_leaf : float, optional (default=0.) + The minimum weighted fraction of the input samples required to be at a + leaf node. Note: this parameter is tree-specific. - max_features : int, string or None, optional (default="auto") - The number of features to consider when looking for the best split: - - If "auto", then `max_features=sqrt(n_features)` on - classification tasks and `max_features=n_features` - on regression problems. - - If "sqrt", then `max_features=sqrt(n_features)`. - - If "log2", then `max_features=log2(n_features)`. - - If None, then `max_features=n_features`. - + max_leaf_nodes : int or None, optional (default=None) + Grow trees with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + If not None then ``max_depth`` will be ignored. Note: this parameter is tree-specific. bootstrap : boolean, optional (default=True) Whether bootstrap samples are used when building trees. - compute_importances : boolean, optional (default=True) - Whether feature importances are computed and stored into the - ``feature_importances_`` attribute when calling fit. - oob_score : bool whether to use out-of-bag samples to estimate the generalization error. n_jobs : integer, optional (default=1) - The number of jobs to run in parallel. If -1, then the number of jobs - is set to the number of cores. + The number of jobs to run in parallel for both `fit` and `predict`. + If -1, then the number of jobs is set to the number of cores. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; @@ -796,24 +933,27 @@ class RandomForestRegressor(ForestRegressor): by `np.random`. verbose : int, optional (default=0) - Controlls the verbosity of the tree building process. + Controls the verbosity of the tree building process. + + warm_start : bool, optional (default=False) + When set to ``True``, reuse the solution of the previous call to fit + and add more estimators to the ensemble, otherwise, just fit a whole + new forest. Attributes ---------- - `estimators_`: list of DecisionTreeRegressor + estimators_ : list of DecisionTreeRegressor The collection of fitted sub-estimators. - `feature_importances_` : array of shape = [n_features] - The feature mportances (the higher, the more important the feature). + feature_importances_ : array of shape = [n_features] + The feature importances (the higher, the more important the feature). - `oob_score_` : float + oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. - `oob_prediction_` : array, shape = [n_samples] + oob_prediction_ : array of shape = [n_samples] Prediction computed with out-of-bag estimate on the training set. - - References ---------- @@ -823,38 +963,42 @@ class RandomForestRegressor(ForestRegressor): -------- DecisionTreeRegressor, ExtraTreesRegressor """ - def __init__(self, n_estimators=10, - criterion="mse", - max_depth=None, - min_samples_split=1, - min_samples_leaf=1, - min_density=0.1, - max_features="auto", - bootstrap=True, - compute_importances=False, - oob_score=False, - n_jobs=1, - random_state=None, - verbose=0): + def __init__(self, + n_estimators=10, + criterion="mse", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0., + max_features="auto", + max_leaf_nodes=None, + bootstrap=True, + oob_score=False, + n_jobs=1, + random_state=None, + verbose=0, + warm_start=False): super(RandomForestRegressor, self).__init__( base_estimator=DecisionTreeRegressor(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", - "min_samples_leaf", "min_density", "max_features", - "random_state"), + "min_samples_leaf", "min_weight_fraction_leaf", + "max_features", "max_leaf_nodes", + "random_state"), bootstrap=bootstrap, - compute_importances=compute_importances, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, - verbose=verbose) + verbose=verbose, + warm_start=warm_start) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf - self.min_density = min_density + self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features + self.max_leaf_nodes = max_leaf_nodes class ExtraTreesClassifier(ForestClassifier): @@ -875,13 +1019,31 @@ class ExtraTreesClassifier(ForestClassifier): "gini" for the Gini impurity and "entropy" for the information gain. Note: this parameter is tree-specific. + max_features : int, float, string or None, optional (default="auto") + The number of features to consider when looking for the best split: + + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a percentage and + `int(max_features * n_features)` features are considered at each + split. + - If "auto", then `max_features=sqrt(n_features)`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + Note: this parameter is tree-specific. + max_depth : integer or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. + Ignored if ``max_leaf_nodes`` is not None. Note: this parameter is tree-specific. - min_samples_split : integer, optional (default=1) + min_samples_split : integer, optional (default=2) The minimum number of samples required to split an internal node. Note: this parameter is tree-specific. @@ -891,42 +1053,28 @@ class ExtraTreesClassifier(ForestClassifier): ``min_samples_leaf`` samples. Note: this parameter is tree-specific. - min_density : float, optional (default=0.1) - This parameter controls a trade-off in an optimization heuristic. It - controls the minimum density of the `sample_mask` (i.e. the - fraction of samples in the mask). If the density falls below this - threshold the mask is recomputed and the input data is packed - which results in data copying. If `min_density` equals to one, - the partitions are always represented as copies of the original - data. Otherwise, partitions are represented as bit masks (aka - sample masks). + min_weight_fraction_leaf : float, optional (default=0.) + The minimum weighted fraction of the input samples required to be at a + leaf node. Note: this parameter is tree-specific. - max_features : int, string or None, optional (default="auto") - The number of features to consider when looking for the best split. - - If "auto", then `max_features=sqrt(n_features)` on - classification tasks and `max_features=n_features` - on regression problems. - - If "sqrt", then `max_features=sqrt(n_features)`. - - If "log2", then `max_features=log2(n_features)`. - - If None, then `max_features=n_features`. - + max_leaf_nodes : int or None, optional (default=None) + Grow trees with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + If not None then ``max_depth`` will be ignored. Note: this parameter is tree-specific. bootstrap : boolean, optional (default=False) Whether bootstrap samples are used when building trees. - compute_importances : boolean, optional (default=True) - Whether feature importances are computed and stored into the - ``feature_importances_`` attribute when calling fit. - oob_score : bool Whether to use out-of-bag samples to estimate the generalization error. n_jobs : integer, optional (default=1) - The number of jobs to run in parallel. If -1, then the number of jobs - is set to the number of cores. + The number of jobs to run in parallel for both `fit` and `predict`. + If -1, then the number of jobs is set to the number of cores. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; @@ -935,22 +1083,55 @@ class ExtraTreesClassifier(ForestClassifier): by `np.random`. verbose : int, optional (default=0) - Controlls the verbosity of the tree building process. + Controls the verbosity of the tree building process. + + warm_start : bool, optional (default=False) + When set to ``True``, reuse the solution of the previous call to fit + and add more estimators to the ensemble, otherwise, just fit a whole + new forest. + + class_weight : dict, list of dicts, "auto", "subsample" or None, optional + + Weights associated with classes in the form ``{class_label: weight}``. + If not given, all classes are supposed to have weight one. For + multi-output problems, a list of dicts can be provided in the same + order as the columns of y. + + The "auto" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data. + + The "subsample" mode is the same as "auto" except that weights are + computed based on the bootstrap sample for every tree grown. + + For multi-output, the weights of each column of y will be multiplied. + + Note that these weights will be multiplied with sample_weight (passed + through the fit method) if sample_weight is specified. Attributes ---------- - `estimators_`: list of DecisionTreeClassifier + estimators_ : list of DecisionTreeClassifier The collection of fitted sub-estimators. - `feature_importances_` : array of shape = [n_features] - The feature mportances (the higher, the more important the feature). + classes_ : array of shape = [n_classes] or a list of such arrays + The classes labels (single output problem), or a list of arrays of + class labels (multi-output problem). + + n_classes_ : int or list + The number of classes (single output problem), or a list containing the + number of classes for each output (multi-output problem). + + feature_importances_ : array of shape = [n_features] + The feature importances (the higher, the more important the feature). - `oob_score_` : float + oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. - `oob_decision_function_` : array, shape = [n_samples, n_classes] + oob_decision_function_ : array of shape = [n_samples, n_classes] Decision function computed with out-of-bag estimate on the training - set. + set. If n_estimators is small it might be possible that a data point + was never left out during the bootstrap. In this case, + `oob_decision_function_` might contain NaN. References ---------- @@ -964,38 +1145,43 @@ class ExtraTreesClassifier(ForestClassifier): RandomForestClassifier : Ensemble Classifier based on trees with optimal splits. """ - def __init__(self, n_estimators=10, - criterion="gini", - max_depth=None, - min_samples_split=1, - min_samples_leaf=1, - min_density=0.1, - max_features="auto", - bootstrap=False, - compute_importances=False, - oob_score=False, - n_jobs=1, - random_state=None, - verbose=0): + def __init__(self, + n_estimators=10, + criterion="gini", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0., + max_features="auto", + max_leaf_nodes=None, + bootstrap=False, + oob_score=False, + n_jobs=1, + random_state=None, + verbose=0, + warm_start=False, + class_weight=None): super(ExtraTreesClassifier, self).__init__( base_estimator=ExtraTreeClassifier(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", - "min_samples_leaf", "min_density", "max_features", - "random_state"), + "min_samples_leaf", "min_weight_fraction_leaf", + "max_features", "max_leaf_nodes", "random_state"), bootstrap=bootstrap, - compute_importances=compute_importances, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, - verbose=verbose) + verbose=verbose, + warm_start=warm_start, + class_weight=class_weight) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf - self.min_density = min_density + self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features + self.max_leaf_nodes = max_leaf_nodes class ExtraTreesRegressor(ForestRegressor): @@ -1016,13 +1202,31 @@ class ExtraTreesRegressor(ForestRegressor): criterion is "mse" for the mean squared error. Note: this parameter is tree-specific. + max_features : int, float, string or None, optional (default="auto") + The number of features to consider when looking for the best split: + + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a percentage and + `int(max_features * n_features)` features are considered at each + split. + - If "auto", then `max_features=n_features`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + Note: this parameter is tree-specific. + max_depth : integer or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. + Ignored if ``max_leaf_nodes`` is not None. Note: this parameter is tree-specific. - min_samples_split : integer, optional (default=1) + min_samples_split : integer, optional (default=2) The minimum number of samples required to split an internal node. Note: this parameter is tree-specific. @@ -1032,43 +1236,29 @@ class ExtraTreesRegressor(ForestRegressor): ``min_samples_leaf`` samples. Note: this parameter is tree-specific. - min_density : float, optional (default=0.1) - This parameter controls a trade-off in an optimization heuristic. It - controls the minimum density of the `sample_mask` (i.e. the - fraction of samples in the mask). If the density falls below this - threshold the mask is recomputed and the input data is packed - which results in data copying. If `min_density` equals to one, - the partitions are always represented as copies of the original - data. Otherwise, partitions are represented as bit masks (aka - sample masks). + min_weight_fraction_leaf : float, optional (default=0.) + The minimum weighted fraction of the input samples required to be at a + leaf node. Note: this parameter is tree-specific. - max_features : int, string or None, optional (default="auto") - The number of features to consider when looking for the best split: - - If "auto", then `max_features=sqrt(n_features)` on - classification tasks and `max_features=n_features` - on regression problems. - - If "sqrt", then `max_features=sqrt(n_features)`. - - If "log2", then `max_features=log2(n_features)`. - - If None, then `max_features=n_features`. - + max_leaf_nodes : int or None, optional (default=None) + Grow trees with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + If not None then ``max_depth`` will be ignored. Note: this parameter is tree-specific. bootstrap : boolean, optional (default=False) Whether bootstrap samples are used when building trees. Note: this parameter is tree-specific. - compute_importances : boolean, optional (default=True) - Whether feature importances are computed and stored into the - ``feature_importances_`` attribute when calling fit. - oob_score : bool Whether to use out-of-bag samples to estimate the generalization error. n_jobs : integer, optional (default=1) - The number of jobs to run in parallel. If -1, then the number of jobs - is set to the number of cores. + The number of jobs to run in parallel for both `fit` and `predict`. + If -1, then the number of jobs is set to the number of cores. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; @@ -1077,20 +1267,25 @@ class ExtraTreesRegressor(ForestRegressor): by `np.random`. verbose : int, optional (default=0) - Controlls the verbosity of the tree building process. + Controls the verbosity of the tree building process. + + warm_start : bool, optional (default=False) + When set to ``True``, reuse the solution of the previous call to fit + and add more estimators to the ensemble, otherwise, just fit a whole + new forest. Attributes ---------- - `estimators_`: list of DecisionTreeRegressor + estimators_ : list of DecisionTreeRegressor The collection of fitted sub-estimators. - `feature_importances_` : array of shape = [n_features] - The feature mportances (the higher, the more important the feature). + feature_importances_ : array of shape = [n_features] + The feature importances (the higher, the more important the feature). - `oob_score_` : float + oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. - `oob_prediction_` : array, shape = [n_samples] + oob_prediction_ : array of shape = [n_samples] Prediction computed with out-of-bag estimate on the training set. References @@ -1104,35 +1299,223 @@ class ExtraTreesRegressor(ForestRegressor): sklearn.tree.ExtraTreeRegressor: Base estimator for this ensemble. RandomForestRegressor: Ensemble regressor using trees with optimal splits. """ - def __init__(self, n_estimators=10, - criterion="mse", - max_depth=None, - min_samples_split=1, - min_samples_leaf=1, - min_density=0.1, - max_features="auto", - bootstrap=False, - compute_importances=False, - oob_score=False, - n_jobs=1, - random_state=None, - verbose=0): + def __init__(self, + n_estimators=10, + criterion="mse", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0., + max_features="auto", + max_leaf_nodes=None, + bootstrap=False, + oob_score=False, + n_jobs=1, + random_state=None, + verbose=0, + warm_start=False): super(ExtraTreesRegressor, self).__init__( base_estimator=ExtraTreeRegressor(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", - "min_samples_leaf", "min_density", "max_features", - "random_state"), + "min_samples_leaf", "min_weight_fraction_leaf", + "max_features", "max_leaf_nodes", + "random_state"), bootstrap=bootstrap, - compute_importances=compute_importances, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, - verbose=verbose) + verbose=verbose, + warm_start=warm_start) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf - self.min_density = min_density + self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features + self.max_leaf_nodes = max_leaf_nodes + + +class RandomTreesEmbedding(BaseForest): + """An ensemble of totally random trees. + + An unsupervised transformation of a dataset to a high-dimensional + sparse representation. A datapoint is coded according to which leaf of + each tree it is sorted into. Using a one-hot encoding of the leaves, + this leads to a binary coding with as many ones as there are trees in + the forest. + + The dimensionality of the resulting representation is + ``n_out <= n_estimators * max_leaf_nodes``. If ``max_leaf_nodes == None``, + the number of leaf nodes is at most ``n_estimators * 2 ** max_depth``. + + Parameters + ---------- + n_estimators : int + Number of trees in the forest. + + max_depth : int + The maximum depth of each tree. If None, then nodes are expanded until + all leaves are pure or until all leaves contain less than + min_samples_split samples. + Ignored if ``max_leaf_nodes`` is not None. + + min_samples_split : integer, optional (default=2) + The minimum number of samples required to split an internal node. + + min_samples_leaf : integer, optional (default=1) + The minimum number of samples in newly created leaves. A split is + discarded if after the split, one of the leaves would contain less then + ``min_samples_leaf`` samples. + + min_weight_fraction_leaf : float, optional (default=0.) + The minimum weighted fraction of the input samples required to be at a + leaf node. + + max_leaf_nodes : int or None, optional (default=None) + Grow trees with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + If not None then ``max_depth`` will be ignored. + + sparse_output : bool, optional (default=True) + Whether or not to return a sparse CSR matrix, as default behavior, + or to return a dense array compatible with dense pipeline operators. + + n_jobs : integer, optional (default=1) + The number of jobs to run in parallel for both `fit` and `predict`. + If -1, then the number of jobs is set to the number of cores. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + verbose : int, optional (default=0) + Controls the verbosity of the tree building process. + + warm_start : bool, optional (default=False) + When set to ``True``, reuse the solution of the previous call to fit + and add more estimators to the ensemble, otherwise, just fit a whole + new forest. + + Attributes + ---------- + estimators_ : list of DecisionTreeClassifier + The collection of fitted sub-estimators. + + References + ---------- + .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", + Machine Learning, 63(1), 3-42, 2006. + .. [2] Moosmann, F. and Triggs, B. and Jurie, F. "Fast discriminative + visual codebooks using randomized clustering forests" + NIPS 2007 + + """ + + def __init__(self, + n_estimators=10, + max_depth=5, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0., + max_leaf_nodes=None, + sparse_output=True, + n_jobs=1, + random_state=None, + verbose=0, + warm_start=False): + super(RandomTreesEmbedding, self).__init__( + base_estimator=ExtraTreeRegressor(), + n_estimators=n_estimators, + estimator_params=("criterion", "max_depth", "min_samples_split", + "min_samples_leaf", "min_weight_fraction_leaf", + "max_features", "max_leaf_nodes", + "random_state"), + bootstrap=False, + oob_score=False, + n_jobs=n_jobs, + random_state=random_state, + verbose=verbose, + warm_start=warm_start) + + self.criterion = 'mse' + self.max_depth = max_depth + self.min_samples_split = min_samples_split + self.min_samples_leaf = min_samples_leaf + self.min_weight_fraction_leaf = min_weight_fraction_leaf + self.max_features = 1 + self.max_leaf_nodes = max_leaf_nodes + self.sparse_output = sparse_output + + def _set_oob_score(self, X, y): + raise NotImplementedError("OOB score not supported by tree embedding") + + def fit(self, X, y=None, sample_weight=None): + """Fit estimator. + + Parameters + ---------- + X : array-like or sparse matrix, shape=(n_samples, n_features) + The input samples. Use ``dtype=np.float32`` for maximum + efficiency. Sparse matrices are also supported, use sparse + ``csc_matrix`` for maximum efficiency. + + Returns + ------- + self : object + Returns self. + + """ + self.fit_transform(X, y, sample_weight=sample_weight) + return self + + def fit_transform(self, X, y=None, sample_weight=None): + """Fit estimator and transform dataset. + + Parameters + ---------- + X : array-like or sparse matrix, shape=(n_samples, n_features) + Input data used to build forests. Use ``dtype=np.float32`` for + maximum efficiency. + + Returns + ------- + X_transformed : sparse matrix, shape=(n_samples, n_out) + Transformed dataset. + """ + # ensure_2d=False because there are actually unit test checking we fail + # for 1d. + X = check_array(X, accept_sparse=['csc'], ensure_2d=False) + if issparse(X): + # Pre-sort indices to avoid that each individual tree of the + # ensemble sorts the indices. + X.sort_indices() + + rnd = check_random_state(self.random_state) + y = rnd.uniform(size=X.shape[0]) + super(RandomTreesEmbedding, self).fit(X, y, + sample_weight=sample_weight) + + self.one_hot_encoder_ = OneHotEncoder(sparse=self.sparse_output) + return self.one_hot_encoder_.fit_transform(self.apply(X)) + + def transform(self, X): + """Transform dataset. + + Parameters + ---------- + X : array-like or sparse matrix, shape=(n_samples, n_features) + Input data to be transformed. Use ``dtype=np.float32`` for maximum + efficiency. Sparse matrices are also supported, use sparse + ``csr_matrix`` for maximum efficiency. + + Returns + ------- + X_transformed : sparse matrix, shape=(n_samples, n_out) + Transformed dataset. + """ + return self.one_hot_encoder_.transform(self.apply(X)) diff --git a/sklearn/ensemble/gradient_boosting.py b/sklearn/ensemble/gradient_boosting.py index 2bd14f0e80551..1e107190beff9 100644 --- a/sklearn/ensemble/gradient_boosting.py +++ b/sklearn/ensemble/gradient_boosting.py @@ -7,7 +7,7 @@ - The ``BaseGradientBoosting`` base class implements a common ``fit`` method for all the estimators in the module. Regression and classification - only differ the the concrete ``LossFunction`` used. + only differ in the concrete ``LossFunction`` used. - ``GradientBoostingClassifier`` implements gradient boosting for classification problems. @@ -16,12 +16,16 @@ regression problems. """ -# Authors: Peter Prettenhofer, Scott White, Gilles Louppe -# License: BSD Style. +# Authors: Peter Prettenhofer, Scott White, Gilles Louppe, Emanuele Olivetti, +# Arnaud Joly +# License: BSD 3 clause +from __future__ import print_function from __future__ import division from abc import ABCMeta, abstractmethod +from time import time +import numbers import numpy as np from scipy import stats @@ -30,28 +34,41 @@ from ..base import BaseEstimator from ..base import ClassifierMixin from ..base import RegressorMixin -from ..utils import check_random_state, array2d, check_arrays - -from ..tree._tree import Tree -from ..tree._tree import _random_sample_mask -from ..tree._tree import MSE -from ..tree._tree import DTYPE, TREE_LEAF, TREE_SPLIT_BEST +from ..utils import check_random_state, check_array, check_X_y, column_or_1d +from ..utils import check_consistent_length +from ..utils.extmath import logsumexp +from ..utils.fixes import expit, bincount +from ..utils.stats import _weighted_percentile +from ..utils.validation import check_is_fitted, NotFittedError +from ..externals import six +from ..feature_selection.from_model import _LearntSelectorMixin + +from ..tree.tree import DecisionTreeRegressor +from ..tree._tree import DTYPE, TREE_LEAF +from ..tree._tree import PresortBestSplitter +from ..tree._tree import FriedmanMSE from ._gradient_boosting import predict_stages from ._gradient_boosting import predict_stage +from ._gradient_boosting import _random_sample_mask class QuantileEstimator(BaseEstimator): """An estimator predicting the alpha-quantile of the training targets.""" def __init__(self, alpha=0.9): if not 0 < alpha < 1.0: - raise ValueError("`alpha` must be in (0, 1.0)") + raise ValueError("`alpha` must be in (0, 1.0) but was %r" % alpha) self.alpha = alpha - def fit(self, X, y): - self.quantile = stats.scoreatpercentile(y, self.alpha * 100.0) + def fit(self, X, y, sample_weight=None): + if sample_weight is None: + self.quantile = stats.scoreatpercentile(y, self.alpha * 100.0) + else: + self.quantile = _weighted_percentile(y, sample_weight, self.alpha * 100.0) def predict(self, X): + check_is_fitted(self, 'quantile') + y = np.empty((X.shape[0], 1), dtype=np.float64) y.fill(self.quantile) return y @@ -59,10 +76,15 @@ def predict(self, X): class MeanEstimator(BaseEstimator): """An estimator predicting the mean of the training targets.""" - def fit(self, X, y): - self.mean = np.mean(y) + def fit(self, X, y, sample_weight=None): + if sample_weight is None: + self.mean = np.mean(y) + else: + self.mean = np.average(y, weights=sample_weight) def predict(self, X): + check_is_fitted(self, 'mean') + y = np.empty((X.shape[0], 1), dtype=np.float64) y.fill(self.mean) return y @@ -70,31 +92,74 @@ def predict(self, X): class LogOddsEstimator(BaseEstimator): """An estimator predicting the log odds ratio.""" - def fit(self, X, y): - n_pos = np.sum(y) - self.prior = np.log(n_pos / (y.shape[0] - n_pos)) + scale = 1.0 + + def fit(self, X, y, sample_weight=None): + # pre-cond: pos, neg are encoded as 1, 0 + if sample_weight is None: + pos = np.sum(y) + neg = y.shape[0] - pos + else: + pos = np.sum(sample_weight * y) + neg = np.sum(sample_weight * (1 - y)) + + if neg == 0 or pos == 0: + raise ValueError('y contains non binary labels.') + self.prior = self.scale * np.log(pos / neg) def predict(self, X): + check_is_fitted(self, 'prior') + y = np.empty((X.shape[0], 1), dtype=np.float64) y.fill(self.prior) return y +class ScaledLogOddsEstimator(LogOddsEstimator): + """Log odds ratio scaled by 0.5 -- for exponential loss. """ + scale = 0.5 + + class PriorProbabilityEstimator(BaseEstimator): """An estimator predicting the probability of each class in the training data. """ - def fit(self, X, y): - class_counts = np.bincount(y) - self.priors = class_counts / float(y.shape[0]) + def fit(self, X, y, sample_weight=None): + if sample_weight is None: + sample_weight = np.ones_like(y, dtype=np.float64) + class_counts = bincount(y, weights=sample_weight) + self.priors = class_counts / class_counts.sum() def predict(self, X): + check_is_fitted(self, 'priors') + y = np.empty((X.shape[0], self.priors.shape[0]), dtype=np.float64) y[:] = self.priors return y -class LossFunction(object): +class ZeroEstimator(BaseEstimator): + """An estimator that simply predicts zero. """ + + def fit(self, X, y, sample_weight=None): + if np.issubdtype(y.dtype, int): + # classification + self.n_classes = np.unique(y).shape[0] + if self.n_classes == 2: + self.n_classes = 1 + else: + # regression + self.n_classes = 1 + + def predict(self, X): + check_is_fitted(self, 'n_classes') + + y = np.empty((X.shape[0], self.n_classes), dtype=np.float64) + y.fill(0.0) + return y + + +class LossFunction(six.with_metaclass(ABCMeta, object)): """Abstract base class for various loss functions. Attributes @@ -104,18 +169,18 @@ class LossFunction(object): 1 for regression and binary classification; ``n_classes`` for multi-class classification. """ - __metaclass__ = ABCMeta is_multi_class = False def __init__(self, n_classes): self.K = n_classes - def init_estimator(self, X, y): + def init_estimator(self): + """Default ``init`` estimator for loss function. """ raise NotImplementedError() @abstractmethod - def __call__(self, y, pred): + def __call__(self, y, pred, sample_weight=None): """Compute the loss of prediction ``pred`` and ``y``. """ @abstractmethod @@ -131,7 +196,8 @@ def negative_gradient(self, y, y_pred, **kargs): """ def update_terminal_regions(self, tree, X, y, residual, y_pred, - sample_mask, learn_rate=1.0, k=0): + sample_weight, sample_mask, + learning_rate=1.0, k=0): """Update the terminal regions (=leaves) of the given tree and updates the current predictions of the model. Traverses tree and invokes template method `_update_terminal_region`. @@ -140,14 +206,24 @@ def update_terminal_regions(self, tree, X, y, residual, y_pred, ---------- tree : tree.Tree The tree object. - X : np.ndarray, shape=(n, m) + X : ndarray, shape=(n, m) The data array. - y : np.ndarray, shape=(n,) + y : ndarray, shape=(n,) The target labels. - residual : np.ndarray, shape=(n,) + residual : ndarray, shape=(n,) The residuals (usually the negative gradient). - y_pred : np.ndarray, shape=(n,): + y_pred : ndarray, shape=(n,) The predictions. + sample_weight : ndarray, shape=(n,) + The weight of each sample. + sample_mask : ndarray, shape=(n,) + The sample mask to be used. + learning_rate : float, default=0.1 + learning rate shrinks the contribution of each tree by + ``learning_rate``. + k : int, default 0 + The index of the estimator being updated. + """ # compute leaf for each sample in ``X``. terminal_regions = tree.apply(X) @@ -160,25 +236,25 @@ def update_terminal_regions(self, tree, X, y, residual, y_pred, for leaf in np.where(tree.children_left == TREE_LEAF)[0]: self._update_terminal_region(tree, masked_terminal_regions, leaf, X, y, residual, - y_pred[:, k]) + y_pred[:, k], sample_weight) # update predictions (both in-bag and out-of-bag) - y_pred[:, k] += learn_rate * tree.value[:, 0, 0].take(terminal_regions, - axis=0) + y_pred[:, k] += (learning_rate + * tree.value[:, 0, 0].take(terminal_regions, axis=0)) @abstractmethod def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, - residual, pred): + residual, pred, sample_weight): """Template method for updating terminal regions (=leaves). """ -class RegressionLossFunction(LossFunction): +class RegressionLossFunction(six.with_metaclass(ABCMeta, LossFunction)): """Base class for regression loss functions. """ - __metaclass__ = ABCMeta def __init__(self, n_classes): if n_classes != 1: - raise ValueError("``n_classes`` must be 1 for regression") + raise ValueError("``n_classes`` must be 1 for regression but " + "was %r" % n_classes) super(RegressionLossFunction, self).__init__(n_classes) @@ -188,23 +264,28 @@ class LeastSquaresError(RegressionLossFunction): def init_estimator(self): return MeanEstimator() - def __call__(self, y, pred): - return np.mean((y - pred.ravel()) ** 2.0) + def __call__(self, y, pred, sample_weight=None): + if sample_weight is None: + return np.mean((y - pred.ravel()) ** 2.0) + else: + return (1.0 / sample_weight.sum() * + np.sum(sample_weight * ((y - pred.ravel()) ** 2.0))) def negative_gradient(self, y, pred, **kargs): return y - pred.ravel() def update_terminal_regions(self, tree, X, y, residual, y_pred, - sample_mask, learn_rate=1.0, k=0): + sample_weight, sample_mask, + learning_rate=1.0, k=0): """Least squares does not need to update terminal regions. But it has to update the predictions. """ # update predictions - y_pred[:, k] += learn_rate * tree.predict(X).ravel() + y_pred[:, k] += learning_rate * tree.predict(X).ravel() def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, - residual, pred): + residual, pred, sample_weight): pass @@ -213,8 +294,12 @@ class LeastAbsoluteError(RegressionLossFunction): def init_estimator(self): return QuantileEstimator(alpha=0.5) - def __call__(self, y, pred): - return np.abs(y - pred.ravel()).mean() + def __call__(self, y, pred, sample_weight=None): + if sample_weight is None: + return np.abs(y - pred.ravel()).mean() + else: + return (1.0 / sample_weight.sum() * + np.sum(sample_weight * np.abs(y - pred.ravel()))) def negative_gradient(self, y, pred, **kargs): """1.0 if y - pred > 0.0 else -1.0""" @@ -222,36 +307,62 @@ def negative_gradient(self, y, pred, **kargs): return 2.0 * (y - pred > 0.0) - 1.0 def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, - residual, pred): + residual, pred, sample_weight): """LAD updates terminal regions to median estimates. """ terminal_region = np.where(terminal_regions == leaf)[0] - tree.value[leaf, 0, 0] = np.median(y.take(terminal_region, axis=0) - \ - pred.take(terminal_region, axis=0)) + sample_weight = sample_weight.take(terminal_region, axis=0) + diff = y.take(terminal_region, axis=0) - pred.take(terminal_region, axis=0) + tree.value[leaf, 0, 0] = _weighted_percentile(diff, sample_weight, percentile=50) class HuberLossFunction(RegressionLossFunction): - """Loss function for least absolute deviation (LAD) regression. """ + """Huber loss function for robust regression. + + M-Regression proposed in Friedman 2001. + + References + ---------- + J. Friedman, Greedy Function Approximation: A Gradient Boosting + Machine, The Annals of Statistics, Vol. 29, No. 5, 2001. + """ def __init__(self, n_classes, alpha=0.9): super(HuberLossFunction, self).__init__(n_classes) self.alpha = alpha + self.gamma = None def init_estimator(self): return QuantileEstimator(alpha=0.5) - def __call__(self, y, pred): + def __call__(self, y, pred, sample_weight=None): pred = pred.ravel() diff = y - pred gamma = self.gamma + if gamma is None: + if sample_weight is None: + gamma = stats.scoreatpercentile(np.abs(diff), self.alpha * 100) + else: + gamma = _weighted_percentile(np.abs(diff), sample_weight, self.alpha * 100) + gamma_mask = np.abs(diff) <= gamma - sq_loss = np.sum(0.5 * diff[gamma_mask] ** 2.0) - lin_loss = np.sum(gamma * (np.abs(diff[~gamma_mask]) - gamma / 2.0)) - return (sq_loss + lin_loss) / y.shape[0] + if sample_weight is None: + sq_loss = np.sum(0.5 * diff[gamma_mask] ** 2.0) + lin_loss = np.sum(gamma * (np.abs(diff[~gamma_mask]) - gamma / 2.0)) + loss = (sq_loss + lin_loss) / y.shape[0] + else: + sq_loss = np.sum(0.5 * sample_weight[gamma_mask] * diff[gamma_mask] ** 2.0) + lin_loss = np.sum(gamma * sample_weight[~gamma_mask] * + (np.abs(diff[~gamma_mask]) - gamma / 2.0)) + loss = (sq_loss + lin_loss) / sample_weight.sum() + return loss - def negative_gradient(self, y, pred, **kargs): + def negative_gradient(self, y, pred, sample_weight=None, **kargs): pred = pred.ravel() diff = y - pred - gamma = stats.scoreatpercentile(np.abs(diff), self.alpha * 100) + if sample_weight is None: + gamma = stats.scoreatpercentile(np.abs(diff), self.alpha * 100) + else: + gamma = _weighted_percentile(np.abs(diff), sample_weight, self.alpha * 100) gamma_mask = np.abs(diff) <= gamma residual = np.zeros((y.shape[0],), dtype=np.float64) residual[gamma_mask] = diff[gamma_mask] @@ -260,13 +371,13 @@ def negative_gradient(self, y, pred, **kargs): return residual def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, - residual, pred): - """LAD updates terminal regions to median estimates. """ + residual, pred, sample_weight): terminal_region = np.where(terminal_regions == leaf)[0] + sample_weight = sample_weight.take(terminal_region, axis=0) gamma = self.gamma - diff = y.take(terminal_region, axis=0) - \ - pred.take(terminal_region, axis=0) - median = np.median(diff) + diff = (y.take(terminal_region, axis=0) + - pred.take(terminal_region, axis=0)) + median = _weighted_percentile(diff, sample_weight, percentile=50) diff_minus_median = diff - median tree.value[leaf, 0] = median + np.mean( np.sign(diff_minus_median) * @@ -289,14 +400,20 @@ def __init__(self, n_classes, alpha=0.9): def init_estimator(self): return QuantileEstimator(self.alpha) - def __call__(self, y, pred): + def __call__(self, y, pred, sample_weight=None): pred = pred.ravel() diff = y - pred alpha = self.alpha mask = y > pred - return (alpha * diff[mask].sum() + - (1.0 - alpha) * diff[~mask].sum()) / y.shape[0] + if sample_weight is None: + loss = (alpha * diff[mask].sum() + + (1.0 - alpha) * diff[~mask].sum()) / y.shape[0] + else: + loss = ((alpha * np.sum(sample_weight[mask] * diff[mask]) + + (1.0 - alpha) * np.sum(sample_weight[~mask] * diff[~mask])) / + sample_weight.sum()) + return loss def negative_gradient(self, y, pred, **kargs): alpha = self.alpha @@ -305,16 +422,35 @@ def negative_gradient(self, y, pred, **kargs): return (alpha * mask) - ((1.0 - alpha) * ~mask) def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, - residual, pred): - """LAD updates terminal regions to median estimates. """ + residual, pred, sample_weight): terminal_region = np.where(terminal_regions == leaf)[0] - diff = y.take(terminal_region, axis=0) - \ - pred.take(terminal_region, axis=0) - val = stats.scoreatpercentile(diff, self.percentile) + diff = (y.take(terminal_region, axis=0) + - pred.take(terminal_region, axis=0)) + sample_weight = sample_weight.take(terminal_region, axis=0) + + val = _weighted_percentile(diff, sample_weight, self.percentile) tree.value[leaf, 0] = val -class BinomialDeviance(LossFunction): +class ClassificationLossFunction(six.with_metaclass(ABCMeta, LossFunction)): + """Base class for classification loss functions. """ + + def _score_to_proba(self, score): + """Template method to convert scores to probabilities. + + If the loss does not support probabilites raises AttributeError. + """ + raise TypeError('%s does not support predict_proba' % type(self).__name__) + + @abstractmethod + def _score_to_decision(self, score): + """Template method to convert scores to decisions. + + Returns int arrays. + """ + + +class BinomialDeviance(ClassificationLossFunction): """Binomial deviance loss function for binary classification. Binary classification is a special case; here, we only need to @@ -322,40 +458,63 @@ class BinomialDeviance(LossFunction): """ def __init__(self, n_classes): if n_classes != 2: - raise ValueError("%s requires 2 classes." % - self.__class__.__name__) + raise ValueError("{0:s} requires 2 classes.".format( + self.__class__.__name__)) # we only need to fit one tree for binary clf. super(BinomialDeviance, self).__init__(1) def init_estimator(self): return LogOddsEstimator() - def __call__(self, y, pred): - """Compute the deviance (= negative log-likelihood). """ + def __call__(self, y, pred, sample_weight=None): + """Compute the deviance (= 2 * negative log-likelihood). """ # logaddexp(0, v) == log(1.0 + exp(v)) pred = pred.ravel() - return np.sum(np.logaddexp(0.0, -2 * y * pred)) / y.shape[0] + if sample_weight is None: + return -2.0 * np.mean((y * pred) - np.logaddexp(0.0, pred)) + else: + return (-2.0 / sample_weight.sum() * + np.sum(sample_weight * ((y * pred) - np.logaddexp(0.0, pred)))) def negative_gradient(self, y, pred, **kargs): - return y - 1.0 / (1.0 + np.exp(-pred.ravel())) + """Compute the residual (= negative gradient). """ + return y - expit(pred.ravel()) def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, - residual, pred): - """Make a single Newton-Raphson step. """ + residual, pred, sample_weight): + """Make a single Newton-Raphson step. + + our node estimate is given by: + + sum(w * (y - prob)) / sum(w * prob * (1 - prob)) + + we take advantage that: y - prob = residual + """ terminal_region = np.where(terminal_regions == leaf)[0] residual = residual.take(terminal_region, axis=0) y = y.take(terminal_region, axis=0) + sample_weight = sample_weight.take(terminal_region, axis=0) - numerator = residual.sum() - denominator = np.sum((y - residual) * (1 - y + residual)) + numerator = np.sum(sample_weight * residual) + denominator = np.sum(sample_weight * (y - residual) * (1 - y + residual)) if denominator == 0.0: tree.value[leaf, 0, 0] = 0.0 else: tree.value[leaf, 0, 0] = numerator / denominator + def _score_to_proba(self, score): + proba = np.ones((score.shape[0], 2), dtype=np.float64) + proba[:, 1] = 1.0 / (1.0 + np.exp(-score.ravel())) + proba[:, 0] -= proba[:, 1] + return proba + + def _score_to_decision(self, score): + proba = self._score_to_proba(score) + return np.argmax(proba, axis=1) + -class MultinomialDeviance(LossFunction): +class MultinomialDeviance(ClassificationLossFunction): """Multinomial deviance loss function for multi-class classification. For multi-class classification we need to fit ``n_classes`` trees at @@ -366,107 +525,217 @@ class MultinomialDeviance(LossFunction): def __init__(self, n_classes): if n_classes < 3: - raise ValueError("%s requires more than 2 classes." - % self.__class__.__name__) + raise ValueError("{0:s} requires more than 2 classes.".format( + self.__class__.__name__)) super(MultinomialDeviance, self).__init__(n_classes) def init_estimator(self): return PriorProbabilityEstimator() - def __call__(self, y, pred): + def __call__(self, y, pred, sample_weight=None): # create one-hot label encoding Y = np.zeros((y.shape[0], self.K), dtype=np.float64) for k in range(self.K): Y[:, k] = y == k - return np.sum(-1 * (Y * pred).sum(axis=1) + - np.log(np.exp(pred).sum(axis=1))) + if sample_weight is None: + return np.sum(-1 * (Y * pred).sum(axis=1) + + logsumexp(pred, axis=1)) + else: + return np.sum(-1 * sample_weight * (Y * pred).sum(axis=1) + + logsumexp(pred, axis=1)) - def negative_gradient(self, y, pred, k=0): + def negative_gradient(self, y, pred, k=0, **kwargs): """Compute negative gradient for the ``k``-th class. """ - return y - np.exp(pred[:, k]) / np.sum(np.exp(pred), axis=1) + return y - np.nan_to_num(np.exp(pred[:, k] - + logsumexp(pred, axis=1))) def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, - residual, pred): + residual, pred, sample_weight): """Make a single Newton-Raphson step. """ terminal_region = np.where(terminal_regions == leaf)[0] residual = residual.take(terminal_region, axis=0) - y = y.take(terminal_region, axis=0) + sample_weight = sample_weight.take(terminal_region, axis=0) - numerator = residual.sum() + numerator = np.sum(sample_weight * residual) numerator *= (self.K - 1) / self.K - denominator = np.sum((y - residual) * (1.0 - y + residual)) + denominator = np.sum(sample_weight * (y - residual) * + (1.0 - y + residual)) if denominator == 0.0: tree.value[leaf, 0, 0] = 0.0 else: tree.value[leaf, 0, 0] = numerator / denominator + def _score_to_proba(self, score): + return np.nan_to_num( + np.exp(score - (logsumexp(score, axis=1)[:, np.newaxis]))) + + def _score_to_decision(self, score): + proba = self._score_to_proba(score) + return np.argmax(proba, axis=1) + + +class ExponentialLoss(ClassificationLossFunction): + """Exponential loss function for binary classification. + + Same loss as AdaBoost. + + References + ---------- + Greg Ridgeway, Generalized Boosted Models: A guide to the gbm package, 2007 + """ + def __init__(self, n_classes): + if n_classes != 2: + raise ValueError("{0:s} requires 2 classes.".format( + self.__class__.__name__)) + # we only need to fit one tree for binary clf. + super(ExponentialLoss, self).__init__(1) + + def init_estimator(self): + return ScaledLogOddsEstimator() + + def __call__(self, y, pred, sample_weight=None): + pred = pred.ravel() + if sample_weight is None: + return np.mean(np.exp(-(2. * y - 1.) * pred)) + else: + return (1.0 / sample_weight.sum() * + np.sum(sample_weight * np.exp(-(2 * y - 1) * pred))) + + def negative_gradient(self, y, pred, **kargs): + y_ = -(2. * y - 1.) + return y_ * np.exp(y_ * pred.ravel()) + + def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, + residual, pred, sample_weight): + terminal_region = np.where(terminal_regions == leaf)[0] + pred = pred.take(terminal_region, axis=0) + y = y.take(terminal_region, axis=0) + sample_weight = sample_weight.take(terminal_region, axis=0) + + y_ = 2. * y - 1. + + numerator = np.sum(y_ * sample_weight * np.exp(-y_ * pred)) + denominator = np.sum(sample_weight * np.exp(-y_ * pred)) + + if denominator == 0.0: + tree.value[leaf, 0, 0] = 0.0 + else: + tree.value[leaf, 0, 0] = numerator / denominator + + def _score_to_proba(self, score): + proba = np.ones((score.shape[0], 2), dtype=np.float64) + proba[:, 1] = 1.0 / (1.0 + np.exp(-2.0 * score.ravel())) + proba[:, 0] -= proba[:, 1] + return proba + + def _score_to_decision(self, score): + return (score.ravel() >= 0.0).astype(np.int) + LOSS_FUNCTIONS = {'ls': LeastSquaresError, 'lad': LeastAbsoluteError, 'huber': HuberLossFunction, 'quantile': QuantileLossFunction, - 'bdeviance': BinomialDeviance, - 'mdeviance': MultinomialDeviance, - 'deviance': None} # for both, multinomial and binomial + 'deviance': None, # for both, multinomial and binomial + 'exponential': ExponentialLoss, + } -class BaseGradientBoosting(BaseEnsemble): +INIT_ESTIMATORS = {'zero': ZeroEstimator} + + +class VerboseReporter(object): + """Reports verbose output to stdout. + + If ``verbose==1`` output is printed once in a while (when iteration mod + verbose_mod is zero).; if larger than 1 then output is printed for + each update. + """ + + def __init__(self, verbose): + self.verbose = verbose + + def init(self, est, begin_at_stage=0): + # header fields and line format str + header_fields = ['Iter', 'Train Loss'] + verbose_fmt = ['{iter:>10d}', '{train_score:>16.4f}'] + # do oob? + if est.subsample < 1: + header_fields.append('OOB Improve') + verbose_fmt.append('{oob_impr:>16.4f}') + header_fields.append('Remaining Time') + verbose_fmt.append('{remaining_time:>16s}') + + # print the header line + print(('%10s ' + '%16s ' * + (len(header_fields) - 1)) % tuple(header_fields)) + + self.verbose_fmt = ' '.join(verbose_fmt) + # plot verbose info each time i % verbose_mod == 0 + self.verbose_mod = 1 + self.start_time = time() + self.begin_at_stage = begin_at_stage + + def update(self, j, est): + """Update reporter with new iteration. """ + do_oob = est.subsample < 1 + # we need to take into account if we fit additional estimators. + i = j - self.begin_at_stage # iteration relative to the start iter + if (i + 1) % self.verbose_mod == 0: + oob_impr = est.oob_improvement_[j] if do_oob else 0 + remaining_time = ((est.n_estimators - (j + 1)) * + (time() - self.start_time) / float(i + 1)) + if remaining_time > 60: + remaining_time = '{0:.2f}m'.format(remaining_time / 60.0) + else: + remaining_time = '{0:.2f}s'.format(remaining_time) + print(self.verbose_fmt.format(iter=j + 1, + train_score=est.train_score_[j], + oob_impr=oob_impr, + remaining_time=remaining_time)) + if self.verbose == 1 and ((i + 1) // (self.verbose_mod * 10) > 0): + # adjust verbose frequency (powers of 10) + self.verbose_mod *= 10 + + +class BaseGradientBoosting(six.with_metaclass(ABCMeta, BaseEnsemble, + _LearntSelectorMixin)): """Abstract base class for Gradient Boosting. """ - __metaclass__ = ABCMeta @abstractmethod - def __init__(self, loss, learn_rate, n_estimators, min_samples_split, - min_samples_leaf, max_depth, init, subsample, - max_features, random_state, alpha=0.9): - if n_estimators <= 0: - raise ValueError("n_estimators must be greater than 0") - self.n_estimators = n_estimators + def __init__(self, loss, learning_rate, n_estimators, min_samples_split, + min_samples_leaf, min_weight_fraction_leaf, + max_depth, init, subsample, max_features, + random_state, alpha=0.9, verbose=0, max_leaf_nodes=None, + warm_start=False): - if learn_rate <= 0.0: - raise ValueError("learn_rate must be greater than 0") - self.learn_rate = learn_rate - - if loss not in LOSS_FUNCTIONS: - raise ValueError("Loss '%s' not supported. " % loss) + self.n_estimators = n_estimators + self.learning_rate = learning_rate self.loss = loss - - if min_samples_split <= 0: - raise ValueError("min_samples_split must be larger than 0") self.min_samples_split = min_samples_split - - if min_samples_leaf <= 0: - raise ValueError("min_samples_leaf must be larger than 0") self.min_samples_leaf = min_samples_leaf - - if subsample <= 0.0 or subsample > 1: - raise ValueError("subsample must be in (0,1]") + self.min_weight_fraction_leaf = min_weight_fraction_leaf self.subsample = subsample - self.max_features = max_features - - if max_depth <= 0: - raise ValueError("max_depth must be larger than 0") self.max_depth = max_depth - - if init is not None: - if not hasattr(init, 'fit') or not hasattr(init, 'predict'): - raise ValueError("init must be valid estimator") self.init = init - - self.random_state = check_random_state(random_state) - - if not (0.0 < alpha < 1.0): - raise ValueError("alpha must be in (0.0, 1.0)") + self.random_state = random_state self.alpha = alpha + self.verbose = verbose + self.max_leaf_nodes = max_leaf_nodes + self.warm_start = warm_start - self.estimators_ = None + self.estimators_ = np.empty((0, 0), dtype=np.object) - def fit_stage(self, i, X, X_argsorted, y, y_pred, sample_mask): + def _fit_stage(self, i, X, y, y_pred, sample_weight, sample_mask, + criterion, splitter, random_state): """Fit another stage of ``n_classes_`` trees to the boosting model. """ + + assert sample_mask.dtype == np.bool loss = self.loss_ original_y = y @@ -474,114 +743,315 @@ def fit_stage(self, i, X, X_argsorted, y, y_pred, sample_mask): if loss.is_multi_class: y = np.array(original_y == k, dtype=np.float64) - residual = loss.negative_gradient(y, y_pred, k=k) + residual = loss.negative_gradient(y, y_pred, k=k, + sample_weight=sample_weight) # induce regression tree on residuals - tree = Tree(self.n_features, (1,), 1, MSE(1), self.max_depth, - self.min_samples_split, self.min_samples_leaf, 0.0, - self.max_features, TREE_SPLIT_BEST, self.random_state) + tree = DecisionTreeRegressor( + criterion=criterion, + splitter=splitter, + max_depth=self.max_depth, + min_samples_split=self.min_samples_split, + min_samples_leaf=self.min_samples_leaf, + min_weight_fraction_leaf=self.min_weight_fraction_leaf, + max_features=self.max_features, + max_leaf_nodes=self.max_leaf_nodes, + random_state=random_state) + + if self.subsample < 1.0: + # no inplace multiplication! + sample_weight = sample_weight * sample_mask.astype(np.float64) - tree.build(X, residual[:, np.newaxis], - sample_mask, X_argsorted) + tree.fit(X, residual, sample_weight=sample_weight, + check_input=False) # update tree leaves - self.loss_.update_terminal_regions(tree, X, y, residual, y_pred, - sample_mask, self.learn_rate, - k=k) + loss.update_terminal_regions(tree.tree_, X, y, residual, y_pred, + sample_weight, sample_mask, + self.learning_rate, k=k) # add tree to ensemble self.estimators_[i, k] = tree return y_pred - def fit(self, X, y): + def _check_params(self): + """Check validity of parameters and raise ValueError if not valid. """ + if self.n_estimators <= 0: + raise ValueError("n_estimators must be greater than 0 but " + "was %r" % self.n_estimators) + + if self.learning_rate <= 0.0: + raise ValueError("learning_rate must be greater than 0 but " + "was %r" % self.learning_rate) + + if (self.loss not in self._SUPPORTED_LOSS + or self.loss not in LOSS_FUNCTIONS): + raise ValueError("Loss '{0:s}' not supported. ".format(self.loss)) + + if self.loss == 'deviance': + loss_class = (MultinomialDeviance + if len(self.classes_) > 2 + else BinomialDeviance) + else: + loss_class = LOSS_FUNCTIONS[self.loss] + + if self.loss in ('huber', 'quantile'): + self.loss_ = loss_class(self.n_classes_, self.alpha) + else: + self.loss_ = loss_class(self.n_classes_) + + if not (0.0 < self.subsample <= 1.0): + raise ValueError("subsample must be in (0,1] but " + "was %r" % self.subsample) + + if self.init is not None: + if isinstance(self.init, six.string_types): + if self.init not in INIT_ESTIMATORS: + raise ValueError('init="%s" is not supported' % self.init) + else: + if (not hasattr(self.init, 'fit') + or not hasattr(self.init, 'predict')): + raise ValueError("init=%r must be valid BaseEstimator " + "and support both fit and " + "predict" % self.init) + + if not (0.0 < self.alpha < 1.0): + raise ValueError("alpha must be in (0.0, 1.0) but " + "was %r" % self.alpha) + + if isinstance(self.max_features, six.string_types): + if self.max_features == "auto": + # if is_classification + if self.n_classes_ > 1: + max_features = max(1, int(np.sqrt(self.n_features))) + else: + # is regression + max_features = self.n_features + elif self.max_features == "sqrt": + max_features = max(1, int(np.sqrt(self.n_features))) + elif self.max_features == "log2": + max_features = max(1, int(np.log2(self.n_features))) + else: + raise ValueError("Invalid value for max_features: %r. " + "Allowed string values are 'auto', 'sqrt' " + "or 'log2'." % self.max_features) + elif self.max_features is None: + max_features = self.n_features + elif isinstance(self.max_features, (numbers.Integral, np.integer)): + max_features = self.max_features + else: # float + if 0. < self.max_features <= 1.: + max_features = max(int(self.max_features * self.n_features), 1) + else: + raise ValueError("max_features must be in (0, n_features]") + + self.max_features_ = max_features + + def _init_state(self): + """Initialize model state and allocate model state data structures. """ + + if self.init is None: + self.init_ = self.loss_.init_estimator() + elif isinstance(self.init, six.string_types): + self.init_ = INIT_ESTIMATORS[self.init]() + else: + self.init_ = self.init + + self.estimators_ = np.empty((self.n_estimators, self.loss_.K), + dtype=np.object) + self.train_score_ = np.zeros((self.n_estimators,), dtype=np.float64) + # do oob? + if self.subsample < 1.0: + self.oob_improvement_ = np.zeros((self.n_estimators), + dtype=np.float64) + + def _clear_state(self): + """Clear the state of the gradient boosting model. """ + if hasattr(self, 'estimators_'): + self.estimators_ = np.empty((0, 0), dtype=np.object) + if hasattr(self, 'train_score_'): + del self.train_score_ + if hasattr(self, 'oob_improvement_'): + del self.oob_improvement_ + if hasattr(self, 'init_'): + del self.init_ + + def _resize_state(self): + """Add additional ``n_estimators`` entries to all attributes. """ + # self.n_estimators is the number of additional est to fit + total_n_estimators = self.n_estimators + if total_n_estimators < self.estimators_.shape[0]: + raise ValueError('resize with smaller n_estimators %d < %d' % + (total_n_estimators, self.estimators_[0])) + + self.estimators_.resize((total_n_estimators, self.loss_.K)) + self.train_score_.resize(total_n_estimators) + if (self.subsample < 1 or hasattr(self, 'oob_improvement_')): + # if do oob resize arrays or create new if not available + if hasattr(self, 'oob_improvement_'): + self.oob_improvement_.resize(total_n_estimators) + else: + self.oob_improvement_ = np.zeros((total_n_estimators,), + dtype=np.float64) + + def _is_initialized(self): + return len(getattr(self, 'estimators_', [])) > 0 + + def fit(self, X, y, sample_weight=None, monitor=None): """Fit the gradient boosting model. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples - and n_features is the number of features. Use fortran-style - to avoid memory copies. + and n_features is the number of features. y : array-like, shape = [n_samples] Target values (integers in classification, real numbers in regression) - For classification, labels must correspond to classes - ``0, 1, ..., n_classes_-1`` + For classification, labels must correspond to classes. + + sample_weight : array-like, shape = [n_samples] or None + Sample weights. If None, then samples are equally weighted. Splits + that would create child nodes with net zero or negative weight are + ignored while searching for a split in each node. In the case of + classification, splits are also ignored if they would result in any + single class carrying a negative weight in either child node. + + monitor : callable, optional + The monitor is called after each iteration with the current + iteration, a reference to the estimator and the local variables of + ``_fit_stages`` as keyword arguments ``callable(i, self, + locals())``. If the callable returns ``True`` the fitting procedure + is stopped. The monitor can be used for various things such as + computing held-out estimates, early stopping, model introspect, and + snapshoting. Returns ------- self : object Returns self. """ - X, y = check_arrays(X, y, sparse_format='dense') - X = np.asfortranarray(X, dtype=DTYPE) - y = np.ravel(y, order='C') - - n_samples, n_features = X.shape - self.n_features = n_features + # if not warmstart - clear the estimator state + if not self.warm_start: + self._clear_state() + + # Check input + X, y = check_X_y(X, y, dtype=DTYPE) + n_samples, self.n_features = X.shape + if sample_weight is None: + sample_weight = np.ones(n_samples, dtype=np.float32) + else: + sample_weight = column_or_1d(sample_weight, warn=True) - if self.max_features is None: - self.max_features = n_features + check_consistent_length(X, y, sample_weight) - if not (0 < self.max_features <= n_features): - raise ValueError("max_features must be in (0, n_features]") + y = self._validate_y(y) - loss_class = LOSS_FUNCTIONS[self.loss] - if self.loss in ('huber', 'quantile'): - loss = loss_class(self.n_classes_, self.alpha) - else: - loss = loss_class(self.n_classes_) + random_state = check_random_state(self.random_state) + self._check_params() - # store loss object for future use - self.loss_ = loss + if not self._is_initialized(): + # init state + self._init_state() - if self.init is None: - self.init = loss.init_estimator() + # fit initial model - FIXME make sample_weight optional + self.init_.fit(X, y, sample_weight) - # create argsorted X for fast tree induction - X_argsorted = np.asfortranarray( - np.argsort(X.T, axis=1).astype(np.int32).T) + # init predictions + y_pred = self.init_.predict(X) + begin_at_stage = 0 + else: + # add more estimators to fitted model + # invariant: warm_start = True + if self.n_estimators < self.estimators_.shape[0]: + raise ValueError('n_estimators=%d must be larger or equal to ' + 'estimators_.shape[0]=%d when ' + 'warm_start==True' + % (self.n_estimators, + self.estimators_.shape[0])) + begin_at_stage = self.estimators_.shape[0] + y_pred = self._decision_function(X) + self._resize_state() + + # fit the boosting stages + n_stages = self._fit_stages(X, y, y_pred, sample_weight, random_state, + begin_at_stage, monitor) + # change shape of arrays after fit (early-stopping or additional ests) + if n_stages != self.estimators_.shape[0]: + self.estimators_ = self.estimators_[:n_stages] + self.train_score_ = self.train_score_[:n_stages] + if hasattr(self, 'oob_improvement_'): + self.oob_improvement_ = self.oob_improvement_[:n_stages] - # fit initial model - self.init.fit(X, y) + return self - # init predictions - y_pred = self.init.predict(X) + def _fit_stages(self, X, y, y_pred, sample_weight, random_state, + begin_at_stage=0, monitor=None): + """Iteratively fits the stages. - self.estimators_ = np.empty((self.n_estimators, loss.K), - dtype=np.object) + For each stage it computes the progress (OOB, train score) + and delegates to ``_fit_stage``. + Returns the number of stages fit; might differ from ``n_estimators`` + due to early stopping. + """ + n_samples = X.shape[0] + do_oob = self.subsample < 1.0 + sample_mask = np.ones((n_samples, ), dtype=np.bool) + n_inbag = max(1, int(self.subsample * n_samples)) + loss_ = self.loss_ - self.train_score_ = np.zeros((self.n_estimators,), dtype=np.float64) - self.oob_score_ = np.zeros((self.n_estimators), dtype=np.float64) + # init criterion and splitter + criterion = FriedmanMSE(1) + splitter = PresortBestSplitter(criterion, + self.max_features_, + self.min_samples_leaf, + self.min_weight_fraction_leaf, + random_state) - sample_mask = np.ones((n_samples,), dtype=np.bool) - n_inbag = max(1, int(self.subsample * n_samples)) + if self.verbose: + verbose_reporter = VerboseReporter(self.verbose) + verbose_reporter.init(self, begin_at_stage) # perform boosting iterations - for i in range(self.n_estimators): + i = begin_at_stage + for i in range(begin_at_stage, self.n_estimators): # subsampling - if self.subsample < 1.0: - # TODO replace with ``np.choice`` if possible. + if do_oob: sample_mask = _random_sample_mask(n_samples, n_inbag, - self.random_state) + random_state) + # OOB score before adding this stage + old_oob_score = loss_(y[~sample_mask], + y_pred[~sample_mask], + sample_weight[~sample_mask]) # fit next stage of trees - y_pred = self.fit_stage(i, X, X_argsorted, y, y_pred, sample_mask) + y_pred = self._fit_stage(i, X, y, y_pred, sample_weight, + sample_mask, criterion, splitter, + random_state) # track deviance (= loss) - if self.subsample < 1.0: - self.train_score_[i] = loss(y[sample_mask], - y_pred[sample_mask]) - self.oob_score_[i] = loss(y[~sample_mask], - y_pred[~sample_mask]) + if do_oob: + self.train_score_[i] = loss_(y[sample_mask], + y_pred[sample_mask], + sample_weight[sample_mask]) + self.oob_improvement_[i] = (old_oob_score - + loss_(y[~sample_mask], y_pred[~sample_mask], + sample_weight[~sample_mask])) else: # no need to fancy index w/ no subsampling - self.train_score_[i] = loss(y, y_pred) + self.train_score_[i] = loss_(y, y_pred, sample_weight) - return self + if self.verbose > 0: + verbose_reporter.update(i, self) + + if monitor is not None: + early_stopping = monitor(i, self, locals()) + if early_stopping: + break + return i + 1 def _make_estimator(self, append=True): # we don't need _make_estimator @@ -590,12 +1060,19 @@ def _make_estimator(self, append=True): def _init_decision_function(self, X): """Check input and compute prediction of ``init``. """ if self.estimators_ is None or len(self.estimators_) == 0: - raise ValueError("Estimator not fitted, call `fit` " \ - "before making predictions`.") + raise NotFittedError("Estimator not fitted, call `fit`" + " before making predictions`.") if X.shape[1] != self.n_features: - raise ValueError("X.shape[1] should be %d, not %d." % - (self.n_features, X.shape[1])) - score = self.init.predict(X).astype(np.float64) + raise ValueError("X.shape[1] should be {0:d}, not {1:d}.".format( + self.n_features, X.shape[1])) + score = self.init_.predict(X).astype(np.float64) + return score + + def _decision_function(self, X): + # for use in inner loop, not raveling the output in single-class case, + # not doing input validation. + score = self._init_decision_function(X) + predict_stages(self.estimators_, X, self.learning_rate, score) return score def decision_function(self, X): @@ -608,15 +1085,16 @@ def decision_function(self, X): Returns ------- - score : array, shape = [n_samples, k] - The decision function of the input samples. Classes are - ordered by arithmetical order. Regression and binary - classification are special cases with ``k == 1``, - otherwise ``k==n_classes``. + score : array, shape = [n_samples, n_classes] or [n_samples] + The decision function of the input samples. The order of the + classes corresponds to that in the attribute `classes_`. + Regression and binary classification produce an array of shape + [n_samples]. """ - X = array2d(X, dtype=DTYPE, order='C') - score = self._init_decision_function(X) - predict_stages(self.estimators_, X, self.learn_rate, score) + X = check_array(X, dtype=DTYPE, order="C") + score = self._decision_function(X) + if score.shape[1] == 1: + return score.ravel() return score def staged_decision_function(self, X): @@ -633,31 +1111,46 @@ def staged_decision_function(self, X): Returns ------- score : generator of array, shape = [n_samples, k] - The decision function of the input samples. Classes are - ordered by arithmetical order. Regression and binary - classification are special cases with ``k == 1``, - otherwise ``k==n_classes``. + The decision function of the input samples. The order of the + classes corresponds to that in the attribute `classes_`. + Regression and binary classification are special cases with + ``k == 1``, otherwise ``k==n_classes``. """ - X = array2d(X, dtype=DTYPE, order='C') + X = check_array(X, dtype=DTYPE, order="C") score = self._init_decision_function(X) - for i in range(self.n_estimators): - predict_stage(self.estimators_, i, X, self.learn_rate, score) - yield score + for i in range(self.estimators_.shape[0]): + predict_stage(self.estimators_, i, X, self.learning_rate, score) + yield score.copy() @property def feature_importances_(self): + """Return the feature importances (the higher, the more important the + feature). + + Returns + ------- + feature_importances_ : array, shape = [n_features] + """ if self.estimators_ is None or len(self.estimators_) == 0: - raise ValueError("Estimator not fitted, " \ - "call `fit` before `feature_importances_`.") + raise NotFittedError("Estimator not fitted, call `fit` before" + " `feature_importances_`.") + total_sum = np.zeros((self.n_features, ), dtype=np.float64) for stage in self.estimators_: - stage_sum = sum(tree.compute_feature_importances(method='gini') + stage_sum = sum(tree.feature_importances_ for tree in stage) / len(stage) total_sum += stage_sum importances = total_sum / len(self.estimators_) return importances + def _validate_y(self, y): + self.n_classes_ = 1 + if y.dtype.kind == 'O': + y = y.astype(np.float64) + # Default implementation + return y + class GradientBoostingClassifier(BaseGradientBoosting, ClassifierMixin): """Gradient Boosting for classification. @@ -671,14 +1164,15 @@ class GradientBoostingClassifier(BaseGradientBoosting, ClassifierMixin): Parameters ---------- - loss : {'deviance'}, optional (default='deviance') + loss : {'deviance', 'exponential'}, optional (default='deviance') loss function to be optimized. 'deviance' refers to deviance (= logistic regression) for classification - with probabilistic outputs. + with probabilistic outputs. For loss 'exponential' gradient + boosting recovers the AdaBoost algorithm. - learn_rate : float, optional (default=0.1) - learning rate shrinks the contribution of each tree by `learn_rate`. - There is a trade-off between learn_rate and n_estimators. + learning_rate : float, optional (default=0.1) + learning rate shrinks the contribution of each tree by `learning_rate`. + There is a trade-off between learning_rate and n_estimators. n_estimators : int (default=100) The number of boosting stages to perform. Gradient boosting @@ -690,13 +1184,18 @@ class GradientBoostingClassifier(BaseGradientBoosting, ClassifierMixin): depth limits the number of nodes in the tree. Tune this parameter for best performance; the best value depends on the interaction of the input variables. + Ignored if ``max_leaf_nodes`` is not None. - min_samples_split : integer, optional (default=1) + min_samples_split : integer, optional (default=2) The minimum number of samples required to split an internal node. min_samples_leaf : integer, optional (default=1) The minimum number of samples required to be at a leaf node. + min_weight_fraction_leaf : float, optional (default=0.) + The minimum weighted fraction of the input samples required to be at a + leaf node. + subsample : float, optional (default=1.0) The fraction of samples to be used for fitting the individual base learners. If smaller than 1.0 this results in Stochastic Gradient @@ -704,40 +1203,75 @@ class GradientBoostingClassifier(BaseGradientBoosting, ClassifierMixin): Choosing `subsample < 1.0` leads to a reduction of variance and an increase in bias. - max_features : int, None, optional (default=None) - The number of features to consider when looking for the best split. - Features are choosen randomly at each split point. - If None, then `max_features=n_features`. Choosing - `max_features < n_features` leads to a reduction of variance + max_features : int, float, string or None, optional (default=None) + The number of features to consider when looking for the best split: + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a percentage and + `int(max_features * n_features)` features are considered at each + split. + - If "auto", then `max_features=sqrt(n_features)`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + Choosing `max_features < n_features` leads to a reduction of variance and an increase in bias. + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + + max_leaf_nodes : int or None, optional (default=None) + Grow trees with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + If not None then ``max_depth`` will be ignored. + + init : BaseEstimator, None, optional (default=None) + An estimator object that is used to compute the initial + predictions. ``init`` has to provide ``fit`` and ``predict``. + If None it uses ``loss.init_estimator``. + + verbose : int, default: 0 + Enable verbose output. If 1 then it prints progress and performance + once in a while (the more trees the lower the frequency). If greater + than 1 then it prints progress and performance for every tree. + + warm_start : bool, default: False + When set to ``True``, reuse the solution of the previous call to fit + and add more estimators to the ensemble, otherwise, just erase the + previous solution. + Attributes ---------- - `feature_importances_` : array, shape = [n_features] + feature_importances_ : array, shape = [n_features] The feature importances (the higher, the more important the feature). - `oob_score_` : array, shape = [n_estimators] - Score of the training dataset obtained using an out-of-bag estimate. - The i-th score ``oob_score_[i]`` is the deviance (= loss) of the - model at iteration ``i`` on the out-of-bag sample. + oob_improvement_ : array, shape = [n_estimators] + The improvement in loss (= deviance) on the out-of-bag samples + relative to the previous iteration. + ``oob_improvement_[0]`` is the improvement in + loss of the first stage over the ``init`` estimator. - `train_score_` : array, shape = [n_estimators] + train_score_ : array, shape = [n_estimators] The i-th score ``train_score_[i]`` is the deviance (= loss) of the model at iteration ``i`` on the in-bag sample. If ``subsample == 1`` this is the deviance on the training data. - Examples - -------- - >>> samples = [[0, 0, 2], [1, 0, 0]] - >>> labels = [0, 1] - >>> from sklearn.ensemble import GradientBoostingClassifier - >>> gb = GradientBoostingClassifier().fit(samples, labels) - >>> print gb.predict([[0.5, 0, 0]]) - [0] + loss_ : LossFunction + The concrete ``LossFunction`` object. + + `init` : BaseEstimator + The estimator that provides the initial predictions. + Set via the ``init`` argument or ``loss.init_estimator``. + + estimators_ : list of DecisionTreeRegressor + The collection of fitted sub-estimators. See also -------- sklearn.tree.DecisionTreeClassifier, RandomForestClassifier + AdaBoostClassifier References ---------- @@ -750,58 +1284,52 @@ class GradientBoostingClassifier(BaseGradientBoosting, ClassifierMixin): Elements of Statistical Learning Ed. 2, Springer, 2009. """ - def __init__(self, loss='deviance', learn_rate=0.1, n_estimators=100, - subsample=1.0, min_samples_split=1, min_samples_leaf=1, + _SUPPORTED_LOSS = ('deviance', 'exponential') + + def __init__(self, loss='deviance', learning_rate=0.1, n_estimators=100, + subsample=1.0, min_samples_split=2, + min_samples_leaf=1, min_weight_fraction_leaf=0., max_depth=3, init=None, random_state=None, - max_features=None): + max_features=None, verbose=0, + max_leaf_nodes=None, warm_start=False): super(GradientBoostingClassifier, self).__init__( - loss, learn_rate, n_estimators, min_samples_split, - min_samples_leaf, max_depth, init, subsample, max_features, - random_state) + loss=loss, learning_rate=learning_rate, n_estimators=n_estimators, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_depth=max_depth, init=init, subsample=subsample, + max_features=max_features, + random_state=random_state, verbose=verbose, + max_leaf_nodes=max_leaf_nodes, warm_start=warm_start) + + def _validate_y(self, y): + self.classes_, y = np.unique(y, return_inverse=True) + self.n_classes_ = len(self.classes_) + return y - def fit(self, X, y): - """Fit the gradient boosting model. + def predict(self, X): + """Predict class for X. Parameters ---------- - X : array-like, shape = [n_samples, n_features] - Training vectors, where n_samples is the number of samples - and n_features is the number of features. Use fortran-style - to avoid memory copies. - - y : array-like, shape = [n_samples] - Target values (integers in classification, real numbers in - regression) - For classification, labels must correspond to classes - ``0, 1, ..., n_classes_-1`` + X : array-like of shape = [n_samples, n_features] + The input samples. Returns ------- - self : object - Returns self. + y: array of shape = ["n_samples] + The predicted values. """ - self.classes_ = np.unique(y) - self.n_classes_ = len(self.classes_) - y = np.searchsorted(self.classes_, y) - if self.loss == 'deviance': - self.loss = 'mdeviance' if len(self.classes_) > 2 else 'bdeviance' - - return super(GradientBoostingClassifier, self).fit(X, y) + score = self.decision_function(X) + decisions = self.loss_._score_to_decision(score) + return self.classes_.take(decisions, axis=0) - def _score_to_proba(self, score): - """Compute class probability estimates from decision scores. """ - proba = np.ones((score.shape[0], self.n_classes_), dtype=np.float64) - if not self.loss_.is_multi_class: - proba[:, 1] = 1.0 / (1.0 + np.exp(-score.ravel())) - proba[:, 0] -= proba[:, 1] - else: - proba = (np.exp(score) - / np.sum(np.exp(score), axis=1)[:, np.newaxis]) - return proba + def staged_predict(self, X): + """Predict class at each stage for X. - def predict_proba(self, X): - """Predict class probabilities for X. + This method allows monitoring (i.e. determine error on testing set) + after each stage. Parameters ---------- @@ -810,49 +1338,64 @@ def predict_proba(self, X): Returns ------- - p : array of shape = [n_samples] - The class probabilities of the input samples. Classes are - ordered by arithmetical order. + y : generator of array of shape = [n_samples] + The predicted value of the input samples. """ - score = self.decision_function(X) - return self._score_to_proba(score) - - def staged_predict_proba(self, X): - """Predict class probabilities at each stage for X. + for score in self.staged_decision_function(X): + decisions = self.loss_._score_to_decision(score) + yield self.classes_.take(decisions, axis=0) - This method allows monitoring (i.e. determine error on testing set) - after each stage. + def predict_proba(self, X): + """Predict class probabilities for X. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. + Raises + ------ + AttributeError + If the ``loss`` does not support probabilities. + Returns ------- - y : array of shape = [n_samples] - The predicted value of the input samples. + p : array of shape = [n_samples] + The class probabilities of the input samples. The order of the + classes corresponds to that in the attribute `classes_`. """ - for score in self.staged_decision_function(X): - yield self._score_to_proba(X) + score = self.decision_function(X) + try: + return self.loss_._score_to_proba(score) + except NotFittedError: + raise + except AttributeError: + raise AttributeError('loss=%r does not support predict_proba' % + self.loss) - def predict(self, X): - """Predict class for X. + def predict_log_proba(self, X): + """Predict class log-probabilities for X. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. + Raises + ------ + AttributeError + If the ``loss`` does not support probabilities. + Returns ------- - y : array of shape = [n_samples] - The predicted classes. + p : array of shape = [n_samples] + The class log-probabilities of the input samples. The order of the + classes corresponds to that in the attribute `classes_`. """ proba = self.predict_proba(X) - return self.classes_.take(np.argmax(proba, axis=1), axis=0) + return np.log(proba) - def staged_predict(self, X): + def staged_predict_proba(self, X): """Predict class probabilities at each stage for X. This method allows monitoring (i.e. determine error on testing set) @@ -865,11 +1408,17 @@ def staged_predict(self, X): Returns ------- - y : array of shape = [n_samples] + y : generator of array of shape = [n_samples] The predicted value of the input samples. """ - for proba in self.staged_predict_proba(X): - yield self.classes_.take(np.argmax(proba, axis=1), axis=0) + try: + for score in self.staged_decision_function(X): + yield self.loss_._score_to_proba(score) + except NotFittedError: + raise + except AttributeError: + raise AttributeError('loss=%r does not support predict_proba' % + self.loss) class GradientBoostingRegressor(BaseGradientBoosting, RegressorMixin): @@ -885,13 +1434,13 @@ class GradientBoostingRegressor(BaseGradientBoosting, RegressorMixin): loss : {'ls', 'lad', 'huber', 'quantile'}, optional (default='ls') loss function to be optimized. 'ls' refers to least squares regression. 'lad' (least absolute deviation) is a highly robust - loss function soley based on order information of the input + loss function solely based on order information of the input variables. 'huber' is a combination of the two. 'quantile' allows quantile regression (use `alpha` to specify the quantile). - learn_rate : float, optional (default=0.1) - learning rate shrinks the contribution of each tree by `learn_rate`. - There is a trade-off between learn_rate and n_estimators. + learning_rate : float, optional (default=0.1) + learning rate shrinks the contribution of each tree by `learning_rate`. + There is a trade-off between learning_rate and n_estimators. n_estimators : int (default=100) The number of boosting stages to perform. Gradient boosting @@ -903,13 +1452,18 @@ class GradientBoostingRegressor(BaseGradientBoosting, RegressorMixin): depth limits the number of nodes in the tree. Tune this parameter for best performance; the best value depends on the interaction of the input variables. + Ignored if ``max_leaf_nodes`` is not None. - min_samples_split : integer, optional (default=1) + min_samples_split : integer, optional (default=2) The minimum number of samples required to split an internal node. min_samples_leaf : integer, optional (default=1) The minimum number of samples required to be at a leaf node. + min_weight_fraction_leaf : float, optional (default=0.) + The minimum weighted fraction of the input samples required to be at a + leaf node. + subsample : float, optional (default=1.0) The fraction of samples to be used for fitting the individual base learners. If smaller than 1.0 this results in Stochastic Gradient @@ -917,40 +1471,74 @@ class GradientBoostingRegressor(BaseGradientBoosting, RegressorMixin): Choosing `subsample < 1.0` leads to a reduction of variance and an increase in bias. - max_features : int, None, optional (default=None) - The number of features to consider when looking for the best split. - Features are choosen randomly at each split point. - If None, then `max_features=n_features`. Choosing - `max_features < n_features` leads to a reduction of variance + max_features : int, float, string or None, optional (default=None) + The number of features to consider when looking for the best split: + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a percentage and + `int(max_features * n_features)` features are considered at each + split. + - If "auto", then `max_features=n_features`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + Choosing `max_features < n_features` leads to a reduction of variance and an increase in bias. + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + + max_leaf_nodes : int or None, optional (default=None) + Grow trees with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + alpha : float (default=0.9) The alpha-quantile of the huber loss function and the quantile loss function. Only if ``loss='huber'`` or ``loss='quantile'``. + init : BaseEstimator, None, optional (default=None) + An estimator object that is used to compute the initial + predictions. ``init`` has to provide ``fit`` and ``predict``. + If None it uses ``loss.init_estimator``. + + verbose : int, default: 0 + Enable verbose output. If 1 then it prints progress and performance + once in a while (the more trees the lower the frequency). If greater + than 1 then it prints progress and performance for every tree. + + warm_start : bool, default: False + When set to ``True``, reuse the solution of the previous call to fit + and add more estimators to the ensemble, otherwise, just erase the + previous solution. + + Attributes ---------- - `feature_importances_` : array, shape = [n_features] + feature_importances_ : array, shape = [n_features] The feature importances (the higher, the more important the feature). - `oob_score_` : array, shape = [n_estimators] - Score of the training dataset obtained using an out-of-bag estimate. - The i-th score ``oob_score_[i]`` is the deviance (= loss) of the - model at iteration ``i`` on the out-of-bag sample. + oob_improvement_ : array, shape = [n_estimators] + The improvement in loss (= deviance) on the out-of-bag samples + relative to the previous iteration. + ``oob_improvement_[0]`` is the improvement in + loss of the first stage over the ``init`` estimator. - `train_score_` : array, shape = [n_estimators] + train_score_ : array, shape = [n_estimators] The i-th score ``train_score_[i]`` is the deviance (= loss) of the model at iteration ``i`` on the in-bag sample. If ``subsample == 1`` this is the deviance on the training data. - Examples - -------- - >>> samples = [[0, 0, 2], [1, 0, 0]] - >>> labels = [0, 1] - >>> from sklearn.ensemble import GradientBoostingRegressor - >>> gb = GradientBoostingRegressor().fit(samples, labels) - >>> print gb.predict([[0, 0, 0]]) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE - [ 1.32806... + loss_ : LossFunction + The concrete ``LossFunction`` object. + + `init` : BaseEstimator + The estimator that provides the initial predictions. + Set via the ``init`` argument or ``loss.init_estimator``. + + estimators_ : list of DecisionTreeRegressor + The collection of fitted sub-estimators. See also -------- @@ -967,39 +1555,24 @@ class GradientBoostingRegressor(BaseGradientBoosting, RegressorMixin): Elements of Statistical Learning Ed. 2, Springer, 2009. """ - def __init__(self, loss='ls', learn_rate=0.1, n_estimators=100, - subsample=1.0, min_samples_split=1, min_samples_leaf=1, + _SUPPORTED_LOSS = ('ls', 'lad', 'huber', 'quantile') + + def __init__(self, loss='ls', learning_rate=0.1, n_estimators=100, + subsample=1.0, min_samples_split=2, + min_samples_leaf=1, min_weight_fraction_leaf=0., max_depth=3, init=None, random_state=None, - max_features=None, alpha=0.9): + max_features=None, alpha=0.9, verbose=0, max_leaf_nodes=None, + warm_start=False): super(GradientBoostingRegressor, self).__init__( - loss, learn_rate, n_estimators, min_samples_split, - min_samples_leaf, max_depth, init, subsample, max_features, - random_state, alpha) - - def fit(self, X, y): - """Fit the gradient boosting model. - - Parameters - ---------- - X : array-like, shape = [n_samples, n_features] - Training vectors, where n_samples is the number of samples - and n_features is the number of features. Use fortran-style - to avoid memory copies. - - y : array-like, shape = [n_samples] - Target values (integers in classification, real numbers in - regression) - For classification, labels must correspond to classes - ``0, 1, ..., n_classes_-1`` - - Returns - ------- - self : object - Returns self. - """ - self.n_classes_ = 1 - return super(GradientBoostingRegressor, self).fit(X, y) + loss=loss, learning_rate=learning_rate, n_estimators=n_estimators, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_depth=max_depth, init=init, subsample=subsample, + max_features=max_features, + random_state=random_state, alpha=alpha, verbose=verbose, + max_leaf_nodes=max_leaf_nodes, warm_start=warm_start) def predict(self, X): """Predict regression target for X. @@ -1011,7 +1584,7 @@ def predict(self, X): Returns ------- - y: array of shape = [n_samples] + y : array of shape = [n_samples] The predicted values. """ return self.decision_function(X).ravel() @@ -1029,7 +1602,7 @@ def staged_predict(self, X): Returns ------- - y : array of shape = [n_samples] + y : generator of array of shape = [n_samples] The predicted value of the input samples. """ for y in self.staged_decision_function(X): diff --git a/sklearn/ensemble/partial_dependence.py b/sklearn/ensemble/partial_dependence.py new file mode 100644 index 0000000000000..4e17bf18869d7 --- /dev/null +++ b/sklearn/ensemble/partial_dependence.py @@ -0,0 +1,388 @@ +"""Partial dependence plots for tree ensembles. """ + +# Authors: Peter Prettenhofer +# License: BSD 3 clause + +from itertools import count +import numbers + +import numpy as np +from scipy.stats.mstats import mquantiles + +from ..utils.extmath import cartesian +from ..externals.joblib import Parallel, delayed +from ..externals import six +from ..externals.six.moves import map, range, zip +from ..utils import check_array +from ..tree._tree import DTYPE + +from ._gradient_boosting import _partial_dependence_tree +from .gradient_boosting import BaseGradientBoosting + + +def _grid_from_X(X, percentiles=(0.05, 0.95), grid_resolution=100): + """Generate a grid of points based on the ``percentiles of ``X``. + + The grid is generated by placing ``grid_resolution`` equally + spaced points between the ``percentiles`` of each column + of ``X``. + + Parameters + ---------- + X : ndarray + The data + percentiles : tuple of floats + The percentiles which are used to construct the extreme + values of the grid axes. + grid_resolution : int + The number of equally spaced points that are placed + on the grid. + + Returns + ------- + grid : ndarray + All data points on the grid; ``grid.shape[1] == X.shape[1]`` + and ``grid.shape[0] == grid_resolution * X.shape[1]``. + axes : seq of ndarray + The axes with which the grid has been created. + """ + if len(percentiles) != 2: + raise ValueError('percentile must be tuple of len 2') + if not all(0. <= x <= 1. for x in percentiles): + raise ValueError('percentile values must be in [0, 1]') + + axes = [] + for col in range(X.shape[1]): + uniques = np.unique(X[:, col]) + if uniques.shape[0] < grid_resolution: + # feature has low resolution use unique vals + axis = uniques + else: + emp_percentiles = mquantiles(X, prob=percentiles, axis=0) + # create axis based on percentiles and grid resolution + axis = np.linspace(emp_percentiles[0, col], + emp_percentiles[1, col], + num=grid_resolution, endpoint=True) + axes.append(axis) + + return cartesian(axes), axes + + +def partial_dependence(gbrt, target_variables, grid=None, X=None, + percentiles=(0.05, 0.95), grid_resolution=100): + """Partial dependence of ``target_variables``. + + Partial dependence plots show the dependence between the joint values + of the ``target_variables`` and the function represented + by the ``gbrt``. + + Parameters + ---------- + gbrt : BaseGradientBoosting + A fitted gradient boosting model. + target_variables : array-like, dtype=int + The target features for which the partial dependecy should be + computed (size should be smaller than 3 for visual renderings). + grid : array-like, shape=(n_points, len(target_variables)) + The grid of ``target_variables`` values for which the + partial dependecy should be evaluated (either ``grid`` or ``X`` + must be specified). + X : array-like, shape=(n_samples, n_features) + The data on which ``gbrt`` was trained. It is used to generate + a ``grid`` for the ``target_variables``. The ``grid`` comprises + ``grid_resolution`` equally spaced points between the two + ``percentiles``. + percentiles : (low, high), default=(0.05, 0.95) + The lower and upper percentile used create the extreme values + for the ``grid``. Only if ``X`` is not None. + grid_resolution : int, default=100 + The number of equally spaced points on the ``grid``. + + Returns + ------- + pdp : array, shape=(n_classes, n_points) + The partial dependence function evaluated on the ``grid``. + For regression and binary classification ``n_classes==1``. + axes : seq of ndarray or None + The axes with which the grid has been created or None if + the grid has been given. + + Examples + -------- + >>> samples = [[0, 0, 2], [1, 0, 0]] + >>> labels = [0, 1] + >>> from sklearn.ensemble import GradientBoostingClassifier + >>> gb = GradientBoostingClassifier(random_state=0).fit(samples, labels) + >>> kwargs = dict(X=samples, percentiles=(0, 1), grid_resolution=2) + >>> partial_dependence(gb, [0], **kwargs) # doctest: +SKIP + (array([[-4.52..., 4.52...]]), [array([ 0., 1.])]) + """ + if not isinstance(gbrt, BaseGradientBoosting): + raise ValueError('gbrt has to be an instance of BaseGradientBoosting') + if gbrt.estimators_.shape[0] == 0: + raise ValueError('Call %s.fit before partial_dependence' % + gbrt.__class__.__name__) + if (grid is None and X is None) or (grid is not None and X is not None): + raise ValueError('Either grid or X must be specified') + + target_variables = np.asarray(target_variables, dtype=np.int32, + order='C').ravel() + + if any([not (0 <= fx < gbrt.n_features) for fx in target_variables]): + raise ValueError('target_variables must be in [0, %d]' + % (gbrt.n_features - 1)) + + if X is not None: + X = check_array(X, dtype=DTYPE, order='C') + grid, axes = _grid_from_X(X[:, target_variables], percentiles, + grid_resolution) + else: + assert grid is not None + # dont return axes if grid is given + axes = None + # grid must be 2d + if grid.ndim == 1: + grid = grid[:, np.newaxis] + if grid.ndim != 2: + raise ValueError('grid must be 2d but is %dd' % grid.ndim) + + grid = np.asarray(grid, dtype=DTYPE, order='C') + assert grid.shape[1] == target_variables.shape[0] + + n_trees_per_stage = gbrt.estimators_.shape[1] + n_estimators = gbrt.estimators_.shape[0] + pdp = np.zeros((n_trees_per_stage, grid.shape[0],), dtype=np.float64, + order='C') + for stage in range(n_estimators): + for k in range(n_trees_per_stage): + tree = gbrt.estimators_[stage, k].tree_ + _partial_dependence_tree(tree, grid, target_variables, + gbrt.learning_rate, pdp[k]) + + return pdp, axes + + +def plot_partial_dependence(gbrt, X, features, feature_names=None, + label=None, n_cols=3, grid_resolution=100, + percentiles=(0.05, 0.95), n_jobs=1, + verbose=0, ax=None, line_kw=None, + contour_kw=None, **fig_kw): + """Partial dependence plots for ``features``. + + The ``len(features)`` plots are arranged in a grid with ``n_cols`` + columns. Two-way partial dependence plots are plotted as contour + plots. + + Parameters + ---------- + gbrt : BaseGradientBoosting + A fitted gradient boosting model. + X : array-like, shape=(n_samples, n_features) + The data on which ``gbrt`` was trained. + features : seq of tuples or ints + If seq[i] is an int or a tuple with one int value, a one-way + PDP is created; if seq[i] is a tuple of two ints, a two-way + PDP is created. + feature_names : seq of str + Name of each feature; feature_names[i] holds + the name of the feature with index i. + label : object + The class label for which the PDPs should be computed. + Only if gbrt is a multi-class model. Must be in ``gbrt.classes_``. + n_cols : int + The number of columns in the grid plot (default: 3). + percentiles : (low, high), default=(0.05, 0.95) + The lower and upper percentile used create the extreme values + for the PDP axes. + grid_resolution : int, default=100 + The number of equally spaced points on the axes. + n_jobs : int + The number of CPUs to use to compute the PDs. -1 means 'all CPUs'. + Defaults to 1. + verbose : int + Verbose output during PD computations. Defaults to 0. + ax : Matplotlib axis object, default None + An axis object onto which the plots will be drawn. + line_kw : dict + Dict with keywords passed to the ``pylab.plot`` call. + For one-way partial dependence plots. + contour_kw : dict + Dict with keywords passed to the ``pylab.plot`` call. + For two-way partial dependence plots. + fig_kw : dict + Dict with keywords passed to the figure() call. + Note that all keywords not recognized above will be automatically + included here. + + Returns + ------- + fig : figure + The Matplotlib Figure object. + axs : seq of Axis objects + A seq of Axis objects, one for each subplot. + + Examples + -------- + >>> from sklearn.datasets import make_friedman1 + >>> from sklearn.ensemble import GradientBoostingRegressor + >>> X, y = make_friedman1() + >>> clf = GradientBoostingRegressor(n_estimators=10).fit(X, y) + >>> fig, axs = plot_partial_dependence(clf, X, [0, (0, 1)]) #doctest: +SKIP + ... + """ + import matplotlib.pyplot as plt + from matplotlib import transforms + from matplotlib.ticker import MaxNLocator + from matplotlib.ticker import ScalarFormatter + + if not isinstance(gbrt, BaseGradientBoosting): + raise ValueError('gbrt has to be an instance of BaseGradientBoosting') + if gbrt.estimators_.shape[0] == 0: + raise ValueError('Call %s.fit before partial_dependence' % + gbrt.__class__.__name__) + + # set label_idx for multi-class GBRT + if hasattr(gbrt, 'classes_') and np.size(gbrt.classes_) > 2: + if label is None: + raise ValueError('label is not given for multi-class PDP') + label_idx = np.searchsorted(gbrt.classes_, label) + if gbrt.classes_[label_idx] != label: + raise ValueError('label %s not in ``gbrt.classes_``' % str(label)) + else: + # regression and binary classification + label_idx = 0 + + X = check_array(X, dtype=DTYPE, order='C') + if gbrt.n_features != X.shape[1]: + raise ValueError('X.shape[1] does not match gbrt.n_features') + + if line_kw is None: + line_kw = {'color': 'green'} + if contour_kw is None: + contour_kw = {} + + # convert feature_names to list + if feature_names is None: + # if not feature_names use fx indices as name + feature_names = [str(i) for i in range(gbrt.n_features)] + elif isinstance(feature_names, np.ndarray): + feature_names = feature_names.tolist() + + def convert_feature(fx): + if isinstance(fx, six.string_types): + try: + fx = feature_names.index(fx) + except ValueError: + raise ValueError('Feature %s not in feature_names' % fx) + return fx + + # convert features into a seq of int tuples + tmp_features = [] + for fxs in features: + if isinstance(fxs, (numbers.Integral,) + six.string_types): + fxs = (fxs,) + try: + fxs = np.array([convert_feature(fx) for fx in fxs], dtype=np.int32) + except TypeError: + raise ValueError('features must be either int, str, or tuple ' + 'of int/str') + if not (1 <= np.size(fxs) <= 2): + raise ValueError('target features must be either one or two') + + tmp_features.append(fxs) + + features = tmp_features + + names = [] + try: + for fxs in features: + l = [] + # explicit loop so "i" is bound for exception below + for i in fxs: + l.append(feature_names[i]) + names.append(l) + except IndexError: + raise ValueError('features[i] must be in [0, n_features) ' + 'but was %d' % i) + + # compute PD functions + pd_result = Parallel(n_jobs=n_jobs, verbose=verbose)( + delayed(partial_dependence)(gbrt, fxs, X=X, + grid_resolution=grid_resolution) + for fxs in features) + + # get global min and max values of PD grouped by plot type + pdp_lim = {} + for pdp, axes in pd_result: + min_pd, max_pd = pdp[label_idx].min(), pdp[label_idx].max() + n_fx = len(axes) + old_min_pd, old_max_pd = pdp_lim.get(n_fx, (min_pd, max_pd)) + min_pd = min(min_pd, old_min_pd) + max_pd = max(max_pd, old_max_pd) + pdp_lim[n_fx] = (min_pd, max_pd) + + # create contour levels for two-way plots + if 2 in pdp_lim: + Z_level = np.linspace(*pdp_lim[2], num=8) + + if ax is None: + fig = plt.figure(**fig_kw) + else: + fig = ax.get_figure() + fig.clear() + + n_cols = min(n_cols, len(features)) + n_rows = int(np.ceil(len(features) / float(n_cols))) + axs = [] + for i, fx, name, (pdp, axes) in zip(count(), features, names, + pd_result): + ax = fig.add_subplot(n_rows, n_cols, i + 1) + + if len(axes) == 1: + ax.plot(axes[0], pdp[label_idx].ravel(), **line_kw) + else: + # make contour plot + assert len(axes) == 2 + XX, YY = np.meshgrid(axes[0], axes[1]) + Z = pdp[label_idx].reshape(list(map(np.size, axes))).T + CS = ax.contour(XX, YY, Z, levels=Z_level, linewidths=0.5, + colors='k') + ax.contourf(XX, YY, Z, levels=Z_level, vmax=Z_level[-1], + vmin=Z_level[0], alpha=0.75, **contour_kw) + ax.clabel(CS, fmt='%2.2f', colors='k', fontsize=10, inline=True) + + # plot data deciles + axes labels + deciles = mquantiles(X[:, fx[0]], prob=np.arange(0.1, 1.0, 0.1)) + trans = transforms.blended_transform_factory(ax.transData, + ax.transAxes) + ylim = ax.get_ylim() + ax.vlines(deciles, [0], 0.05, transform=trans, color='k') + ax.set_xlabel(name[0]) + ax.set_ylim(ylim) + + # prevent x-axis ticks from overlapping + ax.xaxis.set_major_locator(MaxNLocator(nbins=6, prune='lower')) + tick_formatter = ScalarFormatter() + tick_formatter.set_powerlimits((-3, 4)) + ax.xaxis.set_major_formatter(tick_formatter) + + if len(axes) > 1: + # two-way PDP - y-axis deciles + labels + deciles = mquantiles(X[:, fx[1]], prob=np.arange(0.1, 1.0, 0.1)) + trans = transforms.blended_transform_factory(ax.transAxes, + ax.transData) + xlim = ax.get_xlim() + ax.hlines(deciles, [0], 0.05, transform=trans, color='k') + ax.set_ylabel(name[1]) + # hline erases xlim + ax.set_xlim(xlim) + else: + ax.set_ylabel('Partial dependence') + + if len(axes) == 1: + ax.set_ylim(pdp_lim[1]) + axs.append(ax) + + fig.subplots_adjust(bottom=0.15, top=0.7, left=0.1, right=0.95, wspace=0.4, + hspace=0.3) + return fig, axs diff --git a/sklearn/ensemble/tests/test_bagging.py b/sklearn/ensemble/tests/test_bagging.py new file mode 100644 index 0000000000000..bc82ac2f9e2be --- /dev/null +++ b/sklearn/ensemble/tests/test_bagging.py @@ -0,0 +1,556 @@ +""" +Testing for the bagging ensemble module (sklearn.ensemble.bagging). +""" + +# Author: Gilles Louppe +# License: BSD 3 clause + +import numpy as np + +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_warns + +from sklearn.dummy import DummyClassifier, DummyRegressor +from sklearn.grid_search import GridSearchCV, ParameterGrid +from sklearn.ensemble import BaggingClassifier, BaggingRegressor +from sklearn.linear_model import Perceptron, LogisticRegression +from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor +from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor +from sklearn.svm import SVC, SVR +from sklearn.pipeline import make_pipeline +from sklearn.feature_selection import SelectKBest +from sklearn.cross_validation import train_test_split +from sklearn.datasets import load_boston, load_iris +from sklearn.utils import check_random_state + +from scipy.sparse import csc_matrix, csr_matrix + +rng = check_random_state(0) + +# also load the iris dataset +# and randomly permute it +iris = load_iris() +perm = rng.permutation(iris.target.size) +iris.data = iris.data[perm] +iris.target = iris.target[perm] + +# also load the boston dataset +# and randomly permute it +boston = load_boston() +perm = rng.permutation(boston.target.size) +boston.data = boston.data[perm] +boston.target = boston.target[perm] + + +def test_classification(): + """Check classification for various parameter settings.""" + rng = check_random_state(0) + X_train, X_test, y_train, y_test = train_test_split(iris.data, + iris.target, + random_state=rng) + grid = ParameterGrid({"max_samples": [0.5, 1.0], + "max_features": [1, 2, 4], + "bootstrap": [True, False], + "bootstrap_features": [True, False]}) + + for base_estimator in [None, + DummyClassifier(), + Perceptron(), + DecisionTreeClassifier(), + KNeighborsClassifier(), + SVC()]: + for params in grid: + BaggingClassifier(base_estimator=base_estimator, + random_state=rng, + **params).fit(X_train, y_train).predict(X_test) + + +def test_sparse_classification(): + """Check classification for various parameter settings on sparse input.""" + + class CustomSVC(SVC): + """SVC variant that records the nature of the training set""" + + def fit(self, X, y): + super(CustomSVC, self).fit(X, y) + self.data_type_ = type(X) + return self + + rng = check_random_state(0) + X_train, X_test, y_train, y_test = train_test_split(iris.data, + iris.target, + random_state=rng) + parameter_sets = [ + {"max_samples": 0.5, + "max_features": 2, + "bootstrap": True, + "bootstrap_features": True}, + {"max_samples": 1.0, + "max_features": 4, + "bootstrap": True, + "bootstrap_features": True}, + {"max_features": 2, + "bootstrap": False, + "bootstrap_features": True}, + {"max_samples": 0.5, + "bootstrap": True, + "bootstrap_features": False}, + ] + + for sparse_format in [csc_matrix, csr_matrix]: + X_train_sparse = sparse_format(X_train) + X_test_sparse = sparse_format(X_test) + for params in parameter_sets: + + # Trained on sparse format + sparse_classifier = BaggingClassifier( + base_estimator=CustomSVC(), + random_state=1, + **params + ).fit(X_train_sparse, y_train) + sparse_results = sparse_classifier.predict(X_test_sparse) + + # Trained on dense format + dense_results = BaggingClassifier( + base_estimator=CustomSVC(), + random_state=1, + **params + ).fit(X_train, y_train).predict(X_test) + + sparse_type = type(X_train_sparse) + types = [i.data_type_ for i in sparse_classifier.estimators_] + + assert_array_equal(sparse_results, dense_results) + assert all([t == sparse_type for t in types]) + + +def test_regression(): + """Check regression for various parameter settings.""" + rng = check_random_state(0) + X_train, X_test, y_train, y_test = train_test_split(boston.data[:50], + boston.target[:50], + random_state=rng) + grid = ParameterGrid({"max_samples": [0.5, 1.0], + "max_features": [0.5, 1.0], + "bootstrap": [True, False], + "bootstrap_features": [True, False]}) + + for base_estimator in [None, + DummyRegressor(), + DecisionTreeRegressor(), + KNeighborsRegressor(), + SVR()]: + for params in grid: + BaggingRegressor(base_estimator=base_estimator, + random_state=rng, + **params).fit(X_train, y_train).predict(X_test) + + +def test_sparse_regression(): + """Check regression for various parameter settings on sparse input.""" + rng = check_random_state(0) + X_train, X_test, y_train, y_test = train_test_split(boston.data[:50], + boston.target[:50], + random_state=rng) + + class CustomSVR(SVR): + """SVC variant that records the nature of the training set""" + + def fit(self, X, y): + super(CustomSVR, self).fit(X, y) + self.data_type_ = type(X) + return self + + parameter_sets = [ + {"max_samples": 0.5, + "max_features": 2, + "bootstrap": True, + "bootstrap_features": True}, + {"max_samples": 1.0, + "max_features": 4, + "bootstrap": True, + "bootstrap_features": True}, + {"max_features": 2, + "bootstrap": False, + "bootstrap_features": True}, + {"max_samples": 0.5, + "bootstrap": True, + "bootstrap_features": False}, + ] + + for sparse_format in [csc_matrix, csr_matrix]: + X_train_sparse = sparse_format(X_train) + X_test_sparse = sparse_format(X_test) + for params in parameter_sets: + + # Trained on sparse format + sparse_classifier = BaggingRegressor( + base_estimator=CustomSVR(), + random_state=1, + **params + ).fit(X_train_sparse, y_train) + sparse_results = sparse_classifier.predict(X_test_sparse) + + # Trained on dense format + dense_results = BaggingRegressor( + base_estimator=CustomSVR(), + random_state=1, + **params + ).fit(X_train, y_train).predict(X_test) + + sparse_type = type(X_train_sparse) + types = [i.data_type_ for i in sparse_classifier.estimators_] + + assert_array_equal(sparse_results, dense_results) + assert all([t == sparse_type for t in types]) + assert_array_equal(sparse_results, dense_results) + + +def test_bootstrap_samples(): + """Test that bootstraping samples generate non-perfect base estimators.""" + rng = check_random_state(0) + X_train, X_test, y_train, y_test = train_test_split(boston.data, + boston.target, + random_state=rng) + + base_estimator = DecisionTreeRegressor().fit(X_train, y_train) + + # without bootstrap, all trees are perfect on the training set + ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), + max_samples=1.0, + bootstrap=False, + random_state=rng).fit(X_train, y_train) + + assert_equal(base_estimator.score(X_train, y_train), + ensemble.score(X_train, y_train)) + + # with bootstrap, trees are no longer perfect on the training set + ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), + max_samples=1.0, + bootstrap=True, + random_state=rng).fit(X_train, y_train) + + assert_greater(base_estimator.score(X_train, y_train), + ensemble.score(X_train, y_train)) + + +def test_bootstrap_features(): + """Test that bootstraping features may generate dupplicate features.""" + rng = check_random_state(0) + X_train, X_test, y_train, y_test = train_test_split(boston.data, + boston.target, + random_state=rng) + + ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), + max_features=1.0, + bootstrap_features=False, + random_state=rng).fit(X_train, y_train) + + for features in ensemble.estimators_features_: + assert_equal(boston.data.shape[1], np.unique(features).shape[0]) + + ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(), + max_features=1.0, + bootstrap_features=True, + random_state=rng).fit(X_train, y_train) + + for features in ensemble.estimators_features_: + assert_greater(boston.data.shape[1], np.unique(features).shape[0]) + + +def test_probability(): + """Predict probabilities.""" + rng = check_random_state(0) + X_train, X_test, y_train, y_test = train_test_split(iris.data, + iris.target, + random_state=rng) + + with np.errstate(divide="ignore", invalid="ignore"): + # Normal case + ensemble = BaggingClassifier(base_estimator=DecisionTreeClassifier(), + random_state=rng).fit(X_train, y_train) + + assert_array_almost_equal(np.sum(ensemble.predict_proba(X_test), + axis=1), + np.ones(len(X_test))) + + assert_array_almost_equal(ensemble.predict_proba(X_test), + np.exp(ensemble.predict_log_proba(X_test))) + + # Degenerate case, where some classes are missing + ensemble = BaggingClassifier(base_estimator=LogisticRegression(), + random_state=rng, + max_samples=5).fit(X_train, y_train) + + assert_array_almost_equal(np.sum(ensemble.predict_proba(X_test), + axis=1), + np.ones(len(X_test))) + + assert_array_almost_equal(ensemble.predict_proba(X_test), + np.exp(ensemble.predict_log_proba(X_test))) + + +def test_oob_score_classification(): + """Check that oob prediction is a good estimation of the generalization + error.""" + rng = check_random_state(0) + X_train, X_test, y_train, y_test = train_test_split(iris.data, + iris.target, + random_state=rng) + + for base_estimator in [DecisionTreeClassifier(), SVC()]: + clf = BaggingClassifier(base_estimator=base_estimator, + n_estimators=100, + bootstrap=True, + oob_score=True, + random_state=rng).fit(X_train, y_train) + + test_score = clf.score(X_test, y_test) + + assert_less(abs(test_score - clf.oob_score_), 0.1) + + # Test with few estimators + assert_warns(UserWarning, + BaggingClassifier(base_estimator=base_estimator, + n_estimators=1, + bootstrap=True, + oob_score=True, + random_state=rng).fit, + X_train, + y_train) + + +def test_oob_score_regression(): + """Check that oob prediction is a good estimation of the generalization + error.""" + rng = check_random_state(0) + X_train, X_test, y_train, y_test = train_test_split(boston.data, + boston.target, + random_state=rng) + + clf = BaggingRegressor(base_estimator=DecisionTreeRegressor(), + n_estimators=50, + bootstrap=True, + oob_score=True, + random_state=rng).fit(X_train, y_train) + + test_score = clf.score(X_test, y_test) + + assert_less(abs(test_score - clf.oob_score_), 0.1) + + # Test with few estimators + assert_warns(UserWarning, + BaggingRegressor(base_estimator=DecisionTreeRegressor(), + n_estimators=1, + bootstrap=True, + oob_score=True, + random_state=rng).fit, + X_train, + y_train) + + +def test_single_estimator(): + """Check singleton ensembles.""" + rng = check_random_state(0) + X_train, X_test, y_train, y_test = train_test_split(boston.data, + boston.target, + random_state=rng) + + clf1 = BaggingRegressor(base_estimator=KNeighborsRegressor(), + n_estimators=1, + bootstrap=False, + bootstrap_features=False, + random_state=rng).fit(X_train, y_train) + + clf2 = KNeighborsRegressor().fit(X_train, y_train) + + assert_array_equal(clf1.predict(X_test), clf2.predict(X_test)) + + +def test_error(): + """Test that it gives proper exception on deficient input.""" + X, y = iris.data, iris.target + base = DecisionTreeClassifier() + + # Test max_samples + assert_raises(ValueError, + BaggingClassifier(base, max_samples=-1).fit, X, y) + assert_raises(ValueError, + BaggingClassifier(base, max_samples=0.0).fit, X, y) + assert_raises(ValueError, + BaggingClassifier(base, max_samples=2.0).fit, X, y) + assert_raises(ValueError, + BaggingClassifier(base, max_samples=1000).fit, X, y) + assert_raises(ValueError, + BaggingClassifier(base, max_samples="foobar").fit, X, y) + + # Test max_features + assert_raises(ValueError, + BaggingClassifier(base, max_features=-1).fit, X, y) + assert_raises(ValueError, + BaggingClassifier(base, max_features=0.0).fit, X, y) + assert_raises(ValueError, + BaggingClassifier(base, max_features=2.0).fit, X, y) + assert_raises(ValueError, + BaggingClassifier(base, max_features=5).fit, X, y) + assert_raises(ValueError, + BaggingClassifier(base, max_features="foobar").fit, X, y) + + # Test support of decision_function + assert_false(hasattr(BaggingClassifier(base).fit(X, y), 'decision_function')) + + +def test_parallel_classification(): + """Check parallel classification.""" + rng = check_random_state(0) + + # Classification + X_train, X_test, y_train, y_test = train_test_split(iris.data, + iris.target, + random_state=rng) + + ensemble = BaggingClassifier(DecisionTreeClassifier(), + n_jobs=3, + random_state=0).fit(X_train, y_train) + + # predict_proba + ensemble.set_params(n_jobs=1) + y1 = ensemble.predict_proba(X_test) + ensemble.set_params(n_jobs=2) + y2 = ensemble.predict_proba(X_test) + assert_array_almost_equal(y1, y2) + + ensemble = BaggingClassifier(DecisionTreeClassifier(), + n_jobs=1, + random_state=0).fit(X_train, y_train) + + y3 = ensemble.predict_proba(X_test) + assert_array_almost_equal(y1, y3) + + # decision_function + ensemble = BaggingClassifier(SVC(), + n_jobs=3, + random_state=0).fit(X_train, y_train) + + ensemble.set_params(n_jobs=1) + decisions1 = ensemble.decision_function(X_test) + ensemble.set_params(n_jobs=2) + decisions2 = ensemble.decision_function(X_test) + assert_array_almost_equal(decisions1, decisions2) + + ensemble = BaggingClassifier(SVC(), + n_jobs=1, + random_state=0).fit(X_train, y_train) + + decisions3 = ensemble.decision_function(X_test) + assert_array_almost_equal(decisions1, decisions3) + + +def test_parallel_regression(): + """Check parallel regression.""" + rng = check_random_state(0) + + X_train, X_test, y_train, y_test = train_test_split(boston.data, + boston.target, + random_state=rng) + + ensemble = BaggingRegressor(DecisionTreeRegressor(), + n_jobs=3, + random_state=0).fit(X_train, y_train) + + ensemble.set_params(n_jobs=1) + y1 = ensemble.predict(X_test) + ensemble.set_params(n_jobs=2) + y2 = ensemble.predict(X_test) + assert_array_almost_equal(y1, y2) + + ensemble = BaggingRegressor(DecisionTreeRegressor(), + n_jobs=1, + random_state=0).fit(X_train, y_train) + + y3 = ensemble.predict(X_test) + assert_array_almost_equal(y1, y3) + + +def test_gridsearch(): + """Check that bagging ensembles can be grid-searched.""" + # Transform iris into a binary classification task + X, y = iris.data, iris.target + y[y == 2] = 1 + + # Grid search with scoring based on decision_function + parameters = {'n_estimators': (1, 2), + 'base_estimator__C': (1, 2)} + + GridSearchCV(BaggingClassifier(SVC()), + parameters, + scoring="roc_auc").fit(X, y) + + +def test_base_estimator(): + """Check base_estimator and its default values.""" + rng = check_random_state(0) + + # Classification + X_train, X_test, y_train, y_test = train_test_split(iris.data, + iris.target, + random_state=rng) + + ensemble = BaggingClassifier(None, + n_jobs=3, + random_state=0).fit(X_train, y_train) + + assert_true(isinstance(ensemble.base_estimator_, DecisionTreeClassifier)) + + ensemble = BaggingClassifier(DecisionTreeClassifier(), + n_jobs=3, + random_state=0).fit(X_train, y_train) + + assert_true(isinstance(ensemble.base_estimator_, DecisionTreeClassifier)) + + ensemble = BaggingClassifier(Perceptron(), + n_jobs=3, + random_state=0).fit(X_train, y_train) + + assert_true(isinstance(ensemble.base_estimator_, Perceptron)) + + # Regression + X_train, X_test, y_train, y_test = train_test_split(boston.data, + boston.target, + random_state=rng) + + ensemble = BaggingRegressor(None, + n_jobs=3, + random_state=0).fit(X_train, y_train) + + assert_true(isinstance(ensemble.base_estimator_, DecisionTreeRegressor)) + + ensemble = BaggingRegressor(DecisionTreeRegressor(), + n_jobs=3, + random_state=0).fit(X_train, y_train) + + assert_true(isinstance(ensemble.base_estimator_, DecisionTreeRegressor)) + + ensemble = BaggingRegressor(SVR(), + n_jobs=3, + random_state=0).fit(X_train, y_train) + assert_true(isinstance(ensemble.base_estimator_, SVR)) + + +def test_bagging_with_pipeline(): + estimator = BaggingClassifier(make_pipeline(SelectKBest(k=1), + DecisionTreeClassifier()), + max_features=2) + estimator.fit(iris.data, iris.target) + + +if __name__ == "__main__": + import nose + nose.runmodule() diff --git a/sklearn/ensemble/tests/test_base.py b/sklearn/ensemble/tests/test_base.py index c469ae4a69ba8..9a1765819b1aa 100644 --- a/sklearn/ensemble/tests/test_base.py +++ b/sklearn/ensemble/tests/test_base.py @@ -3,19 +3,24 @@ """ # Authors: Gilles Louppe -# License: BSD 3 +# License: BSD 3 clause from numpy.testing import assert_equal -from nose.tools import assert_raises, assert_true +from nose.tools import assert_true -from sklearn.ensemble import BaseEnsemble -from sklearn.tree import DecisionTreeClassifier +from sklearn.utils.testing import assert_raise_message +from sklearn.datasets import load_iris +from sklearn.ensemble import BaggingClassifier +from sklearn.linear_model import Perceptron def test_base(): """Check BaseEnsemble methods.""" - tree = DecisionTreeClassifier() - ensemble = BaseEnsemble(base_estimator=tree, n_estimators=3) + ensemble = BaggingClassifier(base_estimator=Perceptron(), n_estimators=3) + + iris = load_iris() + ensemble.fit(iris.data, iris.target) + ensemble.estimators_ = [] # empty the list and create estimators manually ensemble._make_estimator() ensemble._make_estimator() @@ -25,18 +30,14 @@ def test_base(): assert_equal(3, len(ensemble)) assert_equal(3, len(ensemble.estimators_)) - assert_true(isinstance(ensemble[0], DecisionTreeClassifier)) - - -def test_error(): - """Check that proper errors are triggered.""" - def instantiate(class_name, **params): - return class_name(**params) + assert_true(isinstance(ensemble[0], Perceptron)) - base_estimator = object() - assert_raises(TypeError, instantiate, class_name=BaseEnsemble, - base_estimator=base_estimator, n_estimators=1) - base_estimator = DecisionTreeClassifier() - assert_raises(ValueError, instantiate, class_name=BaseEnsemble, - base_estimator=base_estimator, n_estimators=-1) +def test_base_zero_n_estimators(): + """Check that instantiating a BaseEnsemble with n_estimators<=0 raises + a ValueError.""" + ensemble = BaggingClassifier(base_estimator=Perceptron(), n_estimators=0) + iris = load_iris() + assert_raise_message(ValueError, + "n_estimators must be greater than zero, got 0.", + ensemble.fit, iris.data, iris.target) diff --git a/sklearn/ensemble/tests/test_forest.py b/sklearn/ensemble/tests/test_forest.py index 5229172599724..cd0697af20500 100644 --- a/sklearn/ensemble/tests/test_forest.py +++ b/sklearn/ensemble/tests/test_forest.py @@ -2,24 +2,42 @@ Testing for the forest module (sklearn.ensemble.forest). """ -# Authors: Gilles Louppe, Brian Holt -# License: BSD 3 +# Authors: Gilles Louppe, +# Brian Holt, +# Andreas Mueller, +# Arnaud Joly +# License: BSD 3 clause + +import pickle +from collections import defaultdict +from itertools import product import numpy as np -from numpy.testing import assert_array_equal -from numpy.testing import assert_array_almost_equal -from numpy.testing import assert_equal -from numpy.testing import assert_almost_equal -from nose.tools import assert_true +from scipy.sparse import csr_matrix, csc_matrix, coo_matrix +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_false, assert_true from sklearn.utils.testing import assert_less, assert_greater +from sklearn.utils.testing import assert_greater_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import ignore_warnings -from sklearn.grid_search import GridSearchCV -from sklearn.ensemble import RandomForestClassifier -from sklearn.ensemble import RandomForestRegressor +from sklearn import datasets +from sklearn.decomposition import TruncatedSVD from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import ExtraTreesRegressor -from sklearn import datasets +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import RandomForestRegressor +from sklearn.ensemble import RandomTreesEmbedding +from sklearn.grid_search import GridSearchCV +from sklearn.svm import LinearSVC +from sklearn.utils.validation import check_random_state + +from sklearn.tree.tree import SPARSE_SPLITTERS # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] @@ -30,7 +48,7 @@ # also load the iris dataset # and randomly permute it iris = datasets.load_iris() -rng = np.random.RandomState(0) +rng = check_random_state(0) perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] @@ -42,326 +60,920 @@ boston.data = boston.data[perm] boston.target = boston.target[perm] +FOREST_CLASSIFIERS = { + "ExtraTreesClassifier": ExtraTreesClassifier, + "RandomForestClassifier": RandomForestClassifier, +} -def test_classification_toy(): +FOREST_REGRESSORS = { + "ExtraTreesRegressor": ExtraTreesRegressor, + "RandomForestRegressor": RandomForestRegressor, +} + +FOREST_TRANSFORMERS = { + "RandomTreesEmbedding": RandomTreesEmbedding, +} + +FOREST_ESTIMATORS = dict() +FOREST_ESTIMATORS.update(FOREST_CLASSIFIERS) +FOREST_ESTIMATORS.update(FOREST_REGRESSORS) +FOREST_ESTIMATORS.update(FOREST_TRANSFORMERS) + + +def check_classification_toy(name): """Check classification on a toy dataset.""" - # Random forest - clf = RandomForestClassifier(n_estimators=10, random_state=1) - clf.fit(X, y) - assert_array_equal(clf.predict(T), true_result) - assert_equal(10, len(clf)) + ForestClassifier = FOREST_CLASSIFIERS[name] - clf = RandomForestClassifier(n_estimators=10, max_features=1, - random_state=1) + clf = ForestClassifier(n_estimators=10, random_state=1) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result) assert_equal(10, len(clf)) - # Extra-trees - clf = ExtraTreesClassifier(n_estimators=10, random_state=1) + clf = ForestClassifier(n_estimators=10, max_features=1, random_state=1) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result) assert_equal(10, len(clf)) - clf = ExtraTreesClassifier(n_estimators=10, max_features=1, - random_state=1) - clf.fit(X, y) - assert_array_equal(clf.predict(T), true_result) - assert_equal(10, len(clf)) + # also test apply + leaf_indices = clf.apply(X) + assert_equal(leaf_indices.shape, (len(X), clf.n_estimators)) -def test_iris(): +def test_classification_toy(): + for name in FOREST_CLASSIFIERS: + yield check_classification_toy, name + + +def check_iris_criterion(name, criterion): """Check consistency on dataset iris.""" - for c in ("gini", "entropy"): - # Random forest - clf = RandomForestClassifier(n_estimators=10, criterion=c, - random_state=1) - clf.fit(iris.data, iris.target) - score = clf.score(iris.data, iris.target) - assert score > 0.9, "Failed with criterion %s and score = %f" % (c, - score) + ForestClassifier = FOREST_CLASSIFIERS[name] - clf = RandomForestClassifier(n_estimators=10, criterion=c, - max_features=2, random_state=1) - clf.fit(iris.data, iris.target) - score = clf.score(iris.data, iris.target) - assert score > 0.5, "Failed with criterion %s and score = %f" % (c, - score) + clf = ForestClassifier(n_estimators=10, criterion=criterion, + random_state=1) + clf.fit(iris.data, iris.target) + score = clf.score(iris.data, iris.target) + assert_greater(score, 0.9, "Failed with criterion %s and score = %f" + % (criterion, score)) - # Extra-trees - clf = ExtraTreesClassifier(n_estimators=10, criterion=c, - random_state=1) - clf.fit(iris.data, iris.target) - score = clf.score(iris.data, iris.target) - assert score > 0.9, "Failed with criterion %s and score = %f" % (c, - score) + clf = ForestClassifier(n_estimators=10, criterion=criterion, + max_features=2, random_state=1) + clf.fit(iris.data, iris.target) + score = clf.score(iris.data, iris.target) + assert_greater(score, 0.5, "Failed with criterion %s and score = %f" + % (criterion, score)) - clf = ExtraTreesClassifier(n_estimators=10, criterion=c, - max_features=2, random_state=1) - clf.fit(iris.data, iris.target) - score = clf.score(iris.data, iris.target) - assert score > 0.9, "Failed with criterion %s and score = %f" % (c, - score) +def test_iris(): + for name, criterion in product(FOREST_CLASSIFIERS, ("gini", "entropy")): + yield check_iris_criterion, name, criterion -def test_boston(): + +def check_boston_criterion(name, criterion): """Check consistency on dataset boston house prices.""" - for c in ("mse",): - # Random forest - clf = RandomForestRegressor(n_estimators=5, criterion=c, - random_state=1) - clf.fit(boston.data, boston.target) - score = clf.score(boston.data, boston.target) - assert score < 3, ("Failed with max_features=None, " - "criterion %s and score = %f" % (c, score)) - - clf = RandomForestRegressor(n_estimators=5, criterion=c, - max_features=6, random_state=1) - clf.fit(boston.data, boston.target) - score = clf.score(boston.data, boston.target) - assert score < 3, ("Failed with max_features=None, " - "criterion %s and score = %f" % (c, score)) - - # Extra-trees - clf = ExtraTreesRegressor(n_estimators=5, criterion=c, random_state=1) - clf.fit(boston.data, boston.target) - score = clf.score(boston.data, boston.target) - assert score < 3, ("Failed with max_features=None, " - "criterion %s and score = %f" % (c, score)) - - clf = ExtraTreesRegressor(n_estimators=5, criterion=c, max_features=6, - random_state=1) - clf.fit(boston.data, boston.target) - score = clf.score(boston.data, boston.target) - assert score < 3, ("Failed with max_features=None, " - "criterion %s and score = %f" % (c, score)) + ForestRegressor = FOREST_REGRESSORS[name] + clf = ForestRegressor(n_estimators=5, criterion=criterion, random_state=1) + clf.fit(boston.data, boston.target) + score = clf.score(boston.data, boston.target) + assert_greater(score, 0.95, "Failed with max_features=None, criterion %s " + "and score = %f" % (criterion, score)) -def test_probability(): + clf = ForestRegressor(n_estimators=5, criterion=criterion, + max_features=6, random_state=1) + clf.fit(boston.data, boston.target) + score = clf.score(boston.data, boston.target) + assert_greater(score, 0.95, "Failed with max_features=6, criterion %s " + "and score = %f" % (criterion, score)) + + +def test_boston(): + for name, criterion in product(FOREST_REGRESSORS, ("mse", )): + yield check_boston_criterion, name, criterion + + +def check_regressor_attributes(name): + """Regression models should not have a classes_ attribute.""" + r = FOREST_REGRESSORS[name](random_state=0) + assert_false(hasattr(r, "classes_")) + assert_false(hasattr(r, "n_classes_")) + + r.fit([[1, 2, 3], [4, 5, 6]], [1, 2]) + assert_false(hasattr(r, "classes_")) + assert_false(hasattr(r, "n_classes_")) + + +def test_regressor_attributes(): + for name in FOREST_REGRESSORS: + yield check_regressor_attributes, name + + +def check_probability(name): """Predict probabilities.""" - olderr = np.seterr(divide="ignore") + ForestClassifier = FOREST_CLASSIFIERS[name] + with np.errstate(divide="ignore"): + clf = ForestClassifier(n_estimators=10, random_state=1, max_features=1, + max_depth=1) + clf.fit(iris.data, iris.target) + assert_array_almost_equal(np.sum(clf.predict_proba(iris.data), axis=1), + np.ones(iris.data.shape[0])) + assert_array_almost_equal(clf.predict_proba(iris.data), + np.exp(clf.predict_log_proba(iris.data))) - # Random forest - clf = RandomForestClassifier(n_estimators=10, random_state=1, - max_features=1, max_depth=1) - clf.fit(iris.data, iris.target) - assert_array_almost_equal(np.sum(clf.predict_proba(iris.data), axis=1), - np.ones(iris.data.shape[0])) - assert_array_almost_equal(clf.predict_proba(iris.data), - np.exp(clf.predict_log_proba(iris.data))) - - # Extra-trees - clf = ExtraTreesClassifier(n_estimators=10, random_state=1, max_features=1, - max_depth=1) - clf.fit(iris.data, iris.target) - assert_array_almost_equal(np.sum(clf.predict_proba(iris.data), axis=1), - np.ones(iris.data.shape[0])) - assert_array_almost_equal(clf.predict_proba(iris.data), - np.exp(clf.predict_log_proba(iris.data))) - np.seterr(**olderr) +def test_probability(): + for name in FOREST_CLASSIFIERS: + yield check_probability, name -def test_importances(): +def check_importances(name, X, y): """Check variable importances.""" - X, y = datasets.make_classification(n_samples=1000, - n_features=10, - n_informative=3, - n_redundant=0, - n_repeated=0, - shuffle=False, + + ForestClassifier = FOREST_CLASSIFIERS[name] + for n_jobs in [1, 2]: + clf = ForestClassifier(n_estimators=10, n_jobs=n_jobs) + clf.fit(X, y) + importances = clf.feature_importances_ + n_important = np.sum(importances > 0.1) + assert_equal(importances.shape[0], 10) + assert_equal(n_important, 3) + + X_new = clf.transform(X, threshold="mean") + assert_less(0 < X_new.shape[1], X.shape[1]) + + # Check with sample weights + sample_weight = np.ones(y.shape) + sample_weight[y == 1] *= 100 + + clf = ForestClassifier(n_estimators=50, n_jobs=n_jobs, random_state=0) + clf.fit(X, y, sample_weight=sample_weight) + importances = clf.feature_importances_ + assert_true(np.all(importances >= 0.0)) + + clf = ForestClassifier(n_estimators=50, n_jobs=n_jobs, random_state=0) + clf.fit(X, y, sample_weight=3 * sample_weight) + importances_bis = clf.feature_importances_ + assert_almost_equal(importances, importances_bis) + + +def test_importances(): + X, y = datasets.make_classification(n_samples=1000, n_features=10, + n_informative=3, n_redundant=0, + n_repeated=0, shuffle=False, random_state=0) - clf = RandomForestClassifier(n_estimators=10, compute_importances=True) - clf.fit(X, y) - importances = clf.feature_importances_ - n_important = sum(importances > 0.1) + for name in FOREST_CLASSIFIERS: + yield check_importances, name, X, y - assert_equal(importances.shape[0], 10) - assert_equal(n_important, 3) - X_new = clf.transform(X, threshold="mean") - assert_less(0 < X_new.shape[1], X.shape[1]) +def check_unfitted_feature_importances(name): + assert_raises(ValueError, getattr, FOREST_ESTIMATORS[name](random_state=0), + "feature_importances_") - clf = RandomForestClassifier(n_estimators=10) - clf.fit(X, y) - assert_true(clf.feature_importances_ is None) +def test_unfitted_feature_importances(): + for name in FOREST_ESTIMATORS: + yield check_unfitted_feature_importances, name -def test_oob_score_classification(): - """Check that oob prediction is as acurate as - usual prediction on the training set. - Not really a good test that prediction is independent.""" - clf = RandomForestClassifier(oob_score=True, random_state=rng) - clf.fit(X, y) - training_score = clf.score(X, y) - assert_almost_equal(training_score, clf.oob_score_) +def check_oob_score(name, X, y, n_estimators=20): + """Check that oob prediction is a good estimation of the generalization + error.""" + # Proper behavior + est = FOREST_ESTIMATORS[name](oob_score=True, random_state=0, + n_estimators=n_estimators, bootstrap=True) + n_samples = X.shape[0] + est.fit(X[:n_samples // 2, :], y[:n_samples // 2]) + test_score = est.score(X[n_samples // 2:, :], y[n_samples // 2:]) -def test_oob_score_regression(): - """Check that oob prediction is pessimistic estimate. - Not really a good test that prediction is independent.""" - clf = RandomForestRegressor(n_estimators=50, oob_score=True, - random_state=rng) - n_samples = boston.data.shape[0] - clf.fit(boston.data[:n_samples / 2, :], boston.target[:n_samples / 2]) - test_score = clf.score(boston.data[n_samples / 2:, :], - boston.target[n_samples / 2:]) - assert_greater(test_score, clf.oob_score_) - assert_greater(clf.oob_score_, .8) + if name in FOREST_CLASSIFIERS: + assert_less(abs(test_score - est.oob_score_), 0.1) + else: + assert_greater(test_score, est.oob_score_) + assert_greater(est.oob_score_, .8) + # Check warning if not enough estimators + with np.errstate(divide="ignore", invalid="ignore"): + est = FOREST_ESTIMATORS[name](oob_score=True, random_state=0, + n_estimators=1, bootstrap=True) + assert_warns(UserWarning, est.fit, X, y) -def test_gridsearch(): - """Check that base trees can be grid-searched.""" - # Random forest - forest = RandomForestClassifier() - parameters = {'n_estimators': (1, 2), - 'max_depth': (1, 2)} - clf = GridSearchCV(forest, parameters) - clf.fit(iris.data, iris.target) - # Extra-trees - forest = ExtraTreesClassifier() - parameters = {'n_estimators': (1, 2), - 'max_depth': (1, 2)} - clf = GridSearchCV(forest, parameters) - clf.fit(iris.data, iris.target) +def test_oob_score(): + for name in FOREST_CLASSIFIERS: + yield check_oob_score, name, iris.data, iris.target + # non-contiguous targets in classification + yield check_oob_score, name, iris.data, iris.target * 2 + 1 -def test_parallel(): - """Check parallel computations.""" - # Classification - forest = RandomForestClassifier(n_estimators=10, n_jobs=3, random_state=0) + for name in FOREST_REGRESSORS: + yield check_oob_score, name, boston.data, boston.target, 50 - forest.fit(iris.data, iris.target) - assert_true(10 == len(forest)) - forest.set_params(n_jobs=1) - y1 = forest.predict(iris.data) - forest.set_params(n_jobs=2) - y2 = forest.predict(iris.data) - assert_array_equal(y1, y2) +def check_oob_score_raise_error(name): + ForestEstimator = FOREST_ESTIMATORS[name] + + if name in FOREST_TRANSFORMERS: + for oob_score in [True, False]: + assert_raises(TypeError, ForestEstimator, oob_score=oob_score) + + assert_raises(NotImplementedError, ForestEstimator()._set_oob_score, + X, y) + + else: + # Unfitted / no bootstrap / no oob_score + for oob_score, bootstrap in [(True, False), (False, True), + (False, False)]: + est = ForestEstimator(oob_score=oob_score, bootstrap=bootstrap, + random_state=0) + assert_false(hasattr(est, "oob_score_")) - # Regression - forest = RandomForestRegressor(n_estimators=10, n_jobs=3, random_state=0) + # No bootstrap + assert_raises(ValueError, ForestEstimator(oob_score=True, + bootstrap=False).fit, X, y) - forest.fit(boston.data, boston.target) - assert_true(10 == len(forest)) + +def test_oob_score_raise_error(): + for name in FOREST_ESTIMATORS: + yield check_oob_score_raise_error, name + + +def check_gridsearch(name): + forest = FOREST_CLASSIFIERS[name]() + clf = GridSearchCV(forest, {'n_estimators': (1, 2), 'max_depth': (1, 2)}) + clf.fit(iris.data, iris.target) + + +def test_gridsearch(): + """Check that base trees can be grid-searched.""" + for name in FOREST_CLASSIFIERS: + yield check_gridsearch, name + + +def check_parallel(name, X, y): + """Check parallel computations in classification""" + ForestEstimator = FOREST_ESTIMATORS[name] + forest = ForestEstimator(n_estimators=10, n_jobs=3, random_state=0) + + forest.fit(X, y) + assert_equal(len(forest), 10) forest.set_params(n_jobs=1) - y1 = forest.predict(boston.data) + y1 = forest.predict(X) forest.set_params(n_jobs=2) - y2 = forest.predict(boston.data) + y2 = forest.predict(X) assert_array_almost_equal(y1, y2, 3) - # Use all cores on the classification dataset - forest = RandomForestClassifier(n_jobs=-1) - forest.fit(iris.data, iris.target) +def test_parallel(): + for name in FOREST_CLASSIFIERS: + yield check_parallel, name, iris.data, iris.target -def test_pickle(): + for name in FOREST_REGRESSORS: + yield check_parallel, name, boston.data, boston.target + + +def check_pickle(name, X, y): """Check pickability.""" - import pickle - # Random forest - obj = RandomForestClassifier(random_state=0) - obj.fit(iris.data, iris.target) - score = obj.score(iris.data, iris.target) - s = pickle.dumps(obj) + ForestEstimator = FOREST_ESTIMATORS[name] + obj = ForestEstimator(random_state=0) + obj.fit(X, y) + score = obj.score(X, y) + pickle_object = pickle.dumps(obj) - obj2 = pickle.loads(s) + obj2 = pickle.loads(pickle_object) assert_equal(type(obj2), obj.__class__) - score2 = obj2.score(iris.data, iris.target) - assert_true(score == score2) + score2 = obj2.score(X, y) + assert_equal(score, score2) - obj = RandomForestRegressor(random_state=0) - obj.fit(boston.data, boston.target) - score = obj.score(boston.data, boston.target) - s = pickle.dumps(obj) - obj2 = pickle.loads(s) - assert_equal(type(obj2), obj.__class__) - score2 = obj2.score(boston.data, boston.target) - assert_true(score == score2) +def test_pickle(): + for name in FOREST_CLASSIFIERS: + yield check_pickle, name, iris.data[::2], iris.target[::2] - # Extra-trees - obj = ExtraTreesClassifier(random_state=0) - obj.fit(iris.data, iris.target) - score = obj.score(iris.data, iris.target) - s = pickle.dumps(obj) + for name in FOREST_REGRESSORS: + yield check_pickle, name, boston.data[::2], boston.target[::2] - obj2 = pickle.loads(s) - assert_equal(type(obj2), obj.__class__) - score2 = obj2.score(iris.data, iris.target) - assert_true(score == score2) - obj = ExtraTreesRegressor(random_state=0) - obj.fit(boston.data, boston.target) - score = obj.score(boston.data, boston.target) - s = pickle.dumps(obj) +def check_multioutput(name): + """Check estimators on multi-output problems.""" - obj2 = pickle.loads(s) - assert_equal(type(obj2), obj.__class__) - score2 = obj2.score(boston.data, boston.target) - assert_true(score == score2) + X_train = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1], [-2, 1], + [-1, 1], [-1, 2], [2, -1], [1, -1], [1, -2]] + y_train = [[-1, 0], [-1, 0], [-1, 0], [1, 1], [1, 1], [1, 1], [-1, 2], + [-1, 2], [-1, 2], [1, 3], [1, 3], [1, 3]] + X_test = [[-1, -1], [1, 1], [-1, 1], [1, -1]] + y_test = [[-1, 0], [1, 1], [-1, 2], [1, 3]] + + est = FOREST_ESTIMATORS[name](random_state=0, bootstrap=False) + y_pred = est.fit(X_train, y_train).predict(X_test) + assert_array_almost_equal(y_pred, y_test) + + if name in FOREST_CLASSIFIERS: + with np.errstate(divide="ignore"): + proba = est.predict_proba(X_test) + assert_equal(len(proba), 2) + assert_equal(proba[0].shape, (4, 2)) + assert_equal(proba[1].shape, (4, 4)) + + log_proba = est.predict_log_proba(X_test) + assert_equal(len(log_proba), 2) + assert_equal(log_proba[0].shape, (4, 2)) + assert_equal(log_proba[1].shape, (4, 4)) def test_multioutput(): - """Check estimators on multi-output problems.""" - olderr = np.seterr(divide="ignore") - - X = [[-2, -1], - [-1, -1], - [-1, -2], - [1, 1], - [1, 2], - [2, 1], - [-2, 1], - [-1, 1], - [-1, 2], - [2, -1], - [1, -1], - [1, -2]] - - y = [[-1, 0], - [-1, 0], - [-1, 0], - [1, 1], - [1, 1], - [1, 1], - [-1, 2], - [-1, 2], - [-1, 2], - [1, 3], - [1, 3], - [1, 3]] - - T = [[-1, -1], [1, 1], [-1, 1], [1, -1]] - y_true = [[-1, 0], [1, 1], [-1, 2], [1, 3]] - - # toy classification problem - clf = ExtraTreesClassifier(random_state=0) - y_hat = clf.fit(X, y).predict(T) - assert_array_equal(y_hat, y_true) - assert_equal(y_hat.shape, (4, 2)) - - proba = clf.predict_proba(T) - assert_equal(len(proba), 2) - assert_equal(proba[0].shape, (4, 2)) - assert_equal(proba[1].shape, (4, 4)) - - log_proba = clf.predict_log_proba(T) - assert_equal(len(log_proba), 2) - assert_equal(log_proba[0].shape, (4, 2)) - assert_equal(log_proba[1].shape, (4, 4)) - - # toy regression problem - clf = ExtraTreesRegressor(random_state=5) - y_hat = clf.fit(X, y).predict(T) - assert_almost_equal(y_hat, y_true) - assert_equal(y_hat.shape, (4, 2)) - - np.seterr(**olderr) + for name in FOREST_CLASSIFIERS: + yield check_multioutput, name + + for name in FOREST_REGRESSORS: + yield check_multioutput, name + + +def check_classes_shape(name): + """Test that n_classes_ and classes_ have proper shape.""" + ForestClassifier = FOREST_CLASSIFIERS[name] + + # Classification, single output + clf = ForestClassifier(random_state=0).fit(X, y) + + assert_equal(clf.n_classes_, 2) + assert_array_equal(clf.classes_, [-1, 1]) + + # Classification, multi-output + _y = np.vstack((y, np.array(y) * 2)).T + clf = ForestClassifier(random_state=0).fit(X, _y) + + assert_array_equal(clf.n_classes_, [2, 2]) + assert_array_equal(clf.classes_, [[-1, 1], [-2, 2]]) + + +def test_classes_shape(): + for name in FOREST_CLASSIFIERS: + yield check_classes_shape, name + + +def test_random_trees_dense_type(): + ''' + Test that the `sparse_output` parameter of RandomTreesEmbedding + works by returning a dense array. + ''' + + # Create the RTE with sparse=False + hasher = RandomTreesEmbedding(n_estimators=10, sparse_output=False) + X, y = datasets.make_circles(factor=0.5) + X_transformed = hasher.fit_transform(X) + + # Assert that type is ndarray, not scipy.sparse.csr.csr_matrix + assert_equal(type(X_transformed), np.ndarray) + + +def test_random_trees_dense_equal(): + ''' + Test that the `sparse_output` parameter of RandomTreesEmbedding + works by returning the same array for both argument + values. + ''' + + # Create the RTEs + hasher_dense = RandomTreesEmbedding(n_estimators=10, sparse_output=False, + random_state=0) + hasher_sparse = RandomTreesEmbedding(n_estimators=10, sparse_output=True, + random_state=0) + X, y = datasets.make_circles(factor=0.5) + X_transformed_dense = hasher_dense.fit_transform(X) + X_transformed_sparse = hasher_sparse.fit_transform(X) + + # Assert that dense and sparse hashers have same array. + assert_array_equal(X_transformed_sparse.toarray(), X_transformed_dense) + + +def test_random_hasher(): + # test random forest hashing on circles dataset + # make sure that it is linearly separable. + # even after projected to two SVD dimensions + # Note: Not all random_states produce perfect results. + hasher = RandomTreesEmbedding(n_estimators=30, random_state=1) + X, y = datasets.make_circles(factor=0.5) + X_transformed = hasher.fit_transform(X) + + # test fit and transform: + hasher = RandomTreesEmbedding(n_estimators=30, random_state=1) + assert_array_equal(hasher.fit(X).transform(X).toarray(), + X_transformed.toarray()) + + # one leaf active per data point per forest + assert_equal(X_transformed.shape[0], X.shape[0]) + assert_array_equal(X_transformed.sum(axis=1), hasher.n_estimators) + svd = TruncatedSVD(n_components=2) + X_reduced = svd.fit_transform(X_transformed) + linear_clf = LinearSVC() + linear_clf.fit(X_reduced, y) + assert_equal(linear_clf.score(X_reduced, y), 1.) + + +def test_random_hasher_sparse_data(): + X, y = datasets.make_multilabel_classification(return_indicator=True, + random_state=0) + hasher = RandomTreesEmbedding(n_estimators=30, random_state=1) + X_transformed = hasher.fit_transform(X) + X_transformed_sparse = hasher.fit_transform(csc_matrix(X)) + assert_array_equal(X_transformed_sparse.toarray(), X_transformed.toarray()) + + +def test_parallel_train(): + rng = check_random_state(12321) + n_samples, n_features = 80, 30 + X_train = rng.randn(n_samples, n_features) + y_train = rng.randint(0, 2, n_samples) + + clfs = [ + RandomForestClassifier(n_estimators=20, n_jobs=n_jobs, + random_state=12345).fit(X_train, y_train) + for n_jobs in [1, 2, 3, 8, 16, 32] + ] + + X_test = rng.randn(n_samples, n_features) + probas = [clf.predict_proba(X_test) for clf in clfs] + for proba1, proba2 in zip(probas, probas[1:]): + assert_array_almost_equal(proba1, proba2) + + +def test_distribution(): + rng = check_random_state(12321) + + # Single variable with 4 values + X = rng.randint(0, 4, size=(1000, 1)) + y = rng.rand(1000) + n_trees = 500 + + clf = ExtraTreesRegressor(n_estimators=n_trees, random_state=42).fit(X, y) + + uniques = defaultdict(int) + for tree in clf.estimators_: + tree = "".join(("%d,%d/" % (f, int(t)) if f >= 0 else "-") + for f, t in zip(tree.tree_.feature, + tree.tree_.threshold)) + + uniques[tree] += 1 + + uniques = sorted([(1. * count / n_trees, tree) + for tree, count in uniques.items()]) + + # On a single variable problem where X_0 has 4 equiprobable values, there + # are 5 ways to build a random tree. The more compact (0,1/0,0/--0,2/--) of + # them has probability 1/3 while the 4 others have probability 1/6. + + assert_equal(len(uniques), 5) + assert_greater(0.20, uniques[0][0]) # Rough approximation of 1/6. + assert_greater(0.20, uniques[1][0]) + assert_greater(0.20, uniques[2][0]) + assert_greater(0.20, uniques[3][0]) + assert_greater(uniques[4][0], 0.3) + assert_equal(uniques[4][1], "0,1/0,0/--0,2/--") + + # Two variables, one with 2 values, one with 3 values + X = np.empty((1000, 2)) + X[:, 0] = np.random.randint(0, 2, 1000) + X[:, 1] = np.random.randint(0, 3, 1000) + y = rng.rand(1000) + + clf = ExtraTreesRegressor(n_estimators=100, max_features=1, + random_state=1).fit(X, y) + + uniques = defaultdict(int) + for tree in clf.estimators_: + tree = "".join(("%d,%d/" % (f, int(t)) if f >= 0 else "-") + for f, t in zip(tree.tree_.feature, + tree.tree_.threshold)) + + uniques[tree] += 1 + + uniques = [(count, tree) for tree, count in uniques.items()] + assert_equal(len(uniques), 8) + + +def check_max_leaf_nodes_max_depth(name, X, y): + """Test precedence of max_leaf_nodes over max_depth. """ + ForestEstimator = FOREST_ESTIMATORS[name] + est = ForestEstimator(max_depth=1, max_leaf_nodes=4, + n_estimators=1).fit(X, y) + assert_greater(est.estimators_[0].tree_.max_depth, 1) + + est = ForestEstimator(max_depth=1, n_estimators=1).fit(X, y) + assert_equal(est.estimators_[0].tree_.max_depth, 1) + + +def test_max_leaf_nodes_max_depth(): + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + for name in FOREST_ESTIMATORS: + yield check_max_leaf_nodes_max_depth, name, X, y + + +def check_min_samples_leaf(name, X, y): + """Test if leaves contain more than leaf_count training examples""" + ForestEstimator = FOREST_ESTIMATORS[name] + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes in (None, 1000): + est = ForestEstimator(min_samples_leaf=5, + max_leaf_nodes=max_leaf_nodes, + random_state=0) + est.fit(X, y) + out = est.estimators_[0].tree_.apply(X) + node_counts = np.bincount(out) + # drop inner nodes + leaf_count = node_counts[node_counts != 0] + assert_greater(np.min(leaf_count), 4, + "Failed with {0}".format(name)) + + +def test_min_samples_leaf(): + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + X = X.astype(np.float32) + for name in FOREST_ESTIMATORS: + yield check_min_samples_leaf, name, X, y + + +def check_min_weight_fraction_leaf(name, X, y): + """Test if leaves contain at least min_weight_fraction_leaf of the + training set""" + ForestEstimator = FOREST_ESTIMATORS[name] + rng = np.random.RandomState(0) + weights = rng.rand(X.shape[0]) + total_weight = np.sum(weights) + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes in (None, 1000): + for frac in np.linspace(0, 0.5, 6): + est = ForestEstimator(min_weight_fraction_leaf=frac, + max_leaf_nodes=max_leaf_nodes, + random_state=0) + if isinstance(est, (RandomForestClassifier, + RandomForestRegressor)): + est.bootstrap = False + est.fit(X, y, sample_weight=weights) + out = est.estimators_[0].tree_.apply(X) + node_weights = np.bincount(out, weights=weights) + # drop inner nodes + leaf_weights = node_weights[node_weights != 0] + assert_greater_equal( + np.min(leaf_weights), + total_weight * est.min_weight_fraction_leaf, + "Failed with {0} " + "min_weight_fraction_leaf={1}".format( + name, est.min_weight_fraction_leaf)) + + +def test_min_weight_fraction_leaf(): + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + X = X.astype(np.float32) + for name in FOREST_ESTIMATORS: + yield check_min_weight_fraction_leaf, name, X, y + + +def check_sparse_input(name, X, X_sparse, y): + ForestEstimator = FOREST_ESTIMATORS[name] + + dense = ForestEstimator(random_state=0, max_depth=2).fit(X, y) + sparse = ForestEstimator(random_state=0, max_depth=2).fit(X_sparse, y) + + assert_array_almost_equal(sparse.apply(X), dense.apply(X)) + + if name in FOREST_CLASSIFIERS or name in FOREST_REGRESSORS: + assert_array_almost_equal(sparse.predict(X), dense.predict(X)) + assert_array_almost_equal(sparse.feature_importances_, + dense.feature_importances_) + + if name in FOREST_CLASSIFIERS: + assert_array_almost_equal(sparse.predict_proba(X), + dense.predict_proba(X)) + assert_array_almost_equal(sparse.predict_log_proba(X), + dense.predict_log_proba(X)) + + if name in FOREST_TRANSFORMERS: + assert_array_almost_equal(sparse.transform(X).toarray(), + dense.transform(X).toarray()) + assert_array_almost_equal(sparse.fit_transform(X).toarray(), + dense.fit_transform(X).toarray()) + + +def test_sparse_input(): + X, y = datasets.make_multilabel_classification(return_indicator=True, + random_state=0, + n_samples=40) + + for name, sparse_matrix in product(FOREST_ESTIMATORS, + (csr_matrix, csc_matrix, coo_matrix)): + yield check_sparse_input, name, X, sparse_matrix(X), y + + +def check_memory_layout(name, dtype): + """Check that it works no matter the memory layout""" + + est = FOREST_ESTIMATORS[name](random_state=0, bootstrap=False) + + # Nothing + X = np.asarray(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # C-order + X = np.asarray(iris.data, order="C", dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # F-order + X = np.asarray(iris.data, order="F", dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # Contiguous + X = np.ascontiguousarray(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + if est.base_estimator.splitter in SPARSE_SPLITTERS: + # csr matrix + X = csr_matrix(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # csc_matrix + X = csc_matrix(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # coo_matrix + X = coo_matrix(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # Strided + X = np.asarray(iris.data[::3], dtype=dtype) + y = iris.target[::3] + assert_array_equal(est.fit(X, y).predict(X), y) + + +def test_memory_layout(): + for name, dtype in product(FOREST_CLASSIFIERS, [np.float64, np.float32]): + yield check_memory_layout, name, dtype + + for name, dtype in product(FOREST_REGRESSORS, [np.float64, np.float32]): + yield check_memory_layout, name, dtype + + +def check_1d_input(name, X, X_2d, y): + ForestEstimator = FOREST_ESTIMATORS[name] + assert_raises(ValueError, ForestEstimator(random_state=0).fit, X, y) + + est = ForestEstimator(random_state=0) + est.fit(X_2d, y) + + if name in FOREST_CLASSIFIERS or name in FOREST_REGRESSORS: + assert_raises(ValueError, est.predict, X) + + +def test_1d_input(): + X = iris.data[:, 0].ravel() + X_2d = iris.data[:, 0].reshape((-1, 1)) + y = iris.target + + for name in FOREST_ESTIMATORS: + yield check_1d_input, name, X, X_2d, y + + +def check_class_weights(name): + """Check class_weights resemble sample_weights behavior.""" + ForestClassifier = FOREST_CLASSIFIERS[name] + + # Iris is balanced, so no effect expected for using 'auto' weights + clf1 = ForestClassifier(random_state=0) + clf1.fit(iris.data, iris.target) + clf2 = ForestClassifier(class_weight='auto', random_state=0) + clf2.fit(iris.data, iris.target) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + # Make a multi-output problem with three copies of Iris + iris_multi = np.vstack((iris.target, iris.target, iris.target)).T + # Create user-defined weights that should balance over the outputs + clf3 = ForestClassifier(class_weight=[{0: 2., 1: 2., 2: 1.}, + {0: 2., 1: 1., 2: 2.}, + {0: 1., 1: 2., 2: 2.}], + random_state=0) + clf3.fit(iris.data, iris_multi) + assert_almost_equal(clf2.feature_importances_, clf3.feature_importances_) + # Check against multi-output "auto" which should also have no effect + clf4 = ForestClassifier(class_weight='auto', random_state=0) + clf4.fit(iris.data, iris_multi) + assert_almost_equal(clf3.feature_importances_, clf4.feature_importances_) + + # Inflate importance of class 1, check against user-defined weights + sample_weight = np.ones(iris.target.shape) + sample_weight[iris.target == 1] *= 100 + class_weight = {0: 1., 1: 100., 2: 1.} + clf1 = ForestClassifier(random_state=0) + clf1.fit(iris.data, iris.target, sample_weight) + clf2 = ForestClassifier(class_weight=class_weight, random_state=0) + clf2.fit(iris.data, iris.target) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + # Check that sample_weight and class_weight are multiplicative + clf1 = ForestClassifier(random_state=0) + clf1.fit(iris.data, iris.target, sample_weight**2) + clf2 = ForestClassifier(class_weight=class_weight, random_state=0) + clf2.fit(iris.data, iris.target, sample_weight) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + +def test_class_weights(): + for name in FOREST_CLASSIFIERS: + yield check_class_weights, name + + +def check_class_weight_auto_and_bootstrap_multi_output(name): + """Test class_weight works for multi-output""" + ForestClassifier = FOREST_CLASSIFIERS[name] + _y = np.vstack((y, np.array(y) * 2)).T + clf = ForestClassifier(class_weight='auto', random_state=0) + clf.fit(X, _y) + clf = ForestClassifier(class_weight=[{-1: 0.5, 1: 1.}, {-2: 1., 2: 1.}], + random_state=0) + clf.fit(X, _y) + clf = ForestClassifier(class_weight='subsample', random_state=0) + clf.fit(X, _y) + + +def test_class_weight_auto_and_bootstrap_multi_output(): + for name in FOREST_CLASSIFIERS: + yield check_class_weight_auto_and_bootstrap_multi_output, name + + +def check_class_weight_errors(name): + """Test if class_weight raises errors and warnings when expected.""" + ForestClassifier = FOREST_CLASSIFIERS[name] + _y = np.vstack((y, np.array(y) * 2)).T + + # Invalid preset string + clf = ForestClassifier(class_weight='the larch', random_state=0) + assert_raises(ValueError, clf.fit, X, y) + assert_raises(ValueError, clf.fit, X, _y) + + # Warning warm_start with preset + clf = ForestClassifier(class_weight='auto', warm_start=True, + random_state=0) + assert_warns(UserWarning, clf.fit, X, y) + assert_warns(UserWarning, clf.fit, X, _y) + + # Not a list or preset for multi-output + clf = ForestClassifier(class_weight=1, random_state=0) + assert_raises(ValueError, clf.fit, X, _y) + + # Incorrect length list for multi-output + clf = ForestClassifier(class_weight=[{-1: 0.5, 1: 1.}], random_state=0) + assert_raises(ValueError, clf.fit, X, _y) + + +def test_class_weight_errors(): + for name in FOREST_CLASSIFIERS: + yield check_class_weight_errors, name + + +def check_warm_start(name, random_state=42): + """Test if fitting incrementally with warm start gives a forest of the + right size and the same results as a normal fit.""" + X, y = datasets.make_hastie_10_2(n_samples=20, random_state=1) + ForestEstimator = FOREST_ESTIMATORS[name] + clf_ws = None + for n_estimators in [5, 10]: + if clf_ws is None: + clf_ws = ForestEstimator(n_estimators=n_estimators, + random_state=random_state, + warm_start=True) + else: + clf_ws.set_params(n_estimators=n_estimators) + clf_ws.fit(X, y) + assert_equal(len(clf_ws), n_estimators) + + clf_no_ws = ForestEstimator(n_estimators=10, random_state=random_state, + warm_start=False) + clf_no_ws.fit(X, y) + + assert_equal(set([tree.random_state for tree in clf_ws]), + set([tree.random_state for tree in clf_no_ws])) + + assert_array_equal(clf_ws.apply(X), clf_no_ws.apply(X), + err_msg="Failed with {0}".format(name)) + + +def test_warm_start(): + for name in FOREST_ESTIMATORS: + yield check_warm_start, name + + +def check_warm_start_clear(name): + """Test if fit clears state and grows a new forest when warm_start==False. + """ + X, y = datasets.make_hastie_10_2(n_samples=20, random_state=1) + ForestEstimator = FOREST_ESTIMATORS[name] + clf = ForestEstimator(n_estimators=5, max_depth=1, warm_start=False, + random_state=1) + clf.fit(X, y) + + clf_2 = ForestEstimator(n_estimators=5, max_depth=1, warm_start=True, + random_state=2) + clf_2.fit(X, y) # inits state + clf_2.set_params(warm_start=False, random_state=1) + clf_2.fit(X, y) # clears old state and equals clf + + assert_array_almost_equal(clf_2.apply(X), clf.apply(X)) + + +def test_warm_start_clear(): + for name in FOREST_ESTIMATORS: + yield check_warm_start_clear, name + + +def check_warm_start_smaller_n_estimators(name): + """Test if warm start second fit with smaller n_estimators raises error.""" + X, y = datasets.make_hastie_10_2(n_samples=20, random_state=1) + ForestEstimator = FOREST_ESTIMATORS[name] + clf = ForestEstimator(n_estimators=5, max_depth=1, warm_start=True) + clf.fit(X, y) + clf.set_params(n_estimators=4) + assert_raises(ValueError, clf.fit, X, y) + + +def test_warm_start_smaller_n_estimators(): + for name in FOREST_ESTIMATORS: + yield check_warm_start_smaller_n_estimators, name + + +def check_warm_start_equal_n_estimators(name): + """Test if warm start with equal n_estimators does nothing and returns the + same forest and raises a warning.""" + X, y = datasets.make_hastie_10_2(n_samples=20, random_state=1) + ForestEstimator = FOREST_ESTIMATORS[name] + clf = ForestEstimator(n_estimators=5, max_depth=3, warm_start=True, + random_state=1) + clf.fit(X, y) + + clf_2 = ForestEstimator(n_estimators=5, max_depth=3, warm_start=True, + random_state=1) + clf_2.fit(X, y) + # Now clf_2 equals clf. + + clf_2.set_params(random_state=2) + assert_warns(UserWarning, clf_2.fit, X, y) + # If we had fit the trees again we would have got a different forest as we + # changed the random state. + assert_array_equal(clf.apply(X), clf_2.apply(X)) + + +def test_warm_start_equal_n_estimators(): + for name in FOREST_ESTIMATORS: + yield check_warm_start_equal_n_estimators, name + + +def check_warm_start_oob(name): + """Test that the warm start computes oob score when asked.""" + X, y = datasets.make_hastie_10_2(n_samples=20, random_state=1) + ForestEstimator = FOREST_ESTIMATORS[name] + # Use 15 estimators to avoid 'some inputs do not have OOB scores' warning. + clf = ForestEstimator(n_estimators=15, max_depth=3, warm_start=False, + random_state=1, bootstrap=True, oob_score=True) + clf.fit(X, y) + + clf_2 = ForestEstimator(n_estimators=5, max_depth=3, warm_start=False, + random_state=1, bootstrap=True, oob_score=False) + clf_2.fit(X, y) + + clf_2.set_params(warm_start=True, oob_score=True, n_estimators=15) + clf_2.fit(X, y) + + assert_true(hasattr(clf_2, 'oob_score_')) + assert_equal(clf.oob_score_, clf_2.oob_score_) + + # Test that oob_score is computed even if we don't need to train + # additional trees. + clf_3 = ForestEstimator(n_estimators=15, max_depth=3, warm_start=True, + random_state=1, bootstrap=True, oob_score=False) + clf_3.fit(X, y) + assert_true(not(hasattr(clf_3, 'oob_score_'))) + + clf_3.set_params(oob_score=True) + ignore_warnings(clf_3.fit)(X, y) + + assert_equal(clf.oob_score_, clf_3.oob_score_) + + +def test_warm_start_oob(): + for name in FOREST_CLASSIFIERS: + yield check_warm_start_oob, name + for name in FOREST_REGRESSORS: + yield check_warm_start_oob, name if __name__ == "__main__": diff --git a/sklearn/ensemble/tests/test_gradient_boosting.py b/sklearn/ensemble/tests/test_gradient_boosting.py index 85115ec0b0fe9..c1133dc4c0d54 100644 --- a/sklearn/ensemble/tests/test_gradient_boosting.py +++ b/sklearn/ensemble/tests/test_gradient_boosting.py @@ -3,19 +3,25 @@ """ import numpy as np -from numpy.testing import assert_array_equal -from numpy.testing import assert_array_almost_equal -from numpy.testing import assert_equal - -from nose.tools import assert_raises - -from sklearn.metrics import mean_squared_error -from sklearn.utils import check_random_state +from sklearn import datasets +from sklearn.base import clone from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import GradientBoostingRegressor - -from sklearn import datasets +from sklearn.ensemble.gradient_boosting import ZeroEstimator +from sklearn.metrics import mean_squared_error +from sklearn.utils import check_random_state, tosequence +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_warns +from sklearn.utils.validation import DataConversionWarning +from sklearn.utils.validation import NotFittedError # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] @@ -41,61 +47,73 @@ def test_classification_toy(): """Check classification on a toy dataset.""" - clf = GradientBoostingClassifier(n_estimators=100, random_state=1) - assert_raises(ValueError, clf.predict, T) + for loss in ('deviance', 'exponential'): + clf = GradientBoostingClassifier(loss=loss, n_estimators=10, + random_state=1) - clf.fit(X, y) - assert_array_equal(clf.predict(T), true_result) - assert_equal(100, len(clf.estimators_)) + assert_raises(ValueError, clf.predict, T) + + clf.fit(X, y) + assert_array_equal(clf.predict(T), true_result) + assert_equal(10, len(clf.estimators_)) - deviance_decrease = (clf.train_score_[:-1] - clf.train_score_[1:]) - assert np.any(deviance_decrease >= 0.0), \ - "Train deviance does not monotonically decrease." + deviance_decrease = (clf.train_score_[:-1] - clf.train_score_[1:]) + assert np.any(deviance_decrease >= 0.0), \ + "Train deviance does not monotonically decrease." def test_parameter_checks(): """Check input parameter validation.""" - assert_raises(ValueError, GradientBoostingClassifier, n_estimators=0) - assert_raises(ValueError, GradientBoostingClassifier, n_estimators=-1) - assert_raises(ValueError, GradientBoostingClassifier, learn_rate=0.0) - assert_raises(ValueError, GradientBoostingClassifier, learn_rate=-1.0) + assert_raises(ValueError, + GradientBoostingClassifier(n_estimators=0).fit, X, y) + assert_raises(ValueError, + GradientBoostingClassifier(n_estimators=-1).fit, X, y) - assert_raises(ValueError, GradientBoostingRegressor, loss='foobar') + assert_raises(ValueError, + GradientBoostingClassifier(learning_rate=0.0).fit, X, y) + assert_raises(ValueError, + GradientBoostingClassifier(learning_rate=-1.0).fit, X, y) - assert_raises(ValueError, GradientBoostingClassifier, - min_samples_split=0.0) - assert_raises(ValueError, GradientBoostingClassifier, - min_samples_split=-1.0) + assert_raises(ValueError, + GradientBoostingClassifier(loss='foobar').fit, X, y) - assert_raises(ValueError, GradientBoostingClassifier, min_samples_leaf=0) - assert_raises(ValueError, GradientBoostingClassifier, min_samples_leaf=-1.) + assert_raises(ValueError, + GradientBoostingClassifier(min_samples_split=0.0).fit, X, y) + assert_raises(ValueError, + GradientBoostingClassifier(min_samples_split=-1.0).fit, X, y) - assert_raises(ValueError, GradientBoostingClassifier, subsample=0.0) - assert_raises(ValueError, GradientBoostingClassifier, subsample=1.1) - assert_raises(ValueError, GradientBoostingClassifier, subsample=-0.1) + assert_raises(ValueError, + GradientBoostingClassifier(min_samples_leaf=0).fit, X, y) + assert_raises(ValueError, + GradientBoostingClassifier(min_samples_leaf=-1.).fit, X, y) - assert_raises(ValueError, GradientBoostingClassifier, max_depth=-0.1) - assert_raises(ValueError, GradientBoostingClassifier, max_depth=0) + assert_raises(ValueError, + GradientBoostingClassifier(min_weight_fraction_leaf=-1.).fit, + X, y) + assert_raises(ValueError, + GradientBoostingClassifier(min_weight_fraction_leaf=0.6).fit, + X, y) - assert_raises(ValueError, GradientBoostingClassifier, init={}) + assert_raises(ValueError, + GradientBoostingClassifier(subsample=0.0).fit, X, y) + assert_raises(ValueError, + GradientBoostingClassifier(subsample=1.1).fit, X, y) + assert_raises(ValueError, + GradientBoostingClassifier(subsample=-0.1).fit, X, y) - # test fit before feature importance assert_raises(ValueError, - lambda: GradientBoostingClassifier().feature_importances_) + GradientBoostingClassifier(max_depth=-0.1).fit, X, y) + assert_raises(ValueError, + GradientBoostingClassifier(max_depth=0).fit, X, y) - # binomial deviance requires ``n_classes == 2``. assert_raises(ValueError, - lambda X, y: GradientBoostingClassifier( - loss='bdeviance').fit(X, y), - X, [0, 0, 1, 1, 2, 2]) + GradientBoostingClassifier(init={}).fit, X, y) - # multinomial deviance requires ``n_classes > 2``. + # test fit before feature importance assert_raises(ValueError, - lambda X, y: GradientBoostingClassifier( - loss='mdeviance').fit(X, y), - X, [0, 0, 1, 1, 1, 0]) + lambda: GradientBoostingClassifier().feature_importances_) # deviance requires ``n_classes >= 2``. assert_raises(ValueError, @@ -104,6 +122,21 @@ def test_parameter_checks(): X, [0, 0, 0, 0]) +def test_loss_function(): + assert_raises(ValueError, + GradientBoostingClassifier(loss='ls').fit, X, y) + assert_raises(ValueError, + GradientBoostingClassifier(loss='lad').fit, X, y) + assert_raises(ValueError, + GradientBoostingClassifier(loss='quantile').fit, X, y) + assert_raises(ValueError, + GradientBoostingClassifier(loss='huber').fit, X, y) + assert_raises(ValueError, + GradientBoostingRegressor(loss='deviance').fit, X, y) + assert_raises(ValueError, + GradientBoostingRegressor(loss='exponential').fit, X, y) + + def test_classification_synthetic(): """Test GradientBoostingClassifier on synthetic dataset used by Hastie et al. in ESLII Example 12.7. """ @@ -112,47 +145,66 @@ def test_classification_synthetic(): X_train, X_test = X[:2000], X[2000:] y_train, y_test = y[:2000], y[2000:] - gbrt = GradientBoostingClassifier(n_estimators=100, min_samples_split=1, - max_depth=1, - learn_rate=1.0, random_state=0) - gbrt.fit(X_train, y_train) - error_rate = (1.0 - gbrt.score(X_test, y_test)) - assert error_rate < 0.085, \ - "GB failed with error %.4f" % error_rate - - gbrt = GradientBoostingClassifier(n_estimators=200, min_samples_split=1, - max_depth=1, - learn_rate=1.0, subsample=0.5, - random_state=0) - gbrt.fit(X_train, y_train) - error_rate = (1.0 - gbrt.score(X_test, y_test)) - assert error_rate < 0.08, \ - "Stochastic GB failed with error %.4f" % error_rate + for loss in ('deviance', 'exponential'): + + gbrt = GradientBoostingClassifier(n_estimators=100, min_samples_split=1, + max_depth=1, loss=loss, + learning_rate=1.0, random_state=0) + gbrt.fit(X_train, y_train) + error_rate = (1.0 - gbrt.score(X_test, y_test)) + assert error_rate < 0.09, \ + "GB(loss={}) failed with error {}".format(loss, error_rate) + + gbrt = GradientBoostingClassifier(n_estimators=200, min_samples_split=1, + max_depth=1, + learning_rate=1.0, subsample=0.5, + random_state=0) + gbrt.fit(X_train, y_train) + error_rate = (1.0 - gbrt.score(X_test, y_test)) + assert error_rate < 0.08, ("Stochastic GradientBoostingClassifier(loss={}) " + "failed with error {}".format(loss, error_rate)) def test_boston(): """Check consistency on dataset boston house prices with least squares and least absolute deviation. """ for loss in ("ls", "lad", "huber"): - clf = GradientBoostingRegressor(n_estimators=100, loss=loss, - max_depth=4, - min_samples_split=1, random_state=1) - assert_raises(ValueError, clf.predict, boston.data) - clf.fit(boston.data, boston.target) - y_pred = clf.predict(boston.data) - mse = mean_squared_error(boston.target, y_pred) - assert mse < 6.0, "Failed with loss %s and mse = %.4f" % (loss, mse) + for subsample in (1.0, 0.5): + last_y_pred = None + for i, sample_weight in enumerate((None, np.ones(len(boston.target)), + 2 * np.ones(len(boston.target)))): + clf = GradientBoostingRegressor(n_estimators=100, loss=loss, + max_depth=4, subsample=subsample, + min_samples_split=1, + random_state=1) + + assert_raises(ValueError, clf.predict, boston.data) + clf.fit(boston.data, boston.target, + sample_weight=sample_weight) + y_pred = clf.predict(boston.data) + mse = mean_squared_error(boston.target, y_pred) + assert mse < 6.0, "Failed with loss %s and " \ + "mse = %.4f" % (loss, mse) + + if last_y_pred is not None: + np.testing.assert_array_almost_equal( + last_y_pred, y_pred, + err_msg='pred_%d doesnt match last pred_%d for loss %r and subsample %r. ' + % (i, i - 1, loss, subsample)) + + last_y_pred = y_pred def test_iris(): """Check consistency on dataset iris.""" for subsample in (1.0, 0.5): - clf = GradientBoostingClassifier(n_estimators=100, loss='deviance', - random_state=1, subsample=subsample) - clf.fit(iris.data, iris.target) - score = clf.score(iris.data, iris.target) - assert score > 0.9, "Failed with subsample %.1f " \ - "and score = %f" % (subsample, score) + for sample_weight in (None, np.ones(len(iris.target))): + clf = GradientBoostingClassifier(n_estimators=100, loss='deviance', + random_state=1, subsample=subsample) + clf.fit(iris.data, iris.target, sample_weight=sample_weight) + score = clf.score(iris.data, iris.target) + assert score > 0.9, "Failed with subsample %.1f " \ + "and score = %f" % (subsample, score) def test_regression_synthetic(): @@ -160,7 +212,7 @@ def test_regression_synthetic(): `Bagging Predictors?. Machine Learning 24(2): 123-140 (1996). """ random_state = check_random_state(1) regression_params = {'n_estimators': 100, 'max_depth': 4, - 'min_samples_split': 1, 'learn_rate': 0.1, + 'min_samples_split': 1, 'learning_rate': 0.1, 'loss': 'ls'} # Friedman1 @@ -192,22 +244,28 @@ def test_regression_synthetic(): assert mse < 0.015, "Failed on Friedman3 with mse = %.4f" % mse -# def test_feature_importances(): -# X = np.array(boston.data, dtype=np.float32) -# y = np.array(boston.target, dtype=np.float32) +def test_feature_importances(): + X = np.array(boston.data, dtype=np.float32) + y = np.array(boston.target, dtype=np.float32) + + clf = GradientBoostingRegressor(n_estimators=100, max_depth=5, + min_samples_split=1, random_state=1) + clf.fit(X, y) + #feature_importances = clf.feature_importances_ + assert_true(hasattr(clf, 'feature_importances_')) -# clf = GradientBoostingRegressor(n_estimators=100, max_depth=5, -# min_samples_split=1, random_state=1) -# clf.fit(X, y) -# feature_importances = clf.feature_importances_ + X_new = clf.transform(X, threshold="mean") + assert_less(X_new.shape[1], X.shape[1]) -# # true feature importance ranking -# true_ranking = np.array([3, 1, 8, 2, 10, 9, 4, 11, 0, 6, 7, 5, 12]) + feature_mask = clf.feature_importances_ > clf.feature_importances_.mean() + assert_array_almost_equal(X_new, X[:, feature_mask]) -# assert_array_equal(true_ranking, feature_importances.argsort()) + # true feature importance ranking + # true_ranking = np.array([3, 1, 8, 2, 10, 9, 4, 11, 0, 6, 7, 5, 12]) + # assert_array_equal(true_ranking, feature_importances.argsort()) -def test_probability(): +def test_probability_log(): """Predict probabilities.""" clf = GradientBoostingClassifier(n_estimators=100, random_state=1) @@ -239,6 +297,10 @@ def test_check_inputs(): clf = GradientBoostingClassifier().fit(X, y) assert_raises(TypeError, clf.predict, X_sparse) + clf = GradientBoostingClassifier(n_estimators=100, random_state=1) + assert_raises(ValueError, clf.fit, X, y, + sample_weight=([1] * len(y)) + [0, 1]) + def test_check_inputs_predict(): """X has wrong shape """ @@ -277,6 +339,58 @@ def test_check_max_features(): max_features=(len(X[0]) + 1)) assert_raises(ValueError, clf.fit, X, y) + clf = GradientBoostingRegressor(n_estimators=100, random_state=1, + max_features=-0.1) + assert_raises(ValueError, clf.fit, X, y) + +def test_max_feature_regression(): + """Test to make sure random state is set properly. """ + X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1) + + X_train, X_test = X[:2000], X[2000:] + y_train, y_test = y[:2000], y[2000:] + + gbrt = GradientBoostingClassifier(n_estimators=100, min_samples_split=5, + max_depth=2, learning_rate=.1, + max_features=2, random_state=1) + gbrt.fit(X_train, y_train) + deviance = gbrt.loss_(y_test, gbrt.decision_function(X_test)) + assert_true(deviance < 0.5, "GB failed with deviance %.4f" % deviance) + + +def test_max_feature_auto(): + """Test if max features is set properly for floats and str. """ + X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1) + _, n_features = X.shape + + X_train = X[:2000] + y_train = y[:2000] + + gbrt = GradientBoostingClassifier(n_estimators=1, max_features='auto') + gbrt.fit(X_train, y_train) + assert_equal(gbrt.max_features_, int(np.sqrt(n_features))) + + gbrt = GradientBoostingRegressor(n_estimators=1, max_features='auto') + gbrt.fit(X_train, y_train) + assert_equal(gbrt.max_features_, n_features) + + gbrt = GradientBoostingRegressor(n_estimators=1, max_features=0.3) + gbrt.fit(X_train, y_train) + assert_equal(gbrt.max_features_, int(n_features * 0.3)) + + gbrt = GradientBoostingRegressor(n_estimators=1, max_features='sqrt') + gbrt.fit(X_train, y_train) + assert_equal(gbrt.max_features_, int(np.sqrt(n_features))) + + gbrt = GradientBoostingRegressor(n_estimators=1, max_features='log2') + gbrt.fit(X_train, y_train) + assert_equal(gbrt.max_features_, int(np.log2(n_features))) + + gbrt = GradientBoostingRegressor(n_estimators=1, + max_features=0.01 / X.shape[1]) + gbrt.fit(X_train, y_train) + assert_equal(gbrt.max_features_, 1) + def test_staged_predict(): """Test whether staged decision function eventually gives @@ -285,7 +399,7 @@ def test_staged_predict(): X, y = datasets.make_friedman1(n_samples=1200, random_state=1, noise=1.0) X_train, y_train = X[:200], y[:200] - X_test, y_test = X[200:], y[200:] + X_test = X[200:] clf = GradientBoostingRegressor() # test raise ValueError if not fitted assert_raises(ValueError, lambda X: np.fromiter( @@ -301,6 +415,53 @@ def test_staged_predict(): assert_array_equal(y_pred, y) +def test_staged_predict_proba(): + """Test whether staged predict proba eventually gives + the same prediction. + """ + X, y = datasets.make_hastie_10_2(n_samples=1200, + random_state=1) + X_train, y_train = X[:200], y[:200] + X_test, y_test = X[200:], y[200:] + clf = GradientBoostingClassifier(n_estimators=20) + # test raise NotFittedError if not fitted + assert_raises(NotFittedError, lambda X: np.fromiter( + clf.staged_predict_proba(X), dtype=np.float64), X_test) + + clf.fit(X_train, y_train) + + # test if prediction for last stage equals ``predict`` + for y_pred in clf.staged_predict(X_test): + assert_equal(y_test.shape, y_pred.shape) + + assert_array_equal(clf.predict(X_test), y_pred) + + # test if prediction for last stage equals ``predict_proba`` + for staged_proba in clf.staged_predict_proba(X_test): + assert_equal(y_test.shape[0], staged_proba.shape[0]) + assert_equal(2, staged_proba.shape[1]) + + assert_array_equal(clf.predict_proba(X_test), staged_proba) + + +def test_staged_functions_defensive(): + # test that staged_functions make defensive copies + rng = np.random.RandomState(0) + X = rng.uniform(size=(10, 3)) + y = (4 * X[:, 0]).astype(np.int) + 1 # don't predict zeros + for estimator in [GradientBoostingRegressor(), + GradientBoostingClassifier()]: + estimator.fit(X, y) + for func in ['predict', 'decision_function', 'predict_proba']: + staged_func = getattr(estimator, "staged_" + func, None) + if staged_func is None: + # regressor has no staged_predict_proba + continue + staged_result = list(staged_func(X)) + staged_result[1][:] = 0 + assert_true(np.all(staged_result[0] != 0)) + + def test_serialization(): """Check model serialization.""" clf = GradientBoostingClassifier(n_estimators=100, random_state=1) @@ -356,10 +517,10 @@ def test_symbol_labels(): """Test with non-integer class labels. """ clf = GradientBoostingClassifier(n_estimators=100, random_state=1) - symbol_y = map(str, y) + symbol_y = tosequence(map(str, y)) clf.fit(X, symbol_y) - assert_array_equal(clf.predict(T), map(str, true_result)) + assert_array_equal(clf.predict(T), tosequence(map(str, true_result))) assert_equal(100, len(clf.estimators_)) @@ -382,7 +543,10 @@ def test_shape_y(): y_ = np.asarray(y, dtype=np.int32) y_ = y_[:, np.newaxis] - clf.fit(X, y_) + # This will raise a DataConversionWarning that we want to + # "always" raise, elsewhere the warnings gets ignored in the + # later tests, and the tests that check for this warning fail + assert_warns(DataConversionWarning, clf.fit, X, y_) assert_array_equal(clf.predict(T), true_result) assert_equal(100, len(clf.estimators_)) @@ -402,7 +566,6 @@ def test_mem_layout(): assert_equal(100, len(clf.estimators_)) y_ = np.asarray(y, dtype=np.int32) - y_ = y_[:, np.newaxis] y_ = np.ascontiguousarray(y_) clf = GradientBoostingClassifier(n_estimators=100, random_state=1) clf.fit(X, y_) @@ -410,9 +573,434 @@ def test_mem_layout(): assert_equal(100, len(clf.estimators_)) y_ = np.asarray(y, dtype=np.int32) - y_ = y_[:, np.newaxis] y_ = np.asfortranarray(y_) clf = GradientBoostingClassifier(n_estimators=100, random_state=1) clf.fit(X, y_) assert_array_equal(clf.predict(T), true_result) assert_equal(100, len(clf.estimators_)) + + +def test_oob_improvement(): + """Test if oob improvement has correct shape and regression test. """ + clf = GradientBoostingClassifier(n_estimators=100, random_state=1, + subsample=0.5) + clf.fit(X, y) + assert clf.oob_improvement_.shape[0] == 100 + # hard-coded regression test - change if modification in OOB computation + assert_array_almost_equal(clf.oob_improvement_[:5], + np.array([0.19, 0.15, 0.12, -0.12, -0.11]), + decimal=2) + + +def test_oob_improvement_raise(): + """Test if oob improvement has correct shape. """ + clf = GradientBoostingClassifier(n_estimators=100, random_state=1, + subsample=1.0) + clf.fit(X, y) + assert_raises(AttributeError, lambda: clf.oob_improvement_) + + +def test_oob_multilcass_iris(): + """Check OOB improvement on multi-class dataset.""" + clf = GradientBoostingClassifier(n_estimators=100, loss='deviance', + random_state=1, subsample=0.5) + clf.fit(iris.data, iris.target) + score = clf.score(iris.data, iris.target) + assert score > 0.9, "Failed with subsample %.1f " \ + "and score = %f" % (0.5, score) + + assert clf.oob_improvement_.shape[0] == clf.n_estimators + # hard-coded regression test - change if modification in OOB computation + # FIXME: the following snippet does not yield the same results on 32 bits + # assert_array_almost_equal(clf.oob_improvement_[:5], + # np.array([12.68, 10.45, 8.18, 6.43, 5.13]), + # decimal=2) + + +def test_verbose_output(): + """Check verbose=1 does not cause error. """ + from sklearn.externals.six.moves import cStringIO as StringIO + import sys + old_stdout = sys.stdout + sys.stdout = StringIO() + clf = GradientBoostingClassifier(n_estimators=100, random_state=1, + verbose=1, subsample=0.8) + clf.fit(X, y) + verbose_output = sys.stdout + sys.stdout = old_stdout + + # check output + verbose_output.seek(0) + header = verbose_output.readline().rstrip() + # with OOB + true_header = ' '.join(['%10s'] + ['%16s'] * 3) % ( + 'Iter', 'Train Loss', 'OOB Improve', 'Remaining Time') + assert_equal(true_header, header) + + n_lines = sum(1 for l in verbose_output.readlines()) + # one for 1-10 and then 9 for 20-100 + assert_equal(10 + 9, n_lines) + + +def test_more_verbose_output(): + """Check verbose=2 does not cause error. """ + from sklearn.externals.six.moves import cStringIO as StringIO + import sys + old_stdout = sys.stdout + sys.stdout = StringIO() + clf = GradientBoostingClassifier(n_estimators=100, random_state=1, + verbose=2) + clf.fit(X, y) + verbose_output = sys.stdout + sys.stdout = old_stdout + + # check output + verbose_output.seek(0) + header = verbose_output.readline().rstrip() + # no OOB + true_header = ' '.join(['%10s'] + ['%16s'] * 2) % ( + 'Iter', 'Train Loss', 'Remaining Time') + assert_equal(true_header, header) + + n_lines = sum(1 for l in verbose_output.readlines()) + # 100 lines for n_estimators==100 + assert_equal(100, n_lines) + + +def test_warm_start(): + """Test if warm start equals fit. """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + for Cls in [GradientBoostingRegressor, GradientBoostingClassifier]: + est = Cls(n_estimators=200, max_depth=1) + est.fit(X, y) + + est_ws = Cls(n_estimators=100, max_depth=1, warm_start=True) + est_ws.fit(X, y) + est_ws.set_params(n_estimators=200) + est_ws.fit(X, y) + + assert_array_almost_equal(est_ws.predict(X), est.predict(X)) + + +def test_warm_start_n_estimators(): + """Test if warm start equals fit - set n_estimators. """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + for Cls in [GradientBoostingRegressor, GradientBoostingClassifier]: + est = Cls(n_estimators=300, max_depth=1) + est.fit(X, y) + + est_ws = Cls(n_estimators=100, max_depth=1, warm_start=True) + est_ws.fit(X, y) + est_ws.set_params(n_estimators=300) + est_ws.fit(X, y) + + assert_array_almost_equal(est_ws.predict(X), est.predict(X)) + + +def test_warm_start_max_depth(): + """Test if possible to fit trees of different depth in ensemble. """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + for Cls in [GradientBoostingRegressor, GradientBoostingClassifier]: + est = Cls(n_estimators=100, max_depth=1, warm_start=True) + est.fit(X, y) + est.set_params(n_estimators=110, max_depth=2) + est.fit(X, y) + + # last 10 trees have different depth + assert est.estimators_[0, 0].max_depth == 1 + for i in range(1, 11): + assert est.estimators_[-i, 0].max_depth == 2 + + +def test_warm_start_clear(): + """Test if fit clears state. """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + for Cls in [GradientBoostingRegressor, GradientBoostingClassifier]: + est = Cls(n_estimators=100, max_depth=1) + est.fit(X, y) + + est_2 = Cls(n_estimators=100, max_depth=1, warm_start=True) + est_2.fit(X, y) # inits state + est_2.set_params(warm_start=False) + est_2.fit(X, y) # clears old state and equals est + + assert_array_almost_equal(est_2.predict(X), est.predict(X)) + + +def test_warm_start_zero_n_estimators(): + """Test if warm start with zero n_estimators raises error """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + for Cls in [GradientBoostingRegressor, GradientBoostingClassifier]: + est = Cls(n_estimators=100, max_depth=1, warm_start=True) + est.fit(X, y) + est.set_params(n_estimators=0) + assert_raises(ValueError, est.fit, X, y) + + +def test_warm_start_smaller_n_estimators(): + """Test if warm start with smaller n_estimators raises error """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + for Cls in [GradientBoostingRegressor, GradientBoostingClassifier]: + est = Cls(n_estimators=100, max_depth=1, warm_start=True) + est.fit(X, y) + est.set_params(n_estimators=99) + assert_raises(ValueError, est.fit, X, y) + + +def test_warm_start_equal_n_estimators(): + """Test if warm start with equal n_estimators does nothing """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + for Cls in [GradientBoostingRegressor, GradientBoostingClassifier]: + est = Cls(n_estimators=100, max_depth=1) + est.fit(X, y) + + est2 = clone(est) + est2.set_params(n_estimators=est.n_estimators, warm_start=True) + est2.fit(X, y) + + assert_array_almost_equal(est2.predict(X), est.predict(X)) + + +def test_warm_start_oob_switch(): + """Test if oob can be turned on during warm start. """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + for Cls in [GradientBoostingRegressor, GradientBoostingClassifier]: + est = Cls(n_estimators=100, max_depth=1, warm_start=True) + est.fit(X, y) + est.set_params(n_estimators=110, subsample=0.5) + est.fit(X, y) + + assert_array_equal(est.oob_improvement_[:100], np.zeros(100)) + # the last 10 are not zeros + assert_array_equal(est.oob_improvement_[-10:] == 0.0, + np.zeros(10, dtype=np.bool)) + + +def test_warm_start_oob(): + """Test if warm start OOB equals fit. """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + for Cls in [GradientBoostingRegressor, GradientBoostingClassifier]: + est = Cls(n_estimators=200, max_depth=1, subsample=0.5, + random_state=1) + est.fit(X, y) + + est_ws = Cls(n_estimators=100, max_depth=1, subsample=0.5, + random_state=1, warm_start=True) + est_ws.fit(X, y) + est_ws.set_params(n_estimators=200) + est_ws.fit(X, y) + + assert_array_almost_equal(est_ws.oob_improvement_[:100], + est.oob_improvement_[:100]) + + +def early_stopping_monitor(i, est, locals): + """Returns True on the 10th iteration. """ + if i == 9: + return True + else: + return False + + +def test_monitor_early_stopping(): + """Test if monitor return value works. """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + + for Cls in [GradientBoostingRegressor, GradientBoostingClassifier]: + est = Cls(n_estimators=20, max_depth=1, random_state=1, subsample=0.5) + est.fit(X, y, monitor=early_stopping_monitor) + assert_equal(est.n_estimators, 20) # this is not altered + assert_equal(est.estimators_.shape[0], 10) + assert_equal(est.train_score_.shape[0], 10) + assert_equal(est.oob_improvement_.shape[0], 10) + + # try refit + est.set_params(n_estimators=30) + est.fit(X, y) + assert_equal(est.n_estimators, 30) + assert_equal(est.estimators_.shape[0], 30) + assert_equal(est.train_score_.shape[0], 30) + + est = Cls(n_estimators=20, max_depth=1, random_state=1, subsample=0.5, + warm_start=True) + est.fit(X, y, monitor=early_stopping_monitor) + assert_equal(est.n_estimators, 20) + assert_equal(est.estimators_.shape[0], 10) + assert_equal(est.train_score_.shape[0], 10) + assert_equal(est.oob_improvement_.shape[0], 10) + + # try refit + est.set_params(n_estimators=30, warm_start=False) + est.fit(X, y) + assert_equal(est.n_estimators, 30) + assert_equal(est.train_score_.shape[0], 30) + assert_equal(est.estimators_.shape[0], 30) + assert_equal(est.oob_improvement_.shape[0], 30) + + +def test_complete_classification(): + """Test greedy trees with max_depth + 1 leafs. """ + from sklearn.tree._tree import TREE_LEAF + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + k = 4 + + est = GradientBoostingClassifier(n_estimators=20, max_depth=None, + random_state=1, max_leaf_nodes=k+1) + est.fit(X, y) + + tree = est.estimators_[0, 0].tree_ + assert_equal(tree.max_depth, k) + assert_equal(tree.children_left[tree.children_left == TREE_LEAF].shape[0], + k + 1) + + +def test_complete_regression(): + """Test greedy trees with max_depth + 1 leafs. """ + from sklearn.tree._tree import TREE_LEAF + k = 4 + + est = GradientBoostingRegressor(n_estimators=20, max_depth=None, + random_state=1, max_leaf_nodes=k+1) + est.fit(boston.data, boston.target) + + tree = est.estimators_[-1, 0].tree_ + assert_equal(tree.children_left[tree.children_left == TREE_LEAF].shape[0], + k + 1) + + +def test_zero_estimator_reg(): + """Test if ZeroEstimator works for regression. """ + est = GradientBoostingRegressor(n_estimators=20, max_depth=1, + random_state=1, init=ZeroEstimator()) + est.fit(boston.data, boston.target) + y_pred = est.predict(boston.data) + mse = mean_squared_error(boston.target, y_pred) + assert_almost_equal(mse, 33.0, decimal=0) + + est = GradientBoostingRegressor(n_estimators=20, max_depth=1, + random_state=1, init='zero') + est.fit(boston.data, boston.target) + y_pred = est.predict(boston.data) + mse = mean_squared_error(boston.target, y_pred) + assert_almost_equal(mse, 33.0, decimal=0) + + est = GradientBoostingRegressor(n_estimators=20, max_depth=1, + random_state=1, init='foobar') + assert_raises(ValueError, est.fit, boston.data, boston.target) + + +def test_zero_estimator_clf(): + """Test if ZeroEstimator works for classification. """ + X = iris.data + y = np.array(iris.target) + est = GradientBoostingClassifier(n_estimators=20, max_depth=1, + random_state=1, init=ZeroEstimator()) + est.fit(X, y) + + assert est.score(X, y) > 0.96 + + est = GradientBoostingClassifier(n_estimators=20, max_depth=1, + random_state=1, init='zero') + est.fit(X, y) + + assert est.score(X, y) > 0.96 + + # binary clf + mask = y != 0 + y[mask] = 1 + y[~mask] = 0 + est = GradientBoostingClassifier(n_estimators=20, max_depth=1, + random_state=1, init='zero') + est.fit(X, y) + assert est.score(X, y) > 0.96 + + est = GradientBoostingClassifier(n_estimators=20, max_depth=1, + random_state=1, init='foobar') + assert_raises(ValueError, est.fit, X, y) + + +def test_max_leaf_nodes_max_depth(): + """Test preceedence of max_leaf_nodes over max_depth. """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + all_estimators = [GradientBoostingRegressor, + GradientBoostingClassifier] + + k = 4 + for GBEstimator in all_estimators: + est = GBEstimator(max_depth=1, max_leaf_nodes=k).fit(X, y) + tree = est.estimators_[0, 0].tree_ + assert_greater(tree.max_depth, 1) + + est = GBEstimator(max_depth=1).fit(X, y) + tree = est.estimators_[0, 0].tree_ + assert_equal(tree.max_depth, 1) + + +def test_warm_start_wo_nestimators_change(): + """Test if warm_start does nothing if n_estimators is not changed. + + Regression test for #3513. + """ + clf = GradientBoostingClassifier(n_estimators=10, warm_start=True) + clf.fit([[0, 1], [2, 3]], [0, 1]) + assert clf.estimators_.shape[0] == 10 + clf.fit([[0, 1], [2, 3]], [0, 1]) + assert clf.estimators_.shape[0] == 10 + + +def test_probability_exponential(): + """Predict probabilities.""" + clf = GradientBoostingClassifier(loss='exponential', + n_estimators=100, random_state=1) + + assert_raises(ValueError, clf.predict_proba, T) + + clf.fit(X, y) + assert_array_equal(clf.predict(T), true_result) + + # check if probabilities are in [0, 1]. + y_proba = clf.predict_proba(T) + assert np.all(y_proba >= 0.0) + assert np.all(y_proba <= 1.0) + score = clf.decision_function(T).ravel() + assert_array_equal(y_proba[:, 1], + 1.0 / (1.0 + np.exp(-2 * score))) + + # derive predictions from probabilities + y_pred = clf.classes_.take(y_proba.argmax(axis=1), axis=0) + assert_array_equal(y_pred, true_result) + + +def test_non_uniform_weights_toy_edge_case_reg(): + X = [[1, 0], + [1, 0], + [1, 0], + [0, 1], + ] + y = [0, 0, 1, 0] + # ignore the first 2 training samples by setting their weight to 0 + sample_weight = [0, 0, 1, 1] + for loss in ('ls', 'huber', 'lad', 'quantile'): + gb = GradientBoostingRegressor(n_estimators=5) + gb.fit(X, y, sample_weight=sample_weight) + assert_true(gb.predict([[1, 0]])[0] > 0.5) + + +def test_non_uniform_weights_toy_edge_case_clf(): + X = [[1, 0], + [1, 0], + [1, 0], + [0, 1], + ] + y = [0, 0, 1, 0] + # ignore the first 2 training samples by setting their weight to 0 + sample_weight = [0, 0, 1, 1] + for loss in ('deviance', 'exponential'): + gb = GradientBoostingClassifier(n_estimators=5) + gb.fit(X, y, sample_weight=sample_weight) + assert_array_equal(gb.predict([[1, 0]]), [1]) + + +if __name__ == "__main__": + import nose + nose.runmodule() diff --git a/sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py b/sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py new file mode 100644 index 0000000000000..1c811aeba9af4 --- /dev/null +++ b/sklearn/ensemble/tests/test_gradient_boosting_loss_functions.py @@ -0,0 +1,178 @@ +""" +Testing for the gradient boosting loss functions and initial estimators. +""" + +import numpy as np +from numpy.testing import assert_array_equal +from numpy.testing import assert_almost_equal +from numpy.testing import assert_equal + +from nose.tools import assert_raises + +from sklearn.utils import check_random_state +from sklearn.ensemble.gradient_boosting import BinomialDeviance +from sklearn.ensemble.gradient_boosting import LogOddsEstimator +from sklearn.ensemble.gradient_boosting import LeastSquaresError +from sklearn.ensemble.gradient_boosting import RegressionLossFunction +from sklearn.ensemble.gradient_boosting import LOSS_FUNCTIONS +from sklearn.ensemble.gradient_boosting import _weighted_percentile + + +def test_binomial_deviance(): + """Check binomial deviance loss. + + Check against alternative definitions in ESLII. + """ + bd = BinomialDeviance(2) + + # pred has the same BD for y in {0, 1} + assert_equal(bd(np.array([0.0]), np.array([0.0])), + bd(np.array([1.0]), np.array([0.0]))) + + assert_almost_equal(bd(np.array([1.0, 1.0, 1.0]), + np.array([100.0, 100.0, 100.0])), + 0.0) + assert_almost_equal(bd(np.array([1.0, 0.0, 0.0]), + np.array([100.0, -100.0, -100.0])), 0) + + # check if same results as alternative definition of deviance (from ESLII) + alt_dev = lambda y, pred: np.mean(np.logaddexp(0.0, -2.0 * + (2.0 * y - 1) * pred)) + test_data = [(np.array([1.0, 1.0, 1.0]), np.array([100.0, 100.0, 100.0])), + (np.array([0.0, 0.0, 0.0]), np.array([100.0, 100.0, 100.0])), + (np.array([0.0, 0.0, 0.0]), + np.array([-100.0, -100.0, -100.0])), + (np.array([1.0, 1.0, 1.0]), + np.array([-100.0, -100.0, -100.0]))] + + for datum in test_data: + assert_almost_equal(bd(*datum), alt_dev(*datum)) + + # check the gradient against the + alt_ng = lambda y, pred: (2 * y - 1) / (1 + np.exp(2 * (2 * y - 1) * pred)) + for datum in test_data: + assert_almost_equal(bd.negative_gradient(*datum), alt_ng(*datum)) + + +def test_log_odds_estimator(): + """Check log odds estimator. """ + est = LogOddsEstimator() + assert_raises(ValueError, est.fit, None, np.array([1])) + + est.fit(None, np.array([1.0, 0.0])) + assert_equal(est.prior, 0.0) + assert_array_equal(est.predict(np.array([[1.0], [1.0]])), + np.array([[0.0], [0.0]])) + + +def test_sample_weight_smoke(): + rng = check_random_state(13) + y = rng.rand(100) + pred = rng.rand(100) + + # least squares + loss = LeastSquaresError(1) + loss_wo_sw = loss(y, pred) + loss_w_sw = loss(y, pred, np.ones(pred.shape[0], dtype=np.float32)) + assert_almost_equal(loss_wo_sw, loss_w_sw) + + +def test_sample_weight_init_estimators(): + """Smoke test for init estimators with sample weights. """ + rng = check_random_state(13) + X = rng.rand(100, 2) + sample_weight = np.ones(100) + reg_y = rng.rand(100) + + clf_y = rng.randint(0, 2, size=100) + + for Loss in LOSS_FUNCTIONS.values(): + if Loss is None: + continue + if issubclass(Loss, RegressionLossFunction): + k = 1 + y = reg_y + else: + k = 2 + y = clf_y + if Loss.is_multi_class: + # skip multiclass + continue + + loss = Loss(k) + init_est = loss.init_estimator() + init_est.fit(X, y) + out = init_est.predict(X) + assert_equal(out.shape, (y.shape[0], 1)) + + sw_init_est = loss.init_estimator() + sw_init_est.fit(X, y, sample_weight=sample_weight) + sw_out = init_est.predict(X) + assert_equal(sw_out.shape, (y.shape[0], 1)) + + # check if predictions match + assert_array_equal(out, sw_out) + + +def test_weighted_percentile(): + y = np.empty(102, dtype=np.float) + y[:50] = 0 + y[-51:] = 2 + y[-1] = 100000 + y[50] = 1 + sw = np.ones(102, dtype=np.float) + sw[-1] = 0.0 + score = _weighted_percentile(y, sw, 50) + assert score == 1 + + +def test_weighted_percentile_equal(): + y = np.empty(102, dtype=np.float) + y.fill(0.0) + sw = np.ones(102, dtype=np.float) + sw[-1] = 0.0 + score = _weighted_percentile(y, sw, 50) + assert score == 0 + + +def test_weighted_percentile_zero_weight(): + y = np.empty(102, dtype=np.float) + y.fill(1.0) + sw = np.ones(102, dtype=np.float) + sw.fill(0.0) + score = _weighted_percentile(y, sw, 50) + assert score == 1.0 + + +def test_sample_weight_deviance(): + """Test if deviance supports sample weights. """ + rng = check_random_state(13) + X = rng.rand(100, 2) + sample_weight = np.ones(100) + reg_y = rng.rand(100) + clf_y = rng.randint(0, 2, size=100) + mclf_y = rng.randint(0, 3, size=100) + + for Loss in LOSS_FUNCTIONS.values(): + if Loss is None: + continue + if issubclass(Loss, RegressionLossFunction): + k = 1 + y = reg_y + p = reg_y + else: + k = 2 + y = clf_y + p = clf_y + if Loss.is_multi_class: + k = 3 + y = mclf_y + # one-hot encoding + p = np.zeros((y.shape[0], k), dtype=np.float64) + for i in range(k): + p[:, i] = y == i + + loss = Loss(k) + deviance_w_w = loss(y, p, sample_weight) + deviance_wo_w = loss(y, p) + assert deviance_wo_w == deviance_w_w diff --git a/sklearn/ensemble/tests/test_partial_dependence.py b/sklearn/ensemble/tests/test_partial_dependence.py new file mode 100644 index 0000000000000..feebbe2480c0e --- /dev/null +++ b/sklearn/ensemble/tests/test_partial_dependence.py @@ -0,0 +1,206 @@ +""" +Testing for the partial dependence module. +""" + +import numpy as np +from numpy.testing import assert_array_equal + +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import if_matplotlib +from sklearn.ensemble.partial_dependence import partial_dependence +from sklearn.ensemble.partial_dependence import plot_partial_dependence +from sklearn.ensemble import GradientBoostingClassifier +from sklearn.ensemble import GradientBoostingRegressor +from sklearn import datasets + + +# toy sample +X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] +y = [-1, -1, -1, 1, 1, 1] +T = [[-1, -1], [2, 2], [3, 2]] +true_result = [-1, 1, 1] + +# also load the boston dataset +boston = datasets.load_boston() + +# also load the iris dataset +iris = datasets.load_iris() + + +def test_partial_dependence_classifier(): + """Test partial dependence for classifier """ + clf = GradientBoostingClassifier(n_estimators=10, random_state=1) + clf.fit(X, y) + + pdp, axes = partial_dependence(clf, [0], X=X, grid_resolution=5) + + # only 4 grid points instead of 5 because only 4 unique X[:,0] vals + assert pdp.shape == (1, 4) + assert axes[0].shape[0] == 4 + + # now with our own grid + X_ = np.asarray(X) + grid = np.unique(X_[:, 0]) + pdp_2, axes = partial_dependence(clf, [0], grid=grid) + + assert axes is None + assert_array_equal(pdp, pdp_2) + + +def test_partial_dependence_multiclass(): + """Test partial dependence for multi-class classifier """ + clf = GradientBoostingClassifier(n_estimators=10, random_state=1) + clf.fit(iris.data, iris.target) + + grid_resolution = 25 + n_classes = clf.n_classes_ + pdp, axes = partial_dependence( + clf, [0], X=iris.data, grid_resolution=grid_resolution) + + assert pdp.shape == (n_classes, grid_resolution) + assert len(axes) == 1 + assert axes[0].shape[0] == grid_resolution + + +def test_partial_dependence_regressor(): + """Test partial dependence for regressor """ + clf = GradientBoostingRegressor(n_estimators=10, random_state=1) + clf.fit(boston.data, boston.target) + + grid_resolution = 25 + pdp, axes = partial_dependence( + clf, [0], X=boston.data, grid_resolution=grid_resolution) + + assert pdp.shape == (1, grid_resolution) + assert axes[0].shape[0] == grid_resolution + + +def test_partial_dependecy_input(): + """Test input validation of partial dependence. """ + clf = GradientBoostingClassifier(n_estimators=10, random_state=1) + clf.fit(X, y) + + assert_raises(ValueError, partial_dependence, + clf, [0], grid=None, X=None) + + assert_raises(ValueError, partial_dependence, + clf, [0], grid=[0, 1], X=X) + + # first argument must be an instance of BaseGradientBoosting + assert_raises(ValueError, partial_dependence, + {}, [0], X=X) + + # Gradient boosting estimator must be fit + assert_raises(ValueError, partial_dependence, + GradientBoostingClassifier(), [0], X=X) + + assert_raises(ValueError, partial_dependence, clf, [-1], X=X) + + assert_raises(ValueError, partial_dependence, clf, [100], X=X) + + # wrong ndim for grid + grid = np.random.rand(10, 2, 1) + assert_raises(ValueError, partial_dependence, clf, [0], grid=grid) + + +@if_matplotlib +def test_plot_partial_dependence(): + """Test partial dependence plot function. """ + clf = GradientBoostingRegressor(n_estimators=10, random_state=1) + clf.fit(boston.data, boston.target) + + grid_resolution = 25 + fig, axs = plot_partial_dependence(clf, boston.data, [0, 1, (0, 1)], + grid_resolution=grid_resolution, + feature_names=boston.feature_names) + assert len(axs) == 3 + assert all(ax.has_data for ax in axs) + + # check with str features and array feature names + fig, axs = plot_partial_dependence(clf, boston.data, ['CRIM', 'ZN', + ('CRIM', 'ZN')], + grid_resolution=grid_resolution, + feature_names=boston.feature_names) + + assert len(axs) == 3 + assert all(ax.has_data for ax in axs) + + # check with list feature_names + feature_names = boston.feature_names.tolist() + fig, axs = plot_partial_dependence(clf, boston.data, ['CRIM', 'ZN', + ('CRIM', 'ZN')], + grid_resolution=grid_resolution, + feature_names=feature_names) + assert len(axs) == 3 + assert all(ax.has_data for ax in axs) + + +@if_matplotlib +def test_plot_partial_dependence_input(): + """Test partial dependence plot function input checks. """ + clf = GradientBoostingClassifier(n_estimators=10, random_state=1) + + # not fitted yet + assert_raises(ValueError, plot_partial_dependence, + clf, X, [0]) + + clf.fit(X, y) + + assert_raises(ValueError, plot_partial_dependence, + clf, np.array(X)[:, :0], [0]) + + # first argument must be an instance of BaseGradientBoosting + assert_raises(ValueError, plot_partial_dependence, + {}, X, [0]) + + # must be larger than -1 + assert_raises(ValueError, plot_partial_dependence, + clf, X, [-1]) + + # too large feature value + assert_raises(ValueError, plot_partial_dependence, + clf, X, [100]) + + # str feature but no feature_names + assert_raises(ValueError, plot_partial_dependence, + clf, X, ['foobar']) + + # not valid features value + assert_raises(ValueError, plot_partial_dependence, + clf, X, [{'foo': 'bar'}]) + + +@if_matplotlib +def test_plot_partial_dependence_multiclass(): + """Test partial dependence plot function on multi-class input. """ + clf = GradientBoostingClassifier(n_estimators=10, random_state=1) + clf.fit(iris.data, iris.target) + + grid_resolution = 25 + fig, axs = plot_partial_dependence(clf, iris.data, [0, 1], + label=0, + grid_resolution=grid_resolution) + assert len(axs) == 2 + assert all(ax.has_data for ax in axs) + + # now with symbol labels + target = iris.target_names[iris.target] + clf = GradientBoostingClassifier(n_estimators=10, random_state=1) + clf.fit(iris.data, target) + + grid_resolution = 25 + fig, axs = plot_partial_dependence(clf, iris.data, [0, 1], + label='setosa', + grid_resolution=grid_resolution) + assert len(axs) == 2 + assert all(ax.has_data for ax in axs) + + # label not in gbrt.classes_ + assert_raises(ValueError, plot_partial_dependence, + clf, iris.data, [0, 1], label='foobar', + grid_resolution=grid_resolution) + + # label not provided + assert_raises(ValueError, plot_partial_dependence, + clf, iris.data, [0, 1], + grid_resolution=grid_resolution) diff --git a/sklearn/ensemble/tests/test_weight_boosting.py b/sklearn/ensemble/tests/test_weight_boosting.py new file mode 100755 index 0000000000000..608007623d81d --- /dev/null +++ b/sklearn/ensemble/tests/test_weight_boosting.py @@ -0,0 +1,426 @@ +"""Testing for the boost module (sklearn.ensemble.boost).""" + +import numpy as np +from sklearn.utils.testing import assert_array_equal, assert_array_less +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_raises, assert_raises_regexp + +from sklearn.cross_validation import train_test_split +from sklearn.grid_search import GridSearchCV +from sklearn.ensemble import AdaBoostClassifier +from sklearn.ensemble import AdaBoostRegressor +from scipy.sparse import csc_matrix +from scipy.sparse import csr_matrix +from scipy.sparse import coo_matrix +from scipy.sparse import dok_matrix +from scipy.sparse import lil_matrix +from sklearn.svm import SVC, SVR +from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor +from sklearn.utils import shuffle +from sklearn import datasets + + +# Common random state +rng = np.random.RandomState(0) + +# Toy sample +X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] +y_class = ["foo", "foo", "foo", 1, 1, 1] # test string class labels +y_regr = [-1, -1, -1, 1, 1, 1] +T = [[-1, -1], [2, 2], [3, 2]] +y_t_class = ["foo", 1, 1] +y_t_regr = [-1, 1, 1] + +# Load the iris dataset and randomly permute it +iris = datasets.load_iris() +perm = rng.permutation(iris.target.size) +iris.data, iris.target = shuffle(iris.data, iris.target, random_state=rng) + +# Load the boston dataset and randomly permute it +boston = datasets.load_boston() +boston.data, boston.target = shuffle(boston.data, boston.target, + random_state=rng) + + +def test_classification_toy(): + """Check classification on a toy dataset.""" + for alg in ['SAMME', 'SAMME.R']: + clf = AdaBoostClassifier(algorithm=alg, random_state=0) + clf.fit(X, y_class) + assert_array_equal(clf.predict(T), y_t_class) + assert_array_equal(np.unique(np.asarray(y_t_class)), clf.classes_) + assert_equal(clf.predict_proba(T).shape, (len(T), 2)) + assert_equal(clf.decision_function(T).shape, (len(T),)) + + +def test_regression_toy(): + """Check classification on a toy dataset.""" + clf = AdaBoostRegressor(random_state=0) + clf.fit(X, y_regr) + assert_array_equal(clf.predict(T), y_t_regr) + + +def test_iris(): + """Check consistency on dataset iris.""" + classes = np.unique(iris.target) + clf_samme = prob_samme = None + + for alg in ['SAMME', 'SAMME.R']: + clf = AdaBoostClassifier(algorithm=alg) + clf.fit(iris.data, iris.target) + + assert_array_equal(classes, clf.classes_) + proba = clf.predict_proba(iris.data) + if alg == "SAMME": + clf_samme = clf + prob_samme = proba + assert_equal(proba.shape[1], len(classes)) + assert_equal(clf.decision_function(iris.data).shape[1], len(classes)) + + score = clf.score(iris.data, iris.target) + assert score > 0.9, "Failed with algorithm %s and score = %f" % \ + (alg, score) + + # Somewhat hacky regression test: prior to + # ae7adc880d624615a34bafdb1d75ef67051b8200, + # predict_proba returned SAMME.R values for SAMME. + clf_samme.algorithm = "SAMME.R" + assert_array_less(0, + np.abs(clf_samme.predict_proba(iris.data) - prob_samme)) + + +def test_boston(): + """Check consistency on dataset boston house prices.""" + clf = AdaBoostRegressor(random_state=0) + clf.fit(boston.data, boston.target) + score = clf.score(boston.data, boston.target) + assert score > 0.85 + + +def test_staged_predict(): + """Check staged predictions.""" + rng = np.random.RandomState(0) + iris_weights = rng.randint(10, size=iris.target.shape) + boston_weights = rng.randint(10, size=boston.target.shape) + + # AdaBoost classification + for alg in ['SAMME', 'SAMME.R']: + clf = AdaBoostClassifier(algorithm=alg, n_estimators=10) + clf.fit(iris.data, iris.target, sample_weight=iris_weights) + + predictions = clf.predict(iris.data) + staged_predictions = [p for p in clf.staged_predict(iris.data)] + proba = clf.predict_proba(iris.data) + staged_probas = [p for p in clf.staged_predict_proba(iris.data)] + score = clf.score(iris.data, iris.target, sample_weight=iris_weights) + staged_scores = [ + s for s in clf.staged_score( + iris.data, iris.target, sample_weight=iris_weights)] + + assert_equal(len(staged_predictions), 10) + assert_array_almost_equal(predictions, staged_predictions[-1]) + assert_equal(len(staged_probas), 10) + assert_array_almost_equal(proba, staged_probas[-1]) + assert_equal(len(staged_scores), 10) + assert_array_almost_equal(score, staged_scores[-1]) + + # AdaBoost regression + clf = AdaBoostRegressor(n_estimators=10, random_state=0) + clf.fit(boston.data, boston.target, sample_weight=boston_weights) + + predictions = clf.predict(boston.data) + staged_predictions = [p for p in clf.staged_predict(boston.data)] + score = clf.score(boston.data, boston.target, sample_weight=boston_weights) + staged_scores = [ + s for s in clf.staged_score( + boston.data, boston.target, sample_weight=boston_weights)] + + assert_equal(len(staged_predictions), 10) + assert_array_almost_equal(predictions, staged_predictions[-1]) + assert_equal(len(staged_scores), 10) + assert_array_almost_equal(score, staged_scores[-1]) + + +def test_gridsearch(): + """Check that base trees can be grid-searched.""" + # AdaBoost classification + boost = AdaBoostClassifier(base_estimator=DecisionTreeClassifier()) + parameters = {'n_estimators': (1, 2), + 'base_estimator__max_depth': (1, 2), + 'algorithm': ('SAMME', 'SAMME.R')} + clf = GridSearchCV(boost, parameters) + clf.fit(iris.data, iris.target) + + # AdaBoost regression + boost = AdaBoostRegressor(base_estimator=DecisionTreeRegressor(), + random_state=0) + parameters = {'n_estimators': (1, 2), + 'base_estimator__max_depth': (1, 2)} + clf = GridSearchCV(boost, parameters) + clf.fit(boston.data, boston.target) + + +def test_pickle(): + """Check pickability.""" + import pickle + + # Adaboost classifier + for alg in ['SAMME', 'SAMME.R']: + obj = AdaBoostClassifier(algorithm=alg) + obj.fit(iris.data, iris.target) + score = obj.score(iris.data, iris.target) + s = pickle.dumps(obj) + + obj2 = pickle.loads(s) + assert_equal(type(obj2), obj.__class__) + score2 = obj2.score(iris.data, iris.target) + assert_equal(score, score2) + + # Adaboost regressor + obj = AdaBoostRegressor(random_state=0) + obj.fit(boston.data, boston.target) + score = obj.score(boston.data, boston.target) + s = pickle.dumps(obj) + + obj2 = pickle.loads(s) + assert_equal(type(obj2), obj.__class__) + score2 = obj2.score(boston.data, boston.target) + assert_equal(score, score2) + + +def test_importances(): + """Check variable importances.""" + X, y = datasets.make_classification(n_samples=2000, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=1) + + for alg in ['SAMME', 'SAMME.R']: + clf = AdaBoostClassifier(algorithm=alg) + + clf.fit(X, y) + importances = clf.feature_importances_ + + assert_equal(importances.shape[0], 10) + assert_equal((importances[:3, np.newaxis] >= importances[3:]).all(), + True) + + +def test_error(): + """Test that it gives proper exception on deficient input.""" + assert_raises(ValueError, + AdaBoostClassifier(learning_rate=-1).fit, + X, y_class) + + assert_raises(ValueError, + AdaBoostClassifier(algorithm="foo").fit, + X, y_class) + + assert_raises(ValueError, + AdaBoostClassifier().fit, + X, y_class, sample_weight=np.asarray([-1])) + + +def test_base_estimator(): + """Test different base estimators.""" + from sklearn.ensemble import RandomForestClassifier + from sklearn.svm import SVC + + # XXX doesn't work with y_class because RF doesn't support classes_ + # Shouldn't AdaBoost run a LabelBinarizer? + clf = AdaBoostClassifier(RandomForestClassifier()) + clf.fit(X, y_regr) + + clf = AdaBoostClassifier(SVC(), algorithm="SAMME") + clf.fit(X, y_class) + + from sklearn.ensemble import RandomForestRegressor + from sklearn.svm import SVR + + clf = AdaBoostRegressor(RandomForestRegressor(), random_state=0) + clf.fit(X, y_regr) + + clf = AdaBoostRegressor(SVR(), random_state=0) + clf.fit(X, y_regr) + + # Check that an empty discrete ensemble fails in fit, not predict. + X_fail = [[1, 1], [1, 1], [1, 1], [1, 1]] + y_fail = ["foo", "bar", 1, 2] + clf = AdaBoostClassifier(SVC(), algorithm="SAMME") + assert_raises_regexp(ValueError, "worse than random", + clf.fit, X_fail, y_fail) + + +def test_sample_weight_missing(): + from sklearn.linear_model import LinearRegression + from sklearn.cluster import KMeans + + clf = AdaBoostClassifier(LinearRegression(), algorithm="SAMME") + assert_raises(ValueError, clf.fit, X, y_regr) + + clf = AdaBoostRegressor(LinearRegression()) + assert_raises(ValueError, clf.fit, X, y_regr) + + clf = AdaBoostClassifier(KMeans(), algorithm="SAMME") + assert_raises(ValueError, clf.fit, X, y_regr) + + clf = AdaBoostRegressor(KMeans()) + assert_raises(ValueError, clf.fit, X, y_regr) + + +def test_sparse_classification(): + """Check classification with sparse input.""" + + class CustomSVC(SVC): + """SVC variant that records the nature of the training set.""" + + def fit(self, X, y, sample_weight=None): + """Modification on fit caries data type for later verification.""" + super(CustomSVC, self).fit(X, y, sample_weight=sample_weight) + self.data_type_ = type(X) + return self + + X, y = datasets.make_multilabel_classification(n_classes=1, n_samples=15, + n_features=5, + return_indicator=True, + random_state=42) + # Flatten y to a 1d array + y = np.ravel(y) + + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + + for sparse_format in [csc_matrix, csr_matrix, lil_matrix, coo_matrix, + dok_matrix]: + X_train_sparse = sparse_format(X_train) + X_test_sparse = sparse_format(X_test) + + # Trained on sparse format + sparse_classifier = AdaBoostClassifier( + base_estimator=CustomSVC(probability=True), + random_state=1, + algorithm="SAMME" + ).fit(X_train_sparse, y_train) + + # Trained on dense format + dense_classifier = AdaBoostClassifier( + base_estimator=CustomSVC(probability=True), + random_state=1, + algorithm="SAMME" + ).fit(X_train, y_train) + + # predict + sparse_results = sparse_classifier.predict(X_test_sparse) + dense_results = dense_classifier.predict(X_test) + assert_array_equal(sparse_results, dense_results) + + # decision_function + sparse_results = sparse_classifier.decision_function(X_test_sparse) + dense_results = dense_classifier.decision_function(X_test) + assert_array_equal(sparse_results, dense_results) + + # predict_log_proba + sparse_results = sparse_classifier.predict_log_proba(X_test_sparse) + dense_results = dense_classifier.predict_log_proba(X_test) + assert_array_equal(sparse_results, dense_results) + + # predict_proba + sparse_results = sparse_classifier.predict_proba(X_test_sparse) + dense_results = dense_classifier.predict_proba(X_test) + assert_array_equal(sparse_results, dense_results) + + # score + sparse_results = sparse_classifier.score(X_test_sparse, y_test) + dense_results = dense_classifier.score(X_test, y_test) + assert_array_equal(sparse_results, dense_results) + + # staged_decision_function + sparse_results = sparse_classifier.staged_decision_function( + X_test_sparse) + dense_results = dense_classifier.staged_decision_function(X_test) + for sprase_res, dense_res in zip(sparse_results, dense_results): + assert_array_equal(sprase_res, dense_res) + + # staged_predict + sparse_results = sparse_classifier.staged_predict(X_test_sparse) + dense_results = dense_classifier.staged_predict(X_test) + for sprase_res, dense_res in zip(sparse_results, dense_results): + assert_array_equal(sprase_res, dense_res) + + # staged_predict_proba + sparse_results = sparse_classifier.staged_predict_proba(X_test_sparse) + dense_results = dense_classifier.staged_predict_proba(X_test) + for sprase_res, dense_res in zip(sparse_results, dense_results): + assert_array_equal(sprase_res, dense_res) + + # staged_score + sparse_results = sparse_classifier.staged_score(X_test_sparse, + y_test) + dense_results = dense_classifier.staged_score(X_test, y_test) + for sprase_res, dense_res in zip(sparse_results, dense_results): + assert_array_equal(sprase_res, dense_res) + + # Verify sparsity of data is maintained during training + types = [i.data_type_ for i in sparse_classifier.estimators_] + + assert all([(t == csc_matrix or t == csr_matrix) + for t in types]) + + +def test_sparse_regression(): + """Check regression with sparse input.""" + + class CustomSVR(SVR): + """SVR variant that records the nature of the training set.""" + + def fit(self, X, y, sample_weight=None): + """Modification on fit caries data type for later verification.""" + super(CustomSVR, self).fit(X, y, sample_weight=sample_weight) + self.data_type_ = type(X) + return self + + X, y = datasets.make_regression(n_samples=15, n_features=50, n_targets=1, + random_state=42) + + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + + for sparse_format in [csc_matrix, csr_matrix, lil_matrix, coo_matrix, + dok_matrix]: + X_train_sparse = sparse_format(X_train) + X_test_sparse = sparse_format(X_test) + + # Trained on sparse format + sparse_classifier = AdaBoostRegressor( + base_estimator=CustomSVR(), + random_state=1 + ).fit(X_train_sparse, y_train) + + # Trained on dense format + dense_classifier = dense_results = AdaBoostRegressor( + base_estimator=CustomSVR(), + random_state=1 + ).fit(X_train, y_train) + + # predict + sparse_results = sparse_classifier.predict(X_test_sparse) + dense_results = dense_classifier.predict(X_test) + assert_array_equal(sparse_results, dense_results) + + # staged_predict + sparse_results = sparse_classifier.staged_predict(X_test_sparse) + dense_results = dense_classifier.staged_predict(X_test) + for sprase_res, dense_res in zip(sparse_results, dense_results): + assert_array_equal(sprase_res, dense_res) + + types = [i.data_type_ for i in sparse_classifier.estimators_] + + assert all([(t == csc_matrix or t == csr_matrix) + for t in types]) + + +if __name__ == "__main__": + import nose + nose.runmodule() diff --git a/sklearn/ensemble/weight_boosting.py b/sklearn/ensemble/weight_boosting.py new file mode 100644 index 0000000000000..3a4187f6fae5c --- /dev/null +++ b/sklearn/ensemble/weight_boosting.py @@ -0,0 +1,1121 @@ +"""Weight Boosting + +This module contains weight boosting estimators for both classification and +regression. + +The module structure is the following: + +- The ``BaseWeightBoosting`` base class implements a common ``fit`` method + for all the estimators in the module. Regression and classification + only differ from each other in the loss function that is optimized. + +- ``AdaBoostClassifier`` implements adaptive boosting (AdaBoost-SAMME) for + classification problems. + +- ``AdaBoostRegressor`` implements adaptive boosting (AdaBoost.R2) for + regression problems. +""" + +# Authors: Noel Dawe +# Gilles Louppe +# Hamzeh Alsalhi +# Arnaud Joly +# +# Licence: BSD 3 clause + +from abc import ABCMeta, abstractmethod + +import numpy as np +from numpy.core.umath_tests import inner1d + +from .base import BaseEnsemble +from ..base import ClassifierMixin, RegressorMixin +from ..externals import six +from ..externals.six.moves import zip +from ..externals.six.moves import xrange as range +from .forest import BaseForest +from ..tree import DecisionTreeClassifier, DecisionTreeRegressor +from ..tree.tree import BaseDecisionTree +from ..tree._tree import DTYPE +from ..utils import check_array, check_X_y, check_random_state +from ..metrics import accuracy_score, r2_score +from sklearn.utils.validation import ( + has_fit_parameter, + check_is_fitted) + +__all__ = [ + 'AdaBoostClassifier', + 'AdaBoostRegressor', +] + + +class BaseWeightBoosting(six.with_metaclass(ABCMeta, BaseEnsemble)): + """Base class for AdaBoost estimators. + + Warning: This class should not be used directly. Use derived classes + instead. + """ + + @abstractmethod + def __init__(self, + base_estimator=None, + n_estimators=50, + estimator_params=tuple(), + learning_rate=1., + random_state=None): + + super(BaseWeightBoosting, self).__init__( + base_estimator=base_estimator, + n_estimators=n_estimators, + estimator_params=estimator_params) + + self.learning_rate = learning_rate + self.random_state = random_state + + def fit(self, X, y, sample_weight=None): + """Build a boosted classifier/regressor from the training set (X, y). + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. COO, DOK, and LIL are converted to CSR. The dtype is + forced to DTYPE from tree._tree if the base classifier of this + ensemble weighted boosting classifier is a tree or forest. + + y : array-like of shape = [n_samples] + The target values (class labels in classification, real numbers in + regression). + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. If None, the sample weights are initialized to + 1 / n_samples. + + Returns + ------- + self : object + Returns self. + """ + # Check parameters + if self.learning_rate <= 0: + raise ValueError("learning_rate must be greater than zero") + + if (self.base_estimator is None or + isinstance(self.base_estimator, (BaseDecisionTree, + BaseForest))): + dtype = DTYPE + accept_sparse = 'csc' + else: + dtype = None + accept_sparse = ['csr', 'csc'] + + X, y = check_X_y(X, y, accept_sparse=accept_sparse, dtype=dtype) + + if sample_weight is None: + # Initialize weights to 1 / n_samples + sample_weight = np.empty(X.shape[0], dtype=np.float) + sample_weight[:] = 1. / X.shape[0] + else: + # Normalize existing weights + sample_weight = sample_weight / sample_weight.sum(dtype=np.float64) + + # Check that the sample weights sum is positive + if sample_weight.sum() <= 0: + raise ValueError( + "Attempting to fit with a non-positive " + "weighted number of samples.") + + # Check parameters + self._validate_estimator() + + # Clear any previous fit results + self.estimators_ = [] + self.estimator_weights_ = np.zeros(self.n_estimators, dtype=np.float) + self.estimator_errors_ = np.ones(self.n_estimators, dtype=np.float) + + for iboost in range(self.n_estimators): + # Boosting step + sample_weight, estimator_weight, estimator_error = self._boost( + iboost, + X, y, + sample_weight) + + # Early termination + if sample_weight is None: + break + + self.estimator_weights_[iboost] = estimator_weight + self.estimator_errors_[iboost] = estimator_error + + # Stop if error is zero + if estimator_error == 0: + break + + sample_weight_sum = np.sum(sample_weight) + + # Stop if the sum of sample weights has become non-positive + if sample_weight_sum <= 0: + break + + if iboost < self.n_estimators - 1: + # Normalize + sample_weight /= sample_weight_sum + + return self + + @abstractmethod + def _boost(self, iboost, X, y, sample_weight): + """Implement a single boost. + + Warning: This method needs to be overriden by subclasses. + + Parameters + ---------- + iboost : int + The index of the current boost iteration. + + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. COO, DOK, and LIL are converted to CSR. + + y : array-like of shape = [n_samples] + The target values (class labels). + + sample_weight : array-like of shape = [n_samples] + The current sample weights. + + Returns + ------- + sample_weight : array-like of shape = [n_samples] or None + The reweighted sample weights. + If None then boosting has terminated early. + + estimator_weight : float + The weight for the current boost. + If None then boosting has terminated early. + + error : float + The classification error for the current boost. + If None then boosting has terminated early. + """ + pass + + def staged_score(self, X, y, sample_weight=None): + """Return staged scores for X, y. + + This generator method yields the ensemble score after each iteration of + boosting and therefore allows monitoring, such as to determine the + score on a test set after each boost. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + y : array-like, shape = [n_samples] + Labels for X. + + sample_weight : array-like, shape = [n_samples], optional + Sample weights. + + Returns + ------- + z : float + """ + for y_pred in self.staged_predict(X): + if isinstance(self, ClassifierMixin): + yield accuracy_score(y, y_pred, sample_weight=sample_weight) + else: + yield r2_score(y, y_pred, sample_weight=sample_weight) + + @property + def feature_importances_(self): + """Return the feature importances (the higher, the more important the + feature). + + Returns + ------- + feature_importances_ : array, shape = [n_features] + """ + if self.estimators_ is None or len(self.estimators_) == 0: + raise ValueError("Estimator not fitted, " + "call `fit` before `feature_importances_`.") + + try: + norm = self.estimator_weights_.sum() + return (sum(weight * clf.feature_importances_ for weight, clf + in zip(self.estimator_weights_, self.estimators_)) + / norm) + + except AttributeError: + raise AttributeError( + "Unable to compute feature importances " + "since base_estimator does not have a " + "feature_importances_ attribute") + + def _check_sample_weight(self): + if not has_fit_parameter(self.base_estimator_, "sample_weight"): + raise ValueError("%s doesn't support sample_weight." + % self.base_estimator_.__class__.__name__) + + def _validate_X_predict(self, X): + """Ensure that X is in the proper format""" + if (self.base_estimator is None or + isinstance(self.base_estimator, + (BaseDecisionTree, BaseForest))): + X = check_array(X, accept_sparse='csr', dtype=DTYPE) + + else: + X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) + + return X + +def _samme_proba(estimator, n_classes, X): + """Calculate algorithm 4, step 2, equation c) of Zhu et al [1]. + + References + ---------- + .. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009. + + """ + proba = estimator.predict_proba(X) + + # Displace zero probabilities so the log is defined. + # Also fix negative elements which may occur with + # negative sample weights. + proba[proba <= 0] = 1e-5 + log_proba = np.log(proba) + + return (n_classes - 1) * (log_proba - (1. / n_classes) + * log_proba.sum(axis=1)[:, np.newaxis]) + + +class AdaBoostClassifier(BaseWeightBoosting, ClassifierMixin): + """An AdaBoost classifier. + + An AdaBoost [1] classifier is a meta-estimator that begins by fitting a + classifier on the original dataset and then fits additional copies of the + classifier on the same dataset but where the weights of incorrectly + classified instances are adjusted such that subsequent classifiers focus + more on difficult cases. + + This class implements the algorithm known as AdaBoost-SAMME [2]. + + Parameters + ---------- + base_estimator : object, optional (default=DecisionTreeClassifier) + The base estimator from which the boosted ensemble is built. + Support for sample weighting is required, as well as proper `classes_` + and `n_classes_` attributes. + + n_estimators : integer, optional (default=50) + The maximum number of estimators at which boosting is terminated. + In case of perfect fit, the learning procedure is stopped early. + + learning_rate : float, optional (default=1.) + Learning rate shrinks the contribution of each classifier by + ``learning_rate``. There is a trade-off between ``learning_rate`` and + ``n_estimators``. + + algorithm : {'SAMME', 'SAMME.R'}, optional (default='SAMME.R') + If 'SAMME.R' then use the SAMME.R real boosting algorithm. + ``base_estimator`` must support calculation of class probabilities. + If 'SAMME' then use the SAMME discrete boosting algorithm. + The SAMME.R algorithm typically converges faster than SAMME, + achieving a lower test error with fewer boosting iterations. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + Attributes + ---------- + estimators_ : list of classifiers + The collection of fitted sub-estimators. + + classes_ : array of shape = [n_classes] + The classes labels. + + n_classes_ : int + The number of classes. + + estimator_weights_ : array of floats + Weights for each estimator in the boosted ensemble. + + estimator_errors_ : array of floats + Classification error for each estimator in the boosted + ensemble. + + feature_importances_ : array of shape = [n_features] + The feature importances if supported by the ``base_estimator``. + + See also + -------- + AdaBoostRegressor, GradientBoostingClassifier, DecisionTreeClassifier + + References + ---------- + .. [1] Y. Freund, R. Schapire, "A Decision-Theoretic Generalization of + on-Line Learning and an Application to Boosting", 1995. + + .. [2] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009. + + """ + def __init__(self, + base_estimator=None, + n_estimators=50, + learning_rate=1., + algorithm='SAMME.R', + random_state=None): + + super(AdaBoostClassifier, self).__init__( + base_estimator=base_estimator, + n_estimators=n_estimators, + learning_rate=learning_rate, + random_state=random_state) + + self.algorithm = algorithm + + def fit(self, X, y, sample_weight=None): + """Build a boosted classifier from the training set (X, y). + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + y : array-like of shape = [n_samples] + The target values (class labels). + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. If None, the sample weights are initialized to + ``1 / n_samples``. + + Returns + ------- + self : object + Returns self. + """ + # Check that algorithm is supported + if self.algorithm not in ('SAMME', 'SAMME.R'): + raise ValueError("algorithm %s is not supported" % self.algorithm) + + # Fit + return super(AdaBoostClassifier, self).fit(X, y, sample_weight) + + def _validate_estimator(self): + """Check the estimator and set the base_estimator_ attribute.""" + super(AdaBoostClassifier, self)._validate_estimator( + default=DecisionTreeClassifier(max_depth=1)) + + # SAMME-R requires predict_proba-enabled base estimators + if self.algorithm == 'SAMME.R': + if not hasattr(self.base_estimator_, 'predict_proba'): + raise TypeError( + "AdaBoostClassifier with algorithm='SAMME.R' requires " + "that the weak learner supports the calculation of class " + "probabilities with a predict_proba method.\n" + "Please change the base estimator or set " + "algorithm='SAMME' instead.") + self._check_sample_weight() + + def _boost(self, iboost, X, y, sample_weight): + """Implement a single boost. + + Perform a single boost according to the real multi-class SAMME.R + algorithm or to the discrete SAMME algorithm and return the updated + sample weights. + + Parameters + ---------- + iboost : int + The index of the current boost iteration. + + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + y : array-like of shape = [n_samples] + The target values (class labels). + + sample_weight : array-like of shape = [n_samples] + The current sample weights. + + Returns + ------- + sample_weight : array-like of shape = [n_samples] or None + The reweighted sample weights. + If None then boosting has terminated early. + + estimator_weight : float + The weight for the current boost. + If None then boosting has terminated early. + + estimator_error : float + The classification error for the current boost. + If None then boosting has terminated early. + """ + if self.algorithm == 'SAMME.R': + return self._boost_real(iboost, X, y, sample_weight) + + else: # elif self.algorithm == "SAMME": + return self._boost_discrete(iboost, X, y, sample_weight) + + def _boost_real(self, iboost, X, y, sample_weight): + """Implement a single boost using the SAMME.R real algorithm.""" + estimator = self._make_estimator() + + try: + estimator.set_params(random_state=self.random_state) + except ValueError: + pass + + estimator.fit(X, y, sample_weight=sample_weight) + + y_predict_proba = estimator.predict_proba(X) + + if iboost == 0: + self.classes_ = getattr(estimator, 'classes_', None) + self.n_classes_ = len(self.classes_) + + y_predict = self.classes_.take(np.argmax(y_predict_proba, axis=1), + axis=0) + + # Instances incorrectly classified + incorrect = y_predict != y + + # Error fraction + estimator_error = np.mean( + np.average(incorrect, weights=sample_weight, axis=0)) + + # Stop if classification is perfect + if estimator_error <= 0: + return sample_weight, 1., 0. + + # Construct y coding as described in Zhu et al [2]: + # + # y_k = 1 if c == k else -1 / (K - 1) + # + # where K == n_classes_ and c, k in [0, K) are indices along the second + # axis of the y coding with c being the index corresponding to the true + # class label. + n_classes = self.n_classes_ + classes = self.classes_ + y_codes = np.array([-1. / (n_classes - 1), 1.]) + y_coding = y_codes.take(classes == y[:, np.newaxis]) + + # Displace zero probabilities so the log is defined. + # Also fix negative elements which may occur with + # negative sample weights. + y_predict_proba[y_predict_proba <= 0] = 1e-5 + + # Boost weight using multi-class AdaBoost SAMME.R alg + estimator_weight = (-1. * self.learning_rate + * (((n_classes - 1.) / n_classes) * + inner1d(y_coding, np.log(y_predict_proba)))) + + # Only boost the weights if it will fit again + if not iboost == self.n_estimators - 1: + # Only boost positive weights + sample_weight *= np.exp(estimator_weight * + ((sample_weight > 0) | + (estimator_weight < 0))) + + return sample_weight, 1., estimator_error + + def _boost_discrete(self, iboost, X, y, sample_weight): + """Implement a single boost using the SAMME discrete algorithm.""" + estimator = self._make_estimator() + + try: + estimator.set_params(random_state=self.random_state) + except ValueError: + pass + + estimator.fit(X, y, sample_weight=sample_weight) + + y_predict = estimator.predict(X) + + if iboost == 0: + self.classes_ = getattr(estimator, 'classes_', None) + self.n_classes_ = len(self.classes_) + + # Instances incorrectly classified + incorrect = y_predict != y + + # Error fraction + estimator_error = np.mean( + np.average(incorrect, weights=sample_weight, axis=0)) + + # Stop if classification is perfect + if estimator_error <= 0: + return sample_weight, 1., 0. + + n_classes = self.n_classes_ + + # Stop if the error is at least as bad as random guessing + if estimator_error >= 1. - (1. / n_classes): + self.estimators_.pop(-1) + if len(self.estimators_) == 0: + raise ValueError('BaseClassifier in AdaBoostClassifier ' + 'ensemble is worse than random, ensemble ' + 'can not be fit.') + return None, None, None + + # Boost weight using multi-class AdaBoost SAMME alg + estimator_weight = self.learning_rate * ( + np.log((1. - estimator_error) / estimator_error) + + np.log(n_classes - 1.)) + + # Only boost the weights if I will fit again + if not iboost == self.n_estimators - 1: + # Only boost positive weights + sample_weight *= np.exp(estimator_weight * incorrect * + ((sample_weight > 0) | + (estimator_weight < 0))) + + return sample_weight, estimator_weight, estimator_error + + def predict(self, X): + """Predict classes for X. + + The predicted class of an input sample is computed as the weighted mean + prediction of the classifiers in the ensemble. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + Returns + ------- + y : array of shape = [n_samples] + The predicted classes. + """ + pred = self.decision_function(X) + + if self.n_classes_ == 2: + return self.classes_.take(pred > 0, axis=0) + + return self.classes_.take(np.argmax(pred, axis=1), axis=0) + + def staged_predict(self, X): + """Return staged predictions for X. + + The predicted class of an input sample is computed as the weighted mean + prediction of the classifiers in the ensemble. + + This generator method yields the ensemble prediction after each + iteration of boosting and therefore allows monitoring, such as to + determine the prediction on a test set after each boost. + + Parameters + ---------- + X : array-like of shape = [n_samples, n_features] + The input samples. + + Returns + ------- + y : generator of array, shape = [n_samples] + The predicted classes. + """ + n_classes = self.n_classes_ + classes = self.classes_ + + if n_classes == 2: + for pred in self.staged_decision_function(X): + yield np.array(classes.take(pred > 0, axis=0)) + + else: + for pred in self.staged_decision_function(X): + yield np.array(classes.take( + np.argmax(pred, axis=1), axis=0)) + + def decision_function(self, X): + """Compute the decision function of ``X``. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + Returns + ------- + score : array, shape = [n_samples, k] + The decision function of the input samples. The order of + outputs is the same of that of the `classes_` attribute. + Binary classification is a special cases with ``k == 1``, + otherwise ``k==n_classes``. For binary classification, + values closer to -1 or 1 mean more like the first or second + class in ``classes_``, respectively. + """ + check_is_fitted(self, "n_classes_") + X = self._validate_X_predict(X) + + n_classes = self.n_classes_ + classes = self.classes_[:, np.newaxis] + pred = None + + if self.algorithm == 'SAMME.R': + # The weights are all 1. for SAMME.R + pred = sum(_samme_proba(estimator, n_classes, X) + for estimator in self.estimators_) + else: # self.algorithm == "SAMME" + pred = sum((estimator.predict(X) == classes).T * w + for estimator, w in zip(self.estimators_, + self.estimator_weights_)) + + pred /= self.estimator_weights_.sum() + if n_classes == 2: + pred[:, 0] *= -1 + return pred.sum(axis=1) + return pred + + def staged_decision_function(self, X): + """Compute decision function of ``X`` for each boosting iteration. + + This method allows monitoring (i.e. determine error on testing set) + after each boosting iteration. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + Returns + ------- + score : generator of array, shape = [n_samples, k] + The decision function of the input samples. The order of + outputs is the same of that of the `classes_` attribute. + Binary classification is a special cases with ``k == 1``, + otherwise ``k==n_classes``. For binary classification, + values closer to -1 or 1 mean more like the first or second + class in ``classes_``, respectively. + """ + check_is_fitted(self, "n_classes_") + X = self._validate_X_predict(X) + + n_classes = self.n_classes_ + classes = self.classes_[:, np.newaxis] + pred = None + norm = 0. + + for weight, estimator in zip(self.estimator_weights_, + self.estimators_): + norm += weight + + if self.algorithm == 'SAMME.R': + # The weights are all 1. for SAMME.R + current_pred = _samme_proba(estimator, n_classes, X) + else: # elif self.algorithm == "SAMME": + current_pred = estimator.predict(X) + current_pred = (current_pred == classes).T * weight + + if pred is None: + pred = current_pred + else: + pred += current_pred + + if n_classes == 2: + tmp_pred = np.copy(pred) + tmp_pred[:, 0] *= -1 + yield (tmp_pred / norm).sum(axis=1) + else: + yield pred / norm + + def predict_proba(self, X): + """Predict class probabilities for X. + + The predicted class probabilities of an input sample is computed as + the weighted mean predicted class probabilities of the classifiers + in the ensemble. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + Returns + ------- + p : array of shape = [n_samples] + The class probabilities of the input samples. The order of + outputs is the same of that of the `classes_` attribute. + """ + check_is_fitted(self, "n_classes_") + + n_classes = self.n_classes_ + X = self._validate_X_predict(X) + + if self.algorithm == 'SAMME.R': + # The weights are all 1. for SAMME.R + proba = sum(_samme_proba(estimator, n_classes, X) + for estimator in self.estimators_) + else: # self.algorithm == "SAMME" + proba = sum(estimator.predict_proba(X) * w + for estimator, w in zip(self.estimators_, + self.estimator_weights_)) + + proba /= self.estimator_weights_.sum() + proba = np.exp((1. / (n_classes - 1)) * proba) + normalizer = proba.sum(axis=1)[:, np.newaxis] + normalizer[normalizer == 0.0] = 1.0 + proba /= normalizer + + return proba + + def staged_predict_proba(self, X): + """Predict class probabilities for X. + + The predicted class probabilities of an input sample is computed as + the weighted mean predicted class probabilities of the classifiers + in the ensemble. + + This generator method yields the ensemble predicted class probabilities + after each iteration of boosting and therefore allows monitoring, such + as to determine the predicted class probabilities on a test set after + each boost. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + Returns + ------- + p : generator of array, shape = [n_samples] + The class probabilities of the input samples. The order of + outputs is the same of that of the `classes_` attribute. + """ + X = self._validate_X_predict(X) + + n_classes = self.n_classes_ + proba = None + norm = 0. + + for weight, estimator in zip(self.estimator_weights_, + self.estimators_): + norm += weight + + if self.algorithm == 'SAMME.R': + # The weights are all 1. for SAMME.R + current_proba = _samme_proba(estimator, n_classes, X) + else: # elif self.algorithm == "SAMME": + current_proba = estimator.predict_proba(X) * weight + + if proba is None: + proba = current_proba + else: + proba += current_proba + + real_proba = np.exp((1. / (n_classes - 1)) * (proba / norm)) + normalizer = real_proba.sum(axis=1)[:, np.newaxis] + normalizer[normalizer == 0.0] = 1.0 + real_proba /= normalizer + + yield real_proba + + def predict_log_proba(self, X): + """Predict class log-probabilities for X. + + The predicted class log-probabilities of an input sample is computed as + the weighted mean predicted class log-probabilities of the classifiers + in the ensemble. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + Returns + ------- + p : array of shape = [n_samples] + The class probabilities of the input samples. The order of + outputs is the same of that of the `classes_` attribute. + """ + return np.log(self.predict_proba(X)) + + +class AdaBoostRegressor(BaseWeightBoosting, RegressorMixin): + """An AdaBoost regressor. + + An AdaBoost [1] regressor is a meta-estimator that begins by fitting a + regressor on the original dataset and then fits additional copies of the + regressor on the same dataset but where the weights of instances are + adjusted according to the error of the current prediction. As such, + subsequent regressors focus more on difficult cases. + + This class implements the algorithm known as AdaBoost.R2 [2]. + + Parameters + ---------- + base_estimator : object, optional (default=DecisionTreeRegressor) + The base estimator from which the boosted ensemble is built. + Support for sample weighting is required. + + n_estimators : integer, optional (default=50) + The maximum number of estimators at which boosting is terminated. + In case of perfect fit, the learning procedure is stopped early. + + learning_rate : float, optional (default=1.) + Learning rate shrinks the contribution of each regressor by + ``learning_rate``. There is a trade-off between ``learning_rate`` and + ``n_estimators``. + + loss : {'linear', 'square', 'exponential'}, optional (default='linear') + The loss function to use when updating the weights after each + boosting iteration. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + Attributes + ---------- + estimators_ : list of classifiers + The collection of fitted sub-estimators. + + estimator_weights_ : array of floats + Weights for each estimator in the boosted ensemble. + + estimator_errors_ : array of floats + Regression error for each estimator in the boosted ensemble. + + feature_importances_ : array of shape = [n_features] + The feature importances if supported by the ``base_estimator``. + + See also + -------- + AdaBoostClassifier, GradientBoostingRegressor, DecisionTreeRegressor + + References + ---------- + .. [1] Y. Freund, R. Schapire, "A Decision-Theoretic Generalization of + on-Line Learning and an Application to Boosting", 1995. + + .. [2] H. Drucker, "Improving Regressors using Boosting Techniques", 1997. + + """ + def __init__(self, + base_estimator=None, + n_estimators=50, + learning_rate=1., + loss='linear', + random_state=None): + + super(AdaBoostRegressor, self).__init__( + base_estimator=base_estimator, + n_estimators=n_estimators, + learning_rate=learning_rate, + random_state=random_state) + + self.loss = loss + self.random_state = random_state + + def fit(self, X, y, sample_weight=None): + """Build a boosted regressor from the training set (X, y). + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + y : array-like of shape = [n_samples] + The target values (real numbers). + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. If None, the sample weights are initialized to + 1 / n_samples. + + Returns + ------- + self : object + Returns self. + """ + # Check loss + if self.loss not in ('linear', 'square', 'exponential'): + raise ValueError( + "loss must be 'linear', 'square', or 'exponential'") + + # Fit + return super(AdaBoostRegressor, self).fit(X, y, sample_weight) + + def _validate_estimator(self): + """Check the estimator and set the base_estimator_ attribute.""" + super(AdaBoostRegressor, self)._validate_estimator( + default=DecisionTreeRegressor(max_depth=3)) + self._check_sample_weight() + + def _boost(self, iboost, X, y, sample_weight): + """Implement a single boost for regression + + Perform a single boost according to the AdaBoost.R2 algorithm and + return the updated sample weights. + + Parameters + ---------- + iboost : int + The index of the current boost iteration. + + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + y : array-like of shape = [n_samples] + The target values (class labels in classification, real numbers in + regression). + + sample_weight : array-like of shape = [n_samples] + The current sample weights. + + Returns + ------- + sample_weight : array-like of shape = [n_samples] or None + The reweighted sample weights. + If None then boosting has terminated early. + + estimator_weight : float + The weight for the current boost. + If None then boosting has terminated early. + + estimator_error : float + The regression error for the current boost. + If None then boosting has terminated early. + """ + estimator = self._make_estimator() + + try: + estimator.set_params(random_state=self.random_state) + except ValueError: + pass + + generator = check_random_state(self.random_state) + + # Weighted sampling of the training set with replacement + # For NumPy >= 1.7.0 use np.random.choice + cdf = sample_weight.cumsum() + cdf /= cdf[-1] + uniform_samples = generator.random_sample(X.shape[0]) + bootstrap_idx = cdf.searchsorted(uniform_samples, side='right') + # searchsorted returns a scalar + bootstrap_idx = np.array(bootstrap_idx, copy=False) + + # Fit on the bootstrapped sample and obtain a prediction + # for all samples in the training set + estimator.fit(X[bootstrap_idx], y[bootstrap_idx]) + y_predict = estimator.predict(X) + + error_vect = np.abs(y_predict - y) + error_max = error_vect.max() + + if error_max != 0.: + error_vect /= error_max + + if self.loss == 'square': + error_vect **= 2 + elif self.loss == 'exponential': + error_vect = 1. - np.exp(- error_vect) + + # Calculate the average loss + estimator_error = (sample_weight * error_vect).sum() + + if estimator_error <= 0: + # Stop if fit is perfect + return sample_weight, 1., 0. + + elif estimator_error >= 0.5: + # Discard current estimator only if it isn't the only one + if len(self.estimators_) > 1: + self.estimators_.pop(-1) + return None, None, None + + beta = estimator_error / (1. - estimator_error) + + # Boost weight using AdaBoost.R2 alg + estimator_weight = self.learning_rate * np.log(1. / beta) + + if not iboost == self.n_estimators - 1: + sample_weight *= np.power( + beta, + (1. - error_vect) * self.learning_rate) + + return sample_weight, estimator_weight, estimator_error + + def _get_median_predict(self, X, limit): + # Evaluate predictions of all estimators + predictions = np.array([ + est.predict(X) for est in self.estimators_[:limit]]).T + + # Sort the predictions + sorted_idx = np.argsort(predictions, axis=1) + + # Find index of median prediction for each sample + weight_cdf = self.estimator_weights_[sorted_idx].cumsum(axis=1) + median_or_above = weight_cdf >= 0.5 * weight_cdf[:, -1][:, np.newaxis] + median_idx = median_or_above.argmax(axis=1) + + median_estimators = sorted_idx[np.arange(X.shape[0]), median_idx] + + # Return median predictions + return predictions[np.arange(X.shape[0]), median_estimators] + + def predict(self, X): + """Predict regression value for X. + + The predicted regression value of an input sample is computed + as the weighted median prediction of the classifiers in the ensemble. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + Returns + ------- + y : array of shape = [n_samples] + The predicted regression values. + """ + check_is_fitted(self, "estimator_weights_") + X = self._validate_X_predict(X) + + return self._get_median_predict(X, len(self.estimators_)) + + def staged_predict(self, X): + """Return staged predictions for X. + + The predicted regression value of an input sample is computed + as the weighted median prediction of the classifiers in the ensemble. + + This generator method yields the ensemble prediction after each + iteration of boosting and therefore allows monitoring, such as to + determine the prediction on a test set after each boost. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape = [n_samples, n_features] + The training input samples. Sparse matrix can be CSC, CSR, COO, + DOK, or LIL. DOK and LIL are converted to CSR. + + Returns + ------- + y : generator of array, shape = [n_samples] + The predicted regression values. + """ + check_is_fitted(self, "estimator_weights_") + X = self._validate_X_predict(X) + + for i, _ in enumerate(self.estimators_, 1): + yield self._get_median_predict(X, limit=i) diff --git a/sklearn/externals/copy_joblib.sh b/sklearn/externals/copy_joblib.sh index 5e00f65bdde40..52a6cfc362a72 100755 --- a/sklearn/externals/copy_joblib.sh +++ b/sklearn/externals/copy_joblib.sh @@ -2,17 +2,23 @@ # Script to do a local install of joblib rm -rf tmp joblib mkdir -p tmp/lib/python2.7/site-packages -ln -s tmp/lib/python2.7 tmp/lib/python2.5 ln -s tmp/lib/python2.7 tmp/lib/python2.6 mkdir -p tmp/bin -export PYTHONPATH=$(pwd)/tmp/lib/python2.7/site-packages:$(pwd)/tmp/lib/python2.6/site-packages:$(pwd)/tmp/lib/python2.5/site-packages +export PYTHONPATH=$(pwd)/tmp/lib/python2.7/site-packages:$(pwd)/tmp/lib/python2.6/site-packages easy_install -Zeab tmp joblib old_pwd=$(pwd) -#cd /home/varoquau/dev/joblib/ +#cd /home/varoquau/dev/joblib/ cd tmp/joblib/ python setup.py install --prefix $old_pwd/tmp cd $old_pwd cp -r tmp/lib/python2.7/site-packages/joblib-*.egg/joblib . rm -rf tmp # Needed to rewrite the doctests -find joblib -name "*.py" | xargs sed -i "s/from joblib/from sklearn.externals.joblib/" +find joblib -name "*.py" | xargs sed -i.bak "s/from joblib/from sklearn.externals.joblib/" +find joblib -name "*.bak" | xargs rm + +# Remove the tests folders to speed-up test time for scikit-learn. +# joblib is already tested on its own CI infrastructure upstream. +rm -r joblib/test + +chmod -x joblib/*.py diff --git a/sklearn/externals/joblib/__init__.py b/sklearn/externals/joblib/__init__.py index 5c2d87f90f310..f038a4984b213 100644 --- a/sklearn/externals/joblib/__init__.py +++ b/sklearn/externals/joblib/__init__.py @@ -28,19 +28,17 @@ -------- The vision is to provide tools to easily achieve better performance and -reproducibility when working with long running jobs. In addition, Joblib -can also be used to provide a light-weight make replacement or caching -solution. +reproducibility when working with long running jobs. * **Avoid computing twice the same thing**: code is rerun over an over, for instance when prototyping computational-heavy jobs (as in - scientific development), but hand-crafted solution to aleviate this + scientific development), but hand-crafted solution to alleviate this issue is error-prone and often leads to unreproducible results * **Persist to disk transparently**: persisting in an efficient way arbitrary objects containing large data is hard. Using joblib's caching mechanism avoids hand-written persistence and - implicitely links the file on disk to the execution context of + implicitly links the file on disk to the execution context of the original Python object. As a result, joblib's persistence is good for resuming an application status or computational job, eg after a crash. @@ -64,14 +62,14 @@ >>> from sklearn.externals.joblib import Memory >>> mem = Memory(cachedir='/tmp/joblib') >>> import numpy as np - >>> a = np.vander(np.arange(3)) + >>> a = np.vander(np.arange(3)).astype(np.float) >>> square = mem.cache(np.square) >>> b = square(a) # doctest: +ELLIPSIS ________________________________________________________________________________ [Memory] Calling square... - square(array([[0, 0, 1], - [1, 1, 1], - [4, 2, 1]])) + square(array([[ 0., 0., 1.], + [ 1., 1., 1.], + [ 4., 2., 1.]])) ___________________________________________________________square - 0...s, 0.0min >>> c = square(a) @@ -102,10 +100,10 @@ """ -__version__ = '0.6.4' +__version__ = '0.8.4' -from .memory import Memory +from .memory import Memory, MemorizedResult from .logger import PrintTime from .logger import Logger from .hashing import hash diff --git a/sklearn/externals/joblib/_compat.py b/sklearn/externals/joblib/_compat.py new file mode 100644 index 0000000000000..25b204a83a303 --- /dev/null +++ b/sklearn/externals/joblib/_compat.py @@ -0,0 +1,9 @@ +""" +Compatibility layer for Python 3/Python 2 single codebase +""" + +try: + _basestring = basestring +except NameError: + _basestring = str + diff --git a/sklearn/externals/joblib/_multiprocessing_helpers.py b/sklearn/externals/joblib/_multiprocessing_helpers.py new file mode 100644 index 0000000000000..e7ec21f7571d6 --- /dev/null +++ b/sklearn/externals/joblib/_multiprocessing_helpers.py @@ -0,0 +1,40 @@ +"""Helper module to factorize the conditional multiprocessing import logic + +We use a distinct module to simplify import statements and avoid introducing +circular dependencies (for instance for the assert_spawning name). +""" +import os +import warnings + + +# Obtain possible configuration from the environment, assuming 1 (on) +# by default, upon 0 set to None. Should instructively fail if some non +# 0/1 value is set. +mp = int(os.environ.get('JOBLIB_MULTIPROCESSING', 1)) or None +if mp: + try: + import multiprocessing as mp + import multiprocessing.pool + except ImportError: + mp = None + +# 2nd stage: validate that locking is available on the system and +# issue a warning if not +if mp is not None: + try: + _sem = mp.Semaphore() + del _sem # cleanup + except (ImportError, OSError) as e: + mp = None + warnings.warn('%s. joblib will operate in serial mode' % (e,)) + + +# 3rd stage: backward compat for the assert_spawning helper +if mp is not None: + try: + # Python 3.4+ + from multiprocessing.context import assert_spawning + except ImportError: + from multiprocessing.forking import assert_spawning +else: + assert_spawning = None diff --git a/sklearn/externals/joblib/disk.py b/sklearn/externals/joblib/disk.py index f9b7d0a46bd22..4e825c1912d87 100644 --- a/sklearn/externals/joblib/disk.py +++ b/sklearn/externals/joblib/disk.py @@ -52,7 +52,7 @@ def mkdirp(d): """ try: os.makedirs(d) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise @@ -81,7 +81,7 @@ def rm_subdirs(path, onerror=None): names = [] try: names = os.listdir(path) - except os.error, err: + except os.error as err: if onerror is not None: onerror(os.listdir, path, sys.exc_info()) else: @@ -100,7 +100,7 @@ def rm_subdirs(path, onerror=None): try: shutil.rmtree(fullname, False, None) break - except os.error, err: + except os.error: if err_count > 0: raise err_count += 1 diff --git a/sklearn/externals/joblib/format_stack.py b/sklearn/externals/joblib/format_stack.py index 820627b411cee..32e4335fc7bcb 100644 --- a/sklearn/externals/joblib/format_stack.py +++ b/sklearn/externals/joblib/format_stack.py @@ -37,6 +37,7 @@ PY3 = (sys.version[0] == '3') INDENT = ' ' * 8 +from ._compat import _basestring ############################################################################### # some internal-use functions @@ -187,7 +188,6 @@ def format_records(records): # , print_globals=False): frames = [] abspath = os.path.abspath for frame, file, lnum, func, lines, index in records: - #print '*** record:',file,lnum,func,lines,index # dbg try: file = file and abspath(file) or '?' except OSError: @@ -202,7 +202,7 @@ def format_records(records): # , print_globals=False): # This can happen due to a bug in python2.3. We should be # able to remove this try/except when 2.4 becomes a # requirement. Bug details at http://python.org/sf/1005466 - print "\nJoblib's exception reporting continues...\n" + print("\nJoblib's exception reporting continues...\n") if func == '?': call = '' @@ -220,7 +220,7 @@ def format_records(records): # , print_globals=False): # inspect messes up resolving the argument list of view() # and barfs out. At some point I should dig into this one # and file a bug report about it. - print "\nJoblib's exception reporting continues...\n" + print("\nJoblib's exception reporting continues...\n") call = 'in %s(***failed resolving arguments***)' % func # Initialize a list of names on the current line, which the @@ -232,7 +232,7 @@ def tokeneater(token_type, token, start, end, line): The list of names it appends to (from the enclosing scope) can contain repeated composite names. This is unavoidable, since - there is no way to disambguate partial dotted structures until + there is no way to disambiguate partial dotted structures until the full list is known. The caller is responsible for pruning the final list of duplicates before using it.""" @@ -279,7 +279,7 @@ def linereader(file=file, lnum=[lnum], getline=linecache.getline): except (IndexError, UnicodeDecodeError): # signals exit of tokenizer pass - except tokenize.TokenError, msg: + except tokenize.TokenError as msg: _m = ("An unexpected error occurred while tokenizing input\n" "The following traceback may be corrupted or invalid\n" "The error message is: %s\n" % msg) @@ -295,7 +295,7 @@ def linereader(file=file, lnum=[lnum], getline=linecache.getline): if name_base in frame.f_code.co_varnames: if name_base in locals.keys(): try: - value = repr(eval(name_full, locals)) + value = safe_repr(eval(name_full, locals)) except: value = "undefined" else: @@ -305,7 +305,7 @@ def linereader(file=file, lnum=[lnum], getline=linecache.getline): #elif print_globals: # if frame.f_globals.has_key(name_base): # try: - # value = repr(eval(name_full,frame.f_globals)) + # value = safe_repr(eval(name_full,frame.f_globals)) # except: # value = "undefined" # else: @@ -362,8 +362,8 @@ def format_exc(etype, evalue, etb, context=5, tb_offset=0): records = _fixed_getframes(etb, context, tb_offset) except: raise - print '\nUnfortunately, your original traceback can not be ' + \ - 'constructed.\n' + print('\nUnfortunately, your original traceback can not be ' + 'constructed.\n') return '' # Get (safely) a string form of the exception info @@ -375,23 +375,6 @@ def format_exc(etype, evalue, etb, context=5, tb_offset=0): etype_str, evalue_str = map(str, (etype, evalue)) # ... and format it exception = ['%s: %s' % (etype_str, evalue_str)] - if (not PY3) and type(evalue) is types.InstanceType: - try: - names = [w for w in dir(evalue) if isinstance(w, basestring)] - except: - # Every now and then, an object with funny inernals blows up - # when dir() is called on it. We do the best we can to report - # the problem and continue - exception.append( - 'Exception reporting error (object with broken dir()):' - ) - etype_str, evalue_str = map(str, sys.exc_info()[:2]) - exception.append('%s: %s' % (etype_str, evalue_str)) - names = [] - for name in names: - value = safe_repr(getattr(evalue, name)) - exception.append('\n%s%s = %s' % (INDENT, name, value)) - frames = format_records(records) return '%s\n%s\n%s' % (head, '\n'.join(frames), ''.join(exception[0])) @@ -416,7 +399,7 @@ def format_outer_frames(context=5, stack_start=None, stack_end=None, if filename.endswith('.pyc'): filename = filename[:-4] + '.py' if ignore_ipython: - # Hack to avoid printing the interals of IPython + # Hack to avoid printing the internals of IPython if (os.path.basename(filename) == 'iplib.py' and func_name in ('safe_execfile', 'runcode')): break diff --git a/sklearn/externals/joblib/func_inspect.py b/sklearn/externals/joblib/func_inspect.py index 10eebc7b2e610..663cbc9962efd 100644 --- a/sklearn/externals/joblib/func_inspect.py +++ b/sklearn/externals/joblib/func_inspect.py @@ -6,11 +6,15 @@ # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. -import itertools +from itertools import islice import inspect import warnings +import re import os +from ._compat import _basestring +from .logger import pformat + def get_func_code(func): """ Attempts to retrieve a reliable function code hash. @@ -35,23 +39,36 @@ def get_func_code(func): """ source_file = None try: + code = func.__code__ + source_file = code.co_filename + if not os.path.exists(source_file): + # Use inspect for lambda functions and functions defined in an + # interactive shell, or in doctests + source_code = ''.join(inspect.getsourcelines(func)[0]) + line_no = 1 + if source_file.startswith('', + source_file).groups() + line_no = int(line_no) + source_file = '' % source_file + return source_code, source_file, line_no # Try to retrieve the source code. - source_file = func.func_code.co_filename - source_file_obj = file(source_file) - first_line = func.func_code.co_firstlineno - # All the lines after the function definition: - source_lines = list(itertools.islice(source_file_obj, first_line - 1, - None)) + with open(source_file) as source_file_obj: + first_line = code.co_firstlineno + # All the lines after the function definition: + source_lines = list(islice(source_file_obj, first_line - 1, None)) return ''.join(inspect.getblock(source_lines)), source_file, first_line except: # If the source code fails, we use the hash. This is fragile and # might change from one session to another. - if hasattr(func, 'func_code'): - return str(func.func_code.__hash__()), source_file, -1 + if hasattr(func, '__code__'): + # Python 3.X + return str(func.__code__.__hash__()), source_file, -1 else: - # Weird objects like numpy ufunc don't have func_code + # Weird objects like numpy ufunc don't have __code__ # This is fragile, as quite often the id of the object is - # in the repr, so it might not persist accross sessions, + # in the repr, so it might not persist across sessions, # however it will work for ufuncs. return repr(func), source_file, -1 @@ -59,8 +76,13 @@ def get_func_code(func): def _clean_win_chars(string): "Windows cannot encode some characters in filenames" import urllib + if hasattr(urllib, 'quote'): + quote = urllib.quote + else: + # In Python 3, quote is elsewhere + quote = urllib.parse.quote for char in ('<', '>', '!', ':', '\\'): - string = string.replace(char, urllib.quote(char)) + string = string.replace(char, quote(char)) return string @@ -73,7 +95,7 @@ def get_func_name(func, resolv_alias=True, win_characters=True): func: callable The func to inspect resolv_alias: boolean, optional - If true, possible local alias are indicated. + If true, possible local aliases are indicated. win_characters: boolean, optional If true, substitute special characters using urllib.quote This is useful in Windows, as it cannot encode some filenames @@ -87,7 +109,7 @@ def get_func_name(func, resolv_alias=True, win_characters=True): if hasattr(func, '__class__'): module = func.__class__.__module__ else: - module = 'unkown' + module = 'unknown' if module is None: # Happens in doctests, eg module = '' @@ -98,8 +120,13 @@ def get_func_name(func, resolv_alias=True, win_characters=True): filename = None if filename is not None: # mangling of full path to filename - filename = filename.replace(os.sep, '-') - filename = filename.replace(":", "-") + parts = filename.split(os.sep) + if parts[-1].startswith(' 1500: + arg = '%s...' % arg[:700] + if previous_length > 80: + arg = '\n%s' % arg + previous_length = len(arg) + arg_str.append(arg) + arg_str.extend(['%s=%s' % (v, pformat(i)) for v, i in kwargs.items()]) + arg_str = ', '.join(arg_str) + + signature = '%s(%s)' % (name, arg_str) + return module_path, signature + + +def format_call(func, args, kwargs, object_name="Memory"): + """ Returns a nicely formatted statement displaying the function + call with the given arguments. + """ + path, signature = format_signature(func, *args, **kwargs) + msg = '%s\n[%s] Calling %s...\n%s' % (80 * '_', object_name, + path, signature) + return msg + # XXX: Not using logging framework + #self.debug(msg) diff --git a/sklearn/externals/joblib/hashing.py b/sklearn/externals/joblib/hashing.py index efcba30ed4b17..564817c193e81 100644 --- a/sklearn/externals/joblib/hashing.py +++ b/sklearn/externals/joblib/hashing.py @@ -7,57 +7,89 @@ # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. +import warnings import pickle import hashlib import sys import types import struct -if sys.version_info[0] == 3: - # in python3, StringIO does not accept binary data - # see http://packages.python.org/six/ - import io - StringIO = io.BytesIO +import io + +if sys.version_info[0] < 3: + Pickler = pickle.Pickler else: - import cStringIO - StringIO = cStringIO.StringIO + Pickler = pickle._Pickler + + +class _ConsistentSet(object): + """ Class used to ensure the hash of Sets is preserved + whatever the order of its items. + """ + def __init__(self, set_sequence): + self._sequence = sorted(set_sequence) + + +class _MyHash(object): + """ Class used to hash objects that won't normally pickle """ + def __init__(self, *args): + self.args = args -class Hasher(pickle.Pickler): + +class Hasher(Pickler): """ A subclass of pickler, to do cryptographic hashing, rather than pickling. """ def __init__(self, hash_name='md5'): - self.stream = StringIO() - pickle.Pickler.__init__(self, self.stream, protocol=2) + self.stream = io.BytesIO() + Pickler.__init__(self, self.stream, protocol=2) # Initialise the hash obj self._hash = hashlib.new(hash_name) def hash(self, obj, return_digest=True): - self.dump(obj) + try: + self.dump(obj) + except pickle.PicklingError as e: + warnings.warn('PicklingError while hashing %r: %r' % (obj, e)) dumps = self.stream.getvalue() self._hash.update(dumps) if return_digest: return self._hash.hexdigest() def save(self, obj): - if isinstance(obj, types.MethodType): + if isinstance(obj, (types.MethodType, type({}.pop))): # the Pickler cannot pickle instance methods; here we decompose # them into components that make them uniquely identifiable - func_name = obj.im_func.__name__ - inst = obj.im_self - cls = obj.im_class - obj = (func_name, inst, cls) - pickle.Pickler.save(self, obj) - - if sys.version_info[0] < 3: - # The dispatch table of the pickler is not accessible in Python - # 3, as these lines are only bugware for IPython, we skip them. - def save_global(self, obj, name=None, pack=struct.pack): - # We have to override this method in order to deal with objects - # defined interactively in IPython that are not injected in - # __main__ + if hasattr(obj, '__func__'): + func_name = obj.__func__.__name__ + else: + func_name = obj.__name__ + inst = obj.__self__ + if type(inst) == type(pickle): + obj = _MyHash(func_name, inst.__name__) + elif inst is None: + # type(None) or type(module) do not pickle + obj = _MyHash(func_name, inst) + else: + cls = obj.__self__.__class__ + obj = _MyHash(func_name, inst, cls) + Pickler.save(self, obj) + + # The dispatch table of the pickler is not accessible in Python + # 3, as these lines are only bugware for IPython, we skip them. + def save_global(self, obj, name=None, pack=struct.pack): + # We have to override this method in order to deal with objects + # defined interactively in IPython that are not injected in + # __main__ + kwargs = dict(name=name, pack=pack) + if sys.version_info >= (3, 4): + del kwargs['pack'] + try: + Pickler.save_global(self, obj, **kwargs) + except pickle.PicklingError: + Pickler.save_global(self, obj, **kwargs) module = getattr(obj, "__module__", None) if module == '__main__': my_name = name @@ -68,17 +100,26 @@ def save_global(self, obj, name=None, pack=struct.pack): # IPython doesn't inject the variables define # interactively in __main__ setattr(mod, my_name, obj) - pickle.Pickler.save_global(self, obj, name=name, pack=struct.pack) - dispatch = pickle.Pickler.dispatch.copy() - # builtin - dispatch[type(len)] = save_global - # type - dispatch[type(object)] = save_global - # classobj - dispatch[type(pickle.Pickler)] = save_global - # function - dispatch[type(pickle.dump)] = save_global + dispatch = Pickler.dispatch.copy() + # builtin + dispatch[type(len)] = save_global + # type + dispatch[type(object)] = save_global + # classobj + dispatch[type(Pickler)] = save_global + # function + dispatch[type(pickle.dump)] = save_global + + def _batch_setitems(self, items): + # forces order of keys in dict to ensure consistent hash + Pickler._batch_setitems(self, iter(sorted(items))) + + def save_set(self, set_items): + # forces order of items in Set to ensure consistent hash + Pickler.save(self, _ConsistentSet(set_items)) + + dispatch[type(set())] = save_set class NumpyHasher(Hasher): @@ -100,21 +141,27 @@ def __init__(self, hash_name='md5', coerce_mmap=False): # delayed import of numpy, to avoid tight coupling import numpy as np self.np = np + if hasattr(np, 'getbuffer'): + self._getbuffer = np.getbuffer + else: + self._getbuffer = memoryview def save(self, obj): """ Subclass the save method, to hash ndarray subclass, rather than pickling them. Off course, this is a total abuse of the Pickler class. """ - if isinstance(obj, self.np.ndarray): + if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject: # Compute a hash of the object: try: - self._hash.update(self.np.getbuffer(obj)) - except TypeError: + self._hash.update(self._getbuffer(obj)) + except (TypeError, BufferError, ValueError): # Cater for non-single-segment arrays: this creates a # copy, and thus aleviates this issue. # XXX: There might be a more efficient way of doing this - self._hash.update(self.np.getbuffer(obj.flatten())) + # Python 3.2's memoryview raise a ValueError instead of a + # TypeError or a BufferError + self._hash.update(self._getbuffer(obj.flatten())) # We store the class, to be able to distinguish between # Objects with the same binary content, but different diff --git a/sklearn/externals/joblib/logger.py b/sklearn/externals/joblib/logger.py index 33c0397027227..41b586427dcef 100644 --- a/sklearn/externals/joblib/logger.py +++ b/sklearn/externals/joblib/logger.py @@ -8,7 +8,7 @@ # Copyright (c) 2008 Gael Varoquaux # License: BSD Style, 3 clauses. -from __future__ import with_statement +from __future__ import print_function import time import sys @@ -44,6 +44,19 @@ def short_format_time(t): return " %5.1fs" % (t) +def pformat(obj, indent=0, depth=3): + if 'numpy' in sys.modules: + import numpy as np + print_options = np.get_printoptions() + np.set_printoptions(precision=6, threshold=64, edgeitems=1) + else: + print_options = None + out = pprint.pformat(obj, depth=depth, indent=indent) + if print_options: + np.set_printoptions(**print_options) + return out + + ############################################################################### # class `Logger` ############################################################################### @@ -70,16 +83,7 @@ def debug(self, msg): def format(self, obj, indent=0): """ Return the formated representation of the object. """ - if 'numpy' in sys.modules: - import numpy as np - print_options = np.get_printoptions() - np.set_printoptions(precision=6, threshold=64, edgeitems=1) - else: - print_options = None - out = pprint.pformat(obj, depth=self.depth, indent=indent) - if print_options: - np.set_printoptions(**print_options) - return out + return pformat(obj, indent=indent, depth=self.depth) ############################################################################### @@ -102,7 +106,7 @@ def __init__(self, logfile=None, logdir=None): mkdirp(os.path.dirname(logfile)) if os.path.exists(logfile): # Rotate the logs - for i in xrange(1, 9): + for i in range(1, 9): try: shutil.move(logfile + '.%i' % i, logfile + '.%i' % (i + 1)) @@ -138,14 +142,15 @@ def __call__(self, msg='', total=False): time_lapse = time.time() - self.start_time full_msg = "%s: %.2fs, %.1f min" % (msg, time_lapse, time_lapse / 60) - print >> sys.stderr, full_msg + print(full_msg, file=sys.stderr) if self.logfile is not None: try: - print >> file(self.logfile, 'a'), full_msg + with open(self.logfile, 'a') as f: + print(full_msg, file=f) except: """ Multiprocessing writing to files can create race conditions. Rather fail silently than crash the - caculation. + calculation. """ # XXX: We actually need a debug flag to disable this # silent failure. diff --git a/sklearn/externals/joblib/memory.py b/sklearn/externals/joblib/memory.py index f0a0252f42276..c0e93ce5d1650 100644 --- a/sklearn/externals/joblib/memory.py +++ b/sklearn/externals/joblib/memory.py @@ -14,6 +14,8 @@ import shutil import time import pydoc +import re +import sys try: import cPickle as pickle except ImportError: @@ -22,22 +24,17 @@ import traceback import warnings import inspect -try: - # json is in the standard library for Python >= 2.6 - import json -except ImportError: - try: - import simplejson as json - except ImportError: - # Not the end of the world: we'll do without this functionality - json = None +import json +import weakref # Local imports -from .hashing import hash +from . import hashing from .func_inspect import get_func_code, get_func_name, filter_args -from .logger import Logger, format_time +from .func_inspect import format_signature, format_call +from .logger import Logger, format_time, pformat from . import numpy_pickle from .disk import mkdirp, rm_subdirs +from ._compat import _basestring FIRST_LINE_TEXT = "# first line:" @@ -72,6 +69,234 @@ class JobLibCollisionWarning(UserWarning): """ +def _get_func_fullname(func): + """Compute the part of part associated with a function. + + See code of_cache_key_to_dir() for details + """ + modules, funcname = get_func_name(func) + modules.append(funcname) + return os.path.join(*modules) + + +def _cache_key_to_dir(cachedir, func, argument_hash): + """Compute directory associated with a given cache key. + + func can be a function or a string as returned by _get_func_fullname(). + """ + parts = [cachedir] + if isinstance(func, _basestring): + parts.append(func) + else: + parts.append(_get_func_fullname(func)) + + if argument_hash is not None: + parts.append(argument_hash) + return os.path.join(*parts) + + +def _load_output(output_dir, func_name, timestamp=None, metadata=None, + mmap_mode=None, verbose=0): + """Load output of a computation.""" + if verbose > 1: + signature = "" + try: + if metadata is not None: + args = ", ".join(['%s=%s' % (name, value) + for name, value + in metadata['input_args'].items()]) + signature = "%s(%s)" % (os.path.basename(func_name), + args) + else: + signature = os.path.basename(func_name) + except KeyError: + pass + + if timestamp is not None: + t = "% 16s" % format_time(time.time() - timestamp) + else: + t = "" + + if verbose < 10: + print('[Memory]%s: Loading %s...' % (t, str(signature))) + else: + print('[Memory]%s: Loading %s from %s' % ( + t, str(signature), output_dir)) + + filename = os.path.join(output_dir, 'output.pkl') + if not os.path.isfile(filename): + raise KeyError( + "Non-existing cache value (may have been cleared).\n" + "File %s does not exist" % filename) + return numpy_pickle.load(filename, mmap_mode=mmap_mode) + + +# An in-memory store to avoid looking at the disk-based function +# source code to check if a function definition has changed +_FUNCTION_HASHES = weakref.WeakKeyDictionary() + + +############################################################################### +# class `MemorizedResult` +############################################################################### +class MemorizedResult(Logger): + """Object representing a cached value. + + Attributes + ---------- + cachedir: string + path to root of joblib cache + + func: function or string + function whose output is cached. The string case is intended only for + instanciation based on the output of repr() on another instance. + (namely eval(repr(memorized_instance)) works). + + argument_hash: string + hash of the function arguments + + mmap_mode: {None, 'r+', 'r', 'w+', 'c'} + The memmapping mode used when loading from cache numpy arrays. See + numpy.load for the meaning of the different values. + + verbose: int + verbosity level (0 means no message) + + timestamp, metadata: string + for internal use only + """ + def __init__(self, cachedir, func, argument_hash, + mmap_mode=None, verbose=0, timestamp=None, metadata=None): + Logger.__init__(self) + if isinstance(func, _basestring): + self.func = func + else: + self.func = _get_func_fullname(func) + self.argument_hash = argument_hash + self.cachedir = cachedir + self.mmap_mode = mmap_mode + + self._output_dir = _cache_key_to_dir(cachedir, self.func, + argument_hash) + + if metadata is not None: + self.metadata = metadata + else: + self.metadata = {} + # No error is relevant here. + try: + with open(os.path.join(self._output_dir, 'metadata.json'), + 'rb') as f: + self.metadata = json.load(f) + except: + pass + + self.duration = self.metadata.get('duration', None) + self.verbose = verbose + self.timestamp = timestamp + + def get(self): + """Read value from cache and return it.""" + return _load_output(self._output_dir, _get_func_fullname(self.func), + timestamp=self.timestamp, + metadata=self.metadata, mmap_mode=self.mmap_mode, + verbose=self.verbose) + + def clear(self): + """Clear value from cache""" + shutil.rmtree(self._output_dir, ignore_errors=True) + + def __repr__(self): + return ('{class_name}(cachedir="{cachedir}", func="{func}", ' + 'argument_hash="{argument_hash}")'.format( + class_name=self.__class__.__name__, + cachedir=self.cachedir, + func=self.func, + argument_hash=self.argument_hash + )) + + def __reduce__(self): + return (self.__class__, (self.cachedir, self.func, self.argument_hash), + {'mmap_mode': self.mmap_mode}) + + +class NotMemorizedResult(object): + """Class representing an arbitrary value. + + This class is a replacement for MemorizedResult when there is no cache. + """ + __slots__ = ('value', 'valid') + + def __init__(self, value): + self.value = value + self.valid = True + + def get(self): + if self.valid: + return self.value + else: + raise KeyError("No value stored.") + + def clear(self): + self.valid = False + self.value = None + + def __repr__(self): + if self.valid: + return '{class_name}({value})'.format( + class_name=self.__class__.__name__, + value=pformat(self.value) + ) + else: + return self.__class__.__name__ + ' with no value' + + # __getstate__ and __setstate__ are required because of __slots__ + def __getstate__(self): + return {"valid": self.valid, "value": self.value} + + def __setstate__(self, state): + self.valid = state["valid"] + self.value = state["value"] + + +############################################################################### +# class `NotMemorizedFunc` +############################################################################### +class NotMemorizedFunc(object): + """No-op object decorating a function. + + This class replaces MemorizedFunc when there is no cache. It provides an + identical API but does not write anything on disk. + + Attributes + ---------- + func: callable + Original undecorated function. + """ + # Should be a light as possible (for speed) + def __init__(self, func): + self.func = func + + def __call__(self, *args, **kwargs): + return self.func(*args, **kwargs) + + def call_and_shelve(self, *args, **kwargs): + return NotMemorizedResult(self.func(*args, **kwargs)) + + def __reduce__(self): + return (self.__class__, (self.func,)) + + def __repr__(self): + return '%s(func=%s)' % ( + self.__class__.__name__, + self.func + ) + + def clear(self, warn=True): + # Argument "warn" is for compatibility with MemorizedFunc.clear + pass + + ############################################################################### # class `MemorizedFunc` ############################################################################### @@ -86,21 +311,28 @@ class MemorizedFunc(Logger): ---------- func: callable The original, undecorated, function. + cachedir: string Path to the base cache directory of the memory context. + ignore: list or None List of variable names to ignore when choosing whether to recompute. + mmap_mode: {None, 'r+', 'r', 'w+', 'c'} The memmapping mode used when loading from cache - numpy arrays. See numpy.load for the meaning of the - arguments. - compress: boolean - Whether to zip the stored data on disk. Note that compressed - arrays cannot be read by memmapping. + numpy arrays. See numpy.load for the meaning of the different + values. + + compress: boolean, or integer + Whether to zip the stored data on disk. If an integer is + given, it should be between 1 and 9, and sets the amount + of compression. Note that compressed arrays cannot be + read by memmapping. + verbose: int, optional The verbosity flag, controls messages that are issued as - the function is revaluated. + the function is evaluated. """ #------------------------------------------------------------------------- # Public interface @@ -121,64 +353,98 @@ def __init__(self, func, cachedir, ignore=None, mmap_mode=None, The memmapping mode used when loading from cache numpy arrays. See numpy.load for the meaning of the arguments. + compress : boolean, or integer + Whether to zip the stored data on disk. If an integer is + given, it should be between 1 and 9, and sets the amount + of compression. Note that compressed arrays cannot be + read by memmapping. verbose: int, optional Verbosity flag, controls the debug messages that are issued - as functions are revaluated. The higher, the more verbose + as functions are evaluated. The higher, the more verbose timestamp: float, optional The reference time from which times in tracing messages are reported. """ Logger.__init__(self) + self.mmap_mode = mmap_mode + self.func = func + if ignore is None: + ignore = [] + self.ignore = ignore + self._verbose = verbose self.cachedir = cachedir - self.func = func - self.mmap_mode = mmap_mode self.compress = compress - if compress and mmap_mode is not None: + if compress and self.mmap_mode is not None: warnings.warn('Compressed results cannot be memmapped', stacklevel=2) if timestamp is None: timestamp = time.time() self.timestamp = timestamp - if ignore is None: - ignore = [] - self.ignore = ignore mkdirp(self.cachedir) try: functools.update_wrapper(self, func) except: " Objects like ufunc don't like that " if inspect.isfunction(func): - doc = pydoc.TextDoc().document(func - ).replace('\n', '\n\n', 1) + doc = pydoc.TextDoc().document(func) + # Remove blank line + doc = doc.replace('\n', '\n\n', 1) + # Strip backspace-overprints for compatibility with autodoc + doc = re.sub('\x08.', '', doc) else: # Pydoc does a poor job on other objects doc = func.__doc__ self.__doc__ = 'Memoized version of %s' % doc - def __call__(self, *args, **kwargs): + def _cached_call(self, args, kwargs): + """Call wrapped function and cache result, or read cache if available. + + This function returns the wrapped function output and some metadata. + + Returns + ------- + output: value or tuple + what is returned by wrapped function + + argument_hash: string + hash of function arguments + + metadata: dict + some metadata about wrapped function call (see _persist_input()) + """ # Compare the function code with the previous to see if the # function code has changed - output_dir, argument_hash = self.get_output_dir(*args, **kwargs) + output_dir, argument_hash = self._get_output_dir(*args, **kwargs) + metadata = None # FIXME: The statements below should be try/excepted - if not (self._check_previous_func_code(stacklevel=3) and + if not (self._check_previous_func_code(stacklevel=4) and os.path.exists(output_dir)): if self._verbose > 10: _, name = get_func_name(self.func) self.warn('Computing func %s, argument hash %s in ' 'directory %s' % (name, argument_hash, output_dir)) - return self.call(*args, **kwargs) + out, metadata = self.call(*args, **kwargs) + if self.mmap_mode is not None: + # Memmap the output at the first call to be consistent with + # later calls + out = _load_output(output_dir, _get_func_fullname(self.func), + timestamp=self.timestamp, + mmap_mode=self.mmap_mode, + verbose=self._verbose) else: try: t0 = time.time() - out = self.load_output(output_dir) + out = _load_output(output_dir, _get_func_fullname(self.func), + timestamp=self.timestamp, + metadata=metadata, mmap_mode=self.mmap_mode, + verbose=self._verbose) if self._verbose > 4: t = time.time() - t0 _, name = get_func_name(self.func) msg = '%s cache loaded - %s' % (name, format_time(t)) - print max(0, (80 - len(msg))) * '_' + msg - return out + print(max(0, (80 - len(msg))) * '_' + msg) except Exception: # XXX: Should use an exception logger self.warn('Exception while loading results for ' @@ -186,7 +452,33 @@ def __call__(self, *args, **kwargs): (args, kwargs, traceback.format_exc())) shutil.rmtree(output_dir, ignore_errors=True) - return self.call(*args, **kwargs) + out, metadata = self.call(*args, **kwargs) + argument_hash = None + return (out, argument_hash, metadata) + + def call_and_shelve(self, *args, **kwargs): + """Call wrapped function, cache result and return a reference. + + This method returns a reference to the cached result instead of the + result itself. The reference object is small and pickeable, allowing + to send or store it easily. Call .get() on reference object to get + result. + + Returns + ------- + cached_result: MemorizedResult or NotMemorizedResult + reference to the value returned by the wrapped function. The + class "NotMemorizedResult" is used when there is no cache + activated (e.g. cachedir=None in Memory). + """ + _, argument_hash, metadata = self._cached_call(args, kwargs) + + return MemorizedResult(self.cachedir, self.func, argument_hash, + metadata=metadata, verbose=self._verbose - 1, + timestamp=self.timestamp) + + def __call__(self, *args, **kwargs): + return self._cached_call(args, kwargs)[0] def __reduce__(self): """ We don't store the timestamp when pickling, to avoid the hash @@ -196,47 +488,100 @@ def __reduce__(self): return (self.__class__, (self.func, self.cachedir, self.ignore, self.mmap_mode, self.compress, self._verbose)) + def format_signature(self, *args, **kwargs): + warnings.warn("MemorizedFunc.format_signature will be removed in a " + "future version of joblib.", DeprecationWarning) + return format_signature(self.func, *args, **kwargs) + + def format_call(self, *args, **kwargs): + warnings.warn("MemorizedFunc.format_call will be removed in a " + "future version of joblib.", DeprecationWarning) + return format_call(self.func, args, kwargs) + #------------------------------------------------------------------------- # Private interface #------------------------------------------------------------------------- + def _get_argument_hash(self, *args, **kwargs): + return hashing.hash(filter_args(self.func, self.ignore, + args, kwargs), + coerce_mmap=(self.mmap_mode is not None)) + + def _get_output_dir(self, *args, **kwargs): + """ Return the directory in which are persisted the result + of the function called with the given arguments. + """ + argument_hash = self._get_argument_hash(*args, **kwargs) + output_dir = os.path.join(self._get_func_dir(self.func), + argument_hash) + return output_dir, argument_hash + + get_output_dir = _get_output_dir # backward compatibility + def _get_func_dir(self, mkdir=True): """ Get the directory corresponding to the cache for the function. """ - module, name = get_func_name(self.func) - module.append(name) - func_dir = os.path.join(self.cachedir, *module) + func_dir = _cache_key_to_dir(self.cachedir, self.func, None) if mkdir: mkdirp(func_dir) return func_dir - def get_output_dir(self, *args, **kwargs): - """ Returns the directory in which are persisted the results - of the function corresponding to the given arguments. - - The results can be loaded using the .load_output method. - """ - coerce_mmap = (self.mmap_mode is not None) - argument_hash = hash(filter_args(self.func, self.ignore, - args, kwargs), - coerce_mmap=coerce_mmap) - output_dir = os.path.join(self._get_func_dir(self.func), - argument_hash) - return output_dir, argument_hash + def _hash_func(self): + """Hash a function to key the online cache""" + func_code_h = hash(getattr(self.func, '__code__', None)) + return id(self.func), hash(self.func), func_code_h def _write_func_code(self, filename, func_code, first_line): """ Write the function code and the filename to a file. """ + # We store the first line because the filename and the function + # name is not always enough to identify a function: people + # sometimes have several functions named the same way in a + # file. This is bad practice, but joblib should be robust to bad + # practice. func_code = '%s %i\n%s' % (FIRST_LINE_TEXT, first_line, func_code) with open(filename, 'w') as out: out.write(func_code) + # Also store in the in-memory store of function hashes + is_named_callable = False + if sys.version_info[0] > 2: + is_named_callable = (hasattr(self.func, '__name__') + and self.func.__name__ != '') + else: + is_named_callable = (hasattr(self.func, 'func_name') + and self.func.func_name != '') + if is_named_callable: + # Don't do this for lambda functions or strange callable + # objects, as it ends up being too fragile + func_hash = self._hash_func() + try: + _FUNCTION_HASHES[self.func] = func_hash + except TypeError: + # Some callable are not hashable + pass def _check_previous_func_code(self, stacklevel=2): """ stacklevel is the depth a which this function is called, to issue useful warnings to the user. """ + # First check if our function is in the in-memory store. + # Using the in-memory store not only makes things faster, but it + # also renders us robust to variations of the files when the + # in-memory version of the code does not vary + try: + if self.func in _FUNCTION_HASHES: + # We use as an identifier the id of the function and its + # hash. This is more likely to falsely change than have hash + # collisions, thus we are on the safe side. + func_hash = self._hash_func() + if func_hash == _FUNCTION_HASHES[self.func]: + return True + except TypeError: + # Some callables are not hashable + pass + # Here, we go through some effort to be robust to dynamically # changing code and collision. We cannot inspect.getsource # because it is not reliable when using IPython's magic "%run". @@ -254,13 +599,13 @@ def _check_previous_func_code(self, stacklevel=2): if old_func_code == func_code: return True - # We have differing code, is this because we are refering to - # differing functions, or because the function we are refering as + # We have differing code, is this because we are referring to + # different functions, or because the function we are referring to has # changed? - if old_first_line == first_line == -1: - _, func_name = get_func_name(self.func, resolv_alias=False, - win_characters=False) + _, func_name = get_func_name(self.func, resolv_alias=False, + win_characters=False) + if old_first_line == first_line == -1 or func_name == '': if not first_line == -1: func_description = '%s (%s:%i)' % (func_name, source_file, first_line) @@ -274,21 +619,26 @@ def _check_previous_func_code(self, stacklevel=2): # same than the code store, we have a collision: the code in the # file has not changed, but the name we have is pointing to a new # code block. - if (not old_first_line == first_line - and source_file is not None - and os.path.exists(source_file)): - _, func_name = get_func_name(self.func, resolv_alias=False) - num_lines = len(func_code.split('\n')) - on_disk_func_code = file(source_file).readlines()[ - old_first_line - 1:old_first_line - 1 + num_lines - 1] - on_disk_func_code = ''.join(on_disk_func_code) - if on_disk_func_code.rstrip() == old_func_code.rstrip(): + if not old_first_line == first_line and source_file is not None: + possible_collision = False + if os.path.exists(source_file): + _, func_name = get_func_name(self.func, resolv_alias=False) + num_lines = len(func_code.split('\n')) + with open(source_file) as f: + on_disk_func_code = f.readlines()[ + old_first_line - 1:old_first_line - 1 + num_lines - 1] + on_disk_func_code = ''.join(on_disk_func_code) + possible_collision = (on_disk_func_code.rstrip() + == old_func_code.rstrip()) + else: + possible_collision = source_file.startswith(' 0 and warn: self.warn("Clearing cache %s" % func_dir) if os.path.exists(func_dir): shutil.rmtree(func_dir, ignore_errors=True) @@ -317,58 +667,21 @@ def call(self, *args, **kwargs): persist the output values. """ start_time = time.time() - output_dir, argument_hash = self.get_output_dir(*args, **kwargs) - if self._verbose: - print self.format_call(*args, **kwargs) + output_dir, _ = self._get_output_dir(*args, **kwargs) + if self._verbose > 0: + print(format_call(self.func, args, kwargs)) output = self.func(*args, **kwargs) self._persist_output(output, output_dir) duration = time.time() - start_time - if self._verbose: + metadata = self._persist_input(output_dir, duration, args, kwargs) + + if self._verbose > 0: _, name = get_func_name(self.func) msg = '%s - %s' % (name, format_time(duration)) - print max(0, (80 - len(msg))) * '_' + msg - return output - - def format_call(self, *args, **kwds): - """ Returns a nicely formatted statement displaying the function - call with the given arguments. - """ - path, signature = self.format_signature(self.func, *args, - **kwds) - msg = '%s\n[Memory] Calling %s...\n%s' % (80 * '_', path, signature) - return msg - # XXX: Not using logging framework - #self.debug(msg) - - def format_signature(self, func, *args, **kwds): - # XXX: This should be moved out to a function - # XXX: Should this use inspect.formatargvalues/formatargspec? - module, name = get_func_name(func) - module = [m for m in module if m] - if module: - module.append(name) - module_path = '.'.join(module) - else: - module_path = name - arg_str = list() - previous_length = 0 - for arg in args: - arg = self.format(arg, indent=2) - if len(arg) > 1500: - arg = '%s...' % arg[:700] - if previous_length > 80: - arg = '\n%s' % arg - previous_length = len(arg) - arg_str.append(arg) - arg_str.extend(['%s=%s' % (v, self.format(i)) for v, i in - kwds.iteritems()]) - arg_str = ', '.join(arg_str) - - signature = '%s(%s)' % (name, arg_str) - return module_path, signature - - # Make make public + print(max(0, (80 - len(msg))) * '_' + msg) + return output, metadata + # Make public def _persist_output(self, output, dir): """ Persist the given output tuple in the directory. """ @@ -377,51 +690,76 @@ def _persist_output(self, output, dir): filename = os.path.join(dir, 'output.pkl') numpy_pickle.dump(output, filename, compress=self.compress) if self._verbose > 10: - print 'Persisting in %s' % dir + print('Persisting in %s' % dir) except OSError: " Race condition in the creation of the directory " - def _persist_input(self, output_dir, *args, **kwargs): + def _persist_input(self, output_dir, duration, args, kwargs, + this_duration_limit=0.5): """ Save a small summary of the call using json format in the output directory. + + output_dir: string + directory where to write metadata. + + duration: float + time taken by hashing input arguments, calling the wrapped + function and persisting its output. + + args, kwargs: list and dict + input arguments for wrapped function + + this_duration_limit: float + Max execution time for this function before issuing a warning. """ + start_time = time.time() argument_dict = filter_args(self.func, self.ignore, args, kwargs) - input_repr = dict((k, repr(v)) for k, v in argument_dict.iteritems()) - if json is not None: - # This can fail do to race-conditions with multiple - # concurrent joblibs removing the file or the directory - try: - mkdirp(output_dir) - json.dump( - input_repr, - file(os.path.join(output_dir, 'input_args.json'), 'w'), - ) - except: - pass - return input_repr + input_repr = dict((k, repr(v)) for k, v in argument_dict.items()) + # This can fail due to race-conditions with multiple + # concurrent joblibs removing the file or the directory + metadata = {"duration": duration, "input_args": input_repr} + try: + mkdirp(output_dir) + with open(os.path.join(output_dir, 'metadata.json'), 'w') as f: + json.dump(metadata, f) + except: + pass + + this_duration = time.time() - start_time + if this_duration > this_duration_limit: + # This persistence should be fast. It will not be if repr() takes + # time and its output is large, because json.dump will have to + # write a large file. This should not be an issue with numpy arrays + # for which repr() always output a short representation, but can + # be with complex dictionaries. Fixing the problem should be a + # matter of replacing repr() above by something smarter. + warnings.warn("Persisting input arguments took %.2fs to run.\n" + "If this happens often in your code, it can cause " + "performance problems \n" + "(results will be correct in all cases). \n" + "The reason for this is probably some large input " + "arguments for a wrapped\n" + " function (e.g. large strings).\n" + "THIS IS A JOBLIB ISSUE. If you can, kindly provide " + "the joblib's team with an\n" + " example so that they can fix the problem." + % this_duration, stacklevel=5) + return metadata def load_output(self, output_dir): """ Read the results of a previous calculation from the directory it was cached in. """ - if self._verbose > 1: - t = time.time() - self.timestamp - if self._verbose < 10: - print '[Memory]% 16s: Loading %s...' % ( - format_time(t), - self.format_signature(self.func)[0] - ) - else: - print '[Memory]% 16s: Loading %s from %s' % ( - format_time(t), - self.format_signature(self.func)[0], - output_dir - ) - filename = os.path.join(output_dir, 'output.pkl') - return numpy_pickle.load(filename, - mmap_mode=self.mmap_mode) + warnings.warn("MemorizedFunc.load_output is deprecated and will be " + "removed in a future version\n" + "of joblib. A MemorizedResult provides similar features", + DeprecationWarning) + # No metadata available here. + return _load_output(output_dir, _get_func_fullname(self.func), + timestamp=self.timestamp, + mmap_mode=self.mmap_mode, verbose=self._verbose) # XXX: Need a method to check if results are available. @@ -465,14 +803,16 @@ def __init__(self, cachedir, mmap_mode=None, compress=False, verbose=1): The memmapping mode used when loading from cache numpy arrays. See numpy.load for the meaning of the arguments. - compress: boolean - Whether to zip the stored data on disk. Note that - compressed arrays cannot be read by memmapping. + compress: boolean, or integer + Whether to zip the stored data on disk. If an integer is + given, it should be between 1 and 9, and sets the amount + of compression. Note that compressed arrays cannot be + read by memmapping. verbose: int, optional Verbosity flag, controls the debug messages that are issued - as functions are revaluated. + as functions are evaluated. """ - # XXX: Bad explaination of the None value of cachedir + # XXX: Bad explanation of the None value of cachedir Logger.__init__(self) self._verbose = verbose self.mmap_mode = mmap_mode @@ -517,9 +857,10 @@ def cache(self, func=None, ignore=None, verbose=None, if func is None: # Partial application, to be able to specify extra keyword # arguments in decorators - return functools.partial(self.cache, ignore=ignore) + return functools.partial(self.cache, ignore=ignore, + verbose=verbose, mmap_mode=mmap_mode) if self.cachedir is None: - return func + return NotMemorizedFunc(func) if verbose is None: verbose = self._verbose if mmap_mode is False: diff --git a/sklearn/externals/joblib/my_exceptions.py b/sklearn/externals/joblib/my_exceptions.py index e8fab72489ed5..ce9a2bf5692dd 100644 --- a/sklearn/externals/joblib/my_exceptions.py +++ b/sklearn/externals/joblib/my_exceptions.py @@ -9,28 +9,32 @@ class JoblibException(Exception): - """ A simple exception with an error message that you can get to. - """ + """A simple exception with an error message that you can get to.""" - def __init__(self, message): - self.message = message + def __init__(self, *args): + self.args = args def __reduce__(self): # For pickling - return self.__class__, (self.message,), {} + return self.__class__, self.args, {} def __repr__(self): - return '%s\n%s\n%s\n%s' % ( - self.__class__.__name__, - 75 * '_', - self.message, - 75 * '_') + if hasattr(self, 'args'): + message = self.args[0] + else: + # Python 2 compat: instances of JoblibException can be created + # without calling JoblibException __init__ in case of + # multi-inheritance: in that case the message is stored as an + # explicit attribute under Python 2 (only) + message = self.message + name = self.__class__.__name__ + return '%s\n%s\n%s\n%s' % (name, 75 * '_', message, 75 * '_') __str__ = __repr__ class TransportableException(JoblibException): - """ An exception containing all the info to wrap an original + """An exception containing all the info to wrap an original exception and recreate it. """ @@ -56,9 +60,13 @@ def _mk_exception(exception, name=None): # Avoid creating twice the same exception this_exception = _exception_mapping[this_name] else: + if exception is Exception: + # We cannot create a subclass: we are already a trivial + # subclass + return JoblibException, this_name this_exception = type(this_name, (exception, JoblibException), dict(__repr__=JoblibException.__repr__, - __str__=JoblibException.__str__), + __str__=JoblibException.__str__), ) _exception_mapping[this_name] = this_exception return this_exception, this_name diff --git a/sklearn/externals/joblib/numpy_pickle.py b/sklearn/externals/joblib/numpy_pickle.py index 234b7e59f15f4..fb91c51dff1b1 100644 --- a/sklearn/externals/joblib/numpy_pickle.py +++ b/sklearn/externals/joblib/numpy_pickle.py @@ -13,21 +13,21 @@ import zlib import warnings +from ._compat import _basestring + +from io import BytesIO + if sys.version_info[0] >= 3: - from io import BytesIO - from pickle import _Unpickler as Unpickler + Unpickler = pickle._Unpickler + Pickler = pickle._Pickler def asbytes(s): if isinstance(s, bytes): return s return s.encode('latin1') else: - try: - from io import BytesIO - except ImportError: - # BytesIO has been added in Python 2.5 - from cStringIO import StringIO as BytesIO - from pickle import Unpickler + Unpickler = pickle.Unpickler + Pickler = pickle.Pickler asbytes = str _MEGA = 2 ** 20 @@ -54,7 +54,7 @@ def read_zfile(file_handle): """Read the z-file and return the content as a string Z-files are raw data compressed with zlib used internally by joblib - for persistence. Backward compatibility is not garantied. Do not + for persistence. Backward compatibility is not guaranteed. Do not use for external purposes. """ file_handle.seek(0) @@ -85,8 +85,8 @@ def write_zfile(file_handle, data, compress=1): # We need to remove the trailing 'L' in the hex representation length = length[:-1] # Store the length of the data - file_handle.write(length.ljust(_MAX_LEN)) - file_handle.write(zlib.compress(data, compress)) + file_handle.write(asbytes(length.ljust(_MAX_LEN))) + file_handle.write(zlib.compress(asbytes(data), compress)) ############################################################################### @@ -107,7 +107,8 @@ def read(self, unpickler): "Reconstruct the array" filename = os.path.join(unpickler._dirname, self.filename) # Load the array from the disk - if unpickler.np.__version__ >= '1.3': + np_ver = [int(x) for x in unpickler.np.__version__.split('.', 2)[:2]] + if np_ver >= [1, 3]: array = unpickler.np.load(filename, mmap_mode=unpickler.mmap_mode) else: @@ -125,11 +126,14 @@ def read(self, unpickler): array = new_array return array + #def __reduce__(self): + # return None + class ZNDArrayWrapper(NDArrayWrapper): """An object to be persisted instead of numpy arrays. - This object store the Zfile filename in wich + This object store the Zfile filename in which the data array has been persisted, and the meta information to retrieve it. @@ -153,7 +157,8 @@ def read(self, unpickler): # arrays filename = os.path.join(unpickler._dirname, self.filename) array = unpickler.np.core.multiarray._reconstruct(*self.init_args) - data = read_zfile(open(filename, 'rb')) + with open(filename, 'rb') as f: + data = read_zfile(f) state = self.state + (data,) array.__setstate__(state) return array @@ -162,7 +167,7 @@ def read(self, unpickler): ############################################################################### # Pickler classes -class NumpyPickler(pickle.Pickler): +class NumpyPickler(Pickler): """A pickler to persist of big data efficiently. The main features of this object are: @@ -174,7 +179,7 @@ class NumpyPickler(pickle.Pickler): temporaries. """ - def __init__(self, filename, compress=0, cache_size=100): + def __init__(self, filename, compress=0, cache_size=10): self._filename = filename self._filenames = [filename, ] self.cache_size = cache_size @@ -185,7 +190,7 @@ def __init__(self, filename, compress=0, cache_size=100): self.file = BytesIO() # Count the number of npy files that we have created: self._npy_counter = 0 - pickle.Pickler.__init__(self, self.file, + Pickler.__init__(self, self.file, protocol=pickle.HIGHEST_PROTOCOL) # delayed import of numpy, to avoid tight coupling try: @@ -206,10 +211,8 @@ def _write_array(self, array, filename): # numerics in a z-file _, init_args, state = array.__reduce__() # the last entry of 'state' is the data itself - zfile = open(filename, 'wb') - write_zfile(zfile, state[-1], - compress=self.compress) - zfile.close() + with open(filename, 'wb') as zfile: + write_zfile(zfile, state[-1], compress=self.compress) state = state[:-1] container = ZNDArrayWrapper(os.path.basename(filename), init_args, state) @@ -229,7 +232,7 @@ def save(self, obj): if type(obj) is self.np.memmap: # Pickling doesn't work with memmaped arrays obj = self.np.asarray(obj) - return pickle.Pickler.save(self, obj) + return Pickler.save(self, obj) self._npy_counter += 1 try: filename = '%s_%02i.npy' % (self._filename, @@ -240,17 +243,15 @@ def save(self, obj): except: self._npy_counter -= 1 # XXX: We should have a logging mechanism - print 'Failed to save %s to .npy file:\n%s' % ( + print('Failed to save %s to .npy file:\n%s' % ( type(obj), - traceback.format_exc()) - return pickle.Pickler.save(self, obj) + traceback.format_exc())) + return Pickler.save(self, obj) def close(self): if self.compress: - zfile = open(self._filename, 'wb') - write_zfile(zfile, - self.file.getvalue(), self.compress) - zfile.close() + with open(self._filename, 'wb') as zfile: + write_zfile(zfile, self.file.getvalue(), self.compress) class NumpyUnpickler(Unpickler): @@ -291,7 +292,10 @@ def load_build(self): self.stack.append(array) # Be careful to register our new method. - dispatch[pickle.BUILD] = load_build + if sys.version_info[0] >= 3: + dispatch[pickle.BUILD[0]] = load_build + else: + dispatch[pickle.BUILD] = load_build class ZipNumpyUnpickler(NumpyUnpickler): @@ -348,7 +352,11 @@ def dump(value, filename, compress=0, cache_size=100): addition, compressed files take extra extra memory during dump and load. """ - if not isinstance(filename, basestring): + if compress is True: + # By default, if compress is enabled, we want to be using 3 by + # default + compress = 3 + if not isinstance(filename, _basestring): # People keep inverting arguments, and the resulting error is # incomprehensible raise ValueError( @@ -368,7 +376,7 @@ def dump(value, filename, compress=0, cache_size=100): def load(filename, mmap_mode=None): - """Reconstruct a Python object from a file persisted with joblib.load. + """Reconstruct a Python object from a file persisted with joblib.dump. Parameters ----------- @@ -376,7 +384,7 @@ def load(filename, mmap_mode=None): The name of the file from which to load the object mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional If not None, the arrays are memory-mapped from the disk. This - mode has not effect for compressed files. Note that in this + mode has no effect for compressed files. Note that in this case the reconstructed object might not longer match exactly the originally pickled object. @@ -398,25 +406,24 @@ def load(filename, mmap_mode=None): object might not match the original pickled object. Note that if the file was saved with compression, the arrays cannot be memmaped. """ - file_handle = open(filename, 'rb') - # We are careful to open the file hanlde early and keep it open to - # avoid race-conditions on renames. That said, if data are stored in - # companion files, moving the directory will create a race when - # joblib tries to access the companion files. - if _read_magic(file_handle) == _ZFILE_PREFIX: - if mmap_mode is not None: - warnings.warn('file "%(filename)s" appears to be a zip, ' - 'ignoring mmap_mode "%(mmap_mode)s" flag passed' - % locals(), Warning, stacklevel=2) - unpickler = ZipNumpyUnpickler(filename, file_handle=file_handle) - else: - unpickler = NumpyUnpickler(filename, - file_handle=file_handle, - mmap_mode=mmap_mode) + with open(filename, 'rb') as file_handle: + # We are careful to open the file handle early and keep it open to + # avoid race-conditions on renames. That said, if data are stored in + # companion files, moving the directory will create a race when + # joblib tries to access the companion files. + if _read_magic(file_handle) == _ZFILE_PREFIX: + if mmap_mode is not None: + warnings.warn('file "%(filename)s" appears to be a zip, ' + 'ignoring mmap_mode "%(mmap_mode)s" flag passed' + % locals(), Warning, stacklevel=2) + unpickler = ZipNumpyUnpickler(filename, file_handle=file_handle) + else: + unpickler = NumpyUnpickler(filename, file_handle=file_handle, + mmap_mode=mmap_mode) - try: - obj = unpickler.load() - finally: - if hasattr(unpickler, 'file_handle'): - unpickler.file_handle.close() - return obj + try: + obj = unpickler.load() + finally: + if hasattr(unpickler, 'file_handle'): + unpickler.file_handle.close() + return obj diff --git a/sklearn/externals/joblib/parallel.py b/sklearn/externals/joblib/parallel.py index 77c777ab19b89..af9f8cd14d6aa 100644 --- a/sklearn/externals/joblib/parallel.py +++ b/sklearn/externals/joblib/parallel.py @@ -7,30 +7,37 @@ import os import sys +import gc import warnings +from collections import Sized from math import sqrt import functools import time import threading import itertools + try: import cPickle as pickle except: import pickle -# Obtain possible configuration from the environment, assuming 1 (on) -# by default, upon 0 set to None. Should instructively fail if some non -# 0/1 value is set. -multiprocessing = int(os.environ.get('JOBLIB_MULTIPROCESSING', 1)) or None -if multiprocessing: - try: - import multiprocessing - except ImportError: - multiprocessing = None +from ._multiprocessing_helpers import mp + +if mp is not None: + from .pool import MemmapingPool + from multiprocessing.pool import ThreadPool from .format_stack import format_exc, format_outer_frames from .logger import Logger, short_format_time from .my_exceptions import TransportableException, _mk_exception +from .disk import memstr_to_kbytes +from ._compat import _basestring + + +VALID_BACKENDS = ['multiprocessing', 'threading'] + +# Environment variables to protect against bad situations when nesting +JOBLIB_SPAWNED_PROCESS = "__JOBLIB_SPAWNED_PARALLEL__" ############################################################################### @@ -38,16 +45,16 @@ def cpu_count(): """ Return the number of CPUs. """ - if multiprocessing is None: + if mp is None: return 1 - return multiprocessing.cpu_count() + return mp.cpu_count() ############################################################################### # For verbosity def _verbosity_filter(index, verbose): - """ Returns False for indices increasingly appart, the distance + """ Returns False for indices increasingly apart, the distance depending on the value of verbose. We use a lag increasing as the square of index @@ -98,12 +105,21 @@ def __call__(self, *args, **kwargs): ############################################################################### -def delayed(function): - """ Decorator used to capture the arguments of a function. +def delayed(function, check_pickle=True): + """Decorator used to capture the arguments of a function. + + Pass `check_pickle=False` when: + + - performing a possibly repeated check is too costly and has been done + already once outside of the call to delayed. + + - when used in conjunction `Parallel(backend='threading')`. + """ # Try to pickle the input function, to catch the problems early when - # using with multiprocessing - pickle.dumps(function) + # using with multiprocessing: + if check_pickle: + pickle.dumps(function) def delayed_function(*args, **kwargs): return function, args, kwargs @@ -138,31 +154,95 @@ def __init__(self, index, parallel): def __call__(self, out): self.parallel.print_progress(self.index) - if self.parallel._iterable: + if self.parallel._original_iterable: self.parallel.dispatch_next() +class LockedIterator(object): + """Wrapper to protect a thread-unsafe iterable against concurrent access. + + A Python generator is not thread-safe by default and will raise + ValueError("generator already executing") if two threads consume it + concurrently. + + In joblib this could typically happen when the passed iterator is a + generator expression and pre_dispatch != 'all'. In that case a callback is + passed to the multiprocessing apply_async call and helper threads will + trigger the consumption of the source iterable in the dispatch_next + method. + + """ + def __init__(self, it): + self._lock = threading.Lock() + self._it = iter(it) + + def __iter__(self): + return self + + def next(self): + with self._lock: + return next(self._it) + + # For Python 3 compat + __next__ = next + + + ############################################################################### class Parallel(Logger): ''' Helper class for readable parallel mapping. Parameters ----------- - n_jobs: int + n_jobs : int The number of jobs to use for the computation. If -1 all CPUs are used. If 1 is given, no parallel computing code is used - at all, which is useful for debuging. For n_jobs below -1, - (n_cpus + 1 - n_jobs) are used. Thus for n_jobs = -2, all + at all, which is useful for debugging. For n_jobs below -1, + (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. - verbose: int, optional + backend : str or None + Specify the parallelization backend implementation. + Supported backends are: + - "multiprocessing" used by default, can induce some + communication and memory overhead when exchanging input and + output data with the with the worker Python processes. + - "threading" is a very low-overhead backend but it suffers + from the Python Global Interpreter Lock if the called function + relies a lot on Python objects. "threading" is mostly useful + when the execution bottleneck is a compiled extension that + explicitly releases the GIL (for instance a Cython loop wrapped + in a "with nogil" block or an expensive call to a library such + as NumPy). + verbose : int, optional The verbosity level: if non zero, progress messages are printed. Above 50, the output is sent to stdout. The frequency of the messages increases with the verbosity level. If it more than 10, all iterations are reported. - pre_dispatch: {'all', integer, or expression, as in '3*n_jobs'} + pre_dispatch : {'all', integer, or expression, as in '3*n_jobs'} The amount of jobs to be pre-dispatched. Default is 'all', but it may be memory consuming, for instance if each job involves a lot of a data. + temp_folder : str, optional + Folder to be used by the pool for memmaping large arrays + for sharing memory with worker processes. If None, this will try in + order: + - a folder pointed by the JOBLIB_TEMP_FOLDER environment variable, + - /dev/shm if the folder exists and is writable: this is a RAMdisk + filesystem available by default on modern Linux distributions, + - the default system temporary folder that can be overridden + with TMP, TMPDIR or TEMP environment variables, typically /tmp + under Unix operating systems. + Only active when backend="multiprocessing". + max_nbytes : int, str, or None, optional, 100e6 (100MB) by default + Threshold on the size of arrays passed to the workers that + triggers automated memory mapping in temp_folder. Can be an int + in Bytes, or a human-readable string, e.g., '1M' for 1 megabyte. + Use None to disable memmaping of large arrays. + Only active when backend="multiprocessing". + mmap_mode : 'r', 'r+' or 'c' + Mode for the created memmap datastructure. See the documentation of + numpy.memmap for more details. Note: 'w+' is coerced to 'r+' + automatically to avoid zeroing the data on unpickling. Notes ----- @@ -175,17 +255,23 @@ class Parallel(Logger): * More readable code, in particular since it avoids constructing list of arguments. - * Easier debuging: + * Easier debugging: - informative tracebacks even when the error happens on the client side - using 'n_jobs=1' enables to turn off parallel computing - for debuging without changing the codepath + for debugging without changing the codepath - early capture of pickling errors * An optional progress meter. * Interruption of multiprocesses jobs with 'Ctrl-C' + * Flexible pickling control for the communication to and from + the worker processes. + + * Ability to use shared memory efficiently with worker + processes for large numpy-based datastructures. + Examples -------- @@ -225,31 +311,32 @@ class Parallel(Logger): triggered the exception, even though the traceback happens in the child process:: - >>> from string import atoi + >>> from heapq import nlargest >>> from sklearn.externals.joblib import Parallel, delayed - >>> Parallel(n_jobs=2)(delayed(atoi)(n) for n in ('1', '300', 30)) #doctest: +SKIP + >>> Parallel(n_jobs=2)(delayed(nlargest)(2, n) for n in (range(4), 'abcde', 3)) #doctest: +SKIP #... --------------------------------------------------------------------------- Sub-process traceback: --------------------------------------------------------------------------- - TypeError Fri Jul 2 20:32:05 2010 - PID: 4151 Python 2.6.5: /usr/bin/python + TypeError Mon Nov 12 11:37:46 2012 + PID: 12934 Python 2.7.3: /usr/bin/python ........................................................................... - /usr/lib/python2.6/string.pyc in atoi(s=30, base=10) - 398 is chosen from the leading characters of s, 0 for octal, 0x or - 399 0X for hexadecimal. If base is 16, a preceding 0x or 0X is - 400 accepted. - 401 - 402 """ - --> 403 return _int(s, base) - 404 - 405 - 406 # Convert string to long integer - 407 def atol(s, base=10): - - TypeError: int() can't convert non-string with explicit base + /usr/lib/python2.7/heapq.pyc in nlargest(n=2, iterable=3, key=None) + 419 if n >= size: + 420 return sorted(iterable, key=key, reverse=True)[:n] + 421 + 422 # When key is none, use simpler decoration + 423 if key is None: + --> 424 it = izip(iterable, count(0,-1)) # decorate + 425 result = _nlargest(n, it) + 426 return map(itemgetter(0), result) # undecorate + 427 + 428 # General case, slowest method + + TypeError: izip argument #1 must support iteration ___________________________________________________________________________ + Using pre_dispatch in a producer/consumer situation, where the data is generated on the fly. Note how the producer is first called a 3 times before the parallel loop is initiated, and then @@ -261,7 +348,7 @@ class Parallel(Logger): >>> def producer(): ... for i in range(6): - ... print 'Produced %s' % i + ... print('Produced %s' % i) ... yield i >>> out = Parallel(n_jobs=2, verbose=100, pre_dispatch='1.5*n_jobs')( @@ -279,15 +366,38 @@ class Parallel(Logger): [Parallel(n_jobs=2)]: Done 5 out of 6 | elapsed: 0.0s remaining: 0.0s [Parallel(n_jobs=2)]: Done 6 out of 6 | elapsed: 0.0s finished ''' - def __init__(self, n_jobs=None, verbose=0, pre_dispatch='all'): + def __init__(self, n_jobs=1, backend=None, verbose=0, pre_dispatch='all', + temp_folder=None, max_nbytes=100e6, mmap_mode='r'): self.verbose = verbose + self._mp_context = None + if backend is None: + backend = "multiprocessing" + elif hasattr(backend, 'Pool') and hasattr(backend, 'Lock'): + # Make it possible to pass a custom multiprocessing context as + # backend to change the start method to forkserver or spawn or + # preload modules on the forkserver helper process. + self._mp_context = backend + backend = "multiprocessing" + if backend not in VALID_BACKENDS: + raise ValueError("Invalid backend: %s, expected one of %r" + % (backend, VALID_BACKENDS)) + self.backend = backend self.n_jobs = n_jobs self.pre_dispatch = pre_dispatch self._pool = None + self._temp_folder = temp_folder + if isinstance(max_nbytes, _basestring): + self._max_nbytes = 1024 * memstr_to_kbytes(max_nbytes) + else: + self._max_nbytes = max_nbytes + self._mmap_mode = mmap_mode # Not starting the pool in the __init__ is a design decision, to be # able to close it ASAP, and not burden the user with closing it. self._output = None self._jobs = list() + # A flag used to abort the dispatching of jobs in case an + # exception is found + self._aborting = False def dispatch(self, func, args, kwargs): """ Queue the function for computing, with or without multiprocessing @@ -303,15 +413,17 @@ def dispatch(self, func, args, kwargs): self._jobs.append(job) self.n_dispatched += 1 else: - self._lock.acquire() # If job.get() catches an exception, it closes the queue: + if self._aborting: + return try: + self._lock.acquire() job = self._pool.apply_async(SafeFunction(func), args, kwargs, callback=CallBack(self.n_dispatched, self)) self._jobs.append(job) self.n_dispatched += 1 except AssertionError: - print '[Parallel] Pool seems closed' + print('[Parallel] Pool seems closed') finally: self._lock.release() @@ -322,8 +434,8 @@ def dispatch_next(self): while self._dispatch_amount: try: # XXX: possible race condition shuffling the order of - # dispatchs in the next two lines. - func, args, kwargs = self._iterable.next() + # dispatches in the next two lines. + func, args, kwargs = next(self._original_iterable) self.dispatch(func, args, kwargs) self._dispatch_amount -= 1 except ValueError: @@ -331,7 +443,8 @@ def dispatch_next(self): the dispatch will be done later. """ except StopIteration: - self._iterable = None + self._iterating = False + self._original_iterable = None return def _print(self, msg, msg_args): @@ -350,7 +463,7 @@ def _print(self, msg, msg_args): def print_progress(self, index): """Display the process of the parallel execution only a fraction - of time, controled by self.verbose. + of time, controlled by self.verbose. """ if not self.verbose: return @@ -358,7 +471,7 @@ def print_progress(self, index): # This is heuristic code to print only 'verbose' times a messages # The challenge is that we may not know the queue length - if self._iterable: + if self._original_iterable: if _verbosity_filter(index, self.verbose): return self._print('Done %3i jobs | elapsed: %s', @@ -389,7 +502,11 @@ def print_progress(self, index): def retrieve(self): self._output = list() - while self._jobs: + while self._iterating or len(self._jobs) > 0: + if len(self._jobs) == 0: + # Wait for an async callback to dispatch new jobs + time.sleep(0.01) + continue # We need to be careful: the job queue can be filling up as # we empty it if hasattr(self, '_lock'): @@ -399,79 +516,153 @@ def retrieve(self): self._lock.release() try: self._output.append(job.get()) - except tuple(self.exceptions), exception: - if isinstance(exception, - (KeyboardInterrupt, WorkerInterrupt)): - # We have captured a user interruption, clean up - # everything - if hasattr(self, '_pool'): - self._pool.close() - self._pool.terminate() + except tuple(self.exceptions) as exception: + try: + self._aborting = True + self._lock.acquire() + if isinstance(exception, + (KeyboardInterrupt, WorkerInterrupt)): + # We have captured a user interruption, clean up + # everything + if hasattr(self, '_pool'): + self._pool.close() + self._pool.terminate() + # We can now allow subprocesses again + os.environ.pop('__JOBLIB_SPAWNED_PARALLEL__', 0) + raise exception + elif isinstance(exception, TransportableException): + # Capture exception to add information on the local + # stack in addition to the distant stack + this_report = format_outer_frames(context=10, + stack_start=1) + report = """Multiprocessing exception: + %s + --------------------------------------------------------------------------- + Sub-process traceback: + --------------------------------------------------------------------------- + %s""" % ( + this_report, + exception.message, + ) + # Convert this to a JoblibException + exception_type = _mk_exception(exception.etype)[0] + raise exception_type(report) raise exception - elif isinstance(exception, TransportableException): - # Capture exception to add information on the local stack - # in addition to the distant stack - this_report = format_outer_frames(context=10, - stack_start=1) - report = """Multiprocessing exception: -%s ---------------------------------------------------------------------------- -Sub-process traceback: ---------------------------------------------------------------------------- -%s""" % ( - this_report, - exception.message, - ) - # Convert this to a JoblibException - exception_type = _mk_exception(exception.etype)[0] - raise exception_type(report) - raise exception + finally: + self._lock.release() def __call__(self, iterable): if self._jobs: raise ValueError('This Parallel instance is already running') n_jobs = self.n_jobs - if n_jobs < 0 and multiprocessing is not None: - n_jobs = max(multiprocessing.cpu_count() + 1 + n_jobs, 1) + if n_jobs == 0: + raise ValueError('n_jobs == 0 in Parallel has no meaning') + if n_jobs < 0 and mp is not None: + n_jobs = max(mp.cpu_count() + 1 + n_jobs, 1) # The list of exceptions that we will capture self.exceptions = [TransportableException] - if n_jobs is None or multiprocessing is None or n_jobs == 1: + self._lock = threading.Lock() + + # Whether or not to set an environment flag to track + # multiple process spawning + set_environ_flag = False + if (n_jobs is None or mp is None or n_jobs == 1): n_jobs = 1 self._pool = None - else: - if multiprocessing.current_process()._daemonic: + elif self.backend == 'threading': + self._pool = ThreadPool(n_jobs) + elif self.backend == 'multiprocessing': + if mp.current_process().daemon: # Daemonic processes cannot have children n_jobs = 1 self._pool = None warnings.warn( - 'Parallel loops cannot be nested, setting n_jobs=1', + 'Multiprocessing-backed parallel loops cannot be nested,' + ' setting n_jobs=1', + stacklevel=2) + elif threading.current_thread().name != 'MainThread': + # Prevent posix fork inside in non-main posix threads + n_jobs = 1 + self._pool = None + warnings.warn( + 'Multiprocessing backed parallel loops cannot be nested' + ' below threads, setting n_jobs=1', stacklevel=2) else: - self._pool = multiprocessing.Pool(n_jobs) - self._lock = threading.Lock() + already_forked = int(os.environ.get('__JOBLIB_SPAWNED_PARALLEL__', 0)) + if already_forked: + raise ImportError('[joblib] Attempting to do parallel computing ' + 'without protecting your import on a system that does ' + 'not support forking. To use parallel-computing in a ' + 'script, you must protect your main loop using "if ' + "__name__ == '__main__'" + '". Please see the joblib documentation on Parallel ' + 'for more information' + ) + + # Make sure to free as much memory as possible before forking + gc.collect() + + # Set an environment variable to avoid infinite loops + set_environ_flag = True + poolargs = dict( + max_nbytes=self._max_nbytes, + mmap_mode=self._mmap_mode, + temp_folder=self._temp_folder, + verbose=max(0, self.verbose - 50), + context_id=0, # the pool is used only for one call + ) + if self._mp_context is not None: + # Use Python 3.4+ multiprocessing context isolation + poolargs['context'] = self._mp_context + self._pool = MemmapingPool(n_jobs, **poolargs) # We are using multiprocessing, we also want to capture # KeyboardInterrupts self.exceptions.extend([KeyboardInterrupt, WorkerInterrupt]) + else: + raise ValueError("Unsupported backend: %s" % self.backend) - if self.pre_dispatch == 'all' or n_jobs == 1: - self._iterable = None + pre_dispatch = self.pre_dispatch + if isinstance(iterable, Sized): + # We are given a sized (an object with len). No need to be lazy. + pre_dispatch = 'all' + + if pre_dispatch == 'all' or n_jobs == 1: + self._original_iterable = None self._pre_dispatch_amount = 0 else: - self._iterable = iterable + # The dispatch mechanism relies on multiprocessing helper threads + # to dispatch tasks from the original iterable concurrently upon + # job completions. As Python generators are not thread-safe we + # need to wrap it with a lock + iterable = LockedIterator(iterable) + self._original_iterable = iterable self._dispatch_amount = 0 - pre_dispatch = self.pre_dispatch if hasattr(pre_dispatch, 'endswith'): pre_dispatch = eval(pre_dispatch) self._pre_dispatch_amount = pre_dispatch = int(pre_dispatch) + + # The main thread will consume the first pre_dispatch items and + # the remaining items will later be lazily dispatched by async + # callbacks upon task completions iterable = itertools.islice(iterable, pre_dispatch) self._start_time = time.time() self.n_dispatched = 0 try: + if set_environ_flag: + # Set an environment variable to avoid infinite loops + os.environ[JOBLIB_SPAWNED_PROCESS] = '1' + self._iterating = True for function, args, kwargs in iterable: self.dispatch(function, args, kwargs) + if pre_dispatch == "all" or n_jobs == 1: + # The iterable was consumed all at once by the above for loop. + # No need to wait for async callbacks to trigger to + # consumption. + self._iterating = False self.retrieve() # Make sure that we get a last message telling us we are done elapsed_time = time.time() - self._start_time @@ -484,7 +675,9 @@ def __call__(self, iterable): finally: if n_jobs > 1: self._pool.close() - self._pool.join() + self._pool.terminate() # terminate does a join() + if self.backend == 'multiprocessing': + os.environ.pop(JOBLIB_SPAWNED_PROCESS, 0) self._jobs = list() output = self._output self._output = None diff --git a/sklearn/externals/joblib/pool.py b/sklearn/externals/joblib/pool.py new file mode 100644 index 0000000000000..5dd2c43406cca --- /dev/null +++ b/sklearn/externals/joblib/pool.py @@ -0,0 +1,587 @@ +"""Custom implementation of multiprocessing.Pool with custom pickler + +This module provides efficient ways of working with data stored in +shared memory with numpy.memmap arrays without inducing any memory +copy between the parent and child processes. + +This module should not be imported if multiprocessing is not +available as it implements subclasses of multiprocessing Pool +that uses a custom alternative to SimpleQueue. + +""" +# Author: Olivier Grisel +# Copyright: 2012, Olivier Grisel +# License: BSD 3 clause + +from mmap import mmap +import errno +import os +import stat +import sys +import threading +import atexit +import tempfile +import shutil + +try: + # Python 2 compat + from cPickle import loads + from cPickle import dumps +except ImportError: + from pickle import loads + from pickle import dumps + import copyreg + +# Customizable pure Python pickler in Python 2 +# customizable C-optimized pickler under Python 3.3+ +from pickle import Pickler +if sys.version_info[0] > 2 and not hasattr(Pickler, 'dispatch_table'): + # Special case for Python 3.2: use the pure Python pickler as fallback + from pickle import _Pickler as Pickler + +from pickle import HIGHEST_PROTOCOL +from io import BytesIO + +from ._multiprocessing_helpers import mp, assert_spawning +# We need the class definition to derive from it not the multiprocessing.Pool +# factory function +from multiprocessing.pool import Pool + +try: + import numpy as np + from numpy.lib.stride_tricks import as_strided +except ImportError: + np = None + +from .numpy_pickle import load +from .numpy_pickle import dump +from .hashing import hash + +# Some system have a ramdisk mounted by default, we can use it instead of /tmp +# as the default folder to dump big arrays to share with subprocesses +SYSTEM_SHARED_MEM_FS = '/dev/shm' + +# Folder and file permissions to chmod temporary files generated by the +# memmaping pool. Only the owner of the Python process can access the +# temporary files and folder. +FOLDER_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR +FILE_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR + +############################################################################### +# Support for efficient transient pickling of numpy data structures + + +def _get_backing_memmap(a): + """Recursively look up the original np.memmap instance base if any""" + b = getattr(a, 'base', None) + if b is None: + # TODO: check scipy sparse datastructure if scipy is installed + # a nor its descendants do not have a memmap base + return None + + elif isinstance(b, mmap): + # a is already a real memmap instance. + return a + + else: + # Recursive exploration of the base ancestry + return _get_backing_memmap(b) + + +def has_shareable_memory(a): + """Return True if a is backed by some mmap buffer directly or not""" + return _get_backing_memmap(a) is not None + + +def _strided_from_memmap(filename, dtype, mode, offset, order, shape, strides, + total_buffer_len): + """Reconstruct an array view on a memmory mapped file""" + if mode == 'w+': + # Do not zero the original data when unpickling + mode = 'r+' + + if strides is None: + # Simple, contiguous memmap + return np.memmap(filename, dtype=dtype, shape=shape, mode=mode, + offset=offset, order=order) + else: + # For non-contiguous data, memmap the total enclosing buffer and then + # extract the non-contiguous view with the stride-tricks API + base = np.memmap(filename, dtype=dtype, shape=total_buffer_len, + mode=mode, offset=offset, order=order) + return as_strided(base, shape=shape, strides=strides) + + +def _reduce_memmap_backed(a, m): + """Pickling reduction for memmap backed arrays + + a is expected to be an instance of np.ndarray (or np.memmap) + m is expected to be an instance of np.memmap on the top of the ``base`` + attribute ancestry of a. ``m.base`` should be the real python mmap object. + """ + # offset that comes from the striding differences between a and m + a_start, a_end = np.byte_bounds(a) + m_start = np.byte_bounds(m)[0] + offset = a_start - m_start + + # offset from the backing memmap + offset += m.offset + + if m.flags['F_CONTIGUOUS']: + order = 'F' + else: + # The backing memmap buffer is necessarily contiguous hence C if not + # Fortran + order = 'C' + + if a.flags['F_CONTIGUOUS'] or a.flags['C_CONTIGUOUS']: + # If the array is a contiguous view, no need to pass the strides + strides = None + total_buffer_len = None + else: + # Compute the total number of items to map from which the strided + # view will be extracted. + strides = a.strides + total_buffer_len = (a_end - a_start) // a.itemsize + return (_strided_from_memmap, + (m.filename, a.dtype, m.mode, offset, order, a.shape, strides, + total_buffer_len)) + + +def reduce_memmap(a): + """Pickle the descriptors of a memmap instance to reopen on same file""" + m = _get_backing_memmap(a) + if m is not None: + # m is a real mmap backed memmap instance, reduce a preserving striding + # information + return _reduce_memmap_backed(a, m) + else: + # This memmap instance is actually backed by a regular in-memory + # buffer: this can happen when using binary operators on numpy.memmap + # instances + return (loads, (dumps(np.asarray(a), protocol=HIGHEST_PROTOCOL),)) + + +class ArrayMemmapReducer(object): + """Reducer callable to dump large arrays to memmap files. + + Parameters + ---------- + max_nbytes: int + Threshold to trigger memmaping of large arrays to files created + a folder. + temp_folder: str + Path of a folder where files for backing memmaped arrays are created. + mmap_mode: 'r', 'r+' or 'c' + Mode for the created memmap datastructure. See the documentation of + numpy.memmap for more details. Note: 'w+' is coerced to 'r+' + automatically to avoid zeroing the data on unpickling. + verbose: int, optional, 0 by default + If verbose > 0, memmap creations are logged. + If verbose > 1, both memmap creations, reuse and array pickling are + logged. + context_id: int, optional, None by default + Set to a value identifying a call context to spare costly hashing of + the content of the input arrays when it is safe to assume that each + array will not be mutated by the parent process for the duration of the + dispatch process. This is the case when using the high level Parallel + API. It might not be the case when using the MemmapingPool API + directly. + prewarm: bool, optional, False by default. + Force a read on newly memmaped array to make sure that OS pre-cache it + memory. This can be useful to avoid concurrent disk access when the + same data array is passed to different worker processes. + """ + + def __init__(self, max_nbytes, temp_folder, mmap_mode, verbose=0, + context_id=None, prewarm=True): + self._max_nbytes = max_nbytes + self._temp_folder = temp_folder + self._mmap_mode = mmap_mode + self.verbose = int(verbose) + self._context_id = context_id + self._prewarm = prewarm + + def __call__(self, a): + m = _get_backing_memmap(a) + if m is not None: + # a is already backed by a memmap file, let's reuse it directly + return _reduce_memmap_backed(a, m) + + if (not a.dtype.hasobject + and self._max_nbytes is not None + and a.nbytes > self._max_nbytes): + # check that the folder exists (lazily create the pool temp folder + # if required) + try: + os.makedirs(self._temp_folder) + os.chmod(self._temp_folder, FOLDER_PERMISSIONS) + except OSError as e: + if e.errno != errno.EEXIST: + raise e + + # Find a unique, concurrent safe filename for writing the + # content of this array only once. + if self._context_id is not None: + marker = self._context_id + else: + marker = hash(a) + basename = "%d-%d-%d-%s.pkl" % ( + os.getpid(), id(threading.current_thread()), id(a), marker) + filename = os.path.join(self._temp_folder, basename) + + # In case the same array with the same content is passed several + # times to the pool subprocess children, serialize it only once + + # XXX: implement an explicit reference counting scheme to make it + # possible to delete temporary files as soon as the workers are + # done processing this data. + if not os.path.exists(filename): + if self.verbose > 0: + print("Memmaping (shape=%r, dtype=%s) to new file %s" % ( + a.shape, a.dtype, filename)) + for dumped_filename in dump(a, filename): + os.chmod(dumped_filename, FILE_PERMISSIONS) + + if self._prewarm: + # Warm up the data to avoid concurrent disk access in + # multiple children processes + load(filename, mmap_mode=self._mmap_mode).max() + elif self.verbose > 1: + print("Memmaping (shape=%s, dtype=%s) to old file %s" % ( + a.shape, a.dtype, filename)) + + # Let's use the memmap reducer + return reduce_memmap(load(filename, mmap_mode=self._mmap_mode)) + else: + # do not convert a into memmap, let pickler do its usual copy with + # the default system pickler + if self.verbose > 1: + print("Pickling array (shape=%r, dtype=%s)." % ( + a.shape, a.dtype)) + return (loads, (dumps(a, protocol=HIGHEST_PROTOCOL),)) + + +############################################################################### +# Enable custom pickling in Pool queues + +class CustomizablePickler(Pickler): + """Pickler that accepts custom reducers. + + HIGHEST_PROTOCOL is selected by default as this pickler is used + to pickle ephemeral datastructures for interprocess communication + hence no backward compatibility is required. + + `reducers` is expected expected to be a dictionary with key/values + being `(type, callable)` pairs where `callable` is a function that + give an instance of `type` will return a tuple `(constructor, + tuple_of_objects)` to rebuild an instance out of the pickled + `tuple_of_objects` as would return a `__reduce__` method. See the + standard library documentation on pickling for more details. + + """ + + # We override the pure Python pickler as its the only way to be able to + # customize the dispatch table without side effects in Python 2.6 + # to 3.2. For Python 3.3+ leverage the new dispatch_table + # feature from http://bugs.python.org/issue14166 that makes it possible + # to use the C implementation of the Pickler which is faster. + + def __init__(self, writer, reducers=None, protocol=HIGHEST_PROTOCOL): + Pickler.__init__(self, writer, protocol=protocol) + if reducers is None: + reducers = {} + if hasattr(Pickler, 'dispatch'): + # Make the dispatch registry an instance level attribute instead of + # a reference to the class dictionary under Python 2 + self.dispatch = Pickler.dispatch.copy() + else: + # Under Python 3 initialize the dispatch table with with a copy of + # the default registry + self.dispatch_table = copyreg.dispatch_table.copy() + for type, reduce_func in reducers.items(): + self.register(type, reduce_func) + + def register(self, type, reduce_func): + if hasattr(Pickler, 'dispatch'): + # Python 2 pickler dispatching is not explicitly customizable. + # Let us use a closure to workaround this limitation. + def dispatcher(self, obj): + reduced = reduce_func(obj) + self.save_reduce(obj=obj, *reduced) + self.dispatch[type] = dispatcher + else: + self.dispatch_table[type] = reduce_func + + +class CustomizablePicklingQueue(object): + """Locked Pipe implementation that uses a customizable pickler. + + This class is an alternative to the multiprocessing implementation + of SimpleQueue in order to make it possible to pass custom + pickling reducers, for instance to avoid memory copy when passing + memmory mapped datastructures. + + `reducers` is expected expected to be a dictionary with key/values + being `(type, callable)` pairs where `callable` is a function that + give an instance of `type` will return a tuple `(constructor, + tuple_of_objects)` to rebuild an instance out of the pickled + `tuple_of_objects` as would return a `__reduce__` method. See the + standard library documentation on pickling for more details. + """ + + def __init__(self, context, reducers=None): + self._reducers = reducers + self._reader, self._writer = context.Pipe(duplex=False) + self._rlock = context.Lock() + if sys.platform == 'win32': + self._wlock = None + else: + self._wlock = context.Lock() + self._make_methods() + + def __getstate__(self): + assert_spawning(self) + return (self._reader, self._writer, self._rlock, self._wlock, + self._reducers) + + def __setstate__(self, state): + (self._reader, self._writer, self._rlock, self._wlock, + self._reducers) = state + self._make_methods() + + def empty(self): + return not self._reader.poll() + + def _make_methods(self): + self._recv = recv = self._reader.recv + racquire, rrelease = self._rlock.acquire, self._rlock.release + + def get(): + racquire() + try: + return recv() + finally: + rrelease() + + self.get = get + + if self._reducers: + def send(obj): + buffer = BytesIO() + CustomizablePickler(buffer, self._reducers).dump(obj) + self._writer.send_bytes(buffer.getvalue()) + self._send = send + else: + self._send = send = self._writer.send + if self._wlock is None: + # writes to a message oriented win32 pipe are atomic + self.put = send + else: + wlock_acquire, wlock_release = ( + self._wlock.acquire, self._wlock.release) + + def put(obj): + wlock_acquire() + try: + return send(obj) + finally: + wlock_release() + + self.put = put + + +class PicklingPool(Pool): + """Pool implementation with customizable pickling reducers. + + This is useful to control how data is shipped between processes + and makes it possible to use shared memory without useless + copies induces by the default pickling methods of the original + objects passed as arguments to dispatch. + + `forward_reducers` and `backward_reducers` are expected to be + dictionaries with key/values being `(type, callable)` pairs where + `callable` is a function that give an instance of `type` will return + a tuple `(constructor, tuple_of_objects)` to rebuild an instance out + of the pickled `tuple_of_objects` as would return a `__reduce__` + method. See the standard library documentation on pickling for more + details. + + """ + + def __init__(self, processes=None, forward_reducers=None, + backward_reducers=None, **kwargs): + if forward_reducers is None: + forward_reducers = dict() + if backward_reducers is None: + backward_reducers = dict() + self._forward_reducers = forward_reducers + self._backward_reducers = backward_reducers + poolargs = dict(processes=processes) + poolargs.update(kwargs) + super(PicklingPool, self).__init__(**poolargs) + + def _setup_queues(self): + context = getattr(self, '_ctx', mp) + self._inqueue = CustomizablePicklingQueue(context, + self._forward_reducers) + self._outqueue = CustomizablePicklingQueue(context, + self._backward_reducers) + self._quick_put = self._inqueue._send + self._quick_get = self._outqueue._recv + + +def delete_folder(folder_path): + """Utility function to cleanup a temporary folder if still existing""" + if os.path.exists(folder_path): + shutil.rmtree(folder_path) + + +class MemmapingPool(PicklingPool): + """Process pool that shares large arrays to avoid memory copy. + + This drop-in replacement for `multiprocessing.pool.Pool` makes + it possible to work efficiently with shared memory in a numpy + context. + + Existing instances of numpy.memmap are preserved: the child + suprocesses will have access to the same shared memory in the + original mode except for the 'w+' mode that is automatically + transformed as 'r+' to avoid zeroing the original data upon + instantiation. + + Furthermore large arrays from the parent process are automatically + dumped to a temporary folder on the filesystem such as child + processes to access their content via memmaping (file system + backed shared memory). + + Note: it is important to call the terminate method to collect + the temporary folder used by the pool. + + Parameters + ---------- + processes: int, optional + Number of worker processes running concurrently in the pool. + initializer: callable, optional + Callable executed on worker process creation. + initargs: tuple, optional + Arguments passed to the initializer callable. + temp_folder: str, optional + Folder to be used by the pool for memmaping large arrays + for sharing memory with worker processes. If None, this will try in + order: + - a folder pointed by the JOBLIB_TEMP_FOLDER environment variable, + - /dev/shm if the folder exists and is writable: this is a RAMdisk + filesystem available by default on modern Linux distributions, + - the default system temporary folder that can be overridden + with TMP, TMPDIR or TEMP environment variables, typically /tmp + under Unix operating systems. + max_nbytes int or None, optional, 1e6 by default + Threshold on the size of arrays passed to the workers that + triggers automated memmory mapping in temp_folder. + Use None to disable memmaping of large arrays. + forward_reducers: dictionary, optional + Reducers used to pickle objects passed from master to worker + processes: see below. + backward_reducers: dictionary, optional + Reducers used to pickle return values from workers back to the + master process. + verbose: int, optional + Make it possible to monitor how the communication of numpy arrays + with the subprocess is handled (pickling or memmaping) + context_id: int, optional, None by default + Set to a value identifying a call context to spare costly hashing of + the content of the input arrays when it is safe to assume that each + array will not be mutated by the parent process for the duration of the + dispatch process. This is the case when using the high level Parallel + API. + prewarm: bool or str, optional, "auto" by default. + If True, force a read on newly memmaped array to make sure that OS pre- + cache it in memory. This can be useful to avoid concurrent disk access + when the same data array is passed to different worker processes. + If "auto" (by default), prewarm is set to True, unless the Linux shared + memory partition /dev/shm is available and used as temp_folder. + + `forward_reducers` and `backward_reducers` are expected to be + dictionaries with key/values being `(type, callable)` pairs where + `callable` is a function that give an instance of `type` will return + a tuple `(constructor, tuple_of_objects)` to rebuild an instance out + of the pickled `tuple_of_objects` as would return a `__reduce__` + method. See the standard library documentation on pickling for more + details. + + """ + + def __init__(self, processes=None, temp_folder=None, max_nbytes=1e6, + mmap_mode='r', forward_reducers=None, backward_reducers=None, + verbose=0, context_id=None, prewarm=False, **kwargs): + if forward_reducers is None: + forward_reducers = dict() + if backward_reducers is None: + backward_reducers = dict() + + # Prepare a sub-folder name for the serialization of this particular + # pool instance (do not create in advance to spare FS write access if + # no array is to be dumped): + use_shared_mem = False + pool_folder_name = "joblib_memmaping_pool_%d_%d" % ( + os.getpid(), id(self)) + if temp_folder is None: + temp_folder = os.environ.get('JOBLIB_TEMP_FOLDER', None) + if temp_folder is None: + if os.path.exists(SYSTEM_SHARED_MEM_FS): + try: + temp_folder = SYSTEM_SHARED_MEM_FS + pool_folder = os.path.join(temp_folder, pool_folder_name) + if not os.path.exists(pool_folder): + os.makedirs(pool_folder) + use_shared_mem = True + except IOError: + # Missing rights in the the /dev/shm partition, + # fallback to regular temp folder. + temp_folder = None + if temp_folder is None: + # Fallback to the default tmp folder, typically /tmp + temp_folder = tempfile.gettempdir() + temp_folder = os.path.abspath(os.path.expanduser(temp_folder)) + pool_folder = os.path.join(temp_folder, pool_folder_name) + self._temp_folder = pool_folder + + # Register the garbage collector at program exit in case caller forgets + # to call terminate explicitly: note we do not pass any reference to + # self to ensure that this callback won't prevent garbage collection of + # the pool instance and related file handler resources such as POSIX + # semaphores and pipes + atexit.register(lambda: delete_folder(pool_folder)) + + if np is not None: + # Register smart numpy.ndarray reducers that detects memmap backed + # arrays and that is alse able to dump to memmap large in-memory + # arrays over the max_nbytes threshold + if prewarm == "auto": + prewarm = not use_shared_mem + forward_reduce_ndarray = ArrayMemmapReducer( + max_nbytes, pool_folder, mmap_mode, verbose, + context_id=context_id, prewarm=prewarm) + forward_reducers[np.ndarray] = forward_reduce_ndarray + forward_reducers[np.memmap] = reduce_memmap + + # Communication from child process to the parent process always + # pickles in-memory numpy.ndarray without dumping them as memmap + # to avoid confusing the caller and make it tricky to collect the + # temporary folder + backward_reduce_ndarray = ArrayMemmapReducer( + None, pool_folder, mmap_mode, verbose) + backward_reducers[np.ndarray] = backward_reduce_ndarray + backward_reducers[np.memmap] = reduce_memmap + + poolargs = dict( + processes=processes, + forward_reducers=forward_reducers, + backward_reducers=backward_reducers) + poolargs.update(kwargs) + super(MemmapingPool, self).__init__(**poolargs) + + def terminate(self): + super(MemmapingPool, self).terminate() + delete_folder(self._temp_folder) diff --git a/sklearn/externals/joblib/test/common.py b/sklearn/externals/joblib/test/common.py deleted file mode 100644 index 5e2b61c364544..0000000000000 --- a/sklearn/externals/joblib/test/common.py +++ /dev/null @@ -1,22 +0,0 @@ -""" -Small utilities for testing. -""" -import nose - -# A decorator to run tests only when numpy is available -try: - import numpy as np - - def with_numpy(func): - """ A decorator to skip tests requiring numpy. - """ - return func - -except ImportError: - def with_numpy(func): - """ A decorator to skip tests requiring numpy. - """ - def my_func(): - raise nose.SkipTest('Test requires numpy') - return my_func - np = None diff --git a/sklearn/externals/joblib/test/test_disk.py b/sklearn/externals/joblib/test/test_disk.py deleted file mode 100644 index 353d3bfd6fac7..0000000000000 --- a/sklearn/externals/joblib/test/test_disk.py +++ /dev/null @@ -1,66 +0,0 @@ -""" -Unit tests for the disk utilities. -""" - -# Authors: Gael Varoquaux -# Lars Buitinck -# Copyright (c) 2010 Gael Varoquaux -# License: BSD Style, 3 clauses. - -from __future__ import with_statement - -import os -import shutil -import array -from tempfile import mkdtemp - -import nose - -from ..disk import disk_used, memstr_to_kbytes, mkdirp - - -############################################################################### - -def test_disk_used(): - cachedir = mkdtemp() - try: - if os.path.exists(cachedir): - shutil.rmtree(cachedir) - os.mkdir(cachedir) - # Not write a file that is 1M big in this directory, and check the - # size. The reason we use such a big file is that it makes us robust - # to errors due to block allocation. - a = array.array('i') - sizeof_i = a.itemsize - target_size = 1024 - n = int(target_size * 1024 / sizeof_i) - a = array.array('i', n * (1,)) - with open(os.path.join(cachedir, 'test'), 'wb') as output: - a.tofile(output) - nose.tools.assert_true(disk_used(cachedir) >= target_size) - nose.tools.assert_true(disk_used(cachedir) < target_size + 12) - finally: - shutil.rmtree(cachedir) - - -def test_memstr_to_kbytes(): - for text, value in zip(('80G', '1.4M', '120M', '53K'), - (80 * 1024 ** 2, int(1.4 * 1024), 120 * 1024, 53)): - yield nose.tools.assert_equal, memstr_to_kbytes(text), value - - nose.tools.assert_raises(ValueError, memstr_to_kbytes, 'foobar') - - -def test_mkdirp(): - try: - tmp = mkdtemp() - - mkdirp(os.path.join(tmp, "ham")) - mkdirp(os.path.join(tmp, "ham")) - mkdirp(os.path.join(tmp, "spam", "spam")) - - # Not all OSErrors are ignored - nose.tools.assert_raises(OSError, mkdirp, "") - - finally: - shutil.rmtree(tmp) diff --git a/sklearn/externals/joblib/test/test_format_stack.py b/sklearn/externals/joblib/test/test_format_stack.py deleted file mode 100644 index 28387b4b95356..0000000000000 --- a/sklearn/externals/joblib/test/test_format_stack.py +++ /dev/null @@ -1,22 +0,0 @@ -""" -Unit tests for the stack formatting utilities -""" - -# Author: Gael Varoquaux -# Copyright (c) 2010 Gael Varoquaux -# License: BSD Style, 3 clauses. - -import nose - -from ..format_stack import safe_repr - - -############################################################################### - -class Vicious(object): - def __repr__(self): - raise ValueError - - -def test_safe_repr(): - safe_repr(Vicious()) diff --git a/sklearn/externals/joblib/test/test_func_inspect.py b/sklearn/externals/joblib/test/test_func_inspect.py deleted file mode 100644 index d10eb5ac836bb..0000000000000 --- a/sklearn/externals/joblib/test/test_func_inspect.py +++ /dev/null @@ -1,171 +0,0 @@ -""" -Test the func_inspect module. -""" - -# Author: Gael Varoquaux -# Copyright (c) 2009 Gael Varoquaux -# License: BSD Style, 3 clauses. - -import nose -import tempfile -import functools - -from ..func_inspect import filter_args, get_func_name, get_func_code, \ - _clean_win_chars -from ..memory import Memory - - -############################################################################### -# Module-level functions, for tests -def f(x, y=0): - pass - - -def f2(x): - pass - - -# Create a Memory object to test decorated functions. -# We should be careful not to call the decorated functions, so that -# cache directories are not created in the temp dir. -mem = Memory(cachedir=tempfile.gettempdir()) - - -@mem.cache -def g(x): - return x - - -def h(x, y=0, *args, **kwargs): - pass - - -def i(x=1): - pass - - -def j(x, y, **kwargs): - pass - - -def k(*args, **kwargs): - pass - - -class Klass(object): - - def f(self, x): - return x - - -############################################################################### -# Tests - -def test_filter_args(): - yield nose.tools.assert_equal, filter_args(f, [], (1, )),\ - {'x': 1, 'y': 0} - yield nose.tools.assert_equal, filter_args(f, ['x'], (1, )),\ - {'y': 0} - yield nose.tools.assert_equal, filter_args(f, ['y'], (0, )),\ - {'x': 0} - yield nose.tools.assert_equal, filter_args(f, ['y'], (0, ), - dict(y=1)), {'x': 0} - yield nose.tools.assert_equal, filter_args(f, ['x', 'y'], - (0, )), {} - yield nose.tools.assert_equal, filter_args(f, [], (0,), - dict(y=1)), {'x': 0, 'y': 1} - yield nose.tools.assert_equal, filter_args(f, ['y'], (), - dict(x=2, y=1)), {'x': 2} - - yield nose.tools.assert_equal, filter_args(i, [], (2, )), {'x': 2} - yield nose.tools.assert_equal, filter_args(f2, [], (), - dict(x=1)), {'x': 1} - - -def test_filter_args_method(): - obj = Klass() - nose.tools.assert_equal(filter_args(obj.f, [], (1, )), - {'x': 1, 'self': obj}) - - -def test_filter_varargs(): - yield nose.tools.assert_equal, filter_args(h, [], (1, )), \ - {'x': 1, 'y': 0, '*': [], '**': {}} - yield nose.tools.assert_equal, filter_args(h, [], (1, 2, 3, 4)), \ - {'x': 1, 'y': 2, '*': [3, 4], '**': {}} - yield nose.tools.assert_equal, filter_args(h, [], (1, 25), - dict(ee=2)), \ - {'x': 1, 'y': 25, '*': [], '**': {'ee': 2}} - yield nose.tools.assert_equal, filter_args(h, ['*'], (1, 2, 25), - dict(ee=2)), \ - {'x': 1, 'y': 2, '**': {'ee': 2}} - - -def test_filter_kwargs(): - nose.tools.assert_equal(filter_args(k, [], (1, 2), dict(ee=2)), - {'*': [1, 2], '**': {'ee': 2}}) - nose.tools.assert_equal(filter_args(k, [], (3, 4)), - {'*': [3, 4], '**': {}}) - - -def test_filter_args_2(): - nose.tools.assert_equal(filter_args(j, [], (1, 2), dict(ee=2)), - {'x': 1, 'y': 2, '**': {'ee': 2}}) - - nose.tools.assert_raises(ValueError, filter_args, f, 'a', (None, )) - # Check that we capture an undefined argument - nose.tools.assert_raises(ValueError, filter_args, f, ['a'], (None, )) - ff = functools.partial(f, 1) - # filter_args has to special-case partial - nose.tools.assert_equal(filter_args(ff, [], (1, )), - {'*': [1], '**': {}}) - nose.tools.assert_equal(filter_args(ff, ['y'], (1, )), - {'*': [1], '**': {}}) - - -def test_func_name(): - yield nose.tools.assert_equal, 'f', get_func_name(f)[1] - # Check that we are not confused by the decoration - yield nose.tools.assert_equal, 'g', get_func_name(g)[1] - - -def test_func_inspect_errors(): - """ Check that func_inspect is robust and will work on weird objects - """ - nose.tools.assert_equal(get_func_name('a'.lower)[-1], 'lower') - nose.tools.assert_equal(get_func_code('a'.lower)[1:], (None, -1)) - ff = lambda x: x - nose.tools.assert_equal(get_func_name(ff, win_characters=False)[-1], - '') - nose.tools.assert_equal(get_func_code(ff)[1], - __file__.replace('.pyc', '.py')) - # Simulate a function defined in __main__ - ff.__module__ = '__main__' - nose.tools.assert_equal(get_func_name(ff, win_characters=False)[-1], - '') - nose.tools.assert_equal(get_func_code(ff)[1], - __file__.replace('.pyc', '.py')) - - -def test_bound_methods(): - """ Make sure that calling the same method on two different instances - of the same class does resolv to different signatures. - """ - a = Klass() - b = Klass() - nose.tools.assert_not_equal(filter_args(a.f, [], (1, )), - filter_args(b.f, [], (1, ))) - - -def test_filter_args_error_msg(): - """ Make sure that filter_args returns decent error messages, for the - sake of the user. - """ - nose.tools.assert_raises(ValueError, filter_args, f, []) - - -def test_clean_win_chars(): - string = r'C:\foo\bar\main.py' - mangled_string = _clean_win_chars(string) - for char in ('\\', ':', '<', '>', '!'): - nose.tools.assert_false(char in mangled_string) diff --git a/sklearn/externals/joblib/test/test_hashing.py b/sklearn/externals/joblib/test/test_hashing.py deleted file mode 100644 index 7fdf8228528ac..0000000000000 --- a/sklearn/externals/joblib/test/test_hashing.py +++ /dev/null @@ -1,199 +0,0 @@ -""" -Test the hashing module. -""" - -# Author: Gael Varoquaux -# Copyright (c) 2009 Gael Varoquaux -# License: BSD Style, 3 clauses. - -import nose -import time -import hashlib -import tempfile -import os -import gc -import StringIO - -from ..hashing import hash -from ..func_inspect import filter_args -from ..memory import Memory -from .common import np, with_numpy - -from .test_memory import env as test_memory_env -from .test_memory import setup_module as test_memory_setup_func -from .test_memory import teardown_module as test_memory_teardown_func - - -############################################################################### -# Helper functions for the tests -def time_func(func, *args): - """ Time function func on *args. - """ - times = list() - for _ in range(3): - t1 = time.time() - func(*args) - times.append(time.time() - t1) - return min(times) - - -def relative_time(func1, func2, *args): - """ Return the relative time between func1 and func2 applied on - *args. - """ - time_func1 = time_func(func1, *args) - time_func2 = time_func(func2, *args) - relative_diff = 0.5 * (abs(time_func1 - time_func2) - / (time_func1 + time_func2)) - return relative_diff - - -class Klass(object): - - def f(self, x): - return x - - -class KlassWithCachedMethod(object): - - def __init__(self): - mem = Memory(cachedir=test_memory_env['dir']) - self.f = mem.cache(self.f) - - def f(self, x): - return x - - -############################################################################### -# Tests - -def test_trival_hash(): - """ Smoke test hash on various types. - """ - obj_list = [1, 1., 1 + 1j, - 'a', - (1, ), [1, ], {1:1}, - None, - ] - for obj1 in obj_list: - for obj2 in obj_list: - yield nose.tools.assert_equal, hash(obj1) == hash(obj2), \ - obj1 is obj2 - - -def test_hash_methods(): - """ Check that hashing instance methods works """ - a = StringIO.StringIO('a') - b = StringIO.StringIO('b') - nose.tools.assert_equal(hash(a.flush), hash(a.flush)) - nose.tools.assert_not_equal(hash(a.flush), hash(b.flush)) - - -@with_numpy -def test_hash_numpy(): - """ Test hashing with numpy arrays. - """ - rnd = np.random.RandomState(0) - arr1 = rnd.random_sample((10, 10)) - arr2 = arr1.copy() - arr3 = arr2.copy() - arr3[0] += 1 - obj_list = (arr1, arr2, arr3) - for obj1 in obj_list: - for obj2 in obj_list: - yield nose.tools.assert_equal, hash(obj1) == hash(obj2), \ - np.all(obj1 == obj2) - - d1 = {1: arr1, 2: arr1} - d2 = {1: arr2, 2: arr2} - yield nose.tools.assert_equal, hash(d1), hash(d2) - - d3 = {1: arr2, 2: arr3} - yield nose.tools.assert_not_equal, hash(d1), hash(d3) - - yield nose.tools.assert_not_equal, hash(arr1), hash(arr1.T) - - -@with_numpy -def test_hash_memmap(): - """ Check that memmap and arrays hash identically if coerce_mmap is - True. - """ - filename = tempfile.mktemp() - try: - m = np.memmap(filename, shape=(10, 10), mode='w+') - a = np.asarray(m) - for coerce_mmap in (False, True): - yield (nose.tools.assert_equal, - hash(a, coerce_mmap=coerce_mmap) - == hash(m, coerce_mmap=coerce_mmap), - coerce_mmap) - finally: - if 'm' in locals(): - del m - # Force a garbage-collection cycle, to be certain that the - # object is delete, and we don't run in a problem under - # Windows with a file handle still open. - gc.collect() - try: - os.unlink(filename) - except OSError, e: - # Under windows, some files don't get erased. - if not os.name == 'nt': - raise e - - -@with_numpy -def test_hash_numpy_performance(): - """ Check the performance of hashing numpy arrays: - - In [22]: a = np.random.random(1000000) - - In [23]: %timeit hashlib.md5(a).hexdigest() - 100 loops, best of 3: 20.7 ms per loop - - In [24]: %timeit hashlib.md5(pickle.dumps(a, protocol=2)).hexdigest() - 1 loops, best of 3: 73.1 ms per loop - - In [25]: %timeit hashlib.md5(cPickle.dumps(a, protocol=2)).hexdigest() - 10 loops, best of 3: 53.9 ms per loop - - In [26]: %timeit hash(a) - 100 loops, best of 3: 20.8 ms per loop - """ - rnd = np.random.RandomState(0) - a = rnd.random_sample(1000000) - md5_hash = lambda x: hashlib.md5(np.getbuffer(x)).hexdigest() - - relative_diff = relative_time(md5_hash, hash, a) - yield nose.tools.assert_true, relative_diff < 0.1 - - # Check that hashing an tuple of 3 arrays takes approximately - # 3 times as much as hashing one array - time_hashlib = 3 * time_func(md5_hash, a) - time_hash = time_func(hash, (a, a, a)) - relative_diff = 0.5 * (abs(time_hash - time_hashlib) - / (time_hash + time_hashlib)) - - yield nose.tools.assert_true, relative_diff < 0.2 - - -def test_bound_methods_hash(): - """ Make sure that calling the same method on two different instances - of the same class does resolve to the same hashes. - """ - a = Klass() - b = Klass() - nose.tools.assert_equal(hash(filter_args(a.f, [], (1, ))), - hash(filter_args(b.f, [], (1, )))) - - -@nose.tools.with_setup(test_memory_setup_func, test_memory_teardown_func) -def test_bound_cached_methods_hash(): - """ Make sure that calling the same _cached_ method on two different - instances of the same class does resolve to the same hashes. - """ - a = KlassWithCachedMethod() - b = KlassWithCachedMethod() - nose.tools.assert_equal(hash(filter_args(a.f.func, [], (1, ))), - hash(filter_args(b.f.func, [], (1, )))) diff --git a/sklearn/externals/joblib/test/test_logger.py b/sklearn/externals/joblib/test/test_logger.py deleted file mode 100644 index c4e0f7b1c414d..0000000000000 --- a/sklearn/externals/joblib/test/test_logger.py +++ /dev/null @@ -1,66 +0,0 @@ -""" -Test the logger module. -""" - -# Author: Gael Varoquaux -# Copyright (c) 2009 Gael Varoquaux -# License: BSD Style, 3 clauses. - -import shutil -import os -import sys -import StringIO -from tempfile import mkdtemp -import re - -import nose - -from ..logger import PrintTime - - -############################################################################### -# Test fixtures -env = dict() - - -def setup(): - """ Test setup. - """ - cachedir = mkdtemp() - if os.path.exists(cachedir): - shutil.rmtree(cachedir) - env['dir'] = cachedir - - -def teardown(): - """ Test teardown. - """ - #return True - shutil.rmtree(env['dir']) - - -############################################################################### -# Tests -def test_print_time(): - """ A simple smoke test for PrintTime. - """ - try: - orig_stderr = sys.stderr - sys.stderr = StringIO.StringIO() - print_time = PrintTime(logfile=os.path.join(env['dir'], 'test.log')) - print_time('Foo') - # Create a second time, to smoke test log rotation. - print_time = PrintTime(logfile=os.path.join(env['dir'], 'test.log')) - print_time('Foo') - # And a third time - print_time = PrintTime(logfile=os.path.join(env['dir'], 'test.log')) - print_time('Foo') - printed_text = sys.stderr.getvalue() - # Use regexps to be robust to time variations - match = r"Foo: 0\..s, 0\.0min\nFoo: 0\..s, 0.0min\nFoo: " + \ - r".\..s, 0.0min\n" - if not re.match(match, printed_text): - raise AssertionError('Excepted %s, got %s' % - (match, printed_text)) - finally: - sys.stderr = orig_stderr diff --git a/sklearn/externals/joblib/test/test_memory.py b/sklearn/externals/joblib/test/test_memory.py deleted file mode 100644 index 356f366cbc50c..0000000000000 --- a/sklearn/externals/joblib/test/test_memory.py +++ /dev/null @@ -1,442 +0,0 @@ -""" -Test the memory module. -""" - -# Author: Gael Varoquaux -# Copyright (c) 2009 Gael Varoquaux -# License: BSD Style, 3 clauses. - -from __future__ import with_statement - -import shutil -import os -from tempfile import mkdtemp -import pickle -import warnings - -import nose - -from ..memory import Memory, MemorizedFunc -from .common import with_numpy, np - - -############################################################################### -# Module-level variables for the tests -def f(x, y=1): - """ A module-level function for testing purposes. - """ - return x ** 2 + y - - -############################################################################### -# Test fixtures -env = dict() - - -def setup_module(): - """ Test setup. - """ - cachedir = mkdtemp() - #cachedir = 'foobar' - env['dir'] = cachedir - if os.path.exists(cachedir): - shutil.rmtree(cachedir) - # Don't make the cachedir, Memory should be able to do that on the fly - print 80 * '_' - print 'test_memory setup' - print 80 * '_' - - -def _rmtree_onerror(func, path, excinfo): - print '!' * 79 - print 'os function failed:', repr(func) - print 'file to be removed:', path - print 'exception was:', excinfo[1] - print '!' * 79 - - -def teardown_module(): - """ Test teardown. - """ - shutil.rmtree(env['dir'], False, _rmtree_onerror) - print 80 * '_' - print 'test_memory teardown' - print 80 * '_' - - -############################################################################### -# Helper function for the tests -def check_identity_lazy(func, accumulator): - """ Given a function and an accumulator (a list that grows every - time the function is called, check that the function can be - decorated by memory to be a lazy identity. - """ - # Call each function with several arguments, and check that it is - # evaluated only once per argument. - memory = Memory(cachedir=env['dir'], verbose=0) - memory.clear(warn=False) - func = memory.cache(func) - for i in range(3): - for _ in range(2): - yield nose.tools.assert_equal, func(i), i - yield nose.tools.assert_equal, len(accumulator), i + 1 - - -############################################################################### -# Tests -def test_memory_integration(): - """ Simple test of memory lazy evaluation. - """ - accumulator = list() - # Rmk: this function has the same name than a module-level function, - # thus it serves as a test to see that both are identified - # as different. - - def f(l): - accumulator.append(1) - return l - - for test in check_identity_lazy(f, accumulator): - yield test - - # Now test clearing - for compress in (False, True): - memory = Memory(cachedir=env['dir'], verbose=0, compress=compress) - # First clear the cache directory, to check that our code can - # handle that - # NOTE: this line would raise an exception, as the database file is - # still open; we ignore the error since we want to test what happens if - # the directory disappears - shutil.rmtree(env['dir'], ignore_errors=True) - g = memory.cache(f) - g(1) - g.clear(warn=False) - current_accumulator = len(accumulator) - out = g(1) - yield nose.tools.assert_equal, len(accumulator), \ - current_accumulator + 1 - # Also, check that Memory.eval works similarly - yield nose.tools.assert_equal, memory.eval(f, 1), out - yield nose.tools.assert_equal, len(accumulator), \ - current_accumulator + 1 - - # Now do a smoke test with a function defined in __main__, as the name - # mangling rules are more complex - f.__module__ = '__main__' - memory = Memory(cachedir=env['dir'], verbose=0) - memory.cache(f)(1) - - -def test_no_memory(): - """ Test memory with cachedir=None: no memoize """ - accumulator = list() - - def ff(l): - accumulator.append(1) - return l - - mem = Memory(cachedir=None, verbose=0) - gg = mem.cache(ff) - for _ in range(4): - current_accumulator = len(accumulator) - gg(1) - yield nose.tools.assert_equal, len(accumulator), \ - current_accumulator + 1 - - -def test_memory_kwarg(): - " Test memory with a function with keyword arguments." - accumulator = list() - - def g(l=None, m=1): - accumulator.append(1) - return l - - for test in check_identity_lazy(g, accumulator): - yield test - - memory = Memory(cachedir=env['dir'], verbose=0) - g = memory.cache(g) - # Smoke test with an explicit keyword argument: - nose.tools.assert_equal(g(l=30, m=2), 30) - - -def test_memory_lambda(): - " Test memory with a function with a lambda." - accumulator = list() - - def helper(x): - """ A helper function to define l as a lambda. - """ - accumulator.append(1) - return x - - l = lambda x: helper(x) - - for test in check_identity_lazy(l, accumulator): - yield test - - -def test_memory_name_collision(): - " Check that name collisions with functions will raise warnings" - memory = Memory(cachedir=env['dir'], verbose=0) - - @memory.cache - def name_collision(x): - """ A first function called name_collision - """ - return x - - a = name_collision - - @memory.cache - def name_collision(x): - """ A second function called name_collision - """ - return x - - b = name_collision - - if not hasattr(warnings, 'catch_warnings'): - # catch_warnings is new in Python 2.6 - return - - with warnings.catch_warnings(record=True) as w: - # Cause all warnings to always be triggered. - warnings.simplefilter("always") - a(1) - b(1) - - yield nose.tools.assert_equal, len(w), 1 - yield nose.tools.assert_true, "collision" in str(w[-1].message) - - -def test_memory_warning_lambda_collisions(): - " Check that multiple use of lambda will raise collisions" - memory = Memory(cachedir=env['dir'], verbose=0) - a = lambda x: x - a = memory.cache(a) - b = lambda x: x + 1 - b = memory.cache(b) - - if not hasattr(warnings, 'catch_warnings'): - # catch_warnings is new in Python 2.6 - return - - with warnings.catch_warnings(record=True) as w: - # Cause all warnings to always be triggered. - warnings.simplefilter("always") - a(1) - b(1) - - yield nose.tools.assert_equal, len(w), 2 - yield nose.tools.assert_true, "collision" in str(w[-1].message) - yield nose.tools.assert_true, "collision" in str(w[-2].message) - - -def test_memory_warning_collision_detection(): - """ Check that collisions impossible to detect will raise appropriate - warnings. - """ - memory = Memory(cachedir=env['dir'], verbose=0) - a = eval('lambda x: x') - a = memory.cache(a) - b = eval('lambda x: x+1') - b = memory.cache(b) - - if not hasattr(warnings, 'catch_warnings'): - # catch_warnings is new in Python 2.6 - return - - with warnings.catch_warnings(record=True) as w: - # Cause all warnings to always be triggered. - warnings.simplefilter("always") - a(1) - b(1) - - yield nose.tools.assert_equal, len(w), 1 - yield nose.tools.assert_true, \ - "cannot detect" in str(w[-1].message).lower() - - -def test_memory_partial(): - " Test memory with functools.partial." - accumulator = list() - - def func(x, y): - """ A helper function to define l as a lambda. - """ - accumulator.append(1) - return y - - import functools - function = functools.partial(func, 1) - - for test in check_identity_lazy(function, accumulator): - yield test - - -def test_memory_eval(): - " Smoke test memory with a function with a function defined in an eval." - memory = Memory(cachedir=env['dir'], verbose=0) - - m = eval('lambda x: x') - mm = memory.cache(m) - - yield nose.tools.assert_equal, 1, mm(1) - - -def count_and_append(x=[]): - """ A function with a side effect in its arguments. - - Return the lenght of its argument and append one element. - """ - len_x = len(x) - x.append(None) - return len_x - - -def test_argument_change(): - """ Check that if a function has a side effect in its arguments, it - should use the hash of changing arguments. - """ - mem = Memory(cachedir=env['dir'], verbose=0) - func = mem.cache(count_and_append) - # call the function for the first time, is should cache it with - # argument x=[] - assert func() == 0 - # the second time the argument is x=[None], which is not cached - # yet, so the functions should be called a second time - assert func() == 1 - - -@with_numpy -def test_memory_numpy(): - " Test memory with a function with numpy arrays." - # Check with memmapping and without. - for mmap_mode in (None, 'r'): - accumulator = list() - - def n(l=None): - accumulator.append(1) - return l - - memory = Memory(cachedir=env['dir'], mmap_mode=mmap_mode, - verbose=0) - memory.clear(warn=False) - cached_n = memory.cache(n) - - rnd = np.random.RandomState(0) - for i in range(3): - a = rnd.random_sample((10, 10)) - for _ in range(3): - yield nose.tools.assert_true, np.all(cached_n(a) == a) - yield nose.tools.assert_equal, len(accumulator), i + 1 - - -def test_memory_exception(): - """ Smoketest the exception handling of Memory. - """ - memory = Memory(cachedir=env['dir'], verbose=0) - - class MyException(Exception): - pass - - @memory.cache - def h(exc=0): - if exc: - raise MyException - - # Call once, to initialise the cache - h() - - for _ in range(3): - # Call 3 times, to be sure that the Exception is always raised - yield nose.tools.assert_raises, MyException, h, 1 - - -def test_memory_ignore(): - " Test the ignore feature of memory " - memory = Memory(cachedir=env['dir'], verbose=0) - accumulator = list() - - @memory.cache(ignore=['y']) - def z(x, y=1): - accumulator.append(1) - - yield nose.tools.assert_equal, z.ignore, ['y'] - - z(0, y=1) - yield nose.tools.assert_equal, len(accumulator), 1 - z(0, y=1) - yield nose.tools.assert_equal, len(accumulator), 1 - z(0, y=2) - yield nose.tools.assert_equal, len(accumulator), 1 - - -def test_func_dir(): - """ Test the creation of the memory cache directory for the function. - """ - memory = Memory(cachedir=env['dir'], verbose=0) - path = __name__.split('.') - path.append('f') - path = os.path.join(env['dir'], 'joblib', *path) - - g = memory.cache(f) - # Test that the function directory is created on demand - yield nose.tools.assert_equal, g._get_func_dir(), path - yield nose.tools.assert_true, os.path.exists(path) - - # Test that the code is stored. - yield nose.tools.assert_false, \ - g._check_previous_func_code() - yield nose.tools.assert_true, \ - os.path.exists(os.path.join(path, 'func_code.py')) - yield nose.tools.assert_true, \ - g._check_previous_func_code() - - # Test the robustness to failure of loading previous results. - dir, _ = g.get_output_dir(1) - a = g(1) - yield nose.tools.assert_true, os.path.exists(dir) - os.remove(os.path.join(dir, 'output.pkl')) - yield nose.tools.assert_equal, a, g(1) - - -def test_persistence(): - """ Test the memorized functions can be pickled and restored. - """ - memory = Memory(cachedir=env['dir'], verbose=0) - g = memory.cache(f) - output = g(1) - - h = pickle.loads(pickle.dumps(g)) - - output_dir, _ = g.get_output_dir(1) - yield nose.tools.assert_equal, output, h.load_output(output_dir) - memory2 = pickle.loads(pickle.dumps(memory)) - yield nose.tools.assert_equal, memory.cachedir, memory2.cachedir - - # Smoke test that pickling a memory with cachedir=None works - memory = Memory(cachedir=None, verbose=0) - pickle.loads(pickle.dumps(memory)) - - -def test_format_signature(): - """ Test the signature formatting. - """ - func = MemorizedFunc(f, cachedir=env['dir']) - path, sgn = func.format_signature(f, range(10)) - yield nose.tools.assert_equal, \ - sgn, \ - 'f([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])' - path, sgn = func.format_signature(f, range(10), y=range(10)) - yield nose.tools.assert_equal, \ - sgn, \ - 'f([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], y=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])' - - -@with_numpy -def test_format_signature_numpy(): - """ Test the format signature formatting with numpy. - """ diff --git a/sklearn/externals/joblib/test/test_my_exceptions.py b/sklearn/externals/joblib/test/test_my_exceptions.py deleted file mode 100644 index 0fed0107e469a..0000000000000 --- a/sklearn/externals/joblib/test/test_my_exceptions.py +++ /dev/null @@ -1,14 +0,0 @@ -""" -Test my automatically generate exceptions -""" -from nose.tools import assert_true - -from .. import my_exceptions - - -def test_inheritance(): - assert_true(isinstance(my_exceptions.JoblibNameError(), NameError)) - assert_true(isinstance(my_exceptions.JoblibNameError(), - my_exceptions.JoblibException)) - assert_true(my_exceptions.JoblibNameError is - my_exceptions._mk_exception(NameError)[0]) diff --git a/sklearn/externals/joblib/test/test_numpy_pickle.py b/sklearn/externals/joblib/test/test_numpy_pickle.py deleted file mode 100644 index f5d34cc136479..0000000000000 --- a/sklearn/externals/joblib/test/test_numpy_pickle.py +++ /dev/null @@ -1,238 +0,0 @@ -""" -Test the numpy pickler as a replacement of the standard pickler. - -""" - -from tempfile import mkdtemp -import copy -import shutil -import os -import random - -import nose - -from .common import np, with_numpy - -# numpy_pickle is not a drop-in replacement of pickle, as it takes -# filenames instead of open files as arguments. -from .. import numpy_pickle - -############################################################################### -# Define a list of standard types. -# Borrowed from dill, initial author: Micheal McKerns: -# http://dev.danse.us/trac/pathos/browser/dill/dill_test2.py - -typelist = [] - -# testing types -_none = None -typelist.append(_none) -_type = type -typelist.append(_type) -_bool = bool(1) -typelist.append(_bool) -_int = int(1) -typelist.append(_int) -_long = long(1) -typelist.append(_long) -_float = float(1) -typelist.append(_float) -_complex = complex(1) -typelist.append(_complex) -_string = str(1) -typelist.append(_string) -_unicode = unicode(1) -typelist.append(_unicode) -_tuple = () -typelist.append(_tuple) -_list = [] -typelist.append(_list) -_dict = {} -typelist.append(_dict) -_file = file -typelist.append(_file) -_buffer = buffer -typelist.append(_buffer) -_builtin = len -typelist.append(_builtin) - - -def _function(x): - yield x - - -class _class: - def _method(self): - pass - - -class _newclass(object): - def _method(self): - pass - - -typelist.append(_function) -typelist.append(_class) -typelist.append(_newclass) # -_instance = _class() -typelist.append(_instance) -_object = _newclass() -typelist.append(_object) # - - -############################################################################### -# Test fixtures - -env = dict() - - -def setup_module(): - """ Test setup. - """ - env['dir'] = mkdtemp() - env['filename'] = os.path.join(env['dir'], 'test.pkl') - print 80 * '_' - print 'setup numpy_pickle' - print 80 * '_' - - -def teardown_module(): - """ Test teardown. - """ - shutil.rmtree(env['dir']) - #del env['dir'] - #del env['filename'] - print 80 * '_' - print 'teardown numpy_pickle' - print 80 * '_' - - -############################################################################### -# Tests - -def test_standard_types(): - # Test pickling and saving with standard types. - filename = env['filename'] - for compress in [0, 1]: - for member in typelist: - # Change the file name to avoid side effects between tests - this_filename = filename + str(random.randint(0, 1000)) - numpy_pickle.dump(member, this_filename, compress=compress) - _member = numpy_pickle.load(this_filename) - # We compare the pickled instance to the reloaded one only if it - # can be compared to a copied one - if member == copy.deepcopy(member): - yield nose.tools.assert_equal, member, _member - - -def test_value_error(): - # Test inverting the input arguments to dump - nose.tools.assert_raises(ValueError, numpy_pickle.dump, 'foo', - dict()) - - -@with_numpy -def test_numpy_persistence(): - filename = env['filename'] - rnd = np.random.RandomState(0) - a = rnd.random_sample((10, 2)) - for compress, cache_size in ((0, 0), (1, 0), (1, 10)): - # We use 'a.T' to have a non C-contiguous array. - for index, obj in enumerate(((a,), (a.T,), (a, a), [a, a, a])): - # Change the file name to avoid side effects between tests - this_filename = filename + str(random.randint(0, 1000)) - filenames = numpy_pickle.dump(obj, this_filename, - compress=compress, - cache_size=cache_size) - # Check that one file was created per array - if not compress: - nose.tools.assert_equal(len(filenames), len(obj) + 1) - # Check that these files do exist - for file in filenames: - nose.tools.assert_true( - os.path.exists(os.path.join(env['dir'], file))) - - # Unpickle the object - obj_ = numpy_pickle.load(this_filename) - # Check that the items are indeed arrays - for item in obj_: - nose.tools.assert_true(isinstance(item, np.ndarray)) - # And finally, check that all the values are equal. - nose.tools.assert_true(np.all(np.array(obj) == - np.array(obj_))) - - # Now test with array subclasses - for obj in ( - np.matrix(np.zeros(10)), - np.core.multiarray._reconstruct(np.memmap, (), np.float) - ): - this_filename = filename + str(random.randint(0, 1000)) - filenames = numpy_pickle.dump(obj, this_filename, - compress=compress, - cache_size=cache_size) - obj_ = numpy_pickle.load(this_filename) - if (type(obj) is not np.memmap - and hasattr(obj, '__array_prepare__')): - # We don't reconstruct memmaps - nose.tools.assert_true(isinstance(obj_, type(obj))) - - # Finally smoke test the warning in case of compress + mmap_mode - this_filename = filename + str(random.randint(0, 1000)) - numpy_pickle.dump(a, this_filename, compress=1) - numpy_pickle.load(this_filename, mmap_mode='r') - - -@with_numpy -def test_memmap_persistence(): - rnd = np.random.RandomState(0) - a = rnd.random_sample(10) - filename = env['filename'] + str(random.randint(0, 1000)) - numpy_pickle.dump(a, filename) - b = numpy_pickle.load(filename, mmap_mode='r') - if np.__version__ >= '1.3': - yield nose.tools.assert_true, isinstance(b, np.memmap) - - -@with_numpy -def test_masked_array_persistence(): - # The special-case picker fails, because saving masked_array - # not implemented, but it just delegates to the standard pickler. - rnd = np.random.RandomState(0) - a = rnd.random_sample(10) - a = np.ma.masked_greater(a, 0.5) - filename = env['filename'] + str(random.randint(0, 1000)) - numpy_pickle.dump(a, filename) - b = numpy_pickle.load(filename, mmap_mode='r') - nose.tools.assert_true(isinstance(b, np.ma.masked_array)) - - -def test_z_file(): - # Test saving and loading data with Zfiles - filename = env['filename'] + str(random.randint(0, 1000)) - data = 'Foo, \n Bar, baz, \n\nfoobar' - numpy_pickle.write_zfile(file(filename, 'wb'), data) - data_read = numpy_pickle.read_zfile(file(filename, 'rb')) - nose.tools.assert_equal(data, data_read) - -################################################################################ -# Test dumping array subclasses -if np is not None: - - class SubArray(np.ndarray): - - def __reduce__(self): - return (_load_sub_array, (np.asarray(self), )) - - - def _load_sub_array(arr): - d = SubArray(arr.shape) - d[:] = arr - return d - -@with_numpy -def test_numpy_subclass(): - filename = env['filename'] - a = SubArray((10,)) - numpy_pickle.dump(a, filename) - c = numpy_pickle.load(filename) - nose.tools.assert_true(isinstance(c, SubArray)) diff --git a/sklearn/externals/joblib/test/test_parallel.py b/sklearn/externals/joblib/test/test_parallel.py deleted file mode 100644 index 064a81eeeeb2a..0000000000000 --- a/sklearn/externals/joblib/test/test_parallel.py +++ /dev/null @@ -1,242 +0,0 @@ -""" -Test the parallel module. -""" - -# Author: Gael Varoquaux -# Copyright (c) 2010-2011 Gael Varoquaux -# License: BSD Style, 3 clauses. - -import time -import sys -try: - import cPickle as pickle - PickleError = TypeError -except: - import pickle - PickleError = pickle.PicklingError -try: - from io import BytesIO -except: - from cStringIO import StringIO as BytesIO - -if sys.version_info[0] == 3: - PickleError = pickle.PicklingError - -from ..parallel import Parallel, delayed, SafeFunction, WorkerInterrupt, \ - multiprocessing, cpu_count -from ..my_exceptions import JoblibException - -import nose - - -############################################################################### - -def division(x, y): - return x / y - - -def square(x): - return x ** 2 - - -def exception_raiser(x): - if x == 7: - raise ValueError - return x - - -def interrupt_raiser(x): - time.sleep(.05) - raise KeyboardInterrupt - - -def f(x, y=0, z=0): - """ A module-level function so that it can be spawn with - multiprocessing. - """ - return x ** 2 + y + z - - -############################################################################### -def test_cpu_count(): - assert cpu_count() > 0 - - -############################################################################### -# Test parallel -def test_simple_parallel(): - X = range(5) - for n_jobs in (1, 2, -1, -2): - yield (nose.tools.assert_equal, [square(x) for x in X], - Parallel(n_jobs=-1)( - delayed(square)(x) for x in X)) - try: - # To smoke-test verbosity, we capture stdout - orig_stdout = sys.stdout - sys.stdout = BytesIO() - orig_stderr = sys.stdout - sys.stderr = BytesIO() - for verbose in (2, 11, 100): - Parallel(n_jobs=-1, verbose=verbose)( - delayed(square)(x) for x in X) - Parallel(n_jobs=1, verbose=verbose)( - delayed(square)(x) for x in X) - Parallel(n_jobs=2, verbose=verbose, pre_dispatch=2)( - delayed(square)(x) for x in X) - except Exception: - # Cannot use 'except as' to maintain Python 2.5 compatibility - e = sys.exc_info()[1] - print sys.stdout.getvalue() - print sys.stderr.getvalue() - raise e - finally: - sys.stdout = orig_stdout - sys.stderr = orig_stderr - - -def nested_loop(): - Parallel(n_jobs=2)(delayed(square)(.01) for _ in range(2)) - - -def test_nested_loop(): - Parallel(n_jobs=2)(delayed(nested_loop)() for _ in range(2)) - - -def test_parallel_kwargs(): - """ Check the keyword argument processing of pmap. - """ - lst = range(10) - for n_jobs in (1, 4): - yield (nose.tools.assert_equal, - [f(x, y=1) for x in lst], - Parallel(n_jobs=n_jobs)(delayed(f)(x, y=1) for x in lst) - ) - - -def test_parallel_pickling(): - """ Check that pmap captures the errors when it is passed an object - that cannot be pickled. - """ - def g(x): - return x ** 2 - nose.tools.assert_raises(PickleError, - Parallel(), - (delayed(g)(x) for x in range(10)) - ) - - -def test_error_capture(): - """ Check that error are captured, and that correct exceptions - are raised. - """ - if multiprocessing is not None: - # A JoblibException will be raised only if there is indeed - # multiprocessing - nose.tools.assert_raises(JoblibException, - Parallel(n_jobs=2), - [delayed(division)(x, y) for x, y in zip((0, 1), (1, 0))], - ) - nose.tools.assert_raises(WorkerInterrupt, - Parallel(n_jobs=2), - [delayed(interrupt_raiser)(x) for x in (1, 0)], - ) - else: - nose.tools.assert_raises(KeyboardInterrupt, - Parallel(n_jobs=2), - [delayed(interrupt_raiser)(x) for x in (1, 0)], - ) - nose.tools.assert_raises(ZeroDivisionError, - Parallel(n_jobs=2), - [delayed(division)(x, y) for x, y in zip((0, 1), (1, 0))], - ) - try: - ex = JoblibException - Parallel(n_jobs=1)( - delayed(division)(x, y) for x, y in zip((0, 1), (1, 0))) - except Exception: - # Cannot use 'except as' to maintain Python 2.5 compatibility - ex = sys.exc_info()[1] - nose.tools.assert_false(isinstance(ex, JoblibException)) - - -class Counter(object): - def __init__(self, list1, list2): - self.list1 = list1 - self.list2 = list2 - - def __call__(self, i): - self.list1.append(i) - nose.tools.assert_equal(len(self.list1), len(self.list2)) - - -def consumer(queue, item): - queue.append('Consumed %s' % item) - - -def test_dispatch_one_job(): - """ Test that with only one job, Parallel does act as a iterator. - """ - queue = list() - - def producer(): - for i in range(6): - queue.append('Produced %i' % i) - yield i - - Parallel(n_jobs=1)(delayed(consumer)(queue, x) for x in producer()) - nose.tools.assert_equal(queue, - ['Produced 0', 'Consumed 0', - 'Produced 1', 'Consumed 1', - 'Produced 2', 'Consumed 2', - 'Produced 3', 'Consumed 3', - 'Produced 4', 'Consumed 4', - 'Produced 5', 'Consumed 5'] - ) - nose.tools.assert_equal(len(queue), 12) - - -def test_dispatch_multiprocessing(): - """ Check that using pre_dispatch Parallel does indeed dispatch items - lazily. - """ - if multiprocessing is None: - return - manager = multiprocessing.Manager() - queue = manager.list() - - def producer(): - for i in range(6): - queue.append('Produced %i' % i) - yield i - - Parallel(n_jobs=2, pre_dispatch=3)(delayed(consumer)(queue, i) - for i in producer()) - nose.tools.assert_equal(list(queue)[:4], - ['Produced 0', 'Produced 1', 'Produced 2', - 'Consumed 0', ]) - nose.tools.assert_equal(len(queue), 12) - - -def test_exception_dispatch(): - "Make sure that exception raised during dispatch are indeed captured" - nose.tools.assert_raises( - ValueError, - Parallel(n_jobs=6, pre_dispatch=16, verbose=0), - (delayed(exception_raiser)(i) for i in range(30)), - ) - - -############################################################################### -# Test helpers -def test_joblib_exception(): - # Smoke-test the custom exception - e = JoblibException('foobar') - # Test the repr - repr(e) - # Test the pickle - pickle.dumps(e) - - -def test_safe_function(): - safe_division = SafeFunction(division) - nose.tools.assert_raises(JoblibException, safe_division, 1, 0) diff --git a/sklearn/externals/setup.py b/sklearn/externals/setup.py index bc8a0e774f9cf..936f0327226d6 100644 --- a/sklearn/externals/setup.py +++ b/sklearn/externals/setup.py @@ -5,6 +5,5 @@ def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('externals', parent_package, top_path) config.add_subpackage('joblib') - config.add_subpackage('joblib/test') return config diff --git a/sklearn/externals/six.py b/sklearn/externals/six.py new file mode 100644 index 0000000000000..85898ec71275f --- /dev/null +++ b/sklearn/externals/six.py @@ -0,0 +1,577 @@ +"""Utilities for writing code that runs on Python 2 and 3""" + +# Copyright (c) 2010-2013 Benjamin Peterson +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import operator +import sys +import types + +__author__ = "Benjamin Peterson " +__version__ = "1.4.1" + + +# Useful for very coarse version differentiation. +PY2 = sys.version_info[0] == 2 +PY3 = sys.version_info[0] == 3 + +if PY3: + string_types = str, + integer_types = int, + class_types = type, + text_type = str + binary_type = bytes + + MAXSIZE = sys.maxsize +else: + string_types = basestring, + integer_types = (int, long) + class_types = (type, types.ClassType) + text_type = unicode + binary_type = str + + if sys.platform.startswith("java"): + # Jython always uses 32 bits. + MAXSIZE = int((1 << 31) - 1) + else: + # It's possible to have sizeof(long) != sizeof(Py_ssize_t). + class X(object): + def __len__(self): + return 1 << 31 + try: + len(X()) + except OverflowError: + # 32-bit + MAXSIZE = int((1 << 31) - 1) + else: + # 64-bit + MAXSIZE = int((1 << 63) - 1) + del X + + +def _add_doc(func, doc): + """Add documentation to a function.""" + func.__doc__ = doc + + +def _import_module(name): + """Import module, returning the module after the last dot.""" + __import__(name) + return sys.modules[name] + + +class _LazyDescr(object): + + def __init__(self, name): + self.name = name + + def __get__(self, obj, tp): + result = self._resolve() + setattr(obj, self.name, result) + # This is a bit ugly, but it avoids running this again. + delattr(tp, self.name) + return result + + +class MovedModule(_LazyDescr): + + def __init__(self, name, old, new=None): + super(MovedModule, self).__init__(name) + if PY3: + if new is None: + new = name + self.mod = new + else: + self.mod = old + + def _resolve(self): + return _import_module(self.mod) + + +class MovedAttribute(_LazyDescr): + + def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): + super(MovedAttribute, self).__init__(name) + if PY3: + if new_mod is None: + new_mod = name + self.mod = new_mod + if new_attr is None: + if old_attr is None: + new_attr = name + else: + new_attr = old_attr + self.attr = new_attr + else: + self.mod = old_mod + if old_attr is None: + old_attr = name + self.attr = old_attr + + def _resolve(self): + module = _import_module(self.mod) + return getattr(module, self.attr) + + + +class _MovedItems(types.ModuleType): + """Lazy loading of moved objects""" + + +_moved_attributes = [ + MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), + MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), + MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), + MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), + MovedAttribute("map", "itertools", "builtins", "imap", "map"), + MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("reload_module", "__builtin__", "imp", "reload"), + MovedAttribute("reduce", "__builtin__", "functools"), + MovedAttribute("StringIO", "StringIO", "io"), + MovedAttribute("UserString", "UserString", "collections"), + MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), + MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), + + MovedModule("builtins", "__builtin__"), + MovedModule("configparser", "ConfigParser"), + MovedModule("copyreg", "copy_reg"), + MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), + MovedModule("http_cookies", "Cookie", "http.cookies"), + MovedModule("html_entities", "htmlentitydefs", "html.entities"), + MovedModule("html_parser", "HTMLParser", "html.parser"), + MovedModule("http_client", "httplib", "http.client"), + MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), + MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), + MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), + MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), + MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), + MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), + MovedModule("cPickle", "cPickle", "pickle"), + MovedModule("queue", "Queue"), + MovedModule("reprlib", "repr"), + MovedModule("socketserver", "SocketServer"), + MovedModule("tkinter", "Tkinter"), + MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), + MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), + MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), + MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), + MovedModule("tkinter_tix", "Tix", "tkinter.tix"), + MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), + MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), + MovedModule("tkinter_colorchooser", "tkColorChooser", + "tkinter.colorchooser"), + MovedModule("tkinter_commondialog", "tkCommonDialog", + "tkinter.commondialog"), + MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), + MovedModule("tkinter_font", "tkFont", "tkinter.font"), + MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), + MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", + "tkinter.simpledialog"), + MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), + MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), + MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), + MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), + MovedModule("winreg", "_winreg"), +] +for attr in _moved_attributes: + setattr(_MovedItems, attr.name, attr) +del attr + +moves = sys.modules[__name__ + ".moves"] = _MovedItems(__name__ + ".moves") + + + +class Module_six_moves_urllib_parse(types.ModuleType): + """Lazy loading of moved objects in six.moves.urllib_parse""" + + +_urllib_parse_moved_attributes = [ + MovedAttribute("ParseResult", "urlparse", "urllib.parse"), + MovedAttribute("parse_qs", "urlparse", "urllib.parse"), + MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), + MovedAttribute("urldefrag", "urlparse", "urllib.parse"), + MovedAttribute("urljoin", "urlparse", "urllib.parse"), + MovedAttribute("urlparse", "urlparse", "urllib.parse"), + MovedAttribute("urlsplit", "urlparse", "urllib.parse"), + MovedAttribute("urlunparse", "urlparse", "urllib.parse"), + MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), + MovedAttribute("quote", "urllib", "urllib.parse"), + MovedAttribute("quote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote", "urllib", "urllib.parse"), + MovedAttribute("unquote_plus", "urllib", "urllib.parse"), + MovedAttribute("urlencode", "urllib", "urllib.parse"), +] +for attr in _urllib_parse_moved_attributes: + setattr(Module_six_moves_urllib_parse, attr.name, attr) +del attr + +sys.modules[__name__ + ".moves.urllib_parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse") +sys.modules[__name__ + ".moves.urllib.parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib.parse") + + +class Module_six_moves_urllib_error(types.ModuleType): + """Lazy loading of moved objects in six.moves.urllib_error""" + + +_urllib_error_moved_attributes = [ + MovedAttribute("URLError", "urllib2", "urllib.error"), + MovedAttribute("HTTPError", "urllib2", "urllib.error"), + MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), +] +for attr in _urllib_error_moved_attributes: + setattr(Module_six_moves_urllib_error, attr.name, attr) +del attr + +sys.modules[__name__ + ".moves.urllib_error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib_error") +sys.modules[__name__ + ".moves.urllib.error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib.error") + + +class Module_six_moves_urllib_request(types.ModuleType): + """Lazy loading of moved objects in six.moves.urllib_request""" + + +_urllib_request_moved_attributes = [ + MovedAttribute("urlopen", "urllib2", "urllib.request"), + MovedAttribute("install_opener", "urllib2", "urllib.request"), + MovedAttribute("build_opener", "urllib2", "urllib.request"), + MovedAttribute("pathname2url", "urllib", "urllib.request"), + MovedAttribute("url2pathname", "urllib", "urllib.request"), + MovedAttribute("getproxies", "urllib", "urllib.request"), + MovedAttribute("Request", "urllib2", "urllib.request"), + MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), + MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), + MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), + MovedAttribute("BaseHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), + MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), + MovedAttribute("FileHandler", "urllib2", "urllib.request"), + MovedAttribute("FTPHandler", "urllib2", "urllib.request"), + MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), + MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), + MovedAttribute("urlretrieve", "urllib", "urllib.request"), + MovedAttribute("urlcleanup", "urllib", "urllib.request"), + MovedAttribute("URLopener", "urllib", "urllib.request"), + MovedAttribute("FancyURLopener", "urllib", "urllib.request"), +] +for attr in _urllib_request_moved_attributes: + setattr(Module_six_moves_urllib_request, attr.name, attr) +del attr + +sys.modules[__name__ + ".moves.urllib_request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib_request") +sys.modules[__name__ + ".moves.urllib.request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib.request") + + +class Module_six_moves_urllib_response(types.ModuleType): + """Lazy loading of moved objects in six.moves.urllib_response""" + + +_urllib_response_moved_attributes = [ + MovedAttribute("addbase", "urllib", "urllib.response"), + MovedAttribute("addclosehook", "urllib", "urllib.response"), + MovedAttribute("addinfo", "urllib", "urllib.response"), + MovedAttribute("addinfourl", "urllib", "urllib.response"), +] +for attr in _urllib_response_moved_attributes: + setattr(Module_six_moves_urllib_response, attr.name, attr) +del attr + +sys.modules[__name__ + ".moves.urllib_response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib_response") +sys.modules[__name__ + ".moves.urllib.response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib.response") + + +class Module_six_moves_urllib_robotparser(types.ModuleType): + """Lazy loading of moved objects in six.moves.urllib_robotparser""" + + +_urllib_robotparser_moved_attributes = [ + MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), +] +for attr in _urllib_robotparser_moved_attributes: + setattr(Module_six_moves_urllib_robotparser, attr.name, attr) +del attr + +sys.modules[__name__ + ".moves.urllib_robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib_robotparser") +sys.modules[__name__ + ".moves.urllib.robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser") + + +class Module_six_moves_urllib(types.ModuleType): + """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" + parse = sys.modules[__name__ + ".moves.urllib_parse"] + error = sys.modules[__name__ + ".moves.urllib_error"] + request = sys.modules[__name__ + ".moves.urllib_request"] + response = sys.modules[__name__ + ".moves.urllib_response"] + robotparser = sys.modules[__name__ + ".moves.urllib_robotparser"] + + +sys.modules[__name__ + ".moves.urllib"] = Module_six_moves_urllib(__name__ + ".moves.urllib") + + +def add_move(move): + """Add an item to six.moves.""" + setattr(_MovedItems, move.name, move) + + +def remove_move(name): + """Remove item from six.moves.""" + try: + delattr(_MovedItems, name) + except AttributeError: + try: + del moves.__dict__[name] + except KeyError: + raise AttributeError("no such move, %r" % (name,)) + + +if PY3: + _meth_func = "__func__" + _meth_self = "__self__" + + _func_closure = "__closure__" + _func_code = "__code__" + _func_defaults = "__defaults__" + _func_globals = "__globals__" + + _iterkeys = "keys" + _itervalues = "values" + _iteritems = "items" + _iterlists = "lists" +else: + _meth_func = "im_func" + _meth_self = "im_self" + + _func_closure = "func_closure" + _func_code = "func_code" + _func_defaults = "func_defaults" + _func_globals = "func_globals" + + _iterkeys = "iterkeys" + _itervalues = "itervalues" + _iteritems = "iteritems" + _iterlists = "iterlists" + + +try: + advance_iterator = next +except NameError: + def advance_iterator(it): + return it.next() +next = advance_iterator + + +try: + callable = callable +except NameError: + def callable(obj): + return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) + + +if PY3: + def get_unbound_function(unbound): + return unbound + + create_bound_method = types.MethodType + + Iterator = object +else: + def get_unbound_function(unbound): + return unbound.im_func + + def create_bound_method(func, obj): + return types.MethodType(func, obj, obj.__class__) + + class Iterator(object): + + def next(self): + return type(self).__next__(self) + + callable = callable +_add_doc(get_unbound_function, + """Get the function out of a possibly unbound function""") + + +get_method_function = operator.attrgetter(_meth_func) +get_method_self = operator.attrgetter(_meth_self) +get_function_closure = operator.attrgetter(_func_closure) +get_function_code = operator.attrgetter(_func_code) +get_function_defaults = operator.attrgetter(_func_defaults) +get_function_globals = operator.attrgetter(_func_globals) + + +def iterkeys(d, **kw): + """Return an iterator over the keys of a dictionary.""" + return iter(getattr(d, _iterkeys)(**kw)) + +def itervalues(d, **kw): + """Return an iterator over the values of a dictionary.""" + return iter(getattr(d, _itervalues)(**kw)) + +def iteritems(d, **kw): + """Return an iterator over the (key, value) pairs of a dictionary.""" + return iter(getattr(d, _iteritems)(**kw)) + +def iterlists(d, **kw): + """Return an iterator over the (key, [values]) pairs of a dictionary.""" + return iter(getattr(d, _iterlists)(**kw)) + + +if PY3: + def b(s): + return s.encode("latin-1") + def u(s): + return s + unichr = chr + if sys.version_info[1] <= 1: + def int2byte(i): + return bytes((i,)) + else: + # This is about 2x faster than the implementation above on 3.2+ + int2byte = operator.methodcaller("to_bytes", 1, "big") + byte2int = operator.itemgetter(0) + indexbytes = operator.getitem + iterbytes = iter + import io + StringIO = io.StringIO + BytesIO = io.BytesIO +else: + def b(s): + return s + def u(s): + return unicode(s, "unicode_escape") + unichr = unichr + int2byte = chr + def byte2int(bs): + return ord(bs[0]) + def indexbytes(buf, i): + return ord(buf[i]) + def iterbytes(buf): + return (ord(byte) for byte in buf) + import StringIO + StringIO = BytesIO = StringIO.StringIO +_add_doc(b, """Byte literal""") +_add_doc(u, """Text literal""") + + +if PY3: + import builtins + exec_ = getattr(builtins, "exec") + + + def reraise(tp, value, tb=None): + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + + + print_ = getattr(builtins, "print") + del builtins + +else: + def exec_(_code_, _globs_=None, _locs_=None): + """Execute code in a namespace.""" + if _globs_ is None: + frame = sys._getframe(1) + _globs_ = frame.f_globals + if _locs_ is None: + _locs_ = frame.f_locals + del frame + elif _locs_ is None: + _locs_ = _globs_ + exec("""exec _code_ in _globs_, _locs_""") + + + exec_("""def reraise(tp, value, tb=None): + raise tp, value, tb +""") + + + def print_(*args, **kwargs): + """The new-style print function.""" + fp = kwargs.pop("file", sys.stdout) + if fp is None: + return + def write(data): + if not isinstance(data, basestring): + data = str(data) + fp.write(data) + want_unicode = False + sep = kwargs.pop("sep", None) + if sep is not None: + if isinstance(sep, unicode): + want_unicode = True + elif not isinstance(sep, str): + raise TypeError("sep must be None or a string") + end = kwargs.pop("end", None) + if end is not None: + if isinstance(end, unicode): + want_unicode = True + elif not isinstance(end, str): + raise TypeError("end must be None or a string") + if kwargs: + raise TypeError("invalid keyword arguments to print()") + if not want_unicode: + for arg in args: + if isinstance(arg, unicode): + want_unicode = True + break + if want_unicode: + newline = unicode("\n") + space = unicode(" ") + else: + newline = "\n" + space = " " + if sep is None: + sep = space + if end is None: + end = newline + for i, arg in enumerate(args): + if i: + write(sep) + write(arg) + write(end) + +_add_doc(reraise, """Reraise an exception.""") + + +def with_metaclass(meta, *bases): + """Create a base class with a metaclass.""" + return meta("NewBase", bases, {}) + +def add_metaclass(metaclass): + """Class decorator for creating a class with a metaclass.""" + def wrapper(cls): + orig_vars = cls.__dict__.copy() + orig_vars.pop('__dict__', None) + orig_vars.pop('__weakref__', None) + for slots_var in orig_vars.get('__slots__', ()): + orig_vars.pop(slots_var) + return metaclass(cls.__name__, cls.__bases__, orig_vars) + return wrapper diff --git a/sklearn/feature_extraction/__init__.py b/sklearn/feature_extraction/__init__.py index 2bc97f82a57b9..b45440444d769 100644 --- a/sklearn/feature_extraction/__init__.py +++ b/sklearn/feature_extraction/__init__.py @@ -5,7 +5,9 @@ """ from .dict_vectorizer import DictVectorizer +from .hashing import FeatureHasher from .image import img_to_graph, grid_to_graph from . import text -__all__ = ['DictVectorizer', 'image', 'img_to_graph', 'grid_to_graph', 'text'] +__all__ = ['DictVectorizer', 'image', 'img_to_graph', 'grid_to_graph', 'text', + 'FeatureHasher'] diff --git a/sklearn/feature_extraction/_hashing.c b/sklearn/feature_extraction/_hashing.c new file mode 100644 index 0000000000000..31cc759428427 --- /dev/null +++ b/sklearn/feature_extraction/_hashing.c @@ -0,0 +1,6970 @@ +/* Generated by Cython 0.19.2 on Fri Dec 27 15:32:18 2013 */ + +#define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_VERSION_HEX < 0x03020000 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__feature_extraction___hashing +#define __PYX_HAVE_API__sklearn__feature_extraction___hashing +#include "string.h" +#include "stdio.h" +#include "pythread.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +#ifdef __GNUC__ + /* Test for GCC > 2.95 */ + #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) + #else /* __GNUC__ > 2 ... */ + #define likely(x) (x) + #define unlikely(x) (x) + #endif /* __GNUC__ > 2 ... */ +#else /* __GNUC__ */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "_hashing.pyx", + "array.pxd", + "numpy.pxd", + "type.pxd", + "bool.pxd", + "complex.pxd", +}; + +/* "numpy.pxd":723 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "numpy.pxd":724 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "numpy.pxd":725 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "numpy.pxd":726 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "numpy.pxd":730 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "numpy.pxd":731 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "numpy.pxd":732 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "numpy.pxd":733 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "numpy.pxd":737 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "numpy.pxd":738 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "numpy.pxd":747 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "numpy.pxd":748 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "numpy.pxd":749 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "numpy.pxd":751 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "numpy.pxd":752 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "numpy.pxd":753 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "numpy.pxd":755 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "numpy.pxd":756 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "numpy.pxd":758 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "numpy.pxd":759 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "numpy.pxd":760 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ +#ifndef _ARRAYARRAY_H +struct arrayobject; +typedef struct arrayobject arrayobject; +#endif + +/* "numpy.pxd":762 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "numpy.pxd":763 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "numpy.pxd":764 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "numpy.pxd":766 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +#define __Pyx_SetItemInt(o, i, v, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_SetItemInt_Fast(o, i, v, is_list, wraparound, boundscheck) : \ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v)) +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck); + +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +#ifndef _ARRAYARRAY_H +#define _ARRAYARRAY_H +typedef struct arraydescr { + int typecode; + int itemsize; + PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); + int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); +#if PY_VERSION_HEX >= 0x03000000 + char *formats; +#endif +} arraydescr; +struct arrayobject { + PyObject_HEAD + Py_ssize_t ob_size; + union { + char *ob_item; + float *as_floats; + double *as_doubles; + int *as_ints; + unsigned int *as_uints; + unsigned char *as_uchars; + signed char *as_schars; + char *as_chars; + unsigned long *as_ulongs; + long *as_longs; + short *as_shorts; + unsigned short *as_ushorts; + Py_UNICODE *as_pyunicodes; + void *as_voidptr; + } data; + Py_ssize_t allocated; + struct arraydescr *ob_descr; + PyObject *weakreflist; /* List of weak references */ +#if PY_VERSION_HEX >= 0x03000000 + int ob_exports; /* Number of exported buffers */ +#endif +}; +#ifndef NO_NEWARRAY_INLINE +static CYTHON_INLINE PyObject * newarrayobject(PyTypeObject *type, Py_ssize_t size, + struct arraydescr *descr) { + arrayobject *op; + size_t nbytes; + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } + nbytes = size * descr->itemsize; + if (nbytes / descr->itemsize != (size_t)size) { + return PyErr_NoMemory(); + } + op = (arrayobject *) type->tp_alloc(type, 0); + if (op == NULL) { + return NULL; + } + op->ob_descr = descr; + op->allocated = size; + op->weakreflist = NULL; + op->ob_size = size; + if (size <= 0) { + op->data.ob_item = NULL; + } + else { + op->data.ob_item = PyMem_NEW(char, nbytes); + if (op->data.ob_item == NULL) { + Py_DECREF(op); + return PyErr_NoMemory(); + } + } + return (PyObject *) op; +} +#else +PyObject* newarrayobject(PyTypeObject *type, Py_ssize_t size, + struct arraydescr *descr); +#endif /* ifndef NO_NEWARRAY_INLINE */ +static CYTHON_INLINE int resize(arrayobject *self, Py_ssize_t n) { + void *items = (void*) self->data.ob_item; + PyMem_Resize(items, char, (size_t)(n * self->ob_descr->itemsize)); + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->data.ob_item = (char*) items; + self->ob_size = n; + self->allocated = n; + return 0; +} +static CYTHON_INLINE int resize_smart(arrayobject *self, Py_ssize_t n) { + void *items = (void*) self->data.ob_item; + Py_ssize_t newsize; + if (n < self->allocated) { + if (n*4 > self->allocated) { + self->ob_size = n; + return 0; + } + } + newsize = n * 3 / 2 + 1; + PyMem_Resize(items, char, (size_t)(newsize * self->ob_descr->itemsize)); + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->data.ob_item = (char*) items; + self->ob_size = n; + self->allocated = newsize; + return 0; +} +#endif + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32); + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); + +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); + +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); + +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); + +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); + +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); + +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); + +static int __Pyx_check_binary_version(void); + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'cpython.version' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'cpython.exc' */ + +/* Module declarations from 'cpython.module' */ + +/* Module declarations from 'cpython.mem' */ + +/* Module declarations from 'cpython.tuple' */ + +/* Module declarations from 'cpython.list' */ + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from 'cpython.sequence' */ + +/* Module declarations from 'cpython.mapping' */ + +/* Module declarations from 'cpython.iterator' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'cpython.number' */ + +/* Module declarations from 'cpython.int' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.bool' */ +static PyTypeObject *__pyx_ptype_7cpython_4bool_bool = 0; + +/* Module declarations from 'cpython.long' */ + +/* Module declarations from 'cpython.float' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.complex' */ +static PyTypeObject *__pyx_ptype_7cpython_7complex_complex = 0; + +/* Module declarations from 'cpython.string' */ + +/* Module declarations from 'cpython.unicode' */ + +/* Module declarations from 'cpython.dict' */ + +/* Module declarations from 'cpython.instance' */ + +/* Module declarations from 'cpython.function' */ + +/* Module declarations from 'cpython.method' */ + +/* Module declarations from 'cpython.weakref' */ + +/* Module declarations from 'cpython.getargs' */ + +/* Module declarations from 'cpython.pythread' */ + +/* Module declarations from 'cpython.pystate' */ + +/* Module declarations from 'cpython.cobject' */ + +/* Module declarations from 'cpython.oldbuffer' */ + +/* Module declarations from 'cpython.set' */ + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.bytes' */ + +/* Module declarations from 'cpython.pycapsule' */ + +/* Module declarations from 'cpython' */ + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'libc' */ + +/* Module declarations from 'array' */ + +/* Module declarations from 'cpython.array' */ +static PyTypeObject *__pyx_ptype_7cpython_5array_array = 0; +static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *, char *, Py_ssize_t); /*proto*/ + +/* Module declarations from 'cython' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'sklearn.utils.murmurhash' */ +static __pyx_t_5numpy_int32_t (*__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32)(PyObject *, unsigned int, int __pyx_skip_dispatch); /*proto*/ + +/* Module declarations from 'sklearn.feature_extraction._hashing' */ +#define __Pyx_MODULE_NAME "sklearn.feature_extraction._hashing" +int __pyx_module_is_main_sklearn__feature_extraction___hashing = 0; + +/* Implementation of 'sklearn.feature_extraction._hashing' */ +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_pf_7sklearn_18feature_extraction_8_hashing_transform(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_raw_X, Py_ssize_t __pyx_v_n_features, PyObject *__pyx_v_dtype); /* proto */ +static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags); /* proto */ +static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static char __pyx_k_2[] = "utf-8"; +static char __pyx_k_4[] = "feature names must be strings"; +static char __pyx_k_7[] = "ndarray is not C contiguous"; +static char __pyx_k_9[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_11[] = "Non-native byte order not supported"; +static char __pyx_k_13[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_14[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_17[] = "Format string allocated too short."; +static char __pyx_k_21[] = "/home/lars/src/scikit-learn/sklearn/feature_extraction/_hashing.pyx"; +static char __pyx_k_22[] = "sklearn.feature_extraction._hashing"; +static char __pyx_k__B[] = "B"; +static char __pyx_k__H[] = "H"; +static char __pyx_k__I[] = "I"; +static char __pyx_k__L[] = "L"; +static char __pyx_k__O[] = "O"; +static char __pyx_k__Q[] = "Q"; +static char __pyx_k__b[] = "b"; +static char __pyx_k__d[] = "d"; +static char __pyx_k__f[] = "f"; +static char __pyx_k__g[] = "g"; +static char __pyx_k__h[] = "h"; +static char __pyx_k__i[] = "i"; +static char __pyx_k__l[] = "l"; +static char __pyx_k__q[] = "q"; +static char __pyx_k__v[] = "v"; +static char __pyx_k__x[] = "x"; +static char __pyx_k__Zd[] = "Zd"; +static char __pyx_k__Zf[] = "Zf"; +static char __pyx_k__Zg[] = "Zg"; +static char __pyx_k__np[] = "np"; +static char __pyx_k__size[] = "size"; +static char __pyx_k__array[] = "array"; +static char __pyx_k__dtype[] = "dtype"; +static char __pyx_k__empty[] = "empty"; +static char __pyx_k__int32[] = "int32"; +static char __pyx_k__numpy[] = "numpy"; +static char __pyx_k__range[] = "range"; +static char __pyx_k__raw_X[] = "raw_X"; +static char __pyx_k__value[] = "value"; +static char __pyx_k__encode[] = "encode"; +static char __pyx_k__indptr[] = "indptr"; +static char __pyx_k__resize[] = "resize"; +static char __pyx_k__values[] = "values"; +static char __pyx_k__indices[] = "indices"; +static char __pyx_k____main__[] = "__main__"; +static char __pyx_k____test__[] = "__test__"; +static char __pyx_k__capacity[] = "capacity"; +static char __pyx_k__TypeError[] = "TypeError"; +static char __pyx_k__indices_a[] = "indices_a"; +static char __pyx_k__transform[] = "transform"; +static char __pyx_k__ValueError[] = "ValueError"; +static char __pyx_k____import__[] = "__import__"; +static char __pyx_k__frombuffer[] = "frombuffer"; +static char __pyx_k__n_features[] = "n_features"; +static char __pyx_k__RuntimeError[] = "RuntimeError"; +static PyObject *__pyx_kp_u_11; +static PyObject *__pyx_kp_u_13; +static PyObject *__pyx_kp_u_14; +static PyObject *__pyx_kp_u_17; +static PyObject *__pyx_kp_s_2; +static PyObject *__pyx_kp_s_21; +static PyObject *__pyx_n_s_22; +static PyObject *__pyx_kp_s_4; +static PyObject *__pyx_kp_u_7; +static PyObject *__pyx_kp_u_9; +static PyObject *__pyx_n_s__RuntimeError; +static PyObject *__pyx_n_s__TypeError; +static PyObject *__pyx_n_s__ValueError; +static PyObject *__pyx_n_s____import__; +static PyObject *__pyx_n_s____main__; +static PyObject *__pyx_n_s____test__; +static PyObject *__pyx_n_s__array; +static PyObject *__pyx_n_s__capacity; +static PyObject *__pyx_n_s__dtype; +static PyObject *__pyx_n_s__empty; +static PyObject *__pyx_n_s__encode; +static PyObject *__pyx_n_s__f; +static PyObject *__pyx_n_s__frombuffer; +static PyObject *__pyx_n_s__h; +static PyObject *__pyx_n_s__i; +static PyObject *__pyx_n_s__indices; +static PyObject *__pyx_n_s__indices_a; +static PyObject *__pyx_n_s__indptr; +static PyObject *__pyx_n_s__int32; +static PyObject *__pyx_n_s__n_features; +static PyObject *__pyx_n_s__np; +static PyObject *__pyx_n_s__numpy; +static PyObject *__pyx_n_s__range; +static PyObject *__pyx_n_s__raw_X; +static PyObject *__pyx_n_s__resize; +static PyObject *__pyx_n_s__size; +static PyObject *__pyx_n_s__transform; +static PyObject *__pyx_n_s__v; +static PyObject *__pyx_n_s__value; +static PyObject *__pyx_n_s__values; +static PyObject *__pyx_n_s__x; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_15; +static PyObject *__pyx_k_tuple_1; +static PyObject *__pyx_k_tuple_3; +static PyObject *__pyx_k_tuple_5; +static PyObject *__pyx_k_tuple_6; +static PyObject *__pyx_k_tuple_8; +static PyObject *__pyx_k_tuple_10; +static PyObject *__pyx_k_tuple_12; +static PyObject *__pyx_k_tuple_15; +static PyObject *__pyx_k_tuple_16; +static PyObject *__pyx_k_tuple_18; +static PyObject *__pyx_k_tuple_19; +static PyObject *__pyx_k_codeobj_20; + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_18feature_extraction_8_hashing_1transform(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_18feature_extraction_8_hashing_transform[] = "Guts of FeatureHasher.transform.\n\n Returns\n -------\n n_samples : integer\n indices, indptr, values : lists\n For constructing a scipy.sparse.csr_matrix.\n\n "; +static PyMethodDef __pyx_mdef_7sklearn_18feature_extraction_8_hashing_1transform = {__Pyx_NAMESTR("transform"), (PyCFunction)__pyx_pw_7sklearn_18feature_extraction_8_hashing_1transform, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_18feature_extraction_8_hashing_transform)}; +static PyObject *__pyx_pw_7sklearn_18feature_extraction_8_hashing_1transform(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_raw_X = 0; + Py_ssize_t __pyx_v_n_features; + PyObject *__pyx_v_dtype = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("transform (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__raw_X,&__pyx_n_s__n_features,&__pyx_n_s__dtype,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__raw_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_features)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("transform", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dtype)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("transform", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "transform") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v_raw_X = values[0]; + __pyx_v_n_features = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_n_features == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_dtype = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("transform", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.feature_extraction._hashing.transform", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_18feature_extraction_8_hashing_transform(__pyx_self, __pyx_v_raw_X, __pyx_v_n_features, __pyx_v_dtype); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/feature_extraction/_hashing.pyx":18 + * @cython.boundscheck(False) + * @cython.cdivision(True) + * def transform(raw_X, Py_ssize_t n_features, dtype): # <<<<<<<<<<<<<< + * """Guts of FeatureHasher.transform. + * + */ + +static PyObject *__pyx_pf_7sklearn_18feature_extraction_8_hashing_transform(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_raw_X, Py_ssize_t __pyx_v_n_features, PyObject *__pyx_v_dtype) { + __pyx_t_5numpy_int32_t __pyx_v_h; + double __pyx_v_value; + arrayobject *__pyx_v_indices = 0; + arrayobject *__pyx_v_indptr = 0; + Py_ssize_t __pyx_v_capacity; + __pyx_t_5numpy_int32_t __pyx_v_size; + PyArrayObject *__pyx_v_values = 0; + PyObject *__pyx_v_x = NULL; + PyObject *__pyx_v_f = NULL; + PyObject *__pyx_v_v = NULL; + PyObject *__pyx_v_indices_a = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *(*__pyx_t_11)(PyObject *); + double __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + Py_ssize_t __pyx_t_15; + int __pyx_t_16; + Py_ssize_t __pyx_t_17; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("transform", 0); + + /* "sklearn/feature_extraction/_hashing.pyx":28 + * + * """ + * assert n_features > 0 # <<<<<<<<<<<<<< + * + * cdef np.int32_t h + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!((__pyx_v_n_features > 0) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #endif + + /* "sklearn/feature_extraction/_hashing.pyx":35 + * cdef array.array indices + * cdef array.array indptr + * indices = array.array("i") # <<<<<<<<<<<<<< + * indptr = array.array("i", [0]) + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7cpython_5array_array)), ((PyObject *)__pyx_k_tuple_1), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_indices = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":36 + * cdef array.array indptr + * indices = array.array("i") + * indptr = array.array("i", [0]) # <<<<<<<<<<<<<< + * + * # Since Python array does not understand Numpy dtypes, we grow the indices + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_int_0); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_n_s__i)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_n_s__i)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i)); + PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_t_1)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_1)); + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7cpython_5array_array)), ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_v_indptr = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":40 + * # Since Python array does not understand Numpy dtypes, we grow the indices + * # and values arrays ourselves. Use a Py_ssize_t capacity for safety. + * cdef Py_ssize_t capacity = 8192 # arbitrary # <<<<<<<<<<<<<< + * cdef np.int32_t size = 0 + * cdef np.ndarray values = np.empty(capacity, dtype=dtype) + */ + __pyx_v_capacity = 8192; + + /* "sklearn/feature_extraction/_hashing.pyx":41 + * # and values arrays ourselves. Use a Py_ssize_t capacity for safety. + * cdef Py_ssize_t capacity = 8192 # arbitrary + * cdef np.int32_t size = 0 # <<<<<<<<<<<<<< + * cdef np.ndarray values = np.empty(capacity, dtype=dtype) + * + */ + __pyx_v_size = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":42 + * cdef Py_ssize_t capacity = 8192 # arbitrary + * cdef np.int32_t size = 0 + * cdef np.ndarray values = np.empty(capacity, dtype=dtype) # <<<<<<<<<<<<<< + * + * for x in raw_X: + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_capacity); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_v_dtype) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_values = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":44 + * cdef np.ndarray values = np.empty(capacity, dtype=dtype) + * + * for x in raw_X: # <<<<<<<<<<<<<< + * for f, v in x: + * value = v + */ + if (PyList_CheckExact(__pyx_v_raw_X) || PyTuple_CheckExact(__pyx_v_raw_X)) { + __pyx_t_4 = __pyx_v_raw_X; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_raw_X); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_1 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_1); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_1); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_1 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_1)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_XDECREF_SET(__pyx_v_x, __pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":45 + * + * for x in raw_X: + * for f, v in x: # <<<<<<<<<<<<<< + * value = v + * if value == 0: + */ + if (PyList_CheckExact(__pyx_v_x) || PyTuple_CheckExact(__pyx_v_x)) { + __pyx_t_1 = __pyx_v_x; __Pyx_INCREF(__pyx_t_1); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_x); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_8 = Py_TYPE(__pyx_t_1)->tp_iternext; + } + for (;;) { + if (!__pyx_t_8 && PyList_CheckExact(__pyx_t_1)) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_7); __Pyx_INCREF(__pyx_t_3); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_8 && PyTuple_CheckExact(__pyx_t_1)) { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_7); __Pyx_INCREF(__pyx_t_3); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_3 = __pyx_t_8(__pyx_t_1); + if (unlikely(!__pyx_t_3)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + if ((likely(PyTuple_CheckExact(__pyx_t_3))) || (PyList_CheckExact(__pyx_t_3))) { + PyObject* sequence = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_9 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_2 = PyList_GET_ITEM(sequence, 0); + __pyx_t_9 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_9); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_9 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else + { + Py_ssize_t index = -1; + __pyx_t_10 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_11 = Py_TYPE(__pyx_t_10)->tp_iternext; + index = 0; __pyx_t_2 = __pyx_t_11(__pyx_t_10); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_9 = __pyx_t_11(__pyx_t_10); if (unlikely(!__pyx_t_9)) goto __pyx_L7_unpacking_failed; + __Pyx_GOTREF(__pyx_t_9); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_11(__pyx_t_10), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = NULL; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + goto __pyx_L8_unpacking_done; + __pyx_L7_unpacking_failed:; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_11 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L8_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_f, __pyx_t_2); + __pyx_t_2 = 0; + __Pyx_XDECREF_SET(__pyx_v_v, __pyx_t_9); + __pyx_t_9 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":46 + * for x in raw_X: + * for f, v in x: + * value = v # <<<<<<<<<<<<<< + * if value == 0: + * continue + */ + __pyx_t_12 = __pyx_PyFloat_AsDouble(__pyx_v_v); if (unlikely((__pyx_t_12 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_value = __pyx_t_12; + + /* "sklearn/feature_extraction/_hashing.pyx":47 + * for f, v in x: + * value = v + * if value == 0: # <<<<<<<<<<<<<< + * continue + * + */ + __pyx_t_13 = ((__pyx_v_value == 0.0) != 0); + if (__pyx_t_13) { + + /* "sklearn/feature_extraction/_hashing.pyx":48 + * value = v + * if value == 0: + * continue # <<<<<<<<<<<<<< + * + * if isinstance(f, unicode): + */ + goto __pyx_L5_continue; + goto __pyx_L9; + } + __pyx_L9:; + + /* "sklearn/feature_extraction/_hashing.pyx":50 + * continue + * + * if isinstance(f, unicode): # <<<<<<<<<<<<<< + * f = f.encode("utf-8") + * # Need explicit type check because Murmurhash does not propagate + */ + __pyx_t_13 = PyUnicode_Check(__pyx_v_f); + __pyx_t_14 = (__pyx_t_13 != 0); + if (__pyx_t_14) { + + /* "sklearn/feature_extraction/_hashing.pyx":51 + * + * if isinstance(f, unicode): + * f = f.encode("utf-8") # <<<<<<<<<<<<<< + * # Need explicit type check because Murmurhash does not propagate + * # all exceptions. Add "except *" there? + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_f, __pyx_n_s__encode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_9 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_k_tuple_3), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_f, __pyx_t_9); + __pyx_t_9 = 0; + goto __pyx_L10; + } + + /* "sklearn/feature_extraction/_hashing.pyx":54 + * # Need explicit type check because Murmurhash does not propagate + * # all exceptions. Add "except *" there? + * elif not isinstance(f, bytes): # <<<<<<<<<<<<<< + * raise TypeError("feature names must be strings") + * h = murmurhash3_bytes_s32(f, 0) + */ + __pyx_t_14 = PyBytes_Check(__pyx_v_f); + __pyx_t_13 = ((!(__pyx_t_14 != 0)) != 0); + if (__pyx_t_13) { + + /* "sklearn/feature_extraction/_hashing.pyx":55 + * # all exceptions. Add "except *" there? + * elif not isinstance(f, bytes): + * raise TypeError("feature names must be strings") # <<<<<<<<<<<<<< + * h = murmurhash3_bytes_s32(f, 0) + * + */ + __pyx_t_9 = PyObject_Call(__pyx_builtin_TypeError, ((PyObject *)__pyx_k_tuple_5), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L10; + } + __pyx_L10:; + + /* "sklearn/feature_extraction/_hashing.pyx":56 + * elif not isinstance(f, bytes): + * raise TypeError("feature names must be strings") + * h = murmurhash3_bytes_s32(f, 0) # <<<<<<<<<<<<<< + * + * array.resize_smart(indices, len(indices) + 1) + */ + if (!(likely(PyBytes_CheckExact(__pyx_v_f))||((__pyx_v_f) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_v_f)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_h = __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32(((PyObject*)__pyx_v_f), 0, 0); + + /* "sklearn/feature_extraction/_hashing.pyx":58 + * h = murmurhash3_bytes_s32(f, 0) + * + * array.resize_smart(indices, len(indices) + 1) # <<<<<<<<<<<<<< + * indices[len(indices) - 1] = abs(h) % n_features + * value *= (h >= 0) * 2 - 1 + */ + __pyx_t_15 = Py_SIZE(((PyObject *)__pyx_v_indices)); if (unlikely(__pyx_t_15 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_16 = resize_smart(__pyx_v_indices, (__pyx_t_15 + 1)); if (unlikely(__pyx_t_16 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/feature_extraction/_hashing.pyx":59 + * + * array.resize_smart(indices, len(indices) + 1) + * indices[len(indices) - 1] = abs(h) % n_features # <<<<<<<<<<<<<< + * value *= (h >= 0) * 2 - 1 + * values[size] = value + */ + __pyx_t_9 = PyInt_FromSsize_t((abs(__pyx_v_h) % __pyx_v_n_features)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_15 = Py_SIZE(((PyObject *)__pyx_v_indices)); if (unlikely(__pyx_t_15 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = (__pyx_t_15 - 1); + if (__Pyx_SetItemInt(((PyObject *)__pyx_v_indices), __pyx_t_17, __pyx_t_9, sizeof(Py_ssize_t), PyInt_FromSsize_t, 0, 1, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":60 + * array.resize_smart(indices, len(indices) + 1) + * indices[len(indices) - 1] = abs(h) % n_features + * value *= (h >= 0) * 2 - 1 # <<<<<<<<<<<<<< + * values[size] = value + * size += 1 + */ + __pyx_v_value = (__pyx_v_value * (((__pyx_v_h >= 0) * 2) - 1)); + + /* "sklearn/feature_extraction/_hashing.pyx":61 + * indices[len(indices) - 1] = abs(h) % n_features + * value *= (h >= 0) * 2 - 1 + * values[size] = value # <<<<<<<<<<<<<< + * size += 1 + * + */ + __pyx_t_9 = PyFloat_FromDouble(__pyx_v_value); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + if (__Pyx_SetItemInt(((PyObject *)__pyx_v_values), __pyx_v_size, __pyx_t_9, sizeof(__pyx_t_5numpy_int32_t), __Pyx_PyInt_to_py_npy_int32, 0, 1, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":62 + * value *= (h >= 0) * 2 - 1 + * values[size] = value + * size += 1 # <<<<<<<<<<<<<< + * + * if size == capacity: + */ + __pyx_v_size = (__pyx_v_size + 1); + + /* "sklearn/feature_extraction/_hashing.pyx":64 + * size += 1 + * + * if size == capacity: # <<<<<<<<<<<<<< + * capacity *= 2 + * # can't use resize member because there might be multiple + */ + __pyx_t_13 = ((__pyx_v_size == __pyx_v_capacity) != 0); + if (__pyx_t_13) { + + /* "sklearn/feature_extraction/_hashing.pyx":65 + * + * if size == capacity: + * capacity *= 2 # <<<<<<<<<<<<<< + * # can't use resize member because there might be multiple + * # references to the arrays due to Cython's error checking + */ + __pyx_v_capacity = (__pyx_v_capacity * 2); + + /* "sklearn/feature_extraction/_hashing.pyx":68 + * # can't use resize member because there might be multiple + * # references to the arrays due to Cython's error checking + * values = np.resize(values, capacity) # <<<<<<<<<<<<<< + * + * array.resize_smart(indptr, len(indptr) + 1) + */ + __pyx_t_9 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_n_s__resize); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_capacity); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_values)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_values)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_values)); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_9 = 0; + __pyx_t_9 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_9) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_9, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF_SET(__pyx_v_values, ((PyArrayObject *)__pyx_t_9)); + __pyx_t_9 = 0; + goto __pyx_L11; + } + __pyx_L11:; + __pyx_L5_continue:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":70 + * values = np.resize(values, capacity) + * + * array.resize_smart(indptr, len(indptr) + 1) # <<<<<<<<<<<<<< + * indptr[len(indptr) - 1] = size + * + */ + __pyx_t_7 = Py_SIZE(((PyObject *)__pyx_v_indptr)); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_16 = resize_smart(__pyx_v_indptr, (__pyx_t_7 + 1)); if (unlikely(__pyx_t_16 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/feature_extraction/_hashing.pyx":71 + * + * array.resize_smart(indptr, len(indptr) + 1) + * indptr[len(indptr) - 1] = size # <<<<<<<<<<<<<< + * + * if len(indices): + */ + __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = Py_SIZE(((PyObject *)__pyx_v_indptr)); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = (__pyx_t_7 - 1); + if (__Pyx_SetItemInt(((PyObject *)__pyx_v_indptr), __pyx_t_17, __pyx_t_1, sizeof(Py_ssize_t), PyInt_FromSsize_t, 0, 1, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":73 + * indptr[len(indptr) - 1] = size + * + * if len(indices): # <<<<<<<<<<<<<< + * indices_a = np.frombuffer(indices, dtype=np.int32) + * else: + */ + __pyx_t_5 = Py_SIZE(((PyObject *)__pyx_v_indices)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = (__pyx_t_5 != 0); + if (__pyx_t_13) { + + /* "sklearn/feature_extraction/_hashing.pyx":74 + * + * if len(indices): + * indices_a = np.frombuffer(indices, dtype=np.int32) # <<<<<<<<<<<<<< + * else: + * indices_a = np.empty(0, dtype=np.int32) + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__frombuffer); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_indices)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_indices)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_indices)); + __pyx_t_9 = PyDict_New(); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_9)); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__int32); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_9, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_9)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __pyx_v_indices_a = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L12; + } + /*else*/ { + + /* "sklearn/feature_extraction/_hashing.pyx":76 + * indices_a = np.frombuffer(indices, dtype=np.int32) + * else: + * indices_a = np.empty(0, dtype=np.int32) # <<<<<<<<<<<<<< + * return (indices_a, np.frombuffer(indptr, dtype=np.int32), values[:size]) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_9, ((PyObject *)__pyx_k_tuple_6), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_indices_a = __pyx_t_1; + __pyx_t_1 = 0; + } + __pyx_L12:; + + /* "sklearn/feature_extraction/_hashing.pyx":77 + * else: + * indices_a = np.empty(0, dtype=np.int32) + * return (indices_a, np.frombuffer(indptr, dtype=np.int32), values[:size]) # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__frombuffer); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_indptr)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_indptr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_indptr)); + __pyx_t_9 = PyDict_New(); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_9)); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_9, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_9)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_GetSlice(((PyObject *)__pyx_v_values), 0, __pyx_v_size, NULL, NULL, NULL, 0, 1, 1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_indices_a); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_indices_a); + __Pyx_GIVEREF(__pyx_v_indices_a); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_2 = 0; + __pyx_t_9 = 0; + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("sklearn.feature_extraction._hashing.transform", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_indices); + __Pyx_XDECREF((PyObject *)__pyx_v_indptr); + __Pyx_XDECREF((PyObject *)__pyx_v_values); + __Pyx_XDECREF(__pyx_v_x); + __Pyx_XDECREF(__pyx_v_f); + __Pyx_XDECREF(__pyx_v_v); + __Pyx_XDECREF(__pyx_v_indices_a); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_7cpython_5array_5array_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_7cpython_5array_5array_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_7cpython_5array_5array___getbuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":91 + * __data_union data + * + * def __getbuffer__(array self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags) { + CYTHON_UNUSED unsigned int __pyx_v_itemsize; + int __pyx_r; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "array.pxd":98 + * cdef unsigned rows, columns, itemsize + * + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.buf = self.data.as_chars + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; + + /* "array.pxd":99 + * + * info.suboffsets = NULL + * info.buf = self.data.as_chars # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.ndim = 1 + */ + __pyx_t_1 = __pyx_v_self->data.as_chars; + __pyx_v_info->buf = __pyx_t_1; + + /* "array.pxd":100 + * info.suboffsets = NULL + * info.buf = self.data.as_chars + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.ndim = 1 + * info.itemsize = itemsize = self.ob_descr.itemsize # e.g. sizeof(float) + */ + __pyx_v_info->readonly = 0; + + /* "array.pxd":101 + * info.buf = self.data.as_chars + * info.readonly = 0 + * info.ndim = 1 # <<<<<<<<<<<<<< + * info.itemsize = itemsize = self.ob_descr.itemsize # e.g. sizeof(float) + * + */ + __pyx_v_info->ndim = 1; + + /* "array.pxd":102 + * info.readonly = 0 + * info.ndim = 1 + * info.itemsize = itemsize = self.ob_descr.itemsize # e.g. sizeof(float) # <<<<<<<<<<<<<< + * + * info.strides = \ + */ + __pyx_v_info->itemsize = __pyx_v_self->ob_descr->itemsize; + __pyx_v_itemsize = __pyx_v_self->ob_descr->itemsize; + + /* "array.pxd":104 + * info.itemsize = itemsize = self.ob_descr.itemsize # e.g. sizeof(float) + * + * info.strides = \ # <<<<<<<<<<<<<< + * stdlib.malloc(sizeof(Py_ssize_t) * info.ndim * 2 + 2) + * info.shape = info.strides + 1 + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc(((((sizeof(Py_ssize_t)) * __pyx_v_info->ndim) * 2) + 2))); + + /* "array.pxd":106 + * info.strides = \ + * stdlib.malloc(sizeof(Py_ssize_t) * info.ndim * 2 + 2) + * info.shape = info.strides + 1 # <<<<<<<<<<<<<< + * info.shape[0] = Py_SIZE(self) # number of items + * info.strides[0] = info.itemsize + */ + __pyx_v_info->shape = (__pyx_v_info->strides + 1); + + /* "array.pxd":107 + * stdlib.malloc(sizeof(Py_ssize_t) * info.ndim * 2 + 2) + * info.shape = info.strides + 1 + * info.shape[0] = Py_SIZE(self) # number of items # <<<<<<<<<<<<<< + * info.strides[0] = info.itemsize + * + */ + (__pyx_v_info->shape[0]) = Py_SIZE(((PyObject *)__pyx_v_self)); + + /* "array.pxd":108 + * info.shape = info.strides + 1 + * info.shape[0] = Py_SIZE(self) # number of items + * info.strides[0] = info.itemsize # <<<<<<<<<<<<<< + * + * info.format = (info.strides + 2 * info.ndim) + */ + __pyx_t_2 = __pyx_v_info->itemsize; + (__pyx_v_info->strides[0]) = __pyx_t_2; + + /* "array.pxd":110 + * info.strides[0] = info.itemsize + * + * info.format = (info.strides + 2 * info.ndim) # <<<<<<<<<<<<<< + * info.format[0] = self.ob_descr.typecode + * info.format[1] = 0 + */ + __pyx_v_info->format = ((char *)(__pyx_v_info->strides + (2 * __pyx_v_info->ndim))); + + /* "array.pxd":111 + * + * info.format = (info.strides + 2 * info.ndim) + * info.format[0] = self.ob_descr.typecode # <<<<<<<<<<<<<< + * info.format[1] = 0 + * info.obj = self + */ + __pyx_t_3 = __pyx_v_self->ob_descr->typecode; + (__pyx_v_info->format[0]) = __pyx_t_3; + + /* "array.pxd":112 + * info.format = (info.strides + 2 * info.ndim) + * info.format[0] = self.ob_descr.typecode + * info.format[1] = 0 # <<<<<<<<<<<<<< + * info.obj = self + * + */ + (__pyx_v_info->format[1]) = 0; + + /* "array.pxd":113 + * info.format[0] = self.ob_descr.typecode + * info.format[1] = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * def __releasebuffer__(array self, Py_buffer* info): + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + __pyx_r = 0; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_7cpython_5array_5array_2__releasebuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "array.pxd":115 + * info.obj = self + * + * def __releasebuffer__(array self, Py_buffer* info): # <<<<<<<<<<<<<< + * #if PyArray_HASFIELDS(self): + * # stdlib.free(info.format) + */ + +static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "array.pxd":119 + * # stdlib.free(info.format) + * #if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * + * array newarrayobject(PyTypeObject* type, Py_ssize_t size, arraydescr *descr) + */ + free(__pyx_v_info->strides); + + __Pyx_RefNannyFinishContext(); +} + +/* "array.pxd":130 + * + * + * cdef inline array clone(array template, Py_ssize_t length, bint zero): # <<<<<<<<<<<<<< + * """ fast creation of a new array, given a template array. + * type will be same as template. + */ + +static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_clone(arrayobject *__pyx_v_template, Py_ssize_t __pyx_v_length, int __pyx_v_zero) { + arrayobject *__pyx_v_op = 0; + arrayobject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("clone", 0); + + /* "array.pxd":135 + * if zero is true, new array will be initialized with zeroes.""" + * cdef array op + * op = newarrayobject(Py_TYPE(template), length, template.ob_descr) # <<<<<<<<<<<<<< + * if zero and op is not None: + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) + */ + __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_template)), __pyx_v_length, __pyx_v_template->ob_descr)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_op = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "array.pxd":136 + * cdef array op + * op = newarrayobject(Py_TYPE(template), length, template.ob_descr) + * if zero and op is not None: # <<<<<<<<<<<<<< + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) + * return op + */ + if ((__pyx_v_zero != 0)) { + __pyx_t_2 = (((PyObject *)__pyx_v_op) != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + } else { + __pyx_t_3 = (__pyx_v_zero != 0); + } + if (__pyx_t_3) { + + /* "array.pxd":137 + * op = newarrayobject(Py_TYPE(template), length, template.ob_descr) + * if zero and op is not None: + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) # <<<<<<<<<<<<<< + * return op + * + */ + memset(__pyx_v_op->data.as_chars, 0, (__pyx_v_length * __pyx_v_op->ob_descr->itemsize)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "array.pxd":138 + * if zero and op is not None: + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) + * return op # <<<<<<<<<<<<<< + * + * cdef inline array copy(array self): + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_op)); + __pyx_r = __pyx_v_op; + goto __pyx_L0; + + __pyx_r = ((arrayobject *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("cpython.array.clone", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_op); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":140 + * return op + * + * cdef inline array copy(array self): # <<<<<<<<<<<<<< + * """ make a copy of an array. """ + * cdef array op + */ + +static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_copy(arrayobject *__pyx_v_self) { + arrayobject *__pyx_v_op = 0; + arrayobject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "array.pxd":143 + * """ make a copy of an array. """ + * cdef array op + * op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) # <<<<<<<<<<<<<< + * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) + * return op + */ + __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_self)), Py_SIZE(((PyObject *)__pyx_v_self)), __pyx_v_self->ob_descr)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_op = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "array.pxd":144 + * cdef array op + * op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) + * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) # <<<<<<<<<<<<<< + * return op + * + */ + memcpy(__pyx_v_op->data.as_chars, __pyx_v_self->data.as_chars, (Py_SIZE(((PyObject *)__pyx_v_op)) * __pyx_v_op->ob_descr->itemsize)); + + /* "array.pxd":145 + * op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) + * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) + * return op # <<<<<<<<<<<<<< + * + * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_op)); + __pyx_r = __pyx_v_op; + goto __pyx_L0; + + __pyx_r = ((arrayobject *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("cpython.array.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_op); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":147 + * return op + * + * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: # <<<<<<<<<<<<<< + * """ efficent appending of new stuff of same type + * (e.g. of same array type) + */ + +static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *__pyx_v_self, char *__pyx_v_stuff, Py_ssize_t __pyx_v_n) { + Py_ssize_t __pyx_v_itemsize; + Py_ssize_t __pyx_v_orgsize; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("extend_buffer", 0); + + /* "array.pxd":151 + * (e.g. of same array type) + * n: number of elements (not number of bytes!) """ + * cdef Py_ssize_t itemsize = self.ob_descr.itemsize # <<<<<<<<<<<<<< + * cdef Py_ssize_t orgsize = Py_SIZE(self) + * resize_smart(self, orgsize + n) + */ + __pyx_t_1 = __pyx_v_self->ob_descr->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "array.pxd":152 + * n: number of elements (not number of bytes!) """ + * cdef Py_ssize_t itemsize = self.ob_descr.itemsize + * cdef Py_ssize_t orgsize = Py_SIZE(self) # <<<<<<<<<<<<<< + * resize_smart(self, orgsize + n) + * memcpy(self.data.as_chars + orgsize * itemsize, stuff, n * itemsize) + */ + __pyx_v_orgsize = Py_SIZE(((PyObject *)__pyx_v_self)); + + /* "array.pxd":153 + * cdef Py_ssize_t itemsize = self.ob_descr.itemsize + * cdef Py_ssize_t orgsize = Py_SIZE(self) + * resize_smart(self, orgsize + n) # <<<<<<<<<<<<<< + * memcpy(self.data.as_chars + orgsize * itemsize, stuff, n * itemsize) + * return 0 + */ + __pyx_t_1 = resize_smart(__pyx_v_self, (__pyx_v_orgsize + __pyx_v_n)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "array.pxd":154 + * cdef Py_ssize_t orgsize = Py_SIZE(self) + * resize_smart(self, orgsize + n) + * memcpy(self.data.as_chars + orgsize * itemsize, stuff, n * itemsize) # <<<<<<<<<<<<<< + * return 0 + * + */ + memcpy((__pyx_v_self->data.as_chars + (__pyx_v_orgsize * __pyx_v_itemsize)), __pyx_v_stuff, (__pyx_v_n * __pyx_v_itemsize)); + + /* "array.pxd":155 + * resize_smart(self, orgsize + n) + * memcpy(self.data.as_chars + orgsize * itemsize, stuff, n * itemsize) + * return 0 # <<<<<<<<<<<<<< + * + * cdef inline int extend(array self, array other) except -1: + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("cpython.array.extend_buffer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":157 + * return 0 + * + * cdef inline int extend(array self, array other) except -1: # <<<<<<<<<<<<<< + * """ extend array with data from another array; types must match. """ + * if self.ob_descr.typecode != other.ob_descr.typecode: + */ + +static CYTHON_INLINE int __pyx_f_7cpython_5array_extend(arrayobject *__pyx_v_self, arrayobject *__pyx_v_other) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("extend", 0); + + /* "array.pxd":159 + * cdef inline int extend(array self, array other) except -1: + * """ extend array with data from another array; types must match. """ + * if self.ob_descr.typecode != other.ob_descr.typecode: # <<<<<<<<<<<<<< + * PyErr_BadArgument() + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) + */ + __pyx_t_1 = ((__pyx_v_self->ob_descr->typecode != __pyx_v_other->ob_descr->typecode) != 0); + if (__pyx_t_1) { + + /* "array.pxd":160 + * """ extend array with data from another array; types must match. """ + * if self.ob_descr.typecode != other.ob_descr.typecode: + * PyErr_BadArgument() # <<<<<<<<<<<<<< + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) + * + */ + __pyx_t_2 = PyErr_BadArgument(); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "array.pxd":161 + * if self.ob_descr.typecode != other.ob_descr.typecode: + * PyErr_BadArgument() + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) # <<<<<<<<<<<<<< + * + * cdef inline void zero(array op): + */ + __pyx_t_2 = __pyx_f_7cpython_5array_extend_buffer(__pyx_v_self, __pyx_v_other->data.as_chars, Py_SIZE(((PyObject *)__pyx_v_other))); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("cpython.array.extend", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":163 + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) + * + * cdef inline void zero(array op): # <<<<<<<<<<<<<< + * """ set all elements of array to zero. """ + * memset(op.data.as_chars, 0, Py_SIZE(op) * op.ob_descr.itemsize) + */ + +static CYTHON_INLINE void __pyx_f_7cpython_5array_zero(arrayobject *__pyx_v_op) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("zero", 0); + + /* "array.pxd":165 + * cdef inline void zero(array op): + * """ set all elements of array to zero. """ + * memset(op.data.as_chars, 0, Py_SIZE(op) * op.ob_descr.itemsize) # <<<<<<<<<<<<<< + */ + memset(__pyx_v_op->data.as_chars, 0, (Py_SIZE(((PyObject *)__pyx_v_op)) * __pyx_v_op->ob_descr->itemsize)); + + __Pyx_RefNannyFinishContext(); +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "numpy.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "numpy.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "numpy.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "numpy.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "numpy.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "numpy.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_3) { + + /* "numpy.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "numpy.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "numpy.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "numpy.pxd":222 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "numpy.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { + + /* "numpy.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "numpy.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "numpy.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "numpy.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "numpy.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "numpy.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "numpy.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "numpy.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "numpy.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "numpy.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "numpy.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "numpy.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "numpy.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "numpy.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "numpy.pxd":251 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "numpy.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; + + /* "numpy.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); + if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "numpy.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_1) { + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "numpy.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k__b; + break; + + /* "numpy.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k__B; + break; + + /* "numpy.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k__h; + break; + + /* "numpy.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k__H; + break; + + /* "numpy.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k__i; + break; + + /* "numpy.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k__I; + break; + + /* "numpy.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k__l; + break; + + /* "numpy.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k__L; + break; + + /* "numpy.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k__q; + break; + + /* "numpy.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k__Q; + break; + + /* "numpy.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k__f; + break; + + /* "numpy.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k__d; + break; + + /* "numpy.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k__g; + break; + + /* "numpy.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k__Zf; + break; + + /* "numpy.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k__Zd; + break; + + /* "numpy.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k__Zg; + break; + + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k__O; + break; + default: + + /* "numpy.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_13), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "numpy.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "numpy.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "numpy.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "numpy.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "numpy.pxd":285 + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + * &offset) # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "numpy.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + __pyx_L11:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "numpy.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "numpy.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "numpy.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "numpy.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "numpy.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "numpy.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + long __pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "numpy.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); + __pyx_t_3 = 0; + + /* "numpy.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "numpy.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { + PyObject* sequence = ((PyObject *)__pyx_v_fields); + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); + __pyx_t_4 = 0; + + /* "numpy.pxd":798 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + + /* "numpy.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + + /* "numpy.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_7) { + __pyx_t_8 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_8 = __pyx_t_7; + } + if (!__pyx_t_8) { + + /* "numpy.pxd":802 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + __pyx_t_9 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_10 = __pyx_t_9; + } else { + __pyx_t_10 = __pyx_t_7; + } + __pyx_t_7 = __pyx_t_10; + } else { + __pyx_t_7 = __pyx_t_8; + } + if (__pyx_t_7) { + + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + + /* "numpy.pxd":813 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_7) break; + + /* "numpy.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "numpy.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "numpy.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); + } + + /* "numpy.pxd":818 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); + + /* "numpy.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_7 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_7) { + + /* "numpy.pxd":821 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_3); + __pyx_t_3 = 0; + + /* "numpy.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_7 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_7) { + + /* "numpy.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_18), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 98; + goto __pyx_L13; + } + + /* "numpy.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 66; + goto __pyx_L13; + } + + /* "numpy.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 104; + goto __pyx_L13; + } + + /* "numpy.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 72; + goto __pyx_L13; + } + + /* "numpy.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 105; + goto __pyx_L13; + } + + /* "numpy.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 73; + goto __pyx_L13; + } + + /* "numpy.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 108; + goto __pyx_L13; + } + + /* "numpy.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 76; + goto __pyx_L13; + } + + /* "numpy.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 113; + goto __pyx_L13; + } + + /* "numpy.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 81; + goto __pyx_L13; + } + + /* "numpy.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 102; + goto __pyx_L13; + } + + /* "numpy.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 100; + goto __pyx_L13; + } + + /* "numpy.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 103; + goto __pyx_L13; + } + + /* "numpy.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 79; + goto __pyx_L13; + } + /*else*/ { + + /* "numpy.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_13), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L13:; + + /* "numpy.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_12; + } + __pyx_L11:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "numpy.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":965 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "numpy.pxd":967 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "numpy.pxd":968 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":970 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "numpy.pxd":971 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "numpy.pxd":972 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "numpy.pxd":973 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":975 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "numpy.pxd":976 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":977 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":979 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + __Pyx_NAMESTR("_hashing"), + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, + {&__pyx_kp_u_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 1, 0, 0}, + {&__pyx_kp_u_14, __pyx_k_14, sizeof(__pyx_k_14), 0, 1, 0, 0}, + {&__pyx_kp_u_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 1, 0, 0}, + {&__pyx_kp_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 0}, + {&__pyx_kp_s_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 1, 0}, + {&__pyx_n_s_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 1, 1}, + {&__pyx_kp_s_4, __pyx_k_4, sizeof(__pyx_k_4), 0, 0, 1, 0}, + {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, + {&__pyx_kp_u_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 1, 0, 0}, + {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s__TypeError, __pyx_k__TypeError, sizeof(__pyx_k__TypeError), 0, 0, 1, 1}, + {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, + {&__pyx_n_s____import__, __pyx_k____import__, sizeof(__pyx_k____import__), 0, 0, 1, 1}, + {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, + {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, + {&__pyx_n_s__array, __pyx_k__array, sizeof(__pyx_k__array), 0, 0, 1, 1}, + {&__pyx_n_s__capacity, __pyx_k__capacity, sizeof(__pyx_k__capacity), 0, 0, 1, 1}, + {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, + {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, + {&__pyx_n_s__encode, __pyx_k__encode, sizeof(__pyx_k__encode), 0, 0, 1, 1}, + {&__pyx_n_s__f, __pyx_k__f, sizeof(__pyx_k__f), 0, 0, 1, 1}, + {&__pyx_n_s__frombuffer, __pyx_k__frombuffer, sizeof(__pyx_k__frombuffer), 0, 0, 1, 1}, + {&__pyx_n_s__h, __pyx_k__h, sizeof(__pyx_k__h), 0, 0, 1, 1}, + {&__pyx_n_s__i, __pyx_k__i, sizeof(__pyx_k__i), 0, 0, 1, 1}, + {&__pyx_n_s__indices, __pyx_k__indices, sizeof(__pyx_k__indices), 0, 0, 1, 1}, + {&__pyx_n_s__indices_a, __pyx_k__indices_a, sizeof(__pyx_k__indices_a), 0, 0, 1, 1}, + {&__pyx_n_s__indptr, __pyx_k__indptr, sizeof(__pyx_k__indptr), 0, 0, 1, 1}, + {&__pyx_n_s__int32, __pyx_k__int32, sizeof(__pyx_k__int32), 0, 0, 1, 1}, + {&__pyx_n_s__n_features, __pyx_k__n_features, sizeof(__pyx_k__n_features), 0, 0, 1, 1}, + {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, + {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, + {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, + {&__pyx_n_s__raw_X, __pyx_k__raw_X, sizeof(__pyx_k__raw_X), 0, 0, 1, 1}, + {&__pyx_n_s__resize, __pyx_k__resize, sizeof(__pyx_k__resize), 0, 0, 1, 1}, + {&__pyx_n_s__size, __pyx_k__size, sizeof(__pyx_k__size), 0, 0, 1, 1}, + {&__pyx_n_s__transform, __pyx_k__transform, sizeof(__pyx_k__transform), 0, 0, 1, 1}, + {&__pyx_n_s__v, __pyx_k__v, sizeof(__pyx_k__v), 0, 0, 1, 1}, + {&__pyx_n_s__value, __pyx_k__value, sizeof(__pyx_k__value), 0, 0, 1, 1}, + {&__pyx_n_s__values, __pyx_k__values, sizeof(__pyx_k__values), 0, 0, 1, 1}, + {&__pyx_n_s__x, __pyx_k__x, sizeof(__pyx_k__x), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s__TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "sklearn/feature_extraction/_hashing.pyx":35 + * cdef array.array indices + * cdef array.array indptr + * indices = array.array("i") # <<<<<<<<<<<<<< + * indptr = array.array("i", [0]) + * + */ + __pyx_k_tuple_1 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__i)); if (unlikely(!__pyx_k_tuple_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_1); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_1)); + + /* "sklearn/feature_extraction/_hashing.pyx":51 + * + * if isinstance(f, unicode): + * f = f.encode("utf-8") # <<<<<<<<<<<<<< + * # Need explicit type check because Murmurhash does not propagate + * # all exceptions. Add "except *" there? + */ + __pyx_k_tuple_3 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_2)); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_3); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_3)); + + /* "sklearn/feature_extraction/_hashing.pyx":55 + * # all exceptions. Add "except *" there? + * elif not isinstance(f, bytes): + * raise TypeError("feature names must be strings") # <<<<<<<<<<<<<< + * h = murmurhash3_bytes_s32(f, 0) + * + */ + __pyx_k_tuple_5 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_4)); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_5); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); + + /* "sklearn/feature_extraction/_hashing.pyx":76 + * indices_a = np.frombuffer(indices, dtype=np.int32) + * else: + * indices_a = np.empty(0, dtype=np.int32) # <<<<<<<<<<<<<< + * return (indices_a, np.frombuffer(indptr, dtype=np.int32), values[:size]) + */ + __pyx_k_tuple_6 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_6); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); + + /* "numpy.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_k_tuple_8 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_7)); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_8); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); + + /* "numpy.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_k_tuple_10 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_9)); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_10); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_k_tuple_12 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_11)); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_12); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + + /* "numpy.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_k_tuple_15 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_14)); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_15); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); + + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_k_tuple_16 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_11)); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_16); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); + + /* "numpy.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_k_tuple_18 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_17)); if (unlikely(!__pyx_k_tuple_18)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_18); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_18)); + + /* "sklearn/feature_extraction/_hashing.pyx":18 + * @cython.boundscheck(False) + * @cython.cdivision(True) + * def transform(raw_X, Py_ssize_t n_features, dtype): # <<<<<<<<<<<<<< + * """Guts of FeatureHasher.transform. + * + */ + __pyx_k_tuple_19 = PyTuple_Pack(14, ((PyObject *)__pyx_n_s__raw_X), ((PyObject *)__pyx_n_s__n_features), ((PyObject *)__pyx_n_s__dtype), ((PyObject *)__pyx_n_s__h), ((PyObject *)__pyx_n_s__value), ((PyObject *)__pyx_n_s__indices), ((PyObject *)__pyx_n_s__indptr), ((PyObject *)__pyx_n_s__capacity), ((PyObject *)__pyx_n_s__size), ((PyObject *)__pyx_n_s__values), ((PyObject *)__pyx_n_s__x), ((PyObject *)__pyx_n_s__f), ((PyObject *)__pyx_n_s__v), ((PyObject *)__pyx_n_s__indices_a)); if (unlikely(!__pyx_k_tuple_19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_19); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_19)); + __pyx_k_codeobj_20 = (PyObject*)__Pyx_PyCode_New(3, 0, 14, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_19, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_21, __pyx_n_s__transform, 18, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC init_hashing(void); /*proto*/ +PyMODINIT_FUNC init_hashing(void) +#else +PyMODINIT_FUNC PyInit__hashing(void); /*proto*/ +PyMODINIT_FUNC PyInit__hashing(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__hashing(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_hashing"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.feature_extraction._hashing")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.feature_extraction._hashing", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__feature_extraction___hashing) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), 0); if (unlikely(!__pyx_ptype_7cpython_4bool_bool)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), 0); if (unlikely(!__pyx_ptype_7cpython_7complex_complex)) {__pyx_filename = __pyx_f[5]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_5array_array = __Pyx_ImportType("array", "array", sizeof(arrayobject), 0); if (unlikely(!__pyx_ptype_7cpython_5array_array)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + __pyx_t_1 = __Pyx_ImportModule("sklearn.utils.murmurhash"); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_ImportFunction(__pyx_t_1, "murmurhash3_bytes_s32", (void (**)(void))&__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32, "__pyx_t_5numpy_int32_t (PyObject *, unsigned int, int __pyx_skip_dispatch)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /*--- Execution code ---*/ + + /* "sklearn/feature_extraction/_hashing.pyx":4 + * # License: BSD 3 clause + * + * import array # <<<<<<<<<<<<<< + * from cpython cimport array + * cimport cython + */ + __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s__array), 0, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__array, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":9 + * from libc.stdlib cimport abs + * cimport numpy as np + * import numpy as np # <<<<<<<<<<<<<< + * + * from sklearn.utils.murmurhash cimport murmurhash3_bytes_s32 + */ + __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__np, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":13 + * from sklearn.utils.murmurhash cimport murmurhash3_bytes_s32 + * + * np.import_array() # <<<<<<<<<<<<<< + * + * + */ + import_array(); + + /* "sklearn/feature_extraction/_hashing.pyx":18 + * @cython.boundscheck(False) + * @cython.cdivision(True) + * def transform(raw_X, Py_ssize_t n_features, dtype): # <<<<<<<<<<<<<< + * """Guts of FeatureHasher.transform. + * + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_18feature_extraction_8_hashing_1transform, NULL, __pyx_n_s_22); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__transform, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/feature_extraction/_hashing.pyx":1 + * # Author: Lars Buitinck # <<<<<<<<<<<<<< + * # License: BSD 3 clause + * + */ + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + + /* "numpy.pxd":975 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.feature_extraction._hashing", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.feature_extraction._hashing"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { + #endif +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { + int r; + if (!j) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { + PyObject* old = PyList_GET_ITEM(o, n); + Py_INCREF(v); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 1; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return -1; + } + } + return m->sq_ass_item(o, i, v); + } + } +#else +#if CYTHON_COMPILING_IN_PYPY + if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) { +#else + if (is_list || PySequence_Check(o)) { +#endif + return PySequence_SetItem(o, i, v); + } +#endif + return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); +} + +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { +#if CYTHON_COMPILING_IN_CPYTHON + PyMappingMethods* mp; +#if PY_MAJOR_VERSION < 3 + PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; + if (likely(ms && ms->sq_slice)) { + if (!has_cstart) { + if (_py_start && (*_py_start != Py_None)) { + cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); + if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstart = 0; + } + if (!has_cstop) { + if (_py_stop && (*_py_stop != Py_None)) { + cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); + if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstop = PY_SSIZE_T_MAX; + } + if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { + Py_ssize_t l = ms->sq_length(obj); + if (likely(l >= 0)) { + if (cstop < 0) { + cstop += l; + if (cstop < 0) cstop = 0; + } + if (cstart < 0) { + cstart += l; + if (cstart < 0) cstart = 0; + } + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + goto bad; + } + } + return ms->sq_slice(obj, cstart, cstop); + } +#endif + mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_subscript)) +#endif + { + PyObject* result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyInt_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyInt_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_COMPILING_IN_CPYTHON + result = mp->mp_subscript(obj, py_slice); +#else + result = PyObject_GetItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } + PyErr_Format(PyExc_TypeError, + "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); +bad: + return NULL; +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s____import__); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32 val) { + const npy_int32 neg_one = (npy_int32)-1, const_zero = (npy_int32)0; + const int is_unsigned = const_zero < neg_one; + if ((sizeof(npy_int32) == sizeof(char)) || + (sizeof(npy_int32) == sizeof(short))) { + return PyInt_FromLong((long)val); + } else if ((sizeof(npy_int32) == sizeof(int)) || + (sizeof(npy_int32) == sizeof(long))) { + if (is_unsigned) + return PyLong_FromUnsignedLong((unsigned long)val); + else + return PyInt_FromLong((long)val); + } else if (sizeof(npy_int32) == sizeof(PY_LONG_LONG)) { + if (is_unsigned) + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); + else + return PyLong_FromLongLong((PY_LONG_LONG)val); + } else { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + return _PyLong_FromByteArray(bytes, sizeof(npy_int32), + little, !is_unsigned); + } +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { + const unsigned char neg_one = (unsigned char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned char" : + "value too large to convert to unsigned char"); + } + return (unsigned char)-1; + } + return (unsigned char)val; + } + return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { + const unsigned short neg_one = (unsigned short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned short" : + "value too large to convert to unsigned short"); + } + return (unsigned short)-1; + } + return (unsigned short)val; + } + return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { + const unsigned int neg_one = (unsigned int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned int" : + "value too large to convert to unsigned int"); + } + return (unsigned int)-1; + } + return (unsigned int)val; + } + return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { + const char neg_one = (char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to char" : + "value too large to convert to char"); + } + return (char)-1; + } + return (char)val; + } + return (char)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { + const short neg_one = (short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to short" : + "value too large to convert to short"); + } + return (short)-1; + } + return (short)val; + } + return (short)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { + const signed char neg_one = (signed char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed char" : + "value too large to convert to signed char"); + } + return (signed char)-1; + } + return (signed char)val; + } + return (signed char)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { + const signed short neg_one = (signed short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed short" : + "value too large to convert to signed short"); + } + return (signed short)-1; + } + return (signed short)val; + } + return (signed short)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { + const signed int neg_one = (signed int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed int" : + "value too large to convert to signed int"); + } + return (signed int)-1; + } + return (signed int)val; + } + return (signed int)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { + const unsigned long neg_one = (unsigned long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (unsigned long)PyLong_AsLong(x); + } + } else { + unsigned long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned long)-1; + val = __Pyx_PyInt_AsUnsignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { + const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + unsigned PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsUnsignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { + const long neg_one = (long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (long)PyLong_AsLong(x); + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long)-1; + val = __Pyx_PyInt_AsLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { + const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { + const signed long neg_one = (signed long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (signed long)PyLong_AsLong(x); + } + } else { + signed long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed long)-1; + val = __Pyx_PyInt_AsSignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { + const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + signed PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsSignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%s.%s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + #if PY_VERSION_HEX < 0x02050000 + if (PyErr_Warn(NULL, warning) < 0) goto bad; + #else + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + #endif + } + else if ((size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%s.%s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportFunction +#define __PYX_HAVE_RT_ImportFunction +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); + if (!d) + goto bad; + cobj = PyDict_GetItemString(d, funcname); + if (!cobj) { + PyErr_Format(PyExc_ImportError, + "%s does not export expected C function %s", + PyModule_GetName(module), funcname); + goto bad; + } +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3 && PY_MINOR_VERSION==0) + if (!PyCapsule_IsValid(cobj, sig)) { + PyErr_Format(PyExc_TypeError, + "C function %s.%s has wrong signature (expected %s, got %s)", + PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); + goto bad; + } + tmp.p = PyCapsule_GetPointer(cobj, sig); +#else + {const char *desc, *s1, *s2; + desc = (const char *)PyCObject_GetDesc(cobj); + if (!desc) + goto bad; + s1 = desc; s2 = sig; + while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } + if (*s1 != *s2) { + PyErr_Format(PyExc_TypeError, + "C function %s.%s has wrong signature (expected %s, got %s)", + PyModule_GetName(module), funcname, sig, desc); + goto bad; + } + tmp.p = PyCObject_AsVoidPtr(cobj);} +#endif + *f = tmp.fp; + if (!(*f)) + goto bad; + Py_DECREF(d); + return 0; +bad: + Py_XDECREF(d); + return -1; +} +#endif + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (r < 0) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_MAJOR_VERSION < 3 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%s__ returned non-%s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject* x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { + unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); + if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); + return (size_t)-1; + } + return (size_t)val; +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/feature_extraction/_hashing.pyx b/sklearn/feature_extraction/_hashing.pyx new file mode 100644 index 0000000000000..d291b15f7c655 --- /dev/null +++ b/sklearn/feature_extraction/_hashing.pyx @@ -0,0 +1,77 @@ +# Author: Lars Buitinck +# License: BSD 3 clause + +import array +from cpython cimport array +cimport cython +from libc.stdlib cimport abs +cimport numpy as np +import numpy as np + +from sklearn.utils.murmurhash cimport murmurhash3_bytes_s32 + +np.import_array() + + +@cython.boundscheck(False) +@cython.cdivision(True) +def transform(raw_X, Py_ssize_t n_features, dtype): + """Guts of FeatureHasher.transform. + + Returns + ------- + n_samples : integer + indices, indptr, values : lists + For constructing a scipy.sparse.csr_matrix. + + """ + assert n_features > 0 + + cdef np.int32_t h + cdef double value + + cdef array.array indices + cdef array.array indptr + indices = array.array("i") + indptr = array.array("i", [0]) + + # Since Python array does not understand Numpy dtypes, we grow the indices + # and values arrays ourselves. Use a Py_ssize_t capacity for safety. + cdef Py_ssize_t capacity = 8192 # arbitrary + cdef np.int32_t size = 0 + cdef np.ndarray values = np.empty(capacity, dtype=dtype) + + for x in raw_X: + for f, v in x: + value = v + if value == 0: + continue + + if isinstance(f, unicode): + f = f.encode("utf-8") + # Need explicit type check because Murmurhash does not propagate + # all exceptions. Add "except *" there? + elif not isinstance(f, bytes): + raise TypeError("feature names must be strings") + h = murmurhash3_bytes_s32(f, 0) + + array.resize_smart(indices, len(indices) + 1) + indices[len(indices) - 1] = abs(h) % n_features + value *= (h >= 0) * 2 - 1 + values[size] = value + size += 1 + + if size == capacity: + capacity *= 2 + # can't use resize member because there might be multiple + # references to the arrays due to Cython's error checking + values = np.resize(values, capacity) + + array.resize_smart(indptr, len(indptr) + 1) + indptr[len(indptr) - 1] = size + + if len(indices): + indices_a = np.frombuffer(indices, dtype=np.int32) + else: # workaround for NumPy < 1.7.0 + indices_a = np.empty(0, dtype=np.int32) + return (indices_a, np.frombuffer(indptr, dtype=np.int32), values[:size]) diff --git a/sklearn/feature_extraction/dict_vectorizer.py b/sklearn/feature_extraction/dict_vectorizer.py index fc97f9e92503a..af669aff095ef 100644 --- a/sklearn/feature_extraction/dict_vectorizer.py +++ b/sklearn/feature_extraction/dict_vectorizer.py @@ -1,24 +1,27 @@ -# Author: Lars Buitinck -# License: BSD-style. +# Authors: Lars Buitinck +# Dan Blanchard +# License: BSD 3 clause -from collections import Mapping, Sequence +from array import array +from collections import Mapping from operator import itemgetter import numpy as np import scipy.sparse as sp from ..base import BaseEstimator, TransformerMixin -from ..utils import atleast2d_or_csr +from ..externals import six +from ..externals.six.moves import xrange +from ..utils import check_array, tosequence +from ..utils.fixes import frombuffer_empty def _tosequence(X): """Turn X into a sequence or ndarray, avoiding a copy if possible.""" - if isinstance(X, Mapping): + if isinstance(X, Mapping): # single sample return [X] - elif isinstance(X, (Sequence, np.ndarray)): - return X else: - return list(X) + return tosequence(X) class DictVectorizer(BaseEstimator, TransformerMixin): @@ -48,6 +51,18 @@ class DictVectorizer(BaseEstimator, TransformerMixin): sparse: boolean, optional. Whether transform should produce scipy.sparse matrices. True by default. + sort: boolean, optional. + Whether ``feature_names_`` and ``vocabulary_`` should be sorted when fitting. + True by default. + + Attributes + ---------- + vocabulary_ : dict + A dictionary mapping feature names to feature indices. + + feature_names_ : list + A list of length n_features containing the feature names (e.g., "f=ham" + and "f=spam"). Examples -------- @@ -63,12 +78,20 @@ class DictVectorizer(BaseEstimator, TransformerMixin): True >>> v.transform({'foo': 4, 'unseen_feature': 3}) array([[ 0., 0., 4.]]) + + See also + -------- + FeatureHasher : performs vectorization using only a hash function. + sklearn.preprocessing.OneHotEncoder : handles nominal/categorical features + encoded as columns of integers. """ - def __init__(self, dtype=np.float64, separator="=", sparse=True): + def __init__(self, dtype=np.float64, separator="=", sparse=True, + sort=True): self.dtype = dtype self.separator = separator self.sparse = sparse + self.sort = sort def fit(self, X, y=None): """Learn a list of feature name -> indices mappings. @@ -84,27 +107,107 @@ def fit(self, X, y=None): ------- self """ - X = _tosequence(X) + feature_names = [] + vocab = {} - # collect all the possible feature names - feature_names = set() for x in X: - for f, v in x.iteritems(): - if isinstance(v, basestring): + for f, v in six.iteritems(x): + if isinstance(v, six.string_types): f = "%s%s%s" % (f, self.separator, v) - feature_names.add(f) + if f not in vocab: + feature_names.append(f) + vocab[f] = len(vocab) + + if self.sort: + feature_names.sort() + vocab = dict((f, i) for i, f in enumerate(feature_names)) - # sort the feature names to define the mapping - feature_names = sorted(feature_names) - self.vocabulary_ = dict((f, i) for i, f in enumerate(feature_names)) self.feature_names_ = feature_names + self.vocabulary_ = vocab return self + def _transform(self, X, fitting): + # Sanity check: Python's array has no way of explicitly requesting the + # signed 32-bit integers that scipy.sparse needs, so we use the next + # best thing: typecode "i" (int). However, if that gives larger or + # smaller integers than 32-bit ones, np.frombuffer screws up. + assert array("i").itemsize == 4, ( + "sizeof(int) != 4 on your platform; please report this at" + " https://github.com/scikit-learn/scikit-learn/issues and" + " include the output from platform.platform() in your bug report") + + dtype = self.dtype + if fitting: + feature_names = [] + vocab = {} + else: + feature_names = self.feature_names_ + vocab = self.vocabulary_ + + # Process everything as sparse regardless of setting + X = [X] if isinstance(X, Mapping) else X + + indices = array("i") + indptr = array("i", [0]) + # XXX we could change values to an array.array as well, but it + # would require (heuristic) conversion of dtype to typecode... + values = [] + + # collect all the possible feature names and build sparse matrix at + # same time + for x in X: + for f, v in six.iteritems(x): + if isinstance(v, six.string_types): + f = "%s%s%s" % (f, self.separator, v) + v = 1 + if f in vocab: + indices.append(vocab[f]) + values.append(dtype(v)) + else: + if fitting: + feature_names.append(f) + vocab[f] = len(vocab) + indices.append(vocab[f]) + values.append(dtype(v)) + + indptr.append(len(indices)) + + if len(indptr) == 1: + raise ValueError("Sample sequence X is empty.") + + indices = frombuffer_empty(indices, dtype=np.intc) + indptr = np.frombuffer(indptr, dtype=np.intc) + shape = (len(indptr) - 1, len(vocab)) + + result_matrix = sp.csr_matrix((values, indices, indptr), + shape=shape, dtype=dtype) + + # Sort everything if asked + if fitting and self.sort: + feature_names.sort() + map_index = np.empty(len(feature_names), dtype=np.int32) + for new_val, f in enumerate(feature_names): + map_index[new_val] = vocab[f] + vocab[f] = new_val + result_matrix = result_matrix[:, map_index] + + if self.sparse: + result_matrix.sort_indices() + else: + result_matrix = result_matrix.toarray() + + if fitting: + self.feature_names_ = feature_names + self.vocabulary_ = vocab + + return result_matrix + def fit_transform(self, X, y=None): """Learn a list of feature name -> indices mappings and transform X. - Like fit(X) followed by transform(X). + Like fit(X) followed by transform(X), but does not require + materializing X in memory. Parameters ---------- @@ -118,9 +221,7 @@ def fit_transform(self, X, y=None): Xa : {array, sparse matrix} Feature vectors; always 2-d. """ - X = _tosequence(X) - self.fit(X) - return self.transform(X) + return self._transform(X, fitting=True) def inverse_transform(self, X, dict_type=dict): """Transform array or sparse matrix X back to feature mappings. @@ -145,22 +246,23 @@ def inverse_transform(self, X, dict_type=dict): D : list of dict_type objects, length = n_samples Feature mappings for the samples in X. """ - X = atleast2d_or_csr(X) # COO matrix is not subscriptable + # COO matrix is not subscriptable + X = check_array(X, accept_sparse=['csr', 'csc']) + n_samples = X.shape[0] names = self.feature_names_ - Xd = [dict_type() for _ in xrange(X.shape[0])] + dicts = [dict_type() for _ in xrange(n_samples)] if sp.issparse(X): for i, j in zip(*X.nonzero()): - Xd[i][names[j]] = X[i, j] + dicts[i][names[j]] = X[i, j] else: - for i in xrange(X.shape[0]): - d = Xd[i] + for i, d in enumerate(dicts): for j, v in enumerate(X[i, :]): if v != 0: d[names[j]] = X[i, j] - return Xd + return dicts def transform(self, X, y=None): """Transform feature->value dicts to array or sparse matrix. @@ -180,40 +282,18 @@ def transform(self, X, y=None): Xa : {array, sparse matrix} Feature vectors; always 2-d. """ - dtype = self.dtype - vocab = self.vocabulary_ - if self.sparse: - X = [X] if isinstance(X, Mapping) else X - - i_ind = [] - j_ind = [] - values = [] - - for i, x in enumerate(X): - for f, v in x.iteritems(): - if isinstance(v, basestring): - f = "%s%s%s" % (f, self.separator, v) - v = 1 - try: - j = vocab[f] - i_ind.append(i) - j_ind.append(j) - values.append(dtype(v)) - except KeyError: - pass - - shape = (i + 1, len(vocab)) - return sp.coo_matrix((values, (i_ind, j_ind)), - shape=shape, dtype=dtype) + return self._transform(X, fitting=False) else: + dtype = self.dtype + vocab = self.vocabulary_ X = _tosequence(X) Xa = np.zeros((len(X), len(vocab)), dtype=dtype) for i, x in enumerate(X): - for f, v in x.iteritems(): - if isinstance(v, basestring): + for f, v in six.iteritems(x): + if isinstance(v, six.string_types): f = "%s%s%s" % (f, self.separator, v) v = 1 try: @@ -251,7 +331,7 @@ def restrict(self, support, indices=False): new_vocab[names[i]] = len(new_vocab) self.vocabulary_ = new_vocab - self.feature_names_ = [f for f, i in sorted(new_vocab.iteritems(), + self.feature_names_ = [f for f, i in sorted(six.iteritems(new_vocab), key=itemgetter(1))] return self diff --git a/sklearn/feature_extraction/hashing.py b/sklearn/feature_extraction/hashing.py new file mode 100644 index 0000000000000..87ea0e35ff727 --- /dev/null +++ b/sklearn/feature_extraction/hashing.py @@ -0,0 +1,140 @@ +# Author: Lars Buitinck +# License: BSD 3 clause + +import numbers + +import numpy as np +import scipy.sparse as sp + +from . import _hashing +from ..base import BaseEstimator, TransformerMixin + + +def _iteritems(d): + """Like d.iteritems, but accepts any collections.Mapping.""" + return d.iteritems() if hasattr(d, "iteritems") else d.items() + + +class FeatureHasher(BaseEstimator, TransformerMixin): + """Implements feature hashing, aka the hashing trick. + + This class turns sequences of symbolic feature names (strings) into + scipy.sparse matrices, using a hash function to compute the matrix column + corresponding to a name. The hash function employed is the signed 32-bit + version of Murmurhash3. + + Feature names of type byte string are used as-is. Unicode strings are + converted to UTF-8 first, but no Unicode normalization is done. + + This class is a low-memory alternative to DictVectorizer and + CountVectorizer, intended for large-scale (online) learning and situations + where memory is tight, e.g. when running prediction code on embedded + devices. + + Parameters + ---------- + n_features : integer, optional + The number of features (columns) in the output matrices. Small numbers + of features are likely to cause hash collisions, but large numbers + will cause larger coefficient dimensions in linear learners. + dtype : numpy type, optional + The type of feature values. Passed to scipy.sparse matrix constructors + as the dtype argument. Do not set this to bool, np.boolean or any + unsigned integer type. + input_type : string, optional + Either "dict" (the default) to accept dictionaries over + (feature_name, value); "pair" to accept pairs of (feature_name, value); + or "string" to accept single strings. + feature_name should be a string, while value should be a number. + In the case of "string", a value of 1 is implied. + The feature_name is hashed to find the appropriate column for the + feature. The value's sign might be flipped in the output (but see + non_negative, below). + non_negative : boolean, optional, default np.float64 + Whether output matrices should contain non-negative values only; + effectively calls abs on the matrix prior to returning it. + When True, output values can be interpreted as frequencies. + When False, output values will have expected value zero. + + See also + -------- + DictVectorizer : vectorizes string-valued features using a hash table. + sklearn.preprocessing.OneHotEncoder : handles nominal/categorical features + encoded as columns of integers. + """ + + def __init__(self, n_features=(2 ** 20), input_type="dict", + dtype=np.float64, non_negative=False): + self._validate_params(n_features, input_type) + + self.dtype = dtype + self.input_type = input_type + self.n_features = n_features + self.non_negative = non_negative + + @staticmethod + def _validate_params(n_features, input_type): + # strangely, np.int16 instances are not instances of Integral, + # while np.int64 instances are... + if not isinstance(n_features, (numbers.Integral, np.integer)): + raise TypeError("n_features must be integral, got %r (%s)." + % (n_features, type(n_features))) + elif n_features < 1 or n_features >= 2 ** 31: + raise ValueError("Invalid number of features (%d)." % n_features) + + if input_type not in ("dict", "pair", "string"): + raise ValueError("input_type must be 'dict', 'pair' or 'string'," + " got %r." % input_type) + + def fit(self, X=None, y=None): + """No-op. + + This method doesn't do anything. It exists purely for compatibility + with the scikit-learn transformer API. + + Returns + ------- + self : FeatureHasher + + """ + # repeat input validation for grid search (which calls set_params) + self._validate_params(self.n_features, self.input_type) + return self + + def transform(self, raw_X, y=None): + """Transform a sequence of instances to a scipy.sparse matrix. + + Parameters + ---------- + raw_X : iterable over iterable over raw features, length = n_samples + Samples. Each sample must be iterable an (e.g., a list or tuple) + containing/generating feature names (and optionally values, see + the input_type constructor argument) which will be hashed. + raw_X need not support the len function, so it can be the result + of a generator; n_samples is determined on the fly. + y : (ignored) + + Returns + ------- + X : scipy.sparse matrix, shape = (n_samples, self.n_features) + Feature matrix, for use with estimators or further transformers. + + """ + raw_X = iter(raw_X) + if self.input_type == "dict": + raw_X = (_iteritems(d) for d in raw_X) + elif self.input_type == "string": + raw_X = (((f, 1) for f in x) for x in raw_X) + indices, indptr, values = \ + _hashing.transform(raw_X, self.n_features, self.dtype) + n_samples = indptr.shape[0] - 1 + + if n_samples == 0: + raise ValueError("Cannot vectorize empty sequence.") + + X = sp.csr_matrix((values, indices, indptr), dtype=self.dtype, + shape=(n_samples, self.n_features)) + X.sum_duplicates() # also sorts the indices + if self.non_negative: + np.abs(X.data, X.data) + return X diff --git a/sklearn/feature_extraction/image.py b/sklearn/feature_extraction/image.py index 52db2fbb89be9..7ca737449aa81 100644 --- a/sklearn/feature_extraction/image.py +++ b/sklearn/feature_extraction/image.py @@ -7,14 +7,16 @@ # Gael Varoquaux # Olivier Grisel # Vlad Niculae -# License: BSD +# License: BSD 3 clause from itertools import product +import numbers import numpy as np from scipy import sparse +from numpy.lib.stride_tricks import as_strided -from ..utils.fixes import in1d -from ..utils import array2d, check_random_state +from ..utils import check_array, check_random_state +from ..utils.fixes import astype from ..base import BaseEstimator __all__ = ['PatchExtractor', @@ -52,11 +54,11 @@ def _make_edges_3d(n_x, n_y, n_z=1): def _compute_gradient_3d(edges, img): n_x, n_y, n_z = img.shape gradient = np.abs(img[edges[0] // (n_y * n_z), - (edges[0] % (n_y * n_z)) // n_z, - (edges[0] % (n_y * n_z)) % n_z] - - img[edges[1] // (n_y * n_z), - (edges[1] % (n_y * n_z)) // n_z, - (edges[1] % (n_y * n_z)) % n_z]) + (edges[0] % (n_y * n_z)) // n_z, + (edges[0] % (n_y * n_z)) % n_z] - + img[edges[1] // (n_y * n_z), + (edges[1] % (n_y * n_z)) // n_z, + (edges[1] % (n_y * n_z)) % n_z]) return gradient @@ -66,8 +68,8 @@ def _mask_edges_weights(mask, edges, weights=None): """Apply a mask to edges (weighted or not)""" inds = np.arange(mask.size) inds = inds[mask.ravel()] - ind_mask = np.logical_and(in1d(edges[0], inds), - in1d(edges[1], inds)) + ind_mask = np.logical_and(np.in1d(edges[0], inds), + np.in1d(edges[1], inds)) edges = edges[:, ind_mask] if weights is not None: weights = weights[ind_mask] @@ -106,7 +108,8 @@ def _to_graph(n_x, n_y, n_z, mask=None, img=None, n_voxels = diag.size else: if mask is not None: - mask = mask.astype(np.bool) + mask = astype(mask, dtype=np.bool, copy=False) + mask = np.asarray(mask, dtype=np.bool) edges = _mask_edges_weights(mask, edges) n_voxels = np.sum(mask) else: @@ -123,7 +126,7 @@ def _to_graph(n_x, n_y, n_z, mask=None, img=None, (n_voxels, n_voxels), dtype=dtype) if return_as is np.ndarray: - return graph.todense() + return graph.toarray() return return_as(graph) @@ -144,6 +147,15 @@ def img_to_graph(img, mask=None, return_as=sparse.coo_matrix, dtype=None): dtype: None or dtype, optional The data of the returned sparse matrix. By default it is the dtype of img + + Notes + ===== + For sklearn versions 0.14.1 and prior, return_as=np.ndarray was handled + by returning a dense np.matrix instance. Going forward, np.ndarray + returns an np.ndarray, as expected. + + For compatibility, user code relying on this method should wrap its + calls in ``np.asarray`` to avoid type issues. """ img = np.atleast_3d(img) n_x, n_y, n_z = img.shape @@ -171,6 +183,15 @@ def grid_to_graph(n_x, n_y, n_z=1, mask=None, return_as=sparse.coo_matrix, The class to use to build the returned adjacency matrix. dtype: dtype, optional, default int The data of the returned sparse matrix. By default it is int + + Notes + ===== + For sklearn versions 0.14.1 and prior, return_as=np.ndarray was handled + by returning a dense np.matrix instance. Going forward, np.ndarray + returns an np.ndarray, as expected. + + For compatibility, user code relying on this method should wrap its + calls in ``np.asarray`` to avoid type issues. """ return _to_graph(n_x, n_y, n_z, mask=mask, return_as=return_as, dtype=dtype) @@ -179,6 +200,96 @@ def grid_to_graph(n_x, n_y, n_z=1, mask=None, return_as=sparse.coo_matrix, ############################################################################### # From an image to a set of small image patches +def _compute_n_patches(i_h, i_w, p_h, p_w, max_patches=None): + """Compute the number of patches that will be extracted in an image. + + Parameters + =========== + i_h: int + The image height + i_w: int + The image with + p_h: int + The height of a patch + p_w: int + The width of a patch + max_patches: integer or float, optional default is None + The maximum number of patches to extract. If max_patches is a float + between 0 and 1, it is taken to be a proportion of the total number + of patches. + """ + n_h = i_h - p_h + 1 + n_w = i_w - p_w + 1 + all_patches = n_h * n_w + + if max_patches: + if (isinstance(max_patches, (numbers.Integral)) + and max_patches < all_patches): + return max_patches + elif (isinstance(max_patches, (numbers.Real)) + and 0 < max_patches < 1): + return int(max_patches * all_patches) + else: + raise ValueError("Invalid value for max_patches: %r" % max_patches) + else: + return all_patches + + +def extract_patches(arr, patch_shape=8, extraction_step=1): + """Extracts patches of any n-dimensional array in place using strides. + + Given an n-dimensional array it will return a 2n-dimensional array with + the first n dimensions indexing patch position and the last n indexing + the patch content. This operation is immediate (O(1)). A reshape + performed on the first n dimensions will cause numpy to copy data, leading + to a list of extracted patches. + + Parameters + ---------- + arr: ndarray + n-dimensional array of which patches are to be extracted + + patch_shape: integer or tuple of length arr.ndim + Indicates the shape of the patches to be extracted. If an + integer is given, the shape will be a hypercube of + sidelength given by its value. + + extraction_step: integer or tuple of length arr.ndim + Indicates step size at which extraction shall be performed. + If integer is given, then the step is uniform in all dimensions. + + + Returns + ------- + patches: strided ndarray + 2n-dimensional array indexing patches on first n dimensions and + containing patches on the last n dimensions. These dimensions + are fake, but this way no data is copied. A simple reshape invokes + a copying operation to obtain a list of patches: + result.reshape([-1] + list(patch_shape)) + """ + + arr_ndim = arr.ndim + + if isinstance(patch_shape, numbers.Number): + patch_shape = tuple([patch_shape] * arr_ndim) + if isinstance(extraction_step, numbers.Number): + extraction_step = tuple([extraction_step] * arr_ndim) + + patch_strides = arr.strides + + slices = [slice(None, None, st) for st in extraction_step] + indexing_strides = arr[slices].strides + + patch_indices_shape = ((np.array(arr.shape) - np.array(patch_shape)) // + np.array(extraction_step)) + 1 + + shape = tuple(list(patch_indices_shape) + list(patch_shape)) + strides = tuple(list(indexing_strides) + list(patch_strides)) + + patches = as_strided(arr, shape=shape, strides=strides) + return patches + def extract_patches_2d(image, patch_size, max_patches=None, random_state=None): """Reshape a 2D image into a collection of patches @@ -223,7 +334,7 @@ def extract_patches_2d(image, patch_size, max_patches=None, random_state=None): [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> patches = image.extract_patches_2d(one_image, (2, 2)) - >>> patches.shape + >>> print(patches.shape) (9, 2, 2) >>> patches[0] array([[0, 1], @@ -238,38 +349,32 @@ def extract_patches_2d(image, patch_size, max_patches=None, random_state=None): i_h, i_w = image.shape[:2] p_h, p_w = patch_size - image = array2d(image) + if p_h > i_h: + raise ValueError("Height of the patch should be less than the height" + " of the image.") + + if p_w > i_w: + raise ValueError("Width of the patch should be less than the width" + " of the image.") + image = check_array(image, allow_nd=True) image = image.reshape((i_h, i_w, -1)) n_colors = image.shape[-1] - # compute the dimensions of the patches array - n_h = i_h - p_h + 1 - n_w = i_w - p_w + 1 - all_patches = n_h * n_w + extracted_patches = extract_patches(image, + patch_shape=(p_h, p_w, n_colors), + extraction_step=1) + n_patches = _compute_n_patches(i_h, i_w, p_h, p_w, max_patches) if max_patches: - if (isinstance(max_patches, (int, np.integer)) - and max_patches < all_patches): - n_patches = max_patches - elif (isinstance(max_patches, (float, np.floating)) - and 0 < max_patches < 1): - n_patches = int(max_patches * all_patches) - else: - raise ValueError("Invalid value for max_patches: %r" % max_patches) - rng = check_random_state(random_state) - patches = np.empty((n_patches, p_h, p_w, n_colors), dtype=image.dtype) - i_s = rng.randint(n_h, size=n_patches) - j_s = rng.randint(n_w, size=n_patches) - for p, i, j in zip(patches, i_s, j_s): - p[:] = image[i:i + p_h, j:j + p_w, :] + i_s = rng.randint(i_h - p_h + 1, size=n_patches) + j_s = rng.randint(i_w - p_w + 1, size=n_patches) + patches = extracted_patches[i_s, j_s, 0] else: - n_patches = all_patches - patches = np.empty((n_patches, p_h, p_w, n_colors), dtype=image.dtype) - for p, (i, j) in zip(patches, product(xrange(n_h), xrange(n_w))): - p[:] = image[i:i + p_h, j:j + p_w, :] + patches = extracted_patches + patches = patches.reshape(-1, p_h, p_w, n_colors) # remove the color dimension if useless if patches.shape[-1] == 1: return patches.reshape((n_patches, p_h, p_w)) @@ -308,11 +413,11 @@ def reconstruct_from_patches_2d(patches, image_size): # compute the dimensions of the patches array n_h = i_h - p_h + 1 n_w = i_w - p_w + 1 - for p, (i, j) in zip(patches, product(xrange(n_h), xrange(n_w))): + for p, (i, j) in zip(patches, product(range(n_h), range(n_w))): img[i:i + p_h, j:j + p_w] += p - for i in xrange(i_h): - for j in xrange(i_w): + for i in range(i_h): + for j in range(i_w): # divide by the amount of overlap # XXX: is this the most efficient way? memory-wise yes, cpu wise? img[i, j] /= float(min(i + 1, p_h, i_h - i) * @@ -375,18 +480,18 @@ def transform(self, X): X = np.reshape(X, (n_images, i_h, i_w, -1)) n_channels = X.shape[-1] if self.patch_size is None: - patch_size = i_h / 10, i_w / 10 + patch_size = i_h // 10, i_w // 10 else: patch_size = self.patch_size - if self.max_patches: - n_patches = self.max_patches - else: - p_h, p_w = patch_size - n_patches = (i_h - p_h + 1) * (i_w - p_w + 1) + # compute the dimensions of the patches array + p_h, p_w = patch_size + n_patches = _compute_n_patches(i_h, i_w, p_h, p_w, self.max_patches) patches_shape = (n_images * n_patches,) + patch_size if n_channels > 1: patches_shape += (n_channels,) + + # extract the patches patches = np.empty(patches_shape) for ii, image in enumerate(X): patches[ii * n_patches:(ii + 1) * n_patches] = extract_patches_2d( diff --git a/sklearn/feature_extraction/setup.py b/sklearn/feature_extraction/setup.py new file mode 100644 index 0000000000000..de7ec380cdece --- /dev/null +++ b/sklearn/feature_extraction/setup.py @@ -0,0 +1,18 @@ +import os + + +def configuration(parent_package='', top_path=None): + import numpy + from numpy.distutils.misc_util import Configuration + + config = Configuration('feature_extraction', parent_package, top_path) + libraries = [] + if os.name == 'posix': + libraries.append('m') + + config.add_extension('_hashing', + sources=['_hashing.c'], + include_dirs=[numpy.get_include()], + libraries=libraries) + + return config diff --git a/sklearn/feature_extraction/tests/test_dict_vectorizer.py b/sklearn/feature_extraction/tests/test_dict_vectorizer.py index e0a7b5e6403cd..8662300fd8d6f 100644 --- a/sklearn/feature_extraction/tests/test_dict_vectorizer.py +++ b/sklearn/feature_extraction/tests/test_dict_vectorizer.py @@ -1,14 +1,14 @@ -# Author: Lars Buitinck -# License: BSD-style. +# Authors: Lars Buitinck +# Dan Blanchard +# License: BSD 3 clause from random import Random import numpy as np import scipy.sparse as sp -from nose.tools import assert_equal -from nose.tools import assert_true -from nose.tools import assert_false from numpy.testing import assert_array_equal +from sklearn.utils.testing import (assert_equal, assert_in, + assert_false, assert_true) from sklearn.feature_extraction import DictVectorizer from sklearn.feature_selection import SelectKBest, chi2 @@ -21,27 +21,35 @@ def test_dictvectorizer(): for sparse in (True, False): for dtype in (int, np.float32, np.int16): - v = DictVectorizer(sparse=sparse, dtype=dtype) - X = v.fit_transform(D) + for sort in (True, False): + for iterable in (True, False): + v = DictVectorizer(sparse=sparse, dtype=dtype, sort=sort) + X = v.fit_transform(iter(D) if iterable else D) - assert_equal(sp.issparse(X), sparse) - assert_equal(X.shape, (3, 5)) - assert_equal(X.sum(), 14) - assert_equal(v.inverse_transform(X), D) + assert_equal(sp.issparse(X), sparse) + assert_equal(X.shape, (3, 5)) + assert_equal(X.sum(), 14) + assert_equal(v.inverse_transform(X), D) - if sparse: - # COO matrices can't be compared for equality - assert_array_equal(X.A, v.transform(D).A) - else: - assert_array_equal(X, v.transform(D)) + if sparse: + # CSR matrices can't be compared for equality + assert_array_equal(X.A, v.transform(iter(D) if iterable + else D).A) + else: + assert_array_equal(X, v.transform(iter(D) if iterable + else D)) + + if sort: + assert_equal(v.feature_names_, + sorted(v.feature_names_)) def test_feature_selection(): # make two feature dicts with two useful features and a bunch of useless # ones, in terms of chi2 - d1 = dict([("useless%d" % i, 10) for i in xrange(20)], + d1 = dict([("useless%d" % i, 10) for i in range(20)], useful1=1, useful2=20) - d2 = dict([("useless%d" % i, 10) for i in xrange(20)], + d2 = dict([("useless%d" % i, 10) for i in range(20)], useful1=20, useful2=1) for indices in (True, False): @@ -69,12 +77,25 @@ def test_one_of_k(): assert_false("version" in names) -def test_unseen_features(): +def test_unseen_or_no_features(): D = [{"camelot": 0, "spamalot": 1}] - v = DictVectorizer(sparse=False).fit(D) - X = v.transform({"push the pram a lot": 2}) - - assert_array_equal(X, np.zeros((1, 2))) + for sparse in [True, False]: + v = DictVectorizer(sparse=sparse).fit(D) + + X = v.transform({"push the pram a lot": 2}) + if sparse: + X = X.toarray() + assert_array_equal(X, np.zeros((1, 2))) + + X = v.transform({}) + if sparse: + X = X.toarray() + assert_array_equal(X, np.zeros((1, 2))) + + try: + v.transform([]) + except ValueError as e: + assert_in("empty", str(e)) def test_deterministic_vocabulary(): diff --git a/sklearn/feature_extraction/tests/test_feature_hasher.py b/sklearn/feature_extraction/tests/test_feature_hasher.py new file mode 100644 index 0000000000000..2860eacb35640 --- /dev/null +++ b/sklearn/feature_extraction/tests/test_feature_hasher.py @@ -0,0 +1,88 @@ +from __future__ import unicode_literals + +import numpy as np + +from sklearn.feature_extraction import FeatureHasher + +from nose.tools import assert_raises, assert_true +from numpy.testing import assert_array_equal, assert_equal + + +def test_feature_hasher_dicts(): + h = FeatureHasher(n_features=16) + assert_equal("dict", h.input_type) + + raw_X = [{"dada": 42, "tzara": 37}, {"gaga": 17}] + X1 = FeatureHasher(n_features=16).transform(raw_X) + gen = (iter(d.items()) for d in raw_X) + X2 = FeatureHasher(n_features=16, input_type="pair").transform(gen) + assert_array_equal(X1.toarray(), X2.toarray()) + + +def test_feature_hasher_strings(): + # mix byte and Unicode strings; note that "foo" is a duplicate in row 0 + raw_X = [["foo", "bar", "baz", "foo".encode("ascii")], + ["bar".encode("ascii"), "baz", "quux"]] + + for lg_n_features in (7, 9, 11, 16, 22): + n_features = 2 ** lg_n_features + + it = (x for x in raw_X) # iterable + + h = FeatureHasher(n_features, non_negative=True, input_type="string") + X = h.transform(it) + + assert_equal(X.shape[0], len(raw_X)) + assert_equal(X.shape[1], n_features) + + assert_true(np.all(X.data > 0)) + assert_equal(X[0].sum(), 4) + assert_equal(X[1].sum(), 3) + + assert_equal(X.nnz, 6) + + +def test_feature_hasher_pairs(): + raw_X = (iter(d.items()) for d in [{"foo": 1, "bar": 2}, + {"baz": 3, "quux": 4, "foo": -1}]) + h = FeatureHasher(n_features=16, input_type="pair") + x1, x2 = h.transform(raw_X).toarray() + x1_nz = sorted(np.abs(x1[x1 != 0])) + x2_nz = sorted(np.abs(x2[x2 != 0])) + assert_equal([1, 2], x1_nz) + assert_equal([1, 3, 4], x2_nz) + + +def test_hash_empty_input(): + n_features = 16 + raw_X = [[], (), iter(range(0))] + + h = FeatureHasher(n_features=n_features, input_type="string") + X = h.transform(raw_X) + + assert_array_equal(X.A, np.zeros((len(raw_X), n_features))) + + +def test_hasher_invalid_input(): + assert_raises(ValueError, FeatureHasher, input_type="gobbledygook") + assert_raises(ValueError, FeatureHasher, n_features=-1) + assert_raises(ValueError, FeatureHasher, n_features=0) + assert_raises(TypeError, FeatureHasher, n_features='ham') + + h = FeatureHasher(n_features=np.uint16(2 ** 6)) + assert_raises(ValueError, h.transform, []) + assert_raises(Exception, h.transform, [[5.5]]) + assert_raises(Exception, h.transform, [[None]]) + + +def test_hasher_set_params(): + """Test delayed input validation in fit (useful for grid search).""" + hasher = FeatureHasher() + hasher.set_params(n_features=np.inf) + assert_raises(TypeError, hasher.fit) + + +def test_hasher_zeros(): + """Assert that no zeros are materialized in the output.""" + X = FeatureHasher().transform([{'foo': 0}]) + assert_equal(X.data.shape, (0,)) diff --git a/sklearn/feature_extraction/tests/test_image.py b/sklearn/feature_extraction/tests/test_image.py index f04a7369d8820..fd5a4bc57c87b 100644 --- a/sklearn/feature_extraction/tests/test_image.py +++ b/sklearn/feature_extraction/tests/test_image.py @@ -1,6 +1,6 @@ # Authors: Emmanuelle Gouillart # Gael Varoquaux -# License: BSD +# License: BSD 3 clause import numpy as np import scipy as sp @@ -9,10 +9,10 @@ from nose.tools import assert_equal, assert_true from numpy.testing import assert_raises -from ..image import img_to_graph, grid_to_graph -from ..image import extract_patches_2d, reconstruct_from_patches_2d, \ - PatchExtractor -from ...utils.graph import cs_graph_components +from sklearn.feature_extraction.image import ( + img_to_graph, grid_to_graph, extract_patches_2d, + reconstruct_from_patches_2d, PatchExtractor, extract_patches) +from sklearn.utils.graph import connected_components def test_img_to_graph(): @@ -38,12 +38,12 @@ def test_grid_to_graph(): mask[-roi_size:, -roi_size:] = True mask = mask.reshape(size ** 2) A = grid_to_graph(n_x=size, n_y=size, mask=mask, return_as=np.ndarray) - assert_true(cs_graph_components(A)[0] == 2) + assert_true(connected_components(A)[0] == 2) # Checking that the function works whatever the type of mask is mask = np.ones((size, size), dtype=np.int16) A = grid_to_graph(n_x=size, n_y=size, n_z=size, mask=mask) - assert_true(cs_graph_components(A)[0] == 1) + assert_true(connected_components(A)[0] == 1) # Checking dtype of the graph mask = np.ones((size, size)) @@ -60,26 +60,26 @@ def test_connect_regions(): for thr in (50, 150): mask = lena > thr graph = img_to_graph(lena, mask) - assert_equal(ndimage.label(mask)[1], cs_graph_components(graph)[0]) + assert_equal(ndimage.label(mask)[1], connected_components(graph)[0]) def test_connect_regions_with_grid(): lena = sp.misc.lena() mask = lena > 50 graph = grid_to_graph(*lena.shape, mask=mask) - assert_equal(ndimage.label(mask)[1], cs_graph_components(graph)[0]) + assert_equal(ndimage.label(mask)[1], connected_components(graph)[0]) mask = lena > 150 graph = grid_to_graph(*lena.shape, mask=mask, dtype=None) - assert_equal(ndimage.label(mask)[1], cs_graph_components(graph)[0]) + assert_equal(ndimage.label(mask)[1], connected_components(graph)[0]) def _downsampled_lena(): lena = sp.misc.lena().astype(np.float32) - lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + \ - lena[1::2, 1::2] - lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + \ - lena[1::2, 1::2] + lena = (lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + + lena[1::2, 1::2]) + lena = (lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + + lena[1::2, 1::2]) lena = lena.astype(np.float) lena /= 16.0 return lena @@ -149,12 +149,10 @@ def test_extract_patches_max_patches(): patches = extract_patches_2d(lena, (p_h, p_w), max_patches=0.5) assert_equal(patches.shape, (expected_n_patches, p_h, p_w)) - assert_raises(ValueError, extract_patches_2d, lena, - (p_h, p_w), - max_patches=2.0) - assert_raises(ValueError, extract_patches_2d, lena, - (p_h, p_w), - max_patches=-1.0) + assert_raises(ValueError, extract_patches_2d, lena, (p_h, p_w), + max_patches=2.0) + assert_raises(ValueError, extract_patches_2d, lena, (p_h, p_w), + max_patches=-1.0) def test_reconstruct_patches_perfect(): @@ -183,9 +181,23 @@ def test_patch_extractor_fit(): def test_patch_extractor_max_patches(): lenas = lena_collection - extr = PatchExtractor(patch_size=(8, 8), max_patches=100, random_state=0) + i_h, i_w = lenas.shape[1:3] + p_h, p_w = 8, 8 + + max_patches = 100 + expected_n_patches = len(lenas) * max_patches + extr = PatchExtractor(patch_size=(p_h, p_w), max_patches=max_patches, + random_state=0) + patches = extr.transform(lenas) + assert_true(patches.shape == (expected_n_patches, p_h, p_w)) + + max_patches = 0.5 + expected_n_patches = len(lenas) * int((i_h - p_h + 1) * (i_w - p_w + 1) + * max_patches) + extr = PatchExtractor(patch_size=(p_h, p_w), max_patches=max_patches, + random_state=0) patches = extr.transform(lenas) - assert_true(patches.shape == (len(lenas) * 100, 8, 8)) + assert_true(patches.shape == (expected_n_patches, p_h, p_w)) def test_patch_extractor_max_patches_default(): @@ -214,6 +226,70 @@ def test_patch_extractor_color(): patches = extr.transform(lenas) assert_true(patches.shape == (expected_n_patches, p_h, p_w, 3)) + +def test_extract_patches_strided(): + + image_shapes_1D = [(10,), (10,), (11,), (10,)] + patch_sizes_1D = [(1,), (2,), (3,), (8,)] + patch_steps_1D = [(1,), (1,), (4,), (2,)] + + expected_views_1D = [(10,), (9,), (3,), (2,)] + last_patch_1D = [(10,), (8,), (8,), (2,)] + + image_shapes_2D = [(10, 20), (10, 20), (10, 20), (11, 20)] + patch_sizes_2D = [(2, 2), (10, 10), (10, 11), (6, 6)] + patch_steps_2D = [(5, 5), (3, 10), (3, 4), (4, 2)] + + expected_views_2D = [(2, 4), (1, 2), (1, 3), (2, 8)] + last_patch_2D = [(5, 15), (0, 10), (0, 8), (4, 14)] + + image_shapes_3D = [(5, 4, 3), (3, 3, 3), (7, 8, 9), (7, 8, 9)] + patch_sizes_3D = [(2, 2, 3), (2, 2, 2), (1, 7, 3), (1, 3, 3)] + patch_steps_3D = [(1, 2, 10), (1, 1, 1), (2, 1, 3), (3, 3, 4)] + + expected_views_3D = [(4, 2, 1), (2, 2, 2), (4, 2, 3), (3, 2, 2)] + last_patch_3D = [(3, 2, 0), (1, 1, 1), (6, 1, 6), (6, 3, 4)] + + image_shapes = image_shapes_1D + image_shapes_2D + image_shapes_3D + patch_sizes = patch_sizes_1D + patch_sizes_2D + patch_sizes_3D + patch_steps = patch_steps_1D + patch_steps_2D + patch_steps_3D + expected_views = expected_views_1D + expected_views_2D + expected_views_3D + last_patches = last_patch_1D + last_patch_2D + last_patch_3D + + for (image_shape, patch_size, patch_step, expected_view, + last_patch) in zip(image_shapes, patch_sizes, patch_steps, + expected_views, last_patches): + image = np.arange(np.prod(image_shape)).reshape(image_shape) + patches = extract_patches(image, patch_shape=patch_size, + extraction_step=patch_step) + + ndim = len(image_shape) + + assert_true(patches.shape[:ndim] == expected_view) + last_patch_slices = [slice(i, i + j, None) for i, j in + zip(last_patch, patch_size)] + assert_true((patches[[slice(-1, None, None)] * ndim] == + image[last_patch_slices].squeeze()).all()) + + +def test_extract_patches_square(): + # test same patch size for all dimensions + lena = downsampled_lena + i_h, i_w = lena.shape + p = 8 + expected_n_patches = ((i_h - p + 1), (i_w - p + 1)) + patches = extract_patches(lena, patch_shape=p) + assert_true(patches.shape == (expected_n_patches[0], expected_n_patches[1], + p, p)) + + +def test_width_patch(): + # width and height of the patch should be less than the image + x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + assert_raises(ValueError, extract_patches_2d, x, (4, 1)) + assert_raises(ValueError, extract_patches_2d, x, (1, 4)) + + if __name__ == '__main__': import nose nose.runmodule() diff --git a/sklearn/feature_extraction/tests/test_text.py b/sklearn/feature_extraction/tests/test_text.py index 35f1e034ca18c..5b67e5f5d7a3a 100644 --- a/sklearn/feature_extraction/tests/test_text.py +++ b/sklearn/feature_extraction/tests/test_text.py @@ -1,30 +1,43 @@ +from __future__ import unicode_literals import warnings + from sklearn.feature_extraction.text import strip_tags from sklearn.feature_extraction.text import strip_accents_unicode from sklearn.feature_extraction.text import strip_accents_ascii +from sklearn.feature_extraction.text import HashingVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import TfidfVectorizer -from sklearn.utils.testing import assert_less, assert_greater +from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS +from sklearn.cross_validation import train_test_split +from sklearn.cross_validation import cross_val_score from sklearn.grid_search import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.svm import LinearSVC +from sklearn.base import clone + import numpy as np from nose import SkipTest -from nose.tools import assert_equal, assert_equals, \ - assert_false, assert_not_equal, assert_true +from nose.tools import assert_equal +from nose.tools import assert_false +from nose.tools import assert_not_equal +from nose.tools import assert_true +from nose.tools import assert_almost_equal from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_equal from numpy.testing import assert_raises +from sklearn.utils.testing import (assert_in, assert_less, assert_greater, + assert_warns_message, assert_raise_message, + clean_warning_registry) from collections import defaultdict, Mapping from functools import partial import pickle -from StringIO import StringIO +from io import StringIO JUNK_FOOD_DOCS = ( @@ -52,7 +65,7 @@ def uppercase(s): def strip_eacute(s): - return s.replace(u'\xe9', u'e') + return s.replace('\xe9', 'e') def split_tokenize(s): @@ -65,105 +78,109 @@ def lazy_analyze(s): def test_strip_accents(): # check some classical latin accentuated symbols - a = u'\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9\xea\xeb' - expected = u'aaaaaaceeee' + a = '\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9\xea\xeb' + expected = 'aaaaaaceeee' assert_equal(strip_accents_unicode(a), expected) - a = u'\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf9\xfa\xfb\xfc\xfd' - expected = u'iiiinooooouuuuy' + a = '\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf9\xfa\xfb\xfc\xfd' + expected = 'iiiinooooouuuuy' assert_equal(strip_accents_unicode(a), expected) # check some arabic - a = u'\u0625' # halef with a hamza below - expected = u'\u0627' # simple halef + a = '\u0625' # halef with a hamza below + expected = '\u0627' # simple halef assert_equal(strip_accents_unicode(a), expected) # mix letters accentuated and not - a = u"this is \xe0 test" - expected = u'this is a test' + a = "this is \xe0 test" + expected = 'this is a test' assert_equal(strip_accents_unicode(a), expected) def test_to_ascii(): # check some classical latin accentuated symbols - a = u'\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9\xea\xeb' - expected = u'aaaaaaceeee' + a = '\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9\xea\xeb' + expected = 'aaaaaaceeee' assert_equal(strip_accents_ascii(a), expected) - a = u'\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf9\xfa\xfb\xfc\xfd' - expected = u'iiiinooooouuuuy' + a = '\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf9\xfa\xfb\xfc\xfd' + expected = 'iiiinooooouuuuy' assert_equal(strip_accents_ascii(a), expected) # check some arabic - a = u'\u0625' # halef with a hamza below - expected = u'' # halef has no direct ascii match + a = '\u0625' # halef with a hamza below + expected = '' # halef has no direct ascii match assert_equal(strip_accents_ascii(a), expected) # mix letters accentuated and not - a = u"this is \xe0 test" - expected = u'this is a test' + a = "this is \xe0 test" + expected = 'this is a test' assert_equal(strip_accents_ascii(a), expected) def test_word_analyzer_unigrams(): - wa = CountVectorizer(strip_accents='ascii').build_analyzer() - text = u"J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon." - expected = [u'ai', u'mange', u'du', u'kangourou', u'ce', u'midi', - u'etait', u'pas', u'tres', u'bon'] - assert_equal(wa(text), expected) - - text = "This is a test, really.\n\n I met Harry yesterday." - expected = [u'this', u'is', u'test', u'really', u'met', u'harry', - u'yesterday'] - assert_equal(wa(text), expected) - - wa = CountVectorizer(input='file').build_analyzer() - text = StringIO("This is a test with a file-like object!") - expected = [u'this', u'is', u'test', u'with', u'file', u'like', - u'object'] - assert_equal(wa(text), expected) - - # with custom preprocessor - wa = CountVectorizer(preprocessor=uppercase).build_analyzer() - text = u"J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon." - expected = [u'AI', u'MANGE', u'DU', u'KANGOUROU', u'CE', u'MIDI', - u'ETAIT', u'PAS', u'TRES', u'BON'] - assert_equal(wa(text), expected) - - # with custom tokenizer - wa = CountVectorizer(tokenizer=split_tokenize, - strip_accents='ascii').build_analyzer() - text = u"J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon." - expected = [u"j'ai", u'mange', u'du', u'kangourou', u'ce', u'midi,', - u"c'etait", u'pas', u'tres', u'bon.'] - assert_equal(wa(text), expected) + for Vectorizer in (CountVectorizer, HashingVectorizer): + wa = Vectorizer(strip_accents='ascii').build_analyzer() + text = ("J'ai mang\xe9 du kangourou ce midi, " + "c'\xe9tait pas tr\xeas bon.") + expected = ['ai', 'mange', 'du', 'kangourou', 'ce', 'midi', + 'etait', 'pas', 'tres', 'bon'] + assert_equal(wa(text), expected) + + text = "This is a test, really.\n\n I met Harry yesterday." + expected = ['this', 'is', 'test', 'really', 'met', 'harry', + 'yesterday'] + assert_equal(wa(text), expected) + + wa = Vectorizer(input='file').build_analyzer() + text = StringIO("This is a test with a file-like object!") + expected = ['this', 'is', 'test', 'with', 'file', 'like', + 'object'] + assert_equal(wa(text), expected) + + # with custom preprocessor + wa = Vectorizer(preprocessor=uppercase).build_analyzer() + text = ("J'ai mang\xe9 du kangourou ce midi, " + " c'\xe9tait pas tr\xeas bon.") + expected = ['AI', 'MANGE', 'DU', 'KANGOUROU', 'CE', 'MIDI', + 'ETAIT', 'PAS', 'TRES', 'BON'] + assert_equal(wa(text), expected) + + # with custom tokenizer + wa = Vectorizer(tokenizer=split_tokenize, + strip_accents='ascii').build_analyzer() + text = ("J'ai mang\xe9 du kangourou ce midi, " + "c'\xe9tait pas tr\xeas bon.") + expected = ["j'ai", 'mange', 'du', 'kangourou', 'ce', 'midi,', + "c'etait", 'pas', 'tres', 'bon.'] + assert_equal(wa(text), expected) def test_word_analyzer_unigrams_and_bigrams(): wa = CountVectorizer(analyzer="word", strip_accents='unicode', ngram_range=(1, 2)).build_analyzer() - text = u"J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon." - expected = [u'ai', u'mange', u'du', u'kangourou', u'ce', u'midi', u'etait', - u'pas', u'tres', u'bon', u'ai mange', u'mange du', - u'du kangourou', u'kangourou ce', u'ce midi', u'midi etait', - u'etait pas', u'pas tres', u'tres bon'] + text = "J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon." + expected = ['ai', 'mange', 'du', 'kangourou', 'ce', 'midi', + 'etait', 'pas', 'tres', 'bon', 'ai mange', 'mange du', + 'du kangourou', 'kangourou ce', 'ce midi', 'midi etait', + 'etait pas', 'pas tres', 'tres bon'] assert_equal(wa(text), expected) def test_unicode_decode_error(): # decode_error default to strict, so this should fail # First, encode (as bytes) a unicode string. - text = u"J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon." + text = "J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon." text_bytes = text.encode('utf-8') # Then let the Analyzer try to decode it as ascii. It should fail, - # because we have given it an incorrect charset. - wa = CountVectorizer(ngram_range=(1, 2), charset='ascii').build_analyzer() + # because we have given it an incorrect encoding. + wa = CountVectorizer(ngram_range=(1, 2), encoding='ascii').build_analyzer() assert_raises(UnicodeDecodeError, wa, text_bytes) ca = CountVectorizer(analyzer='char', ngram_range=(3, 6), - charset='ascii').build_analyzer() + encoding='ascii').build_analyzer() assert_raises(UnicodeDecodeError, ca, text_bytes) @@ -171,23 +188,23 @@ def test_char_ngram_analyzer(): cnga = CountVectorizer(analyzer='char', strip_accents='unicode', ngram_range=(3, 6)).build_analyzer() - text = u"J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon" - expected = [u"j'a", u"'ai", u'ai ', u'i m', u' ma'] + text = "J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon" + expected = ["j'a", "'ai", 'ai ', 'i m', ' ma'] assert_equal(cnga(text)[:5], expected) - expected = [u's tres', u' tres ', u'tres b', u'res bo', u'es bon'] + expected = ['s tres', ' tres ', 'tres b', 'res bo', 'es bon'] assert_equal(cnga(text)[-5:], expected) text = "This \n\tis a test, really.\n\n I met Harry yesterday" - expected = [u'thi', u'his', u'is ', u's i', u' is'] + expected = ['thi', 'his', 'is ', 's i', ' is'] assert_equal(cnga(text)[:5], expected) - expected = [u' yeste', u'yester', u'esterd', u'sterda', u'terday'] + expected = [' yeste', 'yester', 'esterd', 'sterda', 'terday'] assert_equal(cnga(text)[-5:], expected) cnga = CountVectorizer(input='file', analyzer='char', ngram_range=(3, 6)).build_analyzer() text = StringIO("This is a test with a file-like object!") - expected = [u'thi', u'his', u'is ', u's i', u' is'] + expected = ['thi', 'his', 'is ', 's i', ' is'] assert_equal(cnga(text)[:5], expected) @@ -196,16 +213,16 @@ def test_char_wb_ngram_analyzer(): ngram_range=(3, 6)).build_analyzer() text = "This \n\tis a test, really.\n\n I met Harry yesterday" - expected = [u' th', u'thi', u'his', u'is ', u' thi'] + expected = [' th', 'thi', 'his', 'is ', ' thi'] assert_equal(cnga(text)[:5], expected) - expected = [u'yester', u'esterd', u'sterda', u'terday', u'erday '] + expected = ['yester', 'esterd', 'sterda', 'terday', 'erday '] assert_equal(cnga(text)[-5:], expected) cnga = CountVectorizer(input='file', analyzer='char_wb', ngram_range=(3, 6)).build_analyzer() text = StringIO("A test with a file-like object!") - expected = [u' a ', u' te', u'tes', u'est', u'st ', u' tes'] + expected = [' a ', ' te', 'tes', 'est', 'st ', ' tes'] assert_equal(cnga(text)[:6], expected) @@ -237,6 +254,52 @@ def test_countvectorizer_custom_vocabulary_pipeline(): assert_equal(X.shape[1], len(what_we_like)) +def test_countvectorizer_custom_vocabulary_repeated_indeces(): + vocab = {"pizza": 0, "beer": 0} + try: + CountVectorizer(vocabulary=vocab) + except ValueError as e: + assert_in("vocabulary contains repeated indices", str(e).lower()) + + +def test_countvectorizer_custom_vocabulary_gap_index(): + vocab = {"pizza": 1, "beer": 2} + try: + CountVectorizer(vocabulary=vocab) + except ValueError as e: + assert_in("doesn't contain index", str(e).lower()) + + +def test_countvectorizer_stop_words(): + cv = CountVectorizer() + cv.set_params(stop_words='english') + assert_equal(cv.get_stop_words(), ENGLISH_STOP_WORDS) + cv.set_params(stop_words='_bad_str_stop_') + assert_raises(ValueError, cv.get_stop_words) + cv.set_params(stop_words='_bad_unicode_stop_') + assert_raises(ValueError, cv.get_stop_words) + stoplist = ['some', 'other', 'words'] + cv.set_params(stop_words=stoplist) + assert_equal(cv.get_stop_words(), stoplist) + + +def test_countvectorizer_empty_vocabulary(): + try: + vect = CountVectorizer(vocabulary=[]) + vect.fit(["foo"]) + assert False, "we shouldn't get here" + except ValueError as e: + assert_in("empty vocabulary", str(e).lower()) + + try: + v = CountVectorizer(max_df=1.0, stop_words="english") + # fit on stopwords only + v.fit(["to be or not to be", "and me too", "and so do you"]) + assert False, "we shouldn't get here" + except ValueError as e: + assert_in("empty vocabulary", str(e).lower()) + + def test_fit_countvectorizer_twice(): cv = CountVectorizer() X1 = cv.fit_transform(ALL_FOOD_DOCS[:5]) @@ -282,21 +345,16 @@ def test_tfidf_no_smoothing(): [1, 0, 0]] tr = TfidfTransformer(smooth_idf=False, norm='l2') - # First we need to verify that numpy here provides div 0 warnings + clean_warning_registry() with warnings.catch_warnings(record=True) as w: 1. / np.array([0.]) numpy_provides_div0_warning = len(w) == 1 - with warnings.catch_warnings(record=True) as w: - tfidf = tr.fit_transform(X).toarray() - if not numpy_provides_div0_warning: - raise SkipTest("Numpy does not provide div 0 warnings.") - assert_equal(len(w), 1) - # For Python 3 compatibility - if hasattr(w[0].message, 'args'): - assert_true("divide by zero" in w[0].message.args[0]) - else: - assert_true("divide by zero" in w[0].message) + in_warning_message = 'divide by zero' + tfidf = assert_warns_message(RuntimeWarning, in_warning_message, + tr.fit_transform, X).toarray() + if not numpy_provides_div0_warning: + raise SkipTest("Numpy does not provide div 0 warnings.") def test_sublinear_tf(): @@ -317,11 +375,11 @@ def test_vectorizer(): n_train = len(ALL_FOOD_DOCS) - 1 # test without vocabulary - v1 = CountVectorizer(max_df=0.5, min_df=1) + v1 = CountVectorizer(max_df=0.5) counts_train = v1.fit_transform(train_data) if hasattr(counts_train, 'tocsr'): counts_train = counts_train.tocsr() - assert_equal(counts_train[0, v1.vocabulary_[u"pizza"]], 2) + assert_equal(counts_train[0, v1.vocabulary_["pizza"]], 2) # build a vectorizer v1 with the same vocabulary as the one fitted by v1 v2 = CountVectorizer(vocabulary=v1.vocabulary_) @@ -333,24 +391,24 @@ def test_vectorizer(): counts_test = counts_test.tocsr() vocabulary = v.vocabulary_ - assert_equal(counts_test[0, vocabulary[u"salad"]], 1) - assert_equal(counts_test[0, vocabulary[u"tomato"]], 1) - assert_equal(counts_test[0, vocabulary[u"water"]], 1) + assert_equal(counts_test[0, vocabulary["salad"]], 1) + assert_equal(counts_test[0, vocabulary["tomato"]], 1) + assert_equal(counts_test[0, vocabulary["water"]], 1) # stop word from the fixed list - assert_false(u"the" in vocabulary) + assert_false("the" in vocabulary) # stop word found automatically by the vectorizer DF thresholding # words that are high frequent across the complete corpus are likely # to be not informative (either real stop words of extraction # artifacts) - assert_false(u"copyright" in vocabulary) + assert_false("copyright" in vocabulary) # not present in the sample - assert_equal(counts_test[0, vocabulary[u"coke"]], 0) - assert_equal(counts_test[0, vocabulary[u"burger"]], 0) - assert_equal(counts_test[0, vocabulary[u"beer"]], 0) - assert_equal(counts_test[0, vocabulary[u"pizza"]], 0) + assert_equal(counts_test[0, vocabulary["coke"]], 0) + assert_equal(counts_test[0, vocabulary["burger"]], 0) + assert_equal(counts_test[0, vocabulary["beer"]], 0) + assert_equal(counts_test[0, vocabulary["pizza"]], 0) # test tf-idf t1 = TfidfTransformer(norm='l1') @@ -367,17 +425,29 @@ def test_vectorizer(): tf = t2.fit(counts_train).transform(counts_train).toarray() assert_equal(t2.idf_, None) + # test idf transform with unlearned idf vector + t3 = TfidfTransformer(use_idf=True) + assert_raises(ValueError, t3.transform, counts_train) + + # test idf transform with incompatible n_features + X = [[1, 1, 5], + [1, 1, 0]] + t3.fit(X) + X_incompt = [[1, 3], + [1, 3]] + assert_raises(ValueError, t3.transform, X_incompt) + # L1-normalized term frequencies sum to one assert_array_almost_equal(np.sum(tf, axis=1), [1.0] * n_train) # test the direct tfidf vectorizer # (equivalent to term count vectorizer + tfidf transformer) train_data = iter(ALL_FOOD_DOCS[:-1]) - tv = TfidfVectorizer(norm='l1', min_df=1) - assert_false(tv.fixed_vocabulary) + tv = TfidfVectorizer(norm='l1') tv.max_df = v1.max_df tfidf2 = tv.fit_transform(train_data).toarray() + assert_false(tv.fixed_vocabulary_) assert_array_almost_equal(tfidf, tfidf2) # test the direct tfidf vectorizer with new data @@ -388,11 +458,77 @@ def test_vectorizer(): v3 = CountVectorizer(vocabulary=None) assert_raises(ValueError, v3.transform, train_data) + # ascii preprocessor? + v3.set_params(strip_accents='ascii', lowercase=False) + assert_equal(v3.build_preprocessor(), strip_accents_ascii) + + # error on bad strip_accents param + v3.set_params(strip_accents='_gabbledegook_', preprocessor=None) + assert_raises(ValueError, v3.build_preprocessor) + + # error with bad analyzer type + v3.set_params = '_invalid_analyzer_type_' + assert_raises(ValueError, v3.build_analyzer) + + +def test_tfidf_vectorizer_setters(): + tv = TfidfVectorizer(norm='l2', use_idf=False, smooth_idf=False, + sublinear_tf=False) + tv.norm = 'l1' + assert_equal(tv._tfidf.norm, 'l1') + tv.use_idf = True + assert_true(tv._tfidf.use_idf) + tv.smooth_idf = True + assert_true(tv._tfidf.smooth_idf) + tv.sublinear_tf = True + assert_true(tv._tfidf.sublinear_tf) + + +def test_hashing_vectorizer(): + v = HashingVectorizer() + X = v.transform(ALL_FOOD_DOCS) + token_nnz = X.nnz + assert_equal(X.shape, (len(ALL_FOOD_DOCS), v.n_features)) + assert_equal(X.dtype, v.dtype) + + # By default the hashed values receive a random sign and l2 normalization + # makes the feature values bounded + assert_true(np.min(X.data) > -1) + assert_true(np.min(X.data) < 0) + assert_true(np.max(X.data) > 0) + assert_true(np.max(X.data) < 1) + + # Check that the rows are normalized + for i in range(X.shape[0]): + assert_almost_equal(np.linalg.norm(X[0].data, 2), 1.0) + + # Check vectorization with some non-default parameters + v = HashingVectorizer(ngram_range=(1, 2), non_negative=True, norm='l1') + X = v.transform(ALL_FOOD_DOCS) + assert_equal(X.shape, (len(ALL_FOOD_DOCS), v.n_features)) + assert_equal(X.dtype, v.dtype) + + # ngrams generate more non zeros + ngrams_nnz = X.nnz + assert_true(ngrams_nnz > token_nnz) + assert_true(ngrams_nnz < 2 * token_nnz) + + # makes the feature values bounded + assert_true(np.min(X.data) > 0) + assert_true(np.max(X.data) < 1) + + # Check that the rows are normalized + for i in range(X.shape[0]): + assert_almost_equal(np.linalg.norm(X[0].data, 1), 1.0) + def test_feature_names(): - cv = CountVectorizer(max_df=0.5, min_df=1) - X = cv.fit_transform(ALL_FOOD_DOCS) + cv = CountVectorizer(max_df=0.5) + # test for Value error on unfitted/empty vocabulary + assert_raises(ValueError, cv.get_feature_names) + + X = cv.fit_transform(ALL_FOOD_DOCS) n_samples, n_features = X.shape assert_equal(len(cv.vocabulary_), n_features) @@ -413,55 +549,93 @@ def test_vectorizer_max_features(): ) expected_vocabulary = set(['burger', 'beer', 'salad', 'pizza']) + expected_stop_words = set([u'celeri', u'tomato', u'copyright', u'coke', + u'sparkling', u'water', u'the']) for vec_factory in vec_factories: # test bounded number of extracted features vectorizer = vec_factory(max_df=0.6, max_features=4) vectorizer.fit(ALL_FOOD_DOCS) - assert_equals(set(vectorizer.vocabulary_), expected_vocabulary) + assert_equal(set(vectorizer.vocabulary_), expected_vocabulary) + assert_equal(vectorizer.stop_words_, expected_stop_words) + + +def test_count_vectorizer_max_features(): + """Regression test: max_features didn't work correctly in 0.14.""" + + cv_1 = CountVectorizer(max_features=1) + cv_3 = CountVectorizer(max_features=3) + cv_None = CountVectorizer(max_features=None) + + counts_1 = cv_1.fit_transform(JUNK_FOOD_DOCS).sum(axis=0) + counts_3 = cv_3.fit_transform(JUNK_FOOD_DOCS).sum(axis=0) + counts_None = cv_None.fit_transform(JUNK_FOOD_DOCS).sum(axis=0) + + features_1 = cv_1.get_feature_names() + features_3 = cv_3.get_feature_names() + features_None = cv_None.get_feature_names() + + # The most common feature is "the", with frequency 7. + assert_equal(7, counts_1.max()) + assert_equal(7, counts_3.max()) + assert_equal(7, counts_None.max()) + + # The most common feature should be the same + assert_equal("the", features_1[np.argmax(counts_1)]) + assert_equal("the", features_3[np.argmax(counts_3)]) + assert_equal("the", features_None[np.argmax(counts_None)]) def test_vectorizer_max_df(): - test_data = [u'abc', u'dea'] # the letter a occurs in both strings - vect = CountVectorizer(analyzer='char', max_df=1.0, min_df=1) + test_data = ['abc', 'dea', 'eat'] + vect = CountVectorizer(analyzer='char', max_df=1.0) vect.fit(test_data) - assert_true(u'a' in vect.vocabulary_.keys()) - assert_equals(len(vect.vocabulary_.keys()), 5) + assert_true('a' in vect.vocabulary_.keys()) + assert_equal(len(vect.vocabulary_.keys()), 6) + assert_equal(len(vect.stop_words_), 0) - vect.max_df = 0.5 + vect.max_df = 0.5 # 0.5 * 3 documents -> max_doc_count == 1.5 vect.fit(test_data) - assert_true(u'a' not in vect.vocabulary_.keys()) # 'a' is ignored - assert_equals(len(vect.vocabulary_.keys()), 4) # the others remain + assert_true('a' not in vect.vocabulary_.keys()) # {ae} ignored + assert_equal(len(vect.vocabulary_.keys()), 4) # {bcdt} remain + assert_true('a' in vect.stop_words_) + assert_equal(len(vect.stop_words_), 2) - # absolute count: if in more than one vect.max_df = 1 vect.fit(test_data) - assert_true(u'a' not in vect.vocabulary_.keys()) # 'a' is ignored - assert_equals(len(vect.vocabulary_.keys()), 4) # the others remain + assert_true('a' not in vect.vocabulary_.keys()) # {ae} ignored + assert_equal(len(vect.vocabulary_.keys()), 4) # {bcdt} remain + assert_true('a' in vect.stop_words_) + assert_equal(len(vect.stop_words_), 2) def test_vectorizer_min_df(): - test_data = [u'abc', u'dea', u'eat'] # the letter a occurs in both strings - vect = CountVectorizer(analyzer='char', max_df=1.0, min_df=1) + test_data = ['abc', 'dea', 'eat'] + vect = CountVectorizer(analyzer='char', min_df=1) vect.fit(test_data) - assert_true(u'a' in vect.vocabulary_.keys()) - assert_equals(len(vect.vocabulary_.keys()), 6) + assert_true('a' in vect.vocabulary_.keys()) + assert_equal(len(vect.vocabulary_.keys()), 6) + assert_equal(len(vect.stop_words_), 0) vect.min_df = 2 vect.fit(test_data) - assert_true(u'c' not in vect.vocabulary_.keys()) # 'c' is ignored - assert_equals(len(vect.vocabulary_.keys()), 2) # only e, a remain + assert_true('c' not in vect.vocabulary_.keys()) # {bcdt} ignored + assert_equal(len(vect.vocabulary_.keys()), 2) # {ae} remain + assert_true('c' in vect.stop_words_) + assert_equal(len(vect.stop_words_), 4) - vect.min_df = .5 + vect.min_df = 0.8 # 0.8 * 3 documents -> min_doc_count == 2.4 vect.fit(test_data) - assert_true(u'c' not in vect.vocabulary_.keys()) # 'c' is ignored - assert_equals(len(vect.vocabulary_.keys()), 2) # only e, a remain + assert_true('c' not in vect.vocabulary_.keys()) # {bcdet} ignored + assert_equal(len(vect.vocabulary_.keys()), 1) # {a} remains + assert_true('c' in vect.stop_words_) + assert_equal(len(vect.stop_words_), 5) -def test_binary_occurrences(): +def test_count_binary_occurrences(): # by default multiple occurrences are counted as longs - test_data = [u'aaabc', u'abbde'] - vect = CountVectorizer(analyzer='char', max_df=1.0, min_df=1) + test_data = ['aaabc', 'abbde'] + vect = CountVectorizer(analyzer='char', max_df=1.0) X = vect.fit_transform(test_data).toarray() assert_array_equal(['a', 'b', 'c', 'd', 'e'], vect.get_feature_names()) assert_array_equal([[3, 1, 1, 0, 0], @@ -469,8 +643,7 @@ def test_binary_occurrences(): # using boolean features, we can fetch the binary occurrence info # instead. - vect = CountVectorizer(analyzer='char', max_df=1.0, - binary=True, min_df=1) + vect = CountVectorizer(analyzer='char', max_df=1.0, binary=True) X = vect.fit_transform(test_data).toarray() assert_array_equal([[1, 1, 1, 0, 0], [1, 1, 0, 1, 1]], X) @@ -482,10 +655,35 @@ def test_binary_occurrences(): assert_equal(X_sparse.dtype, np.float32) +def test_hashed_binary_occurrences(): + # by default multiple occurrences are counted as longs + test_data = ['aaabc', 'abbde'] + vect = HashingVectorizer(analyzer='char', non_negative=True, + norm=None) + X = vect.transform(test_data) + assert_equal(np.max(X[0:1].data), 3) + assert_equal(np.max(X[1:2].data), 2) + assert_equal(X.dtype, np.float64) + + # using boolean features, we can fetch the binary occurrence info + # instead. + vect = HashingVectorizer(analyzer='char', non_negative=True, binary=True, + norm=None) + X = vect.transform(test_data) + assert_equal(np.max(X.data), 1) + assert_equal(X.dtype, np.float64) + + # check the ability to change the dtype + vect = HashingVectorizer(analyzer='char', non_negative=True, binary=True, + norm=None, dtype=np.float64) + X = vect.transform(test_data) + assert_equal(X.dtype, np.float64) + + def test_vectorizer_inverse_transform(): # raw documents data = ALL_FOOD_DOCS - for vectorizer in (TfidfVectorizer(min_df=1), CountVectorizer(min_df=1)): + for vectorizer in (TfidfVectorizer(), CountVectorizer()): transformed_data = vectorizer.fit_transform(data) inversed_data = vectorizer.inverse_transform(transformed_data) analyze = vectorizer.build_analyzer() @@ -504,32 +702,30 @@ def test_vectorizer_inverse_transform(): def test_count_vectorizer_pipeline_grid_selection(): # raw documents data = JUNK_FOOD_DOCS + NOTJUNK_FOOD_DOCS - # simulate iterables - train_data = iter(data[1:-1]) - test_data = iter([data[0], data[-1]]) # label junk food as -1, the others as +1 - y = np.ones(len(data)) - y[:6] = -1 - y_train = y[1:-1] - y_test = np.array([y[0], y[-1]]) + target = [-1] * len(JUNK_FOOD_DOCS) + [1] * len(NOTJUNK_FOOD_DOCS) + + # split the dataset for model development and final evaluation + train_data, test_data, target_train, target_test = train_test_split( + data, target, test_size=.2, random_state=0) - pipeline = Pipeline([('vect', CountVectorizer(min_df=1)), + pipeline = Pipeline([('vect', CountVectorizer()), ('svc', LinearSVC())]) parameters = { 'vect__ngram_range': [(1, 1), (1, 2)], - 'svc__loss': ('l1', 'l2') + 'svc__loss': ('hinge', 'squared_hinge') } # find the best parameters for both the feature extraction and the # classifier grid_search = GridSearchCV(pipeline, parameters, n_jobs=1) - # cross-validation doesn't work if the length of the data is not known, - # hence use lists instead of iterators - pred = grid_search.fit(list(train_data), y_train).predict(list(test_data)) - assert_array_equal(pred, y_test) + # Check that the best model found by grid search is 100% correct on the + # held out evaluation set. + pred = grid_search.fit(train_data, target_train).predict(test_data) + assert_array_equal(pred, target_test) # on this toy dataset bigram representation which is used in the last of # the grid_search is considered the best estimator since they all converge @@ -542,33 +738,31 @@ def test_count_vectorizer_pipeline_grid_selection(): def test_vectorizer_pipeline_grid_selection(): # raw documents data = JUNK_FOOD_DOCS + NOTJUNK_FOOD_DOCS - # simulate iterables - train_data = iter(data[1:-1]) - test_data = iter([data[0], data[-1]]) # label junk food as -1, the others as +1 - y = np.ones(len(data)) - y[:6] = -1 - y_train = y[1:-1] - y_test = np.array([y[0], y[-1]]) + target = [-1] * len(JUNK_FOOD_DOCS) + [1] * len(NOTJUNK_FOOD_DOCS) - pipeline = Pipeline([('vect', TfidfVectorizer(min_df=1)), + # split the dataset for model development and final evaluation + train_data, test_data, target_train, target_test = train_test_split( + data, target, test_size=.1, random_state=0) + + pipeline = Pipeline([('vect', TfidfVectorizer()), ('svc', LinearSVC())]) parameters = { 'vect__ngram_range': [(1, 1), (1, 2)], 'vect__norm': ('l1', 'l2'), - 'svc__loss': ('l1', 'l2'), + 'svc__loss': ('hinge', 'squared_hinge'), } # find the best parameters for both the feature extraction and the # classifier grid_search = GridSearchCV(pipeline, parameters, n_jobs=1) - # cross-validation doesn't work if the length of the data is not known, - # hence use lists instead of iterators - pred = grid_search.fit(list(train_data), y_train).predict(list(test_data)) - assert_array_equal(pred, y_test) + # Check that the best model found by grid search is 100% correct on the + # held out evaluation set. + pred = grid_search.fit(train_data, target_train).predict(test_data) + assert_array_equal(pred, target_test) # on this toy dataset bigram representation which is used in the last of # the grid_search is considered the best estimator since they all converge @@ -577,44 +771,74 @@ def test_vectorizer_pipeline_grid_selection(): best_vectorizer = grid_search.best_estimator_.named_steps['vect'] assert_equal(best_vectorizer.ngram_range, (1, 1)) assert_equal(best_vectorizer.norm, 'l2') - assert_false(best_vectorizer.fixed_vocabulary) + assert_false(best_vectorizer.fixed_vocabulary_) -def test_count_vectorizer_unicode(): +def test_vectorizer_pipeline_cross_validation(): + # raw documents + data = JUNK_FOOD_DOCS + NOTJUNK_FOOD_DOCS + + # label junk food as -1, the others as +1 + target = [-1] * len(JUNK_FOOD_DOCS) + [1] * len(NOTJUNK_FOOD_DOCS) + + pipeline = Pipeline([('vect', TfidfVectorizer()), + ('svc', LinearSVC())]) + + cv_scores = cross_val_score(pipeline, data, target, cv=3) + assert_array_equal(cv_scores, [1., 1., 1.]) + + +def test_vectorizer_unicode(): # tests that the count vectorizer works with cyrillic. - document = (u"\xd0\x9c\xd0\xb0\xd1\x88\xd0\xb8\xd0\xbd\xd0\xbd\xd0\xbe\xd0" - u"\xb5 \xd0\xbe\xd0\xb1\xd1\x83\xd1\x87\xd0\xb5\xd0\xbd\xd0\xb8\xd0" - u"\xb5 \xe2\x80\x94 \xd0\xbe\xd0\xb1\xd1\x88\xd0\xb8\xd1\x80\xd0\xbd" - u"\xd1\x8b\xd0\xb9 \xd0\xbf\xd0\xbe\xd0\xb4\xd1\x80\xd0\xb0\xd0\xb7" - u"\xd0\xb4\xd0\xb5\xd0\xbb \xd0\xb8\xd1\x81\xd0\xba\xd1\x83\xd1\x81" - u"\xd1\x81\xd1\x82\xd0\xb2\xd0\xb5\xd0\xbd\xd0\xbd\xd0\xbe\xd0\xb3" - u"\xd0\xbe \xd0\xb8\xd0\xbd\xd1\x82\xd0\xb5\xd0\xbb\xd0\xbb\xd0" - u"\xb5\xd0\xba\xd1\x82\xd0\xb0, \xd0\xb8\xd0\xb7\xd1\x83\xd1\x87" - u"\xd0\xb0\xd1\x8e\xd1\x89\xd0\xb8\xd0\xb9 \xd0\xbc\xd0\xb5\xd1\x82" - u"\xd0\xbe\xd0\xb4\xd1\x8b \xd0\xbf\xd0\xbe\xd1\x81\xd1\x82\xd1\x80" - u"\xd0\xbe\xd0\xb5\xd0\xbd\xd0\xb8\xd1\x8f \xd0\xb0\xd0\xbb\xd0\xb3" - u"\xd0\xbe\xd1\x80\xd0\xb8\xd1\x82\xd0\xbc\xd0\xbe\xd0\xb2, \xd1\x81" - u"\xd0\xbf\xd0\xbe\xd1\x81\xd0\xbe\xd0\xb1\xd0\xbd\xd1\x8b\xd1\x85 " - u"\xd0\xbe\xd0\xb1\xd1\x83\xd1\x87\xd0\xb0\xd1\x82\xd1\x8c\xd1\x81\xd1" - u"\x8f.") - vect = CountVectorizer(min_df=1) - X = vect.fit_transform([document]) - assert_equal(X.shape, (1, 15)) + document = ( + "\xd0\x9c\xd0\xb0\xd1\x88\xd0\xb8\xd0\xbd\xd0\xbd\xd0\xbe\xd0" + "\xb5 \xd0\xbe\xd0\xb1\xd1\x83\xd1\x87\xd0\xb5\xd0\xbd\xd0\xb8\xd0" + "\xb5 \xe2\x80\x94 \xd0\xbe\xd0\xb1\xd1\x88\xd0\xb8\xd1\x80\xd0\xbd" + "\xd1\x8b\xd0\xb9 \xd0\xbf\xd0\xbe\xd0\xb4\xd1\x80\xd0\xb0\xd0\xb7" + "\xd0\xb4\xd0\xb5\xd0\xbb \xd0\xb8\xd1\x81\xd0\xba\xd1\x83\xd1\x81" + "\xd1\x81\xd1\x82\xd0\xb2\xd0\xb5\xd0\xbd\xd0\xbd\xd0\xbe\xd0\xb3" + "\xd0\xbe \xd0\xb8\xd0\xbd\xd1\x82\xd0\xb5\xd0\xbb\xd0\xbb\xd0" + "\xb5\xd0\xba\xd1\x82\xd0\xb0, \xd0\xb8\xd0\xb7\xd1\x83\xd1\x87" + "\xd0\xb0\xd1\x8e\xd1\x89\xd0\xb8\xd0\xb9 \xd0\xbc\xd0\xb5\xd1\x82" + "\xd0\xbe\xd0\xb4\xd1\x8b \xd0\xbf\xd0\xbe\xd1\x81\xd1\x82\xd1\x80" + "\xd0\xbe\xd0\xb5\xd0\xbd\xd0\xb8\xd1\x8f \xd0\xb0\xd0\xbb\xd0\xb3" + "\xd0\xbe\xd1\x80\xd0\xb8\xd1\x82\xd0\xbc\xd0\xbe\xd0\xb2, \xd1\x81" + "\xd0\xbf\xd0\xbe\xd1\x81\xd0\xbe\xd0\xb1\xd0\xbd\xd1\x8b\xd1\x85 " + "\xd0\xbe\xd0\xb1\xd1\x83\xd1\x87\xd0\xb0\xd1\x82\xd1\x8c\xd1\x81\xd1" + "\x8f.") + + vect = CountVectorizer() + X_counted = vect.fit_transform([document]) + assert_equal(X_counted.shape, (1, 15)) + + vect = HashingVectorizer(norm=None, non_negative=True) + X_hashed = vect.transform([document]) + assert_equal(X_hashed.shape, (1, 2 ** 20)) + + # No collisions on such a small dataset + assert_equal(X_counted.nnz, X_hashed.nnz) + + # When norm is None and non_negative, the tokens are counted up to + # collisions + assert_array_equal(np.sort(X_counted.data), np.sort(X_hashed.data)) def test_tfidf_vectorizer_with_fixed_vocabulary(): # non regression smoke test for inheritance issues vocabulary = ['pizza', 'celeri'] vect = TfidfVectorizer(vocabulary=vocabulary) - assert_true(vect.fixed_vocabulary) X_1 = vect.fit_transform(ALL_FOOD_DOCS) X_2 = vect.transform(ALL_FOOD_DOCS) assert_array_almost_equal(X_1.toarray(), X_2.toarray()) - assert_true(vect.fixed_vocabulary) + assert_true(vect.fixed_vocabulary_) def test_pickling_vectorizer(): instances = [ + HashingVectorizer(), + HashingVectorizer(norm='l1'), + HashingVectorizer(binary=True), + HashingVectorizer(ngram_range=(1, 2)), CountVectorizer(), CountVectorizer(preprocessor=strip_tags), CountVectorizer(analyzer=lazy_analyze), @@ -629,11 +853,35 @@ def test_pickling_vectorizer(): s = pickle.dumps(orig) copy = pickle.loads(s) assert_equal(type(copy), orig.__class__) + assert_equal(copy.get_params(), orig.get_params()) assert_array_equal( copy.fit_transform(JUNK_FOOD_DOCS).toarray(), orig.fit_transform(JUNK_FOOD_DOCS).toarray()) +def test_stop_words_removal(): + """Ensure that deleting the stop_words_ attribute doesn't affect transform + """ + + fitted_vectorizers = ( + TfidfVectorizer().fit(JUNK_FOOD_DOCS), + CountVectorizer(preprocessor=strip_tags).fit(JUNK_FOOD_DOCS), + CountVectorizer(strip_accents=strip_eacute).fit(JUNK_FOOD_DOCS) + ) + + for vect in fitted_vectorizers: + vect_transform = vect.transform(JUNK_FOOD_DOCS).toarray() + + vect.stop_words_ = None + stop_None_transform = vect.transform(JUNK_FOOD_DOCS).toarray() + + delattr(vect, 'stop_words_') + stop_del_transform = vect.transform(JUNK_FOOD_DOCS).toarray() + + assert_array_equal(stop_None_transform, vect_transform) + assert_array_equal(stop_del_transform, vect_transform) + + def test_pickling_transformer(): X = CountVectorizer().fit_transform(JUNK_FOOD_DOCS) orig = TfidfTransformer().fit(X) @@ -643,3 +891,47 @@ def test_pickling_transformer(): assert_array_equal( copy.fit_transform(X).toarray(), orig.fit_transform(X).toarray()) + + +def test_non_unique_vocab(): + vocab = ['a', 'b', 'c', 'a', 'a'] + vect = CountVectorizer(vocabulary=vocab) + assert_raises(ValueError, vect.fit, []) + + +def test_hashingvectorizer_nan_in_docs(): + # np.nan can appear when using pandas to load text fields from a csv file + # with missing values. + message = "np.nan is an invalid document, expected byte or unicode string." + exception = ValueError + + def func(): + hv = HashingVectorizer() + hv.fit_transform(['hello world', np.nan, 'hello hello']) + + assert_raise_message(exception, message, func) + + +def test_tfidfvectorizer_binary(): + # Non-regression test: TfidfVectorizer used to ignore its "binary" param. + v = TfidfVectorizer(binary=True, use_idf=False, norm=None) + assert_true(v.binary) + + X = v.fit_transform(['hello world', 'hello hello']).toarray() + assert_array_equal(X.ravel(), [1, 1, 1, 0]) + X2 = v.transform(['hello world', 'hello hello']).toarray() + assert_array_equal(X2.ravel(), [1, 1, 1, 0]) + + +def test_tfidfvectorizer_export_idf(): + vect = TfidfVectorizer(use_idf=True) + vect.fit(JUNK_FOOD_DOCS) + assert_array_almost_equal(vect.idf_, vect._tfidf.idf_) + + +def test_vectorizer_vocab_clone(): + vect_vocab = TfidfVectorizer(vocabulary=["the"]) + vect_vocab_clone = clone(vect_vocab) + vect_vocab.fit(ALL_FOOD_DOCS) + vect_vocab_clone.fit(ALL_FOOD_DOCS) + assert_equal(vect_vocab_clone.vocabulary_, vect_vocab.vocabulary_) diff --git a/sklearn/feature_extraction/text.py b/sklearn/feature_extraction/text.py index 397702fad84bf..be508b425b52b 100644 --- a/sklearn/feature_extraction/text.py +++ b/sklearn/feature_extraction/text.py @@ -3,26 +3,35 @@ # Mathieu Blondel # Lars Buitinck # Robert Layton +# Jochen Wersdörfer +# Roman Sinayev # -# License: BSD Style. +# License: BSD 3 clause """ The :mod:`sklearn.feature_extraction.text` submodule gathers utilities to build feature vectors from text documents. """ +from __future__ import unicode_literals -from collections import Mapping +import array +from collections import Mapping, defaultdict +import numbers from operator import itemgetter import re import unicodedata -import warnings import numpy as np import scipy.sparse as sp from ..base import BaseEstimator, TransformerMixin +from ..externals import six +from ..externals.six.moves import xrange from ..preprocessing import normalize -from ..utils.fixes import Counter +from .hashing import FeatureHasher from .stop_words import ENGLISH_STOP_WORDS +from ..utils import deprecated +from ..utils.fixes import frombuffer_empty, bincount +from ..utils.validation import check_is_fitted __all__ = ['CountVectorizer', 'ENGLISH_STOP_WORDS', @@ -46,8 +55,8 @@ def strip_accents_unicode(s): Remove accentuated char for any unicode symbol that has a direct ASCII equivalent. """ - return u''.join([c for c in unicodedata.normalize('NFKD', s) - if not unicodedata.combining(c)]) + return ''.join([c for c in unicodedata.normalize('NFKD', s) + if not unicodedata.combining(c)]) def strip_accents_ascii(s): @@ -71,178 +80,22 @@ def strip_tags(s): For serious HTML/XML preprocessing you should rather use an external library such as lxml or BeautifulSoup. """ - return re.compile(ur"<([^>]+)>", flags=re.UNICODE).sub(u" ", s) + return re.compile(r"<([^>]+)>", flags=re.UNICODE).sub(" ", s) def _check_stop_list(stop): if stop == "english": return ENGLISH_STOP_WORDS - elif isinstance(stop, str) or isinstance(stop, unicode): + elif isinstance(stop, six.string_types): raise ValueError("not a built-in stop list: %s" % stop) else: # assume it's a collection return stop -class CountVectorizer(BaseEstimator): - """Convert a collection of raw documents to a matrix of token counts +class VectorizerMixin(object): + """Provides common code for text vectorizers (tokenization logic).""" - This implementation produces a sparse representation of the counts using - scipy.sparse.coo_matrix. - - If you do not provide an a-priori dictionary and you do not use an analyzer - that does some kind of feature selection then the number of features will - be equal to the vocabulary size found by analysing the data. The default - analyzer does simple stop word filtering for English. - - Parameters - ---------- - input: string {'filename', 'file', 'content'} - If filename, the sequence passed as an argument to fit is - expected to be a list of filenames that need reading to fetch - the raw content to analyze. - - If 'file', the sequence items must have 'read' method (file-like - object) it is called to fetch the bytes in memory. - - Otherwise the input is expected to be the sequence strings or - bytes items are expected to be analyzed directly. - - charset: string, 'utf-8' by default. - If bytes or files are given to analyze, this charset is used to - decode. - - charset_error: {'strict', 'ignore', 'replace'} - Instruction on what to do if a byte sequence is given to analyze that - contains characters not of the given `charset`. By default, it is - 'strict', meaning that a UnicodeDecodeError will be raised. Other - values are 'ignore' and 'replace'. - - strip_accents: {'ascii', 'unicode', None} - Remove accents during the preprocessing step. - 'ascii' is a fast method that only works on characters that have - an direct ASCII mapping. - 'unicode' is a slightly slower method that works on any characters. - None (default) does nothing. - - analyzer: string, {'word', 'char', 'char_wb'} or callable - Whether the feature should be made of word or character n-grams. - Option 'char_wb' creates character n-grams only from text inside - word boundaries. - - If a callable is passed it is used to extract the sequence of features - out of the raw, unprocessed input. - - preprocessor: callable or None (default) - Override the preprocessing (string transformation) stage while - preserving the tokenizing and n-grams generation steps. - - tokenizer: callable or None (default) - Override the string tokenization step while preserving the - preprocessing and n-grams generation steps. - - ngram_range: tuple (min_n, max_n) - The lower and upper boundary of the range of n-values for different - n-grams to be extracted. All values of n such that min_n <= n <= max_n - will be used. - - stop_words: string {'english'}, list, or None (default) - If a string, it is passed to _check_stop_list and the appropriate stop - list is returned is currently the only - supported string value. - - If a list, that list is assumed to contain stop words, all of which - will be removed from the resulting tokens. - - If None, no stop words will be used. max_df can be set to a value - in the range [0.7, 1.0) to automatically detect and filter stop - words based on intra corpus document frequency of terms. - - lowercase: boolean, default True - Convert all characters to lowercase befor tokenizing. - - token_pattern: string - Regular expression denoting what constitutes a "token", only used - if `tokenize == 'word'`. The default regexp select tokens of 2 - or more letters characters (punctuation is completely ignored - and always treated as a token separator). - - max_df : float in range [0.0, 1.0] or int, optional, 1.0 by default - When building the vocabulary ignore terms that have a term frequency - strictly higher than the given threshold (corpus specific stop words). - If float, the parameter represents a proportion of documents, integer - absolute counts. - This parameter is ignored if vocabulary is not None. - - min_df : float in range [0.0, 1.0] or int, optional, 2 by default - When building the vocabulary ignore terms that have a term frequency - strictly lower than the given threshold. This value is also called - cut-off in the literature. - If float, the parameter represents a proportion of documents, integer - absolute counts. - This parameter is ignored if vocabulary is not None. - - max_features : optional, None by default - If not None, build a vocabulary that only consider the top - max_features ordered by term frequency across the corpus. - - This parameter is ignored if vocabulary is not None. - - vocabulary: Mapping or iterable, optional - Either a Mapping (e.g., a dict) where keys are terms and values are - indices in the feature matrix, or an iterable over terms. If not - given, a vocabulary is determined from the input documents. - - binary: boolean, False by default. - If True, all non zero counts are set to 1. This is useful for discrete - probabilistic models that model binary events rather than integer - counts. - - dtype: type, optional - Type of the matrix returned by fit_transform() or transform(). - """ - - _white_spaces = re.compile(ur"\s\s+") - - def __init__(self, input='content', charset='utf-8', - charset_error='strict', strip_accents=None, - lowercase=True, preprocessor=None, tokenizer=None, - stop_words=None, token_pattern=ur"(?u)\b\w\w+\b", - ngram_range=(1, 1), - min_n=None, max_n=None, analyzer='word', - max_df=1.0, min_df=2, max_features=None, - vocabulary=None, binary=False, dtype=long): - self.input = input - self.charset = charset - self.charset_error = charset_error - self.strip_accents = strip_accents - self.preprocessor = preprocessor - self.tokenizer = tokenizer - self.analyzer = analyzer - self.lowercase = lowercase - self.token_pattern = token_pattern - self.stop_words = stop_words - self.max_df = max_df - self.min_df = min_df - self.max_features = max_features - if not (max_n is None) or not (min_n is None): - warnings.warn('Parameters max_n and min_n are deprecated. Use ' - 'ngram_range instead. This will be removed in 0.14.', - DeprecationWarning, stacklevel=2) - if min_n is None: - min_n = 1 - if max_n is None: - max_n = min_n - ngram_range = (min_n, max_n) - self.ngram_range = ngram_range - if vocabulary is not None: - self.fixed_vocabulary = True - if not isinstance(vocabulary, Mapping): - vocabulary = dict((t, i) for i, t in enumerate(vocabulary)) - self.vocabulary_ = vocabulary - else: - self.fixed_vocabulary = False - self.binary = binary - self.dtype = dtype + _white_spaces = re.compile(r"\s\s+") def decode(self, doc): """Decode the input into a string of unicode symbols @@ -250,13 +103,19 @@ def decode(self, doc): The decoding strategy depends on the vectorizer parameters. """ if self.input == 'filename': - doc = open(doc, 'rb').read() + with open(doc, 'rb') as fh: + doc = fh.read() elif self.input == 'file': doc = doc.read() if isinstance(doc, bytes): - doc = doc.decode(self.charset, self.charset_error) + doc = doc.decode(self.encoding, self.decode_error) + + if doc is np.nan: + raise ValueError("np.nan is an invalid document, expected byte or " + "unicode string.") + return doc def _word_ngrams(self, tokens, stop_words=None): @@ -274,14 +133,14 @@ def _word_ngrams(self, tokens, stop_words=None): for n in xrange(min_n, min(max_n + 1, n_original_tokens + 1)): for i in xrange(n_original_tokens - n + 1): - tokens.append(u" ".join(original_tokens[i: i + n])) + tokens.append(" ".join(original_tokens[i: i + n])) return tokens def _char_ngrams(self, text_document): """Tokenize text_document into a sequence of character n-grams""" # normalize white spaces - text_document = self._white_spaces.sub(u" ", text_document) + text_document = self._white_spaces.sub(" ", text_document) text_len = len(text_document) ngrams = [] @@ -297,12 +156,12 @@ def _char_wb_ngrams(self, text_document): Tokenize text_document into a sequence of character n-grams excluding any whitespace (operating only inside word boundaries)""" # normalize white spaces - text_document = self._white_spaces.sub(u" ", text_document) + text_document = self._white_spaces.sub(" ", text_document) min_n, max_n = self.ngram_range ngrams = [] for w in text_document.split(): - w = u' ' + w + u' ' + w = ' ' + w + ' ' w_len = len(w) for n in xrange(min_n, max_n + 1): offset = 0 @@ -321,7 +180,7 @@ def build_preprocessor(self): # unfortunately python functools package does not have an efficient # `compose` function that would have allowed us to chain a dynamic - # number of functions. However the however of a lambda call is a few + # number of functions. However the cost of a lambda call is a few # hundreds of nanoseconds which is negligible when compared to the # cost of tokenizing a string of 1000 chars for instance. noop = lambda x: x @@ -329,7 +188,7 @@ def build_preprocessor(self): # accent stripping if not self.strip_accents: strip_accents = noop - elif hasattr(self.strip_accents, '__call__'): + elif callable(self.strip_accents): strip_accents = self.strip_accents elif self.strip_accents == 'ascii': strip_accents = strip_accents_ascii @@ -345,7 +204,7 @@ def build_preprocessor(self): return strip_accents def build_tokenizer(self): - """Return a function that split a string in sequence of tokens""" + """Return a function that splits a string into a sequence of tokens""" if self.tokenizer is not None: return self.tokenizer token_pattern = re.compile(self.token_pattern) @@ -357,7 +216,7 @@ def get_stop_words(self): def build_analyzer(self): """Return a callable that handles preprocessing and tokenization""" - if hasattr(self.analyzer, '__call__'): + if callable(self.analyzer): return self.analyzer preprocess = self.build_preprocessor() @@ -380,36 +239,535 @@ def build_analyzer(self): raise ValueError('%s is not a valid tokenization scheme/analyzer' % self.analyzer) - def _term_count_dicts_to_matrix(self, term_count_dicts): - i_indices = [] - j_indices = [] - values = [] - vocabulary = self.vocabulary_ - - for i, term_count_dict in enumerate(term_count_dicts): - for term, count in term_count_dict.iteritems(): - j = vocabulary.get(term) - if j is not None: - i_indices.append(i) - j_indices.append(j) - values.append(count) - # free memory as we go - term_count_dict.clear() - - shape = (len(term_count_dicts), max(vocabulary.itervalues()) + 1) - spmatrix = sp.coo_matrix((values, (i_indices, j_indices)), - shape=shape, dtype=self.dtype) + def _validate_vocabulary(self): + vocabulary = self.vocabulary + if vocabulary is not None: + if not isinstance(vocabulary, Mapping): + vocab = {} + for i, t in enumerate(vocabulary): + if vocab.setdefault(t, i) != i: + msg = "Duplicate term in vocabulary: %r" % t + raise ValueError(msg) + vocabulary = vocab + else: + indices = set(six.itervalues(vocabulary)) + if len(indices) != len(vocabulary): + raise ValueError("Vocabulary contains repeated indices.") + for i in xrange(len(vocabulary)): + if i not in indices: + msg = ("Vocabulary of size %d doesn't contain index " + "%d." % (len(vocabulary), i)) + raise ValueError(msg) + if not vocabulary: + raise ValueError("empty vocabulary passed to fit") + self.fixed_vocabulary_ = True + self.vocabulary_ = dict(vocabulary) + else: + self.fixed_vocabulary_ = False + + def _check_vocabulary(self): + """Check if vocabulary is empty or missing (not fit-ed)""" + msg="%(name)s - Vocabulary wasn't fitted." + check_is_fitted(self, 'vocabulary_', msg=msg), + + if len(self.vocabulary_) == 0: + raise ValueError("Vocabulary is empty") + + @property + @deprecated("The `fixed_vocabulary` attribute is deprecated and will be " + "removed in 0.18. Please use `fixed_vocabulary_` instead.") + def fixed_vocabulary(self): + return self.fixed_vocabulary_ + + +class HashingVectorizer(BaseEstimator, VectorizerMixin): + """Convert a collection of text documents to a matrix of token occurrences + + It turns a collection of text documents into a scipy.sparse matrix holding + token occurrence counts (or binary occurrence information), possibly + normalized as token frequencies if norm='l1' or projected on the euclidean + unit sphere if norm='l2'. + + This text vectorizer implementation uses the hashing trick to find the + token string name to feature integer index mapping. + + This strategy has several advantages: + + - it is very low memory scalable to large datasets as there is no need to + store a vocabulary dictionary in memory + + - it is fast to pickle and un-pickle as it holds no state besides the + constructor parameters + + - it can be used in a streaming (partial fit) or parallel pipeline as there + is no state computed during fit. + + There are also a couple of cons (vs using a CountVectorizer with an + in-memory vocabulary): + + - there is no way to compute the inverse transform (from feature indices to + string feature names) which can be a problem when trying to introspect + which features are most important to a model. + + - there can be collisions: distinct tokens can be mapped to the same + feature index. However in practice this is rarely an issue if n_features + is large enough (e.g. 2 ** 18 for text classification problems). + + - no IDF weighting as this would render the transformer stateful. + + The hash function employed is the signed 32-bit version of Murmurhash3. + + Parameters + ---------- + + input: string {'filename', 'file', 'content'} + If 'filename', the sequence passed as an argument to fit is + expected to be a list of filenames that need reading to fetch + the raw content to analyze. + + If 'file', the sequence items must have a 'read' method (file-like + object) that is called to fetch the bytes in memory. + + Otherwise the input is expected to be the sequence strings or + bytes items are expected to be analyzed directly. + + encoding : string, 'utf-8' by default. + If bytes or files are given to analyze, this encoding is used to + decode. + + decode_error : {'strict', 'ignore', 'replace'} + Instruction on what to do if a byte sequence is given to analyze that + contains characters not of the given `encoding`. By default, it is + 'strict', meaning that a UnicodeDecodeError will be raised. Other + values are 'ignore' and 'replace'. + + strip_accents: {'ascii', 'unicode', None} + Remove accents during the preprocessing step. + 'ascii' is a fast method that only works on characters that have + an direct ASCII mapping. + 'unicode' is a slightly slower method that works on any characters. + None (default) does nothing. + + analyzer: string, {'word', 'char', 'char_wb'} or callable + Whether the feature should be made of word or character n-grams. + Option 'char_wb' creates character n-grams only from text inside + word boundaries. + + If a callable is passed it is used to extract the sequence of features + out of the raw, unprocessed input. + + preprocessor: callable or None (default) + Override the preprocessing (string transformation) stage while + preserving the tokenizing and n-grams generation steps. + + tokenizer: callable or None (default) + Override the string tokenization step while preserving the + preprocessing and n-grams generation steps. + + ngram_range: tuple (min_n, max_n) + The lower and upper boundary of the range of n-values for different + n-grams to be extracted. All values of n such that min_n <= n <= max_n + will be used. + + stop_words: string {'english'}, list, or None (default) + If 'english', a built-in stop word list for English is used. + + If a list, that list is assumed to contain stop words, all of which + will be removed from the resulting tokens. + + lowercase: boolean, default True + Convert all characters to lowercase before tokenizing. + + token_pattern: string + Regular expression denoting what constitutes a "token", only used + if `analyzer == 'word'`. The default regexp selects tokens of 2 + or more alphanumeric characters (punctuation is completely ignored + and always treated as a token separator). + + n_features : integer, optional, (2 ** 20) by default + The number of features (columns) in the output matrices. Small numbers + of features are likely to cause hash collisions, but large numbers + will cause larger coefficient dimensions in linear learners. + + norm : 'l1', 'l2' or None, optional + Norm used to normalize term vectors. None for no normalization. + + binary: boolean, False by default. + If True, all non zero counts are set to 1. This is useful for discrete + probabilistic models that model binary events rather than integer + counts. + + dtype: type, optional + Type of the matrix returned by fit_transform() or transform(). + + non_negative : boolean, optional + Whether output matrices should contain non-negative values only; + effectively calls abs on the matrix prior to returning it. + When True, output values can be interpreted as frequencies. + When False, output values will have expected value zero. + + See also + -------- + CountVectorizer, TfidfVectorizer + + """ + def __init__(self, input='content', encoding='utf-8', + decode_error='strict', strip_accents=None, + lowercase=True, preprocessor=None, tokenizer=None, + stop_words=None, token_pattern=r"(?u)\b\w\w+\b", + ngram_range=(1, 1), analyzer='word', n_features=(2 ** 20), + binary=False, norm='l2', non_negative=False, + dtype=np.float64): + self.input = input + self.encoding = encoding + self.decode_error = decode_error + self.strip_accents = strip_accents + self.preprocessor = preprocessor + self.tokenizer = tokenizer + self.analyzer = analyzer + self.lowercase = lowercase + self.token_pattern = token_pattern + self.stop_words = stop_words + self.n_features = n_features + self.ngram_range = ngram_range + self.binary = binary + self.norm = norm + self.non_negative = non_negative + self.dtype = dtype + + def partial_fit(self, X, y=None): + """Does nothing: this transformer is stateless. + + This method is just there to mark the fact that this transformer + can work in a streaming setup. + + """ + return self + + def fit(self, X, y=None): + """Does nothing: this transformer is stateless.""" + # triggers a parameter validation + self._get_hasher().fit(X, y=y) + return self + + def transform(self, X, y=None): + """Transform a sequence of documents to a document-term matrix. + + Parameters + ---------- + X : iterable over raw text documents, length = n_samples + Samples. Each sample must be a text document (either bytes or + unicode strings, file name or file object depending on the + constructor argument) which will be tokenized and hashed. + + y : (ignored) + + Returns + ------- + X : scipy.sparse matrix, shape = (n_samples, self.n_features) + Document-term matrix. + + """ + analyzer = self.build_analyzer() + X = self._get_hasher().transform(analyzer(doc) for doc in X) if self.binary: - spmatrix.data.fill(1) - return spmatrix + X.data.fill(1) + if self.norm is not None: + X = normalize(X, norm=self.norm, copy=False) + return X + + # Alias transform to fit_transform for convenience + fit_transform = transform + + def _get_hasher(self): + return FeatureHasher(n_features=self.n_features, + input_type='string', dtype=self.dtype, + non_negative=self.non_negative) + + +def _document_frequency(X): + """Count the number of non-zero values for each feature in sparse X.""" + if sp.isspmatrix_csr(X): + return bincount(X.indices, minlength=X.shape[1]) + else: + return np.diff(sp.csc_matrix(X, copy=False).indptr) + + +class CountVectorizer(BaseEstimator, VectorizerMixin): + """Convert a collection of text documents to a matrix of token counts + + This implementation produces a sparse representation of the counts using + scipy.sparse.coo_matrix. + + If you do not provide an a-priori dictionary and you do not use an analyzer + that does some kind of feature selection then the number of features will + be equal to the vocabulary size found by analyzing the data. + + Parameters + ---------- + input : string {'filename', 'file', 'content'} + If 'filename', the sequence passed as an argument to fit is + expected to be a list of filenames that need reading to fetch + the raw content to analyze. + + If 'file', the sequence items must have a 'read' method (file-like + object) that is called to fetch the bytes in memory. + + Otherwise the input is expected to be the sequence strings or + bytes items are expected to be analyzed directly. + + encoding : string, 'utf-8' by default. + If bytes or files are given to analyze, this encoding is used to + decode. + + decode_error : {'strict', 'ignore', 'replace'} + Instruction on what to do if a byte sequence is given to analyze that + contains characters not of the given `encoding`. By default, it is + 'strict', meaning that a UnicodeDecodeError will be raised. Other + values are 'ignore' and 'replace'. + + strip_accents : {'ascii', 'unicode', None} + Remove accents during the preprocessing step. + 'ascii' is a fast method that only works on characters that have + an direct ASCII mapping. + 'unicode' is a slightly slower method that works on any characters. + None (default) does nothing. + + analyzer : string, {'word', 'char', 'char_wb'} or callable + Whether the feature should be made of word or character n-grams. + Option 'char_wb' creates character n-grams only from text inside + word boundaries. + + If a callable is passed it is used to extract the sequence of features + out of the raw, unprocessed input. + + preprocessor : callable or None (default) + Override the preprocessing (string transformation) stage while + preserving the tokenizing and n-grams generation steps. + + tokenizer : callable or None (default) + Override the string tokenization step while preserving the + preprocessing and n-grams generation steps. + + ngram_range : tuple (min_n, max_n) + The lower and upper boundary of the range of n-values for different + n-grams to be extracted. All values of n such that min_n <= n <= max_n + will be used. + + stop_words : string {'english'}, list, or None (default) + If 'english', a built-in stop word list for English is used. + + If a list, that list is assumed to contain stop words, all of which + will be removed from the resulting tokens. + + If None, no stop words will be used. max_df can be set to a value + in the range [0.7, 1.0) to automatically detect and filter stop + words based on intra corpus document frequency of terms. + + lowercase : boolean, True by default + Convert all characters to lowercase before tokenizing. + + token_pattern : string + Regular expression denoting what constitutes a "token", only used + if `tokenize == 'word'`. The default regexp select tokens of 2 + or more alphanumeric characters (punctuation is completely ignored + and always treated as a token separator). + + max_df : float in range [0.0, 1.0] or int, optional, 1.0 by default + When building the vocabulary ignore terms that have a document + frequency strictly higher than the given threshold (corpus-specific + stop words). + If float, the parameter represents a proportion of documents, integer + absolute counts. + This parameter is ignored if vocabulary is not None. + + min_df : float in range [0.0, 1.0] or int, optional, 1 by default + When building the vocabulary ignore terms that have a document + frequency strictly lower than the given threshold. This value is also + called cut-off in the literature. + If float, the parameter represents a proportion of documents, integer + absolute counts. + This parameter is ignored if vocabulary is not None. + + max_features : optional, None by default + If not None, build a vocabulary that only consider the top + max_features ordered by term frequency across the corpus. + + This parameter is ignored if vocabulary is not None. + + vocabulary : Mapping or iterable, optional + Either a Mapping (e.g., a dict) where keys are terms and values are + indices in the feature matrix, or an iterable over terms. If not + given, a vocabulary is determined from the input documents. Indices + in the mapping should not be repeated and should not have any gap + between 0 and the largest index. + + binary : boolean, False by default. + If True, all non zero counts are set to 1. This is useful for discrete + probabilistic models that model binary events rather than integer + counts. + + dtype : type, optional + Type of the matrix returned by fit_transform() or transform(). + + Attributes + ---------- + vocabulary_ : dict + A mapping of terms to feature indices. + + stop_words_ : set + Terms that were ignored because they either: + + - occurred in too many documents (`max_df`) + - occurred in too few documents (`min_df`) + - were cut off by feature selection (`max_features`). + + This is only available if no vocabulary was given. + + See also + -------- + HashingVectorizer, TfidfVectorizer + + Notes + ----- + The ``stop_words_`` attribute can get large and increase the model size + when pickling. This attribute is provided only for introspection and can + be safely removed using delattr or set to None before pickling. + """ + + def __init__(self, input='content', encoding='utf-8', + decode_error='strict', strip_accents=None, + lowercase=True, preprocessor=None, tokenizer=None, + stop_words=None, token_pattern=r"(?u)\b\w\w+\b", + ngram_range=(1, 1), analyzer='word', + max_df=1.0, min_df=1, max_features=None, + vocabulary=None, binary=False, dtype=np.int64): + self.input = input + self.encoding = encoding + self.decode_error = decode_error + self.strip_accents = strip_accents + self.preprocessor = preprocessor + self.tokenizer = tokenizer + self.analyzer = analyzer + self.lowercase = lowercase + self.token_pattern = token_pattern + self.stop_words = stop_words + self.max_df = max_df + self.min_df = min_df + if max_df < 0 or min_df < 0: + raise ValueError("negative value for max_df of min_df") + self.max_features = max_features + if max_features is not None: + if (not isinstance(max_features, numbers.Integral) or + max_features <= 0): + raise ValueError( + "max_features=%r, neither a positive integer nor None" + % max_features) + self.ngram_range = ngram_range + self.vocabulary = vocabulary + self.binary = binary + self.dtype = dtype + + def _sort_features(self, X, vocabulary): + """Sort features by name + + Returns a reordered matrix and modifies the vocabulary in place + """ + sorted_features = sorted(six.iteritems(vocabulary)) + map_index = np.empty(len(sorted_features), dtype=np.int32) + for new_val, (term, old_val) in enumerate(sorted_features): + map_index[new_val] = old_val + vocabulary[term] = new_val + return X[:, map_index] + + def _limit_features(self, X, vocabulary, high=None, low=None, + limit=None): + """Remove too rare or too common features. + + Prune features that are non zero in more samples than high or less + documents than low, modifying the vocabulary, and restricting it to + at most the limit most frequent. + + This does not prune samples with zero features. + """ + if high is None and low is None and limit is None: + return X, set() + + # Calculate a mask based on document frequencies + dfs = _document_frequency(X) + tfs = np.asarray(X.sum(axis=0)).ravel() + mask = np.ones(len(dfs), dtype=bool) + if high is not None: + mask &= dfs <= high + if low is not None: + mask &= dfs >= low + if limit is not None and mask.sum() > limit: + mask_inds = (-tfs[mask]).argsort()[:limit] + new_mask = np.zeros(len(dfs), dtype=bool) + new_mask[np.where(mask)[0][mask_inds]] = True + mask = new_mask + + new_indices = np.cumsum(mask) - 1 # maps old indices to new + removed_terms = set() + for term, old_index in list(six.iteritems(vocabulary)): + if mask[old_index]: + vocabulary[term] = new_indices[old_index] + else: + del vocabulary[term] + removed_terms.add(term) + kept_indices = np.where(mask)[0] + if len(kept_indices) == 0: + raise ValueError("After pruning, no terms remain. Try a lower" + " min_df or a higher max_df.") + return X[:, kept_indices], removed_terms + + def _count_vocab(self, raw_documents, fixed_vocab): + """Create sparse feature matrix, and vocabulary where fixed_vocab=False + """ + if fixed_vocab: + vocabulary = self.vocabulary_ + else: + # Add a new value when a new vocabulary item is seen + vocabulary = defaultdict() + vocabulary.default_factory = vocabulary.__len__ + + analyze = self.build_analyzer() + j_indices = _make_int_array() + indptr = _make_int_array() + indptr.append(0) + for doc in raw_documents: + for feature in analyze(doc): + try: + j_indices.append(vocabulary[feature]) + except KeyError: + # Ignore out-of-vocabulary items for fixed_vocab=True + continue + indptr.append(len(j_indices)) + + if not fixed_vocab: + # disable defaultdict behaviour + vocabulary = dict(vocabulary) + if not vocabulary: + raise ValueError("empty vocabulary; perhaps the documents only" + " contain stop words") + + j_indices = frombuffer_empty(j_indices, dtype=np.intc) + indptr = np.frombuffer(indptr, dtype=np.intc) + values = np.ones(len(j_indices)) + + X = sp.csr_matrix((values, j_indices, indptr), + shape=(len(indptr) - 1, len(vocabulary)), + dtype=self.dtype) + X.sum_duplicates() + return vocabulary, X def fit(self, raw_documents, y=None): - """Learn a vocabulary dictionary of all tokens in the raw documents + """Learn a vocabulary dictionary of all tokens in the raw documents. Parameters ---------- - raw_documents: iterable - an iterable which yields either str, unicode or file objects + raw_documents : iterable + An iterable which yields either str, unicode or file objects. Returns ------- @@ -419,119 +777,83 @@ def fit(self, raw_documents, y=None): return self def fit_transform(self, raw_documents, y=None): - """Learn the vocabulary dictionary and return the count vectors + """Learn the vocabulary dictionary and return term-document matrix. - This is more efficient than calling fit followed by transform. + This is equivalent to fit followed by transform, but more efficiently + implemented. Parameters ---------- - raw_documents: iterable - an iterable which yields either str, unicode or file objects + raw_documents : iterable + An iterable which yields either str, unicode or file objects. Returns ------- - vectors: array, [n_samples, n_features] + X : array, [n_samples, n_features] + Document-term matrix. """ - if self.fixed_vocabulary: - # No need to fit anything, directly perform the transformation. - # We intentionally don't call the transform method to make it - # fit_transform overridable without unwanted side effects in - # TfidfVectorizer - analyze = self.build_analyzer() - term_counts_per_doc = [Counter(analyze(doc)) - for doc in raw_documents] - return self._term_count_dicts_to_matrix(term_counts_per_doc) - - self.vocabulary_ = {} - # result of document conversion to term count dicts - term_counts_per_doc = [] - term_counts = Counter() - - # term counts across entire corpus (count each term maximum once per - # document) - document_counts = Counter() - - analyze = self.build_analyzer() - - # TODO: parallelize the following loop with joblib? - # (see XXX up ahead) - for doc in raw_documents: - term_count_current = Counter(analyze(doc)) - term_counts.update(term_count_current) - - document_counts.update(term_count_current.iterkeys()) - - term_counts_per_doc.append(term_count_current) - - n_doc = len(term_counts_per_doc) - max_features = self.max_features + # We intentionally don't call the transform method to make + # fit_transform overridable without unwanted side effects in + # TfidfVectorizer. + self._validate_vocabulary() max_df = self.max_df min_df = self.min_df + max_features = self.max_features - max_doc_count = (max_df if isinstance(max_df, (int, np.integer)) - else max_df * n_doc) - min_doc_count = (min_df if isinstance(min_df, (int, np.integer)) - else min_df * n_doc) - - # filter out stop words: terms that occur in almost all documents - if max_doc_count < n_doc or min_doc_count > 1: - stop_words = set(t for t, dc in document_counts.iteritems() - if dc > max_doc_count or dc < min_doc_count) - else: - stop_words = set() - - # list the terms that should be part of the vocabulary - if max_features is None: - terms = set(term_counts) - stop_words - else: - # extract the most frequent terms for the vocabulary - terms = set() - for t, tc in term_counts.most_common(): - if t not in stop_words: - terms.add(t) - if len(terms) >= max_features: - break + vocabulary, X = self._count_vocab(raw_documents, + self.fixed_vocabulary_) - # store the learned stop words to make it easier to debug the value of - # max_df - self.max_df_stop_words_ = stop_words + if self.binary: + X.data.fill(1) + + if not self.fixed_vocabulary_: + X = self._sort_features(X, vocabulary) + + n_doc = X.shape[0] + max_doc_count = (max_df + if isinstance(max_df, numbers.Integral) + else max_df * n_doc) + min_doc_count = (min_df + if isinstance(min_df, numbers.Integral) + else min_df * n_doc) + if max_doc_count < min_doc_count: + raise ValueError( + "max_df corresponds to < documents than min_df") + X, self.stop_words_ = self._limit_features(X, vocabulary, + max_doc_count, + min_doc_count, + max_features) - # store map from term name to feature integer index: we sort the term - # to have reproducible outcome for the vocabulary structure: otherwise - # the mapping from feature name to indices might depend on the memory - # layout of the machine. Furthermore sorted terms might make it - # possible to perform binary search in the feature names array. - self.vocabulary_ = dict(((t, i) for i, t in enumerate(sorted(terms)))) + self.vocabulary_ = vocabulary - # the term_counts and document_counts might be useful statistics, are - # we really sure want we want to drop them? They take some memory but - # can be useful for corpus introspection - return self._term_count_dicts_to_matrix(term_counts_per_doc) + return X def transform(self, raw_documents): - """Extract token counts out of raw text documents using the vocabulary - fitted with fit or the one provided in the constructor. + """Transform documents to document-term matrix. + + Extract token counts out of raw text documents using the vocabulary + fitted with fit or the one provided to the constructor. Parameters ---------- - raw_documents: iterable - an iterable which yields either str, unicode or file objects + raw_documents : iterable + An iterable which yields either str, unicode or file objects. Returns ------- - vectors: sparse matrix, [n_samples, n_features] + X : sparse matrix, [n_samples, n_features] + Document-term matrix. """ - if not hasattr(self, 'vocabulary_') or len(self.vocabulary_) == 0: - raise ValueError("Vocabulary wasn't fitted or is empty!") - - # raw_documents can be an iterable so we don't know its size in - # advance + if not hasattr(self, 'vocabulary_'): + self._validate_vocabulary() + + self._check_vocabulary() - # XXX @larsmans tried to parallelize the following loop with joblib. - # The result was some 20% slower than the serial version. - analyze = self.build_analyzer() - term_counts_per_doc = [Counter(analyze(doc)) for doc in raw_documents] - return self._term_count_dicts_to_matrix(term_counts_per_doc) + # use the same matrix-building strategy as fit_transform + _, X = self._count_vocab(raw_documents, fixed_vocab=True) + if self.binary: + X.data.fill(1) + return X def inverse_transform(self, X): """Return terms per document with nonzero entries in X. @@ -545,46 +867,59 @@ def inverse_transform(self, X): X_inv : list of arrays, len = n_samples List of arrays of terms. """ - if sp.isspmatrix_coo(X): # COO matrix is not indexable + self._check_vocabulary() + + if sp.issparse(X): + # We need CSR format for fast row manipulations. X = X.tocsr() - elif not sp.issparse(X): + else: # We need to convert X to a matrix, so that the indexing # returns 2D objects X = np.asmatrix(X) n_samples = X.shape[0] - terms = np.array(self.vocabulary_.keys()) - indices = np.array(self.vocabulary_.values()) + terms = np.array(list(self.vocabulary_.keys())) + indices = np.array(list(self.vocabulary_.values())) inverse_vocabulary = terms[np.argsort(indices)] return [inverse_vocabulary[X[i, :].nonzero()[1]].ravel() - for i in xrange(n_samples)] + for i in range(n_samples)] def get_feature_names(self): """Array mapping from feature integer indices to feature name""" - if not hasattr(self, 'vocabulary_') or len(self.vocabulary_) == 0: - raise ValueError("Vocabulary wasn't fitted or is empty!") + self._check_vocabulary() - return [t for t, i in sorted(self.vocabulary_.iteritems(), + return [t for t, i in sorted(six.iteritems(self.vocabulary_), key=itemgetter(1))] +def _make_int_array(): + """Construct an array.array of a type suitable for scipy.sparse indices.""" + return array.array(str("i")) + + class TfidfTransformer(BaseEstimator, TransformerMixin): - """Transform a count matrix to a normalized tf or tf–idf representation + """Transform a count matrix to a normalized tf or tf-idf representation - Tf means term-frequency while tf–idf means term-frequency times inverse + Tf means term-frequency while tf-idf means term-frequency times inverse document-frequency. This is a common term weighting scheme in information retrieval, that has also found good use in document classification. - The goal of using tf–idf instead of the raw frequencies of occurrence of a + The goal of using tf-idf instead of the raw frequencies of occurrence of a token in a given document is to scale down the impact of tokens that occur very frequently in a given corpus and that are hence empirically less informative than features that occur in a small fraction of the training corpus. - In the SMART notation used in IR, this class implements several tf–idf - variants. Tf is always "n" (natural), idf is "t" iff use_idf is given, - "n" otherwise, and normalization is "c" iff norm='l2', "n" iff norm=None. + The actual formula used for tf-idf is tf * (idf + 1) = tf + tf * idf, + instead of tf * idf. The effect of this is that terms with zero idf, i.e. + that occur in all documents of a training set, will not be entirely + ignored. The formulas used to compute tf and idf depend on parameter + settings that correspond to the SMART notation used in IR, as follows: + + Tf is "n" (natural) by default, "l" (logarithmic) when sublinear_tf=True. + Idf is "t" when use_idf is given, "n" (none) otherwise. + Normalization is "c" (cosine) when norm='l2', "n" (none) when norm=None. Parameters ---------- @@ -606,11 +941,11 @@ class TfidfTransformer(BaseEstimator, TransformerMixin): ---------- .. [Yates2011] `R. Baeza-Yates and B. Ribeiro-Neto (2011). Modern - Information Retrieval. Addison Wesley, pp. 68–74.` + Information Retrieval. Addison Wesley, pp. 68-74.` - .. [MSR2008] `C.D. Manning, H. Schütze and P. Raghavan (2008). Introduction - to Information Retrieval. Cambridge University Press, - pp. 121–125.` + .. [MRS2008] `C.D. Manning, P. Raghavan and H. Schuetze (2008). + Introduction to Information Retrieval. Cambridge University + Press, pp. 118-120.` """ def __init__(self, norm='l2', use_idf=True, smooth_idf=True, @@ -625,42 +960,42 @@ def fit(self, X, y=None): Parameters ---------- - X: sparse matrix, [n_samples, n_features] + X : sparse matrix, [n_samples, n_features] a matrix of term/token counts """ + if not sp.issparse(X): + X = sp.csc_matrix(X) if self.use_idf: - if not hasattr(X, 'nonzero'): - X = sp.csr_matrix(X) - n_samples, n_features = X.shape - df = np.bincount(X.nonzero()[1]) - if df.shape[0] < n_features: - # bincount might return fewer bins than there are features - df = np.concatenate([df, np.zeros(n_features - df.shape[0])]) + df = _document_frequency(X) # perform idf smoothing if required df += int(self.smooth_idf) n_samples += int(self.smooth_idf) - # avoid division by zeros for features that occur in all documents + # log1p instead of log makes sure terms with zero idf don't get + # suppressed entirely idf = np.log(float(n_samples) / df) + 1.0 - idf_diag = sp.lil_matrix((n_features, n_features)) - idf_diag.setdiag(idf) - self._idf_diag = sp.csc_matrix(idf_diag) + self._idf_diag = sp.spdiags(idf, + diags=0, m=n_features, n=n_features) return self def transform(self, X, copy=True): - """Transform a count matrix to a tf or tf–idf representation + """Transform a count matrix to a tf or tf-idf representation Parameters ---------- - X: sparse matrix, [n_samples, n_features] + X : sparse matrix, [n_samples, n_features] a matrix of term/token counts + copy : boolean, default True + Whether to copy X and operate on the copy or perform in-place + operations. + Returns ------- - vectors: sparse matrix, [n_samples, n_features] + vectors : sparse matrix, [n_samples, n_features] """ if hasattr(X, 'dtype') and np.issubdtype(X.dtype, np.float): # preserve float family dtype @@ -676,6 +1011,8 @@ def transform(self, X, copy=True): X.data += 1 if self.use_idf: + check_is_fitted(self, '_idf_diag', 'idf vector is not fitted') + expected_n_features = self._idf_diag.shape[0] if n_features != expected_n_features: raise ValueError("Input has n_features=%d while the model" @@ -704,58 +1041,57 @@ class TfidfVectorizer(CountVectorizer): Parameters ---------- - input: string {'filename', 'file', 'content'} - If filename, the sequence passed as an argument to fit is + input : string {'filename', 'file', 'content'} + If 'filename', the sequence passed as an argument to fit is expected to be a list of filenames that need reading to fetch the raw content to analyze. - If 'file', the sequence items must have 'read' method (file-like - object) it is called to fetch the bytes in memory. + If 'file', the sequence items must have a 'read' method (file-like + object) that is called to fetch the bytes in memory. Otherwise the input is expected to be the sequence strings or bytes items are expected to be analyzed directly. - charset: string, 'utf-8' by default. - If bytes or files are given to analyze, this charset is used to + encoding : string, 'utf-8' by default. + If bytes or files are given to analyze, this encoding is used to decode. - charset_error: {'strict', 'ignore', 'replace'} + decode_error : {'strict', 'ignore', 'replace'} Instruction on what to do if a byte sequence is given to analyze that - contains characters not of the given `charset`. By default, it is + contains characters not of the given `encoding`. By default, it is 'strict', meaning that a UnicodeDecodeError will be raised. Other values are 'ignore' and 'replace'. - strip_accents: {'ascii', 'unicode', None} + strip_accents : {'ascii', 'unicode', None} Remove accents during the preprocessing step. 'ascii' is a fast method that only works on characters that have an direct ASCII mapping. 'unicode' is a slightly slower method that works on any characters. None (default) does nothing. - analyzer: string, {'word', 'char'} or callable + analyzer : string, {'word', 'char'} or callable Whether the feature should be made of word or character n-grams. If a callable is passed it is used to extract the sequence of features out of the raw, unprocessed input. - preprocessor: callable or None (default) + preprocessor : callable or None (default) Override the preprocessing (string transformation) stage while preserving the tokenizing and n-grams generation steps. - tokenizer: callable or None (default) + tokenizer : callable or None (default) Override the string tokenization step while preserving the preprocessing and n-grams generation steps. - - ngram_range: tuple (min_n, max_n) + ngram_range : tuple (min_n, max_n) The lower and upper boundary of the range of n-values for different n-grams to be extracted. All values of n such that min_n <= n <= max_n will be used. - stop_words: string {'english'}, list, or None (default) + stop_words : string {'english'}, list, or None (default) If a string, it is passed to _check_stop_list and the appropriate stop - list is returned is currently the only - supported string value. + list is returned. 'english' is currently the only supported string + value. If a list, that list is assumed to contain stop words, all of which will be removed from the resulting tokens. @@ -764,24 +1100,24 @@ class TfidfVectorizer(CountVectorizer): in the range [0.7, 1.0) to automatically detect and filter stop words based on intra corpus document frequency of terms. - lowercase: boolean, default True - Convert all characters to lowercase befor tokenizing. + lowercase : boolean, default True + Convert all characters to lowercase before tokenizing. - token_pattern: string + token_pattern : string Regular expression denoting what constitutes a "token", only used - if `tokenize == 'word'`. The default regexp select tokens of 2 - or more letters characters (punctuation is completely ignored + if `analyzer == 'word'`. The default regexp selects tokens of 2 + or more alphanumeric characters (punctuation is completely ignored and always treated as a token separator). max_df : float in range [0.0, 1.0] or int, optional, 1.0 by default - When building the vocabulary ignore terms that have a term frequency + When building the vocabulary ignore terms that have a document frequency strictly higher than the given threshold (corpus specific stop words). If float, the parameter represents a proportion of documents, integer absolute counts. This parameter is ignored if vocabulary is not None. - min_df : float in range [0.0, 1.0] or int, optional, 2 by default - When building the vocabulary ignore terms that have a term frequency + min_df : float in range [0.0, 1.0] or int, optional, 1 by default + When building the vocabulary ignore terms that have a document frequency strictly lower than the given threshold. This value is also called cut-off in the literature. If float, the parameter represents a proportion of documents, integer @@ -794,17 +1130,17 @@ class TfidfVectorizer(CountVectorizer): This parameter is ignored if vocabulary is not None. - vocabulary: Mapping or iterable, optional + vocabulary : Mapping or iterable, optional Either a Mapping (e.g., a dict) where keys are terms and values are indices in the feature matrix, or an iterable over terms. If not given, a vocabulary is determined from the input documents. - binary: boolean, False by default. - If True, all non zero counts are set to 1. This is useful for discrete - probabilistic models that model binary events rather than integer - counts. + binary : boolean, False by default. + If True, all non-zero term counts are set to 1. This does not mean + outputs will have only 0/1 values, only that the tf term in tf-idf + is binary. (Set idf and normalization to False to get 0/1 outputs.) - dtype: type, optional + dtype : type, optional Type of the matrix returned by fit_transform() or transform(). norm : 'l1', 'l2' or None, optional @@ -821,6 +1157,21 @@ class TfidfVectorizer(CountVectorizer): sublinear_tf : boolean, optional Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf). + Attributes + ---------- + idf_ : array, shape = [n_features], or None + The learned idf vector (global term weights) + when ``use_idf`` is set to True, None otherwise. + + stop_words_ : set + Terms that were ignored because they either: + + - occurred in too many documents (`max_df`) + - occurred in too few documents (`min_df`) + - were cut off by feature selection (`max_features`). + + This is only available if no vocabulary was given. + See also -------- CountVectorizer @@ -830,24 +1181,30 @@ class TfidfVectorizer(CountVectorizer): TfidfTransformer Apply Term Frequency Inverse Document Frequency normalization to a sparse matrix of occurrence counts. - + + Notes + ----- + The ``stop_words_`` attribute can get large and increase the model size + when pickling. This attribute is provided only for introspection and can + be safely removed using delattr or set to None before pickling. """ - def __init__(self, input='content', charset='utf-8', - charset_error='strict', strip_accents=None, lowercase=True, - preprocessor=None, tokenizer=None, analyzer='word', - stop_words=None, token_pattern=ur"(?u)\b\w\w+\b", min_n=None, - max_n=None, ngram_range=(1, 1), max_df=1.0, min_df=2, - max_features=None, vocabulary=None, binary=False, dtype=long, - norm='l2', use_idf=True, smooth_idf=True, sublinear_tf=False): + def __init__(self, input='content', encoding='utf-8', + decode_error='strict', strip_accents=None, lowercase=True, + preprocessor=None, tokenizer=None, analyzer='word', + stop_words=None, token_pattern=r"(?u)\b\w\w+\b", + ngram_range=(1, 1), max_df=1.0, min_df=1, + max_features=None, vocabulary=None, binary=False, + dtype=np.int64, norm='l2', use_idf=True, smooth_idf=True, + sublinear_tf=False): super(TfidfVectorizer, self).__init__( - input=input, charset=charset, charset_error=charset_error, + input=input, encoding=encoding, decode_error=decode_error, strip_accents=strip_accents, lowercase=lowercase, preprocessor=preprocessor, tokenizer=tokenizer, analyzer=analyzer, - stop_words=stop_words, token_pattern=token_pattern, min_n=min_n, - max_n=max_n, ngram_range=ngram_range, max_df=max_df, min_df=min_df, - max_features=max_features, vocabulary=vocabulary, binary=False, + stop_words=stop_words, token_pattern=token_pattern, + ngram_range=ngram_range, max_df=max_df, min_df=min_df, + max_features=max_features, vocabulary=vocabulary, binary=binary, dtype=dtype) self._tfidf = TfidfTransformer(norm=norm, use_idf=use_idf, @@ -889,23 +1246,41 @@ def sublinear_tf(self): def sublinear_tf(self, value): self._tfidf.sublinear_tf = value + @property + def idf_(self): + return self._tfidf.idf_ + def fit(self, raw_documents, y=None): - """Learn a conversion law from documents to array data""" + """Learn vocabulary and idf from training set. + + Parameters + ---------- + raw_documents : iterable + an iterable which yields either str, unicode or file objects + + Returns + ------- + self : TfidfVectorizer + """ X = super(TfidfVectorizer, self).fit_transform(raw_documents) self._tfidf.fit(X) return self def fit_transform(self, raw_documents, y=None): - """Learn the representation and return the vectors. + """Learn vocabulary and idf, return term-document matrix. + + This is equivalent to fit followed by transform, but more efficiently + implemented. Parameters ---------- - raw_documents: iterable + raw_documents : iterable an iterable which yields either str, unicode or file objects Returns ------- - vectors: array, [n_samples, n_features] + X : sparse matrix, [n_samples, n_features] + Tf-idf-weighted document-term matrix. """ X = super(TfidfVectorizer, self).fit_transform(raw_documents) self._tfidf.fit(X) @@ -914,16 +1289,26 @@ def fit_transform(self, raw_documents, y=None): return self._tfidf.transform(X, copy=False) def transform(self, raw_documents, copy=True): - """Transform raw text documents to tf–idf vectors + """Transform documents to document-term matrix. + + Uses the vocabulary and document frequencies (df) learned by fit (or + fit_transform). Parameters ---------- - raw_documents: iterable + raw_documents : iterable an iterable which yields either str, unicode or file objects + copy : boolean, default True + Whether to copy X and operate on the copy or perform in-place + operations. + Returns ------- - vectors: sparse matrix, [n_samples, n_features] + X : sparse matrix, [n_samples, n_features] + Tf-idf-weighted document-term matrix. """ + check_is_fitted(self, '_tfidf', 'The tfidf vector is not fitted') + X = super(TfidfVectorizer, self).transform(raw_documents) - return self._tfidf.transform(X, copy) + return self._tfidf.transform(X, copy=False) diff --git a/sklearn/feature_selection/__init__.py b/sklearn/feature_selection/__init__.py index d52972adc6a40..0d222534f5e93 100644 --- a/sklearn/feature_selection/__init__.py +++ b/sklearn/feature_selection/__init__.py @@ -15,6 +15,8 @@ from .univariate_selection import SelectFwe from .univariate_selection import GenericUnivariateSelect +from .variance_threshold import VarianceThreshold + from .rfe import RFE from .rfe import RFECV @@ -26,6 +28,7 @@ 'SelectFwe', 'SelectKBest', 'SelectPercentile', + 'VarianceThreshold', 'chi2', 'f_classif', 'f_oneway', diff --git a/sklearn/feature_selection/base.py b/sklearn/feature_selection/base.py new file mode 100644 index 0000000000000..16f2d274ace62 --- /dev/null +++ b/sklearn/feature_selection/base.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +"""Generic feature selection mixin""" + +# Authors: G. Varoquaux, A. Gramfort, L. Buitinck, J. Nothman +# License: BSD 3 clause + +from abc import ABCMeta, abstractmethod +from warnings import warn + +import numpy as np +from scipy.sparse import issparse, csc_matrix + +from ..base import TransformerMixin +from ..utils import check_array, safe_mask +from ..externals import six + + +class SelectorMixin(six.with_metaclass(ABCMeta, TransformerMixin)): + """ + Tranformer mixin that performs feature selection given a support mask + + This mixin provides a feature selector implementation with `transform` and + `inverse_transform` functionality given an implementation of + `_get_support_mask`. + """ + + def get_support(self, indices=False): + """ + Get a mask, or integer index, of the features selected + + Parameters + ---------- + indices : boolean (default False) + If True, the return value will be an array of integers, rather + than a boolean mask. + + Returns + ------- + support : array + An index that selects the retained features from a feature vector. + If `indices` is False, this is a boolean array of shape + [# input features], in which an element is True iff its + corresponding feature is selected for retention. If `indices` is + True, this is an integer array of shape [# output features] whose + values are indices into the input feature vector. + """ + mask = self._get_support_mask() + return mask if not indices else np.where(mask)[0] + + @abstractmethod + def _get_support_mask(self): + """ + Get the boolean mask indicating which features are selected + + Returns + ------- + support : boolean array of shape [# input features] + An element is True iff its corresponding feature is selected for + retention. + """ + + def transform(self, X): + """Reduce X to the selected features. + + Parameters + ---------- + X : array of shape [n_samples, n_features] + The input samples. + + Returns + ------- + X_r : array of shape [n_samples, n_selected_features] + The input samples with only the selected features. + """ + X = check_array(X, accept_sparse='csr') + mask = self.get_support() + if not mask.any(): + warn("No features were selected: either the data is" + " too noisy or the selection test too strict.", + UserWarning) + return np.empty(0).reshape((X.shape[0], 0)) + if len(mask) != X.shape[1]: + raise ValueError("X has a different shape than during fitting.") + return check_array(X, accept_sparse='csr')[:, safe_mask(X, mask)] + + def inverse_transform(self, X): + """ + Reverse the transformation operation + + Parameters + ---------- + X : array of shape [n_samples, n_selected_features] + The input samples. + + Returns + ------- + X_r : array of shape [n_samples, n_original_features] + `X` with columns of zeros inserted where features would have + been removed by `transform`. + """ + if issparse(X): + X = X.tocsc() + # insert additional entries in indptr: + # e.g. if transform changed indptr from [0 2 6 7] to [0 2 3] + # col_nonzeros here will be [2 0 1] so indptr becomes [0 2 2 3] + col_nonzeros = self.inverse_transform(np.diff(X.indptr)).ravel() + indptr = np.concatenate([[0], np.cumsum(col_nonzeros)]) + Xt = csc_matrix((X.data, X.indices, indptr), + shape=(X.shape[0], len(indptr) - 1), dtype=X.dtype) + return Xt + + support = self.get_support() + X = check_array(X) + if support.sum() != X.shape[1]: + raise ValueError("X has a different shape than during fitting.") + + if X.ndim == 1: + X = X[None, :] + Xt = np.zeros((X.shape[0], support.size), dtype=X.dtype) + Xt[:, support] = X + return Xt diff --git a/sklearn/feature_selection/selector_mixin.py b/sklearn/feature_selection/from_model.py similarity index 70% rename from sklearn/feature_selection/selector_mixin.py rename to sklearn/feature_selection/from_model.py index 5dd7a74663345..9dc652d93e53b 100644 --- a/sklearn/feature_selection/selector_mixin.py +++ b/sklearn/feature_selection/from_model.py @@ -1,14 +1,18 @@ # Authors: Gilles Louppe, Mathieu Blondel -# License: BSD +# License: BSD 3 clause import numpy as np from ..base import TransformerMixin -from ..utils import safe_mask, atleast2d_or_csr +from ..externals import six +from ..utils import safe_mask, check_array +from ..utils.validation import NotFittedError, check_is_fitted -class SelectorMixin(TransformerMixin): - """"Transformer mixin selecting features based on importance weights. +class _LearntSelectorMixin(TransformerMixin): + # Note because of the extra threshold parameter in transform, this does + # not naturally extend from SelectorMixin + """Transformer mixin selecting features based on importance weights. This implementation can be mixin on any estimator that exposes a ``feature_importances_`` or ``coef_`` attribute to evaluate the relative @@ -17,6 +21,10 @@ class SelectorMixin(TransformerMixin): def transform(self, X, threshold=None): """Reduce X to its most important features. + Uses ``coef_`` or ``feature_importances_`` to determine the most + important features. For models with a ``coef_`` for each class, the + absolute sum over the classes is used. + Parameters ---------- X : array or scipy sparse matrix of shape [n_samples, n_features] @@ -36,28 +44,27 @@ def transform(self, X, threshold=None): X_r : array of shape [n_samples, n_selected_features] The input samples with only the selected features. """ - X = atleast2d_or_csr(X) + check_is_fitted(self, ('coef_', 'feature_importances_'), + all_or_any=any) + + X = check_array(X, 'csc') # Retrieve importance vector if hasattr(self, "feature_importances_"): importances = self.feature_importances_ - if importances is None: - raise ValueError("Importance weights not computed. Please " - "Set the compute_importances parameter before fit.") elif hasattr(self, "coef_"): + if self.coef_ is None: + msg = "This model is not fitted yet. Please call fit() first" + raise NotFittedError(msg) + if self.coef_.ndim == 1: importances = np.abs(self.coef_) - else: importances = np.sum(np.abs(self.coef_), axis=0) - else: - raise ValueError("Missing `feature_importances_` or `coef_`" - " attribute, did you forget to set the " - "estimator's parameter to compute it?") if len(importances) != X.shape[1]: raise ValueError("X has different number of features than" - " during model fitting.") + " during model fitting.") # Retrieve threshold if threshold is None: @@ -67,7 +74,7 @@ def transform(self, X, threshold=None): else: threshold = getattr(self, "threshold", "mean") - if isinstance(threshold, basestring): + if isinstance(threshold, six.string_types): if "*" in threshold: scale, reference = threshold.split("*") scale = float(scale.strip()) @@ -92,7 +99,12 @@ def transform(self, X, threshold=None): threshold = float(threshold) # Selection - mask = importances >= threshold + try: + mask = importances >= threshold + except TypeError: + # Fails in Python 3.x when threshold is str; + # result is array of True + raise ValueError("Invalid threshold: all features are discarded.") if np.any(mask): mask = safe_mask(X, mask) diff --git a/sklearn/feature_selection/rfe.py b/sklearn/feature_selection/rfe.py index 924b75ecbc51f..e1d6dd403968b 100644 --- a/sklearn/feature_selection/rfe.py +++ b/sklearn/feature_selection/rfe.py @@ -2,20 +2,24 @@ # Vincent Michel # Gilles Louppe # -# License: BSD Style. +# License: BSD 3 clause """Recursive feature elimination for feature ranking""" import numpy as np -from ..utils import check_arrays, safe_sqr, safe_mask +from ..utils import check_X_y, safe_sqr +from ..utils.metaestimators import if_delegate_has_method from ..base import BaseEstimator from ..base import MetaEstimatorMixin from ..base import clone from ..base import is_classifier -from ..cross_validation import check_cv +from ..cross_validation import _check_cv as check_cv +from ..cross_validation import _safe_split, _score +from ..metrics.scorer import check_scoring +from .base import SelectorMixin -class RFE(BaseEstimator, MetaEstimatorMixin): +class RFE(BaseEstimator, MetaEstimatorMixin, SelectorMixin): """Feature ranking with recursive feature elimination. Given an external estimator that assigns weights to features (e.g., the @@ -50,22 +54,26 @@ class RFE(BaseEstimator, MetaEstimatorMixin): estimator_params : dict Parameters for the external estimator. - Useful for doing grid searches. + Useful for doing grid searches when an `RFE` object is passed as an + argument to, e.g., a `sklearn.grid_search.GridSearchCV` object. + + verbose : int, default=0 + Controls verbosity of output. Attributes ---------- - `n_features_` : int + n_features_ : int The number of selected features. - `support_` : array of shape [n_features] + support_ : array of shape [n_features] The mask of selected features. - `ranking_` : array of shape [n_features] - The feature ranking, such that `ranking_[i]` corresponds to the \ - ranking position of the i-th feature. Selected (i.e., estimated \ + ranking_ : array of shape [n_features] + The feature ranking, such that ``ranking_[i]`` corresponds to the + ranking position of the i-th feature. Selected (i.e., estimated best) features are assigned rank 1. - `estimator_` : object + estimator_ : object The external estimator fit on the reduced dataset. Examples @@ -113,7 +121,7 @@ def fit(self, X, y): y : array-like, shape = [n_samples] The target values. """ - X, y = check_arrays(X, y, sparse_format="csr") + X, y = check_X_y(X, y, "csc") # Initialization n_features = X.shape[1] if self.n_features_to_select is None: @@ -122,7 +130,7 @@ def fit(self, X, y): n_features_to_select = self.n_features_to_select if 0.0 < self.step < 1.0: - step = int(self.step * n_features) + step = int(max(1, self.step * n_features)) else: step = int(self.step) if step <= 0: @@ -166,6 +174,7 @@ def fit(self, X, y): return self + @if_delegate_has_method(delegate='estimator') def predict(self, X): """Reduce X to the selected features and then predict using the underlying estimator. @@ -180,8 +189,9 @@ def predict(self, X): y : array of shape [n_samples] The predicted target values. """ - return self.estimator_.predict(X[:, safe_mask(X, self.support_)]) + return self.estimator_.predict(self.transform(X)) + @if_delegate_has_method(delegate='estimator') def score(self, X, y): """Reduce X to the selected features and then return the score of the underlying estimator. @@ -194,34 +204,27 @@ def score(self, X, y): y : array of shape [n_samples] The target values. """ - return self.estimator_.score(X[:, safe_mask(X, self.support_)], y) - - def transform(self, X): - """Reduce X to the selected features during the elimination. - - Parameters - ---------- - X : array of shape [n_samples, n_features] - The input samples. + return self.estimator_.score(self.transform(X), y) - Returns - ------- - X_r : array of shape [n_samples, n_selected_features] - The input samples with only the features selected during the \ - elimination. - """ - return X[:, safe_mask(X, self.support_)] + def _get_support_mask(self): + return self.support_ + @if_delegate_has_method(delegate='estimator') def decision_function(self, X): return self.estimator_.decision_function(self.transform(X)) + @if_delegate_has_method(delegate='estimator') def predict_proba(self, X): return self.estimator_.predict_proba(self.transform(X)) + @if_delegate_has_method(delegate='estimator') + def predict_log_proba(self, X): + return self.estimator_.predict_log_proba(self.transform(X)) + class RFECV(RFE, MetaEstimatorMixin): """Feature ranking with recursive feature elimination and cross-validated - selection of the best number of features. + selection of the best number of features. Parameters ---------- @@ -246,39 +249,47 @@ class RFECV(RFE, MetaEstimatorMixin): Specific cross-validation objects can also be passed, see `sklearn.cross_validation module` for details. - loss_function : function, optional (default=None) - The loss function to minimize by cross-validation. If None, then the - score function of the estimator is maximized. + scoring : string, callable or None, optional, default: None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. estimator_params : dict Parameters for the external estimator. - Useful for doing grid searches. + Useful for doing grid searches when an `RFE` object is passed as an + argument to, e.g., a `sklearn.grid_search.GridSearchCV` object. verbose : int, default=0 Controls verbosity of output. Attributes ---------- - `n_features_` : int + n_features_ : int The number of selected features with cross-validation. - `support_` : array of shape [n_features] + + support_ : array of shape [n_features] The mask of selected features. - `ranking_` : array of shape [n_features] + ranking_ : array of shape [n_features] The feature ranking, such that `ranking_[i]` corresponds to the ranking position of the i-th feature. Selected (i.e., estimated best) features are assigned rank 1. - `cv_scores_` : array of shape [n_subsets_of_features] + grid_scores_ : array of shape [n_subsets_of_features] The cross-validation scores such that - `cv_scores_[i]` corresponds to + ``grid_scores_[i]`` corresponds to the CV score of the i-th subset of features. - `estimator_` : object + estimator_ : object The external estimator fit on the reduced dataset. + Notes + ----- + The size of ``grid_scores_`` is equal to (n_features + step - 2) // step + 1, + where step is the number of features removed at each iteration. + Examples -------- The following example shows how to retrieve the a-priori not known 5 @@ -304,12 +315,12 @@ class RFECV(RFE, MetaEstimatorMixin): for cancer classification using support vector machines", Mach. Learn., 46(1-3), 389--422, 2002. """ - def __init__(self, estimator, step=1, cv=None, loss_func=None, - estimator_params={}, verbose=0): + def __init__(self, estimator, step=1, cv=None, scoring=None, + estimator_params={}, verbose=0): self.estimator = estimator self.step = step self.cv = cv - self.loss_func = loss_func + self.scoring = scoring self.estimator_params = estimator_params self.verbose = verbose @@ -327,72 +338,62 @@ def fit(self, X, y): Target values (integers for classification, real numbers for regression). """ - X, y = check_arrays(X, y, sparse_format="csr") + X, y = check_X_y(X, y, "csr") # Initialization rfe = RFE(estimator=self.estimator, n_features_to_select=1, - step=self.step, estimator_params=self.estimator_params, - verbose=self.verbose - 1) + step=self.step, estimator_params=self.estimator_params, + verbose=self.verbose - 1) cv = check_cv(self.cv, X, y, is_classifier(self.estimator)) - scores = {} + scorer = check_scoring(self.estimator, scoring=self.scoring) + scores = np.zeros(X.shape[1]) + n_features_to_select_by_rank = np.zeros(X.shape[1]) # Cross-validation - n = 0 + for n, (train, test) in enumerate(cv): + X_train, y_train = _safe_split(self.estimator, X, y, train) + X_test, y_test = _safe_split(self.estimator, X, y, test, train) - for train, test in cv: # Compute a full ranking of the features - ranking_ = rfe.fit(X[train], y[train]).ranking_ + # ranking_ contains the same set of values for all CV folds, + # but perhaps reordered + ranking_ = rfe.fit(X_train, y_train).ranking_ # Score each subset of features - for k in xrange(1, max(ranking_) + 1): - mask = np.where(ranking_ <= k)[0] + for k in range(0, np.max(ranking_)): + indices = np.where(ranking_ <= k + 1)[0] estimator = clone(self.estimator) - estimator.fit(X[train][:, mask], y[train]) - - if self.loss_func is None: - score_k = 1.0 - estimator.score( - X[test][:, mask], - y[test]) - else: - score_k = self.loss_func( - y[test], - estimator.predict(X[test][:, mask])) - - if not k in scores: - scores[k] = 0.0 + estimator.fit(X_train[:, indices], y_train) + score = _score(estimator, X_test[:, indices], y_test, scorer) if self.verbose > 0: - print("Finished fold with %d / %d feature ranks, loss=%f" - % (k, max(ranking_), score_k)) - scores[k] += score_k - - n += 1 - - # Pick the best number of features on average - best_score = np.inf - best_k = None - - for k, score in sorted(scores.iteritems()): - if score < best_score: - best_score = score - best_k = k + print("Finished fold with %d / %d feature ranks, score=%f" + % (k + 1, np.max(ranking_), score)) + scores[k] += score + # n_features_to_select_by_rank[k] is being overwritten + # multiple times, but by the same value + n_features_to_select_by_rank[k] = indices.size + + # Select the best upper bound for feature rank. It's OK to use the + # last ranking_, as np.max(ranking_) is the same over all CV folds. + scores = scores[:np.max(ranking_)] + k = np.argmax(scores) # Re-execute an elimination with best_k over the whole set rfe = RFE(estimator=self.estimator, - n_features_to_select=best_k, + n_features_to_select=n_features_to_select_by_rank[k], step=self.step, estimator_params=self.estimator_params) rfe.fit(X, y) # Set final attributes - self.estimator_ = clone(self.estimator) - self.estimator_.set_params(**self.estimator_params) - self.estimator_.fit(X[:, safe_mask(X, rfe.support_)], y) - self.n_features_ = rfe.n_features_ self.support_ = rfe.support_ + self.n_features_ = rfe.n_features_ self.ranking_ = rfe.ranking_ + self.estimator_ = clone(self.estimator) + self.estimator_.set_params(**self.estimator_params) + self.estimator_.fit(self.transform(X), y) - self.cv_scores_ = [0] * len(scores) - for k, score in scores.iteritems(): - self.cv_scores_[k - 1] = score / n - + # Fixing a normalization error, n is equal to len(cv) - 1 + # here, the scores are normalized by len(cv) + self.grid_scores_ = scores / len(cv) return self diff --git a/sklearn/feature_selection/tests/test_base.py b/sklearn/feature_selection/tests/test_base.py new file mode 100644 index 0000000000000..fe17fa0f75326 --- /dev/null +++ b/sklearn/feature_selection/tests/test_base.py @@ -0,0 +1,115 @@ +import numpy as np +from scipy import sparse as sp + +from nose.tools import assert_raises, assert_equal +from numpy.testing import assert_array_equal + +from sklearn.base import BaseEstimator +from sklearn.feature_selection.base import SelectorMixin +from sklearn.utils import check_array + + +class StepSelector(SelectorMixin, BaseEstimator): + """Retain every `step` features (beginning with 0)""" + def __init__(self, step=2): + self.step = step + + def fit(self, X, y=None): + X = check_array(X, 'csc') + self.n_input_feats = X.shape[1] + return self + + def _get_support_mask(self): + mask = np.zeros(self.n_input_feats, dtype=bool) + mask[::self.step] = True + return mask + + +support = [True, False] * 5 +support_inds = [0, 2, 4, 6, 8] +X = np.arange(20).reshape(2, 10) +Xt = np.arange(0, 20, 2).reshape(2, 5) +Xinv = X.copy() +Xinv[:, 1::2] = 0 +y = [0, 1] +feature_names = list('ABCDEFGHIJ') +feature_names_t = feature_names[::2] +feature_names_inv = np.array(feature_names) +feature_names_inv[1::2] = '' + + +def test_transform_dense(): + sel = StepSelector() + Xt_actual = sel.fit(X, y).transform(X) + Xt_actual2 = StepSelector().fit_transform(X, y) + assert_array_equal(Xt, Xt_actual) + assert_array_equal(Xt, Xt_actual2) + + # Check dtype matches + assert_equal(np.int32, sel.transform(X.astype(np.int32)).dtype) + assert_equal(np.float32, sel.transform(X.astype(np.float32)).dtype) + + # Check 1d list and other dtype: + names_t_actual = sel.transform(feature_names) + assert_array_equal(feature_names_t, names_t_actual.ravel()) + + # Check wrong shape raises error + assert_raises(ValueError, sel.transform, np.array([[1], [2]])) + + +def test_transform_sparse(): + sparse = sp.csc_matrix + sel = StepSelector() + Xt_actual = sel.fit(sparse(X)).transform(sparse(X)) + Xt_actual2 = sel.fit_transform(sparse(X)) + assert_array_equal(Xt, Xt_actual.toarray()) + assert_array_equal(Xt, Xt_actual2.toarray()) + + # Check dtype matches + assert_equal(np.int32, sel.transform(sparse(X).astype(np.int32)).dtype) + assert_equal(np.float32, sel.transform(sparse(X).astype(np.float32)).dtype) + + # Check wrong shape raises error + assert_raises(ValueError, sel.transform, np.array([[1], [2]])) + + +def test_inverse_transform_dense(): + sel = StepSelector() + Xinv_actual = sel.fit(X, y).inverse_transform(Xt) + assert_array_equal(Xinv, Xinv_actual) + + # Check dtype matches + assert_equal(np.int32, + sel.inverse_transform(Xt.astype(np.int32)).dtype) + assert_equal(np.float32, + sel.inverse_transform(Xt.astype(np.float32)).dtype) + + # Check 1d list and other dtype: + names_inv_actual = sel.inverse_transform(feature_names_t) + assert_array_equal(feature_names_inv, names_inv_actual.ravel()) + + # Check wrong shape raises error + assert_raises(ValueError, sel.inverse_transform, np.array([[1], [2]])) + + +def test_inverse_transform_sparse(): + sparse = sp.csc_matrix + sel = StepSelector() + Xinv_actual = sel.fit(sparse(X)).inverse_transform(sparse(Xt)) + assert_array_equal(Xinv, Xinv_actual.toarray()) + + # Check dtype matches + assert_equal(np.int32, + sel.inverse_transform(sparse(Xt).astype(np.int32)).dtype) + assert_equal(np.float32, + sel.inverse_transform(sparse(Xt).astype(np.float32)).dtype) + + # Check wrong shape raises error + assert_raises(ValueError, sel.inverse_transform, np.array([[1], [2]])) + + +def test_get_support(): + sel = StepSelector() + sel.fit(X, y) + assert_array_equal(support, sel.get_support()) + assert_array_equal(support_inds, sel.get_support(indices=True)) diff --git a/sklearn/feature_selection/tests/test_chi2.py b/sklearn/feature_selection/tests/test_chi2.py index 1fa66e7fdd2c7..06ffdff629a50 100644 --- a/sklearn/feature_selection/tests/test_chi2.py +++ b/sklearn/feature_selection/tests/test_chi2.py @@ -4,10 +4,14 @@ """ import numpy as np -from numpy.testing import assert_equal from scipy.sparse import coo_matrix, csr_matrix +import scipy.stats -from .. import SelectKBest, chi2 +from sklearn.feature_selection import SelectKBest, chi2 +from sklearn.feature_selection.univariate_selection import _chisquare + +from nose.tools import assert_raises +from numpy.testing import assert_equal, assert_array_almost_equal # Feature 0 is highly informative for class 1; # feature 1 is the same everywhere; @@ -55,3 +59,24 @@ def test_chi2_coo(): Xcoo = coo_matrix(X) mkchi2(k=2).fit_transform(Xcoo, y) # if we got here without an exception, we're safe + + +def test_chi2_negative(): + """Check for proper error on negative numbers in the input X.""" + X, y = [[0, 1], [-1e-20, 1]], [0, 1] + for X in (X, np.array(X), csr_matrix(X)): + assert_raises(ValueError, chi2, X, y) + + +def test_chisquare(): + """Test replacement for scipy.stats.chisquare against the original.""" + obs = np.array([[2., 2.], + [1., 1.]]) + exp = np.array([[1.5, 1.5], + [1.5, 1.5]]) + # call SciPy first because our version overwrites obs + chi_scp, p_scp = scipy.stats.chisquare(obs, exp) + chi_our, p_our = _chisquare(obs, exp) + + assert_array_almost_equal(chi_scp, chi_our) + assert_array_almost_equal(p_scp, p_our) diff --git a/sklearn/feature_selection/tests/test_feature_select.py b/sklearn/feature_selection/tests/test_feature_select.py index 7c66cbe5b3082..4b91b0b311b03 100644 --- a/sklearn/feature_selection/tests/test_feature_select.py +++ b/sklearn/feature_selection/tests/test_feature_select.py @@ -1,14 +1,27 @@ """ Todo: cross-check the F-value with stats model """ - -import numpy as np +from __future__ import division +import itertools import warnings - -from nose.tools import assert_equal, assert_raises, assert_true -from numpy.testing import assert_array_equal, assert_array_almost_equal +import numpy as np from scipy import stats, sparse +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_not_in +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import ignore_warnings +from sklearn.utils.testing import assert_warns_message +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_greater_equal +from sklearn.utils import safe_mask + from sklearn.datasets.samples_generator import (make_classification, make_regression) from sklearn.feature_selection import (chi2, f_classif, f_oneway, f_regression, @@ -34,7 +47,15 @@ def test_f_oneway_vs_scipy_stats(): def test_f_oneway_ints(): # Smoke test f_oneway on integers: that it does raise casting errors # with recent numpys - f_oneway(np.random.randint(10, size=(10, 10)), np.arange(10)) + rng = np.random.RandomState(0) + X = rng.randint(10, size=(10, 10)) + y = np.arange(10) + fint, pint = f_oneway(X, y) + + # test that is gives the same result as with float + f, p = f_oneway(X.astype(np.float), y) + assert_array_almost_equal(f, fint, decimal=4) + assert_array_almost_equal(p, pint, decimal=4) def test_f_classif(): @@ -49,12 +70,12 @@ def test_f_classif(): class_sep=10, shuffle=False, random_state=0) F, pv = f_classif(X, y) - F_sparse, pv_sparse = f_classif(sparse.csr_matrix(X), y) - assert(F > 0).all() - assert(pv > 0).all() - assert(pv < 1).all() - assert(pv[:5] < 0.05).all() - assert(pv[5:] > 1.e-4).all() + F_sparse, pv_sparse = f_classif(sparse.csr_matrix(X), y) + assert_true((F > 0).all()) + assert_true((pv > 0).all()) + assert_true((pv < 1).all()) + assert_true((pv[:5] < 0.05).all()) + assert_true((pv[5:] > 1.e-4).all()) assert_array_almost_equal(F_sparse, F) assert_array_almost_equal(pv_sparse, pv) @@ -64,15 +85,15 @@ def test_f_regression(): Test whether the F test yields meaningful results on a simple simulated regression problem """ - X, y = make_regression(n_samples=200, n_features=20, - n_informative=5, shuffle=False, random_state=0) + X, y = make_regression(n_samples=200, n_features=20, n_informative=5, + shuffle=False, random_state=0) F, pv = f_regression(X, y) - assert(F > 0).all() - assert(pv > 0).all() - assert(pv < 1).all() - assert(pv[:5] < 0.05).all() - assert(pv[5:] > 1.e-4).all() + assert_true((F > 0).all()) + assert_true((pv > 0).all()) + assert_true((pv < 1).all()) + assert_true((pv[:5] < 0.05).all()) + assert_true((pv[5:] > 1.e-4).all()) # again without centering, compare with sparse F, pv = f_regression(X, y, center=False) @@ -96,6 +117,25 @@ def test_f_regression_input_dtype(): assert_array_almost_equal(pv1, pv2, 5) +def test_f_regression_center(): + """Test whether f_regression preserves dof according to 'center' argument + + We use two centered variates so we have a simple relationship between + F-score with variates centering and F-score without variates centering. + """ + # Create toy example + X = np.arange(-5, 6).reshape(-1, 1) # X has zero mean + n_samples = X.size + Y = np.ones(n_samples) + Y[::2] *= -1. + Y[0] = 0. # have Y mean being null + + F1, _ = f_regression(X, Y, center=True) + F2, _ = f_regression(X, Y, center=False) + assert_array_almost_equal(F1 * (n_samples - 1.) / (n_samples - 2.), F2) + assert_almost_equal(F2[0], 0.232558139) # value from statsmodels OLS + + def test_f_classif_multi_class(): """ Test whether the F test yields meaningful results @@ -108,11 +148,11 @@ def test_f_classif_multi_class(): class_sep=10, shuffle=False, random_state=0) F, pv = f_classif(X, y) - assert(F > 0).all() - assert(pv > 0).all() - assert(pv < 1).all() - assert(pv[:5] < 0.05).all() - assert(pv[5:] > 1.e-5).all() + assert_true((F > 0).all()) + assert_true((pv > 0).all()) + assert_true((pv < 1).all()) + assert_true((pv[:5] < 0.05).all()) + assert_true((pv[5:] > 1.e-4).all()) def test_select_percentile_classif(): @@ -130,7 +170,7 @@ def test_select_percentile_classif(): univariate_filter = SelectPercentile(f_classif, percentile=25) X_r = univariate_filter.fit(X, y).transform(X) X_r2 = GenericUnivariateSelect(f_classif, mode='percentile', - param=25).fit(X, y).transform(X) + param=25).fit(X, y).transform(X) assert_array_equal(X_r, X_r2) support = univariate_filter.get_support() gtruth = np.zeros(20) @@ -153,13 +193,21 @@ def test_select_percentile_classif_sparse(): univariate_filter = SelectPercentile(f_classif, percentile=25) X_r = univariate_filter.fit(X, y).transform(X) X_r2 = GenericUnivariateSelect(f_classif, mode='percentile', - param=25).fit(X, y).transform(X) + param=25).fit(X, y).transform(X) assert_array_equal(X_r.toarray(), X_r2.toarray()) support = univariate_filter.get_support() gtruth = np.zeros(20) gtruth[:5] = 1 assert_array_equal(support, gtruth) + X_r2inv = univariate_filter.inverse_transform(X_r2) + assert_true(sparse.issparse(X_r2inv)) + support_mask = safe_mask(X_r2inv, support) + assert_equal(X_r2inv.shape, X.shape) + assert_array_equal(X_r2inv[:, support_mask].toarray(), X_r.toarray()) + # Check other columns are empty + assert_equal(X_r2inv.getnnz(), X_r.getnnz()) + ############################################################################## # Test univariate selection in classification settings @@ -178,8 +226,8 @@ def test_select_kbest_classif(): univariate_filter = SelectKBest(f_classif, k=5) X_r = univariate_filter.fit(X, y).transform(X) - X_r2 = GenericUnivariateSelect(f_classif, mode='k_best', - param=5).fit(X, y).transform(X) + X_r2 = GenericUnivariateSelect( + f_classif, mode='k_best', param=5).fit(X, y).transform(X) assert_array_equal(X_r, X_r2) support = univariate_filter.get_support() gtruth = np.zeros(20) @@ -187,57 +235,40 @@ def test_select_kbest_classif(): assert_array_equal(support, gtruth) -def test_select_fpr_classif(): +def test_select_kbest_all(): """ - Test whether the relative univariate feature selection - gets the correct items in a simple classification problem - with the fpr heuristic + Test whether k="all" correctly returns all features. """ - X, y = make_classification(n_samples=200, n_features=20, - n_informative=3, n_redundant=2, - n_repeated=0, n_classes=8, - n_clusters_per_class=1, flip_y=0.0, - class_sep=10, shuffle=False, random_state=0) + X, y = make_classification(n_samples=20, n_features=10, + shuffle=False, random_state=0) - univariate_filter = SelectFpr(f_classif, alpha=0.0001) + univariate_filter = SelectKBest(f_classif, k='all') X_r = univariate_filter.fit(X, y).transform(X) - X_r2 = GenericUnivariateSelect(f_classif, mode='fpr', - param=0.0001).fit(X, y).transform(X) - assert_array_equal(X_r, X_r2) - support = univariate_filter.get_support() - gtruth = np.zeros(20) - gtruth[:5] = 1 - assert_array_equal(support, gtruth) + assert_array_equal(X, X_r) -def test_select_fdr_classif(): +def test_select_kbest_zero(): """ - Test whether the relative univariate feature selection - gets the correct items in a simple classification problem - with the fpr heuristic + Test whether k=0 correctly returns no features. """ - X, y = make_classification(n_samples=200, n_features=20, - n_informative=3, n_redundant=2, - n_repeated=0, n_classes=8, - n_clusters_per_class=1, flip_y=0.0, - class_sep=10, shuffle=False, random_state=0) + X, y = make_classification(n_samples=20, n_features=10, + shuffle=False, random_state=0) - univariate_filter = SelectFdr(f_classif, alpha=0.0001) - X_r = univariate_filter.fit(X, y).transform(X) - X_r2 = GenericUnivariateSelect(f_classif, mode='fdr', - param=0.0001).fit(X, y).transform(X) - assert_array_equal(X_r, X_r2) + univariate_filter = SelectKBest(f_classif, k=0) + univariate_filter.fit(X, y) support = univariate_filter.get_support() - gtruth = np.zeros(20) - gtruth[:5] = 1 + gtruth = np.zeros(10, dtype=bool) assert_array_equal(support, gtruth) + X_selected = assert_warns_message(UserWarning, 'No features were selected', + univariate_filter.transform, X) + assert_equal(X_selected.shape, (20, 0)) -def test_select_fwe_classif(): +def test_select_heuristics_classif(): """ Test whether the relative univariate feature selection gets the correct items in a simple classification problem - with the fpr heuristic + with the fdr, fwe and fpr heuristics """ X, y = make_classification(n_samples=200, n_features=20, n_informative=3, n_redundant=2, @@ -247,18 +278,27 @@ def test_select_fwe_classif(): univariate_filter = SelectFwe(f_classif, alpha=0.01) X_r = univariate_filter.fit(X, y).transform(X) - X_r2 = GenericUnivariateSelect(f_classif, mode='fwe', - param=0.01).fit(X, y).transform(X) - assert_array_equal(X_r, X_r2) - support = univariate_filter.get_support() gtruth = np.zeros(20) gtruth[:5] = 1 - assert(np.sum(np.abs(support - gtruth)) < 2) + for mode in ['fdr', 'fpr', 'fwe']: + X_r2 = GenericUnivariateSelect( + f_classif, mode=mode, param=0.01).fit(X, y).transform(X) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + assert_array_almost_equal(support, gtruth) ############################################################################## # Test univariate selection in regression settings + +def assert_best_scores_kept(score_filter): + scores = score_filter.scores_ + support = score_filter.get_support() + assert_array_equal(np.sort(scores[support]), + np.sort(scores)[-support.sum():]) + + def test_select_percentile_regression(): """ Test whether the relative univariate feature selection @@ -270,8 +310,9 @@ def test_select_percentile_regression(): univariate_filter = SelectPercentile(f_regression, percentile=25) X_r = univariate_filter.fit(X, y).transform(X) - X_r2 = GenericUnivariateSelect(f_regression, mode='percentile', - param=25).fit(X, y).transform(X) + assert_best_scores_kept(univariate_filter) + X_r2 = GenericUnivariateSelect( + f_regression, mode='percentile', param=25).fit(X, y).transform(X) assert_array_equal(X_r, X_r2) support = univariate_filter.get_support() gtruth = np.zeros(20) @@ -280,6 +321,9 @@ def test_select_percentile_regression(): X_2 = X.copy() X_2[:, np.logical_not(support)] = 0 assert_array_equal(X_2, univariate_filter.inverse_transform(X_r)) + # Check inverse_transform respects dtype + assert_array_equal(X_2.astype(bool), + univariate_filter.inverse_transform(X_r.astype(bool))) def test_select_percentile_regression_full(): @@ -292,8 +336,9 @@ def test_select_percentile_regression_full(): univariate_filter = SelectPercentile(f_regression, percentile=100) X_r = univariate_filter.fit(X, y).transform(X) - X_r2 = GenericUnivariateSelect(f_regression, mode='percentile', - param=100).fit(X, y).transform(X) + assert_best_scores_kept(univariate_filter) + X_r2 = GenericUnivariateSelect( + f_regression, mode='percentile', param=100).fit(X, y).transform(X) assert_array_equal(X_r, X_r2) support = univariate_filter.get_support() gtruth = np.ones(20) @@ -301,7 +346,15 @@ def test_select_percentile_regression_full(): def test_invalid_percentile(): - assert_raises(ValueError, SelectPercentile, percentile=101) + X, y = make_regression(n_samples=10, n_features=20, + n_informative=2, shuffle=False, random_state=0) + + assert_raises(ValueError, SelectPercentile(percentile=-1).fit, X, y) + assert_raises(ValueError, SelectPercentile(percentile=101).fit, X, y) + assert_raises(ValueError, GenericUnivariateSelect(mode='percentile', + param=-1).fit, X, y) + assert_raises(ValueError, GenericUnivariateSelect(mode='percentile', + param=101).fit, X, y) def test_select_kbest_regression(): @@ -310,13 +363,14 @@ def test_select_kbest_regression(): gets the correct items in a simple regression problem with the k best heuristic """ - X, y = make_regression(n_samples=200, n_features=20, - n_informative=5, shuffle=False, random_state=0) + X, y = make_regression(n_samples=200, n_features=20, n_informative=5, + shuffle=False, random_state=0, noise=10) univariate_filter = SelectKBest(f_regression, k=5) X_r = univariate_filter.fit(X, y).transform(X) - X_r2 = GenericUnivariateSelect(f_regression, mode='k_best', - param=5).fit(X, y).transform(X) + assert_best_scores_kept(univariate_filter) + X_r2 = GenericUnivariateSelect( + f_regression, mode='k_best', param=5).fit(X, y).transform(X) assert_array_equal(X_r, X_r2) support = univariate_filter.get_support() gtruth = np.zeros(20) @@ -324,45 +378,70 @@ def test_select_kbest_regression(): assert_array_equal(support, gtruth) -def test_select_fpr_regression(): +def test_select_heuristics_regression(): """ Test whether the relative univariate feature selection gets the correct items in a simple regression problem - with the fpr heuristic + with the fpr, fdr or fwe heuristics """ - X, y = make_regression(n_samples=200, n_features=20, - n_informative=5, shuffle=False, random_state=0) + X, y = make_regression(n_samples=200, n_features=20, n_informative=5, + shuffle=False, random_state=0, noise=10) univariate_filter = SelectFpr(f_regression, alpha=0.01) X_r = univariate_filter.fit(X, y).transform(X) - X_r2 = GenericUnivariateSelect(f_regression, mode='fpr', - param=0.01).fit(X, y).transform(X) - assert_array_equal(X_r, X_r2) - support = univariate_filter.get_support() gtruth = np.zeros(20) gtruth[:5] = 1 - assert(support[:5] == 1).all() - assert(np.sum(support[5:] == 1) < 3) + for mode in ['fdr', 'fpr', 'fwe']: + X_r2 = GenericUnivariateSelect( + f_regression, mode=mode, param=0.01).fit(X, y).transform(X) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + assert_array_equal(support[:5], np.ones((5, ), dtype=np.bool)) + assert_less(np.sum(support[5:] == 1), 3) def test_select_fdr_regression(): """ - Test whether the relative univariate feature selection - gets the correct items in a simple regression problem - with the fdr heuristic - """ - X, y = make_regression(n_samples=200, n_features=20, - n_informative=5, shuffle=False, random_state=0) - - univariate_filter = SelectFdr(f_regression, alpha=0.01) - X_r = univariate_filter.fit(X, y).transform(X) - X_r2 = GenericUnivariateSelect(f_regression, mode='fdr', - param=0.01).fit(X, y).transform(X) - assert_array_equal(X_r, X_r2) - support = univariate_filter.get_support() - gtruth = np.zeros(20) - gtruth[:5] = 1 - assert_array_equal(support, gtruth) + Test that fdr heuristic actually has low FDR. + """ + def single_fdr(alpha, n_informative, random_state): + X, y = make_regression(n_samples=150, n_features=20, + n_informative=n_informative, shuffle=False, + random_state=random_state, noise=10) + + with warnings.catch_warnings(record=True): + # Warnings can be raised when no features are selected + # (low alpha or very noisy data) + univariate_filter = SelectFdr(f_regression, alpha=alpha) + X_r = univariate_filter.fit(X, y).transform(X) + X_r2 = GenericUnivariateSelect( + f_regression, mode='fdr', param=alpha).fit(X, y).transform(X) + + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + num_false_positives = np.sum(support[n_informative:] == 1) + num_true_positives = np.sum(support[:n_informative] == 1) + + if num_false_positives == 0: + return 0. + false_discovery_rate = (num_false_positives / + (num_true_positives + num_false_positives)) + return false_discovery_rate + + for alpha in [0.001, 0.01, 0.1]: + for n_informative in [1, 5, 10]: + # As per Benjamini-Hochberg, the expected false discovery rate + # should be lower than alpha: + # FDR = E(FP / (TP + FP)) <= alpha + false_discovery_rate = np.mean([single_fdr(alpha, n_informative, + random_state) for + random_state in range(30)]) + assert_greater_equal(alpha, false_discovery_rate) + + # Make sure that the empirical false discovery rate increases + # with alpha: + if false_discovery_rate != 0: + assert_greater(false_discovery_rate, alpha / 10) def test_select_fwe_regression(): @@ -376,14 +455,14 @@ def test_select_fwe_regression(): univariate_filter = SelectFwe(f_regression, alpha=0.01) X_r = univariate_filter.fit(X, y).transform(X) - X_r2 = GenericUnivariateSelect(f_regression, mode='fwe', - param=0.01).fit(X, y).transform(X) + X_r2 = GenericUnivariateSelect( + f_regression, mode='fwe', param=0.01).fit(X, y).transform(X) assert_array_equal(X_r, X_r2) support = univariate_filter.get_support() gtruth = np.zeros(20) gtruth[:5] = 1 - assert(support[:5] == 1).all() - assert(np.sum(support[5:] == 1) < 2) + assert_array_equal(support[:5], np.ones((5, ), dtype=np.bool)) + assert_less(np.sum(support[5:] == 1), 2) def test_selectkbest_tiebreaking(): @@ -391,25 +470,126 @@ def test_selectkbest_tiebreaking(): Prior to 0.11, SelectKBest would return more features than requested. """ - X = [[1, 0, 0], [0, 1, 1]] - y = [0, 1] - with warnings.catch_warnings(record=True): - X1 = SelectKBest(chi2, k=1).fit_transform(X, y) + Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]] + y = [1] + dummy_score = lambda X, y: (X[0], X[0]) + for X in Xs: + sel = SelectKBest(dummy_score, k=1) + X1 = ignore_warnings(sel.fit_transform)([X], y) assert_equal(X1.shape[1], 1) + assert_best_scores_kept(sel) - X2 = SelectKBest(chi2, k=2).fit_transform(X, y) + sel = SelectKBest(dummy_score, k=2) + X2 = ignore_warnings(sel.fit_transform)([X], y) assert_equal(X2.shape[1], 2) + assert_best_scores_kept(sel) def test_selectpercentile_tiebreaking(): - """Test if SelectPercentile actually selects k features in case of ties. - """ - X = [[1, 0, 0], [0, 1, 1]] - y = [0, 1] - - with warnings.catch_warnings(record=True): - X1 = SelectPercentile(chi2, percentile=34).fit_transform(X, y) + """Test if SelectPercentile selects the right n_features in case of ties. + """ + Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]] + y = [1] + dummy_score = lambda X, y: (X[0], X[0]) + for X in Xs: + sel = SelectPercentile(dummy_score, percentile=34) + X1 = ignore_warnings(sel.fit_transform)([X], y) assert_equal(X1.shape[1], 1) + assert_best_scores_kept(sel) - X2 = SelectPercentile(chi2, percentile=67).fit_transform(X, y) + sel = SelectPercentile(dummy_score, percentile=67) + X2 = ignore_warnings(sel.fit_transform)([X], y) assert_equal(X2.shape[1], 2) + assert_best_scores_kept(sel) + + +def test_tied_pvalues(): + """Test whether k-best and percentiles work with tied pvalues from chi2.""" + # chi2 will return the same p-values for the following features, but it + # will return different scores. + X0 = np.array([[10000, 9999, 9998], [1, 1, 1]]) + y = [0, 1] + + for perm in itertools.permutations((0, 1, 2)): + X = X0[:, perm] + Xt = SelectKBest(chi2, k=2).fit_transform(X, y) + assert_equal(Xt.shape, (2, 2)) + assert_not_in(9998, Xt) + + Xt = SelectPercentile(chi2, percentile=67).fit_transform(X, y) + assert_equal(Xt.shape, (2, 2)) + assert_not_in(9998, Xt) + + +def test_tied_scores(): + """Test for stable sorting in k-best with tied scores.""" + X_train = np.array([[0, 0, 0], [1, 1, 1]]) + y_train = [0, 1] + + for n_features in [1, 2, 3]: + sel = SelectKBest(chi2, k=n_features).fit(X_train, y_train) + X_test = sel.transform([0, 1, 2]) + assert_array_equal(X_test[0], np.arange(3)[-n_features:]) + + +def test_nans(): + """Assert that SelectKBest and SelectPercentile can handle NaNs.""" + # First feature has zero variance to confuse f_classif (ANOVA) and + # make it return a NaN. + X = [[0, 1, 0], [0, -1, -1], [0, .5, .5]] + y = [1, 0, 1] + + for select in (SelectKBest(f_classif, 2), + SelectPercentile(f_classif, percentile=67)): + ignore_warnings(select.fit)(X, y) + assert_array_equal(select.get_support(indices=True), np.array([1, 2])) + + +def test_score_func_error(): + X = [[0, 1, 0], [0, -1, -1], [0, .5, .5]] + y = [1, 0, 1] + + for SelectFeatures in [SelectKBest, SelectPercentile, SelectFwe, + SelectFdr, SelectFpr, GenericUnivariateSelect]: + assert_raises(TypeError, SelectFeatures(score_func=10).fit, X, y) + + +def test_invalid_k(): + X = [[0, 1, 0], [0, -1, -1], [0, .5, .5]] + y = [1, 0, 1] + + assert_raises(ValueError, SelectKBest(k=-1).fit, X, y) + assert_raises(ValueError, SelectKBest(k=4).fit, X, y) + assert_raises(ValueError, + GenericUnivariateSelect(mode='k_best', param=-1).fit, X, y) + assert_raises(ValueError, + GenericUnivariateSelect(mode='k_best', param=4).fit, X, y) + + +def test_f_classif_constant_feature(): + """Test that f_classif warns if a feature is constant throughout.""" + + X, y = make_classification(n_samples=10, n_features=5) + X[:, 0] = 2.0 + assert_warns(UserWarning, f_classif, X, y) + + +def test_no_feature_selected(): + rng = np.random.RandomState(0) + + # Generate random uncorrelated data: a strict univariate test should + # rejects all the features + X = rng.rand(40, 10) + y = rng.randint(0, 4, size=40) + strict_selectors = [ + SelectFwe(alpha=0.01).fit(X, y), + SelectFdr(alpha=0.01).fit(X, y), + SelectFpr(alpha=0.01).fit(X, y), + SelectPercentile(percentile=0).fit(X, y), + SelectKBest(k=0).fit(X, y), + ] + for selector in strict_selectors: + assert_array_equal(selector.get_support(), np.zeros(10)) + X_selected = assert_warns_message( + UserWarning, 'No features were selected', selector.transform, X) + assert_equal(X_selected.shape, (40, 0)) diff --git a/sklearn/feature_selection/tests/test_selector_mixin.py b/sklearn/feature_selection/tests/test_from_model.py similarity index 80% rename from sklearn/feature_selection/tests/test_selector_mixin.py rename to sklearn/feature_selection/tests/test_from_model.py index 62d7127e4b18e..8367ac65c56d3 100644 --- a/sklearn/feature_selection/tests/test_selector_mixin.py +++ b/sklearn/feature_selection/tests/test_from_model.py @@ -4,6 +4,7 @@ from nose.tools import assert_raises, assert_true from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_greater from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression @@ -16,7 +17,8 @@ def test_transform_linear_model(): for clf in (LogisticRegression(C=0.1), LinearSVC(C=0.01, dual=False), - SGDClassifier(alpha=0.1, n_iter=10, shuffle=True, seed=0)): + SGDClassifier(alpha=0.001, n_iter=50, shuffle=True, + random_state=0)): for thresh in (None, ".09*mean", "1e-5 * median"): for func in (np.array, sp.csr_matrix): X = func(iris.data) @@ -30,11 +32,11 @@ def test_transform_linear_model(): clf.set_params(penalty="l2") clf.fit(X_new, iris.target) pred = clf.predict(X_new) - assert_true(np.mean(pred == iris.target) >= 0.7) + assert_greater(np.mean(pred == iris.target), 0.7) def test_invalid_input(): - clf = SGDClassifier(alpha=0.1, n_iter=10, shuffle=True, seed=0) + clf = SGDClassifier(alpha=0.1, n_iter=10, shuffle=True, random_state=None) clf.fit(iris.data, iris.target) assert_raises(ValueError, clf.transform, iris.data, "gobbledigook") diff --git a/sklearn/feature_selection/tests/test_rfe.py b/sklearn/feature_selection/tests/test_rfe.py index 190b9bc88a9ef..9984060750bed 100644 --- a/sklearn/feature_selection/tests/test_rfe.py +++ b/sklearn/feature_selection/tests/test_rfe.py @@ -4,15 +4,51 @@ import numpy as np from numpy.testing import assert_array_almost_equal, assert_array_equal -from nose.tools import assert_equal +from nose.tools import assert_equal, assert_true from scipy import sparse from sklearn.feature_selection.rfe import RFE, RFECV -from sklearn.datasets import load_iris -from sklearn.metrics import zero_one -from sklearn.svm import SVC +from sklearn.datasets import load_iris, make_friedman1 +from sklearn.metrics import zero_one_loss +from sklearn.svm import SVC, SVR from sklearn.utils import check_random_state +from sklearn.utils.testing import ignore_warnings +from sklearn.metrics import make_scorer +from sklearn.metrics import get_scorer + +class MockClassifier(object): + """ + Dummy classifier to test recursive feature ellimination + """ + + def __init__(self, foo_param=0): + self.foo_param = foo_param + + def fit(self, X, Y): + assert_true(len(X) == len(Y)) + self.coef_ = np.ones(X.shape[1], dtype=np.float64) + return self + + def predict(self, T): + return T.shape[0] + + predict_proba = predict + decision_function = predict + transform = predict + + def score(self, X=None, Y=None): + if self.foo_param > 1: + score = 1. + else: + score = 0. + return score + + def get_params(self, deep=True): + return {'foo_param': self.foo_param} + + def set_params(self, **params): + return self def test_rfe_set_params(): generator = check_random_state(0) @@ -59,36 +95,117 @@ def test_rfe(): assert_array_almost_equal(X_r, X_r_sparse.toarray()) -def test_rfecv(): +def test_rfe_mockclassifier(): generator = check_random_state(0) + iris = load_iris() + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + y = iris.target + # dense model + clf = MockClassifier() + rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1) + rfe.fit(X, y) + X_r = rfe.transform(X) + clf.fit(X_r, y) + assert_equal(len(rfe.ranking_), X.shape[1]) + assert_equal(X_r.shape, iris.data.shape) + + +def test_rfecv(): + generator = check_random_state(0) iris = load_iris() X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] y = list(iris.target) # regression test: list should be supported # Test using the score function - rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=3) + rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=5) rfecv.fit(X, y) # non-regression test for missing worst feature: - assert_equal(len(rfecv.cv_scores_), X.shape[1]) + assert_equal(len(rfecv.grid_scores_), X.shape[1]) assert_equal(len(rfecv.ranking_), X.shape[1]) X_r = rfecv.transform(X) + # All the noisy variable were filtered out + assert_array_equal(X_r, iris.data) + # same in sparse - rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=1, cv=3) + rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=1, cv=5) X_sparse = sparse.csr_matrix(X) rfecv_sparse.fit(X_sparse, y) X_r_sparse = rfecv_sparse.transform(X_sparse) - - assert_equal(X_r.shape, iris.data.shape) - assert_array_almost_equal(X_r[:10], iris.data[:10]) - assert_array_almost_equal(X_r_sparse.toarray(), X_r) + assert_array_equal(X_r_sparse.toarray(), iris.data) # Test using a customized loss function - rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=3, - loss_func=zero_one) + scoring = make_scorer(zero_one_loss, greater_is_better=False) + rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=5, + scoring=scoring) + ignore_warnings(rfecv.fit)(X, y) + X_r = rfecv.transform(X) + assert_array_equal(X_r, iris.data) + + # Test using a scorer + scorer = get_scorer('accuracy') + rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=5, + scoring=scorer) rfecv.fit(X, y) X_r = rfecv.transform(X) + assert_array_equal(X_r, iris.data) - assert_equal(X_r.shape, iris.data.shape) - assert_array_almost_equal(X_r[:10], iris.data[:10]) + # Test fix on grid_scores + def test_scorer(estimator, X, y): + return 1.0 + rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=5, + scoring=test_scorer) + rfecv.fit(X, y) + assert_array_equal(rfecv.grid_scores_, np.ones(len(rfecv.grid_scores_))) + + # Same as the first two tests, but with step=2 + rfecv = RFECV(estimator=SVC(kernel="linear"), step=2, cv=5) + rfecv.fit(X, y) + assert_equal(len(rfecv.grid_scores_), 6) + assert_equal(len(rfecv.ranking_), X.shape[1]) + X_r = rfecv.transform(X) + assert_array_equal(X_r, iris.data) + + rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=2, cv=5) + X_sparse = sparse.csr_matrix(X) + rfecv_sparse.fit(X_sparse, y) + X_r_sparse = rfecv_sparse.transform(X_sparse) + assert_array_equal(X_r_sparse.toarray(), iris.data) + + +def test_rfecv_mockclassifier(): + generator = check_random_state(0) + iris = load_iris() + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + y = list(iris.target) # regression test: list should be supported + + # Test using the score function + rfecv = RFECV(estimator=MockClassifier(), step=1, cv=5) + rfecv.fit(X, y) + # non-regression test for missing worst feature: + assert_equal(len(rfecv.grid_scores_), X.shape[1]) + assert_equal(len(rfecv.ranking_), X.shape[1]) + + +def test_rfe_min_step(): + + n_features = 10 + X, y = make_friedman1(n_samples=50, n_features=n_features, random_state=0) + n_samples, n_features = X.shape + estimator = SVR(kernel="linear") + + # Test when floor(step * n_features) <= 0 + selector = RFE(estimator, step=0.01) + sel = selector.fit(X,y) + assert_equal(sel.support_.sum(), n_features // 2) + + # Test when step is between (0,1) and floor(step * n_features) > 0 + selector = RFE(estimator, step=0.20) + sel = selector.fit(X,y) + assert_equal(sel.support_.sum(), n_features // 2) + + # Test when step is an integer + selector = RFE(estimator, step=5) + sel = selector.fit(X,y) + assert_equal(sel.support_.sum(), n_features // 2) diff --git a/sklearn/feature_selection/tests/test_variance_threshold.py b/sklearn/feature_selection/tests/test_variance_threshold.py new file mode 100644 index 0000000000000..10cae41f15e45 --- /dev/null +++ b/sklearn/feature_selection/tests/test_variance_threshold.py @@ -0,0 +1,28 @@ +from sklearn.utils.testing import (assert_array_equal, assert_equal, + assert_raises) + +from scipy.sparse import bsr_matrix, csc_matrix, csr_matrix + +from sklearn.feature_selection import VarianceThreshold + +data = [[0, 1, 2, 3, 4], + [0, 2, 2, 3, 5], + [1, 1, 2, 4, 0]] + + +def test_zero_variance(): + """Test VarianceThreshold with default setting, zero variance.""" + + for X in [data, csr_matrix(data), csc_matrix(data), bsr_matrix(data)]: + sel = VarianceThreshold().fit(X) + assert_array_equal([0, 1, 3, 4], sel.get_support(indices=True)) + + assert_raises(ValueError, VarianceThreshold().fit, [0, 1, 2, 3]) + assert_raises(ValueError, VarianceThreshold().fit, [[0, 1], [0, 1]]) + + +def test_variance_threshold(): + """Test VarianceThreshold with custom variance.""" + for X in [data, csr_matrix(data)]: + X = VarianceThreshold(threshold=.4).fit_transform(X) + assert_equal((len(data), 1), X.shape) diff --git a/sklearn/feature_selection/univariate_selection.py b/sklearn/feature_selection/univariate_selection.py index 1c9fa19a35ae6..81f4a08e51a0f 100644 --- a/sklearn/feature_selection/univariate_selection.py +++ b/sklearn/feature_selection/univariate_selection.py @@ -1,23 +1,36 @@ -# -*- coding: utf-8 -*- """Univariate features selection.""" # Authors: V. Michel, B. Thirion, G. Varoquaux, A. Gramfort, E. Duchesnay. -# L. Buitinck +# L. Buitinck, A. Joly # License: BSD 3 clause -from abc import ABCMeta, abstractmethod -from warnings import warn - import numpy as np -from scipy import stats +import warnings + +from scipy import special, stats from scipy.sparse import issparse -from ..base import BaseEstimator, TransformerMixin +from ..base import BaseEstimator from ..preprocessing import LabelBinarizer -from ..utils import (array2d, atleast2d_or_csr, check_arrays, safe_asarray, - safe_sqr, safe_mask) -from ..utils.extmath import safe_sparse_dot +from ..utils import (as_float_array, check_array, check_X_y, safe_sqr, + safe_mask) +from ..utils.extmath import norm, safe_sparse_dot +from ..utils.validation import check_is_fitted +from .base import SelectorMixin + + +def _clean_nans(scores): + """ + Fixes Issue #1240: NaNs can't be properly compared, so change them to the + smallest value of scores's dtype. -inf seems to be unreliable. + """ + # XXX where should this function be called? fit? scoring functions + # themselves? + scores = as_float_array(scores, copy=True) + scores[np.isnan(scores)] = np.finfo(scores.dtype).min + return scores + ###################################################################### # Scoring functions @@ -30,7 +43,7 @@ def f_oneway(*args): """Performs a 1-way ANOVA. The one-way ANOVA tests the null hypothesis that 2 or more groups have - the same population mean. The test is applied to samples from two or + the same population mean. The test is applied to samples from two or more groups, possibly with differing sizes. Parameters @@ -41,9 +54,9 @@ def f_oneway(*args): Returns ------- F-value : float - The computed F-value of the test + The computed F-value of the test. p-value : float - The associated p-value from the F-distribution + The associated p-value from the F-distribution. Notes ----- @@ -75,14 +88,13 @@ def f_oneway(*args): """ n_classes = len(args) - args = [safe_asarray(a) for a in args] + args = [as_float_array(a) for a in args] n_samples_per_class = np.array([a.shape[0] for a in args]) n_samples = np.sum(n_samples_per_class) - ss_alldata = reduce(lambda x, y: x + y, - [safe_sqr(a).sum(axis=0) for a in args]) - sums_args = [a.sum(axis=0) for a in args] - square_of_sums_alldata = safe_sqr(reduce(lambda x, y: x + y, sums_args)) - square_of_sums_args = [safe_sqr(s) for s in sums_args] + ss_alldata = sum(safe_sqr(a).sum(axis=0) for a in args) + sums_args = [np.asarray(a.sum(axis=0)) for a in args] + square_of_sums_alldata = sum(sums_args) ** 2 + square_of_sums_args = [s ** 2 for s in sums_args] sstot = ss_alldata - square_of_sums_alldata / float(n_samples) ssbn = 0. for k, _ in enumerate(args): @@ -93,6 +105,10 @@ def f_oneway(*args): dfwn = n_samples - n_classes msb = ssbn / float(dfbn) msw = sswn / float(dfwn) + constant_features_idx = np.where(msw == 0.)[0] + if (np.nonzero(msb)[0].size != msb.size and constant_features_idx.size): + warnings.warn("Features %s are constant." % constant_features_idx, + UserWarning) f = msb / msw # flatten matrix to vector in sparse case f = np.asarray(f).ravel() @@ -101,36 +117,61 @@ def f_oneway(*args): def f_classif(X, y): - """Compute the Anova F-value for the provided sample + """Compute the ANOVA F-value for the provided sample. Parameters ---------- X : {array-like, sparse matrix} shape = [n_samples, n_features] - The set of regressors that will tested sequentially + The set of regressors that will tested sequentially. + y : array of shape(n_samples) - The data matrix + The data matrix. Returns ------- F : array, shape = [n_features,] - The set of F values + The set of F values. + pval : array, shape = [n_features,] - The set of p-values + The set of p-values. + + See also + -------- + chi2: Chi-squared stats of non-negative features for classification tasks. + f_regression: F-value between label/feature for regression tasks. """ - X, y = check_arrays(X, y) + X, y = check_X_y(X, y, ['csr', 'csc', 'coo']) args = [X[safe_mask(X, y == k)] for k in np.unique(y)] return f_oneway(*args) +def _chisquare(f_obs, f_exp): + """Fast replacement for scipy.stats.chisquare. + + Version from https://github.com/scipy/scipy/pull/2525 with additional + optimizations. + """ + f_obs = np.asarray(f_obs, dtype=np.float64) + + k = len(f_obs) + # Reuse f_obs for chi-squared statistics + chisq = f_obs + chisq -= f_exp + chisq **= 2 + chisq /= f_exp + chisq = chisq.sum(axis=0) + return chisq, special.chdtrc(k - 1, chisq) + + def chi2(X, y): - """Compute χ² (chi-squared) statistic for each class/feature combination. + """Compute chi-squared stats between each non-negative feature and class. This score can be used to select the n_features features with the - highest values for the χ² (chi-square) statistic from either boolean or - multinomially distributed data (e.g., term counts in document - classification) relative to the classes. + highest values for the test chi-squared statistic from X, which must + contain only non-negative features such as booleans or frequencies + (e.g., term counts in document classification), relative to the classes. - Recall that the χ² statistic measures dependence between stochastic + Recall that the chi-square test measures dependence between stochastic variables, so using this function "weeds out" the features that are the most likely to be independent of class and therefore irrelevant for classification. @@ -153,40 +194,50 @@ def chi2(X, y): Notes ----- Complexity of this algorithm is O(n_classes * n_features). + + See also + -------- + f_classif: ANOVA F-value between labe/feature for classification tasks. + f_regression: F-value between label/feature for regression tasks. """ # XXX: we might want to do some of the following in logspace instead for # numerical stability. - X = atleast2d_or_csr(X) + X = check_array(X, accept_sparse='csr') + if np.any((X.data if issparse(X) else X) < 0): + raise ValueError("Input X must be non-negative.") + Y = LabelBinarizer().fit_transform(y) if Y.shape[1] == 1: Y = np.append(1 - Y, Y, axis=1) observed = safe_sparse_dot(Y.T, X) # n_classes * n_features - feature_count = array2d(X.sum(axis=0)) - class_prob = array2d(Y.mean(axis=0)) + feature_count = check_array(X.sum(axis=0)) + class_prob = check_array(Y.mean(axis=0)) expected = np.dot(class_prob.T, feature_count) - return stats.chisquare(observed, expected) + return _chisquare(observed, expected) def f_regression(X, y, center=True): - """Univariate linear regression tests + """Univariate linear regression tests. Quick linear model for testing the effect of a single regressor, sequentially for many regressors. This is done in 3 steps: - 1. the regressor of interest and the data are orthogonalized - wrt constant regressors - 2. the cross correlation between data and regressors is computed - 3. it is converted to an F score then to a p-value + + 1. The regressor of interest and the data are orthogonalized + wrt constant regressors. + 2. The cross correlation between data and regressors is computed. + 3. It is converted to an F score then to a p-value. Parameters ---------- X : {array-like, sparse matrix} shape = (n_samples, n_features) The set of regressors that will tested sequentially. + y : array of shape(n_samples). The data matrix @@ -197,13 +248,18 @@ def f_regression(X, y, center=True): ------- F : array, shape=(n_features,) F values of features. + pval : array, shape=(n_features,) p-values of F-scores. + + See also + -------- + f_classif: ANOVA F-value between labe/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. """ if issparse(X) and center: raise ValueError("center=True only allowed for dense data") - X, y = check_arrays(X, y, dtype=np.float) - y = y.ravel() + X, y = check_X_y(X, y, ['csr', 'csc', 'coo'], dtype=np.float) if center: y = y - np.mean(y) X = X.copy('F') # faster in fortran @@ -211,89 +267,73 @@ def f_regression(X, y, center=True): # compute the correlation corr = safe_sparse_dot(y, X) + # XXX could use corr /= row_norms(X.T) here, but the test doesn't pass corr /= np.asarray(np.sqrt(safe_sqr(X).sum(axis=0))).ravel() - corr /= np.asarray(np.sqrt(safe_sqr(y).sum())).ravel() + corr /= norm(y) # convert to p-value - dof = y.size - 2 - F = corr ** 2 / (1 - corr ** 2) * dof - pv = stats.f.sf(F, 1, dof) + degrees_of_freedom = y.size - (2 if center else 1) + F = corr ** 2 / (1 - corr ** 2) * degrees_of_freedom + pv = stats.f.sf(F, 1, degrees_of_freedom) return F, pv ###################################################################### -# General class for filter univariate selection +# Base classes -class _AbstractUnivariateFilter(BaseEstimator, TransformerMixin): - __metaclass__ = ABCMeta +class _BaseFilter(BaseEstimator, SelectorMixin): + """Initialize the univariate feature selection. + + Parameters + ---------- + score_func : callable + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues). + """ def __init__(self, score_func): - """ Initialize the univariate feature selection. + self.score_func = score_func + + def fit(self, X, y): + """Run score function on (X, y) and get the appropriate features. Parameters ---------- - score_func : callable - Function taking two arrays X and y, and returning a pair of arrays - (scores, pvalues). - """ - if not callable(score_func): - raise TypeError( - "The score function should be a callable, %r " - "was passed." % (score_func, type(score_func))) - self.score_func = score_func + X : array-like, shape = [n_samples, n_features] + The training input samples. - def fit(self, X, y): - """ - Evaluate the function - """ - self.scores_, self.pvalues_ = self.score_func(X, y) - if len(np.unique(self.pvalues_)) < len(self.pvalues_): - warn("Duplicate p-values. Result may depend on feature ordering." - "There are probably duplicate features, or you used a " - "classification score for a regression task.") - return self + y : array-like, shape = [n_samples] + The target values (class labels in classification, real numbers in + regression). - def get_support(self, indices=False): + Returns + ------- + self : object + Returns self. """ - Return a mask, or list, of the features/indices selected. - """ - mask = self._get_support_mask() - return mask if not indices else np.where(mask)[0] + X, y = check_X_y(X, y, ['csr', 'csc', 'coo']) - @abstractmethod - def _get_support_mask(self): - """ - Must return a boolean mask indicating which features are selected. - """ + if not callable(self.score_func): + raise TypeError("The score function should be a callable, %s (%s) " + "was passed." + % (self.score_func, type(self.score_func))) - def transform(self, X): - """ - Transform a new matrix using the selected features - """ - X = atleast2d_or_csr(X) - mask = self._get_support_mask() - if len(mask) != X.shape[1]: - raise ValueError("X has a different shape than during fitting.") - return atleast2d_or_csr(X)[:, safe_mask(X, mask)] + self._check_params(X, y) - def inverse_transform(self, X): - """ - Transform a new matrix using the selected features - """ - support_ = self.get_support() - if X.ndim == 1: - X = X[None, :] - Xt = np.zeros((X.shape[0], support_.size)) - Xt[:, support_] = X - return Xt + self.scores_, self.pvalues_ = self.score_func(X, y) + self.scores_ = np.asarray(self.scores_) + self.pvalues_ = np.asarray(self.pvalues_) + return self + + def _check_params(self, X, y): + pass ###################################################################### # Specific filters ###################################################################### - -class SelectPercentile(_AbstractUnivariateFilter): - """Filter: Select the best percentile of the p-values. +class SelectPercentile(_BaseFilter): + """Select features according to a percentile of the highest scores. Parameters ---------- @@ -314,41 +354,53 @@ class SelectPercentile(_AbstractUnivariateFilter): Notes ----- - Ties between features with equal p-values will be broken in an unspecified + Ties between features with equal scores will be broken in an unspecified way. + See also + -------- + f_classif: ANOVA F-value between labe/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. + f_regression: F-value between label/feature for regression tasks. + SelectKBest: Select features based on the k highest scores. + SelectFpr: Select features based on a false positive rate test. + SelectFdr: Select features based on an estimated false discovery rate. + SelectFwe: Select features based on family-wise error rate. + GenericUnivariateSelect: Univariate feature selector with configurable mode. """ def __init__(self, score_func=f_classif, percentile=10): - if not 0 <= percentile <= 100: - raise ValueError("percentile should be >=0, <=100; got %r" - % percentile) - self.percentile = percentile super(SelectPercentile, self).__init__(score_func) + self.percentile = percentile + + def _check_params(self, X, y): + if not 0 <= self.percentile <= 100: + raise ValueError("percentile should be >=0, <=100; got %r" + % self.percentile) def _get_support_mask(self): - percentile = self.percentile - if percentile > 100: - raise ValueError("percentile should be between 0 and 100" - " (%f given)" % (percentile)) - # Cater for Nans - if percentile == 100: - return np.ones(len(self.pvalues_), dtype=np.bool) - elif percentile == 0: - return np.zeros(len(self.pvalues_), dtype=np.bool) - alpha = stats.scoreatpercentile(self.pvalues_, percentile) - # XXX refactor the indices -> mask -> indices -> mask thing - inds = np.where(self.pvalues_ <= alpha)[0] - # if we selected to many because of equal p-values, - # we throw them away now - inds = inds[:len(self.pvalues_) * percentile // 100] - mask = np.zeros(self.pvalues_.shape, dtype=np.bool) - mask[inds] = True + check_is_fitted(self, 'scores_') + + # Cater for NaNs + if self.percentile == 100: + return np.ones(len(self.scores_), dtype=np.bool) + elif self.percentile == 0: + return np.zeros(len(self.scores_), dtype=np.bool) + + scores = _clean_nans(self.scores_) + treshold = stats.scoreatpercentile(scores, + 100 - self.percentile) + mask = scores > treshold + ties = np.where(scores == treshold)[0] + if len(ties): + max_feats = len(scores) * self.percentile // 100 + kept_ties = ties[:max_feats - mask.sum()] + mask[kept_ties] = True return mask -class SelectKBest(_AbstractUnivariateFilter): - """Filter: Select the k lowest p-values. +class SelectKBest(_BaseFilter): + """Select features according to the k highest scores. Parameters ---------- @@ -356,8 +408,9 @@ class SelectKBest(_AbstractUnivariateFilter): Function taking two arrays X and y, and returning a pair of arrays (scores, pvalues). - k : int, optional, default=10 + k : int or "all", optional, default=10 Number of top features to select. + The "all" option bypasses selection, for use in a parameter search. Attributes ---------- @@ -369,30 +422,49 @@ class SelectKBest(_AbstractUnivariateFilter): Notes ----- - Ties between features with equal p-values will be broken in an unspecified + Ties between features with equal scores will be broken in an unspecified way. + See also + -------- + f_classif: ANOVA F-value between labe/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. + f_regression: F-value between label/feature for regression tasks. + SelectPercentile: Select features based on percentile of the highest scores. + SelectFpr: Select features based on a false positive rate test. + SelectFdr: Select features based on an estimated false discovery rate. + SelectFwe: Select features based on family-wise error rate. + GenericUnivariateSelect: Univariate feature selector with configurable mode. """ def __init__(self, score_func=f_classif, k=10): - self.k = k super(SelectKBest, self).__init__(score_func) + self.k = k + + def _check_params(self, X, y): + if not (self.k == "all" or 0 <= self.k <= X.shape[1]): + raise ValueError("k should be >=0, <= n_features; got %r." + "Use k='all' to return all features." + % self.k) def _get_support_mask(self): - k = self.k - if k > len(self.pvalues_): - raise ValueError("cannot select %d features among %d" - % (k, len(self.pvalues_))) - - # XXX This should be refactored; we're getting an array of indices - # from argsort, which we transform to a mask, which we probably - # transform back to indices later. - mask = np.zeros(self.pvalues_.shape, dtype=bool) - mask[np.argsort(self.pvalues_)[:k]] = 1 - return mask + check_is_fitted(self, 'scores_') + + if self.k == 'all': + return np.ones(self.scores_.shape, dtype=bool) + elif self.k == 0: + return np.zeros(self.scores_.shape, dtype=bool) + else: + scores = _clean_nans(self.scores_) + mask = np.zeros(scores.shape, dtype=bool) + + # Request a stable sort. Mergesort takes more memory (~40MB per + # megafeature on x86-64). + mask[np.argsort(scores, kind="mergesort")[-self.k:]] = 1 + return mask -class SelectFpr(_AbstractUnivariateFilter): +class SelectFpr(_BaseFilter): """Filter: Select the pvalues below alpha based on a FPR test. FPR test stands for False Positive Rate test. It controls the total @@ -414,22 +486,34 @@ class SelectFpr(_AbstractUnivariateFilter): pvalues_ : array-like, shape=(n_features,) p-values of feature scores. + + See also + -------- + f_classif: ANOVA F-value between labe/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. + f_regression: F-value between label/feature for regression tasks. + SelectPercentile: Select features based on percentile of the highest scores. + SelectKBest: Select features based on the k highest scores. + SelectFdr: Select features based on an estimated false discovery rate. + SelectFwe: Select features based on family-wise error rate. + GenericUnivariateSelect: Univariate feature selector with configurable mode. """ def __init__(self, score_func=f_classif, alpha=5e-2): - self.alpha = alpha super(SelectFpr, self).__init__(score_func) + self.alpha = alpha def _get_support_mask(self): - alpha = self.alpha - return self.pvalues_ < alpha + check_is_fitted(self, 'scores_') + return self.pvalues_ < self.alpha -class SelectFdr(_AbstractUnivariateFilter): + +class SelectFdr(_BaseFilter): """Filter: Select the p-values for an estimated false discovery rate - This uses the Benjamini-Hochberg procedure. ``alpha`` is the target false - discovery rate. + This uses the Benjamini-Hochberg procedure. ``alpha`` is an upper bound + on the expected false discovery rate. Parameters ---------- @@ -448,20 +532,40 @@ class SelectFdr(_AbstractUnivariateFilter): pvalues_ : array-like, shape=(n_features,) p-values of feature scores. + + References + ---------- + http://en.wikipedia.org/wiki/False_discovery_rate + + See also + -------- + f_classif: ANOVA F-value between labe/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. + f_regression: F-value between label/feature for regression tasks. + SelectPercentile: Select features based on percentile of the highest scores. + SelectKBest: Select features based on the k highest scores. + SelectFpr: Select features based on a false positive rate test. + SelectFwe: Select features based on family-wise error rate. + GenericUnivariateSelect: Univariate feature selector with configurable mode. """ def __init__(self, score_func=f_classif, alpha=5e-2): - self.alpha = alpha super(SelectFdr, self).__init__(score_func) + self.alpha = alpha def _get_support_mask(self): - alpha = self.alpha + check_is_fitted(self, 'scores_') + + n_features = len(self.pvalues_) sv = np.sort(self.pvalues_) - threshold = sv[sv < alpha * np.arange(len(self.pvalues_))].max() - return self.pvalues_ <= threshold + selected = sv[sv <= float(self.alpha) / n_features + * np.arange(n_features)] + if selected.size == 0: + return np.zeros_like(self.pvalues_, dtype=bool) + return self.pvalues_ <= selected.max() -class SelectFwe(_AbstractUnivariateFilter): +class SelectFwe(_BaseFilter): """Filter: Select the p-values corresponding to Family-wise error rate Parameters @@ -480,22 +584,36 @@ class SelectFwe(_AbstractUnivariateFilter): pvalues_ : array-like, shape=(n_features,) p-values of feature scores. + + See also + -------- + f_classif: ANOVA F-value between labe/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. + f_regression: F-value between label/feature for regression tasks. + SelectPercentile: Select features based on percentile of the highest scores. + SelectKBest: Select features based on the k highest scores. + SelectFpr: Select features based on a false positive rate test. + SelectFdr: Select features based on an estimated false discovery rate. + GenericUnivariateSelect: Univariate feature selector with configurable mode. """ def __init__(self, score_func=f_classif, alpha=5e-2): - self.alpha = alpha super(SelectFwe, self).__init__(score_func) + self.alpha = alpha def _get_support_mask(self): - alpha = self.alpha - return (self.pvalues_ < alpha / len(self.pvalues_)) + check_is_fitted(self, 'scores_') + + return (self.pvalues_ < self.alpha / len(self.pvalues_)) ###################################################################### # Generic filter ###################################################################### -class GenericUnivariateSelect(_AbstractUnivariateFilter): +# TODO this class should fit on either p-values or scores, +# depending on the mode. +class GenericUnivariateSelect(_BaseFilter): """Univariate feature selector with configurable strategy. Parameters @@ -517,33 +635,54 @@ class GenericUnivariateSelect(_AbstractUnivariateFilter): pvalues_ : array-like, shape=(n_features,) p-values of feature scores. + + See also + -------- + f_classif: ANOVA F-value between labe/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. + f_regression: F-value between label/feature for regression tasks. + SelectPercentile: Select features based on percentile of the highest scores. + SelectKBest: Select features based on the k highest scores. + SelectFpr: Select features based on a false positive rate test. + SelectFdr: Select features based on an estimated false discovery rate. + SelectFwe: Select features based on family-wise error rate. """ _selection_modes = {'percentile': SelectPercentile, 'k_best': SelectKBest, 'fpr': SelectFpr, 'fdr': SelectFdr, - 'fwe': SelectFwe, - } + 'fwe': SelectFwe} def __init__(self, score_func=f_classif, mode='percentile', param=1e-5): - if mode not in self._selection_modes: - raise ValueError( - "The mode passed should be one of %s, %r " - "was passed." % ( - self._selection_modes.keys(), - mode, type(mode))) super(GenericUnivariateSelect, self).__init__(score_func) self.mode = mode self.param = param - def _get_support_mask(self): - selector = self._selection_modes[self.mode](lambda x: x) - selector.pvalues_ = self.pvalues_ - selector.scores_ = self.scores_ + def _make_selector(self): + selector = self._selection_modes[self.mode](score_func=self.score_func) + # Now perform some acrobatics to set the right named parameter in # the selector possible_params = selector._get_param_names() possible_params.remove('score_func') selector.set_params(**{possible_params[0]: self.param}) + + return selector + + def _check_params(self, X, y): + if self.mode not in self._selection_modes: + raise ValueError("The mode passed should be one of %s, %r," + " (type %s) was passed." + % (self._selection_modes.keys(), self.mode, + type(self.mode))) + + self._make_selector()._check_params(X, y) + + def _get_support_mask(self): + check_is_fitted(self, 'scores_') + + selector = self._make_selector() + selector.pvalues_ = self.pvalues_ + selector.scores_ = self.scores_ return selector._get_support_mask() diff --git a/sklearn/feature_selection/variance_threshold.py b/sklearn/feature_selection/variance_threshold.py new file mode 100644 index 0000000000000..202a86d1a88b5 --- /dev/null +++ b/sklearn/feature_selection/variance_threshold.py @@ -0,0 +1,80 @@ +# Author: Lars Buitinck +# License: 3-clause BSD + +import numpy as np +from ..base import BaseEstimator +from .base import SelectorMixin +from ..utils import check_array +from ..utils.sparsefuncs import mean_variance_axis +from ..utils.validation import check_is_fitted + + +class VarianceThreshold(BaseEstimator, SelectorMixin): + """Feature selector that removes all low-variance features. + + This feature selection algorithm looks only at the features (X), not the + desired outputs (y), and can thus be used for unsupervised learning. + + Parameters + ---------- + threshold : float, optional + Features with a training-set variance lower than this threshold will + be removed. The default is to keep all features with non-zero variance, + i.e. remove the features that have the same value in all samples. + + Attributes + ---------- + variances_ : array, shape (n_features,) + Variances of individual features. + + Examples + -------- + The following dataset has integer features, two of which are the same + in every sample. These are removed with the default setting for threshold:: + + >>> X = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]] + >>> selector = VarianceThreshold() + >>> selector.fit_transform(X) + array([[2, 0], + [1, 4], + [1, 1]]) + """ + + def __init__(self, threshold=0.): + self.threshold = threshold + + def fit(self, X, y=None): + """Learn empirical variances from X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Sample vectors from which to compute variances. + + y : any + Ignored. This parameter exists only for compatibility with + sklearn.pipeline.Pipeline. + + Returns + ------- + self + """ + X = check_array(X, ('csr', 'csc'), dtype=np.float64) + + if hasattr(X, "toarray"): # sparse matrix + _, self.variances_ = mean_variance_axis(X, axis=0) + else: + self.variances_ = np.var(X, axis=0) + + if np.all(self.variances_ <= self.threshold): + msg = "No feature in X meets the variance threshold {0:.5f}" + if X.shape[0] == 1: + msg += " (X contains only one sample)" + raise ValueError(msg.format(self.threshold)) + + return self + + def _get_support_mask(self): + check_is_fitted(self, 'variances_') + + return self.variances_ > self.threshold diff --git a/sklearn/gaussian_process/__init__.py b/sklearn/gaussian_process/__init__.py index 33da44b9ecce5..1d903181be719 100644 --- a/sklearn/gaussian_process/__init__.py +++ b/sklearn/gaussian_process/__init__.py @@ -1,9 +1,8 @@ -#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Vincent Dubourg # (mostly translation, see implementation details) -# License: BSD style +# Licence: BSD 3 clause """ The :mod:`sklearn.gaussian_process` module implements scalar Gaussian Process diff --git a/sklearn/gaussian_process/correlation_models.py b/sklearn/gaussian_process/correlation_models.py index 00bb55afa8fa5..cec09af733dba 100644 --- a/sklearn/gaussian_process/correlation_models.py +++ b/sklearn/gaussian_process/correlation_models.py @@ -1,9 +1,8 @@ -#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Vincent Dubourg # (mostly translation, see implementation details) -# License: BSD style +# Licence: BSD 3 clause """ The built-in correlation models submodule for the gaussian_process module. @@ -18,9 +17,9 @@ def absolute_exponential(theta, d): Absolute exponential autocorrelation model. (Ornstein-Uhlenbeck stochastic process):: - n - theta, dx --> r(theta, dx) = exp( sum - theta_i * |dx_i| ) - i = 1 + n + theta, d --> r(theta, d) = exp( sum - theta_i * |d_i| ) + i = 1 Parameters ---------- @@ -28,7 +27,7 @@ def absolute_exponential(theta, d): An array with shape 1 (isotropic) or n (anisotropic) giving the autocorrelation parameter(s). - dx : array_like + d : array_like An array with shape (n_eval, n_features) giving the componentwise distances between locations x and x' at which the correlation model should be evaluated. @@ -60,9 +59,9 @@ def squared_exponential(theta, d): Squared exponential correlation model (Radial Basis Function). (Infinitely differentiable stochastic process, very smooth):: - n - theta, dx --> r(theta, dx) = exp( sum - theta_i * (dx_i)^2 ) - i = 1 + n + theta, d --> r(theta, d) = exp( sum - theta_i * (d_i)^2 ) + i = 1 Parameters ---------- @@ -70,7 +69,7 @@ def squared_exponential(theta, d): An array with shape 1 (isotropic) or n (anisotropic) giving the autocorrelation parameter(s). - dx : array_like + d : array_like An array with shape (n_eval, n_features) giving the componentwise distances between locations x and x' at which the correlation model should be evaluated. @@ -104,9 +103,9 @@ def generalized_exponential(theta, d): (Useful when one does not know the smoothness of the function to be predicted.):: - n - theta, dx --> r(theta, dx) = exp( sum - theta_i * |dx_i|^p ) - i = 1 + n + theta, d --> r(theta, d) = exp( sum - theta_i * |d_i|^p ) + i = 1 Parameters ---------- @@ -114,7 +113,7 @@ def generalized_exponential(theta, d): An array with shape 1+1 (isotropic) or n+1 (anisotropic) giving the autocorrelation parameter(s) (theta, p). - dx : array_like + d : array_like An array with shape (n_eval, n_features) giving the componentwise distances between locations x and x' at which the correlation model should be evaluated. @@ -153,17 +152,17 @@ def pure_nugget(theta, d): Spatial independence correlation model (pure nugget). (Useful when one wants to solve an ordinary least squares problem!):: - n - theta, dx --> r(theta, dx) = 1 if sum |dx_i| == 0 - i = 1 - 0 otherwise + n + theta, d --> r(theta, d) = 1 if sum |d_i| == 0 + i = 1 + 0 otherwise Parameters ---------- theta : array_like None. - dx : array_like + d : array_like An array with shape (n_eval, n_features) giving the componentwise distances between locations x and x' at which the correlation model should be evaluated. @@ -189,9 +188,9 @@ def cubic(theta, d): """ Cubic correlation model:: - theta, dx --> r(theta, dx) = + theta, d --> r(theta, d) = n - prod max(0, 1 - 3(theta_j*d_ij)^2 + 2(theta_j*d_ij)^3) , i = 1,...,m + prod max(0, 1 - 3(theta_j*d_ij)^2 + 2(theta_j*d_ij)^3) , i = 1,...,m j = 1 Parameters @@ -200,7 +199,7 @@ def cubic(theta, d): An array with shape 1 (isotropic) or n (anisotropic) giving the autocorrelation parameter(s). - dx : array_like + d : array_like An array with shape (n_eval, n_features) giving the componentwise distances between locations x and x' at which the correlation model should be evaluated. @@ -221,7 +220,7 @@ def cubic(theta, d): n_features = 1 lth = theta.size - if lth == 1: + if lth == 1: td = np.abs(d) * theta elif lth != n_features: raise Exception("Length of theta must be 1 or " + str(n_features)) @@ -239,7 +238,7 @@ def linear(theta, d): """ Linear correlation model:: - theta, dx --> r(theta, dx) = + theta, d --> r(theta, d) = n prod max(0, 1 - theta_j*d_ij) , i = 1,...,m j = 1 @@ -250,7 +249,7 @@ def linear(theta, d): An array with shape 1 (isotropic) or n (anisotropic) giving the autocorrelation parameter(s). - dx : array_like + d : array_like An array with shape (n_eval, n_features) giving the componentwise distances between locations x and x' at which the correlation model should be evaluated. diff --git a/sklearn/gaussian_process/gaussian_process.py b/sklearn/gaussian_process/gaussian_process.py index 18986d4b46824..d1507f98414f2 100644 --- a/sklearn/gaussian_process/gaussian_process.py +++ b/sklearn/gaussian_process/gaussian_process.py @@ -1,28 +1,22 @@ -#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Vincent Dubourg # (mostly translation, see implementation details) -# License: BSD style +# Licence: BSD 3 clause + +from __future__ import print_function import numpy as np -from scipy import linalg, optimize, rand +from scipy import linalg, optimize from ..base import BaseEstimator, RegressorMixin from ..metrics.pairwise import manhattan_distances -from ..utils import array2d, check_random_state -from ..utils import deprecated +from ..utils import check_random_state, check_array, check_X_y +from ..utils.validation import check_is_fitted from . import regression_models as regression from . import correlation_models as correlation MACHINE_EPSILON = np.finfo(np.double).eps -if hasattr(linalg, 'solve_triangular'): - # only in scipy since 0.9 - solve_triangular = linalg.solve_triangular -else: - # slower, but works - def solve_triangular(x, y, lower=True): - return linalg.solve(x, y) def l1_cross_distances(X): @@ -46,9 +40,9 @@ def l1_cross_distances(X): The indices i and j of the vectors in X associated to the cross- distances in D: D[k] = np.abs(X[ij[k, 0]] - Y[ij[k, 1]]). """ - X = array2d(X) + X = check_array(X) n_samples, n_features = X.shape - n_nonzero_cross_dist = n_samples * (n_samples - 1) / 2 + n_nonzero_cross_dist = n_samples * (n_samples - 1) // 2 ij = np.zeros((n_nonzero_cross_dist, 2), dtype=np.int) D = np.zeros((n_nonzero_cross_dist, n_features)) ll_1 = 0 @@ -59,7 +53,7 @@ def l1_cross_distances(X): ij[ll_0:ll_1, 1] = np.arange(k + 1, n_samples) D[ll_0:ll_1] = np.abs(X[k] - X[(k + 1):n_samples]) - return D, ij.astype(np.int) + return D, ij class GaussianProcess(BaseEstimator, RegressorMixin): @@ -109,7 +103,7 @@ class GaussianProcess(BaseEstimator, RegressorMixin): An array with shape (n_features, ) or (1, ). The parameters in the autocorrelation model. If thetaL and thetaU are also specified, theta0 is considered as - the starting point for the maximum likelihood rstimation of the + the starting point for the maximum likelihood estimation of the best set of parameters. Default assumes isotropic autocorrelation model with theta0 = 1e-1. @@ -172,11 +166,11 @@ class GaussianProcess(BaseEstimator, RegressorMixin): Attributes ---------- - `theta_`: array + theta_ : array Specified theta OR the best set of autocorrelation parameters (the \ sought maximizer of the reduced likelihood function). - `reduced_likelihood_function_value_`: array + reduced_likelihood_function_value_ : array The optimal reduced likelihood function value. Examples @@ -244,9 +238,6 @@ def __init__(self, regr='constant', corr='squared_exponential', beta0=None, self.random_start = random_start self.random_state = random_state - # Run input checks - self._check_params() - def fit(self, X, y): """ The Gaussian Process model fitting method. @@ -258,8 +249,8 @@ def fit(self, X, y): observations were made. y : double array_like - An array with shape (n_features, ) with the observations of the - scalar output to be predicted. + An array with shape (n_samples, ) or shape (n_samples, n_targets) + with the observations of the output to be predicted. Returns ------- @@ -267,20 +258,20 @@ def fit(self, X, y): A fitted Gaussian Process model object awaiting data to perform predictions. """ + # Run input checks + self._check_params() + self.random_state = check_random_state(self.random_state) # Force data to 2D numpy.array - X = array2d(X) - y = np.asarray(y).ravel()[:, np.newaxis] + X, y = check_X_y(X, y, multi_output=True, y_numeric=True) + self.y_ndim_ = y.ndim + if y.ndim == 1: + y = y[:, np.newaxis] # Check shapes of DOE & observations - n_samples_X, n_features = X.shape - n_samples_y = y.shape[0] - - if n_samples_X != n_samples_y: - raise ValueError("X and y must have the same number of rows.") - else: - n_samples = n_samples_X + n_samples, n_features = X.shape + _, n_targets = y.shape # Run input checks self._check_params(n_samples) @@ -304,10 +295,10 @@ def fit(self, X, y): # Calculate matrix of distances D between samples D, ij = l1_cross_distances(X) - if np.min(np.sum(D, axis=1)) == 0. \ - and self.corr != correlation.pure_nugget: + if (np.min(np.sum(D, axis=1)) == 0. + and self.corr != correlation.pure_nugget): raise Exception("Multiple input features cannot have the same" - " value") + " target value.") # Regression matrix and parameters F = self.regr(X) @@ -318,12 +309,12 @@ def fit(self, X, y): p = 1 if n_samples_F != n_samples: raise Exception("Number of rows in F and X do not match. Most " - + "likely something is going wrong with the " - + "regression model.") + "likely something is going wrong with the " + "regression model.") if p > n_samples_F: raise Exception(("Ordinary least squares problem is undetermined " - + "n_samples=%d must be greater than the " - + "regression model size p=%d.") % (n_samples, p)) + "n_samples=%d must be greater than the " + "regression model size p=%d.") % (n_samples, p)) if self.beta0 is not None: if self.beta0.shape[0] != p: raise Exception("Shapes of beta0 and F do not match.") @@ -342,18 +333,18 @@ def fit(self, X, y): # Maximum Likelihood Estimation of the parameters if self.verbose: print("Performing Maximum Likelihood Estimation of the " - + "autocorrelation parameters...") + "autocorrelation parameters...") self.theta_, self.reduced_likelihood_function_value_, par = \ self._arg_max_reduced_likelihood_function() if np.isinf(self.reduced_likelihood_function_value_): raise Exception("Bad parameter region. " - + "Try increasing upper bound") + "Try increasing upper bound") else: # Given parameters if self.verbose: print("Given autocorrelation parameters. " - + "Computing Gaussian Process model parameters...") + "Computing Gaussian Process model parameters...") self.theta_ = self.theta0 self.reduced_likelihood_function_value_, par = \ self.reduced_likelihood_function() @@ -372,7 +363,7 @@ def fit(self, X, y): # (it is required only when MSE is wanted in self.predict) if self.verbose: print("Light storage mode specified. " - + "Flushing autocorrelation matrix...") + "Flushing autocorrelation matrix...") self.D = None self.ij = None self.F = None @@ -400,32 +391,39 @@ def predict(self, X, eval_MSE=False, batch_size=None): batch_size : integer, optional An integer giving the maximum number of points that can be - evaluated simulatneously (depending on the available memory). + evaluated simultaneously (depending on the available memory). Default is None so that all given points are evaluated at the same time. Returns ------- - y : array_like - An array with shape (n_eval, ) with the Best Linear Unbiased + y : array_like, shape (n_samples, ) or (n_samples, n_targets) + An array with shape (n_eval, ) if the Gaussian Process was trained + on an array of shape (n_samples, ) or an array with shape + (n_eval, n_targets) if the Gaussian Process was trained on an array + of shape (n_samples, n_targets) with the Best Linear Unbiased Prediction at x. MSE : array_like, optional (if eval_MSE == True) - An array with shape (n_eval, ) with the Mean Squared Error at x. + An array with shape (n_eval, ) or (n_eval, n_targets) as with y, + with the Mean Squared Error at x. """ + check_is_fitted(self, "X") # Check input shapes - X = array2d(X) - n_eval, n_features_X = X.shape + X = check_array(X) + n_eval, _ = X.shape n_samples, n_features = self.X.shape + n_samples_y, n_targets = self.y.shape # Run input checks self._check_params(n_samples) - if n_features_X != n_features: + if X.shape[1] != n_features: raise ValueError(("The number of features in X (X.shape[1] = %d) " - + "should match the sample size used for fit() " - + "which is %d.") % (n_features_X, n_features)) + "should match the number of features used " + "for fit() " + "which is %d.") % (X.shape[1], n_features)) if batch_size is None: # No memory management @@ -449,7 +447,10 @@ def predict(self, X, eval_MSE=False, batch_size=None): y_ = np.dot(f, self.beta) + np.dot(r, self.gamma) # Predictor - y = (self.y_mean + self.y_std * y_).ravel() + y = (self.y_mean + self.y_std * y_).reshape(n_eval, n_targets) + + if self.y_ndim_ == 1: + y = y.ravel() # Mean Squared Error if eval_MSE: @@ -458,31 +459,37 @@ def predict(self, X, eval_MSE=False, batch_size=None): # Light storage mode (need to recompute C, F, Ft and G) if self.verbose: print("This GaussianProcess used 'light' storage mode " - + "at instanciation. Need to recompute " - + "autocorrelation matrix...") + "at instantiation. Need to recompute " + "autocorrelation matrix...") reduced_likelihood_function_value, par = \ self.reduced_likelihood_function() self.C = par['C'] self.Ft = par['Ft'] self.G = par['G'] - rt = solve_triangular(self.C, r.T, lower=True) + rt = linalg.solve_triangular(self.C, r.T, lower=True) if self.beta0 is None: # Universal Kriging - u = solve_triangular(self.G.T, - np.dot(self.Ft.T, rt) - f.T) + u = linalg.solve_triangular(self.G.T, + np.dot(self.Ft.T, rt) - f.T, + lower=True) else: # Ordinary Kriging - u = np.zeros(y.shape) + u = np.zeros((n_targets, n_eval)) - MSE = self.sigma2 * (1. - (rt ** 2.).sum(axis=0) - + (u ** 2.).sum(axis=0)) + MSE = np.dot(self.sigma2.reshape(n_targets, 1), + (1. - (rt ** 2.).sum(axis=0) + + (u ** 2.).sum(axis=0))[np.newaxis, :]) + MSE = np.sqrt((MSE ** 2.).sum(axis=0) / n_targets) # Mean Squared Error might be slightly negative depending on # machine precision: force to zero! MSE[MSE < 0.] = 0. + if self.y_ndim_ == 1: + MSE = MSE.ravel() + return y, MSE else: @@ -562,6 +569,7 @@ def reduced_likelihood_function(self, theta=None): G QR decomposition of the matrix Ft. """ + check_is_fitted(self, "X") if theta is None: # Use built-in autocorrelation parameters @@ -580,8 +588,8 @@ def reduced_likelihood_function(self, theta=None): if D is None: # Light storage mode (need to recompute D, ij and F) D, ij = l1_cross_distances(self.X) - if np.min(np.sum(D, axis=1)) == 0. \ - and self.corr != correlation.pure_nugget: + if (np.min(np.sum(D, axis=1)) == 0. + and self.corr != correlation.pure_nugget): raise Exception("Multiple X are not allowed") F = self.regr(self.X) @@ -598,7 +606,7 @@ def reduced_likelihood_function(self, theta=None): return reduced_likelihood_function_value, par # Get generalized least squares solution - Ft = solve_triangular(C, F, lower=True) + Ft = linalg.solve_triangular(C, F, lower=True) try: Q, G = linalg.qr(Ft, econ=True) except: @@ -617,15 +625,15 @@ def reduced_likelihood_function(self, theta=None): condF = sv[0] / sv[-1] if condF > 1e15: raise Exception("F is too ill conditioned. Poor combination " - + "of regression model and observations.") + "of regression model and observations.") else: # Ft is too ill conditioned, get out (try different theta) return reduced_likelihood_function_value, par - Yt = solve_triangular(C, self.y, lower=True) + Yt = linalg.solve_triangular(C, self.y, lower=True) if self.beta0 is None: # Universal Kriging - beta = solve_triangular(G, np.dot(Q.T, Yt)) + beta = linalg.solve_triangular(G, np.dot(Q.T, Yt)) else: # Ordinary Kriging beta = np.array(self.beta0) @@ -640,31 +648,13 @@ def reduced_likelihood_function(self, theta=None): reduced_likelihood_function_value = - sigma2.sum() * detR par['sigma2'] = sigma2 * self.y_std ** 2. par['beta'] = beta - par['gamma'] = solve_triangular(C.T, rho) + par['gamma'] = linalg.solve_triangular(C.T, rho) par['C'] = C par['Ft'] = Ft par['G'] = G return reduced_likelihood_function_value, par - @deprecated("to be removed in 0.14, access ``self.theta_`` etc. directly " - " after fit.") - def arg_max_reduced_likelihood_function(self): - return self._arg_max_reduced_likelihood_function() - - @property - @deprecated('``theta`` is deprecated and will be removed in 0.14, ' - 'please use ``theta_`` instead.') - def theta(self): - return self.theta_ - - @property - @deprecated("``reduced_likelihood_function_value`` is deprecated and will" - "be removed in 0.14, please use " - "``reduced_likelihood_function_value_`` instead.") - def reduced_likelihood_function_value(self): - return self.reduced_likelihood_function_value_ - def _arg_max_reduced_likelihood_function(self): """ This function estimates the autocorrelation parameters theta as the @@ -695,9 +685,9 @@ def _arg_max_reduced_likelihood_function(self): best_optimal_par = [] if self.verbose: - print "The chosen optimizer is: " + str(self.optimizer) + print("The chosen optimizer is: " + str(self.optimizer)) if self.random_start > 1: - print str(self.random_start) + " random starts are required." + print(str(self.random_start) + " random starts are required.") percent_completed = 0. @@ -708,15 +698,15 @@ def _arg_max_reduced_likelihood_function(self): if self.optimizer == 'fmin_cobyla': def minus_reduced_likelihood_function(log10t): - return - self.reduced_likelihood_function(theta=10. - ** log10t)[0] + return - self.reduced_likelihood_function( + theta=10. ** log10t)[0] constraints = [] for i in range(self.theta0.size): - constraints.append(lambda log10t: \ - log10t[i] - np.log10(self.thetaL[0, i])) - constraints.append(lambda log10t: \ - np.log10(self.thetaU[0, i]) - log10t[i]) + constraints.append(lambda log10t, i=i: + log10t[i] - np.log10(self.thetaL[0, i])) + constraints.append(lambda log10t, i=i: + np.log10(self.thetaU[0, i]) - log10t[i]) for k in range(self.random_start): @@ -727,23 +717,24 @@ def minus_reduced_likelihood_function(log10t): # Generate a random starting point log10-uniformly # distributed between bounds log10theta0 = np.log10(self.thetaL) \ - + rand(self.theta0.size).reshape(self.theta0.shape) \ - * np.log10(self.thetaU / self.thetaL) + + self.random_state.rand(self.theta0.size).reshape( + self.theta0.shape) * np.log10(self.thetaU + / self.thetaL) theta0 = 10. ** log10theta0 # Run Cobyla try: log10_optimal_theta = \ optimize.fmin_cobyla(minus_reduced_likelihood_function, - np.log10(theta0), constraints, iprint=0) + np.log10(theta0), constraints, + iprint=0) except ValueError as ve: print("Optimization failed. Try increasing the ``nugget``") raise ve optimal_theta = 10. ** log10_optimal_theta - optimal_minus_rlf_value, optimal_par = \ + optimal_rlf_value, optimal_par = \ self.reduced_likelihood_function(theta=optimal_theta) - optimal_rlf_value = - optimal_minus_rlf_value # Compare the new optimizer to the best previous one if k > 0: @@ -758,7 +749,7 @@ def minus_reduced_likelihood_function(log10t): if self.verbose and self.random_start > 1: if (20 * k) / self.random_start > percent_completed: percent_completed = (20 * k) / self.random_start - print "%s completed" % (5 * percent_completed) + print("%s completed" % (5 * percent_completed)) optimal_rlf_value = best_optimal_rlf_value optimal_par = best_optimal_par @@ -778,9 +769,9 @@ def minus_reduced_likelihood_function(log10t): # Initialize under isotropy assumption if verbose: print("Initialize under isotropy assumption...") - self.theta0 = array2d(self.theta0.min()) - self.thetaL = array2d(self.thetaL.min()) - self.thetaU = array2d(self.thetaU.max()) + self.theta0 = check_array(self.theta0.min()) + self.thetaL = check_array(self.thetaL.min()) + self.thetaU = check_array(self.thetaU.max()) theta_iso, optimal_rlf_value_iso, par_iso = \ self._arg_max_reduced_likelihood_function() optimal_theta = theta_iso + np.zeros(theta0.shape) @@ -790,16 +781,17 @@ def minus_reduced_likelihood_function(log10t): print("Now improving allowing for anisotropy...") for i in self.random_state.permutation(theta0.size): if verbose: - print "Proceeding along dimension %d..." % (i + 1) - self.theta0 = array2d(theta_iso) - self.thetaL = array2d(thetaL[0, i]) - self.thetaU = array2d(thetaU[0, i]) + print("Proceeding along dimension %d..." % (i + 1)) + self.theta0 = check_array(theta_iso) + self.thetaL = check_array(thetaL[0, i]) + self.thetaU = check_array(thetaU[0, i]) def corr_cut(t, d): - return corr(array2d(np.hstack([ - optimal_theta[0][0:i], - t[0], - optimal_theta[0][(i + 1)::]])), d) + return corr(check_array(np.hstack([optimal_theta[0][0:i], + t[0], + optimal_theta[0][(i + + 1)::]])), + d) self.corr = corr_cut optimal_theta[0, i], optimal_rlf_value, optimal_par = \ @@ -813,9 +805,9 @@ def corr_cut(t, d): else: - raise NotImplementedError(("This optimizer ('%s') is not " - + "implemented yet. Please contribute!") - % self.optimizer) + raise NotImplementedError("This optimizer ('%s') is not " + "implemented yet. Please contribute!" + % self.optimizer) return optimal_theta, optimal_rlf_value, optimal_par @@ -826,13 +818,13 @@ def _check_params(self, n_samples=None): if self.regr in self._regression_types: self.regr = self._regression_types[self.regr] else: - raise ValueError(("regr should be one of %s or callable, " - + "%s was given.") - % (self._regression_types.keys(), self.regr)) + raise ValueError("regr should be one of %s or callable, " + "%s was given." + % (self._regression_types.keys(), self.regr)) # Check regression weights if given (Ordinary Kriging) if self.beta0 is not None: - self.beta0 = array2d(self.beta0) + self.beta0 = check_array(self.beta0) if self.beta0.shape[1] != 1: # Force to column vector self.beta0 = self.beta0.T @@ -842,28 +834,28 @@ def _check_params(self, n_samples=None): if self.corr in self._correlation_types: self.corr = self._correlation_types[self.corr] else: - raise ValueError(("corr should be one of %s or callable, " - + "%s was given.") - % (self._correlation_types.keys(), self.corr)) + raise ValueError("corr should be one of %s or callable, " + "%s was given." + % (self._correlation_types.keys(), self.corr)) # Check storage mode if self.storage_mode != 'full' and self.storage_mode != 'light': raise ValueError("Storage mode should either be 'full' or " - + "'light', %s was given." % self.storage_mode) + "'light', %s was given." % self.storage_mode) # Check correlation parameters - self.theta0 = array2d(self.theta0) + self.theta0 = check_array(self.theta0) lth = self.theta0.size if self.thetaL is not None and self.thetaU is not None: - self.thetaL = array2d(self.thetaL) - self.thetaU = array2d(self.thetaU) + self.thetaL = check_array(self.thetaL) + self.thetaU = check_array(self.thetaU) if self.thetaL.size != lth or self.thetaU.size != lth: raise ValueError("theta0, thetaL and thetaU must have the " - + "same length.") + "same length.") if np.any(self.thetaL <= 0) or np.any(self.thetaU < self.thetaL): raise ValueError("The bounds must satisfy O < thetaL <= " - + "thetaU.") + "thetaU.") elif self.thetaL is None and self.thetaU is None: if np.any(self.theta0 <= 0): @@ -871,7 +863,7 @@ def _check_params(self, n_samples=None): elif self.thetaL is None or self.thetaU is None: raise ValueError("thetaL and thetaU should either be both or " - + "neither specified.") + "neither specified.") # Force verbose type to bool self.verbose = bool(self.verbose) @@ -884,14 +876,14 @@ def _check_params(self, n_samples=None): if np.any(self.nugget) < 0.: raise ValueError("nugget must be positive or zero.") if (n_samples is not None - and self.nugget.shape not in [(), (n_samples,)]): + and self.nugget.shape not in [(), (n_samples,)]): raise ValueError("nugget must be either a scalar " "or array of length n_samples.") # Check optimizer - if not self.optimizer in self._optimizer_types: + if self.optimizer not in self._optimizer_types: raise ValueError("optimizer should be one of %s" - % self._optimizer_types) + % self._optimizer_types) # Force random_start type to int self.random_start = int(self.random_start) diff --git a/sklearn/gaussian_process/regression_models.py b/sklearn/gaussian_process/regression_models.py index df8bb301a09d1..ad240d8ee948d 100644 --- a/sklearn/gaussian_process/regression_models.py +++ b/sklearn/gaussian_process/regression_models.py @@ -1,9 +1,8 @@ -#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Vincent Dubourg # (mostly translation, see implementation details) -# License: BSD style +# Licence: BSD 3 clause """ The built-in regression models submodule for the gaussian_process module. diff --git a/sklearn/gaussian_process/tests/test_gaussian_process.py b/sklearn/gaussian_process/tests/test_gaussian_process.py index 293f2da14d599..a3c09f4664891 100644 --- a/sklearn/gaussian_process/tests/test_gaussian_process.py +++ b/sklearn/gaussian_process/tests/test_gaussian_process.py @@ -3,7 +3,7 @@ """ # Author: Vincent Dubourg -# License: BSD style +# Licence: BSD 3 clause from nose.tools import raises from nose.tools import assert_true @@ -13,6 +13,14 @@ from sklearn.gaussian_process import GaussianProcess from sklearn.gaussian_process import regression_models as regression from sklearn.gaussian_process import correlation_models as correlation +from sklearn.datasets import make_regression +from sklearn.utils.testing import assert_greater + + +f = lambda x: x * np.sin(x) +X = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T +X2 = np.atleast_2d([2., 4., 5.5, 6.5, 7.5]).T +y = f(X).ravel() def test_1d(regr=regression.constant, corr=correlation.squared_exponential, @@ -23,15 +31,14 @@ def test_1d(regr=regression.constant, corr=correlation.squared_exponential, Test the interpolating property. """ - f = lambda x: x * np.sin(x) - X = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T - y = f(X).ravel() gp = GaussianProcess(regr=regr, corr=corr, beta0=beta0, theta0=1e-2, thetaL=1e-4, thetaU=1e-1, random_start=random_start, verbose=False).fit(X, y) y_pred, MSE = gp.predict(X, eval_MSE=True) + y2_pred, MSE2 = gp.predict(X2, eval_MSE=True) - assert_true(np.allclose(y_pred, y) and np.allclose(MSE, 0.)) + assert_true(np.allclose(y_pred, y) and np.allclose(MSE, 0.) + and np.allclose(MSE2, 0., atol=10)) def test_2d(regr=regression.constant, corr=correlation.squared_exponential, @@ -53,6 +60,42 @@ def test_2d(regr=regression.constant, corr=correlation.squared_exponential, [-2.87600388, 6.74310541], [5.21301203, 4.26386883]]) y = g(X).ravel() + + thetaL = [1e-4] * 2 + thetaU = [1e-1] * 2 + gp = GaussianProcess(regr=regr, corr=corr, beta0=beta0, + theta0=[1e-2] * 2, thetaL=thetaL, + thetaU=thetaU, + random_start=random_start, verbose=False) + gp.fit(X, y) + y_pred, MSE = gp.predict(X, eval_MSE=True) + + assert_true(np.allclose(y_pred, y) and np.allclose(MSE, 0.)) + + assert_true(np.all(gp.theta_ >= thetaL)) # Lower bounds of hyperparameters + assert_true(np.all(gp.theta_ <= thetaU)) # Upper bounds of hyperparameters + + +def test_2d_2d(regr=regression.constant, corr=correlation.squared_exponential, + random_start=10, beta0=None): + """ + MLE estimation of a two-dimensional Gaussian Process model accounting for + anisotropy. Check random start optimization. + + Test the GP interpolation for 2D output + """ + b, kappa, e = 5., .5, .1 + g = lambda x: b - x[:, 1] - kappa * (x[:, 0] - e) ** 2. + f = lambda x: np.vstack((g(x), g(x))).T + X = np.array([[-4.61611719, -6.00099547], + [4.10469096, 5.32782448], + [0.00000000, -0.50000000], + [-6.17289014, -4.6984743], + [1.3109306, -6.93271427], + [-5.03823144, 3.10584743], + [-2.87600388, 6.74310541], + [5.21301203, 4.26386883]]) + y = f(X) gp = GaussianProcess(regr=regr, corr=corr, beta0=beta0, theta0=[1e-2] * 2, thetaL=[1e-4] * 2, thetaU=[1e-1] * 2, @@ -80,6 +123,7 @@ def test_more_builtin_correlation_models(random_start=1): for corr in all_corr: test_1d(regr='constant', corr=corr, random_start=random_start) test_2d(regr='constant', corr=corr, random_start=random_start) + test_2d_2d(regr='constant', corr=corr, random_start=random_start) def test_ordinary_kriging(): @@ -91,3 +135,50 @@ def test_ordinary_kriging(): test_1d(regr='quadratic', beta0=[0., 0.5, 0.5]) test_2d(regr='linear', beta0=[0., 0.5, 0.5]) test_2d(regr='quadratic', beta0=[0., 0.5, 0.5, 0.5, 0.5, 0.5]) + test_2d_2d(regr='linear', beta0=[0., 0.5, 0.5]) + test_2d_2d(regr='quadratic', beta0=[0., 0.5, 0.5, 0.5, 0.5, 0.5]) + + +def test_no_normalize(): + gp = GaussianProcess(normalize=False).fit(X, y) + y_pred = gp.predict(X) + assert_true(np.allclose(y_pred, y)) + + +def test_random_starts(): + """ + Test that an increasing number of random-starts of GP fitting only + increases the reduced likelihood function of the optimal theta. + """ + n_samples, n_features = 50, 3 + np.random.seed(0) + rng = np.random.RandomState(0) + X = rng.randn(n_samples, n_features) * 2 - 1 + y = np.sin(X).sum(axis=1) + np.sin(3 * X).sum(axis=1) + best_likelihood = -np.inf + for random_start in range(1, 5): + gp = GaussianProcess(regr="constant", corr="squared_exponential", + theta0=[1e-0] * n_features, + thetaL=[1e-4] * n_features, + thetaU=[1e+1] * n_features, + random_start=random_start, random_state=0, + verbose=False).fit(X, y) + rlf = gp.reduced_likelihood_function()[0] + assert_greater(rlf, best_likelihood - np.finfo(np.float32).eps) + best_likelihood = rlf + + +def test_mse_solving(): + # test the MSE estimate to be sane. + # non-regression test for ignoring off-diagonals of feature covariance, + # testing with nugget that renders covariance useless, only + # using the mean function, with low effective rank of data + gp = GaussianProcess(corr='absolute_exponential', theta0=1e-4, + thetaL=1e-12, thetaU=1e-2, nugget=1e-2, + optimizer='Welch', regr="linear", random_state=0) + + X, y = make_regression(n_informative=3, n_features=60, noise=50, + random_state=0, effective_rank=1) + + gp.fit(X, y) + assert_greater(1000, gp.predict(X, eval_MSE=True)[1].mean()) diff --git a/sklearn/grid_search.py b/sklearn/grid_search.py index d08277dcfefec..c0e428f4bc8d0 100644 --- a/sklearn/grid_search.py +++ b/sklearn/grid_search.py @@ -2,140 +2,268 @@ The :mod:`sklearn.grid_search` includes utilities to fine-tune the parameters of an estimator. """ +from __future__ import print_function # Author: Alexandre Gramfort , # Gael Varoquaux -# License: BSD Style. +# Andreas Mueller +# Olivier Grisel +# License: BSD 3 clause +from abc import ABCMeta, abstractmethod +from collections import Mapping, namedtuple, Sized +from functools import partial, reduce from itertools import product -import time +import operator +import warnings import numpy as np from .base import BaseEstimator, is_classifier, clone from .base import MetaEstimatorMixin -from .cross_validation import check_cv -from .externals.joblib import Parallel, delayed, logger -from .utils import check_arrays, safe_mask +from .cross_validation import _check_cv as check_cv +from .cross_validation import _fit_and_score +from .externals.joblib import Parallel, delayed +from .externals import six +from .utils import check_random_state +from .utils.random import sample_without_replacement +from .utils.validation import _num_samples, indexable +from .utils.metaestimators import if_delegate_has_method +from .metrics.scorer import check_scoring -__all__ = ['GridSearchCV', 'IterGrid', 'fit_grid_point'] +__all__ = ['GridSearchCV', 'ParameterGrid', 'fit_grid_point', + 'ParameterSampler', 'RandomizedSearchCV'] -class IterGrid(object): - """Generators on the combination of the various parameter lists given + +class ParameterGrid(object): + """Grid of parameters with a discrete number of values for each. + + Can be used to iterate over parameter value combinations with the + Python built-in function iter. Parameters ---------- - param_grid: dict of string to sequence + param_grid : dict of string to sequence, or sequence of such The parameter grid to explore, as a dictionary mapping estimator parameters to sequences of allowed values. - Returns - ------- - params: dict of string to any - **Yields** dictionaries mapping each estimator parameter to one of its - allowed values. + An empty dict signifies default parameters. + + A sequence of dicts signifies a sequence of grids to search, and is + useful to avoid exploring parameter combinations that make no sense + or have no effect. See the examples below. Examples -------- - >>> from sklearn.grid_search import IterGrid - >>> param_grid = {'a':[1, 2], 'b':[True, False]} - >>> list(IterGrid(param_grid)) #doctest: +NORMALIZE_WHITESPACE - [{'a': 1, 'b': True}, {'a': 1, 'b': False}, - {'a': 2, 'b': True}, {'a': 2, 'b': False}] + >>> from sklearn.grid_search import ParameterGrid + >>> param_grid = {'a': [1, 2], 'b': [True, False]} + >>> list(ParameterGrid(param_grid)) == ( + ... [{'a': 1, 'b': True}, {'a': 1, 'b': False}, + ... {'a': 2, 'b': True}, {'a': 2, 'b': False}]) + True + + >>> grid = [{'kernel': ['linear']}, {'kernel': ['rbf'], 'gamma': [1, 10]}] + >>> list(ParameterGrid(grid)) == [{'kernel': 'linear'}, + ... {'kernel': 'rbf', 'gamma': 1}, + ... {'kernel': 'rbf', 'gamma': 10}] + True See also -------- :class:`GridSearchCV`: - uses ``IterGrid`` to perform a full parallelized grid search. + uses ``ParameterGrid`` to perform a full parallelized parameter search. """ def __init__(self, param_grid): + if isinstance(param_grid, Mapping): + # wrap dictionary in a singleton list to support either dict + # or list of dicts + param_grid = [param_grid] self.param_grid = param_grid def __iter__(self): - param_grid = self.param_grid - if hasattr(param_grid, 'items'): - # wrap dictionary in a singleton list - param_grid = [param_grid] - for p in param_grid: + """Iterate over the points in the grid. + + Returns + ------- + params : iterator over dict of string to any + Yields dictionaries mapping each estimator parameter to one of its + allowed values. + """ + for p in self.param_grid: # Always sort the keys of a dictionary, for reproducibility items = sorted(p.items()) - keys, values = zip(*items) - for v in product(*values): - params = dict(zip(keys, v)) - yield params + if not items: + yield {} + else: + keys, values = zip(*items) + for v in product(*values): + params = dict(zip(keys, v)) + yield params + + def __len__(self): + """Number of points on the grid.""" + # Product function that can handle iterables (np.product can't). + product = partial(reduce, operator.mul) + return sum(product(len(v) for v in p.values()) if p else 1 + for p in self.param_grid) + + +class ParameterSampler(object): + """Generator on parameters sampled from given distributions. + + Non-deterministic iterable over random candidate combinations for hyper- + parameter search. If all parameters are presented as a list, + sampling without replacement is performed. If at least one parameter + is given as a distribution, sampling with replacement is used. + It is highly recommended to use continuous distributions for continuous + parameters. + + Note that as of SciPy 0.12, the ``scipy.stats.distributions`` do not accept + a custom RNG instance and always use the singleton RNG from + ``numpy.random``. Hence setting ``random_state`` will not guarantee a + deterministic iteration whenever ``scipy.stats`` distributions are used to + define the parameter search space. + + Parameters + ---------- + param_distributions : dict + Dictionary where the keys are parameters and values + are distributions from which a parameter is to be sampled. + Distributions either have to provide a ``rvs`` function + to sample from them, or can be given as a list of values, + where a uniform distribution is assumed. + n_iter : integer + Number of parameter settings that are produced. -def fit_grid_point(X, y, base_clf, clf_params, train, test, loss_func, - score_func, verbose, **fit_params): - """Run fit on one set of parameters + random_state : int or RandomState + Pseudo random number generator state used for random uniform sampling + from lists of possible values instead of scipy.stats distributions. - Returns the score and the instance of the classifier + Returns + ------- + params : dict of string to any + **Yields** dictionaries mapping each estimator parameter to + as sampled value. + + Examples + -------- + >>> from sklearn.grid_search import ParameterSampler + >>> from scipy.stats.distributions import expon + >>> import numpy as np + >>> np.random.seed(0) + >>> param_grid = {'a':[1, 2], 'b': expon()} + >>> param_list = list(ParameterSampler(param_grid, n_iter=4)) + >>> rounded_list = [dict((k, round(v, 6)) for (k, v) in d.items()) + ... for d in param_list] + >>> rounded_list == [{'b': 0.89856, 'a': 1}, + ... {'b': 0.923223, 'a': 1}, + ... {'b': 1.878964, 'a': 2}, + ... {'b': 1.038159, 'a': 2}] + True """ - if verbose > 1: - start_time = time.time() - msg = '%s' % (', '.join('%s=%s' % (k, v) - for k, v in clf_params.iteritems())) - print "[GridSearchCV] %s %s" % (msg, (64 - len(msg)) * '.') - - X, y = check_arrays(X, y, sparse_format="csr") - # update parameters of the classifier after a copy of its base structure - clf = clone(base_clf) - clf.set_params(**clf_params) - - if hasattr(base_clf, 'kernel') and hasattr(base_clf.kernel, '__call__'): - # cannot compute the kernel values with custom function - raise ValueError( - "Cannot use a custom kernel function. " - "Precompute the kernel matrix instead.") - - if getattr(base_clf, "_pairwise", False): - # X is a precomputed square kernel matrix - if X.shape[0] != X.shape[1]: - raise ValueError("X should be a square kernel matrix") - X_train = X[np.ix_(train, train)] - X_test = X[np.ix_(test, train)] - else: - X_train = X[safe_mask(X, train)] - X_test = X[safe_mask(X, test)] - - if y is not None: - y_test = y[safe_mask(y, test)] - y_train = y[safe_mask(y, train)] - else: - y_test = None - y_train = None - - clf.fit(X_train, y_train, **fit_params) - - if loss_func is not None: - y_pred = clf.predict(X_test) - this_score = -loss_func(y_test, y_pred) - elif score_func is not None: - y_pred = clf.predict(X_test) - this_score = score_func(y_test, y_pred) - else: - this_score = clf.score(X_test, y_test) - - if y is not None: - if hasattr(y, 'shape'): - this_n_test_samples = y.shape[0] - else: - this_n_test_samples = len(y) - else: - if hasattr(X, 'shape'): - this_n_test_samples = X.shape[0] + def __init__(self, param_distributions, n_iter, random_state=None): + self.param_distributions = param_distributions + self.n_iter = n_iter + self.random_state = random_state + + def __iter__(self): + samples = [] + # check if all distributions are given as lists + # in this case we want to sample without replacement + all_lists = np.all([not hasattr(v, "rvs") + for v in self.param_distributions.values()]) + rnd = check_random_state(self.random_state) + + if all_lists: + # get complete grid and yield from it + param_grid = list(ParameterGrid(self.param_distributions)) + grid_size = len(param_grid) + + if grid_size < self.n_iter: + raise ValueError( + "The total space of parameters %d is smaller " + "than n_iter=%d." % (grid_size, self.n_iter) + + " For exhaustive searches, use GridSearchCV.") + for i in sample_without_replacement(grid_size, self.n_iter, + random_state=rnd): + yield param_grid[i] + else: - this_n_test_samples = len(X) - if verbose > 2: - msg += ", score=%f" % this_score - if verbose > 1: - end_msg = "%s -%s" % (msg, - logger.short_format_time(time.time() - - start_time)) - print "[GridSearchCV] %s %s" % ((64 - len(end_msg)) * '.', end_msg) - return this_score, clf_params, this_n_test_samples + # Always sort the keys of a dictionary, for reproducibility + items = sorted(self.param_distributions.items()) + while len(samples) < self.n_iter: + params = dict() + for k, v in items: + if hasattr(v, "rvs"): + params[k] = v.rvs() + else: + params[k] = v[rnd.randint(len(v))] + samples.append(params) + yield params + + def __len__(self): + """Number of points that will be sampled.""" + return self.n_iter + + +def fit_grid_point(X, y, estimator, parameters, train, test, scorer, + verbose, error_score='raise', **fit_params): + """Run fit on one set of parameters. + + Parameters + ---------- + X : array-like, sparse matrix or list + Input data. + + y : array-like or None + Targets for input data. + + estimator : estimator object + This estimator will be cloned and then fitted. + + parameters : dict + Parameters to be set on estimator for this grid point. + + train : ndarray, dtype int or bool + Boolean mask or indices for training set. + + test : ndarray, dtype int or bool + Boolean mask or indices for test set. + + scorer : callable or None. + If provided must be a scorer callable object / function with signature + ``scorer(estimator, X, y)``. + + verbose : int + Verbosity level. + + **fit_params : kwargs + Additional parameter passed to the fit function of the estimator. + + error_score : 'raise' (default) or numeric + Value to assign to the score if an error occurs in estimator fitting. + If set to 'raise', the error is raised. If a numeric value is given, + FitFailedWarning is raised. This parameter does not affect the refit + step, which will always raise the error. + + Returns + ------- + score : float + Score of this parameter setting on given training / test split. + + parameters : dict + The parameters that have been evaluated. + + n_samples_test : int + Number of test samples in this split. + """ + score, n_samples_test, _ = _fit_and_score(estimator, X, y, scorer, train, + test, verbose, parameters, + fit_params, error_score) + return score, parameters, n_samples_test def _check_param_grid(param_grid): @@ -143,33 +271,292 @@ def _check_param_grid(param_grid): param_grid = [param_grid] for p in param_grid: - for v in p.itervalues(): + for v in p.values(): if isinstance(v, np.ndarray) and v.ndim > 1: raise ValueError("Parameter array should be one-dimensional.") check = [isinstance(v, k) for k in (list, tuple, np.ndarray)] - if not True in check: + if True not in check: raise ValueError("Parameter values should be a list.") if len(v) == 0: raise ValueError("Parameter values should be a non-empty " - "list.") + "list.") + + +class _CVScoreTuple (namedtuple('_CVScoreTuple', + ('parameters', + 'mean_validation_score', + 'cv_validation_scores'))): + # A raw namedtuple is very memory efficient as it packs the attributes + # in a struct to get rid of the __dict__ of attributes in particular it + # does not copy the string for the keys on each instance. + # By deriving a namedtuple class just to introduce the __repr__ method we + # would also reintroduce the __dict__ on the instance. By telling the + # Python interpreter that this subclass uses static __slots__ instead of + # dynamic attributes. Furthermore we don't need any additional slot in the + # subclass so we set __slots__ to the empty tuple. + __slots__ = () + + def __repr__(self): + """Simple custom repr to summarize the main info""" + return "mean: {0:.5f}, std: {1:.5f}, params: {2}".format( + self.mean_validation_score, + np.std(self.cv_validation_scores), + self.parameters) + + +class ChangedBehaviorWarning(UserWarning): + pass + + +class BaseSearchCV(six.with_metaclass(ABCMeta, BaseEstimator, + MetaEstimatorMixin)): + """Base class for hyper parameter search with cross-validation.""" + + @abstractmethod + def __init__(self, estimator, scoring=None, + fit_params=None, n_jobs=1, iid=True, + refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', + error_score='raise'): + + self.scoring = scoring + self.estimator = estimator + self.n_jobs = n_jobs + self.fit_params = fit_params if fit_params is not None else {} + self.iid = iid + self.refit = refit + self.cv = cv + self.verbose = verbose + self.pre_dispatch = pre_dispatch + self.error_score = error_score + def score(self, X, y=None): + """Returns the score on the given data, if the estimator has been refit -def _has_one_grid_point(param_grid): - if hasattr(param_grid, 'items'): - param_grid = [param_grid] + This uses the score defined by ``scoring`` where provided, and the + ``best_estimator_.score`` method otherwise. - for p in param_grid: - for v in p.itervalues(): - if len(v) > 1: - return False + Parameters + ---------- + X : array-like, shape = [n_samples, n_features] + Input data, where n_samples is the number of samples and + n_features is the number of features. + + y : array-like, shape = [n_samples] or [n_samples, n_output], optional + Target relative to X for classification or regression; + None for unsupervised learning. + + Returns + ------- + score : float + + Notes + ----- + * The long-standing behavior of this method changed in version 0.16. + * It no longer uses the metric provided by ``estimator.score`` if the + ``scoring`` parameter was set when fitting. + + """ + if self.scorer_ is None: + raise ValueError("No score function explicitly defined, " + "and the estimator doesn't provide one %s" + % self.best_estimator_) + if self.scoring is not None and hasattr(self.best_estimator_, 'score'): + warnings.warn("The long-standing behavior to use the estimator's " + "score function in {0}.score has changed. The " + "scoring parameter is now used." + "".format(self.__class__.__name__), + ChangedBehaviorWarning) + return self.scorer_(self.best_estimator_, X, y) + + @if_delegate_has_method(delegate='estimator') + def predict(self, X): + """Call predict on the estimator with the best found parameters. + + Only available if ``refit=True`` and the underlying estimator supports + ``predict``. + + Parameters + ----------- + X : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + """ + return self.best_estimator_.predict(X) + + @if_delegate_has_method(delegate='estimator') + def predict_proba(self, X): + """Call predict_proba on the estimator with the best found parameters. + + Only available if ``refit=True`` and the underlying estimator supports + ``predict_proba``. + + Parameters + ----------- + X : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + """ + return self.best_estimator_.predict_proba(X) + + @if_delegate_has_method(delegate='estimator') + def predict_log_proba(self, X): + """Call predict_log_proba on the estimator with the best found parameters. + + Only available if ``refit=True`` and the underlying estimator supports + ``predict_log_proba``. + + Parameters + ----------- + X : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + """ + return self.best_estimator_.predict_log_proba(X) + + @if_delegate_has_method(delegate='estimator') + def decision_function(self, X): + """Call decision_function on the estimator with the best found parameters. + + Only available if ``refit=True`` and the underlying estimator supports + ``decision_function``. + + Parameters + ----------- + X : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + """ + return self.best_estimator_.decision_function(X) + + @if_delegate_has_method(delegate='estimator') + def transform(self, X): + """Call transform on the estimator with the best found parameters. + + Only available if the underlying estimator supports ``transform`` and + ``refit=True``. + + Parameters + ----------- + X : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + """ + return self.best_estimator_.transform(X) + + @if_delegate_has_method(delegate='estimator') + def inverse_transform(self, Xt): + """Call inverse_transform on the estimator with the best found parameters. + + Only available if the underlying estimator implements ``inverse_transform`` and + ``refit=True``. + + Parameters + ----------- + Xt : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + """ + return self.best_estimator_.transform(Xt) + + def _fit(self, X, y, parameter_iterable): + """Actual fitting, performing the search over parameters.""" + + estimator = self.estimator + cv = self.cv + self.scorer_ = check_scoring(self.estimator, scoring=self.scoring) + + n_samples = _num_samples(X) + X, y = indexable(X, y) + + if y is not None: + if len(y) != n_samples: + raise ValueError('Target variable (y) has a different number ' + 'of samples (%i) than data (X: %i samples)' + % (len(y), n_samples)) + cv = check_cv(cv, X, y, classifier=is_classifier(estimator)) + + if self.verbose > 0: + if isinstance(parameter_iterable, Sized): + n_candidates = len(parameter_iterable) + print("Fitting {0} folds for each of {1} candidates, totalling" + " {2} fits".format(len(cv), n_candidates, + n_candidates * len(cv))) + + base_estimator = clone(self.estimator) + + pre_dispatch = self.pre_dispatch + + out = Parallel( + n_jobs=self.n_jobs, verbose=self.verbose, + pre_dispatch=pre_dispatch + )( + delayed(_fit_and_score)(clone(base_estimator), X, y, self.scorer_, + train, test, self.verbose, parameters, + self.fit_params, return_parameters=True, + error_score=self.error_score) + for parameters in parameter_iterable + for train, test in cv) + + # Out is a list of triplet: score, estimator, n_test_samples + n_fits = len(out) + n_folds = len(cv) + + scores = list() + grid_scores = list() + for grid_start in range(0, n_fits, n_folds): + n_test_samples = 0 + score = 0 + all_scores = [] + for this_score, this_n_test_samples, _, parameters in \ + out[grid_start:grid_start + n_folds]: + all_scores.append(this_score) + if self.iid: + this_score *= this_n_test_samples + n_test_samples += this_n_test_samples + score += this_score + if self.iid: + score /= float(n_test_samples) + else: + score /= float(n_folds) + scores.append((score, parameters)) + # TODO: shall we also store the test_fold_sizes? + grid_scores.append(_CVScoreTuple( + parameters, + score, + np.array(all_scores))) + # Store the computed scores + self.grid_scores_ = grid_scores - return True + # Find the best parameters by comparing on the mean validation score: + # note that `sorted` is deterministic in the way it breaks ties + best = sorted(grid_scores, key=lambda x: x.mean_validation_score, + reverse=True)[0] + self.best_params_ = best.parameters + self.best_score_ = best.mean_validation_score + + if self.refit: + # fit the best estimator using the entire dataset + # clone first to work around broken estimators + best_estimator = clone(base_estimator).set_params( + **best.parameters) + if y is not None: + best_estimator.fit(X, y, **self.fit_params) + else: + best_estimator.fit(X, **self.fit_params) + self.best_estimator_ = best_estimator + return self -class GridSearchCV(BaseEstimator, MetaEstimatorMixin): - """Grid search on the parameters of a classifier +class GridSearchCV(BaseSearchCV): + """Exhaustive search over specified parameter values for an estimator. Important members are fit, predict. @@ -179,36 +566,34 @@ class GridSearchCV(BaseEstimator, MetaEstimatorMixin): Parameters ---------- - estimator: object type that implements the "fit" and "predict" methods + estimator : object type that implements the "fit" and "predict" methods A object of that type is instantiated for each grid point. - param_grid: dict + param_grid : dict or list of dictionaries Dictionary with parameters names (string) as keys and lists of - parameter settings to try as values. + parameter settings to try as values, or a list of such + dictionaries, in which case the grids spanned by each dictionary + in the list are explored. This enables searching over any sequence + of parameter settings. - loss_func: callable, optional - function that takes 2 arguments and compares them in - order to evaluate the performance of prediciton (small is good) - if None is passed, the score of the estimator is maximized - - score_func: callable, optional - A function that takes 2 arguments and compares them in - order to evaluate the performance of prediction (high is good). - If None is passed, the score of the estimator is maximized. + scoring : string, callable or None, optional, default: None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. fit_params : dict, optional - parameters to pass to the fit method + Parameters to pass to the fit method. - n_jobs: int, optional - number of jobs to run in parallel (default 1) + n_jobs : int, default 1 + Number of jobs to run in parallel. - pre_dispatch: int, or string, optional + pre_dispatch : int, or string, optional Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - - None, in which case all the jobs are immediatly + - None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs @@ -219,24 +604,31 @@ class GridSearchCV(BaseEstimator, MetaEstimatorMixin): - A string, giving an expression as a function of n_jobs, as in '2*n_jobs' - iid: boolean, optional + iid : boolean, default=True If True, the data is assumed to be identically distributed across the folds, and the loss minimized is the total loss per sample, and not the mean loss across the folds. - cv : integer or crossvalidation generator, optional - If an integer is passed, it is the number of fold (default 3). - Specific crossvalidation objects can be passed, see + cv : integer or cross-validation generator, default=3 + If an integer is passed, it is the number of folds. + Specific cross-validation objects can be passed, see sklearn.cross_validation module for the list of possible objects - refit: boolean - refit the best estimator with the entire dataset. + refit : boolean, default=True + Refit the best estimator with the entire dataset. If "False", it is impossible to make predictions using - this GridSearch instance after fitting. + this GridSearchCV instance after fitting. - verbose: integer + verbose : integer Controls the verbosity: the higher, the more messages. + error_score : 'raise' (default) or numeric + Value to assign to the score if an error occurs in estimator fitting. + If set to 'raise', the error is raised. If a numeric value is given, + FitFailedWarning is raised. This parameter does not affect the refit + step, which will always raise the error. + + Examples -------- >>> from sklearn import svm, grid_search, datasets @@ -246,48 +638,59 @@ class GridSearchCV(BaseEstimator, MetaEstimatorMixin): >>> clf = grid_search.GridSearchCV(svr, parameters) >>> clf.fit(iris.data, iris.target) ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS - GridSearchCV(cv=None, - estimator=SVC(C=1.0, cache_size=..., coef0=..., degree=..., - gamma=..., kernel='rbf', probability=False, - shrinking=True, tol=...), - fit_params={}, iid=True, loss_func=None, n_jobs=1, - param_grid=..., - ...) + GridSearchCV(cv=None, error_score=..., + estimator=SVC(C=1.0, cache_size=..., class_weight=..., coef0=..., + degree=..., gamma=..., kernel='rbf', max_iter=-1, + probability=False, random_state=None, shrinking=True, + tol=..., verbose=False), + fit_params={}, iid=..., n_jobs=1, + param_grid=..., pre_dispatch=..., refit=..., + scoring=..., verbose=...) + Attributes ---------- - `grid_scores_` : dict of any to float + grid_scores_ : list of named tuples Contains scores for all parameter combinations in param_grid. + Each entry corresponds to one parameter setting. + Each named tuple has the attributes: - `best_estimator_` : estimator - Estimator that was choosen by grid search, i.e. estimator + * ``parameters``, a dict of parameter settings + * ``mean_validation_score``, the mean score over the + cross-validation folds + * ``cv_validation_scores``, the list of scores for each fold + + best_estimator_ : estimator + Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) - on the left out data. + on the left out data. Not available if refit=False. - `best_score_` : float - score of best_estimator on the left out data. + best_score_ : float + Score of best_estimator on the left out data. - `best_params_` : dict + best_params_ : dict Parameter setting that gave the best results on the hold out data. + scorer_ : function + Scorer function used on the held out data to choose the best + parameters for the model. + Notes ------ The parameters selected are those that maximize the score of the left out - data, unless an explicit score_func is passed in which case it is used - instead. If a loss function loss_func is passed, it overrides the score - functions and is minimized. + data, unless an explicit score is passed in which case it is used instead. If `n_jobs` was set to a value higher than one, the data is copied for each point in the grid (and not `n_jobs` times). This is done for efficiency reasons if individual jobs take very little time, but may raise errors if the dataset is large and not enough memory is available. A workaround in this case is to set `pre_dispatch`. Then, the memory is copied only - `pre_dispatch` many times. A reasonable value for `pre_dispatch` is 2 * - `n_jobs`. + `pre_dispatch` many times. A reasonable value for `pre_dispatch` is `2 * + n_jobs`. See Also --------- - :class:`IterGrid`: + :class:`ParameterGrid`: generates all the combinations of a an hyperparameter grid. :func:`sklearn.cross_validation.train_test_split`: @@ -295,163 +698,201 @@ class GridSearchCV(BaseEstimator, MetaEstimatorMixin): for fitting a GridSearchCV instance and an evaluation set for its final evaluation. - """ + :func:`sklearn.metrics.make_scorer`: + Make a scorer from a performance metric or loss function. - def __init__(self, estimator, param_grid, loss_func=None, score_func=None, - fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, - verbose=0, pre_dispatch='2*n_jobs', - ): - if not hasattr(estimator, 'fit') or \ - not (hasattr(estimator, 'predict') or hasattr(estimator, 'score')): - raise TypeError("estimator should a be an estimator implementing" - " 'fit' and 'predict' or 'score' methods," - " %s (type %s) was passed" % - (estimator, type(estimator))) - if loss_func is None and score_func is None: - if not hasattr(estimator, 'score'): - raise TypeError( - "If no loss_func is specified, the estimator passed " - "should have a 'score' method. The estimator %s " - "does not." % estimator) + """ - _check_param_grid(param_grid) + def __init__(self, estimator, param_grid, scoring=None, loss_func=None, + score_func=None, fit_params=None, n_jobs=1, iid=True, + refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', + error_score='raise'): - self.estimator = estimator + super(GridSearchCV, self).__init__( + estimator, scoring, fit_params, n_jobs, iid, + refit, cv, verbose, pre_dispatch, error_score) self.param_grid = param_grid - self.loss_func = loss_func - self.score_func = score_func - self.n_jobs = n_jobs - self.fit_params = fit_params if fit_params is not None else {} - self.iid = iid - self.refit = refit - self.cv = cv - self.verbose = verbose - self.pre_dispatch = pre_dispatch - - def _set_methods(self): - if hasattr(self.best_estimator_, 'predict'): - self.predict = self.best_estimator_.predict - if hasattr(self.best_estimator_, 'predict_proba'): - self.predict_proba = self.best_estimator_.predict_proba - - def fit(self, X, y=None, **params): - """Run fit with all sets of parameters + _check_param_grid(param_grid) - Returns the best classifier + def fit(self, X, y=None): + """Run fit with all sets of parameters. Parameters ---------- - X: array, [n_samples, n_features] - Training vector, where n_samples in the number of samples and + X : array-like, shape = [n_samples, n_features] + Training vector, where n_samples is the number of samples and n_features is the number of features. - y: array-like, shape = [n_samples], optional - Target vector relative to X for classification; + y : array-like, shape = [n_samples] or [n_samples, n_output], optional + Target relative to X for classification or regression; None for unsupervised learning. """ - return self._fit(X, y) + return self._fit(X, y, ParameterGrid(self.param_grid)) - def _fit(self, X, y): - estimator = self.estimator - cv = self.cv - if hasattr(X, 'shape'): - n_samples = X.shape[0] - else: - # support list of unstructured objects on which feature - # extraction will be applied later in the tranformer chain - n_samples = len(X) - if y is not None: - if len(y) != n_samples: - raise ValueError('Target variable (y) has a different number ' - 'of samples (%i) than data (X: %i samples)' - % (len(y), n_samples)) - y = np.asarray(y) - cv = check_cv(cv, X, y, classifier=is_classifier(estimator)) +class RandomizedSearchCV(BaseSearchCV): + """Randomized search on hyper parameters. - grid = IterGrid(self.param_grid) - base_clf = clone(self.estimator) + RandomizedSearchCV implements a "fit" method and a "predict" method like + any classifier except that the parameters of the classifier + used to predict is optimized by cross-validation. - # Return early if there is only one grid point. - if _has_one_grid_point(self.param_grid): - params = next(iter(grid)) - base_clf.set_params(**params) - base_clf.fit(X, y) - self.best_estimator_ = base_clf - self._set_methods() - return self + In contrast to GridSearchCV, not all parameter values are tried out, but + rather a fixed number of parameter settings is sampled from the specified + distributions. The number of parameter settings that are tried is + given by n_iter. - pre_dispatch = self.pre_dispatch - out = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, - pre_dispatch=pre_dispatch)( - delayed(fit_grid_point)( - X, y, base_clf, clf_params, train, test, self.loss_func, - self.score_func, self.verbose, **self.fit_params) - for clf_params in grid for train, test in cv) + If all parameters are presented as a list, + sampling without replacement is performed. If at least one parameter + is given as a distribution, sampling with replacement is used. + It is highly recommended to use continuous distributions for continuous + parameters. - # Out is a list of triplet: score, estimator, n_test_samples - n_grid_points = len(list(grid)) - n_fits = len(out) - n_folds = n_fits // n_grid_points + Parameters + ---------- + estimator : object type that implements the "fit" and "predict" methods + A object of that type is instantiated for each parameter setting. - scores = list() - cv_scores = list() - for grid_start in range(0, n_fits, n_folds): - n_test_samples = 0 - score = 0 - these_points = list() - for this_score, clf_params, this_n_test_samples in \ - out[grid_start:grid_start + n_folds]: - these_points.append(this_score) - if self.iid: - this_score *= this_n_test_samples - score += this_score - n_test_samples += this_n_test_samples - if self.iid: - score /= float(n_test_samples) - scores.append((score, clf_params)) - cv_scores.append(these_points) + param_distributions : dict + Dictionary with parameters names (string) as keys and distributions + or lists of parameters to try. Distributions must provide a ``rvs`` + method for sampling (such as those from scipy.stats.distributions). + If a list is given, it is sampled uniformly. - cv_scores = np.asarray(cv_scores) + n_iter : int, default=10 + Number of parameter settings that are sampled. n_iter trades + off runtime vs quality of the solution. - # Note: we do not use max(out) to make ties deterministic even if - # comparison on estimator instances is not deterministic - best_score = -np.inf - for score, params in scores: - if score > best_score: - best_score = score - best_params = params + scoring : string, callable or None, optional, default: None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. - if best_score is None: - raise ValueError('Best score could not be found') - self.best_score_ = best_score - self.best_params_ = best_params + fit_params : dict, optional + Parameters to pass to the fit method. - if self.refit: - # fit the best estimator using the entire dataset - # clone first to work around broken estimators - best_estimator = clone(base_clf).set_params(**best_params) - best_estimator.fit(X, y, **self.fit_params) - self.best_estimator_ = best_estimator - self._set_methods() + n_jobs : int, default=1 + Number of jobs to run in parallel. - # Store the computed scores - # XXX: the name is too specific, it shouldn't have - # 'grid' in it. Also, we should be retrieving/storing variance - self.grid_scores_ = [ - (clf_params, score, all_scores) - for clf_params, (score, _), all_scores - in zip(grid, scores, cv_scores)] - return self + pre_dispatch : int, or string, optional + Controls the number of jobs that get dispatched during parallel + execution. Reducing this number can be useful to avoid an + explosion of memory consumption when more jobs get dispatched + than CPUs can process. This parameter can be: - def score(self, X, y=None): - if hasattr(self.best_estimator_, 'score'): - return self.best_estimator_.score(X, y) - if self.score_func is None: - raise ValueError("No score function explicitly defined, " - "and the estimator doesn't provide one %s" - % self.best_estimator_) - y_predicted = self.predict(X) - return self.score_func(y, y_predicted) + - None, in which case all the jobs are immediately + created and spawned. Use this for lightweight and + fast-running jobs, to avoid delays due to on-demand + spawning of the jobs + + - An int, giving the exact number of total jobs that are + spawned + + - A string, giving an expression as a function of n_jobs, + as in '2*n_jobs' + + iid : boolean, default=True + If True, the data is assumed to be identically distributed across + the folds, and the loss minimized is the total loss per sample, + and not the mean loss across the folds. + + cv : integer or cross-validation generator, optional + If an integer is passed, it is the number of folds (default 3). + Specific cross-validation objects can be passed, see + sklearn.cross_validation module for the list of possible objects + + refit : boolean, default=True + Refit the best estimator with the entire dataset. + If "False", it is impossible to make predictions using + this RandomizedSearchCV instance after fitting. + + verbose : integer + Controls the verbosity: the higher, the more messages. + + error_score : 'raise' (default) or numeric + Value to assign to the score if an error occurs in estimator fitting. + If set to 'raise', the error is raised. If a numeric value is given, + FitFailedWarning is raised. This parameter does not affect the refit + step, which will always raise the error. + + + Attributes + ---------- + grid_scores_ : list of named tuples + Contains scores for all parameter combinations in param_grid. + Each entry corresponds to one parameter setting. + Each named tuple has the attributes: + + * ``parameters``, a dict of parameter settings + * ``mean_validation_score``, the mean score over the + cross-validation folds + * ``cv_validation_scores``, the list of scores for each fold + + best_estimator_ : estimator + Estimator that was chosen by the search, i.e. estimator + which gave highest score (or smallest loss if specified) + on the left out data. Not available if refit=False. + + best_score_ : float + Score of best_estimator on the left out data. + + best_params_ : dict + Parameter setting that gave the best results on the hold out data. + + Notes + ----- + The parameters selected are those that maximize the score of the held-out + data, according to the scoring parameter. + + If `n_jobs` was set to a value higher than one, the data is copied for each + parameter setting(and not `n_jobs` times). This is done for efficiency + reasons if individual jobs take very little time, but may raise errors if + the dataset is large and not enough memory is available. A workaround in + this case is to set `pre_dispatch`. Then, the memory is copied only + `pre_dispatch` many times. A reasonable value for `pre_dispatch` is `2 * + n_jobs`. + + See Also + -------- + :class:`GridSearchCV`: + Does exhaustive search over a grid of parameters. + + :class:`ParameterSampler`: + A generator over parameter settins, constructed from + param_distributions. + + """ + + def __init__(self, estimator, param_distributions, n_iter=10, scoring=None, + fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, + verbose=0, pre_dispatch='2*n_jobs', random_state=None, + error_score='raise'): + + self.param_distributions = param_distributions + self.n_iter = n_iter + self.random_state = random_state + super(RandomizedSearchCV, self).__init__( + estimator=estimator, scoring=scoring, fit_params=fit_params, + n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose, + pre_dispatch=pre_dispatch, error_score=error_score) + + def fit(self, X, y=None): + """Run fit on the estimator with randomly drawn parameters. + + Parameters + ---------- + X : array-like, shape = [n_samples, n_features] + Training vector, where n_samples in the number of samples and + n_features is the number of features. + + y : array-like, shape = [n_samples] or [n_samples, n_output], optional + Target relative to X for classification or regression; + None for unsupervised learning. + + """ + sampled_params = ParameterSampler(self.param_distributions, + self.n_iter, + random_state=self.random_state) + return self._fit(X, y, sampled_params) diff --git a/sklearn/hmm.py b/sklearn/hmm.py index de27fc7f85ea7..c05d3ef616054 100644 --- a/sklearn/hmm.py +++ b/sklearn/hmm.py @@ -8,17 +8,19 @@ The :mod:`sklearn.hmm` module implements hidden Markov models. **Warning:** :mod:`sklearn.hmm` is orphaned, undocumented and has known -numerical stability issues. If nobody volunteers to write documentation and -make it more stable, this module will be removed in version 0.11. +numerical stability issues. This module will be removed in version 0.17. + +It has been moved to a separate repository: +https://github.com/hmmlearn/hmmlearn """ import string -import warnings import numpy as np -from .utils import check_random_state +from .utils import check_random_state, deprecated from .utils.extmath import logsumexp +from .utils.validation import check_is_fitted from .base import BaseEstimator from .mixture import ( GMM, log_multivariate_normal_density, sample_gaussian, @@ -38,9 +40,16 @@ decoder_algorithms = ("viterbi", "map") +@deprecated("WARNING: The HMM module and its functions will be removed in 0.17 " + "as it no longer falls within the project's scope and API. " + "It has been moved to a separate repository: " + "https://github.com/hmmlearn/hmmlearn") def normalize(A, axis=None): """ Normalize the input array so that it sums to 1. + WARNING: The HMM module and its functions will be removed in 0.17 + as it no longer falls within the project's scope and API. + Parameters ---------- A: array, shape (n_samples, n_features) @@ -66,6 +75,10 @@ def normalize(A, axis=None): return A / Asum +@deprecated("WARNING: The HMM module and its function will be removed in 0.17" + "as it no longer falls within the project's scope and API. " + "It has been moved to a separate repository: " + "https://github.com/hmmlearn/hmmlearn") class _BaseHMM(BaseEstimator): """Hidden Markov Model base class. @@ -76,6 +89,11 @@ class _BaseHMM(BaseEstimator): See the instance documentation for details specific to a particular object. + .. warning:: + + The HMM module and its functions will be removed in 0.17 + as it no longer falls within the project's scope and API. + Attributes ---------- n_components : int @@ -108,14 +126,16 @@ class _BaseHMM(BaseEstimator): params : string, optional Controls which parameters are updated in the training process. Can contain any combination of 's' for startprob, - 't' for transmat, 'm' for means, and 'c' for covars, etc. - Defaults to all parameters. + 't' for transmat, and other characters for subclass-specific + emmission parameters. Defaults to all parameters. + init_params : string, optional Controls which parameters are initialized prior to training. Can contain any combination of 's' for - startprob, 't' for transmat, 'm' for means, and 'c' for - covars, etc. Defaults to all parameters. + startprob, 't' for transmat, and other characters for + subclass-specific emmission parameters. Defaults to all + parameters. See Also -------- @@ -131,7 +151,7 @@ class _BaseHMM(BaseEstimator): # which depend on the specific emission distribution. # # Subclasses will probably also want to implement properties for - # the emission distribution parameters to expose them publically. + # the emission distribution parameters to expose them publicly. def __init__(self, n_components=1, startprob=None, transmat=None, startprob_prior=None, transmat_prior=None, @@ -151,23 +171,24 @@ def __init__(self, n_components=1, startprob=None, transmat=None, self._algorithm = algorithm self.random_state = random_state - def eval(self, obs): - """Compute the log probability under the model and compute posteriors + def eval(self, X): + return self.score_samples(X) - Implements rank and beam pruning in the forward-backward - algorithm to speed up inference in large models. + def score_samples(self, obs): + """Compute the log probability under the model and compute posteriors. Parameters ---------- obs : array_like, shape (n, n_features) - Sequence of n_features-dimensional data points. Each row + Sequence of n_features-dimensional data points. Each row corresponds to a single point in the sequence. Returns ------- logprob : float - Log likelihood of the sequence `obs` - posteriors: array_like, shape (n, n_components) + Log likelihood of the sequence ``obs``. + + posteriors : array_like, shape (n, n_components) Posterior probabilities of each state for each observation @@ -202,11 +223,13 @@ def score(self, obs): Returns ------- logprob : float - Log likelihood of the `obs` + Log likelihood of the ``obs``. See Also -------- - eval : Compute the log probability under the model and posteriors + score_samples : Compute the log probability under the model and + posteriors + decode : Find most likely state sequence corresponding to a `obs` """ obs = np.asarray(obs) @@ -215,26 +238,29 @@ def score(self, obs): return logprob def _decode_viterbi(self, obs): - """Find most likely state sequence corresponding to `obs`. + """Find most likely state sequence corresponding to ``obs``. Uses the Viterbi algorithm. Parameters ---------- obs : array_like, shape (n, n_features) - List of n_features-dimensional data points. Each row - corresponds to a single data point. + Sequence of n_features-dimensional data points. Each row + corresponds to a single point in the sequence. Returns ------- viterbi_logprob : float - Log probability of the maximum likelihood path through the HMM + Log probability of the maximum likelihood path through the HMM. + state_sequence : array_like, shape (n,) - Index of the most likely states for each observation + Index of the most likely states for each observation. See Also -------- - eval : Compute the log probability under the model and posteriors + score_samples : Compute the log probability under the model and + posteriors. + score : Compute the log probability under the model """ obs = np.asarray(obs) @@ -250,8 +276,8 @@ def _decode_map(self, obs): Parameters ---------- obs : array_like, shape (n, n_features) - List of n_features-dimensional data points. Each row - corresponds to a single data point. + Sequence of n_features-dimensional data points. Each row + corresponds to a single point in the sequence. Returns ------- @@ -262,23 +288,24 @@ def _decode_map(self, obs): See Also -------- - eval : Compute the log probability under the model and posteriors - score : Compute the log probability under the model + score_samples : Compute the log probability under the model and + posteriors. + score : Compute the log probability under the model. """ - _, posteriors = self.eval(obs) + _, posteriors = self.score_samples(obs) state_sequence = np.argmax(posteriors, axis=1) map_logprob = np.max(posteriors, axis=1).sum() return map_logprob, state_sequence def decode(self, obs, algorithm="viterbi"): - """Find most likely state sequence corresponding to `obs`. + """Find most likely state sequence corresponding to ``obs``. Uses the selected algorithm for decoding. Parameters ---------- obs : array_like, shape (n, n_features) - List of n_features-dimensional data points. Each row - corresponds to a single data point. + Sequence of n_features-dimensional data points. Each row + corresponds to a single point in the sequence. algorithm : string, one of the `decoder_algorithms` decoder algorithm to be used @@ -287,13 +314,16 @@ def decode(self, obs, algorithm="viterbi"): ------- logprob : float Log probability of the maximum likelihood path through the HMM + state_sequence : array_like, shape (n,) Index of the most likely states for each observation See Also -------- - eval : Compute the log probability under the model and posteriors - score : Compute the log probability under the model + score_samples : Compute the log probability under the model and + posteriors. + + score : Compute the log probability under the model. """ if self._algorithm in decoder_algorithms: algorithm = self._algorithm @@ -310,8 +340,8 @@ def predict(self, obs, algorithm="viterbi"): Parameters ---------- obs : array_like, shape (n, n_features) - List of n_features-dimensional data points. Each row - corresponds to a single data point. + Sequence of n_features-dimensional data points. Each row + corresponds to a single point in the sequence. Returns ------- @@ -327,15 +357,15 @@ def predict_proba(self, obs): Parameters ---------- obs : array_like, shape (n, n_features) - List of n_features-dimensional data points. Each row - corresponds to a single data point. + Sequence of n_features-dimensional data points. Each row + corresponds to a single point in the sequence. Returns ------- T : array-like, shape (n, n_components) Returns the probability of the sample for each state in the model. """ - _, posteriors = self.eval(obs) + _, posteriors = self.score_samples(obs) return posteriors def sample(self, n=1, random_state=None): @@ -370,67 +400,48 @@ def sample(self, n=1, random_state=None): currstate = (startprob_cdf > rand).argmax() hidden_states = [currstate] obs = [self._generate_sample_from_state( - currstate, random_state=random_state)] + currstate, random_state=random_state)] - for _ in xrange(n - 1): + for _ in range(n - 1): rand = random_state.rand() currstate = (transmat_cdf[currstate] > rand).argmax() hidden_states.append(currstate) obs.append(self._generate_sample_from_state( - currstate, random_state=random_state)) + currstate, random_state=random_state)) return np.array(obs), np.array(hidden_states, dtype=int) - def fit(self, obs, **kwargs): + def fit(self, obs): """Estimate model parameters. An initialization step is performed before entering the EM - algorithm. If you want to avoid this step, set the keyword - argument init_params to the empty string ''. Likewise, if you - would like just to do an initialization, call this method with - n_iter=0. + algorithm. If you want to avoid this step, pass proper + ``init_params`` keyword argument to estimator's constructor. Parameters ---------- obs : list - List of array-like observation sequences (shape (n_i, n_features)). + List of array-like observation sequences, each of which + has shape (n_i, n_features), where n_i is the length of + the i_th observation. Notes ----- In general, `logprob` should be non-decreasing unless aggressive pruning is used. Decreasing `logprob` is generally a sign of overfitting (e.g. a covariance parameter getting too - small). You can fix this by getting more training data, or - decreasing `covars_prior`. - - **Please note that setting parameters in the `fit` method is - deprecated and will be removed in the next release. - Set it on initialization instead.** + small). You can fix this by getting more training data, + or strengthening the appropriate subclass-specific regularization + parameter. """ - if kwargs: - warnings.warn("Setting parameters in the 'fit' method is" - "deprecated and will be removed in 0.14. Set it on " - "initialization instead.", DeprecationWarning, - stacklevel=2) - # initialisations for in case the user still adds parameters to fit - # so things don't break - if 'n_iter' in kwargs: - self.n_iter = kwargs['n_iter'] - if 'thresh' in kwargs: - self.thresh = kwargs['thresh'] - if 'params' in kwargs: - self.params = kwargs['params'] - if 'init_params' in kwargs: - self.init_params = kwargs['init_params'] - if self.algorithm not in decoder_algorithms: self._algorithm = "viterbi" self._init(obs, self.init_params) logprob = [] - for i in xrange(self.n_iter): + for i in range(self.n_iter): # Expectation step stats = self._initialize_sufficient_statistics() curr_logprob = 0 @@ -473,6 +484,13 @@ def _get_startprob(self): def _set_startprob(self, startprob): if startprob is None: startprob = np.tile(1.0 / self.n_components, self.n_components) + else: + startprob = np.asarray(startprob, dtype=np.float) + + # check if there exists a component whose value is exactly zero + # if so, add a small number and re-normalize + if not np.alltrue(startprob): + normalize(startprob) if len(startprob) != self.n_components: raise ValueError('startprob must have length n_components') @@ -490,12 +508,17 @@ def _get_transmat(self): def _set_transmat(self, transmat): if transmat is None: transmat = np.tile(1.0 / self.n_components, - (self.n_components, self.n_components)) + (self.n_components, self.n_components)) + + # check if there exists a component whose value is exactly zero + # if so, add a small number and re-normalize + if not np.alltrue(transmat): + normalize(transmat, axis=1) if (np.asarray(transmat).shape != (self.n_components, self.n_components)): - raise ValueError('transmat must have shape ' + - '(n_components, n_components)') + raise ValueError('transmat must have shape ' + '(n_components, n_components)') if not np.all(np.allclose(np.sum(transmat, axis=1), 1.0)): raise ValueError('Rows of transmat must sum to 1.0') @@ -508,8 +531,8 @@ def _set_transmat(self, transmat): def _do_viterbi_pass(self, framelogprob): n_observations, n_components = framelogprob.shape state_sequence, logprob = _hmmc._viterbi( - n_observations, n_components, self._log_startprob, - self._log_transmat, framelogprob) + n_observations, n_components, self._log_startprob, + self._log_transmat, framelogprob) return logprob, state_sequence def _do_forward_pass(self, framelogprob): @@ -517,16 +540,15 @@ def _do_forward_pass(self, framelogprob): n_observations, n_components = framelogprob.shape fwdlattice = np.zeros((n_observations, n_components)) _hmmc._forward(n_observations, n_components, self._log_startprob, - self._log_transmat, framelogprob, fwdlattice) + self._log_transmat, framelogprob, fwdlattice) fwdlattice[fwdlattice <= ZEROLOGPROB] = NEGINF return logsumexp(fwdlattice[-1]), fwdlattice def _do_backward_pass(self, framelogprob): n_observations, n_components = framelogprob.shape bwdlattice = np.zeros((n_observations, n_components)) - _hmmc._backward(n_observations, n_components, - self._log_startprob, self._log_transmat, - framelogprob, bwdlattice) + _hmmc._backward(n_observations, n_components, self._log_startprob, + self._log_transmat, framelogprob, bwdlattice) bwdlattice[bwdlattice <= ZEROLOGPROB] = NEGINF @@ -559,21 +581,16 @@ def _accumulate_sufficient_statistics(self, stats, seq, framelogprob, if 's' in params: stats['start'] += posteriors[0] if 't' in params: - if _hmmc: - n_observations, n_components = framelogprob.shape - lneta = np.zeros((n_observations - 1, - n_components, n_components)) + n_observations, n_components = framelogprob.shape + # when the sample is of length 1, it contains no transitions + # so there is no reason to update our trans. matrix estimate + if n_observations > 1: + lneta = np.zeros((n_observations - 1, n_components, n_components)) lnP = logsumexp(fwdlattice[-1]) - _hmmc._compute_lneta(n_observations, n_components, - fwdlattice, self._log_transmat, bwdlattice, - framelogprob, lnP, lneta) - stats["trans"] += np.exp(logsumexp(lneta, 0)) - else: - for t in xrange(len(framelogprob)): - zeta = (fwdlattice[t - 1][:, np.newaxis] - + self._log_transmat + framelogprob[t] - + bwdlattice[t]) - stats['trans'] += np.exp(zeta - logsumexp(zeta)) + _hmmc._compute_lneta(n_observations, n_components, fwdlattice, + self._log_transmat, bwdlattice, framelogprob, + lnP, lneta) + stats['trans'] += np.exp(np.minimum(logsumexp(lneta, 0), 700)) def _do_mstep(self, stats, params): # Based on Huang, Acero, Hon, "Spoken Language Processing", @@ -587,9 +604,10 @@ def _do_mstep(self, stats, params): self.startprob_ = normalize( np.maximum(self.startprob_prior - 1.0 + stats['start'], 1e-20)) if 't' in params: - self.transmat_ = normalize( + transmat_ = normalize( np.maximum(self.transmat_prior - 1.0 + stats['trans'], 1e-20), axis=1) + self.transmat_ = transmat_ class GaussianHMM(_BaseHMM): @@ -599,6 +617,11 @@ class GaussianHMM(_BaseHMM): This class allows for easy evaluation of, sampling from, and maximum-likelihood estimation of the parameters of a HMM. + .. warning:: + + The HMM module and its functions will be removed in 0.17 + as it no longer falls within the project's scope and API. + Parameters ---------- n_components : int @@ -651,14 +674,14 @@ class GaussianHMM(_BaseHMM): params : string, optional Controls which parameters are updated in the training process. Can contain any combination of 's' for startprob, - 't' for transmat, 'm' for means, and 'c' for covars, etc. + 't' for transmat, 'm' for means, and 'c' for covars. Defaults to all parameters. init_params : string, optional Controls which parameters are initialized prior to training. Can contain any combination of 's' for startprob, 't' for transmat, 'm' for means, and 'c' for - covars, etc. Defaults to all parameters. + covars. Defaults to all parameters. Examples @@ -682,14 +705,11 @@ def __init__(self, n_components=1, covariance_type='diag', startprob=None, params=string.ascii_letters, init_params=string.ascii_letters): _BaseHMM.__init__(self, n_components, startprob, transmat, - startprob_prior=startprob_prior, - transmat_prior=transmat_prior, - algorithm=algorithm, - random_state=random_state, - n_iter=n_iter, - thresh=thresh, - params=params, - init_params=init_params) + startprob_prior=startprob_prior, + transmat_prior=transmat_prior, algorithm=algorithm, + random_state=random_state, n_iter=n_iter, + thresh=thresh, params=params, + init_params=init_params) self._covariance_type = covariance_type if not covariance_type in ['spherical', 'tied', 'diag', 'full']: @@ -701,7 +721,6 @@ def __init__(self, n_components=1, covariance_type='diag', startprob=None, self.covars_prior = covars_prior self.covars_weight = covars_weight - # Read-only properties. @property def covariance_type(self): """Covariance type of the model. @@ -716,10 +735,10 @@ def _get_means(self): def _set_means(self, means): means = np.asarray(means) - if hasattr(self, 'n_features') and \ - means.shape != (self.n_components, self.n_features): - raise ValueError('means must have shape' + - '(n_components, n_features)') + if (hasattr(self, 'n_features') + and means.shape != (self.n_components, self.n_features)): + raise ValueError('means must have shape ' + '(n_components, n_features)') self._means_ = means.copy() self.n_features = self._means_.shape[1] @@ -744,6 +763,8 @@ def _set_covars(self, covars): covars_ = property(_get_covars, _set_covars) def _compute_log_likelihood(self, obs): + check_is_fitted(self, '_means_') + return log_multivariate_normal_density( obs, self._means_, self._covars_, self._covariance_type) @@ -759,7 +780,7 @@ def _init(self, obs, params='stmc'): super(GaussianHMM, self)._init(obs, params=params) if (hasattr(self, 'n_features') - and self.n_features != obs[0].shape[1]): + and self.n_features != obs[0].shape[1]): raise ValueError('Unexpected number of dimensions, got %s but ' 'expected %s' % (obs[0].shape[1], self.n_features)) @@ -775,6 +796,7 @@ def _init(self, obs, params='stmc'): cv.shape = (1, 1) self._covars_ = distribute_covar_matrix_to_match_covariance_type( cv, self._covariance_type, self.n_components) + self._covars_[self._covars_ == 0] = 1e-5 def _initialize_sufficient_statistics(self): stats = super(GaussianHMM, self)._initialize_sufficient_statistics() @@ -802,7 +824,7 @@ def _accumulate_sufficient_statistics(self, stats, obs, framelogprob, elif self._covariance_type in ('tied', 'full'): for t, o in enumerate(obs): obsobsT = np.outer(o, o) - for c in xrange(self.n_components): + for c in range(self.n_components): stats['obs*obs.T'][c] += posteriors[t, c] * obsobsT def _do_mstep(self, stats, params): @@ -839,14 +861,15 @@ def _do_mstep(self, stats, params): - 2 * self._means_ * stats['obs'] + self._means_ ** 2 * denom) cv_den = max(covars_weight - 1, 0) + denom - self._covars_ = (covars_prior + cv_num) / cv_den + self._covars_ = (covars_prior + cv_num) / np.maximum(cv_den, 1e-5) if self._covariance_type == 'spherical': - self._covars_ = np.tile(self._covars_.mean(1) - [:, np.newaxis], (1, self._covars_.shape[1])) + self._covars_ = np.tile( + self._covars_.mean(1)[:, np.newaxis], + (1, self._covars_.shape[1])) elif self._covariance_type in ('tied', 'full'): cvnum = np.empty((self.n_components, self.n_features, self.n_features)) - for c in xrange(self.n_components): + for c in range(self.n_components): obsmean = np.outer(stats['obs'][c], self._means_[c]) cvnum[c] = (means_weight * np.outer(meandiff[c], @@ -857,16 +880,44 @@ def _do_mstep(self, stats, params): * stats['post'][c]) cvweight = max(covars_weight - self.n_features, 0) if self._covariance_type == 'tied': - self._covars_ = ((covars_prior + cvnum.sum(axis=0)) - / (cvweight + stats['post'].sum())) + self._covars_ = ((covars_prior + cvnum.sum(axis=0)) / + (cvweight + stats['post'].sum())) elif self._covariance_type == 'full': - self._covars_ = ((covars_prior + cvnum) - / (cvweight + stats['post'][:, None, None])) + self._covars_ = ((covars_prior + cvnum) / + (cvweight + stats['post'][:, None, None])) + def fit(self, obs): + """Estimate model parameters. + + An initialization step is performed before entering the EM + algorithm. If you want to avoid this step, pass proper + ``init_params`` keyword argument to estimator's constructor. + + Parameters + ---------- + obs : list + List of array-like observation sequences, each of which + has shape (n_i, n_features), where n_i is the length of + the i_th observation. + + Notes + ----- + In general, `logprob` should be non-decreasing unless + aggressive pruning is used. Decreasing `logprob` is generally + a sign of overfitting (e.g. the covariance parameter on one or + more components becomminging too small). You can fix this by getting + more training data, or increasing covars_prior. + """ + return super(GaussianHMM, self).fit(obs) class MultinomialHMM(_BaseHMM): """Hidden Markov Model with multinomial (discrete) emissions + .. warning:: + + The HMM module and its functions will be removed in 0.17 + as it no longer falls within the project's scope and API. + Attributes ---------- n_components : int @@ -896,14 +947,14 @@ class MultinomialHMM(_BaseHMM): params : string, optional Controls which parameters are updated in the training process. Can contain any combination of 's' for startprob, - 't' for transmat, 'm' for means, and 'c' for covars, etc. + 't' for transmat, 'e' for emmissionprob. Defaults to all parameters. init_params : string, optional Controls which parameters are initialized prior to training. Can contain any combination of 's' for - startprob, 't' for transmat, 'm' for means, and 'c' for - covars, etc. Defaults to all parameters. + startprob, 't' for transmat, 'e' for emmissionprob. + Defaults to all parameters. Examples -------- @@ -946,10 +997,15 @@ def _get_emissionprob(self): def _set_emissionprob(self, emissionprob): emissionprob = np.asarray(emissionprob) if hasattr(self, 'n_symbols') and \ - emissionprob.shape != (self.n_components, self.n_symbols): + emissionprob.shape != (self.n_components, self.n_symbols): raise ValueError('emissionprob must have shape ' '(n_components, n_symbols)') + # check if there exists a component whose value is exactly zero + # if so, add a small number and re-normalize + if not np.alltrue(emissionprob): + normalize(emissionprob) + self._log_emissionprob = np.log(emissionprob) underflow_idx = np.isnan(self._log_emissionprob) self._log_emissionprob[underflow_idx] = NEGINF @@ -958,6 +1014,7 @@ def _set_emissionprob(self, emissionprob): emissionprob_ = property(_get_emissionprob, _set_emissionprob) def _compute_log_likelihood(self, obs): + check_is_fitted(self, 'emissionprob_') return self._log_emissionprob[:, obs].T def _generate_sample_from_state(self, state, random_state=None): @@ -972,8 +1029,13 @@ def _init(self, obs, params='ste'): self.random_state = check_random_state(self.random_state) if 'e' in params: + if not hasattr(self, 'n_symbols'): + symbols = set() + for o in obs: + symbols = symbols.union(set(o)) + self.n_symbols = len(symbols) emissionprob = normalize(self.random_state.rand(self.n_components, - self.n_symbols), 1) + self.n_symbols), 1) self.emissionprob_ = emissionprob def _initialize_sufficient_statistics(self): @@ -995,24 +1057,68 @@ def _do_mstep(self, stats, params): super(MultinomialHMM, self)._do_mstep(stats, params) if 'e' in params: self.emissionprob_ = (stats['obs'] - / stats['obs'].sum(1)[:, np.newaxis]) + / stats['obs'].sum(1)[:, np.newaxis]) + + def _check_input_symbols(self, obs): + """check if input can be used for Multinomial.fit input must be both + positive integer array and every element must be continuous. + e.g. x = [0, 0, 2, 1, 3, 1, 1] is OK and y = [0, 0, 3, 5, 10] not + """ + + symbols = np.asarray(obs).flatten() + + if symbols.dtype.kind != 'i': + # input symbols must be integer + return False + + if len(symbols) == 1: + # input too short + return False + + if np.any(symbols < 0): + # input contains negative intiger + return False + + symbols.sort() + if np.any(np.diff(symbols) > 1): + # input is discontinous + return False + + return True + + def fit(self, obs, **kwargs): + """Estimate model parameters. + + An initialization step is performed before entering the EM + algorithm. If you want to avoid this step, pass proper + ``init_params`` keyword argument to estimator's constructor. + + Parameters + ---------- + obs : list + List of array-like observation sequences, each of which + has shape (n_i, n_features), where n_i is the length of + the i_th observation. + """ + err_msg = ("Input must be both positive integer array and " + "every element must be continuous, but %s was given.") + + if not self._check_input_symbols(obs): + raise ValueError(err_msg % obs) + + return _BaseHMM.fit(self, obs, **kwargs) class GMMHMM(_BaseHMM): """Hidden Markov Model with Gaussin mixture emissions - Attributes - ---------- - init_params : string, optional - Controls which parameters are initialized prior to training. Can \ - contain any combination of 's' for startprob, 't' for transmat, 'm' \ - for means, and 'c' for covars, etc. Defaults to all parameters. + .. warning:: - params : string, optional - Controls which parameters are updated in the training process. Can - contain any combination of 's' for startprob, 't' for transmat,'m' for - means, and 'c' for covars, etc. Defaults to all parameters. + The HMM module and its functions will be removed in 0.17 + as it no longer falls within the project's scope and API. + Attributes + ---------- n_components : int Number of states in the model. @@ -1034,6 +1140,18 @@ class GMMHMM(_BaseHMM): thresh : float, optional Convergence threshold. + init_params : string, optional + Controls which parameters are initialized prior to training. + Can contain any combination of 's' for startprob, 't' for transmat, 'm' + for means, 'c' for covars, and 'w' for GMM mixing weights. Defaults to + all parameters. + + params : string, optional + Controls which parameters are updated in the training process. Can + contain any combination of 's' for startprob, 't' for transmat, + 'm' for means, and 'c' for covars, and 'w' for GMM mixing weights. + Defaults to all parameters. + Examples -------- >>> from sklearn.hmm import GMMHMM @@ -1074,15 +1192,16 @@ def __init__(self, n_components=1, n_mix=1, startprob=None, transmat=None, self.n_mix = n_mix self._covariance_type = covariance_type self.covars_prior = covars_prior + self.gmms = gmms if gmms is None: gmms = [] - for x in xrange(self.n_components): + for x in range(self.n_components): if covariance_type is None: g = GMM(n_mix) else: g = GMM(n_mix, covariance_type=covariance_type) gmms.append(g) - self.gmms = gmms + self.gmms_ = gmms # Read-only properties. @property @@ -1094,24 +1213,24 @@ def covariance_type(self): return self._covariance_type def _compute_log_likelihood(self, obs): - return np.array([g.score(obs) for g in self.gmms]).T + return np.array([g.score(obs) for g in self.gmms_]).T def _generate_sample_from_state(self, state, random_state=None): - return self.gmms[state].sample(1, random_state=random_state).flatten() + return self.gmms_[state].sample(1, random_state=random_state).flatten() def _init(self, obs, params='stwmc'): super(GMMHMM, self)._init(obs, params=params) allobs = np.concatenate(obs, 0) - for g in self.gmms: + for g in self.gmms_: g.set_params(init_params=params, n_iter=0) g.fit(allobs) def _initialize_sufficient_statistics(self): stats = super(GMMHMM, self)._initialize_sufficient_statistics() - stats['norm'] = [np.zeros(g.weights_.shape) for g in self.gmms] - stats['means'] = [np.zeros(np.shape(g.means_)) for g in self.gmms] - stats['covars'] = [np.zeros(np.shape(g.covars_)) for g in self.gmms] + stats['norm'] = [np.zeros(g.weights_.shape) for g in self.gmms_] + stats['means'] = [np.zeros(np.shape(g.means_)) for g in self.gmms_] + stats['covars'] = [np.zeros(np.shape(g.covars_)) for g in self.gmms_] return stats def _accumulate_sufficient_statistics(self, stats, obs, framelogprob, @@ -1121,8 +1240,8 @@ def _accumulate_sufficient_statistics(self, stats, obs, framelogprob, stats, obs, framelogprob, posteriors, fwdlattice, bwdlattice, params) - for state, g in enumerate(self.gmms): - _, lgmm_posteriors = g.eval(obs) + for state, g in enumerate(self.gmms_): + _, lgmm_posteriors = g.score_samples(obs) lgmm_posteriors += np.log(posteriors[:, state][:, np.newaxis] + np.finfo(np.float).eps) gmm_posteriors = np.exp(lgmm_posteriors) @@ -1154,7 +1273,7 @@ def _do_mstep(self, stats, params): super(GMMHMM, self)._do_mstep(stats, params) # All that is left to do is to apply covars_prior to the # parameters updated in _accumulate_sufficient_statistics. - for state, g in enumerate(self.gmms): + for state, g in enumerate(self.gmms_): n_features = g.means_.shape[1] norm = stats['norm'][state] if 'w' in params: @@ -1165,17 +1284,17 @@ def _do_mstep(self, stats, params): if g.covariance_type == 'tied': g.covars_ = ((stats['covars'][state] + self.covars_prior * np.eye(n_features)) - / norm.sum()) + / norm.sum()) else: cvnorm = np.copy(norm) shape = np.ones(g.covars_.ndim) shape[0] = np.shape(g.covars_)[0] cvnorm.shape = shape if (g.covariance_type in ['spherical', 'diag']): - g.covars_ = (stats['covars'][state] - + self.covars_prior) / cvnorm + g.covars_ = (stats['covars'][state] + + self.covars_prior) / cvnorm elif g.covariance_type == 'full': eye = np.eye(n_features) g.covars_ = ((stats['covars'][state] + self.covars_prior * eye[np.newaxis]) - / cvnorm) + / cvnorm) diff --git a/sklearn/isotonic.py b/sklearn/isotonic.py new file mode 100644 index 0000000000000..bb0a210efb5eb --- /dev/null +++ b/sklearn/isotonic.py @@ -0,0 +1,377 @@ +# Authors: Fabian Pedregosa +# Alexandre Gramfort +# Nelle Varoquaux +# License: BSD 3 clause + +import numpy as np +from scipy import interpolate +from scipy.stats import spearmanr +from .base import BaseEstimator, TransformerMixin, RegressorMixin +from .utils import as_float_array, check_array, check_consistent_length +from .utils.fixes import astype +from ._isotonic import _isotonic_regression, _make_unique +import warnings +import math + + +def check_increasing(x, y): + """Determine whether y is monotonically correlated with x. + + y is found increasing or decreasing with respect to x based on a Spearman + correlation test. + + Parameters + ---------- + x : array-like, shape=(n_samples,) + Training data. + + y : array-like, shape=(n_samples,) + Training target. + + Returns + ------- + `increasing_bool` : boolean + Whether the relationship is increasing or decreasing. + + Notes + ----- + The Spearman correlation coefficient is estimated from the data, and the + sign of the resulting estimate is used as the result. + + In the event that the 95% confidence interval based on Fisher transform + spans zero, a warning is raised. + + References + ---------- + Fisher transformation. Wikipedia. + http://en.wikipedia.org/w/index.php?title=Fisher_transformation + """ + + # Calculate Spearman rho estimate and set return accordingly. + rho, _ = spearmanr(x, y) + increasing_bool = rho >= 0 + + # Run Fisher transform to get the rho CI, but handle rho=+/-1 + if rho not in [-1.0, 1.0]: + F = 0.5 * math.log((1. + rho) / (1. - rho)) + F_se = 1 / math.sqrt(len(x) - 3) + + # Use a 95% CI, i.e., +/-1.96 S.E. + # http://en.wikipedia.org/wiki/Fisher_transformation + rho_0 = math.tanh(F - 1.96 * F_se) + rho_1 = math.tanh(F + 1.96 * F_se) + + # Warn if the CI spans zero. + if np.sign(rho_0) != np.sign(rho_1): + warnings.warn("Confidence interval of the Spearman " + "correlation coefficient spans zero. " + "Determination of ``increasing`` may be " + "suspect.") + + return increasing_bool + + +def isotonic_regression(y, sample_weight=None, y_min=None, y_max=None, + increasing=True): + """Solve the isotonic regression model:: + + min sum w[i] (y[i] - y_[i]) ** 2 + + subject to y_min = y_[1] <= y_[2] ... <= y_[n] = y_max + + where: + - y[i] are inputs (real numbers) + - y_[i] are fitted + - w[i] are optional strictly positive weights (default to 1.0) + + Parameters + ---------- + y : iterable of floating-point values + The data. + + sample_weight : iterable of floating-point values, optional, default: None + Weights on each point of the regression. + If None, weight is set to 1 (equal weights). + + y_min : optional, default: None + If not None, set the lowest value of the fit to y_min. + + y_max : optional, default: None + If not None, set the highest value of the fit to y_max. + + increasing : boolean, optional, default: True + Whether to compute ``y_`` is increasing (if set to True) or decreasing + (if set to False) + + Returns + ------- + y_ : list of floating-point values + Isotonic fit of y. + + References + ---------- + "Active set algorithms for isotonic regression; A unifying framework" + by Michael J. Best and Nilotpal Chakravarti, section 3. + """ + y = np.asarray(y, dtype=np.float) + if sample_weight is None: + sample_weight = np.ones(len(y), dtype=y.dtype) + else: + sample_weight = np.asarray(sample_weight, dtype=np.float) + if not increasing: + y = y[::-1] + sample_weight = sample_weight[::-1] + + if y_min is not None or y_max is not None: + y = np.copy(y) + sample_weight = np.copy(sample_weight) + # upper bound on the cost function + C = np.dot(sample_weight, y * y) * 10 + if y_min is not None: + y[0] = y_min + sample_weight[0] = C + if y_max is not None: + y[-1] = y_max + sample_weight[-1] = C + + solution = np.empty(len(y)) + y_ = _isotonic_regression(y, sample_weight, solution) + if increasing: + return y_ + else: + return y_[::-1] + + +class IsotonicRegression(BaseEstimator, TransformerMixin, RegressorMixin): + """Isotonic regression model. + + The isotonic regression optimization problem is defined by:: + + min sum w_i (y[i] - y_[i]) ** 2 + + subject to y_[i] <= y_[j] whenever X[i] <= X[j] + and min(y_) = y_min, max(y_) = y_max + + where: + - ``y[i]`` are inputs (real numbers) + - ``y_[i]`` are fitted + - ``X`` specifies the order. + If ``X`` is non-decreasing then ``y_`` is non-decreasing. + - ``w[i]`` are optional strictly positive weights (default to 1.0) + + Parameters + ---------- + y_min : optional, default: None + If not None, set the lowest value of the fit to y_min. + + y_max : optional, default: None + If not None, set the highest value of the fit to y_max. + + increasing : boolean or string, optional, default: True + If boolean, whether or not to fit the isotonic regression with y + increasing or decreasing. + + The string value "auto" determines whether y should + increase or decrease based on the Spearman correlation estimate's + sign. + + out_of_bounds : string, optional, default: "nan" + The ``out_of_bounds`` parameter handles how x-values outside of the + training domain are handled. When set to "nan", predicted y-values + will be NaN. When set to "clip", predicted y-values will be + set to the value corresponding to the nearest train interval endpoint. + When set to "raise", allow ``interp1d`` to throw ValueError. + + + Attributes + ---------- + X_ : ndarray (n_samples, ) + A copy of the input X. + + y_ : ndarray (n_samples, ) + Isotonic fit of y. + + X_min_ : float + Minimum value of input array `X_` for left bound. + + X_max_ : float + Maximum value of input array `X_` for right bound. + + f_ : function + The stepwise interpolating function that covers the domain + X_. + + Notes + ----- + Ties are broken using the secondary method from Leeuw, 1977. + + References + ---------- + Isotonic Median Regression: A Linear Programming Approach + Nilotpal Chakravarti + Mathematics of Operations Research + Vol. 14, No. 2 (May, 1989), pp. 303-308 + + Isotone Optimization in R : Pool-Adjacent-Violators + Algorithm (PAVA) and Active Set Methods + Leeuw, Hornik, Mair + Journal of Statistical Software 2009 + + Correctness of Kruskal's algorithms for monotone regression with ties + Leeuw, Psychometrica, 1977 + """ + def __init__(self, y_min=None, y_max=None, increasing=True, + out_of_bounds='nan'): + self.y_min = y_min + self.y_max = y_max + self.increasing = increasing + self.out_of_bounds = out_of_bounds + + def _check_fit_data(self, X, y, sample_weight=None): + if len(X.shape) != 1: + raise ValueError("X should be a 1d array") + + def _build_f(self, X, y): + """Build the f_ interp1d function.""" + + # Handle the out_of_bounds argument by setting bounds_error + if self.out_of_bounds not in ["raise", "nan", "clip"]: + raise ValueError("The argument ``out_of_bounds`` must be in " + "'nan', 'clip', 'raise'; got {0}" + .format(self.out_of_bounds)) + + bounds_error = self.out_of_bounds == "raise" + if len(y) == 1: + # single y, constant prediction + self.f_ = lambda x: y.repeat(x.shape) + else: + self.f_ = interpolate.interp1d(X, y, kind='slinear', + bounds_error=bounds_error) + + def _build_y(self, X, y, sample_weight): + """Build the y_ IsotonicRegression.""" + check_consistent_length(X, y, sample_weight) + X, y = [check_array(x, ensure_2d=False) for x in [X, y]] + + y = as_float_array(y) + self._check_fit_data(X, y, sample_weight) + + # Determine increasing if auto-determination requested + if self.increasing == 'auto': + self.increasing_ = check_increasing(X, y) + else: + self.increasing_ = self.increasing + + # If sample_weights is passed, removed zero-weight values and clean order + if sample_weight is not None: + sample_weight = check_array(sample_weight, ensure_2d=False) + mask = sample_weight > 0 + X, y, sample_weight = X[mask], y[mask], sample_weight[mask] + else: + sample_weight = np.ones(len(y)) + + order = np.lexsort((y, X)) + order_inv = np.argsort(order) + X, y, sample_weight = [astype(array[order], np.float64, copy=False) + for array in [X, y, sample_weight]] + unique_X, unique_y, unique_sample_weight = _make_unique(X, y, sample_weight) + self.X_ = unique_X + self.y_ = isotonic_regression(unique_y, unique_sample_weight, self.y_min, + self.y_max, increasing=self.increasing_) + + return order_inv + + def fit(self, X, y, sample_weight=None): + """Fit the model using X, y as training data. + + Parameters + ---------- + X : array-like, shape=(n_samples,) + Training data. + + y : array-like, shape=(n_samples,) + Training target. + + sample_weight : array-like, shape=(n_samples,), optional, default: None + Weights. If set to None, all weights will be set to 1 (equal + weights). + + Returns + ------- + self : object + Returns an instance of self. + + Notes + ----- + X is stored for future use, as `transform` needs X to interpolate + new input data. + """ + # Build y_ + self._build_y(X, y, sample_weight) + + # Handle the left and right bounds on X + self.X_min_ = np.min(self.X_) + self.X_max_ = np.max(self.X_) + + # Build f_ + self._build_f(self.X_, self.y_) + + return self + + def transform(self, T): + """Transform new data by linear interpolation + + Parameters + ---------- + T : array-like, shape=(n_samples,) + Data to transform. + + Returns + ------- + T_ : array, shape=(n_samples,) + The transformed data + """ + T = as_float_array(T) + if len(T.shape) != 1: + raise ValueError("Isotonic regression input should be a 1d array") + + # Handle the out_of_bounds argument by clipping if needed + if self.out_of_bounds not in ["raise", "nan", "clip"]: + raise ValueError("The argument ``out_of_bounds`` must be in " + "'nan', 'clip', 'raise'; got {0}" + .format(self.out_of_bounds)) + + if self.out_of_bounds == "clip": + T = np.clip(T, self.X_min_, self.X_max_) + return self.f_(T) + + def predict(self, T): + """Predict new data by linear interpolation. + + Parameters + ---------- + T : array-like, shape=(n_samples,) + Data to transform. + + Returns + ------- + T_ : array, shape=(n_samples,) + Transformed data. + """ + return self.transform(T) + + def __getstate__(self): + """Pickle-protocol - return state of the estimator. """ + # copy __dict__ + state = dict(self.__dict__) + # remove interpolation method + state.pop('f_', None) + return state + + def __setstate__(self, state): + """Pickle-protocol - set state of the estimator. + + We need to rebuild the interpolation function. + """ + self.__dict__.update(state) + self._build_f(self.X_, self.y_) diff --git a/sklearn/kernel_approximation.py b/sklearn/kernel_approximation.py index 25833e6072418..dc29e7c3f805c 100644 --- a/sklearn/kernel_approximation.py +++ b/sklearn/kernel_approximation.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ The :mod:`sklearn.kernel_approximation` module implements several approximate kernel feature maps base on Fourier transforms. @@ -6,28 +5,35 @@ # Author: Andreas Mueller # -# License: BSD Style. +# License: BSD 3 clause + +import warnings import numpy as np import scipy.sparse as sp +from scipy.linalg import svd from .base import BaseEstimator from .base import TransformerMixin -from .utils import array2d, atleast2d_or_csr, check_random_state +from .utils import check_array, check_random_state, as_float_array from .utils.extmath import safe_sparse_dot +from .utils.validation import check_is_fitted +from .metrics.pairwise import pairwise_kernels class RBFSampler(BaseEstimator, TransformerMixin): """Approximates feature map of an RBF kernel by Monte Carlo approximation of its Fourier transform. + + It implements a variant of Random Kitchen Sinks.[1] Parameters ---------- - gamma: float - parameter of RBF kernel: exp(-gamma * x**2) + gamma : float + Parameter of RBF kernel: exp(-gamma * x^2) - n_components: int - number of Monte Carlo samples per original feature. + n_components : int + Number of Monte Carlo samples per original feature. Equals the dimensionality of the computed feature space. random_state : {int, RandomState}, optional @@ -38,9 +44,14 @@ class RBFSampler(BaseEstimator, TransformerMixin): ----- See "Random Features for Large-Scale Kernel Machines" by A. Rahimi and Benjamin Recht. + + [1] "Weighted Sums of Random Kitchen Sinks: Replacing + minimization with randomization in learning" by A. Rahimi and + Benjamin Recht. + (http://www.eecs.berkeley.edu/~brecht/papers/08.rah.rec.nips.pdf) """ - def __init__(self, gamma=1., n_components=100., random_state=None): + def __init__(self, gamma=1., n_components=100, random_state=None): self.gamma = gamma self.n_components = n_components self.random_state = random_state @@ -52,7 +63,7 @@ def fit(self, X, y=None): Parameters ---------- - X: {array-like, sparse matrix}, shape (n_samples, n_features) + X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data, where n_samples in the number of samples and n_features is the number of features. @@ -62,14 +73,15 @@ def fit(self, X, y=None): Returns the transformer. """ - X = atleast2d_or_csr(X) - self.random_state = check_random_state(self.random_state) + X = check_array(X, accept_sparse='csr') + random_state = check_random_state(self.random_state) n_features = X.shape[1] - self.random_weights_ = (np.sqrt(self.gamma) * - self.random_state.normal(size=(n_features, self.n_components))) - self.random_offset_ = self.random_state.uniform(0, - 2 * np.pi, size=self.n_components) + self.random_weights_ = (np.sqrt(2 * self.gamma) * random_state.normal( + size=(n_features, self.n_components))) + + self.random_offset_ = random_state.uniform(0, 2 * np.pi, + size=self.n_components) return self def transform(self, X, y=None): @@ -77,18 +89,22 @@ def transform(self, X, y=None): Parameters ---------- - X: {array-like, sparse matrix}, shape (n_samples, n_features) + X : {array-like, sparse matrix}, shape (n_samples, n_features) New data, where n_samples in the number of samples and n_features is the number of features. Returns ------- - X_new: array-like, shape (n_samples, n_components) + X_new : array-like, shape (n_samples, n_components) """ - X = atleast2d_or_csr(X) + check_is_fitted(self, 'random_weights_') + + X = check_array(X, accept_sparse='csr') projection = safe_sparse_dot(X, self.random_weights_) - return (np.sqrt(2.) / np.sqrt(self.n_components) - * np.cos(projection + self.random_offset_)) + projection += self.random_offset_ + np.cos(projection, projection) + projection *= np.sqrt(2.) / np.sqrt(self.n_components) + return projection class SkewedChi2Sampler(BaseEstimator, TransformerMixin): @@ -97,10 +113,10 @@ class SkewedChi2Sampler(BaseEstimator, TransformerMixin): Parameters ---------- - skewedness: float + skewedness : float "skewedness" parameter of the kernel. Needs to be cross-validated. - n_components: int + n_components : int number of Monte Carlo samples per original feature. Equals the dimensionality of the computed feature space. @@ -108,10 +124,17 @@ class SkewedChi2Sampler(BaseEstimator, TransformerMixin): If int, random_state is the seed used by the random number generator; if RandomState instance, random_state is the random number generator. - Notes - ----- + References + ---------- See "Random Fourier Approximations for Skewed Multiplicative Histogram Kernels" by Fuxin Li, Catalin Ionescu and Cristian Sminchisescu. + + See also + -------- + AdditiveChi2Sampler : A different approach for approximating an additive + variant of the chi squared kernel. + + sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel. """ def __init__(self, skewedness=1., n_components=100, random_state=None): @@ -126,7 +149,7 @@ def fit(self, X, y=None): Parameters ---------- - X: array-like, shape (n_samples, n_features) + X : array-like, shape (n_samples, n_features) Training data, where n_samples in the number of samples and n_features is the number of features. @@ -136,16 +159,15 @@ def fit(self, X, y=None): Returns the transformer. """ - X = array2d(X) - self.random_state = check_random_state(self.random_state) + X = check_array(X) + random_state = check_random_state(self.random_state) n_features = X.shape[1] - uniform = self.random_state.uniform(size=(n_features, - self.n_components)) + uniform = random_state.uniform(size=(n_features, self.n_components)) # transform by inverse CDF of sech self.random_weights_ = (1. / np.pi - * np.log(np.tan(np.pi / 2. * uniform))) - self.random_offset_ = self.random_state.uniform(0, - 2 * np.pi, size=self.n_components) + * np.log(np.tan(np.pi / 2. * uniform))) + self.random_offset_ = random_state.uniform(0, 2 * np.pi, + size=self.n_components) return self def transform(self, X, y=None): @@ -153,34 +175,39 @@ def transform(self, X, y=None): Parameters ---------- - X: array-like, shape (n_samples, n_features) + X : array-like, shape (n_samples, n_features) New data, where n_samples in the number of samples and n_features is the number of features. Returns ------- - X_new: array-like, shape (n_samples, n_components) + X_new : array-like, shape (n_samples, n_components) """ - X = array2d(X) + check_is_fitted(self, 'random_weights_') + + X = as_float_array(X, copy=True) + X = check_array(X, copy=False) if (X < 0).any(): raise ValueError("X may not contain entries smaller than zero.") - projection = safe_sparse_dot(np.log(X + self.skewedness), - self.random_weights_) - - return (np.sqrt(2.) / np.sqrt(self.n_components) - * np.cos(projection + self.random_offset_)) + X += self.skewedness + np.log(X, X) + projection = safe_sparse_dot(X, self.random_weights_) + projection += self.random_offset_ + np.cos(projection, projection) + projection *= np.sqrt(2.) / np.sqrt(self.n_components) + return projection class AdditiveChi2Sampler(BaseEstimator, TransformerMixin): - """Approximate feature map for additive chi² kernel. + """Approximate feature map for additive chi2 kernel. Uses sampling the fourier transform of the kernel characteristic at regular intervals. Since the kernel that is to be approximated is additive, the components of the input vectors can be treated separately. Each entry in the original - space is transformed into 2×sample_steps+1 features, where sample_steps is + space is transformed into 2*sample_steps+1 features, where sample_steps is a parameter of the method. Typical values of sample_steps include 1, 2 and 3. @@ -189,13 +216,28 @@ class AdditiveChi2Sampler(BaseEstimator, TransformerMixin): Parameters ---------- - sample_steps: int, optional + sample_steps : int, optional Gives the number of (complex) sampling points. - sample_interval: float, optional + sample_interval : float, optional Sampling interval. Must be specified when sample_steps not in {1,2,3}. Notes ----- + This estimator approximates a slightly different version of the additive + chi squared kernel then ``metric.additive_chi2`` computes. + + See also + -------- + SkewedChi2Sampler : A Fourier-approximation to a non-additive variant of + the chi squared kernel. + + sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel. + + sklearn.metrics.pairwise.additive_chi2_kernel : The exact additive chi + squared kernel. + + References + ---------- See `"Efficient additive kernels via explicit feature maps" `_ Vedaldi, A. and Zisserman, A., Computer Vision and Pattern Recognition 2010 @@ -208,17 +250,20 @@ def __init__(self, sample_steps=2, sample_interval=None): def fit(self, X, y=None): """Set parameters.""" - if self.sample_interval == None: + X = check_array(X, accept_sparse='csr') + if self.sample_interval is None: # See reference, figure 2 c) if self.sample_steps == 1: - self.sample_interval = 0.8 + self.sample_interval_ = 0.8 elif self.sample_steps == 2: - self.sample_interval = 0.5 + self.sample_interval_ = 0.5 elif self.sample_steps == 3: - self.sample_interval = 0.4 + self.sample_interval_ = 0.4 else: raise ValueError("If sample_steps is not in [1, 2, 3]," - " you need to provide sample_interval") + " you need to provide sample_interval") + else: + self.sample_interval_ = self.sample_interval return self def transform(self, X, y=None): @@ -226,17 +271,20 @@ def transform(self, X, y=None): Parameters ---------- - X: {array-like, sparse matrix}, shape = (n_samples, n_features) + X : {array-like, sparse matrix}, shape = (n_samples, n_features) Returns ------- - X_new: {array, sparse matrix}, \ - shape = (n_samples, n_features × (2×sample_steps + 1)) + X_new : {array, sparse matrix}, \ + shape = (n_samples, n_features * (2*sample_steps + 1)) Whether the return value is an array of sparse matrix depends on the type of the input X. """ + msg = ("%(name)s is not fitted. Call fit to set the parameters before" + " calling transform") + check_is_fitted(self, "sample_interval_", msg=msg) - X = atleast2d_or_csr(X) + X = check_array(X, accept_sparse='csr') sparse = sp.issparse(X) # check if X has negative values. Doesn't play well with np.log. @@ -254,16 +302,16 @@ def _transform_dense(self, X): X_nz = X[non_zero] X_step = np.zeros_like(X) - X_step[non_zero] = np.sqrt(X_nz * self.sample_interval) + X_step[non_zero] = np.sqrt(X_nz * self.sample_interval_) X_new = [X_step] - log_step_nz = self.sample_interval * np.log(X_nz) - step_nz = 2 * X_nz * self.sample_interval + log_step_nz = self.sample_interval_ * np.log(X_nz) + step_nz = 2 * X_nz * self.sample_interval_ - for j in xrange(1, self.sample_steps): + for j in range(1, self.sample_steps): factor_nz = np.sqrt(step_nz / - np.cosh(np.pi * j * self.sample_interval)) + np.cosh(np.pi * j * self.sample_interval_)) X_step = np.zeros_like(X) X_step[non_zero] = factor_nz * np.cos(j * log_step_nz) @@ -279,17 +327,17 @@ def _transform_sparse(self, X): indices = X.indices.copy() indptr = X.indptr.copy() - data_step = np.sqrt(X.data * self.sample_interval) + data_step = np.sqrt(X.data * self.sample_interval_) X_step = sp.csr_matrix((data_step, indices, indptr), shape=X.shape, dtype=X.dtype, copy=False) X_new = [X_step] - log_step_nz = self.sample_interval * np.log(X.data) - step_nz = 2 * X.data * self.sample_interval + log_step_nz = self.sample_interval_ * np.log(X.data) + step_nz = 2 * X.data * self.sample_interval_ - for j in xrange(1, self.sample_steps): + for j in range(1, self.sample_steps): factor_nz = np.sqrt(step_nz / - np.cosh(np.pi * j * self.sample_interval)) + np.cosh(np.pi * j * self.sample_interval_)) data_step = factor_nz * np.cos(j * log_step_nz) X_step = sp.csr_matrix((data_step, indices, indptr), @@ -302,3 +350,164 @@ def _transform_sparse(self, X): X_new.append(X_step) return sp.hstack(X_new) + + +class Nystroem(BaseEstimator, TransformerMixin): + """Approximate a kernel map using a subset of the training data. + + Constructs an approximate feature map for an arbitrary kernel + using a subset of the data as basis. + + Parameters + ---------- + kernel : string or callable, default="rbf" + Kernel map to be approximated. A callable should accept two arguments + and the keyword arguments passed to this object as kernel_params, and + should return a floating point number. + + n_components : int + Number of features to construct. + How many data points will be used to construct the mapping. + + gamma : float, default=None + Gamma parameter for the RBF, polynomial, exponential chi2 and + sigmoid kernels. Interpretation of the default value is left to + the kernel; see the documentation for sklearn.metrics.pairwise. + Ignored by other kernels. + + degree : float, default=3 + Degree of the polynomial kernel. Ignored by other kernels. + + coef0 : float, default=1 + Zero coefficient for polynomial and sigmoid kernels. + Ignored by other kernels. + + kernel_params : mapping of string to any, optional + Additional parameters (keyword arguments) for kernel function passed + as callable object. + + random_state : {int, RandomState}, optional + If int, random_state is the seed used by the random number generator; + if RandomState instance, random_state is the random number generator. + + + Attributes + ---------- + components_ : array, shape (n_components, n_features) + Subset of training points used to construct the feature map. + + component_indices_ : array, shape (n_components) + Indices of ``components_`` in the training set. + + normalization_ : array, shape (n_components, n_components) + Normalization matrix needed for embedding. + Square root of the kernel matrix on ``components_``. + + + References + ---------- + * Williams, C.K.I. and Seeger, M. + "Using the Nystroem method to speed up kernel machines", + Advances in neural information processing systems 2001 + + * T. Yang, Y. Li, M. Mahdavi, R. Jin and Z. Zhou + "Nystroem Method vs Random Fourier Features: A Theoretical and Empirical + Comparison", + Advances in Neural Information Processing Systems 2012 + + + See also + -------- + RBFSampler : An approximation to the RBF kernel using random Fourier + features. + + sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels. + """ + def __init__(self, kernel="rbf", gamma=None, coef0=1, degree=3, + kernel_params=None, n_components=100, random_state=None): + self.kernel = kernel + self.gamma = gamma + self.coef0 = coef0 + self.degree = degree + self.kernel_params = kernel_params + self.n_components = n_components + self.random_state = random_state + + def fit(self, X, y=None): + """Fit estimator to data. + + Samples a subset of training points, computes kernel + on these and computes normalization matrix. + + Parameters + ---------- + X : array-like, shape=(n_samples, n_feature) + Training data. + """ + X = check_array(X, accept_sparse='csr') + rnd = check_random_state(self.random_state) + n_samples = X.shape[0] + + # get basis vectors + if self.n_components > n_samples: + # XXX should we just bail? + n_components = n_samples + warnings.warn("n_components > n_samples. This is not possible.\n" + "n_components was set to n_samples, which results" + " in inefficient evaluation of the full kernel.") + + else: + n_components = self.n_components + n_components = min(n_samples, n_components) + inds = rnd.permutation(n_samples) + basis_inds = inds[:n_components] + basis = X[basis_inds] + + basis_kernel = pairwise_kernels(basis, metric=self.kernel, + filter_params=True, + **self._get_kernel_params()) + + # sqrt of kernel matrix on basis vectors + U, S, V = svd(basis_kernel) + S = np.maximum(S, 1e-12) + self.normalization_ = np.dot(U * 1. / np.sqrt(S), V) + self.components_ = basis + self.component_indices_ = inds + return self + + def transform(self, X): + """Apply feature map to X. + + Computes an approximate feature map using the kernel + between some training points and X. + + Parameters + ---------- + X : array-like, shape=(n_samples, n_features) + Data to transform. + + Returns + ------- + X_transformed : array, shape=(n_samples, n_components) + Transformed data. + """ + check_is_fitted(self, 'components_') + X = check_array(X, accept_sparse='csr') + + kernel_params = self._get_kernel_params() + embedded = pairwise_kernels(X, self.components_, + metric=self.kernel, + filter_params=True, + **kernel_params) + return np.dot(embedded, self.normalization_.T) + + def _get_kernel_params(self): + params = self.kernel_params + if params is None: + params = {} + if not callable(self.kernel): + params['gamma'] = self.gamma + params['degree'] = self.degree + params['coef0'] = self.coef0 + + return params diff --git a/sklearn/kernel_ridge.py b/sklearn/kernel_ridge.py new file mode 100644 index 0000000000000..9dccbc6841349 --- /dev/null +++ b/sklearn/kernel_ridge.py @@ -0,0 +1,181 @@ +"""Module :mod:`sklearn.kernel_ridge` implements kernel ridge regression.""" + +# Authors: Mathieu Blondel +# Jan Hendrik Metzen +# License: BSD 3 clause + +import numpy as np + +from .base import BaseEstimator, RegressorMixin +from .metrics.pairwise import pairwise_kernels +from .linear_model.ridge import _solve_cholesky_kernel +from .utils import check_X_y +from .utils.validation import check_is_fitted + + +class KernelRidge(BaseEstimator, RegressorMixin): + """Kernel ridge regression. + + Kernel ridge regression (KRR) combines ridge regression (linear least + squares with l2-norm regularization) with the kernel trick. It thus + learns a linear function in the space induced by the respective kernel and + the data. For non-linear kernels, this corresponds to a non-linear + function in the original space. + + The form of the model learned by KRR is identical to support vector + regression (SVR). However, different loss functions are used: KRR uses + squared error loss while support vector regression uses epsilon-insensitive + loss, both combined with l2 regularization. In contrast to SVR, fitting a + KRR model can be done in closed-form and is typically faster for + medium-sized datasets. On the other hand, the learned model is non-sparse + and thus slower than SVR, which learns a sparse model for epsilon > 0, at + prediction-time. + + This estimator has built-in support for multi-variate regression + (i.e., when y is a 2d-array of shape [n_samples, n_targets]). + + Parameters + ---------- + alpha : {float, array-like}, shape = [n_targets] + Small positive values of alpha improve the conditioning of the problem + and reduce the variance of the estimates. Alpha corresponds to + ``(2*C)^-1`` in other linear models such as LogisticRegression or + LinearSVC. If an array is passed, penalties are assumed to be specific + to the targets. Hence they must correspond in number. + + kernel : string or callable, default="linear" + Kernel mapping used internally. A callable should accept two arguments + and the keyword arguments passed to this object as kernel_params, and + should return a floating point number. + + gamma : float, default=None + Gamma parameter for the RBF, polynomial, exponential chi2 and + sigmoid kernels. Interpretation of the default value is left to + the kernel; see the documentation for sklearn.metrics.pairwise. + Ignored by other kernels. + + degree : float, default=3 + Degree of the polynomial kernel. Ignored by other kernels. + + coef0 : float, default=1 + Zero coefficient for polynomial and sigmoid kernels. + Ignored by other kernels. + + kernel_params : mapping of string to any, optional + Additional parameters (keyword arguments) for kernel function passed + as callable object. + + Attributes + ---------- + dual_coef_ : array, shape = [n_features] or [n_targets, n_features] + Weight vector(s) in kernel space + + X_fit_ : {array-like, sparse matrix}, shape = [n_samples, n_features] + Training data, which is also required for prediction + + References + ---------- + * Kevin P. Murphy + "Machine Learning: A Probabilistic Perspective", The MIT Press + chapter 14.4.3, pp. 492-493 + + See also + -------- + Ridge + Linear ridge regression. + SVR + Support Vector Regression implemented using libsvm. + + Examples + -------- + >>> from sklearn.kernel_ridge import KernelRidge + >>> import numpy as np + >>> n_samples, n_features = 10, 5 + >>> rng = np.random.RandomState(0) + >>> y = rng.randn(n_samples) + >>> X = rng.randn(n_samples, n_features) + >>> clf = KernelRidge(alpha=1.0) + >>> clf.fit(X, y) # doctest: +NORMALIZE_WHITESPACE + KernelRidge(alpha=1.0, coef0=1, degree=3, gamma=None, kernel='linear', + kernel_params=None) + """ + def __init__(self, alpha=1, kernel="linear", gamma=None, degree=3, coef0=1, + kernel_params=None): + self.alpha = alpha + self.kernel = kernel + self.gamma = gamma + self.degree = degree + self.coef0 = coef0 + self.kernel_params = kernel_params + + def _get_kernel(self, X, Y=None): + if callable(self.kernel): + params = self.kernel_params or {} + else: + params = {"gamma": self.gamma, + "degree": self.degree, + "coef0": self.coef0} + return pairwise_kernels(X, Y, metric=self.kernel, + filter_params=True, **params) + + @property + def _pairwise(self): + return self.kernel == "precomputed" + + def fit(self, X, y=None, sample_weight=None): + """Fit Kernel Ridge regression model + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Training data + + y : array-like, shape = [n_samples] or [n_samples, n_targets] + Target values + + sample_weight : float or numpy array of shape [n_samples] + Individual weights for each sample, ignored if None is passed. + + Returns + ------- + self : returns an instance of self. + """ + # Convert data + X, y = check_X_y(X, y, accept_sparse=("csr", "csc"), multi_output=True) + + n_samples = X.shape[0] + K = self._get_kernel(X) + alpha = np.atleast_1d(self.alpha) + + ravel = False + if len(y.shape) == 1: + y = y.reshape(-1, 1) + ravel = True + + copy = self.kernel == "precomputed" + self.dual_coef_ = _solve_cholesky_kernel(K, y, alpha, + sample_weight, + copy) + if ravel: + self.dual_coef_ = self.dual_coef_.ravel() + + self.X_fit_ = X + + return self + + def predict(self, X): + """Predict using the the kernel ridge model + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Samples. + + Returns + ------- + C : array, shape = [n_samples] or [n_samples, n_targets] + Returns predicted values. + """ + check_is_fitted(self, ["X_fit_", "dual_coef_"]) + K = self._get_kernel(X, self.X_fit_) + return np.dot(K, self.dual_coef_) diff --git a/sklearn/lda.py b/sklearn/lda.py index 2807862fd3b88..61a79fb934bbf 100644 --- a/sklearn/lda.py +++ b/sklearn/lda.py @@ -1,56 +1,215 @@ """ -The :mod:`sklearn.lda` module implements Linear Discriminant Analysis (LDA). +Linear Discriminant Analysis (LDA) """ -# Authors: Matthieu Perrot + +# Authors: Clemens Brunner +# Martin Billinger +# Matthieu Perrot # Mathieu Blondel +# License: BSD 3-Clause + +from __future__ import print_function import warnings import numpy as np from scipy import linalg +from .externals.six import string_types + +from .base import BaseEstimator, TransformerMixin +from .linear_model.base import LinearClassifierMixin +from .covariance import ledoit_wolf, empirical_covariance, shrunk_covariance +from .utils.multiclass import unique_labels +from .utils import check_array, check_X_y +from .utils.validation import check_is_fitted +from .utils.fixes import bincount +from .preprocessing import StandardScaler -from .base import BaseEstimator, ClassifierMixin, TransformerMixin -from .utils.extmath import logsumexp -from .utils.fixes import unique -from .utils import check_arrays __all__ = ['LDA'] -class LDA(BaseEstimator, ClassifierMixin, TransformerMixin): +def _cov(X, shrinkage=None): + """Estimate covariance matrix (using optional shrinkage). + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Input data. + + shrinkage : string or float, optional + Shrinkage parameter, possible values: + - None or 'empirical': no shrinkage (default). + - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. + - float between 0 and 1: fixed shrinkage parameter. + + Returns + ------- + s : array, shape (n_features, n_features) + Estimated covariance matrix. + """ + shrinkage = "empirical" if shrinkage is None else shrinkage + if isinstance(shrinkage, string_types): + if shrinkage == 'auto': + sc = StandardScaler() # standardize features + X = sc.fit_transform(X) + s = sc.std_ * ledoit_wolf(X)[0] * sc.std_ # scale back + elif shrinkage == 'empirical': + s = empirical_covariance(X) + else: + raise ValueError('unknown shrinkage parameter') + elif isinstance(shrinkage, float) or isinstance(shrinkage, int): + if shrinkage < 0 or shrinkage > 1: + raise ValueError('shrinkage parameter must be between 0 and 1') + s = shrunk_covariance(empirical_covariance(X), shrinkage) + else: + raise TypeError('shrinkage must be of string or int type') + return s + + +def _class_means(X, y): + """Compute class means. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Input data. + + y : array-like, shape (n_samples,) or (n_samples, n_targets) + Target values. + + Returns + ------- + means : array-like, shape (n_features,) + Class means. + """ + means = [] + classes = np.unique(y) + for group in classes: + Xg = X[y == group, :] + means.append(Xg.mean(0)) + return np.asarray(means) + + +def _class_cov(X, y, priors=None, shrinkage=None): + """Compute class covariance matrix. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Input data. + + y : array-like, shape (n_samples,) or (n_samples, n_targets) + Target values. + + priors : array-like, shape (n_classes,) + Class priors. + + shrinkage : string or float, optional + Shrinkage parameter, possible values: + - None: no shrinkage (default). + - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. + - float between 0 and 1: fixed shrinkage parameter. + + Returns + ------- + cov : array-like, shape (n_features, n_features) + Class covariance matrix. """ - Linear Discriminant Analysis (LDA) + classes = np.unique(y) + covs = [] + for group in classes: + Xg = X[y == group, :] + covs.append(np.atleast_2d(_cov(Xg, shrinkage))) + return np.average(covs, axis=0, weights=priors) - A classifier with a linear decision boundary, generated - by fitting class conditional densities to the data - and using Bayes' rule. - The model fits a Gaussian density to each class, assuming that - all classes share the same covariance matrix. +class LDA(BaseEstimator, LinearClassifierMixin, TransformerMixin): + """Linear Discriminant Analysis (LDA). - The fitted model can also be used to reduce the dimensionality - of the input, by projecting it to the most discriminative - directions. + A classifier with a linear decision boundary, generated by fitting class + conditional densities to the data and using Bayes' rule. + + The model fits a Gaussian density to each class, assuming that all classes + share the same covariance matrix. + + The fitted model can also be used to reduce the dimensionality of the input + by projecting it to the most discriminative directions. Parameters ---------- + solver : string, optional + Solver to use, possible values: + - 'svd': Singular value decomposition (default). Does not compute the + covariance matrix, therefore this solver is recommended for + data with a large number of features. + - 'lsqr': Least squares solution, can be combined with shrinkage. + - 'eigen': Eigenvalue decomposition, can be combined with shrinkage. + + shrinkage : string or float, optional + Shrinkage parameter, possible values: + - None: no shrinkage (default). + - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. + - float between 0 and 1: fixed shrinkage parameter. + Note that shrinkage works only with 'lsqr' and 'eigen' solvers. - n_components: int - Number of components (< n_classes - 1) for dimensionality reduction + priors : array, optional, shape (n_classes,) + Class priors. - priors : array, optional, shape = [n_classes] - Priors on classes + n_components : int, optional + Number of components (< n_classes - 1) for dimensionality reduction. + + store_covariance : bool, optional + Additionally compute class covariance matrix (default False). + + tol : float, optional + Threshold used for rank estimation in SVD solver. Attributes ---------- - `means_` : array-like, shape = [n_classes, n_features] - Class means - `xbar_` : float, shape = [n_features] - Over all mean - `priors_` : array-like, shape = [n_classes] - Class priors (sum to 1) - `covariance_` : array-like, shape = [n_features, n_features] - Covariance matrix (shared by all classes) + coef_ : array, shape (n_features,) or (n_classes, n_features) + Weight vector(s). + + intercept_ : array, shape (n_features,) + Intercept term. + + covariance_ : array-like, shape (n_features, n_features) + Covariance matrix (shared by all classes). + + means_ : array-like, shape (n_classes, n_features) + Class means. + + priors_ : array-like, shape (n_classes,) + Class priors (sum to 1). + + scalings_ : array-like, shape (rank, n_classes - 1) + Scaling of the features in the space spanned by the class centroids. + + xbar_ : array-like, shape (n_features,) + Overall mean. + + classes_ : array-like, shape (n_classes,) + Unique class labels. + + See also + -------- + sklearn.qda.QDA: Quadratic discriminant analysis + + Notes + ----- + The default solver is 'svd'. It can perform both classification and + transform, and it does not rely on the calculation of the covariance + matrix. This can be an advantage in situations where the number of features + is large. However, the 'svd' solver cannot be used with shrinkage. + + The 'lsqr' solver is an efficient algorithm that only works for + classification. It supports shrinkage. + + The 'eigen' solver is based on the optimization of the between class + scatter to within class scatter ratio. It can be used for both + classification and transform, and it supports shrinkage. However, the + 'eigen' solver needs to compute the covariance matrix, so it might not be + suitable for situations with a high number of features. Examples -------- @@ -60,220 +219,286 @@ class LDA(BaseEstimator, ClassifierMixin, TransformerMixin): >>> y = np.array([1, 1, 1, 2, 2, 2]) >>> clf = LDA() >>> clf.fit(X, y) - LDA(n_components=None, priors=None) + LDA(n_components=None, priors=None, shrinkage=None, solver='svd', + store_covariance=False, tol=0.0001) >>> print(clf.predict([[-0.8, -1]])) [1] + """ + def __init__(self, solver='svd', shrinkage=None, priors=None, + n_components=None, store_covariance=False, tol=1e-4): + self.solver = solver + self.shrinkage = shrinkage + self.priors = priors + self.n_components = n_components + self.store_covariance = store_covariance # used only in svd solver + self.tol = tol # used only in svd solver - See also - -------- - sklearn.qda.QDA: Quadratic discriminant analysis + def _solve_lsqr(self, X, y, shrinkage): + """Least squares solver. - """ + The least squares solver computes a straightforward solution of the + optimal decision rule based directly on the discriminant functions. It + can only be used for classification (with optional shrinkage), because + estimation of eigenvectors is not performed. Therefore, dimensionality + reduction with the transform is not supported. - def __init__(self, n_components=None, priors=None): - self.n_components = n_components - self.priors = np.asarray(priors) if priors is not None else None + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data. - if self.priors is not None: - if (self.priors < 0).any(): - raise ValueError('priors must be non-negative') - if self.priors.sum() != 1: - print 'warning: the priors do not sum to 1. Renormalizing' - self.priors = self.priors / self.priors.sum() + y : array-like, shape (n_samples,) or (n_samples, n_classes) + Target values. - def fit(self, X, y, store_covariance=False, tol=1.0e-4): + shrinkage : string or float, optional + Shrinkage parameter, possible values: + - None: no shrinkage (default). + - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. + - float between 0 and 1: fixed shrinkage parameter. + + Notes + ----- + This solver is based on [1]_, section 2.6.2, pp. 39-41. + + References + ---------- + .. [1] R. O. Duda, P. E. Hart, D. G. Stork. Pattern Classification + (Second Edition). John Wiley & Sons, Inc., New York, 2001. ISBN + 0-471-05669-3. + """ + self.means_ = _class_means(X, y) + self.covariance_ = _class_cov(X, y, self.priors_, shrinkage) + self.coef_ = linalg.lstsq(self.covariance_, self.means_.T)[0].T + self.intercept_ = (-0.5 * np.diag(np.dot(self.means_, self.coef_.T)) + + np.log(self.priors_)) + + def _solve_eigen(self, X, y, shrinkage): + """Eigenvalue solver. + + The eigenvalue solver computes the optimal solution of the Rayleigh + coefficient (basically the ratio of between class scatter to within + class scatter). This solver supports both classification and + dimensionality reduction (with optional shrinkage). + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data. + + y : array-like, shape (n_samples,) or (n_samples, n_targets) + Target values. + + shrinkage : string or float, optional + Shrinkage parameter, possible values: + - None: no shrinkage (default). + - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. + - float between 0 and 1: fixed shrinkage constant. + + Notes + ----- + This solver is based on [1]_, section 3.8.3, pp. 121-124. + + References + ---------- + .. [1] R. O. Duda, P. E. Hart, D. G. Stork. Pattern Classification + (Second Edition). John Wiley & Sons, Inc., New York, 2001. ISBN + 0-471-05669-3. """ - Fit the LDA model according to the given training data and parameters. + self.means_ = _class_means(X, y) + self.covariance_ = _class_cov(X, y, self.priors_, shrinkage) + + Sw = self.covariance_ # within scatter + St = _cov(X, shrinkage) # total scatter + Sb = St - Sw # between scatter + + evals, evecs = linalg.eigh(Sb, Sw) + evecs = evecs[:, np.argsort(evals)[::-1]] # sort eigenvectors + # evecs /= np.linalg.norm(evecs, axis=0) # doesn't work with numpy 1.6 + evecs /= np.apply_along_axis(np.linalg.norm, 0, evecs) + + self.scalings_ = evecs + self.coef_ = np.dot(self.means_, evecs).dot(evecs.T) + self.intercept_ = (-0.5 * np.diag(np.dot(self.means_, self.coef_.T)) + + np.log(self.priors_)) + + def _solve_svd(self, X, y, store_covariance=False, tol=1.0e-4): + """SVD solver. Parameters ---------- - X : array-like, shape = [n_samples, n_features] - Training vector, where n_samples in the number of samples and - n_features is the number of features. - y : array, shape = [n_samples] - Target values (integers) - store_covariance : boolean - If True the covariance matrix (shared by all classes) is computed - and stored in `self.covariance_` attribute. + X : array-like, shape (n_samples, n_features) + Training data. + + y : array-like, shape (n_samples,) or (n_samples, n_targets) + Target values. + + store_covariance : bool, optional + Additionally compute class covariance matrix (default False). + + tol : float, optional + Threshold used for rank estimation. """ - X, y = check_arrays(X, y, sparse_format='dense') - self.classes_, y = unique(y, return_inverse=True) n_samples, n_features = X.shape n_classes = len(self.classes_) - if n_classes < 2: - raise ValueError('y has less than 2 classes') - if self.priors is None: - self.priors_ = np.bincount(y) / float(n_samples) - else: - self.priors_ = self.priors - # Group means n_classes*n_features matrix - means = [] - Xc = [] - cov = None - if store_covariance: - cov = np.zeros((n_features, n_features)) - for ind in xrange(n_classes): - Xg = X[y == ind, :] - meang = Xg.mean(0) - means.append(meang) - # centered group data - Xgc = Xg - meang - Xc.append(Xgc) - if store_covariance: - cov += np.dot(Xgc.T, Xgc) + self.means_ = _class_means(X, y) if store_covariance: - cov /= (n_samples - n_classes) - self.covariance_ = cov + self.covariance_ = _class_cov(X, y, self.priors_) + + Xc = [] + for idx, group in enumerate(self.classes_): + Xg = X[y == group, :] + Xc.append(Xg - self.means_[idx]) - self.means_ = np.asarray(means) - Xc = np.concatenate(Xc, 0) + self.xbar_ = np.dot(self.priors_, self.means_) + + Xc = np.concatenate(Xc, axis=0) - # ---------------------------- # 1) within (univariate) scaling by with classes std-dev std = Xc.std(axis=0) # avoid division by zero in normalization std[std == 0] = 1. - fac = float(1) / (n_samples - n_classes) - # ---------------------------- + fac = 1. / (n_samples - n_classes) + # 2) Within variance scaling X = np.sqrt(fac) * (Xc / std) # SVD of centered (within)scaled data - U, S, V = linalg.svd(X, full_matrices=0) + U, S, V = linalg.svd(X, full_matrices=False) rank = np.sum(S > tol) if rank < n_features: - warnings.warn("Variables are collinear") + warnings.warn("Variables are collinear.") # Scaling of within covariance is: V' 1/S - scaling = (V[:rank] / std).T / S[:rank] + scalings = (V[:rank] / std).T / S[:rank] - ## ---------------------------- - ## 3) Between variance scaling - # Overall mean - xbar = np.dot(self.priors_, self.means_) + # 3) Between variance scaling # Scale weighted centers X = np.dot(((np.sqrt((n_samples * self.priors_) * fac)) * - (means - xbar).T).T, scaling) + (self.means_ - self.xbar_).T).T, scalings) # Centers are living in a space with n_classes-1 dim (maximum) - # Use svd to find projection in the space spanned by the + # Use SVD to find projection in the space spanned by the # (n_classes) centers _, S, V = linalg.svd(X, full_matrices=0) rank = np.sum(S > tol * S[0]) - # compose the scalings - self.scaling = np.dot(scaling, V.T[:, :rank]) - self.xbar_ = xbar - # weight vectors / centroids - self.coef_ = np.dot(self.means_ - self.xbar_, self.scaling) - self.intercept_ = -0.5 * np.sum(self.coef_ ** 2, axis=1) + \ - np.log(self.priors_) - return self + self.scalings_ = np.dot(scalings, V.T[:, :rank]) + coef = np.dot(self.means_ - self.xbar_, self.scalings_) + self.intercept_ = (-0.5 * np.sum(coef ** 2, axis=1) + + np.log(self.priors_)) + self.coef_ = np.dot(coef, self.scalings_.T) + self.intercept_ -= np.dot(self.xbar_, self.coef_.T) - @property - def classes(self): - warnings.warn("LDA.classes is deprecated and will be removed in 0.14. " - "Use LDA.classes_ instead.", DeprecationWarning, - stacklevel=2) - return self.classes_ - - def _decision_function(self, X): - X = np.asarray(X) - # center and scale data - X = np.dot(X - self.xbar_, self.scaling) - return np.dot(X, self.coef_.T) + self.intercept_ - - def decision_function(self, X): - """ - This function return the decision function values related to each - class on an array of test vectors X. + def fit(self, X, y, store_covariance=False, tol=1.0e-4): + """Fit LDA model according to the given training data and parameters. Parameters ---------- - X : array-like, shape = [n_samples, n_features] - - Returns - ------- - C : array, shape = [n_samples, n_classes] or [n_samples,] - Decision function values related to each class, per sample. - In the two-class case, the shape is [n_samples,], giving the - log likelihood ratio of the positive class. - """ - dec_func = self._decision_function(X) - if len(self.classes_) == 2: - return dec_func[:, 1] - dec_func[:, 0] - return dec_func + X : array-like, shape (n_samples, n_features) + Training data. - def transform(self, X): + y : array, shape (n_samples,) + Target values. """ - Project the data so as to maximize class separation (large separation - between projected class means and small variance within each class). - - Parameters - ---------- - X : array-like, shape = [n_samples, n_features] - - Returns - ------- - X_new : array, shape = [n_samples, n_components] - """ - X = np.asarray(X) - # center and scale data - X = np.dot(X - self.xbar_, self.scaling) - n_comp = X.shape[1] if self.n_components is None else self.n_components - return np.dot(X, self.coef_[:n_comp].T) + if store_covariance: + warnings.warn("'store_covariance' was moved to the __init__()" + "method in version 0.16 and will be removed from" + "fit() in version 0.18.", DeprecationWarning) + else: + store_covariance = self.store_covariance + if tol != 1.0e-4: + warnings.warn("'tol' was moved to __init__() method in version" + " 0.16 and will be removed from fit() in 0.18", + DeprecationWarning) + self.tol = tol + X, y = check_X_y(X, y) + self.classes_ = unique_labels(y) + + if self.priors is None: # estimate priors from sample + _, y_t = np.unique(y, return_inverse=True) # non-negative ints + self.priors_ = bincount(y_t) / float(len(y)) + else: + self.priors_ = self.priors - def predict(self, X): - """ - This function does classification on an array of test vectors X. + if self.solver == 'svd': + if self.shrinkage is not None: + raise NotImplementedError('shrinkage not supported') + self._solve_svd(X, y, store_covariance=store_covariance, tol=tol) + elif self.solver == 'lsqr': + self._solve_lsqr(X, y, shrinkage=self.shrinkage) + elif self.solver == 'eigen': + self._solve_eigen(X, y, shrinkage=self.shrinkage) + else: + raise ValueError("unknown solver {} (valid solvers are 'svd', " + "'lsqr', and 'eigen').".format(self.solver)) + if self.classes_.size == 2: # treat binary case as a special case + self.coef_ = np.array(self.coef_[1, :] - self.coef_[0, :], ndmin=2) + self.intercept_ = np.array(self.intercept_[1] - self.intercept_[0], + ndmin=1) + return self - The predicted class C for each sample in X is returned. + def transform(self, X): + """Project data to maximize class separation. Parameters ---------- - X : array-like, shape = [n_samples, n_features] + X : array-like, shape (n_samples, n_features) + Input data. Returns ------- - C : array, shape = [n_samples] + X_new : array, shape (n_samples, n_components) + Transformed data. """ - d = self._decision_function(X) - y_pred = self.classes_.take(d.argmax(1)) - return y_pred + check_is_fitted(self, ['xbar_', 'scalings_'], all_or_any=any) + + X = check_array(X) + if self.solver == 'lsqr': + raise NotImplementedError("transform not implemented for 'lsqr' " + "solver (use 'svd' or 'eigen').") + elif self.solver == 'svd': + X_new = np.dot(X - self.xbar_, self.scalings_) + elif self.solver == 'eigen': + X_new = np.dot(X, self.scalings_) + n_components = X.shape[1] if self.n_components is None \ + else self.n_components + return X_new[:, :n_components] def predict_proba(self, X): - """ - This function return posterior probabilities of classification - according to each class on an array of test vectors X. + """Estimate probability. Parameters ---------- - X : array-like, shape = [n_samples, n_features] + X : array-like, shape (n_samples, n_features) + Input data. Returns ------- - C : array, shape = [n_samples, n_classes] + C : array, shape (n_samples, n_classes) + Estimated probabilities. """ - values = self._decision_function(X) - # compute the likelihood of the underlying gaussian models - # up to a multiplicative constant. - likelihood = np.exp(values - values.max(axis=1)[:, np.newaxis]) - # compute posterior probabilities - return likelihood / likelihood.sum(axis=1)[:, np.newaxis] + prob = self.decision_function(X) + prob *= -1 + np.exp(prob, prob) + prob += 1 + np.reciprocal(prob, prob) + if len(self.classes_) == 2: # binary case + return np.column_stack([1 - prob, prob]) + else: + # OvR normalization, like LibLinear's predict_probability + prob /= prob.sum(axis=1).reshape((prob.shape[0], -1)) + return prob def predict_log_proba(self, X): - """ - This function return posterior log-probabilities of classification - according to each class on an array of test vectors X. + """Estimate log probability. Parameters ---------- - X : array-like, shape = [n_samples, n_features] + X : array-like, shape (n_samples, n_features) + Input data. Returns ------- - C : array, shape = [n_samples, n_classes] + C : array, shape (n_samples, n_classes) + Estimated log probabilities. """ - values = self._decision_function(X) - loglikelihood = (values - values.max(axis=1)[:, np.newaxis]) - normalization = logsumexp(loglikelihood, axis=1) - return loglikelihood - normalization[:, np.newaxis] + return np.log(self.predict_proba(X)) diff --git a/sklearn/learning_curve.py b/sklearn/learning_curve.py new file mode 100644 index 0000000000000..55c4cf6547d86 --- /dev/null +++ b/sklearn/learning_curve.py @@ -0,0 +1,308 @@ +"""Utilities to evaluate models with respect to a variable +""" +# Author: Alexander Fabisch +# +# License: BSD 3 clause + +import warnings + +import numpy as np + +from .base import is_classifier, clone +from .cross_validation import _check_cv +from .externals.joblib import Parallel, delayed +from .cross_validation import _safe_split, _score, _fit_and_score +from .metrics.scorer import check_scoring +from .utils import indexable +from .utils.fixes import astype + + +def learning_curve(estimator, X, y, train_sizes=np.linspace(0.1, 1.0, 5), + cv=None, scoring=None, exploit_incremental_learning=False, + n_jobs=1, pre_dispatch="all", verbose=0): + """Learning curve. + + Determines cross-validated training and test scores for different training + set sizes. + + A cross-validation generator splits the whole dataset k times in training + and test data. Subsets of the training set with varying sizes will be used + to train the estimator and a score for each training subset size and the + test set will be computed. Afterwards, the scores will be averaged over + all k runs for each training subset size. + + Parameters + ---------- + estimator : object type that implements the "fit" and "predict" methods + An object of that type which is cloned for each validation. + + X : array-like, shape (n_samples, n_features) + Training vector, where n_samples is the number of samples and + n_features is the number of features. + + y : array-like, shape (n_samples) or (n_samples, n_features), optional + Target relative to X for classification or regression; + None for unsupervised learning. + + train_sizes : array-like, shape (n_ticks,), dtype float or int + Relative or absolute numbers of training examples that will be used to + generate the learning curve. If the dtype is float, it is regarded as a + fraction of the maximum size of the training set (that is determined + by the selected validation method), i.e. it has to be within (0, 1]. + Otherwise it is interpreted as absolute sizes of the training sets. + Note that for classification the number of samples usually have to + be big enough to contain at least one sample from each class. + (default: np.linspace(0.1, 1.0, 5)) + + cv : integer, cross-validation generator, optional + If an integer is passed, it is the number of folds (defaults to 3). + Specific cross-validation objects can be passed, see + sklearn.cross_validation module for the list of possible objects + + scoring : string, callable or None, optional, default: None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. + + exploit_incremental_learning : boolean, optional, default: False + If the estimator supports incremental learning, this will be + used to speed up fitting for different training set sizes. + + n_jobs : integer, optional + Number of jobs to run in parallel (default 1). + + pre_dispatch : integer or string, optional + Number of predispatched jobs for parallel execution (default is + all). The option can reduce the allocated memory. The string can + be an expression like '2*n_jobs'. + + verbose : integer, optional + Controls the verbosity: the higher, the more messages. + + Returns + ------- + train_sizes_abs : array, shape = (n_unique_ticks,), dtype int + Numbers of training examples that has been used to generate the + learning curve. Note that the number of ticks might be less + than n_ticks because duplicate entries will be removed. + + train_scores : array, shape (n_ticks, n_cv_folds) + Scores on training sets. + + test_scores : array, shape (n_ticks, n_cv_folds) + Scores on test set. + + Notes + ----- + See :ref:`examples/model_selection/plot_learning_curve.py + ` + """ + if exploit_incremental_learning and not hasattr(estimator, "partial_fit"): + raise ValueError("An estimator must support the partial_fit interface " + "to exploit incremental learning") + + X, y = indexable(X, y) + # Make a list since we will be iterating multiple times over the folds + cv = list(_check_cv(cv, X, y, classifier=is_classifier(estimator))) + scorer = check_scoring(estimator, scoring=scoring) + + # HACK as long as boolean indices are allowed in cv generators + if cv[0][0].dtype == bool: + new_cv = [] + for i in range(len(cv)): + new_cv.append((np.nonzero(cv[i][0])[0], np.nonzero(cv[i][1])[0])) + cv = new_cv + + n_max_training_samples = len(cv[0][0]) + # Because the lengths of folds can be significantly different, it is + # not guaranteed that we use all of the available training data when we + # use the first 'n_max_training_samples' samples. + train_sizes_abs = _translate_train_sizes(train_sizes, + n_max_training_samples) + n_unique_ticks = train_sizes_abs.shape[0] + if verbose > 0: + print("[learning_curve] Training set sizes: " + str(train_sizes_abs)) + + parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, + verbose=verbose) + if exploit_incremental_learning: + classes = np.unique(y) if is_classifier(estimator) else None + out = parallel(delayed(_incremental_fit_estimator)( + clone(estimator), X, y, classes, train, test, train_sizes_abs, + scorer, verbose) for train, test in cv) + else: + out = parallel(delayed(_fit_and_score)( + clone(estimator), X, y, scorer, train[:n_train_samples], test, + verbose, parameters=None, fit_params=None, return_train_score=True) + for train, test in cv for n_train_samples in train_sizes_abs) + out = np.array(out)[:, :2] + n_cv_folds = out.shape[0] // n_unique_ticks + out = out.reshape(n_cv_folds, n_unique_ticks, 2) + + out = np.asarray(out).transpose((2, 1, 0)) + + return train_sizes_abs, out[0], out[1] + + +def _translate_train_sizes(train_sizes, n_max_training_samples): + """Determine absolute sizes of training subsets and validate 'train_sizes'. + + Examples: + _translate_train_sizes([0.5, 1.0], 10) -> [5, 10] + _translate_train_sizes([5, 10], 10) -> [5, 10] + + Parameters + ---------- + train_sizes : array-like, shape (n_ticks,), dtype float or int + Numbers of training examples that will be used to generate the + learning curve. If the dtype is float, it is regarded as a + fraction of 'n_max_training_samples', i.e. it has to be within (0, 1]. + + n_max_training_samples : int + Maximum number of training samples (upper bound of 'train_sizes'). + + Returns + ------- + train_sizes_abs : array, shape (n_unique_ticks,), dtype int + Numbers of training examples that will be used to generate the + learning curve. Note that the number of ticks might be less + than n_ticks because duplicate entries will be removed. + """ + train_sizes_abs = np.asarray(train_sizes) + n_ticks = train_sizes_abs.shape[0] + n_min_required_samples = np.min(train_sizes_abs) + n_max_required_samples = np.max(train_sizes_abs) + if np.issubdtype(train_sizes_abs.dtype, np.float): + if n_min_required_samples <= 0.0 or n_max_required_samples > 1.0: + raise ValueError("train_sizes has been interpreted as fractions " + "of the maximum number of training samples and " + "must be within (0, 1], but is within [%f, %f]." + % (n_min_required_samples, + n_max_required_samples)) + train_sizes_abs = astype(train_sizes_abs * n_max_training_samples, + dtype=np.int, copy=False) + train_sizes_abs = np.clip(train_sizes_abs, 1, + n_max_training_samples) + else: + if (n_min_required_samples <= 0 or + n_max_required_samples > n_max_training_samples): + raise ValueError("train_sizes has been interpreted as absolute " + "numbers of training samples and must be within " + "(0, %d], but is within [%d, %d]." + % (n_max_training_samples, + n_min_required_samples, + n_max_required_samples)) + + train_sizes_abs = np.unique(train_sizes_abs) + if n_ticks > train_sizes_abs.shape[0]: + warnings.warn("Removed duplicate entries from 'train_sizes'. Number " + "of ticks will be less than than the size of " + "'train_sizes' %d instead of %d)." + % (train_sizes_abs.shape[0], n_ticks), RuntimeWarning) + + return train_sizes_abs + + +def _incremental_fit_estimator(estimator, X, y, classes, train, test, + train_sizes, scorer, verbose): + """Train estimator on training subsets incrementally and compute scores.""" + train_scores, test_scores = [], [] + partitions = zip(train_sizes, np.split(train, train_sizes)[:-1]) + for n_train_samples, partial_train in partitions: + train_subset = train[:n_train_samples] + X_train, y_train = _safe_split(estimator, X, y, train_subset) + X_partial_train, y_partial_train = _safe_split(estimator, X, y, + partial_train) + X_test, y_test = _safe_split(estimator, X, y, test, train_subset) + if y_partial_train is None: + estimator.partial_fit(X_partial_train, classes=classes) + else: + estimator.partial_fit(X_partial_train, y_partial_train, + classes=classes) + train_scores.append(_score(estimator, X_train, y_train, scorer)) + test_scores.append(_score(estimator, X_test, y_test, scorer)) + return np.array((train_scores, test_scores)).T + + +def validation_curve(estimator, X, y, param_name, param_range, cv=None, + scoring=None, n_jobs=1, pre_dispatch="all", verbose=0): + """Validation curve. + + Determine training and test scores for varying parameter values. + + Compute scores for an estimator with different values of a specified + parameter. This is similar to grid search with one parameter. However, this + will also compute training scores and is merely a utility for plotting the + results. + + Parameters + ---------- + estimator : object type that implements the "fit" and "predict" methods + An object of that type which is cloned for each validation. + + X : array-like, shape (n_samples, n_features) + Training vector, where n_samples is the number of samples and + n_features is the number of features. + + y : array-like, shape (n_samples) or (n_samples, n_features), optional + Target relative to X for classification or regression; + None for unsupervised learning. + + param_name : string + Name of the parameter that will be varied. + + param_range : array-like, shape (n_values,) + The values of the parameter that will be evaluated. + + cv : integer, cross-validation generator, optional + If an integer is passed, it is the number of folds (defaults to 3). + Specific cross-validation objects can be passed, see + sklearn.cross_validation module for the list of possible objects + + scoring : string, callable or None, optional, default: None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. + + n_jobs : integer, optional + Number of jobs to run in parallel (default 1). + + pre_dispatch : integer or string, optional + Number of predispatched jobs for parallel execution (default is + all). The option can reduce the allocated memory. The string can + be an expression like '2*n_jobs'. + + verbose : integer, optional + Controls the verbosity: the higher, the more messages. + + Returns + ------- + train_scores : array, shape (n_ticks, n_cv_folds) + Scores on training sets. + + test_scores : array, shape (n_ticks, n_cv_folds) + Scores on test set. + + Notes + ----- + See + :ref:`examples/model_selection/plot_validation_curve.py + ` + """ + X, y = indexable(X, y) + cv = _check_cv(cv, X, y, classifier=is_classifier(estimator)) + scorer = check_scoring(estimator, scoring=scoring) + + parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, + verbose=verbose) + out = parallel(delayed(_fit_and_score)( + estimator, X, y, scorer, train, test, verbose, + parameters={param_name: v}, fit_params=None, return_train_score=True) + for train, test in cv for v in param_range) + + out = np.asarray(out)[:, :2] + n_params = len(param_range) + n_cv_folds = out.shape[0] // n_params + out = out.reshape(n_cv_folds, n_params, 2).transpose((2, 1, 0)) + + return out[0], out[1] diff --git a/sklearn/linear_model/__init__.py b/sklearn/linear_model/__init__.py index f31cf40451aa9..b6c512f4abd38 100644 --- a/sklearn/linear_model/__init__.py +++ b/sklearn/linear_model/__init__.py @@ -1,5 +1,5 @@ """ -The :mod:`sklearn.linear_model` module implements genelarized linear models. It +The :mod:`sklearn.linear_model` module implements generalized linear models. It includes Ridge regression, Bayesian Regression, Lasso and Elastic Net estimators computed with Least Angle Regression and coordinate descent. It also implements Stochastic Gradient Descent related algorithms. @@ -12,21 +12,27 @@ from .base import LinearRegression from .bayes import BayesianRidge, ARDRegression -from .least_angle import Lars, LassoLars, lars_path, LarsCV, LassoLarsCV, \ - LassoLarsIC -from .coordinate_descent import Lasso, ElasticNet, LassoCV, ElasticNetCV, \ - lasso_path, enet_path, MultiTaskLasso, \ - MultiTaskElasticNet +from .least_angle import (Lars, LassoLars, lars_path, LarsCV, LassoLarsCV, + LassoLarsIC) +from .coordinate_descent import (Lasso, ElasticNet, LassoCV, ElasticNetCV, + lasso_path, enet_path, MultiTaskLasso, + MultiTaskElasticNet, MultiTaskElasticNetCV, + MultiTaskLassoCV) from .sgd_fast import Hinge, Log, ModifiedHuber, SquaredLoss, Huber from .stochastic_gradient import SGDClassifier, SGDRegressor -from .ridge import Ridge, RidgeCV, RidgeClassifier, RidgeClassifierCV, \ - ridge_regression -from .logistic import LogisticRegression -from .omp import orthogonal_mp, orthogonal_mp_gram, OrthogonalMatchingPursuit +from .ridge import (Ridge, RidgeCV, RidgeClassifier, RidgeClassifierCV, + ridge_regression) +from .logistic import (LogisticRegression, LogisticRegressionCV, + logistic_regression_path) +from .omp import (orthogonal_mp, orthogonal_mp_gram, OrthogonalMatchingPursuit, + OrthogonalMatchingPursuitCV) +from .passive_aggressive import PassiveAggressiveClassifier +from .passive_aggressive import PassiveAggressiveRegressor from .perceptron import Perceptron -from .randomized_l1 import RandomizedLasso, RandomizedLogisticRegression, \ - lasso_stability_path -from .isotonic_regression_ import IsotonicRegression +from .randomized_l1 import (RandomizedLasso, RandomizedLogisticRegression, + lasso_stability_path) +from .ransac import RANSACRegressor +from .theil_sen import TheilSenRegressor __all__ = ['ARDRegression', 'BayesianRidge', @@ -44,10 +50,16 @@ 'LinearRegression', 'Log', 'LogisticRegression', + 'LogisticRegressionCV', 'ModifiedHuber', 'MultiTaskElasticNet', + 'MultiTaskElasticNetCV', 'MultiTaskLasso', + 'MultiTaskLassoCV', 'OrthogonalMatchingPursuit', + 'OrthogonalMatchingPursuitCV', + 'PassiveAggressiveClassifier', + 'PassiveAggressiveRegressor', 'Perceptron', 'RandomizedLasso', 'RandomizedLogisticRegression', @@ -58,10 +70,13 @@ 'SGDClassifier', 'SGDRegressor', 'SquaredLoss', + 'TheilSenRegressor', 'enet_path', 'lars_path', 'lasso_path', 'lasso_stability_path', + 'logistic_regression_path', 'orthogonal_mp', 'orthogonal_mp_gram', - 'ridge_regression'] + 'ridge_regression', + 'RANSACRegressor'] diff --git a/sklearn/linear_model/base.py b/sklearn/linear_model/base.py index 0076b28b085db..ca4c36e1098b1 100644 --- a/sklearn/linear_model/base.py +++ b/sklearn/linear_model/base.py @@ -10,22 +10,26 @@ # Mathieu Blondel # Lars Buitinck # -# License: BSD Style. +# License: BSD 3 clause +from __future__ import division from abc import ABCMeta, abstractmethod +import numbers +import warnings import numpy as np import scipy.sparse as sp from scipy import linalg +from scipy import sparse +from ..externals import six from ..externals.joblib import Parallel, delayed from ..base import BaseEstimator, ClassifierMixin, RegressorMixin -from ..utils import as_float_array, atleast2d_or_csr, safe_asarray +from ..utils import as_float_array, check_array, check_X_y from ..utils.extmath import safe_sparse_dot -from ..utils.fixes import lsqr -from ..utils.sparsefuncs import (csc_mean_variance_axis0, - inplace_csc_column_scale) -from cd_fast import sparse_std +from ..utils.sparsefuncs import mean_variance_axis, inplace_column_scale +from ..utils.fixes import sparse_lsqr +from ..utils.validation import NotFittedError, check_is_fitted ### @@ -39,21 +43,29 @@ def sparse_center_data(X, y, fit_intercept, normalize=False): """ - Compute informations needed to center data to have mean zero along + Compute information needed to center data to have mean zero along axis 0. Be aware that X will not be centered since it would break the sparsity, but will be normalized if asked so. """ - X_data = np.array(X.data, np.float64) if fit_intercept: - # copy if 'normalize' is True or X is not a csc matrix - X = sp.csc_matrix(X, copy=normalize) - X_mean, X_std = csc_mean_variance_axis0(X) + # we might require not to change the csr matrix sometimes + # store a copy if normalize is True. + # Change dtype to float64 since mean_variance_axis accepts + # it that way. + if sp.isspmatrix(X) and X.getformat() == 'csr': + X = sp.csr_matrix(X, copy=normalize, dtype=np.float64) + else: + X = sp.csc_matrix(X, copy=normalize, dtype=np.float64) + + X_mean, X_var = mean_variance_axis(X, axis=0) if normalize: - X_std = sparse_std( - X.shape[0], X.shape[1], - X_data, X.indices, X.indptr, X_mean) + # transform variance to std in-place + # XXX: currently scaled to variance=n_samples to match center_data + X_var *= X.shape[0] + X_std = np.sqrt(X_var, X_var) + del X_var X_std[X_std == 0] = 1 - inplace_csc_column_scale(X, X_std) + inplace_column_scale(X, 1. / X_std) else: X_std = np.ones(X.shape[1]) y_mean = y.mean(axis=0) @@ -63,31 +75,36 @@ def sparse_center_data(X, y, fit_intercept, normalize=False): X_std = np.ones(X.shape[1]) y_mean = 0. if y.ndim == 1 else np.zeros(y.shape[1], dtype=X.dtype) - X_data = np.array(X.data, np.float64) - return X_data, y, X_mean, y_mean, X_std + return X, y, X_mean, y_mean, X_std -def center_data(X, y, fit_intercept, normalize=False, copy=True): +def center_data(X, y, fit_intercept, normalize=False, copy=True, + sample_weight=None): """ Centers data to have mean zero along axis 0. This is here because nearly all linear models will want their data to be centered. + + If sample_weight is not None, then the weighted mean of X and y + is zero, and not the mean itself """ X = as_float_array(X, copy) - if fit_intercept: + if isinstance(sample_weight, numbers.Number): + sample_weight = None if sp.issparse(X): X_mean = np.zeros(X.shape[1]) X_std = np.ones(X.shape[1]) else: - X_mean = X.mean(axis=0) + X_mean = np.average(X, axis=0, weights=sample_weight) X -= X_mean if normalize: + # XXX: currently scaled to variance=n_samples X_std = np.sqrt(np.sum(X ** 2, axis=0)) X_std[X_std == 0] = 1 X /= X_std else: X_std = np.ones(X.shape[1]) - y_mean = y.mean(axis=0) + y_mean = np.average(y, axis=0, weights=sample_weight) y = y - y_mean else: X_mean = np.zeros(X.shape[1]) @@ -96,39 +113,43 @@ def center_data(X, y, fit_intercept, normalize=False, copy=True): return X, y, X_mean, y_mean, X_std -class LinearModel(BaseEstimator): +class LinearModel(six.with_metaclass(ABCMeta, BaseEstimator)): """Base class for Linear Models""" - __metaclass__ = ABCMeta @abstractmethod def fit(self, X, y): """Fit model.""" def decision_function(self, X): - """Decision function of the linear model + """Decision function of the linear model. Parameters ---------- - X : numpy array of shape [n_samples, n_features] + X : {array-like, sparse matrix}, shape = (n_samples, n_features) + Samples. Returns ------- - C : array, shape = [n_samples] + C : array, shape = (n_samples,) Returns predicted values. """ - X = safe_asarray(X) - return safe_sparse_dot(X, self.coef_.T) + self.intercept_ + check_is_fitted(self, "coef_") + + X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) + return safe_sparse_dot(X, self.coef_.T, + dense_output=True) + self.intercept_ def predict(self, X): """Predict using the linear model Parameters ---------- - X : numpy array of shape [n_samples, n_features] + X : {array-like, sparse matrix}, shape = (n_samples, n_features) + Samples. Returns ------- - C : array, shape = [n_samples] + C : array, shape = (n_samples,) Returns predicted values. """ return self.decision_function(X) @@ -161,23 +182,29 @@ def decision_function(self, X): Parameters ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] + X : {array-like, sparse matrix}, shape = (n_samples, n_features) Samples. Returns ------- - array, shape = [n_samples] if n_classes == 2 else [n_samples,n_classes] + array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes) Confidence scores per (sample, class) combination. In the binary - case, confidence score for the "positive" class. + case, confidence score for self.classes_[1] where >0 means this + class would be predicted. """ - X = atleast2d_or_csr(X) + if not hasattr(self, 'coef_') or self.coef_ is None: + raise NotFittedError("This %(name)s instance is not fitted" + "yet" % {'name': type(self).__name__}) + + X = check_array(X, accept_sparse='csr') n_features = self.coef_.shape[1] if X.shape[1] != n_features: raise ValueError("X has %d features per sample; expecting %d" % (X.shape[1], n_features)) - scores = safe_sparse_dot(X, self.coef_.T) + self.intercept_ + scores = safe_sparse_dot(X, self.coef_.T, + dense_output=True) + self.intercept_ return scores.ravel() if scores.shape[1] == 1 else scores def predict(self, X): @@ -200,39 +227,126 @@ def predict(self, X): indices = scores.argmax(axis=1) return self.classes_[indices] + def _predict_proba_lr(self, X): + """Probability estimation for OvR logistic regression. -class LinearRegression(LinearModel, RegressorMixin): + Positive class probabilities are computed as + 1. / (1. + np.exp(-self.decision_function(X))); + multiclass is handled by normalizing that over all classes. + """ + prob = self.decision_function(X) + prob *= -1 + np.exp(prob, prob) + prob += 1 + np.reciprocal(prob, prob) + if len(prob.shape) == 1: + return np.vstack([1 - prob, prob]).T + else: + # OvR normalization, like LibLinear's predict_probability + prob /= prob.sum(axis=1).reshape((prob.shape[0], -1)) + return prob + + +class SparseCoefMixin(object): + """Mixin for converting coef_ to and from CSR format. + + L1-regularizing estimators should inherit this. """ - Ordinary least squares Linear Regression. - Attributes - ---------- - `coef_` : array - Estimated coefficients for the linear regression problem. + def densify(self): + """Convert coefficient matrix to dense array format. - `intercept_` : array - Independent term in the linear model. + Converts the ``coef_`` member (back) to a numpy.ndarray. This is the + default format of ``coef_`` and is required for fitting, so calling + this method is only required on models that have previously been + sparsified; otherwise, it is a no-op. + + Returns + ------- + self: estimator + """ + msg = "Estimator, %(name)s, must be fitted before densifying." + check_is_fitted(self, "coef_", msg=msg) + if sp.issparse(self.coef_): + self.coef_ = self.coef_.toarray() + return self + + def sparsify(self): + """Convert coefficient matrix to sparse format. + + Converts the ``coef_`` member to a scipy.sparse matrix, which for + L1-regularized models can be much more memory- and storage-efficient + than the usual numpy.ndarray representation. + + The ``intercept_`` member is not converted. + + Notes + ----- + For non-sparse models, i.e. when there are not many zeros in ``coef_``, + this may actually *increase* memory usage, so use this method with + care. A rule of thumb is that the number of zero elements, which can + be computed with ``(coef_ == 0).sum()``, must be more than 50% for this + to provide significant benefits. + + After calling this method, further fitting with the partial_fit + method (if any) will not work until you call densify. + + Returns + ------- + self: estimator + """ + msg = "Estimator, %(name)s, must be fitted before sparsifying." + check_is_fitted(self, "coef_", msg=msg) + self.coef_ = sp.csr_matrix(self.coef_) + return self + + +class LinearRegression(LinearModel, RegressorMixin): + """ + Ordinary least squares Linear Regression. Parameters ---------- fit_intercept : boolean, optional - wether to calculate the intercept for this model. If set + whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). - normalize : boolean, optional - If True, the regressors X are normalized + + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. + + copy_X : boolean, optional, default True + If True, X will be copied; else, it may be overwritten. + + n_jobs : int, optional, default 1 + The number of jobs to use for the computation. + If -1 all CPUs are used. This will only provide speedup for + n_targets > 1 and sufficient large problems. + + Attributes + ---------- + coef_ : array, shape (n_features, ) or (n_targets, n_features) + Estimated coefficients for the linear regression problem. + If multiple targets are passed during the fit (y 2D), this + is a 2D array of shape (n_targets, n_features), while if only + one target is passed, this is a 1D array of length n_features. + + intercept_ : array + Independent term in the linear model. Notes ----- From the implementation point of view, this is just plain Ordinary - Least Squares (numpy.linalg.lstsq) wrapped as a predictor object. + Least Squares (scipy.linalg.lstsq) wrapped as a predictor object. """ - def __init__(self, fit_intercept=True, normalize=False, copy_X=True): + def __init__(self, fit_intercept=True, normalize=False, copy_X=True, + n_jobs=1): self.fit_intercept = fit_intercept self.normalize = normalize self.copy_X = copy_X + self.n_jobs = n_jobs def fit(self, X, y, n_jobs=1): """ @@ -242,39 +356,81 @@ def fit(self, X, y, n_jobs=1): ---------- X : numpy array or sparse matrix of shape [n_samples,n_features] Training data - y : numpy array of shape [n_samples, n_responses] + + y : numpy array of shape [n_samples, n_targets] Target values - n_jobs : The number of jobs to use for the computation. - If -1 all CPUs are used. This will only provide speedup for - n_response > 1 and sufficient large problems Returns ------- self : returns an instance of self. """ - X = safe_asarray(X) - y = np.asarray(y) + if n_jobs != 1: + warnings.warn("The n_jobs parameter in fit is deprecated and will " + "be removed in 0.17. It has been moved from the fit " + "method to the LinearRegression class constructor.", + DeprecationWarning, stacklevel=2) + n_jobs_ = n_jobs + else: + n_jobs_ = self.n_jobs + X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'], + y_numeric=True, multi_output=True) - X, y, X_mean, y_mean, X_std = self._center_data(X, y, - self.fit_intercept, self.normalize, self.copy_X) + X, y, X_mean, y_mean, X_std = self._center_data( + X, y, self.fit_intercept, self.normalize, self.copy_X) if sp.issparse(X): if y.ndim < 2: - out = lsqr(X, y) + out = sparse_lsqr(X, y) self.coef_ = out[0] self.residues_ = out[3] else: # sparse_lstsq cannot handle y with shape (M, K) - outs = Parallel(n_jobs=n_jobs)(delayed(lsqr) - (X, y[:, j].ravel()) for j in range(y.shape[1])) + outs = Parallel(n_jobs=n_jobs_)( + delayed(sparse_lsqr)(X, y[:, j].ravel()) + for j in range(y.shape[1])) self.coef_ = np.vstack(out[0] for out in outs) self.residues_ = np.vstack(out[3] for out in outs) else: self.coef_, self.residues_, self.rank_, self.singular_ = \ - linalg.lstsq(X, y) + linalg.lstsq(X, y) self.coef_ = self.coef_.T if y.ndim == 1: self.coef_ = np.ravel(self.coef_) self._set_intercept(X_mean, y_mean, X_std) return self + + +def _pre_fit(X, y, Xy, precompute, normalize, fit_intercept, copy): + """Aux function used at beginning of fit in linear models""" + n_samples, n_features = X.shape + if sparse.isspmatrix(X): + precompute = False + X, y, X_mean, y_mean, X_std = sparse_center_data( + X, y, fit_intercept, normalize) + else: + # copy was done in fit if necessary + X, y, X_mean, y_mean, X_std = center_data( + X, y, fit_intercept, normalize, copy=copy) + + if hasattr(precompute, '__array__') \ + and not np.allclose(X_mean, np.zeros(n_features)) \ + and not np.allclose(X_std, np.ones(n_features)): + # recompute Gram + precompute = 'auto' + Xy = None + + # precompute if n_samples > n_features + if precompute == 'auto': + precompute = (n_samples > n_features) + + if precompute is True: + precompute = np.dot(X.T, X) + + if not hasattr(precompute, '__array__'): + Xy = None # cannot use Xy if precompute is not Gram + + if hasattr(precompute, '__array__') and Xy is None: + Xy = np.dot(X.T, y) + + return X, y, X_mean, y_mean, X_std, precompute, Xy diff --git a/sklearn/linear_model/bayes.py b/sklearn/linear_model/bayes.py index a3faf894684d8..2f40648527adf 100644 --- a/sklearn/linear_model/bayes.py +++ b/sklearn/linear_model/bayes.py @@ -1,6 +1,7 @@ """ Various bayesian regression """ +from __future__ import print_function # Authors: V. Michel, F. Pedregosa, A. Gramfort # License: BSD 3 clause @@ -12,7 +13,7 @@ from .base import LinearModel from ..base import RegressorMixin from ..utils.extmath import fast_logdet, pinvh -from ..utils import check_arrays +from ..utils import check_X_y ############################################################################### @@ -26,12 +27,6 @@ class BayesianRidge(LinearModel, RegressorMixin): Parameters ---------- - X : array, shape = (n_samples, n_features) - Training vectors. - - y : array, shape = (length) - Target values for training vectors - n_iter : int, optional Maximum number of iterations. Default is 300. @@ -61,13 +56,13 @@ class BayesianRidge(LinearModel, RegressorMixin): Default is False fit_intercept : boolean, optional - wether to calculate the intercept for this model. If set + whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). Default is True. normalize : boolean, optional, default False - If True, the regressors X are normalized + If True, the regressors X will be normalized before regression. copy_X : boolean, optional, default True If True, X will be copied; else, it may be overwritten. @@ -78,16 +73,16 @@ class BayesianRidge(LinearModel, RegressorMixin): Attributes ---------- - `coef_` : array, shape = (n_features) + coef_ : array, shape = (n_features) Coefficients of the regression model (mean of distribution) - `alpha_` : float + alpha_ : float estimated precision of the noise. - `lambda_` : array, shape = (n_features) + lambda_ : array, shape = (n_features) estimated precisions of the weights. - `scores_` : float + scores_ : float if computed, value of the objective function (to be maximized) Examples @@ -108,9 +103,9 @@ class BayesianRidge(LinearModel, RegressorMixin): """ def __init__(self, n_iter=300, tol=1.e-3, alpha_1=1.e-6, alpha_2=1.e-6, - lambda_1=1.e-6, lambda_2=1.e-6, compute_score=False, - fit_intercept=True, normalize=False, - copy_X=True, verbose=False): + lambda_1=1.e-6, lambda_2=1.e-6, compute_score=False, + fit_intercept=True, normalize=False, copy_X=True, + verbose=False): self.n_iter = n_iter self.tol = tol self.alpha_1 = alpha_1 @@ -137,10 +132,9 @@ def fit(self, X, y): ------- self : returns an instance of self. """ - X, y = check_arrays(X, y, sparse_format='dense', - dtype=np.float) - X, y, X_mean, y_mean, X_std = self._center_data(X, y, - self.fit_intercept, self.normalize, self.copy_X) + X, y = check_X_y(X, y, dtype=np.float64, y_numeric=True) + X, y, X_mean, y_mean, X_std = self._center_data( + X, y, self.fit_intercept, self.normalize, self.copy_X) n_samples, n_features = X.shape ### Initialization of the values of the parameters @@ -175,7 +169,7 @@ def fit(self, X, y): np.log(lambda_ + alpha_ * eigen_vals_)) else: coef_ = np.dot(X.T, np.dot( - U / (eigen_vals_ + lambda_ / alpha_)[None, :], U.T)) + U / (eigen_vals_ + lambda_ / alpha_)[None, :], U.T)) coef_ = np.dot(coef_, y) if self.compute_score: logdet_sigma_ = lambda_ * np.ones(n_features) @@ -185,28 +179,28 @@ def fit(self, X, y): ### Update alpha and lambda rmse_ = np.sum((y - np.dot(X, coef_)) ** 2) gamma_ = (np.sum((alpha_ * eigen_vals_) - / (lambda_ + alpha_ * eigen_vals_))) + / (lambda_ + alpha_ * eigen_vals_))) lambda_ = ((gamma_ + 2 * lambda_1) - / (np.sum(coef_ ** 2) + 2 * lambda_2)) + / (np.sum(coef_ ** 2) + 2 * lambda_2)) alpha_ = ((n_samples - gamma_ + 2 * alpha_1) - / (rmse_ + 2 * alpha_2)) + / (rmse_ + 2 * alpha_2)) ### Compute the objective function if self.compute_score: s = lambda_1 * log(lambda_) - lambda_2 * lambda_ s += alpha_1 * log(alpha_) - alpha_2 * alpha_ s += 0.5 * (n_features * log(lambda_) - + n_samples * log(alpha_) - - alpha_ * rmse_ - - (lambda_ * np.sum(coef_ ** 2)) - - logdet_sigma_ - - n_samples * log(2 * np.pi)) + + n_samples * log(alpha_) + - alpha_ * rmse_ + - (lambda_ * np.sum(coef_ ** 2)) + - logdet_sigma_ + - n_samples * log(2 * np.pi)) self.scores_.append(s) ### Check for convergence if iter_ != 0 and np.sum(np.abs(coef_old_ - coef_)) < self.tol: if verbose: - print "Convergence after ", str(iter_), " iterations" + print("Convergence after ", str(iter_), " iterations") break coef_old_ = np.copy(coef_) @@ -233,12 +227,6 @@ class ARDRegression(LinearModel, RegressorMixin): Parameters ---------- - X : array, shape = (n_samples, n_features) - Training vectors. - - y : array, shape = (n_samples) - Target values for training vectors - n_iter : int, optional Maximum number of iterations. Default is 300 @@ -270,13 +258,13 @@ class ARDRegression(LinearModel, RegressorMixin): the computation. Default is 1.e+4. fit_intercept : boolean, optional - wether to calculate the intercept for this model. If set + whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). Default is True. - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. copy_X : boolean, optional, default True. If True, X will be copied; else, it may be overwritten. @@ -286,19 +274,19 @@ class ARDRegression(LinearModel, RegressorMixin): Attributes ---------- - `coef_` : array, shape = (n_features) + coef_ : array, shape = (n_features) Coefficients of the regression model (mean of distribution) - `alpha_` : float + alpha_ : float estimated precision of the noise. - `lambda_` : array, shape = (n_features) + lambda_ : array, shape = (n_features) estimated precisions of the weights. - `sigma_` : array, shape = (n_features, n_features) + sigma_ : array, shape = (n_features, n_features) estimated variance-covariance matrix of the weights - `scores_` : float + scores_ : float if computed, value of the objective function (to be maximized) Examples @@ -320,9 +308,9 @@ class ARDRegression(LinearModel, RegressorMixin): """ def __init__(self, n_iter=300, tol=1.e-3, alpha_1=1.e-6, alpha_2=1.e-6, - lambda_1=1.e-6, lambda_2=1.e-6, compute_score=False, - threshold_lambda=1.e+4, fit_intercept=True, - normalize=False, copy_X=True, verbose=False): + lambda_1=1.e-6, lambda_2=1.e-6, compute_score=False, + threshold_lambda=1.e+4, fit_intercept=True, normalize=False, + copy_X=True, verbose=False): self.n_iter = n_iter self.tol = tol self.fit_intercept = fit_intercept @@ -354,14 +342,13 @@ def fit(self, X, y): ------- self : returns an instance of self. """ - X, y = check_arrays(X, y, sparse_format='dense', - dtype=np.float) + X, y = check_X_y(X, y, dtype=np.float64, y_numeric=True) n_samples, n_features = X.shape coef_ = np.zeros(n_features) - X, y, X_mean, y_mean, X_std = self._center_data(X, y, - self.fit_intercept, self.normalize, self.copy_X) + X, y, X_mean, y_mean, X_std = self._center_data( + X, y, self.fit_intercept, self.normalize, self.copy_X) ### Launch the convergence loop keep_lambda = np.ones(n_features, dtype=bool) @@ -383,29 +370,29 @@ def fit(self, X, y): for iter_ in range(self.n_iter): ### Compute mu and sigma (using Woodbury matrix identity) sigma_ = pinvh(np.eye(n_samples) / alpha_ + - np.dot(X[:, keep_lambda] * - np.reshape(1. / lambda_[keep_lambda], [1, -1]), - X[:, keep_lambda].T)) + np.dot(X[:, keep_lambda] * + np.reshape(1. / lambda_[keep_lambda], [1, -1]), + X[:, keep_lambda].T)) sigma_ = np.dot(sigma_, X[:, keep_lambda] - * np.reshape(1. / lambda_[keep_lambda], [1, -1])) + * np.reshape(1. / lambda_[keep_lambda], [1, -1])) sigma_ = - np.dot(np.reshape(1. / lambda_[keep_lambda], [-1, 1]) - * X[:, keep_lambda].T, sigma_) - sigma_.flat[::(sigma_.shape[1] + 1)] += \ - 1. / lambda_[keep_lambda] + * X[:, keep_lambda].T, sigma_) + sigma_.flat[::(sigma_.shape[1] + 1)] += 1. / lambda_[keep_lambda] coef_[keep_lambda] = alpha_ * np.dot( - sigma_, np.dot(X[:, keep_lambda].T, y)) + sigma_, np.dot(X[:, keep_lambda].T, y)) ### Update alpha and lambda rmse_ = np.sum((y - np.dot(X, coef_)) ** 2) gamma_ = 1. - lambda_[keep_lambda] * np.diag(sigma_) - lambda_[keep_lambda] = (gamma_ + 2. * lambda_1) \ - / ((coef_[keep_lambda]) ** 2 + 2. * lambda_2) - alpha_ = (n_samples - gamma_.sum() + 2. * alpha_1) \ - / (rmse_ + 2. * alpha_2) + lambda_[keep_lambda] = ((gamma_ + 2. * lambda_1) + / ((coef_[keep_lambda]) ** 2 + + 2. * lambda_2)) + alpha_ = ((n_samples - gamma_.sum() + 2. * alpha_1) + / (rmse_ + 2. * alpha_2)) ### Prune the weights with a precision over a threshold keep_lambda = lambda_ < self.threshold_lambda - coef_[keep_lambda == False] = 0 + coef_[~keep_lambda] = 0 ### Compute the objective function if self.compute_score: @@ -419,13 +406,13 @@ def fit(self, X, y): ### Check for convergence if iter_ > 0 and np.sum(np.abs(coef_old_ - coef_)) < self.tol: if verbose: - print "Converged after %s iterations" % iter_ + print("Converged after %s iterations" % iter_) break coef_old_ = np.copy(coef_) self.coef_ = coef_ self.alpha_ = alpha_ self.sigma_ = sigma_ - + self.lambda_ = lambda_ self._set_intercept(X_mean, y_mean, X_std) return self diff --git a/sklearn/linear_model/cd_fast.c b/sklearn/linear_model/cd_fast.c index 5350e4620cb4d..76ad23296c3de 100644 --- a/sklearn/linear_model/cd_fast.c +++ b/sklearn/linear_model/cd_fast.c @@ -1,16 +1,29 @@ -/* Generated by Cython 0.15.1 on Fri Aug 3 21:04:00 2012 */ +/* Generated by Cython 0.21 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) + #error Cython requires Python 2.6+ or Python 3.2+. #else - -#include /* For offsetof */ +#define CYTHON_ABI "0_21" +#include #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -22,85 +35,84 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - -#if PY_VERSION_HEX < 0x02040000 - #define METH_COEXIST 0 - #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) - #define PyDict_Contains(d,o) PySequence_Contains(d,o) +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL #endif - -#if PY_VERSION_HEX < 0x02050000 - typedef int Py_ssize_t; - #define PY_SSIZE_T_MAX INT_MAX - #define PY_SSIZE_T_MIN INT_MIN - #define PY_FORMAT_SIZE_T "" - #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) - #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 #endif - -#if PY_VERSION_HEX < 0x02060000 - #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) - #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) - #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) - #define PyVarObject_HEAD_INIT(type, size) \ - PyObject_HEAD_INIT(type) size, - #define PyType_Modified(t) - - typedef struct { - void *buf; - PyObject *obj; - Py_ssize_t len; - Py_ssize_t itemsize; - int readonly; - int ndim; - char *format; - Py_ssize_t *shape; - Py_ssize_t *strides; - Py_ssize_t *suboffsets; - void *internal; - } Py_buffer; - - #define PyBUF_SIMPLE 0 - #define PyBUF_WRITABLE 0x0001 - #define PyBUF_FORMAT 0x0004 - #define PyBUF_ND 0x0008 - #define PyBUF_STRIDES (0x0010 | PyBUF_ND) - #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) - #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) - #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) - #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 +#define Py_OptimizeFlag 0 #endif - +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - -#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) +#if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -108,36 +120,17 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - -#if PY_VERSION_HEX < 0x02060000 - #define PyBytesObject PyStringObject - #define PyBytes_Type PyString_Type - #define PyBytes_Check PyString_Check - #define PyBytes_CheckExact PyString_CheckExact - #define PyBytes_FromString PyString_FromString - #define PyBytes_FromStringAndSize PyString_FromStringAndSize - #define PyBytes_FromFormat PyString_FromFormat - #define PyBytes_DecodeEscape PyString_DecodeEscape - #define PyBytes_AsString PyString_AsString - #define PyBytes_AsStringAndSize PyString_AsStringAndSize - #define PyBytes_Size PyString_Size - #define PyBytes_AS_STRING PyString_AS_STRING - #define PyBytes_GET_SIZE PyString_GET_SIZE - #define PyBytes_Repr PyString_Repr - #define PyBytes_Concat PyString_Concat - #define PyBytes_ConcatAndDel PyString_ConcatAndDel -#endif - -#if PY_VERSION_HEX < 0x02060000 - #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) - #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -153,13 +146,12 @@ #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - -#if PY_VERSION_HEX < 0x03020000 +#if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong @@ -167,55 +159,57 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - #if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - -#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) - #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) - #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) -#else - #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) - #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif #endif - -#if PY_MAJOR_VERSION >= 3 - #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif #endif - -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#ifdef NAN +#define __PYX_NAN() ((float) NAN) #else - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#ifdef __cplusplus +template +void __Pyx_call_destructor(T* x) { + x->~T(); +} #endif -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_NAMESTR(n) ((char *)(n)) - #define __Pyx_DOCSTR(n) ((char *)(n)) + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else - #define __Pyx_NAMESTR(n) (n) - #define __Pyx_DOCSTR(n) (n) + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C @@ -232,13 +226,15 @@ #include #define __PYX_HAVE__sklearn__linear_model__cd_fast #define __PYX_HAVE_API__sklearn__linear_model__cd_fast +#include "math.h" +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "pythread.h" -#include "math.h" #include "cblas.h" +#include "pystate.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -247,21 +243,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -269,48 +250,163 @@ # else # define CYTHON_UNUSED # endif -# elif defined(__ICC) || defined(__INTEL_COMPILER) +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif -#ifdef __GNUC__ - /* Test for GCC > 2.95 */ - #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) - #else /* __GNUC__ > 2 ... */ - #define likely(x) (x) - #define unlikely(x) (x) - #endif /* __GNUC__ > 2 ... */ -#else /* __GNUC__ */ +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -319,7 +415,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -329,7 +424,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -337,20 +431,113 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { - "cd_fast.pyx", - "numpy.pxd", + "sklearn/linear_model/cd_fast.pyx", + "__init__.pxd", + "stringsource", + "type.pxd", "bool.pxd", "complex.pxd", }; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; + struct __Pyx_StructField_* fields; + size_t size; + size_t arraysize[8]; + int ndim; + char typegroup; + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + +struct __pyx_memoryview_obj; +typedef struct { + struct __pyx_memoryview_obj *memview; + char *data; + Py_ssize_t shape[8]; + Py_ssize_t strides[8]; + Py_ssize_t suboffsets[8]; +} __Pyx_memviewslice; + +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __pyx_atomic_int_type int +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ + !defined(__i386__) + #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && MSC_VER + #include + #define __pyx_atomic_int_type LONG + #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using MSVC atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 + #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using Intel atomics" + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif +typedef volatile __pyx_atomic_int_type __pyx_atomic_int; +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview) \ + __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) +#else + #define __pyx_add_acquisition_count(memview) \ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif -/* "numpy.pxd":719 + +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -359,7 +546,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -368,7 +555,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -377,7 +564,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -386,7 +573,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -395,7 +582,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -404,7 +591,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -413,7 +600,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -422,7 +609,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -431,7 +618,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -440,7 +627,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -449,7 +636,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -458,7 +645,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -467,7 +654,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -476,7 +663,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -485,7 +672,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -494,7 +681,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -503,7 +690,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -512,7 +699,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -521,7 +708,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -530,7 +717,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -539,24 +726,23 @@ typedef npy_double __pyx_t_5numpy_double_t; */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; -/* "sklearn/linear_model/cd_fast.pyx":57 - * +/* "sklearn/linear_model/cd_fast.pyx":18 + * import warnings * * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< - * ctypedef np.int32_t INTEGER + * ctypedef np.uint32_t UINT32_t * */ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE; -/* "sklearn/linear_model/cd_fast.pyx":58 +/* "sklearn/linear_model/cd_fast.pyx":19 * * ctypedef np.float64_t DOUBLE - * ctypedef np.int32_t INTEGER # <<<<<<<<<<<<<< - * + * ctypedef np.uint32_t UINT32_t # <<<<<<<<<<<<<< * + * np.import_array() */ -typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER; - +typedef __pyx_t_5numpy_uint32_t __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t; #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -577,9 +763,14 @@ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER; typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ +struct __pyx_array_obj; +struct __pyx_MemviewEnum_obj; +struct __pyx_memoryview_obj; +struct __pyx_memoryviewslice_obj; -/* "numpy.pxd":758 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -588,7 +779,7 @@ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -597,7 +788,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -606,7 +797,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -615,11 +806,129 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; */ typedef npy_cdouble __pyx_t_5numpy_complex_t; +/* "sklearn/linear_model/cd_fast.pyx":25 + * # The following two functions are shamelessly copied from the tree code. + * + * cdef enum: # <<<<<<<<<<<<<< + * # Max value for our rand_r replacement (near the bottom). + * # We don't use RAND_MAX because it's different across platforms and + */ +enum { + __pyx_e_7sklearn_12linear_model_7cd_fast_RAND_R_MAX = 0x7FFFFFFF +}; + +/* "View.MemoryView":99 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ +struct __pyx_array_obj { + PyObject_HEAD + char *data; + Py_ssize_t len; + char *format; + int ndim; + Py_ssize_t *_shape; + Py_ssize_t *_strides; + Py_ssize_t itemsize; + PyObject *mode; + PyObject *_format; + void (*callback_free_data)(void *); + int free_data; + int dtype_is_object; +}; + + +/* "View.MemoryView":269 + * + * @cname('__pyx_MemviewEnum') + * cdef class Enum(object): # <<<<<<<<<<<<<< + * cdef object name + * def __init__(self, name): + */ +struct __pyx_MemviewEnum_obj { + PyObject_HEAD + PyObject *name; +}; + + +/* "View.MemoryView":302 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ +struct __pyx_memoryview_obj { + PyObject_HEAD + struct __pyx_vtabstruct_memoryview *__pyx_vtab; + PyObject *obj; + PyObject *_size; + PyObject *_array_interface; + PyThread_type_lock lock; + __pyx_atomic_int acquisition_count[2]; + __pyx_atomic_int *acquisition_count_aligned_p; + Py_buffer view; + int flags; + int dtype_is_object; + __Pyx_TypeInfo *typeinfo; +}; + + +/* "View.MemoryView":922 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ +struct __pyx_memoryviewslice_obj { + struct __pyx_memoryview_obj __pyx_base; + __Pyx_memviewslice from_slice; + PyObject *from_object; + PyObject *(*to_object_func)(char *); + int (*to_dtype_func)(char *, PyObject *); +}; + + +/* "View.MemoryView":302 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ + +struct __pyx_vtabstruct_memoryview { + char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); + PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); +}; +static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; + + +/* "View.MemoryView":922 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ + +struct __pyx_vtabstruct__memoryviewslice { + struct __pyx_vtabstruct_memoryview __pyx_base; +}; +static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -630,10 +939,23 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -644,7 +966,7 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -654,179 +976,317 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) -#endif /* CYTHON_REFNANNY */ - -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +#endif +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ +static CYTHON_INLINE long __Pyx_mod_long(long, long); /* proto */ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); -/* Run-time type information about structs used with buffers */ -struct __Pyx_StructField_; +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename, + int full_traceback); -typedef struct { - const char* name; /* for error messages only */ - struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ -} __Pyx_TypeInfo; +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif -static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ -#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); +#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) +#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d +#define __Pyx_MEMVIEW_DIRECT 1 +#define __Pyx_MEMVIEW_PTR 2 +#define __Pyx_MEMVIEW_FULL 4 +#define __Pyx_MEMVIEW_CONTIG 8 +#define __Pyx_MEMVIEW_STRIDED 16 +#define __Pyx_MEMVIEW_FOLLOW 32 +#define __Pyx_IS_C_CONTIG 1 +#define __Pyx_IS_F_CONTIG 2 +static int __Pyx_init_memviewslice( + struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference); +static CYTHON_INLINE int __pyx_add_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) +#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) +#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) +#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) +static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); -#define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_List_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); -#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Tuple_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} +#include +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); -#define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { - PyObject *r; - if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) { - r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - } - else if (PyTuple_CheckExact(o) && ((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - } - else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0))) { - r = PySequence_GetItem(o, i); - } - else { - r = __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals +#else +#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals +#endif + +static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); /* proto */ + +#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) + +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); + +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; } - return r; + return PyList_Append(list, x); } +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif -#define __Pyx_SetItemInt(o, i, v, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_SetItemInt_Fast(o, i, v) : \ - __Pyx_SetItemInt_Generic(o, to_py_func(i), v)) - -static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { - int r; - if (!j) return -1; - r = PyObject_SetItem(o, j, v); - Py_DECREF(j); - return r; +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject* none = _PyList_Extend((PyListObject*)L, v); + if (unlikely(!none)) + return -1; + Py_DECREF(none); + return 0; +#else + return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); +#endif } -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v) { - if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) { - Py_INCREF(v); - Py_DECREF(PyList_GET_ITEM(o, i)); - PyList_SET_ITEM(o, i, v); - return 1; - } - else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && (likely(i >= 0))) - return PySequence_SetItem(o, i, v); - else { - PyObject *j = PyInt_FromSsize_t(i); - return __Pyx_SetItemInt_Generic(o, j, v); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; } + return PyList_Append(list, x); } -#define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +static CYTHON_INLINE long __Pyx_div_long(long, long); /* proto */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static int __Pyx_SetVtable(PyObject *dict, void *vtable); -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ #if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); -static void __Pyx_ReleaseBuffer(Py_buffer *view); + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); #else -#define __Pyx_GetBuffer PyObject_GetBuffer -#define __Pyx_ReleaseBuffer PyBuffer_Release + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release #endif -Py_ssize_t __Pyx_zeros[] = {0, 0}; -Py_ssize_t __Pyx_minusones[] = {-1, -1}; -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32); +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); + +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dcd__double(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value); + +static CYTHON_INLINE npy_uint32 __Pyx_PyInt_As_npy_uint32(PyObject *); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object); + +#define __pyx_memoryview_copy_slice_dc_double_c(slice) \ + __pyx_memoryview_copy_new_contig(&slice, "c", 1, \ + sizeof(double), (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), \ + 0) + +static PyObject *__pyx_memview_get_double(const char *itemp); +static int __pyx_memview_set_double(const char *itemp, PyObject *obj); #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -840,8 +1300,7 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - -#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else @@ -927,57 +1386,66 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); +static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim); -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); +static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize); -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(PyObject *); -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_double(PyObject *); -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); +static int __Pyx_check_binary_version(void); -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif -static int __Pyx_check_binary_version(void); +static PyObject *__Pyx_ImportModule(const char *name); -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto*/ +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj); /* proto*/ +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src); /* proto*/ +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value); /* proto*/ +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto*/ +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ +/* Module declarations from 'libc.math' */ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -988,16 +1456,10 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ -/* Module declarations from 'cython.cython.view' */ +/* Module declarations from 'cython.view' */ +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ /* Module declarations from 'cython' */ @@ -1019,8 +1481,6 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); / /* Module declarations from 'cpython.iterator' */ -/* Module declarations from 'cpython.type' */ - /* Module declarations from 'cpython.number' */ /* Module declarations from 'cpython.int' */ @@ -1072,205 +1532,653 @@ static PyTypeObject *__pyx_ptype_7cpython_7complex_complex = 0; /* Module declarations from 'cpython' */ /* Module declarations from 'sklearn.linear_model.cd_fast' */ +static PyTypeObject *__pyx_array_type = 0; +static PyTypeObject *__pyx_MemviewEnum_type = 0; +static PyTypeObject *__pyx_memoryview_type = 0; +static PyTypeObject *__pyx_memoryviewslice_type = 0; +static PyObject *generic = 0; +static PyObject *strided = 0; +static PyObject *indirect = 0; +static PyObject *contiguous = 0; +static PyObject *indirect_contiguous = 0; +static CYTHON_INLINE __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_f_7sklearn_12linear_model_7cd_fast_our_rand_r(__pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t *); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_f_7sklearn_12linear_model_7cd_fast_rand_int(__pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t, __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t *); /*proto*/ static CYTHON_INLINE double __pyx_f_7sklearn_12linear_model_7cd_fast_fmax(double, double); /*proto*/ static CYTHON_INLINE double __pyx_f_7sklearn_12linear_model_7cd_fast_fsign(double); /*proto*/ static double __pyx_f_7sklearn_12linear_model_7cd_fast_abs_max(int, double *); /*proto*/ +static double __pyx_f_7sklearn_12linear_model_7cd_fast_max(int, double *); /*proto*/ static double __pyx_f_7sklearn_12linear_model_7cd_fast_diff_abs_max(int, double *, double *); /*proto*/ -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE), 'R' }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER = { "INTEGER", NULL, sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER), 'I' }; +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ +static void *__pyx_align_pointer(void *, size_t); /*proto*/ +static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ +static PyObject *_unellipsify(PyObject *, int); /*proto*/ +static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ +static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ +static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ +static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ +static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ +static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ +static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ +static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 }; #define __Pyx_MODULE_NAME "sklearn.linear_model.cd_fast" int __pyx_module_is_main_sklearn__linear_model__cd_fast = 0; /* Implementation of 'sklearn.linear_model.cd_fast' */ -static PyObject *__pyx_builtin_xrange; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; -static char __pyx_k_2[] = "Coordinate descent with alpha=0 may lead to unexpected results and is discouraged."; -static char __pyx_k_6[] = "Coordinate descent with l1_reg=0 may lead to unexpected results and is discouraged."; -static char __pyx_k_8[] = "ndarray is not C contiguous"; -static char __pyx_k_10[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_12[] = "Non-native byte order not supported"; -static char __pyx_k_14[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_15[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_18[] = "Format string allocated too short."; -static char __pyx_k_20[] = "numpy.linalg"; -static char __pyx_k_21[] = "*"; -static char __pyx_k_22[] = "sklearn.linear_model.cd_fast"; -static char __pyx_k_23[] = "enet_coordinate_descent"; -static char __pyx_k_24[] = "sparse_enet_coordinate_descent"; -static char __pyx_k_25[] = "enet_coordinate_descent_gram"; -static char __pyx_k_26[] = "enet_coordinate_descent_multi_task"; -static char __pyx_k__B[] = "B"; -static char __pyx_k__C[] = "C"; -static char __pyx_k__H[] = "H"; -static char __pyx_k__I[] = "I"; -static char __pyx_k__L[] = "L"; -static char __pyx_k__O[] = "O"; -static char __pyx_k__Q[] = "Q"; -static char __pyx_k__T[] = "T"; -static char __pyx_k__W[] = "W"; -static char __pyx_k__X[] = "X"; -static char __pyx_k__Y[] = "Y"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__d[] = "d"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__g[] = "g"; -static char __pyx_k__h[] = "h"; -static char __pyx_k__i[] = "i"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__q[] = "q"; -static char __pyx_k__w[] = "w"; -static char __pyx_k__y[] = "y"; -static char __pyx_k__Zd[] = "Zd"; -static char __pyx_k__Zf[] = "Zf"; -static char __pyx_k__Zg[] = "Zg"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__any[] = "any"; -static char __pyx_k__dot[] = "dot"; -static char __pyx_k__inf[] = "inf"; -static char __pyx_k__max[] = "max"; -static char __pyx_k__sum[] = "sum"; -static char __pyx_k__tol[] = "tol"; -static char __pyx_k__axis[] = "axis"; -static char __pyx_k__beta[] = "beta"; -static char __pyx_k__copy[] = "copy"; -static char __pyx_k__norm[] = "norm"; -static char __pyx_k__sqrt[] = "sqrt"; -static char __pyx_k__warn[] = "warn"; -static char __pyx_k__alpha[] = "alpha"; -static char __pyx_k__dtype[] = "dtype"; -static char __pyx_k__float[] = "float"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__order[] = "order"; -static char __pyx_k__range[] = "range"; -static char __pyx_k__zeros[] = "zeros"; -static char __pyx_k__X_data[] = "X_data"; -static char __pyx_k__X_mean[] = "X_mean"; -static char __pyx_k__l1_reg[] = "l1_reg"; -static char __pyx_k__l2_reg[] = "l2_reg"; -static char __pyx_k__linalg[] = "linalg"; -static char __pyx_k__xrange[] = "xrange"; -static char __pyx_k__asarray[] = "asarray"; -static char __pyx_k__float64[] = "float64"; -static char __pyx_k__X_indptr[] = "X_indptr"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__max_iter[] = "max_iter"; -static char __pyx_k__positive[] = "positive"; -static char __pyx_k__warnings[] = "warnings"; -static char __pyx_k__X_indices[] = "X_indices"; -static char __pyx_k__n_samples[] = "n_samples"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__n_features[] = "n_features"; -static char __pyx_k__sparse_std[] = "sparse_std"; -static char __pyx_k__RuntimeError[] = "RuntimeError"; -static PyObject *__pyx_kp_u_10; -static PyObject *__pyx_kp_u_12; -static PyObject *__pyx_kp_u_14; -static PyObject *__pyx_kp_u_15; -static PyObject *__pyx_kp_u_18; -static PyObject *__pyx_kp_s_2; -static PyObject *__pyx_n_s_20; -static PyObject *__pyx_n_s_21; -static PyObject *__pyx_n_s_22; -static PyObject *__pyx_n_s_23; -static PyObject *__pyx_n_s_24; -static PyObject *__pyx_n_s_25; -static PyObject *__pyx_n_s_26; -static PyObject *__pyx_kp_s_6; -static PyObject *__pyx_kp_u_8; -static PyObject *__pyx_n_s__C; -static PyObject *__pyx_n_s__Q; -static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__T; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s__W; -static PyObject *__pyx_n_s__X; -static PyObject *__pyx_n_s__X_data; -static PyObject *__pyx_n_s__X_indices; -static PyObject *__pyx_n_s__X_indptr; -static PyObject *__pyx_n_s__X_mean; -static PyObject *__pyx_n_s__Y; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__alpha; -static PyObject *__pyx_n_s__any; -static PyObject *__pyx_n_s__asarray; -static PyObject *__pyx_n_s__axis; -static PyObject *__pyx_n_s__beta; -static PyObject *__pyx_n_s__copy; -static PyObject *__pyx_n_s__dot; -static PyObject *__pyx_n_s__dtype; -static PyObject *__pyx_n_s__float; -static PyObject *__pyx_n_s__float64; -static PyObject *__pyx_n_s__inf; -static PyObject *__pyx_n_s__l1_reg; -static PyObject *__pyx_n_s__l2_reg; -static PyObject *__pyx_n_s__linalg; -static PyObject *__pyx_n_s__max; -static PyObject *__pyx_n_s__max_iter; -static PyObject *__pyx_n_s__n_features; -static PyObject *__pyx_n_s__n_samples; -static PyObject *__pyx_n_s__norm; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__order; -static PyObject *__pyx_n_s__positive; -static PyObject *__pyx_n_s__q; -static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__sparse_std; -static PyObject *__pyx_n_s__sqrt; -static PyObject *__pyx_n_s__sum; -static PyObject *__pyx_n_s__tol; -static PyObject *__pyx_n_s__w; -static PyObject *__pyx_n_s__warn; -static PyObject *__pyx_n_s__warnings; -static PyObject *__pyx_n_s__xrange; -static PyObject *__pyx_n_s__y; -static PyObject *__pyx_n_s__zeros; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_Ellipsis; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_xrange; +static PyObject *__pyx_builtin_id; +static PyObject *__pyx_builtin_IndexError; +static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_enet_coordinate_descent(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_w, double __pyx_v_alpha, double __pyx_v_beta, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_y, int __pyx_v_max_iter, double __pyx_v_tol, PyObject *__pyx_v_rng, int __pyx_v_random, int __pyx_v_positive); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordinate_descent(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_w, double __pyx_v_alpha, double __pyx_v_beta, __Pyx_memviewslice __pyx_v_X_data, __Pyx_memviewslice __pyx_v_X_indices, __Pyx_memviewslice __pyx_v_X_indptr, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_X_mean, int __pyx_v_max_iter, double __pyx_v_tol, PyObject *__pyx_v_rng, int __pyx_v_random, int __pyx_v_positive); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_gram(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_w, double __pyx_v_alpha, double __pyx_v_beta, __Pyx_memviewslice __pyx_v_Q, __Pyx_memviewslice __pyx_v_q, __Pyx_memviewslice __pyx_v_y, int __pyx_v_max_iter, double __pyx_v_tol, PyObject *__pyx_v_rng, int __pyx_v_random, int __pyx_v_positive); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_6enet_coordinate_descent_multi_task(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_W, double __pyx_v_l1_reg, double __pyx_v_l2_reg, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, int __pyx_v_max_iter, double __pyx_v_tol, PyObject *__pyx_v_rng, int __pyx_v_random); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_B[] = "B"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_R[] = "R"; +static char __pyx_k_W[] = "W"; +static char __pyx_k_X[] = "X"; +static char __pyx_k_Y[] = "Y"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_c[] = "c"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_w[] = "w"; +static char __pyx_k_y[] = "y"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_id[] = "id"; +static char __pyx_k_ii[] = "ii"; +static char __pyx_k_jj[] = "jj"; +static char __pyx_k_nn[] = "nn"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_XtA[] = "XtA"; +static char __pyx_k__21[] = "*"; +static char __pyx_k_dot[] = "dot"; +static char __pyx_k_gap[] = "gap"; +static char __pyx_k_obj[] = "obj"; +static char __pyx_k_rng[] = "rng"; +static char __pyx_k_sum[] = "sum"; +static char __pyx_k_tmp[] = "tmp"; +static char __pyx_k_tol[] = "tol"; +static char __pyx_k_axis[] = "axis"; +static char __pyx_k_base[] = "base"; +static char __pyx_k_beta[] = "beta"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_mode[] = "mode"; +static char __pyx_k_name[] = "name"; +static char __pyx_k_ndim[] = "ndim"; +static char __pyx_k_pack[] = "pack"; +static char __pyx_k_size[] = "size"; +static char __pyx_k_step[] = "step"; +static char __pyx_k_stop[] = "stop"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_w_ii[] = "w_ii"; +static char __pyx_k_warn[] = "warn"; +static char __pyx_k_H_ptr[] = "H_ptr"; +static char __pyx_k_Q_ptr[] = "Q_ptr"; +static char __pyx_k_R_sum[] = "R_sum"; +static char __pyx_k_W_ptr[] = "W_ptr"; +static char __pyx_k_X_T_R[] = "X_T_R"; +static char __pyx_k_X_ptr[] = "X_ptr"; +static char __pyx_k_Y_ptr[] = "Y_ptr"; +static char __pyx_k_alpha[] = "alpha"; +static char __pyx_k_class[] = "__class__"; +static char __pyx_k_const[] = "const"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_empty[] = "empty"; +static char __pyx_k_error[] = "error"; +static char __pyx_k_flags[] = "flags"; +static char __pyx_k_float[] = "float"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_shape[] = "shape"; +static char __pyx_k_start[] = "start"; +static char __pyx_k_w_max[] = "w_max"; +static char __pyx_k_zeros[] = "zeros"; +static char __pyx_k_A_norm[] = "A_norm"; +static char __pyx_k_R_norm[] = "R_norm"; +static char __pyx_k_X_data[] = "X_data"; +static char __pyx_k_X_mean[] = "X_mean"; +static char __pyx_k_center[] = "center"; +static char __pyx_k_d_w_ii[] = "d_w_ii"; +static char __pyx_k_endptr[] = "endptr"; +static char __pyx_k_f_iter[] = "f_iter"; +static char __pyx_k_format[] = "format"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_l1_reg[] = "l1_reg"; +static char __pyx_k_l2_reg[] = "l2_reg"; +static char __pyx_k_linalg[] = "linalg"; +static char __pyx_k_n_iter[] = "n_iter"; +static char __pyx_k_name_2[] = "__name__"; +static char __pyx_k_random[] = "random"; +static char __pyx_k_ry_sum[] = "ry_sum"; +static char __pyx_k_struct[] = "struct"; +static char __pyx_k_unpack[] = "unpack"; +static char __pyx_k_w_norm[] = "w_norm"; +static char __pyx_k_xrange[] = "xrange"; +static char __pyx_k_A_norm2[] = "A_norm2"; +static char __pyx_k_R_norm2[] = "R_norm2"; +static char __pyx_k_XtA_ptr[] = "XtA_ptr"; +static char __pyx_k_asarray[] = "asarray"; +static char __pyx_k_d_w_max[] = "d_w_max"; +static char __pyx_k_d_w_tol[] = "d_w_tol"; +static char __pyx_k_float64[] = "float64"; +static char __pyx_k_fortran[] = "fortran"; +static char __pyx_k_l1_norm[] = "l1_norm"; +static char __pyx_k_memview[] = "memview"; +static char __pyx_k_n_tasks[] = "n_tasks"; +static char __pyx_k_q_dot_w[] = "q_dot_w"; +static char __pyx_k_randint[] = "randint"; +static char __pyx_k_w_norm2[] = "w_norm2"; +static char __pyx_k_wii_ptr[] = "wii_ptr"; +static char __pyx_k_y_norm2[] = "y_norm2"; +static char __pyx_k_Ellipsis[] = "Ellipsis"; +static char __pyx_k_X_indptr[] = "X_indptr"; +static char __pyx_k_itemsize[] = "itemsize"; +static char __pyx_k_l21_norm[] = "l21_norm"; +static char __pyx_k_max_iter[] = "max_iter"; +static char __pyx_k_positive[] = "positive"; +static char __pyx_k_startptr[] = "startptr"; +static char __pyx_k_warnings[] = "warnings"; +static char __pyx_k_TypeError[] = "TypeError"; +static char __pyx_k_X_indices[] = "X_indices"; +static char __pyx_k_X_mean_ii[] = "X_mean_ii"; +static char __pyx_k_enumerate[] = "enumerate"; +static char __pyx_k_n_samples[] = "n_samples"; +static char __pyx_k_IndexError[] = "IndexError"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_n_features[] = "n_features"; +static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static char __pyx_k_MemoryError[] = "MemoryError"; +static char __pyx_k_norm_cols_X[] = "norm_cols_X"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_W_ii_abs_max[] = "W_ii_abs_max"; +static char __pyx_k_numpy_linalg[] = "numpy.linalg"; +static char __pyx_k_rand_r_state[] = "rand_r_state"; +static char __pyx_k_XtA_axis1norm[] = "XtA_axis1norm"; +static char __pyx_k_dual_norm_XtA[] = "dual_norm_XtA"; +static char __pyx_k_normalize_sum[] = "normalize_sum"; +static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k_allocate_buffer[] = "allocate_buffer"; +static char __pyx_k_dtype_is_object[] = "dtype_is_object"; +static char __pyx_k_rand_r_state_seed[] = "rand_r_state_seed"; +static char __pyx_k_strided_and_direct[] = ""; +static char __pyx_k_strided_and_indirect[] = ""; +static char __pyx_k_contiguous_and_direct[] = ""; +static char __pyx_k_MemoryView_of_r_object[] = ""; +static char __pyx_k_MemoryView_of_r_at_0x_x[] = ""; +static char __pyx_k_contiguous_and_indirect[] = ""; +static char __pyx_k_enet_coordinate_descent[] = "enet_coordinate_descent"; +static char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; +static char __pyx_k_getbuffer_obj_view_flags[] = "getbuffer(obj, view, flags)"; +static char __pyx_k_Dimension_d_is_not_direct[] = "Dimension %d is not direct"; +static char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; +static char __pyx_k_Index_out_of_bounds_axis_d[] = "Index out of bounds (axis %d)"; +static char __pyx_k_Step_may_not_be_zero_axis_d[] = "Step may not be zero (axis %d)"; +static char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_enet_coordinate_descent_gram[] = "enet_coordinate_descent_gram"; +static char __pyx_k_sklearn_linear_model_cd_fast[] = "sklearn.linear_model.cd_fast"; +static char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; +static char __pyx_k_sparse_enet_coordinate_descent[] = "sparse_enet_coordinate_descent"; +static char __pyx_k_strided_and_direct_or_indirect[] = ""; +static char __pyx_k_Coordinate_descent_with_alpha_0[] = "Coordinate descent with alpha=0 may lead to unexpected results and is discouraged."; +static char __pyx_k_Users_alex_work_src_scikit_lear[] = "/Users/alex/work/src/scikit-learn/sklearn/linear_model/cd_fast.pyx"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_All_dimensions_preceding_dimensi[] = "All dimensions preceding dimension %d must be indexed and not sliced"; +static char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; +static char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; +static char __pyx_k_Cannot_transpose_memoryview_with[] = "Cannot transpose memoryview with indirect dimensions"; +static char __pyx_k_Coordinate_descent_with_l1_reg_0[] = "Coordinate descent with l1_reg=0 may lead to unexpected results and is discouraged."; +static char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; +static char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; +static char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; +static char __pyx_k_enet_coordinate_descent_multi_ta[] = "enet_coordinate_descent_multi_task"; +static char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_n_s_A_norm; +static PyObject *__pyx_n_s_A_norm2; +static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; +static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; +static PyObject *__pyx_kp_s_Cannot_index_with_type_s; +static PyObject *__pyx_kp_s_Coordinate_descent_with_alpha_0; +static PyObject *__pyx_kp_s_Coordinate_descent_with_l1_reg_0; +static PyObject *__pyx_n_s_Ellipsis; +static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_n_s_H; +static PyObject *__pyx_n_s_H_ptr; +static PyObject *__pyx_n_s_IndexError; +static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; +static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; +static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; +static PyObject *__pyx_n_s_MemoryError; +static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; +static PyObject *__pyx_kp_s_MemoryView_of_r_object; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_b_O; +static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; +static PyObject *__pyx_n_s_Q; +static PyObject *__pyx_n_s_Q_ptr; +static PyObject *__pyx_n_s_R; +static PyObject *__pyx_n_s_R_norm; +static PyObject *__pyx_n_s_R_norm2; +static PyObject *__pyx_n_s_R_sum; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_TypeError; +static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; +static PyObject *__pyx_kp_s_Users_alex_work_src_scikit_lear; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_W; +static PyObject *__pyx_n_s_W_ii_abs_max; +static PyObject *__pyx_n_s_W_ptr; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_n_s_X_T_R; +static PyObject *__pyx_n_s_X_data; +static PyObject *__pyx_n_s_X_indices; +static PyObject *__pyx_n_s_X_indptr; +static PyObject *__pyx_n_s_X_mean; +static PyObject *__pyx_n_s_X_mean_ii; +static PyObject *__pyx_n_s_X_ptr; +static PyObject *__pyx_n_s_XtA; +static PyObject *__pyx_n_s_XtA_axis1norm; +static PyObject *__pyx_n_s_XtA_ptr; +static PyObject *__pyx_n_s_Y; +static PyObject *__pyx_n_s_Y_ptr; +static PyObject *__pyx_n_s__21; +static PyObject *__pyx_n_s_allocate_buffer; +static PyObject *__pyx_n_s_alpha; +static PyObject *__pyx_n_s_asarray; +static PyObject *__pyx_n_s_axis; +static PyObject *__pyx_n_s_base; +static PyObject *__pyx_n_s_beta; +static PyObject *__pyx_n_s_c; +static PyObject *__pyx_n_u_c; +static PyObject *__pyx_n_s_center; +static PyObject *__pyx_n_s_class; +static PyObject *__pyx_n_s_const; +static PyObject *__pyx_kp_s_contiguous_and_direct; +static PyObject *__pyx_kp_s_contiguous_and_indirect; +static PyObject *__pyx_n_s_d_w_ii; +static PyObject *__pyx_n_s_d_w_max; +static PyObject *__pyx_n_s_d_w_tol; +static PyObject *__pyx_n_s_dot; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_dtype_is_object; +static PyObject *__pyx_n_s_dual_norm_XtA; +static PyObject *__pyx_n_s_empty; +static PyObject *__pyx_n_s_endptr; +static PyObject *__pyx_n_s_enet_coordinate_descent; +static PyObject *__pyx_n_s_enet_coordinate_descent_gram; +static PyObject *__pyx_n_s_enet_coordinate_descent_multi_ta; +static PyObject *__pyx_n_s_enumerate; +static PyObject *__pyx_n_s_error; +static PyObject *__pyx_n_s_f_iter; +static PyObject *__pyx_n_s_flags; +static PyObject *__pyx_n_s_float; +static PyObject *__pyx_n_s_float64; +static PyObject *__pyx_n_s_format; +static PyObject *__pyx_n_s_fortran; +static PyObject *__pyx_n_u_fortran; +static PyObject *__pyx_n_s_gap; +static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; +static PyObject *__pyx_n_s_i; +static PyObject *__pyx_n_s_id; +static PyObject *__pyx_n_s_ii; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_itemsize; +static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; +static PyObject *__pyx_n_s_jj; +static PyObject *__pyx_n_s_l1_norm; +static PyObject *__pyx_n_s_l1_reg; +static PyObject *__pyx_n_s_l21_norm; +static PyObject *__pyx_n_s_l2_reg; +static PyObject *__pyx_n_s_linalg; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_max_iter; +static PyObject *__pyx_n_s_memview; +static PyObject *__pyx_n_s_mode; +static PyObject *__pyx_n_s_n_features; +static PyObject *__pyx_n_s_n_iter; +static PyObject *__pyx_n_s_n_samples; +static PyObject *__pyx_n_s_n_tasks; +static PyObject *__pyx_n_s_name; +static PyObject *__pyx_n_s_name_2; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_ndim; +static PyObject *__pyx_n_s_nn; +static PyObject *__pyx_n_s_norm_cols_X; +static PyObject *__pyx_n_s_normalize_sum; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_numpy_linalg; +static PyObject *__pyx_n_s_obj; +static PyObject *__pyx_n_s_pack; +static PyObject *__pyx_n_s_positive; +static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_vtable; +static PyObject *__pyx_n_s_q; +static PyObject *__pyx_n_s_q_dot_w; +static PyObject *__pyx_n_s_rand_r_state; +static PyObject *__pyx_n_s_rand_r_state_seed; +static PyObject *__pyx_n_s_randint; +static PyObject *__pyx_n_s_random; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_rng; +static PyObject *__pyx_n_s_ry_sum; +static PyObject *__pyx_n_s_shape; +static PyObject *__pyx_n_s_size; +static PyObject *__pyx_n_s_sklearn_linear_model_cd_fast; +static PyObject *__pyx_n_s_sparse_enet_coordinate_descent; +static PyObject *__pyx_n_s_start; +static PyObject *__pyx_n_s_startptr; +static PyObject *__pyx_n_s_step; +static PyObject *__pyx_n_s_stop; +static PyObject *__pyx_kp_s_strided_and_direct; +static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; +static PyObject *__pyx_kp_s_strided_and_indirect; +static PyObject *__pyx_n_s_struct; +static PyObject *__pyx_n_s_sum; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_n_s_tmp; +static PyObject *__pyx_n_s_tol; +static PyObject *__pyx_kp_s_unable_to_allocate_array_data; +static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_unpack; +static PyObject *__pyx_n_s_w; +static PyObject *__pyx_n_s_w_ii; +static PyObject *__pyx_n_s_w_max; +static PyObject *__pyx_n_s_w_norm; +static PyObject *__pyx_n_s_w_norm2; +static PyObject *__pyx_n_s_warn; +static PyObject *__pyx_n_s_warnings; +static PyObject *__pyx_n_s_wii_ptr; +static PyObject *__pyx_n_s_xrange; +static PyObject *__pyx_n_s_y; +static PyObject *__pyx_n_s_y_norm2; +static PyObject *__pyx_n_s_zeros; static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_2; -static PyObject *__pyx_int_15; -static PyBoolObject *__pyx_k_1; -static PyBoolObject *__pyx_k_4; -static PyObject *__pyx_k_tuple_3; -static PyObject *__pyx_k_tuple_5; -static PyObject *__pyx_k_tuple_7; -static PyObject *__pyx_k_tuple_9; -static PyObject *__pyx_k_tuple_11; -static PyObject *__pyx_k_tuple_13; -static PyObject *__pyx_k_tuple_16; -static PyObject *__pyx_k_tuple_17; -static PyObject *__pyx_k_tuple_19; +static PyObject *__pyx_int_neg_1; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__8; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_slice__17; +static PyObject *__pyx_slice__18; +static PyObject *__pyx_slice__19; +static PyObject *__pyx_tuple__10; +static PyObject *__pyx_tuple__11; +static PyObject *__pyx_tuple__12; +static PyObject *__pyx_tuple__13; +static PyObject *__pyx_tuple__14; +static PyObject *__pyx_tuple__15; +static PyObject *__pyx_tuple__16; +static PyObject *__pyx_tuple__20; +static PyObject *__pyx_tuple__22; +static PyObject *__pyx_tuple__24; +static PyObject *__pyx_tuple__26; +static PyObject *__pyx_tuple__28; +static PyObject *__pyx_tuple__30; +static PyObject *__pyx_tuple__31; +static PyObject *__pyx_tuple__32; +static PyObject *__pyx_tuple__33; +static PyObject *__pyx_tuple__34; +static PyObject *__pyx_codeobj__23; +static PyObject *__pyx_codeobj__25; +static PyObject *__pyx_codeobj__27; +static PyObject *__pyx_codeobj__29; + +/* "sklearn/linear_model/cd_fast.pyx":32 + * + * + * cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil: # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) + */ + +static CYTHON_INLINE __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_f_7sklearn_12linear_model_7cd_fast_our_rand_r(__pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t *__pyx_v_seed) { + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_r; + long __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; -/* "sklearn/linear_model/cd_fast.pyx":19 - * double sqrt(double f) + /* "sklearn/linear_model/cd_fast.pyx":33 + * + * cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil: + * seed[0] ^= (seed[0] << 13) # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] >> 17) + * seed[0] ^= (seed[0] << 5) + */ + __pyx_t_1 = 0; + (__pyx_v_seed[__pyx_t_1]) = ((__pyx_v_seed[__pyx_t_1]) ^ ((__pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t)((__pyx_v_seed[0]) << 13))); + + /* "sklearn/linear_model/cd_fast.pyx":34 + * cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil: + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] << 5) + * + */ + __pyx_t_1 = 0; + (__pyx_v_seed[__pyx_t_1]) = ((__pyx_v_seed[__pyx_t_1]) ^ ((__pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t)((__pyx_v_seed[0]) >> 17))); + + /* "sklearn/linear_model/cd_fast.pyx":35 + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) + * seed[0] ^= (seed[0] << 5) # <<<<<<<<<<<<<< + * + * return seed[0] % (RAND_R_MAX + 1) + */ + __pyx_t_1 = 0; + (__pyx_v_seed[__pyx_t_1]) = ((__pyx_v_seed[__pyx_t_1]) ^ ((__pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t)((__pyx_v_seed[0]) << 5))); + + /* "sklearn/linear_model/cd_fast.pyx":37 + * seed[0] ^= (seed[0] << 5) + * + * return seed[0] % (RAND_R_MAX + 1) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = (((__pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t)__pyx_e_7sklearn_12linear_model_7cd_fast_RAND_R_MAX) + 1); + if (unlikely(__pyx_t_1 == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_r = __Pyx_mod_long((__pyx_v_seed[0]), __pyx_t_1); + goto __pyx_L0; + + /* "sklearn/linear_model/cd_fast.pyx":32 + * + * + * cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil: # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_WriteUnraisable("sklearn.linear_model.cd_fast.our_rand_r", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/linear_model/cd_fast.pyx":40 + * + * + * cdef inline UINT32_t rand_int(UINT32_t end, UINT32_t* random_state) nogil: # <<<<<<<<<<<<<< + * """Generate a random integer in [0; end).""" + * return our_rand_r(random_state) % end + */ + +static CYTHON_INLINE __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_f_7sklearn_12linear_model_7cd_fast_rand_int(__pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_v_end, __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t *__pyx_v_random_state) { + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_r; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "sklearn/linear_model/cd_fast.pyx":42 + * cdef inline UINT32_t rand_int(UINT32_t end, UINT32_t* random_state) nogil: + * """Generate a random integer in [0; end).""" + * return our_rand_r(random_state) % end # <<<<<<<<<<<<<< * - * cdef inline double fmax(double x, double y): # <<<<<<<<<<<<<< + * + */ + __pyx_t_1 = __pyx_f_7sklearn_12linear_model_7cd_fast_our_rand_r(__pyx_v_random_state); + if (unlikely(__pyx_v_end == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_r = (__pyx_t_1 % __pyx_v_end); + goto __pyx_L0; + + /* "sklearn/linear_model/cd_fast.pyx":40 + * + * + * cdef inline UINT32_t rand_int(UINT32_t end, UINT32_t* random_state) nogil: # <<<<<<<<<<<<<< + * """Generate a random integer in [0; end).""" + * return our_rand_r(random_state) % end + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_WriteUnraisable("sklearn.linear_model.cd_fast.rand_int", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/linear_model/cd_fast.pyx":45 + * + * + * cdef inline double fmax(double x, double y) nogil: # <<<<<<<<<<<<<< * if x > y: * return x */ static CYTHON_INLINE double __pyx_f_7sklearn_12linear_model_7cd_fast_fmax(double __pyx_v_x, double __pyx_v_y) { double __pyx_r; - __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("fmax"); - /* "sklearn/linear_model/cd_fast.pyx":20 + /* "sklearn/linear_model/cd_fast.pyx":46 * - * cdef inline double fmax(double x, double y): + * cdef inline double fmax(double x, double y) nogil: * if x > y: # <<<<<<<<<<<<<< * return x * return y */ - __pyx_t_1 = (__pyx_v_x > __pyx_v_y); + __pyx_t_1 = ((__pyx_v_x > __pyx_v_y) != 0); if (__pyx_t_1) { - /* "sklearn/linear_model/cd_fast.pyx":21 - * cdef inline double fmax(double x, double y): + /* "sklearn/linear_model/cd_fast.pyx":47 + * cdef inline double fmax(double x, double y) nogil: * if x > y: * return x # <<<<<<<<<<<<<< * return y @@ -1278,52 +2186,55 @@ static CYTHON_INLINE double __pyx_f_7sklearn_12linear_model_7cd_fast_fmax(double */ __pyx_r = __pyx_v_x; goto __pyx_L0; - goto __pyx_L3; } - __pyx_L3:; - /* "sklearn/linear_model/cd_fast.pyx":22 + /* "sklearn/linear_model/cd_fast.pyx":48 * if x > y: * return x * return y # <<<<<<<<<<<<<< * - * cdef inline double fsign(double f): + * */ __pyx_r = __pyx_v_y; goto __pyx_L0; - __pyx_r = 0; + /* "sklearn/linear_model/cd_fast.pyx":45 + * + * + * cdef inline double fmax(double x, double y) nogil: # <<<<<<<<<<<<<< + * if x > y: + * return x + */ + + /* function exit code */ __pyx_L0:; - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/cd_fast.pyx":24 - * return y +/* "sklearn/linear_model/cd_fast.pyx":51 * - * cdef inline double fsign(double f): # <<<<<<<<<<<<<< + * + * cdef inline double fsign(double f) nogil: # <<<<<<<<<<<<<< * if f == 0: * return 0 */ static CYTHON_INLINE double __pyx_f_7sklearn_12linear_model_7cd_fast_fsign(double __pyx_v_f) { double __pyx_r; - __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("fsign"); - /* "sklearn/linear_model/cd_fast.pyx":25 + /* "sklearn/linear_model/cd_fast.pyx":52 * - * cdef inline double fsign(double f): + * cdef inline double fsign(double f) nogil: * if f == 0: # <<<<<<<<<<<<<< * return 0 * elif f > 0: */ - __pyx_t_1 = (__pyx_v_f == 0.0); + __pyx_t_1 = ((__pyx_v_f == 0.0) != 0); if (__pyx_t_1) { - /* "sklearn/linear_model/cd_fast.pyx":26 - * cdef inline double fsign(double f): + /* "sklearn/linear_model/cd_fast.pyx":53 + * cdef inline double fsign(double f) nogil: * if f == 0: * return 0 # <<<<<<<<<<<<<< * elif f > 0: @@ -1331,20 +2242,19 @@ static CYTHON_INLINE double __pyx_f_7sklearn_12linear_model_7cd_fast_fsign(doubl */ __pyx_r = 0.0; goto __pyx_L0; - goto __pyx_L3; } - /* "sklearn/linear_model/cd_fast.pyx":27 + /* "sklearn/linear_model/cd_fast.pyx":54 * if f == 0: * return 0 * elif f > 0: # <<<<<<<<<<<<<< * return 1.0 * else: */ - __pyx_t_1 = (__pyx_v_f > 0.0); + __pyx_t_1 = ((__pyx_v_f > 0.0) != 0); if (__pyx_t_1) { - /* "sklearn/linear_model/cd_fast.pyx":28 + /* "sklearn/linear_model/cd_fast.pyx":55 * return 0 * elif f > 0: * return 1.0 # <<<<<<<<<<<<<< @@ -1353,542 +2263,310 @@ static CYTHON_INLINE double __pyx_f_7sklearn_12linear_model_7cd_fast_fsign(doubl */ __pyx_r = 1.0; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":30 + /* "sklearn/linear_model/cd_fast.pyx":57 * return 1.0 * else: * return -1.0 # <<<<<<<<<<<<<< * - * cdef extern from "cblas.h": + * */ __pyx_r = -1.0; goto __pyx_L0; } - __pyx_L3:; - __pyx_r = 0; + /* "sklearn/linear_model/cd_fast.pyx":51 + * + * + * cdef inline double fsign(double f) nogil: # <<<<<<<<<<<<<< + * if f == 0: + * return 0 + */ + + /* function exit code */ __pyx_L0:; - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/cd_fast.pyx":64 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def sparse_std(unsigned int n_samples, # <<<<<<<<<<<<<< - * unsigned int n_features, - * np.ndarray[DOUBLE, ndim=1] X_data, +/* "sklearn/linear_model/cd_fast.pyx":60 + * + * + * cdef double abs_max(int n, double* a) nogil: # <<<<<<<<<<<<<< + * """np.max(np.abs(a))""" + * cdef int i */ -static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_sparse_std(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7sklearn_12linear_model_7cd_fast_sparse_std = {__Pyx_NAMESTR("sparse_std"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_7cd_fast_sparse_std, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; -static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_sparse_std(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - PyArrayObject *__pyx_v_X_data = 0; - PyArrayObject *__pyx_v_X_indices = 0; - PyArrayObject *__pyx_v_X_indptr = 0; - PyArrayObject *__pyx_v_X_mean = 0; - unsigned int __pyx_v_ii; - unsigned int __pyx_v_jj; - unsigned int __pyx_v_nnz_ii; - double __pyx_v_X_sum_ii; - double __pyx_v_X_mean_ii; - double __pyx_v_diff; - PyArrayObject *__pyx_v_X_std = 0; - Py_buffer __pyx_bstruct_X_std; - Py_ssize_t __pyx_bstride_0_X_std = 0; - Py_ssize_t __pyx_bshape_0_X_std = 0; - Py_buffer __pyx_bstruct_X_mean; - Py_ssize_t __pyx_bstride_0_X_mean = 0; - Py_ssize_t __pyx_bshape_0_X_mean = 0; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyArrayObject *__pyx_t_5 = NULL; - int __pyx_t_6; - PyArrayObject *__pyx_t_7 = NULL; - int __pyx_t_8; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - unsigned int __pyx_t_12; - unsigned int __pyx_t_13; - long __pyx_t_14; - __pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER __pyx_t_15; - unsigned int __pyx_t_16; - unsigned int __pyx_t_17; - unsigned int __pyx_t_18; - unsigned int __pyx_t_19; - long __pyx_t_20; - unsigned int __pyx_t_21; - unsigned int __pyx_t_22; - unsigned int __pyx_t_23; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_samples,&__pyx_n_s__n_features,&__pyx_n_s__X_data,&__pyx_n_s__X_indices,&__pyx_n_s__X_indptr,&__pyx_n_s__X_mean,0}; - __Pyx_RefNannySetupContext("sparse_std"); - __pyx_self = __pyx_self; - { - PyObject* values[6] = {0,0,0,0,0,0}; +static double __pyx_f_7sklearn_12linear_model_7cd_fast_abs_max(int __pyx_v_n, double *__pyx_v_a) { + int __pyx_v_i; + double __pyx_v_m; + double __pyx_v_d; + double __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; - /* "sklearn/linear_model/cd_fast.pyx":69 - * np.ndarray[INTEGER, ndim=1] X_indices, - * np.ndarray[INTEGER, ndim=1] X_indptr, - * np.ndarray[DOUBLE, ndim=1] X_mean=None): # <<<<<<<<<<<<<< - * cdef unsigned int ii - * cdef unsigned int jj + /* "sklearn/linear_model/cd_fast.pyx":63 + * """np.max(np.abs(a))""" + * cdef int i + * cdef double m = fabs(a[0]) # <<<<<<<<<<<<<< + * cdef double d + * for i in range(1, n): */ - values[5] = (PyObject *)((PyArrayObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_samples); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_features); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("sparse_std", 0, 5, 6, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_data); - if (likely(values[2])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("sparse_std", 0, 5, 6, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_indices); - if (likely(values[3])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("sparse_std", 0, 5, 6, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_indptr); - if (likely(values[4])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("sparse_std", 0, 5, 6, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 5: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_mean); - if (value) { values[5] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "sparse_std") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_n_samples = __Pyx_PyInt_AsUnsignedInt(values[0]); if (unlikely((__pyx_v_n_samples == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_n_features = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_n_features == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_X_data = ((PyArrayObject *)values[2]); - __pyx_v_X_indices = ((PyArrayObject *)values[3]); - __pyx_v_X_indptr = ((PyArrayObject *)values[4]); - __pyx_v_X_mean = ((PyArrayObject *)values[5]); - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("sparse_std", 0, 5, 6, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.cd_fast.sparse_std", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_INCREF((PyObject *)__pyx_v_X_mean); - __pyx_bstruct_X_std.buf = NULL; - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; - __pyx_bstruct_X_mean.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_data), __pyx_ptype_5numpy_ndarray, 1, "X_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_indices), __pyx_ptype_5numpy_ndarray, 1, "X_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_indptr), __pyx_ptype_5numpy_ndarray, 1, "X_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_mean), __pyx_ptype_5numpy_ndarray, 1, "X_mean", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_v_X_data, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_v_X_indices, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_v_X_indptr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_mean, (PyObject*)__pyx_v_X_mean, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_X_mean = __pyx_bstruct_X_mean.strides[0]; - __pyx_bshape_0_X_mean = __pyx_bstruct_X_mean.shape[0]; + __pyx_v_m = fabs((__pyx_v_a[0])); - /* "sklearn/linear_model/cd_fast.pyx":78 - * cdef double X_std_ii - * - * cdef np.ndarray[DOUBLE, ndim = 1] X_std = np.zeros(n_features, np.float64) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":65 + * cdef double m = fabs(a[0]) + * cdef double d + * for i in range(1, n): # <<<<<<<<<<<<<< + * d = fabs(a[i]) + * if d > m: + */ + __pyx_t_1 = __pyx_v_n; + for (__pyx_t_2 = 1; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "sklearn/linear_model/cd_fast.pyx":66 + * cdef double d + * for i in range(1, n): + * d = fabs(a[i]) # <<<<<<<<<<<<<< + * if d > m: + * m = d + */ + __pyx_v_d = fabs((__pyx_v_a[__pyx_v_i])); + + /* "sklearn/linear_model/cd_fast.pyx":67 + * for i in range(1, n): + * d = fabs(a[i]) + * if d > m: # <<<<<<<<<<<<<< + * m = d + * return m + */ + __pyx_t_3 = ((__pyx_v_d > __pyx_v_m) != 0); + if (__pyx_t_3) { + + /* "sklearn/linear_model/cd_fast.pyx":68 + * d = fabs(a[i]) + * if d > m: + * m = d # <<<<<<<<<<<<<< + * return m * - * if X_mean is None: */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyLong_FromUnsignedLong(__pyx_v_n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_1 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = ((PyArrayObject *)__pyx_t_4); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_std, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_std = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_std.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_std = __pyx_bstruct_X_std.strides[0]; - __pyx_bshape_0_X_std = __pyx_bstruct_X_std.shape[0]; + __pyx_v_m = __pyx_v_d; + goto __pyx_L5; } + __pyx_L5:; } - __pyx_t_5 = 0; - __pyx_v_X_std = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; - /* "sklearn/linear_model/cd_fast.pyx":80 - * cdef np.ndarray[DOUBLE, ndim = 1] X_std = np.zeros(n_features, np.float64) + /* "sklearn/linear_model/cd_fast.pyx":69 + * if d > m: + * m = d + * return m # <<<<<<<<<<<<<< * - * if X_mean is None: # <<<<<<<<<<<<<< - * X_mean = np.zeros(n_features, np.float64) * */ - __pyx_t_6 = (((PyObject *)__pyx_v_X_mean) == Py_None); - if (__pyx_t_6) { + __pyx_r = __pyx_v_m; + goto __pyx_L0; - /* "sklearn/linear_model/cd_fast.pyx":81 + /* "sklearn/linear_model/cd_fast.pyx":60 * - * if X_mean is None: - * X_mean = np.zeros(n_features, np.float64) # <<<<<<<<<<<<<< * - * for ii in xrange(n_features): + * cdef double abs_max(int n, double* a) nogil: # <<<<<<<<<<<<<< + * """np.max(np.abs(a))""" + * cdef int i */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyLong_FromUnsignedLong(__pyx_v_n_features); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_4 = 0; - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_mean); - __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_X_mean, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_8 < 0)) { - PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_mean, (PyObject*)__pyx_v_X_mean, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); - } - } - __pyx_bstride_0_X_mean = __pyx_bstruct_X_mean.strides[0]; - __pyx_bshape_0_X_mean = __pyx_bstruct_X_mean.shape[0]; - if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_X_mean)); - __pyx_v_X_mean = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - /* "sklearn/linear_model/cd_fast.pyx":83 - * X_mean = np.zeros(n_features, np.float64) + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/linear_model/cd_fast.pyx":72 + * * - * for ii in xrange(n_features): # <<<<<<<<<<<<<< - * # Computes the mean - * X_sum_ii = 0.0 + * cdef double max(int n, double* a) nogil: # <<<<<<<<<<<<<< + * """np.max(a)""" + * cdef int i + */ + +static double __pyx_f_7sklearn_12linear_model_7cd_fast_max(int __pyx_v_n, double *__pyx_v_a) { + int __pyx_v_i; + double __pyx_v_m; + double __pyx_v_d; + double __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "sklearn/linear_model/cd_fast.pyx":75 + * """np.max(a)""" + * cdef int i + * cdef double m = a[0] # <<<<<<<<<<<<<< + * cdef double d + * for i in range(1, n): */ - __pyx_t_12 = __pyx_v_n_features; - for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { - __pyx_v_ii = __pyx_t_13; + __pyx_v_m = (__pyx_v_a[0]); - /* "sklearn/linear_model/cd_fast.pyx":85 - * for ii in xrange(n_features): - * # Computes the mean - * X_sum_ii = 0.0 # <<<<<<<<<<<<<< - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * X_sum_ii += X_data[jj] + /* "sklearn/linear_model/cd_fast.pyx":77 + * cdef double m = a[0] + * cdef double d + * for i in range(1, n): # <<<<<<<<<<<<<< + * d = a[i] + * if d > m: */ - __pyx_v_X_sum_ii = 0.0; + __pyx_t_1 = __pyx_v_n; + for (__pyx_t_2 = 1; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; - /* "sklearn/linear_model/cd_fast.pyx":86 - * # Computes the mean - * X_sum_ii = 0.0 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): # <<<<<<<<<<<<<< - * X_sum_ii += X_data[jj] - * X_mean[ii] = X_sum_ii / n_samples + /* "sklearn/linear_model/cd_fast.pyx":78 + * cdef double d + * for i in range(1, n): + * d = a[i] # <<<<<<<<<<<<<< + * if d > m: + * m = d */ - __pyx_t_14 = (__pyx_v_ii + 1); - __pyx_t_15 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_14, __pyx_bstride_0_X_indptr)); - __pyx_t_16 = __pyx_v_ii; - for (__pyx_t_17 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_16, __pyx_bstride_0_X_indptr)); __pyx_t_17 < __pyx_t_15; __pyx_t_17+=1) { - __pyx_v_jj = __pyx_t_17; + __pyx_v_d = (__pyx_v_a[__pyx_v_i]); - /* "sklearn/linear_model/cd_fast.pyx":87 - * X_sum_ii = 0.0 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * X_sum_ii += X_data[jj] # <<<<<<<<<<<<<< - * X_mean[ii] = X_sum_ii / n_samples - * + /* "sklearn/linear_model/cd_fast.pyx":79 + * for i in range(1, n): + * d = a[i] + * if d > m: # <<<<<<<<<<<<<< + * m = d + * return m */ - __pyx_t_18 = __pyx_v_jj; - __pyx_v_X_sum_ii = (__pyx_v_X_sum_ii + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_18, __pyx_bstride_0_X_data))); - } + __pyx_t_3 = ((__pyx_v_d > __pyx_v_m) != 0); + if (__pyx_t_3) { - /* "sklearn/linear_model/cd_fast.pyx":88 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * X_sum_ii += X_data[jj] - * X_mean[ii] = X_sum_ii / n_samples # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":80 + * d = a[i] + * if d > m: + * m = d # <<<<<<<<<<<<<< + * return m * - * for ii in xrange(n_features): */ - __pyx_t_17 = __pyx_v_ii; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_mean.buf, __pyx_t_17, __pyx_bstride_0_X_mean) = (__pyx_v_X_sum_ii / __pyx_v_n_samples); + __pyx_v_m = __pyx_v_d; + goto __pyx_L5; } - goto __pyx_L6; + __pyx_L5:; } - __pyx_L6:; - /* "sklearn/linear_model/cd_fast.pyx":90 - * X_mean[ii] = X_sum_ii / n_samples + /* "sklearn/linear_model/cd_fast.pyx":81 + * if d > m: + * m = d + * return m # <<<<<<<<<<<<<< + * * - * for ii in xrange(n_features): # <<<<<<<<<<<<<< - * X_mean_ii = X_mean[ii] - * X_sum_ii = 0.0 */ - __pyx_t_12 = __pyx_v_n_features; - for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { - __pyx_v_ii = __pyx_t_13; + __pyx_r = __pyx_v_m; + goto __pyx_L0; - /* "sklearn/linear_model/cd_fast.pyx":91 + /* "sklearn/linear_model/cd_fast.pyx":72 * - * for ii in xrange(n_features): - * X_mean_ii = X_mean[ii] # <<<<<<<<<<<<<< - * X_sum_ii = 0.0 - * nnz_ii = 0 + * + * cdef double max(int n, double* a) nogil: # <<<<<<<<<<<<<< + * """np.max(a)""" + * cdef int i */ - __pyx_t_19 = __pyx_v_ii; - __pyx_v_X_mean_ii = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_mean.buf, __pyx_t_19, __pyx_bstride_0_X_mean)); - /* "sklearn/linear_model/cd_fast.pyx":92 - * for ii in xrange(n_features): - * X_mean_ii = X_mean[ii] - * X_sum_ii = 0.0 # <<<<<<<<<<<<<< - * nnz_ii = 0 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/linear_model/cd_fast.pyx":84 + * + * + * cdef double diff_abs_max(int n, double* a, double* b) nogil: # <<<<<<<<<<<<<< + * """np.max(np.abs(a - b))""" + * cdef int i */ - __pyx_v_X_sum_ii = 0.0; - /* "sklearn/linear_model/cd_fast.pyx":93 - * X_mean_ii = X_mean[ii] - * X_sum_ii = 0.0 - * nnz_ii = 0 # <<<<<<<<<<<<<< - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * diff = X_data[jj] - X_mean_ii +static double __pyx_f_7sklearn_12linear_model_7cd_fast_diff_abs_max(int __pyx_v_n, double *__pyx_v_a, double *__pyx_v_b) { + int __pyx_v_i; + double __pyx_v_m; + double __pyx_v_d; + double __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "sklearn/linear_model/cd_fast.pyx":87 + * """np.max(np.abs(a - b))""" + * cdef int i + * cdef double m = fabs(a[0] - b[0]) # <<<<<<<<<<<<<< + * cdef double d + * for i in range(1, n): */ - __pyx_v_nnz_ii = 0; + __pyx_v_m = fabs(((__pyx_v_a[0]) - (__pyx_v_b[0]))); - /* "sklearn/linear_model/cd_fast.pyx":94 - * X_sum_ii = 0.0 - * nnz_ii = 0 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): # <<<<<<<<<<<<<< - * diff = X_data[jj] - X_mean_ii - * X_sum_ii += diff * diff + /* "sklearn/linear_model/cd_fast.pyx":89 + * cdef double m = fabs(a[0] - b[0]) + * cdef double d + * for i in range(1, n): # <<<<<<<<<<<<<< + * d = fabs(a[i] - b[i]) + * if d > m: */ - __pyx_t_20 = (__pyx_v_ii + 1); - __pyx_t_15 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_20, __pyx_bstride_0_X_indptr)); - __pyx_t_21 = __pyx_v_ii; - for (__pyx_t_22 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_21, __pyx_bstride_0_X_indptr)); __pyx_t_22 < __pyx_t_15; __pyx_t_22+=1) { - __pyx_v_jj = __pyx_t_22; + __pyx_t_1 = __pyx_v_n; + for (__pyx_t_2 = 1; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; - /* "sklearn/linear_model/cd_fast.pyx":95 - * nnz_ii = 0 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * diff = X_data[jj] - X_mean_ii # <<<<<<<<<<<<<< - * X_sum_ii += diff * diff - * nnz_ii += 1 + /* "sklearn/linear_model/cd_fast.pyx":90 + * cdef double d + * for i in range(1, n): + * d = fabs(a[i] - b[i]) # <<<<<<<<<<<<<< + * if d > m: + * m = d */ - __pyx_t_23 = __pyx_v_jj; - __pyx_v_diff = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_23, __pyx_bstride_0_X_data)) - __pyx_v_X_mean_ii); + __pyx_v_d = fabs(((__pyx_v_a[__pyx_v_i]) - (__pyx_v_b[__pyx_v_i]))); - /* "sklearn/linear_model/cd_fast.pyx":96 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * diff = X_data[jj] - X_mean_ii - * X_sum_ii += diff * diff # <<<<<<<<<<<<<< - * nnz_ii += 1 - * + /* "sklearn/linear_model/cd_fast.pyx":91 + * for i in range(1, n): + * d = fabs(a[i] - b[i]) + * if d > m: # <<<<<<<<<<<<<< + * m = d + * return m */ - __pyx_v_X_sum_ii = (__pyx_v_X_sum_ii + (__pyx_v_diff * __pyx_v_diff)); + __pyx_t_3 = ((__pyx_v_d > __pyx_v_m) != 0); + if (__pyx_t_3) { - /* "sklearn/linear_model/cd_fast.pyx":97 - * diff = X_data[jj] - X_mean_ii - * X_sum_ii += diff * diff - * nnz_ii += 1 # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":92 + * d = fabs(a[i] - b[i]) + * if d > m: + * m = d # <<<<<<<<<<<<<< + * return m * - * X_std[ii] = (X_sum_ii + (n_samples - nnz_ii) * X_mean_ii * X_mean_ii) */ - __pyx_v_nnz_ii = (__pyx_v_nnz_ii + 1); + __pyx_v_m = __pyx_v_d; + goto __pyx_L5; } + __pyx_L5:; + } - /* "sklearn/linear_model/cd_fast.pyx":99 - * nnz_ii += 1 + /* "sklearn/linear_model/cd_fast.pyx":93 + * if d > m: + * m = d + * return m # <<<<<<<<<<<<<< * - * X_std[ii] = (X_sum_ii + (n_samples - nnz_ii) * X_mean_ii * X_mean_ii) # <<<<<<<<<<<<<< - * return np.sqrt(X_std) * */ - __pyx_t_22 = __pyx_v_ii; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_std.buf, __pyx_t_22, __pyx_bstride_0_X_std) = (__pyx_v_X_sum_ii + (((__pyx_v_n_samples - __pyx_v_nnz_ii) * __pyx_v_X_mean_ii) * __pyx_v_X_mean_ii)); - } + __pyx_r = __pyx_v_m; + goto __pyx_L0; - /* "sklearn/linear_model/cd_fast.pyx":100 - * - * X_std[ii] = (X_sum_ii + (n_samples - nnz_ii) * X_mean_ii * X_mean_ii) - * return np.sqrt(X_std) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":84 * * + * cdef double diff_abs_max(int n, double* a, double* b) nogil: # <<<<<<<<<<<<<< + * """np.max(np.abs(a - b))""" + * cdef int i */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__sqrt); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_v_X_std)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_X_std)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_X_std)); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_std); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_mean); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.linear_model.cd_fast.sparse_std", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; + /* function exit code */ __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_std); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_mean); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_X_std); - __Pyx_XDECREF((PyObject *)__pyx_v_X_mean); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/cd_fast.pyx":106 +/* "sklearn/linear_model/cd_fast.pyx":126 * @cython.wraparound(False) * @cython.cdivision(True) * def enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, # <<<<<<<<<<<<<< @@ -1896,10 +2574,11 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_sparse_std(PyObject * * np.ndarray[DOUBLE, ndim=2] X, */ -static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent[] = "Cython version of the coordinate descent algorithm\n for Elastic-Net regression\n\n We minimize\n\n 1 norm(y - X w, 2)^2 + alpha norm(w, 1) + beta norm(w, 2)^2\n - ----\n 2 2\n\n "; -static PyMethodDef __pyx_mdef_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent = {__Pyx_NAMESTR("enet_coordinate_descent"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent)}; -static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_12linear_model_7cd_fast_enet_coordinate_descent[] = "Cython version of the coordinate descent algorithm\n for Elastic-Net regression\n\n We minimize\n\n 1 norm(y - X w, 2)^2 + alpha norm(w, 1) + beta norm(w, 2)^2\n - ----\n 2 2\n\n "; +static PyMethodDef __pyx_mdef_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent = {"enet_coordinate_descent", (PyCFunction)__pyx_pw_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_12linear_model_7cd_fast_enet_coordinate_descent}; +static PyObject *__pyx_pw_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_w = 0; double __pyx_v_alpha; double __pyx_v_beta; @@ -1907,86 +2586,24 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_1enet_coordinate_desc PyArrayObject *__pyx_v_y = 0; int __pyx_v_max_iter; double __pyx_v_tol; - PyBoolObject *__pyx_v_positive = 0; - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - PyArrayObject *__pyx_v_norm_cols_X = 0; - PyArrayObject *__pyx_v_R = 0; - double __pyx_v_tmp; - double __pyx_v_w_ii; - double __pyx_v_d_w_max; - double __pyx_v_w_max; - double __pyx_v_d_w_ii; - double __pyx_v_gap; - double __pyx_v_d_w_tol; - unsigned int __pyx_v_ii; - unsigned int __pyx_v_n_iter; - PyObject *__pyx_v_XtA = NULL; - PyObject *__pyx_v_dual_norm_XtA = NULL; - PyObject *__pyx_v_R_norm = NULL; - PyObject *__pyx_v_w_norm = NULL; - PyObject *__pyx_v_const = NULL; - PyObject *__pyx_v_A_norm = NULL; - Py_buffer __pyx_bstruct_norm_cols_X; - Py_ssize_t __pyx_bstride_0_norm_cols_X = 0; - Py_ssize_t __pyx_bshape_0_norm_cols_X = 0; - Py_buffer __pyx_bstruct_R; - Py_ssize_t __pyx_bstride_0_R = 0; - Py_ssize_t __pyx_bshape_0_R = 0; - Py_buffer __pyx_bstruct_X; - Py_ssize_t __pyx_bstride_0_X = 0; - Py_ssize_t __pyx_bstride_1_X = 0; - Py_ssize_t __pyx_bshape_0_X = 0; - Py_ssize_t __pyx_bshape_1_X = 0; - Py_buffer __pyx_bstruct_w; - Py_ssize_t __pyx_bstride_0_w = 0; - Py_ssize_t __pyx_bshape_0_w = 0; - Py_buffer __pyx_bstruct_y; - Py_ssize_t __pyx_bstride_0_y = 0; - Py_ssize_t __pyx_bshape_0_y = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyArrayObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyArrayObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - double __pyx_t_12; - unsigned int __pyx_t_13; - unsigned int __pyx_t_14; - unsigned int __pyx_t_15; - unsigned int __pyx_t_16; - unsigned int __pyx_t_17; - int __pyx_t_18; - int __pyx_t_19; - unsigned int __pyx_t_20; - unsigned int __pyx_t_21; - unsigned int __pyx_t_22; - unsigned int __pyx_t_23; - unsigned int __pyx_t_24; - unsigned int __pyx_t_25; - unsigned int __pyx_t_26; - unsigned int __pyx_t_27; - int __pyx_t_28; - PyObject *__pyx_t_29 = NULL; + PyObject *__pyx_v_rng = 0; + int __pyx_v_random; + int __pyx_v_positive; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__w,&__pyx_n_s__alpha,&__pyx_n_s__beta,&__pyx_n_s__X,&__pyx_n_s__y,&__pyx_n_s__max_iter,&__pyx_n_s__tol,&__pyx_n_s__positive,0}; - __Pyx_RefNannySetupContext("enet_coordinate_descent"); - __pyx_self = __pyx_self; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("enet_coordinate_descent (wrapper)", 0); { - PyObject* values[8] = {0,0,0,0,0,0,0,0}; - values[7] = (PyObject *)__pyx_k_1; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_w,&__pyx_n_s_alpha,&__pyx_n_s_beta,&__pyx_n_s_X,&__pyx_n_s_y,&__pyx_n_s_max_iter,&__pyx_n_s_tol,&__pyx_n_s_rng,&__pyx_n_s_random,&__pyx_n_s_positive,0}; + PyObject* values[10] = {0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); + case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); @@ -1999,60 +2616,65 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_1enet_coordinate_desc default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__w); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_w)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__alpha); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_alpha)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 7, 8, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 8, 10, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__beta); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_beta)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 7, 8, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 8, 10, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 7, 8, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 8, 10, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 7, 8, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 8, 10, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__max_iter); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_iter)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 7, 8, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 8, 10, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__tol); - if (likely(values[6])) kw_args--; + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tol)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 7, 8, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 8, 10, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_rng)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 8, 10, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 8: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__positive); - if (value) { values[7] = value; kw_args--; } + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random); + if (value) { values[8] = value; kw_args--; } + } + case 9: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_positive); + if (value) { values[9] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "enet_coordinate_descent") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "enet_coordinate_descent") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { + case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); + case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); @@ -2064,51 +2686,161 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_1enet_coordinate_desc } } __pyx_v_w = ((PyArrayObject *)values[0]); - __pyx_v_alpha = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_alpha == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_beta = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_beta == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_alpha = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_alpha == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_beta = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_beta == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_X = ((PyArrayObject *)values[3]); __pyx_v_y = ((PyArrayObject *)values[4]); - __pyx_v_max_iter = __Pyx_PyInt_AsInt(values[5]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_tol = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_positive = ((PyBoolObject *)values[7]); + __pyx_v_max_iter = __Pyx_PyInt_As_int(values[5]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_tol = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_rng = values[7]; + if (values[8]) { + __pyx_v_random = __Pyx_PyObject_IsTrue(values[8]); if (unlikely((__pyx_v_random == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_random = ((int)0); + } + if (values[9]) { + __pyx_v_positive = __Pyx_PyObject_IsTrue(values[9]); if (unlikely((__pyx_v_positive == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_positive = ((int)0); + } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 7, 8, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent", 0, 8, 10, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.linear_model.cd_fast.enet_coordinate_descent", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_norm_cols_X.buf = NULL; - __pyx_bstruct_R.buf = NULL; - __pyx_bstruct_w.buf = NULL; - __pyx_bstruct_X.buf = NULL; - __pyx_bstruct_y.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_w), __pyx_ptype_5numpy_ndarray, 1, "w", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_positive), __pyx_ptype_7cpython_4bool_bool, 1, "positive", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_w), __pyx_ptype_5numpy_ndarray, 1, "w", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_12linear_model_7cd_fast_enet_coordinate_descent(__pyx_self, __pyx_v_w, __pyx_v_alpha, __pyx_v_beta, __pyx_v_X, __pyx_v_y, __pyx_v_max_iter, __pyx_v_tol, __pyx_v_rng, __pyx_v_random, __pyx_v_positive); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_enet_coordinate_descent(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_w, double __pyx_v_alpha, double __pyx_v_beta, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_y, int __pyx_v_max_iter, double __pyx_v_tol, PyObject *__pyx_v_rng, int __pyx_v_random, int __pyx_v_positive) { + unsigned int __pyx_v_n_samples; + unsigned int __pyx_v_n_features; + unsigned int __pyx_v_n_tasks; + PyArrayObject *__pyx_v_norm_cols_X = 0; + PyArrayObject *__pyx_v_R = 0; + PyArrayObject *__pyx_v_XtA = 0; + double __pyx_v_tmp; + double __pyx_v_w_ii; + double __pyx_v_d_w_max; + double __pyx_v_w_max; + double __pyx_v_d_w_ii; + double __pyx_v_gap; + double __pyx_v_d_w_tol; + double __pyx_v_dual_norm_XtA; + double __pyx_v_R_norm2; + double __pyx_v_w_norm2; + double __pyx_v_l1_norm; + unsigned int __pyx_v_ii; + unsigned int __pyx_v_i; + unsigned int __pyx_v_n_iter; + unsigned int __pyx_v_f_iter; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_v_rand_r_state_seed; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t *__pyx_v_rand_r_state; + double __pyx_v_const; + double __pyx_v_A_norm2; + __Pyx_LocalBuf_ND __pyx_pybuffernd_R; + __Pyx_Buffer __pyx_pybuffer_R; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_LocalBuf_ND __pyx_pybuffernd_XtA; + __Pyx_Buffer __pyx_pybuffer_XtA; + __Pyx_LocalBuf_ND __pyx_pybuffernd_norm_cols_X; + __Pyx_Buffer __pyx_pybuffer_norm_cols_X; + __Pyx_LocalBuf_ND __pyx_pybuffernd_w; + __Pyx_Buffer __pyx_pybuffer_w; + __Pyx_LocalBuf_ND __pyx_pybuffernd_y; + __Pyx_Buffer __pyx_pybuffer_y; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyArrayObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyArrayObject *__pyx_t_7 = NULL; + PyArrayObject *__pyx_t_8 = NULL; + Py_ssize_t __pyx_t_9; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_t_10; + int __pyx_t_11; + unsigned int __pyx_t_12; + unsigned int __pyx_t_13; + unsigned int __pyx_t_14; + unsigned int __pyx_t_15; + int __pyx_t_16; + unsigned int __pyx_t_17; + unsigned int __pyx_t_18; + unsigned int __pyx_t_19; + int __pyx_t_20; + unsigned int __pyx_t_21; + unsigned int __pyx_t_22; + unsigned int __pyx_t_23; + unsigned int __pyx_t_24; + unsigned int __pyx_t_25; + unsigned int __pyx_t_26; + unsigned int __pyx_t_27; + unsigned int __pyx_t_28; + unsigned int __pyx_t_29; + unsigned int __pyx_t_30; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("enet_coordinate_descent", 0); + __pyx_pybuffer_norm_cols_X.pybuffer.buf = NULL; + __pyx_pybuffer_norm_cols_X.refcount = 0; + __pyx_pybuffernd_norm_cols_X.data = NULL; + __pyx_pybuffernd_norm_cols_X.rcbuffer = &__pyx_pybuffer_norm_cols_X; + __pyx_pybuffer_R.pybuffer.buf = NULL; + __pyx_pybuffer_R.refcount = 0; + __pyx_pybuffernd_R.data = NULL; + __pyx_pybuffernd_R.rcbuffer = &__pyx_pybuffer_R; + __pyx_pybuffer_XtA.pybuffer.buf = NULL; + __pyx_pybuffer_XtA.refcount = 0; + __pyx_pybuffernd_XtA.data = NULL; + __pyx_pybuffernd_XtA.rcbuffer = &__pyx_pybuffer_XtA; + __pyx_pybuffer_w.pybuffer.buf = NULL; + __pyx_pybuffer_w.refcount = 0; + __pyx_pybuffernd_w.data = NULL; + __pyx_pybuffernd_w.rcbuffer = &__pyx_pybuffer_w; + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + __pyx_pybuffer_y.pybuffer.buf = NULL; + __pyx_pybuffer_y.refcount = 0; + __pyx_pybuffernd_y.data = NULL; + __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_w, (PyObject*)__pyx_v_w, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_v_w, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_w = __pyx_bstruct_w.strides[0]; - __pyx_bshape_0_w = __pyx_bstruct_w.shape[0]; + __pyx_pybuffernd_w.diminfo[0].strides = __pyx_pybuffernd_w.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_w.diminfo[0].shape = __pyx_pybuffernd_w.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_X = __pyx_bstruct_X.strides[0]; __pyx_bstride_1_X = __pyx_bstruct_X.strides[1]; - __pyx_bshape_0_X = __pyx_bstruct_X.shape[0]; __pyx_bshape_1_X = __pyx_bstruct_X.shape[1]; + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_y, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_y = __pyx_bstruct_y.strides[0]; - __pyx_bshape_0_y = __pyx_bstruct_y.shape[0]; + __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; - /* "sklearn/linear_model/cd_fast.pyx":123 + /* "sklearn/linear_model/cd_fast.pyx":144 * * # get the data information into easy vars * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< @@ -2117,1059 +2849,961 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_1enet_coordinate_desc */ __pyx_v_n_samples = (__pyx_v_X->dimensions[0]); - /* "sklearn/linear_model/cd_fast.pyx":124 + /* "sklearn/linear_model/cd_fast.pyx":145 * # get the data information into easy vars * cdef unsigned int n_samples = X.shape[0] * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< * - * # compute norms of the columns of X + * # get the number of tasks indirectly, using strides */ __pyx_v_n_features = (__pyx_v_X->dimensions[1]); - /* "sklearn/linear_model/cd_fast.pyx":127 + /* "sklearn/linear_model/cd_fast.pyx":148 + * + * # get the number of tasks indirectly, using strides + * cdef unsigned int n_tasks = y.strides[0] / sizeof(DOUBLE) # <<<<<<<<<<<<<< + * + * # compute norms of the columns of X + */ + __pyx_v_n_tasks = ((__pyx_v_y->strides[0]) / (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))); + + /* "sklearn/linear_model/cd_fast.pyx":151 * * # compute norms of the columns of X * cdef np.ndarray[DOUBLE, ndim=1] norm_cols_X = (X**2).sum(axis=0) # <<<<<<<<<<<<<< * * # initial value of the residuals */ - __pyx_t_1 = PyNumber_Power(((PyObject *)__pyx_v_X), __pyx_int_2, Py_None); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyNumber_Power(((PyObject *)__pyx_v_X), __pyx_int_2, Py_None); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__sum); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_sum); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__axis), __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_axis, __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_empty_tuple, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_4 = ((PyArrayObject *)__pyx_t_3); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_norm_cols_X, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_norm_cols_X = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_norm_cols_X.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_norm_cols_X = __pyx_bstruct_norm_cols_X.strides[0]; - __pyx_bshape_0_norm_cols_X = __pyx_bstruct_norm_cols_X.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_norm_cols_X.rcbuffer->pybuffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_norm_cols_X = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_norm_cols_X.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_norm_cols_X.diminfo[0].strides = __pyx_pybuffernd_norm_cols_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_norm_cols_X.diminfo[0].shape = __pyx_pybuffernd_norm_cols_X.rcbuffer->pybuffer.shape[0]; } } __pyx_t_4 = 0; __pyx_v_norm_cols_X = ((PyArrayObject *)__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/linear_model/cd_fast.pyx":137 + /* "sklearn/linear_model/cd_fast.pyx":154 + * + * # initial value of the residuals + * cdef np.ndarray[DOUBLE, ndim=1] R = np.empty(n_samples) # <<<<<<<<<<<<<< + * + * cdef np.ndarray[DOUBLE, ndim=1] XtA = np.empty(n_features) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (!__pyx_t_5) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_GOTREF(__pyx_t_3); + } else { + __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; + PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_3); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_R.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_R = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_R.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_R.diminfo[0].strides = __pyx_pybuffernd_R.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_R.diminfo[0].shape = __pyx_pybuffernd_R.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_7 = 0; + __pyx_v_R = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":156 + * cdef np.ndarray[DOUBLE, ndim=1] R = np.empty(n_samples) + * + * cdef np.ndarray[DOUBLE, ndim=1] XtA = np.empty(n_features) # <<<<<<<<<<<<<< + * cdef double tmp + * cdef double w_ii + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_features); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_6); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_6, function); + } + } + if (!__pyx_t_1) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_6, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_GOTREF(__pyx_t_3); + } else { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = NULL; + PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((PyArrayObject *)__pyx_t_3); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_XtA.rcbuffer->pybuffer, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_XtA = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_XtA.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_XtA.diminfo[0].strides = __pyx_pybuffernd_XtA.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_XtA.diminfo[0].shape = __pyx_pybuffernd_XtA.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_8 = 0; + __pyx_v_XtA = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":162 * cdef double w_max * cdef double d_w_ii * cdef double gap = tol + 1.0 # <<<<<<<<<<<<<< * cdef double d_w_tol = tol - * cdef unsigned int ii + * cdef double dual_norm_XtA */ __pyx_v_gap = (__pyx_v_tol + 1.0); - /* "sklearn/linear_model/cd_fast.pyx":138 + /* "sklearn/linear_model/cd_fast.pyx":163 * cdef double d_w_ii * cdef double gap = tol + 1.0 * cdef double d_w_tol = tol # <<<<<<<<<<<<<< - * cdef unsigned int ii - * cdef unsigned int n_iter + * cdef double dual_norm_XtA + * cdef double R_norm2 */ __pyx_v_d_w_tol = __pyx_v_tol; - /* "sklearn/linear_model/cd_fast.pyx":142 + /* "sklearn/linear_model/cd_fast.pyx":172 * cdef unsigned int n_iter + * cdef unsigned int f_iter + * cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) # <<<<<<<<<<<<<< + * cdef UINT32_t* rand_r_state = &rand_r_state_seed + * + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_rng, __pyx_n_s_randint); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_e_7sklearn_12linear_model_7cd_fast_RAND_R_MAX); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_2 = NULL; + __pyx_t_9 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_6); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_6, function); + __pyx_t_9 = 1; + } + } + __pyx_t_1 = PyTuple_New(2+__pyx_t_9); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (__pyx_t_2) { + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = NULL; + } + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_1, 0+__pyx_t_9, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_1, 1+__pyx_t_9, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_1, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_10 = __Pyx_PyInt_As_npy_uint32(__pyx_t_3); if (unlikely((__pyx_t_10 == (npy_uint32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_rand_r_state_seed = __pyx_t_10; + + /* "sklearn/linear_model/cd_fast.pyx":173 + * cdef unsigned int f_iter + * cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + * cdef UINT32_t* rand_r_state = &rand_r_state_seed # <<<<<<<<<<<<<< + * + * if alpha == 0: + */ + __pyx_v_rand_r_state = (&__pyx_v_rand_r_state_seed); + + /* "sklearn/linear_model/cd_fast.pyx":175 + * cdef UINT32_t* rand_r_state = &rand_r_state_seed * * if alpha == 0: # <<<<<<<<<<<<<< * warnings.warn("Coordinate descent with alpha=0 may lead to unexpected" * " results and is discouraged.") */ - __pyx_t_5 = (__pyx_v_alpha == 0.0); - if (__pyx_t_5) { + __pyx_t_11 = ((__pyx_v_alpha == 0.0) != 0); + if (__pyx_t_11) { - /* "sklearn/linear_model/cd_fast.pyx":143 + /* "sklearn/linear_model/cd_fast.pyx":176 * * if alpha == 0: * warnings.warn("Coordinate descent with alpha=0 may lead to unexpected" # <<<<<<<<<<<<<< * " results and is discouraged.") * */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__warnings); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_warnings); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__warn); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_warn); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_3), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L6; + goto __pyx_L3; } - __pyx_L6:; + __pyx_L3:; - /* "sklearn/linear_model/cd_fast.pyx":146 + /* "sklearn/linear_model/cd_fast.pyx":179 * " results and is discouraged.") * - * R = y - np.dot(X, w) # <<<<<<<<<<<<<< + * with nogil: # <<<<<<<<<<<<<< * - * tol = tol * linalg.norm(y) ** 2 + * # R = y - np.dot(X, w) */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__dot); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(((PyObject *)__pyx_v_X)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_X)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_X)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(((PyObject *)__pyx_v_y), __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_3); { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_R); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_R, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_R, (PyObject*)__pyx_v_R, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); - } - } - __pyx_bstride_0_R = __pyx_bstruct_R.strides[0]; - __pyx_bshape_0_R = __pyx_bstruct_R.shape[0]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_6 = 0; - __pyx_v_R = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { - /* "sklearn/linear_model/cd_fast.pyx":148 - * R = y - np.dot(X, w) - * - * tol = tol * linalg.norm(y) ** 2 # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":182 * - * for n_iter in range(max_iter): + * # R = y - np.dot(X, w) + * for i in range(n_samples): # <<<<<<<<<<<<<< + * R[i] = y[i] - ddot(n_features, + * (X.data + i * sizeof(DOUBLE)), */ - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_tol); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__norm); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_y)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_y)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); - __pyx_t_11 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Power(__pyx_t_11, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_11 = PyNumber_Multiply(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_12 = __pyx_PyFloat_AsDouble(__pyx_t_11); if (unlikely((__pyx_t_12 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_v_tol = __pyx_t_12; + __pyx_t_12 = __pyx_v_n_samples; + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; - /* "sklearn/linear_model/cd_fast.pyx":150 - * tol = tol * linalg.norm(y) ** 2 - * - * for n_iter in range(max_iter): # <<<<<<<<<<<<<< - * w_max = 0.0 - * d_w_max = 0.0 + /* "sklearn/linear_model/cd_fast.pyx":183 + * # R = y - np.dot(X, w) + * for i in range(n_samples): + * R[i] = y[i] - ddot(n_features, # <<<<<<<<<<<<<< + * (X.data + i * sizeof(DOUBLE)), + * n_samples, w.data, 1) */ - __pyx_t_7 = __pyx_v_max_iter; - for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_7; __pyx_t_13+=1) { - __pyx_v_n_iter = __pyx_t_13; + __pyx_t_14 = __pyx_v_i; - /* "sklearn/linear_model/cd_fast.pyx":151 + /* "sklearn/linear_model/cd_fast.pyx":185 + * R[i] = y[i] - ddot(n_features, + * (X.data + i * sizeof(DOUBLE)), + * n_samples, w.data, 1) # <<<<<<<<<<<<<< * - * for n_iter in range(max_iter): - * w_max = 0.0 # <<<<<<<<<<<<<< - * d_w_max = 0.0 - * for ii in xrange(n_features): # Loop over coordinates - */ - __pyx_v_w_max = 0.0; - - /* "sklearn/linear_model/cd_fast.pyx":152 - * for n_iter in range(max_iter): - * w_max = 0.0 - * d_w_max = 0.0 # <<<<<<<<<<<<<< - * for ii in xrange(n_features): # Loop over coordinates - * if norm_cols_X[ii] == 0.0: + * # tol *= np.dot(y, y) */ - __pyx_v_d_w_max = 0.0; + __pyx_t_15 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_R.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_R.diminfo[0].strides) = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_y.diminfo[0].strides)) - cblas_ddot(__pyx_v_n_features, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_X->data + (__pyx_v_i * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), __pyx_v_n_samples, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_w->data), 1)); + } - /* "sklearn/linear_model/cd_fast.pyx":153 - * w_max = 0.0 - * d_w_max = 0.0 - * for ii in xrange(n_features): # Loop over coordinates # <<<<<<<<<<<<<< - * if norm_cols_X[ii] == 0.0: - * continue + /* "sklearn/linear_model/cd_fast.pyx":188 + * + * # tol *= np.dot(y, y) + * tol *= ddot(n_samples, y.data, n_tasks, # <<<<<<<<<<<<<< + * y.data, n_tasks) + * */ - __pyx_t_14 = __pyx_v_n_features; - for (__pyx_t_15 = 0; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { - __pyx_v_ii = __pyx_t_15; + __pyx_v_tol = (__pyx_v_tol * cblas_ddot(__pyx_v_n_samples, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_y->data), __pyx_v_n_tasks, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_y->data), __pyx_v_n_tasks)); - /* "sklearn/linear_model/cd_fast.pyx":154 - * d_w_max = 0.0 - * for ii in xrange(n_features): # Loop over coordinates - * if norm_cols_X[ii] == 0.0: # <<<<<<<<<<<<<< - * continue + /* "sklearn/linear_model/cd_fast.pyx":191 + * y.data, n_tasks) * + * for n_iter in range(max_iter): # <<<<<<<<<<<<<< + * w_max = 0.0 + * d_w_max = 0.0 */ - __pyx_t_16 = __pyx_v_ii; - __pyx_t_5 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_norm_cols_X.buf, __pyx_t_16, __pyx_bstride_0_norm_cols_X)) == 0.0); - if (__pyx_t_5) { + __pyx_t_16 = __pyx_v_max_iter; + for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_16; __pyx_t_12+=1) { + __pyx_v_n_iter = __pyx_t_12; - /* "sklearn/linear_model/cd_fast.pyx":155 - * for ii in xrange(n_features): # Loop over coordinates - * if norm_cols_X[ii] == 0.0: - * continue # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":192 * - * w_ii = w[ii] # Store previous value + * for n_iter in range(max_iter): + * w_max = 0.0 # <<<<<<<<<<<<<< + * d_w_max = 0.0 + * for f_iter in range(n_features): # Loop over coordinates */ - goto __pyx_L9_continue; - goto __pyx_L11; - } - __pyx_L11:; + __pyx_v_w_max = 0.0; - /* "sklearn/linear_model/cd_fast.pyx":157 - * continue - * - * w_ii = w[ii] # Store previous value # <<<<<<<<<<<<<< - * - * if w_ii != 0.0: + /* "sklearn/linear_model/cd_fast.pyx":193 + * for n_iter in range(max_iter): + * w_max = 0.0 + * d_w_max = 0.0 # <<<<<<<<<<<<<< + * for f_iter in range(n_features): # Loop over coordinates + * if random: */ - __pyx_t_17 = __pyx_v_ii; - __pyx_v_w_ii = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_17, __pyx_bstride_0_w)); + __pyx_v_d_w_max = 0.0; - /* "sklearn/linear_model/cd_fast.pyx":159 - * w_ii = w[ii] # Store previous value - * - * if w_ii != 0.0: # <<<<<<<<<<<<<< - * # R += w_ii * X[:,ii] - * daxpy(n_samples, w_ii, + /* "sklearn/linear_model/cd_fast.pyx":194 + * w_max = 0.0 + * d_w_max = 0.0 + * for f_iter in range(n_features): # Loop over coordinates # <<<<<<<<<<<<<< + * if random: + * ii = rand_int(n_features, rand_r_state) */ - __pyx_t_5 = (__pyx_v_w_ii != 0.0); - if (__pyx_t_5) { + __pyx_t_13 = __pyx_v_n_features; + for (__pyx_t_17 = 0; __pyx_t_17 < __pyx_t_13; __pyx_t_17+=1) { + __pyx_v_f_iter = __pyx_t_17; - /* "sklearn/linear_model/cd_fast.pyx":163 - * daxpy(n_samples, w_ii, - * (X.data + ii * n_samples * sizeof(DOUBLE)), 1, - * R.data, 1) # <<<<<<<<<<<<<< - * - * # tmp = (X[:,ii]*R).sum() + /* "sklearn/linear_model/cd_fast.pyx":195 + * d_w_max = 0.0 + * for f_iter in range(n_features): # Loop over coordinates + * if random: # <<<<<<<<<<<<<< + * ii = rand_int(n_features, rand_r_state) + * else: */ - cblas_daxpy(__pyx_v_n_samples, __pyx_v_w_ii, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_X->data + ((__pyx_v_ii * __pyx_v_n_samples) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), 1); - goto __pyx_L12; - } - __pyx_L12:; + __pyx_t_11 = (__pyx_v_random != 0); + if (__pyx_t_11) { - /* "sklearn/linear_model/cd_fast.pyx":168 - * tmp = ddot(n_samples, - * (X.data + ii * n_samples * sizeof(DOUBLE)), 1, - * R.data, 1) # <<<<<<<<<<<<<< - * - * if positive and tmp < 0: + /* "sklearn/linear_model/cd_fast.pyx":196 + * for f_iter in range(n_features): # Loop over coordinates + * if random: + * ii = rand_int(n_features, rand_r_state) # <<<<<<<<<<<<<< + * else: + * ii = f_iter */ - __pyx_v_tmp = cblas_ddot(__pyx_v_n_samples, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_X->data + ((__pyx_v_ii * __pyx_v_n_samples) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), 1); + __pyx_v_ii = __pyx_f_7sklearn_12linear_model_7cd_fast_rand_int(__pyx_v_n_features, __pyx_v_rand_r_state); + goto __pyx_L13; + } + /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":170 - * R.data, 1) + /* "sklearn/linear_model/cd_fast.pyx":198 + * ii = rand_int(n_features, rand_r_state) + * else: + * ii = f_iter # <<<<<<<<<<<<<< * - * if positive and tmp < 0: # <<<<<<<<<<<<<< - * w[ii] = 0.0 - * else: + * if norm_cols_X[ii] == 0.0: */ - __pyx_t_5 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_positive)); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_5) { - __pyx_t_18 = (__pyx_v_tmp < 0.0); - __pyx_t_19 = __pyx_t_18; - } else { - __pyx_t_19 = __pyx_t_5; - } - if (__pyx_t_19) { + __pyx_v_ii = __pyx_v_f_iter; + } + __pyx_L13:; - /* "sklearn/linear_model/cd_fast.pyx":171 + /* "sklearn/linear_model/cd_fast.pyx":200 + * ii = f_iter + * + * if norm_cols_X[ii] == 0.0: # <<<<<<<<<<<<<< + * continue * - * if positive and tmp < 0: - * w[ii] = 0.0 # <<<<<<<<<<<<<< - * else: - * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ */ - __pyx_t_20 = __pyx_v_ii; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_20, __pyx_bstride_0_w) = 0.0; - goto __pyx_L13; - } - /*else*/ { + __pyx_t_18 = __pyx_v_ii; + __pyx_t_11 = (((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_norm_cols_X.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_norm_cols_X.diminfo[0].strides)) == 0.0) != 0); + if (__pyx_t_11) { - /* "sklearn/linear_model/cd_fast.pyx":174 - * else: - * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ - * / (norm_cols_X[ii] + beta) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":201 + * + * if norm_cols_X[ii] == 0.0: + * continue # <<<<<<<<<<<<<< * - * if w[ii] != 0.0: + * w_ii = w[ii] # Store previous value */ - __pyx_t_21 = __pyx_v_ii; + goto __pyx_L11_continue; + } - /* "sklearn/linear_model/cd_fast.pyx":173 - * w[ii] = 0.0 - * else: - * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ # <<<<<<<<<<<<<< - * / (norm_cols_X[ii] + beta) + /* "sklearn/linear_model/cd_fast.pyx":203 + * continue * + * w_ii = w[ii] # Store previous value # <<<<<<<<<<<<<< + * + * if w_ii != 0.0: */ - __pyx_t_22 = __pyx_v_ii; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_22, __pyx_bstride_0_w) = ((__pyx_f_7sklearn_12linear_model_7cd_fast_fsign(__pyx_v_tmp) * __pyx_f_7sklearn_12linear_model_7cd_fast_fmax((fabs(__pyx_v_tmp) - __pyx_v_alpha), 0.0)) / ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_norm_cols_X.buf, __pyx_t_21, __pyx_bstride_0_norm_cols_X)) + __pyx_v_beta)); - } - __pyx_L13:; + __pyx_t_19 = __pyx_v_ii; + __pyx_v_w_ii = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_w.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_w.diminfo[0].strides)); - /* "sklearn/linear_model/cd_fast.pyx":176 - * / (norm_cols_X[ii] + beta) + /* "sklearn/linear_model/cd_fast.pyx":205 + * w_ii = w[ii] # Store previous value * - * if w[ii] != 0.0: # <<<<<<<<<<<<<< - * # R -= w[ii] * X[:,ii] # Update residual - * daxpy(n_samples, -w[ii], + * if w_ii != 0.0: # <<<<<<<<<<<<<< + * # R += w_ii * X[:,ii] + * daxpy(n_samples, w_ii, */ - __pyx_t_23 = __pyx_v_ii; - __pyx_t_19 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_23, __pyx_bstride_0_w)) != 0.0); - if (__pyx_t_19) { + __pyx_t_11 = ((__pyx_v_w_ii != 0.0) != 0); + if (__pyx_t_11) { - /* "sklearn/linear_model/cd_fast.pyx":178 - * if w[ii] != 0.0: - * # R -= w[ii] * X[:,ii] # Update residual - * daxpy(n_samples, -w[ii], # <<<<<<<<<<<<<< - * (X.data + ii * n_samples * sizeof(DOUBLE)), 1, - * R.data, 1) + /* "sklearn/linear_model/cd_fast.pyx":207 + * if w_ii != 0.0: + * # R += w_ii * X[:,ii] + * daxpy(n_samples, w_ii, # <<<<<<<<<<<<<< + * (X.data + ii * n_samples * sizeof(DOUBLE)), + * 1, R.data, 1) */ - __pyx_t_24 = __pyx_v_ii; + cblas_daxpy(__pyx_v_n_samples, __pyx_v_w_ii, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_X->data + ((__pyx_v_ii * __pyx_v_n_samples) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), 1); + goto __pyx_L15; + } + __pyx_L15:; - /* "sklearn/linear_model/cd_fast.pyx":180 - * daxpy(n_samples, -w[ii], - * (X.data + ii * n_samples * sizeof(DOUBLE)), 1, - * R.data, 1) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":212 * - * # update the maximum absolute coefficient update + * # tmp = (X[:,ii]*R).sum() + * tmp = ddot(n_samples, # <<<<<<<<<<<<<< + * (X.data + ii * n_samples * sizeof(DOUBLE)), + * 1, R.data, 1) */ - cblas_daxpy(__pyx_v_n_samples, (-(*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_24, __pyx_bstride_0_w))), ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_X->data + ((__pyx_v_ii * __pyx_v_n_samples) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), 1); - goto __pyx_L14; - } - __pyx_L14:; + __pyx_v_tmp = cblas_ddot(__pyx_v_n_samples, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_X->data + ((__pyx_v_ii * __pyx_v_n_samples) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), 1); - /* "sklearn/linear_model/cd_fast.pyx":183 + /* "sklearn/linear_model/cd_fast.pyx":216 + * 1, R.data, 1) * - * # update the maximum absolute coefficient update - * d_w_ii = fabs(w[ii] - w_ii) # <<<<<<<<<<<<<< - * if d_w_ii > d_w_max: - * d_w_max = d_w_ii + * if positive and tmp < 0: # <<<<<<<<<<<<<< + * w[ii] = 0.0 + * else: */ - __pyx_t_25 = __pyx_v_ii; - __pyx_v_d_w_ii = fabs(((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_25, __pyx_bstride_0_w)) - __pyx_v_w_ii)); + __pyx_t_20 = (__pyx_v_positive != 0); + if (__pyx_t_20) { + goto __pyx_L18_next_and; + } else { + __pyx_t_11 = __pyx_t_20; + goto __pyx_L17_bool_binop_done; + } + __pyx_L18_next_and:; + __pyx_t_20 = ((__pyx_v_tmp < 0.0) != 0); + __pyx_t_11 = __pyx_t_20; + __pyx_L17_bool_binop_done:; + if (__pyx_t_11) { - /* "sklearn/linear_model/cd_fast.pyx":184 - * # update the maximum absolute coefficient update - * d_w_ii = fabs(w[ii] - w_ii) - * if d_w_ii > d_w_max: # <<<<<<<<<<<<<< - * d_w_max = d_w_ii + /* "sklearn/linear_model/cd_fast.pyx":217 * + * if positive and tmp < 0: + * w[ii] = 0.0 # <<<<<<<<<<<<<< + * else: + * w[ii] = (fsign(tmp) * fmax(fabs(tmp) - alpha, 0) */ - __pyx_t_19 = (__pyx_v_d_w_ii > __pyx_v_d_w_max); - if (__pyx_t_19) { + __pyx_t_21 = __pyx_v_ii; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_w.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_w.diminfo[0].strides) = 0.0; + goto __pyx_L16; + } + /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":185 - * d_w_ii = fabs(w[ii] - w_ii) - * if d_w_ii > d_w_max: - * d_w_max = d_w_ii # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":220 + * else: + * w[ii] = (fsign(tmp) * fmax(fabs(tmp) - alpha, 0) + * / (norm_cols_X[ii] + beta)) # <<<<<<<<<<<<<< * - * if fabs(w[ii]) > w_max: + * if w[ii] != 0.0: */ - __pyx_v_d_w_max = __pyx_v_d_w_ii; - goto __pyx_L15; - } - __pyx_L15:; + __pyx_t_22 = __pyx_v_ii; - /* "sklearn/linear_model/cd_fast.pyx":187 - * d_w_max = d_w_ii + /* "sklearn/linear_model/cd_fast.pyx":219 + * w[ii] = 0.0 + * else: + * w[ii] = (fsign(tmp) * fmax(fabs(tmp) - alpha, 0) # <<<<<<<<<<<<<< + * / (norm_cols_X[ii] + beta)) * - * if fabs(w[ii]) > w_max: # <<<<<<<<<<<<<< - * w_max = fabs(w[ii]) + */ + __pyx_t_23 = __pyx_v_ii; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_w.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_w.diminfo[0].strides) = ((__pyx_f_7sklearn_12linear_model_7cd_fast_fsign(__pyx_v_tmp) * __pyx_f_7sklearn_12linear_model_7cd_fast_fmax((fabs(__pyx_v_tmp) - __pyx_v_alpha), 0.0)) / ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_norm_cols_X.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_norm_cols_X.diminfo[0].strides)) + __pyx_v_beta)); + } + __pyx_L16:; + + /* "sklearn/linear_model/cd_fast.pyx":222 + * / (norm_cols_X[ii] + beta)) * + * if w[ii] != 0.0: # <<<<<<<<<<<<<< + * # R -= w[ii] * X[:,ii] # Update residual + * daxpy(n_samples, -w[ii], */ - __pyx_t_26 = __pyx_v_ii; - __pyx_t_19 = (fabs((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_26, __pyx_bstride_0_w))) > __pyx_v_w_max); - if (__pyx_t_19) { + __pyx_t_24 = __pyx_v_ii; + __pyx_t_11 = (((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_w.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_w.diminfo[0].strides)) != 0.0) != 0); + if (__pyx_t_11) { - /* "sklearn/linear_model/cd_fast.pyx":188 + /* "sklearn/linear_model/cd_fast.pyx":224 + * if w[ii] != 0.0: + * # R -= w[ii] * X[:,ii] # Update residual + * daxpy(n_samples, -w[ii], # <<<<<<<<<<<<<< + * (X.data + ii * n_samples * sizeof(DOUBLE)), + * 1, R.data, 1) + */ + __pyx_t_25 = __pyx_v_ii; + + /* "sklearn/linear_model/cd_fast.pyx":226 + * daxpy(n_samples, -w[ii], + * (X.data + ii * n_samples * sizeof(DOUBLE)), + * 1, R.data, 1) # <<<<<<<<<<<<<< * - * if fabs(w[ii]) > w_max: - * w_max = fabs(w[ii]) # <<<<<<<<<<<<<< + * # update the maximum absolute coefficient update + */ + cblas_daxpy(__pyx_v_n_samples, (-(*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_w.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_w.diminfo[0].strides))), ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_X->data + ((__pyx_v_ii * __pyx_v_n_samples) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), 1); + goto __pyx_L19; + } + __pyx_L19:; + + /* "sklearn/linear_model/cd_fast.pyx":229 * - * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: + * # update the maximum absolute coefficient update + * d_w_ii = fabs(w[ii] - w_ii) # <<<<<<<<<<<<<< + * if d_w_ii > d_w_max: + * d_w_max = d_w_ii */ - __pyx_t_27 = __pyx_v_ii; - __pyx_v_w_max = fabs((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_27, __pyx_bstride_0_w))); - goto __pyx_L16; - } - __pyx_L16:; - __pyx_L9_continue:; - } + __pyx_t_26 = __pyx_v_ii; + __pyx_v_d_w_ii = fabs(((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_w.rcbuffer->pybuffer.buf, __pyx_t_26, __pyx_pybuffernd_w.diminfo[0].strides)) - __pyx_v_w_ii)); - /* "sklearn/linear_model/cd_fast.pyx":190 - * w_max = fabs(w[ii]) + /* "sklearn/linear_model/cd_fast.pyx":230 + * # update the maximum absolute coefficient update + * d_w_ii = fabs(w[ii] - w_ii) + * if d_w_ii > d_w_max: # <<<<<<<<<<<<<< + * d_w_max = d_w_ii * - * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: # <<<<<<<<<<<<<< - * # the biggest coordinate update of this iteration was smaller than - * # the tolerance: check the duality gap as ultimate stopping */ - __pyx_t_19 = (__pyx_v_w_max == 0.0); - if (!__pyx_t_19) { - __pyx_t_5 = ((__pyx_v_d_w_max / __pyx_v_w_max) < __pyx_v_d_w_tol); - if (!__pyx_t_5) { - __pyx_t_18 = (__pyx_v_n_iter == (__pyx_v_max_iter - 1)); - __pyx_t_28 = __pyx_t_18; - } else { - __pyx_t_28 = __pyx_t_5; - } - __pyx_t_5 = __pyx_t_28; - } else { - __pyx_t_5 = __pyx_t_19; - } - if (__pyx_t_5) { + __pyx_t_11 = ((__pyx_v_d_w_ii > __pyx_v_d_w_max) != 0); + if (__pyx_t_11) { - /* "sklearn/linear_model/cd_fast.pyx":195 - * # criterion + /* "sklearn/linear_model/cd_fast.pyx":231 + * d_w_ii = fabs(w[ii] - w_ii) + * if d_w_ii > d_w_max: + * d_w_max = d_w_ii # <<<<<<<<<<<<<< * - * XtA = np.dot(X.T, R) - beta * w # <<<<<<<<<<<<<< - * if positive: - * dual_norm_XtA = np.max(XtA) + * if fabs(w[ii]) > w_max: */ - __pyx_t_11 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_11, __pyx_n_s__dot); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_11 = PyObject_GetAttr(((PyObject *)__pyx_v_X), __pyx_n_s__T); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_11); - __Pyx_GIVEREF(__pyx_t_11); - __Pyx_INCREF(((PyObject *)__pyx_v_R)); - PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_v_R)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_R)); - __pyx_t_11 = 0; - __pyx_t_11 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_beta); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_3, ((PyObject *)__pyx_v_w)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_11, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_v_XtA); - __pyx_v_XtA = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_v_d_w_max = __pyx_v_d_w_ii; + goto __pyx_L20; + } + __pyx_L20:; - /* "sklearn/linear_model/cd_fast.pyx":196 + /* "sklearn/linear_model/cd_fast.pyx":233 + * d_w_max = d_w_ii + * + * if fabs(w[ii]) > w_max: # <<<<<<<<<<<<<< + * w_max = fabs(w[ii]) * - * XtA = np.dot(X.T, R) - beta * w - * if positive: # <<<<<<<<<<<<<< - * dual_norm_XtA = np.max(XtA) - * else: */ - __pyx_t_5 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_positive)); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_5) { + __pyx_t_27 = __pyx_v_ii; + __pyx_t_11 = ((fabs((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_w.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_w.diminfo[0].strides))) > __pyx_v_w_max) != 0); + if (__pyx_t_11) { - /* "sklearn/linear_model/cd_fast.pyx":197 - * XtA = np.dot(X.T, R) - beta * w - * if positive: - * dual_norm_XtA = np.max(XtA) # <<<<<<<<<<<<<< - * else: - * dual_norm_XtA = linalg.norm(XtA, np.inf) + /* "sklearn/linear_model/cd_fast.pyx":234 + * + * if fabs(w[ii]) > w_max: + * w_max = fabs(w[ii]) # <<<<<<<<<<<<<< + * + * if (w_max == 0.0 */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__max); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(__pyx_v_XtA); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_XtA); - __Pyx_GIVEREF(__pyx_v_XtA); - __pyx_t_11 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_dual_norm_XtA); - __pyx_v_dual_norm_XtA = __pyx_t_11; - __pyx_t_11 = 0; - goto __pyx_L18; - } - /*else*/ { + __pyx_t_28 = __pyx_v_ii; + __pyx_v_w_max = fabs((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_w.rcbuffer->pybuffer.buf, __pyx_t_28, __pyx_pybuffernd_w.diminfo[0].strides))); + goto __pyx_L21; + } + __pyx_L21:; + __pyx_L11_continue:; + } - /* "sklearn/linear_model/cd_fast.pyx":199 - * dual_norm_XtA = np.max(XtA) - * else: - * dual_norm_XtA = linalg.norm(XtA, np.inf) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":236 + * w_max = fabs(w[ii]) * - * # TODO: use squared L2 norm directly + * if (w_max == 0.0 # <<<<<<<<<<<<<< + * or d_w_max / w_max < d_w_tol + * or n_iter == max_iter - 1): */ - __pyx_t_11 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_11, __pyx_n_s__norm); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_11 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_11, __pyx_n_s__inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_11)); - __Pyx_INCREF(__pyx_v_XtA); - PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_v_XtA); - __Pyx_GIVEREF(__pyx_v_XtA); - PyTuple_SET_ITEM(__pyx_t_11, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_11), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_11)); __pyx_t_11 = 0; - __Pyx_XDECREF(__pyx_v_dual_norm_XtA); - __pyx_v_dual_norm_XtA = __pyx_t_2; - __pyx_t_2 = 0; - } - __pyx_L18:; + __pyx_t_20 = ((__pyx_v_w_max == 0.0) != 0); + if (!__pyx_t_20) { + goto __pyx_L24_next_or; + } else { + __pyx_t_11 = __pyx_t_20; + goto __pyx_L23_bool_binop_done; + } + __pyx_L24_next_or:; - /* "sklearn/linear_model/cd_fast.pyx":202 + /* "sklearn/linear_model/cd_fast.pyx":237 * - * # TODO: use squared L2 norm directly - * R_norm = linalg.norm(R) # <<<<<<<<<<<<<< - * w_norm = linalg.norm(w, 2) - * if (dual_norm_XtA > alpha): + * if (w_max == 0.0 + * or d_w_max / w_max < d_w_tol # <<<<<<<<<<<<<< + * or n_iter == max_iter - 1): + * # the biggest coordinate update of this iteration was smaller */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_11 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__norm); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_R)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_R)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_R)); - __pyx_t_3 = PyObject_Call(__pyx_t_11, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_v_R_norm); - __pyx_v_R_norm = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_20 = (((__pyx_v_d_w_max / __pyx_v_w_max) < __pyx_v_d_w_tol) != 0); + if (!__pyx_t_20) { + goto __pyx_L25_next_or; + } else { + __pyx_t_11 = __pyx_t_20; + goto __pyx_L23_bool_binop_done; + } + __pyx_L25_next_or:; - /* "sklearn/linear_model/cd_fast.pyx":203 - * # TODO: use squared L2 norm directly - * R_norm = linalg.norm(R) - * w_norm = linalg.norm(w, 2) # <<<<<<<<<<<<<< - * if (dual_norm_XtA > alpha): - * const = alpha / dual_norm_XtA + /* "sklearn/linear_model/cd_fast.pyx":238 + * if (w_max == 0.0 + * or d_w_max / w_max < d_w_tol + * or n_iter == max_iter - 1): # <<<<<<<<<<<<<< + * # the biggest coordinate update of this iteration was smaller + * # than the tolerance: check the duality gap as ultimate */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__norm); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __Pyx_INCREF(__pyx_int_2); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_2); - __Pyx_GIVEREF(__pyx_int_2); - __pyx_t_11 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_w_norm); - __pyx_v_w_norm = __pyx_t_11; - __pyx_t_11 = 0; - - /* "sklearn/linear_model/cd_fast.pyx":204 - * R_norm = linalg.norm(R) - * w_norm = linalg.norm(w, 2) - * if (dual_norm_XtA > alpha): # <<<<<<<<<<<<<< - * const = alpha / dual_norm_XtA - * A_norm = R_norm * const - */ - __pyx_t_11 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_dual_norm_XtA, __pyx_t_11, Py_GT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_5) { + __pyx_t_20 = ((__pyx_v_n_iter == (__pyx_v_max_iter - 1)) != 0); + __pyx_t_11 = __pyx_t_20; + __pyx_L23_bool_binop_done:; + if (__pyx_t_11) { - /* "sklearn/linear_model/cd_fast.pyx":205 - * w_norm = linalg.norm(w, 2) - * if (dual_norm_XtA > alpha): - * const = alpha / dual_norm_XtA # <<<<<<<<<<<<<< - * A_norm = R_norm * const - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) + /* "sklearn/linear_model/cd_fast.pyx":244 + * + * # XtA = np.dot(X.T, R) - beta * w + * for i in range(n_features): # <<<<<<<<<<<<<< + * XtA[i] = ddot( + * n_samples, */ - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_11 = __Pyx_PyNumber_Divide(__pyx_t_3, __pyx_v_dual_norm_XtA); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_const); - __pyx_v_const = __pyx_t_11; - __pyx_t_11 = 0; - - /* "sklearn/linear_model/cd_fast.pyx":206 - * if (dual_norm_XtA > alpha): - * const = alpha / dual_norm_XtA - * A_norm = R_norm * const # <<<<<<<<<<<<<< - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) - * else: + __pyx_t_13 = __pyx_v_n_features; + for (__pyx_t_17 = 0; __pyx_t_17 < __pyx_t_13; __pyx_t_17+=1) { + __pyx_v_i = __pyx_t_17; + + /* "sklearn/linear_model/cd_fast.pyx":248 + * n_samples, + * (X.data + i * n_samples *sizeof(DOUBLE)), + * 1, R.data, 1) - beta * w[i] # <<<<<<<<<<<<<< + * + * if positive: */ - __pyx_t_11 = PyNumber_Multiply(__pyx_v_R_norm, __pyx_v_const); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_v_A_norm); - __pyx_v_A_norm = __pyx_t_11; - __pyx_t_11 = 0; - - /* "sklearn/linear_model/cd_fast.pyx":207 - * const = alpha / dual_norm_XtA - * A_norm = R_norm * const - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) # <<<<<<<<<<<<<< - * else: - * const = 1.0 + __pyx_t_29 = __pyx_v_i; + + /* "sklearn/linear_model/cd_fast.pyx":245 + * # XtA = np.dot(X.T, R) - beta * w + * for i in range(n_features): + * XtA[i] = ddot( # <<<<<<<<<<<<<< + * n_samples, + * (X.data + i * n_samples *sizeof(DOUBLE)), */ - __pyx_t_11 = PyFloat_FromDouble(0.5); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_3 = PyNumber_Power(__pyx_v_R_norm, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyNumber_Power(__pyx_v_A_norm, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Add(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_t_11, __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_12 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_12 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_gap = __pyx_t_12; - goto __pyx_L19; - } - /*else*/ { + __pyx_t_30 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_XtA.rcbuffer->pybuffer.buf, __pyx_t_30, __pyx_pybuffernd_XtA.diminfo[0].strides) = (cblas_ddot(__pyx_v_n_samples, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_X->data + ((__pyx_v_i * __pyx_v_n_samples) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), 1) - (__pyx_v_beta * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_pybuffernd_w.rcbuffer->pybuffer.buf, __pyx_t_29, __pyx_pybuffernd_w.diminfo[0].strides)))); + } - /* "sklearn/linear_model/cd_fast.pyx":209 - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) - * else: - * const = 1.0 # <<<<<<<<<<<<<< - * gap = R_norm ** 2 + /* "sklearn/linear_model/cd_fast.pyx":250 + * 1, R.data, 1) - beta * w[i] * + * if positive: # <<<<<<<<<<<<<< + * dual_norm_XtA = max(n_features, XtA.data) + * else: */ - __pyx_t_2 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_v_const); - __pyx_v_const = __pyx_t_2; - __pyx_t_2 = 0; + __pyx_t_11 = (__pyx_v_positive != 0); + if (__pyx_t_11) { - /* "sklearn/linear_model/cd_fast.pyx":210 - * else: - * const = 1.0 - * gap = R_norm ** 2 # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":251 * - * gap += alpha * linalg.norm(w, 1) - const * np.dot(R.T, y) + \ + * if positive: + * dual_norm_XtA = max(n_features, XtA.data) # <<<<<<<<<<<<<< + * else: + * dual_norm_XtA = abs_max(n_features, XtA.data) */ - __pyx_t_2 = PyNumber_Power(__pyx_v_R_norm, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_12 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_12 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_gap = __pyx_t_12; - } - __pyx_L19:; + __pyx_v_dual_norm_XtA = __pyx_f_7sklearn_12linear_model_7cd_fast_max(__pyx_v_n_features, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_XtA->data)); + goto __pyx_L28; + } + /*else*/ { + + /* "sklearn/linear_model/cd_fast.pyx":253 + * dual_norm_XtA = max(n_features, XtA.data) + * else: + * dual_norm_XtA = abs_max(n_features, XtA.data) # <<<<<<<<<<<<<< + * + * # R_norm2 = np.dot(R, R) + */ + __pyx_v_dual_norm_XtA = __pyx_f_7sklearn_12linear_model_7cd_fast_abs_max(__pyx_v_n_features, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_XtA->data)); + } + __pyx_L28:; - /* "sklearn/linear_model/cd_fast.pyx":212 - * gap = R_norm ** 2 + /* "sklearn/linear_model/cd_fast.pyx":256 * - * gap += alpha * linalg.norm(w, 1) - const * np.dot(R.T, y) + \ # <<<<<<<<<<<<<< - * 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) + * # R_norm2 = np.dot(R, R) + * R_norm2 = ddot(n_samples, R.data, 1, # <<<<<<<<<<<<<< + * R.data, 1) * */ - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_11 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_11, __pyx_n_s__norm); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_11)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_11, 0, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_t_11, 1, __pyx_int_1); - __Pyx_GIVEREF(__pyx_int_1); - __pyx_t_29 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_11), NULL); if (unlikely(!__pyx_t_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_29); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_11)); __pyx_t_11 = 0; - __pyx_t_11 = PyNumber_Multiply(__pyx_t_1, __pyx_t_29); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; - __pyx_t_29 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_29); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_29, __pyx_n_s__dot); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; - __pyx_t_29 = PyObject_GetAttr(((PyObject *)__pyx_v_R), __pyx_n_s__T); if (unlikely(!__pyx_t_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_29); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_29); - __Pyx_GIVEREF(__pyx_t_29); - __Pyx_INCREF(((PyObject *)__pyx_v_y)); - PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_v_y)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); - __pyx_t_29 = 0; - __pyx_t_29 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_29); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Multiply(__pyx_v_const, __pyx_t_29); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; - __pyx_t_29 = PyNumber_Subtract(__pyx_t_11, __pyx_t_3); if (unlikely(!__pyx_t_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_29); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_R_norm2 = cblas_ddot(__pyx_v_n_samples, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), 1); - /* "sklearn/linear_model/cd_fast.pyx":213 + /* "sklearn/linear_model/cd_fast.pyx":260 * - * gap += alpha * linalg.norm(w, 1) - const * np.dot(R.T, y) + \ - * 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) # <<<<<<<<<<<<<< + * # w_norm2 = np.dot(w, w) + * w_norm2 = ddot(n_features, w.data, 1, # <<<<<<<<<<<<<< + * w.data, 1) * - * if gap < tol: */ - __pyx_t_3 = PyFloat_FromDouble((0.5 * __pyx_v_beta)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_11 = PyNumber_Power(__pyx_v_const, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_1 = PyNumber_Add(__pyx_int_1, __pyx_t_11); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_11 = PyNumber_Multiply(__pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Power(__pyx_v_w_norm, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyNumber_Multiply(__pyx_t_11, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_29, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_InPlaceAdd(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_12 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_12 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_gap = __pyx_t_12; + __pyx_v_w_norm2 = cblas_ddot(__pyx_v_n_features, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_w->data), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_w->data), 1); - /* "sklearn/linear_model/cd_fast.pyx":215 - * 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) + /* "sklearn/linear_model/cd_fast.pyx":263 + * w.data, 1) * - * if gap < tol: # <<<<<<<<<<<<<< - * # return if we reached desired tolerance - * break + * if (dual_norm_XtA > alpha): # <<<<<<<<<<<<<< + * const = alpha / dual_norm_XtA + * A_norm2 = R_norm2 * (const ** 2) */ - __pyx_t_5 = (__pyx_v_gap < __pyx_v_tol); - if (__pyx_t_5) { + __pyx_t_11 = ((__pyx_v_dual_norm_XtA > __pyx_v_alpha) != 0); + if (__pyx_t_11) { - /* "sklearn/linear_model/cd_fast.pyx":217 - * if gap < tol: - * # return if we reached desired tolerance - * break # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":264 + * + * if (dual_norm_XtA > alpha): + * const = alpha / dual_norm_XtA # <<<<<<<<<<<<<< + * A_norm2 = R_norm2 * (const ** 2) + * gap = 0.5 * (R_norm2 + A_norm2) + */ + __pyx_v_const = (__pyx_v_alpha / __pyx_v_dual_norm_XtA); + + /* "sklearn/linear_model/cd_fast.pyx":265 + * if (dual_norm_XtA > alpha): + * const = alpha / dual_norm_XtA + * A_norm2 = R_norm2 * (const ** 2) # <<<<<<<<<<<<<< + * gap = 0.5 * (R_norm2 + A_norm2) + * else: + */ + __pyx_v_A_norm2 = (__pyx_v_R_norm2 * pow(__pyx_v_const, 2.0)); + + /* "sklearn/linear_model/cd_fast.pyx":266 + * const = alpha / dual_norm_XtA + * A_norm2 = R_norm2 * (const ** 2) + * gap = 0.5 * (R_norm2 + A_norm2) # <<<<<<<<<<<<<< + * else: + * const = 1.0 + */ + __pyx_v_gap = (0.5 * (__pyx_v_R_norm2 + __pyx_v_A_norm2)); + goto __pyx_L29; + } + /*else*/ { + + /* "sklearn/linear_model/cd_fast.pyx":268 + * gap = 0.5 * (R_norm2 + A_norm2) + * else: + * const = 1.0 # <<<<<<<<<<<<<< + * gap = R_norm2 + * + */ + __pyx_v_const = 1.0; + + /* "sklearn/linear_model/cd_fast.pyx":269 + * else: + * const = 1.0 + * gap = R_norm2 # <<<<<<<<<<<<<< + * + * l1_norm = dasum(n_features, w.data, 1) + */ + __pyx_v_gap = __pyx_v_R_norm2; + } + __pyx_L29:; + + /* "sklearn/linear_model/cd_fast.pyx":271 + * gap = R_norm2 + * + * l1_norm = dasum(n_features, w.data, 1) # <<<<<<<<<<<<<< * - * return w, gap, tol + * # np.dot(R.T, y) */ - goto __pyx_L8_break; - goto __pyx_L20; + __pyx_v_l1_norm = cblas_dasum(__pyx_v_n_features, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_w->data), 1); + + /* "sklearn/linear_model/cd_fast.pyx":274 + * + * # np.dot(R.T, y) + * gap += (alpha * l1_norm - const * ddot( # <<<<<<<<<<<<<< + * n_samples, + * R.data, 1, + */ + __pyx_v_gap = (__pyx_v_gap + (((__pyx_v_alpha * __pyx_v_l1_norm) - (__pyx_v_const * cblas_ddot(__pyx_v_n_samples, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_y->data), __pyx_v_n_tasks))) + (((0.5 * __pyx_v_beta) * (1.0 + pow(__pyx_v_const, 2.0))) * __pyx_v_w_norm2))); + + /* "sklearn/linear_model/cd_fast.pyx":280 + * + 0.5 * beta * (1 + const ** 2) * (w_norm2)) + * + * if gap < tol: # <<<<<<<<<<<<<< + * # return if we reached desired tolerance + * break + */ + __pyx_t_11 = ((__pyx_v_gap < __pyx_v_tol) != 0); + if (__pyx_t_11) { + + /* "sklearn/linear_model/cd_fast.pyx":282 + * if gap < tol: + * # return if we reached desired tolerance + * break # <<<<<<<<<<<<<< + * + * return w, gap, tol, n_iter + 1 + */ + goto __pyx_L10_break; + } + goto __pyx_L22; + } + __pyx_L22:; + } + __pyx_L10_break:; + } + + /* "sklearn/linear_model/cd_fast.pyx":179 + * " results and is discouraged.") + * + * with nogil: # <<<<<<<<<<<<<< + * + * # R = y - np.dot(X, w) + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L6; + } + __pyx_L6:; } - __pyx_L20:; - goto __pyx_L17; - } - __pyx_L17:; } - __pyx_L8_break:; - /* "sklearn/linear_model/cd_fast.pyx":219 - * break + /* "sklearn/linear_model/cd_fast.pyx":284 + * break * - * return w, gap, tol # <<<<<<<<<<<<<< + * return w, gap, tol, n_iter + 1 # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_tol); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyFloat_FromDouble(__pyx_v_tol); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_1 = __Pyx_PyInt_From_long((__pyx_v_n_iter + 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_w)); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_w)); __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_3 = 0; + __pyx_t_6 = 0; __pyx_t_1 = 0; - __pyx_r = ((PyObject *)__pyx_t_2); - __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/linear_model/cd_fast.pyx":126 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, # <<<<<<<<<<<<<< + * double alpha, double beta, + * np.ndarray[DOUBLE, ndim=2] X, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_t_29); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_norm_cols_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_R); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_w); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_y); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_R.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_XtA.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_norm_cols_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.linear_model.cd_fast.enet_coordinate_descent", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_norm_cols_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_R); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_w); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_y); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_R.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_XtA.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_norm_cols_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_norm_cols_X); __Pyx_XDECREF((PyObject *)__pyx_v_R); - __Pyx_XDECREF(__pyx_v_XtA); - __Pyx_XDECREF(__pyx_v_dual_norm_XtA); - __Pyx_XDECREF(__pyx_v_R_norm); - __Pyx_XDECREF(__pyx_v_w_norm); - __Pyx_XDECREF(__pyx_v_const); - __Pyx_XDECREF(__pyx_v_A_norm); + __Pyx_XDECREF((PyObject *)__pyx_v_XtA); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/cd_fast.pyx":225 +/* "sklearn/linear_model/cd_fast.pyx":290 * @cython.wraparound(False) * @cython.cdivision(True) - * def sparse_enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, # <<<<<<<<<<<<<< + * def sparse_enet_coordinate_descent(double[:] w, # <<<<<<<<<<<<<< * double alpha, double beta, - * np.ndarray[DOUBLE, ndim=1] X_data, + * double[:] X_data, int[:] X_indices, */ -static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordinate_descent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_7cd_fast_3sparse_enet_coordinate_descent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordinate_descent[] = "Cython version of the coordinate descent algorithm for Elastic-Net\n\n We minimize:\n\n 1 norm(y - X w, 2)^2 + alpha norm(w, 1) + beta norm(w, 2)^2\n - ----\n 2 2\n\n "; -static PyMethodDef __pyx_mdef_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordinate_descent = {__Pyx_NAMESTR("sparse_enet_coordinate_descent"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordinate_descent, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordinate_descent)}; -static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordinate_descent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_w = 0; +static PyMethodDef __pyx_mdef_7sklearn_12linear_model_7cd_fast_3sparse_enet_coordinate_descent = {"sparse_enet_coordinate_descent", (PyCFunction)__pyx_pw_7sklearn_12linear_model_7cd_fast_3sparse_enet_coordinate_descent, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordinate_descent}; +static PyObject *__pyx_pw_7sklearn_12linear_model_7cd_fast_3sparse_enet_coordinate_descent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __Pyx_memviewslice __pyx_v_w = { 0, 0, { 0 }, { 0 }, { 0 } }; double __pyx_v_alpha; double __pyx_v_beta; - PyArrayObject *__pyx_v_X_data = 0; - PyArrayObject *__pyx_v_X_indices = 0; - PyArrayObject *__pyx_v_X_indptr = 0; - PyArrayObject *__pyx_v_y = 0; - PyArrayObject *__pyx_v_X_mean = 0; + __Pyx_memviewslice __pyx_v_X_data = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_X_indices = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_X_indptr = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_y = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_X_mean = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_max_iter; double __pyx_v_tol; + PyObject *__pyx_v_rng = 0; + int __pyx_v_random; int __pyx_v_positive; - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - unsigned int __pyx_v_ii; - PyArrayObject *__pyx_v_norm_cols_X = 0; - PyArrayObject *__pyx_v_R = 0; - double __pyx_v_tmp; - double __pyx_v_w_ii; - double __pyx_v_d_w_max; - double __pyx_v_w_max; - double __pyx_v_d_w_ii; - double __pyx_v_X_mean_ii; - double __pyx_v_R_sum; - double __pyx_v_gap; - double __pyx_v_d_w_tol; - unsigned int __pyx_v_jj; - unsigned int __pyx_v_n_iter; - int __pyx_v_center; - PyObject *__pyx_v_X_T_R = NULL; - PyObject *__pyx_v_XtA = NULL; - PyObject *__pyx_v_dual_norm_XtA = NULL; - PyObject *__pyx_v_R_norm = NULL; - PyObject *__pyx_v_w_norm = NULL; - PyObject *__pyx_v_const = NULL; - PyObject *__pyx_v_A_norm = NULL; - Py_buffer __pyx_bstruct_X_mean; - Py_ssize_t __pyx_bstride_0_X_mean = 0; - Py_ssize_t __pyx_bshape_0_X_mean = 0; - Py_buffer __pyx_bstruct_norm_cols_X; - Py_ssize_t __pyx_bstride_0_norm_cols_X = 0; - Py_ssize_t __pyx_bshape_0_norm_cols_X = 0; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_R; - Py_ssize_t __pyx_bstride_0_R = 0; - Py_ssize_t __pyx_bshape_0_R = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; - Py_buffer __pyx_bstruct_w; - Py_ssize_t __pyx_bstride_0_w = 0; - Py_ssize_t __pyx_bshape_0_w = 0; - Py_buffer __pyx_bstruct_y; - Py_ssize_t __pyx_bstride_0_y = 0; - Py_ssize_t __pyx_bshape_0_y = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyArrayObject *__pyx_t_5 = NULL; - unsigned int __pyx_t_6; - unsigned int __pyx_t_7; - unsigned int __pyx_t_8; - long __pyx_t_9; - unsigned int __pyx_t_10; - long __pyx_t_11; - unsigned int __pyx_t_12; - unsigned int __pyx_t_13; - __pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE __pyx_t_14; - unsigned int __pyx_t_15; - int __pyx_t_16; - PyArrayObject *__pyx_t_17 = NULL; - int __pyx_t_18; - PyObject *__pyx_t_19 = NULL; - PyObject *__pyx_t_20 = NULL; - PyObject *__pyx_t_21 = NULL; - long __pyx_t_22; - __pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER __pyx_t_23; - unsigned int __pyx_t_24; - unsigned int __pyx_t_25; - unsigned int __pyx_t_26; - unsigned int __pyx_t_27; - unsigned int __pyx_t_28; - __pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER __pyx_t_29; - unsigned int __pyx_t_30; - double __pyx_t_31; - unsigned int __pyx_t_32; - unsigned int __pyx_t_33; - unsigned int __pyx_t_34; - unsigned int __pyx_t_35; - long __pyx_t_36; - unsigned int __pyx_t_37; - unsigned int __pyx_t_38; - unsigned int __pyx_t_39; - unsigned int __pyx_t_40; - __pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER __pyx_t_41; - unsigned int __pyx_t_42; - unsigned int __pyx_t_43; - unsigned int __pyx_t_44; - long __pyx_t_45; - unsigned int __pyx_t_46; - __pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER __pyx_t_47; - unsigned int __pyx_t_48; - unsigned int __pyx_t_49; - unsigned int __pyx_t_50; - int __pyx_t_51; - unsigned int __pyx_t_52; - unsigned int __pyx_t_53; - long __pyx_t_54; - unsigned int __pyx_t_55; - unsigned int __pyx_t_56; - unsigned int __pyx_t_57; - unsigned int __pyx_t_58; - unsigned int __pyx_t_59; - __pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER __pyx_t_60; - unsigned int __pyx_t_61; - unsigned int __pyx_t_62; - unsigned int __pyx_t_63; - unsigned int __pyx_t_64; - int __pyx_t_65; - int __pyx_t_66; - long __pyx_t_67; - unsigned int __pyx_t_68; - unsigned int __pyx_t_69; - unsigned int __pyx_t_70; - unsigned int __pyx_t_71; - unsigned int __pyx_t_72; - __pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER __pyx_t_73; - PyObject *__pyx_t_74 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__w,&__pyx_n_s__alpha,&__pyx_n_s__beta,&__pyx_n_s__X_data,&__pyx_n_s__X_indices,&__pyx_n_s__X_indptr,&__pyx_n_s__y,&__pyx_n_s__X_mean,&__pyx_n_s__max_iter,&__pyx_n_s__tol,&__pyx_n_s__positive,0}; - __Pyx_RefNannySetupContext("sparse_enet_coordinate_descent"); - __pyx_self = __pyx_self; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("sparse_enet_coordinate_descent (wrapper)", 0); { - PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_w,&__pyx_n_s_alpha,&__pyx_n_s_beta,&__pyx_n_s_X_data,&__pyx_n_s_X_indices,&__pyx_n_s_X_indptr,&__pyx_n_s_y,&__pyx_n_s_X_mean,&__pyx_n_s_max_iter,&__pyx_n_s_tol,&__pyx_n_s_rng,&__pyx_n_s_random,&__pyx_n_s_positive,0}; + PyObject* values[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 13: values[12] = PyTuple_GET_ITEM(__pyx_args, 12); + case 12: values[11] = PyTuple_GET_ITEM(__pyx_args, 11); case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); @@ -3185,78 +3819,80 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordina default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__w); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_w)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__alpha); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_alpha)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 10, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 11, 13, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__beta); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_beta)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 10, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 11, 13, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_data); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_data)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 10, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 11, 13, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_indices); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indices)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 10, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 11, 13, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_indptr); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indptr)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 10, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 11, 13, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[6])) kw_args--; + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 10, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 11, 13, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: - values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_mean); - if (likely(values[7])) kw_args--; + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_mean)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 10, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 11, 13, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: - values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__max_iter); - if (likely(values[8])) kw_args--; + if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_iter)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 10, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 11, 13, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: - values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__tol); - if (likely(values[9])) kw_args--; + if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tol)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 10, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 11, 13, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: + if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_rng)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 11, 13, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 11: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__positive); - if (value) { values[10] = value; kw_args--; } + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random); + if (value) { values[11] = value; kw_args--; } + } + case 12: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_positive); + if (value) { values[12] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "sparse_enet_coordinate_descent") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "sparse_enet_coordinate_descent") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { + case 13: values[12] = PyTuple_GET_ITEM(__pyx_args, 12); + case 12: values[11] = PyTuple_GET_ITEM(__pyx_args, 11); case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); - case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); + values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); @@ -3270,249 +3906,369 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordina default: goto __pyx_L5_argtuple_error; } } - __pyx_v_w = ((PyArrayObject *)values[0]); - __pyx_v_alpha = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_alpha == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_beta = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_beta == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_X_data = ((PyArrayObject *)values[3]); - __pyx_v_X_indices = ((PyArrayObject *)values[4]); - __pyx_v_X_indptr = ((PyArrayObject *)values[5]); - __pyx_v_y = ((PyArrayObject *)values[6]); - __pyx_v_X_mean = ((PyArrayObject *)values[7]); - __pyx_v_max_iter = __Pyx_PyInt_AsInt(values[8]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_tol = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - if (values[10]) { - __pyx_v_positive = __Pyx_PyObject_IsTrue(values[10]); if (unlikely((__pyx_v_positive == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_w = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[0]); if (unlikely(!__pyx_v_w.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_alpha = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_alpha == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_beta = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_beta == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X_data = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[3]); if (unlikely(!__pyx_v_X_data.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 292; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X_indices = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[4]); if (unlikely(!__pyx_v_X_indices.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 292; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X_indptr = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[5]); if (unlikely(!__pyx_v_X_indptr.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 293; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[6]); if (unlikely(!__pyx_v_y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 293; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X_mean = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[7]); if (unlikely(!__pyx_v_X_mean.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_max_iter = __Pyx_PyInt_As_int(values[8]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_tol = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 295; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_rng = values[10]; + if (values[11]) { + __pyx_v_random = __Pyx_PyObject_IsTrue(values[11]); if (unlikely((__pyx_v_random == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 295; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_random = ((int)0); + } + if (values[12]) { + __pyx_v_positive = __Pyx_PyObject_IsTrue(values[12]); if (unlikely((__pyx_v_positive == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/linear_model/cd_fast.pyx":232 - * np.ndarray[DOUBLE, ndim=1] y, - * np.ndarray[DOUBLE, ndim=1] X_mean, - * int max_iter, double tol, bint positive=False): # <<<<<<<<<<<<<< - * """Cython version of the coordinate descent algorithm for Elastic-Net - * - */ __pyx_v_positive = ((int)0); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 10, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("sparse_enet_coordinate_descent", 0, 11, 13, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.linear_model.cd_fast.sparse_enet_coordinate_descent", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_norm_cols_X.buf = NULL; - __pyx_bstruct_R.buf = NULL; - __pyx_bstruct_w.buf = NULL; - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; - __pyx_bstruct_y.buf = NULL; - __pyx_bstruct_X_mean.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_w), __pyx_ptype_5numpy_ndarray, 1, "w", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_data), __pyx_ptype_5numpy_ndarray, 1, "X_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_indices), __pyx_ptype_5numpy_ndarray, 1, "X_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_indptr), __pyx_ptype_5numpy_ndarray, 1, "X_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 229; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_mean), __pyx_ptype_5numpy_ndarray, 1, "X_mean", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_w, (PyObject*)__pyx_v_w, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_w = __pyx_bstruct_w.strides[0]; - __pyx_bshape_0_w = __pyx_bstruct_w.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_v_X_data, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_v_X_indices, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_v_X_indptr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_y, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_y = __pyx_bstruct_y.strides[0]; - __pyx_bshape_0_y = __pyx_bstruct_y.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_mean, (PyObject*)__pyx_v_X_mean, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_X_mean = __pyx_bstruct_X_mean.strides[0]; - __pyx_bshape_0_X_mean = __pyx_bstruct_X_mean.shape[0]; + __pyx_r = __pyx_pf_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordinate_descent(__pyx_self, __pyx_v_w, __pyx_v_alpha, __pyx_v_beta, __pyx_v_X_data, __pyx_v_X_indices, __pyx_v_X_indptr, __pyx_v_y, __pyx_v_X_mean, __pyx_v_max_iter, __pyx_v_tol, __pyx_v_rng, __pyx_v_random, __pyx_v_positive); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordinate_descent(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_w, double __pyx_v_alpha, double __pyx_v_beta, __Pyx_memviewslice __pyx_v_X_data, __Pyx_memviewslice __pyx_v_X_indices, __Pyx_memviewslice __pyx_v_X_indptr, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_X_mean, int __pyx_v_max_iter, double __pyx_v_tol, PyObject *__pyx_v_rng, int __pyx_v_random, int __pyx_v_positive) { + unsigned int __pyx_v_n_samples; + unsigned int __pyx_v_n_features; + unsigned int __pyx_v_ii; + __Pyx_memviewslice __pyx_v_norm_cols_X = { 0, 0, { 0 }, { 0 }, { 0 } }; + unsigned int __pyx_v_startptr; + unsigned int __pyx_v_endptr; + unsigned int __pyx_v_n_tasks; + __Pyx_memviewslice __pyx_v_R = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_X_T_R = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_XtA = { 0, 0, { 0 }, { 0 }, { 0 } }; + double __pyx_v_tmp; + double __pyx_v_w_ii; + double __pyx_v_d_w_max; + double __pyx_v_w_max; + double __pyx_v_d_w_ii; + double __pyx_v_X_mean_ii; + double __pyx_v_R_sum; + double __pyx_v_normalize_sum; + double __pyx_v_gap; + double __pyx_v_d_w_tol; + unsigned int __pyx_v_jj; + unsigned int __pyx_v_n_iter; + unsigned int __pyx_v_f_iter; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_v_rand_r_state_seed; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t *__pyx_v_rand_r_state; + int __pyx_v_center; + double __pyx_v_dual_norm_XtA; + double __pyx_v_R_norm2; + double __pyx_v_w_norm2; + double __pyx_v_const; + double __pyx_v_A_norm2; + double __pyx_v_l1_norm; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + __Pyx_memviewslice __pyx_t_8 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_9 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_10 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_11 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_12; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_t_13; + unsigned int __pyx_t_14; + unsigned int __pyx_t_15; + unsigned int __pyx_t_16; + int __pyx_t_17; + unsigned int __pyx_t_18; + long __pyx_t_19; + unsigned int __pyx_t_20; + unsigned int __pyx_t_21; + unsigned int __pyx_t_22; + unsigned int __pyx_t_23; + unsigned int __pyx_t_24; + unsigned int __pyx_t_25; + int __pyx_t_26; + unsigned int __pyx_t_27; + unsigned int __pyx_t_28; + Py_ssize_t __pyx_t_29; + int __pyx_t_30; + unsigned int __pyx_t_31; + long __pyx_t_32; + unsigned int __pyx_t_33; + unsigned int __pyx_t_34; + unsigned int __pyx_t_35; + unsigned int __pyx_t_36; + unsigned int __pyx_t_37; + unsigned int __pyx_t_38; + int __pyx_t_39; + unsigned int __pyx_t_40; + unsigned int __pyx_t_41; + int __pyx_t_42; + unsigned int __pyx_t_43; + unsigned int __pyx_t_44; + int __pyx_t_45; + unsigned int __pyx_t_46; + unsigned int __pyx_t_47; + unsigned int __pyx_t_48; + unsigned int __pyx_t_49; + unsigned int __pyx_t_50; + unsigned int __pyx_t_51; + unsigned int __pyx_t_52; + int __pyx_t_53; + unsigned int __pyx_t_54; + unsigned int __pyx_t_55; + unsigned int __pyx_t_56; + unsigned int __pyx_t_57; + unsigned int __pyx_t_58; + long __pyx_t_59; + int __pyx_t_60; + unsigned int __pyx_t_61; + unsigned int __pyx_t_62; + unsigned int __pyx_t_63; + unsigned int __pyx_t_64; + int __pyx_t_65; + unsigned int __pyx_t_66; + unsigned int __pyx_t_67; + unsigned int __pyx_t_68; + unsigned int __pyx_t_69; + unsigned int __pyx_t_70; + Py_ssize_t __pyx_t_71; + Py_ssize_t __pyx_t_72; + Py_ssize_t __pyx_t_73; + Py_ssize_t __pyx_t_74; + Py_ssize_t __pyx_t_75; + Py_ssize_t __pyx_t_76; + Py_ssize_t __pyx_t_77; + Py_ssize_t __pyx_t_78; + Py_ssize_t __pyx_t_79; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("sparse_enet_coordinate_descent", 0); - /* "sklearn/linear_model/cd_fast.pyx":244 + /* "sklearn/linear_model/cd_fast.pyx":308 * * # get the data information into easy vars * cdef unsigned int n_samples = y.shape[0] # <<<<<<<<<<<<<< * cdef unsigned int n_features = w.shape[0] * */ - __pyx_v_n_samples = (__pyx_v_y->dimensions[0]); + __pyx_v_n_samples = (__pyx_v_y.shape[0]); - /* "sklearn/linear_model/cd_fast.pyx":245 + /* "sklearn/linear_model/cd_fast.pyx":309 * # get the data information into easy vars * cdef unsigned int n_samples = y.shape[0] * cdef unsigned int n_features = w.shape[0] # <<<<<<<<<<<<<< * * # compute norms of the columns of X */ - __pyx_v_n_features = (__pyx_v_w->dimensions[0]); + __pyx_v_n_features = (__pyx_v_w.shape[0]); - /* "sklearn/linear_model/cd_fast.pyx":249 + /* "sklearn/linear_model/cd_fast.pyx":313 * # compute norms of the columns of X * cdef unsigned int ii - * cdef np.ndarray[DOUBLE, ndim = 1] norm_cols_X = np.zeros(n_features, # <<<<<<<<<<<<<< - * np.float64) - * for ii in xrange(n_features): + * cdef double[:] norm_cols_X = np.zeros(n_features, np.float64) # <<<<<<<<<<<<<< + * + * cdef unsigned int startptr = X_indptr[0] */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyLong_FromUnsignedLong(__pyx_v_n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - - /* "sklearn/linear_model/cd_fast.pyx":250 - * cdef unsigned int ii - * cdef np.ndarray[DOUBLE, ndim = 1] norm_cols_X = np.zeros(n_features, - * np.float64) # <<<<<<<<<<<<<< - * for ii in xrange(n_features): - * norm_cols_X[ii] = ((X_data[X_indptr[ii]:X_indptr[ii + 1]] - \ - */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_1 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = ((PyArrayObject *)__pyx_t_4); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_norm_cols_X, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_norm_cols_X = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_norm_cols_X.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_norm_cols_X = __pyx_bstruct_norm_cols_X.strides[0]; - __pyx_bshape_0_norm_cols_X = __pyx_bstruct_norm_cols_X.shape[0]; + __pyx_t_2 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_features); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = NULL; + __pyx_t_6 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_6 = 1; } } + __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (__pyx_t_4) { + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + } + PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_2 = 0; __pyx_t_5 = 0; - __pyx_v_norm_cols_X = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_8 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_t_1); + if (unlikely(!__pyx_t_8.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_norm_cols_X = __pyx_t_8; + __pyx_t_8.memview = NULL; + __pyx_t_8.data = NULL; - /* "sklearn/linear_model/cd_fast.pyx":251 - * cdef np.ndarray[DOUBLE, ndim = 1] norm_cols_X = np.zeros(n_features, - * np.float64) - * for ii in xrange(n_features): # <<<<<<<<<<<<<< - * norm_cols_X[ii] = ((X_data[X_indptr[ii]:X_indptr[ii + 1]] - \ - * X_mean[ii]) ** 2).sum() + \ - */ - __pyx_t_6 = __pyx_v_n_features; - for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { - __pyx_v_ii = __pyx_t_7; - - /* "sklearn/linear_model/cd_fast.pyx":252 - * np.float64) - * for ii in xrange(n_features): - * norm_cols_X[ii] = ((X_data[X_indptr[ii]:X_indptr[ii + 1]] - \ # <<<<<<<<<<<<<< - * X_mean[ii]) ** 2).sum() + \ - * (n_samples - X_indptr[ii + 1] + X_indptr[ii]) * X_mean[ii] ** 2 - */ - __pyx_t_8 = __pyx_v_ii; - __pyx_t_9 = (__pyx_v_ii + 1); - __pyx_t_4 = __Pyx_PySequence_GetSlice(((PyObject *)__pyx_v_X_data), (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_8, __pyx_bstride_0_X_indptr)), (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_9, __pyx_bstride_0_X_indptr))); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + /* "sklearn/linear_model/cd_fast.pyx":315 + * cdef double[:] norm_cols_X = np.zeros(n_features, np.float64) + * + * cdef unsigned int startptr = X_indptr[0] # <<<<<<<<<<<<<< + * cdef unsigned int endptr + * + */ + __pyx_t_6 = 0; + __pyx_v_startptr = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_6 * __pyx_v_X_indptr.strides[0]) ))); - /* "sklearn/linear_model/cd_fast.pyx":253 - * for ii in xrange(n_features): - * norm_cols_X[ii] = ((X_data[X_indptr[ii]:X_indptr[ii + 1]] - \ - * X_mean[ii]) ** 2).sum() + \ # <<<<<<<<<<<<<< - * (n_samples - X_indptr[ii + 1] + X_indptr[ii]) * X_mean[ii] ** 2 + /* "sklearn/linear_model/cd_fast.pyx":319 * + * # get the number of tasks indirectly, using strides + * cdef unsigned int n_tasks = y.strides[0] / sizeof(DOUBLE) # <<<<<<<<<<<<<< + * + * # initial value of the residuals */ - __pyx_t_10 = __pyx_v_ii; - __pyx_t_3 = PyFloat_FromDouble((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_mean.buf, __pyx_t_10, __pyx_bstride_0_X_mean))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyNumber_Subtract(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Power(__pyx_t_2, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__sum); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_n_tasks = ((__pyx_v_y.strides[0]) / (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))); - /* "sklearn/linear_model/cd_fast.pyx":254 - * norm_cols_X[ii] = ((X_data[X_indptr[ii]:X_indptr[ii + 1]] - \ - * X_mean[ii]) ** 2).sum() + \ - * (n_samples - X_indptr[ii + 1] + X_indptr[ii]) * X_mean[ii] ** 2 # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":322 * * # initial value of the residuals + * cdef double[:] R = y.copy() # <<<<<<<<<<<<<< + * + * cdef double[:] X_T_R = np.zeros(n_features) */ - __pyx_t_11 = (__pyx_v_ii + 1); - __pyx_t_12 = __pyx_v_ii; - __pyx_t_13 = __pyx_v_ii; - __pyx_t_2 = PyFloat_FromDouble((((__pyx_v_n_samples - (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_11, __pyx_bstride_0_X_indptr))) + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_12, __pyx_bstride_0_X_indptr))) * pow((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_mean.buf, __pyx_t_13, __pyx_bstride_0_X_mean)), 2.0))); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyNumber_Add(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_t_9 = __pyx_memoryview_copy_slice_dc_double_c(__pyx_v_y); if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_R = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "sklearn/linear_model/cd_fast.pyx":324 + * cdef double[:] R = y.copy() + * + * cdef double[:] X_T_R = np.zeros(n_features) # <<<<<<<<<<<<<< + * cdef double[:] XtA = np.zeros(n_features) + * + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_features); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_7); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_7, function); + } + } + if (!__pyx_t_5) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_2 = PyTuple_New(1+1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; + PyTuple_SET_ITEM(__pyx_t_2, 0+1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_14 = __pyx_PyFloat_AsDouble(__pyx_t_4); if (unlikely((__pyx_t_14 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_10 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_t_1); + if (unlikely(!__pyx_t_10.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_X_T_R = __pyx_t_10; + __pyx_t_10.memview = NULL; + __pyx_t_10.data = NULL; - /* "sklearn/linear_model/cd_fast.pyx":252 - * np.float64) - * for ii in xrange(n_features): - * norm_cols_X[ii] = ((X_data[X_indptr[ii]:X_indptr[ii + 1]] - \ # <<<<<<<<<<<<<< - * X_mean[ii]) ** 2).sum() + \ - * (n_samples - X_indptr[ii + 1] + X_indptr[ii]) * X_mean[ii] ** 2 + /* "sklearn/linear_model/cd_fast.pyx":325 + * + * cdef double[:] X_T_R = np.zeros(n_features) + * cdef double[:] XtA = np.zeros(n_features) # <<<<<<<<<<<<<< + * + * cdef double tmp */ - __pyx_t_15 = __pyx_v_ii; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_norm_cols_X.buf, __pyx_t_15, __pyx_bstride_0_norm_cols_X) = __pyx_t_14; + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_features); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (!__pyx_t_3) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_7); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = NULL; + PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_11 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_t_1); + if (unlikely(!__pyx_t_11.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_XtA = __pyx_t_11; + __pyx_t_11.memview = NULL; + __pyx_t_11.data = NULL; - /* "sklearn/linear_model/cd_fast.pyx":266 - * cdef double X_mean_ii + /* "sklearn/linear_model/cd_fast.pyx":335 * cdef double R_sum + * cdef double normalize_sum * cdef double gap = tol + 1.0 # <<<<<<<<<<<<<< * cdef double d_w_tol = tol * cdef unsigned int jj */ __pyx_v_gap = (__pyx_v_tol + 1.0); - /* "sklearn/linear_model/cd_fast.pyx":267 - * cdef double R_sum + /* "sklearn/linear_model/cd_fast.pyx":336 + * cdef double normalize_sum * cdef double gap = tol + 1.0 * cdef double d_w_tol = tol # <<<<<<<<<<<<<< * cdef unsigned int jj @@ -3520,1277 +4276,1218 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordina */ __pyx_v_d_w_tol = __pyx_v_tol; - /* "sklearn/linear_model/cd_fast.pyx":270 - * cdef unsigned int jj + /* "sklearn/linear_model/cd_fast.pyx":340 * cdef unsigned int n_iter - * cdef bint center = (X_mean != 0).any() # <<<<<<<<<<<<<< - * - * # initialize the residuals + * cdef unsigned int f_iter + * cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) # <<<<<<<<<<<<<< + * cdef UINT32_t* rand_r_state = &rand_r_state_seed + * cdef bint center = False */ - __pyx_t_4 = PyObject_RichCompare(((PyObject *)__pyx_v_X_mean), __pyx_int_0, Py_NE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_rng, __pyx_n_s_randint); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_e_7sklearn_12linear_model_7cd_fast_RAND_R_MAX); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = NULL; + __pyx_t_12 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_12 = 1; + } + } + __pyx_t_3 = PyTuple_New(2+__pyx_t_12); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (__pyx_t_7) { + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); __pyx_t_7 = NULL; + } + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 0+__pyx_t_12, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1+__pyx_t_12, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_16 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely((__pyx_t_16 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_center = __pyx_t_16; + __pyx_t_13 = __Pyx_PyInt_As_npy_uint32(__pyx_t_1); if (unlikely((__pyx_t_13 == (npy_uint32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_rand_r_state_seed = __pyx_t_13; - /* "sklearn/linear_model/cd_fast.pyx":273 + /* "sklearn/linear_model/cd_fast.pyx":341 + * cdef unsigned int f_iter + * cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + * cdef UINT32_t* rand_r_state = &rand_r_state_seed # <<<<<<<<<<<<<< + * cdef bint center = False * - * # initialize the residuals - * R = y.copy() # <<<<<<<<<<<<<< - * - * for ii in xrange(n_features): */ - __pyx_t_4 = PyObject_GetAttr(((PyObject *)__pyx_v_y), __pyx_n_s__copy); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_17 = ((PyArrayObject *)__pyx_t_2); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_R); - __pyx_t_18 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_R, (PyObject*)__pyx_t_17, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_18 < 0)) { - PyErr_Fetch(&__pyx_t_19, &__pyx_t_20, &__pyx_t_21); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_R, (PyObject*)__pyx_v_R, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_19); Py_XDECREF(__pyx_t_20); Py_XDECREF(__pyx_t_21); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_19, __pyx_t_20, __pyx_t_21); - } - } - __pyx_bstride_0_R = __pyx_bstruct_R.strides[0]; - __pyx_bshape_0_R = __pyx_bstruct_R.shape[0]; - if (unlikely(__pyx_t_18 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_17 = 0; - __pyx_v_R = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; + __pyx_v_rand_r_state = (&__pyx_v_rand_r_state_seed); - /* "sklearn/linear_model/cd_fast.pyx":275 - * R = y.copy() + /* "sklearn/linear_model/cd_fast.pyx":342 + * cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + * cdef UINT32_t* rand_r_state = &rand_r_state_seed + * cdef bint center = False # <<<<<<<<<<<<<< * - * for ii in xrange(n_features): # <<<<<<<<<<<<<< - * # sparse X column / dense w dot product - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): + * with nogil: */ - __pyx_t_6 = __pyx_v_n_features; - for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { - __pyx_v_ii = __pyx_t_7; + __pyx_v_center = 0; - /* "sklearn/linear_model/cd_fast.pyx":277 - * for ii in xrange(n_features): - * # sparse X column / dense w dot product - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): # <<<<<<<<<<<<<< - * R[X_indices[jj]] -= X_data[jj] * w[ii] - * if center: + /* "sklearn/linear_model/cd_fast.pyx":344 + * cdef bint center = False + * + * with nogil: # <<<<<<<<<<<<<< + * # center = (X_mean != 0).any() + * for ii in range(n_features): */ - __pyx_t_22 = (__pyx_v_ii + 1); - __pyx_t_23 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_22, __pyx_bstride_0_X_indptr)); - __pyx_t_24 = __pyx_v_ii; - for (__pyx_t_25 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_24, __pyx_bstride_0_X_indptr)); __pyx_t_25 < __pyx_t_23; __pyx_t_25+=1) { - __pyx_v_jj = __pyx_t_25; - - /* "sklearn/linear_model/cd_fast.pyx":278 - * # sparse X column / dense w dot product - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * R[X_indices[jj]] -= X_data[jj] * w[ii] # <<<<<<<<<<<<<< - * if center: - * R += X_mean[ii] * w[ii] + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/linear_model/cd_fast.pyx":346 + * with nogil: + * # center = (X_mean != 0).any() + * for ii in range(n_features): # <<<<<<<<<<<<<< + * if X_mean[ii]: + * center = True + */ + __pyx_t_14 = __pyx_v_n_features; + for (__pyx_t_15 = 0; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { + __pyx_v_ii = __pyx_t_15; + + /* "sklearn/linear_model/cd_fast.pyx":347 + * # center = (X_mean != 0).any() + * for ii in range(n_features): + * if X_mean[ii]: # <<<<<<<<<<<<<< + * center = True + * break */ - __pyx_t_26 = __pyx_v_jj; - __pyx_t_27 = __pyx_v_ii; - __pyx_t_28 = __pyx_v_jj; - __pyx_t_29 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indices.buf, __pyx_t_28, __pyx_bstride_0_X_indices)); - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_R.buf, __pyx_t_29, __pyx_bstride_0_R) -= ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_26, __pyx_bstride_0_X_data)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_27, __pyx_bstride_0_w))); - } + __pyx_t_16 = __pyx_v_ii; + __pyx_t_17 = ((*((double *) ( /* dim=0 */ (__pyx_v_X_mean.data + __pyx_t_16 * __pyx_v_X_mean.strides[0]) ))) != 0); + if (__pyx_t_17) { - /* "sklearn/linear_model/cd_fast.pyx":279 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * R[X_indices[jj]] -= X_data[jj] * w[ii] - * if center: # <<<<<<<<<<<<<< - * R += X_mean[ii] * w[ii] + /* "sklearn/linear_model/cd_fast.pyx":348 + * for ii in range(n_features): + * if X_mean[ii]: + * center = True # <<<<<<<<<<<<<< + * break * */ - if (__pyx_v_center) { + __pyx_v_center = 1; - /* "sklearn/linear_model/cd_fast.pyx":280 - * R[X_indices[jj]] -= X_data[jj] * w[ii] - * if center: - * R += X_mean[ii] * w[ii] # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":349 + * if X_mean[ii]: + * center = True + * break # <<<<<<<<<<<<<< * - * tol = tol * linalg.norm(y) ** 2 + * for ii in range(n_features): */ - __pyx_t_25 = __pyx_v_ii; - __pyx_t_30 = __pyx_v_ii; - __pyx_t_2 = PyFloat_FromDouble(((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_mean.buf, __pyx_t_25, __pyx_bstride_0_X_mean)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_30, __pyx_bstride_0_w)))); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyNumber_InPlaceAdd(((PyObject *)__pyx_v_R), __pyx_t_2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_17 = ((PyArrayObject *)__pyx_t_4); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_R); - __pyx_t_18 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_R, (PyObject*)__pyx_t_17, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_18 < 0)) { - PyErr_Fetch(&__pyx_t_21, &__pyx_t_20, &__pyx_t_19); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_R, (PyObject*)__pyx_v_R, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_21); Py_XDECREF(__pyx_t_20); Py_XDECREF(__pyx_t_19); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_21, __pyx_t_20, __pyx_t_19); + goto __pyx_L7_break; } } - __pyx_bstride_0_R = __pyx_bstruct_R.strides[0]; - __pyx_bshape_0_R = __pyx_bstruct_R.shape[0]; - if (unlikely(__pyx_t_18 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_17 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_R)); - __pyx_v_R = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; - goto __pyx_L12; - } - __pyx_L12:; - } + __pyx_L7_break:; - /* "sklearn/linear_model/cd_fast.pyx":282 - * R += X_mean[ii] * w[ii] - * - * tol = tol * linalg.norm(y) ** 2 # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":351 + * break * - * for n_iter in range(max_iter): + * for ii in range(n_features): # <<<<<<<<<<<<<< + * X_mean_ii = X_mean[ii] + * endptr = X_indptr[ii + 1] */ - __pyx_t_4 = PyFloat_FromDouble(__pyx_v_tol); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__norm); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_y)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_y)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Power(__pyx_t_1, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_t_4, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_31 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_31 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_tol = __pyx_t_31; + __pyx_t_14 = __pyx_v_n_features; + for (__pyx_t_15 = 0; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { + __pyx_v_ii = __pyx_t_15; - /* "sklearn/linear_model/cd_fast.pyx":284 - * tol = tol * linalg.norm(y) ** 2 + /* "sklearn/linear_model/cd_fast.pyx":352 * - * for n_iter in range(max_iter): # <<<<<<<<<<<<<< - * - * w_max = 0.0 + * for ii in range(n_features): + * X_mean_ii = X_mean[ii] # <<<<<<<<<<<<<< + * endptr = X_indptr[ii + 1] + * normalize_sum = 0.0 */ - __pyx_t_18 = __pyx_v_max_iter; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_18; __pyx_t_6+=1) { - __pyx_v_n_iter = __pyx_t_6; + __pyx_t_18 = __pyx_v_ii; + __pyx_v_X_mean_ii = (*((double *) ( /* dim=0 */ (__pyx_v_X_mean.data + __pyx_t_18 * __pyx_v_X_mean.strides[0]) ))); - /* "sklearn/linear_model/cd_fast.pyx":286 - * for n_iter in range(max_iter): - * - * w_max = 0.0 # <<<<<<<<<<<<<< - * d_w_max = 0.0 - * + /* "sklearn/linear_model/cd_fast.pyx":353 + * for ii in range(n_features): + * X_mean_ii = X_mean[ii] + * endptr = X_indptr[ii + 1] # <<<<<<<<<<<<<< + * normalize_sum = 0.0 + * w_ii = w[ii] */ - __pyx_v_w_max = 0.0; + __pyx_t_19 = (__pyx_v_ii + 1); + __pyx_v_endptr = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_19 * __pyx_v_X_indptr.strides[0]) ))); - /* "sklearn/linear_model/cd_fast.pyx":287 - * - * w_max = 0.0 - * d_w_max = 0.0 # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":354 + * X_mean_ii = X_mean[ii] + * endptr = X_indptr[ii + 1] + * normalize_sum = 0.0 # <<<<<<<<<<<<<< + * w_ii = w[ii] * - * for ii in xrange(n_features): # Loop over coordinates */ - __pyx_v_d_w_max = 0.0; + __pyx_v_normalize_sum = 0.0; - /* "sklearn/linear_model/cd_fast.pyx":289 - * d_w_max = 0.0 - * - * for ii in xrange(n_features): # Loop over coordinates # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":355 + * endptr = X_indptr[ii + 1] + * normalize_sum = 0.0 + * w_ii = w[ii] # <<<<<<<<<<<<<< * - * if norm_cols_X[ii] == 0.0: + * for jj in range(startptr, endptr): */ - __pyx_t_7 = __pyx_v_n_features; - for (__pyx_t_32 = 0; __pyx_t_32 < __pyx_t_7; __pyx_t_32+=1) { - __pyx_v_ii = __pyx_t_32; + __pyx_t_20 = __pyx_v_ii; + __pyx_v_w_ii = (*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_20 * __pyx_v_w.strides[0]) ))); - /* "sklearn/linear_model/cd_fast.pyx":291 - * for ii in xrange(n_features): # Loop over coordinates - * - * if norm_cols_X[ii] == 0.0: # <<<<<<<<<<<<<< - * continue + /* "sklearn/linear_model/cd_fast.pyx":357 + * w_ii = w[ii] * + * for jj in range(startptr, endptr): # <<<<<<<<<<<<<< + * normalize_sum += (X_data[jj] - X_mean_ii) ** 2 + * R[X_indices[jj]] -= X_data[jj] * w_ii */ - __pyx_t_33 = __pyx_v_ii; - __pyx_t_16 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_norm_cols_X.buf, __pyx_t_33, __pyx_bstride_0_norm_cols_X)) == 0.0); - if (__pyx_t_16) { + __pyx_t_21 = __pyx_v_endptr; + for (__pyx_t_22 = __pyx_v_startptr; __pyx_t_22 < __pyx_t_21; __pyx_t_22+=1) { + __pyx_v_jj = __pyx_t_22; - /* "sklearn/linear_model/cd_fast.pyx":292 - * - * if norm_cols_X[ii] == 0.0: - * continue # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":358 * - * w_ii = w[ii] # Store previous value + * for jj in range(startptr, endptr): + * normalize_sum += (X_data[jj] - X_mean_ii) ** 2 # <<<<<<<<<<<<<< + * R[X_indices[jj]] -= X_data[jj] * w_ii + * norm_cols_X[ii] = normalize_sum + \ */ - goto __pyx_L15_continue; - goto __pyx_L17; - } - __pyx_L17:; + __pyx_t_23 = __pyx_v_jj; + __pyx_v_normalize_sum = (__pyx_v_normalize_sum + pow(((*((double *) ( /* dim=0 */ (__pyx_v_X_data.data + __pyx_t_23 * __pyx_v_X_data.strides[0]) ))) - __pyx_v_X_mean_ii), 2.0)); - /* "sklearn/linear_model/cd_fast.pyx":294 - * continue - * - * w_ii = w[ii] # Store previous value # <<<<<<<<<<<<<< - * X_mean_ii = X_mean[ii] - * + /* "sklearn/linear_model/cd_fast.pyx":359 + * for jj in range(startptr, endptr): + * normalize_sum += (X_data[jj] - X_mean_ii) ** 2 + * R[X_indices[jj]] -= X_data[jj] * w_ii # <<<<<<<<<<<<<< + * norm_cols_X[ii] = normalize_sum + \ + * (n_samples - endptr + startptr) * X_mean_ii ** 2 */ - __pyx_t_34 = __pyx_v_ii; - __pyx_v_w_ii = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_34, __pyx_bstride_0_w)); + __pyx_t_24 = __pyx_v_jj; + __pyx_t_25 = __pyx_v_jj; + __pyx_t_26 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indices.data + __pyx_t_25 * __pyx_v_X_indices.strides[0]) ))); + *((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_26 * __pyx_v_R.strides[0]) )) -= ((*((double *) ( /* dim=0 */ (__pyx_v_X_data.data + __pyx_t_24 * __pyx_v_X_data.strides[0]) ))) * __pyx_v_w_ii); + } - /* "sklearn/linear_model/cd_fast.pyx":295 + /* "sklearn/linear_model/cd_fast.pyx":360 + * normalize_sum += (X_data[jj] - X_mean_ii) ** 2 + * R[X_indices[jj]] -= X_data[jj] * w_ii + * norm_cols_X[ii] = normalize_sum + \ # <<<<<<<<<<<<<< + * (n_samples - endptr + startptr) * X_mean_ii ** 2 * - * w_ii = w[ii] # Store previous value - * X_mean_ii = X_mean[ii] # <<<<<<<<<<<<<< + */ + __pyx_t_21 = __pyx_v_ii; + *((double *) ( /* dim=0 */ (__pyx_v_norm_cols_X.data + __pyx_t_21 * __pyx_v_norm_cols_X.strides[0]) )) = (__pyx_v_normalize_sum + (((__pyx_v_n_samples - __pyx_v_endptr) + __pyx_v_startptr) * pow(__pyx_v_X_mean_ii, 2.0))); + + /* "sklearn/linear_model/cd_fast.pyx":363 + * (n_samples - endptr + startptr) * X_mean_ii ** 2 * - * if w_ii != 0.0: + * if center: # <<<<<<<<<<<<<< + * for jj in range(n_samples): + * R[jj] += X_mean_ii * w_ii */ - __pyx_t_35 = __pyx_v_ii; - __pyx_v_X_mean_ii = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_mean.buf, __pyx_t_35, __pyx_bstride_0_X_mean)); + __pyx_t_17 = (__pyx_v_center != 0); + if (__pyx_t_17) { - /* "sklearn/linear_model/cd_fast.pyx":297 - * X_mean_ii = X_mean[ii] + /* "sklearn/linear_model/cd_fast.pyx":364 * - * if w_ii != 0.0: # <<<<<<<<<<<<<< - * # R += w_ii * X[:,ii] - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): + * if center: + * for jj in range(n_samples): # <<<<<<<<<<<<<< + * R[jj] += X_mean_ii * w_ii + * startptr = endptr */ - __pyx_t_16 = (__pyx_v_w_ii != 0.0); - if (__pyx_t_16) { + __pyx_t_22 = __pyx_v_n_samples; + for (__pyx_t_27 = 0; __pyx_t_27 < __pyx_t_22; __pyx_t_27+=1) { + __pyx_v_jj = __pyx_t_27; - /* "sklearn/linear_model/cd_fast.pyx":299 - * if w_ii != 0.0: - * # R += w_ii * X[:,ii] - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): # <<<<<<<<<<<<<< - * R[X_indices[jj]] += X_data[jj] * w_ii - * if center: + /* "sklearn/linear_model/cd_fast.pyx":365 + * if center: + * for jj in range(n_samples): + * R[jj] += X_mean_ii * w_ii # <<<<<<<<<<<<<< + * startptr = endptr + * */ - __pyx_t_36 = (__pyx_v_ii + 1); - __pyx_t_23 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_36, __pyx_bstride_0_X_indptr)); - __pyx_t_37 = __pyx_v_ii; - for (__pyx_t_38 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_37, __pyx_bstride_0_X_indptr)); __pyx_t_38 < __pyx_t_23; __pyx_t_38+=1) { - __pyx_v_jj = __pyx_t_38; + __pyx_t_28 = __pyx_v_jj; + *((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_28 * __pyx_v_R.strides[0]) )) += (__pyx_v_X_mean_ii * __pyx_v_w_ii); + } + goto __pyx_L13; + } + __pyx_L13:; - /* "sklearn/linear_model/cd_fast.pyx":300 - * # R += w_ii * X[:,ii] - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * R[X_indices[jj]] += X_data[jj] * w_ii # <<<<<<<<<<<<<< - * if center: - * for jj in xrange(n_samples): + /* "sklearn/linear_model/cd_fast.pyx":366 + * for jj in range(n_samples): + * R[jj] += X_mean_ii * w_ii + * startptr = endptr # <<<<<<<<<<<<<< + * + * # tol *= np.dot(y, y) */ - __pyx_t_39 = __pyx_v_jj; - __pyx_t_40 = __pyx_v_jj; - __pyx_t_41 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indices.buf, __pyx_t_40, __pyx_bstride_0_X_indices)); - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_R.buf, __pyx_t_41, __pyx_bstride_0_R) += ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_39, __pyx_bstride_0_X_data)) * __pyx_v_w_ii); + __pyx_v_startptr = __pyx_v_endptr; } - /* "sklearn/linear_model/cd_fast.pyx":301 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * R[X_indices[jj]] += X_data[jj] * w_ii - * if center: # <<<<<<<<<<<<<< - * for jj in xrange(n_samples): - * R[jj] -= X_mean_ii * w[ii] + /* "sklearn/linear_model/cd_fast.pyx":369 + * + * # tol *= np.dot(y, y) + * tol *= ddot(n_samples, &y[0], 1, &y[0], 1) # <<<<<<<<<<<<<< + * + * for n_iter in range(max_iter): */ - if (__pyx_v_center) { + __pyx_t_12 = 0; + __pyx_t_29 = 0; + __pyx_v_tol = (__pyx_v_tol * cblas_ddot(__pyx_v_n_samples, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(&(*((double *) ( /* dim=0 */ (__pyx_v_y.data + __pyx_t_12 * __pyx_v_y.strides[0]) ))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(&(*((double *) ( /* dim=0 */ (__pyx_v_y.data + __pyx_t_29 * __pyx_v_y.strides[0]) ))))), 1)); - /* "sklearn/linear_model/cd_fast.pyx":302 - * R[X_indices[jj]] += X_data[jj] * w_ii - * if center: - * for jj in xrange(n_samples): # <<<<<<<<<<<<<< - * R[jj] -= X_mean_ii * w[ii] + /* "sklearn/linear_model/cd_fast.pyx":371 + * tol *= ddot(n_samples, &y[0], 1, &y[0], 1) * + * for n_iter in range(max_iter): # <<<<<<<<<<<<<< + * + * w_max = 0.0 */ - __pyx_t_38 = __pyx_v_n_samples; - for (__pyx_t_42 = 0; __pyx_t_42 < __pyx_t_38; __pyx_t_42+=1) { - __pyx_v_jj = __pyx_t_42; + __pyx_t_30 = __pyx_v_max_iter; + for (__pyx_t_14 = 0; __pyx_t_14 < __pyx_t_30; __pyx_t_14+=1) { + __pyx_v_n_iter = __pyx_t_14; - /* "sklearn/linear_model/cd_fast.pyx":303 - * if center: - * for jj in xrange(n_samples): - * R[jj] -= X_mean_ii * w[ii] # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":373 + * for n_iter in range(max_iter): + * + * w_max = 0.0 # <<<<<<<<<<<<<< + * d_w_max = 0.0 * - * # tmp = (X[:,ii] * R).sum() */ - __pyx_t_43 = __pyx_v_ii; - __pyx_t_44 = __pyx_v_jj; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_R.buf, __pyx_t_44, __pyx_bstride_0_R) -= (__pyx_v_X_mean_ii * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_43, __pyx_bstride_0_w))); - } - goto __pyx_L21; - } - __pyx_L21:; - goto __pyx_L18; - } - __pyx_L18:; + __pyx_v_w_max = 0.0; - /* "sklearn/linear_model/cd_fast.pyx":306 + /* "sklearn/linear_model/cd_fast.pyx":374 * - * # tmp = (X[:,ii] * R).sum() - * tmp = 0.0 # <<<<<<<<<<<<<< - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * tmp += R[X_indices[jj]] * X_data[jj] + * w_max = 0.0 + * d_w_max = 0.0 # <<<<<<<<<<<<<< + * + * for f_iter in range(n_features): # Loop over coordinates */ - __pyx_v_tmp = 0.0; + __pyx_v_d_w_max = 0.0; - /* "sklearn/linear_model/cd_fast.pyx":307 - * # tmp = (X[:,ii] * R).sum() - * tmp = 0.0 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): # <<<<<<<<<<<<<< - * tmp += R[X_indices[jj]] * X_data[jj] + /* "sklearn/linear_model/cd_fast.pyx":376 + * d_w_max = 0.0 * + * for f_iter in range(n_features): # Loop over coordinates # <<<<<<<<<<<<<< + * if random: + * ii = rand_int(n_features, rand_r_state) */ - __pyx_t_45 = (__pyx_v_ii + 1); - __pyx_t_23 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_45, __pyx_bstride_0_X_indptr)); - __pyx_t_38 = __pyx_v_ii; - for (__pyx_t_42 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_38, __pyx_bstride_0_X_indptr)); __pyx_t_42 < __pyx_t_23; __pyx_t_42+=1) { - __pyx_v_jj = __pyx_t_42; + __pyx_t_15 = __pyx_v_n_features; + for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_15; __pyx_t_22+=1) { + __pyx_v_f_iter = __pyx_t_22; - /* "sklearn/linear_model/cd_fast.pyx":308 - * tmp = 0.0 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * tmp += R[X_indices[jj]] * X_data[jj] # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":377 * - * if center: + * for f_iter in range(n_features): # Loop over coordinates + * if random: # <<<<<<<<<<<<<< + * ii = rand_int(n_features, rand_r_state) + * else: */ - __pyx_t_46 = __pyx_v_jj; - __pyx_t_47 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indices.buf, __pyx_t_46, __pyx_bstride_0_X_indices)); - __pyx_t_48 = __pyx_v_jj; - __pyx_v_tmp = (__pyx_v_tmp + ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_R.buf, __pyx_t_47, __pyx_bstride_0_R)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_48, __pyx_bstride_0_X_data)))); - } + __pyx_t_17 = (__pyx_v_random != 0); + if (__pyx_t_17) { + + /* "sklearn/linear_model/cd_fast.pyx":378 + * for f_iter in range(n_features): # Loop over coordinates + * if random: + * ii = rand_int(n_features, rand_r_state) # <<<<<<<<<<<<<< + * else: + * ii = f_iter + */ + __pyx_v_ii = __pyx_f_7sklearn_12linear_model_7cd_fast_rand_int(__pyx_v_n_features, __pyx_v_rand_r_state); + goto __pyx_L20; + } + /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":310 - * tmp += R[X_indices[jj]] * X_data[jj] + /* "sklearn/linear_model/cd_fast.pyx":380 + * ii = rand_int(n_features, rand_r_state) + * else: + * ii = f_iter # <<<<<<<<<<<<<< * - * if center: # <<<<<<<<<<<<<< - * R_sum = 0.0 - * for jj in xrange(n_samples): + * if norm_cols_X[ii] == 0.0: */ - if (__pyx_v_center) { + __pyx_v_ii = __pyx_v_f_iter; + } + __pyx_L20:; - /* "sklearn/linear_model/cd_fast.pyx":311 + /* "sklearn/linear_model/cd_fast.pyx":382 + * ii = f_iter + * + * if norm_cols_X[ii] == 0.0: # <<<<<<<<<<<<<< + * continue * - * if center: - * R_sum = 0.0 # <<<<<<<<<<<<<< - * for jj in xrange(n_samples): - * R_sum += R[jj] */ - __pyx_v_R_sum = 0.0; + __pyx_t_27 = __pyx_v_ii; + __pyx_t_17 = (((*((double *) ( /* dim=0 */ (__pyx_v_norm_cols_X.data + __pyx_t_27 * __pyx_v_norm_cols_X.strides[0]) ))) == 0.0) != 0); + if (__pyx_t_17) { - /* "sklearn/linear_model/cd_fast.pyx":312 - * if center: - * R_sum = 0.0 - * for jj in xrange(n_samples): # <<<<<<<<<<<<<< - * R_sum += R[jj] - * tmp -= R_sum * X_mean_ii + /* "sklearn/linear_model/cd_fast.pyx":383 + * + * if norm_cols_X[ii] == 0.0: + * continue # <<<<<<<<<<<<<< + * + * startptr = X_indptr[ii] */ - __pyx_t_42 = __pyx_v_n_samples; - for (__pyx_t_49 = 0; __pyx_t_49 < __pyx_t_42; __pyx_t_49+=1) { - __pyx_v_jj = __pyx_t_49; + goto __pyx_L18_continue; + } - /* "sklearn/linear_model/cd_fast.pyx":313 - * R_sum = 0.0 - * for jj in xrange(n_samples): - * R_sum += R[jj] # <<<<<<<<<<<<<< - * tmp -= R_sum * X_mean_ii + /* "sklearn/linear_model/cd_fast.pyx":385 + * continue * + * startptr = X_indptr[ii] # <<<<<<<<<<<<<< + * endptr = X_indptr[ii + 1] + * w_ii = w[ii] # Store previous value */ - __pyx_t_50 = __pyx_v_jj; - __pyx_v_R_sum = (__pyx_v_R_sum + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_R.buf, __pyx_t_50, __pyx_bstride_0_R))); - } + __pyx_t_31 = __pyx_v_ii; + __pyx_v_startptr = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_31 * __pyx_v_X_indptr.strides[0]) ))); - /* "sklearn/linear_model/cd_fast.pyx":314 - * for jj in xrange(n_samples): - * R_sum += R[jj] - * tmp -= R_sum * X_mean_ii # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":386 * - * if positive and tmp < 0.0: + * startptr = X_indptr[ii] + * endptr = X_indptr[ii + 1] # <<<<<<<<<<<<<< + * w_ii = w[ii] # Store previous value + * X_mean_ii = X_mean[ii] */ - __pyx_v_tmp = (__pyx_v_tmp - (__pyx_v_R_sum * __pyx_v_X_mean_ii)); - goto __pyx_L26; - } - __pyx_L26:; + __pyx_t_32 = (__pyx_v_ii + 1); + __pyx_v_endptr = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_32 * __pyx_v_X_indptr.strides[0]) ))); - /* "sklearn/linear_model/cd_fast.pyx":316 - * tmp -= R_sum * X_mean_ii + /* "sklearn/linear_model/cd_fast.pyx":387 + * startptr = X_indptr[ii] + * endptr = X_indptr[ii + 1] + * w_ii = w[ii] # Store previous value # <<<<<<<<<<<<<< + * X_mean_ii = X_mean[ii] * - * if positive and tmp < 0.0: # <<<<<<<<<<<<<< - * w[ii] = 0.0 - * else: */ - if (__pyx_v_positive) { - __pyx_t_16 = (__pyx_v_tmp < 0.0); - __pyx_t_51 = __pyx_t_16; - } else { - __pyx_t_51 = __pyx_v_positive; - } - if (__pyx_t_51) { + __pyx_t_33 = __pyx_v_ii; + __pyx_v_w_ii = (*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_33 * __pyx_v_w.strides[0]) ))); - /* "sklearn/linear_model/cd_fast.pyx":317 + /* "sklearn/linear_model/cd_fast.pyx":388 + * endptr = X_indptr[ii + 1] + * w_ii = w[ii] # Store previous value + * X_mean_ii = X_mean[ii] # <<<<<<<<<<<<<< * - * if positive and tmp < 0.0: - * w[ii] = 0.0 # <<<<<<<<<<<<<< - * else: - * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ + * if w_ii != 0.0: */ - __pyx_t_42 = __pyx_v_ii; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_42, __pyx_bstride_0_w) = 0.0; - goto __pyx_L29; - } - /*else*/ { + __pyx_t_34 = __pyx_v_ii; + __pyx_v_X_mean_ii = (*((double *) ( /* dim=0 */ (__pyx_v_X_mean.data + __pyx_t_34 * __pyx_v_X_mean.strides[0]) ))); - /* "sklearn/linear_model/cd_fast.pyx":320 - * else: - * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ - * / (norm_cols_X[ii] + beta) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":390 + * X_mean_ii = X_mean[ii] * - * if w[ii] != 0.0: + * if w_ii != 0.0: # <<<<<<<<<<<<<< + * # R += w_ii * X[:,ii] + * for jj in range(startptr, endptr): */ - __pyx_t_49 = __pyx_v_ii; + __pyx_t_17 = ((__pyx_v_w_ii != 0.0) != 0); + if (__pyx_t_17) { - /* "sklearn/linear_model/cd_fast.pyx":319 - * w[ii] = 0.0 - * else: - * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ # <<<<<<<<<<<<<< - * / (norm_cols_X[ii] + beta) + /* "sklearn/linear_model/cd_fast.pyx":392 + * if w_ii != 0.0: + * # R += w_ii * X[:,ii] + * for jj in range(startptr, endptr): # <<<<<<<<<<<<<< + * R[X_indices[jj]] += X_data[jj] * w_ii + * if center: + */ + __pyx_t_35 = __pyx_v_endptr; + for (__pyx_t_36 = __pyx_v_startptr; __pyx_t_36 < __pyx_t_35; __pyx_t_36+=1) { + __pyx_v_jj = __pyx_t_36; + + /* "sklearn/linear_model/cd_fast.pyx":393 + * # R += w_ii * X[:,ii] + * for jj in range(startptr, endptr): + * R[X_indices[jj]] += X_data[jj] * w_ii # <<<<<<<<<<<<<< + * if center: + * for jj in range(n_samples): + */ + __pyx_t_37 = __pyx_v_jj; + __pyx_t_38 = __pyx_v_jj; + __pyx_t_39 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indices.data + __pyx_t_38 * __pyx_v_X_indices.strides[0]) ))); + *((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_39 * __pyx_v_R.strides[0]) )) += ((*((double *) ( /* dim=0 */ (__pyx_v_X_data.data + __pyx_t_37 * __pyx_v_X_data.strides[0]) ))) * __pyx_v_w_ii); + } + + /* "sklearn/linear_model/cd_fast.pyx":394 + * for jj in range(startptr, endptr): + * R[X_indices[jj]] += X_data[jj] * w_ii + * if center: # <<<<<<<<<<<<<< + * for jj in range(n_samples): + * R[jj] -= X_mean_ii * w_ii + */ + __pyx_t_17 = (__pyx_v_center != 0); + if (__pyx_t_17) { + + /* "sklearn/linear_model/cd_fast.pyx":395 + * R[X_indices[jj]] += X_data[jj] * w_ii + * if center: + * for jj in range(n_samples): # <<<<<<<<<<<<<< + * R[jj] -= X_mean_ii * w_ii * */ - __pyx_t_52 = __pyx_v_ii; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_52, __pyx_bstride_0_w) = ((__pyx_f_7sklearn_12linear_model_7cd_fast_fsign(__pyx_v_tmp) * __pyx_f_7sklearn_12linear_model_7cd_fast_fmax((fabs(__pyx_v_tmp) - __pyx_v_alpha), 0.0)) / ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_norm_cols_X.buf, __pyx_t_49, __pyx_bstride_0_norm_cols_X)) + __pyx_v_beta)); - } - __pyx_L29:; + __pyx_t_35 = __pyx_v_n_samples; + for (__pyx_t_36 = 0; __pyx_t_36 < __pyx_t_35; __pyx_t_36+=1) { + __pyx_v_jj = __pyx_t_36; + + /* "sklearn/linear_model/cd_fast.pyx":396 + * if center: + * for jj in range(n_samples): + * R[jj] -= X_mean_ii * w_ii # <<<<<<<<<<<<<< + * + * # tmp = (X[:,ii] * R).sum() + */ + __pyx_t_40 = __pyx_v_jj; + *((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_40 * __pyx_v_R.strides[0]) )) -= (__pyx_v_X_mean_ii * __pyx_v_w_ii); + } + goto __pyx_L25; + } + __pyx_L25:; + goto __pyx_L22; + } + __pyx_L22:; - /* "sklearn/linear_model/cd_fast.pyx":322 - * / (norm_cols_X[ii] + beta) + /* "sklearn/linear_model/cd_fast.pyx":399 * - * if w[ii] != 0.0: # <<<<<<<<<<<<<< - * # R -= w[ii] * X[:,ii] # Update residual - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): + * # tmp = (X[:,ii] * R).sum() + * tmp = 0.0 # <<<<<<<<<<<<<< + * for jj in range(startptr, endptr): + * tmp += R[X_indices[jj]] * X_data[jj] */ - __pyx_t_53 = __pyx_v_ii; - __pyx_t_51 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_53, __pyx_bstride_0_w)) != 0.0); - if (__pyx_t_51) { + __pyx_v_tmp = 0.0; - /* "sklearn/linear_model/cd_fast.pyx":324 - * if w[ii] != 0.0: - * # R -= w[ii] * X[:,ii] # Update residual - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): # <<<<<<<<<<<<<< - * R[X_indices[jj]] -= X_data[jj] * w[ii] + /* "sklearn/linear_model/cd_fast.pyx":400 + * # tmp = (X[:,ii] * R).sum() + * tmp = 0.0 + * for jj in range(startptr, endptr): # <<<<<<<<<<<<<< + * tmp += R[X_indices[jj]] * X_data[jj] * */ - __pyx_t_54 = (__pyx_v_ii + 1); - __pyx_t_23 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_54, __pyx_bstride_0_X_indptr)); - __pyx_t_55 = __pyx_v_ii; - for (__pyx_t_56 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_55, __pyx_bstride_0_X_indptr)); __pyx_t_56 < __pyx_t_23; __pyx_t_56+=1) { - __pyx_v_jj = __pyx_t_56; + __pyx_t_35 = __pyx_v_endptr; + for (__pyx_t_36 = __pyx_v_startptr; __pyx_t_36 < __pyx_t_35; __pyx_t_36+=1) { + __pyx_v_jj = __pyx_t_36; - /* "sklearn/linear_model/cd_fast.pyx":325 - * # R -= w[ii] * X[:,ii] # Update residual - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * R[X_indices[jj]] -= X_data[jj] * w[ii] # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":401 + * tmp = 0.0 + * for jj in range(startptr, endptr): + * tmp += R[X_indices[jj]] * X_data[jj] # <<<<<<<<<<<<<< * * if center: */ - __pyx_t_57 = __pyx_v_jj; - __pyx_t_58 = __pyx_v_ii; - __pyx_t_59 = __pyx_v_jj; - __pyx_t_60 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indices.buf, __pyx_t_59, __pyx_bstride_0_X_indices)); - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_R.buf, __pyx_t_60, __pyx_bstride_0_R) -= ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_57, __pyx_bstride_0_X_data)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_58, __pyx_bstride_0_w))); - } + __pyx_t_41 = __pyx_v_jj; + __pyx_t_42 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indices.data + __pyx_t_41 * __pyx_v_X_indices.strides[0]) ))); + __pyx_t_43 = __pyx_v_jj; + __pyx_v_tmp = (__pyx_v_tmp + ((*((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_42 * __pyx_v_R.strides[0]) ))) * (*((double *) ( /* dim=0 */ (__pyx_v_X_data.data + __pyx_t_43 * __pyx_v_X_data.strides[0]) ))))); + } - /* "sklearn/linear_model/cd_fast.pyx":327 - * R[X_indices[jj]] -= X_data[jj] * w[ii] + /* "sklearn/linear_model/cd_fast.pyx":403 + * tmp += R[X_indices[jj]] * X_data[jj] * * if center: # <<<<<<<<<<<<<< - * for jj in xrange(n_samples): - * R[jj] += X_mean_ii * w[ii] + * R_sum = 0.0 + * for jj in range(n_samples): */ - if (__pyx_v_center) { + __pyx_t_17 = (__pyx_v_center != 0); + if (__pyx_t_17) { - /* "sklearn/linear_model/cd_fast.pyx":328 + /* "sklearn/linear_model/cd_fast.pyx":404 * * if center: - * for jj in xrange(n_samples): # <<<<<<<<<<<<<< - * R[jj] += X_mean_ii * w[ii] - * + * R_sum = 0.0 # <<<<<<<<<<<<<< + * for jj in range(n_samples): + * R_sum += R[jj] */ - __pyx_t_56 = __pyx_v_n_samples; - for (__pyx_t_61 = 0; __pyx_t_61 < __pyx_t_56; __pyx_t_61+=1) { - __pyx_v_jj = __pyx_t_61; + __pyx_v_R_sum = 0.0; - /* "sklearn/linear_model/cd_fast.pyx":329 + /* "sklearn/linear_model/cd_fast.pyx":405 * if center: - * for jj in xrange(n_samples): - * R[jj] += X_mean_ii * w[ii] # <<<<<<<<<<<<<< + * R_sum = 0.0 + * for jj in range(n_samples): # <<<<<<<<<<<<<< + * R_sum += R[jj] + * tmp -= R_sum * X_mean_ii + */ + __pyx_t_35 = __pyx_v_n_samples; + for (__pyx_t_36 = 0; __pyx_t_36 < __pyx_t_35; __pyx_t_36+=1) { + __pyx_v_jj = __pyx_t_36; + + /* "sklearn/linear_model/cd_fast.pyx":406 + * R_sum = 0.0 + * for jj in range(n_samples): + * R_sum += R[jj] # <<<<<<<<<<<<<< + * tmp -= R_sum * X_mean_ii * - * # update the maximum absolute coefficient update */ - __pyx_t_62 = __pyx_v_ii; - __pyx_t_63 = __pyx_v_jj; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_R.buf, __pyx_t_63, __pyx_bstride_0_R) += (__pyx_v_X_mean_ii * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_62, __pyx_bstride_0_w))); - } - goto __pyx_L33; - } - __pyx_L33:; - goto __pyx_L30; - } - __pyx_L30:; + __pyx_t_44 = __pyx_v_jj; + __pyx_v_R_sum = (__pyx_v_R_sum + (*((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_44 * __pyx_v_R.strides[0]) )))); + } - /* "sklearn/linear_model/cd_fast.pyx":332 + /* "sklearn/linear_model/cd_fast.pyx":407 + * for jj in range(n_samples): + * R_sum += R[jj] + * tmp -= R_sum * X_mean_ii # <<<<<<<<<<<<<< * - * # update the maximum absolute coefficient update - * d_w_ii = fabs(w[ii] - w_ii) # <<<<<<<<<<<<<< - * if d_w_ii > d_w_max: - * d_w_max = d_w_ii + * if positive and tmp < 0.0: */ - __pyx_t_56 = __pyx_v_ii; - __pyx_v_d_w_ii = fabs(((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_56, __pyx_bstride_0_w)) - __pyx_v_w_ii)); + __pyx_v_tmp = (__pyx_v_tmp - (__pyx_v_R_sum * __pyx_v_X_mean_ii)); + goto __pyx_L30; + } + __pyx_L30:; - /* "sklearn/linear_model/cd_fast.pyx":333 - * # update the maximum absolute coefficient update - * d_w_ii = fabs(w[ii] - w_ii) - * if d_w_ii > d_w_max: # <<<<<<<<<<<<<< - * d_w_max = d_w_ii + /* "sklearn/linear_model/cd_fast.pyx":409 + * tmp -= R_sum * X_mean_ii * + * if positive and tmp < 0.0: # <<<<<<<<<<<<<< + * w[ii] = 0.0 + * else: */ - __pyx_t_51 = (__pyx_v_d_w_ii > __pyx_v_d_w_max); - if (__pyx_t_51) { + __pyx_t_45 = (__pyx_v_positive != 0); + if (__pyx_t_45) { + goto __pyx_L35_next_and; + } else { + __pyx_t_17 = __pyx_t_45; + goto __pyx_L34_bool_binop_done; + } + __pyx_L35_next_and:; + __pyx_t_45 = ((__pyx_v_tmp < 0.0) != 0); + __pyx_t_17 = __pyx_t_45; + __pyx_L34_bool_binop_done:; + if (__pyx_t_17) { - /* "sklearn/linear_model/cd_fast.pyx":334 - * d_w_ii = fabs(w[ii] - w_ii) - * if d_w_ii > d_w_max: - * d_w_max = d_w_ii # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":410 * - * if w[ii] > w_max: + * if positive and tmp < 0.0: + * w[ii] = 0.0 # <<<<<<<<<<<<<< + * else: + * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ */ - __pyx_v_d_w_max = __pyx_v_d_w_ii; - goto __pyx_L36; - } - __pyx_L36:; + __pyx_t_35 = __pyx_v_ii; + *((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_35 * __pyx_v_w.strides[0]) )) = 0.0; + goto __pyx_L33; + } + /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":336 - * d_w_max = d_w_ii + /* "sklearn/linear_model/cd_fast.pyx":413 + * else: + * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ + * / (norm_cols_X[ii] + beta) # <<<<<<<<<<<<<< * - * if w[ii] > w_max: # <<<<<<<<<<<<<< - * w_max = w[ii] + * if w[ii] != 0.0: + */ + __pyx_t_36 = __pyx_v_ii; + + /* "sklearn/linear_model/cd_fast.pyx":412 + * w[ii] = 0.0 + * else: + * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ # <<<<<<<<<<<<<< + * / (norm_cols_X[ii] + beta) * */ - __pyx_t_61 = __pyx_v_ii; - __pyx_t_51 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_61, __pyx_bstride_0_w)) > __pyx_v_w_max); - if (__pyx_t_51) { + __pyx_t_46 = __pyx_v_ii; + *((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_46 * __pyx_v_w.strides[0]) )) = ((__pyx_f_7sklearn_12linear_model_7cd_fast_fsign(__pyx_v_tmp) * __pyx_f_7sklearn_12linear_model_7cd_fast_fmax((fabs(__pyx_v_tmp) - __pyx_v_alpha), 0.0)) / ((*((double *) ( /* dim=0 */ (__pyx_v_norm_cols_X.data + __pyx_t_36 * __pyx_v_norm_cols_X.strides[0]) ))) + __pyx_v_beta)); + } + __pyx_L33:; - /* "sklearn/linear_model/cd_fast.pyx":337 + /* "sklearn/linear_model/cd_fast.pyx":415 + * / (norm_cols_X[ii] + beta) * - * if w[ii] > w_max: - * w_max = w[ii] # <<<<<<<<<<<<<< + * if w[ii] != 0.0: # <<<<<<<<<<<<<< + * # R -= w[ii] * X[:,ii] # Update residual + * for jj in range(startptr, endptr): + */ + __pyx_t_47 = __pyx_v_ii; + __pyx_t_17 = (((*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_47 * __pyx_v_w.strides[0]) ))) != 0.0) != 0); + if (__pyx_t_17) { + + /* "sklearn/linear_model/cd_fast.pyx":417 + * if w[ii] != 0.0: + * # R -= w[ii] * X[:,ii] # Update residual + * for jj in range(startptr, endptr): # <<<<<<<<<<<<<< + * R[X_indices[jj]] -= X_data[jj] * w[ii] * - * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: */ - __pyx_t_64 = __pyx_v_ii; - __pyx_v_w_max = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_64, __pyx_bstride_0_w)); - goto __pyx_L37; - } - __pyx_L37:; - __pyx_L15_continue:; - } + __pyx_t_48 = __pyx_v_endptr; + for (__pyx_t_49 = __pyx_v_startptr; __pyx_t_49 < __pyx_t_48; __pyx_t_49+=1) { + __pyx_v_jj = __pyx_t_49; - /* "sklearn/linear_model/cd_fast.pyx":339 - * w_max = w[ii] + /* "sklearn/linear_model/cd_fast.pyx":418 + * # R -= w[ii] * X[:,ii] # Update residual + * for jj in range(startptr, endptr): + * R[X_indices[jj]] -= X_data[jj] * w[ii] # <<<<<<<<<<<<<< * - * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: # <<<<<<<<<<<<<< - * # the biggest coordinate update of this iteration was smaller than - * # the tolerance: check the duality gap as ultimate stopping + * if center: */ - __pyx_t_51 = (__pyx_v_w_max == 0.0); - if (!__pyx_t_51) { - __pyx_t_16 = ((__pyx_v_d_w_max / __pyx_v_w_max) < __pyx_v_d_w_tol); - if (!__pyx_t_16) { - __pyx_t_65 = (__pyx_v_n_iter == (__pyx_v_max_iter - 1)); - __pyx_t_66 = __pyx_t_65; - } else { - __pyx_t_66 = __pyx_t_16; - } - __pyx_t_16 = __pyx_t_66; - } else { - __pyx_t_16 = __pyx_t_51; - } - if (__pyx_t_16) { + __pyx_t_50 = __pyx_v_jj; + __pyx_t_51 = __pyx_v_ii; + __pyx_t_52 = __pyx_v_jj; + __pyx_t_53 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indices.data + __pyx_t_52 * __pyx_v_X_indices.strides[0]) ))); + *((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_53 * __pyx_v_R.strides[0]) )) -= ((*((double *) ( /* dim=0 */ (__pyx_v_X_data.data + __pyx_t_50 * __pyx_v_X_data.strides[0]) ))) * (*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_51 * __pyx_v_w.strides[0]) )))); + } - /* "sklearn/linear_model/cd_fast.pyx":345 + /* "sklearn/linear_model/cd_fast.pyx":420 + * R[X_indices[jj]] -= X_data[jj] * w[ii] * - * # sparse X.T / dense R dot product - * X_T_R = np.zeros(n_features) # <<<<<<<<<<<<<< - * for ii in xrange(n_features): - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): + * if center: # <<<<<<<<<<<<<< + * for jj in range(n_samples): + * R[jj] += X_mean_ii * w[ii] */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyLong_FromUnsignedLong(__pyx_v_n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_v_X_T_R); - __pyx_v_X_T_R = __pyx_t_1; - __pyx_t_1 = 0; + __pyx_t_17 = (__pyx_v_center != 0); + if (__pyx_t_17) { - /* "sklearn/linear_model/cd_fast.pyx":346 - * # sparse X.T / dense R dot product - * X_T_R = np.zeros(n_features) - * for ii in xrange(n_features): # <<<<<<<<<<<<<< - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * X_T_R[ii] += X_data[jj] * R[X_indices[jj]] - */ - __pyx_t_7 = __pyx_v_n_features; - for (__pyx_t_32 = 0; __pyx_t_32 < __pyx_t_7; __pyx_t_32+=1) { - __pyx_v_ii = __pyx_t_32; - - /* "sklearn/linear_model/cd_fast.pyx":347 - * X_T_R = np.zeros(n_features) - * for ii in xrange(n_features): - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): # <<<<<<<<<<<<<< - * X_T_R[ii] += X_data[jj] * R[X_indices[jj]] - * X_T_R[ii] -= X_mean[ii] * R.sum() - */ - __pyx_t_67 = (__pyx_v_ii + 1); - __pyx_t_23 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_67, __pyx_bstride_0_X_indptr)); - __pyx_t_68 = __pyx_v_ii; - for (__pyx_t_69 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indptr.buf, __pyx_t_68, __pyx_bstride_0_X_indptr)); __pyx_t_69 < __pyx_t_23; __pyx_t_69+=1) { - __pyx_v_jj = __pyx_t_69; - - /* "sklearn/linear_model/cd_fast.pyx":348 - * for ii in xrange(n_features): - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * X_T_R[ii] += X_data[jj] * R[X_indices[jj]] # <<<<<<<<<<<<<< - * X_T_R[ii] -= X_mean[ii] * R.sum() - * - */ - __pyx_t_70 = __pyx_v_ii; - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_X_T_R, __pyx_t_70, sizeof(unsigned int)+1, PyLong_FromUnsignedLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_71 = __pyx_v_jj; - __pyx_t_72 = __pyx_v_jj; - __pyx_t_73 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_INTEGER *, __pyx_bstruct_X_indices.buf, __pyx_t_72, __pyx_bstride_0_X_indices)); - __pyx_t_4 = PyFloat_FromDouble(((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_71, __pyx_bstride_0_X_data)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_R.buf, __pyx_t_73, __pyx_bstride_0_R)))); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyNumber_InPlaceAdd(__pyx_t_1, __pyx_t_4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__Pyx_SetItemInt(__pyx_v_X_T_R, __pyx_t_70, __pyx_t_2, sizeof(unsigned int)+1, PyLong_FromUnsignedLong) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - - /* "sklearn/linear_model/cd_fast.pyx":349 - * for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - * X_T_R[ii] += X_data[jj] * R[X_indices[jj]] - * X_T_R[ii] -= X_mean[ii] * R.sum() # <<<<<<<<<<<<<< - * - * XtA = X_T_R - beta * w - */ - __pyx_t_69 = __pyx_v_ii; - __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_X_T_R, __pyx_t_69, sizeof(unsigned int)+1, PyLong_FromUnsignedLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_70 = __pyx_v_ii; - __pyx_t_4 = PyFloat_FromDouble((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_X_mean.buf, __pyx_t_70, __pyx_bstride_0_X_mean))); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_R), __pyx_n_s__sum); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_InPlaceSubtract(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__Pyx_SetItemInt(__pyx_v_X_T_R, __pyx_t_69, __pyx_t_3, sizeof(unsigned int)+1, PyLong_FromUnsignedLong) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } + /* "sklearn/linear_model/cd_fast.pyx":421 + * + * if center: + * for jj in range(n_samples): # <<<<<<<<<<<<<< + * R[jj] += X_mean_ii * w[ii] + * + */ + __pyx_t_48 = __pyx_v_n_samples; + for (__pyx_t_49 = 0; __pyx_t_49 < __pyx_t_48; __pyx_t_49+=1) { + __pyx_v_jj = __pyx_t_49; - /* "sklearn/linear_model/cd_fast.pyx":351 - * X_T_R[ii] -= X_mean[ii] * R.sum() + /* "sklearn/linear_model/cd_fast.pyx":422 + * if center: + * for jj in range(n_samples): + * R[jj] += X_mean_ii * w[ii] # <<<<<<<<<<<<<< * - * XtA = X_T_R - beta * w # <<<<<<<<<<<<<< - * if positive: - * dual_norm_XtA = np.max(XtA) + * # update the maximum absolute coefficient update */ - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_beta); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_3, ((PyObject *)__pyx_v_w)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_v_X_T_R, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_v_XtA); - __pyx_v_XtA = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_54 = __pyx_v_ii; + __pyx_t_55 = __pyx_v_jj; + *((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_55 * __pyx_v_R.strides[0]) )) += (__pyx_v_X_mean_ii * (*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_54 * __pyx_v_w.strides[0]) )))); + } + goto __pyx_L39; + } + __pyx_L39:; + goto __pyx_L36; + } + __pyx_L36:; - /* "sklearn/linear_model/cd_fast.pyx":352 + /* "sklearn/linear_model/cd_fast.pyx":425 * - * XtA = X_T_R - beta * w - * if positive: # <<<<<<<<<<<<<< - * dual_norm_XtA = np.max(XtA) - * else: + * # update the maximum absolute coefficient update + * d_w_ii = fabs(w[ii] - w_ii) # <<<<<<<<<<<<<< + * if d_w_ii > d_w_max: + * d_w_max = d_w_ii */ - if (__pyx_v_positive) { + __pyx_t_48 = __pyx_v_ii; + __pyx_v_d_w_ii = fabs(((*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_48 * __pyx_v_w.strides[0]) ))) - __pyx_v_w_ii)); - /* "sklearn/linear_model/cd_fast.pyx":353 - * XtA = X_T_R - beta * w - * if positive: - * dual_norm_XtA = np.max(XtA) # <<<<<<<<<<<<<< - * else: - * dual_norm_XtA = linalg.norm(XtA, np.inf) + /* "sklearn/linear_model/cd_fast.pyx":426 + * # update the maximum absolute coefficient update + * d_w_ii = fabs(w[ii] - w_ii) + * if d_w_ii > d_w_max: # <<<<<<<<<<<<<< + * d_w_max = d_w_ii + * */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 353; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__max); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 353; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 353; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(__pyx_v_XtA); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_XtA); - __Pyx_GIVEREF(__pyx_v_XtA); - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 353; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_dual_norm_XtA); - __pyx_v_dual_norm_XtA = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L43; - } - /*else*/ { + __pyx_t_17 = ((__pyx_v_d_w_ii > __pyx_v_d_w_max) != 0); + if (__pyx_t_17) { - /* "sklearn/linear_model/cd_fast.pyx":355 - * dual_norm_XtA = np.max(XtA) - * else: - * dual_norm_XtA = linalg.norm(XtA, np.inf) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":427 + * d_w_ii = fabs(w[ii] - w_ii) + * if d_w_ii > d_w_max: + * d_w_max = d_w_ii # <<<<<<<<<<<<<< * - * # TODO: use squared L2 norm directly + * if w[ii] > w_max: */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__norm); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__inf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(__pyx_v_XtA); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_XtA); - __Pyx_GIVEREF(__pyx_v_XtA); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_v_dual_norm_XtA); - __pyx_v_dual_norm_XtA = __pyx_t_1; - __pyx_t_1 = 0; - } - __pyx_L43:; + __pyx_v_d_w_max = __pyx_v_d_w_ii; + goto __pyx_L42; + } + __pyx_L42:; - /* "sklearn/linear_model/cd_fast.pyx":358 + /* "sklearn/linear_model/cd_fast.pyx":429 + * d_w_max = d_w_ii * - * # TODO: use squared L2 norm directly - * R_norm = linalg.norm(R) # <<<<<<<<<<<<<< - * w_norm = linalg.norm(w, 2) - * if (dual_norm_XtA > alpha): + * if w[ii] > w_max: # <<<<<<<<<<<<<< + * w_max = w[ii] + * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 358; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__norm); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 358; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 358; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_v_R)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_R)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_R)); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 358; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_v_R_norm); - __pyx_v_R_norm = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_49 = __pyx_v_ii; + __pyx_t_17 = (((*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_49 * __pyx_v_w.strides[0]) ))) > __pyx_v_w_max) != 0); + if (__pyx_t_17) { - /* "sklearn/linear_model/cd_fast.pyx":359 - * # TODO: use squared L2 norm directly - * R_norm = linalg.norm(R) - * w_norm = linalg.norm(w, 2) # <<<<<<<<<<<<<< - * if (dual_norm_XtA > alpha): - * const = alpha / dual_norm_XtA + /* "sklearn/linear_model/cd_fast.pyx":430 + * + * if w[ii] > w_max: + * w_max = w[ii] # <<<<<<<<<<<<<< + * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: + * # the biggest coordinate update of this iteration was smaller than */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__norm); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __Pyx_INCREF(__pyx_int_2); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_2); - __Pyx_GIVEREF(__pyx_int_2); - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_w_norm); - __pyx_v_w_norm = __pyx_t_2; - __pyx_t_2 = 0; - - /* "sklearn/linear_model/cd_fast.pyx":360 - * R_norm = linalg.norm(R) - * w_norm = linalg.norm(w, 2) - * if (dual_norm_XtA > alpha): # <<<<<<<<<<<<<< - * const = alpha / dual_norm_XtA - * A_norm = R_norm * const - */ - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_dual_norm_XtA, __pyx_t_2, Py_GT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_16 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_16 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_16) { + __pyx_t_56 = __pyx_v_ii; + __pyx_v_w_max = (*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_56 * __pyx_v_w.strides[0]) ))); + goto __pyx_L43; + } + __pyx_L43:; + __pyx_L18_continue:; + } - /* "sklearn/linear_model/cd_fast.pyx":361 - * w_norm = linalg.norm(w, 2) - * if (dual_norm_XtA > alpha): - * const = alpha / dual_norm_XtA # <<<<<<<<<<<<<< - * A_norm = R_norm * const - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) + /* "sklearn/linear_model/cd_fast.pyx":431 + * if w[ii] > w_max: + * w_max = w[ii] + * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: # <<<<<<<<<<<<<< + * # the biggest coordinate update of this iteration was smaller than + * # the tolerance: check the duality gap as ultimate stopping */ - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_t_3, __pyx_v_dual_norm_XtA); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_const); - __pyx_v_const = __pyx_t_2; - __pyx_t_2 = 0; - - /* "sklearn/linear_model/cd_fast.pyx":362 - * if (dual_norm_XtA > alpha): - * const = alpha / dual_norm_XtA - * A_norm = R_norm * const # <<<<<<<<<<<<<< - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) - * else: + __pyx_t_45 = ((__pyx_v_w_max == 0.0) != 0); + if (!__pyx_t_45) { + goto __pyx_L46_next_or; + } else { + __pyx_t_17 = __pyx_t_45; + goto __pyx_L45_bool_binop_done; + } + __pyx_L46_next_or:; + __pyx_t_45 = (((__pyx_v_d_w_max / __pyx_v_w_max) < __pyx_v_d_w_tol) != 0); + if (!__pyx_t_45) { + goto __pyx_L47_next_or; + } else { + __pyx_t_17 = __pyx_t_45; + goto __pyx_L45_bool_binop_done; + } + __pyx_L47_next_or:; + __pyx_t_45 = ((__pyx_v_n_iter == (__pyx_v_max_iter - 1)) != 0); + __pyx_t_17 = __pyx_t_45; + __pyx_L45_bool_binop_done:; + if (__pyx_t_17) { + + /* "sklearn/linear_model/cd_fast.pyx":437 + * + * # sparse X.T / dense R dot product + * if center: # <<<<<<<<<<<<<< + * R_sum = 0.0 + * for jj in range(n_samples): */ - __pyx_t_2 = PyNumber_Multiply(__pyx_v_R_norm, __pyx_v_const); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_v_A_norm); - __pyx_v_A_norm = __pyx_t_2; - __pyx_t_2 = 0; + __pyx_t_17 = (__pyx_v_center != 0); + if (__pyx_t_17) { - /* "sklearn/linear_model/cd_fast.pyx":363 - * const = alpha / dual_norm_XtA - * A_norm = R_norm * const - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) # <<<<<<<<<<<<<< - * else: - * const = 1.0 + /* "sklearn/linear_model/cd_fast.pyx":438 + * # sparse X.T / dense R dot product + * if center: + * R_sum = 0.0 # <<<<<<<<<<<<<< + * for jj in range(n_samples): + * R_sum += R[jj] */ - __pyx_t_2 = PyFloat_FromDouble(0.5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Power(__pyx_v_R_norm, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyNumber_Power(__pyx_v_A_norm, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Add(__pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_31 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_31 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_gap = __pyx_t_31; - goto __pyx_L44; - } - /*else*/ { + __pyx_v_R_sum = 0.0; - /* "sklearn/linear_model/cd_fast.pyx":365 - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) - * else: - * const = 1.0 # <<<<<<<<<<<<<< - * gap = R_norm ** 2 + /* "sklearn/linear_model/cd_fast.pyx":439 + * if center: + * R_sum = 0.0 + * for jj in range(n_samples): # <<<<<<<<<<<<<< + * R_sum += R[jj] * */ - __pyx_t_1 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 365; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_v_const); - __pyx_v_const = __pyx_t_1; - __pyx_t_1 = 0; + __pyx_t_15 = __pyx_v_n_samples; + for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_15; __pyx_t_22+=1) { + __pyx_v_jj = __pyx_t_22; - /* "sklearn/linear_model/cd_fast.pyx":366 - * else: - * const = 1.0 - * gap = R_norm ** 2 # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":440 + * R_sum = 0.0 + * for jj in range(n_samples): + * R_sum += R[jj] # <<<<<<<<<<<<<< * - * gap += alpha * linalg.norm(w, 1) - const * np.dot(R.T, y) + \ + * for ii in range(n_features): */ - __pyx_t_1 = PyNumber_Power(__pyx_v_R_norm, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_31 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_31 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_gap = __pyx_t_31; - } - __pyx_L44:; + __pyx_t_57 = __pyx_v_jj; + __pyx_v_R_sum = (__pyx_v_R_sum + (*((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_57 * __pyx_v_R.strides[0]) )))); + } + goto __pyx_L48; + } + __pyx_L48:; - /* "sklearn/linear_model/cd_fast.pyx":368 - * gap = R_norm ** 2 + /* "sklearn/linear_model/cd_fast.pyx":442 + * R_sum += R[jj] * - * gap += alpha * linalg.norm(w, 1) - const * np.dot(R.T, y) + \ # <<<<<<<<<<<<<< - * 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) + * for ii in range(n_features): # <<<<<<<<<<<<<< + * X_T_R[ii] = 0.0 + * for jj in range(X_indptr[ii], X_indptr[ii + 1]): + */ + __pyx_t_15 = __pyx_v_n_features; + for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_15; __pyx_t_22+=1) { + __pyx_v_ii = __pyx_t_22; + + /* "sklearn/linear_model/cd_fast.pyx":443 * + * for ii in range(n_features): + * X_T_R[ii] = 0.0 # <<<<<<<<<<<<<< + * for jj in range(X_indptr[ii], X_indptr[ii + 1]): + * X_T_R[ii] += X_data[jj] * R[X_indices[jj]] */ - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__norm); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_int_1); - __Pyx_GIVEREF(__pyx_int_1); - __pyx_t_74 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_74)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_74); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_t_4, __pyx_t_74); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_74); __pyx_t_74 = 0; - __pyx_t_74 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_74)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_74); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_74, __pyx_n_s__dot); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_74); __pyx_t_74 = 0; - __pyx_t_74 = PyObject_GetAttr(((PyObject *)__pyx_v_R), __pyx_n_s__T); if (unlikely(!__pyx_t_74)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_74); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_74); - __Pyx_GIVEREF(__pyx_t_74); - __Pyx_INCREF(((PyObject *)__pyx_v_y)); - PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_v_y)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); - __pyx_t_74 = 0; - __pyx_t_74 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_74)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_74); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Multiply(__pyx_v_const, __pyx_t_74); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_74); __pyx_t_74 = 0; - __pyx_t_74 = PyNumber_Subtract(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_74)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_74); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_58 = __pyx_v_ii; + *((double *) ( /* dim=0 */ (__pyx_v_X_T_R.data + __pyx_t_58 * __pyx_v_X_T_R.strides[0]) )) = 0.0; - /* "sklearn/linear_model/cd_fast.pyx":369 + /* "sklearn/linear_model/cd_fast.pyx":444 + * for ii in range(n_features): + * X_T_R[ii] = 0.0 + * for jj in range(X_indptr[ii], X_indptr[ii + 1]): # <<<<<<<<<<<<<< + * X_T_R[ii] += X_data[jj] * R[X_indices[jj]] * - * gap += alpha * linalg.norm(w, 1) - const * np.dot(R.T, y) + \ - * 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) # <<<<<<<<<<<<<< + */ + __pyx_t_59 = (__pyx_v_ii + 1); + __pyx_t_60 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_59 * __pyx_v_X_indptr.strides[0]) ))); + __pyx_t_61 = __pyx_v_ii; + for (__pyx_t_62 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_61 * __pyx_v_X_indptr.strides[0]) ))); __pyx_t_62 < __pyx_t_60; __pyx_t_62+=1) { + __pyx_v_jj = __pyx_t_62; + + /* "sklearn/linear_model/cd_fast.pyx":445 + * X_T_R[ii] = 0.0 + * for jj in range(X_indptr[ii], X_indptr[ii + 1]): + * X_T_R[ii] += X_data[jj] * R[X_indices[jj]] # <<<<<<<<<<<<<< * - * if gap < tol: + * if center: */ - __pyx_t_3 = PyFloat_FromDouble((0.5 * __pyx_v_beta)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyNumber_Power(__pyx_v_const, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyNumber_Add(__pyx_int_1, __pyx_t_2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Multiply(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Power(__pyx_v_w_norm, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyNumber_Multiply(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Add(__pyx_t_74, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_74); __pyx_t_74 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_InPlaceAdd(__pyx_t_1, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_31 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_31 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_gap = __pyx_t_31; + __pyx_t_63 = __pyx_v_jj; + __pyx_t_64 = __pyx_v_jj; + __pyx_t_65 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indices.data + __pyx_t_64 * __pyx_v_X_indices.strides[0]) ))); + __pyx_t_66 = __pyx_v_ii; + *((double *) ( /* dim=0 */ (__pyx_v_X_T_R.data + __pyx_t_66 * __pyx_v_X_T_R.strides[0]) )) += ((*((double *) ( /* dim=0 */ (__pyx_v_X_data.data + __pyx_t_63 * __pyx_v_X_data.strides[0]) ))) * (*((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_65 * __pyx_v_R.strides[0]) )))); + } - /* "sklearn/linear_model/cd_fast.pyx":371 - * 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) + /* "sklearn/linear_model/cd_fast.pyx":447 + * X_T_R[ii] += X_data[jj] * R[X_indices[jj]] * - * if gap < tol: # <<<<<<<<<<<<<< - * # return if we reached desired tolerance - * break + * if center: # <<<<<<<<<<<<<< + * X_T_R[ii] -= X_mean[ii] * R_sum + * XtA[ii] = X_T_R[ii] - beta * w[ii] */ - __pyx_t_16 = (__pyx_v_gap < __pyx_v_tol); - if (__pyx_t_16) { + __pyx_t_17 = (__pyx_v_center != 0); + if (__pyx_t_17) { - /* "sklearn/linear_model/cd_fast.pyx":373 - * if gap < tol: - * # return if we reached desired tolerance - * break # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":448 + * + * if center: + * X_T_R[ii] -= X_mean[ii] * R_sum # <<<<<<<<<<<<<< + * XtA[ii] = X_T_R[ii] - beta * w[ii] * - * return w, gap, tol */ - goto __pyx_L14_break; - goto __pyx_L45; - } - __pyx_L45:; - goto __pyx_L38; - } - __pyx_L38:; - } - __pyx_L14_break:; + __pyx_t_62 = __pyx_v_ii; + __pyx_t_67 = __pyx_v_ii; + *((double *) ( /* dim=0 */ (__pyx_v_X_T_R.data + __pyx_t_67 * __pyx_v_X_T_R.strides[0]) )) -= ((*((double *) ( /* dim=0 */ (__pyx_v_X_mean.data + __pyx_t_62 * __pyx_v_X_mean.strides[0]) ))) * __pyx_v_R_sum); + goto __pyx_L55; + } + __pyx_L55:; - /* "sklearn/linear_model/cd_fast.pyx":375 - * break + /* "sklearn/linear_model/cd_fast.pyx":449 + * if center: + * X_T_R[ii] -= X_mean[ii] * R_sum + * XtA[ii] = X_T_R[ii] - beta * w[ii] # <<<<<<<<<<<<<< * - * return w, gap, tol # <<<<<<<<<<<<<< + * if positive: + */ + __pyx_t_68 = __pyx_v_ii; + __pyx_t_69 = __pyx_v_ii; + __pyx_t_70 = __pyx_v_ii; + *((double *) ( /* dim=0 */ (__pyx_v_XtA.data + __pyx_t_70 * __pyx_v_XtA.strides[0]) )) = ((*((double *) ( /* dim=0 */ (__pyx_v_X_T_R.data + __pyx_t_68 * __pyx_v_X_T_R.strides[0]) ))) - (__pyx_v_beta * (*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_69 * __pyx_v_w.strides[0]) ))))); + } + + /* "sklearn/linear_model/cd_fast.pyx":451 + * XtA[ii] = X_T_R[ii] - beta * w[ii] * + * if positive: # <<<<<<<<<<<<<< + * dual_norm_XtA = max(n_features, &XtA[0]) + * else: + */ + __pyx_t_17 = (__pyx_v_positive != 0); + if (__pyx_t_17) { + + /* "sklearn/linear_model/cd_fast.pyx":452 * + * if positive: + * dual_norm_XtA = max(n_features, &XtA[0]) # <<<<<<<<<<<<<< + * else: + * dual_norm_XtA = abs_max(n_features, &XtA[0]) */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyFloat_FromDouble(__pyx_v_tol); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_r = ((PyObject *)__pyx_t_1); - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_t_71 = 0; + __pyx_v_dual_norm_XtA = __pyx_f_7sklearn_12linear_model_7cd_fast_max(__pyx_v_n_features, (&(*((double *) ( /* dim=0 */ (__pyx_v_XtA.data + __pyx_t_71 * __pyx_v_XtA.strides[0]) ))))); + goto __pyx_L56; + } + /*else*/ { - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_74); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_mean); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_norm_cols_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_R); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_w); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_y); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + /* "sklearn/linear_model/cd_fast.pyx":454 + * dual_norm_XtA = max(n_features, &XtA[0]) + * else: + * dual_norm_XtA = abs_max(n_features, &XtA[0]) # <<<<<<<<<<<<<< + * + * # R_norm2 = np.dot(R, R) + */ + __pyx_t_72 = 0; + __pyx_v_dual_norm_XtA = __pyx_f_7sklearn_12linear_model_7cd_fast_abs_max(__pyx_v_n_features, (&(*((double *) ( /* dim=0 */ (__pyx_v_XtA.data + __pyx_t_72 * __pyx_v_XtA.strides[0]) ))))); + } + __pyx_L56:; + + /* "sklearn/linear_model/cd_fast.pyx":457 + * + * # R_norm2 = np.dot(R, R) + * R_norm2 = ddot(n_samples, &R[0], 1, &R[0], 1) # <<<<<<<<<<<<<< + * + * # w_norm2 = np.dot(w, w) + */ + __pyx_t_73 = 0; + __pyx_t_74 = 0; + __pyx_v_R_norm2 = cblas_ddot(__pyx_v_n_samples, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(&(*((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_73 * __pyx_v_R.strides[0]) ))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(&(*((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_74 * __pyx_v_R.strides[0]) ))))), 1); + + /* "sklearn/linear_model/cd_fast.pyx":460 + * + * # w_norm2 = np.dot(w, w) + * w_norm2 = ddot(n_features, &w[0], 1, &w[0], 1) # <<<<<<<<<<<<<< + * if (dual_norm_XtA > alpha): + * const = alpha / dual_norm_XtA + */ + __pyx_t_75 = 0; + __pyx_t_76 = 0; + __pyx_v_w_norm2 = cblas_ddot(__pyx_v_n_features, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(&(*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_75 * __pyx_v_w.strides[0]) ))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(&(*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_76 * __pyx_v_w.strides[0]) ))))), 1); + + /* "sklearn/linear_model/cd_fast.pyx":461 + * # w_norm2 = np.dot(w, w) + * w_norm2 = ddot(n_features, &w[0], 1, &w[0], 1) + * if (dual_norm_XtA > alpha): # <<<<<<<<<<<<<< + * const = alpha / dual_norm_XtA + * A_norm2 = R_norm2 * const**2 + */ + __pyx_t_17 = ((__pyx_v_dual_norm_XtA > __pyx_v_alpha) != 0); + if (__pyx_t_17) { + + /* "sklearn/linear_model/cd_fast.pyx":462 + * w_norm2 = ddot(n_features, &w[0], 1, &w[0], 1) + * if (dual_norm_XtA > alpha): + * const = alpha / dual_norm_XtA # <<<<<<<<<<<<<< + * A_norm2 = R_norm2 * const**2 + * gap = 0.5 * (R_norm2 + A_norm2) + */ + __pyx_v_const = (__pyx_v_alpha / __pyx_v_dual_norm_XtA); + + /* "sklearn/linear_model/cd_fast.pyx":463 + * if (dual_norm_XtA > alpha): + * const = alpha / dual_norm_XtA + * A_norm2 = R_norm2 * const**2 # <<<<<<<<<<<<<< + * gap = 0.5 * (R_norm2 + A_norm2) + * else: + */ + __pyx_v_A_norm2 = (__pyx_v_R_norm2 * pow(__pyx_v_const, 2.0)); + + /* "sklearn/linear_model/cd_fast.pyx":464 + * const = alpha / dual_norm_XtA + * A_norm2 = R_norm2 * const**2 + * gap = 0.5 * (R_norm2 + A_norm2) # <<<<<<<<<<<<<< + * else: + * const = 1.0 + */ + __pyx_v_gap = (0.5 * (__pyx_v_R_norm2 + __pyx_v_A_norm2)); + goto __pyx_L57; + } + /*else*/ { + + /* "sklearn/linear_model/cd_fast.pyx":466 + * gap = 0.5 * (R_norm2 + A_norm2) + * else: + * const = 1.0 # <<<<<<<<<<<<<< + * gap = R_norm2 + * + */ + __pyx_v_const = 1.0; + + /* "sklearn/linear_model/cd_fast.pyx":467 + * else: + * const = 1.0 + * gap = R_norm2 # <<<<<<<<<<<<<< + * + * l1_norm = dasum(n_features, &w[0], 1) + */ + __pyx_v_gap = __pyx_v_R_norm2; + } + __pyx_L57:; + + /* "sklearn/linear_model/cd_fast.pyx":469 + * gap = R_norm2 + * + * l1_norm = dasum(n_features, &w[0], 1) # <<<<<<<<<<<<<< + * + * # The expression inside ddot is equivalent to np.dot(R.T, y) + */ + __pyx_t_77 = 0; + __pyx_v_l1_norm = cblas_dasum(__pyx_v_n_features, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(&(*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_77 * __pyx_v_w.strides[0]) ))))), 1); + + /* "sklearn/linear_model/cd_fast.pyx":474 + * gap += (alpha * l1_norm - const * ddot( + * n_samples, + * &R[0], 1, # <<<<<<<<<<<<<< + * &y[0], n_tasks + * ) + */ + __pyx_t_78 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":475 + * n_samples, + * &R[0], 1, + * &y[0], n_tasks # <<<<<<<<<<<<<< + * ) + * + 0.5 * beta * (1 + const ** 2) * w_norm2) + */ + __pyx_t_79 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":472 + * + * # The expression inside ddot is equivalent to np.dot(R.T, y) + * gap += (alpha * l1_norm - const * ddot( # <<<<<<<<<<<<<< + * n_samples, + * &R[0], 1, + */ + __pyx_v_gap = (__pyx_v_gap + (((__pyx_v_alpha * __pyx_v_l1_norm) - (__pyx_v_const * cblas_ddot(__pyx_v_n_samples, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(&(*((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_78 * __pyx_v_R.strides[0]) ))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(&(*((double *) ( /* dim=0 */ (__pyx_v_y.data + __pyx_t_79 * __pyx_v_y.strides[0]) ))))), __pyx_v_n_tasks))) + (((0.5 * __pyx_v_beta) * (1.0 + pow(__pyx_v_const, 2.0))) * __pyx_v_w_norm2))); + + /* "sklearn/linear_model/cd_fast.pyx":479 + * + 0.5 * beta * (1 + const ** 2) * w_norm2) + * + * if gap < tol: # <<<<<<<<<<<<<< + * # return if we reached desired tolerance + * break + */ + __pyx_t_17 = ((__pyx_v_gap < __pyx_v_tol) != 0); + if (__pyx_t_17) { + + /* "sklearn/linear_model/cd_fast.pyx":481 + * if gap < tol: + * # return if we reached desired tolerance + * break # <<<<<<<<<<<<<< + * + * return w, gap, tol, n_iter + 1 + */ + goto __pyx_L17_break; + } + goto __pyx_L44; + } + __pyx_L44:; + } + __pyx_L17_break:; + } + + /* "sklearn/linear_model/cd_fast.pyx":344 + * cdef bint center = False + * + * with nogil: # <<<<<<<<<<<<<< + * # center = (X_mean != 0).any() + * for ii in range(n_features): + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "sklearn/linear_model/cd_fast.pyx":483 + * break + * + * return w, gap, tol, n_iter + 1 # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_w, 1, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_tol); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyInt_From_long((__pyx_v_n_iter + 1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = PyTuple_New(4); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_7, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_7, 3, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_5 = 0; + __pyx_r = __pyx_t_7; + __pyx_t_7 = 0; + goto __pyx_L0; + + /* "sklearn/linear_model/cd_fast.pyx":290 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def sparse_enet_coordinate_descent(double[:] w, # <<<<<<<<<<<<<< + * double alpha, double beta, + * double[:] X_data, int[:] X_indices, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); + __PYX_XDEC_MEMVIEW(&__pyx_t_8, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_9, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_10, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_11, 1); __Pyx_AddTraceback("sklearn.linear_model.cd_fast.sparse_enet_coordinate_descent", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; - goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_mean); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_norm_cols_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_R); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_w); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_y); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_norm_cols_X); - __Pyx_XDECREF((PyObject *)__pyx_v_R); - __Pyx_XDECREF(__pyx_v_X_T_R); - __Pyx_XDECREF(__pyx_v_XtA); - __Pyx_XDECREF(__pyx_v_dual_norm_XtA); - __Pyx_XDECREF(__pyx_v_R_norm); - __Pyx_XDECREF(__pyx_v_w_norm); - __Pyx_XDECREF(__pyx_v_const); - __Pyx_XDECREF(__pyx_v_A_norm); + __PYX_XDEC_MEMVIEW(&__pyx_v_norm_cols_X, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_R, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X_T_R, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_XtA, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_w, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X_data, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X_indices, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X_indptr, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_y, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X_mean, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/cd_fast.pyx":381 +/* "sklearn/linear_model/cd_fast.pyx":489 * @cython.wraparound(False) * @cython.cdivision(True) - * def enet_coordinate_descent_gram(np.ndarray[DOUBLE, ndim=1] w, # <<<<<<<<<<<<<< - * double alpha, double beta, - * np.ndarray[DOUBLE, ndim=2] Q, + * def enet_coordinate_descent_gram(double[:] w, double alpha, double beta, # <<<<<<<<<<<<<< + * double[:, :] Q, double[:] q, double[:] y, + * int max_iter, double tol, object rng, */ -static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_3enet_coordinate_descent_gram(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_12linear_model_7cd_fast_3enet_coordinate_descent_gram[] = "Cython version of the coordinate descent algorithm\n for Elastic-Net regression\n\n We minimize\n\n 1 w^T Q w - q^T w + alpha norm(w, 1) + beta norm(w, 2)^2\n - ----\n 2 2\n\n which amount to the Elastic-Net problem when:\n Q = X^T X (Gram matrix)\n q = X^T y\n "; -static PyMethodDef __pyx_mdef_7sklearn_12linear_model_7cd_fast_3enet_coordinate_descent_gram = {__Pyx_NAMESTR("enet_coordinate_descent_gram"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_7cd_fast_3enet_coordinate_descent_gram, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_12linear_model_7cd_fast_3enet_coordinate_descent_gram)}; -static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_3enet_coordinate_descent_gram(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_w = 0; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_7cd_fast_5enet_coordinate_descent_gram(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_gram[] = "Cython version of the coordinate descent algorithm\n for Elastic-Net regression\n\n We minimize\n\n 1 w^T Q w - q^T w + alpha norm(w, 1) + beta norm(w, 2)^2\n - ----\n 2 2\n\n which amount to the Elastic-Net problem when:\n Q = X^T X (Gram matrix)\n q = X^T y\n "; +static PyMethodDef __pyx_mdef_7sklearn_12linear_model_7cd_fast_5enet_coordinate_descent_gram = {"enet_coordinate_descent_gram", (PyCFunction)__pyx_pw_7sklearn_12linear_model_7cd_fast_5enet_coordinate_descent_gram, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_gram}; +static PyObject *__pyx_pw_7sklearn_12linear_model_7cd_fast_5enet_coordinate_descent_gram(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __Pyx_memviewslice __pyx_v_w = { 0, 0, { 0 }, { 0 }, { 0 } }; double __pyx_v_alpha; double __pyx_v_beta; - PyArrayObject *__pyx_v_Q = 0; - PyArrayObject *__pyx_v_q = 0; - PyArrayObject *__pyx_v_y = 0; + __Pyx_memviewslice __pyx_v_Q = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_q = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_y = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_max_iter; double __pyx_v_tol; - PyBoolObject *__pyx_v_positive = 0; - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - PyArrayObject *__pyx_v_H = 0; - double __pyx_v_tmp; - double __pyx_v_w_ii; - double __pyx_v_d_w_max; - double __pyx_v_w_max; - double __pyx_v_d_w_ii; - double __pyx_v_gap; - double __pyx_v_d_w_tol; - unsigned int __pyx_v_ii; - unsigned int __pyx_v_n_iter; - double __pyx_v_y_norm2; - PyObject *__pyx_v_q_dot_w = NULL; - PyObject *__pyx_v_XtA = NULL; - PyObject *__pyx_v_dual_norm_XtA = NULL; - PyObject *__pyx_v_R_norm2 = NULL; - PyObject *__pyx_v_w_norm = NULL; - PyObject *__pyx_v_const = NULL; - PyObject *__pyx_v_A_norm2 = NULL; - Py_buffer __pyx_bstruct_H; - Py_ssize_t __pyx_bstride_0_H = 0; - Py_ssize_t __pyx_bshape_0_H = 0; - Py_buffer __pyx_bstruct_Q; - Py_ssize_t __pyx_bstride_0_Q = 0; - Py_ssize_t __pyx_bstride_1_Q = 0; - Py_ssize_t __pyx_bshape_0_Q = 0; - Py_ssize_t __pyx_bshape_1_Q = 0; - Py_buffer __pyx_bstruct_q; - Py_ssize_t __pyx_bstride_0_q = 0; - Py_ssize_t __pyx_bshape_0_q = 0; - Py_buffer __pyx_bstruct_w; - Py_ssize_t __pyx_bstride_0_w = 0; - Py_ssize_t __pyx_bshape_0_w = 0; - Py_buffer __pyx_bstruct_y; - Py_ssize_t __pyx_bstride_0_y = 0; - Py_ssize_t __pyx_bshape_0_y = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyArrayObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - unsigned int __pyx_t_8; - unsigned int __pyx_t_9; - unsigned int __pyx_t_10; - unsigned int __pyx_t_11; - unsigned int __pyx_t_12; - unsigned int __pyx_t_13; - unsigned int __pyx_t_14; - unsigned int __pyx_t_15; - int __pyx_t_16; - int __pyx_t_17; - unsigned int __pyx_t_18; - unsigned int __pyx_t_19; - unsigned int __pyx_t_20; - unsigned int __pyx_t_21; - unsigned int __pyx_t_22; - unsigned int __pyx_t_23; - unsigned int __pyx_t_24; - unsigned int __pyx_t_25; - unsigned int __pyx_t_26; - int __pyx_t_27; - PyObject *__pyx_t_28 = NULL; - PyObject *__pyx_t_29 = NULL; + PyObject *__pyx_v_rng = 0; + int __pyx_v_random; + int __pyx_v_positive; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__w,&__pyx_n_s__alpha,&__pyx_n_s__beta,&__pyx_n_s__Q,&__pyx_n_s__q,&__pyx_n_s__y,&__pyx_n_s__max_iter,&__pyx_n_s__tol,&__pyx_n_s__positive,0}; - __Pyx_RefNannySetupContext("enet_coordinate_descent_gram"); - __pyx_self = __pyx_self; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("enet_coordinate_descent_gram (wrapper)", 0); { - PyObject* values[9] = {0,0,0,0,0,0,0,0,0}; - values[8] = (PyObject *)__pyx_k_4; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_w,&__pyx_n_s_alpha,&__pyx_n_s_beta,&__pyx_n_s_Q,&__pyx_n_s_q,&__pyx_n_s_y,&__pyx_n_s_max_iter,&__pyx_n_s_tol,&__pyx_n_s_rng,&__pyx_n_s_random,&__pyx_n_s_positive,0}; + PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); + case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); @@ -4804,66 +5501,70 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_3enet_coordinate_desc default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__w); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_w)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__alpha); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_alpha)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 8, 9, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 9, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__beta); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_beta)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 8, 9, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 9, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__Q); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Q)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 8, 9, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 9, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__q); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_q)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 8, 9, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 9, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 8, 9, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 9, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__max_iter); - if (likely(values[6])) kw_args--; + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_iter)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 8, 9, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 9, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: - values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__tol); - if (likely(values[7])) kw_args--; + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tol)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 8, 9, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 9, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: + if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_rng)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 9, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 9: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__positive); - if (value) { values[8] = value; kw_args--; } + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random); + if (value) { values[9] = value; kw_args--; } + } + case 10: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_positive); + if (value) { values[10] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "enet_coordinate_descent_gram") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "enet_coordinate_descent_gram") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { + case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); + case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); @@ -4875,1242 +5576,1133 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_3enet_coordinate_desc default: goto __pyx_L5_argtuple_error; } } - __pyx_v_w = ((PyArrayObject *)values[0]); - __pyx_v_alpha = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_alpha == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_beta = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_beta == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_Q = ((PyArrayObject *)values[3]); - __pyx_v_q = ((PyArrayObject *)values[4]); - __pyx_v_y = ((PyArrayObject *)values[5]); - __pyx_v_max_iter = __Pyx_PyInt_AsInt(values[6]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_tol = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_positive = ((PyBoolObject *)values[8]); + __pyx_v_w = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[0]); if (unlikely(!__pyx_v_w.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_alpha = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_alpha == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_beta = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_beta == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_Q = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[3]); if (unlikely(!__pyx_v_Q.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 490; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_q = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[4]); if (unlikely(!__pyx_v_q.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 490; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[5]); if (unlikely(!__pyx_v_y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 490; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_max_iter = __Pyx_PyInt_As_int(values[6]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 491; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_tol = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 491; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_rng = values[8]; + if (values[9]) { + __pyx_v_random = __Pyx_PyObject_IsTrue(values[9]); if (unlikely((__pyx_v_random == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 492; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_random = ((int)0); + } + if (values[10]) { + __pyx_v_positive = __Pyx_PyObject_IsTrue(values[10]); if (unlikely((__pyx_v_positive == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 492; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_positive = ((int)0); + } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 8, 9, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_gram", 0, 9, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.linear_model.cd_fast.enet_coordinate_descent_gram", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_H.buf = NULL; - __pyx_bstruct_w.buf = NULL; - __pyx_bstruct_Q.buf = NULL; - __pyx_bstruct_q.buf = NULL; - __pyx_bstruct_y.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_w), __pyx_ptype_5numpy_ndarray, 1, "w", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Q), __pyx_ptype_5numpy_ndarray, 1, "Q", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_q), __pyx_ptype_5numpy_ndarray, 1, "q", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_positive), __pyx_ptype_7cpython_4bool_bool, 1, "positive", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_w, (PyObject*)__pyx_v_w, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_w = __pyx_bstruct_w.strides[0]; - __pyx_bshape_0_w = __pyx_bstruct_w.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_Q, (PyObject*)__pyx_v_Q, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_Q = __pyx_bstruct_Q.strides[0]; __pyx_bstride_1_Q = __pyx_bstruct_Q.strides[1]; - __pyx_bshape_0_Q = __pyx_bstruct_Q.shape[0]; __pyx_bshape_1_Q = __pyx_bstruct_Q.shape[1]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_q, (PyObject*)__pyx_v_q, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_q = __pyx_bstruct_q.strides[0]; - __pyx_bshape_0_q = __pyx_bstruct_q.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_y, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_y = __pyx_bstruct_y.strides[0]; - __pyx_bshape_0_y = __pyx_bstruct_y.shape[0]; + __pyx_r = __pyx_pf_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_gram(__pyx_self, __pyx_v_w, __pyx_v_alpha, __pyx_v_beta, __pyx_v_Q, __pyx_v_q, __pyx_v_y, __pyx_v_max_iter, __pyx_v_tol, __pyx_v_rng, __pyx_v_random, __pyx_v_positive); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_gram(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_w, double __pyx_v_alpha, double __pyx_v_beta, __Pyx_memviewslice __pyx_v_Q, __Pyx_memviewslice __pyx_v_q, __Pyx_memviewslice __pyx_v_y, int __pyx_v_max_iter, double __pyx_v_tol, PyObject *__pyx_v_rng, int __pyx_v_random, int __pyx_v_positive) { + CYTHON_UNUSED unsigned int __pyx_v_n_samples; + unsigned int __pyx_v_n_features; + unsigned int __pyx_v_n_tasks; + __Pyx_memviewslice __pyx_v_H = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_XtA = { 0, 0, { 0 }, { 0 }, { 0 } }; + double __pyx_v_tmp; + double __pyx_v_w_ii; + double __pyx_v_d_w_max; + double __pyx_v_w_max; + double __pyx_v_d_w_ii; + double __pyx_v_gap; + double __pyx_v_d_w_tol; + double __pyx_v_dual_norm_XtA; + unsigned int __pyx_v_ii; + unsigned int __pyx_v_n_iter; + unsigned int __pyx_v_f_iter; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_v_rand_r_state_seed; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t *__pyx_v_rand_r_state; + double __pyx_v_y_norm2; + double *__pyx_v_Q_ptr; + double *__pyx_v_H_ptr; + double *__pyx_v_XtA_ptr; + double __pyx_v_q_dot_w; + double __pyx_v_R_norm2; + double __pyx_v_w_norm2; + double __pyx_v_const; + double __pyx_v_A_norm2; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + __Pyx_memviewslice __pyx_t_8 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_9 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_t_10; + double __pyx_t_11; + Py_ssize_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + Py_ssize_t __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + unsigned int __pyx_t_17; + unsigned int __pyx_t_18; + unsigned int __pyx_t_19; + unsigned int __pyx_t_20; + unsigned int __pyx_t_21; + unsigned int __pyx_t_22; + unsigned int __pyx_t_23; + unsigned int __pyx_t_24; + int __pyx_t_25; + unsigned int __pyx_t_26; + unsigned int __pyx_t_27; + unsigned int __pyx_t_28; + unsigned int __pyx_t_29; + unsigned int __pyx_t_30; + unsigned int __pyx_t_31; + unsigned int __pyx_t_32; + unsigned int __pyx_t_33; + unsigned int __pyx_t_34; + Py_ssize_t __pyx_t_35; + Py_ssize_t __pyx_t_36; + unsigned int __pyx_t_37; + unsigned int __pyx_t_38; + unsigned int __pyx_t_39; + unsigned int __pyx_t_40; + unsigned int __pyx_t_41; + unsigned int __pyx_t_42; + Py_ssize_t __pyx_t_43; + Py_ssize_t __pyx_t_44; + Py_ssize_t __pyx_t_45; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("enet_coordinate_descent_gram", 0); - /* "sklearn/linear_model/cd_fast.pyx":402 + /* "sklearn/linear_model/cd_fast.pyx":508 * * # get the data information into easy vars * cdef unsigned int n_samples = y.shape[0] # <<<<<<<<<<<<<< * cdef unsigned int n_features = Q.shape[0] - * + * cdef unsigned int n_tasks = y.strides[0] / sizeof(DOUBLE) */ - __pyx_v_n_samples = (__pyx_v_y->dimensions[0]); + __pyx_v_n_samples = (__pyx_v_y.shape[0]); - /* "sklearn/linear_model/cd_fast.pyx":403 + /* "sklearn/linear_model/cd_fast.pyx":509 * # get the data information into easy vars * cdef unsigned int n_samples = y.shape[0] * cdef unsigned int n_features = Q.shape[0] # <<<<<<<<<<<<<< + * cdef unsigned int n_tasks = y.strides[0] / sizeof(DOUBLE) + * + */ + __pyx_v_n_features = (__pyx_v_Q.shape[0]); + + /* "sklearn/linear_model/cd_fast.pyx":510 + * cdef unsigned int n_samples = y.shape[0] + * cdef unsigned int n_features = Q.shape[0] + * cdef unsigned int n_tasks = y.strides[0] / sizeof(DOUBLE) # <<<<<<<<<<<<<< * * # initial value "Q w" which will be kept of up to date in the iterations */ - __pyx_v_n_features = (__pyx_v_Q->dimensions[0]); + __pyx_v_n_tasks = ((__pyx_v_y.strides[0]) / (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))); - /* "sklearn/linear_model/cd_fast.pyx":406 + /* "sklearn/linear_model/cd_fast.pyx":513 * * # initial value "Q w" which will be kept of up to date in the iterations - * cdef np.ndarray[DOUBLE, ndim=1] H = np.dot(Q, w) # <<<<<<<<<<<<<< + * cdef double[:] H = np.dot(Q, w) # <<<<<<<<<<<<<< * - * cdef double tmp + * cdef double[:] XtA = np.zeros(n_features) */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 406; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__dot); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 406; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 406; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_v_Q)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_Q)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_Q)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 406; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_dot); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 406; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = ((PyArrayObject *)__pyx_t_3); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_H, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_H = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_H.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 406; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_H = __pyx_bstruct_H.strides[0]; - __pyx_bshape_0_H = __pyx_bstruct_H.shape[0]; + __pyx_t_2 = __pyx_memoryview_fromslice(__pyx_v_Q, 2, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_w, 1, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = NULL; + __pyx_t_6 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_6 = 1; } } + __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (__pyx_t_5) { + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; + } + PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; __pyx_t_4 = 0; - __pyx_v_H = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_8 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_t_1); + if (unlikely(!__pyx_t_8.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_H = __pyx_t_8; + __pyx_t_8.memview = NULL; + __pyx_t_8.data = NULL; - /* "sklearn/linear_model/cd_fast.pyx":413 - * cdef double w_max - * cdef double d_w_ii - * cdef double gap = tol + 1.0 # <<<<<<<<<<<<<< - * cdef double d_w_tol = tol - * cdef unsigned int ii + /* "sklearn/linear_model/cd_fast.pyx":515 + * cdef double[:] H = np.dot(Q, w) + * + * cdef double[:] XtA = np.zeros(n_features) # <<<<<<<<<<<<<< + * cdef double tmp + * cdef double w_ii */ - __pyx_v_gap = (__pyx_v_tol + 1.0); - - /* "sklearn/linear_model/cd_fast.pyx":414 - * cdef double d_w_ii + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_features); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_7); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_7, function); + } + } + if (!__pyx_t_4) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_2 = PyTuple_New(1+1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + PyTuple_SET_ITEM(__pyx_t_2, 0+1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_9 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_t_1); + if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_XtA = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "sklearn/linear_model/cd_fast.pyx":521 + * cdef double w_max + * cdef double d_w_ii + * cdef double gap = tol + 1.0 # <<<<<<<<<<<<<< + * cdef double d_w_tol = tol + * cdef double dual_norm_XtA + */ + __pyx_v_gap = (__pyx_v_tol + 1.0); + + /* "sklearn/linear_model/cd_fast.pyx":522 + * cdef double d_w_ii * cdef double gap = tol + 1.0 * cdef double d_w_tol = tol # <<<<<<<<<<<<<< + * cdef double dual_norm_XtA * cdef unsigned int ii - * cdef unsigned int n_iter */ __pyx_v_d_w_tol = __pyx_v_tol; - /* "sklearn/linear_model/cd_fast.pyx":418 + /* "sklearn/linear_model/cd_fast.pyx":527 * cdef unsigned int n_iter - * - * cdef double y_norm2 = linalg.norm(y) ** 2 # <<<<<<<<<<<<<< - * tol = tol * y_norm2 + * cdef unsigned int f_iter + * cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) # <<<<<<<<<<<<<< + * cdef UINT32_t* rand_r_state = &rand_r_state_seed * */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__norm); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_rng, __pyx_n_s_randint); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_e_7sklearn_12linear_model_7cd_fast_RAND_R_MAX); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_6 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_7); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_7, function); + __pyx_t_6 = 1; + } + } + __pyx_t_4 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (__pyx_t_3) { + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = NULL; + } + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_4, 0+__pyx_t_6, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_4, 1+__pyx_t_6, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(((PyObject *)__pyx_v_y)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_y)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_10 = __Pyx_PyInt_As_npy_uint32(__pyx_t_1); if (unlikely((__pyx_t_10 == (npy_uint32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_rand_r_state_seed = __pyx_t_10; + + /* "sklearn/linear_model/cd_fast.pyx":528 + * cdef unsigned int f_iter + * cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + * cdef UINT32_t* rand_r_state = &rand_r_state_seed # <<<<<<<<<<<<<< + * + * cdef double y_norm2 = np.dot(y, y) + */ + __pyx_v_rand_r_state = (&__pyx_v_rand_r_state_seed); + + /* "sklearn/linear_model/cd_fast.pyx":530 + * cdef UINT32_t* rand_r_state = &rand_r_state_seed + * + * cdef double y_norm2 = np.dot(y, y) # <<<<<<<<<<<<<< + * cdef double* Q_ptr = &Q[0, 0] + * cdef double* H_ptr = &H[0] + */ + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_dot); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __pyx_memoryview_fromslice(__pyx_v_y, 1, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __pyx_memoryview_fromslice(__pyx_v_y, 1, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_6 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + __pyx_t_6 = 1; + } + } + __pyx_t_5 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (__pyx_t_3) { + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = NULL; + } + PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_6, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_6, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_7 = 0; + __pyx_t_2 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_11 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_11 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Power(__pyx_t_2, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_y_norm2 = __pyx_t_5; + __pyx_v_y_norm2 = __pyx_t_11; - /* "sklearn/linear_model/cd_fast.pyx":419 + /* "sklearn/linear_model/cd_fast.pyx":531 * - * cdef double y_norm2 = linalg.norm(y) ** 2 + * cdef double y_norm2 = np.dot(y, y) + * cdef double* Q_ptr = &Q[0, 0] # <<<<<<<<<<<<<< + * cdef double* H_ptr = &H[0] + * cdef double* XtA_ptr = &XtA[0] + */ + __pyx_t_6 = 0; + __pyx_t_12 = 0; + __pyx_v_Q_ptr = (&(*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Q.data + __pyx_t_6 * __pyx_v_Q.strides[0]) ) + __pyx_t_12 * __pyx_v_Q.strides[1]) )))); + + /* "sklearn/linear_model/cd_fast.pyx":532 + * cdef double y_norm2 = np.dot(y, y) + * cdef double* Q_ptr = &Q[0, 0] + * cdef double* H_ptr = &H[0] # <<<<<<<<<<<<<< + * cdef double* XtA_ptr = &XtA[0] + * tol = tol * y_norm2 + */ + __pyx_t_13 = 0; + __pyx_v_H_ptr = (&(*((double *) ( /* dim=0 */ (__pyx_v_H.data + __pyx_t_13 * __pyx_v_H.strides[0]) )))); + + /* "sklearn/linear_model/cd_fast.pyx":533 + * cdef double* Q_ptr = &Q[0, 0] + * cdef double* H_ptr = &H[0] + * cdef double* XtA_ptr = &XtA[0] # <<<<<<<<<<<<<< + * tol = tol * y_norm2 + * + */ + __pyx_t_14 = 0; + __pyx_v_XtA_ptr = (&(*((double *) ( /* dim=0 */ (__pyx_v_XtA.data + __pyx_t_14 * __pyx_v_XtA.strides[0]) )))); + + /* "sklearn/linear_model/cd_fast.pyx":534 + * cdef double* H_ptr = &H[0] + * cdef double* XtA_ptr = &XtA[0] * tol = tol * y_norm2 # <<<<<<<<<<<<<< * * if alpha == 0: */ __pyx_v_tol = (__pyx_v_tol * __pyx_v_y_norm2); - /* "sklearn/linear_model/cd_fast.pyx":421 + /* "sklearn/linear_model/cd_fast.pyx":536 * tol = tol * y_norm2 * * if alpha == 0: # <<<<<<<<<<<<<< * warnings.warn("Coordinate descent with alpha=0 may lead to unexpected" * " results and is discouraged.") */ - __pyx_t_6 = (__pyx_v_alpha == 0.0); - if (__pyx_t_6) { + __pyx_t_15 = ((__pyx_v_alpha == 0.0) != 0); + if (__pyx_t_15) { - /* "sklearn/linear_model/cd_fast.pyx":422 + /* "sklearn/linear_model/cd_fast.pyx":537 * * if alpha == 0: * warnings.warn("Coordinate descent with alpha=0 may lead to unexpected" # <<<<<<<<<<<<<< * " results and is discouraged.") * */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__warnings); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__warn); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_k_tuple_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L6; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_warnings); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_warn); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L3; } - __pyx_L6:; + __pyx_L3:; - /* "sklearn/linear_model/cd_fast.pyx":425 + /* "sklearn/linear_model/cd_fast.pyx":540 * " results and is discouraged.") * - * for n_iter in range(max_iter): # <<<<<<<<<<<<<< - * w_max = 0.0 - * d_w_max = 0.0 + * with nogil: # <<<<<<<<<<<<<< + * for n_iter in range(max_iter): + * w_max = 0.0 */ - __pyx_t_7 = __pyx_v_max_iter; - for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { - __pyx_v_n_iter = __pyx_t_8; - - /* "sklearn/linear_model/cd_fast.pyx":426 - * - * for n_iter in range(max_iter): - * w_max = 0.0 # <<<<<<<<<<<<<< - * d_w_max = 0.0 - * for ii in xrange(n_features): # Loop over coordinates + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/linear_model/cd_fast.pyx":541 + * + * with nogil: + * for n_iter in range(max_iter): # <<<<<<<<<<<<<< + * w_max = 0.0 + * d_w_max = 0.0 + */ + __pyx_t_16 = __pyx_v_max_iter; + for (__pyx_t_17 = 0; __pyx_t_17 < __pyx_t_16; __pyx_t_17+=1) { + __pyx_v_n_iter = __pyx_t_17; + + /* "sklearn/linear_model/cd_fast.pyx":542 + * with nogil: + * for n_iter in range(max_iter): + * w_max = 0.0 # <<<<<<<<<<<<<< + * d_w_max = 0.0 + * for f_iter in range(n_features): # Loop over coordinates + */ + __pyx_v_w_max = 0.0; + + /* "sklearn/linear_model/cd_fast.pyx":543 + * for n_iter in range(max_iter): + * w_max = 0.0 + * d_w_max = 0.0 # <<<<<<<<<<<<<< + * for f_iter in range(n_features): # Loop over coordinates + * if random: + */ + __pyx_v_d_w_max = 0.0; + + /* "sklearn/linear_model/cd_fast.pyx":544 + * w_max = 0.0 + * d_w_max = 0.0 + * for f_iter in range(n_features): # Loop over coordinates # <<<<<<<<<<<<<< + * if random: + * ii = rand_int(n_features, rand_r_state) + */ + __pyx_t_18 = __pyx_v_n_features; + for (__pyx_t_19 = 0; __pyx_t_19 < __pyx_t_18; __pyx_t_19+=1) { + __pyx_v_f_iter = __pyx_t_19; + + /* "sklearn/linear_model/cd_fast.pyx":545 + * d_w_max = 0.0 + * for f_iter in range(n_features): # Loop over coordinates + * if random: # <<<<<<<<<<<<<< + * ii = rand_int(n_features, rand_r_state) + * else: */ - __pyx_v_w_max = 0.0; + __pyx_t_15 = (__pyx_v_random != 0); + if (__pyx_t_15) { - /* "sklearn/linear_model/cd_fast.pyx":427 - * for n_iter in range(max_iter): - * w_max = 0.0 - * d_w_max = 0.0 # <<<<<<<<<<<<<< - * for ii in xrange(n_features): # Loop over coordinates - * if Q[ii, ii] == 0.0: + /* "sklearn/linear_model/cd_fast.pyx":546 + * for f_iter in range(n_features): # Loop over coordinates + * if random: + * ii = rand_int(n_features, rand_r_state) # <<<<<<<<<<<<<< + * else: + * ii = f_iter */ - __pyx_v_d_w_max = 0.0; + __pyx_v_ii = __pyx_f_7sklearn_12linear_model_7cd_fast_rand_int(__pyx_v_n_features, __pyx_v_rand_r_state); + goto __pyx_L11; + } + /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":428 - * w_max = 0.0 - * d_w_max = 0.0 - * for ii in xrange(n_features): # Loop over coordinates # <<<<<<<<<<<<<< - * if Q[ii, ii] == 0.0: - * continue + /* "sklearn/linear_model/cd_fast.pyx":548 + * ii = rand_int(n_features, rand_r_state) + * else: + * ii = f_iter # <<<<<<<<<<<<<< + * + * if Q[ii, ii] == 0.0: */ - __pyx_t_9 = __pyx_v_n_features; - for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { - __pyx_v_ii = __pyx_t_10; + __pyx_v_ii = __pyx_v_f_iter; + } + __pyx_L11:; - /* "sklearn/linear_model/cd_fast.pyx":429 - * d_w_max = 0.0 - * for ii in xrange(n_features): # Loop over coordinates - * if Q[ii, ii] == 0.0: # <<<<<<<<<<<<<< - * continue + /* "sklearn/linear_model/cd_fast.pyx":550 + * ii = f_iter + * + * if Q[ii, ii] == 0.0: # <<<<<<<<<<<<<< + * continue * */ - __pyx_t_11 = __pyx_v_ii; - __pyx_t_12 = __pyx_v_ii; - __pyx_t_6 = ((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_Q.buf, __pyx_t_11, __pyx_bstride_0_Q, __pyx_t_12, __pyx_bstride_1_Q)) == 0.0); - if (__pyx_t_6) { + __pyx_t_20 = __pyx_v_ii; + __pyx_t_21 = __pyx_v_ii; + __pyx_t_15 = (((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Q.data + __pyx_t_20 * __pyx_v_Q.strides[0]) ) + __pyx_t_21 * __pyx_v_Q.strides[1]) ))) == 0.0) != 0); + if (__pyx_t_15) { - /* "sklearn/linear_model/cd_fast.pyx":430 - * for ii in xrange(n_features): # Loop over coordinates - * if Q[ii, ii] == 0.0: - * continue # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":551 * - * w_ii = w[ii] # Store previous value + * if Q[ii, ii] == 0.0: + * continue # <<<<<<<<<<<<<< + * + * w_ii = w[ii] # Store previous value */ - goto __pyx_L9_continue; - goto __pyx_L11; - } - __pyx_L11:; + goto __pyx_L9_continue; + } - /* "sklearn/linear_model/cd_fast.pyx":432 - * continue + /* "sklearn/linear_model/cd_fast.pyx":553 + * continue * - * w_ii = w[ii] # Store previous value # <<<<<<<<<<<<<< + * w_ii = w[ii] # Store previous value # <<<<<<<<<<<<<< * - * if w_ii != 0.0: + * if w_ii != 0.0: */ - __pyx_t_13 = __pyx_v_ii; - __pyx_v_w_ii = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_13, __pyx_bstride_0_w)); + __pyx_t_22 = __pyx_v_ii; + __pyx_v_w_ii = (*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_22 * __pyx_v_w.strides[0]) ))); - /* "sklearn/linear_model/cd_fast.pyx":434 - * w_ii = w[ii] # Store previous value + /* "sklearn/linear_model/cd_fast.pyx":555 + * w_ii = w[ii] # Store previous value * - * if w_ii != 0.0: # <<<<<<<<<<<<<< - * # H -= w_ii * Q[ii] - * daxpy(n_features, -w_ii, + * if w_ii != 0.0: # <<<<<<<<<<<<<< + * # H -= w_ii * Q[ii] + * daxpy(n_features, -w_ii, Q_ptr + ii * n_features, 1, */ - __pyx_t_6 = (__pyx_v_w_ii != 0.0); - if (__pyx_t_6) { + __pyx_t_15 = ((__pyx_v_w_ii != 0.0) != 0); + if (__pyx_t_15) { - /* "sklearn/linear_model/cd_fast.pyx":438 - * daxpy(n_features, -w_ii, - * (Q.data + ii * n_features * sizeof(DOUBLE)), 1, - * H.data, 1) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":557 + * if w_ii != 0.0: + * # H -= w_ii * Q[ii] + * daxpy(n_features, -w_ii, Q_ptr + ii * n_features, 1, # <<<<<<<<<<<<<< + * H_ptr, 1) * - * tmp = q[ii] - H[ii] */ - cblas_daxpy(__pyx_v_n_features, (-__pyx_v_w_ii), ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_Q->data + ((__pyx_v_ii * __pyx_v_n_features) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_H->data), 1); - goto __pyx_L12; - } - __pyx_L12:; + cblas_daxpy(__pyx_v_n_features, (-__pyx_v_w_ii), (__pyx_v_Q_ptr + (__pyx_v_ii * __pyx_v_n_features)), 1, __pyx_v_H_ptr, 1); + goto __pyx_L13; + } + __pyx_L13:; - /* "sklearn/linear_model/cd_fast.pyx":440 - * H.data, 1) + /* "sklearn/linear_model/cd_fast.pyx":560 + * H_ptr, 1) * - * tmp = q[ii] - H[ii] # <<<<<<<<<<<<<< + * tmp = q[ii] - H[ii] # <<<<<<<<<<<<<< * - * if positive and tmp < 0: + * if positive and tmp < 0: */ - __pyx_t_14 = __pyx_v_ii; - __pyx_t_15 = __pyx_v_ii; - __pyx_v_tmp = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_q.buf, __pyx_t_14, __pyx_bstride_0_q)) - (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_H.buf, __pyx_t_15, __pyx_bstride_0_H))); + __pyx_t_23 = __pyx_v_ii; + __pyx_t_24 = __pyx_v_ii; + __pyx_v_tmp = ((*((double *) ( /* dim=0 */ (__pyx_v_q.data + __pyx_t_23 * __pyx_v_q.strides[0]) ))) - (*((double *) ( /* dim=0 */ (__pyx_v_H.data + __pyx_t_24 * __pyx_v_H.strides[0]) )))); - /* "sklearn/linear_model/cd_fast.pyx":442 - * tmp = q[ii] - H[ii] + /* "sklearn/linear_model/cd_fast.pyx":562 + * tmp = q[ii] - H[ii] * - * if positive and tmp < 0: # <<<<<<<<<<<<<< - * w[ii] = 0.0 - * else: + * if positive and tmp < 0: # <<<<<<<<<<<<<< + * w[ii] = 0.0 + * else: */ - __pyx_t_6 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_positive)); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_6) { - __pyx_t_16 = (__pyx_v_tmp < 0.0); - __pyx_t_17 = __pyx_t_16; - } else { - __pyx_t_17 = __pyx_t_6; - } - if (__pyx_t_17) { + __pyx_t_25 = (__pyx_v_positive != 0); + if (__pyx_t_25) { + goto __pyx_L16_next_and; + } else { + __pyx_t_15 = __pyx_t_25; + goto __pyx_L15_bool_binop_done; + } + __pyx_L16_next_and:; + __pyx_t_25 = ((__pyx_v_tmp < 0.0) != 0); + __pyx_t_15 = __pyx_t_25; + __pyx_L15_bool_binop_done:; + if (__pyx_t_15) { - /* "sklearn/linear_model/cd_fast.pyx":443 + /* "sklearn/linear_model/cd_fast.pyx":563 * - * if positive and tmp < 0: - * w[ii] = 0.0 # <<<<<<<<<<<<<< - * else: - * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ + * if positive and tmp < 0: + * w[ii] = 0.0 # <<<<<<<<<<<<<< + * else: + * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ */ - __pyx_t_18 = __pyx_v_ii; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_18, __pyx_bstride_0_w) = 0.0; - goto __pyx_L13; - } - /*else*/ { + __pyx_t_26 = __pyx_v_ii; + *((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_26 * __pyx_v_w.strides[0]) )) = 0.0; + goto __pyx_L14; + } + /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":446 - * else: - * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ - * / (Q[ii, ii] + beta) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":566 + * else: + * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ + * / (Q[ii, ii] + beta) # <<<<<<<<<<<<<< * - * if w[ii] != 0.0: + * if w[ii] != 0.0: */ - __pyx_t_19 = __pyx_v_ii; - __pyx_t_20 = __pyx_v_ii; + __pyx_t_27 = __pyx_v_ii; + __pyx_t_28 = __pyx_v_ii; - /* "sklearn/linear_model/cd_fast.pyx":445 - * w[ii] = 0.0 - * else: - * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ # <<<<<<<<<<<<<< - * / (Q[ii, ii] + beta) + /* "sklearn/linear_model/cd_fast.pyx":565 + * w[ii] = 0.0 + * else: + * w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ # <<<<<<<<<<<<<< + * / (Q[ii, ii] + beta) * */ - __pyx_t_21 = __pyx_v_ii; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_21, __pyx_bstride_0_w) = ((__pyx_f_7sklearn_12linear_model_7cd_fast_fsign(__pyx_v_tmp) * __pyx_f_7sklearn_12linear_model_7cd_fast_fmax((fabs(__pyx_v_tmp) - __pyx_v_alpha), 0.0)) / ((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_Q.buf, __pyx_t_19, __pyx_bstride_0_Q, __pyx_t_20, __pyx_bstride_1_Q)) + __pyx_v_beta)); - } - __pyx_L13:; + __pyx_t_29 = __pyx_v_ii; + *((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_29 * __pyx_v_w.strides[0]) )) = ((__pyx_f_7sklearn_12linear_model_7cd_fast_fsign(__pyx_v_tmp) * __pyx_f_7sklearn_12linear_model_7cd_fast_fmax((fabs(__pyx_v_tmp) - __pyx_v_alpha), 0.0)) / ((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Q.data + __pyx_t_27 * __pyx_v_Q.strides[0]) ) + __pyx_t_28 * __pyx_v_Q.strides[1]) ))) + __pyx_v_beta)); + } + __pyx_L14:; - /* "sklearn/linear_model/cd_fast.pyx":448 - * / (Q[ii, ii] + beta) + /* "sklearn/linear_model/cd_fast.pyx":568 + * / (Q[ii, ii] + beta) * - * if w[ii] != 0.0: # <<<<<<<<<<<<<< - * # H += w[ii] * Q[ii] # Update H = X.T X w - * daxpy(n_features, w[ii], + * if w[ii] != 0.0: # <<<<<<<<<<<<<< + * # H += w[ii] * Q[ii] # Update H = X.T X w + * daxpy(n_features, w[ii], Q_ptr + ii * n_features, 1, */ - __pyx_t_22 = __pyx_v_ii; - __pyx_t_17 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_22, __pyx_bstride_0_w)) != 0.0); - if (__pyx_t_17) { + __pyx_t_30 = __pyx_v_ii; + __pyx_t_15 = (((*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_30 * __pyx_v_w.strides[0]) ))) != 0.0) != 0); + if (__pyx_t_15) { - /* "sklearn/linear_model/cd_fast.pyx":450 - * if w[ii] != 0.0: - * # H += w[ii] * Q[ii] # Update H = X.T X w - * daxpy(n_features, w[ii], # <<<<<<<<<<<<<< - * (Q.data + ii * n_features * sizeof(DOUBLE)), 1, - * H.data, 1) + /* "sklearn/linear_model/cd_fast.pyx":570 + * if w[ii] != 0.0: + * # H += w[ii] * Q[ii] # Update H = X.T X w + * daxpy(n_features, w[ii], Q_ptr + ii * n_features, 1, # <<<<<<<<<<<<<< + * H_ptr, 1) + * */ - __pyx_t_23 = __pyx_v_ii; + __pyx_t_31 = __pyx_v_ii; - /* "sklearn/linear_model/cd_fast.pyx":452 - * daxpy(n_features, w[ii], - * (Q.data + ii * n_features * sizeof(DOUBLE)), 1, - * H.data, 1) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":571 + * # H += w[ii] * Q[ii] # Update H = X.T X w + * daxpy(n_features, w[ii], Q_ptr + ii * n_features, 1, + * H_ptr, 1) # <<<<<<<<<<<<<< * - * # update the maximum absolute coefficient update + * # update the maximum absolute coefficient update */ - cblas_daxpy(__pyx_v_n_features, (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_23, __pyx_bstride_0_w)), ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_Q->data + ((__pyx_v_ii * __pyx_v_n_features) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_H->data), 1); - goto __pyx_L14; - } - __pyx_L14:; + cblas_daxpy(__pyx_v_n_features, (*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_31 * __pyx_v_w.strides[0]) ))), (__pyx_v_Q_ptr + (__pyx_v_ii * __pyx_v_n_features)), 1, __pyx_v_H_ptr, 1); + goto __pyx_L17; + } + __pyx_L17:; - /* "sklearn/linear_model/cd_fast.pyx":455 + /* "sklearn/linear_model/cd_fast.pyx":574 * - * # update the maximum absolute coefficient update - * d_w_ii = fabs(w[ii] - w_ii) # <<<<<<<<<<<<<< - * if d_w_ii > d_w_max: - * d_w_max = d_w_ii + * # update the maximum absolute coefficient update + * d_w_ii = fabs(w[ii] - w_ii) # <<<<<<<<<<<<<< + * if d_w_ii > d_w_max: + * d_w_max = d_w_ii */ - __pyx_t_24 = __pyx_v_ii; - __pyx_v_d_w_ii = fabs(((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_24, __pyx_bstride_0_w)) - __pyx_v_w_ii)); + __pyx_t_32 = __pyx_v_ii; + __pyx_v_d_w_ii = fabs(((*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_32 * __pyx_v_w.strides[0]) ))) - __pyx_v_w_ii)); - /* "sklearn/linear_model/cd_fast.pyx":456 - * # update the maximum absolute coefficient update - * d_w_ii = fabs(w[ii] - w_ii) - * if d_w_ii > d_w_max: # <<<<<<<<<<<<<< - * d_w_max = d_w_ii + /* "sklearn/linear_model/cd_fast.pyx":575 + * # update the maximum absolute coefficient update + * d_w_ii = fabs(w[ii] - w_ii) + * if d_w_ii > d_w_max: # <<<<<<<<<<<<<< + * d_w_max = d_w_ii * */ - __pyx_t_17 = (__pyx_v_d_w_ii > __pyx_v_d_w_max); - if (__pyx_t_17) { + __pyx_t_15 = ((__pyx_v_d_w_ii > __pyx_v_d_w_max) != 0); + if (__pyx_t_15) { - /* "sklearn/linear_model/cd_fast.pyx":457 - * d_w_ii = fabs(w[ii] - w_ii) - * if d_w_ii > d_w_max: - * d_w_max = d_w_ii # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":576 + * d_w_ii = fabs(w[ii] - w_ii) + * if d_w_ii > d_w_max: + * d_w_max = d_w_ii # <<<<<<<<<<<<<< * - * if fabs(w[ii]) > w_max: + * if fabs(w[ii]) > w_max: */ - __pyx_v_d_w_max = __pyx_v_d_w_ii; - goto __pyx_L15; - } - __pyx_L15:; + __pyx_v_d_w_max = __pyx_v_d_w_ii; + goto __pyx_L18; + } + __pyx_L18:; - /* "sklearn/linear_model/cd_fast.pyx":459 - * d_w_max = d_w_ii + /* "sklearn/linear_model/cd_fast.pyx":578 + * d_w_max = d_w_ii * - * if fabs(w[ii]) > w_max: # <<<<<<<<<<<<<< - * w_max = fabs(w[ii]) + * if fabs(w[ii]) > w_max: # <<<<<<<<<<<<<< + * w_max = fabs(w[ii]) * */ - __pyx_t_25 = __pyx_v_ii; - __pyx_t_17 = (fabs((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_25, __pyx_bstride_0_w))) > __pyx_v_w_max); - if (__pyx_t_17) { + __pyx_t_33 = __pyx_v_ii; + __pyx_t_15 = ((fabs((*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_33 * __pyx_v_w.strides[0]) )))) > __pyx_v_w_max) != 0); + if (__pyx_t_15) { - /* "sklearn/linear_model/cd_fast.pyx":460 + /* "sklearn/linear_model/cd_fast.pyx":579 * - * if fabs(w[ii]) > w_max: - * w_max = fabs(w[ii]) # <<<<<<<<<<<<<< + * if fabs(w[ii]) > w_max: + * w_max = fabs(w[ii]) # <<<<<<<<<<<<<< * - * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: + * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: */ - __pyx_t_26 = __pyx_v_ii; - __pyx_v_w_max = fabs((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_w.buf, __pyx_t_26, __pyx_bstride_0_w))); - goto __pyx_L16; - } - __pyx_L16:; - __pyx_L9_continue:; - } + __pyx_t_34 = __pyx_v_ii; + __pyx_v_w_max = fabs((*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_34 * __pyx_v_w.strides[0]) )))); + goto __pyx_L19; + } + __pyx_L19:; + __pyx_L9_continue:; + } - /* "sklearn/linear_model/cd_fast.pyx":462 - * w_max = fabs(w[ii]) + /* "sklearn/linear_model/cd_fast.pyx":581 + * w_max = fabs(w[ii]) * - * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: # <<<<<<<<<<<<<< - * # the biggest coordinate update of this iteration was smaller than - * # the tolerance: check the duality gap as ultimate stopping + * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: # <<<<<<<<<<<<<< + * # the biggest coordinate update of this iteration was smaller than + * # the tolerance: check the duality gap as ultimate stopping */ - __pyx_t_17 = (__pyx_v_w_max == 0.0); - if (!__pyx_t_17) { - __pyx_t_6 = ((__pyx_v_d_w_max / __pyx_v_w_max) < __pyx_v_d_w_tol); - if (!__pyx_t_6) { - __pyx_t_16 = (__pyx_v_n_iter == (__pyx_v_max_iter - 1)); - __pyx_t_27 = __pyx_t_16; - } else { - __pyx_t_27 = __pyx_t_6; - } - __pyx_t_6 = __pyx_t_27; - } else { - __pyx_t_6 = __pyx_t_17; - } - if (__pyx_t_6) { + __pyx_t_25 = ((__pyx_v_w_max == 0.0) != 0); + if (!__pyx_t_25) { + goto __pyx_L22_next_or; + } else { + __pyx_t_15 = __pyx_t_25; + goto __pyx_L21_bool_binop_done; + } + __pyx_L22_next_or:; + __pyx_t_25 = (((__pyx_v_d_w_max / __pyx_v_w_max) < __pyx_v_d_w_tol) != 0); + if (!__pyx_t_25) { + goto __pyx_L23_next_or; + } else { + __pyx_t_15 = __pyx_t_25; + goto __pyx_L21_bool_binop_done; + } + __pyx_L23_next_or:; + __pyx_t_25 = ((__pyx_v_n_iter == (__pyx_v_max_iter - 1)) != 0); + __pyx_t_15 = __pyx_t_25; + __pyx_L21_bool_binop_done:; + if (__pyx_t_15) { + + /* "sklearn/linear_model/cd_fast.pyx":589 + * # Note that increment in q is not 1 because the strides + * # vary if q is sliced from a 2-D array. + * q_dot_w = ddot(n_features, &w[0], 1, &q[0], n_tasks) # <<<<<<<<<<<<<< + * + * for ii in range(n_features): + */ + __pyx_t_35 = 0; + __pyx_t_36 = 0; + __pyx_v_q_dot_w = cblas_ddot(__pyx_v_n_features, (&(*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_35 * __pyx_v_w.strides[0]) )))), 1, (&(*((double *) ( /* dim=0 */ (__pyx_v_q.data + __pyx_t_36 * __pyx_v_q.strides[0]) )))), __pyx_v_n_tasks); + + /* "sklearn/linear_model/cd_fast.pyx":591 + * q_dot_w = ddot(n_features, &w[0], 1, &q[0], n_tasks) + * + * for ii in range(n_features): # <<<<<<<<<<<<<< + * XtA[ii] = q[ii] - H[ii] - beta * w[ii] + * if positive: + */ + __pyx_t_18 = __pyx_v_n_features; + for (__pyx_t_19 = 0; __pyx_t_19 < __pyx_t_18; __pyx_t_19+=1) { + __pyx_v_ii = __pyx_t_19; + + /* "sklearn/linear_model/cd_fast.pyx":592 + * + * for ii in range(n_features): + * XtA[ii] = q[ii] - H[ii] - beta * w[ii] # <<<<<<<<<<<<<< + * if positive: + * dual_norm_XtA = max(n_features, XtA_ptr) + */ + __pyx_t_37 = __pyx_v_ii; + __pyx_t_38 = __pyx_v_ii; + __pyx_t_39 = __pyx_v_ii; + __pyx_t_40 = __pyx_v_ii; + *((double *) ( /* dim=0 */ (__pyx_v_XtA.data + __pyx_t_40 * __pyx_v_XtA.strides[0]) )) = (((*((double *) ( /* dim=0 */ (__pyx_v_q.data + __pyx_t_37 * __pyx_v_q.strides[0]) ))) - (*((double *) ( /* dim=0 */ (__pyx_v_H.data + __pyx_t_38 * __pyx_v_H.strides[0]) )))) - (__pyx_v_beta * (*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_39 * __pyx_v_w.strides[0]) ))))); + } - /* "sklearn/linear_model/cd_fast.pyx":467 - * # criterion - * - * q_dot_w = np.dot(w, q) # <<<<<<<<<<<<<< - * - * XtA = q - H - beta * w + /* "sklearn/linear_model/cd_fast.pyx":593 + * for ii in range(n_features): + * XtA[ii] = q[ii] - H[ii] - beta * w[ii] + * if positive: # <<<<<<<<<<<<<< + * dual_norm_XtA = max(n_features, XtA_ptr) + * else: */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__dot); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __Pyx_INCREF(((PyObject *)__pyx_v_q)); - PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_v_q)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_q)); - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_q_dot_w); - __pyx_v_q_dot_w = __pyx_t_1; - __pyx_t_1 = 0; + __pyx_t_15 = (__pyx_v_positive != 0); + if (__pyx_t_15) { + + /* "sklearn/linear_model/cd_fast.pyx":594 + * XtA[ii] = q[ii] - H[ii] - beta * w[ii] + * if positive: + * dual_norm_XtA = max(n_features, XtA_ptr) # <<<<<<<<<<<<<< + * else: + * dual_norm_XtA = abs_max(n_features, XtA_ptr) + */ + __pyx_v_dual_norm_XtA = __pyx_f_7sklearn_12linear_model_7cd_fast_max(__pyx_v_n_features, __pyx_v_XtA_ptr); + goto __pyx_L26; + } + /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":469 - * q_dot_w = np.dot(w, q) + /* "sklearn/linear_model/cd_fast.pyx":596 + * dual_norm_XtA = max(n_features, XtA_ptr) + * else: + * dual_norm_XtA = abs_max(n_features, XtA_ptr) # <<<<<<<<<<<<<< * - * XtA = q - H - beta * w # <<<<<<<<<<<<<< - * if positive: - * dual_norm_XtA = np.max(XtA) + * # temp = np.sum(w * H) */ - __pyx_t_1 = PyNumber_Subtract(((PyObject *)__pyx_v_q), ((PyObject *)__pyx_v_H)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_beta); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_3, ((PyObject *)__pyx_v_w)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_v_XtA); - __pyx_v_XtA = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_v_dual_norm_XtA = __pyx_f_7sklearn_12linear_model_7cd_fast_abs_max(__pyx_v_n_features, __pyx_v_XtA_ptr); + } + __pyx_L26:; - /* "sklearn/linear_model/cd_fast.pyx":470 + /* "sklearn/linear_model/cd_fast.pyx":599 * - * XtA = q - H - beta * w - * if positive: # <<<<<<<<<<<<<< - * dual_norm_XtA = np.max(XtA) - * else: + * # temp = np.sum(w * H) + * tmp = 0.0 # <<<<<<<<<<<<<< + * for ii in range(n_features): + * tmp += w[ii] * H[ii] */ - __pyx_t_6 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_positive)); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_6) { + __pyx_v_tmp = 0.0; - /* "sklearn/linear_model/cd_fast.pyx":471 - * XtA = q - H - beta * w - * if positive: - * dual_norm_XtA = np.max(XtA) # <<<<<<<<<<<<<< - * else: - * dual_norm_XtA = linalg.norm(XtA, np.inf) + /* "sklearn/linear_model/cd_fast.pyx":600 + * # temp = np.sum(w * H) + * tmp = 0.0 + * for ii in range(n_features): # <<<<<<<<<<<<<< + * tmp += w[ii] * H[ii] + * R_norm2 = y_norm2 + tmp - 2.0 * q_dot_w */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__max); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(__pyx_v_XtA); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_XtA); - __Pyx_GIVEREF(__pyx_v_XtA); - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_dual_norm_XtA); - __pyx_v_dual_norm_XtA = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L18; - } - /*else*/ { + __pyx_t_18 = __pyx_v_n_features; + for (__pyx_t_19 = 0; __pyx_t_19 < __pyx_t_18; __pyx_t_19+=1) { + __pyx_v_ii = __pyx_t_19; - /* "sklearn/linear_model/cd_fast.pyx":473 - * dual_norm_XtA = np.max(XtA) - * else: - * dual_norm_XtA = linalg.norm(XtA, np.inf) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":601 + * tmp = 0.0 + * for ii in range(n_features): + * tmp += w[ii] * H[ii] # <<<<<<<<<<<<<< + * R_norm2 = y_norm2 + tmp - 2.0 * q_dot_w * - * R_norm2 = y_norm2 + np.sum(w * H) - 2.0 * q_dot_w */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 473; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__norm); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 473; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 473; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 473; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 473; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(__pyx_v_XtA); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_XtA); - __Pyx_GIVEREF(__pyx_v_XtA); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 473; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_v_dual_norm_XtA); - __pyx_v_dual_norm_XtA = __pyx_t_2; - __pyx_t_2 = 0; - } - __pyx_L18:; + __pyx_t_41 = __pyx_v_ii; + __pyx_t_42 = __pyx_v_ii; + __pyx_v_tmp = (__pyx_v_tmp + ((*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_41 * __pyx_v_w.strides[0]) ))) * (*((double *) ( /* dim=0 */ (__pyx_v_H.data + __pyx_t_42 * __pyx_v_H.strides[0]) ))))); + } - /* "sklearn/linear_model/cd_fast.pyx":475 - * dual_norm_XtA = linalg.norm(XtA, np.inf) + /* "sklearn/linear_model/cd_fast.pyx":602 + * for ii in range(n_features): + * tmp += w[ii] * H[ii] + * R_norm2 = y_norm2 + tmp - 2.0 * q_dot_w # <<<<<<<<<<<<<< * - * R_norm2 = y_norm2 + np.sum(w * H) - 2.0 * q_dot_w # <<<<<<<<<<<<<< - * w_norm = linalg.norm(w, 2) - * if (dual_norm_XtA > alpha): + * # w_norm2 = np.dot(w, w) */ - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_y_norm2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__sum); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(((PyObject *)__pyx_v_w), ((PyObject *)__pyx_v_H)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_28 = PyTuple_New(1); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_28)); - PyTuple_SET_ITEM(__pyx_t_28, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_28), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_28)); __pyx_t_28 = 0; - __pyx_t_28 = PyNumber_Add(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyFloat_FromDouble(2.0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_1, __pyx_v_q_dot_w); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Subtract(__pyx_t_28, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_28); __pyx_t_28 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_v_R_norm2); - __pyx_v_R_norm2 = __pyx_t_1; - __pyx_t_1 = 0; + __pyx_v_R_norm2 = ((__pyx_v_y_norm2 + __pyx_v_tmp) - (2.0 * __pyx_v_q_dot_w)); - /* "sklearn/linear_model/cd_fast.pyx":476 + /* "sklearn/linear_model/cd_fast.pyx":605 * - * R_norm2 = y_norm2 + np.sum(w * H) - 2.0 * q_dot_w - * w_norm = linalg.norm(w, 2) # <<<<<<<<<<<<<< - * if (dual_norm_XtA > alpha): - * const = alpha / dual_norm_XtA + * # w_norm2 = np.dot(w, w) + * w_norm2 = ddot(n_features, &w[0], 1, &w[0], 1) # <<<<<<<<<<<<<< + * + * if (dual_norm_XtA > alpha): */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__norm); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __Pyx_INCREF(__pyx_int_2); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_2); - __Pyx_GIVEREF(__pyx_int_2); - __pyx_t_28 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_v_w_norm); - __pyx_v_w_norm = __pyx_t_28; - __pyx_t_28 = 0; - - /* "sklearn/linear_model/cd_fast.pyx":477 - * R_norm2 = y_norm2 + np.sum(w * H) - 2.0 * q_dot_w - * w_norm = linalg.norm(w, 2) - * if (dual_norm_XtA > alpha): # <<<<<<<<<<<<<< - * const = alpha / dual_norm_XtA - * A_norm2 = R_norm2 * (const ** 2) - */ - __pyx_t_28 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 477; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __pyx_t_1 = PyObject_RichCompare(__pyx_v_dual_norm_XtA, __pyx_t_28, Py_GT); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 477; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_28); __pyx_t_28 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 477; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_6) { + __pyx_t_43 = 0; + __pyx_t_44 = 0; + __pyx_v_w_norm2 = cblas_ddot(__pyx_v_n_features, (&(*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_43 * __pyx_v_w.strides[0]) )))), 1, (&(*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_44 * __pyx_v_w.strides[0]) )))), 1); - /* "sklearn/linear_model/cd_fast.pyx":478 - * w_norm = linalg.norm(w, 2) - * if (dual_norm_XtA > alpha): - * const = alpha / dual_norm_XtA # <<<<<<<<<<<<<< - * A_norm2 = R_norm2 * (const ** 2) - * gap = 0.5 * (R_norm2 + A_norm2) - */ - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_28 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_v_dual_norm_XtA); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_v_const); - __pyx_v_const = __pyx_t_28; - __pyx_t_28 = 0; - - /* "sklearn/linear_model/cd_fast.pyx":479 - * if (dual_norm_XtA > alpha): - * const = alpha / dual_norm_XtA - * A_norm2 = R_norm2 * (const ** 2) # <<<<<<<<<<<<<< - * gap = 0.5 * (R_norm2 + A_norm2) - * else: + /* "sklearn/linear_model/cd_fast.pyx":607 + * w_norm2 = ddot(n_features, &w[0], 1, &w[0], 1) + * + * if (dual_norm_XtA > alpha): # <<<<<<<<<<<<<< + * const = alpha / dual_norm_XtA + * A_norm2 = R_norm2 * (const ** 2) */ - __pyx_t_28 = PyNumber_Power(__pyx_v_const, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __pyx_t_1 = PyNumber_Multiply(__pyx_v_R_norm2, __pyx_t_28); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_28); __pyx_t_28 = 0; - __Pyx_XDECREF(__pyx_v_A_norm2); - __pyx_v_A_norm2 = __pyx_t_1; - __pyx_t_1 = 0; + __pyx_t_15 = ((__pyx_v_dual_norm_XtA > __pyx_v_alpha) != 0); + if (__pyx_t_15) { - /* "sklearn/linear_model/cd_fast.pyx":480 - * const = alpha / dual_norm_XtA - * A_norm2 = R_norm2 * (const ** 2) - * gap = 0.5 * (R_norm2 + A_norm2) # <<<<<<<<<<<<<< - * else: - * const = 1.0 + /* "sklearn/linear_model/cd_fast.pyx":608 + * + * if (dual_norm_XtA > alpha): + * const = alpha / dual_norm_XtA # <<<<<<<<<<<<<< + * A_norm2 = R_norm2 * (const ** 2) + * gap = 0.5 * (R_norm2 + A_norm2) */ - __pyx_t_1 = PyFloat_FromDouble(0.5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_28 = PyNumber_Add(__pyx_v_R_norm2, __pyx_v_A_norm2); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __pyx_t_2 = PyNumber_Multiply(__pyx_t_1, __pyx_t_28); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_28); __pyx_t_28 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_gap = __pyx_t_5; - goto __pyx_L19; - } - /*else*/ { + __pyx_v_const = (__pyx_v_alpha / __pyx_v_dual_norm_XtA); - /* "sklearn/linear_model/cd_fast.pyx":482 - * gap = 0.5 * (R_norm2 + A_norm2) - * else: - * const = 1.0 # <<<<<<<<<<<<<< - * gap = R_norm2 - * + /* "sklearn/linear_model/cd_fast.pyx":609 + * if (dual_norm_XtA > alpha): + * const = alpha / dual_norm_XtA + * A_norm2 = R_norm2 * (const ** 2) # <<<<<<<<<<<<<< + * gap = 0.5 * (R_norm2 + A_norm2) + * else: */ - __pyx_t_2 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 482; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_v_const); - __pyx_v_const = __pyx_t_2; - __pyx_t_2 = 0; + __pyx_v_A_norm2 = (__pyx_v_R_norm2 * pow(__pyx_v_const, 2.0)); - /* "sklearn/linear_model/cd_fast.pyx":483 - * else: - * const = 1.0 - * gap = R_norm2 # <<<<<<<<<<<<<< - * - * gap += alpha * linalg.norm(w, 1) \ + /* "sklearn/linear_model/cd_fast.pyx":610 + * const = alpha / dual_norm_XtA + * A_norm2 = R_norm2 * (const ** 2) + * gap = 0.5 * (R_norm2 + A_norm2) # <<<<<<<<<<<<<< + * else: + * const = 1.0 */ - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_v_R_norm2); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_gap = __pyx_t_5; - } - __pyx_L19:; + __pyx_v_gap = (0.5 * (__pyx_v_R_norm2 + __pyx_v_A_norm2)); + goto __pyx_L29; + } + /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":485 - * gap = R_norm2 + /* "sklearn/linear_model/cd_fast.pyx":612 + * gap = 0.5 * (R_norm2 + A_norm2) + * else: + * const = 1.0 # <<<<<<<<<<<<<< + * gap = R_norm2 * - * gap += alpha * linalg.norm(w, 1) \ # <<<<<<<<<<<<<< - * - const * y_norm2 \ - * + const * q_dot_w + \ */ - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); + __pyx_v_const = 1.0; - /* "sklearn/linear_model/cd_fast.pyx":486 + /* "sklearn/linear_model/cd_fast.pyx":613 + * else: + * const = 1.0 + * gap = R_norm2 # <<<<<<<<<<<<<< * - * gap += alpha * linalg.norm(w, 1) \ - * - const * y_norm2 \ # <<<<<<<<<<<<<< - * + const * q_dot_w + \ - * 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) + * # The call to dasum is equivalent to the L1 norm of w */ - __pyx_t_28 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); + __pyx_v_gap = __pyx_v_R_norm2; + } + __pyx_L29:; - /* "sklearn/linear_model/cd_fast.pyx":485 - * gap = R_norm2 + /* "sklearn/linear_model/cd_fast.pyx":616 * - * gap += alpha * linalg.norm(w, 1) \ # <<<<<<<<<<<<<< - * - const * y_norm2 \ - * + const * q_dot_w + \ + * # The call to dasum is equivalent to the L1 norm of w + * gap += (alpha * dasum(n_features, &w[0], 1) - # <<<<<<<<<<<<<< + * const * y_norm2 + const * q_dot_w + + * 0.5 * beta * (1 + const ** 2) * w_norm2) */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__linalg); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__norm); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_1); - __Pyx_GIVEREF(__pyx_int_1); - __pyx_t_29 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_29); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_t_28, __pyx_t_29); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_28); __pyx_t_28 = 0; - __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; - - /* "sklearn/linear_model/cd_fast.pyx":487 - * gap += alpha * linalg.norm(w, 1) \ - * - const * y_norm2 \ - * + const * q_dot_w + \ # <<<<<<<<<<<<<< - * 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) - * - */ - __pyx_t_29 = PyFloat_FromDouble(__pyx_v_y_norm2); if (unlikely(!__pyx_t_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_29); - __pyx_t_28 = PyNumber_Multiply(__pyx_v_const, __pyx_t_29); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; - __pyx_t_29 = PyNumber_Subtract(__pyx_t_1, __pyx_t_28); if (unlikely(!__pyx_t_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_29); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_28); __pyx_t_28 = 0; - __pyx_t_28 = PyNumber_Multiply(__pyx_v_const, __pyx_v_q_dot_w); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __pyx_t_1 = PyNumber_Add(__pyx_t_29, __pyx_t_28); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; - __Pyx_DECREF(__pyx_t_28); __pyx_t_28 = 0; + __pyx_t_45 = 0; - /* "sklearn/linear_model/cd_fast.pyx":488 - * - const * y_norm2 \ - * + const * q_dot_w + \ - * 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":617 + * # The call to dasum is equivalent to the L1 norm of w + * gap += (alpha * dasum(n_features, &w[0], 1) - + * const * y_norm2 + const * q_dot_w + # <<<<<<<<<<<<<< + * 0.5 * beta * (1 + const ** 2) * w_norm2) * - * if gap < tol: */ - __pyx_t_28 = PyFloat_FromDouble((0.5 * __pyx_v_beta)); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __pyx_t_29 = PyNumber_Power(__pyx_v_const, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_29); - __pyx_t_3 = PyNumber_Add(__pyx_int_1, __pyx_t_29); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; - __pyx_t_29 = PyNumber_Multiply(__pyx_t_28, __pyx_t_3); if (unlikely(!__pyx_t_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_29); - __Pyx_DECREF(__pyx_t_28); __pyx_t_28 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Power(__pyx_v_w_norm, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_28 = PyNumber_Multiply(__pyx_t_29, __pyx_t_3); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __Pyx_DECREF(__pyx_t_29); __pyx_t_29 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Add(__pyx_t_1, __pyx_t_28); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_28); __pyx_t_28 = 0; - __pyx_t_28 = PyNumber_InPlaceAdd(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_28); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_28); __pyx_t_28 = 0; - __pyx_v_gap = __pyx_t_5; + __pyx_v_gap = (__pyx_v_gap + ((((__pyx_v_alpha * cblas_dasum(__pyx_v_n_features, (&(*((double *) ( /* dim=0 */ (__pyx_v_w.data + __pyx_t_45 * __pyx_v_w.strides[0]) )))), 1)) - (__pyx_v_const * __pyx_v_y_norm2)) + (__pyx_v_const * __pyx_v_q_dot_w)) + (((0.5 * __pyx_v_beta) * (1.0 + pow(__pyx_v_const, 2.0))) * __pyx_v_w_norm2))); - /* "sklearn/linear_model/cd_fast.pyx":490 - * 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) + /* "sklearn/linear_model/cd_fast.pyx":620 + * 0.5 * beta * (1 + const ** 2) * w_norm2) * - * if gap < tol: # <<<<<<<<<<<<<< - * # return if we reached desired tolerance - * break + * if gap < tol: # <<<<<<<<<<<<<< + * # return if we reached desired tolerance + * break */ - __pyx_t_6 = (__pyx_v_gap < __pyx_v_tol); - if (__pyx_t_6) { + __pyx_t_15 = ((__pyx_v_gap < __pyx_v_tol) != 0); + if (__pyx_t_15) { - /* "sklearn/linear_model/cd_fast.pyx":492 - * if gap < tol: - * # return if we reached desired tolerance - * break # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":622 + * if gap < tol: + * # return if we reached desired tolerance + * break # <<<<<<<<<<<<<< * - * return w, gap, tol + * return np.asarray(w), gap, tol, n_iter + 1 */ - goto __pyx_L8_break; - goto __pyx_L20; - } - __pyx_L20:; - goto __pyx_L17; - } - __pyx_L17:; + goto __pyx_L8_break; + } + goto __pyx_L20; + } + __pyx_L20:; + } + __pyx_L8_break:; + } + + /* "sklearn/linear_model/cd_fast.pyx":540 + * " results and is discouraged.") + * + * with nogil: # <<<<<<<<<<<<<< + * for n_iter in range(max_iter): + * w_max = 0.0 + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L6; + } + __pyx_L6:; + } } - __pyx_L8_break:; - /* "sklearn/linear_model/cd_fast.pyx":494 - * break + /* "sklearn/linear_model/cd_fast.pyx":624 + * break * - * return w, gap, tol # <<<<<<<<<<<<<< + * return np.asarray(w), gap, tol, n_iter + 1 # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_28 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_28); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_tol); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_28); - __Pyx_GIVEREF(__pyx_t_28); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_28 = 0; - __pyx_t_3 = 0; - __pyx_r = ((PyObject *)__pyx_t_2); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_asarray); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_w, 1, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_5); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_5, function); + } + } + if (!__pyx_t_2) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_7 = PyTuple_New(1+1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = NULL; + PyTuple_SET_ITEM(__pyx_t_7, 0+1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + } + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = PyFloat_FromDouble(__pyx_v_tol); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = __Pyx_PyInt_From_long((__pyx_v_n_iter + 1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_1 = 0; + __pyx_t_5 = 0; + __pyx_t_7 = 0; + __pyx_t_4 = 0; + __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/linear_model/cd_fast.pyx":489 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def enet_coordinate_descent_gram(double[:] w, double alpha, double beta, # <<<<<<<<<<<<<< + * double[:, :] Q, double[:] q, double[:] y, + * int max_iter, double tol, object rng, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_28); - __Pyx_XDECREF(__pyx_t_29); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_H); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_Q); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_q); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_w); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_y); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); + __PYX_XDEC_MEMVIEW(&__pyx_t_8, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_9, 1); __Pyx_AddTraceback("sklearn.linear_model.cd_fast.enet_coordinate_descent_gram", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; - goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_H); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_Q); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_q); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_w); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_y); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_H); - __Pyx_XDECREF(__pyx_v_q_dot_w); - __Pyx_XDECREF(__pyx_v_XtA); - __Pyx_XDECREF(__pyx_v_dual_norm_XtA); - __Pyx_XDECREF(__pyx_v_R_norm2); - __Pyx_XDECREF(__pyx_v_w_norm); - __Pyx_XDECREF(__pyx_v_const); - __Pyx_XDECREF(__pyx_v_A_norm2); + __PYX_XDEC_MEMVIEW(&__pyx_v_H, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_XtA, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_w, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Q, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_q, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_y, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/cd_fast.pyx":497 - * - * - * cdef double abs_max(int n, double* a): # <<<<<<<<<<<<<< - * """np.max(np.abs(a))""" - * cdef int i - */ - -static double __pyx_f_7sklearn_12linear_model_7cd_fast_abs_max(int __pyx_v_n, double *__pyx_v_a) { - int __pyx_v_i; - double __pyx_v_m; - double __pyx_v_d; - double __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - __Pyx_RefNannySetupContext("abs_max"); - - /* "sklearn/linear_model/cd_fast.pyx":500 - * """np.max(np.abs(a))""" - * cdef int i - * cdef double m = fabs(a[0]) # <<<<<<<<<<<<<< - * cdef double d - * for i in xrange(1, n): - */ - __pyx_v_m = fabs((__pyx_v_a[0])); - - /* "sklearn/linear_model/cd_fast.pyx":502 - * cdef double m = fabs(a[0]) - * cdef double d - * for i in xrange(1, n): # <<<<<<<<<<<<<< - * d = fabs(a[i]) - * if d > m: - */ - __pyx_t_1 = __pyx_v_n; - for (__pyx_t_2 = 1; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { - __pyx_v_i = __pyx_t_2; - - /* "sklearn/linear_model/cd_fast.pyx":503 - * cdef double d - * for i in xrange(1, n): - * d = fabs(a[i]) # <<<<<<<<<<<<<< - * if d > m: - * m = d - */ - __pyx_v_d = fabs((__pyx_v_a[__pyx_v_i])); - - /* "sklearn/linear_model/cd_fast.pyx":504 - * for i in xrange(1, n): - * d = fabs(a[i]) - * if d > m: # <<<<<<<<<<<<<< - * m = d - * return m - */ - __pyx_t_3 = (__pyx_v_d > __pyx_v_m); - if (__pyx_t_3) { - - /* "sklearn/linear_model/cd_fast.pyx":505 - * d = fabs(a[i]) - * if d > m: - * m = d # <<<<<<<<<<<<<< - * return m - * - */ - __pyx_v_m = __pyx_v_d; - goto __pyx_L5; - } - __pyx_L5:; - } - - /* "sklearn/linear_model/cd_fast.pyx":506 - * if d > m: - * m = d - * return m # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_m; - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/linear_model/cd_fast.pyx":509 - * - * - * cdef double diff_abs_max(int n, double* a, double* b): # <<<<<<<<<<<<<< - * """np.max(np.abs(a - b))""" - * cdef int i - */ - -static double __pyx_f_7sklearn_12linear_model_7cd_fast_diff_abs_max(int __pyx_v_n, double *__pyx_v_a, double *__pyx_v_b) { - int __pyx_v_i; - double __pyx_v_m; - double __pyx_v_d; - double __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - __Pyx_RefNannySetupContext("diff_abs_max"); - - /* "sklearn/linear_model/cd_fast.pyx":512 - * """np.max(np.abs(a - b))""" - * cdef int i - * cdef double m = fabs(a[0] - b[0]) # <<<<<<<<<<<<<< - * cdef double d - * for i in xrange(1, n): - */ - __pyx_v_m = fabs(((__pyx_v_a[0]) - (__pyx_v_b[0]))); - - /* "sklearn/linear_model/cd_fast.pyx":514 - * cdef double m = fabs(a[0] - b[0]) - * cdef double d - * for i in xrange(1, n): # <<<<<<<<<<<<<< - * d = fabs(a[i] - b[i]) - * if d > m: - */ - __pyx_t_1 = __pyx_v_n; - for (__pyx_t_2 = 1; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { - __pyx_v_i = __pyx_t_2; - - /* "sklearn/linear_model/cd_fast.pyx":515 - * cdef double d - * for i in xrange(1, n): - * d = fabs(a[i] - b[i]) # <<<<<<<<<<<<<< - * if d > m: - * m = d - */ - __pyx_v_d = fabs(((__pyx_v_a[__pyx_v_i]) - (__pyx_v_b[__pyx_v_i]))); - - /* "sklearn/linear_model/cd_fast.pyx":516 - * for i in xrange(1, n): - * d = fabs(a[i] - b[i]) - * if d > m: # <<<<<<<<<<<<<< - * m = d - * return m - */ - __pyx_t_3 = (__pyx_v_d > __pyx_v_m); - if (__pyx_t_3) { - - /* "sklearn/linear_model/cd_fast.pyx":517 - * d = fabs(a[i] - b[i]) - * if d > m: - * m = d # <<<<<<<<<<<<<< - * return m - * - */ - __pyx_v_m = __pyx_v_d; - goto __pyx_L5; - } - __pyx_L5:; - } - - /* "sklearn/linear_model/cd_fast.pyx":518 - * if d > m: - * m = d - * return m # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_m; - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/linear_model/cd_fast.pyx":524 +/* "sklearn/linear_model/cd_fast.pyx":630 * @cython.wraparound(False) * @cython.cdivision(True) - * def enet_coordinate_descent_multi_task(np.ndarray[DOUBLE, ndim=2, mode='fortran'] W, # <<<<<<<<<<<<<< - * double l1_reg, double l2_reg, - * np.ndarray[DOUBLE, ndim=2, mode='fortran'] X, + * def enet_coordinate_descent_multi_task(double[::1, :] W, double l1_reg, # <<<<<<<<<<<<<< + * double l2_reg, double[::1, :] X, + * double[:, :] Y, int max_iter, */ -static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_multi_task(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_multi_task[] = "Cython version of the coordinate descent algorithm\n for Elastic-Net mult-task regression\n\n We minimize\n\n 1 norm(y - X w, 2)^2 + l1_reg ||w||_21 + l2_reg norm(w, 2)^2\n - ----\n 2 2\n\n "; -static PyMethodDef __pyx_mdef_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_multi_task = {__Pyx_NAMESTR("enet_coordinate_descent_multi_task"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_multi_task, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_multi_task)}; -static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_multi_task(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_W = 0; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_7cd_fast_7enet_coordinate_descent_multi_task(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_12linear_model_7cd_fast_6enet_coordinate_descent_multi_task[] = "Cython version of the coordinate descent algorithm\n for Elastic-Net mult-task regression\n\n We minimize\n\n 1 norm(y - X w, 2)^2 + l1_reg ||w||_21 + l2_reg norm(w, 2)^2\n - ----\n 2 2\n\n "; +static PyMethodDef __pyx_mdef_7sklearn_12linear_model_7cd_fast_7enet_coordinate_descent_multi_task = {"enet_coordinate_descent_multi_task", (PyCFunction)__pyx_pw_7sklearn_12linear_model_7cd_fast_7enet_coordinate_descent_multi_task, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_12linear_model_7cd_fast_6enet_coordinate_descent_multi_task}; +static PyObject *__pyx_pw_7sklearn_12linear_model_7cd_fast_7enet_coordinate_descent_multi_task(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __Pyx_memviewslice __pyx_v_W = { 0, 0, { 0 }, { 0 }, { 0 } }; double __pyx_v_l1_reg; double __pyx_v_l2_reg; - PyArrayObject *__pyx_v_X = 0; - PyArrayObject *__pyx_v_Y = 0; + __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_max_iter; double __pyx_v_tol; - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - unsigned int __pyx_v_n_tasks; - PyArrayObject *__pyx_v_norm_cols_X = 0; - PyArrayObject *__pyx_v_R = 0; - PyArrayObject *__pyx_v_tmp = 0; - PyArrayObject *__pyx_v_w_ii = 0; - double __pyx_v_d_w_max; - double __pyx_v_w_max; - double __pyx_v_d_w_ii; - double __pyx_v_nn; - double __pyx_v_W_ii_abs_max; - double __pyx_v_gap; - double __pyx_v_d_w_tol; - unsigned int __pyx_v_ii; - unsigned int __pyx_v_n_iter; - PyObject *__pyx_v_XtA = NULL; - PyObject *__pyx_v_dual_norm_XtA = NULL; - double __pyx_v_R_norm; - double __pyx_v_w_norm; - PyObject *__pyx_v_const = NULL; - PyObject *__pyx_v_A_norm = NULL; - Py_buffer __pyx_bstruct_norm_cols_X; - Py_ssize_t __pyx_bstride_0_norm_cols_X = 0; - Py_ssize_t __pyx_bshape_0_norm_cols_X = 0; - Py_buffer __pyx_bstruct_tmp; - Py_ssize_t __pyx_bstride_0_tmp = 0; - Py_ssize_t __pyx_bshape_0_tmp = 0; - Py_buffer __pyx_bstruct_w_ii; - Py_ssize_t __pyx_bstride_0_w_ii = 0; - Py_ssize_t __pyx_bshape_0_w_ii = 0; - Py_buffer __pyx_bstruct_R; - Py_ssize_t __pyx_bstride_0_R = 0; - Py_ssize_t __pyx_bstride_1_R = 0; - Py_ssize_t __pyx_bshape_0_R = 0; - Py_ssize_t __pyx_bshape_1_R = 0; - Py_buffer __pyx_bstruct_W; - Py_ssize_t __pyx_bstride_0_W = 0; - Py_ssize_t __pyx_bstride_1_W = 0; - Py_ssize_t __pyx_bshape_0_W = 0; - Py_ssize_t __pyx_bshape_1_W = 0; - Py_buffer __pyx_bstruct_Y; - Py_ssize_t __pyx_bstride_0_Y = 0; - Py_ssize_t __pyx_bstride_1_Y = 0; - Py_ssize_t __pyx_bshape_0_Y = 0; - Py_ssize_t __pyx_bshape_1_Y = 0; - Py_buffer __pyx_bstruct_X; - Py_ssize_t __pyx_bstride_0_X = 0; - Py_ssize_t __pyx_bstride_1_X = 0; - Py_ssize_t __pyx_bshape_0_X = 0; - Py_ssize_t __pyx_bshape_1_X = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyArrayObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyArrayObject *__pyx_t_7 = NULL; - PyArrayObject *__pyx_t_8 = NULL; - int __pyx_t_9; - PyArrayObject *__pyx_t_10 = NULL; - int __pyx_t_11; - PyObject *__pyx_t_12 = NULL; - PyObject *__pyx_t_13 = NULL; - PyObject *__pyx_t_14 = NULL; - unsigned int __pyx_t_15; - unsigned int __pyx_t_16; - unsigned int __pyx_t_17; - unsigned int __pyx_t_18; - unsigned int __pyx_t_19; - int __pyx_t_20; - int __pyx_t_21; - int __pyx_t_22; - PyObject *__pyx_t_23 = NULL; - double __pyx_t_24; - PyObject *__pyx_t_25 = NULL; + PyObject *__pyx_v_rng = 0; + int __pyx_v_random; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__W,&__pyx_n_s__l1_reg,&__pyx_n_s__l2_reg,&__pyx_n_s__X,&__pyx_n_s__Y,&__pyx_n_s__max_iter,&__pyx_n_s__tol,0}; - __Pyx_RefNannySetupContext("enet_coordinate_descent_multi_task"); - __pyx_self = __pyx_self; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("enet_coordinate_descent_multi_task (wrapper)", 0); { - PyObject* values[7] = {0,0,0,0,0,0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_W,&__pyx_n_s_l1_reg,&__pyx_n_s_l2_reg,&__pyx_n_s_X,&__pyx_n_s_Y,&__pyx_n_s_max_iter,&__pyx_n_s_tol,&__pyx_n_s_rng,&__pyx_n_s_random,0}; + PyObject* values[9] = {0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); + case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); @@ -6122,1101 +6714,1454 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_4enet_coordinate_desc default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__W); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_W)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__l1_reg); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_l1_reg)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 1, 7, 7, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 0, 8, 9, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__l2_reg); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_l2_reg)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 1, 7, 7, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 0, 8, 9, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 1, 7, 7, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 0, 8, 9, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__Y); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 1, 7, 7, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 0, 8, 9, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__max_iter); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_iter)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 1, 7, 7, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 0, 8, 9, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__tol); - if (likely(values[6])) kw_args--; + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tol)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 0, 8, 9, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 7: + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_rng)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 1, 7, 7, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 0, 8, 9, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 8: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random); + if (value) { values[8] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "enet_coordinate_descent_multi_task") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "enet_coordinate_descent_multi_task") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - } else if (PyTuple_GET_SIZE(__pyx_args) != 7) { - goto __pyx_L5_argtuple_error; } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - } - __pyx_v_W = ((PyArrayObject *)values[0]); - __pyx_v_l1_reg = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_l1_reg == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_l2_reg = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_l2_reg == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_X = ((PyArrayObject *)values[3]); - __pyx_v_Y = ((PyArrayObject *)values[4]); - __pyx_v_max_iter = __Pyx_PyInt_AsInt(values[5]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_tol = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 1, 7, 7, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); + case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_W = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(values[0]); if (unlikely(!__pyx_v_W.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_l1_reg = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_l1_reg == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_l2_reg = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_l2_reg == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(values[3]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[4]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_max_iter = __Pyx_PyInt_As_int(values[5]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_tol = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 633; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_rng = values[7]; + if (values[8]) { + __pyx_v_random = __Pyx_PyObject_IsTrue(values[8]); if (unlikely((__pyx_v_random == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_random = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("enet_coordinate_descent_multi_task", 0, 8, 9, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.linear_model.cd_fast.enet_coordinate_descent_multi_task", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_norm_cols_X.buf = NULL; - __pyx_bstruct_R.buf = NULL; - __pyx_bstruct_tmp.buf = NULL; - __pyx_bstruct_w_ii.buf = NULL; - __pyx_bstruct_W.buf = NULL; - __pyx_bstruct_X.buf = NULL; - __pyx_bstruct_Y.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_W), __pyx_ptype_5numpy_ndarray, 1, "W", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_W, (PyObject*)__pyx_v_W, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_W = __pyx_bstruct_W.strides[0]; __pyx_bstride_1_W = __pyx_bstruct_W.strides[1]; - __pyx_bshape_0_W = __pyx_bstruct_W.shape[0]; __pyx_bshape_1_W = __pyx_bstruct_W.shape[1]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_X = __pyx_bstruct_X.strides[0]; __pyx_bstride_1_X = __pyx_bstruct_X.strides[1]; - __pyx_bshape_0_X = __pyx_bstruct_X.shape[0]; __pyx_bshape_1_X = __pyx_bstruct_X.shape[1]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_Y, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_Y = __pyx_bstruct_Y.strides[0]; __pyx_bstride_1_Y = __pyx_bstruct_Y.strides[1]; - __pyx_bshape_0_Y = __pyx_bstruct_Y.shape[0]; __pyx_bshape_1_Y = __pyx_bstruct_Y.shape[1]; + __pyx_r = __pyx_pf_7sklearn_12linear_model_7cd_fast_6enet_coordinate_descent_multi_task(__pyx_self, __pyx_v_W, __pyx_v_l1_reg, __pyx_v_l2_reg, __pyx_v_X, __pyx_v_Y, __pyx_v_max_iter, __pyx_v_tol, __pyx_v_rng, __pyx_v_random); - /* "sklearn/linear_model/cd_fast.pyx":540 + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_6enet_coordinate_descent_multi_task(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_W, double __pyx_v_l1_reg, double __pyx_v_l2_reg, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, int __pyx_v_max_iter, double __pyx_v_tol, PyObject *__pyx_v_rng, int __pyx_v_random) { + unsigned int __pyx_v_n_samples; + unsigned int __pyx_v_n_features; + unsigned int __pyx_v_n_tasks; + __Pyx_memviewslice __pyx_v_XtA = { 0, 0, { 0 }, { 0 }, { 0 } }; + double __pyx_v_XtA_axis1norm; + double __pyx_v_dual_norm_XtA; + __Pyx_memviewslice __pyx_v_R = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_norm_cols_X = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_tmp = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_w_ii = { 0, 0, { 0 }, { 0 }, { 0 } }; + double __pyx_v_d_w_max; + double __pyx_v_w_max; + double __pyx_v_d_w_ii; + double __pyx_v_nn; + double __pyx_v_W_ii_abs_max; + double __pyx_v_gap; + double __pyx_v_d_w_tol; + double __pyx_v_ry_sum; + double __pyx_v_l21_norm; + unsigned int __pyx_v_ii; + unsigned int __pyx_v_jj; + unsigned int __pyx_v_n_iter; + unsigned int __pyx_v_f_iter; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_v_rand_r_state_seed; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t *__pyx_v_rand_r_state; + double *__pyx_v_X_ptr; + double *__pyx_v_W_ptr; + double *__pyx_v_Y_ptr; + double *__pyx_v_wii_ptr; + double __pyx_v_R_norm; + double __pyx_v_w_norm; + double __pyx_v_const; + double __pyx_v_A_norm; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_8 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_9 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_10 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_11; + __pyx_t_7sklearn_12linear_model_7cd_fast_UINT32_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + Py_ssize_t __pyx_t_14; + Py_ssize_t __pyx_t_15; + Py_ssize_t __pyx_t_16; + Py_ssize_t __pyx_t_17; + Py_ssize_t __pyx_t_18; + int __pyx_t_19; + unsigned int __pyx_t_20; + unsigned int __pyx_t_21; + unsigned int __pyx_t_22; + unsigned int __pyx_t_23; + unsigned int __pyx_t_24; + unsigned int __pyx_t_25; + unsigned int __pyx_t_26; + unsigned int __pyx_t_27; + unsigned int __pyx_t_28; + unsigned int __pyx_t_29; + unsigned int __pyx_t_30; + int __pyx_t_31; + Py_ssize_t __pyx_t_32; + Py_ssize_t __pyx_t_33; + Py_ssize_t __pyx_t_34; + Py_ssize_t __pyx_t_35; + Py_ssize_t __pyx_t_36; + Py_ssize_t __pyx_t_37; + Py_ssize_t __pyx_t_38; + unsigned int __pyx_t_39; + Py_ssize_t __pyx_t_40; + Py_ssize_t __pyx_t_41; + int __pyx_t_42; + unsigned int __pyx_t_43; + unsigned int __pyx_t_44; + Py_ssize_t __pyx_t_45; + Py_ssize_t __pyx_t_46; + unsigned int __pyx_t_47; + unsigned int __pyx_t_48; + unsigned int __pyx_t_49; + unsigned int __pyx_t_50; + Py_ssize_t __pyx_t_51; + Py_ssize_t __pyx_t_52; + Py_ssize_t __pyx_t_53; + Py_ssize_t __pyx_t_54; + unsigned int __pyx_t_55; + unsigned int __pyx_t_56; + unsigned int __pyx_t_57; + unsigned int __pyx_t_58; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("enet_coordinate_descent_multi_task", 0); + + /* "sklearn/linear_model/cd_fast.pyx":646 * """ * # get the data information into easy vars * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< * cdef unsigned int n_features = X.shape[1] * cdef unsigned int n_tasks = Y.shape[1] */ - __pyx_v_n_samples = (__pyx_v_X->dimensions[0]); + __pyx_v_n_samples = (__pyx_v_X.shape[0]); - /* "sklearn/linear_model/cd_fast.pyx":541 + /* "sklearn/linear_model/cd_fast.pyx":647 * # get the data information into easy vars * cdef unsigned int n_samples = X.shape[0] * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< * cdef unsigned int n_tasks = Y.shape[1] * */ - __pyx_v_n_features = (__pyx_v_X->dimensions[1]); + __pyx_v_n_features = (__pyx_v_X.shape[1]); - /* "sklearn/linear_model/cd_fast.pyx":542 + /* "sklearn/linear_model/cd_fast.pyx":648 * cdef unsigned int n_samples = X.shape[0] * cdef unsigned int n_features = X.shape[1] * cdef unsigned int n_tasks = Y.shape[1] # <<<<<<<<<<<<<< * - * # compute norms of the columns of X + * # to store XtA */ - __pyx_v_n_tasks = (__pyx_v_Y->dimensions[1]); + __pyx_v_n_tasks = (__pyx_v_Y.shape[1]); - /* "sklearn/linear_model/cd_fast.pyx":545 - * - * # compute norms of the columns of X - * cdef np.ndarray[DOUBLE, ndim=1] norm_cols_X = (X ** 2).sum(axis=0) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":651 * - * # initial value of the residuals + * # to store XtA + * cdef double[:, ::1] XtA = np.zeros((n_features, n_tasks)) # <<<<<<<<<<<<<< + * cdef double XtA_axis1norm + * cdef double dual_norm_XtA */ - __pyx_t_1 = PyNumber_Power(((PyObject *)__pyx_v_X), __pyx_int_2, Py_None); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__sum); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 651; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__axis), __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 651; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = ((PyArrayObject *)__pyx_t_3); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_norm_cols_X, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_norm_cols_X = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_norm_cols_X.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_norm_cols_X = __pyx_bstruct_norm_cols_X.strides[0]; - __pyx_bshape_0_norm_cols_X = __pyx_bstruct_norm_cols_X.shape[0]; + __pyx_t_2 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_features); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 651; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_tasks); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 651; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 651; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); } } - __pyx_t_4 = 0; - __pyx_v_norm_cols_X = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; + if (!__pyx_t_4) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 651; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_2 = PyTuple_New(1+1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 651; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + PyTuple_SET_ITEM(__pyx_t_2, 0+1, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 651; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(__pyx_t_1); + if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 651; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_XtA = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; - /* "sklearn/linear_model/cd_fast.pyx":550 - * cdef np.ndarray[DOUBLE, ndim=2, mode='c'] R + /* "sklearn/linear_model/cd_fast.pyx":656 * - * cdef np.ndarray[DOUBLE, ndim=1, mode='c'] tmp = np.zeros(n_tasks, dtype=np.float) # <<<<<<<<<<<<<< - * cdef np.ndarray[DOUBLE, ndim=1] w_ii = np.zeros(n_tasks, dtype=np.float) - * cdef double d_w_max + * # initial value of the residuals + * cdef double[:, ::1] R = np.zeros((n_samples, n_tasks)) # <<<<<<<<<<<<<< + * + * cdef double[:] norm_cols_X = np.zeros(n_features) */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyLong_FromUnsignedLong(__pyx_v_n_tasks); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_samples); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __pyx_t_5 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_tasks); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__float); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = 0; + __pyx_t_5 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (!__pyx_t_5) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_3 = PyTuple_New(1+1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; + PyTuple_SET_ITEM(__pyx_t_3, 0+1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_7 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(__pyx_t_1); + if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = ((PyArrayObject *)__pyx_t_6); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_tmp, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - __pyx_v_tmp = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_tmp.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_tmp = __pyx_bstruct_tmp.strides[0]; - __pyx_bshape_0_tmp = __pyx_bstruct_tmp.shape[0]; + __pyx_v_R = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; + + /* "sklearn/linear_model/cd_fast.pyx":658 + * cdef double[:, ::1] R = np.zeros((n_samples, n_tasks)) + * + * cdef double[:] norm_cols_X = np.zeros(n_features) # <<<<<<<<<<<<<< + * cdef double[::1] tmp = np.zeros(n_tasks, dtype=np.float) + * cdef double[:] w_ii = np.zeros(n_tasks, dtype=np.float) + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 658; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 658; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_features); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 658; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); } } - __pyx_t_7 = 0; - __pyx_v_tmp = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; + if (!__pyx_t_4) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 658; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 658; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 658; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_8 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_t_1); + if (unlikely(!__pyx_t_8.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 658; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_norm_cols_X = __pyx_t_8; + __pyx_t_8.memview = NULL; + __pyx_t_8.data = NULL; - /* "sklearn/linear_model/cd_fast.pyx":551 + /* "sklearn/linear_model/cd_fast.pyx":659 * - * cdef np.ndarray[DOUBLE, ndim=1, mode='c'] tmp = np.zeros(n_tasks, dtype=np.float) - * cdef np.ndarray[DOUBLE, ndim=1] w_ii = np.zeros(n_tasks, dtype=np.float) # <<<<<<<<<<<<<< + * cdef double[:] norm_cols_X = np.zeros(n_features) + * cdef double[::1] tmp = np.zeros(n_tasks, dtype=np.float) # <<<<<<<<<<<<<< + * cdef double[:] w_ii = np.zeros(n_tasks, dtype=np.float) * cdef double d_w_max - * cdef double w_max */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyLong_FromUnsignedLong(__pyx_v_n_tasks); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_6); - __pyx_t_6 = 0; - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_tasks); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__float); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyEval_CallObjectWithKeywords(__pyx_t_3, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_9 = __Pyx_PyObject_to_MemoryviewSlice_dc_double(__pyx_t_4); + if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_tmp = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "sklearn/linear_model/cd_fast.pyx":660 + * cdef double[:] norm_cols_X = np.zeros(n_features) + * cdef double[::1] tmp = np.zeros(n_tasks, dtype=np.float) + * cdef double[:] w_ii = np.zeros(n_tasks, dtype=np.float) # <<<<<<<<<<<<<< + * cdef double d_w_max + * cdef double w_max + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_tasks); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_float); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_8 = ((PyArrayObject *)__pyx_t_5); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_w_ii, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_w_ii = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_w_ii.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_w_ii = __pyx_bstruct_w_ii.strides[0]; - __pyx_bshape_0_w_ii = __pyx_bstruct_w_ii.shape[0]; - } - } - __pyx_t_8 = 0; - __pyx_v_w_ii = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_10 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_t_2); + if (unlikely(!__pyx_t_10.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_w_ii = __pyx_t_10; + __pyx_t_10.memview = NULL; + __pyx_t_10.data = NULL; - /* "sklearn/linear_model/cd_fast.pyx":557 + /* "sklearn/linear_model/cd_fast.pyx":666 * cdef double nn * cdef double W_ii_abs_max * cdef double gap = tol + 1.0 # <<<<<<<<<<<<<< * cdef double d_w_tol = tol - * cdef unsigned int ii + * cdef double ry_sum */ __pyx_v_gap = (__pyx_v_tol + 1.0); - /* "sklearn/linear_model/cd_fast.pyx":558 + /* "sklearn/linear_model/cd_fast.pyx":667 * cdef double W_ii_abs_max * cdef double gap = tol + 1.0 * cdef double d_w_tol = tol # <<<<<<<<<<<<<< - * cdef unsigned int ii - * cdef unsigned int n_iter + * cdef double ry_sum + * cdef double l21_norm */ __pyx_v_d_w_tol = __pyx_v_tol; - /* "sklearn/linear_model/cd_fast.pyx":562 + /* "sklearn/linear_model/cd_fast.pyx":674 * cdef unsigned int n_iter + * cdef unsigned int f_iter + * cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) # <<<<<<<<<<<<<< + * cdef UINT32_t* rand_r_state = &rand_r_state_seed + * + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_rng, __pyx_n_s_randint); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 674; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_e_7sklearn_12linear_model_7cd_fast_RAND_R_MAX); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 674; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = NULL; + __pyx_t_11 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + __pyx_t_11 = 1; + } + } + __pyx_t_3 = PyTuple_New(2+__pyx_t_11); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 674; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (__pyx_t_1) { + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = NULL; + } + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 0+__pyx_t_11, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1+__pyx_t_11, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 674; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_12 = __Pyx_PyInt_As_npy_uint32(__pyx_t_2); if (unlikely((__pyx_t_12 == (npy_uint32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 674; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_rand_r_state_seed = __pyx_t_12; + + /* "sklearn/linear_model/cd_fast.pyx":675 + * cdef unsigned int f_iter + * cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + * cdef UINT32_t* rand_r_state = &rand_r_state_seed # <<<<<<<<<<<<<< + * + * cdef double* X_ptr = &X[0, 0] + */ + __pyx_v_rand_r_state = (&__pyx_v_rand_r_state_seed); + + /* "sklearn/linear_model/cd_fast.pyx":677 + * cdef UINT32_t* rand_r_state = &rand_r_state_seed + * + * cdef double* X_ptr = &X[0, 0] # <<<<<<<<<<<<<< + * cdef double* W_ptr = &W[0, 0] + * cdef double* Y_ptr = &Y[0, 0] + */ + __pyx_t_11 = 0; + __pyx_t_13 = 0; + __pyx_v_X_ptr = (&(*((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_X.data) + __pyx_t_11)) ) + __pyx_t_13 * __pyx_v_X.strides[1]) )))); + + /* "sklearn/linear_model/cd_fast.pyx":678 + * + * cdef double* X_ptr = &X[0, 0] + * cdef double* W_ptr = &W[0, 0] # <<<<<<<<<<<<<< + * cdef double* Y_ptr = &Y[0, 0] + * cdef double* wii_ptr = &w_ii[0] + */ + __pyx_t_14 = 0; + __pyx_t_15 = 0; + __pyx_v_W_ptr = (&(*((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_W.data) + __pyx_t_14)) ) + __pyx_t_15 * __pyx_v_W.strides[1]) )))); + + /* "sklearn/linear_model/cd_fast.pyx":679 + * cdef double* X_ptr = &X[0, 0] + * cdef double* W_ptr = &W[0, 0] + * cdef double* Y_ptr = &Y[0, 0] # <<<<<<<<<<<<<< + * cdef double* wii_ptr = &w_ii[0] + * + */ + __pyx_t_16 = 0; + __pyx_t_17 = 0; + __pyx_v_Y_ptr = (&(*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_16 * __pyx_v_Y.strides[0]) ) + __pyx_t_17 * __pyx_v_Y.strides[1]) )))); + + /* "sklearn/linear_model/cd_fast.pyx":680 + * cdef double* W_ptr = &W[0, 0] + * cdef double* Y_ptr = &Y[0, 0] + * cdef double* wii_ptr = &w_ii[0] # <<<<<<<<<<<<<< + * + * if l1_reg == 0: + */ + __pyx_t_18 = 0; + __pyx_v_wii_ptr = (&(*((double *) ( /* dim=0 */ (__pyx_v_w_ii.data + __pyx_t_18 * __pyx_v_w_ii.strides[0]) )))); + + /* "sklearn/linear_model/cd_fast.pyx":682 + * cdef double* wii_ptr = &w_ii[0] * * if l1_reg == 0: # <<<<<<<<<<<<<< * warnings.warn("Coordinate descent with l1_reg=0 may lead to unexpected" * " results and is discouraged.") */ - __pyx_t_9 = (__pyx_v_l1_reg == 0.0); - if (__pyx_t_9) { + __pyx_t_19 = ((__pyx_v_l1_reg == 0.0) != 0); + if (__pyx_t_19) { - /* "sklearn/linear_model/cd_fast.pyx":563 + /* "sklearn/linear_model/cd_fast.pyx":683 * * if l1_reg == 0: * warnings.warn("Coordinate descent with l1_reg=0 may lead to unexpected" # <<<<<<<<<<<<<< * " results and is discouraged.") * */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__warnings); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__warn); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_k_tuple_7), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L6; + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_warnings); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 683; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_warn); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 683; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 683; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L3; } - __pyx_L6:; + __pyx_L3:; - /* "sklearn/linear_model/cd_fast.pyx":566 + /* "sklearn/linear_model/cd_fast.pyx":686 * " results and is discouraged.") * - * R = Y - np.dot(X, W.T) # <<<<<<<<<<<<<< - * R = np.asarray(R, order='C') - * + * with nogil: # <<<<<<<<<<<<<< + * # norm_cols_X = (np.asarray(X) ** 2).sum(axis=0) + * for ii in range(n_features): */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__dot); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_GetAttr(((PyObject *)__pyx_v_W), __pyx_n_s__T); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_X)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_X)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_X)); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyNumber_Subtract(((PyObject *)__pyx_v_Y), __pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = ((PyArrayObject *)__pyx_t_2); { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_R); - __pyx_t_11 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_R, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_11 < 0)) { - PyErr_Fetch(&__pyx_t_12, &__pyx_t_13, &__pyx_t_14); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_R, (PyObject*)__pyx_v_R, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_13); Py_XDECREF(__pyx_t_14); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_12, __pyx_t_13, __pyx_t_14); - } - } - __pyx_bstride_0_R = __pyx_bstruct_R.strides[0]; __pyx_bstride_1_R = __pyx_bstruct_R.strides[1]; - __pyx_bshape_0_R = __pyx_bstruct_R.shape[0]; __pyx_bshape_1_R = __pyx_bstruct_R.shape[1]; - if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_10 = 0; - __pyx_v_R = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/linear_model/cd_fast.pyx":688 + * with nogil: + * # norm_cols_X = (np.asarray(X) ** 2).sum(axis=0) + * for ii in range(n_features): # <<<<<<<<<<<<<< + * for jj in range(n_samples): + * norm_cols_X[ii] += X[jj, ii] ** 2 + */ + __pyx_t_20 = __pyx_v_n_features; + for (__pyx_t_21 = 0; __pyx_t_21 < __pyx_t_20; __pyx_t_21+=1) { + __pyx_v_ii = __pyx_t_21; + + /* "sklearn/linear_model/cd_fast.pyx":689 + * # norm_cols_X = (np.asarray(X) ** 2).sum(axis=0) + * for ii in range(n_features): + * for jj in range(n_samples): # <<<<<<<<<<<<<< + * norm_cols_X[ii] += X[jj, ii] ** 2 + * + */ + __pyx_t_22 = __pyx_v_n_samples; + for (__pyx_t_23 = 0; __pyx_t_23 < __pyx_t_22; __pyx_t_23+=1) { + __pyx_v_jj = __pyx_t_23; + + /* "sklearn/linear_model/cd_fast.pyx":690 + * for ii in range(n_features): + * for jj in range(n_samples): + * norm_cols_X[ii] += X[jj, ii] ** 2 # <<<<<<<<<<<<<< + * + * # R = Y - np.dot(X, W.T) + */ + __pyx_t_24 = __pyx_v_jj; + __pyx_t_25 = __pyx_v_ii; + __pyx_t_26 = __pyx_v_ii; + *((double *) ( /* dim=0 */ (__pyx_v_norm_cols_X.data + __pyx_t_26 * __pyx_v_norm_cols_X.strides[0]) )) += pow((*((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_X.data) + __pyx_t_24)) ) + __pyx_t_25 * __pyx_v_X.strides[1]) ))), 2.0); + } + } - /* "sklearn/linear_model/cd_fast.pyx":567 + /* "sklearn/linear_model/cd_fast.pyx":693 * - * R = Y - np.dot(X, W.T) - * R = np.asarray(R, order='C') # <<<<<<<<<<<<<< + * # R = Y - np.dot(X, W.T) + * for ii in range(n_samples): # <<<<<<<<<<<<<< + * for jj in range(n_tasks): + * R[ii, jj] = Y[ii, jj] - ( + */ + __pyx_t_20 = __pyx_v_n_samples; + for (__pyx_t_21 = 0; __pyx_t_21 < __pyx_t_20; __pyx_t_21+=1) { + __pyx_v_ii = __pyx_t_21; + + /* "sklearn/linear_model/cd_fast.pyx":694 + * # R = Y - np.dot(X, W.T) + * for ii in range(n_samples): + * for jj in range(n_tasks): # <<<<<<<<<<<<<< + * R[ii, jj] = Y[ii, jj] - ( + * ddot(n_features, X_ptr + ii, n_samples, W_ptr + jj, n_tasks) + */ + __pyx_t_22 = __pyx_v_n_tasks; + for (__pyx_t_23 = 0; __pyx_t_23 < __pyx_t_22; __pyx_t_23+=1) { + __pyx_v_jj = __pyx_t_23; + + /* "sklearn/linear_model/cd_fast.pyx":695 + * for ii in range(n_samples): + * for jj in range(n_tasks): + * R[ii, jj] = Y[ii, jj] - ( # <<<<<<<<<<<<<< + * ddot(n_features, X_ptr + ii, n_samples, W_ptr + jj, n_tasks) + * ) + */ + __pyx_t_27 = __pyx_v_ii; + __pyx_t_28 = __pyx_v_jj; + + /* "sklearn/linear_model/cd_fast.pyx":696 + * for jj in range(n_tasks): + * R[ii, jj] = Y[ii, jj] - ( + * ddot(n_features, X_ptr + ii, n_samples, W_ptr + jj, n_tasks) # <<<<<<<<<<<<<< + * ) * - * # tol = tol * linalg.norm(Y, ord='fro') ** 2 */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 567; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__asarray); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 567; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 567; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_R)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_R)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_R)); - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 567; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 567; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = PyEval_CallObjectWithKeywords(__pyx_t_5, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 567; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 567; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = ((PyArrayObject *)__pyx_t_3); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_R); - __pyx_t_11 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_R, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_11 < 0)) { - PyErr_Fetch(&__pyx_t_14, &__pyx_t_13, &__pyx_t_12); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_R, (PyObject*)__pyx_v_R, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_14); Py_XDECREF(__pyx_t_13); Py_XDECREF(__pyx_t_12); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_14, __pyx_t_13, __pyx_t_12); - } - } - __pyx_bstride_0_R = __pyx_bstruct_R.strides[0]; __pyx_bstride_1_R = __pyx_bstruct_R.strides[1]; - __pyx_bshape_0_R = __pyx_bstruct_R.shape[0]; __pyx_bshape_1_R = __pyx_bstruct_R.shape[1]; - if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 567; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_10 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_R)); - __pyx_v_R = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; + __pyx_t_29 = __pyx_v_ii; + __pyx_t_30 = __pyx_v_jj; + *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_29 * __pyx_v_R.strides[0]) )) + __pyx_t_30)) )) = ((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_27 * __pyx_v_Y.strides[0]) ) + __pyx_t_28 * __pyx_v_Y.strides[1]) ))) - cblas_ddot(__pyx_v_n_features, (__pyx_v_X_ptr + __pyx_v_ii), __pyx_v_n_samples, (__pyx_v_W_ptr + __pyx_v_jj), __pyx_v_n_tasks)); + } + } - /* "sklearn/linear_model/cd_fast.pyx":570 + /* "sklearn/linear_model/cd_fast.pyx":700 * - * # tol = tol * linalg.norm(Y, ord='fro') ** 2 - * tol = tol * dnrm2(n_samples * n_tasks, Y.data, 1) ** 2 # <<<<<<<<<<<<<< + * # tol = tol * linalg.norm(Y, ord='fro') ** 2 + * tol = tol * dnrm2(n_samples * n_tasks, Y_ptr, 1) ** 2 # <<<<<<<<<<<<<< * - * for n_iter in range(max_iter): + * for n_iter in range(max_iter): */ - __pyx_v_tol = (__pyx_v_tol * pow(cblas_dnrm2((__pyx_v_n_samples * __pyx_v_n_tasks), ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_Y->data), 1), 2.0)); + __pyx_v_tol = (__pyx_v_tol * pow(cblas_dnrm2((__pyx_v_n_samples * __pyx_v_n_tasks), __pyx_v_Y_ptr, 1), 2.0)); - /* "sklearn/linear_model/cd_fast.pyx":572 - * tol = tol * dnrm2(n_samples * n_tasks, Y.data, 1) ** 2 + /* "sklearn/linear_model/cd_fast.pyx":702 + * tol = tol * dnrm2(n_samples * n_tasks, Y_ptr, 1) ** 2 * - * for n_iter in range(max_iter): # <<<<<<<<<<<<<< - * w_max = 0.0 - * d_w_max = 0.0 + * for n_iter in range(max_iter): # <<<<<<<<<<<<<< + * w_max = 0.0 + * d_w_max = 0.0 */ - __pyx_t_11 = __pyx_v_max_iter; - for (__pyx_t_15 = 0; __pyx_t_15 < __pyx_t_11; __pyx_t_15+=1) { - __pyx_v_n_iter = __pyx_t_15; + __pyx_t_31 = __pyx_v_max_iter; + for (__pyx_t_20 = 0; __pyx_t_20 < __pyx_t_31; __pyx_t_20+=1) { + __pyx_v_n_iter = __pyx_t_20; - /* "sklearn/linear_model/cd_fast.pyx":573 + /* "sklearn/linear_model/cd_fast.pyx":703 * - * for n_iter in range(max_iter): - * w_max = 0.0 # <<<<<<<<<<<<<< - * d_w_max = 0.0 - * for ii in xrange(n_features): # Loop over coordinates + * for n_iter in range(max_iter): + * w_max = 0.0 # <<<<<<<<<<<<<< + * d_w_max = 0.0 + * for f_iter in range(n_features): # Loop over coordinates + */ + __pyx_v_w_max = 0.0; + + /* "sklearn/linear_model/cd_fast.pyx":704 + * for n_iter in range(max_iter): + * w_max = 0.0 + * d_w_max = 0.0 # <<<<<<<<<<<<<< + * for f_iter in range(n_features): # Loop over coordinates + * if random: + */ + __pyx_v_d_w_max = 0.0; + + /* "sklearn/linear_model/cd_fast.pyx":705 + * w_max = 0.0 + * d_w_max = 0.0 + * for f_iter in range(n_features): # Loop over coordinates # <<<<<<<<<<<<<< + * if random: + * ii = rand_int(n_features, rand_r_state) */ - __pyx_v_w_max = 0.0; + __pyx_t_21 = __pyx_v_n_features; + for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_21; __pyx_t_22+=1) { + __pyx_v_f_iter = __pyx_t_22; - /* "sklearn/linear_model/cd_fast.pyx":574 - * for n_iter in range(max_iter): - * w_max = 0.0 - * d_w_max = 0.0 # <<<<<<<<<<<<<< - * for ii in xrange(n_features): # Loop over coordinates - * if norm_cols_X[ii] == 0.0: + /* "sklearn/linear_model/cd_fast.pyx":706 + * d_w_max = 0.0 + * for f_iter in range(n_features): # Loop over coordinates + * if random: # <<<<<<<<<<<<<< + * ii = rand_int(n_features, rand_r_state) + * else: */ - __pyx_v_d_w_max = 0.0; + __pyx_t_19 = (__pyx_v_random != 0); + if (__pyx_t_19) { - /* "sklearn/linear_model/cd_fast.pyx":575 - * w_max = 0.0 - * d_w_max = 0.0 - * for ii in xrange(n_features): # Loop over coordinates # <<<<<<<<<<<<<< - * if norm_cols_X[ii] == 0.0: - * continue + /* "sklearn/linear_model/cd_fast.pyx":707 + * for f_iter in range(n_features): # Loop over coordinates + * if random: + * ii = rand_int(n_features, rand_r_state) # <<<<<<<<<<<<<< + * else: + * ii = f_iter */ - __pyx_t_16 = __pyx_v_n_features; - for (__pyx_t_17 = 0; __pyx_t_17 < __pyx_t_16; __pyx_t_17+=1) { - __pyx_v_ii = __pyx_t_17; + __pyx_v_ii = __pyx_f_7sklearn_12linear_model_7cd_fast_rand_int(__pyx_v_n_features, __pyx_v_rand_r_state); + goto __pyx_L19; + } + /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":576 - * d_w_max = 0.0 - * for ii in xrange(n_features): # Loop over coordinates - * if norm_cols_X[ii] == 0.0: # <<<<<<<<<<<<<< - * continue + /* "sklearn/linear_model/cd_fast.pyx":709 + * ii = rand_int(n_features, rand_r_state) + * else: + * ii = f_iter # <<<<<<<<<<<<<< * + * if norm_cols_X[ii] == 0.0: */ - __pyx_t_18 = __pyx_v_ii; - __pyx_t_9 = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_norm_cols_X.buf, __pyx_t_18, __pyx_bstride_0_norm_cols_X)) == 0.0); - if (__pyx_t_9) { + __pyx_v_ii = __pyx_v_f_iter; + } + __pyx_L19:; - /* "sklearn/linear_model/cd_fast.pyx":577 - * for ii in xrange(n_features): # Loop over coordinates - * if norm_cols_X[ii] == 0.0: - * continue # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":711 + * ii = f_iter + * + * if norm_cols_X[ii] == 0.0: # <<<<<<<<<<<<<< + * continue * - * # w_ii = W[:, ii] # Store previous value */ - goto __pyx_L9_continue; - goto __pyx_L11; - } - __pyx_L11:; + __pyx_t_23 = __pyx_v_ii; + __pyx_t_19 = (((*((double *) ( /* dim=0 */ (__pyx_v_norm_cols_X.data + __pyx_t_23 * __pyx_v_norm_cols_X.strides[0]) ))) == 0.0) != 0); + if (__pyx_t_19) { - /* "sklearn/linear_model/cd_fast.pyx":581 - * # w_ii = W[:, ii] # Store previous value - * dcopy(n_tasks, (W.data + ii * n_tasks * sizeof(DOUBLE)), - * 1, w_ii.data, 1) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":712 + * + * if norm_cols_X[ii] == 0.0: + * continue # <<<<<<<<<<<<<< * - * # if np.sum(w_ii ** 2) != 0.0: # can do better + * # w_ii = W[:, ii] # Store previous value */ - cblas_dcopy(__pyx_v_n_tasks, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_W->data + ((__pyx_v_ii * __pyx_v_n_tasks) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_w_ii->data), 1); + goto __pyx_L17_continue; + } - /* "sklearn/linear_model/cd_fast.pyx":584 + /* "sklearn/linear_model/cd_fast.pyx":715 + * + * # w_ii = W[:, ii] # Store previous value + * dcopy(n_tasks, W_ptr + ii * n_tasks, 1, wii_ptr, 1) # <<<<<<<<<<<<<< * - * # if np.sum(w_ii ** 2) != 0.0: # can do better - * if dnrm2(n_tasks, w_ii.data, 1) != 0.0: # <<<<<<<<<<<<<< - * # R += np.dot(X[:, ii][:, None], w_ii[None, :]) # rank 1 update - * dger(CblasRowMajor, n_samples, n_tasks, 1.0, + * # if np.sum(w_ii ** 2) != 0.0: # can do better */ - __pyx_t_9 = (cblas_dnrm2(__pyx_v_n_tasks, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_w_ii->data), 1) != 0.0); - if (__pyx_t_9) { + cblas_dcopy(__pyx_v_n_tasks, (__pyx_v_W_ptr + (__pyx_v_ii * __pyx_v_n_tasks)), 1, __pyx_v_wii_ptr, 1); - /* "sklearn/linear_model/cd_fast.pyx":589 - * (X.data + ii * n_samples * sizeof(DOUBLE)), 1, - * w_ii.data, 1, - * R.data, n_tasks) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":718 * - * # tmp = np.dot(X[:, ii][None, :], R).ravel() + * # if np.sum(w_ii ** 2) != 0.0: # can do better + * if dnrm2(n_tasks, wii_ptr, 1) != 0.0: # <<<<<<<<<<<<<< + * # R += np.dot(X[:, ii][:, None], w_ii[None, :]) # rank 1 update + * dger(CblasRowMajor, n_samples, n_tasks, 1.0, */ - cblas_dger(CblasRowMajor, __pyx_v_n_samples, __pyx_v_n_tasks, 1.0, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_X->data + ((__pyx_v_ii * __pyx_v_n_samples) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_w_ii->data), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), __pyx_v_n_tasks); - goto __pyx_L12; - } - __pyx_L12:; + __pyx_t_19 = ((cblas_dnrm2(__pyx_v_n_tasks, __pyx_v_wii_ptr, 1) != 0.0) != 0); + if (__pyx_t_19) { - /* "sklearn/linear_model/cd_fast.pyx":595 - * n_samples, n_tasks, 1.0, R.data, - * n_tasks, (X.data + ii * n_samples * sizeof(DOUBLE)), - * 1, 0.0, tmp.data, 1) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":722 + * dger(CblasRowMajor, n_samples, n_tasks, 1.0, + * X_ptr + ii * n_samples, 1, + * wii_ptr, 1, &R[0, 0], n_tasks) # <<<<<<<<<<<<<< * - * # nn = sqrt(np.sum(tmp ** 2)) + * # tmp = np.dot(X[:, ii][None, :], R).ravel() + */ + __pyx_t_32 = 0; + __pyx_t_33 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":720 + * if dnrm2(n_tasks, wii_ptr, 1) != 0.0: + * # R += np.dot(X[:, ii][:, None], w_ii[None, :]) # rank 1 update + * dger(CblasRowMajor, n_samples, n_tasks, 1.0, # <<<<<<<<<<<<<< + * X_ptr + ii * n_samples, 1, + * wii_ptr, 1, &R[0, 0], n_tasks) */ - cblas_dgemv(CblasRowMajor, CblasTrans, __pyx_v_n_samples, __pyx_v_n_tasks, 1.0, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), __pyx_v_n_tasks, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_X->data + ((__pyx_v_ii * __pyx_v_n_samples) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, 0.0, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_tmp->data), 1); + cblas_dger(CblasRowMajor, __pyx_v_n_samples, __pyx_v_n_tasks, 1.0, (__pyx_v_X_ptr + (__pyx_v_ii * __pyx_v_n_samples)), 1, __pyx_v_wii_ptr, 1, (&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_32 * __pyx_v_R.strides[0]) )) + __pyx_t_33)) )))), __pyx_v_n_tasks); + goto __pyx_L21; + } + __pyx_L21:; - /* "sklearn/linear_model/cd_fast.pyx":598 + /* "sklearn/linear_model/cd_fast.pyx":726 + * # tmp = np.dot(X[:, ii][None, :], R).ravel() + * dgemv(CblasRowMajor, CblasTrans, + * n_samples, n_tasks, 1.0, &R[0, 0], n_tasks, # <<<<<<<<<<<<<< + * X_ptr + ii * n_samples, 1, 0.0, &tmp[0], 1) * - * # nn = sqrt(np.sum(tmp ** 2)) - * nn = dnrm2(n_tasks, tmp.data, 1) # <<<<<<<<<<<<<< + */ + __pyx_t_34 = 0; + __pyx_t_35 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":727 + * dgemv(CblasRowMajor, CblasTrans, + * n_samples, n_tasks, 1.0, &R[0, 0], n_tasks, + * X_ptr + ii * n_samples, 1, 0.0, &tmp[0], 1) # <<<<<<<<<<<<<< * - * # W[:, ii] = tmp * fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg) + * # nn = sqrt(np.sum(tmp ** 2)) */ - __pyx_v_nn = cblas_dnrm2(__pyx_v_n_tasks, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_tmp->data), 1); + __pyx_t_36 = 0; - /* "sklearn/linear_model/cd_fast.pyx":602 - * # W[:, ii] = tmp * fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg) - * dcopy(n_tasks, tmp.data, - * 1, (W.data + ii * n_tasks * sizeof(DOUBLE)), 1) # <<<<<<<<<<<<<< - * dscal(n_tasks, fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg), - * (W.data + ii * n_tasks * sizeof(DOUBLE)), 1) + /* "sklearn/linear_model/cd_fast.pyx":725 + * + * # tmp = np.dot(X[:, ii][None, :], R).ravel() + * dgemv(CblasRowMajor, CblasTrans, # <<<<<<<<<<<<<< + * n_samples, n_tasks, 1.0, &R[0, 0], n_tasks, + * X_ptr + ii * n_samples, 1, 0.0, &tmp[0], 1) */ - cblas_dcopy(__pyx_v_n_tasks, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_tmp->data), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_W->data + ((__pyx_v_ii * __pyx_v_n_tasks) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1); + cblas_dgemv(CblasRowMajor, CblasTrans, __pyx_v_n_samples, __pyx_v_n_tasks, 1.0, (&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_34 * __pyx_v_R.strides[0]) )) + __pyx_t_35)) )))), __pyx_v_n_tasks, (__pyx_v_X_ptr + (__pyx_v_ii * __pyx_v_n_samples)), 1, 0.0, (&(*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_tmp.data) + __pyx_t_36)) )))), 1); - /* "sklearn/linear_model/cd_fast.pyx":603 - * dcopy(n_tasks, tmp.data, - * 1, (W.data + ii * n_tasks * sizeof(DOUBLE)), 1) - * dscal(n_tasks, fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg), # <<<<<<<<<<<<<< - * (W.data + ii * n_tasks * sizeof(DOUBLE)), 1) + /* "sklearn/linear_model/cd_fast.pyx":730 * + * # nn = sqrt(np.sum(tmp ** 2)) + * nn = dnrm2(n_tasks, &tmp[0], 1) # <<<<<<<<<<<<<< + * + * # W[:, ii] = tmp * fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg) */ - __pyx_t_19 = __pyx_v_ii; + __pyx_t_37 = 0; + __pyx_v_nn = cblas_dnrm2(__pyx_v_n_tasks, (&(*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_tmp.data) + __pyx_t_37)) )))), 1); - /* "sklearn/linear_model/cd_fast.pyx":604 - * 1, (W.data + ii * n_tasks * sizeof(DOUBLE)), 1) - * dscal(n_tasks, fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg), - * (W.data + ii * n_tasks * sizeof(DOUBLE)), 1) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":733 * - * # if np.sum(W[:, ii] ** 2) != 0.0: # can do better + * # W[:, ii] = tmp * fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg) + * dcopy(n_tasks, &tmp[0], 1, W_ptr + ii * n_tasks, 1) # <<<<<<<<<<<<<< + * dscal(n_tasks, fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg), + * W_ptr + ii * n_tasks, 1) */ - cblas_dscal(__pyx_v_n_tasks, (__pyx_f_7sklearn_12linear_model_7cd_fast_fmax((1. - (__pyx_v_l1_reg / __pyx_v_nn)), 0.0) / ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *, __pyx_bstruct_norm_cols_X.buf, __pyx_t_19, __pyx_bstride_0_norm_cols_X)) + __pyx_v_l2_reg)), ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_W->data + ((__pyx_v_ii * __pyx_v_n_tasks) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1); + __pyx_t_38 = 0; + cblas_dcopy(__pyx_v_n_tasks, (&(*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_tmp.data) + __pyx_t_38)) )))), 1, (__pyx_v_W_ptr + (__pyx_v_ii * __pyx_v_n_tasks)), 1); - /* "sklearn/linear_model/cd_fast.pyx":607 + /* "sklearn/linear_model/cd_fast.pyx":734 + * # W[:, ii] = tmp * fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg) + * dcopy(n_tasks, &tmp[0], 1, W_ptr + ii * n_tasks, 1) + * dscal(n_tasks, fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg), # <<<<<<<<<<<<<< + * W_ptr + ii * n_tasks, 1) * - * # if np.sum(W[:, ii] ** 2) != 0.0: # can do better - * if dnrm2(n_tasks, (W.data + ii * n_tasks * sizeof(DOUBLE)), 1) != 0.0: # <<<<<<<<<<<<<< - * # R -= np.dot(X[:, ii][:, None], W[:, ii][None, :]) # Update residual : rank 1 update - * dger(CblasRowMajor, n_samples, n_tasks, -1.0, */ - __pyx_t_9 = (cblas_dnrm2(__pyx_v_n_tasks, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_W->data + ((__pyx_v_ii * __pyx_v_n_tasks) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1) != 0.0); - if (__pyx_t_9) { + __pyx_t_39 = __pyx_v_ii; - /* "sklearn/linear_model/cd_fast.pyx":612 - * (X.data + ii * n_samples * sizeof(DOUBLE)), 1, - * (W.data + ii * n_tasks * sizeof(DOUBLE)), 1, - * R.data, n_tasks) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":735 + * dcopy(n_tasks, &tmp[0], 1, W_ptr + ii * n_tasks, 1) + * dscal(n_tasks, fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg), + * W_ptr + ii * n_tasks, 1) # <<<<<<<<<<<<<< * - * # update the maximum absolute coefficient update + * # if np.sum(W[:, ii] ** 2) != 0.0: # can do better */ - cblas_dger(CblasRowMajor, __pyx_v_n_samples, __pyx_v_n_tasks, -1.0, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_X->data + ((__pyx_v_ii * __pyx_v_n_samples) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_W->data + ((__pyx_v_ii * __pyx_v_n_tasks) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), 1, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), __pyx_v_n_tasks); - goto __pyx_L13; - } - __pyx_L13:; + cblas_dscal(__pyx_v_n_tasks, (__pyx_f_7sklearn_12linear_model_7cd_fast_fmax((1. - (__pyx_v_l1_reg / __pyx_v_nn)), 0.0) / ((*((double *) ( /* dim=0 */ (__pyx_v_norm_cols_X.data + __pyx_t_39 * __pyx_v_norm_cols_X.strides[0]) ))) + __pyx_v_l2_reg)), (__pyx_v_W_ptr + (__pyx_v_ii * __pyx_v_n_tasks)), 1); - /* "sklearn/linear_model/cd_fast.pyx":617 - * d_w_ii = diff_abs_max(n_tasks, - * (W.data + ii * n_tasks * sizeof(DOUBLE)), - * w_ii.data) # <<<<<<<<<<<<<< - * if d_w_ii > d_w_max: - * d_w_max = d_w_ii + /* "sklearn/linear_model/cd_fast.pyx":738 + * + * # if np.sum(W[:, ii] ** 2) != 0.0: # can do better + * if dnrm2(n_tasks, W_ptr + ii * n_tasks, 1) != 0.0: # <<<<<<<<<<<<<< + * # R -= np.dot(X[:, ii][:, None], W[:, ii][None, :]) # Update residual : rank 1 update + * dger(CblasRowMajor, n_samples, n_tasks, -1.0, */ - __pyx_v_d_w_ii = __pyx_f_7sklearn_12linear_model_7cd_fast_diff_abs_max(__pyx_v_n_tasks, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_W->data + ((__pyx_v_ii * __pyx_v_n_tasks) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE))))), ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_w_ii->data)); + __pyx_t_19 = ((cblas_dnrm2(__pyx_v_n_tasks, (__pyx_v_W_ptr + (__pyx_v_ii * __pyx_v_n_tasks)), 1) != 0.0) != 0); + if (__pyx_t_19) { - /* "sklearn/linear_model/cd_fast.pyx":618 - * (W.data + ii * n_tasks * sizeof(DOUBLE)), - * w_ii.data) - * if d_w_ii > d_w_max: # <<<<<<<<<<<<<< - * d_w_max = d_w_ii + /* "sklearn/linear_model/cd_fast.pyx":742 + * dger(CblasRowMajor, n_samples, n_tasks, -1.0, + * X_ptr + ii * n_samples, 1, W_ptr + ii * n_tasks, 1, + * &R[0, 0], n_tasks) # <<<<<<<<<<<<<< * + * # update the maximum absolute coefficient update */ - __pyx_t_9 = (__pyx_v_d_w_ii > __pyx_v_d_w_max); - if (__pyx_t_9) { + __pyx_t_40 = 0; + __pyx_t_41 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":740 + * if dnrm2(n_tasks, W_ptr + ii * n_tasks, 1) != 0.0: + * # R -= np.dot(X[:, ii][:, None], W[:, ii][None, :]) # Update residual : rank 1 update + * dger(CblasRowMajor, n_samples, n_tasks, -1.0, # <<<<<<<<<<<<<< + * X_ptr + ii * n_samples, 1, W_ptr + ii * n_tasks, 1, + * &R[0, 0], n_tasks) + */ + cblas_dger(CblasRowMajor, __pyx_v_n_samples, __pyx_v_n_tasks, -1.0, (__pyx_v_X_ptr + (__pyx_v_ii * __pyx_v_n_samples)), 1, (__pyx_v_W_ptr + (__pyx_v_ii * __pyx_v_n_tasks)), 1, (&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_40 * __pyx_v_R.strides[0]) )) + __pyx_t_41)) )))), __pyx_v_n_tasks); + goto __pyx_L22; + } + __pyx_L22:; - /* "sklearn/linear_model/cd_fast.pyx":619 - * w_ii.data) - * if d_w_ii > d_w_max: - * d_w_max = d_w_ii # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":745 * - * W_ii_abs_max = abs_max(n_tasks, + * # update the maximum absolute coefficient update + * d_w_ii = diff_abs_max(n_tasks, W_ptr + ii * n_tasks, wii_ptr) # <<<<<<<<<<<<<< + * + * if d_w_ii > d_w_max: */ - __pyx_v_d_w_max = __pyx_v_d_w_ii; - goto __pyx_L14; - } - __pyx_L14:; + __pyx_v_d_w_ii = __pyx_f_7sklearn_12linear_model_7cd_fast_diff_abs_max(__pyx_v_n_tasks, (__pyx_v_W_ptr + (__pyx_v_ii * __pyx_v_n_tasks)), __pyx_v_wii_ptr); - /* "sklearn/linear_model/cd_fast.pyx":622 + /* "sklearn/linear_model/cd_fast.pyx":747 + * d_w_ii = diff_abs_max(n_tasks, W_ptr + ii * n_tasks, wii_ptr) + * + * if d_w_ii > d_w_max: # <<<<<<<<<<<<<< + * d_w_max = d_w_ii * - * W_ii_abs_max = abs_max(n_tasks, - * (W.data + ii * n_tasks * sizeof(DOUBLE))) # <<<<<<<<<<<<<< - * if W_ii_abs_max > w_max: - * w_max = W_ii_abs_max */ - __pyx_v_W_ii_abs_max = __pyx_f_7sklearn_12linear_model_7cd_fast_abs_max(__pyx_v_n_tasks, ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)(__pyx_v_W->data + ((__pyx_v_ii * __pyx_v_n_tasks) * (sizeof(__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE)))))); + __pyx_t_19 = ((__pyx_v_d_w_ii > __pyx_v_d_w_max) != 0); + if (__pyx_t_19) { - /* "sklearn/linear_model/cd_fast.pyx":623 - * W_ii_abs_max = abs_max(n_tasks, - * (W.data + ii * n_tasks * sizeof(DOUBLE))) - * if W_ii_abs_max > w_max: # <<<<<<<<<<<<<< - * w_max = W_ii_abs_max + /* "sklearn/linear_model/cd_fast.pyx":748 + * + * if d_w_ii > d_w_max: + * d_w_max = d_w_ii # <<<<<<<<<<<<<< * + * W_ii_abs_max = abs_max(n_tasks, W_ptr + ii * n_tasks) */ - __pyx_t_9 = (__pyx_v_W_ii_abs_max > __pyx_v_w_max); - if (__pyx_t_9) { + __pyx_v_d_w_max = __pyx_v_d_w_ii; + goto __pyx_L23; + } + __pyx_L23:; - /* "sklearn/linear_model/cd_fast.pyx":624 - * (W.data + ii * n_tasks * sizeof(DOUBLE))) - * if W_ii_abs_max > w_max: - * w_max = W_ii_abs_max # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":750 + * d_w_max = d_w_ii * - * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: + * W_ii_abs_max = abs_max(n_tasks, W_ptr + ii * n_tasks) # <<<<<<<<<<<<<< + * if W_ii_abs_max > w_max: + * w_max = W_ii_abs_max */ - __pyx_v_w_max = __pyx_v_W_ii_abs_max; - goto __pyx_L15; - } - __pyx_L15:; - __pyx_L9_continue:; - } + __pyx_v_W_ii_abs_max = __pyx_f_7sklearn_12linear_model_7cd_fast_abs_max(__pyx_v_n_tasks, (__pyx_v_W_ptr + (__pyx_v_ii * __pyx_v_n_tasks))); - /* "sklearn/linear_model/cd_fast.pyx":626 - * w_max = W_ii_abs_max + /* "sklearn/linear_model/cd_fast.pyx":751 + * + * W_ii_abs_max = abs_max(n_tasks, W_ptr + ii * n_tasks) + * if W_ii_abs_max > w_max: # <<<<<<<<<<<<<< + * w_max = W_ii_abs_max * - * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: # <<<<<<<<<<<<<< - * # the biggest coordinate update of this iteration was smaller than - * # the tolerance: check the duality gap as ultimate stopping */ - __pyx_t_9 = (__pyx_v_w_max == 0.0); - if (!__pyx_t_9) { - __pyx_t_20 = ((__pyx_v_d_w_max / __pyx_v_w_max) < __pyx_v_d_w_tol); - if (!__pyx_t_20) { - __pyx_t_21 = (__pyx_v_n_iter == (__pyx_v_max_iter - 1)); - __pyx_t_22 = __pyx_t_21; - } else { - __pyx_t_22 = __pyx_t_20; - } - __pyx_t_20 = __pyx_t_22; - } else { - __pyx_t_20 = __pyx_t_9; - } - if (__pyx_t_20) { + __pyx_t_19 = ((__pyx_v_W_ii_abs_max > __pyx_v_w_max) != 0); + if (__pyx_t_19) { - /* "sklearn/linear_model/cd_fast.pyx":631 - * # criterion + /* "sklearn/linear_model/cd_fast.pyx":752 + * W_ii_abs_max = abs_max(n_tasks, W_ptr + ii * n_tasks) + * if W_ii_abs_max > w_max: + * w_max = W_ii_abs_max # <<<<<<<<<<<<<< * - * XtA = np.dot(X.T, R) - l2_reg * W.T # <<<<<<<<<<<<<< - * dual_norm_XtA = np.max(np.sqrt(np.sum(XtA ** 2, axis=1))) + * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: + */ + __pyx_v_w_max = __pyx_v_W_ii_abs_max; + goto __pyx_L24; + } + __pyx_L24:; + __pyx_L17_continue:; + } + + /* "sklearn/linear_model/cd_fast.pyx":754 + * w_max = W_ii_abs_max * + * if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: # <<<<<<<<<<<<<< + * # the biggest coordinate update of this iteration was smaller than + * # the tolerance: check the duality gap as ultimate stopping */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__dot); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_GetAttr(((PyObject *)__pyx_v_X), __pyx_n_s__T); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_R)); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_R)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_R)); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_l2_reg); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = PyObject_GetAttr(((PyObject *)__pyx_v_W), __pyx_n_s__T); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_5 = PyNumber_Multiply(__pyx_t_2, __pyx_t_6); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyNumber_Subtract(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_v_XtA); - __pyx_v_XtA = __pyx_t_6; - __pyx_t_6 = 0; + __pyx_t_42 = ((__pyx_v_w_max == 0.0) != 0); + if (!__pyx_t_42) { + goto __pyx_L27_next_or; + } else { + __pyx_t_19 = __pyx_t_42; + goto __pyx_L26_bool_binop_done; + } + __pyx_L27_next_or:; + __pyx_t_42 = (((__pyx_v_d_w_max / __pyx_v_w_max) < __pyx_v_d_w_tol) != 0); + if (!__pyx_t_42) { + goto __pyx_L28_next_or; + } else { + __pyx_t_19 = __pyx_t_42; + goto __pyx_L26_bool_binop_done; + } + __pyx_L28_next_or:; + __pyx_t_42 = ((__pyx_v_n_iter == (__pyx_v_max_iter - 1)) != 0); + __pyx_t_19 = __pyx_t_42; + __pyx_L26_bool_binop_done:; + if (__pyx_t_19) { + + /* "sklearn/linear_model/cd_fast.pyx":760 + * + * # XtA = np.dot(X.T, R) - l2_reg * W.T + * for ii in range(n_features): # <<<<<<<<<<<<<< + * for jj in range(n_tasks): + * XtA[ii, jj] = ddot( + */ + __pyx_t_21 = __pyx_v_n_features; + for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_21; __pyx_t_22+=1) { + __pyx_v_ii = __pyx_t_22; + + /* "sklearn/linear_model/cd_fast.pyx":761 + * # XtA = np.dot(X.T, R) - l2_reg * W.T + * for ii in range(n_features): + * for jj in range(n_tasks): # <<<<<<<<<<<<<< + * XtA[ii, jj] = ddot( + * n_samples, X_ptr + ii * n_samples, 1, + */ + __pyx_t_43 = __pyx_v_n_tasks; + for (__pyx_t_44 = 0; __pyx_t_44 < __pyx_t_43; __pyx_t_44+=1) { + __pyx_v_jj = __pyx_t_44; + + /* "sklearn/linear_model/cd_fast.pyx":764 + * XtA[ii, jj] = ddot( + * n_samples, X_ptr + ii * n_samples, 1, + * &R[0, 0] + jj, n_tasks # <<<<<<<<<<<<<< + * ) - l2_reg * W[jj, ii] + * + */ + __pyx_t_45 = 0; + __pyx_t_46 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":765 + * n_samples, X_ptr + ii * n_samples, 1, + * &R[0, 0] + jj, n_tasks + * ) - l2_reg * W[jj, ii] # <<<<<<<<<<<<<< + * + * # dual_norm_XtA = np.max(np.sqrt(np.sum(XtA ** 2, axis=1))) + */ + __pyx_t_47 = __pyx_v_jj; + __pyx_t_48 = __pyx_v_ii; + + /* "sklearn/linear_model/cd_fast.pyx":762 + * for ii in range(n_features): + * for jj in range(n_tasks): + * XtA[ii, jj] = ddot( # <<<<<<<<<<<<<< + * n_samples, X_ptr + ii * n_samples, 1, + * &R[0, 0] + jj, n_tasks + */ + __pyx_t_49 = __pyx_v_ii; + __pyx_t_50 = __pyx_v_jj; + *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_XtA.data + __pyx_t_49 * __pyx_v_XtA.strides[0]) )) + __pyx_t_50)) )) = (cblas_ddot(__pyx_v_n_samples, (__pyx_v_X_ptr + (__pyx_v_ii * __pyx_v_n_samples)), 1, ((&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_45 * __pyx_v_R.strides[0]) )) + __pyx_t_46)) )))) + __pyx_v_jj), __pyx_v_n_tasks) - (__pyx_v_l2_reg * (*((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_W.data) + __pyx_t_47)) ) + __pyx_t_48 * __pyx_v_W.strides[1]) ))))); + } + } - /* "sklearn/linear_model/cd_fast.pyx":632 + /* "sklearn/linear_model/cd_fast.pyx":768 * - * XtA = np.dot(X.T, R) - l2_reg * W.T - * dual_norm_XtA = np.max(np.sqrt(np.sum(XtA ** 2, axis=1))) # <<<<<<<<<<<<<< + * # dual_norm_XtA = np.max(np.sqrt(np.sum(XtA ** 2, axis=1))) + * dual_norm_XtA = 0.0 # <<<<<<<<<<<<<< + * for ii in range(n_features): + * # np.sqrt(np.sum(XtA ** 2, axis=1)) + */ + __pyx_v_dual_norm_XtA = 0.0; + + /* "sklearn/linear_model/cd_fast.pyx":769 + * # dual_norm_XtA = np.max(np.sqrt(np.sum(XtA ** 2, axis=1))) + * dual_norm_XtA = 0.0 + * for ii in range(n_features): # <<<<<<<<<<<<<< + * # np.sqrt(np.sum(XtA ** 2, axis=1)) + * XtA_axis1norm = dnrm2(n_tasks, &XtA[0, 0] + ii * n_tasks, 1) + */ + __pyx_t_21 = __pyx_v_n_features; + for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_21; __pyx_t_22+=1) { + __pyx_v_ii = __pyx_t_22; + + /* "sklearn/linear_model/cd_fast.pyx":771 + * for ii in range(n_features): + * # np.sqrt(np.sum(XtA ** 2, axis=1)) + * XtA_axis1norm = dnrm2(n_tasks, &XtA[0, 0] + ii * n_tasks, 1) # <<<<<<<<<<<<<< + * if XtA_axis1norm > dual_norm_XtA: + * dual_norm_XtA = XtA_axis1norm + */ + __pyx_t_51 = 0; + __pyx_t_52 = 0; + __pyx_v_XtA_axis1norm = cblas_dnrm2(__pyx_v_n_tasks, ((&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_XtA.data + __pyx_t_51 * __pyx_v_XtA.strides[0]) )) + __pyx_t_52)) )))) + (__pyx_v_ii * __pyx_v_n_tasks)), 1); + + /* "sklearn/linear_model/cd_fast.pyx":772 + * # np.sqrt(np.sum(XtA ** 2, axis=1)) + * XtA_axis1norm = dnrm2(n_tasks, &XtA[0, 0] + ii * n_tasks, 1) + * if XtA_axis1norm > dual_norm_XtA: # <<<<<<<<<<<<<< + * dual_norm_XtA = XtA_axis1norm * - * # TODO: use squared L2 norm directly */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__max); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__sqrt); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__sum); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyNumber_Power(__pyx_v_XtA, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_6); - __pyx_t_6 = 0; - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__axis), __pyx_int_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_23 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_23); - __Pyx_GIVEREF(__pyx_t_23); - __pyx_t_23 = 0; - __pyx_t_23 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_23); - __Pyx_GIVEREF(__pyx_t_23); - __pyx_t_23 = 0; - __pyx_t_23 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_v_dual_norm_XtA); - __pyx_v_dual_norm_XtA = __pyx_t_23; - __pyx_t_23 = 0; - - /* "sklearn/linear_model/cd_fast.pyx":637 - * # R_norm = linalg.norm(R, ord='fro') - * # w_norm = linalg.norm(W, ord='fro') - * R_norm = dnrm2(n_samples * n_tasks, R.data, 1) # <<<<<<<<<<<<<< - * w_norm = dnrm2(n_features * n_tasks, W.data, 1) - * if (dual_norm_XtA > l1_reg): - */ - __pyx_v_R_norm = cblas_dnrm2((__pyx_v_n_samples * __pyx_v_n_tasks), ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_R->data), 1); - - /* "sklearn/linear_model/cd_fast.pyx":638 - * # w_norm = linalg.norm(W, ord='fro') - * R_norm = dnrm2(n_samples * n_tasks, R.data, 1) - * w_norm = dnrm2(n_features * n_tasks, W.data, 1) # <<<<<<<<<<<<<< - * if (dual_norm_XtA > l1_reg): - * const = l1_reg / dual_norm_XtA - */ - __pyx_v_w_norm = cblas_dnrm2((__pyx_v_n_features * __pyx_v_n_tasks), ((__pyx_t_7sklearn_12linear_model_7cd_fast_DOUBLE *)__pyx_v_W->data), 1); - - /* "sklearn/linear_model/cd_fast.pyx":639 - * R_norm = dnrm2(n_samples * n_tasks, R.data, 1) - * w_norm = dnrm2(n_features * n_tasks, W.data, 1) - * if (dual_norm_XtA > l1_reg): # <<<<<<<<<<<<<< - * const = l1_reg / dual_norm_XtA - * A_norm = R_norm * const - */ - __pyx_t_23 = PyFloat_FromDouble(__pyx_v_l1_reg); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 639; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __pyx_t_6 = PyObject_RichCompare(__pyx_v_dual_norm_XtA, __pyx_t_23, Py_GT); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 639; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; - __pyx_t_20 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_20 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 639; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (__pyx_t_20) { + __pyx_t_19 = ((__pyx_v_XtA_axis1norm > __pyx_v_dual_norm_XtA) != 0); + if (__pyx_t_19) { - /* "sklearn/linear_model/cd_fast.pyx":640 - * w_norm = dnrm2(n_features * n_tasks, W.data, 1) - * if (dual_norm_XtA > l1_reg): - * const = l1_reg / dual_norm_XtA # <<<<<<<<<<<<<< - * A_norm = R_norm * const - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) + /* "sklearn/linear_model/cd_fast.pyx":773 + * XtA_axis1norm = dnrm2(n_tasks, &XtA[0, 0] + ii * n_tasks, 1) + * if XtA_axis1norm > dual_norm_XtA: + * dual_norm_XtA = XtA_axis1norm # <<<<<<<<<<<<<< + * + * # TODO: use squared L2 norm directly */ - __pyx_t_6 = PyFloat_FromDouble(__pyx_v_l1_reg); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_23 = __Pyx_PyNumber_Divide(__pyx_t_6, __pyx_v_dual_norm_XtA); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_v_const); - __pyx_v_const = __pyx_t_23; - __pyx_t_23 = 0; - - /* "sklearn/linear_model/cd_fast.pyx":641 - * if (dual_norm_XtA > l1_reg): - * const = l1_reg / dual_norm_XtA - * A_norm = R_norm * const # <<<<<<<<<<<<<< - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) - * else: + __pyx_v_dual_norm_XtA = __pyx_v_XtA_axis1norm; + goto __pyx_L35; + } + __pyx_L35:; + } + + /* "sklearn/linear_model/cd_fast.pyx":778 + * # R_norm = linalg.norm(R, ord='fro') + * # w_norm = linalg.norm(W, ord='fro') + * R_norm = dnrm2(n_samples * n_tasks, &R[0, 0], 1) # <<<<<<<<<<<<<< + * w_norm = dnrm2(n_features * n_tasks, W_ptr, 1) + * if (dual_norm_XtA > l1_reg): + */ + __pyx_t_53 = 0; + __pyx_t_54 = 0; + __pyx_v_R_norm = cblas_dnrm2((__pyx_v_n_samples * __pyx_v_n_tasks), (&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_53 * __pyx_v_R.strides[0]) )) + __pyx_t_54)) )))), 1); + + /* "sklearn/linear_model/cd_fast.pyx":779 + * # w_norm = linalg.norm(W, ord='fro') + * R_norm = dnrm2(n_samples * n_tasks, &R[0, 0], 1) + * w_norm = dnrm2(n_features * n_tasks, W_ptr, 1) # <<<<<<<<<<<<<< + * if (dual_norm_XtA > l1_reg): + * const = l1_reg / dual_norm_XtA + */ + __pyx_v_w_norm = cblas_dnrm2((__pyx_v_n_features * __pyx_v_n_tasks), __pyx_v_W_ptr, 1); + + /* "sklearn/linear_model/cd_fast.pyx":780 + * R_norm = dnrm2(n_samples * n_tasks, &R[0, 0], 1) + * w_norm = dnrm2(n_features * n_tasks, W_ptr, 1) + * if (dual_norm_XtA > l1_reg): # <<<<<<<<<<<<<< + * const = l1_reg / dual_norm_XtA + * A_norm = R_norm * const + */ + __pyx_t_19 = ((__pyx_v_dual_norm_XtA > __pyx_v_l1_reg) != 0); + if (__pyx_t_19) { + + /* "sklearn/linear_model/cd_fast.pyx":781 + * w_norm = dnrm2(n_features * n_tasks, W_ptr, 1) + * if (dual_norm_XtA > l1_reg): + * const = l1_reg / dual_norm_XtA # <<<<<<<<<<<<<< + * A_norm = R_norm * const + * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) + */ + __pyx_v_const = (__pyx_v_l1_reg / __pyx_v_dual_norm_XtA); + + /* "sklearn/linear_model/cd_fast.pyx":782 + * if (dual_norm_XtA > l1_reg): + * const = l1_reg / dual_norm_XtA + * A_norm = R_norm * const # <<<<<<<<<<<<<< + * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) + * else: */ - __pyx_t_23 = PyFloat_FromDouble(__pyx_v_R_norm); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __pyx_t_6 = PyNumber_Multiply(__pyx_t_23, __pyx_v_const); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; - __Pyx_XDECREF(__pyx_v_A_norm); - __pyx_v_A_norm = __pyx_t_6; - __pyx_t_6 = 0; + __pyx_v_A_norm = (__pyx_v_R_norm * __pyx_v_const); - /* "sklearn/linear_model/cd_fast.pyx":642 - * const = l1_reg / dual_norm_XtA - * A_norm = R_norm * const - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) # <<<<<<<<<<<<<< - * else: - * const = 1.0 + /* "sklearn/linear_model/cd_fast.pyx":783 + * const = l1_reg / dual_norm_XtA + * A_norm = R_norm * const + * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) # <<<<<<<<<<<<<< + * else: + * const = 1.0 */ - __pyx_t_6 = PyFloat_FromDouble(0.5); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_23 = PyFloat_FromDouble(pow(__pyx_v_R_norm, 2.0)); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __pyx_t_5 = PyNumber_Power(__pyx_v_A_norm, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyNumber_Add(__pyx_t_23, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Multiply(__pyx_t_6, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_24 = __pyx_PyFloat_AsDouble(__pyx_t_5); if (unlikely((__pyx_t_24 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_gap = __pyx_t_24; - goto __pyx_L17; - } - /*else*/ { + __pyx_v_gap = (0.5 * (pow(__pyx_v_R_norm, 2.0) + pow(__pyx_v_A_norm, 2.0))); + goto __pyx_L36; + } + /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":644 - * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) - * else: - * const = 1.0 # <<<<<<<<<<<<<< - * gap = R_norm ** 2 + /* "sklearn/linear_model/cd_fast.pyx":785 + * gap = 0.5 * (R_norm ** 2 + A_norm ** 2) + * else: + * const = 1.0 # <<<<<<<<<<<<<< + * gap = R_norm ** 2 * */ - __pyx_t_5 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_v_const); - __pyx_v_const = __pyx_t_5; - __pyx_t_5 = 0; + __pyx_v_const = 1.0; - /* "sklearn/linear_model/cd_fast.pyx":645 - * else: - * const = 1.0 - * gap = R_norm ** 2 # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":786 + * else: + * const = 1.0 + * gap = R_norm ** 2 # <<<<<<<<<<<<<< * - * gap += l1_reg * np.sqrt(np.sum(W ** 2, axis=0)).sum() - const * np.sum(R * Y) + \ + * # ry_sum = np.sum(R * y) */ - __pyx_v_gap = pow(__pyx_v_R_norm, 2.0); - } - __pyx_L17:; + __pyx_v_gap = pow(__pyx_v_R_norm, 2.0); + } + __pyx_L36:; - /* "sklearn/linear_model/cd_fast.pyx":647 - * gap = R_norm ** 2 + /* "sklearn/linear_model/cd_fast.pyx":789 * - * gap += l1_reg * np.sqrt(np.sum(W ** 2, axis=0)).sum() - const * np.sum(R * Y) + \ # <<<<<<<<<<<<<< - * 0.5 * l2_reg * (1 + const ** 2) * (w_norm ** 2) + * # ry_sum = np.sum(R * y) + * ry_sum = 0.0 # <<<<<<<<<<<<<< + * for ii in range(n_samples): + * for jj in range(n_tasks): + */ + __pyx_v_ry_sum = 0.0; + + /* "sklearn/linear_model/cd_fast.pyx":790 + * # ry_sum = np.sum(R * y) + * ry_sum = 0.0 + * for ii in range(n_samples): # <<<<<<<<<<<<<< + * for jj in range(n_tasks): + * ry_sum += R[ii, jj] * Y[ii, jj] + */ + __pyx_t_21 = __pyx_v_n_samples; + for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_21; __pyx_t_22+=1) { + __pyx_v_ii = __pyx_t_22; + + /* "sklearn/linear_model/cd_fast.pyx":791 + * ry_sum = 0.0 + * for ii in range(n_samples): + * for jj in range(n_tasks): # <<<<<<<<<<<<<< + * ry_sum += R[ii, jj] * Y[ii, jj] * */ - __pyx_t_5 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_l1_reg); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_23 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__sqrt); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__sum); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyNumber_Power(((PyObject *)__pyx_v_W), __pyx_int_2, Py_None); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_6); - __pyx_t_6 = 0; - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__axis), __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_25 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_25); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_25); - __Pyx_GIVEREF(__pyx_t_25); - __pyx_t_25 = 0; - __pyx_t_25 = PyObject_Call(__pyx_t_23, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_25); - __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_GetAttr(__pyx_t_25, __pyx_n_s__sum); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_25); __pyx_t_25 = 0; - __pyx_t_25 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_25); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyNumber_Multiply(__pyx_t_3, __pyx_t_25); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_25); __pyx_t_25 = 0; - __pyx_t_25 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_25); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_25, __pyx_n_s__sum); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_25); __pyx_t_25 = 0; - __pyx_t_25 = PyNumber_Multiply(((PyObject *)__pyx_v_R), ((PyObject *)__pyx_v_Y)); if (unlikely(!__pyx_t_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_25); - __pyx_t_23 = PyTuple_New(1); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_23)); - PyTuple_SET_ITEM(__pyx_t_23, 0, __pyx_t_25); - __Pyx_GIVEREF(__pyx_t_25); - __pyx_t_25 = 0; - __pyx_t_25 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_23), NULL); if (unlikely(!__pyx_t_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_25); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_23)); __pyx_t_23 = 0; - __pyx_t_23 = PyNumber_Multiply(__pyx_v_const, __pyx_t_25); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __Pyx_DECREF(__pyx_t_25); __pyx_t_25 = 0; - __pyx_t_25 = PyNumber_Subtract(__pyx_t_6, __pyx_t_23); if (unlikely(!__pyx_t_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_25); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; + __pyx_t_43 = __pyx_v_n_tasks; + for (__pyx_t_44 = 0; __pyx_t_44 < __pyx_t_43; __pyx_t_44+=1) { + __pyx_v_jj = __pyx_t_44; - /* "sklearn/linear_model/cd_fast.pyx":648 + /* "sklearn/linear_model/cd_fast.pyx":792 + * for ii in range(n_samples): + * for jj in range(n_tasks): + * ry_sum += R[ii, jj] * Y[ii, jj] # <<<<<<<<<<<<<< * - * gap += l1_reg * np.sqrt(np.sum(W ** 2, axis=0)).sum() - const * np.sum(R * Y) + \ - * 0.5 * l2_reg * (1 + const ** 2) * (w_norm ** 2) # <<<<<<<<<<<<<< + * # l21_norm = np.sqrt(np.sum(W ** 2, axis=0)).sum() + */ + __pyx_t_55 = __pyx_v_ii; + __pyx_t_56 = __pyx_v_jj; + __pyx_t_57 = __pyx_v_ii; + __pyx_t_58 = __pyx_v_jj; + __pyx_v_ry_sum = (__pyx_v_ry_sum + ((*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_R.data + __pyx_t_55 * __pyx_v_R.strides[0]) )) + __pyx_t_56)) ))) * (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_57 * __pyx_v_Y.strides[0]) ) + __pyx_t_58 * __pyx_v_Y.strides[1]) ))))); + } + } + + /* "sklearn/linear_model/cd_fast.pyx":795 * - * if gap < tol: + * # l21_norm = np.sqrt(np.sum(W ** 2, axis=0)).sum() + * l21_norm = 0.0 # <<<<<<<<<<<<<< + * for ii in range(n_features): + * # np.sqrt(np.sum(W ** 2, axis=0)) */ - __pyx_t_23 = PyFloat_FromDouble((0.5 * __pyx_v_l2_reg)); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __pyx_t_6 = PyNumber_Power(__pyx_v_const, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_3 = PyNumber_Add(__pyx_int_1, __pyx_t_6); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyNumber_Multiply(__pyx_t_23, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(pow(__pyx_v_w_norm, 2.0)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_23 = PyNumber_Multiply(__pyx_t_6, __pyx_t_3); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Add(__pyx_t_25, __pyx_t_23); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_25); __pyx_t_25 = 0; - __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; - __pyx_t_23 = PyNumber_InPlaceAdd(__pyx_t_5, __pyx_t_3); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_24 = __pyx_PyFloat_AsDouble(__pyx_t_23); if (unlikely((__pyx_t_24 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; - __pyx_v_gap = __pyx_t_24; + __pyx_v_l21_norm = 0.0; + + /* "sklearn/linear_model/cd_fast.pyx":796 + * # l21_norm = np.sqrt(np.sum(W ** 2, axis=0)).sum() + * l21_norm = 0.0 + * for ii in range(n_features): # <<<<<<<<<<<<<< + * # np.sqrt(np.sum(W ** 2, axis=0)) + * l21_norm += dnrm2(n_tasks, W_ptr + n_tasks * ii, 1) + */ + __pyx_t_21 = __pyx_v_n_features; + for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_21; __pyx_t_22+=1) { + __pyx_v_ii = __pyx_t_22; - /* "sklearn/linear_model/cd_fast.pyx":650 - * 0.5 * l2_reg * (1 + const ** 2) * (w_norm ** 2) + /* "sklearn/linear_model/cd_fast.pyx":798 + * for ii in range(n_features): + * # np.sqrt(np.sum(W ** 2, axis=0)) + * l21_norm += dnrm2(n_tasks, W_ptr + n_tasks * ii, 1) # <<<<<<<<<<<<<< * - * if gap < tol: # <<<<<<<<<<<<<< - * # return if we reached desired tolerance - * break + * gap += l1_reg * l21_norm - const * ry_sum + \ */ - __pyx_t_20 = (__pyx_v_gap < __pyx_v_tol); - if (__pyx_t_20) { + __pyx_v_l21_norm = (__pyx_v_l21_norm + cblas_dnrm2(__pyx_v_n_tasks, (__pyx_v_W_ptr + (__pyx_v_n_tasks * __pyx_v_ii)), 1)); + } - /* "sklearn/linear_model/cd_fast.pyx":652 - * if gap < tol: - * # return if we reached desired tolerance - * break # <<<<<<<<<<<<<< + /* "sklearn/linear_model/cd_fast.pyx":800 + * l21_norm += dnrm2(n_tasks, W_ptr + n_tasks * ii, 1) + * + * gap += l1_reg * l21_norm - const * ry_sum + \ # <<<<<<<<<<<<<< + * 0.5 * l2_reg * (1 + const ** 2) * (w_norm ** 2) + * + */ + __pyx_v_gap = (__pyx_v_gap + (((__pyx_v_l1_reg * __pyx_v_l21_norm) - (__pyx_v_const * __pyx_v_ry_sum)) + (((0.5 * __pyx_v_l2_reg) * (1.0 + pow(__pyx_v_const, 2.0))) * pow(__pyx_v_w_norm, 2.0)))); + + /* "sklearn/linear_model/cd_fast.pyx":803 + * 0.5 * l2_reg * (1 + const ** 2) * (w_norm ** 2) + * + * if gap < tol: # <<<<<<<<<<<<<< + * # return if we reached desired tolerance + * break + */ + __pyx_t_19 = ((__pyx_v_gap < __pyx_v_tol) != 0); + if (__pyx_t_19) { + + /* "sklearn/linear_model/cd_fast.pyx":805 + * if gap < tol: + * # return if we reached desired tolerance + * break # <<<<<<<<<<<<<< * - * return W, gap, tol + * return np.asarray(W), gap, tol, n_iter + 1 */ - goto __pyx_L8_break; - goto __pyx_L18; + goto __pyx_L16_break; + } + goto __pyx_L25; + } + __pyx_L25:; + } + __pyx_L16_break:; + } + + /* "sklearn/linear_model/cd_fast.pyx":686 + * " results and is discouraged.") + * + * with nogil: # <<<<<<<<<<<<<< + * # norm_cols_X = (np.asarray(X) ** 2).sum(axis=0) + * for ii in range(n_features): + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L6; + } + __pyx_L6:; } - __pyx_L18:; - goto __pyx_L16; - } - __pyx_L16:; } - __pyx_L8_break:; - /* "sklearn/linear_model/cd_fast.pyx":654 - * break + /* "sklearn/linear_model/cd_fast.pyx":807 + * break * - * return W, gap, tol # <<<<<<<<<<<<<< + * return np.asarray(W), gap, tol, n_iter + 1 # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); - __pyx_t_23 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_23); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_tol); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_asarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_W, 2, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (!__pyx_t_5) { + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_GOTREF(__pyx_t_2); + } else { + __pyx_t_1 = PyTuple_New(1+1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; + PyTuple_SET_ITEM(__pyx_t_1, 0+1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_gap); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __Pyx_INCREF(((PyObject *)__pyx_v_W)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_W)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_W)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_23); - __Pyx_GIVEREF(__pyx_t_23); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_tol); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyInt_From_long((__pyx_v_n_iter + 1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_23 = 0; + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; __pyx_t_3 = 0; - __pyx_r = ((PyObject *)__pyx_t_5); + __pyx_t_1 = 0; + __pyx_t_4 = 0; + __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/linear_model/cd_fast.pyx":630 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def enet_coordinate_descent_multi_task(double[::1, :] W, double l1_reg, # <<<<<<<<<<<<<< + * double l2_reg, double[::1, :] X, + * double[:, :] Y, int max_iter, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_23); - __Pyx_XDECREF(__pyx_t_25); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_norm_cols_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_tmp); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_w_ii); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_R); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_W); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_Y); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_8, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_9, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_10, 1); __Pyx_AddTraceback("sklearn.linear_model.cd_fast.enet_coordinate_descent_multi_task", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; - goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_norm_cols_X); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_tmp); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_w_ii); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_R); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_W); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_Y); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_norm_cols_X); - __Pyx_XDECREF((PyObject *)__pyx_v_R); - __Pyx_XDECREF((PyObject *)__pyx_v_tmp); - __Pyx_XDECREF((PyObject *)__pyx_v_w_ii); - __Pyx_XDECREF(__pyx_v_XtA); - __Pyx_XDECREF(__pyx_v_dual_norm_XtA); - __Pyx_XDECREF(__pyx_v_const); - __Pyx_XDECREF(__pyx_v_A_norm); + __PYX_XDEC_MEMVIEW(&__pyx_v_XtA, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_R, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_norm_cols_X, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_tmp, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_w_ii, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_W, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Y, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":190 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< @@ -7224,8 +8169,20 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_7cd_fast_4enet_coordinate_desc * # requirements, and does not yet fullfill the PEP. */ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; @@ -7240,38 +8197,34 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - char *__pyx_t_9; + PyObject *__pyx_t_6 = NULL; + char *__pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__"); + __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":196 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ - __pyx_t_1 = (__pyx_v_info == NULL); + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; - goto __pyx_L5; } - __pyx_L5:; - /* "numpy.pxd":199 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -7280,7 +8233,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":200 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -7289,26 +8242,26 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":202 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":204 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":205 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -7316,11 +8269,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ * copy_shape = 0 */ __pyx_v_copy_shape = 1; - goto __pyx_L6; + goto __pyx_L4; } /*else*/ { - /* "numpy.pxd":207 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -7329,98 +8282,102 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_copy_shape = 0; } - __pyx_L6:; + __pyx_L4:; - /* "numpy.pxd":209 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); - if (__pyx_t_1) { + __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_2) { + goto __pyx_L7_next_and; + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L6_bool_binop_done; + } + __pyx_L7_next_and:; - /* "numpy.pxd":210 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); - __pyx_t_3 = __pyx_t_2; - } else { - __pyx_t_3 = __pyx_t_1; - } - if (__pyx_t_3) { + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L6_bool_binop_done:; + if (__pyx_t_1) { - /* "numpy.pxd":211 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L7:; - /* "numpy.pxd":213 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); - if (__pyx_t_3) { + __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_2) { + goto __pyx_L10_next_and; + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L9_bool_binop_done; + } + __pyx_L10_next_and:; - /* "numpy.pxd":214 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); - __pyx_t_2 = __pyx_t_1; - } else { - __pyx_t_2 = __pyx_t_3; - } - if (__pyx_t_2) { + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L9_bool_binop_done:; + if (__pyx_t_1) { - /* "numpy.pxd":215 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L8:; - /* "numpy.pxd":217 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":218 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -7429,16 +8386,17 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":219 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ - if (__pyx_v_copy_shape) { + __pyx_t_1 = (__pyx_v_copy_shape != 0); + if (__pyx_t_1) { - /* "numpy.pxd":222 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -7447,7 +8405,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":223 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -7456,60 +8414,60 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":224 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] */ - __pyx_t_5 = __pyx_v_ndim; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; + __pyx_t_4 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; - /* "numpy.pxd":225 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":226 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } - goto __pyx_L9; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":228 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":229 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } - __pyx_L9:; + __pyx_L11:; - /* "numpy.pxd":230 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -7518,25 +8476,25 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":231 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":232 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - /* "numpy.pxd":235 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -7545,17 +8503,19 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_f = NULL; - /* "numpy.pxd":236 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; - /* "numpy.pxd":240 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -7564,23 +8524,27 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":242 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); - __pyx_t_1 = __pyx_t_3; + goto __pyx_L16_next_and; } else { __pyx_t_1 = __pyx_t_2; + goto __pyx_L15_bool_binop_done; } + __pyx_L16_next_and:; + __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L15_bool_binop_done:; if (__pyx_t_1) { - /* "numpy.pxd":244 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -7592,344 +8556,326 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; - goto __pyx_L12; + goto __pyx_L14; } /*else*/ { - /* "numpy.pxd":247 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } - __pyx_L12:; + __pyx_L14:; - /* "numpy.pxd":249 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { - /* "numpy.pxd":250 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_4 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_4; - /* "numpy.pxd":251 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); - if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; + __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); + if (!__pyx_t_2) { + goto __pyx_L20_next_or; } else { - __pyx_t_2 = __pyx_t_1; + goto __pyx_L21_next_and; } + __pyx_L21_next_and:; + __pyx_t_2 = (__pyx_v_little_endian != 0); if (!__pyx_t_2) { + goto __pyx_L20_next_or; + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_L20_next_or:; - /* "numpy.pxd":252 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); - if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); - __pyx_t_7 = __pyx_t_3; - } else { - __pyx_t_7 = __pyx_t_1; - } - __pyx_t_1 = __pyx_t_7; + __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_2) { + goto __pyx_L22_next_and; } else { __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; } + __pyx_L22_next_and:; + __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L19_bool_binop_done:; if (__pyx_t_1) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_13), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L14:; - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__b; - goto __pyx_L15; - } + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; - /* "numpy.pxd":255 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__B; - goto __pyx_L15; - } + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; - /* "numpy.pxd":256 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__h; - goto __pyx_L15; - } + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; - /* "numpy.pxd":257 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__H; - goto __pyx_L15; - } + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; - /* "numpy.pxd":258 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__i; - goto __pyx_L15; - } + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; - /* "numpy.pxd":259 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__I; - goto __pyx_L15; - } + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; - /* "numpy.pxd":260 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__l; - goto __pyx_L15; - } + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; - /* "numpy.pxd":261 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__L; - goto __pyx_L15; - } + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; - /* "numpy.pxd":262 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__q; - goto __pyx_L15; - } + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; - /* "numpy.pxd":263 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; - } + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; - /* "numpy.pxd":264 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__f; - goto __pyx_L15; - } + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; - /* "numpy.pxd":265 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__d; - goto __pyx_L15; - } + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; - /* "numpy.pxd":266 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__g; - goto __pyx_L15; - } + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; - /* "numpy.pxd":267 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; - } + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; - /* "numpy.pxd":268 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; - } + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; - /* "numpy.pxd":269 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; - } + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; - /* "numpy.pxd":270 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L15; - } - /*else*/ { + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: - /* "numpy.pxd":272 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_14), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); - __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L15:; - /* "numpy.pxd":273 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -7938,7 +8884,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":274 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -7947,63 +8893,70 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":276 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":277 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":278 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":281 - * f = _util_dtypestring(descr, info.format + 1, + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, - * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string - * + * &offset) */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_9; + __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_7; - /* "numpy.pxd":282 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L13:; + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { @@ -8022,31 +8975,41 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ return __pyx_r; } -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__"); + __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":285 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { - /* "numpy.pxd":286 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -8054,21 +9017,21 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * stdlib.free(info.strides) */ free(__pyx_v_info->format); - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":287 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":288 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -8076,14 +9039,23 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * */ free(__pyx_v_info->strides); - goto __pyx_L6; + goto __pyx_L4; } - __pyx_L6:; + __pyx_L4:; + + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":764 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -8098,9 +9070,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":765 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -8108,14 +9080,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -8126,7 +9105,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":767 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -8141,9 +9120,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":768 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -8151,14 +9130,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -8169,7 +9155,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -8184,9 +9170,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":771 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -8194,14 +9180,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -8212,7 +9205,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -8227,9 +9220,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":774 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -8237,14 +9230,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -8255,7 +9255,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -8270,9 +9270,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":777 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -8280,14 +9280,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -8298,7 +9305,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -8320,19 +9327,17 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; + int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; + long __pyx_t_8; + char *__pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring"); + __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":786 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -8341,7 +9346,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":787 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -8350,161 +9355,169 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":790 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ - if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":791 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; - /* "numpy.pxd":792 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * - * if (end - f) - (new_offset - offset[0]) < 15: - */ - if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { - PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; - /* "numpy.pxd":794 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { - /* "numpy.pxd":795 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L5:; - /* "numpy.pxd":797 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (!__pyx_t_7) { + goto __pyx_L8_next_or; } else { - __pyx_t_7 = __pyx_t_6; + goto __pyx_L9_next_and; } + __pyx_L9_next_and:; + __pyx_t_7 = (__pyx_v_little_endian != 0); if (!__pyx_t_7) { + goto __pyx_L8_next_or; + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_L8_next_or:; - /* "numpy.pxd":798 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; - } else { - __pyx_t_9 = __pyx_t_6; - } - __pyx_t_6 = __pyx_t_9; + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + goto __pyx_L10_next_and; } else { __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; } + __pyx_L10_next_and:; + __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L7_bool_binop_done:; if (__pyx_t_6) { - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_17), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; - /* "numpy.pxd":809 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -8512,16 +9525,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; - /* "numpy.pxd":810 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -8530,7 +9542,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":811 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -8539,430 +9551,410 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":812 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); } - /* "numpy.pxd":814 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); - /* "numpy.pxd":816 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { - /* "numpy.pxd":817 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":818 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { - /* "numpy.pxd":819 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_19), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L10:; - /* "numpy.pxd":822 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":823 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":824 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 104; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":825 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":826 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 105; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":827 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":828 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 108; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":829 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":830 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 113; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":831 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":832 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 102; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":833 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 100; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":834 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 103; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":835 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":836 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":837 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":838 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; - goto __pyx_L11; + goto __pyx_L15; } /*else*/ { - /* "numpy.pxd":840 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_14), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L11:; + __pyx_L15:; - /* "numpy.pxd":841 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -8970,25 +9962,33 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":845 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; } - __pyx_L9:; + __pyx_L13:; + + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":846 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -8998,13 +9998,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_r = __pyx_v_f; goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -9017,7 +10023,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":961 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -9029,9 +10035,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base"); + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":963 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -9039,9 +10046,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "numpy.pxd":964 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -9053,7 +10061,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":966 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":971 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -9062,7 +10070,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":967 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":972 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -9073,7 +10081,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":968 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":973 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -9082,7 +10090,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":969 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":974 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -9091,10 +10099,19 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ __pyx_v_arr->base = __pyx_v_baseptr; + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":971 +/* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -9106,19 +10123,19 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base"); + __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":972 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { - /* "numpy.pxd":973 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":978 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -9129,11 +10146,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "numpy.pxd":975 + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -9143,997 +10159,12955 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } - __pyx_L3:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; +/* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ -#if PY_MAJOR_VERSION >= 3 -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - __Pyx_NAMESTR("cd_fast"), - 0, /* m_doc */ - -1, /* m_size */ - __pyx_methods /* m_methods */, - NULL, /* m_reload */ - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif +/* Python wrapper */ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_shape = 0; + Py_ssize_t __pyx_v_itemsize; + PyObject *__pyx_v_format = 0; + PyObject *__pyx_v_mode = 0; + int __pyx_v_allocate_buffer; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[3] = ((PyObject *)__pyx_n_s_c); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mode); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_allocate_buffer); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_shape = ((PyObject*)values[0]); + __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_format = values[2]; + __pyx_v_mode = values[3]; + if (values[4]) { + __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_u_10, __pyx_k_10, sizeof(__pyx_k_10), 0, 1, 0, 0}, - {&__pyx_kp_u_12, __pyx_k_12, sizeof(__pyx_k_12), 0, 1, 0, 0}, - {&__pyx_kp_u_14, __pyx_k_14, sizeof(__pyx_k_14), 0, 1, 0, 0}, - {&__pyx_kp_u_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 1, 0, 0}, - {&__pyx_kp_u_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 1, 0, 0}, - {&__pyx_kp_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 0}, - {&__pyx_n_s_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 1, 1}, - {&__pyx_n_s_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 1, 1}, - {&__pyx_n_s_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 1, 1}, - {&__pyx_n_s_23, __pyx_k_23, sizeof(__pyx_k_23), 0, 0, 1, 1}, - {&__pyx_n_s_24, __pyx_k_24, sizeof(__pyx_k_24), 0, 0, 1, 1}, - {&__pyx_n_s_25, __pyx_k_25, sizeof(__pyx_k_25), 0, 0, 1, 1}, - {&__pyx_n_s_26, __pyx_k_26, sizeof(__pyx_k_26), 0, 0, 1, 1}, - {&__pyx_kp_s_6, __pyx_k_6, sizeof(__pyx_k_6), 0, 0, 1, 0}, - {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, - {&__pyx_n_s__C, __pyx_k__C, sizeof(__pyx_k__C), 0, 0, 1, 1}, - {&__pyx_n_s__Q, __pyx_k__Q, sizeof(__pyx_k__Q), 0, 0, 1, 1}, - {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__T, __pyx_k__T, sizeof(__pyx_k__T), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s__W, __pyx_k__W, sizeof(__pyx_k__W), 0, 0, 1, 1}, - {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, - {&__pyx_n_s__X_data, __pyx_k__X_data, sizeof(__pyx_k__X_data), 0, 0, 1, 1}, - {&__pyx_n_s__X_indices, __pyx_k__X_indices, sizeof(__pyx_k__X_indices), 0, 0, 1, 1}, - {&__pyx_n_s__X_indptr, __pyx_k__X_indptr, sizeof(__pyx_k__X_indptr), 0, 0, 1, 1}, - {&__pyx_n_s__X_mean, __pyx_k__X_mean, sizeof(__pyx_k__X_mean), 0, 0, 1, 1}, - {&__pyx_n_s__Y, __pyx_k__Y, sizeof(__pyx_k__Y), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__alpha, __pyx_k__alpha, sizeof(__pyx_k__alpha), 0, 0, 1, 1}, - {&__pyx_n_s__any, __pyx_k__any, sizeof(__pyx_k__any), 0, 0, 1, 1}, - {&__pyx_n_s__asarray, __pyx_k__asarray, sizeof(__pyx_k__asarray), 0, 0, 1, 1}, - {&__pyx_n_s__axis, __pyx_k__axis, sizeof(__pyx_k__axis), 0, 0, 1, 1}, - {&__pyx_n_s__beta, __pyx_k__beta, sizeof(__pyx_k__beta), 0, 0, 1, 1}, - {&__pyx_n_s__copy, __pyx_k__copy, sizeof(__pyx_k__copy), 0, 0, 1, 1}, - {&__pyx_n_s__dot, __pyx_k__dot, sizeof(__pyx_k__dot), 0, 0, 1, 1}, - {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, - {&__pyx_n_s__float, __pyx_k__float, sizeof(__pyx_k__float), 0, 0, 1, 1}, - {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, - {&__pyx_n_s__inf, __pyx_k__inf, sizeof(__pyx_k__inf), 0, 0, 1, 1}, - {&__pyx_n_s__l1_reg, __pyx_k__l1_reg, sizeof(__pyx_k__l1_reg), 0, 0, 1, 1}, - {&__pyx_n_s__l2_reg, __pyx_k__l2_reg, sizeof(__pyx_k__l2_reg), 0, 0, 1, 1}, - {&__pyx_n_s__linalg, __pyx_k__linalg, sizeof(__pyx_k__linalg), 0, 0, 1, 1}, - {&__pyx_n_s__max, __pyx_k__max, sizeof(__pyx_k__max), 0, 0, 1, 1}, - {&__pyx_n_s__max_iter, __pyx_k__max_iter, sizeof(__pyx_k__max_iter), 0, 0, 1, 1}, - {&__pyx_n_s__n_features, __pyx_k__n_features, sizeof(__pyx_k__n_features), 0, 0, 1, 1}, - {&__pyx_n_s__n_samples, __pyx_k__n_samples, sizeof(__pyx_k__n_samples), 0, 0, 1, 1}, - {&__pyx_n_s__norm, __pyx_k__norm, sizeof(__pyx_k__norm), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__order, __pyx_k__order, sizeof(__pyx_k__order), 0, 0, 1, 1}, - {&__pyx_n_s__positive, __pyx_k__positive, sizeof(__pyx_k__positive), 0, 0, 1, 1}, - {&__pyx_n_s__q, __pyx_k__q, sizeof(__pyx_k__q), 0, 0, 1, 1}, - {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__sparse_std, __pyx_k__sparse_std, sizeof(__pyx_k__sparse_std), 0, 0, 1, 1}, - {&__pyx_n_s__sqrt, __pyx_k__sqrt, sizeof(__pyx_k__sqrt), 0, 0, 1, 1}, - {&__pyx_n_s__sum, __pyx_k__sum, sizeof(__pyx_k__sum), 0, 0, 1, 1}, - {&__pyx_n_s__tol, __pyx_k__tol, sizeof(__pyx_k__tol), 0, 0, 1, 1}, - {&__pyx_n_s__w, __pyx_k__w, sizeof(__pyx_k__w), 0, 0, 1, 1}, - {&__pyx_n_s__warn, __pyx_k__warn, sizeof(__pyx_k__warn), 0, 0, 1, 1}, - {&__pyx_n_s__warnings, __pyx_k__warnings, sizeof(__pyx_k__warnings), 0, 0, 1, 1}, - {&__pyx_n_s__xrange, __pyx_k__xrange, sizeof(__pyx_k__xrange), 0, 0, 1, 1}, - {&__pyx_n_s__y, __pyx_k__y, sizeof(__pyx_k__y), 0, 0, 1, 1}, - {&__pyx_n_s__zeros, __pyx_k__zeros, sizeof(__pyx_k__zeros), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static int __Pyx_InitCachedBuiltins(void) { - #if PY_MAJOR_VERSION >= 3 - __pyx_builtin_xrange = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_builtin_xrange = __Pyx_GetName(__pyx_b, __pyx_n_s__xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - return 0; - __pyx_L1_error:; + /* "View.MemoryView":117 + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, + * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_v_allocate_buffer = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { + PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_r = __pyx_array_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); + + /* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; } -static int __Pyx_InitCachedConstants(void) { +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { + int __pyx_v_idx; + Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_dim; + PyObject **__pyx_v_p; + char __pyx_v_order; + int __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + char *__pyx_t_5; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_INCREF(__pyx_v_format); - /* "sklearn/linear_model/cd_fast.pyx":143 + /* "View.MemoryView":123 + * cdef PyObject **p * - * if alpha == 0: - * warnings.warn("Coordinate descent with alpha=0 may lead to unexpected" # <<<<<<<<<<<<<< - * " results and is discouraged.") + * self.ndim = len(shape) # <<<<<<<<<<<<<< + * self.itemsize = itemsize * */ - __pyx_k_tuple_3 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_3)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_2)); - PyTuple_SET_ITEM(__pyx_k_tuple_3, 0, ((PyObject *)__pyx_kp_s_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_3)); + if (unlikely(__pyx_v_shape == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->ndim = ((int)__pyx_t_1); - /* "sklearn/linear_model/cd_fast.pyx":422 + /* "View.MemoryView":124 * - * if alpha == 0: - * warnings.warn("Coordinate descent with alpha=0 may lead to unexpected" # <<<<<<<<<<<<<< - * " results and is discouraged.") + * self.ndim = len(shape) + * self.itemsize = itemsize # <<<<<<<<<<<<<< * + * if not self.ndim: */ - __pyx_k_tuple_5 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_5)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_2)); - PyTuple_SET_ITEM(__pyx_k_tuple_5, 0, ((PyObject *)__pyx_kp_s_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); + __pyx_v_self->itemsize = __pyx_v_itemsize; - /* "sklearn/linear_model/cd_fast.pyx":563 + /* "View.MemoryView":126 + * self.itemsize = itemsize * - * if l1_reg == 0: - * warnings.warn("Coordinate descent with l1_reg=0 may lead to unexpected" # <<<<<<<<<<<<<< - * " results and is discouraged.") + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") * */ - __pyx_k_tuple_7 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_7)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_6)); - PyTuple_SET_ITEM(__pyx_k_tuple_7, 0, ((PyObject *)__pyx_kp_s_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); + __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); + if (__pyx_t_2) { - /* "numpy.pxd":211 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + /* "View.MemoryView":127 * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if itemsize <= 0: */ - __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_9)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "numpy.pxd":215 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + /* "View.MemoryView":129 + * raise ValueError("Empty shape tuple for cython.array") + * + * if itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") * - * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_11 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_11)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_10)); - PyTuple_SET_ITEM(__pyx_k_tuple_11, 0, ((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); + __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); + if (__pyx_t_2) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" + /* "View.MemoryView":130 + * + * if itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * if isinstance(format, unicode): */ - __pyx_k_tuple_13 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_13)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_12)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 0, ((PyObject *)__pyx_kp_u_12)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_12)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "numpy.pxd":795 + /* "View.MemoryView":132 + * raise ValueError("itemsize <= 0 for cython.array") * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * if isinstance(format, unicode): # <<<<<<<<<<<<<< + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string + */ + __pyx_t_2 = PyUnicode_Check(__pyx_v_format); + __pyx_t_4 = (__pyx_t_2 != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":133 * - * if ((child.byteorder == '>' and little_endian) or + * if isinstance(format, unicode): + * format = (format).encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format # keep a reference to the byte string + * self.format = self._format */ - __pyx_k_tuple_16 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_16)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_15)); - PyTuple_SET_ITEM(__pyx_k_tuple_16, 0, ((PyObject *)__pyx_kp_u_15)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_15)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); + if (unlikely(__pyx_v_format == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", "encode"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = PyUnicode_AsASCIIString(((PyObject*)__pyx_v_format)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L5; + } + __pyx_L5:; - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * # One could encode it in the format string and have Cython - * # complain instead, BUT: < and > in format strings also imply + /* "View.MemoryView":134 + * if isinstance(format, unicode): + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< + * self.format = self._format + * */ - __pyx_k_tuple_17 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_17)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_17)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_12)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 0, ((PyObject *)__pyx_kp_u_12)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_12)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_17)); + if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_v_format; + __Pyx_INCREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->_format); + __Pyx_DECREF(__pyx_v_self->_format); + __pyx_v_self->_format = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; - /* "numpy.pxd":819 - * t = child.type_num - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + /* "View.MemoryView":135 + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string + * self.format = self._format # <<<<<<<<<<<<<< + * * - * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_19 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_19)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_19)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_18)); - PyTuple_SET_ITEM(__pyx_k_tuple_19, 0, ((PyObject *)__pyx_kp_u_18)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_18)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_19)); - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} + __pyx_t_5 = __Pyx_PyObject_AsString(__pyx_v_self->_format); if (unlikely((!__pyx_t_5) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->format = __pyx_t_5; -static int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - return 0; - __pyx_L1_error:; - return -1; -} + /* "View.MemoryView":138 + * + * + * self._shape = PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< + * self._strides = self._shape + self.ndim + * + */ + __pyx_v_self->_shape = ((Py_ssize_t *)PyMem_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); -#if PY_MAJOR_VERSION < 3 -PyMODINIT_FUNC initcd_fast(void); /*proto*/ -PyMODINIT_FUNC initcd_fast(void) -#else -PyMODINIT_FUNC PyInit_cd_fast(void); /*proto*/ -PyMODINIT_FUNC PyInit_cd_fast(void) -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - __Pyx_RefNannyDeclarations - #if CYTHON_REFNANNY - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); - if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); + /* "View.MemoryView":139 + * + * self._shape = PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) + * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< + * + * if not self._shape: + */ + __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); + + /* "View.MemoryView":141 + * self._strides = self._shape + self.ndim + * + * if not self._shape: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape and strides.") + * + */ + __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":142 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_cd_fast(void)"); - if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __pyx_binding_PyCFunctionType_USED - if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #endif - /*--- Module creation code ---*/ - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("cd_fast"), __pyx_methods, 0, 0, PYTHON_API_VERSION); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); - #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - /*--- Initialize various global constants etc. ---*/ - if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_module_is_main_sklearn__linear_model__cd_fast) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + + /* "View.MemoryView":145 + * + * + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + __pyx_t_6 = 0; + __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; + for (;;) { + if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_7); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_t_8 = __Pyx_PyIndex_AsSsize_t(__pyx_t_7); if (unlikely((__pyx_t_8 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_dim = __pyx_t_8; + __pyx_v_idx = __pyx_t_6; + __pyx_t_6 = (__pyx_t_6 + 1); + + /* "View.MemoryView":146 + * + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim + */ + __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":147 + * for idx, dim in enumerate(shape): + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< + * self._shape[idx] = dim + * + */ + __pyx_t_7 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_7 = 0; + __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_10, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":148 + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim # <<<<<<<<<<<<<< + * + * cdef char order + */ + (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; + + /* "View.MemoryView":145 + * + * + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ } - /*--- Builtin init code ---*/ - if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Constants init code ---*/ - if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Global init code ---*/ - /*--- Variable export code ---*/ - /*--- Function export code ---*/ - /*--- Type init code ---*/ - /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), 0); if (unlikely(!__pyx_ptype_7cpython_4bool_bool)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), 0); if (unlikely(!__pyx_ptype_7cpython_7complex_complex)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Variable import code ---*/ - /*--- Function import code ---*/ - /*--- Execution code ---*/ + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":151 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = b'F' + * self.mode = u'fortran' + */ + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":152 + * cdef char order + * if mode == 'fortran': + * order = b'F' # <<<<<<<<<<<<<< + * self.mode = u'fortran' + * elif mode == 'c': + */ + __pyx_v_order = 'F'; + + /* "View.MemoryView":153 + * if mode == 'fortran': + * order = b'F' + * self.mode = u'fortran' # <<<<<<<<<<<<<< + * elif mode == 'c': + * order = b'C' + */ + __Pyx_INCREF(__pyx_n_u_fortran); + __Pyx_GIVEREF(__pyx_n_u_fortran); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(__pyx_v_self->mode); + __pyx_v_self->mode = __pyx_n_u_fortran; + goto __pyx_L10; + } + + /* "View.MemoryView":154 + * order = b'F' + * self.mode = u'fortran' + * elif mode == 'c': # <<<<<<<<<<<<<< + * order = b'C' + * self.mode = u'c' + */ + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":155 + * self.mode = u'fortran' + * elif mode == 'c': + * order = b'C' # <<<<<<<<<<<<<< + * self.mode = u'c' + * else: + */ + __pyx_v_order = 'C'; + + /* "View.MemoryView":156 + * elif mode == 'c': + * order = b'C' + * self.mode = u'c' # <<<<<<<<<<<<<< + * else: + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + */ + __Pyx_INCREF(__pyx_n_u_c); + __Pyx_GIVEREF(__pyx_n_u_c); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(__pyx_v_self->mode); + __pyx_v_self->mode = __pyx_n_u_c; + goto __pyx_L10; + } + /*else*/ { - /* "sklearn/linear_model/cd_fast.pyx":9 + /* "View.MemoryView":158 + * self.mode = u'c' + * else: + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< * - * cimport numpy as np - * import numpy as np # <<<<<<<<<<<<<< - * import numpy.linalg as linalg - * cimport cython + * self.len = fill_contig_strides_array(self._shape, self._strides, */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L10:; - /* "sklearn/linear_model/cd_fast.pyx":10 - * cimport numpy as np - * import numpy as np - * import numpy.linalg as linalg # <<<<<<<<<<<<<< - * cimport cython - * from cpython cimport bool + /* "View.MemoryView":160 + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + * + * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< + * itemsize, self.ndim, order) + * */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_n_s_21)); - PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s_21)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s_21)); - __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s_20), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__linalg, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); - /* "sklearn/linear_model/cd_fast.pyx":13 - * cimport cython - * from cpython cimport bool - * import warnings # <<<<<<<<<<<<<< + /* "View.MemoryView":163 + * itemsize, self.ndim, order) * - * cdef extern from "math.h": + * self.free_data = allocate_buffer # <<<<<<<<<<<<<< + * self.dtype_is_object = format == b'O' + * if allocate_buffer: */ - __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s__warnings), 0, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__warnings, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_self->free_data = __pyx_v_allocate_buffer; - /* "sklearn/linear_model/cd_fast.pyx":64 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def sparse_std(unsigned int n_samples, # <<<<<<<<<<<<<< - * unsigned int n_features, - * np.ndarray[DOUBLE, ndim=1] X_data, + /* "View.MemoryView":164 + * + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< + * if allocate_buffer: + * */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_7cd_fast_sparse_std, NULL, __pyx_n_s_22); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__sparse_std, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_4; - /* "sklearn/linear_model/cd_fast.pyx":110 - * np.ndarray[DOUBLE, ndim=2] X, - * np.ndarray[DOUBLE, ndim=1] y, - * int max_iter, double tol, bool positive=False): # <<<<<<<<<<<<<< - * """Cython version of the coordinate descent algorithm - * for Elastic-Net regression + /* "View.MemoryView":165 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * + * */ - __pyx_t_2 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_7cpython_4bool_bool)))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_1 = ((PyBoolObject *)__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; + __pyx_t_4 = (__pyx_v_allocate_buffer != 0); + if (__pyx_t_4) { - /* "sklearn/linear_model/cd_fast.pyx":106 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, # <<<<<<<<<<<<<< - * double alpha, double beta, - * np.ndarray[DOUBLE, ndim=2] X, + /* "View.MemoryView":168 + * + * + * self.data = malloc(self.len) # <<<<<<<<<<<<<< + * if not self.data: + * raise MemoryError("unable to allocate array data.") */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent, NULL, __pyx_n_s_22); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_23, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); - /* "sklearn/linear_model/cd_fast.pyx":225 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def sparse_enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, # <<<<<<<<<<<<<< - * double alpha, double beta, - * np.ndarray[DOUBLE, ndim=1] X_data, + /* "View.MemoryView":169 + * + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_7cd_fast_2sparse_enet_coordinate_descent, NULL, __pyx_n_s_22); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_24, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); + if (__pyx_t_4) { - /* "sklearn/linear_model/cd_fast.pyx":386 - * np.ndarray[DOUBLE, ndim=1] q, - * np.ndarray[DOUBLE, ndim=1] y, - * int max_iter, double tol, bool positive=False): # <<<<<<<<<<<<<< - * """Cython version of the coordinate descent algorithm - * for Elastic-Net regression + /* "View.MemoryView":170 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: */ - __pyx_t_2 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_7cpython_4bool_bool)))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_4 = ((PyBoolObject *)__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "sklearn/linear_model/cd_fast.pyx":381 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def enet_coordinate_descent_gram(np.ndarray[DOUBLE, ndim=1] w, # <<<<<<<<<<<<<< - * double alpha, double beta, - * np.ndarray[DOUBLE, ndim=2] Q, + /* "View.MemoryView":172 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_7cd_fast_3enet_coordinate_descent_gram, NULL, __pyx_n_s_22); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_25, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_4) { - /* "sklearn/linear_model/cd_fast.pyx":524 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def enet_coordinate_descent_multi_task(np.ndarray[DOUBLE, ndim=2, mode='fortran'] W, # <<<<<<<<<<<<<< - * double l1_reg, double l2_reg, - * np.ndarray[DOUBLE, ndim=2, mode='fortran'] X, + /* "View.MemoryView":173 + * + * if self.dtype_is_object: + * p = self.data # <<<<<<<<<<<<<< + * for i in range(self.len / itemsize): + * p[i] = Py_None */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_7cd_fast_4enet_coordinate_descent_multi_task, NULL, __pyx_n_s_22); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_26, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_p = ((PyObject **)__pyx_v_self->data); - /* "sklearn/linear_model/cd_fast.pyx":1 - * # Author: Alexandre Gramfort # <<<<<<<<<<<<<< - * # Fabian Pedregosa - * # Olivier Grisel + /* "View.MemoryView":174 + * if self.dtype_is_object: + * p = self.data + * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< + * p[i] = Py_None + * Py_INCREF(Py_None) */ - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_1; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; - /* "numpy.pxd":971 - * arr.base = baseptr + /* "View.MemoryView":175 + * p = self.data + * for i in range(self.len / itemsize): + * p[i] = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * if arr.base is NULL: - * return None */ + (__pyx_v_p[__pyx_v_i]) = Py_None; + + /* "View.MemoryView":176 + * for i in range(self.len / itemsize): + * p[i] = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + Py_INCREF(Py_None); + } + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - if (__pyx_m) { - __Pyx_AddTraceback("init sklearn.linear_model.cd_fast", __pyx_clineno, __pyx_lineno, __pyx_filename); - Py_DECREF(__pyx_m); __pyx_m = 0; - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init sklearn.linear_model.cd_fast"); - } + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; + __Pyx_XDECREF(__pyx_v_format); __Pyx_RefNannyFinishContext(); - #if PY_MAJOR_VERSION < 3 - return; - #else - return __pyx_m; - #endif + return __pyx_r; } -/* Runtime support code */ +/* "View.MemoryView":179 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == u"c": + */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule((char *)modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif /* CYTHON_REFNANNY */ +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } - } - return result; + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; } -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_bufmode; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + Py_ssize_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); - #endif -} + /* "View.MemoryView":180 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 # <<<<<<<<<<<<<< + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = -1; -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; + /* "View.MemoryView":181 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == u"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + */ + __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { - values[name-argnames] = value; - } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - } - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} + /* "View.MemoryView":182 + * cdef int bufmode = -1 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact) -{ - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; - } - if (none_allowed && obj == Py_None) return 1; - else if (exact) { - if (Py_TYPE(obj) == type) return 1; - } - else { - if (PyObject_TypeCheck(obj, type)) return 1; - } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; -} + /* "View.MemoryView":183 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ + __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { -static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { - unsigned int n = 1; - return *(unsigned char*)(&n) != 0; -} + /* "View.MemoryView":184 + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + */ + __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + __pyx_L3:; -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; -} __Pyx_BufFmt_Context; + /* "View.MemoryView":185 + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ + __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); + if (__pyx_t_1) { -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type) { - stack[0].field = &ctx->root; - stack[0].parent_offset = 0; - ctx->root.type = type; - ctx->root.name = "buffer dtype"; - ctx->root.offset = 0; - ctx->head = stack; - ctx->head->field = &ctx->root; - ctx->fmt_offset = 0; - ctx->head->parent_offset = 0; - ctx->new_packmode = '@'; - ctx->enc_packmode = '@'; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->is_complex = 0; - while (type->typegroup == 'S') { - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = 0; - type = type->fields->type; + /* "View.MemoryView":186 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__14, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } -} -static int __Pyx_BufFmt_ParseNumber(const char** ts) { - int count; - const char* t = *ts; - if (*t < '0' || *t > '9') { - return -1; - } else { - count = *t++ - '0'; - while (*t >= '0' && *t < '9') { - count *= 10; - count += *t++ - '0'; - } - } - *ts = t; - return count; -} + /* "View.MemoryView":187 + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data # <<<<<<<<<<<<<< + * info.len = self.len + * info.ndim = self.ndim + */ + __pyx_t_4 = __pyx_v_self->data; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":188 + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + * info.len = self.len # <<<<<<<<<<<<<< + * info.ndim = self.ndim + * info.shape = self._shape + */ + __pyx_t_5 = __pyx_v_self->len; + __pyx_v_info->len = __pyx_t_5; + + /* "View.MemoryView":189 + * info.buf = self.data + * info.len = self.len + * info.ndim = self.ndim # <<<<<<<<<<<<<< + * info.shape = self._shape + * info.strides = self._strides + */ + __pyx_t_6 = __pyx_v_self->ndim; + __pyx_v_info->ndim = __pyx_t_6; + + /* "View.MemoryView":190 + * info.len = self.len + * info.ndim = self.ndim + * info.shape = self._shape # <<<<<<<<<<<<<< + * info.strides = self._strides + * info.suboffsets = NULL + */ + __pyx_t_7 = __pyx_v_self->_shape; + __pyx_v_info->shape = __pyx_t_7; + + /* "View.MemoryView":191 + * info.ndim = self.ndim + * info.shape = self._shape + * info.strides = self._strides # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = self.itemsize + */ + __pyx_t_7 = __pyx_v_self->_strides; + __pyx_v_info->strides = __pyx_t_7; + + /* "View.MemoryView":192 + * info.shape = self._shape + * info.strides = self._strides + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = self.itemsize + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; -static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { - PyErr_Format(PyExc_ValueError, - "Unexpected format string character: '%c'", ch); -} + /* "View.MemoryView":193 + * info.strides = self._strides + * info.suboffsets = NULL + * info.itemsize = self.itemsize # <<<<<<<<<<<<<< + * info.readonly = 0 + * + */ + __pyx_t_5 = __pyx_v_self->itemsize; + __pyx_v_info->itemsize = __pyx_t_5; -static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { - switch (ch) { - case 'b': return "'char'"; - case 'B': return "'unsigned char'"; - case 'h': return "'short'"; - case 'H': return "'unsigned short'"; - case 'i': return "'int'"; - case 'I': return "'unsigned int'"; - case 'l': return "'long'"; - case 'L': return "'unsigned long'"; - case 'q': return "'long long'"; - case 'Q': return "'unsigned long long'"; - case 'f': return (is_complex ? "'complex float'" : "'float'"); - case 'd': return (is_complex ? "'complex double'" : "'double'"); - case 'g': return (is_complex ? "'complex long double'" : "'long double'"); - case 'T': return "a struct"; - case 'O': return "Python object"; - case 'P': return "a pointer"; - case 0: return "end"; - default: return "unparseable format string"; - } -} + /* "View.MemoryView":194 + * info.suboffsets = NULL + * info.itemsize = self.itemsize + * info.readonly = 0 # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->readonly = 0; -static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; - case 'h': case 'H': return 2; - case 'i': case 'I': case 'l': case 'L': return 4; - case 'q': case 'Q': return 8; - case 'f': return (is_complex ? 8 : 4); - case 'd': return (is_complex ? 16 : 8); - case 'g': { - PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); - return 0; - } - case 'O': case 'P': return sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} + /* "View.MemoryView":196 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { -static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { - switch (ch) { - case 'c': case 'b': case 'B': return 1; - case 'h': case 'H': return sizeof(short); - case 'i': case 'I': return sizeof(int); - case 'l': case 'L': return sizeof(long); - #ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(PY_LONG_LONG); - #endif - case 'f': return sizeof(float) * (is_complex ? 2 : 1); - case 'd': return sizeof(double) * (is_complex ? 2 : 1); - case 'g': return sizeof(long double) * (is_complex ? 2 : 1); - case 'O': case 'P': return sizeof(void*); - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } + /* "View.MemoryView":197 + * + * if flags & PyBUF_FORMAT: + * info.format = self.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_4 = __pyx_v_self->format; + __pyx_v_info->format = __pyx_t_4; + goto __pyx_L5; } -} + /*else*/ { -typedef struct { char c; short x; } __Pyx_st_short; -typedef struct { char c; int x; } __Pyx_st_int; -typedef struct { char c; long x; } __Pyx_st_long; -typedef struct { char c; float x; } __Pyx_st_float; -typedef struct { char c; double x; } __Pyx_st_double; -typedef struct { char c; long double x; } __Pyx_st_longdouble; -typedef struct { char c; void *x; } __Pyx_st_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; -#endif + /* "View.MemoryView":199 + * info.format = self.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.obj = self + */ + __pyx_v_info->format = NULL; + } + __pyx_L5:; -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; - case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_st_float) - sizeof(float); - case 'd': return sizeof(__Pyx_st_double) - sizeof(double); - case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} + /* "View.MemoryView":201 + * info.format = NULL + * + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); -static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { - switch (ch) { - case 'c': case 'b': case 'h': case 'i': case 'l': case 'q': return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; - case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); - case 'O': return 'O'; - case 'P': return 'P'; - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } + /* "View.MemoryView":179 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == u"c": + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; } -static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { - if (ctx->head == NULL || ctx->head->field == &ctx->root) { - const char* expected; - const char* quote; - if (ctx->head == NULL) { - expected = "end"; - quote = ""; - } else { - expected = ctx->head->field->type->name; - quote = "'"; - } - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected %s%s%s but got %s", - quote, expected, quote, - __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); - } else { - __Pyx_StructField* field = ctx->head->field; - __Pyx_StructField* parent = (ctx->head - 1)->field; - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", - field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), - parent->type->name, field->name); - } +/* "View.MemoryView":205 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + +/* Python wrapper */ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_array_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); } -static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { - char group; - size_t size, offset; - if (ctx->enc_type == 0) return 0; - group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); - do { - __Pyx_StructField* field = ctx->head->field; - __Pyx_TypeInfo* type = field->type; +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__dealloc__", 0); - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { - size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); - } else { - size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); - } - if (ctx->enc_packmode == '@') { - size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); - size_t align_mod_offset; - if (align_at == 0) return -1; - align_mod_offset = ctx->fmt_offset % align_at; - if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; - } + /* "View.MemoryView":206 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ + __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); + if (__pyx_t_1) { - if (type->size != size || type->typegroup != group) { - if (type->typegroup == 'C' && type->fields != NULL) { - /* special case -- treat as struct rather than complex number */ - size_t parent_offset = ctx->head->parent_offset + field->offset; - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = parent_offset; - continue; - } + /* "View.MemoryView":207 + * def __dealloc__(array self): + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) # <<<<<<<<<<<<<< + * elif self.free_data: + * if self.dtype_is_object: + */ + __pyx_v_self->callback_free_data(__pyx_v_self->data); + goto __pyx_L3; + } - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } + /* "View.MemoryView":208 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ + __pyx_t_1 = (__pyx_v_self->free_data != 0); + if (__pyx_t_1) { - offset = ctx->head->parent_offset + field->offset; - if (ctx->fmt_offset != offset) { - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", - (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); - return -1; + /* "View.MemoryView":209 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":210 + * elif self.free_data: + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< + * self._strides, self.ndim, False) + * free(self.data) + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); + goto __pyx_L4; } + __pyx_L4:; - ctx->fmt_offset += size; + /* "View.MemoryView":212 + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + * free(self.data) # <<<<<<<<<<<<<< + * PyMem_Free(self._shape) + * + */ + free(__pyx_v_self->data); + goto __pyx_L3; + } + __pyx_L3:; - --ctx->enc_count; /* Consume from buffer string */ + /* "View.MemoryView":213 + * self._strides, self.ndim, False) + * free(self.data) + * PyMem_Free(self._shape) # <<<<<<<<<<<<<< + * + * property memview: + */ + PyMem_Free(__pyx_v_self->_shape); - /* Done checking, move to next field, pushing or popping struct stack if needed */ - while (1) { - if (field == &ctx->root) { - ctx->head = NULL; - if (ctx->enc_count != 0) { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - break; /* breaks both loops as ctx->enc_count == 0 */ - } - ctx->head->field = ++field; - if (field->type == NULL) { - --ctx->head; - field = ctx->head->field; - continue; - } else if (field->type->typegroup == 'S') { - size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; /* empty struct */ - field = field->type->fields; - ++ctx->head; - ctx->head->field = field; - ctx->head->parent_offset = parent_offset; - break; - } else { - break; - } - } - } while (ctx->enc_count); - ctx->enc_type = 0; - ctx->is_complex = 0; - return 0; + /* "View.MemoryView":205 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); } -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { - int got_Z = 0; - while (1) { - switch(*ts) { - case 0: - if (ctx->enc_type != 0 && ctx->head == NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - if (ctx->head != NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - return ts; - case ' ': - case 10: - case 13: - ++ts; - break; - case '<': - if (!__Pyx_IsLittleEndian()) { - PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '>': - case '!': - if (__Pyx_IsLittleEndian()) { - PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '=': - case '@': - case '^': - ctx->new_packmode = *ts++; - break; - case 'T': /* substruct */ - { - const char* ts_after_sub; - size_t i, struct_count = ctx->new_count; +/* "View.MemoryView":217 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + +/* Python wrapper */ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = get_memview_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":219 + * def __get__(self): + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< + * return memoryview(self, flags, self.dtype_is_object) + * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":220 + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":217 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":223 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":224 + * + * def __getattr__(self, attr): + * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * + * def __getitem__(self, item): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":223 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":226 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":227 + * + * def __getitem__(self, item): + * return self.memview[item] # <<<<<<<<<<<<<< + * + * def __setitem__(self, item, value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":226 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":229 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + +/* Python wrapper */ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "View.MemoryView":230 + * + * def __setitem__(self, item, value): + * self.memview[item] = value # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":229 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":234 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + +static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { + struct __pyx_array_obj *__pyx_v_result = 0; + struct __pyx_array_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("array_cwrapper", 0); + + /* "View.MemoryView":238 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":239 + * + * if buf == NULL: + * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":241 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":242 + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) # <<<<<<<<<<<<<< + * result.data = buf + * + */ + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":241 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":243 + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) + * result.data = buf # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->data = __pyx_v_buf; + } + __pyx_L3:; + + /* "View.MemoryView":245 + * result.data = buf + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":234 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":271 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + +/* Python wrapper */ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_name = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_name = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "View.MemoryView":272 + * cdef object name + * def __init__(self, name): + * self.name = name # <<<<<<<<<<<<<< + * def __repr__(self): + * return self.name + */ + __Pyx_INCREF(__pyx_v_name); + __Pyx_GIVEREF(__pyx_v_name); + __Pyx_GOTREF(__pyx_v_self->name); + __Pyx_DECREF(__pyx_v_self->name); + __pyx_v_self->name = __pyx_v_name; + + /* "View.MemoryView":271 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":273 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + +/* Python wrapper */ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":274 + * self.name = name + * def __repr__(self): + * return self.name # <<<<<<<<<<<<<< + * + * cdef generic = Enum("") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->name); + __pyx_r = __pyx_v_self->name; + goto __pyx_L0; + + /* "View.MemoryView":273 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":288 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + +static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { + Py_intptr_t __pyx_v_aligned_p; + size_t __pyx_v_offset; + void *__pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":290 + * cdef void *align_pointer(void *memory, size_t alignment) nogil: + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< + * cdef size_t offset + * + */ + __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + + /* "View.MemoryView":294 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":296 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + __pyx_t_1 = ((__pyx_v_offset > 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":297 + * + * if offset > 0: + * aligned_p += alignment - offset # <<<<<<<<<<<<<< + * + * return aligned_p + */ + __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":299 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview') + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + /* "View.MemoryView":288 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":317 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + +/* Python wrapper */ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_obj = 0; + int __pyx_v_flags; + int __pyx_v_dtype_is_object; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dtype_is_object); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_obj = values[0]; + __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[2]) { + __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_dtype_is_object = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_memoryview_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "View.MemoryView":318 + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj # <<<<<<<<<<<<<< + * self.flags = flags + * if type(self) is memoryview or obj is not None: + */ + __Pyx_INCREF(__pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __Pyx_GOTREF(__pyx_v_self->obj); + __Pyx_DECREF(__pyx_v_self->obj); + __pyx_v_self->obj = __pyx_v_obj; + + /* "View.MemoryView":319 + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj + * self.flags = flags # <<<<<<<<<<<<<< + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + */ + __pyx_v_self->flags = __pyx_v_flags; + + /* "View.MemoryView":320 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ + __pyx_t_2 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type))); + __pyx_t_3 = (__pyx_t_2 != 0); + if (!__pyx_t_3) { + goto __pyx_L5_next_or; + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + __pyx_L5_next_or:; + __pyx_t_3 = (__pyx_v_obj != Py_None); + __pyx_t_2 = (__pyx_t_3 != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L4_bool_binop_done:; + if (__pyx_t_1) { + + /* "View.MemoryView":321 + * self.flags = flags + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + */ + __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":322 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":323 + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; + + /* "View.MemoryView":324 + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * self.lock = PyThread_allocate_lock() + */ + Py_INCREF(Py_None); + goto __pyx_L6; + } + __pyx_L6:; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":326 + * Py_INCREF(Py_None) + * + * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< + * if self.lock == NULL: + * raise MemoryError + */ + __pyx_v_self->lock = PyThread_allocate_lock(); + + /* "View.MemoryView":327 + * + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":328 + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":330 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = self.view.format == b'O' + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":331 + * + * if flags & PyBUF_FORMAT: + * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< + * else: + * self.dtype_is_object = dtype_is_object + */ + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_5, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_1; + goto __pyx_L8; + } + /*else*/ { + + /* "View.MemoryView":333 + * self.dtype_is_object = self.view.format == b'O' + * else: + * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + */ + __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; + } + __pyx_L8:; + + /* "View.MemoryView":335 + * self.dtype_is_object = dtype_is_object + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL + */ + __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); + + /* "View.MemoryView":337 + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(memoryview self): + */ + __pyx_v_self->typeinfo = NULL; + + /* "View.MemoryView":317 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":339 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + +/* Python wrapper */ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":340 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< + * __Pyx_ReleaseBuffer(&self.view) + * + */ + __pyx_t_1 = (__pyx_v_self->obj != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":341 + * def __dealloc__(memoryview self): + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< + * + * if self.lock != NULL: + */ + __Pyx_ReleaseBuffer((&__pyx_v_self->view)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":343 + * __Pyx_ReleaseBuffer(&self.view) + * + * if self.lock != NULL: # <<<<<<<<<<<<<< + * PyThread_free_lock(self.lock) + * + */ + __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":344 + * + * if self.lock != NULL: + * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + */ + PyThread_free_lock(__pyx_v_self->lock); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":339 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":346 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + Py_ssize_t __pyx_v_dim; + char *__pyx_v_itemp; + PyObject *__pyx_v_idx = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_item_pointer", 0); + + /* "View.MemoryView":348 + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< + * + * for dim, idx in enumerate(index): + */ + __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); + + /* "View.MemoryView":350 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + __pyx_t_1 = 0; + if (likely(PyList_CheckExact(__pyx_v_index)) || PyTuple_CheckExact(__pyx_v_index)) { + __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + for (;;) { + if (likely(!__pyx_t_4)) { + if (likely(PyList_CheckExact(__pyx_t_2))) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); + __pyx_t_5 = 0; + __pyx_v_dim = __pyx_t_1; + __pyx_t_1 = (__pyx_t_1 + 1); + + /* "View.MemoryView":351 + * + * for dim, idx in enumerate(index): + * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< + * + * return itemp + */ + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_7; + + /* "View.MemoryView":350 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":353 + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + * return itemp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_itemp; + goto __pyx_L0; + + /* "View.MemoryView":346 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":356 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_indices = NULL; + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + char *__pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":357 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":358 + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: + * return self # <<<<<<<<<<<<<< + * + * have_slices, indices = _unellipsify(index, self.view.ndim) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __pyx_r = ((PyObject *)__pyx_v_self); + goto __pyx_L0; + } + + /* "View.MemoryView":360 + * return self + * + * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * cdef char *itemp + */ + __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (likely(__pyx_t_3 != Py_None)) { + PyObject* sequence = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_have_slices = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; + + /* "View.MemoryView":363 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":364 + * cdef char *itemp + * if have_slices: + * return memview_slice(self, indices) # <<<<<<<<<<<<<< + * else: + * itemp = self.get_item_pointer(indices) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 364; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":366 + * return memview_slice(self, indices) + * else: + * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< + * return self.convert_item_to_object(itemp) + * + */ + __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_6; + + /* "View.MemoryView":367 + * else: + * itemp = self.get_item_pointer(indices) + * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< + * + * def __setitem__(memoryview self, object index, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 367; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":356 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":369 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + +/* Python wrapper */ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_obj = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_INCREF(__pyx_v_index); + + /* "View.MemoryView":370 + * + * def __setitem__(memoryview self, object index, object value): + * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * if have_slices: + */ + __pyx_t_1 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (likely(__pyx_t_1 != Py_None)) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_have_slices = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":372 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":373 + * + * if have_slices: + * obj = self.is_slice(value) # <<<<<<<<<<<<<< + * if obj: + * self.setitem_slice_assignment(self[index], obj) + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_obj = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":374 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":375 + * obj = self.is_slice(value) + * if obj: + * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< + * else: + * self.setitem_slice_assign_scalar(self[index], value) + */ + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":377 + * self.setitem_slice_assignment(self[index], obj) + * else: + * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< + * else: + * self.setitem_indexed(index, value) + */ + __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":379 + * self.setitem_slice_assign_scalar(self[index], value) + * else: + * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< + * + * cdef is_slice(self, obj): + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":369 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":381 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_slice", 0); + __Pyx_INCREF(__pyx_v_obj); + + /* "View.MemoryView":382 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type)); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":383 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + { + __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + /*try:*/ { + + /* "View.MemoryView":384 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_6 = __Pyx_PyInt_From_int((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":385 + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * except TypeError: + * return None + */ + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":384 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); + __pyx_t_7 = 0; + } + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L11_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":386 + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + * except TypeError: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":387 + * self.dtype_is_object) + * except TypeError: + * return None # <<<<<<<<<<<<<< + * + * return obj + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L7_except_return; + } + goto __pyx_L6_except_error; + __pyx_L6_except_error:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L1_error; + __pyx_L7_except_return:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L0; + __pyx_L11_try_end:; + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":389 + * return None + * + * return obj # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assignment(self, dst, src): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_obj); + __pyx_r = __pyx_v_obj; + goto __pyx_L0; + + /* "View.MemoryView":381 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":391 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { + __Pyx_memviewslice __pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_src_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); + + /* "View.MemoryView":395 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":396 + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< + * src.ndim, dst.ndim, self.dtype_is_object) + * + */ + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":397 + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":395 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":391 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":399 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { + int __pyx_v_array[128]; + void *__pyx_v_tmp; + void *__pyx_v_item; + __Pyx_memviewslice *__pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_tmp_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + char const *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); + + /* "View.MemoryView":401 + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + * cdef int array[128] + * cdef void *tmp = NULL # <<<<<<<<<<<<<< + * cdef void *item + * + */ + __pyx_v_tmp = NULL; + + /* "View.MemoryView":406 + * cdef __Pyx_memviewslice *dst_slice + * cdef __Pyx_memviewslice tmp_slice + * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< + * + * if self.view.itemsize > sizeof(array): + */ + __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); + + /* "View.MemoryView":408 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + */ + __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":409 + * + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError + */ + __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); + + /* "View.MemoryView":410 + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":411 + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * item = tmp + * else: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":412 + * if tmp == NULL: + * raise MemoryError + * item = tmp # <<<<<<<<<<<<<< + * else: + * item = array + */ + __pyx_v_item = __pyx_v_tmp; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":414 + * item = tmp + * else: + * item = array # <<<<<<<<<<<<<< + * + * try: + */ + __pyx_v_item = ((void *)__pyx_v_array); + } + __pyx_L3:; + + /* "View.MemoryView":416 + * item = array + * + * try: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * ( item)[0] = value + */ + /*try:*/ { + + /* "View.MemoryView":417 + * + * try: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":418 + * try: + * if self.dtype_is_object: + * ( item)[0] = value # <<<<<<<<<<<<<< + * else: + * self.assign_item_from_object( item, value) + */ + (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); + goto __pyx_L8; + } + /*else*/ { + + /* "View.MemoryView":420 + * ( item)[0] = value + * else: + * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_L8:; + + /* "View.MemoryView":424 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":425 + * + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + */ + __pyx_t_2 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":426 + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< + * item, self.dtype_is_object) + * finally: + */ + __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); + } + + /* "View.MemoryView":429 + * item, self.dtype_is_object) + * finally: + * PyMem_Free(tmp) # <<<<<<<<<<<<<< + * + * cdef setitem_indexed(self, index, value): + */ + /*finally:*/ { + /*normal exit:*/{ + PyMem_Free(__pyx_v_tmp); + goto __pyx_L7; + } + /*exception exit:*/{ + __pyx_L6_error:; + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8) < 0)) __Pyx_ErrFetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_11); + __pyx_t_3 = __pyx_lineno; __pyx_t_4 = __pyx_clineno; __pyx_t_5 = __pyx_filename; + { + PyMem_Free(__pyx_v_tmp); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } + __Pyx_XGIVEREF(__pyx_t_6); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_ErrRestore(__pyx_t_6, __pyx_t_7, __pyx_t_8); + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __pyx_lineno = __pyx_t_3; __pyx_clineno = __pyx_t_4; __pyx_filename = __pyx_t_5; + goto __pyx_L1_error; + } + __pyx_L7:; + } + + /* "View.MemoryView":399 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":431 + * PyMem_Free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_indexed", 0); + + /* "View.MemoryView":432 + * + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< + * self.assign_item_from_object(itemp, value) + * + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_1; + + /* "View.MemoryView":433 + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":431 + * PyMem_Free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":435 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_v_struct = NULL; + PyObject *__pyx_v_bytesitem = 0; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + size_t __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":438 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef bytes bytesitem + * + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":441 + * cdef bytes bytesitem + * + * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< + * try: + * result = struct.unpack(self.view.format, bytesitem) + */ + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":442 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":443 + * bytesitem = itemp[:self.view.itemsize] + * try: + * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< + * except struct.error: + * raise ValueError("Unable to convert item to object") + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = NULL; + __pyx_t_8 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_5, function); + __pyx_t_8 = 1; + } + } + __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_9); + if (__pyx_t_7) { + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); __pyx_t_7 = NULL; + } + PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_INCREF(__pyx_v_bytesitem); + PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_bytesitem); + __Pyx_GIVEREF(__pyx_v_bytesitem); + __pyx_t_6 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_result = __pyx_t_1; + __pyx_t_1 = 0; + } + /*else:*/ { + + /* "View.MemoryView":447 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + __pyx_t_10 = strlen(__pyx_v_self->view.format); + __pyx_t_11 = ((__pyx_t_10 == 1) != 0); + if (__pyx_t_11) { + + /* "View.MemoryView":448 + * else: + * if len(self.view.format) == 1: + * return result[0] # <<<<<<<<<<<<<< + * return result + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L6_except_return; + } + + /* "View.MemoryView":449 + * if len(self.view.format) == 1: + * return result[0] + * return result # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L6_except_return; + } + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":444 + * try: + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: # <<<<<<<<<<<<<< + * raise ValueError("Unable to convert item to object") + * else: + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_12 = PyErr_ExceptionMatches(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_12) { + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_9); + + /* "View.MemoryView":445 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + } + goto __pyx_L5_except_error; + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L6_except_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + } + + /* "View.MemoryView":435 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesitem); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":451 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_v_struct = NULL; + char __pyx_v_c; + PyObject *__pyx_v_bytesvalue = 0; + Py_ssize_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + char *__pyx_t_10; + char *__pyx_t_11; + char *__pyx_t_12; + char *__pyx_t_13; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":454 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef char c + * cdef bytes bytesvalue + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":459 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + __pyx_t_2 = PyTuple_Check(__pyx_v_value); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":460 + * + * if isinstance(value, tuple): + * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< + * else: + * bytesvalue = struct.pack(self.view.format, value) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":462 + * bytesvalue = struct.pack(self.view.format, *value) + * else: + * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< + * + * for i, c in enumerate(bytesvalue): + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = NULL; + __pyx_t_7 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_6, function); + __pyx_t_7 = 1; + } + } + __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (__pyx_t_5) { + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; + } + PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + __pyx_t_1 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":464 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = 0; + if (unlikely(__pyx_v_bytesvalue == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_INCREF(__pyx_v_bytesvalue); + __pyx_t_9 = __pyx_v_bytesvalue; + __pyx_t_11 = PyBytes_AS_STRING(__pyx_t_9); + __pyx_t_12 = (__pyx_t_11 + PyBytes_GET_SIZE(__pyx_t_9)); + for (__pyx_t_13 = __pyx_t_11; __pyx_t_13 < __pyx_t_12; __pyx_t_13++) { + __pyx_t_10 = __pyx_t_13; + __pyx_v_c = (__pyx_t_10[0]); + + /* "View.MemoryView":465 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + __pyx_v_i = __pyx_t_7; + + /* "View.MemoryView":464 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":465 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; + } + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "View.MemoryView":451 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":468 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + char *__pyx_t_3; + void *__pyx_t_4; + int __pyx_t_5; + Py_ssize_t __pyx_t_6; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":469 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":470 + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape # <<<<<<<<<<<<<< + * else: + * info.shape = NULL + */ + __pyx_t_2 = __pyx_v_self->view.shape; + __pyx_v_info->shape = __pyx_t_2; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":472 + * info.shape = self.view.shape + * else: + * info.shape = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_STRIDES: + */ + __pyx_v_info->shape = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":474 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":475 + * + * if flags & PyBUF_STRIDES: + * info.strides = self.view.strides # <<<<<<<<<<<<<< + * else: + * info.strides = NULL + */ + __pyx_t_2 = __pyx_v_self->view.strides; + __pyx_v_info->strides = __pyx_t_2; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":477 + * info.strides = self.view.strides + * else: + * info.strides = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_INDIRECT: + */ + __pyx_v_info->strides = NULL; + } + __pyx_L4:; + + /* "View.MemoryView":479 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":480 + * + * if flags & PyBUF_INDIRECT: + * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< + * else: + * info.suboffsets = NULL + */ + __pyx_t_2 = __pyx_v_self->view.suboffsets; + __pyx_v_info->suboffsets = __pyx_t_2; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":482 + * info.suboffsets = self.view.suboffsets + * else: + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->suboffsets = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":484 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":485 + * + * if flags & PyBUF_FORMAT: + * info.format = self.view.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_3 = __pyx_v_self->view.format; + __pyx_v_info->format = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":487 + * info.format = self.view.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.buf = self.view.buf + */ + __pyx_v_info->format = NULL; + } + __pyx_L6:; + + /* "View.MemoryView":489 + * info.format = NULL + * + * info.buf = self.view.buf # <<<<<<<<<<<<<< + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + */ + __pyx_t_4 = __pyx_v_self->view.buf; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":490 + * + * info.buf = self.view.buf + * info.ndim = self.view.ndim # <<<<<<<<<<<<<< + * info.itemsize = self.view.itemsize + * info.len = self.view.len + */ + __pyx_t_5 = __pyx_v_self->view.ndim; + __pyx_v_info->ndim = __pyx_t_5; + + /* "View.MemoryView":491 + * info.buf = self.view.buf + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< + * info.len = self.view.len + * info.readonly = 0 + */ + __pyx_t_6 = __pyx_v_self->view.itemsize; + __pyx_v_info->itemsize = __pyx_t_6; + + /* "View.MemoryView":492 + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + * info.len = self.view.len # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.obj = self + */ + __pyx_t_6 = __pyx_v_self->view.len; + __pyx_v_info->len = __pyx_t_6; + + /* "View.MemoryView":493 + * info.itemsize = self.view.itemsize + * info.len = self.view.len + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.obj = self + * + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":494 + * info.len = self.view.len + * info.readonly = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "View.MemoryView":468 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + + /* function exit code */ + __pyx_r = 0; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":501 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":502 + * @cname('__pyx_memoryview_transpose') + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< + * transpose_memslice(&result.from_slice) + * return result + */ + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":503 + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":504 + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + * return result # <<<<<<<<<<<<<< + * + * property base: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":501 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":508 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":509 + * @cname('__pyx_memoryview__get__base') + * def __get__(self): + * return self.obj # <<<<<<<<<<<<<< + * + * property shape: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->obj); + __pyx_r = __pyx_v_self->obj; + goto __pyx_L0; + + /* "View.MemoryView":508 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":513 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":514 + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property strides: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_v_self->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->view.shape[__pyx_v_i])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __pyx_t_4 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + + /* "View.MemoryView":513 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":518 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":519 + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":521 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":523 + * raise ValueError("Buffer view does not expose strides") + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property suboffsets: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.strides[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":518 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":527 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":528 + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return [-1] * self.view.ndim + * + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":529 + * def __get__(self): + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(1 * ((__pyx_v_self->view.ndim<0) ? 0:__pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_self->view.ndim; __pyx_temp++) { + __Pyx_INCREF(__pyx_int_neg_1); + PyList_SET_ITEM(__pyx_t_2, __pyx_temp, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + } + } + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":531 + * return [-1] * self.view.ndim + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property ndim: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.suboffsets[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":527 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":535 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":536 + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): + * return self.view.ndim # <<<<<<<<<<<<<< + * + * property itemsize: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":535 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":540 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":541 + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): + * return self.view.itemsize # <<<<<<<<<<<<<< + * + * property nbytes: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 541; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":540 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":545 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":546 + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): + * return self.size * self.view.itemsize # <<<<<<<<<<<<<< + * + * property size: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":545 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":550 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":551 + * @cname('__pyx_memoryview_get_size') + * def __get__(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + __pyx_t_1 = (__pyx_v_self->_size == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":552 + * def __get__(self): + * if self._size is None: + * result = 1 # <<<<<<<<<<<<<< + * + * for length in self.shape: + */ + __Pyx_INCREF(__pyx_int_1); + __pyx_v_result = __pyx_int_1; + + /* "View.MemoryView":554 + * result = 1 + * + * for length in self.shape: # <<<<<<<<<<<<<< + * result *= length + * + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (likely(PyList_CheckExact(__pyx_t_3)) || PyTuple_CheckExact(__pyx_t_3)) { + __pyx_t_4 = __pyx_t_3; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_4))) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } + } else { + __pyx_t_3 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_3)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":555 + * + * for length in self.shape: + * result *= length # <<<<<<<<<<<<<< + * + * self._size = result + */ + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 555; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":554 + * result = 1 + * + * for length in self.shape: # <<<<<<<<<<<<<< + * result *= length + * + */ + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "View.MemoryView":557 + * result *= length + * + * self._size = result # <<<<<<<<<<<<<< + * + * return self._size + */ + __Pyx_INCREF(__pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __Pyx_GOTREF(__pyx_v_self->_size); + __Pyx_DECREF(__pyx_v_self->_size); + __pyx_v_self->_size = __pyx_v_result; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":559 + * self._size = result + * + * return self._size # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->_size); + __pyx_r = __pyx_v_self->_size; + goto __pyx_L0; + + /* "View.MemoryView":550 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":561 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + +/* Python wrapper */ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__len__", 0); + + /* "View.MemoryView":562 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":563 + * def __len__(self): + * if self.view.ndim >= 1: + * return self.view.shape[0] # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_r = (__pyx_v_self->view.shape[0]); + goto __pyx_L0; + } + + /* "View.MemoryView":565 + * return self.view.shape[0] + * + * return 0 # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":561 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":567 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":568 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":569 + * def __repr__(self): + * return "" % (self.base.__class__.__name__, + * id(self)) # <<<<<<<<<<<<<< + * + * def __str__(self): + */ + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_id, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":568 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":567 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":571 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__str__", 0); + + /* "View.MemoryView":572 + * + * def __str__(self): + * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":571 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":575 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_c_contig", 0); + + /* "View.MemoryView":578 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":579 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< + * + * def is_f_contig(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":575 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":581 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_f_contig", 0); + + /* "View.MemoryView":584 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":585 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< + * + * def copy(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":581 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":587 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_mslice; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "View.MemoryView":589 + * def copy(self): + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &mslice) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); + + /* "View.MemoryView":591 + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + * + * slice_copy(self, &mslice) # <<<<<<<<<<<<<< + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); + + /* "View.MemoryView":592 + * + * slice_copy(self, &mslice) + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_C_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k_c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":597 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< + * + * def copy_fortran(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":587 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":599 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy_fortran", 0); + + /* "View.MemoryView":601 + * def copy_fortran(self): + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &src) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); + + /* "View.MemoryView":603 + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + * + * slice_copy(self, &src) # <<<<<<<<<<<<<< + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); + + /* "View.MemoryView":604 + * + * slice_copy(self, &src) + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_F_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k_fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dst = __pyx_t_1; + + /* "View.MemoryView":609 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":599 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":613 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + +static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { + struct __pyx_memoryview_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); + + /* "View.MemoryView":614 + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< + * result.typeinfo = typeinfo + * return result + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); + __Pyx_GIVEREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":615 + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_v_result->typeinfo = __pyx_v_typeinfo; + + /* "View.MemoryView":616 + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_check') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":613 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":619 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("memoryview_check", 0); + + /* "View.MemoryView":620 + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): + * return isinstance(o, memoryview) # <<<<<<<<<<<<<< + * + * cdef tuple _unellipsify(object index, int ndim): + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type)); + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + /* "View.MemoryView":619 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":622 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + +static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { + PyObject *__pyx_v_tup = NULL; + PyObject *__pyx_v_result = NULL; + int __pyx_v_have_slices; + int __pyx_v_seen_ellipsis; + CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_item = NULL; + Py_ssize_t __pyx_v_nslices; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_unellipsify", 0); + + /* "View.MemoryView":627 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + __pyx_t_1 = PyTuple_Check(__pyx_v_index); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":628 + * """ + * if not isinstance(index, tuple): + * tup = (index,) # <<<<<<<<<<<<<< + * else: + * tup = index + */ + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_index); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); + __Pyx_GIVEREF(__pyx_v_index); + __pyx_v_tup = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":630 + * tup = (index,) + * else: + * tup = index # <<<<<<<<<<<<<< + * + * result = [] + */ + __Pyx_INCREF(__pyx_v_index); + __pyx_v_tup = __pyx_v_index; + } + __pyx_L3:; + + /* "View.MemoryView":632 + * tup = index + * + * result = [] # <<<<<<<<<<<<<< + * have_slices = False + * seen_ellipsis = False + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_result = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":633 + * + * result = [] + * have_slices = False # <<<<<<<<<<<<<< + * seen_ellipsis = False + * for idx, item in enumerate(tup): + */ + __pyx_v_have_slices = 0; + + /* "View.MemoryView":634 + * result = [] + * have_slices = False + * seen_ellipsis = False # <<<<<<<<<<<<<< + * for idx, item in enumerate(tup): + * if item is Ellipsis: + */ + __pyx_v_seen_ellipsis = 0; + + /* "View.MemoryView":635 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_3 = __pyx_int_0; + if (likely(PyList_CheckExact(__pyx_v_tup)) || PyTuple_CheckExact(__pyx_v_tup)) { + __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_4))) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } + } else { + __pyx_t_7 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_7)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); + __pyx_t_7 = 0; + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); + __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_t_7; + __pyx_t_7 = 0; + + /* "View.MemoryView":636 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ + __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":637 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ + __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":638 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { + __Pyx_INCREF(__pyx_slice__17); + PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__17); + __Pyx_GIVEREF(__pyx_slice__17); + } + } + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":639 + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True # <<<<<<<<<<<<<< + * else: + * result.append(slice(None)) + */ + __pyx_v_seen_ellipsis = 1; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":641 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__18); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + + /* "View.MemoryView":642 + * else: + * result.append(slice(None)) + * have_slices = True # <<<<<<<<<<<<<< + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + */ + __pyx_v_have_slices = 1; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":644 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ + __pyx_t_2 = PySlice_Check(__pyx_v_item); + __pyx_t_10 = ((!(__pyx_t_2 != 0)) != 0); + if (__pyx_t_10) { + goto __pyx_L10_next_and; + } else { + __pyx_t_1 = __pyx_t_10; + goto __pyx_L9_bool_binop_done; + } + __pyx_L10_next_and:; + __pyx_t_10 = ((!(PyIndex_Check(__pyx_v_item) != 0)) != 0); + __pyx_t_1 = __pyx_t_10; + __pyx_L9_bool_binop_done:; + if (__pyx_t_1) { + + /* "View.MemoryView":645 + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< + * + * have_slices = have_slices or isinstance(item, slice) + */ + __pyx_t_7 = __Pyx_PyString_Format(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_11 = PyTuple_New(1); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_11, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_Raise(__pyx_t_7, 0, 0, 0); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":647 + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< + * result.append(item) + * + */ + __pyx_t_10 = (__pyx_v_have_slices != 0); + if (!__pyx_t_10) { + goto __pyx_L12_next_or; + } else { + __pyx_t_1 = __pyx_t_10; + goto __pyx_L11_bool_binop_done; + } + __pyx_L12_next_or:; + __pyx_t_10 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = (__pyx_t_10 != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L11_bool_binop_done:; + __pyx_v_have_slices = __pyx_t_1; + + /* "View.MemoryView":648 + * + * have_slices = have_slices or isinstance(item, slice) + * result.append(item) # <<<<<<<<<<<<<< + * + * nslices = ndim - len(result) + */ + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L6:; + + /* "View.MemoryView":635 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":650 + * result.append(item) + * + * nslices = ndim - len(result) # <<<<<<<<<<<<<< + * if nslices: + * result.extend([slice(None)] * nslices) + */ + __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); + + /* "View.MemoryView":651 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + __pyx_t_1 = (__pyx_v_nslices != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":652 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { + __Pyx_INCREF(__pyx_slice__19); + PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__19); + __Pyx_GIVEREF(__pyx_slice__19); + } + } + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L13; + } + __pyx_L13:; + + /* "View.MemoryView":654 + * result.extend([slice(None)] * nslices) + * + * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + */ + __Pyx_XDECREF(__pyx_r); + if (!__pyx_v_have_slices) { + goto __pyx_L15_next_or; + } else { + __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L14_bool_binop_done; + } + __pyx_L15_next_or:; + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_L14_bool_binop_done:; + __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_r = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + goto __pyx_L0; + + /* "View.MemoryView":622 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_tup); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_item); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":656 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + +static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); + + /* "View.MemoryView":658 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * cdef int i + * for i in range(ndim): # <<<<<<<<<<<<<< + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":659 + * cdef int i + * for i in range(ndim): + * if suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ + __pyx_t_3 = (((__pyx_v_suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":660 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + + /* "View.MemoryView":656 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":667 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { + int __pyx_v_new_ndim; + int __pyx_v_suboffset_dim; + int __pyx_v_dim; + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + __Pyx_memviewslice *__pyx_v_p_src; + struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; + __Pyx_memviewslice *__pyx_v_p_dst; + int *__pyx_v_p_suboffset_dim; + Py_ssize_t __pyx_v_start; + Py_ssize_t __pyx_v_stop; + Py_ssize_t __pyx_v_step; + int __pyx_v_have_start; + int __pyx_v_have_stop; + int __pyx_v_have_step; + PyObject *__pyx_v_index = NULL; + struct __pyx_memoryview_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + struct __pyx_memoryview_obj *__pyx_t_4; + char *__pyx_t_5; + int __pyx_t_6; + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + Py_ssize_t __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memview_slice", 0); + + /* "View.MemoryView":668 + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): + * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< + * cdef bint negative_step + * cdef __Pyx_memviewslice src, dst + */ + __pyx_v_new_ndim = 0; + __pyx_v_suboffset_dim = -1; + + /* "View.MemoryView":675 + * + * + * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< + * + * cdef _memoryviewslice memviewsliceobj + */ + memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); + + /* "View.MemoryView":679 + * cdef _memoryviewslice memviewsliceobj + * + * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "View.MemoryView":681 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":682 + * + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview # <<<<<<<<<<<<<< + * p_src = &memviewsliceobj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 682; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":683 + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, &src) + */ + __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":685 + * p_src = &memviewsliceobj.from_slice + * else: + * slice_copy(memview, &src) # <<<<<<<<<<<<<< + * p_src = &src + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); + + /* "View.MemoryView":686 + * else: + * slice_copy(memview, &src) + * p_src = &src # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_src = (&__pyx_v_src); + } + __pyx_L3:; + + /* "View.MemoryView":692 + * + * + * dst.memview = p_src.memview # <<<<<<<<<<<<<< + * dst.data = p_src.data + * + */ + __pyx_t_4 = __pyx_v_p_src->memview; + __pyx_v_dst.memview = __pyx_t_4; + + /* "View.MemoryView":693 + * + * dst.memview = p_src.memview + * dst.data = p_src.data # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_v_p_src->data; + __pyx_v_dst.data = __pyx_t_5; + + /* "View.MemoryView":698 + * + * + * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< + * cdef int *p_suboffset_dim = &suboffset_dim + * cdef Py_ssize_t start, stop, step + */ + __pyx_v_p_dst = (&__pyx_v_dst); + + /* "View.MemoryView":699 + * + * cdef __Pyx_memviewslice *p_dst = &dst + * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< + * cdef Py_ssize_t start, stop, step + * cdef bint have_start, have_stop, have_step + */ + __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); + + /* "View.MemoryView":703 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + __pyx_t_6 = 0; + if (likely(PyList_CheckExact(__pyx_v_indices)) || PyTuple_CheckExact(__pyx_v_indices)) { + __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + for (;;) { + if (likely(!__pyx_t_8)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } + } else { + __pyx_t_9 = __pyx_t_8(__pyx_t_3); + if (unlikely(!__pyx_t_9)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_9); + } + __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); + __pyx_t_9 = 0; + __pyx_v_dim = __pyx_t_6; + __pyx_t_6 = (__pyx_t_6 + 1); + + /* "View.MemoryView":704 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ + __pyx_t_2 = (PyIndex_Check(__pyx_v_index) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":708 + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< + * 0, 0, 0, # have_{start,stop,step} + * False) + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":705 + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 705; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + + /* "View.MemoryView":711 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ + __pyx_t_2 = (__pyx_v_index == Py_None); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":712 + * False) + * elif index is None: + * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + */ + (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; + + /* "View.MemoryView":713 + * elif index is None: + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 + */ + (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; + + /* "View.MemoryView":714 + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< + * new_ndim += 1 + * else: + */ + (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1; + + /* "View.MemoryView":715 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 # <<<<<<<<<<<<<< + * else: + * start = index.start or 0 + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":717 + * new_ndim += 1 + * else: + * start = index.start or 0 # <<<<<<<<<<<<<< + * stop = index.stop or 0 + * step = index.step or 0 + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L8_next_or; + } else { + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_t_12; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L7_bool_binop_done; + } + __pyx_L8_next_or:; + __pyx_t_10 = 0; + __pyx_L7_bool_binop_done:; + __pyx_v_start = __pyx_t_10; + + /* "View.MemoryView":718 + * else: + * start = index.start or 0 + * stop = index.stop or 0 # <<<<<<<<<<<<<< + * step = index.step or 0 + * + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L10_next_or; + } else { + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_t_12; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L9_bool_binop_done; + } + __pyx_L10_next_or:; + __pyx_t_10 = 0; + __pyx_L9_bool_binop_done:; + __pyx_v_stop = __pyx_t_10; + + /* "View.MemoryView":719 + * start = index.start or 0 + * stop = index.stop or 0 + * step = index.step or 0 # <<<<<<<<<<<<<< + * + * have_start = index.start is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L12_next_or; + } else { + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_t_12; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L11_bool_binop_done; + } + __pyx_L12_next_or:; + __pyx_t_10 = 0; + __pyx_L11_bool_binop_done:; + __pyx_v_step = __pyx_t_10; + + /* "View.MemoryView":721 + * step = index.step or 0 + * + * have_start = index.start is not None # <<<<<<<<<<<<<< + * have_stop = index.stop is not None + * have_step = index.step is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 721; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = (__pyx_t_9 != Py_None); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_have_start = __pyx_t_1; + + /* "View.MemoryView":722 + * + * have_start = index.start is not None + * have_stop = index.stop is not None # <<<<<<<<<<<<<< + * have_step = index.step is not None + * + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = (__pyx_t_9 != Py_None); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_have_stop = __pyx_t_1; + + /* "View.MemoryView":723 + * have_start = index.start is not None + * have_stop = index.stop is not None + * have_step = index.step is not None # <<<<<<<<<<<<<< + * + * slice_memviewslice( + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = (__pyx_t_9 != Py_None); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_have_step = __pyx_t_1; + + /* "View.MemoryView":725 + * have_step = index.step is not None + * + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":731 + * have_start, have_stop, have_step, + * True) + * new_ndim += 1 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + } + __pyx_L6:; + + /* "View.MemoryView":703 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":733 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":734 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":735 + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 735; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":736 + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * else: + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 736; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":734 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 734; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 734; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":739 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":740 + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":739 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":667 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":764 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { + Py_ssize_t __pyx_v_new_shape; + int __pyx_v_negative_step; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":784 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":786 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + __pyx_t_1 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":787 + * + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":788 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + __pyx_t_1 = (0 <= __pyx_v_start); + if (__pyx_t_1) { + __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); + } + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":789 + * start += shape + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< + * else: + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_Index_out_of_bounds_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 789; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":792 + * else: + * + * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< + * + * if have_step and step == 0: + */ + __pyx_t_1 = ((__pyx_v_have_step != 0) != 0); + if (__pyx_t_1) { + goto __pyx_L7_next_and; + } else { + __pyx_t_2 = __pyx_t_1; + goto __pyx_L6_bool_binop_done; + } + __pyx_L7_next_and:; + __pyx_t_1 = ((__pyx_v_step < 0) != 0); + __pyx_t_2 = __pyx_t_1; + __pyx_L6_bool_binop_done:; + __pyx_v_negative_step = __pyx_t_2; + + /* "View.MemoryView":794 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + __pyx_t_1 = (__pyx_v_have_step != 0); + if (__pyx_t_1) { + goto __pyx_L10_next_and; + } else { + __pyx_t_2 = __pyx_t_1; + goto __pyx_L9_bool_binop_done; + } + __pyx_L10_next_and:; + __pyx_t_1 = ((__pyx_v_step == 0) != 0); + __pyx_t_2 = __pyx_t_1; + __pyx_L9_bool_binop_done:; + if (__pyx_t_2) { + + /* "View.MemoryView":795 + * + * if have_step and step == 0: + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Step_may_not_be_zero_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":798 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + __pyx_t_2 = (__pyx_v_have_start != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":799 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":800 + * if have_start: + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if start < 0: + * start = 0 + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":801 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":802 + * start += shape + * if start < 0: + * start = 0 # <<<<<<<<<<<<<< + * elif start >= shape: + * if negative_step: + */ + __pyx_v_start = 0; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L12; + } + + /* "View.MemoryView":803 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":804 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":805 + * elif start >= shape: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = shape + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L14; + } + /*else*/ { + + /* "View.MemoryView":807 + * start = shape - 1 + * else: + * start = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_start = __pyx_v_shape; + } + __pyx_L14:; + goto __pyx_L12; + } + __pyx_L12:; + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":809 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":810 + * else: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = 0 + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L15; + } + /*else*/ { + + /* "View.MemoryView":812 + * start = shape - 1 + * else: + * start = 0 # <<<<<<<<<<<<<< + * + * if have_stop: + */ + __pyx_v_start = 0; + } + __pyx_L15:; + } + __pyx_L11:; + + /* "View.MemoryView":814 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + __pyx_t_2 = (__pyx_v_have_stop != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":815 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":816 + * if have_stop: + * if stop < 0: + * stop += shape # <<<<<<<<<<<<<< + * if stop < 0: + * stop = 0 + */ + __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); + + /* "View.MemoryView":817 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":818 + * stop += shape + * if stop < 0: + * stop = 0 # <<<<<<<<<<<<<< + * elif stop > shape: + * stop = shape + */ + __pyx_v_stop = 0; + goto __pyx_L18; + } + __pyx_L18:; + goto __pyx_L17; + } + + /* "View.MemoryView":819 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":820 + * stop = 0 + * elif stop > shape: + * stop = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_stop = __pyx_v_shape; + goto __pyx_L17; + } + __pyx_L17:; + goto __pyx_L16; + } + /*else*/ { + + /* "View.MemoryView":822 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":823 + * else: + * if negative_step: + * stop = -1 # <<<<<<<<<<<<<< + * else: + * stop = shape + */ + __pyx_v_stop = -1; + goto __pyx_L19; + } + /*else*/ { + + /* "View.MemoryView":825 + * stop = -1 + * else: + * stop = shape # <<<<<<<<<<<<<< + * + * if not have_step: + */ + __pyx_v_stop = __pyx_v_shape; + } + __pyx_L19:; + } + __pyx_L16:; + + /* "View.MemoryView":827 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":828 + * + * if not have_step: + * step = 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_step = 1; + goto __pyx_L20; + } + __pyx_L20:; + + /* "View.MemoryView":832 + * + * with cython.cdivision(True): + * new_shape = (stop - start) // step # <<<<<<<<<<<<<< + * + * if (stop - start) - step * new_shape: + */ + __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); + + /* "View.MemoryView":834 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":835 + * + * if (stop - start) - step * new_shape: + * new_shape += 1 # <<<<<<<<<<<<<< + * + * if new_shape < 0: + */ + __pyx_v_new_shape = (__pyx_v_new_shape + 1); + goto __pyx_L21; + } + __pyx_L21:; + + /* "View.MemoryView":837 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":838 + * + * if new_shape < 0: + * new_shape = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_new_shape = 0; + goto __pyx_L22; + } + __pyx_L22:; + + /* "View.MemoryView":841 + * + * + * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset + */ + (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); + + /* "View.MemoryView":842 + * + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< + * dst.suboffsets[new_ndim] = suboffset + * + */ + (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; + + /* "View.MemoryView":843 + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; + } + __pyx_L3:; + + /* "View.MemoryView":846 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":847 + * + * if suboffset_dim[0] < 0: + * dst.data += start * stride # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride + */ + __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); + goto __pyx_L23; + } + /*else*/ { + + /* "View.MemoryView":849 + * dst.data += start * stride + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< + * + * if suboffset >= 0: + */ + __pyx_t_3 = (__pyx_v_suboffset_dim[0]); + (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); + } + __pyx_L23:; + + /* "View.MemoryView":851 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":852 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":853 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":854 + * if not is_slice: + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + */ + __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); + goto __pyx_L26; + } + /*else*/ { + + /* "View.MemoryView":856 + * dst.data = ( dst.data)[0] + suboffset + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< + * "must be indexed and not sliced", dim) + * else: + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_All_dimensions_preceding_dimensi, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 856; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L26:; + goto __pyx_L25; + } + /*else*/ { + + /* "View.MemoryView":859 + * "must be indexed and not sliced", dim) + * else: + * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< + * + * return 0 + */ + (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; + } + __pyx_L25:; + goto __pyx_L24; + } + __pyx_L24:; + + /* "View.MemoryView":861 + * suboffset_dim[0] = new_ndim + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":764 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":867 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + +static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { + Py_ssize_t __pyx_v_shape; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_suboffset; + Py_ssize_t __pyx_v_itemsize; + char *__pyx_v_resultp; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pybuffer_index", 0); + + /* "View.MemoryView":869 + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< + * cdef Py_ssize_t itemsize = view.itemsize + * cdef char *resultp + */ + __pyx_v_suboffset = -1; + + /* "View.MemoryView":870 + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< + * cdef char *resultp + * + */ + __pyx_t_1 = __pyx_v_view->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":873 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":874 + * + * if view.ndim == 0: + * shape = view.len / itemsize # <<<<<<<<<<<<<< + * stride = itemsize + * else: + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 874; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 874; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); + + /* "View.MemoryView":875 + * if view.ndim == 0: + * shape = view.len / itemsize + * stride = itemsize # <<<<<<<<<<<<<< + * else: + * shape = view.shape[dim] + */ + __pyx_v_stride = __pyx_v_itemsize; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":877 + * stride = itemsize + * else: + * shape = view.shape[dim] # <<<<<<<<<<<<<< + * stride = view.strides[dim] + * if view.suboffsets != NULL: + */ + __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); + + /* "View.MemoryView":878 + * else: + * shape = view.shape[dim] + * stride = view.strides[dim] # <<<<<<<<<<<<<< + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] + */ + __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); + + /* "View.MemoryView":879 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":880 + * stride = view.strides[dim] + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< + * + * if index < 0: + */ + __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); + goto __pyx_L4; + } + __pyx_L4:; + } + __pyx_L3:; + + /* "View.MemoryView":882 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":883 + * + * if index < 0: + * index += view.shape[dim] # <<<<<<<<<<<<<< + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + */ + __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); + + /* "View.MemoryView":884 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":885 + * index += view.shape[dim] + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * if index >= shape: + */ + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":887 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":888 + * + * if index >= shape: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * resultp = bufp + index * stride + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":890 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * resultp = bufp + index * stride # <<<<<<<<<<<<<< + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset + */ + __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); + + /* "View.MemoryView":891 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":892 + * resultp = bufp + index * stride + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< + * + * return resultp + */ + __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":894 + * resultp = ( resultp)[0] + suboffset + * + * return resultp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_resultp; + goto __pyx_L0; + + /* "View.MemoryView":867 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":900 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + +static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { + int __pyx_v_ndim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + int __pyx_v_i; + int __pyx_v_j; + int __pyx_r; + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + long __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":901 + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: + * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< + * + * cdef Py_ssize_t *shape = memslice.shape + */ + __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; + __pyx_v_ndim = __pyx_t_1; + + /* "View.MemoryView":903 + * cdef int ndim = memslice.memview.view.ndim + * + * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< + * cdef Py_ssize_t *strides = memslice.strides + * + */ + __pyx_t_2 = __pyx_v_memslice->shape; + __pyx_v_shape = __pyx_t_2; + + /* "View.MemoryView":904 + * + * cdef Py_ssize_t *shape = memslice.shape + * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_v_memslice->strides; + __pyx_v_strides = __pyx_t_2; + + /* "View.MemoryView":908 + * + * cdef int i, j + * for i in range(ndim / 2): # <<<<<<<<<<<<<< + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + */ + __pyx_t_3 = __Pyx_div_long(__pyx_v_ndim, 2); + for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":909 + * cdef int i, j + * for i in range(ndim / 2): + * j = ndim - 1 - i # <<<<<<<<<<<<<< + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] + */ + __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); + + /* "View.MemoryView":910 + * for i in range(ndim / 2): + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< + * shape[i], shape[j] = shape[j], shape[i] + * + */ + __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); + __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); + (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; + (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; + + /* "View.MemoryView":911 + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + */ + __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); + __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); + (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; + (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; + + /* "View.MemoryView":913 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); + if (!__pyx_t_7) { + goto __pyx_L7_next_or; + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L6_bool_binop_done; + } + __pyx_L7_next_or:; + __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L6_bool_binop_done:; + if (__pyx_t_6) { + + /* "View.MemoryView":914 + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< + * + * return 1 + */ + __pyx_t_8 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_Cannot_transpose_memoryview_with); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 914; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "View.MemoryView":916 + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + * return 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 1; + goto __pyx_L0; + + /* "View.MemoryView":900 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":933 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + +/* Python wrapper */ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":934 + * + * def __dealloc__(self): + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); + + /* "View.MemoryView":933 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":936 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":937 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":938 + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) # <<<<<<<<<<<<<< + * else: + * return memoryview.convert_item_to_object(self, itemp) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 938; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":940 + * return self.to_object_func(itemp) + * else: + * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 940; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":936 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":942 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":943 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":944 + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< + * else: + * memoryview.assign_item_from_object(self, itemp, value) + */ + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":946 + * self.to_dtype_func(itemp, value) + * else: + * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< + * + * property base: + */ + __pyx_t_3 = __pyx_memoryview_assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":942 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":950 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":951 + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): + * return self.from_object # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->from_object); + __pyx_r = __pyx_v_self->from_object; + goto __pyx_L0; + + /* "View.MemoryView":950 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":957 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_TypeInfo *__pyx_t_4; + Py_buffer __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_fromslice", 0); + + /* "View.MemoryView":966 + * cdef int i + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":967 + * + * if memviewslice.memview == Py_None: + * return None # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + + /* "View.MemoryView":972 + * + * + * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< + * + * result.from_slice = memviewslice + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":974 + * result = _memoryviewslice(None, 0, dtype_is_object) + * + * result.from_slice = memviewslice # <<<<<<<<<<<<<< + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + */ + __pyx_v_result->from_slice = __pyx_v_memviewslice; + + /* "View.MemoryView":975 + * + * result.from_slice = memviewslice + * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< + * + * result.from_object = ( memviewslice.memview).base + */ + __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); + + /* "View.MemoryView":977 + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< + * result.typeinfo = memviewslice.memview.typeinfo + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_result->from_object); + __Pyx_DECREF(__pyx_v_result->from_object); + __pyx_v_result->from_object = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":978 + * + * result.from_object = ( memviewslice.memview).base + * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< + * + * result.view = memviewslice.memview.view + */ + __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; + __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; + + /* "View.MemoryView":980 + * result.typeinfo = memviewslice.memview.typeinfo + * + * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + */ + __pyx_t_5 = __pyx_v_memviewslice.memview->view; + __pyx_v_result->__pyx_base.view = __pyx_t_5; + + /* "View.MemoryView":981 + * + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + */ + __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); + + /* "View.MemoryView":982 + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data + * result.view.ndim = ndim # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; + + /* "View.MemoryView":983 + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; + + /* "View.MemoryView":984 + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * result.flags = PyBUF_RECORDS + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":986 + * Py_INCREF(Py_None) + * + * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< + * + * result.view.shape = result.from_slice.shape + */ + __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; + + /* "View.MemoryView":988 + * result.flags = PyBUF_RECORDS + * + * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets + */ + __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); + + /* "View.MemoryView":989 + * + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * + */ + __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); + + /* "View.MemoryView":990 + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + * + * result.view.len = result.view.itemsize + */ + __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + + /* "View.MemoryView":992 + * result.view.suboffsets = result.from_slice.suboffsets + * + * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< + * for i in range(ndim): + * result.view.len *= result.view.shape[i] + */ + __pyx_t_6 = __pyx_v_result->__pyx_base.view.itemsize; + __pyx_v_result->__pyx_base.view.len = __pyx_t_6; + + /* "View.MemoryView":993 + * + * result.view.len = result.view.itemsize + * for i in range(ndim): # <<<<<<<<<<<<<< + * result.view.len *= result.view.shape[i] + * + */ + __pyx_t_7 = __pyx_v_ndim; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "View.MemoryView":994 + * result.view.len = result.view.itemsize + * for i in range(ndim): + * result.view.len *= result.view.shape[i] # <<<<<<<<<<<<<< + * + * result.to_object_func = to_object_func + */ + __pyx_v_result->__pyx_base.view.len = (__pyx_v_result->__pyx_base.view.len * (__pyx_v_result->__pyx_base.view.shape[__pyx_v_i])); + } + + /* "View.MemoryView":996 + * result.view.len *= result.view.shape[i] + * + * result.to_object_func = to_object_func # <<<<<<<<<<<<<< + * result.to_dtype_func = to_dtype_func + * + */ + __pyx_v_result->to_object_func = __pyx_v_to_object_func; + + /* "View.MemoryView":997 + * + * result.to_object_func = to_object_func + * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; + + /* "View.MemoryView":999 + * result.to_dtype_func = to_dtype_func + * + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":957 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1002 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { + struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; + __Pyx_memviewslice *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_slice_from_memview", 0); + + /* "View.MemoryView":1005 + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1006 + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): + * obj = memview # <<<<<<<<<<<<<< + * return &obj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":1007 + * if isinstance(memview, _memoryviewslice): + * obj = memview + * return &obj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, mslice) + */ + __pyx_r = (&__pyx_v_obj->from_slice); + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1009 + * return &obj.from_slice + * else: + * slice_copy(memview, mslice) # <<<<<<<<<<<<<< + * return mslice + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); + + /* "View.MemoryView":1010 + * else: + * slice_copy(memview, mslice) + * return mslice # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_copy') + */ + __pyx_r = __pyx_v_mslice; + goto __pyx_L0; + } + + /* "View.MemoryView":1002 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_obj); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1013 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { + int __pyx_v_dim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + Py_ssize_t *__pyx_v_suboffsets; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + __Pyx_RefNannySetupContext("slice_copy", 0); + + /* "View.MemoryView":1017 + * cdef (Py_ssize_t*) shape, strides, suboffsets + * + * shape = memview.view.shape # <<<<<<<<<<<<<< + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets + */ + __pyx_t_1 = __pyx_v_memview->view.shape; + __pyx_v_shape = __pyx_t_1; + + /* "View.MemoryView":1018 + * + * shape = memview.view.shape + * strides = memview.view.strides # <<<<<<<<<<<<<< + * suboffsets = memview.view.suboffsets + * + */ + __pyx_t_1 = __pyx_v_memview->view.strides; + __pyx_v_strides = __pyx_t_1; + + /* "View.MemoryView":1019 + * shape = memview.view.shape + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< + * + * dst.memview = <__pyx_memoryview *> memview + */ + __pyx_t_1 = __pyx_v_memview->view.suboffsets; + __pyx_v_suboffsets = __pyx_t_1; + + /* "View.MemoryView":1021 + * suboffsets = memview.view.suboffsets + * + * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< + * dst.data = memview.view.buf + * + */ + __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); + + /* "View.MemoryView":1022 + * + * dst.memview = <__pyx_memoryview *> memview + * dst.data = memview.view.buf # <<<<<<<<<<<<<< + * + * for dim in range(memview.view.ndim): + */ + __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); + + /* "View.MemoryView":1024 + * dst.data = memview.view.buf + * + * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + */ + __pyx_t_2 = __pyx_v_memview->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_dim = __pyx_t_3; + + /* "View.MemoryView":1025 + * + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + */ + (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); + + /* "View.MemoryView":1026 + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 + */ + (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); + + /* "View.MemoryView":1027 + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: # <<<<<<<<<<<<<< + * dst.suboffsets[dim] = -1 + * else: + */ + __pyx_t_4 = ((__pyx_v_suboffsets == NULL) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":1028 + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[dim] = suboffsets[dim] + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = -1; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1030 + * dst.suboffsets[dim] = -1 + * else: + * dst.suboffsets[dim] = suboffsets[dim] # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object') + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = (__pyx_v_suboffsets[__pyx_v_dim]); + } + __pyx_L5:; + } + + /* "View.MemoryView":1013 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1033 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { + __Pyx_memviewslice __pyx_v_memviewslice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy", 0); + + /* "View.MemoryView":1036 + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< + * return memoryview_copy_from_slice(memview, &memviewslice) + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); + + /* "View.MemoryView":1037 + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) + * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object_from_slice') + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1033 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1040 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { + PyObject *(*__pyx_v_to_object_func)(char *); + int (*__pyx_v_to_dtype_func)(char *, PyObject *); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *(*__pyx_t_3)(char *); + int (*__pyx_t_4)(char *, PyObject *); + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); + + /* "View.MemoryView":1047 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1048 + * + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + */ + __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; + __pyx_v_to_object_func = __pyx_t_3; + + /* "View.MemoryView":1049 + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< + * else: + * to_object_func = NULL + */ + __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; + __pyx_v_to_dtype_func = __pyx_t_4; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1051 + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + * to_object_func = NULL # <<<<<<<<<<<<<< + * to_dtype_func = NULL + * + */ + __pyx_v_to_object_func = NULL; + + /* "View.MemoryView":1052 + * else: + * to_object_func = NULL + * to_dtype_func = NULL # <<<<<<<<<<<<<< + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + */ + __pyx_v_to_dtype_func = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":1054 + * to_dtype_func = NULL + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< + * to_object_func, to_dtype_func, + * memview.dtype_is_object) + */ + __Pyx_XDECREF(__pyx_r); + + /* "View.MemoryView":1056 + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + * to_object_func, to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1040 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1062 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + +static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { + Py_ssize_t __pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":1063 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + __pyx_t_1 = ((__pyx_v_arg < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1064 + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: + * return -arg # <<<<<<<<<<<<<< + * else: + * return arg + */ + __pyx_r = (-__pyx_v_arg); + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1066 + * return -arg + * else: + * return arg # <<<<<<<<<<<<<< + * + * @cname('__pyx_get_best_slice_order') + */ + __pyx_r = __pyx_v_arg; + goto __pyx_L0; + } + + /* "View.MemoryView":1062 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1069 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + +static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_c_stride; + Py_ssize_t __pyx_v_f_stride; + char __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1074 + * """ + * cdef int i + * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t f_stride = 0 + * + */ + __pyx_v_c_stride = 0; + + /* "View.MemoryView":1075 + * cdef int i + * cdef Py_ssize_t c_stride = 0 + * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_f_stride = 0; + + /* "View.MemoryView":1077 + * cdef Py_ssize_t f_stride = 0 + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1078 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1079 + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1080 + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + goto __pyx_L4_break; + } + } + __pyx_L4_break:; + + /* "View.MemoryView":1082 + * break + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1083 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1084 + * for i in range(ndim): + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1085 + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + */ + goto __pyx_L7_break; + } + } + __pyx_L7_break:; + + /* "View.MemoryView":1087 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1088 + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + * return 'C' # <<<<<<<<<<<<<< + * else: + * return 'F' + */ + __pyx_r = 'C'; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1090 + * return 'C' + * else: + * return 'F' # <<<<<<<<<<<<<< + * + * @cython.cdivision(True) + */ + __pyx_r = 'F'; + goto __pyx_L0; + } + + /* "View.MemoryView":1069 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1093 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + +static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; + Py_ssize_t __pyx_v_dst_extent; + Py_ssize_t __pyx_v_src_stride; + Py_ssize_t __pyx_v_dst_stride; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + + /* "View.MemoryView":1100 + * + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + */ + __pyx_v_src_extent = (__pyx_v_src_shape[0]); + + /* "View.MemoryView":1101 + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] + */ + __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); + + /* "View.MemoryView":1102 + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + */ + __pyx_v_src_stride = (__pyx_v_src_strides[0]); + + /* "View.MemoryView":1103 + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); + + /* "View.MemoryView":1105 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1106 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + __pyx_t_2 = ((__pyx_v_src_stride > 0) != 0); + if (__pyx_t_2) { + goto __pyx_L6_next_and; + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L5_bool_binop_done; + } + __pyx_L6_next_and:; + __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); + if (__pyx_t_2) { + goto __pyx_L7_next_and; + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L5_bool_binop_done; + } + __pyx_L7_next_and:; + + /* "View.MemoryView":1107 + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + */ + __pyx_t_2 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); + if (__pyx_t_2) { + __pyx_t_2 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); + } + __pyx_t_3 = (__pyx_t_2 != 0); + __pyx_t_1 = __pyx_t_3; + __pyx_L5_bool_binop_done:; + if (__pyx_t_1) { + + /* "View.MemoryView":1108 + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":1110 + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + */ + __pyx_t_4 = __pyx_v_dst_extent; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1111 + * else: + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); + + /* "View.MemoryView":1112 + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * else: + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1113 + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1115 + * dst_data += dst_stride + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * _copy_strided_to_strided(src_data, src_strides + 1, + * dst_data, dst_strides + 1, + */ + __pyx_t_4 = __pyx_v_dst_extent; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1116 + * else: + * for i in range(dst_extent): + * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< + * dst_data, dst_strides + 1, + * src_shape + 1, dst_shape + 1, + */ + _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); + + /* "View.MemoryView":1120 + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1121 + * ndim - 1, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1093 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + + /* function exit code */ +} + +/* "View.MemoryView":1123 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + +static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + + /* "View.MemoryView":1126 + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< + * src.shape, dst.shape, ndim, itemsize) + * + */ + _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1123 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1130 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_size; + Py_ssize_t __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1133 + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_size = __pyx_t_1; + + /* "View.MemoryView":1135 + * cdef Py_ssize_t size = src.memview.view.itemsize + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * size *= src.shape[i] + * + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1136 + * + * for i in range(ndim): + * size *= src.shape[i] # <<<<<<<<<<<<<< + * + * return size + */ + __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); + } + + /* "View.MemoryView":1138 + * size *= src.shape[i] + * + * return size # <<<<<<<<<<<<<< + * + * @cname('__pyx_fill_contig_strides_array') + */ + __pyx_r = __pyx_v_size; + goto __pyx_L0; + + /* "View.MemoryView":1130 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1141 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { + int __pyx_v_idx; + Py_ssize_t __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1150 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + __pyx_t_1 = ((__pyx_v_order == 'F') != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1151 + * + * if order == 'F': + * for idx in range(ndim): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_idx = __pyx_t_3; + + /* "View.MemoryView":1152 + * if order == 'F': + * for idx in range(ndim): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * else: + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1153 + * for idx in range(ndim): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * else: + * for idx in range(ndim - 1, -1, -1): + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1155 + * stride = stride * shape[idx] + * else: + * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { + __pyx_v_idx = __pyx_t_2; + + /* "View.MemoryView":1156 + * else: + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1157 + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * + * return stride + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + } + __pyx_L3:; + + /* "View.MemoryView":1159 + * stride = stride * shape[idx] + * + * return stride # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_data_to_temp') + */ + __pyx_r = __pyx_v_stride; + goto __pyx_L0; + + /* "View.MemoryView":1141 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1162 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { + int __pyx_v_i; + void *__pyx_v_result; + size_t __pyx_v_itemsize; + size_t __pyx_v_size; + void *__pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + struct __pyx_memoryview_obj *__pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1173 + * cdef void *result + * + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef size_t size = slice_get_size(src, ndim) + * + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1174 + * + * cdef size_t itemsize = src.memview.view.itemsize + * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< + * + * result = malloc(size) + */ + __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); + + /* "View.MemoryView":1176 + * cdef size_t size = slice_get_size(src, ndim) + * + * result = malloc(size) # <<<<<<<<<<<<<< + * if not result: + * _err(MemoryError, NULL) + */ + __pyx_v_result = malloc(__pyx_v_size); + + /* "View.MemoryView":1177 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1178 + * result = malloc(size) + * if not result: + * _err(MemoryError, NULL) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1181 + * + * + * tmpslice.data = result # <<<<<<<<<<<<<< + * tmpslice.memview = src.memview + * for i in range(ndim): + */ + __pyx_v_tmpslice->data = ((char *)__pyx_v_result); + + /* "View.MemoryView":1182 + * + * tmpslice.data = result + * tmpslice.memview = src.memview # <<<<<<<<<<<<<< + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + */ + __pyx_t_4 = __pyx_v_src->memview; + __pyx_v_tmpslice->memview = __pyx_t_4; + + /* "View.MemoryView":1183 + * tmpslice.data = result + * tmpslice.memview = src.memview + * for i in range(ndim): # <<<<<<<<<<<<<< + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1184 + * tmpslice.memview = src.memview + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< + * tmpslice.suboffsets[i] = -1 + * + */ + (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); + + /* "View.MemoryView":1185 + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + */ + (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1187 + * tmpslice.suboffsets[i] = -1 + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< + * ndim, order) + * + */ + __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); + + /* "View.MemoryView":1191 + * + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1192 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1193 + * for i in range(ndim): + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< + * + * if slice_is_contig(src, order, ndim): + */ + (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1195 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1196 + * + * if slice_is_contig(src, order, ndim): + * memcpy(result, src.data, size) # <<<<<<<<<<<<<< + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + */ + memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1198 + * memcpy(result, src.data, size) + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< + * + * return result + */ + copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); + } + __pyx_L9:; + + /* "View.MemoryView":1200 + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":1162 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = NULL; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1205 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + +static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_extents", 0); + + /* "View.MemoryView":1208 + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + * (i, extent1, extent2)) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err_dim') + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + + /* "View.MemoryView":1207 + * cdef int _err_extents(int i, Py_ssize_t extent1, + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< + * (i, extent1, extent2)) + * + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1205 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1211 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + +static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_dim", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1212 + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: + * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err') + */ + __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_INCREF(__pyx_v_error); + __pyx_t_3 = __pyx_v_error; __pyx_t_2 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (!__pyx_t_2) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = NULL; + PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1211 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1215 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + +static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1216 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ + __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1217 + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: + * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< + * else: + * raise error + */ + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_error); + __pyx_t_4 = __pyx_v_error; __pyx_t_5 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + } + } + if (!__pyx_t_5) { + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_GOTREF(__pyx_t_2); + } else { + __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; + PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + /*else*/ { + + /* "View.MemoryView":1219 + * raise error(msg.decode('ascii')) + * else: + * raise error # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_contents') + */ + __Pyx_Raise(__pyx_v_error, 0, 0, 0); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":1215 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1222 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { + void *__pyx_v_tmpdata; + size_t __pyx_v_itemsize; + int __pyx_v_i; + char __pyx_v_order; + int __pyx_v_broadcasting; + int __pyx_v_direct_copy; + __Pyx_memviewslice __pyx_v_tmp; + int __pyx_v_ndim; + int __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + void *__pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1230 + * Check for overlapping memory and verify the shapes. + * """ + * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + */ + __pyx_v_tmpdata = NULL; + + /* "View.MemoryView":1231 + * """ + * cdef void *tmpdata = NULL + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + */ + __pyx_t_1 = __pyx_v_src.memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1233 + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< + * cdef bint broadcasting = False + * cdef bint direct_copy = False + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); + + /* "View.MemoryView":1234 + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False # <<<<<<<<<<<<<< + * cdef bint direct_copy = False + * cdef __Pyx_memviewslice tmp + */ + __pyx_v_broadcasting = 0; + + /* "View.MemoryView":1235 + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False + * cdef bint direct_copy = False # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice tmp + * + */ + __pyx_v_direct_copy = 0; + + /* "View.MemoryView":1238 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ + __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1239 + * + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); + goto __pyx_L3; + } + + /* "View.MemoryView":1240 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ + __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1241 + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< + * + * cdef int ndim = max(src_ndim, dst_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1243 + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_3 = __pyx_v_dst_ndim; + __pyx_t_4 = __pyx_v_src_ndim; + if (((__pyx_t_3 > __pyx_t_4) != 0)) { + __pyx_t_5 = __pyx_t_3; + } else { + __pyx_t_5 = __pyx_t_4; + } + __pyx_v_ndim = __pyx_t_5; + + /* "View.MemoryView":1245 + * cdef int ndim = max(src_ndim, dst_ndim) + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1246 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1247 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1248 + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + * broadcasting = True # <<<<<<<<<<<<<< + * src.strides[i] = 0 + * else: + */ + __pyx_v_broadcasting = 1; + + /* "View.MemoryView":1249 + * if src.shape[i] == 1: + * broadcasting = True + * src.strides[i] = 0 # <<<<<<<<<<<<<< + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) + */ + (__pyx_v_src.strides[__pyx_v_i]) = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":1251 + * src.strides[i] = 0 + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< + * + * if src.suboffsets[i] >= 0: + */ + __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":1253 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ + __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1254 + * + * if src.suboffsets[i] >= 0: + * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< + * + * if slices_overlap(&src, &dst, ndim, itemsize): + */ + __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Dimension_d_is_not_direct, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1256 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(&src, order, ndim): + */ + __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1258 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1259 + * + * if not slice_is_contig(&src, order, ndim): + * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":1261 + * order = get_best_order(&dst, ndim) + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< + * src = tmp + * + */ + __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_tmpdata = __pyx_t_6; + + /* "View.MemoryView":1262 + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + * src = tmp # <<<<<<<<<<<<<< + * + * if not broadcasting: + */ + __pyx_v_src = __pyx_v_tmp; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":1264 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1267 + * + * + * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1268 + * + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); + goto __pyx_L12; + } + + /* "View.MemoryView":1269 + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1270 + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< + * + * if direct_copy: + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":1272 + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_2 = (__pyx_v_direct_copy != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1274 + * if direct_copy: + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1275 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) + */ + memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); + + /* "View.MemoryView":1276 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * free(tmpdata) + * return 0 + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1277 + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1278 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * if order == 'F' == get_best_order(&dst, ndim): + */ + __pyx_r = 0; + goto __pyx_L0; + } + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":1280 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = (__pyx_v_order == 'F'); + if (__pyx_t_2) { + __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); + } + __pyx_t_7 = (__pyx_t_2 != 0); + if (__pyx_t_7) { + + /* "View.MemoryView":1283 + * + * + * transpose_memslice(&src) # <<<<<<<<<<<<<< + * transpose_memslice(&dst) + * + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1284 + * + * transpose_memslice(&src) + * transpose_memslice(&dst) # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":1286 + * transpose_memslice(&dst) + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1287 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + */ + copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1288 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * free(tmpdata) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1290 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1291 + * + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_broadcast_leading') + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":1222 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1294 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice, int __pyx_v_ndim, int __pyx_v_ndim_other) { + int __pyx_v_i; + int __pyx_v_offset; + int __pyx_t_1; + int __pyx_t_2; + + /* "View.MemoryView":1298 + * int ndim_other) nogil: + * cdef int i + * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); + + /* "View.MemoryView":1300 + * cdef int offset = ndim_other - ndim + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1301 + * + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] # <<<<<<<<<<<<<< + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] + */ + (__pyx_v_slice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->shape[__pyx_v_i]); + + /* "View.MemoryView":1302 + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] # <<<<<<<<<<<<<< + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + */ + (__pyx_v_slice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->strides[__pyx_v_i]); + + /* "View.MemoryView":1303 + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] # <<<<<<<<<<<<<< + * + * for i in range(offset): + */ + (__pyx_v_slice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->suboffsets[__pyx_v_i]); + } + + /* "View.MemoryView":1305 + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + * for i in range(offset): # <<<<<<<<<<<<<< + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + */ + __pyx_t_1 = __pyx_v_offset; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1306 + * + * for i in range(offset): + * slice.shape[i] = 1 # <<<<<<<<<<<<<< + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 + */ + (__pyx_v_slice->shape[__pyx_v_i]) = 1; + + /* "View.MemoryView":1307 + * for i in range(offset): + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] # <<<<<<<<<<<<<< + * slice.suboffsets[i] = -1 + * + */ + (__pyx_v_slice->strides[__pyx_v_i]) = (__pyx_v_slice->strides[0]); + + /* "View.MemoryView":1308 + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_slice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1294 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1316 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { + int __pyx_t_1; + + /* "View.MemoryView":1320 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + __pyx_t_1 = (__pyx_v_dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1321 + * + * if dtype_is_object: + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< + * dst.strides, ndim, inc) + * + */ + __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1316 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + + /* function exit code */ +} + +/* "View.MemoryView":1325 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + __Pyx_RefNannyDeclarations + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); + + /* "View.MemoryView":1328 + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); + + /* "View.MemoryView":1325 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif +} + +/* "View.MemoryView":1331 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + +static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); + + /* "View.MemoryView":1335 + * cdef Py_ssize_t i + * + * for i in range(shape[0]): # <<<<<<<<<<<<<< + * if ndim == 1: + * if inc: + */ + __pyx_t_1 = (__pyx_v_shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1336 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1337 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + __pyx_t_3 = (__pyx_v_inc != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1338 + * if ndim == 1: + * if inc: + * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * Py_DECREF(( data)[0]) + */ + Py_INCREF((((PyObject **)__pyx_v_data)[0])); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":1340 + * Py_INCREF(( data)[0]) + * else: + * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + */ + Py_DECREF((((PyObject **)__pyx_v_data)[0])); + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1342 + * Py_DECREF(( data)[0]) + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, inc) + * + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); + } + __pyx_L5:; + + /* "View.MemoryView":1345 + * ndim - 1, inc) + * + * data += strides[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); + } + + /* "View.MemoryView":1331 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1351 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { + + /* "View.MemoryView":1354 + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1355 + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1357 + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1351 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1361 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + +static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_extent; + int __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + + /* "View.MemoryView":1365 + * size_t itemsize, void *item) nogil: + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t extent = shape[0] + * + */ + __pyx_v_stride = (__pyx_v_strides[0]); + + /* "View.MemoryView":1366 + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] + * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_extent = (__pyx_v_shape[0]); + + /* "View.MemoryView":1368 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1369 + * + * if ndim == 1: + * for i in range(extent): # <<<<<<<<<<<<<< + * memcpy(data, item, itemsize) + * data += stride + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1370 + * if ndim == 1: + * for i in range(extent): + * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< + * data += stride + * else: + */ + memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); + + /* "View.MemoryView":1371 + * for i in range(extent): + * memcpy(data, item, itemsize) + * data += stride # <<<<<<<<<<<<<< + * else: + * for i in range(extent): + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1373 + * data += stride + * else: + * for i in range(extent): # <<<<<<<<<<<<<< + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1374 + * else: + * for i in range(extent): + * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, itemsize, item) + * data += stride + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1376 + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + * data += stride # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1361 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + + /* function exit code */ +} + +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_array_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_array_obj *)o); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_array___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->mode); + Py_CLEAR(p->_format); + (*Py_TYPE(o)->tp_free)(o); +} +static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_array___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { + PyObject *v = PyObject_GenericGetAttr(o, n); + if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + v = __pyx_array___getattr__(o, n); + } + return v; +} + +static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { + return get_memview(o); +} + +static PyMethodDef __pyx_methods_array[] = { + {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_array[] = { + {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_array = { + 0, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_array, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_array = { + 0, /*mp_length*/ + __pyx_array___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_array = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + __pyx_array_getbuffer, /*bf_getbuffer*/ + 0, /*bf_releasebuffer*/ +}; + +static PyTypeObject __pyx_type___pyx_array = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.cd_fast.array", /*tp_name*/ + sizeof(struct __pyx_array_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_array, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + __pyx_tp_getattro_array, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_array, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_array, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_array, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_MemviewEnum_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_MemviewEnum_obj *)o); + p->name = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->name); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + if (p->name) { + e = (*v)(p->name, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_Enum(PyObject *o) { + PyObject* tmp; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + tmp = ((PyObject*)p->name); + p->name = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_Enum[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_MemviewEnum = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.cd_fast.Enum", /*tp_name*/ + sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_Enum, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_MemviewEnum___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_Enum, /*tp_traverse*/ + __pyx_tp_clear_Enum, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_Enum, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_MemviewEnum___init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_Enum, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; + +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryview_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryview_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_memoryview; + p->obj = Py_None; Py_INCREF(Py_None); + p->_size = Py_None; Py_INCREF(Py_None); + p->_array_interface = Py_None; Py_INCREF(Py_None); + p->view.obj = NULL; + if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryview___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->obj); + Py_CLEAR(p->_size); + Py_CLEAR(p->_array_interface); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + if (p->obj) { + e = (*v)(p->obj, a); if (e) return e; + } + if (p->_size) { + e = (*v)(p->_size, a); if (e) return e; + } + if (p->_array_interface) { + e = (*v)(p->_array_interface, a); if (e) return e; + } + if (p->view.obj) { + e = (*v)(p->view.obj, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_memoryview(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + tmp = ((PyObject*)p->obj); + p->obj = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_size); + p->_size = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_array_interface); + p->_array_interface = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + Py_CLEAR(p->view.obj); + return 0; +} +static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_memoryview___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_transpose(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview__get__base(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_shape(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_strides(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_suboffsets(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_ndim(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_itemsize(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_nbytes(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_size(o); +} + +static PyMethodDef __pyx_methods_memoryview[] = { + {"is_c_contig", (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, 0}, + {"is_f_contig", (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, 0}, + {"copy", (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, 0}, + {"copy_fortran", (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_memoryview[] = { + {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, + {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, + {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, + {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, + {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, + {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, + {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, + {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_memoryview = { + __pyx_memoryview___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_memoryview, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_memoryview = { + __pyx_memoryview___len__, /*mp_length*/ + __pyx_memoryview___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_memoryview = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + __pyx_memoryview_getbuffer, /*bf_getbuffer*/ + 0, /*bf_releasebuffer*/ +}; + +static PyTypeObject __pyx_type___pyx_memoryview = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.cd_fast.memoryview", /*tp_name*/ + sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_memoryview___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_memoryview___str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_memoryview, /*tp_traverse*/ + __pyx_tp_clear_memoryview, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_memoryview, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_memoryview, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_memoryview, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; + +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryviewslice_obj *p; + PyObject *o = __pyx_tp_new_memoryview(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryviewslice_obj *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; + p->from_object = Py_None; Py_INCREF(Py_None); + p->from_slice.memview = NULL; + return o; +} + +static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryviewslice___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->from_object); + PyObject_GC_Track(o); + __pyx_tp_dealloc_memoryview(o); +} + +static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; + if (p->from_object) { + e = (*v)(p->from_object, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear__memoryviewslice(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + __pyx_tp_clear_memoryview(o); + tmp = ((PyObject*)p->from_object); + p->from_object = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + __PYX_XDEC_MEMVIEW(&p->from_slice, 1); + return 0; +} + +static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryviewslice__get__base(o); +} + +static PyMethodDef __pyx_methods__memoryviewslice[] = { + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { + {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_memoryviewslice = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.cd_fast._memoryviewslice", /*tp_name*/ + sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___repr__, /*tp_repr*/ + #else + 0, /*tp_repr*/ + #endif + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___str__, /*tp_str*/ + #else + 0, /*tp_str*/ + #endif + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + "Internal class for passing memoryview slices to Python", /*tp_doc*/ + __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ + __pyx_tp_clear__memoryviewslice, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods__memoryviewslice, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets__memoryviewslice, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new__memoryviewslice, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + "cd_fast", + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_n_s_A_norm, __pyx_k_A_norm, sizeof(__pyx_k_A_norm), 0, 0, 1, 1}, + {&__pyx_n_s_A_norm2, __pyx_k_A_norm2, sizeof(__pyx_k_A_norm2), 0, 0, 1, 1}, + {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, + {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, + {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, + {&__pyx_kp_s_Coordinate_descent_with_alpha_0, __pyx_k_Coordinate_descent_with_alpha_0, sizeof(__pyx_k_Coordinate_descent_with_alpha_0), 0, 0, 1, 0}, + {&__pyx_kp_s_Coordinate_descent_with_l1_reg_0, __pyx_k_Coordinate_descent_with_l1_reg_0, sizeof(__pyx_k_Coordinate_descent_with_l1_reg_0), 0, 0, 1, 0}, + {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, + {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_n_s_H, __pyx_k_H, sizeof(__pyx_k_H), 0, 0, 1, 1}, + {&__pyx_n_s_H_ptr, __pyx_k_H_ptr, sizeof(__pyx_k_H_ptr), 0, 0, 1, 1}, + {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, + {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, + {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, + {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, + {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, + {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, + {&__pyx_n_s_Q, __pyx_k_Q, sizeof(__pyx_k_Q), 0, 0, 1, 1}, + {&__pyx_n_s_Q_ptr, __pyx_k_Q_ptr, sizeof(__pyx_k_Q_ptr), 0, 0, 1, 1}, + {&__pyx_n_s_R, __pyx_k_R, sizeof(__pyx_k_R), 0, 0, 1, 1}, + {&__pyx_n_s_R_norm, __pyx_k_R_norm, sizeof(__pyx_k_R_norm), 0, 0, 1, 1}, + {&__pyx_n_s_R_norm2, __pyx_k_R_norm2, sizeof(__pyx_k_R_norm2), 0, 0, 1, 1}, + {&__pyx_n_s_R_sum, __pyx_k_R_sum, sizeof(__pyx_k_R_sum), 0, 0, 1, 1}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, + {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, + {&__pyx_kp_s_Users_alex_work_src_scikit_lear, __pyx_k_Users_alex_work_src_scikit_lear, sizeof(__pyx_k_Users_alex_work_src_scikit_lear), 0, 0, 1, 0}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_W, __pyx_k_W, sizeof(__pyx_k_W), 0, 0, 1, 1}, + {&__pyx_n_s_W_ii_abs_max, __pyx_k_W_ii_abs_max, sizeof(__pyx_k_W_ii_abs_max), 0, 0, 1, 1}, + {&__pyx_n_s_W_ptr, __pyx_k_W_ptr, sizeof(__pyx_k_W_ptr), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_n_s_X_T_R, __pyx_k_X_T_R, sizeof(__pyx_k_X_T_R), 0, 0, 1, 1}, + {&__pyx_n_s_X_data, __pyx_k_X_data, sizeof(__pyx_k_X_data), 0, 0, 1, 1}, + {&__pyx_n_s_X_indices, __pyx_k_X_indices, sizeof(__pyx_k_X_indices), 0, 0, 1, 1}, + {&__pyx_n_s_X_indptr, __pyx_k_X_indptr, sizeof(__pyx_k_X_indptr), 0, 0, 1, 1}, + {&__pyx_n_s_X_mean, __pyx_k_X_mean, sizeof(__pyx_k_X_mean), 0, 0, 1, 1}, + {&__pyx_n_s_X_mean_ii, __pyx_k_X_mean_ii, sizeof(__pyx_k_X_mean_ii), 0, 0, 1, 1}, + {&__pyx_n_s_X_ptr, __pyx_k_X_ptr, sizeof(__pyx_k_X_ptr), 0, 0, 1, 1}, + {&__pyx_n_s_XtA, __pyx_k_XtA, sizeof(__pyx_k_XtA), 0, 0, 1, 1}, + {&__pyx_n_s_XtA_axis1norm, __pyx_k_XtA_axis1norm, sizeof(__pyx_k_XtA_axis1norm), 0, 0, 1, 1}, + {&__pyx_n_s_XtA_ptr, __pyx_k_XtA_ptr, sizeof(__pyx_k_XtA_ptr), 0, 0, 1, 1}, + {&__pyx_n_s_Y, __pyx_k_Y, sizeof(__pyx_k_Y), 0, 0, 1, 1}, + {&__pyx_n_s_Y_ptr, __pyx_k_Y_ptr, sizeof(__pyx_k_Y_ptr), 0, 0, 1, 1}, + {&__pyx_n_s__21, __pyx_k__21, sizeof(__pyx_k__21), 0, 0, 1, 1}, + {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, + {&__pyx_n_s_alpha, __pyx_k_alpha, sizeof(__pyx_k_alpha), 0, 0, 1, 1}, + {&__pyx_n_s_asarray, __pyx_k_asarray, sizeof(__pyx_k_asarray), 0, 0, 1, 1}, + {&__pyx_n_s_axis, __pyx_k_axis, sizeof(__pyx_k_axis), 0, 0, 1, 1}, + {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, + {&__pyx_n_s_beta, __pyx_k_beta, sizeof(__pyx_k_beta), 0, 0, 1, 1}, + {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, + {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, + {&__pyx_n_s_center, __pyx_k_center, sizeof(__pyx_k_center), 0, 0, 1, 1}, + {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, + {&__pyx_n_s_const, __pyx_k_const, sizeof(__pyx_k_const), 0, 0, 1, 1}, + {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_d_w_ii, __pyx_k_d_w_ii, sizeof(__pyx_k_d_w_ii), 0, 0, 1, 1}, + {&__pyx_n_s_d_w_max, __pyx_k_d_w_max, sizeof(__pyx_k_d_w_max), 0, 0, 1, 1}, + {&__pyx_n_s_d_w_tol, __pyx_k_d_w_tol, sizeof(__pyx_k_d_w_tol), 0, 0, 1, 1}, + {&__pyx_n_s_dot, __pyx_k_dot, sizeof(__pyx_k_dot), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, + {&__pyx_n_s_dual_norm_XtA, __pyx_k_dual_norm_XtA, sizeof(__pyx_k_dual_norm_XtA), 0, 0, 1, 1}, + {&__pyx_n_s_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 0, 0, 1, 1}, + {&__pyx_n_s_endptr, __pyx_k_endptr, sizeof(__pyx_k_endptr), 0, 0, 1, 1}, + {&__pyx_n_s_enet_coordinate_descent, __pyx_k_enet_coordinate_descent, sizeof(__pyx_k_enet_coordinate_descent), 0, 0, 1, 1}, + {&__pyx_n_s_enet_coordinate_descent_gram, __pyx_k_enet_coordinate_descent_gram, sizeof(__pyx_k_enet_coordinate_descent_gram), 0, 0, 1, 1}, + {&__pyx_n_s_enet_coordinate_descent_multi_ta, __pyx_k_enet_coordinate_descent_multi_ta, sizeof(__pyx_k_enet_coordinate_descent_multi_ta), 0, 0, 1, 1}, + {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, + {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, + {&__pyx_n_s_f_iter, __pyx_k_f_iter, sizeof(__pyx_k_f_iter), 0, 0, 1, 1}, + {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, + {&__pyx_n_s_float, __pyx_k_float, sizeof(__pyx_k_float), 0, 0, 1, 1}, + {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 0, 0, 1, 1}, + {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, + {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, + {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, + {&__pyx_n_s_gap, __pyx_k_gap, sizeof(__pyx_k_gap), 0, 0, 1, 1}, + {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, + {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, + {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, + {&__pyx_n_s_ii, __pyx_k_ii, sizeof(__pyx_k_ii), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, + {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, + {&__pyx_n_s_jj, __pyx_k_jj, sizeof(__pyx_k_jj), 0, 0, 1, 1}, + {&__pyx_n_s_l1_norm, __pyx_k_l1_norm, sizeof(__pyx_k_l1_norm), 0, 0, 1, 1}, + {&__pyx_n_s_l1_reg, __pyx_k_l1_reg, sizeof(__pyx_k_l1_reg), 0, 0, 1, 1}, + {&__pyx_n_s_l21_norm, __pyx_k_l21_norm, sizeof(__pyx_k_l21_norm), 0, 0, 1, 1}, + {&__pyx_n_s_l2_reg, __pyx_k_l2_reg, sizeof(__pyx_k_l2_reg), 0, 0, 1, 1}, + {&__pyx_n_s_linalg, __pyx_k_linalg, sizeof(__pyx_k_linalg), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_max_iter, __pyx_k_max_iter, sizeof(__pyx_k_max_iter), 0, 0, 1, 1}, + {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, + {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, + {&__pyx_n_s_n_features, __pyx_k_n_features, sizeof(__pyx_k_n_features), 0, 0, 1, 1}, + {&__pyx_n_s_n_iter, __pyx_k_n_iter, sizeof(__pyx_k_n_iter), 0, 0, 1, 1}, + {&__pyx_n_s_n_samples, __pyx_k_n_samples, sizeof(__pyx_k_n_samples), 0, 0, 1, 1}, + {&__pyx_n_s_n_tasks, __pyx_k_n_tasks, sizeof(__pyx_k_n_tasks), 0, 0, 1, 1}, + {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, + {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, + {&__pyx_n_s_nn, __pyx_k_nn, sizeof(__pyx_k_nn), 0, 0, 1, 1}, + {&__pyx_n_s_norm_cols_X, __pyx_k_norm_cols_X, sizeof(__pyx_k_norm_cols_X), 0, 0, 1, 1}, + {&__pyx_n_s_normalize_sum, __pyx_k_normalize_sum, sizeof(__pyx_k_normalize_sum), 0, 0, 1, 1}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_numpy_linalg, __pyx_k_numpy_linalg, sizeof(__pyx_k_numpy_linalg), 0, 0, 1, 1}, + {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, + {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, + {&__pyx_n_s_positive, __pyx_k_positive, sizeof(__pyx_k_positive), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_n_s_q, __pyx_k_q, sizeof(__pyx_k_q), 0, 0, 1, 1}, + {&__pyx_n_s_q_dot_w, __pyx_k_q_dot_w, sizeof(__pyx_k_q_dot_w), 0, 0, 1, 1}, + {&__pyx_n_s_rand_r_state, __pyx_k_rand_r_state, sizeof(__pyx_k_rand_r_state), 0, 0, 1, 1}, + {&__pyx_n_s_rand_r_state_seed, __pyx_k_rand_r_state_seed, sizeof(__pyx_k_rand_r_state_seed), 0, 0, 1, 1}, + {&__pyx_n_s_randint, __pyx_k_randint, sizeof(__pyx_k_randint), 0, 0, 1, 1}, + {&__pyx_n_s_random, __pyx_k_random, sizeof(__pyx_k_random), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_rng, __pyx_k_rng, sizeof(__pyx_k_rng), 0, 0, 1, 1}, + {&__pyx_n_s_ry_sum, __pyx_k_ry_sum, sizeof(__pyx_k_ry_sum), 0, 0, 1, 1}, + {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, + {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_linear_model_cd_fast, __pyx_k_sklearn_linear_model_cd_fast, sizeof(__pyx_k_sklearn_linear_model_cd_fast), 0, 0, 1, 1}, + {&__pyx_n_s_sparse_enet_coordinate_descent, __pyx_k_sparse_enet_coordinate_descent, sizeof(__pyx_k_sparse_enet_coordinate_descent), 0, 0, 1, 1}, + {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, + {&__pyx_n_s_startptr, __pyx_k_startptr, sizeof(__pyx_k_startptr), 0, 0, 1, 1}, + {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, + {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, + {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, + {&__pyx_n_s_sum, __pyx_k_sum, sizeof(__pyx_k_sum), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_tmp, __pyx_k_tmp, sizeof(__pyx_k_tmp), 0, 0, 1, 1}, + {&__pyx_n_s_tol, __pyx_k_tol, sizeof(__pyx_k_tol), 0, 0, 1, 1}, + {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, + {&__pyx_kp_s_unable_to_allocate_shape_and_str, __pyx_k_unable_to_allocate_shape_and_str, sizeof(__pyx_k_unable_to_allocate_shape_and_str), 0, 0, 1, 0}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, + {&__pyx_n_s_w, __pyx_k_w, sizeof(__pyx_k_w), 0, 0, 1, 1}, + {&__pyx_n_s_w_ii, __pyx_k_w_ii, sizeof(__pyx_k_w_ii), 0, 0, 1, 1}, + {&__pyx_n_s_w_max, __pyx_k_w_max, sizeof(__pyx_k_w_max), 0, 0, 1, 1}, + {&__pyx_n_s_w_norm, __pyx_k_w_norm, sizeof(__pyx_k_w_norm), 0, 0, 1, 1}, + {&__pyx_n_s_w_norm2, __pyx_k_w_norm2, sizeof(__pyx_k_w_norm2), 0, 0, 1, 1}, + {&__pyx_n_s_warn, __pyx_k_warn, sizeof(__pyx_k_warn), 0, 0, 1, 1}, + {&__pyx_n_s_warnings, __pyx_k_warnings, sizeof(__pyx_k_warnings), 0, 0, 1, 1}, + {&__pyx_n_s_wii_ptr, __pyx_k_wii_ptr, sizeof(__pyx_k_wii_ptr), 0, 0, 1, 1}, + {&__pyx_n_s_xrange, __pyx_k_xrange, sizeof(__pyx_k_xrange), 0, 0, 1, 1}, + {&__pyx_n_s_y, __pyx_k_y, sizeof(__pyx_k_y), 0, 0, 1, 1}, + {&__pyx_n_s_y_norm2, __pyx_k_y_norm2, sizeof(__pyx_k_y_norm2), 0, 0, 1, 1}, + {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 789; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "sklearn/linear_model/cd_fast.pyx":176 + * + * if alpha == 0: + * warnings.warn("Coordinate descent with alpha=0 may lead to unexpected" # <<<<<<<<<<<<<< + * " results and is discouraged.") + * + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_s_Coordinate_descent_with_alpha_0); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "sklearn/linear_model/cd_fast.pyx":537 + * + * if alpha == 0: + * warnings.warn("Coordinate descent with alpha=0 may lead to unexpected" # <<<<<<<<<<<<<< + * " results and is discouraged.") + * + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_Coordinate_descent_with_alpha_0); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "sklearn/linear_model/cd_fast.pyx":683 + * + * if l1_reg == 0: + * warnings.warn("Coordinate descent with l1_reg=0 may lead to unexpected" # <<<<<<<<<<<<<< + * " results and is discouraged.") + * + */ + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_Coordinate_descent_with_l1_reg_0); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 683; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + + /* "../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + + /* "View.MemoryView":127 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if itemsize <= 0: + */ + __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + + /* "View.MemoryView":130 + * + * if itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * if isinstance(format, unicode): + */ + __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__11); + __Pyx_GIVEREF(__pyx_tuple__11); + + /* "View.MemoryView":142 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + + /* "View.MemoryView":170 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__13); + __Pyx_GIVEREF(__pyx_tuple__13); + + /* "View.MemoryView":186 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_tuple__14 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__14)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_GIVEREF(__pyx_tuple__14); + + /* "View.MemoryView":445 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__15)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__15); + __Pyx_GIVEREF(__pyx_tuple__15); + + /* "View.MemoryView":521 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__16)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__16); + __Pyx_GIVEREF(__pyx_tuple__16); + + /* "View.MemoryView":638 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_slice__17 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__17)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice__17); + __Pyx_GIVEREF(__pyx_slice__17); + + /* "View.MemoryView":641 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_slice__18 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__18)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice__18); + __Pyx_GIVEREF(__pyx_slice__18); + + /* "View.MemoryView":652 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_slice__19 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__19)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice__19); + __Pyx_GIVEREF(__pyx_slice__19); + + /* "View.MemoryView":660 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__20)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__20); + __Pyx_GIVEREF(__pyx_tuple__20); + + /* "sklearn/linear_model/cd_fast.pyx":126 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, # <<<<<<<<<<<<<< + * double alpha, double beta, + * np.ndarray[DOUBLE, ndim=2] X, + */ + __pyx_tuple__22 = PyTuple_Pack(35, __pyx_n_s_w, __pyx_n_s_alpha, __pyx_n_s_beta, __pyx_n_s_X, __pyx_n_s_y, __pyx_n_s_max_iter, __pyx_n_s_tol, __pyx_n_s_rng, __pyx_n_s_random, __pyx_n_s_positive, __pyx_n_s_n_samples, __pyx_n_s_n_features, __pyx_n_s_n_tasks, __pyx_n_s_norm_cols_X, __pyx_n_s_R, __pyx_n_s_XtA, __pyx_n_s_tmp, __pyx_n_s_w_ii, __pyx_n_s_d_w_max, __pyx_n_s_w_max, __pyx_n_s_d_w_ii, __pyx_n_s_gap, __pyx_n_s_d_w_tol, __pyx_n_s_dual_norm_XtA, __pyx_n_s_R_norm2, __pyx_n_s_w_norm2, __pyx_n_s_l1_norm, __pyx_n_s_ii, __pyx_n_s_i, __pyx_n_s_n_iter, __pyx_n_s_f_iter, __pyx_n_s_rand_r_state_seed, __pyx_n_s_rand_r_state, __pyx_n_s_const, __pyx_n_s_A_norm2); if (unlikely(!__pyx_tuple__22)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__22); + __Pyx_GIVEREF(__pyx_tuple__22); + __pyx_codeobj__23 = (PyObject*)__Pyx_PyCode_New(10, 0, 35, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__22, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_alex_work_src_scikit_lear, __pyx_n_s_enet_coordinate_descent, 126, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/linear_model/cd_fast.pyx":290 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def sparse_enet_coordinate_descent(double[:] w, # <<<<<<<<<<<<<< + * double alpha, double beta, + * double[:] X_data, int[:] X_indices, + */ + __pyx_tuple__24 = PyTuple_Pack(45, __pyx_n_s_w, __pyx_n_s_alpha, __pyx_n_s_beta, __pyx_n_s_X_data, __pyx_n_s_X_indices, __pyx_n_s_X_indptr, __pyx_n_s_y, __pyx_n_s_X_mean, __pyx_n_s_max_iter, __pyx_n_s_tol, __pyx_n_s_rng, __pyx_n_s_random, __pyx_n_s_positive, __pyx_n_s_n_samples, __pyx_n_s_n_features, __pyx_n_s_ii, __pyx_n_s_norm_cols_X, __pyx_n_s_startptr, __pyx_n_s_endptr, __pyx_n_s_n_tasks, __pyx_n_s_R, __pyx_n_s_X_T_R, __pyx_n_s_XtA, __pyx_n_s_tmp, __pyx_n_s_w_ii, __pyx_n_s_d_w_max, __pyx_n_s_w_max, __pyx_n_s_d_w_ii, __pyx_n_s_X_mean_ii, __pyx_n_s_R_sum, __pyx_n_s_normalize_sum, __pyx_n_s_gap, __pyx_n_s_d_w_tol, __pyx_n_s_jj, __pyx_n_s_n_iter, __pyx_n_s_f_iter, __pyx_n_s_rand_r_state_seed, __pyx_n_s_rand_r_state, __pyx_n_s_center, __pyx_n_s_dual_norm_XtA, __pyx_n_s_R_norm2, __pyx_n_s_w_norm2, __pyx_n_s_const, __pyx_n_s_A_norm2, __pyx_n_s_l1_norm); if (unlikely(!__pyx_tuple__24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__24); + __Pyx_GIVEREF(__pyx_tuple__24); + __pyx_codeobj__25 = (PyObject*)__Pyx_PyCode_New(13, 0, 45, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__24, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_alex_work_src_scikit_lear, __pyx_n_s_sparse_enet_coordinate_descent, 290, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/linear_model/cd_fast.pyx":489 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def enet_coordinate_descent_gram(double[:] w, double alpha, double beta, # <<<<<<<<<<<<<< + * double[:, :] Q, double[:] q, double[:] y, + * int max_iter, double tol, object rng, + */ + __pyx_tuple__26 = PyTuple_Pack(38, __pyx_n_s_w, __pyx_n_s_alpha, __pyx_n_s_beta, __pyx_n_s_Q, __pyx_n_s_q, __pyx_n_s_y, __pyx_n_s_max_iter, __pyx_n_s_tol, __pyx_n_s_rng, __pyx_n_s_random, __pyx_n_s_positive, __pyx_n_s_n_samples, __pyx_n_s_n_features, __pyx_n_s_n_tasks, __pyx_n_s_H, __pyx_n_s_XtA, __pyx_n_s_tmp, __pyx_n_s_w_ii, __pyx_n_s_d_w_max, __pyx_n_s_w_max, __pyx_n_s_d_w_ii, __pyx_n_s_gap, __pyx_n_s_d_w_tol, __pyx_n_s_dual_norm_XtA, __pyx_n_s_ii, __pyx_n_s_n_iter, __pyx_n_s_f_iter, __pyx_n_s_rand_r_state_seed, __pyx_n_s_rand_r_state, __pyx_n_s_y_norm2, __pyx_n_s_Q_ptr, __pyx_n_s_H_ptr, __pyx_n_s_XtA_ptr, __pyx_n_s_q_dot_w, __pyx_n_s_R_norm2, __pyx_n_s_w_norm2, __pyx_n_s_const, __pyx_n_s_A_norm2); if (unlikely(!__pyx_tuple__26)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__26); + __Pyx_GIVEREF(__pyx_tuple__26); + __pyx_codeobj__27 = (PyObject*)__Pyx_PyCode_New(11, 0, 38, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__26, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_alex_work_src_scikit_lear, __pyx_n_s_enet_coordinate_descent_gram, 489, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__27)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/linear_model/cd_fast.pyx":630 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def enet_coordinate_descent_multi_task(double[::1, :] W, double l1_reg, # <<<<<<<<<<<<<< + * double l2_reg, double[::1, :] X, + * double[:, :] Y, int max_iter, + */ + __pyx_tuple__28 = PyTuple_Pack(42, __pyx_n_s_W, __pyx_n_s_l1_reg, __pyx_n_s_l2_reg, __pyx_n_s_X, __pyx_n_s_Y, __pyx_n_s_max_iter, __pyx_n_s_tol, __pyx_n_s_rng, __pyx_n_s_random, __pyx_n_s_n_samples, __pyx_n_s_n_features, __pyx_n_s_n_tasks, __pyx_n_s_XtA, __pyx_n_s_XtA_axis1norm, __pyx_n_s_dual_norm_XtA, __pyx_n_s_R, __pyx_n_s_norm_cols_X, __pyx_n_s_tmp, __pyx_n_s_w_ii, __pyx_n_s_d_w_max, __pyx_n_s_w_max, __pyx_n_s_d_w_ii, __pyx_n_s_nn, __pyx_n_s_W_ii_abs_max, __pyx_n_s_gap, __pyx_n_s_d_w_tol, __pyx_n_s_ry_sum, __pyx_n_s_l21_norm, __pyx_n_s_ii, __pyx_n_s_jj, __pyx_n_s_n_iter, __pyx_n_s_f_iter, __pyx_n_s_rand_r_state_seed, __pyx_n_s_rand_r_state, __pyx_n_s_X_ptr, __pyx_n_s_W_ptr, __pyx_n_s_Y_ptr, __pyx_n_s_wii_ptr, __pyx_n_s_R_norm, __pyx_n_s_w_norm, __pyx_n_s_const, __pyx_n_s_A_norm); if (unlikely(!__pyx_tuple__28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__28); + __Pyx_GIVEREF(__pyx_tuple__28); + __pyx_codeobj__29 = (PyObject*)__Pyx_PyCode_New(9, 0, 42, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__28, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_alex_work_src_scikit_lear, __pyx_n_s_enet_coordinate_descent_multi_ta, 630, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":276 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_tuple__30 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__30)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__30); + __Pyx_GIVEREF(__pyx_tuple__30); + + /* "View.MemoryView":277 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_tuple__31 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__31)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__31); + __Pyx_GIVEREF(__pyx_tuple__31); + + /* "View.MemoryView":278 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__32 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__32)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__32); + __Pyx_GIVEREF(__pyx_tuple__32); + + /* "View.MemoryView":281 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_tuple__33 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__33)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__33); + __Pyx_GIVEREF(__pyx_tuple__33); + + /* "View.MemoryView":282 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__34 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__34)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__34); + __Pyx_GIVEREF(__pyx_tuple__34); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC initcd_fast(void); /*proto*/ +PyMODINIT_FUNC initcd_fast(void) +#else +PyMODINIT_FUNC PyInit_cd_fast(void); /*proto*/ +PyMODINIT_FUNC PyInit_cd_fast(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_cd_fast(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4("cd_fast", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__linear_model__cd_fast) { + if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.linear_model.cd_fast")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.linear_model.cd_fast", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + generic = Py_None; Py_INCREF(Py_None); + strided = Py_None; Py_INCREF(Py_None); + indirect = Py_None; Py_INCREF(Py_None); + contiguous = Py_None; Py_INCREF(Py_None); + indirect_contiguous = Py_None; Py_INCREF(Py_None); + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_array.tp_print = 0; + __pyx_array_type = &__pyx_type___pyx_array; + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_MemviewEnum.tp_print = 0; + __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; + __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; + __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; + __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; + __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; + __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; + __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; + __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; + __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; + if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_memoryview.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryview_type = &__pyx_type___pyx_memoryview; + __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; + __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; + __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; + __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; + __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_memoryviewslice.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), 0); if (unlikely(!__pyx_ptype_7cpython_4bool_bool)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), 0); if (unlikely(!__pyx_ptype_7cpython_7complex_complex)) {__pyx_filename = __pyx_f[5]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/linear_model/cd_fast.pyx":11 + * from libc.math cimport fabs, sqrt + * cimport numpy as np + * import numpy as np # <<<<<<<<<<<<<< + * import numpy.linalg as linalg + * + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":12 + * cimport numpy as np + * import numpy as np + * import numpy.linalg as linalg # <<<<<<<<<<<<<< + * + * cimport cython + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s__21); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s__21); + __Pyx_GIVEREF(__pyx_n_s__21); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_numpy_linalg, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_linalg, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":16 + * cimport cython + * from cpython cimport bool + * import warnings # <<<<<<<<<<<<<< + * + * ctypedef np.float64_t DOUBLE + */ + __pyx_t_2 = __Pyx_Import(__pyx_n_s_warnings, 0, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_warnings, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":21 + * ctypedef np.uint32_t UINT32_t + * + * np.import_array() # <<<<<<<<<<<<<< + * + * # The following two functions are shamelessly copied from the tree code. + */ + import_array(); + + /* "sklearn/linear_model/cd_fast.pyx":126 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, # <<<<<<<<<<<<<< + * double alpha, double beta, + * np.ndarray[DOUBLE, ndim=2] X, + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_7cd_fast_1enet_coordinate_descent, NULL, __pyx_n_s_sklearn_linear_model_cd_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_enet_coordinate_descent, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":290 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def sparse_enet_coordinate_descent(double[:] w, # <<<<<<<<<<<<<< + * double alpha, double beta, + * double[:] X_data, int[:] X_indices, + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_7cd_fast_3sparse_enet_coordinate_descent, NULL, __pyx_n_s_sklearn_linear_model_cd_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_sparse_enet_coordinate_descent, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":489 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def enet_coordinate_descent_gram(double[:] w, double alpha, double beta, # <<<<<<<<<<<<<< + * double[:, :] Q, double[:] q, double[:] y, + * int max_iter, double tol, object rng, + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_7cd_fast_5enet_coordinate_descent_gram, NULL, __pyx_n_s_sklearn_linear_model_cd_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_enet_coordinate_descent_gram, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 489; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":630 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def enet_coordinate_descent_multi_task(double[::1, :] W, double l1_reg, # <<<<<<<<<<<<<< + * double l2_reg, double[::1, :] X, + * double[:, :] Y, int max_iter, + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_7cd_fast_7enet_coordinate_descent_multi_task, NULL, __pyx_n_s_sklearn_linear_model_cd_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_enet_coordinate_descent_multi_ta, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/linear_model/cd_fast.pyx":1 + * # Author: Alexandre Gramfort # <<<<<<<<<<<<<< + * # Fabian Pedregosa + * # Olivier Grisel + */ + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":203 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * def __dealloc__(array self): + */ + __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_array_type); + + /* "View.MemoryView":276 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__30, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(generic); + __Pyx_DECREF_SET(generic, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":277 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__31, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(strided); + __Pyx_DECREF_SET(strided, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":278 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__32, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(indirect); + __Pyx_DECREF_SET(indirect, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":281 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__33, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(contiguous); + __Pyx_DECREF_SET(contiguous, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":282 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__34, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(indirect_contiguous); + __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":496 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_memoryview_type); + + /* "View.MemoryView":953 + * return self.from_object + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_memoryviewslice_type); + + /* "View.MemoryView":1361 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + if (__pyx_d) { + __Pyx_AddTraceback("init sklearn.linear_model.cd_fast", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_d); __pyx_d = 0; + } + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.linear_model.cd_fast"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static CYTHON_INLINE long __Pyx_mod_long(long a, long b) { + long r = a % b; + r += ((r != 0) & ((r ^ b) < 0)) * b; + return r; +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, + int full_traceback) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + if (full_traceback) { + Py_XINCREF(old_exc); + Py_XINCREF(old_val); + Py_XINCREF(old_tb); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + PyErr_PrintEx(1); + } + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(PyObject_TypeCheck(obj, type))) return 1; + } + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case '\r': + case '\n': + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + ctx->enc_count = 0; + ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { @@ -10141,417 +23115,1921 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha if (!ts_after_sub) return NULL; } ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; + } + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (likely(result)) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = PyCFunction_GET_FUNCTION(func); + self = PyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *result; + PyObject *args = PyTuple_New(1); + if (unlikely(!args)) return NULL; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, arg); + result = __Pyx_PyObject_Call(func, args, NULL); + Py_DECREF(args); + return result; +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { +#ifdef __Pyx_CyFunction_USED + if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { +#else + if (likely(PyCFunction_Check(func))) { +#endif + if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { + return __Pyx_PyObject_CallMethO(func, arg); + } + } + return __Pyx__PyObject_CallOneArg(func, arg); +} +#else +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject* args = PyTuple_Pack(1, arg); + return (likely(args)) ? __Pyx_PyObject_Call(func, args, NULL) : NULL; +} +#endif + +static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (!buf) { + PyErr_SetString(PyExc_ValueError, + "buf is NULL."); + goto fail; + } else if (memviewslice->memview || memviewslice->data) { + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); + } + retval = 0; + goto no_fail; +fail: + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} +static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { + va_list vargs; + char msg[200]; + va_start(vargs, fmt); +#ifdef HAVE_STDARG_PROTOTYPES + va_start(vargs, fmt); +#else + va_start(vargs); +#endif + vsnprintf(msg, 200, fmt, vargs); + Py_FatalError(msg); + va_end(vargs); +} +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) +{ + int first_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview || (PyObject *) memview == Py_None) + return; + if (__pyx_get_slice_count(memview) < 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + first_time = __pyx_add_acquisition_count(memview) == 0; + if (first_time) { + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); + } + } +} +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, + int have_gil, int lineno) { + int last_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview ) { + return; + } else if ((PyObject *) memview == Py_None) { + memslice->memview = NULL; + return; + } + if (__pyx_get_slice_count(memview) <= 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; + if (last_time) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } + } else { + memslice->memview = NULL; + } +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + if (PyType_Check(type)) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } } - break; - case '}': /* end of substruct; either repeat or move on */ - ++ts; - return ts; - case 'x': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->fmt_offset += ctx->new_count; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->enc_packmode = ctx->new_packmode; - ++ts; - break; - case 'Z': - got_Z = 1; - ++ts; - if (*ts != 'f' && *ts != 'd' && *ts != 'g') { - __Pyx_BufFmt_RaiseUnexpectedChar('Z'); - return NULL; - } /* fall through */ - case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': - case 'l': case 'L': case 'q': case 'Q': - case 'f': case 'd': case 'g': - case 'O': - if (ctx->enc_type == *ts && got_Z == ctx->is_complex && - ctx->enc_packmode == ctx->new_packmode) { - /* Continue pooling same type */ - ctx->enc_count += ctx->new_count; + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); } else { - /* New type */ - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; } - ++ts; - ctx->new_count = 1; - got_Z = 0; - break; - case ':': - ++ts; - while(*ts != ':') ++ts; - ++ts; - break; - default: - { - int number = __Pyx_BufFmt_ParseNumber(&ts); - if (number == -1) { /* First char was not a digit */ - PyErr_Format(PyExc_ValueError, - "Does not understand character buffer dtype format string ('%c')", *ts); - return NULL; - } - ctx->new_count = (size_t)number; + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); } } - } +bad: + Py_XDECREF(owned_instance); + return; } +#endif -static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { - buf->buf = NULL; - buf->obj = NULL; - buf->strides = __Pyx_zeros; - buf->shape = __Pyx_zeros; - buf->suboffsets = __Pyx_minusones; +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { - if (obj == Py_None || obj == NULL) { - __Pyx_ZeroBuffer(buf); - return 0; - } - buf->buf = NULL; - if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; - if (buf->ndim != nd) { - PyErr_Format(PyExc_ValueError, - "Buffer has wrong number of dimensions (expected %d, got %d)", - nd, buf->ndim); - goto fail; - } - if (!cast) { - __Pyx_BufFmt_Context ctx; - __Pyx_BufFmt_Init(&ctx, stack, dtype); - if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; - } - if ((unsigned)buf->itemsize != dtype->size) { +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", - buf->itemsize, (buf->itemsize > 1) ? "s" : "", - dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); - goto fail; - } - if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; - return 0; -fail:; - __Pyx_ZeroBuffer(buf); - return -1; + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); + } +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif +} + +static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { + Py_ssize_t q = a / b; + Py_ssize_t r = a - q*b; + q -= ((r != 0) & ((r ^ b) < 0)); + return q; +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +#if CYTHON_COMPILING_IN_CPYTHON +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) +#else + if (likely(PyString_Check(n))) +#endif + return __Pyx_PyObject_GetAttrStr(o, n); +#endif + return PyObject_GetAttr(o, n); +} + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + length = strlen(cstring); + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +#else + PyErr_GetExcInfo(type, value, tb); +#endif +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(type, value, tb); +#endif +} + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } + #endif + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; +#else + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); +#endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +static CYTHON_INLINE long __Pyx_div_long(long a, long b) { + long q = a / b; + long r = a - q*b; + q -= ((r != 0) & ((r ^ b) < 0)); + return q; +} + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; } -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { - if (info->buf == NULL) return; - if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; - __Pyx_ReleaseBuffer(info); +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } } - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; } - -static void __Pyx_RaiseBufferFallbackError(void) { - PyErr_Format(PyExc_ValueError, - "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); } +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); - - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + Py_DECREF(obj); + view->obj = NULL; } +#endif -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { - PyThreadState *tstate = PyThreadState_GET(); - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; } +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ + { \ + func_type value = func_value; \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + if (is_unsigned && unlikely(value < zero)) \ + goto raise_neg_overflow; \ + else \ + goto raise_overflow; \ + } \ + } \ + return (target_type) value; \ + } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif - +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ - Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; - Py_INCREF(value); - } - #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) - #else - if (!PyType_Check(type)) - #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; } - /* Normalize to raise , */ - Py_DECREF(value); - value = type; - #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, ((PyLongObject*)x)->ob_digit[0]); } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; } - #else - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong(x)) } - #endif + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong(x)) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; } - - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; } -#else /* Python 3+ */ - -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; +static int +__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) +{ + int i; + if (!a || !b) + return 0; + if (a == b) + return 1; + if (a->size != b->size || a->typegroup != b->typegroup || + a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { + if (a->typegroup == 'H' || b->typegroup == 'H') { + return a->size == b->size; + } else { + return 0; + } } - if (value == Py_None) - value = 0; - - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; + if (a->ndim) { + for (i = 0; i < a->ndim; i++) + if (a->arraysize[i] != b->arraysize[i]) + return 0; + } + if (a->typegroup == 'S') { + if (a->flags != b->flags) + return 0; + if (a->fields || b->fields) { + if (!(a->fields && b->fields)) + return 0; + for (i = 0; a->fields[i].type && b->fields[i].type; i++) { + __Pyx_StructField *field_a = a->fields + i; + __Pyx_StructField *field_b = b->fields + i; + if (field_a->offset != field_b->offset || + !__pyx_typeinfo_cmp(field_a->type, field_b->type)) + return 0; + } + return !a->fields[i].type && !b->fields[i].type; } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; } + return 1; +} - if (cause) { - PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; +static int +__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) +{ + if (buf->shape[dim] <= 1) + return 1; + if (buf->strides) { + if (spec & __Pyx_MEMVIEW_CONTIG) { + if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { + if (buf->strides[dim] != sizeof(void *)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly contiguous " + "in dimension %d.", dim); + goto fail; + } + } else if (buf->strides[dim] != buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_FOLLOW) { + Py_ssize_t stride = buf->strides[dim]; + if (stride < 0) + stride = -stride; + if (stride < buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + } else { + if (spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not contiguous in " + "dimension %d", dim); + goto fail; + } else if (spec & (__Pyx_MEMVIEW_PTR)) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not indirect in " + "dimension %d", dim); + goto fail; + } else if (buf->suboffsets) { + PyErr_SetString(PyExc_ValueError, + "Buffer exposes suboffsets but no strides"); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) +{ + if (spec & __Pyx_MEMVIEW_DIRECT) { + if (buf->suboffsets && buf->suboffsets[dim] >= 0) { + PyErr_Format(PyExc_ValueError, + "Buffer not compatible with direct access " + "in dimension %d.", dim); + goto fail; } - else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); + } + if (spec & __Pyx_MEMVIEW_PTR) { + if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly accessible " + "in dimension %d.", dim); + goto fail; } - else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; + } + return 1; +fail: + return 0; +} +static int +__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) +{ + int i; + if (c_or_f_flag & __Pyx_IS_F_CONTIG) { + Py_ssize_t stride = 1; + for (i = 0; i < ndim; i++) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) + { + PyErr_SetString(PyExc_ValueError, + "Buffer not fortran contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; } - if (!value) { - value = PyObject_CallObject(type, NULL); + } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { + Py_ssize_t stride = 1; + for (i = ndim - 1; i >- 1; i--) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) { + PyErr_SetString(PyExc_ValueError, + "Buffer not C contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; } - PyException_SetCause(value, fixed_cause); } - - PyErr_SetObject(type, value); - - if (tb) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } + return 1; +fail: + return 0; +} +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj) +{ + struct __pyx_memoryview_obj *memview, *new_memview; + __Pyx_RefNannyDeclarations + Py_buffer *buf; + int i, spec = 0, retval = -1; + __Pyx_BufFmt_Context ctx; + int from_memoryview = __pyx_memoryview_check(original_obj); + __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); + if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) + original_obj)->typeinfo)) { + memview = (struct __pyx_memoryview_obj *) original_obj; + new_memview = NULL; + } else { + memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + original_obj, buf_flags, 0, dtype); + new_memview = memview; + if (unlikely(!memview)) + goto fail; + } + buf = &memview->view; + if (buf->ndim != ndim) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + ndim, buf->ndim); + goto fail; + } + if (new_memview) { + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned) buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " + "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", + buf->itemsize, + (buf->itemsize > 1) ? "s" : "", + dtype->name, + dtype->size, + (dtype->size > 1) ? "s" : ""); + goto fail; + } + for (i = 0; i < ndim; i++) { + spec = axes_specs[i]; + if (!__pyx_check_strides(buf, i, ndim, spec)) + goto fail; + if (!__pyx_check_suboffsets(buf, i, ndim, spec)) + goto fail; } + if (buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, + new_memview != NULL) == -1)) { + goto fail; + } + retval = 0; + goto no_fail; +fail: + Py_XDECREF(new_memview); + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} -bad: - return; +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS, 1, + &__Pyx_TypeInfo_double, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; } -#endif -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS, 1, + &__Pyx_TypeInfo_int, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; } -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS, 2, + &__Pyx_TypeInfo_double, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; } -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dcd__double(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_F_CONTIG, + (PyBUF_F_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2, + &__Pyx_TypeInfo_double, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } } else { - __Pyx_RaiseTooManyValuesError(index); + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); } } -#if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); - else { - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value) { + const unsigned int neg_one = (unsigned int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(unsigned int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(unsigned int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(unsigned int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(unsigned int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(unsigned int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(unsigned int), + little, !is_unsigned); } } -static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject* obj = view->obj; - if (obj) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;} - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray_1__releasebuffer__(obj, view); - Py_DECREF(obj); - view->obj = NULL; - } +static CYTHON_INLINE npy_uint32 __Pyx_PyInt_As_npy_uint32(PyObject *x) { + const npy_uint32 neg_one = (npy_uint32) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(npy_uint32) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (npy_uint32) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_uint32, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(npy_uint32) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(npy_uint32) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_uint32, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(npy_uint32, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(npy_uint32) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, long, PyLong_AsLong(x)) + } else if (sizeof(npy_uint32) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + npy_uint32 val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (npy_uint32) -1; + } + } else { + npy_uint32 val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (npy_uint32) -1; + val = __Pyx_PyInt_As_npy_uint32(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to npy_uint32"); + return (npy_uint32) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to npy_uint32"); + return (npy_uint32) -1; } +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) { + const unsigned int neg_one = (unsigned int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(unsigned int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (unsigned int) val; + } + } else #endif - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); - if (!py_import) - goto bad; - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - #if PY_VERSION_HEX >= 0x02050000 - { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - } - #else - if (level>0) { - PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); - goto bad; + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(unsigned int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(unsigned int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(unsigned int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(unsigned int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyLong_AsLong(x)) + } else if (sizeof(unsigned int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + unsigned int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (unsigned int) -1; + } + } else { + unsigned int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned int) -1; + val = __Pyx_PyInt_As_unsigned_int(tmp); + Py_DECREF(tmp); + return val; } - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, NULL); - #endif -bad: - Py_XDECREF(empty_list); - Py_XDECREF(py_import); - Py_XDECREF(empty_dict); - return module; +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to unsigned int"); + return (unsigned int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned int"); + return (unsigned int) -1; } -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32 val) { - const npy_int32 neg_one = (npy_int32)-1, const_zero = (npy_int32)0; - const int is_unsigned = const_zero < neg_one; - if ((sizeof(npy_int32) == sizeof(char)) || - (sizeof(npy_int32) == sizeof(short))) { - return PyInt_FromLong((long)val); - } else if ((sizeof(npy_int32) == sizeof(int)) || - (sizeof(npy_int32) == sizeof(long))) { - if (is_unsigned) - return PyLong_FromUnsignedLong((unsigned long)val); - else - return PyInt_FromLong((long)val); - } else if (sizeof(npy_int32) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); - else - return PyLong_FromLongLong((PY_LONG_LONG)val); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - return _PyLong_FromByteArray(bytes, sizeof(npy_int32), + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + for (i = 0; i < ndim; i++) { + if (from_mvs->suboffsets[i] >= 0) { + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; + } + } + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; + } + __Pyx_GOTREF(shape_tuple); + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; + } else { + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; + } + } + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + goto no_fail; +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; +} + +static PyObject *__pyx_memview_get_double(const char *itemp) { + return (PyObject *) PyFloat_FromDouble(*(double *) itemp); +} +static int __pyx_memview_set_double(const char *itemp, PyObject *obj) { + double value = __pyx_PyFloat_AsDouble(obj); + if ((value == (double)-1) && PyErr_Occurred()) + return 0; + *(double *) itemp = value; + return 1; +} + #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { @@ -10787,409 +25265,312 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32 val) { z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cos(z_theta); z.imag = z_r * sin(z_theta); - return z; - } - #endif -#endif - -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; - } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; - } - return (unsigned short)val; - } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; - } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; - } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; - } - return (short)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; - } - return (signed char)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; + return z; } - return (signed short)val; - } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} + #endif +#endif -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; - } - return (signed int)val; +static int +__pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim) +{ + int i, index, step, start; + Py_ssize_t itemsize = mvs->memview->view.itemsize; + if (order == 'F') { + step = 1; + start = 0; + } else { + step = -1; + start = ndim - 1; } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; + for (i = 0; i < ndim; i++) { + index = start + step * i; + if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) + return 0; + itemsize *= mvs->shape[index]; } - return (int)__Pyx_PyInt_AsLong(x); + return 1; } -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)PyLong_AsUnsignedLong(x); +static void +__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + start = end = slice->data; + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + if (extent == 0) { + *out_start = *out_end = start; + return; } else { - return (unsigned long)PyLong_AsLong(x); + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; } + *out_start = start; + *out_end = end + itemsize; +} +static int +__pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize) +{ + void *start1, *end1, *start2, *end2; + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + return (start1 < end2) && (start2 < end1); } -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)val; - } else +static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) +{ + PyObject *cobj; +#if PY_VERSION_HEX >= 0x02070000 + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; - } + return cobj; } -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { + const char neg_one = (char) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; + if (sizeof(char) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (char) val; } - return (long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(char, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; + goto raise_neg_overflow; + } + if (sizeof(char) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(char) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long long, PyLong_AsUnsignedLongLong(x)) } - return (long)PyLong_AsUnsignedLong(x); } else { - return (long)PyLong_AsLong(x); +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(char, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(char) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyLong_AsLong(x)) + } else if (sizeof(char) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(char, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + char val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (char) -1; } } else { - long val; + char val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); + if (!tmp) return (char) -1; + val = __Pyx_PyInt_As_char(tmp); Py_DECREF(tmp); return val; } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to char"); + return (char) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to char"); + return (char) -1; } -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; } - return (PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; + goto raise_neg_overflow; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong(x)) } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { - return (PY_LONG_LONG)PyLong_AsLongLong(x); +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong(x)) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; } } else { - PY_LONG_LONG val; + long val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; } -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)PyLong_AsUnsignedLong(x); - } else { - return (signed long)PyLong_AsLong(x); - } - } else { - signed long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); - Py_DECREF(tmp); - return val; +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2, + &__Pyx_TypeInfo_double, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; } -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; - } - return (signed PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; - } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - signed PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); - Py_DECREF(tmp); - return val; +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_double(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_double, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; } static int __Pyx_check_binary_version(void) { @@ -11202,15 +25583,28 @@ static int __Pyx_check_binary_version(void) { "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); - #if PY_VERSION_HEX < 0x02050000 - return PyErr_Warn(NULL, message); - #else return PyErr_WarnEx(NULL, message, 1); - #endif } return 0; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -11220,15 +25614,14 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(class_name); - #else - py_name = PyUnicode_FromString(class_name); - #endif + py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); @@ -11240,23 +25633,31 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", + "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); - #if PY_VERSION_HEX < 0x02050000 - if (PyErr_Warn(NULL, warning) < 0) goto bad; - #else if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", + "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } @@ -11268,99 +25669,6 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(name); - #else - py_name = PyUnicode_FromString(name); - #endif - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; -} -#endif - -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); - #else - py_srcfile = PyUnicode_FromString(__pyx_filename); - #endif - if (!py_srcfile) goto bad; - if (__pyx_clineno) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_code = PyCode_New( - 0, /*int argcount,*/ - #if PY_MAJOR_VERSION >= 3 - 0, /*int kwonlyargcount,*/ - #endif - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ - 0, /*int flags,*/ - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - if (!py_code) goto bad; - py_frame = PyFrame_New( - PyThreadState_GET(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - py_globals, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 @@ -11371,7 +25679,7 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } - #else /* Python 3+ has unicode identifiers */ + #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); @@ -11391,26 +25699,88 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else + if (__Pyx_PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif + } else +#endif +#if !CYTHON_COMPILING_IN_PYPY + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -11426,13 +25796,13 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", + "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; @@ -11444,40 +25814,33 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { -#if PY_VERSION_HEX < 0x02050000 - if (ival <= LONG_MAX) - return PyInt_FromLong((long)ival); - else { - unsigned char *bytes = (unsigned char *) &ival; - int one = 1; int little = (int)*(unsigned char*)&one; - return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); - } -#else - return PyInt_FromSize_t(ival); -#endif -} - -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; + return PyInt_FromSize_t(ival); } diff --git a/sklearn/linear_model/cd_fast.pyx b/sklearn/linear_model/cd_fast.pyx index d8fb677748abd..ad2fd0d6069ba 100644 --- a/sklearn/linear_model/cd_fast.pyx +++ b/sklearn/linear_model/cd_fast.pyx @@ -2,26 +2,53 @@ # Fabian Pedregosa # Olivier Grisel # Alexis Mignon +# Manoj Kumar # -# License: BSD Style. +# Licence: BSD 3 clause +from libc.math cimport fabs, sqrt cimport numpy as np import numpy as np import numpy.linalg as linalg + cimport cython from cpython cimport bool import warnings -cdef extern from "math.h": - double fabs(double f) - double sqrt(double f) +ctypedef np.float64_t DOUBLE +ctypedef np.uint32_t UINT32_t + +np.import_array() + +# The following two functions are shamelessly copied from the tree code. + +cdef enum: + # Max value for our rand_r replacement (near the bottom). + # We don't use RAND_MAX because it's different across platforms and + # particularly tiny on Windows/MSVC. + RAND_R_MAX = 0x7FFFFFFF + + +cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil: + seed[0] ^= (seed[0] << 13) + seed[0] ^= (seed[0] >> 17) + seed[0] ^= (seed[0] << 5) -cdef inline double fmax(double x, double y): + return seed[0] % (RAND_R_MAX + 1) + + +cdef inline UINT32_t rand_int(UINT32_t end, UINT32_t* random_state) nogil: + """Generate a random integer in [0; end).""" + return our_rand_r(random_state) % end + + +cdef inline double fmax(double x, double y) nogil: if x > y: return x return y -cdef inline double fsign(double f): + +cdef inline double fsign(double f) nogil: if f == 0: return 0 elif f > 0: @@ -29,6 +56,43 @@ cdef inline double fsign(double f): else: return -1.0 + +cdef double abs_max(int n, double* a) nogil: + """np.max(np.abs(a))""" + cdef int i + cdef double m = fabs(a[0]) + cdef double d + for i in range(1, n): + d = fabs(a[i]) + if d > m: + m = d + return m + + +cdef double max(int n, double* a) nogil: + """np.max(a)""" + cdef int i + cdef double m = a[0] + cdef double d + for i in range(1, n): + d = a[i] + if d > m: + m = d + return m + + +cdef double diff_abs_max(int n, double* a, double* b) nogil: + """np.max(np.abs(a - b))""" + cdef int i + cdef double m = fabs(a[0] - b[0]) + cdef double d + for i in range(1, n): + d = fabs(a[i] - b[i]) + if d > m: + m = d + return m + + cdef extern from "cblas.h": enum CBLAS_ORDER: CblasRowMajor=101 @@ -40,64 +104,20 @@ cdef extern from "cblas.h": AtlasConj=114 void daxpy "cblas_daxpy"(int N, double alpha, double *X, int incX, - double *Y, int incY) - double ddot "cblas_ddot"(int N, double *X, int incX, double *Y, int incY) + double *Y, int incY) nogil + double ddot "cblas_ddot"(int N, double *X, int incX, double *Y, int incY + ) nogil + double dasum "cblas_dasum"(int N, double *X, int incX) nogil void dger "cblas_dger"(CBLAS_ORDER Order, int M, int N, double alpha, - double *X, int incX, double *Y, int incY, double *A, int lda) + double *X, int incX, double *Y, int incY, double *A, int lda) nogil void dgemv "cblas_dgemv"(CBLAS_ORDER Order, CBLAS_TRANSPOSE TransA, int M, int N, double alpha, double *A, int lda, double *X, int incX, double beta, - double *Y, int incY) - double dnrm2 "cblas_dnrm2"(int N, double *X, int incX) - void dcopy "cblas_dcopy"(int N, double *X, int incX, double *Y, int incY) - void dscal "cblas_dscal"(int N, double alpha, double *X, int incX) - - -ctypedef np.float64_t DOUBLE -ctypedef np.int32_t INTEGER - - -@cython.boundscheck(False) -@cython.wraparound(False) -@cython.cdivision(True) -def sparse_std(unsigned int n_samples, - unsigned int n_features, - np.ndarray[DOUBLE, ndim=1] X_data, - np.ndarray[INTEGER, ndim=1] X_indices, - np.ndarray[INTEGER, ndim=1] X_indptr, - np.ndarray[DOUBLE, ndim=1] X_mean=None): - cdef unsigned int ii - cdef unsigned int jj - cdef unsigned int nnz_ii - cdef double X_sum_ii - cdef double X_mean_ii - cdef double diff - cdef double X_std_ii - - cdef np.ndarray[DOUBLE, ndim = 1] X_std = np.zeros(n_features, np.float64) - - if X_mean is None: - X_mean = np.zeros(n_features, np.float64) - - for ii in xrange(n_features): - # Computes the mean - X_sum_ii = 0.0 - for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - X_sum_ii += X_data[jj] - X_mean[ii] = X_sum_ii / n_samples - - for ii in xrange(n_features): - X_mean_ii = X_mean[ii] - X_sum_ii = 0.0 - nnz_ii = 0 - for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - diff = X_data[jj] - X_mean_ii - X_sum_ii += diff * diff - nnz_ii += 1 - - X_std[ii] = (X_sum_ii + (n_samples - nnz_ii) * X_mean_ii * X_mean_ii) - return np.sqrt(X_std) + double *Y, int incY) nogil + double dnrm2 "cblas_dnrm2"(int N, double *X, int incX) nogil + void dcopy "cblas_dcopy"(int N, double *X, int incX, double *Y, int incY) nogil + void dscal "cblas_dscal"(int N, double alpha, double *X, int incX) nogil @cython.boundscheck(False) @@ -107,7 +127,8 @@ def enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, double alpha, double beta, np.ndarray[DOUBLE, ndim=2] X, np.ndarray[DOUBLE, ndim=1] y, - int max_iter, double tol, bool positive=False): + int max_iter, double tol, + object rng, bint random=0, bint positive=0): """Cython version of the coordinate descent algorithm for Elastic-Net regression @@ -123,12 +144,16 @@ def enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, cdef unsigned int n_samples = X.shape[0] cdef unsigned int n_features = X.shape[1] + # get the number of tasks indirectly, using strides + cdef unsigned int n_tasks = y.strides[0] / sizeof(DOUBLE) + # compute norms of the columns of X cdef np.ndarray[DOUBLE, ndim=1] norm_cols_X = (X**2).sum(axis=0) # initial value of the residuals - cdef np.ndarray[DOUBLE, ndim=1] R + cdef np.ndarray[DOUBLE, ndim=1] R = np.empty(n_samples) + cdef np.ndarray[DOUBLE, ndim=1] XtA = np.empty(n_features) cdef double tmp cdef double w_ii cdef double d_w_max @@ -136,100 +161,139 @@ def enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, cdef double d_w_ii cdef double gap = tol + 1.0 cdef double d_w_tol = tol + cdef double dual_norm_XtA + cdef double R_norm2 + cdef double w_norm2 + cdef double l1_norm cdef unsigned int ii + cdef unsigned int i cdef unsigned int n_iter + cdef unsigned int f_iter + cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + cdef UINT32_t* rand_r_state = &rand_r_state_seed if alpha == 0: warnings.warn("Coordinate descent with alpha=0 may lead to unexpected" " results and is discouraged.") - R = y - np.dot(X, w) - - tol = tol * linalg.norm(y) ** 2 - - for n_iter in range(max_iter): - w_max = 0.0 - d_w_max = 0.0 - for ii in xrange(n_features): # Loop over coordinates - if norm_cols_X[ii] == 0.0: - continue - - w_ii = w[ii] # Store previous value - - if w_ii != 0.0: - # R += w_ii * X[:,ii] - daxpy(n_samples, w_ii, - (X.data + ii * n_samples * sizeof(DOUBLE)), 1, - R.data, 1) - - # tmp = (X[:,ii]*R).sum() - tmp = ddot(n_samples, - (X.data + ii * n_samples * sizeof(DOUBLE)), 1, - R.data, 1) - - if positive and tmp < 0: - w[ii] = 0.0 - else: - w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ - / (norm_cols_X[ii] + beta) - - if w[ii] != 0.0: - # R -= w[ii] * X[:,ii] # Update residual - daxpy(n_samples, -w[ii], - (X.data + ii * n_samples * sizeof(DOUBLE)), 1, - R.data, 1) - - # update the maximum absolute coefficient update - d_w_ii = fabs(w[ii] - w_ii) - if d_w_ii > d_w_max: - d_w_max = d_w_ii - - if fabs(w[ii]) > w_max: - w_max = fabs(w[ii]) - - if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: - # the biggest coordinate update of this iteration was smaller than - # the tolerance: check the duality gap as ultimate stopping - # criterion - - XtA = np.dot(X.T, R) - beta * w - if positive: - dual_norm_XtA = np.max(XtA) - else: - dual_norm_XtA = linalg.norm(XtA, np.inf) - - # TODO: use squared L2 norm directly - R_norm = linalg.norm(R) - w_norm = linalg.norm(w, 2) - if (dual_norm_XtA > alpha): - const = alpha / dual_norm_XtA - A_norm = R_norm * const - gap = 0.5 * (R_norm ** 2 + A_norm ** 2) - else: - const = 1.0 - gap = R_norm ** 2 - - gap += alpha * linalg.norm(w, 1) - const * np.dot(R.T, y) + \ - 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) - - if gap < tol: - # return if we reached desired tolerance - break - - return w, gap, tol + with nogil: + + # R = y - np.dot(X, w) + for i in range(n_samples): + R[i] = y[i] - ddot(n_features, + (X.data + i * sizeof(DOUBLE)), + n_samples, w.data, 1) + + # tol *= np.dot(y, y) + tol *= ddot(n_samples, y.data, n_tasks, + y.data, n_tasks) + + for n_iter in range(max_iter): + w_max = 0.0 + d_w_max = 0.0 + for f_iter in range(n_features): # Loop over coordinates + if random: + ii = rand_int(n_features, rand_r_state) + else: + ii = f_iter + + if norm_cols_X[ii] == 0.0: + continue + + w_ii = w[ii] # Store previous value + + if w_ii != 0.0: + # R += w_ii * X[:,ii] + daxpy(n_samples, w_ii, + (X.data + ii * n_samples * sizeof(DOUBLE)), + 1, R.data, 1) + + # tmp = (X[:,ii]*R).sum() + tmp = ddot(n_samples, + (X.data + ii * n_samples * sizeof(DOUBLE)), + 1, R.data, 1) + + if positive and tmp < 0: + w[ii] = 0.0 + else: + w[ii] = (fsign(tmp) * fmax(fabs(tmp) - alpha, 0) + / (norm_cols_X[ii] + beta)) + + if w[ii] != 0.0: + # R -= w[ii] * X[:,ii] # Update residual + daxpy(n_samples, -w[ii], + (X.data + ii * n_samples * sizeof(DOUBLE)), + 1, R.data, 1) + + # update the maximum absolute coefficient update + d_w_ii = fabs(w[ii] - w_ii) + if d_w_ii > d_w_max: + d_w_max = d_w_ii + + if fabs(w[ii]) > w_max: + w_max = fabs(w[ii]) + + if (w_max == 0.0 + or d_w_max / w_max < d_w_tol + or n_iter == max_iter - 1): + # the biggest coordinate update of this iteration was smaller + # than the tolerance: check the duality gap as ultimate + # stopping criterion + + # XtA = np.dot(X.T, R) - beta * w + for i in range(n_features): + XtA[i] = ddot( + n_samples, + (X.data + i * n_samples *sizeof(DOUBLE)), + 1, R.data, 1) - beta * w[i] + + if positive: + dual_norm_XtA = max(n_features, XtA.data) + else: + dual_norm_XtA = abs_max(n_features, XtA.data) + + # R_norm2 = np.dot(R, R) + R_norm2 = ddot(n_samples, R.data, 1, + R.data, 1) + + # w_norm2 = np.dot(w, w) + w_norm2 = ddot(n_features, w.data, 1, + w.data, 1) + + if (dual_norm_XtA > alpha): + const = alpha / dual_norm_XtA + A_norm2 = R_norm2 * (const ** 2) + gap = 0.5 * (R_norm2 + A_norm2) + else: + const = 1.0 + gap = R_norm2 + + l1_norm = dasum(n_features, w.data, 1) + + # np.dot(R.T, y) + gap += (alpha * l1_norm - const * ddot( + n_samples, + R.data, 1, + y.data, n_tasks) + + 0.5 * beta * (1 + const ** 2) * (w_norm2)) + + if gap < tol: + # return if we reached desired tolerance + break + + return w, gap, tol, n_iter + 1 @cython.boundscheck(False) @cython.wraparound(False) @cython.cdivision(True) -def sparse_enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, +def sparse_enet_coordinate_descent(double[:] w, double alpha, double beta, - np.ndarray[DOUBLE, ndim=1] X_data, - np.ndarray[INTEGER, ndim=1] X_indices, - np.ndarray[INTEGER, ndim=1] X_indptr, - np.ndarray[DOUBLE, ndim=1] y, - np.ndarray[DOUBLE, ndim=1] X_mean, - int max_iter, double tol, bint positive=False): + double[:] X_data, int[:] X_indices, + int[:] X_indptr, double[:] y, + double[:] X_mean, int max_iter, + double tol, object rng, bint random=0, + bint positive=0): """Cython version of the coordinate descent algorithm for Elastic-Net We minimize: @@ -246,15 +310,19 @@ def sparse_enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, # compute norms of the columns of X cdef unsigned int ii - cdef np.ndarray[DOUBLE, ndim = 1] norm_cols_X = np.zeros(n_features, - np.float64) - for ii in xrange(n_features): - norm_cols_X[ii] = ((X_data[X_indptr[ii]:X_indptr[ii + 1]] - \ - X_mean[ii]) ** 2).sum() + \ - (n_samples - X_indptr[ii + 1] + X_indptr[ii]) * X_mean[ii] ** 2 + cdef double[:] norm_cols_X = np.zeros(n_features, np.float64) + + cdef unsigned int startptr = X_indptr[0] + cdef unsigned int endptr + + # get the number of tasks indirectly, using strides + cdef unsigned int n_tasks = y.strides[0] / sizeof(DOUBLE) # initial value of the residuals - cdef np.ndarray[DOUBLE, ndim = 1] R + cdef double[:] R = y.copy() + + cdef double[:] X_T_R = np.zeros(n_features) + cdef double[:] XtA = np.zeros(n_features) cdef double tmp cdef double w_ii @@ -263,127 +331,165 @@ def sparse_enet_coordinate_descent(np.ndarray[DOUBLE, ndim=1] w, cdef double d_w_ii cdef double X_mean_ii cdef double R_sum + cdef double normalize_sum cdef double gap = tol + 1.0 cdef double d_w_tol = tol cdef unsigned int jj cdef unsigned int n_iter - cdef bint center = (X_mean != 0).any() + cdef unsigned int f_iter + cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + cdef UINT32_t* rand_r_state = &rand_r_state_seed + cdef bint center = False + + with nogil: + # center = (X_mean != 0).any() + for ii in range(n_features): + if X_mean[ii]: + center = True + break - # initialize the residuals - R = y.copy() + for ii in range(n_features): + X_mean_ii = X_mean[ii] + endptr = X_indptr[ii + 1] + normalize_sum = 0.0 + w_ii = w[ii] - for ii in xrange(n_features): - # sparse X column / dense w dot product - for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - R[X_indices[jj]] -= X_data[jj] * w[ii] - if center: - R += X_mean[ii] * w[ii] + for jj in range(startptr, endptr): + normalize_sum += (X_data[jj] - X_mean_ii) ** 2 + R[X_indices[jj]] -= X_data[jj] * w_ii + norm_cols_X[ii] = normalize_sum + \ + (n_samples - endptr + startptr) * X_mean_ii ** 2 - tol = tol * linalg.norm(y) ** 2 + if center: + for jj in range(n_samples): + R[jj] += X_mean_ii * w_ii + startptr = endptr - for n_iter in range(max_iter): + # tol *= np.dot(y, y) + tol *= ddot(n_samples, &y[0], 1, &y[0], 1) - w_max = 0.0 - d_w_max = 0.0 + for n_iter in range(max_iter): - for ii in xrange(n_features): # Loop over coordinates + w_max = 0.0 + d_w_max = 0.0 - if norm_cols_X[ii] == 0.0: - continue + for f_iter in range(n_features): # Loop over coordinates + if random: + ii = rand_int(n_features, rand_r_state) + else: + ii = f_iter - w_ii = w[ii] # Store previous value - X_mean_ii = X_mean[ii] + if norm_cols_X[ii] == 0.0: + continue - if w_ii != 0.0: - # R += w_ii * X[:,ii] - for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - R[X_indices[jj]] += X_data[jj] * w_ii - if center: - for jj in xrange(n_samples): - R[jj] -= X_mean_ii * w[ii] + startptr = X_indptr[ii] + endptr = X_indptr[ii + 1] + w_ii = w[ii] # Store previous value + X_mean_ii = X_mean[ii] - # tmp = (X[:,ii] * R).sum() - tmp = 0.0 - for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - tmp += R[X_indices[jj]] * X_data[jj] + if w_ii != 0.0: + # R += w_ii * X[:,ii] + for jj in range(startptr, endptr): + R[X_indices[jj]] += X_data[jj] * w_ii + if center: + for jj in range(n_samples): + R[jj] -= X_mean_ii * w_ii - if center: - R_sum = 0.0 - for jj in xrange(n_samples): - R_sum += R[jj] - tmp -= R_sum * X_mean_ii - - if positive and tmp < 0.0: - w[ii] = 0.0 - else: - w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ - / (norm_cols_X[ii] + beta) - - if w[ii] != 0.0: - # R -= w[ii] * X[:,ii] # Update residual - for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - R[X_indices[jj]] -= X_data[jj] * w[ii] + # tmp = (X[:,ii] * R).sum() + tmp = 0.0 + for jj in range(startptr, endptr): + tmp += R[X_indices[jj]] * X_data[jj] if center: - for jj in xrange(n_samples): - R[jj] += X_mean_ii * w[ii] - - # update the maximum absolute coefficient update - d_w_ii = fabs(w[ii] - w_ii) - if d_w_ii > d_w_max: - d_w_max = d_w_ii - - if w[ii] > w_max: - w_max = w[ii] - - if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: - # the biggest coordinate update of this iteration was smaller than - # the tolerance: check the duality gap as ultimate stopping - # criterion - - # sparse X.T / dense R dot product - X_T_R = np.zeros(n_features) - for ii in xrange(n_features): - for jj in xrange(X_indptr[ii], X_indptr[ii + 1]): - X_T_R[ii] += X_data[jj] * R[X_indices[jj]] - X_T_R[ii] -= X_mean[ii] * R.sum() - - XtA = X_T_R - beta * w - if positive: - dual_norm_XtA = np.max(XtA) - else: - dual_norm_XtA = linalg.norm(XtA, np.inf) - - # TODO: use squared L2 norm directly - R_norm = linalg.norm(R) - w_norm = linalg.norm(w, 2) - if (dual_norm_XtA > alpha): - const = alpha / dual_norm_XtA - A_norm = R_norm * const - gap = 0.5 * (R_norm ** 2 + A_norm ** 2) - else: - const = 1.0 - gap = R_norm ** 2 - - gap += alpha * linalg.norm(w, 1) - const * np.dot(R.T, y) + \ - 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) - - if gap < tol: - # return if we reached desired tolerance - break - - return w, gap, tol + R_sum = 0.0 + for jj in range(n_samples): + R_sum += R[jj] + tmp -= R_sum * X_mean_ii + + if positive and tmp < 0.0: + w[ii] = 0.0 + else: + w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ + / (norm_cols_X[ii] + beta) + + if w[ii] != 0.0: + # R -= w[ii] * X[:,ii] # Update residual + for jj in range(startptr, endptr): + R[X_indices[jj]] -= X_data[jj] * w[ii] + + if center: + for jj in range(n_samples): + R[jj] += X_mean_ii * w[ii] + + # update the maximum absolute coefficient update + d_w_ii = fabs(w[ii] - w_ii) + if d_w_ii > d_w_max: + d_w_max = d_w_ii + + if w[ii] > w_max: + w_max = w[ii] + if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: + # the biggest coordinate update of this iteration was smaller than + # the tolerance: check the duality gap as ultimate stopping + # criterion + + # sparse X.T / dense R dot product + if center: + R_sum = 0.0 + for jj in range(n_samples): + R_sum += R[jj] + + for ii in range(n_features): + X_T_R[ii] = 0.0 + for jj in range(X_indptr[ii], X_indptr[ii + 1]): + X_T_R[ii] += X_data[jj] * R[X_indices[jj]] + + if center: + X_T_R[ii] -= X_mean[ii] * R_sum + XtA[ii] = X_T_R[ii] - beta * w[ii] + + if positive: + dual_norm_XtA = max(n_features, &XtA[0]) + else: + dual_norm_XtA = abs_max(n_features, &XtA[0]) + + # R_norm2 = np.dot(R, R) + R_norm2 = ddot(n_samples, &R[0], 1, &R[0], 1) + + # w_norm2 = np.dot(w, w) + w_norm2 = ddot(n_features, &w[0], 1, &w[0], 1) + if (dual_norm_XtA > alpha): + const = alpha / dual_norm_XtA + A_norm2 = R_norm2 * const**2 + gap = 0.5 * (R_norm2 + A_norm2) + else: + const = 1.0 + gap = R_norm2 + + l1_norm = dasum(n_features, &w[0], 1) + + # The expression inside ddot is equivalent to np.dot(R.T, y) + gap += (alpha * l1_norm - const * ddot( + n_samples, + &R[0], 1, + &y[0], n_tasks + ) + + 0.5 * beta * (1 + const ** 2) * w_norm2) + + if gap < tol: + # return if we reached desired tolerance + break + + return w, gap, tol, n_iter + 1 @cython.boundscheck(False) @cython.wraparound(False) @cython.cdivision(True) -def enet_coordinate_descent_gram(np.ndarray[DOUBLE, ndim=1] w, - double alpha, double beta, - np.ndarray[DOUBLE, ndim=2] Q, - np.ndarray[DOUBLE, ndim=1] q, - np.ndarray[DOUBLE, ndim=1] y, - int max_iter, double tol, bool positive=False): +def enet_coordinate_descent_gram(double[:] w, double alpha, double beta, + double[:, :] Q, double[:] q, double[:] y, + int max_iter, double tol, object rng, + bint random=0, bint positive=0): """Cython version of the coordinate descent algorithm for Elastic-Net regression @@ -401,10 +507,12 @@ def enet_coordinate_descent_gram(np.ndarray[DOUBLE, ndim=1] w, # get the data information into easy vars cdef unsigned int n_samples = y.shape[0] cdef unsigned int n_features = Q.shape[0] + cdef unsigned int n_tasks = y.strides[0] / sizeof(DOUBLE) # initial value "Q w" which will be kept of up to date in the iterations - cdef np.ndarray[DOUBLE, ndim=1] H = np.dot(Q, w) + cdef double[:] H = np.dot(Q, w) + cdef double[:] XtA = np.zeros(n_features) cdef double tmp cdef double w_ii cdef double d_w_max @@ -412,120 +520,118 @@ def enet_coordinate_descent_gram(np.ndarray[DOUBLE, ndim=1] w, cdef double d_w_ii cdef double gap = tol + 1.0 cdef double d_w_tol = tol + cdef double dual_norm_XtA cdef unsigned int ii cdef unsigned int n_iter - - cdef double y_norm2 = linalg.norm(y) ** 2 + cdef unsigned int f_iter + cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + cdef UINT32_t* rand_r_state = &rand_r_state_seed + + cdef double y_norm2 = np.dot(y, y) + cdef double* Q_ptr = &Q[0, 0] + cdef double* H_ptr = &H[0] + cdef double* XtA_ptr = &XtA[0] tol = tol * y_norm2 if alpha == 0: warnings.warn("Coordinate descent with alpha=0 may lead to unexpected" " results and is discouraged.") - for n_iter in range(max_iter): - w_max = 0.0 - d_w_max = 0.0 - for ii in xrange(n_features): # Loop over coordinates - if Q[ii, ii] == 0.0: - continue - - w_ii = w[ii] # Store previous value - - if w_ii != 0.0: - # H -= w_ii * Q[ii] - daxpy(n_features, -w_ii, - (Q.data + ii * n_features * sizeof(DOUBLE)), 1, - H.data, 1) - - tmp = q[ii] - H[ii] - - if positive and tmp < 0: - w[ii] = 0.0 - else: - w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ - / (Q[ii, ii] + beta) - - if w[ii] != 0.0: - # H += w[ii] * Q[ii] # Update H = X.T X w - daxpy(n_features, w[ii], - (Q.data + ii * n_features * sizeof(DOUBLE)), 1, - H.data, 1) - - # update the maximum absolute coefficient update - d_w_ii = fabs(w[ii] - w_ii) - if d_w_ii > d_w_max: - d_w_max = d_w_ii - - if fabs(w[ii]) > w_max: - w_max = fabs(w[ii]) - - if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: - # the biggest coordinate update of this iteration was smaller than - # the tolerance: check the duality gap as ultimate stopping - # criterion - - q_dot_w = np.dot(w, q) - - XtA = q - H - beta * w - if positive: - dual_norm_XtA = np.max(XtA) - else: - dual_norm_XtA = linalg.norm(XtA, np.inf) - - R_norm2 = y_norm2 + np.sum(w * H) - 2.0 * q_dot_w - w_norm = linalg.norm(w, 2) - if (dual_norm_XtA > alpha): - const = alpha / dual_norm_XtA - A_norm2 = R_norm2 * (const ** 2) - gap = 0.5 * (R_norm2 + A_norm2) - else: - const = 1.0 - gap = R_norm2 - - gap += alpha * linalg.norm(w, 1) \ - - const * y_norm2 \ - + const * q_dot_w + \ - 0.5 * beta * (1 + const ** 2) * (w_norm ** 2) - - if gap < tol: - # return if we reached desired tolerance - break - - return w, gap, tol - - -cdef double abs_max(int n, double* a): - """np.max(np.abs(a))""" - cdef int i - cdef double m = fabs(a[0]) - cdef double d - for i in xrange(1, n): - d = fabs(a[i]) - if d > m: - m = d - return m - - -cdef double diff_abs_max(int n, double* a, double* b): - """np.max(np.abs(a - b))""" - cdef int i - cdef double m = fabs(a[0] - b[0]) - cdef double d - for i in xrange(1, n): - d = fabs(a[i] - b[i]) - if d > m: - m = d - return m + with nogil: + for n_iter in range(max_iter): + w_max = 0.0 + d_w_max = 0.0 + for f_iter in range(n_features): # Loop over coordinates + if random: + ii = rand_int(n_features, rand_r_state) + else: + ii = f_iter + + if Q[ii, ii] == 0.0: + continue + + w_ii = w[ii] # Store previous value + + if w_ii != 0.0: + # H -= w_ii * Q[ii] + daxpy(n_features, -w_ii, Q_ptr + ii * n_features, 1, + H_ptr, 1) + + tmp = q[ii] - H[ii] + + if positive and tmp < 0: + w[ii] = 0.0 + else: + w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ + / (Q[ii, ii] + beta) + + if w[ii] != 0.0: + # H += w[ii] * Q[ii] # Update H = X.T X w + daxpy(n_features, w[ii], Q_ptr + ii * n_features, 1, + H_ptr, 1) + + # update the maximum absolute coefficient update + d_w_ii = fabs(w[ii] - w_ii) + if d_w_ii > d_w_max: + d_w_max = d_w_ii + + if fabs(w[ii]) > w_max: + w_max = fabs(w[ii]) + + if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: + # the biggest coordinate update of this iteration was smaller than + # the tolerance: check the duality gap as ultimate stopping + # criterion + + # q_dot_w = np.dot(w, q) + # Note that increment in q is not 1 because the strides + # vary if q is sliced from a 2-D array. + q_dot_w = ddot(n_features, &w[0], 1, &q[0], n_tasks) + + for ii in range(n_features): + XtA[ii] = q[ii] - H[ii] - beta * w[ii] + if positive: + dual_norm_XtA = max(n_features, XtA_ptr) + else: + dual_norm_XtA = abs_max(n_features, XtA_ptr) + + # temp = np.sum(w * H) + tmp = 0.0 + for ii in range(n_features): + tmp += w[ii] * H[ii] + R_norm2 = y_norm2 + tmp - 2.0 * q_dot_w + + # w_norm2 = np.dot(w, w) + w_norm2 = ddot(n_features, &w[0], 1, &w[0], 1) + + if (dual_norm_XtA > alpha): + const = alpha / dual_norm_XtA + A_norm2 = R_norm2 * (const ** 2) + gap = 0.5 * (R_norm2 + A_norm2) + else: + const = 1.0 + gap = R_norm2 + + # The call to dasum is equivalent to the L1 norm of w + gap += (alpha * dasum(n_features, &w[0], 1) - + const * y_norm2 + const * q_dot_w + + 0.5 * beta * (1 + const ** 2) * w_norm2) + + if gap < tol: + # return if we reached desired tolerance + break + + return np.asarray(w), gap, tol, n_iter + 1 @cython.boundscheck(False) @cython.wraparound(False) @cython.cdivision(True) -def enet_coordinate_descent_multi_task(np.ndarray[DOUBLE, ndim=2, mode='fortran'] W, - double l1_reg, double l2_reg, - np.ndarray[DOUBLE, ndim=2, mode='fortran'] X, - np.ndarray[DOUBLE, ndim=2] Y, - int max_iter, double tol): +def enet_coordinate_descent_multi_task(double[::1, :] W, double l1_reg, + double l2_reg, double[::1, :] X, + double[:, :] Y, int max_iter, + double tol, object rng, + bint random=0): """Cython version of the coordinate descent algorithm for Elastic-Net mult-task regression @@ -541,14 +647,17 @@ def enet_coordinate_descent_multi_task(np.ndarray[DOUBLE, ndim=2, mode='fortran' cdef unsigned int n_features = X.shape[1] cdef unsigned int n_tasks = Y.shape[1] - # compute norms of the columns of X - cdef np.ndarray[DOUBLE, ndim=1] norm_cols_X = (X ** 2).sum(axis=0) + # to store XtA + cdef double[:, ::1] XtA = np.zeros((n_features, n_tasks)) + cdef double XtA_axis1norm + cdef double dual_norm_XtA # initial value of the residuals - cdef np.ndarray[DOUBLE, ndim=2, mode='c'] R + cdef double[:, ::1] R = np.zeros((n_samples, n_tasks)) - cdef np.ndarray[DOUBLE, ndim=1, mode='c'] tmp = np.zeros(n_tasks, dtype=np.float) - cdef np.ndarray[DOUBLE, ndim=1] w_ii = np.zeros(n_tasks, dtype=np.float) + cdef double[:] norm_cols_X = np.zeros(n_features) + cdef double[::1] tmp = np.zeros(n_tasks, dtype=np.float) + cdef double[:] w_ii = np.zeros(n_tasks, dtype=np.float) cdef double d_w_max cdef double w_max cdef double d_w_ii @@ -556,99 +665,143 @@ def enet_coordinate_descent_multi_task(np.ndarray[DOUBLE, ndim=2, mode='fortran' cdef double W_ii_abs_max cdef double gap = tol + 1.0 cdef double d_w_tol = tol + cdef double ry_sum + cdef double l21_norm cdef unsigned int ii + cdef unsigned int jj cdef unsigned int n_iter + cdef unsigned int f_iter + cdef UINT32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + cdef UINT32_t* rand_r_state = &rand_r_state_seed + + cdef double* X_ptr = &X[0, 0] + cdef double* W_ptr = &W[0, 0] + cdef double* Y_ptr = &Y[0, 0] + cdef double* wii_ptr = &w_ii[0] if l1_reg == 0: warnings.warn("Coordinate descent with l1_reg=0 may lead to unexpected" " results and is discouraged.") - R = Y - np.dot(X, W.T) - R = np.asarray(R, order='C') - - # tol = tol * linalg.norm(Y, ord='fro') ** 2 - tol = tol * dnrm2(n_samples * n_tasks, Y.data, 1) ** 2 - - for n_iter in range(max_iter): - w_max = 0.0 - d_w_max = 0.0 - for ii in xrange(n_features): # Loop over coordinates - if norm_cols_X[ii] == 0.0: - continue - - # w_ii = W[:, ii] # Store previous value - dcopy(n_tasks, (W.data + ii * n_tasks * sizeof(DOUBLE)), - 1, w_ii.data, 1) - - # if np.sum(w_ii ** 2) != 0.0: # can do better - if dnrm2(n_tasks, w_ii.data, 1) != 0.0: - # R += np.dot(X[:, ii][:, None], w_ii[None, :]) # rank 1 update - dger(CblasRowMajor, n_samples, n_tasks, 1.0, - (X.data + ii * n_samples * sizeof(DOUBLE)), 1, - w_ii.data, 1, - R.data, n_tasks) - - # tmp = np.dot(X[:, ii][None, :], R).ravel() - dgemv(CblasRowMajor, CblasTrans, - n_samples, n_tasks, 1.0, R.data, - n_tasks, (X.data + ii * n_samples * sizeof(DOUBLE)), - 1, 0.0, tmp.data, 1) - - # nn = sqrt(np.sum(tmp ** 2)) - nn = dnrm2(n_tasks, tmp.data, 1) - - # W[:, ii] = tmp * fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg) - dcopy(n_tasks, tmp.data, - 1, (W.data + ii * n_tasks * sizeof(DOUBLE)), 1) - dscal(n_tasks, fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg), - (W.data + ii * n_tasks * sizeof(DOUBLE)), 1) - - # if np.sum(W[:, ii] ** 2) != 0.0: # can do better - if dnrm2(n_tasks, (W.data + ii * n_tasks * sizeof(DOUBLE)), 1) != 0.0: - # R -= np.dot(X[:, ii][:, None], W[:, ii][None, :]) # Update residual : rank 1 update - dger(CblasRowMajor, n_samples, n_tasks, -1.0, - (X.data + ii * n_samples * sizeof(DOUBLE)), 1, - (W.data + ii * n_tasks * sizeof(DOUBLE)), 1, - R.data, n_tasks) - - # update the maximum absolute coefficient update - d_w_ii = diff_abs_max(n_tasks, - (W.data + ii * n_tasks * sizeof(DOUBLE)), - w_ii.data) - if d_w_ii > d_w_max: - d_w_max = d_w_ii - - W_ii_abs_max = abs_max(n_tasks, - (W.data + ii * n_tasks * sizeof(DOUBLE))) - if W_ii_abs_max > w_max: - w_max = W_ii_abs_max - - if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: - # the biggest coordinate update of this iteration was smaller than - # the tolerance: check the duality gap as ultimate stopping - # criterion - - XtA = np.dot(X.T, R) - l2_reg * W.T - dual_norm_XtA = np.max(np.sqrt(np.sum(XtA ** 2, axis=1))) - - # TODO: use squared L2 norm directly - # R_norm = linalg.norm(R, ord='fro') - # w_norm = linalg.norm(W, ord='fro') - R_norm = dnrm2(n_samples * n_tasks, R.data, 1) - w_norm = dnrm2(n_features * n_tasks, W.data, 1) - if (dual_norm_XtA > l1_reg): - const = l1_reg / dual_norm_XtA - A_norm = R_norm * const - gap = 0.5 * (R_norm ** 2 + A_norm ** 2) - else: - const = 1.0 - gap = R_norm ** 2 - - gap += l1_reg * np.sqrt(np.sum(W ** 2, axis=0)).sum() - const * np.sum(R * Y) + \ - 0.5 * l2_reg * (1 + const ** 2) * (w_norm ** 2) - - if gap < tol: - # return if we reached desired tolerance - break - - return W, gap, tol + with nogil: + # norm_cols_X = (np.asarray(X) ** 2).sum(axis=0) + for ii in range(n_features): + for jj in range(n_samples): + norm_cols_X[ii] += X[jj, ii] ** 2 + + # R = Y - np.dot(X, W.T) + for ii in range(n_samples): + for jj in range(n_tasks): + R[ii, jj] = Y[ii, jj] - ( + ddot(n_features, X_ptr + ii, n_samples, W_ptr + jj, n_tasks) + ) + + # tol = tol * linalg.norm(Y, ord='fro') ** 2 + tol = tol * dnrm2(n_samples * n_tasks, Y_ptr, 1) ** 2 + + for n_iter in range(max_iter): + w_max = 0.0 + d_w_max = 0.0 + for f_iter in range(n_features): # Loop over coordinates + if random: + ii = rand_int(n_features, rand_r_state) + else: + ii = f_iter + + if norm_cols_X[ii] == 0.0: + continue + + # w_ii = W[:, ii] # Store previous value + dcopy(n_tasks, W_ptr + ii * n_tasks, 1, wii_ptr, 1) + + # if np.sum(w_ii ** 2) != 0.0: # can do better + if dnrm2(n_tasks, wii_ptr, 1) != 0.0: + # R += np.dot(X[:, ii][:, None], w_ii[None, :]) # rank 1 update + dger(CblasRowMajor, n_samples, n_tasks, 1.0, + X_ptr + ii * n_samples, 1, + wii_ptr, 1, &R[0, 0], n_tasks) + + # tmp = np.dot(X[:, ii][None, :], R).ravel() + dgemv(CblasRowMajor, CblasTrans, + n_samples, n_tasks, 1.0, &R[0, 0], n_tasks, + X_ptr + ii * n_samples, 1, 0.0, &tmp[0], 1) + + # nn = sqrt(np.sum(tmp ** 2)) + nn = dnrm2(n_tasks, &tmp[0], 1) + + # W[:, ii] = tmp * fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg) + dcopy(n_tasks, &tmp[0], 1, W_ptr + ii * n_tasks, 1) + dscal(n_tasks, fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg), + W_ptr + ii * n_tasks, 1) + + # if np.sum(W[:, ii] ** 2) != 0.0: # can do better + if dnrm2(n_tasks, W_ptr + ii * n_tasks, 1) != 0.0: + # R -= np.dot(X[:, ii][:, None], W[:, ii][None, :]) # Update residual : rank 1 update + dger(CblasRowMajor, n_samples, n_tasks, -1.0, + X_ptr + ii * n_samples, 1, W_ptr + ii * n_tasks, 1, + &R[0, 0], n_tasks) + + # update the maximum absolute coefficient update + d_w_ii = diff_abs_max(n_tasks, W_ptr + ii * n_tasks, wii_ptr) + + if d_w_ii > d_w_max: + d_w_max = d_w_ii + + W_ii_abs_max = abs_max(n_tasks, W_ptr + ii * n_tasks) + if W_ii_abs_max > w_max: + w_max = W_ii_abs_max + + if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1: + # the biggest coordinate update of this iteration was smaller than + # the tolerance: check the duality gap as ultimate stopping + # criterion + + # XtA = np.dot(X.T, R) - l2_reg * W.T + for ii in range(n_features): + for jj in range(n_tasks): + XtA[ii, jj] = ddot( + n_samples, X_ptr + ii * n_samples, 1, + &R[0, 0] + jj, n_tasks + ) - l2_reg * W[jj, ii] + + # dual_norm_XtA = np.max(np.sqrt(np.sum(XtA ** 2, axis=1))) + dual_norm_XtA = 0.0 + for ii in range(n_features): + # np.sqrt(np.sum(XtA ** 2, axis=1)) + XtA_axis1norm = dnrm2(n_tasks, &XtA[0, 0] + ii * n_tasks, 1) + if XtA_axis1norm > dual_norm_XtA: + dual_norm_XtA = XtA_axis1norm + + # TODO: use squared L2 norm directly + # R_norm = linalg.norm(R, ord='fro') + # w_norm = linalg.norm(W, ord='fro') + R_norm = dnrm2(n_samples * n_tasks, &R[0, 0], 1) + w_norm = dnrm2(n_features * n_tasks, W_ptr, 1) + if (dual_norm_XtA > l1_reg): + const = l1_reg / dual_norm_XtA + A_norm = R_norm * const + gap = 0.5 * (R_norm ** 2 + A_norm ** 2) + else: + const = 1.0 + gap = R_norm ** 2 + + # ry_sum = np.sum(R * y) + ry_sum = 0.0 + for ii in range(n_samples): + for jj in range(n_tasks): + ry_sum += R[ii, jj] * Y[ii, jj] + + # l21_norm = np.sqrt(np.sum(W ** 2, axis=0)).sum() + l21_norm = 0.0 + for ii in range(n_features): + # np.sqrt(np.sum(W ** 2, axis=0)) + l21_norm += dnrm2(n_tasks, W_ptr + n_tasks * ii, 1) + + gap += l1_reg * l21_norm - const * ry_sum + \ + 0.5 * l2_reg * (1 + const ** 2) * (w_norm ** 2) + + if gap < tol: + # return if we reached desired tolerance + break + + return np.asarray(W), gap, tol, n_iter + 1 diff --git a/sklearn/linear_model/coordinate_descent.py b/sklearn/linear_model/coordinate_descent.py index 4d555dbd638eb..8b370929acc06 100644 --- a/sklearn/linear_model/coordinate_descent.py +++ b/sklearn/linear_model/coordinate_descent.py @@ -3,39 +3,471 @@ # Olivier Grisel # Gael Varoquaux # -# License: BSD Style. +# License: BSD 3 clause import sys import warnings -import itertools -import operator from abc import ABCMeta, abstractmethod import numpy as np from scipy import sparse -from .base import LinearModel +from .base import LinearModel, _pre_fit from ..base import RegressorMixin -from .base import sparse_center_data, center_data -from ..utils import array2d, atleast2d_or_csc -from ..cross_validation import check_cv +from .base import center_data, sparse_center_data +from ..utils import check_array, check_X_y +from ..utils.validation import check_random_state +from ..cross_validation import _check_cv as check_cv from ..externals.joblib import Parallel, delayed +from ..externals import six +from ..externals.six.moves import xrange from ..utils.extmath import safe_sparse_dot +from ..utils.validation import check_is_fitted +from ..utils import ConvergenceWarning from . import cd_fast +############################################################################### +# Paths functions + +def _alpha_grid(X, y, Xy=None, l1_ratio=1.0, fit_intercept=True, + eps=1e-3, n_alphas=100, normalize=False, copy_X=True): + """ Compute the grid of alpha values for elastic net parameter search + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. Pass directly as Fortran-contiguous data to avoid + unnecessary memory duplication + + y : ndarray, shape = (n_samples,) + Target values + + Xy : array-like, optional + Xy = np.dot(X.T, y) that can be precomputed. + + l1_ratio : float + The elastic net mixing parameter, with ``0 <= l1_ratio <= 1``. + For ``l1_ratio = 0`` the penalty is an L2 penalty. ``For + l1_ratio = 1`` it is an L1 penalty. For ``0 < l1_ratio < + 1``, the penalty is a combination of L1 and L2. + + eps : float, optional + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3`` + + n_alphas : int, optional + Number of alphas along the regularization path + + fit_intercept : boolean, default True + Whether to fit an intercept or not + + normalize : boolean, optional, default False + If ``True``, the regressors X will be normalized before regression. + + copy_X : boolean, optional, default True + If ``True``, X will be copied; else, it may be overwritten. + """ + n_samples = len(y) + + sparse_center = False + if Xy is None: + X_sparse = sparse.isspmatrix(X) + sparse_center = X_sparse and (fit_intercept or normalize) + X = check_array(X, 'csc', + copy=(copy_X and fit_intercept and not X_sparse)) + if not X_sparse: + # X can be touched inplace thanks to the above line + X, y, _, _, _ = center_data(X, y, fit_intercept, + normalize, copy=False) + Xy = safe_sparse_dot(X.T, y, dense_output=True) + + if sparse_center: + # Workaround to find alpha_max for sparse matrices. + # since we should not destroy the sparsity of such matrices. + _, _, X_mean, _, X_std = sparse_center_data(X, y, fit_intercept, + normalize) + mean_dot = X_mean * np.sum(y) + + if Xy.ndim == 1: + Xy = Xy[:, np.newaxis] + + if sparse_center: + if fit_intercept: + Xy -= mean_dot[:, np.newaxis] + if normalize: + Xy /= X_std[:, np.newaxis] + + alpha_max = (np.sqrt(np.sum(Xy ** 2, axis=1)).max() / + (n_samples * l1_ratio)) + + if alpha_max <= np.finfo(float).resolution: + alphas = np.empty(n_alphas) + alphas.fill(np.finfo(float).resolution) + return alphas + + return np.logspace(np.log10(alpha_max * eps), np.log10(alpha_max), + num=n_alphas)[::-1] + + +def lasso_path(X, y, eps=1e-3, n_alphas=100, alphas=None, + precompute='auto', Xy=None, copy_X=True, coef_init=None, + verbose=False, return_n_iter=False, positive=False, **params): + """Compute Lasso path with coordinate descent + + The Lasso optimization function varies for mono and multi-outputs. + + For mono-output tasks it is:: + + (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 + + For multi-output tasks it is:: + + (1 / (2 * n_samples)) * ||Y - XW||^2_Fro + alpha * ||W||_21 + + Where:: + + ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2} + + i.e. the sum of norm of each row. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. Pass directly as Fortran-contiguous data to avoid + unnecessary memory duplication. If ``y`` is mono-output then ``X`` + can be sparse. + + y : ndarray, shape = (n_samples,), or (n_samples, n_outputs) + Target values + + eps : float, optional + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3`` + + n_alphas : int, optional + Number of alphas along the regularization path + + alphas : ndarray, optional + List of alphas where to compute the models. + If ``None`` alphas are set automatically + + precompute : True | False | 'auto' | array-like + Whether to use a precomputed Gram matrix to speed up + calculations. If set to ``'auto'`` let us decide. The Gram + matrix can also be passed as argument. + + Xy : array-like, optional + Xy = np.dot(X.T, y) that can be precomputed. It is useful + only when the Gram matrix is precomputed. + + copy_X : boolean, optional, default True + If ``True``, X will be copied; else, it may be overwritten. + + coef_init : array, shape (n_features, ) | None + The initial values of the coefficients. + + verbose : bool or integer + Amount of verbosity. + + params : kwargs + keyword arguments passed to the coordinate descent solver. + + positive : bool, default False + If set to True, forces coefficients to be positive. + + return_n_iter : bool + whether to return the number of iterations or not. + + Returns + ------- + alphas : array, shape (n_alphas,) + The alphas along the path where models are computed. + + coefs : array, shape (n_features, n_alphas) or + (n_outputs, n_features, n_alphas) + Coefficients along the path. + + dual_gaps : array, shape (n_alphas,) + The dual gaps at the end of the optimization for each alpha. + + n_iters : array-like, shape (n_alphas,) + The number of iterations taken by the coordinate descent optimizer to + reach the specified tolerance for each alpha. + + Notes + ----- + See examples/linear_model/plot_lasso_coordinate_descent_path.py + for an example. + + To avoid unnecessary memory duplication the X argument of the fit method + should be directly passed as a Fortran-contiguous numpy array. + + Note that in certain cases, the Lars solver may be significantly + faster to implement this functionality. In particular, linear + interpolation can be used to retrieve model coefficients between the + values output by lars_path + + Examples + --------- + + Comparing lasso_path and lars_path with interpolation: + + >>> X = np.array([[1, 2, 3.1], [2.3, 5.4, 4.3]]).T + >>> y = np.array([1, 2, 3.1]) + >>> # Use lasso_path to compute a coefficient path + >>> _, coef_path, _ = lasso_path(X, y, alphas=[5., 1., .5]) + >>> print(coef_path) + [[ 0. 0. 0.46874778] + [ 0.2159048 0.4425765 0.23689075]] + + >>> # Now use lars_path and 1D linear interpolation to compute the + >>> # same path + >>> from sklearn.linear_model import lars_path + >>> alphas, active, coef_path_lars = lars_path(X, y, method='lasso') + >>> from scipy import interpolate + >>> coef_path_continuous = interpolate.interp1d(alphas[::-1], + ... coef_path_lars[:, ::-1]) + >>> print(coef_path_continuous([5., 1., .5])) + [[ 0. 0. 0.46915237] + [ 0.2159048 0.4425765 0.23668876]] + + + See also + -------- + lars_path + Lasso + LassoLars + LassoCV + LassoLarsCV + sklearn.decomposition.sparse_encode + """ + return enet_path(X, y, l1_ratio=1., eps=eps, n_alphas=n_alphas, + alphas=alphas, precompute=precompute, Xy=Xy, + copy_X=copy_X, coef_init=coef_init, verbose=verbose, + positive=positive, **params) + + +def enet_path(X, y, l1_ratio=0.5, eps=1e-3, n_alphas=100, alphas=None, + precompute='auto', Xy=None, copy_X=True, coef_init=None, + verbose=False, return_n_iter=False, positive=False, **params): + """Compute elastic net path with coordinate descent + + The elastic net optimization function varies for mono and multi-outputs. + + For mono-output tasks it is:: + + 1 / (2 * n_samples) * ||y - Xw||^2_2 + + + alpha * l1_ratio * ||w||_1 + + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2 + + For multi-output tasks it is:: + + (1 / (2 * n_samples)) * ||Y - XW||^Fro_2 + + alpha * l1_ratio * ||W||_21 + + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2 + + Where:: + + ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2} + + i.e. the sum of norm of each row. + + Parameters + ---------- + X : {array-like}, shape (n_samples, n_features) + Training data. Pass directly as Fortran-contiguous data to avoid + unnecessary memory duplication. If ``y`` is mono-output then ``X`` + can be sparse. + + y : ndarray, shape = (n_samples,) or (n_samples, n_outputs) + Target values + + l1_ratio : float, optional + float between 0 and 1 passed to elastic net (scaling between + l1 and l2 penalties). ``l1_ratio=1`` corresponds to the Lasso + + eps : float + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3`` + + n_alphas : int, optional + Number of alphas along the regularization path + + alphas : ndarray, optional + List of alphas where to compute the models. + If None alphas are set automatically + + precompute : True | False | 'auto' | array-like + Whether to use a precomputed Gram matrix to speed up + calculations. If set to ``'auto'`` let us decide. The Gram + matrix can also be passed as argument. + + Xy : array-like, optional + Xy = np.dot(X.T, y) that can be precomputed. It is useful + only when the Gram matrix is precomputed. + + copy_X : boolean, optional, default True + If ``True``, X will be copied; else, it may be overwritten. + + coef_init : array, shape (n_features, ) | None + The initial values of the coefficients. + + verbose : bool or integer + Amount of verbosity. + + params : kwargs + keyword arguments passed to the coordinate descent solver. + + return_n_iter : bool + whether to return the number of iterations or not. + + positive : bool, default False + If set to True, forces coefficients to be positive. + + Returns + ------- + alphas : array, shape (n_alphas,) + The alphas along the path where models are computed. + + coefs : array, shape (n_features, n_alphas) or + (n_outputs, n_features, n_alphas) + Coefficients along the path. + + dual_gaps : array, shape (n_alphas,) + The dual gaps at the end of the optimization for each alpha. + + n_iters : array-like, shape (n_alphas,) + The number of iterations taken by the coordinate descent optimizer to + reach the specified tolerance for each alpha. + (Is returned when ``return_n_iter`` is set to True). + + Notes + ----- + See examples/plot_lasso_coordinate_descent_path.py for an example. + + See also + -------- + MultiTaskElasticNet + MultiTaskElasticNetCV + ElasticNet + ElasticNetCV + """ + X = check_array(X, 'csc', dtype=np.float64, order='F', copy=copy_X) + if Xy is not None: + Xy = check_array(Xy, 'csc', dtype=np.float64, order='F', copy=False, + ensure_2d=False) + n_samples, n_features = X.shape + + multi_output = False + if y.ndim != 1: + multi_output = True + _, n_outputs = y.shape + + # MultiTaskElasticNet does not support sparse matrices + if not multi_output and sparse.isspmatrix(X): + if 'X_mean' in params: + # As sparse matrices are not actually centered we need this + # to be passed to the CD solver. + X_sparse_scaling = params['X_mean'] / params['X_std'] + else: + X_sparse_scaling = np.zeros(n_features) + + # X should be normalized and fit already. + X, y, X_mean, y_mean, X_std, precompute, Xy = \ + _pre_fit(X, y, Xy, precompute, normalize=False, fit_intercept=False, + copy=False) + if alphas is None: + # No need to normalize of fit_intercept: it has been done + # above + alphas = _alpha_grid(X, y, Xy=Xy, l1_ratio=l1_ratio, + fit_intercept=False, eps=eps, n_alphas=n_alphas, + normalize=False, copy_X=False) + else: + alphas = np.sort(alphas)[::-1] # make sure alphas are properly ordered + + n_alphas = len(alphas) + tol = params.get('tol', 1e-4) + max_iter = params.get('max_iter', 1000) + dual_gaps = np.empty(n_alphas) + n_iters = [] + + rng = check_random_state(params.get('random_state', None)) + selection = params.get('selection', 'cyclic') + if selection not in ['random', 'cyclic']: + raise ValueError("selection should be either random or cyclic.") + random = (selection == 'random') + + if not multi_output: + coefs = np.empty((n_features, n_alphas), dtype=np.float64) + else: + coefs = np.empty((n_outputs, n_features, n_alphas), + dtype=np.float64) + + if coef_init is None: + coef_ = np.asfortranarray(np.zeros(coefs.shape[:-1])) + else: + coef_ = np.asfortranarray(coef_init) + + for i, alpha in enumerate(alphas): + l1_reg = alpha * l1_ratio * n_samples + l2_reg = alpha * (1.0 - l1_ratio) * n_samples + if not multi_output and sparse.isspmatrix(X): + model = cd_fast.sparse_enet_coordinate_descent( + coef_, l1_reg, l2_reg, X.data, X.indices, + X.indptr, y, X_sparse_scaling, + max_iter, tol, rng, random, positive) + elif multi_output: + model = cd_fast.enet_coordinate_descent_multi_task( + coef_, l1_reg, l2_reg, X, y, max_iter, tol, rng, random) + elif isinstance(precompute, np.ndarray): + precompute = check_array(precompute, 'csc', dtype=np.float64, order='F') + model = cd_fast.enet_coordinate_descent_gram( + coef_, l1_reg, l2_reg, precompute, Xy, y, max_iter, + tol, rng, random, positive) + elif precompute is False: + model = cd_fast.enet_coordinate_descent( + coef_, l1_reg, l2_reg, X, y, max_iter, tol, rng, random, + positive) + else: + raise ValueError("Precompute should be one of True, False, " + "'auto' or array-like") + coef_, dual_gap_, eps_, n_iter_ = model + coefs[..., i] = coef_ + dual_gaps[i] = dual_gap_ + n_iters.append(n_iter_) + if dual_gap_ > eps_: + warnings.warn('Objective did not converge.' + + ' You might want' + + ' to increase the number of iterations', + ConvergenceWarning) + + if verbose: + if verbose > 2: + print(model) + elif verbose > 1: + print('Path: %03i out of %03i' % (i, n_alphas)) + else: + sys.stderr.write('.') + + if return_n_iter: + return alphas, coefs, dual_gaps, n_iters + return alphas, coefs, dual_gaps + + ############################################################################### # ElasticNet model class ElasticNet(LinearModel, RegressorMixin): - """Linear Model trained with L1 and L2 prior as regularizer + """Linear regression with combined L1 and L2 priors as regularizer. Minimizes the objective function:: 1 / (2 * n_samples) * ||y - Xw||^2_2 + - + alpha * rho * ||w||_1 + 0.5 * alpha * (1 - rho) * ||w||^2_2 + + alpha * l1_ratio * ||w||_1 + + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2 If you are interested in controlling the L1 and L2 penalty separately, keep in mind that this is equivalent to:: @@ -44,78 +476,110 @@ class ElasticNet(LinearModel, RegressorMixin): where:: - alpha = a + b and rho = a / (a + b) + alpha = a + b and l1_ratio = a / (a + b) - The parameter rho corresponds to alpha in the glmnet R package while - alpha corresponds to the lambda parameter in glmnet. Specifically, rho = - 1 is the lasso penalty. Currently, rho <= 0.01 is not reliable, unless - you supply your own sequence of alpha. + The parameter l1_ratio corresponds to alpha in the glmnet R package while + alpha corresponds to the lambda parameter in glmnet. Specifically, l1_ratio + = 1 is the lasso penalty. Currently, l1_ratio <= 0.01 is not reliable, + unless you supply your own sequence of alpha. Parameters ---------- alpha : float Constant that multiplies the penalty terms. Defaults to 1.0 See the notes for the exact mathematical meaning of this - parameter + parameter. + ``alpha = 0`` is equivalent to an ordinary least square, solved + by the :class:`LinearRegression` object. For numerical + reasons, using ``alpha = 0`` with the Lasso object is not advised + and you should prefer the LinearRegression object. + + l1_ratio : float + The ElasticNet mixing parameter, with ``0 <= l1_ratio <= 1``. For + ``l1_ratio = 0`` the penalty is an L2 penalty. ``For l1_ratio = 1`` it + is an L1 penalty. For ``0 < l1_ratio < 1``, the penalty is a + combination of L1 and L2. - rho : float - The ElasticNet mixing parameter, with 0 < rho <= 1. For rho = 0 - the penalty is an L2 penalty. For rho = 1 it is an L1 penalty. - For 0 < rho < 1, the penalty is a combination of L1 and L2 - - fit_intercept: bool - Whether the intercept should be estimated or not. If False, the + fit_intercept : bool + Whether the intercept should be estimated or not. If ``False``, the data is assumed to be already centered. - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default False + If ``True``, the regressors X will be normalized before regression. precompute : True | False | 'auto' | array-like Whether to use a precomputed Gram matrix to speed up - calculations. If set to 'auto' let us decide. The Gram + calculations. If set to ``'auto'`` let us decide. The Gram matrix can also be passed as argument. For sparse input - this option is always True to preserve sparsity. + this option is always ``True`` to preserve sparsity. + WARNING : The ``'auto'`` option is deprecated and will + be removed in 0.18. - max_iter: int, optional + max_iter : int, optional The maximum number of iterations - copy_X : boolean, optional, default False - If True, X will be copied; else, it may be overwritten. + copy_X : boolean, optional, default True + If ``True``, X will be copied; else, it may be overwritten. - tol: float, optional + tol : float, optional The tolerance for the optimization: if the updates are - smaller than 'tol', the optimization code checks the + smaller than ``tol``, the optimization code checks the dual gap for optimality and continues until it is smaller - than tol. + than ``tol``. warm_start : bool, optional - When set to True, reuse the solution of the previous call to fit as + When set to ``True``, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. - positive: bool, optional - When set to True, forces the coefficients to be positive. + positive : bool, optional + When set to ``True``, forces the coefficients to be positive. + + selection : str, default 'cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + random_state : int, RandomState instance, or None (default) + The seed of the pseudo random number generator that selects + a random feature to update. Useful only when selection is set to + 'random'. Attributes ---------- - `coef_` : array, shape = (n_features,) + coef_ : array, shape = (n_features,) | (n_targets, n_features) parameter vector (w in the cost function formula) - `sparse_coef_` : scipy.sparse matrix, shape = (n_features, 1) - `sparse_coef_` is a readonly property derived from `coef_` + sparse_coef_ : scipy.sparse matrix, shape = (n_features, 1) | \ + (n_targets, n_features) + ``sparse_coef_`` is a readonly property derived from ``coef_`` - `intercept_` : float | array, shape = (n_targets,) + intercept_ : float | array, shape = (n_targets,) independent term in decision function. + n_iter_ : array-like, shape (n_targets,) + number of iterations run by the coordinate descent solver to reach + the specified tolerance. + Notes ----- To avoid unnecessary memory duplication the X argument of the fit method - should be directly passed as a fortran contiguous numpy array. + should be directly passed as a Fortran-contiguous numpy array. + + See also + -------- + SGDRegressor: implements elastic net regression with incremental training. + SGDClassifier: implements logistic regression with elastic net penalty + (``SGDClassifier(loss="log", penalty="elasticnet")``). """ - def __init__(self, alpha=1.0, rho=0.5, fit_intercept=True, - normalize=False, precompute='auto', max_iter=1000, - copy_X=True, tol=1e-4, warm_start=False, positive=False): + path = staticmethod(enet_path) + + def __init__(self, alpha=1.0, l1_ratio=0.5, fit_intercept=True, + normalize=False, precompute=False, max_iter=1000, + copy_X=True, tol=1e-4, warm_start=False, positive=False, + random_state=None, selection='cyclic'): self.alpha = alpha - self.rho = rho + self.l1_ratio = l1_ratio self.coef_ = None self.fit_intercept = fit_intercept self.normalize = normalize @@ -126,46 +590,48 @@ def __init__(self, alpha=1.0, rho=0.5, fit_intercept=True, self.warm_start = warm_start self.positive = positive self.intercept_ = 0.0 + self.random_state = random_state + self.selection = selection - def fit(self, X, y, Xy=None, coef_init=None): - """Fit model with coordinate descent + def fit(self, X, y): + """Fit model with coordinate descent. Parameters ----------- - X: ndarray or scipy.sparse matrix, (n_samples, n_features) + X : ndarray or scipy.sparse matrix, (n_samples, n_features) Data - y: ndarray, shape = (n_samples,) or (n_samples, n_targets) + + y : ndarray, shape = (n_samples,) or (n_samples, n_targets) Target - Xy : array-like, optional - Xy = np.dot(X.T, y) that can be precomputed. It is useful - only when the Gram matrix is precomputed. - coef_init: ndarray of shape n_features or (n_targets, n_features) - The initial coeffients to warm-start the optimization Notes ----- Coordinate descent is an algorithm that considers each column of data at a time hence it will automatically convert the X input - as a fortran contiguous numpy array if necessary. + as a Fortran-contiguous numpy array if necessary. To avoid memory re-allocation it is advised to allocate the initial data in memory directly using that format. """ - X = atleast2d_or_csc(X, dtype=np.float64, order='F', - copy=self.copy_X and self.fit_intercept) - # From now on X can be touched inplace - y = np.asarray(y, dtype=np.float64) - # now all computation with X can be done inplace - fit = self._sparse_fit if sparse.isspmatrix(X) else self._dense_fit - fit(X, y, Xy, coef_init) - return self + if self.alpha == 0: + warnings.warn("With alpha=0, this algorithm does not converge " + "well. You are advised to use the LinearRegression " + "estimator", stacklevel=2) + + if self.precompute == 'auto': + warnings.warn("Setting precompute to 'auto', was found to be " + "slower even when n_samples > n_features. Hence " + "it will be removed in 0.18.", + DeprecationWarning, stacklevel=2) - def _dense_fit(self, X, y, Xy=None, coef_init=None): + X, y = check_X_y(X, y, accept_sparse='csc', dtype=np.float64, + order='F', copy=self.copy_X and self.fit_intercept, + multi_output=True, y_numeric=True) - X, y, X_mean, y_mean, X_std = center_data(X, y, - self.fit_intercept, self.normalize, - copy=False) # copy was done in fit if necessary + X, y, X_mean, y_mean, X_std, precompute, Xy = \ + _pre_fit(X, y, None, self.precompute, self.normalize, + self.fit_intercept, copy=True) if y.ndim == 1: y = y[:, np.newaxis] @@ -175,121 +641,49 @@ def _dense_fit(self, X, y, Xy=None, coef_init=None): n_samples, n_features = X.shape n_targets = y.shape[1] - precompute = self.precompute - if hasattr(precompute, '__array__') \ - and not np.allclose(X_mean, np.zeros(n_features)) \ - and not np.allclose(X_std, np.ones(n_features)): - # recompute Gram - precompute = 'auto' - Xy = None - - coef_ = self._init_coef(coef_init, n_features, n_targets) - dual_gap_ = np.empty(n_targets) - eps_ = np.empty(n_targets) - - l1_reg = self.alpha * self.rho * n_samples - l2_reg = self.alpha * (1.0 - self.rho) * n_samples - - # precompute if n_samples > n_features - if hasattr(precompute, '__array__'): - Gram = precompute - elif precompute == True or \ - (precompute == 'auto' and n_samples > n_features): - Gram = np.dot(X.T, X) - else: - Gram = None + if self.selection not in ['cyclic', 'random']: + raise ValueError("selection should be either random or cyclic.") - for k in xrange(n_targets): - if Gram is None: - coef_[k, :], dual_gap_[k], eps_[k] = \ - cd_fast.enet_coordinate_descent(coef_[k, :], - l1_reg, l2_reg, X, y[:, k], self.max_iter, self.tol, - self.positive) - else: - Gram = Gram.copy() - if Xy is None: - this_Xy = np.dot(X.T, y[:, k]) - else: - this_Xy = Xy[:, k] - coef_[k, :], dual_gap_[k], eps_[k] = \ - cd_fast.enet_coordinate_descent_gram(coef_[k, :], - l1_reg, l2_reg, Gram, this_Xy, y[:, k], self.max_iter, - self.tol, self.positive) - - if dual_gap_[k] > eps_[k]: - warnings.warn('Objective did not converge for ' + - 'target %d, you might want' % k + - ' to increase the number of iterations') - - self.coef_, self.dual_gap_, self.eps_ = (np.squeeze(a) for a in ( - coef_, dual_gap_, eps_)) - self._set_intercept(X_mean, y_mean, X_std) - - # return self for chaining fit and predict calls - return self - - def _sparse_fit(self, X, y, Xy=None, coef_init=None): - - if X.shape[0] != y.shape[0]: - raise ValueError("X and y have incompatible shapes.\n" + - "Note: Sparse matrices cannot be indexed w/" + - "boolean masks (use `indices=True` in CV).") - - # NOTE: we are explicitly not centering the data the naive way to - # avoid breaking the sparsity of X - X_data, y, X_mean, y_mean, X_std = sparse_center_data(X, y, - self.fit_intercept, - self.normalize) - - if y.ndim == 1: - y = y[:, np.newaxis] - - n_samples, n_features = X.shape[0], X.shape[1] - n_targets = y.shape[1] - - coef_ = self._init_coef(coef_init, n_features, n_targets) - dual_gap_ = np.empty(n_targets) - eps_ = np.empty(n_targets) + if not self.warm_start or self.coef_ is None: + coef_ = np.zeros((n_targets, n_features), dtype=np.float64, + order='F') + else: + coef_ = self.coef_ + if coef_.ndim == 1: + coef_ = coef_[np.newaxis, :] - l1_reg = self.alpha * self.rho * n_samples - l2_reg = self.alpha * (1.0 - self.rho) * n_samples + dual_gaps_ = np.zeros(n_targets, dtype=np.float64) + self.n_iter_ = [] for k in xrange(n_targets): - coef_[k, :], dual_gap_[k], eps_[k] = \ - cd_fast.sparse_enet_coordinate_descent( - coef_[k, :], l1_reg, l2_reg, X_data, X.indices, - X.indptr, y[:, k], X_mean / X_std, - self.max_iter, self.tol, self.positive) - - if dual_gap_[k] > eps_[k]: - warnings.warn('Objective did not converge for ' + - 'target %d, you might want' % k + - ' to increase the number of iterations') - - self.coef_, self.dual_gap_, self.eps_ = (np.squeeze(a) for a in ( - coef_, dual_gap_, eps_)) + if Xy is not None: + this_Xy = Xy[:, k] + else: + this_Xy = None + _, this_coef, this_dual_gap, this_iter = \ + self.path(X, y[:, k], + l1_ratio=self.l1_ratio, eps=None, + n_alphas=None, alphas=[self.alpha], + precompute=precompute, Xy=this_Xy, + fit_intercept=False, normalize=False, copy_X=True, + verbose=False, tol=self.tol, positive=self.positive, + X_mean=X_mean, X_std=X_std, return_n_iter=True, + coef_init=coef_[k], max_iter=self.max_iter, + random_state=self.random_state, + selection=self.selection) + coef_[k] = this_coef[:, 0] + dual_gaps_[k] = this_dual_gap[0] + self.n_iter_.append(this_iter[0]) + + if n_targets == 1: + self.n_iter_ = self.n_iter_[0] + + self.coef_, self.dual_gap_ = map(np.squeeze, [coef_, dual_gaps_]) self._set_intercept(X_mean, y_mean, X_std) # return self for chaining fit and predict calls return self - def _init_coef(self, coef_init, n_features, n_targets): - if coef_init is None: - if not self.warm_start or self.coef_ is None: - coef_ = np.zeros((n_targets, n_features), dtype=np.float64) - else: - coef_ = self.coef_ - else: - coef_ = coef_init - - if coef_.ndim == 1: - coef_ = coef_[np.newaxis, :] - if coef_.shape != (n_targets, n_features): - raise ValueError("X and coef_init have incompatible " + - "shapes (%s != %s)." % (coef_.shape, (n_targets, n_features))) - - return coef_ - @property def sparse_coef_(self): """ sparse representation of the fitted coef """ @@ -307,9 +701,10 @@ def decision_function(self, X): T : array, shape = (n_samples,) The predicted decision function """ + check_is_fitted(self, 'n_iter_') if sparse.isspmatrix(X): - return np.ravel(safe_sparse_dot(self.coef_, X.T, \ - dense_output=True) + self.intercept_) + return np.ravel(safe_sparse_dot(self.coef_, X.T, dense_output=True) + + self.intercept_) else: return super(ElasticNet, self).decision_function(X) @@ -325,66 +720,87 @@ class Lasso(ElasticNet): (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 Technically the Lasso model is optimizing the same objective function as - the Elastic Net with rho=1.0 (no L2 penalty). + the Elastic Net with ``l1_ratio=1.0`` (no L2 penalty). Parameters ---------- alpha : float, optional - Constant that multiplies the L1 term. Defaults to 1.0 + Constant that multiplies the L1 term. Defaults to 1.0. + ``alpha = 0`` is equivalent to an ordinary least square, solved + by the :class:`LinearRegression` object. For numerical + reasons, using ``alpha = 0`` is with the Lasso object is not advised + and you should prefer the LinearRegression object. fit_intercept : boolean whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default False + If ``True``, the regressors X will be normalized before regression. copy_X : boolean, optional, default True - If True, X will be copied; else, it may be overwritten. + If ``True``, X will be copied; else, it may be overwritten. precompute : True | False | 'auto' | array-like Whether to use a precomputed Gram matrix to speed up - calculations. If set to 'auto' let us decide. The Gram + calculations. If set to ``'auto'`` let us decide. The Gram matrix can also be passed as argument. For sparse input - this option is always True to preserve sparsity. + this option is always ``True`` to preserve sparsity. + WARNING : The ``'auto'`` option is deprecated and will + be removed in 0.18. - max_iter: int, optional + max_iter : int, optional The maximum number of iterations tol : float, optional The tolerance for the optimization: if the updates are - smaller than 'tol', the optimization code checks the + smaller than ``tol``, the optimization code checks the dual gap for optimality and continues until it is smaller - than tol. + than ``tol``. warm_start : bool, optional When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. positive : bool, optional - When set to True, forces the coefficients to be positive. + When set to ``True``, forces the coefficients to be positive. + + selection : str, default 'cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + random_state : int, RandomState instance, or None (default) + The seed of the pseudo random number generator that selects + a random feature to update. Useful only when selection is set to + 'random'. Attributes ---------- - `coef_` : array, shape = (n_features,) + coef_ : array, shape = (n_features,) | (n_targets, n_features) parameter vector (w in the cost function formula) - `sparse_coef_` : scipy.sparse matrix, shape = (n_features, 1) - `sparse_coef_` is a readonly property derived from `coef_` + sparse_coef_ : scipy.sparse matrix, shape = (n_features, 1) | \ + (n_targets, n_features) + ``sparse_coef_`` is a readonly property derived from ``coef_`` - `intercept_` : float + intercept_ : float | array, shape = (n_targets,) independent term in decision function. + n_iter_ : int | array-like, shape (n_targets,) + number of iterations run by the coordinate descent solver to reach + the specified tolerance. + Examples -------- >>> from sklearn import linear_model >>> clf = linear_model.Lasso(alpha=0.1) >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2]) Lasso(alpha=0.1, copy_X=True, fit_intercept=True, max_iter=1000, - normalize=False, positive=False, precompute='auto', tol=0.0001, - warm_start=False) + normalize=False, positive=False, precompute=False, random_state=None, + selection='cyclic', tol=0.0001, warm_start=False) >>> print(clf.coef_) [ 0.85 0. ] >>> print(clf.intercept_) @@ -404,256 +820,138 @@ class Lasso(ElasticNet): The algorithm used to fit the model is coordinate descent. To avoid unnecessary memory duplication the X argument of the fit method - should be directly passed as a fortran contiguous numpy array. + should be directly passed as a Fortran-contiguous numpy array. """ + path = staticmethod(enet_path) def __init__(self, alpha=1.0, fit_intercept=True, normalize=False, - precompute='auto', copy_X=True, max_iter=1000, - tol=1e-4, warm_start=False, positive=False): - super(Lasso, self).__init__(alpha=alpha, rho=1.0, - fit_intercept=fit_intercept, normalize=normalize, - precompute=precompute, copy_X=copy_X, - max_iter=max_iter, tol=tol, warm_start=warm_start, - positive=positive) + precompute=False, copy_X=True, max_iter=1000, + tol=1e-4, warm_start=False, positive=False, + random_state=None, selection='cyclic'): + super(Lasso, self).__init__( + alpha=alpha, l1_ratio=1.0, fit_intercept=fit_intercept, + normalize=normalize, precompute=precompute, copy_X=copy_X, + max_iter=max_iter, tol=tol, warm_start=warm_start, + positive=positive, random_state=random_state, + selection=selection) ############################################################################### -# Classes to store linear models along a regularization path - -def lasso_path(X, y, eps=1e-3, n_alphas=100, alphas=None, - precompute='auto', Xy=None, fit_intercept=True, - normalize=False, copy_X=True, verbose=False, - **params): - """Compute Lasso path with coordinate descent - - The optimization objective for Lasso is:: - - (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 - - Parameters - ---------- - X : ndarray, shape = (n_samples, n_features) - Training data. Pass directly as fortran contiguous data to avoid - unnecessary memory duplication - - y : ndarray, shape = (n_samples,) - Target values - - eps : float, optional - Length of the path. eps=1e-3 means that - alpha_min / alpha_max = 1e-3 - - n_alphas : int, optional - Number of alphas along the regularization path - - alphas : ndarray, optional - List of alphas where to compute the models. - If None alphas are set automatically - - precompute : True | False | 'auto' | array-like - Whether to use a precomputed Gram matrix to speed up - calculations. If set to 'auto' let us decide. The Gram - matrix can also be passed as argument. - - Xy : array-like, optional - Xy = np.dot(X.T, y) that can be precomputed. It is useful - only when the Gram matrix is precomputed. - - fit_intercept : bool - Fit or not an intercept - - normalize : boolean, optional - If True, the regressors X are normalized - - copy_X : boolean, optional, default True - If True, X will be copied; else, it may be overwritten. - - verbose : bool or integer - Amount of verbosity - - params : kwargs - keyword arguments passed to the Lasso objects - - Returns - ------- - models : a list of models along the regularization path - - Notes - ----- - See examples/linear_model/plot_lasso_coordinate_descent_path.py - for an example. - - To avoid unnecessary memory duplication the X argument of the fit method - should be directly passed as a fortran contiguous numpy array. - - See also - -------- - lars_path - Lasso - LassoLars - LassoCV - LassoLarsCV - sklearn.decomposition.sparse_encode - """ - return enet_path(X, y, rho=1., eps=eps, n_alphas=n_alphas, alphas=alphas, - precompute=precompute, Xy=Xy, - fit_intercept=fit_intercept, normalize=normalize, - copy_X=copy_X, verbose=verbose, **params) +# Functions for CV with paths functions - -def enet_path(X, y, rho=0.5, eps=1e-3, n_alphas=100, alphas=None, - precompute='auto', Xy=None, fit_intercept=True, - normalize=False, copy_X=True, verbose=False, - **params): - """Compute Elastic-Net path with coordinate descent - - The Elastic Net optimization function is:: - - 1 / (2 * n_samples) * ||y - Xw||^2_2 + - + alpha * rho * ||w||_1 + 0.5 * alpha * (1 - rho) * ||w||^2_2 +def _path_residuals(X, y, train, test, path, path_params, alphas=None, + l1_ratio=1, X_order=None, dtype=None): + """Returns the MSE for the models computed by 'path' Parameters ---------- - X : ndarray, shape = (n_samples, n_features) - Training data. Pass directly as fortran contiguous data to avoid - unnecessary memory duplication - - y : ndarray, shape = (n_samples,) - Target values - - rho : float, optional - float between 0 and 1 passed to ElasticNet (scaling between - l1 and l2 penalties). rho=1 corresponds to the Lasso - - eps : float - Length of the path. eps=1e-3 means that - alpha_min / alpha_max = 1e-3 - - n_alphas : int, optional - Number of alphas along the regularization path - - alphas : ndarray, optional - List of alphas where to compute the models. - If None alphas are set automatically - - precompute : True | False | 'auto' | array-like - Whether to use a precomputed Gram matrix to speed up - calculations. If set to 'auto' let us decide. The Gram - matrix can also be passed as argument. - - Xy : array-like, optional - Xy = np.dot(X.T, y) that can be precomputed. It is useful - only when the Gram matrix is precomputed. - - fit_intercept : bool - Fit or not an intercept - - normalize : boolean, optional - If True, the regressors X are normalized - - copy_X : boolean, optional, default True - If True, X will be copied; else, it may be overwritten. + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. - verbose : bool or integer - Amount of verbosity - - params : kwargs - keyword arguments passed to the Lasso objects - - Returns - ------- - models : a list of models along the regularization path - - Notes - ----- - See examples/plot_lasso_coordinate_descent_path.py for an example. + y : array-like, shape (n_samples,) or (n_samples, n_targets) + Target values - See also - -------- - ElasticNet - ElasticNetCV - """ - X = atleast2d_or_csc(X, dtype=np.float64, order='F', - copy=copy_X and fit_intercept) - # From now on X can be touched inplace - if not sparse.isspmatrix(X): - X, y, X_mean, y_mean, X_std = center_data(X, y, fit_intercept, - normalize, copy=False) - # XXX : in the sparse case the data will be centered - # at each fit... + train : list of indices + The indices of the train set - n_samples, n_features = X.shape + test : list of indices + The indices of the test set - if hasattr(precompute, '__array__') \ - and not np.allclose(X_mean, np.zeros(n_features)) \ - and not np.allclose(X_std, np.ones(n_features)): - # recompute Gram - precompute = 'auto' - Xy = None + path : callable + function returning a list of models on the path. See + enet_path for an example of signature - if precompute is True or \ - ((precompute == 'auto') and (n_samples > n_features)): - if sparse.isspmatrix(X): - warnings.warn("precompute is ignored for sparse data") - precompute = False - else: - precompute = np.dot(X.T, X) + path_params : dictionary + Parameters passed to the path function - if Xy is None: - Xy = safe_sparse_dot(X.T, y, dense_output=True) + alphas : array-like, optional + Array of float that is used for cross-validation. If not + provided, computed using 'path' - n_samples = X.shape[0] - if alphas is None: - alpha_max = np.abs(Xy).max() / (n_samples * rho) - alphas = np.logspace(np.log10(alpha_max * eps), np.log10(alpha_max), - num=n_alphas)[::-1] - else: - alphas = np.sort(alphas)[::-1] # make sure alphas are properly ordered - coef_ = None # init coef_ - models = [] + l1_ratio : float, optional + float between 0 and 1 passed to ElasticNet (scaling between + l1 and l2 penalties). For ``l1_ratio = 0`` the penalty is an + L2 penalty. For ``l1_ratio = 1`` it is an L1 penalty. For ``0 + < l1_ratio < 1``, the penalty is a combination of L1 and L2 - n_alphas = len(alphas) - for i, alpha in enumerate(alphas): - model = ElasticNet(alpha=alpha, rho=rho, - fit_intercept=fit_intercept if sparse.isspmatrix(X) else False, - precompute=precompute) - model.set_params(**params) - model.fit(X, y, coef_init=coef_, Xy=Xy) - if fit_intercept and not sparse.isspmatrix(X): - model.fit_intercept = True - model._set_intercept(X_mean, y_mean, X_std) - if verbose: - if verbose > 2: - print model - elif verbose > 1: - print 'Path: %03i out of %03i' % (i, n_alphas) - else: - sys.stderr.write('.') - coef_ = model.coef_.copy() - models.append(model) - return models + X_order : {'F', 'C', or None}, optional + The order of the arrays expected by the path function to + avoid memory copies + dtype : a numpy dtype or None + The dtype of the arrays expected by the path function to + avoid memory copies + """ + X_train = X[train] + y_train = y[train] + X_test = X[test] + y_test = y[test] + fit_intercept = path_params['fit_intercept'] + normalize = path_params['normalize'] + + if y.ndim == 1: + precompute = path_params['precompute'] + else: + # No Gram variant of multi-task exists right now. + # Fall back to default enet_multitask + precompute = False + + X_train, y_train, X_mean, y_mean, X_std, precompute, Xy = \ + _pre_fit(X_train, y_train, None, precompute, normalize, fit_intercept, + copy=False) + + path_params = path_params.copy() + path_params['Xy'] = Xy + path_params['X_mean'] = X_mean + path_params['X_std'] = X_std + path_params['precompute'] = precompute + path_params['copy_X'] = False + path_params['alphas'] = alphas + + if 'l1_ratio' in path_params: + path_params['l1_ratio'] = l1_ratio + + # Do the ordering and type casting here, as if it is done in the path, + # X is copied and a reference is kept here + X_train = check_array(X_train, 'csc', dtype=dtype, order=X_order) + alphas, coefs, _ = path(X_train, y_train, **path_params) + del X_train, y_train + + if y.ndim == 1: + # Doing this so that it becomes coherent with multioutput. + coefs = coefs[np.newaxis, :, :] + y_mean = np.atleast_1d(y_mean) + y_test = y_test[:, np.newaxis] + + if normalize: + nonzeros = np.flatnonzero(X_std) + coefs[:, nonzeros] /= X_std[nonzeros][:, np.newaxis] + + intercepts = y_mean[:, np.newaxis] - np.dot(X_mean, coefs) + if sparse.issparse(X_test): + n_order, n_features, n_alphas = coefs.shape + # Work around for sparse matices since coefs is a 3-D numpy array. + coefs_feature_major = np.rollaxis(coefs, 1) + feature_2d = np.reshape(coefs_feature_major, (n_features, -1)) + X_test_coefs = safe_sparse_dot(X_test, feature_2d) + X_test_coefs = X_test_coefs.reshape(X_test.shape[0], n_order, -1) + else: + X_test_coefs = safe_sparse_dot(X_test, coefs) + residues = X_test_coefs - y_test[:, :, np.newaxis] + residues += intercepts + this_mses = ((residues ** 2).mean(axis=0)).mean(axis=0) -def _path_residuals(X, y, train, test, path, path_params, rho=1): - this_mses = list() - if 'rho' in path_params: - path_params['rho'] = rho - models_train = path(X[train], y[train], **path_params) - this_mses = np.empty(len(models_train)) - for i_model, model in enumerate(models_train): - y_ = model.predict(X[test]) - this_mses[i_model] = ((y_ - y[test]) ** 2).mean() - return this_mses, rho + return this_mses -class LinearModelCV(LinearModel): +class LinearModelCV(six.with_metaclass(ABCMeta, LinearModel)): """Base class for iterative model fitting along a regularization path""" - __metaclass__ = ABCMeta @abstractmethod def __init__(self, eps=1e-3, n_alphas=100, alphas=None, fit_intercept=True, - normalize=False, precompute='auto', max_iter=1000, tol=1e-4, - copy_X=True, cv=None, verbose=False): + normalize=False, precompute='auto', max_iter=1000, tol=1e-4, + copy_X=True, cv=None, verbose=False, n_jobs=1, + positive=False, random_state=None, selection='cyclic'): self.eps = eps self.n_alphas = n_alphas self.alphas = alphas @@ -665,6 +963,10 @@ def __init__(self, eps=1e-3, n_alphas=100, alphas=None, fit_intercept=True, self.copy_X = copy_X self.cv = cv self.verbose = verbose + self.n_jobs = n_jobs + self.positive = positive + self.random_state = random_state + self.selection = selection def fit(self, X, y): """Fit linear model with coordinate descent @@ -673,43 +975,109 @@ def fit(self, X, y): Parameters ---------- + X : {array-like}, shape (n_samples, n_features) + Training data. Pass directly as float64, Fortran-contiguous data + to avoid unnecessary memory duplication. If y is mono-output, + X can be sparse. - X : array-like, shape (n_samples, n_features) - Training data. Pass directly as fortran contiguous data to avoid - unnecessary memory duplication - - y : narray, shape (n_samples,) or (n_samples, n_targets) + y : array-like, shape (n_samples,) or (n_samples, n_targets) Target values - """ - X = atleast2d_or_csc(X, dtype=np.float64, order='F', - copy=self.copy_X and self.fit_intercept) - # From now on X can be touched inplace y = np.asarray(y, dtype=np.float64) + if y.shape[0] == 0: + raise ValueError("y has 0 samples: %r" % y) + + if hasattr(self, 'l1_ratio'): + model_str = 'ElasticNet' + else: + model_str = 'Lasso' + + if isinstance(self, ElasticNetCV) or isinstance(self, LassoCV): + if model_str == 'ElasticNet': + model = ElasticNet() + else: + model = Lasso() + if y.ndim > 1: + raise ValueError("For multi-task outputs, use " + "MultiTask%sCV" % (model_str)) + else: + if sparse.isspmatrix(X): + raise TypeError("X should be dense but a sparse matrix was" + "passed") + elif y.ndim == 1: + raise ValueError("For mono-task outputs, use " + "%sCV" % (model_str)) + if model_str == 'ElasticNet': + model = MultiTaskElasticNet() + else: + model = MultiTaskLasso() + + if self.selection not in ["random", "cyclic"]: + raise ValueError("selection should be either random or cyclic.") + + # This makes sure that there is no duplication in memory. + # Dealing right with copy_X is important in the following: + # Multiple functions touch X and subsamples of X and can induce a + # lot of duplication of memory + copy_X = self.copy_X and self.fit_intercept + + if isinstance(X, np.ndarray) or sparse.isspmatrix(X): + # Keep a reference to X + reference_to_old_X = X + # Let us not impose fortran ordering or float64 so far: it is + # not useful for the cross-validation loop and will be done + # by the model fitting itself + X = check_array(X, 'csc', copy=False) + if sparse.isspmatrix(X): + if not np.may_share_memory(reference_to_old_X.data, X.data): + # X is a sparse matrix and has been copied + copy_X = False + elif not np.may_share_memory(reference_to_old_X, X): + # X has been copied + copy_X = False + del reference_to_old_X + else: + X = check_array(X, 'csc', dtype=np.float64, order='F', copy=copy_X) + copy_X = False + if X.shape[0] != y.shape[0]: raise ValueError("X and y have inconsistent dimensions (%d != %d)" - % (X.shape[0], y.shape[0])) + % (X.shape[0], y.shape[0])) # All LinearModelCV parameters except 'cv' are acceptable path_params = self.get_params() - if 'rho' in path_params: - rhos = np.atleast_1d(path_params['rho']) - # For the first path, we need to set rho - path_params['rho'] = rhos[0] + if 'l1_ratio' in path_params: + l1_ratios = np.atleast_1d(path_params['l1_ratio']) + # For the first path, we need to set l1_ratio + path_params['l1_ratio'] = l1_ratios[0] else: - rhos = [1, ] + l1_ratios = [1, ] path_params.pop('cv', None) path_params.pop('n_jobs', None) - # Start to compute path on full data - # XXX: is this really useful: we are fitting models that we won't - # use later - models = self.path(X, y, **path_params) - - # Update the alphas list - alphas = [model.alpha for model in models] - n_alphas = len(alphas) - path_params.update({'alphas': alphas, 'n_alphas': n_alphas}) + alphas = self.alphas + n_l1_ratio = len(l1_ratios) + if alphas is None: + alphas = [] + for l1_ratio in l1_ratios: + alphas.append(_alpha_grid( + X, y, l1_ratio=l1_ratio, + fit_intercept=self.fit_intercept, + eps=self.eps, n_alphas=self.n_alphas, + normalize=self.normalize, + copy_X=self.copy_X)) + else: + # Making sure alphas is properly ordered. + alphas = np.tile(np.sort(alphas)[::-1], (n_l1_ratio, 1)) + # We want n_alphas to be the number of alphas used for each l1_ratio. + n_alphas = len(alphas[0]) + path_params.update({'n_alphas': n_alphas}) + + path_params['copy_X'] = copy_X + # We are not computing in parallel, we can modify X + # inplace in the folds + if not (self.n_jobs == 1 or self.n_jobs is None): + path_params['copy_X'] = False # init cross-validation generator cv = check_cv(self.cv, X) @@ -717,49 +1085,57 @@ def fit(self, X, y): # Compute path for all folds and compute MSE to get the best alpha folds = list(cv) best_mse = np.inf - all_mse_paths = list() # We do a double for loop folded in one, in order to be able to - # iterate in parallel on rho and folds - for rho, mse_alphas in itertools.groupby( - Parallel(n_jobs=self.n_jobs, verbose=self.verbose)( - delayed(_path_residuals)(X, y, train, test, - self.path, path_params, rho=rho) - for rho in rhos for train, test in folds - ), operator.itemgetter(1)): - - mse_alphas = [m[0] for m in mse_alphas] - mse_alphas = np.array(mse_alphas) - mse = np.mean(mse_alphas, axis=0) - i_best_alpha = np.argmin(mse) - this_best_mse = mse[i_best_alpha] - all_mse_paths.append(mse_alphas.T) + # iterate in parallel on l1_ratio and folds + jobs = (delayed(_path_residuals)(X, y, train, test, self.path, + path_params, alphas=this_alphas, + l1_ratio=this_l1_ratio, X_order='F', + dtype=np.float64) + for this_l1_ratio, this_alphas in zip(l1_ratios, alphas) + for train, test in folds) + mse_paths = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, + backend="threading")(jobs) + mse_paths = np.reshape(mse_paths, (n_l1_ratio, len(folds), -1)) + mean_mse = np.mean(mse_paths, axis=1) + self.mse_path_ = np.squeeze(np.rollaxis(mse_paths, 2, 1)) + for l1_ratio, l1_alphas, mse_alphas in zip(l1_ratios, alphas, + mean_mse): + i_best_alpha = np.argmin(mse_alphas) + this_best_mse = mse_alphas[i_best_alpha] if this_best_mse < best_mse: - model = models[i_best_alpha] - best_rho = rho - - if hasattr(model, 'rho'): - if model.rho != best_rho: - # Need to refit the model - model.rho = best_rho - model.fit(X, y) - self.rho_ = model.rho + best_alpha = l1_alphas[i_best_alpha] + best_l1_ratio = l1_ratio + best_mse = this_best_mse + + self.l1_ratio_ = best_l1_ratio + self.alpha_ = best_alpha + if self.alphas is None: + self.alphas_ = np.asarray(alphas) + if n_l1_ratio == 1: + self.alphas_ = self.alphas_[0] + # Remove duplicate alphas in case alphas is provided. + else: + self.alphas_ = np.asarray(alphas[0]) + + # Refit the model with the parameters selected + common_params = dict((name, value) + for name, value in self.get_params().items() + if name in model.get_params()) + model.set_params(**common_params) + model.alpha = best_alpha + model.l1_ratio = best_l1_ratio + model.copy_X = copy_X + model.precompute = False + model.fit(X, y) + if not hasattr(self, 'l1_ratio'): + del self.l1_ratio_ self.coef_ = model.coef_ self.intercept_ = model.intercept_ - self.alpha_ = model.alpha - self.alphas_ = np.asarray(alphas) - self.coef_path_ = np.asarray([model.coef_ for model in models]) - self.mse_path_ = np.squeeze(all_mse_paths) + self.dual_gap_ = model.dual_gap_ + self.n_iter_ = model.n_iter_ return self - @property - def alpha(self): - warnings.warn("Use alpha_. Using alpha is deprecated" - "since version 0.12, and backward compatibility " - "won't be maintained from version 0.14 onward. ", - DeprecationWarning, stacklevel=1) - return self.alpha_ - class LassoCV(LinearModelCV, RegressorMixin): """Lasso linear model with iterative fitting along a regularization path @@ -773,62 +1149,100 @@ class LassoCV(LinearModelCV, RegressorMixin): Parameters ---------- eps : float, optional - Length of the path. eps=1e-3 means that - alpha_min / alpha_max = 1e-3. + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3``. n_alphas : int, optional Number of alphas along the regularization path alphas : numpy array, optional List of alphas where to compute the models. - If None alphas are set automatically + If ``None`` alphas are set automatically precompute : True | False | 'auto' | array-like Whether to use a precomputed Gram matrix to speed up - calculations. If set to 'auto' let us decide. The Gram + calculations. If set to ``'auto'`` let us decide. The Gram matrix can also be passed as argument. - max_iter: int, optional + max_iter : int, optional The maximum number of iterations - tol: float, optional + tol : float, optional The tolerance for the optimization: if the updates are - smaller than 'tol', the optimization code checks the + smaller than ``tol``, the optimization code checks the dual gap for optimality and continues until it is smaller - than tol. + than ``tol``. - cv : integer or crossvalidation generator, optional + cv : integer or cross-validation generator, optional If an integer is passed, it is the number of fold (default 3). - Specific crossvalidation objects can be passed, see - sklearn.cross_validation module for the list of possible objects + Specific cross-validation objects can be passed, see the + :mod:`sklearn.cross_validation` module for the list of possible + objects. verbose : bool or integer - amount of verbosity + Amount of verbosity. + + n_jobs : integer, optional + Number of CPUs to use during the cross validation. If ``-1``, use + all the CPUs. + + positive : bool, optional + If positive, restrict regression coefficients to be positive + + selection : str, default 'cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + random_state : int, RandomState instance, or None (default) + The seed of the pseudo random number generator that selects + a random feature to update. Useful only when selection is set to + 'random'. + + fit_intercept : boolean, default True + whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (e.g. data is expected to be already centered). + + normalize : boolean, optional, default False + If ``True``, the regressors X will be normalized before regression. + + copy_X : boolean, optional, default True + If ``True``, X will be copied; else, it may be overwritten. Attributes ---------- - `alpha_`: float - The amount of penalization choosen by cross validation + alpha_ : float + The amount of penalization chosen by cross validation - `coef_` : array, shape = (n_features,) + coef_ : array, shape = (n_features,) | (n_targets, n_features) parameter vector (w in the cost function formula) - `intercept_` : float + intercept_ : float | array, shape = (n_targets,) independent term in decision function. - `mse_path_`: array, shape = (n_alphas, n_folds) + mse_path_ : array, shape = (n_alphas, n_folds) mean square error for the test set on each fold, varying alpha - `alphas_`: numpy array + alphas_ : numpy array, shape = (n_alphas,) The grid of alphas used for fitting + dual_gap_ : ndarray, shape () + The dual gap at the end of the optimization for the optimal alpha + (``alpha_``). + + n_iter_ : int + number of iterations run by the coordinate descent solver to reach + the specified tolerance for the optimal alpha. + Notes ----- See examples/linear_model/lasso_path_with_crossvalidation.py for an example. To avoid unnecessary memory duplication the X argument of the fit method - should be directly passed as a fortran contiguous numpy array. + should be directly passed as a Fortran-contiguous numpy array. See also -------- @@ -839,15 +1253,17 @@ class LassoCV(LinearModelCV, RegressorMixin): LassoLarsCV """ path = staticmethod(lasso_path) - n_jobs = 1 def __init__(self, eps=1e-3, n_alphas=100, alphas=None, fit_intercept=True, - normalize=False, precompute='auto', max_iter=1000, tol=1e-4, - copy_X=True, cv=None, verbose=False): - super(LassoCV, self).__init__(eps=eps, n_alphas=n_alphas, - alphas=alphas, fit_intercept=fit_intercept, - normalize=normalize, precompute=precompute, max_iter=max_iter, - tol=tol, copy_X=copy_X, cv=cv, verbose=verbose) + normalize=False, precompute='auto', max_iter=1000, tol=1e-4, + copy_X=True, cv=None, verbose=False, n_jobs=1, + positive=False, random_state=None, selection='cyclic'): + super(LassoCV, self).__init__( + eps=eps, n_alphas=n_alphas, alphas=alphas, + fit_intercept=fit_intercept, normalize=normalize, + precompute=precompute, max_iter=max_iter, tol=tol, copy_X=copy_X, + cv=cv, verbose=verbose, n_jobs=n_jobs, positive=positive, + random_state=random_state, selection=selection) class ElasticNetCV(LinearModelCV, RegressorMixin): @@ -857,24 +1273,24 @@ class ElasticNetCV(LinearModelCV, RegressorMixin): Parameters ---------- - rho : float, optional + l1_ratio : float, optional float between 0 and 1 passed to ElasticNet (scaling between - l1 and l2 penalties). For rho = 0 - the penalty is an L2 penalty. For rho = 1 it is an L1 penalty. - For 0 < rho < 1, the penalty is a combination of L1 and L2 + l1 and l2 penalties). For ``l1_ratio = 0`` + the penalty is an L2 penalty. For ``l1_ratio = 1`` it is an L1 penalty. + For ``0 < l1_ratio < 1``, the penalty is a combination of L1 and L2 This parameter can be a list, in which case the different values are tested by cross-validation and the one giving the best prediction score is used. Note that a good choice of list of - values for rho is often to put more values close to 1 - (i.e. Lasso) and less close to 0 (i.e. Ridge), as in [.1, .5, .7, - .9, .95, .99, 1] + values for l1_ratio is often to put more values close to 1 + (i.e. Lasso) and less close to 0 (i.e. Ridge), as in ``[.1, .5, .7, + .9, .95, .99, 1]`` eps : float, optional - Length of the path. eps=1e-3 means that - alpha_min / alpha_max = 1e-3. + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3``. n_alphas : int, optional - Number of alphas along the regularization path + Number of alphas along the regularization path, used for each l1_ratio. alphas : numpy array, optional List of alphas where to compute the models. @@ -882,7 +1298,7 @@ class ElasticNetCV(LinearModelCV, RegressorMixin): precompute : True | False | 'auto' | array-like Whether to use a precomputed Gram matrix to speed up - calculations. If set to 'auto' let us decide. The Gram + calculations. If set to ``'auto'`` let us decide. The Gram matrix can also be passed as argument. max_iter : int, optional @@ -890,41 +1306,73 @@ class ElasticNetCV(LinearModelCV, RegressorMixin): tol : float, optional The tolerance for the optimization: if the updates are - smaller than 'tol', the optimization code checks the + smaller than ``tol``, the optimization code checks the dual gap for optimality and continues until it is smaller - than tol. + than ``tol``. - cv : integer or crossvalidation generator, optional + cv : integer or cross-validation generator, optional If an integer is passed, it is the number of fold (default 3). - Specific crossvalidation objects can be passed, see - sklearn.cross_validation module for the list of possible objects + Specific cross-validation objects can be passed, see the + :mod:`sklearn.cross_validation` module for the list of possible + objects. verbose : bool or integer - amount of verbosity + Amount of verbosity. n_jobs : integer, optional - Number of CPUs to use during the cross validation. If '-1', use - all the CPUs. Note that this is used only if multiple values for - rho are given. + Number of CPUs to use during the cross validation. If ``-1``, use + all the CPUs. + + positive : bool, optional + When set to ``True``, forces the coefficients to be positive. + + selection : str, default 'cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + random_state : int, RandomState instance, or None (default) + The seed of the pseudo random number generator that selects + a random feature to update. Useful only when selection is set to + 'random'. + + fit_intercept : boolean + whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (e.g. data is expected to be already centered). + + normalize : boolean, optional, default False + If ``True``, the regressors X will be normalized before regression. + + copy_X : boolean, optional, default True + If ``True``, X will be copied; else, it may be overwritten. Attributes ---------- - `alpha_` : float - The amount of penalization choosen by cross validation + alpha_ : float + The amount of penalization chosen by cross validation - `rho_` : float - The compromise between l1 and l2 penalization choosen by + l1_ratio_ : float + The compromise between l1 and l2 penalization chosen by cross validation - `coef_` : array, shape = (n_features,) - parameter vector (w in the cost function formula) + coef_ : array, shape = (n_features,) | (n_targets, n_features) + Parameter vector (w in the cost function formula), - `intercept_` : float - independent term in decision function. + intercept_ : float | array, shape = (n_targets, n_features) + Independent term in the decision function. - `mse_path_` : array, shape = (n_rho, n_alpha, n_folds) - mean square error for the test set on each fold, varying rho and - alpha + mse_path_ : array, shape = (n_l1_ratio, n_alpha, n_folds) + Mean square error for the test set on each fold, varying l1_ratio and + alpha. + + alphas_ : numpy array, shape = (n_alphas,) or (n_l1_ratio, n_alphas) + The grid of alphas used for fitting, for each l1_ratio. + + n_iter_ : int + number of iterations run by the coordinate descent solver to reach + the specified tolerance for the optimal alpha. Notes ----- @@ -932,14 +1380,15 @@ class ElasticNetCV(LinearModelCV, RegressorMixin): for an example. To avoid unnecessary memory duplication the X argument of the fit method - should be directly passed as a fortran contiguous numpy array. + should be directly passed as a Fortran-contiguous numpy array. - The parameter rho corresponds to alpha in the glmnet R package + The parameter l1_ratio corresponds to alpha in the glmnet R package while alpha corresponds to the lambda parameter in glmnet. More specifically, the optimization objective is:: 1 / (2 * n_samples) * ||y - Xw||^2_2 + - + alpha * rho * ||w||_1 + 0.5 * alpha * (1 - rho) * ||w||^2_2 + + alpha * l1_ratio * ||w||_1 + + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2 If you are interested in controlling the L1 and L2 penalty separately, keep in mind that this is equivalent to:: @@ -948,7 +1397,7 @@ class ElasticNetCV(LinearModelCV, RegressorMixin): for:: - alpha = a + b and rho = a / (a + b) + alpha = a + b and l1_ratio = a / (a + b). See also -------- @@ -958,11 +1407,12 @@ class ElasticNetCV(LinearModelCV, RegressorMixin): """ path = staticmethod(enet_path) - def __init__(self, rho=0.5, eps=1e-3, n_alphas=100, alphas=None, + def __init__(self, l1_ratio=0.5, eps=1e-3, n_alphas=100, alphas=None, fit_intercept=True, normalize=False, precompute='auto', max_iter=1000, tol=1e-4, cv=None, copy_X=True, - verbose=0, n_jobs=1): - self.rho = rho + verbose=0, n_jobs=1, positive=False, random_state=None, + selection='cyclic'): + self.l1_ratio = l1_ratio self.eps = eps self.n_alphas = n_alphas self.alphas = alphas @@ -975,67 +1425,88 @@ def __init__(self, rho=0.5, eps=1e-3, n_alphas=100, alphas=None, self.copy_X = copy_X self.verbose = verbose self.n_jobs = n_jobs + self.positive = positive + self.random_state = random_state + self.selection = selection ############################################################################### # Multi Task ElasticNet and Lasso models (with joint feature selection) + class MultiTaskElasticNet(Lasso): """Multi-task ElasticNet model trained with L1/L2 mixed-norm as regularizer - The optimization objective for Lasso is:: + The optimization objective for MultiTaskElasticNet is:: (1 / (2 * n_samples)) * ||Y - XW||^Fro_2 - + alpha * rho * ||W||_21 + 0.5 * alpha * (1 - rho) * ||W||_Fro^2 + + alpha * l1_ratio * ||W||_21 + + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2 Where:: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2} - i.e. the sum of norm of earch row. + i.e. the sum of norm of each row. Parameters ---------- alpha : float, optional Constant that multiplies the L1/L2 term. Defaults to 1.0 - rho : float - The ElasticNet mixing parameter, with 0 < rho <= 1. For rho = 0 - the penalty is an L1/L2 penalty. For rho = 1 it is an L1 penalty. - For 0 < rho < 1, the penalty is a combination of L1/L2 and L2 + l1_ratio : float + The ElasticNet mixing parameter, with 0 < l1_ratio <= 1. + For l1_ratio = 0 the penalty is an L1/L2 penalty. For l1_ratio = 1 it + is an L1 penalty. + For ``0 < l1_ratio < 1``, the penalty is a combination of L1/L2 and L2. fit_intercept : boolean whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default False + If ``True``, the regressors X will be normalized before regression. copy_X : boolean, optional, default True - If True, X will be copied; else, it may be overwritten. + If ``True``, X will be copied; else, it may be overwritten. max_iter : int, optional The maximum number of iterations tol : float, optional The tolerance for the optimization: if the updates are - smaller than 'tol', the optimization code checks the + smaller than ``tol``, the optimization code checks the dual gap for optimality and continues until it is smaller - than tol. + than ``tol``. warm_start : bool, optional - When set to True, reuse the solution of the previous call to fit as + When set to ``True``, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. + selection : str, default 'cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + random_state : int, RandomState instance, or None (default) + The seed of the pseudo random number generator that selects + a random feature to update. Useful only when selection is set to + 'random'. + Attributes ---------- - `intercept_` : array, shape = (n_tasks,) + intercept_ : array, shape = (n_tasks,) Independent term in decision function. - `coef_` : array, shape = (n_tasks, n_features) + coef_ : array, shape = (n_tasks, n_features) Parameter vector (W in the cost function formula). If a 1D y is \ - passed in at fit (non multi-task usage), `coef_` is then a 1D array + passed in at fit (non multi-task usage), ``coef_`` is then a 1D array + + n_iter_ : int + number of iterations run by the coordinate descent solver to reach + the specified tolerance. Examples -------- @@ -1044,12 +1515,12 @@ class MultiTaskElasticNet(Lasso): >>> clf.fit([[0,0], [1, 1], [2, 2]], [[0, 0], [1, 1], [2, 2]]) ... #doctest: +NORMALIZE_WHITESPACE MultiTaskElasticNet(alpha=0.1, copy_X=True, fit_intercept=True, - max_iter=1000, normalize=False, rho=0.5, tol=0.0001, - warm_start=False) - >>> print clf.coef_ + l1_ratio=0.5, max_iter=1000, normalize=False, random_state=None, + selection='cyclic', tol=0.0001, warm_start=False) + >>> print(clf.coef_) [[ 0.45663524 0.45612256] [ 0.45663524 0.45612256]] - >>> print clf.intercept_ + >>> print(clf.intercept_) [ 0.0872422 0.0872422] See also @@ -1061,10 +1532,12 @@ class MultiTaskElasticNet(Lasso): The algorithm used to fit the model is coordinate descent. To avoid unnecessary memory duplication the X argument of the fit method - should be directly passed as a fortran contiguous numpy array. + should be directly passed as a Fortran-contiguous numpy array. """ - def __init__(self, alpha=1.0, rho=0.5, fit_intercept=True, normalize=False, - copy_X=True, max_iter=1000, tol=1e-4, warm_start=False): + def __init__(self, alpha=1.0, l1_ratio=0.5, fit_intercept=True, + normalize=False, copy_X=True, max_iter=1000, tol=1e-4, + warm_start=False, random_state=None, selection='cyclic'): + self.l1_ratio = l1_ratio self.alpha = alpha self.coef_ = None self.fit_intercept = fit_intercept @@ -1073,68 +1546,70 @@ def __init__(self, alpha=1.0, rho=0.5, fit_intercept=True, normalize=False, self.copy_X = copy_X self.tol = tol self.warm_start = warm_start - self.rho = rho + self.random_state = random_state + self.selection = selection - def fit(self, X, y, Xy=None, coef_init=None): + def fit(self, X, y): """Fit MultiTaskLasso model with coordinate descent Parameters ----------- - X: ndarray, shape = (n_samples, n_features) + X : ndarray, shape = (n_samples, n_features) Data - y: ndarray, shape = (n_samples, n_tasks) + y : ndarray, shape = (n_samples, n_tasks) Target - coef_init: ndarray of shape n_features - The initial coeffients to warm-start the optimization Notes ----- Coordinate descent is an algorithm that considers each column of data at a time hence it will automatically convert the X input - as a fortran contiguous numpy array if necessary. + as a Fortran-contiguous numpy array if necessary. To avoid memory re-allocation it is advised to allocate the initial data in memory directly using that format. """ # X and y must be of type float64 - X = array2d(X, dtype=np.float64, order='F', - copy=self.copy_X and self.fit_intercept) + X = check_array(X, dtype=np.float64, order='F', + copy=self.copy_X and self.fit_intercept) y = np.asarray(y, dtype=np.float64) - squeeze_me = False + if hasattr(self, 'l1_ratio'): + model_str = 'ElasticNet' + else: + model_str = 'Lasso' if y.ndim == 1: - squeeze_me = True - y = y[:, np.newaxis] + raise ValueError("For mono-task outputs, use %s" % model_str) n_samples, n_features = X.shape _, n_tasks = y.shape - X, y, X_mean, y_mean, X_std = center_data(X, y, - self.fit_intercept, self.normalize, copy=False) + if n_samples != y.shape[0]: + raise ValueError("X and y have inconsistent dimensions (%d != %d)" + % (n_samples, y.shape[0])) - if coef_init is None: - if not self.warm_start or self.coef_ is None: - self.coef_ = np.zeros((n_tasks, n_features), dtype=np.float64, - order='F') - else: - self.coef_ = coef_init + X, y, X_mean, y_mean, X_std = center_data( + X, y, self.fit_intercept, self.normalize, copy=False) - l1_reg = self.alpha * self.rho * n_samples - l2_reg = self.alpha * (1.0 - self.rho) * n_samples + if not self.warm_start or self.coef_ is None: + self.coef_ = np.zeros((n_tasks, n_features), dtype=np.float64, + order='F') + + l1_reg = self.alpha * self.l1_ratio * n_samples + l2_reg = self.alpha * (1.0 - self.l1_ratio) * n_samples self.coef_ = np.asfortranarray(self.coef_) # coef contiguous in memory - self.coef_, self.dual_gap_, self.eps_ = \ - cd_fast.enet_coordinate_descent_multi_task(self.coef_, l1_reg, - l2_reg, X, y, self.max_iter, self.tol) + if self.selection not in ['random', 'cyclic']: + raise ValueError("selection should be either random or cyclic.") + random = (self.selection == 'random') - self._set_intercept(X_mean, y_mean, X_std) + self.coef_, self.dual_gap_, self.eps_, self.n_iter_ = \ + cd_fast.enet_coordinate_descent_multi_task( + self.coef_, l1_reg, l2_reg, X, y, self.max_iter, self.tol, + check_random_state(self.random_state), random) - # Make sure that the coef_ have the same shape as the given 'y', - # to predict with the same shape - if squeeze_me: - self.coef_ = self.coef_.squeeze() + self._set_intercept(X_mean, y_mean, X_std) if self.dual_gap_ > self.eps_: warnings.warn('Objective did not converge, you might want' @@ -1167,44 +1642,60 @@ class MultiTaskLasso(MultiTaskElasticNet): to false, no intercept will be used in calculations (e.g. data is expected to be already centered). - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default False + If ``True``, the regressors X will be normalized before regression. copy_X : boolean, optional, default True - If True, X will be copied; else, it may be overwritten. + If ``True``, X will be copied; else, it may be overwritten. max_iter : int, optional The maximum number of iterations tol : float, optional The tolerance for the optimization: if the updates are - smaller than 'tol', the optimization code checks the + smaller than ``tol``, the optimization code checks the dual gap for optimality and continues until it is smaller - than tol. + than ``tol``. warm_start : bool, optional - When set to True, reuse the solution of the previous call to fit as + When set to ``True``, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. + selection : str, default 'cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4 + + random_state : int, RandomState instance, or None (default) + The seed of the pseudo random number generator that selects + a random feature to update. Useful only when selection is set to + 'random'. + Attributes ---------- - `coef_` : array, shape = (n_tasks, n_features) + coef_ : array, shape = (n_tasks, n_features) parameter vector (W in the cost function formula) - `intercept_` : array, shape = (n_tasks,) + intercept_ : array, shape = (n_tasks,) independent term in decision function. + n_iter_ : int + number of iterations run by the coordinate descent solver to reach + the specified tolerance. + Examples -------- >>> from sklearn import linear_model >>> clf = linear_model.MultiTaskLasso(alpha=0.1) >>> clf.fit([[0,0], [1, 1], [2, 2]], [[0, 0], [1, 1], [2, 2]]) MultiTaskLasso(alpha=0.1, copy_X=True, fit_intercept=True, max_iter=1000, - normalize=False, tol=0.0001, warm_start=False) - >>> print clf.coef_ + normalize=False, random_state=None, selection='cyclic', tol=0.0001, + warm_start=False) + >>> print(clf.coef_) [[ 0.89393398 0. ] [ 0.89393398 0. ]] - >>> print clf.intercept_ + >>> print(clf.intercept_) [ 0.10606602 0.10606602] See also @@ -1216,10 +1707,11 @@ class MultiTaskLasso(MultiTaskElasticNet): The algorithm used to fit the model is coordinate descent. To avoid unnecessary memory duplication the X argument of the fit method - should be directly passed as a fortran contiguous numpy array. + should be directly passed as a Fortran-contiguous numpy array. """ def __init__(self, alpha=1.0, fit_intercept=True, normalize=False, - copy_X=True, max_iter=1000, tol=1e-4, warm_start=False): + copy_X=True, max_iter=1000, tol=1e-4, warm_start=False, + random_state=None, selection='cyclic'): self.alpha = alpha self.coef_ = None self.fit_intercept = fit_intercept @@ -1228,4 +1720,281 @@ def __init__(self, alpha=1.0, fit_intercept=True, normalize=False, self.copy_X = copy_X self.tol = tol self.warm_start = warm_start - self.rho = 1.0 + self.l1_ratio = 1.0 + self.random_state = random_state + self.selection = selection + + +class MultiTaskElasticNetCV(LinearModelCV, RegressorMixin): + """Multi-task L1/L2 ElasticNet with built-in cross-validation. + + The optimization objective for MultiTaskElasticNet is:: + + (1 / (2 * n_samples)) * ||Y - XW||^Fro_2 + + alpha * l1_ratio * ||W||_21 + + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2 + + Where:: + + ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2} + + i.e. the sum of norm of each row. + + Parameters + ---------- + eps : float, optional + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3``. + + alphas : array-like, optional + List of alphas where to compute the models. + If not provided, set automatically. + + n_alphas : int, optional + Number of alphas along the regularization path + + l1_ratio : float or array of floats + The ElasticNet mixing parameter, with 0 < l1_ratio <= 1. + For l1_ratio = 0 the penalty is an L1/L2 penalty. For l1_ratio = 1 it + is an L1 penalty. + For ``0 < l1_ratio < 1``, the penalty is a combination of L1/L2 and L2. + + fit_intercept : boolean + whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (e.g. data is expected to be already centered). + + normalize : boolean, optional, default False + If ``True``, the regressors X will be normalized before regression. + + copy_X : boolean, optional, default True + If ``True``, X will be copied; else, it may be overwritten. + + max_iter : int, optional + The maximum number of iterations + + tol : float, optional + The tolerance for the optimization: if the updates are + smaller than ``tol``, the optimization code checks the + dual gap for optimality and continues until it is smaller + than ``tol``. + + cv : integer or cross-validation generator, optional + If an integer is passed, it is the number of fold (default 3). + Specific cross-validation objects can be passed, see the + :mod:`sklearn.cross_validation` module for the list of possible + objects. + + verbose : bool or integer + Amount of verbosity. + + n_jobs : integer, optional + Number of CPUs to use during the cross validation. If ``-1``, use + all the CPUs. Note that this is used only if multiple values for + l1_ratio are given. + + selection : str, default 'cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + random_state : int, RandomState instance, or None (default) + The seed of the pseudo random number generator that selects + a random feature to update. Useful only when selection is set to + 'random'. + + Attributes + ---------- + intercept_ : array, shape (n_tasks,) + Independent term in decision function. + + coef_ : array, shape (n_tasks, n_features) + Parameter vector (W in the cost function formula). + + alpha_ : float + The amount of penalization chosen by cross validation + + mse_path_ : array, shape (n_alphas, n_folds) or + (n_l1_ratio, n_alphas, n_folds) + mean square error for the test set on each fold, varying alpha + + alphas_ : numpy array, shape (n_alphas,) or (n_l1_ratio, n_alphas) + The grid of alphas used for fitting, for each l1_ratio + + l1_ratio_ : float + best l1_ratio obtained by cross-validation. + + n_iter_ : int + number of iterations run by the coordinate descent solver to reach + the specified tolerance for the optimal alpha. + + Examples + -------- + >>> from sklearn import linear_model + >>> clf = linear_model.MultiTaskElasticNetCV() + >>> clf.fit([[0,0], [1, 1], [2, 2]], + ... [[0, 0], [1, 1], [2, 2]]) + ... #doctest: +NORMALIZE_WHITESPACE + MultiTaskElasticNetCV(alphas=None, copy_X=True, cv=None, eps=0.001, + fit_intercept=True, l1_ratio=0.5, max_iter=1000, n_alphas=100, + n_jobs=1, normalize=False, random_state=None, selection='cyclic', + tol=0.0001, verbose=0) + >>> print(clf.coef_) + [[ 0.52875032 0.46958558] + [ 0.52875032 0.46958558]] + >>> print(clf.intercept_) + [ 0.00166409 0.00166409] + + See also + -------- + MultiTaskElasticNet + ElasticNetCV + MultiTaskLassoCV + + Notes + ----- + The algorithm used to fit the model is coordinate descent. + + To avoid unnecessary memory duplication the X argument of the fit method + should be directly passed as a Fortran-contiguous numpy array. + """ + path = staticmethod(enet_path) + + def __init__(self, l1_ratio=0.5, eps=1e-3, n_alphas=100, alphas=None, + fit_intercept=True, normalize=False, + max_iter=1000, tol=1e-4, cv=None, copy_X=True, + verbose=0, n_jobs=1, random_state=None, selection='cyclic'): + self.l1_ratio = l1_ratio + self.eps = eps + self.n_alphas = n_alphas + self.alphas = alphas + self.fit_intercept = fit_intercept + self.normalize = normalize + self.max_iter = max_iter + self.tol = tol + self.cv = cv + self.copy_X = copy_X + self.verbose = verbose + self.n_jobs = n_jobs + self.random_state = random_state + self.selection = selection + + +class MultiTaskLassoCV(LinearModelCV, RegressorMixin): + """Multi-task L1/L2 Lasso with built-in cross-validation. + + The optimization objective for MultiTaskLasso is:: + + (1 / (2 * n_samples)) * ||Y - XW||^Fro_2 + alpha * ||W||_21 + + Where:: + + ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2} + + i.e. the sum of norm of each row. + + Parameters + ---------- + eps : float, optional + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3``. + + alphas : array-like, optional + List of alphas where to compute the models. + If not provided, set automaticlly. + + n_alphas : int, optional + Number of alphas along the regularization path + + fit_intercept : boolean + whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (e.g. data is expected to be already centered). + + normalize : boolean, optional, default False + If ``True``, the regressors X will be normalized before regression. + + copy_X : boolean, optional, default True + If ``True``, X will be copied; else, it may be overwritten. + + max_iter : int, optional + The maximum number of iterations. + + tol : float, optional + The tolerance for the optimization: if the updates are + smaller than ``tol``, the optimization code checks the + dual gap for optimality and continues until it is smaller + than ``tol``. + + cv : integer or cross-validation generator, optional + If an integer is passed, it is the number of fold (default 3). + Specific cross-validation objects can be passed, see the + :mod:`sklearn.cross_validation` module for the list of possible + objects. + + verbose : bool or integer + Amount of verbosity. + + n_jobs : integer, optional + Number of CPUs to use during the cross validation. If ``-1``, use + all the CPUs. Note that this is used only if multiple values for + l1_ratio are given. + + selection : str, default 'cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + random_state : int, RandomState instance, or None (default) + The seed of the pseudo random number generator that selects + a random feature to update. Useful only when selection is set to + 'random'. + + Attributes + ---------- + intercept_ : array, shape (n_tasks,) + Independent term in decision function. + + coef_ : array, shape (n_tasks, n_features) + Parameter vector (W in the cost function formula). + + alpha_ : float + The amount of penalization chosen by cross validation + + mse_path_ : array, shape (n_alphas, n_folds) + mean square error for the test set on each fold, varying alpha + + alphas_ : numpy array, shape (n_alphas,) + The grid of alphas used for fitting. + + n_iter_ : int + number of iterations run by the coordinate descent solver to reach + the specified tolerance for the optimal alpha. + + See also + -------- + MultiTaskElasticNet + ElasticNetCV + MultiTaskElasticNetCV + + Notes + ----- + The algorithm used to fit the model is coordinate descent. + + To avoid unnecessary memory duplication the X argument of the fit method + should be directly passed as a Fortran-contiguous numpy array. + """ + path = staticmethod(lasso_path) + + def __init__(self, eps=1e-3, n_alphas=100, alphas=None, fit_intercept=True, + normalize=False, max_iter=1000, tol=1e-4, copy_X=True, + cv=None, verbose=False, n_jobs=1, random_state=None, + selection='cyclic'): + super(MultiTaskLassoCV, self).__init__( + eps=eps, n_alphas=n_alphas, alphas=alphas, + fit_intercept=fit_intercept, normalize=normalize, + max_iter=max_iter, tol=tol, copy_X=copy_X, + cv=cv, verbose=verbose, n_jobs=n_jobs, random_state=random_state, + selection=selection) diff --git a/sklearn/linear_model/isotonic_regression_.py b/sklearn/linear_model/isotonic_regression_.py deleted file mode 100644 index 420f60614190f..0000000000000 --- a/sklearn/linear_model/isotonic_regression_.py +++ /dev/null @@ -1,241 +0,0 @@ -# Authors: Fabian Pedregosa -# Alexandre Gramfort -# Nelle Varoquaux -# License: BSD Style. - -import numpy as np -from scipy import interpolate -from ..base import BaseEstimator, TransformerMixin, RegressorMixin -from ..utils import as_float_array, check_arrays - - -def isotonic_regression(y, weight=None, y_min=None, y_max=None): - """Solve the isotonic regression model: - - min sum w[i] (y[i] - y_[i]) ** 2 - - subject to y_min = y_[1] <= y_[2] ... <= y_[n] = y_max - - where: - - y[i] are inputs (real numbers) - - y_[i] are fitted - - w[i] are optional strictly positive weights (default to 1.0) - - Parameters - ---------- - y: iterable of floating-point values - The data - - weight: iterable of floating-point values, optional, default: None - Weights on each point of the regression. - If None, weight is set to 1 (equal weights) - - y_min: optional, default: None - if not None, set the lowest value of the fit to y_min - - y_max: optional, default: None - if not None, set the highest value of the fit to y_max - - Returns - ------- - y_: list of floating-point values - Isotonic fit of y - - References - ---------- - "Active set algorithms for isotonic regression; A unifying framework" - by Michael J. Best and Nilotpal Chakravarti, section 3. - """ - if weight is None: - weight = np.ones(len(y), dtype=y.dtype) - if y_min is not None or y_max is not None: - y = np.copy(y) - weight = np.copy(weight) - C = np.dot(weight, y * y) * 10 # upper bound on the cost function - if y_min is not None: - y[0] = y_min - weight[0] = C - if y_max is not None: - y[-1] = y_max - weight[-1] = C - - active_set = [(weight[i] * y[i], weight[i], [i, ]) - for i in range(len(y))] - current = 0 - - while current < len(active_set) - 1: - value0, value1, value2 = 0, 0, np.inf - weight0, weight1, weight2 = 1, 1, 1 - while value0 * weight1 <= value1 * weight0 and \ - current < len(active_set) - 1: - value0, weight0, idx0 = active_set[current] - value1, weight1, idx1 = active_set[current + 1] - if value0 * weight1 <= value1 * weight0: - current += 1 - - if current == len(active_set) - 1: - break - - # merge two groups - value0, weight0, idx0 = active_set.pop(current) - value1, weight1, idx1 = active_set.pop(current) - active_set.insert(current, - (value0 + value1, - weight0 + weight1, idx0 + idx1)) - while value2 * weight0 > value0 * weight2 and current > 0: - value0, weight0, idx0 = active_set[current] - value2, weight2, idx2 = active_set[current - 1] - if weight0 * value2 >= weight2 * value0: - active_set.pop(current) - active_set[current - 1] = (value0 + value2, - weight0 + weight2, - idx0 + idx2) - current -= 1 - - solution = np.empty(len(y)) - for value, weight, idx in active_set: - solution[idx] = value / weight - return solution - - -class IsotonicRegression(BaseEstimator, TransformerMixin, RegressorMixin): - """Isotonic regression model. - - The isotonic regression optimization problem is defined by:: - min sum w_i (y[i] - y_[i]) ** 2 - - subject to y_min = y_[1] <= y_[2] ... <= y_[n] = y_max - - where: - - y[i] are inputs (real numbers) - - y_[i] are fitted - - w[i] are optional strictly positive weights (default to 1.0) - - Parameters - ---------- - y_min: optional, default: None - If not None, set the lowest value of the fit to y_min. - - y_max: optional, default: None - If not None, set the highest value of the fit to y_max. - - Attributes - ---------- - `X_`: ndarray (n_samples, ) - A copy of the input X. - - `y_`: ndarray (n_samples, ) - Isotonic fit of y. - - References - ---------- - Isotonic Median Regression: A Linear Programming Approach - Nilotpal Chakravarti - Mathematics of Operations Research - Vol. 14, No. 2 (May, 1989), pp. 303-308 - """ - def __init__(self, y_min=None, y_max=None): - self.y_min = y_min - self.y_max = y_max - - def _check_fit_data(self, X, y, weight=None): - if len(X.shape) != 1: - raise ValueError("X should be a vector") - - def fit(self, X, y, weight=None): - """Fit the model using X, y as training data. - - Parameters - ---------- - X: array-like, shape=(n_samples,) - training data - - y: array-like, shape=(n_samples,) - training target - - weight: array-like, shape=(n_samples,), optional, default: None - weights. If set to None, all weights will be set to 1 (equal - weights) - - Returns - ------- - self; object - returns an instance of self - - Note - ---- - X doesn't influence the result of `fit`. It is however stored - for future use, as `transform` needs X to interpolate new - input data. - """ - X, y, weight = check_arrays(X, y, weight, sparse_format='dense') - y = as_float_array(y) - self.X_ = as_float_array(X, copy=True) - self._check_fit_data(self.X_, y, weight) - self.y_ = isotonic_regression(y, weight, self.y_min, self.y_max) - return self - - def transform(self, T): - """Transform new data by linear interpolation - - Parameters - ---------- - T: array-like, shape=(n_samples,) - data to transform - - Returns - ------- - T_: array, shape=(n_samples,) - The transformed data - """ - T = as_float_array(T) - if len(T.shape) != 1: - raise ValueError("X should be a vector") - - f = interpolate.interp1d(self.X_, self.y_, kind='linear', - bounds_error=True) - return f(T) - - def fit_transform(self, X, y, weight=None): - """Fit model and transform y by linear interpolation. - - Parameters - ---------- - X: array-like, shape=(n_samples,) - training data - - y: array-like, shape=(n_samples,) - training target - - weight: array-like, shape=(n_samples,), optional, default: None - weights. If set to None, all weights will be equal to 1 (equal - weights) - - Returns - ------- - y_: array, shape=(n_samples,) - The transformed data - - Note - ---- - X doesn't influence the result of `fit_transform`. It is however stored - for future use, as `transform` needs X to interpolate new input - data. - """ - self.fit(X, y, weight) - return self.y_ - - def predict(self, T): - """Predict new data by linear interpolation. - - Parameters - ---------- - T: array-like, shape=(n_samples,) - Data to transform. - - Returns - ------- - T_: array, shape=(n_samples,) - Transformed data. - """ - return self.transform(T) diff --git a/sklearn/linear_model/least_angle.py b/sklearn/linear_model/least_angle.py index c44e0f15c0e17..f2c352ff353ff 100644 --- a/sklearn/linear_model/least_angle.py +++ b/sklearn/linear_model/least_angle.py @@ -2,16 +2,18 @@ Least Angle Regression algorithm. See the documentation on the Generalized Linear Model for a complete discussion. """ +from __future__ import print_function # Author: Fabian Pedregosa # Alexandre Gramfort # Gael Varoquaux # -# License: BSD Style. +# License: BSD 3 clause from math import log import sys import warnings +from distutils.version import LooseVersion import numpy as np from scipy import linalg, interpolate @@ -19,67 +21,95 @@ from .base import LinearModel from ..base import RegressorMixin -from ..utils import array2d, arrayfuncs, as_float_array -from ..cross_validation import check_cv +from ..utils import arrayfuncs, as_float_array, check_X_y +from ..cross_validation import _check_cv as check_cv +from ..utils import ConvergenceWarning from ..externals.joblib import Parallel, delayed +from ..externals.six.moves import xrange + +import scipy +solve_triangular_args = {} +if LooseVersion(scipy.__version__) >= LooseVersion('0.12'): + solve_triangular_args = {'check_finite': False} def lars_path(X, y, Xy=None, Gram=None, max_iter=500, alpha_min=0, method='lar', copy_X=True, eps=np.finfo(np.float).eps, - copy_Gram=True, verbose=False, return_path=True): - """Compute Least Angle Regression and Lasso path + copy_Gram=True, verbose=0, return_path=True, + return_n_iter=False): + """Compute Least Angle Regression or Lasso path using LARS algorithm [1] - The optimization objective for Lasso is:: + The optimization objective for the case method='lasso' is:: (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 + in the case of method='lars', the objective function is only known in + the form of an implicit equation (see discussion in [1]) + Parameters ----------- - X: array, shape: (n_samples, n_features) - Input data + X : array, shape: (n_samples, n_features) + Input data. - y: array, shape: (n_samples) - Input targets + y : array, shape: (n_samples) + Input targets. - max_iter: integer, optional + max_iter : integer, optional (default=500) Maximum number of iterations to perform, set to infinity for no limit. - Gram: None, 'auto', array, shape: (n_features, n_features), optional - Precomputed Gram matrix (X' * X), if 'auto', the Gram + Gram : None, 'auto', array, shape: (n_features, n_features), optional + Precomputed Gram matrix (X' * X), if ``'auto'``, the Gram matrix is precomputed from the given X, if there are more samples - than features + than features. - alpha_min: float, optional + alpha_min : float, optional (default=0) Minimum correlation along the path. It corresponds to the regularization parameter alpha parameter in the Lasso. - method: {'lar', 'lasso'} - Specifies the returned model. Select 'lar' for Least Angle - Regression, 'lasso' for the Lasso. + method : {'lar', 'lasso'}, optional (default='lar') + Specifies the returned model. Select ``'lar'`` for Least Angle + Regression, ``'lasso'`` for the Lasso. - eps: float, optional + eps : float, optional (default=``np.finfo(np.float).eps``) The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. - copy_X: bool - If False, X is overwritten. + copy_X : bool, optional (default=True) + If ``False``, ``X`` is overwritten. + + copy_Gram : bool, optional (default=True) + If ``False``, ``Gram`` is overwritten. + + verbose : int (default=0) + Controls output verbosity. - copy_Gram: bool - If False, Gram is overwritten. + return_path : bool, optional (default=True) + If ``return_path==True`` returns the entire path, else returns only the + last point of the path. + + return_n_iter : bool, optional (default=False) + Whether to return the number of iterations. Returns -------- - alphas: array, shape: (max_features + 1,) + alphas : array, shape: [n_alphas + 1] Maximum of covariances (in absolute value) at each iteration. + ``n_alphas`` is either ``max_iter``, ``n_features`` or the + number of nodes in the path with ``alpha >= alpha_min``, whichever + is smaller. - active: array, shape (max_features,) + active : array, shape [n_alphas] Indices of active variables at the end of the path. - coefs: array, shape (n_features, max_features + 1) + coefs : array, shape (n_features, n_alphas + 1) Coefficients along the path + n_iter : int + Number of iterations run. Returned only if return_n_iter is set + to True. + See also -------- lasso_path @@ -89,11 +119,17 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, LarsCV sklearn.decomposition.sparse_encode - Notes - ------ - * http://en.wikipedia.org/wiki/Least-angle_regression + References + ---------- + .. [1] "Least Angle Regression", Effron et al. + http://www-stat.stanford.edu/~tibs/ftp/lars.pdf + + .. [2] `Wikipedia entry on the Least-angle regression + `_ + + .. [3] `Wikipedia entry on the Lasso + `_ - * http://en.wikipedia.org/wiki/Lasso_(statistics)#LASSO_method """ n_features = X.shape[1] @@ -115,7 +151,13 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, # will hold the cholesky factorization. Only lower part is # referenced. - L = np.empty((max_features, max_features), dtype=X.dtype) + # We are initializing this to "zeros" and not empty, because + # it is passed to scipy linalg functions and thus if it has NaNs, + # even if they are in the upper part that it not used, we + # get errors raised. + # Once we support only scipy > 0.12 we can use check_finite=False and + # go back to "empty" + L = np.zeros((max_features, max_features), dtype=X.dtype) swap, nrm2 = linalg.get_blas_funcs(('swap', 'nrm2'), (X,)) solve_cholesky, = get_lapack_funcs(('potrs',), (X,)) @@ -130,7 +172,7 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, if X.shape[0] > X.shape[1]: Gram = np.dot(X.T, X) elif copy_Gram: - Gram = Gram.copy() + Gram = Gram.copy() if Xy is None: Cov = np.dot(X.T, y) @@ -139,13 +181,14 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, if verbose: if verbose > 1: - print "Step\t\tAdded\t\tDropped\t\tActive set size\t\tC" + print("Step\t\tAdded\t\tDropped\t\tActive set size\t\tC") else: sys.stdout.write('.') sys.stdout.flush() tiny = np.finfo(np.float).tiny # to avoid division by 0 warning tiny32 = np.finfo(np.float32).tiny # to avoid division by 0 warning + equality_tolerance = np.finfo(np.float32).eps while True: if Cov.size: @@ -162,14 +205,16 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, prev_coef = coefs[n_iter - 1] alpha[0] = C / n_samples - if alpha[0] < alpha_min: # early stopping - # interpolation factor 0 <= ss < 1 - if n_iter > 0: - # In the first iteration, all alphas are zero, the formula - # below would make ss a NaN - ss = (prev_alpha[0] - alpha_min) / (prev_alpha[0] - alpha[0]) - coef[:] = prev_coef + ss * (coef - prev_coef) - alpha[0] = alpha_min + if alpha[0] <= alpha_min + equality_tolerance: # early stopping + if abs(alpha[0] - alpha_min) > equality_tolerance: + # interpolation factor 0 <= ss < 1 + if n_iter > 0: + # In the first iteration, all alphas are zero, the formula + # below would make ss a NaN + ss = ((prev_alpha[0] - alpha_min) / + (prev_alpha[0] - alpha[0])) + coef[:] = prev_coef + ss * (coef - prev_coef) + alpha[0] = alpha_min if return_path: coefs[n_iter] = coef break @@ -193,6 +238,7 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, Cov[C_idx], Cov[0] = swap(Cov[C_idx], Cov[0]) indices[n], indices[m] = indices[m], indices[n] + Cov_not_shortened = Cov Cov = Cov[1:] # remove Cov[0] if Gram is None: @@ -209,37 +255,87 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, L[n_active, :n_active] = Gram[n_active, :n_active] # Update the cholesky decomposition for the Gram matrix - arrayfuncs.solve_triangular(L[:n_active, :n_active], - L[n_active, :n_active]) + if n_active: + linalg.solve_triangular(L[:n_active, :n_active], + L[n_active, :n_active], + trans=0, lower=1, + overwrite_b=True, + **solve_triangular_args) + v = np.dot(L[n_active, :n_active], L[n_active, :n_active]) diag = max(np.sqrt(np.abs(c - v)), eps) L[n_active, n_active] = diag + if diag < 1e-7: + # The system is becoming too ill-conditioned. + # We have degenerate vectors in our active set. + # We'll 'drop for good' the last regressor added. + + # Note: this case is very rare. It is no longer triggered by the + # test suite. The `equality_tolerance` margin added in 0.16.0 to + # get early stopping to work consistently on all versions of + # Python including 32 bit Python under Windows seems to make it + # very difficult to trigger the 'drop for good' strategy. + warnings.warn('Regressors in active set degenerate. ' + 'Dropping a regressor, after %i iterations, ' + 'i.e. alpha=%.3e, ' + 'with an active set of %i regressors, and ' + 'the smallest cholesky pivot element being %.3e' + % (n_iter, alpha, n_active, diag), + ConvergenceWarning) + # XXX: need to figure a 'drop for good' way + Cov = Cov_not_shortened + Cov[0] = 0 + Cov[C_idx], Cov[0] = swap(Cov[C_idx], Cov[0]) + continue + active.append(indices[n_active]) n_active += 1 if verbose > 1: - print "%s\t\t%s\t\t%s\t\t%s\t\t%s" % (n_iter, active[-1], '', - n_active, C) + print("%s\t\t%s\t\t%s\t\t%s\t\t%s" % (n_iter, active[-1], '', + n_active, C)) + + if method == 'lasso' and n_iter > 0 and prev_alpha[0] < alpha[0]: + # alpha is increasing. This is because the updates of Cov are + # bringing in too much numerical error that is greater than + # than the remaining correlation with the + # regressors. Time to bail out + warnings.warn('Early stopping the lars path, as the residues ' + 'are small and the current value of alpha is no ' + 'longer well controlled. %i iterations, alpha=%.3e, ' + 'previous alpha=%.3e, with an active set of %i ' + 'regressors.' + % (n_iter, alpha, prev_alpha, n_active), + ConvergenceWarning) + break + # least squares solution least_squares, info = solve_cholesky(L[:n_active, :n_active], - sign_active[:n_active], lower=True) - - # is this really needed ? - AA = 1. / np.sqrt(np.sum(least_squares * sign_active[:n_active])) - - if not np.isfinite(AA): - # L is too ill-conditionned - i = 0 - L_ = L[:n_active, :n_active].copy() - while not np.isfinite(AA): - L_.flat[::n_active + 1] += (2 ** i) * eps - least_squares, info = solve_cholesky(L_, - sign_active[:n_active], lower=True) - tmp = max(np.sum(least_squares * sign_active[:n_active]), eps) - AA = 1. / np.sqrt(tmp) - i += 1 - least_squares *= AA + sign_active[:n_active], + lower=True) + + if least_squares.size == 1 and least_squares == 0: + # This happens because sign_active[:n_active] = 0 + least_squares[...] = 1 + AA = 1. + else: + # is this really needed ? + AA = 1. / np.sqrt(np.sum(least_squares * sign_active[:n_active])) + + if not np.isfinite(AA): + # L is too ill-conditioned + i = 0 + L_ = L[:n_active, :n_active].copy() + while not np.isfinite(AA): + L_.flat[::n_active + 1] += (2 ** i) * eps + least_squares, info = solve_cholesky( + L_, sign_active[:n_active], lower=True) + tmp = max(np.sum(least_squares * sign_active[:n_active]), + eps) + AA = 1. / np.sqrt(tmp) + i += 1 + least_squares *= AA if Gram is None: # equiangular direction of variables in the active set @@ -264,7 +360,7 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, z_pos = arrayfuncs.min_pos(z) if z_pos < gamma_: # some coefficients have changed sign - idx = np.where(z == z_pos)[0] + idx = np.where(z == z_pos)[0][::-1] # update the sign, important for LAR sign_active[idx] = -sign_active[idx] @@ -280,8 +376,8 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, del coef, alpha, prev_alpha, prev_coef # resize the coefs and alphas array add_features = 2 * max(1, (max_features - n_active)) - coefs.resize((n_iter + add_features, n_features)) - alphas.resize(n_iter + add_features) + coefs = np.resize(coefs, (n_iter + add_features, n_features)) + alphas = np.resize(alphas, n_iter + add_features) coef = coefs[n_iter] prev_coef = coefs[n_iter - 1] alpha = alphas[n_iter, np.newaxis] @@ -300,18 +396,22 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, # See if any coefficient has changed sign if drop and method == 'lasso': - arrayfuncs.cholesky_delete(L[:n_active, :n_active], idx) + # handle the case when idx is not length of 1 + [arrayfuncs.cholesky_delete(L[:n_active, :n_active], ii) for ii in + idx] n_active -= 1 m, n = idx, n_active - drop_idx = active.pop(idx) + # handle the case when idx is not length of 1 + drop_idx = [active.pop(ii) for ii in idx] if Gram is None: # propagate dropped variable - for i in range(idx, n_active): - X.T[i], X.T[i + 1] = swap(X.T[i], X.T[i + 1]) - indices[i], indices[i + 1] = \ - indices[i + 1], indices[i] # yeah this is stupid + for ii in idx: + for i in range(ii, n_active): + X.T[i], X.T[i + 1] = swap(X.T[i], X.T[i + 1]) + # yeah this is stupid + indices[i], indices[i + 1] = indices[i + 1], indices[i] # TODO: this could be updated residual = y - np.dot(X[:, :n_active], coef[active]) @@ -319,12 +419,12 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, Cov = np.r_[temp, Cov] else: - for i in range(idx, n_active): - indices[i], indices[i + 1] = \ - indices[i + 1], indices[i] - Gram[i], Gram[i + 1] = swap(Gram[i], Gram[i + 1]) - Gram[:, i], Gram[:, i + 1] = swap(Gram[:, i], - Gram[:, i + 1]) + for ii in idx: + for i in range(ii, n_active): + indices[i], indices[i + 1] = indices[i + 1], indices[i] + Gram[i], Gram[i + 1] = swap(Gram[i], Gram[i + 1]) + Gram[:, i], Gram[:, i + 1] = swap(Gram[:, i], + Gram[:, i + 1]) # Cov_n = Cov_j + x_j * X + increment(betas) TODO: # will this still work with multiple drops ? @@ -340,17 +440,23 @@ def lars_path(X, y, Xy=None, Gram=None, max_iter=500, sign_active = np.delete(sign_active, idx) sign_active = np.append(sign_active, 0.) # just to maintain size if verbose > 1: - print "%s\t\t%s\t\t%s\t\t%s\t\t%s" % (n_iter, '', drop_idx, - n_active, abs(temp)) + print("%s\t\t%s\t\t%s\t\t%s\t\t%s" % (n_iter, '', drop_idx, + n_active, abs(temp))) if return_path: # resize coefs in case of early stop alphas = alphas[:n_iter + 1] coefs = coefs[:n_iter + 1] - return alphas, active, coefs.T + if return_n_iter: + return alphas, active, coefs.T, n_iter + else: + return alphas, active, coefs.T else: - return alpha, active, coef + if return_n_iter: + return alpha, active, coef, n_iter + else: + return alpha, active, coef ############################################################################### @@ -362,7 +468,7 @@ class Lars(LinearModel, RegressorMixin): Parameters ---------- n_nonzero_coefs : int, optional - Target number of non-zero coefficients. Use np.inf for no limit. + Target number of non-zero coefficients. Use ``np.inf`` for no limit. fit_intercept : boolean Whether to calculate the intercept for this model. If set @@ -372,43 +478,55 @@ class Lars(LinearModel, RegressorMixin): verbose : boolean or integer, optional Sets the verbosity amount - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default False + If ``True``, the regressors X will be normalized before regression. precompute : True | False | 'auto' | array-like Whether to use a precomputed Gram matrix to speed up - calculations. If set to 'auto' let us decide. The Gram + calculations. If set to ``'auto'`` let us decide. The Gram matrix can also be passed as argument. copy_X : boolean, optional, default True - If True, X will be copied; else, it may be overwritten. + If ``True``, X will be copied; else, it may be overwritten. - eps: float, optional + eps : float, optional The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned - systems. Unlike the 'tol' parameter in some iterative + systems. Unlike the ``tol`` parameter in some iterative optimization-based algorithms, this parameter does not control the tolerance of the optimization. fit_path : boolean - If True the full path is stored in the `coef_path_` attribute. + If True the full path is stored in the ``coef_path_`` attribute. If you compute the solution for a large problem or many targets, - setting fit_path to False will lead to a speedup, especially + setting ``fit_path`` to ``False`` will lead to a speedup, especially with a small alpha. Attributes ---------- - `coef_path_` : array, shape = [n_features, n_alpha] - The varying values of the coefficients along the path. It is not \ - present if the fit_path parameter is False. + alphas_ : array, shape (n_alphas + 1,) | list of n_targets such arrays + Maximum of covariances (in absolute value) at each iteration. \ + ``n_alphas`` is either ``n_nonzero_coefs`` or ``n_features``, \ + whichever is smaller. + + active_ : list, length = n_alphas | list of n_targets such lists + Indices of active variables at the end of the path. + coef_path_ : array, shape (n_features, n_alphas + 1) \ + | list of n_targets such arrays + The varying values of the coefficients along the path. It is not + present if the ``fit_path`` parameter is ``False``. - `coef_` : array, shape = [n_features] - Parameter vector (w in the fomulation formula). + coef_ : array, shape (n_features,) or (n_targets, n_features) + Parameter vector (w in the formulation formula). - `intercept_` : float + intercept_ : float | array, shape (n_targets,) Independent term in decision function. + n_iter_ : array-like or int + The number of iterations taken by lars_path to find the + grid of alphas for each target. + Examples -------- >>> from sklearn import linear_model @@ -425,7 +543,6 @@ class Lars(LinearModel, RegressorMixin): lars_path, LarsCV sklearn.decomposition.sparse_encode - http://en.wikipedia.org/wiki/Least_angle_regression """ def __init__(self, fit_intercept=True, verbose=False, normalize=True, precompute='auto', n_nonzero_coefs=500, @@ -456,13 +573,14 @@ def fit(self, X, y, Xy=None): parameters ---------- - X : array-like, shape = [n_samples, n_features] - training data. + X : array-like, shape (n_samples, n_features) + Training data. - y : array-like, shape = [n_samples] or [n_samples, n_targets] - target values. + y : array-like, shape (n_samples,) or (n_samples, n_targets) + Target values. - Xy : array-like, shape = [n_samples] or [n_samples, n_targets], optional + Xy : array-like, shape (n_samples,) or (n_samples, n_targets), \ + optional Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed. @@ -471,8 +589,7 @@ def fit(self, X, y, Xy=None): self : object returns an instance of self. """ - X = array2d(X) - y = np.asarray(y) + X, y = check_X_y(X, y, y_numeric=True, multi_output=True) n_features = X.shape[1] X, y, X_mean, y_mean, X_std = self._center_data(X, y, @@ -492,46 +609,55 @@ def fit(self, X, y, Xy=None): else: max_iter = self.max_iter - self.coef_ = np.zeros((n_targets, n_features)) - precompute = self.precompute - if not hasattr(precompute, '__array__') and (precompute == True or - (precompute == 'auto' and X.shape[0] > X.shape[1]) or - (precompute == 'auto' and y.shape[1] > 1)): + if not hasattr(precompute, '__array__') and ( + precompute is True or + (precompute == 'auto' and X.shape[0] > X.shape[1]) or + (precompute == 'auto' and y.shape[1] > 1)): Gram = np.dot(X.T, X) else: Gram = self._get_gram() + self.alphas_ = [] + self.n_iter_ = [] + if self.fit_path: - self.alphas_ = np.ones((n_targets, max_iter + 1)) - self.active_ = np.ones((n_targets, max_iter)) - self.coef_path_ = np.zeros((n_targets, n_features, max_iter + 1)) + self.coef_ = [] + self.active_ = [] + self.coef_path_ = [] for k in xrange(n_targets): this_Xy = None if Xy is None else Xy[:, k] - alphas, active, coef_path = lars_path( + alphas, active, coef_path, n_iter_ = lars_path( X, y[:, k], Gram=Gram, Xy=this_Xy, copy_X=self.copy_X, copy_Gram=True, alpha_min=alpha, method=self.method, verbose=max(0, self.verbose - 1), max_iter=max_iter, - eps=self.eps, return_path=True) - self.alphas_[k, :len(alphas)] = alphas - self.active_[k, :len(active)] = active - self.coef_path_[k, :, :coef_path.shape[1]] = coef_path - self.coef_[k, :] = coef_path[:, -1] - - self.alphas_, self.active_, self.coef_path_, self.coef_ = ( - np.squeeze(a) for a in (self.alphas_, self.active_, - self.coef_path_, self.coef_)) + eps=self.eps, return_path=True, + return_n_iter=True) + self.alphas_.append(alphas) + self.active_.append(active) + self.n_iter_.append(n_iter_) + self.coef_path_.append(coef_path) + self.coef_.append(coef_path[:, -1]) + + if n_targets == 1: + self.alphas_, self.active_, self.coef_path_, self.coef_ = [ + a[0] for a in (self.alphas_, self.active_, self.coef_path_, + self.coef_)] + self.n_iter_ = self.n_iter_[0] else: - self.alphas_ = np.empty(n_targets) + self.coef_ = np.empty((n_targets, n_features)) for k in xrange(n_targets): this_Xy = None if Xy is None else Xy[:, k] - self.alphas_[k], _, self.coef_[k, :] = lars_path( + alphas, _, self.coef_[k], n_iter_ = lars_path( X, y[:, k], Gram=Gram, Xy=this_Xy, copy_X=self.copy_X, copy_Gram=True, alpha_min=alpha, method=self.method, verbose=max(0, self.verbose - 1), max_iter=max_iter, - eps=self.eps, return_path=False) - self.alphas_, self.coef_ = (np.squeeze(a) for a in (self.alphas_, - self.coef_)) + eps=self.eps, return_path=False, return_n_iter=True) + self.alphas_.append(alphas) + self.n_iter_.append(n_iter_) + if n_targets == 1: + self.alphas_ = self.alphas_[0] + self.n_iter_ = self.n_iter_[0] self._set_intercept(X_mean, y_mean, X_std) return self @@ -547,6 +673,13 @@ class LassoLars(Lars): Parameters ---------- + alpha : float + Constant that multiplies the penalty term. Defaults to 1.0. + ``alpha = 0`` is equivalent to an ordinary least square, solved + by :class:`LinearRegression`. For numerical reasons, using + ``alpha = 0`` with the LassoLars object is not advised and you + should prefer the LinearRegression object. + fit_intercept : boolean whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations @@ -555,45 +688,59 @@ class LassoLars(Lars): verbose : boolean or integer, optional Sets the verbosity amount - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. copy_X : boolean, optional, default True If True, X will be copied; else, it may be overwritten. precompute : True | False | 'auto' | array-like Whether to use a precomputed Gram matrix to speed up - calculations. If set to 'auto' let us decide. The Gram + calculations. If set to ``'auto'`` let us decide. The Gram matrix can also be passed as argument. - max_iter: integer, optional + max_iter : integer, optional Maximum number of iterations to perform. - eps: float, optional + eps : float, optional The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned - systems. Unlike the 'tol' parameter in some iterative + systems. Unlike the ``tol`` parameter in some iterative optimization-based algorithms, this parameter does not control the tolerance of the optimization. fit_path : boolean - If True the full path is stored in the `coef_path_` attribute. + If ``True`` the full path is stored in the ``coef_path_`` attribute. If you compute the solution for a large problem or many targets, - setting fit_path to False will lead to a speedup, especially + setting ``fit_path`` to ``False`` will lead to a speedup, especially with a small alpha. Attributes ---------- - `coef_path_` : array, shape = [n_features, n_alpha] - The varying values of the coefficients along the path. It is not \ - present if fit_path parameter is False. + alphas_ : array, shape (n_alphas + 1,) | list of n_targets such arrays + Maximum of covariances (in absolute value) at each iteration. \ + ``n_alphas`` is either ``max_iter``, ``n_features``, or the number of \ + nodes in the path with correlation greater than ``alpha``, whichever \ + is smaller. + + active_ : list, length = n_alphas | list of n_targets such lists + Indices of active variables at the end of the path. + + coef_path_ : array, shape (n_features, n_alphas + 1) or list + If a list is passed it's expected to be one of n_targets such arrays. + The varying values of the coefficients along the path. It is not + present if the ``fit_path`` parameter is ``False``. - `coef_` : array, shape = [n_features] - Parameter vector (w in the fomulation formula). + coef_ : array, shape (n_features,) or (n_targets, n_features) + Parameter vector (w in the formulation formula). - `intercept_` : float + intercept_ : float | array, shape (n_targets,) Independent term in decision function. + n_iter_ : array-like or int. + The number of iterations taken by lars_path to find the + grid of alphas for each target. + Examples -------- >>> from sklearn import linear_model @@ -615,7 +762,6 @@ class LassoLars(Lars): LassoLarsCV sklearn.decomposition.sparse_encode - http://en.wikipedia.org/wiki/Least_angle_regression """ def __init__(self, alpha=1.0, fit_intercept=True, verbose=False, @@ -644,55 +790,56 @@ def _lars_path_residues(X_train, y_train, X_test, y_test, Gram=None, Parameters ----------- - X_train: array, shape (n_samples, n_features) + X_train : array, shape (n_samples, n_features) The data to fit the LARS on - y_train: array, shape (n_samples) + y_train : array, shape (n_samples) The target variable to fit LARS on - X_test: array, shape (n_samples, n_features) + X_test : array, shape (n_samples, n_features) The data to compute the residues on - y_test: array, shape (n_samples) + y_test : array, shape (n_samples) The target variable to compute the residues on - Gram: None, 'auto', array, shape: (n_features, n_features), optional - Precomputed Gram matrix (X' * X), if 'auto', the Gram + Gram : None, 'auto', array, shape: (n_features, n_features), optional + Precomputed Gram matrix (X' * X), if ``'auto'``, the Gram matrix is precomputed from the given X, if there are more samples than features - copy: boolean, optional + copy : boolean, optional Whether X_train, X_test, y_train and y_test should be copied; if False, they may be overwritten. - method: 'lar' | 'lasso' - Specifies the returned model. Select 'lar' for Least Angle - Regression, 'lasso' for the Lasso. - verbose: integer, optional + method : 'lar' | 'lasso' + Specifies the returned model. Select ``'lar'`` for Least Angle + Regression, ``'lasso'`` for the Lasso. + verbose : integer, optional Sets the amount of verbosity fit_intercept : boolean whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). - normalize : boolean, optional - If True, the regressors X are normalized - max_iter: integer, optional + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. + max_iter : integer, optional Maximum number of iterations to perform. - eps: float, optional - The machine-precision regularization in the computation of the + eps : float, optional + The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned - systems. Unlike the 'tol' parameter in some iterative + systems. Unlike the ``tol`` parameter in some iterative optimization-based algorithms, this parameter does not control the tolerance of the optimization. Returns -------- - alphas: array, shape: (max_features + 1,) - Maximum of covariances (in absolute value) at each - iteration. + alphas : array, shape (n_alphas,) + Maximum of covariances (in absolute value) at each iteration. + ``n_alphas`` is either ``max_iter`` or ``n_features``, whichever + is smaller. - active: array, shape (max_features,) + active : list Indices of active variables at the end of the path. - coefs: array, shape (n_features, max_features + 1) + coefs : array, shape (n_features, n_alphas) Coefficients along the path - residues: array, shape (n_features, max_features + 1) + residues : array, shape (n_alphas, n_samples) Residues of the prediction on the test data """ if copy: @@ -716,15 +863,13 @@ def _lars_path_residues(X_train, y_train, X_test, y_test, Gram=None, nonzeros = np.flatnonzero(norms) X_train[:, nonzeros] /= norms[nonzeros] - alphas, active, coefs = lars_path(X_train, y_train, Gram=Gram, - copy_X=False, copy_Gram=False, - method=method, verbose=max(0, verbose - 1), - max_iter=max_iter, eps=eps) + alphas, active, coefs = lars_path( + X_train, y_train, Gram=Gram, copy_X=False, copy_Gram=False, + method=method, verbose=max(0, verbose - 1), max_iter=max_iter, eps=eps) if normalize: coefs[nonzeros] /= norms[nonzeros][:, np.newaxis] - residues = np.array([(np.dot(X_test, coef) - y_test) - for coef in coefs.T]) - return alphas, active, coefs, residues + residues = np.dot(X_test, coefs) - y_test[:, np.newaxis] + return alphas, active, coefs, residues.T class LarsCV(Lars): @@ -740,22 +885,22 @@ class LarsCV(Lars): verbose : boolean or integer, optional Sets the verbosity amount - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. copy_X : boolean, optional, default True - If True, X will be copied; else, it may be overwritten. + If ``True``, X will be copied; else, it may be overwritten. precompute : True | False | 'auto' | array-like Whether to use a precomputed Gram matrix to speed up - calculations. If set to 'auto' let us decide. The Gram + calculations. If set to ``'auto'`` let us decide. The Gram matrix can also be passed as argument. max_iter: integer, optional Maximum number of iterations to perform. - cv : crossvalidation generator, optional - see sklearn.cross_validation module. If None is passed, default to + cv : cross-validation generator, optional + see :mod:`sklearn.cross_validation`. If ``None`` is passed, default to a 5-fold strategy max_n_alphas : integer, optional @@ -763,10 +908,10 @@ class LarsCV(Lars): residuals in the cross-validation n_jobs : integer, optional - Number of CPUs to use during the cross validation. If '-1', use + Number of CPUs to use during the cross validation. If ``-1``, use all the CPUs - eps: float, optional + eps : float, optional The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. @@ -774,27 +919,30 @@ class LarsCV(Lars): Attributes ---------- - `coef_` : array, shape = [n_features] - parameter vector (w in the fomulation formula) + coef_ : array, shape (n_features,) + parameter vector (w in the formulation formula) - `intercept_` : float + intercept_ : float independent term in decision function - `coef_path_`: array, shape = [n_features, n_alpha] + coef_path_ : array, shape (n_features, n_alphas) the varying values of the coefficients along the path - `alpha_`: float + alpha_ : float the estimated regularization parameter alpha - `alphas_`: array, shape = [n_alpha] + alphas_ : array, shape (n_alphas,) the different values of alpha along the path - `cv_alphas_`: array, shape = [n_cv_alphas] + cv_alphas_ : array, shape (n_cv_alphas,) all the values of alpha along the path for the different folds - `cv_mse_path_`: array, shape = [n_folds, n_cv_alphas] + cv_mse_path_ : array, shape (n_folds, n_cv_alphas) the mean square error on left-out for each fold along the path - (alpha values given by cv_alphas) + (alpha values given by ``cv_alphas``) + + n_iter_ : array-like or int + the number of iterations run by Lars with the optimal alpha. See also -------- @@ -823,10 +971,10 @@ def fit(self, X, y): Parameters ---------- - X : array-like, shape = [n_samples, n_features] + X : array-like, shape (n_samples, n_features) Training data. - y : array-like, shape = [n_samples] + y : array-like, shape (n_samples,) Target values. Returns @@ -835,7 +983,7 @@ def fit(self, X, y): returns an instance of self. """ self.fit_path = True - X = array2d(X) + X, y = check_X_y(X, y) # init cross-validation generator cv = check_cv(self.cv, X, y, classifier=False) @@ -843,15 +991,12 @@ def fit(self, X, y): Gram = 'auto' if self.precompute else None cv_paths = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)( - delayed(_lars_path_residues)(X[train], y[train], - X[test], y[test], Gram=Gram, - copy=False, method=self.method, - verbose=max(0, self.verbose - 1), - normalize=self.normalize, - fit_intercept=self.fit_intercept, - max_iter=self.max_iter, - eps=self.eps) - for train, test in cv) + delayed(_lars_path_residues)( + X[train], y[train], X[test], y[test], Gram=Gram, copy=False, + method=self.method, verbose=max(0, self.verbose - 1), + normalize=self.normalize, fit_intercept=self.fit_intercept, + max_iter=self.max_iter, eps=self.eps) + for train, test in cv) all_alphas = np.concatenate(list(zip(*cv_paths))[0]) # Unique also sorts all_alphas = np.unique(all_alphas) @@ -898,14 +1043,6 @@ def alpha(self): # impedance matching for the above Lars.fit (should not be documented) return self.alpha_ - @property - def cv_alphas(self): - warnings.warn("Use cv_alphas_. Using cv_alphas is deprecated" - "since version 0.12, and backward compatibility " - "won't be maintained from version 0.14 onward. ", - DeprecationWarning, stacklevel=2) - return self.cv_alphas_ - class LassoLarsCV(LarsCV): """Cross-validated Lasso, using the LARS algorithm @@ -924,18 +1061,18 @@ class LassoLarsCV(LarsCV): verbose : boolean or integer, optional Sets the verbosity amount - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. precompute : True | False | 'auto' | array-like Whether to use a precomputed Gram matrix to speed up - calculations. If set to 'auto' let us decide. The Gram + calculations. If set to ``'auto'`` let us decide. The Gram matrix can also be passed as argument. - max_iter: integer, optional + max_iter : integer, optional Maximum number of iterations to perform. - cv : crossvalidation generator, optional + cv : cross-validation generator, optional see sklearn.cross_validation module. If None is passed, default to a 5-fold strategy @@ -944,10 +1081,10 @@ class LassoLarsCV(LarsCV): residuals in the cross-validation n_jobs : integer, optional - Number of CPUs to use during the cross validation. If '-1', use + Number of CPUs to use during the cross validation. If ``-1``, use all the CPUs - eps: float, optional + eps : float, optional The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. @@ -957,33 +1094,36 @@ class LassoLarsCV(LarsCV): Attributes ---------- - `coef_` : array, shape = [n_features] - parameter vector (w in the fomulation formula) + coef_ : array, shape (n_features,) + parameter vector (w in the formulation formula) - `intercept_` : float + intercept_ : float independent term in decision function. - `coef_path_`: array, shape = [n_features, n_alpha] + coef_path_ : array, shape (n_features, n_alphas) the varying values of the coefficients along the path - `alpha_`: float + alpha_ : float the estimated regularization parameter alpha - `alphas_`: array, shape = [n_alpha] + alphas_ : array, shape (n_alphas,) the different values of alpha along the path - `cv_alphas_`: array, shape = [n_cv_alphas] + cv_alphas_ : array, shape (n_cv_alphas,) all the values of alpha along the path for the different folds - `cv_mse_path_`: array, shape = [n_folds, n_cv_alphas] + cv_mse_path_ : array, shape (n_folds, n_cv_alphas) the mean square error on left-out for each fold along the path - (alpha values given by cv_alphas) + (alpha values given by ``cv_alphas``) + + n_iter_ : array-like or int + the number of iterations run by Lars with the optimal alpha. Notes ----- The object solves the same problem as the LassoCV object. However, - unlike the LassoCV, it find the relevent alphas values by itself. + unlike the LassoCV, it find the relevant alphas values by itself. In general, because of this property, it will be more stable. However, it is more fragile to heavily multicollinear datasets. @@ -1014,7 +1154,7 @@ class LassoLarsIC(LassoLars): Parameters ---------- - criterion: 'bic' | 'aic' + criterion : 'bic' | 'aic' The type of criterion to use. fit_intercept : boolean @@ -1025,40 +1165,49 @@ class LassoLarsIC(LassoLars): verbose : boolean or integer, optional Sets the verbosity amount - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. copy_X : boolean, optional, default True If True, X will be copied; else, it may be overwritten. precompute : True | False | 'auto' | array-like Whether to use a precomputed Gram matrix to speed up - calculations. If set to 'auto' let us decide. The Gram + calculations. If set to ``'auto'`` let us decide. The Gram matrix can also be passed as argument. - max_iter: integer, optional + max_iter : integer, optional Maximum number of iterations to perform. Can be used for early stopping. - eps: float, optional + eps : float, optional The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned - systems. Unlike the 'tol' parameter in some iterative + systems. Unlike the ``tol`` parameter in some iterative optimization-based algorithms, this parameter does not control the tolerance of the optimization. Attributes ---------- - `coef_` : array, shape = [n_features] - parameter vector (w in the fomulation formula) + coef_ : array, shape (n_features,) + parameter vector (w in the formulation formula) - `intercept_` : float + intercept_ : float independent term in decision function. - `alpha_` : float + alpha_ : float the alpha parameter chosen by the information criterion + n_iter_ : int + number of iterations run by lars_path to find the grid of + alphas. + + criterion_ : array, shape (n_alphas,) + The value of the information criteria ('aic', 'bic') across all + alphas. The alpha which has the smallest information criteria + is chosen. + Examples -------- >>> from sklearn import linear_model @@ -1089,8 +1238,6 @@ class LassoLarsIC(LassoLars): def __init__(self, criterion='aic', fit_intercept=True, verbose=False, normalize=True, precompute='auto', max_iter=500, eps=np.finfo(np.float).eps, copy_X=True): - if criterion not in ['aic', 'bic']: - raise ValueError('criterion should be either bic or aic') self.criterion = criterion self.fit_intercept = fit_intercept self.max_iter = max_iter @@ -1103,36 +1250,35 @@ def __init__(self, criterion='aic', fit_intercept=True, verbose=False, def fit(self, X, y, copy_X=True): """Fit the model using X, y as training data. - parameters + Parameters ---------- - x : array-like, shape = [n_samples, n_features] + X : array-like, shape (n_samples, n_features) training data. - y : array-like, shape = [n_samples] + y : array-like, shape (n_samples,) target values. + + copy_X : boolean, optional, default True + If ``True``, X will be copied; else, it may be overwritten. - returns + Returns ------- self : object returns an instance of self. """ self.fit_path = True - X = array2d(X) - y = np.asarray(y) + X, y = check_X_y(X, y, multi_output=True, y_numeric=True) - X, y, Xmean, ymean, Xstd = LinearModel._center_data(X, y, - self.fit_intercept, - self.normalize, - self.copy_X) + X, y, Xmean, ymean, Xstd = LinearModel._center_data( + X, y, self.fit_intercept, self.normalize, self.copy_X) max_iter = self.max_iter Gram = self._get_gram() - alphas_, active_, coef_path_ = lars_path(X, y, - Gram=Gram, copy_X=copy_X, - copy_Gram=True, alpha_min=0.0, - method='lasso', verbose=self.verbose, - max_iter=max_iter, eps=self.eps) + alphas_, active_, coef_path_, self.n_iter_ = lars_path( + X, y, Gram=Gram, copy_X=copy_X, copy_Gram=True, alpha_min=0.0, + method='lasso', verbose=self.verbose, max_iter=max_iter, + eps=self.eps, return_n_iter=True) n_samples = X.shape[0] @@ -1157,7 +1303,8 @@ def fit(self, X, y, copy_X=True): df[k] = np.sum(mask) self.alphas_ = alphas_ - self.criterion_ = n_samples * np.log(mean_squared_error) + K * df + with np.errstate(divide='ignore'): + self.criterion_ = n_samples * np.log(mean_squared_error) + K * df n_best = np.argmin(self.criterion_) self.alpha_ = alphas_[n_best] diff --git a/sklearn/linear_model/logistic.py b/sklearn/linear_model/logistic.py index 0a709cd1141fc..f47d77023f7d7 100644 --- a/sklearn/linear_model/logistic.py +++ b/sklearn/linear_model/logistic.py @@ -1,40 +1,892 @@ +""" +Logistic Regression +""" + +# Author: Gael Varoquaux +# Fabian Pedregosa +# Alexandre Gramfort +# Manoj Kumar +# Lars Buitinck +# Simon Wu + +import numbers +import warnings + import numpy as np +from scipy import optimize, sparse + +from .base import LinearClassifierMixin, SparseCoefMixin, BaseEstimator +from ..feature_selection.from_model import _LearntSelectorMixin +from ..preprocessing import LabelEncoder, LabelBinarizer +from ..svm.base import _fit_liblinear +from ..utils import check_array, check_consistent_length, compute_class_weight +from ..utils.extmath import (logsumexp, log_logistic, safe_sparse_dot, + squared_norm) +from ..utils.optimize import newton_cg +from ..utils.validation import (as_float_array, DataConversionWarning, + check_X_y) +from ..utils.fixes import expit +from ..externals.joblib import Parallel, delayed +from ..cross_validation import _check_cv +from ..externals import six +from ..metrics import SCORERS + + +# .. some helper functions for logistic_regression_path .. +def _intercept_dot(w, X, y): + """Computes y * np.dot(X, w). + + It takes into consideration if the intercept should be fit or not. + + Parameters + ---------- + w : ndarray, shape (n_features,) or (n_features + 1,) + Coefficient vector. + + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + y : ndarray, shape (n_samples,) + Array of labels. + """ + c = 0. + if w.size == X.shape[1] + 1: + c = w[-1] + w = w[:-1] + + z = safe_sparse_dot(X, w) + c + return w, c, y * z + + +def _logistic_loss_and_grad(w, X, y, alpha, sample_weight=None): + """Computes the logistic loss and gradient. + + Parameters + ---------- + w : ndarray, shape (n_features,) or (n_features + 1,) + Coefficient vector. + + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + y : ndarray, shape (n_samples,) + Array of labels. + + alpha : float + Regularization parameter. alpha is equal to 1 / C. + + sample_weight : ndarray, shape (n_samples,) optional + Array of weights that are assigned to individual samples. + If not provided, then each sample is given unit weight. + + Returns + ------- + out : float + Logistic loss. + + grad : ndarray, shape (n_features,) or (n_features + 1,) + Logistic gradient. + """ + _, n_features = X.shape + grad = np.empty_like(w) + + w, c, yz = _intercept_dot(w, X, y) + + if sample_weight is None: + sample_weight = np.ones(y.shape[0]) + + # Logistic loss is the negative of the log of the logistic function. + out = -np.sum(sample_weight * log_logistic(yz)) + .5 * alpha * np.dot(w, w) + + z = expit(yz) + z0 = sample_weight * (z - 1) * y + + grad[:n_features] = safe_sparse_dot(X.T, z0) + alpha * w + + # Case where we fit the intercept. + if grad.shape[0] > n_features: + grad[-1] = z0.sum() + return out, grad + + +def _logistic_loss(w, X, y, alpha, sample_weight=None): + """Computes the logistic loss. + + Parameters + ---------- + w : ndarray, shape (n_features,) or (n_features + 1,) + Coefficient vector. + + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + y : ndarray, shape (n_samples,) + Array of labels. + + alpha : float + Regularization parameter. alpha is equal to 1 / C. + + sample_weight : ndarray, shape (n_samples,) optional + Array of weights that are assigned to individual samples. + If not provided, then each sample is given unit weight. + + Returns + ------- + out : float + Logistic loss. + """ + w, c, yz = _intercept_dot(w, X, y) + + if sample_weight is None: + sample_weight = np.ones(y.shape[0]) + + # Logistic loss is the negative of the log of the logistic function. + out = -np.sum(sample_weight * log_logistic(yz)) + .5 * alpha * np.dot(w, w) + return out + + +def _logistic_loss_grad_hess(w, X, y, alpha, sample_weight=None): + """Computes the logistic loss, gradient and the Hessian. + + Parameters + ---------- + w : ndarray, shape (n_features,) or (n_features + 1,) + Coefficient vector. + + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + y : ndarray, shape (n_samples,) + Array of labels. + + alpha : float + Regularization parameter. alpha is equal to 1 / C. + + sample_weight : ndarray, shape (n_samples,) optional + Array of weights that are assigned to individual samples. + If not provided, then each sample is given unit weight. + + Returns + ------- + out : float + Logistic loss. + + grad : ndarray, shape (n_features,) or (n_features + 1,) + Logistic gradient. + + Hs : callable + Function that takes the gradient as a parameter and returns the + matrix product of the Hessian and gradient. + """ + n_samples, n_features = X.shape + grad = np.empty_like(w) + fit_intercept = grad.shape[0] > n_features + + w, c, yz = _intercept_dot(w, X, y) + + if sample_weight is None: + sample_weight = np.ones(y.shape[0]) + + # Logistic loss is the negative of the log of the logistic function. + out = -np.sum(sample_weight * log_logistic(yz)) + .5 * alpha * np.dot(w, w) + + z = expit(yz) + z0 = sample_weight * (z - 1) * y + + grad[:n_features] = safe_sparse_dot(X.T, z0) + alpha * w + + # Case where we fit the intercept. + if fit_intercept: + grad[-1] = z0.sum() + + # The mat-vec product of the Hessian + d = sample_weight * z * (1 - z) + if sparse.issparse(X): + dX = safe_sparse_dot(sparse.dia_matrix((d, 0), + shape=(n_samples, n_samples)), X) + else: + # Precompute as much as possible + dX = d[:, np.newaxis] * X + + if fit_intercept: + # Calculate the double derivative with respect to intercept + # In the case of sparse matrices this returns a matrix object. + dd_intercept = np.squeeze(np.array(dX.sum(axis=0))) + + def Hs(s): + ret = np.empty_like(s) + ret[:n_features] = X.T.dot(dX.dot(s[:n_features])) + ret[:n_features] += alpha * s[:n_features] + + # For the fit intercept case. + if fit_intercept: + ret[:n_features] += s[-1] * dd_intercept + ret[-1] = dd_intercept.dot(s[:n_features]) + ret[-1] += d.sum() * s[-1] + return ret + + return out, grad, Hs + + +def _multinomial_loss(w, X, Y, alpha, sample_weight): + """Computes multinomial loss and class probabilities. + + Parameters + ---------- + w : ndarray, shape (n_classes * n_features,) or (n_classes * (n_features + 1),) + Coefficient vector. + + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + Y : ndarray, shape (n_samples, n_classes) + Transformed labels according to the output of LabelBinarizer. + + alpha : float + Regularization parameter. alpha is equal to 1 / C. + + sample_weight : ndarray, shape (n_samples,) optional + Array of weights that are assigned to individual samples. + If not provided, then each sample is given unit weight. + + Returns + ------- + loss : float + Multinomial loss. + + p : ndarray, shape (n_samples, n_classes) + Estimated class probabilities. + + w : ndarray, shape (n_classes, n_features) + Reshaped param vector excluding intercept terms. + """ + n_classes = Y.shape[1] + n_features = X.shape[1] + fit_intercept = w.size == (n_classes * (n_features + 1)) + w = w.reshape(n_classes, -1) + sample_weight = sample_weight[:, np.newaxis] + if fit_intercept: + intercept = w[:, -1] + w = w[:, :-1] + else: + intercept = 0 + p = safe_sparse_dot(X, w.T) + p += intercept + p -= logsumexp(p, axis=1)[:, np.newaxis] + loss = -(sample_weight * Y * p).sum() + loss += 0.5 * alpha * squared_norm(w) + p = np.exp(p, p) + return loss, p, w + + +def _multinomial_loss_grad(w, X, Y, alpha, sample_weight): + """Computes the multinomial loss, gradient and class probabilities. + + Parameters + ---------- + w : ndarray, shape (n_classes * n_features,) or (n_classes * (n_features + 1),) + Coefficient vector. + + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + Y : ndarray, shape (n_samples, n_classes) + Transformed labels according to the output of LabelBinarizer. + + alpha : float + Regularization parameter. alpha is equal to 1 / C. + + sample_weight : ndarray, shape (n_samples,) optional + Array of weights that are assigned to individual samples. + + Returns + ------- + loss : float + Multinomial loss. + + grad : ndarray, shape (n_classes * n_features,) or + (n_classes * (n_features + 1),) + Ravelled gradient of the multinomial loss. + + p : ndarray, shape (n_samples, n_classes) + Estimated class probabilities + """ + n_classes = Y.shape[1] + n_features = X.shape[1] + fit_intercept = (w.size == n_classes * (n_features + 1)) + grad = np.zeros((n_classes, n_features + bool(fit_intercept))) + loss, p, w = _multinomial_loss(w, X, Y, alpha, sample_weight) + sample_weight = sample_weight[:, np.newaxis] + diff = sample_weight * (p - Y) + grad[:, :n_features] = safe_sparse_dot(diff.T, X) + grad[:, :n_features] += alpha * w + if fit_intercept: + grad[:, -1] = diff.sum(axis=0) + return loss, grad.ravel(), p + + +def _multinomial_loss_grad_hess(w, X, Y, alpha, sample_weight): + """ + Provides multinomial loss, gradient, and a function for computing hessian + vector product. + + Parameters + ---------- + w : ndarray, shape (n_classes * n_features,) or (n_classes * (n_features + 1),) + Coefficient vector. + + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + Y : ndarray, shape (n_samples, n_classes) + Transformed labels according to the output of LabelBinarizer. + + alpha : float + Regularization parameter. alpha is equal to 1 / C. + + sample_weight : ndarray, shape (n_samples,) optional + Array of weights that are assigned to individual samples. + + Returns + ------- + loss : float + Multinomial loss. + + grad : array, shape (n_classes * n_features,) or + (n_classes * (n_features + 1),) + Ravelled gradient of the multinomial loss. + + hessp : callable + Function that takes in a vector input of shape (n_classes * n_features) + or (n_classes * (n_features + 1)) and returns matrix-vector product + with hessian. + + References + ---------- + Barak A. Pearlmutter (1993). Fast Exact Multiplication by the Hessian. + http://www.bcl.hamilton.ie/~barak/papers/nc-hessian.pdf + """ + n_features = X.shape[1] + n_classes = Y.shape[1] + fit_intercept = w.size == (n_classes * (n_features + 1)) + loss, grad, p = _multinomial_loss_grad(w, X, Y, alpha, sample_weight) + sample_weight = sample_weight[:, np.newaxis] + + # Hessian-vector product derived by applying the R-operator on the gradient + # of the multinomial loss function. + def hessp(v): + v = v.reshape(n_classes, -1) + if fit_intercept: + inter_terms = v[:, -1] + v = v[:, :-1] + else: + inter_terms = 0 + # r_yhat holds the result of applying the R-operator on the multinomial + # estimator. + r_yhat = safe_sparse_dot(X, v.T) + r_yhat += inter_terms + r_yhat += (-p * r_yhat).sum(axis=1)[:, np.newaxis] + r_yhat *= p + r_yhat *= sample_weight + hessProd = np.zeros((n_classes, n_features + bool(fit_intercept))) + hessProd[:, :n_features] = safe_sparse_dot(r_yhat.T, X) + hessProd[:, :n_features] += v * alpha + if fit_intercept: + hessProd[:, -1] = r_yhat.sum(axis=0) + return hessProd.ravel() + + return loss, grad, hessp + + +def logistic_regression_path(X, y, pos_class=None, Cs=10, fit_intercept=True, + max_iter=100, tol=1e-4, verbose=0, + solver='lbfgs', coef=None, copy=True, + class_weight=None, dual=False, penalty='l2', + intercept_scaling=1., multi_class='ovr'): + """Compute a Logistic Regression model for a list of regularization + parameters. + + This is an implementation that uses the result of the previous model + to speed up computations along the set of solutions, making it faster + than sequentially calling LogisticRegression for the different parameters. + + Parameters + ---------- + X : array-like or sparse matrix, shape (n_samples, n_features) + Input data. + + y : array-like, shape (n_samples,) + Input data, target values. + + Cs : int | array-like, shape (n_cs,) + List of values for the regularization parameter or integer specifying + the number of regularization parameters that should be used. In this + case, the parameters will be chosen in a logarithmic scale between + 1e-4 and 1e4. + + pos_class : int, None + The class with respect to which we perform a one-vs-all fit. + If None, then it is assumed that the given problem is binary. + + fit_intercept : bool + Whether to fit an intercept for the model. In this case the shape of + the returned array is (n_cs, n_features + 1). + + max_iter : int + Maximum number of iterations for the solver. + + tol : float + Stopping criterion. For the newton-cg and lbfgs solvers, the iteration + will stop when ``max{|g_i | i = 1, ..., n} <= tol`` + where ``g_i`` is the i-th component of the gradient. + + verbose : int + For the liblinear and lbfgs solvers set verbose to any positive + number for verbosity. + + solver : {'lbfgs', 'newton-cg', 'liblinear'} + Numerical solver to use. + + coef : array-like, shape (n_features,), default None + Initialization value for coefficients of logistic regression. + + copy : bool, default True + Whether or not to produce a copy of the data. Setting this to + True will be useful in cases, when logistic_regression_path + is called repeatedly with the same data, as y is modified + along the path. + + class_weight : {dict, 'auto'}, optional + Over-/undersamples the samples of each class according to the given + weights. If not given, all classes are supposed to have weight one. + The 'auto' mode selects weights inversely proportional to class + frequencies in the training set. + + dual : bool + Dual or primal formulation. Dual formulation is only implemented for + l2 penalty with liblinear solver. Prefer dual=False when + n_samples > n_features. + + penalty : str, 'l1' or 'l2' + Used to specify the norm used in the penalization. The newton-cg and + lbfgs solvers support only l2 penalties. + + intercept_scaling : float, default 1. + This parameter is useful only when the solver 'liblinear' is used + and self.fit_intercept is set to True. In this case, x becomes + [x, self.intercept_scaling], + i.e. a "synthetic" feature with constant value equals to + intercept_scaling is appended to the instance vector. + The intercept becomes intercept_scaling * synthetic feature weight + Note! the synthetic feature weight is subject to l1/l2 regularization + as all other features. + To lessen the effect of regularization on synthetic feature weight + (and therefore on the intercept) intercept_scaling has to be increased. + + multi_class : str, {'ovr', 'multinomial'} + Multiclass option can be either 'ovr' or 'multinomial'. If the option + chosen is 'ovr', then a binary problem is fit for each label. Else + the loss minimised is the multinomial loss fit across + the entire probability distribution. Works only for the 'lbfgs' + solver. + + Returns + ------- + coefs : ndarray, shape (n_cs, n_features) or (n_cs, n_features + 1) + List of coefficients for the Logistic Regression model. If + fit_intercept is set to True then the second dimension will be + n_features + 1, where the last item represents the intercept. + + Cs : ndarray + Grid of Cs used for cross-validation. + + Notes + ----- + You might get slighly different results with the solver liblinear than + with the others since this uses LIBLINEAR which penalizes the intercept. + """ + if isinstance(Cs, numbers.Integral): + Cs = np.logspace(-4, 4, Cs) + + if multi_class not in ['multinomial', 'ovr']: + raise ValueError("multi_class can be either 'multinomial' or 'ovr'" + "got %s" % multi_class) + + if solver not in ['liblinear', 'newton-cg', 'lbfgs']: + raise ValueError("Logistic Regression supports only liblinear," + " newton-cg and lbfgs solvers. got %s" % solver) + + if multi_class == 'multinomial' and solver == 'liblinear': + raise ValueError("Solver %s cannot solve problems with " + "a multinomial backend." % solver) + + if solver != 'liblinear': + if penalty != 'l2': + raise ValueError("newton-cg and lbfgs solvers support only " + "l2 penalties, got %s penalty." % penalty) + if dual: + raise ValueError("newton-cg and lbfgs solvers support only " + "dual=False, got dual=%s" % dual) + # Preprocessing. + X = check_array(X, accept_sparse='csr', dtype=np.float64) + y = check_array(y, ensure_2d=False, copy=copy, dtype=None) + _, n_features = X.shape + check_consistent_length(X, y) + classes = np.unique(y) + + if pos_class is None and multi_class != 'multinomial': + if (classes.size > 2): + raise ValueError('To fit OvR, use the pos_class argument') + # np.unique(y) gives labels in sorted order. + pos_class = classes[1] + + # If class_weights is a dict (provided by the user), the weights + # are assigned to the original labels. If it is "auto", then + # the class_weights are assigned after masking the labels with a OvR. + sample_weight = np.ones(X.shape[0]) + le = LabelEncoder() + + if isinstance(class_weight, dict): + if solver == "liblinear": + if classes.size == 2: + # Reconstruct the weights with keys 1 and -1 + temp = {1: class_weight[pos_class], + -1: class_weight[classes[0]]} + class_weight = temp.copy() + else: + raise ValueError("In LogisticRegressionCV the liblinear " + "solver cannot handle multiclass with " + "class_weight of type dict. Use the lbfgs, " + "newton-cg solvers or set " + "class_weight='auto'") + else: + class_weight_ = compute_class_weight(class_weight, classes, y) + sample_weight = class_weight_[le.fit_transform(y)] + + # For doing a ovr, we need to mask the labels first. for the + # multinomial case this is not necessary. + if multi_class == 'ovr': + w0 = np.zeros(n_features + int(fit_intercept)) + mask_classes = [-1, 1] + mask = (y == pos_class) + y[mask] = 1 + y[~mask] = -1 + # To take care of object dtypes, i.e 1 and -1 are in the form of + # strings. + y = as_float_array(y, copy=False) + + else: + lbin = LabelBinarizer() + Y_bin = lbin.fit_transform(y) + if Y_bin.shape[1] == 1: + Y_bin = np.hstack([1 - Y_bin, Y_bin]) + w0 = np.zeros((Y_bin.shape[1], n_features + int(fit_intercept)), + order='F') + mask_classes = classes + + if class_weight == "auto": + class_weight_ = compute_class_weight(class_weight, mask_classes, y) + sample_weight = class_weight_[le.fit_transform(y)] + + if coef is not None: + # it must work both giving the bias term and not + if multi_class == 'ovr': + if coef.size not in (n_features, w0.size): + raise ValueError( + 'Initialization coef is of shape %d, expected shape ' + '%d or %d' % (coef.size, n_features, w0.size) + ) + w0[:coef.size] = coef + else: + # For binary problems coef.shape[0] should be 1, otherwise it + # should be classes.size. + n_vectors = classes.size + if n_vectors == 2: + n_vectors = 1 + + if (coef.shape[0] != n_vectors or + coef.shape[1] not in (n_features, n_features + 1)): + raise ValueError( + 'Initialization coef is of shape (%d, %d), expected ' + 'shape (%d, %d) or (%d, %d)' % ( + coef.shape[0], coef.shape[1], classes.size, + n_features, classes.size, n_features + 1 + ) + ) + w0[:, :coef.shape[1]] = coef + + if multi_class == 'multinomial': + # fmin_l_bfgs_b and newton-cg accepts only ravelled parameters. + w0 = w0.ravel() + target = Y_bin + if solver == 'lbfgs': + func = lambda x, *args: _multinomial_loss_grad(x, *args)[0:2] + elif solver == 'newton-cg': + func = lambda x, *args: _multinomial_loss(x, *args)[0] + grad = lambda x, *args: _multinomial_loss_grad(x, *args)[1] + hess = _multinomial_loss_grad_hess + else: + target = y + if solver == 'lbfgs': + func = _logistic_loss_and_grad + elif solver == 'newton-cg': + func = _logistic_loss + grad = lambda x, *args: _logistic_loss_and_grad(x, *args)[1] + hess = _logistic_loss_grad_hess + + coefs = list() + + for C in Cs: + if solver == 'lbfgs': + try: + w0, loss, info = optimize.fmin_l_bfgs_b( + func, w0, fprime=None, + args=(X, target, 1. / C, sample_weight), + iprint=(verbose > 0) - 1, pgtol=tol, maxiter=max_iter + ) + except TypeError: + # old scipy doesn't have maxiter + w0, loss, info = optimize.fmin_l_bfgs_b( + func, w0, fprime=None, + args=(X, target, 1. / C, sample_weight), + iprint=(verbose > 0) - 1, pgtol=tol + ) + if info["warnflag"] == 1 and verbose > 0: + warnings.warn("lbfgs failed to converge. Increase the number " + "of iterations.") + elif solver == 'newton-cg': + args = (X, target, 1. / C, sample_weight) + w0 = newton_cg(hess, func, grad, w0, args=args, maxiter=max_iter, + tol=tol) + elif solver == 'liblinear': + coef_, intercept_, _, = _fit_liblinear( + X, y, C, fit_intercept, intercept_scaling, class_weight, + penalty, dual, verbose, max_iter, tol, + ) + if fit_intercept: + w0 = np.concatenate([coef_.ravel(), intercept_]) + else: + w0 = coef_.ravel() + else: + raise ValueError("solver must be one of {'liblinear', 'lbfgs', " + "'newton-cg'}, got '%s' instead" % solver) + + if multi_class == 'multinomial': + multi_w0 = np.reshape(w0, (classes.size, -1)) + if classes.size == 2: + multi_w0 = multi_w0[1][np.newaxis, :] + coefs.append(multi_w0) + else: + coefs.append(w0) + return coefs, np.array(Cs) + + +# helper function for LogisticCV +def _log_reg_scoring_path(X, y, train, test, pos_class=None, Cs=10, + scoring=None, fit_intercept=False, + max_iter=100, tol=1e-4, class_weight=None, + verbose=0, solver='lbfgs', penalty='l2', + dual=False, copy=True, intercept_scaling=1., + multi_class='ovr'): + """Computes scores across logistic_regression_path + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + y : array-like, shape (n_samples,) or (n_samples, n_targets) + Target labels. + + train : list of indices + The indices of the train set. + + test : list of indices + The indices of the test set. + + pos_class : int, None + The class with respect to which we perform a one-vs-all fit. + If None, then it is assumed that the given problem is binary. + + Cs : list of floats | int + Each of the values in Cs describes the inverse of + regularization strength. If Cs is as an int, then a grid of Cs + values are chosen in a logarithmic scale between 1e-4 and 1e4. + If not provided, then a fixed set of values for Cs are used. -from .base import LinearClassifierMixin -from ..feature_selection.selector_mixin import SelectorMixin -from ..svm.base import BaseLibLinear + scoring : callable + For a list of scoring functions that can be used, look at + :mod:`sklearn.metrics`. The default scoring option used is + accuracy_score. + fit_intercept : bool + If False, then the bias term is set to zero. Else the last + term of each coef_ gives us the intercept. + + max_iter : int + Maximum number of iterations for the solver. + + tol : float + Tolerance for stopping criteria. + + class_weight : {dict, 'auto'}, optional + Over-/undersamples the samples of each class according to the given + weights. If not given, all classes are supposed to have weight one. + The 'auto' mode selects weights inversely proportional to class + frequencies in the training set. + + verbose : int + For the liblinear and lbfgs solvers set verbose to any positive + number for verbosity. + + solver : {'lbfgs', 'newton-cg', 'liblinear'} + Decides which solver to use. + + penalty : str, 'l1' or 'l2' + Used to specify the norm used in the penalization. The newton-cg and + lbfgs solvers support only l2 penalties. + + dual : bool + Dual or primal formulation. Dual formulation is only implemented for + l2 penalty with liblinear solver. Prefer dual=False when + n_samples > n_features. + + intercept_scaling : float, default 1. + This parameter is useful only when the solver 'liblinear' is used + and self.fit_intercept is set to True. In this case, x becomes + [x, self.intercept_scaling], + i.e. a "synthetic" feature with constant value equals to + intercept_scaling is appended to the instance vector. + The intercept becomes intercept_scaling * synthetic feature weight + Note! the synthetic feature weight is subject to l1/l2 regularization + as all other features. + To lessen the effect of regularization on synthetic feature weight + (and therefore on the intercept) intercept_scaling has to be increased. + + multi_class : str, {'ovr', 'multinomial'} + Multiclass option can be either 'ovr' or 'multinomial'. If the option + chosen is 'ovr', then a binary problem is fit for each label. Else + the loss minimised is the multinomial loss fit across + the entire probability distribution. Works only for the 'lbfgs' + solver. + + copy : bool, default True + Whether or not to produce a copy of the data. Setting this to + True will be useful in cases, when ``_log_reg_scoring_path`` is called + repeatedly with the same data, as y is modified along the path. + + Returns + ------- + coefs : ndarray, shape (n_cs, n_features) or (n_cs, n_features + 1) + List of coefficients for the Logistic Regression model. If + fit_intercept is set to True then the second dimension will be + n_features + 1, where the last item represents the intercept. + + Cs : ndarray + Grid of Cs used for cross-validation. + + scores : ndarray, shape (n_cs,) + Scores obtained for each Cs. + """ + + log_reg = LogisticRegression(fit_intercept=fit_intercept) + + X_train = X[train] + X_test = X[test] + y_train = y[train] + y_test = y[test] + + # The score method of Logistic Regression has a classes_ attribute. + if multi_class == 'ovr': + log_reg.classes_ = np.array([-1, 1]) + elif multi_class == 'multinomial': + log_reg.classes_ = np.unique(y_train) + else: + raise ValueError("multi_class should be either multinomial or ovr, " + "got %d" % multi_class) + + if pos_class is not None: + mask = (y_test == pos_class) + y_test[mask] = 1 + y_test[~mask] = -1 + + # To deal with object dtypes, we need to convert into an array of floats. + y_test = as_float_array(y_test, copy=False) + + coefs, Cs = logistic_regression_path(X_train, y_train, Cs=Cs, + fit_intercept=fit_intercept, + solver=solver, + max_iter=max_iter, + class_weight=class_weight, + copy=copy, pos_class=pos_class, + multi_class=multi_class, + tol=tol, verbose=verbose, + dual=dual, penalty=penalty, + intercept_scaling=intercept_scaling) + + scores = list() + + if isinstance(scoring, six.string_types): + scoring = SCORERS[scoring] + for w in coefs: + if multi_class == 'ovr': + w = w[np.newaxis, :] + if fit_intercept: + log_reg.coef_ = w[:, :-1] + log_reg.intercept_ = w[:, -1] + else: + log_reg.coef_ = w + log_reg.intercept_ = 0. -class LogisticRegression(BaseLibLinear, LinearClassifierMixin, SelectorMixin): + if scoring is None: + scores.append(log_reg.score(X_test, y_test)) + else: + scores.append(scoring(log_reg, X_test, y_test)) + return coefs, Cs, np.array(scores) + + +class LogisticRegression(BaseEstimator, LinearClassifierMixin, + _LearntSelectorMixin, SparseCoefMixin): """Logistic Regression (aka logit, MaxEnt) classifier. - In the multiclass case, the training algorithm uses a one-vs.-all (OvA) - scheme, rather than the "true" multinomial LR. + In the multiclass case, the training algorithm uses the one-vs-rest (OvR) + scheme if the 'multi_class' option is set to 'ovr' and uses the + cross-entropy loss, if the 'multi_class' option is set to 'multinomial'. + (Currently the 'multinomial' option is supported only by the 'lbfgs' and + 'newton-cg' solvers.) - This class implements L1 and L2 regularized logistic regression using the - `liblinear` library. It can handle both dense and sparse input. Use - C-ordered arrays or CSR matrices containing 64-bit floats for optimal - performance; any other input format will be converted (and copied). + This class implements regularized logistic regression using the + `liblinear` library, newton-cg and lbfgs solvers. It can handle both + dense and sparse input. Use C-ordered arrays or CSR matrices containing + 64-bit floats for optimal performance; any other input format will be + converted (and copied). + + The newton-cg and lbfgs solvers support only L2 regularization with primal + formulation. The liblinear solver supports both L1 and L2 regularization, + with a dual formulation only for the L2 penalty. Parameters ---------- - penalty : string, 'l1' or 'l2' - Used to specify the norm used in the penalization + penalty : str, 'l1' or 'l2' + Used to specify the norm used in the penalization. The newton-cg and + lbfgs solvers support only l2 penalties. - dual : boolean - Dual or primal formulation. Dual formulation is only - implemented for l2 penalty. Prefer dual=False when + dual : bool + Dual or primal formulation. Dual formulation is only implemented for + l2 penalty with liblinear solver. Prefer dual=False when n_samples > n_features. C : float, optional (default=1.0) - Specifies the strength of the regularization. The smaller it is - the bigger is the regularization. + Inverse of regularization strength; must be a positive float. + Like in support vector machines, smaller values specify stronger + regularization. fit_intercept : bool, default: True Specifies if a constant (a.k.a. bias or intercept) should be - added the decision function + added the decision function. intercept_scaling : float, default: 1 + Useful only if solver is liblinear. when self.fit_intercept is True, instance vector x becomes [x, self.intercept_scaling], i.e. a "synthetic" feature with constant value equals to @@ -43,33 +895,57 @@ class LogisticRegression(BaseLibLinear, LinearClassifierMixin, SelectorMixin): Note! the synthetic feature weight is subject to l1/l2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight - (and therefore on the intercept) intercept_scaling has to be increased + (and therefore on the intercept) intercept_scaling has to be increased. class_weight : {dict, 'auto'}, optional - Set the parameter C of class i to class_weight[i]*C for - SVC. If not given, all classes are supposed to have - weight one. The 'auto' mode uses the values of y to - automatically adjust weights inversely proportional to - class frequencies. + Over-/undersamples the samples of each class according to the given + weights. If not given, all classes are supposed to have weight one. + The 'auto' mode selects weights inversely proportional to class + frequencies in the training set. + + max_iter : int + Useful only for the newton-cg and lbfgs solvers. Maximum number of + iterations taken for the solvers to converge. + + random_state : int seed, RandomState instance, or None (default) + The seed of the pseudo random number generator to use when + shuffling the data. - tol: float, optional - tolerance for stopping criteria + solver : {'newton-cg', 'lbfgs', 'liblinear'} + Algorithm to use in the optimization problem. + + tol : float, optional + Tolerance for stopping criteria. + + multi_class : str, {'ovr', 'multinomial'} + Multiclass option can be either 'ovr' or 'multinomial'. If the option + chosen is 'ovr', then a binary problem is fit for each label. Else + the loss minimised is the multinomial loss fit across + the entire probability distribution. Works only for the 'lbfgs' + solver. + + verbose : int + For the liblinear and lbfgs solvers set verbose to any positive + number for verbosity. Attributes ---------- - `coef_` : array, shape = [n_classes-1, n_features] + coef_ : array, shape (n_classes, n_features) Coefficient of the features in the decision function. - `coef_` is readonly property derived from `raw_coef_` that \ - follows the internal memory layout of liblinear. + intercept_ : array, shape (n_classes,) + Intercept (a.k.a. bias) added to the decision function. + If `fit_intercept` is set to False, the intercept is set to zero. - `intercept_` : array, shape = [n_classes-1] - intercept (a.k.a. bias) added to the decision function. - It is available only when parameter intercept is set to True + n_iter_ : int + Maximum of the actual number of iterations across all classes. + Valid only for the liblinear solver. See also -------- - LinearSVC + SGDClassifier : incrementally trained logistic regression (when given + the parameter ``loss="log"``). + sklearn.svm.LinearSVC : learns SVM models using the same algorithm. Notes ----- @@ -78,7 +954,12 @@ class frequencies. to have slightly different results for the same input data. If that happens, try with a smaller tol parameter. - References: + Predict output may not match that of standalone liblinear in certain + cases. See :ref:`differences from liblinear ` + in the narrative documentation. + + References + ---------- LIBLINEAR -- A Library for Large Linear Classification http://www.csie.ntu.edu.tw/~cjlin/liblinear/ @@ -87,14 +968,113 @@ class frequencies. methods for logistic regression and maximum entropy models. Machine Learning 85(1-2):41-75. http://www.csie.ntu.edu.tw/~cjlin/papers/maxent_dual.pdf + + + See also + -------- + sklearn.linear_model.SGDClassifier """ def __init__(self, penalty='l2', dual=False, tol=1e-4, C=1.0, - fit_intercept=True, intercept_scaling=1, class_weight=None): + fit_intercept=True, intercept_scaling=1, class_weight=None, + random_state=None, solver='liblinear', max_iter=100, + multi_class='ovr', verbose=0): + + self.penalty = penalty + self.dual = dual + self.tol = tol + self.C = C + self.fit_intercept = fit_intercept + self.intercept_scaling = intercept_scaling + self.class_weight = class_weight + self.random_state = random_state + self.solver = solver + self.max_iter = max_iter + self.multi_class = multi_class + self.verbose = verbose + + def fit(self, X, y): + """Fit the model according to the given training data. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training vector, where n_samples in the number of samples and + n_features is the number of features. + + y : array-like, shape (n_samples,) + Target vector relative to X. + + Returns + ------- + self : object + Returns self. + """ + if self.C < 0: + raise ValueError("Penalty term must be positive; got (C=%r)" + % self.C) + + X, y = check_X_y(X, y, accept_sparse='csr', dtype=np.float64, order="C") + self.classes_ = np.unique(y) + if self.solver not in ['liblinear', 'newton-cg', 'lbfgs']: + raise ValueError( + "Logistic Regression supports only liblinear, newton-cg and " + "lbfgs solvers, Got solver=%s" % self.solver + ) + + if self.solver == 'liblinear' and self.multi_class == 'multinomial': + raise ValueError("Solver %s does not support a multinomial " + "backend." % self.solver) + if self.multi_class not in ['ovr', 'multinomial']: + raise ValueError("multi_class should be either ovr or multinomial " + "got %s" % self.multi_class) + + if self.solver == 'liblinear': + self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear( + X, y, self.C, self.fit_intercept, self.intercept_scaling, + self.class_weight, self.penalty, self.dual, self.verbose, + self.max_iter, self.tol + ) + return self + + n_classes = len(self.classes_) + classes_ = self.classes_ + if n_classes < 2: + raise ValueError("This solver needs samples of at least 2 classes" + " in the data, but the data contains only one" + " class: %r" % classes_[0]) + + if len(self.classes_) == 2: + n_classes = 1 + classes_ = classes_[1:] - super(LogisticRegression, self).__init__(penalty=penalty, dual=dual, - loss='lr', tol=tol, C=C, fit_intercept=fit_intercept, - intercept_scaling=intercept_scaling, class_weight=class_weight) + self.coef_ = list() + self.intercept_ = np.zeros(n_classes) + + # Hack so that we iterate only once for the multinomial case. + if self.multi_class == 'multinomial': + classes_ = [None] + + for ind, class_ in enumerate(classes_): + coef_, _ = logistic_regression_path( + X, y, pos_class=class_, Cs=[self.C], + fit_intercept=self.fit_intercept, tol=self.tol, + verbose=self.verbose, solver=self.solver, + multi_class=self.multi_class, max_iter=self.max_iter, + class_weight=self.class_weight) + self.coef_.append(coef_[0]) + + self.coef_ = np.squeeze(self.coef_) + # For the binary case, this get squeezed to a 1-D array. + if self.coef_.ndim == 1: + self.coef_ = self.coef_[np.newaxis, :] + + self.coef_ = np.asarray(self.coef_) + if self.fit_intercept: + self.intercept_ = self.coef_[:, -1] + self.coef_ = self.coef_[:, :-1] + + return self def predict_proba(self, X): """Probability estimates. @@ -110,20 +1090,9 @@ def predict_proba(self, X): ------- T : array-like, shape = [n_samples, n_classes] Returns the probability of the sample for each class in the model, - where classes are ordered as they are in self.classes_. + where classes are ordered as they are in ``self.classes_``. """ - # 1. / (1. + np.exp(-scores)), computed in-place - prob = self.decision_function(X) - prob *= -1 - np.exp(prob, prob) - prob += 1 - np.reciprocal(prob, prob) - if len(prob.shape) == 1: - return np.vstack([1 - prob, prob]).T - else: - # OvR, not softmax, like Liblinear's predict_probability - prob /= prob.sum(axis=0) - return prob + return self._predict_proba_lr(X) def predict_log_proba(self, X): """Log of probability estimates. @@ -139,6 +1108,359 @@ def predict_log_proba(self, X): ------- T : array-like, shape = [n_samples, n_classes] Returns the log-probability of the sample for each class in the - model, where classes are ordered as they are in self.classes_. + model, where classes are ordered as they are in ``self.classes_``. """ return np.log(self.predict_proba(X)) + + +class LogisticRegressionCV(LogisticRegression, BaseEstimator, + LinearClassifierMixin, _LearntSelectorMixin): + """Logistic Regression CV (aka logit, MaxEnt) classifier. + + This class implements logistic regression using liblinear, newton-cg or + LBFGS optimizer. The newton-cg and lbfgs solvers support only L2 + regularization with primal formulation. The liblinear solver supports both + L1 and L2 regularization, with a dual formulation only for the L2 penalty. + + For the grid of Cs values (that are set by default to be ten values in + a logarithmic scale between 1e-4 and 1e4), the best hyperparameter is + selected by the cross-validator StratifiedKFold, but it can be changed + using the cv parameter. In the case of newton-cg and lbfgs solvers, + we warm start along the path i.e guess the initial coefficients of the + present fit to be the coefficients got after convergence in the previous + fit, so in general it is supposed to be faster. + + For a multiclass problem, the hyperparameters for each class are computed + using the best scores got by doing a one-vs-rest in parallel across all + folds and classes. Hence this is not the true multinomial loss. + + Parameters + ---------- + Cs : list of floats | int + Each of the values in Cs describes the inverse of regularization + strength. If Cs is as an int, then a grid of Cs values are chosen + in a logarithmic scale between 1e-4 and 1e4. + Like in support vector machines, smaller values specify stronger + regularization. + + fit_intercept : bool, default: True + Specifies if a constant (a.k.a. bias or intercept) should be + added the decision function. + + class_weight : {dict, 'auto'}, optional + Over-/undersamples the samples of each class according to the given + weights. If not given, all classes are supposed to have weight one. + The 'auto' mode selects weights inversely proportional to class + frequencies in the training set. + + cv : integer or cross-validation generator + The default cross-validation generator used is Stratified K-Folds. + If an integer is provided, then it is the number of folds used. + See the module :mod:`sklearn.cross_validation` module for the + list of possible cross-validation objects. + + penalty : str, 'l1' or 'l2' + Used to specify the norm used in the penalization. The newton-cg and + lbfgs solvers support only l2 penalties. + + dual : bool + Dual or primal formulation. Dual formulation is only implemented for + l2 penalty with liblinear solver. Prefer dual=False when + n_samples > n_features. + + scoring : callabale + Scoring function to use as cross-validation criteria. For a list of + scoring functions that can be used, look at :mod:`sklearn.metrics`. + The default scoring option used is accuracy_score. + + solver : {'newton-cg', 'lbfgs', 'liblinear'} + Algorithm to use in the optimization problem. + + tol : float, optional + Tolerance for stopping criteria. + + max_iter : int, optional + Maximum number of iterations of the optimization algorithm. + + class_weight : {dict, 'auto'}, optional + Over-/undersamples the samples of each class according to the given + weights. If not given, all classes are supposed to have weight one. + The 'auto' mode selects weights inversely proportional to class + frequencies in the training set. + + n_jobs : int, optional + Number of CPU cores used during the cross-validation loop. If given + a value of -1, all cores are used. + + verbose : int + For the liblinear and lbfgs solvers set verbose to any positive + number for verbosity. + + refit : bool + If set to True, the scores are averaged across all folds, and the + coefs and the C that corresponds to the best score is taken, and a + final refit is done using these parameters. + Otherwise the coefs, intercepts and C that correspond to the + best scores across folds are averaged. + + multi_class : str, {'ovr', 'multinomial'} + Multiclass option can be either 'ovr' or 'multinomial'. If the option + chosen is 'ovr', then a binary problem is fit for each label. Else + the loss minimised is the multinomial loss fit across + the entire probability distribution. Works only for the 'lbfgs' + solver. + + intercept_scaling : float, default 1. + Useful only if solver is liblinear. + This parameter is useful only when the solver 'liblinear' is used + and self.fit_intercept is set to True. In this case, x becomes + [x, self.intercept_scaling], + i.e. a "synthetic" feature with constant value equals to + intercept_scaling is appended to the instance vector. + The intercept becomes intercept_scaling * synthetic feature weight + Note! the synthetic feature weight is subject to l1/l2 regularization + as all other features. + To lessen the effect of regularization on synthetic feature weight + (and therefore on the intercept) intercept_scaling has to be increased. + + Attributes + ---------- + coef_ : array, shape (1, n_features) or (n_classes, n_features) + Coefficient of the features in the decision function. + + `coef_` is of shape (1, n_features) when the given problem + is binary. + `coef_` is readonly property derived from `raw_coef_` that + follows the internal memory layout of liblinear. + + intercept_ : array, shape (1,) or (n_classes,) + Intercept (a.k.a. bias) added to the decision function. + It is available only when parameter intercept is set to True + and is of shape(1,) when the problem is binary. + + Cs_ : array + Array of C i.e. inverse of regularization parameter values used + for cross-validation. + + coefs_paths_ : array, shape ``(n_folds, len(Cs_), n_features)`` or + ``(n_folds, len(Cs_), n_features + 1)`` + dict with classes as the keys, and the path of coefficients obtained + during cross-validating across each fold and then across each Cs + after doing an OvR for the corresponding class as values. + If the 'multi_class' option is set to 'multinomial', then + the coefs_paths are the coefficients corresponding to each class. + Each dict value has shape ``(n_folds, len(Cs_), n_features)`` or + ``(n_folds, len(Cs_), n_features + 1)`` depending on whether the + intercept is fit or not. + + scores_ : dict + dict with classes as the keys, and the values as the + grid of scores obtained during cross-validating each fold, after doing + an OvR for the corresponding class. If the 'multi_class' option + given is 'multinomial' then the same scores are repeated across + all classes, since this is the multinomial class. + Each dict value has shape (n_folds, len(Cs)) + + C_ : array, shape (n_classes,) or (n_classes - 1,) + Array of C that maps to the best scores across every class. If refit is + set to False, then for each class, the best C is the average of the + C's that correspond to the best scores for each fold. + + See also + -------- + LogisticRegression + + """ + + def __init__(self, Cs=10, fit_intercept=True, cv=None, dual=False, + penalty='l2', scoring=None, solver='lbfgs', tol=1e-4, + max_iter=100, class_weight=None, n_jobs=1, verbose=0, + refit=True, intercept_scaling=1., multi_class='ovr'): + self.Cs = Cs + self.fit_intercept = fit_intercept + self.cv = cv + self.dual = dual + self.penalty = penalty + self.scoring = scoring + self.tol = tol + self.max_iter = max_iter + self.class_weight = class_weight + self.n_jobs = n_jobs + self.verbose = verbose + self.solver = solver + self.refit = refit + self.intercept_scaling = intercept_scaling + self.multi_class = multi_class + + def fit(self, X, y): + """Fit the model according to the given training data. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training vector, where n_samples in the number of samples and + n_features is the number of features. + + y : array-like, shape (n_samples,) + Target vector relative to X. + + Returns + ------- + self : object + Returns self. + """ + if self.solver != 'liblinear': + if self.penalty != 'l2': + raise ValueError("newton-cg and lbfgs solvers support only " + "l2 penalties.") + if self.dual: + raise ValueError("newton-cg and lbfgs solvers support only " + "the primal form.") + + X = check_array(X, accept_sparse='csr', dtype=np.float64) + y = check_array(y, ensure_2d=False, dtype=None) + + if self.multi_class not in ['ovr', 'multinomial']: + raise ValueError("multi_class backend should be either " + "'ovr' or 'multinomial'" + " got %s" % self.multi_class) + + if y.ndim == 2 and y.shape[1] == 1: + warnings.warn( + "A column-vector y was passed when a 1d array was" + " expected. Please change the shape of y to " + "(n_samples, ), for example using ravel().", + DataConversionWarning + ) + y = np.ravel(y) + + check_consistent_length(X, y) + + # init cross-validation generator + cv = _check_cv(self.cv, X, y, classifier=True) + folds = list(cv) + + self._enc = LabelEncoder() + self._enc.fit(y) + + labels = self.classes_ = np.unique(y) + n_classes = len(labels) + + if n_classes < 2: + raise ValueError("This solver needs samples of at least 2 classes" + " in the data, but the data contains only one" + " class: %r" % self.classes_[0]) + if n_classes == 2: + # OvR in case of binary problems is as good as fitting + # the higher label + n_classes = 1 + labels = labels[1:] + + # We need this hack to iterate only once over labels, in the case of + # multi_class = multinomial, without changing the value of the labels. + iter_labels = labels + if self.multi_class == 'multinomial': + iter_labels = [None] + + if self.class_weight and not(isinstance(self.class_weight, dict) or + self.class_weight == 'auto'): + raise ValueError("class_weight provided should be a " + "dict or 'auto'") + + path_func = delayed(_log_reg_scoring_path) + + fold_coefs_ = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)( + path_func(X, y, train, test, pos_class=label, Cs=self.Cs, + fit_intercept=self.fit_intercept, penalty=self.penalty, + dual=self.dual, solver=self.solver, tol=self.tol, + max_iter=self.max_iter, verbose=self.verbose, + class_weight=self.class_weight, scoring=self.scoring, + multi_class=self.multi_class, + intercept_scaling=self.intercept_scaling + ) + for label in iter_labels + for train, test in folds) + + if self.multi_class == 'multinomial': + multi_coefs_paths, Cs, multi_scores = zip(*fold_coefs_) + multi_coefs_paths = np.asarray(multi_coefs_paths) + multi_scores = np.asarray(multi_scores) + + # This is just to maintain API similarity between the ovr and + # multinomial option. + # Coefs_paths in now n_folds X len(Cs) X n_classes X n_features + # we need it to be n_classes X len(Cs) X n_folds X n_features + # to be similar to "ovr". + coefs_paths = np.rollaxis(multi_coefs_paths, 2, 0) + + # Multinomial has a true score across all labels. Hence the + # shape is n_folds X len(Cs). We need to repeat this score + # across all labels for API similarity. + scores = np.tile(multi_scores, (n_classes, 1, 1)) + self.Cs_ = Cs[0] + + else: + coefs_paths, Cs, scores = zip(*fold_coefs_) + self.Cs_ = Cs[0] + coefs_paths = np.reshape(coefs_paths, (n_classes, len(folds), + len(self.Cs_), -1)) + + self.coefs_paths_ = dict(zip(labels, coefs_paths)) + scores = np.reshape(scores, (n_classes, len(folds), -1)) + self.scores_ = dict(zip(labels, scores)) + + self.C_ = list() + self.coef_ = np.empty((n_classes, X.shape[1])) + self.intercept_ = np.zeros(n_classes) + + # hack to iterate only once for multinomial case. + if self.multi_class == 'multinomial': + scores = multi_scores + coefs_paths = multi_coefs_paths + + for index, label in enumerate(iter_labels): + if self.multi_class == 'ovr': + scores = self.scores_[label] + coefs_paths = self.coefs_paths_[label] + + if self.refit: + best_index = scores.sum(axis=0).argmax() + + C_ = self.Cs_[best_index] + self.C_.append(C_) + if self.multi_class == 'multinomial': + coef_init = np.mean(coefs_paths[:, best_index, :, :], + axis=0) + else: + coef_init = np.mean(coefs_paths[:, best_index, :], axis=0) + w, _ = logistic_regression_path( + X, y, pos_class=label, Cs=[C_], solver=self.solver, + fit_intercept=self.fit_intercept, coef=coef_init, + max_iter=self.max_iter, tol=self.tol, + class_weight=self.class_weight, + multi_class=self.multi_class, + verbose=max(0, self.verbose - 1)) + w = w[0] + + else: + # Take the best scores across every fold and the average of all + # coefficients corresponding to the best scores. + best_indices = np.argmax(scores, axis=1) + w = np.mean([ + coefs_paths[i][best_indices[i]] + for i in range(len(folds)) + ], axis=0) + self.C_.append(np.mean(self.Cs_[best_indices])) + + if self.multi_class == 'multinomial': + self.C_ = np.tile(self.C_, n_classes) + self.coef_ = w[:, :X.shape[1]] + if self.fit_intercept: + self.intercept_ = w[:, -1] + else: + self.coef_[index] = w[: X.shape[1]] + if self.fit_intercept: + self.intercept_[index] = w[-1] + + self.C_ = np.asarray(self.C_) + return self diff --git a/sklearn/linear_model/omp.py b/sklearn/linear_model/omp.py index 146d8db75c807..c45d80bf1c686 100644 --- a/sklearn/linear_model/omp.py +++ b/sklearn/linear_model/omp.py @@ -3,55 +3,75 @@ # Author: Vlad Niculae # -# License: BSD Style. +# License: BSD 3 clause import warnings +from distutils.version import LooseVersion import numpy as np from scipy import linalg from scipy.linalg.lapack import get_lapack_funcs -from .base import LinearModel +from .base import LinearModel, _pre_fit from ..base import RegressorMixin -from ..utils import array2d -from ..utils.arrayfuncs import solve_triangular +from ..utils import as_float_array, check_array, check_X_y +from ..cross_validation import _check_cv as check_cv +from ..externals.joblib import Parallel, delayed + +import scipy +solve_triangular_args = {} +if LooseVersion(scipy.__version__) >= LooseVersion('0.12'): + solve_triangular_args = {'check_finite': False} + premature = """ Orthogonal matching pursuit ended prematurely due to linear dependence in the dictionary. The requested precision might not have been met. """ -def _cholesky_omp(X, y, n_nonzero_coefs, tol=None, copy_X=True): +def _cholesky_omp(X, y, n_nonzero_coefs, tol=None, copy_X=True, + return_path=False): """Orthogonal Matching Pursuit step using the Cholesky decomposition. - Parameters: - ----------- - X: array, shape = (n_samples, n_features) + Parameters + ---------- + X : array, shape (n_samples, n_features) Input dictionary. Columns are assumed to have unit norm. - y: array, shape = (n_samples,) + y : array, shape (n_samples,) Input targets - n_nonzero_coefs: int + n_nonzero_coefs : int Targeted number of non-zero elements - tol: float + tol : float Targeted squared error, if not None overrides n_nonzero_coefs. - copy_X: bool, optional + copy_X : bool, optional Whether the design matrix X must be copied by the algorithm. A false value is only helpful if X is already Fortran-ordered, otherwise a copy is made anyway. - Returns: - -------- - gamma: array, shape = (n_nonzero_coefs,) + return_path : bool, optional. Default: False + Whether to return every value of the nonzero coefficients along the + forward path. Useful for cross-validation. + + Returns + ------- + gamma : array, shape (n_nonzero_coefs,) Non-zero elements of the solution - idx: array, shape = (n_nonzero_coefs,) + idx : array, shape (n_nonzero_coefs,) Indices of the positions of the elements in gamma within the solution vector + coef : array, shape (n_features, n_nonzero_coefs) + The first k values of column k correspond to the coefficient value + for the active features at that step. The lower left triangle contains + garbage. Only returned if ``return_path=True``. + + n_active : int + Number of active features at convergence. """ if copy_X: X = X.copy('F') @@ -66,11 +86,13 @@ def _cholesky_omp(X, y, n_nonzero_coefs, tol=None, copy_X=True): residual = y gamma = np.empty(0) n_active = 0 - indices = range(X.shape[1]) # keeping track of swapping + indices = np.arange(X.shape[1]) # keeping track of swapping max_features = X.shape[1] if tol is not None else n_nonzero_coefs L = np.empty((max_features, max_features), dtype=X.dtype) L[0, 0] = 1. + if return_path: + coefs = np.empty_like(L) while True: lam = np.argmax(np.abs(np.dot(X.T, residual))) @@ -81,7 +103,11 @@ def _cholesky_omp(X, y, n_nonzero_coefs, tol=None, copy_X=True): if n_active > 0: # Updates the Cholesky decomposition of X' X L[n_active, :n_active] = np.dot(X[:, :n_active].T, X[:, lam]) - solve_triangular(L[:n_active, :n_active], L[n_active, :n_active]) + linalg.solve_triangular(L[:n_active, :n_active], + L[n_active, :n_active], + trans=0, lower=1, + overwrite_b=True, + **solve_triangular_args) v = nrm2(L[n_active, :n_active]) ** 2 if 1 - v <= min_float: # selected atoms are dependent warnings.warn(premature, RuntimeWarning, stacklevel=2) @@ -94,57 +120,72 @@ def _cholesky_omp(X, y, n_nonzero_coefs, tol=None, copy_X=True): # solves LL'x = y as a composition of two triangular systems gamma, _ = potrs(L[:n_active, :n_active], alpha[:n_active], lower=True, overwrite_b=False) - + if return_path: + coefs[:n_active, n_active - 1] = gamma residual = y - np.dot(X[:, :n_active], gamma) if tol is not None and nrm2(residual) ** 2 <= tol: break elif n_active == max_features: break - return gamma, indices[:n_active] + if return_path: + return gamma, indices[:n_active], coefs[:, :n_active], n_active + else: + return gamma, indices[:n_active], n_active def _gram_omp(Gram, Xy, n_nonzero_coefs, tol_0=None, tol=None, - copy_Gram=True, copy_Xy=True): + copy_Gram=True, copy_Xy=True, return_path=False): """Orthogonal Matching Pursuit step on a precomputed Gram matrix. This function uses the the Cholesky decomposition method. - Parameters: - ----------- - Gram: array, shape = (n_features, n_features) + Parameters + ---------- + Gram : array, shape (n_features, n_features) Gram matrix of the input data matrix - Xy: array, shape = (n_features,) + Xy : array, shape (n_features,) Input targets - n_nonzero_coefs: int + n_nonzero_coefs : int Targeted number of non-zero elements - tol_0: float + tol_0 : float Squared norm of y, required if tol is not None. - tol: float + tol : float Targeted squared error, if not None overrides n_nonzero_coefs. - copy_Gram: bool, optional + copy_Gram : bool, optional Whether the gram matrix must be copied by the algorithm. A false value is only helpful if it is already Fortran-ordered, otherwise a copy is made anyway. - copy_Xy: bool, optional + copy_Xy : bool, optional Whether the covariance vector Xy must be copied by the algorithm. If False, it may be overwritten. - Returns: - -------- - gamma: array, shape = (n_nonzero_coefs,) + return_path : bool, optional. Default: False + Whether to return every value of the nonzero coefficients along the + forward path. Useful for cross-validation. + + Returns + ------- + gamma : array, shape (n_nonzero_coefs,) Non-zero elements of the solution - idx: array, shape = (n_nonzero_coefs,) + idx : array, shape (n_nonzero_coefs,) Indices of the positions of the elements in gamma within the solution vector + coefs : array, shape (n_features, n_nonzero_coefs) + The first k values of column k correspond to the coefficient value + for the active features at that step. The lower left triangle contains + garbage. Only returned if ``return_path=True``. + + n_active : int + Number of active features at convergence. """ Gram = Gram.copy('F') if copy_Gram else np.asfortranarray(Gram) @@ -155,7 +196,7 @@ def _gram_omp(Gram, Xy, n_nonzero_coefs, tol_0=None, tol=None, nrm2, swap = linalg.get_blas_funcs(('nrm2', 'swap'), (Gram,)) potrs, = get_lapack_funcs(('potrs',), (Gram,)) - indices = range(len(Gram)) # keeping track of swapping + indices = np.arange(len(Gram)) # keeping track of swapping alpha = Xy tol_curr = tol_0 delta = 0 @@ -165,19 +206,25 @@ def _gram_omp(Gram, Xy, n_nonzero_coefs, tol_0=None, tol=None, max_features = len(Gram) if tol is not None else n_nonzero_coefs L = np.empty((max_features, max_features), dtype=Gram.dtype) L[0, 0] = 1. + if return_path: + coefs = np.empty_like(L) while True: lam = np.argmax(np.abs(alpha)) if lam < n_active or alpha[lam] ** 2 < min_float: # selected same atom twice, or inner product too small - warnings.warn(premature, RuntimeWarning, stacklevel=2) + warnings.warn(premature, RuntimeWarning, stacklevel=3) break if n_active > 0: L[n_active, :n_active] = Gram[lam, :n_active] - solve_triangular(L[:n_active, :n_active], L[n_active, :n_active]) + linalg.solve_triangular(L[:n_active, :n_active], + L[n_active, :n_active], + trans=0, lower=1, + overwrite_b=True, + **solve_triangular_args) v = nrm2(L[n_active, :n_active]) ** 2 if 1 - v <= min_float: # selected atoms are dependent - warnings.warn(premature, RuntimeWarning, stacklevel=2) + warnings.warn(premature, RuntimeWarning, stacklevel=3) break L[n_active, n_active] = np.sqrt(1 - v) Gram[n_active], Gram[lam] = swap(Gram[n_active], Gram[lam]) @@ -188,23 +235,28 @@ def _gram_omp(Gram, Xy, n_nonzero_coefs, tol_0=None, tol=None, # solves LL'x = y as a composition of two triangular systems gamma, _ = potrs(L[:n_active, :n_active], Xy[:n_active], lower=True, overwrite_b=False) - + if return_path: + coefs[:n_active, n_active - 1] = gamma beta = np.dot(Gram[:, :n_active], gamma) alpha = Xy - beta if tol is not None: tol_curr += delta delta = np.inner(gamma, beta[:n_active]) tol_curr -= delta - if tol_curr <= tol: + if abs(tol_curr) <= tol: break elif n_active == max_features: break - return gamma, indices[:n_active] + if return_path: + return gamma, indices[:n_active], coefs[:, :n_active], n_active + else: + return gamma, indices[:n_active], n_active -def orthogonal_mp(X, y, n_nonzero_coefs=None, tol=None, precompute_gram=False, - copy_X=True): +def orthogonal_mp(X, y, n_nonzero_coefs=None, tol=None, precompute=False, + copy_X=True, return_path=False, + return_n_iter=False): """Orthogonal Matching Pursuit (OMP) Solves n_targets Orthogonal Matching Pursuit problems. @@ -219,32 +271,47 @@ def orthogonal_mp(X, y, n_nonzero_coefs=None, tol=None, precompute_gram=False, Parameters ---------- - X: array, shape = (n_samples, n_features) + X : array, shape (n_samples, n_features) Input data. Columns are assumed to have unit norm. - y: array, shape = (n_samples,) or (n_samples, n_targets) + y : array, shape (n_samples,) or (n_samples, n_targets) Input targets - n_nonzero_coefs: int + n_nonzero_coefs : int Desired number of non-zero entries in the solution. If None (by default) this value is set to 10% of n_features. - tol: float + tol : float Maximum norm of the residual. If not None, overrides n_nonzero_coefs. - precompute_gram: {True, False, 'auto'}, + precompute : {True, False, 'auto'}, Whether to perform precomputations. Improves performance when n_targets or n_samples is very large. - copy_X: bool, optional + copy_X : bool, optional Whether the design matrix X must be copied by the algorithm. A false value is only helpful if X is already Fortran-ordered, otherwise a copy is made anyway. + return_path : bool, optional. Default: False + Whether to return every value of the nonzero coefficients along the + forward path. Useful for cross-validation. + + return_n_iter : bool, optional default False + Whether or not to return the number of iterations. + Returns ------- - coef: array, shape = (n_features,) or (n_features, n_targets) - Coefficients of the OMP solution + coef : array, shape (n_features,) or (n_features, n_targets) + Coefficients of the OMP solution. If `return_path=True`, this contains + the whole coefficient path. In this case its shape is + (n_features, n_features) or (n_features, n_targets, n_features) and + iterating over the last axis yields coefficients in increasing order + of active features. + + n_iters : array-like or int + Number of active features across every target. Returned only if + `return_n_iter` is set to True. See also -------- @@ -266,15 +333,17 @@ def orthogonal_mp(X, y, n_nonzero_coefs=None, tol=None, precompute_gram=False, http://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf """ - X = array2d(X, order='F', copy=copy_X) + X = check_array(X, order='F', copy=copy_X) copy_X = False - y = np.asarray(y) if y.ndim == 1: - y = y[:, np.newaxis] + y = y.reshape(-1, 1) + y = check_array(y) if y.shape[1] > 1: # subsequent targets will be affected copy_X = True - if n_nonzero_coefs == None and tol == None: - n_nonzero_coefs = int(0.1 * X.shape[1]) + if n_nonzero_coefs is None and tol is None: + # default for n_nonzero_coefs is 0.1 * n_features + # but at least one. + n_nonzero_coefs = max(int(0.1 * X.shape[1]), 1) if tol is not None and tol < 0: raise ValueError("Epsilon cannot be negative") if tol is None and n_nonzero_coefs <= 0: @@ -282,9 +351,9 @@ def orthogonal_mp(X, y, n_nonzero_coefs=None, tol=None, precompute_gram=False, if tol is None and n_nonzero_coefs > X.shape[1]: raise ValueError("The number of atoms cannot be more than the number " "of features") - if precompute_gram == 'auto': - precompute_gram = X.shape[0] > X.shape[1] - if precompute_gram: + if precompute == 'auto': + precompute = X.shape[0] > X.shape[1] + if precompute: G = np.dot(X.T, X) G = np.asfortranarray(G) Xy = np.dot(X.T, y) @@ -293,19 +362,42 @@ def orthogonal_mp(X, y, n_nonzero_coefs=None, tol=None, precompute_gram=False, else: norms_squared = None return orthogonal_mp_gram(G, Xy, n_nonzero_coefs, tol, norms_squared, - copy_Gram=copy_X, copy_Xy=False) + copy_Gram=copy_X, copy_Xy=False, return_path=return_path) + + if return_path: + coef = np.zeros((X.shape[1], y.shape[1], X.shape[1])) + else: + coef = np.zeros((X.shape[1], y.shape[1])) + n_iters = [] + + for k in range(y.shape[1]): + out = _cholesky_omp( + X, y[:, k], n_nonzero_coefs, tol, + copy_X=copy_X, return_path=return_path + ) + if return_path: + _, idx, coefs, n_iter = out + coef = coef[:, :, :len(idx)] + for n_active, x in enumerate(coefs.T): + coef[idx[:n_active + 1], k, n_active] = x[:n_active + 1] + else: + x, idx, n_iter = out + coef[idx, k] = x + n_iters.append(n_iter) - coef = np.zeros((X.shape[1], y.shape[1])) - for k in xrange(y.shape[1]): - x, idx = _cholesky_omp(X, y[:, k], n_nonzero_coefs, tol, - copy_X=copy_X) - coef[idx, k] = x - return np.squeeze(coef) + if y.shape[1] == 1: + n_iters = n_iters[0] + + if return_n_iter: + return np.squeeze(coef), n_iters + else: + return np.squeeze(coef) def orthogonal_mp_gram(Gram, Xy, n_nonzero_coefs=None, tol=None, norms_squared=None, copy_Gram=True, - copy_Xy=True): + copy_Xy=True, return_path=False, + return_n_iter=False): """Gram Orthogonal Matching Pursuit (OMP) Solves n_targets Orthogonal Matching Pursuit problems using only @@ -313,35 +405,50 @@ def orthogonal_mp_gram(Gram, Xy, n_nonzero_coefs=None, tol=None, Parameters ---------- - Gram: array, shape = (n_features, n_features) + Gram : array, shape (n_features, n_features) Gram matrix of the input data: X.T * X - Xy: array, shape = (n_features,) or (n_features, n_targets) + Xy : array, shape (n_features,) or (n_features, n_targets) Input targets multiplied by X: X.T * y - n_nonzero_coefs: int + n_nonzero_coefs : int Desired number of non-zero entries in the solution. If None (by default) this value is set to 10% of n_features. - tol: float + tol : float Maximum norm of the residual. If not None, overrides n_nonzero_coefs. - norms_squared: array-like, shape = (n_targets,) + norms_squared : array-like, shape (n_targets,) Squared L2 norms of the lines of y. Required if tol is not None. - copy_Gram: bool, optional + copy_Gram : bool, optional Whether the gram matrix must be copied by the algorithm. A false value is only helpful if it is already Fortran-ordered, otherwise a copy is made anyway. - copy_Xy: bool, optional + copy_Xy : bool, optional Whether the covariance vector Xy must be copied by the algorithm. If False, it may be overwritten. + return_path : bool, optional. Default: False + Whether to return every value of the nonzero coefficients along the + forward path. Useful for cross-validation. + + return_n_iter : bool, optional default False + Whether or not to return the number of iterations. + Returns ------- - coef: array, shape = (n_features,) or (n_features, n_targets) - Coefficients of the OMP solution + coef : array, shape (n_features,) or (n_features, n_targets) + Coefficients of the OMP solution. If `return_path=True`, this contains + the whole coefficient path. In this case its shape is + (n_features, n_features) or (n_features, n_targets, n_features) and + iterating over the last axis yields coefficients in increasing order + of active features. + + n_iters : array-like or int + Number of active features across every target. Returned only if + `return_n_iter` is set to True. See also -------- @@ -363,18 +470,19 @@ def orthogonal_mp_gram(Gram, Xy, n_nonzero_coefs=None, tol=None, http://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf """ - Gram = array2d(Gram, order='F', copy=copy_Gram) + Gram = check_array(Gram, order='F', copy=copy_Gram) Xy = np.asarray(Xy) - if Xy.ndim > 1 and Xy.shape[1] > 1: # or subsequent target will be affected + if Xy.ndim > 1 and Xy.shape[1] > 1: + # or subsequent target will be affected copy_Gram = True if Xy.ndim == 1: Xy = Xy[:, np.newaxis] if tol is not None: norms_squared = [norms_squared] - if n_nonzero_coefs == None and tol is None: + if n_nonzero_coefs is None and tol is None: n_nonzero_coefs = int(0.1 * len(Gram)) - if tol is not None and norms_squared == None: + if tol is not None and norms_squared is None: raise ValueError('Gram OMP needs the precomputed norms in order ' 'to evaluate the error sum of squares.') if tol is not None and tol < 0: @@ -383,18 +491,42 @@ def orthogonal_mp_gram(Gram, Xy, n_nonzero_coefs=None, tol=None, raise ValueError("The number of atoms must be positive") if tol is None and n_nonzero_coefs > len(Gram): raise ValueError("The number of atoms cannot be more than the number " - "of features") - coef = np.zeros((len(Gram), Xy.shape[1])) + "of features") + + if return_path: + coef = np.zeros((len(Gram), Xy.shape[1], len(Gram))) + else: + coef = np.zeros((len(Gram), Xy.shape[1])) + + n_iters = [] for k in range(Xy.shape[1]): - x, idx = _gram_omp(Gram, Xy[:, k], n_nonzero_coefs, - norms_squared[k] if tol is not None else None, tol, - copy_Gram=copy_Gram, copy_Xy=copy_Xy) - coef[idx, k] = x - return np.squeeze(coef) + out = _gram_omp( + Gram, Xy[:, k], n_nonzero_coefs, + norms_squared[k] if tol is not None else None, tol, + copy_Gram=copy_Gram, copy_Xy=copy_Xy, + return_path=return_path + ) + if return_path: + _, idx, coefs, n_iter = out + coef = coef[:, :, :len(idx)] + for n_active, x in enumerate(coefs.T): + coef[idx[:n_active + 1], k, n_active] = x[:n_active + 1] + else: + x, idx, n_iter = out + coef[idx, k] = x + n_iters.append(n_iter) + + if Xy.shape[1] == 1: + n_iters = n_iters[0] + + if return_n_iter: + return np.squeeze(coef), n_iters + else: + return np.squeeze(coef) class OrthogonalMatchingPursuit(LinearModel, RegressorMixin): - """Orthogonal Mathching Pursuit model (OMP) + """Orthogonal Matching Pursuit model (OMP) Parameters ---------- @@ -413,35 +545,23 @@ class OrthogonalMatchingPursuit(LinearModel, RegressorMixin): normalize : boolean, optional If False, the regressors X are assumed to be already normalized. - precompute_gram : {True, False, 'auto'}, + precompute : {True, False, 'auto'}, default 'auto' Whether to use a precomputed Gram and Xy matrix to speed up calculations. Improves performance when `n_targets` or `n_samples` is very large. Note that if you already have such matrices, you can pass them directly to the fit method. - copy_X : bool, optional - Whether the design matrix X must be copied by the algorithm. A false - value is only helpful if X is already Fortran-ordered, otherwise a - copy is made anyway. - - copy_Gram : bool, optional - Whether the gram matrix must be copied by the algorithm. A false - value is only helpful if X is already Fortran-ordered, otherwise a - copy is made anyway. - - copy_Xy : bool, optional - Whether the covariance vector Xy must be copied by the algorithm. - If False, it may be overwritten. - - Attributes ---------- - `coef_` : array, shape = (n_features,) or (n_features, n_targets) - parameter vector (w in the fomulation formula) + coef_ : array, shape (n_features,) or (n_features, n_targets) + parameter vector (w in the formula) - `intercept_` : float or array, shape =(n_targets,) + intercept_ : float or array, shape (n_targets,) independent term in decision function. + n_iter_ : int or array-like + Number of active features across every target. + Notes ----- Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang, @@ -464,93 +584,248 @@ class OrthogonalMatchingPursuit(LinearModel, RegressorMixin): decomposition.sparse_encode """ - def __init__(self, copy_X=True, copy_Gram=True, - copy_Xy=True, n_nonzero_coefs=None, tol=None, - fit_intercept=True, normalize=True, precompute_gram=False): + def __init__(self, n_nonzero_coefs=None, tol=None, fit_intercept=True, + normalize=True, precompute='auto'): self.n_nonzero_coefs = n_nonzero_coefs self.tol = tol self.fit_intercept = fit_intercept self.normalize = normalize - self.precompute_gram = precompute_gram - self.copy_Gram = copy_Gram - self.copy_Xy = copy_Xy - self.copy_X = copy_X + self.precompute = precompute - def fit(self, X, y, Gram=None, Xy=None): + def fit(self, X, y): """Fit the model using X, y as training data. Parameters ---------- - X: array-like, shape = (n_samples, n_features) + X : array-like, shape (n_samples, n_features) Training data. - y: array-like, shape = (n_samples,) or (n_samples, n_targets) + y : array-like, shape (n_samples,) or (n_samples, n_targets) Target values. - Gram: array-like, shape = (n_features, n_features) (optional) - Gram matrix of the input data: X.T * X - - Xy: array-like, shape = (n_features,) or (n_features, n_targets) - (optional) - Input targets multiplied by X: X.T * y - Returns ------- - self: object + self : object returns an instance of self. """ - X = array2d(X) - y = np.asarray(y) + X, y = check_X_y(X, y, multi_output=True, y_numeric=True) n_features = X.shape[1] - X, y, X_mean, y_mean, X_std = self._center_data(X, y, - self.fit_intercept, - self.normalize, - self.copy_X) + X, y, X_mean, y_mean, X_std, Gram, Xy = \ + _pre_fit(X, y, None, self.precompute, self.normalize, + self.fit_intercept, copy=True) if y.ndim == 1: y = y[:, np.newaxis] - if self.n_nonzero_coefs == None and self.tol is None: - self.n_nonzero_coefs = int(0.1 * n_features) - if (Gram is not None or Xy is not None) and (self.fit_intercept is True - or self.normalize is True): - warnings.warn('Mean subtraction (fit_intercept) and ' - 'normalization cannot be applied on precomputed Gram ' - 'and Xy matrices. Your precomputed values are ignored ' - 'and recomputed. To avoid this, do the scaling yourself ' - 'and call with fit_intercept and normalize set to False.', - RuntimeWarning, stacklevel=2) - Gram, Xy = None, None - - if Gram is not None: - if Xy is None: - Xy = np.dot(X.T, y) - else: - if self.copy_Xy: - Xy = Xy.copy() - if self.normalize: - if len(Xy.shape) == 1: - Xy /= X_std - else: - Xy /= X_std[:, np.newaxis] - - if self.normalize: - Gram /= X_std - Gram /= X_std[:, np.newaxis] + if self.n_nonzero_coefs is None and self.tol is None: + # default for n_nonzero_coefs is 0.1 * n_features + # but at least one. + self.n_nonzero_coefs_ = max(int(0.1 * n_features), 1) + else: + self.n_nonzero_coefs_ = self.n_nonzero_coefs - norms_sq = np.sum(y ** 2, axis=0) if self.tol is not None else None - self.coef_ = orthogonal_mp_gram(Gram, Xy, self.n_nonzero_coefs, - self.tol, norms_sq, - self.copy_Gram, True).T + if Gram is False: + coef_, self.n_iter_ = orthogonal_mp( + X, y, self.n_nonzero_coefs_, self.tol, + precompute=False, copy_X=True, + return_n_iter=True) else: - precompute_gram = self.precompute_gram - if precompute_gram == 'auto': - precompute_gram = X.shape[0] > X.shape[1] - self.coef_ = orthogonal_mp(X, y, self.n_nonzero_coefs, self.tol, - precompute_gram=self.precompute_gram, - copy_X=self.copy_X).T + norms_sq = np.sum(y ** 2, axis=0) if self.tol is not None else None + coef_, self.n_iter_ = orthogonal_mp_gram( + Gram, Xy=Xy, n_nonzero_coefs=self.n_nonzero_coefs_, + tol=self.tol, norms_squared=norms_sq, + copy_Gram=True, copy_Xy=True, + return_n_iter=True) + self.coef_ = coef_.T self._set_intercept(X_mean, y_mean, X_std) return self + + +def _omp_path_residues(X_train, y_train, X_test, y_test, copy=True, + fit_intercept=True, normalize=True, max_iter=100): + """Compute the residues on left-out data for a full LARS path + + Parameters + ----------- + X_train : array, shape (n_samples, n_features) + The data to fit the LARS on + + y_train : array, shape (n_samples) + The target variable to fit LARS on + + X_test : array, shape (n_samples, n_features) + The data to compute the residues on + + y_test : array, shape (n_samples) + The target variable to compute the residues on + + copy : boolean, optional + Whether X_train, X_test, y_train and y_test should be copied. If + False, they may be overwritten. + + fit_intercept : boolean + whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (e.g. data is expected to be already centered). + + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. + + max_iter : integer, optional + Maximum numbers of iterations to perform, therefore maximum features + to include. 100 by default. + + Returns + ------- + residues: array, shape (n_samples, max_features) + Residues of the prediction on the test data + """ + + if copy: + X_train = X_train.copy() + y_train = y_train.copy() + X_test = X_test.copy() + y_test = y_test.copy() + + if fit_intercept: + X_mean = X_train.mean(axis=0) + X_train -= X_mean + X_test -= X_mean + y_mean = y_train.mean(axis=0) + y_train = as_float_array(y_train, copy=False) + y_train -= y_mean + y_test = as_float_array(y_test, copy=False) + y_test -= y_mean + + if normalize: + norms = np.sqrt(np.sum(X_train ** 2, axis=0)) + nonzeros = np.flatnonzero(norms) + X_train[:, nonzeros] /= norms[nonzeros] + + coefs = orthogonal_mp(X_train, y_train, n_nonzero_coefs=max_iter, tol=None, + precompute=False, copy_X=False, + return_path=True) + if coefs.ndim == 1: + coefs = coefs[:, np.newaxis] + if normalize: + coefs[nonzeros] /= norms[nonzeros][:, np.newaxis] + + return np.dot(coefs.T, X_test.T) - y_test + + +class OrthogonalMatchingPursuitCV(LinearModel, RegressorMixin): + """Cross-validated Orthogonal Matching Pursuit model (OMP) + + Parameters + ---------- + copy : bool, optional + Whether the design matrix X must be copied by the algorithm. A false + value is only helpful if X is already Fortran-ordered, otherwise a + copy is made anyway. + + fit_intercept : boolean, optional + whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (e.g. data is expected to be already centered). + + normalize : boolean, optional + If False, the regressors X are assumed to be already normalized. + + max_iter : integer, optional + Maximum numbers of iterations to perform, therefore maximum features + to include. 10% of ``n_features`` but at least 5 if available. + + cv : cross-validation generator, optional + see :mod:`sklearn.cross_validation`. If ``None`` is passed, default to + a 5-fold strategy + + n_jobs : integer, optional + Number of CPUs to use during the cross validation. If ``-1``, use + all the CPUs + + verbose : boolean or integer, optional + Sets the verbosity amount + + Attributes + ---------- + intercept_ : float or array, shape (n_targets,) + Independent term in decision function. + + coef_ : array, shape (n_features,) or (n_features, n_targets) + Parameter vector (w in the problem formulation). + + n_nonzero_coefs_ : int + Estimated number of non-zero coefficients giving the best mean squared + error over the cross-validation folds. + + n_iter_ : int or array-like + Number of active features across every target for the model refit with + the best hyperparameters got by cross-validating across all folds. + + See also + -------- + orthogonal_mp + orthogonal_mp_gram + lars_path + Lars + LassoLars + OrthogonalMatchingPursuit + LarsCV + LassoLarsCV + decomposition.sparse_encode + + """ + def __init__(self, copy=True, fit_intercept=True, normalize=True, + max_iter=None, cv=None, n_jobs=1, verbose=False): + self.copy = copy + self.fit_intercept = fit_intercept + self.normalize = normalize + self.max_iter = max_iter + self.cv = cv + self.n_jobs = n_jobs + self.verbose = verbose + + def fit(self, X, y): + """Fit the model using X, y as training data. + + Parameters + ---------- + X : array-like, shape [n_samples, n_features] + Training data. + + y : array-like, shape [n_samples] + Target values. + + Returns + ------- + self : object + returns an instance of self. + """ + X, y = check_X_y(X, y, y_numeric=True) + X = as_float_array(X, copy=False, force_all_finite=False) + cv = check_cv(self.cv, X, y, classifier=False) + max_iter = (min(max(int(0.1 * X.shape[1]), 5), X.shape[1]) + if not self.max_iter + else self.max_iter) + cv_paths = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)( + delayed(_omp_path_residues)( + X[train], y[train], X[test], y[test], self.copy, + self.fit_intercept, self.normalize, max_iter) + for train, test in cv) + + min_early_stop = min(fold.shape[0] for fold in cv_paths) + mse_folds = np.array([(fold[:min_early_stop] ** 2).mean(axis=1) + for fold in cv_paths]) + best_n_nonzero_coefs = np.argmin(mse_folds.mean(axis=0)) + 1 + self.n_nonzero_coefs_ = best_n_nonzero_coefs + omp = OrthogonalMatchingPursuit(n_nonzero_coefs=best_n_nonzero_coefs, + fit_intercept=self.fit_intercept, + normalize=self.normalize) + omp.fit(X, y) + self.coef_ = omp.coef_ + self.intercept_ = omp.intercept_ + self.n_iter_ = omp.n_iter_ + return self diff --git a/sklearn/linear_model/passive_aggressive.py b/sklearn/linear_model/passive_aggressive.py new file mode 100644 index 0000000000000..d4ec3098de7e7 --- /dev/null +++ b/sklearn/linear_model/passive_aggressive.py @@ -0,0 +1,272 @@ +# Authors: Rob Zinkov, Mathieu Blondel +# License: BSD 3 clause + +from .stochastic_gradient import BaseSGDClassifier +from .stochastic_gradient import BaseSGDRegressor +from .stochastic_gradient import DEFAULT_EPSILON + + +class PassiveAggressiveClassifier(BaseSGDClassifier): + """Passive Aggressive Classifier + + Parameters + ---------- + + C : float + Maximum step size (regularization). Defaults to 1.0. + + fit_intercept : bool, default=False + Whether the intercept should be estimated or not. If False, the + data is assumed to be already centered. + + n_iter : int, optional + The number of passes over the training data (aka epochs). + Defaults to 5. + + shuffle : bool, default=True + Whether or not the training data should be shuffled after each epoch. + + random_state : int seed, RandomState instance, or None (default) + The seed of the pseudo random number generator to use when + shuffling the data. + + verbose : integer, optional + The verbosity level + + n_jobs : integer, optional + The number of CPUs to use to do the OVA (One Versus All, for + multi-class problems) computation. -1 means 'all CPUs'. Defaults + to 1. + + loss : string, optional + The loss function to be used: + hinge: equivalent to PA-I in the reference paper. + squared_hinge: equivalent to PA-II in the reference paper. + + warm_start : bool, optional + When set to True, reuse the solution of the previous call to fit as + initialization, otherwise, just erase the previous solution. + + Attributes + ---------- + coef_ : array, shape = [1, n_features] if n_classes == 2 else [n_classes,\ + n_features] + Weights assigned to the features. + + intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] + Constants in decision function. + + See also + -------- + + SGDClassifier + Perceptron + + References + ---------- + Online Passive-Aggressive Algorithms + + K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006) + + """ + def __init__(self, C=1.0, fit_intercept=True, + n_iter=5, shuffle=True, verbose=0, loss="hinge", + n_jobs=1, random_state=None, warm_start=False): + BaseSGDClassifier.__init__(self, + penalty=None, + fit_intercept=fit_intercept, + n_iter=n_iter, + shuffle=shuffle, + verbose=verbose, + random_state=random_state, + eta0=1.0, + warm_start=warm_start, + n_jobs=n_jobs) + self.C = C + self.loss = loss + + def partial_fit(self, X, y, classes=None): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Subset of the training data + + y : numpy array of shape [n_samples] + Subset of the target values + + classes : array, shape = [n_classes] + Classes across all calls to partial_fit. + Can be obtained by via `np.unique(y_all)`, where y_all is the + target vector of the entire dataset. + This argument is required for the first call to partial_fit + and can be omitted in the subsequent calls. + Note that y doesn't need to contain all labels in `classes`. + + Returns + ------- + self : returns an instance of self. + """ + lr = "pa1" if self.loss == "hinge" else "pa2" + return self._partial_fit(X, y, alpha=1.0, C=self.C, + loss="hinge", learning_rate=lr, n_iter=1, + classes=classes, sample_weight=None, + coef_init=None, intercept_init=None) + + def fit(self, X, y, coef_init=None, intercept_init=None): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Training data + + y : numpy array of shape [n_samples] + Target values + + coef_init : array, shape = [n_classes,n_features] + The initial coefficients to warm-start the optimization. + + intercept_init : array, shape = [n_classes] + The initial intercept to warm-start the optimization. + + Returns + ------- + self : returns an instance of self. + """ + lr = "pa1" if self.loss == "hinge" else "pa2" + return self._fit(X, y, alpha=1.0, C=self.C, + loss="hinge", learning_rate=lr, + coef_init=coef_init, intercept_init=intercept_init) + + +class PassiveAggressiveRegressor(BaseSGDRegressor): + """Passive Aggressive Regressor + + Parameters + ---------- + + C : float + Maximum step size (regularization). Defaults to 1.0. + + epsilon : float + If the difference between the current prediction and the correct label + is below this threshold, the model is not updated. + + fit_intercept : bool + Whether the intercept should be estimated or not. If False, the + data is assumed to be already centered. Defaults to True. + + n_iter : int, optional + The number of passes over the training data (aka epochs). + Defaults to 5. + + shuffle : bool, default=True + Whether or not the training data should be shuffled after each epoch. + + random_state : int seed, RandomState instance, or None (default) + The seed of the pseudo random number generator to use when + shuffling the data. + + verbose : integer, optional + The verbosity level + + loss : string, optional + The loss function to be used: + epsilon_insensitive: equivalent to PA-I in the reference paper. + squared_epsilon_insensitive: equivalent to PA-II in the reference + paper. + + warm_start : bool, optional + When set to True, reuse the solution of the previous call to fit as + initialization, otherwise, just erase the previous solution. + + Attributes + ---------- + coef_ : array, shape = [1, n_features] if n_classes == 2 else [n_classes,\ + n_features] + Weights assigned to the features. + + intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] + Constants in decision function. + + See also + -------- + + SGDRegressor + + References + ---------- + Online Passive-Aggressive Algorithms + + K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006) + + """ + def __init__(self, C=1.0, fit_intercept=True, n_iter=5, shuffle=True, + verbose=0, loss="epsilon_insensitive", + epsilon=DEFAULT_EPSILON, random_state=None, class_weight=None, + warm_start=False): + BaseSGDRegressor.__init__(self, + penalty=None, + l1_ratio=0, + epsilon=epsilon, + eta0=1.0, + fit_intercept=fit_intercept, + n_iter=n_iter, + shuffle=shuffle, + verbose=verbose, + random_state=random_state, + warm_start=warm_start) + self.C = C + self.loss = loss + + def partial_fit(self, X, y): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Subset of training data + + y : numpy array of shape [n_samples] + Subset of target values + + Returns + ------- + self : returns an instance of self. + """ + lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2" + return self._partial_fit(X, y, alpha=1.0, C=self.C, + loss="epsilon_insensitive", + learning_rate=lr, n_iter=1, + sample_weight=None, + coef_init=None, intercept_init=None) + + def fit(self, X, y, coef_init=None, intercept_init=None): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Training data + + y : numpy array of shape [n_samples] + Target values + + coef_init : array, shape = [n_features] + The initial coefficients to warm-start the optimization. + + intercept_init : array, shape = [1] + The initial intercept to warm-start the optimization. + + Returns + ------- + self : returns an instance of self. + """ + lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2" + return self._fit(X, y, alpha=1.0, C=self.C, + loss="epsilon_insensitive", + learning_rate=lr, + coef_init=coef_init, + intercept_init=intercept_init) diff --git a/sklearn/linear_model/perceptron.py b/sklearn/linear_model/perceptron.py index 67126d5bba5f5..49946152fb9a5 100644 --- a/sklearn/linear_model/perceptron.py +++ b/sklearn/linear_model/perceptron.py @@ -1,10 +1,11 @@ # Author: Mathieu Blondel -# License: BSD Style. +# License: BSD 3 clause -from .stochastic_gradient import SGDClassifier +from .stochastic_gradient import BaseSGDClassifier +from ..feature_selection.from_model import _LearntSelectorMixin -class Perceptron(SGDClassifier): +class Perceptron(BaseSGDClassifier, _LearntSelectorMixin): """Perceptron Parameters @@ -17,26 +18,25 @@ class Perceptron(SGDClassifier): Constant that multiplies the regularization term if regularization is used. Defaults to 0.0001 - fit_intercept: bool + fit_intercept : bool Whether the intercept should be estimated or not. If False, the data is assumed to be already centered. Defaults to True. - n_iter: int, optional + n_iter : int, optional The number of passes over the training data (aka epochs). Defaults to 5. - shuffle: bool, optional + shuffle : bool, optional, default True Whether or not the training data should be shuffled after each epoch. - Defaults to False. - seed: int, optional + random_state : int seed, RandomState instance, or None (default) The seed of the pseudo random number generator to use when shuffling the data. - verbose: integer, optional + verbose : integer, optional The verbosity level - n_jobs: integer, optional + n_jobs : integer, optional The number of CPUs to use to do the OVA (One Versus All, for multi-class problems) computation. -1 means 'all CPUs'. Defaults to 1. @@ -44,7 +44,7 @@ class Perceptron(SGDClassifier): eta0 : double Constant by which the updates are multiplied. Defaults to 1. - class_weight : dict, {class_label : weight} or "auto" or None, optional + class_weight : dict, {class_label: weight} or "auto" or None, optional Preset for the class_weight fit parameter. Weights associated with classes. If not given, all classes @@ -59,11 +59,11 @@ class Perceptron(SGDClassifier): Attributes ---------- - `coef_` : array, shape = [1, n_features] if n_classes == 2 else [n_classes, - n_features] + coef_ : array, shape = [1, n_features] if n_classes == 2 else [n_classes,\ + n_features] Weights assigned to the features. - `intercept_` : array, shape = [1] if n_classes == 2 else [n_classes] + intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] Constants in decision function. Notes @@ -84,16 +84,16 @@ class Perceptron(SGDClassifier): http://en.wikipedia.org/wiki/Perceptron and references therein. """ def __init__(self, penalty=None, alpha=0.0001, fit_intercept=True, - n_iter=5, shuffle=False, verbose=0, eta0=1.0, - n_jobs=1, seed=0, class_weight=None, warm_start=False): + n_iter=5, shuffle=True, verbose=0, eta0=1.0, n_jobs=1, + random_state=0, class_weight=None, warm_start=False): super(Perceptron, self).__init__(loss="perceptron", penalty=penalty, - alpha=alpha, rho=0, + alpha=alpha, l1_ratio=0, fit_intercept=fit_intercept, n_iter=n_iter, shuffle=shuffle, verbose=verbose, - seed=seed, + random_state=random_state, learning_rate="constant", eta0=eta0, power_t=0.5, diff --git a/sklearn/linear_model/randomized_l1.py b/sklearn/linear_model/randomized_l1.py index 0bc874f2daad3..04a3a2ee87dd7 100644 --- a/sklearn/linear_model/randomized_l1.py +++ b/sklearn/linear_model/randomized_l1.py @@ -5,22 +5,25 @@ # Author: Gael Varoquaux, Alexandre Gramfort # -# License: BSD Style. +# License: BSD 3 clause import itertools from abc import ABCMeta, abstractmethod +import warnings import numpy as np from scipy.sparse import issparse +from scipy import sparse from scipy.interpolate import interp1d from .base import center_data from ..base import BaseEstimator, TransformerMixin -from ..utils import as_float_array, check_random_state, safe_asarray, \ - check_arrays -from ..externals.joblib import Parallel, delayed +from ..externals import six +from ..externals.joblib import Memory, Parallel, delayed +from ..utils import (as_float_array, check_random_state, check_X_y, + check_array, safe_mask, ConvergenceWarning) +from ..utils.validation import check_is_fitted from .least_angle import lars_path, LassoLarsIC from .logistic import LogisticRegression -from ..externals.joblib import Memory ############################################################################### @@ -35,33 +38,33 @@ def _resample_model(estimator_func, X, y, scaling=.5, n_resampling=200, if not (0 < scaling < 1): raise ValueError( - "'scaling' should be between 0 and 1. Got %r instead." % scaling) + "'scaling' should be between 0 and 1. Got %r instead." % scaling) scaling = 1. - scaling scores_ = 0.0 for active_set in Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch)( - delayed(estimator_func)(X, y, - weights=scaling * random_state.random_integers(0, - 1, size=(n_features,)), - mask=(random_state.rand(n_samples) < sample_fraction), - verbose=max(0, verbose - 1), - **params) - for _ in range(n_resampling)): - scores_ += active_set.astype(np.float) + delayed(estimator_func)( + X, y, weights=scaling * random_state.random_integers( + 0, 1, size=(n_features,)), + mask=(random_state.rand(n_samples) < sample_fraction), + verbose=max(0, verbose - 1), + **params) + for _ in range(n_resampling)): + scores_ += active_set scores_ /= n_resampling return scores_ -class BaseRandomizedLinearModel(BaseEstimator, TransformerMixin): +class BaseRandomizedLinearModel(six.with_metaclass(ABCMeta, BaseEstimator, + TransformerMixin)): """Base class to implement randomized linear models for feature selection This implements the strategy by Meinshausen and Buhlman: stability selection with randomized sampling, and random re-weighting of the penalty. """ - __metaclass__ = ABCMeta @abstractmethod def __init__(self): @@ -74,18 +77,18 @@ def fit(self, X, y): Parameters ---------- - X : array-like, shape = [n_samples, n_features] - training data. + X : array-like, sparse matrix shape = [n_samples, n_features] + Training data. y : array-like, shape = [n_samples] - target values. + Target values. Returns ------- self : object - returns an instance of self. + Returns an instance of self. """ - X, y = check_arrays(X, y, sparse_format='dense') + X, y = check_X_y(X, y, ['csr', 'csc', 'coo'], y_numeric=True) X = as_float_array(X, copy=False) n_samples, n_features = X.shape @@ -95,20 +98,17 @@ def fit(self, X, y): estimator_func, params = self._make_estimator_and_params(X, y) memory = self.memory - if isinstance(memory, basestring): + if isinstance(memory, six.string_types): memory = Memory(cachedir=memory) - scores_ = memory.cache(_resample_model, - ignore=['verbose', 'n_jobs', 'pre_dispatch'])( - estimator_func, X, y, - scaling=self.scaling, - n_resampling=self.n_resampling, - n_jobs=self.n_jobs, - verbose=self.verbose, - pre_dispatch=self.pre_dispatch, - random_state=self.random_state, - sample_fraction=self.sample_fraction, - **params) + scores_ = memory.cache( + _resample_model, ignore=['verbose', 'n_jobs', 'pre_dispatch'] + )( + estimator_func, X, y, + scaling=self.scaling, n_resampling=self.n_resampling, + n_jobs=self.n_jobs, verbose=self.verbose, + pre_dispatch=self.pre_dispatch, random_state=self.random_state, + sample_fraction=self.sample_fraction, **params) if scores_.ndim == 1: scores_ = scores_[:, np.newaxis] @@ -122,6 +122,8 @@ def _make_estimator_and_params(self, X, y): def get_support(self, indices=False): """Return a mask, or list, of the features/indices selected.""" + check_is_fitted(self, 'scores_') + mask = self.scores_ > self.selection_threshold return mask if not indices else np.where(mask)[0] @@ -129,10 +131,11 @@ def get_support(self, indices=False): # Should we add an intermediate base class? def transform(self, X): """Transform a new matrix using the selected features""" - mask = self.get_support(indices=issparse(X)) + mask = self.get_support() + X = check_array(X) if len(mask) != X.shape[1]: raise ValueError("X has a different shape than during fitting.") - return safe_asarray(X)[:, mask] + return check_array(X)[:, safe_mask(X, mask)] def inverse_transform(self, X): """Transform a new matrix using the selected features""" @@ -150,7 +153,7 @@ def inverse_transform(self, X): def _randomized_lasso(X, y, weights, mask, alpha=1., verbose=False, precompute=False, eps=np.finfo(np.float).eps, max_iter=500): - X = X[mask] + X = X[safe_mask(X, mask)] y = y[mask] # Center X and y to avoid fit the intercept @@ -160,11 +163,13 @@ def _randomized_lasso(X, y, weights, mask, alpha=1., verbose=False, alpha = np.atleast_1d(np.asarray(alpha, dtype=np.float)) X = (1 - weights) * X - alphas_, _, coef_ = lars_path(X, y, - Gram=precompute, copy_X=False, - copy_Gram=False, alpha_min=np.min(alpha), - method='lasso', verbose=verbose, - max_iter=max_iter, eps=eps) + with warnings.catch_warnings(): + warnings.simplefilter('ignore', ConvergenceWarning) + alphas_, _, coef_ = lars_path(X, y, + Gram=precompute, copy_X=False, + copy_Gram=False, alpha_min=np.min(alpha), + method='lasso', verbose=verbose, + max_iter=max_iter, eps=eps) if len(alpha) > 1: if len(alphas_) > 1: # np.min(alpha) < alpha_min @@ -179,7 +184,7 @@ def _randomized_lasso(X, y, weights, mask, alpha=1., verbose=False, class RandomizedLasso(BaseRandomizedLinearModel): - """Randomized Lasso + """Randomized Lasso. Randomized Lasso works by resampling the train data and computing a Lasso on each resampling. In short, the features selected more @@ -187,20 +192,26 @@ class RandomizedLasso(BaseRandomizedLinearModel): Parameters ---------- - alpha : float, 'aic', or 'bic' + alpha : float, 'aic', or 'bic', optional The regularization parameter alpha parameter in the Lasso. Warning: this is not the alpha parameter in the stability selection article which is scaling. - scaling : float + scaling : float, optional The alpha parameter in the stability selection article used to randomly scale the features. Should be between 0 and 1. - sample_fraction : float + sample_fraction : float, optional The fraction of samples to be used in each randomized design. Should be between 0 and 1. If 1, all samples are used. - fit_intercept : boolean + n_resampling : int, optional + Number of randomized models. + + selection_threshold: float, optional + The score above which features should be selected. + + fit_intercept : boolean, optional whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). @@ -208,8 +219,8 @@ class RandomizedLasso(BaseRandomizedLinearModel): verbose : boolean or integer, optional Sets the verbosity amount - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default True + If True, the regressors X will be normalized before regression. precompute : True | False | 'auto' Whether to use a precomputed Gram matrix to speed up @@ -242,7 +253,7 @@ class RandomizedLasso(BaseRandomizedLinearModel): explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - - None, in which case all the jobs are immediatly + - None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs @@ -255,14 +266,14 @@ class RandomizedLasso(BaseRandomizedLinearModel): memory : Instance of joblib.Memory or string Used for internal caching. By default, no caching is done. - If a string is given, it is thepath to the caching directory. + If a string is given, it is the path to the caching directory. Attributes ---------- - `scores_` : array, shape = [n_features] + scores_ : array, shape = [n_features] Feature scores between 0 and 1. - `all_scores_` : array, shape = [n_features, n_reg_parameter] + all_scores_ : array, shape = [n_features, n_reg_parameter] Feature scores between 0 and 1 for all values of the regularization \ parameter. The reference article suggests ``scores_`` is the max of \ ``all_scores_``. @@ -322,9 +333,9 @@ def _make_estimator_and_params(self, X, y): eps=self.eps) model.fit(X, y) self.alpha_ = alpha = model.alpha_ - return _randomized_lasso, dict(alpha=alpha, - max_iter=self.max_iter, eps=self.eps, - precompute=self.precompute) + return _randomized_lasso, dict(alpha=alpha, max_iter=self.max_iter, + eps=self.eps, + precompute=self.precompute) ############################################################################### @@ -332,9 +343,14 @@ def _make_estimator_and_params(self, X, y): def _randomized_logistic(X, y, weights, mask, C=1., verbose=False, fit_intercept=True, tol=1e-3): - X = X[mask] + X = X[safe_mask(X, mask)] y = y[mask] - X = (1 - weights) * X + if issparse(X): + size = len(weights) + weight_dia = sparse.dia_matrix((1 - weights, 0), (size, size)) + X = X * weight_dia + else: + X *= (1 - weights) C = np.atleast_1d(np.asarray(C, dtype=np.float)) scores = np.zeros((X.shape[1], len(C)), dtype=np.bool) @@ -342,10 +358,10 @@ def _randomized_logistic(X, y, weights, mask, C=1., verbose=False, for this_C, this_scores in zip(C, scores.T): # XXX : would be great to do it with a warm_start ... clf = LogisticRegression(C=this_C, tol=tol, penalty='l1', dual=False, - fit_intercept=fit_intercept) + fit_intercept=fit_intercept) clf.fit(X, y) this_scores[:] = np.any( - np.abs(clf.coef_) > 10 * np.finfo(np.float).eps, axis=0) + np.abs(clf.coef_) > 10 * np.finfo(np.float).eps, axis=0) return scores @@ -358,18 +374,24 @@ class RandomizedLogisticRegression(BaseRandomizedLinearModel): Parameters ---------- - C : float + C : float, optional, default=1 The regularization parameter C in the LogisticRegression. - scaling : float + scaling : float, optional, default=0.5 The alpha parameter in the stability selection article used to randomly scale the features. Should be between 0 and 1. - sample_fraction : float + sample_fraction : float, optional, default=0.75 The fraction of samples to be used in each randomized design. Should be between 0 and 1. If 1, all samples are used. - fit_intercept : boolean + n_resampling : int, optional, default=200 + Number of randomized models. + + selection_threshold : float, optional, default=0.25 + The score above which features should be selected. + + fit_intercept : boolean, optional, default=True whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). @@ -377,10 +399,10 @@ class RandomizedLogisticRegression(BaseRandomizedLinearModel): verbose : boolean or integer, optional Sets the verbosity amount - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default=True + If True, the regressors X will be normalized before regression. - tol : float, optional + tol : float, optional, default=1e-3 tolerance for stopping criteria of LogisticRegression n_jobs : integer, optional @@ -399,7 +421,7 @@ class RandomizedLogisticRegression(BaseRandomizedLinearModel): explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - - None, in which case all the jobs are immediatly + - None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs @@ -412,14 +434,14 @@ class RandomizedLogisticRegression(BaseRandomizedLinearModel): memory : Instance of joblib.Memory or string Used for internal caching. By default, no caching is done. - If a string is given, it is thepath to the caching directory. + If a string is given, it is the path to the caching directory. Attributes ---------- - `scores_` : array, shape = [n_features] + scores_ : array, shape = [n_features] Feature scores between 0 and 1. - `all_scores_` : array, shape = [n_features, n_reg_parameter] + all_scores_ : array, shape = [n_features, n_reg_parameter] Feature scores between 0 and 1 for all values of the regularization \ parameter. The reference article suggests ``scores_`` is the max \ of ``all_scores_``. @@ -431,7 +453,7 @@ class RandomizedLogisticRegression(BaseRandomizedLinearModel): Notes ----- - See examples/linear_model/plot_randomized_lasso.py for an example. + See examples/linear_model/plot_sparse_recovery.py for an example. References ---------- @@ -475,7 +497,7 @@ def _make_estimator_and_params(self, X, y): def _center_data(self, X, y, fit_intercept, normalize=False): """Center the data in X but not in y""" X, _, Xmean, _, X_std = center_data(X, y, fit_intercept, - normalize=normalize) + normalize=normalize) return X, y, Xmean, y, X_std @@ -484,13 +506,15 @@ def _center_data(self, X, y, fit_intercept, normalize=False): def _lasso_stability_path(X, y, mask, weights, eps): "Inner loop of lasso_stability_path" X = X * weights[np.newaxis, :] - X = X[mask, :] + X = X[safe_mask(X, mask), :] y = y[mask] alpha_max = np.max(np.abs(np.dot(X.T, y))) / X.shape[0] alpha_min = eps * alpha_max # set for early stopping in path - alphas, _, coefs = lars_path(X, y, method='lasso', verbose=False, - alpha_min=alpha_min) + with warnings.catch_warnings(): + warnings.simplefilter('ignore', ConvergenceWarning) + alphas, _, coefs = lars_path(X, y, method='lasso', verbose=False, + alpha_min=alpha_min) # Scale alpha by alpha_max alphas /= alphas[0] # Sort alphas in assending order @@ -521,25 +545,25 @@ def lasso_stability_path(X, y, scaling=0.5, random_state=None, y : array-like, shape = [n_samples] target values. - scaling : float + scaling : float, optional, default=0.5 The alpha parameter in the stability selection article used to randomly scale the features. Should be between 0 and 1. - random_state : integer or numpy.RandomState, optional + random_state : integer or numpy.random.RandomState, optional The generator used to randomize the design. - n_resampling : int + n_resampling : int, optional, default=200 Number of randomized models. - n_grid : int + n_grid : int, optional, default=100 Number of grid points. The path is linearly reinterpolated on a grid between 0 and 1 before computing the scores. - sample_fraction : float + sample_fraction : float, optional, default=0.75 The fraction of samples to be used in each randomized design. Should be between 0 and 1. If 1, all samples are used. - eps : float + eps : float, optional Smallest value of alpha / alpha_max considered n_jobs : integer, optional @@ -559,7 +583,7 @@ def lasso_stability_path(X, y, scaling=0.5, random_state=None, Notes ----- - See examples/linear_model/plot_randomized_lasso.py for an example. + See examples/linear_model/plot_sparse_recovery.py for an example. """ rng = check_random_state(random_state) @@ -570,12 +594,12 @@ def lasso_stability_path(X, y, scaling=0.5, random_state=None, n_samples, n_features = X.shape paths = Parallel(n_jobs=n_jobs, verbose=verbose)( - delayed(_lasso_stability_path)(X, y, - mask=rng.rand(n_samples) < sample_fraction, - weights=1. - scaling * rng.random_integers(0, - 1, size=(n_features,)), - eps=eps) - for k in xrange(n_resampling)) + delayed(_lasso_stability_path)( + X, y, mask=rng.rand(n_samples) < sample_fraction, + weights=1. - scaling * rng.random_integers(0, 1, + size=(n_features,)), + eps=eps) + for k in range(n_resampling)) all_alphas = sorted(list(set(itertools.chain(*[p[0] for p in paths])))) # Take approximately n_grid values diff --git a/sklearn/linear_model/ransac.py b/sklearn/linear_model/ransac.py new file mode 100644 index 0000000000000..c04a27b5fa398 --- /dev/null +++ b/sklearn/linear_model/ransac.py @@ -0,0 +1,379 @@ +# coding: utf-8 + +# Author: Johannes Schönberger +# +# License: BSD 3 clause + +import numpy as np + +from ..base import BaseEstimator, MetaEstimatorMixin, RegressorMixin, clone +from ..utils import check_random_state, check_array, check_consistent_length +from ..utils.random import sample_without_replacement +from ..utils.validation import check_is_fitted +from .base import LinearRegression + + +_EPSILON = np.spacing(1) + + +def _dynamic_max_trials(n_inliers, n_samples, min_samples, probability): + """Determine number trials such that at least one outlier-free subset is + sampled for the given inlier/outlier ratio. + + Parameters + ---------- + n_inliers : int + Number of inliers in the data. + + n_samples : int + Total number of samples in the data. + + min_samples : int + Minimum number of samples chosen randomly from original data. + + probability : float + Probability (confidence) that one outlier-free sample is generated. + + Returns + ------- + trials : int + Number of trials. + + """ + inlier_ratio = n_inliers / float(n_samples) + nom = max(_EPSILON, 1 - probability) + denom = max(_EPSILON, 1 - inlier_ratio ** min_samples) + if nom == 1: + return 0 + if denom == 1: + return float('inf') + return abs(float(np.ceil(np.log(nom) / np.log(denom)))) + + +class RANSACRegressor(BaseEstimator, MetaEstimatorMixin, RegressorMixin): + """RANSAC (RANdom SAmple Consensus) algorithm. + + RANSAC is an iterative algorithm for the robust estimation of parameters + from a subset of inliers from the complete data set. More information can + be found in the general documentation of linear models. + + A detailed description of the algorithm can be found in the documentation + of the ``linear_model`` sub-package. + + Parameters + ---------- + base_estimator : object, optional + Base estimator object which implements the following methods: + + * `fit(X, y)`: Fit model to given training data and target values. + * `score(X, y)`: Returns the mean accuracy on the given test data, + which is used for the stop criterion defined by `stop_score`. + Additionally, the score is used to decide which of two equally + large consensus sets is chosen as the better one. + + If `base_estimator` is None, then + ``base_estimator=sklearn.linear_model.LinearRegression()`` is used for + target values of dtype float. + + Note that the current implementation only supports regression + estimators. + + min_samples : int (>= 1) or float ([0, 1]), optional + Minimum number of samples chosen randomly from original data. Treated + as an absolute number of samples for `min_samples >= 1`, treated as a + relative number `ceil(min_samples * X.shape[0]`) for + `min_samples < 1`. This is typically chosen as the minimal number of + samples necessary to estimate the given `base_estimator`. By default a + ``sklearn.linear_model.LinearRegression()`` estimator is assumed and + `min_samples` is chosen as ``X.shape[1] + 1``. + + residual_threshold : float, optional + Maximum residual for a data sample to be classified as an inlier. + By default the threshold is chosen as the MAD (median absolute + deviation) of the target values `y`. + + is_data_valid : callable, optional + This function is called with the randomly selected data before the + model is fitted to it: `is_data_valid(X, y)`. If its return value is + False the current randomly chosen sub-sample is skipped. + + is_model_valid : callable, optional + This function is called with the estimated model and the randomly + selected data: `is_model_valid(model, X, y)`. If its return value is + False the current randomly chosen sub-sample is skipped. + Rejecting samples with this function is computationally costlier than + with `is_data_valid`. `is_model_valid` should therefore only be used if + the estimated model is needed for making the rejection decision. + + max_trials : int, optional + Maximum number of iterations for random sample selection. + + stop_n_inliers : int, optional + Stop iteration if at least this number of inliers are found. + + stop_score : float, optional + Stop iteration if score is greater equal than this threshold. + + stop_probability : float in range [0, 1], optional + RANSAC iteration stops if at least one outlier-free set of the training + data is sampled in RANSAC. This requires to generate at least N + samples (iterations):: + + N >= log(1 - probability) / log(1 - e**m) + + where the probability (confidence) is typically set to high value such + as 0.99 (the default) and e is the current fraction of inliers w.r.t. + the total number of samples. + + residual_metric : callable, optional + Metric to reduce the dimensionality of the residuals to 1 for + multi-dimensional target values ``y.shape[1] > 1``. By default the sum + of absolute differences is used:: + + lambda dy: np.sum(np.abs(dy), axis=1) + + random_state : integer or numpy.RandomState, optional + The generator used to initialize the centers. If an integer is + given, it fixes the seed. Defaults to the global numpy random + number generator. + + Attributes + ---------- + estimator_ : object + Best fitted model (copy of the `base_estimator` object). + + n_trials_ : int + Number of random selection trials until one of the stop criteria is + met. It is always ``<= max_trials``. + + inlier_mask_ : bool array of shape [n_samples] + Boolean mask of inliers classified as ``True``. + + References + ---------- + .. [1] http://en.wikipedia.org/wiki/RANSAC + .. [2] http://www.cs.columbia.edu/~belhumeur/courses/compPhoto/ransac.pdf + .. [3] http://www.bmva.org/bmvc/2009/Papers/Paper355/Paper355.pdf + """ + + def __init__(self, base_estimator=None, min_samples=None, + residual_threshold=None, is_data_valid=None, + is_model_valid=None, max_trials=100, + stop_n_inliers=np.inf, stop_score=np.inf, + stop_probability=0.99, residual_metric=None, + random_state=None): + + self.base_estimator = base_estimator + self.min_samples = min_samples + self.residual_threshold = residual_threshold + self.is_data_valid = is_data_valid + self.is_model_valid = is_model_valid + self.max_trials = max_trials + self.stop_n_inliers = stop_n_inliers + self.stop_score = stop_score + self.stop_probability = stop_probability + self.residual_metric = residual_metric + self.random_state = random_state + + def fit(self, X, y): + """Fit estimator using RANSAC algorithm. + + Parameters + ---------- + X : array-like or sparse matrix, shape [n_samples, n_features] + Training data. + + y : array-like, shape = [n_samples] or [n_samples, n_targets] + Target values. + + Raises + ------ + ValueError + If no valid consensus set could be found. This occurs if + `is_data_valid` and `is_model_valid` return False for all + `max_trials` randomly chosen sub-samples. + + """ + X = check_array(X, accept_sparse='csr') + y = check_array(y, ensure_2d=False) + if y.ndim == 1: + y = y.reshape(-1, 1) + check_consistent_length(X, y) + + if self.base_estimator is not None: + base_estimator = clone(self.base_estimator) + else: + base_estimator = LinearRegression() + + if self.min_samples is None: + # assume linear model by default + min_samples = X.shape[1] + 1 + elif 0 < self.min_samples < 1: + min_samples = np.ceil(self.min_samples * X.shape[0]) + elif self.min_samples >= 1: + if self.min_samples % 1 != 0: + raise ValueError("Absolute number of samples must be an " + "integer value.") + min_samples = self.min_samples + else: + raise ValueError("Value for `min_samples` must be scalar and " + "positive.") + if min_samples > X.shape[0]: + raise ValueError("`min_samples` may not be larger than number " + "of samples ``X.shape[0]``.") + + if self.stop_probability < 0 or self.stop_probability > 1: + raise ValueError("`stop_probability` must be in range [0, 1].") + + if self.residual_threshold is None: + # MAD (median absolute deviation) + residual_threshold = np.median(np.abs(y - np.median(y))) + else: + residual_threshold = self.residual_threshold + + if self.residual_metric is None: + residual_metric = lambda dy: np.sum(np.abs(dy), axis=1) + else: + residual_metric = self.residual_metric + + random_state = check_random_state(self.random_state) + + try: # Not all estimator accept a random_state + base_estimator.set_params(random_state=random_state) + except ValueError: + pass + + n_inliers_best = 0 + score_best = np.inf + inlier_mask_best = None + X_inlier_best = None + y_inlier_best = None + + # number of data samples + n_samples = X.shape[0] + sample_idxs = np.arange(n_samples) + + n_samples, _ = X.shape + + for self.n_trials_ in range(1, self.max_trials + 1): + + # choose random sample set + subset_idxs = sample_without_replacement(n_samples, min_samples, + random_state=random_state) + X_subset = X[subset_idxs] + y_subset = y[subset_idxs] + + # check if random sample set is valid + if (self.is_data_valid is not None + and not self.is_data_valid(X_subset, y_subset)): + continue + + # fit model for current random sample set + base_estimator.fit(X_subset, y_subset) + + # check if estimated model is valid + if (self.is_model_valid is not None and not + self.is_model_valid(base_estimator, X_subset, y_subset)): + continue + + # residuals of all data for current random sample model + y_pred = base_estimator.predict(X) + if y_pred.ndim == 1: + y_pred = y_pred[:, None] + + residuals_subset = residual_metric(y_pred - y) + + # classify data into inliers and outliers + inlier_mask_subset = residuals_subset < residual_threshold + n_inliers_subset = np.sum(inlier_mask_subset) + + # less inliers -> skip current random sample + if n_inliers_subset < n_inliers_best: + continue + + # extract inlier data set + inlier_idxs_subset = sample_idxs[inlier_mask_subset] + X_inlier_subset = X[inlier_idxs_subset] + y_inlier_subset = y[inlier_idxs_subset] + + # score of inlier data set + score_subset = base_estimator.score(X_inlier_subset, + y_inlier_subset) + + # same number of inliers but worse score -> skip current random + # sample + if (n_inliers_subset == n_inliers_best + and score_subset < score_best): + continue + + # save current random sample as best sample + n_inliers_best = n_inliers_subset + score_best = score_subset + inlier_mask_best = inlier_mask_subset + X_inlier_best = X_inlier_subset + y_inlier_best = y_inlier_subset + + # break if sufficient number of inliers or score is reached + if (n_inliers_best >= self.stop_n_inliers + or score_best >= self.stop_score + or self.n_trials_ + >= _dynamic_max_trials(n_inliers_best, n_samples, + min_samples, + self.stop_probability)): + break + + # if none of the iterations met the required criteria + if inlier_mask_best is None: + raise ValueError( + "RANSAC could not find valid consensus set, because" + " either the `residual_threshold` rejected all the samples or" + " `is_data_valid` and `is_model_valid` returned False for all" + " `max_trials` randomly ""chosen sub-samples. Consider " + "relaxing the ""constraints.") + + # estimate final model using all inliers + base_estimator.fit(X_inlier_best, y_inlier_best) + + self.estimator_ = base_estimator + self.inlier_mask_ = inlier_mask_best + return self + + def predict(self, X): + """Predict using the estimated model. + + This is a wrapper for `estimator_.predict(X)`. + + Parameters + ---------- + X : numpy array of shape [n_samples, n_features] + + Returns + ------- + y : array, shape = [n_samples] or [n_samples, n_targets] + Returns predicted values. + """ + check_is_fitted(self, 'estimator_') + + return self.estimator_.predict(X) + + def score(self, X, y): + """Returns the score of the prediction. + + This is a wrapper for `estimator_.score(X, y)`. + + Parameters + ---------- + X : numpy array or sparse matrix of shape [n_samples, n_features] + Training data. + + y : array, shape = [n_samples] or [n_samples, n_targets] + Target values. + + Returns + ------- + z : float + Score of the prediction. + """ + check_is_fitted(self, 'estimator_') + + return self.estimator_.score(X, y) diff --git a/sklearn/linear_model/ridge.py b/sklearn/linear_model/ridge.py index 98e44c974b1a2..9cf6ed43077e0 100644 --- a/sklearn/linear_model/ridge.py +++ b/sklearn/linear_model/ridge.py @@ -5,7 +5,8 @@ # Author: Mathieu Blondel # Reuben Fletcher-Costin # Fabian Pedregosa -# License: Simplified BSD +# Michael Eickenberg +# License: BSD 3 clause from abc import ABCMeta, abstractmethod @@ -19,43 +20,253 @@ from .base import LinearClassifierMixin, LinearModel from ..base import RegressorMixin from ..utils.extmath import safe_sparse_dot -from ..utils import safe_asarray +from ..utils import check_X_y +from ..utils import compute_sample_weight, compute_class_weight +from ..utils import column_or_1d from ..preprocessing import LabelBinarizer from ..grid_search import GridSearchCV +from ..externals import six +from ..metrics.scorer import check_scoring -def ridge_regression(X, y, alpha, sample_weight=1.0, solver='auto', - max_iter=None, tol=1e-3): +def _solve_sparse_cg(X, y, alpha, max_iter=None, tol=1e-3, verbose=0): + n_samples, n_features = X.shape + X1 = sp_linalg.aslinearoperator(X) + coefs = np.empty((y.shape[1], n_features)) + + if n_features > n_samples: + def create_mv(curr_alpha): + def _mv(x): + return X1.matvec(X1.rmatvec(x)) + curr_alpha * x + return _mv + else: + def create_mv(curr_alpha): + def _mv(x): + return X1.rmatvec(X1.matvec(x)) + curr_alpha * x + return _mv + + for i in range(y.shape[1]): + y_column = y[:, i] + + mv = create_mv(alpha[i]) + if n_features > n_samples: + # kernel ridge + # w = X.T * inv(X X^t + alpha*Id) y + C = sp_linalg.LinearOperator( + (n_samples, n_samples), matvec=mv, dtype=X.dtype) + coef, info = sp_linalg.cg(C, y_column, tol=tol) + coefs[i] = X1.rmatvec(coef) + else: + # linear ridge + # w = inv(X^t X + alpha*Id) * X.T y + y_column = X1.rmatvec(y_column) + C = sp_linalg.LinearOperator( + (n_features, n_features), matvec=mv, dtype=X.dtype) + coefs[i], info = sp_linalg.cg(C, y_column, maxiter=max_iter, + tol=tol) + if info < 0: + raise ValueError("Failed with error code %d" % info) + + if max_iter is None and info > 0 and verbose: + warnings.warn("sparse_cg did not converge after %d iterations." % + info) + + return coefs + + +def _solve_lsqr(X, y, alpha, max_iter=None, tol=1e-3): + n_samples, n_features = X.shape + coefs = np.empty((y.shape[1], n_features)) + + # According to the lsqr documentation, alpha = damp^2. + sqrt_alpha = np.sqrt(alpha) + + for i in range(y.shape[1]): + y_column = y[:, i] + coefs[i] = sp_linalg.lsqr(X, y_column, damp=sqrt_alpha[i], + atol=tol, btol=tol, iter_lim=max_iter)[0] + + return coefs + + +def _solve_cholesky(X, y, alpha): + # w = inv(X^t X + alpha*Id) * X.T y + n_samples, n_features = X.shape + n_targets = y.shape[1] + + A = safe_sparse_dot(X.T, X, dense_output=True) + Xy = safe_sparse_dot(X.T, y, dense_output=True) + + one_alpha = np.array_equal(alpha, len(alpha) * [alpha[0]]) + + if one_alpha: + A.flat[::n_features + 1] += alpha[0] + return linalg.solve(A, Xy, sym_pos=True, + overwrite_a=True).T + else: + coefs = np.empty([n_targets, n_features]) + for coef, target, current_alpha in zip(coefs, Xy.T, alpha): + A.flat[::n_features + 1] += current_alpha + coef[:] = linalg.solve(A, target, sym_pos=True, + overwrite_a=False).ravel() + A.flat[::n_features + 1] -= current_alpha + return coefs + + +def _solve_cholesky_kernel(K, y, alpha, sample_weight=None, copy=False): + # dual_coef = inv(X X^t + alpha*Id) y + n_samples = K.shape[0] + n_targets = y.shape[1] + + if copy: + K = K.copy() + + alpha = np.atleast_1d(alpha) + one_alpha = (alpha == alpha[0]).all() + has_sw = isinstance(sample_weight, np.ndarray) \ + or sample_weight not in [1.0, None] + + if has_sw: + # Unlike other solvers, we need to support sample_weight directly + # because K might be a pre-computed kernel. + sw = np.sqrt(np.atleast_1d(sample_weight)) + y = y * sw[:, np.newaxis] + K *= np.outer(sw, sw) + + if one_alpha: + # Only one penalty, we can solve multi-target problems in one time. + K.flat[::n_samples + 1] += alpha[0] + + try: + # Note: we must use overwrite_a=False in order to be able to + # use the fall-back solution below in case a LinAlgError + # is raised + dual_coef = linalg.solve(K, y, sym_pos=True, + overwrite_a=False) + except np.linalg.LinAlgError: + warnings.warn("Singular matrix in solving dual problem. Using " + "least-squares solution instead.") + dual_coef = linalg.lstsq(K, y)[0] + + # K is expensive to compute and store in memory so change it back in + # case it was user-given. + K.flat[::n_samples + 1] -= alpha[0] + + if has_sw: + dual_coef *= sw[:, np.newaxis] + + return dual_coef + else: + # One penalty per target. We need to solve each target separately. + dual_coefs = np.empty([n_targets, n_samples]) + + for dual_coef, target, current_alpha in zip(dual_coefs, y.T, alpha): + K.flat[::n_samples + 1] += current_alpha + + dual_coef[:] = linalg.solve(K, target, sym_pos=True, + overwrite_a=False).ravel() + + K.flat[::n_samples + 1] -= current_alpha + + if has_sw: + dual_coefs *= sw[np.newaxis, :] + + return dual_coefs.T + + +def _solve_svd(X, y, alpha): + U, s, Vt = linalg.svd(X, full_matrices=False) + idx = s > 1e-15 # same default value as scipy.linalg.pinv + s_nnz = s[idx][:, np.newaxis] + UTy = np.dot(U.T, y) + d = np.zeros((s.size, alpha.size)) + d[idx] = s_nnz / (s_nnz ** 2 + alpha) + d_UT_y = d * UTy + return np.dot(Vt.T, d_UT_y).T + + +def _deprecate_dense_cholesky(solver): + if solver == 'dense_cholesky': + warnings.warn(DeprecationWarning( + "The name 'dense_cholesky' is deprecated and will " + "be removed in 0.17. Use 'cholesky' instead. ")) + solver = 'cholesky' + + return solver + + +def _rescale_data(X, y, sample_weight): + """Rescale data so as to support sample_weight""" + n_samples = X.shape[0] + sample_weight = sample_weight * np.ones(n_samples) + sample_weight = np.sqrt(sample_weight) + sw_matrix = sparse.dia_matrix((sample_weight, 0), + shape=(n_samples, n_samples)) + X = safe_sparse_dot(sw_matrix, X) + y = safe_sparse_dot(sw_matrix, y) + return X, y + + +def ridge_regression(X, y, alpha, sample_weight=None, solver='auto', + max_iter=None, tol=1e-3, verbose=0): """Solve the ridge equation by the method of normal equations. Parameters ---------- - X : {array-like, sparse matrix, LinearOperator}, shape = [n_samples, n_features] + X : {array-like, sparse matrix, LinearOperator}, + shape = [n_samples, n_features] Training data - y : array-like, shape = [n_samples] or [n_samples, n_responses] + y : array-like, shape = [n_samples] or [n_samples, n_targets] Target values + alpha : {float, array-like}, + shape = [n_targets] if array-like + The l_2 penalty to be used. If an array is passed, penalties are + assumed to be specific to targets + max_iter : int, optional Maximum number of iterations for conjugate gradient solver. The default value is determined by scipy.sparse.linalg. sample_weight : float or numpy array of shape [n_samples] - Individual weights for each sample + Individual weights for each sample. If sample_weight is set, then + the solver will automatically be set to 'cholesky' - solver : {'auto', 'dense_cholesky', 'sparse_cg'}, optional - Solver to use in the computational routines. 'dense_cholesky' - will use the standard scipy.linalg.solve function, 'sparse_cg' - will use the conjugate gradient solver as found in - scipy.sparse.linalg.cg while 'auto' will chose the most - appropriate depending on the matrix X. + solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg'} + Solver to use in the computational routines: + + - 'auto' chooses the solver automatically based on the type of data. + + - 'svd' uses a Singular Value Decomposition of X to compute the Ridge + coefficients. More stable for singular matrices than + 'cholesky'. + + - 'cholesky' uses the standard scipy.linalg.solve function to + obtain a closed-form solution via a Cholesky decomposition of + dot(X.T, X) - tol: float + - 'sparse_cg' uses the conjugate gradient solver as found in + scipy.sparse.linalg.cg. As an iterative algorithm, this solver is + more appropriate than 'cholesky' for large-scale data + (possibility to set `tol` and `max_iter`). + + - 'lsqr' uses the dedicated regularized least-squares routine + scipy.sparse.linalg.lsqr. It is the fatest but may not be available + in old scipy versions. It also uses an iterative procedure. + + All three solvers support both dense and sparse data. + + tol : float Precision of the solution. + verbose : int + Verbosity level. Setting verbose > 0 will display additional information + depending on the solver used. + Returns ------- - coef: array, shape = [n_features] or [n_responses, n_features] + coef : array, shape = [n_features] or [n_targets, n_features] Weight vector(s). Notes @@ -65,120 +276,127 @@ def ridge_regression(X, y, alpha, sample_weight=1.0, solver='auto', n_samples, n_features = X.shape + if y.ndim > 2: + raise ValueError("Target y has the wrong shape %s" % str(y.shape)) + + ravel = False + if y.ndim == 1: + y = y.reshape(-1, 1) + ravel = True + + n_samples_, n_targets = y.shape + + if n_samples != n_samples_: + raise ValueError("Number of samples in X and y does not correspond:" + " %d != %d" % (n_samples, n_samples_)) + + has_sw = sample_weight is not None + + solver = _deprecate_dense_cholesky(solver) + if solver == 'auto': # cholesky if it's a dense array and cg in # any other case - if hasattr(X, '__array__'): - solver = 'dense_cholesky' + if not sparse.issparse(X) or has_sw: + solver = 'cholesky' else: solver = 'sparse_cg' + elif solver == 'lsqr' and not hasattr(sp_linalg, 'lsqr'): + warnings.warn("""lsqr not available on this machine, falling back + to sparse_cg.""") + solver = 'sparse_cg' + + if has_sw: + if np.atleast_1d(sample_weight).ndim > 1: + raise ValueError("Sample weights must be 1D array or scalar") + + # Sample weight can be implemented via a simple rescaling. + X, y = _rescale_data(X, y, sample_weight) + + # There should be either 1 or n_targets penalties + alpha = np.asarray(alpha).ravel() + if alpha.size not in [1, n_targets]: + raise ValueError("Number of targets and number of penalties " + "do not correspond: %d != %d" + % (alpha.size, n_targets)) + + if alpha.size == 1 and n_targets > 1: + alpha = np.repeat(alpha, n_targets) + + if solver not in ('sparse_cg', 'cholesky', 'svd', 'lsqr'): + raise ValueError('Solver %s not understood' % solver) + if solver == 'sparse_cg': - # gradient descent - X1 = sp_linalg.aslinearoperator(X) - if y.ndim == 1: - y1 = np.reshape(y, (-1, 1)) + coef = _solve_sparse_cg(X, y, alpha, max_iter, tol, verbose) + + elif solver == "lsqr": + coef = _solve_lsqr(X, y, alpha, max_iter, tol) + + elif solver == 'cholesky': + if n_features > n_samples: + K = safe_sparse_dot(X, X.T, dense_output=True) + try: + dual_coef = _solve_cholesky_kernel(K, y, alpha) + + coef = safe_sparse_dot(X.T, dual_coef, dense_output=True).T + except linalg.LinAlgError: + # use SVD solver if matrix is singular + solver = 'svd' + else: - y1 = y - coefs = np.empty((y1.shape[1], n_features)) - - for i in range(y1.shape[1]): - y_column = y1[:, i] - if n_features > n_samples: - # kernel ridge - # w = X.T * inv(X X^t + alpha*Id) y - def mv(x): - return X1.matvec(X1.rmatvec(x)) + alpha * x - C = sp_linalg.LinearOperator( - (n_samples, n_samples), matvec=mv, dtype=X.dtype) - coef, info = sp_linalg.cg(C, y_column, tol=tol) - coefs[i] = X1.rmatvec(coef) - else: - # ridge - # w = inv(X^t X + alpha*Id) * X.T y - def mv(x): - return X1.rmatvec(X1.matvec(x)) + alpha * x - y_column = X1.rmatvec(y_column) - C = sp_linalg.LinearOperator( - (n_features, n_features), matvec=mv, dtype=X.dtype) - coefs[i], info = sp_linalg.cg(C, y_column, maxiter=max_iter, - tol=tol) - if info != 0: - raise ValueError("Failed with error code %d" % info) - - if y.ndim == 1: - return np.ravel(coefs) - return coefs - else: - # normal equations (cholesky) method + try: + coef = _solve_cholesky(X, y, alpha) + except linalg.LinAlgError: + # use SVD solver if matrix is singular + solver = 'svd' + + if solver == 'svd': if sparse.issparse(X): - X = X.toarray() - if n_features > n_samples or \ - isinstance(sample_weight, np.ndarray) or \ - sample_weight != 1.0: + raise TypeError('SVD solver does not support sparse' + ' inputs currently') + coef = _solve_svd(X, y, alpha) - # kernel ridge - # w = X.T * inv(X X^t + alpha*Id) y - A = np.dot(X, X.T) - A.flat[::n_samples + 1] += alpha * sample_weight - coef = np.dot(X.T, linalg.solve(A, y, sym_pos=True, overwrite_a=True)) - else: - # ridge - # w = inv(X^t X + alpha*Id) * X.T y - A = np.dot(X.T, X) - A.flat[::n_features + 1] += alpha - coef = linalg.solve(A, np.dot(X.T, y), sym_pos=True, overwrite_a=True) + if ravel: + # When y was passed as a 1d-array, we flatten the coefficients. + coef = coef.ravel() - return coef.T + return coef -class _BaseRidge(LinearModel): - __metaclass__ = ABCMeta +class _BaseRidge(six.with_metaclass(ABCMeta, LinearModel)): @abstractmethod def __init__(self, alpha=1.0, fit_intercept=True, normalize=False, - copy_X=True, max_iter=None, tol=1e-3): + copy_X=True, max_iter=None, tol=1e-3, solver="auto"): self.alpha = alpha self.fit_intercept = fit_intercept self.normalize = normalize self.copy_X = copy_X + self.max_iter = max_iter self.tol = tol + self.solver = solver - def fit(self, X, y, sample_weight=1.0, solver='auto'): - """Fit Ridge regression model - - Parameters - ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] - Training data - - y : array-like, shape = [n_samples] or [n_samples, n_responses] - Target values + def fit(self, X, y, sample_weight=None): + X, y = check_X_y(X, y, ['csr', 'csc', 'coo'], dtype=np.float, + multi_output=True, y_numeric=True) - sample_weight : float or numpy array of shape [n_samples] - Individual weights for each sample + if ((sample_weight is not None) and + np.atleast_1d(sample_weight).ndim > 1): + raise ValueError("Sample weights must be 1D array or scalar") - solver : {'auto', 'dense_cholesky', 'sparse_cg'} - Solver to use in the computational - routines. 'dense_cholesky' will use the standard - scipy.linalg.solve function, 'sparse_cg' will use the - conjugate gradient solver as found in - scipy.sparse.linalg.cg while 'auto' will chose the most - appropriate depending on the matrix X. + X, y, X_mean, y_mean, X_std = self._center_data( + X, y, self.fit_intercept, self.normalize, self.copy_X, + sample_weight=sample_weight) - Returns - ------- - self : returns an instance of self. - """ - X = safe_asarray(X, dtype=np.float) - y = np.asarray(y, dtype=np.float) - - X, y, X_mean, y_mean, X_std = \ - self._center_data(X, y, self.fit_intercept, - self.normalize, self.copy_X) + solver = _deprecate_dense_cholesky(self.solver) - self.coef_ = ridge_regression(X, y, self.alpha, sample_weight, - solver, self.tol) + self.coef_ = ridge_regression(X, y, + alpha=self.alpha, + sample_weight=sample_weight, + max_iter=self.max_iter, + tol=self.tol, + solver=solver) self._set_intercept(X_mean, y_mean, X_std) return self @@ -190,42 +408,67 @@ class Ridge(_BaseRidge, RegressorMixin): the linear least squares function and regularization is given by the l2-norm. Also known as Ridge Regression or Tikhonov regularization. This estimator has built-in support for multi-variate regression - (i.e., when y is a 2d-array of shape [n_samples, n_responses]). + (i.e., when y is a 2d-array of shape [n_samples, n_targets]). Parameters ---------- - alpha : float + alpha : {float, array-like} + shape = [n_targets] Small positive values of alpha improve the conditioning of the problem and reduce the variance of the estimates. Alpha corresponds to ``(2*C)^-1`` in other linear models such as LogisticRegression or - LinearSVC. + LinearSVC. If an array is passed, penalties are assumed to be specific + to the targets. Hence they must correspond in number. + + copy_X : boolean, optional, default True + If True, X will be copied; else, it may be overwritten. fit_intercept : boolean Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). - normalize : boolean, optional - If True, the regressors X are normalized - - copy_X : boolean, optional, default True - If True, X will be copied; else, it may be overwritten. - max_iter : int, optional Maximum number of iterations for conjugate gradient solver. The default value is determined by scipy.sparse.linalg. + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. + + solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg'} + Solver to use in the computational routines: + + - 'auto' chooses the solver automatically based on the type of data. + + - 'svd' uses a Singular Value Decomposition of X to compute the Ridge + coefficients. More stable for singular matrices than + 'cholesky'. + + - 'cholesky' uses the standard scipy.linalg.solve function to + obtain a closed-form solution. + + - 'sparse_cg' uses the conjugate gradient solver as found in + scipy.sparse.linalg.cg. As an iterative algorithm, this solver is + more appropriate than 'cholesky' for large-scale data + (possibility to set `tol` and `max_iter`). + + - 'lsqr' uses the dedicated regularized least-squares routine + scipy.sparse.linalg.lsqr. It is the fatest but may not be available + in old scipy versions. It also uses an iterative procedure. + + All three solvers support both dense and sparse data. + tol : float Precision of the solution. Attributes ---------- - `coef_` : array, shape = [n_features] or [n_responses, n_features] + coef_ : array, shape = [n_features] or [n_targets, n_features] Weight vector(s). See also -------- - RidgeClassifier, RidgeCV + RidgeClassifier, RidgeCV, KernelRidge Examples -------- @@ -237,13 +480,34 @@ class Ridge(_BaseRidge, RegressorMixin): >>> X = np.random.randn(n_samples, n_features) >>> clf = Ridge(alpha=1.0) >>> clf.fit(X, y) # doctest: +NORMALIZE_WHITESPACE - Ridge(alpha=1.0, copy_X=True, fit_intercept=True, normalize=False, - tol=0.001) + Ridge(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=None, + normalize=False, solver='auto', tol=0.001) """ def __init__(self, alpha=1.0, fit_intercept=True, normalize=False, - copy_X=True, tol=1e-3): + copy_X=True, max_iter=None, tol=1e-3, solver="auto"): super(Ridge, self).__init__(alpha=alpha, fit_intercept=fit_intercept, - normalize=normalize, copy_X=copy_X, tol=tol) + normalize=normalize, copy_X=copy_X, + max_iter=max_iter, tol=tol, solver=solver) + + def fit(self, X, y, sample_weight=None): + """Fit Ridge regression model + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Training data + + y : array-like, shape = [n_samples] or [n_samples, n_targets] + Target values + + sample_weight : float or numpy array of shape [n_samples] + Individual weights for each sample + + Returns + ------- + self : returns an instance of self. + """ + return super(Ridge, self).fit(X, y, sample_weight=sample_weight) class RidgeClassifier(LinearClassifierMixin, _BaseRidge): @@ -257,32 +521,42 @@ class RidgeClassifier(LinearClassifierMixin, _BaseRidge): ``(2*C)^-1`` in other linear models such as LogisticRegression or LinearSVC. + class_weight : dict, optional + Weights associated with classes in the form + ``{class_label : weight}``. If not given, all classes are + supposed to have weight one. + + copy_X : boolean, optional, default True + If True, X will be copied; else, it may be overwritten. + fit_intercept : boolean Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). - normalize : boolean, optional - If True, the regressors X are normalized - - copy_X : boolean, optional, default True - If True, X will be copied; else, it may be overwritten. - max_iter : int, optional Maximum number of iterations for conjugate gradient solver. The default value is determined by scipy.sparse.linalg. + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. + + solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg'} + Solver to use in the computational + routines. 'svd' will use a Singular value decomposition to obtain + the solution, 'cholesky' will use the standard + scipy.linalg.solve function, 'sparse_cg' will use the + conjugate gradient solver as found in + scipy.sparse.linalg.cg while 'auto' will chose the most + appropriate depending on the matrix X. 'lsqr' uses + a direct regularized least-squares routine provided by scipy. + tol : float Precision of the solution. - class_weight : dict, optional - Weights associated with classes in the form - {class_label : weight}. If not given, all classes are - supposed to have weight one. - Attributes ---------- - `coef_` : array, shape = [n_features] or [n_classes, n_features] + coef_ : array, shape = [n_features] or [n_classes, n_features] Weight vector(s). See also @@ -296,13 +570,14 @@ class RidgeClassifier(LinearClassifierMixin, _BaseRidge): advantage of the multi-variate response support in Ridge. """ def __init__(self, alpha=1.0, fit_intercept=True, normalize=False, - copy_X=True, max_iter=None, tol=1e-3, class_weight=None): - super(RidgeClassifier, self).__init__(alpha=alpha, - fit_intercept=fit_intercept, normalize=normalize, - copy_X=copy_X, max_iter=max_iter, tol=tol) + copy_X=True, max_iter=None, tol=1e-3, class_weight=None, + solver="auto"): + super(RidgeClassifier, self).__init__( + alpha=alpha, fit_intercept=fit_intercept, normalize=normalize, + copy_X=copy_X, max_iter=max_iter, tol=tol, solver=solver) self.class_weight = class_weight - def fit(self, X, y, solver='auto'): + def fit(self, X, y): """Fit Ridge regression model. Parameters @@ -313,28 +588,22 @@ def fit(self, X, y, solver='auto'): y : array-like, shape = [n_samples] Target values - solver : {'auto', 'dense_cholesky', 'sparse_cg'} - Solver to use in the computational - routines. 'dense_cholesky' will use the standard - scipy.linalg.solve function, 'sparse_cg' will use the - conjugate gradient solver as found in - scipy.sparse.linalg.cg while 'auto' will chose the most - appropriate depending on the matrix X. - Returns ------- self : returns an instance of self. """ - if self.class_weight is None: - class_weight = {} - else: - class_weight = self.class_weight - - sample_weight_classes = np.array([class_weight.get(k, 1.0) for k in y]) self._label_binarizer = LabelBinarizer(pos_label=1, neg_label=-1) Y = self._label_binarizer.fit_transform(y) - _BaseRidge.fit(self, X, Y, solver=solver, - sample_weight=sample_weight_classes) + if not self._label_binarizer.y_type_.startswith('multilabel'): + y = column_or_1d(y, warn=True) + + if self.class_weight: + # get the class weight corresponding to each sample + sample_weight = compute_sample_weight(self.class_weight, y) + else: + sample_weight = None + + super(RidgeClassifier, self).fit(X, Y, sample_weight=sample_weight) return self @property @@ -381,14 +650,14 @@ class _RidgeGCV(LinearModel): http://www.mit.edu/~9.520/spring07/Classes/rlsslides.pdf """ - def __init__(self, alphas=[0.1, 1.0, 10.0], fit_intercept=True, - normalize=False, score_func=None, loss_func=None, - copy_X=True, gcv_mode=None, store_cv_values=False): + def __init__(self, alphas=[0.1, 1.0, 10.0], + fit_intercept=True, normalize=False, + scoring=None, copy_X=True, + gcv_mode=None, store_cv_values=False): self.alphas = np.asarray(alphas) self.fit_intercept = fit_intercept self.normalize = normalize - self.score_func = score_func - self.loss_func = loss_func + self.scoring = scoring self.copy_X = copy_X self.gcv_mode = gcv_mode self.store_cv_values = store_cv_values @@ -432,9 +701,9 @@ def _values(self, alpha, y, v, Q, QT_y): return y - (c / G_diag), c def _pre_compute_svd(self, X, y): - if sparse.issparse(X) and hasattr(X, 'toarray'): - X = X.toarray() - U, s, _ = np.linalg.svd(X, full_matrices=0) + if sparse.issparse(X): + raise TypeError("SVD not supported for sparse matrices") + U, s, _ = linalg.svd(X, full_matrices=0) v = s ** 2 UT_y = np.dot(U.T, y) return v, U, UT_y @@ -457,7 +726,7 @@ def _values_svd(self, alpha, y, v, U, UT_y): G_diag = G_diag[:, np.newaxis] return y - (c / G_diag), c - def fit(self, X, y, sample_weight=1.0): + def fit(self, X, y, sample_weight=None): """Fit Ridge regression model Parameters @@ -465,7 +734,7 @@ def fit(self, X, y, sample_weight=1.0): X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training data - y : array-like, shape = [n_samples] or [n_samples, n_responses] + y : array-like, shape = [n_samples] or [n_samples, n_targets] Target values sample_weight : float or array-like of shape [n_samples] @@ -475,26 +744,27 @@ def fit(self, X, y, sample_weight=1.0): ------- self : Returns self. """ - X = safe_asarray(X, dtype=np.float) - y = np.asarray(y, dtype=np.float) + X, y = check_X_y(X, y, ['csr', 'csc', 'coo'], dtype=np.float, + multi_output=True, y_numeric=True) n_samples, n_features = X.shape - X, y, X_mean, y_mean, X_std = LinearModel._center_data(X, y, - self.fit_intercept, self.normalize, self.copy_X) + X, y, X_mean, y_mean, X_std = LinearModel._center_data( + X, y, self.fit_intercept, self.normalize, self.copy_X, + sample_weight=sample_weight) gcv_mode = self.gcv_mode with_sw = len(np.shape(sample_weight)) if gcv_mode is None or gcv_mode == 'auto': - if n_features > n_samples or with_sw: + if sparse.issparse(X) or n_features > n_samples or with_sw: gcv_mode = 'eigen' else: gcv_mode = 'svd' elif gcv_mode == "svd" and with_sw: # FIXME non-uniform sample weights not yet supported warnings.warn("non-uniform sample weights unsupported for svd, " - "forcing usage of eigen") + "forcing usage of eigen") gcv_mode = 'eigen' if gcv_mode == 'eigen': @@ -514,23 +784,34 @@ def fit(self, X, y, sample_weight=1.0): cv_values = np.zeros((n_samples * n_y, len(self.alphas))) C = [] - error = self.score_func is None and self.loss_func is None + scorer = check_scoring(self, scoring=self.scoring, allow_none=True) + error = scorer is None for i, alpha in enumerate(self.alphas): + weighted_alpha = (sample_weight * alpha + if sample_weight is not None + else alpha) if error: - out, c = _errors(sample_weight * alpha, y, v, Q, QT_y) + out, c = _errors(weighted_alpha, y, v, Q, QT_y) else: - out, c = _values(sample_weight * alpha, y, v, Q, QT_y) + out, c = _values(weighted_alpha, y, v, Q, QT_y) cv_values[:, i] = out.ravel() C.append(c) if error: best = cv_values.mean(axis=0).argmin() else: - func = self.score_func if self.score_func else self.loss_func - out = [func(y.ravel(), cv_values[:, i]) - for i in range(len(self.alphas))] - best = np.argmax(out) if self.score_func else np.argmin(out) + # The scorer want an object that will make the predictions but + # they are already computed efficiently by _RidgeGCV. This + # identity_estimator will just return them + def identity_estimator(): + pass + identity_estimator.decision_function = lambda y_predict: y_predict + identity_estimator.predict = lambda y_predict: y_predict + + out = [scorer(identity_estimator, y.ravel(), cv_values[:, i]) + for i in range(len(self.alphas))] + best = np.argmax(out) self.alpha_ = self.alphas[best] self.dual_coef_ = C[best] @@ -547,31 +828,21 @@ def fit(self, X, y, sample_weight=1.0): return self - @property - def best_alpha(self): - warnings.warn("Use alpha_. Using best_alpha is deprecated" - "since version 0.12, and backward compatibility " - "won't be maintained from version 0.14 onward. ", - DeprecationWarning, stacklevel=2) - return self.alpha_ - class _BaseRidgeCV(LinearModel): - def __init__(self, alphas=np.array([0.1, 1.0, 10.0]), - fit_intercept=True, normalize=False, score_func=None, - loss_func=None, cv=None, gcv_mode=None, + fit_intercept=True, normalize=False, scoring=None, + cv=None, gcv_mode=None, store_cv_values=False): self.alphas = alphas self.fit_intercept = fit_intercept self.normalize = normalize - self.score_func = score_func - self.loss_func = loss_func + self.scoring = scoring self.cv = cv self.gcv_mode = gcv_mode self.store_cv_values = store_cv_values - def fit(self, X, y, sample_weight=1.0): + def fit(self, X, y, sample_weight=None): """Fit Ridge regression model Parameters @@ -579,7 +850,7 @@ def fit(self, X, y, sample_weight=1.0): X : array-like, shape = [n_samples, n_features] Training data - y : array-like, shape = [n_samples] or [n_samples, n_responses] + y : array-like, shape = [n_samples] or [n_samples, n_targets] Target values sample_weight : float or array-like of shape [n_samples] @@ -593,8 +864,7 @@ def fit(self, X, y, sample_weight=1.0): estimator = _RidgeGCV(self.alphas, fit_intercept=self.fit_intercept, normalize=self.normalize, - score_func=self.score_func, - loss_func=self.loss_func, + scoring=self.scoring, gcv_mode=self.gcv_mode, store_cv_values=self.store_cv_values) estimator.fit(X, y, sample_weight=sample_weight) @@ -630,7 +900,7 @@ class RidgeCV(_BaseRidgeCV, RegressorMixin): Parameters ---------- - alphas: numpy array of shape [n_alphas] + alphas : numpy array of shape [n_alphas] Array of alpha values to try. Small positive values of alpha improve the conditioning of the problem and reduce the variance of the estimates. @@ -642,33 +912,34 @@ class RidgeCV(_BaseRidgeCV, RegressorMixin): to false, no intercept will be used in calculations (e.g. data is expected to be already centered). - normalize : boolean, optional - If True, the regressors X are normalized + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. - score_func: callable, optional - function that takes 2 arguments and compares them in - order to evaluate the performance of prediction (big is good) - if None is passed, the score of the estimator is maximized + scoring : string, callable or None, optional, default: None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. - loss_func: callable, optional - function that takes 2 arguments and compares them in - order to evaluate the performance of prediction (small is good) - if None is passed, the score of the estimator is maximized - - cv : cross-validation generator, optional + cv : integer or cross-validation generator, optional If None, Generalized Cross-Validation (efficient Leave-One-Out) will be used. + If an integer is passed, it is the number of folds for KFold cross + validation. Specific cross-validation objects can be passed, see + sklearn.cross_validation module for the list of possible objects gcv_mode : {None, 'auto', 'svd', eigen'}, optional Flag indicating which strategy to use when performing Generalized Cross-Validation. Options are:: - 'auto' : use svd if n_samples > n_features, otherwise use eigen + 'auto' : use svd if n_samples > n_features or when X is a sparse + matrix, otherwise use eigen 'svd' : force computation via singular value decomposition of X + (does not work for sparse matrices) 'eigen' : force computation via eigendecomposition of X^T X - The 'auto' mode is the default and is intended to pick the cheaper \ - option of the two depending upon the shape of the training data. + The 'auto' mode is the default and is intended to pick the cheaper + option of the two depending upon the shape and format of the training + data. store_cv_values : boolean, default=False Flag indicating if the cross-validation values corresponding to @@ -678,19 +949,23 @@ class RidgeCV(_BaseRidgeCV, RegressorMixin): Attributes ---------- - `cv_values_` : array, shape = [n_samples, n_alphas] or \ - shape = [n_samples, n_responses, n_alphas], optional + cv_values_ : array, shape = [n_samples, n_alphas] or \ + shape = [n_samples, n_targets, n_alphas], optional Cross-validation values for each alpha (if `store_cv_values=True` and \ `cv=None`). After `fit()` has been called, this attribute will \ contain the mean squared errors (by default) or the values of the \ `{loss,score}_func` function (if provided in the constructor). - `coef_` : array, shape = [n_features] or [n_responses, n_features] + coef_ : array, shape = [n_features] or [n_targets, n_features] Weight vector(s). - `alpha_` : float + alpha_ : float Estimated regularization parameter. + intercept_ : float | array, shape = (n_targets,) + Independent term in decision function. Set to 0.0 if + ``fit_intercept = False``. + See also -------- Ridge: Ridge regression @@ -709,11 +984,11 @@ class RidgeClassifierCV(LinearClassifierMixin, _BaseRidgeCV): Parameters ---------- - alphas: numpy array of shape [n_alphas] + alphas : numpy array of shape [n_alphas] Array of alpha values to try. Small positive values of alpha improve the conditioning of the problem and reduce the variance of the estimates. - Alpha corresponds to (2*C)^-1 in other linear models such as + Alpha corresponds to ``(2*C)^-1`` in other linear models such as LogisticRegression or LinearSVC. fit_intercept : boolean @@ -721,18 +996,13 @@ class RidgeClassifierCV(LinearClassifierMixin, _BaseRidgeCV): to false, no intercept will be used in calculations (e.g. data is expected to be already centered). - normalize : boolean, optional - If True, the regressors X are normalized - - score_func: callable, optional - function that takes 2 arguments and compares them in - order to evaluate the performance of prediction (big is good) - if None is passed, the score of the estimator is maximized + normalize : boolean, optional, default False + If True, the regressors X will be normalized before regression. - loss_func: callable, optional - function that takes 2 arguments and compares them in - order to evaluate the performance of prediction (small is good) - if None is passed, the score of the estimator is maximized + scoring : string, callable or None, optional, default: None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. cv : cross-validation generator, optional If None, Generalized Cross-Validation (efficient Leave-One-Out) @@ -740,22 +1010,22 @@ class RidgeClassifierCV(LinearClassifierMixin, _BaseRidgeCV): class_weight : dict, optional Weights associated with classes in the form - {class_label : weight}. If not given, all classes are + ``{class_label : weight}``. If not given, all classes are supposed to have weight one. Attributes ---------- - `cv_values_` : array, shape = [n_samples, n_alphas] or \ + cv_values_ : array, shape = [n_samples, n_alphas] or \ shape = [n_samples, n_responses, n_alphas], optional Cross-validation values for each alpha (if `store_cv_values=True` and `cv=None`). After `fit()` has been called, this attribute will contain \ the mean squared errors (by default) or the values of the \ `{loss,score}_func` function (if provided in the constructor). - `coef_` : array, shape = [n_features] or [n_responses, n_features] + coef_ : array, shape = [n_features] or [n_targets, n_features] Weight vector(s). - `alpha_` : float + alpha_ : float Estimated regularization parameter See also @@ -771,39 +1041,42 @@ class RidgeClassifierCV(LinearClassifierMixin, _BaseRidgeCV): advantage of the multi-variate response support in Ridge. """ def __init__(self, alphas=np.array([0.1, 1.0, 10.0]), fit_intercept=True, - normalize=False, score_func=None, loss_func=None, cv=None, - class_weight=None): - super(RidgeClassifierCV, self).__init__(alphas=alphas, - fit_intercept=fit_intercept, normalize=normalize, - score_func=score_func, loss_func=loss_func, cv=cv) + normalize=False, scoring=None, cv=None, class_weight=None): + super(RidgeClassifierCV, self).__init__( + alphas=alphas, fit_intercept=fit_intercept, normalize=normalize, + scoring=scoring, cv=cv) self.class_weight = class_weight - def fit(self, X, y, sample_weight=1.0, class_weight=None): + def fit(self, X, y, sample_weight=None): """Fit the ridge classifier. Parameters ---------- - X : array-like, shape = [n_samples, n_features] + X : array-like, shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. - y : array-like, shape = [n_samples] + y : array-like, shape (n_samples,) Target values. - sample_weight : float or numpy array of shape [n_samples] - Sample weight + sample_weight : float or numpy array of shape (n_samples,) + Sample weight. Returns ------- self : object Returns self. """ - if self.class_weight is not None: - get_cw = self.class_weight.get - sample_weight = (sample_weight - * np.array([get_cw(k, 1.0) for k in y])) + if sample_weight is None: + sample_weight = 1. + self._label_binarizer = LabelBinarizer(pos_label=1, neg_label=-1) Y = self._label_binarizer.fit_transform(y) + if not self._label_binarizer.y_type_.startswith('multilabel'): + y = column_or_1d(y, warn=True) + # modify the sample weights with the corresponding class weight + sample_weight = (sample_weight * + compute_sample_weight(self.class_weight, y)) _BaseRidgeCV.fit(self, X, Y, sample_weight=sample_weight) return self diff --git a/sklearn/linear_model/setup.py b/sklearn/linear_model/setup.py index 30c355152e0b2..2460bfcdd1092 100644 --- a/sklearn/linear_model/setup.py +++ b/sklearn/linear_model/setup.py @@ -13,26 +13,26 @@ def configuration(parent_package='', top_path=None): cblas_libs, blas_info = get_blas_info() - libraries = [] if os.name == 'posix': cblas_libs.append('m') - libraries.append('m') - - config.add_extension('cd_fast', - sources=['cd_fast.c'], - libraries=cblas_libs, - include_dirs=[join('..', 'src', 'cblas'), - numpy.get_include(), - blas_info.pop('include_dirs', [])], - extra_compile_args=blas_info.pop('extra_compile_args', []), - **blas_info - ) + + config.add_extension('cd_fast', sources=['cd_fast.c'], + libraries=cblas_libs, + include_dirs=[join('..', 'src', 'cblas'), + numpy.get_include(), + blas_info.pop('include_dirs', [])], + extra_compile_args=blas_info.pop('extra_compile_args', + []), **blas_info) config.add_extension('sgd_fast', - sources=['sgd_fast.c'], - include_dirs=[numpy.get_include()], - libraries=libraries, - ) + sources=['sgd_fast.c'], + include_dirs=[join('..', 'src', 'cblas'), + numpy.get_include(), + blas_info.pop('include_dirs', [])], + libraries=cblas_libs, + extra_compile_args=blas_info.pop('extra_compile_args', + []), + **blas_info) # add other directories config.add_subpackage('tests') diff --git a/sklearn/linear_model/sgd_fast.c b/sklearn/linear_model/sgd_fast.c index 8f45e8a576033..4b470a6eb1844 100644 --- a/sklearn/linear_model/sgd_fast.c +++ b/sklearn/linear_model/sgd_fast.c @@ -1,16 +1,29 @@ -/* Generated by Cython 0.15.1 on Thu May 3 20:20:57 2012 */ +/* Generated by Cython 0.21.1 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) + #error Cython requires Python 2.6+ or Python 3.2+. #else - -#include /* For offsetof */ +#define CYTHON_ABI "0_21_1" +#include #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -22,85 +35,84 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - -#if PY_VERSION_HEX < 0x02040000 - #define METH_COEXIST 0 - #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) - #define PyDict_Contains(d,o) PySequence_Contains(d,o) +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL #endif - -#if PY_VERSION_HEX < 0x02050000 - typedef int Py_ssize_t; - #define PY_SSIZE_T_MAX INT_MAX - #define PY_SSIZE_T_MIN INT_MIN - #define PY_FORMAT_SIZE_T "" - #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) - #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 #endif - -#if PY_VERSION_HEX < 0x02060000 - #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) - #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) - #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) - #define PyVarObject_HEAD_INIT(type, size) \ - PyObject_HEAD_INIT(type) size, - #define PyType_Modified(t) - - typedef struct { - void *buf; - PyObject *obj; - Py_ssize_t len; - Py_ssize_t itemsize; - int readonly; - int ndim; - char *format; - Py_ssize_t *shape; - Py_ssize_t *strides; - Py_ssize_t *suboffsets; - void *internal; - } Py_buffer; - - #define PyBUF_SIMPLE 0 - #define PyBUF_WRITABLE 0x0001 - #define PyBUF_FORMAT 0x0004 - #define PyBUF_ND 0x0008 - #define PyBUF_STRIDES (0x0010 | PyBUF_ND) - #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) - #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) - #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) - #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 +#define Py_OptimizeFlag 0 #endif - +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 -#endif - -#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) + #define __Pyx_PyFrozenSet_Size(s) PyObject_Size(s) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) + #define __Pyx_PyFrozenSet_Size(s) PySet_Size(s) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -108,36 +120,17 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - -#if PY_VERSION_HEX < 0x02060000 - #define PyBytesObject PyStringObject - #define PyBytes_Type PyString_Type - #define PyBytes_Check PyString_Check - #define PyBytes_CheckExact PyString_CheckExact - #define PyBytes_FromString PyString_FromString - #define PyBytes_FromStringAndSize PyString_FromStringAndSize - #define PyBytes_FromFormat PyString_FromFormat - #define PyBytes_DecodeEscape PyString_DecodeEscape - #define PyBytes_AsString PyString_AsString - #define PyBytes_AsStringAndSize PyString_AsStringAndSize - #define PyBytes_Size PyString_Size - #define PyBytes_AS_STRING PyString_AS_STRING - #define PyBytes_GET_SIZE PyString_GET_SIZE - #define PyBytes_Repr PyString_Repr - #define PyBytes_Concat PyString_Concat - #define PyBytes_ConcatAndDel PyString_ConcatAndDel -#endif - -#if PY_VERSION_HEX < 0x02060000 - #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) - #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -153,13 +146,17 @@ #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - -#if PY_VERSION_HEX < 0x03020000 +#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY + #ifndef PyUnicode_InternFromString + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) + #endif +#endif +#if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong @@ -167,55 +164,59 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - #if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) + #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) + #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif - -#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) - #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) - #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) -#else - #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) - #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif #endif - -#if PY_MAJOR_VERSION >= 3 - #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif #endif - -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#ifdef NAN +#define __PYX_NAN() ((float) NAN) #else - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#ifdef __cplusplus +template +void __Pyx_call_destructor(T* x) { + x->~T(); +} #endif -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_NAMESTR(n) ((char *)(n)) - #define __Pyx_DOCSTR(n) ((char *)(n)) + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else - #define __Pyx_NAMESTR(n) (n) - #define __Pyx_DOCSTR(n) (n) + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C @@ -232,11 +233,13 @@ #include #define __PYX_HAVE__sklearn__linear_model__sgd_fast #define __PYX_HAVE_API__sklearn__linear_model__sgd_fast +#include "math.h" +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" -#include "math.h" +#include "sgd_fast_helpers.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -245,21 +248,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -267,48 +255,163 @@ # else # define CYTHON_UNUSED # endif -# elif defined(__ICC) || defined(__INTEL_COMPILER) +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif -#ifdef __GNUC__ - /* Test for GCC > 2.95 */ - #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) - #else /* __GNUC__ > 2 ... */ - #define likely(x) (x) - #define unlikely(x) (x) - #endif /* __GNUC__ > 2 ... */ -#else /* __GNUC__ */ +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -317,7 +420,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -327,7 +429,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -335,20 +436,56 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { - "sgd_fast.pyx", - "numpy.pxd", - "weight_vector.pxd", - "seq_dataset.pxd", + "sklearn/linear_model/sgd_fast.pyx", + "__init__.pxd", + "type.pxd", + "sklearn/utils/weight_vector.pxd", + "sklearn/utils/seq_dataset.pxd", }; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; + struct __Pyx_StructField_* fields; + size_t size; + size_t arraysize[8]; + int ndim; + char typegroup; + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; -/* "numpy.pxd":719 + +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -357,7 +494,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -366,7 +503,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -375,7 +512,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -384,7 +521,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -393,7 +530,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -402,7 +539,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -411,7 +548,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -420,7 +557,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -429,7 +566,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -438,7 +575,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -447,7 +584,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -456,7 +593,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -465,7 +602,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -474,7 +611,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -483,7 +620,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -492,7 +629,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -501,7 +638,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -510,7 +647,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -519,7 +656,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -528,7 +665,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -536,61 +673,6 @@ typedef npy_double __pyx_t_5numpy_double_t; * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; - -/* "sklearn/utils/weight_vector.pxd":10 - * - * - * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< - * ctypedef np.int32_t INTEGER - * - */ -typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE; - -/* "sklearn/utils/weight_vector.pxd":11 - * - * ctypedef np.float64_t DOUBLE - * ctypedef np.int32_t INTEGER # <<<<<<<<<<<<<< - * - * - */ -typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_5utils_13weight_vector_INTEGER; - -/* "sklearn/utils/seq_dataset.pxd":5 - * cimport numpy as np - * - * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< - * ctypedef np.int32_t INTEGER - * - */ -typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE; - -/* "sklearn/utils/seq_dataset.pxd":6 - * - * ctypedef np.float64_t DOUBLE - * ctypedef np.int32_t INTEGER # <<<<<<<<<<<<<< - * - * - */ -typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER; - -/* "sklearn/linear_model/sgd_fast.pyx":28 - * cdef extern double pow(double x, double y) - * - * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< - * ctypedef np.int32_t INTEGER - * - */ -typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE; - -/* "sklearn/linear_model/sgd_fast.pyx":29 - * - * ctypedef np.float64_t DOUBLE - * ctypedef np.int32_t INTEGER # <<<<<<<<<<<<<< - * - * - */ -typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_12linear_model_8sgd_fast_INTEGER; - #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -611,22 +693,25 @@ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_12linear_model_8sgd_fast_INTEGER typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ +struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector; +struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset; +struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset; +struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset; struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction; struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression; -struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber; -struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset; -struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification; -struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset; -struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log; -struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge; -struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset; struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber; -struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector; +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge; +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge; +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log; struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss; +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber; +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive; -/* "numpy.pxd":758 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -635,7 +720,7 @@ struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -644,7 +729,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -653,7 +738,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -662,72 +747,110 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; */ typedef npy_cdouble __pyx_t_5numpy_complex_t; -/* "sklearn/linear_model/sgd_fast.pyx":47 - * # ---------------------------------------- +/* "sklearn/utils/weight_vector.pxd":10 * - * cdef class LossFunction: # <<<<<<<<<<<<<< - * """Base class for convex loss functions""" * + * cdef class WeightVector(object): # <<<<<<<<<<<<<< + * cdef np.ndarray w + * cdef np.ndarray aw */ -struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction { +struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector { PyObject_HEAD - struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_vtab; + struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__pyx_vtab; + PyArrayObject *w; + PyArrayObject *aw; + double *w_data_ptr; + double *aw_data_ptr; + double wscale; + double average_a; + double average_b; + int n_features; + double sq_norm; }; -/* "sklearn/linear_model/sgd_fast.pyx":85 - * - * - * cdef class Regression(LossFunction): # <<<<<<<<<<<<<< - * """Base class for loss functions for regression""" +/* "sklearn/utils/seq_dataset.pxd":8 + * # iterators over the rows of a matrix X and corresponding target values y. * + * cdef class SequentialDataset: # <<<<<<<<<<<<<< + * cdef int current_index + * cdef np.ndarray index */ -struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction __pyx_base; +struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_vtab; + int current_index; + PyArrayObject *index; + int *index_data_ptr; + Py_ssize_t n_samples; }; -/* "sklearn/linear_model/sgd_fast.pyx":204 - * +/* "sklearn/utils/seq_dataset.pxd":19 * - * cdef class Huber(Regression): # <<<<<<<<<<<<<< - * """Huber regression loss * + * cdef class ArrayDataset(SequentialDataset): # <<<<<<<<<<<<<< + * cdef Py_ssize_t n_features + * cdef int stride */ -struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression __pyx_base; - double c; +struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset { + struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; + Py_ssize_t n_features; + int stride; + double *X_data_ptr; + double *Y_data_ptr; + PyArrayObject *feature_indices; + int *feature_indices_ptr; + double *sample_weight_data; }; -/* "sklearn/utils/seq_dataset.pxd":9 - * +/* "sklearn/utils/seq_dataset.pxd":32 * - * cdef class SequentialDataset: # <<<<<<<<<<<<<< - * cdef Py_ssize_t n_samples * + * cdef class CSRDataset(SequentialDataset): # <<<<<<<<<<<<<< + * cdef int stride + * cdef double *X_data_ptr */ -struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset { - PyObject_HEAD - struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_vtab; - Py_ssize_t n_samples; +struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset { + struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; + int stride; + double *X_data_ptr; + int *X_indptr_ptr; + int *X_indices_ptr; + double *Y_data_ptr; + PyArrayObject *feature_indices; + int *feature_indices_ptr; + double *sample_weight_data; }; -/* "sklearn/linear_model/sgd_fast.pyx":240 +/* "sklearn/linear_model/sgd_fast.pyx":45 + * # ---------------------------------------- * + * cdef class LossFunction: # <<<<<<<<<<<<<< + * """Base class for convex loss functions""" * - * cdef class EpsilonInsensitive(Regression): # <<<<<<<<<<<<<< - * """Epsilon-Insensitive loss (used by SVR). + */ +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_vtab; +}; + + +/* "sklearn/linear_model/sgd_fast.pyx":88 + * + * + * cdef class Regression(LossFunction): # <<<<<<<<<<<<<< + * """Base class for loss functions for regression""" * */ -struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression __pyx_base; - double epsilon; +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction __pyx_base; }; -/* "sklearn/linear_model/sgd_fast.pyx":95 +/* "sklearn/linear_model/sgd_fast.pyx":98 * * * cdef class Classification(LossFunction): # <<<<<<<<<<<<<< @@ -739,30 +862,45 @@ struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification { }; -/* "sklearn/utils/seq_dataset.pxd":34 +/* "sklearn/linear_model/sgd_fast.pyx":108 * * - * cdef class CSRDataset(SequentialDataset): # <<<<<<<<<<<<<< - * cdef int current_index - * cdef int stride + * cdef class ModifiedHuber(Classification): # <<<<<<<<<<<<<< + * """Modified Huber loss for binary classification with y in {-1, 1} + * */ -struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset { - struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; - int current_index; - int stride; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *X_data_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *X_indptr_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *X_indices_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *Y_data_ptr; - PyArrayObject *feature_indices; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *feature_indices_ptr; - PyArrayObject *index; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *index_data_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *sample_weight_data; +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification __pyx_base; +}; + + +/* "sklearn/linear_model/sgd_fast.pyx":138 + * + * + * cdef class Hinge(Classification): # <<<<<<<<<<<<<< + * """Hinge loss for binary classification tasks with y in {-1,1} + * + */ +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification __pyx_base; + double threshold; +}; + + +/* "sklearn/linear_model/sgd_fast.pyx":170 + * + * + * cdef class SquaredHinge(LossFunction): # <<<<<<<<<<<<<< + * """Squared Hinge loss for binary classification tasks with y in {-1,1} + * + */ +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction __pyx_base; + double threshold; }; -/* "sklearn/linear_model/sgd_fast.pyx":167 +/* "sklearn/linear_model/sgd_fast.pyx":202 * * * cdef class Log(Classification): # <<<<<<<<<<<<<< @@ -774,85 +912,121 @@ struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log { }; -/* "sklearn/linear_model/sgd_fast.pyx":135 +/* "sklearn/linear_model/sgd_fast.pyx":227 * * - * cdef class Hinge(Classification): # <<<<<<<<<<<<<< - * """Hinge loss for binary classification tasks with y in {-1,1} + * cdef class SquaredLoss(Regression): # <<<<<<<<<<<<<< + * """Squared loss traditional used in linear regression.""" + * cdef double loss(self, double p, double y) nogil: + */ +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression __pyx_base; +}; + + +/* "sklearn/linear_model/sgd_fast.pyx":239 + * + * + * cdef class Huber(Regression): # <<<<<<<<<<<<<< + * """Huber regression loss * */ -struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification __pyx_base; - double threshold; +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression __pyx_base; + double c; }; -/* "sklearn/utils/seq_dataset.pxd":17 +/* "sklearn/linear_model/sgd_fast.pyx":275 * * - * cdef class ArrayDataset(SequentialDataset): # <<<<<<<<<<<<<< - * cdef Py_ssize_t n_features - * cdef int current_index + * cdef class EpsilonInsensitive(Regression): # <<<<<<<<<<<<<< + * """Epsilon-Insensitive loss (used by SVR). + * */ -struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset { - struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; - Py_ssize_t n_features; - int current_index; - int stride; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *X_data_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *Y_data_ptr; - PyArrayObject *feature_indices; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *feature_indices_ptr; - PyArrayObject *index; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *index_data_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *sample_weight_data; +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression __pyx_base; + double epsilon; }; -/* "sklearn/linear_model/sgd_fast.pyx":105 +/* "sklearn/linear_model/sgd_fast.pyx":302 * * - * cdef class ModifiedHuber(Classification): # <<<<<<<<<<<<<< - * """Modified Huber loss for binary classification with y in {-1, 1} + * cdef class SquaredEpsilonInsensitive(Regression): # <<<<<<<<<<<<<< + * """Epsilon-Insensitive loss. * */ -struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification __pyx_base; +struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression __pyx_base; + double epsilon; }; -/* "sklearn/utils/weight_vector.pxd":14 + +/* "sklearn/utils/weight_vector.pxd":10 * * * cdef class WeightVector(object): # <<<<<<<<<<<<<< * cdef np.ndarray w - * cdef DOUBLE *w_data_ptr + * cdef np.ndarray aw */ -struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector { - PyObject_HEAD - struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__pyx_vtab; - PyArrayObject *w; - __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *w_data_ptr; - double wscale; - Py_ssize_t n_features; - double sq_norm; + +struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector { + void (*add)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double *, int *, int, double); + void (*add_average)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double *, int *, int, double, double); + double (*dot)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double *, int *, int); + void (*scale)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double); + void (*reset_wscale)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *); + double (*norm)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *); }; +static struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__pyx_vtabptr_7sklearn_5utils_13weight_vector_WeightVector; -/* "sklearn/linear_model/sgd_fast.pyx":192 +/* "sklearn/utils/seq_dataset.pxd":8 + * # iterators over the rows of a matrix X and corresponding target values y. + * + * cdef class SequentialDataset: # <<<<<<<<<<<<<< + * cdef int current_index + * cdef np.ndarray index + */ + +struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset { + void (*next)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, double **, int **, int *, double *, double *); + void (*shuffle)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, __pyx_t_5numpy_uint32_t); +}; +static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset; + + +/* "sklearn/utils/seq_dataset.pxd":19 * * - * cdef class SquaredLoss(Regression): # <<<<<<<<<<<<<< - * """Squared loss traditional used in linear regression.""" - * cpdef double loss(self, double p, double y): + * cdef class ArrayDataset(SequentialDataset): # <<<<<<<<<<<<<< + * cdef Py_ssize_t n_features + * cdef int stride */ -struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression __pyx_base; + +struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset { + struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; }; +static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset; + +/* "sklearn/utils/seq_dataset.pxd":32 + * + * + * cdef class CSRDataset(SequentialDataset): # <<<<<<<<<<<<<< + * cdef int stride + * cdef double *X_data_ptr + */ + +struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_CSRDataset { + struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_CSRDataset *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset; -/* "sklearn/linear_model/sgd_fast.pyx":47 +/* "sklearn/linear_model/sgd_fast.pyx":45 * # ---------------------------------------- * * cdef class LossFunction: # <<<<<<<<<<<<<< @@ -861,13 +1035,13 @@ struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss { */ struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction { - double (*loss)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch); - double (*dloss)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch); + double (*loss)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double); + double (*_dloss)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double); }; static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction; -/* "sklearn/linear_model/sgd_fast.pyx":85 +/* "sklearn/linear_model/sgd_fast.pyx":88 * * * cdef class Regression(LossFunction): # <<<<<<<<<<<<<< @@ -881,21 +1055,7 @@ struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Regression { static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Regression *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression; -/* "sklearn/linear_model/sgd_fast.pyx":192 - * - * - * cdef class SquaredLoss(Regression): # <<<<<<<<<<<<<< - * """Squared loss traditional used in linear regression.""" - * cpdef double loss(self, double p, double y): - */ - -struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredLoss { - struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Regression __pyx_base; -}; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredLoss *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredLoss; - - -/* "sklearn/linear_model/sgd_fast.pyx":95 +/* "sklearn/linear_model/sgd_fast.pyx":98 * * * cdef class Classification(LossFunction): # <<<<<<<<<<<<<< @@ -909,7 +1069,7 @@ struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Classification { static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Classification *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification; -/* "sklearn/linear_model/sgd_fast.pyx":105 +/* "sklearn/linear_model/sgd_fast.pyx":108 * * * cdef class ModifiedHuber(Classification): # <<<<<<<<<<<<<< @@ -923,78 +1083,63 @@ struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_ModifiedHuber { static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_ModifiedHuber; -/* "sklearn/linear_model/sgd_fast.pyx":167 +/* "sklearn/linear_model/sgd_fast.pyx":138 * * - * cdef class Log(Classification): # <<<<<<<<<<<<<< - * """Logistic regression loss for binary classification with y in {-1, 1}""" + * cdef class Hinge(Classification): # <<<<<<<<<<<<<< + * """Hinge loss for binary classification tasks with y in {-1,1} * */ -struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Log { +struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Hinge { struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Classification __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Log *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Log; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Hinge; -/* "sklearn/utils/seq_dataset.pxd":9 +/* "sklearn/linear_model/sgd_fast.pyx":170 * * - * cdef class SequentialDataset: # <<<<<<<<<<<<<< - * cdef Py_ssize_t n_samples + * cdef class SquaredHinge(LossFunction): # <<<<<<<<<<<<<< + * """Squared Hinge loss for binary classification tasks with y in {-1,1} * */ -struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset { - void (*next)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE **, __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER **, int *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *); - void (*shuffle)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, PyObject *); +struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredHinge { + struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredHinge *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredHinge; -/* "sklearn/utils/seq_dataset.pxd":17 +/* "sklearn/linear_model/sgd_fast.pyx":202 * * - * cdef class ArrayDataset(SequentialDataset): # <<<<<<<<<<<<<< - * cdef Py_ssize_t n_features - * cdef int current_index - */ - -struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset { - struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; -}; -static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset; - - -/* "sklearn/utils/seq_dataset.pxd":34 - * + * cdef class Log(Classification): # <<<<<<<<<<<<<< + * """Logistic regression loss for binary classification with y in {-1, 1}""" * - * cdef class CSRDataset(SequentialDataset): # <<<<<<<<<<<<<< - * cdef int current_index - * cdef int stride */ -struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_CSRDataset { - struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; +struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Log { + struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Classification __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_CSRDataset *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Log *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Log; -/* "sklearn/linear_model/sgd_fast.pyx":240 - * +/* "sklearn/linear_model/sgd_fast.pyx":227 * - * cdef class EpsilonInsensitive(Regression): # <<<<<<<<<<<<<< - * """Epsilon-Insensitive loss (used by SVR). * + * cdef class SquaredLoss(Regression): # <<<<<<<<<<<<<< + * """Squared loss traditional used in linear regression.""" + * cdef double loss(self, double p, double y) nogil: */ -struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive { +struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredLoss { struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Regression __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredLoss *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredLoss; -/* "sklearn/linear_model/sgd_fast.pyx":204 +/* "sklearn/linear_model/sgd_fast.pyx":239 * * * cdef class Huber(Regression): # <<<<<<<<<<<<<< @@ -1008,42 +1153,35 @@ struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Huber { static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Huber *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Huber; -/* "sklearn/linear_model/sgd_fast.pyx":135 +/* "sklearn/linear_model/sgd_fast.pyx":275 * * - * cdef class Hinge(Classification): # <<<<<<<<<<<<<< - * """Hinge loss for binary classification tasks with y in {-1,1} + * cdef class EpsilonInsensitive(Regression): # <<<<<<<<<<<<<< + * """Epsilon-Insensitive loss (used by SVR). * */ -struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Hinge { - struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Classification __pyx_base; +struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive { + struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Regression __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Hinge; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; -/* "sklearn/utils/weight_vector.pxd":14 +/* "sklearn/linear_model/sgd_fast.pyx":302 * * - * cdef class WeightVector(object): # <<<<<<<<<<<<<< - * cdef np.ndarray w - * cdef DOUBLE *w_data_ptr + * cdef class SquaredEpsilonInsensitive(Regression): # <<<<<<<<<<<<<< + * """Epsilon-Insensitive loss. + * */ -struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector { - void (*add)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *, __pyx_t_7sklearn_5utils_13weight_vector_INTEGER *, int, double); - double (*dot)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *, __pyx_t_7sklearn_5utils_13weight_vector_INTEGER *, int); - void (*scale)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double); - void (*reset_wscale)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *); - double (*norm)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *); +struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive { + struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Regression __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__pyx_vtabptr_7sklearn_5utils_13weight_vector_WeightVector; - - +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive; #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -1054,10 +1192,23 @@ static struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__p void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -1068,7 +1219,7 @@ static struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__p #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -1078,156 +1229,187 @@ static struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__p #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) -#endif /* CYTHON_REFNANNY */ +#endif +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact); /*proto*/ +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); -/* Run-time type information about structs used with buffers */ -struct __Pyx_StructField_; +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif -typedef struct { - const char* name; /* for error messages only */ - struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ -} __Pyx_TypeInfo; +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; +static CYTHON_INLINE int __Pyx_IterFinish(void); +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); -static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ +#define __Pyx_BufPtrCContig1d(type, buf, i0, s0) ((type)buf + i0) +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); +static void __Pyx_RaiseBufferFallbackError(void); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); -#define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_List_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); +#else +#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) +#endif -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif -#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Tuple_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); +static int __Pyx_SetVtable(PyObject *dict, void *vtable); -#define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static void* __Pyx_GetVtable(PyObject *dict); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { - PyObject *r; - if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) { - r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - } - else if (PyTuple_CheckExact(o) && ((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - } - else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0))) { - r = PySequence_GetItem(o, i); - } - else { - r = __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); - } - return r; -} +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ #if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); -static void __Pyx_ReleaseBuffer(Py_buffer *view); + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); #else -#define __Pyx_GetBuffer PyObject_GetBuffer -#define __Pyx_ReleaseBuffer PyBuffer_Release + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release #endif -Py_ssize_t __Pyx_zeros[] = {0}; -Py_ssize_t __Pyx_minusones[] = {-1}; -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; -static int __Pyx_Print(PyObject*, PyObject *, int); /*proto*/ -#if PY_MAJOR_VERSION >= 3 +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +static CYTHON_INLINE npy_uint32 __Pyx_PyInt_As_npy_uint32(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_uint32(npy_uint32 value); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static int __Pyx_Print(PyObject*, PyObject *, int); +#if CYTHON_COMPILING_IN_PYPY || PY_MAJOR_VERSION >= 3 static PyObject* __pyx_print = 0; static PyObject* __pyx_print_kwargs = 0; #endif -static int __Pyx_PrintOne(PyObject* stream, PyObject *o); /*proto*/ +static int __Pyx_PrintOne(PyObject* stream, PyObject *o); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value); #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -1241,8 +1423,7 @@ static int __Pyx_PrintOne(PyObject* stream, PyObject *o); /*proto*/ #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - -#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else @@ -1328,64 +1509,66 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); - -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename); /*proto*/ +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); static int __Pyx_check_binary_version(void); -static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ - -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ - -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif -static void* __Pyx_GetVtable(PyObject *dict); /*proto*/ +static PyObject *__Pyx_ImportModule(const char *name); + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); + +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_12LossFunction__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_10Regression_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_10Regression__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_14Classification_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_14Classification__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge__dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_12SquaredHinge__dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_3Log__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_11SquaredLoss__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber__dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive__dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive__dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto*/ -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ +/* Module declarations from 'cython' */ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ +/* Module declarations from 'libc.math' */ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -1396,18 +1579,7 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ - -/* Module declarations from 'cython.cython.view' */ - -/* Module declarations from 'cython' */ /* Module declarations from 'sklearn.utils.weight_vector' */ static PyTypeObject *__pyx_ptype_7sklearn_5utils_13weight_vector_WeightVector = 0; @@ -1423,285 +1595,350 @@ static PyTypeObject *__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Regression = static PyTypeObject *__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Classification = 0; static PyTypeObject *__pyx_ptype_7sklearn_12linear_model_8sgd_fast_ModifiedHuber = 0; static PyTypeObject *__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Hinge = 0; +static PyTypeObject *__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredHinge = 0; static PyTypeObject *__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Log = 0; static PyTypeObject *__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredLoss = 0; static PyTypeObject *__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Huber = 0; static PyTypeObject *__pyx_ptype_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive = 0; -static CYTHON_INLINE double __pyx_f_7sklearn_12linear_model_8sgd_fast_max(double, double); /*proto*/ -static CYTHON_INLINE double __pyx_f_7sklearn_12linear_model_8sgd_fast_min(double, double); /*proto*/ -static void __pyx_f_7sklearn_12linear_model_8sgd_fast_l1penalty(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, __pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE *, __pyx_t_7sklearn_12linear_model_8sgd_fast_INTEGER *, int, double); /*proto*/ -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE), 'R' }; +static PyTypeObject *__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive = 0; +static int __pyx_f_7sklearn_12linear_model_8sgd_fast_any_nonfinite(double *, int); /*proto*/ +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_sqnorm(double *, int *, int); /*proto*/ +static void __pyx_f_7sklearn_12linear_model_8sgd_fast_l1penalty(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double *, int *, int, double); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "sklearn.linear_model.sgd_fast" int __pyx_module_is_main_sklearn__linear_model__sgd_fast = 0; /* Implementation of 'sklearn.linear_model.sgd_fast' */ -static PyObject *__pyx_builtin_NotImplementedError; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; -static char __pyx_k_1[] = "-- Epoch %d"; -static char __pyx_k_2[] = "Norm: %.2f, NNZs: %d, Bias: %.6f, T: %d, Avg. loss: %.6f"; -static char __pyx_k_3[] = "Total training time: %.2f seconds."; -static char __pyx_k_4[] = "floating-point under-/overflow occured."; -static char __pyx_k_6[] = "ndarray is not C contiguous"; -static char __pyx_k_8[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_10[] = "Non-native byte order not supported"; -static char __pyx_k_12[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_13[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_16[] = "Format string allocated too short."; -static char __pyx_k_18[] = "sklearn.linear_model.sgd_fast"; -static char __pyx_k__B[] = "B"; -static char __pyx_k__H[] = "H"; -static char __pyx_k__I[] = "I"; -static char __pyx_k__L[] = "L"; -static char __pyx_k__O[] = "O"; -static char __pyx_k__Q[] = "Q"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__c[] = "c"; -static char __pyx_k__d[] = "d"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__g[] = "g"; -static char __pyx_k__h[] = "h"; -static char __pyx_k__i[] = "i"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__p[] = "p"; -static char __pyx_k__q[] = "q"; -static char __pyx_k__t[] = "t"; -static char __pyx_k__y[] = "y"; -static char __pyx_k__Zd[] = "Zd"; -static char __pyx_k__Zf[] = "Zf"; -static char __pyx_k__Zg[] = "Zg"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__any[] = "any"; -static char __pyx_k__rho[] = "rho"; -static char __pyx_k__sys[] = "sys"; -static char __pyx_k__eta0[] = "eta0"; -static char __pyx_k__loss[] = "loss"; -static char __pyx_k__seed[] = "seed"; -static char __pyx_k__time[] = "time"; -static char __pyx_k__alpha[] = "alpha"; -static char __pyx_k__dloss[] = "dloss"; -static char __pyx_k__dtype[] = "dtype"; -static char __pyx_k__isinf[] = "isinf"; -static char __pyx_k__isnan[] = "isnan"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__order[] = "order"; -static char __pyx_k__range[] = "range"; -static char __pyx_k__shape[] = "shape"; -static char __pyx_k__zeros[] = "zeros"; -static char __pyx_k__n_iter[] = "n_iter"; -static char __pyx_k__dataset[] = "dataset"; -static char __pyx_k__epsilon[] = "epsilon"; -static char __pyx_k__float64[] = "float64"; -static char __pyx_k__nonzero[] = "nonzero"; -static char __pyx_k__power_t[] = "power_t"; -static char __pyx_k__shuffle[] = "shuffle"; -static char __pyx_k__verbose[] = "verbose"; -static char __pyx_k__weights[] = "weights"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__intercept[] = "intercept"; -static char __pyx_k__plain_sgd[] = "plain_sgd"; -static char __pyx_k__threshold[] = "threshold"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__weight_neg[] = "weight_neg"; -static char __pyx_k__weight_pos[] = "weight_pos"; -static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k__penalty_type[] = "penalty_type"; -static char __pyx_k__fit_intercept[] = "fit_intercept"; -static char __pyx_k__learning_rate[] = "learning_rate"; -static char __pyx_k__intercept_decay[] = "intercept_decay"; -static char __pyx_k__NotImplementedError[] = "NotImplementedError"; -static PyObject *__pyx_kp_s_1; -static PyObject *__pyx_kp_u_10; -static PyObject *__pyx_kp_u_12; -static PyObject *__pyx_kp_u_13; -static PyObject *__pyx_kp_u_16; -static PyObject *__pyx_n_s_18; -static PyObject *__pyx_kp_s_2; -static PyObject *__pyx_kp_s_3; -static PyObject *__pyx_kp_s_4; -static PyObject *__pyx_kp_u_6; -static PyObject *__pyx_kp_u_8; -static PyObject *__pyx_n_s__NotImplementedError; -static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__alpha; -static PyObject *__pyx_n_s__any; -static PyObject *__pyx_n_s__c; -static PyObject *__pyx_n_s__dataset; -static PyObject *__pyx_n_s__dloss; -static PyObject *__pyx_n_s__dtype; -static PyObject *__pyx_n_s__epsilon; -static PyObject *__pyx_n_s__eta0; -static PyObject *__pyx_n_s__fit_intercept; -static PyObject *__pyx_n_s__float64; -static PyObject *__pyx_n_s__intercept; -static PyObject *__pyx_n_s__intercept_decay; -static PyObject *__pyx_n_s__isinf; -static PyObject *__pyx_n_s__isnan; -static PyObject *__pyx_n_s__learning_rate; -static PyObject *__pyx_n_s__loss; -static PyObject *__pyx_n_s__n_iter; -static PyObject *__pyx_n_s__nonzero; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__order; -static PyObject *__pyx_n_s__p; -static PyObject *__pyx_n_s__penalty_type; -static PyObject *__pyx_n_s__plain_sgd; -static PyObject *__pyx_n_s__power_t; -static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__rho; -static PyObject *__pyx_n_s__seed; -static PyObject *__pyx_n_s__shape; -static PyObject *__pyx_n_s__shuffle; -static PyObject *__pyx_n_s__sys; -static PyObject *__pyx_n_s__t; -static PyObject *__pyx_n_s__threshold; -static PyObject *__pyx_n_s__time; -static PyObject *__pyx_n_s__verbose; -static PyObject *__pyx_n_s__weight_neg; -static PyObject *__pyx_n_s__weight_pos; -static PyObject *__pyx_n_s__weights; -static PyObject *__pyx_n_s__y; -static PyObject *__pyx_n_s__zeros; -static PyObject *__pyx_int_15; -static PyObject *__pyx_k_tuple_5; -static PyObject *__pyx_k_tuple_7; -static PyObject *__pyx_k_tuple_9; -static PyObject *__pyx_k_tuple_11; -static PyObject *__pyx_k_tuple_14; -static PyObject *__pyx_k_tuple_15; -static PyObject *__pyx_k_tuple_17; - -/* "sklearn/linear_model/sgd_fast.pyx":50 +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_self, double __pyx_v_p, double __pyx_v_y); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber___reduce__(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge___init__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_v_self, double __pyx_v_threshold); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_2__reduce__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_12SquaredHinge___init__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *__pyx_v_self, double __pyx_v_threshold); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_2__reduce__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log___reduce__(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss___reduce__(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber___init__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *__pyx_v_self, double __pyx_v_c); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_2__reduce__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive___init__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_v_self, double __pyx_v_epsilon); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_2__reduce__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive___init__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *__pyx_v_self, double __pyx_v_epsilon); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_2__reduce__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_plain_sgd(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_weights, double __pyx_v_intercept, struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_loss, int __pyx_v_penalty_type, double __pyx_v_alpha, double __pyx_v_C, double __pyx_v_l1_ratio, struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_dataset, int __pyx_v_n_iter, int __pyx_v_fit_intercept, int __pyx_v_verbose, int __pyx_v_shuffle, __pyx_t_5numpy_uint32_t __pyx_v_seed, double __pyx_v_weight_pos, double __pyx_v_weight_neg, int __pyx_v_learning_rate, double __pyx_v_eta0, double __pyx_v_power_t, double __pyx_v_t, double __pyx_v_intercept_decay); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_2average_sgd(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_weights, double __pyx_v_intercept, PyArrayObject *__pyx_v_average_weights, double __pyx_v_average_intercept, struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_loss, int __pyx_v_penalty_type, double __pyx_v_alpha, double __pyx_v_C, double __pyx_v_l1_ratio, struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_dataset, int __pyx_v_n_iter, int __pyx_v_fit_intercept, int __pyx_v_verbose, int __pyx_v_shuffle, __pyx_t_5numpy_uint32_t __pyx_v_seed, double __pyx_v_weight_pos, double __pyx_v_weight_neg, int __pyx_v_learning_rate, double __pyx_v_eta0, double __pyx_v_power_t, double __pyx_v_t, double __pyx_v_intercept_decay, int __pyx_v_average); /* proto */ +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_4_plain_sgd(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_weights, double __pyx_v_intercept, PyArrayObject *__pyx_v_average_weights, double __pyx_v_average_intercept, struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_loss, int __pyx_v_penalty_type, double __pyx_v_alpha, double __pyx_v_C, double __pyx_v_l1_ratio, struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_dataset, int __pyx_v_n_iter, int __pyx_v_fit_intercept, int __pyx_v_verbose, int __pyx_v_shuffle, __pyx_t_5numpy_uint32_t __pyx_v_seed, double __pyx_v_weight_pos, double __pyx_v_weight_neg, int __pyx_v_learning_rate, double __pyx_v_eta0, double __pyx_v_power_t, double __pyx_v_t, double __pyx_v_intercept_decay, int __pyx_v_average); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Regression(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Classification(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_ModifiedHuber(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Hinge(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_SquaredHinge(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Log(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_SquaredLoss(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Huber(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_B[] = "B"; +static char __pyx_k_C[] = "C"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_c[] = "c"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_p[] = "p"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_t[] = "t"; +static char __pyx_k_u[] = "u"; +static char __pyx_k_w[] = "w"; +static char __pyx_k_y[] = "y"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k__7[] = "_"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_end[] = "end"; +static char __pyx_k_eta[] = "eta"; +static char __pyx_k_sys[] = "sys"; +static char __pyx_k_eta0[] = "eta0"; +static char __pyx_k_file[] = "file"; +static char __pyx_k_loss[] = "loss"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_seed[] = "seed"; +static char __pyx_k_sqrt[] = "sqrt"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_time[] = "time"; +static char __pyx_k_typw[] = "typw"; +static char __pyx_k_xnnz[] = "xnnz"; +static char __pyx_k_alpha[] = "alpha"; +static char __pyx_k_count[] = "count"; +static char __pyx_k_dloss[] = "dloss"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_epoch[] = "epoch"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_order[] = "order"; +static char __pyx_k_print[] = "print"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_shape[] = "shape"; +static char __pyx_k_w_ptr[] = "w_ptr"; +static char __pyx_k_zeros[] = "zeros"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_n_iter[] = "n_iter"; +static char __pyx_k_ps_ptr[] = "ps_ptr"; +static char __pyx_k_update[] = "update"; +static char __pyx_k_Epoch_d[] = "-- Epoch %d"; +static char __pyx_k_average[] = "average"; +static char __pyx_k_dataset[] = "dataset"; +static char __pyx_k_epsilon[] = "epsilon"; +static char __pyx_k_float64[] = "float64"; +static char __pyx_k_nonzero[] = "nonzero"; +static char __pyx_k_power_t[] = "power_t"; +static char __pyx_k_shuffle[] = "shuffle"; +static char __pyx_k_sumloss[] = "sumloss"; +static char __pyx_k_t_start[] = "t_start"; +static char __pyx_k_verbose[] = "verbose"; +static char __pyx_k_weights[] = "weights"; +static char __pyx_k_infinity[] = "infinity"; +static char __pyx_k_is_hinge[] = "is_hinge"; +static char __pyx_k_l1_ratio[] = "l1_ratio"; +static char __pyx_k_MAX_DLOSS[] = "MAX_DLOSS"; +static char __pyx_k_intercept[] = "intercept"; +static char __pyx_k_n_samples[] = "n_samples"; +static char __pyx_k_plain_sgd[] = "_plain_sgd"; +static char __pyx_k_threshold[] = "threshold"; +static char __pyx_k_x_ind_ptr[] = "x_ind_ptr"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_n_features[] = "n_features"; +static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static char __pyx_k_q_data_ptr[] = "q_data_ptr"; +static char __pyx_k_weight_neg[] = "weight_neg"; +static char __pyx_k_weight_pos[] = "weight_pos"; +static char __pyx_k_x_data_ptr[] = "x_data_ptr"; +static char __pyx_k_average_sgd[] = "average_sgd"; +static char __pyx_k_plain_sgd_2[] = "plain_sgd"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_class_weight[] = "class_weight"; +static char __pyx_k_initial_eta0[] = "initial_eta0"; +static char __pyx_k_optimal_init[] = "optimal_init"; +static char __pyx_k_penalty_type[] = "penalty_type"; +static char __pyx_k_fit_intercept[] = "fit_intercept"; +static char __pyx_k_learning_rate[] = "learning_rate"; +static char __pyx_k_sample_weight[] = "sample_weight"; +static char __pyx_k_average_weights[] = "average_weights"; +static char __pyx_k_intercept_decay[] = "intercept_decay"; +static char __pyx_k_standard_weights[] = "standard_weights"; +static char __pyx_k_average_intercept[] = "average_intercept"; +static char __pyx_k_standard_intercept[] = "standard_intercept"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_sklearn_linear_model_sgd_fast[] = "sklearn.linear_model.sgd_fast"; +static char __pyx_k_Total_training_time_2f_seconds[] = "Total training time: %.2f seconds."; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_volatile_ogrisel_code_scikit_le[] = "/volatile/ogrisel/code/scikit-learn/sklearn/linear_model/sgd_fast.pyx"; +static char __pyx_k_Floating_point_under_overflow_oc[] = "Floating-point under-/overflow occurred at epoch #%d. Scaling input data with StandardScaler or MinMaxScaler might help."; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_Norm_2f_NNZs_d_Bias_6f_T_d_Avg_l[] = "Norm: %.2f, NNZs: %d, Bias: %.6f, T: %d, Avg. loss: %.6f"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_n_s_C; +static PyObject *__pyx_kp_s_Epoch_d; +static PyObject *__pyx_kp_s_Floating_point_under_overflow_oc; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_n_s_MAX_DLOSS; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_kp_s_Norm_2f_NNZs_d_Bias_6f_T_d_Avg_l; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_kp_s_Total_training_time_2f_seconds; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s__7; +static PyObject *__pyx_n_s_alpha; +static PyObject *__pyx_n_s_average; +static PyObject *__pyx_n_s_average_intercept; +static PyObject *__pyx_n_s_average_sgd; +static PyObject *__pyx_n_s_average_weights; +static PyObject *__pyx_n_s_c; +static PyObject *__pyx_n_s_class_weight; +static PyObject *__pyx_n_s_count; +static PyObject *__pyx_n_s_dataset; +static PyObject *__pyx_n_s_dloss; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_end; +static PyObject *__pyx_n_s_epoch; +static PyObject *__pyx_n_s_epsilon; +static PyObject *__pyx_n_s_eta; +static PyObject *__pyx_n_s_eta0; +static PyObject *__pyx_n_s_file; +static PyObject *__pyx_n_s_fit_intercept; +static PyObject *__pyx_n_s_float64; +static PyObject *__pyx_n_s_i; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_infinity; +static PyObject *__pyx_n_s_initial_eta0; +static PyObject *__pyx_n_s_intercept; +static PyObject *__pyx_n_s_intercept_decay; +static PyObject *__pyx_n_s_is_hinge; +static PyObject *__pyx_n_s_l1_ratio; +static PyObject *__pyx_n_s_learning_rate; +static PyObject *__pyx_n_s_loss; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_n_features; +static PyObject *__pyx_n_s_n_iter; +static PyObject *__pyx_n_s_n_samples; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_nonzero; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_optimal_init; +static PyObject *__pyx_n_s_order; +static PyObject *__pyx_n_s_p; +static PyObject *__pyx_n_s_penalty_type; +static PyObject *__pyx_n_s_plain_sgd; +static PyObject *__pyx_n_s_plain_sgd_2; +static PyObject *__pyx_n_s_power_t; +static PyObject *__pyx_n_s_print; +static PyObject *__pyx_n_s_ps_ptr; +static PyObject *__pyx_n_s_pyx_vtable; +static PyObject *__pyx_n_s_q; +static PyObject *__pyx_n_s_q_data_ptr; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_sample_weight; +static PyObject *__pyx_n_s_seed; +static PyObject *__pyx_n_s_shape; +static PyObject *__pyx_n_s_shuffle; +static PyObject *__pyx_n_s_sklearn_linear_model_sgd_fast; +static PyObject *__pyx_n_s_sqrt; +static PyObject *__pyx_n_s_standard_intercept; +static PyObject *__pyx_n_s_standard_weights; +static PyObject *__pyx_n_s_sumloss; +static PyObject *__pyx_n_s_sys; +static PyObject *__pyx_n_s_t; +static PyObject *__pyx_n_s_t_start; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_n_s_threshold; +static PyObject *__pyx_n_s_time; +static PyObject *__pyx_n_s_typw; +static PyObject *__pyx_n_s_u; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_update; +static PyObject *__pyx_n_s_verbose; +static PyObject *__pyx_kp_s_volatile_ogrisel_code_scikit_le; +static PyObject *__pyx_n_s_w; +static PyObject *__pyx_n_s_w_ptr; +static PyObject *__pyx_n_s_weight_neg; +static PyObject *__pyx_n_s_weight_pos; +static PyObject *__pyx_n_s_weights; +static PyObject *__pyx_n_s_x_data_ptr; +static PyObject *__pyx_n_s_x_ind_ptr; +static PyObject *__pyx_n_s_xnnz; +static PyObject *__pyx_n_s_y; +static PyObject *__pyx_n_s_zeros; +static PyObject *__pyx_float_1_0; +static PyObject *__pyx_int_0; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__8; +static PyObject *__pyx_tuple__10; +static PyObject *__pyx_tuple__12; +static PyObject *__pyx_codeobj__9; +static PyObject *__pyx_codeobj__11; +static PyObject *__pyx_codeobj__13; + +/* "sklearn/linear_model/sgd_fast.pyx":48 * """Base class for convex loss functions""" * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * """Evaluate the loss function. * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y) { double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("loss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__loss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - /* "sklearn/linear_model/sgd_fast.pyx":65 + /* "sklearn/linear_model/sgd_fast.pyx":63 * The loss evaluated at `p` and `y`. * """ - * raise NotImplementedError() # <<<<<<<<<<<<<< + * return 0. # <<<<<<<<<<<<<< * - * cpdef double dloss(self, double p, double y): + * def dloss(self, double p, double y): */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_NotImplementedError, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - __pyx_r = 0; + __pyx_r = 0.; goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.LossFunction.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -/* "sklearn/linear_model/sgd_fast.pyx":50 + /* "sklearn/linear_model/sgd_fast.pyx":48 * """Base class for convex loss functions""" * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * """Evaluate the loss function. * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss[] = "Evaluate the loss function.\n\n Parameters\n ----------\n p : double\n The prediction, p = w^T x\n y : double\n The true value (aka target)\n\n Returns\n -------\n double\n The loss evaluated at `p` and `y`.\n "; -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/linear_model/sgd_fast.pyx":65 + * return 0. + * + * def dloss(self, double p, double y): # <<<<<<<<<<<<<< + * """Evaluate the derivative of the loss function with respect to + * the prediction `p`. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_12LossFunction_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_12linear_model_8sgd_fast_12LossFunction_dloss[] = "Evaluate the derivative of the loss function with respect to\n the prediction `p`.\n\n Parameters\n ----------\n p : double\n The prediction, p = w^T x\n y : double\n The true value (aka target)\n Returns\n -------\n double\n The derivative of the loss function with regards to `p`.\n "; +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_12LossFunction_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { double __pyx_v_p; double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("loss"); + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dloss (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_p,&__pyx_n_s_y,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_p)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "loss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "dloss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; @@ -1709,188 +1946,56 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss( values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.LossFunction.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.LossFunction.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self)->__pyx_vtab)->loss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_dloss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.LossFunction.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":67 - * raise NotImplementedError() - * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< - * """Evaluate the derivative of the loss function with respect to - * the prediction `p`. - */ - -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_12LossFunction_dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { - double __pyx_r; +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { + PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dloss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__dloss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_1dloss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + __Pyx_RefNannySetupContext("dloss", 0); - /* "sklearn/linear_model/sgd_fast.pyx":82 - * The derivative of the loss function w.r.t. `p`. + /* "sklearn/linear_model/sgd_fast.pyx":80 + * The derivative of the loss function with regards to `p`. * """ - * raise NotImplementedError() # <<<<<<<<<<<<<< - * + * return self._dloss(p, y) # <<<<<<<<<<<<<< * + * cdef double _dloss(self, double p, double y) nogil: */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_NotImplementedError, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self->__pyx_vtab)->_dloss(__pyx_v_self, __pyx_v_p, __pyx_v_y)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - __pyx_r = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.LossFunction.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -/* "sklearn/linear_model/sgd_fast.pyx":67 - * raise NotImplementedError() + /* "sklearn/linear_model/sgd_fast.pyx":65 + * return 0. * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< + * def dloss(self, double p, double y): # <<<<<<<<<<<<<< * """Evaluate the derivative of the loss function with respect to * the prediction `p`. */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_12linear_model_8sgd_fast_12LossFunction_1dloss[] = "Evaluate the derivative of the loss function with respect to\n the prediction `p`.\n\n Parameters\n ----------\n p : double\n The prediction, p = w^T x\n y : double\n The true value (aka target)\n Returns\n -------\n double\n The derivative of the loss function w.r.t. `p`.\n "; -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("dloss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "dloss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.LossFunction.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self)->__pyx_vtab)->dloss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.LossFunction.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -1901,724 +2006,209 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_1dlos return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":88 - * """Base class for loss functions for regression""" - * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< - * raise NotImplementedError() +/* "sklearn/linear_model/sgd_fast.pyx":82 + * return self._dloss(p, y) * + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * # Implementation of dloss; separate function because cpdef and nogil + * # can't be combined. */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_10Regression_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_10Regression_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_12LossFunction__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y) { double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("loss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__loss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_10Regression_loss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - /* "sklearn/linear_model/sgd_fast.pyx":89 + /* "sklearn/linear_model/sgd_fast.pyx":85 + * # Implementation of dloss; separate function because cpdef and nogil + * # can't be combined. + * return 0. # <<<<<<<<<<<<<< * - * cpdef double loss(self, double p, double y): - * raise NotImplementedError() # <<<<<<<<<<<<<< * - * cpdef double dloss(self, double p, double y): */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_NotImplementedError, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - __pyx_r = 0; + __pyx_r = 0.; goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.Regression.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + + /* "sklearn/linear_model/sgd_fast.pyx":82 + * return self._dloss(p, y) + * + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * # Implementation of dloss; separate function because cpdef and nogil + * # can't be combined. + */ + + /* function exit code */ __pyx_L0:; - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":88 +/* "sklearn/linear_model/sgd_fast.pyx":91 * """Base class for loss functions for regression""" * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< - * raise NotImplementedError() + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * return 0. * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_10Regression_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_10Regression_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("loss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "loss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Regression.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Regression *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *)__pyx_v_self)->__pyx_base.__pyx_vtab)->__pyx_base.loss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_10Regression_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y) { + double __pyx_r; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "sklearn/linear_model/sgd_fast.pyx":92 + * + * cdef double loss(self, double p, double y) nogil: + * return 0. # <<<<<<<<<<<<<< + * + * cdef double _dloss(self, double p, double y) nogil: + */ + __pyx_r = 0.; goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Regression.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + + /* "sklearn/linear_model/sgd_fast.pyx":91 + * """Base class for loss functions for regression""" + * + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * return 0. + * + */ + + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":91 - * raise NotImplementedError() +/* "sklearn/linear_model/sgd_fast.pyx":94 + * return 0. * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< - * raise NotImplementedError() + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * return 0. * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_10Regression_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_10Regression_dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_10Regression__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y) { double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dloss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__dloss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_10Regression_1dloss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - /* "sklearn/linear_model/sgd_fast.pyx":92 + /* "sklearn/linear_model/sgd_fast.pyx":95 * - * cpdef double dloss(self, double p, double y): - * raise NotImplementedError() # <<<<<<<<<<<<<< + * cdef double _dloss(self, double p, double y) nogil: + * return 0. # <<<<<<<<<<<<<< * * */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_NotImplementedError, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - __pyx_r = 0; + __pyx_r = 0.; goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.Regression.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + + /* "sklearn/linear_model/sgd_fast.pyx":94 + * return 0. + * + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * return 0. + * + */ + + /* function exit code */ __pyx_L0:; - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":91 - * raise NotImplementedError() +/* "sklearn/linear_model/sgd_fast.pyx":101 + * """Base class for loss functions for classification""" * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< - * raise NotImplementedError() + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * return 0. * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_10Regression_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_10Regression_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("dloss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "dloss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Regression.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Regression *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *)__pyx_v_self)->__pyx_base.__pyx_vtab)->__pyx_base.dloss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_14Classification_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y) { + double __pyx_r; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "sklearn/linear_model/sgd_fast.pyx":102 + * + * cdef double loss(self, double p, double y) nogil: + * return 0. # <<<<<<<<<<<<<< + * + * cdef double _dloss(self, double p, double y) nogil: + */ + __pyx_r = 0.; goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Regression.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + + /* "sklearn/linear_model/sgd_fast.pyx":101 + * """Base class for loss functions for classification""" + * + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * return 0. + * + */ + + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":98 - * """Base class for loss functions for classification""" +/* "sklearn/linear_model/sgd_fast.pyx":104 + * return 0. * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< - * raise NotImplementedError() + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * return 0. * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_14Classification_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_14Classification_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_14Classification__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *__pyx_v_self, CYTHON_UNUSED double __pyx_v_p, CYTHON_UNUSED double __pyx_v_y) { double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("loss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__loss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_14Classification_loss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - /* "sklearn/linear_model/sgd_fast.pyx":99 + /* "sklearn/linear_model/sgd_fast.pyx":105 + * + * cdef double _dloss(self, double p, double y) nogil: + * return 0. # <<<<<<<<<<<<<< * - * cpdef double loss(self, double p, double y): - * raise NotImplementedError() # <<<<<<<<<<<<<< * - * cpdef double dloss(self, double p, double y): */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_NotImplementedError, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - __pyx_r = 0; + __pyx_r = 0.; goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.Classification.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + + /* "sklearn/linear_model/sgd_fast.pyx":104 + * return 0. + * + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * return 0. + * + */ + + /* function exit code */ __pyx_L0:; - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":98 - * """Base class for loss functions for classification""" - * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< - * raise NotImplementedError() - * +/* "sklearn/linear_model/sgd_fast.pyx":116 + * Stochastic Gradient Descent', ICML'04. + * """ + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double z = p * y + * if z >= 1.0: */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_14Classification_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_14Classification_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("loss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "loss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Classification.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Classification *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *)__pyx_v_self)->__pyx_base.__pyx_vtab)->__pyx_base.loss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Classification.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/linear_model/sgd_fast.pyx":101 - * raise NotImplementedError() - * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< - * raise NotImplementedError() - * - */ - -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_14Classification_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_14Classification_dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { - double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dloss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__dloss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_14Classification_1dloss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - - /* "sklearn/linear_model/sgd_fast.pyx":102 - * - * cpdef double dloss(self, double p, double y): - * raise NotImplementedError() # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_NotImplementedError, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.Classification.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/linear_model/sgd_fast.pyx":101 - * raise NotImplementedError() - * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< - * raise NotImplementedError() - * - */ - -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_14Classification_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_14Classification_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("dloss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "dloss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Classification.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Classification *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *)__pyx_v_self)->__pyx_base.__pyx_vtab)->__pyx_base.dloss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Classification.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/linear_model/sgd_fast.pyx":113 - * Stochastic Gradient Descent', ICML'04. - * """ - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< - * cdef double z = p * y - * if z >= 1.0: - */ - -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_v_z; double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("loss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__loss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + int __pyx_t_1; - /* "sklearn/linear_model/sgd_fast.pyx":114 + /* "sklearn/linear_model/sgd_fast.pyx":117 * """ - * cpdef double loss(self, double p, double y): + * cdef double loss(self, double p, double y) nogil: * cdef double z = p * y # <<<<<<<<<<<<<< * if z >= 1.0: * return 0.0 */ __pyx_v_z = (__pyx_v_p * __pyx_v_y); - /* "sklearn/linear_model/sgd_fast.pyx":115 - * cpdef double loss(self, double p, double y): + /* "sklearn/linear_model/sgd_fast.pyx":118 + * cdef double loss(self, double p, double y) nogil: * cdef double z = p * y * if z >= 1.0: # <<<<<<<<<<<<<< * return 0.0 * elif z >= -1.0: */ - __pyx_t_6 = (__pyx_v_z >= 1.0); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_z >= 1.0) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":116 + /* "sklearn/linear_model/sgd_fast.pyx":119 * cdef double z = p * y * if z >= 1.0: * return 0.0 # <<<<<<<<<<<<<< @@ -2627,20 +2217,19 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss(str */ __pyx_r = 0.0; goto __pyx_L0; - goto __pyx_L3; } - /* "sklearn/linear_model/sgd_fast.pyx":117 + /* "sklearn/linear_model/sgd_fast.pyx":120 * if z >= 1.0: * return 0.0 * elif z >= -1.0: # <<<<<<<<<<<<<< * return (1.0 - z) * (1.0 - z) * else: */ - __pyx_t_6 = (__pyx_v_z >= -1.0); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_z >= -1.0) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":118 + /* "sklearn/linear_model/sgd_fast.pyx":121 * return 0.0 * elif z >= -1.0: * return (1.0 - z) * (1.0 - z) # <<<<<<<<<<<<<< @@ -2649,192 +2238,66 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss(str */ __pyx_r = ((1.0 - __pyx_v_z) * (1.0 - __pyx_v_z)); goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "sklearn/linear_model/sgd_fast.pyx":120 + /* "sklearn/linear_model/sgd_fast.pyx":123 * return (1.0 - z) * (1.0 - z) * else: * return -4.0 * z # <<<<<<<<<<<<<< * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: */ __pyx_r = (-4.0 * __pyx_v_z); goto __pyx_L0; } - __pyx_L3:; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.ModifiedHuber.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -/* "sklearn/linear_model/sgd_fast.pyx":113 + /* "sklearn/linear_model/sgd_fast.pyx":116 * Stochastic Gradient Descent', ICML'04. * """ - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double z = p * y * if z >= 1.0: */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("loss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "loss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.ModifiedHuber.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.loss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.ModifiedHuber.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":122 +/* "sklearn/linear_model/sgd_fast.pyx":125 * return -4.0 * z * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double z = p * y * if z >= 1.0: */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_v_z; double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dloss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__dloss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_1dloss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + int __pyx_t_1; - /* "sklearn/linear_model/sgd_fast.pyx":123 + /* "sklearn/linear_model/sgd_fast.pyx":126 * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: * cdef double z = p * y # <<<<<<<<<<<<<< * if z >= 1.0: * return 0.0 */ __pyx_v_z = (__pyx_v_p * __pyx_v_y); - /* "sklearn/linear_model/sgd_fast.pyx":124 - * cpdef double dloss(self, double p, double y): + /* "sklearn/linear_model/sgd_fast.pyx":127 + * cdef double _dloss(self, double p, double y) nogil: * cdef double z = p * y * if z >= 1.0: # <<<<<<<<<<<<<< * return 0.0 * elif z >= -1.0: */ - __pyx_t_6 = (__pyx_v_z >= 1.0); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_z >= 1.0) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":125 + /* "sklearn/linear_model/sgd_fast.pyx":128 * cdef double z = p * y * if z >= 1.0: * return 0.0 # <<<<<<<<<<<<<< @@ -2843,20 +2306,19 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_dloss(st */ __pyx_r = 0.0; goto __pyx_L0; - goto __pyx_L3; } - /* "sklearn/linear_model/sgd_fast.pyx":126 + /* "sklearn/linear_model/sgd_fast.pyx":129 * if z >= 1.0: * return 0.0 * elif z >= -1.0: # <<<<<<<<<<<<<< * return 2.0 * (1.0 - z) * -y * else: */ - __pyx_t_6 = (__pyx_v_z >= -1.0); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_z >= -1.0) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":127 + /* "sklearn/linear_model/sgd_fast.pyx":130 * return 0.0 * elif z >= -1.0: * return 2.0 * (1.0 - z) * -y # <<<<<<<<<<<<<< @@ -2865,11 +2327,10 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_dloss(st */ __pyx_r = ((2.0 * (1.0 - __pyx_v_z)) * (-__pyx_v_y)); goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "sklearn/linear_model/sgd_fast.pyx":129 + /* "sklearn/linear_model/sgd_fast.pyx":132 * return 2.0 * (1.0 - z) * -y * else: * return -4.0 * y # <<<<<<<<<<<<<< @@ -2879,105 +2340,21 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_dloss(st __pyx_r = (-4.0 * __pyx_v_y); goto __pyx_L0; } - __pyx_L3:; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.ModifiedHuber.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -/* "sklearn/linear_model/sgd_fast.pyx":122 + /* "sklearn/linear_model/sgd_fast.pyx":125 * return -4.0 * z * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double z = p * y * if z >= 1.0: */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("dloss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "dloss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.ModifiedHuber.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.dloss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.ModifiedHuber.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":131 +/* "sklearn/linear_model/sgd_fast.pyx":134 * return -4.0 * y * * def __reduce__(self): # <<<<<<<<<<<<<< @@ -2985,17 +2362,29 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_1dlo * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_2__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_2__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber___reduce__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber___reduce__(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce__"); + __Pyx_RefNannySetupContext("__reduce__", 0); - /* "sklearn/linear_model/sgd_fast.pyx":132 + /* "sklearn/linear_model/sgd_fast.pyx":135 * * def __reduce__(self): * return ModifiedHuber, () # <<<<<<<<<<<<<< @@ -3003,20 +2392,27 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_2__r * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_ModifiedHuber))); PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_ModifiedHuber))); __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_ModifiedHuber))); - __Pyx_INCREF(((PyObject *)__pyx_empty_tuple)); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_empty_tuple)); - __Pyx_GIVEREF(((PyObject *)__pyx_empty_tuple)); - __pyx_r = ((PyObject *)__pyx_t_1); + __Pyx_INCREF(__pyx_empty_tuple); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_empty_tuple); + __Pyx_GIVEREF(__pyx_empty_tuple); + __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/linear_model/sgd_fast.pyx":134 + * return -4.0 * y + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return ModifiedHuber, () + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.ModifiedHuber.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -3027,7 +2423,7 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_2__r return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":148 +/* "sklearn/linear_model/sgd_fast.pyx":151 * cdef double threshold * * def __init__(self, double threshold=1.0): # <<<<<<<<<<<<<< @@ -3035,35 +2431,37 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_2__r * */ -static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static int __pyx_pw_7sklearn_12linear_model_8sgd_fast_5Hinge_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_12linear_model_8sgd_fast_5Hinge_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { double __pyx_v_threshold; - int __pyx_r; - __Pyx_RefNannyDeclarations int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__threshold,0}; - __Pyx_RefNannySetupContext("__init__"); + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_threshold,0}; PyObject* values[1] = {0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__threshold); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_threshold); if (value) { values[0] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { @@ -3073,108 +2471,87 @@ static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge___init__(PyObject * } } if (values[0]) { - __pyx_v_threshold = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_threshold == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_threshold = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_threshold == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_threshold = ((double)1.0); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__init__", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Hinge.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge___init__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *)__pyx_v_self), __pyx_v_threshold); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge___init__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_v_self, double __pyx_v_threshold) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); - /* "sklearn/linear_model/sgd_fast.pyx":149 + /* "sklearn/linear_model/sgd_fast.pyx":152 * * def __init__(self, double threshold=1.0): * self.threshold = threshold # <<<<<<<<<<<<<< * - * cpdef double loss(self, double p, double y): + * cdef double loss(self, double p, double y) nogil: + */ + __pyx_v_self->threshold = __pyx_v_threshold; + + /* "sklearn/linear_model/sgd_fast.pyx":151 + * cdef double threshold + * + * def __init__(self, double threshold=1.0): # <<<<<<<<<<<<<< + * self.threshold = threshold + * */ - ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *)__pyx_v_self)->threshold = __pyx_v_threshold; + /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":151 +/* "sklearn/linear_model/sgd_fast.pyx":154 * self.threshold = threshold * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double z = p * y * if z <= self.threshold: */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_1loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_v_z; double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("loss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__loss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_1loss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + int __pyx_t_1; - /* "sklearn/linear_model/sgd_fast.pyx":152 + /* "sklearn/linear_model/sgd_fast.pyx":155 * - * cpdef double loss(self, double p, double y): + * cdef double loss(self, double p, double y) nogil: * cdef double z = p * y # <<<<<<<<<<<<<< * if z <= self.threshold: * return (self.threshold - z) */ __pyx_v_z = (__pyx_v_p * __pyx_v_y); - /* "sklearn/linear_model/sgd_fast.pyx":153 - * cpdef double loss(self, double p, double y): + /* "sklearn/linear_model/sgd_fast.pyx":156 + * cdef double loss(self, double p, double y) nogil: * cdef double z = p * y * if z <= self.threshold: # <<<<<<<<<<<<<< * return (self.threshold - z) * return 0.0 */ - __pyx_t_6 = (__pyx_v_z <= __pyx_v_self->threshold); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_z <= __pyx_v_self->threshold) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":154 + /* "sklearn/linear_model/sgd_fast.pyx":157 * cdef double z = p * y * if z <= self.threshold: * return (self.threshold - z) # <<<<<<<<<<<<<< @@ -3183,190 +2560,64 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge_loss(struct __pyx */ __pyx_r = (__pyx_v_self->threshold - __pyx_v_z); goto __pyx_L0; - goto __pyx_L3; } - __pyx_L3:; - /* "sklearn/linear_model/sgd_fast.pyx":155 + /* "sklearn/linear_model/sgd_fast.pyx":158 * if z <= self.threshold: * return (self.threshold - z) * return 0.0 # <<<<<<<<<<<<<< * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: */ __pyx_r = 0.0; goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.Hinge.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/linear_model/sgd_fast.pyx":151 + /* "sklearn/linear_model/sgd_fast.pyx":154 * self.threshold = threshold * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double z = p * y * if z <= self.threshold: */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_1loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_1loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("loss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "loss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Hinge.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Hinge *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.loss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Hinge.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":157 +/* "sklearn/linear_model/sgd_fast.pyx":160 * return 0.0 * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double z = p * y * if z <= self.threshold: */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_2dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge_dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge__dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_v_z; double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dloss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__dloss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_2dloss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + int __pyx_t_1; - /* "sklearn/linear_model/sgd_fast.pyx":158 + /* "sklearn/linear_model/sgd_fast.pyx":161 * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: * cdef double z = p * y # <<<<<<<<<<<<<< * if z <= self.threshold: * return -y */ __pyx_v_z = (__pyx_v_p * __pyx_v_y); - /* "sklearn/linear_model/sgd_fast.pyx":159 - * cpdef double dloss(self, double p, double y): + /* "sklearn/linear_model/sgd_fast.pyx":162 + * cdef double _dloss(self, double p, double y) nogil: * cdef double z = p * y * if z <= self.threshold: # <<<<<<<<<<<<<< * return -y * return 0.0 */ - __pyx_t_6 = (__pyx_v_z <= __pyx_v_self->threshold); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_z <= __pyx_v_self->threshold) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":160 + /* "sklearn/linear_model/sgd_fast.pyx":163 * cdef double z = p * y * if z <= self.threshold: * return -y # <<<<<<<<<<<<<< @@ -3375,11 +2626,9 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge_dloss(struct __py */ __pyx_r = (-__pyx_v_y); goto __pyx_L0; - goto __pyx_L3; } - __pyx_L3:; - /* "sklearn/linear_model/sgd_fast.pyx":161 + /* "sklearn/linear_model/sgd_fast.pyx":164 * if z <= self.threshold: * return -y * return 0.0 # <<<<<<<<<<<<<< @@ -3389,112 +2638,347 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge_dloss(struct __py __pyx_r = 0.0; goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.Hinge.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + /* "sklearn/linear_model/sgd_fast.pyx":160 + * return 0.0 + * + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double z = p * y + * if z <= self.threshold: + */ + + /* function exit code */ __pyx_L0:; - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":157 +/* "sklearn/linear_model/sgd_fast.pyx":166 * return 0.0 * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< - * cdef double z = p * y - * if z <= self.threshold: + * def __reduce__(self): # <<<<<<<<<<<<<< + * return Hinge, (self.threshold,) + * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_2dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_2dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_5Hinge_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_5Hinge_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_2__reduce__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_2__reduce__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("dloss"); - { - PyObject* values[2] = {0,0}; + __Pyx_RefNannySetupContext("__reduce__", 0); + + /* "sklearn/linear_model/sgd_fast.pyx":167 + * + * def __reduce__(self): + * return Hinge, (self.threshold,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->threshold); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Hinge))); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Hinge))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Hinge))); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/linear_model/sgd_fast.pyx":166 + * return 0.0 + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return Hinge, (self.threshold,) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Hinge.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/linear_model/sgd_fast.pyx":183 + * cdef double threshold + * + * def __init__(self, double threshold=1.0): # <<<<<<<<<<<<<< + * self.threshold = threshold + * + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + double __pyx_v_threshold; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_threshold,0}; + PyObject* values[1] = {0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_threshold); + if (value) { values[0] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "dloss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + } + if (values[0]) { + __pyx_v_threshold = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_threshold == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_threshold = ((double)1.0); } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__init__", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Hinge.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.SquaredHinge.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); - return NULL; + return -1; __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Hinge *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.dloss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_12SquaredHinge___init__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *)__pyx_v_self), __pyx_v_threshold); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_12SquaredHinge___init__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *__pyx_v_self, double __pyx_v_threshold) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/linear_model/sgd_fast.pyx":184 + * + * def __init__(self, double threshold=1.0): + * self.threshold = threshold # <<<<<<<<<<<<<< + * + * cdef double loss(self, double p, double y) nogil: + */ + __pyx_v_self->threshold = __pyx_v_threshold; + + /* "sklearn/linear_model/sgd_fast.pyx":183 + * cdef double threshold + * + * def __init__(self, double threshold=1.0): # <<<<<<<<<<<<<< + * self.threshold = threshold + * + */ + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/linear_model/sgd_fast.pyx":186 + * self.threshold = threshold + * + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double z = self.threshold - p * y + * if z > 0: + */ + +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { + double __pyx_v_z; + double __pyx_r; + int __pyx_t_1; + + /* "sklearn/linear_model/sgd_fast.pyx":187 + * + * cdef double loss(self, double p, double y) nogil: + * cdef double z = self.threshold - p * y # <<<<<<<<<<<<<< + * if z > 0: + * return z * z + */ + __pyx_v_z = (__pyx_v_self->threshold - (__pyx_v_p * __pyx_v_y)); + + /* "sklearn/linear_model/sgd_fast.pyx":188 + * cdef double loss(self, double p, double y) nogil: + * cdef double z = self.threshold - p * y + * if z > 0: # <<<<<<<<<<<<<< + * return z * z + * return 0.0 + */ + __pyx_t_1 = ((__pyx_v_z > 0.0) != 0); + if (__pyx_t_1) { + + /* "sklearn/linear_model/sgd_fast.pyx":189 + * cdef double z = self.threshold - p * y + * if z > 0: + * return z * z # <<<<<<<<<<<<<< + * return 0.0 + * + */ + __pyx_r = (__pyx_v_z * __pyx_v_z); + goto __pyx_L0; + } + + /* "sklearn/linear_model/sgd_fast.pyx":190 + * if z > 0: + * return z * z + * return 0.0 # <<<<<<<<<<<<<< + * + * cdef double _dloss(self, double p, double y) nogil: + */ + __pyx_r = 0.0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "sklearn/linear_model/sgd_fast.pyx":186 + * self.threshold = threshold + * + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double z = self.threshold - p * y + * if z > 0: + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/linear_model/sgd_fast.pyx":192 + * return 0.0 + * + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double z = self.threshold - p * y + * if z > 0: + */ + +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_12SquaredHinge__dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { + double __pyx_v_z; + double __pyx_r; + int __pyx_t_1; + + /* "sklearn/linear_model/sgd_fast.pyx":193 + * + * cdef double _dloss(self, double p, double y) nogil: + * cdef double z = self.threshold - p * y # <<<<<<<<<<<<<< + * if z > 0: + * return -2 * y * z + */ + __pyx_v_z = (__pyx_v_self->threshold - (__pyx_v_p * __pyx_v_y)); + + /* "sklearn/linear_model/sgd_fast.pyx":194 + * cdef double _dloss(self, double p, double y) nogil: + * cdef double z = self.threshold - p * y + * if z > 0: # <<<<<<<<<<<<<< + * return -2 * y * z + * return 0.0 + */ + __pyx_t_1 = ((__pyx_v_z > 0.0) != 0); + if (__pyx_t_1) { + + /* "sklearn/linear_model/sgd_fast.pyx":195 + * cdef double z = self.threshold - p * y + * if z > 0: + * return -2 * y * z # <<<<<<<<<<<<<< + * return 0.0 + * + */ + __pyx_r = ((-2.0 * __pyx_v_y) * __pyx_v_z); + goto __pyx_L0; + } + + /* "sklearn/linear_model/sgd_fast.pyx":196 + * if z > 0: + * return -2 * y * z + * return 0.0 # <<<<<<<<<<<<<< + * + * def __reduce__(self): + */ + __pyx_r = 0.0; goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Hinge.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + + /* "sklearn/linear_model/sgd_fast.pyx":192 + * return 0.0 + * + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double z = self.threshold - p * y + * if z > 0: + */ + + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":163 +/* "sklearn/linear_model/sgd_fast.pyx":198 * return 0.0 * * def __reduce__(self): # <<<<<<<<<<<<<< - * return Hinge, (self.threshold,) + * return SquaredHinge, (self.threshold,) * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_2__reduce__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_2__reduce__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -3502,41 +2986,48 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_3__reduce__(P int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce__"); + __Pyx_RefNannySetupContext("__reduce__", 0); - /* "sklearn/linear_model/sgd_fast.pyx":164 + /* "sklearn/linear_model/sgd_fast.pyx":199 * * def __reduce__(self): - * return Hinge, (self.threshold,) # <<<<<<<<<<<<<< + * return SquaredHinge, (self.threshold,) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *)__pyx_v_self)->threshold); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->threshold); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Hinge))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Hinge))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Hinge))); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredHinge))); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredHinge))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredHinge))); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/linear_model/sgd_fast.pyx":198 + * return 0.0 + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return SquaredHinge, (self.threshold,) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Hinge.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.SquaredHinge.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); @@ -3544,80 +3035,39 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_3__reduce__(P return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":170 +/* "sklearn/linear_model/sgd_fast.pyx":205 * """Logistic regression loss for binary classification with y in {-1, 1}""" * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double z = p * y * # approximately equal and saves the computation of the log */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_v_z; double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("loss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__loss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_loss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + int __pyx_t_1; - /* "sklearn/linear_model/sgd_fast.pyx":171 + /* "sklearn/linear_model/sgd_fast.pyx":206 * - * cpdef double loss(self, double p, double y): + * cdef double loss(self, double p, double y) nogil: * cdef double z = p * y # <<<<<<<<<<<<<< * # approximately equal and saves the computation of the log * if z > 18: */ __pyx_v_z = (__pyx_v_p * __pyx_v_y); - /* "sklearn/linear_model/sgd_fast.pyx":173 + /* "sklearn/linear_model/sgd_fast.pyx":208 * cdef double z = p * y * # approximately equal and saves the computation of the log * if z > 18: # <<<<<<<<<<<<<< * return exp(-z) * if z < -18: */ - __pyx_t_6 = (__pyx_v_z > 18.0); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_z > 18.0) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":174 + /* "sklearn/linear_model/sgd_fast.pyx":209 * # approximately equal and saves the computation of the log * if z > 18: * return exp(-z) # <<<<<<<<<<<<<< @@ -3626,21 +3076,19 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_loss(struct __pyx_o */ __pyx_r = exp((-__pyx_v_z)); goto __pyx_L0; - goto __pyx_L3; } - __pyx_L3:; - /* "sklearn/linear_model/sgd_fast.pyx":175 + /* "sklearn/linear_model/sgd_fast.pyx":210 * if z > 18: * return exp(-z) * if z < -18: # <<<<<<<<<<<<<< * return -z * return log(1.0 + exp(-z)) */ - __pyx_t_6 = (__pyx_v_z < -18.0); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_z < -18.0) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":176 + /* "sklearn/linear_model/sgd_fast.pyx":211 * return exp(-z) * if z < -18: * return -z # <<<<<<<<<<<<<< @@ -3649,190 +3097,64 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_loss(struct __pyx_o */ __pyx_r = (-__pyx_v_z); goto __pyx_L0; - goto __pyx_L4; } - __pyx_L4:; - /* "sklearn/linear_model/sgd_fast.pyx":177 + /* "sklearn/linear_model/sgd_fast.pyx":212 * if z < -18: * return -z * return log(1.0 + exp(-z)) # <<<<<<<<<<<<<< * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: */ __pyx_r = log((1.0 + exp((-__pyx_v_z)))); goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.Log.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + /* "sklearn/linear_model/sgd_fast.pyx":205 + * """Logistic regression loss for binary classification with y in {-1, 1}""" + * + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double z = p * y + * # approximately equal and saves the computation of the log + */ + + /* function exit code */ __pyx_L0:; - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":170 - * """Logistic regression loss for binary classification with y in {-1, 1}""" +/* "sklearn/linear_model/sgd_fast.pyx":214 + * return log(1.0 + exp(-z)) * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double z = p * y * # approximately equal and saves the computation of the log */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("loss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "loss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Log.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Log *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.loss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Log.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/linear_model/sgd_fast.pyx":179 - * return log(1.0 + exp(-z)) - * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< - * cdef double z = p * y - * # approximately equal and saves the computation of the log - */ - -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_3Log__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_v_z; double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dloss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__dloss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_1dloss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + int __pyx_t_1; - /* "sklearn/linear_model/sgd_fast.pyx":180 + /* "sklearn/linear_model/sgd_fast.pyx":215 * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: * cdef double z = p * y # <<<<<<<<<<<<<< * # approximately equal and saves the computation of the log * if z > 18.0: */ __pyx_v_z = (__pyx_v_p * __pyx_v_y); - /* "sklearn/linear_model/sgd_fast.pyx":182 + /* "sklearn/linear_model/sgd_fast.pyx":217 * cdef double z = p * y * # approximately equal and saves the computation of the log * if z > 18.0: # <<<<<<<<<<<<<< * return exp(-z) * -y * if z < -18.0: */ - __pyx_t_6 = (__pyx_v_z > 18.0); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_z > 18.0) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":183 + /* "sklearn/linear_model/sgd_fast.pyx":218 * # approximately equal and saves the computation of the log * if z > 18.0: * return exp(-z) * -y # <<<<<<<<<<<<<< @@ -3841,21 +3163,19 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_dloss(struct __pyx_ */ __pyx_r = (exp((-__pyx_v_z)) * (-__pyx_v_y)); goto __pyx_L0; - goto __pyx_L3; } - __pyx_L3:; - /* "sklearn/linear_model/sgd_fast.pyx":184 + /* "sklearn/linear_model/sgd_fast.pyx":219 * if z > 18.0: * return exp(-z) * -y * if z < -18.0: # <<<<<<<<<<<<<< * return -y * return -y / (exp(z) + 1.0) */ - __pyx_t_6 = (__pyx_v_z < -18.0); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_z < -18.0) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":185 + /* "sklearn/linear_model/sgd_fast.pyx":220 * return exp(-z) * -y * if z < -18.0: * return -y # <<<<<<<<<<<<<< @@ -3864,11 +3184,9 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_dloss(struct __pyx_ */ __pyx_r = (-__pyx_v_y); goto __pyx_L0; - goto __pyx_L4; } - __pyx_L4:; - /* "sklearn/linear_model/sgd_fast.pyx":186 + /* "sklearn/linear_model/sgd_fast.pyx":221 * if z < -18.0: * return -y * return -y / (exp(z) + 1.0) # <<<<<<<<<<<<<< @@ -3878,103 +3196,20 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_dloss(struct __pyx_ __pyx_r = ((-__pyx_v_y) / (exp(__pyx_v_z) + 1.0)); goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.Log.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/linear_model/sgd_fast.pyx":179 + /* "sklearn/linear_model/sgd_fast.pyx":214 * return log(1.0 + exp(-z)) * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double z = p * y * # approximately equal and saves the computation of the log */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("dloss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "dloss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Log.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Log *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.dloss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Log.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":188 +/* "sklearn/linear_model/sgd_fast.pyx":223 * return -y / (exp(z) + 1.0) * * def __reduce__(self): # <<<<<<<<<<<<<< @@ -3982,17 +3217,29 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_1dloss(PyObject * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_2__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_2__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_3Log_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_3Log_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log___reduce__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log___reduce__(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce__"); + __Pyx_RefNannySetupContext("__reduce__", 0); - /* "sklearn/linear_model/sgd_fast.pyx":189 + /* "sklearn/linear_model/sgd_fast.pyx":224 * * def __reduce__(self): * return Log, () # <<<<<<<<<<<<<< @@ -4000,20 +3247,27 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_2__reduce__(PyO * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Log))); PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Log))); __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Log))); - __Pyx_INCREF(((PyObject *)__pyx_empty_tuple)); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_empty_tuple)); - __Pyx_GIVEREF(((PyObject *)__pyx_empty_tuple)); - __pyx_r = ((PyObject *)__pyx_t_1); + __Pyx_INCREF(__pyx_empty_tuple); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_empty_tuple); + __Pyx_GIVEREF(__pyx_empty_tuple); + __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/linear_model/sgd_fast.pyx":223 + * return -y / (exp(z) + 1.0) + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return Log, () + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Log.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -4024,219 +3278,54 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_2__reduce__(PyO return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":194 +/* "sklearn/linear_model/sgd_fast.pyx":229 * cdef class SquaredLoss(Regression): * """Squared loss traditional used in linear regression.""" - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * return 0.5 * (p - y) * (p - y) * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_loss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("loss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__loss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_loss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - /* "sklearn/linear_model/sgd_fast.pyx":195 + /* "sklearn/linear_model/sgd_fast.pyx":230 * """Squared loss traditional used in linear regression.""" - * cpdef double loss(self, double p, double y): + * cdef double loss(self, double p, double y) nogil: * return 0.5 * (p - y) * (p - y) # <<<<<<<<<<<<<< * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: */ __pyx_r = ((0.5 * (__pyx_v_p - __pyx_v_y)) * (__pyx_v_p - __pyx_v_y)); goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.SquaredLoss.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/linear_model/sgd_fast.pyx":194 + /* "sklearn/linear_model/sgd_fast.pyx":229 * cdef class SquaredLoss(Regression): * """Squared loss traditional used in linear regression.""" - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * return 0.5 * (p - y) * (p - y) * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("loss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "loss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.SquaredLoss.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredLoss *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.loss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.SquaredLoss.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":197 +/* "sklearn/linear_model/sgd_fast.pyx":232 * return 0.5 * (p - y) * (p - y) * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * return p - y * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_11SquaredLoss__dloss(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dloss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__dloss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_1dloss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - /* "sklearn/linear_model/sgd_fast.pyx":198 + /* "sklearn/linear_model/sgd_fast.pyx":233 * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: * return p - y # <<<<<<<<<<<<<< * * def __reduce__(self): @@ -4244,103 +3333,20 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_dloss(stru __pyx_r = (__pyx_v_p - __pyx_v_y); goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.SquaredLoss.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/linear_model/sgd_fast.pyx":197 + /* "sklearn/linear_model/sgd_fast.pyx":232 * return 0.5 * (p - y) * (p - y) * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * return p - y * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_1dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("dloss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "dloss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.SquaredLoss.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredLoss *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.dloss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.SquaredLoss.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":200 +/* "sklearn/linear_model/sgd_fast.pyx":235 * return p - y * * def __reduce__(self): # <<<<<<<<<<<<<< @@ -4348,17 +3354,29 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_1dloss * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_2__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_2__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss___reduce__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss___reduce__(CYTHON_UNUSED struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce__"); + __Pyx_RefNannySetupContext("__reduce__", 0); - /* "sklearn/linear_model/sgd_fast.pyx":201 + /* "sklearn/linear_model/sgd_fast.pyx":236 * * def __reduce__(self): * return SquaredLoss, () # <<<<<<<<<<<<<< @@ -4366,20 +3384,27 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_2__red * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredLoss))); PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredLoss))); __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredLoss))); - __Pyx_INCREF(((PyObject *)__pyx_empty_tuple)); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_empty_tuple)); - __Pyx_GIVEREF(((PyObject *)__pyx_empty_tuple)); - __pyx_r = ((PyObject *)__pyx_t_1); + __Pyx_INCREF(__pyx_empty_tuple); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_empty_tuple); + __Pyx_GIVEREF(__pyx_empty_tuple); + __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/linear_model/sgd_fast.pyx":235 + * return p - y + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return SquaredLoss, () + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.SquaredLoss.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -4390,7 +3415,7 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_2__red return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":215 +/* "sklearn/linear_model/sgd_fast.pyx":250 * cdef double c * * def __init__(self, double c): # <<<<<<<<<<<<<< @@ -4398,157 +3423,130 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_2__red * */ -static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static int __pyx_pw_7sklearn_12linear_model_8sgd_fast_5Huber_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_12linear_model_8sgd_fast_5Huber_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { double __pyx_v_c; - int __pyx_r; - __Pyx_RefNannyDeclarations int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__c,0}; - __Pyx_RefNannySetupContext("__init__"); + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_c,0}; PyObject* values[1] = {0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__c); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_c)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); } - __pyx_v_c = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_c == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_c = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_c == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Huber.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber___init__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *)__pyx_v_self), __pyx_v_c); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber___init__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *__pyx_v_self, double __pyx_v_c) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); - /* "sklearn/linear_model/sgd_fast.pyx":216 + /* "sklearn/linear_model/sgd_fast.pyx":251 * * def __init__(self, double c): * self.c = c # <<<<<<<<<<<<<< * - * cpdef double loss(self, double p, double y): + * cdef double loss(self, double p, double y) nogil: + */ + __pyx_v_self->c = __pyx_v_c; + + /* "sklearn/linear_model/sgd_fast.pyx":250 + * cdef double c + * + * def __init__(self, double c): # <<<<<<<<<<<<<< + * self.c = c + * */ - ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *)__pyx_v_self)->c = __pyx_v_c; + /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":218 +/* "sklearn/linear_model/sgd_fast.pyx":253 * self.c = c * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double r = p - y - * cdef double abs_r = abs(r) + * cdef double abs_r = fabs(r) */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_1loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_v_r; double __pyx_v_abs_r; double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("loss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__loss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_1loss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + int __pyx_t_1; - /* "sklearn/linear_model/sgd_fast.pyx":219 + /* "sklearn/linear_model/sgd_fast.pyx":254 * - * cpdef double loss(self, double p, double y): + * cdef double loss(self, double p, double y) nogil: * cdef double r = p - y # <<<<<<<<<<<<<< - * cdef double abs_r = abs(r) + * cdef double abs_r = fabs(r) * if abs_r <= self.c: */ __pyx_v_r = (__pyx_v_p - __pyx_v_y); - /* "sklearn/linear_model/sgd_fast.pyx":220 - * cpdef double loss(self, double p, double y): + /* "sklearn/linear_model/sgd_fast.pyx":255 + * cdef double loss(self, double p, double y) nogil: * cdef double r = p - y - * cdef double abs_r = abs(r) # <<<<<<<<<<<<<< + * cdef double abs_r = fabs(r) # <<<<<<<<<<<<<< * if abs_r <= self.c: * return 0.5 * r * r */ - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_r); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyNumber_Absolute(__pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_abs_r = __pyx_t_5; + __pyx_v_abs_r = fabs(__pyx_v_r); - /* "sklearn/linear_model/sgd_fast.pyx":221 + /* "sklearn/linear_model/sgd_fast.pyx":256 * cdef double r = p - y - * cdef double abs_r = abs(r) + * cdef double abs_r = fabs(r) * if abs_r <= self.c: # <<<<<<<<<<<<<< * return 0.5 * r * r * else: */ - __pyx_t_6 = (__pyx_v_abs_r <= __pyx_v_self->c); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_abs_r <= __pyx_v_self->c) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":222 - * cdef double abs_r = abs(r) + /* "sklearn/linear_model/sgd_fast.pyx":257 + * cdef double abs_r = fabs(r) * if abs_r <= self.c: * return 0.5 * r * r # <<<<<<<<<<<<<< * else: @@ -4556,210 +3554,77 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber_loss(struct __pyx */ __pyx_r = ((0.5 * __pyx_v_r) * __pyx_v_r); goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "sklearn/linear_model/sgd_fast.pyx":224 + /* "sklearn/linear_model/sgd_fast.pyx":259 * return 0.5 * r * r * else: * return self.c * abs_r - (0.5 * self.c * self.c) # <<<<<<<<<<<<<< * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: */ __pyx_r = ((__pyx_v_self->c * __pyx_v_abs_r) - ((0.5 * __pyx_v_self->c) * __pyx_v_self->c)); goto __pyx_L0; } - __pyx_L3:; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.Huber.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -/* "sklearn/linear_model/sgd_fast.pyx":218 + /* "sklearn/linear_model/sgd_fast.pyx":253 * self.c = c * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double r = p - y - * cdef double abs_r = abs(r) + * cdef double abs_r = fabs(r) */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_1loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_1loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("loss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "loss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Huber.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Huber *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.loss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Huber.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":226 +/* "sklearn/linear_model/sgd_fast.pyx":261 * return self.c * abs_r - (0.5 * self.c * self.c) * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double r = p - y - * cdef double abs_r = abs(r) + * cdef double abs_r = fabs(r) */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_2dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber_dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber__dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_v_r; double __pyx_v_abs_r; double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dloss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__dloss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_2dloss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + int __pyx_t_1; - /* "sklearn/linear_model/sgd_fast.pyx":227 + /* "sklearn/linear_model/sgd_fast.pyx":262 * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: * cdef double r = p - y # <<<<<<<<<<<<<< - * cdef double abs_r = abs(r) + * cdef double abs_r = fabs(r) * if abs_r <= self.c: */ __pyx_v_r = (__pyx_v_p - __pyx_v_y); - /* "sklearn/linear_model/sgd_fast.pyx":228 - * cpdef double dloss(self, double p, double y): + /* "sklearn/linear_model/sgd_fast.pyx":263 + * cdef double _dloss(self, double p, double y) nogil: * cdef double r = p - y - * cdef double abs_r = abs(r) # <<<<<<<<<<<<<< + * cdef double abs_r = fabs(r) # <<<<<<<<<<<<<< * if abs_r <= self.c: * return r */ - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_r); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyNumber_Absolute(__pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_abs_r = __pyx_t_5; + __pyx_v_abs_r = fabs(__pyx_v_r); - /* "sklearn/linear_model/sgd_fast.pyx":229 + /* "sklearn/linear_model/sgd_fast.pyx":264 * cdef double r = p - y - * cdef double abs_r = abs(r) + * cdef double abs_r = fabs(r) * if abs_r <= self.c: # <<<<<<<<<<<<<< * return r * elif r > 0.0: */ - __pyx_t_6 = (__pyx_v_abs_r <= __pyx_v_self->c); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_abs_r <= __pyx_v_self->c) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":230 - * cdef double abs_r = abs(r) + /* "sklearn/linear_model/sgd_fast.pyx":265 + * cdef double abs_r = fabs(r) * if abs_r <= self.c: * return r # <<<<<<<<<<<<<< * elif r > 0.0: @@ -4767,20 +3632,19 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber_dloss(struct __py */ __pyx_r = __pyx_v_r; goto __pyx_L0; - goto __pyx_L3; } - /* "sklearn/linear_model/sgd_fast.pyx":231 + /* "sklearn/linear_model/sgd_fast.pyx":266 * if abs_r <= self.c: * return r * elif r > 0.0: # <<<<<<<<<<<<<< * return self.c * else: */ - __pyx_t_6 = (__pyx_v_r > 0.0); - if (__pyx_t_6) { + __pyx_t_1 = ((__pyx_v_r > 0.0) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":232 + /* "sklearn/linear_model/sgd_fast.pyx":267 * return r * elif r > 0.0: * return self.c # <<<<<<<<<<<<<< @@ -4789,11 +3653,10 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber_dloss(struct __py */ __pyx_r = __pyx_v_self->c; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "sklearn/linear_model/sgd_fast.pyx":234 + /* "sklearn/linear_model/sgd_fast.pyx":269 * return self.c * else: * return -self.c # <<<<<<<<<<<<<< @@ -4803,105 +3666,21 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber_dloss(struct __py __pyx_r = (-__pyx_v_self->c); goto __pyx_L0; } - __pyx_L3:; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.Huber.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -/* "sklearn/linear_model/sgd_fast.pyx":226 + /* "sklearn/linear_model/sgd_fast.pyx":261 * return self.c * abs_r - (0.5 * self.c * self.c) * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * cdef double r = p - y - * cdef double abs_r = abs(r) + * cdef double abs_r = fabs(r) */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_2dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_2dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("dloss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "dloss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Huber.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Huber *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.dloss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.Huber.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":236 +/* "sklearn/linear_model/sgd_fast.pyx":271 * return -self.c * * def __reduce__(self): # <<<<<<<<<<<<<< @@ -4909,8 +3688,20 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_2dloss(PyObje * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_5Huber_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_5Huber_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_2__reduce__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_2__reduce__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -4918,9 +3709,9 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_3__reduce__(P int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce__"); + __Pyx_RefNannySetupContext("__reduce__", 0); - /* "sklearn/linear_model/sgd_fast.pyx":237 + /* "sklearn/linear_model/sgd_fast.pyx":272 * * def __reduce__(self): * return Huber, (self.c,) # <<<<<<<<<<<<<< @@ -4928,27 +3719,34 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_3__reduce__(P * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *)__pyx_v_self)->c); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 237; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->c); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 237; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 237; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Huber))); PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Huber))); __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Huber))); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/linear_model/sgd_fast.pyx":271 + * return -self.c + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return Huber, (self.c,) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); @@ -4960,7 +3758,7 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_3__reduce__(P return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":248 +/* "sklearn/linear_model/sgd_fast.pyx":283 * cdef double epsilon * * def __init__(self, double epsilon): # <<<<<<<<<<<<<< @@ -4968,316 +3766,160 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_3__reduce__(P * */ -static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static int __pyx_pw_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { double __pyx_v_epsilon; - int __pyx_r; - __Pyx_RefNannyDeclarations int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__epsilon,0}; - __Pyx_RefNannySetupContext("__init__"); + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_epsilon,0}; PyObject* values[1] = {0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__epsilon); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_epsilon)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 248; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); } - __pyx_v_epsilon = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_epsilon == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 248; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_epsilon = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_epsilon == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 248; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.EpsilonInsensitive.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive___init__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *)__pyx_v_self), __pyx_v_epsilon); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/linear_model/sgd_fast.pyx":249 +static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive___init__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_v_self, double __pyx_v_epsilon) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/linear_model/sgd_fast.pyx":284 * * def __init__(self, double epsilon): * self.epsilon = epsilon # <<<<<<<<<<<<<< * - * cpdef double loss(self, double p, double y): + * cdef double loss(self, double p, double y) nogil: + */ + __pyx_v_self->epsilon = __pyx_v_epsilon; + + /* "sklearn/linear_model/sgd_fast.pyx":283 + * cdef double epsilon + * + * def __init__(self, double epsilon): # <<<<<<<<<<<<<< + * self.epsilon = epsilon + * */ - ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *)__pyx_v_self)->epsilon = __pyx_v_epsilon; + /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":251 +/* "sklearn/linear_model/sgd_fast.pyx":286 * self.epsilon = epsilon * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< - * cdef double ret = abs(y - p) - self.epsilon + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double ret = fabs(y - p) - self.epsilon * return ret if ret > 0 else 0 */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_1loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_v_ret; double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("loss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__loss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_1loss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + double __pyx_t_1; - /* "sklearn/linear_model/sgd_fast.pyx":252 + /* "sklearn/linear_model/sgd_fast.pyx":287 * - * cpdef double loss(self, double p, double y): - * cdef double ret = abs(y - p) - self.epsilon # <<<<<<<<<<<<<< + * cdef double loss(self, double p, double y) nogil: + * cdef double ret = fabs(y - p) - self.epsilon # <<<<<<<<<<<<<< * return ret if ret > 0 else 0 * */ - __pyx_t_1 = PyFloat_FromDouble((__pyx_v_y - __pyx_v_p)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyNumber_Absolute(__pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->epsilon); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Subtract(__pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_4); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_ret = __pyx_t_5; + __pyx_v_ret = (fabs((__pyx_v_y - __pyx_v_p)) - __pyx_v_self->epsilon); - /* "sklearn/linear_model/sgd_fast.pyx":253 - * cpdef double loss(self, double p, double y): - * cdef double ret = abs(y - p) - self.epsilon + /* "sklearn/linear_model/sgd_fast.pyx":288 + * cdef double loss(self, double p, double y) nogil: + * cdef double ret = fabs(y - p) - self.epsilon * return ret if ret > 0 else 0 # <<<<<<<<<<<<<< * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: */ - if ((__pyx_v_ret > 0.0)) { - __pyx_t_5 = __pyx_v_ret; + if (((__pyx_v_ret > 0.0) != 0)) { + __pyx_t_1 = __pyx_v_ret; } else { - __pyx_t_5 = 0; + __pyx_t_1 = 0.0; } - __pyx_r = __pyx_t_5; - goto __pyx_L0; - - __pyx_r = 0; + __pyx_r = __pyx_t_1; goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.EpsilonInsensitive.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -/* "sklearn/linear_model/sgd_fast.pyx":251 + /* "sklearn/linear_model/sgd_fast.pyx":286 * self.epsilon = epsilon * - * cpdef double loss(self, double p, double y): # <<<<<<<<<<<<<< - * cdef double ret = abs(y - p) - self.epsilon + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double ret = fabs(y - p) - self.epsilon * return ret if ret > 0 else 0 */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_1loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_1loss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("loss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "loss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.EpsilonInsensitive.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.loss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.EpsilonInsensitive.loss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":255 +/* "sklearn/linear_model/sgd_fast.pyx":290 * return ret if ret > 0 else 0 * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< * if y - p > self.epsilon: * return -1 */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_2dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static double __pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_v_self, double __pyx_v_p, double __pyx_v_y, int __pyx_skip_dispatch) { +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive__dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { double __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - double __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dloss"); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__dloss); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (void *)&__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_2dloss)) { - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_p); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_y); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + int __pyx_t_1; - /* "sklearn/linear_model/sgd_fast.pyx":256 + /* "sklearn/linear_model/sgd_fast.pyx":291 * - * cpdef double dloss(self, double p, double y): + * cdef double _dloss(self, double p, double y) nogil: * if y - p > self.epsilon: # <<<<<<<<<<<<<< * return -1 * elif p - y > self.epsilon: */ - __pyx_t_6 = ((__pyx_v_y - __pyx_v_p) > __pyx_v_self->epsilon); - if (__pyx_t_6) { + __pyx_t_1 = (((__pyx_v_y - __pyx_v_p) > __pyx_v_self->epsilon) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":257 - * cpdef double dloss(self, double p, double y): + /* "sklearn/linear_model/sgd_fast.pyx":292 + * cdef double _dloss(self, double p, double y) nogil: * if y - p > self.epsilon: * return -1 # <<<<<<<<<<<<<< * elif p - y > self.epsilon: @@ -5285,20 +3927,19 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_dlo */ __pyx_r = -1.0; goto __pyx_L0; - goto __pyx_L3; } - /* "sklearn/linear_model/sgd_fast.pyx":258 + /* "sklearn/linear_model/sgd_fast.pyx":293 * if y - p > self.epsilon: * return -1 * elif p - y > self.epsilon: # <<<<<<<<<<<<<< * return 1 * else: */ - __pyx_t_6 = ((__pyx_v_p - __pyx_v_y) > __pyx_v_self->epsilon); - if (__pyx_t_6) { + __pyx_t_1 = (((__pyx_v_p - __pyx_v_y) > __pyx_v_self->epsilon) != 0); + if (__pyx_t_1) { - /* "sklearn/linear_model/sgd_fast.pyx":259 + /* "sklearn/linear_model/sgd_fast.pyx":294 * return -1 * elif p - y > self.epsilon: * return 1 # <<<<<<<<<<<<<< @@ -5307,11 +3948,10 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_dlo */ __pyx_r = 1.0; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "sklearn/linear_model/sgd_fast.pyx":261 + /* "sklearn/linear_model/sgd_fast.pyx":296 * return 1 * else: * return 0 # <<<<<<<<<<<<<< @@ -5321,114 +3961,347 @@ static double __pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_dlo __pyx_r = 0.0; goto __pyx_L0; } - __pyx_L3:; - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_WriteUnraisable("sklearn.linear_model.sgd_fast.EpsilonInsensitive.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + /* "sklearn/linear_model/sgd_fast.pyx":290 + * return ret if ret > 0 else 0 + * + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * if y - p > self.epsilon: + * return -1 + */ + + /* function exit code */ __pyx_L0:; - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":255 - * return ret if ret > 0 else 0 +/* "sklearn/linear_model/sgd_fast.pyx":298 + * return 0 + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return EpsilonInsensitive, (self.epsilon,) * - * cpdef double dloss(self, double p, double y): # <<<<<<<<<<<<<< - * if y - p > self.epsilon: - * return -1 */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_2dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_2dloss(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - double __pyx_v_p; - double __pyx_v_y; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_2__reduce__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_2__reduce__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("dloss"); - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } + __Pyx_RefNannySetupContext("__reduce__", 0); + + /* "sklearn/linear_model/sgd_fast.pyx":299 + * + * def __reduce__(self): + * return EpsilonInsensitive, (self.epsilon,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->epsilon); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive))); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive))); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/linear_model/sgd_fast.pyx":298 + * return 0 + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return EpsilonInsensitive, (self.epsilon,) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.EpsilonInsensitive.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/linear_model/sgd_fast.pyx":310 + * cdef double epsilon + * + * def __init__(self, double epsilon): # <<<<<<<<<<<<<< + * self.epsilon = epsilon + * + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + double __pyx_v_epsilon; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_epsilon,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_epsilon)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "dloss") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } - __pyx_v_p = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_y == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_epsilon = __pyx_PyFloat_AsDouble(values[0]); if (unlikely((__pyx_v_epsilon == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("dloss", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.EpsilonInsensitive.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.SquaredEpsilonInsensitive.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); - return NULL; + return -1; __pyx_L4_argument_unpacking_done:; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *)((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *)__pyx_v_self)->__pyx_base.__pyx_base.__pyx_vtab)->__pyx_base.__pyx_base.dloss(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_self), __pyx_v_p, __pyx_v_y, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive___init__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *)__pyx_v_self), __pyx_v_epsilon); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive___init__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *__pyx_v_self, double __pyx_v_epsilon) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/linear_model/sgd_fast.pyx":311 + * + * def __init__(self, double epsilon): + * self.epsilon = epsilon # <<<<<<<<<<<<<< + * + * cdef double loss(self, double p, double y) nogil: + */ + __pyx_v_self->epsilon = __pyx_v_epsilon; + + /* "sklearn/linear_model/sgd_fast.pyx":310 + * cdef double epsilon + * + * def __init__(self, double epsilon): # <<<<<<<<<<<<<< + * self.epsilon = epsilon + * + */ + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/linear_model/sgd_fast.pyx":313 + * self.epsilon = epsilon + * + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double ret = fabs(y - p) - self.epsilon + * return ret * ret if ret > 0 else 0 + */ + +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_loss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { + double __pyx_v_ret; + double __pyx_r; + double __pyx_t_1; + + /* "sklearn/linear_model/sgd_fast.pyx":314 + * + * cdef double loss(self, double p, double y) nogil: + * cdef double ret = fabs(y - p) - self.epsilon # <<<<<<<<<<<<<< + * return ret * ret if ret > 0 else 0 + * + */ + __pyx_v_ret = (fabs((__pyx_v_y - __pyx_v_p)) - __pyx_v_self->epsilon); + + /* "sklearn/linear_model/sgd_fast.pyx":315 + * cdef double loss(self, double p, double y) 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: + */ + if (((__pyx_v_ret > 0.0) != 0)) { + __pyx_t_1 = (__pyx_v_ret * __pyx_v_ret); + } else { + __pyx_t_1 = 0.0; + } __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.EpsilonInsensitive.dloss", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + /* "sklearn/linear_model/sgd_fast.pyx":313 + * self.epsilon = epsilon + * + * cdef double loss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double ret = fabs(y - p) - self.epsilon + * return ret * ret if ret > 0 else 0 + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/linear_model/sgd_fast.pyx":317 + * return ret * ret if ret > 0 else 0 + * + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double z + * z = y - p + */ + +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive__dloss(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *__pyx_v_self, double __pyx_v_p, double __pyx_v_y) { + double __pyx_v_z; + double __pyx_r; + int __pyx_t_1; + + /* "sklearn/linear_model/sgd_fast.pyx":319 + * cdef double _dloss(self, double p, double y) nogil: + * cdef double z + * z = y - p # <<<<<<<<<<<<<< + * if z > self.epsilon: + * return -2 * (z - self.epsilon) + */ + __pyx_v_z = (__pyx_v_y - __pyx_v_p); + + /* "sklearn/linear_model/sgd_fast.pyx":320 + * cdef double z + * z = y - p + * if z > self.epsilon: # <<<<<<<<<<<<<< + * return -2 * (z - self.epsilon) + * elif z < self.epsilon: + */ + __pyx_t_1 = ((__pyx_v_z > __pyx_v_self->epsilon) != 0); + if (__pyx_t_1) { + + /* "sklearn/linear_model/sgd_fast.pyx":321 + * z = y - p + * if z > self.epsilon: + * return -2 * (z - self.epsilon) # <<<<<<<<<<<<<< + * elif z < self.epsilon: + * return 2 * (-z - self.epsilon) + */ + __pyx_r = (-2.0 * (__pyx_v_z - __pyx_v_self->epsilon)); + goto __pyx_L0; + } + + /* "sklearn/linear_model/sgd_fast.pyx":322 + * if z > self.epsilon: + * return -2 * (z - self.epsilon) + * elif z < self.epsilon: # <<<<<<<<<<<<<< + * return 2 * (-z - self.epsilon) + * else: + */ + __pyx_t_1 = ((__pyx_v_z < __pyx_v_self->epsilon) != 0); + if (__pyx_t_1) { + + /* "sklearn/linear_model/sgd_fast.pyx":323 + * return -2 * (z - self.epsilon) + * elif z < self.epsilon: + * return 2 * (-z - self.epsilon) # <<<<<<<<<<<<<< + * else: + * return 0 + */ + __pyx_r = (2.0 * ((-__pyx_v_z) - __pyx_v_self->epsilon)); + goto __pyx_L0; + } + /*else*/ { + + /* "sklearn/linear_model/sgd_fast.pyx":325 + * return 2 * (-z - self.epsilon) + * else: + * return 0 # <<<<<<<<<<<<<< + * + * def __reduce__(self): + */ + __pyx_r = 0.0; + goto __pyx_L0; + } + + /* "sklearn/linear_model/sgd_fast.pyx":317 + * return ret * ret if ret > 0 else 0 + * + * cdef double _dloss(self, double p, double y) nogil: # <<<<<<<<<<<<<< + * cdef double z + * z = y - p + */ + + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":263 +/* "sklearn/linear_model/sgd_fast.pyx":327 * return 0 * * def __reduce__(self): # <<<<<<<<<<<<<< - * return EpsilonInsensitive, (self.epsilon,) + * return SquaredEpsilonInsensitive, (self.epsilon,) * */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_2__reduce__(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_2__reduce__(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -5436,41 +4309,48 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce__"); + __Pyx_RefNannySetupContext("__reduce__", 0); - /* "sklearn/linear_model/sgd_fast.pyx":264 + /* "sklearn/linear_model/sgd_fast.pyx":328 * * def __reduce__(self): - * return EpsilonInsensitive, (self.epsilon,) # <<<<<<<<<<<<<< + * return SquaredEpsilonInsensitive, (self.epsilon,) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *)__pyx_v_self)->epsilon); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 264; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->epsilon); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 264; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 264; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive))); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive))); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive))); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/linear_model/sgd_fast.pyx":327 + * return 0 + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return SquaredEpsilonInsensitive, (self.epsilon,) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.EpsilonInsensitive.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.SquaredEpsilonInsensitive.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); @@ -5478,30 +4358,32 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive return __pyx_r; } -/* "sklearn/linear_model/sgd_fast.pyx":267 +/* "sklearn/linear_model/sgd_fast.pyx":331 * * - * def plain_sgd(np.ndarray[DOUBLE, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * def plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< * double intercept, * LossFunction loss, */ -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_plain_sgd(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_12linear_model_8sgd_fast_plain_sgd[] = "Plain SGD for generic loss functions and penalties.\n\n Parameters\n ----------\n weights : ndarray[double, ndim=1]\n The allocated coef_ vector.\n intercept : double\n The initial intercept.\n loss : LossFunction\n A concrete ``LossFunction`` object.\n penalty_type : int\n The penalty 2 for L2, 1 for L1, and 3 for Elastic-Net.\n alpha : float\n The regularization parameter.\n rho : float\n The elastic net hyperparameter.\n dataset : SequentialDataset\n A concrete ``SequentialDataset`` object.\n n_iter : int\n The number of iterations (epochs).\n fit_intercept : int\n Whether or not to fit the intercept (1 or 0).\n verbose : int\n Print verbose output; 0 for quite.\n shuffle : int\n Whether to shuffle the training data before each epoch.\n weight_pos : float\n The weight of the positive class.\n weight_neg : float\n The weight of the negative class.\n seed : int\n The seed of the pseudo random number generator to use when\n shuffling the data\n learning_rate : int\n The learning rate:\n (1) constant, eta = eta0\n (2) optimal, eta = 1.0/(t+t0)\n (3) inverse scaling, eta = eta0 / pow(t, power_t)\n eta0 : double\n The initial learning rate.\n power_t : double\n The exponent for inverse scaling learning rate.\n t : double\n Initial state of the learning rate. This value is equal to the\n iteration count except when the learning rate is set to `optimal`.\n Default: 1.0.\n\n Returns\n -------\n weights : array, shape=[n_features]\n The fitted weight vector.\n intercept : float\n The fitted intercept term.\n\n "; -static PyMethodDef __pyx_mdef_7sklearn_12linear_model_8sgd_fast_plain_sgd = {__Pyx_NAMESTR("plain_sgd"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_plain_sgd, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_12linear_model_8sgd_fast_plain_sgd)}; -static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_plain_sgd(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_1plain_sgd(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_12linear_model_8sgd_fast_plain_sgd[] = "Plain SGD for generic loss functions and penalties.\n\n Parameters\n ----------\n weights : ndarray[double, ndim=1]\n The allocated coef_ vector.\n intercept : double\n The initial intercept.\n loss : LossFunction\n A concrete ``LossFunction`` object.\n penalty_type : int\n The penalty 2 for L2, 1 for L1, and 3 for Elastic-Net.\n alpha : float\n The regularization parameter.\n C : float\n Maximum step size for passive aggressive.\n l1_ratio : float\n The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1.\n l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1.\n dataset : SequentialDataset\n A concrete ``SequentialDataset`` object.\n n_iter : int\n The number of iterations (epochs).\n fit_intercept : int\n Whether or not to fit the intercept (1 or 0).\n verbose : int\n Print verbose output; 0 for quite.\n shuffle : boolean\n Whether to shuffle the training data before each epoch.\n weight_pos : float\n The weight of the positive class.\n weight_neg : float\n The weight of the negative class.\n seed : np.uint32_t\n Seed of the pseudorandom number generator used to shuffle the data.\n learning_rate : int\n The learning rate:\n (1) constant, eta = eta0\n (2) optimal, eta = 1.0/(alpha * t).\n (3) inverse scaling, eta = eta0 / pow(t, power_t)\n (4) Passive Agressive-I, eta = min(alpha, loss/norm(x))\n (5) Passive Agressive-II, eta = 1.0 / (norm(x) + 0.5*alpha)\n eta0 : double\n The initial learning rate.\n power_t : double\n The exponent for inverse scaling learning rate.\n t : double\n Initial state of the learning rate. This value is equal to the\n iteration count except when the learning rate is set to `optimal`.\n Default: 1.0.\n\n Returns\n -------\n weights : array, shape=[n_features]\n The fitted"" weight vector.\n intercept : float\n The fitted intercept term.\n "; +static PyMethodDef __pyx_mdef_7sklearn_12linear_model_8sgd_fast_1plain_sgd = {"plain_sgd", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_1plain_sgd, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_12linear_model_8sgd_fast_plain_sgd}; +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_1plain_sgd(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_weights = 0; double __pyx_v_intercept; struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_loss = 0; int __pyx_v_penalty_type; double __pyx_v_alpha; - double __pyx_v_rho; + double __pyx_v_C; + double __pyx_v_l1_ratio; struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_dataset = 0; int __pyx_v_n_iter; int __pyx_v_fit_intercept; int __pyx_v_verbose; int __pyx_v_shuffle; - int __pyx_v_seed; + __pyx_t_5numpy_uint32_t __pyx_v_seed; double __pyx_v_weight_pos; double __pyx_v_weight_neg; int __pyx_v_learning_rate; @@ -5509,64 +4391,20 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_plain_sgd(PyObject * double __pyx_v_power_t; double __pyx_v_t; double __pyx_v_intercept_decay; - Py_ssize_t __pyx_v_n_samples; - Py_ssize_t __pyx_v_n_features; - struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_w = 0; - __pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE *__pyx_v_x_data_ptr; - __pyx_t_7sklearn_12linear_model_8sgd_fast_INTEGER *__pyx_v_x_ind_ptr; - int __pyx_v_xnnz; - double __pyx_v_eta; - double __pyx_v_p; - double __pyx_v_update; - double __pyx_v_sumloss; - __pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE __pyx_v_y; - __pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE __pyx_v_sample_weight; - double __pyx_v_class_weight; - unsigned int __pyx_v_count; - unsigned int __pyx_v_epoch; - unsigned int __pyx_v_i; - PyArrayObject *__pyx_v_q = 0; - __pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE *__pyx_v_q_data_ptr; - double __pyx_v_u; - PyObject *__pyx_v_t_start = NULL; - Py_buffer __pyx_bstruct_q; - Py_ssize_t __pyx_bstride_0_q = 0; - Py_ssize_t __pyx_bshape_0_q = 0; - Py_buffer __pyx_bstruct_weights; - Py_ssize_t __pyx_bstride_0_weights = 0; - Py_ssize_t __pyx_bshape_0_weights = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyArrayObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - unsigned int __pyx_t_11; - int __pyx_t_12; - Py_ssize_t __pyx_t_13; - unsigned int __pyx_t_14; - PyObject *__pyx_t_15 = NULL; - int __pyx_t_16; - int __pyx_t_17; - int __pyx_t_18; - int __pyx_t_19; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__weights,&__pyx_n_s__intercept,&__pyx_n_s__loss,&__pyx_n_s__penalty_type,&__pyx_n_s__alpha,&__pyx_n_s__rho,&__pyx_n_s__dataset,&__pyx_n_s__n_iter,&__pyx_n_s__fit_intercept,&__pyx_n_s__verbose,&__pyx_n_s__shuffle,&__pyx_n_s__seed,&__pyx_n_s__weight_pos,&__pyx_n_s__weight_neg,&__pyx_n_s__learning_rate,&__pyx_n_s__eta0,&__pyx_n_s__power_t,&__pyx_n_s__t,&__pyx_n_s__intercept_decay,0}; - __Pyx_RefNannySetupContext("plain_sgd"); - __pyx_self = __pyx_self; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("plain_sgd (wrapper)", 0); { - PyObject* values[19] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_weights,&__pyx_n_s_intercept,&__pyx_n_s_loss,&__pyx_n_s_penalty_type,&__pyx_n_s_alpha,&__pyx_n_s_C,&__pyx_n_s_l1_ratio,&__pyx_n_s_dataset,&__pyx_n_s_n_iter,&__pyx_n_s_fit_intercept,&__pyx_n_s_verbose,&__pyx_n_s_shuffle,&__pyx_n_s_seed,&__pyx_n_s_weight_pos,&__pyx_n_s_weight_neg,&__pyx_n_s_learning_rate,&__pyx_n_s_eta0,&__pyx_n_s_power_t,&__pyx_n_s_t,&__pyx_n_s_intercept_decay,0}; + PyObject* values[20] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); @@ -5590,126 +4428,115 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_plain_sgd(PyObject * default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weights); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_weights)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__intercept); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_intercept)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__loss); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_loss)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__penalty_type); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_penalty_type)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__alpha); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_alpha)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__rho); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_C)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dataset); - if (likely(values[6])) kw_args--; + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_l1_ratio)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: - values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_iter); - if (likely(values[7])) kw_args--; + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dataset)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: - values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__fit_intercept); - if (likely(values[8])) kw_args--; + if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_iter)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: - values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__verbose); - if (likely(values[9])) kw_args--; + if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_fit_intercept)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: - values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shuffle); - if (likely(values[10])) kw_args--; + if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_verbose)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 11: - values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed); - if (likely(values[11])) kw_args--; + if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shuffle)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 12: - values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight_pos); - if (likely(values[12])) kw_args--; + if (likely((values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_seed)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 13: - values[13] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight_neg); - if (likely(values[13])) kw_args--; + if (likely((values[13] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_weight_pos)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 13); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 13); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 14: - values[14] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__learning_rate); - if (likely(values[14])) kw_args--; + if (likely((values[14] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_weight_neg)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 14); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 14); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 15: - values[15] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__eta0); - if (likely(values[15])) kw_args--; + if (likely((values[15] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_learning_rate)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 15); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 15); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 16: - values[16] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__power_t); - if (likely(values[16])) kw_args--; + if (likely((values[16] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_eta0)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, 16); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 16); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 17: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__t); - if (value) { values[17] = value; kw_args--; } + if (likely((values[17] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_power_t)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, 17); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 18: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__intercept_decay); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_t); if (value) { values[18] = value; kw_args--; } } + case 19: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_intercept_decay); + if (value) { values[19] = value; kw_args--; } + } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "plain_sgd") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "plain_sgd") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { + case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); - case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); + values[16] = PyTuple_GET_ITEM(__pyx_args, 16); values[15] = PyTuple_GET_ITEM(__pyx_args, 15); values[14] = PyTuple_GET_ITEM(__pyx_args, 14); values[13] = PyTuple_GET_ITEM(__pyx_args, 13); @@ -5731,5237 +4558,7620 @@ static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_plain_sgd(PyObject * } } __pyx_v_weights = ((PyArrayObject *)values[0]); - __pyx_v_intercept = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_intercept == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 268; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_intercept = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_intercept == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 332; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_loss = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)values[2]); - __pyx_v_penalty_type = __Pyx_PyInt_AsInt(values[3]); if (unlikely((__pyx_v_penalty_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_alpha = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_alpha == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_rho = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_rho == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_dataset = ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *)values[6]); - __pyx_v_n_iter = __Pyx_PyInt_AsInt(values[7]); if (unlikely((__pyx_v_n_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_fit_intercept = __Pyx_PyInt_AsInt(values[8]); if (unlikely((__pyx_v_fit_intercept == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_verbose = __Pyx_PyInt_AsInt(values[9]); if (unlikely((__pyx_v_verbose == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 274; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_shuffle = __Pyx_PyInt_AsInt(values[10]); if (unlikely((__pyx_v_shuffle == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 274; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_seed = __Pyx_PyInt_AsInt(values[11]); if (unlikely((__pyx_v_seed == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 274; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_weight_pos = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_weight_pos == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_weight_neg = __pyx_PyFloat_AsDouble(values[13]); if (unlikely((__pyx_v_weight_neg == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_learning_rate = __Pyx_PyInt_AsInt(values[14]); if (unlikely((__pyx_v_learning_rate == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_eta0 = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_eta0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_power_t = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_power_t == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - if (values[17]) { - __pyx_v_t = __pyx_PyFloat_AsDouble(values[17]); if (unlikely((__pyx_v_t == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_penalty_type = __Pyx_PyInt_As_int(values[3]); if (unlikely((__pyx_v_penalty_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 334; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_alpha = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_alpha == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_C = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_l1_ratio = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_l1_ratio == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 336; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_dataset = ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *)values[7]); + __pyx_v_n_iter = __Pyx_PyInt_As_int(values[8]); if (unlikely((__pyx_v_n_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 338; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_fit_intercept = __Pyx_PyInt_As_int(values[9]); if (unlikely((__pyx_v_fit_intercept == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 338; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_verbose = __Pyx_PyInt_As_int(values[10]); if (unlikely((__pyx_v_verbose == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 339; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_shuffle = __Pyx_PyObject_IsTrue(values[11]); if (unlikely((__pyx_v_shuffle == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 339; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_seed = __Pyx_PyInt_As_npy_uint32(values[12]); if (unlikely((__pyx_v_seed == (npy_uint32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 339; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_weight_pos = __pyx_PyFloat_AsDouble(values[13]); if (unlikely((__pyx_v_weight_pos == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_weight_neg = __pyx_PyFloat_AsDouble(values[14]); if (unlikely((__pyx_v_weight_neg == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_learning_rate = __Pyx_PyInt_As_int(values[15]); if (unlikely((__pyx_v_learning_rate == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 341; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_eta0 = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_eta0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 341; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_power_t = __pyx_PyFloat_AsDouble(values[17]); if (unlikely((__pyx_v_power_t == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 342; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[18]) { + __pyx_v_t = __pyx_PyFloat_AsDouble(values[18]); if (unlikely((__pyx_v_t == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/linear_model/sgd_fast.pyx":278 - * int learning_rate, double eta0, - * double power_t, - * double t=1.0, # <<<<<<<<<<<<<< - * double intercept_decay=1.0): - * """Plain SGD for generic loss functions and penalties. - */ __pyx_v_t = ((double)1.0); } - if (values[18]) { - __pyx_v_intercept_decay = __pyx_PyFloat_AsDouble(values[18]); if (unlikely((__pyx_v_intercept_decay == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[19]) { + __pyx_v_intercept_decay = __pyx_PyFloat_AsDouble(values[19]); if (unlikely((__pyx_v_intercept_decay == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 344; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/linear_model/sgd_fast.pyx":279 - * double power_t, - * double t=1.0, - * double intercept_decay=1.0): # <<<<<<<<<<<<<< - * """Plain SGD for generic loss functions and penalties. - * - */ __pyx_v_intercept_decay = ((double)1.0); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 17, 19, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("plain_sgd", 0, 18, 20, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.plain_sgd", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_q.buf = NULL; - __pyx_bstruct_weights.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weights), __pyx_ptype_5numpy_ndarray, 1, "weights", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_loss), __pyx_ptype_7sklearn_12linear_model_8sgd_fast_LossFunction, 1, "loss", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_dataset), __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset, 1, "dataset", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_weights, (PyObject*)__pyx_v_weights, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_weights = __pyx_bstruct_weights.strides[0]; - __pyx_bshape_0_weights = __pyx_bstruct_weights.shape[0]; - - /* "sklearn/linear_model/sgd_fast.pyx":337 - * - * # get the data information into easy vars - * cdef Py_ssize_t n_samples = dataset.n_samples # <<<<<<<<<<<<<< - * cdef Py_ssize_t n_features = weights.shape[0] - * - */ - __pyx_v_n_samples = __pyx_v_dataset->n_samples; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weights), __pyx_ptype_5numpy_ndarray, 1, "weights", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_loss), __pyx_ptype_7sklearn_12linear_model_8sgd_fast_LossFunction, 1, "loss", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 333; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_dataset), __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset, 1, "dataset", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_plain_sgd(__pyx_self, __pyx_v_weights, __pyx_v_intercept, __pyx_v_loss, __pyx_v_penalty_type, __pyx_v_alpha, __pyx_v_C, __pyx_v_l1_ratio, __pyx_v_dataset, __pyx_v_n_iter, __pyx_v_fit_intercept, __pyx_v_verbose, __pyx_v_shuffle, __pyx_v_seed, __pyx_v_weight_pos, __pyx_v_weight_neg, __pyx_v_learning_rate, __pyx_v_eta0, __pyx_v_power_t, __pyx_v_t, __pyx_v_intercept_decay); - /* "sklearn/linear_model/sgd_fast.pyx":338 - * # get the data information into easy vars - * cdef Py_ssize_t n_samples = dataset.n_samples - * cdef Py_ssize_t n_features = weights.shape[0] # <<<<<<<<<<<<<< - * - * cdef WeightVector w = WeightVector(weights) - */ - __pyx_v_n_features = (__pyx_v_weights->dimensions[0]); + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/linear_model/sgd_fast.pyx":340 - * cdef Py_ssize_t n_features = weights.shape[0] - * - * cdef WeightVector w = WeightVector(weights) # <<<<<<<<<<<<<< - * - * cdef DOUBLE *x_data_ptr = NULL - */ - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_v_weights)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_weights)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_weights)); - __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_5utils_13weight_vector_WeightVector)), ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_v_w = ((struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "sklearn/linear_model/sgd_fast.pyx":342 - * cdef WeightVector w = WeightVector(weights) - * - * cdef DOUBLE *x_data_ptr = NULL # <<<<<<<<<<<<<< - * cdef INTEGER *x_ind_ptr = NULL - * - */ - __pyx_v_x_data_ptr = NULL; - - /* "sklearn/linear_model/sgd_fast.pyx":343 - * - * cdef DOUBLE *x_data_ptr = NULL - * cdef INTEGER *x_ind_ptr = NULL # <<<<<<<<<<<<<< - * - * # helper variable - */ - __pyx_v_x_ind_ptr = NULL; - - /* "sklearn/linear_model/sgd_fast.pyx":347 - * # helper variable - * cdef int xnnz - * cdef double eta = 0.0 # <<<<<<<<<<<<<< - * cdef double p = 0.0 - * cdef double update = 0.0 - */ - __pyx_v_eta = 0.0; - - /* "sklearn/linear_model/sgd_fast.pyx":348 - * cdef int xnnz - * cdef double eta = 0.0 - * cdef double p = 0.0 # <<<<<<<<<<<<<< - * cdef double update = 0.0 - * cdef double sumloss = 0.0 - */ - __pyx_v_p = 0.0; - - /* "sklearn/linear_model/sgd_fast.pyx":349 - * cdef double eta = 0.0 - * cdef double p = 0.0 - * cdef double update = 0.0 # <<<<<<<<<<<<<< - * cdef double sumloss = 0.0 - * cdef DOUBLE y = 0.0 - */ - __pyx_v_update = 0.0; - - /* "sklearn/linear_model/sgd_fast.pyx":350 - * cdef double p = 0.0 - * cdef double update = 0.0 - * cdef double sumloss = 0.0 # <<<<<<<<<<<<<< - * cdef DOUBLE y = 0.0 - * cdef DOUBLE sample_weight - */ - __pyx_v_sumloss = 0.0; - - /* "sklearn/linear_model/sgd_fast.pyx":351 - * cdef double update = 0.0 - * cdef double sumloss = 0.0 - * cdef DOUBLE y = 0.0 # <<<<<<<<<<<<<< - * cdef DOUBLE sample_weight - * cdef double class_weight = 1.0 - */ - __pyx_v_y = 0.0; +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_plain_sgd(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_weights, double __pyx_v_intercept, struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_loss, int __pyx_v_penalty_type, double __pyx_v_alpha, double __pyx_v_C, double __pyx_v_l1_ratio, struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_dataset, int __pyx_v_n_iter, int __pyx_v_fit_intercept, int __pyx_v_verbose, int __pyx_v_shuffle, __pyx_t_5numpy_uint32_t __pyx_v_seed, double __pyx_v_weight_pos, double __pyx_v_weight_neg, int __pyx_v_learning_rate, double __pyx_v_eta0, double __pyx_v_power_t, double __pyx_v_t, double __pyx_v_intercept_decay) { + PyObject *__pyx_v_standard_weights = NULL; + PyObject *__pyx_v_standard_intercept = NULL; + CYTHON_UNUSED PyObject *__pyx_v__ = NULL; + __Pyx_LocalBuf_ND __pyx_pybuffernd_weights; + __Pyx_Buffer __pyx_pybuffer_weights; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + PyObject *__pyx_t_14 = NULL; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + PyObject *__pyx_t_17 = NULL; + PyObject *__pyx_t_18 = NULL; + PyObject *__pyx_t_19 = NULL; + PyObject *__pyx_t_20 = NULL; + Py_ssize_t __pyx_t_21; + PyObject *__pyx_t_22 = NULL; + PyObject *(*__pyx_t_23)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("plain_sgd", 0); + __pyx_pybuffer_weights.pybuffer.buf = NULL; + __pyx_pybuffer_weights.refcount = 0; + __pyx_pybuffernd_weights.data = NULL; + __pyx_pybuffernd_weights.rcbuffer = &__pyx_pybuffer_weights; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weights.rcbuffer->pybuffer, (PyObject*)__pyx_v_weights, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_weights.diminfo[0].strides = __pyx_pybuffernd_weights.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weights.diminfo[0].shape = __pyx_pybuffernd_weights.rcbuffer->pybuffer.shape[0]; - /* "sklearn/linear_model/sgd_fast.pyx":353 - * cdef DOUBLE y = 0.0 - * cdef DOUBLE sample_weight - * cdef double class_weight = 1.0 # <<<<<<<<<<<<<< - * cdef unsigned int count = 0 - * cdef unsigned int epoch = 0 + /* "sklearn/linear_model/sgd_fast.pyx":404 + * """ + * standard_weights, standard_intercept,\ + * _, _ = _plain_sgd(weights, # <<<<<<<<<<<<<< + * intercept, + * None, */ - __pyx_v_class_weight = 1.0; + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_plain_sgd); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 404; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); - /* "sklearn/linear_model/sgd_fast.pyx":354 - * cdef DOUBLE sample_weight - * cdef double class_weight = 1.0 - * cdef unsigned int count = 0 # <<<<<<<<<<<<<< - * cdef unsigned int epoch = 0 - * cdef unsigned int i = 0 + /* "sklearn/linear_model/sgd_fast.pyx":405 + * standard_weights, standard_intercept,\ + * _, _ = _plain_sgd(weights, + * intercept, # <<<<<<<<<<<<<< + * None, + * 0, */ - __pyx_v_count = 0; + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_intercept); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 405; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); - /* "sklearn/linear_model/sgd_fast.pyx":355 - * cdef double class_weight = 1.0 - * cdef unsigned int count = 0 - * cdef unsigned int epoch = 0 # <<<<<<<<<<<<<< - * cdef unsigned int i = 0 - * + /* "sklearn/linear_model/sgd_fast.pyx":409 + * 0, + * loss, + * penalty_type, # <<<<<<<<<<<<<< + * alpha, C, + * l1_ratio, */ - __pyx_v_epoch = 0; + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_penalty_type); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 409; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); - /* "sklearn/linear_model/sgd_fast.pyx":356 - * cdef unsigned int count = 0 - * cdef unsigned int epoch = 0 - * cdef unsigned int i = 0 # <<<<<<<<<<<<<< - * - * # q vector is only used for L1 regularization + /* "sklearn/linear_model/sgd_fast.pyx":410 + * loss, + * penalty_type, + * alpha, C, # <<<<<<<<<<<<<< + * l1_ratio, + * dataset, */ - __pyx_v_i = 0; + __pyx_t_5 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyFloat_FromDouble(__pyx_v_C); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); - /* "sklearn/linear_model/sgd_fast.pyx":359 - * - * # q vector is only used for L1 regularization - * cdef np.ndarray[DOUBLE, ndim=1, mode="c"] q = None # <<<<<<<<<<<<<< - * cdef DOUBLE *q_data_ptr = NULL - * if penalty_type == L1 or penalty_type == ELASTICNET: - */ - __pyx_t_3 = ((PyArrayObject *)Py_None); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_q, (PyObject*)__pyx_t_3, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - __pyx_v_q = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_q.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_q = __pyx_bstruct_q.strides[0]; - __pyx_bshape_0_q = __pyx_bstruct_q.shape[0]; + /* "sklearn/linear_model/sgd_fast.pyx":411 + * penalty_type, + * alpha, C, + * l1_ratio, # <<<<<<<<<<<<<< + * dataset, + * n_iter, fit_intercept, + */ + __pyx_t_7 = PyFloat_FromDouble(__pyx_v_l1_ratio); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + + /* "sklearn/linear_model/sgd_fast.pyx":413 + * l1_ratio, + * dataset, + * n_iter, fit_intercept, # <<<<<<<<<<<<<< + * verbose, shuffle, seed, + * weight_pos, weight_neg, + */ + __pyx_t_8 = __Pyx_PyInt_From_int(__pyx_v_n_iter); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyInt_From_int(__pyx_v_fit_intercept); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + + /* "sklearn/linear_model/sgd_fast.pyx":414 + * dataset, + * n_iter, fit_intercept, + * verbose, shuffle, seed, # <<<<<<<<<<<<<< + * weight_pos, weight_neg, + * learning_rate, eta0, + */ + __pyx_t_10 = __Pyx_PyInt_From_int(__pyx_v_verbose); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = __Pyx_PyBool_FromLong(__pyx_v_shuffle); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_12 = __Pyx_PyInt_From_npy_uint32(__pyx_v_seed); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + + /* "sklearn/linear_model/sgd_fast.pyx":415 + * n_iter, fit_intercept, + * verbose, shuffle, seed, + * weight_pos, weight_neg, # <<<<<<<<<<<<<< + * learning_rate, eta0, + * power_t, + */ + __pyx_t_13 = PyFloat_FromDouble(__pyx_v_weight_pos); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_13); + __pyx_t_14 = PyFloat_FromDouble(__pyx_v_weight_neg); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_14); + + /* "sklearn/linear_model/sgd_fast.pyx":416 + * verbose, shuffle, seed, + * weight_pos, weight_neg, + * learning_rate, eta0, # <<<<<<<<<<<<<< + * power_t, + * t, + */ + __pyx_t_15 = __Pyx_PyInt_From_int(__pyx_v_learning_rate); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_16 = PyFloat_FromDouble(__pyx_v_eta0); if (unlikely(!__pyx_t_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_16); + + /* "sklearn/linear_model/sgd_fast.pyx":417 + * weight_pos, weight_neg, + * learning_rate, eta0, + * power_t, # <<<<<<<<<<<<<< + * t, + * intercept_decay, + */ + __pyx_t_17 = PyFloat_FromDouble(__pyx_v_power_t); if (unlikely(!__pyx_t_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 417; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_17); + + /* "sklearn/linear_model/sgd_fast.pyx":418 + * learning_rate, eta0, + * power_t, + * t, # <<<<<<<<<<<<<< + * intercept_decay, + * 0) + */ + __pyx_t_18 = PyFloat_FromDouble(__pyx_v_t); if (unlikely(!__pyx_t_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_18); + + /* "sklearn/linear_model/sgd_fast.pyx":419 + * power_t, + * t, + * intercept_decay, # <<<<<<<<<<<<<< + * 0) + * return standard_weights, standard_intercept + */ + __pyx_t_19 = PyFloat_FromDouble(__pyx_v_intercept_decay); if (unlikely(!__pyx_t_19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 419; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_19); + __pyx_t_20 = NULL; + __pyx_t_21 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_20 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_20)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_20); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_21 = 1; } } - __pyx_t_3 = 0; + __pyx_t_22 = PyTuple_New(23+__pyx_t_21); if (unlikely(!__pyx_t_22)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 404; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_22); + if (__pyx_t_20) { + PyTuple_SET_ITEM(__pyx_t_22, 0, __pyx_t_20); __Pyx_GIVEREF(__pyx_t_20); __pyx_t_20 = NULL; + } + __Pyx_INCREF(((PyObject *)__pyx_v_weights)); + PyTuple_SET_ITEM(__pyx_t_22, 0+__pyx_t_21, ((PyObject *)__pyx_v_weights)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_weights)); + PyTuple_SET_ITEM(__pyx_t_22, 1+__pyx_t_21, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); __Pyx_INCREF(Py_None); - __pyx_v_q = ((PyArrayObject *)Py_None); - - /* "sklearn/linear_model/sgd_fast.pyx":360 - * # q vector is only used for L1 regularization - * cdef np.ndarray[DOUBLE, ndim=1, mode="c"] q = None - * cdef DOUBLE *q_data_ptr = NULL # <<<<<<<<<<<<<< - * if penalty_type == L1 or penalty_type == ELASTICNET: - * q = np.zeros((n_features,), dtype=np.float64, order="c") - */ - __pyx_v_q_data_ptr = NULL; - - /* "sklearn/linear_model/sgd_fast.pyx":361 - * cdef np.ndarray[DOUBLE, ndim=1, mode="c"] q = None - * cdef DOUBLE *q_data_ptr = NULL - * if penalty_type == L1 or penalty_type == ELASTICNET: # <<<<<<<<<<<<<< - * q = np.zeros((n_features,), dtype=np.float64, order="c") - * q_data_ptr = q.data - */ - switch (__pyx_v_penalty_type) { - case 1: - case 3: - - /* "sklearn/linear_model/sgd_fast.pyx":362 - * cdef DOUBLE *q_data_ptr = NULL - * if penalty_type == L1 or penalty_type == ELASTICNET: - * q = np.zeros((n_features,), dtype=np.float64, order="c") # <<<<<<<<<<<<<< - * q_data_ptr = q.data - * cdef double u = 0.0 - */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_n_features); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); - __pyx_t_4 = 0; - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__c)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = ((PyArrayObject *)__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_22, 2+__pyx_t_21, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_22, 3+__pyx_t_21, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + __Pyx_INCREF(((PyObject *)__pyx_v_loss)); + PyTuple_SET_ITEM(__pyx_t_22, 4+__pyx_t_21, ((PyObject *)__pyx_v_loss)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_loss)); + PyTuple_SET_ITEM(__pyx_t_22, 5+__pyx_t_21, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_22, 6+__pyx_t_21, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_22, 7+__pyx_t_21, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_22, 8+__pyx_t_21, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __Pyx_INCREF(((PyObject *)__pyx_v_dataset)); + PyTuple_SET_ITEM(__pyx_t_22, 9+__pyx_t_21, ((PyObject *)__pyx_v_dataset)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_dataset)); + PyTuple_SET_ITEM(__pyx_t_22, 10+__pyx_t_21, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_22, 11+__pyx_t_21, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_22, 12+__pyx_t_21, __pyx_t_10); + __Pyx_GIVEREF(__pyx_t_10); + PyTuple_SET_ITEM(__pyx_t_22, 13+__pyx_t_21, __pyx_t_11); + __Pyx_GIVEREF(__pyx_t_11); + PyTuple_SET_ITEM(__pyx_t_22, 14+__pyx_t_21, __pyx_t_12); + __Pyx_GIVEREF(__pyx_t_12); + PyTuple_SET_ITEM(__pyx_t_22, 15+__pyx_t_21, __pyx_t_13); + __Pyx_GIVEREF(__pyx_t_13); + PyTuple_SET_ITEM(__pyx_t_22, 16+__pyx_t_21, __pyx_t_14); + __Pyx_GIVEREF(__pyx_t_14); + PyTuple_SET_ITEM(__pyx_t_22, 17+__pyx_t_21, __pyx_t_15); + __Pyx_GIVEREF(__pyx_t_15); + PyTuple_SET_ITEM(__pyx_t_22, 18+__pyx_t_21, __pyx_t_16); + __Pyx_GIVEREF(__pyx_t_16); + PyTuple_SET_ITEM(__pyx_t_22, 19+__pyx_t_21, __pyx_t_17); + __Pyx_GIVEREF(__pyx_t_17); + PyTuple_SET_ITEM(__pyx_t_22, 20+__pyx_t_21, __pyx_t_18); + __Pyx_GIVEREF(__pyx_t_18); + PyTuple_SET_ITEM(__pyx_t_22, 21+__pyx_t_21, __pyx_t_19); + __Pyx_GIVEREF(__pyx_t_19); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_22, 22+__pyx_t_21, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_8 = 0; + __pyx_t_9 = 0; + __pyx_t_10 = 0; + __pyx_t_11 = 0; + __pyx_t_12 = 0; + __pyx_t_13 = 0; + __pyx_t_14 = 0; + __pyx_t_15 = 0; + __pyx_t_16 = 0; + __pyx_t_17 = 0; + __pyx_t_18 = 0; + __pyx_t_19 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_22, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 404; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_22); __pyx_t_22 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 4)) { + if (size > 4) __Pyx_RaiseTooManyValuesError(4); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_22 = PyTuple_GET_ITEM(sequence, 1); + __pyx_t_19 = PyTuple_GET_ITEM(sequence, 2); + __pyx_t_18 = PyTuple_GET_ITEM(sequence, 3); + } else { + __pyx_t_2 = PyList_GET_ITEM(sequence, 0); + __pyx_t_22 = PyList_GET_ITEM(sequence, 1); + __pyx_t_19 = PyList_GET_ITEM(sequence, 2); + __pyx_t_18 = PyList_GET_ITEM(sequence, 3); + } + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_22); + __Pyx_INCREF(__pyx_t_19); + __Pyx_INCREF(__pyx_t_18); + #else { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_q); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_q, (PyObject*)__pyx_t_3, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_q, (PyObject*)__pyx_v_q, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); - } + Py_ssize_t i; + PyObject** temps[4] = {&__pyx_t_2,&__pyx_t_22,&__pyx_t_19,&__pyx_t_18}; + for (i=0; i < 4; i++) { + PyObject* item = PySequence_ITEM(sequence, i); if (unlikely(!item)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(item); + *(temps[i]) = item; } - __pyx_bstride_0_q = __pyx_bstruct_q.strides[0]; - __pyx_bshape_0_q = __pyx_bstruct_q.shape[0]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_q)); - __pyx_v_q = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; - - /* "sklearn/linear_model/sgd_fast.pyx":363 - * if penalty_type == L1 or penalty_type == ELASTICNET: - * q = np.zeros((n_features,), dtype=np.float64, order="c") - * q_data_ptr = q.data # <<<<<<<<<<<<<< - * cdef double u = 0.0 - * - */ - __pyx_v_q_data_ptr = ((__pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE *)__pyx_v_q->data); - break; + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + PyObject** temps[4] = {&__pyx_t_2,&__pyx_t_22,&__pyx_t_19,&__pyx_t_18}; + __pyx_t_17 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_17); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_23 = Py_TYPE(__pyx_t_17)->tp_iternext; + for (index=0; index < 4; index++) { + PyObject* item = __pyx_t_23(__pyx_t_17); if (unlikely(!item)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(item); + *(temps[index]) = item; + } + if (__Pyx_IternextUnpackEndCheck(__pyx_t_23(__pyx_t_17), 4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_23 = NULL; + __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; + __pyx_t_23 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L4_unpacking_done:; } - /* "sklearn/linear_model/sgd_fast.pyx":364 - * q = np.zeros((n_features,), dtype=np.float64, order="c") - * q_data_ptr = q.data - * cdef double u = 0.0 # <<<<<<<<<<<<<< - * - * if penalty_type == L2: - */ - __pyx_v_u = 0.0; - - /* "sklearn/linear_model/sgd_fast.pyx":368 - * if penalty_type == L2: - * rho = 1.0 - * elif penalty_type == L1: # <<<<<<<<<<<<<< - * rho = 0.0 - * - */ - switch (__pyx_v_penalty_type) { - - /* "sklearn/linear_model/sgd_fast.pyx":366 - * cdef double u = 0.0 - * - * if penalty_type == L2: # <<<<<<<<<<<<<< - * rho = 1.0 - * elif penalty_type == L1: - */ - case 2: - - /* "sklearn/linear_model/sgd_fast.pyx":367 - * - * if penalty_type == L2: - * rho = 1.0 # <<<<<<<<<<<<<< - * elif penalty_type == L1: - * rho = 0.0 - */ - __pyx_v_rho = 1.0; - break; - - /* "sklearn/linear_model/sgd_fast.pyx":368 - * if penalty_type == L2: - * rho = 1.0 - * elif penalty_type == L1: # <<<<<<<<<<<<<< - * rho = 0.0 - * - */ - case 1: - - /* "sklearn/linear_model/sgd_fast.pyx":369 - * rho = 1.0 - * elif penalty_type == L1: - * rho = 0.0 # <<<<<<<<<<<<<< - * - * eta = eta0 + /* "sklearn/linear_model/sgd_fast.pyx":403 + * The fitted intercept term. + * """ + * standard_weights, standard_intercept,\ # <<<<<<<<<<<<<< + * _, _ = _plain_sgd(weights, + * intercept, */ - __pyx_v_rho = 0.0; - break; - } + __pyx_v_standard_weights = __pyx_t_2; + __pyx_t_2 = 0; + __pyx_v_standard_intercept = __pyx_t_22; + __pyx_t_22 = 0; + __pyx_v__ = __pyx_t_19; + __pyx_t_19 = 0; + __Pyx_DECREF_SET(__pyx_v__, __pyx_t_18); + __pyx_t_18 = 0; - /* "sklearn/linear_model/sgd_fast.pyx":371 - * rho = 0.0 + /* "sklearn/linear_model/sgd_fast.pyx":421 + * intercept_decay, + * 0) + * return standard_weights, standard_intercept # <<<<<<<<<<<<<< * - * eta = eta0 # <<<<<<<<<<<<<< - * - * t_start = time() - */ - __pyx_v_eta = __pyx_v_eta0; - - /* "sklearn/linear_model/sgd_fast.pyx":373 - * eta = eta0 * - * t_start = time() # <<<<<<<<<<<<<< - * for epoch in range(n_iter): - * if verbose > 0: */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__time); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_4 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_v_t_start = __pyx_t_4; - __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_standard_weights); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_standard_weights); + __Pyx_GIVEREF(__pyx_v_standard_weights); + __Pyx_INCREF(__pyx_v_standard_intercept); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_standard_intercept); + __Pyx_GIVEREF(__pyx_v_standard_intercept); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; - /* "sklearn/linear_model/sgd_fast.pyx":374 + /* "sklearn/linear_model/sgd_fast.pyx":331 * - * t_start = time() - * for epoch in range(n_iter): # <<<<<<<<<<<<<< - * if verbose > 0: - * print("-- Epoch %d" % (epoch + 1)) - */ - __pyx_t_7 = __pyx_v_n_iter; - for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_7; __pyx_t_11+=1) { - __pyx_v_epoch = __pyx_t_11; - - /* "sklearn/linear_model/sgd_fast.pyx":375 - * t_start = time() - * for epoch in range(n_iter): - * if verbose > 0: # <<<<<<<<<<<<<< - * print("-- Epoch %d" % (epoch + 1)) - * if shuffle: - */ - __pyx_t_12 = (__pyx_v_verbose > 0); - if (__pyx_t_12) { - - /* "sklearn/linear_model/sgd_fast.pyx":376 - * for epoch in range(n_iter): - * if verbose > 0: - * print("-- Epoch %d" % (epoch + 1)) # <<<<<<<<<<<<<< - * if shuffle: - * dataset.shuffle(seed) - */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_epoch + 1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_1), __pyx_t_4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__Pyx_PrintOne(0, ((PyObject *)__pyx_t_6)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - goto __pyx_L8; - } - __pyx_L8:; - - /* "sklearn/linear_model/sgd_fast.pyx":377 - * if verbose > 0: - * print("-- Epoch %d" % (epoch + 1)) - * if shuffle: # <<<<<<<<<<<<<< - * dataset.shuffle(seed) - * for i in range(n_samples): - */ - if (__pyx_v_shuffle) { - - /* "sklearn/linear_model/sgd_fast.pyx":378 - * print("-- Epoch %d" % (epoch + 1)) - * if shuffle: - * dataset.shuffle(seed) # <<<<<<<<<<<<<< - * for i in range(n_samples): - * dataset.next(&x_data_ptr, &x_ind_ptr, &xnnz, &y, - */ - __pyx_t_6 = PyInt_FromLong(__pyx_v_seed); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - ((struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset *)__pyx_v_dataset->__pyx_vtab)->shuffle(__pyx_v_dataset, __pyx_t_6); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - goto __pyx_L9; - } - __pyx_L9:; - - /* "sklearn/linear_model/sgd_fast.pyx":379 - * if shuffle: - * dataset.shuffle(seed) - * for i in range(n_samples): # <<<<<<<<<<<<<< - * dataset.next(&x_data_ptr, &x_ind_ptr, &xnnz, &y, - * &sample_weight) - */ - __pyx_t_13 = __pyx_v_n_samples; - for (__pyx_t_14 = 0; __pyx_t_14 < __pyx_t_13; __pyx_t_14+=1) { - __pyx_v_i = __pyx_t_14; - - /* "sklearn/linear_model/sgd_fast.pyx":381 - * for i in range(n_samples): - * dataset.next(&x_data_ptr, &x_ind_ptr, &xnnz, &y, - * &sample_weight) # <<<<<<<<<<<<<< * - * if learning_rate == OPTIMAL: + * def plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * double intercept, + * LossFunction loss, */ - ((struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset *)__pyx_v_dataset->__pyx_vtab)->next(__pyx_v_dataset, (&__pyx_v_x_data_ptr), (&__pyx_v_x_ind_ptr), (&__pyx_v_xnnz), (&__pyx_v_y), (&__pyx_v_sample_weight)); - /* "sklearn/linear_model/sgd_fast.pyx":385 - * if learning_rate == OPTIMAL: - * eta = 1.0 / (alpha * t) - * elif learning_rate == INVSCALING: # <<<<<<<<<<<<<< - * eta = eta0 / pow(t, power_t) - * p = w.dot(x_data_ptr, x_ind_ptr, xnnz) + intercept - */ - switch (__pyx_v_learning_rate) { + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_XDECREF(__pyx_t_13); + __Pyx_XDECREF(__pyx_t_14); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_XDECREF(__pyx_t_16); + __Pyx_XDECREF(__pyx_t_17); + __Pyx_XDECREF(__pyx_t_18); + __Pyx_XDECREF(__pyx_t_19); + __Pyx_XDECREF(__pyx_t_20); + __Pyx_XDECREF(__pyx_t_22); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weights.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.plain_sgd", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weights.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF(__pyx_v_standard_weights); + __Pyx_XDECREF(__pyx_v_standard_intercept); + __Pyx_XDECREF(__pyx_v__); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/linear_model/sgd_fast.pyx":383 - * &sample_weight) +/* "sklearn/linear_model/sgd_fast.pyx":424 * - * if learning_rate == OPTIMAL: # <<<<<<<<<<<<<< - * eta = 1.0 / (alpha * t) - * elif learning_rate == INVSCALING: - */ - case 2: - - /* "sklearn/linear_model/sgd_fast.pyx":384 * - * if learning_rate == OPTIMAL: - * eta = 1.0 / (alpha * t) # <<<<<<<<<<<<<< - * elif learning_rate == INVSCALING: - * eta = eta0 / pow(t, power_t) + * def average_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * double intercept, + * np.ndarray[double, ndim=1, mode='c'] average_weights, */ - __pyx_v_eta = (1.0 / (__pyx_v_alpha * __pyx_v_t)); - break; - /* "sklearn/linear_model/sgd_fast.pyx":385 - * if learning_rate == OPTIMAL: - * eta = 1.0 / (alpha * t) - * elif learning_rate == INVSCALING: # <<<<<<<<<<<<<< - * eta = eta0 / pow(t, power_t) - * p = w.dot(x_data_ptr, x_ind_ptr, xnnz) + intercept - */ - case 3: - - /* "sklearn/linear_model/sgd_fast.pyx":386 - * eta = 1.0 / (alpha * t) - * elif learning_rate == INVSCALING: - * eta = eta0 / pow(t, power_t) # <<<<<<<<<<<<<< - * p = w.dot(x_data_ptr, x_ind_ptr, xnnz) + intercept - * - */ - __pyx_v_eta = (__pyx_v_eta0 / pow(__pyx_v_t, __pyx_v_power_t)); +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_3average_sgd(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_12linear_model_8sgd_fast_2average_sgd[] = "Average SGD for generic loss functions and penalties.\n\n Parameters\n ----------\n weights : ndarray[double, ndim=1]\n The allocated coef_ vector.\n intercept : double\n The initial intercept.\n average_weights : ndarray[double, ndim=1]\n The average weights as computed for ASGD\n average_intercept : double\n The average intercept for ASGD\n loss : LossFunction\n A concrete ``LossFunction`` object.\n penalty_type : int\n The penalty 2 for L2, 1 for L1, and 3 for Elastic-Net.\n alpha : float\n The regularization parameter.\n C : float\n Maximum step size for passive aggressive.\n l1_ratio : float\n The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1.\n l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1.\n dataset : SequentialDataset\n A concrete ``SequentialDataset`` object.\n n_iter : int\n The number of iterations (epochs).\n fit_intercept : int\n Whether or not to fit the intercept (1 or 0).\n verbose : int\n Print verbose output; 0 for quite.\n shuffle : boolean\n Whether to shuffle the training data before each epoch.\n weight_pos : float\n The weight of the positive class.\n weight_neg : float\n The weight of the negative class.\n seed : np.uint32_t\n Seed of the pseudorandom number generator used to shuffle the data.\n learning_rate : int\n The learning rate:\n (1) constant, eta = eta0\n (2) optimal, eta = 1.0/(alpha * t).\n (3) inverse scaling, eta = eta0 / pow(t, power_t)\n (4) Passive Agressive-I, eta = min(alpha, loss/norm(x))\n (5) Passive Agressive-II, eta = 1.0 / (norm(x) + 0.5*alpha)\n eta0 : double\n The initial learning rate.\n power_t : double\n The exponent for inverse scaling learning rate.\n t : double\n Initial state of the learning rate. This value is equal to the\n iterati""on count except when the learning rate is set to `optimal`.\n Default: 1.0.\n average : int\n The number of iterations before averaging starts. average=1 is\n equivalent to averaging for all iterations.\n\n Returns\n -------\n weights : array, shape=[n_features]\n The fitted weight vector.\n intercept : float\n The fitted intercept term.\n average_weights : array shape=[n_features]\n The averaged weights accross iterations\n average_intercept : float\n The averaged intercept accross iterations\n "; +static PyMethodDef __pyx_mdef_7sklearn_12linear_model_8sgd_fast_3average_sgd = {"average_sgd", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_3average_sgd, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_12linear_model_8sgd_fast_2average_sgd}; +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_3average_sgd(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_weights = 0; + double __pyx_v_intercept; + PyArrayObject *__pyx_v_average_weights = 0; + double __pyx_v_average_intercept; + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_loss = 0; + int __pyx_v_penalty_type; + double __pyx_v_alpha; + double __pyx_v_C; + double __pyx_v_l1_ratio; + struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_dataset = 0; + int __pyx_v_n_iter; + int __pyx_v_fit_intercept; + int __pyx_v_verbose; + int __pyx_v_shuffle; + __pyx_t_5numpy_uint32_t __pyx_v_seed; + double __pyx_v_weight_pos; + double __pyx_v_weight_neg; + int __pyx_v_learning_rate; + double __pyx_v_eta0; + double __pyx_v_power_t; + double __pyx_v_t; + double __pyx_v_intercept_decay; + int __pyx_v_average; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("average_sgd (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_weights,&__pyx_n_s_intercept,&__pyx_n_s_average_weights,&__pyx_n_s_average_intercept,&__pyx_n_s_loss,&__pyx_n_s_penalty_type,&__pyx_n_s_alpha,&__pyx_n_s_C,&__pyx_n_s_l1_ratio,&__pyx_n_s_dataset,&__pyx_n_s_n_iter,&__pyx_n_s_fit_intercept,&__pyx_n_s_verbose,&__pyx_n_s_shuffle,&__pyx_n_s_seed,&__pyx_n_s_weight_pos,&__pyx_n_s_weight_neg,&__pyx_n_s_learning_rate,&__pyx_n_s_eta0,&__pyx_n_s_power_t,&__pyx_n_s_t,&__pyx_n_s_intercept_decay,&__pyx_n_s_average,0}; + PyObject* values[23] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); + case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); + case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); + case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); + case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); + case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); + case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); + case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); + case 15: values[14] = PyTuple_GET_ITEM(__pyx_args, 14); + case 14: values[13] = PyTuple_GET_ITEM(__pyx_args, 13); + case 13: values[12] = PyTuple_GET_ITEM(__pyx_args, 12); + case 12: values[11] = PyTuple_GET_ITEM(__pyx_args, 11); + case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); + case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); + case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); + case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_weights)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_intercept)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_average_weights)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_average_intercept)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_loss)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 5: + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_penalty_type)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 6: + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_alpha)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 7: + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_C)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 8: + if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_l1_ratio)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 9: + if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dataset)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 10: + if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_iter)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 11: + if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_fit_intercept)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 12: + if (likely((values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_verbose)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 13: + if (likely((values[13] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shuffle)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 13); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 14: + if (likely((values[14] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_seed)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 14); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 15: + if (likely((values[15] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_weight_pos)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 15); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 16: + if (likely((values[16] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_weight_neg)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 16); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 17: + if (likely((values[17] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_learning_rate)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 17); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 18: + if (likely((values[18] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_eta0)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 18); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 19: + if (likely((values[19] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_power_t)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, 19); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 20: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_t); + if (value) { values[20] = value; kw_args--; } + } + case 21: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_intercept_decay); + if (value) { values[21] = value; kw_args--; } + } + case 22: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_average); + if (value) { values[22] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "average_sgd") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); + case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); + case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); + case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); + values[18] = PyTuple_GET_ITEM(__pyx_args, 18); + values[17] = PyTuple_GET_ITEM(__pyx_args, 17); + values[16] = PyTuple_GET_ITEM(__pyx_args, 16); + values[15] = PyTuple_GET_ITEM(__pyx_args, 15); + values[14] = PyTuple_GET_ITEM(__pyx_args, 14); + values[13] = PyTuple_GET_ITEM(__pyx_args, 13); + values[12] = PyTuple_GET_ITEM(__pyx_args, 12); + values[11] = PyTuple_GET_ITEM(__pyx_args, 11); + values[10] = PyTuple_GET_ITEM(__pyx_args, 10); + values[9] = PyTuple_GET_ITEM(__pyx_args, 9); + values[8] = PyTuple_GET_ITEM(__pyx_args, 8); + values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; + default: goto __pyx_L5_argtuple_error; } + } + __pyx_v_weights = ((PyArrayObject *)values[0]); + __pyx_v_intercept = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_intercept == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_average_weights = ((PyArrayObject *)values[2]); + __pyx_v_average_intercept = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_average_intercept == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 427; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_loss = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)values[4]); + __pyx_v_penalty_type = __Pyx_PyInt_As_int(values[5]); if (unlikely((__pyx_v_penalty_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_alpha = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_alpha == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_C = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_l1_ratio = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_l1_ratio == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 431; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_dataset = ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *)values[9]); + __pyx_v_n_iter = __Pyx_PyInt_As_int(values[10]); if (unlikely((__pyx_v_n_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_fit_intercept = __Pyx_PyInt_As_int(values[11]); if (unlikely((__pyx_v_fit_intercept == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_verbose = __Pyx_PyInt_As_int(values[12]); if (unlikely((__pyx_v_verbose == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 434; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_shuffle = __Pyx_PyObject_IsTrue(values[13]); if (unlikely((__pyx_v_shuffle == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 434; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_seed = __Pyx_PyInt_As_npy_uint32(values[14]); if (unlikely((__pyx_v_seed == (npy_uint32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 434; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_weight_pos = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_weight_pos == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 435; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_weight_neg = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_weight_neg == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 435; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_learning_rate = __Pyx_PyInt_As_int(values[17]); if (unlikely((__pyx_v_learning_rate == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_eta0 = __pyx_PyFloat_AsDouble(values[18]); if (unlikely((__pyx_v_eta0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_power_t = __pyx_PyFloat_AsDouble(values[19]); if (unlikely((__pyx_v_power_t == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 437; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[20]) { + __pyx_v_t = __pyx_PyFloat_AsDouble(values[20]); if (unlikely((__pyx_v_t == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 438; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_t = ((double)1.0); + } + if (values[21]) { + __pyx_v_intercept_decay = __pyx_PyFloat_AsDouble(values[21]); if (unlikely((__pyx_v_intercept_decay == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 439; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_intercept_decay = ((double)1.0); + } + if (values[22]) { + __pyx_v_average = __Pyx_PyInt_As_int(values[22]); if (unlikely((__pyx_v_average == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_average = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("average_sgd", 0, 20, 23, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.average_sgd", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weights), __pyx_ptype_5numpy_ndarray, 1, "weights", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_average_weights), __pyx_ptype_5numpy_ndarray, 1, "average_weights", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 426; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_loss), __pyx_ptype_7sklearn_12linear_model_8sgd_fast_LossFunction, 1, "loss", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 428; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_dataset), __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset, 1, "dataset", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_2average_sgd(__pyx_self, __pyx_v_weights, __pyx_v_intercept, __pyx_v_average_weights, __pyx_v_average_intercept, __pyx_v_loss, __pyx_v_penalty_type, __pyx_v_alpha, __pyx_v_C, __pyx_v_l1_ratio, __pyx_v_dataset, __pyx_v_n_iter, __pyx_v_fit_intercept, __pyx_v_verbose, __pyx_v_shuffle, __pyx_v_seed, __pyx_v_weight_pos, __pyx_v_weight_neg, __pyx_v_learning_rate, __pyx_v_eta0, __pyx_v_power_t, __pyx_v_t, __pyx_v_intercept_decay, __pyx_v_average); - /* "sklearn/linear_model/sgd_fast.pyx":387 - * elif learning_rate == INVSCALING: - * eta = eta0 / pow(t, power_t) - * p = w.dot(x_data_ptr, x_ind_ptr, xnnz) + intercept # <<<<<<<<<<<<<< - * - * if verbose > 0: - */ - __pyx_v_p = (((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_w->__pyx_vtab)->dot(__pyx_v_w, __pyx_v_x_data_ptr, __pyx_v_x_ind_ptr, __pyx_v_xnnz) + __pyx_v_intercept); + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/linear_model/sgd_fast.pyx":389 - * p = w.dot(x_data_ptr, x_ind_ptr, xnnz) + intercept - * - * if verbose > 0: # <<<<<<<<<<<<<< - * sumloss += loss.loss(p, y) - * - */ - __pyx_t_12 = (__pyx_v_verbose > 0); - if (__pyx_t_12) { +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_2average_sgd(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_weights, double __pyx_v_intercept, PyArrayObject *__pyx_v_average_weights, double __pyx_v_average_intercept, struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_loss, int __pyx_v_penalty_type, double __pyx_v_alpha, double __pyx_v_C, double __pyx_v_l1_ratio, struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_dataset, int __pyx_v_n_iter, int __pyx_v_fit_intercept, int __pyx_v_verbose, int __pyx_v_shuffle, __pyx_t_5numpy_uint32_t __pyx_v_seed, double __pyx_v_weight_pos, double __pyx_v_weight_neg, int __pyx_v_learning_rate, double __pyx_v_eta0, double __pyx_v_power_t, double __pyx_v_t, double __pyx_v_intercept_decay, int __pyx_v_average) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_average_weights; + __Pyx_Buffer __pyx_pybuffer_average_weights; + __Pyx_LocalBuf_ND __pyx_pybuffernd_weights; + __Pyx_Buffer __pyx_pybuffer_weights; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + PyObject *__pyx_t_14 = NULL; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + PyObject *__pyx_t_17 = NULL; + PyObject *__pyx_t_18 = NULL; + PyObject *__pyx_t_19 = NULL; + PyObject *__pyx_t_20 = NULL; + PyObject *__pyx_t_21 = NULL; + PyObject *__pyx_t_22 = NULL; + Py_ssize_t __pyx_t_23; + PyObject *__pyx_t_24 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("average_sgd", 0); + __pyx_pybuffer_weights.pybuffer.buf = NULL; + __pyx_pybuffer_weights.refcount = 0; + __pyx_pybuffernd_weights.data = NULL; + __pyx_pybuffernd_weights.rcbuffer = &__pyx_pybuffer_weights; + __pyx_pybuffer_average_weights.pybuffer.buf = NULL; + __pyx_pybuffer_average_weights.refcount = 0; + __pyx_pybuffernd_average_weights.data = NULL; + __pyx_pybuffernd_average_weights.rcbuffer = &__pyx_pybuffer_average_weights; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weights.rcbuffer->pybuffer, (PyObject*)__pyx_v_weights, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_weights.diminfo[0].strides = __pyx_pybuffernd_weights.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weights.diminfo[0].shape = __pyx_pybuffernd_weights.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_average_weights.rcbuffer->pybuffer, (PyObject*)__pyx_v_average_weights, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_average_weights.diminfo[0].strides = __pyx_pybuffernd_average_weights.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_average_weights.diminfo[0].shape = __pyx_pybuffernd_average_weights.rcbuffer->pybuffer.shape[0]; - /* "sklearn/linear_model/sgd_fast.pyx":390 - * - * if verbose > 0: - * sumloss += loss.loss(p, y) # <<<<<<<<<<<<<< - * - * if y > 0.0: + /* "sklearn/linear_model/sgd_fast.pyx":510 + * The averaged intercept accross iterations + * """ + * return _plain_sgd(weights, # <<<<<<<<<<<<<< + * intercept, + * average_weights, */ - __pyx_v_sumloss = (__pyx_v_sumloss + ((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_loss->__pyx_vtab)->loss(__pyx_v_loss, __pyx_v_p, __pyx_v_y, 0)); - goto __pyx_L12; - } - __pyx_L12:; + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_plain_sgd); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); - /* "sklearn/linear_model/sgd_fast.pyx":392 - * sumloss += loss.loss(p, y) - * - * if y > 0.0: # <<<<<<<<<<<<<< - * class_weight = weight_pos - * else: + /* "sklearn/linear_model/sgd_fast.pyx":511 + * """ + * return _plain_sgd(weights, + * intercept, # <<<<<<<<<<<<<< + * average_weights, + * average_intercept, */ - __pyx_t_12 = (__pyx_v_y > 0.0); - if (__pyx_t_12) { + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_intercept); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); - /* "sklearn/linear_model/sgd_fast.pyx":393 - * - * if y > 0.0: - * class_weight = weight_pos # <<<<<<<<<<<<<< - * else: - * class_weight = weight_neg + /* "sklearn/linear_model/sgd_fast.pyx":513 + * intercept, + * average_weights, + * average_intercept, # <<<<<<<<<<<<<< + * loss, + * penalty_type, */ - __pyx_v_class_weight = __pyx_v_weight_pos; - goto __pyx_L13; - } - /*else*/ { + __pyx_t_4 = PyFloat_FromDouble(__pyx_v_average_intercept); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); - /* "sklearn/linear_model/sgd_fast.pyx":395 - * class_weight = weight_pos - * else: - * class_weight = weight_neg # <<<<<<<<<<<<<< - * - * update = eta * loss.dloss(p, y) * class_weight * sample_weight + /* "sklearn/linear_model/sgd_fast.pyx":515 + * average_intercept, + * loss, + * penalty_type, # <<<<<<<<<<<<<< + * alpha, C, + * l1_ratio, */ - __pyx_v_class_weight = __pyx_v_weight_neg; - } - __pyx_L13:; + __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_penalty_type); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); - /* "sklearn/linear_model/sgd_fast.pyx":397 - * class_weight = weight_neg - * - * update = eta * loss.dloss(p, y) * class_weight * sample_weight # <<<<<<<<<<<<<< - * if update != 0.0: - * w.add(x_data_ptr, x_ind_ptr, xnnz, -update) + /* "sklearn/linear_model/sgd_fast.pyx":516 + * loss, + * penalty_type, + * alpha, C, # <<<<<<<<<<<<<< + * l1_ratio, + * dataset, */ - __pyx_v_update = (((__pyx_v_eta * ((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_loss->__pyx_vtab)->dloss(__pyx_v_loss, __pyx_v_p, __pyx_v_y, 0)) * __pyx_v_class_weight) * __pyx_v_sample_weight); + __pyx_t_6 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyFloat_FromDouble(__pyx_v_C); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + + /* "sklearn/linear_model/sgd_fast.pyx":517 + * penalty_type, + * alpha, C, + * l1_ratio, # <<<<<<<<<<<<<< + * dataset, + * n_iter, fit_intercept, + */ + __pyx_t_8 = PyFloat_FromDouble(__pyx_v_l1_ratio); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 517; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + + /* "sklearn/linear_model/sgd_fast.pyx":519 + * l1_ratio, + * dataset, + * n_iter, fit_intercept, # <<<<<<<<<<<<<< + * verbose, shuffle, seed, + * weight_pos, weight_neg, + */ + __pyx_t_9 = __Pyx_PyInt_From_int(__pyx_v_n_iter); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = __Pyx_PyInt_From_int(__pyx_v_fit_intercept); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + + /* "sklearn/linear_model/sgd_fast.pyx":520 + * dataset, + * n_iter, fit_intercept, + * verbose, shuffle, seed, # <<<<<<<<<<<<<< + * weight_pos, weight_neg, + * learning_rate, eta0, + */ + __pyx_t_11 = __Pyx_PyInt_From_int(__pyx_v_verbose); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_12 = __Pyx_PyBool_FromLong(__pyx_v_shuffle); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_13 = __Pyx_PyInt_From_npy_uint32(__pyx_v_seed); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_13); + + /* "sklearn/linear_model/sgd_fast.pyx":521 + * n_iter, fit_intercept, + * verbose, shuffle, seed, + * weight_pos, weight_neg, # <<<<<<<<<<<<<< + * learning_rate, eta0, + * power_t, + */ + __pyx_t_14 = PyFloat_FromDouble(__pyx_v_weight_pos); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_14); + __pyx_t_15 = PyFloat_FromDouble(__pyx_v_weight_neg); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + + /* "sklearn/linear_model/sgd_fast.pyx":522 + * verbose, shuffle, seed, + * weight_pos, weight_neg, + * learning_rate, eta0, # <<<<<<<<<<<<<< + * power_t, + * t, + */ + __pyx_t_16 = __Pyx_PyInt_From_int(__pyx_v_learning_rate); if (unlikely(!__pyx_t_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_16); + __pyx_t_17 = PyFloat_FromDouble(__pyx_v_eta0); if (unlikely(!__pyx_t_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_17); + + /* "sklearn/linear_model/sgd_fast.pyx":523 + * weight_pos, weight_neg, + * learning_rate, eta0, + * power_t, # <<<<<<<<<<<<<< + * t, + * intercept_decay, + */ + __pyx_t_18 = PyFloat_FromDouble(__pyx_v_power_t); if (unlikely(!__pyx_t_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_18); + + /* "sklearn/linear_model/sgd_fast.pyx":524 + * learning_rate, eta0, + * power_t, + * t, # <<<<<<<<<<<<<< + * intercept_decay, + * average) + */ + __pyx_t_19 = PyFloat_FromDouble(__pyx_v_t); if (unlikely(!__pyx_t_19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_19); + + /* "sklearn/linear_model/sgd_fast.pyx":525 + * power_t, + * t, + * intercept_decay, # <<<<<<<<<<<<<< + * average) + * + */ + __pyx_t_20 = PyFloat_FromDouble(__pyx_v_intercept_decay); if (unlikely(!__pyx_t_20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_20); + + /* "sklearn/linear_model/sgd_fast.pyx":526 + * t, + * intercept_decay, + * average) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_21 = __Pyx_PyInt_From_int(__pyx_v_average); if (unlikely(!__pyx_t_21)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_21); + __pyx_t_22 = NULL; + __pyx_t_23 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_22 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_22)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_22); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_23 = 1; + } + } + __pyx_t_24 = PyTuple_New(23+__pyx_t_23); if (unlikely(!__pyx_t_24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_24); + if (__pyx_t_22) { + PyTuple_SET_ITEM(__pyx_t_24, 0, __pyx_t_22); __Pyx_GIVEREF(__pyx_t_22); __pyx_t_22 = NULL; + } + __Pyx_INCREF(((PyObject *)__pyx_v_weights)); + PyTuple_SET_ITEM(__pyx_t_24, 0+__pyx_t_23, ((PyObject *)__pyx_v_weights)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_weights)); + PyTuple_SET_ITEM(__pyx_t_24, 1+__pyx_t_23, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_average_weights)); + PyTuple_SET_ITEM(__pyx_t_24, 2+__pyx_t_23, ((PyObject *)__pyx_v_average_weights)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_average_weights)); + PyTuple_SET_ITEM(__pyx_t_24, 3+__pyx_t_23, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_loss)); + PyTuple_SET_ITEM(__pyx_t_24, 4+__pyx_t_23, ((PyObject *)__pyx_v_loss)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_loss)); + PyTuple_SET_ITEM(__pyx_t_24, 5+__pyx_t_23, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_24, 6+__pyx_t_23, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_24, 7+__pyx_t_23, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_24, 8+__pyx_t_23, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __Pyx_INCREF(((PyObject *)__pyx_v_dataset)); + PyTuple_SET_ITEM(__pyx_t_24, 9+__pyx_t_23, ((PyObject *)__pyx_v_dataset)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_dataset)); + PyTuple_SET_ITEM(__pyx_t_24, 10+__pyx_t_23, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_24, 11+__pyx_t_23, __pyx_t_10); + __Pyx_GIVEREF(__pyx_t_10); + PyTuple_SET_ITEM(__pyx_t_24, 12+__pyx_t_23, __pyx_t_11); + __Pyx_GIVEREF(__pyx_t_11); + PyTuple_SET_ITEM(__pyx_t_24, 13+__pyx_t_23, __pyx_t_12); + __Pyx_GIVEREF(__pyx_t_12); + PyTuple_SET_ITEM(__pyx_t_24, 14+__pyx_t_23, __pyx_t_13); + __Pyx_GIVEREF(__pyx_t_13); + PyTuple_SET_ITEM(__pyx_t_24, 15+__pyx_t_23, __pyx_t_14); + __Pyx_GIVEREF(__pyx_t_14); + PyTuple_SET_ITEM(__pyx_t_24, 16+__pyx_t_23, __pyx_t_15); + __Pyx_GIVEREF(__pyx_t_15); + PyTuple_SET_ITEM(__pyx_t_24, 17+__pyx_t_23, __pyx_t_16); + __Pyx_GIVEREF(__pyx_t_16); + PyTuple_SET_ITEM(__pyx_t_24, 18+__pyx_t_23, __pyx_t_17); + __Pyx_GIVEREF(__pyx_t_17); + PyTuple_SET_ITEM(__pyx_t_24, 19+__pyx_t_23, __pyx_t_18); + __Pyx_GIVEREF(__pyx_t_18); + PyTuple_SET_ITEM(__pyx_t_24, 20+__pyx_t_23, __pyx_t_19); + __Pyx_GIVEREF(__pyx_t_19); + PyTuple_SET_ITEM(__pyx_t_24, 21+__pyx_t_23, __pyx_t_20); + __Pyx_GIVEREF(__pyx_t_20); + PyTuple_SET_ITEM(__pyx_t_24, 22+__pyx_t_23, __pyx_t_21); + __Pyx_GIVEREF(__pyx_t_21); + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_8 = 0; + __pyx_t_9 = 0; + __pyx_t_10 = 0; + __pyx_t_11 = 0; + __pyx_t_12 = 0; + __pyx_t_13 = 0; + __pyx_t_14 = 0; + __pyx_t_15 = 0; + __pyx_t_16 = 0; + __pyx_t_17 = 0; + __pyx_t_18 = 0; + __pyx_t_19 = 0; + __pyx_t_20 = 0; + __pyx_t_21 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_24, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_24); __pyx_t_24 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; - /* "sklearn/linear_model/sgd_fast.pyx":398 + /* "sklearn/linear_model/sgd_fast.pyx":424 * - * update = eta * loss.dloss(p, y) * class_weight * sample_weight - * if update != 0.0: # <<<<<<<<<<<<<< - * w.add(x_data_ptr, x_ind_ptr, xnnz, -update) - * if fit_intercept == 1: - */ - __pyx_t_12 = (__pyx_v_update != 0.0); - if (__pyx_t_12) { - - /* "sklearn/linear_model/sgd_fast.pyx":399 - * update = eta * loss.dloss(p, y) * class_weight * sample_weight - * if update != 0.0: - * w.add(x_data_ptr, x_ind_ptr, xnnz, -update) # <<<<<<<<<<<<<< - * if fit_intercept == 1: - * intercept -= update * intercept_decay - */ - ((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_w->__pyx_vtab)->add(__pyx_v_w, __pyx_v_x_data_ptr, __pyx_v_x_ind_ptr, __pyx_v_xnnz, (-__pyx_v_update)); - - /* "sklearn/linear_model/sgd_fast.pyx":400 - * if update != 0.0: - * w.add(x_data_ptr, x_ind_ptr, xnnz, -update) - * if fit_intercept == 1: # <<<<<<<<<<<<<< - * intercept -= update * intercept_decay - * if penalty_type >= L2: - */ - __pyx_t_12 = (__pyx_v_fit_intercept == 1); - if (__pyx_t_12) { - - /* "sklearn/linear_model/sgd_fast.pyx":401 - * w.add(x_data_ptr, x_ind_ptr, xnnz, -update) - * if fit_intercept == 1: - * intercept -= update * intercept_decay # <<<<<<<<<<<<<< - * if penalty_type >= L2: - * w.scale(1.0 - (rho * eta * alpha)) - */ - __pyx_v_intercept = (__pyx_v_intercept - (__pyx_v_update * __pyx_v_intercept_decay)); - goto __pyx_L15; - } - __pyx_L15:; - goto __pyx_L14; - } - __pyx_L14:; - - /* "sklearn/linear_model/sgd_fast.pyx":402 - * if fit_intercept == 1: - * intercept -= update * intercept_decay - * if penalty_type >= L2: # <<<<<<<<<<<<<< - * w.scale(1.0 - (rho * eta * alpha)) * + * def average_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * double intercept, + * np.ndarray[double, ndim=1, mode='c'] average_weights, */ - __pyx_t_12 = (__pyx_v_penalty_type >= 2); - if (__pyx_t_12) { - /* "sklearn/linear_model/sgd_fast.pyx":403 - * intercept -= update * intercept_decay - * if penalty_type >= L2: - * w.scale(1.0 - (rho * eta * alpha)) # <<<<<<<<<<<<<< - * - * if penalty_type == L1 or penalty_type == ELASTICNET: - */ - ((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_w->__pyx_vtab)->scale(__pyx_v_w, (1.0 - ((__pyx_v_rho * __pyx_v_eta) * __pyx_v_alpha))); - goto __pyx_L16; - } - __pyx_L16:; + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_XDECREF(__pyx_t_13); + __Pyx_XDECREF(__pyx_t_14); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_XDECREF(__pyx_t_16); + __Pyx_XDECREF(__pyx_t_17); + __Pyx_XDECREF(__pyx_t_18); + __Pyx_XDECREF(__pyx_t_19); + __Pyx_XDECREF(__pyx_t_20); + __Pyx_XDECREF(__pyx_t_21); + __Pyx_XDECREF(__pyx_t_22); + __Pyx_XDECREF(__pyx_t_24); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_average_weights.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weights.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.average_sgd", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_average_weights.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weights.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/linear_model/sgd_fast.pyx":405 - * w.scale(1.0 - (rho * eta * alpha)) +/* "sklearn/linear_model/sgd_fast.pyx":529 + * * - * if penalty_type == L1 or penalty_type == ELASTICNET: # <<<<<<<<<<<<<< - * u += ((1.0 - rho) * eta * alpha) - * l1penalty(w, q_data_ptr, x_ind_ptr, xnnz, u) + * def _plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * double intercept, + * np.ndarray[double, ndim=1, mode='c'] average_weights, */ - switch (__pyx_v_penalty_type) { - case 1: - case 3: - /* "sklearn/linear_model/sgd_fast.pyx":406 - * - * if penalty_type == L1 or penalty_type == ELASTICNET: - * u += ((1.0 - rho) * eta * alpha) # <<<<<<<<<<<<<< - * l1penalty(w, q_data_ptr, x_ind_ptr, xnnz, u) - * t += 1 - */ - __pyx_v_u = (__pyx_v_u + (((1.0 - __pyx_v_rho) * __pyx_v_eta) * __pyx_v_alpha)); - - /* "sklearn/linear_model/sgd_fast.pyx":407 - * if penalty_type == L1 or penalty_type == ELASTICNET: - * u += ((1.0 - rho) * eta * alpha) - * l1penalty(w, q_data_ptr, x_ind_ptr, xnnz, u) # <<<<<<<<<<<<<< - * t += 1 - * count += 1 - */ - __pyx_f_7sklearn_12linear_model_8sgd_fast_l1penalty(__pyx_v_w, __pyx_v_q_data_ptr, __pyx_v_x_ind_ptr, __pyx_v_xnnz, __pyx_v_u); +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_5_plain_sgd(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_12linear_model_8sgd_fast_5_plain_sgd = {"_plain_sgd", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_5_plain_sgd, METH_VARARGS|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_7sklearn_12linear_model_8sgd_fast_5_plain_sgd(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_weights = 0; + double __pyx_v_intercept; + PyArrayObject *__pyx_v_average_weights = 0; + double __pyx_v_average_intercept; + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_loss = 0; + int __pyx_v_penalty_type; + double __pyx_v_alpha; + double __pyx_v_C; + double __pyx_v_l1_ratio; + struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_dataset = 0; + int __pyx_v_n_iter; + int __pyx_v_fit_intercept; + int __pyx_v_verbose; + int __pyx_v_shuffle; + __pyx_t_5numpy_uint32_t __pyx_v_seed; + double __pyx_v_weight_pos; + double __pyx_v_weight_neg; + int __pyx_v_learning_rate; + double __pyx_v_eta0; + double __pyx_v_power_t; + double __pyx_v_t; + double __pyx_v_intercept_decay; + int __pyx_v_average; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_plain_sgd (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_weights,&__pyx_n_s_intercept,&__pyx_n_s_average_weights,&__pyx_n_s_average_intercept,&__pyx_n_s_loss,&__pyx_n_s_penalty_type,&__pyx_n_s_alpha,&__pyx_n_s_C,&__pyx_n_s_l1_ratio,&__pyx_n_s_dataset,&__pyx_n_s_n_iter,&__pyx_n_s_fit_intercept,&__pyx_n_s_verbose,&__pyx_n_s_shuffle,&__pyx_n_s_seed,&__pyx_n_s_weight_pos,&__pyx_n_s_weight_neg,&__pyx_n_s_learning_rate,&__pyx_n_s_eta0,&__pyx_n_s_power_t,&__pyx_n_s_t,&__pyx_n_s_intercept_decay,&__pyx_n_s_average,0}; + PyObject* values[23] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); + case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); + case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); + case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); + case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); + case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); + case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); + case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); + case 15: values[14] = PyTuple_GET_ITEM(__pyx_args, 14); + case 14: values[13] = PyTuple_GET_ITEM(__pyx_args, 13); + case 13: values[12] = PyTuple_GET_ITEM(__pyx_args, 12); + case 12: values[11] = PyTuple_GET_ITEM(__pyx_args, 11); + case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); + case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); + case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); + case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_weights)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_intercept)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_average_weights)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_average_intercept)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_loss)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 5: + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_penalty_type)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 6: + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_alpha)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 7: + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_C)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 8: + if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_l1_ratio)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 9: + if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dataset)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 10: + if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_iter)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 11: + if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_fit_intercept)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 12: + if (likely((values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_verbose)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 13: + if (likely((values[13] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shuffle)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 13); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 14: + if (likely((values[14] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_seed)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 14); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 15: + if (likely((values[15] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_weight_pos)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 15); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 16: + if (likely((values[16] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_weight_neg)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 16); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 17: + if (likely((values[17] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_learning_rate)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 17); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 18: + if (likely((values[18] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_eta0)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 18); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 19: + if (likely((values[19] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_power_t)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, 19); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 20: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_t); + if (value) { values[20] = value; kw_args--; } + } + case 21: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_intercept_decay); + if (value) { values[21] = value; kw_args--; } + } + case 22: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_average); + if (value) { values[22] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_plain_sgd") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); + case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); + case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); + case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); + values[18] = PyTuple_GET_ITEM(__pyx_args, 18); + values[17] = PyTuple_GET_ITEM(__pyx_args, 17); + values[16] = PyTuple_GET_ITEM(__pyx_args, 16); + values[15] = PyTuple_GET_ITEM(__pyx_args, 15); + values[14] = PyTuple_GET_ITEM(__pyx_args, 14); + values[13] = PyTuple_GET_ITEM(__pyx_args, 13); + values[12] = PyTuple_GET_ITEM(__pyx_args, 12); + values[11] = PyTuple_GET_ITEM(__pyx_args, 11); + values[10] = PyTuple_GET_ITEM(__pyx_args, 10); + values[9] = PyTuple_GET_ITEM(__pyx_args, 9); + values[8] = PyTuple_GET_ITEM(__pyx_args, 8); + values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; + default: goto __pyx_L5_argtuple_error; } + } + __pyx_v_weights = ((PyArrayObject *)values[0]); + __pyx_v_intercept = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_intercept == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_average_weights = ((PyArrayObject *)values[2]); + __pyx_v_average_intercept = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_average_intercept == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_loss = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)values[4]); + __pyx_v_penalty_type = __Pyx_PyInt_As_int(values[5]); if (unlikely((__pyx_v_penalty_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 534; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_alpha = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_alpha == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_C = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_l1_ratio = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_l1_ratio == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_dataset = ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *)values[9]); + __pyx_v_n_iter = __Pyx_PyInt_As_int(values[10]); if (unlikely((__pyx_v_n_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_fit_intercept = __Pyx_PyInt_As_int(values[11]); if (unlikely((__pyx_v_fit_intercept == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_verbose = __Pyx_PyInt_As_int(values[12]); if (unlikely((__pyx_v_verbose == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_shuffle = __Pyx_PyObject_IsTrue(values[13]); if (unlikely((__pyx_v_shuffle == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_seed = __Pyx_PyInt_As_npy_uint32(values[14]); if (unlikely((__pyx_v_seed == (npy_uint32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_weight_pos = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_weight_pos == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 540; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_weight_neg = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_weight_neg == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 540; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_learning_rate = __Pyx_PyInt_As_int(values[17]); if (unlikely((__pyx_v_learning_rate == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 541; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_eta0 = __pyx_PyFloat_AsDouble(values[18]); if (unlikely((__pyx_v_eta0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 541; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_power_t = __pyx_PyFloat_AsDouble(values[19]); if (unlikely((__pyx_v_power_t == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[20]) { + __pyx_v_t = __pyx_PyFloat_AsDouble(values[20]); if (unlikely((__pyx_v_t == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 543; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_t = ((double)1.0); + } + if (values[21]) { + __pyx_v_intercept_decay = __pyx_PyFloat_AsDouble(values[21]); if (unlikely((__pyx_v_intercept_decay == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 544; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_intercept_decay = ((double)1.0); + } + if (values[22]) { + __pyx_v_average = __Pyx_PyInt_As_int(values[22]); if (unlikely((__pyx_v_average == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_average = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_plain_sgd", 0, 20, 23, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast._plain_sgd", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weights), __pyx_ptype_5numpy_ndarray, 1, "weights", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_average_weights), __pyx_ptype_5numpy_ndarray, 1, "average_weights", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_loss), __pyx_ptype_7sklearn_12linear_model_8sgd_fast_LossFunction, 1, "loss", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_dataset), __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset, 1, "dataset", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_12linear_model_8sgd_fast_4_plain_sgd(__pyx_self, __pyx_v_weights, __pyx_v_intercept, __pyx_v_average_weights, __pyx_v_average_intercept, __pyx_v_loss, __pyx_v_penalty_type, __pyx_v_alpha, __pyx_v_C, __pyx_v_l1_ratio, __pyx_v_dataset, __pyx_v_n_iter, __pyx_v_fit_intercept, __pyx_v_verbose, __pyx_v_shuffle, __pyx_v_seed, __pyx_v_weight_pos, __pyx_v_weight_neg, __pyx_v_learning_rate, __pyx_v_eta0, __pyx_v_power_t, __pyx_v_t, __pyx_v_intercept_decay, __pyx_v_average); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_12linear_model_8sgd_fast_4_plain_sgd(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_weights, double __pyx_v_intercept, PyArrayObject *__pyx_v_average_weights, double __pyx_v_average_intercept, struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *__pyx_v_loss, int __pyx_v_penalty_type, double __pyx_v_alpha, double __pyx_v_C, double __pyx_v_l1_ratio, struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_dataset, int __pyx_v_n_iter, int __pyx_v_fit_intercept, int __pyx_v_verbose, int __pyx_v_shuffle, __pyx_t_5numpy_uint32_t __pyx_v_seed, double __pyx_v_weight_pos, double __pyx_v_weight_neg, int __pyx_v_learning_rate, double __pyx_v_eta0, double __pyx_v_power_t, double __pyx_v_t, double __pyx_v_intercept_decay, int __pyx_v_average) { + Py_ssize_t __pyx_v_n_samples; + Py_ssize_t __pyx_v_n_features; + struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_w = 0; + CYTHON_UNUSED double *__pyx_v_w_ptr; + double *__pyx_v_x_data_ptr; + int *__pyx_v_x_ind_ptr; + CYTHON_UNUSED double *__pyx_v_ps_ptr; + int __pyx_v_infinity; + int __pyx_v_xnnz; + double __pyx_v_eta; + double __pyx_v_p; + double __pyx_v_update; + double __pyx_v_sumloss; + double __pyx_v_y; + double __pyx_v_sample_weight; + double __pyx_v_class_weight; + unsigned int __pyx_v_count; + unsigned int __pyx_v_epoch; + CYTHON_UNUSED unsigned int __pyx_v_i; + int __pyx_v_is_hinge; + double __pyx_v_optimal_init; + double __pyx_v_dloss; + double __pyx_v_MAX_DLOSS; + PyArrayObject *__pyx_v_q = 0; + double *__pyx_v_q_data_ptr; + double __pyx_v_u; + PyObject *__pyx_v_typw = NULL; + PyObject *__pyx_v_initial_eta0 = NULL; + PyObject *__pyx_v_t_start = NULL; + __Pyx_LocalBuf_ND __pyx_pybuffernd_average_weights; + __Pyx_Buffer __pyx_pybuffer_average_weights; + __Pyx_LocalBuf_ND __pyx_pybuffernd_q; + __Pyx_Buffer __pyx_pybuffer_q; + __Pyx_LocalBuf_ND __pyx_pybuffernd_weights; + __Pyx_Buffer __pyx_pybuffer_weights; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + long __pyx_t_4; + int __pyx_t_5; + PyArrayObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + int __pyx_t_10; + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + PyObject *__pyx_t_14 = NULL; + PyObject *__pyx_t_15 = NULL; + double __pyx_t_16; + unsigned int __pyx_t_17; + unsigned int __pyx_t_18; + double __pyx_t_19; + double __pyx_t_20; + long __pyx_t_21; + int __pyx_t_22; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_plain_sgd", 0); + __pyx_pybuffer_q.pybuffer.buf = NULL; + __pyx_pybuffer_q.refcount = 0; + __pyx_pybuffernd_q.data = NULL; + __pyx_pybuffernd_q.rcbuffer = &__pyx_pybuffer_q; + __pyx_pybuffer_weights.pybuffer.buf = NULL; + __pyx_pybuffer_weights.refcount = 0; + __pyx_pybuffernd_weights.data = NULL; + __pyx_pybuffernd_weights.rcbuffer = &__pyx_pybuffer_weights; + __pyx_pybuffer_average_weights.pybuffer.buf = NULL; + __pyx_pybuffer_average_weights.refcount = 0; + __pyx_pybuffernd_average_weights.data = NULL; + __pyx_pybuffernd_average_weights.rcbuffer = &__pyx_pybuffer_average_weights; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weights.rcbuffer->pybuffer, (PyObject*)__pyx_v_weights, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_weights.diminfo[0].strides = __pyx_pybuffernd_weights.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weights.diminfo[0].shape = __pyx_pybuffernd_weights.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_average_weights.rcbuffer->pybuffer, (PyObject*)__pyx_v_average_weights, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_average_weights.diminfo[0].strides = __pyx_pybuffernd_average_weights.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_average_weights.diminfo[0].shape = __pyx_pybuffernd_average_weights.rcbuffer->pybuffer.shape[0]; - /* "sklearn/linear_model/sgd_fast.pyx":408 - * u += ((1.0 - rho) * eta * alpha) - * l1penalty(w, q_data_ptr, x_ind_ptr, xnnz, u) - * t += 1 # <<<<<<<<<<<<<< - * count += 1 + /* "sklearn/linear_model/sgd_fast.pyx":548 + * + * # get the data information into easy vars + * cdef Py_ssize_t n_samples = dataset.n_samples # <<<<<<<<<<<<<< + * cdef Py_ssize_t n_features = weights.shape[0] * */ - __pyx_v_t = (__pyx_v_t + 1.0); + __pyx_t_1 = __pyx_v_dataset->n_samples; + __pyx_v_n_samples = __pyx_t_1; - /* "sklearn/linear_model/sgd_fast.pyx":409 - * l1penalty(w, q_data_ptr, x_ind_ptr, xnnz, u) - * t += 1 - * count += 1 # <<<<<<<<<<<<<< + /* "sklearn/linear_model/sgd_fast.pyx":549 + * # get the data information into easy vars + * cdef Py_ssize_t n_samples = dataset.n_samples + * cdef Py_ssize_t n_features = weights.shape[0] # <<<<<<<<<<<<<< * - * # report epoch information + * cdef WeightVector w = WeightVector(weights, average_weights) */ - __pyx_v_count = (__pyx_v_count + 1); - } + __pyx_v_n_features = (__pyx_v_weights->dimensions[0]); - /* "sklearn/linear_model/sgd_fast.pyx":412 + /* "sklearn/linear_model/sgd_fast.pyx":551 + * cdef Py_ssize_t n_features = weights.shape[0] * - * # report epoch information - * if verbose > 0: # <<<<<<<<<<<<<< - * print("Norm: %.2f, NNZs: %d, "\ - * "Bias: %.6f, T: %d, Avg. loss: %.6f" % (w.norm(), + * cdef WeightVector w = WeightVector(weights, average_weights) # <<<<<<<<<<<<<< + * cdef double* w_ptr = &weights[0] + * cdef double *x_data_ptr = NULL */ - __pyx_t_12 = (__pyx_v_verbose > 0); - if (__pyx_t_12) { + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_weights)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_weights)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_weights)); + __Pyx_INCREF(((PyObject *)__pyx_v_average_weights)); + PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_average_weights)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_average_weights)); + __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_5utils_13weight_vector_WeightVector)), __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_w = ((struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_t_3); + __pyx_t_3 = 0; - /* "sklearn/linear_model/sgd_fast.pyx":414 - * if verbose > 0: - * print("Norm: %.2f, NNZs: %d, "\ - * "Bias: %.6f, T: %d, Avg. loss: %.6f" % (w.norm(), # <<<<<<<<<<<<<< - * weights.nonzero()[0].shape[0], - * intercept, count, + /* "sklearn/linear_model/sgd_fast.pyx":552 + * + * cdef WeightVector w = WeightVector(weights, average_weights) + * cdef double* w_ptr = &weights[0] # <<<<<<<<<<<<<< + * cdef double *x_data_ptr = NULL + * cdef int *x_ind_ptr = NULL */ - __pyx_t_6 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_w->__pyx_vtab)->norm(__pyx_v_w)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = 0; + __pyx_v_w_ptr = (&(*__Pyx_BufPtrCContig1d(double *, __pyx_pybuffernd_weights.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_weights.diminfo[0].strides))); - /* "sklearn/linear_model/sgd_fast.pyx":415 - * print("Norm: %.2f, NNZs: %d, "\ - * "Bias: %.6f, T: %d, Avg. loss: %.6f" % (w.norm(), - * weights.nonzero()[0].shape[0], # <<<<<<<<<<<<<< - * intercept, count, - * sumloss / count)) + /* "sklearn/linear_model/sgd_fast.pyx":553 + * cdef WeightVector w = WeightVector(weights, average_weights) + * cdef double* w_ptr = &weights[0] + * cdef double *x_data_ptr = NULL # <<<<<<<<<<<<<< + * cdef int *x_ind_ptr = NULL + * cdef double* ps_ptr = NULL */ - __pyx_t_4 = PyObject_GetAttr(((PyObject *)__pyx_v_weights), __pyx_n_s__nonzero); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_GetItemInt(__pyx_t_2, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_GetItemInt(__pyx_t_2, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "sklearn/linear_model/sgd_fast.pyx":416 - * "Bias: %.6f, T: %d, Avg. loss: %.6f" % (w.norm(), - * weights.nonzero()[0].shape[0], - * intercept, count, # <<<<<<<<<<<<<< - * sumloss / count)) - * print("Total training time: %.2f seconds." % (time() - t_start)) - */ - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_intercept); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyLong_FromUnsignedLong(__pyx_v_count); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - - /* "sklearn/linear_model/sgd_fast.pyx":417 - * weights.nonzero()[0].shape[0], - * intercept, count, - * sumloss / count)) # <<<<<<<<<<<<<< - * print("Total training time: %.2f seconds." % (time() - t_start)) - * - */ - __pyx_t_5 = PyFloat_FromDouble((__pyx_v_sumloss / __pyx_v_count)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 417; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_15 = PyTuple_New(5); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_15)); - PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_15, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_15, 2, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_15, 3, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_15, 4, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_6 = 0; - __pyx_t_4 = 0; - __pyx_t_2 = 0; - __pyx_t_1 = 0; - __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_2), ((PyObject *)__pyx_t_15)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __Pyx_DECREF(((PyObject *)__pyx_t_15)); __pyx_t_15 = 0; - if (__Pyx_PrintOne(0, ((PyObject *)__pyx_t_5)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - - /* "sklearn/linear_model/sgd_fast.pyx":418 - * intercept, count, - * sumloss / count)) - * print("Total training time: %.2f seconds." % (time() - t_start)) # <<<<<<<<<<<<<< - * - * # floating-point under-/overflow check. - */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__time); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_15 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_15); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Subtract(__pyx_t_15, __pyx_v_t_start); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - __pyx_t_15 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_3), __pyx_t_5); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_15)); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__Pyx_PrintOne(0, ((PyObject *)__pyx_t_15)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_15)); __pyx_t_15 = 0; - goto __pyx_L17; - } - __pyx_L17:; + __pyx_v_x_data_ptr = NULL; - /* "sklearn/linear_model/sgd_fast.pyx":421 + /* "sklearn/linear_model/sgd_fast.pyx":554 + * cdef double* w_ptr = &weights[0] + * cdef double *x_data_ptr = NULL + * cdef int *x_ind_ptr = NULL # <<<<<<<<<<<<<< + * cdef double* ps_ptr = NULL * - * # floating-point under-/overflow check. - * if np.any(np.isinf(weights)) or np.any(np.isnan(weights)) \ # <<<<<<<<<<<<<< - * or np.isnan(intercept) or np.isinf(intercept): - * raise ValueError("floating-point under-/overflow occured.") */ - __pyx_t_15 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_15); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_15, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - __pyx_t_15 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_15); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_15, __pyx_n_s__isinf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - __pyx_t_15 = PyTuple_New(1); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_15)); - __Pyx_INCREF(((PyObject *)__pyx_v_weights)); - PyTuple_SET_ITEM(__pyx_t_15, 0, ((PyObject *)__pyx_v_weights)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_weights)); - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_15), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_15)); __pyx_t_15 = 0; - __pyx_t_15 = PyTuple_New(1); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_15)); - PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_15), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_15)); __pyx_t_15 = 0; - __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!__pyx_t_12) { + __pyx_v_x_ind_ptr = NULL; - /* "sklearn/linear_model/sgd_fast.pyx":422 - * # floating-point under-/overflow check. - * if np.any(np.isinf(weights)) or np.any(np.isnan(weights)) \ - * or np.isnan(intercept) or np.isinf(intercept): # <<<<<<<<<<<<<< - * raise ValueError("floating-point under-/overflow occured.") + /* "sklearn/linear_model/sgd_fast.pyx":555 + * cdef double *x_data_ptr = NULL + * cdef int *x_ind_ptr = NULL + * cdef double* ps_ptr = NULL # <<<<<<<<<<<<<< * + * # helper variables */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_15 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_15); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_ps_ptr = NULL; - /* "sklearn/linear_model/sgd_fast.pyx":421 + /* "sklearn/linear_model/sgd_fast.pyx":558 * - * # floating-point under-/overflow check. - * if np.any(np.isinf(weights)) or np.any(np.isnan(weights)) \ # <<<<<<<<<<<<<< - * or np.isnan(intercept) or np.isinf(intercept): - * raise ValueError("floating-point under-/overflow occured.") + * # helper variables + * cdef bint infinity = False # <<<<<<<<<<<<<< + * cdef int xnnz + * cdef double eta = 0.0 */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isnan); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_weights)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_weights)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_weights)); - __pyx_t_1 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_15, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_16 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_16 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!__pyx_t_16) { - - /* "sklearn/linear_model/sgd_fast.pyx":422 - * # floating-point under-/overflow check. - * if np.any(np.isinf(weights)) or np.any(np.isnan(weights)) \ - * or np.isnan(intercept) or np.isinf(intercept): # <<<<<<<<<<<<<< - * raise ValueError("floating-point under-/overflow occured.") - * - */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__isnan); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_intercept); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_15 = PyTuple_New(1); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_15)); - PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_15), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_15)); __pyx_t_15 = 0; - __pyx_t_17 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_17 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!__pyx_t_17) { - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_15 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__isinf); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_15); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_intercept); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_15, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_18 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_18 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_19 = __pyx_t_18; - } else { - __pyx_t_19 = __pyx_t_17; - } - __pyx_t_17 = __pyx_t_19; - } else { - __pyx_t_17 = __pyx_t_16; - } - __pyx_t_16 = __pyx_t_17; - } else { - __pyx_t_16 = __pyx_t_12; - } - if (__pyx_t_16) { + __pyx_v_infinity = 0; - /* "sklearn/linear_model/sgd_fast.pyx":423 - * if np.any(np.isinf(weights)) or np.any(np.isnan(weights)) \ - * or np.isnan(intercept) or np.isinf(intercept): - * raise ValueError("floating-point under-/overflow occured.") # <<<<<<<<<<<<<< - * - * w.reset_wscale() + /* "sklearn/linear_model/sgd_fast.pyx":560 + * cdef bint infinity = False + * cdef int xnnz + * cdef double eta = 0.0 # <<<<<<<<<<<<<< + * cdef double p = 0.0 + * cdef double update = 0.0 */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_5), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L18; - } - __pyx_L18:; - } + __pyx_v_eta = 0.0; - /* "sklearn/linear_model/sgd_fast.pyx":425 - * raise ValueError("floating-point under-/overflow occured.") - * - * w.reset_wscale() # <<<<<<<<<<<<<< - * - * return weights, intercept + /* "sklearn/linear_model/sgd_fast.pyx":561 + * cdef int xnnz + * cdef double eta = 0.0 + * cdef double p = 0.0 # <<<<<<<<<<<<<< + * cdef double update = 0.0 + * cdef double sumloss = 0.0 */ - ((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_w->__pyx_vtab)->reset_wscale(__pyx_v_w); + __pyx_v_p = 0.0; - /* "sklearn/linear_model/sgd_fast.pyx":427 - * w.reset_wscale() - * - * return weights, intercept # <<<<<<<<<<<<<< - * - * + /* "sklearn/linear_model/sgd_fast.pyx":562 + * cdef double eta = 0.0 + * cdef double p = 0.0 + * cdef double update = 0.0 # <<<<<<<<<<<<<< + * cdef double sumloss = 0.0 + * cdef double y = 0.0 */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_intercept); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 427; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 427; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_weights)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_weights)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_weights)); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_r = ((PyObject *)__pyx_t_2); - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_15); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_q); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_weights); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.linear_model.sgd_fast.plain_sgd", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_q); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_weights); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_w); - __Pyx_XDECREF((PyObject *)__pyx_v_q); - __Pyx_XDECREF(__pyx_v_t_start); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_v_update = 0.0; -/* "sklearn/linear_model/sgd_fast.pyx":430 - * - * - * cdef inline double max(double a, double b): # <<<<<<<<<<<<<< - * return a if a >= b else b - * + /* "sklearn/linear_model/sgd_fast.pyx":563 + * cdef double p = 0.0 + * cdef double update = 0.0 + * cdef double sumloss = 0.0 # <<<<<<<<<<<<<< + * cdef double y = 0.0 + * cdef double sample_weight */ + __pyx_v_sumloss = 0.0; -static CYTHON_INLINE double __pyx_f_7sklearn_12linear_model_8sgd_fast_max(double __pyx_v_a, double __pyx_v_b) { - double __pyx_r; - __Pyx_RefNannyDeclarations - double __pyx_t_1; - __Pyx_RefNannySetupContext("max"); - - /* "sklearn/linear_model/sgd_fast.pyx":431 - * - * cdef inline double max(double a, double b): - * return a if a >= b else b # <<<<<<<<<<<<<< - * - * + /* "sklearn/linear_model/sgd_fast.pyx":564 + * cdef double update = 0.0 + * cdef double sumloss = 0.0 + * cdef double y = 0.0 # <<<<<<<<<<<<<< + * cdef double sample_weight + * cdef double class_weight = 1.0 */ - if ((__pyx_v_a >= __pyx_v_b)) { - __pyx_t_1 = __pyx_v_a; - } else { - __pyx_t_1 = __pyx_v_b; - } - __pyx_r = __pyx_t_1; - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_v_y = 0.0; -/* "sklearn/linear_model/sgd_fast.pyx":434 - * - * - * cdef inline double min(double a, double b): # <<<<<<<<<<<<<< - * return a if a <= b else b - * + /* "sklearn/linear_model/sgd_fast.pyx":566 + * cdef double y = 0.0 + * cdef double sample_weight + * cdef double class_weight = 1.0 # <<<<<<<<<<<<<< + * cdef unsigned int count = 0 + * cdef unsigned int epoch = 0 */ + __pyx_v_class_weight = 1.0; -static CYTHON_INLINE double __pyx_f_7sklearn_12linear_model_8sgd_fast_min(double __pyx_v_a, double __pyx_v_b) { - double __pyx_r; - __Pyx_RefNannyDeclarations - double __pyx_t_1; - __Pyx_RefNannySetupContext("min"); - - /* "sklearn/linear_model/sgd_fast.pyx":435 - * - * cdef inline double min(double a, double b): - * return a if a <= b else b # <<<<<<<<<<<<<< - * - * + /* "sklearn/linear_model/sgd_fast.pyx":567 + * cdef double sample_weight + * cdef double class_weight = 1.0 + * cdef unsigned int count = 0 # <<<<<<<<<<<<<< + * cdef unsigned int epoch = 0 + * cdef unsigned int i = 0 */ - if ((__pyx_v_a <= __pyx_v_b)) { - __pyx_t_1 = __pyx_v_a; - } else { - __pyx_t_1 = __pyx_v_b; - } - __pyx_r = __pyx_t_1; - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_v_count = 0; -/* "sklearn/linear_model/sgd_fast.pyx":438 - * - * - * cdef void l1penalty(WeightVector w, DOUBLE *q_data_ptr, # <<<<<<<<<<<<<< - * INTEGER *x_ind_ptr, int xnnz, double u): - * """Apply the L1 penalty to each updated feature + /* "sklearn/linear_model/sgd_fast.pyx":568 + * cdef double class_weight = 1.0 + * cdef unsigned int count = 0 + * cdef unsigned int epoch = 0 # <<<<<<<<<<<<<< + * cdef unsigned int i = 0 + * cdef int is_hinge = isinstance(loss, Hinge) */ + __pyx_v_epoch = 0; -static void __pyx_f_7sklearn_12linear_model_8sgd_fast_l1penalty(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_w, __pyx_t_7sklearn_12linear_model_8sgd_fast_DOUBLE *__pyx_v_q_data_ptr, __pyx_t_7sklearn_12linear_model_8sgd_fast_INTEGER *__pyx_v_x_ind_ptr, int __pyx_v_xnnz, double __pyx_v_u) { - double __pyx_v_z; - int __pyx_v_j; - int __pyx_v_idx; - double __pyx_v_wscale; - double *__pyx_v_w_data_ptr; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - __Pyx_RefNannySetupContext("l1penalty"); - - /* "sklearn/linear_model/sgd_fast.pyx":445 - * [Tsuruoka, Y., Tsujii, J., and Ananiadou, S., 2009]. - * """ - * cdef double z = 0.0 # <<<<<<<<<<<<<< - * cdef int j = 0 - * cdef int idx = 0 + /* "sklearn/linear_model/sgd_fast.pyx":569 + * cdef unsigned int count = 0 + * cdef unsigned int epoch = 0 + * cdef unsigned int i = 0 # <<<<<<<<<<<<<< + * cdef int is_hinge = isinstance(loss, Hinge) + * cdef double optimal_init = 0.0 */ - __pyx_v_z = 0.0; + __pyx_v_i = 0; - /* "sklearn/linear_model/sgd_fast.pyx":446 - * """ - * cdef double z = 0.0 - * cdef int j = 0 # <<<<<<<<<<<<<< - * cdef int idx = 0 - * cdef double wscale = w.wscale + /* "sklearn/linear_model/sgd_fast.pyx":570 + * cdef unsigned int epoch = 0 + * cdef unsigned int i = 0 + * cdef int is_hinge = isinstance(loss, Hinge) # <<<<<<<<<<<<<< + * cdef double optimal_init = 0.0 + * cdef double dloss = 0.0 */ - __pyx_v_j = 0; + __pyx_t_5 = __Pyx_TypeCheck(((PyObject *)__pyx_v_loss), ((PyObject*)__pyx_ptype_7sklearn_12linear_model_8sgd_fast_Hinge)); + __pyx_v_is_hinge = __pyx_t_5; - /* "sklearn/linear_model/sgd_fast.pyx":447 - * cdef double z = 0.0 - * cdef int j = 0 - * cdef int idx = 0 # <<<<<<<<<<<<<< - * cdef double wscale = w.wscale - * cdef double* w_data_ptr = w.w_data_ptr + /* "sklearn/linear_model/sgd_fast.pyx":571 + * cdef unsigned int i = 0 + * cdef int is_hinge = isinstance(loss, Hinge) + * cdef double optimal_init = 0.0 # <<<<<<<<<<<<<< + * cdef double dloss = 0.0 + * cdef double MAX_DLOSS = 1e12 */ - __pyx_v_idx = 0; + __pyx_v_optimal_init = 0.0; - /* "sklearn/linear_model/sgd_fast.pyx":448 - * cdef int j = 0 - * cdef int idx = 0 - * cdef double wscale = w.wscale # <<<<<<<<<<<<<< - * cdef double* w_data_ptr = w.w_data_ptr - * for j in range(xnnz): + /* "sklearn/linear_model/sgd_fast.pyx":572 + * cdef int is_hinge = isinstance(loss, Hinge) + * cdef double optimal_init = 0.0 + * cdef double dloss = 0.0 # <<<<<<<<<<<<<< + * cdef double MAX_DLOSS = 1e12 + * */ - __pyx_v_wscale = __pyx_v_w->wscale; + __pyx_v_dloss = 0.0; - /* "sklearn/linear_model/sgd_fast.pyx":449 - * cdef int idx = 0 - * cdef double wscale = w.wscale - * cdef double* w_data_ptr = w.w_data_ptr # <<<<<<<<<<<<<< - * for j in range(xnnz): - * idx = x_ind_ptr[j] + /* "sklearn/linear_model/sgd_fast.pyx":573 + * cdef double optimal_init = 0.0 + * cdef double dloss = 0.0 + * cdef double MAX_DLOSS = 1e12 # <<<<<<<<<<<<<< + * + * # q vector is only used for L1 regularization */ - __pyx_v_w_data_ptr = __pyx_v_w->w_data_ptr; + __pyx_v_MAX_DLOSS = 1e12; - /* "sklearn/linear_model/sgd_fast.pyx":450 - * cdef double wscale = w.wscale - * cdef double* w_data_ptr = w.w_data_ptr - * for j in range(xnnz): # <<<<<<<<<<<<<< - * idx = x_ind_ptr[j] - * z = w_data_ptr[idx] + /* "sklearn/linear_model/sgd_fast.pyx":576 + * + * # q vector is only used for L1 regularization + * cdef np.ndarray[double, ndim = 1, mode = "c"] q = None # <<<<<<<<<<<<<< + * cdef double * q_data_ptr = NULL + * if penalty_type == L1 or penalty_type == ELASTICNET: */ - __pyx_t_1 = __pyx_v_xnnz; - for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { - __pyx_v_j = __pyx_t_2; + __pyx_t_6 = ((PyArrayObject *)Py_None); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_q.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_q = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_q.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_q.diminfo[0].strides = __pyx_pybuffernd_q.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_q.diminfo[0].shape = __pyx_pybuffernd_q.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __Pyx_INCREF(Py_None); + __pyx_v_q = ((PyArrayObject *)Py_None); - /* "sklearn/linear_model/sgd_fast.pyx":451 - * cdef double* w_data_ptr = w.w_data_ptr - * for j in range(xnnz): - * idx = x_ind_ptr[j] # <<<<<<<<<<<<<< - * z = w_data_ptr[idx] - * if (wscale * w_data_ptr[idx]) > 0.0: + /* "sklearn/linear_model/sgd_fast.pyx":577 + * # q vector is only used for L1 regularization + * cdef np.ndarray[double, ndim = 1, mode = "c"] q = None + * cdef double * q_data_ptr = NULL # <<<<<<<<<<<<<< + * if penalty_type == L1 or penalty_type == ELASTICNET: + * q = np.zeros((n_features,), dtype=np.float64, order="c") */ - __pyx_v_idx = (__pyx_v_x_ind_ptr[__pyx_v_j]); + __pyx_v_q_data_ptr = NULL; - /* "sklearn/linear_model/sgd_fast.pyx":452 - * for j in range(xnnz): - * idx = x_ind_ptr[j] - * z = w_data_ptr[idx] # <<<<<<<<<<<<<< - * if (wscale * w_data_ptr[idx]) > 0.0: - * w_data_ptr[idx] = max( + /* "sklearn/linear_model/sgd_fast.pyx":578 + * cdef np.ndarray[double, ndim = 1, mode = "c"] q = None + * cdef double * q_data_ptr = NULL + * if penalty_type == L1 or penalty_type == ELASTICNET: # <<<<<<<<<<<<<< + * q = np.zeros((n_features,), dtype=np.float64, order="c") + * q_data_ptr = q.data */ - __pyx_v_z = (__pyx_v_w_data_ptr[__pyx_v_idx]); + switch (__pyx_v_penalty_type) { + case 1: + case 3: - /* "sklearn/linear_model/sgd_fast.pyx":453 - * idx = x_ind_ptr[j] - * z = w_data_ptr[idx] - * if (wscale * w_data_ptr[idx]) > 0.0: # <<<<<<<<<<<<<< - * w_data_ptr[idx] = max( - * 0.0, w_data_ptr[idx] - ((u + q_data_ptr[idx]) / wscale)) + /* "sklearn/linear_model/sgd_fast.pyx":579 + * cdef double * q_data_ptr = NULL + * if penalty_type == L1 or penalty_type == ELASTICNET: + * q = np.zeros((n_features,), dtype=np.float64, order="c") # <<<<<<<<<<<<<< + * q_data_ptr = q.data + * cdef double u = 0.0 */ - __pyx_t_3 = ((__pyx_v_wscale * (__pyx_v_w_data_ptr[__pyx_v_idx])) > 0.0); - if (__pyx_t_3) { + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_n_features); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_float64); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_dtype, __pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_order, __pyx_n_s_c) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_7); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (!(likely(((__pyx_t_9) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_9, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_9); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_q.rcbuffer->pybuffer); + __pyx_t_10 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_q.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_10 < 0)) { + PyErr_Fetch(&__pyx_t_11, &__pyx_t_12, &__pyx_t_13); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_q.rcbuffer->pybuffer, (PyObject*)__pyx_v_q, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_13); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_11, __pyx_t_12, __pyx_t_13); + } + } + __pyx_pybuffernd_q.diminfo[0].strides = __pyx_pybuffernd_q.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_q.diminfo[0].shape = __pyx_pybuffernd_q.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_10 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_6 = 0; + __Pyx_DECREF_SET(__pyx_v_q, ((PyArrayObject *)__pyx_t_9)); + __pyx_t_9 = 0; - /* "sklearn/linear_model/sgd_fast.pyx":454 - * z = w_data_ptr[idx] - * if (wscale * w_data_ptr[idx]) > 0.0: - * w_data_ptr[idx] = max( # <<<<<<<<<<<<<< - * 0.0, w_data_ptr[idx] - ((u + q_data_ptr[idx]) / wscale)) + /* "sklearn/linear_model/sgd_fast.pyx":580 + * if penalty_type == L1 or penalty_type == ELASTICNET: + * q = np.zeros((n_features,), dtype=np.float64, order="c") + * q_data_ptr = q.data # <<<<<<<<<<<<<< + * cdef double u = 0.0 * */ - (__pyx_v_w_data_ptr[__pyx_v_idx]) = __pyx_f_7sklearn_12linear_model_8sgd_fast_max(0.0, ((__pyx_v_w_data_ptr[__pyx_v_idx]) - ((__pyx_v_u + (__pyx_v_q_data_ptr[__pyx_v_idx])) / __pyx_v_wscale))); - goto __pyx_L5; - } + __pyx_v_q_data_ptr = ((double *)__pyx_v_q->data); + break; + default: break; + } - /* "sklearn/linear_model/sgd_fast.pyx":457 - * 0.0, w_data_ptr[idx] - ((u + q_data_ptr[idx]) / wscale)) + /* "sklearn/linear_model/sgd_fast.pyx":581 + * q = np.zeros((n_features,), dtype=np.float64, order="c") + * q_data_ptr = q.data + * cdef double u = 0.0 # <<<<<<<<<<<<<< * - * elif (wscale * w_data_ptr[idx]) < 0.0: # <<<<<<<<<<<<<< - * w_data_ptr[idx] = min( - * 0.0, w_data_ptr[idx] + ((u - q_data_ptr[idx]) / wscale)) + * if penalty_type == L2: */ - __pyx_t_3 = ((__pyx_v_wscale * (__pyx_v_w_data_ptr[__pyx_v_idx])) < 0.0); - if (__pyx_t_3) { + __pyx_v_u = 0.0; - /* "sklearn/linear_model/sgd_fast.pyx":458 - * - * elif (wscale * w_data_ptr[idx]) < 0.0: - * w_data_ptr[idx] = min( # <<<<<<<<<<<<<< - * 0.0, w_data_ptr[idx] + ((u - q_data_ptr[idx]) / wscale)) + /* "sklearn/linear_model/sgd_fast.pyx":585 + * if penalty_type == L2: + * l1_ratio = 0.0 + * elif penalty_type == L1: # <<<<<<<<<<<<<< + * l1_ratio = 1.0 * */ - (__pyx_v_w_data_ptr[__pyx_v_idx]) = __pyx_f_7sklearn_12linear_model_8sgd_fast_min(0.0, ((__pyx_v_w_data_ptr[__pyx_v_idx]) + ((__pyx_v_u - (__pyx_v_q_data_ptr[__pyx_v_idx])) / __pyx_v_wscale))); - goto __pyx_L5; - } - __pyx_L5:; + switch (__pyx_v_penalty_type) { - /* "sklearn/linear_model/sgd_fast.pyx":461 - * 0.0, w_data_ptr[idx] + ((u - q_data_ptr[idx]) / wscale)) + /* "sklearn/linear_model/sgd_fast.pyx":583 + * cdef double u = 0.0 * - * q_data_ptr[idx] += (wscale * (w_data_ptr[idx] - z)) # <<<<<<<<<<<<<< + * if penalty_type == L2: # <<<<<<<<<<<<<< + * l1_ratio = 0.0 + * elif penalty_type == L1: */ - __pyx_t_4 = __pyx_v_idx; - (__pyx_v_q_data_ptr[__pyx_t_4]) = ((__pyx_v_q_data_ptr[__pyx_t_4]) + (__pyx_v_wscale * ((__pyx_v_w_data_ptr[__pyx_v_idx]) - __pyx_v_z))); - } - - __Pyx_RefNannyFinishContext(); -} + case 2: -/* "numpy.pxd":190 - * # experimental exception made for __getbuffer__ and __releasebuffer__ - * # -- the details of this may change. - * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< - * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP. + /* "sklearn/linear_model/sgd_fast.pyx":584 + * + * if penalty_type == L2: + * l1_ratio = 0.0 # <<<<<<<<<<<<<< + * elif penalty_type == L1: + * l1_ratio = 1.0 */ + __pyx_v_l1_ratio = 0.0; + break; -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_v_copy_shape; - int __pyx_v_i; - int __pyx_v_ndim; - int __pyx_v_endian_detector; - int __pyx_v_little_endian; - int __pyx_v_t; - char *__pyx_v_f; - PyArray_Descr *__pyx_v_descr = 0; - int __pyx_v_offset; - int __pyx_v_hasfields; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - char *__pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__"); - if (__pyx_v_info != NULL) { - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); - } - - /* "numpy.pxd":196 - * # of flags + /* "sklearn/linear_model/sgd_fast.pyx":585 + * if penalty_type == L2: + * l1_ratio = 0.0 + * elif penalty_type == L1: # <<<<<<<<<<<<<< + * l1_ratio = 1.0 * - * if info == NULL: return # <<<<<<<<<<<<<< + */ + case 1: + + /* "sklearn/linear_model/sgd_fast.pyx":586 + * l1_ratio = 0.0 + * elif penalty_type == L1: + * l1_ratio = 1.0 # <<<<<<<<<<<<<< * - * cdef int copy_shape, i, ndim + * eta = eta0 */ - __pyx_t_1 = (__pyx_v_info == NULL); - if (__pyx_t_1) { - __pyx_r = 0; - goto __pyx_L0; - goto __pyx_L5; + __pyx_v_l1_ratio = 1.0; + break; + default: break; } - __pyx_L5:; - /* "numpy.pxd":199 + /* "sklearn/linear_model/sgd_fast.pyx":588 + * l1_ratio = 1.0 * - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) + * eta = eta0 # <<<<<<<<<<<<<< * + * if learning_rate == OPTIMAL: */ - __pyx_v_endian_detector = 1; + __pyx_v_eta = __pyx_v_eta0; - /* "numpy.pxd":200 - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/sgd_fast.pyx":590 + * eta = eta0 * - * ndim = PyArray_NDIM(self) + * if learning_rate == OPTIMAL: # <<<<<<<<<<<<<< + * typw = np.sqrt(1.0 / np.sqrt(alpha)) + * # computing eta0, the initial learning rate */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + __pyx_t_5 = ((__pyx_v_learning_rate == 2) != 0); + if (__pyx_t_5) { - /* "numpy.pxd":202 - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * - * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/sgd_fast.pyx":591 * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * if learning_rate == OPTIMAL: + * typw = np.sqrt(1.0 / np.sqrt(alpha)) # <<<<<<<<<<<<<< + * # computing eta0, the initial learning rate + * initial_eta0 = typw / max(1.0, loss.dloss(-typw, 1.0)) */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_sqrt); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_sqrt); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_14 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_8))) { + __pyx_t_14 = PyMethod_GET_SELF(__pyx_t_8); + if (likely(__pyx_t_14)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8); + __Pyx_INCREF(__pyx_t_14); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_8, function); + } + } + if (!__pyx_t_14) { + __pyx_t_7 = __Pyx_PyObject_CallOneArg(__pyx_t_8, __pyx_t_2); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_GOTREF(__pyx_t_7); + } else { + __pyx_t_15 = PyTuple_New(1+1); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_t_14); __Pyx_GIVEREF(__pyx_t_14); __pyx_t_14 = NULL; + PyTuple_SET_ITEM(__pyx_t_15, 0+1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_15, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyNumber_Divide(__pyx_float_1_0, __pyx_t_7); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (!__pyx_t_7) { + __pyx_t_9 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_8); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_GOTREF(__pyx_t_9); + } else { + __pyx_t_15 = PyTuple_New(1+1); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); __pyx_t_7 = NULL; + PyTuple_SET_ITEM(__pyx_t_15, 0+1, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_15, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_typw = __pyx_t_9; + __pyx_t_9 = 0; - /* "numpy.pxd":204 - * ndim = PyArray_NDIM(self) - * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * copy_shape = 1 - * else: + /* "sklearn/linear_model/sgd_fast.pyx":593 + * typw = np.sqrt(1.0 / np.sqrt(alpha)) + * # computing eta0, the initial learning rate + * initial_eta0 = typw / max(1.0, loss.dloss(-typw, 1.0)) # <<<<<<<<<<<<<< + * # initialize t such that eta at first sample equals eta0 + * optimal_init = 1.0 / (initial_eta0 * alpha) */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); - if (__pyx_t_1) { + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_loss), __pyx_n_s_dloss); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_15 = PyNumber_Negative(__pyx_v_typw); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_8 = NULL; + __pyx_t_1 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_8)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_1 = 1; + } + } + __pyx_t_7 = PyTuple_New(2+__pyx_t_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (__pyx_t_8) { + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_8); __Pyx_GIVEREF(__pyx_t_8); __pyx_t_8 = NULL; + } + PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_1, __pyx_t_15); + __Pyx_GIVEREF(__pyx_t_15); + __Pyx_INCREF(__pyx_float_1_0); + PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_1, __pyx_float_1_0); + __Pyx_GIVEREF(__pyx_float_1_0); + __pyx_t_15 = 0; + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_7, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_16 = 1.0; + __pyx_t_7 = PyFloat_FromDouble(__pyx_t_16); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_15 = PyObject_RichCompare(__pyx_t_9, __pyx_t_7, Py_GT); __Pyx_XGOTREF(__pyx_t_15); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_15); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + if (__pyx_t_5) { + __Pyx_INCREF(__pyx_t_9); + __pyx_t_3 = __pyx_t_9; + } else { + __pyx_t_15 = PyFloat_FromDouble(__pyx_t_16); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_3 = __pyx_t_15; + __pyx_t_15 = 0; + } + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyNumber_Divide(__pyx_v_typw, __pyx_t_3); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_initial_eta0 = __pyx_t_9; + __pyx_t_9 = 0; - /* "numpy.pxd":205 + /* "sklearn/linear_model/sgd_fast.pyx":595 + * initial_eta0 = typw / max(1.0, loss.dloss(-typw, 1.0)) + * # initialize t such that eta at first sample equals eta0 + * optimal_init = 1.0 / (initial_eta0 * alpha) # <<<<<<<<<<<<<< * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * copy_shape = 1 # <<<<<<<<<<<<<< - * else: - * copy_shape = 0 + * t_start = time() */ - __pyx_v_copy_shape = 1; - goto __pyx_L6; + __pyx_t_9 = PyFloat_FromDouble(__pyx_v_alpha); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 595; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_3 = PyNumber_Multiply(__pyx_v_initial_eta0, __pyx_t_9); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 595; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyNumber_Divide(__pyx_float_1_0, __pyx_t_3); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 595; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_16 = __pyx_PyFloat_AsDouble(__pyx_t_9); if (unlikely((__pyx_t_16 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 595; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_optimal_init = __pyx_t_16; + goto __pyx_L3; } - /*else*/ { + __pyx_L3:; - /* "numpy.pxd":207 - * copy_shape = 1 - * else: - * copy_shape = 0 # <<<<<<<<<<<<<< + /* "sklearn/linear_model/sgd_fast.pyx":597 + * optimal_init = 1.0 / (initial_eta0 * alpha) * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * t_start = time() # <<<<<<<<<<<<<< + * with nogil: + * for epoch in range(n_iter): */ - __pyx_v_copy_shape = 0; + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_time); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_15 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_15 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_15)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_15); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (__pyx_t_15) { + __pyx_t_9 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_15); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + } else { + __pyx_t_9 = __Pyx_PyObject_CallNoArg(__pyx_t_3); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_t_start = __pyx_t_9; + __pyx_t_9 = 0; - /* "numpy.pxd":209 - * copy_shape = 0 + /* "sklearn/linear_model/sgd_fast.pyx":598 * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") + * t_start = time() + * with nogil: # <<<<<<<<<<<<<< + * for epoch in range(n_iter): + * if verbose > 0: */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); - if (__pyx_t_1) { + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { - /* "numpy.pxd":210 - * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not C contiguous") + /* "sklearn/linear_model/sgd_fast.pyx":599 + * t_start = time() + * with nogil: + * for epoch in range(n_iter): # <<<<<<<<<<<<<< + * if verbose > 0: + * with gil: + */ + __pyx_t_10 = __pyx_v_n_iter; + for (__pyx_t_17 = 0; __pyx_t_17 < __pyx_t_10; __pyx_t_17+=1) { + __pyx_v_epoch = __pyx_t_17; + + /* "sklearn/linear_model/sgd_fast.pyx":600 + * with nogil: + * for epoch in range(n_iter): + * if verbose > 0: # <<<<<<<<<<<<<< + * with gil: + * print("-- Epoch %d" % (epoch + 1)) + */ + __pyx_t_5 = ((__pyx_v_verbose > 0) != 0); + if (__pyx_t_5) { + + /* "sklearn/linear_model/sgd_fast.pyx":601 + * for epoch in range(n_iter): + * if verbose > 0: + * with gil: # <<<<<<<<<<<<<< + * print("-- Epoch %d" % (epoch + 1)) + * if shuffle: + */ + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + /*try:*/ { + + /* "sklearn/linear_model/sgd_fast.pyx":602 + * if verbose > 0: + * with gil: + * print("-- Epoch %d" % (epoch + 1)) # <<<<<<<<<<<<<< + * if shuffle: + * dataset.shuffle(seed) + */ + __pyx_t_9 = __Pyx_PyInt_From_long((__pyx_v_epoch + 1)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 602; __pyx_clineno = __LINE__; goto __pyx_L13_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Epoch_d, __pyx_t_9); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 602; __pyx_clineno = __LINE__; goto __pyx_L13_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (__Pyx_PrintOne(0, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 602; __pyx_clineno = __LINE__; goto __pyx_L13_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + + /* "sklearn/linear_model/sgd_fast.pyx":601 + * for epoch in range(n_iter): + * if verbose > 0: + * with gil: # <<<<<<<<<<<<<< + * print("-- Epoch %d" % (epoch + 1)) + * if shuffle: + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + goto __pyx_L14; + } + __pyx_L13_error: { + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + goto __pyx_L5_error; + } + __pyx_L14:; + } + } + goto __pyx_L9; + } + __pyx_L9:; + + /* "sklearn/linear_model/sgd_fast.pyx":603 + * with gil: + * print("-- Epoch %d" % (epoch + 1)) + * if shuffle: # <<<<<<<<<<<<<< + * dataset.shuffle(seed) + * for i in range(n_samples): + */ + __pyx_t_5 = (__pyx_v_shuffle != 0); + if (__pyx_t_5) { + + /* "sklearn/linear_model/sgd_fast.pyx":604 + * print("-- Epoch %d" % (epoch + 1)) + * if shuffle: + * dataset.shuffle(seed) # <<<<<<<<<<<<<< + * for i in range(n_samples): + * dataset.next(&x_data_ptr, + */ + ((struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset *)__pyx_v_dataset->__pyx_vtab)->shuffle(__pyx_v_dataset, __pyx_v_seed); + goto __pyx_L15; + } + __pyx_L15:; + + /* "sklearn/linear_model/sgd_fast.pyx":605 + * if shuffle: + * dataset.shuffle(seed) + * for i in range(n_samples): # <<<<<<<<<<<<<< + * dataset.next(&x_data_ptr, + * &x_ind_ptr, + */ + __pyx_t_1 = __pyx_v_n_samples; + for (__pyx_t_18 = 0; __pyx_t_18 < __pyx_t_1; __pyx_t_18+=1) { + __pyx_v_i = __pyx_t_18; + + /* "sklearn/linear_model/sgd_fast.pyx":606 + * dataset.shuffle(seed) + * for i in range(n_samples): + * dataset.next(&x_data_ptr, # <<<<<<<<<<<<<< + * &x_ind_ptr, + * &xnnz, + */ + ((struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset *)__pyx_v_dataset->__pyx_vtab)->next(__pyx_v_dataset, (&__pyx_v_x_data_ptr), (&__pyx_v_x_ind_ptr), (&__pyx_v_xnnz), (&__pyx_v_y), (&__pyx_v_sample_weight)); + + /* "sklearn/linear_model/sgd_fast.pyx":612 + * &sample_weight) * + * p = w.dot(x_data_ptr, x_ind_ptr, xnnz) + intercept # <<<<<<<<<<<<<< + * if learning_rate == OPTIMAL: + * eta = 1.0 / (alpha * (optimal_init + t - 1)) */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); - __pyx_t_3 = __pyx_t_2; - } else { - __pyx_t_3 = __pyx_t_1; - } - if (__pyx_t_3) { + __pyx_v_p = (((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_w->__pyx_vtab)->dot(__pyx_v_w, __pyx_v_x_data_ptr, __pyx_v_x_ind_ptr, __pyx_v_xnnz) + __pyx_v_intercept); - /* "numpy.pxd":211 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + /* "sklearn/linear_model/sgd_fast.pyx":615 + * if learning_rate == OPTIMAL: + * eta = 1.0 / (alpha * (optimal_init + t - 1)) + * elif learning_rate == INVSCALING: # <<<<<<<<<<<<<< + * eta = eta0 / pow(t, power_t) * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_7), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; + switch (__pyx_v_learning_rate) { - /* "numpy.pxd":213 - * raise ValueError(u"ndarray is not C contiguous") + /* "sklearn/linear_model/sgd_fast.pyx":613 * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") + * p = w.dot(x_data_ptr, x_ind_ptr, xnnz) + intercept + * if learning_rate == OPTIMAL: # <<<<<<<<<<<<<< + * eta = 1.0 / (alpha * (optimal_init + t - 1)) + * elif learning_rate == INVSCALING: + */ + case 2: + + /* "sklearn/linear_model/sgd_fast.pyx":614 + * p = w.dot(x_data_ptr, x_ind_ptr, xnnz) + intercept + * if learning_rate == OPTIMAL: + * eta = 1.0 / (alpha * (optimal_init + t - 1)) # <<<<<<<<<<<<<< + * elif learning_rate == INVSCALING: + * eta = eta0 / pow(t, power_t) */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); - if (__pyx_t_3) { + __pyx_v_eta = (1.0 / (__pyx_v_alpha * ((__pyx_v_optimal_init + __pyx_v_t) - 1.0))); + break; - /* "numpy.pxd":214 + /* "sklearn/linear_model/sgd_fast.pyx":615 + * if learning_rate == OPTIMAL: + * eta = 1.0 / (alpha * (optimal_init + t - 1)) + * elif learning_rate == INVSCALING: # <<<<<<<<<<<<<< + * eta = eta0 / pow(t, power_t) * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not Fortran contiguous") + */ + case 3: + + /* "sklearn/linear_model/sgd_fast.pyx":616 + * eta = 1.0 / (alpha * (optimal_init + t - 1)) + * elif learning_rate == INVSCALING: + * eta = eta0 / pow(t, power_t) # <<<<<<<<<<<<<< * + * if verbose > 0: */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); - __pyx_t_2 = __pyx_t_1; - } else { - __pyx_t_2 = __pyx_t_3; - } - if (__pyx_t_2) { + __pyx_v_eta = (__pyx_v_eta0 / pow(__pyx_v_t, __pyx_v_power_t)); + break; + default: break; + } - /* "numpy.pxd":215 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + /* "sklearn/linear_model/sgd_fast.pyx":618 + * eta = eta0 / pow(t, power_t) + * + * if verbose > 0: # <<<<<<<<<<<<<< + * sumloss += loss.loss(p, y) * - * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; - } - __pyx_L8:; + __pyx_t_5 = ((__pyx_v_verbose > 0) != 0); + if (__pyx_t_5) { - /* "numpy.pxd":217 - * raise ValueError(u"ndarray is not Fortran contiguous") + /* "sklearn/linear_model/sgd_fast.pyx":619 * - * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< - * info.ndim = ndim - * if copy_shape: + * if verbose > 0: + * sumloss += loss.loss(p, y) # <<<<<<<<<<<<<< + * + * if y > 0.0: */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_v_sumloss = (__pyx_v_sumloss + ((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_loss->__pyx_vtab)->loss(__pyx_v_loss, __pyx_v_p, __pyx_v_y)); + goto __pyx_L18; + } + __pyx_L18:; - /* "numpy.pxd":218 + /* "sklearn/linear_model/sgd_fast.pyx":621 + * sumloss += loss.loss(p, y) * - * info.buf = PyArray_DATA(self) - * info.ndim = ndim # <<<<<<<<<<<<<< - * if copy_shape: - * # Allocate new buffer for strides and shape info. + * if y > 0.0: # <<<<<<<<<<<<<< + * class_weight = weight_pos + * else: */ - __pyx_v_info->ndim = __pyx_v_ndim; + __pyx_t_5 = ((__pyx_v_y > 0.0) != 0); + if (__pyx_t_5) { - /* "numpy.pxd":219 - * info.buf = PyArray_DATA(self) - * info.ndim = ndim - * if copy_shape: # <<<<<<<<<<<<<< - * # Allocate new buffer for strides and shape info. - * # This is allocated as one block, strides first. + /* "sklearn/linear_model/sgd_fast.pyx":622 + * + * if y > 0.0: + * class_weight = weight_pos # <<<<<<<<<<<<<< + * else: + * class_weight = weight_neg */ - if (__pyx_v_copy_shape) { + __pyx_v_class_weight = __pyx_v_weight_pos; + goto __pyx_L19; + } + /*else*/ { - /* "numpy.pxd":222 - * # Allocate new buffer for strides and shape info. - * # This is allocated as one block, strides first. - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< - * info.shape = info.strides + ndim - * for i in range(ndim): + /* "sklearn/linear_model/sgd_fast.pyx":624 + * class_weight = weight_pos + * else: + * class_weight = weight_neg # <<<<<<<<<<<<<< + * + * if learning_rate == PA1: */ - __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + __pyx_v_class_weight = __pyx_v_weight_neg; + } + __pyx_L19:; + + /* "sklearn/linear_model/sgd_fast.pyx":631 + * continue + * update = min(C, loss.loss(p, y) / update) + * elif learning_rate == PA2: # <<<<<<<<<<<<<< + * update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) + * update = loss.loss(p, y) / (update + 0.5 / C) + */ + switch (__pyx_v_learning_rate) { + + /* "sklearn/linear_model/sgd_fast.pyx":626 + * class_weight = weight_neg + * + * if learning_rate == PA1: # <<<<<<<<<<<<<< + * update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) + * if update == 0: + */ + case 4: + + /* "sklearn/linear_model/sgd_fast.pyx":627 + * + * if learning_rate == PA1: + * update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) # <<<<<<<<<<<<<< + * if update == 0: + * continue + */ + __pyx_v_update = __pyx_f_7sklearn_12linear_model_8sgd_fast_sqnorm(__pyx_v_x_data_ptr, __pyx_v_x_ind_ptr, __pyx_v_xnnz); + + /* "sklearn/linear_model/sgd_fast.pyx":628 + * if learning_rate == PA1: + * update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) + * if update == 0: # <<<<<<<<<<<<<< + * continue + * update = min(C, loss.loss(p, y) / update) + */ + __pyx_t_5 = ((__pyx_v_update == 0.0) != 0); + if (__pyx_t_5) { + + /* "sklearn/linear_model/sgd_fast.pyx":629 + * update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) + * if update == 0: + * continue # <<<<<<<<<<<<<< + * update = min(C, loss.loss(p, y) / update) + * elif learning_rate == PA2: + */ + goto __pyx_L16_continue; + } + + /* "sklearn/linear_model/sgd_fast.pyx":630 + * if update == 0: + * continue + * update = min(C, loss.loss(p, y) / update) # <<<<<<<<<<<<<< + * elif learning_rate == PA2: + * update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) + */ + __pyx_t_16 = (((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_loss->__pyx_vtab)->loss(__pyx_v_loss, __pyx_v_p, __pyx_v_y) / __pyx_v_update); + __pyx_t_19 = __pyx_v_C; + if (((__pyx_t_16 < __pyx_t_19) != 0)) { + __pyx_t_20 = __pyx_t_16; + } else { + __pyx_t_20 = __pyx_t_19; + } + __pyx_v_update = __pyx_t_20; + break; + + /* "sklearn/linear_model/sgd_fast.pyx":631 + * continue + * update = min(C, loss.loss(p, y) / update) + * elif learning_rate == PA2: # <<<<<<<<<<<<<< + * update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) + * update = loss.loss(p, y) / (update + 0.5 / C) + */ + case 5: + + /* "sklearn/linear_model/sgd_fast.pyx":632 + * update = min(C, loss.loss(p, y) / update) + * elif learning_rate == PA2: + * update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) # <<<<<<<<<<<<<< + * update = loss.loss(p, y) / (update + 0.5 / C) + * else: + */ + __pyx_v_update = __pyx_f_7sklearn_12linear_model_8sgd_fast_sqnorm(__pyx_v_x_data_ptr, __pyx_v_x_ind_ptr, __pyx_v_xnnz); - /* "numpy.pxd":223 - * # This is allocated as one block, strides first. - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) - * info.shape = info.strides + ndim # <<<<<<<<<<<<<< - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] + /* "sklearn/linear_model/sgd_fast.pyx":633 + * elif learning_rate == PA2: + * update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) + * update = loss.loss(p, y) / (update + 0.5 / C) # <<<<<<<<<<<<<< + * else: + * dloss = loss._dloss(p, y) */ - __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + __pyx_v_update = (((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_loss->__pyx_vtab)->loss(__pyx_v_loss, __pyx_v_p, __pyx_v_y) / (__pyx_v_update + (0.5 / __pyx_v_C))); + break; + default: - /* "numpy.pxd":224 - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) - * info.shape = info.strides + ndim - * for i in range(ndim): # <<<<<<<<<<<<<< - * info.strides[i] = PyArray_STRIDES(self)[i] - * info.shape[i] = PyArray_DIMS(self)[i] + /* "sklearn/linear_model/sgd_fast.pyx":635 + * update = loss.loss(p, y) / (update + 0.5 / C) + * else: + * dloss = loss._dloss(p, y) # <<<<<<<<<<<<<< + * # clip dloss with large values to avoid numerical + * # instabilities + */ + __pyx_v_dloss = ((struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction *)__pyx_v_loss->__pyx_vtab)->_dloss(__pyx_v_loss, __pyx_v_p, __pyx_v_y); + + /* "sklearn/linear_model/sgd_fast.pyx":638 + * # clip dloss with large values to avoid numerical + * # instabilities + * if dloss < -MAX_DLOSS: # <<<<<<<<<<<<<< + * dloss = -MAX_DLOSS + * elif dloss > MAX_DLOSS: + */ + __pyx_t_5 = ((__pyx_v_dloss < (-__pyx_v_MAX_DLOSS)) != 0); + if (__pyx_t_5) { + + /* "sklearn/linear_model/sgd_fast.pyx":639 + * # instabilities + * if dloss < -MAX_DLOSS: + * dloss = -MAX_DLOSS # <<<<<<<<<<<<<< + * elif dloss > MAX_DLOSS: + * dloss = MAX_DLOSS + */ + __pyx_v_dloss = (-__pyx_v_MAX_DLOSS); + goto __pyx_L21; + } + + /* "sklearn/linear_model/sgd_fast.pyx":640 + * if dloss < -MAX_DLOSS: + * dloss = -MAX_DLOSS + * elif dloss > MAX_DLOSS: # <<<<<<<<<<<<<< + * dloss = MAX_DLOSS + * update = -eta * dloss + */ + __pyx_t_5 = ((__pyx_v_dloss > __pyx_v_MAX_DLOSS) != 0); + if (__pyx_t_5) { + + /* "sklearn/linear_model/sgd_fast.pyx":641 + * dloss = -MAX_DLOSS + * elif dloss > MAX_DLOSS: + * dloss = MAX_DLOSS # <<<<<<<<<<<<<< + * update = -eta * dloss + * + */ + __pyx_v_dloss = __pyx_v_MAX_DLOSS; + goto __pyx_L21; + } + __pyx_L21:; + + /* "sklearn/linear_model/sgd_fast.pyx":642 + * elif dloss > MAX_DLOSS: + * dloss = MAX_DLOSS + * update = -eta * dloss # <<<<<<<<<<<<<< + * + * if learning_rate >= PA1: + */ + __pyx_v_update = ((-__pyx_v_eta) * __pyx_v_dloss); + break; + } + + /* "sklearn/linear_model/sgd_fast.pyx":644 + * update = -eta * dloss + * + * if learning_rate >= PA1: # <<<<<<<<<<<<<< + * if is_hinge: + * # classification */ - __pyx_t_5 = __pyx_v_ndim; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; + __pyx_t_5 = ((__pyx_v_learning_rate >= 4) != 0); + if (__pyx_t_5) { - /* "numpy.pxd":225 - * info.shape = info.strides + ndim - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< - * info.shape[i] = PyArray_DIMS(self)[i] - * else: + /* "sklearn/linear_model/sgd_fast.pyx":645 + * + * if learning_rate >= PA1: + * if is_hinge: # <<<<<<<<<<<<<< + * # classification + * update *= y */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + __pyx_t_5 = (__pyx_v_is_hinge != 0); + if (__pyx_t_5) { - /* "numpy.pxd":226 - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] - * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< - * else: - * info.strides = PyArray_STRIDES(self) + /* "sklearn/linear_model/sgd_fast.pyx":647 + * if is_hinge: + * # classification + * update *= y # <<<<<<<<<<<<<< + * elif y - p < 0: + * # regression */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); - } - goto __pyx_L9; - } - /*else*/ { + __pyx_v_update = (__pyx_v_update * __pyx_v_y); + goto __pyx_L23; + } - /* "numpy.pxd":228 - * info.shape[i] = PyArray_DIMS(self)[i] - * else: - * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL + /* "sklearn/linear_model/sgd_fast.pyx":648 + * # classification + * update *= y + * elif y - p < 0: # <<<<<<<<<<<<<< + * # regression + * update *= -1 */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_t_5 = (((__pyx_v_y - __pyx_v_p) < 0.0) != 0); + if (__pyx_t_5) { - /* "numpy.pxd":229 - * else: - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) + /* "sklearn/linear_model/sgd_fast.pyx":650 + * elif y - p < 0: + * # regression + * update *= -1 # <<<<<<<<<<<<<< + * + * update *= class_weight * sample_weight */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); - } - __pyx_L9:; + __pyx_v_update = (__pyx_v_update * -1.0); + goto __pyx_L23; + } + __pyx_L23:; + goto __pyx_L22; + } + __pyx_L22:; - /* "numpy.pxd":230 - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * info.itemsize = PyArray_ITEMSIZE(self) - * info.readonly = not PyArray_ISWRITEABLE(self) + /* "sklearn/linear_model/sgd_fast.pyx":652 + * update *= -1 + * + * update *= class_weight * sample_weight # <<<<<<<<<<<<<< + * + * if penalty_type >= L2: */ - __pyx_v_info->suboffsets = NULL; + __pyx_v_update = (__pyx_v_update * (__pyx_v_class_weight * __pyx_v_sample_weight)); - /* "numpy.pxd":231 - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< - * info.readonly = not PyArray_ISWRITEABLE(self) + /* "sklearn/linear_model/sgd_fast.pyx":654 + * update *= class_weight * sample_weight * + * if penalty_type >= L2: # <<<<<<<<<<<<<< + * # do not scale to negative values when eta or alpha are too + * # big: instead set the weights to zero */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_t_5 = ((__pyx_v_penalty_type >= 2) != 0); + if (__pyx_t_5) { - /* "numpy.pxd":232 - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) - * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< - * - * cdef int t + /* "sklearn/linear_model/sgd_fast.pyx":657 + * # do not scale to negative values when eta or alpha are too + * # big: instead set the weights to zero + * w.scale(max(0, 1.0 - ((1.0 - l1_ratio) * eta * alpha))) # <<<<<<<<<<<<<< + * if update != 0.0: + * w.add(x_data_ptr, x_ind_ptr, xnnz, update) */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_t_20 = (1.0 - (((1.0 - __pyx_v_l1_ratio) * __pyx_v_eta) * __pyx_v_alpha)); + __pyx_t_21 = 0; + if (((__pyx_t_20 > __pyx_t_21) != 0)) { + __pyx_t_16 = __pyx_t_20; + } else { + __pyx_t_16 = __pyx_t_21; + } + ((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_w->__pyx_vtab)->scale(__pyx_v_w, __pyx_t_16); + goto __pyx_L24; + } + __pyx_L24:; - /* "numpy.pxd":235 - * - * cdef int t - * cdef char* f = NULL # <<<<<<<<<<<<<< - * cdef dtype descr = self.descr - * cdef list stack + /* "sklearn/linear_model/sgd_fast.pyx":658 + * # big: instead set the weights to zero + * w.scale(max(0, 1.0 - ((1.0 - l1_ratio) * eta * alpha))) + * if update != 0.0: # <<<<<<<<<<<<<< + * w.add(x_data_ptr, x_ind_ptr, xnnz, update) + * if fit_intercept == 1: */ - __pyx_v_f = NULL; + __pyx_t_5 = ((__pyx_v_update != 0.0) != 0); + if (__pyx_t_5) { - /* "numpy.pxd":236 - * cdef int t - * cdef char* f = NULL - * cdef dtype descr = self.descr # <<<<<<<<<<<<<< - * cdef list stack - * cdef int offset + /* "sklearn/linear_model/sgd_fast.pyx":659 + * w.scale(max(0, 1.0 - ((1.0 - l1_ratio) * eta * alpha))) + * if update != 0.0: + * w.add(x_data_ptr, x_ind_ptr, xnnz, update) # <<<<<<<<<<<<<< + * if fit_intercept == 1: + * intercept += update * intercept_decay */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + ((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_w->__pyx_vtab)->add(__pyx_v_w, __pyx_v_x_data_ptr, __pyx_v_x_ind_ptr, __pyx_v_xnnz, __pyx_v_update); - /* "numpy.pxd":240 - * cdef int offset - * - * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + /* "sklearn/linear_model/sgd_fast.pyx":660 + * if update != 0.0: + * w.add(x_data_ptr, x_ind_ptr, xnnz, update) + * if fit_intercept == 1: # <<<<<<<<<<<<<< + * intercept += update * intercept_decay * - * if not hasfields and not copy_shape: */ - __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + __pyx_t_5 = ((__pyx_v_fit_intercept == 1) != 0); + if (__pyx_t_5) { - /* "numpy.pxd":242 - * cdef bint hasfields = PyDataType_HASFIELDS(descr) + /* "sklearn/linear_model/sgd_fast.pyx":661 + * w.add(x_data_ptr, x_ind_ptr, xnnz, update) + * if fit_intercept == 1: + * intercept += update * intercept_decay # <<<<<<<<<<<<<< * - * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< - * # do not call releasebuffer - * info.obj = None + * if average > 0 and average <= t: */ - __pyx_t_2 = (!__pyx_v_hasfields); - if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); - __pyx_t_1 = __pyx_t_3; - } else { - __pyx_t_1 = __pyx_t_2; - } - if (__pyx_t_1) { + __pyx_v_intercept = (__pyx_v_intercept + (__pyx_v_update * __pyx_v_intercept_decay)); + goto __pyx_L26; + } + __pyx_L26:; + goto __pyx_L25; + } + __pyx_L25:; - /* "numpy.pxd":244 - * if not hasfields and not copy_shape: - * # do not call releasebuffer - * info.obj = None # <<<<<<<<<<<<<< - * else: - * # need to call releasebuffer + /* "sklearn/linear_model/sgd_fast.pyx":663 + * intercept += update * intercept_decay + * + * if average > 0 and average <= t: # <<<<<<<<<<<<<< + * # compute the average for the intercept and update the + * # average weights, this is done regardless as to whther */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = Py_None; - goto __pyx_L12; - } - /*else*/ { + __pyx_t_22 = ((__pyx_v_average > 0) != 0); + if (__pyx_t_22) { + } else { + __pyx_t_5 = __pyx_t_22; + goto __pyx_L28_bool_binop_done; + } + __pyx_t_22 = ((__pyx_v_average <= __pyx_v_t) != 0); + __pyx_t_5 = __pyx_t_22; + __pyx_L28_bool_binop_done:; + if (__pyx_t_5) { - /* "numpy.pxd":247 - * else: - * # need to call releasebuffer - * info.obj = self # <<<<<<<<<<<<<< + /* "sklearn/linear_model/sgd_fast.pyx":668 + * # the update is 0 * - * if not hasfields: + * w.add_average(x_data_ptr, x_ind_ptr, xnnz, # <<<<<<<<<<<<<< + * update, (t - average + 1)) + * average_intercept += ((intercept - average_intercept) / */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; - } - __pyx_L12:; + ((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_w->__pyx_vtab)->add_average(__pyx_v_w, __pyx_v_x_data_ptr, __pyx_v_x_ind_ptr, __pyx_v_xnnz, __pyx_v_update, ((__pyx_v_t - __pyx_v_average) + 1.0)); - /* "numpy.pxd":249 - * info.obj = self + /* "sklearn/linear_model/sgd_fast.pyx":670 + * w.add_average(x_data_ptr, x_ind_ptr, xnnz, + * update, (t - average + 1)) + * average_intercept += ((intercept - average_intercept) / # <<<<<<<<<<<<<< + * (t - average + 1)) * - * if not hasfields: # <<<<<<<<<<<<<< - * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); - if (__pyx_t_1) { + __pyx_v_average_intercept = (__pyx_v_average_intercept + ((__pyx_v_intercept - __pyx_v_average_intercept) / ((__pyx_v_t - __pyx_v_average) + 1.0))); + goto __pyx_L27; + } + __pyx_L27:; - /* "numpy.pxd":250 + /* "sklearn/linear_model/sgd_fast.pyx":673 + * (t - average + 1)) * - * if not hasfields: - * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if penalty_type == L1 or penalty_type == ELASTICNET: # <<<<<<<<<<<<<< + * u += (l1_ratio * eta * alpha) + * l1penalty(w, q_data_ptr, x_ind_ptr, xnnz, u) */ - __pyx_v_t = __pyx_v_descr->type_num; + switch (__pyx_v_penalty_type) { + case 1: + case 3: - /* "numpy.pxd":251 - * if not hasfields: - * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") + /* "sklearn/linear_model/sgd_fast.pyx":674 + * + * if penalty_type == L1 or penalty_type == ELASTICNET: + * u += (l1_ratio * eta * alpha) # <<<<<<<<<<<<<< + * l1penalty(w, q_data_ptr, x_ind_ptr, xnnz, u) + * */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); - if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; - } else { - __pyx_t_2 = __pyx_t_1; - } - if (!__pyx_t_2) { + __pyx_v_u = (__pyx_v_u + ((__pyx_v_l1_ratio * __pyx_v_eta) * __pyx_v_alpha)); - /* "numpy.pxd":252 - * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" + /* "sklearn/linear_model/sgd_fast.pyx":675 + * if penalty_type == L1 or penalty_type == ELASTICNET: + * u += (l1_ratio * eta * alpha) + * l1penalty(w, q_data_ptr, x_ind_ptr, xnnz, u) # <<<<<<<<<<<<<< + * + * t += 1 */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); - if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); - __pyx_t_7 = __pyx_t_3; - } else { - __pyx_t_7 = __pyx_t_1; - } - __pyx_t_1 = __pyx_t_7; - } else { - __pyx_t_1 = __pyx_t_2; - } - if (__pyx_t_1) { + __pyx_f_7sklearn_12linear_model_8sgd_fast_l1penalty(__pyx_v_w, __pyx_v_q_data_ptr, __pyx_v_x_ind_ptr, __pyx_v_xnnz, __pyx_v_u); + break; + default: break; + } - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" + /* "sklearn/linear_model/sgd_fast.pyx":677 + * l1penalty(w, q_data_ptr, x_ind_ptr, xnnz, u) + * + * t += 1 # <<<<<<<<<<<<<< + * count += 1 + * */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; - } - __pyx_L14:; + __pyx_v_t = (__pyx_v_t + 1.0); - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" + /* "sklearn/linear_model/sgd_fast.pyx":678 + * + * t += 1 + * count += 1 # <<<<<<<<<<<<<< + * + * # report epoch information */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__b; - goto __pyx_L15; - } + __pyx_v_count = (__pyx_v_count + 1); + __pyx_L16_continue:; + } - /* "numpy.pxd":255 - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" + /* "sklearn/linear_model/sgd_fast.pyx":681 + * + * # report epoch information + * if verbose > 0: # <<<<<<<<<<<<<< + * with gil: + * print("Norm: %.2f, NNZs: %d, " */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__B; - goto __pyx_L15; - } + __pyx_t_5 = ((__pyx_v_verbose > 0) != 0); + if (__pyx_t_5) { - /* "numpy.pxd":256 - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" - */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__h; - goto __pyx_L15; - } + /* "sklearn/linear_model/sgd_fast.pyx":682 + * # report epoch information + * if verbose > 0: + * with gil: # <<<<<<<<<<<<<< + * print("Norm: %.2f, NNZs: %d, " + * "Bias: %.6f, T: %d, Avg. loss: %.6f" + */ + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + /*try:*/ { + + /* "sklearn/linear_model/sgd_fast.pyx":685 + * print("Norm: %.2f, NNZs: %d, " + * "Bias: %.6f, T: %d, Avg. loss: %.6f" + * % (w.norm(), weights.nonzero()[0].shape[0], # <<<<<<<<<<<<<< + * intercept, count, sumloss / count)) + * print("Total training time: %.2f seconds." + */ + __pyx_t_3 = PyFloat_FromDouble(((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_w->__pyx_vtab)->norm(__pyx_v_w)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 685; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_15 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_weights), __pyx_n_s_nonzero); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 685; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_7 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_15))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_15); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_15); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_15, function); + } + } + if (__pyx_t_7) { + __pyx_t_9 = __Pyx_PyObject_CallOneArg(__pyx_t_15, __pyx_t_7); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 685; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + } else { + __pyx_t_9 = __Pyx_PyObject_CallNoArg(__pyx_t_15); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 685; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + } + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_15 = __Pyx_GetItemInt(__pyx_t_9, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_15 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 685; __pyx_clineno = __LINE__; goto __pyx_L34_error;}; + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_15, __pyx_n_s_shape); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 685; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_15 = __Pyx_GetItemInt(__pyx_t_9, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_15 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 685; __pyx_clineno = __LINE__; goto __pyx_L34_error;}; + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "sklearn/linear_model/sgd_fast.pyx":686 + * "Bias: %.6f, T: %d, Avg. loss: %.6f" + * % (w.norm(), weights.nonzero()[0].shape[0], + * intercept, count, sumloss / count)) # <<<<<<<<<<<<<< + * print("Total training time: %.2f seconds." + * % (time() - t_start)) + */ + __pyx_t_9 = PyFloat_FromDouble(__pyx_v_intercept); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 686; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_7 = __Pyx_PyInt_From_unsigned_int(__pyx_v_count); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 686; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyFloat_FromDouble((__pyx_v_sumloss / __pyx_v_count)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 686; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_GOTREF(__pyx_t_8); + + /* "sklearn/linear_model/sgd_fast.pyx":685 + * print("Norm: %.2f, NNZs: %d, " + * "Bias: %.6f, T: %d, Avg. loss: %.6f" + * % (w.norm(), weights.nonzero()[0].shape[0], # <<<<<<<<<<<<<< + * intercept, count, sumloss / count)) + * print("Total training time: %.2f seconds." + */ + __pyx_t_2 = PyTuple_New(5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 685; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_15); + __Pyx_GIVEREF(__pyx_t_15); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_2, 4, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_3 = 0; + __pyx_t_15 = 0; + __pyx_t_9 = 0; + __pyx_t_7 = 0; + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyString_Format(__pyx_kp_s_Norm_2f_NNZs_d_Bias_6f_T_d_Avg_l, __pyx_t_2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 685; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_PrintOne(0, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 683; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "sklearn/linear_model/sgd_fast.pyx":688 + * intercept, count, sumloss / count)) + * print("Total training time: %.2f seconds." + * % (time() - t_start)) # <<<<<<<<<<<<<< + * + * # floating-point under-/overflow check. + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_time); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 688; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (__pyx_t_7) { + __pyx_t_8 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_7); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 688; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + } else { + __pyx_t_8 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 688; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + } + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyNumber_Subtract(__pyx_t_8, __pyx_v_t_start); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 688; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyString_Format(__pyx_kp_s_Total_training_time_2f_seconds, __pyx_t_2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 688; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_PrintOne(0, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 687; __pyx_clineno = __LINE__; goto __pyx_L34_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + } - /* "numpy.pxd":257 - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" - */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__H; - goto __pyx_L15; - } + /* "sklearn/linear_model/sgd_fast.pyx":682 + * # report epoch information + * if verbose > 0: + * with gil: # <<<<<<<<<<<<<< + * print("Norm: %.2f, NNZs: %d, " + * "Bias: %.6f, T: %d, Avg. loss: %.6f" + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + goto __pyx_L35; + } + __pyx_L34_error: { + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + goto __pyx_L5_error; + } + __pyx_L35:; + } + } + goto __pyx_L30; + } + __pyx_L30:; - /* "numpy.pxd":258 - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" + /* "sklearn/linear_model/sgd_fast.pyx":691 + * + * # floating-point under-/overflow check. + * if (not skl_isfinite(intercept) # <<<<<<<<<<<<<< + * or any_nonfinite(weights.data, n_features)): + * infinity = True */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__i; - goto __pyx_L15; - } + __pyx_t_22 = ((!(skl_isfinite(__pyx_v_intercept) != 0)) != 0); + if (!__pyx_t_22) { + } else { + __pyx_t_5 = __pyx_t_22; + goto __pyx_L37_bool_binop_done; + } - /* "numpy.pxd":259 - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" + /* "sklearn/linear_model/sgd_fast.pyx":692 + * # floating-point under-/overflow check. + * if (not skl_isfinite(intercept) + * or any_nonfinite(weights.data, n_features)): # <<<<<<<<<<<<<< + * infinity = True + * break */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__I; - goto __pyx_L15; - } + __pyx_t_22 = (__pyx_f_7sklearn_12linear_model_8sgd_fast_any_nonfinite(((double *)__pyx_v_weights->data), __pyx_v_n_features) != 0); + __pyx_t_5 = __pyx_t_22; + __pyx_L37_bool_binop_done:; + if (__pyx_t_5) { - /* "numpy.pxd":260 - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" + /* "sklearn/linear_model/sgd_fast.pyx":693 + * if (not skl_isfinite(intercept) + * or any_nonfinite(weights.data, n_features)): + * infinity = True # <<<<<<<<<<<<<< + * break + * */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__l; - goto __pyx_L15; - } + __pyx_v_infinity = 1; - /* "numpy.pxd":261 - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" + /* "sklearn/linear_model/sgd_fast.pyx":694 + * or any_nonfinite(weights.data, n_features)): + * infinity = True + * break # <<<<<<<<<<<<<< + * + * if infinity: */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__L; - goto __pyx_L15; - } + goto __pyx_L8_break; + } + } + __pyx_L8_break:; + } - /* "numpy.pxd":262 - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" + /* "sklearn/linear_model/sgd_fast.pyx":598 + * + * t_start = time() + * with nogil: # <<<<<<<<<<<<<< + * for epoch in range(n_iter): + * if verbose > 0: */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__q; - goto __pyx_L15; - } + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L6; + } + __pyx_L5_error: { + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L1_error; + } + __pyx_L6:; + } + } - /* "numpy.pxd":263 - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" + /* "sklearn/linear_model/sgd_fast.pyx":696 + * break + * + * if infinity: # <<<<<<<<<<<<<< + * raise ValueError(("Floating-point under-/overflow occurred at epoch" + * " #%d. Scaling input data with StandardScaler or" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; - } + __pyx_t_5 = (__pyx_v_infinity != 0); + if (__pyx_t_5) { - /* "numpy.pxd":264 - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" + /* "sklearn/linear_model/sgd_fast.pyx":699 + * raise ValueError(("Floating-point under-/overflow occurred at epoch" + * " #%d. Scaling input data with StandardScaler or" + * " MinMaxScaler might help.") % (epoch + 1)) # <<<<<<<<<<<<<< + * + * w.reset_wscale() */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__f; - goto __pyx_L15; - } + __pyx_t_8 = __Pyx_PyInt_From_long((__pyx_v_epoch + 1)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_2 = __Pyx_PyString_Format(__pyx_kp_s_Floating_point_under_overflow_oc, __pyx_t_8); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - /* "numpy.pxd":265 - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" + /* "sklearn/linear_model/sgd_fast.pyx":697 + * + * if infinity: + * raise ValueError(("Floating-point under-/overflow occurred at epoch" # <<<<<<<<<<<<<< + * " #%d. Scaling input data with StandardScaler or" + * " MinMaxScaler might help.") % (epoch + 1)) */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__d; - goto __pyx_L15; - } + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_8, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "numpy.pxd":266 - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" - */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__g; - goto __pyx_L15; - } - - /* "numpy.pxd":267 - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" - */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; - } - - /* "numpy.pxd":268 - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< - * elif t == NPY_CLONGDOUBLE: f = "Zg" - * elif t == NPY_OBJECT: f = "O" + /* "sklearn/linear_model/sgd_fast.pyx":701 + * " MinMaxScaler might help.") % (epoch + 1)) + * + * w.reset_wscale() # <<<<<<<<<<<<<< + * + * return weights, intercept, average_weights, average_intercept */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; - } + ((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_w->__pyx_vtab)->reset_wscale(__pyx_v_w); - /* "numpy.pxd":269 - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< - * elif t == NPY_OBJECT: f = "O" - * else: + /* "sklearn/linear_model/sgd_fast.pyx":703 + * w.reset_wscale() + * + * return weights, intercept, average_weights, average_intercept # <<<<<<<<<<<<<< + * + * */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; - } + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_intercept); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_8 = PyFloat_FromDouble(__pyx_v_average_intercept); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_7 = PyTuple_New(4); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_INCREF(((PyObject *)__pyx_v_weights)); + PyTuple_SET_ITEM(__pyx_t_7, 0, ((PyObject *)__pyx_v_weights)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_weights)); + PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_average_weights)); + PyTuple_SET_ITEM(__pyx_t_7, 2, ((PyObject *)__pyx_v_average_weights)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_average_weights)); + PyTuple_SET_ITEM(__pyx_t_7, 3, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_2 = 0; + __pyx_t_8 = 0; + __pyx_r = __pyx_t_7; + __pyx_t_7 = 0; + goto __pyx_L0; - /* "numpy.pxd":270 - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" - * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + /* "sklearn/linear_model/sgd_fast.pyx":529 + * + * + * def _plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * double intercept, + * np.ndarray[double, ndim=1, mode='c'] average_weights, */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L15; - } - /*else*/ { - /* "numpy.pxd":272 - * elif t == NPY_OBJECT: f = "O" - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< - * info.format = f - * return - */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_12), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); - __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L15:; + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_14); + __Pyx_XDECREF(__pyx_t_15); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_average_weights.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_q.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weights.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.linear_model.sgd_fast._plain_sgd", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_average_weights.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_q.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weights.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_w); + __Pyx_XDECREF((PyObject *)__pyx_v_q); + __Pyx_XDECREF(__pyx_v_typw); + __Pyx_XDECREF(__pyx_v_initial_eta0); + __Pyx_XDECREF(__pyx_v_t_start); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "numpy.pxd":273 - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * info.format = f # <<<<<<<<<<<<<< - * return - * else: +/* "sklearn/linear_model/sgd_fast.pyx":706 + * + * + * cdef bint any_nonfinite(double *w, int n) nogil: # <<<<<<<<<<<<<< + * for i in range(n): + * if not skl_isfinite(w[i]): */ - __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":274 - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * info.format = f - * return # <<<<<<<<<<<<<< - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) - */ - __pyx_r = 0; - goto __pyx_L0; - goto __pyx_L13; - } - /*else*/ { +static int __pyx_f_7sklearn_12linear_model_8sgd_fast_any_nonfinite(double *__pyx_v_w, int __pyx_v_n) { + int __pyx_v_i; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; - /* "numpy.pxd":276 - * return - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment - * offset = 0 + /* "sklearn/linear_model/sgd_fast.pyx":707 + * + * cdef bint any_nonfinite(double *w, int n) nogil: + * for i in range(n): # <<<<<<<<<<<<<< + * if not skl_isfinite(w[i]): + * return True */ - __pyx_v_info->format = ((char *)malloc(255)); + __pyx_t_1 = __pyx_v_n; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; - /* "numpy.pxd":277 - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< - * offset = 0 - * f = _util_dtypestring(descr, info.format + 1, + /* "sklearn/linear_model/sgd_fast.pyx":708 + * cdef bint any_nonfinite(double *w, int n) nogil: + * for i in range(n): + * if not skl_isfinite(w[i]): # <<<<<<<<<<<<<< + * return True + * return 0 */ - (__pyx_v_info->format[0]) = '^'; + __pyx_t_3 = ((!(skl_isfinite((__pyx_v_w[__pyx_v_i])) != 0)) != 0); + if (__pyx_t_3) { - /* "numpy.pxd":278 - * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment - * offset = 0 # <<<<<<<<<<<<<< - * f = _util_dtypestring(descr, info.format + 1, - * info.format + _buffer_format_string_len, + /* "sklearn/linear_model/sgd_fast.pyx":709 + * for i in range(n): + * if not skl_isfinite(w[i]): + * return True # <<<<<<<<<<<<<< + * return 0 + * */ - __pyx_v_offset = 0; + __pyx_r = 1; + goto __pyx_L0; + } + } - /* "numpy.pxd":281 - * f = _util_dtypestring(descr, info.format + 1, - * info.format + _buffer_format_string_len, - * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string + /* "sklearn/linear_model/sgd_fast.pyx":710 + * if not skl_isfinite(w[i]): + * return True + * return 0 # <<<<<<<<<<<<<< + * * */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_9; + __pyx_r = 0; + goto __pyx_L0; - /* "numpy.pxd":282 - * info.format + _buffer_format_string_len, - * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + /* "sklearn/linear_model/sgd_fast.pyx":706 * - * def __releasebuffer__(ndarray self, Py_buffer* info): + * + * cdef bint any_nonfinite(double *w, int n) nogil: # <<<<<<<<<<<<<< + * for i in range(n): + * if not skl_isfinite(w[i]): */ - (__pyx_v_f[0]) = 0; - } - __pyx_L13:; - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; - } - goto __pyx_L2; + /* function exit code */ __pyx_L0:; - if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { - __Pyx_GOTREF(Py_None); - __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; - } - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_descr); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string +/* "sklearn/linear_model/sgd_fast.pyx":713 * - * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) + * + * cdef double sqnorm(double * x_data_ptr, int * x_ind_ptr, int xnnz) nogil: # <<<<<<<<<<<<<< + * cdef double x_norm = 0.0 + * cdef int j */ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { - __Pyx_RefNannyDeclarations +static double __pyx_f_7sklearn_12linear_model_8sgd_fast_sqnorm(double *__pyx_v_x_data_ptr, CYTHON_UNUSED int *__pyx_v_x_ind_ptr, int __pyx_v_xnnz) { + double __pyx_v_x_norm; + int __pyx_v_j; + double __pyx_v_z; + double __pyx_r; int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__"); + int __pyx_t_2; - /* "numpy.pxd":285 + /* "sklearn/linear_model/sgd_fast.pyx":714 * - * def __releasebuffer__(ndarray self, Py_buffer* info): - * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< - * stdlib.free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * cdef double sqnorm(double * x_data_ptr, int * x_ind_ptr, int xnnz) nogil: + * cdef double x_norm = 0.0 # <<<<<<<<<<<<<< + * cdef int j + * cdef double z */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); - if (__pyx_t_1) { + __pyx_v_x_norm = 0.0; - /* "numpy.pxd":286 - * def __releasebuffer__(ndarray self, Py_buffer* info): - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) # <<<<<<<<<<<<<< - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * stdlib.free(info.strides) + /* "sklearn/linear_model/sgd_fast.pyx":717 + * cdef int j + * cdef double z + * for j in range(xnnz): # <<<<<<<<<<<<<< + * z = x_data_ptr[j] + * x_norm += z * z */ - free(__pyx_v_info->format); - goto __pyx_L5; - } - __pyx_L5:; + __pyx_t_1 = __pyx_v_xnnz; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; - /* "numpy.pxd":287 - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * stdlib.free(info.strides) - * # info.shape was stored after info.strides in the same block + /* "sklearn/linear_model/sgd_fast.pyx":718 + * cdef double z + * for j in range(xnnz): + * z = x_data_ptr[j] # <<<<<<<<<<<<<< + * x_norm += z * z + * return x_norm */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); - if (__pyx_t_1) { + __pyx_v_z = (__pyx_v_x_data_ptr[__pyx_v_j]); - /* "numpy.pxd":288 - * stdlib.free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * stdlib.free(info.strides) # <<<<<<<<<<<<<< - * # info.shape was stored after info.strides in the same block + /* "sklearn/linear_model/sgd_fast.pyx":719 + * for j in range(xnnz): + * z = x_data_ptr[j] + * x_norm += z * z # <<<<<<<<<<<<<< + * return x_norm * */ - free(__pyx_v_info->strides); - goto __pyx_L6; + __pyx_v_x_norm = (__pyx_v_x_norm + (__pyx_v_z * __pyx_v_z)); } - __pyx_L6:; - - __Pyx_RefNannyFinishContext(); -} -/* "numpy.pxd":764 - * ctypedef npy_cdouble complex_t + /* "sklearn/linear_model/sgd_fast.pyx":720 + * z = x_data_ptr[j] + * x_norm += z * z + * return x_norm # <<<<<<<<<<<<<< * - * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(1, a) * */ + __pyx_r = __pyx_v_x_norm; + goto __pyx_L0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); - - /* "numpy.pxd":765 + /* "sklearn/linear_model/sgd_fast.pyx":713 * - * cdef inline object PyArray_MultiIterNew1(a): - * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< * - * cdef inline object PyArray_MultiIterNew2(a, b): + * cdef double sqnorm(double * x_data_ptr, int * x_ind_ptr, int xnnz) nogil: # <<<<<<<<<<<<<< + * cdef double x_norm = 0.0 + * cdef int j */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":767 - * return PyArray_MultiIterNew(1, a) +/* "sklearn/linear_model/sgd_fast.pyx":723 * - * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(2, a, b) * + * cdef void l1penalty(WeightVector w, double * q_data_ptr, # <<<<<<<<<<<<<< + * int *x_ind_ptr, int xnnz, double u) nogil: + * """Apply the L1 penalty to each updated feature */ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); +static void __pyx_f_7sklearn_12linear_model_8sgd_fast_l1penalty(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_w, double *__pyx_v_q_data_ptr, int *__pyx_v_x_ind_ptr, int __pyx_v_xnnz, double __pyx_v_u) { + double __pyx_v_z; + int __pyx_v_j; + int __pyx_v_idx; + double __pyx_v_wscale; + double *__pyx_v_w_data_ptr; + double __pyx_t_1; + double *__pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + double __pyx_t_6; + double __pyx_t_7; + int __pyx_t_8; - /* "numpy.pxd":768 - * - * cdef inline object PyArray_MultiIterNew2(a, b): - * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + /* "sklearn/linear_model/sgd_fast.pyx":730 + * [Tsuruoka, Y., Tsujii, J., and Ananiadou, S., 2009]. + * """ + * cdef double z = 0.0 # <<<<<<<<<<<<<< + * cdef int j = 0 + * cdef int idx = 0 + */ + __pyx_v_z = 0.0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/linear_model/sgd_fast.pyx":731 + * """ + * cdef double z = 0.0 + * cdef int j = 0 # <<<<<<<<<<<<<< + * cdef int idx = 0 + * cdef double wscale = w.wscale + */ + __pyx_v_j = 0; -/* "numpy.pxd":770 - * return PyArray_MultiIterNew(2, a, b) - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(3, a, b, c) - * + /* "sklearn/linear_model/sgd_fast.pyx":732 + * cdef double z = 0.0 + * cdef int j = 0 + * cdef int idx = 0 # <<<<<<<<<<<<<< + * cdef double wscale = w.wscale + * cdef double *w_data_ptr = w.w_data_ptr */ + __pyx_v_idx = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); + /* "sklearn/linear_model/sgd_fast.pyx":733 + * cdef int j = 0 + * cdef int idx = 0 + * cdef double wscale = w.wscale # <<<<<<<<<<<<<< + * cdef double *w_data_ptr = w.w_data_ptr + * for j in range(xnnz): + */ + __pyx_t_1 = __pyx_v_w->wscale; + __pyx_v_wscale = __pyx_t_1; - /* "numpy.pxd":771 - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): - * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + /* "sklearn/linear_model/sgd_fast.pyx":734 + * cdef int idx = 0 + * cdef double wscale = w.wscale + * cdef double *w_data_ptr = w.w_data_ptr # <<<<<<<<<<<<<< + * for j in range(xnnz): + * idx = x_ind_ptr[j] */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_t_2 = __pyx_v_w->w_data_ptr; + __pyx_v_w_data_ptr = __pyx_t_2; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/linear_model/sgd_fast.pyx":735 + * cdef double wscale = w.wscale + * cdef double *w_data_ptr = w.w_data_ptr + * for j in range(xnnz): # <<<<<<<<<<<<<< + * idx = x_ind_ptr[j] + * z = w_data_ptr[idx] + */ + __pyx_t_3 = __pyx_v_xnnz; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_j = __pyx_t_4; -/* "numpy.pxd":773 - * return PyArray_MultiIterNew(3, a, b, c) - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(4, a, b, c, d) - * + /* "sklearn/linear_model/sgd_fast.pyx":736 + * cdef double *w_data_ptr = w.w_data_ptr + * for j in range(xnnz): + * idx = x_ind_ptr[j] # <<<<<<<<<<<<<< + * z = w_data_ptr[idx] + * if wscale * w_data_ptr[idx] > 0.0: */ + __pyx_v_idx = (__pyx_v_x_ind_ptr[__pyx_v_j]); -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); + /* "sklearn/linear_model/sgd_fast.pyx":737 + * for j in range(xnnz): + * idx = x_ind_ptr[j] + * z = w_data_ptr[idx] # <<<<<<<<<<<<<< + * if wscale * w_data_ptr[idx] > 0.0: + * w_data_ptr[idx] = max( + */ + __pyx_v_z = (__pyx_v_w_data_ptr[__pyx_v_idx]); + + /* "sklearn/linear_model/sgd_fast.pyx":738 + * idx = x_ind_ptr[j] + * z = w_data_ptr[idx] + * if wscale * w_data_ptr[idx] > 0.0: # <<<<<<<<<<<<<< + * w_data_ptr[idx] = max( + * 0.0, w_data_ptr[idx] - ((u + q_data_ptr[idx]) / wscale)) + */ + __pyx_t_5 = (((__pyx_v_wscale * (__pyx_v_w_data_ptr[__pyx_v_idx])) > 0.0) != 0); + if (__pyx_t_5) { - /* "numpy.pxd":774 + /* "sklearn/linear_model/sgd_fast.pyx":740 + * if wscale * w_data_ptr[idx] > 0.0: + * w_data_ptr[idx] = max( + * 0.0, w_data_ptr[idx] - ((u + q_data_ptr[idx]) / wscale)) # <<<<<<<<<<<<<< * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): - * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * elif wscale * w_data_ptr[idx] < 0.0: + */ + __pyx_t_1 = ((__pyx_v_w_data_ptr[__pyx_v_idx]) - ((__pyx_v_u + (__pyx_v_q_data_ptr[__pyx_v_idx])) / __pyx_v_wscale)); + __pyx_t_6 = 0.0; + if (((__pyx_t_1 > __pyx_t_6) != 0)) { + __pyx_t_7 = __pyx_t_1; + } else { + __pyx_t_7 = __pyx_t_6; + } + + /* "sklearn/linear_model/sgd_fast.pyx":739 + * z = w_data_ptr[idx] + * if wscale * w_data_ptr[idx] > 0.0: + * w_data_ptr[idx] = max( # <<<<<<<<<<<<<< + * 0.0, w_data_ptr[idx] - ((u + q_data_ptr[idx]) / wscale)) * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + (__pyx_v_w_data_ptr[__pyx_v_idx]) = __pyx_t_7; + goto __pyx_L5; + } - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/linear_model/sgd_fast.pyx":742 + * 0.0, w_data_ptr[idx] - ((u + q_data_ptr[idx]) / wscale)) + * + * elif wscale * w_data_ptr[idx] < 0.0: # <<<<<<<<<<<<<< + * w_data_ptr[idx] = min( + * 0.0, w_data_ptr[idx] + ((u - q_data_ptr[idx]) / wscale)) + */ + __pyx_t_5 = (((__pyx_v_wscale * (__pyx_v_w_data_ptr[__pyx_v_idx])) < 0.0) != 0); + if (__pyx_t_5) { -/* "numpy.pxd":776 - * return PyArray_MultiIterNew(4, a, b, c, d) + /* "sklearn/linear_model/sgd_fast.pyx":744 + * elif wscale * w_data_ptr[idx] < 0.0: + * w_data_ptr[idx] = min( + * 0.0, w_data_ptr[idx] + ((u - q_data_ptr[idx]) / wscale)) # <<<<<<<<<<<<<< * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(5, a, b, c, d, e) + * q_data_ptr[idx] += wscale * (w_data_ptr[idx] - z) + */ + __pyx_t_7 = ((__pyx_v_w_data_ptr[__pyx_v_idx]) + ((__pyx_v_u - (__pyx_v_q_data_ptr[__pyx_v_idx])) / __pyx_v_wscale)); + __pyx_t_1 = 0.0; + if (((__pyx_t_7 < __pyx_t_1) != 0)) { + __pyx_t_6 = __pyx_t_7; + } else { + __pyx_t_6 = __pyx_t_1; + } + + /* "sklearn/linear_model/sgd_fast.pyx":743 + * + * elif wscale * w_data_ptr[idx] < 0.0: + * w_data_ptr[idx] = min( # <<<<<<<<<<<<<< + * 0.0, w_data_ptr[idx] + ((u - q_data_ptr[idx]) / wscale)) * */ + (__pyx_v_w_data_ptr[__pyx_v_idx]) = __pyx_t_6; + goto __pyx_L5; + } + __pyx_L5:; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); + /* "sklearn/linear_model/sgd_fast.pyx":746 + * 0.0, w_data_ptr[idx] + ((u - q_data_ptr[idx]) / wscale)) + * + * q_data_ptr[idx] += wscale * (w_data_ptr[idx] - z) # <<<<<<<<<<<<<< + */ + __pyx_t_8 = __pyx_v_idx; + (__pyx_v_q_data_ptr[__pyx_t_8]) = ((__pyx_v_q_data_ptr[__pyx_t_8]) + (__pyx_v_wscale * ((__pyx_v_w_data_ptr[__pyx_v_idx]) - __pyx_v_z))); + } - /* "numpy.pxd":777 + /* "sklearn/linear_model/sgd_fast.pyx":723 * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): - * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< * - * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + * cdef void l1penalty(WeightVector w, double * q_data_ptr, # <<<<<<<<<<<<<< + * int *x_ind_ptr, int xnnz, double u) nogil: + * """Apply the L1 penalty to each updated feature */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; + /* function exit code */ } -/* "numpy.pxd":779 - * return PyArray_MultiIterNew(5, a, b, c, d, e) - * - * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< - * # Recursive utility function used in __getbuffer__ to get format - * # string. The new location in the format string is returned. +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. */ -static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { - PyArray_Descr *__pyx_v_child = 0; +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; int __pyx_v_endian_detector; int __pyx_v_little_endian; - PyObject *__pyx_v_fields = 0; - PyObject *__pyx_v_childname = NULL; - PyObject *__pyx_v_new_offset = NULL; - PyObject *__pyx_v_t = NULL; - char *__pyx_r; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; + int __pyx_t_1; + int __pyx_t_2; PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + char *__pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring"); - - /* "numpy.pxd":786 - * cdef int delta_offset - * cdef tuple i - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * cdef tuple fields - */ - __pyx_v_endian_detector = 1; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } - /* "numpy.pxd":787 - * cdef tuple i - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< - * cdef tuple fields + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< * + * cdef int copy_shape, i, ndim */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + } - /* "numpy.pxd":790 - * cdef tuple fields + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":203 * - * for childname in descr.names: # <<<<<<<<<<<<<< - * fields = descr.fields[childname] - * child, new_offset = fields - */ - if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; - __pyx_t_3 = 0; - - /* "numpy.pxd":791 - * - * for childname in descr.names: - * fields = descr.fields[childname] # <<<<<<<<<<<<<< - * child, new_offset = fields + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; + __pyx_v_endian_detector = 1; - /* "numpy.pxd":792 - * for childname in descr.names: - * fields = descr.fields[childname] - * child, new_offset = fields # <<<<<<<<<<<<<< + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * - * if (end - f) - (new_offset - offset[0]) < 15: + * ndim = PyArray_NDIM(self) */ - if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { - PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); - __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; - __pyx_t_4 = 0; + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":794 - * child, new_offset = fields + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":795 - * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":208 + * ndim = PyArray_NDIM(self) * - * if ((child.byteorder == '>' and little_endian) or + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { - /* "numpy.pxd":797 - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":209 * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; - } else { - __pyx_t_7 = __pyx_t_6; - } - if (!__pyx_t_7) { + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { - /* "numpy.pxd":798 + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< - * raise ValueError(u"Non-native byte order not supported") - * # One could encode it in the format string and have Cython - */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; - } else { - __pyx_t_9 = __pyx_t_6; - } - __pyx_t_6 = __pyx_t_9; - } else { - __pyx_t_6 = __pyx_t_7; - } - if (__pyx_t_6) { - - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * # One could encode it in the format string and have Cython - * # complain instead, BUT: < and > in format strings also imply + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; + __pyx_v_copy_shape = 0; + } + __pyx_L4:; - /* "numpy.pxd":809 + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":213 + * copy_shape = 0 * - * # Output padding bytes - * while offset[0] < new_offset: # <<<<<<<<<<<<<< - * f[0] = 120 # "x"; pad byte - * f += 1 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") */ - while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!__pyx_t_6) break; + __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L6_bool_binop_done; + } - /* "numpy.pxd":810 - * # Output padding bytes - * while offset[0] < new_offset: - * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< - * f += 1 - * offset[0] += 1 + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * */ - (__pyx_v_f[0]) = 120; + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L6_bool_binop_done:; + if (__pyx_t_1) { - /* "numpy.pxd":811 - * while offset[0] < new_offset: - * f[0] = 120 # "x"; pad byte - * f += 1 # <<<<<<<<<<<<<< - * offset[0] += 1 + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_v_f = (__pyx_v_f + 1); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "numpy.pxd":812 - * f[0] = 120 # "x"; pad byte - * f += 1 - * offset[0] += 1 # <<<<<<<<<<<<<< + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") * - * offset[0] += child.itemsize + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); - } + __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L9_bool_binop_done; + } - /* "numpy.pxd":814 - * offset[0] += 1 + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":218 * - * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") * - * if not PyDataType_HASFIELDS(child): */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L9_bool_binop_done:; + if (__pyx_t_1) { - /* "numpy.pxd":816 - * offset[0] += child.itemsize + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * - * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< - * t = child.type_num - * if end - f < 5: + * info.buf = PyArray_DATA(self) */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); - if (__pyx_t_6) { + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "numpy.pxd":817 + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") * - * if not PyDataType_HASFIELDS(child): - * t = child.type_num # <<<<<<<<<<<<<< - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":818 - * if not PyDataType_HASFIELDS(child): - * t = child.type_num - * if end - f < 5: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short.") + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":222 * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); - if (__pyx_t_6) { + __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":819 - * t = child.type_num - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< - * - * # Until ticket #99 is fixed, use integers to avoid warnings + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_17), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; - } - __pyx_L10:; + __pyx_t_1 = (__pyx_v_copy_shape != 0); + if (__pyx_t_1) { - /* "numpy.pxd":822 - * - * # Until ticket #99 is fixed, use integers to avoid warnings - * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 98; - goto __pyx_L11; - } + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":823 - * # Until ticket #99 is fixed, use integers to avoid warnings - * if t == NPY_BYTE: f[0] = 98 #"b" - * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 66; - goto __pyx_L11; - } + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":824 - * if t == NPY_BYTE: f[0] = 98 #"b" - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 104; - goto __pyx_L11; - } + __pyx_t_4 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; - /* "numpy.pxd":825 - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" - */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 72; - goto __pyx_L11; - } - - /* "numpy.pxd":826 - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 105; - goto __pyx_L11; - } + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":827 - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 73; - goto __pyx_L11; - } + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L11; + } + /*else*/ { - /* "numpy.pxd":828 - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 108; - goto __pyx_L11; - } + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":829 - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 76; - goto __pyx_L11; - } + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L11:; - /* "numpy.pxd":830 - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 113; - goto __pyx_L11; - } + __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":831 - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 81; - goto __pyx_L11; - } + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":832 - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 102; - goto __pyx_L11; - } + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - /* "numpy.pxd":833 - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 100; - goto __pyx_L11; - } + __pyx_v_f = NULL; - /* "numpy.pxd":834 - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 103; - goto __pyx_L11; - } + __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; - /* "numpy.pxd":835 - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 102; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; - } + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":836 - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg - * elif t == NPY_OBJECT: f[0] = 79 #"O" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 100; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; - } + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L15_bool_binop_done; + } + __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L15_bool_binop_done:; + if (__pyx_t_1) { - /* "numpy.pxd":837 - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< - * elif t == NPY_OBJECT: f[0] = 79 #"O" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< * else: + * # need to call releasebuffer */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 103; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; - } + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L14; + } + /*else*/ { - /* "numpy.pxd":838 - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg - * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":251 * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 79; - goto __pyx_L11; - } - /*else*/ { + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L14:; - /* "numpy.pxd":840 - * elif t == NPY_OBJECT: f[0] = 79 #"O" - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< - * f += 1 - * else: + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_12), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L11:; + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { - /* "numpy.pxd":841 - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * f += 1 # <<<<<<<<<<<<<< - * else: - * # Cython ignores struct boundary information ("T{...}"), + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; - } - /*else*/ { + __pyx_t_4 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_4; - /* "numpy.pxd":845 - * # Cython ignores struct boundary information ("T{...}"), - * # so don't output it - * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< - * return f - * + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; + __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); + if (!__pyx_t_2) { + goto __pyx_L20_next_or; + } else { } - __pyx_L9:; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_2 = (__pyx_v_little_endian != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_L20_next_or:; - /* "numpy.pxd":846 - * # so don't output it - * f = _util_dtypestring(child, f, end, offset) - * return f # <<<<<<<<<<<<<< - * - * + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" */ - __pyx_r = __pyx_v_f; - goto __pyx_L0; + __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L19_bool_binop_done:; + if (__pyx_t_1) { - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_child); - __Pyx_XDECREF(__pyx_v_fields); - __Pyx_XDECREF(__pyx_v_childname); - __Pyx_XDECREF(__pyx_v_new_offset); - __Pyx_XDECREF(__pyx_v_t); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } -/* "numpy.pxd":961 - * - * - * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< - * cdef PyObject* baseptr - * if base is None: + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ + switch (__pyx_v_t) { -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { - PyObject *__pyx_v_baseptr; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base"); + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; - /* "numpy.pxd":963 - * cdef inline void set_array_base(ndarray arr, object base): - * cdef PyObject* baseptr - * if base is None: # <<<<<<<<<<<<<< - * baseptr = NULL - * else: + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; - /* "numpy.pxd":964 - * cdef PyObject* baseptr - * if base is None: - * baseptr = NULL # <<<<<<<<<<<<<< - * else: - * Py_INCREF(base) # important to do this before decref below! + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" */ - __pyx_v_baseptr = NULL; - goto __pyx_L3; - } - /*else*/ { + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; - /* "numpy.pxd":966 - * baseptr = NULL - * else: - * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< - * baseptr = base - * Py_XDECREF(arr.base) + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" */ - Py_INCREF(__pyx_v_base); + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; - /* "numpy.pxd":967 - * else: - * Py_INCREF(base) # important to do this before decref below! - * baseptr = base # <<<<<<<<<<<<<< - * Py_XDECREF(arr.base) - * arr.base = baseptr + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" */ - __pyx_v_baseptr = ((PyObject *)__pyx_v_base); - } - __pyx_L3:; + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; - /* "numpy.pxd":968 - * Py_INCREF(base) # important to do this before decref below! - * baseptr = base - * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< - * arr.base = baseptr - * + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" */ - Py_XDECREF(__pyx_v_arr->base); + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; - /* "numpy.pxd":969 - * baseptr = base - * Py_XDECREF(arr.base) - * arr.base = baseptr # <<<<<<<<<<<<<< - * - * cdef inline object get_array_base(ndarray arr): + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" */ - __pyx_v_arr->base = __pyx_v_baseptr; + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; - __Pyx_RefNannyFinishContext(); -} + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; -/* "numpy.pxd":971 - * arr.base = baseptr - * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * if arr.base is NULL: - * return None + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base"); + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; - /* "numpy.pxd":972 - * - * cdef inline object get_array_base(ndarray arr): - * if arr.base is NULL: # <<<<<<<<<<<<<< - * return None - * else: + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); - if (__pyx_t_1) { + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; - /* "numpy.pxd":973 - * cdef inline object get_array_base(ndarray arr): - * if arr.base is NULL: - * return None # <<<<<<<<<<<<<< - * else: - * return arr.base + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_None); - __pyx_r = Py_None; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; - /* "numpy.pxd":975 - * return None - * else: - * return arr.base # <<<<<<<<<<<<<< + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); - __pyx_r = ((PyObject *)__pyx_v_arr->base); - goto __pyx_L0; - } - __pyx_L3:; + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction __pyx_vtable_7sklearn_12linear_model_8sgd_fast_LossFunction; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; -static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *p; - PyObject *o = (*t->tp_alloc)(t, 0); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)o); - p->__pyx_vtab = __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction; - return o; -} + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; -static void __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction(PyObject *o) { - (*Py_TYPE(o)->tp_free)(o); -} + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; -static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_LossFunction[] = { - {__Pyx_NAMESTR("loss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss)}, - {__Pyx_NAMESTR("dloss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_12LossFunction_1dloss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_12linear_model_8sgd_fast_12LossFunction_1dloss)}, - {0, 0, 0, 0} -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: -static PyNumberMethods __pyx_tp_as_number_LossFunction = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } -static PySequenceMethods __pyx_tp_as_sequence_LossFunction = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; -static PyMappingMethods __pyx_tp_as_mapping_LossFunction = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + } + /*else*/ { -static PyBufferProcs __pyx_tp_as_buffer_LossFunction = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); -static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_LossFunction = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.linear_model.sgd_fast.LossFunction"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_LossFunction, /*tp_as_number*/ - &__pyx_tp_as_sequence_LossFunction, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_LossFunction, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_LossFunction, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Base class for convex loss functions"), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Regression __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Regression; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; -static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Regression(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *p; - PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression; - return o; -} + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; -static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_Regression[] = { - {__Pyx_NAMESTR("loss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_10Regression_loss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("dloss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_10Regression_1dloss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {0, 0, 0, 0} -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< + * info.format + _buffer_format_string_len, + * &offset) + */ + __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_7; -static PyNumberMethods __pyx_tp_as_number_Regression = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } -static PySequenceMethods __pyx_tp_as_sequence_Regression = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ -static PyMappingMethods __pyx_tp_as_mapping_Regression = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} -static PyBufferProcs __pyx_tp_as_buffer_Regression = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ -static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_Regression = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.linear_model.sgd_fast.Regression"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_Regression, /*tp_as_number*/ - &__pyx_tp_as_sequence_Regression, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_Regression, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_Regression, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Base class for loss functions for regression"), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_12linear_model_8sgd_fast_Regression, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Regression, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Classification __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Classification; +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); -static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Classification(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *p; - PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification; - return o; + /* function exit code */ + __Pyx_RefNannyFinishContext(); } -static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_Classification[] = { - {__Pyx_NAMESTR("loss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_14Classification_loss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("dloss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_14Classification_1dloss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {0, 0, 0, 0} -}; +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); -static PyNumberMethods __pyx_tp_as_number_Classification = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { -static PySequenceMethods __pyx_tp_as_sequence_Classification = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; -static PyMappingMethods __pyx_tp_as_mapping_Classification = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { -static PyBufferProcs __pyx_tp_as_buffer_Classification = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; -static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_Classification = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.linear_model.sgd_fast.Classification"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_Classification, /*tp_as_number*/ - &__pyx_tp_as_sequence_Classification, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_Classification, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_Classification, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Base class for loss functions for classification"), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_12linear_model_8sgd_fast_Classification, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Classification, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_ModifiedHuber __pyx_vtable_7sklearn_12linear_model_8sgd_fast_ModifiedHuber; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ -static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_ModifiedHuber(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *p; - PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *)o); - p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_ModifiedHuber; - return o; + /* function exit code */ + __Pyx_RefNannyFinishContext(); } -static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_ModifiedHuber[] = { - {__Pyx_NAMESTR("loss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("dloss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_1dloss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_2__reduce__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {0, 0, 0, 0} -}; - -static PyNumberMethods __pyx_tp_as_number_ModifiedHuber = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; - -static PySequenceMethods __pyx_tp_as_sequence_ModifiedHuber = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ -static PyMappingMethods __pyx_tp_as_mapping_ModifiedHuber = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); -static PyBufferProcs __pyx_tp_as_buffer_ModifiedHuber = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; -static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.linear_model.sgd_fast.ModifiedHuber"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_ModifiedHuber, /*tp_as_number*/ - &__pyx_tp_as_sequence_ModifiedHuber, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_ModifiedHuber, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_ModifiedHuber, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Modified Huber loss for binary classification with y in {-1, 1}\n\n This is equivalent to quadratically smoothed SVM with gamma = 2.\n\n See T. Zhang 'Solving Large Scale Linear Prediction Problems Using\n Stochastic Gradient Descent', ICML'04.\n "), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_12linear_model_8sgd_fast_ModifiedHuber, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_ModifiedHuber, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Hinge __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Hinge; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ -static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Hinge(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *p; - PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *)o); - p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Hinge; - return o; + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; } -static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_Hinge[] = { - {__Pyx_NAMESTR("loss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_1loss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("dloss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_2dloss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge_3__reduce__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {0, 0, 0, 0} -}; +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ -static PyNumberMethods __pyx_tp_as_number_Hinge = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); -static PySequenceMethods __pyx_tp_as_sequence_Hinge = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; -static PyMappingMethods __pyx_tp_as_mapping_Hinge = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ -static PyBufferProcs __pyx_tp_as_buffer_Hinge = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} -static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.linear_model.sgd_fast.Hinge"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_Hinge, /*tp_as_number*/ - &__pyx_tp_as_sequence_Hinge, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_Hinge, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_Hinge, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Hinge loss for binary classification tasks with y in {-1,1}\n\n Parameters\n ----------\n\n threshold : float > 0.0\n Margin threshold. When threshold=1.0, one gets the loss used by SVM.\n When threshold=0.0, one gets the loss used by the Perceptron.\n "), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_12linear_model_8sgd_fast_Hinge, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Hinge___init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Hinge, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Log __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Log; +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ -static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Log(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *p; - PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *)o); - p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Log; - return o; +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; } -static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_Log[] = { - {__Pyx_NAMESTR("loss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_loss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("dloss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_1dloss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_3Log_2__reduce__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {0, 0, 0, 0} -}; +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ -static PyNumberMethods __pyx_tp_as_number_Log = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); -static PySequenceMethods __pyx_tp_as_sequence_Log = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; -static PyMappingMethods __pyx_tp_as_mapping_Log = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ -static PyBufferProcs __pyx_tp_as_buffer_Log = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} -static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_Log = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.linear_model.sgd_fast.Log"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_Log, /*tp_as_number*/ - &__pyx_tp_as_sequence_Log, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_Log, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_Log, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Logistic regression loss for binary classification with y in {-1, 1}"), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_12linear_model_8sgd_fast_Log, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Log, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredLoss __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredLoss; +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ -static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_SquaredLoss(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *p; - PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *)o); - p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredLoss; - return o; -} +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); -static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_SquaredLoss[] = { - {__Pyx_NAMESTR("loss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_loss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("dloss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_1dloss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_2__reduce__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {0, 0, 0, 0} -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; -static PyNumberMethods __pyx_tp_as_number_SquaredLoss = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ -static PySequenceMethods __pyx_tp_as_sequence_SquaredLoss = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} -static PyMappingMethods __pyx_tp_as_mapping_SquaredLoss = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ -static PyBufferProcs __pyx_tp_as_buffer_SquaredLoss = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + long __pyx_t_8; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); -static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.linear_model.sgd_fast.SquaredLoss"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_SquaredLoss, /*tp_as_number*/ - &__pyx_tp_as_sequence_SquaredLoss, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_SquaredLoss, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_SquaredLoss, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Squared loss traditional used in linear regression."), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_12linear_model_8sgd_fast_SquaredLoss, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_SquaredLoss, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Huber __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Huber; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; -static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Huber(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *p; - PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *)o); - p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Huber; - return o; -} + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); -static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_Huber[] = { - {__Pyx_NAMESTR("loss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_1loss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("dloss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_2dloss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber_3__reduce__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {0, 0, 0, 0} -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); + __pyx_t_3 = 0; -static PyNumberMethods __pyx_tp_as_number_Huber = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; -static PySequenceMethods __pyx_tp_as_sequence_Huber = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); + __pyx_t_4 = 0; -static PyMappingMethods __pyx_tp_as_mapping_Huber = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_Huber = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; - -static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_Huber = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.linear_model.sgd_fast.Huber"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_Huber, /*tp_as_number*/ - &__pyx_tp_as_sequence_Huber, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_Huber, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_Huber, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Huber regression loss\n\n Variant of the SquaredLoss that is robust to outliers (quadratic near zero,\n linear in for large errors).\n\n http://en.wikipedia.org/wiki/Huber_Loss_Function\n "), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_12linear_model_8sgd_fast_Huber, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pf_7sklearn_12linear_model_8sgd_fast_5Huber___init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Huber, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive __pyx_vtable_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; - -static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *p; - PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *)o); - p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; - return o; -} - -static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive[] = { - {__Pyx_NAMESTR("loss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_1loss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("dloss"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_2dloss, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_3__reduce__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {0, 0, 0, 0} -}; - -static PyNumberMethods __pyx_tp_as_number_EpsilonInsensitive = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; - -static PySequenceMethods __pyx_tp_as_sequence_EpsilonInsensitive = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_EpsilonInsensitive = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_EpsilonInsensitive = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; - -static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.linear_model.sgd_fast.EpsilonInsensitive"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_EpsilonInsensitive, /*tp_as_number*/ - &__pyx_tp_as_sequence_EpsilonInsensitive, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_EpsilonInsensitive, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_EpsilonInsensitive, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Epsilon-Insensitive loss (used by SVR).\n\n loss = max(0, |y - p| - epsilon)\n "), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pf_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive___init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; - -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - __Pyx_NAMESTR("sgd_fast"), - 0, /* m_doc */ - -1, /* m_size */ - __pyx_methods /* m_methods */, - NULL, /* m_reload */ - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 0}, - {&__pyx_kp_u_10, __pyx_k_10, sizeof(__pyx_k_10), 0, 1, 0, 0}, - {&__pyx_kp_u_12, __pyx_k_12, sizeof(__pyx_k_12), 0, 1, 0, 0}, - {&__pyx_kp_u_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 1, 0, 0}, - {&__pyx_kp_u_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 1, 0, 0}, - {&__pyx_n_s_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 0, 1, 1}, - {&__pyx_kp_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 0}, - {&__pyx_kp_s_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 0, 1, 0}, - {&__pyx_kp_s_4, __pyx_k_4, sizeof(__pyx_k_4), 0, 0, 1, 0}, - {&__pyx_kp_u_6, __pyx_k_6, sizeof(__pyx_k_6), 0, 1, 0, 0}, - {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, - {&__pyx_n_s__NotImplementedError, __pyx_k__NotImplementedError, sizeof(__pyx_k__NotImplementedError), 0, 0, 1, 1}, - {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__alpha, __pyx_k__alpha, sizeof(__pyx_k__alpha), 0, 0, 1, 1}, - {&__pyx_n_s__any, __pyx_k__any, sizeof(__pyx_k__any), 0, 0, 1, 1}, - {&__pyx_n_s__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 0, 1, 1}, - {&__pyx_n_s__dataset, __pyx_k__dataset, sizeof(__pyx_k__dataset), 0, 0, 1, 1}, - {&__pyx_n_s__dloss, __pyx_k__dloss, sizeof(__pyx_k__dloss), 0, 0, 1, 1}, - {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, - {&__pyx_n_s__epsilon, __pyx_k__epsilon, sizeof(__pyx_k__epsilon), 0, 0, 1, 1}, - {&__pyx_n_s__eta0, __pyx_k__eta0, sizeof(__pyx_k__eta0), 0, 0, 1, 1}, - {&__pyx_n_s__fit_intercept, __pyx_k__fit_intercept, sizeof(__pyx_k__fit_intercept), 0, 0, 1, 1}, - {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, - {&__pyx_n_s__intercept, __pyx_k__intercept, sizeof(__pyx_k__intercept), 0, 0, 1, 1}, - {&__pyx_n_s__intercept_decay, __pyx_k__intercept_decay, sizeof(__pyx_k__intercept_decay), 0, 0, 1, 1}, - {&__pyx_n_s__isinf, __pyx_k__isinf, sizeof(__pyx_k__isinf), 0, 0, 1, 1}, - {&__pyx_n_s__isnan, __pyx_k__isnan, sizeof(__pyx_k__isnan), 0, 0, 1, 1}, - {&__pyx_n_s__learning_rate, __pyx_k__learning_rate, sizeof(__pyx_k__learning_rate), 0, 0, 1, 1}, - {&__pyx_n_s__loss, __pyx_k__loss, sizeof(__pyx_k__loss), 0, 0, 1, 1}, - {&__pyx_n_s__n_iter, __pyx_k__n_iter, sizeof(__pyx_k__n_iter), 0, 0, 1, 1}, - {&__pyx_n_s__nonzero, __pyx_k__nonzero, sizeof(__pyx_k__nonzero), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__order, __pyx_k__order, sizeof(__pyx_k__order), 0, 0, 1, 1}, - {&__pyx_n_s__p, __pyx_k__p, sizeof(__pyx_k__p), 0, 0, 1, 1}, - {&__pyx_n_s__penalty_type, __pyx_k__penalty_type, sizeof(__pyx_k__penalty_type), 0, 0, 1, 1}, - {&__pyx_n_s__plain_sgd, __pyx_k__plain_sgd, sizeof(__pyx_k__plain_sgd), 0, 0, 1, 1}, - {&__pyx_n_s__power_t, __pyx_k__power_t, sizeof(__pyx_k__power_t), 0, 0, 1, 1}, - {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__rho, __pyx_k__rho, sizeof(__pyx_k__rho), 0, 0, 1, 1}, - {&__pyx_n_s__seed, __pyx_k__seed, sizeof(__pyx_k__seed), 0, 0, 1, 1}, - {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, - {&__pyx_n_s__shuffle, __pyx_k__shuffle, sizeof(__pyx_k__shuffle), 0, 0, 1, 1}, - {&__pyx_n_s__sys, __pyx_k__sys, sizeof(__pyx_k__sys), 0, 0, 1, 1}, - {&__pyx_n_s__t, __pyx_k__t, sizeof(__pyx_k__t), 0, 0, 1, 1}, - {&__pyx_n_s__threshold, __pyx_k__threshold, sizeof(__pyx_k__threshold), 0, 0, 1, 1}, - {&__pyx_n_s__time, __pyx_k__time, sizeof(__pyx_k__time), 0, 0, 1, 1}, - {&__pyx_n_s__verbose, __pyx_k__verbose, sizeof(__pyx_k__verbose), 0, 0, 1, 1}, - {&__pyx_n_s__weight_neg, __pyx_k__weight_neg, sizeof(__pyx_k__weight_neg), 0, 0, 1, 1}, - {&__pyx_n_s__weight_pos, __pyx_k__weight_pos, sizeof(__pyx_k__weight_pos), 0, 0, 1, 1}, - {&__pyx_n_s__weights, __pyx_k__weights, sizeof(__pyx_k__weights), 0, 0, 1, 1}, - {&__pyx_n_s__y, __pyx_k__y, sizeof(__pyx_k__y), 0, 0, 1, 1}, - {&__pyx_n_s__zeros, __pyx_k__zeros, sizeof(__pyx_k__zeros), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_NotImplementedError = __Pyx_GetName(__pyx_b, __pyx_n_s__NotImplementedError); if (!__pyx_builtin_NotImplementedError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - return 0; - __pyx_L1_error:; - return -1; -} - -static int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); - - /* "sklearn/linear_model/sgd_fast.pyx":423 - * if np.any(np.isinf(weights)) or np.any(np.isnan(weights)) \ - * or np.isnan(intercept) or np.isinf(intercept): - * raise ValueError("floating-point under-/overflow occured.") # <<<<<<<<<<<<<< + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":798 + * child, new_offset = fields * - * w.reset_wscale() - */ - __pyx_k_tuple_5 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_5)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_4)); - PyTuple_SET_ITEM(__pyx_k_tuple_5, 0, ((PyObject *)__pyx_kp_s_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); - - /* "numpy.pxd":211 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_7 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_7)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_6)); - PyTuple_SET_ITEM(__pyx_k_tuple_7, 0, ((PyObject *)__pyx_kp_u_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); + if (__pyx_t_6) { - /* "numpy.pxd":215 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":799 * - * info.buf = PyArray_DATA(self) + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_9)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") */ - __pyx_k_tuple_11 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_11)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_10)); - PyTuple_SET_ITEM(__pyx_k_tuple_11, 0, ((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (!__pyx_t_7) { + goto __pyx_L8_next_or; + } else { + } + __pyx_t_7 = (__pyx_v_little_endian != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_L8_next_or:; - /* "numpy.pxd":795 - * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython */ - __pyx_k_tuple_14 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_14)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_13)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, ((PyObject *)__pyx_kp_u_13)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_13)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L7_bool_binop_done:; + if (__pyx_t_6) { - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_15 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_15)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_10)); - PyTuple_SET_ITEM(__pyx_k_tuple_15, 0, ((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "numpy.pxd":819 - * t = child.type_num - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":813 * - * # Until ticket #99 is fixed, use integers to avoid warnings + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 */ - __pyx_k_tuple_17 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_17)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_17)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_16)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 0, ((PyObject *)__pyx_kp_u_16)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_16)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_17)); - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - return 0; - __pyx_L1_error:; - return -1; -} + while (1) { + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_6) break; -#if PY_MAJOR_VERSION < 3 -PyMODINIT_FUNC initsgd_fast(void); /*proto*/ -PyMODINIT_FUNC initsgd_fast(void) -#else -PyMODINIT_FUNC PyInit_sgd_fast(void); /*proto*/ -PyMODINIT_FUNC PyInit_sgd_fast(void) -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - __Pyx_RefNannyDeclarations - #if CYTHON_REFNANNY - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); - if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); - } - #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_sgd_fast(void)"); - if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __pyx_binding_PyCFunctionType_USED - if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #endif - /*--- Module creation code ---*/ - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("sgd_fast"), __pyx_methods, 0, 0, PYTHON_API_VERSION); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); - #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - /*--- Initialize various global constants etc. ---*/ - if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_module_is_main_sklearn__linear_model__sgd_fast) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - } - /*--- Builtin init code ---*/ - if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Constants init code ---*/ - if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Global init code ---*/ - /*--- Variable export code ---*/ - /*--- Function export code ---*/ - /*--- Type init code ---*/ - __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_LossFunction; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_LossFunction.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_LossFunction.dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_12LossFunction_dloss; - if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_LossFunction) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_LossFunction.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "LossFunction", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_LossFunction) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_12linear_model_8sgd_fast_LossFunction = &__pyx_type_7sklearn_12linear_model_8sgd_fast_LossFunction; - __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_Regression; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Regression.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Regression.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_10Regression_loss; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Regression.__pyx_base.dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_10Regression_dloss; - __pyx_type_7sklearn_12linear_model_8sgd_fast_Regression.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_LossFunction; - if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_Regression) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_Regression.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "Regression", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_Regression) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Regression = &__pyx_type_7sklearn_12linear_model_8sgd_fast_Regression; - __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_Classification; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Classification.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Classification.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_14Classification_loss; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Classification.__pyx_base.dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_14Classification_dloss; - __pyx_type_7sklearn_12linear_model_8sgd_fast_Classification.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_LossFunction; - if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_Classification) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_Classification.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "Classification", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_Classification) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Classification = &__pyx_type_7sklearn_12linear_model_8sgd_fast_Classification; - __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_ModifiedHuber = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_ModifiedHuber; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_ModifiedHuber.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_ModifiedHuber.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_ModifiedHuber.__pyx_base.__pyx_base.dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_dloss; - __pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Classification; - if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_ModifiedHuber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "ModifiedHuber", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_12linear_model_8sgd_fast_ModifiedHuber = &__pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber; - __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Hinge = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_Hinge; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Hinge.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Hinge.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge_loss; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Hinge.__pyx_base.__pyx_base.dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge_dloss; - __pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Classification; - if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Hinge) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "Hinge", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Hinge = &__pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge; - __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Log = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_Log; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Log.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Log.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_loss; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Log.__pyx_base.__pyx_base.dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_dloss; - __pyx_type_7sklearn_12linear_model_8sgd_fast_Log.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Classification; - if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_Log) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_Log.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Log) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "Log", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_Log) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Log = &__pyx_type_7sklearn_12linear_model_8sgd_fast_Log; - __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredLoss = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredLoss; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredLoss.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredLoss.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_loss; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredLoss.__pyx_base.__pyx_base.dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_dloss; - __pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Regression; - if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 192; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredLoss) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 192; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "SquaredLoss", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 192; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredLoss = &__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss; - __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Huber = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_Huber; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Huber.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Huber.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber_loss; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Huber.__pyx_base.__pyx_base.dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber_dloss; - __pyx_type_7sklearn_12linear_model_8sgd_fast_Huber.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Regression; - if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_Huber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_Huber.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Huber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "Huber", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_Huber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Huber = &__pyx_type_7sklearn_12linear_model_8sgd_fast_Huber; - __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_loss; - __pyx_vtable_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive.__pyx_base.__pyx_base.dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double, int __pyx_skip_dispatch))__pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_dloss; - __pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Regression; - if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "EpsilonInsensitive", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive = &__pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; - /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_5utils_13weight_vector_WeightVector = __Pyx_ImportType("sklearn.utils.weight_vector", "WeightVector", sizeof(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector), 1); if (unlikely(!__pyx_ptype_7sklearn_5utils_13weight_vector_WeightVector)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_vtabptr_7sklearn_5utils_13weight_vector_WeightVector = (struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector*)__Pyx_GetVtable(__pyx_ptype_7sklearn_5utils_13weight_vector_WeightVector->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_5utils_13weight_vector_WeightVector)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset = __Pyx_ImportType("sklearn.utils.seq_dataset", "SequentialDataset", sizeof(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset), 1); if (unlikely(!__pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset = (struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset*)__Pyx_GetVtable(__pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_5utils_11seq_dataset_ArrayDataset = __Pyx_ImportType("sklearn.utils.seq_dataset", "ArrayDataset", sizeof(struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset), 1); if (unlikely(!__pyx_ptype_7sklearn_5utils_11seq_dataset_ArrayDataset)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset = (struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset*)__Pyx_GetVtable(__pyx_ptype_7sklearn_5utils_11seq_dataset_ArrayDataset->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_5utils_11seq_dataset_CSRDataset = __Pyx_ImportType("sklearn.utils.seq_dataset", "CSRDataset", sizeof(struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset), 1); if (unlikely(!__pyx_ptype_7sklearn_5utils_11seq_dataset_CSRDataset)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset = (struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_CSRDataset*)__Pyx_GetVtable(__pyx_ptype_7sklearn_5utils_11seq_dataset_CSRDataset->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Variable import code ---*/ - /*--- Function import code ---*/ - /*--- Execution code ---*/ + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; - /* "sklearn/linear_model/sgd_fast.pyx":11 + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< * - * import numpy as np # <<<<<<<<<<<<<< - * import sys - * from time import time + * offset[0] += child.itemsize */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); + } - /* "sklearn/linear_model/sgd_fast.pyx":12 + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":818 + * offset[0] += 1 * - * import numpy as np - * import sys # <<<<<<<<<<<<<< - * from time import time + * offset[0] += child.itemsize # <<<<<<<<<<<<<< * + * if not PyDataType_HASFIELDS(child): */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__sys), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__sys, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); - /* "sklearn/linear_model/sgd_fast.pyx":13 - * import numpy as np - * import sys - * from time import time # <<<<<<<<<<<<<< + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_6) { + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":821 * - * cimport numpy as np + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__time)); - PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s__time)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__time)); - __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s__time), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__time); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__time, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; - /* "sklearn/linear_model/sgd_fast.pyx":267 + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") * + */ + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_6) { + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * - * def plain_sgd(np.ndarray[DOUBLE, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< - * double intercept, - * LossFunction loss, + * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_8sgd_fast_plain_sgd, NULL, __pyx_n_s_18); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__plain_sgd, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L15; + } + /*else*/ { + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L15:; + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + /*else*/ { + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + } + __pyx_L13:; + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":968 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":969 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":971 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":972 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":973 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":974 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":977 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":978 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + /*else*/ { + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":980 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction __pyx_vtable_7sklearn_12linear_model_8sgd_fast_LossFunction; + +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction; + return o; +} + +static void __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction(PyObject *o) { + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + (*Py_TYPE(o)->tp_free)(o); +} + +static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_LossFunction[] = { + {"dloss", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_12LossFunction_1dloss, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_12linear_model_8sgd_fast_12LossFunction_dloss}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_LossFunction = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.sgd_fast.LossFunction", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Base class for convex loss functions", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Regression __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Regression; + +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Regression(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *p; + PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression; + return o; +} + +static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_Regression = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.sgd_fast.Regression", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Regression), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Base class for loss functions for regression", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Regression, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Classification __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Classification; + +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Classification(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *p; + PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification; + return o; +} + +static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_Classification = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.sgd_fast.Classification", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Classification), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Base class for loss functions for classification", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Classification, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_ModifiedHuber __pyx_vtable_7sklearn_12linear_model_8sgd_fast_ModifiedHuber; + +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_ModifiedHuber(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *p; + PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Classification(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_ModifiedHuber; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_ModifiedHuber[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_1__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.sgd_fast.ModifiedHuber", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_ModifiedHuber), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Modified Huber loss for binary classification with y in {-1, 1}\n\n This is equivalent to quadratically smoothed SVM with gamma = 2.\n\n See T. Zhang 'Solving Large Scale Linear Prediction Problems Using\n Stochastic Gradient Descent', ICML'04.\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_12linear_model_8sgd_fast_ModifiedHuber, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_ModifiedHuber, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Hinge __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Hinge; + +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Hinge(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *p; + PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Classification(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Hinge; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_Hinge[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_5Hinge_3__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.sgd_fast.Hinge", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Hinge), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Hinge loss for binary classification tasks with y in {-1,1}\n\n Parameters\n ----------\n\n threshold : float > 0.0\n Margin threshold. When threshold=1.0, one gets the loss used by SVM.\n When threshold=0.0, one gets the loss used by the Perceptron.\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_12linear_model_8sgd_fast_Hinge, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_12linear_model_8sgd_fast_5Hinge_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Hinge, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredHinge __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredHinge; + +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_SquaredHinge(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *p; + PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_LossFunction(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredHinge; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_SquaredHinge[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_3__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredHinge = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.sgd_fast.SquaredHinge", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredHinge), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Squared Hinge loss for binary classification tasks with y in {-1,1}\n\n Parameters\n ----------\n\n threshold : float > 0.0\n Margin threshold. When threshold=1.0, one gets the loss used by\n (quadratically penalized) SVM.\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_12linear_model_8sgd_fast_SquaredHinge, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_SquaredHinge, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Log __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Log; + +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Log(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *p; + PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Classification(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Log; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_Log[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_3Log_1__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_Log = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.sgd_fast.Log", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Log), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Logistic regression loss for binary classification with y in {-1, 1}", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_12linear_model_8sgd_fast_Log, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Log, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredLoss __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredLoss; + +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_SquaredLoss(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *p; + PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Regression(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredLoss; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_SquaredLoss[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_1__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.sgd_fast.SquaredLoss", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredLoss), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Squared loss traditional used in linear regression.", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_12linear_model_8sgd_fast_SquaredLoss, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_SquaredLoss, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_Huber __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Huber; + +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Huber(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *p; + PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Regression(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Huber; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_Huber[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_5Huber_3__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_Huber = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.sgd_fast.Huber", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_Huber), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Huber regression loss\n\n Variant of the SquaredLoss that is robust to outliers (quadratic near zero,\n linear in for large errors).\n\n http://en.wikipedia.org/wiki/Huber_Loss_Function\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_12linear_model_8sgd_fast_Huber, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_12linear_model_8sgd_fast_5Huber_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Huber, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive __pyx_vtable_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; + +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *p; + PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Regression(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_3__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.sgd_fast.EpsilonInsensitive", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Epsilon-Insensitive loss (used by SVR).\n\n loss = max(0, |y - p| - epsilon)\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive; + +static PyObject *__pyx_tp_new_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *p; + PyObject *o = __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_Regression(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_12linear_model_8sgd_fast_LossFunction*)__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_3__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.linear_model.sgd_fast.SquaredEpsilonInsensitive", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_12linear_model_8sgd_fast_LossFunction, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Epsilon-Insensitive loss.\n\n loss = max(0, |y - p| - epsilon)^2\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + "sgd_fast", + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_n_s_C, __pyx_k_C, sizeof(__pyx_k_C), 0, 0, 1, 1}, + {&__pyx_kp_s_Epoch_d, __pyx_k_Epoch_d, sizeof(__pyx_k_Epoch_d), 0, 0, 1, 0}, + {&__pyx_kp_s_Floating_point_under_overflow_oc, __pyx_k_Floating_point_under_overflow_oc, sizeof(__pyx_k_Floating_point_under_overflow_oc), 0, 0, 1, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_n_s_MAX_DLOSS, __pyx_k_MAX_DLOSS, sizeof(__pyx_k_MAX_DLOSS), 0, 0, 1, 1}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_kp_s_Norm_2f_NNZs_d_Bias_6f_T_d_Avg_l, __pyx_k_Norm_2f_NNZs_d_Bias_6f_T_d_Avg_l, sizeof(__pyx_k_Norm_2f_NNZs_d_Bias_6f_T_d_Avg_l), 0, 0, 1, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_kp_s_Total_training_time_2f_seconds, __pyx_k_Total_training_time_2f_seconds, sizeof(__pyx_k_Total_training_time_2f_seconds), 0, 0, 1, 0}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s__7, __pyx_k__7, sizeof(__pyx_k__7), 0, 0, 1, 1}, + {&__pyx_n_s_alpha, __pyx_k_alpha, sizeof(__pyx_k_alpha), 0, 0, 1, 1}, + {&__pyx_n_s_average, __pyx_k_average, sizeof(__pyx_k_average), 0, 0, 1, 1}, + {&__pyx_n_s_average_intercept, __pyx_k_average_intercept, sizeof(__pyx_k_average_intercept), 0, 0, 1, 1}, + {&__pyx_n_s_average_sgd, __pyx_k_average_sgd, sizeof(__pyx_k_average_sgd), 0, 0, 1, 1}, + {&__pyx_n_s_average_weights, __pyx_k_average_weights, sizeof(__pyx_k_average_weights), 0, 0, 1, 1}, + {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, + {&__pyx_n_s_class_weight, __pyx_k_class_weight, sizeof(__pyx_k_class_weight), 0, 0, 1, 1}, + {&__pyx_n_s_count, __pyx_k_count, sizeof(__pyx_k_count), 0, 0, 1, 1}, + {&__pyx_n_s_dataset, __pyx_k_dataset, sizeof(__pyx_k_dataset), 0, 0, 1, 1}, + {&__pyx_n_s_dloss, __pyx_k_dloss, sizeof(__pyx_k_dloss), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_end, __pyx_k_end, sizeof(__pyx_k_end), 0, 0, 1, 1}, + {&__pyx_n_s_epoch, __pyx_k_epoch, sizeof(__pyx_k_epoch), 0, 0, 1, 1}, + {&__pyx_n_s_epsilon, __pyx_k_epsilon, sizeof(__pyx_k_epsilon), 0, 0, 1, 1}, + {&__pyx_n_s_eta, __pyx_k_eta, sizeof(__pyx_k_eta), 0, 0, 1, 1}, + {&__pyx_n_s_eta0, __pyx_k_eta0, sizeof(__pyx_k_eta0), 0, 0, 1, 1}, + {&__pyx_n_s_file, __pyx_k_file, sizeof(__pyx_k_file), 0, 0, 1, 1}, + {&__pyx_n_s_fit_intercept, __pyx_k_fit_intercept, sizeof(__pyx_k_fit_intercept), 0, 0, 1, 1}, + {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 0, 0, 1, 1}, + {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_infinity, __pyx_k_infinity, sizeof(__pyx_k_infinity), 0, 0, 1, 1}, + {&__pyx_n_s_initial_eta0, __pyx_k_initial_eta0, sizeof(__pyx_k_initial_eta0), 0, 0, 1, 1}, + {&__pyx_n_s_intercept, __pyx_k_intercept, sizeof(__pyx_k_intercept), 0, 0, 1, 1}, + {&__pyx_n_s_intercept_decay, __pyx_k_intercept_decay, sizeof(__pyx_k_intercept_decay), 0, 0, 1, 1}, + {&__pyx_n_s_is_hinge, __pyx_k_is_hinge, sizeof(__pyx_k_is_hinge), 0, 0, 1, 1}, + {&__pyx_n_s_l1_ratio, __pyx_k_l1_ratio, sizeof(__pyx_k_l1_ratio), 0, 0, 1, 1}, + {&__pyx_n_s_learning_rate, __pyx_k_learning_rate, sizeof(__pyx_k_learning_rate), 0, 0, 1, 1}, + {&__pyx_n_s_loss, __pyx_k_loss, sizeof(__pyx_k_loss), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_n_features, __pyx_k_n_features, sizeof(__pyx_k_n_features), 0, 0, 1, 1}, + {&__pyx_n_s_n_iter, __pyx_k_n_iter, sizeof(__pyx_k_n_iter), 0, 0, 1, 1}, + {&__pyx_n_s_n_samples, __pyx_k_n_samples, sizeof(__pyx_k_n_samples), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_nonzero, __pyx_k_nonzero, sizeof(__pyx_k_nonzero), 0, 0, 1, 1}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_optimal_init, __pyx_k_optimal_init, sizeof(__pyx_k_optimal_init), 0, 0, 1, 1}, + {&__pyx_n_s_order, __pyx_k_order, sizeof(__pyx_k_order), 0, 0, 1, 1}, + {&__pyx_n_s_p, __pyx_k_p, sizeof(__pyx_k_p), 0, 0, 1, 1}, + {&__pyx_n_s_penalty_type, __pyx_k_penalty_type, sizeof(__pyx_k_penalty_type), 0, 0, 1, 1}, + {&__pyx_n_s_plain_sgd, __pyx_k_plain_sgd, sizeof(__pyx_k_plain_sgd), 0, 0, 1, 1}, + {&__pyx_n_s_plain_sgd_2, __pyx_k_plain_sgd_2, sizeof(__pyx_k_plain_sgd_2), 0, 0, 1, 1}, + {&__pyx_n_s_power_t, __pyx_k_power_t, sizeof(__pyx_k_power_t), 0, 0, 1, 1}, + {&__pyx_n_s_print, __pyx_k_print, sizeof(__pyx_k_print), 0, 0, 1, 1}, + {&__pyx_n_s_ps_ptr, __pyx_k_ps_ptr, sizeof(__pyx_k_ps_ptr), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_n_s_q, __pyx_k_q, sizeof(__pyx_k_q), 0, 0, 1, 1}, + {&__pyx_n_s_q_data_ptr, __pyx_k_q_data_ptr, sizeof(__pyx_k_q_data_ptr), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_sample_weight, __pyx_k_sample_weight, sizeof(__pyx_k_sample_weight), 0, 0, 1, 1}, + {&__pyx_n_s_seed, __pyx_k_seed, sizeof(__pyx_k_seed), 0, 0, 1, 1}, + {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, + {&__pyx_n_s_shuffle, __pyx_k_shuffle, sizeof(__pyx_k_shuffle), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_linear_model_sgd_fast, __pyx_k_sklearn_linear_model_sgd_fast, sizeof(__pyx_k_sklearn_linear_model_sgd_fast), 0, 0, 1, 1}, + {&__pyx_n_s_sqrt, __pyx_k_sqrt, sizeof(__pyx_k_sqrt), 0, 0, 1, 1}, + {&__pyx_n_s_standard_intercept, __pyx_k_standard_intercept, sizeof(__pyx_k_standard_intercept), 0, 0, 1, 1}, + {&__pyx_n_s_standard_weights, __pyx_k_standard_weights, sizeof(__pyx_k_standard_weights), 0, 0, 1, 1}, + {&__pyx_n_s_sumloss, __pyx_k_sumloss, sizeof(__pyx_k_sumloss), 0, 0, 1, 1}, + {&__pyx_n_s_sys, __pyx_k_sys, sizeof(__pyx_k_sys), 0, 0, 1, 1}, + {&__pyx_n_s_t, __pyx_k_t, sizeof(__pyx_k_t), 0, 0, 1, 1}, + {&__pyx_n_s_t_start, __pyx_k_t_start, sizeof(__pyx_k_t_start), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_threshold, __pyx_k_threshold, sizeof(__pyx_k_threshold), 0, 0, 1, 1}, + {&__pyx_n_s_time, __pyx_k_time, sizeof(__pyx_k_time), 0, 0, 1, 1}, + {&__pyx_n_s_typw, __pyx_k_typw, sizeof(__pyx_k_typw), 0, 0, 1, 1}, + {&__pyx_n_s_u, __pyx_k_u, sizeof(__pyx_k_u), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, + {&__pyx_n_s_verbose, __pyx_k_verbose, sizeof(__pyx_k_verbose), 0, 0, 1, 1}, + {&__pyx_kp_s_volatile_ogrisel_code_scikit_le, __pyx_k_volatile_ogrisel_code_scikit_le, sizeof(__pyx_k_volatile_ogrisel_code_scikit_le), 0, 0, 1, 0}, + {&__pyx_n_s_w, __pyx_k_w, sizeof(__pyx_k_w), 0, 0, 1, 1}, + {&__pyx_n_s_w_ptr, __pyx_k_w_ptr, sizeof(__pyx_k_w_ptr), 0, 0, 1, 1}, + {&__pyx_n_s_weight_neg, __pyx_k_weight_neg, sizeof(__pyx_k_weight_neg), 0, 0, 1, 1}, + {&__pyx_n_s_weight_pos, __pyx_k_weight_pos, sizeof(__pyx_k_weight_pos), 0, 0, 1, 1}, + {&__pyx_n_s_weights, __pyx_k_weights, sizeof(__pyx_k_weights), 0, 0, 1, 1}, + {&__pyx_n_s_x_data_ptr, __pyx_k_x_data_ptr, sizeof(__pyx_k_x_data_ptr), 0, 0, 1, 1}, + {&__pyx_n_s_x_ind_ptr, __pyx_k_x_ind_ptr, sizeof(__pyx_k_x_ind_ptr), 0, 0, 1, 1}, + {&__pyx_n_s_xnnz, __pyx_k_xnnz, sizeof(__pyx_k_xnnz), 0, 0, 1, 1}, + {&__pyx_n_s_y, __pyx_k_y, sizeof(__pyx_k_y), 0, 0, 1, 1}, + {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + + /* "sklearn/linear_model/sgd_fast.pyx":331 + * + * + * def plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * double intercept, + * LossFunction loss, + */ + __pyx_tuple__8 = PyTuple_Pack(23, __pyx_n_s_weights, __pyx_n_s_intercept, __pyx_n_s_loss, __pyx_n_s_penalty_type, __pyx_n_s_alpha, __pyx_n_s_C, __pyx_n_s_l1_ratio, __pyx_n_s_dataset, __pyx_n_s_n_iter, __pyx_n_s_fit_intercept, __pyx_n_s_verbose, __pyx_n_s_shuffle, __pyx_n_s_seed, __pyx_n_s_weight_pos, __pyx_n_s_weight_neg, __pyx_n_s_learning_rate, __pyx_n_s_eta0, __pyx_n_s_power_t, __pyx_n_s_t, __pyx_n_s_intercept_decay, __pyx_n_s_standard_weights, __pyx_n_s_standard_intercept, __pyx_n_s__7); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + __pyx_codeobj__9 = (PyObject*)__Pyx_PyCode_New(20, 0, 23, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__8, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_volatile_ogrisel_code_scikit_le, __pyx_n_s_plain_sgd_2, 331, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/linear_model/sgd_fast.pyx":424 + * + * + * def average_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * double intercept, + * np.ndarray[double, ndim=1, mode='c'] average_weights, + */ + __pyx_tuple__10 = PyTuple_Pack(23, __pyx_n_s_weights, __pyx_n_s_intercept, __pyx_n_s_average_weights, __pyx_n_s_average_intercept, __pyx_n_s_loss, __pyx_n_s_penalty_type, __pyx_n_s_alpha, __pyx_n_s_C, __pyx_n_s_l1_ratio, __pyx_n_s_dataset, __pyx_n_s_n_iter, __pyx_n_s_fit_intercept, __pyx_n_s_verbose, __pyx_n_s_shuffle, __pyx_n_s_seed, __pyx_n_s_weight_pos, __pyx_n_s_weight_neg, __pyx_n_s_learning_rate, __pyx_n_s_eta0, __pyx_n_s_power_t, __pyx_n_s_t, __pyx_n_s_intercept_decay, __pyx_n_s_average); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + __pyx_codeobj__11 = (PyObject*)__Pyx_PyCode_New(23, 0, 23, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__10, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_volatile_ogrisel_code_scikit_le, __pyx_n_s_average_sgd, 424, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/linear_model/sgd_fast.pyx":529 + * + * + * def _plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * double intercept, + * np.ndarray[double, ndim=1, mode='c'] average_weights, + */ + __pyx_tuple__12 = PyTuple_Pack(52, __pyx_n_s_weights, __pyx_n_s_intercept, __pyx_n_s_average_weights, __pyx_n_s_average_intercept, __pyx_n_s_loss, __pyx_n_s_penalty_type, __pyx_n_s_alpha, __pyx_n_s_C, __pyx_n_s_l1_ratio, __pyx_n_s_dataset, __pyx_n_s_n_iter, __pyx_n_s_fit_intercept, __pyx_n_s_verbose, __pyx_n_s_shuffle, __pyx_n_s_seed, __pyx_n_s_weight_pos, __pyx_n_s_weight_neg, __pyx_n_s_learning_rate, __pyx_n_s_eta0, __pyx_n_s_power_t, __pyx_n_s_t, __pyx_n_s_intercept_decay, __pyx_n_s_average, __pyx_n_s_n_samples, __pyx_n_s_n_features, __pyx_n_s_w, __pyx_n_s_w_ptr, __pyx_n_s_x_data_ptr, __pyx_n_s_x_ind_ptr, __pyx_n_s_ps_ptr, __pyx_n_s_infinity, __pyx_n_s_xnnz, __pyx_n_s_eta, __pyx_n_s_p, __pyx_n_s_update, __pyx_n_s_sumloss, __pyx_n_s_y, __pyx_n_s_sample_weight, __pyx_n_s_class_weight, __pyx_n_s_count, __pyx_n_s_epoch, __pyx_n_s_i, __pyx_n_s_is_hinge, __pyx_n_s_optimal_init, __pyx_n_s_dloss, __pyx_n_s_MAX_DLOSS, __pyx_n_s_q, __pyx_n_s_q_data_ptr, __pyx_n_s_u, __pyx_n_s_typw, __pyx_n_s_initial_eta0, __pyx_n_s_t_start); if (unlikely(!__pyx_tuple__12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + __pyx_codeobj__13 = (PyObject*)__Pyx_PyCode_New(23, 0, 52, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__12, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_volatile_ogrisel_code_scikit_le, __pyx_n_s_plain_sgd, 529, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_float_1_0 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_float_1_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC initsgd_fast(void); /*proto*/ +PyMODINIT_FUNC initsgd_fast(void) +#else +PyMODINIT_FUNC PyInit_sgd_fast(void); /*proto*/ +PyMODINIT_FUNC PyInit_sgd_fast(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_sgd_fast(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4("sgd_fast", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__linear_model__sgd_fast) { + if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.linear_model.sgd_fast")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.linear_model.sgd_fast", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_LossFunction; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_LossFunction.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_12LossFunction_loss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_LossFunction._dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_12LossFunction__dloss; + if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_LossFunction) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_12linear_model_8sgd_fast_LossFunction.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_LossFunction.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "LossFunction", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_LossFunction) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_12linear_model_8sgd_fast_LossFunction = &__pyx_type_7sklearn_12linear_model_8sgd_fast_LossFunction; + __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_Regression; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Regression.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Regression.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_10Regression_loss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Regression.__pyx_base._dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_10Regression__dloss; + __pyx_type_7sklearn_12linear_model_8sgd_fast_Regression.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_LossFunction; + if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_Regression) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_12linear_model_8sgd_fast_Regression.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_Regression.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "Regression", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_Regression) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Regression = &__pyx_type_7sklearn_12linear_model_8sgd_fast_Regression; + __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_Classification; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Classification.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Classification.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_14Classification_loss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Classification.__pyx_base._dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_14Classification__dloss; + __pyx_type_7sklearn_12linear_model_8sgd_fast_Classification.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_LossFunction; + if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_Classification) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_12linear_model_8sgd_fast_Classification.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_Classification.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "Classification", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_Classification) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Classification = &__pyx_type_7sklearn_12linear_model_8sgd_fast_Classification; + __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_ModifiedHuber = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_ModifiedHuber; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_ModifiedHuber.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_ModifiedHuber.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber_loss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_ModifiedHuber.__pyx_base.__pyx_base._dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_13ModifiedHuber__dloss; + __pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Classification; + if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_ModifiedHuber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "ModifiedHuber", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_12linear_model_8sgd_fast_ModifiedHuber = &__pyx_type_7sklearn_12linear_model_8sgd_fast_ModifiedHuber; + __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Hinge = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_Hinge; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Hinge.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Hinge.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge_loss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Hinge.__pyx_base.__pyx_base._dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_5Hinge__dloss; + __pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Classification; + if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Hinge) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "Hinge", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Hinge = &__pyx_type_7sklearn_12linear_model_8sgd_fast_Hinge; + __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredHinge = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredHinge; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredHinge.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_LossFunction; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredHinge.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_12SquaredHinge_loss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredHinge.__pyx_base._dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_12SquaredHinge__dloss; + __pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredHinge.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_LossFunction; + if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredHinge) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredHinge.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredHinge.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredHinge) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "SquaredHinge", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredHinge) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredHinge = &__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredHinge; + __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Log = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_Log; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Log.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Classification; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Log.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_3Log_loss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Log.__pyx_base.__pyx_base._dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_3Log__dloss; + __pyx_type_7sklearn_12linear_model_8sgd_fast_Log.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Classification; + if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_Log) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_12linear_model_8sgd_fast_Log.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_Log.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Log) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "Log", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_Log) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Log = &__pyx_type_7sklearn_12linear_model_8sgd_fast_Log; + __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredLoss = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredLoss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredLoss.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredLoss.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_11SquaredLoss_loss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredLoss.__pyx_base.__pyx_base._dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_11SquaredLoss__dloss; + __pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Regression; + if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredLoss) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "SquaredLoss", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredLoss = &__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredLoss; + __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Huber = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_Huber; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Huber.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Huber.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber_loss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_Huber.__pyx_base.__pyx_base._dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_5Huber__dloss; + __pyx_type_7sklearn_12linear_model_8sgd_fast_Huber.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Regression; + if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_Huber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_12linear_model_8sgd_fast_Huber.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_Huber.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Huber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "Huber", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_Huber) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Huber = &__pyx_type_7sklearn_12linear_model_8sgd_fast_Huber; + __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive_loss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive.__pyx_base.__pyx_base._dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_18EpsilonInsensitive__dloss; + __pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Regression; + if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "EpsilonInsensitive", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive = &__pyx_type_7sklearn_12linear_model_8sgd_fast_EpsilonInsensitive; + __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive = &__pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive.__pyx_base = *__pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_Regression; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive.__pyx_base.__pyx_base.loss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive_loss; + __pyx_vtable_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive.__pyx_base.__pyx_base._dloss = (double (*)(struct __pyx_obj_7sklearn_12linear_model_8sgd_fast_LossFunction *, double, double))__pyx_f_7sklearn_12linear_model_8sgd_fast_25SquaredEpsilonInsensitive__dloss; + __pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive.tp_base = __pyx_ptype_7sklearn_12linear_model_8sgd_fast_Regression; + if (PyType_Ready(&__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive.tp_dict, __pyx_vtabptr_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "SquaredEpsilonInsensitive", (PyObject *)&__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive = &__pyx_type_7sklearn_12linear_model_8sgd_fast_SquaredEpsilonInsensitive; + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_5utils_13weight_vector_WeightVector = __Pyx_ImportType("sklearn.utils.weight_vector", "WeightVector", sizeof(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector), 1); if (unlikely(!__pyx_ptype_7sklearn_5utils_13weight_vector_WeightVector)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_5utils_13weight_vector_WeightVector = (struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector*)__Pyx_GetVtable(__pyx_ptype_7sklearn_5utils_13weight_vector_WeightVector->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_5utils_13weight_vector_WeightVector)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset = __Pyx_ImportType("sklearn.utils.seq_dataset", "SequentialDataset", sizeof(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset), 1); if (unlikely(!__pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset = (struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset*)__Pyx_GetVtable(__pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_5utils_11seq_dataset_ArrayDataset = __Pyx_ImportType("sklearn.utils.seq_dataset", "ArrayDataset", sizeof(struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset), 1); if (unlikely(!__pyx_ptype_7sklearn_5utils_11seq_dataset_ArrayDataset)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset = (struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset*)__Pyx_GetVtable(__pyx_ptype_7sklearn_5utils_11seq_dataset_ArrayDataset->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_5utils_11seq_dataset_CSRDataset = __Pyx_ImportType("sklearn.utils.seq_dataset", "CSRDataset", sizeof(struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset), 1); if (unlikely(!__pyx_ptype_7sklearn_5utils_11seq_dataset_CSRDataset)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset = (struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_CSRDataset*)__Pyx_GetVtable(__pyx_ptype_7sklearn_5utils_11seq_dataset_CSRDataset->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/linear_model/sgd_fast.pyx":13 + * + * + * import numpy as np # <<<<<<<<<<<<<< + * import sys + * from time import time + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/linear_model/sgd_fast.pyx":14 + * + * import numpy as np + * import sys # <<<<<<<<<<<<<< + * from time import time + * + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_sys, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_sys, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/linear_model/sgd_fast.pyx":15 + * import numpy as np + * import sys + * from time import time # <<<<<<<<<<<<<< + * + * cimport cython + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s_time); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_time); + __Pyx_GIVEREF(__pyx_n_s_time); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_time, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_time); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_time, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/linear_model/sgd_fast.pyx":26 + * from sklearn.utils.seq_dataset cimport SequentialDataset + * + * np.import_array() # <<<<<<<<<<<<<< + * + * # Penalty constants + */ + import_array(); + + /* "sklearn/linear_model/sgd_fast.pyx":331 + * + * + * def plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * double intercept, + * LossFunction loss, + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_8sgd_fast_1plain_sgd, NULL, __pyx_n_s_sklearn_linear_model_sgd_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_plain_sgd_2, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/linear_model/sgd_fast.pyx":424 + * + * + * def average_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * double intercept, + * np.ndarray[double, ndim=1, mode='c'] average_weights, + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_8sgd_fast_3average_sgd, NULL, __pyx_n_s_sklearn_linear_model_sgd_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_average_sgd, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/linear_model/sgd_fast.pyx":529 + * + * + * def _plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, # <<<<<<<<<<<<<< + * double intercept, + * np.ndarray[double, ndim=1, mode='c'] average_weights, + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_12linear_model_8sgd_fast_5_plain_sgd, NULL, __pyx_n_s_sklearn_linear_model_sgd_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_plain_sgd, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/linear_model/sgd_fast.pyx":1 + * # cython: cdivision=True # <<<<<<<<<<<<<< + * # cython: boundscheck=False + * # cython: wraparound=False + */ + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "../../envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + if (__pyx_d) { + __Pyx_AddTraceback("init sklearn.linear_model.sgd_fast", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.linear_model.sgd_fast"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(PyObject_TypeCheck(obj, type))) return 1; + } + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case '\r': + case '\n': + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; + } + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} - /* "sklearn/linear_model/sgd_fast.pyx":1 - * # encoding: utf-8 # <<<<<<<<<<<<<< - * # cython: cdivision=True - * # cython: boundscheck=False - */ - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (likely(result)) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} - /* "numpy.pxd":971 - * arr.base = baseptr - * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * if arr.base is NULL: - * return None - */ - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - if (__pyx_m) { - __Pyx_AddTraceback("init sklearn.linear_model.sgd_fast", __pyx_clineno, __pyx_lineno, __pyx_filename); - Py_DECREF(__pyx_m); __pyx_m = 0; - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init sklearn.linear_model.sgd_fast"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if PY_MAJOR_VERSION < 3 - return; - #else - return __pyx_m; - #endif +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; } +#endif -/* Runtime support code */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule((char *)modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); } -#endif /* CYTHON_REFNANNY */ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; } } - return result; + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; } static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; @@ -10971,78 +12181,224 @@ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyOb Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif } - static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; } +static void __Pyx_RaiseBufferFallbackError(void) { + PyErr_SetString(PyExc_ValueError, + "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +} -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ - Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = PyCFunction_GET_FUNCTION(func); + self = PyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; + return result; +} +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *result; + PyObject *args = PyTuple_New(1); + if (unlikely(!args)) return NULL; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, arg); + result = __Pyx_PyObject_Call(func, args, NULL); + Py_DECREF(args); + return result; +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { +#ifdef __Pyx_CyFunction_USED + if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { +#else + if (likely(PyCFunction_Check(func))) { +#endif + if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { + return __Pyx_PyObject_CallMethO(func, arg); + } } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; - Py_INCREF(value); + return __Pyx__PyObject_CallOneArg(func, arg); +} +#else +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject* args = PyTuple_Pack(1, arg); + return (likely(args)) ? __Pyx_PyObject_Call(func, args, NULL) : NULL; +} +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { +#ifdef __Pyx_CyFunction_USED + if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { +#else + if (likely(PyCFunction_Check(func))) { +#endif + if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { + return __Pyx_PyObject_CallMethO(func, NULL); + } } - #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) - #else - if (!PyType_Check(type)) - #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { + return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); +} +#endif + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + if (PyType_Check(type)) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - /* Normalize to raise , */ - Py_DECREF(value); value = type; - #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - #endif + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } } - __Pyx_ErrRestore(type, value, tb); return; raise_error: @@ -11051,10 +12407,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tb); return; } - -#else /* Python 3+ */ - +#else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -11064,7 +12419,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } if (value == Py_None) value = 0; - if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, @@ -11073,749 +12427,785 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } - - if (cause) { - PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } - else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } - else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - if (!value) { - value = PyObject_CallObject(type, NULL); - } - PyException_SetCause(value, fixed_cause); - } - - PyErr_SetObject(type, value); - - if (tb) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } - } - -bad: - return; -} -#endif - -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); - #endif -} - -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { - values[name-argnames] = value; + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } + instance_class = NULL; } } } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact) -{ - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; - } - if (none_allowed && obj == Py_None) return 1; - else if (exact) { - if (Py_TYPE(obj) == type) return 1; - } - else { - if (PyObject_TypeCheck(obj, type)) return 1; - } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; -} - -static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { - unsigned int n = 1; - return *(unsigned char*)(&n) != 0; -} - -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; -} __Pyx_BufFmt_Context; - -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type) { - stack[0].field = &ctx->root; - stack[0].parent_offset = 0; - ctx->root.type = type; - ctx->root.name = "buffer dtype"; - ctx->root.offset = 0; - ctx->head = stack; - ctx->head->field = &ctx->root; - ctx->fmt_offset = 0; - ctx->head->parent_offset = 0; - ctx->new_packmode = '@'; - ctx->enc_packmode = '@'; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->is_complex = 0; - while (type->typegroup == 'S') { - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = 0; - type = type->fields->type; - } -} - -static int __Pyx_BufFmt_ParseNumber(const char** ts) { - int count; - const char* t = *ts; - if (*t < '0' || *t > '9') { - return -1; - } else { - count = *t++ - '0'; - while (*t >= '0' && *t < '9') { - count *= 10; - count += *t++ - '0'; - } - } - *ts = t; - return count; -} - -static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { - PyErr_Format(PyExc_ValueError, - "Unexpected format string character: '%c'", ch); -} - -static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { - switch (ch) { - case 'b': return "'char'"; - case 'B': return "'unsigned char'"; - case 'h': return "'short'"; - case 'H': return "'unsigned short'"; - case 'i': return "'int'"; - case 'I': return "'unsigned int'"; - case 'l': return "'long'"; - case 'L': return "'unsigned long'"; - case 'q': return "'long long'"; - case 'Q': return "'unsigned long long'"; - case 'f': return (is_complex ? "'complex float'" : "'float'"); - case 'd': return (is_complex ? "'complex double'" : "'double'"); - case 'g': return (is_complex ? "'complex long double'" : "'long double'"); - case 'T': return "a struct"; - case 'O': return "Python object"; - case 'P': return "a pointer"; - case 0: return "end"; - default: return "unparseable format string"; - } -} - -static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; - case 'h': case 'H': return 2; - case 'i': case 'I': case 'l': case 'L': return 4; - case 'q': case 'Q': return 8; - case 'f': return (is_complex ? 8 : 4); - case 'd': return (is_complex ? 16 : 8); - case 'g': { - PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); - return 0; - } - case 'O': case 'P': return sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if CYTHON_COMPILING_IN_PYPY + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(tmp_type, tmp_value, tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#else + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#endif } +bad: + Py_XDECREF(owned_instance); + return; } +#endif -static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { - switch (ch) { - case 'c': case 'b': case 'B': return 1; - case 'h': case 'H': return sizeof(short); - case 'i': case 'I': return sizeof(int); - case 'l': case 'L': return sizeof(long); - #ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(PY_LONG_LONG); - #endif - case 'f': return sizeof(float) * (is_complex ? 2 : 1); - case 'd': return sizeof(double) * (is_complex ? 2 : 1); - case 'g': return sizeof(long double) * (is_complex ? 2 : 1); - case 'O': case 'P': return sizeof(void*); - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -typedef struct { char c; short x; } __Pyx_st_short; -typedef struct { char c; int x; } __Pyx_st_int; -typedef struct { char c; long x; } __Pyx_st_long; -typedef struct { char c; float x; } __Pyx_st_float; -typedef struct { char c; double x; } __Pyx_st_double; -typedef struct { char c; long double x; } __Pyx_st_longdouble; -typedef struct { char c; void *x; } __Pyx_st_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); #endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; - case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +static void* __Pyx_GetVtable(PyObject *dict) { + void* ptr; + PyObject *ob = PyObject_GetItem(dict, __pyx_n_s_pyx_vtable); + if (!ob) + goto bad; +#if PY_VERSION_HEX >= 0x02070000 + ptr = PyCapsule_GetPointer(ob, 0); +#else + ptr = PyCObject_AsVoidPtr(ob); #endif - case 'f': return sizeof(__Pyx_st_float) - sizeof(float); - case 'd': return sizeof(__Pyx_st_double) - sizeof(double); - case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; } -static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { - switch (ch) { - case 'c': case 'b': case 'h': case 'i': case 'l': case 'q': return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; - case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); - case 'O': return 'O'; - case 'P': return 'P'; - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif } - } + return value; } -static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { - if (ctx->head == NULL || ctx->head->field == &ctx->root) { - const char* expected; - const char* quote; - if (ctx->head == NULL) { - expected = "end"; - quote = ""; - } else { - expected = ctx->head->field->type->name; - quote = "'"; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; } - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected %s%s%s but got %s", - quote, expected, quote, - __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); - } else { - __Pyx_StructField* field = ctx->head->field; - __Pyx_StructField* parent = (ctx->head - 1)->field; - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", - field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), - parent->type->name, field->name); - } -} - -static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { - char group; - size_t size, offset; - if (ctx->enc_type == 0) return 0; - group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); - do { - __Pyx_StructField* field = ctx->head->field; - __Pyx_TypeInfo* type = field->type; - - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { - size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; } else { - size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; } - if (ctx->enc_packmode == '@') { - size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); - size_t align_mod_offset; - if (align_at == 0) return -1; - align_mod_offset = ctx->fmt_offset % align_at; - if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; } - - if (type->size != size || type->typegroup != group) { - if (type->typegroup == 'C' && type->fields != NULL) { - /* special case -- treat as struct rather than complex number */ - size_t parent_offset = ctx->head->parent_offset + field->offset; - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = parent_offset; - continue; - } - - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} - offset = ctx->head->parent_offset + field->offset; - if (ctx->fmt_offset != offset) { - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", - (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); - return -1; +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif } - - ctx->fmt_offset += size; - - --ctx->enc_count; /* Consume from buffer string */ - - /* Done checking, move to next field, pushing or popping struct stack if needed */ - while (1) { - if (field == &ctx->root) { - ctx->head = NULL; - if (ctx->enc_count != 0) { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - break; /* breaks both loops as ctx->enc_count == 0 */ - } - ctx->head->field = ++field; - if (field->type == NULL) { - --ctx->head; - field = ctx->head->field; - continue; - } else if (field->type->typegroup == 'S') { - size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; /* empty struct */ - field = field->type->fields; - ++ctx->head; - ctx->head->field = field; - ctx->head->parent_offset = parent_offset; - break; - } else { - break; - } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; } - } while (ctx->enc_count); - ctx->enc_type = 0; - ctx->is_complex = 0; - return 0; + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + Py_DECREF(obj); + view->obj = NULL; } +#endif -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { - int got_Z = 0; - while (1) { - switch(*ts) { - case 0: - if (ctx->enc_type != 0 && ctx->head == NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - if (ctx->head != NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - return ts; - case ' ': - case 10: - case 13: - ++ts; - break; - case '<': - if (!__Pyx_IsLittleEndian()) { - PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); - return NULL; + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; } - ctx->new_packmode = '='; - ++ts; - break; - case '>': - case '!': - if (__Pyx_IsLittleEndian()) { - PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); - return NULL; + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif } - ctx->new_packmode = '='; - ++ts; - break; - case '=': - case '@': - case '^': - ctx->new_packmode = *ts++; - break; - case 'T': /* substruct */ - { - const char* ts_after_sub; - size_t i, struct_count = ctx->new_count; - ctx->new_count = 1; - ++ts; - if (*ts != '{') { - PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); - return NULL; - } - ++ts; - ts_after_sub = ts; - for (i = 0; i != struct_count; ++i) { - ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); - if (!ts_after_sub) return NULL; - } - ts = ts_after_sub; + } +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ + { \ + func_type value = func_value; \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + if (is_unsigned && unlikely(value < zero)) \ + goto raise_neg_overflow; \ + else \ + goto raise_overflow; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; } - break; - case '}': /* end of substruct; either repeat or move on */ - ++ts; - return ts; - case 'x': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->fmt_offset += ctx->new_count; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->enc_packmode = ctx->new_packmode; - ++ts; - break; - case 'Z': - got_Z = 1; - ++ts; - if (*ts != 'f' && *ts != 'd' && *ts != 'g') { - __Pyx_BufFmt_RaiseUnexpectedChar('Z'); - return NULL; - } /* fall through */ - case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': - case 'l': case 'L': case 'q': case 'Q': - case 'f': case 'd': case 'g': - case 'O': - if (ctx->enc_type == *ts && got_Z == ctx->is_complex && - ctx->enc_packmode == ctx->new_packmode) { - /* Continue pooling same type */ - ctx->enc_count += ctx->new_count; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } } else { - /* New type */ - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong(x)) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong(x)) + } } - ++ts; - ctx->new_count = 1; - got_Z = 0; - break; - case ':': - ++ts; - while(*ts != ':') ++ts; - ++ts; - break; - default: { - int number = __Pyx_BufFmt_ParseNumber(&ts); - if (number == -1) { /* First char was not a digit */ - PyErr_Format(PyExc_ValueError, - "Does not understand character buffer dtype format string ('%c')", *ts); - return NULL; - } - ctx->new_count = (size_t)number; +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; } - } -} - -static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { - buf->buf = NULL; - buf->obj = NULL; - buf->strides = __Pyx_zeros; - buf->shape = __Pyx_zeros; - buf->suboffsets = __Pyx_minusones; -} - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { - if (obj == Py_None || obj == NULL) { - __Pyx_ZeroBuffer(buf); - return 0; - } - buf->buf = NULL; - if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; - if (buf->ndim != nd) { - PyErr_Format(PyExc_ValueError, - "Buffer has wrong number of dimensions (expected %d, got %d)", - nd, buf->ndim); - goto fail; - } - if (!cast) { - __Pyx_BufFmt_Context ctx; - __Pyx_BufFmt_Init(&ctx, stack, dtype); - if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; - } - if ((unsigned)buf->itemsize != dtype->size) { - PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", - buf->itemsize, (buf->itemsize > 1) ? "s" : "", - dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); - goto fail; - } - if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; - return 0; -fail:; - __Pyx_ZeroBuffer(buf); - return -1; +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; } -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { - if (info->buf == NULL) return; - if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; - __Pyx_ReleaseBuffer(info); -} - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; +static CYTHON_INLINE npy_uint32 __Pyx_PyInt_As_npy_uint32(PyObject *x) { + const npy_uint32 neg_one = (npy_uint32) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(npy_uint32) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (npy_uint32) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_uint32, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(npy_uint32) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(npy_uint32) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_uint32, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(npy_uint32, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(npy_uint32) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, long, PyLong_AsLong(x)) + } else if (sizeof(npy_uint32) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + npy_uint32 val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (npy_uint32) -1; + } + } else { + npy_uint32 val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (npy_uint32) -1; + val = __Pyx_PyInt_As_npy_uint32(tmp); + Py_DECREF(tmp); + return val; } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -static void __Pyx_RaiseBufferFallbackError(void) { - PyErr_Format(PyExc_ValueError, - "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); -} - - - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); -} - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to npy_uint32"); + return (npy_uint32) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to npy_uint32"); + return (npy_uint32) -1; } -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_uint32(npy_uint32 value) { + const npy_uint32 neg_one = (npy_uint32) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(npy_uint32) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(npy_uint32) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(npy_uint32) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } } else { - __Pyx_RaiseTooManyValuesError(index); + if (sizeof(npy_uint32) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(npy_uint32) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(npy_uint32), + little, !is_unsigned); } } +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) { + const unsigned int neg_one = (unsigned int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); - else { - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; + if (likely(PyInt_Check(x))) { + if (sizeof(unsigned int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (unsigned int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(unsigned int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(unsigned int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(unsigned int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(unsigned int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyLong_AsLong(x)) + } else if (sizeof(unsigned int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + unsigned int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (unsigned int) -1; + } + } else { + unsigned int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned int) -1; + val = __Pyx_PyInt_As_unsigned_int(tmp); + Py_DECREF(tmp); + return val; } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to unsigned int"); + return (unsigned int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned int"); + return (unsigned int) -1; } -static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject* obj = view->obj; - if (obj) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;} - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray_1__releasebuffer__(obj, view); - Py_DECREF(obj); - view->obj = NULL; - } -} - -#endif - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); - if (!py_import) - goto bad; - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - #if PY_VERSION_HEX >= 0x02050000 { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - } - #else - if (level>0) { - PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); - goto bad; + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); } - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, NULL); - #endif -bad: - Py_XDECREF(empty_list); - Py_XDECREF(py_import); - Py_XDECREF(empty_dict); - return module; } -#if PY_MAJOR_VERSION < 3 +#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION < 3 static PyObject *__Pyx_GetStdout(void) { PyObject *f = PySys_GetObject((char *)"stdout"); if (!f) { @@ -11823,48 +13213,54 @@ static PyObject *__Pyx_GetStdout(void) { } return f; } - static int __Pyx_Print(PyObject* f, PyObject *arg_tuple, int newline) { - PyObject* v; int i; - if (!f) { if (!(f = __Pyx_GetStdout())) return -1; } + Py_INCREF(f); for (i=0; i < PyTuple_GET_SIZE(arg_tuple); i++) { + PyObject* v; if (PyFile_SoftSpace(f, 1)) { if (PyFile_WriteString(" ", f) < 0) - return -1; + goto error; } v = PyTuple_GET_ITEM(arg_tuple, i); if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) - return -1; + goto error; if (PyString_Check(v)) { char *s = PyString_AsString(v); Py_ssize_t len = PyString_Size(v); - if (len > 0 && - isspace(Py_CHARMASK(s[len-1])) && - s[len-1] != ' ') - PyFile_SoftSpace(f, 0); + if (len > 0) { + switch (s[len-1]) { + case ' ': break; + case '\f': case '\r': case '\n': case '\t': case '\v': + PyFile_SoftSpace(f, 0); + break; + default: break; + } + } } } if (newline) { if (PyFile_WriteString("\n", f) < 0) - return -1; + goto error; PyFile_SoftSpace(f, 0); } + Py_DECREF(f); return 0; +error: + Py_DECREF(f); + return -1; } - -#else /* Python 3 has a print function */ - +#else static int __Pyx_Print(PyObject* stream, PyObject *arg_tuple, int newline) { PyObject* kwargs = 0; PyObject* result = 0; PyObject* end_string; if (unlikely(!__pyx_print)) { - __pyx_print = __Pyx_GetAttrString(__pyx_b, "print"); + __pyx_print = PyObject_GetAttr(__pyx_b, __pyx_n_s_print); if (!__pyx_print) return -1; } @@ -11872,13 +13268,13 @@ static int __Pyx_Print(PyObject* stream, PyObject *arg_tuple, int newline) { kwargs = PyDict_New(); if (unlikely(!kwargs)) return -1; - if (unlikely(PyDict_SetItemString(kwargs, "file", stream) < 0)) + if (unlikely(PyDict_SetItem(kwargs, __pyx_n_s_file, stream) < 0)) goto bad; if (!newline) { end_string = PyUnicode_FromStringAndSize(" ", 1); if (unlikely(!end_string)) goto bad; - if (PyDict_SetItemString(kwargs, "end", end_string) < 0) { + if (PyDict_SetItem(kwargs, __pyx_n_s_end, end_string) < 0) { Py_DECREF(end_string); goto bad; } @@ -11892,7 +13288,7 @@ static int __Pyx_Print(PyObject* stream, PyObject *arg_tuple, int newline) { end_string = PyUnicode_FromStringAndSize(" ", 1); if (unlikely(!end_string)) return -1; - if (PyDict_SetItemString(__pyx_print_kwargs, "end", end_string) < 0) { + if (PyDict_SetItem(__pyx_print_kwargs, __pyx_n_s_end, end_string) < 0) { Py_DECREF(end_string); return -1; } @@ -11912,46 +13308,70 @@ static int __Pyx_Print(PyObject* stream, PyObject *arg_tuple, int newline) { Py_XDECREF(kwargs); return -1; } - #endif -#if PY_MAJOR_VERSION < 3 - +#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION < 3 static int __Pyx_PrintOne(PyObject* f, PyObject *o) { if (!f) { if (!(f = __Pyx_GetStdout())) return -1; } + Py_INCREF(f); if (PyFile_SoftSpace(f, 0)) { if (PyFile_WriteString(" ", f) < 0) - return -1; + goto error; } if (PyFile_WriteObject(o, f, Py_PRINT_RAW) < 0) - return -1; + goto error; if (PyFile_WriteString("\n", f) < 0) - return -1; + goto error; + Py_DECREF(f); return 0; - /* the line below is just to avoid compiler - * compiler warnings about unused functions */ +error: + Py_DECREF(f); + return -1; + /* the line below is just to avoid C compiler + * warnings about unused functions */ return __Pyx_Print(f, NULL, 0); } - -#else /* Python 3 has a print function */ - +#else static int __Pyx_PrintOne(PyObject* stream, PyObject *o) { int res; - PyObject* arg_tuple = PyTuple_New(1); + PyObject* arg_tuple = PyTuple_Pack(1, o); if (unlikely(!arg_tuple)) return -1; - Py_INCREF(o); - PyTuple_SET_ITEM(arg_tuple, 0, o); res = __Pyx_Print(stream, arg_tuple, 1); Py_DECREF(arg_tuple); return res; } - #endif +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value) { + const unsigned int neg_one = (unsigned int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(unsigned int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(unsigned int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(unsigned int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(unsigned int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(unsigned int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(unsigned int), + little, !is_unsigned); + } +} + #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { @@ -12169,446 +13589,122 @@ static int __Pyx_PrintOne(PyObject* stream, PyObject *o) { return __Pyx_c_prod(z, a); case 4: z = __Pyx_c_prod(a, a); - return __Pyx_c_prod(z, z); - } - } - if (a.imag == 0) { - if (a.real == 0) { - return a; - } - r = a.real; - theta = 0; - } else { - r = __Pyx_c_abs(a); - theta = atan2(a.imag, a.real); - } - lnr = log(r); - z_r = exp(lnr * b.real - theta * b.imag); - z_theta = theta * b.real + lnr * b.imag; - z.real = z_r * cos(z_theta); - z.imag = z_r * sin(z_theta); - return z; - } - #endif -#endif - -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; - } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; - } - return (unsigned short)val; - } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; - } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; - } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; - } - return (short)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; - } - return (signed char)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; - } - return (signed short)val; - } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; - } - return (signed int)val; - } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)PyLong_AsUnsignedLong(x); - } else { - return (unsigned long)PyLong_AsLong(x); - } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; + return __Pyx_c_prod(z, z); + } } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; } - } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} + #endif +#endif -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; } - return (long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, ((PyLongObject*)x)->ob_digit[0]); } - return (long)PyLong_AsUnsignedLong(x); - } else { - return (long)PyLong_AsLong(x); - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)val; - } else + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; + goto raise_neg_overflow; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong(x)) } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { - return (PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)val; - } else +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong(x)) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong(x)) } - return (signed long)PyLong_AsUnsignedLong(x); - } else { - return (signed long)PyLong_AsLong(x); - } - } else { - signed long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; } - return (signed PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; } } else { - signed PY_LONG_LONG val; + long val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } -} - -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename) { - PyObject *old_exc, *old_val, *old_tb; - PyObject *ctx; - __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); - #if PY_MAJOR_VERSION < 3 - ctx = PyString_FromString(name); - #else - ctx = PyUnicode_FromString(name); - #endif - __Pyx_ErrRestore(old_exc, old_val, old_tb); - if (!ctx) { - PyErr_WriteUnraisable(Py_None); - } else { - PyErr_WriteUnraisable(ctx); - Py_DECREF(ctx); - } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; } static int __Pyx_check_binary_version(void) { @@ -12621,31 +13717,27 @@ static int __Pyx_check_binary_version(void) { "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); - #if PY_VERSION_HEX < 0x02050000 - return PyErr_Warn(NULL, message); - #else return PyErr_WarnEx(NULL, message, 1); - #endif } return 0; } -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItemString(dict, "__pyx_vtable__", ob) < 0) +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) goto bad; - Py_DECREF(ob); - return 0; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; bad: - Py_XDECREF(ob); - return -1; + Py_XDECREF(py_name); + return 0; } +#endif #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType @@ -12656,15 +13748,14 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(class_name); - #else - py_name = PyUnicode_FromString(class_name); - #endif + py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); @@ -12676,23 +13767,31 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", + "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); - #if PY_VERSION_HEX < 0x02050000 - if (PyErr_Warn(NULL, warning) < 0) goto bad; - #else if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", + "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } @@ -12704,118 +13803,6 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(name); - #else - py_name = PyUnicode_FromString(name); - #endif - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; -} -#endif - -static void* __Pyx_GetVtable(PyObject *dict) { - void* ptr; - PyObject *ob = PyMapping_GetItemString(dict, (char *)"__pyx_vtable__"); - if (!ob) - goto bad; -#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) - ptr = PyCapsule_GetPointer(ob, 0); -#else - ptr = PyCObject_AsVoidPtr(ob); -#endif - if (!ptr && !PyErr_Occurred()) - PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); - Py_DECREF(ob); - return ptr; -bad: - Py_XDECREF(ob); - return NULL; -} - -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); - #else - py_srcfile = PyUnicode_FromString(__pyx_filename); - #endif - if (!py_srcfile) goto bad; - if (__pyx_clineno) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_code = PyCode_New( - 0, /*int argcount,*/ - #if PY_MAJOR_VERSION >= 3 - 0, /*int kwonlyargcount,*/ - #endif - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ - 0, /*int flags,*/ - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - if (!py_code) goto bad; - py_frame = PyFrame_New( - PyThreadState_GET(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - py_globals, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 @@ -12826,7 +13813,7 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } - #else /* Python 3+ has unicode identifiers */ + #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); @@ -12846,26 +13833,88 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else + if (__Pyx_PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif + } else +#endif +#if !CYTHON_COMPILING_IN_PYPY + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -12881,13 +13930,13 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", + "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; @@ -12899,40 +13948,33 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { -#if PY_VERSION_HEX < 0x02050000 - if (ival <= LONG_MAX) - return PyInt_FromLong((long)ival); - else { - unsigned char *bytes = (unsigned char *) &ival; - int one = 1; int little = (int)*(unsigned char*)&one; - return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); - } -#else - return PyInt_FromSize_t(ival); -#endif -} - -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; + return PyInt_FromSize_t(ival); } diff --git a/sklearn/linear_model/sgd_fast.pyx b/sklearn/linear_model/sgd_fast.pyx index ae48e2399d146..3bec5a9f5b3a1 100644 --- a/sklearn/linear_model/sgd_fast.pyx +++ b/sklearn/linear_model/sgd_fast.pyx @@ -1,35 +1,31 @@ -# encoding: utf-8 # cython: cdivision=True # cython: boundscheck=False # cython: wraparound=False # # Author: Peter Prettenhofer +# Mathieu Blondel (partial_fit support) +# Rob Zinkov (passive-aggressive) +# Lars Buitinck # -# License: BSD Style. +# Licence: BSD 3 clause import numpy as np import sys from time import time -cimport numpy as np cimport cython +from libc.math cimport exp, log, sqrt, pow, fabs +cimport numpy as np +cdef extern from "sgd_fast_helpers.h": + bint skl_isfinite(double) nogil from sklearn.utils.weight_vector cimport WeightVector from sklearn.utils.seq_dataset cimport SequentialDataset +np.import_array() -cdef extern from "math.h": - cdef extern double exp(double x) - cdef extern double log(double x) - cdef extern double sqrt(double x) - cdef extern double pow(double x, double y) - -ctypedef np.float64_t DOUBLE -ctypedef np.int32_t INTEGER - - -# Penalty constans +# Penalty constants DEF NO_PENALTY = 0 DEF L1 = 1 DEF L2 = 2 @@ -39,6 +35,8 @@ DEF ELASTICNET = 3 DEF CONSTANT = 1 DEF OPTIMAL = 2 DEF INVSCALING = 3 +DEF PA1 = 4 +DEF PA2 = 5 # ---------------------------------------- # Extension Types for Loss Functions @@ -47,7 +45,7 @@ DEF INVSCALING = 3 cdef class LossFunction: """Base class for convex loss functions""" - cpdef double loss(self, double p, double y): + cdef double loss(self, double p, double y) nogil: """Evaluate the loss function. Parameters @@ -62,9 +60,9 @@ cdef class LossFunction: double The loss evaluated at `p` and `y`. """ - raise NotImplementedError() + return 0. - cpdef double dloss(self, double p, double y): + def dloss(self, double p, double y): """Evaluate the derivative of the loss function with respect to the prediction `p`. @@ -77,29 +75,34 @@ cdef class LossFunction: Returns ------- double - The derivative of the loss function w.r.t. `p`. + The derivative of the loss function with regards to `p`. """ - raise NotImplementedError() + return self._dloss(p, y) + + cdef double _dloss(self, double p, double y) nogil: + # Implementation of dloss; separate function because cpdef and nogil + # can't be combined. + return 0. cdef class Regression(LossFunction): """Base class for loss functions for regression""" - cpdef double loss(self, double p, double y): - raise NotImplementedError() + cdef double loss(self, double p, double y) nogil: + return 0. - cpdef double dloss(self, double p, double y): - raise NotImplementedError() + cdef double _dloss(self, double p, double y) nogil: + return 0. cdef class Classification(LossFunction): """Base class for loss functions for classification""" - cpdef double loss(self, double p, double y): - raise NotImplementedError() + cdef double loss(self, double p, double y) nogil: + return 0. - cpdef double dloss(self, double p, double y): - raise NotImplementedError() + cdef double _dloss(self, double p, double y) nogil: + return 0. cdef class ModifiedHuber(Classification): @@ -110,7 +113,7 @@ cdef class ModifiedHuber(Classification): See T. Zhang 'Solving Large Scale Linear Prediction Problems Using Stochastic Gradient Descent', ICML'04. """ - cpdef double loss(self, double p, double y): + cdef double loss(self, double p, double y) nogil: cdef double z = p * y if z >= 1.0: return 0.0 @@ -119,7 +122,7 @@ cdef class ModifiedHuber(Classification): else: return -4.0 * z - cpdef double dloss(self, double p, double y): + cdef double _dloss(self, double p, double y) nogil: cdef double z = p * y if z >= 1.0: return 0.0 @@ -148,13 +151,13 @@ cdef class Hinge(Classification): def __init__(self, double threshold=1.0): self.threshold = threshold - cpdef double loss(self, double p, double y): + cdef double loss(self, double p, double y) nogil: cdef double z = p * y if z <= self.threshold: return (self.threshold - z) return 0.0 - cpdef double dloss(self, double p, double y): + cdef double _dloss(self, double p, double y) nogil: cdef double z = p * y if z <= self.threshold: return -y @@ -164,10 +167,42 @@ cdef class Hinge(Classification): return Hinge, (self.threshold,) +cdef class SquaredHinge(LossFunction): + """Squared Hinge loss for binary classification tasks with y in {-1,1} + + Parameters + ---------- + + threshold : float > 0.0 + Margin threshold. When threshold=1.0, one gets the loss used by + (quadratically penalized) SVM. + """ + + cdef double threshold + + def __init__(self, double threshold=1.0): + self.threshold = threshold + + cdef double loss(self, double p, double y) 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 z = self.threshold - p * y + if z > 0: + return -2 * y * z + return 0.0 + + def __reduce__(self): + return SquaredHinge, (self.threshold,) + + cdef class Log(Classification): """Logistic regression loss for binary classification with y in {-1, 1}""" - cpdef double loss(self, double p, double y): + cdef double loss(self, double p, double y) nogil: cdef double z = p * y # approximately equal and saves the computation of the log if z > 18: @@ -176,7 +211,7 @@ cdef class Log(Classification): return -z return log(1.0 + exp(-z)) - cpdef double dloss(self, double p, double y): + cdef double _dloss(self, double p, double y) nogil: cdef double z = p * y # approximately equal and saves the computation of the log if z > 18.0: @@ -191,10 +226,10 @@ cdef class Log(Classification): cdef class SquaredLoss(Regression): """Squared loss traditional used in linear regression.""" - cpdef double loss(self, double p, double y): + cdef double loss(self, double p, double y) nogil: return 0.5 * (p - y) * (p - y) - cpdef double dloss(self, double p, double y): + cdef double _dloss(self, double p, double y) nogil: return p - y def __reduce__(self): @@ -215,17 +250,17 @@ cdef class Huber(Regression): def __init__(self, double c): self.c = c - cpdef double loss(self, double p, double y): + cdef double loss(self, double p, double y) nogil: cdef double r = p - y - cdef double abs_r = abs(r) + cdef double abs_r = fabs(r) if abs_r <= self.c: return 0.5 * r * r else: return self.c * abs_r - (0.5 * self.c * self.c) - cpdef double dloss(self, double p, double y): + cdef double _dloss(self, double p, double y) nogil: cdef double r = p - y - cdef double abs_r = abs(r) + cdef double abs_r = fabs(r) if abs_r <= self.c: return r elif r > 0.0: @@ -248,11 +283,11 @@ cdef class EpsilonInsensitive(Regression): def __init__(self, double epsilon): self.epsilon = epsilon - cpdef double loss(self, double p, double y): - cdef double ret = abs(y - p) - self.epsilon + cdef double loss(self, double p, double y) nogil: + cdef double ret = fabs(y - p) - self.epsilon return ret if ret > 0 else 0 - cpdef double dloss(self, double p, double y): + cdef double _dloss(self, double p, double y) nogil: if y - p > self.epsilon: return -1 elif p - y > self.epsilon: @@ -264,14 +299,44 @@ cdef class EpsilonInsensitive(Regression): return EpsilonInsensitive, (self.epsilon,) -def plain_sgd(np.ndarray[DOUBLE, ndim=1, mode='c'] weights, +cdef class SquaredEpsilonInsensitive(Regression): + """Epsilon-Insensitive loss. + + loss = max(0, |y - p| - epsilon)^2 + """ + + cdef double epsilon + + def __init__(self, double epsilon): + self.epsilon = epsilon + + cdef double loss(self, double p, double y) 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 z + z = y - p + if z > self.epsilon: + return -2 * (z - self.epsilon) + elif z < self.epsilon: + return 2 * (-z - self.epsilon) + else: + return 0 + + def __reduce__(self): + return SquaredEpsilonInsensitive, (self.epsilon,) + + +def plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, double intercept, LossFunction loss, int penalty_type, - double alpha, double rho, + double alpha, double C, + double l1_ratio, SequentialDataset dataset, int n_iter, int fit_intercept, - int verbose, int shuffle, int seed, + int verbose, bint shuffle, np.uint32_t seed, double weight_pos, double weight_neg, int learning_rate, double eta0, double power_t, @@ -291,8 +356,11 @@ def plain_sgd(np.ndarray[DOUBLE, ndim=1, mode='c'] weights, The penalty 2 for L2, 1 for L1, and 3 for Elastic-Net. alpha : float The regularization parameter. - rho : float - The elastic net hyperparameter. + C : float + Maximum step size for passive aggressive. + l1_ratio : float + The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. + l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. dataset : SequentialDataset A concrete ``SequentialDataset`` object. n_iter : int @@ -301,20 +369,21 @@ def plain_sgd(np.ndarray[DOUBLE, ndim=1, mode='c'] weights, Whether or not to fit the intercept (1 or 0). verbose : int Print verbose output; 0 for quite. - shuffle : int + shuffle : boolean Whether to shuffle the training data before each epoch. weight_pos : float The weight of the positive class. weight_neg : float The weight of the negative class. - seed : int - The seed of the pseudo random number generator to use when - shuffling the data + seed : np.uint32_t + Seed of the pseudorandom number generator used to shuffle the data. learning_rate : int The learning rate: (1) constant, eta = eta0 - (2) optimal, eta = 1.0/(t+t0) + (2) optimal, eta = 1.0/(alpha * t). (3) inverse scaling, eta = eta0 / pow(t, power_t) + (4) Passive Agressive-I, eta = min(alpha, loss/norm(x)) + (5) Passive Agressive-II, eta = 1.0 / (norm(x) + 0.5*alpha) eta0 : double The initial learning rate. power_t : double @@ -330,113 +399,329 @@ def plain_sgd(np.ndarray[DOUBLE, ndim=1, mode='c'] weights, The fitted weight vector. intercept : float The fitted intercept term. + """ + standard_weights, standard_intercept,\ + _, _ = _plain_sgd(weights, + intercept, + None, + 0, + loss, + penalty_type, + alpha, C, + l1_ratio, + dataset, + n_iter, fit_intercept, + verbose, shuffle, seed, + weight_pos, weight_neg, + learning_rate, eta0, + power_t, + t, + intercept_decay, + 0) + return standard_weights, standard_intercept + + +def average_sgd(np.ndarray[double, ndim=1, mode='c'] weights, + double intercept, + np.ndarray[double, ndim=1, mode='c'] average_weights, + double average_intercept, + LossFunction loss, + int penalty_type, + double alpha, double C, + double l1_ratio, + SequentialDataset dataset, + int n_iter, int fit_intercept, + int verbose, bint shuffle, np.uint32_t seed, + double weight_pos, double weight_neg, + int learning_rate, double eta0, + double power_t, + double t=1.0, + double intercept_decay=1.0, + int average=1): + """Average SGD for generic loss functions and penalties. + Parameters + ---------- + weights : ndarray[double, ndim=1] + The allocated coef_ vector. + intercept : double + The initial intercept. + average_weights : ndarray[double, ndim=1] + The average weights as computed for ASGD + average_intercept : double + The average intercept for ASGD + loss : LossFunction + A concrete ``LossFunction`` object. + penalty_type : int + The penalty 2 for L2, 1 for L1, and 3 for Elastic-Net. + alpha : float + The regularization parameter. + C : float + Maximum step size for passive aggressive. + l1_ratio : float + The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. + l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. + dataset : SequentialDataset + A concrete ``SequentialDataset`` object. + n_iter : int + The number of iterations (epochs). + fit_intercept : int + Whether or not to fit the intercept (1 or 0). + verbose : int + Print verbose output; 0 for quite. + shuffle : boolean + Whether to shuffle the training data before each epoch. + weight_pos : float + The weight of the positive class. + weight_neg : float + The weight of the negative class. + seed : np.uint32_t + Seed of the pseudorandom number generator used to shuffle the data. + learning_rate : int + The learning rate: + (1) constant, eta = eta0 + (2) optimal, eta = 1.0/(alpha * t). + (3) inverse scaling, eta = eta0 / pow(t, power_t) + (4) Passive Agressive-I, eta = min(alpha, loss/norm(x)) + (5) Passive Agressive-II, eta = 1.0 / (norm(x) + 0.5*alpha) + eta0 : double + The initial learning rate. + power_t : double + The exponent for inverse scaling learning rate. + t : double + Initial state of the learning rate. This value is equal to the + iteration count except when the learning rate is set to `optimal`. + Default: 1.0. + average : int + The number of iterations before averaging starts. average=1 is + equivalent to averaging for all iterations. + + Returns + ------- + weights : array, shape=[n_features] + The fitted weight vector. + intercept : float + The fitted intercept term. + average_weights : array shape=[n_features] + The averaged weights accross iterations + average_intercept : float + The averaged intercept accross iterations """ + return _plain_sgd(weights, + intercept, + average_weights, + average_intercept, + loss, + penalty_type, + alpha, C, + l1_ratio, + dataset, + n_iter, fit_intercept, + verbose, shuffle, seed, + weight_pos, weight_neg, + learning_rate, eta0, + power_t, + t, + intercept_decay, + average) + + +def _plain_sgd(np.ndarray[double, ndim=1, mode='c'] weights, + double intercept, + np.ndarray[double, ndim=1, mode='c'] average_weights, + double average_intercept, + LossFunction loss, + int penalty_type, + double alpha, double C, + double l1_ratio, + SequentialDataset dataset, + int n_iter, int fit_intercept, + int verbose, bint shuffle, np.uint32_t seed, + double weight_pos, double weight_neg, + int learning_rate, double eta0, + double power_t, + double t=1.0, + double intercept_decay=1.0, + int average=0): # get the data information into easy vars cdef Py_ssize_t n_samples = dataset.n_samples cdef Py_ssize_t n_features = weights.shape[0] - cdef WeightVector w = WeightVector(weights) + cdef WeightVector w = WeightVector(weights, average_weights) + cdef double* w_ptr = &weights[0] + cdef double *x_data_ptr = NULL + cdef int *x_ind_ptr = NULL + cdef double* ps_ptr = NULL - cdef DOUBLE *x_data_ptr = NULL - cdef INTEGER *x_ind_ptr = NULL - - # helper variable + # helper variables + cdef bint infinity = False cdef int xnnz cdef double eta = 0.0 cdef double p = 0.0 cdef double update = 0.0 cdef double sumloss = 0.0 - cdef DOUBLE y = 0.0 - cdef DOUBLE sample_weight + cdef double y = 0.0 + cdef double sample_weight cdef double class_weight = 1.0 cdef unsigned int count = 0 cdef unsigned int epoch = 0 cdef unsigned int i = 0 + cdef int is_hinge = isinstance(loss, Hinge) + cdef double optimal_init = 0.0 + cdef double dloss = 0.0 + cdef double MAX_DLOSS = 1e12 # q vector is only used for L1 regularization - cdef np.ndarray[DOUBLE, ndim=1, mode="c"] q = None - cdef DOUBLE *q_data_ptr = NULL + cdef np.ndarray[double, ndim = 1, mode = "c"] q = None + cdef double * q_data_ptr = NULL if penalty_type == L1 or penalty_type == ELASTICNET: q = np.zeros((n_features,), dtype=np.float64, order="c") - q_data_ptr = q.data + q_data_ptr = q.data cdef double u = 0.0 if penalty_type == L2: - rho = 1.0 + l1_ratio = 0.0 elif penalty_type == L1: - rho = 0.0 + l1_ratio = 1.0 eta = eta0 - t_start = time() - for epoch in range(n_iter): - if verbose > 0: - print("-- Epoch %d" % (epoch + 1)) - if shuffle: - dataset.shuffle(seed) - for i in range(n_samples): - dataset.next(&x_data_ptr, &x_ind_ptr, &xnnz, &y, - &sample_weight) - - if learning_rate == OPTIMAL: - eta = 1.0 / (alpha * t) - elif learning_rate == INVSCALING: - eta = eta0 / pow(t, power_t) - p = w.dot(x_data_ptr, x_ind_ptr, xnnz) + intercept + if learning_rate == OPTIMAL: + typw = np.sqrt(1.0 / np.sqrt(alpha)) + # computing eta0, the initial learning rate + initial_eta0 = typw / max(1.0, loss.dloss(-typw, 1.0)) + # initialize t such that eta at first sample equals eta0 + optimal_init = 1.0 / (initial_eta0 * alpha) + t_start = time() + with nogil: + for epoch in range(n_iter): if verbose > 0: - sumloss += loss.loss(p, y) - - if y > 0.0: - class_weight = weight_pos - else: - class_weight = weight_neg - - update = eta * loss.dloss(p, y) * class_weight * sample_weight - if update != 0.0: - w.add(x_data_ptr, x_ind_ptr, xnnz, -update) - if fit_intercept == 1: - intercept -= update * intercept_decay - if penalty_type >= L2: - w.scale(1.0 - (rho * eta * alpha)) - - if penalty_type == L1 or penalty_type == ELASTICNET: - u += ((1.0 - rho) * eta * alpha) - l1penalty(w, q_data_ptr, x_ind_ptr, xnnz, u) - t += 1 - count += 1 - - # report epoch information - if verbose > 0: - print("Norm: %.2f, NNZs: %d, "\ - "Bias: %.6f, T: %d, Avg. loss: %.6f" % (w.norm(), - weights.nonzero()[0].shape[0], - intercept, count, - sumloss / count)) - print("Total training time: %.2f seconds." % (time() - t_start)) - - # floating-point under-/overflow check. - if np.any(np.isinf(weights)) or np.any(np.isnan(weights)) \ - or np.isnan(intercept) or np.isinf(intercept): - raise ValueError("floating-point under-/overflow occured.") + with gil: + print("-- Epoch %d" % (epoch + 1)) + if shuffle: + dataset.shuffle(seed) + for i in range(n_samples): + dataset.next(&x_data_ptr, + &x_ind_ptr, + &xnnz, + &y, + &sample_weight) + + p = w.dot(x_data_ptr, x_ind_ptr, xnnz) + intercept + if learning_rate == OPTIMAL: + eta = 1.0 / (alpha * (optimal_init + t - 1)) + elif learning_rate == INVSCALING: + eta = eta0 / pow(t, power_t) + + if verbose > 0: + sumloss += loss.loss(p, y) + + if y > 0.0: + class_weight = weight_pos + else: + class_weight = weight_neg + + if learning_rate == PA1: + update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) + if update == 0: + continue + update = min(C, loss.loss(p, y) / update) + elif learning_rate == PA2: + update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) + update = loss.loss(p, y) / (update + 0.5 / C) + else: + dloss = loss._dloss(p, y) + # clip dloss with large values to avoid numerical + # instabilities + if dloss < -MAX_DLOSS: + dloss = -MAX_DLOSS + elif dloss > MAX_DLOSS: + dloss = MAX_DLOSS + update = -eta * dloss + + if learning_rate >= PA1: + if is_hinge: + # classification + update *= y + elif y - p < 0: + # regression + update *= -1 + + update *= class_weight * sample_weight + + if penalty_type >= L2: + # do not scale to negative values when eta or alpha are too + # big: instead set the weights to zero + w.scale(max(0, 1.0 - ((1.0 - l1_ratio) * eta * alpha))) + if update != 0.0: + w.add(x_data_ptr, x_ind_ptr, xnnz, update) + if fit_intercept == 1: + intercept += update * intercept_decay + + if average > 0 and average <= t: + # compute the average for the intercept and update the + # average weights, this is done regardless as to whether + # the update is 0 + + w.add_average(x_data_ptr, x_ind_ptr, xnnz, + update, (t - average + 1)) + average_intercept += ((intercept - average_intercept) / + (t - average + 1)) + + if penalty_type == L1 or penalty_type == ELASTICNET: + u += (l1_ratio * eta * alpha) + l1penalty(w, q_data_ptr, x_ind_ptr, xnnz, u) + + t += 1 + count += 1 + + # report epoch information + if verbose > 0: + with gil: + print("Norm: %.2f, NNZs: %d, " + "Bias: %.6f, T: %d, Avg. loss: %.6f" + % (w.norm(), weights.nonzero()[0].shape[0], + intercept, count, sumloss / count)) + print("Total training time: %.2f seconds." + % (time() - t_start)) + + # floating-point under-/overflow check. + if (not skl_isfinite(intercept) + or any_nonfinite(weights.data, n_features)): + infinity = True + break + + if infinity: + raise ValueError(("Floating-point under-/overflow occurred at epoch" + " #%d. Scaling input data with StandardScaler or" + " MinMaxScaler might help.") % (epoch + 1)) w.reset_wscale() - return weights, intercept + return weights, intercept, average_weights, average_intercept -cdef inline double max(double a, double b): - return a if a >= b else b +cdef bint any_nonfinite(double *w, int n) nogil: + for i in range(n): + if not skl_isfinite(w[i]): + return True + return 0 -cdef inline double min(double a, double b): - return a if a <= b else b +cdef double sqnorm(double * x_data_ptr, int * x_ind_ptr, int xnnz) nogil: + cdef double x_norm = 0.0 + cdef int j + cdef double z + for j in range(xnnz): + z = x_data_ptr[j] + x_norm += z * z + return x_norm -cdef void l1penalty(WeightVector w, DOUBLE *q_data_ptr, - INTEGER *x_ind_ptr, int xnnz, double u): +cdef void l1penalty(WeightVector w, double * q_data_ptr, + int *x_ind_ptr, int xnnz, double u) nogil: """Apply the L1 penalty to each updated feature This implements the truncated gradient approach by @@ -446,16 +731,16 @@ cdef void l1penalty(WeightVector w, DOUBLE *q_data_ptr, cdef int j = 0 cdef int idx = 0 cdef double wscale = w.wscale - cdef double* w_data_ptr = w.w_data_ptr + cdef double *w_data_ptr = w.w_data_ptr for j in range(xnnz): idx = x_ind_ptr[j] z = w_data_ptr[idx] - if (wscale * w_data_ptr[idx]) > 0.0: + if wscale * w_data_ptr[idx] > 0.0: w_data_ptr[idx] = max( 0.0, w_data_ptr[idx] - ((u + q_data_ptr[idx]) / wscale)) - elif (wscale * w_data_ptr[idx]) < 0.0: + elif wscale * w_data_ptr[idx] < 0.0: w_data_ptr[idx] = min( 0.0, w_data_ptr[idx] + ((u - q_data_ptr[idx]) / wscale)) - q_data_ptr[idx] += (wscale * (w_data_ptr[idx] - z)) + q_data_ptr[idx] += wscale * (w_data_ptr[idx] - z) diff --git a/sklearn/linear_model/sgd_fast_helpers.h b/sklearn/linear_model/sgd_fast_helpers.h new file mode 100644 index 0000000000000..42984c18a3a3f --- /dev/null +++ b/sklearn/linear_model/sgd_fast_helpers.h @@ -0,0 +1,9 @@ +// We cannot directly reuse the npy_isfinite from npy_math.h as numpy +// and scikit-learn are not necessarily built with the same compiler. +#ifdef _MSC_VER +# include +# define skl_isfinite _finite +#else +# include +# define skl_isfinite npy_isfinite +#endif diff --git a/sklearn/linear_model/stochastic_gradient.py b/sklearn/linear_model/stochastic_gradient.py index 1da59543b82d1..77602c80a7470 100644 --- a/sklearn/linear_model/stochastic_gradient.py +++ b/sklearn/linear_model/stochastic_gradient.py @@ -1,34 +1,41 @@ # Authors: Peter Prettenhofer (main author) # Mathieu Blondel (partial_fit support) # -# License: BSD Style. +# License: BSD 3 clause """Classification and regression using Stochastic Gradient Descent (SGD).""" import numpy as np import scipy.sparse as sp +import warnings from abc import ABCMeta, abstractmethod -import warnings from ..externals.joblib import Parallel, delayed -from .base import LinearClassifierMixin +from .base import LinearClassifierMixin, SparseCoefMixin from ..base import BaseEstimator, RegressorMixin -from ..feature_selection.selector_mixin import SelectorMixin -from ..utils import array2d, atleast2d_or_csr, check_arrays +from ..feature_selection.from_model import _LearntSelectorMixin +from ..utils import (check_array, check_random_state, check_X_y) from ..utils.extmath import safe_sparse_dot +from ..utils.multiclass import _check_partial_fit_first_call +from ..utils.validation import check_is_fitted +from ..externals import six -from .sgd_fast import plain_sgd as plain_sgd +from .sgd_fast import plain_sgd, average_sgd from ..utils.seq_dataset import ArrayDataset, CSRDataset +from ..utils import compute_class_weight from .sgd_fast import Hinge +from .sgd_fast import SquaredHinge from .sgd_fast import Log from .sgd_fast import ModifiedHuber from .sgd_fast import SquaredLoss from .sgd_fast import Huber from .sgd_fast import EpsilonInsensitive +from .sgd_fast import SquaredEpsilonInsensitive -LEARNING_RATE_TYPES = {"constant": 1, "optimal": 2, "invscaling": 3} +LEARNING_RATE_TYPES = {"constant": 1, "optimal": 2, "invscaling": 3, + "pa1": 4, "pa2": 5} PENALTY_TYPES = {"none": 0, "l2": 2, "l1": 1, "elasticnet": 3} @@ -40,33 +47,38 @@ """Default value of ``epsilon`` parameter. """ -class BaseSGD(BaseEstimator): +class BaseSGD(six.with_metaclass(ABCMeta, BaseEstimator, SparseCoefMixin)): """Base class for SGD classification and regression.""" - __metaclass__ = ABCMeta - - def __init__(self, loss, penalty='l2', alpha=0.0001, - rho=0.85, fit_intercept=True, n_iter=5, shuffle=False, - verbose=0, epsilon=0.1, seed=0, learning_rate="optimal", - eta0=0.0, power_t=0.5, warm_start=False): + def __init__(self, loss, penalty='l2', alpha=0.0001, C=1.0, + l1_ratio=0.15, fit_intercept=True, n_iter=5, shuffle=True, + verbose=0, epsilon=0.1, random_state=None, + learning_rate="optimal", eta0=0.0, power_t=0.5, + warm_start=False, average=False): self.loss = loss self.penalty = penalty self.learning_rate = learning_rate self.epsilon = epsilon self.alpha = alpha - self.rho = rho + self.C = C + self.l1_ratio = l1_ratio self.fit_intercept = fit_intercept self.n_iter = n_iter self.shuffle = shuffle - self.seed = seed + self.random_state = random_state self.verbose = verbose self.eta0 = eta0 self.power_t = power_t self.warm_start = warm_start + self.average = average self._validate_params() self.coef_ = None + + if self.average > 0: + self.standard_coef_ = None + self.average_coef_ = None # iteration count for learning rate schedule # must not be int (e.g. if ``learning_rate=='optimal'``) self.t_ = None @@ -74,6 +86,7 @@ def __init__(self, loss, penalty='l2', alpha=0.0001, def set_params(self, *args, **kwargs): super(BaseSGD, self).set_params(*args, **kwargs) self._validate_params() + return self @abstractmethod def fit(self, X, y): @@ -84,14 +97,14 @@ def _validate_params(self): if not isinstance(self.shuffle, bool): raise ValueError("shuffle must be either True or False") if self.n_iter <= 0: - raise ValueError("n_iter must be greater than zero") - if not (0.0 <= self.rho <= 1.0): - raise ValueError("rho must be in [0, 1]") + raise ValueError("n_iter must be > zero") + if not (0.0 <= self.l1_ratio <= 1.0): + raise ValueError("l1_ratio must be in [0, 1]") if self.alpha < 0.0: - raise ValueError("alpha must be greater than zero") - if self.learning_rate != "optimal": + raise ValueError("alpha must be >= 0") + if self.learning_rate in ("constant", "invscaling"): if self.eta0 <= 0.0: - raise ValueError("eta0 must be greater than 0.0") + raise ValueError("eta0 must be > 0") # raises ValueError if not registered self._get_penalty_type(self.penalty) @@ -100,26 +113,13 @@ def _validate_params(self): if self.loss not in self.loss_functions: raise ValueError("The loss %s is not supported. " % self.loss) - def _init_t(self, loss_function): - """Initialize iteration counter attr ``t_``. - - If ``self.loss=='optimal'`` initialize ``t_`` such that ``eta`` at - first sample equals ``self.eta0``. - """ - self.t_ = 1.0 - if self.learning_rate == "optimal": - typw = np.sqrt(1.0 / np.sqrt(self.alpha)) - # computing eta0, the initial learning rate - eta0 = typw / max(1.0, loss_function.dloss(-typw, 1.0)) - # initialize t such that eta at first sample equals eta0 - self.t_ = 1.0 / (eta0 * self.alpha) - def _get_loss_function(self, loss): """Get concrete ``LossFunction`` object for str ``loss``. """ try: loss_ = self.loss_functions[loss] loss_class, args = loss_[0], loss_[1:] - if loss in ('huber', 'epsilon_insensitive'): + if loss in ('huber', 'epsilon_insensitive', + 'squared_epsilon_insensitive'): args = (self.epsilon, ) return loss_class(*args) except KeyError: @@ -129,7 +129,7 @@ def _get_learning_rate_type(self, learning_rate): try: return LEARNING_RATE_TYPES[learning_rate] except KeyError: - raise ValueError("learning rate %s" + raise ValueError("learning rate %s " "is not supported. " % learning_rate) def _get_penalty_type(self, penalty): @@ -152,15 +152,6 @@ def _validate_sample_weight(self, sample_weight, n_samples): raise ValueError("Shapes of X and sample_weight do not match.") return sample_weight - def _set_coef(self, coef_): - """Make sure that coef_ is fortran-style and 2d. - - Fortran-style memory layout is needed to ensure that computing - the dot product between input ``X`` and ``coef_`` does not trigger - a memory copy. - """ - self.coef_ = np.asfortranarray(array2d(coef_)) - def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None, intercept_init=None): """Allocate mem for parameters; initialize if provided.""" @@ -169,7 +160,7 @@ def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None, if coef_init is not None: coef_init = np.asarray(coef_init, order="C") if coef_init.shape != (n_classes, n_features): - raise ValueError("Provided coef_ does not match dataset. ") + raise ValueError("Provided ``coef_`` does not match dataset. ") self.coef_ = coef_init else: self.coef_ = np.zeros((n_classes, n_features), @@ -179,7 +170,7 @@ def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None, if intercept_init is not None: intercept_init = np.asarray(intercept_init, order="C") if intercept_init.shape != (n_classes, ): - raise ValueError("Provided intercept_init " \ + raise ValueError("Provided intercept_init " "does not match dataset.") self.intercept_ = intercept_init else: @@ -192,28 +183,34 @@ def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None, order="C") coef_init = coef_init.ravel() if coef_init.shape != (n_features,): - raise ValueError("Provided coef_init does not " \ + raise ValueError("Provided coef_init does not " "match dataset.") self.coef_ = coef_init else: - self.coef_ = np.zeros(n_features, dtype=np.float64, order="C") + self.coef_ = np.zeros(n_features, + dtype=np.float64, + order="C") # allocate intercept_ for binary problem if intercept_init is not None: intercept_init = np.asarray(intercept_init, dtype=np.float64) if intercept_init.shape != (1,) and intercept_init.shape != (): - raise ValueError("Provided intercept_init " \ + raise ValueError("Provided intercept_init " "does not match dataset.") self.intercept_ = intercept_init.reshape(1,) else: self.intercept_ = np.zeros(1, dtype=np.float64, order="C") - -def _check_fit_data(X, y): - """Check if shape of input data matches. """ - n_samples, _ = X.shape - if n_samples != y.shape[0]: - raise ValueError("Shapes of X and y do not match.") + # initialize average parameters + if self.average > 0: + self.standard_coef_ = self.coef_ + self.standard_intercept_ = self.intercept_ + self.average_coef_ = np.zeros(self.coef_.shape, + dtype=np.float64, + order="C") + self.average_intercept_ = np.zeros(self.standard_intercept_.shape, + dtype=np.float64, + order="C") def _make_dataset(X, y_i, sample_weight): @@ -231,237 +228,274 @@ def _make_dataset(X, y_i, sample_weight): return dataset, intercept_decay -class SGDClassifier(BaseSGD, LinearClassifierMixin, SelectorMixin): - """Linear model fitted by minimizing a regularized empirical loss with SGD. - - SGD stands for Stochastic Gradient Descent: the gradient of the loss is - estimated each sample at a time and the model is updated along the way with - a decreasing strength schedule (aka learning rate). - - The regularizer is a penalty added to the loss function that shrinks model - parameters towards the zero vector using either the squared euclidean norm - L2 or the absolute norm L1 or a combination of both (Elastic Net). If the - parameter update crosses the 0.0 value because of the regularizer, the - update is truncated to 0.0 to allow for learning sparse models and achieve - online feature selection. - - This implementation works with data represented as dense or sparse arrays - of floating point values for the features. - - Parameters - ---------- - loss : str, 'hinge' or 'log' or 'modified_huber' - The loss function to be used. Defaults to 'hinge'. The hinge loss is - a margin loss used by standard linear SVM models. The 'log' loss is - the loss of logistic regression models and can be used for - probability estimation in binary classifiers. 'modified_huber' - is another smooth loss that brings tolerance to outliers. - - penalty : str, 'l2' or 'l1' or 'elasticnet' - The penalty (aka regularization term) to be used. Defaults to 'l2' - which is the standard regularizer for linear SVM models. 'l1' and - 'elasticnet' migh bring sparsity to the model (feature selection) - not achievable with 'l2'. - - alpha : float - Constant that multiplies the regularization term. Defaults to 0.0001 - - rho : float - The Elastic Net mixing parameter, with 0 < rho <= 1. - Defaults to 0.85. - - fit_intercept: bool - Whether the intercept should be estimated or not. If False, the - data is assumed to be already centered. Defaults to True. - - n_iter: int, optional - The number of passes over the training data (aka epochs). - Defaults to 5. - - shuffle: bool, optional - Whether or not the training data should be shuffled after each epoch. - Defaults to False. - - seed: int, optional - The seed of the pseudo random number generator to use when - shuffling the data. - - verbose: integer, optional - The verbosity level - - n_jobs: integer, optional - The number of CPUs to use to do the OVA (One Versus All, for - multi-class problems) computation. -1 means 'all CPUs'. Defaults - to 1. - - learning_rate : string, optional - The learning rate: - constant: eta = eta0 - optimal: eta = 1.0/(t+t0) [default] - invscaling: eta = eta0 / pow(t, power_t) +def _prepare_fit_binary(est, y, i): + """Initialization for fit_binary. - eta0 : double - The initial learning rate [default 0.01]. + Returns y, coef, intercept. + """ + y_i = np.ones(y.shape, dtype=np.float64, order="C") + y_i[y != est.classes_[i]] = -1.0 + average_intercept = 0 + average_coef = None - power_t : double - The exponent for inverse scaling learning rate [default 0.25]. + if len(est.classes_) == 2: + if not est.average: + coef = est.coef_.ravel() + intercept = est.intercept_[0] + else: + coef = est.standard_coef_.ravel() + intercept = est.standard_intercept_[0] + average_coef = est.average_coef_.ravel() + average_intercept = est.average_intercept_[0] + else: + if not est.average: + coef = est.coef_[i] + intercept = est.intercept_[i] + else: + coef = est.standard_coef_[i] + intercept = est.standard_intercept_[i] + average_coef = est.average_coef_[i] + average_intercept = est.average_intercept_[i] - class_weight : dict, {class_label : weight} or "auto" or None, optional - Preset for the class_weight fit parameter. + return y_i, coef, intercept, average_coef, average_intercept - Weights associated with classes. If not given, all classes - are supposed to have weight one. - The "auto" mode uses the values of y to automatically adjust - weights inversely proportional to class frequencies. +def fit_binary(est, i, X, y, alpha, C, learning_rate, n_iter, + pos_weight, neg_weight, sample_weight): + """Fit a single binary classifier. - warm_start : bool, optional - When set to True, reuse the solution of the previous call to fit as - initialization, otherwise, just erase the previous solution. + The i'th class is considered the "positive" class. + """ + # if average is not true, average_coef, and average_intercept will be + # unused + y_i, coef, intercept, average_coef, average_intercept = \ + _prepare_fit_binary(est, y, i) + assert y_i.shape[0] == y.shape[0] == sample_weight.shape[0] + dataset, intercept_decay = _make_dataset(X, y_i, sample_weight) - Attributes - ---------- - `coef_` : array, shape = [1, n_features] if n_classes == 2 else [n_classes, - n_features] - Weights assigned to the features. + penalty_type = est._get_penalty_type(est.penalty) + learning_rate_type = est._get_learning_rate_type(learning_rate) + + # XXX should have random_state_! + random_state = check_random_state(est.random_state) + # numpy mtrand expects a C long which is a signed 32 bit integer under + # Windows + seed = random_state.randint(0, np.iinfo(np.int32).max) + + if not est.average: + return plain_sgd(coef, intercept, est.loss_function, + penalty_type, alpha, C, est.l1_ratio, + dataset, n_iter, int(est.fit_intercept), + int(est.verbose), int(est.shuffle), seed, + pos_weight, neg_weight, + learning_rate_type, est.eta0, + est.power_t, est.t_, intercept_decay) - `intercept_` : array, shape = [1] if n_classes == 2 else [n_classes] - Constants in decision function. + else: + standard_coef, standard_intercept, average_coef, \ + average_intercept = average_sgd(coef, intercept, average_coef, + average_intercept, + est.loss_function, penalty_type, + alpha, C, est.l1_ratio, dataset, + n_iter, int(est.fit_intercept), + int(est.verbose), int(est.shuffle), + seed, pos_weight, neg_weight, + learning_rate_type, est.eta0, + est.power_t, est.t_, + intercept_decay, + est.average) + + if len(est.classes_) == 2: + est.average_intercept_[0] = average_intercept + else: + est.average_intercept_[i] = average_intercept - Examples - -------- - >>> import numpy as np - >>> from sklearn import linear_model - >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) - >>> Y = np.array([1, 1, 2, 2]) - >>> clf = linear_model.SGDClassifier() - >>> clf.fit(X, Y) - ... #doctest: +NORMALIZE_WHITESPACE - SGDClassifier(alpha=0.0001, class_weight=None, epsilon=0.1, eta0=0.0, - fit_intercept=True, learning_rate='optimal', loss='hinge', - n_iter=5, n_jobs=1, penalty='l2', power_t=0.5, rho=0.85, seed=0, - shuffle=False, verbose=0, warm_start=False) - >>> print(clf.predict([[-0.8, -1]])) - [1] + return standard_coef, standard_intercept - See also - -------- - LinearSVC, LogisticRegression, Perceptron - """ +class BaseSGDClassifier(six.with_metaclass(ABCMeta, BaseSGD, + LinearClassifierMixin)): loss_functions = { "hinge": (Hinge, 1.0), + "squared_hinge": (SquaredHinge, 1.0), "perceptron": (Hinge, 0.0), "log": (Log, ), "modified_huber": (ModifiedHuber, ), "squared_loss": (SquaredLoss, ), "huber": (Huber, DEFAULT_EPSILON), "epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON), + "squared_epsilon_insensitive": (SquaredEpsilonInsensitive, + DEFAULT_EPSILON), } - def __init__(self, loss="hinge", penalty='l2', alpha=0.0001, - rho=0.85, fit_intercept=True, n_iter=5, shuffle=False, - verbose=0, epsilon=DEFAULT_EPSILON, n_jobs=1, seed=0, + @abstractmethod + def __init__(self, loss="hinge", penalty='l2', alpha=0.0001, l1_ratio=0.15, + fit_intercept=True, n_iter=5, shuffle=True, verbose=0, + epsilon=DEFAULT_EPSILON, n_jobs=1, random_state=None, learning_rate="optimal", eta0=0.0, power_t=0.5, - class_weight=None, warm_start=False): - super(SGDClassifier, self).__init__(loss=loss, penalty=penalty, - alpha=alpha, rho=rho, - fit_intercept=fit_intercept, - n_iter=n_iter, shuffle=shuffle, - verbose=verbose, epsilon=epsilon, - seed=seed, - learning_rate=learning_rate, - eta0=eta0, power_t=power_t, - warm_start=warm_start) + class_weight=None, warm_start=False, average=False): + + super(BaseSGDClassifier, self).__init__(loss=loss, penalty=penalty, + alpha=alpha, l1_ratio=l1_ratio, + fit_intercept=fit_intercept, + n_iter=n_iter, shuffle=shuffle, + verbose=verbose, + epsilon=epsilon, + random_state=random_state, + learning_rate=learning_rate, + eta0=eta0, power_t=power_t, + warm_start=warm_start, + average=average) self.class_weight = class_weight self.classes_ = None self.n_jobs = int(n_jobs) - def _set_class_weight(self, class_weight, classes, y): - """Estimate class weights for unbalanced datasets.""" - if class_weight is None or len(class_weight) == 0: - # uniform class weights - weight = np.ones(classes.shape[0], dtype=np.float64, order='C') - elif class_weight == 'auto': - # proportional to the number of samples in the class - weight = np.array([1.0 / np.sum(y == i) for i in classes], - dtype=np.float64, order='C') - weight *= classes.shape[0] / np.sum(weight) - else: - # user-defined dictionary - weight = np.ones(classes.shape[0], dtype=np.float64, order='C') - if not isinstance(class_weight, dict): - raise ValueError("class_weight must be dict, 'auto', or None," - " got: %r" % class_weight) - for c in class_weight: - i = np.searchsorted(classes, c) - if classes[i] != c: - raise ValueError("Class label %d not present." % c) - else: - weight[i] = class_weight[c] - - self._expanded_class_weight = weight - - def _partial_fit(self, X, y, n_iter, classes=None, sample_weight=None, - coef_init=None, intercept_init=None): - X = atleast2d_or_csr(X, dtype=np.float64, order="C") - y = np.asarray(y).ravel() + def _partial_fit(self, X, y, alpha, C, + loss, learning_rate, n_iter, + classes, sample_weight, + coef_init, intercept_init): + X, y = check_X_y(X, y, 'csr', dtype=np.float64, order="C") n_samples, n_features = X.shape - _check_fit_data(X, y) self._validate_params() - - if self.classes_ is None and classes is None: - raise ValueError("classes must be passed on the first call " - "to partial_fit.") - elif classes is not None and self.classes_ is not None: - if not np.all(self.classes_ == np.unique(classes)): - raise ValueError("`classes` is not the same as on last call " - "to partial_fit.") - elif classes is not None: - self.classes_ = classes + _check_partial_fit_first_call(self, classes) n_classes = self.classes_.shape[0] # Allocate datastructures from input arguments - self._set_class_weight(self.class_weight, self.classes_, y) + self._expanded_class_weight = compute_class_weight(self.class_weight, + self.classes_, y) sample_weight = self._validate_sample_weight(sample_weight, n_samples) - if self.coef_ is None: + if self.coef_ is None or coef_init is not None: self._allocate_parameter_mem(n_classes, n_features, coef_init, intercept_init) + elif n_features != self.coef_.shape[-1]: + raise ValueError("Number of features %d does not match previous data %d." + % (n_features, self.coef_.shape[-1])) - self.loss_function = self._get_loss_function(self.loss) + self.loss_function = self._get_loss_function(loss) if self.t_ is None: - self._init_t(self.loss_function) + self.t_ = 1.0 # delegate to concrete training procedure if n_classes > 2: - self._fit_multiclass(X, y, sample_weight, n_iter) + self._fit_multiclass(X, y, alpha=alpha, C=C, + learning_rate=learning_rate, + sample_weight=sample_weight, n_iter=n_iter) elif n_classes == 2: - self._fit_binary(X, y, sample_weight, n_iter) + self._fit_binary(X, y, alpha=alpha, C=C, + learning_rate=learning_rate, + sample_weight=sample_weight, n_iter=n_iter) else: raise ValueError("The number of class labels must be " "greater than one.") - self.t_ += n_iter * n_samples + return self + + def _fit(self, X, y, alpha, C, loss, learning_rate, coef_init=None, + intercept_init=None, sample_weight=None): + if hasattr(self, "classes_"): + self.classes_ = None + + X, y = check_X_y(X, y, 'csr', dtype=np.float64, order="C") + n_samples, n_features = X.shape + + # labels can be encoded as float, int, or string literals + # np.unique sorts in asc order; largest class id is positive class + classes = np.unique(y) + + if self.warm_start and self.coef_ is not None: + if coef_init is None: + coef_init = self.coef_ + if intercept_init is None: + intercept_init = self.intercept_ + else: + self.coef_ = None + self.intercept_ = None + + if self.average > 0: + self.standard_coef_ = self.coef_ + self.standard_intercept_ = self.intercept_ + self.average_coef_ = None + self.average_intercept_ = None + + # Clear iteration count for multiple call to fit. + self.t_ = None + + self._partial_fit(X, y, alpha, C, loss, learning_rate, self.n_iter, + classes, sample_weight, coef_init, intercept_init) return self + def _fit_binary(self, X, y, alpha, C, sample_weight, + learning_rate, n_iter): + """Fit a binary classifier on X and y. """ + coef, intercept = fit_binary(self, 1, X, y, alpha, C, + learning_rate, n_iter, + self._expanded_class_weight[1], + self._expanded_class_weight[0], + sample_weight) + + self.t_ += n_iter * X.shape[0] + + # need to be 2d + if self.average > 0: + if self.average <= self.t_ - 1: + self.coef_ = self.average_coef_.reshape(1, -1) + self.intercept_ = self.average_intercept_ + else: + self.coef_ = self.standard_coef_.reshape(1, -1) + self.standard_intercept_ = np.atleast_1d(intercept) + self.intercept_ = self.standard_intercept_ + else: + self.coef_ = coef.reshape(1, -1) + # intercept is a float, need to convert it to an array of length 1 + self.intercept_ = np.atleast_1d(intercept) + + def _fit_multiclass(self, X, y, alpha, C, learning_rate, + sample_weight, n_iter): + """Fit a multi-class classifier by combining binary classifiers + + Each binary classifier predicts one class versus all others. This + strategy is called OVA: One Versus All. + """ + # Use joblib to fit OvA in parallel. + result = Parallel(n_jobs=self.n_jobs, backend="threading", + verbose=self.verbose)( + delayed(fit_binary)(self, i, X, y, alpha, C, learning_rate, + n_iter, self._expanded_class_weight[i], 1., + sample_weight) + for i in range(len(self.classes_))) + + for i, (_, intercept) in enumerate(result): + self.intercept_[i] = intercept + + self.t_ += n_iter * X.shape[0] + + if self.average > 0: + if self.average <= self.t_ - 1.0: + self.coef_ = self.average_coef_ + self.intercept_ = self.average_intercept_ + else: + self.coef_ = self.standard_coef_ + self.standard_intercept_ = np.atleast_1d(intercept) + self.intercept_ = self.standard_intercept_ + def partial_fit(self, X, y, classes=None, sample_weight=None): """Fit linear model with Stochastic Gradient Descent. Parameters ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] + X : {array-like, sparse matrix}, shape (n_samples, n_features) Subset of the training data - y : numpy array of shape [n_samples] + y : numpy array, shape (n_samples,) Subset of the target values - classes : array, shape = [n_classes] + classes : array, shape (n_classes,) Classes across all calls to partial_fit. Can be obtained by via `np.unique(y_all)`, where y_all is the target vector of the entire dataset. @@ -469,7 +503,7 @@ def partial_fit(self, X, y, classes=None, sample_weight=None): and can be omitted in the subsequent calls. Note that y doesn't need to contain all labels in `classes`. - sample_weight : array-like, shape = [n_samples], optional + sample_weight : array-like, shape (n_samples,), optional Weights applied to individual samples. If not provided, uniform weights are assumed. @@ -477,8 +511,19 @@ def partial_fit(self, X, y, classes=None, sample_weight=None): ------- self : returns an instance of self. """ - return self._partial_fit(X, y, n_iter=1, classes=classes, - sample_weight=sample_weight) + if self.class_weight == 'auto': + raise ValueError("class_weight 'auto' is not supported for " + "partial_fit. In order to use 'auto' weights, " + "use compute_class_weight('auto', classes, y). " + "In place of y you can us a large enough sample " + "of the full training set target to properly " + "estimate the class frequency distributions. " + "Pass the resulting weights as the class_weight " + "parameter.") + return self._partial_fit(X, y, alpha=self.alpha, C=1.0, loss=self.loss, + learning_rate=self.learning_rate, n_iter=1, + classes=classes, sample_weight=sample_weight, + coef_init=None, intercept_init=None) def fit(self, X, y, coef_init=None, intercept_init=None, class_weight=None, sample_weight=None): @@ -486,190 +531,563 @@ def fit(self, X, y, coef_init=None, intercept_init=None, Parameters ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] + X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data - y : numpy array of shape [n_samples] + y : numpy array, shape (n_samples,) Target values - coef_init : array, shape = [n_classes,n_features] - The initial coeffients to warm-start the optimization. + coef_init : array, shape (n_classes, n_features) + The initial coefficients to warm-start the optimization. - intercept_init : array, shape = [n_classes] + intercept_init : array, shape (n_classes,) The initial intercept to warm-start the optimization. - sample_weight : array-like, shape = [n_samples], optional + sample_weight : array-like, shape (n_samples,), optional Weights applied to individual samples. - If not provided, uniform weights are assumed. + If not provided, uniform weights are assumed. These weights will + be multiplied with class_weight (passed through the + contructor) if class_weight is specified Returns ------- self : returns an instance of self. """ if class_weight is not None: - warnings.warn("Using 'class_weight' as a parameter to the 'fit'" - "method is deprecated and will be removed in 0.13. " - "Set it on initialization instead.", - DeprecationWarning, stacklevel=2) + warnings.warn("You are trying to set class_weight through the fit " + "method, which is deprecated and will be removed in" + "v0.17 of scikit-learn. Pass the class_weight into " + "the constructor instead.", DeprecationWarning) + return self._fit(X, y, alpha=self.alpha, C=1.0, + loss=self.loss, learning_rate=self.learning_rate, + coef_init=coef_init, intercept_init=intercept_init, + sample_weight=sample_weight) + + +class SGDClassifier(BaseSGDClassifier, _LearntSelectorMixin): + """Linear classifiers (SVM, logistic regression, a.o.) with SGD training. + + This estimator implements regularized linear models with stochastic + gradient descent (SGD) learning: the gradient of the loss is estimated + each sample at a time and the model is updated along the way with a + decreasing strength schedule (aka learning rate). SGD allows minibatch + (online/out-of-core) learning, see the partial_fit method. + For best results using the default learning rate schedule, the data should + have zero mean and unit variance. - self.class_weight = class_weight + This implementation works with data represented as dense or sparse arrays + of floating point values for the features. The model it fits can be + controlled with the loss parameter; by default, it fits a linear support + vector machine (SVM). - X = atleast2d_or_csr(X, dtype=np.float64, order="C") - n_samples, n_features = X.shape + The regularizer is a penalty added to the loss function that shrinks model + parameters towards the zero vector using either the squared euclidean norm + L2 or the absolute norm L1 or a combination of both (Elastic Net). If the + parameter update crosses the 0.0 value because of the regularizer, the + update is truncated to 0.0 to allow for learning sparse models and achieve + online feature selection. - # labels can be encoded as float, int, or string literals - # np.unique sorts in asc order; largest class id is positive class - classes = np.unique(y) + Parameters + ---------- + loss : str, 'hinge', 'log', 'modified_huber', 'squared_hinge',\ + 'perceptron', or a regression loss: 'squared_loss', 'huber',\ + 'epsilon_insensitive', or 'squared_epsilon_insensitive' + The loss function to be used. Defaults to 'hinge', which gives a + linear SVM. + The 'log' loss gives logistic regression, a probabilistic classifier. + 'modified_huber' is another smooth loss that brings tolerance to + outliers as well as probability estimates. + 'squared_hinge' is like hinge but is quadratically penalized. + 'perceptron' is the linear loss used by the perceptron algorithm. + The other losses are designed for regression but can be useful in + classification as well; see SGDRegressor for a description. + + penalty : str, 'none', 'l2', 'l1', or 'elasticnet' + The penalty (aka regularization term) to be used. Defaults to 'l2' + which is the standard regularizer for linear SVM models. 'l1' and + 'elasticnet' might bring sparsity to the model (feature selection) + not achievable with 'l2'. - if self.warm_start and self.coef_ is not None: - if coef_init is None: - coef_init = self.coef_ - if intercept_init is None: - intercept_init = self.intercept_ - else: - self.coef_ = None - self.intercept_ = None + alpha : float + Constant that multiplies the regularization term. Defaults to 0.0001 - # Clear iteration count for multiple call to fit. - self.t_ = None + l1_ratio : float + The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. + l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. + Defaults to 0.15. + + fit_intercept : bool + Whether the intercept should be estimated or not. If False, the + data is assumed to be already centered. Defaults to True. - self._partial_fit(X, y, self.n_iter, classes, - sample_weight, coef_init, intercept_init) + n_iter : int, optional + The number of passes over the training data (aka epochs). The number + of iterations is set to 1 if using partial_fit. + Defaults to 5. - # fitting is over, we can now transform coef_ to fortran order - # for faster predictions - self._set_coef(self.coef_) + shuffle : bool, optional + Whether or not the training data should be shuffled after each epoch. + Defaults to True. - return self + random_state : int seed, RandomState instance, or None (default) + The seed of the pseudo random number generator to use when + shuffling the data. + + verbose : integer, optional + The verbosity level + + epsilon : float + Epsilon in the epsilon-insensitive loss functions; only if `loss` is + 'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'. + For 'huber', determines the threshold at which it becomes less + important to get the prediction exactly right. + For epsilon-insensitive, any differences between the current prediction + and the correct label are ignored if they are less than this threshold. + + n_jobs : integer, optional + The number of CPUs to use to do the OVA (One Versus All, for + multi-class problems) computation. -1 means 'all CPUs'. Defaults + to 1. + + learning_rate : string, optional + The learning rate schedule: + constant: eta = eta0 + optimal: eta = 1.0 / (t + t0) [default] + invscaling: eta = eta0 / pow(t, power_t) + where t0 is chosen by a heuristic proposed by Leon Bottou. + + eta0 : double + The initial learning rate for the 'constant' or 'invscaling' + schedules. The default value is 0.0 as eta0 is not used by the + default schedule 'optimal'. + + power_t : double + The exponent for inverse scaling learning rate [default 0.5]. + + class_weight : dict, {class_label: weight} or "auto" or None, optional + Preset for the class_weight fit parameter. + + Weights associated with classes. If not given, all classes + are supposed to have weight one. + + The "auto" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies. + + warm_start : bool, optional + When set to True, reuse the solution of the previous call to fit as + initialization, otherwise, just erase the previous solution. + + average : bool or int, optional + When set to True, computes the averaged SGD weights and stores the + result in the ``coef_`` attribute. If set to an int greater than 1, + averaging will begin once the total number of samples seen reaches + average. So average=10 will begin averaging after seeing 10 samples. + + Attributes + ---------- + coef_ : array, shape (1, n_features) if n_classes == 2 else (n_classes,\ + n_features) + Weights assigned to the features. + + intercept_ : array, shape (1,) if n_classes == 2 else (n_classes,) + Constants in decision function. + + Examples + -------- + >>> import numpy as np + >>> from sklearn import linear_model + >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) + >>> Y = np.array([1, 1, 2, 2]) + >>> clf = linear_model.SGDClassifier() + >>> clf.fit(X, Y) + ... #doctest: +NORMALIZE_WHITESPACE + SGDClassifier(alpha=0.0001, average=False, class_weight=None, epsilon=0.1, + eta0=0.0, fit_intercept=True, l1_ratio=0.15, + learning_rate='optimal', loss='hinge', n_iter=5, n_jobs=1, + penalty='l2', power_t=0.5, random_state=None, shuffle=True, + verbose=0, warm_start=False) + >>> print(clf.predict([[-0.8, -1]])) + [1] + + See also + -------- + LinearSVC, LogisticRegression, Perceptron - def predict_proba(self, X): + """ + + def __init__(self, loss="hinge", penalty='l2', alpha=0.0001, l1_ratio=0.15, + fit_intercept=True, n_iter=5, shuffle=True, verbose=0, + epsilon=DEFAULT_EPSILON, n_jobs=1, random_state=None, + learning_rate="optimal", eta0=0.0, power_t=0.5, + class_weight=None, warm_start=False, average=False): + super(SGDClassifier, self).__init__( + loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio, + fit_intercept=fit_intercept, n_iter=n_iter, shuffle=shuffle, + verbose=verbose, epsilon=epsilon, n_jobs=n_jobs, + random_state=random_state, learning_rate=learning_rate, eta0=eta0, + power_t=power_t, class_weight=class_weight, warm_start=warm_start, + average=average) + + def _check_proba(self): + check_is_fitted(self, "t_") + + if self.loss not in ("log", "modified_huber"): + raise AttributeError("probability estimates are not available for" + " loss=%r" % self.loss) + + @property + def predict_proba(self): """Probability estimates. - Probability estimates are only supported for binary classification. + This method is only available for log loss and modified Huber loss. + + Multiclass probability estimates are derived from binary (one-vs.-rest) + estimates by simple normalization, as recommended by Zadrozny and + Elkan. + + Binary probability estimates for loss="modified_huber" are given by + (clip(decision_function(X), -1, 1) + 1) / 2. Parameters ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] + X : {array-like, sparse matrix}, shape (n_samples, n_features) Returns ------- - array, shape = [n_samples, n_classes] + array, shape (n_samples, n_classes) Returns the probability of the sample for each class in the model, - where classes are ordered as they are in self.classes_. + where classes are ordered as they are in `self.classes_`. References ---------- + Zadrozny and Elkan, "Transforming classifier scores into multiclass + probability estimates", SIGKDD'02, + http://www.research.ibm.com/people/z/zadrozny/kdd2002-Transf.pdf The justification for the formula in the loss="modified_huber" case is in the appendix B in: http://jmlr.csail.mit.edu/papers/volume2/zhang02c/zhang02c.pdf """ - if len(self.classes_) != 2: - raise NotImplementedError("predict_(log_)proba only supported" - " for binary classification") + self._check_proba() + return self._predict_proba - scores = self.decision_function(X) - proba = np.ones((scores.shape[0], 2), dtype=np.float64) + def _predict_proba(self, X): if self.loss == "log": - proba[:, 1] = 1. / (1. + np.exp(-scores)) + return self._predict_proba_lr(X) elif self.loss == "modified_huber": - proba[:, 1] = (np.minimum(1, np.maximum(-1, scores)) + 1) / 2.0 + binary = (len(self.classes_) == 2) + scores = self.decision_function(X) + + if binary: + prob2 = np.ones((scores.shape[0], 2)) + prob = prob2[:, 1] + else: + prob = scores + + np.clip(scores, -1, 1, prob) + prob += 1. + prob /= 2. + + if binary: + prob2[:, 0] -= prob + prob = prob2 + else: + # the above might assign zero to all classes, which doesn't + # normalize neatly; work around this to produce uniform + # probabilities + prob_sum = prob.sum(axis=1) + all_zero = (prob_sum == 0) + if np.any(all_zero): + prob[all_zero, :] = 1 + prob_sum[all_zero] = len(self.classes_) + + # normalize + prob /= prob_sum.reshape((prob.shape[0], -1)) + + return prob else: raise NotImplementedError("predict_(log_)proba only supported when" " loss='log' or loss='modified_huber' " - "(%s given)" % self.loss) - proba[:, 0] -= proba[:, 1] - return proba + "(%r given)" % self.loss) - def predict_log_proba(self, X): + @property + def predict_log_proba(self): """Log of probability estimates. - Log probability estimates are only supported for binary classification. + This method is only available for log loss and modified Huber loss. + + When loss="modified_huber", probability estimates may be hard zeros + and ones, so taking the logarithm is not possible. + + See ``predict_proba`` for details. Parameters ---------- - X : array-like, shape = [n_samples, n_features] + X : array-like, shape (n_samples, n_features) Returns ------- - T : array-like, shape = [n_samples, n_classes] + T : array-like, shape (n_samples, n_classes) Returns the log-probability of the sample for each class in the - model, where classes are ordered as they are in self.classes_. + model, where classes are ordered as they are in + `self.classes_`. """ + self._check_proba() + return self._predict_log_proba + + def _predict_log_proba(self, X): return np.log(self.predict_proba(X)) - def _fit_binary(self, X, y, sample_weight, n_iter): - """Fit a binary classifier on X and y. """ - coef, intercept = fit_binary(self, 1, X, y, n_iter, - self._expanded_class_weight[1], - self._expanded_class_weight[0], - sample_weight) - # need to be 2d - self.coef_ = coef.reshape(1, -1) - # intercept is a float, need to convert it to an array of length 1 - self.intercept_ = np.atleast_1d(intercept) - def _fit_multiclass(self, X, y, sample_weight, n_iter): - """Fit a multi-class classifier by combining binary classifiers +class BaseSGDRegressor(BaseSGD, RegressorMixin): - Each binary classifier predicts one class versus all others. This - strategy is called OVA: One Versus All. + loss_functions = { + "squared_loss": (SquaredLoss, ), + "huber": (Huber, DEFAULT_EPSILON), + "epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON), + "squared_epsilon_insensitive": (SquaredEpsilonInsensitive, + DEFAULT_EPSILON), + } + + @abstractmethod + def __init__(self, loss="squared_loss", penalty="l2", alpha=0.0001, + l1_ratio=0.15, fit_intercept=True, n_iter=5, shuffle=True, + verbose=0, epsilon=DEFAULT_EPSILON, random_state=None, + learning_rate="invscaling", eta0=0.01, power_t=0.25, + warm_start=False, average=False): + super(BaseSGDRegressor, self).__init__(loss=loss, penalty=penalty, + alpha=alpha, l1_ratio=l1_ratio, + fit_intercept=fit_intercept, + n_iter=n_iter, shuffle=shuffle, + verbose=verbose, + epsilon=epsilon, + random_state=random_state, + learning_rate=learning_rate, + eta0=eta0, power_t=power_t, + warm_start=warm_start, + average=average) + + def _partial_fit(self, X, y, alpha, C, loss, learning_rate, + n_iter, sample_weight, + coef_init, intercept_init): + X, y = check_X_y(X, y, "csr", copy=False, order='C', dtype=np.float64) + y = y.astype(np.float64) + + n_samples, n_features = X.shape + + self._validate_params() + + # Allocate datastructures from input arguments + sample_weight = self._validate_sample_weight(sample_weight, n_samples) + + if self.coef_ is None: + self._allocate_parameter_mem(1, n_features, + coef_init, intercept_init) + elif n_features != self.coef_.shape[-1]: + raise ValueError("Number of features %d does not match previous data %d." + % (n_features, self.coef_.shape[-1])) + if self.average > 0 and self.average_coef_ is None: + self.average_coef_ = np.zeros(n_features, + dtype=np.float64, + order="C") + self.average_intercept_ = np.zeros(1, + dtype=np.float64, + order="C") + + self._fit_regressor(X, y, alpha, C, loss, learning_rate, + sample_weight, n_iter) + + return self + + def partial_fit(self, X, y, sample_weight=None): + """Fit linear model with Stochastic Gradient Descent. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Subset of training data + + y : numpy array of shape (n_samples,) + Subset of target values + + sample_weight : array-like, shape (n_samples,), optional + Weights applied to individual samples. + If not provided, uniform weights are assumed. + + Returns + ------- + self : returns an instance of self. """ - # Use joblib to fit OvA in parallel - result = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)( - delayed(fit_binary)(self, i, X, y, n_iter, - self._expanded_class_weight[i], 1., - sample_weight) - for i in xrange(len(self.classes_))) + return self._partial_fit(X, y, self.alpha, C=1.0, + loss=self.loss, + learning_rate=self.learning_rate, n_iter=1, + sample_weight=sample_weight, + coef_init=None, intercept_init=None) + + def _fit(self, X, y, alpha, C, loss, learning_rate, coef_init=None, + intercept_init=None, sample_weight=None): + if self.warm_start and self.coef_ is not None: + if coef_init is None: + coef_init = self.coef_ + if intercept_init is None: + intercept_init = self.intercept_ + else: + self.coef_ = None + self.intercept_ = None - for i, (coef, intercept) in enumerate(result): - self.coef_[i] = coef - self.intercept_[i] = intercept + if self.average > 0: + self.standard_intercept_ = self.intercept_ + self.standard_coef_ = self.coef_ + self.average_coef_ = None + self.average_intercept_ = None + # Clear iteration count for multiple call to fit. + self.t_ = None -def _prepare_fit_binary(est, y, i): - """Initialization for fit_binary. + return self._partial_fit(X, y, alpha, C, loss, learning_rate, + self.n_iter, sample_weight, + coef_init, intercept_init) - Returns y, coef, intercept. - """ - y_i = np.ones(y.shape, dtype=np.float64, order="C") - y_i[y != est.classes_[i]] = -1.0 + def fit(self, X, y, coef_init=None, intercept_init=None, + sample_weight=None): + """Fit linear model with Stochastic Gradient Descent. - if len(est.classes_) == 2: - coef = est.coef_.ravel() - intercept = est.intercept_[0] - else: - coef = est.coef_[i] - intercept = est.intercept_[i] + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data - return y_i, coef, intercept + y : numpy array, shape (n_samples,) + Target values + coef_init : array, shape (n_features,) + The initial coefficients to warm-start the optimization. -def fit_binary(est, i, X, y, n_iter, pos_weight, neg_weight, - sample_weight): - """Fit a single binary classifier. + intercept_init : array, shape (1,) + The initial intercept to warm-start the optimization. - The i'th class is considered the "positive" class. - """ - y_i, coef, intercept = _prepare_fit_binary(est, y, i) - assert y_i.shape[0] == y.shape[0] == sample_weight.shape[0] - dataset, intercept_decay = _make_dataset(X, y_i, sample_weight) + sample_weight : array-like, shape (n_samples,), optional + Weights applied to individual samples (1. for unweighted). - penalty_type = est._get_penalty_type(est.penalty) - learning_rate_type = est._get_learning_rate_type(est.learning_rate) + Returns + ------- + self : returns an instance of self. + """ + return self._fit(X, y, alpha=self.alpha, C=1.0, + loss=self.loss, learning_rate=self.learning_rate, + coef_init=coef_init, + intercept_init=intercept_init, + sample_weight=sample_weight) + + def decision_function(self, X): + """Predict using the linear model + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) - return plain_sgd(coef, intercept, est.loss_function, - penalty_type, est.alpha, est.rho, - dataset, n_iter, int(est.fit_intercept), - int(est.verbose), int(est.shuffle), est.seed, - pos_weight, neg_weight, - learning_rate_type, est.eta0, - est.power_t, est.t_, intercept_decay) + Returns + ------- + array, shape (n_samples,) + Predicted target values per element in X. + """ + check_is_fitted(self, ["t_", "coef_", "intercept_"], all_or_any=all) + X = check_array(X, accept_sparse='csr') -class SGDRegressor(BaseSGD, RegressorMixin, SelectorMixin): + scores = safe_sparse_dot(X, self.coef_.T, + dense_output=True) + self.intercept_ + return scores.ravel() + + def predict(self, X): + """Predict using the linear model + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + + Returns + ------- + array, shape (n_samples,) + Predicted target values per element in X. + """ + return self.decision_function(X) + + def _fit_regressor(self, X, y, alpha, C, loss, learning_rate, + sample_weight, n_iter): + dataset, intercept_decay = _make_dataset(X, y, sample_weight) + + loss_function = self._get_loss_function(loss) + penalty_type = self._get_penalty_type(self.penalty) + learning_rate_type = self._get_learning_rate_type(learning_rate) + + if self.t_ is None: + self.t_ = 1.0 + + random_state = check_random_state(self.random_state) + # numpy mtrand expects a C long which is a signed 32 bit integer under + # Windows + seed = random_state.randint(0, np.iinfo(np.int32).max) + + if self.average > 0: + self.standard_coef_, self.standard_intercept_, \ + self.average_coef_, self.average_intercept_ =\ + average_sgd(self.standard_coef_, + self.standard_intercept_[0], + self.average_coef_, + self.average_intercept_[0], + loss_function, + penalty_type, + alpha, C, + self.l1_ratio, + dataset, + n_iter, + int(self.fit_intercept), + int(self.verbose), + int(self.shuffle), + seed, + 1.0, 1.0, + learning_rate_type, + self.eta0, self.power_t, self.t_, + intercept_decay, self.average) + + self.average_intercept_ = np.atleast_1d(self.average_intercept_) + self.standard_intercept_ = np.atleast_1d(self.standard_intercept_) + self.t_ += n_iter * X.shape[0] + + if self.average <= self.t_ - 1.0: + self.coef_ = self.average_coef_ + self.intercept_ = self.average_intercept_ + else: + self.coef_ = self.standard_coef_ + self.intercept_ = self.standard_intercept_ + + else: + self.coef_, self.intercept_ = \ + plain_sgd(self.coef_, + self.intercept_[0], + loss_function, + penalty_type, + alpha, C, + self.l1_ratio, + dataset, + n_iter, + int(self.fit_intercept), + int(self.verbose), + int(self.shuffle), + seed, + 1.0, 1.0, + learning_rate_type, + self.eta0, self.power_t, self.t_, + intercept_decay) + + self.t_ += n_iter * X.shape[0] + self.intercept_ = np.atleast_1d(self.intercept_) + + +class SGDRegressor(BaseSGDRegressor, _LearntSelectorMixin): """Linear model fitted by minimizing a regularized empirical loss with SGD SGD stands for Stochastic Gradient Descent: the gradient of the loss is @@ -688,51 +1106,62 @@ class SGDRegressor(BaseSGD, RegressorMixin, SelectorMixin): Parameters ---------- - loss : str, 'squared_loss' or 'huber' + loss : str, 'squared_loss', 'huber', 'epsilon_insensitive', \ + or 'squared_epsilon_insensitive' The loss function to be used. Defaults to 'squared_loss' which refers - to the ordinary least squares fit. 'huber' is an epsilon insensitive - loss function for robust regression. - - penalty : str, 'l2' or 'l1' or 'elasticnet' + to the ordinary least squares fit. 'huber' modifies 'squared_loss' to + focus less on getting outliers correct by switching from squared to + linear loss past a distance of epsilon. 'epsilon_insensitive' ignores + errors less than epsilon and is linear past that; this is the loss + function used in SVR. 'squared_epsilon_insensitive' is the same but + becomes squared loss past a tolerance of epsilon. + + penalty : str, 'none', 'l2', 'l1', or 'elasticnet' The penalty (aka regularization term) to be used. Defaults to 'l2' which is the standard regularizer for linear SVM models. 'l1' and - 'elasticnet' migh bring sparsity to the model (feature selection) + 'elasticnet' might bring sparsity to the model (feature selection) not achievable with 'l2'. alpha : float Constant that multiplies the regularization term. Defaults to 0.0001 - rho : float - The Elastic Net mixing parameter, with 0 < rho <= 1. - Defaults to 0.85. + l1_ratio : float + The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. + l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. + Defaults to 0.15. - fit_intercept: bool + fit_intercept : bool Whether the intercept should be estimated or not. If False, the data is assumed to be already centered. Defaults to True. - n_iter: int, optional - The number of passes over the training data (aka epochs). + n_iter : int, optional + The number of passes over the training data (aka epochs). The number + of iterations is set to 1 if using partial_fit. Defaults to 5. - shuffle: bool, optional + shuffle : bool, optional Whether or not the training data should be shuffled after each epoch. - Defaults to False. + Defaults to True. - seed: int, optional + random_state : int seed, RandomState instance, or None (default) The seed of the pseudo random number generator to use when shuffling the data. - verbose: integer, optional + verbose : integer, optional The verbosity level. - epsilon: float - Epsilon in the epsilon-insensitive huber loss function; - only if `loss=='huber'`. + epsilon : float + Epsilon in the epsilon-insensitive loss functions; only if `loss` is + 'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'. + For 'huber', determines the threshold at which it becomes less + important to get the prediction exactly right. + For epsilon-insensitive, any differences between the current prediction + and the correct label are ignored if they are less than this threshold. learning_rate : string, optional The learning rate: constant: eta = eta0 - optimal: eta = 1.0/(t+t0) + optimal: eta = 1.0/(alpha * t) invscaling: eta = eta0 / pow(t, power_t) [default] eta0 : double, optional @@ -745,14 +1174,26 @@ class SGDRegressor(BaseSGD, RegressorMixin, SelectorMixin): When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. + average : bool or int, optional + When set to True, computes the averaged SGD weights and stores the + result in the ``coef_`` attribute. If set to an int greater than 1, + averaging will begin once the total number of samples seen reaches + average. So ``average=10 will`` begin averaging after seeing 10 samples. + Attributes ---------- - `coef_` : array, shape = [n_features] - Weights asigned to the features. + coef_ : array, shape (n_features,) + Weights assigned to the features. - `intercept_` : array, shape = [1] + intercept_ : array, shape (1,) The intercept term. + `average_coef_` : array, shape (n_features,) + Averaged weights assigned to the features. + + `average_intercept_` : array, shape (1,) + The averaged intercept term. + Examples -------- >>> import numpy as np @@ -763,185 +1204,30 @@ class SGDRegressor(BaseSGD, RegressorMixin, SelectorMixin): >>> X = np.random.randn(n_samples, n_features) >>> clf = linear_model.SGDRegressor() >>> clf.fit(X, y) - SGDRegressor(alpha=0.0001, epsilon=0.1, eta0=0.01, fit_intercept=True, - learning_rate='invscaling', loss='squared_loss', n_iter=5, p=None, - penalty='l2', power_t=0.25, rho=0.85, seed=0, shuffle=False, - verbose=0, warm_start=False) + ... #doctest: +NORMALIZE_WHITESPACE + SGDRegressor(alpha=0.0001, average=False, epsilon=0.1, eta0=0.01, + fit_intercept=True, l1_ratio=0.15, learning_rate='invscaling', + loss='squared_loss', n_iter=5, penalty='l2', power_t=0.25, + random_state=None, shuffle=True, verbose=0, warm_start=False) See also -------- Ridge, ElasticNet, Lasso, SVR """ - - loss_functions = { - "squared_loss": (SquaredLoss, ), - "huber": (Huber, DEFAULT_EPSILON), - "epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON) - } - def __init__(self, loss="squared_loss", penalty="l2", alpha=0.0001, - rho=0.85, fit_intercept=True, n_iter=5, shuffle=False, verbose=0, - epsilon=DEFAULT_EPSILON, p=None, seed=0, - learning_rate="invscaling", eta0=0.01, - power_t=0.25, warm_start=False): - - if p is not None: - warnings.warn("Using 'p' is deprecated and will be removed in " - "scikit-learn 0.14, use epsilon instead.", - DeprecationWarning, stacklevel=2) - self.p = float(p) - epsilon = p - + l1_ratio=0.15, fit_intercept=True, n_iter=5, shuffle=True, + verbose=0, epsilon=DEFAULT_EPSILON, random_state=None, + learning_rate="invscaling", eta0=0.01, power_t=0.25, + warm_start=False, average=False): super(SGDRegressor, self).__init__(loss=loss, penalty=penalty, - alpha=alpha, rho=rho, + alpha=alpha, l1_ratio=l1_ratio, fit_intercept=fit_intercept, n_iter=n_iter, shuffle=shuffle, - verbose=verbose, epsilon=epsilon, - seed=seed, + verbose=verbose, + epsilon=epsilon, + random_state=random_state, learning_rate=learning_rate, eta0=eta0, power_t=power_t, - warm_start=False) - - def _partial_fit(self, X, y, n_iter, sample_weight=None, - coef_init=None, intercept_init=None): - X, y = check_arrays(X, y, sparse_format="csr", copy=False, - check_ccontiguous=True, dtype=np.float64) - y = y.ravel() - - n_samples, n_features = X.shape - _check_fit_data(X, y) - - self._validate_params() - - # Allocate datastructures from input arguments - sample_weight = self._validate_sample_weight(sample_weight, n_samples) - - if self.coef_ is None: - self._allocate_parameter_mem(1, n_features, - coef_init, intercept_init) - - self._fit_regressor(X, y, sample_weight, n_iter) - - self.t_ += n_iter * n_samples - - return self - - def partial_fit(self, X, y, sample_weight=None): - """Fit linear model with Stochastic Gradient Descent. - - Parameters - ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] - Subset of training data - - y : numpy array of shape [n_samples] - Subset of target values - - sample_weight : array-like, shape = [n_samples], optional - Weights applied to individual samples. - If not provided, uniform weights are assumed. - - Returns - ------- - self : returns an instance of self. - """ - return self._partial_fit(X, y, n_iter=1, sample_weight=sample_weight) - - def fit(self, X, y, coef_init=None, intercept_init=None, - sample_weight=None): - """Fit linear model with Stochastic Gradient Descent. - - Parameters - ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] - Training data - - y : numpy array of shape [n_samples] - Target values - - coef_init : array, shape = [n_features] - The initial coeffients to warm-start the optimization. - - intercept_init : array, shape = [1] - The initial intercept to warm-start the optimization. - - sample_weight : array-like, shape = [n_samples], optional - Weights applied to individual samples (1. for unweighted). - - Returns - ------- - self : returns an instance of self. - """ - if self.warm_start and self.coef_ is not None: - if coef_init is None: - coef_init = self.coef_ - if intercept_init is None: - intercept_init = self.intercept_ - else: - self.coef_ = None - self.intercept_ = None - - # Clear iteration count for multiple call to fit. - self.t_ = None - - return self._partial_fit(X, y, self.n_iter, sample_weight, - coef_init, intercept_init) - - def decision_function(self, X): - """Predict using the linear model - - Parameters - ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] - - Returns - ------- - array, shape = [n_samples] - Predicted target values per element in X. - """ - X = atleast2d_or_csr(X) - scores = safe_sparse_dot(X, self.coef_) + self.intercept_ - return scores.ravel() - - def predict(self, X): - """Predict using the linear model - - Parameters - ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] - - Returns - ------- - array, shape = [n_samples] - Predicted target values per element in X. - """ - return self.decision_function(X) - - def _fit_regressor(self, X, y, sample_weight, n_iter): - dataset, intercept_decay = _make_dataset(X, y, sample_weight) - - loss_function = self._get_loss_function(self.loss) - penalty_type = self._get_penalty_type(self.penalty) - learning_rate_type = self._get_learning_rate_type(self.learning_rate) - - if self.t_ is None: - self._init_t(loss_function) - - self.coef_, intercept = plain_sgd(self.coef_, - self.intercept_[0], - loss_function, - penalty_type, - self.alpha, self.rho, - dataset, - n_iter, - int(self.fit_intercept), - int(self.verbose), - int(self.shuffle), - self.seed, - 1.0, 1.0, - learning_rate_type, - self.eta0, self.power_t, self.t_, - intercept_decay) - - self.intercept_ = np.atleast_1d(intercept) + warm_start=warm_start, + average=average) diff --git a/sklearn/linear_model/tests/test_base.py b/sklearn/linear_model/tests/test_base.py index 79fad17a16463..0be3b2dec7d5a 100644 --- a/sklearn/linear_model/tests/test_base.py +++ b/sklearn/linear_model/tests/test_base.py @@ -1,16 +1,20 @@ # Author: Alexandre Gramfort # Fabian Pedregosa # -# License: BSD Style. +# License: BSD 3 clause -from numpy.testing import assert_array_almost_equal, assert_equal import numpy as np from scipy import sparse +import warnings -from ..base import LinearRegression -from ...utils import check_random_state -from ...datasets.samples_generator import make_sparse_uncorrelated -from ...datasets.samples_generator import make_regression +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_equal + +from sklearn.linear_model.base import LinearRegression +from sklearn.linear_model.base import center_data, sparse_center_data +from sklearn.utils import check_random_state +from sklearn.datasets.samples_generator import make_sparse_uncorrelated +from sklearn.datasets.samples_generator import make_regression def test_linear_regression(): @@ -39,6 +43,19 @@ def test_linear_regression(): assert_array_almost_equal(clf.predict(X), [0]) +def test_linear_regression_n_jobs(): + """ + Test for the n_jobs parameter on the fit method and the constructor + """ + X = [[1], [2]] + Y = [1, 2] + clf = LinearRegression() + with warnings.catch_warnings(record=True): + clf_fit = clf.fit(X, Y, 4) + assert_equal(clf_fit.n_jobs, clf.n_jobs) + assert_equal(clf.n_jobs, 1) + + def test_fit_intercept(): """ Test assertions on betas shape. @@ -66,15 +83,16 @@ def test_fit_intercept(): def test_linear_regression_sparse(random_state=0): "Test that linear regression also works with sparse data" random_state = check_random_state(random_state) - n = 100 - X = sparse.eye(n, n) - beta = random_state.rand(n) - y = X * beta[:, np.newaxis] + for i in range(10): + n = 100 + X = sparse.eye(n, n) + beta = random_state.rand(n) + y = X * beta[:, np.newaxis] - ols = LinearRegression() - ols.fit(X, y.ravel()) - assert_array_almost_equal(beta, ols.coef_ + ols.intercept_) - assert_array_almost_equal(ols.residues_, 0) + ols = LinearRegression() + ols.fit(X, y.ravel()) + assert_array_almost_equal(beta, ols.coef_ + ols.intercept_) + assert_array_almost_equal(ols.residues_, 0) def test_linear_regression_multiple_outcome(random_state=0): @@ -108,3 +126,150 @@ def test_linear_regression_sparse_multiple_outcome(random_state=0): ols.fit(X, y.ravel()) y_pred = ols.predict(X) assert_array_almost_equal(np.vstack((y_pred, y_pred)).T, Y_pred, decimal=3) + + +def test_center_data(): + n_samples = 200 + n_features = 2 + rng = check_random_state(0) + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples) + expected_X_mean = np.mean(X, axis=0) + # XXX: currently scaled to variance=n_samples + expected_X_std = np.std(X, axis=0) * np.sqrt(X.shape[0]) + expected_y_mean = np.mean(y, axis=0) + + Xt, yt, X_mean, y_mean, X_std = center_data(X, y, fit_intercept=False, + normalize=False) + assert_array_almost_equal(X_mean, np.zeros(n_features)) + assert_array_almost_equal(y_mean, 0) + assert_array_almost_equal(X_std, np.ones(n_features)) + assert_array_almost_equal(Xt, X) + assert_array_almost_equal(yt, y) + + Xt, yt, X_mean, y_mean, X_std = center_data(X, y, fit_intercept=True, + normalize=False) + assert_array_almost_equal(X_mean, expected_X_mean) + assert_array_almost_equal(y_mean, expected_y_mean) + assert_array_almost_equal(X_std, np.ones(n_features)) + assert_array_almost_equal(Xt, X - expected_X_mean) + assert_array_almost_equal(yt, y - expected_y_mean) + + Xt, yt, X_mean, y_mean, X_std = center_data(X, y, fit_intercept=True, + normalize=True) + assert_array_almost_equal(X_mean, expected_X_mean) + assert_array_almost_equal(y_mean, expected_y_mean) + assert_array_almost_equal(X_std, expected_X_std) + assert_array_almost_equal(Xt, (X - expected_X_mean) / expected_X_std) + assert_array_almost_equal(yt, y - expected_y_mean) + + +def test_center_data_multioutput(): + n_samples = 200 + n_features = 3 + n_outputs = 2 + rng = check_random_state(0) + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples, n_outputs) + expected_y_mean = np.mean(y, axis=0) + + args = [(center_data, X), (sparse_center_data, sparse.csc_matrix(X))] + for center, X in args: + _, yt, _, y_mean, _ = center(X, y, fit_intercept=False, + normalize=False) + assert_array_almost_equal(y_mean, np.zeros(n_outputs)) + assert_array_almost_equal(yt, y) + + _, yt, _, y_mean, _ = center(X, y, fit_intercept=True, + normalize=False) + assert_array_almost_equal(y_mean, expected_y_mean) + assert_array_almost_equal(yt, y - y_mean) + + _, yt, _, y_mean, _ = center(X, y, fit_intercept=True, + normalize=True) + assert_array_almost_equal(y_mean, expected_y_mean) + assert_array_almost_equal(yt, y - y_mean) + + +def test_center_data_weighted(): + n_samples = 200 + n_features = 2 + rng = check_random_state(0) + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples) + sample_weight = rng.rand(n_samples) + expected_X_mean = np.average(X, axis=0, weights=sample_weight) + expected_y_mean = np.average(y, axis=0, weights=sample_weight) + + # XXX: if normalize=True, should we expect a weighted standard deviation? + # Currently not weighted, but calculated with respect to weighted mean + # XXX: currently scaled to variance=n_samples + expected_X_std = (np.sqrt(X.shape[0]) * + np.mean((X - expected_X_mean) ** 2, axis=0) ** .5) + + Xt, yt, X_mean, y_mean, X_std = center_data(X, y, fit_intercept=True, + normalize=False, + sample_weight=sample_weight) + assert_array_almost_equal(X_mean, expected_X_mean) + assert_array_almost_equal(y_mean, expected_y_mean) + assert_array_almost_equal(X_std, np.ones(n_features)) + assert_array_almost_equal(Xt, X - expected_X_mean) + assert_array_almost_equal(yt, y - expected_y_mean) + + Xt, yt, X_mean, y_mean, X_std = center_data(X, y, fit_intercept=True, + normalize=True, + sample_weight=sample_weight) + assert_array_almost_equal(X_mean, expected_X_mean) + assert_array_almost_equal(y_mean, expected_y_mean) + assert_array_almost_equal(X_std, expected_X_std) + assert_array_almost_equal(Xt, (X - expected_X_mean) / expected_X_std) + assert_array_almost_equal(yt, y - expected_y_mean) + + +def test_sparse_center_data(): + n_samples = 200 + n_features = 2 + rng = check_random_state(0) + # random_state not supported yet in sparse.rand + X = sparse.rand(n_samples, n_features, density=.5) # , random_state=rng + X = X.tolil() + y = rng.rand(n_samples) + XA = X.toarray() + # XXX: currently scaled to variance=n_samples + expected_X_std = np.std(XA, axis=0) * np.sqrt(X.shape[0]) + + Xt, yt, X_mean, y_mean, X_std = sparse_center_data(X, y, + fit_intercept=False, + normalize=False) + assert_array_almost_equal(X_mean, np.zeros(n_features)) + assert_array_almost_equal(y_mean, 0) + assert_array_almost_equal(X_std, np.ones(n_features)) + assert_array_almost_equal(Xt.A, XA) + assert_array_almost_equal(yt, y) + + Xt, yt, X_mean, y_mean, X_std = sparse_center_data(X, y, + fit_intercept=True, + normalize=False) + assert_array_almost_equal(X_mean, np.mean(XA, axis=0)) + assert_array_almost_equal(y_mean, np.mean(y, axis=0)) + assert_array_almost_equal(X_std, np.ones(n_features)) + assert_array_almost_equal(Xt.A, XA) + assert_array_almost_equal(yt, y - np.mean(y, axis=0)) + + Xt, yt, X_mean, y_mean, X_std = sparse_center_data(X, y, + fit_intercept=True, + normalize=True) + assert_array_almost_equal(X_mean, np.mean(XA, axis=0)) + assert_array_almost_equal(y_mean, np.mean(y, axis=0)) + assert_array_almost_equal(X_std, expected_X_std) + assert_array_almost_equal(Xt.A, XA / expected_X_std) + assert_array_almost_equal(yt, y - np.mean(y, axis=0)) + + +def test_csr_sparse_center_data(): + """Test output format of sparse_center_data, when input is csr""" + X, y = make_regression() + X[X < 2.5] = 0.0 + csr = sparse.csr_matrix(X) + csr_, y, _, _, _ = sparse_center_data(csr, y, True) + assert_equal(csr_.getformat(), 'csr') diff --git a/sklearn/linear_model/tests/test_bayes.py b/sklearn/linear_model/tests/test_bayes.py index f5048c24d65fc..100d50f6fcbf1 100644 --- a/sklearn/linear_model/tests/test_bayes.py +++ b/sklearn/linear_model/tests/test_bayes.py @@ -1,24 +1,23 @@ # Author: Alexandre Gramfort # Fabian Pedregosa # -# License: BSD Style. +# License: BSD 3 clause import numpy as np -from numpy.testing import assert_array_equal - -import nose - -from ..bayes import BayesianRidge, ARDRegression - +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import SkipTest +from sklearn.linear_model.bayes import BayesianRidge, ARDRegression from sklearn import datasets +from sklearn.utils.testing import assert_array_almost_equal + def test_bayesian_on_diabetes(): """ Test BayesianRidge on diabetes """ - raise nose.SkipTest("XFailed Test") + raise SkipTest("XFailed Test") diabetes = datasets.load_diabetes() X, y = diabetes.data, diabetes.target @@ -45,8 +44,10 @@ def test_toy_bayesian_ridge_object(): Y = np.array([1, 2, 6, 8, 10]) clf = BayesianRidge(compute_score=True) clf.fit(X, Y) - X_test = [[1], [3], [4]] - assert(np.abs(clf.predict(X_test) - [1, 3, 4]).sum() < 1.e-2) # identity + + # Check that the model could approximately learn the identity function + test = [[1], [3], [4]] + assert_array_almost_equal(clf.predict(test), [1, 3, 4], 2) def test_toy_ard_object(): @@ -57,5 +58,7 @@ def test_toy_ard_object(): Y = np.array([1, 2, 3]) clf = ARDRegression(compute_score=True) clf.fit(X, Y) + + # Check that the model could approximately learn the identity function test = [[1], [3], [4]] - assert(np.abs(clf.predict(test) - [1, 3, 4]).sum() < 1.e-3) # identity + assert_array_almost_equal(clf.predict(test), [1, 3, 4], 2) diff --git a/sklearn/linear_model/tests/test_coordinate_descent.py b/sklearn/linear_model/tests/test_coordinate_descent.py index bcee7372cdd51..cada4377d1807 100644 --- a/sklearn/linear_model/tests/test_coordinate_descent.py +++ b/sklearn/linear_model/tests/test_coordinate_descent.py @@ -1,22 +1,29 @@ # Authors: Olivier Grisel # Alexandre Gramfort -# License: BSD Style. +# License: BSD 3 clause -import warnings from sys import version_info import numpy as np -from scipy import interpolate -from numpy.testing import assert_array_almost_equal, assert_almost_equal, \ - assert_equal -from nose import SkipTest -from nose.tools import assert_true - +from scipy import interpolate, sparse +from copy import deepcopy + +from sklearn.datasets import load_boston +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import SkipTest +from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import ignore_warnings +from sklearn.utils.testing import assert_array_equal from sklearn.linear_model.coordinate_descent import Lasso, \ - LassoCV, ElasticNet, ElasticNetCV, MultiTaskLasso, MultiTaskElasticNet -from sklearn.linear_model import LassoLarsCV + LassoCV, ElasticNet, ElasticNetCV, MultiTaskLasso, MultiTaskElasticNet, \ + MultiTaskElasticNetCV, MultiTaskLassoCV, lasso_path, enet_path +from sklearn.linear_model import LassoLarsCV, lars_path def check_warnings(): @@ -79,9 +86,9 @@ def test_lasso_toy(): def test_enet_toy(): """ - Test ElasticNet for various parameters of alpha and rho. + Test ElasticNet for various parameters of alpha and l1_ratio. - Actualy, the parameters alpha = 0 should not be alowed. However, + Actually, the parameters alpha = 0 should not be allowed. However, we test it as a border case. ElasticNet is tested with and without precomputed Gram matrix @@ -92,14 +99,14 @@ def test_enet_toy(): T = [[2.], [3.], [4.]] # test sample # this should be the same as lasso - clf = ElasticNet(alpha=1e-8, rho=1.0) + clf = ElasticNet(alpha=1e-8, l1_ratio=1.0) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [1]) assert_array_almost_equal(pred, [2, 3, 4]) assert_almost_equal(clf.dual_gap_, 0) - clf = ElasticNet(alpha=0.5, rho=0.3, max_iter=100, + clf = ElasticNet(alpha=0.5, l1_ratio=0.3, max_iter=100, precompute=False) clf.fit(X, Y) pred = clf.predict(T) @@ -121,7 +128,7 @@ def test_enet_toy(): assert_array_almost_equal(pred, [1.0163, 1.5245, 2.0327], decimal=3) assert_almost_equal(clf.dual_gap_, 0) - clf = ElasticNet(alpha=0.5, rho=0.5) + clf = ElasticNet(alpha=0.5, l1_ratio=0.5) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [0.45454], 3) @@ -148,15 +155,15 @@ def build_dataset(n_samples=50, n_features=200, n_informative_features=10, return X, y, X_test, y_test -def test_lasso_path(): +def test_lasso_cv(): X, y, X_test, y_test = build_dataset() max_iter = 150 clf = LassoCV(n_alphas=10, eps=1e-3, max_iter=max_iter).fit(X, y) - assert_almost_equal(clf.alpha_, 0.026, 2) + assert_almost_equal(clf.alpha_, 0.056, 2) clf = LassoCV(n_alphas=10, eps=1e-3, max_iter=max_iter, precompute=True) clf.fit(X, y) - assert_almost_equal(clf.alpha_, 0.026, 2) + assert_almost_equal(clf.alpha_, 0.056, 2) # Check that the lars and the coordinate descent implementation # select a similar alpha @@ -164,88 +171,144 @@ def test_lasso_path(): # for this we check that they don't fall in the grid of # clf.alphas further than 1 assert_true(np.abs( - np.searchsorted(clf.alphas_[::-1], lars.alpha_) - - np.searchsorted(clf.alphas_[::-1], clf.alpha_) - ) <= 1) + np.searchsorted(clf.alphas_[::-1], lars.alpha_) + - np.searchsorted(clf.alphas_[::-1], clf.alpha_)) <= 1) # check that they also give a similar MSE mse_lars = interpolate.interp1d(lars.cv_alphas_, lars.cv_mse_path_.T) - np.testing.assert_approx_equal( - mse_lars(clf.alphas_[5]).mean(), - clf.mse_path_[5].mean(), - significant=2) + np.testing.assert_approx_equal(mse_lars(clf.alphas_[5]).mean(), + clf.mse_path_[5].mean(), significant=2) # test set assert_greater(clf.score(X_test, y_test), 0.99) -def test_enet_path(): +def test_lasso_cv_positive_constraint(): X, y, X_test, y_test = build_dataset() + max_iter = 500 + + # Ensure the unconstrained fit has a negative coefficient + clf_unconstrained = LassoCV(n_alphas=3, eps=1e-1, max_iter=max_iter, cv=2, + n_jobs=1) + clf_unconstrained.fit(X, y) + assert_true(min(clf_unconstrained.coef_) < 0) + + # On same data, constrained fit has non-negative coefficients + clf_constrained = LassoCV(n_alphas=3, eps=1e-1, max_iter=max_iter, + positive=True, cv=2, n_jobs=1) + clf_constrained.fit(X, y) + assert_true(min(clf_constrained.coef_) >= 0) + + +def test_lasso_path_return_models_vs_new_return_gives_same_coefficients(): + # Test that lasso_path with lars_path style output gives the + # same result + + # Some toy data + X = np.array([[1, 2, 3.1], [2.3, 5.4, 4.3]]).T + y = np.array([1, 2, 3.1]) + alphas = [5., 1., .5] + + # Use lars_path and lasso_path(new output) with 1D linear interpolation + # to compute the the same path + alphas_lars, _, coef_path_lars = lars_path(X, y, method='lasso') + coef_path_cont_lars = interpolate.interp1d(alphas_lars[::-1], + coef_path_lars[:, ::-1]) + alphas_lasso2, coef_path_lasso2, _ = lasso_path(X, y, alphas=alphas, + return_models=False) + coef_path_cont_lasso = interpolate.interp1d(alphas_lasso2[::-1], + coef_path_lasso2[:, ::-1]) + + assert_array_almost_equal( + coef_path_cont_lasso(alphas), coef_path_cont_lars(alphas), + decimal=1) + + +def test_enet_path(): + # We use a large number of samples and of informative features so that + # the l1_ratio selected is more toward ridge than lasso + X, y, X_test, y_test = build_dataset(n_samples=200, n_features=100, + n_informative_features=100) max_iter = 150 - with warnings.catch_warnings(): - # Here we have a small number of iterations, and thus the - # ElasticNet might not converge. This is to speed up tests - warnings.simplefilter("ignore", UserWarning) - clf = ElasticNetCV(n_alphas=5, eps=2e-3, rho=[0.9, 0.95], cv=3, - max_iter=max_iter) - clf.fit(X, y) - assert_almost_equal(clf.alpha_, 0.002, 2) - assert_equal(clf.rho_, 0.95) - - clf = ElasticNetCV(n_alphas=5, eps=2e-3, rho=[0.9, 0.95], cv=3, - max_iter=max_iter, precompute=True) - clf.fit(X, y) - assert_almost_equal(clf.alpha_, 0.002, 2) - assert_equal(clf.rho_, 0.95) + # Here we have a small number of iterations, and thus the + # ElasticNet might not converge. This is to speed up tests + clf = ElasticNetCV(alphas=[0.01, 0.05, 0.1], eps=2e-3, + l1_ratio=[0.5, 0.7], cv=3, + max_iter=max_iter) + ignore_warnings(clf.fit)(X, y) + # Well-conditioned settings, we should have selected our + # smallest penalty + assert_almost_equal(clf.alpha_, min(clf.alphas_)) + # Non-sparse ground truth: we should have seleted an elastic-net + # that is closer to ridge than to lasso + assert_equal(clf.l1_ratio_, min(clf.l1_ratio)) + + clf = ElasticNetCV(alphas=[0.01, 0.05, 0.1], eps=2e-3, + l1_ratio=[0.5, 0.7], cv=3, + max_iter=max_iter, precompute=True) + ignore_warnings(clf.fit)(X, y) + + # Well-conditioned settings, we should have selected our + # smallest penalty + assert_almost_equal(clf.alpha_, min(clf.alphas_)) + # Non-sparse ground truth: we should have seleted an elastic-net + # that is closer to ridge than to lasso + assert_equal(clf.l1_ratio_, min(clf.l1_ratio)) + + # We are in well-conditioned settings with low noise: we should + # have a good test-set performance + assert_greater(clf.score(X_test, y_test), 0.99) - # test set + # Multi-output/target case + X, y, X_test, y_test = build_dataset(n_features=10, n_targets=3) + clf = MultiTaskElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7], + cv=3, max_iter=max_iter) + ignore_warnings(clf.fit)(X, y) + # We are in well-conditioned settings with low noise: we should + # have a good test-set performance assert_greater(clf.score(X_test, y_test), 0.99) + assert_equal(clf.coef_.shape, (3, 10)) + + # Mono-output should have same cross-validated alpha_ and l1_ratio_ + # in both cases. + X, y, _, _ = build_dataset(n_features=10) + clf1 = ElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) + clf1.fit(X, y) + clf2 = MultiTaskElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) + clf2.fit(X, y[:, np.newaxis]) + assert_almost_equal(clf1.l1_ratio_, clf2.l1_ratio_) + assert_almost_equal(clf1.alpha_, clf2.alpha_) def test_path_parameters(): X, y, _, _ = build_dataset() - max_iter = 50 + max_iter = 100 clf = ElasticNetCV(n_alphas=50, eps=1e-3, max_iter=max_iter, - rho=0.5) + l1_ratio=0.5, tol=1e-3) clf.fit(X, y) # new params - assert_almost_equal(0.5, clf.rho) + assert_almost_equal(0.5, clf.l1_ratio) assert_equal(50, clf.n_alphas) assert_equal(50, len(clf.alphas_)) def test_warm_start(): X, y, _, _ = build_dataset() - # Test that explicit warm restart... - clf = ElasticNet(alpha=1.0, max_iter=50) - clf.fit(X, y) + clf = ElasticNet(alpha=0.1, max_iter=5, warm_start=True) + ignore_warnings(clf.fit)(X, y) + ignore_warnings(clf.fit)(X, y) # do a second round with 5 iterations - clf2 = ElasticNet(alpha=0.1, max_iter=50) - clf2.fit(X, y, coef_init=clf.coef_.copy()) - - #... and implicit warm restart are equivalent. - clf3 = ElasticNet(alpha=1.0, max_iter=50, warm_start=True) - clf3.fit(X, y) - - assert_array_almost_equal(clf3.coef_, clf.coef_) - - clf3.set_params(alpha=0.1) - clf3.fit(X, y) - - assert_array_almost_equal(clf3.coef_, clf2.coef_) + clf2 = ElasticNet(alpha=0.1, max_iter=10) + ignore_warnings(clf2.fit)(X, y) + assert_array_almost_equal(clf2.coef_, clf.coef_) def test_lasso_alpha_warning(): - check_warnings() # Skip if unsupported Python version - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - X = [[-1], [0], [1]] - Y = [-1, 0, 1] # just a straight line - - clf = Lasso(alpha=0) - clf.fit(X, Y) + X = [[-1], [0], [1]] + Y = [-1, 0, 1] # just a straight line - assert_greater(len(w), 0) # warnings should be raised + clf = Lasso(alpha=0) + assert_warns(UserWarning, clf.fit, X, Y) def test_lasso_positive_constraint(): @@ -270,10 +333,59 @@ def test_enet_positive_constraint(): assert_true(min(enet.coef_) >= 0) +def test_enet_cv_positive_constraint(): + X, y, X_test, y_test = build_dataset() + max_iter = 500 + + # Ensure the unconstrained fit has a negative coefficient + enetcv_unconstrained = ElasticNetCV(n_alphas=3, eps=1e-1, + max_iter=max_iter, + cv=2, n_jobs=1) + enetcv_unconstrained.fit(X, y) + assert_true(min(enetcv_unconstrained.coef_) < 0) + + # On same data, constrained fit has non-negative coefficients + enetcv_constrained = ElasticNetCV(n_alphas=3, eps=1e-1, max_iter=max_iter, + cv=2, positive=True, n_jobs=1) + enetcv_constrained.fit(X, y) + assert_true(min(enetcv_constrained.coef_) >= 0) + + +def test_uniform_targets(): + enet = ElasticNetCV(fit_intercept=True, n_alphas=3) + m_enet = MultiTaskElasticNetCV(fit_intercept=True, n_alphas=3) + lasso = LassoCV(fit_intercept=True, n_alphas=3) + m_lasso = MultiTaskLassoCV(fit_intercept=True, n_alphas=3) + + models_single_task = (enet, lasso) + models_multi_task = (m_enet, m_lasso) + + rng = np.random.RandomState(0) + + X_train = rng.random_sample(size=(10, 3)) + X_test = rng.random_sample(size=(10, 3)) + + y1 = np.empty(10) + y2 = np.empty((10, 2)) + + for model in models_single_task: + for y_values in (0, 5): + y1.fill(y_values) + assert_array_equal(model.fit(X_train, y1).predict(X_test), y1) + assert_array_equal(model.alphas_, [np.finfo(float).resolution]*3) + + for model in models_multi_task: + for y_values in (0, 5): + y2[:, 0].fill(y_values) + y2[:, 1].fill(2 * y_values) + assert_array_equal(model.fit(X_train, y2).predict(X_test), y2) + assert_array_equal(model.alphas_, [np.finfo(float).resolution]*3) + + def test_multi_task_lasso_and_enet(): X, y, X_test, y_test = build_dataset() Y = np.c_[y, y] - #Y_test = np.c_[y_test, y_test] + # Y_test = np.c_[y_test, y_test] clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y) assert_true(0 < clf.dual_gap_ < 1e-5) assert_array_almost_equal(clf.coef_[0], clf.coef_[1]) @@ -289,15 +401,224 @@ def test_enet_multitarget(): n_informative_features=10, n_targets=n_targets) estimator = ElasticNet(alpha=0.01, fit_intercept=True) estimator.fit(X, y) - coef, intercept, dual_gap, eps = (estimator.coef_, estimator.intercept_, - estimator.dual_gap_, estimator.eps_) + coef, intercept, dual_gap = (estimator.coef_, estimator.intercept_, + estimator.dual_gap_) - for k in xrange(n_targets): + for k in range(n_targets): estimator.fit(X, y[:, k]) assert_array_almost_equal(coef[k, :], estimator.coef_) assert_array_almost_equal(intercept[k], estimator.intercept_) assert_array_almost_equal(dual_gap[k], estimator.dual_gap_) - assert_array_almost_equal(eps[k], estimator.eps_) + + +def test_multioutput_enetcv_error(): + X = np.random.randn(10, 2) + y = np.random.randn(10, 2) + clf = ElasticNetCV() + assert_raises(ValueError, clf.fit, X, y) + + +def test_multitask_enet_and_lasso_cv(): + X, y, _, _ = build_dataset(n_features=100, n_targets=3) + clf = MultiTaskElasticNetCV().fit(X, y) + assert_almost_equal(clf.alpha_, 0.00556, 3) + clf = MultiTaskLassoCV().fit(X, y) + assert_almost_equal(clf.alpha_, 0.00278, 3) + + X, y, _, _ = build_dataset(n_targets=3) + clf = MultiTaskElasticNetCV(n_alphas=50, eps=1e-3, max_iter=100, + l1_ratio=[0.3, 0.5], tol=1e-3) + clf.fit(X, y) + assert_equal(0.5, clf.l1_ratio_) + assert_equal((3, X.shape[1]), clf.coef_.shape) + assert_equal((3, ), clf.intercept_.shape) + assert_equal((2, 50, 3), clf.mse_path_.shape) + assert_equal((2, 50), clf.alphas_.shape) + + X, y, _, _ = build_dataset(n_targets=3) + clf = MultiTaskLassoCV(n_alphas=50, eps=1e-3, max_iter=100, tol=1e-3) + clf.fit(X, y) + assert_equal((3, X.shape[1]), clf.coef_.shape) + assert_equal((3, ), clf.intercept_.shape) + assert_equal((50, 3), clf.mse_path_.shape) + assert_equal(50, len(clf.alphas_)) + + +def test_1d_multioutput_enet_and_multitask_enet_cv(): + X, y, _, _ = build_dataset(n_features=10) + y = y[:, np.newaxis] + clf = ElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) + clf.fit(X, y[:, 0]) + clf1 = MultiTaskElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) + clf1.fit(X, y) + assert_almost_equal(clf.l1_ratio_, clf1.l1_ratio_) + assert_almost_equal(clf.alpha_, clf1.alpha_) + assert_almost_equal(clf.coef_, clf1.coef_[0]) + assert_almost_equal(clf.intercept_, clf1.intercept_[0]) + + +def test_1d_multioutput_lasso_and_multitask_lasso_cv(): + X, y, _, _ = build_dataset(n_features=10) + y = y[:, np.newaxis] + clf = LassoCV(n_alphas=5, eps=2e-3) + clf.fit(X, y[:, 0]) + clf1 = MultiTaskLassoCV(n_alphas=5, eps=2e-3) + clf1.fit(X, y) + assert_almost_equal(clf.alpha_, clf1.alpha_) + assert_almost_equal(clf.coef_, clf1.coef_[0]) + assert_almost_equal(clf.intercept_, clf1.intercept_[0]) + + +def test_sparse_input_dtype_enet_and_lassocv(): + X, y, _, _ = build_dataset(n_features=10) + clf = ElasticNetCV(n_alphas=5) + clf.fit(sparse.csr_matrix(X), y) + clf1 = ElasticNetCV(n_alphas=5) + clf1.fit(sparse.csr_matrix(X, dtype=np.float32), y) + assert_almost_equal(clf.alpha_, clf1.alpha_, decimal=6) + assert_almost_equal(clf.coef_, clf1.coef_, decimal=6) + + clf = LassoCV(n_alphas=5) + clf.fit(sparse.csr_matrix(X), y) + clf1 = LassoCV(n_alphas=5) + clf1.fit(sparse.csr_matrix(X, dtype=np.float32), y) + assert_almost_equal(clf.alpha_, clf1.alpha_, decimal=6) + assert_almost_equal(clf.coef_, clf1.coef_, decimal=6) + + +def test_precompute_invalid_argument(): + X, y, _, _ = build_dataset() + for clf in [ElasticNetCV(precompute="invalid"), + LassoCV(precompute="invalid")]: + assert_raises(ValueError, clf.fit, X, y) + + +def test_warm_start_convergence(): + X, y, _, _ = build_dataset() + model = ElasticNet(alpha=1e-3, tol=1e-3).fit(X, y) + n_iter_reference = model.n_iter_ + + # This dataset is not trivial enough for the model to converge in one pass. + assert_greater(n_iter_reference, 2) + + # Check that n_iter_ is invariant to multiple calls to fit + # when warm_start=False, all else being equal. + model.fit(X, y) + n_iter_cold_start = model.n_iter_ + assert_equal(n_iter_cold_start, n_iter_reference) + + # Fit the same model again, using a warm start: the optimizer just performs + # a single pass before checking that it has already converged + model.set_params(warm_start=True) + model.fit(X, y) + n_iter_warm_start = model.n_iter_ + assert_equal(n_iter_warm_start, 1) + + +def test_warm_start_convergence_with_regularizer_decrement(): + boston = load_boston() + X, y = boston.data, boston.target + + # Train a model to converge on a lightly regularized problem + final_alpha = 1e-5 + low_reg_model = ElasticNet(alpha=final_alpha).fit(X, y) + + # Fitting a new model on a more regularized version of the same problem. + # Fitting with high regularization is easier it should converge faster + # in general. + high_reg_model = ElasticNet(alpha=final_alpha * 10).fit(X, y) + assert_greater(low_reg_model.n_iter_, high_reg_model.n_iter_) + + # Fit the solution to the original, less regularized version of the + # problem but from the solution of the highly regularized variant of + # the problem as a better starting point. This should also converge + # faster than the original model that starts from zero. + warm_low_reg_model = deepcopy(high_reg_model) + warm_low_reg_model.set_params(warm_start=True, alpha=final_alpha) + warm_low_reg_model.fit(X, y) + assert_greater(low_reg_model.n_iter_, warm_low_reg_model.n_iter_) + + +def test_random_descent(): + """Test that both random and cyclic selection give the same results. + + Ensure that the test models fully converge and check a wide + range of conditions. + """ + + # This uses the coordinate descent algo using the gram trick. + X, y, _, _ = build_dataset(n_samples=50, n_features=20) + clf_cyclic = ElasticNet(selection='cyclic', tol=1e-8) + clf_cyclic.fit(X, y) + clf_random = ElasticNet(selection='random', tol=1e-8, random_state=42) + clf_random.fit(X, y) + assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) + assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) + + # This uses the descent algo without the gram trick + clf_cyclic = ElasticNet(selection='cyclic', tol=1e-8) + clf_cyclic.fit(X.T, y[:20]) + clf_random = ElasticNet(selection='random', tol=1e-8, random_state=42) + clf_random.fit(X.T, y[:20]) + assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) + assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) + + # Sparse Case + clf_cyclic = ElasticNet(selection='cyclic', tol=1e-8) + clf_cyclic.fit(sparse.csr_matrix(X), y) + clf_random = ElasticNet(selection='random', tol=1e-8, random_state=42) + clf_random.fit(sparse.csr_matrix(X), y) + assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) + assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) + + # Multioutput case. + new_y = np.hstack((y[:, np.newaxis], y[:, np.newaxis])) + clf_cyclic = MultiTaskElasticNet(selection='cyclic', tol=1e-8) + clf_cyclic.fit(X, new_y) + clf_random = MultiTaskElasticNet(selection='random', tol=1e-8, + random_state=42) + clf_random.fit(X, new_y) + assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) + assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) + + # Raise error when selection is not in cyclic or random. + clf_random = ElasticNet(selection='invalid') + assert_raises(ValueError, clf_random.fit, X, y) + + +def test_deprection_precompute_enet(): + """ + Test that setting precompute="auto" gives a Deprecation Warning. + """ + + X, y, _, _ = build_dataset(n_samples=20, n_features=10) + clf = ElasticNet(precompute="auto") + assert_warns(DeprecationWarning, clf.fit, X, y) + clf = Lasso(precompute="auto") + assert_warns(DeprecationWarning, clf.fit, X, y) + + +def test_enet_path_positive(): + """ + Test that the coefs returned by positive=True in enet_path are positive + """ + + X, y, _, _ = build_dataset(n_samples=50, n_features=50) + for path in [enet_path, lasso_path]: + pos_path_coef = path(X, y, positive=True)[1] + assert_true(np.all(pos_path_coef >= 0)) + + +def test_sparse_dense_descent_paths(): + """ + Test that dense and sparse input give the same input for descent paths. + """ + X, y, _, _ = build_dataset(n_samples=50, n_features=20) + csr = sparse.csr_matrix(X) + for path in [enet_path, lasso_path]: + _, coefs, _ = path(X, y, fit_intercept=False) + _, sparse_coefs, _ = path(csr, y, fit_intercept=False) + assert_array_almost_equal(coefs, sparse_coefs) if __name__ == '__main__': diff --git a/sklearn/linear_model/tests/test_isotonic_regression.py b/sklearn/linear_model/tests/test_isotonic_regression.py deleted file mode 100644 index 8ea636dafaeea..0000000000000 --- a/sklearn/linear_model/tests/test_isotonic_regression.py +++ /dev/null @@ -1,28 +0,0 @@ -import numpy as np -from numpy.testing import assert_array_equal - -from sklearn.linear_model.isotonic_regression_ import isotonic_regression -from sklearn.linear_model import IsotonicRegression - -from nose.tools import assert_raises - - -def test_isotonic_regression(): - y = np.array([3, 7, 5, 9, 8, 7, 10]) - y_ = np.array([3, 6, 6, 8, 8, 8, 10]) - assert_array_equal(y_, isotonic_regression(y)) - - x = np.arange(len(y)) - ir = IsotonicRegression(y_min=0., y_max=1.) - ir.fit(x, y) - assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) - assert_array_equal(ir.transform(x), ir.predict(x)) - - -def test_assert_raises_exceptions(): - ir = IsotonicRegression() - rng = np.random.RandomState(42) - assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) - assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) - assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2]) - assert_raises(ValueError, ir.transform, rng.randn(3, 10)) diff --git a/sklearn/linear_model/tests/test_least_angle.py b/sklearn/linear_model/tests/test_least_angle.py index d532d48c9cab1..d7e49d5d25dea 100644 --- a/sklearn/linear_model/tests/test_least_angle.py +++ b/sklearn/linear_model/tests/test_least_angle.py @@ -1,8 +1,16 @@ -import numpy as np -from numpy.testing import assert_array_almost_equal -from nose.tools import assert_true +from nose.tools import assert_equal -from sklearn.utils.testing import assert_less, assert_greater +import numpy as np +from scipy import linalg + +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import ignore_warnings, assert_warns_message +from sklearn.utils.testing import assert_no_warnings, assert_warns +from sklearn.utils import ConvergenceWarning from sklearn import linear_model, datasets diabetes = datasets.load_diabetes() @@ -16,20 +24,31 @@ def test_simple(): Principle of Lars is to keep covariances tied and decreasing """ - alphas_, active, coef_path_ = linear_model.lars_path( - diabetes.data, diabetes.target, method="lar") - - for (i, coef_) in enumerate(coef_path_.T): - res = y - np.dot(X, coef_) - cov = np.dot(X.T, res) - C = np.max(abs(cov)) - eps = 1e-3 - ocur = len(cov[C - eps < abs(cov)]) - if i < X.shape[1]: - assert_true(ocur == i + 1) - else: - # no more than max_pred variables can go into the active set - assert_true(ocur == X.shape[1]) + # also test verbose output + from sklearn.externals.six.moves import cStringIO as StringIO + import sys + old_stdout = sys.stdout + try: + sys.stdout = StringIO() + + alphas_, active, coef_path_ = linear_model.lars_path( + diabetes.data, diabetes.target, method="lar", verbose=10) + + sys.stdout = old_stdout + + for (i, coef_) in enumerate(coef_path_.T): + res = y - np.dot(X, coef_) + cov = np.dot(X.T, res) + C = np.max(abs(cov)) + eps = 1e-3 + ocur = len(cov[C - eps < abs(cov)]) + if i < X.shape[1]: + assert_true(ocur == i + 1) + else: + # no more than max_pred variables can go into the active set + assert_true(ocur == X.shape[1]) + finally: + sys.stdout = old_stdout def test_simple_precomputed(): @@ -97,7 +116,8 @@ def test_collinearity(): [1., 1., 0]]) y = np.array([1., 0., 0]) - _, _, coef_path_ = linear_model.lars_path(X, y, alpha_min=0.01) + f = ignore_warnings + _, _, coef_path_ = f(linear_model.lars_path)(X, y, alpha_min=0.01) assert_true(not np.isnan(coef_path_).any()) residual = np.dot(X, coef_path_[:, -1]) - y assert_less((residual ** 2).sum(), 1.) # just make sure it's bounded @@ -106,8 +126,9 @@ def test_collinearity(): X = np.random.rand(n_samples, 5) y = np.zeros(n_samples) _, _, coef_path_ = linear_model.lars_path(X, y, Gram='auto', copy_X=False, - copy_Gram=False, alpha_min=0., method='lasso', verbose=0, - max_iter=500) + copy_Gram=False, alpha_min=0., + method='lasso', verbose=0, + max_iter=500) assert_array_almost_equal(coef_path_, np.zeros_like(coef_path_)) @@ -152,7 +173,7 @@ def test_no_path_all_precomputed(): alphas_, active_, coef_path_ = linear_model.lars_path( X, y, method="lasso", Gram=G, Xy=Xy, alpha_min=0.9) - print "---" + print("---") alpha_, active, coef = linear_model.lars_path( X, y, method="lasso", Gram=G, Xy=Xy, alpha_min=0.9, return_path=False) @@ -161,19 +182,44 @@ def test_no_path_all_precomputed(): def test_singular_matrix(): - """ - Test when input is a singular matrix - """ + # Test when input is a singular matrix X1 = np.array([[1, 1.], [1., 1.]]) y1 = np.array([1, 1]) alphas, active, coef_path = linear_model.lars_path(X1, y1) - assert_array_almost_equal(coef_path.T, [[0, 0], [1, 0], [1, 0]]) + assert_array_almost_equal(coef_path.T, [[0, 0], [1, 0]]) + + +def test_rank_deficient_design(): + # consistency test that checks that LARS Lasso is handling rank + # deficient input data (with n_features < rank) in the same way + # as coordinate descent Lasso + y = [5, 0, 5] + for X in ([[5, 0], + [0, 5], + [10, 10]], + + [[10, 10, 0], + [1e-32, 0, 0], + [0, 0, 1]], + ): + # To be able to use the coefs to compute the objective function, + # we need to turn off normalization + lars = linear_model.LassoLars(.1, normalize=False) + coef_lars_ = lars.fit(X, y).coef_ + obj_lars = (1. / (2. * 3.) + * linalg.norm(y - np.dot(X, coef_lars_)) ** 2 + + .1 * linalg.norm(coef_lars_, 1)) + coord_descent = linear_model.Lasso(.1, tol=1e-6, normalize=False) + coef_cd_ = coord_descent.fit(X, y).coef_ + obj_cd = ((1. / (2. * 3.)) * linalg.norm(y - np.dot(X, coef_cd_)) ** 2 + + .1 * linalg.norm(coef_cd_, 1)) + assert_less(obj_lars, obj_cd * (1. + 1e-8)) def test_lasso_lars_vs_lasso_cd(verbose=False): """ Test that LassoLars and Lasso using coordinate descent give the - same results + same results. """ X = 3 * diabetes.data @@ -184,15 +230,15 @@ def test_lasso_lars_vs_lasso_cd(verbose=False): continue lasso_cd.alpha = a lasso_cd.fit(X, y) - error = np.linalg.norm(c - lasso_cd.coef_) + error = linalg.norm(c - lasso_cd.coef_) assert_less(error, 0.01) # similar test, with the classifiers - for alpha in np.linspace(1e-2, 1 - 1e-2): + for alpha in np.linspace(1e-2, 1 - 1e-2, 20): clf1 = linear_model.LassoLars(alpha=alpha, normalize=False).fit(X, y) clf2 = linear_model.Lasso(alpha=alpha, tol=1e-8, normalize=False).fit(X, y) - err = np.linalg.norm(clf1.coef_ - clf2.coef_) + err = linalg.norm(clf1.coef_ - clf2.coef_) assert_less(err, 1e-3) # same test, with normalized data @@ -205,7 +251,7 @@ def test_lasso_lars_vs_lasso_cd(verbose=False): continue lasso_cd.alpha = a lasso_cd.fit(X, y) - error = np.linalg.norm(c - lasso_cd.coef_) + error = linalg.norm(c - lasso_cd.coef_) assert_less(error, 0.01) @@ -218,26 +264,99 @@ def test_lasso_lars_vs_lasso_cd_early_stopping(verbose=False): alphas_min = [10, 0.9, 1e-4] for alphas_min in alphas_min: alphas, _, lasso_path = linear_model.lars_path(X, y, method='lasso', - alpha_min=0.9) + alpha_min=0.9) lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8) lasso_cd.alpha = alphas[-1] lasso_cd.fit(X, y) - error = np.linalg.norm(lasso_path[:, -1] - lasso_cd.coef_) + error = linalg.norm(lasso_path[:, -1] - lasso_cd.coef_) assert_less(error, 0.01) alphas_min = [10, 0.9, 1e-4] # same test, with normalization for alphas_min in alphas_min: alphas, _, lasso_path = linear_model.lars_path(X, y, method='lasso', - alpha_min=0.9) + alpha_min=0.9) lasso_cd = linear_model.Lasso(fit_intercept=True, normalize=True, tol=1e-8) lasso_cd.alpha = alphas[-1] lasso_cd.fit(X, y) - error = np.linalg.norm(lasso_path[:, -1] - lasso_cd.coef_) + error = linalg.norm(lasso_path[:, -1] - lasso_cd.coef_) assert_less(error, 0.01) +def test_lasso_lars_path_length(): + # Test that the path length of the LassoLars is right + lasso = linear_model.LassoLars() + lasso.fit(X, y) + lasso2 = linear_model.LassoLars(alpha=lasso.alphas_[2]) + lasso2.fit(X, y) + assert_array_almost_equal(lasso.alphas_[:3], lasso2.alphas_) + # Also check that the sequence of alphas is always decreasing + assert_true(np.all(np.diff(lasso.alphas_) < 0)) + + +def test_lasso_lars_vs_lasso_cd_ill_conditioned(): + # Test lasso lars on a very ill-conditioned design, and check that + # it does not blow up, and stays somewhat close to a solution given + # by the coordinate descent solver + # Also test that lasso_path (using lars_path output style) gives + # the same result as lars_path and previous lasso output style + # under these conditions. + rng = np.random.RandomState(42) + + # Generate data + n, m = 70, 100 + k = 5 + X = rng.randn(n, m) + w = np.zeros((m, 1)) + i = np.arange(0, m) + rng.shuffle(i) + supp = i[:k] + w[supp] = np.sign(rng.randn(k, 1)) * (rng.rand(k, 1) + 1) + y = np.dot(X, w) + sigma = 0.2 + y += sigma * rng.rand(*y.shape) + y = y.squeeze() + lars_alphas, _, lars_coef = linear_model.lars_path(X, y, method='lasso') + + + _, lasso_coef2, _ = linear_model.lasso_path(X, y, + alphas=lars_alphas, + tol=1e-6, + fit_intercept=False) + + assert_array_almost_equal(lars_coef, lasso_coef2, decimal=1) + + +def test_lasso_lars_vs_lasso_cd_ill_conditioned2(): + # Create an ill-conditioned situation in which the LARS has to go + # far in the path to converge, and check that LARS and coordinate + # descent give the same answers + # Note it used to be the case that Lars had to use the drop for good + # strategy for this but this is no longer the case with the + # equality_tolerance checks + X = [[1e20, 1e20, 0], + [-1e-32, 0, 0], + [1, 1, 1]] + y = [10, 10, 1] + alpha = .0001 + + def objective_function(coef): + return (1. / (2. * len(X)) * linalg.norm(y - np.dot(X, coef)) ** 2 + + alpha * linalg.norm(coef, 1)) + + lars = linear_model.LassoLars(alpha=alpha, normalize=False) + assert_warns(ConvergenceWarning, lars.fit, X, y) + lars_coef_ = lars.coef_ + lars_obj = objective_function(lars_coef_) + + coord_descent = linear_model.Lasso(alpha=alpha, tol=1e-10, normalize=False) + cd_coef_ = coord_descent.fit(X, y).coef_ + cd_obj = objective_function(cd_coef_) + + assert_less(lars_obj, cd_obj * (1. + 1e-8)) + + def test_lars_add_features(): """ assure that at least some features get added if necessary @@ -255,7 +374,10 @@ def test_lars_add_features(): def test_lars_n_nonzero_coefs(verbose=False): lars = linear_model.Lars(n_nonzero_coefs=6, verbose=verbose) lars.fit(X, y) - assert_true(len(lars.coef_.nonzero()[0]) == 6) + assert_equal(len(lars.coef_.nonzero()[0]), 6) + # The path should be of length 6 + 1 in a Lars going down to 6 + # non-zero coefs + assert_equal(len(lars.alphas_), 7) def test_multitarget(): @@ -268,21 +390,26 @@ def test_multitarget(): for estimator in (linear_model.LassoLars(), linear_model.Lars()): estimator.fit(X, Y) + Y_pred = estimator.predict(X) + Y_dec = estimator.decision_function(X) + assert_array_almost_equal(Y_pred, Y_dec) alphas, active, coef, path = (estimator.alphas_, estimator.active_, estimator.coef_, estimator.coef_path_) - for k in xrange(n_targets): + for k in range(n_targets): estimator.fit(X, Y[:, k]) - assert_array_almost_equal(alphas[k, :], estimator.alphas_) - assert_array_almost_equal(active[k, :], estimator.active_) - assert_array_almost_equal(coef[k, :], estimator.coef_) - assert_array_almost_equal(path[k, :, :], estimator.coef_path_) + y_pred = estimator.predict(X) + assert_array_almost_equal(alphas[k], estimator.alphas_) + assert_array_almost_equal(active[k], estimator.active_) + assert_array_almost_equal(coef[k], estimator.coef_) + assert_array_almost_equal(path[k], estimator.coef_path_) + assert_array_almost_equal(Y_pred[:, k], y_pred) def test_lars_cv(): """ Test the LassoLarsCV object by checking that the optimal alpha increases as the number of samples increases. - This property is not actualy garantied in general and is just a + This property is not actually garantied in general and is just a property of the given dataset, with the given steps chosen. """ old_alpha = 0 @@ -315,6 +442,19 @@ def test_lasso_lars_ic(): assert_less(len(nonzero_bic), len(nonzero_aic)) assert_less(np.max(nonzero_bic), diabetes.data.shape[1]) + # test error on unknown IC + lars_broken = linear_model.LassoLarsIC('') + assert_raises(ValueError, lars_broken.fit, X, y) + + +def test_no_warning_for_zero_mse(): + """LassoLarsIC should not warn for log of zero MSE.""" + y = np.arange(10, dtype=float) + X = y.reshape(-1, 1) + lars = linear_model.LassoLarsIC(normalize=False) + assert_no_warnings(lars.fit, X, y) + assert_true(np.any(np.isinf(lars.criterion_))) + if __name__ == '__main__': import nose diff --git a/sklearn/linear_model/tests/test_logistic.py b/sklearn/linear_model/tests/test_logistic.py index 58611830be027..2ba808c9629df 100644 --- a/sklearn/linear_model/tests/test_logistic.py +++ b/sklearn/linear_model/tests/test_logistic.py @@ -1,20 +1,52 @@ import numpy as np import scipy.sparse as sp +from scipy import linalg, optimize, sparse -from numpy.testing import assert_array_equal -import nose -from nose.tools import assert_equal, assert_raises, raises - +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import raises +from sklearn.utils.testing import ignore_warnings +from sklearn.utils import ConvergenceWarning + +from sklearn.linear_model.logistic import ( + LogisticRegression, + logistic_regression_path, LogisticRegressionCV, + _logistic_loss_and_grad, _logistic_loss_grad_hess, + _multinomial_loss_grad_hess + ) +from sklearn.cross_validation import StratifiedKFold +from sklearn.datasets import load_iris, make_classification -from sklearn.linear_model import logistic -from sklearn import datasets X = [[-1, 0], [0, 1], [1, 1]] X_sp = sp.csr_matrix(X) Y1 = [0, 1, 1] Y2 = [2, 1, 0] -iris = datasets.load_iris() +iris = load_iris() + + +def check_predictions(clf, X, y): + """Check that the model is able to fit the classification data""" + n_samples = len(y) + classes = np.unique(y) + n_classes = classes.shape[0] + + predicted = clf.fit(X, y).predict(X) + assert_array_equal(clf.classes_, classes) + + assert_equal(predicted.shape, (n_samples,)) + assert_array_equal(predicted, y) + + probabilities = clf.predict_proba(X) + assert_equal(probabilities.shape, (n_samples, n_classes)) + assert_array_almost_equal(probabilities.sum(axis=1), np.ones(n_samples)) + assert_array_equal(probabilities.argmax(axis=1), y) def test_predict_2_classes(): @@ -22,58 +54,104 @@ def test_predict_2_classes(): Make sure it predicts the correct result on simple datasets. """ - clf = logistic.LogisticRegression().fit(X, Y1) - assert_array_equal(clf.predict(X), Y1) - assert_array_equal(clf.predict_proba(X).argmax(axis=1), Y1) - - clf = logistic.LogisticRegression().fit(X_sp, Y1) - assert_array_equal(clf.predict(X_sp), Y1) - assert_array_equal(clf.predict_proba(X_sp).argmax(axis=1), Y1) - - clf = logistic.LogisticRegression(C=100).fit(X, Y1) - assert_array_equal(clf.predict(X), Y1) - assert_array_equal(clf.predict_proba(X).argmax(axis=1), Y1) + check_predictions(LogisticRegression(random_state=0), X, Y1) + check_predictions(LogisticRegression(random_state=0), X_sp, Y1) - clf = logistic.LogisticRegression(C=100).fit(X_sp, Y1) - assert_array_equal(clf.predict(X_sp), Y1) - assert_array_equal(clf.predict_proba(X_sp).argmax(axis=1), Y1) + check_predictions(LogisticRegression(C=100, random_state=0), X, Y1) + check_predictions(LogisticRegression(C=100, random_state=0), X_sp, Y1) - clf = logistic.LogisticRegression(fit_intercept=False).fit(X, Y1) - assert_array_equal(clf.predict(X), Y1) - assert_array_equal(clf.predict_proba(X).argmax(axis=1), Y1) - - clf = logistic.LogisticRegression(fit_intercept=False).fit(X_sp, Y1) - assert_array_equal(clf.predict(X_sp), Y1) - assert_array_equal(clf.predict_proba(X_sp).argmax(axis=1), Y1) + check_predictions(LogisticRegression(fit_intercept=False, + random_state=0), X, Y1) + check_predictions(LogisticRegression(fit_intercept=False, + random_state=0), X_sp, Y1) def test_error(): """Test for appropriate exception on errors""" - assert_raises(ValueError, logistic.LogisticRegression(C=-1).fit, X, Y1) + assert_raises(ValueError, LogisticRegression(C=-1).fit, X, Y1) def test_predict_3_classes(): - clf = logistic.LogisticRegression(C=10).fit(X, Y2) - assert_array_equal(clf.predict(X), Y2) - assert_array_equal(clf.predict_proba(X).argmax(axis=1), Y2) - - clf = logistic.LogisticRegression(C=10).fit(X_sp, Y2) - assert_array_equal(clf.predict(X_sp), Y2) - assert_array_equal(clf.predict_proba(X_sp).argmax(axis=1), Y2) + check_predictions(LogisticRegression(C=10), X, Y2) + check_predictions(LogisticRegression(C=10), X_sp, Y2) def test_predict_iris(): - """Test logisic regression with the iris dataset""" + """Test logistic regression with the iris dataset""" + n_samples, n_features = iris.data.shape + + target = iris.target_names[iris.target] + + # Test that both multinomial and OvR solvers handle + # multiclass data correctly and give good accuracy + # score (>0.95) for the training data. + for clf in [LogisticRegression(C=len(iris.data)), + LogisticRegression(C=len(iris.data), solver='lbfgs', + multi_class='multinomial'), + LogisticRegression(C=len(iris.data), solver='newton-cg', + multi_class='multinomial')]: + clf.fit(iris.data, target) + assert_array_equal(np.unique(target), clf.classes_) + + pred = clf.predict(iris.data) + assert_greater(np.mean(pred == target), .95) + + probabilities = clf.predict_proba(iris.data) + assert_array_almost_equal(probabilities.sum(axis=1), + np.ones(n_samples)) + + pred = iris.target_names[probabilities.argmax(axis=1)] + assert_greater(np.mean(pred == target), .95) + + +def test_multinomial_validation(): + for solver in ['lbfgs', 'newton-cg']: + lr = LogisticRegression(C=-1, solver=solver, multi_class='multinomial') + assert_raises(ValueError, lr.fit, [[0, 1], [1, 0]], [0, 1]) + +def test_multinomial_binary(): + """Test multinomial LR on a binary problem.""" + target = (iris.target > 0).astype(np.intp) + target = np.array(["setosa", "not-setosa"])[target] + + for solver in ['lbfgs', 'newton-cg']: + clf = LogisticRegression(solver=solver, multi_class='multinomial') + clf.fit(iris.data, target) + + assert_equal(clf.coef_.shape, (1, iris.data.shape[1])) + assert_equal(clf.intercept_.shape, (1,)) + assert_array_equal(clf.predict(iris.data), target) + + mlr = LogisticRegression(solver=solver, multi_class='multinomial', + fit_intercept=False) + mlr.fit(iris.data, target) + pred = clf.classes_[np.argmax(clf.predict_log_proba(iris.data), + axis=1)] + assert_greater(np.mean(pred == target), .9) + + +def test_sparsify(): + """Test sparsify and densify members.""" + n_samples, n_features = iris.data.shape target = iris.target_names[iris.target] - clf = logistic.LogisticRegression(C=len(iris.data)).fit(iris.data, target) - assert_equal(set(target), set(clf.classes_)) + clf = LogisticRegression(random_state=0).fit(iris.data, target) - pred = clf.predict(iris.data) - assert_greater(np.mean(pred == target), .95) + pred_d_d = clf.decision_function(iris.data) - pred = iris.target_names[clf.predict_proba(iris.data).argmax(axis=1)] - assert_greater(np.mean(pred == target), .95) + clf.sparsify() + assert_true(sp.issparse(clf.coef_)) + pred_s_d = clf.decision_function(iris.data) + + sp_data = sp.coo_matrix(iris.data) + pred_s_s = clf.decision_function(sp_data) + + clf.densify() + pred_d_s = clf.decision_function(sp_data) + + assert_array_almost_equal(pred_d_d, pred_s_d) + assert_array_almost_equal(pred_d_d, pred_s_s) + assert_array_almost_equal(pred_d_d, pred_d_s) def test_inconsistent_input(): @@ -83,7 +161,7 @@ def test_inconsistent_input(): y_ = np.ones(X_.shape[0]) y_[0] = 0 - clf = logistic.LogisticRegression() + clf = LogisticRegression(random_state=0) # Wrong dimensions for training data y_wrong = y_[:-1] @@ -91,19 +169,16 @@ def test_inconsistent_input(): # Wrong dimensions for test data assert_raises(ValueError, clf.fit(X_, y_).predict, - rng.random_sample((3, 12))) + rng.random_sample((3, 12))) def test_write_parameters(): """Test that we can write to coef_ and intercept_""" - #rng = np.random.RandomState(0) - #X = rng.random_sample((5, 10)) - #y = np.ones(X.shape[0]) - clf = logistic.LogisticRegression() + clf = LogisticRegression(random_state=0) clf.fit(X, Y1) clf.coef_[:] = 0 clf.intercept_[:] = 0 - assert_array_equal(clf.decision_function(X), 0) + assert_array_almost_equal(clf.decision_function(X), 0) @raises(ValueError) @@ -114,8 +189,411 @@ def test_nan(): """ Xnan = np.array(X, dtype=np.float64) Xnan[0, 1] = np.nan - logistic.LogisticRegression().fit(Xnan, Y1) + LogisticRegression(random_state=0).fit(Xnan, Y1) + + +def test_consistency_path(): + """Test that the path algorithm is consistent""" + rng = np.random.RandomState(0) + X = np.concatenate((rng.randn(100, 2) + [1, 1], rng.randn(100, 2))) + y = [1] * 100 + [-1] * 100 + Cs = np.logspace(0, 4, 10) + + f = ignore_warnings + # can't test with fit_intercept=True since LIBLINEAR + # penalizes the intercept + for method in ('lbfgs', 'newton-cg', 'liblinear'): + coefs, Cs = f(logistic_regression_path)( + X, y, Cs=Cs, fit_intercept=False, tol=1e-16, solver=method) + for i, C in enumerate(Cs): + lr = LogisticRegression(C=C, fit_intercept=False, tol=1e-16) + lr.fit(X, y) + lr_coef = lr.coef_.ravel() + assert_array_almost_equal(lr_coef, coefs[i], decimal=4) + + # test for fit_intercept=True + for method in ('lbfgs', 'newton-cg', 'liblinear'): + Cs = [1e3] + coefs, Cs = f(logistic_regression_path)( + X, y, Cs=Cs, fit_intercept=True, tol=1e-4, solver=method) + lr = LogisticRegression(C=Cs[0], fit_intercept=True, tol=1e-4, + intercept_scaling=10000) + lr.fit(X, y) + lr_coef = np.concatenate([lr.coef_.ravel(), lr.intercept_]) + assert_array_almost_equal(lr_coef, coefs[0], decimal=4) + + +def test_liblinear_random_state(): + X, y = make_classification(n_samples=20) + lr1 = LogisticRegression(random_state=0) + lr1.fit(X, y) + lr2 = LogisticRegression(random_state=0) + lr2.fit(X, y) + assert_array_almost_equal(lr1.coef_, lr2.coef_) + + +def test_logistic_loss_and_grad(): + X_ref, y = make_classification(n_samples=20) + n_features = X_ref.shape[1] + + X_sp = X_ref.copy() + X_sp[X_sp < .1] = 0 + X_sp = sp.csr_matrix(X_sp) + for X in (X_ref, X_sp): + w = np.zeros(n_features) + + # First check that our derivation of the grad is correct + loss, grad = _logistic_loss_and_grad(w, X, y, alpha=1.) + approx_grad = optimize.approx_fprime( + w, lambda w: _logistic_loss_and_grad(w, X, y, alpha=1.)[0], 1e-3 + ) + assert_array_almost_equal(grad, approx_grad, decimal=2) + + # Second check that our intercept implementation is good + w = np.zeros(n_features + 1) + loss_interp, grad_interp = _logistic_loss_and_grad( + w, X, y, alpha=1. + ) + assert_array_almost_equal(loss, loss_interp) + + approx_grad = optimize.approx_fprime( + w, lambda w: _logistic_loss_and_grad(w, X, y, alpha=1.)[0], 1e-3 + ) + assert_array_almost_equal(grad_interp, approx_grad, decimal=2) + + +def test_logistic_loss_grad_hess(): + rng = np.random.RandomState(0) + n_samples, n_features = 50, 5 + X_ref = rng.randn(n_samples, n_features) + y = np.sign(X_ref.dot(5 * rng.randn(n_features))) + X_ref -= X_ref.mean() + X_ref /= X_ref.std() + X_sp = X_ref.copy() + X_sp[X_sp < .1] = 0 + X_sp = sp.csr_matrix(X_sp) + for X in (X_ref, X_sp): + w = .1 * np.ones(n_features) + + # First check that _logistic_loss_grad_hess is consistent + # with _logistic_loss_and_grad + loss, grad = _logistic_loss_and_grad(w, X, y, alpha=1.) + loss_2, grad_2, hess = _logistic_loss_grad_hess(w, X, y, alpha=1.) + assert_array_almost_equal(grad, grad_2) + + # Now check our hessian along the second direction of the grad + vector = np.zeros_like(grad) + vector[1] = 1 + hess_col = hess(vector) + + # Computation of the Hessian is particularly fragile to numerical + # errors when doing simple finite differences. Here we compute the + # grad along a path in the direction of the vector and then use a + # least-square regression to estimate the slope + e = 1e-3 + d_x = np.linspace(-e, e, 30) + d_grad = np.array([ + _logistic_loss_and_grad(w + t * vector, X, y, alpha=1.)[1] + for t in d_x + ]) + + d_grad -= d_grad.mean(axis=0) + approx_hess_col = linalg.lstsq(d_x[:, np.newaxis], d_grad)[0].ravel() + + assert_array_almost_equal(approx_hess_col, hess_col, decimal=3) + + # Second check that our intercept implementation is good + w = np.zeros(n_features + 1) + loss_interp, grad_interp = _logistic_loss_and_grad( + w, X, y, alpha=1. + ) + loss_interp_2, grad_interp_2, hess = \ + _logistic_loss_grad_hess(w, X, y, alpha=1.) + assert_array_almost_equal(loss_interp, loss_interp_2) + assert_array_almost_equal(grad_interp, grad_interp_2) + + +def test_logistic_cv(): + """test for LogisticRegressionCV object""" + n_samples, n_features = 50, 5 + rng = np.random.RandomState(0) + X_ref = rng.randn(n_samples, n_features) + y = np.sign(X_ref.dot(5 * rng.randn(n_features))) + X_ref -= X_ref.mean() + X_ref /= X_ref.std() + lr_cv = LogisticRegressionCV(Cs=[1.], fit_intercept=False, + solver='liblinear') + lr_cv.fit(X_ref, y) + lr = LogisticRegression(C=1., fit_intercept=False) + lr.fit(X_ref, y) + assert_array_almost_equal(lr.coef_, lr_cv.coef_) + + assert_array_equal(lr_cv.coef_.shape, (1, n_features)) + assert_array_equal(lr_cv.classes_, [-1, 1]) + assert_equal(len(lr_cv.classes_), 2) + + coefs_paths = np.asarray(list(lr_cv.coefs_paths_.values())) + assert_array_equal(coefs_paths.shape, (1, 3, 1, n_features)) + assert_array_equal(lr_cv.Cs_.shape, (1, )) + scores = np.asarray(list(lr_cv.scores_.values())) + assert_array_equal(scores.shape, (1, 3, 1)) + + +def test_logistic_cv_sparse(): + X, y = make_classification(n_samples=50, n_features=5, + random_state=0) + X[X < 1.0] = 0.0 + csr = sp.csr_matrix(X) + + clf = LogisticRegressionCV(fit_intercept=True) + clf.fit(X, y) + clfs = LogisticRegressionCV(fit_intercept=True) + clfs.fit(csr, y) + assert_array_almost_equal(clfs.coef_, clf.coef_) + assert_array_almost_equal(clfs.intercept_, clf.intercept_) + assert_equal(clfs.C_, clf.C_) + + +def test_intercept_logistic_helper(): + n_samples, n_features = 10, 5 + X, y = make_classification(n_samples=n_samples, n_features=n_features, + random_state=0) + + # Fit intercept case. + alpha = 1. + w = np.ones(n_features + 1) + loss_interp, grad_interp, hess_interp = _logistic_loss_grad_hess( + w, X, y, alpha) + + # Do not fit intercept. This can be considered equivalent to adding + # a feature vector of ones, i.e column of one vectors. + X_ = np.hstack((X, np.ones(10)[:, np.newaxis])) + loss, grad, hess = _logistic_loss_grad_hess(w, X_, y, alpha) + + # In the fit_intercept=False case, the feature vector of ones is + # penalized. This should be taken care of. + assert_almost_equal(loss_interp + 0.5 * (w[-1] ** 2), loss) + + # Check gradient. + assert_array_almost_equal(grad_interp[:n_features], grad[:n_features]) + assert_almost_equal(grad_interp[-1] + alpha * w[-1], grad[-1]) + + rng = np.random.RandomState(0) + grad = rng.rand(n_features + 1) + hess_interp = hess_interp(grad) + hess = hess(grad) + assert_array_almost_equal(hess_interp[:n_features], hess[:n_features]) + assert_almost_equal(hess_interp[-1] + alpha * grad[-1], hess[-1]) + + +def test_ovr_multinomial_iris(): + """Test that OvR and multinomial are correct using the iris dataset.""" + train, target = iris.data, iris.target + n_samples, n_features = train.shape + + # Use pre-defined fold as folds generated for different y + cv = StratifiedKFold(target, 3) + clf = LogisticRegressionCV(cv=cv) + clf.fit(train, target) + + clf1 = LogisticRegressionCV(cv=cv) + target_copy = target.copy() + target_copy[target_copy == 0] = 1 + clf1.fit(train, target_copy) + + assert_array_almost_equal(clf.scores_[2], clf1.scores_[2]) + assert_array_almost_equal(clf.intercept_[2:], clf1.intercept_) + assert_array_almost_equal(clf.coef_[2][np.newaxis, :], clf1.coef_) + + # Test the shape of various attributes. + assert_equal(clf.coef_.shape, (3, n_features)) + assert_array_equal(clf.classes_, [0, 1, 2]) + coefs_paths = np.asarray(list(clf.coefs_paths_.values())) + assert_array_almost_equal(coefs_paths.shape, (3, 3, 10, n_features + 1)) + assert_equal(clf.Cs_.shape, (10, )) + scores = np.asarray(list(clf.scores_.values())) + assert_equal(scores.shape, (3, 3, 10)) + + # Test that for the iris data multinomial gives a better accuracy than OvR + for solver in ['lbfgs', 'newton-cg']: + clf_multi = LogisticRegressionCV( + solver=solver, multi_class='multinomial', max_iter=15 + ) + clf_multi.fit(train, target) + multi_score = clf_multi.score(train, target) + ovr_score = clf.score(train, target) + assert_greater(multi_score, ovr_score) + + # Test attributes of LogisticRegressionCV + assert_equal(clf.coef_.shape, clf_multi.coef_.shape) + assert_array_equal(clf_multi.classes_, [0, 1, 2]) + coefs_paths = np.asarray(list(clf_multi.coefs_paths_.values())) + assert_array_almost_equal(coefs_paths.shape, (3, 3, 10, + n_features + 1)) + assert_equal(clf_multi.Cs_.shape, (10, )) + scores = np.asarray(list(clf_multi.scores_.values())) + assert_equal(scores.shape, (3, 3, 10)) + + +def test_logistic_regression_solvers(): + X, y = make_classification(n_features=10, n_informative=5, random_state=0) + clf_n = LogisticRegression(solver='newton-cg', fit_intercept=False) + clf_n.fit(X, y) + clf_lbf = LogisticRegression(solver='lbfgs', fit_intercept=False) + clf_lbf.fit(X, y) + clf_lib = LogisticRegression(fit_intercept=False) + clf_lib.fit(X, y) + assert_array_almost_equal(clf_n.coef_, clf_lib.coef_, decimal=3) + assert_array_almost_equal(clf_lib.coef_, clf_lbf.coef_, decimal=3) + assert_array_almost_equal(clf_n.coef_, clf_lbf.coef_, decimal=3) + + +def test_logistic_regression_solvers_multiclass(): + X, y = make_classification(n_samples=20, n_features=20, n_informative=10, + n_classes=3, random_state=0) + clf_n = LogisticRegression(solver='newton-cg', fit_intercept=False) + clf_n.fit(X, y) + clf_lbf = LogisticRegression(solver='lbfgs', fit_intercept=False) + clf_lbf.fit(X, y) + clf_lib = LogisticRegression(fit_intercept=False) + clf_lib.fit(X, y) + assert_array_almost_equal(clf_n.coef_, clf_lib.coef_, decimal=4) + assert_array_almost_equal(clf_lib.coef_, clf_lbf.coef_, decimal=4) + assert_array_almost_equal(clf_n.coef_, clf_lbf.coef_, decimal=4) + + +def test_logistic_regressioncv_class_weights(): + X, y = make_classification(n_samples=20, n_features=20, n_informative=10, + n_classes=3, random_state=0) + + # Test the liblinear fails when class_weight of type dict is + # provided, when it is multiclass. However it can handle + # binary problems. + clf_lib = LogisticRegressionCV(class_weight={0: 0.1, 1: 0.2}, + solver='liblinear') + assert_raises(ValueError, clf_lib.fit, X, y) + y_ = y.copy() + y_[y == 2] = 1 + clf_lib.fit(X, y_) + assert_array_equal(clf_lib.classes_, [0, 1]) + + # Test for class_weight=auto + X, y = make_classification(n_samples=20, n_features=20, n_informative=10, + random_state=0) + clf_lbf = LogisticRegressionCV(solver='lbfgs', fit_intercept=False, + class_weight='auto') + clf_lbf.fit(X, y) + clf_lib = LogisticRegressionCV(solver='liblinear', fit_intercept=False, + class_weight='auto') + clf_lib.fit(X, y) + assert_array_almost_equal(clf_lib.coef_, clf_lbf.coef_, decimal=4) + + +def test_logistic_regression_convergence_warnings(): + """Test that warnings are raised if model does not converge""" + + X, y = make_classification(n_samples=20, n_features=20) + clf_lib = LogisticRegression(solver='liblinear', max_iter=2, verbose=1) + assert_warns(ConvergenceWarning, clf_lib.fit, X, y) + assert_equal(clf_lib.n_iter_, 2) + + +def test_logistic_regression_multinomial(): + """Tests for the multinomial option in logistic regression""" + + # Some basic attributes of Logistic Regression + n_samples, n_features, n_classes = 50, 20, 3 + X, y = make_classification(n_samples=n_samples, + n_features=n_features, + n_informative=10, + n_classes=n_classes, random_state=0) + clf_int = LogisticRegression(solver='lbfgs', multi_class='multinomial') + clf_int.fit(X, y) + assert_array_equal(clf_int.coef_.shape, (n_classes, n_features)) + + clf_wint = LogisticRegression(solver='lbfgs', multi_class='multinomial', + fit_intercept=False) + clf_wint.fit(X, y) + assert_array_equal(clf_wint.coef_.shape, (n_classes, n_features)) + + # Similar tests for newton-cg solver option + clf_ncg_int = LogisticRegression(solver='newton-cg', + multi_class='multinomial') + clf_ncg_int.fit(X, y) + assert_array_equal(clf_ncg_int.coef_.shape, (n_classes, n_features)) + + clf_ncg_wint = LogisticRegression(solver='newton-cg', fit_intercept=False, + multi_class='multinomial') + clf_ncg_wint.fit(X, y) + assert_array_equal(clf_ncg_wint.coef_.shape, (n_classes, n_features)) + + # Compare solutions between lbfgs and newton-cg + assert_almost_equal(clf_int.coef_, clf_ncg_int.coef_, decimal=3) + assert_almost_equal(clf_wint.coef_, clf_ncg_wint.coef_, decimal=3) + assert_almost_equal(clf_int.intercept_, clf_ncg_int.intercept_, decimal=3) + + # Test that the path give almost the same results. However since in this + # case we take the average of the coefs after fitting across all the + # folds, it need not be exactly the same. + for solver in ['lbfgs', 'newton-cg']: + clf_path = LogisticRegressionCV(solver=solver, + multi_class='multinomial', Cs=[1.]) + clf_path.fit(X, y) + assert_array_almost_equal(clf_path.coef_, clf_int.coef_, decimal=3) + assert_almost_equal(clf_path.intercept_, clf_int.intercept_, decimal=3) + + +def test_multinomial_loss_grad_hess(): + rng = np.random.RandomState(0) + n_samples, n_features, n_classes = 100, 5, 3 + X = rng.randn(n_samples, n_features) + w = rng.rand(n_classes, n_features) + Y = np.zeros((n_samples, n_classes)) + ind = np.argmax(np.dot(X, w.T), axis=1) + Y[range(0, n_samples), ind] = 1 + w = w.ravel() + sample_weights = np.ones(X.shape[0]) + _, grad, hessp = _multinomial_loss_grad_hess(w, X, Y, alpha=1., + sample_weight=sample_weights) + # extract first column of hessian matrix + vec = np.zeros(n_features * n_classes) + vec[0] = 1 + hess_col = hessp(vec) + + # Estimate hessian using least squares as done in + # test_logistic_loss_grad_hess + e = 1e-3 + d_x = np.linspace(-e, e, 30) + d_grad = np.array([ + _multinomial_loss_grad_hess(w + t * vec, X, Y, alpha=1., + sample_weight=sample_weights)[1] + for t in d_x + ]) + d_grad -= d_grad.mean(axis=0) + approx_hess_col = linalg.lstsq(d_x[:, np.newaxis], d_grad)[0].ravel() + assert_array_almost_equal(hess_col, approx_hess_col) + + +def test_liblinear_decision_function_zero(): + """Test negative prediction when decision_function values are zero. + + Liblinear predicts the positive class when decision_function values + are zero. This is a test to verify that we do not do the same. + See Issue: https://github.com/scikit-learn/scikit-learn/issues/3600 + and the PR https://github.com/scikit-learn/scikit-learn/pull/3623 + """ + X, y = make_classification(n_samples=5, n_features=5) + clf = LogisticRegression(fit_intercept=False) + clf.fit(X, y) + + # Dummy data such that the decision function becomes zero. + X = np.zeros((5, 5)) + assert_array_equal(clf.predict(X), np.zeros(5)) + +def test_liblinear_logregcv_sparse(): + """Test LogRegCV with solver='liblinear' works for sparse matrices""" -if __name__ == '__main__': - nose.runmodule() + X, y = make_classification(n_samples=10, n_features=5) + clf = LogisticRegressionCV(solver='liblinear') + clf.fit(sparse.csr_matrix(X), y) diff --git a/sklearn/linear_model/tests/test_omp.py b/sklearn/linear_model/tests/test_omp.py index 0c2cb16d1a755..f267a9e04b896 100644 --- a/sklearn/linear_model/tests/test_omp.py +++ b/sklearn/linear_model/tests/test_omp.py @@ -1,18 +1,23 @@ # Author: Vlad Niculae -# License: BSD style - -import warnings +# Licence: BSD 3 clause import numpy as np -from nose.tools import assert_raises, assert_true -from numpy.testing import assert_equal, assert_array_almost_equal - -from sklearn.utils.testing import assert_greater - -from sklearn.linear_model import orthogonal_mp, orthogonal_mp_gram, \ - OrthogonalMatchingPursuit -from sklearn.utils.fixes import count_nonzero +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import ignore_warnings +from sklearn.utils.testing import check_skip_travis + + +from sklearn.linear_model import (orthogonal_mp, orthogonal_mp_gram, + OrthogonalMatchingPursuit, + OrthogonalMatchingPursuitCV, + LinearRegression) +from sklearn.utils import check_random_state from sklearn.datasets import make_sparse_coded_signal n_samples, n_features, n_nonzero_coefs, n_targets = 20, 30, 5, 3 @@ -38,16 +43,16 @@ def test_correct_shapes_gram(): def test_n_nonzero_coefs(): - assert_true(count_nonzero(orthogonal_mp(X, y[:, 0], - n_nonzero_coefs=5)) <= 5) - assert_true(count_nonzero(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5, - precompute_gram=True)) <= 5) + assert_true(np.count_nonzero(orthogonal_mp(X, y[:, 0], + n_nonzero_coefs=5)) <= 5) + assert_true(np.count_nonzero(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5, + precompute=True)) <= 5) def test_tol(): tol = 0.5 gamma = orthogonal_mp(X, y[:, 0], tol=tol) - gamma_gram = orthogonal_mp(X, y[:, 0], tol=tol, precompute_gram=True) + gamma_gram = orthogonal_mp(X, y[:, 0], tol=tol, precompute=True) assert_true(np.sum((y[:, 0] - np.dot(X, gamma)) ** 2) <= tol) assert_true(np.sum((y[:, 0] - np.dot(X, gamma_gram)) ** 2) <= tol) @@ -55,27 +60,25 @@ def test_tol(): def test_with_without_gram(): assert_array_almost_equal( orthogonal_mp(X, y, n_nonzero_coefs=5), - orthogonal_mp(X, y, n_nonzero_coefs=5, precompute_gram=True)) + orthogonal_mp(X, y, n_nonzero_coefs=5, precompute=True)) def test_with_without_gram_tol(): assert_array_almost_equal( orthogonal_mp(X, y, tol=1.), - orthogonal_mp(X, y, tol=1., precompute_gram=True)) + orthogonal_mp(X, y, tol=1., precompute=True)) def test_unreachable_accuracy(): - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - assert_array_almost_equal( - orthogonal_mp(X, y, tol=0), - orthogonal_mp(X, y, n_nonzero_coefs=n_features)) + assert_array_almost_equal( + orthogonal_mp(X, y, tol=0), + orthogonal_mp(X, y, n_nonzero_coefs=n_features)) - assert_array_almost_equal( - orthogonal_mp(X, y, tol=0, precompute_gram=True), - orthogonal_mp(X, y, precompute_gram=True, - n_nonzero_coefs=n_features)) - assert_greater(len(w), 0) # warnings should be raised + assert_array_almost_equal( + assert_warns(RuntimeWarning, orthogonal_mp, X, y, tol=0, + precompute=True), + orthogonal_mp(X, y, precompute=True, + n_nonzero_coefs=n_features)) def test_bad_input(): @@ -90,12 +93,11 @@ def test_bad_input(): def test_perfect_signal_recovery(): - # XXX: use signal generator idx, = gamma[:, 0].nonzero() gamma_rec = orthogonal_mp(X, y[:, 0], 5) gamma_gram = orthogonal_mp_gram(G, Xy[:, 0], 5) - assert_equal(idx, np.flatnonzero(gamma_rec)) - assert_equal(idx, np.flatnonzero(gamma_gram)) + assert_array_equal(idx, np.flatnonzero(gamma_rec)) + assert_array_equal(idx, np.flatnonzero(gamma_gram)) assert_array_almost_equal(gamma[:, 0], gamma_rec, decimal=2) assert_array_almost_equal(gamma[:, 0], gamma_gram, decimal=2) @@ -105,47 +107,24 @@ def test_estimator(): omp.fit(X, y[:, 0]) assert_equal(omp.coef_.shape, (n_features,)) assert_equal(omp.intercept_.shape, ()) - assert_true(count_nonzero(omp.coef_) <= n_nonzero_coefs) + assert_true(np.count_nonzero(omp.coef_) <= n_nonzero_coefs) omp.fit(X, y) assert_equal(omp.coef_.shape, (n_targets, n_features)) assert_equal(omp.intercept_.shape, (n_targets,)) - assert_true(count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs) + assert_true(np.count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs) omp.set_params(fit_intercept=False, normalize=False) - omp.fit(X, y[:, 0], Gram=G, Xy=Xy[:, 0]) + omp.fit(X, y[:, 0]) assert_equal(omp.coef_.shape, (n_features,)) assert_equal(omp.intercept_, 0) - assert_true(count_nonzero(omp.coef_) <= n_nonzero_coefs) + assert_true(np.count_nonzero(omp.coef_) <= n_nonzero_coefs) - omp.fit(X, y, Gram=G, Xy=Xy) + omp.fit(X, y) assert_equal(omp.coef_.shape, (n_targets, n_features)) assert_equal(omp.intercept_, 0) - assert_true(count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs) - - -def test_scaling_with_gram(): - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - # Use only 1 nonzero coef to be faster and to avoid warnings - omp1 = OrthogonalMatchingPursuit(n_nonzero_coefs=1, - fit_intercept=False, normalize=False) - omp2 = OrthogonalMatchingPursuit(n_nonzero_coefs=1, - fit_intercept=True, normalize=False) - omp3 = OrthogonalMatchingPursuit(n_nonzero_coefs=1, - fit_intercept=False, normalize=True) - omp1.fit(X, y, Gram=G) - omp1.fit(X, y, Gram=G, Xy=Xy) - assert_true(len(w) == 0) - omp2.fit(X, y, Gram=G) - assert_true(len(w) == 1) - omp2.fit(X, y, Gram=G, Xy=Xy) - assert_true(len(w) == 2) - omp3.fit(X, y, Gram=G) - assert_true(len(w) == 3) - omp3.fit(X, y, Gram=G, Xy=Xy) - assert_true(len(w) == 4) + assert_true(np.count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs) def test_identical_regressors(): @@ -154,10 +133,7 @@ def test_identical_regressors(): gamma = np.zeros(n_features) gamma[0] = gamma[1] = 1. newy = np.dot(newX, gamma) - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - orthogonal_mp(newX, newy, 2) - assert_true(len(w) == 1) + assert_warns(RuntimeWarning, orthogonal_mp, newX, newy, 2) def test_swapped_regressors(): @@ -171,16 +147,64 @@ def test_swapped_regressors(): new_Xy = np.dot(X.T, new_y) gamma_hat = orthogonal_mp(X, new_y, 2) gamma_hat_gram = orthogonal_mp_gram(G, new_Xy, 2) - assert_equal(np.flatnonzero(gamma_hat), [0, 21]) - assert_equal(np.flatnonzero(gamma_hat_gram), [0, 21]) + assert_array_equal(np.flatnonzero(gamma_hat), [0, 21]) + assert_array_equal(np.flatnonzero(gamma_hat_gram), [0, 21]) def test_no_atoms(): y_empty = np.zeros_like(y) Xy_empty = np.dot(X.T, y_empty) - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - gamma_empty = orthogonal_mp(X, y_empty, 1) - gamma_empty_gram = orthogonal_mp_gram(G, Xy_empty, 1) + gamma_empty = ignore_warnings(orthogonal_mp)(X, y_empty, 1) + gamma_empty_gram = ignore_warnings(orthogonal_mp)(G, Xy_empty, 1) assert_equal(np.all(gamma_empty == 0), True) assert_equal(np.all(gamma_empty_gram == 0), True) + + +def test_omp_path(): + path = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=True) + last = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=False) + assert_equal(path.shape, (n_features, n_targets, 5)) + assert_array_almost_equal(path[:, :, -1], last) + path = orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5, return_path=True) + last = orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5, return_path=False) + assert_equal(path.shape, (n_features, n_targets, 5)) + assert_array_almost_equal(path[:, :, -1], last) + + +def test_omp_return_path_prop_with_gram(): + path = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=True, + precompute=True) + last = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=False, + precompute=True) + assert_equal(path.shape, (n_features, n_targets, 5)) + assert_array_almost_equal(path[:, :, -1], last) + + +def test_omp_cv(): + # FIXME: This test is unstable on Travis, see issue #3190 for more detail. + check_skip_travis() + y_ = y[:, 0] + gamma_ = gamma[:, 0] + ompcv = OrthogonalMatchingPursuitCV(normalize=True, fit_intercept=False, + max_iter=10, cv=5) + ompcv.fit(X, y_) + assert_equal(ompcv.n_nonzero_coefs_, n_nonzero_coefs) + assert_array_almost_equal(ompcv.coef_, gamma_) + omp = OrthogonalMatchingPursuit(normalize=True, fit_intercept=False, + n_nonzero_coefs=ompcv.n_nonzero_coefs_) + omp.fit(X, y_) + assert_array_almost_equal(ompcv.coef_, omp.coef_) + + +def test_omp_reaches_least_squares(): + # Use small simple data; it's a sanity check but OMP can stop early + rng = check_random_state(0) + n_samples, n_features = (10, 8) + n_targets = 3 + X = rng.randn(n_samples, n_features) + Y = rng.randn(n_samples, n_targets) + omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_features) + lstsq = LinearRegression() + omp.fit(X, Y) + lstsq.fit(X, Y) + assert_array_almost_equal(omp.coef_, lstsq.coef_) diff --git a/sklearn/linear_model/tests/test_passive_aggressive.py b/sklearn/linear_model/tests/test_passive_aggressive.py new file mode 100644 index 0000000000000..c62cec838af87 --- /dev/null +++ b/sklearn/linear_model/tests/test_passive_aggressive.py @@ -0,0 +1,180 @@ +import numpy as np +import scipy.sparse as sp + +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_array_almost_equal, assert_array_equal +from sklearn.utils.testing import assert_raises + +from sklearn.base import ClassifierMixin +from sklearn.utils import check_random_state +from sklearn.datasets import load_iris +from sklearn.linear_model import PassiveAggressiveClassifier +from sklearn.linear_model import PassiveAggressiveRegressor + +iris = load_iris() +random_state = check_random_state(12) +indices = np.arange(iris.data.shape[0]) +random_state.shuffle(indices) +X = iris.data[indices] +y = iris.target[indices] +X_csr = sp.csr_matrix(X) + + +class MyPassiveAggressive(ClassifierMixin): + + def __init__(self, C=1.0, epsilon=0.01, loss="hinge", + fit_intercept=True, n_iter=1, random_state=None): + self.C = C + self.epsilon = epsilon + self.loss = loss + self.fit_intercept = fit_intercept + self.n_iter = n_iter + + def fit(self, X, y): + n_samples, n_features = X.shape + self.w = np.zeros(n_features, dtype=np.float64) + self.b = 0.0 + + for t in range(self.n_iter): + for i in range(n_samples): + p = self.project(X[i]) + if self.loss in ("hinge", "squared_hinge"): + loss = max(1 - y[i] * p, 0) + else: + loss = max(np.abs(p - y[i]) - self.epsilon, 0) + + sqnorm = np.dot(X[i], X[i]) + + if self.loss in ("hinge", "epsilon_insensitive"): + step = min(self.C, loss / sqnorm) + elif self.loss in ("squared_hinge", + "squared_epsilon_insensitive"): + step = loss / (sqnorm + 1.0 / (2 * self.C)) + + if self.loss in ("hinge", "squared_hinge"): + step *= y[i] + else: + step *= np.sign(y[i] - p) + + self.w += step * X[i] + if self.fit_intercept: + self.b += step + + def project(self, X): + return np.dot(X, self.w) + self.b + + +def test_classifier_accuracy(): + for data in (X, X_csr): + for fit_intercept in (True, False): + clf = PassiveAggressiveClassifier(C=1.0, n_iter=30, + fit_intercept=fit_intercept, + random_state=0) + clf.fit(data, y) + score = clf.score(data, y) + assert_greater(score, 0.79) + + +def test_classifier_partial_fit(): + classes = np.unique(y) + for data in (X, X_csr): + clf = PassiveAggressiveClassifier(C=1.0, + fit_intercept=True, + random_state=0) + for t in range(30): + clf.partial_fit(data, y, classes) + score = clf.score(data, y) + assert_greater(score, 0.79) + + +def test_classifier_refit(): + """Classifier can be retrained on different labels and features.""" + clf = PassiveAggressiveClassifier().fit(X, y) + assert_array_equal(clf.classes_, np.unique(y)) + + clf.fit(X[:, :-1], iris.target_names[y]) + assert_array_equal(clf.classes_, iris.target_names) + + +def test_classifier_correctness(): + y_bin = y.copy() + y_bin[y != 1] = -1 + + for loss in ("hinge", "squared_hinge"): + + clf1 = MyPassiveAggressive(C=1.0, + loss=loss, + fit_intercept=True, + n_iter=2) + clf1.fit(X, y_bin) + + for data in (X, X_csr): + clf2 = PassiveAggressiveClassifier(C=1.0, + loss=loss, + fit_intercept=True, + n_iter=2, shuffle=False) + clf2.fit(data, y_bin) + + assert_array_almost_equal(clf1.w, clf2.coef_.ravel(), decimal=2) + + +def test_classifier_undefined_methods(): + clf = PassiveAggressiveClassifier() + for meth in ("predict_proba", "predict_log_proba", "transform"): + assert_raises(AttributeError, lambda x: getattr(clf, x), meth) + + +def test_regressor_mse(): + y_bin = y.copy() + y_bin[y != 1] = -1 + + for data in (X, X_csr): + for fit_intercept in (True, False): + reg = PassiveAggressiveRegressor(C=1.0, n_iter=50, + fit_intercept=fit_intercept, + random_state=0) + reg.fit(data, y_bin) + pred = reg.predict(data) + assert_less(np.mean((pred - y_bin) ** 2), 1.7) + + +def test_regressor_partial_fit(): + y_bin = y.copy() + y_bin[y != 1] = -1 + + for data in (X, X_csr): + reg = PassiveAggressiveRegressor(C=1.0, + fit_intercept=True, + random_state=0) + for t in range(50): + reg.partial_fit(data, y_bin) + pred = reg.predict(data) + assert_less(np.mean((pred - y_bin) ** 2), 1.7) + + +def test_regressor_correctness(): + y_bin = y.copy() + y_bin[y != 1] = -1 + + for loss in ("epsilon_insensitive", "squared_epsilon_insensitive"): + reg1 = MyPassiveAggressive(C=1.0, + loss=loss, + fit_intercept=True, + n_iter=2) + reg1.fit(X, y_bin) + + for data in (X, X_csr): + reg2 = PassiveAggressiveRegressor(C=1.0, + loss=loss, + fit_intercept=True, + n_iter=2, shuffle=False) + reg2.fit(data, y_bin) + + assert_array_almost_equal(reg1.w, reg2.coef_.ravel(), decimal=2) + + +def test_regressor_undefined_methods(): + reg = PassiveAggressiveRegressor() + for meth in ("transform",): + assert_raises(AttributeError, lambda x: getattr(reg, x), meth) diff --git a/sklearn/linear_model/tests/test_perceptron.py b/sklearn/linear_model/tests/test_perceptron.py index 94e557679d232..a5b97c431af3a 100644 --- a/sklearn/linear_model/tests/test_perceptron.py +++ b/sklearn/linear_model/tests/test_perceptron.py @@ -1,8 +1,9 @@ import numpy as np import scipy.sparse as sp -from numpy.testing import assert_array_almost_equal -from nose.tools import assert_true +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_raises from sklearn.utils import check_random_state from sklearn.datasets import load_iris @@ -44,7 +45,7 @@ def predict(self, X): def test_perceptron_accuracy(): for data in (X, X_csr): - clf = Perceptron(n_iter=30, shuffle=False, seed=0) + clf = Perceptron(n_iter=30, shuffle=False) clf.fit(data, y) score = clf.score(data, y) assert_true(score >= 0.7) @@ -57,7 +58,13 @@ def test_perceptron_correctness(): clf1 = MyPerceptron(n_iter=2) clf1.fit(X, y_bin) - clf2 = Perceptron(n_iter=2) + clf2 = Perceptron(n_iter=2, shuffle=False) clf2.fit(X, y_bin) assert_array_almost_equal(clf1.w, clf2.coef_.ravel()) + + +def test_undefined_methods(): + clf = Perceptron() + for meth in ("predict_proba", "predict_log_proba"): + assert_raises(AttributeError, lambda x: getattr(clf, x), meth) diff --git a/sklearn/linear_model/tests/test_randomized_l1.py b/sklearn/linear_model/tests/test_randomized_l1.py index df6680a432ebe..3f202b3bf4000 100644 --- a/sklearn/linear_model/tests/test_randomized_l1.py +++ b/sklearn/linear_model/tests/test_randomized_l1.py @@ -1,14 +1,20 @@ # Authors: Alexandre Gramfort -# License: BSD Style. +# License: BSD 3 clause import numpy as np -from numpy.testing import assert_equal, assert_raises +from scipy import sparse -from sklearn.linear_model.randomized_l1 import lasso_stability_path, \ - RandomizedLasso, RandomizedLogisticRegression +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_raises + +from sklearn.linear_model.randomized_l1 import (lasso_stability_path, + RandomizedLasso, + RandomizedLogisticRegression) from sklearn.datasets import load_diabetes, load_iris from sklearn.feature_selection import f_regression, f_classif from sklearn.preprocessing import StandardScaler +from sklearn.linear_model.base import center_data diabetes = load_diabetes() X = diabetes.data @@ -25,10 +31,11 @@ def test_lasso_stability_path(): # Load diabetes data and add noisy features scaling = 0.3 coef_grid, scores_path = lasso_stability_path(X, y, scaling=scaling, - random_state=42, n_resampling=30) + random_state=42, + n_resampling=30) - assert_equal(np.argsort(F)[-3:], - np.argsort(np.sum(scores_path, axis=1))[-3:]) + assert_array_equal(np.argsort(F)[-3:], + np.argsort(np.sum(scores_path, axis=1))[-3:]) def test_randomized_lasso(): @@ -38,16 +45,18 @@ def test_randomized_lasso(): # or with 1 alpha clf = RandomizedLasso(verbose=False, alpha=1, random_state=42, - scaling=scaling, selection_threshold=selection_threshold) + scaling=scaling, + selection_threshold=selection_threshold) feature_scores = clf.fit(X, y).scores_ - assert_equal(np.argsort(F)[-3:], np.argsort(feature_scores)[-3:]) + assert_array_equal(np.argsort(F)[-3:], np.argsort(feature_scores)[-3:]) # or with many alphas clf = RandomizedLasso(verbose=False, alpha=[1, 0.8], random_state=42, - scaling=scaling, selection_threshold=selection_threshold) + scaling=scaling, + selection_threshold=selection_threshold) feature_scores = clf.fit(X, y).scores_ assert_equal(clf.all_scores_.shape, (X.shape[1], 2)) - assert_equal(np.argsort(F)[-3:], np.argsort(feature_scores)[-3:]) + assert_array_equal(np.argsort(F)[-3:], np.argsort(feature_scores)[-3:]) X_r = clf.transform(X) X_full = clf.inverse_transform(X_r) @@ -57,7 +66,7 @@ def test_randomized_lasso(): clf = RandomizedLasso(verbose=False, alpha='aic', random_state=42, scaling=scaling) feature_scores = clf.fit(X, y).scores_ - assert_equal(feature_scores, X.shape[1] * [1.]) + assert_array_equal(feature_scores, X.shape[1] * [1.]) clf = RandomizedLasso(verbose=False, scaling=-0.1) assert_raises(ValueError, clf.fit, X, y) @@ -78,11 +87,42 @@ def test_randomized_logistic(): scaling = 0.3 clf = RandomizedLogisticRegression(verbose=False, C=1., random_state=42, - scaling=scaling, n_resampling=50, tol=1e-3) + scaling=scaling, n_resampling=50, + tol=1e-3) + X_orig = X.copy() feature_scores = clf.fit(X, y).scores_ - assert_equal(np.argsort(F), np.argsort(feature_scores)) + assert_array_equal(X, X_orig) # fit does not modify X + assert_array_equal(np.argsort(F), np.argsort(feature_scores)) clf = RandomizedLogisticRegression(verbose=False, C=[1., 0.5], - random_state=42, scaling=scaling, n_resampling=50, tol=1e-3) + random_state=42, scaling=scaling, + n_resampling=50, tol=1e-3) feature_scores = clf.fit(X, y).scores_ - assert_equal(np.argsort(F), np.argsort(feature_scores)) + assert_array_equal(np.argsort(F), np.argsort(feature_scores)) + + +def test_randomized_logistic_sparse(): + """Check randomized sparse logistic regression on sparse data""" + iris = load_iris() + X = iris.data[:, [0, 2]] + y = iris.target + X = X[y != 2] + y = y[y != 2] + + # center here because sparse matrices are usually not centered + X, y, _, _, _ = center_data(X, y, True, True) + + X_sp = sparse.csr_matrix(X) + + F, _ = f_classif(X, y) + + scaling = 0.3 + clf = RandomizedLogisticRegression(verbose=False, C=1., random_state=42, + scaling=scaling, n_resampling=50, + tol=1e-3) + feature_scores = clf.fit(X, y).scores_ + clf = RandomizedLogisticRegression(verbose=False, C=1., random_state=42, + scaling=scaling, n_resampling=50, + tol=1e-3) + feature_scores_sp = clf.fit(X_sp, y).scores_ + assert_array_equal(feature_scores, feature_scores_sp) diff --git a/sklearn/linear_model/tests/test_ransac.py b/sklearn/linear_model/tests/test_ransac.py new file mode 100644 index 0000000000000..001ac70d99aeb --- /dev/null +++ b/sklearn/linear_model/tests/test_ransac.py @@ -0,0 +1,346 @@ +import numpy as np +from numpy.testing import assert_equal, assert_raises +from numpy.testing import assert_array_almost_equal +from scipy import sparse + +from sklearn.utils.testing import assert_less +from sklearn.linear_model import LinearRegression, RANSACRegressor +from sklearn.linear_model.ransac import _dynamic_max_trials + + +# Generate coordinates of line +X = np.arange(-200, 200) +y = 0.2 * X + 20 +data = np.column_stack([X, y]) + +# Add some faulty data +outliers = np.array((10, 30, 200)) +data[outliers[0], :] = (1000, 1000) +data[outliers[1], :] = (-1000, -1000) +data[outliers[2], :] = (-100, -50) + +X = data[:, 0][:, np.newaxis] +y = data[:, 1] + + +def test_ransac_inliers_outliers(): + + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, random_state=0) + + # Estimate parameters of corrupted data + ransac_estimator.fit(X, y) + + # Ground truth / reference inlier mask + ref_inlier_mask = np.ones_like(ransac_estimator.inlier_mask_ + ).astype(np.bool_) + ref_inlier_mask[outliers] = False + + assert_equal(ransac_estimator.inlier_mask_, ref_inlier_mask) + + +def test_ransac_is_data_valid(): + def is_data_valid(X, y): + assert_equal(X.shape[0], 2) + assert_equal(y.shape[0], 2) + return False + + X = np.random.rand(10, 2) + y = np.random.rand(10, 1) + + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, + is_data_valid=is_data_valid, + random_state=0) + + assert_raises(ValueError, ransac_estimator.fit, X, y) + + +def test_ransac_is_model_valid(): + def is_model_valid(estimator, X, y): + assert_equal(X.shape[0], 2) + assert_equal(y.shape[0], 2) + return False + + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, + is_model_valid=is_model_valid, + random_state=0) + + assert_raises(ValueError, ransac_estimator.fit, X, y) + + +def test_ransac_max_trials(): + base_estimator = LinearRegression() + + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, max_trials=0, + random_state=0) + assert_raises(ValueError, ransac_estimator.fit, X, y) + + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, max_trials=11, + random_state=0) + assert getattr(ransac_estimator, 'n_trials_', None) is None + ransac_estimator.fit(X, y) + assert_equal(ransac_estimator.n_trials_, 2) + + +def test_ransac_stop_n_inliers(): + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, stop_n_inliers=2, + random_state=0) + ransac_estimator.fit(X, y) + + assert_equal(ransac_estimator.n_trials_, 1) + + +def test_ransac_stop_score(): + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, stop_score=0, + random_state=0) + ransac_estimator.fit(X, y) + + assert_equal(ransac_estimator.n_trials_, 1) + + +def test_ransac_score(): + X = np.arange(100)[:, None] + y = np.zeros((100, )) + y[0] = 1 + y[1] = 100 + + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=0.5, random_state=0) + ransac_estimator.fit(X, y) + + assert_equal(ransac_estimator.score(X[2:], y[2:]), 1) + assert_less(ransac_estimator.score(X[:2], y[:2]), 1) + + +def test_ransac_predict(): + X = np.arange(100)[:, None] + y = np.zeros((100, )) + y[0] = 1 + y[1] = 100 + + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=0.5, random_state=0) + ransac_estimator.fit(X, y) + + assert_equal(ransac_estimator.predict(X), np.zeros((100, 1))) + + +def test_ransac_sparse_coo(): + X_sparse = sparse.coo_matrix(X) + + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, random_state=0) + ransac_estimator.fit(X_sparse, y) + + ref_inlier_mask = np.ones_like(ransac_estimator.inlier_mask_ + ).astype(np.bool_) + ref_inlier_mask[outliers] = False + + assert_equal(ransac_estimator.inlier_mask_, ref_inlier_mask) + + +def test_ransac_sparse_csr(): + X_sparse = sparse.csr_matrix(X) + + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, random_state=0) + ransac_estimator.fit(X_sparse, y) + + ref_inlier_mask = np.ones_like(ransac_estimator.inlier_mask_ + ).astype(np.bool_) + ref_inlier_mask[outliers] = False + + assert_equal(ransac_estimator.inlier_mask_, ref_inlier_mask) + + +def test_ransac_sparse_csc(): + X_sparse = sparse.csc_matrix(X) + + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, random_state=0) + ransac_estimator.fit(X_sparse, y) + + ref_inlier_mask = np.ones_like(ransac_estimator.inlier_mask_ + ).astype(np.bool_) + ref_inlier_mask[outliers] = False + + assert_equal(ransac_estimator.inlier_mask_, ref_inlier_mask) + + +def test_ransac_none_estimator(): + + base_estimator = LinearRegression() + + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, random_state=0) + ransac_none_estimator = RANSACRegressor(None, 2, 5, random_state=0) + + ransac_estimator.fit(X, y) + ransac_none_estimator.fit(X, y) + + assert_array_almost_equal(ransac_estimator.predict(X), + ransac_none_estimator.predict(X)) + + +def test_ransac_min_n_samples(): + base_estimator = LinearRegression() + ransac_estimator1 = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, random_state=0) + ransac_estimator2 = RANSACRegressor(base_estimator, + min_samples=2. / X.shape[0], + residual_threshold=5, random_state=0) + ransac_estimator3 = RANSACRegressor(base_estimator, min_samples=-1, + residual_threshold=5, random_state=0) + ransac_estimator4 = RANSACRegressor(base_estimator, min_samples=5.2, + residual_threshold=5, random_state=0) + ransac_estimator5 = RANSACRegressor(base_estimator, min_samples=2.0, + residual_threshold=5, random_state=0) + ransac_estimator6 = RANSACRegressor(base_estimator, + residual_threshold=5, random_state=0) + ransac_estimator7 = RANSACRegressor(base_estimator, + min_samples=X.shape[0] + 1, + residual_threshold=5, random_state=0) + + ransac_estimator1.fit(X, y) + ransac_estimator2.fit(X, y) + ransac_estimator5.fit(X, y) + ransac_estimator6.fit(X, y) + + assert_array_almost_equal(ransac_estimator1.predict(X), + ransac_estimator2.predict(X)) + assert_array_almost_equal(ransac_estimator1.predict(X), + ransac_estimator5.predict(X)) + assert_array_almost_equal(ransac_estimator1.predict(X), + ransac_estimator6.predict(X)) + + assert_raises(ValueError, ransac_estimator3.fit, X, y) + assert_raises(ValueError, ransac_estimator4.fit, X, y) + assert_raises(ValueError, ransac_estimator7.fit, X, y) + + +def test_ransac_multi_dimensional_targets(): + + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, random_state=0) + + # 3-D target values + yyy = np.column_stack([y, y, y]) + + # Estimate parameters of corrupted data + ransac_estimator.fit(X, yyy) + + # Ground truth / reference inlier mask + ref_inlier_mask = np.ones_like(ransac_estimator.inlier_mask_ + ).astype(np.bool_) + ref_inlier_mask[outliers] = False + + assert_equal(ransac_estimator.inlier_mask_, ref_inlier_mask) + + +def test_ransac_residual_metric(): + residual_metric1 = lambda dy: np.sum(np.abs(dy), axis=1) + residual_metric2 = lambda dy: np.sum(dy ** 2, axis=1) + + yyy = np.column_stack([y, y, y]) + + base_estimator = LinearRegression() + ransac_estimator0 = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, random_state=0) + ransac_estimator1 = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, random_state=0, + residual_metric=residual_metric1) + ransac_estimator2 = RANSACRegressor(base_estimator, min_samples=2, + residual_threshold=5, random_state=0, + residual_metric=residual_metric2) + + # multi-dimensional + ransac_estimator0.fit(X, yyy) + ransac_estimator1.fit(X, yyy) + ransac_estimator2.fit(X, yyy) + assert_array_almost_equal(ransac_estimator0.predict(X), + ransac_estimator1.predict(X)) + assert_array_almost_equal(ransac_estimator0.predict(X), + ransac_estimator2.predict(X)) + + # one-dimensional + ransac_estimator0.fit(X, y) + ransac_estimator2.fit(X, y) + assert_array_almost_equal(ransac_estimator0.predict(X), + ransac_estimator2.predict(X)) + + +def test_ransac_default_residual_threshold(): + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + random_state=0) + + # Estimate parameters of corrupted data + ransac_estimator.fit(X, y) + + # Ground truth / reference inlier mask + ref_inlier_mask = np.ones_like(ransac_estimator.inlier_mask_ + ).astype(np.bool_) + ref_inlier_mask[outliers] = False + + assert_equal(ransac_estimator.inlier_mask_, ref_inlier_mask) + + +def test_ransac_dynamic_max_trials(): + # Numbers hand-calculated and confirmed on page 119 (Table 4.3) in + # Hartley, R.~I. and Zisserman, A., 2004, + # Multiple View Geometry in Computer Vision, Second Edition, + # Cambridge University Press, ISBN: 0521540518 + + # e = 0%, min_samples = X + assert_equal(_dynamic_max_trials(100, 100, 2, 0.99), 1) + + # e = 5%, min_samples = 2 + assert_equal(_dynamic_max_trials(95, 100, 2, 0.99), 2) + # e = 10%, min_samples = 2 + assert_equal(_dynamic_max_trials(90, 100, 2, 0.99), 3) + # e = 30%, min_samples = 2 + assert_equal(_dynamic_max_trials(70, 100, 2, 0.99), 7) + # e = 50%, min_samples = 2 + assert_equal(_dynamic_max_trials(50, 100, 2, 0.99), 17) + + # e = 5%, min_samples = 8 + assert_equal(_dynamic_max_trials(95, 100, 8, 0.99), 5) + # e = 10%, min_samples = 8 + assert_equal(_dynamic_max_trials(90, 100, 8, 0.99), 9) + # e = 30%, min_samples = 8 + assert_equal(_dynamic_max_trials(70, 100, 8, 0.99), 78) + # e = 50%, min_samples = 8 + assert_equal(_dynamic_max_trials(50, 100, 8, 0.99), 1177) + + # e = 0%, min_samples = 10 + assert_equal(_dynamic_max_trials(1, 100, 10, 0), 0) + assert_equal(_dynamic_max_trials(1, 100, 10, 1), float('inf')) + + base_estimator = LinearRegression() + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + stop_probability=-0.1) + assert_raises(ValueError, ransac_estimator.fit, X, y) + ransac_estimator = RANSACRegressor(base_estimator, min_samples=2, + stop_probability=1.1) + assert_raises(ValueError, ransac_estimator.fit, X, y) + + +if __name__ == "__main__": + np.testing.run_module_suite() diff --git a/sklearn/linear_model/tests/test_ridge.py b/sklearn/linear_model/tests/test_ridge.py index a192b0f692ec0..677fa88b70511 100644 --- a/sklearn/linear_model/tests/test_ridge.py +++ b/sklearn/linear_model/tests/test_ridge.py @@ -1,26 +1,39 @@ import numpy as np import scipy.sparse as sp -from nose.tools import assert_true -from numpy.testing import assert_almost_equal, assert_array_almost_equal, \ - assert_equal, assert_array_equal +from scipy import linalg + +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_raise_message +from sklearn.utils.testing import ignore_warnings + from sklearn import datasets from sklearn.metrics import mean_squared_error -from sklearn.utils.testing import assert_greater +from sklearn.metrics import make_scorer +from sklearn.metrics import get_scorer from sklearn.linear_model.base import LinearRegression +from sklearn.linear_model.ridge import ridge_regression from sklearn.linear_model.ridge import Ridge from sklearn.linear_model.ridge import _RidgeGCV from sklearn.linear_model.ridge import RidgeCV from sklearn.linear_model.ridge import RidgeClassifier from sklearn.linear_model.ridge import RidgeClassifierCV - +from sklearn.linear_model.ridge import _solve_cholesky +from sklearn.linear_model.ridge import _solve_cholesky_kernel from sklearn.cross_validation import KFold -rng = np.random.RandomState(0) + diabetes = datasets.load_diabetes() X_diabetes, y_diabetes = diabetes.data, diabetes.target ind = np.arange(X_diabetes.shape[0]) +rng = np.random.RandomState(0) rng.shuffle(ind) ind = ind[:200] X_diabetes, y_diabetes = X_diabetes[ind], y_diabetes[ind] @@ -40,36 +53,116 @@ def test_ridge(): TODO: for this test to be robust, we should use a dataset instead of np.random. """ + rng = np.random.RandomState(0) alpha = 1.0 - # With more samples than features - n_samples, n_features = 6, 5 - y = rng.randn(n_samples) - X = rng.randn(n_samples, n_features) - - ridge = Ridge(alpha=alpha) + for solver in ("svd", "sparse_cg", "cholesky", "lsqr"): + # With more samples than features + n_samples, n_features = 6, 5 + y = rng.randn(n_samples) + X = rng.randn(n_samples, n_features) + + ridge = Ridge(alpha=alpha, solver=solver) + ridge.fit(X, y) + assert_equal(ridge.coef_.shape, (X.shape[1], )) + assert_greater(ridge.score(X, y), 0.47) + + if solver == "cholesky": + # Currently the only solver to support sample_weight. + ridge.fit(X, y, sample_weight=np.ones(n_samples)) + assert_greater(ridge.score(X, y), 0.47) + + # With more features than samples + n_samples, n_features = 5, 10 + y = rng.randn(n_samples) + X = rng.randn(n_samples, n_features) + ridge = Ridge(alpha=alpha, solver=solver) + ridge.fit(X, y) + assert_greater(ridge.score(X, y), .9) + + if solver == "cholesky": + # Currently the only solver to support sample_weight. + ridge.fit(X, y, sample_weight=np.ones(n_samples)) + assert_greater(ridge.score(X, y), 0.9) + + +def test_primal_dual_relationship(): + y = y_diabetes.reshape(-1, 1) + coef = _solve_cholesky(X_diabetes, y, alpha=[1e-2]) + K = np.dot(X_diabetes, X_diabetes.T) + dual_coef = _solve_cholesky_kernel(K, y, alpha=[1e-2]) + coef2 = np.dot(X_diabetes.T, dual_coef).T + assert_array_almost_equal(coef, coef2) + + +def test_ridge_singular(): + # test on a singular matrix + rng = np.random.RandomState(0) + n_samples, n_features = 6, 6 + y = rng.randn(n_samples // 2) + y = np.concatenate((y, y)) + X = rng.randn(n_samples // 2, n_features) + X = np.concatenate((X, X), axis=0) + + ridge = Ridge(alpha=0) ridge.fit(X, y) - assert_equal(ridge.coef_.shape, (X.shape[1], )) - assert_greater(ridge.score(X, y), 0.5) + assert_greater(ridge.score(X, y), 0.9) - ridge.fit(X, y, sample_weight=np.ones(n_samples)) - assert_greater(ridge.score(X, y), 0.5) - # With more features than samples - n_samples, n_features = 5, 10 - y = rng.randn(n_samples) - X = rng.randn(n_samples, n_features) - ridge = Ridge(alpha=alpha) - ridge.fit(X, y) - assert_greater(ridge.score(X, y), .9) - - ridge.fit(X, y, sample_weight=np.ones(n_samples)) - assert_greater(ridge.score(X, y), 0.9) +def test_ridge_sample_weights(): + rng = np.random.RandomState(0) + + for solver in ("cholesky", ): + for n_samples, n_features in ((6, 5), (5, 10)): + for alpha in (1.0, 1e-2): + y = rng.randn(n_samples) + X = rng.randn(n_samples, n_features) + sample_weight = 1 + rng.rand(n_samples) + + coefs = ridge_regression(X, y, + alpha=alpha, + sample_weight=sample_weight, + solver=solver) + # Sample weight can be implemented via a simple rescaling + # for the square loss. + coefs2 = ridge_regression( + X * np.sqrt(sample_weight)[:, np.newaxis], + y * np.sqrt(sample_weight), + alpha=alpha, solver=solver) + assert_array_almost_equal(coefs, coefs2) + + # Test for fit_intercept = True + est = Ridge(alpha=alpha, solver=solver) + est.fit(X, y, sample_weight=sample_weight) + + # Check using Newton's Method + # Quadratic function should be solved in a single step. + # Initialize + sample_weight = np.sqrt(sample_weight) + X_weighted = sample_weight[:, np.newaxis] * ( + np.column_stack((np.ones(n_samples), X))) + y_weighted = y * sample_weight + + # Gradient is (X*coef-y)*X + alpha*coef_[1:] + # Remove coef since it is initialized to zero. + grad = -np.dot(y_weighted, X_weighted) + + # Hessian is (X.T*X) + alpha*I except that the first + # diagonal element should be zero, since there is no + # penalization of intercept. + diag = alpha * np.ones(n_features + 1) + diag[0] = 0. + hess = np.dot(X_weighted.T, X_weighted) + hess.flat[::n_features + 2] += diag + coef_ = - np.dot(linalg.inv(hess), grad) + assert_almost_equal(coef_[0], est.intercept_) + assert_array_almost_equal(coef_[1:], est.coef_) def test_ridge_shapes(): """Test shape of coef_ and intercept_ """ + rng = np.random.RandomState(0) n_samples, n_features = 5, 10 X = rng.randn(n_samples, n_features) y = rng.randn(n_samples) @@ -94,6 +187,7 @@ def test_ridge_shapes(): def test_ridge_intercept(): """Test intercept with multiple targets GH issue #708 """ + rng = np.random.RandomState(0) n_samples, n_features = 5, 10 X = rng.randn(n_samples, n_features) y = rng.randn(n_samples) @@ -136,6 +230,7 @@ def test_toy_ridge_object(): def test_ridge_vs_lstsq(): """On alpha=0., Ridge and OLS yield the same solution.""" + rng = np.random.RandomState(0) # we need more samples than features n_samples, n_features = 5, 4 y = rng.randn(n_samples) @@ -153,6 +248,32 @@ def test_ridge_vs_lstsq(): assert_almost_equal(ridge.coef_, ols.coef_) +def test_ridge_individual_penalties(): + """Tests the ridge object using individual penalties""" + + rng = np.random.RandomState(42) + + n_samples, n_features, n_targets = 20, 10, 5 + X = rng.randn(n_samples, n_features) + y = rng.randn(n_samples, n_targets) + + penalties = np.arange(n_targets) + + coef_cholesky = np.array([ + Ridge(alpha=alpha, solver="cholesky").fit(X, target).coef_ + for alpha, target in zip(penalties, y.T)]) + + coefs_indiv_pen = [ + Ridge(alpha=penalties, solver=solver, tol=1e-6).fit(X, y).coef_ + for solver in ['svd', 'sparse_cg', 'lsqr', 'cholesky']] + for coef_indiv_pen in coefs_indiv_pen: + assert_array_almost_equal(coef_cholesky, coef_indiv_pen) + + # Test error is raised when number of targets and penalties do not match. + ridge = Ridge(alpha=penalties[:3]) + assert_raises(ValueError, ridge.fit, X, y) + + def _test_ridge_loo(filter_): # test that can work with both dense or sparse matrices n_samples = X_diabetes.shape[0] @@ -200,16 +321,25 @@ def _test_ridge_loo(filter_): ret.append(alpha_) # check that we get same best alpha with custom loss_func - ridge_gcv2 = RidgeCV(fit_intercept=False, loss_func=mean_squared_error) - ridge_gcv2.fit(filter_(X_diabetes), y_diabetes) + f = ignore_warnings + scoring = make_scorer(mean_squared_error, greater_is_better=False) + ridge_gcv2 = RidgeCV(fit_intercept=False, scoring=scoring) + f(ridge_gcv2.fit)(filter_(X_diabetes), y_diabetes) assert_equal(ridge_gcv2.alpha_, alpha_) # check that we get same best alpha with custom score_func func = lambda x, y: -mean_squared_error(x, y) - ridge_gcv3 = RidgeCV(fit_intercept=False, score_func=func) - ridge_gcv3.fit(filter_(X_diabetes), y_diabetes) + scoring = make_scorer(func) + ridge_gcv3 = RidgeCV(fit_intercept=False, scoring=scoring) + f(ridge_gcv3.fit)(filter_(X_diabetes), y_diabetes) assert_equal(ridge_gcv3.alpha_, alpha_) + # check that we get same best alpha with a scorer + scorer = get_scorer('mean_squared_error') + ridge_gcv4 = RidgeCV(fit_intercept=False, scoring=scorer) + ridge_gcv4.fit(filter_(X_diabetes), y_diabetes) + assert_equal(ridge_gcv4.alpha_, alpha_) + # check that we get same best alpha with sample weights ridge_gcv.fit(filter_(X_diabetes), y_diabetes, sample_weight=np.ones(n_samples)) @@ -310,10 +440,23 @@ def test_dense_sparse(): # test sparse matrix ret_sparse = test_func(SPARSE_FILTER) # test that the outputs are the same - if ret_dense != None and ret_sparse != None: + if ret_dense is not None and ret_sparse is not None: assert_array_almost_equal(ret_dense, ret_sparse, decimal=3) +def test_ridge_cv_sparse_svd(): + X = sp.csr_matrix(X_diabetes) + ridge = RidgeCV(gcv_mode="svd") + assert_raises(TypeError, ridge.fit, X) + + +def test_ridge_sparse_svd(): + X = sp.csc_matrix(rng.rand(100, 10)) + y = rng.rand(100) + ridge = Ridge(solver='svd') + assert_raises(TypeError, ridge.fit, X, y) + + def test_class_weights(): """ Test class weights. @@ -334,6 +477,23 @@ def test_class_weights(): # the prediction on this point should shift assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([-1])) + # check if class_weight = 'auto' can handle negative labels. + clf = RidgeClassifier(class_weight='auto') + clf.fit(X, y) + assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([1])) + + # class_weight = 'auto', and class_weight = None should return + # same values when y has equal number of all labels + X = np.array([[-1.0, -1.0], [-1.0, 0], [-.8, -1.0], [1.0, 1.0]]) + y = [1, 1, -1, -1] + clf = RidgeClassifier(class_weight=None) + clf.fit(X, y) + clfa = RidgeClassifier(class_weight='auto') + clfa.fit(X, y) + assert_equal(len(clfa.classes_), 2) + assert_array_almost_equal(clf.coef_, clfa.coef_) + assert_array_almost_equal(clf.intercept_, clfa.intercept_) + def test_class_weights_cv(): """ @@ -377,3 +537,96 @@ def test_ridgecv_store_cv_values(): y = rng.randn(n_samples, n_responses) r.fit(x, y) assert_equal(r.cv_values_.shape, (n_samples, n_responses, n_alphas)) + + +def test_raises_value_error_if_sample_weights_greater_than_1d(): + """Sample weights must be either scalar or 1D""" + + n_sampless = [2, 3] + n_featuress = [3, 2] + + rng = np.random.RandomState(42) + + for n_samples, n_features in zip(n_sampless, n_featuress): + X = rng.randn(n_samples, n_features) + y = rng.randn(n_samples) + sample_weights_OK = rng.randn(n_samples) ** 2 + 1 + sample_weights_OK_1 = 1. + sample_weights_OK_2 = 2. + sample_weights_not_OK = sample_weights_OK[:, np.newaxis] + sample_weights_not_OK_2 = sample_weights_OK[np.newaxis, :] + + ridge = Ridge(alpha=1) + + # make sure the "OK" sample weights actually work + ridge.fit(X, y, sample_weights_OK) + ridge.fit(X, y, sample_weights_OK_1) + ridge.fit(X, y, sample_weights_OK_2) + + def fit_ridge_not_ok(): + ridge.fit(X, y, sample_weights_not_OK) + + def fit_ridge_not_ok_2(): + ridge.fit(X, y, sample_weights_not_OK_2) + + assert_raise_message(ValueError, + "Sample weights must be 1D array or scalar", + fit_ridge_not_ok) + + assert_raise_message(ValueError, + "Sample weights must be 1D array or scalar", + fit_ridge_not_ok_2) + + +def test_sparse_design_with_sample_weights(): + """Sample weights must work with sparse matrices""" + + n_sampless = [2, 3] + n_featuress = [3, 2] + + rng = np.random.RandomState(42) + + sparse_matrix_converters = [sp.coo_matrix, + sp.csr_matrix, + sp.csc_matrix, + sp.lil_matrix, + sp.dok_matrix + ] + + sparse_ridge = Ridge(alpha=1., fit_intercept=False) + dense_ridge = Ridge(alpha=1., fit_intercept=False) + + for n_samples, n_features in zip(n_sampless, n_featuress): + X = rng.randn(n_samples, n_features) + y = rng.randn(n_samples) + sample_weights = rng.randn(n_samples) ** 2 + 1 + for sparse_converter in sparse_matrix_converters: + X_sparse = sparse_converter(X) + sparse_ridge.fit(X_sparse, y, sample_weight=sample_weights) + dense_ridge.fit(X, y, sample_weight=sample_weights) + + assert_array_almost_equal(sparse_ridge.coef_, dense_ridge.coef_, + decimal=6) + + +def test_raises_value_error_if_solver_not_supported(): + """Tests whether a ValueError is raised if a non-identified solver + is passed to ridge_regression""" + + wrong_solver = "This is not a solver (MagritteSolveCV QuantumBitcoin)" + + exception = ValueError + message = "Solver %s not understood" % wrong_solver + + def func(): + X = np.eye(3) + y = np.ones(3) + ridge_regression(X, y, alpha=1., solver=wrong_solver) + + assert_raise_message(exception, message, func) + + +def test_sparse_cg_max_iter(): + reg = Ridge(solver="sparse_cg", max_iter=1) + reg.fit(X_diabetes, y_diabetes) + assert_equal(reg.coef_.shape[0], X_diabetes.shape[1]) diff --git a/sklearn/linear_model/tests/test_sgd.py b/sklearn/linear_model/tests/test_sgd.py index c39adf8f86796..93749e1852bdb 100644 --- a/sklearn/linear_model/tests/test_sgd.py +++ b/sklearn/linear_model/tests/test_sgd.py @@ -1,41 +1,44 @@ +import pickle +import unittest + import numpy as np import scipy.sparse as sp -from numpy.testing import assert_array_equal, assert_approx_equal -from numpy.testing import assert_almost_equal, assert_array_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import raises +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_false, assert_true +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_raises_regexp +from sklearn.utils.testing import assert_warns_message from sklearn import linear_model, datasets, metrics -from sklearn import preprocessing -from sklearn.linear_model import SGDClassifier, SGDRegressor -from sklearn.utils.testing import assert_greater, assert_less from sklearn.base import clone - -import unittest -from nose.tools import raises -from nose.tools import assert_raises, assert_true, assert_equal +from sklearn.linear_model import SGDClassifier, SGDRegressor +from sklearn.preprocessing import LabelEncoder, scale, MinMaxScaler class SparseSGDClassifier(SGDClassifier): def fit(self, X, y, *args, **kw): X = sp.csr_matrix(X) - return SGDClassifier.fit(self, X, y, *args, **kw) + return super(SparseSGDClassifier, self).fit(X, y, *args, **kw) def partial_fit(self, X, y, *args, **kw): X = sp.csr_matrix(X) - return SGDClassifier.partial_fit(self, X, y, *args, **kw) + return super(SparseSGDClassifier, self).partial_fit(X, y, *args, **kw) - def decision_function(self, X, *args, **kw): + def decision_function(self, X): X = sp.csr_matrix(X) - return SGDClassifier.decision_function(self, X, *args, **kw) + return super(SparseSGDClassifier, self).decision_function(X) - def predict_proba(self, X, *args, **kw): + def predict_proba(self, X): X = sp.csr_matrix(X) - return SGDClassifier.predict_proba(self, X, *args, **kw) - - def predict_log_proba(self, X, *args, **kw): - X = sp.csr_matrix(X) - return SGDClassifier.predict_log_proba(self, X, *args, **kw) + return super(SparseSGDClassifier, self).predict_proba(X) class SparseSGDRegressor(SGDRegressor): @@ -52,10 +55,8 @@ def decision_function(self, X, *args, **kw): X = sp.csr_matrix(X) return SGDRegressor.decision_function(self, X, *args, **kw) -## -## Test Data -## +# Test Data # test sample 1 X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]) @@ -92,14 +93,53 @@ def decision_function(self, X, *args, **kw): Y5 = [1, 1, 1, 2, 2, 2] true_result5 = [0, 1, 1] -## -## Classification Test Case -## +# Classification Test Case class CommonTest(object): - def _test_warm_start(self, lr): + def factory(self, **kwargs): + if "random_state" not in kwargs: + kwargs["random_state"] = 42 + return self.factory_class(**kwargs) + + # a simple implementation of ASGD to use for testing + # uses squared loss to find the gradient + def asgd(self, X, y, eta, alpha, weight_init=None, intercept_init=0.0): + if weight_init is None: + weights = np.zeros(X.shape[1]) + else: + weights = weight_init + + average_weights = np.zeros(X.shape[1]) + intercept = intercept_init + average_intercept = 0.0 + decay = 1.0 + + # sparse data has a fixed decay of .01 + if (isinstance(self, SparseSGDClassifierTestCase) or + isinstance(self, SparseSGDRegressorTestCase)): + decay = .01 + + for i, entry in enumerate(X): + p = np.dot(entry, weights) + p += intercept + gradient = p - y[i] + weights *= 1.0 - (eta * alpha) + weights += -(eta * gradient * entry) + intercept += -(eta * gradient) * decay + + average_weights *= i + average_weights += weights + average_weights /= i + 1.0 + + average_intercept *= i + average_intercept += intercept + average_intercept /= i + 1.0 + + return average_weights, average_intercept + + def _test_warm_start(self, X, Y, lr): # Test that explicit warm restart... clf = self.factory(alpha=0.01, eta0=0.01, n_iter=5, shuffle=False, learning_rate=lr) @@ -111,7 +151,7 @@ def _test_warm_start(self, lr): coef_init=clf.coef_.copy(), intercept_init=clf.intercept_.copy()) - #... and implicit warm restart are equivalent. + # ... and implicit warm restart are equivalent. clf3 = self.factory(alpha=0.01, eta0=0.01, n_iter=5, shuffle=False, warm_start=True, learning_rate=lr) clf3.fit(X, Y) @@ -126,29 +166,20 @@ def _test_warm_start(self, lr): assert_array_almost_equal(clf3.coef_, clf2.coef_) def test_warm_start_constant(self): - self._test_warm_start("constant") + self._test_warm_start(X, Y, "constant") def test_warm_start_invscaling(self): - self._test_warm_start("invscaling") + self._test_warm_start(X, Y, "invscaling") def test_warm_start_optimal(self): - self._test_warm_start("optimal") - - def test_multiple_fit(self): - """Test multiple calls of fit w/ different shaped inputs.""" - clf = self.factory(alpha=0.01, n_iter=5, - shuffle=False) - clf.fit(X, Y) - assert_true(hasattr(clf, "coef_")) - - clf.fit(X[:, :-1], Y) + self._test_warm_start(X, Y, "optimal") def test_input_format(self): """Input format tests. """ clf = self.factory(alpha=0.01, n_iter=5, shuffle=False) + clf.fit(X, Y) Y_ = np.array(Y)[:, np.newaxis] - clf.fit(X, Y_) Y_ = np.c_[Y_, Y_] assert_raises(ValueError, clf.fit, X, Y_) @@ -165,25 +196,103 @@ def test_clone(self): assert_array_equal(clf.coef_, clf2.coef_) + def test_plain_has_no_average_attr(self): + clf = self.factory(average=True, eta0=.01) + clf.fit(X, Y) + + assert_true(hasattr(clf, 'average_coef_')) + assert_true(hasattr(clf, 'average_intercept_')) + assert_true(hasattr(clf, 'standard_intercept_')) + assert_true(hasattr(clf, 'standard_coef_')) + + clf = self.factory() + clf.fit(X, Y) + + assert_false(hasattr(clf, 'average_coef_')) + assert_false(hasattr(clf, 'average_intercept_')) + assert_false(hasattr(clf, 'standard_intercept_')) + assert_false(hasattr(clf, 'standard_coef_')) + + def test_late_onset_averaging_not_reached(self): + clf1 = self.factory(average=600) + clf2 = self.factory() + for _ in range(100): + if isinstance(clf1, SGDClassifier): + clf1.partial_fit(X, Y, classes=np.unique(Y)) + clf2.partial_fit(X, Y, classes=np.unique(Y)) + else: + clf1.partial_fit(X, Y) + clf2.partial_fit(X, Y) + + assert_array_almost_equal(clf1.coef_, clf2.coef_, decimal=16) + assert_almost_equal(clf1.intercept_, clf2.intercept_, decimal=16) + + def test_late_onset_averaging_reached(self): + eta0 = .001 + alpha = .0001 + Y_encode = np.array(Y) + Y_encode[Y_encode == 1] = -1.0 + Y_encode[Y_encode == 2] = 1.0 + + clf1 = self.factory(average=7, learning_rate="constant", + loss='squared_loss', eta0=eta0, + alpha=alpha, n_iter=2, shuffle=False) + clf2 = self.factory(average=0, learning_rate="constant", + loss='squared_loss', eta0=eta0, + alpha=alpha, n_iter=1, shuffle=False) + + clf1.fit(X, Y_encode) + clf2.fit(X, Y_encode) + + average_weights, average_intercept = \ + self.asgd(X, Y_encode, eta0, alpha, + weight_init=clf2.coef_.ravel(), + intercept_init=clf2.intercept_) + + assert_array_almost_equal(clf1.coef_.ravel(), + average_weights.ravel(), + decimal=16) + assert_almost_equal(clf1.intercept_, average_intercept, decimal=16) + class DenseSGDClassifierTestCase(unittest.TestCase, CommonTest): """Test suite for the dense representation variant of SGD""" - - factory = SGDClassifier + factory_class = SGDClassifier def test_sgd(self): """Check that SGD gives any results :-)""" - clf = self.factory(penalty='l2', alpha=0.01, fit_intercept=True, - n_iter=10, shuffle=True) - clf.fit(X, Y) - #assert_almost_equal(clf.coef_[0], clf.coef_[1], decimal=7) - assert_array_equal(clf.predict(T), true_result) + for loss in ("hinge", "squared_hinge", "log", "modified_huber"): + clf = self.factory(penalty='l2', alpha=0.01, fit_intercept=True, + loss=loss, n_iter=10, shuffle=True) + clf.fit(X, Y) + # assert_almost_equal(clf.coef_[0], clf.coef_[1], decimal=7) + assert_array_equal(clf.predict(T), true_result) + + @raises(ValueError) + def test_sgd_bad_l1_ratio(self): + """Check whether expected ValueError on bad l1_ratio""" + self.factory(l1_ratio=1.1) + + @raises(ValueError) + def test_sgd_bad_learning_rate_schedule(self): + """Check whether expected ValueError on bad learning_rate""" + self.factory(learning_rate="") + + @raises(ValueError) + def test_sgd_bad_eta0(self): + """Check whether expected ValueError on bad eta0""" + self.factory(eta0=0, learning_rate="constant") + + @raises(ValueError) + def test_sgd_bad_alpha(self): + """Check whether expected ValueError on bad alpha""" + self.factory(alpha=-.1) @raises(ValueError) def test_sgd_bad_penalty(self): """Check whether expected ValueError on bad penalty""" - self.factory(penalty='foobar', rho=0.85) + self.factory(penalty='foobar', l1_ratio=0.85) @raises(ValueError) def test_sgd_bad_loss(self): @@ -201,7 +310,7 @@ def test_sgd_shuffle_param(self): self.factory(shuffle="false") @raises(TypeError) - def test_arument_coef(self): + def test_argument_coef(self): """Checks coef_init not allowed as model argument (only fit)""" # Provided coef_ does not match dataset. self.factory(coef_init=np.zeros((3,))).fit(X, Y) @@ -222,6 +331,35 @@ def test_set_intercept_binary(self): """Checks intercept_ shape for the warm starts in binary case""" self.factory().fit(X5, Y5, intercept_init=0) + def test_average_binary_computed_correctly(self): + """Checks the SGDClassifier correctly computes the average weights""" + eta = .1 + alpha = 2. + n_samples = 20 + n_features = 10 + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, n_features)) + w = rng.normal(size=n_features) + + clf = self.factory(loss='squared_loss', + learning_rate='constant', + eta0=eta, alpha=alpha, + fit_intercept=True, + n_iter=1, average=True, shuffle=False) + + # simple linear function without noise + y = np.dot(X, w) + y = np.sign(y) + + clf.fit(X, y) + + average_weights, average_intercept = self.asgd(X, y, eta, alpha) + average_weights = average_weights.reshape(1, -1) + assert_array_almost_equal(clf.coef_, + average_weights, + decimal=14) + assert_almost_equal(clf.intercept_, average_intercept, decimal=14) + def test_set_intercept_to_intercept(self): """Checks intercept_ shape consistency for the warm starts""" # Inconsistent intercept_ shape. @@ -235,6 +373,20 @@ def test_sgd_at_least_two_labels(self): """Target must have at least two labels""" self.factory(alpha=0.01, n_iter=20).fit(X2, np.ones(9)) + def test_partial_fit_weight_class_auto(self): + """partial_fit with class_weight='auto' not supported""" + assert_raises_regexp(ValueError, + "class_weight 'auto' is not supported for " + "partial_fit. In order to use 'auto' weights, " + "use compute_class_weight\('auto', classes, y\). " + "In place of y you can us a large enough sample " + "of the full training set target to properly " + "estimate the class frequency distributions. " + "Pass the resulting weights as the class_weight " + "parameter.", + self.factory(class_weight='auto').partial_fit, + X, Y, classes=np.unique(Y)) + def test_sgd_multiclass(self): """Multi-class test case""" clf = self.factory(alpha=0.01, n_iter=20).fit(X2, Y2) @@ -244,6 +396,29 @@ def test_sgd_multiclass(self): pred = clf.predict(T2) assert_array_equal(pred, true_result2) + def test_sgd_multiclass_average(self): + eta = .001 + alpha = .01 + """Multi-class average test case""" + clf = self.factory(loss='squared_loss', + learning_rate='constant', + eta0=eta, alpha=alpha, + fit_intercept=True, + n_iter=1, average=True, shuffle=False) + + np_Y2 = np.array(Y2) + clf.fit(X2, np_Y2) + classes = np.unique(np_Y2) + + for i, cl in enumerate(classes): + y_i = np.ones(np_Y2.shape[0]) + y_i[np_Y2 != cl] = -1 + average_coef, average_intercept = self.asgd(X2, y_i, eta, alpha) + assert_array_almost_equal(average_coef, clf.coef_[i], decimal=16) + assert_almost_equal(average_intercept, + clf.intercept_[i], + decimal=16) + def test_sgd_multiclass_with_init_coef(self): """Multi-class test case""" clf = self.factory(alpha=0.01, n_iter=20) @@ -284,13 +459,18 @@ def test_set_coef_multiclass(self): def test_sgd_proba(self): """Check SGD.predict_proba""" - # hinge loss does not allow for conditional prob estimate - clf = self.factory(loss="hinge", alpha=0.01, n_iter=10).fit(X, Y) - assert_raises(NotImplementedError, clf.predict_proba, [3, 2]) - - # the log and modified_huber losses can output "probability" estimates - for loss in ("log", "modified_huber"): - clf = self.factory(loss=loss, alpha=0.01, n_iter=10).fit(X, Y) + # Hinge loss does not allow for conditional prob estimate. + # We cannot use the factory here, because it defines predict_proba + # anyway. + clf = SGDClassifier(loss="hinge", alpha=0.01, n_iter=10).fit(X, Y) + assert_false(hasattr(clf, "predict_proba")) + assert_false(hasattr(clf, "predict_log_proba")) + + # log and modified_huber losses can output probability estimates + # binary case + for loss in ["log", "modified_huber"]: + clf = self.factory(loss="modified_huber", alpha=0.01, n_iter=10) + clf.fit(X, Y) p = clf.predict_proba([3, 2]) assert_true(p[0, 1] > 0.5) p = clf.predict_proba([-1, -1]) @@ -301,6 +481,48 @@ def test_sgd_proba(self): p = clf.predict_log_proba([-1, -1]) assert_true(p[0, 1] < p[0, 0]) + # log loss multiclass probability estimates + clf = self.factory(loss="log", alpha=0.01, n_iter=10).fit(X2, Y2) + + d = clf.decision_function([[.1, -.1], [.3, .2]]) + p = clf.predict_proba([[.1, -.1], [.3, .2]]) + assert_array_equal(np.argmax(p, axis=1), np.argmax(d, axis=1)) + assert_almost_equal(p[0].sum(), 1) + assert_true(np.all(p[0] >= 0)) + + p = clf.predict_proba([-1, -1]) + d = clf.decision_function([-1, -1]) + assert_array_equal(np.argsort(p[0]), np.argsort(d[0])) + + l = clf.predict_log_proba([3, 2]) + p = clf.predict_proba([3, 2]) + assert_array_almost_equal(np.log(p), l) + + l = clf.predict_log_proba([-1, -1]) + p = clf.predict_proba([-1, -1]) + assert_array_almost_equal(np.log(p), l) + + # Modified Huber multiclass probability estimates; requires a separate + # test because the hard zero/one probabilities may destroy the + # ordering present in decision_function output. + clf = self.factory(loss="modified_huber", alpha=0.01, n_iter=10) + clf.fit(X2, Y2) + d = clf.decision_function([3, 2]) + p = clf.predict_proba([3, 2]) + if not isinstance(self, SparseSGDClassifierTestCase): + assert_equal(np.argmax(d, axis=1), np.argmax(p, axis=1)) + else: # XXX the sparse test gets a different X2 (?) + assert_equal(np.argmin(d, axis=1), np.argmin(p, axis=1)) + + # the following sample produces decision_function values < -1, + # which would cause naive normalization to fail (see comment + # in SGDClassifier.predict_proba) + x = X.mean(axis=0) + d = clf.decision_function(x) + if np.all(d < -1): # XXX not true in sparse test case (why?) + p = clf.predict_proba(x) + assert_array_almost_equal(p[0], [1 / 3.] * 3) + def test_sgd_l1(self): """Test L1 regularization""" n = len(X4) @@ -309,15 +531,27 @@ def test_sgd_l1(self): rng.shuffle(idx) X = X4[idx, :] - Y = Y4[idx, :] + Y = Y4[idx] clf = self.factory(penalty='l1', alpha=.2, fit_intercept=False, - n_iter=2000) + n_iter=2000, shuffle=False) clf.fit(X, Y) assert_array_equal(clf.coef_[0, 1:-1], np.zeros((4,))) pred = clf.predict(X) assert_array_equal(pred, Y) + # test sparsify with dense inputs + clf.sparsify() + assert_true(sp.issparse(clf.coef_)) + pred = clf.predict(X) + assert_array_equal(pred, Y) + + # pickle and unpickle with sparse coef_ + clf = pickle.loads(pickle.dumps(clf)) + assert_true(sp.issparse(clf.coef_)) + pred = clf.predict(X) + assert_array_equal(pred, Y) + def test_class_weights(self): """ Test class weights. @@ -333,7 +567,7 @@ def test_class_weights(self): # we give a small weights to class 1 clf = self.factory(alpha=0.1, n_iter=1000, fit_intercept=False, - class_weight={1: 0.001}) + class_weight={1: 0.001}) clf.fit(X, y) # now the hyperplane should rotate clock-wise and @@ -350,7 +584,7 @@ def test_equal_class_weight(self): X = [[1, 0], [0, 1]] y = [0, 1] clf_weighted = self.factory(alpha=0.1, n_iter=1000, - class_weight={0: 0.5, 1: 0.5}) + class_weight={0: 0.5, 1: 0.5}) clf_weighted.fit(X, y) # should be similar up to some epsilon due to learning rate schedule @@ -368,25 +602,57 @@ def test_wrong_class_weight_format(self): clf = self.factory(alpha=0.1, n_iter=1000, class_weight=[0.5]) clf.fit(X, Y) + def test_class_weight_warning(self): + """Tests that class_weight passed through fit raises warning. + This test should be removed after deprecating support for this""" + + clf = self.factory() + warning_message = ("You are trying to set class_weight through the fit " + "method, which is deprecated and will be removed in" + "v0.17 of scikit-learn. Pass the class_weight into " + "the constructor instead.") + assert_warns_message(DeprecationWarning, + warning_message, + clf.fit, X4, Y4, + class_weight=1) + + def test_weights_multiplied(self): + """Tests that class_weight and sample_weight are multiplicative""" + class_weights = {1: .6, 2: .3} + sample_weights = np.random.random(Y4.shape[0]) + multiplied_together = np.copy(sample_weights) + multiplied_together[Y4 == 1] *= class_weights[1] + multiplied_together[Y4 == 2] *= class_weights[2] + + clf1 = self.factory(alpha=0.1, n_iter=20, class_weight=class_weights) + clf2 = self.factory(alpha=0.1, n_iter=20) + + clf1.fit(X4, Y4, sample_weight=sample_weights) + clf2.fit(X4, Y4, sample_weight=multiplied_together) + + assert_array_equal(clf1.coef_, clf2.coef_) + def test_auto_weight(self): """Test class weights for imbalanced data""" # compute reference metrics on iris dataset that is quite balanced by # default X, y = iris.data, iris.target - X = preprocessing.scale(X) + X = scale(X) idx = np.arange(X.shape[0]) - rng = np.random.RandomState(0) + rng = np.random.RandomState(6) rng.shuffle(idx) X = X[idx] y = y[idx] clf = self.factory(alpha=0.0001, n_iter=1000, - class_weight=None).fit(X, y) - assert_approx_equal(metrics.f1_score(y, clf.predict(X)), 0.96, 2) + class_weight=None, shuffle=False).fit(X, y) + assert_almost_equal(metrics.f1_score(y, clf.predict(X), average='weighted'), 0.96, + decimal=1) # make the same prediction using automated class_weight clf_auto = self.factory(alpha=0.0001, n_iter=1000, - class_weight="auto").fit(X, y) - assert_approx_equal(metrics.f1_score(y, clf_auto.predict(X)), 0.96, 2) + class_weight="auto", shuffle=False).fit(X, y) + assert_almost_equal(metrics.f1_score(y, clf_auto.predict(X), average='weighted'), 0.96, + decimal=1) # Make sure that in the balanced case it does not change anything # to use "auto" @@ -400,22 +666,22 @@ def test_auto_weight(self): y_imbalanced = np.concatenate([y] + [y_0] * 10) # fit a model on the imbalanced data without class weight info - clf = self.factory(n_iter=1000, class_weight=None) + clf = self.factory(n_iter=1000, class_weight=None, shuffle=False) clf.fit(X_imbalanced, y_imbalanced) y_pred = clf.predict(X) - assert_less(metrics.f1_score(y, y_pred), 0.96) + assert_less(metrics.f1_score(y, y_pred, average='weighted'), 0.96) # fit a model with auto class_weight enabled - clf = self.factory(n_iter=1000, class_weight="auto") + clf = self.factory(n_iter=1000, class_weight="auto", shuffle=False) clf.fit(X_imbalanced, y_imbalanced) y_pred = clf.predict(X) - assert_greater(metrics.f1_score(y, y_pred), 0.96) + assert_greater(metrics.f1_score(y, y_pred, average='weighted'), 0.96) # fit another using a fit parameter override - clf = self.factory(n_iter=1000, class_weight="auto") + clf = self.factory(n_iter=1000, class_weight="auto", shuffle=False) clf.fit(X_imbalanced, y_imbalanced) y_pred = clf.predict(X) - assert_greater(metrics.f1_score(y, y_pred), 0.96) + assert_greater(metrics.f1_score(y, y_pred, average='weighted'), 0.96) def test_sample_weights(self): """Test weights on individual samples""" @@ -439,7 +705,7 @@ def test_wrong_sample_weights(self): """Test if ValueError is raised if sample_weight has wrong shape""" clf = self.factory(alpha=0.1, n_iter=1000, fit_intercept=False) # provided sample_weight too long - clf.fit(X, Y, sample_weight=range(7)) + clf.fit(X, Y, sample_weight=np.arange(7)) @raises(ValueError) def test_partial_fit_exception(self): @@ -482,6 +748,16 @@ def test_partial_fit_multiclass(self): # check that coef_ haven't been re-allocated assert_true(id1, id2) + def test_fit_then_partial_fit(self): + """Partial_fit should work after initial fit in the multiclass case. + + Non-regression test for #2496; fit would previously produce a + Fortran-ordered coef_ that subsequent partial_fit couldn't handle. + """ + clf = self.factory() + clf.fit(X2, Y2) + clf.partial_fit(X2, Y2) # no exception here + def _test_partial_fit_equal_fit(self, lr): for X_, Y_, T_ in ((X, Y, T), (X2, Y2, T2)): clf = self.factory(alpha=0.01, eta0=0.01, n_iter=2, @@ -515,6 +791,11 @@ def test_regression_losses(self): clf.fit(X, Y) assert_equal(1.0, np.mean(clf.predict(X) == Y)) + clf = self.factory(alpha=0.01, learning_rate="constant", + eta0=0.1, loss="squared_epsilon_insensitive") + clf.fit(X, Y) + assert_equal(1.0, np.mean(clf.predict(X) == Y)) + clf = self.factory(alpha=0.01, loss="huber") clf.fit(X, Y) assert_equal(1.0, np.mean(clf.predict(X) == Y)) @@ -524,20 +805,34 @@ def test_regression_losses(self): clf.fit(X, Y) assert_equal(1.0, np.mean(clf.predict(X) == Y)) + def test_warm_start_multiclass(self): + self._test_warm_start(X2, Y2, "optimal") + + def test_multiple_fit(self): + """Test multiple calls of fit w/ different shaped inputs.""" + clf = self.factory(alpha=0.01, n_iter=5, + shuffle=False) + clf.fit(X, Y) + assert_true(hasattr(clf, "coef_")) + + # Non-regression test: try fitting with a different label set. + y = [["ham", "spam"][i] for i in LabelEncoder().fit_transform(Y)] + clf.fit(X[:, :-1], y) + class SparseSGDClassifierTestCase(DenseSGDClassifierTestCase): """Run exactly the same tests using the sparse representation variant""" - factory = SparseSGDClassifier + factory_class = SparseSGDClassifier ############################################################################### # Regression Test Case -class DenseSGDRegressorTestCase(unittest.TestCase): +class DenseSGDRegressorTestCase(unittest.TestCase, CommonTest): """Test suite for the dense representation variant of SGD""" - factory = SGDRegressor + factory_class = SGDRegressor def test_sgd(self): """Check that SGD gives any results.""" @@ -549,13 +844,91 @@ def test_sgd(self): @raises(ValueError) def test_sgd_bad_penalty(self): """Check whether expected ValueError on bad penalty""" - self.factory(penalty='foobar', rho=0.85) + self.factory(penalty='foobar', l1_ratio=0.85) @raises(ValueError) def test_sgd_bad_loss(self): """Check whether expected ValueError on bad loss""" self.factory(loss="foobar") + def test_sgd_averaged_computed_correctly(self): + """Tests the average regressor matches the naive implementation""" + + eta = .001 + alpha = .01 + n_samples = 20 + n_features = 10 + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, n_features)) + w = rng.normal(size=n_features) + + # simple linear function without noise + y = np.dot(X, w) + + clf = self.factory(loss='squared_loss', + learning_rate='constant', + eta0=eta, alpha=alpha, + fit_intercept=True, + n_iter=1, average=True, shuffle=False) + + clf.fit(X, y) + average_weights, average_intercept = self.asgd(X, y, eta, alpha) + + assert_array_almost_equal(clf.coef_, + average_weights, + decimal=16) + assert_almost_equal(clf.intercept_, average_intercept, decimal=16) + + def test_sgd_averaged_partial_fit(self): + """Tests whether the partial fit yields the same average as the fit""" + eta = .001 + alpha = .01 + n_samples = 20 + n_features = 10 + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, n_features)) + w = rng.normal(size=n_features) + + # simple linear function without noise + y = np.dot(X, w) + + clf = self.factory(loss='squared_loss', + learning_rate='constant', + eta0=eta, alpha=alpha, + fit_intercept=True, + n_iter=1, average=True, shuffle=False) + + clf.partial_fit(X[:int(n_samples / 2)][:], y[:int(n_samples / 2)]) + clf.partial_fit(X[int(n_samples / 2):][:], y[int(n_samples / 2):]) + average_weights, average_intercept = self.asgd(X, y, eta, alpha) + + assert_array_almost_equal(clf.coef_, + average_weights, + decimal=16) + assert_almost_equal(clf.intercept_[0], average_intercept, decimal=16) + + def test_average_sparse(self): + """Checks the average weights on data with 0s""" + + eta = .001 + alpha = .01 + clf = self.factory(loss='squared_loss', + learning_rate='constant', + eta0=eta, alpha=alpha, + fit_intercept=True, + n_iter=1, average=True, shuffle=False) + + n_samples = Y3.shape[0] + + clf.partial_fit(X3[:int(n_samples / 2)][:], Y3[:int(n_samples / 2)]) + clf.partial_fit(X3[int(n_samples / 2):][:], Y3[int(n_samples / 2):]) + average_weights, average_intercept = self.asgd(X3, Y3, eta, alpha) + + assert_array_almost_equal(clf.coef_, + average_weights, + decimal=16) + assert_almost_equal(clf.intercept_, average_intercept, decimal=16) + def test_sgd_least_squares_fit(self): xmin, xmax = -5, 5 n_samples = 100 @@ -631,7 +1004,7 @@ def test_sgd_huber_fit(self): assert_greater(score, 0.5) def test_elasticnet_convergence(self): - """Check that the SGD ouput is consistent with coordinate descent""" + """Check that the SGD output is consistent with coordinate descent""" n_samples, n_features = 1000, 5 rng = np.random.RandomState(0) @@ -643,15 +1016,17 @@ def test_elasticnet_convergence(self): # XXX: alpha = 0.1 seems to cause convergence problems for alpha in [0.01, 0.001]: - for rho in [0.5, 0.8, 1.0]: - cd = linear_model.ElasticNet(alpha=alpha, rho=rho, + for l1_ratio in [0.5, 0.8, 1.0]: + cd = linear_model.ElasticNet(alpha=alpha, l1_ratio=l1_ratio, fit_intercept=False) cd.fit(X, y) sgd = self.factory(penalty='elasticnet', n_iter=50, - alpha=alpha, rho=rho, fit_intercept=False) + alpha=alpha, l1_ratio=l1_ratio, + fit_intercept=False) sgd.fit(X, y) err_msg = ("cd and sgd did not converge to comparable " - "results for alpha=%f and rho=%f" % (alpha, rho)) + "results for alpha=%f and l1_ratio=%f" + % (alpha, l1_ratio)) assert_almost_equal(cd.coef_, sgd.coef_, decimal=2, err_msg=err_msg) @@ -704,4 +1079,80 @@ def test_loss_function_epsilon(self): class SparseSGDRegressorTestCase(DenseSGDRegressorTestCase): """Run exactly the same tests using the sparse representation variant""" - factory = SparseSGDRegressor + factory_class = SparseSGDRegressor + + +def test_l1_ratio(): + """Test if l1 ratio extremes match L1 and L2 penalty settings. """ + X, y = datasets.make_classification(n_samples=1000, + n_features=100, n_informative=20, + random_state=1234) + + # test if elasticnet with l1_ratio near 1 gives same result as pure l1 + est_en = SGDClassifier(alpha=0.001, penalty='elasticnet', + l1_ratio=0.9999999999, random_state=42).fit(X, y) + est_l1 = SGDClassifier(alpha=0.001, penalty='l1', random_state=42).fit(X, y) + assert_array_almost_equal(est_en.coef_, est_l1.coef_) + + # test if elasticnet with l1_ratio near 0 gives same result as pure l2 + est_en = SGDClassifier(alpha=0.001, penalty='elasticnet', + l1_ratio=0.0000000001, random_state=42).fit(X, y) + est_l2 = SGDClassifier(alpha=0.001, penalty='l2', random_state=42).fit(X, y) + assert_array_almost_equal(est_en.coef_, est_l2.coef_) + + +def test_underflow_or_overlow(): + with np.errstate(all='raise'): + # Generate some weird data with hugely unscaled features + rng = np.random.RandomState(0) + n_samples = 100 + n_features = 10 + + X = rng.normal(size=(n_samples, n_features)) + X[:, :2] *= 1e300 + assert_true(np.isfinite(X).all()) + + # Use MinMaxScaler to scale the data without introducing a numerical + # instability (computing the standard deviation naively is not possible + # on this data) + X_scaled = MinMaxScaler().fit_transform(X) + assert_true(np.isfinite(X_scaled).all()) + + # Define a ground truth on the scaled data + ground_truth = rng.normal(size=n_features) + y = (np.dot(X_scaled, ground_truth) > 0.).astype(np.int32) + assert_array_equal(np.unique(y), [0, 1]) + + model = SGDClassifier(alpha=0.1, loss='squared_hinge', n_iter=500) + + # smoke test: model is stable on scaled data + model.fit(X_scaled, y) + assert_true(np.isfinite(model.coef_).all()) + + # model is numerically unstable on unscaled data + msg_regxp = (r"Floating-point under-/overflow occurred at epoch #.*" + " Scaling input data with StandardScaler or MinMaxScaler" + " might help.") + assert_raises_regexp(ValueError, msg_regxp, model.fit, X, y) + + +def test_numerical_stability_large_gradient(): + # Non regression test case for numerical stability on scaled problems + # where the gradient can still explode with some losses + model = SGDClassifier(loss='squared_hinge', n_iter=10, shuffle=True, + penalty='elasticnet', l1_ratio=0.3, alpha=0.01, + eta0=0.001, random_state=0) + with np.errstate(all='raise'): + model.fit(iris.data, iris.target) + assert_true(np.isfinite(model.coef_).all()) + + +def test_large_regularization(): + # Non regression tests for numerical stability issues caused by large + # regularization parameters + for penalty in ['l2', 'l1', 'elasticnet']: + model = SGDClassifier(alpha=1e5, learning_rate='constant', eta0=0.1, + n_iter=5, penalty=penalty, shuffle=False) + with np.errstate(all='raise'): + model.fit(iris.data, iris.target) + assert_array_almost_equal(model.coef_, np.zeros_like(model.coef_)) diff --git a/sklearn/linear_model/tests/test_sparse_coordinate_descent.py b/sklearn/linear_model/tests/test_sparse_coordinate_descent.py index f6a7f9c9e77fe..cafcc3639d9cc 100644 --- a/sklearn/linear_model/tests/test_sparse_coordinate_descent.py +++ b/sklearn/linear_model/tests/test_sparse_coordinate_descent.py @@ -1,15 +1,17 @@ import numpy as np import scipy.sparse as sp -from numpy.testing import assert_array_almost_equal -from numpy.testing import assert_almost_equal -from numpy.testing import assert_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_true -from nose.tools import assert_true -from sklearn.utils.testing import assert_less, assert_greater +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import ignore_warnings -from sklearn.linear_model.coordinate_descent import Lasso, ElasticNet, \ - ElasticNetCV +from sklearn.linear_model.coordinate_descent import (Lasso, ElasticNet, + LassoCV, ElasticNetCV) def test_sparse_coef(): @@ -18,7 +20,7 @@ def test_sparse_coef(): clf.coef_ = [1, 2, 3] assert_true(sp.isspmatrix(clf.sparse_coef_)) - assert_equal(clf.sparse_coef_.todense().tolist()[0], clf.coef_) + assert_equal(clf.sparse_coef_.toarray().tolist()[0], clf.coef_) def test_normalize_option(): @@ -47,7 +49,7 @@ def test_lasso_zero(): def test_enet_toy_list_input(): - """Test ElasticNet for various parameters of alpha and rho with list X""" + """Test ElasticNet for various values of alpha and l1_ratio with list X""" X = np.array([[-1], [0], [1]]) X = sp.csc_matrix(X) @@ -55,21 +57,23 @@ def test_enet_toy_list_input(): T = np.array([[2], [3], [4]]) # test sample # this should be the same as unregularized least squares - clf = ElasticNet(alpha=0, rho=1.0) - clf.fit(X, Y) + clf = ElasticNet(alpha=0, l1_ratio=1.0) + # catch warning about alpha=0. + # this is discouraged but should work. + ignore_warnings(clf.fit)(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [1]) assert_array_almost_equal(pred, [2, 3, 4]) assert_almost_equal(clf.dual_gap_, 0) - clf = ElasticNet(alpha=0.5, rho=0.3, max_iter=1000) + clf = ElasticNet(alpha=0.5, l1_ratio=0.3, max_iter=1000) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [0.50819], decimal=3) assert_array_almost_equal(pred, [1.0163, 1.5245, 2.0327], decimal=3) assert_almost_equal(clf.dual_gap_, 0) - clf = ElasticNet(alpha=0.5, rho=0.5) + clf = ElasticNet(alpha=0.5, l1_ratio=0.5) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [0.45454], 3) @@ -78,8 +82,9 @@ def test_enet_toy_list_input(): def test_enet_toy_explicit_sparse_input(): - """Test ElasticNet for various parameters of alpha and rho with sparse X""" - + """Test ElasticNet for various values of alpha and l1_ratio with sparse + X""" + f = ignore_warnings # training samples X = sp.lil_matrix((3, 1)) X[0, 0] = -1 @@ -94,21 +99,21 @@ def test_enet_toy_explicit_sparse_input(): T[2, 0] = 4 # this should be the same as lasso - clf = ElasticNet(alpha=0, rho=1.0) - clf.fit(X, Y) + clf = ElasticNet(alpha=0, l1_ratio=1.0) + f(clf.fit)(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [1]) assert_array_almost_equal(pred, [2, 3, 4]) assert_almost_equal(clf.dual_gap_, 0) - clf = ElasticNet(alpha=0.5, rho=0.3, max_iter=1000) + clf = ElasticNet(alpha=0.5, l1_ratio=0.3, max_iter=1000) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [0.50819], decimal=3) assert_array_almost_equal(pred, [1.0163, 1.5245, 2.0327], decimal=3) assert_almost_equal(clf.dual_gap_, 0) - clf = ElasticNet(alpha=0.5, rho=0.5) + clf = ElasticNet(alpha=0.5, l1_ratio=0.5) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [0.45454], 3) @@ -148,10 +153,10 @@ def _test_sparse_enet_not_as_toy_dataset(alpha, fit_intercept, positive): X, y = make_sparse_data(n_samples, n_features, n_informative, positive=positive) - X_train, X_test = X[n_samples / 2:], X[:n_samples / 2] - y_train, y_test = y[n_samples / 2:], y[:n_samples / 2] + X_train, X_test = X[n_samples // 2:], X[:n_samples // 2] + y_train, y_test = y[n_samples // 2:], y[:n_samples // 2] - s_clf = ElasticNet(alpha=alpha, rho=0.8, fit_intercept=fit_intercept, + s_clf = ElasticNet(alpha=alpha, l1_ratio=0.8, fit_intercept=fit_intercept, max_iter=max_iter, tol=1e-7, positive=positive, warm_start=True) s_clf.fit(X_train, y_train) @@ -160,10 +165,10 @@ def _test_sparse_enet_not_as_toy_dataset(alpha, fit_intercept, positive): assert_greater(s_clf.score(X_test, y_test), 0.85) # check the convergence is the same as the dense version - d_clf = ElasticNet(alpha=alpha, rho=0.8, fit_intercept=fit_intercept, - max_iter=max_iter, tol=1e-7, positive=positive, - warm_start=True) - d_clf.fit(X_train.todense(), y_train) + d_clf = ElasticNet(alpha=alpha, l1_ratio=0.8, fit_intercept=fit_intercept, + max_iter=max_iter, tol=1e-7, positive=positive, + warm_start=True) + d_clf.fit(X_train.toarray(), y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) assert_greater(d_clf.score(X_test, y_test), 0.85) @@ -174,18 +179,6 @@ def _test_sparse_enet_not_as_toy_dataset(alpha, fit_intercept, positive): # check that the coefs are sparse assert_less(np.sum(s_clf.coef_ != 0.0), 2 * n_informative) - # check that warm restart leads to the same result with - # sparse and dense versions - - rng = np.random.RandomState(seed=0) - coef_init = rng.randn(n_features) - - d_clf.fit(X_train.todense(), y_train, coef_init=coef_init) - s_clf.fit(X_train, y_train, coef_init=coef_init) - - assert_almost_equal(s_clf.coef_, d_clf.coef_, 5) - assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5) - def test_sparse_enet_not_as_toy_dataset(): _test_sparse_enet_not_as_toy_dataset(alpha=0.1, fit_intercept=False, @@ -204,19 +197,17 @@ def test_sparse_lasso_not_as_toy_dataset(): n_informative = 10 X, y = make_sparse_data(n_samples=n_samples, n_informative=n_informative) - X_train, X_test = X[n_samples / 2:], X[:n_samples / 2] - y_train, y_test = y[n_samples / 2:], y[:n_samples / 2] + X_train, X_test = X[n_samples // 2:], X[:n_samples // 2] + y_train, y_test = y[n_samples // 2:], y[:n_samples // 2] - s_clf = Lasso(alpha=0.1, fit_intercept=False, - max_iter=max_iter, tol=1e-7) + s_clf = Lasso(alpha=0.1, fit_intercept=False, max_iter=max_iter, tol=1e-7) s_clf.fit(X_train, y_train) assert_almost_equal(s_clf.dual_gap_, 0, 4) assert_greater(s_clf.score(X_test, y_test), 0.85) # check the convergence is the same as the dense version - d_clf = Lasso(alpha=0.1, fit_intercept=False, max_iter=max_iter, - tol=1e-7) - d_clf.fit(X_train.todense(), y_train) + d_clf = Lasso(alpha=0.1, fit_intercept=False, max_iter=max_iter, tol=1e-7) + d_clf.fit(X_train.toarray(), y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) assert_greater(d_clf.score(X_test, y_test), 0.85) @@ -231,15 +222,15 @@ def test_enet_multitarget(): estimator = ElasticNet(alpha=0.01, fit_intercept=True, precompute=None) # XXX: There is a bug when precompute is not None! estimator.fit(X, y) - coef, intercept, dual_gap, eps = (estimator.coef_, estimator.intercept_, - estimator.dual_gap_, estimator.eps_) + coef, intercept, dual_gap = (estimator.coef_, + estimator.intercept_, + estimator.dual_gap_) - for k in xrange(n_targets): + for k in range(n_targets): estimator.fit(X, y[:, k]) assert_array_almost_equal(coef[k, :], estimator.coef_) assert_array_almost_equal(intercept[k], estimator.intercept_) assert_array_almost_equal(dual_gap[k], estimator.dual_gap_) - assert_array_almost_equal(eps[k], estimator.eps_) def test_path_parameters(): @@ -247,8 +238,33 @@ def test_path_parameters(): max_iter = 50 n_alphas = 10 clf = ElasticNetCV(n_alphas=n_alphas, eps=1e-3, max_iter=max_iter, - rho=0.5, fit_intercept=False) - clf.fit(X, y) # new params - assert_almost_equal(0.5, clf.rho) + l1_ratio=0.5, fit_intercept=False) + ignore_warnings(clf.fit)(X, y) # new params + assert_almost_equal(0.5, clf.l1_ratio) assert_equal(n_alphas, clf.n_alphas) assert_equal(n_alphas, len(clf.alphas_)) + sparse_mse_path = clf.mse_path_ + ignore_warnings(clf.fit)(X.toarray(), y) # compare with dense data + assert_almost_equal(clf.mse_path_, sparse_mse_path) + + +def test_same_output_sparse_dense_lasso_and_enet_cv(): + X, y = make_sparse_data(n_samples=40, n_features=10) + for normalize in [True, False]: + clfs = ElasticNetCV(max_iter=100, cv=5, normalize=normalize) + ignore_warnings(clfs.fit)(X, y) + clfd = ElasticNetCV(max_iter=100, cv=5, normalize=normalize) + ignore_warnings(clfd.fit)(X.toarray(), y) + assert_almost_equal(clfs.alpha_, clfd.alpha_, 7) + assert_almost_equal(clfs.intercept_, clfd.intercept_, 7) + assert_array_almost_equal(clfs.mse_path_, clfd.mse_path_) + assert_array_almost_equal(clfs.alphas_, clfd.alphas_) + + clfs = LassoCV(max_iter=100, cv=4, normalize=normalize) + ignore_warnings(clfs.fit)(X, y) + clfd = LassoCV(max_iter=100, cv=4, normalize=normalize) + ignore_warnings(clfd.fit)(X.toarray(), y) + assert_almost_equal(clfs.alpha_, clfd.alpha_, 7) + assert_almost_equal(clfs.intercept_, clfd.intercept_, 7) + assert_array_almost_equal(clfs.mse_path_, clfd.mse_path_) + assert_array_almost_equal(clfs.alphas_, clfd.alphas_) diff --git a/sklearn/linear_model/tests/test_theil_sen.py b/sklearn/linear_model/tests/test_theil_sen.py new file mode 100644 index 0000000000000..521fe272f2d05 --- /dev/null +++ b/sklearn/linear_model/tests/test_theil_sen.py @@ -0,0 +1,285 @@ +""" +Testing for Theil-Sen module (sklearn.linear_model.theil_sen) +""" + +# Author: Florian Wilhelm +# License: BSD 3 clause + +from __future__ import division, print_function, absolute_import + +import os +import sys +from contextlib import contextmanager +import numpy as np +from numpy.testing import assert_array_equal, assert_array_less +from numpy.testing import assert_array_almost_equal, assert_warns +from scipy.linalg import norm +from scipy.optimize import fmin_bfgs +from nose.tools import raises, assert_almost_equal +from sklearn.utils import ConvergenceWarning +from sklearn.linear_model import LinearRegression, TheilSenRegressor +from sklearn.linear_model.theil_sen import _spatial_median, _breakdown_point +from sklearn.linear_model.theil_sen import _modified_weiszfeld_step +from sklearn.utils.testing import assert_greater, assert_less + + +@contextmanager +def no_stdout_stderr(): + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = open(os.devnull, 'w') + sys.stderr = open(os.devnull, 'w') + yield + sys.stdout.flush() + sys.stderr.flush() + sys.stdout = old_stdout + sys.stderr = old_stderr + + +def gen_toy_problem_1d(intercept=True): + random_state = np.random.RandomState(0) + # Linear model y = 3*x + N(2, 0.1**2) + w = 3. + if intercept: + c = 2. + n_samples = 50 + else: + c = 0.1 + n_samples = 100 + x = random_state.normal(size=n_samples) + noise = 0.1 * random_state.normal(size=n_samples) + y = w * x + c + noise + # Add some outliers + if intercept: + x[42], y[42] = (-2, 4) + x[43], y[43] = (-2.5, 8) + x[33], y[33] = (2.5, 1) + x[49], y[49] = (2.1, 2) + else: + x[42], y[42] = (-2, 4) + x[43], y[43] = (-2.5, 8) + x[53], y[53] = (2.5, 1) + x[60], y[60] = (2.1, 2) + x[72], y[72] = (1.8, -7) + return x[:, np.newaxis], y, w, c + + +def gen_toy_problem_2d(): + random_state = np.random.RandomState(0) + n_samples = 100 + # Linear model y = 5*x_1 + 10*x_2 + N(1, 0.1**2) + X = random_state.normal(size=(n_samples, 2)) + w = np.array([5., 10.]) + c = 1. + noise = 0.1 * random_state.normal(size=n_samples) + y = np.dot(X, w) + c + noise + # Add some outliers + n_outliers = n_samples // 10 + ix = random_state.randint(0, n_samples, size=n_outliers) + y[ix] = 50 * random_state.normal(size=n_outliers) + return X, y, w, c + + +def gen_toy_problem_4d(): + random_state = np.random.RandomState(0) + n_samples = 10000 + # Linear model y = 5*x_1 + 10*x_2 + 42*x_3 + 7*x_4 + N(1, 0.1**2) + X = random_state.normal(size=(n_samples, 4)) + w = np.array([5., 10., 42., 7.]) + c = 1. + noise = 0.1 * random_state.normal(size=n_samples) + y = np.dot(X, w) + c + noise + # Add some outliers + n_outliers = n_samples // 10 + ix = random_state.randint(0, n_samples, size=n_outliers) + y[ix] = 50 * random_state.normal(size=n_outliers) + return X, y, w, c + + +def test_modweiszfeld_step_1d(): + X = np.array([1., 2., 3.]).reshape(3, 1) + # Check startvalue is element of X and solution + median = 2. + new_y = _modified_weiszfeld_step(X, median) + assert_array_almost_equal(new_y, median) + # Check startvalue is not the solution + y = 2.5 + new_y = _modified_weiszfeld_step(X, y) + assert_array_less(median, new_y) + assert_array_less(new_y, y) + # Check startvalue is not the solution but element of X + y = 3. + new_y = _modified_weiszfeld_step(X, y) + assert_array_less(median, new_y) + assert_array_less(new_y, y) + # Check that a single vector is identity + X = np.array([1., 2., 3.]).reshape(1, 3) + y = X[0, ] + new_y = _modified_weiszfeld_step(X, y) + assert_array_equal(y, new_y) + + +def test_modweiszfeld_step_2d(): + X = np.array([0., 0., 1., 1., 0., 1.]).reshape(3, 2) + y = np.array([0.5, 0.5]) + # Check first two iterations + new_y = _modified_weiszfeld_step(X, y) + assert_array_almost_equal(new_y, np.array([1 / 3, 2 / 3])) + new_y = _modified_weiszfeld_step(X, new_y) + assert_array_almost_equal(new_y, np.array([0.2792408, 0.7207592])) + # Check fix point + y = np.array([0.21132505, 0.78867497]) + new_y = _modified_weiszfeld_step(X, y) + assert_array_almost_equal(new_y, y) + + +def test_spatial_median_1d(): + X = np.array([1., 2., 3.]).reshape(3, 1) + true_median = 2. + _, median = _spatial_median(X) + assert_array_almost_equal(median, true_median) + # Test larger problem and for exact solution in 1d case + random_state = np.random.RandomState(0) + X = random_state.randint(100, size=(1000, 1)) + true_median = np.median(X.ravel()) + _, median = _spatial_median(X) + assert_array_equal(median, true_median) + + +def test_spatial_median_2d(): + X = np.array([0., 0., 1., 1., 0., 1.]).reshape(3, 2) + _, median = _spatial_median(X, max_iter=100, tol=1.e-6) + + def cost_func(y): + dists = np.array([norm(x - y) for x in X]) + return np.sum(dists) + + # Check if median is solution of the Fermat-Weber location problem + fermat_weber = fmin_bfgs(cost_func, median, disp=False) + assert_array_almost_equal(median, fermat_weber) + # Check when maximum iteration is exceeded a warning is emitted + assert_warns(ConvergenceWarning, _spatial_median, X, max_iter=30, tol=0.) + + +def test_theil_sen_1d(): + X, y, w, c = gen_toy_problem_1d() + # Check that Least Squares fails + lstq = LinearRegression().fit(X, y) + assert_greater(np.abs(lstq.coef_ - w), 0.9) + # Check that Theil-Sen works + theil_sen = TheilSenRegressor(random_state=0).fit(X, y) + assert_array_almost_equal(theil_sen.coef_, w, 1) + assert_array_almost_equal(theil_sen.intercept_, c, 1) + + +def test_theil_sen_1d_no_intercept(): + X, y, w, c = gen_toy_problem_1d(intercept=False) + # Check that Least Squares fails + lstq = LinearRegression(fit_intercept=False).fit(X, y) + assert_greater(np.abs(lstq.coef_ - w - c), 0.5) + # Check that Theil-Sen works + theil_sen = TheilSenRegressor(fit_intercept=False, + random_state=0).fit(X, y) + assert_array_almost_equal(theil_sen.coef_, w + c, 1) + assert_almost_equal(theil_sen.intercept_, 0.) + + +def test_theil_sen_2d(): + X, y, w, c = gen_toy_problem_2d() + # Check that Least Squares fails + lstq = LinearRegression().fit(X, y) + assert_greater(norm(lstq.coef_ - w), 1.0) + # Check that Theil-Sen works + theil_sen = TheilSenRegressor(max_subpopulation=1e3, + random_state=0).fit(X, y) + assert_array_almost_equal(theil_sen.coef_, w, 1) + assert_array_almost_equal(theil_sen.intercept_, c, 1) + + +def test_calc_breakdown_point(): + bp = _breakdown_point(1e10, 2) + assert_less(np.abs(bp - 1 + 1/(np.sqrt(2))), 1.e-6) + + +@raises(ValueError) +def test_checksubparams_negative_subpopulation(): + X, y, w, c = gen_toy_problem_1d() + TheilSenRegressor(max_subpopulation=-1, random_state=0).fit(X, y) + + +@raises(ValueError) +def test_checksubparams_too_few_subsamples(): + X, y, w, c = gen_toy_problem_1d() + TheilSenRegressor(n_subsamples=1, random_state=0).fit(X, y) + + +@raises(ValueError) +def test_checksubparams_too_many_subsamples(): + X, y, w, c = gen_toy_problem_1d() + TheilSenRegressor(n_subsamples=101, random_state=0).fit(X, y) + + +@raises(ValueError) +def test_checksubparams_n_subsamples_if_less_samples_than_features(): + random_state = np.random.RandomState(0) + n_samples, n_features = 10, 20 + X = random_state.normal(size=(n_samples, n_features)) + y = random_state.normal(size=n_samples) + TheilSenRegressor(n_subsamples=9, random_state=0).fit(X, y) + + +def test_subpopulation(): + X, y, w, c = gen_toy_problem_4d() + theil_sen = TheilSenRegressor(max_subpopulation=250, + random_state=0).fit(X, y) + assert_array_almost_equal(theil_sen.coef_, w, 1) + assert_array_almost_equal(theil_sen.intercept_, c, 1) + + +def test_subsamples(): + X, y, w, c = gen_toy_problem_4d() + theil_sen = TheilSenRegressor(n_subsamples=X.shape[0], + random_state=0).fit(X, y) + lstq = LinearRegression().fit(X, y) + # Check for exact the same results as Least Squares + assert_array_almost_equal(theil_sen.coef_, lstq.coef_, 9) + + +def test_verbosity(): + X, y, w, c = gen_toy_problem_1d() + # Check that Theil-Sen can be verbose + with no_stdout_stderr(): + TheilSenRegressor(verbose=True, random_state=0).fit(X, y) + TheilSenRegressor(verbose=True, + max_subpopulation=10, + random_state=0).fit(X, y) + + +def test_theil_sen_parallel(): + X, y, w, c = gen_toy_problem_2d() + # Check that Least Squares fails + lstq = LinearRegression().fit(X, y) + assert_greater(norm(lstq.coef_ - w), 1.0) + # Check that Theil-Sen works + theil_sen = TheilSenRegressor(n_jobs=-1, + random_state=0, + max_subpopulation=2e3).fit(X, y) + assert_array_almost_equal(theil_sen.coef_, w, 1) + assert_array_almost_equal(theil_sen.intercept_, c, 1) + + +def test_less_samples_than_features(): + random_state = np.random.RandomState(0) + n_samples, n_features = 10, 20 + X = random_state.normal(size=(n_samples, n_features)) + y = random_state.normal(size=n_samples) + # Check that Theil-Sen falls back to Least Squares if fit_intercept=False + theil_sen = TheilSenRegressor(fit_intercept=False, + random_state=0).fit(X, y) + lstq = LinearRegression(fit_intercept=False).fit(X, y) + assert_array_almost_equal(theil_sen.coef_, lstq.coef_, 12) + # Check fit_intercept=True case. This will not be equal to the Least + # Squares solution since the intercept is calculated differently. + theil_sen = TheilSenRegressor(fit_intercept=True, random_state=0).fit(X, y) + y_pred = theil_sen.predict(X) + assert_array_almost_equal(y_pred, y, 12) diff --git a/sklearn/linear_model/theil_sen.py b/sklearn/linear_model/theil_sen.py new file mode 100644 index 0000000000000..0705162e12fd2 --- /dev/null +++ b/sklearn/linear_model/theil_sen.py @@ -0,0 +1,388 @@ +# -*- coding: utf-8 -*- +""" +A Theil-Sen Estimator for Multiple Linear Regression Model +""" + +# Author: Florian Wilhelm +# +# License: BSD 3 clause + +from __future__ import division, print_function, absolute_import + +import warnings +from itertools import combinations + +import numpy as np +from scipy import linalg +from scipy.special import binom +from scipy.linalg.lapack import get_lapack_funcs + +from .base import LinearModel +from ..base import RegressorMixin +from ..utils import check_array, check_random_state, ConvergenceWarning +from ..utils import check_consistent_length, _get_n_jobs +from ..utils.random import choice +from ..externals.joblib import Parallel, delayed +from ..externals.six.moves import xrange as range + +_EPSILON = np.finfo(np.double).eps + + +def _modified_weiszfeld_step(X, x_old): + """Modified Weiszfeld step. + + This function defines one iteration step in order to approximate the + spatial median (L1 median). It is a form of an iteratively re-weighted + least squares method. + + Parameters + ---------- + X : array, shape = [n_samples, n_features] + Training vector, where n_samples is the number of samples and + n_features is the number of features. + + x_old : array, shape = [n_features] + Current start vector. + + Returns + ------- + x_new : array, shape = [n_features] + New iteration step. + + References + ---------- + - On Computation of Spatial Median for Robust Data Mining, 2005 + T. Kärkkäinen and S. Äyrämö + http://users.jyu.fi/~samiayr/pdf/ayramo_eurogen05.pdf + """ + diff = X - x_old + diff_norm = np.sqrt(np.sum(diff ** 2, axis=1)) + mask = diff_norm >= _EPSILON + # x_old equals one of our samples + is_x_old_in_X = int(mask.sum() < X.shape[0]) + + diff = diff[mask] + diff_norm = diff_norm[mask][:, np.newaxis] + quotient_norm = linalg.norm(np.sum(diff / diff_norm, axis=0)) + + if quotient_norm > _EPSILON: # to avoid division by zero + new_direction = (np.sum(X[mask, :] / diff_norm, axis=0) + / np.sum(1 / diff_norm, axis=0)) + else: + new_direction = 1. + quotient_norm = 1. + + return (max(0., 1. - is_x_old_in_X / quotient_norm) * new_direction + + min(1., is_x_old_in_X / quotient_norm) * x_old) + + +def _spatial_median(X, max_iter=300, tol=1.e-3): + """Spatial median (L1 median). + + The spatial median is member of a class of so-called M-estimators which + are defined by an optimization problem. Given a number of p points in an + n-dimensional space, the point x minimizing the sum of all distances to the + p other points is called spatial median. + + Parameters + ---------- + X : array, shape = [n_samples, n_features] + Training vector, where n_samples is the number of samples and + n_features is the number of features. + + max_iter : int, optional + Maximum number of iterations. Default is 300. + + tol : float, optional + Stop the algorithm if spatial_median has converged. Default is 1.e-3. + + Returns + ------- + spatial_median : array, shape = [n_features] + Spatial median. + + n_iter: int + Number of iterations needed. + + References + ---------- + - On Computation of Spatial Median for Robust Data Mining, 2005 + T. Kärkkäinen and S. Äyrämö + http://users.jyu.fi/~samiayr/pdf/ayramo_eurogen05.pdf + """ + if X.shape[1] == 1: + return 1, np.median(X.ravel()) + + tol **= 2 # We are computing the tol on the squared norm + spatial_median_old = np.mean(X, axis=0) + + for n_iter in range(max_iter): + spatial_median = _modified_weiszfeld_step(X, spatial_median_old) + if np.sum((spatial_median_old - spatial_median) ** 2) < tol: + break + else: + spatial_median_old = spatial_median + else: + warnings.warn("Maximum number of iterations {max_iter} reached in " + "spatial median for TheilSen regressor." + "".format(max_iter=max_iter), ConvergenceWarning) + + return n_iter, spatial_median + + +def _breakdown_point(n_samples, n_subsamples): + """Approximation of the breakdown point. + + Parameters + ---------- + n_samples : int + Number of samples. + + n_subsamples : int + Number of subsamples to consider. + + Returns + ------- + breakdown_point : float + Approximation of breakdown point. + """ + return 1 - (0.5 ** (1 / n_subsamples) * (n_samples - n_subsamples + 1) + + n_subsamples - 1) / n_samples + + +def _lstsq(X, y, indices, fit_intercept): + """Least Squares Estimator for TheilSenRegressor class. + + This function calculates the least squares method on a subset of rows of X + and y defined by the indices array. Optionally, an intercept column is + added if intercept is set to true. + + Parameters + ---------- + X : array, shape = [n_samples, n_features] + Design matrix, where n_samples is the number of samples and + n_features is the number of features. + + y : array, shape = [n_samples] + Target vector, where n_samples is the number of samples. + + indices : array, shape = [n_subpopulation, n_subsamples] + Indices of all subsamples with respect to the chosen subpopulation. + + fit_intercept : bool + Fit intercept or not. + + Returns + ------- + weights : array, shape = [n_subpopulation, n_features + intercept] + Solution matrix of n_subpopulation solved least square problems. + """ + fit_intercept = int(fit_intercept) + n_features = X.shape[1] + fit_intercept + n_subsamples = indices.shape[1] + weights = np.empty((indices.shape[0], n_features)) + X_subpopulation = np.ones((n_subsamples, n_features)) + # gelss need to pad y_subpopulation to be of the max dim of X_subpopulation + y_subpopulation = np.zeros((max(n_subsamples, n_features))) + lstsq, = get_lapack_funcs(('gelss',), (X_subpopulation, y_subpopulation)) + + for index, subset in enumerate(indices): + X_subpopulation[:, fit_intercept:] = X[subset, :] + y_subpopulation[:n_subsamples] = y[subset] + weights[index] = lstsq(X_subpopulation, + y_subpopulation)[1][:n_features] + + return weights + + +class TheilSenRegressor(LinearModel, RegressorMixin): + """Theil-Sen Estimator: robust multivariate regression model. + + The algorithm calculates least square solutions on subsets with size + n_subsamples of the samples in X. Any value of n_subsamples between the + number of features and samples leads to an estimator with a compromise + between robustness and efficiency. Since the number of least square + solutions is "n_samples choose n_subsamples", it can be extremely large + and can therefore be limited with max_subpopulation. If this limit is + reached, the subsets are chosen randomly. In a final step, the spatial + median (or L1 median) is calculated of all least square solutions. + + Parameters + ---------- + fit_intercept : boolean, optional, default True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations. + + copy_X : boolean, optional, default True + If True, X will be copied; else, it may be overwritten. + + max_subpopulation : int, optional, default 1e4 + Instead of computing with a set of cardinality 'n choose k', where n is + the number of samples and k is the number of subsamples (at least + number of features), consider only a stochastic subpopulation of a + given maximal size if 'n choose k' is larger than max_subpopulation. + For other than small problem sizes this parameter will determine + memory usage and runtime if n_subsamples is not changed. + + n_subsamples : int, optional, default None + Number of samples to calculate the parameters. This is at least the + number of features (plus 1 if fit_intercept=True) and the number of + samples as a maximum. A lower number leads to a higher breakdown + point and a low efficiency while a high number leads to a low + breakdown point and a high efficiency. If None, take the + minimum number of subsamples leading to maximal robustness. + If n_subsamples is set to n_samples, Theil-Sen is identical to least + squares. + + max_iter : int, optional, default 300 + Maximum number of iterations for the calculation of spatial median. + + tol : float, optional, default 1.e-3 + Tolerance when calculating spatial median. + + random_state : RandomState or an int seed, optional, default None + A random number generator instance to define the state of the + random permutations generator. + + n_jobs : integer, optional, default 1 + Number of CPUs to use during the cross validation. If ``-1``, use + all the CPUs. + + verbose : boolean, optional, default False + Verbose mode when fitting the model. + + Attributes + ---------- + `coef_` : array, shape = (n_features) + Coefficients of the regression model (median of distribution). + + `intercept_` : float + Estimated intercept of regression model. + + `breakdown_` : float + Approximated breakdown point. + + `n_iter_` : int + Number of iterations needed for the spatial median. + + n_subpopulation_ : int + Number of combinations taken into account from 'n choose k', where n is + the number of samples and k is the number of subsamples. + + References + ---------- + - Theil-Sen Estimators in a Multiple Linear Regression Model, 2009 + Xin Dang, Hanxiang Peng, Xueqin Wang and Heping Zhang + http://www.math.iupui.edu/~hpeng/MTSE_0908.pdf + """ + + def __init__(self, fit_intercept=True, copy_X=True, + max_subpopulation=1e4, n_subsamples=None, max_iter=300, + tol=1.e-3, random_state=None, n_jobs=1, verbose=False): + self.fit_intercept = fit_intercept + self.copy_X = copy_X + self.max_subpopulation = int(max_subpopulation) + self.n_subsamples = n_subsamples + self.max_iter = max_iter + self.tol = tol + self.random_state = random_state + self.n_jobs = n_jobs + self.verbose = verbose + + def _check_subparams(self, n_samples, n_features): + n_subsamples = self.n_subsamples + + if self.fit_intercept: + n_dim = n_features + 1 + else: + n_dim = n_features + + if n_subsamples is not None: + if n_subsamples > n_samples: + raise ValueError("Invalid parameter since n_subsamples > " + "n_samples ({0} > {1}).".format(n_subsamples, + n_samples)) + if n_samples >= n_features: + if n_dim > n_subsamples: + plus_1 = "+1" if self.fit_intercept else "" + raise ValueError("Invalid parameter since n_features{0} " + "> n_subsamples ({1} > {2})." + "".format(plus_1, n_dim, n_samples)) + else: # if n_samples < n_features + if n_subsamples != n_samples: + raise ValueError("Invalid parameter since n_subsamples != " + "n_samples ({0} != {1}) while n_samples " + "< n_features.".format(n_subsamples, + n_samples)) + else: + n_subsamples = min(n_dim, n_samples) + + if self.max_subpopulation <= 0: + raise ValueError("Subpopulation must be strictly positive " + "({0} <= 0).".format(self.max_subpopulation)) + + all_combinations = max(1, np.rint(binom(n_samples, n_subsamples))) + n_subpopulation = int(min(self.max_subpopulation, all_combinations)) + + return n_subsamples, n_subpopulation + + def fit(self, X, y): + """Fit linear model. + + Parameters + ---------- + X : numpy array of shape [n_samples, n_features] + Training data + y : numpy array of shape [n_samples] + Target values + + Returns + ------- + self : returns an instance of self. + """ + random_state = check_random_state(self.random_state) + X = check_array(X) + y = check_array(y, ensure_2d=False) + check_consistent_length(X, y) + n_samples, n_features = X.shape + n_subsamples, self.n_subpopulation_ = self._check_subparams(n_samples, + n_features) + self.breakdown_ = _breakdown_point(n_samples, n_subsamples) + + if self.verbose: + print("Breakdown point: {0}".format(self.breakdown_)) + print("Number of samples: {0}".format(n_samples)) + tol_outliers = int(self.breakdown_ * n_samples) + print("Tolerable outliers: {0}".format(tol_outliers)) + print("Number of subpopulations: {0}".format( + self.n_subpopulation_)) + + # Determine indices of subpopulation + if np.rint(binom(n_samples, n_subsamples)) <= self.max_subpopulation: + indices = list(combinations(range(n_samples), n_subsamples)) + else: + indices = [choice(n_samples, + size=n_subsamples, + replace=False, + random_state=random_state) + for _ in range(self.n_subpopulation_)] + + n_jobs = _get_n_jobs(self.n_jobs) + index_list = np.array_split(indices, n_jobs) + weights = Parallel(n_jobs=n_jobs, + verbose=self.verbose)( + delayed(_lstsq)(X, y, index_list[job], self.fit_intercept) + for job in range(n_jobs)) + weights = np.vstack(weights) + self.n_iter_, coefs = _spatial_median(weights, + max_iter=self.max_iter, + tol=self.tol) + + if self.fit_intercept: + self.intercept_ = coefs[0] + self.coef_ = coefs[1:] + else: + self.intercept_ = 0. + self.coef_ = coefs + + return self diff --git a/sklearn/manifold/__init__.py b/sklearn/manifold/__init__.py index 7ae011739adf4..c16d87881a1ad 100644 --- a/sklearn/manifold/__init__.py +++ b/sklearn/manifold/__init__.py @@ -5,3 +5,8 @@ from .locally_linear import locally_linear_embedding, LocallyLinearEmbedding from .isomap import Isomap from .mds import MDS +from .spectral_embedding_ import SpectralEmbedding, spectral_embedding +from .t_sne import TSNE + +__all__ = ['locally_linear_embedding', 'LocallyLinearEmbedding', 'Isomap', + 'MDS', 'SpectralEmbedding', 'spectral_embedding', "TSNE"] diff --git a/sklearn/manifold/_utils.c b/sklearn/manifold/_utils.c new file mode 100644 index 0000000000000..237896982ef20 --- /dev/null +++ b/sklearn/manifold/_utils.c @@ -0,0 +1,6607 @@ +/* Generated by Cython 0.20.1 on Thu Jun 5 16:28:05 2014 */ + +#define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#define CYTHON_ABI "0_20_1" +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if CYTHON_COMPILING_IN_PYPY +#define Py_OptimizeFlag 0 +#endif +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT) + #define Py_TPFLAGS_IS_ABSTRACT 0 +#endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_VERSION_HEX < 0x030200A4 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__manifold___utils +#define __PYX_HAVE_API__sklearn__manifold___utils +#include "math.h" +#include "string.h" +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#include "numpy/npy_math.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +#ifdef __GNUC__ + /* Test for GCC > 2.95 */ + #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) + #else /* __GNUC__ > 2 ... */ + #define likely(x) (x) + #define unlikely(x) (x) + #endif /* __GNUC__ > 2 ... */ +#else /* __GNUC__ */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "_utils.pyx", + "__init__.pxd", + "type.pxd", +}; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":723 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":724 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":725 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":726 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":730 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":731 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":732 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":733 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":737 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":738 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":747 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":748 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":749 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":751 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":752 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":753 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":755 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":756 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":758 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":759 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":760 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":762 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":763 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":764 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":766 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +#define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) +static CYTHON_INLINE long __Pyx_mod_long(long, long); /* proto */ + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); /*proto*/ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static int __Pyx_Print(PyObject*, PyObject *, int); /*proto*/ +#if CYTHON_COMPILING_IN_PYPY || PY_MAJOR_VERSION >= 3 +static PyObject* __pyx_print = 0; +static PyObject* __pyx_print_kwargs = 0; +#endif + +static int __Pyx_PrintOne(PyObject* stream, PyObject *o); /*proto*/ + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); + +static int __Pyx_check_binary_version(void); + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'libc' */ + +/* Module declarations from 'libc.math' */ + +/* Module declarations from 'cython' */ + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'sklearn.manifold._utils' */ +static double __pyx_v_7sklearn_8manifold_6_utils_EPSILON_DBL; +static double __pyx_v_7sklearn_8manifold_6_utils_PERPLEXITY_TOLERANCE; +static PyArrayObject *__pyx_f_7sklearn_8manifold_6_utils__binary_search_perplexity(PyArrayObject *, double, int, int __pyx_skip_dispatch); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float_t = { "float_t", NULL, sizeof(__pyx_t_5numpy_float_t), { 0 }, 0, 'R', 0, 0 }; +#define __Pyx_MODULE_NAME "sklearn.manifold._utils" +int __pyx_module_is_main_sklearn__manifold___utils = 0; + +/* Implementation of 'sklearn.manifold._utils' */ +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_pf_7sklearn_8manifold_6_utils__binary_search_perplexity(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_affinities, double __pyx_v_desired_perplexity, int __pyx_v_verbose); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static char __pyx_k_B[] = "B"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_end[] = "end"; +static char __pyx_k_file[] = "file"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_mean[] = "mean"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_print[] = "print"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_double[] = "double"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_verbose[] = "verbose"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_affinities[] = "affinities"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k_pyx_releasebuffer[] = "__pyx_releasebuffer"; +static char __pyx_k_desired_perplexity[] = "desired_perplexity"; +static char __pyx_k_t_SNE_Mean_sigma_f[] = "[t-SNE] Mean sigma: %f"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_t_SNE_Computed_conditional_prob[] = "[t-SNE] Computed conditional probabilities for sample %d / %d"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_affinities; +static PyObject *__pyx_n_s_desired_perplexity; +static PyObject *__pyx_n_s_double; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_end; +static PyObject *__pyx_n_s_file; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_mean; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_print; +static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_releasebuffer; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_kp_s_t_SNE_Computed_conditional_prob; +static PyObject *__pyx_kp_s_t_SNE_Mean_sigma_f; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_verbose; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; + +/* "sklearn/manifold/_utils.pyx":14 + * + * @cython.boundscheck(False) + * cpdef np.ndarray[np.float_t, ndim=2] _binary_search_perplexity( # <<<<<<<<<<<<<< + * np.ndarray[np.float_t, ndim=2] affinities, double desired_perplexity, + * int verbose): + */ + +static PyObject *__pyx_pw_7sklearn_8manifold_6_utils_1_binary_search_perplexity(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyArrayObject *__pyx_f_7sklearn_8manifold_6_utils__binary_search_perplexity(PyArrayObject *__pyx_v_affinities, double __pyx_v_desired_perplexity, int __pyx_v_verbose, CYTHON_UNUSED int __pyx_skip_dispatch) { + int __pyx_v_n_steps; + int __pyx_v_n_samples; + PyArrayObject *__pyx_v_P = 0; + double __pyx_v_beta; + double __pyx_v_beta_min; + double __pyx_v_beta_max; + double __pyx_v_beta_sum; + double __pyx_v_desired_entropy; + double __pyx_v_entropy_diff; + double __pyx_v_entropy; + double __pyx_v_sum_Pi; + double __pyx_v_sum_disti_Pi; + int __pyx_v_i; + int __pyx_v_j; + CYTHON_UNUSED int __pyx_v__; + __Pyx_LocalBuf_ND __pyx_pybuffernd_P; + __Pyx_Buffer __pyx_pybuffer_P; + __Pyx_LocalBuf_ND __pyx_pybuffernd_affinities; + __Pyx_Buffer __pyx_pybuffer_affinities; + PyArrayObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + int __pyx_t_17; + int __pyx_t_18; + int __pyx_t_19; + int __pyx_t_20; + int __pyx_t_21; + int __pyx_t_22; + int __pyx_t_23; + int __pyx_t_24; + int __pyx_t_25; + int __pyx_t_26; + int __pyx_t_27; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_binary_search_perplexity", 0); + __pyx_pybuffer_P.pybuffer.buf = NULL; + __pyx_pybuffer_P.refcount = 0; + __pyx_pybuffernd_P.data = NULL; + __pyx_pybuffernd_P.rcbuffer = &__pyx_pybuffer_P; + __pyx_pybuffer_affinities.pybuffer.buf = NULL; + __pyx_pybuffer_affinities.refcount = 0; + __pyx_pybuffernd_affinities.data = NULL; + __pyx_pybuffernd_affinities.rcbuffer = &__pyx_pybuffer_affinities; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_affinities.rcbuffer->pybuffer, (PyObject*)__pyx_v_affinities, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_affinities.diminfo[0].strides = __pyx_pybuffernd_affinities.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_affinities.diminfo[0].shape = __pyx_pybuffernd_affinities.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_affinities.diminfo[1].strides = __pyx_pybuffernd_affinities.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_affinities.diminfo[1].shape = __pyx_pybuffernd_affinities.rcbuffer->pybuffer.shape[1]; + + /* "sklearn/manifold/_utils.pyx":43 + * """ + * # Maximum number of binary search steps + * cdef int n_steps = 100 # <<<<<<<<<<<<<< + * + * cdef int n_samples = affinities.shape[0] + */ + __pyx_v_n_steps = 100; + + /* "sklearn/manifold/_utils.pyx":45 + * cdef int n_steps = 100 + * + * cdef int n_samples = affinities.shape[0] # <<<<<<<<<<<<<< + * cdef np.ndarray[np.float_t, ndim=2] P = np.ndarray((n_samples, n_samples), + * dtype=np.double) + */ + __pyx_v_n_samples = (__pyx_v_affinities->dimensions[0]); + + /* "sklearn/manifold/_utils.pyx":46 + * + * cdef int n_samples = affinities.shape[0] + * cdef np.ndarray[np.float_t, ndim=2] P = np.ndarray((n_samples, n_samples), # <<<<<<<<<<<<<< + * dtype=np.double) + * # Precisions of conditional Gaussian distrubutions + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_n_samples); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "sklearn/manifold/_utils.pyx":47 + * cdef int n_samples = affinities.shape[0] + * cdef np.ndarray[np.float_t, ndim=2] P = np.ndarray((n_samples, n_samples), + * dtype=np.double) # <<<<<<<<<<<<<< + * # Precisions of conditional Gaussian distrubutions + * cdef double beta + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_double); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "sklearn/manifold/_utils.pyx":46 + * + * cdef int n_samples = affinities.shape[0] + * cdef np.ndarray[np.float_t, ndim=2] P = np.ndarray((n_samples, n_samples), # <<<<<<<<<<<<<< + * dtype=np.double) + * # Precisions of conditional Gaussian distrubutions + */ + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_5numpy_ndarray)), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_P.rcbuffer->pybuffer, (PyObject*)((PyArrayObject *)__pyx_t_4), &__Pyx_TypeInfo_nn___pyx_t_5numpy_float_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) { + __pyx_v_P = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_P.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_P.diminfo[0].strides = __pyx_pybuffernd_P.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_P.diminfo[0].shape = __pyx_pybuffernd_P.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_P.diminfo[1].strides = __pyx_pybuffernd_P.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_P.diminfo[1].shape = __pyx_pybuffernd_P.rcbuffer->pybuffer.shape[1]; + } + } + __pyx_v_P = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/manifold/_utils.pyx":52 + * cdef double beta_min + * cdef double beta_max + * cdef double beta_sum = 0.0 # <<<<<<<<<<<<<< + * # Now we go to log scale + * cdef double desired_entropy = math.log(desired_perplexity) + */ + __pyx_v_beta_sum = 0.0; + + /* "sklearn/manifold/_utils.pyx":54 + * cdef double beta_sum = 0.0 + * # Now we go to log scale + * cdef double desired_entropy = math.log(desired_perplexity) # <<<<<<<<<<<<<< + * cdef double entropy_diff + * + */ + __pyx_v_desired_entropy = log(__pyx_v_desired_perplexity); + + /* "sklearn/manifold/_utils.pyx":63 + * cdef int j + * + * for i in range(n_samples): # <<<<<<<<<<<<<< + * beta_min = -NPY_INFINITY + * beta_max = NPY_INFINITY + */ + __pyx_t_5 = __pyx_v_n_samples; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "sklearn/manifold/_utils.pyx":64 + * + * for i in range(n_samples): + * beta_min = -NPY_INFINITY # <<<<<<<<<<<<<< + * beta_max = NPY_INFINITY + * beta = 1.0 + */ + __pyx_v_beta_min = (-NPY_INFINITY); + + /* "sklearn/manifold/_utils.pyx":65 + * for i in range(n_samples): + * beta_min = -NPY_INFINITY + * beta_max = NPY_INFINITY # <<<<<<<<<<<<<< + * beta = 1.0 + * + */ + __pyx_v_beta_max = NPY_INFINITY; + + /* "sklearn/manifold/_utils.pyx":66 + * beta_min = -NPY_INFINITY + * beta_max = NPY_INFINITY + * beta = 1.0 # <<<<<<<<<<<<<< + * + * # Binary search of precision for i-th conditional distribution + */ + __pyx_v_beta = 1.0; + + /* "sklearn/manifold/_utils.pyx":69 + * + * # Binary search of precision for i-th conditional distribution + * for _ in range(n_steps): # <<<<<<<<<<<<<< + * # Compute current entropy and corresponding probabilities + * for j in range(n_samples): + */ + __pyx_t_7 = __pyx_v_n_steps; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v__ = __pyx_t_8; + + /* "sklearn/manifold/_utils.pyx":71 + * for _ in range(n_steps): + * # Compute current entropy and corresponding probabilities + * for j in range(n_samples): # <<<<<<<<<<<<<< + * P[i, j] = math.exp(-affinities[i, j] * beta) + * P[i, i] = 0.0 + */ + __pyx_t_9 = __pyx_v_n_samples; + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { + __pyx_v_j = __pyx_t_10; + + /* "sklearn/manifold/_utils.pyx":72 + * # Compute current entropy and corresponding probabilities + * for j in range(n_samples): + * P[i, j] = math.exp(-affinities[i, j] * beta) # <<<<<<<<<<<<<< + * P[i, i] = 0.0 + * sum_Pi = 0.0 + */ + __pyx_t_11 = __pyx_v_i; + __pyx_t_12 = __pyx_v_j; + if (__pyx_t_11 < 0) __pyx_t_11 += __pyx_pybuffernd_affinities.diminfo[0].shape; + if (__pyx_t_12 < 0) __pyx_t_12 += __pyx_pybuffernd_affinities.diminfo[1].shape; + __pyx_t_13 = __pyx_v_i; + __pyx_t_14 = __pyx_v_j; + if (__pyx_t_13 < 0) __pyx_t_13 += __pyx_pybuffernd_P.diminfo[0].shape; + if (__pyx_t_14 < 0) __pyx_t_14 += __pyx_pybuffernd_P.diminfo[1].shape; + *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_float_t *, __pyx_pybuffernd_P.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_P.diminfo[0].strides, __pyx_t_14, __pyx_pybuffernd_P.diminfo[1].strides) = exp(((-(*__Pyx_BufPtrStrided2d(__pyx_t_5numpy_float_t *, __pyx_pybuffernd_affinities.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_affinities.diminfo[0].strides, __pyx_t_12, __pyx_pybuffernd_affinities.diminfo[1].strides))) * __pyx_v_beta)); + } + + /* "sklearn/manifold/_utils.pyx":73 + * for j in range(n_samples): + * P[i, j] = math.exp(-affinities[i, j] * beta) + * P[i, i] = 0.0 # <<<<<<<<<<<<<< + * sum_Pi = 0.0 + * for j in range(n_samples): + */ + __pyx_t_9 = __pyx_v_i; + __pyx_t_10 = __pyx_v_i; + if (__pyx_t_9 < 0) __pyx_t_9 += __pyx_pybuffernd_P.diminfo[0].shape; + if (__pyx_t_10 < 0) __pyx_t_10 += __pyx_pybuffernd_P.diminfo[1].shape; + *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_float_t *, __pyx_pybuffernd_P.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_P.diminfo[0].strides, __pyx_t_10, __pyx_pybuffernd_P.diminfo[1].strides) = 0.0; + + /* "sklearn/manifold/_utils.pyx":74 + * P[i, j] = math.exp(-affinities[i, j] * beta) + * P[i, i] = 0.0 + * sum_Pi = 0.0 # <<<<<<<<<<<<<< + * for j in range(n_samples): + * sum_Pi += P[i, j] + */ + __pyx_v_sum_Pi = 0.0; + + /* "sklearn/manifold/_utils.pyx":75 + * P[i, i] = 0.0 + * sum_Pi = 0.0 + * for j in range(n_samples): # <<<<<<<<<<<<<< + * sum_Pi += P[i, j] + * if sum_Pi == 0.0: + */ + __pyx_t_15 = __pyx_v_n_samples; + for (__pyx_t_16 = 0; __pyx_t_16 < __pyx_t_15; __pyx_t_16+=1) { + __pyx_v_j = __pyx_t_16; + + /* "sklearn/manifold/_utils.pyx":76 + * sum_Pi = 0.0 + * for j in range(n_samples): + * sum_Pi += P[i, j] # <<<<<<<<<<<<<< + * if sum_Pi == 0.0: + * sum_Pi = EPSILON_DBL + */ + __pyx_t_17 = __pyx_v_i; + __pyx_t_18 = __pyx_v_j; + if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_pybuffernd_P.diminfo[0].shape; + if (__pyx_t_18 < 0) __pyx_t_18 += __pyx_pybuffernd_P.diminfo[1].shape; + __pyx_v_sum_Pi = (__pyx_v_sum_Pi + (*__Pyx_BufPtrStrided2d(__pyx_t_5numpy_float_t *, __pyx_pybuffernd_P.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_P.diminfo[0].strides, __pyx_t_18, __pyx_pybuffernd_P.diminfo[1].strides))); + } + + /* "sklearn/manifold/_utils.pyx":77 + * for j in range(n_samples): + * sum_Pi += P[i, j] + * if sum_Pi == 0.0: # <<<<<<<<<<<<<< + * sum_Pi = EPSILON_DBL + * sum_disti_Pi = 0.0 + */ + __pyx_t_19 = ((__pyx_v_sum_Pi == 0.0) != 0); + if (__pyx_t_19) { + + /* "sklearn/manifold/_utils.pyx":78 + * sum_Pi += P[i, j] + * if sum_Pi == 0.0: + * sum_Pi = EPSILON_DBL # <<<<<<<<<<<<<< + * sum_disti_Pi = 0.0 + * for j in range(n_samples): + */ + __pyx_v_sum_Pi = __pyx_v_7sklearn_8manifold_6_utils_EPSILON_DBL; + goto __pyx_L11; + } + __pyx_L11:; + + /* "sklearn/manifold/_utils.pyx":79 + * if sum_Pi == 0.0: + * sum_Pi = EPSILON_DBL + * sum_disti_Pi = 0.0 # <<<<<<<<<<<<<< + * for j in range(n_samples): + * P[i, j] /= sum_Pi + */ + __pyx_v_sum_disti_Pi = 0.0; + + /* "sklearn/manifold/_utils.pyx":80 + * sum_Pi = EPSILON_DBL + * sum_disti_Pi = 0.0 + * for j in range(n_samples): # <<<<<<<<<<<<<< + * P[i, j] /= sum_Pi + * sum_disti_Pi += affinities[i, j] * P[i, j] + */ + __pyx_t_15 = __pyx_v_n_samples; + for (__pyx_t_16 = 0; __pyx_t_16 < __pyx_t_15; __pyx_t_16+=1) { + __pyx_v_j = __pyx_t_16; + + /* "sklearn/manifold/_utils.pyx":81 + * sum_disti_Pi = 0.0 + * for j in range(n_samples): + * P[i, j] /= sum_Pi # <<<<<<<<<<<<<< + * sum_disti_Pi += affinities[i, j] * P[i, j] + * entropy = math.log(sum_Pi) + beta * sum_disti_Pi + */ + __pyx_t_20 = __pyx_v_i; + __pyx_t_21 = __pyx_v_j; + if (__pyx_t_20 < 0) __pyx_t_20 += __pyx_pybuffernd_P.diminfo[0].shape; + if (__pyx_t_21 < 0) __pyx_t_21 += __pyx_pybuffernd_P.diminfo[1].shape; + *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_float_t *, __pyx_pybuffernd_P.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_P.diminfo[0].strides, __pyx_t_21, __pyx_pybuffernd_P.diminfo[1].strides) /= __pyx_v_sum_Pi; + + /* "sklearn/manifold/_utils.pyx":82 + * for j in range(n_samples): + * P[i, j] /= sum_Pi + * sum_disti_Pi += affinities[i, j] * P[i, j] # <<<<<<<<<<<<<< + * entropy = math.log(sum_Pi) + beta * sum_disti_Pi + * entropy_diff = entropy - desired_entropy + */ + __pyx_t_22 = __pyx_v_i; + __pyx_t_23 = __pyx_v_j; + if (__pyx_t_22 < 0) __pyx_t_22 += __pyx_pybuffernd_affinities.diminfo[0].shape; + if (__pyx_t_23 < 0) __pyx_t_23 += __pyx_pybuffernd_affinities.diminfo[1].shape; + __pyx_t_24 = __pyx_v_i; + __pyx_t_25 = __pyx_v_j; + if (__pyx_t_24 < 0) __pyx_t_24 += __pyx_pybuffernd_P.diminfo[0].shape; + if (__pyx_t_25 < 0) __pyx_t_25 += __pyx_pybuffernd_P.diminfo[1].shape; + __pyx_v_sum_disti_Pi = (__pyx_v_sum_disti_Pi + ((*__Pyx_BufPtrStrided2d(__pyx_t_5numpy_float_t *, __pyx_pybuffernd_affinities.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_affinities.diminfo[0].strides, __pyx_t_23, __pyx_pybuffernd_affinities.diminfo[1].strides)) * (*__Pyx_BufPtrStrided2d(__pyx_t_5numpy_float_t *, __pyx_pybuffernd_P.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_P.diminfo[0].strides, __pyx_t_25, __pyx_pybuffernd_P.diminfo[1].strides)))); + } + + /* "sklearn/manifold/_utils.pyx":83 + * P[i, j] /= sum_Pi + * sum_disti_Pi += affinities[i, j] * P[i, j] + * entropy = math.log(sum_Pi) + beta * sum_disti_Pi # <<<<<<<<<<<<<< + * entropy_diff = entropy - desired_entropy + * + */ + __pyx_v_entropy = (log(__pyx_v_sum_Pi) + (__pyx_v_beta * __pyx_v_sum_disti_Pi)); + + /* "sklearn/manifold/_utils.pyx":84 + * sum_disti_Pi += affinities[i, j] * P[i, j] + * entropy = math.log(sum_Pi) + beta * sum_disti_Pi + * entropy_diff = entropy - desired_entropy # <<<<<<<<<<<<<< + * + * if math.fabs(entropy_diff) <= PERPLEXITY_TOLERANCE: + */ + __pyx_v_entropy_diff = (__pyx_v_entropy - __pyx_v_desired_entropy); + + /* "sklearn/manifold/_utils.pyx":86 + * entropy_diff = entropy - desired_entropy + * + * if math.fabs(entropy_diff) <= PERPLEXITY_TOLERANCE: # <<<<<<<<<<<<<< + * break + * + */ + __pyx_t_19 = ((fabs(__pyx_v_entropy_diff) <= __pyx_v_7sklearn_8manifold_6_utils_PERPLEXITY_TOLERANCE) != 0); + if (__pyx_t_19) { + + /* "sklearn/manifold/_utils.pyx":87 + * + * if math.fabs(entropy_diff) <= PERPLEXITY_TOLERANCE: + * break # <<<<<<<<<<<<<< + * + * if entropy_diff > 0.0: + */ + goto __pyx_L6_break; + } + + /* "sklearn/manifold/_utils.pyx":89 + * break + * + * if entropy_diff > 0.0: # <<<<<<<<<<<<<< + * beta_min = beta + * if beta_max == NPY_INFINITY: + */ + __pyx_t_19 = ((__pyx_v_entropy_diff > 0.0) != 0); + if (__pyx_t_19) { + + /* "sklearn/manifold/_utils.pyx":90 + * + * if entropy_diff > 0.0: + * beta_min = beta # <<<<<<<<<<<<<< + * if beta_max == NPY_INFINITY: + * beta *= 2.0 + */ + __pyx_v_beta_min = __pyx_v_beta; + + /* "sklearn/manifold/_utils.pyx":91 + * if entropy_diff > 0.0: + * beta_min = beta + * if beta_max == NPY_INFINITY: # <<<<<<<<<<<<<< + * beta *= 2.0 + * else: + */ + __pyx_t_19 = ((__pyx_v_beta_max == NPY_INFINITY) != 0); + if (__pyx_t_19) { + + /* "sklearn/manifold/_utils.pyx":92 + * beta_min = beta + * if beta_max == NPY_INFINITY: + * beta *= 2.0 # <<<<<<<<<<<<<< + * else: + * beta = (beta + beta_max) / 2.0 + */ + __pyx_v_beta = (__pyx_v_beta * 2.0); + goto __pyx_L16; + } + /*else*/ { + + /* "sklearn/manifold/_utils.pyx":94 + * beta *= 2.0 + * else: + * beta = (beta + beta_max) / 2.0 # <<<<<<<<<<<<<< + * else: + * beta_max = beta + */ + __pyx_v_beta = ((__pyx_v_beta + __pyx_v_beta_max) / 2.0); + } + __pyx_L16:; + goto __pyx_L15; + } + /*else*/ { + + /* "sklearn/manifold/_utils.pyx":96 + * beta = (beta + beta_max) / 2.0 + * else: + * beta_max = beta # <<<<<<<<<<<<<< + * if beta_min == -NPY_INFINITY: + * beta /= 2.0 + */ + __pyx_v_beta_max = __pyx_v_beta; + + /* "sklearn/manifold/_utils.pyx":97 + * else: + * beta_max = beta + * if beta_min == -NPY_INFINITY: # <<<<<<<<<<<<<< + * beta /= 2.0 + * else: + */ + __pyx_t_19 = ((__pyx_v_beta_min == (-NPY_INFINITY)) != 0); + if (__pyx_t_19) { + + /* "sklearn/manifold/_utils.pyx":98 + * beta_max = beta + * if beta_min == -NPY_INFINITY: + * beta /= 2.0 # <<<<<<<<<<<<<< + * else: + * beta = (beta + beta_min) / 2.0 + */ + __pyx_v_beta = (__pyx_v_beta / 2.0); + goto __pyx_L17; + } + /*else*/ { + + /* "sklearn/manifold/_utils.pyx":100 + * beta /= 2.0 + * else: + * beta = (beta + beta_min) / 2.0 # <<<<<<<<<<<<<< + * + * beta_sum += beta + */ + __pyx_v_beta = ((__pyx_v_beta + __pyx_v_beta_min) / 2.0); + } + __pyx_L17:; + } + __pyx_L15:; + } + __pyx_L6_break:; + + /* "sklearn/manifold/_utils.pyx":102 + * beta = (beta + beta_min) / 2.0 + * + * beta_sum += beta # <<<<<<<<<<<<<< + * + * if verbose and ((i + 1) % 1000 == 0 or i + 1 == n_samples): + */ + __pyx_v_beta_sum = (__pyx_v_beta_sum + __pyx_v_beta); + + /* "sklearn/manifold/_utils.pyx":104 + * beta_sum += beta + * + * if verbose and ((i + 1) % 1000 == 0 or i + 1 == n_samples): # <<<<<<<<<<<<<< + * print("[t-SNE] Computed conditional probabilities for sample " + * "%d / %d" % (i + 1, n_samples)) + */ + if ((__pyx_v_verbose != 0)) { + __pyx_t_19 = (__Pyx_mod_long((__pyx_v_i + 1), 1000) == 0); + if (!__pyx_t_19) { + __pyx_t_26 = ((__pyx_v_i + 1) == __pyx_v_n_samples); + __pyx_t_27 = __pyx_t_26; + } else { + __pyx_t_27 = __pyx_t_19; + } + __pyx_t_19 = __pyx_t_27; + } else { + __pyx_t_19 = (__pyx_v_verbose != 0); + } + if (__pyx_t_19) { + + /* "sklearn/manifold/_utils.pyx":106 + * if verbose and ((i + 1) % 1000 == 0 or i + 1 == n_samples): + * print("[t-SNE] Computed conditional probabilities for sample " + * "%d / %d" % (i + 1, n_samples)) # <<<<<<<<<<<<<< + * + * if verbose: + */ + __pyx_t_4 = __Pyx_PyInt_From_long((__pyx_v_i + 1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_n_samples); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_t_SNE_Computed_conditional_prob, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_PrintOne(0, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L18; + } + __pyx_L18:; + } + + /* "sklearn/manifold/_utils.pyx":108 + * "%d / %d" % (i + 1, n_samples)) + * + * if verbose: # <<<<<<<<<<<<<< + * print("[t-SNE] Mean sigma: %f" + * % np.mean(math.sqrt(n_samples / beta_sum))) + */ + __pyx_t_19 = (__pyx_v_verbose != 0); + if (__pyx_t_19) { + + /* "sklearn/manifold/_utils.pyx":110 + * if verbose: + * print("[t-SNE] Mean sigma: %f" + * % np.mean(math.sqrt(n_samples / beta_sum))) # <<<<<<<<<<<<<< + * return P + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_mean); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(__pyx_v_beta_sum == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "float division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = PyFloat_FromDouble(sqrt((__pyx_v_n_samples / __pyx_v_beta_sum))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_t_SNE_Mean_sigma_f, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_PrintOne(0, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L19; + } + __pyx_L19:; + + /* "sklearn/manifold/_utils.pyx":111 + * print("[t-SNE] Mean sigma: %f" + * % np.mean(math.sqrt(n_samples / beta_sum))) + * return P # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_P)); + __pyx_r = ((PyArrayObject *)__pyx_v_P); + goto __pyx_L0; + + /* "sklearn/manifold/_utils.pyx":14 + * + * @cython.boundscheck(False) + * cpdef np.ndarray[np.float_t, ndim=2] _binary_search_perplexity( # <<<<<<<<<<<<<< + * np.ndarray[np.float_t, ndim=2] affinities, double desired_perplexity, + * int verbose): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_P.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_affinities.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.manifold._utils._binary_search_perplexity", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_P.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_affinities.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_P); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_8manifold_6_utils_1_binary_search_perplexity(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_8manifold_6_utils__binary_search_perplexity[] = "Binary search for sigmas of conditional Gaussians.\n\n We are looking for sigma = sqrt(1/beta) so that the perplexity\n of the conditional distribution p_i|j matches approximately the\n desired value. p_i|j are Gaussian distributed.\n\n The idea has been proposed in \"Stochastic Neighbor Embedding\"\n Geoffrey Hinton and Sam Roweis, 2003.\n\n Parameters\n ----------\n affinities : array-like, shape (n_samples, n_samples)\n Distances between training samples.\n\n desired_perplexity : double\n Desired perplexity (2^entropy) of the conditional Gaussians.\n\n verbose : int\n Verbosity level.\n\n Returns\n -------\n P : array, shape (n_samples, n_samples)\n Probabilities of conditional Gaussian distributions p_i|j.\n "; +static PyObject *__pyx_pw_7sklearn_8manifold_6_utils_1_binary_search_perplexity(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_affinities = 0; + double __pyx_v_desired_perplexity; + int __pyx_v_verbose; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_binary_search_perplexity (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_affinities,&__pyx_n_s_desired_perplexity,&__pyx_n_s_verbose,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_affinities)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_desired_perplexity)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_binary_search_perplexity", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_verbose)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_binary_search_perplexity", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_binary_search_perplexity") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v_affinities = ((PyArrayObject *)values[0]); + __pyx_v_desired_perplexity = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_desired_perplexity == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_verbose = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_verbose == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_binary_search_perplexity", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.manifold._utils._binary_search_perplexity", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_affinities), __pyx_ptype_5numpy_ndarray, 1, "affinities", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_8manifold_6_utils__binary_search_perplexity(__pyx_self, __pyx_v_affinities, __pyx_v_desired_perplexity, __pyx_v_verbose); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_8manifold_6_utils__binary_search_perplexity(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_affinities, double __pyx_v_desired_perplexity, int __pyx_v_verbose) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_affinities; + __Pyx_Buffer __pyx_pybuffer_affinities; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_binary_search_perplexity", 0); + __pyx_pybuffer_affinities.pybuffer.buf = NULL; + __pyx_pybuffer_affinities.refcount = 0; + __pyx_pybuffernd_affinities.data = NULL; + __pyx_pybuffernd_affinities.rcbuffer = &__pyx_pybuffer_affinities; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_affinities.rcbuffer->pybuffer, (PyObject*)__pyx_v_affinities, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_affinities.diminfo[0].strides = __pyx_pybuffernd_affinities.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_affinities.diminfo[0].shape = __pyx_pybuffernd_affinities.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_affinities.diminfo[1].strides = __pyx_pybuffernd_affinities.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_affinities.diminfo[1].shape = __pyx_pybuffernd_affinities.rcbuffer->pybuffer.shape[1]; + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_8manifold_6_utils__binary_search_perplexity(__pyx_v_affinities, __pyx_v_desired_perplexity, __pyx_v_verbose, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_affinities.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.manifold._utils._binary_search_perplexity", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_affinities.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_1) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_3) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":222 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":251 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); + if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_1) { + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< + * info.format + _buffer_format_string_len, + * &offset) + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + long __pyx_t_10; + char *__pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); + __pyx_t_3 = 0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":798 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); + if (__pyx_t_6) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_6 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_6) { + __pyx_t_7 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_7 = __pyx_t_6; + } + if (!__pyx_t_7) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_6 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_6) { + __pyx_t_8 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_9 = __pyx_t_8; + } else { + __pyx_t_9 = __pyx_t_6; + } + __pyx_t_6 = __pyx_t_9; + } else { + __pyx_t_6 = __pyx_t_7; + } + if (__pyx_t_6) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":813 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_6) break; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":818 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_6) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":821 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_6) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L11; + } + /*else*/ { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L11:; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L9; + } + /*else*/ { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_11; + } + __pyx_L9:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":968 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":969 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":971 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":972 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":973 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":974 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":977 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":978 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + /*else*/ { + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":980 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyMethodDef __pyx_methods[] = { + {__Pyx_NAMESTR("_binary_search_perplexity"), (PyCFunction)__pyx_pw_7sklearn_8manifold_6_utils_1_binary_search_perplexity, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_8manifold_6_utils__binary_search_perplexity)}, + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + __Pyx_NAMESTR("_utils"), + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_affinities, __pyx_k_affinities, sizeof(__pyx_k_affinities), 0, 0, 1, 1}, + {&__pyx_n_s_desired_perplexity, __pyx_k_desired_perplexity, sizeof(__pyx_k_desired_perplexity), 0, 0, 1, 1}, + {&__pyx_n_s_double, __pyx_k_double, sizeof(__pyx_k_double), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_end, __pyx_k_end, sizeof(__pyx_k_end), 0, 0, 1, 1}, + {&__pyx_n_s_file, __pyx_k_file, sizeof(__pyx_k_file), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_mean, __pyx_k_mean, sizeof(__pyx_k_mean), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_print, __pyx_k_print, sizeof(__pyx_k_print), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_releasebuffer, __pyx_k_pyx_releasebuffer, sizeof(__pyx_k_pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_kp_s_t_SNE_Computed_conditional_prob, __pyx_k_t_SNE_Computed_conditional_prob, sizeof(__pyx_k_t_SNE_Computed_conditional_prob), 0, 0, 1, 0}, + {&__pyx_kp_s_t_SNE_Mean_sigma_f, __pyx_k_t_SNE_Mean_sigma_f, sizeof(__pyx_k_t_SNE_Mean_sigma_f), 0, 0, 1, 0}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_verbose, __pyx_k_verbose, sizeof(__pyx_k_verbose), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC init_utils(void); /*proto*/ +PyMODINIT_FUNC init_utils(void) +#else +PyMODINIT_FUNC PyInit__utils(void); /*proto*/ +PyMODINIT_FUNC PyInit__utils(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__utils(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_utils"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__manifold___utils) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.manifold._utils")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.manifold._utils", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/manifold/_utils.pyx":3 + * from libc cimport math + * cimport cython + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * cdef extern from "numpy/npy_math.h": + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/manifold/_utils.pyx":9 + * + * + * cdef double EPSILON_DBL = 1e-7 # <<<<<<<<<<<<<< + * cdef double PERPLEXITY_TOLERANCE = 1e-5 + * + */ + __pyx_v_7sklearn_8manifold_6_utils_EPSILON_DBL = 1e-7; + + /* "sklearn/manifold/_utils.pyx":10 + * + * cdef double EPSILON_DBL = 1e-7 + * cdef double PERPLEXITY_TOLERANCE = 1e-5 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_7sklearn_8manifold_6_utils_PERPLEXITY_TOLERANCE = 1e-5; + + /* "sklearn/manifold/_utils.pyx":1 + * from libc cimport math # <<<<<<<<<<<<<< + * cimport cython + * import numpy as np + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "/volatile/ogrisel/envs/py34/lib/python3.4/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.manifold._utils", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.manifold._utils"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; /* Consume from buffer string */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; /* not a 'break' in the loop */ + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case 10: + case 13: + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } /* fall through */ + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 's': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + } else { + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + } + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; +#endif + result = (*call)(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + Py_LeaveRecursiveCall(); +#endif + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +static CYTHON_INLINE long __Pyx_mod_long(long a, long b) { + long r = a % b; + r += ((r != 0) & ((r ^ b) < 0)) * b; + return r; +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(PyObject_TypeCheck(obj, type))) return 1; + } + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); + return 0; +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { + #endif +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } + } + #endif + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: + Py_DECREF(obj); + view->obj = NULL; +} +#endif /* PY_MAJOR_VERSION < 3 */ + + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \ + { \ + func_type value = func(x); \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + PyErr_SetString(PyExc_OverflowError, \ + (is_unsigned && unlikely(value < zero)) ? \ + "can't convert negative value to " #target_type : \ + "value too large to convert to " #target_type); \ + return (target_type) -1; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(int) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); + } +} + +#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION < 3 +static PyObject *__Pyx_GetStdout(void) { + PyObject *f = PySys_GetObject((char *)"stdout"); + if (!f) { + PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); + } + return f; +} +static int __Pyx_Print(PyObject* f, PyObject *arg_tuple, int newline) { + int i; + if (!f) { + if (!(f = __Pyx_GetStdout())) + return -1; + } + Py_INCREF(f); + for (i=0; i < PyTuple_GET_SIZE(arg_tuple); i++) { + PyObject* v; + if (PyFile_SoftSpace(f, 1)) { + if (PyFile_WriteString(" ", f) < 0) + goto error; + } + v = PyTuple_GET_ITEM(arg_tuple, i); + if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) + goto error; + if (PyString_Check(v)) { + char *s = PyString_AsString(v); + Py_ssize_t len = PyString_Size(v); + if (len > 0) { + switch (s[len-1]) { + case ' ': break; + case '\f': case '\r': case '\n': case '\t': case '\v': + PyFile_SoftSpace(f, 0); + break; + default: break; + } + } + } + } + if (newline) { + if (PyFile_WriteString("\n", f) < 0) + goto error; + PyFile_SoftSpace(f, 0); + } + Py_DECREF(f); + return 0; +error: + Py_DECREF(f); + return -1; +} +#else /* Python 3 has a print function */ +static int __Pyx_Print(PyObject* stream, PyObject *arg_tuple, int newline) { + PyObject* kwargs = 0; + PyObject* result = 0; + PyObject* end_string; + if (unlikely(!__pyx_print)) { + __pyx_print = PyObject_GetAttr(__pyx_b, __pyx_n_s_print); + if (!__pyx_print) + return -1; + } + if (stream) { + kwargs = PyDict_New(); + if (unlikely(!kwargs)) + return -1; + if (unlikely(PyDict_SetItem(kwargs, __pyx_n_s_file, stream) < 0)) + goto bad; + if (!newline) { + end_string = PyUnicode_FromStringAndSize(" ", 1); + if (unlikely(!end_string)) + goto bad; + if (PyDict_SetItem(kwargs, __pyx_n_s_end, end_string) < 0) { + Py_DECREF(end_string); + goto bad; + } + Py_DECREF(end_string); + } + } else if (!newline) { + if (unlikely(!__pyx_print_kwargs)) { + __pyx_print_kwargs = PyDict_New(); + if (unlikely(!__pyx_print_kwargs)) + return -1; + end_string = PyUnicode_FromStringAndSize(" ", 1); + if (unlikely(!end_string)) + return -1; + if (PyDict_SetItem(__pyx_print_kwargs, __pyx_n_s_end, end_string) < 0) { + Py_DECREF(end_string); + return -1; + } + Py_DECREF(end_string); + } + kwargs = __pyx_print_kwargs; + } + result = PyObject_Call(__pyx_print, arg_tuple, kwargs); + if (unlikely(kwargs) && (kwargs != __pyx_print_kwargs)) + Py_DECREF(kwargs); + if (!result) + return -1; + Py_DECREF(result); + return 0; +bad: + if (kwargs != __pyx_print_kwargs) + Py_XDECREF(kwargs); + return -1; +} +#endif + +#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION < 3 +static int __Pyx_PrintOne(PyObject* f, PyObject *o) { + if (!f) { + if (!(f = __Pyx_GetStdout())) + return -1; + } + Py_INCREF(f); + if (PyFile_SoftSpace(f, 0)) { + if (PyFile_WriteString(" ", f) < 0) + goto error; + } + if (PyFile_WriteObject(o, f, Py_PRINT_RAW) < 0) + goto error; + if (PyFile_WriteString("\n", f) < 0) + goto error; + Py_DECREF(f); + return 0; +error: + Py_DECREF(f); + return -1; + /* the line below is just to avoid C compiler + * warnings about unused functions */ + return __Pyx_Print(f, NULL, 0); +} +#else /* Python 3 has a print function */ +static int __Pyx_PrintOne(PyObject* stream, PyObject *o) { + int res; + PyObject* arg_tuple = PyTuple_Pack(1, o); + if (unlikely(!arg_tuple)) + return -1; + res = __Pyx_Print(stream, arg_tuple, 1); + Py_DECREF(arg_tuple); + return res; +} +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; + } + return (long) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); + Py_DECREF(tmp); + return val; + } +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + #if PY_VERSION_HEX < 0x02050000 + if (PyErr_Warn(NULL, warning) < 0) goto bad; + #else + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + #endif + } + else if ((size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ +#if !CYTHON_COMPILING_IN_PYPY +#if PY_VERSION_HEX >= 0x02060000 + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_MAJOR_VERSION < 3 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%.4s__ returned non-%.4s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + #if PY_VERSION_HEX < 0x02060000 + return PyInt_AsSsize_t(b); + #else + return PyLong_AsSsize_t(b); + #endif + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/manifold/_utils.pyx b/sklearn/manifold/_utils.pyx new file mode 100644 index 0000000000000..def2715cde3fb --- /dev/null +++ b/sklearn/manifold/_utils.pyx @@ -0,0 +1,111 @@ +from libc cimport math +cimport cython +import numpy as np +cimport numpy as np +cdef extern from "numpy/npy_math.h": + float NPY_INFINITY + + +cdef double EPSILON_DBL = 1e-7 +cdef double PERPLEXITY_TOLERANCE = 1e-5 + + +@cython.boundscheck(False) +cpdef np.ndarray[np.float_t, ndim=2] _binary_search_perplexity( + np.ndarray[np.float_t, ndim=2] affinities, double desired_perplexity, + int verbose): + """Binary search for sigmas of conditional Gaussians. + + We are looking for sigma = sqrt(1/beta) so that the perplexity + of the conditional distribution p_i|j matches approximately the + desired value. p_i|j are Gaussian distributed. + + The idea has been proposed in "Stochastic Neighbor Embedding" + Geoffrey Hinton and Sam Roweis, 2003. + + Parameters + ---------- + affinities : array-like, shape (n_samples, n_samples) + Distances between training samples. + + desired_perplexity : double + Desired perplexity (2^entropy) of the conditional Gaussians. + + verbose : int + Verbosity level. + + Returns + ------- + P : array, shape (n_samples, n_samples) + Probabilities of conditional Gaussian distributions p_i|j. + """ + # Maximum number of binary search steps + cdef int n_steps = 100 + + cdef int n_samples = affinities.shape[0] + cdef np.ndarray[np.float_t, ndim=2] P = np.ndarray((n_samples, n_samples), + dtype=np.double) + # Precisions of conditional Gaussian distrubutions + cdef double beta + cdef double beta_min + cdef double beta_max + cdef double beta_sum = 0.0 + # Now we go to log scale + cdef double desired_entropy = math.log(desired_perplexity) + cdef double entropy_diff + + cdef double entropy + cdef double sum_Pi + cdef double sum_disti_Pi + cdef int i + cdef int j + + for i in range(n_samples): + beta_min = -NPY_INFINITY + beta_max = NPY_INFINITY + beta = 1.0 + + # Binary search of precision for i-th conditional distribution + for _ in range(n_steps): + # Compute current entropy and corresponding probabilities + for j in range(n_samples): + P[i, j] = math.exp(-affinities[i, j] * beta) + P[i, i] = 0.0 + sum_Pi = 0.0 + for j in range(n_samples): + sum_Pi += P[i, j] + if sum_Pi == 0.0: + sum_Pi = EPSILON_DBL + sum_disti_Pi = 0.0 + for j in range(n_samples): + P[i, j] /= sum_Pi + sum_disti_Pi += affinities[i, j] * P[i, j] + entropy = math.log(sum_Pi) + beta * sum_disti_Pi + entropy_diff = entropy - desired_entropy + + if math.fabs(entropy_diff) <= PERPLEXITY_TOLERANCE: + break + + if entropy_diff > 0.0: + beta_min = beta + if beta_max == NPY_INFINITY: + beta *= 2.0 + else: + beta = (beta + beta_max) / 2.0 + else: + beta_max = beta + if beta_min == -NPY_INFINITY: + beta /= 2.0 + else: + beta = (beta + beta_min) / 2.0 + + beta_sum += beta + + if verbose and ((i + 1) % 1000 == 0 or i + 1 == n_samples): + print("[t-SNE] Computed conditional probabilities for sample " + "%d / %d" % (i + 1, n_samples)) + + if verbose: + print("[t-SNE] Mean sigma: %f" + % np.mean(math.sqrt(n_samples / beta_sum))) + return P diff --git a/sklearn/manifold/isomap.py b/sklearn/manifold/isomap.py index 67d4324d77423..b3cbdc61e92ee 100644 --- a/sklearn/manifold/isomap.py +++ b/sklearn/manifold/isomap.py @@ -1,12 +1,12 @@ """Isomap for manifold learning""" # Author: Jake Vanderplas -- -# License: BSD, (C) 2011 +# License: BSD 3 clause (C) 2011 import numpy as np from ..base import BaseEstimator, TransformerMixin from ..neighbors import NearestNeighbors, kneighbors_graph -from ..utils import check_arrays +from ..utils import check_array from ..utils.graph import graph_shortest_path from ..decomposition import KernelPCA from ..preprocessing import KernelCenterer @@ -26,59 +26,64 @@ class Isomap(BaseEstimator, TransformerMixin): number of coordinates for the manifold eigen_solver : ['auto'|'arpack'|'dense'] - 'auto' : attempt to choose the most efficient solver - for the given problem. - 'arpack' : use Arnoldi decomposition to find the eigenvalues - and eigenvectors. Note that arpack can handle both dense - and sparse data efficiently - 'dense' : use a direct solver (i.e. LAPACK) - for the eigenvalue decomposition. + 'auto' : Attempt to choose the most efficient solver + for the given problem. + + 'arpack' : Use Arnoldi decomposition to find the eigenvalues + and eigenvectors. + + 'dense' : Use a direct solver (i.e. LAPACK) + for the eigenvalue decomposition. tol : float - convergence tolerance passed to arpack or lobpcg. - not used if eigen_solver == 'dense' + Convergence tolerance passed to arpack or lobpcg. + not used if eigen_solver == 'dense'. max_iter : integer - maximum number of iterations for the arpack solver. - not used if eigen_solver == 'dense' + Maximum number of iterations for the arpack solver. + not used if eigen_solver == 'dense'. path_method : string ['auto'|'FW'|'D'] - method to use in finding shortest path. - 'auto' : attempt to choose the best algorithm automatically - 'FW' : Floyd-Warshall algorithm - 'D' : Dijkstra algorithm with Fibonacci Heaps + Method to use in finding shortest path. + + 'auto' : attempt to choose the best algorithm automatically. + + 'FW' : Floyd-Warshall algorithm. + + 'D' : Dijkstra's algorithm. neighbors_algorithm : string ['auto'|'brute'|'kd_tree'|'ball_tree'] - algorithm to use for nearest neighbors search, - passed to neighbors.NearestNeighbors instance + Algorithm to use for nearest neighbors search, + passed to neighbors.NearestNeighbors instance. Attributes ---------- - `embedding_` : array-like, shape (n_samples, n_components) - Stores the embedding vectors + embedding_ : array-like, shape (n_samples, n_components) + Stores the embedding vectors. - `kernel_pca_` : `KernelPCA` object used to implement the embedding + kernel_pca_ : object + `KernelPCA` object used to implement the embedding. - `training_data_` : array-like, shape (n_samples, n_features) - Stores the training data + training_data_ : array-like, shape (n_samples, n_features) + Stores the training data. - `nbrs_` : sklearn.neighbors.NearestNeighbors instance + nbrs_ : sklearn.neighbors.NearestNeighbors instance Stores nearest neighbors instance, including BallTree or KDtree if applicable. - `dist_matrix_` : array-like, shape (n_samples, n_samples) - Stores the geodesic distance matrix of training data + dist_matrix_ : array-like, shape (n_samples, n_samples) + Stores the geodesic distance matrix of training data. References ---------- - [1] Tenenbaum, J.B.; De Silva, V.; & Langford, J.C. A global geometric - framework for nonlinear dimensionality reduction. Science 290 (5500) + .. [1] Tenenbaum, J.B.; De Silva, V.; & Langford, J.C. A global geometric + framework for nonlinear dimensionality reduction. Science 290 (5500) """ def __init__(self, n_neighbors=5, n_components=2, eigen_solver='auto', - tol=0, max_iter=None, path_method='auto', - neighbors_algorithm='auto'): + tol=0, max_iter=None, path_method='auto', + neighbors_algorithm='auto'): self.n_neighbors = n_neighbors self.n_components = n_components @@ -91,12 +96,13 @@ def __init__(self, n_neighbors=5, n_components=2, eigen_solver='auto', algorithm=neighbors_algorithm) def _fit_transform(self, X): - X, = check_arrays(X, sparse_format='dense') + X = check_array(X) self.nbrs_.fit(X) self.training_data_ = self.nbrs_._fit_X self.kernel_pca_ = KernelPCA(n_components=self.n_components, - kernel="precomputed", eigen_solver=self.eigen_solver, - tol=self.tol, max_iter=self.max_iter) + kernel="precomputed", + eigen_solver=self.eigen_solver, + tol=self.tol, max_iter=self.max_iter) kng = kneighbors_graph(self.nbrs_, self.n_neighbors, mode='distance') @@ -138,9 +144,9 @@ def fit(self, X, y=None): Parameters ---------- - X : {array-like, sparse matrix, BallTree, cKDTree, NearestNeighbors} + X : {array-like, sparse matrix, BallTree, KDTree, NearestNeighbors} Sample data, shape = (n_samples, n_features), in the form of a - numpy array, sparse array, precomputed tree, or NearestNeighbors + numpy array, precomputed tree, or NearestNeighbors object. Returns @@ -155,7 +161,7 @@ def fit_transform(self, X, y=None): Parameters ---------- - X: {array-like, sparse matrix, BallTree, cKDTree} + X: {array-like, sparse matrix, BallTree, KDTree} Training vector, where n_samples in the number of samples and n_features is the number of features. @@ -185,6 +191,7 @@ def transform(self, X): ------- X_new: array-like, shape (n_samples, n_components) """ + X = check_array(X) distances, indices = self.nbrs_.kneighbors(X, return_distance=True) #Create the graph of shortest distances from X to self.training_data_ diff --git a/sklearn/manifold/locally_linear.py b/sklearn/manifold/locally_linear.py index d5543cea1ca8b..5d78713115146 100644 --- a/sklearn/manifold/locally_linear.py +++ b/sklearn/manifold/locally_linear.py @@ -2,14 +2,15 @@ # Author: Fabian Pedregosa -- # Jake Vanderplas -- -# License: BSD, (C) INRIA 2011 +# License: BSD 3 clause (C) INRIA 2011 import numpy as np from scipy.linalg import eigh, svd, qr, solve from scipy.sparse import eye, csr_matrix from ..base import BaseEstimator, TransformerMixin -from ..utils import array2d, check_random_state, check_arrays +from ..utils import check_random_state, check_array from ..utils.arpack import eigsh +from ..utils.validation import check_is_fitted from ..neighbors import NearestNeighbors @@ -69,7 +70,7 @@ def barycenter_kneighbors_graph(X, n_neighbors, reg=1e-3): Parameters ---------- - X : {array-like, sparse matrix, BallTree, cKDTree, NearestNeighbors} + X : {array-like, sparse matrix, BallTree, KDTree, NearestNeighbors} Sample data, shape = (n_samples, n_features), in the form of a numpy array, sparse array, precomputed tree, or NearestNeighbors object. @@ -177,15 +178,14 @@ def null_space(M, k, k_skip=1, eigen_solver='arpack', tol=1E-6, max_iter=100, def locally_linear_embedding( - X, n_neighbors, n_components, reg=1e-3, eigen_solver='auto', - tol=1e-6, max_iter=100, method='standard', - hessian_tol=1E-4, modified_tol=1E-12, - random_state=None): + X, n_neighbors, n_components, reg=1e-3, eigen_solver='auto', tol=1e-6, + max_iter=100, method='standard', hessian_tol=1E-4, modified_tol=1E-12, + random_state=None): """Perform a Locally Linear Embedding analysis on the data. Parameters ---------- - X : {array-like, sparse matrix, BallTree, cKDTree, NearestNeighbors} + X : {array-like, sparse matrix, BallTree, KDTree, NearestNeighbors} Sample data, shape = (n_samples, n_features), in the form of a numpy array, sparse array, precomputed tree, or NearestNeighbors object. @@ -305,11 +305,12 @@ def locally_linear_embedding( M.flat[::M.shape[0] + 1] += 1 # W = W - I = W - I elif method == 'hessian': - dp = n_components * (n_components + 1) / 2 + dp = n_components * (n_components + 1) // 2 if n_neighbors <= n_components + dp: raise ValueError("for method='hessian', n_neighbors must be " - "greater than [n_components * (n_components + 3) / 2]") + "greater than " + "[n_components * (n_components + 3) / 2]") neighbors = nbrs.kneighbors(X, n_neighbors=n_neighbors + 1, return_distance=False) @@ -337,8 +338,8 @@ def locally_linear_embedding( j = 1 + n_components for k in range(n_components): - Yi[:, j:j + n_components - k] = \ - U[:, k:k + 1] * U[:, k:n_components] + Yi[:, j:j + n_components - k] = (U[:, k:k + 1] + * U[:, k:n_components]) j += n_components - k Q, R = qr(Yi) @@ -358,7 +359,7 @@ def locally_linear_embedding( elif method == 'modified': if n_neighbors < n_components: raise ValueError("modified LLE requires " - "n_neighbors >= n_components") + "n_neighbors >= n_components") neighbors = nbrs.kneighbors(X, n_neighbors=n_neighbors + 1, return_distance=False) @@ -533,11 +534,11 @@ class LocallyLinearEmbedding(BaseEstimator, TransformerMixin): maximum number of iterations for the arpack solver. Not used if eigen_solver=='dense'. - method : string ['standard' | 'hessian' | 'modified'] - standard : use the standard locally linear embedding algorithm. - see reference [1] - hessian : use the Hessian eigenmap method. This method requires - n_neighbors > n_components * (1 + (n_components + 1) / 2. + method : string ('standard', 'hessian', 'modified' or 'ltsa') + standard : use the standard locally linear embedding algorithm. see + reference [1] + hessian : use the Hessian eigenmap method. This method requires + ``n_neighbors > n_components * (1 + (n_components + 1) / 2`` see reference [2] modified : use the modified locally linear embedding algorithm. see reference [3] @@ -546,11 +547,11 @@ class LocallyLinearEmbedding(BaseEstimator, TransformerMixin): hessian_tol : float, optional Tolerance for Hessian eigenmapping method. - Only used if method == 'hessian' + Only used if ``method == 'hessian'`` modified_tol : float, optional Tolerance for modified LLE method. - Only used if method == 'modified' + Only used if ``method == 'modified'`` neighbors_algorithm : string ['auto'|'brute'|'kd_tree'|'ball_tree'] algorithm to use for nearest neighbors search, @@ -562,13 +563,13 @@ class LocallyLinearEmbedding(BaseEstimator, TransformerMixin): Attributes ---------- - `embedding_vectors_` : array-like, shape [n_components, n_samples] + embedding_vectors_ : array-like, shape [n_components, n_samples] Stores the embedding vectors - `reconstruction_error_` : float + reconstruction_error_ : float Reconstruction error associated with `embedding_vectors_` - `nbrs_` : NearestNeighbors object + nbrs_ : NearestNeighbors object Stores nearest neighbors instance, including BallTree or KDtree if applicable. @@ -589,9 +590,9 @@ class LocallyLinearEmbedding(BaseEstimator, TransformerMixin): """ def __init__(self, n_neighbors=5, n_components=2, reg=1E-3, - eigen_solver='auto', tol=1E-6, max_iter=100, method='standard', - hessian_tol=1E-4, modified_tol=1E-12, neighbors_algorithm='auto', - random_state=None): + eigen_solver='auto', tol=1E-6, max_iter=100, + method='standard', hessian_tol=1E-4, modified_tol=1E-12, + neighbors_algorithm='auto', random_state=None): self.n_neighbors = n_neighbors self.n_components = n_components @@ -607,10 +608,10 @@ def __init__(self, n_neighbors=5, n_components=2, reg=1E-3, def _fit_transform(self, X): self.nbrs_ = NearestNeighbors(self.n_neighbors, - algorithm=self.neighbors_algorithm) + algorithm=self.neighbors_algorithm) - self.random_state = check_random_state(self.random_state) - X, = check_arrays(X, sparse_format='dense') + random_state = check_random_state(self.random_state) + X = check_array(X) self.nbrs_.fit(X) self.embedding_, self.reconstruction_error_ = \ locally_linear_embedding( @@ -618,7 +619,7 @@ def _fit_transform(self, X): eigen_solver=self.eigen_solver, tol=self.tol, max_iter=self.max_iter, method=self.method, hessian_tol=self.hessian_tol, modified_tol=self.modified_tol, - random_state=self.random_state) + random_state=random_state) def fit(self, X, y=None): """Compute the embedding vectors for data X @@ -667,7 +668,9 @@ def transform(self, X): Because of scaling performed by this method, it is discouraged to use it together with methods that are not scale-invariant (like SVMs) """ - X = array2d(X) + check_is_fitted(self, "nbrs_") + + X = check_array(X) ind = self.nbrs_.kneighbors(X, n_neighbors=self.n_neighbors, return_distance=False) weights = barycenter_weights(X, self.nbrs_._fit_X[ind], diff --git a/sklearn/manifold/mds.py b/sklearn/manifold/mds.py index aa87d87dabfa6..a5dd1c67472d7 100644 --- a/sklearn/manifold/mds.py +++ b/sklearn/manifold/mds.py @@ -11,14 +11,14 @@ from ..base import BaseEstimator from ..metrics import euclidean_distances -from ..utils import check_random_state, check_arrays +from ..utils import check_random_state, check_array, check_symmetric from ..externals.joblib import Parallel from ..externals.joblib import delayed -from ..linear_model.isotonic_regression_ import isotonic_regression +from ..isotonic import IsotonicRegression def _smacof_single(similarities, metric=True, n_components=2, init=None, - max_iter=300, verbose=0, eps=1e-3, random_state=None): + max_iter=300, verbose=0, eps=1e-3, random_state=None): """ Computes multidimensional scaling using SMACOF algorithm @@ -61,17 +61,15 @@ def _smacof_single(similarities, metric=True, n_components=2, init=None, The final value of the stress (sum of squared distance of the disparities and the distances for all constrained points) + n_iter : int + Number of iterations run. + """ + similarities = check_symmetric(similarities, raise_exception=True) + n_samples = similarities.shape[0] random_state = check_random_state(random_state) - if similarities.shape[0] != similarities.shape[1]: - raise ValueError("similarities must be a square array (shape=%d)" % - n_samples) - res = 100 * np.finfo(np.float).resolution - if np.any((similarities - similarities.T) > res): - raise ValueError("similarities must be symmetric") - sim_flat = ((1 - np.tri(n_samples)) * similarities).ravel() sim_flat_w = sim_flat[sim_flat != 0] if init is None: @@ -83,10 +81,11 @@ def _smacof_single(similarities, metric=True, n_components=2, init=None, n_components = init.shape[1] if n_samples != init.shape[0]: raise ValueError("init matrix should be of shape (%d, %d)" % - (n_samples, n_components)) + (n_samples, n_components)) X = init old_stress = None + ir = IsotonicRegression() for it in range(max_iter): # Compute distance and monotonic regression dis = euclidean_distances(X) @@ -99,19 +98,15 @@ def _smacof_single(similarities, metric=True, n_components=2, init=None, dis_flat_w = dis_flat[sim_flat != 0] # Compute the disparities using a monotonic regression - indxs = np.lexsort((dis_flat_w, sim_flat_w)) - rindxs = np.argsort(indxs) - disparities_flat = isotonic_regression(dis_flat_w[indxs]) - disparities_flat = disparities_flat[rindxs] + disparities_flat = ir.fit_transform(sim_flat_w, dis_flat_w) disparities = dis_flat.copy() disparities[sim_flat != 0] = disparities_flat disparities = disparities.reshape((n_samples, n_samples)) disparities *= np.sqrt((n_samples * (n_samples - 1) / 2) / - (disparities ** 2).sum()) + (disparities ** 2).sum()) # Compute stress - stress = ((dis.ravel() - - disparities.ravel()) ** 2).sum() / 2 + stress = ((dis.ravel() - disparities.ravel()) ** 2).sum() / 2 # Update X using the Guttman transform dis[dis == 0] = 1e-5 @@ -121,21 +116,22 @@ def _smacof_single(similarities, metric=True, n_components=2, init=None, X = 1. / n_samples * np.dot(B, X) dis = np.sqrt((X ** 2).sum(axis=1)).sum() - if verbose == 2: - print 'it: %d, stress %s' % (it, stress) + if verbose >= 2: + print('it: %d, stress %s' % (it, stress)) if old_stress is not None: if(old_stress - stress / dis) < eps: if verbose: - print 'breaking at iteration %d with stress %s' % (it, - stress) + print('breaking at iteration %d with stress %s' % (it, + stress)) break old_stress = stress / dis - return X, stress + return X, stress, it + 1 def smacof(similarities, metric=True, n_components=2, init=None, n_init=8, - n_jobs=1, max_iter=300, verbose=0, eps=1e-3, random_state=None): + n_jobs=1, max_iter=300, verbose=0, eps=1e-3, random_state=None, + return_n_iter=False): """ Computes multidimensional scaling using SMACOF (Scaling by Majorizing a Complicated Function) algorithm @@ -144,7 +140,7 @@ def smacof(similarities, metric=True, n_components=2, init=None, n_init=8, a objective function, the *stress*, using a majorization technique. The Stress Majorization, also known as the Guttman Transform, guarantees a monotone convergence of Stress, and is more powerful than traditional - technics such as gradient descent. + techniques such as gradient descent. The SMACOF algorithm for metric MDS can summarized by the following steps: @@ -184,8 +180,8 @@ def smacof(similarities, metric=True, n_components=2, init=None, n_init=8, parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is - used at all, which is useful for debuging. For n_jobs below -1, - (n_cpus + 1 - n_jobs) are used. Thus for n_jobs = -2, all CPUs but one + used at all, which is useful for debugging. For n_jobs below -1, + (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. max_iter : int, optional, default: 300 @@ -202,6 +198,9 @@ def smacof(similarities, metric=True, n_components=2, init=None, n_init=8, given, it fixes the seed. Defaults to the global numpy random number generator. + return_n_iter : bool + Whether or not to return the number of iterations. + Returns ------- X : ndarray (n_samples,n_components) @@ -211,6 +210,10 @@ def smacof(similarities, metric=True, n_components=2, init=None, n_init=8, The final value of the stress (sum of squared distance of the disparities and the distances for all constrained points) + n_iter : int + The number of iterations corresponding to the best stress. + Returned only if `return_n_iter` is set to True. + Notes ----- "Modern Multidimensional Scaling - Theory and Applications" Borg, I.; @@ -223,7 +226,7 @@ def smacof(similarities, metric=True, n_components=2, init=None, n_init=8, hypothesis" Kruskal, J. Psychometrika, 29, (1964) """ - similarities, = check_arrays(similarities, sparse_format='dense') + similarities = check_array(similarities) random_state = check_random_state(random_state) if hasattr(init, '__array__'): @@ -239,33 +242,37 @@ def smacof(similarities, metric=True, n_components=2, init=None, n_init=8, if n_jobs == 1: for it in range(n_init): - pos, stress = _smacof_single(similarities, metric=metric, - n_components=n_components, - init=init, max_iter=max_iter, - verbose=verbose, eps=eps, - random_state=random_state) + pos, stress, n_iter_ = _smacof_single( + similarities, metric=metric, + n_components=n_components, init=init, + max_iter=max_iter, verbose=verbose, + eps=eps, random_state=random_state) if best_stress is None or stress < best_stress: best_stress = stress best_pos = pos.copy() + best_iter = n_iter_ else: seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init) results = Parallel(n_jobs=n_jobs, verbose=max(verbose - 1, 0))( delayed(_smacof_single)( - similarities, metric=metric, n_components=n_components, - init=init, max_iter=max_iter, - verbose=verbose, eps=eps, - random_state=seed) - for seed in seeds) - positions, stress = zip(results) + similarities, metric=metric, n_components=n_components, + init=init, max_iter=max_iter, verbose=verbose, eps=eps, + random_state=seed) + for seed in seeds) + positions, stress, n_iters = zip(*results) best = np.argmin(stress) best_stress = stress[best] best_pos = positions[best] - return best_pos, best_stress + best_iter = n_iters[best] + + if return_n_iter: + return best_pos, best_stress, best_iter + else: + return best_pos, best_stress class MDS(BaseEstimator): - """ - Multidimensional scaling + """Multidimensional scaling Parameters ---------- @@ -297,8 +304,8 @@ class MDS(BaseEstimator): parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is - used at all, which is useful for debuging. For n_jobs below -1, - (n_cpus + 1 - n_jobs) are used. Thus for n_jobs = -2, all CPUs but one + used at all, which is useful for debugging. For n_jobs below -1, + (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. random_state : integer or numpy.RandomState, optional @@ -306,19 +313,23 @@ class MDS(BaseEstimator): given, it fixes the seed. Defaults to the global numpy random number generator. + dissimilarity : string + Which dissimilarity measure to use. + Supported are 'euclidean' and 'precomputed'. + Attributes ---------- - ``embedding_`` : array-like, shape [n_components, n_samples] + embedding_ : array-like, shape [n_components, n_samples] Stores the position of the dataset in the embedding space - ``stress_`` : float + stress_ : float The final value of the stress (sum of squared distance of the disparities and the distances for all constrained points) - Notes - ----- + References + ---------- "Modern Multidimensional Scaling - Theory and Applications" Borg, I.; Groenen P. Springer Series in Statistics (1997) @@ -331,59 +342,73 @@ class MDS(BaseEstimator): """ def __init__(self, n_components=2, metric=True, n_init=4, max_iter=300, verbose=0, eps=1e-3, n_jobs=1, - random_state=None): + random_state=None, dissimilarity="euclidean"): self.n_components = n_components + self.dissimilarity = dissimilarity self.metric = metric self.n_init = n_init self.max_iter = max_iter self.eps = eps self.verbose = verbose self.n_jobs = n_jobs - self.random_state = None + self.random_state = random_state + + @property + def _pairwise(self): + return self.kernel == "precomputed" - def fit(self, X, init=None, y=None): + def fit(self, X, y=None, init=None): """ Computes the position of the points in the embedding space Parameters ---------- - X: array, shape=[n_samples, n_samples], symetric - Proximity matrice + X : array, shape=[n_samples, n_features], or [n_samples, n_samples] \ + if dissimilarity='precomputed' + Input data. - init: {None or ndarray, shape (n_samples,)}, optional - if None, randomly chooses the initial configuration - if ndarray, initialize the SMACOF algorithm with this array + init : {None or ndarray, shape (n_samples,)}, optional + If None, randomly chooses the initial configuration + if ndarray, initialize the SMACOF algorithm with this array. """ - self.embedding_, self.stress_ = smacof(X, metric=self.metric, - n_components=self.n_components, - init=init, - n_init=self.n_init, - max_iter=self.max_iter, - verbose=self.verbose, - eps=self.eps, - random_state=self.random_state) + self.fit_transform(X, init=init) return self - def fit_transform(self, X, init=None, y=None): + def fit_transform(self, X, y=None, init=None): """ Fit the data from X, and returns the embedded coordinates Parameters ---------- - X: array, shape=[n_samples, n_samples], symetric - Proximity matrice + X : array, shape=[n_samples, n_features], or [n_samples, n_samples] \ + if dissimilarity='precomputed' + Input data. - init: {None or ndarray, shape (n_samples,)}, optional - if None, randomly chooses the initial configuration - if ndarray, initialize the SMACOF algorithm with this array + init : {None or ndarray, shape (n_samples,)}, optional + If None, randomly chooses the initial configuration + if ndarray, initialize the SMACOF algorithm with this array. """ - self.embedding_, self.stress_ = smacof(X, metric=self.metric, - n_components=self.n_components, - init=init, - n_init=self.n_init, - max_iter=self.max_iter, - verbose=self.verbose, - eps=self.eps) + X = check_array(X) + if X.shape[0] == X.shape[1] and self.dissimilarity != "precomputed": + warnings.warn("The MDS API has changed. ``fit`` now constructs an" + " dissimilarity matrix from data. To use a custom " + "dissimilarity matrix, set " + "``dissimilarity=precomputed``.") + + if self.dissimilarity == "precomputed": + self.dissimilarity_matrix_ = X + elif self.dissimilarity == "euclidean": + self.dissimilarity_matrix_ = euclidean_distances(X) + else: + raise ValueError("Proximity must be 'precomputed' or 'euclidean'." + " Got %s instead" % str(self.dissimilarity)) + + self.embedding_, self.stress_, self.n_iter_ = smacof( + self.dissimilarity_matrix_, metric=self.metric, + n_components=self.n_components, init=init, n_init=self.n_init, + n_jobs=self.n_jobs, max_iter=self.max_iter, verbose=self.verbose, + eps=self.eps, random_state=self.random_state, + return_n_iter=True) return self.embedding_ diff --git a/sklearn/manifold/setup.py b/sklearn/manifold/setup.py new file mode 100644 index 0000000000000..c9fe4ddf9a324 --- /dev/null +++ b/sklearn/manifold/setup.py @@ -0,0 +1,22 @@ +import os + +import numpy +from numpy.distutils.misc_util import Configuration + + +def configuration(parent_package="", top_path=None): + config = Configuration("manifold", parent_package, top_path) + libraries = [] + if os.name == 'posix': + libraries.append('m') + config.add_extension("_utils", + sources=["_utils.c"], + include_dirs=[numpy.get_include()], + libraries=libraries, + extra_compile_args=["-O3"]) + + return config + +if __name__ == "__main__": + from numpy.distutils.core import setup + setup(**configuration().todict()) diff --git a/sklearn/manifold/spectral_embedding_.py b/sklearn/manifold/spectral_embedding_.py new file mode 100644 index 0000000000000..277ce0c48c9f3 --- /dev/null +++ b/sklearn/manifold/spectral_embedding_.py @@ -0,0 +1,484 @@ +"""Spectral Embedding""" + +# Author: Gael Varoquaux +# Wei LI +# License: BSD 3 clause + +import warnings +import numpy as np + +from scipy import sparse +from scipy.linalg import eigh +from scipy.sparse.linalg import lobpcg + +from ..base import BaseEstimator +from ..externals import six +from ..utils import check_random_state, check_array, check_symmetric +from ..utils.extmath import _deterministic_vector_sign_flip +from ..utils.graph import graph_laplacian +from ..utils.sparsetools import connected_components +from ..utils.arpack import eigsh +from ..metrics.pairwise import rbf_kernel +from ..neighbors import kneighbors_graph + + +def _graph_connected_component(graph, node_id): + """Find the largest graph connected components the contains one + given node + + Parameters + ---------- + graph : array-like, shape: (n_samples, n_samples) + adjacency matrix of the graph, non-zero weight means an edge + between the nodes + + node_id : int + The index of the query node of the graph + + Returns + ------- + connected_components_matrix : array-like, shape: (n_samples,) + An array of bool value indicates the indexes of the nodes + belong to the largest connected components of the given query + node + """ + connected_components_matrix = np.zeros( + shape=(graph.shape[0]), dtype=np.bool) + connected_components_matrix[node_id] = True + n_node = graph.shape[0] + for i in range(n_node): + last_num_component = connected_components_matrix.sum() + _, node_to_add = np.where(graph[connected_components_matrix] != 0) + connected_components_matrix[node_to_add] = True + if last_num_component >= connected_components_matrix.sum(): + break + return connected_components_matrix + + +def _graph_is_connected(graph): + """ Return whether the graph is connected (True) or Not (False) + + Parameters + ---------- + graph : array-like or sparse matrix, shape: (n_samples, n_samples) + adjacency matrix of the graph, non-zero weight means an edge + between the nodes + + Returns + ------- + is_connected : bool + True means the graph is fully connected and False means not + """ + if sparse.isspmatrix(graph): + # sparse graph, find all the connected components + n_connected_components, _ = connected_components(graph) + return n_connected_components == 1 + else: + # dense graph, find all connected components start from node 0 + return _graph_connected_component(graph, 0).sum() == graph.shape[0] + + +def _set_diag(laplacian, value): + """Set the diagonal of the laplacian matrix and convert it to a + sparse format well suited for eigenvalue decomposition + + Parameters + ---------- + laplacian : array or sparse matrix + The graph laplacian + value : float + The value of the diagonal + + Returns + ------- + laplacian : array or sparse matrix + An array of matrix in a form that is well suited to fast + eigenvalue decomposition, depending on the band width of the + matrix. + """ + n_nodes = laplacian.shape[0] + # We need all entries in the diagonal to values + if not sparse.isspmatrix(laplacian): + laplacian.flat[::n_nodes + 1] = value + else: + laplacian = laplacian.tocoo() + diag_idx = (laplacian.row == laplacian.col) + laplacian.data[diag_idx] = value + # If the matrix has a small number of diagonals (as in the + # case of structured matrices coming from images), the + # dia format might be best suited for matvec products: + n_diags = np.unique(laplacian.row - laplacian.col).size + if n_diags <= 7: + # 3 or less outer diagonals on each side + laplacian = laplacian.todia() + else: + # csr has the fastest matvec and is thus best suited to + # arpack + laplacian = laplacian.tocsr() + return laplacian + + +def spectral_embedding(adjacency, n_components=8, eigen_solver=None, + random_state=None, eigen_tol=0.0, + norm_laplacian=True, drop_first=True): + """Project the sample on the first eigen vectors of the graph Laplacian. + + The adjacency matrix is used to compute a normalized graph Laplacian + whose spectrum (especially the eigen vectors associated to the + smallest eigen values) has an interpretation in terms of minimal + number of cuts necessary to split the graph into comparably sized + components. + + This embedding can also 'work' even if the ``adjacency`` variable is + not strictly the adjacency matrix of a graph but more generally + an affinity or similarity matrix between samples (for instance the + heat kernel of a euclidean distance matrix or a k-NN matrix). + + However care must taken to always make the affinity matrix symmetric + so that the eigen vector decomposition works as expected. + + Parameters + ---------- + adjacency : array-like or sparse matrix, shape: (n_samples, n_samples) + The adjacency matrix of the graph to embed. + + n_components : integer, optional, default 8 + The dimension of the projection subspace. + + eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'}, default None + The eigenvalue decomposition strategy to use. AMG requires pyamg + to be installed. It can be faster on very large, sparse problems, + but may also lead to instabilities. + + random_state : int seed, RandomState instance, or None (default) + A pseudo random number generator used for the initialization of the + lobpcg eigen vectors decomposition when eigen_solver == 'amg'. + By default, arpack is used. + + eigen_tol : float, optional, default=0.0 + Stopping criterion for eigendecomposition of the Laplacian matrix + when using arpack eigen_solver. + + drop_first : bool, optional, default=True + Whether to drop the first eigenvector. For spectral embedding, this + should be True as the first eigenvector should be constant vector for + connected graph, but for spectral clustering, this should be kept as + False to retain the first eigenvector. + + norm_laplacian : bool, optional, default=True + If True, then compute normalized Laplacian. + + Returns + ------- + embedding : array, shape=(n_samples, n_components) + The reduced samples. + + Notes + ----- + Spectral embedding is most useful when the graph has one connected + component. If there graph has many components, the first few eigenvectors + will simply uncover the connected components of the graph. + + References + ---------- + * http://en.wikipedia.org/wiki/LOBPCG + + * Toward the Optimal Preconditioned Eigensolver: Locally Optimal + Block Preconditioned Conjugate Gradient Method + Andrew V. Knyazev + http://dx.doi.org/10.1137%2FS1064827500366124 + """ + adjacency = check_symmetric(adjacency) + + try: + from pyamg import smoothed_aggregation_solver + except ImportError: + if eigen_solver == "amg": + raise ValueError("The eigen_solver was set to 'amg', but pyamg is " + "not available.") + + if eigen_solver is None: + eigen_solver = 'arpack' + elif eigen_solver not in ('arpack', 'lobpcg', 'amg'): + raise ValueError("Unknown value for eigen_solver: '%s'." + "Should be 'amg', 'arpack', or 'lobpcg'" + % eigen_solver) + + random_state = check_random_state(random_state) + + n_nodes = adjacency.shape[0] + # Whether to drop the first eigenvector + if drop_first: + n_components = n_components + 1 + + if not _graph_is_connected(adjacency): + warnings.warn("Graph is not fully connected, spectral embedding" + " may not work as expected.") + + laplacian, dd = graph_laplacian(adjacency, + normed=norm_laplacian, return_diag=True) + if (eigen_solver == 'arpack' + or eigen_solver != 'lobpcg' and + (not sparse.isspmatrix(laplacian) + or n_nodes < 5 * n_components)): + # lobpcg used with eigen_solver='amg' has bugs for low number of nodes + # for details see the source code in scipy: + # https://github.com/scipy/scipy/blob/v0.11.0/scipy/sparse/linalg/eigen + # /lobpcg/lobpcg.py#L237 + # or matlab: + # http://www.mathworks.com/matlabcentral/fileexchange/48-lobpcg-m + laplacian = _set_diag(laplacian, 1) + + # Here we'll use shift-invert mode for fast eigenvalues + # (see http://docs.scipy.org/doc/scipy/reference/tutorial/arpack.html + # for a short explanation of what this means) + # Because the normalized Laplacian has eigenvalues between 0 and 2, + # I - L has eigenvalues between -1 and 1. ARPACK is most efficient + # when finding eigenvalues of largest magnitude (keyword which='LM') + # and when these eigenvalues are very large compared to the rest. + # For very large, very sparse graphs, I - L can have many, many + # eigenvalues very near 1.0. This leads to slow convergence. So + # instead, we'll use ARPACK's shift-invert mode, asking for the + # eigenvalues near 1.0. This effectively spreads-out the spectrum + # near 1.0 and leads to much faster convergence: potentially an + # orders-of-magnitude speedup over simply using keyword which='LA' + # in standard mode. + try: + # We are computing the opposite of the laplacian inplace so as + # to spare a memory allocation of a possibly very large array + laplacian *= -1 + lambdas, diffusion_map = eigsh(laplacian, k=n_components, + sigma=1.0, which='LM', + tol=eigen_tol) + embedding = diffusion_map.T[n_components::-1] * dd + except RuntimeError: + # When submatrices are exactly singular, an LU decomposition + # in arpack fails. We fallback to lobpcg + eigen_solver = "lobpcg" + # Revert the laplacian to its opposite to have lobpcg work + laplacian *= -1 + + if eigen_solver == 'amg': + # Use AMG to get a preconditioner and speed up the eigenvalue + # problem. + if not sparse.issparse(laplacian): + warnings.warn("AMG works better for sparse matrices") + laplacian = laplacian.astype(np.float) # lobpcg needs native floats + laplacian = _set_diag(laplacian, 1) + ml = smoothed_aggregation_solver(check_array(laplacian, 'csr')) + M = ml.aspreconditioner() + X = random_state.rand(laplacian.shape[0], n_components + 1) + X[:, 0] = dd.ravel() + lambdas, diffusion_map = lobpcg(laplacian, X, M=M, tol=1.e-12, + largest=False) + embedding = diffusion_map.T * dd + if embedding.shape[0] == 1: + raise ValueError + + elif eigen_solver == "lobpcg": + laplacian = laplacian.astype(np.float) # lobpcg needs native floats + if n_nodes < 5 * n_components + 1: + # see note above under arpack why lobpcg has problems with small + # number of nodes + # lobpcg will fallback to eigh, so we short circuit it + if sparse.isspmatrix(laplacian): + laplacian = laplacian.toarray() + lambdas, diffusion_map = eigh(laplacian) + embedding = diffusion_map.T[:n_components] * dd + else: + # lobpcg needs native floats + laplacian = laplacian.astype(np.float) + laplacian = _set_diag(laplacian, 1) + # We increase the number of eigenvectors requested, as lobpcg + # doesn't behave well in low dimension + X = random_state.rand(laplacian.shape[0], n_components + 1) + X[:, 0] = dd.ravel() + lambdas, diffusion_map = lobpcg(laplacian, X, tol=1e-15, + largest=False, maxiter=2000) + embedding = diffusion_map.T[:n_components] * dd + if embedding.shape[0] == 1: + raise ValueError + + embedding = _deterministic_vector_sign_flip(embedding) + if drop_first: + return embedding[1:n_components].T + else: + return embedding[:n_components].T + + +class SpectralEmbedding(BaseEstimator): + """Spectral embedding for non-linear dimensionality reduction. + + Forms an affinity matrix given by the specified function and + applies spectral decomposition to the corresponding graph laplacian. + The resulting transformation is given by the value of the + eigenvectors for each data point. + + Parameters + ----------- + n_components : integer, default: 2 + The dimension of the projected subspace. + + eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'} + The eigenvalue decomposition strategy to use. AMG requires pyamg + to be installed. It can be faster on very large, sparse problems, + but may also lead to instabilities. + + random_state : int seed, RandomState instance, or None, default : None + A pseudo random number generator used for the initialization of the + lobpcg eigen vectors decomposition when eigen_solver == 'amg'. + + affinity : string or callable, default : "nearest_neighbors" + How to construct the affinity matrix. + - 'nearest_neighbors' : construct affinity matrix by knn graph + - 'rbf' : construct affinity matrix by rbf kernel + - 'precomputed' : interpret X as precomputed affinity matrix + - callable : use passed in function as affinity + the function takes in data matrix (n_samples, n_features) + and return affinity matrix (n_samples, n_samples). + + gamma : float, optional, default : 1/n_features + Kernel coefficient for rbf kernel. + + n_neighbors : int, default : max(n_samples/10 , 1) + Number of nearest neighbors for nearest_neighbors graph building. + + Attributes + ---------- + + embedding_ : array, shape = (n_samples, n_components) + Spectral embedding of the training matrix. + + affinity_matrix_ : array, shape = (n_samples, n_samples) + Affinity_matrix constructed from samples or precomputed. + + References + ---------- + + - A Tutorial on Spectral Clustering, 2007 + Ulrike von Luxburg + http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323 + + - On Spectral Clustering: Analysis and an algorithm, 2011 + Andrew Y. Ng, Michael I. Jordan, Yair Weiss + http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.8100 + + - Normalized cuts and image segmentation, 2000 + Jianbo Shi, Jitendra Malik + http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.160.2324 + """ + + def __init__(self, n_components=2, affinity="nearest_neighbors", + gamma=None, random_state=None, eigen_solver=None, + n_neighbors=None): + self.n_components = n_components + self.affinity = affinity + self.gamma = gamma + self.random_state = random_state + self.eigen_solver = eigen_solver + self.n_neighbors = n_neighbors + + @property + def _pairwise(self): + return self.affinity == "precomputed" + + def _get_affinity_matrix(self, X, Y=None): + """Caclulate the affinity matrix from data + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training vector, where n_samples in the number of samples + and n_features is the number of features. + + If affinity is "precomputed" + X : array-like, shape (n_samples, n_samples), + Interpret X as precomputed adjacency graph computed from + samples. + + Returns + ------- + affinity_matrix, shape (n_samples, n_samples) + """ + if self.affinity == 'precomputed': + self.affinity_matrix_ = X + return self.affinity_matrix_ + if self.affinity == 'nearest_neighbors': + if sparse.issparse(X): + warnings.warn("Nearest neighbors affinity currently does " + "not support sparse input, falling back to " + "rbf affinity") + self.affinity = "rbf" + else: + self.n_neighbors_ = (self.n_neighbors + if self.n_neighbors is not None + else max(int(X.shape[0] / 10), 1)) + self.affinity_matrix_ = kneighbors_graph(X, self.n_neighbors_) + # currently only symmetric affinity_matrix supported + self.affinity_matrix_ = 0.5 * (self.affinity_matrix_ + + self.affinity_matrix_.T) + return self.affinity_matrix_ + if self.affinity == 'rbf': + self.gamma_ = (self.gamma + if self.gamma is not None else 1.0 / X.shape[1]) + self.affinity_matrix_ = rbf_kernel(X, gamma=self.gamma_) + return self.affinity_matrix_ + self.affinity_matrix_ = self.affinity(X) + return self.affinity_matrix_ + + def fit(self, X, y=None): + """Fit the model from data in X. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training vector, where n_samples in the number of samples + and n_features is the number of features. + + If affinity is "precomputed" + X : array-like, shape (n_samples, n_samples), + Interpret X as precomputed adjacency graph computed from + samples. + + Returns + ------- + self : object + Returns the instance itself. + """ + random_state = check_random_state(self.random_state) + if isinstance(self.affinity, six.string_types): + if self.affinity not in set(("nearest_neighbors", "rbf", + "precomputed")): + raise ValueError(("%s is not a valid affinity. Expected " + "'precomputed', 'rbf', 'nearest_neighbors' " + "or a callable.") % self.affinity) + elif not callable(self.affinity): + raise ValueError(("'affinity' is expected to be an an affinity " + "name or a callable. Got: %s") % self.affinity) + + affinity_matrix = self._get_affinity_matrix(X) + self.embedding_ = spectral_embedding(affinity_matrix, + n_components=self.n_components, + eigen_solver=self.eigen_solver, + random_state=random_state) + return self + + def fit_transform(self, X, y=None): + """Fit the model from data in X and transform X. + + Parameters + ---------- + X: array-like, shape (n_samples, n_features) + Training vector, where n_samples in the number of samples + and n_features is the number of features. + + If affinity is "precomputed" + X : array-like, shape (n_samples, n_samples), + Interpret X as precomputed adjacency graph computed from + samples. + + Returns + ------- + X_new: array-like, shape (n_samples, n_components) + """ + self.fit(X) + return self.embedding_ diff --git a/sklearn/manifold/t_sne.py b/sklearn/manifold/t_sne.py new file mode 100644 index 0000000000000..60b3a1abe5b49 --- /dev/null +++ b/sklearn/manifold/t_sne.py @@ -0,0 +1,525 @@ +# Author: Alexander Fabisch -- +# License: BSD 3 clause (C) 2014 + +# This is the standard t-SNE implementation. There are faster modifications of +# the algorithm: +# * Barnes-Hut-SNE: reduces the complexity of the gradient computation from +# N^2 to N log N (http://arxiv.org/abs/1301.3342) +# * Fast Optimization for t-SNE: +# http://cseweb.ucsd.edu/~lvdmaaten/workshops/nips2010/papers/vandermaaten.pdf + +import numpy as np +from scipy import linalg +from scipy.spatial.distance import pdist +from scipy.spatial.distance import squareform +from ..base import BaseEstimator +from ..utils import check_array +from ..utils import check_random_state +from ..utils.extmath import _ravel +from ..decomposition import RandomizedPCA +from ..metrics.pairwise import pairwise_distances +from . import _utils + + +MACHINE_EPSILON = np.finfo(np.double).eps + + +def _joint_probabilities(distances, desired_perplexity, verbose): + """Compute joint probabilities p_ij from distances. + + Parameters + ---------- + distances : array, shape (n_samples * (n_samples-1) / 2,) + Distances of samples are stored as condensed matrices, i.e. + we omit the diagonal and duplicate entries and store everything + in a one-dimensional array. + + desired_perplexity : float + Desired perplexity of the joint probability distributions. + + verbose : int + Verbosity level. + + Returns + ------- + P : array, shape (n_samples * (n_samples-1) / 2,) + Condensed joint probability matrix. + """ + # Compute conditional probabilities such that they approximately match + # the desired perplexity + conditional_P = _utils._binary_search_perplexity( + distances, desired_perplexity, verbose) + P = conditional_P + conditional_P.T + sum_P = np.maximum(np.sum(P), MACHINE_EPSILON) + P = np.maximum(squareform(P) / sum_P, MACHINE_EPSILON) + return P + + +def _kl_divergence(params, P, alpha, n_samples, n_components): + """t-SNE objective function: KL divergence of p_ijs and q_ijs. + + Parameters + ---------- + params : array, shape (n_params,) + Unraveled embedding. + + P : array, shape (n_samples * (n_samples-1) / 2,) + Condensed joint probability matrix. + + alpha : float + Degrees of freedom of the Student's-t distribution. + + n_samples : int + Number of samples. + + n_components : int + Dimension of the embedded space. + + Returns + ------- + kl_divergence : float + Kullback-Leibler divergence of p_ij and q_ij. + + grad : array, shape (n_params,) + Unraveled gradient of the Kullback-Leibler divergence with respect to + the embedding. + """ + X_embedded = params.reshape(n_samples, n_components) + + # Q is a heavy-tailed distribution: Student's t-distribution + n = pdist(X_embedded, "sqeuclidean") + n += 1. + n /= alpha + n **= (alpha + 1.0) / -2.0 + Q = np.maximum(n / (2.0 * np.sum(n)), MACHINE_EPSILON) + + # Optimization trick below: np.dot(x, y) is faster than + # np.sum(x * y) because it calls BLAS + + # Objective: C (Kullback-Leibler divergence of P and Q) + kl_divergence = 2.0 * np.dot(P, np.log(P / Q)) + + # Gradient: dC/dY + grad = np.ndarray((n_samples, n_components)) + PQd = squareform((P - Q) * n) + for i in range(n_samples): + np.dot(_ravel(PQd[i]), X_embedded[i] - X_embedded, out=grad[i]) + grad = grad.ravel() + c = 2.0 * (alpha + 1.0) / alpha + grad *= c + + return kl_divergence, grad + + +def _gradient_descent(objective, p0, it, n_iter, n_iter_without_progress=30, + momentum=0.5, learning_rate=1000.0, min_gain=0.01, + min_grad_norm=1e-7, min_error_diff=1e-7, verbose=0, + args=[]): + """Batch gradient descent with momentum and individual gains. + + Parameters + ---------- + objective : function or callable + Should return a tuple of cost and gradient for a given parameter + vector. + + p0 : array-like, shape (n_params,) + Initial parameter vector. + + it : int + Current number of iterations (this function will be called more than + once during the optimization). + + n_iter : int + Maximum number of gradient descent iterations. + + n_iter_without_progress : int, optional (default: 30) + Maximum number of iterations without progress before we abort the + optimization. + + momentum : float, within (0.0, 1.0), optional (default: 0.5) + The momentum generates a weight for previous gradients that decays + exponentially. + + learning_rate : float, optional (default: 1000.0) + The learning rate should be extremely high for t-SNE! Values in the + range [100.0, 1000.0] are common. + + min_gain : float, optional (default: 0.01) + Minimum individual gain for each parameter. + + min_grad_norm : float, optional (default: 1e-7) + If the gradient norm is below this threshold, the optimization will + be aborted. + + min_error_diff : float, optional (default: 1e-7) + If the absolute difference of two successive cost function values + is below this threshold, the optimization will be aborted. + + verbose : int, optional (default: 0) + Verbosity level. + + args : sequence + Arguments to pass to objective function. + + Returns + ------- + p : array, shape (n_params,) + Optimum parameters. + + error : float + Optimum. + + i : int + Last iteration. + """ + p = p0.copy().ravel() + update = np.zeros_like(p) + gains = np.ones_like(p) + error = np.finfo(np.float).max + best_error = np.finfo(np.float).max + best_iter = 0 + + for i in range(it, n_iter): + new_error, grad = objective(p, *args) + error_diff = np.abs(new_error - error) + error = new_error + grad_norm = linalg.norm(grad) + + if error < best_error: + best_error = error + best_iter = i + elif i - best_iter > n_iter_without_progress: + if verbose >= 2: + print("[t-SNE] Iteration %d: did not make any progress " + "during the last %d episodes. Finished." + % (i + 1, n_iter_without_progress)) + break + if min_grad_norm >= grad_norm: + if verbose >= 2: + print("[t-SNE] Iteration %d: gradient norm %f. Finished." + % (i + 1, grad_norm)) + break + if min_error_diff >= error_diff: + if verbose >= 2: + print("[t-SNE] Iteration %d: error difference %f. Finished." + % (i + 1, error_diff)) + break + + inc = update * grad >= 0.0 + dec = np.invert(inc) + gains[inc] += 0.05 + gains[dec] *= 0.95 + np.clip(gains, min_gain, np.inf) + grad *= gains + update = momentum * update - learning_rate * grad + p += update + + if verbose >= 2 and (i + 1) % 10 == 0: + print("[t-SNE] Iteration %d: error = %.7f, gradient norm = %.7f" + % (i + 1, error, grad_norm)) + + return p, error, i + + +def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False): + """Expresses to what extent the local structure is retained. + + The trustworthiness is within [0, 1]. It is defined as + + .. math:: + + T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1} + \sum_{j \in U^{(k)}_i (r(i, j) - k)} + + where :math:`r(i, j)` is the rank of the embedded datapoint j + according to the pairwise distances between the embedded datapoints, + :math:`U^{(k)}_i` is the set of points that are in the k nearest + neighbors in the embedded space but not in the original space. + + * "Neighborhood Preservation in Nonlinear Projection Methods: An + Experimental Study" + J. Venna, S. Kaski + * "Learning a Parametric Embedding by Preserving Local Structure" + L.J.P. van der Maaten + + Parameters + ---------- + X : array, shape (n_samples, n_features) or (n_samples, n_samples) + If the metric is 'precomputed' X must be a square distance + matrix. Otherwise it contains a sample per row. + + X_embedded : array, shape (n_samples, n_components) + Embedding of the training data in low-dimensional space. + + n_neighbors : int, optional (default: 5) + Number of neighbors k that will be considered. + + precomputed : bool, optional (default: False) + Set this flag if X is a precomputed square distance matrix. + + Returns + ------- + trustworthiness : float + Trustworthiness of the low-dimensional embedding. + """ + if precomputed: + dist_X = X + else: + dist_X = pairwise_distances(X, squared=True) + dist_X_embedded = pairwise_distances(X_embedded, squared=True) + ind_X = np.argsort(dist_X, axis=1) + ind_X_embedded = np.argsort(dist_X_embedded, axis=1)[:, 1:n_neighbors + 1] + + n_samples = X.shape[0] + t = 0.0 + ranks = np.zeros(n_neighbors) + for i in range(n_samples): + for j in range(n_neighbors): + ranks[j] = np.where(ind_X[i] == ind_X_embedded[i, j])[0][0] + ranks -= n_neighbors + t += np.sum(ranks[ranks > 0]) + t = 1.0 - t * (2.0 / (n_samples * n_neighbors * + (2.0 * n_samples - 3.0 * n_neighbors - 1.0))) + return t + + +class TSNE(BaseEstimator): + """t-distributed Stochastic Neighbor Embedding. + + t-SNE [1] is a tool to visualize high-dimensional data. It converts + similarities between data points to joint probabilities and tries + to minimize the Kullback-Leibler divergence between the joint + probabilities of the low-dimensional embedding and the + high-dimensional data. t-SNE has a cost function that is not convex, + i.e. with different initializations we can get different results. + + It is highly recommended to use another dimensionality reduction + method (e.g. PCA for dense data or TruncatedSVD for sparse data) + to reduce the number of dimensions to a reasonable amount (e.g. 50) + if the number of features is very high. This will suppress some + noise and speed up the computation of pairwise distances between + samples. For more tips see Laurens van der Maaten's FAQ [2]. + + Parameters + ---------- + n_components : int, optional (default: 2) + Dimension of the embedded space. + + perplexity : float, optional (default: 30) + The perplexity is related to the number of nearest neighbors that + is used in other manifold learning algorithms. Larger datasets + usually require a larger perplexity. Consider selcting a value + between 5 and 50. The choice is not extremely critical since t-SNE + is quite insensitive to this parameter. + + early_exaggeration : float, optional (default: 4.0) + Controls how tight natural clusters in the original space are in + the embedded space and how much space will be between them. For + larger values, the space between natural clusters will be larger + in the embedded space. Again, the choice of this parameter is not + very critical. If the cost function increases during initial + optimization, the early exaggeration factor or the learning rate + might be too high. + + learning_rate : float, optional (default: 1000) + The learning rate can be a critical parameter. It should be + between 100 and 1000. If the cost function increases during initial + optimization, the early exaggeration factor or the learning rate + might be too high. If the cost function gets stuck in a bad local + minimum increasing the learning rate helps sometimes. + + n_iter : int, optional (default: 1000) + Maximum number of iterations for the optimization. Should be at + least 200. + + metric : string or callable, optional + The metric to use when calculating distance between instances in a + feature array. If metric is a string, it must be one of the options + allowed by scipy.spatial.distance.pdist for its metric parameter, or + a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS. + If metric is "precomputed", X is assumed to be a distance matrix. + Alternatively, if metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays from X as input and return a value indicating + the distance between them. The default is "euclidean" which is + interpreted as squared euclidean distance. + + init : string, optional (default: "random") + Initialization of embedding. Possible options are 'random' and 'pca'. + PCA initialization cannot be used with precomputed distances and is + usually more globally stable than random initialization. + + verbose : int, optional (default: 0) + Verbosity level. + + random_state : int or RandomState instance or None (default) + Pseudo Random Number generator seed control. If None, use the + numpy.random singleton. Note that different initializations + might result in different local minima of the cost function. + + Attributes + ---------- + embedding_ : array-like, shape (n_samples, n_components) + Stores the embedding vectors. + + training_data_ : array-like, shape (n_samples, n_features) + Stores the training data. + + Examples + -------- + + >>> import numpy as np + >>> from sklearn.manifold import TSNE + >>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) + >>> model = TSNE(n_components=2, random_state=0) + >>> model.fit_transform(X) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + array([[ 887.28..., 238.61...], + [ -714.79..., 3243.34...], + [ 957.30..., -2505.78...], + [-1130.28..., -974.78...]) + + References + ---------- + + [1] van der Maaten, L.J.P.; Hinton, G.E. Visualizing High-Dimensional Data + Using t-SNE. Journal of Machine Learning Research 9:2579-2605, 2008. + + [2] van der Maaten, L.J.P. t-Distributed Stochastic Neighbor Embedding + http://homepage.tudelft.nl/19j49/t-SNE.html + """ + def __init__(self, n_components=2, perplexity=30.0, + early_exaggeration=4.0, learning_rate=1000.0, n_iter=1000, + metric="euclidean", init="random", verbose=0, + random_state=None): + if init not in ["pca", "random"]: + raise ValueError("'init' must be either 'pca' or 'random'") + self.n_components = n_components + self.perplexity = perplexity + self.early_exaggeration = early_exaggeration + self.learning_rate = learning_rate + self.n_iter = n_iter + self.metric = metric + self.init = init + self.verbose = verbose + self.random_state = random_state + + def fit(self, X, y=None): + """Fit the model using X as training data. + + Parameters + ---------- + X : array, shape (n_samples, n_features) or (n_samples, n_samples) + If the metric is 'precomputed' X must be a square distance + matrix. Otherwise it contains a sample per row. + """ + X = check_array(X, accept_sparse=['csr', 'csc', 'coo'], dtype=np.float64) + random_state = check_random_state(self.random_state) + + if self.early_exaggeration < 1.0: + raise ValueError("early_exaggeration must be at least 1, but is " + "%f" % self.early_exaggeration) + + if self.n_iter < 200: + raise ValueError("n_iter should be at least 200") + + if self.metric == "precomputed": + if self.init == 'pca': + raise ValueError("The parameter init=\"pca\" cannot be used " + "with metric=\"precomputed\".") + if X.shape[0] != X.shape[1]: + raise ValueError("X should be a square distance matrix") + distances = X + else: + if self.verbose: + print("[t-SNE] Computing pairwise distances...") + + if self.metric == "euclidean": + distances = pairwise_distances(X, metric=self.metric, squared=True) + else: + distances = pairwise_distances(X, metric=self.metric) + + # Degrees of freedom of the Student's t-distribution. The suggestion + # alpha = n_components - 1 comes from "Learning a Parametric Embedding + # by Preserving Local Structure" Laurens van der Maaten, 2009. + alpha = max(self.n_components - 1.0, 1) + n_samples = X.shape[0] + self.training_data_ = X + + P = _joint_probabilities(distances, self.perplexity, self.verbose) + if self.init == 'pca': + pca = RandomizedPCA(n_components=self.n_components, + random_state=random_state) + X_embedded = pca.fit_transform(X) + elif self.init == 'random': + X_embedded = None + else: + raise ValueError("Unsupported initialization scheme: %s" + % self.init) + + self.embedding_ = self._tsne(P, alpha, n_samples, random_state, + X_embedded=X_embedded) + + def _tsne(self, P, alpha, n_samples, random_state, X_embedded=None): + """Runs t-SNE.""" + # t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P + # and the Student's t-distributions Q. The optimization algorithm that + # we use is batch gradient descent with three stages: + # * early exaggeration with momentum 0.5 + # * early exaggeration with momentum 0.8 + # * final optimization with momentum 0.8 + # The embedding is initialized with iid samples from Gaussians with + # standard deviation 1e-4. + + if X_embedded is None: + # Initialize embedding randomly + X_embedded = 1e-4 * random_state.randn(n_samples, + self.n_components) + params = X_embedded.ravel() + + # Early exaggeration + P *= self.early_exaggeration + params, error, it = _gradient_descent( + _kl_divergence, params, it=0, n_iter=50, momentum=0.5, + min_grad_norm=0.0, min_error_diff=0.0, + learning_rate=self.learning_rate, verbose=self.verbose, + args=[P, alpha, n_samples, self.n_components]) + params, error, it = _gradient_descent( + _kl_divergence, params, it=it + 1, n_iter=100, momentum=0.8, + min_grad_norm=0.0, min_error_diff=0.0, + learning_rate=self.learning_rate, verbose=self.verbose, + args=[P, alpha, n_samples, self.n_components]) + if self.verbose: + print("[t-SNE] Error after %d iterations with early " + "exaggeration: %f" % (it + 1, error)) + + # Final optimization + P /= self.early_exaggeration + params, error, it = _gradient_descent( + _kl_divergence, params, it=it + 1, n_iter=self.n_iter, + momentum=0.8, learning_rate=self.learning_rate, + verbose=self.verbose, args=[P, alpha, n_samples, + self.n_components]) + if self.verbose: + print("[t-SNE] Error after %d iterations: %f" % (it + 1, error)) + + X_embedded = params.reshape(n_samples, self.n_components) + + return X_embedded + + def fit_transform(self, X, y=None): + """Transform X to the embedded space. + + Parameters + ---------- + X : array, shape (n_samples, n_features) or (n_samples, n_samples) + If the metric is 'precomputed' X must be a square distance + matrix. Otherwise it contains a sample per row. + + Returns + ------- + X_new : array, shape (n_samples, n_components) + Embedding of the training data in low-dimensional space. + """ + self.fit(X) + return self.embedding_ diff --git a/sklearn/manifold/tests/test_isomap.py b/sklearn/manifold/tests/test_isomap.py index 15d099eb03736..08b2eada00d28 100644 --- a/sklearn/manifold/tests/test_isomap.py +++ b/sklearn/manifold/tests/test_isomap.py @@ -86,7 +86,7 @@ def test_transform(): noise_scale = 0.01 # Create S-curve dataset - X, y = datasets.samples_generator.make_s_curve(n_samples) + X, y = datasets.samples_generator.make_s_curve(n_samples, random_state=0) # Compute isomap embedding iso = manifold.Isomap(n_components, 2) diff --git a/sklearn/manifold/tests/test_locally_linear.py b/sklearn/manifold/tests/test_locally_linear.py index 9abaa67bac3b9..deea74b878582 100644 --- a/sklearn/manifold/tests/test_locally_linear.py +++ b/sklearn/manifold/tests/test_locally_linear.py @@ -1,11 +1,14 @@ from itertools import product -import numpy as np from nose.tools import assert_true +import numpy as np from numpy.testing import assert_almost_equal, assert_array_almost_equal +from scipy import linalg + from sklearn import neighbors, manifold from sklearn.manifold.locally_linear import barycenter_kneighbors_graph from sklearn.utils.testing import assert_less +from sklearn.utils.testing import ignore_warnings eigen_solvers = ['dense', 'arpack'] @@ -17,16 +20,16 @@ def test_barycenter_kneighbors_graph(): A = barycenter_kneighbors_graph(X, 1) assert_array_almost_equal( - A.todense(), + A.toarray(), [[0., 1., 0.], [1., 0., 0.], [0., 1., 0.]]) A = barycenter_kneighbors_graph(X, 2) # check that columns sum to one - assert_array_almost_equal(np.sum(A.todense(), 1), np.ones((3, 1))) - pred = np.dot(A.todense(), X) - assert_less(np.linalg.norm(pred - X) / X.shape[0], 1) + assert_array_almost_equal(np.sum(A.toarray(), 1), np.ones(3)) + pred = np.dot(A.toarray(), X) + assert_less(linalg.norm(pred - X) / X.shape[0], 1) #---------------------------------------------------------------------- @@ -43,18 +46,19 @@ def test_lle_simple_grid(): X = X + 1e-10 * rng.uniform(size=X.shape) n_components = 2 clf = manifold.LocallyLinearEmbedding(n_neighbors=5, - n_components=n_components, random_state=rng) + n_components=n_components, + random_state=rng) tol = 0.1 - N = barycenter_kneighbors_graph(X, clf.n_neighbors).todense() - reconstruction_error = np.linalg.norm(np.dot(N, X) - X, 'fro') + N = barycenter_kneighbors_graph(X, clf.n_neighbors).toarray() + reconstruction_error = linalg.norm(np.dot(N, X) - X, 'fro') assert_less(reconstruction_error, tol) for solver in eigen_solvers: clf.set_params(eigen_solver=solver) clf.fit(X) assert_true(clf.embedding_.shape[1] == n_components) - reconstruction_error = np.linalg.norm( + reconstruction_error = linalg.norm( np.dot(N, clf.embedding_) - clf.embedding_, 'fro') ** 2 assert_less(reconstruction_error, tol) @@ -64,33 +68,33 @@ def test_lle_simple_grid(): # re-embed a noisy version of X using the transform method noise = rng.randn(*X.shape) / 100 X_reembedded = clf.transform(X + noise) - assert_less(np.linalg.norm(X_reembedded - clf.embedding_), tol) + assert_less(linalg.norm(X_reembedded - clf.embedding_), tol) def test_lle_manifold(): rng = np.random.RandomState(0) # similar test on a slightly more complex manifold - X = np.array(list(product(range(20), repeat=2))) - X = np.c_[X, X[:, 0] ** 2 / 20] + X = np.array(list(product(np.arange(18), repeat=2))) + X = np.c_[X, X[:, 0] ** 2 / 18] X = X + 1e-10 * rng.uniform(size=X.shape) n_components = 2 for method in ["standard", "hessian", "modified", "ltsa"]: clf = manifold.LocallyLinearEmbedding(n_neighbors=6, - n_components=n_components, method=method, random_state=0) + n_components=n_components, + method=method, random_state=0) tol = 1.5 if method == "standard" else 3 N = barycenter_kneighbors_graph(X, clf.n_neighbors).toarray() - reconstruction_error = np.linalg.norm(np.dot(N, X) - X) + reconstruction_error = linalg.norm(np.dot(N, X) - X) assert_less(reconstruction_error, tol) for solver in eigen_solvers: clf.set_params(eigen_solver=solver) clf.fit(X) assert_true(clf.embedding_.shape[1] == n_components) - reconstruction_error = np.linalg.norm( + reconstruction_error = linalg.norm( np.dot(N, clf.embedding_) - clf.embedding_, 'fro') ** 2 - details = ("solver: %s, method: %s" - % (solver, method)) + details = ("solver: %s, method: %s" % (solver, method)) assert_less(reconstruction_error, tol, msg=details) assert_less(np.abs(clf.reconstruction_error_ - reconstruction_error), @@ -112,12 +116,11 @@ def test_pipeline(): # Test the error raised when the weight matrix is singular def test_singular_matrix(): - import warnings from nose.tools import assert_raises M = np.ones((10, 3)) - with warnings.catch_warnings(record=True): - assert_raises(ValueError, manifold.locally_linear_embedding, - M, 2, 1, method='standard', eigen_solver='arpack') + f = ignore_warnings + assert_raises(ValueError, f(manifold.locally_linear_embedding), + M, 2, 1, method='standard', eigen_solver='arpack') if __name__ == '__main__': diff --git a/sklearn/manifold/tests/test_mds.py b/sklearn/manifold/tests/test_mds.py index 53a6a68fea0a0..a078afd8ca21a 100644 --- a/sklearn/manifold/tests/test_mds.py +++ b/sklearn/manifold/tests/test_mds.py @@ -57,5 +57,5 @@ def test_MDS(): [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) - mds_clf = mds.MDS(metric=False, n_jobs=3) + mds_clf = mds.MDS(metric=False, n_jobs=3, dissimilarity="precomputed") mds_clf.fit(sim) diff --git a/sklearn/manifold/tests/test_spectral_embedding.py b/sklearn/manifold/tests/test_spectral_embedding.py new file mode 100644 index 0000000000000..6313def4cf826 --- /dev/null +++ b/sklearn/manifold/tests/test_spectral_embedding.py @@ -0,0 +1,194 @@ +from nose.tools import assert_true +from nose.tools import assert_equal + +from scipy.sparse import csr_matrix +from scipy.sparse import csc_matrix +import numpy as np +from numpy.testing import assert_array_almost_equal, assert_array_equal + +from nose.tools import assert_raises +from nose.plugins.skip import SkipTest + +from sklearn.manifold.spectral_embedding_ import SpectralEmbedding +from sklearn.manifold.spectral_embedding_ import _graph_is_connected +from sklearn.manifold import spectral_embedding +from sklearn.metrics.pairwise import rbf_kernel +from sklearn.metrics import normalized_mutual_info_score +from sklearn.cluster import KMeans +from sklearn.datasets.samples_generator import make_blobs + + +# non centered, sparse centers to check the +centers = np.array([ + [0.0, 5.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 4.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 5.0, 1.0], +]) +n_samples = 1000 +n_clusters, n_features = centers.shape +S, true_labels = make_blobs(n_samples=n_samples, centers=centers, + cluster_std=1., random_state=42) + + +def _check_with_col_sign_flipping(A, B, tol=0.0): + """ Check array A and B are equal with possible sign flipping on + each columns""" + sign = True + for column_idx in range(A.shape[1]): + sign = sign and ((((A[:, column_idx] - + B[:, column_idx]) ** 2).mean() <= tol ** 2) or + (((A[:, column_idx] + + B[:, column_idx]) ** 2).mean() <= tol ** 2)) + if not sign: + return False + return True + + +def test_spectral_embedding_two_components(seed=36): + """Test spectral embedding with two components""" + random_state = np.random.RandomState(seed) + n_sample = 100 + affinity = np.zeros(shape=[n_sample * 2, + n_sample * 2]) + # first component + affinity[0:n_sample, + 0:n_sample] = np.abs(random_state.randn(n_sample, n_sample)) + 2 + # second component + affinity[n_sample::, + n_sample::] = np.abs(random_state.randn(n_sample, n_sample)) + 2 + # connection + affinity[0, n_sample + 1] = 1 + affinity[n_sample + 1, 0] = 1 + affinity.flat[::2 * n_sample + 1] = 0 + affinity = 0.5 * (affinity + affinity.T) + + true_label = np.zeros(shape=2 * n_sample) + true_label[0:n_sample] = 1 + + se_precomp = SpectralEmbedding(n_components=1, affinity="precomputed", + random_state=np.random.RandomState(seed)) + embedded_coordinate = se_precomp.fit_transform(affinity) + # Some numpy versions are touchy with types + embedded_coordinate = \ + se_precomp.fit_transform(affinity.astype(np.float32)) + # thresholding on the first components using 0. + label_ = np.array(embedded_coordinate.ravel() < 0, dtype="float") + assert_equal(normalized_mutual_info_score(true_label, label_), 1.0) + + +def test_spectral_embedding_precomputed_affinity(seed=36): + """Test spectral embedding with precomputed kernel""" + gamma = 1.0 + se_precomp = SpectralEmbedding(n_components=2, affinity="precomputed", + random_state=np.random.RandomState(seed)) + se_rbf = SpectralEmbedding(n_components=2, affinity="rbf", + gamma=gamma, + random_state=np.random.RandomState(seed)) + embed_precomp = se_precomp.fit_transform(rbf_kernel(S, gamma=gamma)) + embed_rbf = se_rbf.fit_transform(S) + assert_array_almost_equal( + se_precomp.affinity_matrix_, se_rbf.affinity_matrix_) + assert_true(_check_with_col_sign_flipping(embed_precomp, embed_rbf, 0.05)) + + +def test_spectral_embedding_callable_affinity(seed=36): + """Test spectral embedding with callable affinity""" + gamma = 0.9 + kern = rbf_kernel(S, gamma=gamma) + se_callable = SpectralEmbedding(n_components=2, + affinity=( + lambda x: rbf_kernel(x, gamma=gamma)), + gamma=gamma, + random_state=np.random.RandomState(seed)) + se_rbf = SpectralEmbedding(n_components=2, affinity="rbf", + gamma=gamma, + random_state=np.random.RandomState(seed)) + embed_rbf = se_rbf.fit_transform(S) + embed_callable = se_callable.fit_transform(S) + assert_array_almost_equal( + se_callable.affinity_matrix_, se_rbf.affinity_matrix_) + assert_array_almost_equal(kern, se_rbf.affinity_matrix_) + assert_true( + _check_with_col_sign_flipping(embed_rbf, embed_callable, 0.05)) + + +def test_spectral_embedding_amg_solver(seed=36): + """Test spectral embedding with amg solver""" + try: + from pyamg import smoothed_aggregation_solver + except ImportError: + raise SkipTest("pyamg not available.") + + se_amg = SpectralEmbedding(n_components=2, affinity="nearest_neighbors", + eigen_solver="amg", n_neighbors=5, + random_state=np.random.RandomState(seed)) + se_arpack = SpectralEmbedding(n_components=2, affinity="nearest_neighbors", + eigen_solver="arpack", n_neighbors=5, + random_state=np.random.RandomState(seed)) + embed_amg = se_amg.fit_transform(S) + embed_arpack = se_arpack.fit_transform(S) + assert_true(_check_with_col_sign_flipping(embed_amg, embed_arpack, 0.05)) + + +def test_pipeline_spectral_clustering(seed=36): + """Test using pipeline to do spectral clustering""" + random_state = np.random.RandomState(seed) + se_rbf = SpectralEmbedding(n_components=n_clusters, + affinity="rbf", + random_state=random_state) + se_knn = SpectralEmbedding(n_components=n_clusters, + affinity="nearest_neighbors", + n_neighbors=5, + random_state=random_state) + for se in [se_rbf, se_knn]: + km = KMeans(n_clusters=n_clusters, random_state=random_state) + km.fit(se.fit_transform(S)) + assert_array_almost_equal( + normalized_mutual_info_score( + km.labels_, + true_labels), 1.0, 2) + + +def test_spectral_embedding_unknown_eigensolver(seed=36): + """Test that SpectralClustering fails with an unknown eigensolver""" + se = SpectralEmbedding(n_components=1, affinity="precomputed", + random_state=np.random.RandomState(seed), + eigen_solver="") + assert_raises(ValueError, se.fit, S) + + +def test_spectral_embedding_unknown_affinity(seed=36): + """Test that SpectralClustering fails with an unknown affinity type""" + se = SpectralEmbedding(n_components=1, affinity="", + random_state=np.random.RandomState(seed)) + assert_raises(ValueError, se.fit, S) + + +def test_connectivity(seed=36): + """Test that graph connectivity test works as expected""" + graph = np.array([[1, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 1, 1], + [0, 0, 0, 1, 1]]) + assert_equal(_graph_is_connected(graph), False) + assert_equal(_graph_is_connected(csr_matrix(graph)), False) + assert_equal(_graph_is_connected(csc_matrix(graph)), False) + graph = np.array([[1, 1, 0, 0, 0], + [1, 1, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 1, 1], + [0, 0, 0, 1, 1]]) + assert_equal(_graph_is_connected(graph), True) + assert_equal(_graph_is_connected(csr_matrix(graph)), True) + assert_equal(_graph_is_connected(csc_matrix(graph)), True) + + +def test_spectral_embedding_deterministic(): + # Test that Spectral Embedding is deterministic + random_state = np.random.RandomState(36) + data = random_state.randn(10, 30) + sims = rbf_kernel(data) + embedding_1 = spectral_embedding(sims) + embedding_2 = spectral_embedding(sims) + assert_array_almost_equal(embedding_1, embedding_2) diff --git a/sklearn/manifold/tests/test_t_sne.py b/sklearn/manifold/tests/test_t_sne.py new file mode 100644 index 0000000000000..ec857403a5fed --- /dev/null +++ b/sklearn/manifold/tests/test_t_sne.py @@ -0,0 +1,273 @@ +import sys +from sklearn.externals.six.moves import cStringIO as StringIO +import numpy as np +import scipy.sparse as sp +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_raises_regexp +from sklearn.utils import check_random_state +from sklearn.manifold.t_sne import _joint_probabilities +from sklearn.manifold.t_sne import _kl_divergence +from sklearn.manifold.t_sne import _gradient_descent +from sklearn.manifold.t_sne import trustworthiness +from sklearn.manifold.t_sne import TSNE +from sklearn.manifold._utils import _binary_search_perplexity +from scipy.optimize import check_grad +from scipy.spatial.distance import pdist +from scipy.spatial.distance import squareform + + +def test_gradient_descent_stops(): + """Test stopping conditions of gradient descent.""" + class ObjectiveSmallGradient: + def __init__(self): + self.it = -1 + + def __call__(self, _): + self.it += 1 + return (10 - self.it) / 10.0, np.array([1e-5]) + + def flat_function(_): + return 0.0, np.ones(1) + + # Gradient norm + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + _, error, it = _gradient_descent( + ObjectiveSmallGradient(), np.zeros(1), 0, n_iter=100, + n_iter_without_progress=100, momentum=0.0, learning_rate=0.0, + min_gain=0.0, min_grad_norm=1e-5, min_error_diff=0.0, verbose=2) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + assert_equal(error, 1.0) + assert_equal(it, 0) + assert("gradient norm" in out) + + # Error difference + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + _, error, it = _gradient_descent( + ObjectiveSmallGradient(), np.zeros(1), 0, n_iter=100, + n_iter_without_progress=100, momentum=0.0, learning_rate=0.0, + min_gain=0.0, min_grad_norm=0.0, min_error_diff=0.2, verbose=2) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + assert_equal(error, 0.9) + assert_equal(it, 1) + assert("error difference" in out) + + # Maximum number of iterations without improvement + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + _, error, it = _gradient_descent( + flat_function, np.zeros(1), 0, n_iter=100, + n_iter_without_progress=10, momentum=0.0, learning_rate=0.0, + min_gain=0.0, min_grad_norm=0.0, min_error_diff=-1.0, verbose=2) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + assert_equal(error, 0.0) + assert_equal(it, 11) + assert("did not make any progress" in out) + + # Maximum number of iterations + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + _, error, it = _gradient_descent( + ObjectiveSmallGradient(), np.zeros(1), 0, n_iter=11, + n_iter_without_progress=100, momentum=0.0, learning_rate=0.0, + min_gain=0.0, min_grad_norm=0.0, min_error_diff=0.0, verbose=2) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + assert_equal(error, 0.0) + assert_equal(it, 10) + assert("Iteration 10" in out) + + +def test_binary_search(): + """Test if the binary search finds Gaussians with desired perplexity.""" + random_state = check_random_state(0) + distances = random_state.randn(50, 2) + distances = distances.dot(distances.T) + np.fill_diagonal(distances, 0.0) + desired_perplexity = 25.0 + P = _binary_search_perplexity(distances, desired_perplexity, verbose=0) + P = np.maximum(P, np.finfo(np.double).eps) + mean_perplexity = np.mean([np.exp(-np.sum(P[i] * np.log(P[i]))) + for i in range(P.shape[0])]) + assert_almost_equal(mean_perplexity, desired_perplexity, decimal=3) + + +def test_gradient(): + """Test gradient of Kullback-Leibler divergence.""" + random_state = check_random_state(0) + + n_samples = 50 + n_features = 2 + n_components = 2 + alpha = 1.0 + + distances = random_state.randn(n_samples, n_features) + distances = distances.dot(distances.T) + np.fill_diagonal(distances, 0.0) + X_embedded = random_state.randn(n_samples, n_components) + + P = _joint_probabilities(distances, desired_perplexity=25.0, + verbose=0) + fun = lambda params: _kl_divergence(params, P, alpha, n_samples, + n_components)[0] + grad = lambda params: _kl_divergence(params, P, alpha, n_samples, + n_components)[1] + assert_almost_equal(check_grad(fun, grad, X_embedded.ravel()), 0.0, + decimal=5) + + +def test_trustworthiness(): + """Test trustworthiness score.""" + random_state = check_random_state(0) + + # Affine transformation + X = random_state.randn(100, 2) + assert_equal(trustworthiness(X, 5.0 + X / 10.0), 1.0) + + # Randomly shuffled + X = np.arange(100).reshape(-1, 1) + X_embedded = X.copy() + random_state.shuffle(X_embedded) + assert_less(trustworthiness(X, X_embedded), 0.6) + + # Completely different + X = np.arange(5).reshape(-1, 1) + X_embedded = np.array([[0], [2], [4], [1], [3]]) + assert_almost_equal(trustworthiness(X, X_embedded, n_neighbors=1), 0.2) + + +def test_preserve_trustworthiness_approximately(): + """Nearest neighbors should be preserved approximately.""" + random_state = check_random_state(0) + X = random_state.randn(100, 2) + for init in ('random', 'pca'): + tsne = TSNE(n_components=2, perplexity=10, learning_rate=100.0, + init=init, random_state=0) + X_embedded = tsne.fit_transform(X) + assert_almost_equal(trustworthiness(X, X_embedded, n_neighbors=1), 1.0, + decimal=1) + + +def test_fit_csr_matrix(): + """X can be a sparse matrix.""" + random_state = check_random_state(0) + X = random_state.randn(100, 2) + X[(np.random.randint(0, 100, 50), np.random.randint(0, 2, 50))] = 0.0 + X_csr = sp.csr_matrix(X) + tsne = TSNE(n_components=2, perplexity=10, learning_rate=100.0, + random_state=0) + X_embedded = tsne.fit_transform(X_csr) + assert_almost_equal(trustworthiness(X_csr, X_embedded, n_neighbors=1), 1.0, + decimal=1) + + +def test_preserve_trustworthiness_approximately_with_precomputed_distances(): + """Nearest neighbors should be preserved approximately.""" + random_state = check_random_state(0) + X = random_state.randn(100, 2) + D = squareform(pdist(X), "sqeuclidean") + tsne = TSNE(n_components=2, perplexity=10, learning_rate=100.0, + metric="precomputed", random_state=0) + X_embedded = tsne.fit_transform(D) + assert_almost_equal(trustworthiness(D, X_embedded, n_neighbors=1, + precomputed=True), 1.0, decimal=1) + + +def test_early_exaggeration_too_small(): + """Early exaggeration factor must be >= 1.""" + tsne = TSNE(early_exaggeration=0.99) + assert_raises_regexp(ValueError, "early_exaggeration .*", + tsne.fit_transform, np.array([[0.0]])) + + +def test_too_few_iterations(): + """Number of gradient descent iterations must be at least 200.""" + tsne = TSNE(n_iter=199) + assert_raises_regexp(ValueError, "n_iter .*", tsne.fit_transform, + np.array([[0.0]])) + + +def test_non_square_precomputed_distances(): + """Precomputed distance matrices must be square matrices.""" + tsne = TSNE(metric="precomputed") + assert_raises_regexp(ValueError, ".* square distance matrix", + tsne.fit_transform, np.array([[0.0], [1.0]])) + + +def test_init_not_available(): + """'init' must be 'pca' or 'random'.""" + assert_raises_regexp(ValueError, "'init' must be either 'pca' or 'random'", + TSNE, init="not available") + + +def test_distance_not_available(): + """'metric' must be valid.""" + tsne = TSNE(metric="not available") + assert_raises_regexp(ValueError, "Unknown metric not available.*", + tsne.fit_transform, np.array([[0.0], [1.0]])) + + +def test_pca_initialization_not_compatible_with_precomputed_kernel(): + """Precomputed distance matrices must be square matrices.""" + tsne = TSNE(metric="precomputed", init="pca") + assert_raises_regexp(ValueError, "The parameter init=\"pca\" cannot be " + "used with metric=\"precomputed\".", + tsne.fit_transform, np.array([[0.0], [1.0]])) + + +def test_verbose(): + random_state = check_random_state(0) + tsne = TSNE(verbose=2) + X = random_state.randn(5, 2) + + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + tsne.fit_transform(X) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + + assert("[t-SNE]" in out) + assert("Computing pairwise distances" in out) + assert("Computed conditional probabilities" in out) + assert("Mean sigma" in out) + assert("Finished" in out) + assert("early exaggeration" in out) + assert("Finished" in out) + + +def test_chebyshev_metric(): + """t-SNE should allow metrics that cannot be squared (issue #3526).""" + random_state = check_random_state(0) + tsne = TSNE(metric="chebyshev") + X = random_state.randn(5, 2) + tsne.fit_transform(X) + + +def test_reduction_to_one_component(): + """t-SNE should allow reduction to one component (issue #4154).""" + random_state = check_random_state(0) + tsne = TSNE(n_components=1) + X = random_state.randn(5, 2) + X_embedded = tsne.fit_transform(X) + assert(np.all(np.isfinite(X_embedded))) diff --git a/sklearn/metrics/__init__.py b/sklearn/metrics/__init__.py index 654d95c55b9ac..c455f9e8c4d81 100644 --- a/sklearn/metrics/__init__.py +++ b/sklearn/metrics/__init__.py @@ -3,55 +3,107 @@ and pairwise metrics and distance computations. """ -from .metrics import (confusion_matrix, roc_curve, auc, precision_score, - recall_score, fbeta_score, f1_score, zero_one_score, - precision_recall_fscore_support, classification_report, - precision_recall_curve, explained_variance_score, - r2_score, zero_one, hinge_loss, matthews_corrcoef, - mean_squared_error, average_precision_score, auc_score) + +from .ranking import auc +from .ranking import average_precision_score +from .ranking import coverage_error +from .ranking import label_ranking_average_precision_score +from .ranking import precision_recall_curve +from .ranking import roc_auc_score +from .ranking import roc_curve + +from .classification import accuracy_score +from .classification import classification_report +from .classification import confusion_matrix +from .classification import f1_score +from .classification import fbeta_score +from .classification import hamming_loss +from .classification import hinge_loss +from .classification import jaccard_similarity_score +from .classification import log_loss +from .classification import matthews_corrcoef +from .classification import precision_recall_fscore_support +from .classification import precision_score +from .classification import recall_score +from .classification import zero_one_loss +from .classification import brier_score_loss from . import cluster +from .cluster import adjusted_mutual_info_score from .cluster import adjusted_rand_score +from .cluster import completeness_score +from .cluster import consensus_score from .cluster import homogeneity_completeness_v_measure from .cluster import homogeneity_score -from .cluster import completeness_score -from .cluster import v_measure_score -from .cluster import silhouette_score from .cluster import mutual_info_score -from .cluster import adjusted_mutual_info_score from .cluster import normalized_mutual_info_score -from .pairwise import euclidean_distances, pairwise_distances, pairwise_kernels - -__all__ = ['adjusted_mutual_info_score', - 'adjusted_rand_score', - 'auc', - 'auc_score', - 'average_precision_score', - 'classification_report', - 'cluster', - 'completeness_score', - 'confusion_matrix', - 'euclidean_distances', - 'explained_variance_score', - 'f1_score', - 'fbeta_score', - 'hinge_loss', - 'homogeneity_completeness_v_measure', - 'homogeneity_score', - 'matthews_corrcoef', - 'mean_square_error', - 'mean_squared_error', - 'mutual_info_score', - 'normalized_mutual_info_score', - 'pairwise_distances', - 'pairwise_kernels', - 'precision_recall_curve', - 'precision_recall_fscore_support', - 'precision_score', - 'r2_score', - 'recall_score', - 'roc_curve', - 'silhouette_score', - 'v_measure_score', - 'zero_one', - 'zero_one_score'] +from .cluster import silhouette_samples +from .cluster import silhouette_score +from .cluster import v_measure_score + +from .pairwise import euclidean_distances +from .pairwise import pairwise_distances +from .pairwise import pairwise_distances_argmin +from .pairwise import pairwise_distances_argmin_min +from .pairwise import pairwise_kernels + +from .regression import explained_variance_score +from .regression import mean_absolute_error +from .regression import mean_squared_error +from .regression import median_absolute_error +from .regression import r2_score + +from .scorer import make_scorer +from .scorer import SCORERS +from .scorer import get_scorer + +__all__ = [ + 'accuracy_score', + 'adjusted_mutual_info_score', + 'adjusted_rand_score', + 'auc', + 'average_precision_score', + 'classification_report', + 'cluster', + 'completeness_score', + 'confusion_matrix', + 'consensus_score', + 'coverage_error', + 'euclidean_distances', + 'explained_variance_score', + 'f1_score', + 'fbeta_score', + 'get_scorer', + 'hamming_loss', + 'hinge_loss', + 'homogeneity_completeness_v_measure', + 'homogeneity_score', + 'jaccard_similarity_score', + 'label_ranking_average_precision_score', + 'log_loss', + 'make_scorer', + 'matthews_corrcoef', + 'mean_absolute_error', + 'mean_squared_error', + 'median_absolute_error', + 'mutual_info_score', + 'normalized_mutual_info_score', + 'pairwise_distances', + 'pairwise_distances_argmin', + 'pairwise_distances_argmin_min', + 'pairwise_distances_argmin_min', + 'pairwise_kernels', + 'precision_recall_curve', + 'precision_recall_fscore_support', + 'precision_score', + 'r2_score', + 'recall_score', + 'roc_auc_score', + 'roc_curve', + 'SCORERS', + 'silhouette_samples', + 'silhouette_score', + 'v_measure_score', + 'zero_one_loss', + 'brier_score_loss', +] diff --git a/sklearn/metrics/base.py b/sklearn/metrics/base.py new file mode 100644 index 0000000000000..5e9593880fbb5 --- /dev/null +++ b/sklearn/metrics/base.py @@ -0,0 +1,128 @@ +""" +Common code for all metrics + +""" +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Olivier Grisel +# Arnaud Joly +# Jochen Wersdorfer +# Lars Buitinck +# Joel Nothman +# Noel Dawe +# License: BSD 3 clause + +from __future__ import division + +import numpy as np + +from ..utils import check_array, check_consistent_length +from ..utils.multiclass import type_of_target + + +class UndefinedMetricWarning(UserWarning): + pass + + +def _average_binary_score(binary_metric, y_true, y_score, average, + sample_weight=None): + """Average a binary metric for multilabel classification + + Parameters + ---------- + y_true : array, shape = [n_samples] or [n_samples, n_classes] + True binary labels in binary label indicators. + + y_score : array, shape = [n_samples] or [n_samples, n_classes] + Target scores, can either be probability estimates of the positive + class, confidence values, or binary decisions. + + average : string, [None, 'micro', 'macro' (default), 'samples', 'weighted'] + If ``None``, the scores for each class are returned. Otherwise, + this determines the type of averaging performed on the data: + + ``'micro'``: + Calculate metrics globally by considering each element of the label + indicator matrix as a label. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). + ``'samples'``: + Calculate metrics for each instance, and find their average. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + binary_metric : callable, returns shape [n_classes] + The binary metric function to use. + + Returns + ------- + score : float or array of shape [n_classes] + If not ``None``, average the score, else return the score for each + classes. + + """ + average_options = (None, 'micro', 'macro', 'weighted', 'samples') + if average not in average_options: + raise ValueError('average has to be one of {0}' + ''.format(average_options)) + + y_type = type_of_target(y_true) + if y_type not in ("binary", "multilabel-indicator"): + raise ValueError("{0} format is not supported".format(y_type)) + + if y_type == "binary": + return binary_metric(y_true, y_score, sample_weight=sample_weight) + + check_consistent_length(y_true, y_score, sample_weight) + y_true = check_array(y_true) + y_score = check_array(y_score) + + not_average_axis = 1 + score_weight = sample_weight + average_weight = None + + if average == "micro": + if score_weight is not None: + score_weight = np.repeat(score_weight, y_true.shape[1]) + y_true = y_true.ravel() + y_score = y_score.ravel() + + elif average == 'weighted': + if score_weight is not None: + average_weight = np.sum(np.multiply( + y_true, np.reshape(score_weight, (-1, 1))), axis=0) + else: + average_weight = np.sum(y_true, axis=0) + if average_weight.sum() == 0: + return 0 + + elif average == 'samples': + # swap average_weight <-> score_weight + average_weight = score_weight + score_weight = None + not_average_axis = 0 + + if y_true.ndim == 1: + y_true = y_true.reshape((-1, 1)) + + if y_score.ndim == 1: + y_score = y_score.reshape((-1, 1)) + + n_classes = y_score.shape[not_average_axis] + score = np.zeros((n_classes,)) + for c in range(n_classes): + y_true_c = y_true.take([c], axis=not_average_axis).ravel() + y_score_c = y_score.take([c], axis=not_average_axis).ravel() + score[c] = binary_metric(y_true_c, y_score_c, + sample_weight=score_weight) + + # Average the results + if average is not None: + return np.average(score, weights=average_weight) + else: + return score diff --git a/sklearn/metrics/classification.py b/sklearn/metrics/classification.py new file mode 100644 index 0000000000000..78d00e2c155c6 --- /dev/null +++ b/sklearn/metrics/classification.py @@ -0,0 +1,1649 @@ +"""Metrics to assess performance on classification task given classe prediction + +Functions named as ``*_score`` return a scalar value to maximize: the higher +the better + +Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: +the lower the better +""" + +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Olivier Grisel +# Arnaud Joly +# Jochen Wersdorfer +# Lars Buitinck +# Joel Nothman +# Noel Dawe +# Jatin Shah +# Saurabh Jha +# License: BSD 3 clause + +from __future__ import division + +import warnings +import numpy as np + +from scipy.sparse import coo_matrix +from scipy.sparse import csr_matrix +from scipy.spatial.distance import hamming as sp_hamming + +from ..preprocessing import LabelBinarizer, label_binarize +from ..preprocessing import LabelEncoder +from ..utils import check_array +from ..utils import check_consistent_length +from ..preprocessing import MultiLabelBinarizer +from ..utils import column_or_1d +from ..utils import check_consistent_length +from ..utils.multiclass import unique_labels +from ..utils.multiclass import type_of_target +from ..utils.validation import _num_samples +from ..utils.sparsefuncs import count_nonzero +from ..utils.fixes import bincount + +from .base import UndefinedMetricWarning + + +def _check_targets(y_true, y_pred): + """Check that y_true and y_pred belong to the same classification task + + This converts multiclass or binary types to a common shape, and raises a + ValueError for a mix of multilabel and multiclass targets, a mix of + multilabel formats, for the presence of continuous-valued or multioutput + targets, or for targets of different lengths. + + Column vectors are squeezed to 1d, while multilabel formats are returned + as CSR sparse label indicators. + + Parameters + ---------- + y_true : array-like + + y_pred : array-like + + Returns + ------- + type_true : one of {'multilabel-indicator', 'multilabel-sequences', \ + 'multiclass', 'binary'} + The type of the true target data, as output by + ``utils.multiclass.type_of_target`` + + y_true : array or indicator matrix + + y_pred : array or indicator matrix + """ + check_consistent_length(y_true, y_pred) + type_true = type_of_target(y_true) + type_pred = type_of_target(y_pred) + + y_type = set([type_true, type_pred]) + if y_type == set(["binary", "multiclass"]): + y_type = set(["multiclass"]) + + if len(y_type) > 1: + raise ValueError("Can't handle mix of {0} and {1}" + "".format(type_true, type_pred)) + + # We can't have more than one value on y_type => The set is no more needed + y_type = y_type.pop() + + # No metrics support "multiclass-multioutput" format + if (y_type not in ["binary", "multiclass", "multilabel-indicator", + "multilabel-sequences"]): + raise ValueError("{0} is not supported".format(y_type)) + + if y_type in ["binary", "multiclass"]: + y_true = column_or_1d(y_true) + y_pred = column_or_1d(y_pred) + + if y_type.startswith('multilabel'): + if y_type == 'multilabel-sequences': + labels = unique_labels(y_true, y_pred) + binarizer = MultiLabelBinarizer(classes=labels, sparse_output=True) + y_true = binarizer.fit_transform(y_true) + y_pred = binarizer.fit_transform(y_pred) + + y_true = csr_matrix(y_true) + y_pred = csr_matrix(y_pred) + y_type = 'multilabel-indicator' + + return y_type, y_true, y_pred + + +def _weighted_sum(sample_score, sample_weight, normalize=False): + if normalize: + return np.average(sample_score, weights=sample_weight) + elif sample_weight is not None: + return np.dot(sample_score, sample_weight) + else: + return sample_score.sum() + + +def accuracy_score(y_true, y_pred, normalize=True, sample_weight=None): + """Accuracy classification score. + + In multilabel classification, this function computes subset accuracy: + the set of labels predicted for a sample must *exactly* match the + corresponding set of labels in y_true. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + normalize : bool, optional (default=True) + If ``False``, return the number of correctly classified samples. + Otherwise, return the fraction of correctly classified samples. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + score : float + If ``normalize == True``, return the correctly classified samples + (float), else it returns the number of correctly classified samples + (int). + + The best performance is 1 with ``normalize == True`` and the number + of samples with ``normalize == False``. + + See also + -------- + jaccard_similarity_score, hamming_loss, zero_one_loss + + Notes + ----- + In binary and multiclass classification, this function is equal + to the ``jaccard_similarity_score`` function. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import accuracy_score + >>> y_pred = [0, 2, 1, 3] + >>> y_true = [0, 1, 2, 3] + >>> accuracy_score(y_true, y_pred) + 0.5 + >>> accuracy_score(y_true, y_pred, normalize=False) + 2 + + In the multilabel case with binary label indicators: + >>> accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) + 0.5 + """ + + # Compute accuracy for each possible representation + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + if y_type.startswith('multilabel'): + differing_labels = count_nonzero(y_true - y_pred, axis=1) + score = differing_labels == 0 + else: + score = y_true == y_pred + + return _weighted_sum(score, sample_weight, normalize) + + +def confusion_matrix(y_true, y_pred, labels=None): + """Compute confusion matrix to evaluate the accuracy of a classification + + By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}` + is equal to the number of observations known to be in group :math:`i` but + predicted to be in group :math:`j`. + + Parameters + ---------- + y_true : array, shape = [n_samples] + Ground truth (correct) target values. + + y_pred : array, shape = [n_samples] + Estimated targets as returned by a classifier. + + labels : array, shape = [n_classes], optional + List of labels to index the matrix. This may be used to reorder + or select a subset of labels. + If none is given, those that appear at least once + in ``y_true`` or ``y_pred`` are used in sorted order. + + Returns + ------- + C : array, shape = [n_classes, n_classes] + Confusion matrix + + References + ---------- + .. [1] `Wikipedia entry for the Confusion matrix + `_ + + Examples + -------- + >>> from sklearn.metrics import confusion_matrix + >>> y_true = [2, 0, 2, 2, 0, 1] + >>> y_pred = [0, 0, 2, 2, 0, 2] + >>> confusion_matrix(y_true, y_pred) + array([[2, 0, 0], + [0, 0, 1], + [1, 0, 2]]) + + """ + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + if y_type not in ("binary", "multiclass"): + raise ValueError("%s is not supported" % y_type) + + if labels is None: + labels = unique_labels(y_true, y_pred) + else: + labels = np.asarray(labels) + + n_labels = labels.size + label_to_ind = dict((y, x) for x, y in enumerate(labels)) + # convert yt, yp into index + y_pred = np.array([label_to_ind.get(x, n_labels + 1) for x in y_pred]) + y_true = np.array([label_to_ind.get(x, n_labels + 1) for x in y_true]) + + # intersect y_pred, y_true with labels, eliminate items not in labels + ind = np.logical_and(y_pred < n_labels, y_true < n_labels) + y_pred = y_pred[ind] + y_true = y_true[ind] + + CM = coo_matrix((np.ones(y_true.shape[0], dtype=np.int), (y_true, y_pred)), + shape=(n_labels, n_labels) + ).toarray() + + return CM + + +def jaccard_similarity_score(y_true, y_pred, normalize=True, + sample_weight=None): + """Jaccard similarity coefficient score + + The Jaccard index [1], or Jaccard similarity coefficient, defined as + the size of the intersection divided by the size of the union of two label + sets, is used to compare set of predicted labels for a sample to the + corresponding set of labels in ``y_true``. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + normalize : bool, optional (default=True) + If ``False``, return the sum of the Jaccard similarity coefficient + over the sample set. Otherwise, return the average of Jaccard + similarity coefficient. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + score : float + If ``normalize == True``, return the average Jaccard similarity + coefficient, else it returns the sum of the Jaccard similarity + coefficient over the sample set. + + The best performance is 1 with ``normalize == True`` and the number + of samples with ``normalize == False``. + + See also + -------- + accuracy_score, hamming_loss, zero_one_loss + + Notes + ----- + In binary and multiclass classification, this function is equivalent + to the ``accuracy_score``. It differs in the multilabel classification + problem. + + References + ---------- + .. [1] `Wikipedia entry for the Jaccard index + `_ + + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import jaccard_similarity_score + >>> y_pred = [0, 2, 1, 3] + >>> y_true = [0, 1, 2, 3] + >>> jaccard_similarity_score(y_true, y_pred) + 0.5 + >>> jaccard_similarity_score(y_true, y_pred, normalize=False) + 2 + + In the multilabel case with binary label indicators: + + >>> jaccard_similarity_score(np.array([[0, 1], [1, 1]]),\ + np.ones((2, 2))) + 0.75 + """ + + # Compute accuracy for each possible representation + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + if y_type.startswith('multilabel'): + with np.errstate(divide='ignore', invalid='ignore'): + # oddly, we may get an "invalid" rather than a "divide" error here + pred_or_true = count_nonzero(y_true + y_pred, axis=1) + pred_and_true = count_nonzero(y_true.multiply(y_pred), axis=1) + score = pred_and_true / pred_or_true + + # If there is no label, it results in a Nan instead, we set + # the jaccard to 1: lim_{x->0} x/x = 1 + # Note with py2.6 and np 1.3: we can't check safely for nan. + score[pred_or_true == 0.0] = 1.0 + else: + score = y_true == y_pred + + return _weighted_sum(score, sample_weight, normalize) + + +def matthews_corrcoef(y_true, y_pred): + """Compute the Matthews correlation coefficient (MCC) for binary classes + + The Matthews correlation coefficient is used in machine learning as a + measure of the quality of binary (two-class) classifications. It takes into + account true and false positives and negatives and is generally regarded as + a balanced measure which can be used even if the classes are of very + different sizes. The MCC is in essence a correlation coefficient value + between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 + an average random prediction and -1 an inverse prediction. The statistic + is also known as the phi coefficient. [source: Wikipedia] + + Only in the binary case does this relate to information about true and + false positives and negatives. See references below. + + Parameters + ---------- + y_true : array, shape = [n_samples] + Ground truth (correct) target values. + + y_pred : array, shape = [n_samples] + Estimated targets as returned by a classifier. + + Returns + ------- + mcc : float + The Matthews correlation coefficient (+1 represents a perfect + prediction, 0 an average random prediction and -1 and inverse + prediction). + + References + ---------- + .. [1] `Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the + accuracy of prediction algorithms for classification: an overview + `_ + + .. [2] `Wikipedia entry for the Matthews Correlation Coefficient + `_ + + Examples + -------- + >>> from sklearn.metrics import matthews_corrcoef + >>> y_true = [+1, +1, +1, -1] + >>> y_pred = [+1, -1, +1, +1] + >>> matthews_corrcoef(y_true, y_pred) # doctest: +ELLIPSIS + -0.33... + + """ + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + + if y_type != "binary": + raise ValueError("%s is not supported" % y_type) + + lb = LabelEncoder() + lb.fit(np.hstack([y_true, y_pred])) + y_true = lb.transform(y_true) + y_pred = lb.transform(y_pred) + with np.errstate(invalid='ignore'): + mcc = np.corrcoef(y_true, y_pred)[0, 1] + + if np.isnan(mcc): + return 0. + else: + return mcc + + +def zero_one_loss(y_true, y_pred, normalize=True, sample_weight=None): + """Zero-one classification loss. + + If normalize is ``True``, return the fraction of misclassifications + (float), else it returns the number of misclassifications (int). The best + performance is 0. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + normalize : bool, optional (default=True) + If ``False``, return the number of misclassifications. + Otherwise, return the fraction of misclassifications. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + loss : float or int, + If ``normalize == True``, return the fraction of misclassifications + (float), else it returns the number of misclassifications (int). + + Notes + ----- + In multilabel classification, the zero_one_loss function corresponds to + the subset zero-one loss: for each sample, the entire set of labels must be + correctly predicted, otherwise the loss for that sample is equal to one. + + See also + -------- + accuracy_score, hamming_loss, jaccard_similarity_score + + Examples + -------- + >>> from sklearn.metrics import zero_one_loss + >>> y_pred = [1, 2, 3, 4] + >>> y_true = [2, 2, 3, 4] + >>> zero_one_loss(y_true, y_pred) + 0.25 + >>> zero_one_loss(y_true, y_pred, normalize=False) + 1 + + In the multilabel case with binary label indicators: + + >>> zero_one_loss(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) + 0.5 + """ + score = accuracy_score(y_true, y_pred, + normalize=normalize, + sample_weight=sample_weight) + + if normalize: + return 1 - score + else: + if sample_weight is not None: + n_samples = np.sum(sample_weight) + else: + n_samples = _num_samples(y_true) + return n_samples - score + + +def f1_score(y_true, y_pred, labels=None, pos_label=1, average='binary', + sample_weight=None): + """Compute the F1 score, also known as balanced F-score or F-measure + + The F1 score can be interpreted as a weighted average of the precision and + recall, where an F1 score reaches its best value at 1 and worst score at 0. + The relative contribution of precision and recall to the F1 score are + equal. The formula for the F1 score is:: + + F1 = 2 * (precision * recall) / (precision + recall) + + In the multi-class and multi-label case, this is the weighted average of + the F1 score of each class. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array + Integer array of labels. + + pos_label : str or int, 1 by default + The class to report if ``average='binary'``. Until version 0.18 it is + necessary to set ``pos_label=None`` if seeking to use another averaging + method over binary targets. + + average : string, [None, 'binary' (default), 'micro', 'macro', 'samples', \ + 'weighted'] + This parameter is required for multiclass/multilabel targets. + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + Note that if ``pos_label`` is given in binary classification with + `average != 'binary'`, only that positive class is reported. This + behavior is deprecated and will change in version 0.18. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + f1_score : float or array of float, shape = [n_unique_labels] + F1 score of the positive class in binary classification or weighted + average of the F1 scores of each class for the multiclass task. + + References + ---------- + .. [1] `Wikipedia entry for the F1-score + `_ + + Examples + -------- + >>> from sklearn.metrics import f1_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> f1_score(y_true, y_pred, average='macro') # doctest: +ELLIPSIS + 0.26... + >>> f1_score(y_true, y_pred, average='micro') # doctest: +ELLIPSIS + 0.33... + >>> f1_score(y_true, y_pred, average='weighted') # doctest: +ELLIPSIS + 0.26... + >>> f1_score(y_true, y_pred, average=None) + array([ 0.8, 0. , 0. ]) + + + """ + return fbeta_score(y_true, y_pred, 1, labels=labels, + pos_label=pos_label, average=average, + sample_weight=sample_weight) + + +def fbeta_score(y_true, y_pred, beta, labels=None, pos_label=1, + average='binary', sample_weight=None): + """Compute the F-beta score + + The F-beta score is the weighted harmonic mean of precision and recall, + reaching its optimal value at 1 and its worst value at 0. + + The `beta` parameter determines the weight of precision in the combined + score. ``beta < 1`` lends more weight to precision, while ``beta > 1`` + favors recall (``beta -> 0`` considers only precision, ``beta -> inf`` + only recall). + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + beta: float + Weight of precision in harmonic mean. + + labels : array + Integer array of labels. + + pos_label : str or int, 1 by default + The class to report if ``average='binary'``. Until version 0.18 it is + necessary to set ``pos_label=None`` if seeking to use another averaging + method over binary targets. + + average : string, [None, 'binary' (default), 'micro', 'macro', 'samples', \ + 'weighted'] + This parameter is required for multiclass/multilabel targets. + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + Note that if ``pos_label`` is given in binary classification with + `average != 'binary'`, only that positive class is reported. This + behavior is deprecated and will change in version 0.18. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + fbeta_score : float (if average is not None) or array of float, shape =\ + [n_unique_labels] + F-beta score of the positive class in binary classification or weighted + average of the F-beta score of each class for the multiclass task. + + References + ---------- + .. [1] R. Baeza-Yates and B. Ribeiro-Neto (2011). + Modern Information Retrieval. Addison Wesley, pp. 327-328. + + .. [2] `Wikipedia entry for the F1-score + `_ + + Examples + -------- + >>> from sklearn.metrics import fbeta_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> fbeta_score(y_true, y_pred, average='macro', beta=0.5) + ... # doctest: +ELLIPSIS + 0.23... + >>> fbeta_score(y_true, y_pred, average='micro', beta=0.5) + ... # doctest: +ELLIPSIS + 0.33... + >>> fbeta_score(y_true, y_pred, average='weighted', beta=0.5) + ... # doctest: +ELLIPSIS + 0.23... + >>> fbeta_score(y_true, y_pred, average=None, beta=0.5) + ... # doctest: +ELLIPSIS + array([ 0.71..., 0. , 0. ]) + + """ + _, _, f, _ = precision_recall_fscore_support(y_true, y_pred, + beta=beta, + labels=labels, + pos_label=pos_label, + average=average, + warn_for=('f-score',), + sample_weight=sample_weight) + return f + + +def _prf_divide(numerator, denominator, metric, modifier, average, warn_for): + """Performs division and handles divide-by-zero. + + On zero-division, sets the corresponding result elements to zero + and raises a warning. + + The metric, modifier and average arguments are used only for determining + an appropriate warning. + """ + result = numerator / denominator + mask = denominator == 0.0 + if not np.any(mask): + return result + + # remove infs + result[mask] = 0.0 + + # build appropriate warning + # E.g. "Precision and F-score are ill-defined and being set to 0.0 in + # labels with no predicted samples" + axis0 = 'sample' + axis1 = 'label' + if average == 'samples': + axis0, axis1 = axis1, axis0 + + if metric in warn_for and 'f-score' in warn_for: + msg_start = '{0} and F-score are'.format(metric.title()) + elif metric in warn_for: + msg_start = '{0} is'.format(metric.title()) + elif 'f-score' in warn_for: + msg_start = 'F-score is' + else: + return result + + msg = ('{0} ill-defined and being set to 0.0 {{0}} ' + 'no {1} {2}s.'.format(msg_start, modifier, axis0)) + if len(mask) == 1: + msg = msg.format('due to') + else: + msg = msg.format('in {0}s with'.format(axis1)) + warnings.warn(msg, UndefinedMetricWarning, stacklevel=2) + return result + + +def precision_recall_fscore_support(y_true, y_pred, beta=1.0, labels=None, + pos_label=1, average=None, + warn_for=('precision', 'recall', + 'f-score'), + sample_weight=None): + """Compute precision, recall, F-measure and support for each class + + The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of + true positives and ``fp`` the number of false positives. The precision is + intuitively the ability of the classifier not to label as positive a sample + that is negative. + + The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of + true positives and ``fn`` the number of false negatives. The recall is + intuitively the ability of the classifier to find all the positive samples. + + The F-beta score can be interpreted as a weighted harmonic mean of + the precision and recall, where an F-beta score reaches its best + value at 1 and worst score at 0. + + The F-beta score weights recall more than precision by a factor of + ``beta``. ``beta == 1.0`` means recall and precision are equally important. + + The support is the number of occurrences of each class in ``y_true``. + + If ``pos_label is None`` and in binary classification, this function + returns the average precision, recall and F-measure if ``average`` + is one of ``'micro'``, ``'macro'``, ``'weighted'`` or ``'samples'``. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + beta : float, 1.0 by default + The strength of recall versus precision in the F-score. + + labels : array + Integer array of labels. + + pos_label : str or int, 1 by default + The class to report if ``average='binary'``. Until version 0.18 it is + necessary to set ``pos_label=None`` if seeking to use another averaging + method over binary targets. + + average : string, [None (default), 'binary', 'micro', 'macro', 'samples', \ + 'weighted'] + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + Note that if ``pos_label`` is given in binary classification with + `average != 'binary'`, only that positive class is reported. This + behavior is deprecated and will change in version 0.18. + + warn_for : tuple or set, for internal use + This determines which warnings will be made in the case that this + function is being used to return only one of its metrics. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + precision: float (if average is not None) or array of float, shape =\ + [n_unique_labels] + + recall: float (if average is not None) or array of float, , shape =\ + [n_unique_labels] + + fbeta_score: float (if average is not None) or array of float, shape =\ + [n_unique_labels] + + support: int (if average is not None) or array of int, shape =\ + [n_unique_labels] + The number of occurrences of each label in ``y_true``. + + References + ---------- + .. [1] `Wikipedia entry for the Precision and recall + `_ + + .. [2] `Wikipedia entry for the F1-score + `_ + + .. [3] `Discriminative Methods for Multi-labeled Classification Advances + in Knowledge Discovery and Data Mining (2004), pp. 22-30 by Shantanu + Godbole, Sunita Sarawagi + ` + + Examples + -------- + >>> from sklearn.metrics import precision_recall_fscore_support + >>> y_true = np.array([0, 1, 2, 0, 1, 2]) + >>> y_pred = np.array([0, 2, 1, 0, 0, 1]) + >>> precision_recall_fscore_support(y_true, y_pred, average='macro') + ... # doctest: +ELLIPSIS + (0.22..., 0.33..., 0.26..., None) + >>> precision_recall_fscore_support(y_true, y_pred, average='micro') + ... # doctest: +ELLIPSIS + (0.33..., 0.33..., 0.33..., None) + >>> precision_recall_fscore_support(y_true, y_pred, average='weighted') + ... # doctest: +ELLIPSIS + (0.22..., 0.33..., 0.26..., None) + + """ + average_options = (None, 'micro', 'macro', 'weighted', 'samples') + if average not in average_options and average != 'binary': + raise ValueError('average has to be one of ' + + str(average_options)) + if beta <= 0: + raise ValueError("beta should be >0 in the F-beta score") + + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + + if average == 'binary' and (y_type != 'binary' or pos_label is None): + warnings.warn('The default `weighted` averaging is deprecated, ' + 'and from version 0.18, use of precision, recall or ' + 'F-score with multiclass or multilabel data or ' + 'pos_label=None will result in an exception. ' + 'Please set an explicit value for `average`, one of ' + '%s. In cross validation use, for instance, ' + 'scoring="f1_weighted" instead of scoring="f1".' + % str(average_options), DeprecationWarning, stacklevel=2) + average = 'weighted' + + label_order = labels # save this for later + if labels is None: + labels = unique_labels(y_true, y_pred) + else: + labels = np.sort(labels) + + ### Calculate tp_sum, pred_sum, true_sum ### + + if y_type.startswith('multilabel'): + sum_axis = 1 if average == 'samples' else 0 + + # calculate weighted counts + true_and_pred = y_true.multiply(y_pred) + tp_sum = count_nonzero(true_and_pred, axis=sum_axis, + sample_weight=sample_weight) + pred_sum = count_nonzero(y_pred, axis=sum_axis, + sample_weight=sample_weight) + true_sum = count_nonzero(y_true, axis=sum_axis, + sample_weight=sample_weight) + + elif average == 'samples': + raise ValueError("Sample-based precision, recall, fscore is " + "not meaningful outside multilabel " + "classification. See the accuracy_score instead.") + else: + lb = LabelEncoder() + lb.fit(labels) + y_true = lb.transform(y_true) + y_pred = lb.transform(y_pred) + labels = lb.classes_ + + # labels are now from 0 to len(labels) - 1 -> use bincount + tp = y_true == y_pred + tp_bins = y_true[tp] + if sample_weight is not None: + tp_bins_weights = np.asarray(sample_weight)[tp] + else: + tp_bins_weights = None + + if len(tp_bins): + tp_sum = bincount(tp_bins, weights=tp_bins_weights, + minlength=len(labels)) + else: + # Pathological case + true_sum = pred_sum = tp_sum = np.zeros(len(labels)) + if len(y_pred): + pred_sum = bincount(y_pred, weights=sample_weight, + minlength=len(labels)) + if len(y_true): + true_sum = bincount(y_true, weights=sample_weight, + minlength=len(labels)) + + ### Select labels to keep ### + + if y_type == 'binary' and average is not None and pos_label is not None: + if average != 'binary': + warnings.warn('From version 0.18, binary input will not be ' + 'handled specially when using averaged ' + 'precision/recall/F-score. ' + 'Please use average=\'binary\' to report only the ' + 'positive class performance.', DeprecationWarning) + if pos_label not in labels: + if len(labels) == 1: + # Only negative labels + return (0., 0., 0., 0) + else: + raise ValueError("pos_label=%r is not a valid label: %r" % + (pos_label, labels)) + pos_label_idx = labels == pos_label + tp_sum = tp_sum[pos_label_idx] + pred_sum = pred_sum[pos_label_idx] + true_sum = true_sum[pos_label_idx] + + elif average == 'micro': + tp_sum = np.array([tp_sum.sum()]) + pred_sum = np.array([pred_sum.sum()]) + true_sum = np.array([true_sum.sum()]) + + ### Finally, we have all our sufficient statistics. Divide! ### + + beta2 = beta ** 2 + with np.errstate(divide='ignore', invalid='ignore'): + # Divide, and on zero-division, set scores to 0 and warn: + + # Oddly, we may get an "invalid" rather than a "divide" error + # here. + precision = _prf_divide(tp_sum, pred_sum, + 'precision', 'predicted', average, warn_for) + recall = _prf_divide(tp_sum, true_sum, + 'recall', 'true', average, warn_for) + # Don't need to warn for F: either P or R warned, or tp == 0 where pos + # and true are nonzero, in which case, F is well-defined and zero + f_score = ((1 + beta2) * precision * recall / + (beta2 * precision + recall)) + f_score[tp_sum == 0] = 0.0 + + ## Average the results ## + + if average == 'weighted': + weights = true_sum + if weights.sum() == 0: + return 0, 0, 0, None + elif average == 'samples': + weights = sample_weight + else: + weights = None + + if average is not None: + assert average != 'binary' or len(precision) == 1 + precision = np.average(precision, weights=weights) + recall = np.average(recall, weights=weights) + f_score = np.average(f_score, weights=weights) + true_sum = None # return no support + elif label_order is not None: + indices = np.searchsorted(labels, label_order) + precision = precision[indices] + recall = recall[indices] + f_score = f_score[indices] + true_sum = true_sum[indices] + + return precision, recall, f_score, true_sum + + +def precision_score(y_true, y_pred, labels=None, pos_label=1, + average='binary', sample_weight=None): + """Compute the precision + + The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of + true positives and ``fp`` the number of false positives. The precision is + intuitively the ability of the classifier not to label as positive a sample + that is negative. + + The best value is 1 and the worst value is 0. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array + Integer array of labels. + + pos_label : str or int, 1 by default + The class to report if ``average='binary'``. Until version 0.18 it is + necessary to set ``pos_label=None`` if seeking to use another averaging + method over binary targets. + + average : string, [None, 'binary' (default), 'micro', 'macro', 'samples', \ + 'weighted'] + This parameter is required for multiclass/multilabel targets. + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + Note that if ``pos_label`` is given in binary classification with + `average != 'binary'`, only that positive class is reported. This + behavior is deprecated and will change in version 0.18. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + precision : float (if average is not None) or array of float, shape =\ + [n_unique_labels] + Precision of the positive class in binary classification or weighted + average of the precision of each class for the multiclass task. + + Examples + -------- + + >>> from sklearn.metrics import precision_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> precision_score(y_true, y_pred, average='macro') # doctest: +ELLIPSIS + 0.22... + >>> precision_score(y_true, y_pred, average='micro') # doctest: +ELLIPSIS + 0.33... + >>> precision_score(y_true, y_pred, average='weighted') + ... # doctest: +ELLIPSIS + 0.22... + >>> precision_score(y_true, y_pred, average=None) # doctest: +ELLIPSIS + array([ 0.66..., 0. , 0. ]) + + """ + p, _, _, _ = precision_recall_fscore_support(y_true, y_pred, + labels=labels, + pos_label=pos_label, + average=average, + warn_for=('precision',), + sample_weight=sample_weight) + return p + + +def recall_score(y_true, y_pred, labels=None, pos_label=1, average='binary', + sample_weight=None): + """Compute the recall + + The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of + true positives and ``fn`` the number of false negatives. The recall is + intuitively the ability of the classifier to find all the positive samples. + + The best value is 1 and the worst value is 0. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array + Integer array of labels. + + pos_label : str or int, 1 by default + The class to report if ``average='binary'``. Until version 0.18 it is + necessary to set ``pos_label=None`` if seeking to use another averaging + method over binary targets. + + average : string, [None, 'binary' (default), 'micro', 'macro', 'samples', \ + 'weighted'] + This parameter is required for multiclass/multilabel targets. + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + Note that if ``pos_label`` is given in binary classification with + `average != 'binary'`, only that positive class is reported. This + behavior is deprecated and will change in version 0.18. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + recall : float (if average is not None) or array of float, shape =\ + [n_unique_labels] + Recall of the positive class in binary classification or weighted + average of the recall of each class for the multiclass task. + + Examples + -------- + >>> from sklearn.metrics import recall_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> recall_score(y_true, y_pred, average='macro') # doctest: +ELLIPSIS + 0.33... + >>> recall_score(y_true, y_pred, average='micro') # doctest: +ELLIPSIS + 0.33... + >>> recall_score(y_true, y_pred, average='weighted') # doctest: +ELLIPSIS + 0.33... + >>> recall_score(y_true, y_pred, average=None) + array([ 1., 0., 0.]) + + + """ + _, r, _, _ = precision_recall_fscore_support(y_true, y_pred, + labels=labels, + pos_label=pos_label, + average=average, + warn_for=('recall',), + sample_weight=sample_weight) + return r + + +def classification_report(y_true, y_pred, labels=None, target_names=None, + sample_weight=None, digits=2): + """Build a text report showing the main classification metrics + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array, shape = [n_labels] + Optional list of label indices to include in the report. + + target_names : list of strings + Optional display names matching the labels (same order). + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + digits : int + Number of digits for formatting output floating point values + + Returns + ------- + report : string + Text summary of the precision, recall, F1 score for each class. + + Examples + -------- + >>> from sklearn.metrics import classification_report + >>> y_true = [0, 1, 2, 2, 2] + >>> y_pred = [0, 0, 2, 2, 1] + >>> target_names = ['class 0', 'class 1', 'class 2'] + >>> print(classification_report(y_true, y_pred, target_names=target_names)) + precision recall f1-score support + + class 0 0.50 1.00 0.67 1 + class 1 0.00 0.00 0.00 1 + class 2 1.00 0.67 0.80 3 + + avg / total 0.70 0.60 0.61 5 + + + """ + + if labels is None: + labels = unique_labels(y_true, y_pred) + else: + labels = np.asarray(labels) + + last_line_heading = 'avg / total' + + if target_names is None: + width = len(last_line_heading) + target_names = ['%s' % l for l in labels] + else: + width = max(len(cn) for cn in target_names) + width = max(width, len(last_line_heading), digits) + + headers = ["precision", "recall", "f1-score", "support"] + fmt = '%% %ds' % width # first column: class name + fmt += ' ' + fmt += ' '.join(['% 9s' for _ in headers]) + fmt += '\n' + + headers = [""] + headers + report = fmt % tuple(headers) + report += '\n' + + p, r, f1, s = precision_recall_fscore_support(y_true, y_pred, + labels=labels, + average=None, + sample_weight=sample_weight) + + for i, label in enumerate(labels): + values = [target_names[i]] + for v in (p[i], r[i], f1[i]): + values += ["{0:0.{1}f}".format(v, digits)] + values += ["{0}".format(s[i])] + report += fmt % tuple(values) + + report += '\n' + + # compute averages + values = [last_line_heading] + for v in (np.average(p, weights=s), + np.average(r, weights=s), + np.average(f1, weights=s)): + values += ["{0:0.{1}f}".format(v, digits)] + values += ['{0}'.format(np.sum(s))] + report += fmt % tuple(values) + return report + + +def hamming_loss(y_true, y_pred, classes=None): + """Compute the average Hamming loss. + + The Hamming loss is the fraction of labels that are incorrectly predicted. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + classes : array, shape = [n_labels], optional + Integer array of labels. + + Returns + ------- + loss : float or int, + Return the average Hamming loss between element of ``y_true`` and + ``y_pred``. + + See Also + -------- + accuracy_score, jaccard_similarity_score, zero_one_loss + + Notes + ----- + In multiclass classification, the Hamming loss correspond to the Hamming + distance between ``y_true`` and ``y_pred`` which is equivalent to the + subset ``zero_one_loss`` function. + + In multilabel classification, the Hamming loss is different from the + subset zero-one loss. The zero-one loss considers the entire set of labels + for a given sample incorrect if it does entirely match the true set of + labels. Hamming loss is more forgiving in that it penalizes the individual + labels. + + The Hamming loss is upperbounded by the subset zero-one loss. When + normalized over samples, the Hamming loss is always between 0 and 1. + + References + ---------- + .. [1] Grigorios Tsoumakas, Ioannis Katakis. Multi-Label Classification: + An Overview. International Journal of Data Warehousing & Mining, + 3(3), 1-13, July-September 2007. + + .. [2] `Wikipedia entry on the Hamming distance + `_ + + Examples + -------- + >>> from sklearn.metrics import hamming_loss + >>> y_pred = [1, 2, 3, 4] + >>> y_true = [2, 2, 3, 4] + >>> hamming_loss(y_true, y_pred) + 0.25 + + In the multilabel case with binary label indicators: + + >>> hamming_loss(np.array([[0, 1], [1, 1]]), np.zeros((2, 2))) + 0.75 + """ + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + + if classes is None: + classes = unique_labels(y_true, y_pred) + else: + classes = np.asarray(classes) + + if y_type.startswith('multilabel'): + n_differences = count_nonzero(y_true - y_pred) + return (n_differences / (y_true.shape[0] * len(classes))) + + elif y_type in ["binary", "multiclass"]: + return sp_hamming(y_true, y_pred) + else: + raise ValueError("{0} is not supported".format(y_type)) + + +def log_loss(y_true, y_pred, eps=1e-15, normalize=True, sample_weight=None): + """Log loss, aka logistic loss or cross-entropy loss. + + This is the loss function used in (multinomial) logistic regression + and extensions of it such as neural networks, defined as the negative + log-likelihood of the true labels given a probabilistic classifier's + predictions. For a single sample with true label yt in {0,1} and + estimated probability yp that yt = 1, the log loss is + + -log P(yt|yp) = -(yt log(yp) + (1 - yt) log(1 - yp)) + + Parameters + ---------- + y_true : array-like or label indicator matrix + Ground truth (correct) labels for n_samples samples. + + y_pred : array-like of float, shape = (n_samples, n_classes) + Predicted probabilities, as returned by a classifier's + predict_proba method. + + eps : float + Log loss is undefined for p=0 or p=1, so probabilities are + clipped to max(eps, min(1 - eps, p)). + + normalize : bool, optional (default=True) + If true, return the mean loss per sample. + Otherwise, return the sum of the per-sample losses. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + loss : float + + Examples + -------- + >>> log_loss(["spam", "ham", "ham", "spam"], # doctest: +ELLIPSIS + ... [[.1, .9], [.9, .1], [.8, .2], [.35, .65]]) + 0.21616... + + References + ---------- + C.M. Bishop (2006). Pattern Recognition and Machine Learning. Springer, + p. 209. + + Notes + ----- + The logarithm used is the natural logarithm (base-e). + """ + lb = LabelBinarizer() + T = lb.fit_transform(y_true) + if T.shape[1] == 1: + T = np.append(1 - T, T, axis=1) + + # Clipping + Y = np.clip(y_pred, eps, 1 - eps) + + # This happens in cases when elements in y_pred have type "str". + if not isinstance(Y, np.ndarray): + raise ValueError("y_pred should be an array of floats.") + + # If y_pred is of single dimension, assume y_true to be binary + # and then check. + if Y.ndim == 1: + Y = Y[:, np.newaxis] + if Y.shape[1] == 1: + Y = np.append(1 - Y, Y, axis=1) + + # Check if dimensions are consistent. + check_consistent_length(T, Y) + T = check_array(T) + Y = check_array(Y) + if T.shape[1] != Y.shape[1]: + raise ValueError("y_true and y_pred have different number of classes " + "%d, %d" % (T.shape[1], Y.shape[1])) + + # Renormalize + Y /= Y.sum(axis=1)[:, np.newaxis] + loss = -(T * np.log(Y)).sum(axis=1) + + return _weighted_sum(loss, sample_weight, normalize) + + +def hinge_loss(y_true, pred_decision, labels=None, sample_weight=None): + """Average hinge loss (non-regularized) + + In binary class case, assuming labels in y_true are encoded with +1 and -1, + when a prediction mistake is made, ``margin = y_true * pred_decision`` is + always negative (since the signs disagree), implying ``1 - margin`` is + always greater than 1. The cumulated hinge loss is therefore an upper + bound of the number of mistakes made by the classifier. + + In multiclass case, the function expects that either all the labels are + included in y_true or an optional labels argument is provided which + contains all the labels. The multilabel margin is calculated according + to Crammer-Singer's method. As in the binary case, the cumulated hinge loss + is an upper bound of the number of mistakes made by the classifier. + + Parameters + ---------- + y_true : array, shape = [n_samples] + True target, consisting of integers of two values. The positive label + must be greater than the negative label. + + pred_decision : array, shape = [n_samples] or [n_samples, n_classes] + Predicted decisions, as output by decision_function (floats). + + labels : array, optional, default None + Contains all the labels for the problem. Used in multiclass hinge loss. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + loss : float + + References + ---------- + .. [1] `Wikipedia entry on the Hinge loss + `_ + + .. [2] Koby Crammer, Yoram Singer. On the Algorithmic + Implementation of Multiclass Kernel-based Vector + Machines. Journal of Machine Learning Research 2, + (2001), 265-292 + + .. [3] 'L1 AND L2 Regularization for Multiclass Hinge Loss Models + by Robert C. Moore, John DeNero. + ' + + Examples + -------- + >>> from sklearn import svm + >>> from sklearn.metrics import hinge_loss + >>> X = [[0], [1]] + >>> y = [-1, 1] + >>> est = svm.LinearSVC(random_state=0) + >>> est.fit(X, y) + LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True, + intercept_scaling=1, loss='squared_hinge', max_iter=1000, + multi_class='ovr', penalty='l2', random_state=0, tol=0.0001, + verbose=0) + >>> pred_decision = est.decision_function([[-2], [3], [0.5]]) + >>> pred_decision # doctest: +ELLIPSIS + array([-2.18..., 2.36..., 0.09...]) + >>> hinge_loss([-1, 1, 1], pred_decision) # doctest: +ELLIPSIS + 0.30... + + In the multiclass case: + >>> X = np.array([[0], [1], [2], [3]]) + >>> Y = np.array([0, 1, 2, 3]) + >>> labels = np.array([0, 1, 2, 3]) + >>> est = svm.LinearSVC() + >>> est.fit(X, Y) + LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True, + intercept_scaling=1, loss='squared_hinge', max_iter=1000, + multi_class='ovr', penalty='l2', random_state=None, tol=0.0001, + verbose=0) + >>> pred_decision = est.decision_function([[-1], [2], [3]]) + >>> y_true = [0, 2, 3] + >>> hinge_loss(y_true, pred_decision, labels) #doctest: +ELLIPSIS + 0.56... + """ + check_consistent_length(y_true, pred_decision, sample_weight) + pred_decision = check_array(pred_decision, ensure_2d=False) + y_true = column_or_1d(y_true) + y_true_unique = np.unique(y_true) + if y_true_unique.size > 2: + if (labels is None and pred_decision.ndim > 1 and + (np.size(y_true_unique) != pred_decision.shape[1])): + raise ValueError("Please include all labels in y_true " + "or pass labels as third argument") + if labels is None: + labels = y_true_unique + le = LabelEncoder() + le.fit(labels) + y_true = le.transform(y_true) + mask = np.ones_like(pred_decision, dtype=bool) + mask[np.arange(y_true.shape[0]), y_true] = False + margin = pred_decision[~mask] + margin -= np.max(pred_decision[mask].reshape(y_true.shape[0], -1), + axis=1) + + else: + # Handles binary class case + # this code assumes that positive and negative labels + # are encoded as +1 and -1 respectively + pred_decision = column_or_1d(pred_decision) + pred_decision = np.ravel(pred_decision) + + lbin = LabelBinarizer(neg_label=-1) + y_true = lbin.fit_transform(y_true)[:, 0] + + try: + margin = y_true * pred_decision + except TypeError: + raise TypeError("pred_decision should be an array of floats.") + + losses = 1 - margin + # The hinge_loss doesn't penalize good enough predictions. + losses[losses <= 0] = 0 + return np.average(losses, weights=sample_weight) + + +def _check_binary_probabilistic_predictions(y_true, y_prob): + """Check that y_true is binary and y_prob contains valid probabilities""" + check_consistent_length(y_true, y_prob) + + labels = np.unique(y_true) + + if len(labels) != 2: + raise ValueError("Only binary classification is supported. " + "Provided labels %s." % labels) + + if y_prob.max() > 1: + raise ValueError("y_prob contains values greater than 1.") + + if y_prob.min() < 0: + raise ValueError("y_prob contains values less than 0.") + + return label_binarize(y_true, labels)[:, 0] + + +def brier_score_loss(y_true, y_prob, sample_weight=None, pos_label=None): + """Compute the Brier score. + + The smaller the Brier score, the better, hence the naming with "loss". + + Across all items in a set N predictions, the Brier score measures the + mean squared difference between (1) the predicted probability assigned + to the possible outcomes for item i, and (2) the actual outcome. + Therefore, the lower the Brier score is for a set of predictions, the + better the predictions are calibrated. Note that the Brier score always + takes on a value between zero and one, since this is the largest + possible difference between a predicted probability (which must be + between zero and one) and the actual outcome (which can take on values + of only 0 and 1). + + The Brier score is appropriate for binary and categorical outcomes that + can be structured as true or false, but is inappropriate for ordinal + variables which can take on three or more values (this is because the + Brier score assumes that all possible outcomes are equivalently + "distant" from one another). Which label is considered to be the positive + label is controlled via the parameter pos_label, which defaults to 1. + + + Parameters + ---------- + y_true : array, shape (n_samples,) + True targets. + + y_prob : array, shape (n_samples,) + Probabilities of the positive class. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + pos_label : int (default: None) + Label of the positive class. If None, the maximum label is used as + positive class + + Returns + ------- + score : float + Brier score + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import brier_score_loss + >>> y_true = np.array([0, 1, 1, 0]) + >>> y_true_categorical = np.array(["spam", "ham", "ham", "spam"]) + >>> y_prob = np.array([0.1, 0.9, 0.8, 0.3]) + >>> brier_score_loss(y_true, y_prob) # doctest: +ELLIPSIS + 0.037... + >>> brier_score_loss(y_true, 1-y_prob, pos_label=0) # doctest: +ELLIPSIS + 0.037... + >>> brier_score_loss(y_true_categorical, y_prob, \ + pos_label="ham") # doctest: +ELLIPSIS + 0.037... + >>> brier_score_loss(y_true, np.array(y_prob) > 0.5) + 0.0 + + References + ---------- + http://en.wikipedia.org/wiki/Brier_score + """ + y_true = column_or_1d(y_true) + y_prob = column_or_1d(y_prob) + if pos_label is None: + pos_label = y_true.max() + y_true = np.array(y_true == pos_label, int) + y_true = _check_binary_probabilistic_predictions(y_true, y_prob) + return np.average((y_true - y_prob) ** 2, weights=sample_weight) diff --git a/sklearn/metrics/cluster/__init__.py b/sklearn/metrics/cluster/__init__.py index ad8fc36c13686..8a58dc2acb669 100644 --- a/sklearn/metrics/cluster/__init__.py +++ b/sklearn/metrics/cluster/__init__.py @@ -18,3 +18,11 @@ from .supervised import entropy from .unsupervised import silhouette_samples from .unsupervised import silhouette_score +from .bicluster import consensus_score + +__all__ = ["adjusted_mutual_info_score", "normalized_mutual_info_score", + "adjusted_rand_score", "completeness_score", "contingency_matrix", + "expected_mutual_information", "homogeneity_completeness_v_measure", + "homogeneity_score", "mutual_info_score", "v_measure_score", + "entropy", "silhouette_samples", "silhouette_score", + "consensus_score"] diff --git a/sklearn/metrics/cluster/bicluster.py b/sklearn/metrics/cluster/bicluster.py new file mode 100644 index 0000000000000..0ec2af9e6b2fe --- /dev/null +++ b/sklearn/metrics/cluster/bicluster.py @@ -0,0 +1,84 @@ +from __future__ import division + +import numpy as np + +from sklearn.utils.linear_assignment_ import linear_assignment +from sklearn.utils.validation import check_consistent_length, check_array + +__all__ = ["consensus_score"] + + +def _check_rows_and_columns(a, b): + """Unpacks the row and column arrays and checks their shape.""" + check_consistent_length(*a) + check_consistent_length(*b) + checks = lambda x: check_array(x, ensure_2d=False) + a_rows, a_cols = map(checks, a) + b_rows, b_cols = map(checks, b) + return a_rows, a_cols, b_rows, b_cols + + +def _jaccard(a_rows, a_cols, b_rows, b_cols): + """Jaccard coefficient on the elements of the two biclusters.""" + intersection = ((a_rows * b_rows).sum() * + (a_cols * b_cols).sum()) + + a_size = a_rows.sum() * a_cols.sum() + b_size = b_rows.sum() * b_cols.sum() + + return intersection / (a_size + b_size - intersection) + + +def _pairwise_similarity(a, b, similarity): + """Computes pairwise similarity matrix. + + result[i, j] is the Jaccard coefficient of a's bicluster i and b's + bicluster j. + + """ + a_rows, a_cols, b_rows, b_cols = _check_rows_and_columns(a, b) + n_a = a_rows.shape[0] + n_b = b_rows.shape[0] + result = np.array(list(list(similarity(a_rows[i], a_cols[i], + b_rows[j], b_cols[j]) + for j in range(n_b)) + for i in range(n_a))) + return result + + +def consensus_score(a, b, similarity="jaccard"): + """The similarity of two sets of biclusters. + + Similarity between individual biclusters is computed. Then the + best matching between sets is found using the Hungarian algorithm. + The final score is the sum of similarities divided by the size of + the larger set. + + Parameters + ---------- + a : (rows, columns) + Tuple of row and column indicators for a set of biclusters. + + b : (rows, columns) + Another set of biclusters like ``a``. + + similarity : string or function, optional, default: "jaccard" + May be the string "jaccard" to use the Jaccard coefficient, or + any function that takes four arguments, each of which is a 1d + indicator vector: (a_rows, a_columns, b_rows, b_columns). + + References + ---------- + + * Hochreiter, Bodenhofer, et. al., 2010. `FABIA: factor analysis + for bicluster acquisition + `__. + + """ + if similarity == "jaccard": + similarity = _jaccard + matrix = _pairwise_similarity(a, b, similarity) + indices = linear_assignment(1. - matrix) + n_a = len(a[0]) + n_b = len(b[0]) + return matrix[indices[:, 0], indices[:, 1]].sum() / max(n_a, n_b) diff --git a/sklearn/utils/sparsefuncs.c b/sklearn/metrics/cluster/expected_mutual_info_fast.c similarity index 51% rename from sklearn/utils/sparsefuncs.c rename to sklearn/metrics/cluster/expected_mutual_info_fast.c index 43d538a4afe78..6ea6e4c32bf50 100644 --- a/sklearn/utils/sparsefuncs.c +++ b/sklearn/metrics/cluster/expected_mutual_info_fast.c @@ -1,16 +1,16 @@ -/* Generated by Cython 0.15.1 on Mon May 7 11:30:13 2012 */ +/* Generated by Cython 0.17.4 on Sun Jan 13 14:07:22 2013 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. #else - #include /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -22,36 +22,47 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - -#if PY_VERSION_HEX < 0x02040000 - #define METH_COEXIST 0 - #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) - #define PyDict_Contains(d,o) PySequence_Contains(d,o) +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 #endif - #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -59,7 +70,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -73,7 +83,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -83,24 +92,44 @@ #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -108,7 +137,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -127,7 +155,6 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -135,9 +162,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -154,11 +179,9 @@ #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - #if PY_VERSION_HEX < 0x03020000 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong @@ -167,16 +190,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -195,11 +208,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -209,7 +220,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -218,6 +228,15 @@ #define __Pyx_DOCSTR(n) (n) #endif + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" @@ -230,13 +249,13 @@ #define _USE_MATH_DEFINES #endif #include -#define __PYX_HAVE__sklearn__utils__sparsefuncs -#define __PYX_HAVE_API__sklearn__utils__sparsefuncs +#define __PYX_HAVE__sklearn__metrics__cluster__expected_mutual_info_fast +#define __PYX_HAVE_API__sklearn__metrics__cluster__expected_mutual_info_fast +#include "math.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" -#include "math.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -267,7 +286,7 @@ # else # define CYTHON_UNUSED # endif -# elif defined(__ICC) || defined(__INTEL_COMPILER) +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED @@ -291,8 +310,12 @@ static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) - +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #ifdef __GNUC__ /* Test for GCC > 2.95 */ @@ -317,7 +340,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -327,7 +349,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -335,18 +356,54 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { - "sparsefuncs.pyx", + "expected_mutual_info_fast.pyx", "numpy.pxd", + "type.pxd", }; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; -/* "numpy.pxd":719 + +/* "numpy.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -355,7 +412,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "numpy.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -364,7 +421,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "numpy.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -373,7 +430,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "numpy.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -382,7 +439,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "numpy.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -391,7 +448,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "numpy.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -400,7 +457,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "numpy.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -409,7 +466,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "numpy.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -418,7 +475,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "numpy.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -427,7 +484,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "numpy.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -436,7 +493,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "numpy.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -445,7 +502,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "numpy.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -454,7 +511,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "numpy.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -463,7 +520,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "numpy.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -472,7 +529,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "numpy.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -481,7 +538,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "numpy.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -490,7 +547,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "numpy.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -499,7 +556,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "numpy.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -508,7 +565,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "numpy.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -517,7 +574,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "numpy.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -526,7 +583,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "numpy.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -534,16 +591,6 @@ typedef npy_double __pyx_t_5numpy_double_t; * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; - -/* "sklearn/utils/sparsefuncs.pyx":16 - * double sqrt(double f) - * - * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< - * - * @cython.boundscheck(False) - */ -typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE; - #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -564,9 +611,10 @@ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE; typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ -/* "numpy.pxd":758 +/* "numpy.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -575,7 +623,7 @@ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "numpy.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -584,7 +632,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "numpy.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -593,7 +641,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "numpy.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -601,12 +649,9 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; - - #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -619,8 +664,21 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -631,7 +689,7 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -642,176 +700,90 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} - - -#define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_List_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) - -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ -#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Tuple_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); -#define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { - PyObject *r; - if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) { - r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - } - else if (PyTuple_CheckExact(o) && ((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - } - else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0))) { - r = PySequence_GetItem(o, i); - } - else { - r = __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); - } - return r; -} +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ -/* Run-time type information about structs used with buffers */ -struct __Pyx_StructField_; - -typedef struct { - const char* name; /* for error messages only */ - struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ -} __Pyx_TypeInfo; - -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; - -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; - - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); -#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) -#define __Pyx_SetItemInt(o, i, v, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_SetItemInt_Fast(o, i, v) : \ - __Pyx_SetItemInt_Generic(o, to_py_func(i), v)) - -static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { - int r; - if (!j) return -1; - r = PyObject_SetItem(o, j, v); - Py_DECREF(j); - return r; -} +static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v) { - if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) { - Py_INCREF(v); - Py_DECREF(PyList_GET_ITEM(o, i)); - PyList_SET_ITEM(o, i, v); - return 1; - } - else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && (likely(i >= 0))) - return PySequence_SetItem(o, i, v); - else { - PyObject *j = PyInt_FromSsize_t(i); - return __Pyx_SetItemInt_Generic(o, j, v); +#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; } + return PyList_Append(list, x); } +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif -static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ - +#define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ - -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ - -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ - -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact); /*proto*/ - static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + #if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); -static void __Pyx_ReleaseBuffer(Py_buffer *view); + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); #else -#define __Pyx_GetBuffer PyObject_GetBuffer -#define __Pyx_ReleaseBuffer PyBuffer_Release + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release #endif -Py_ssize_t __Pyx_zeros[] = {0}; -Py_ssize_t __Pyx_minusones[] = {-1}; + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name); + #if CYTHON_CCOMPLEX #ifdef __cplusplus #define __Pyx_CREAL(z) ((z).real()) @@ -824,7 +796,6 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - #if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) @@ -945,15 +916,42 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject * static int __Pyx_check_binary_version(void); -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + +/* Module declarations from 'libc.math' */ + /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ @@ -962,6 +960,11 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -972,2415 +975,1562 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ - -/* Module declarations from 'cython.cython.view' */ /* Module declarations from 'cython' */ -/* Module declarations from 'sklearn.utils.sparsefuncs' */ -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE), 'R' }; -static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), 'I' }; -#define __Pyx_MODULE_NAME "sklearn.utils.sparsefuncs" -int __pyx_module_is_main_sklearn__utils__sparsefuncs = 0; +/* Module declarations from 'sklearn.utils.lgamma' */ +static double (*__pyx_f_7sklearn_5utils_6lgamma_lgamma)(double); /*proto*/ -/* Implementation of 'sklearn.utils.sparsefuncs' */ -static PyObject *__pyx_builtin_xrange; -static PyObject *__pyx_builtin_TypeError; -static PyObject *__pyx_builtin_ValueError; +/* Module declarations from 'sklearn.metrics.cluster.expected_mutual_info_fast' */ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t = { "int32_t", NULL, sizeof(__pyx_t_5numpy_int32_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_int32_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_int32_t), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; +#define __Pyx_MODULE_NAME "sklearn.metrics.cluster.expected_mutual_info_fast" +int __pyx_module_is_main_sklearn__metrics__cluster__expected_mutual_info_fast = 0; + +/* Implementation of 'sklearn.metrics.cluster.expected_mutual_info_fast' */ static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; -static char __pyx_k_1[] = "csr_mean_variance_axis0"; -static char __pyx_k_2[] = "csc_mean_variance_axis0"; -static char __pyx_k_3[] = "Unsupported matrix type. Expected a CSR or CSC sparse matrix."; -static char __pyx_k_5[] = "ndarray is not C contiguous"; -static char __pyx_k_7[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_9[] = "Non-native byte order not supported"; -static char __pyx_k_11[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_12[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_15[] = "Format string allocated too short."; -static char __pyx_k_17[] = "scipy.sparse"; -static char __pyx_k_18[] = "*"; -static char __pyx_k_19[] = "sklearn.utils.sparsefuncs"; -static char __pyx_k_20[] = "inplace_csr_row_normalize_l1"; -static char __pyx_k_21[] = "inplace_csr_row_normalize_l2"; -static char __pyx_k_22[] = "inplace_csr_column_scale"; -static char __pyx_k_23[] = "inplace_csc_column_scale"; +static PyObject *__pyx_pf_7sklearn_7metrics_7cluster_25expected_mutual_info_fast_expected_mutual_information(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_contingency, int __pyx_v_n_samples); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static char __pyx_k_1[] = "ndarray is not C contiguous"; +static char __pyx_k_3[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_5[] = "Non-native byte order not supported"; +static char __pyx_k_7[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_8[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_11[] = "Format string allocated too short."; +static char __pyx_k_13[] = "scipy.special"; +static char __pyx_k_16[] = "expected_mutual_information"; +static char __pyx_k_17[] = "/Users/vene/code/scikit-learn/sklearn/metrics/cluster/expected_mutual_info_fast.pyx"; +static char __pyx_k_18[] = "sklearn.metrics.cluster.expected_mutual_info_fast"; static char __pyx_k__B[] = "B"; +static char __pyx_k__C[] = "C"; static char __pyx_k__H[] = "H"; static char __pyx_k__I[] = "I"; static char __pyx_k__L[] = "L"; +static char __pyx_k__N[] = "N"; static char __pyx_k__O[] = "O"; static char __pyx_k__Q[] = "Q"; -static char __pyx_k__X[] = "X"; +static char __pyx_k__R[] = "R"; +static char __pyx_k__T[] = "T"; +static char __pyx_k__a[] = "a"; static char __pyx_k__b[] = "b"; static char __pyx_k__d[] = "d"; static char __pyx_k__f[] = "f"; static char __pyx_k__g[] = "g"; static char __pyx_k__h[] = "h"; static char __pyx_k__i[] = "i"; +static char __pyx_k__j[] = "j"; static char __pyx_k__l[] = "l"; static char __pyx_k__q[] = "q"; +static char __pyx_k__v[] = "v"; +static char __pyx_k__w[] = "w"; static char __pyx_k__Zd[] = "Zd"; static char __pyx_k__Zf[] = "Zf"; static char __pyx_k__Zg[] = "Zg"; static char __pyx_k__np[] = "np"; -static char __pyx_k__sp[] = "sp"; +static char __pyx_k__emi[] = "emi"; +static char __pyx_k__end[] = "end"; +static char __pyx_k__gln[] = "gln"; +static char __pyx_k__int[] = "int"; +static char __pyx_k__log[] = "log"; +static char __pyx_k__max[] = "max"; +static char __pyx_k__nij[] = "nij"; +static char __pyx_k__sum[] = "sum"; static char __pyx_k__axis[] = "axis"; -static char __pyx_k__data[] = "data"; -static char __pyx_k__mean[] = "mean"; +static char __pyx_k__nijs[] = "nijs"; +static char __pyx_k__array[] = "array"; +static char __pyx_k__dtype[] = "dtype"; +static char __pyx_k__float[] = "float"; +static char __pyx_k__gln_N[] = "gln_N"; +static char __pyx_k__gln_a[] = "gln_a"; +static char __pyx_k__gln_b[] = "gln_b"; +static char __pyx_k__int32[] = "int32"; static char __pyx_k__numpy[] = "numpy"; +static char __pyx_k__outer[] = "outer"; static char __pyx_k__range[] = "range"; -static char __pyx_k__scale[] = "scale"; static char __pyx_k__shape[] = "shape"; -static char __pyx_k__indptr[] = "indptr"; -static char __pyx_k__xrange[] = "xrange"; -static char __pyx_k__asarray[] = "asarray"; -static char __pyx_k__indices[] = "indices"; +static char __pyx_k__start[] = "start"; +static char __pyx_k__term1[] = "term1"; +static char __pyx_k__term2[] = "term2"; +static char __pyx_k__term3[] = "term3"; +static char __pyx_k__arange[] = "arange"; +static char __pyx_k__astype[] = "astype"; +static char __pyx_k__gln_Na[] = "gln_Na"; +static char __pyx_k__gln_Nb[] = "gln_Nb"; +static char __pyx_k__resize[] = "resize"; +static char __pyx_k__gammaln[] = "gammaln"; +static char __pyx_k__gln_nij[] = "gln_nij"; +static char __pyx_k__maximum[] = "maximum"; +static char __pyx_k__minimum[] = "minimum"; static char __pyx_k____main__[] = "__main__"; static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__TypeError[] = "TypeError"; +static char __pyx_k__log_Nnij[] = "log_Nnij"; +static char __pyx_k__n_samples[] = "n_samples"; static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__csc_matrix[] = "csc_matrix"; -static char __pyx_k__csr_matrix[] = "csr_matrix"; -static char __pyx_k__zeros_like[] = "zeros_like"; +static char __pyx_k__contingency[] = "contingency"; static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k__mean_variance_axis0[] = "mean_variance_axis0"; -static PyObject *__pyx_n_s_1; +static char __pyx_k__log_ab_outer[] = "log_ab_outer"; +static PyObject *__pyx_kp_u_1; static PyObject *__pyx_kp_u_11; -static PyObject *__pyx_kp_u_12; -static PyObject *__pyx_kp_u_15; -static PyObject *__pyx_n_s_17; +static PyObject *__pyx_n_s_13; +static PyObject *__pyx_n_s_16; +static PyObject *__pyx_kp_s_17; static PyObject *__pyx_n_s_18; -static PyObject *__pyx_n_s_19; -static PyObject *__pyx_n_s_2; -static PyObject *__pyx_n_s_20; -static PyObject *__pyx_n_s_21; -static PyObject *__pyx_n_s_22; -static PyObject *__pyx_n_s_23; -static PyObject *__pyx_kp_s_3; +static PyObject *__pyx_kp_u_3; static PyObject *__pyx_kp_u_5; static PyObject *__pyx_kp_u_7; -static PyObject *__pyx_kp_u_9; +static PyObject *__pyx_kp_u_8; +static PyObject *__pyx_n_s__C; +static PyObject *__pyx_n_s__N; +static PyObject *__pyx_n_s__R; static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__TypeError; +static PyObject *__pyx_n_s__T; static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s__X; static PyObject *__pyx_n_s____main__; static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__asarray; +static PyObject *__pyx_n_s__a; +static PyObject *__pyx_n_s__arange; +static PyObject *__pyx_n_s__array; +static PyObject *__pyx_n_s__astype; static PyObject *__pyx_n_s__axis; -static PyObject *__pyx_n_s__csc_matrix; -static PyObject *__pyx_n_s__csr_matrix; -static PyObject *__pyx_n_s__data; -static PyObject *__pyx_n_s__indices; -static PyObject *__pyx_n_s__indptr; -static PyObject *__pyx_n_s__mean; -static PyObject *__pyx_n_s__mean_variance_axis0; +static PyObject *__pyx_n_s__b; +static PyObject *__pyx_n_s__contingency; +static PyObject *__pyx_n_s__dtype; +static PyObject *__pyx_n_s__emi; +static PyObject *__pyx_n_s__end; +static PyObject *__pyx_n_s__float; +static PyObject *__pyx_n_s__gammaln; +static PyObject *__pyx_n_s__gln; +static PyObject *__pyx_n_s__gln_N; +static PyObject *__pyx_n_s__gln_Na; +static PyObject *__pyx_n_s__gln_Nb; +static PyObject *__pyx_n_s__gln_a; +static PyObject *__pyx_n_s__gln_b; +static PyObject *__pyx_n_s__gln_nij; +static PyObject *__pyx_n_s__i; +static PyObject *__pyx_n_s__int; +static PyObject *__pyx_n_s__int32; +static PyObject *__pyx_n_s__j; +static PyObject *__pyx_n_s__log; +static PyObject *__pyx_n_s__log_Nnij; +static PyObject *__pyx_n_s__log_ab_outer; +static PyObject *__pyx_n_s__max; +static PyObject *__pyx_n_s__maximum; +static PyObject *__pyx_n_s__minimum; +static PyObject *__pyx_n_s__n_samples; +static PyObject *__pyx_n_s__nij; +static PyObject *__pyx_n_s__nijs; static PyObject *__pyx_n_s__np; static PyObject *__pyx_n_s__numpy; +static PyObject *__pyx_n_s__outer; static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__scale; +static PyObject *__pyx_n_s__resize; static PyObject *__pyx_n_s__shape; -static PyObject *__pyx_n_s__sp; -static PyObject *__pyx_n_s__xrange; -static PyObject *__pyx_n_s__zeros_like; +static PyObject *__pyx_n_s__start; +static PyObject *__pyx_n_s__sum; +static PyObject *__pyx_n_s__term1; +static PyObject *__pyx_n_s__term2; +static PyObject *__pyx_n_s__term3; +static PyObject *__pyx_n_s__v; +static PyObject *__pyx_n_s__w; static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; -static PyObject *__pyx_int_2; static PyObject *__pyx_int_15; +static PyObject *__pyx_k_tuple_2; static PyObject *__pyx_k_tuple_4; static PyObject *__pyx_k_tuple_6; -static PyObject *__pyx_k_tuple_8; +static PyObject *__pyx_k_tuple_9; static PyObject *__pyx_k_tuple_10; -static PyObject *__pyx_k_tuple_13; +static PyObject *__pyx_k_tuple_12; static PyObject *__pyx_k_tuple_14; -static PyObject *__pyx_k_tuple_16; +static PyObject *__pyx_k_codeobj_15; + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7metrics_7cluster_25expected_mutual_info_fast_1expected_mutual_information(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7metrics_7cluster_25expected_mutual_info_fast_expected_mutual_information[] = "Calculate the expected mutual information for two labelings."; +static PyMethodDef __pyx_mdef_7sklearn_7metrics_7cluster_25expected_mutual_info_fast_1expected_mutual_information = {__Pyx_NAMESTR("expected_mutual_information"), (PyCFunction)__pyx_pw_7sklearn_7metrics_7cluster_25expected_mutual_info_fast_1expected_mutual_information, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7metrics_7cluster_25expected_mutual_info_fast_expected_mutual_information)}; +static PyObject *__pyx_pw_7sklearn_7metrics_7cluster_25expected_mutual_info_fast_1expected_mutual_information(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_contingency = 0; + int __pyx_v_n_samples; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("expected_mutual_information (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__contingency,&__pyx_n_s__n_samples,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__contingency)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_samples)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("expected_mutual_information", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "expected_mutual_information") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_contingency = values[0]; + __pyx_v_n_samples = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_n_samples == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("expected_mutual_information", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.metrics.cluster.expected_mutual_info_fast.expected_mutual_information", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_7metrics_7cluster_25expected_mutual_info_fast_expected_mutual_information(__pyx_self, __pyx_v_contingency, __pyx_v_n_samples); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} -/* "sklearn/utils/sparsefuncs.pyx":21 +/* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":21 + * @cython.boundscheck(False) * @cython.wraparound(False) - * @cython.cdivision(True) - * def csr_mean_variance_axis0(X): # <<<<<<<<<<<<<< - * """Compute mean and variance along axis 0 on a CSR matrix - * - */ - -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_csr_mean_variance_axis0(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ -static char __pyx_doc_7sklearn_5utils_11sparsefuncs_csr_mean_variance_axis0[] = "Compute mean and variance along axis 0 on a CSR matrix\n\n Parameters\n ----------\n X: CSR sparse matrix, shape (n_samples, n_features)\n Input data.\n\n Returns\n -------\n\n means: float array with shape (n_features,)\n Feature-wise means\n\n variances: float array with shape (n_features,)\n Feature-wise variances\n\n "; -static PyMethodDef __pyx_mdef_7sklearn_5utils_11sparsefuncs_csr_mean_variance_axis0 = {__Pyx_NAMESTR("csr_mean_variance_axis0"), (PyCFunction)__pyx_pf_7sklearn_5utils_11sparsefuncs_csr_mean_variance_axis0, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_11sparsefuncs_csr_mean_variance_axis0)}; -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_csr_mean_variance_axis0(PyObject *__pyx_self, PyObject *__pyx_v_X) { - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - PyArrayObject *__pyx_v_X_data = 0; - PyArrayObject *__pyx_v_X_indices = 0; - PyArrayObject *__pyx_v_X_indptr = 0; - unsigned int __pyx_v_i; - unsigned int __pyx_v_j; - unsigned int __pyx_v_ind; - double __pyx_v_diff; - PyArrayObject *__pyx_v_means = 0; - PyArrayObject *__pyx_v_variances = 0; - PyObject *__pyx_v_counts = NULL; - PyObject *__pyx_v_nz = NULL; - Py_buffer __pyx_bstruct_means; - Py_ssize_t __pyx_bstride_0_means = 0; - Py_ssize_t __pyx_bshape_0_means = 0; - Py_buffer __pyx_bstruct_variances; - Py_ssize_t __pyx_bstride_0_variances = 0; - Py_ssize_t __pyx_bshape_0_variances = 0; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; + * def expected_mutual_information(contingency, int n_samples): # <<<<<<<<<<<<<< + * """Calculate the expected mutual information for two labelings.""" + * cdef int R, C + */ + +static PyObject *__pyx_pf_7sklearn_7metrics_7cluster_25expected_mutual_info_fast_expected_mutual_information(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_contingency, int __pyx_v_n_samples) { + int __pyx_v_R; + int __pyx_v_C; + float __pyx_v_N; + float __pyx_v_gln_N; + float __pyx_v_emi; + float __pyx_v_term2; + float __pyx_v_term3; + float __pyx_v_gln; + PyArrayObject *__pyx_v_gln_a = 0; + PyArrayObject *__pyx_v_gln_b = 0; + PyArrayObject *__pyx_v_gln_Na = 0; + PyArrayObject *__pyx_v_gln_Nb = 0; + PyArrayObject *__pyx_v_gln_nij = 0; + PyArrayObject *__pyx_v_log_Nnij = 0; + PyArrayObject *__pyx_v_nijs = 0; + PyArrayObject *__pyx_v_term1 = 0; + PyArrayObject *__pyx_v_log_ab_outer = 0; + PyArrayObject *__pyx_v_a = 0; + PyArrayObject *__pyx_v_b = 0; + PyObject *__pyx_v_start = NULL; + PyObject *__pyx_v_end = NULL; + Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_j; + Py_ssize_t __pyx_v_nij; + PyObject *__pyx_v_v = NULL; + PyObject *__pyx_v_w = NULL; + __Pyx_LocalBuf_ND __pyx_pybuffernd_a; + __Pyx_Buffer __pyx_pybuffer_a; + __Pyx_LocalBuf_ND __pyx_pybuffernd_b; + __Pyx_Buffer __pyx_pybuffer_b; + __Pyx_LocalBuf_ND __pyx_pybuffernd_gln_Na; + __Pyx_Buffer __pyx_pybuffer_gln_Na; + __Pyx_LocalBuf_ND __pyx_pybuffernd_gln_Nb; + __Pyx_Buffer __pyx_pybuffer_gln_Nb; + __Pyx_LocalBuf_ND __pyx_pybuffernd_gln_a; + __Pyx_Buffer __pyx_pybuffer_gln_a; + __Pyx_LocalBuf_ND __pyx_pybuffernd_gln_b; + __Pyx_Buffer __pyx_pybuffer_gln_b; + __Pyx_LocalBuf_ND __pyx_pybuffernd_gln_nij; + __Pyx_Buffer __pyx_pybuffer_gln_nij; + __Pyx_LocalBuf_ND __pyx_pybuffernd_log_Nnij; + __Pyx_Buffer __pyx_pybuffer_log_Nnij; + __Pyx_LocalBuf_ND __pyx_pybuffernd_log_ab_outer; + __Pyx_Buffer __pyx_pybuffer_log_ab_outer; + __Pyx_LocalBuf_ND __pyx_pybuffernd_nijs; + __Pyx_Buffer __pyx_pybuffer_nijs; + __Pyx_LocalBuf_ND __pyx_pybuffernd_term1; + __Pyx_Buffer __pyx_pybuffer_term1; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; - unsigned int __pyx_t_3; - PyArrayObject *__pyx_t_4 = NULL; - PyArrayObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyArrayObject *__pyx_t_9 = NULL; - PyArrayObject *__pyx_t_10 = NULL; - unsigned int __pyx_t_11; - long __pyx_t_12; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *(*__pyx_t_5)(PyObject *); + int __pyx_t_6; + int __pyx_t_7; + PyArrayObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; int __pyx_t_13; - unsigned int __pyx_t_14; - unsigned int __pyx_t_15; - unsigned int __pyx_t_16; - unsigned int __pyx_t_17; - unsigned int __pyx_t_18; - unsigned int __pyx_t_19; - unsigned int __pyx_t_20; - PyObject *__pyx_t_21 = NULL; - PyObject *__pyx_t_22 = NULL; + PyArrayObject *__pyx_t_14 = NULL; + long __pyx_t_15; + PyArrayObject *__pyx_t_16 = NULL; + PyArrayObject *__pyx_t_17 = NULL; + float __pyx_t_18; + Py_ssize_t __pyx_t_19; + PyObject *(*__pyx_t_20)(PyObject *); + Py_ssize_t __pyx_t_21; + PyObject *(*__pyx_t_22)(PyObject *); PyObject *__pyx_t_23 = NULL; + PyObject *__pyx_t_24 = NULL; + long __pyx_t_25; + long __pyx_t_26; + Py_ssize_t __pyx_t_27; + Py_ssize_t __pyx_t_28; + Py_ssize_t __pyx_t_29; + Py_ssize_t __pyx_t_30; + Py_ssize_t __pyx_t_31; + Py_ssize_t __pyx_t_32; + Py_ssize_t __pyx_t_33; + Py_ssize_t __pyx_t_34; + Py_ssize_t __pyx_t_35; + Py_ssize_t __pyx_t_36; + Py_ssize_t __pyx_t_37; + Py_ssize_t __pyx_t_38; + Py_ssize_t __pyx_t_39; + Py_ssize_t __pyx_t_40; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("csr_mean_variance_axis0"); - __pyx_self = __pyx_self; - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; - __pyx_bstruct_means.buf = NULL; - __pyx_bstruct_variances.buf = NULL; - - /* "sklearn/utils/sparsefuncs.pyx":39 - * - * """ - * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< - * cdef unsigned int n_features = X.shape[1] - * - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RefNannySetupContext("expected_mutual_information", 0); + __pyx_pybuffer_gln_a.pybuffer.buf = NULL; + __pyx_pybuffer_gln_a.refcount = 0; + __pyx_pybuffernd_gln_a.data = NULL; + __pyx_pybuffernd_gln_a.rcbuffer = &__pyx_pybuffer_gln_a; + __pyx_pybuffer_gln_b.pybuffer.buf = NULL; + __pyx_pybuffer_gln_b.refcount = 0; + __pyx_pybuffernd_gln_b.data = NULL; + __pyx_pybuffernd_gln_b.rcbuffer = &__pyx_pybuffer_gln_b; + __pyx_pybuffer_gln_Na.pybuffer.buf = NULL; + __pyx_pybuffer_gln_Na.refcount = 0; + __pyx_pybuffernd_gln_Na.data = NULL; + __pyx_pybuffernd_gln_Na.rcbuffer = &__pyx_pybuffer_gln_Na; + __pyx_pybuffer_gln_Nb.pybuffer.buf = NULL; + __pyx_pybuffer_gln_Nb.refcount = 0; + __pyx_pybuffernd_gln_Nb.data = NULL; + __pyx_pybuffernd_gln_Nb.rcbuffer = &__pyx_pybuffer_gln_Nb; + __pyx_pybuffer_gln_nij.pybuffer.buf = NULL; + __pyx_pybuffer_gln_nij.refcount = 0; + __pyx_pybuffernd_gln_nij.data = NULL; + __pyx_pybuffernd_gln_nij.rcbuffer = &__pyx_pybuffer_gln_nij; + __pyx_pybuffer_log_Nnij.pybuffer.buf = NULL; + __pyx_pybuffer_log_Nnij.refcount = 0; + __pyx_pybuffernd_log_Nnij.data = NULL; + __pyx_pybuffernd_log_Nnij.rcbuffer = &__pyx_pybuffer_log_Nnij; + __pyx_pybuffer_nijs.pybuffer.buf = NULL; + __pyx_pybuffer_nijs.refcount = 0; + __pyx_pybuffernd_nijs.data = NULL; + __pyx_pybuffernd_nijs.rcbuffer = &__pyx_pybuffer_nijs; + __pyx_pybuffer_term1.pybuffer.buf = NULL; + __pyx_pybuffer_term1.refcount = 0; + __pyx_pybuffernd_term1.data = NULL; + __pyx_pybuffernd_term1.rcbuffer = &__pyx_pybuffer_term1; + __pyx_pybuffer_log_ab_outer.pybuffer.buf = NULL; + __pyx_pybuffer_log_ab_outer.refcount = 0; + __pyx_pybuffernd_log_ab_outer.data = NULL; + __pyx_pybuffernd_log_ab_outer.rcbuffer = &__pyx_pybuffer_log_ab_outer; + __pyx_pybuffer_a.pybuffer.buf = NULL; + __pyx_pybuffer_a.refcount = 0; + __pyx_pybuffernd_a.data = NULL; + __pyx_pybuffernd_a.rcbuffer = &__pyx_pybuffer_a; + __pyx_pybuffer_b.pybuffer.buf = NULL; + __pyx_pybuffer_b.refcount = 0; + __pyx_pybuffernd_b.data = NULL; + __pyx_pybuffernd_b.rcbuffer = &__pyx_pybuffer_b; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":30 + * cdef np.ndarray[np.int32_t] a, b + * #cdef np.ndarray[int, ndim=2] start, end + * R, C = contingency.shape # <<<<<<<<<<<<<< + * N = float(n_samples) + * a = np.sum(contingency, axis=1).astype(np.int32) + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_contingency, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_2 = PyList_GET_ITEM(sequence, 0); + __pyx_t_3 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else + { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_3 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = NULL; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L4_unpacking_done:; + } + __pyx_t_6 = __Pyx_PyInt_AsInt(__pyx_t_2); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_n_samples = __pyx_t_3; - - /* "sklearn/utils/sparsefuncs.pyx":40 - * """ - * cdef unsigned int n_samples = X.shape[0] - * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - */ - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyInt_AsInt(__pyx_t_3); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_R = __pyx_t_6; + __pyx_v_C = __pyx_t_7; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":31 + * #cdef np.ndarray[int, ndim=2] start, end + * R, C = contingency.shape + * N = float(n_samples) # <<<<<<<<<<<<<< + * a = np.sum(contingency, axis=1).astype(np.int32) + * b = np.sum(contingency, axis=0).astype(np.int32) + */ + __pyx_v_N = ((double)__pyx_v_n_samples); + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":32 + * R, C = contingency.shape + * N = float(n_samples) + * a = np.sum(contingency, axis=1).astype(np.int32) # <<<<<<<<<<<<<< + * b = np.sum(contingency, axis=0).astype(np.int32) + * # There are three major terms to the EMI equation, which are multiplied to + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__sum); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_n_features = __pyx_t_3; - - /* "sklearn/utils/sparsefuncs.pyx":42 - * cdef unsigned int n_features = X.shape[1] - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_data.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; - } - } - __pyx_t_4 = 0; - __pyx_v_X_data = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":43 - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - * - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_contingency); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_contingency); + __Pyx_GIVEREF(__pyx_v_contingency); + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__axis), __pyx_int_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__astype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indices.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; - } - } - __pyx_t_5 = 0; - __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":44 - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< - * - * cdef unsigned int i - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indptr.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_a.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_a.rcbuffer->pybuffer, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_7 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_a.rcbuffer->pybuffer, (PyObject*)__pyx_v_a, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } } + __pyx_pybuffernd_a.diminfo[0].strides = __pyx_pybuffernd_a.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_a.diminfo[0].shape = __pyx_pybuffernd_a.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_6 = 0; - __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_8 = 0; + __pyx_v_a = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/utils/sparsefuncs.pyx":52 - * - * # means[j] contains the mean of feature j - * cdef np.ndarray[DOUBLE, ndim=1] means = np.asarray(X.mean(axis=0))[0] # <<<<<<<<<<<<<< - * - * # variances[j] contains the variance of feature j + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":33 + * N = float(n_samples) + * a = np.sum(contingency, axis=1).astype(np.int32) + * b = np.sum(contingency, axis=0).astype(np.int32) # <<<<<<<<<<<<<< + * # There are three major terms to the EMI equation, which are multiplied to + * # and then summed over varying nij values. */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__sum); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__mean); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__axis), __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_8 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_8); - __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_GetItemInt(__pyx_t_8, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_9 = ((PyArrayObject *)__pyx_t_7); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_means, (PyObject*)__pyx_t_9, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_means = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_means.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_means = __pyx_bstruct_means.strides[0]; - __pyx_bshape_0_means = __pyx_bstruct_means.shape[0]; - } - } - __pyx_t_9 = 0; - __pyx_v_means = ((PyArrayObject *)__pyx_t_7); - __pyx_t_7 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":55 - * - * # variances[j] contains the variance of feature j - * cdef np.ndarray[DOUBLE, ndim=1] variances = np.zeros_like(means) # <<<<<<<<<<<<<< - * - * # counts[j] contains the number of samples where feature j is non-zero - */ - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__zeros_like); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __Pyx_INCREF(((PyObject *)__pyx_v_means)); - PyTuple_SET_ITEM(__pyx_t_7, 0, ((PyObject *)__pyx_v_means)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_means)); - __pyx_t_2 = PyObject_Call(__pyx_t_8, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_contingency); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_contingency); + __Pyx_GIVEREF(__pyx_v_contingency); + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__axis), __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__astype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = ((PyArrayObject *)__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__int32); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_variances, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_variances = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_variances.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_variances = __pyx_bstruct_variances.strides[0]; - __pyx_bshape_0_variances = __pyx_bstruct_variances.shape[0]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_b.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_b.rcbuffer->pybuffer, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_7 < 0)) { + PyErr_Fetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_b.rcbuffer->pybuffer, (PyObject*)__pyx_v_b, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_11, __pyx_t_10, __pyx_t_9); + } } + __pyx_pybuffernd_b.diminfo[0].strides = __pyx_pybuffernd_b.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_b.diminfo[0].shape = __pyx_pybuffernd_b.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_10 = 0; - __pyx_v_variances = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":58 - * - * # counts[j] contains the number of samples where feature j is non-zero - * counts = np.zeros_like(means) # <<<<<<<<<<<<<< - * - * for i in xrange(n_samples): - */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__zeros_like); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_means)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_means)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_means)); - __pyx_t_8 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_v_counts = __pyx_t_8; __pyx_t_8 = 0; + __pyx_v_b = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/utils/sparsefuncs.pyx":60 - * counts = np.zeros_like(means) - * - * for i in xrange(n_samples): # <<<<<<<<<<<<<< - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * ind = X_indices[j] - */ - __pyx_t_3 = __pyx_v_n_samples; - for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_3; __pyx_t_11+=1) { - __pyx_v_i = __pyx_t_11; - - /* "sklearn/utils/sparsefuncs.pyx":61 - * - * for i in xrange(n_samples): - * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< - * ind = X_indices[j] - * diff = X_data[j] - means[ind] - */ - __pyx_t_12 = (__pyx_v_i + 1); - __pyx_t_13 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_12, __pyx_bstride_0_X_indptr)); - __pyx_t_14 = __pyx_v_i; - for (__pyx_t_15 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_14, __pyx_bstride_0_X_indptr)); __pyx_t_15 < __pyx_t_13; __pyx_t_15+=1) { - __pyx_v_j = __pyx_t_15; - - /* "sklearn/utils/sparsefuncs.pyx":62 - * for i in xrange(n_samples): - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * ind = X_indices[j] # <<<<<<<<<<<<<< - * diff = X_data[j] - means[ind] - * variances[ind] += diff * diff - */ - __pyx_t_16 = __pyx_v_j; - __pyx_v_ind = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indices.buf, __pyx_t_16, __pyx_bstride_0_X_indices)); - - /* "sklearn/utils/sparsefuncs.pyx":63 - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * ind = X_indices[j] - * diff = X_data[j] - means[ind] # <<<<<<<<<<<<<< - * variances[ind] += diff * diff - * counts[ind] += 1 - */ - __pyx_t_17 = __pyx_v_j; - __pyx_t_18 = __pyx_v_ind; - __pyx_v_diff = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_17, __pyx_bstride_0_X_data)) - (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_means.buf, __pyx_t_18, __pyx_bstride_0_means))); - - /* "sklearn/utils/sparsefuncs.pyx":64 - * ind = X_indices[j] - * diff = X_data[j] - means[ind] - * variances[ind] += diff * diff # <<<<<<<<<<<<<< - * counts[ind] += 1 - * - */ - __pyx_t_19 = __pyx_v_ind; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_variances.buf, __pyx_t_19, __pyx_bstride_0_variances) += (__pyx_v_diff * __pyx_v_diff); - - /* "sklearn/utils/sparsefuncs.pyx":65 - * diff = X_data[j] - means[ind] - * variances[ind] += diff * diff - * counts[ind] += 1 # <<<<<<<<<<<<<< - * - * nz = n_samples - counts - */ - __pyx_t_20 = __pyx_v_ind; - __pyx_t_8 = __Pyx_GetItemInt(__pyx_v_counts, __pyx_t_20, sizeof(unsigned int)+1, PyLong_FromUnsignedLong); if (!__pyx_t_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_2 = PyNumber_InPlaceAdd(__pyx_t_8, __pyx_int_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (__Pyx_SetItemInt(__pyx_v_counts, __pyx_t_20, __pyx_t_2, sizeof(unsigned int)+1, PyLong_FromUnsignedLong) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - } - - /* "sklearn/utils/sparsefuncs.pyx":67 - * counts[ind] += 1 - * - * nz = n_samples - counts # <<<<<<<<<<<<<< - * variances += nz * means ** 2 - * variances /= n_samples + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":37 + * # and then summed over varying nij values. + * # While nijs[0] will never be used, having it simplifies the indexing. + * nijs = np.arange(0, max(np.max(a), np.max(b)) + 1, dtype='float') # <<<<<<<<<<<<<< + * nijs[0] = 1 # Stops divide by zero warnings. As its not used, no issue. + * # term1 is nij / N */ - __pyx_t_2 = PyLong_FromUnsignedLong(__pyx_v_n_samples); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__arange); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__max); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_8 = PyNumber_Subtract(__pyx_t_2, __pyx_v_counts); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_b)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_b)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_b)); + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_nz = __pyx_t_8; - __pyx_t_8 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":68 - * - * nz = n_samples - counts - * variances += nz * means ** 2 # <<<<<<<<<<<<<< - * variances /= n_samples - * - */ - __pyx_t_8 = PyNumber_Power(((PyObject *)__pyx_v_means), __pyx_int_2, Py_None); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_2 = PyNumber_Multiply(__pyx_v_nz, __pyx_t_8); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__max); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyNumber_InPlaceAdd(((PyObject *)__pyx_v_variances), __pyx_t_2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_a)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_a)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_a)); + __pyx_t_12 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_2 = PyObject_RichCompare(__pyx_t_4, __pyx_t_12, Py_GT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_13 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_8) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_8, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = ((PyArrayObject *)__pyx_t_8); + if (__pyx_t_13) { + __Pyx_INCREF(__pyx_t_4); + __pyx_t_1 = __pyx_t_4; + } else { + __Pyx_INCREF(__pyx_t_12); + __pyx_t_1 = __pyx_t_12; + } + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_Add(__pyx_t_1, __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), ((PyObject *)__pyx_n_s__float)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_12) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_12, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = ((PyArrayObject *)__pyx_t_12); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_variances); - __pyx_t_13 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_variances, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_13 < 0)) { - PyErr_Fetch(&__pyx_t_21, &__pyx_t_22, &__pyx_t_23); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_variances, (PyObject*)__pyx_v_variances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_21); Py_XDECREF(__pyx_t_22); Py_XDECREF(__pyx_t_23); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nijs.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nijs.rcbuffer->pybuffer, (PyObject*)__pyx_t_14, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_7 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nijs.rcbuffer->pybuffer, (PyObject*)__pyx_v_nijs, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_21, __pyx_t_22, __pyx_t_23); + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); } } - __pyx_bstride_0_variances = __pyx_bstruct_variances.strides[0]; - __pyx_bshape_0_variances = __pyx_bstruct_variances.shape[0]; - if (unlikely(__pyx_t_13 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_pybuffernd_nijs.diminfo[0].strides = __pyx_pybuffernd_nijs.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_nijs.diminfo[0].shape = __pyx_pybuffernd_nijs.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_10 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_variances)); - __pyx_v_variances = ((PyArrayObject *)__pyx_t_8); - __pyx_t_8 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":69 - * nz = n_samples - counts - * variances += nz * means ** 2 - * variances /= n_samples # <<<<<<<<<<<<<< - * - * return means, variances - */ - __pyx_t_8 = PyLong_FromUnsignedLong(__pyx_v_n_samples); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_2 = __Pyx_PyNumber_InPlaceDivide(((PyObject *)__pyx_v_variances), __pyx_t_8); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = ((PyArrayObject *)__pyx_t_2); + __pyx_t_14 = 0; + __pyx_v_nijs = ((PyArrayObject *)__pyx_t_12); + __pyx_t_12 = 0; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":38 + * # While nijs[0] will never be used, having it simplifies the indexing. + * nijs = np.arange(0, max(np.max(a), np.max(b)) + 1, dtype='float') + * nijs[0] = 1 # Stops divide by zero warnings. As its not used, no issue. # <<<<<<<<<<<<<< + * # term1 is nij / N + * term1 = nijs / N + */ + __pyx_t_15 = 0; + *__Pyx_BufPtrStrided1d(double *, __pyx_pybuffernd_nijs.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_nijs.diminfo[0].strides) = 1.0; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":40 + * nijs[0] = 1 # Stops divide by zero warnings. As its not used, no issue. + * # term1 is nij / N + * term1 = nijs / N # <<<<<<<<<<<<<< + * # term2 is log((N*nij) / (a * b)) == log(N * nij) - log(a * b) + * # term2 uses the outer product + */ + __pyx_t_12 = PyFloat_FromDouble(__pyx_v_N); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_4 = __Pyx_PyNumber_Divide(((PyObject *)__pyx_v_nijs), __pyx_t_12); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_variances); - __pyx_t_13 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_variances, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_13 < 0)) { - PyErr_Fetch(&__pyx_t_23, &__pyx_t_22, &__pyx_t_21); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_variances, (PyObject*)__pyx_v_variances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_23); Py_XDECREF(__pyx_t_22); Py_XDECREF(__pyx_t_21); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_term1.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_term1.rcbuffer->pybuffer, (PyObject*)__pyx_t_14, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_7 < 0)) { + PyErr_Fetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_term1.rcbuffer->pybuffer, (PyObject*)__pyx_v_term1, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_23, __pyx_t_22, __pyx_t_21); + PyErr_Restore(__pyx_t_11, __pyx_t_10, __pyx_t_9); } } - __pyx_bstride_0_variances = __pyx_bstruct_variances.strides[0]; - __pyx_bshape_0_variances = __pyx_bstruct_variances.shape[0]; - if (unlikely(__pyx_t_13 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_pybuffernd_term1.diminfo[0].strides = __pyx_pybuffernd_term1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_term1.diminfo[0].shape = __pyx_pybuffernd_term1.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_10 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_variances)); - __pyx_v_variances = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":71 - * variances /= n_samples - * - * return means, variances # <<<<<<<<<<<<<< - * - * @cython.boundscheck(False) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_means)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_means)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_means)); - __Pyx_INCREF(((PyObject *)__pyx_v_variances)); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_variances)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_variances)); - __pyx_r = ((PyObject *)__pyx_t_2); - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_means); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_variances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.utils.sparsefuncs.csr_mean_variance_axis0", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_means); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_variances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_X_data); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indptr); - __Pyx_XDECREF((PyObject *)__pyx_v_means); - __Pyx_XDECREF((PyObject *)__pyx_v_variances); - __Pyx_XDECREF(__pyx_v_counts); - __Pyx_XDECREF(__pyx_v_nz); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/utils/sparsefuncs.pyx":76 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def inplace_csr_row_normalize_l1(X): # <<<<<<<<<<<<<< - * """Inplace row normalize using the l1 norm""" - * cdef unsigned int n_samples = X.shape[0] - */ - -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_1inplace_csr_row_normalize_l1(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ -static char __pyx_doc_7sklearn_5utils_11sparsefuncs_1inplace_csr_row_normalize_l1[] = "Inplace row normalize using the l1 norm"; -static PyMethodDef __pyx_mdef_7sklearn_5utils_11sparsefuncs_1inplace_csr_row_normalize_l1 = {__Pyx_NAMESTR("inplace_csr_row_normalize_l1"), (PyCFunction)__pyx_pf_7sklearn_5utils_11sparsefuncs_1inplace_csr_row_normalize_l1, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_11sparsefuncs_1inplace_csr_row_normalize_l1)}; -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_1inplace_csr_row_normalize_l1(PyObject *__pyx_self, PyObject *__pyx_v_X) { - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - PyArrayObject *__pyx_v_X_data = 0; - PyArrayObject *__pyx_v_X_indices = 0; - PyArrayObject *__pyx_v_X_indptr = 0; - unsigned int __pyx_v_i; - unsigned int __pyx_v_j; - double __pyx_v_sum_; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - unsigned int __pyx_t_3; - PyArrayObject *__pyx_t_4 = NULL; - PyArrayObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - unsigned int __pyx_t_7; - long __pyx_t_8; - int __pyx_t_9; - unsigned int __pyx_t_10; - unsigned int __pyx_t_11; - unsigned int __pyx_t_12; - int __pyx_t_13; - long __pyx_t_14; - unsigned int __pyx_t_15; - unsigned int __pyx_t_16; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("inplace_csr_row_normalize_l1"); - __pyx_self = __pyx_self; - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; - - /* "sklearn/utils/sparsefuncs.pyx":78 - * def inplace_csr_row_normalize_l1(X): - * """Inplace row normalize using the l1 norm""" - * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< - * cdef unsigned int n_features = X.shape[1] - * - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_n_samples = __pyx_t_3; + __pyx_t_14 = 0; + __pyx_v_term1 = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; - /* "sklearn/utils/sparsefuncs.pyx":79 - * """Inplace row normalize using the l1 norm""" - * cdef unsigned int n_samples = X.shape[0] - * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":43 + * # term2 is log((N*nij) / (a * b)) == log(N * nij) - log(a * b) + * # term2 uses the outer product + * log_ab_outer = np.log(np.outer(a, b)) # <<<<<<<<<<<<<< + * # term2 uses N * nij + * log_Nnij = np.log(N * nijs) */ - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_12 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__log); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__outer); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_a)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_a)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_a)); + __Pyx_INCREF(((PyObject *)__pyx_v_b)); + PyTuple_SET_ITEM(__pyx_t_4, 1, ((PyObject *)__pyx_v_b)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_b)); + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_n_features = __pyx_t_3; - - /* "sklearn/utils/sparsefuncs.pyx":81 - * cdef unsigned int n_features = X.shape[1] - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_12, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_16 = ((PyArrayObject *)__pyx_t_3); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_data.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_ab_outer.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_log_ab_outer.rcbuffer->pybuffer, (PyObject*)__pyx_t_16, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_7 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_log_ab_outer.rcbuffer->pybuffer, (PyObject*)__pyx_v_log_ab_outer, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } } + __pyx_pybuffernd_log_ab_outer.diminfo[0].strides = __pyx_pybuffernd_log_ab_outer.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_log_ab_outer.diminfo[0].shape = __pyx_pybuffernd_log_ab_outer.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_log_ab_outer.diminfo[1].strides = __pyx_pybuffernd_log_ab_outer.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_log_ab_outer.diminfo[1].shape = __pyx_pybuffernd_log_ab_outer.rcbuffer->pybuffer.shape[1]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_4 = 0; - __pyx_v_X_data = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":82 - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - * - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = ((PyArrayObject *)__pyx_t_1); + __pyx_t_16 = 0; + __pyx_v_log_ab_outer = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":45 + * log_ab_outer = np.log(np.outer(a, b)) + * # term2 uses N * nij + * log_Nnij = np.log(N * nijs) # <<<<<<<<<<<<<< + * # term3 is large, and involved many factorials. Calculate these in log + * # space to stop overflows. + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__log); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_N); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_12 = PyNumber_Multiply(__pyx_t_3, ((PyObject *)__pyx_v_nijs)); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_12); + __Pyx_GIVEREF(__pyx_t_12); + __pyx_t_12 = 0; + __pyx_t_12 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_12) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_12, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = ((PyArrayObject *)__pyx_t_12); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indices.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_Nnij.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_log_Nnij.rcbuffer->pybuffer, (PyObject*)__pyx_t_17, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_7 < 0)) { + PyErr_Fetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_log_Nnij.rcbuffer->pybuffer, (PyObject*)__pyx_v_log_Nnij, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_11, __pyx_t_10, __pyx_t_9); + } } + __pyx_pybuffernd_log_Nnij.diminfo[0].strides = __pyx_pybuffernd_log_Nnij.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_log_Nnij.diminfo[0].shape = __pyx_pybuffernd_log_Nnij.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_5 = 0; - __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":83 - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< - * - * # the column indices for row i are stored in: - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); + __pyx_t_17 = 0; + __pyx_v_log_Nnij = ((PyArrayObject *)__pyx_t_12); + __pyx_t_12 = 0; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":48 + * # term3 is large, and involved many factorials. Calculate these in log + * # space to stop overflows. + * gln_a = gammaln(a + 1) # <<<<<<<<<<<<<< + * gln_b = gammaln(b + 1) + * gln_Na = gammaln(N - a + 1) + */ + __pyx_t_12 = __Pyx_GetName(__pyx_m, __pyx_n_s__gammaln); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_3 = PyNumber_Add(((PyObject *)__pyx_v_a), __pyx_int_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_12, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = ((PyArrayObject *)__pyx_t_3); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indptr.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_a.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_gln_a.rcbuffer->pybuffer, (PyObject*)__pyx_t_17, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_7 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_gln_a.rcbuffer->pybuffer, (PyObject*)__pyx_v_gln_a, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } } + __pyx_pybuffernd_gln_a.diminfo[0].strides = __pyx_pybuffernd_gln_a.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_gln_a.diminfo[0].shape = __pyx_pybuffernd_gln_a.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_6 = 0; - __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":93 - * cdef double sum_ - * - * for i in xrange(n_samples): # <<<<<<<<<<<<<< - * sum_ = 0.0 - * - */ - __pyx_t_3 = __pyx_v_n_samples; - for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_3; __pyx_t_7+=1) { - __pyx_v_i = __pyx_t_7; - - /* "sklearn/utils/sparsefuncs.pyx":94 - * - * for i in xrange(n_samples): - * sum_ = 0.0 # <<<<<<<<<<<<<< - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - */ - __pyx_v_sum_ = 0.0; - - /* "sklearn/utils/sparsefuncs.pyx":96 - * sum_ = 0.0 - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< - * sum_ += fabs(X_data[j]) - * - */ - __pyx_t_8 = (__pyx_v_i + 1); - __pyx_t_9 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_8, __pyx_bstride_0_X_indptr)); - __pyx_t_10 = __pyx_v_i; - for (__pyx_t_11 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_10, __pyx_bstride_0_X_indptr)); __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { - __pyx_v_j = __pyx_t_11; - - /* "sklearn/utils/sparsefuncs.pyx":97 - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * sum_ += fabs(X_data[j]) # <<<<<<<<<<<<<< - * - * if sum_ == 0.0: - */ - __pyx_t_12 = __pyx_v_j; - __pyx_v_sum_ = (__pyx_v_sum_ + fabs((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_12, __pyx_bstride_0_X_data)))); - } - - /* "sklearn/utils/sparsefuncs.pyx":99 - * sum_ += fabs(X_data[j]) - * - * if sum_ == 0.0: # <<<<<<<<<<<<<< - * # do not normalize empty rows (can happen if CSR is not pruned - * # correctly) - */ - __pyx_t_13 = (__pyx_v_sum_ == 0.0); - if (__pyx_t_13) { - - /* "sklearn/utils/sparsefuncs.pyx":102 - * # do not normalize empty rows (can happen if CSR is not pruned - * # correctly) - * continue # <<<<<<<<<<<<<< - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - */ - goto __pyx_L5_continue; - goto __pyx_L9; - } - __pyx_L9:; - - /* "sklearn/utils/sparsefuncs.pyx":104 - * continue - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< - * X_data[j] /= sum_ - * - */ - __pyx_t_14 = (__pyx_v_i + 1); - __pyx_t_9 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_14, __pyx_bstride_0_X_indptr)); - __pyx_t_11 = __pyx_v_i; - for (__pyx_t_15 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_11, __pyx_bstride_0_X_indptr)); __pyx_t_15 < __pyx_t_9; __pyx_t_15+=1) { - __pyx_v_j = __pyx_t_15; - - /* "sklearn/utils/sparsefuncs.pyx":105 - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * X_data[j] /= sum_ # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_16 = __pyx_v_j; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_16, __pyx_bstride_0_X_data) /= __pyx_v_sum_; - } - __pyx_L5_continue:; - } - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.utils.sparsefuncs.inplace_csr_row_normalize_l1", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_X_data); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indptr); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/utils/sparsefuncs.pyx":111 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def inplace_csr_row_normalize_l2(X): # <<<<<<<<<<<<<< - * """Inplace row normalize using the l2 norm""" - * cdef unsigned int n_samples = X.shape[0] - */ - -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_2inplace_csr_row_normalize_l2(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ -static char __pyx_doc_7sklearn_5utils_11sparsefuncs_2inplace_csr_row_normalize_l2[] = "Inplace row normalize using the l2 norm"; -static PyMethodDef __pyx_mdef_7sklearn_5utils_11sparsefuncs_2inplace_csr_row_normalize_l2 = {__Pyx_NAMESTR("inplace_csr_row_normalize_l2"), (PyCFunction)__pyx_pf_7sklearn_5utils_11sparsefuncs_2inplace_csr_row_normalize_l2, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_11sparsefuncs_2inplace_csr_row_normalize_l2)}; -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_2inplace_csr_row_normalize_l2(PyObject *__pyx_self, PyObject *__pyx_v_X) { - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - PyArrayObject *__pyx_v_X_data = 0; - PyArrayObject *__pyx_v_X_indices = 0; - PyArrayObject *__pyx_v_X_indptr = 0; - unsigned int __pyx_v_i; - unsigned int __pyx_v_j; - double __pyx_v_sum_; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - unsigned int __pyx_t_3; - PyArrayObject *__pyx_t_4 = NULL; - PyArrayObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - unsigned int __pyx_t_7; - long __pyx_t_8; - int __pyx_t_9; - unsigned int __pyx_t_10; - unsigned int __pyx_t_11; - unsigned int __pyx_t_12; - unsigned int __pyx_t_13; - int __pyx_t_14; - long __pyx_t_15; - unsigned int __pyx_t_16; - unsigned int __pyx_t_17; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("inplace_csr_row_normalize_l2"); - __pyx_self = __pyx_self; - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; - - /* "sklearn/utils/sparsefuncs.pyx":113 - * def inplace_csr_row_normalize_l2(X): - * """Inplace row normalize using the l2 norm""" - * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< - * cdef unsigned int n_features = X.shape[1] - * - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_n_samples = __pyx_t_3; - - /* "sklearn/utils/sparsefuncs.pyx":114 - * """Inplace row normalize using the l2 norm""" - * cdef unsigned int n_samples = X.shape[0] - * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - */ - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_n_features = __pyx_t_3; - - /* "sklearn/utils/sparsefuncs.pyx":116 - * cdef unsigned int n_features = X.shape[1] - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_data.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; - } - } - __pyx_t_4 = 0; - __pyx_v_X_data = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":117 - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - * - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indices.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; - } - } - __pyx_t_5 = 0; - __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":118 - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< - * - * cdef unsigned int i - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indptr.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; - } - } - __pyx_t_6 = 0; - __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":124 - * cdef double sum_ - * - * for i in xrange(n_samples): # <<<<<<<<<<<<<< - * sum_ = 0.0 - * - */ - __pyx_t_3 = __pyx_v_n_samples; - for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_3; __pyx_t_7+=1) { - __pyx_v_i = __pyx_t_7; - - /* "sklearn/utils/sparsefuncs.pyx":125 - * - * for i in xrange(n_samples): - * sum_ = 0.0 # <<<<<<<<<<<<<< - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - */ - __pyx_v_sum_ = 0.0; - - /* "sklearn/utils/sparsefuncs.pyx":127 - * sum_ = 0.0 - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< - * sum_ += (X_data[j] * X_data[j]) - * - */ - __pyx_t_8 = (__pyx_v_i + 1); - __pyx_t_9 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_8, __pyx_bstride_0_X_indptr)); - __pyx_t_10 = __pyx_v_i; - for (__pyx_t_11 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_10, __pyx_bstride_0_X_indptr)); __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { - __pyx_v_j = __pyx_t_11; - - /* "sklearn/utils/sparsefuncs.pyx":128 - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * sum_ += (X_data[j] * X_data[j]) # <<<<<<<<<<<<<< - * - * if sum_ == 0.0: - */ - __pyx_t_12 = __pyx_v_j; - __pyx_t_13 = __pyx_v_j; - __pyx_v_sum_ = (__pyx_v_sum_ + ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_12, __pyx_bstride_0_X_data)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_13, __pyx_bstride_0_X_data)))); - } - - /* "sklearn/utils/sparsefuncs.pyx":130 - * sum_ += (X_data[j] * X_data[j]) - * - * if sum_ == 0.0: # <<<<<<<<<<<<<< - * # do not normalize empty rows (can happen if CSR is not pruned - * # correctly) - */ - __pyx_t_14 = (__pyx_v_sum_ == 0.0); - if (__pyx_t_14) { - - /* "sklearn/utils/sparsefuncs.pyx":133 - * # do not normalize empty rows (can happen if CSR is not pruned - * # correctly) - * continue # <<<<<<<<<<<<<< - * - * sum_ = sqrt(sum_) - */ - goto __pyx_L5_continue; - goto __pyx_L9; - } - __pyx_L9:; - - /* "sklearn/utils/sparsefuncs.pyx":135 - * continue - * - * sum_ = sqrt(sum_) # <<<<<<<<<<<<<< - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - */ - __pyx_v_sum_ = sqrt(__pyx_v_sum_); - - /* "sklearn/utils/sparsefuncs.pyx":137 - * sum_ = sqrt(sum_) - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< - * X_data[j] /= sum_ - * - */ - __pyx_t_15 = (__pyx_v_i + 1); - __pyx_t_9 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_15, __pyx_bstride_0_X_indptr)); - __pyx_t_11 = __pyx_v_i; - for (__pyx_t_16 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_11, __pyx_bstride_0_X_indptr)); __pyx_t_16 < __pyx_t_9; __pyx_t_16+=1) { - __pyx_v_j = __pyx_t_16; - - /* "sklearn/utils/sparsefuncs.pyx":138 - * - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * X_data[j] /= sum_ # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_17 = __pyx_v_j; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_17, __pyx_bstride_0_X_data) /= __pyx_v_sum_; - } - __pyx_L5_continue:; - } - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.utils.sparsefuncs.inplace_csr_row_normalize_l2", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_X_data); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indptr); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/utils/sparsefuncs.pyx":144 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def inplace_csr_column_scale(X, np.ndarray[DOUBLE, ndim=1] scale): # <<<<<<<<<<<<<< - * """Inplace column scaling of a CSR matrix. - * - */ - -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_3inplace_csr_column_scale(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_5utils_11sparsefuncs_3inplace_csr_column_scale[] = "Inplace column scaling of a CSR matrix.\n\n Scale each feature of the data matrix by multiplying with specific scale\n provided by the caller assuming a (n_samples, n_features) shape.\n\n Parameters\n ----------\n X: CSR matrix with shape (n_samples, n_features)\n Matrix to normalize using the variance of the features.\n\n scale: float array with shape (n_features,)\n Array of precomputed feature-wise values to use for scaling.\n "; -static PyMethodDef __pyx_mdef_7sklearn_5utils_11sparsefuncs_3inplace_csr_column_scale = {__Pyx_NAMESTR("inplace_csr_column_scale"), (PyCFunction)__pyx_pf_7sklearn_5utils_11sparsefuncs_3inplace_csr_column_scale, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_11sparsefuncs_3inplace_csr_column_scale)}; -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_3inplace_csr_column_scale(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_X = 0; - PyArrayObject *__pyx_v_scale = 0; - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - PyArrayObject *__pyx_v_X_data = 0; - PyArrayObject *__pyx_v_X_indices = 0; - PyArrayObject *__pyx_v_X_indptr = 0; - unsigned int __pyx_v_i; - unsigned int __pyx_v_j; - Py_buffer __pyx_bstruct_scale; - Py_ssize_t __pyx_bstride_0_scale = 0; - Py_ssize_t __pyx_bshape_0_scale = 0; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - unsigned int __pyx_t_3; - PyArrayObject *__pyx_t_4 = NULL; - PyArrayObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - unsigned int __pyx_t_7; - long __pyx_t_8; - int __pyx_t_9; - unsigned int __pyx_t_10; - unsigned int __pyx_t_11; - unsigned int __pyx_t_12; - int __pyx_t_13; - unsigned int __pyx_t_14; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__scale,0}; - __Pyx_RefNannySetupContext("inplace_csr_column_scale"); - __pyx_self = __pyx_self; - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("inplace_csr_column_scale", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "inplace_csr_column_scale") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_X = values[0]; - __pyx_v_scale = ((PyArrayObject *)values[1]); - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("inplace_csr_column_scale", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.utils.sparsefuncs.inplace_csr_column_scale", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; - __pyx_bstruct_scale.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_scale), __pyx_ptype_5numpy_ndarray, 1, "scale", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_scale, (PyObject*)__pyx_v_scale, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_scale = __pyx_bstruct_scale.strides[0]; - __pyx_bshape_0_scale = __pyx_bstruct_scale.shape[0]; - - /* "sklearn/utils/sparsefuncs.pyx":158 - * Array of precomputed feature-wise values to use for scaling. - * """ - * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< - * cdef unsigned int n_features = X.shape[1] - * - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_n_samples = __pyx_t_3; - - /* "sklearn/utils/sparsefuncs.pyx":159 - * """ - * cdef unsigned int n_samples = X.shape[0] - * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - */ - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_n_features = __pyx_t_3; - - /* "sklearn/utils/sparsefuncs.pyx":161 - * cdef unsigned int n_features = X.shape[1] - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_data.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; - } - } - __pyx_t_4 = 0; - __pyx_v_X_data = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":162 - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - * - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indices.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; - } - } - __pyx_t_5 = 0; - __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":163 - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< - * - * cdef unsigned int i, j - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indptr.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; - } - } - __pyx_t_6 = 0; - __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":166 - * - * cdef unsigned int i, j - * for i in xrange(n_samples): # <<<<<<<<<<<<<< - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * X_data[j] *= scale[X_indices[j]] - */ - __pyx_t_3 = __pyx_v_n_samples; - for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_3; __pyx_t_7+=1) { - __pyx_v_i = __pyx_t_7; - - /* "sklearn/utils/sparsefuncs.pyx":167 - * cdef unsigned int i, j - * for i in xrange(n_samples): - * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< - * X_data[j] *= scale[X_indices[j]] - * - */ - __pyx_t_8 = (__pyx_v_i + 1); - __pyx_t_9 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_8, __pyx_bstride_0_X_indptr)); - __pyx_t_10 = __pyx_v_i; - for (__pyx_t_11 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_10, __pyx_bstride_0_X_indptr)); __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { - __pyx_v_j = __pyx_t_11; - - /* "sklearn/utils/sparsefuncs.pyx":168 - * for i in xrange(n_samples): - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * X_data[j] *= scale[X_indices[j]] # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_12 = __pyx_v_j; - __pyx_t_13 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indices.buf, __pyx_t_12, __pyx_bstride_0_X_indices)); - __pyx_t_14 = __pyx_v_j; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_14, __pyx_bstride_0_X_data) *= (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_scale.buf, __pyx_t_13, __pyx_bstride_0_scale)); - } - } - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_scale); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.utils.sparsefuncs.inplace_csr_column_scale", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_scale); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_X_data); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indptr); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/utils/sparsefuncs.pyx":174 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def csc_mean_variance_axis0(X): # <<<<<<<<<<<<<< - * """Compute mean and variance along axis 0 on a CSC matrix - * - */ - -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_4csc_mean_variance_axis0(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ -static char __pyx_doc_7sklearn_5utils_11sparsefuncs_4csc_mean_variance_axis0[] = "Compute mean and variance along axis 0 on a CSC matrix\n\n Parameters\n ----------\n X: CSC sparse matrix, shape (n_samples, n_features)\n Input data.\n\n Returns\n -------\n\n means: float array with shape (n_features,)\n Feature-wise means\n\n variances: float array with shape (n_features,)\n Feature-wise variances\n\n "; -static PyMethodDef __pyx_mdef_7sklearn_5utils_11sparsefuncs_4csc_mean_variance_axis0 = {__Pyx_NAMESTR("csc_mean_variance_axis0"), (PyCFunction)__pyx_pf_7sklearn_5utils_11sparsefuncs_4csc_mean_variance_axis0, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_11sparsefuncs_4csc_mean_variance_axis0)}; -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_4csc_mean_variance_axis0(PyObject *__pyx_self, PyObject *__pyx_v_X) { - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - PyArrayObject *__pyx_v_X_data = 0; - PyArrayObject *__pyx_v_X_indices = 0; - PyArrayObject *__pyx_v_X_indptr = 0; - unsigned int __pyx_v_i; - unsigned int __pyx_v_j; - double __pyx_v_diff; - PyArrayObject *__pyx_v_means = 0; - PyArrayObject *__pyx_v_variances = 0; - PyObject *__pyx_v_counts = NULL; - PyObject *__pyx_v_nz = NULL; - Py_buffer __pyx_bstruct_means; - Py_ssize_t __pyx_bstride_0_means = 0; - Py_ssize_t __pyx_bshape_0_means = 0; - Py_buffer __pyx_bstruct_variances; - Py_ssize_t __pyx_bstride_0_variances = 0; - Py_ssize_t __pyx_bshape_0_variances = 0; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - unsigned int __pyx_t_3; - PyArrayObject *__pyx_t_4 = NULL; - PyArrayObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyArrayObject *__pyx_t_9 = NULL; - PyArrayObject *__pyx_t_10 = NULL; - unsigned int __pyx_t_11; - long __pyx_t_12; - int __pyx_t_13; - unsigned int __pyx_t_14; - unsigned int __pyx_t_15; - unsigned int __pyx_t_16; - unsigned int __pyx_t_17; - unsigned int __pyx_t_18; - unsigned int __pyx_t_19; - PyObject *__pyx_t_20 = NULL; - PyObject *__pyx_t_21 = NULL; - PyObject *__pyx_t_22 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("csc_mean_variance_axis0"); - __pyx_self = __pyx_self; - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; - __pyx_bstruct_means.buf = NULL; - __pyx_bstruct_variances.buf = NULL; - - /* "sklearn/utils/sparsefuncs.pyx":192 - * - * """ - * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< - * cdef unsigned int n_features = X.shape[1] - * - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 192; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 192; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 192; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_n_samples = __pyx_t_3; - - /* "sklearn/utils/sparsefuncs.pyx":193 - * """ - * cdef unsigned int n_samples = X.shape[0] - * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - */ - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_n_features = __pyx_t_3; - - /* "sklearn/utils/sparsefuncs.pyx":195 - * cdef unsigned int n_features = X.shape[1] - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_data.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; - } - } - __pyx_t_4 = 0; - __pyx_v_X_data = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":196 - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - * - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indices.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; - } - } - __pyx_t_5 = 0; - __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":197 - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< - * - * cdef unsigned int i - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indptr.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; - } - } - __pyx_t_6 = 0; - __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":204 - * - * # means[j] contains the mean of feature j - * cdef np.ndarray[DOUBLE, ndim=1] means = np.asarray(X.mean(axis=0))[0] # <<<<<<<<<<<<<< - * - * # variances[j] contains the variance of feature j - */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__mean); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__axis), __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_8 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_8); - __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_GetItemInt(__pyx_t_8, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_9 = ((PyArrayObject *)__pyx_t_7); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_means, (PyObject*)__pyx_t_9, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_means = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_means.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_means = __pyx_bstruct_means.strides[0]; - __pyx_bshape_0_means = __pyx_bstruct_means.shape[0]; - } - } - __pyx_t_9 = 0; - __pyx_v_means = ((PyArrayObject *)__pyx_t_7); - __pyx_t_7 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":207 - * - * # variances[j] contains the variance of feature j - * cdef np.ndarray[DOUBLE, ndim=1] variances = np.zeros_like(means) # <<<<<<<<<<<<<< - * - * # counts[j] contains the number of samples where feature j is non-zero - */ - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__zeros_like); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __Pyx_INCREF(((PyObject *)__pyx_v_means)); - PyTuple_SET_ITEM(__pyx_t_7, 0, ((PyObject *)__pyx_v_means)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_means)); - __pyx_t_2 = PyObject_Call(__pyx_t_8, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = ((PyArrayObject *)__pyx_t_2); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_variances, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_variances = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_variances.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_variances = __pyx_bstruct_variances.strides[0]; - __pyx_bshape_0_variances = __pyx_bstruct_variances.shape[0]; - } - } - __pyx_t_10 = 0; - __pyx_v_variances = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":210 - * - * # counts[j] contains the number of samples where feature j is non-zero - * counts = np.zeros_like(means) # <<<<<<<<<<<<<< - * - * for i in xrange(n_features): - */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__zeros_like); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_means)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_means)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_means)); - __pyx_t_8 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_v_counts = __pyx_t_8; - __pyx_t_8 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":212 - * counts = np.zeros_like(means) - * - * for i in xrange(n_features): # <<<<<<<<<<<<<< - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * diff = X_data[j] - means[i] - */ - __pyx_t_3 = __pyx_v_n_features; - for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_3; __pyx_t_11+=1) { - __pyx_v_i = __pyx_t_11; - - /* "sklearn/utils/sparsefuncs.pyx":213 - * - * for i in xrange(n_features): - * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< - * diff = X_data[j] - means[i] - * variances[i] += diff * diff - */ - __pyx_t_12 = (__pyx_v_i + 1); - __pyx_t_13 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_12, __pyx_bstride_0_X_indptr)); - __pyx_t_14 = __pyx_v_i; - for (__pyx_t_15 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_14, __pyx_bstride_0_X_indptr)); __pyx_t_15 < __pyx_t_13; __pyx_t_15+=1) { - __pyx_v_j = __pyx_t_15; - - /* "sklearn/utils/sparsefuncs.pyx":214 - * for i in xrange(n_features): - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * diff = X_data[j] - means[i] # <<<<<<<<<<<<<< - * variances[i] += diff * diff - * counts[i] += 1 - */ - __pyx_t_16 = __pyx_v_j; - __pyx_t_17 = __pyx_v_i; - __pyx_v_diff = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_16, __pyx_bstride_0_X_data)) - (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_means.buf, __pyx_t_17, __pyx_bstride_0_means))); - - /* "sklearn/utils/sparsefuncs.pyx":215 - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * diff = X_data[j] - means[i] - * variances[i] += diff * diff # <<<<<<<<<<<<<< - * counts[i] += 1 - * - */ - __pyx_t_18 = __pyx_v_i; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_variances.buf, __pyx_t_18, __pyx_bstride_0_variances) += (__pyx_v_diff * __pyx_v_diff); - - /* "sklearn/utils/sparsefuncs.pyx":216 - * diff = X_data[j] - means[i] - * variances[i] += diff * diff - * counts[i] += 1 # <<<<<<<<<<<<<< - * - * nz = n_samples - counts - */ - __pyx_t_19 = __pyx_v_i; - __pyx_t_8 = __Pyx_GetItemInt(__pyx_v_counts, __pyx_t_19, sizeof(unsigned int)+1, PyLong_FromUnsignedLong); if (!__pyx_t_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_2 = PyNumber_InPlaceAdd(__pyx_t_8, __pyx_int_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (__Pyx_SetItemInt(__pyx_v_counts, __pyx_t_19, __pyx_t_2, sizeof(unsigned int)+1, PyLong_FromUnsignedLong) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - } - - /* "sklearn/utils/sparsefuncs.pyx":218 - * counts[i] += 1 - * - * nz = n_samples - counts # <<<<<<<<<<<<<< - * variances += nz * means ** 2 - * variances /= n_samples - */ - __pyx_t_2 = PyLong_FromUnsignedLong(__pyx_v_n_samples); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_8 = PyNumber_Subtract(__pyx_t_2, __pyx_v_counts); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_nz = __pyx_t_8; - __pyx_t_8 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":219 - * - * nz = n_samples - counts - * variances += nz * means ** 2 # <<<<<<<<<<<<<< - * variances /= n_samples - * - */ - __pyx_t_8 = PyNumber_Power(((PyObject *)__pyx_v_means), __pyx_int_2, Py_None); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_2 = PyNumber_Multiply(__pyx_v_nz, __pyx_t_8); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyNumber_InPlaceAdd(((PyObject *)__pyx_v_variances), __pyx_t_2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_8) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_8, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = ((PyArrayObject *)__pyx_t_8); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_variances); - __pyx_t_13 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_variances, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_13 < 0)) { - PyErr_Fetch(&__pyx_t_20, &__pyx_t_21, &__pyx_t_22); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_variances, (PyObject*)__pyx_v_variances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_20); Py_XDECREF(__pyx_t_21); Py_XDECREF(__pyx_t_22); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_20, __pyx_t_21, __pyx_t_22); - } - } - __pyx_bstride_0_variances = __pyx_bstruct_variances.strides[0]; - __pyx_bshape_0_variances = __pyx_bstruct_variances.shape[0]; - if (unlikely(__pyx_t_13 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_10 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_variances)); - __pyx_v_variances = ((PyArrayObject *)__pyx_t_8); - __pyx_t_8 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":220 - * nz = n_samples - counts - * variances += nz * means ** 2 - * variances /= n_samples # <<<<<<<<<<<<<< - * - * return means, variances - */ - __pyx_t_8 = PyLong_FromUnsignedLong(__pyx_v_n_samples); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_2 = __Pyx_PyNumber_InPlaceDivide(((PyObject *)__pyx_v_variances), __pyx_t_8); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = ((PyArrayObject *)__pyx_t_2); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_variances); - __pyx_t_13 = __Pyx_GetBufferAndValidate(&__pyx_bstruct_variances, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_13 < 0)) { - PyErr_Fetch(&__pyx_t_22, &__pyx_t_21, &__pyx_t_20); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_variances, (PyObject*)__pyx_v_variances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_22); Py_XDECREF(__pyx_t_21); Py_XDECREF(__pyx_t_20); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_22, __pyx_t_21, __pyx_t_20); - } - } - __pyx_bstride_0_variances = __pyx_bstruct_variances.strides[0]; - __pyx_bshape_0_variances = __pyx_bstruct_variances.shape[0]; - if (unlikely(__pyx_t_13 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_10 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_variances)); - __pyx_v_variances = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":222 - * variances /= n_samples - * - * return means, variances # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)__pyx_v_means)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_means)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_means)); - __Pyx_INCREF(((PyObject *)__pyx_v_variances)); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_variances)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_variances)); - __pyx_r = ((PyObject *)__pyx_t_2); - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_means); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_variances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.utils.sparsefuncs.csc_mean_variance_axis0", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_means); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_variances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_X_data); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indptr); - __Pyx_XDECREF((PyObject *)__pyx_v_means); - __Pyx_XDECREF((PyObject *)__pyx_v_variances); - __Pyx_XDECREF(__pyx_v_counts); - __Pyx_XDECREF(__pyx_v_nz); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/utils/sparsefuncs.pyx":228 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def inplace_csc_column_scale(X, np.ndarray[DOUBLE, ndim=1] scale): # <<<<<<<<<<<<<< - * """Inplace column scaling of a CSC matrix. - * - */ - -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_5inplace_csc_column_scale(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_5utils_11sparsefuncs_5inplace_csc_column_scale[] = "Inplace column scaling of a CSC matrix.\n\n Scale each feature of the data matrix by multiplying with specific scale\n provided by the caller assuming a (n_samples, n_features) shape.\n\n Parameters\n ----------\n X: CSC matrix with shape (n_samples, n_features)\n Matrix to normalize using the variance of the features.\n\n scale: float array with shape (n_features,)\n Array of precomputed feature-wise values to use for scaling.\n "; -static PyMethodDef __pyx_mdef_7sklearn_5utils_11sparsefuncs_5inplace_csc_column_scale = {__Pyx_NAMESTR("inplace_csc_column_scale"), (PyCFunction)__pyx_pf_7sklearn_5utils_11sparsefuncs_5inplace_csc_column_scale, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_11sparsefuncs_5inplace_csc_column_scale)}; -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_5inplace_csc_column_scale(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_X = 0; - PyArrayObject *__pyx_v_scale = 0; - unsigned int __pyx_v_n_samples; - unsigned int __pyx_v_n_features; - PyArrayObject *__pyx_v_X_data = 0; - PyArrayObject *__pyx_v_X_indices = 0; - PyArrayObject *__pyx_v_X_indptr = 0; - unsigned int __pyx_v_i; - unsigned int __pyx_v_j; - Py_buffer __pyx_bstruct_scale; - Py_ssize_t __pyx_bstride_0_scale = 0; - Py_ssize_t __pyx_bshape_0_scale = 0; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - unsigned int __pyx_t_3; - PyArrayObject *__pyx_t_4 = NULL; - PyArrayObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - unsigned int __pyx_t_7; - long __pyx_t_8; - int __pyx_t_9; - unsigned int __pyx_t_10; - unsigned int __pyx_t_11; - unsigned int __pyx_t_12; - unsigned int __pyx_t_13; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__scale,0}; - __Pyx_RefNannySetupContext("inplace_csc_column_scale"); - __pyx_self = __pyx_self; - { - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("inplace_csc_column_scale", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "inplace_csc_column_scale") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_X = values[0]; - __pyx_v_scale = ((PyArrayObject *)values[1]); - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("inplace_csc_column_scale", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.utils.sparsefuncs.inplace_csc_column_scale", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; - __pyx_bstruct_scale.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_scale), __pyx_ptype_5numpy_ndarray, 1, "scale", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_scale, (PyObject*)__pyx_v_scale, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_bstride_0_scale = __pyx_bstruct_scale.strides[0]; - __pyx_bshape_0_scale = __pyx_bstruct_scale.shape[0]; - - /* "sklearn/utils/sparsefuncs.pyx":242 - * Array of precomputed feature-wise values to use for scaling. - * """ - * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< - * cdef unsigned int n_features = X.shape[1] - * - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_n_samples = __pyx_t_3; - - /* "sklearn/utils/sparsefuncs.pyx":243 - * """ - * cdef unsigned int n_samples = X.shape[0] - * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - */ - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_n_features = __pyx_t_3; - - /* "sklearn/utils/sparsefuncs.pyx":245 - * cdef unsigned int n_features = X.shape[1] - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); + __pyx_t_17 = 0; + __pyx_v_gln_a = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":49 + * # space to stop overflows. + * gln_a = gammaln(a + 1) + * gln_b = gammaln(b + 1) # <<<<<<<<<<<<<< + * gln_Na = gammaln(N - a + 1) + * gln_Nb = gammaln(N - b + 1) + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__gammaln); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyNumber_Add(((PyObject *)__pyx_v_b), __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_12 = PyTuple_New(1); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + PyTuple_SET_ITEM(__pyx_t_12, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_12), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_12)); __pyx_t_12 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_data.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_b.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_gln_b.rcbuffer->pybuffer, (PyObject*)__pyx_t_17, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_7 < 0)) { + PyErr_Fetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_gln_b.rcbuffer->pybuffer, (PyObject*)__pyx_v_gln_b, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_11, __pyx_t_10, __pyx_t_9); + } } + __pyx_pybuffernd_gln_b.diminfo[0].strides = __pyx_pybuffernd_gln_b.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_gln_b.diminfo[0].shape = __pyx_pybuffernd_gln_b.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_17 = 0; + __pyx_v_gln_b = ((PyArrayObject *)__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_X_data = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - /* "sklearn/utils/sparsefuncs.pyx":246 - * - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - * + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":50 + * gln_a = gammaln(a + 1) + * gln_b = gammaln(b + 1) + * gln_Na = gammaln(N - a + 1) # <<<<<<<<<<<<<< + * gln_Nb = gammaln(N - b + 1) + * gln_N = gammaln(N + 1) */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = ((PyArrayObject *)__pyx_t_1); + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__gammaln); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_12 = PyFloat_FromDouble(__pyx_v_N); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_3 = PyNumber_Subtract(__pyx_t_12, ((PyObject *)__pyx_v_a)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_t_12 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_12); + __Pyx_GIVEREF(__pyx_t_12); + __pyx_t_12 = 0; + __pyx_t_12 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_12) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_12, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = ((PyArrayObject *)__pyx_t_12); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indices.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_Na.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_gln_Na.rcbuffer->pybuffer, (PyObject*)__pyx_t_17, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_7 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_gln_Na.rcbuffer->pybuffer, (PyObject*)__pyx_v_gln_Na, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } } + __pyx_pybuffernd_gln_Na.diminfo[0].strides = __pyx_pybuffernd_gln_Na.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_gln_Na.diminfo[0].shape = __pyx_pybuffernd_gln_Na.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_5 = 0; - __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":247 - * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - * cdef np.ndarray[int, ndim=1] X_indices = X.indices - * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< - * - * cdef unsigned int i, j - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); + __pyx_t_17 = 0; + __pyx_v_gln_Na = ((PyArrayObject *)__pyx_t_12); + __pyx_t_12 = 0; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":51 + * gln_b = gammaln(b + 1) + * gln_Na = gammaln(N - a + 1) + * gln_Nb = gammaln(N - b + 1) # <<<<<<<<<<<<<< + * gln_N = gammaln(N + 1) + * gln_nij = gammaln(nijs + 1) + */ + __pyx_t_12 = __Pyx_GetName(__pyx_m, __pyx_n_s__gammaln); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_N); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyNumber_Subtract(__pyx_t_3, ((PyObject *)__pyx_v_b)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Add(__pyx_t_4, __pyx_int_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_12, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = ((PyArrayObject *)__pyx_t_3); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { - __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_X_indptr.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_Nb.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_gln_Nb.rcbuffer->pybuffer, (PyObject*)__pyx_t_17, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_7 < 0)) { + PyErr_Fetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_gln_Nb.rcbuffer->pybuffer, (PyObject*)__pyx_v_gln_Nb, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_11, __pyx_t_10, __pyx_t_9); + } } + __pyx_pybuffernd_gln_Nb.diminfo[0].strides = __pyx_pybuffernd_gln_Nb.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_gln_Nb.diminfo[0].shape = __pyx_pybuffernd_gln_Nb.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_6 = 0; - __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":250 - * - * cdef unsigned int i, j - * for i in xrange(n_features): # <<<<<<<<<<<<<< - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * X_data[j] *= scale[i] - */ - __pyx_t_3 = __pyx_v_n_features; - for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_3; __pyx_t_7+=1) { - __pyx_v_i = __pyx_t_7; - - /* "sklearn/utils/sparsefuncs.pyx":251 - * cdef unsigned int i, j - * for i in xrange(n_features): - * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< - * X_data[j] *= scale[i] - * - */ - __pyx_t_8 = (__pyx_v_i + 1); - __pyx_t_9 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_8, __pyx_bstride_0_X_indptr)); - __pyx_t_10 = __pyx_v_i; - for (__pyx_t_11 = (*__Pyx_BufPtrStrided1d(int *, __pyx_bstruct_X_indptr.buf, __pyx_t_10, __pyx_bstride_0_X_indptr)); __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { - __pyx_v_j = __pyx_t_11; + __pyx_t_17 = 0; + __pyx_v_gln_Nb = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":52 + * gln_Na = gammaln(N - a + 1) + * gln_Nb = gammaln(N - b + 1) + * gln_N = gammaln(N + 1) # <<<<<<<<<<<<<< + * gln_nij = gammaln(nijs + 1) + * # start and end values for nij terms for each summation. + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__gammaln); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyFloat_FromDouble((__pyx_v_N + 1.0)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_12 = PyTuple_New(1); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + PyTuple_SET_ITEM(__pyx_t_12, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_12), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_12)); __pyx_t_12 = 0; + __pyx_t_18 = __pyx_PyFloat_AsFloat(__pyx_t_4); if (unlikely((__pyx_t_18 == (float)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_gln_N = __pyx_t_18; - /* "sklearn/utils/sparsefuncs.pyx":252 - * for i in xrange(n_features): - * for j in xrange(X_indptr[i], X_indptr[i + 1]): - * X_data[j] *= scale[i] # <<<<<<<<<<<<<< - * - * def mean_variance_axis0(X): + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":53 + * gln_Nb = gammaln(N - b + 1) + * gln_N = gammaln(N + 1) + * gln_nij = gammaln(nijs + 1) # <<<<<<<<<<<<<< + * # start and end values for nij terms for each summation. + * start = np.array([[v - N + w for w in b] for v in a], dtype='int') */ - __pyx_t_12 = __pyx_v_i; - __pyx_t_13 = __pyx_v_j; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_X_data.buf, __pyx_t_13, __pyx_bstride_0_X_data) *= (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_11sparsefuncs_DOUBLE *, __pyx_bstruct_scale.buf, __pyx_t_12, __pyx_bstride_0_scale)); + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__gammaln); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_12 = PyNumber_Add(((PyObject *)__pyx_v_nijs), __pyx_int_1); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_12); + __Pyx_GIVEREF(__pyx_t_12); + __pyx_t_12 = 0; + __pyx_t_12 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_12) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_12, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = ((PyArrayObject *)__pyx_t_12); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_nij.rcbuffer->pybuffer); + __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_gln_nij.rcbuffer->pybuffer, (PyObject*)__pyx_t_17, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_7 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_gln_nij.rcbuffer->pybuffer, (PyObject*)__pyx_v_gln_nij, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } } + __pyx_pybuffernd_gln_nij.diminfo[0].strides = __pyx_pybuffernd_gln_nij.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_gln_nij.diminfo[0].shape = __pyx_pybuffernd_gln_nij.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_scale); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.utils.sparsefuncs.inplace_csc_column_scale", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_scale); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_X_data); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); - __Pyx_XDECREF((PyObject *)__pyx_v_X_indptr); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/utils/sparsefuncs.pyx":254 - * X_data[j] *= scale[i] - * - * def mean_variance_axis0(X): # <<<<<<<<<<<<<< - * """Compute mean and variance along axis 0 on a CSR or CSC matrix - * - */ - -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_6mean_variance_axis0(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ -static char __pyx_doc_7sklearn_5utils_11sparsefuncs_6mean_variance_axis0[] = "Compute mean and variance along axis 0 on a CSR or CSC matrix\n\n Parameters\n ----------\n X: CSR or CSC sparse matrix, shape (n_samples, n_features)\n Input data.\n\n Returns\n -------\n\n means: float array with shape (n_features,)\n Feature-wise means\n\n variances: float array with shape (n_features,)\n Feature-wise variances\n\n "; -static PyMethodDef __pyx_mdef_7sklearn_5utils_11sparsefuncs_6mean_variance_axis0 = {__Pyx_NAMESTR("mean_variance_axis0"), (PyCFunction)__pyx_pf_7sklearn_5utils_11sparsefuncs_6mean_variance_axis0, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_11sparsefuncs_6mean_variance_axis0)}; -static PyObject *__pyx_pf_7sklearn_5utils_11sparsefuncs_6mean_variance_axis0(PyObject *__pyx_self, PyObject *__pyx_v_X) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("mean_variance_axis0"); - __pyx_self = __pyx_self; - - /* "sklearn/utils/sparsefuncs.pyx":272 - * - * """ - * if isinstance(X, sp.csr_matrix): # <<<<<<<<<<<<<< - * return csr_mean_variance_axis0(X) - * elif isinstance(X, sp.csc_matrix): - */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__sp); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__csr_matrix); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = PyObject_IsInstance(__pyx_v_X, __pyx_t_2); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_3) { - - /* "sklearn/utils/sparsefuncs.pyx":273 - * """ - * if isinstance(X, sp.csr_matrix): - * return csr_mean_variance_axis0(X) # <<<<<<<<<<<<<< - * elif isinstance(X, sp.csc_matrix): - * return csc_mean_variance_axis0(X) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(__pyx_v_X); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_X); - __Pyx_GIVEREF(__pyx_v_X); - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = 0; + __pyx_v_gln_nij = ((PyArrayObject *)__pyx_t_12); + __pyx_t_12 = 0; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":55 + * gln_nij = gammaln(nijs + 1) + * # start and end values for nij terms for each summation. + * start = np.array([[v - N + w for w in b] for v in a], dtype='int') # <<<<<<<<<<<<<< + * start = np.maximum(start, 1) + * end = np.minimum(np.resize(a, (C, R)).T, np.resize(b, (R, C))) + 1 + */ + __pyx_t_12 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_12, __pyx_n_s__array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_t_12 = PyList_New(0); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + if (PyList_CheckExact(((PyObject *)__pyx_v_a)) || PyTuple_CheckExact(((PyObject *)__pyx_v_a))) { + __pyx_t_4 = ((PyObject *)__pyx_v_a); __Pyx_INCREF(__pyx_t_4); __pyx_t_19 = 0; + __pyx_t_20 = NULL; + } else { + __pyx_t_19 = -1; __pyx_t_4 = PyObject_GetIter(((PyObject *)__pyx_v_a)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); + __pyx_t_20 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + for (;;) { + if (!__pyx_t_20 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_19 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_1 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_19); __Pyx_INCREF(__pyx_t_1); __pyx_t_19++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_4, __pyx_t_19); __pyx_t_19++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_20 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_19 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_19); __Pyx_INCREF(__pyx_t_1); __pyx_t_19++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_4, __pyx_t_19); __pyx_t_19++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_1 = __pyx_t_20(__pyx_t_4); + if (unlikely(!__pyx_t_1)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_XDECREF(__pyx_v_v); + __pyx_v_v = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyList_CheckExact(((PyObject *)__pyx_v_b)) || PyTuple_CheckExact(((PyObject *)__pyx_v_b))) { + __pyx_t_2 = ((PyObject *)__pyx_v_b); __Pyx_INCREF(__pyx_t_2); __pyx_t_21 = 0; + __pyx_t_22 = NULL; + } else { + __pyx_t_21 = -1; __pyx_t_2 = PyObject_GetIter(((PyObject *)__pyx_v_b)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_22 = Py_TYPE(__pyx_t_2)->tp_iternext; + } + for (;;) { + if (!__pyx_t_22 && PyList_CheckExact(__pyx_t_2)) { + if (__pyx_t_21 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_23 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_21); __Pyx_INCREF(__pyx_t_23); __pyx_t_21++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_23 = PySequence_ITEM(__pyx_t_2, __pyx_t_21); __pyx_t_21++; if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_22 && PyTuple_CheckExact(__pyx_t_2)) { + if (__pyx_t_21 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_23 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_21); __Pyx_INCREF(__pyx_t_23); __pyx_t_21++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_23 = PySequence_ITEM(__pyx_t_2, __pyx_t_21); __pyx_t_21++; if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_23 = __pyx_t_22(__pyx_t_2); + if (unlikely(!__pyx_t_23)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_23); + } + __Pyx_XDECREF(__pyx_v_w); + __pyx_v_w = __pyx_t_23; + __pyx_t_23 = 0; + __pyx_t_23 = PyFloat_FromDouble(__pyx_v_N); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_23); + __pyx_t_24 = PyNumber_Subtract(__pyx_v_v, __pyx_t_23); if (unlikely(!__pyx_t_24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_24); + __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; + __pyx_t_23 = PyNumber_Add(__pyx_t_24, __pyx_v_w); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_23); + __Pyx_DECREF(__pyx_t_24); __pyx_t_24 = 0; + if (unlikely(__Pyx_PyList_Append(__pyx_t_1, (PyObject*)__pyx_t_23))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; + } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(__Pyx_PyList_Append(__pyx_t_12, (PyObject*)__pyx_t_1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - goto __pyx_L5; } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_t_12)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_12)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_12)); + __Pyx_DECREF(((PyObject *)__pyx_t_12)); __pyx_t_12 = 0; + __pyx_t_12 = PyDict_New(); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_12)); + if (PyDict_SetItem(__pyx_t_12, ((PyObject *)__pyx_n_s__dtype), ((PyObject *)__pyx_n_s__int)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_12)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_12)); __pyx_t_12 = 0; + __pyx_v_start = __pyx_t_1; + __pyx_t_1 = 0; - /* "sklearn/utils/sparsefuncs.pyx":274 - * if isinstance(X, sp.csr_matrix): - * return csr_mean_variance_axis0(X) - * elif isinstance(X, sp.csc_matrix): # <<<<<<<<<<<<<< - * return csc_mean_variance_axis0(X) - * else: + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":56 + * # start and end values for nij terms for each summation. + * start = np.array([[v - N + w for w in b] for v in a], dtype='int') + * start = np.maximum(start, 1) # <<<<<<<<<<<<<< + * end = np.minimum(np.resize(a, (C, R)).T, np.resize(b, (R, C))) + 1 + * # emi itself is a summation over the various values. + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_12 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__maximum); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_start); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_start); + __Pyx_GIVEREF(__pyx_v_start); + __Pyx_INCREF(__pyx_int_1); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_1); + __Pyx_GIVEREF(__pyx_int_1); + __pyx_t_4 = PyObject_Call(__pyx_t_12, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_v_start); + __pyx_v_start = __pyx_t_4; + __pyx_t_4 = 0; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":57 + * start = np.array([[v - N + w for w in b] for v in a], dtype='int') + * start = np.maximum(start, 1) + * end = np.minimum(np.resize(a, (C, R)).T, np.resize(b, (R, C))) + 1 # <<<<<<<<<<<<<< + * # emi itself is a summation over the various values. + * emi = 0 */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__sp); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 274; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__csc_matrix); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 274; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__minimum); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_3 = PyObject_IsInstance(__pyx_v_X, __pyx_t_1); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 274; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_12 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__resize); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyInt_FromLong(__pyx_v_C); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyInt_FromLong(__pyx_v_R); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_a)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_a)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_a)); + PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_t_2)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_12, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__T); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_12 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__resize); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyInt_FromLong(__pyx_v_R); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyInt_FromLong(__pyx_v_C); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_23 = PyTuple_New(2); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_23); + PyTuple_SET_ITEM(__pyx_t_23, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_23, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_b)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_b)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_b)); + PyTuple_SET_ITEM(__pyx_t_4, 1, ((PyObject *)__pyx_t_23)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_23)); + __pyx_t_23 = 0; + __pyx_t_23 = PyObject_Call(__pyx_t_12, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_23); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_23); + __Pyx_GIVEREF(__pyx_t_23); + __pyx_t_3 = 0; + __pyx_t_23 = 0; + __pyx_t_23 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_23); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_3) { + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_Add(__pyx_t_23, __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; + __pyx_v_end = __pyx_t_4; + __pyx_t_4 = 0; - /* "sklearn/utils/sparsefuncs.pyx":275 - * return csr_mean_variance_axis0(X) - * elif isinstance(X, sp.csc_matrix): - * return csc_mean_variance_axis0(X) # <<<<<<<<<<<<<< - * else: - * raise TypeError("Unsupported matrix type. Expected a CSR or CSC sparse matrix.") - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __Pyx_INCREF(__pyx_v_X); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_X); - __Pyx_GIVEREF(__pyx_v_X); - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L5; + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":59 + * end = np.minimum(np.resize(a, (C, R)).T, np.resize(b, (R, C))) + 1 + * # emi itself is a summation over the various values. + * emi = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t i, j, nij + * for i in range(R): + */ + __pyx_v_emi = 0.0; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":61 + * emi = 0 + * cdef Py_ssize_t i, j, nij + * for i in range(R): # <<<<<<<<<<<<<< + * for j in range(C): + * for nij in range(start[i,j], end[i,j]): + */ + __pyx_t_7 = __pyx_v_R; + for (__pyx_t_19 = 0; __pyx_t_19 < __pyx_t_7; __pyx_t_19+=1) { + __pyx_v_i = __pyx_t_19; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":62 + * cdef Py_ssize_t i, j, nij + * for i in range(R): + * for j in range(C): # <<<<<<<<<<<<<< + * for nij in range(start[i,j], end[i,j]): + * term2 = log_Nnij[nij] - log_ab_outer[i,j] + */ + __pyx_t_6 = __pyx_v_C; + for (__pyx_t_21 = 0; __pyx_t_21 < __pyx_t_6; __pyx_t_21+=1) { + __pyx_v_j = __pyx_t_21; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":63 + * for i in range(R): + * for j in range(C): + * for nij in range(start[i,j], end[i,j]): # <<<<<<<<<<<<<< + * term2 = log_Nnij[nij] - log_ab_outer[i,j] + * # Numerators are positive, denominators are negative. + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_i); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_23 = PyInt_FromSsize_t(__pyx_v_j); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_23); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_23); + __Pyx_GIVEREF(__pyx_t_23); + __pyx_t_4 = 0; + __pyx_t_23 = 0; + __pyx_t_23 = PyObject_GetItem(__pyx_v_end, ((PyObject *)__pyx_t_1)); if (!__pyx_t_23) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_23); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_25 = __Pyx_PyInt_AsLong(__pyx_t_23); if (unlikely((__pyx_t_25 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_23); __pyx_t_23 = 0; + __pyx_t_23 = PyInt_FromSsize_t(__pyx_v_i); if (unlikely(!__pyx_t_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_23); + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_j); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_23); + __Pyx_GIVEREF(__pyx_t_23); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_23 = 0; + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetItem(__pyx_v_start, ((PyObject *)__pyx_t_4)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_26 = __Pyx_PyInt_AsLong(__pyx_t_1); if (unlikely((__pyx_t_26 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (__pyx_t_27 = __pyx_t_26; __pyx_t_27 < __pyx_t_25; __pyx_t_27+=1) { + __pyx_v_nij = __pyx_t_27; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":64 + * for j in range(C): + * for nij in range(start[i,j], end[i,j]): + * term2 = log_Nnij[nij] - log_ab_outer[i,j] # <<<<<<<<<<<<<< + * # Numerators are positive, denominators are negative. + * gln = (gln_a[i] + gln_b[j] + gln_Na[i] + gln_Nb[j] + */ + __pyx_t_28 = __pyx_v_nij; + __pyx_t_29 = __pyx_v_i; + __pyx_t_30 = __pyx_v_j; + __pyx_v_term2 = ((*__Pyx_BufPtrStrided1d(double *, __pyx_pybuffernd_log_Nnij.rcbuffer->pybuffer.buf, __pyx_t_28, __pyx_pybuffernd_log_Nnij.diminfo[0].strides)) - (*__Pyx_BufPtrStrided2d(double *, __pyx_pybuffernd_log_ab_outer.rcbuffer->pybuffer.buf, __pyx_t_29, __pyx_pybuffernd_log_ab_outer.diminfo[0].strides, __pyx_t_30, __pyx_pybuffernd_log_ab_outer.diminfo[1].strides))); + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":66 + * term2 = log_Nnij[nij] - log_ab_outer[i,j] + * # Numerators are positive, denominators are negative. + * gln = (gln_a[i] + gln_b[j] + gln_Na[i] + gln_Nb[j] # <<<<<<<<<<<<<< + * - gln_N - gln_nij[nij] - lgamma(a[i] - nij + 1) + * - lgamma(b[j] - nij + 1) + */ + __pyx_t_31 = __pyx_v_i; + __pyx_t_32 = __pyx_v_j; + __pyx_t_33 = __pyx_v_i; + __pyx_t_34 = __pyx_v_j; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":67 + * # Numerators are positive, denominators are negative. + * gln = (gln_a[i] + gln_b[j] + gln_Na[i] + gln_Nb[j] + * - gln_N - gln_nij[nij] - lgamma(a[i] - nij + 1) # <<<<<<<<<<<<<< + * - lgamma(b[j] - nij + 1) + * - lgamma(N - a[i] - b[j] + nij + 1)) + */ + __pyx_t_35 = __pyx_v_nij; + __pyx_t_36 = __pyx_v_i; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":68 + * gln = (gln_a[i] + gln_b[j] + gln_Na[i] + gln_Nb[j] + * - gln_N - gln_nij[nij] - lgamma(a[i] - nij + 1) + * - lgamma(b[j] - nij + 1) # <<<<<<<<<<<<<< + * - lgamma(N - a[i] - b[j] + nij + 1)) + * term3 = exp(gln) + */ + __pyx_t_37 = __pyx_v_j; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":69 + * - gln_N - gln_nij[nij] - lgamma(a[i] - nij + 1) + * - lgamma(b[j] - nij + 1) + * - lgamma(N - a[i] - b[j] + nij + 1)) # <<<<<<<<<<<<<< + * term3 = exp(gln) + * emi += (term1[nij] * term2 * term3) + */ + __pyx_t_38 = __pyx_v_i; + __pyx_t_39 = __pyx_v_j; + __pyx_v_gln = (((((((((*__Pyx_BufPtrStrided1d(double *, __pyx_pybuffernd_gln_a.rcbuffer->pybuffer.buf, __pyx_t_31, __pyx_pybuffernd_gln_a.diminfo[0].strides)) + (*__Pyx_BufPtrStrided1d(double *, __pyx_pybuffernd_gln_b.rcbuffer->pybuffer.buf, __pyx_t_32, __pyx_pybuffernd_gln_b.diminfo[0].strides))) + (*__Pyx_BufPtrStrided1d(double *, __pyx_pybuffernd_gln_Na.rcbuffer->pybuffer.buf, __pyx_t_33, __pyx_pybuffernd_gln_Na.diminfo[0].strides))) + (*__Pyx_BufPtrStrided1d(double *, __pyx_pybuffernd_gln_Nb.rcbuffer->pybuffer.buf, __pyx_t_34, __pyx_pybuffernd_gln_Nb.diminfo[0].strides))) - __pyx_v_gln_N) - (*__Pyx_BufPtrStrided1d(double *, __pyx_pybuffernd_gln_nij.rcbuffer->pybuffer.buf, __pyx_t_35, __pyx_pybuffernd_gln_nij.diminfo[0].strides))) - __pyx_f_7sklearn_5utils_6lgamma_lgamma((((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int32_t *, __pyx_pybuffernd_a.rcbuffer->pybuffer.buf, __pyx_t_36, __pyx_pybuffernd_a.diminfo[0].strides)) - __pyx_v_nij) + 1))) - __pyx_f_7sklearn_5utils_6lgamma_lgamma((((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int32_t *, __pyx_pybuffernd_b.rcbuffer->pybuffer.buf, __pyx_t_37, __pyx_pybuffernd_b.diminfo[0].strides)) - __pyx_v_nij) + 1))) - __pyx_f_7sklearn_5utils_6lgamma_lgamma(((((__pyx_v_N - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int32_t *, __pyx_pybuffernd_a.rcbuffer->pybuffer.buf, __pyx_t_38, __pyx_pybuffernd_a.diminfo[0].strides))) - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int32_t *, __pyx_pybuffernd_b.rcbuffer->pybuffer.buf, __pyx_t_39, __pyx_pybuffernd_b.diminfo[0].strides))) + __pyx_v_nij) + 1.0))); + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":70 + * - lgamma(b[j] - nij + 1) + * - lgamma(N - a[i] - b[j] + nij + 1)) + * term3 = exp(gln) # <<<<<<<<<<<<<< + * emi += (term1[nij] * term2 * term3) + * return emi + */ + __pyx_v_term3 = exp(__pyx_v_gln); + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":71 + * - lgamma(N - a[i] - b[j] + nij + 1)) + * term3 = exp(gln) + * emi += (term1[nij] * term2 * term3) # <<<<<<<<<<<<<< + * return emi + */ + __pyx_t_40 = __pyx_v_nij; + __pyx_v_emi = (__pyx_v_emi + (((*__Pyx_BufPtrStrided1d(double *, __pyx_pybuffernd_term1.rcbuffer->pybuffer.buf, __pyx_t_40, __pyx_pybuffernd_term1.diminfo[0].strides)) * __pyx_v_term2) * __pyx_v_term3)); + } + } } - /*else*/ { - /* "sklearn/utils/sparsefuncs.pyx":277 - * return csc_mean_variance_axis0(X) - * else: - * raise TypeError("Unsupported matrix type. Expected a CSR or CSC sparse matrix.") # <<<<<<<<<<<<<< + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":72 + * term3 = exp(gln) + * emi += (term1[nij] * term2 * term3) + * return emi # <<<<<<<<<<<<<< */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_TypeError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L5:; + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_emi); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("sklearn.utils.sparsefuncs.mean_variance_axis0", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_XDECREF(__pyx_t_23); + __Pyx_XDECREF(__pyx_t_24); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_a.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_b.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_Na.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_Nb.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_a.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_b.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_nij.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_Nnij.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_ab_outer.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nijs.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_term1.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.metrics.cluster.expected_mutual_info_fast.expected_mutual_information", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; + goto __pyx_L2; __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_a.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_b.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_Na.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_Nb.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_a.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_b.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_gln_nij.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_Nnij.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_log_ab_outer.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nijs.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_term1.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_gln_a); + __Pyx_XDECREF((PyObject *)__pyx_v_gln_b); + __Pyx_XDECREF((PyObject *)__pyx_v_gln_Na); + __Pyx_XDECREF((PyObject *)__pyx_v_gln_Nb); + __Pyx_XDECREF((PyObject *)__pyx_v_gln_nij); + __Pyx_XDECREF((PyObject *)__pyx_v_log_Nnij); + __Pyx_XDECREF((PyObject *)__pyx_v_nijs); + __Pyx_XDECREF((PyObject *)__pyx_v_term1); + __Pyx_XDECREF((PyObject *)__pyx_v_log_ab_outer); + __Pyx_XDECREF((PyObject *)__pyx_v_a); + __Pyx_XDECREF((PyObject *)__pyx_v_b); + __Pyx_XDECREF(__pyx_v_start); + __Pyx_XDECREF(__pyx_v_end); + __Pyx_XDECREF(__pyx_v_v); + __Pyx_XDECREF(__pyx_v_w); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":190 +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":194 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP. + * # requirements, and does not yet fulfill the PEP. */ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; @@ -3405,13 +2555,13 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__"); + __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":196 + /* "numpy.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< @@ -3422,11 +2572,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":199 + /* "numpy.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -3435,7 +2585,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":200 + /* "numpy.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -3444,16 +2594,16 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":202 + /* "numpy.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":204 + /* "numpy.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< @@ -3463,7 +2613,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_t_1) { - /* "numpy.pxd":205 + /* "numpy.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -3471,11 +2621,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ * copy_shape = 0 */ __pyx_v_copy_shape = 1; - goto __pyx_L6; + goto __pyx_L4; } /*else*/ { - /* "numpy.pxd":207 + /* "numpy.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -3484,9 +2634,9 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_copy_shape = 0; } - __pyx_L6:; + __pyx_L4:; - /* "numpy.pxd":209 + /* "numpy.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< @@ -3496,37 +2646,37 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); if (__pyx_t_1) { - /* "numpy.pxd":210 + /* "numpy.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); + __pyx_t_2 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS)); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { - /* "numpy.pxd":211 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; } - __pyx_L7:; + __pyx_L5:; - /* "numpy.pxd":213 + /* "numpy.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< @@ -3536,46 +2686,46 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); if (__pyx_t_3) { - /* "numpy.pxd":214 + /* "numpy.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); + __pyx_t_1 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS)); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { - /* "numpy.pxd":215 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; } - __pyx_L8:; + __pyx_L6:; - /* "numpy.pxd":217 + /* "numpy.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":218 + /* "numpy.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -3584,7 +2734,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":219 + /* "numpy.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< @@ -3593,7 +2743,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ if (__pyx_v_copy_shape) { - /* "numpy.pxd":222 + /* "numpy.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -3602,7 +2752,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":223 + /* "numpy.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -3611,7 +2761,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":224 + /* "numpy.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< @@ -3622,49 +2772,49 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "numpy.pxd":225 + /* "numpy.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":226 + /* "numpy.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } - goto __pyx_L9; + goto __pyx_L7; } /*else*/ { - /* "numpy.pxd":228 + /* "numpy.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":229 + /* "numpy.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } - __pyx_L9:; + __pyx_L7:; - /* "numpy.pxd":230 + /* "numpy.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -3673,25 +2823,25 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":231 + /* "numpy.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":232 + /* "numpy.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); - /* "numpy.pxd":235 + /* "numpy.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -3700,17 +2850,19 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_f = NULL; - /* "numpy.pxd":236 + /* "numpy.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":240 + /* "numpy.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -3719,7 +2871,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":242 + /* "numpy.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< @@ -3735,7 +2887,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (__pyx_t_1) { - /* "numpy.pxd":244 + /* "numpy.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -3747,49 +2899,50 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; - goto __pyx_L12; + goto __pyx_L10; } /*else*/ { - /* "numpy.pxd":247 + /* "numpy.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } - __pyx_L12:; + __pyx_L10:; - /* "numpy.pxd":249 + /* "numpy.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ __pyx_t_1 = (!__pyx_v_hasfields); if (__pyx_t_1) { - /* "numpy.pxd":250 + /* "numpy.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; - /* "numpy.pxd":251 + /* "numpy.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); @@ -3800,10 +2953,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (!__pyx_t_2) { - /* "numpy.pxd":252 + /* "numpy.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ @@ -3820,24 +2973,24 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (__pyx_t_1) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; } - __pyx_L14:; + __pyx_L12:; - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" @@ -3846,10 +2999,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_BYTE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__b; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":255 + /* "numpy.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< @@ -3859,10 +3012,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__B; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":256 + /* "numpy.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< @@ -3872,10 +3025,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_SHORT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__h; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":257 + /* "numpy.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< @@ -3885,10 +3038,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_USHORT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__H; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":258 + /* "numpy.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< @@ -3898,10 +3051,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_INT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__i; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":259 + /* "numpy.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< @@ -3911,10 +3064,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_UINT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__I; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":260 + /* "numpy.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< @@ -3924,10 +3077,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_LONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__l; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":261 + /* "numpy.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< @@ -3937,10 +3090,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_ULONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__L; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":262 + /* "numpy.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< @@ -3950,10 +3103,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__q; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":263 + /* "numpy.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< @@ -3963,10 +3116,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":264 + /* "numpy.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< @@ -3976,10 +3129,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__f; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":265 + /* "numpy.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< @@ -3989,10 +3142,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__d; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":266 + /* "numpy.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< @@ -4002,10 +3155,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__g; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":267 + /* "numpy.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< @@ -4015,10 +3168,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":268 + /* "numpy.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< @@ -4028,10 +3181,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":269 + /* "numpy.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< @@ -4041,10 +3194,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":270 + /* "numpy.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< @@ -4054,37 +3207,37 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__O; - goto __pyx_L15; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":272 + /* "numpy.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_11), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_8)); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L15:; + __pyx_L13:; - /* "numpy.pxd":273 + /* "numpy.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -4093,7 +3246,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":274 + /* "numpy.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -4102,57 +3255,57 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L13; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":276 + /* "numpy.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":277 + /* "numpy.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":278 + /* "numpy.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":281 + /* "numpy.pxd":285 * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string + * f[0] = c'\0' # Terminate format string * */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; - /* "numpy.pxd":282 + /* "numpy.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L13:; + __pyx_L11:; __pyx_r = 0; goto __pyx_L0; @@ -4177,31 +3330,39 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ return __pyx_r; } -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":288 + * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__"); + __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":285 + /* "numpy.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); if (__pyx_t_1) { - /* "numpy.pxd":286 + /* "numpy.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -4209,11 +3370,11 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * stdlib.free(info.strides) */ free(__pyx_v_info->format); - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":287 + /* "numpy.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< @@ -4223,7 +3384,7 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_t_1) { - /* "numpy.pxd":288 + /* "numpy.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -4231,14 +3392,14 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * */ free(__pyx_v_info->strides); - goto __pyx_L6; + goto __pyx_L4; } - __pyx_L6:; + __pyx_L4:; __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":764 +/* "numpy.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -4253,9 +3414,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":765 + /* "numpy.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -4263,7 +3424,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -4281,7 +3442,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":767 +/* "numpy.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -4296,9 +3457,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":768 + /* "numpy.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -4306,7 +3467,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -4324,7 +3485,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "numpy.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -4339,9 +3500,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":771 + /* "numpy.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -4349,7 +3510,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -4367,7 +3528,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "numpy.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -4382,9 +3543,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":774 + /* "numpy.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -4392,7 +3553,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -4410,7 +3571,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "numpy.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -4425,9 +3586,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":777 + /* "numpy.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -4435,7 +3596,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -4453,7 +3614,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "numpy.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -4476,18 +3637,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; + PyObject *(*__pyx_t_6)(PyObject *); int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; + int __pyx_t_10; + long __pyx_t_11; + char *__pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring"); + __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":786 + /* "numpy.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -4496,7 +3658,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":787 + /* "numpy.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -4505,7 +3667,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":790 + /* "numpy.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< @@ -4513,31 +3675,36 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * child, new_offset = fields */ if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif __Pyx_XDECREF(__pyx_v_childname); __pyx_v_childname = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":791 + /* "numpy.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); __pyx_v_fields = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":792 + /* "numpy.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< @@ -4546,20 +3713,49 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); - } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_child)); __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; @@ -4567,99 +3763,98 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_v_new_offset = __pyx_t_4; __pyx_t_4 = 0; - /* "numpy.pxd":794 + /* "numpy.pxd":798 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":795 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_13), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; } - __pyx_L5:; + __pyx_L7:; - /* "numpy.pxd":797 + /* "numpy.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = (__pyx_v_child->byteorder == '>'); + if (__pyx_t_7) { + __pyx_t_8 = __pyx_v_little_endian; } else { - __pyx_t_7 = __pyx_t_6; + __pyx_t_8 = __pyx_t_7; } - if (!__pyx_t_7) { + if (!__pyx_t_8) { - /* "numpy.pxd":798 + /* "numpy.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; + __pyx_t_7 = (__pyx_v_child->byteorder == '<'); + if (__pyx_t_7) { + __pyx_t_9 = (!__pyx_v_little_endian); + __pyx_t_10 = __pyx_t_9; } else { - __pyx_t_9 = __pyx_t_6; + __pyx_t_10 = __pyx_t_7; } - __pyx_t_6 = __pyx_t_9; + __pyx_t_7 = __pyx_t_10; } else { - __pyx_t_6 = __pyx_t_7; + __pyx_t_7 = __pyx_t_8; } - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; } - __pyx_L6:; + __pyx_L8:; - /* "numpy.pxd":809 + /* "numpy.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -4667,16 +3862,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!__pyx_t_6) break; + if (!__pyx_t_7) break; - /* "numpy.pxd":810 + /* "numpy.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -4685,7 +3879,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":811 + /* "numpy.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -4694,430 +3888,413 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":812 + /* "numpy.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); } - /* "numpy.pxd":814 + /* "numpy.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); - /* "numpy.pxd":816 + /* "numpy.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); - if (__pyx_t_6) { + __pyx_t_7 = (!PyDataType_HASFIELDS(__pyx_v_child)); + if (__pyx_t_7) { - /* "numpy.pxd":817 + /* "numpy.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XDECREF(__pyx_v_t); __pyx_v_t = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":818 + /* "numpy.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); - if (__pyx_t_6) { + __pyx_t_7 = ((__pyx_v_end - __pyx_v_f) < 5); + if (__pyx_t_7) { - /* "numpy.pxd":819 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; } - __pyx_L10:; + __pyx_L12:; - /* "numpy.pxd":822 + /* "numpy.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 98; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":823 + /* "numpy.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 66; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":824 + /* "numpy.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 104; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":825 + /* "numpy.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 72; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":826 + /* "numpy.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 105; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":827 + /* "numpy.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 73; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":828 + /* "numpy.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 108; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":829 + /* "numpy.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 76; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":830 + /* "numpy.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 113; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":831 + /* "numpy.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 81; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":832 + /* "numpy.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 102; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":833 + /* "numpy.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 100; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":834 + /* "numpy.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 103; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":835 + /* "numpy.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":836 + /* "numpy.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":837 + /* "numpy.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":838 + /* "numpy.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 79; - goto __pyx_L11; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":840 + /* "numpy.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_11), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L11:; + __pyx_L13:; - /* "numpy.pxd":841 + /* "numpy.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -5125,25 +4302,25 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":845 + /* "numpy.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_12; } - __pyx_L9:; + __pyx_L11:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":846 + /* "numpy.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -5172,7 +4349,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":961 +/* "numpy.pxd":965 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -5184,9 +4361,9 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base"); + __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":963 + /* "numpy.pxd":967 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -5196,7 +4373,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a __pyx_t_1 = (__pyx_v_base == Py_None); if (__pyx_t_1) { - /* "numpy.pxd":964 + /* "numpy.pxd":968 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -5208,7 +4385,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":966 + /* "numpy.pxd":970 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -5217,7 +4394,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":967 + /* "numpy.pxd":971 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -5228,7 +4405,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":968 + /* "numpy.pxd":972 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -5237,7 +4414,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":969 + /* "numpy.pxd":973 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -5249,7 +4426,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":971 +/* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -5261,9 +4438,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base"); + __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":972 + /* "numpy.pxd":976 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< @@ -5273,7 +4450,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __pyx_t_1 = (__pyx_v_arr->base == NULL); if (__pyx_t_1) { - /* "numpy.pxd":973 + /* "numpy.pxd":977 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -5288,7 +4465,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py } /*else*/ { - /* "numpy.pxd":975 + /* "numpy.pxd":979 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -5314,7 +4491,7 @@ static PyMethodDef __pyx_methods[] = { #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { PyModuleDef_HEAD_INIT, - __Pyx_NAMESTR("sparsefuncs"), + __Pyx_NAMESTR("expected_mutual_info_fast"), 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, @@ -5326,57 +4503,75 @@ static struct PyModuleDef __pyx_moduledef = { #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_n_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 1}, + {&__pyx_kp_u_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 1, 0, 0}, {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, - {&__pyx_kp_u_12, __pyx_k_12, sizeof(__pyx_k_12), 0, 1, 0, 0}, - {&__pyx_kp_u_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 1, 0, 0}, - {&__pyx_n_s_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 0, 1, 1}, + {&__pyx_n_s_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 0, 1, 1}, + {&__pyx_n_s_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 1, 1}, + {&__pyx_kp_s_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 0, 1, 0}, {&__pyx_n_s_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 0, 1, 1}, - {&__pyx_n_s_19, __pyx_k_19, sizeof(__pyx_k_19), 0, 0, 1, 1}, - {&__pyx_n_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 1}, - {&__pyx_n_s_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 1, 1}, - {&__pyx_n_s_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 1, 1}, - {&__pyx_n_s_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 1, 1}, - {&__pyx_n_s_23, __pyx_k_23, sizeof(__pyx_k_23), 0, 0, 1, 1}, - {&__pyx_kp_s_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 0, 1, 0}, + {&__pyx_kp_u_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 1, 0, 0}, {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, - {&__pyx_kp_u_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 1, 0, 0}, + {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, + {&__pyx_n_s__C, __pyx_k__C, sizeof(__pyx_k__C), 0, 0, 1, 1}, + {&__pyx_n_s__N, __pyx_k__N, sizeof(__pyx_k__N), 0, 0, 1, 1}, + {&__pyx_n_s__R, __pyx_k__R, sizeof(__pyx_k__R), 0, 0, 1, 1}, {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__TypeError, __pyx_k__TypeError, sizeof(__pyx_k__TypeError), 0, 0, 1, 1}, + {&__pyx_n_s__T, __pyx_k__T, sizeof(__pyx_k__T), 0, 0, 1, 1}, {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__asarray, __pyx_k__asarray, sizeof(__pyx_k__asarray), 0, 0, 1, 1}, + {&__pyx_n_s__a, __pyx_k__a, sizeof(__pyx_k__a), 0, 0, 1, 1}, + {&__pyx_n_s__arange, __pyx_k__arange, sizeof(__pyx_k__arange), 0, 0, 1, 1}, + {&__pyx_n_s__array, __pyx_k__array, sizeof(__pyx_k__array), 0, 0, 1, 1}, + {&__pyx_n_s__astype, __pyx_k__astype, sizeof(__pyx_k__astype), 0, 0, 1, 1}, {&__pyx_n_s__axis, __pyx_k__axis, sizeof(__pyx_k__axis), 0, 0, 1, 1}, - {&__pyx_n_s__csc_matrix, __pyx_k__csc_matrix, sizeof(__pyx_k__csc_matrix), 0, 0, 1, 1}, - {&__pyx_n_s__csr_matrix, __pyx_k__csr_matrix, sizeof(__pyx_k__csr_matrix), 0, 0, 1, 1}, - {&__pyx_n_s__data, __pyx_k__data, sizeof(__pyx_k__data), 0, 0, 1, 1}, - {&__pyx_n_s__indices, __pyx_k__indices, sizeof(__pyx_k__indices), 0, 0, 1, 1}, - {&__pyx_n_s__indptr, __pyx_k__indptr, sizeof(__pyx_k__indptr), 0, 0, 1, 1}, - {&__pyx_n_s__mean, __pyx_k__mean, sizeof(__pyx_k__mean), 0, 0, 1, 1}, - {&__pyx_n_s__mean_variance_axis0, __pyx_k__mean_variance_axis0, sizeof(__pyx_k__mean_variance_axis0), 0, 0, 1, 1}, + {&__pyx_n_s__b, __pyx_k__b, sizeof(__pyx_k__b), 0, 0, 1, 1}, + {&__pyx_n_s__contingency, __pyx_k__contingency, sizeof(__pyx_k__contingency), 0, 0, 1, 1}, + {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, + {&__pyx_n_s__emi, __pyx_k__emi, sizeof(__pyx_k__emi), 0, 0, 1, 1}, + {&__pyx_n_s__end, __pyx_k__end, sizeof(__pyx_k__end), 0, 0, 1, 1}, + {&__pyx_n_s__float, __pyx_k__float, sizeof(__pyx_k__float), 0, 0, 1, 1}, + {&__pyx_n_s__gammaln, __pyx_k__gammaln, sizeof(__pyx_k__gammaln), 0, 0, 1, 1}, + {&__pyx_n_s__gln, __pyx_k__gln, sizeof(__pyx_k__gln), 0, 0, 1, 1}, + {&__pyx_n_s__gln_N, __pyx_k__gln_N, sizeof(__pyx_k__gln_N), 0, 0, 1, 1}, + {&__pyx_n_s__gln_Na, __pyx_k__gln_Na, sizeof(__pyx_k__gln_Na), 0, 0, 1, 1}, + {&__pyx_n_s__gln_Nb, __pyx_k__gln_Nb, sizeof(__pyx_k__gln_Nb), 0, 0, 1, 1}, + {&__pyx_n_s__gln_a, __pyx_k__gln_a, sizeof(__pyx_k__gln_a), 0, 0, 1, 1}, + {&__pyx_n_s__gln_b, __pyx_k__gln_b, sizeof(__pyx_k__gln_b), 0, 0, 1, 1}, + {&__pyx_n_s__gln_nij, __pyx_k__gln_nij, sizeof(__pyx_k__gln_nij), 0, 0, 1, 1}, + {&__pyx_n_s__i, __pyx_k__i, sizeof(__pyx_k__i), 0, 0, 1, 1}, + {&__pyx_n_s__int, __pyx_k__int, sizeof(__pyx_k__int), 0, 0, 1, 1}, + {&__pyx_n_s__int32, __pyx_k__int32, sizeof(__pyx_k__int32), 0, 0, 1, 1}, + {&__pyx_n_s__j, __pyx_k__j, sizeof(__pyx_k__j), 0, 0, 1, 1}, + {&__pyx_n_s__log, __pyx_k__log, sizeof(__pyx_k__log), 0, 0, 1, 1}, + {&__pyx_n_s__log_Nnij, __pyx_k__log_Nnij, sizeof(__pyx_k__log_Nnij), 0, 0, 1, 1}, + {&__pyx_n_s__log_ab_outer, __pyx_k__log_ab_outer, sizeof(__pyx_k__log_ab_outer), 0, 0, 1, 1}, + {&__pyx_n_s__max, __pyx_k__max, sizeof(__pyx_k__max), 0, 0, 1, 1}, + {&__pyx_n_s__maximum, __pyx_k__maximum, sizeof(__pyx_k__maximum), 0, 0, 1, 1}, + {&__pyx_n_s__minimum, __pyx_k__minimum, sizeof(__pyx_k__minimum), 0, 0, 1, 1}, + {&__pyx_n_s__n_samples, __pyx_k__n_samples, sizeof(__pyx_k__n_samples), 0, 0, 1, 1}, + {&__pyx_n_s__nij, __pyx_k__nij, sizeof(__pyx_k__nij), 0, 0, 1, 1}, + {&__pyx_n_s__nijs, __pyx_k__nijs, sizeof(__pyx_k__nijs), 0, 0, 1, 1}, {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, + {&__pyx_n_s__outer, __pyx_k__outer, sizeof(__pyx_k__outer), 0, 0, 1, 1}, {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__scale, __pyx_k__scale, sizeof(__pyx_k__scale), 0, 0, 1, 1}, + {&__pyx_n_s__resize, __pyx_k__resize, sizeof(__pyx_k__resize), 0, 0, 1, 1}, {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, - {&__pyx_n_s__sp, __pyx_k__sp, sizeof(__pyx_k__sp), 0, 0, 1, 1}, - {&__pyx_n_s__xrange, __pyx_k__xrange, sizeof(__pyx_k__xrange), 0, 0, 1, 1}, - {&__pyx_n_s__zeros_like, __pyx_k__zeros_like, sizeof(__pyx_k__zeros_like), 0, 0, 1, 1}, + {&__pyx_n_s__start, __pyx_k__start, sizeof(__pyx_k__start), 0, 0, 1, 1}, + {&__pyx_n_s__sum, __pyx_k__sum, sizeof(__pyx_k__sum), 0, 0, 1, 1}, + {&__pyx_n_s__term1, __pyx_k__term1, sizeof(__pyx_k__term1), 0, 0, 1, 1}, + {&__pyx_n_s__term2, __pyx_k__term2, sizeof(__pyx_k__term2), 0, 0, 1, 1}, + {&__pyx_n_s__term3, __pyx_k__term3, sizeof(__pyx_k__term3), 0, 0, 1, 1}, + {&__pyx_n_s__v, __pyx_k__v, sizeof(__pyx_k__v), 0, 0, 1, 1}, + {&__pyx_n_s__w, __pyx_k__w, sizeof(__pyx_k__w), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - #if PY_MAJOR_VERSION >= 3 - __pyx_builtin_xrange = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_builtin_xrange = __Pyx_GetName(__pyx_b, __pyx_n_s__xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - __pyx_builtin_TypeError = __Pyx_GetName(__pyx_b, __pyx_n_s__TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -5384,103 +4579,187 @@ static int __Pyx_InitCachedBuiltins(void) { static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); - - /* "sklearn/utils/sparsefuncs.pyx":277 - * return csc_mean_variance_axis0(X) - * else: - * raise TypeError("Unsupported matrix type. Expected a CSR or CSC sparse matrix.") # <<<<<<<<<<<<<< - */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_4)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_3)); - PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_s_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "numpy.pxd":211 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_6)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); + __pyx_k_tuple_2 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_2); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_1)); + PyTuple_SET_ITEM(__pyx_k_tuple_2, 0, ((PyObject *)__pyx_kp_u_1)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_1)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); - /* "numpy.pxd":215 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_8 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_8)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_7)); - PyTuple_SET_ITEM(__pyx_k_tuple_8, 0, ((PyObject *)__pyx_kp_u_7)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_7)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); + __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_4); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_3)); + PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_u_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_10)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_9)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_6); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); + PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_u_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); - /* "numpy.pxd":795 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_13 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_13)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_12)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 0, ((PyObject *)__pyx_kp_u_12)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_12)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); + __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_9); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); + PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_u_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_14 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_14)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_9)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, ((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_10); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); + PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); - /* "numpy.pxd":819 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_16 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_16)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_15)); - PyTuple_SET_ITEM(__pyx_k_tuple_16, 0, ((PyObject *)__pyx_kp_u_15)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_15)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); + __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_12); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); + PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_11)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":21 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def expected_mutual_information(contingency, int n_samples): # <<<<<<<<<<<<<< + * """Calculate the expected mutual information for two labelings.""" + * cdef int R, C + */ + __pyx_k_tuple_14 = PyTuple_New(28); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_14); + __Pyx_INCREF(((PyObject *)__pyx_n_s__contingency)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, ((PyObject *)__pyx_n_s__contingency)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__contingency)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__n_samples)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 1, ((PyObject *)__pyx_n_s__n_samples)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_samples)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__R)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 2, ((PyObject *)__pyx_n_s__R)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__R)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__C)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 3, ((PyObject *)__pyx_n_s__C)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__C)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__N)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 4, ((PyObject *)__pyx_n_s__N)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__N)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__gln_N)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 5, ((PyObject *)__pyx_n_s__gln_N)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gln_N)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__emi)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 6, ((PyObject *)__pyx_n_s__emi)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__emi)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__term2)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 7, ((PyObject *)__pyx_n_s__term2)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__term2)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__term3)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 8, ((PyObject *)__pyx_n_s__term3)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__term3)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__gln)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 9, ((PyObject *)__pyx_n_s__gln)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gln)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__gln_a)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 10, ((PyObject *)__pyx_n_s__gln_a)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gln_a)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__gln_b)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 11, ((PyObject *)__pyx_n_s__gln_b)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gln_b)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__gln_Na)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 12, ((PyObject *)__pyx_n_s__gln_Na)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gln_Na)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__gln_Nb)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 13, ((PyObject *)__pyx_n_s__gln_Nb)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gln_Nb)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__gln_nij)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 14, ((PyObject *)__pyx_n_s__gln_nij)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gln_nij)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__log_Nnij)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 15, ((PyObject *)__pyx_n_s__log_Nnij)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__log_Nnij)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__nijs)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 16, ((PyObject *)__pyx_n_s__nijs)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nijs)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__term1)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 17, ((PyObject *)__pyx_n_s__term1)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__term1)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__log_ab_outer)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 18, ((PyObject *)__pyx_n_s__log_ab_outer)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__log_ab_outer)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__a)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 19, ((PyObject *)__pyx_n_s__a)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__a)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__b)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 20, ((PyObject *)__pyx_n_s__b)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__b)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__start)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 21, ((PyObject *)__pyx_n_s__start)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__start)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__end)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 22, ((PyObject *)__pyx_n_s__end)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__end)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__i)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 23, ((PyObject *)__pyx_n_s__i)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__j)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 24, ((PyObject *)__pyx_n_s__j)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__j)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__nij)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 25, ((PyObject *)__pyx_n_s__nij)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nij)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__v)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 26, ((PyObject *)__pyx_n_s__v)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__v)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__w)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 27, ((PyObject *)__pyx_n_s__w)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__w)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + __pyx_k_codeobj_15 = (PyObject*)__Pyx_PyCode_New(2, 0, 28, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_14, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_17, __pyx_n_s_16, 21, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -5492,7 +4771,6 @@ static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; return 0; __pyx_L1_error:; @@ -5500,15 +4778,16 @@ static int __Pyx_InitGlobals(void) { } #if PY_MAJOR_VERSION < 3 -PyMODINIT_FUNC initsparsefuncs(void); /*proto*/ -PyMODINIT_FUNC initsparsefuncs(void) +PyMODINIT_FUNC initexpected_mutual_info_fast(void); /*proto*/ +PyMODINIT_FUNC initexpected_mutual_info_fast(void) #else -PyMODINIT_FUNC PyInit_sparsefuncs(void); /*proto*/ -PyMODINIT_FUNC PyInit_sparsefuncs(void) +PyMODINIT_FUNC PyInit_expected_mutual_info_fast(void); /*proto*/ +PyMODINIT_FUNC PyInit_expected_mutual_info_fast(void) #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -5519,12 +4798,18 @@ PyMODINIT_FUNC PyInit_sparsefuncs(void) Py_FatalError("failed to import 'refnanny' module"); } #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_sparsefuncs(void)"); + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_expected_mutual_info_fast(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __pyx_binding_PyCFunctionType_USED - if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -5535,20 +4820,27 @@ PyMODINIT_FUNC PyInit_sparsefuncs(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("sparsefuncs"), __pyx_methods, 0, 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("expected_mutual_info_fast"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.metrics.cluster.expected_mutual_info_fast")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.metrics.cluster.expected_mutual_info_fast", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_module_is_main_sklearn__utils__sparsefuncs) { + if (__pyx_module_is_main_sklearn__metrics__cluster__expected_mutual_info_fast) { if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } /*--- Builtin init code ---*/ @@ -5560,140 +4852,94 @@ PyMODINIT_FUNC PyInit_sparsefuncs(void) /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ + __pyx_t_1 = __Pyx_ImportModule("sklearn.utils.lgamma"); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_ImportFunction(__pyx_t_1, "lgamma", (void (**)(void))&__pyx_f_7sklearn_5utils_6lgamma_lgamma, "double (double)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; /*--- Execution code ---*/ - /* "sklearn/utils/sparsefuncs.pyx":7 + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":10 * - * cimport numpy as np - * import numpy as np # <<<<<<<<<<<<<< - * import scipy.sparse as sp - * cimport cython - */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":8 - * cimport numpy as np + * from libc.math cimport exp + * from scipy.special import gammaln # <<<<<<<<<<<<<< * import numpy as np - * import scipy.sparse as sp # <<<<<<<<<<<<<< - * cimport cython - * - */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_n_s_18)); - PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s_18)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s_18)); - __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s_17), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__sp, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":21 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def csr_mean_variance_axis0(X): # <<<<<<<<<<<<<< - * """Compute mean and variance along axis 0 on a CSR matrix - * - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_11sparsefuncs_csr_mean_variance_axis0, NULL, __pyx_n_s_19); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_1, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":76 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def inplace_csr_row_normalize_l1(X): # <<<<<<<<<<<<<< - * """Inplace row normalize using the l1 norm""" - * cdef unsigned int n_samples = X.shape[0] - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_11sparsefuncs_1inplace_csr_row_normalize_l1, NULL, __pyx_n_s_19); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_20, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":111 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def inplace_csr_row_normalize_l2(X): # <<<<<<<<<<<<<< - * """Inplace row normalize using the l2 norm""" - * cdef unsigned int n_samples = X.shape[0] + * cimport numpy as np */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_11sparsefuncs_2inplace_csr_row_normalize_l2, NULL, __pyx_n_s_19); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_21, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":144 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def inplace_csr_column_scale(X, np.ndarray[DOUBLE, ndim=1] scale): # <<<<<<<<<<<<<< - * """Inplace column scaling of a CSR matrix. - * - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_11sparsefuncs_3inplace_csr_column_scale, NULL, __pyx_n_s_19); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(((PyObject *)__pyx_n_s__gammaln)); + PyList_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_n_s__gammaln)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gammaln)); + __pyx_t_3 = __Pyx_Import(((PyObject *)__pyx_n_s_13), ((PyObject *)__pyx_t_2), -1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__gammaln); + if (__pyx_t_2 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__gammaln); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_22, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__gammaln, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/utils/sparsefuncs.pyx":174 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def csc_mean_variance_axis0(X): # <<<<<<<<<<<<<< - * """Compute mean and variance along axis 0 on a CSC matrix - * + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":11 + * from libc.math cimport exp + * from scipy.special import gammaln + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * cimport cython */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_11sparsefuncs_4csc_mean_variance_axis0, NULL, __pyx_n_s_19); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_2, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/utils/sparsefuncs.pyx":228 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def inplace_csc_column_scale(X, np.ndarray[DOUBLE, ndim=1] scale): # <<<<<<<<<<<<<< - * """Inplace column scaling of a CSC matrix. + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":16 + * from sklearn.utils.lgamma cimport lgamma * - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_11sparsefuncs_5inplace_csc_column_scale, NULL, __pyx_n_s_19); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_23, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":254 - * X_data[j] *= scale[i] + * np.import_array() # <<<<<<<<<<<<<< * - * def mean_variance_axis0(X): # <<<<<<<<<<<<<< - * """Compute mean and variance along axis 0 on a CSR or CSC matrix * */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_11sparsefuncs_6mean_variance_axis0, NULL, __pyx_n_s_19); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__mean_variance_axis0, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "sklearn/utils/sparsefuncs.pyx":1 - * # Author: Mathieu Blondel # <<<<<<<<<<<<<< - * # Olivier Grisel - * # - */ - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + import_array(); - /* "numpy.pxd":971 + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":21 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def expected_mutual_information(contingency, int n_samples): # <<<<<<<<<<<<<< + * """Calculate the expected mutual information for two labelings.""" + * cdef int R, C + */ + __pyx_t_3 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7metrics_7cluster_25expected_mutual_info_fast_1expected_mutual_information, NULL, __pyx_n_s_18); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_16, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "sklearn/metrics/cluster/expected_mutual_info_fast.pyx":1 + * # encoding: utf-8 # <<<<<<<<<<<<<< + * # cython: cdivision=True + * # cython: boundscheck=False + */ + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_3)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + + /* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -5704,11 +4950,12 @@ PyMODINIT_FUNC PyInit_sparsefuncs(void) __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); if (__pyx_m) { - __Pyx_AddTraceback("init sklearn.utils.sparsefuncs", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("init sklearn.metrics.cluster.expected_mutual_info_fast", __pyx_clineno, __pyx_lineno, __pyx_filename); Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init sklearn.utils.sparsefuncs"); + PyErr_SetString(PyExc_ImportError, "init sklearn.metrics.cluster.expected_mutual_info_fast"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); @@ -5719,39 +4966,232 @@ PyMODINIT_FUNC PyInit_sparsefuncs(void) #endif } -/* Runtime support code */ +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { + PyObject *result; + result = PyObject_GetAttr(dict, name); + if (!result) { + if (dict != __pyx_b) { + PyErr_Clear(); + result = PyObject_GetAttr(__pyx_b, name); + } + if (!result) { + PyErr_SetObject(PyExc_NameError, name); + } + } + return result; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule((char *)modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } -#endif /* CYTHON_REFNANNY */ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; } } - return result; + return 0; +#endif } +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; +} static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { @@ -5769,18 +5209,6 @@ static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } - -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; -} __Pyx_BufFmt_Context; - static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { @@ -5799,6 +5227,8 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; @@ -5806,7 +5236,6 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, type = type->fields->type; } } - static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; @@ -5822,15 +5251,21 @@ static int __Pyx_BufFmt_ParseNumber(const char** ts) { *ts = t; return count; } - +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } - static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { - case 'b': return "'char'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; @@ -5846,14 +5281,14 @@ static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; + case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } - static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; @@ -5869,10 +5304,9 @@ static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { return 0; } } - static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'B': return 1; + case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); @@ -5889,7 +5323,6 @@ static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { } } } - typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; @@ -5900,10 +5333,9 @@ typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif - -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); @@ -5919,21 +5351,59 @@ static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { return 0; } } - +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'h': case 'i': case 'l': case 'q': return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; - case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); - case 'O': return 'O'; - case 'P': return 'P'; + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } - static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; @@ -5958,16 +5428,37 @@ static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { parent->type->name, field->name); } } - static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; - size_t size, offset; + size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { @@ -5979,35 +5470,35 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); } - if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { - /* special case -- treat as struct rather than complex number */ size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } - - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } - offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } - ctx->fmt_offset += size; - + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; /* Consume from buffer string */ - - /* Done checking, move to next field, pushing or popping struct stack if needed */ while (1) { if (field == &ctx->root) { ctx->head = NULL; @@ -6039,7 +5530,48 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ctx->is_complex = 0; return 0; } - +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + if (isspace(*ts)) + continue; + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { @@ -6054,7 +5586,7 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } - return ts; + return ts; case ' ': case 10: case 13: @@ -6086,12 +5618,17 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { @@ -6099,10 +5636,19 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha if (!ts_after_sub) return NULL; } ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': /* end of substruct; either repeat or move on */ - ++ts; + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; @@ -6123,13 +5669,11 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': - case 'O': + case 'O': case 's': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { - /* Continue pooling same type */ ctx->enc_count += ctx->new_count; } else { - /* New type */ if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; @@ -6145,20 +5689,18 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha while(*ts != ':') ++ts; ++ts; break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; default: { - int number = __Pyx_BufFmt_ParseNumber(&ts); - if (number == -1) { /* First char was not a digit */ - PyErr_Format(PyExc_ValueError, - "Does not understand character buffer dtype format string ('%c')", *ts); - return NULL; - } - ctx->new_count = (size_t)number; + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; } } } } - static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; @@ -6166,8 +5708,10 @@ static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; @@ -6187,7 +5731,7 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* ob } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; @@ -6195,223 +5739,87 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* ob if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; fail:; - __Pyx_ZeroBuffer(buf); - return -1; -} - -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { - if (info->buf == NULL) return; - if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; - __Pyx_ReleaseBuffer(info); -} - - -static void __Pyx_RaiseBufferFallbackError(void) { - PyErr_Format(PyExc_ValueError, - "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); -} - - -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); - - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} - -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { - PyThreadState *tstate = PyThreadState_GET(); - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -} - - -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); - #endif + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); } -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { - values[name-argnames] = value; - } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - } - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; +static void __Pyx_RaiseBufferFallbackError(void) { + PyErr_Format(PyExc_ValueError, + "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); } -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact) -{ - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; - } - if (none_allowed && obj == Py_None) return 1; - else if (exact) { - if (Py_TYPE(obj) == type) return 1; - } - else { - if (PyObject_TypeCheck(obj, type)) return 1; - } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif } #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) + if (PyClass_Check(type)) { #else - if (!PyType_Check(type)) + if (PyType_Check(type)) { #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - /* Normalize to raise , */ - Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 if (PyInstance_Check(type)) { @@ -6434,7 +5842,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } #endif } - __Pyx_ErrRestore(type, value, tb); return; raise_error: @@ -6443,10 +5850,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tb); return; } - #else /* Python 3+ */ - static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -6456,7 +5862,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } if (value == Py_None) value = 0; - if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, @@ -6465,13 +5870,36 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } + else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } - - if (cause) { + if (cause && cause != Py_None) { PyObject *fixed_cause; if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); @@ -6488,14 +5916,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; @@ -6505,64 +5928,90 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tmp_tb); } } - bad: + Py_XDECREF(owned_instance); return; } #endif -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); -} - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); -} - static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); - } else { - __Pyx_RaiseTooManyValuesError(index); - } -} - #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + CYTHON_UNUSED PyObject *getbuffer_cobj; #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); - else { - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict && + (getbuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, + "__pyx_getbuffer"))) { + getbufferproc func; + #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + func = (getbufferproc) PyCapsule_GetPointer(getbuffer_cobj, "getbuffer(obj, view, flags)"); + #else + func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + #endif + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); } + #endif + PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; } - static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject* obj = view->obj; - if (obj) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;} - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray_1__releasebuffer__(obj, view); + PyObject *obj = view->obj; + CYTHON_UNUSED PyObject *releasebuffer_cobj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict && + (releasebuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, + "__pyx_releasebuffer"))) { + releasebufferproc func; + #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + func = (releasebufferproc) PyCapsule_GetPointer(releasebuffer_cobj, "releasebuffer(obj, view)"); + #else + func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + #endif + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: Py_DECREF(obj); view->obj = NULL; - } } +#endif /* PY_MAJOR_VERSION < 3 */ -#endif -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { PyObject *py_import = 0; PyObject *empty_list = 0; PyObject *module = 0; @@ -6588,12 +6037,33 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { goto bad; #if PY_VERSION_HEX >= 0x02050000 { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + /* try package relative import first */ + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + } } #else if (level>0) { @@ -6610,6 +6080,15 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { return module; } +static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name) { +#if PY_MAJOR_VERSION < 3 + PyErr_Format(PyExc_ImportError, "cannot import name %.230s", + PyString_AsString(name)); +#else + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); +#endif +} + #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { @@ -7269,6 +6748,23 @@ static int __Pyx_check_binary_version(void) { return 0; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -7278,15 +6774,10 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(class_name); - #else - py_name = PyUnicode_FromString(class_name); - #endif + py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); @@ -7302,7 +6793,7 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { + if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -7312,7 +6803,7 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { PyErr_Format(PyExc_ValueError, "%s.%s has the wrong size, try recompiling", module_name, class_name); @@ -7326,51 +6817,158 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(name); - #else - py_name = PyUnicode_FromString(name); - #endif - if (!py_name) +#ifndef __PYX_HAVE_RT_ImportFunction +#define __PYX_HAVE_RT_ImportFunction +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); + if (!d) goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); + cobj = PyDict_GetItemString(d, funcname); + if (!cobj) { + PyErr_Format(PyExc_ImportError, + "%s does not export expected C function %s", + PyModule_GetName(module), funcname); + goto bad; + } +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3 && PY_MINOR_VERSION==0) + if (!PyCapsule_IsValid(cobj, sig)) { + PyErr_Format(PyExc_TypeError, + "C function %s.%s has wrong signature (expected %s, got %s)", + PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); + goto bad; + } + tmp.p = PyCapsule_GetPointer(cobj, sig); +#else + {const char *desc, *s1, *s2; + desc = (const char *)PyCObject_GetDesc(cobj); + if (!desc) + goto bad; + s1 = desc; s2 = sig; + while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } + if (*s1 != *s2) { + PyErr_Format(PyExc_TypeError, + "C function %s.%s has wrong signature (expected %s, got %s)", + PyModule_GetName(module), funcname, sig, desc); + goto bad; + } + tmp.p = PyCObject_AsVoidPtr(cobj);} +#endif + *f = tmp.fp; + if (!(*f)) + goto bad; + Py_DECREF(d); return 0; +bad: + Py_XDECREF(d); + return -1; } #endif +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + #include "compile.h" #include "frameobject.h" #include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); + py_srcfile = PyString_FromString(filename); #else - py_srcfile = PyUnicode_FromString(__pyx_filename); + py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; - if (__pyx_clineno) { + if (c_line) { #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { @@ -7381,28 +6979,45 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, #endif } if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_code = PyCode_New( + py_code = __Pyx_PyCode_New( 0, /*int argcount,*/ - #if PY_MAJOR_VERSION >= 3 0, /*int kwonlyargcount,*/ - #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ + py_line, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); - if (!py_code) goto bad; + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ @@ -7410,11 +7025,9 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; + py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); } @@ -7449,6 +7062,7 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } + /* Type Conversion Functions */ static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { diff --git a/sklearn/metrics/cluster/expected_mutual_info_fast.pyx b/sklearn/metrics/cluster/expected_mutual_info_fast.pyx new file mode 100644 index 0000000000000..f47677c2358c4 --- /dev/null +++ b/sklearn/metrics/cluster/expected_mutual_info_fast.pyx @@ -0,0 +1,71 @@ +# cython: cdivision=True +# cython: boundscheck=False +# cython: wraparound=False +# Authors: Robert Layton +# Corey Lynch +# Licence: BSD 3 clause + +from libc.math cimport exp +from scipy.special import gammaln +import numpy as np +cimport numpy as np +cimport cython +from sklearn.utils.lgamma cimport lgamma + +np.import_array() + + +@cython.boundscheck(False) +@cython.wraparound(False) +def expected_mutual_information(contingency, int n_samples): + """Calculate the expected mutual information for two labelings.""" + cdef int R, C + cdef float N, gln_N, emi, term2, term3, gln + cdef np.ndarray[double] gln_a, gln_b, gln_Na, gln_Nb, gln_nij, log_Nnij + cdef np.ndarray[double] nijs, term1 + cdef np.ndarray[double, ndim=2] log_ab_outer + cdef np.ndarray[np.int32_t] a, b + #cdef np.ndarray[int, ndim=2] start, end + R, C = contingency.shape + N = float(n_samples) + a = np.sum(contingency, axis=1).astype(np.int32) + b = np.sum(contingency, axis=0).astype(np.int32) + # There are three major terms to the EMI equation, which are multiplied to + # and then summed over varying nij values. + # While nijs[0] will never be used, having it simplifies the indexing. + nijs = np.arange(0, max(np.max(a), np.max(b)) + 1, dtype='float') + nijs[0] = 1 # Stops divide by zero warnings. As its not used, no issue. + # term1 is nij / N + term1 = nijs / N + # term2 is log((N*nij) / (a * b)) == log(N * nij) - log(a * b) + # term2 uses the outer product + log_ab_outer = np.log(np.outer(a, b)) + # term2 uses N * nij + log_Nnij = np.log(N * nijs) + # term3 is large, and involved many factorials. Calculate these in log + # space to stop overflows. + gln_a = gammaln(a + 1) + gln_b = gammaln(b + 1) + gln_Na = gammaln(N - a + 1) + gln_Nb = gammaln(N - b + 1) + gln_N = gammaln(N + 1) + gln_nij = gammaln(nijs + 1) + # start and end values for nij terms for each summation. + start = np.array([[v - N + w for w in b] for v in a], dtype='int') + start = np.maximum(start, 1) + end = np.minimum(np.resize(a, (C, R)).T, np.resize(b, (R, C))) + 1 + # emi itself is a summation over the various values. + emi = 0 + cdef Py_ssize_t i, j, nij + for i in range(R): + for j in range(C): + for nij in range(start[i,j], end[i,j]): + term2 = log_Nnij[nij] - log_ab_outer[i,j] + # Numerators are positive, denominators are negative. + gln = (gln_a[i] + gln_b[j] + gln_Na[i] + gln_Nb[j] + - gln_N - gln_nij[nij] - lgamma(a[i] - nij + 1) + - lgamma(b[j] - nij + 1) + - lgamma(N - a[i] - b[j] + nij + 1)) + term3 = exp(gln) + emi += (term1[nij] * term2 * term3) + return emi diff --git a/sklearn/metrics/cluster/setup.py b/sklearn/metrics/cluster/setup.py new file mode 100644 index 0000000000000..22debe88fe6ff --- /dev/null +++ b/sklearn/metrics/cluster/setup.py @@ -0,0 +1,23 @@ +import os + +import numpy +from numpy.distutils.misc_util import Configuration + + +def configuration(parent_package="", top_path=None): + config = Configuration("metrics/cluster", parent_package, top_path) + libraries = [] + if os.name == 'posix': + libraries.append('m') + config.add_extension("expected_mutual_info_fast", + sources=["expected_mutual_info_fast.c"], + include_dirs=[numpy.get_include()], + libraries=libraries) + + config.add_subpackage("tests") + + return config + +if __name__ == "__main__": + from numpy.distutils.core import setup + setup(**configuration().todict()) diff --git a/sklearn/metrics/cluster/supervised.py b/sklearn/metrics/cluster/supervised.py index cccf41f32aa48..b7cc4123afc90 100644 --- a/sklearn/metrics/cluster/supervised.py +++ b/sklearn/metrics/cluster/supervised.py @@ -5,20 +5,23 @@ """ # Authors: Olivier Grisel -# License: BSD Style. +# Wei LI +# Diego Molla +# License: BSD 3 clause from math import log -from scipy.misc import comb -from scipy.special import gammaln +from scipy.misc import comb +from scipy.sparse import coo_matrix import numpy as np -from ...utils.fixes import unique +from .expected_mutual_info_fast import expected_mutual_information +from ...utils.fixes import bincount -# the exact version if faster for k == 2: use it by default globally in -# this module instead of the float approximate variant def comb2(n): + # the exact version is faster for k == 2: use it by default globally in + # this module instead of the float approximate variant return comb(n, 2, exact=1) @@ -54,31 +57,31 @@ def contingency_matrix(labels_true, labels_pred, eps=None): eps: None or float If a float, that value is added to all values in the contingency - matrix. This helps to stop NaN propogation. - If None, nothing is adjusted. + matrix. This helps to stop NaN propagation. + If ``None``, nothing is adjusted. Returns ------- contingency: array, shape=[n_classes_true, n_classes_pred] - Matrix C such that C[i][j] is the number of samples in true class i and - in predicted class j. If eps is None, the dtype of this array will be - integer. If eps is given, the dtype will be float. + Matrix :math:`C` such that :math:`C_{i, j}` is the number of samples in + true class :math:`i` and in predicted class :math:`j`. If + ``eps is None``, the dtype of this array will be integer. If ``eps`` is + given, the dtype will be float. """ - classes = np.unique(labels_true) - clusters = np.unique(labels_pred) - # The cluster and class ids are not necessarily consecutive integers - # starting at 0 hence build a map - class_idx = dict((k, v) for v, k in enumerate(classes)) - cluster_idx = dict((k, v) for v, k in enumerate(clusters)) - # Build the contingency table + classes, class_idx = np.unique(labels_true, return_inverse=True) + clusters, cluster_idx = np.unique(labels_pred, return_inverse=True) n_classes = classes.shape[0] n_clusters = clusters.shape[0] - contingency = np.zeros((n_classes, n_clusters), dtype=np.int) - for c, k in zip(labels_true, labels_pred): - contingency[class_idx[c], cluster_idx[k]] += 1 + # Using coo_matrix to accelerate simple histogram calculation, + # i.e. bins are consecutive integers + # Currently, coo_matrix is faster than histogram2d for simple cases + contingency = coo_matrix((np.ones(class_idx.shape[0]), + (class_idx, cluster_idx)), + shape=(n_classes, n_clusters), + dtype=np.int).toarray() if eps is not None: - # Must be a float matrix to accept float eps - contingency = np.array(contingency, dtype='float') + eps + # don't use += as contingency is integer + contingency = contingency + eps return contingency @@ -167,10 +170,12 @@ def adjusted_rand_score(labels_true, labels_pred): n_samples = labels_true.shape[0] classes = np.unique(labels_true) clusters = np.unique(labels_pred) - # Special limit cases: no clustering since the data is not split. - # This is a perfect match hence return 1.0. + # Special limit cases: no clustering since the data is not split; + # or trivial clustering where each document is assigned a unique cluster. + # These are perfect matches hence return 1.0. if (classes.shape[0] == clusters.shape[0] == 1 - or classes.shape[0] == clusters.shape[0] == 0): + or classes.shape[0] == clusters.shape[0] == 0 + or classes.shape[0] == clusters.shape[0] == len(labels_true)): return 1.0 contingency = contingency_matrix(labels_true, labels_pred) @@ -186,7 +191,7 @@ def adjusted_rand_score(labels_true, labels_pred): def homogeneity_completeness_v_measure(labels_true, labels_pred): - """Compute the homogeneity and completeness and V-measure scores at once + """Compute the homogeneity and completeness and V-Measure scores at once Those metrics are based on normalized conditional entropy measures of the clustering labeling to evaluate given the knowledge of a Ground @@ -205,8 +210,8 @@ def homogeneity_completeness_v_measure(labels_true, labels_pred): a permutation of the class or cluster label values won't change the score values in any way. - V-Measure is furthermore symmetric: swapping `labels_true` and - `label_pred` will give the same score. This does not hold for + V-Measure is furthermore symmetric: swapping ``labels_true`` and + ``label_pred`` will give the same score. This does not hold for homogeneity and completeness. Parameters @@ -235,37 +240,17 @@ def homogeneity_completeness_v_measure(labels_true, labels_pred): v_measure_score """ labels_true, labels_pred = check_clusterings(labels_true, labels_pred) - n_samples = labels_true.shape[0] - - entropy_K_given_C = 0. - entropy_C_given_K = 0. - entropy_C = 0. - entropy_K = 0. - - classes = np.unique(labels_true) - clusters = np.unique(labels_pred) - - n_C = [float(np.sum(labels_true == c)) for c in classes] - n_K = [float(np.sum(labels_pred == k)) for k in clusters] - - for i in xrange(len(classes)): - entropy_C -= n_C[i] / n_samples * log(n_C[i] / n_samples) - for j in xrange(len(clusters)): - entropy_K -= n_K[j] / n_samples * log(n_K[j] / n_samples) + if len(labels_true) == 0: + return 1.0, 1.0, 1.0 - for i, c in enumerate(classes): - for j, k in enumerate(clusters): - # count samples at the intersection of class c and cluster k - n_CK = float(np.sum((labels_true == c) * (labels_pred == k))) + entropy_C = entropy(labels_true) + entropy_K = entropy(labels_pred) - if n_CK != 0.0: - # turn label assignments into contribution to entropies - entropy_C_given_K -= n_CK / n_samples * log(n_CK / n_K[j]) - entropy_K_given_C -= n_CK / n_samples * log(n_CK / n_C[i]) + MI = mutual_info_score(labels_true, labels_pred) - homogeneity = 1.0 - entropy_C_given_K / entropy_C if entropy_C else 1.0 - completeness = 1.0 - entropy_K_given_C / entropy_K if entropy_K else 1.0 + homogeneity = MI / (entropy_C) if entropy_C else 1.0 + completeness = MI / (entropy_K) if entropy_K else 1.0 if homogeneity + completeness == 0.0: v_measure_score = 0.0 @@ -286,8 +271,9 @@ def homogeneity_score(labels_true, labels_pred): a permutation of the class or cluster label values won't change the score value in any way. - This metric is not symmetric: switching `label_true` with `label_pred` - will return the completeness_score which will be different in general. + This metric is not symmetric: switching ``label_true`` with ``label_pred`` + will return the :func:`completeness_score` which will be different in + general. Parameters ---------- @@ -305,9 +291,9 @@ def homogeneity_score(labels_true, labels_pred): References ---------- - * Andrew Rosenberg and Julia Hirschberg `V-Measure: A conditional - entropy-based external cluster evaluation measure`, 2007 - http://acl.ldc.upenn.edu/D/D07/D07-1043.pdf + .. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A + conditional entropy-based external cluster evaluation measure + `_ See also -------- @@ -317,27 +303,31 @@ def homogeneity_score(labels_true, labels_pred): Examples -------- - Perfect labelings are homegenous:: + Perfect labelings are homogeneous:: >>> from sklearn.metrics.cluster import homogeneity_score >>> homogeneity_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 - Non-pefect labelings that futher split classes into more clusters can be + Non-perfect labelings that further split classes into more clusters can be perfectly homogeneous:: - >>> homogeneity_score([0, 0, 1, 1], [0, 0, 1, 2]) - 1.0 - >>> homogeneity_score([0, 0, 1, 1], [0, 1, 2, 3]) - 1.0 + >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 1, 2])) + ... # doctest: +ELLIPSIS + 1.0... + >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 2, 3])) + ... # doctest: +ELLIPSIS + 1.0... Clusters that include samples from different classes do not make for an homogeneous labeling:: - >>> homogeneity_score([0, 0, 1, 1], [0, 1, 0, 1]) - 0.0 - >>> homogeneity_score([0, 0, 1, 1], [0, 0, 0, 0]) - 0.0 + >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 0, 1])) + ... # doctest: +ELLIPSIS + 0.0... + >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 0, 0])) + ... # doctest: +ELLIPSIS + 0.0... """ return homogeneity_completeness_v_measure(labels_true, labels_pred)[0] @@ -353,8 +343,9 @@ def completeness_score(labels_true, labels_pred): a permutation of the class or cluster label values won't change the score value in any way. - This metric is not symmetric: switching `label_true` with `label_pred` - will return the homogeneity_score which will be different in general. + This metric is not symmetric: switching ``label_true`` with ``label_pred`` + will return the :func:`homogeneity_score` which will be different in + general. Parameters ---------- @@ -372,9 +363,9 @@ def completeness_score(labels_true, labels_pred): References ---------- - * Andrew Rosenberg and Julia Hirschberg `V-Measure: A conditional - entropy-based external cluster evaluation measure`, 2007 - http://acl.ldc.upenn.edu/D/D07/D07-1043.pdf + .. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A + conditional entropy-based external cluster evaluation measure + `_ See also -------- @@ -390,20 +381,20 @@ def completeness_score(labels_true, labels_pred): >>> completeness_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 - Non-pefect labelings that assign all classes members to the same clusters + Non-perfect labelings that assign all classes members to the same clusters are still complete:: - >>> completeness_score([0, 0, 1, 1], [0, 0, 0, 0]) + >>> print(completeness_score([0, 0, 1, 1], [0, 0, 0, 0])) 1.0 - >>> completeness_score([0, 1, 2, 3], [0, 0, 1, 1]) + >>> print(completeness_score([0, 1, 2, 3], [0, 0, 1, 1])) 1.0 - If classes members are splitted across different clusters, the + If classes members are split across different clusters, the assignment cannot be complete:: - >>> completeness_score([0, 0, 1, 1], [0, 1, 0, 1]) + >>> print(completeness_score([0, 0, 1, 1], [0, 1, 0, 1])) 0.0 - >>> completeness_score([0, 0, 0, 0], [0, 1, 2, 3]) + >>> print(completeness_score([0, 0, 0, 0], [0, 1, 2, 3])) 0.0 """ @@ -411,11 +402,11 @@ def completeness_score(labels_true, labels_pred): def v_measure_score(labels_true, labels_pred): - """V-Measure cluster labeling given a ground truth. + """V-measure cluster labeling given a ground truth. - This score is identical to normalized_mutual_info_score. + This score is identical to :func:`normalized_mutual_info_score`. - The V-Measure is the hormonic mean between homogeneity and completeness:: + The V-measure is the harmonic mean between homogeneity and completeness:: v = 2 * (homogeneity * completeness) / (homogeneity + completeness) @@ -423,8 +414,8 @@ def v_measure_score(labels_true, labels_pred): a permutation of the class or cluster label values won't change the score value in any way. - This metric is furthermore symmetric: switching `label_true` with - `label_pred` will return the same score value. This can be useful to + This metric is furthermore symmetric: switching ``label_true`` with + ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. @@ -438,15 +429,15 @@ def v_measure_score(labels_true, labels_pred): Returns ------- - completeness: float + v_measure: float score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling References ---------- - .. [Rosenberg2007] `V-Measure: A conditional entropy-based external cluster - evaluation measure Andrew Rosenberg and Julia Hirschberg, 2007` - http://acl.ldc.upenn.edu/D/D07/D07-1043.pdf + .. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A + conditional entropy-based external cluster evaluation measure + `_ See also -------- @@ -467,31 +458,37 @@ def v_measure_score(labels_true, labels_pred): Labelings that assign all classes members to the same clusters are complete be not homogeneous, hence penalized:: - >>> v_measure_score([0, 0, 1, 2], [0, 0, 1, 1]) # doctest: +ELLIPSIS + >>> print("%.6f" % v_measure_score([0, 0, 1, 2], [0, 0, 1, 1])) + ... # doctest: +ELLIPSIS 0.8... - >>> v_measure_score([0, 1, 2, 3], [0, 0, 1, 1]) # doctest: +ELLIPSIS + >>> print("%.6f" % v_measure_score([0, 1, 2, 3], [0, 0, 1, 1])) + ... # doctest: +ELLIPSIS 0.66... Labelings that have pure clusters with members coming from the same classes are homogeneous but un-necessary splits harms completeness and thus penalize V-measure as well:: - >>> v_measure_score([0, 0, 1, 1], [0, 0, 1, 2]) # doctest: +ELLIPSIS + >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 1, 2])) + ... # doctest: +ELLIPSIS 0.8... - >>> v_measure_score([0, 0, 1, 1], [0, 1, 2, 3]) # doctest: +ELLIPSIS + >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 1, 2, 3])) + ... # doctest: +ELLIPSIS 0.66... - If classes members are completly splitted across different clusters, - the assignment is totally in-complete, hence the v-measure is null:: + If classes members are completely split across different clusters, + the assignment is totally incomplete, hence the V-Measure is null:: - >>> v_measure_score([0, 0, 0, 0], [0, 1, 2, 3]) - 0.0 + >>> print("%.6f" % v_measure_score([0, 0, 0, 0], [0, 1, 2, 3])) + ... # doctest: +ELLIPSIS + 0.0... Clusters that include samples from totally different classes totally destroy the homogeneity of the labeling, hence:: - >>> v_measure_score([0, 0, 1, 1], [0, 0, 0, 0]) - 0.0 + >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 0, 0])) + ... # doctest: +ELLIPSIS + 0.0... """ return homogeneity_completeness_v_measure(labels_true, labels_pred)[2] @@ -500,11 +497,11 @@ def v_measure_score(labels_true, labels_pred): def mutual_info_score(labels_true, labels_pred, contingency=None): """Mutual Information between two clusterings - The Mutual Information is a measure of the similarity between two labels - of the same data. Where P(i) is the probability of a random sample occuring - in cluster U_i and P'(j) is the probability of a random sample occuring in - cluster V_j, the Mutual information between clusterings U and V is given - as: + The Mutual Information is a measure of the similarity between two labels of + the same data. Where :math:`P(i)` is the probability of a random sample + occurring in cluster :math:`U_i` and :math:`P'(j)` is the probability of a + random sample occurring in cluster :math:`V_j`, the Mutual Information + between clusterings :math:`U` and :math:`V` is given as: .. math:: @@ -517,8 +514,8 @@ def mutual_info_score(labels_true, labels_pred, contingency=None): a permutation of the class or cluster label values won't change the score value in any way. - This metric is furthermore symmetric: switching `label_true` with - `label_pred` will return the same score value. This can be useful to + This metric is furthermore symmetric: switching ``label_true`` with + ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. @@ -531,9 +528,9 @@ def mutual_info_score(labels_true, labels_pred, contingency=None): A clustering of the data into disjoint subsets. contingency: None or array, shape = [n_classes_true, n_classes_pred] - A contingency matrix given by the contingency_matrix function. - If value is None, it will be computed, otherwise the given value is - used, with labels_true and labels_pred ignored. + A contingency matrix given by the :func:`contingency_matrix` function. + If value is ``None``, it will be computed, otherwise the given value is + used, with ``labels_true`` and ``labels_pred`` ignored. Returns ------- @@ -549,25 +546,31 @@ def mutual_info_score(labels_true, labels_pred, contingency=None): labels_true, labels_pred = check_clusterings(labels_true, labels_pred) contingency = contingency_matrix(labels_true, labels_pred) contingency = np.array(contingency, dtype='float') - contingency /= np.sum(contingency) + contingency_sum = np.sum(contingency) pi = np.sum(contingency, axis=1) - pi /= np.sum(pi) pj = np.sum(contingency, axis=0) - pj /= np.sum(pj) outer = np.outer(pi, pj) nnz = contingency != 0.0 - mi = contingency[nnz] * np.log(contingency[nnz] / outer[nnz]) + # normalized contingency + contingency_nm = contingency[nnz] + log_contingency_nm = np.log(contingency_nm) + contingency_nm /= contingency_sum + # log(a / b) should be calculated as log(a) - log(b) for + # possible loss of precision + log_outer = -np.log(outer[nnz]) + log(pi.sum()) + log(pj.sum()) + mi = (contingency_nm * (log_contingency_nm - log(contingency_sum)) + + contingency_nm * log_outer) return mi.sum() def adjusted_mutual_info_score(labels_true, labels_pred): """Adjusted Mutual Information between two clusterings - Adjusted Mutual Information (AMI) is an adjustement of the Mutual + Adjusted Mutual Information (AMI) is an adjustment of the Mutual Information (MI) score to account for chance. It accounts for the fact that the MI is generally higher for two clusterings with a larger number of clusters, regardless of whether there is actually more information shared. - For two clusterings U and V, the AMI is given as:: + For two clusterings :math:`U` and :math:`V`, the AMI is given as:: AMI(U, V) = [MI(U, V) - E(MI(U, V))] / [max(H(U), H(V)) - E(MI(U, V))] @@ -575,8 +578,8 @@ def adjusted_mutual_info_score(labels_true, labels_pred): a permutation of the class or cluster label values won't change the score value in any way. - This metric is furthermore symmetric: switching `label_true` with - `label_pred` will return the same score value. This can be useful to + This metric is furthermore symmetric: switching ``label_true`` with + ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. @@ -593,8 +596,10 @@ def adjusted_mutual_info_score(labels_true, labels_pred): Returns ------- - ami: float - score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling + ami: float(upperlimited by 1.0) + The AMI returns a value of 1 when the two partitions are identical + (ie perfectly matched). Random partitions (independent labellings) have + an expected AMI around 0 on average hence can be negative. See also -------- @@ -613,7 +618,7 @@ def adjusted_mutual_info_score(labels_true, labels_pred): >>> adjusted_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 - If classes members are completly splitted across different clusters, + If classes members are completely split across different clusters, the assignment is totally in-complete, hence the AMI is null:: >>> adjusted_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) @@ -621,10 +626,10 @@ def adjusted_mutual_info_score(labels_true, labels_pred): References ---------- - .. [1] Vinh, Epps, and Bailey, (2010). Information Theoretic Measures for + .. [1] `Vinh, Epps, and Bailey, (2010). Information Theoretic Measures for Clusterings Comparison: Variants, Properties, Normalization and - Correction for Chance}, JMLR - http://jmlr.csail.mit.edu/papers/volume11/vinh10a/vinh10a.pdf + Correction for Chance, JMLR + `_ .. [2] `Wikipedia entry for the Adjusted Mutual Information `_ @@ -637,7 +642,7 @@ def adjusted_mutual_info_score(labels_true, labels_pred): # Special limit cases: no clustering since the data is not split. # This is a perfect match hence return 1.0. if (classes.shape[0] == clusters.shape[0] == 1 - or classes.shape[0] == clusters.shape[0] == 0): + or classes.shape[0] == clusters.shape[0] == 0): return 1.0 contingency = contingency_matrix(labels_true, labels_pred) contingency = np.array(contingency, dtype='float') @@ -657,17 +662,18 @@ def normalized_mutual_info_score(labels_true, labels_pred): Normalized Mutual Information (NMI) is an normalization of the Mutual Information (MI) score to scale the results between 0 (no mutual - information) and 1 (perfect correlation). + information) and 1 (perfect correlation). In this function, mutual + information is normalized by ``sqrt(H(labels_true) * H(labels_pred))`` This measure is not adjusted for chance. Therefore - ``adjusted_mustual_info_score`` might be preferred. + :func:`adjusted_mustual_info_score` might be preferred. This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. - This metric is furthermore symmetric: switching `label_true` with - `label_pred` will return the same score value. This can be useful to + This metric is furthermore symmetric: switching ``label_true`` with + ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. @@ -702,7 +708,7 @@ def normalized_mutual_info_score(labels_true, labels_pred): >>> normalized_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 - If classes members are completly splitted across different clusters, + If classes members are completely split across different clusters, the assignment is totally in-complete, hence the NMI is null:: >>> normalized_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) @@ -715,7 +721,7 @@ def normalized_mutual_info_score(labels_true, labels_pred): # Special limit cases: no clustering since the data is not split. # This is a perfect match hence return 1.0. if (classes.shape[0] == clusters.shape[0] == 1 - or classes.shape[0] == clusters.shape[0] == 0): + or classes.shape[0] == clusters.shape[0] == 0): return 1.0 contingency = contingency_matrix(labels_true, labels_pred) contingency = np.array(contingency, dtype='float') @@ -729,57 +735,14 @@ def normalized_mutual_info_score(labels_true, labels_pred): return nmi -def expected_mutual_information(contingency, n_samples): - """Calculate the expected mutual information for two labelings.""" - R, C = contingency.shape - N = float(n_samples) - a = np.sum(contingency, axis=1, dtype='int') - b = np.sum(contingency, axis=0, dtype='int') - # There are three major terms to the EMI equation, which are multiplied to - # and then summed over varying nij values. - # While nijs[0] will never be used, having it simplifies the indexing. - nijs = np.arange(0, max(np.max(a), np.max(b)) + 1, dtype='float') - nijs[0] = 1 # Stops divide by zero warnings. As its not used, no issue. - # term1 is nij / N - term1 = nijs / N - # term2 is log((N*nij) / (a * b)) == log(N * nij) - log(a * b) - # term2 uses the outer product - log_ab_outer = np.log(np.outer(a, b)) - # term2 uses N * nij - log_Nnij = np.log(N * nijs) - # term3 is large, and involved many factorials. Calculate these in log - # space to stop overflows. - gln_a = gammaln(a + 1) - gln_b = gammaln(b + 1) - gln_Na = gammaln(N - a + 1) - gln_Nb = gammaln(N - b + 1) - gln_N = gammaln(N + 1) - gln_nij = gammaln(nijs + 1) - # start and end values for nij terms for each summation. - start = np.array([[v - N + w for w in b] for v in a], dtype='int') - start = np.maximum(start, 1) - end = np.minimum(np.resize(a, (C, R)).T, np.resize(b, (R, C))) + 1 - # emi itself is a summation over the various values. - emi = 0 - for i in range(R): - for j in range(C): - for nij in range(start[i][j], end[i][j]): - term2 = log_Nnij[nij] - log_ab_outer[i][j] - # Numerators are positive, denominators are negative. - gln = (gln_a[i] + gln_b[j] + gln_Na[i] + gln_Nb[j] - - gln_N - gln_nij[nij] - gammaln(a[i] - nij + 1) - - gammaln(b[j] - nij + 1) - - gammaln(N - a[i] - b[j] + nij + 1)) - term3 = np.exp(gln) - # Add the product of all terms. - emi += (term1[nij] * term2 * term3) - return emi - - def entropy(labels): """Calculates the entropy for a labeling.""" - label_idx = unique(labels, return_inverse=True)[1] - pi = np.bincount(label_idx).astype(np.float) + if len(labels) == 0: + return 1.0 + label_idx = np.unique(labels, return_inverse=True)[1] + pi = bincount(label_idx).astype(np.float) pi = pi[pi > 0] - pi /= np.sum(pi) - return -np.sum(pi * np.log(pi)) + pi_sum = np.sum(pi) + # log(a / b) should be calculated as log(a) - log(b) for + # possible loss of precision + return -np.sum((pi / pi_sum) * (np.log(pi) - log(pi_sum))) diff --git a/sklearn/metrics/cluster/tests/test_bicluster.py b/sklearn/metrics/cluster/tests/test_bicluster.py new file mode 100644 index 0000000000000..1ca98b744a7b1 --- /dev/null +++ b/sklearn/metrics/cluster/tests/test_bicluster.py @@ -0,0 +1,50 @@ +"""Testing for bicluster metrics module""" + +import numpy as np + +from sklearn.utils.testing import assert_equal, assert_almost_equal + +from sklearn.metrics.cluster.bicluster import _jaccard +from sklearn.metrics import consensus_score + + +def test_jaccard(): + a1 = np.array([True, True, False, False]) + a2 = np.array([True, True, True, True]) + a3 = np.array([False, True, True, False]) + a4 = np.array([False, False, True, True]) + + assert_equal(_jaccard(a1, a1, a1, a1), 1) + assert_equal(_jaccard(a1, a1, a2, a2), 0.25) + assert_equal(_jaccard(a1, a1, a3, a3), 1.0 / 7) + assert_equal(_jaccard(a1, a1, a4, a4), 0) + + +def test_consensus_score(): + a = [[True, True, False, False], + [False, False, True, True]] + b = a[::-1] + + assert_equal(consensus_score((a, a), (a, a)), 1) + assert_equal(consensus_score((a, a), (b, b)), 1) + assert_equal(consensus_score((a, b), (a, b)), 1) + assert_equal(consensus_score((a, b), (b, a)), 1) + + assert_equal(consensus_score((a, a), (b, a)), 0) + assert_equal(consensus_score((a, a), (a, b)), 0) + assert_equal(consensus_score((b, b), (a, b)), 0) + assert_equal(consensus_score((b, b), (b, a)), 0) + + +def test_consensus_score_issue2445(): + ''' Different number of biclusters in A and B''' + a_rows = np.array([[True, True, False, False], + [False, False, True, True], + [False, False, False, True]]) + a_cols = np.array([[True, True, False, False], + [False, False, True, True], + [False, False, False, True]]) + idx = [0, 2] + s = consensus_score((a_rows, a_cols), (a_rows[idx], a_cols[idx])) + # B contains 2 of the 3 biclusters in A, so score should be 2/3 + assert_almost_equal(s, 2.0/3.0) diff --git a/sklearn/metrics/cluster/tests/test_supervised.py b/sklearn/metrics/cluster/tests/test_supervised.py index ec651d278501e..6f80d8790bdba 100644 --- a/sklearn/metrics/cluster/tests/test_supervised.py +++ b/sklearn/metrics/cluster/tests/test_supervised.py @@ -12,6 +12,7 @@ from sklearn.metrics.cluster import contingency_matrix from sklearn.metrics.cluster import entropy +from sklearn.utils.testing import assert_raise_message from nose.tools import assert_almost_equal from nose.tools import assert_equal from numpy.testing import assert_array_almost_equal @@ -27,15 +28,6 @@ ] -def assert_raise_message(exception, message, callable, *args, **kwargs): - """Helper function to test error messages in exceptions""" - try: - callable(*args, **kwargs) - raise AssertionError("Should have raised %r" % exception(message)) - except exception as e: - assert str(e) == message - - def test_error_messages_on_wrong_input(): for score_func in score_funcs: expected = ('labels_true and labels_pred must have same size,' @@ -43,11 +35,11 @@ def test_error_messages_on_wrong_input(): assert_raise_message(ValueError, expected, score_func, [0, 1], [1, 1, 1]) - expected = "labels_true must be 1D: shape is (2, 2)" + expected = "labels_true must be 1D: shape is (2" assert_raise_message(ValueError, expected, score_func, [[0, 1], [1, 0]], [1, 1, 1]) - expected = "labels_pred must be 1D: shape is (2, 2)" + expected = "labels_pred must be 1D: shape is (2" assert_raise_message(ValueError, expected, score_func, [0, 1, 0], [[1, 1], [0, 0]]) @@ -59,6 +51,8 @@ def test_perfect_matches(): assert_equal(score_func([0, 0, 0], [0, 0, 0]), 1.0) assert_equal(score_func([0, 1, 0], [42, 7, 42]), 1.0) assert_equal(score_func([0., 1., 0.], [42., 7., 42.]), 1.0) + assert_equal(score_func([0., 1., 2.], [42., 7., 2.]), 1.0) + assert_equal(score_func([0, 1, 2], [42, 7, 2]), 1.0) def test_homogeneous_but_not_complete_labeling(): @@ -167,3 +161,38 @@ def test_adjusted_mutual_info_score(): def test_entropy(): ent = entropy([0, 0, 42.]) assert_almost_equal(ent, 0.6365141, 5) + assert_almost_equal(entropy([]), 1) + + +def test_contingency_matrix(): + labels_a = np.array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]) + labels_b = np.array([1, 1, 1, 1, 2, 1, 2, 2, 2, 2, 3, 1, 3, 3, 3, 2, 2]) + C = contingency_matrix(labels_a, labels_b) + C2 = np.histogram2d(labels_a, labels_b, + bins=(np.arange(1, 5), + np.arange(1, 5)))[0] + assert_array_almost_equal(C, C2) + C = contingency_matrix(labels_a, labels_b, eps=.1) + assert_array_almost_equal(C, C2 + .1) + + +def test_exactly_zero_info_score(): + """Check numerical stability when information is exactly zero""" + for i in np.logspace(1, 4, 4).astype(np.int): + labels_a, labels_b = np.ones(i, dtype=np.int),\ + np.arange(i, dtype=np.int) + assert_equal(normalized_mutual_info_score(labels_a, labels_b), 0.0) + assert_equal(v_measure_score(labels_a, labels_b), 0.0) + assert_equal(adjusted_mutual_info_score(labels_a, labels_b), 0.0) + assert_equal(normalized_mutual_info_score(labels_a, labels_b), 0.0) + + +def test_v_measure_and_mutual_information(seed=36): + """Check relation between v_measure, entropy and mutual information""" + for i in np.logspace(1, 4, 4).astype(np.int): + random_state = np.random.RandomState(seed) + labels_a, labels_b = random_state.random_integers(0, 10, i),\ + random_state.random_integers(0, 10, i) + assert_almost_equal(v_measure_score(labels_a, labels_b), + 2.0 * mutual_info_score(labels_a, labels_b) / + (entropy(labels_a) + entropy(labels_b)), 0) diff --git a/sklearn/metrics/cluster/tests/test_unsupervised.py b/sklearn/metrics/cluster/tests/test_unsupervised.py index c586d9917bf69..39dfa4b2f9426 100644 --- a/sklearn/metrics/cluster/tests/test_unsupervised.py +++ b/sklearn/metrics/cluster/tests/test_unsupervised.py @@ -1,10 +1,11 @@ import numpy as np from scipy.sparse import csr_matrix -from .... import datasets -from ..unsupervised import silhouette_score -from ... import pairwise_distances -from nose.tools import assert_false +from sklearn import datasets +from sklearn.metrics.cluster.unsupervised import silhouette_score +from sklearn.metrics import pairwise_distances +from sklearn.utils.testing import assert_false, assert_almost_equal +from sklearn.utils.testing import assert_raises_regexp def test_silhouette(): @@ -19,11 +20,17 @@ def test_silhouette(): assert(silhouette > 0) # Test without calculating D silhouette_metric = silhouette_score(X, y, metric='euclidean') - assert(silhouette == silhouette_metric) + assert_almost_equal(silhouette, silhouette_metric) # Test with sampling silhouette = silhouette_score(D, y, metric='precomputed', - sample_size=int(X.shape[0] / 2)) + sample_size=int(X.shape[0] / 2), + random_state=0) + silhouette_metric = silhouette_score(X, y, metric='euclidean', + sample_size=int(X.shape[0] / 2), + random_state=0) assert(silhouette > 0) + assert(silhouette_metric > 0) + assert_almost_equal(silhouette_metric, silhouette) # Test with sparse X X_sparse = csr_matrix(X) D = pairwise_distances(X_sparse, metric='euclidean') @@ -43,3 +50,23 @@ def test_no_nan(): D = np.random.RandomState(0).rand(len(labels), len(labels)) silhouette = silhouette_score(D, labels, metric='precomputed') assert_false(np.isnan(silhouette)) + + +def test_correct_labelsize(): + """Assert 1 < n_labels < n_samples""" + dataset = datasets.load_iris() + X = dataset.data + + # n_labels = n_samples + y = np.arange(X.shape[0]) + assert_raises_regexp(ValueError, + 'Number of labels is %d\. Valid values are 2 ' + 'to n_samples - 1 \(inclusive\)' % len(np.unique(y)), + silhouette_score, X, y) + + # n_labels = 1 + y = np.zeros(X.shape[0]) + assert_raises_regexp(ValueError, + 'Number of labels is %d\. Valid values are 2 ' + 'to n_samples - 1 \(inclusive\)' % len(np.unique(y)), + silhouette_score, X, y) diff --git a/sklearn/metrics/cluster/unsupervised.py b/sklearn/metrics/cluster/unsupervised.py index 93767c721f2bc..d4249c9ea13ff 100644 --- a/sklearn/metrics/cluster/unsupervised.py +++ b/sklearn/metrics/cluster/unsupervised.py @@ -2,7 +2,7 @@ # Authors: Robert Layton # -# License: BSD Style. +# License: BSD 3 clause import numpy as np @@ -10,18 +10,20 @@ from ..pairwise import pairwise_distances -def silhouette_score(X, labels, metric='euclidean', - sample_size=None, random_state=None, **kwds): +def silhouette_score(X, labels, metric='euclidean', sample_size=None, + random_state=None, **kwds): """Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster - distance (a) and the mean nearest-cluster distance (b) for each sample. - The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. - To clarrify, b is the distance between a sample and the nearest cluster - that b is not a part of. + distance (``a``) and the mean nearest-cluster distance (``b``) for each + sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, + b)``. To clarify, ``b`` is the distance between a sample and the nearest + cluster that the sample is not a part of. + Note that Silhouette Coefficent is only defined if number of labels + is 2 <= n_labels <= n_samples - 1. - This function returns the mean Silhoeutte Coefficient over all samples. - To obtain the values for each sample, use silhouette_samples + This function returns the mean Silhouette Coefficient over all samples. + To obtain the values for each sample, use :func:`silhouette_samples`. The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters. Negative values generally indicate that a sample has @@ -34,17 +36,18 @@ def silhouette_score(X, labels, metric='euclidean', Array of pairwise distances between samples, or a feature array. labels : array, shape = [n_samples] - label values for each sample + Predicted labels for each sample. metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options - allowed by metrics.pairwise.pairwise_distances. If X is the distance - array itself, use "precomputed" as the metric. + allowed by :func:`metrics.pairwise.pairwise_distances + `. If X is the distance + array itself, use ``metric="precomputed"``. sample_size : int or None The size of the sample to use when computing the Silhouette - Coefficient. If sample_size is None, no sampling is used. + Coefficient. If ``sample_size is None``, no sampling is used. random_state : integer or numpy.RandomState, optional The generator used to initialize the centers. If an integer is @@ -64,13 +67,21 @@ def silhouette_score(X, labels, metric='euclidean', References ---------- - Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the - Interpretation and Validation of Cluster Analysis". Computational - and Applied Mathematics 20: 53-65. doi:10.1016/0377-0427(87)90125-7. + .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the + Interpretation and Validation of Cluster Analysis". Computational + and Applied Mathematics 20: 53-65. + `_ - http://en.wikipedia.org/wiki/Silhouette_(clustering) + .. [2] `Wikipedia entry on the Silhouette Coefficient + `_ """ + n_labels = len(np.unique(labels)) + n_samples = X.shape[0] + if not 1 < n_labels < n_samples: + raise ValueError("Number of labels is %d. Valid values are 2 " + "to n_samples - 1 (inclusive)" % n_labels) + if sample_size is not None: random_state = check_random_state(random_state) indices = random_state.permutation(X.shape[0])[:sample_size] @@ -84,17 +95,20 @@ def silhouette_score(X, labels, metric='euclidean', def silhouette_samples(X, labels, metric='euclidean', **kwds): """Compute the Silhouette Coefficient for each sample. - The Silhoeutte Coefficient is a measure of how well samples are clustered + The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to be dense, where samples in the same cluster are similar to each other, and well separated, where samples in different clusters are not very similar to each other. The Silhouette Coefficient is calculated using the mean intra-cluster - distance (a) and the mean nearest-cluster distance (b) for each sample. - The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. + distance (``a``) and the mean nearest-cluster distance (``b``) for each + sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, + b)``. + Note that Silhouette Coefficent is only defined if number of labels + is 2 <= n_labels <= n_samples - 1. - This function returns the Silhoeutte Coefficient for each sample. + This function returns the Silhouette Coefficient for each sample. The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters. @@ -111,12 +125,12 @@ def silhouette_samples(X, labels, metric='euclidean', **kwds): metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options - allowed by metrics.pairwise.pairwise_distances. If X is the distance - array itself, use "precomputed" as the metric. + allowed by :func:`sklearn.metrics.pairwise.pairwise_distances`. If X is + the distance array itself, use "precomputed" as the metric. `**kwds` : optional keyword parameters Any further parameters are passed directly to the distance function. - If using a scipy.spatial.distance metric, the parameters are still + If using a ``scipy.spatial.distance`` metric, the parameters are still metric dependent. See the scipy docs for usage examples. Returns @@ -127,11 +141,13 @@ def silhouette_samples(X, labels, metric='euclidean', **kwds): References ---------- - Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the - Interpretation and Validation of Cluster Analysis". Computational - and Applied Mathematics 20: 53-65. doi:10.1016/0377-0427(87)90125-7. + .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the + Interpretation and Validation of Cluster Analysis". Computational + and Applied Mathematics 20: 53-65. + `_ - http://en.wikipedia.org/wiki/Silhouette_(clustering) + .. [2] `Wikipedia entry on the Silhouette Coefficient + `_ """ distances = pairwise_distances(X, metric=metric, **kwds) diff --git a/sklearn/metrics/metrics.py b/sklearn/metrics/metrics.py index de17cbc4857aa..72fec05174241 100644 --- a/sklearn/metrics/metrics.py +++ b/sklearn/metrics/metrics.py @@ -1,1061 +1,33 @@ -"""Utilities to evaluate the predictive performance of models - -Functions named as *_score return a scalar value to maximize: the higher the -better - -Function named as *_loss return a scalar value to minimize: the lower the -better -""" - -# Authors: Alexandre Gramfort -# Mathieu Blondel -# Olivier Grisel -# License: BSD Style. - -import numpy as np - -from ..utils import check_arrays - - -def unique_labels(*lists_of_labels): - """Extract an ordered array of unique labels""" - labels = set() - for l in lists_of_labels: - if hasattr(l, 'ravel'): - l = l.ravel() - labels |= set(l) - return np.unique(sorted(labels)) - - -def confusion_matrix(y_true, y_pred, labels=None): - """Compute confusion matrix to evaluate the accuracy of a classification - - By definition a confusion matrix cm is such that cm[i, j] is equal - to the number of observations known to be in group i but predicted - to be in group j. - - Parameters - ---------- - y_true : array, shape = [n_samples] - true targets - - y_pred : array, shape = [n_samples] - estimated targets - - labels : array, shape = [n_classes] - lists all labels occuring in the dataset. - If none is given, those that appear at least once - in y_true or y_pred are used. - - Returns - ------- - CM : array, shape = [n_classes, n_classes] - confusion matrix - - References - ---------- - http://en.wikipedia.org/wiki/Confusion_matrix - """ - if labels is None: - labels = unique_labels(y_true, y_pred) - else: - labels = np.asarray(labels, dtype=np.int) - - n_labels = labels.size - label_to_ind = dict((y, x) for x, y in enumerate(labels)) - - if n_labels >= 15: - CM = np.zeros((n_labels, n_labels), dtype=np.long) - for yt, yp in zip(y_true, y_pred): - CM[label_to_ind[yt], label_to_ind[yp]] += 1 - else: - CM = np.empty((n_labels, n_labels), dtype=np.long) - for i, label_i in enumerate(labels): - for j, label_j in enumerate(labels): - CM[i, j] = np.sum( - np.logical_and(y_true == label_i, y_pred == label_j)) - - return CM - - -def roc_curve(y_true, y_score): - """compute Receiver operating characteristic (ROC) - - Note: this implementation is restricted to the binary classification task. - - Parameters - ---------- - - y_true : array, shape = [n_samples] - true binary labels - - y_score : array, shape = [n_samples] - target scores, can either be probability estimates of - the positive class, confidence values, or binary decisions. - - Returns - ------- - fpr : array, shape = [>2] - False Positive Rates - - tpr : array, shape = [>2] - True Positive Rates - - thresholds : array, shape = [>2] - Thresholds on y_score used to compute fpr and tpr. - - *Note*: Since the thresholds are sorted from low to high values, - they are reversed upon returning them to ensure they - correspond to both fpr and tpr, which are sorted in reversed order - during their calculation. - - - Examples - -------- - >>> import numpy as np - >>> from sklearn import metrics - >>> y = np.array([1, 1, 2, 2]) - >>> scores = np.array([0.1, 0.4, 0.35, 0.8]) - >>> fpr, tpr, thresholds = metrics.roc_curve(y, scores) - >>> fpr - array([ 0. , 0.5, 0.5, 1. ]) - - References - ---------- - http://en.wikipedia.org/wiki/Receiver_operating_characteristic - - """ - y_true = np.ravel(y_true) - classes = np.unique(y_true) - - # ROC only for binary classification - if classes.shape[0] != 2: - raise ValueError("ROC is defined for binary classification only") - - y_score = np.ravel(y_score) - - n_pos = float(np.sum(y_true == classes[1])) # nb of true positive - n_neg = float(np.sum(y_true == classes[0])) # nb of true negative - - thresholds = np.unique(y_score) - neg_value, pos_value = classes[0], classes[1] - - tpr = np.empty(thresholds.size, dtype=np.float) # True positive rate - fpr = np.empty(thresholds.size, dtype=np.float) # False positive rate - - # Build tpr/fpr vector - current_pos_count = current_neg_count = sum_pos = sum_neg = idx = 0 - - signal = np.c_[y_score, y_true] - sorted_signal = signal[signal[:, 0].argsort(), :][::-1] - last_score = sorted_signal[0][0] - for score, value in sorted_signal: - if score == last_score: - if value == pos_value: - current_pos_count += 1 - else: - current_neg_count += 1 - else: - tpr[idx] = (sum_pos + current_pos_count) / n_pos - fpr[idx] = (sum_neg + current_neg_count) / n_neg - sum_pos += current_pos_count - sum_neg += current_neg_count - current_pos_count = 1 if value == pos_value else 0 - current_neg_count = 1 if value == neg_value else 0 - idx += 1 - last_score = score - else: - tpr[-1] = (sum_pos + current_pos_count) / n_pos - fpr[-1] = (sum_neg + current_neg_count) / n_neg - - # hard decisions, add (0,0) - if fpr.shape[0] == 2: - fpr = np.array([0.0, fpr[0], fpr[1]]) - tpr = np.array([0.0, tpr[0], tpr[1]]) - # trivial decisions, add (0,0) and (1,1) - elif fpr.shape[0] == 1: - fpr = np.array([0.0, fpr[0], 1.0]) - tpr = np.array([0.0, tpr[0], 1.0]) - - return fpr, tpr, thresholds[::-1] - - -def average_precision_score(y_true, y_score): - """Compute average precision (AP) from prediction scores. - - This score corresponds to the area under the precision-recall curve. - - Note: this implementation is restricted to the binary classification task. - - Parameters - ---------- - - y_true : array, shape = [n_samples] - true binary labels - - y_score : array, shape = [n_samples] - target scores, can either be probability estimates of - the positive class, confidence values, or binary decisions. - - Returns - ------- - average_precision : float - - References - ---------- - http://en.wikipedia.org/wiki/Information_retrieval#Average_precision - - - See also - -------- - auc_score: Area under the ROC curve - """ - precision, recall, thresholds = precision_recall_curve(y_true, y_score) - - return auc(recall, precision) - - -def auc_score(y_true, y_score): - """Compute Area Under the Curve (AUC) from prediction scores. - - Note: this implementation is restricted to the binary classification task. - - Parameters - ---------- - - y_true : array, shape = [n_samples] - true binary labels - - y_score : array, shape = [n_samples] - target scores, can either be probability estimates of - the positive class, confidence values, or binary decisions. - - Returns - ------- - auc : float - - References - ---------- - http://en.wikipedia.org/wiki/Receiver_operating_characteristic - - See also - -------- - average_precision_score: Area under the precision-recall curve - """ - - fpr, tpr, tresholds = roc_curve(y_true, y_score) - return auc(fpr, tpr) - - -def auc(x, y): - """Compute Area Under the Curve (AUC) using the trapezoidal rule - - This is a general fuction, given points on a curve. - For computing the area under the ROC-curve, see auc_score. - - Parameters - ---------- - x : array, shape = [n] - x coordinates - - y : array, shape = [n] - y coordinates - - Returns - ------- - auc : float - - Examples - -------- - >>> import numpy as np - >>> from sklearn import metrics - >>> y = np.array([1, 1, 2, 2]) - >>> pred = np.array([0.1, 0.4, 0.35, 0.8]) - >>> fpr, tpr, thresholds = metrics.roc_curve(y, pred) - >>> metrics.auc(fpr, tpr) - 0.75 - - See also - -------- - auc_score Computes the area under the ROC curve - - """ - x, y = check_arrays(x, y) - if x.shape[0] != y.shape[0]: - raise ValueError('x and y should have the same shape' - ' to compute area under curve,' - ' but x.shape = %s and y.shape = %s.' - % (x.shape, y.shape)) - if x.shape[0] < 2: - raise ValueError('At least 2 points are needed to compute' - ' area under curve, but x.shape = %s' % x.shape) - - # reorder the data points according to the x axis and using y to break ties - x, y = np.array(sorted(points for points in zip(x, y))).T - - h = np.diff(x) - area = np.sum(h * (y[1:] + y[:-1])) / 2.0 - return area - - -def precision_score(y_true, y_pred, labels=None, pos_label=1, - average='weighted'): - """Compute the precision - - The precision is the ratio :math:`tp / (tp + fp)` where tp is the - number of true positives and fp the number of false positives. The - precision is intuitively the ability of the classifier not to - label as positive a sample that is negative. - - The best value is 1 and the worst value is 0. - - Parameters - ---------- - y_true : array, shape = [n_samples] - True targets - - y_pred : array, shape = [n_samples] - Predicted targets - - labels : array - Integer array of labels - - pos_label : int - In the binary classification case, give the label of the positive - class (default is 1). Everything else but 'pos_label' - is considered to belong to the negative class. - Set to None in the case of multiclass classification. - - average : string, [None, 'micro', 'macro', 'weighted'(default)] - In the multiclass classification case, this determines the - type of averaging performed on the data. - - macro: - Average over classes (does not take imbalance into account). - micro: - Average over instances (takes imbalance into account). - This implies that ``precision == recall == f1`` - weighted: - Average weighted by support (takes imbalance into account). - Can result in f1 score that is not between precision and recall. - - Returns - ------- - precision : float - Precision of the positive class in binary classification or - weighted average of the precision of each class for the - multiclass task - - """ - p, _, _, _ = precision_recall_fscore_support(y_true, y_pred, - labels=labels, - pos_label=pos_label, - average=average) - return p - - -def recall_score(y_true, y_pred, labels=None, pos_label=1, average='weighted'): - """Compute the recall - - The recall is the ratio :math:`tp / (tp + fn)` where tp is the number of - true positives and fn the number of false negatives. The recall is - intuitively the ability of the classifier to find all the positive samples. - - The best value is 1 and the worst value is 0. - - Parameters - ---------- - y_true : array, shape = [n_samples] - True targets - - y_pred : array, shape = [n_samples] - Predicted targets - - labels : array - Integer array of labels - - pos_label : int - In the binary classification case, give the label of the positive - class (default is 1). Everything else but 'pos_label' - is considered to belong to the negative class. - Set to None in the case of multiclass classification. - - average : string, [None, 'micro', 'macro', 'weighted'(default)] - In the multiclass classification case, this determines the - type of averaging performed on the data. - - macro: - Average over classes (does not take imbalance into account). - micro: - Average over instances (takes imbalance into account). - This implies that ``precision == recall == f1`` - weighted: - Average weighted by support (takes imbalance into account). - Can result in f1 score that is not between precision and recall. - - Returns - ------- - recall : float - Recall of the positive class in binary classification or weighted - average of the recall of each class for the multiclass task. - - """ - _, r, _, _ = precision_recall_fscore_support(y_true, y_pred, - labels=labels, - pos_label=pos_label, - average=average) - return r - - -def fbeta_score(y_true, y_pred, beta, labels=None, pos_label=1, - average='weighted'): - """Compute fbeta score - - The F_beta score is the weighted harmonic mean of precision and recall, - reaching its optimal value at 1 and its worst value at 0. - - The beta parameter determines the weight of precision in the combined - score. ``beta < 1`` lends more weight to precision, while ``beta > 1`` - favors precision (``beta == 0`` considers only precision, ``beta == inf`` - only recall). - - Parameters - ---------- - y_true : array, shape = [n_samples] - True targets - - y_pred : array, shape = [n_samples] - Predicted targets - - beta: float - Weight of precision in harmonic mean. - - labels : array - Integer array of labels - - pos_label : int - In the binary classification case, give the label of the positive - class (default is 1). Everything else but 'pos_label' - is considered to belong to the negative class. - Set to None in the case of multiclass classification. - - average : string, [None, 'micro', 'macro', 'weighted'(default)] - In the multiclass classification case, this determines the - type of averaging performed on the data. - - macro: - Average over classes (does not take imbalance into account). - micro: - Average over instances (takes imbalance into account). - This implies that ``precision == recall == f1`` - weighted: - Average weighted by support (takes imbalance into account). - Can result in f1 score that is not between precision and recall. - - Returns - ------- - fbeta_score : float - fbeta_score of the positive class in binary classification or weighted - average of the fbeta_score of each class for the multiclass task. - - References - ---------- - R. Baeza-Yates and B. Ribeiro-Neto (2011). Modern Information Retrieval. - Addison Wesley, pp. 327-328. - - http://en.wikipedia.org/wiki/F1_score - - """ - _, _, f, _ = precision_recall_fscore_support(y_true, y_pred, - beta=beta, - labels=labels, - pos_label=pos_label, - average=average) - return f - - -def f1_score(y_true, y_pred, labels=None, pos_label=1, average='weighted'): - """Compute f1 score - - The F1 score can be interpreted as a weighted average of the precision - and recall, where an F1 score reaches its best value at 1 and worst - score at 0. The relative contribution of precision and recall to the f1 - score are equal. The formular for the F_1 score is:: - - F_1 = 2 * (precision * recall) / (precision + recall) - - See: http://en.wikipedia.org/wiki/F1_score - - In the multi-class case, this is the weighted average of the f1-score of - each class. - - Parameters - ---------- - y_true : array, shape = [n_samples] - True targets - - y_pred : array, shape = [n_samples] - Predicted targets - - labels : array - Integer array of labels - - pos_label : int - In the binary classification case, give the label of the positive - class (default is 1). Everything else but 'pos_label' - is considered to belong to the negative class. - Set to None in the case of multiclass classification. - - average : string, [None, 'micro', 'macro', 'weighted'(default)] - In the multiclass classification case, this determines the - type of averaging performed on the data. - - macro: - Average over classes (does not take imbalance into account). - micro: - Average over instances (takes imbalance into account). - This implies that ``precision == recall == f1`` - weighted: - Average weighted by support (takes imbalance into account). - Can result in f1 score that is not between precision and recall. - - Returns - ------- - f1_score : float - f1_score of the positive class in binary classification or weighted - average of the f1_scores of each class for the multiclass task - - References - ---------- - http://en.wikipedia.org/wiki/F1_score - - """ - return fbeta_score(y_true, y_pred, 1, labels=labels, - pos_label=pos_label, average=average) - - -def precision_recall_fscore_support(y_true, y_pred, beta=1.0, labels=None, - pos_label=1, average=None): - """Compute precisions, recalls, f-measures and support for each class - - The precision is the ratio :math:`tp / (tp + fp)` where tp is the number of - true positives and fp the number of false positives. The precision is - intuitively the ability of the classifier not to label as positive a sample - that is negative. - - The recall is the ratio :math:`tp / (tp + fn)` where tp is the number of - true positives and fn the number of false negatives. The recall is - intuitively the ability of the classifier to find all the positive samples. - - The F_beta score can be interpreted as a weighted harmonic mean of - the precision and recall, where an F_beta score reaches its best - value at 1 and worst score at 0. - - The F_beta score weights recall beta as much as precision. beta = 1.0 means - recall and precsion are equally important. - - The support is the number of occurrences of each class in y_true. - - If pos_label is None, this function returns the average precision, recall - and f-measure if `average` is one of 'micro', 'macro', 'weighted'. - - Parameters - ---------- - y_true : array, shape = [n_samples] - True targets - - y_pred : array, shape = [n_samples] - Predicted targets - - beta : float, 1.0 by default - The strength of recall versus precision in the f-score. - - labels : array - Integer array of labels - - pos_label : int - In the binary classification case, give the label of the positive - class (default is 1). Everything else but 'pos_label' - is considered to belong to the negative class. - Set to None in the case of multiclass classification. - - average : string, [None, 'micro', 'macro', 'weighted'(default)] - In the multiclass classification case, this determines the - type of averaging performed on the data. - - macro: - Average over classes (does not take imbalance into account). - micro: - Average over instances (takes imbalance into account). - This implies that ``precision == recall == f1`` - weighted: - Average weighted by support (takes imbalance into account). - Can result in f1 score that is not between precision and recall. - - Returns - ------- - precision: array, shape = [n_unique_labels], dtype = np.double - recall: array, shape = [n_unique_labels], dtype = np.double - f1_score: array, shape = [n_unique_labels], dtype = np.double - support: array, shape = [n_unique_labels], dtype = np.long - - References - ---------- - http://en.wikipedia.org/wiki/Precision_and_recall - - """ - if beta <= 0: - raise ValueError("beta should be >0 in the F-beta score") - - y_true, y_pred = check_arrays(y_true, y_pred) - if labels is None: - labels = unique_labels(y_true, y_pred) - else: - labels = np.asarray(labels, dtype=np.int) - - n_labels = labels.size - true_pos = np.zeros(n_labels, dtype=np.double) - false_pos = np.zeros(n_labels, dtype=np.double) - false_neg = np.zeros(n_labels, dtype=np.double) - support = np.zeros(n_labels, dtype=np.long) - - for i, label_i in enumerate(labels): - true_pos[i] = np.sum(y_pred[y_true == label_i] == label_i) - false_pos[i] = np.sum(y_pred[y_true != label_i] == label_i) - false_neg[i] = np.sum(y_pred[y_true == label_i] != label_i) - support[i] = np.sum(y_true == label_i) - - try: - # oddly, we may get an "invalid" rather than a "divide" error here - old_err_settings = np.seterr(divide='ignore', invalid='ignore') - - # precision and recall - precision = true_pos / (true_pos + false_pos) - recall = true_pos / (true_pos + false_neg) - - # handle division by 0.0 in precision and recall - precision[(true_pos + false_pos) == 0.0] = 0.0 - recall[(true_pos + false_neg) == 0.0] = 0.0 - - # fbeta score - beta2 = beta ** 2 - fscore = (1 + beta2) * (precision * recall) / ( - beta2 * precision + recall) - - # handle division by 0.0 in fscore - fscore[(precision + recall) == 0.0] = 0.0 - finally: - np.seterr(**old_err_settings) - - if not average: - return precision, recall, fscore, support - - elif n_labels == 2: - if pos_label not in labels: - raise ValueError("pos_label=%d is not a valid label: %r" % - (pos_label, labels)) - pos_label_idx = list(labels).index(pos_label) - return (precision[pos_label_idx], recall[pos_label_idx], - fscore[pos_label_idx], support[pos_label_idx]) - else: - average_options = (None, 'micro', 'macro', 'weighted') - if average == 'micro': - avg_precision = true_pos.sum() / (true_pos.sum() + - false_pos.sum()) - avg_recall = true_pos.sum() / (true_pos.sum() + false_neg.sum()) - avg_fscore = (1 + beta2) * (avg_precision * avg_recall) / \ - (beta2 * avg_precision + avg_recall) - elif average == 'macro': - avg_precision = np.mean(precision) - avg_recall = np.mean(recall) - avg_fscore = np.mean(fscore) - elif average == 'weighted': - avg_precision = np.average(precision, weights=support) - avg_recall = np.average(recall, weights=support) - avg_fscore = np.average(fscore, weights=support) - else: - raise ValueError('average has to be one of ' + - str(average_options)) - - return avg_precision, avg_recall, avg_fscore, None - - -def matthews_corrcoef(y_true, y_pred): - """Returns matthew's correlation coefficient for binary classes - - The Matthews correlation coefficient is used in machine learning as a - measure of the quality of binary (two-class) classifications. It takes - into account true and false positives and negatives and is generally - regarded as a balanced measure which can be used even if the classes are - of very different sizes. The MCC is in essence a correlation coefficient - value between -1 and +1. A coefficient of +1 represents a perfect - prediction, 0 an average random prediction and -1 an inverse prediction. - The statistic is also known as the phi coefficient. [source: Wikipedia] - - Only in the binary case does this relate to information about true and - false positives and negatives. See references below. - - Parameters - ---------- - y_true : array, shape = [n_samples] - true targets - - y_pred : array, shape = [n_samples] - estimated targets - - Returns - ------- - mcc : float - matthew's correlation coefficient (+1 represents a perfect prediction, - 0 an average random prediction and -1 and inverse prediction). - - References - ---------- - http://en.wikipedia.org/wiki/Matthews_correlation_coefficient - http://dx.doi.org/10.1093/bioinformatics/16.5.412 - - """ - mcc = np.corrcoef(y_true, y_pred)[0, 1] - if np.isnan(mcc): - return 0. - else: - return mcc - - -def classification_report(y_true, y_pred, labels=None, target_names=None): - """Build a text report showing the main classification metrics - - Parameters - ---------- - y_true : array, shape = [n_samples] - True targets - - y_pred : array, shape = [n_samples] - Estimated targets - - labels : array, shape = [n_labels] - Optional list of label indices to include in the report - - target_names : list of strings - Optional display names matching the labels (same order) - - Returns - ------- - report : string - Text summary of the precision, recall, f1-score for each class - - """ - - if labels is None: - labels = unique_labels(y_true, y_pred) - else: - labels = np.asarray(labels, dtype=np.int) - - last_line_heading = 'avg / total' - - if target_names is None: - width = len(last_line_heading) - target_names = ['%d' % l for l in labels] - else: - width = max(len(cn) for cn in target_names) - width = max(width, len(last_line_heading)) - - headers = ["precision", "recall", "f1-score", "support"] - fmt = '%% %ds' % width # first column: class name - fmt += ' ' - fmt += ' '.join(['% 9s' for _ in headers]) - fmt += '\n' - - headers = [""] + headers - report = fmt % tuple(headers) - report += '\n' - - p, r, f1, s = precision_recall_fscore_support(y_true, y_pred, - labels=labels, - average=None) - - for i, label in enumerate(labels): - values = [target_names[i]] - for v in (p[i], r[i], f1[i]): - values += ["%0.2f" % float(v)] - values += ["%d" % int(s[i])] - report += fmt % tuple(values) - - report += '\n' - - # compute averages - values = [last_line_heading] - for v in (np.average(p, weights=s), - np.average(r, weights=s), - np.average(f1, weights=s)): - values += ["%0.2f" % float(v)] - values += ['%d' % np.sum(s)] - report += fmt % tuple(values) - return report - - -def precision_recall_curve(y_true, probas_pred): - """Compute precision-recall pairs for different probability thresholds - - Note: this implementation is restricted to the binary classification task. - - The precision is the ratio :math:`tp / (tp + fp)` where tp is the number of - true positives and fp the number of false positives. The precision is - intuitively the ability of the classifier not to label as positive a sample - that is negative. - - The recall is the ratio :math:`tp / (tp + fn)` where tp is the number of - true positives and fn the number of false negatives. The recall is - intuitively the ability of the classifier to find all the positive samples. - - The last precision and recall values are 1. and 0. respectively and do not - have a corresponding threshold. This ensures that the graph starts on the - x axis. - - Parameters - ---------- - y_true : array, shape = [n_samples] - True targets of binary classification in range {-1, 1} or {0, 1} - - probas_pred : array, shape = [n_samples] - Estimated probabilities - - Returns - ------- - precision : array, shape = [n + 1] - Precision values - - recall : array, shape = [n + 1] - Recall values - - thresholds : array, shape = [n] - Thresholds on y_score used to compute precision and recall - - """ - y_true = np.ravel(y_true) - probas_pred = np.ravel(probas_pred) - - # Make sure input is boolean - labels = np.unique(y_true) - if np.all(labels == np.array([-1, 1])): - # convert {-1, 1} to boolean {0, 1} repr - y_true = y_true.copy() - y_true[y_true == -1] = 0 - elif not np.all(labels == np.array([0, 1])): - raise ValueError("y_true contains non binary labels: %r" % labels) - - # Initialize true and false positive counts, precision and recall - total_positive = float(y_true.sum()) - tp_count, fp_count = 0., 0. - last_prob_val = 1. - thresholds = [] - precision = [1.] - recall = [0.] - last_recorded_idx = -1 - - # Iterate over (predict_prob, true_val) pairs, in order of highest - # to lowest predicted probabilities. Incrementally keep track of how - # many true and false labels have been encountered. If several of the - # predicted probabilities are the same, then create only one new point - # in the curve that represents all of these "tied" predictions. - # (In other words, add new points only when new values of prob_val - # are encountered) - sorted_pred_idxs = np.argsort(probas_pred, kind="mergesort")[::-1] - pairs = np.vstack((probas_pred, y_true)).T - for idx, (prob_val, class_val) in enumerate(pairs[sorted_pred_idxs, :]): - if class_val: - tp_count += 1. - else: - fp_count += 1. - if (prob_val < last_prob_val) and (prob_val > 0.): - thresholds.append(prob_val) - fn_count = float(total_positive - tp_count) - precision.append(tp_count / (tp_count + fp_count)) - recall.append(tp_count / (tp_count + fn_count)) - last_prob_val = prob_val - last_recorded_idx = idx - # Don't forget to include the last point in the PR-curve if - # it wasn't yet recorded. - if last_recorded_idx != idx: - recall.append(1.0) - precision.append(total_positive / (tp_count + fp_count)) - - # Sklearn expects these in reverse order - thresholds = np.array(thresholds)[::-1] - precision = np.array(precision)[::-1] - recall = np.array(recall)[::-1] - return precision, recall, thresholds - - -def explained_variance_score(y_true, y_pred): - """Explained variance regression score function - - Best possible score is 1.0, lower values are worse. - - Note: the explained variance is not a symmetric function. - - return the explained variance - - Parameters - ---------- - y_true : array-like - - y_pred : array-like - - """ - y_true, y_pred = check_arrays(y_true, y_pred) - numerator = np.var(y_true - y_pred) - denominator = np.var(y_true) - if denominator == 0.0: - if numerator == 0.0: - return 1.0 - else: - # arbitary set to zero to avoid -inf scores, having a constant - # y_true is not interesting for scoring a regression anyway - return 0.0 - return 1 - numerator / denominator - - -def r2_score(y_true, y_pred): - """R^2 (coefficient of determination) regression score function - - Best possible score is 1.0, lower values are worse. - - Parameters - ---------- - y_true : array-like - - y_pred : array-like - - Returns - ------- - z : float - The R^2 score - - Notes - ----- - This is not a symmetric function. - - References - ---------- - http://en.wikipedia.org/wiki/Coefficient_of_determination - """ - y_true, y_pred = check_arrays(y_true, y_pred) - if len(y_true) == 1: - raise ValueError("r2_score can only be computed given more than one" - " sample.") - numerator = ((y_true - y_pred) ** 2).sum() - denominator = ((y_true - y_true.mean()) ** 2).sum() - if denominator == 0.0: - if numerator == 0.0: - return 1.0 - else: - # arbitary set to zero to avoid -inf scores, having a constant - # y_true is not interesting for scoring a regression anyway - return 0.0 - return 1 - numerator / denominator - - -def zero_one_score(y_true, y_pred): - """Zero-one classification score (accuracy) - - Positive integer (number of good classifications). - The best performance is 1. - - Return the fraction of correct predictions in y_pred. - - Parameters - ---------- - y_true : array-like, shape = n_samples - Gold standard labels. - - y_pred : array-like, shape = n_samples - Predicted labels, as returned by a classifier. - - Returns - ------- - score : float - - """ - y_true, y_pred = check_arrays(y_true, y_pred) - return np.mean(y_pred == y_true) - - -############################################################################### -# Loss functions - -def zero_one(y_true, y_pred): - """Zero-One classification loss - - Positive integer (number of misclassifications). The best performance - is 0. - - Return the number of errors - - Parameters - ---------- - y_true : array-like - - y_pred : array-like - - Returns - ------- - loss : float - - """ - y_true, y_pred = check_arrays(y_true, y_pred) - return np.sum(y_pred != y_true) - - -def mean_squared_error(y_true, y_pred): - """Mean squared error regression loss - - Return a a positive floating point value (the best value is 0.0). - - Parameters - ---------- - y_true : array-like - - y_pred : array-like - - Returns - ------- - loss : float - """ - y_true, y_pred = check_arrays(y_true, y_pred) - return np.mean((y_pred - y_true) ** 2) - - -def hinge_loss(y_true, pred_decision, pos_label=1, neg_label=-1): - """ - Cumulated hinge loss (non-regularized). - - Assuming labels in y_true are encoded with +1 and -1, - when a prediction mistake is made, margin = y_true * pred_decision - is always negative (since the signs disagree), therefore 1 - margin - is always greater than 1. The cumulated hinge loss therefore - upperbounds the number of mistakes made by the classifier. - - Parameters - ---------- - y_true : array, shape = [n_samples] - True target (integers) - - pred_decision : array, shape = [n_samples] or [n_samples, n_classes] - Predicted decisions, as output by decision_function (floats) - - """ - # TODO: multi-class hinge-loss - - if pos_label != 1 or neg_label != -1: - # the rest of the code assumes that positive and negative labels - # are encoded as +1 and -1 respectively - y_true = y_true.copy() - y_true[y_true == pos_label] = 1 - y_true[y_true == neg_label] = -1 - - margin = y_true * pred_decision - losses = 1 - margin - # The hinge doesn't penalize good enough predictions. - losses[losses <= 0] = 0 - return np.mean(losses) +import warnings +warnings.warn("sklearn.metrics.metrics is deprecated and will be removed in " + "0.18. Please import from sklearn.metrics", + DeprecationWarning) + + +from .ranking import auc +from .ranking import average_precision_score +from .ranking import label_ranking_average_precision_score +from .ranking import precision_recall_curve +from .ranking import roc_auc_score +from .ranking import roc_curve + +from .classification import accuracy_score +from .classification import classification_report +from .classification import confusion_matrix +from .classification import f1_score +from .classification import fbeta_score +from .classification import hamming_loss +from .classification import hinge_loss +from .classification import jaccard_similarity_score +from .classification import log_loss +from .classification import matthews_corrcoef +from .classification import precision_recall_fscore_support +from .classification import precision_score +from .classification import recall_score +from .classification import zero_one_loss + +from .regression import explained_variance_score +from .regression import mean_absolute_error +from .regression import mean_squared_error +from .regression import median_absolute_error +from .regression import r2_score diff --git a/sklearn/metrics/pairwise.py b/sklearn/metrics/pairwise.py index 08c962c41b417..ed979183071a8 100644 --- a/sklearn/metrics/pairwise.py +++ b/sklearn/metrics/pairwise.py @@ -1,54 +1,59 @@ -""" -The :mod:`sklearn.metrics.pairwise` submodule implements utilities to evaluate -pairwise distances or affinity of sets of samples. - -This module contains both distance metrics and kernels. A brief summary is -given on the two here. - -Distance metrics are a function d(a, b) such that d(a, b) < d(a, c) if objects -a and b are considered "more similar" to objects a and c. Two objects exactly -alike would have a distance of zero. -One of the most popular examples is Euclidean distance. -To be a 'true' metric, it must obey the following four conditions:: - - 1. d(a, b) >= 0, for all a and b - 2. d(a, b) == 0, if and only if a = b, positive definiteness - 3. d(a, b) == d(b, a), symmetry - 4. d(a, c) <= d(a, b) + d(b, c), the triangle inequality - -Kernels are measures of similarity, i.e. ``s(a, b) > s(a, c)`` -if objects ``a`` and ``b`` are considered "more similar" to objects -``a`` and ``c``. A kernel must also be positive semi-definite. - -There are a number of ways to convert between a distance metric and a -similarity measure, such as a kernel. Let D be the distance, and S be the -kernel:: - - 1. ``S = np.exp(-D * gamma)``, where one heuristic for choosing - ``gamma`` is ``1 / num_features`` - 2. ``S = 1. / (D / np.max(D))`` -""" +# -*- coding: utf-8 -*- # Authors: Alexandre Gramfort # Mathieu Blondel # Robert Layton -# License: BSD Style. +# Andreas Mueller +# Philippe Gervais +# Lars Buitinck +# Joel Nothman +# License: BSD 3 clause + +import itertools import numpy as np from scipy.spatial import distance from scipy.sparse import csr_matrix from scipy.sparse import issparse -from ..utils import safe_asarray -from ..utils import atleast2d_or_csr +from ..utils import check_array from ..utils import gen_even_slices -from ..utils.extmath import safe_sparse_dot +from ..utils import gen_batches +from ..utils.fixes import partial +from ..utils.extmath import row_norms, safe_sparse_dot +from ..preprocessing import normalize from ..externals.joblib import Parallel from ..externals.joblib import delayed from ..externals.joblib.parallel import cpu_count +from .pairwise_fast import _chi2_kernel_fast, _sparse_manhattan + # Utility Functions +def _return_float_dtype(X, Y): + """ + 1. If dtype of X and Y is float32, then dtype float32 is returned. + 2. Else dtype float is returned. + """ + if not issparse(X) and not isinstance(X, np.ndarray): + X = np.asarray(X) + + if Y is None: + Y_dtype = X.dtype + elif not issparse(Y) and not isinstance(Y, np.ndarray): + Y = np.asarray(Y) + Y_dtype = Y.dtype + else: + Y_dtype = Y.dtype + + if X.dtype == Y_dtype == np.float32: + dtype = np.float32 + else: + dtype = np.float + + return X, Y, dtype + + def check_pairwise_arrays(X, Y): """ Set X and Y appropriately and checks inputs @@ -64,40 +69,70 @@ def check_pairwise_arrays(X, Y): Parameters ---------- - X : {array-like, sparse matrix}, shape = [n_samples_a, n_features] + X : {array-like, sparse matrix}, shape (n_samples_a, n_features) - Y : {array-like, sparse matrix}, shape = [n_samples_b, n_features] + Y : {array-like, sparse matrix}, shape (n_samples_b, n_features) Returns ------- - safe_X : {array-like, sparse matrix}, shape = [n_samples_a, n_features] - An array equal to X, guarenteed to be a numpy array. + safe_X : {array-like, sparse matrix}, shape (n_samples_a, n_features) + An array equal to X, guaranteed to be a numpy array. - safe_Y : {array-like, sparse matrix}, shape = [n_samples_b, n_features] - An array equal to Y if Y was not None, guarenteed to be a numpy array. + safe_Y : {array-like, sparse matrix}, shape (n_samples_b, n_features) + An array equal to Y if Y was not None, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ + X, Y, dtype = _return_float_dtype(X, Y) + if Y is X or Y is None: - X = safe_asarray(X) - X = Y = atleast2d_or_csr(X, dtype=np.float) + X = Y = check_array(X, accept_sparse='csr', dtype=dtype) else: - X = safe_asarray(X) - Y = safe_asarray(Y) - X = atleast2d_or_csr(X, dtype=np.float) - Y = atleast2d_or_csr(Y, dtype=np.float) - if len(X.shape) < 2: - raise ValueError("X is required to be at least two dimensional.") - if len(Y.shape) < 2: - raise ValueError("Y is required to be at least two dimensional.") + X = check_array(X, accept_sparse='csr', dtype=dtype) + Y = check_array(Y, accept_sparse='csr', dtype=dtype) if X.shape[1] != Y.shape[1]: raise ValueError("Incompatible dimension for X and Y matrices: " "X.shape[1] == %d while Y.shape[1] == %d" % ( X.shape[1], Y.shape[1])) + + return X, Y + + +def check_paired_arrays(X, Y): + """ Set X and Y appropriately and checks inputs for paired distances + + All paired distance metrics should use this function first to assert that + the given parameters are correct and safe to use. + + Specifically, this function first ensures that both X and Y are arrays, + then checks that they are at least two dimensional while ensuring that + their elements are floats. Finally, the function checks that the size + of the dimensions of the two arrays are equal. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples_a, n_features) + + Y : {array-like, sparse matrix}, shape (n_samples_b, n_features) + + Returns + ------- + safe_X : {array-like, sparse matrix}, shape (n_samples_a, n_features) + An array equal to X, guaranteed to be a numpy array. + + safe_Y : {array-like, sparse matrix}, shape (n_samples_b, n_features) + An array equal to Y if Y was not None, guaranteed to be a numpy array. + If Y was None, safe_Y will be a pointer to X. + + """ + X, Y = check_pairwise_arrays(X, Y) + if X.shape != Y.shape: + raise ValueError("X and Y should be of same shape. They were " + "respectively %r and %r long." % (X.shape, Y.shape)) return X, Y -# Distances +# Pairwise distances def euclidean_distances(X, Y=None, Y_norm_squared=None, squared=False): """ Considering the rows of X (and Y=X) as vectors, compute the @@ -108,18 +143,22 @@ def euclidean_distances(X, Y=None, Y_norm_squared=None, squared=False): dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y)) - This formulation has two main advantages. First, it is computationally - efficient when dealing with sparse data. Second, if x varies but y - remains unchanged, then the right-most dot-product `dot(y, y)` can be - pre-computed. + This formulation has two advantages over other ways of computing distances. + First, it is computationally efficient when dealing with sparse data. + Second, if x varies but y remains unchanged, then the right-most dot + product `dot(y, y)` can be pre-computed. + + However, this is not the most precise way of doing this computation, and + the distance matrix returned by this function may not be exactly + symmetric as required by, e.g., ``scipy.spatial.distance`` functions. Parameters ---------- - X : {array-like, sparse matrix}, shape = [n_samples_1, n_features] + X : {array-like, sparse matrix}, shape (n_samples_1, n_features) - Y : {array-like, sparse matrix}, shape = [n_samples_2, n_features] + Y : {array-like, sparse matrix}, shape (n_samples_2, n_features) - Y_norm_squared : array-like, shape = [n_samples_2], optional + Y_norm_squared : array-like, shape (n_samples_2, ), optional Pre-computed dot-products of vectors in Y (e.g., ``(Y**2).sum(axis=1)``) @@ -128,7 +167,7 @@ def euclidean_distances(X, Y=None, Y_norm_squared=None, squared=False): Returns ------- - distances : {array, sparse matrix}, shape = [n_samples_1, n_samples_2] + distances : {array, sparse matrix}, shape (n_samples_1, n_samples_2) Examples -------- @@ -142,50 +181,250 @@ def euclidean_distances(X, Y=None, Y_norm_squared=None, squared=False): >>> euclidean_distances(X, [[0, 0]]) array([[ 1. ], [ 1.41421356]]) + + See also + -------- + paired_distances : distances betweens pairs of elements of X and Y. """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. X, Y = check_pairwise_arrays(X, Y) - if issparse(X): - XX = X.multiply(X).sum(axis=1) + + if Y_norm_squared is not None: + YY = check_array(Y_norm_squared) + if YY.shape != (1, Y.shape[0]): + raise ValueError( + "Incompatible dimensions for Y and Y_norm_squared") else: - XX = np.sum(X * X, axis=1)[:, np.newaxis] + YY = row_norms(Y, squared=True)[np.newaxis, :] if X is Y: # shortcut in the common case euclidean_distances(X, X) - YY = XX.T - elif Y_norm_squared is None: - if issparse(Y): - # scipy.sparse matrices don't have element-wise scalar - # exponentiation, and tocsr has a copy kwarg only on CSR matrices. - YY = Y.copy() if isinstance(Y, csr_matrix) else Y.tocsr() - YY.data **= 2 - YY = np.asarray(YY.sum(axis=1)).T - else: - YY = np.sum(Y ** 2, axis=1)[np.newaxis, :] + XX = YY.T else: - YY = atleast2d_or_csr(Y_norm_squared) - if YY.shape != (1, Y.shape[0]): - raise ValueError( - "Incompatible dimensions for Y and Y_norm_squared") + XX = row_norms(X, squared=True)[:, np.newaxis] - # TODO: a faster Cython implementation would do the clipping of negative - # values in a single pass over the output matrix. distances = safe_sparse_dot(X, Y.T, dense_output=True) distances *= -2 distances += XX distances += YY - np.maximum(distances, 0, distances) + np.maximum(distances, 0, out=distances) if X is Y: # Ensure that distances between vectors and themselves are set to 0.0. # This may not be the case due to floating point rounding errors. distances.flat[::distances.shape[0] + 1] = 0.0 - return distances if squared else np.sqrt(distances) + return distances if squared else np.sqrt(distances, out=distances) + + +def pairwise_distances_argmin_min(X, Y, axis=1, metric="euclidean", + batch_size=500, metric_kwargs=None): + """Compute minimum distances between one point and a set of points. + + This function computes for each row in X, the index of the row of Y which + is closest (according to the specified distance). The minimal distances are + also returned. + + This is mostly equivalent to calling: + + (pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis), + pairwise_distances(X, Y=Y, metric=metric).min(axis=axis)) + + but uses much less memory, and is faster for large arrays. + + Parameters + ---------- + X, Y : {array-like, sparse matrix} + Arrays containing points. Respective shapes (n_samples1, n_features) + and (n_samples2, n_features) + + batch_size : integer + To reduce memory consumption over the naive solution, data are + processed in batches, comprising batch_size rows of X and + batch_size rows of Y. The default value is quite conservative, but + can be changed for fine-tuning. The larger the number, the larger the + memory usage. + + metric : string or callable, default 'euclidean' + metric to use for distance computation. Any metric from scikit-learn + or scipy.spatial.distance can be used. + + If metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays as input and return one value indicating the + distance between them. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + Distance matrices are not supported. + + Valid values for metric are: + + - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan'] + + - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', + 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', + 'sqeuclidean', 'yule'] + + See the documentation for scipy.spatial.distance for details on these + metrics. + + metric_kwargs : dict, optional + Keyword arguments to pass to specified metric function. + + axis : int, optional, default 1 + Axis along which the argmin and distances are to be computed. + + Returns + ------- + argmin : numpy.ndarray + Y[argmin[i], :] is the row in Y that is closest to X[i, :]. + + distances : numpy.ndarray + distances[i] is the distance between the i-th row in X and the + argmin[i]-th row in Y. + + See also + -------- + sklearn.metrics.pairwise_distances + sklearn.metrics.pairwise_distances_argmin + """ + dist_func = None + if metric in PAIRWISE_DISTANCE_FUNCTIONS: + dist_func = PAIRWISE_DISTANCE_FUNCTIONS[metric] + elif not callable(metric) and not isinstance(metric, str): + raise ValueError("'metric' must be a string or a callable") + + X, Y = check_pairwise_arrays(X, Y) + if metric_kwargs is None: + metric_kwargs = {} -def manhattan_distances(X, Y=None, sum_over_features=True): + if axis == 0: + X, Y = Y, X + + # Allocate output arrays + indices = np.empty(X.shape[0], dtype=np.intp) + values = np.empty(X.shape[0]) + values.fill(np.infty) + + for chunk_x in gen_batches(X.shape[0], batch_size): + X_chunk = X[chunk_x, :] + + for chunk_y in gen_batches(Y.shape[0], batch_size): + Y_chunk = Y[chunk_y, :] + + if dist_func is not None: + if metric == 'euclidean': # special case, for speed + d_chunk = safe_sparse_dot(X_chunk, Y_chunk.T, + dense_output=True) + d_chunk *= -2 + d_chunk += row_norms(X_chunk, squared=True)[:, np.newaxis] + d_chunk += row_norms(Y_chunk, squared=True)[np.newaxis, :] + np.maximum(d_chunk, 0, d_chunk) + else: + d_chunk = dist_func(X_chunk, Y_chunk, **metric_kwargs) + else: + d_chunk = pairwise_distances(X_chunk, Y_chunk, + metric=metric, **metric_kwargs) + + # Update indices and minimum values using chunk + min_indices = d_chunk.argmin(axis=1) + min_values = d_chunk[np.arange(chunk_x.stop - chunk_x.start), + min_indices] + + flags = values[chunk_x] > min_values + indices[chunk_x][flags] = min_indices[flags] + chunk_y.start + values[chunk_x][flags] = min_values[flags] + + if metric == "euclidean" and not metric_kwargs.get("squared", False): + np.sqrt(values, values) + return indices, values + + +def pairwise_distances_argmin(X, Y, axis=1, metric="euclidean", + batch_size=500, metric_kwargs={}): + """Compute minimum distances between one point and a set of points. + + This function computes for each row in X, the index of the row of Y which + is closest (according to the specified distance). + + This is mostly equivalent to calling: + + pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis) + + but uses much less memory, and is faster for large arrays. + + This function works with dense 2D arrays only. + + Parameters + ========== + X : array-like + Arrays containing points. Respective shapes (n_samples1, n_features) + and (n_samples2, n_features) + + Y : array-like + Arrays containing points. Respective shapes (n_samples1, n_features) + and (n_samples2, n_features) + + batch_size : integer + To reduce memory consumption over the naive solution, data are + processed in batches, comprising batch_size rows of X and + batch_size rows of Y. The default value is quite conservative, but + can be changed for fine-tuning. The larger the number, the larger the + memory usage. + + metric : string or callable + metric to use for distance computation. Any metric from scikit-learn + or scipy.spatial.distance can be used. + + If metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays as input and return one value indicating the + distance between them. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + Distance matrices are not supported. + + Valid values for metric are: + + - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan'] + + - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', + 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', + 'sqeuclidean', 'yule'] + + See the documentation for scipy.spatial.distance for details on these + metrics. + + metric_kwargs : dict + keyword arguments to pass to specified metric function. + + axis : int, optional, default 1 + Axis along which the argmin and distances are to be computed. + + Returns + ======= + argmin : numpy.ndarray + Y[argmin[i], :] is the row in Y that is closest to X[i, :]. + + See also + ======== + sklearn.metrics.pairwise_distances + sklearn.metrics.pairwise_distances_argmin_min + """ + return pairwise_distances_argmin_min(X, Y, axis, metric, batch_size, + metric_kwargs)[0] + + +def manhattan_distances(X, Y=None, sum_over_features=True, + size_threshold=5e8): """ Compute the L1 distances between the vectors in X and Y. With sum_over_features equal to False it returns the componentwise @@ -202,6 +441,10 @@ def manhattan_distances(X, Y=None, sum_over_features=True): sum_over_features : bool, default=True If True the function returns the pairwise distance matrix else it returns the componentwise L1 pairwise-distances. + Not supported for sparse matrix inputs. + + size_threshold : int, default=5e8 + Unused parameter. Returns ------- @@ -210,7 +453,7 @@ def manhattan_distances(X, Y=None, sum_over_features=True): (n_samples_X * n_samples_Y, n_features) and D contains the componentwise L1 pairwise-distances (ie. absolute difference), else shape is (n_samples_X, n_samples_Y) and D contains - the pairwise l1 distances. + the pairwise L1 distances. Examples -------- @@ -233,16 +476,186 @@ def manhattan_distances(X, Y=None, sum_over_features=True): [ 1., 1.]]...) """ X, Y = check_pairwise_arrays(X, Y) - n_samples_X, n_features_X = X.shape - n_samples_Y, n_features_Y = Y.shape - if n_features_X != n_features_Y: - raise Exception("X and Y should have the same number of features!") - D = np.abs(X[:, np.newaxis, :] - Y[np.newaxis, :, :]) + + if issparse(X) or issparse(Y): + if not sum_over_features: + raise TypeError("sum_over_features=%r not supported" + " for sparse matrices" % sum_over_features) + + X = csr_matrix(X, copy=False) + Y = csr_matrix(Y, copy=False) + D = np.zeros((X.shape[0], Y.shape[0])) + _sparse_manhattan(X.data, X.indices, X.indptr, + Y.data, Y.indices, Y.indptr, + X.shape[1], D) + return D + if sum_over_features: - D = np.sum(D, axis=2) + return distance.cdist(X, Y, 'cityblock') + + D = X[:, np.newaxis, :] - Y[np.newaxis, :, :] + D = np.abs(D, D) + return D.reshape((-1, X.shape[1])) + + +def cosine_distances(X, Y=None): + """ + Compute cosine distance between samples in X and Y. + + Cosine distance is defined as 1.0 minus the cosine similarity. + + Parameters + ---------- + X : array_like, sparse matrix + with shape (n_samples_X, n_features). + + Y : array_like, sparse matrix (optional) + with shape (n_samples_Y, n_features). + + Returns + ------- + distance matrix : array + An array with shape (n_samples_X, n_samples_Y). + + See also + -------- + sklearn.metrics.pairwise.cosine_similarity + scipy.spatial.distance.cosine (dense matrices only) + """ + # 1.0 - cosine_similarity(X, Y) without copy + S = cosine_similarity(X, Y) + S *= -1 + S += 1 + return S + + +# Paired distances +def paired_euclidean_distances(X, Y): + """ + Computes the paired euclidean distances between X and Y + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + + Y : array-like, shape (n_samples, n_features) + + Returns + ------- + distances : ndarray (n_samples, ) + """ + X, Y = check_paired_arrays(X, Y) + return row_norms(X - Y) + + +def paired_manhattan_distances(X, Y): + """Compute the L1 distances between the vectors in X and Y. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + + Y : array-like, shape (n_samples, n_features) + + Returns + ------- + distances : ndarray (n_samples, ) + """ + X, Y = check_paired_arrays(X, Y) + diff = X - Y + if issparse(diff): + diff.data = np.abs(diff.data) + return np.squeeze(np.array(diff.sum(axis=1))) + else: + return np.abs(diff).sum(axis=-1) + + +def paired_cosine_distances(X, Y): + """ + Computes the paired cosine distances between X and Y + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + + Y : array-like, shape (n_samples, n_features) + + Returns + ------- + distances : ndarray, shape (n_samples, ) + + Notes + ------ + The cosine distance is equivalent to the half the squared + euclidean distance if each sample is normalized to unit norm + """ + X, Y = check_paired_arrays(X, Y) + return .5 * row_norms(normalize(X) - normalize(Y), squared=True) + + +PAIRED_DISTANCES = { + 'cosine': paired_cosine_distances, + 'euclidean': paired_euclidean_distances, + 'l2': paired_euclidean_distances, + 'l1': paired_manhattan_distances, + 'manhattan': paired_manhattan_distances, + 'cityblock': paired_manhattan_distances, + } + + +def paired_distances(X, Y, metric="euclidean", **kwds): + """ + Computes the paired distances between X and Y. + + Computes the distances between (X[0], Y[0]), (X[1], Y[1]), etc... + + Parameters + ---------- + X : ndarray (n_samples, n_features) + Array 1 for distance computation. + + Y : ndarray (n_samples, n_features) + Array 2 for distance computation. + + metric : string or callable + The metric to use when calculating distance between instances in a + feature array. If metric is a string, it must be one of the options + specified in PAIRED_DISTANCES, including "euclidean", + "manhattan", or "cosine". + Alternatively, if metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays from X as input and return a value indicating + the distance between them. + + Returns + ------- + distances : ndarray (n_samples, ) + + Examples + -------- + >>> from sklearn.metrics.pairwise import paired_distances + >>> X = [[0, 1], [1, 1]] + >>> Y = [[0, 1], [2, 1]] + >>> paired_distances(X, Y) + array([ 0., 1.]) + + See also + -------- + pairwise_distances : pairwise distances. + """ + + if metric in PAIRED_DISTANCES: + func = PAIRED_DISTANCES[metric] + return func(X, Y) + elif callable(metric): + # Check the matrix first (it is usually done by the metric) + X, Y = check_paired_arrays(X, Y) + distances = np.zeros(len(X)) + for i in range(len(X)): + distances[i] = metric(X[i], Y[i]) + return distances else: - D = D.reshape((n_samples_X * n_samples_Y, n_features_X)) - return D + raise ValueError('Unknown distance %s' % metric) # Kernels @@ -264,7 +677,7 @@ def linear_kernel(X, Y=None): return safe_sparse_dot(X, Y.T, dense_output=True) -def polynomial_kernel(X, Y=None, degree=3, gamma=0, coef0=1): +def polynomial_kernel(X, Y=None, degree=3, gamma=None, coef0=1): """ Compute the polynomial kernel between X and Y:: @@ -272,28 +685,30 @@ def polynomial_kernel(X, Y=None, degree=3, gamma=0, coef0=1): Parameters ---------- - X : array of shape (n_samples_1, n_features) + X : ndarray of shape (n_samples_1, n_features) - Y : array of shape (n_samples_2, n_features) + Y : ndarray of shape (n_samples_2, n_features) - degree : int + coef0 : int, default 1 + + degree : int, default 3 Returns ------- Gram matrix : array of shape (n_samples_1, n_samples_2) """ X, Y = check_pairwise_arrays(X, Y) - if gamma == 0: + if gamma is None: gamma = 1.0 / X.shape[1] - K = linear_kernel(X, Y) + K = safe_sparse_dot(X, Y.T, dense_output=True) K *= gamma K += coef0 K **= degree return K -def sigmoid_kernel(X, Y=None, gamma=0, coef0=1): +def sigmoid_kernel(X, Y=None, gamma=None, coef0=1): """ Compute the sigmoid kernel between X and Y:: @@ -301,47 +716,49 @@ def sigmoid_kernel(X, Y=None, gamma=0, coef0=1): Parameters ---------- - X : array of shape (n_samples_1, n_features) + X : ndarray of shape (n_samples_1, n_features) - Y : array of shape (n_samples_2, n_features) + Y : ndarray of shape (n_samples_2, n_features) - degree : int + coef0 : int, default 1 Returns ------- Gram matrix: array of shape (n_samples_1, n_samples_2) """ X, Y = check_pairwise_arrays(X, Y) - if gamma == 0: + if gamma is None: gamma = 1.0 / X.shape[1] - K = linear_kernel(X, Y) + K = safe_sparse_dot(X, Y.T, dense_output=True) K *= gamma K += coef0 np.tanh(K, K) # compute tanh in-place return K -def rbf_kernel(X, Y=None, gamma=0): +def rbf_kernel(X, Y=None, gamma=None): """ Compute the rbf (gaussian) kernel between X and Y:: - K(X, Y) = exp(-gamma ||X-Y||^2) + K(x, y) = exp(-gamma ||x-y||^2) + + for each pair of rows x in X and y in Y. Parameters ---------- - X : array of shape (n_samples_1, n_features) + X : array of shape (n_samples_X, n_features) - Y : array of shape (n_samples_2, n_features) + Y : array of shape (n_samples_Y, n_features) gamma : float Returns ------- - Gram matrix : array of shape (n_samples_1, n_samples_2) + kernel_matrix : array of shape (n_samples_X, n_samples_Y) """ X, Y = check_pairwise_arrays(X, Y) - if gamma == 0: + if gamma is None: gamma = 1.0 / X.shape[1] K = euclidean_distances(X, Y, squared=True) @@ -350,39 +767,183 @@ def rbf_kernel(X, Y=None, gamma=0): return K +def cosine_similarity(X, Y=None): + """Compute cosine similarity between samples in X and Y. + + Cosine similarity, or the cosine kernel, computes similarity as the + normalized dot product of X and Y: + + K(X, Y) = / (||X||*||Y||) + + On L2-normalized data, this function is equivalent to linear_kernel. + + Parameters + ---------- + X : array_like, sparse matrix + with shape (n_samples_X, n_features). + + Y : array_like, sparse matrix (optional) + with shape (n_samples_Y, n_features). + + Returns + ------- + kernel matrix : array + An array with shape (n_samples_X, n_samples_Y). + """ + # to avoid recursive import + + X, Y = check_pairwise_arrays(X, Y) + + X_normalized = normalize(X, copy=True) + if X is Y: + Y_normalized = X_normalized + else: + Y_normalized = normalize(Y, copy=True) + + K = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=True) + + return K + + +def additive_chi2_kernel(X, Y=None): + """Computes the additive chi-squared kernel between observations in X and Y + + The chi-squared kernel is computed between each pair of rows in X and Y. X + and Y have to be non-negative. This kernel is most commonly applied to + histograms. + + The chi-squared kernel is given by:: + + k(x, y) = -Sum [(x - y)^2 / (x + y)] + + It can be interpreted as a weighted difference per entry. + + Notes + ----- + As the negative of a distance, this kernel is only conditionally positive + definite. + + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) + + Y : array of shape (n_samples_Y, n_features) + + Returns + ------- + kernel_matrix : array of shape (n_samples_X, n_samples_Y) + + References + ---------- + * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. + Local features and kernels for classification of texture and object + categories: A comprehensive study + International Journal of Computer Vision 2007 + http://eprints.pascal-network.org/archive/00002309/01/Zhang06-IJCV.pdf + + + See also + -------- + chi2_kernel : The exponentiated version of the kernel, which is usually + preferable. + + sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation + to this kernel. + """ + if issparse(X) or issparse(Y): + raise ValueError("additive_chi2 does not support sparse matrices.") + X, Y = check_pairwise_arrays(X, Y) + if (X < 0).any(): + raise ValueError("X contains negative values.") + if Y is not X and (Y < 0).any(): + raise ValueError("Y contains negative values.") + + result = np.zeros((X.shape[0], Y.shape[0]), dtype=X.dtype) + _chi2_kernel_fast(X, Y, result) + return result + + +def chi2_kernel(X, Y=None, gamma=1.): + """Computes the exponential chi-squared kernel X and Y. + + The chi-squared kernel is computed between each pair of rows in X and Y. X + and Y have to be non-negative. This kernel is most commonly applied to + histograms. + + The chi-squared kernel is given by:: + + k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)]) + + It can be interpreted as a weighted difference per entry. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) + + Y : array of shape (n_samples_Y, n_features) + + gamma : float, default=1. + Scaling parameter of the chi2 kernel. + + Returns + ------- + kernel_matrix : array of shape (n_samples_X, n_samples_Y) + + References + ---------- + * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. + Local features and kernels for classification of texture and object + categories: A comprehensive study + International Journal of Computer Vision 2007 + http://eprints.pascal-network.org/archive/00002309/01/Zhang06-IJCV.pdf + + See also + -------- + additive_chi2_kernel : The additive version of this kernel + + sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation + to the additive version of this kernel. + """ + K = additive_chi2_kernel(X, Y) + K *= gamma + return np.exp(K, K) + + # Helper functions - distance -pairwise_distance_functions = { +PAIRWISE_DISTANCE_FUNCTIONS = { # If updating this dictionary, update the doc in both distance_metrics() # and also in pairwise_distances()! + 'cityblock': manhattan_distances, + 'cosine': cosine_distances, 'euclidean': euclidean_distances, 'l2': euclidean_distances, 'l1': manhattan_distances, - 'manhattan': manhattan_distances, - 'cityblock': manhattan_distances, - } + 'manhattan': manhattan_distances, } def distance_metrics(): - """ Valid metrics for pairwise_distances + """Valid metrics for pairwise_distances. This function simply returns the valid pairwise distance metrics. - It exists, however, to allow for a verbose description of the mapping for + It exists to allow for a description of the mapping for each of the valid strings. The valid distance metrics, and the function they map to, are: - =========== ==================================== - metric Function - =========== ==================================== - 'cityblock' sklearn.pairwise.manhattan_distances - 'euclidean' sklearn.pairwise.euclidean_distances - 'l1' sklearn.pairwise.manhattan_distances - 'l2' sklearn.pairwise.euclidean_distances - 'manhattan' sklearn.pairwise.manhattan_distances - =========== ==================================== + ============ ==================================== + metric Function + ============ ==================================== + 'cityblock' metrics.pairwise.manhattan_distances + 'cosine' metrics.pairwise.cosine_distances + 'euclidean' metrics.pairwise.euclidean_distances + 'l1' metrics.pairwise.manhattan_distances + 'l2' metrics.pairwise.euclidean_distances + 'manhattan' metrics.pairwise.manhattan_distances + ============ ==================================== """ - return pairwise_distance_functions + return PAIRWISE_DISTANCE_FUNCTIONS def _parallel_pairwise(X, Y, func, n_jobs, **kwds): @@ -394,13 +955,59 @@ def _parallel_pairwise(X, Y, func, n_jobs, **kwds): if Y is None: Y = X + if n_jobs == 1: + # Special case to avoid picklability checks in delayed + return func(X, Y, **kwds) + + # TODO: in some cases, backend='threading' may be appropriate + fd = delayed(func) ret = Parallel(n_jobs=n_jobs, verbose=0)( - delayed(func)(X, Y[s], **kwds) - for s in gen_even_slices(Y.shape[0], n_jobs)) + fd(X, Y[s], **kwds) + for s in gen_even_slices(Y.shape[0], n_jobs)) return np.hstack(ret) +def _pairwise_callable(X, Y, metric, **kwds): + """Handle the callable case for pairwise_{distances,kernels} + """ + X, Y = check_pairwise_arrays(X, Y) + + if X is Y: + # Only calculate metric for upper triangle + out = np.zeros((X.shape[0], Y.shape[0]), dtype='float') + iterator = itertools.combinations(range(X.shape[0]), 2) + for i, j in iterator: + out[i, j] = metric(X[i], Y[j], **kwds) + + # Make symmetric + # NB: out += out.T will produce incorrect results + out = out + out.T + + # Calculate diagonal + # NB: nonzero diagonals are allowed for both metrics and kernels + for i in range(X.shape[0]): + x = X[i] + out[i, i] = metric(x, x, **kwds) + + else: + # Calculate all cells + out = np.empty((X.shape[0], Y.shape[0]), dtype='float') + iterator = itertools.product(range(X.shape[0]), range(Y.shape[0])) + for i, j in iterator: + out[i, j] = metric(X[i], Y[j], **kwds) + + return out + + +_VALID_METRICS = ['euclidean', 'l2', 'l1', 'manhattan', 'cityblock', + 'braycurtis', 'canberra', 'chebyshev', 'correlation', + 'cosine', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', + 'russellrao', 'seuclidean', 'sokalmichener', + 'sokalsneath', 'sqeuclidean', 'yule', "wminkowski"] + + def pairwise_distances(X, Y=None, metric="euclidean", n_jobs=1, **kwds): """ Compute the distance matrix from a vector array X and optional Y. @@ -409,31 +1016,30 @@ def pairwise_distances(X, Y=None, metric="euclidean", n_jobs=1, **kwds): computed. If the input is a distances matrix, it is returned instead. This method provides a safe way to take a distance matrix as input, while - preserving compatability with many other algorithms that take a vector + preserving compatibility with many other algorithms that take a vector array. If Y is given (default is None), then the returned matrix is the pairwise distance between the arrays from both X and Y. - Please note that support for sparse matrices is currently limited to those - metrics listed in pairwise.pairwise_distance_functions. - Valid values for metric are: - - from scikit-learn: ['euclidean', 'l2', 'l1', 'manhattan', 'cityblock'] + - From scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan']. These metrics support sparse matrix inputs. - - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', - 'correlation', 'cosine', 'dice', 'hamming', 'jaccard', 'kulsinski', - 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', - 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] + - From scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', + 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', + 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these - metrics. + metrics. These metrics do not support sparse matrix inputs. - Note in the case of 'euclidean' and 'cityblock' (which are valid - scipy.spatial.distance metrics), the values will use the scikit-learn - implementation, which is faster and has support for sparse matrices. - For a verbose description of the metrics from scikit-learn, see the - __doc__ of the sklearn.pairwise.distance_metrics function. + Note that in the case of 'cityblock', 'cosine' and 'euclidean' (which are + valid scipy.spatial.distance metrics), the scikit-learn implementation + will be used, which is faster and has support for sparse matrices (except + for 'cityblock'). For a verbose description of the metrics from + scikit-learn, see the __doc__ of the sklearn.pairwise.distance_metrics + function. Parameters ---------- @@ -448,7 +1054,7 @@ def pairwise_distances(X, Y=None, metric="euclidean", n_jobs=1, **kwds): The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by scipy.spatial.distance.pdist for its metric parameter, or - a metric listed in pairwise.pairwise_distance_functions. + a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS. If metric is "precomputed", X is assumed to be a distance matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable @@ -461,8 +1067,8 @@ def pairwise_distances(X, Y=None, metric="euclidean", n_jobs=1, **kwds): parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is - used at all, which is useful for debuging. For n_jobs below -1, - (n_cpus + 1 - n_jobs) are used. Thus for n_jobs = -2, all CPUs but one + used at all, which is useful for debugging. For n_jobs below -1, + (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. `**kwds` : optional keyword parameters @@ -479,56 +1085,43 @@ def pairwise_distances(X, Y=None, metric="euclidean", n_jobs=1, **kwds): from X and the jth array from Y. """ + if (metric not in _VALID_METRICS and + not callable(metric) and metric != "precomputed"): + raise ValueError("Unknown metric %s. " + "Valid metrics are %s, or 'precomputed', or a " + "callable" % (metric, _VALID_METRICS)) + if metric == "precomputed": return X - elif metric in pairwise_distance_functions: - func = pairwise_distance_functions[metric] - if n_jobs == 1: - return func(X, Y, **kwds) - else: - return _parallel_pairwise(X, Y, func, n_jobs, **kwds) + elif metric in PAIRWISE_DISTANCE_FUNCTIONS: + func = PAIRWISE_DISTANCE_FUNCTIONS[metric] elif callable(metric): - # Check matrices first (this is usually done by the metric). - X, Y = check_pairwise_arrays(X, Y) - n_x, n_y = X.shape[0], Y.shape[0] - # Calculate distance for each element in X and Y. - # FIXME: can use n_jobs here too - D = np.zeros((n_x, n_y), dtype='float') - for i in range(n_x): - start = 0 - if X is Y: - start = i - for j in range(start, n_y): - # distance assumed to be symmetric. - D[i][j] = metric(X[i], Y[j], **kwds) - if X is Y: - D[j][i] = D[i][j] - return D + func = partial(_pairwise_callable, metric=metric, **kwds) else: - # Note: the distance module doesn't support sparse matrices! - if type(X) is csr_matrix: + if issparse(X) or issparse(Y): raise TypeError("scipy distance metrics do not" " support sparse matrices.") - if Y is None: + X, Y = check_pairwise_arrays(X, Y) + if n_jobs == 1 and X is Y: return distance.squareform(distance.pdist(X, metric=metric, **kwds)) - else: - if type(Y) is csr_matrix: - raise TypeError("scipy distance metrics do not" - " support sparse matrices.") - return distance.cdist(X, Y, metric=metric, **kwds) + func = partial(distance.cdist, metric=metric, **kwds) + + return _parallel_pairwise(X, Y, func, n_jobs, **kwds) # Helper functions - distance -pairwise_kernel_functions = { +PAIRWISE_KERNEL_FUNCTIONS = { # If updating this dictionary, update the doc in both distance_metrics() # and also in pairwise_distances()! - 'rbf': rbf_kernel, - 'sigmoid': sigmoid_kernel, + 'additive_chi2': additive_chi2_kernel, + 'chi2': chi2_kernel, + 'linear': linear_kernel, 'polynomial': polynomial_kernel, 'poly': polynomial_kernel, - 'linear': linear_kernel - } + 'rbf': rbf_kernel, + 'sigmoid': sigmoid_kernel, + 'cosine': cosine_similarity, } def kernel_metrics(): @@ -539,45 +1132,52 @@ def kernel_metrics(): each of the valid strings. The valid distance metrics, and the function they map to, are: - ============ ================================== - metric Function - ============ ================================== - 'linear' sklearn.pairwise.linear_kernel - 'poly' sklearn.pairwise.polynomial_kernel - 'polynomial' sklearn.pairwise.polynomial_kernel - 'rbf' sklearn.pairwise.rbf_kernel - 'sigmoid' sklearn.pairwise.sigmoid_kernel - ============ ================================== - """ - return pairwise_kernel_functions - - -kernel_params = { - "rbf": set(("gamma",)), - "sigmoid": set(("gamma", "coef0")), - "polynomial": set(("gamma", "degree", "coef0")), - "poly": set(("gamma", "degree", "coef0")), - "linear": () + =============== ======================================== + metric Function + =============== ======================================== + 'additive_chi2' sklearn.pairwise.additive_chi2_kernel + 'chi2' sklearn.pairwise.chi2_kernel + 'linear' sklearn.pairwise.linear_kernel + 'poly' sklearn.pairwise.polynomial_kernel + 'polynomial' sklearn.pairwise.polynomial_kernel + 'rbf' sklearn.pairwise.rbf_kernel + 'sigmoid' sklearn.pairwise.sigmoid_kernel + 'cosine' sklearn.pairwise.cosine_similarity + =============== ======================================== + """ + return PAIRWISE_KERNEL_FUNCTIONS + + +KERNEL_PARAMS = { + "additive_chi2": (), + "chi2": (), + "cosine": (), + "exp_chi2": frozenset(["gamma"]), + "linear": (), + "poly": frozenset(["gamma", "degree", "coef0"]), + "polynomial": frozenset(["gamma", "degree", "coef0"]), + "rbf": frozenset(["gamma"]), + "sigmoid": frozenset(["gamma", "coef0"]), } def pairwise_kernels(X, Y=None, metric="linear", filter_params=False, n_jobs=1, **kwds): - """ Compute the kernel between arrays X and optional array Y. + """Compute the kernel between arrays X and optional array Y. This method takes either a vector array or a kernel matrix, and returns a kernel matrix. If the input is a vector array, the kernels are computed. If the input is a kernel matrix, it is returned instead. This method provides a safe way to take a kernel matrix as input, while - preserving compatability with many other algorithms that take a vector + preserving compatibility with many other algorithms that take a vector array. If Y is given (default is None), then the returned matrix is the pairwise kernel between the arrays from both X and Y. Valid values for metric are:: - ['rbf', 'sigmoid', 'polynomial', 'poly', 'linear'] + ['rbf', 'sigmoid', 'polynomial', 'poly', 'linear', 'cosine'] Parameters ---------- @@ -591,7 +1191,7 @@ def pairwise_kernels(X, Y=None, metric="linear", filter_params=False, metric : string, or callable The metric to use when calculating kernel between instances in a feature array. If metric is a string, it must be one of the metrics - in pairwise.pairwise_kernel_functions. + in pairwise.PAIRWISE_KERNEL_FUNCTIONS. If metric is "precomputed", X is assumed to be a kernel matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable @@ -604,8 +1204,8 @@ def pairwise_kernels(X, Y=None, metric="linear", filter_params=False, parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is - used at all, which is useful for debuging. For n_jobs below -1, - (n_cpus + 1 - n_jobs) are used. Thus for n_jobs = -2, all CPUs but one + used at all, which is useful for debugging. For n_jobs below -1, + (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. filter_params: boolean @@ -629,30 +1229,14 @@ def pairwise_kernels(X, Y=None, metric="linear", filter_params=False, """ if metric == "precomputed": return X - elif metric in pairwise_kernel_functions: + elif metric in PAIRWISE_KERNEL_FUNCTIONS: if filter_params: - kwds = dict((k, kwds[k]) for k in kwds \ - if k in kernel_params[metric]) - func = pairwise_kernel_functions[metric] - if n_jobs == 1: - return func(X, Y, **kwds) - else: - return _parallel_pairwise(X, Y, func, n_jobs, **kwds) + kwds = dict((k, kwds[k]) for k in kwds + if k in KERNEL_PARAMS[metric]) + func = PAIRWISE_KERNEL_FUNCTIONS[metric] elif callable(metric): - # Check matrices first (this is usually done by the metric). - X, Y = check_pairwise_arrays(X, Y) - n_x, n_y = X.shape[0], Y.shape[0] - # Calculate kernel for each element in X and Y. - K = np.zeros((n_x, n_y), dtype='float') - for i in range(n_x): - start = 0 - if X is Y: - start = i - for j in range(start, n_y): - # Kernel assumed to be symmetric. - K[i][j] = metric(X[i], Y[j], **kwds) - if X is Y: - K[j][i] = K[i][j] - return K + func = partial(_pairwise_callable, metric=metric, **kwds) else: - raise AttributeError("Unknown metric %s" % metric) + raise ValueError("Unknown kernel %r" % metric) + + return _parallel_pairwise(X, Y, func, n_jobs, **kwds) diff --git a/sklearn/metrics/pairwise_fast.c b/sklearn/metrics/pairwise_fast.c new file mode 100644 index 0000000000000..62ab30efb0567 --- /dev/null +++ b/sklearn/metrics/pairwise_fast.c @@ -0,0 +1,23188 @@ +/* Generated by Cython 0.20.1 on Mon Mar 10 14:28:31 2014 */ + +#define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#define CYTHON_ABI "0_20_1" +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if CYTHON_COMPILING_IN_PYPY +#define Py_OptimizeFlag 0 +#endif +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT) + #define Py_TPFLAGS_IS_ABSTRACT 0 +#endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_VERSION_HEX < 0x030200A4 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__metrics__pairwise_fast +#define __PYX_HAVE_API__sklearn__metrics__pairwise_fast +#include "string.h" +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#include "cblas.h" +#include "pythread.h" +#include "pystate.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +#ifdef __GNUC__ + /* Test for GCC > 2.95 */ + #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) + #else /* __GNUC__ > 2 ... */ + #define likely(x) (x) + #define unlikely(x) (x) + #endif /* __GNUC__ > 2 ... */ +#else /* __GNUC__ */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "pairwise_fast.pyx", + "__init__.pxd", + "stringsource", + "type.pxd", +}; +struct __pyx_memoryview_obj; +typedef struct { + struct __pyx_memoryview_obj *memview; + char *data; + Py_ssize_t shape[8]; + Py_ssize_t strides[8]; + Py_ssize_t suboffsets[8]; +} __Pyx_memviewslice; + +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __pyx_atomic_int_type int +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ + !defined(__i386__) + #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && MSC_VER + #include + #define __pyx_atomic_int_type LONG + #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using MSVC atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 + #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using Intel atomics" + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif +typedef volatile __pyx_atomic_int_type __pyx_atomic_int; +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview) \ + __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) +#else + #define __pyx_add_acquisition_count(memview) \ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif + + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":723 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":724 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":725 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":726 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":730 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":731 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":732 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":733 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":737 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":738 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":747 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":748 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":749 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":751 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":752 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":753 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":755 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":756 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":758 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":759 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":760 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ +struct __pyx_array_obj; +struct __pyx_MemviewEnum_obj; +struct __pyx_memoryview_obj; +struct __pyx_memoryviewslice_obj; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":762 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":763 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":764 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":766 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; + +/* "sklearn/metrics/pairwise_fast.pyx":17 + * double cblas_dasum(int, const double *, int) nogil + * + * ctypedef float [:, :] float_array_2d_t # <<<<<<<<<<<<<< + * ctypedef double [:, :] double_array_2d_t + * + */ +typedef __Pyx_memviewslice __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t; + +/* "sklearn/metrics/pairwise_fast.pyx":18 + * + * ctypedef float [:, :] float_array_2d_t + * ctypedef double [:, :] double_array_2d_t # <<<<<<<<<<<<<< + * + * cdef fused floating1d: + */ +typedef __Pyx_memviewslice __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t; + +/* "View.MemoryView":96 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ +struct __pyx_array_obj { + PyObject_HEAD + char *data; + Py_ssize_t len; + char *format; + int ndim; + Py_ssize_t *_shape; + Py_ssize_t *_strides; + Py_ssize_t itemsize; + PyObject *mode; + PyObject *_format; + void (*callback_free_data)(void *); + int free_data; + int dtype_is_object; +}; + + +/* "View.MemoryView":275 + * + * @cname('__pyx_MemviewEnum') + * cdef class Enum(object): # <<<<<<<<<<<<<< + * cdef object name + * def __init__(self, name): + */ +struct __pyx_MemviewEnum_obj { + PyObject_HEAD + PyObject *name; +}; + + +/* "View.MemoryView":308 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ +struct __pyx_memoryview_obj { + PyObject_HEAD + struct __pyx_vtabstruct_memoryview *__pyx_vtab; + PyObject *obj; + PyObject *_size; + PyObject *_array_interface; + PyThread_type_lock lock; + __pyx_atomic_int acquisition_count[2]; + __pyx_atomic_int *acquisition_count_aligned_p; + Py_buffer view; + int flags; + int dtype_is_object; + __Pyx_TypeInfo *typeinfo; +}; + + +/* "View.MemoryView":930 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ +struct __pyx_memoryviewslice_obj { + struct __pyx_memoryview_obj __pyx_base; + __Pyx_memviewslice from_slice; + PyObject *from_object; + PyObject *(*to_object_func)(char *); + int (*to_dtype_func)(char *, PyObject *); +}; + + + +/* "View.MemoryView":308 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ + +struct __pyx_vtabstruct_memoryview { + char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); + PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); +}; +static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; + + +/* "View.MemoryView":930 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ + +struct __pyx_vtabstruct__memoryviewslice { + struct __pyx_vtabstruct_memoryview __pyx_base; +}; +static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static CYTHON_INLINE int __Pyx_PySequence_Contains(PyObject* item, PyObject* seq, int eq) { + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +#include + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals +#else +#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals +#endif + +#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) : \ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck); + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d +#define __Pyx_MEMVIEW_DIRECT 1 +#define __Pyx_MEMVIEW_PTR 2 +#define __Pyx_MEMVIEW_FULL 4 +#define __Pyx_MEMVIEW_CONTIG 8 +#define __Pyx_MEMVIEW_STRIDED 16 +#define __Pyx_MEMVIEW_FOLLOW 32 +#define __Pyx_IS_C_CONTIG 1 +#define __Pyx_IS_F_CONTIG 2 +static int __Pyx_init_memviewslice( + struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference); +static CYTHON_INLINE int __pyx_add_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) +#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) +#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) +#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) +static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/ + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) + +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject* none = _PyList_Extend((PyListObject*)L, v); + if (unlikely(!none)) + return -1; + Py_DECREF(none); + return 0; +#else + return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); +#endif +} + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); + +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename, + int full_traceback); /*proto*/ + +static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ + +static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); + +#define __Pyx_CyFunction_USED 1 +#include +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CyFunction_GetClosure(f) \ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#define __Pyx_CyFunction_GetClassObj(f) \ + (((__pyx_CyFunctionObject *) (f))->func_classobj) +#define __Pyx_CyFunction_Defaults(type, f) \ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g) \ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) +typedef struct { + PyCFunctionObject func; + PyObject *func_dict; + PyObject *func_weakreflist; + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; + PyObject *func_classobj; /* No-args super() class cell */ + void *defaults; + int defaults_pyobjects; + int flags; + PyObject *defaults_tuple; /* Const defaults tuple */ + PyObject *defaults_kwdict; /* Const kwonly defaults dict */ + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; /* function annotations dict */ +} __pyx_CyFunctionObject; +static PyTypeObject *__pyx_CyFunctionType = 0; +#define __Pyx_CyFunction_NewEx(ml, flags, qualname, self, module, globals, code) \ + __Pyx_CyFunction_New(__pyx_CyFunctionType, ml, flags, qualname, self, module, globals, code) +static PyObject *__Pyx_CyFunction_New(PyTypeObject *, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *self, + PyObject *module, PyObject *globals, + PyObject* code); +static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *m, + size_t size, + int pyobjects); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __Pyx_CyFunction_init(void); + +typedef struct { + __pyx_CyFunctionObject func; + PyObject *__signatures__; + PyObject *type; + PyObject *self; +} __pyx_FusedFunctionObject; +#define __pyx_FusedFunction_NewEx(ml, flags, qualname, self, module, globals, code) \ + __pyx_FusedFunction_New(__pyx_FusedFunctionType, ml, flags, qualname, self, module, globals, code) +static PyObject *__pyx_FusedFunction_New(PyTypeObject *type, + PyMethodDef *ml, int flags, + PyObject *qualname, PyObject *self, + PyObject *module, PyObject *globals, + PyObject *code); +static int __pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self); +static PyTypeObject *__pyx_FusedFunctionType = NULL; +static int __pyx_FusedFunction_init(void); +#define __Pyx_FusedFunction_USED + +static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); + +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_float(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *); + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_float(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_double(PyObject *); + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *); + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_char(char value); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim); + +static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize); + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object); + +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); + +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); + +static int __Pyx_check_binary_version(void); + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'sklearn.metrics.pairwise_fast' */ +static PyTypeObject *__pyx_array_type = 0; +static PyTypeObject *__pyx_MemviewEnum_type = 0; +static PyTypeObject *__pyx_memoryview_type = 0; +static PyTypeObject *__pyx_memoryviewslice_type = 0; +static PyObject *generic = 0; +static PyObject *strided = 0; +static PyObject *indirect = 0; +static PyObject *contiguous = 0; +static PyObject *indirect_contiguous = 0; +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ +static void *__pyx_align_pointer(void *, size_t); /*proto*/ +static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ +static PyObject *_unellipsify(PyObject *, int); /*proto*/ +static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ +static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ +static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ +static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ +static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ +static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ +static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ +static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_float = { "float", NULL, sizeof(float), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 }; +#define __Pyx_MODULE_NAME "sklearn.metrics.pairwise_fast" +int __pyx_module_is_main_sklearn__metrics__pairwise_fast = 0; + +/* Implementation of 'sklearn.metrics.pairwise_fast' */ +static PyObject *__pyx_builtin_ImportError; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_ord; +static PyObject *__pyx_builtin_zip; +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_Ellipsis; +static PyObject *__pyx_builtin_xrange; +static PyObject *__pyx_builtin_id; +static PyObject *__pyx_builtin_IndexError; +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast__chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults); /* proto */ +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_4_chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_X, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_Y, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_result); /* proto */ +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_6_chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_X, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_Y, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_result); /* proto */ +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults); /* proto */ +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_10_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X_data, __Pyx_memviewslice __pyx_v_X_indices, __Pyx_memviewslice __pyx_v_X_indptr, __Pyx_memviewslice __pyx_v_Y_data, __Pyx_memviewslice __pyx_v_Y_indices, __Pyx_memviewslice __pyx_v_Y_indptr, npy_intp __pyx_v_n_features, __Pyx_memviewslice __pyx_v_D); /* proto */ +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_12_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X_data, __Pyx_memviewslice __pyx_v_X_indices, __Pyx_memviewslice __pyx_v_X_indptr, __Pyx_memviewslice __pyx_v_Y_data, __Pyx_memviewslice __pyx_v_Y_indices, __Pyx_memviewslice __pyx_v_Y_indptr, npy_intp __pyx_v_n_features, __Pyx_memviewslice __pyx_v_D); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_B[] = "B"; +static char __pyx_k_D[] = "D"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_X[] = "X"; +static char __pyx_k_Y[] = "Y"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_c[] = "c"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_j[] = "j"; +static char __pyx_k_k[] = "k"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_u[] = "u"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k__2[] = "()"; +static char __pyx_k__4[] = "|"; +static char __pyx_k_id[] = "id"; +static char __pyx_k_ix[] = "ix"; +static char __pyx_k_iy[] = "iy"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_nom[] = "nom"; +static char __pyx_k_obj[] = "obj"; +static char __pyx_k_ord[] = "ord"; +static char __pyx_k_res[] = "res"; +static char __pyx_k_row[] = "row"; +static char __pyx_k_zip[] = "zip"; +static char __pyx_k_args[] = "args"; +static char __pyx_k_base[] = "base"; +static char __pyx_k_kind[] = "kind"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_mode[] = "mode"; +static char __pyx_k_name[] = "name"; +static char __pyx_k_ndim[] = "ndim"; +static char __pyx_k_pack[] = "pack"; +static char __pyx_k_size[] = "size"; +static char __pyx_k_step[] = "step"; +static char __pyx_k_stop[] = "stop"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_ASCII[] = "ASCII"; +static char __pyx_k_class[] = "__class__"; +static char __pyx_k_denom[] = "denom"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_empty[] = "empty"; +static char __pyx_k_error[] = "error"; +static char __pyx_k_flags[] = "flags"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_shape[] = "shape"; +static char __pyx_k_split[] = "split"; +static char __pyx_k_start[] = "start"; +static char __pyx_k_strip[] = "strip"; +static char __pyx_k_X_data[] = "X_data"; +static char __pyx_k_Y_data[] = "Y_data"; +static char __pyx_k_decode[] = "decode"; +static char __pyx_k_encode[] = "encode"; +static char __pyx_k_format[] = "format"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_kwargs[] = "kwargs"; +static char __pyx_k_name_2[] = "__name__"; +static char __pyx_k_result[] = "result"; +static char __pyx_k_struct[] = "struct"; +static char __pyx_k_unpack[] = "unpack"; +static char __pyx_k_xrange[] = "xrange"; +static char __pyx_k_float_1[] = "float[::1]"; +static char __pyx_k_fortran[] = "fortran"; +static char __pyx_k_memview[] = "memview"; +static char __pyx_k_ndarray[] = "ndarray"; +static char __pyx_k_Ellipsis[] = "Ellipsis"; +static char __pyx_k_X_indptr[] = "X_indptr"; +static char __pyx_k_Y_indptr[] = "Y_indptr"; +static char __pyx_k_defaults[] = "defaults"; +static char __pyx_k_double_1[] = "double[::1]"; +static char __pyx_k_itemsize[] = "itemsize"; +static char __pyx_k_TypeError[] = "TypeError"; +static char __pyx_k_X_indices[] = "X_indices"; +static char __pyx_k_Y_indices[] = "Y_indices"; +static char __pyx_k_enumerate[] = "enumerate"; +static char __pyx_k_IndexError[] = "IndexError"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_n_features[] = "n_features"; +static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static char __pyx_k_signatures[] = "signatures"; +static char __pyx_k_ImportError[] = "ImportError"; +static char __pyx_k_MemoryError[] = "MemoryError"; +static char __pyx_k_n_samples_X[] = "n_samples_X"; +static char __pyx_k_n_samples_Y[] = "n_samples_Y"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k_allocate_buffer[] = "allocate_buffer"; +static char __pyx_k_dtype_is_object[] = "dtype_is_object"; +static char __pyx_k_chi2_kernel_fast[] = "_chi2_kernel_fast"; +static char __pyx_k_float_array_2d_t[] = "float_array_2d_t"; +static char __pyx_k_sparse_manhattan[] = "_sparse_manhattan"; +static char __pyx_k_double_array_2d_t[] = "double_array_2d_t"; +static char __pyx_k_pyx_releasebuffer[] = "__pyx_releasebuffer"; +static char __pyx_k_strided_and_direct[] = ""; +static char __pyx_k_strided_and_indirect[] = ""; +static char __pyx_k_contiguous_and_direct[] = ""; +static char __pyx_k_MemoryView_of_r_object[] = ""; +static char __pyx_k_MemoryView_of_r_at_0x_x[] = ""; +static char __pyx_k_contiguous_and_indirect[] = ""; +static char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; +static char __pyx_k_getbuffer_obj_view_flags[] = "getbuffer(obj, view, flags)"; +static char __pyx_k_sparse_manhattan_line_53[] = "_sparse_manhattan (line 53)"; +static char __pyx_k_Dimension_d_is_not_direct[] = "Dimension %d is not direct"; +static char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; +static char __pyx_k_Index_out_of_bounds_axis_d[] = "Index out of bounds (axis %d)"; +static char __pyx_k_No_matching_signature_found[] = "No matching signature found"; +static char __pyx_k_Step_may_not_be_zero_axis_d[] = "Step may not be zero (axis %d)"; +static char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_Expected_at_least_d_arguments[] = "Expected at least %d arguments"; +static char __pyx_k_sklearn_metrics_pairwise_fast[] = "sklearn.metrics.pairwise_fast"; +static char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; +static char __pyx_k_strided_and_direct_or_indirect[] = ""; +static char __pyx_k_home_larsb_src_scikit_learn_skl[] = "/home/larsb/src/scikit-learn/sklearn/metrics/pairwise_fast.pyx"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_All_dimensions_preceding_dimensi[] = "All dimensions preceding dimension %d must be indexed and not sliced"; +static char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; +static char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; +static char __pyx_k_Cannot_transpose_memoryview_with[] = "Cannot transpose memoryview with indirect dimensions"; +static char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Function_call_with_ambiguous_arg[] = "Function call with ambiguous argument types"; +static char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; +static char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; +static char __pyx_k_Pairwise_L1_distances_for_CSR_ma[] = "Pairwise L1 distances for CSR matrices.\n\n Usage:\n\n >>> D = np.zeros(X.shape[0], Y.shape[0])\n >>> sparse_manhattan(X.data, X.indices, X.indptr,\n ... Y.data, Y.indices, Y.indptr,\n ... X.shape[1], D)\n "; +static char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; +static char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_unable_to_allocate_shape_or_stri[] = "unable to allocate shape or strides."; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_n_s_ASCII; +static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; +static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; +static PyObject *__pyx_kp_s_Cannot_index_with_type_s; +static PyObject *__pyx_n_s_D; +static PyObject *__pyx_n_s_Ellipsis; +static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; +static PyObject *__pyx_kp_s_Expected_at_least_d_arguments; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_kp_s_Function_call_with_ambiguous_arg; +static PyObject *__pyx_n_s_ImportError; +static PyObject *__pyx_n_s_IndexError; +static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; +static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; +static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; +static PyObject *__pyx_n_s_MemoryError; +static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; +static PyObject *__pyx_kp_s_MemoryView_of_r_object; +static PyObject *__pyx_kp_s_No_matching_signature_found; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_b_O; +static PyObject *__pyx_n_s_O; +static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; +static PyObject *__pyx_kp_u_Pairwise_L1_distances_for_CSR_ma; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_TypeError; +static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_n_s_X_data; +static PyObject *__pyx_n_s_X_indices; +static PyObject *__pyx_n_s_X_indptr; +static PyObject *__pyx_n_s_Y; +static PyObject *__pyx_n_s_Y_data; +static PyObject *__pyx_n_s_Y_indices; +static PyObject *__pyx_n_s_Y_indptr; +static PyObject *__pyx_kp_s__2; +static PyObject *__pyx_kp_s__4; +static PyObject *__pyx_n_s_allocate_buffer; +static PyObject *__pyx_n_s_args; +static PyObject *__pyx_n_s_base; +static PyObject *__pyx_n_b_c; +static PyObject *__pyx_n_s_c; +static PyObject *__pyx_n_u_c; +static PyObject *__pyx_n_s_chi2_kernel_fast; +static PyObject *__pyx_n_s_class; +static PyObject *__pyx_kp_s_contiguous_and_direct; +static PyObject *__pyx_kp_s_contiguous_and_indirect; +static PyObject *__pyx_n_s_decode; +static PyObject *__pyx_n_s_defaults; +static PyObject *__pyx_n_s_denom; +static PyObject *__pyx_kp_s_double_1; +static PyObject *__pyx_n_s_double_array_2d_t; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_dtype_is_object; +static PyObject *__pyx_n_s_empty; +static PyObject *__pyx_n_s_encode; +static PyObject *__pyx_n_s_enumerate; +static PyObject *__pyx_n_s_error; +static PyObject *__pyx_n_s_f; +static PyObject *__pyx_n_s_flags; +static PyObject *__pyx_kp_s_float_1; +static PyObject *__pyx_n_s_float_array_2d_t; +static PyObject *__pyx_n_s_format; +static PyObject *__pyx_n_b_fortran; +static PyObject *__pyx_n_s_fortran; +static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; +static PyObject *__pyx_kp_s_home_larsb_src_scikit_learn_skl; +static PyObject *__pyx_n_s_i; +static PyObject *__pyx_n_s_id; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_itemsize; +static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; +static PyObject *__pyx_n_s_ix; +static PyObject *__pyx_n_s_iy; +static PyObject *__pyx_n_s_j; +static PyObject *__pyx_n_s_k; +static PyObject *__pyx_n_s_kind; +static PyObject *__pyx_n_s_kwargs; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_memview; +static PyObject *__pyx_n_s_mode; +static PyObject *__pyx_n_s_n_features; +static PyObject *__pyx_n_s_n_samples_X; +static PyObject *__pyx_n_s_n_samples_Y; +static PyObject *__pyx_n_s_name; +static PyObject *__pyx_n_s_name_2; +static PyObject *__pyx_n_s_ndarray; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_ndim; +static PyObject *__pyx_n_s_nom; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_obj; +static PyObject *__pyx_n_s_ord; +static PyObject *__pyx_n_s_pack; +static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_releasebuffer; +static PyObject *__pyx_n_s_pyx_vtable; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_res; +static PyObject *__pyx_n_s_result; +static PyObject *__pyx_n_s_row; +static PyObject *__pyx_n_s_shape; +static PyObject *__pyx_n_s_signatures; +static PyObject *__pyx_n_s_size; +static PyObject *__pyx_n_s_sklearn_metrics_pairwise_fast; +static PyObject *__pyx_n_s_sparse_manhattan; +static PyObject *__pyx_kp_u_sparse_manhattan_line_53; +static PyObject *__pyx_n_s_split; +static PyObject *__pyx_n_s_start; +static PyObject *__pyx_n_s_step; +static PyObject *__pyx_n_s_stop; +static PyObject *__pyx_kp_s_strided_and_direct; +static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; +static PyObject *__pyx_kp_s_strided_and_indirect; +static PyObject *__pyx_n_s_strip; +static PyObject *__pyx_n_s_struct; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_n_s_u; +static PyObject *__pyx_kp_s_unable_to_allocate_array_data; +static PyObject *__pyx_kp_s_unable_to_allocate_shape_or_stri; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_unpack; +static PyObject *__pyx_n_s_xrange; +static PyObject *__pyx_n_s_zip; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_1; +static PyObject *__pyx_int_2; +static PyObject *__pyx_int_105; +static PyObject *__pyx_int_neg_1; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__8; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_tuple__10; +static PyObject *__pyx_tuple__11; +static PyObject *__pyx_tuple__12; +static PyObject *__pyx_tuple__13; +static PyObject *__pyx_tuple__14; +static PyObject *__pyx_tuple__15; +static PyObject *__pyx_tuple__16; +static PyObject *__pyx_tuple__17; +static PyObject *__pyx_tuple__18; +static PyObject *__pyx_tuple__19; +static PyObject *__pyx_tuple__20; +static PyObject *__pyx_tuple__21; +static PyObject *__pyx_tuple__22; +static PyObject *__pyx_tuple__23; +static PyObject *__pyx_tuple__24; +static PyObject *__pyx_tuple__25; +static PyObject *__pyx_tuple__26; +static PyObject *__pyx_tuple__27; +static PyObject *__pyx_tuple__28; +static PyObject *__pyx_tuple__29; +static PyObject *__pyx_tuple__30; +static PyObject *__pyx_tuple__31; +static PyObject *__pyx_tuple__32; +static PyObject *__pyx_tuple__34; +static PyObject *__pyx_tuple__36; +static PyObject *__pyx_tuple__37; +static PyObject *__pyx_tuple__38; +static PyObject *__pyx_tuple__39; +static PyObject *__pyx_tuple__40; +static PyObject *__pyx_codeobj__33; +static PyObject *__pyx_codeobj__35; + +/* "sklearn/metrics/pairwise_fast.pyx":32 + * + * + * def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<< + * floating_array_2d_t Y, + * floating_array_2d_t result): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7metrics_13pairwise_fast_1_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_7metrics_13pairwise_fast_1_chi2_kernel_fast = {__Pyx_NAMESTR("_chi2_kernel_fast"), (PyCFunction)__pyx_pw_7sklearn_7metrics_13pairwise_fast_1_chi2_kernel_fast, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_7metrics_13pairwise_fast_1_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_signatures = 0; + PyObject *__pyx_v_args = 0; + PyObject *__pyx_v_kwargs = 0; + CYTHON_UNUSED PyObject *__pyx_v_defaults = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_fused_cpdef (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_signatures,&__pyx_n_s_args,&__pyx_n_s_kwargs,&__pyx_n_s_defaults,0}; + PyObject* values[4] = {0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_signatures)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_args)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kwargs)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_defaults)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_fused_cpdef") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + } + __pyx_v_signatures = values[0]; + __pyx_v_args = values[1]; + __pyx_v_kwargs = values[2]; + __pyx_v_defaults = values[3]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast__chi2_kernel_fast(__pyx_self, __pyx_v_signatures, __pyx_v_args, __pyx_v_kwargs, __pyx_v_defaults); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast__chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults) { + PyObject *__pyx_v_dest_sig = NULL; + PyObject *__pyx_v_numpy = NULL; + __Pyx_memviewslice __pyx_v_memslice; + Py_ssize_t __pyx_v_itemsize; + CYTHON_UNUSED int __pyx_v_dtype_signed; + char __pyx_v_kind; + PyObject *__pyx_v_arg = NULL; + PyObject *__pyx_v_dtype = NULL; + PyObject *__pyx_v_candidates = NULL; + PyObject *__pyx_v_sig = NULL; + int __pyx_v_match_found; + PyObject *__pyx_v_src_type = NULL; + PyObject *__pyx_v_dst_type = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + char __pyx_t_12; + PyObject *(*__pyx_t_13)(PyObject *); + Py_ssize_t __pyx_t_14; + PyObject *(*__pyx_t_15)(PyObject *); + PyObject *__pyx_t_16 = NULL; + PyObject *__pyx_t_17 = NULL; + PyObject *__pyx_t_18 = NULL; + PyObject *(*__pyx_t_19)(PyObject *); + int __pyx_t_20; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_chi2_kernel_fast", 0); + __Pyx_INCREF(__pyx_v_kwargs); + __pyx_t_1 = PyList_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 0, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 1, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 2, Py_None); + __Pyx_GIVEREF(Py_None); + __pyx_v_dest_sig = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_2 = (__pyx_v_kwargs == Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF_SET(__pyx_v_kwargs, __pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L3; + } + __pyx_L3:; + { + __Pyx_ExceptionSave(&__pyx_t_4, &__pyx_t_5, &__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_6); + /*try:*/ { + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_numpy = __pyx_t_1; + __pyx_t_1 = 0; + } + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L11_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_7 = PyErr_ExceptionMatches(__pyx_builtin_ImportError); + if (__pyx_t_7) { + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_8, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_9); + __Pyx_INCREF(Py_None); + __Pyx_XDECREF_SET(__pyx_v_numpy, Py_None); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L5_exception_handled; + } + goto __pyx_L6_except_error; + __pyx_L6_except_error:; + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_XGIVEREF(__pyx_t_6); + __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); + goto __pyx_L1_error; + __pyx_L5_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_XGIVEREF(__pyx_t_6); + __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); + __pyx_L11_try_end:; + } + __pyx_v_itemsize = -1; + __pyx_t_10 = PyObject_Length(__pyx_v_args); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((0 < __pyx_t_10) != 0); + if (__pyx_t_3) { + __pyx_t_9 = __Pyx_GetItemInt(__pyx_v_args, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_9); + __pyx_v_arg = __pyx_t_9; + __pyx_t_9 = 0; + goto __pyx_L14; + } + __pyx_t_3 = (__Pyx_PySequence_Contains(__pyx_n_s_X, __pyx_v_kwargs, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__pyx_t_3 != 0); + if (__pyx_t_2) { + __pyx_t_9 = PyObject_GetItem(__pyx_v_kwargs, __pyx_n_s_X); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_9); + __pyx_v_arg = __pyx_t_9; + __pyx_t_9 = 0; + goto __pyx_L14; + } + /*else*/ { + __pyx_t_10 = PyObject_Length(__pyx_v_args); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = PyInt_FromSsize_t(__pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_8 = __Pyx_PyString_Format(__pyx_kp_s_Expected_at_least_d_arguments, __pyx_t_9); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L14:; + if (0) { + goto __pyx_L15; + } + /*else*/ { + while (1) { + if (!1) break; + __pyx_t_2 = (__pyx_v_numpy != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_numpy, __pyx_n_s_ndarray); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_3 = PyObject_IsInstance(__pyx_v_arg, __pyx_t_8); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_2 = (__pyx_t_3 != 0); + if (__pyx_t_2) { + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_v_dtype = __pyx_t_8; + __pyx_t_8 = 0; + goto __pyx_L19; + } + __pyx_t_2 = (__pyx_memoryview_check(__pyx_v_arg) != 0); + if (__pyx_t_2) { + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_numpy, __pyx_n_s_ndarray); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_3 = PyObject_IsInstance(__pyx_t_8, __pyx_t_9); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_11 = (__pyx_t_3 != 0); + } else { + __pyx_t_11 = __pyx_t_2; + } + if (__pyx_t_11) { + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_dtype = __pyx_t_8; + __pyx_t_8 = 0; + goto __pyx_L19; + } + /*else*/ { + __Pyx_INCREF(Py_None); + __pyx_v_dtype = Py_None; + } + __pyx_L19:; + __pyx_v_itemsize = -1; + __pyx_t_11 = (__pyx_v_dtype != Py_None); + __pyx_t_2 = (__pyx_t_11 != 0); + if (__pyx_t_2) { + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_itemsize = __pyx_t_10; + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ord, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_12 = __Pyx_PyInt_As_char(__pyx_t_8); if (unlikely((__pyx_t_12 == (char)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_kind = __pyx_t_12; + __pyx_t_8 = __Pyx_PyInt_From_char(__pyx_v_kind); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyObject_RichCompare(__pyx_t_8, __pyx_int_105, Py_EQ); __Pyx_XGOTREF(__pyx_t_9); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_dtype_signed = __pyx_t_2; + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_2 = (__Pyx_PySequence_Contains(__pyx_t_9, __pyx_tuple_, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_11 = (__pyx_t_2 != 0); + if (__pyx_t_11) { + goto __pyx_L21; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_11 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_f, Py_EQ)); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (__pyx_t_11) { + __pyx_t_11 = ((sizeof(float)) == __pyx_v_itemsize); + if (__pyx_t_11) { + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_8 = PyObject_RichCompare(__pyx_t_9, __pyx_int_2, Py_EQ); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_11; + } + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_float_array_2d_t, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L17_break; + } + __pyx_t_3 = ((sizeof(double)) == __pyx_v_itemsize); + if (__pyx_t_3) { + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyObject_RichCompare(__pyx_t_8, __pyx_int_2, Py_EQ); __Pyx_XGOTREF(__pyx_t_9); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = __pyx_t_11; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_double_array_2d_t, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L17_break; + } + goto __pyx_L21; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_2 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (__pyx_t_2) { + goto __pyx_L21; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_2 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_O, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (__pyx_t_2) { + goto __pyx_L21; + } + __pyx_L21:; + goto __pyx_L20; + } + __pyx_L20:; + goto __pyx_L18; + } + __pyx_L18:; + __pyx_t_2 = ((__pyx_v_itemsize == -1) != 0); + if (!__pyx_t_2) { + __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(float))) != 0); + __pyx_t_11 = __pyx_t_3; + } else { + __pyx_t_11 = __pyx_t_2; + } + if (__pyx_t_11) { + __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_dsds_float(__pyx_v_arg); + __pyx_t_11 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_11) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_float_array_2d_t, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L17_break; + } + /*else*/ { + PyErr_Clear(); + } + goto __pyx_L24; + } + __pyx_L24:; + __pyx_t_11 = ((__pyx_v_itemsize == -1) != 0); + if (!__pyx_t_11) { + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(double))) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_11; + } + if (__pyx_t_3) { + __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(__pyx_v_arg); + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_double_array_2d_t, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L17_break; + } + /*else*/ { + PyErr_Clear(); + } + goto __pyx_L26; + } + __pyx_L26:; + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, Py_None, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L17_break; + } + __pyx_L17_break:; + } + __pyx_L15:; + __pyx_t_9 = PyList_New(0); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_v_candidates = ((PyObject*)__pyx_t_9); + __pyx_t_9 = 0; + if (PyList_CheckExact(__pyx_v_signatures) || PyTuple_CheckExact(__pyx_v_signatures)) { + __pyx_t_9 = __pyx_v_signatures; __Pyx_INCREF(__pyx_t_9); __pyx_t_10 = 0; + __pyx_t_13 = NULL; + } else { + __pyx_t_10 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_v_signatures); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_13 = Py_TYPE(__pyx_t_9)->tp_iternext; + } + for (;;) { + if (!__pyx_t_13 && PyList_CheckExact(__pyx_t_9)) { + if (__pyx_t_10 >= PyList_GET_SIZE(__pyx_t_9)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_8 = PyList_GET_ITEM(__pyx_t_9, __pyx_t_10); __Pyx_INCREF(__pyx_t_8); __pyx_t_10++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_8 = PySequence_ITEM(__pyx_t_9, __pyx_t_10); __pyx_t_10++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_13 && PyTuple_CheckExact(__pyx_t_9)) { + if (__pyx_t_10 >= PyTuple_GET_SIZE(__pyx_t_9)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_8 = PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_10); __Pyx_INCREF(__pyx_t_8); __pyx_t_10++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_8 = PySequence_ITEM(__pyx_t_9, __pyx_t_10); __pyx_t_10++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_8 = __pyx_t_13(__pyx_t_9); + if (unlikely(!__pyx_t_8)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_8); + } + __Pyx_XDECREF_SET(__pyx_v_sig, __pyx_t_8); + __pyx_t_8 = 0; + __pyx_v_match_found = 0; + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_sig, __pyx_n_s_strip); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_split); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyTuple_New(2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_dest_sig); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_v_dest_sig); + __Pyx_GIVEREF(__pyx_v_dest_sig); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_8, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (PyList_CheckExact(__pyx_t_1) || PyTuple_CheckExact(__pyx_t_1)) { + __pyx_t_8 = __pyx_t_1; __Pyx_INCREF(__pyx_t_8); __pyx_t_14 = 0; + __pyx_t_15 = NULL; + } else { + __pyx_t_14 = -1; __pyx_t_8 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_15 = Py_TYPE(__pyx_t_8)->tp_iternext; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (;;) { + if (!__pyx_t_15 && PyList_CheckExact(__pyx_t_8)) { + if (__pyx_t_14 >= PyList_GET_SIZE(__pyx_t_8)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_1 = PyList_GET_ITEM(__pyx_t_8, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_8, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_15 && PyTuple_CheckExact(__pyx_t_8)) { + if (__pyx_t_14 >= PyTuple_GET_SIZE(__pyx_t_8)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_8, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_8, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_1 = __pyx_t_15(__pyx_t_8); + if (unlikely(!__pyx_t_1)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_1); + } + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_16 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_17 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_16 = PyList_GET_ITEM(sequence, 0); + __pyx_t_17 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_16); + __Pyx_INCREF(__pyx_t_17); + #else + __pyx_t_16 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_16); + __pyx_t_17 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_17); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_18 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_18); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_19 = Py_TYPE(__pyx_t_18)->tp_iternext; + index = 0; __pyx_t_16 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_16)) goto __pyx_L32_unpacking_failed; + __Pyx_GOTREF(__pyx_t_16); + index = 1; __pyx_t_17 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_17)) goto __pyx_L32_unpacking_failed; + __Pyx_GOTREF(__pyx_t_17); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_19(__pyx_t_18), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_19 = NULL; + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + goto __pyx_L33_unpacking_done; + __pyx_L32_unpacking_failed:; + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + __pyx_t_19 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L33_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_src_type, __pyx_t_16); + __pyx_t_16 = 0; + __Pyx_XDECREF_SET(__pyx_v_dst_type, __pyx_t_17); + __pyx_t_17 = 0; + __pyx_t_3 = (__pyx_v_dst_type != Py_None); + __pyx_t_11 = (__pyx_t_3 != 0); + if (__pyx_t_11) { + __pyx_t_1 = PyObject_RichCompare(__pyx_v_src_type, __pyx_v_dst_type, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_11) { + __pyx_v_match_found = 1; + goto __pyx_L35; + } + /*else*/ { + __pyx_v_match_found = 0; + goto __pyx_L31_break; + } + __pyx_L35:; + goto __pyx_L34; + } + __pyx_L34:; + } + __pyx_L31_break:; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_11 = (__pyx_v_match_found != 0); + if (__pyx_t_11) { + __pyx_t_20 = __Pyx_PyList_Append(__pyx_v_candidates, __pyx_v_sig); if (unlikely(__pyx_t_20 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L36; + } + __pyx_L36:; + } + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_11 = (__pyx_v_candidates != Py_None) && (PyList_GET_SIZE(__pyx_v_candidates) != 0); + __pyx_t_3 = ((!__pyx_t_11) != 0); + if (__pyx_t_3) { + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_10 = PyList_GET_SIZE(__pyx_v_candidates); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((__pyx_t_10 > 1) != 0); + if (__pyx_t_3) { + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __pyx_t_9 = PyObject_GetItem(__pyx_v_signatures, PyList_GET_ITEM(__pyx_v_candidates, 0)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_9); + __pyx_r = __pyx_t_9; + __pyx_t_9 = 0; + goto __pyx_L0; + } + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_16); + __Pyx_XDECREF(__pyx_t_17); + __Pyx_XDECREF(__pyx_t_18); + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_dest_sig); + __Pyx_XDECREF(__pyx_v_numpy); + __Pyx_XDECREF(__pyx_v_arg); + __Pyx_XDECREF(__pyx_v_dtype); + __Pyx_XDECREF(__pyx_v_candidates); + __Pyx_XDECREF(__pyx_v_sig); + __Pyx_XDECREF(__pyx_v_src_type); + __Pyx_XDECREF(__pyx_v_dst_type); + __Pyx_XDECREF(__pyx_v_kwargs); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_5_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_fuse_0__pyx_mdef_7sklearn_7metrics_13pairwise_fast_5_chi2_kernel_fast = {__Pyx_NAMESTR("__pyx_fuse_0_chi2_kernel_fast"), (PyCFunction)__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_5_chi2_kernel_fast, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_5_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_result = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_chi2_kernel_fast (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_Y,&__pyx_n_s_result,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_result)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_chi2_kernel_fast") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_float(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_dsds_float(values[1]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_result = __Pyx_PyObject_to_MemoryviewSlice_dsds_float(values[2]); if (unlikely(!__pyx_v_result.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast._chi2_kernel_fast", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast_4_chi2_kernel_fast(__pyx_self, __pyx_v_X, __pyx_v_Y, __pyx_v_result); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_4_chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_X, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_Y, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_result) { + npy_intp __pyx_v_i; + npy_intp __pyx_v_j; + npy_intp __pyx_v_k; + npy_intp __pyx_v_n_samples_X; + npy_intp __pyx_v_n_samples_Y; + npy_intp __pyx_v_n_features; + double __pyx_v_res; + double __pyx_v_nom; + double __pyx_v_denom; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + npy_intp __pyx_t_1; + npy_intp __pyx_t_2; + npy_intp __pyx_t_3; + npy_intp __pyx_t_4; + npy_intp __pyx_t_5; + npy_intp __pyx_t_6; + npy_intp __pyx_t_7; + npy_intp __pyx_t_8; + npy_intp __pyx_t_9; + npy_intp __pyx_t_10; + npy_intp __pyx_t_11; + npy_intp __pyx_t_12; + npy_intp __pyx_t_13; + npy_intp __pyx_t_14; + int __pyx_t_15; + __Pyx_RefNannySetupContext("__pyx_fuse_0_chi2_kernel_fast", 0); + + /* "sklearn/metrics/pairwise_fast.pyx":36 + * floating_array_2d_t result): + * cdef np.npy_intp i, j, k + * cdef np.npy_intp n_samples_X = X.shape[0] # <<<<<<<<<<<<<< + * cdef np.npy_intp n_samples_Y = Y.shape[0] + * cdef np.npy_intp n_features = X.shape[1] + */ + __pyx_v_n_samples_X = (__pyx_v_X.shape[0]); + + /* "sklearn/metrics/pairwise_fast.pyx":37 + * cdef np.npy_intp i, j, k + * cdef np.npy_intp n_samples_X = X.shape[0] + * cdef np.npy_intp n_samples_Y = Y.shape[0] # <<<<<<<<<<<<<< + * cdef np.npy_intp n_features = X.shape[1] + * cdef double res, nom, denom + */ + __pyx_v_n_samples_Y = (__pyx_v_Y.shape[0]); + + /* "sklearn/metrics/pairwise_fast.pyx":38 + * cdef np.npy_intp n_samples_X = X.shape[0] + * cdef np.npy_intp n_samples_Y = Y.shape[0] + * cdef np.npy_intp n_features = X.shape[1] # <<<<<<<<<<<<<< + * cdef double res, nom, denom + * + */ + __pyx_v_n_features = (__pyx_v_X.shape[1]); + + /* "sklearn/metrics/pairwise_fast.pyx":41 + * cdef double res, nom, denom + * + * with nogil: # <<<<<<<<<<<<<< + * for i in range(n_samples_X): + * for j in range(n_samples_Y): + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/metrics/pairwise_fast.pyx":42 + * + * with nogil: + * for i in range(n_samples_X): # <<<<<<<<<<<<<< + * for j in range(n_samples_Y): + * res = 0 + */ + __pyx_t_1 = __pyx_v_n_samples_X; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "sklearn/metrics/pairwise_fast.pyx":43 + * with nogil: + * for i in range(n_samples_X): + * for j in range(n_samples_Y): # <<<<<<<<<<<<<< + * res = 0 + * for k in range(n_features): + */ + __pyx_t_3 = __pyx_v_n_samples_Y; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_j = __pyx_t_4; + + /* "sklearn/metrics/pairwise_fast.pyx":44 + * for i in range(n_samples_X): + * for j in range(n_samples_Y): + * res = 0 # <<<<<<<<<<<<<< + * for k in range(n_features): + * denom = (X[i, k] - Y[j, k]) + */ + __pyx_v_res = 0.0; + + /* "sklearn/metrics/pairwise_fast.pyx":45 + * for j in range(n_samples_Y): + * res = 0 + * for k in range(n_features): # <<<<<<<<<<<<<< + * denom = (X[i, k] - Y[j, k]) + * nom = (X[i, k] + Y[j, k]) + */ + __pyx_t_5 = __pyx_v_n_features; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_k = __pyx_t_6; + + /* "sklearn/metrics/pairwise_fast.pyx":46 + * res = 0 + * for k in range(n_features): + * denom = (X[i, k] - Y[j, k]) # <<<<<<<<<<<<<< + * nom = (X[i, k] + Y[j, k]) + * if nom != 0: + */ + __pyx_t_7 = __pyx_v_i; + __pyx_t_8 = __pyx_v_k; + __pyx_t_9 = __pyx_v_j; + __pyx_t_10 = __pyx_v_k; + __pyx_v_denom = ((*((float *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_X.data + __pyx_t_7 * __pyx_v_X.strides[0]) ) + __pyx_t_8 * __pyx_v_X.strides[1]) ))) - (*((float *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_9 * __pyx_v_Y.strides[0]) ) + __pyx_t_10 * __pyx_v_Y.strides[1]) )))); + + /* "sklearn/metrics/pairwise_fast.pyx":47 + * for k in range(n_features): + * denom = (X[i, k] - Y[j, k]) + * nom = (X[i, k] + Y[j, k]) # <<<<<<<<<<<<<< + * if nom != 0: + * res += denom * denom / nom + */ + __pyx_t_11 = __pyx_v_i; + __pyx_t_12 = __pyx_v_k; + __pyx_t_13 = __pyx_v_j; + __pyx_t_14 = __pyx_v_k; + __pyx_v_nom = ((*((float *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_X.data + __pyx_t_11 * __pyx_v_X.strides[0]) ) + __pyx_t_12 * __pyx_v_X.strides[1]) ))) + (*((float *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_13 * __pyx_v_Y.strides[0]) ) + __pyx_t_14 * __pyx_v_Y.strides[1]) )))); + + /* "sklearn/metrics/pairwise_fast.pyx":48 + * denom = (X[i, k] - Y[j, k]) + * nom = (X[i, k] + Y[j, k]) + * if nom != 0: # <<<<<<<<<<<<<< + * res += denom * denom / nom + * result[i, j] = -res + */ + __pyx_t_15 = ((__pyx_v_nom != 0.0) != 0); + if (__pyx_t_15) { + + /* "sklearn/metrics/pairwise_fast.pyx":49 + * nom = (X[i, k] + Y[j, k]) + * if nom != 0: + * res += denom * denom / nom # <<<<<<<<<<<<<< + * result[i, j] = -res + * + */ + __pyx_v_res = (__pyx_v_res + ((__pyx_v_denom * __pyx_v_denom) / __pyx_v_nom)); + goto __pyx_L12; + } + __pyx_L12:; + } + + /* "sklearn/metrics/pairwise_fast.pyx":50 + * if nom != 0: + * res += denom * denom / nom + * result[i, j] = -res # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_v_i; + __pyx_t_6 = __pyx_v_j; + *((float *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_result.data + __pyx_t_5 * __pyx_v_result.strides[0]) ) + __pyx_t_6 * __pyx_v_result.strides[1]) )) = (-__pyx_v_res); + } + } + } + + /* "sklearn/metrics/pairwise_fast.pyx":41 + * cdef double res, nom, denom + * + * with nogil: # <<<<<<<<<<<<<< + * for i in range(n_samples_X): + * for j in range(n_samples_Y): + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "sklearn/metrics/pairwise_fast.pyx":32 + * + * + * def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<< + * floating_array_2d_t Y, + * floating_array_2d_t result): + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __PYX_XDEC_MEMVIEW(&__pyx_v_X, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Y, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_result, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_7_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_fuse_1__pyx_mdef_7sklearn_7metrics_13pairwise_fast_7_chi2_kernel_fast = {__Pyx_NAMESTR("__pyx_fuse_1_chi2_kernel_fast"), (PyCFunction)__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_7_chi2_kernel_fast, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_7_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_result = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_chi2_kernel_fast (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_Y,&__pyx_n_s_result,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_result)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_chi2_kernel_fast") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[1]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_result = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_result.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast._chi2_kernel_fast", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast_6_chi2_kernel_fast(__pyx_self, __pyx_v_X, __pyx_v_Y, __pyx_v_result); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_6_chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_X, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_Y, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_result) { + npy_intp __pyx_v_i; + npy_intp __pyx_v_j; + npy_intp __pyx_v_k; + npy_intp __pyx_v_n_samples_X; + npy_intp __pyx_v_n_samples_Y; + npy_intp __pyx_v_n_features; + double __pyx_v_res; + double __pyx_v_nom; + double __pyx_v_denom; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + npy_intp __pyx_t_1; + npy_intp __pyx_t_2; + npy_intp __pyx_t_3; + npy_intp __pyx_t_4; + npy_intp __pyx_t_5; + npy_intp __pyx_t_6; + npy_intp __pyx_t_7; + npy_intp __pyx_t_8; + npy_intp __pyx_t_9; + npy_intp __pyx_t_10; + npy_intp __pyx_t_11; + npy_intp __pyx_t_12; + npy_intp __pyx_t_13; + npy_intp __pyx_t_14; + int __pyx_t_15; + __Pyx_RefNannySetupContext("__pyx_fuse_1_chi2_kernel_fast", 0); + + /* "sklearn/metrics/pairwise_fast.pyx":36 + * floating_array_2d_t result): + * cdef np.npy_intp i, j, k + * cdef np.npy_intp n_samples_X = X.shape[0] # <<<<<<<<<<<<<< + * cdef np.npy_intp n_samples_Y = Y.shape[0] + * cdef np.npy_intp n_features = X.shape[1] + */ + __pyx_v_n_samples_X = (__pyx_v_X.shape[0]); + + /* "sklearn/metrics/pairwise_fast.pyx":37 + * cdef np.npy_intp i, j, k + * cdef np.npy_intp n_samples_X = X.shape[0] + * cdef np.npy_intp n_samples_Y = Y.shape[0] # <<<<<<<<<<<<<< + * cdef np.npy_intp n_features = X.shape[1] + * cdef double res, nom, denom + */ + __pyx_v_n_samples_Y = (__pyx_v_Y.shape[0]); + + /* "sklearn/metrics/pairwise_fast.pyx":38 + * cdef np.npy_intp n_samples_X = X.shape[0] + * cdef np.npy_intp n_samples_Y = Y.shape[0] + * cdef np.npy_intp n_features = X.shape[1] # <<<<<<<<<<<<<< + * cdef double res, nom, denom + * + */ + __pyx_v_n_features = (__pyx_v_X.shape[1]); + + /* "sklearn/metrics/pairwise_fast.pyx":41 + * cdef double res, nom, denom + * + * with nogil: # <<<<<<<<<<<<<< + * for i in range(n_samples_X): + * for j in range(n_samples_Y): + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/metrics/pairwise_fast.pyx":42 + * + * with nogil: + * for i in range(n_samples_X): # <<<<<<<<<<<<<< + * for j in range(n_samples_Y): + * res = 0 + */ + __pyx_t_1 = __pyx_v_n_samples_X; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "sklearn/metrics/pairwise_fast.pyx":43 + * with nogil: + * for i in range(n_samples_X): + * for j in range(n_samples_Y): # <<<<<<<<<<<<<< + * res = 0 + * for k in range(n_features): + */ + __pyx_t_3 = __pyx_v_n_samples_Y; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_j = __pyx_t_4; + + /* "sklearn/metrics/pairwise_fast.pyx":44 + * for i in range(n_samples_X): + * for j in range(n_samples_Y): + * res = 0 # <<<<<<<<<<<<<< + * for k in range(n_features): + * denom = (X[i, k] - Y[j, k]) + */ + __pyx_v_res = 0.0; + + /* "sklearn/metrics/pairwise_fast.pyx":45 + * for j in range(n_samples_Y): + * res = 0 + * for k in range(n_features): # <<<<<<<<<<<<<< + * denom = (X[i, k] - Y[j, k]) + * nom = (X[i, k] + Y[j, k]) + */ + __pyx_t_5 = __pyx_v_n_features; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_k = __pyx_t_6; + + /* "sklearn/metrics/pairwise_fast.pyx":46 + * res = 0 + * for k in range(n_features): + * denom = (X[i, k] - Y[j, k]) # <<<<<<<<<<<<<< + * nom = (X[i, k] + Y[j, k]) + * if nom != 0: + */ + __pyx_t_7 = __pyx_v_i; + __pyx_t_8 = __pyx_v_k; + __pyx_t_9 = __pyx_v_j; + __pyx_t_10 = __pyx_v_k; + __pyx_v_denom = ((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_X.data + __pyx_t_7 * __pyx_v_X.strides[0]) ) + __pyx_t_8 * __pyx_v_X.strides[1]) ))) - (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_9 * __pyx_v_Y.strides[0]) ) + __pyx_t_10 * __pyx_v_Y.strides[1]) )))); + + /* "sklearn/metrics/pairwise_fast.pyx":47 + * for k in range(n_features): + * denom = (X[i, k] - Y[j, k]) + * nom = (X[i, k] + Y[j, k]) # <<<<<<<<<<<<<< + * if nom != 0: + * res += denom * denom / nom + */ + __pyx_t_11 = __pyx_v_i; + __pyx_t_12 = __pyx_v_k; + __pyx_t_13 = __pyx_v_j; + __pyx_t_14 = __pyx_v_k; + __pyx_v_nom = ((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_X.data + __pyx_t_11 * __pyx_v_X.strides[0]) ) + __pyx_t_12 * __pyx_v_X.strides[1]) ))) + (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_13 * __pyx_v_Y.strides[0]) ) + __pyx_t_14 * __pyx_v_Y.strides[1]) )))); + + /* "sklearn/metrics/pairwise_fast.pyx":48 + * denom = (X[i, k] - Y[j, k]) + * nom = (X[i, k] + Y[j, k]) + * if nom != 0: # <<<<<<<<<<<<<< + * res += denom * denom / nom + * result[i, j] = -res + */ + __pyx_t_15 = ((__pyx_v_nom != 0.0) != 0); + if (__pyx_t_15) { + + /* "sklearn/metrics/pairwise_fast.pyx":49 + * nom = (X[i, k] + Y[j, k]) + * if nom != 0: + * res += denom * denom / nom # <<<<<<<<<<<<<< + * result[i, j] = -res + * + */ + __pyx_v_res = (__pyx_v_res + ((__pyx_v_denom * __pyx_v_denom) / __pyx_v_nom)); + goto __pyx_L12; + } + __pyx_L12:; + } + + /* "sklearn/metrics/pairwise_fast.pyx":50 + * if nom != 0: + * res += denom * denom / nom + * result[i, j] = -res # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_v_i; + __pyx_t_6 = __pyx_v_j; + *((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_result.data + __pyx_t_5 * __pyx_v_result.strides[0]) ) + __pyx_t_6 * __pyx_v_result.strides[1]) )) = (-__pyx_v_res); + } + } + } + + /* "sklearn/metrics/pairwise_fast.pyx":41 + * cdef double res, nom, denom + * + * with nogil: # <<<<<<<<<<<<<< + * for i in range(n_samples_X): + * for j in range(n_samples_Y): + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "sklearn/metrics/pairwise_fast.pyx":32 + * + * + * def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<< + * floating_array_2d_t Y, + * floating_array_2d_t result): + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __PYX_XDEC_MEMVIEW(&__pyx_v_X, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Y, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_result, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/metrics/pairwise_fast.pyx":53 + * + * + * def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<< + * floating1d Y_data, int[:] Y_indices, int[:] Y_indptr, + * np.npy_intp n_features, double[:, ::1] D): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_7metrics_13pairwise_fast_3_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan[] = "Pairwise L1 distances for CSR matrices.\n\n Usage:\n\n >>> D = np.zeros(X.shape[0], Y.shape[0])\n >>> sparse_manhattan(X.data, X.indices, X.indptr,\n ... Y.data, Y.indices, Y.indptr,\n ... X.shape[1], D)\n "; +static PyMethodDef __pyx_mdef_7sklearn_7metrics_13pairwise_fast_3_sparse_manhattan = {__Pyx_NAMESTR("_sparse_manhattan"), (PyCFunction)__pyx_pw_7sklearn_7metrics_13pairwise_fast_3_sparse_manhattan, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan)}; +static PyObject *__pyx_pw_7sklearn_7metrics_13pairwise_fast_3_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_signatures = 0; + PyObject *__pyx_v_args = 0; + PyObject *__pyx_v_kwargs = 0; + CYTHON_UNUSED PyObject *__pyx_v_defaults = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_fused_cpdef (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_signatures,&__pyx_n_s_args,&__pyx_n_s_kwargs,&__pyx_n_s_defaults,0}; + PyObject* values[4] = {0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_signatures)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_args)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kwargs)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_defaults)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_fused_cpdef") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + } + __pyx_v_signatures = values[0]; + __pyx_v_args = values[1]; + __pyx_v_kwargs = values[2]; + __pyx_v_defaults = values[3]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan(__pyx_self, __pyx_v_signatures, __pyx_v_args, __pyx_v_kwargs, __pyx_v_defaults); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults) { + PyObject *__pyx_v_dest_sig = NULL; + PyObject *__pyx_v_numpy = NULL; + __Pyx_memviewslice __pyx_v_memslice; + Py_ssize_t __pyx_v_itemsize; + CYTHON_UNUSED int __pyx_v_dtype_signed; + char __pyx_v_kind; + PyObject *__pyx_v_arg = NULL; + PyObject *__pyx_v_dtype = NULL; + PyObject *__pyx_v_candidates = NULL; + PyObject *__pyx_v_sig = NULL; + int __pyx_v_match_found; + PyObject *__pyx_v_src_type = NULL; + PyObject *__pyx_v_dst_type = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + char __pyx_t_12; + PyObject *(*__pyx_t_13)(PyObject *); + Py_ssize_t __pyx_t_14; + PyObject *(*__pyx_t_15)(PyObject *); + PyObject *__pyx_t_16 = NULL; + PyObject *__pyx_t_17 = NULL; + PyObject *__pyx_t_18 = NULL; + PyObject *(*__pyx_t_19)(PyObject *); + int __pyx_t_20; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_sparse_manhattan", 0); + __Pyx_INCREF(__pyx_v_kwargs); + __pyx_t_1 = PyList_New(8); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 0, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 1, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 2, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 3, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 4, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 5, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 6, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 7, Py_None); + __Pyx_GIVEREF(Py_None); + __pyx_v_dest_sig = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_2 = (__pyx_v_kwargs == Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF_SET(__pyx_v_kwargs, __pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L3; + } + __pyx_L3:; + { + __Pyx_ExceptionSave(&__pyx_t_4, &__pyx_t_5, &__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_6); + /*try:*/ { + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_numpy = __pyx_t_1; + __pyx_t_1 = 0; + } + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L11_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_7 = PyErr_ExceptionMatches(__pyx_builtin_ImportError); + if (__pyx_t_7) { + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_8, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_9); + __Pyx_INCREF(Py_None); + __Pyx_XDECREF_SET(__pyx_v_numpy, Py_None); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L5_exception_handled; + } + goto __pyx_L6_except_error; + __pyx_L6_except_error:; + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_XGIVEREF(__pyx_t_6); + __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); + goto __pyx_L1_error; + __pyx_L5_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_XGIVEREF(__pyx_t_6); + __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); + __pyx_L11_try_end:; + } + __pyx_v_itemsize = -1; + __pyx_t_10 = PyObject_Length(__pyx_v_args); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((0 < __pyx_t_10) != 0); + if (__pyx_t_3) { + __pyx_t_9 = __Pyx_GetItemInt(__pyx_v_args, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_9); + __pyx_v_arg = __pyx_t_9; + __pyx_t_9 = 0; + goto __pyx_L14; + } + __pyx_t_3 = (__Pyx_PySequence_Contains(__pyx_n_s_X_data, __pyx_v_kwargs, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__pyx_t_3 != 0); + if (__pyx_t_2) { + __pyx_t_9 = PyObject_GetItem(__pyx_v_kwargs, __pyx_n_s_X_data); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_9); + __pyx_v_arg = __pyx_t_9; + __pyx_t_9 = 0; + goto __pyx_L14; + } + /*else*/ { + __pyx_t_10 = PyObject_Length(__pyx_v_args); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = PyInt_FromSsize_t(__pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_8 = __Pyx_PyString_Format(__pyx_kp_s_Expected_at_least_d_arguments, __pyx_t_9); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L14:; + if (0) { + goto __pyx_L15; + } + /*else*/ { + while (1) { + if (!1) break; + __pyx_t_2 = (__pyx_v_numpy != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_numpy, __pyx_n_s_ndarray); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_3 = PyObject_IsInstance(__pyx_v_arg, __pyx_t_8); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_2 = (__pyx_t_3 != 0); + if (__pyx_t_2) { + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_v_dtype = __pyx_t_8; + __pyx_t_8 = 0; + goto __pyx_L19; + } + __pyx_t_2 = (__pyx_memoryview_check(__pyx_v_arg) != 0); + if (__pyx_t_2) { + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_numpy, __pyx_n_s_ndarray); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_3 = PyObject_IsInstance(__pyx_t_8, __pyx_t_9); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_11 = (__pyx_t_3 != 0); + } else { + __pyx_t_11 = __pyx_t_2; + } + if (__pyx_t_11) { + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_dtype = __pyx_t_8; + __pyx_t_8 = 0; + goto __pyx_L19; + } + /*else*/ { + __Pyx_INCREF(Py_None); + __pyx_v_dtype = Py_None; + } + __pyx_L19:; + __pyx_v_itemsize = -1; + __pyx_t_11 = (__pyx_v_dtype != Py_None); + __pyx_t_2 = (__pyx_t_11 != 0); + if (__pyx_t_2) { + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_itemsize = __pyx_t_10; + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ord, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_12 = __Pyx_PyInt_As_char(__pyx_t_8); if (unlikely((__pyx_t_12 == (char)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_kind = __pyx_t_12; + __pyx_t_8 = __Pyx_PyInt_From_char(__pyx_v_kind); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyObject_RichCompare(__pyx_t_8, __pyx_int_105, Py_EQ); __Pyx_XGOTREF(__pyx_t_9); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_dtype_signed = __pyx_t_2; + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_2 = (__Pyx_PySequence_Contains(__pyx_t_9, __pyx_tuple__8, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_11 = (__pyx_t_2 != 0); + if (__pyx_t_11) { + goto __pyx_L21; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_11 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_f, Py_EQ)); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (__pyx_t_11) { + __pyx_t_11 = ((sizeof(float)) == __pyx_v_itemsize); + if (__pyx_t_11) { + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_8 = PyObject_RichCompare(__pyx_t_9, __pyx_int_1, Py_EQ); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_11; + } + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_float_1, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L17_break; + } + __pyx_t_3 = ((sizeof(double)) == __pyx_v_itemsize); + if (__pyx_t_3) { + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyObject_RichCompare(__pyx_t_8, __pyx_int_1, Py_EQ); __Pyx_XGOTREF(__pyx_t_9); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = __pyx_t_11; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_double_1, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L17_break; + } + goto __pyx_L21; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_2 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (__pyx_t_2) { + goto __pyx_L21; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_2 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_O, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (__pyx_t_2) { + goto __pyx_L21; + } + __pyx_L21:; + goto __pyx_L20; + } + __pyx_L20:; + goto __pyx_L18; + } + __pyx_L18:; + __pyx_t_2 = ((__pyx_v_itemsize == -1) != 0); + if (!__pyx_t_2) { + __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(float))) != 0); + __pyx_t_11 = __pyx_t_3; + } else { + __pyx_t_11 = __pyx_t_2; + } + if (__pyx_t_11) { + __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_dc_float(__pyx_v_arg); + __pyx_t_11 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_11) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_float_1, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L17_break; + } + /*else*/ { + PyErr_Clear(); + } + goto __pyx_L24; + } + __pyx_L24:; + __pyx_t_11 = ((__pyx_v_itemsize == -1) != 0); + if (!__pyx_t_11) { + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(double))) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_11; + } + if (__pyx_t_3) { + __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_dc_double(__pyx_v_arg); + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_double_1, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L17_break; + } + /*else*/ { + PyErr_Clear(); + } + goto __pyx_L26; + } + __pyx_L26:; + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, Py_None, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L17_break; + } + __pyx_L17_break:; + } + __pyx_L15:; + __pyx_t_9 = PyList_New(0); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_v_candidates = ((PyObject*)__pyx_t_9); + __pyx_t_9 = 0; + if (PyList_CheckExact(__pyx_v_signatures) || PyTuple_CheckExact(__pyx_v_signatures)) { + __pyx_t_9 = __pyx_v_signatures; __Pyx_INCREF(__pyx_t_9); __pyx_t_10 = 0; + __pyx_t_13 = NULL; + } else { + __pyx_t_10 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_v_signatures); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_13 = Py_TYPE(__pyx_t_9)->tp_iternext; + } + for (;;) { + if (!__pyx_t_13 && PyList_CheckExact(__pyx_t_9)) { + if (__pyx_t_10 >= PyList_GET_SIZE(__pyx_t_9)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_8 = PyList_GET_ITEM(__pyx_t_9, __pyx_t_10); __Pyx_INCREF(__pyx_t_8); __pyx_t_10++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_8 = PySequence_ITEM(__pyx_t_9, __pyx_t_10); __pyx_t_10++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_13 && PyTuple_CheckExact(__pyx_t_9)) { + if (__pyx_t_10 >= PyTuple_GET_SIZE(__pyx_t_9)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_8 = PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_10); __Pyx_INCREF(__pyx_t_8); __pyx_t_10++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_8 = PySequence_ITEM(__pyx_t_9, __pyx_t_10); __pyx_t_10++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_8 = __pyx_t_13(__pyx_t_9); + if (unlikely(!__pyx_t_8)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_8); + } + __Pyx_XDECREF_SET(__pyx_v_sig, __pyx_t_8); + __pyx_t_8 = 0; + __pyx_v_match_found = 0; + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_sig, __pyx_n_s_strip); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_split); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyTuple_New(2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_dest_sig); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_v_dest_sig); + __Pyx_GIVEREF(__pyx_v_dest_sig); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_8, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (PyList_CheckExact(__pyx_t_1) || PyTuple_CheckExact(__pyx_t_1)) { + __pyx_t_8 = __pyx_t_1; __Pyx_INCREF(__pyx_t_8); __pyx_t_14 = 0; + __pyx_t_15 = NULL; + } else { + __pyx_t_14 = -1; __pyx_t_8 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_15 = Py_TYPE(__pyx_t_8)->tp_iternext; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (;;) { + if (!__pyx_t_15 && PyList_CheckExact(__pyx_t_8)) { + if (__pyx_t_14 >= PyList_GET_SIZE(__pyx_t_8)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_1 = PyList_GET_ITEM(__pyx_t_8, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_8, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_15 && PyTuple_CheckExact(__pyx_t_8)) { + if (__pyx_t_14 >= PyTuple_GET_SIZE(__pyx_t_8)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_8, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_8, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_1 = __pyx_t_15(__pyx_t_8); + if (unlikely(!__pyx_t_1)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_1); + } + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_16 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_17 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_16 = PyList_GET_ITEM(sequence, 0); + __pyx_t_17 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_16); + __Pyx_INCREF(__pyx_t_17); + #else + __pyx_t_16 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_16); + __pyx_t_17 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_17); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_18 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_18); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_19 = Py_TYPE(__pyx_t_18)->tp_iternext; + index = 0; __pyx_t_16 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_16)) goto __pyx_L32_unpacking_failed; + __Pyx_GOTREF(__pyx_t_16); + index = 1; __pyx_t_17 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_17)) goto __pyx_L32_unpacking_failed; + __Pyx_GOTREF(__pyx_t_17); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_19(__pyx_t_18), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_19 = NULL; + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + goto __pyx_L33_unpacking_done; + __pyx_L32_unpacking_failed:; + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + __pyx_t_19 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L33_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_src_type, __pyx_t_16); + __pyx_t_16 = 0; + __Pyx_XDECREF_SET(__pyx_v_dst_type, __pyx_t_17); + __pyx_t_17 = 0; + __pyx_t_3 = (__pyx_v_dst_type != Py_None); + __pyx_t_11 = (__pyx_t_3 != 0); + if (__pyx_t_11) { + __pyx_t_1 = PyObject_RichCompare(__pyx_v_src_type, __pyx_v_dst_type, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_11) { + __pyx_v_match_found = 1; + goto __pyx_L35; + } + /*else*/ { + __pyx_v_match_found = 0; + goto __pyx_L31_break; + } + __pyx_L35:; + goto __pyx_L34; + } + __pyx_L34:; + } + __pyx_L31_break:; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_11 = (__pyx_v_match_found != 0); + if (__pyx_t_11) { + __pyx_t_20 = __Pyx_PyList_Append(__pyx_v_candidates, __pyx_v_sig); if (unlikely(__pyx_t_20 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L36; + } + __pyx_L36:; + } + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_11 = (__pyx_v_candidates != Py_None) && (PyList_GET_SIZE(__pyx_v_candidates) != 0); + __pyx_t_3 = ((!__pyx_t_11) != 0); + if (__pyx_t_3) { + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_10 = PyList_GET_SIZE(__pyx_v_candidates); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((__pyx_t_10 > 1) != 0); + if (__pyx_t_3) { + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __pyx_t_9 = PyObject_GetItem(__pyx_v_signatures, PyList_GET_ITEM(__pyx_v_candidates, 0)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_9); + __pyx_r = __pyx_t_9; + __pyx_t_9 = 0; + goto __pyx_L0; + } + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_16); + __Pyx_XDECREF(__pyx_t_17); + __Pyx_XDECREF(__pyx_t_18); + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_dest_sig); + __Pyx_XDECREF(__pyx_v_numpy); + __Pyx_XDECREF(__pyx_v_arg); + __Pyx_XDECREF(__pyx_v_dtype); + __Pyx_XDECREF(__pyx_v_candidates); + __Pyx_XDECREF(__pyx_v_sig); + __Pyx_XDECREF(__pyx_v_src_type); + __Pyx_XDECREF(__pyx_v_dst_type); + __Pyx_XDECREF(__pyx_v_kwargs); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_11_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_fuse_0__pyx_mdef_7sklearn_7metrics_13pairwise_fast_11_sparse_manhattan = {__Pyx_NAMESTR("__pyx_fuse_0_sparse_manhattan"), (PyCFunction)__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_11_sparse_manhattan, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan)}; +static PyObject *__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_11_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __Pyx_memviewslice __pyx_v_X_data = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_X_indices = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_X_indptr = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_Y_data = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_Y_indices = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_Y_indptr = { 0, 0, { 0 }, { 0 }, { 0 } }; + npy_intp __pyx_v_n_features; + __Pyx_memviewslice __pyx_v_D = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_sparse_manhattan (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X_data,&__pyx_n_s_X_indices,&__pyx_n_s_X_indptr,&__pyx_n_s_Y_data,&__pyx_n_s_Y_indices,&__pyx_n_s_Y_indptr,&__pyx_n_s_n_features,&__pyx_n_s_D,0}; + PyObject* values[8] = {0,0,0,0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_data)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indices)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indptr)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_data)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_indices)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 5: + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_indptr)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 6: + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_features)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 7: + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_D)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_sparse_manhattan") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 8) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + } + __pyx_v_X_data = __Pyx_PyObject_to_MemoryviewSlice_dc_float(values[0]); if (unlikely(!__pyx_v_X_data.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X_indices = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[1]); if (unlikely(!__pyx_v_X_indices.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X_indptr = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[2]); if (unlikely(!__pyx_v_X_indptr.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_Y_data = __Pyx_PyObject_to_MemoryviewSlice_dc_float(values[3]); if (unlikely(!__pyx_v_Y_data.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_Y_indices = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[4]); if (unlikely(!__pyx_v_Y_indices.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_Y_indptr = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[5]); if (unlikely(!__pyx_v_Y_indptr.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_features = __Pyx_PyInt_As_Py_intptr_t(values[6]); if (unlikely((__pyx_v_n_features == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_D = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(values[7]); if (unlikely(!__pyx_v_D.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast._sparse_manhattan", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast_10_sparse_manhattan(__pyx_self, __pyx_v_X_data, __pyx_v_X_indices, __pyx_v_X_indptr, __pyx_v_Y_data, __pyx_v_Y_indices, __pyx_v_Y_indptr, __pyx_v_n_features, __pyx_v_D); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_10_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X_data, __Pyx_memviewslice __pyx_v_X_indices, __Pyx_memviewslice __pyx_v_X_indptr, __Pyx_memviewslice __pyx_v_Y_data, __Pyx_memviewslice __pyx_v_Y_indices, __Pyx_memviewslice __pyx_v_Y_indptr, npy_intp __pyx_v_n_features, __Pyx_memviewslice __pyx_v_D) { + __Pyx_memviewslice __pyx_v_row = { 0, 0, { 0 }, { 0 }, { 0 } }; + npy_intp __pyx_v_ix; + npy_intp __pyx_v_iy; + npy_intp __pyx_v_j; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_5; + npy_intp __pyx_t_6; + Py_ssize_t __pyx_t_7; + npy_intp __pyx_t_8; + Py_ssize_t __pyx_t_9; + long __pyx_t_10; + int __pyx_t_11; + npy_intp __pyx_t_12; + npy_intp __pyx_t_13; + npy_intp __pyx_t_14; + npy_intp __pyx_t_15; + int __pyx_t_16; + long __pyx_t_17; + npy_intp __pyx_t_18; + npy_intp __pyx_t_19; + npy_intp __pyx_t_20; + int __pyx_t_21; + Py_ssize_t __pyx_t_22; + npy_intp __pyx_t_23; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_fuse_0_sparse_manhattan", 0); + + /* "sklearn/metrics/pairwise_fast.pyx":65 + * ... X.shape[1], D) + * """ + * cdef double[::1] row = np.empty(n_features) # <<<<<<<<<<<<<< + * cdef np.npy_intp ix, iy, j + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyObject_to_MemoryviewSlice_dc_double(__pyx_t_1); + if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_row = __pyx_t_4; + __pyx_t_4.memview = NULL; + __pyx_t_4.data = NULL; + + /* "sklearn/metrics/pairwise_fast.pyx":68 + * cdef np.npy_intp ix, iy, j + * + * with nogil: # <<<<<<<<<<<<<< + * for ix in range(D.shape[0]): + * for iy in range(D.shape[1]): + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/metrics/pairwise_fast.pyx":69 + * + * with nogil: + * for ix in range(D.shape[0]): # <<<<<<<<<<<<<< + * for iy in range(D.shape[1]): + * # Simple strategy: densify current row of X, then subtract the + */ + __pyx_t_5 = (__pyx_v_D.shape[0]); + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_ix = __pyx_t_6; + + /* "sklearn/metrics/pairwise_fast.pyx":70 + * with nogil: + * for ix in range(D.shape[0]): + * for iy in range(D.shape[1]): # <<<<<<<<<<<<<< + * # Simple strategy: densify current row of X, then subtract the + * # corresponding row of Y. + */ + __pyx_t_7 = (__pyx_v_D.shape[1]); + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_iy = __pyx_t_8; + + /* "sklearn/metrics/pairwise_fast.pyx":73 + * # Simple strategy: densify current row of X, then subtract the + * # corresponding row of Y. + * memset(&row[0], 0, n_features * sizeof(double)) # <<<<<<<<<<<<<< + * for j in range(X_indptr[ix], X_indptr[ix + 1]): + * row[X_indices[j]] = X_data[j] + */ + __pyx_t_9 = 0; + memset((&(*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_9)) )))), 0, (__pyx_v_n_features * (sizeof(double)))); + + /* "sklearn/metrics/pairwise_fast.pyx":74 + * # corresponding row of Y. + * memset(&row[0], 0, n_features * sizeof(double)) + * for j in range(X_indptr[ix], X_indptr[ix + 1]): # <<<<<<<<<<<<<< + * row[X_indices[j]] = X_data[j] + * for j in range(Y_indptr[iy], Y_indptr[iy + 1]): + */ + __pyx_t_10 = (__pyx_v_ix + 1); + __pyx_t_11 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_10 * __pyx_v_X_indptr.strides[0]) ))); + __pyx_t_12 = __pyx_v_ix; + for (__pyx_t_13 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_12 * __pyx_v_X_indptr.strides[0]) ))); __pyx_t_13 < __pyx_t_11; __pyx_t_13+=1) { + __pyx_v_j = __pyx_t_13; + + /* "sklearn/metrics/pairwise_fast.pyx":75 + * memset(&row[0], 0, n_features * sizeof(double)) + * for j in range(X_indptr[ix], X_indptr[ix + 1]): + * row[X_indices[j]] = X_data[j] # <<<<<<<<<<<<<< + * for j in range(Y_indptr[iy], Y_indptr[iy + 1]): + * row[Y_indices[j]] -= Y_data[j] + */ + __pyx_t_14 = __pyx_v_j; + __pyx_t_15 = __pyx_v_j; + __pyx_t_16 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indices.data + __pyx_t_15 * __pyx_v_X_indices.strides[0]) ))); + *((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_16)) )) = (*((float *) ( /* dim=0 */ ((char *) (((float *) __pyx_v_X_data.data) + __pyx_t_14)) ))); + } + + /* "sklearn/metrics/pairwise_fast.pyx":76 + * for j in range(X_indptr[ix], X_indptr[ix + 1]): + * row[X_indices[j]] = X_data[j] + * for j in range(Y_indptr[iy], Y_indptr[iy + 1]): # <<<<<<<<<<<<<< + * row[Y_indices[j]] -= Y_data[j] + * + */ + __pyx_t_17 = (__pyx_v_iy + 1); + __pyx_t_11 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indptr.data + __pyx_t_17 * __pyx_v_Y_indptr.strides[0]) ))); + __pyx_t_13 = __pyx_v_iy; + for (__pyx_t_18 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indptr.data + __pyx_t_13 * __pyx_v_Y_indptr.strides[0]) ))); __pyx_t_18 < __pyx_t_11; __pyx_t_18+=1) { + __pyx_v_j = __pyx_t_18; + + /* "sklearn/metrics/pairwise_fast.pyx":77 + * row[X_indices[j]] = X_data[j] + * for j in range(Y_indptr[iy], Y_indptr[iy + 1]): + * row[Y_indices[j]] -= Y_data[j] # <<<<<<<<<<<<<< + * + * D[ix, iy] = cblas_dasum(n_features, &row[0], 1) + */ + __pyx_t_19 = __pyx_v_j; + __pyx_t_20 = __pyx_v_j; + __pyx_t_21 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indices.data + __pyx_t_20 * __pyx_v_Y_indices.strides[0]) ))); + *((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_21)) )) -= (*((float *) ( /* dim=0 */ ((char *) (((float *) __pyx_v_Y_data.data) + __pyx_t_19)) ))); + } + + /* "sklearn/metrics/pairwise_fast.pyx":79 + * row[Y_indices[j]] -= Y_data[j] + * + * D[ix, iy] = cblas_dasum(n_features, &row[0], 1) # <<<<<<<<<<<<<< + */ + __pyx_t_22 = 0; + __pyx_t_18 = __pyx_v_ix; + __pyx_t_23 = __pyx_v_iy; + *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_D.data + __pyx_t_18 * __pyx_v_D.strides[0]) )) + __pyx_t_23)) )) = cblas_dasum(__pyx_v_n_features, (&(*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_22)) )))), 1); + } + } + } + + /* "sklearn/metrics/pairwise_fast.pyx":68 + * cdef np.npy_intp ix, iy, j + * + * with nogil: # <<<<<<<<<<<<<< + * for ix in range(D.shape[0]): + * for iy in range(D.shape[1]): + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "sklearn/metrics/pairwise_fast.pyx":53 + * + * + * def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<< + * floating1d Y_data, int[:] Y_indices, int[:] Y_indptr, + * np.npy_intp n_features, double[:, ::1] D): + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __PYX_XDEC_MEMVIEW(&__pyx_t_4, 1); + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast._sparse_manhattan", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_row, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X_data, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X_indices, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X_indptr, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Y_data, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Y_indices, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Y_indptr, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_D, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_13_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_fuse_1__pyx_mdef_7sklearn_7metrics_13pairwise_fast_13_sparse_manhattan = {__Pyx_NAMESTR("__pyx_fuse_1_sparse_manhattan"), (PyCFunction)__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_13_sparse_manhattan, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan)}; +static PyObject *__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_13_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __Pyx_memviewslice __pyx_v_X_data = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_X_indices = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_X_indptr = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_Y_data = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_Y_indices = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_Y_indptr = { 0, 0, { 0 }, { 0 }, { 0 } }; + npy_intp __pyx_v_n_features; + __Pyx_memviewslice __pyx_v_D = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_sparse_manhattan (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X_data,&__pyx_n_s_X_indices,&__pyx_n_s_X_indptr,&__pyx_n_s_Y_data,&__pyx_n_s_Y_indices,&__pyx_n_s_Y_indptr,&__pyx_n_s_n_features,&__pyx_n_s_D,0}; + PyObject* values[8] = {0,0,0,0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_data)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indices)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indptr)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_data)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_indices)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 5: + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_indptr)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 6: + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_features)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 7: + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_D)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_sparse_manhattan") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 8) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + } + __pyx_v_X_data = __Pyx_PyObject_to_MemoryviewSlice_dc_double(values[0]); if (unlikely(!__pyx_v_X_data.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X_indices = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[1]); if (unlikely(!__pyx_v_X_indices.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X_indptr = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[2]); if (unlikely(!__pyx_v_X_indptr.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_Y_data = __Pyx_PyObject_to_MemoryviewSlice_dc_double(values[3]); if (unlikely(!__pyx_v_Y_data.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_Y_indices = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[4]); if (unlikely(!__pyx_v_Y_indices.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_Y_indptr = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[5]); if (unlikely(!__pyx_v_Y_indptr.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_features = __Pyx_PyInt_As_Py_intptr_t(values[6]); if (unlikely((__pyx_v_n_features == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_D = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(values[7]); if (unlikely(!__pyx_v_D.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast._sparse_manhattan", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast_12_sparse_manhattan(__pyx_self, __pyx_v_X_data, __pyx_v_X_indices, __pyx_v_X_indptr, __pyx_v_Y_data, __pyx_v_Y_indices, __pyx_v_Y_indptr, __pyx_v_n_features, __pyx_v_D); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_12_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X_data, __Pyx_memviewslice __pyx_v_X_indices, __Pyx_memviewslice __pyx_v_X_indptr, __Pyx_memviewslice __pyx_v_Y_data, __Pyx_memviewslice __pyx_v_Y_indices, __Pyx_memviewslice __pyx_v_Y_indptr, npy_intp __pyx_v_n_features, __Pyx_memviewslice __pyx_v_D) { + __Pyx_memviewslice __pyx_v_row = { 0, 0, { 0 }, { 0 }, { 0 } }; + npy_intp __pyx_v_ix; + npy_intp __pyx_v_iy; + npy_intp __pyx_v_j; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_5; + npy_intp __pyx_t_6; + Py_ssize_t __pyx_t_7; + npy_intp __pyx_t_8; + Py_ssize_t __pyx_t_9; + long __pyx_t_10; + int __pyx_t_11; + npy_intp __pyx_t_12; + npy_intp __pyx_t_13; + npy_intp __pyx_t_14; + npy_intp __pyx_t_15; + int __pyx_t_16; + long __pyx_t_17; + npy_intp __pyx_t_18; + npy_intp __pyx_t_19; + npy_intp __pyx_t_20; + int __pyx_t_21; + Py_ssize_t __pyx_t_22; + npy_intp __pyx_t_23; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_fuse_1_sparse_manhattan", 0); + + /* "sklearn/metrics/pairwise_fast.pyx":65 + * ... X.shape[1], D) + * """ + * cdef double[::1] row = np.empty(n_features) # <<<<<<<<<<<<<< + * cdef np.npy_intp ix, iy, j + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyObject_to_MemoryviewSlice_dc_double(__pyx_t_1); + if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_row = __pyx_t_4; + __pyx_t_4.memview = NULL; + __pyx_t_4.data = NULL; + + /* "sklearn/metrics/pairwise_fast.pyx":68 + * cdef np.npy_intp ix, iy, j + * + * with nogil: # <<<<<<<<<<<<<< + * for ix in range(D.shape[0]): + * for iy in range(D.shape[1]): + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/metrics/pairwise_fast.pyx":69 + * + * with nogil: + * for ix in range(D.shape[0]): # <<<<<<<<<<<<<< + * for iy in range(D.shape[1]): + * # Simple strategy: densify current row of X, then subtract the + */ + __pyx_t_5 = (__pyx_v_D.shape[0]); + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_ix = __pyx_t_6; + + /* "sklearn/metrics/pairwise_fast.pyx":70 + * with nogil: + * for ix in range(D.shape[0]): + * for iy in range(D.shape[1]): # <<<<<<<<<<<<<< + * # Simple strategy: densify current row of X, then subtract the + * # corresponding row of Y. + */ + __pyx_t_7 = (__pyx_v_D.shape[1]); + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_iy = __pyx_t_8; + + /* "sklearn/metrics/pairwise_fast.pyx":73 + * # Simple strategy: densify current row of X, then subtract the + * # corresponding row of Y. + * memset(&row[0], 0, n_features * sizeof(double)) # <<<<<<<<<<<<<< + * for j in range(X_indptr[ix], X_indptr[ix + 1]): + * row[X_indices[j]] = X_data[j] + */ + __pyx_t_9 = 0; + memset((&(*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_9)) )))), 0, (__pyx_v_n_features * (sizeof(double)))); + + /* "sklearn/metrics/pairwise_fast.pyx":74 + * # corresponding row of Y. + * memset(&row[0], 0, n_features * sizeof(double)) + * for j in range(X_indptr[ix], X_indptr[ix + 1]): # <<<<<<<<<<<<<< + * row[X_indices[j]] = X_data[j] + * for j in range(Y_indptr[iy], Y_indptr[iy + 1]): + */ + __pyx_t_10 = (__pyx_v_ix + 1); + __pyx_t_11 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_10 * __pyx_v_X_indptr.strides[0]) ))); + __pyx_t_12 = __pyx_v_ix; + for (__pyx_t_13 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_12 * __pyx_v_X_indptr.strides[0]) ))); __pyx_t_13 < __pyx_t_11; __pyx_t_13+=1) { + __pyx_v_j = __pyx_t_13; + + /* "sklearn/metrics/pairwise_fast.pyx":75 + * memset(&row[0], 0, n_features * sizeof(double)) + * for j in range(X_indptr[ix], X_indptr[ix + 1]): + * row[X_indices[j]] = X_data[j] # <<<<<<<<<<<<<< + * for j in range(Y_indptr[iy], Y_indptr[iy + 1]): + * row[Y_indices[j]] -= Y_data[j] + */ + __pyx_t_14 = __pyx_v_j; + __pyx_t_15 = __pyx_v_j; + __pyx_t_16 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indices.data + __pyx_t_15 * __pyx_v_X_indices.strides[0]) ))); + *((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_16)) )) = (*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_X_data.data) + __pyx_t_14)) ))); + } + + /* "sklearn/metrics/pairwise_fast.pyx":76 + * for j in range(X_indptr[ix], X_indptr[ix + 1]): + * row[X_indices[j]] = X_data[j] + * for j in range(Y_indptr[iy], Y_indptr[iy + 1]): # <<<<<<<<<<<<<< + * row[Y_indices[j]] -= Y_data[j] + * + */ + __pyx_t_17 = (__pyx_v_iy + 1); + __pyx_t_11 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indptr.data + __pyx_t_17 * __pyx_v_Y_indptr.strides[0]) ))); + __pyx_t_13 = __pyx_v_iy; + for (__pyx_t_18 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indptr.data + __pyx_t_13 * __pyx_v_Y_indptr.strides[0]) ))); __pyx_t_18 < __pyx_t_11; __pyx_t_18+=1) { + __pyx_v_j = __pyx_t_18; + + /* "sklearn/metrics/pairwise_fast.pyx":77 + * row[X_indices[j]] = X_data[j] + * for j in range(Y_indptr[iy], Y_indptr[iy + 1]): + * row[Y_indices[j]] -= Y_data[j] # <<<<<<<<<<<<<< + * + * D[ix, iy] = cblas_dasum(n_features, &row[0], 1) + */ + __pyx_t_19 = __pyx_v_j; + __pyx_t_20 = __pyx_v_j; + __pyx_t_21 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indices.data + __pyx_t_20 * __pyx_v_Y_indices.strides[0]) ))); + *((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_21)) )) -= (*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_Y_data.data) + __pyx_t_19)) ))); + } + + /* "sklearn/metrics/pairwise_fast.pyx":79 + * row[Y_indices[j]] -= Y_data[j] + * + * D[ix, iy] = cblas_dasum(n_features, &row[0], 1) # <<<<<<<<<<<<<< + */ + __pyx_t_22 = 0; + __pyx_t_18 = __pyx_v_ix; + __pyx_t_23 = __pyx_v_iy; + *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_D.data + __pyx_t_18 * __pyx_v_D.strides[0]) )) + __pyx_t_23)) )) = cblas_dasum(__pyx_v_n_features, (&(*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_22)) )))), 1); + } + } + } + + /* "sklearn/metrics/pairwise_fast.pyx":68 + * cdef np.npy_intp ix, iy, j + * + * with nogil: # <<<<<<<<<<<<<< + * for ix in range(D.shape[0]): + * for iy in range(D.shape[1]): + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "sklearn/metrics/pairwise_fast.pyx":53 + * + * + * def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<< + * floating1d Y_data, int[:] Y_indices, int[:] Y_indptr, + * np.npy_intp n_features, double[:, ::1] D): + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __PYX_XDEC_MEMVIEW(&__pyx_t_4, 1); + __Pyx_AddTraceback("sklearn.metrics.pairwise_fast._sparse_manhattan", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_row, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X_data, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X_indices, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_X_indptr, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Y_data, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Y_indices, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Y_indptr, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_D, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_1) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_3) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__14, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":222 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":251 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); + if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_1) { + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< + * info.format + _buffer_format_string_len, + * &offset) + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + long __pyx_t_10; + char *__pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); + __pyx_t_3 = 0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":798 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); + if (__pyx_t_6) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_6 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_6) { + __pyx_t_7 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_7 = __pyx_t_6; + } + if (!__pyx_t_7) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_6 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_6) { + __pyx_t_8 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_9 = __pyx_t_8; + } else { + __pyx_t_9 = __pyx_t_6; + } + __pyx_t_6 = __pyx_t_9; + } else { + __pyx_t_6 = __pyx_t_7; + } + if (__pyx_t_6) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":813 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_6) break; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":818 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_6) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":821 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_6) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L11; + } + /*else*/ { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L11:; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L9; + } + /*else*/ { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_11; + } + __pyx_L9:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":968 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":969 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":971 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":972 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":973 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":974 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":977 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":978 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + /*else*/ { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":980 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":113 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode=u"c", bint allocate_buffer=True): + * + */ + +/* Python wrapper */ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_shape = 0; + Py_ssize_t __pyx_v_itemsize; + PyObject *__pyx_v_format = 0; + PyObject *__pyx_v_mode = 0; + int __pyx_v_allocate_buffer; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[3] = ((PyObject *)__pyx_n_u_c); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mode); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_allocate_buffer); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_shape = ((PyObject*)values[0]); + __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_format = values[2]; + __pyx_v_mode = values[3]; + if (values[4]) { + __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "View.MemoryView":114 + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, + * mode=u"c", bint allocate_buffer=True): # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_v_allocate_buffer = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { + PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_r = __pyx_array_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); + + /* "View.MemoryView":113 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode=u"c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { + int __pyx_v_idx; + Py_ssize_t __pyx_v_i; + PyObject **__pyx_v_p; + PyObject *__pyx_v_encode = NULL; + PyObject *__pyx_v_dim = NULL; + char __pyx_v_order; + PyObject *__pyx_v_decode = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_INCREF(__pyx_v_format); + __Pyx_INCREF(__pyx_v_mode); + + /* "View.MemoryView":120 + * cdef PyObject **p + * + * self.ndim = len(shape) # <<<<<<<<<<<<<< + * self.itemsize = itemsize + * + */ + if (unlikely(__pyx_v_shape == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->ndim = ((int)__pyx_t_1); + + /* "View.MemoryView":121 + * + * self.ndim = len(shape) + * self.itemsize = itemsize # <<<<<<<<<<<<<< + * + * if not self.ndim: + */ + __pyx_v_self->itemsize = __pyx_v_itemsize; + + /* "View.MemoryView":123 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ + __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":124 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if self.itemsize <= 0: + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":126 + * raise ValueError("Empty shape tuple for cython.array") + * + * if self.itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ + __pyx_t_2 = ((__pyx_v_self->itemsize <= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":127 + * + * if self.itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * encode = getattr(format, 'encode', None) + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":129 + * raise ValueError("itemsize <= 0 for cython.array") + * + * encode = getattr(format, 'encode', None) # <<<<<<<<<<<<<< + * if encode: + * format = encode('ASCII') + */ + __pyx_t_3 = __Pyx_GetAttr3(__pyx_v_format, __pyx_n_s_encode, Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_encode = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":130 + * + * encode = getattr(format, 'encode', None) + * if encode: # <<<<<<<<<<<<<< + * format = encode('ASCII') + * self._format = format + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_encode); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":131 + * encode = getattr(format, 'encode', None) + * if encode: + * format = encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format + * self.format = self._format + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_v_encode, __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":132 + * if encode: + * format = encode('ASCII') + * self._format = format # <<<<<<<<<<<<<< + * self.format = self._format + * + */ + if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_v_format; + __Pyx_INCREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->_format); + __Pyx_DECREF(__pyx_v_self->_format); + __pyx_v_self->_format = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":133 + * format = encode('ASCII') + * self._format = format + * self.format = self._format # <<<<<<<<<<<<<< + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) + */ + __pyx_t_4 = __Pyx_PyObject_AsString(__pyx_v_self->_format); if (unlikely((!__pyx_t_4) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->format = __pyx_t_4; + + /* "View.MemoryView":135 + * self.format = self._format + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<< + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) + * + */ + __pyx_v_self->_shape = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim))); + + /* "View.MemoryView":136 + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<< + * + * if not self._shape or not self._strides: + */ + __pyx_v_self->_strides = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim))); + + /* "View.MemoryView":138 + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) + * + * if not self._shape or not self._strides: # <<<<<<<<<<<<<< + * free(self._shape) + * free(self._strides) + */ + __pyx_t_2 = ((!(__pyx_v_self->_shape != 0)) != 0); + if (!__pyx_t_2) { + __pyx_t_5 = ((!(__pyx_v_self->_strides != 0)) != 0); + __pyx_t_6 = __pyx_t_5; + } else { + __pyx_t_6 = __pyx_t_2; + } + if (__pyx_t_6) { + + /* "View.MemoryView":139 + * + * if not self._shape or not self._strides: + * free(self._shape) # <<<<<<<<<<<<<< + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") + */ + free(__pyx_v_self->_shape); + + /* "View.MemoryView":140 + * if not self._shape or not self._strides: + * free(self._shape) + * free(self._strides) # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape or strides.") + * + */ + free(__pyx_v_self->_strides); + + /* "View.MemoryView":141 + * free(self._shape) + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__22, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":144 + * + * + * idx = 0 # <<<<<<<<<<<<<< + * for idx, dim in enumerate(shape): + * if dim <= 0: + */ + __pyx_v_idx = 0; + + /* "View.MemoryView":145 + * + * idx = 0 + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + __pyx_t_7 = 0; + __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; + for (;;) { + if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_8 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_8); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_8 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_dim, __pyx_t_8); + __pyx_t_8 = 0; + __pyx_v_idx = __pyx_t_7; + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":146 + * idx = 0 + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * + */ + __pyx_t_8 = PyObject_RichCompare(__pyx_v_dim, __pyx_int_0, Py_LE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (__pyx_t_6) { + + /* "View.MemoryView":147 + * for idx, dim in enumerate(shape): + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< + * + * self._shape[idx] = dim + */ + __pyx_t_8 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_dim); + PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_dim); + __Pyx_GIVEREF(__pyx_v_dim); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_9); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":149 + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * + * self._shape[idx] = dim # <<<<<<<<<<<<<< + * idx += 1 + * + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_dim); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_t_10; + + /* "View.MemoryView":150 + * + * self._shape[idx] = dim + * idx += 1 # <<<<<<<<<<<<<< + * + * if mode not in ("fortran", "c"): + */ + __pyx_v_idx = (__pyx_v_idx + 1); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":152 + * idx += 1 + * + * if mode not in ("fortran", "c"): # <<<<<<<<<<<<<< + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + * + */ + __Pyx_INCREF(__pyx_v_mode); + __pyx_t_3 = __pyx_v_mode; + __pyx_t_6 = (__Pyx_PyString_Equals(__pyx_t_3, __pyx_n_s_fortran, Py_NE)); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + __pyx_t_2 = (__Pyx_PyString_Equals(__pyx_t_3, __pyx_n_s_c, Py_NE)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __pyx_t_2; + } else { + __pyx_t_5 = __pyx_t_6; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = (__pyx_t_5 != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":153 + * + * if mode not in ("fortran", "c"): + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< + * + * cdef char order + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_8, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":156 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = 'F' + * else: + */ + __pyx_t_6 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":157 + * cdef char order + * if mode == 'fortran': + * order = 'F' # <<<<<<<<<<<<<< + * else: + * order = 'C' + */ + __pyx_v_order = 'F'; + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":159 + * order = 'F' + * else: + * order = 'C' # <<<<<<<<<<<<<< + * + * self.len = fill_contig_strides_array(self._shape, self._strides, + */ + __pyx_v_order = 'C'; + } + __pyx_L11:; + + /* "View.MemoryView":161 + * order = 'C' + * + * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< + * itemsize, self.ndim, order) + * + */ + __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); + + /* "View.MemoryView":164 + * itemsize, self.ndim, order) + * + * decode = getattr(mode, 'decode', None) # <<<<<<<<<<<<<< + * if decode: + * mode = decode('ASCII') + */ + __pyx_t_3 = __Pyx_GetAttr3(__pyx_v_mode, __pyx_n_s_decode, Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_decode = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":165 + * + * decode = getattr(mode, 'decode', None) + * if decode: # <<<<<<<<<<<<<< + * mode = decode('ASCII') + * self.mode = mode + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_decode); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":166 + * decode = getattr(mode, 'decode', None) + * if decode: + * mode = decode('ASCII') # <<<<<<<<<<<<<< + * self.mode = mode + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_v_decode, __pyx_tuple__23, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_mode, __pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":167 + * if decode: + * mode = decode('ASCII') + * self.mode = mode # <<<<<<<<<<<<<< + * + * self.free_data = allocate_buffer + */ + if (!(likely(PyUnicode_CheckExact(__pyx_v_mode))||((__pyx_v_mode) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_v_mode)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_v_mode; + __Pyx_INCREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(__pyx_v_self->mode); + __pyx_v_self->mode = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":169 + * self.mode = mode + * + * self.free_data = allocate_buffer # <<<<<<<<<<<<<< + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + */ + __pyx_v_self->free_data = __pyx_v_allocate_buffer; + + /* "View.MemoryView":170 + * + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< + * if allocate_buffer: + * self.data = malloc(self.len) + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_6; + + /* "View.MemoryView":171 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * self.data = malloc(self.len) + * if not self.data: + */ + __pyx_t_6 = (__pyx_v_allocate_buffer != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":172 + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + * self.data = malloc(self.len) # <<<<<<<<<<<<<< + * if not self.data: + * raise MemoryError("unable to allocate array data.") + */ + __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); + + /* "View.MemoryView":173 + * if allocate_buffer: + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ + __pyx_t_6 = ((!(__pyx_v_self->data != 0)) != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":174 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__24, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":176 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ + __pyx_t_6 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":177 + * + * if self.dtype_is_object: + * p = self.data # <<<<<<<<<<<<<< + * for i in range(self.len / itemsize): + * p[i] = Py_None + */ + __pyx_v_p = ((PyObject **)__pyx_v_self->data); + + /* "View.MemoryView":178 + * if self.dtype_is_object: + * p = self.data + * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< + * p[i] = Py_None + * Py_INCREF(Py_None) + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = (__pyx_v_self->len / __pyx_v_itemsize); + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_1; __pyx_t_10+=1) { + __pyx_v_i = __pyx_t_10; + + /* "View.MemoryView":179 + * p = self.data + * for i in range(self.len / itemsize): + * p[i] = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + (__pyx_v_p[__pyx_v_i]) = Py_None; + + /* "View.MemoryView":180 + * for i in range(self.len / itemsize): + * p[i] = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + Py_INCREF(Py_None); + } + goto __pyx_L15; + } + __pyx_L15:; + goto __pyx_L13; + } + __pyx_L13:; + + /* "View.MemoryView":113 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode=u"c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_encode); + __Pyx_XDECREF(__pyx_v_dim); + __Pyx_XDECREF(__pyx_v_decode); + __Pyx_XDECREF(__pyx_v_format); + __Pyx_XDECREF(__pyx_v_mode); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":183 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == b"c": + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_bufmode; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + Py_ssize_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":184 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 # <<<<<<<<<<<<<< + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = -1; + + /* "View.MemoryView":185 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == b"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": + */ + __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_b_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":186 + * cdef int bufmode = -1 + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + + /* "View.MemoryView":187 + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ + __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_b_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":188 + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + */ + __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":189 + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ + __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":190 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__25, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":191 + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data # <<<<<<<<<<<<<< + * info.len = self.len + * info.ndim = self.ndim + */ + __pyx_t_4 = __pyx_v_self->data; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":192 + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + * info.len = self.len # <<<<<<<<<<<<<< + * info.ndim = self.ndim + * info.shape = self._shape + */ + __pyx_t_5 = __pyx_v_self->len; + __pyx_v_info->len = __pyx_t_5; + + /* "View.MemoryView":193 + * info.buf = self.data + * info.len = self.len + * info.ndim = self.ndim # <<<<<<<<<<<<<< + * info.shape = self._shape + * info.strides = self._strides + */ + __pyx_t_6 = __pyx_v_self->ndim; + __pyx_v_info->ndim = __pyx_t_6; + + /* "View.MemoryView":194 + * info.len = self.len + * info.ndim = self.ndim + * info.shape = self._shape # <<<<<<<<<<<<<< + * info.strides = self._strides + * info.suboffsets = NULL + */ + __pyx_t_7 = __pyx_v_self->_shape; + __pyx_v_info->shape = __pyx_t_7; + + /* "View.MemoryView":195 + * info.ndim = self.ndim + * info.shape = self._shape + * info.strides = self._strides # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = self.itemsize + */ + __pyx_t_7 = __pyx_v_self->_strides; + __pyx_v_info->strides = __pyx_t_7; + + /* "View.MemoryView":196 + * info.shape = self._shape + * info.strides = self._strides + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = self.itemsize + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; + + /* "View.MemoryView":197 + * info.strides = self._strides + * info.suboffsets = NULL + * info.itemsize = self.itemsize # <<<<<<<<<<<<<< + * info.readonly = 0 + * + */ + __pyx_t_5 = __pyx_v_self->itemsize; + __pyx_v_info->itemsize = __pyx_t_5; + + /* "View.MemoryView":198 + * info.suboffsets = NULL + * info.itemsize = self.itemsize + * info.readonly = 0 # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":200 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":201 + * + * if flags & PyBUF_FORMAT: + * info.format = self.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_4 = __pyx_v_self->format; + __pyx_v_info->format = __pyx_t_4; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":203 + * info.format = self.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.obj = self + */ + __pyx_v_info->format = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":205 + * info.format = NULL + * + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "View.MemoryView":183 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == b"c": + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":209 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + +/* Python wrapper */ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_array_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":210 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ + __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":211 + * def __dealloc__(array self): + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) # <<<<<<<<<<<<<< + * elif self.free_data: + * if self.dtype_is_object: + */ + __pyx_v_self->callback_free_data(__pyx_v_self->data); + goto __pyx_L3; + } + + /* "View.MemoryView":212 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ + __pyx_t_1 = (__pyx_v_self->free_data != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":213 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":214 + * elif self.free_data: + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< + * self._strides, self.ndim, False) + * free(self.data) + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":216 + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + * free(self.data) # <<<<<<<<<<<<<< + * + * free(self._strides) + */ + free(__pyx_v_self->data); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":218 + * free(self.data) + * + * free(self._strides) # <<<<<<<<<<<<<< + * free(self._shape) + * + */ + free(__pyx_v_self->_strides); + + /* "View.MemoryView":219 + * + * free(self._strides) + * free(self._shape) # <<<<<<<<<<<<<< + * + * property memview: + */ + free(__pyx_v_self->_shape); + + /* "View.MemoryView":209 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":223 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + +/* Python wrapper */ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = get_memview_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":225 + * def __get__(self): + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< + * return memoryview(self, flags, self.dtype_is_object) + * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":226 + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":223 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":229 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":230 + * + * def __getattr__(self, attr): + * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * + * def __getitem__(self, item): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":229 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":232 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":233 + * + * def __getitem__(self, item): + * return self.memview[item] # <<<<<<<<<<<<<< + * + * def __setitem__(self, item, value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":232 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":235 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + +/* Python wrapper */ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "View.MemoryView":236 + * + * def __setitem__(self, item, value): + * self.memview[item] = value # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":235 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":240 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + +static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { + struct __pyx_array_obj *__pyx_v_result = 0; + struct __pyx_array_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("array_cwrapper", 0); + + /* "View.MemoryView":244 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":245 + * + * if buf == NULL: + * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":247 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":248 + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) # <<<<<<<<<<<<<< + * result.data = buf + * + */ + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":247 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":249 + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) + * result.data = buf # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->data = __pyx_v_buf; + } + __pyx_L3:; + + /* "View.MemoryView":251 + * result.data = buf + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":240 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":277 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + +/* Python wrapper */ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_name = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_name = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "View.MemoryView":278 + * cdef object name + * def __init__(self, name): + * self.name = name # <<<<<<<<<<<<<< + * def __repr__(self): + * return self.name + */ + __Pyx_INCREF(__pyx_v_name); + __Pyx_GIVEREF(__pyx_v_name); + __Pyx_GOTREF(__pyx_v_self->name); + __Pyx_DECREF(__pyx_v_self->name); + __pyx_v_self->name = __pyx_v_name; + + /* "View.MemoryView":277 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":279 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + +/* Python wrapper */ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":280 + * self.name = name + * def __repr__(self): + * return self.name # <<<<<<<<<<<<<< + * + * cdef generic = Enum("") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->name); + __pyx_r = __pyx_v_self->name; + goto __pyx_L0; + + /* "View.MemoryView":279 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":294 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + +static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { + Py_intptr_t __pyx_v_aligned_p; + size_t __pyx_v_offset; + void *__pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":296 + * cdef void *align_pointer(void *memory, size_t alignment) nogil: + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< + * cdef size_t offset + * + */ + __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + + /* "View.MemoryView":300 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":302 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + __pyx_t_1 = ((__pyx_v_offset > 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":303 + * + * if offset > 0: + * aligned_p += alignment - offset # <<<<<<<<<<<<<< + * + * return aligned_p + */ + __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":305 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview') + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + /* "View.MemoryView":294 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":323 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + +/* Python wrapper */ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_obj = 0; + int __pyx_v_flags; + int __pyx_v_dtype_is_object; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dtype_is_object); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_obj = values[0]; + __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[2]) { + __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_dtype_is_object = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_memoryview_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "View.MemoryView":324 + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj # <<<<<<<<<<<<<< + * self.flags = flags + * if type(self) is memoryview or obj is not None: + */ + __Pyx_INCREF(__pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __Pyx_GOTREF(__pyx_v_self->obj); + __Pyx_DECREF(__pyx_v_self->obj); + __pyx_v_self->obj = __pyx_v_obj; + + /* "View.MemoryView":325 + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj + * self.flags = flags # <<<<<<<<<<<<<< + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + */ + __pyx_v_self->flags = __pyx_v_flags; + + /* "View.MemoryView":326 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ + __pyx_t_1 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type))); + if (!(__pyx_t_1 != 0)) { + __pyx_t_2 = (__pyx_v_obj != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + } else { + __pyx_t_3 = (__pyx_t_1 != 0); + } + if (__pyx_t_3) { + + /* "View.MemoryView":327 + * self.flags = flags + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + */ + __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":328 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_t_3 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":329 + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; + + /* "View.MemoryView":330 + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * self.lock = PyThread_allocate_lock() + */ + Py_INCREF(Py_None); + goto __pyx_L4; + } + __pyx_L4:; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":332 + * Py_INCREF(Py_None) + * + * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< + * if self.lock == NULL: + * raise MemoryError + */ + __pyx_v_self->lock = PyThread_allocate_lock(); + + /* "View.MemoryView":333 + * + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + __pyx_t_3 = ((__pyx_v_self->lock == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":334 + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":336 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = self.view.format == b'O' + * else: + */ + __pyx_t_3 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":337 + * + * if flags & PyBUF_FORMAT: + * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< + * else: + * self.dtype_is_object = dtype_is_object + */ + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_5, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":339 + * self.dtype_is_object = self.view.format == b'O' + * else: + * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + */ + __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; + } + __pyx_L6:; + + /* "View.MemoryView":341 + * self.dtype_is_object = dtype_is_object + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL + */ + __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); + + /* "View.MemoryView":343 + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(memoryview self): + */ + __pyx_v_self->typeinfo = NULL; + + /* "View.MemoryView":323 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":345 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + +/* Python wrapper */ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":346 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< + * __Pyx_ReleaseBuffer(&self.view) + * + */ + __pyx_t_1 = (__pyx_v_self->obj != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":347 + * def __dealloc__(memoryview self): + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< + * + * if self.lock != NULL: + */ + __Pyx_ReleaseBuffer((&__pyx_v_self->view)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":349 + * __Pyx_ReleaseBuffer(&self.view) + * + * if self.lock != NULL: # <<<<<<<<<<<<<< + * PyThread_free_lock(self.lock) + * + */ + __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":350 + * + * if self.lock != NULL: + * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + */ + PyThread_free_lock(__pyx_v_self->lock); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":345 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":352 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + Py_ssize_t __pyx_v_dim; + char *__pyx_v_itemp; + PyObject *__pyx_v_idx = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_item_pointer", 0); + + /* "View.MemoryView":354 + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< + * + * for dim, idx in enumerate(index): + */ + __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); + + /* "View.MemoryView":356 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + __pyx_t_1 = 0; + if (PyList_CheckExact(__pyx_v_index) || PyTuple_CheckExact(__pyx_v_index)) { + __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; + } + for (;;) { + if (!__pyx_t_4 && PyList_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_4 && PyTuple_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); + __pyx_t_5 = 0; + __pyx_v_dim = __pyx_t_1; + __pyx_t_1 = (__pyx_t_1 + 1); + + /* "View.MemoryView":357 + * + * for dim, idx in enumerate(index): + * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< + * + * return itemp + */ + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_7; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":359 + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + * return itemp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_itemp; + goto __pyx_L0; + + /* "View.MemoryView":352 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":362 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_indices = NULL; + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + char *__pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":363 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":364 + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: + * return self # <<<<<<<<<<<<<< + * + * have_slices, indices = _unellipsify(index, self.view.ndim) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __pyx_r = ((PyObject *)__pyx_v_self); + goto __pyx_L0; + } + + /* "View.MemoryView":366 + * return self + * + * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * cdef char *itemp + */ + __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (likely(__pyx_t_3 != Py_None)) { + PyObject* sequence = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_have_slices = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; + + /* "View.MemoryView":369 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":370 + * cdef char *itemp + * if have_slices: + * return memview_slice(self, indices) # <<<<<<<<<<<<<< + * else: + * itemp = self.get_item_pointer(indices) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":372 + * return memview_slice(self, indices) + * else: + * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< + * return self.convert_item_to_object(itemp) + * + */ + __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_6; + + /* "View.MemoryView":373 + * else: + * itemp = self.get_item_pointer(indices) + * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< + * + * def __setitem__(memoryview self, object index, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":362 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":375 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + +/* Python wrapper */ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_obj = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_INCREF(__pyx_v_index); + + /* "View.MemoryView":376 + * + * def __setitem__(memoryview self, object index, object value): + * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * if have_slices: + */ + __pyx_t_1 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (likely(__pyx_t_1 != Py_None)) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_have_slices = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":378 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":379 + * + * if have_slices: + * obj = self.is_slice(value) # <<<<<<<<<<<<<< + * if obj: + * self.setitem_slice_assignment(self[index], obj) + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_obj = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":380 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":381 + * obj = self.is_slice(value) + * if obj: + * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< + * else: + * self.setitem_slice_assign_scalar(self[index], value) + */ + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":383 + * self.setitem_slice_assignment(self[index], obj) + * else: + * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< + * else: + * self.setitem_indexed(index, value) + */ + __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":385 + * self.setitem_slice_assign_scalar(self[index], value) + * else: + * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< + * + * cdef is_slice(self, obj): + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":375 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":387 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_slice", 0); + __Pyx_INCREF(__pyx_v_obj); + + /* "View.MemoryView":388 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type)); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":389 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + { + __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + /*try:*/ { + + /* "View.MemoryView":390 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_6 = __Pyx_PyInt_From_int((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":391 + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * except TypeError: + * return None + */ + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":390 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); + __pyx_t_7 = 0; + } + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L11_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":392 + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + * except TypeError: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":393 + * self.dtype_is_object) + * except TypeError: + * return None # <<<<<<<<<<<<<< + * + * return obj + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L7_except_return; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L5_exception_handled; + } + goto __pyx_L6_except_error; + __pyx_L6_except_error:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L1_error; + __pyx_L7_except_return:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L0; + __pyx_L5_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + __pyx_L11_try_end:; + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":395 + * return None + * + * return obj # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assignment(self, dst, src): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_obj); + __pyx_r = __pyx_v_obj; + goto __pyx_L0; + + /* "View.MemoryView":387 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":397 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { + __Pyx_memviewslice __pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_src_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); + + /* "View.MemoryView":401 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":402 + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< + * src.ndim, dst.ndim, self.dtype_is_object) + * + */ + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":403 + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":401 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":397 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":405 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { + int __pyx_v_array[128]; + void *__pyx_v_tmp; + void *__pyx_v_item; + __Pyx_memviewslice *__pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_tmp_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); + + /* "View.MemoryView":407 + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + * cdef int array[128] + * cdef void *tmp = NULL # <<<<<<<<<<<<<< + * cdef void *item + * + */ + __pyx_v_tmp = NULL; + + /* "View.MemoryView":412 + * cdef __Pyx_memviewslice *dst_slice + * cdef __Pyx_memviewslice tmp_slice + * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< + * + * if self.view.itemsize > sizeof(array): + */ + __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); + + /* "View.MemoryView":414 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: + */ + __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":415 + * + * if self.view.itemsize > sizeof(array): + * tmp = malloc(self.view.itemsize) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError + */ + __pyx_v_tmp = malloc(__pyx_v_self->view.itemsize); + + /* "View.MemoryView":416 + * if self.view.itemsize > sizeof(array): + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":417 + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * item = tmp + * else: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 417; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":418 + * if tmp == NULL: + * raise MemoryError + * item = tmp # <<<<<<<<<<<<<< + * else: + * item = array + */ + __pyx_v_item = __pyx_v_tmp; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":420 + * item = tmp + * else: + * item = array # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_v_item = ((void *)__pyx_v_array); + } + __pyx_L3:; + + /* "View.MemoryView":422 + * item = array + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":423 + * + * if self.dtype_is_object: + * ( item)[0] = value # <<<<<<<<<<<<<< + * else: + * try: + */ + (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":425 + * ( item)[0] = value + * else: + * try: # <<<<<<<<<<<<<< + * self.assign_item_from_object( item, value) + * except: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":426 + * else: + * try: + * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< + * except: + * free(tmp) + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 426; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L13_try_end; + __pyx_L6_error:; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":427 + * try: + * self.assign_item_from_object( item, value) + * except: # <<<<<<<<<<<<<< + * free(tmp) + * raise + */ + /*except:*/ { + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 427; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":428 + * self.assign_item_from_object( item, value) + * except: + * free(tmp) # <<<<<<<<<<<<<< + * raise + * + */ + free(__pyx_v_tmp); + + /* "View.MemoryView":429 + * except: + * free(tmp) + * raise # <<<<<<<<<<<<<< + * + * + */ + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_ErrRestore(__pyx_t_5, __pyx_t_6, __pyx_t_7); + __pyx_t_5 = 0; __pyx_t_6 = 0; __pyx_t_7 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L7_exception_handled; + } + __pyx_L8_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L7_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L13_try_end:; + } + } + __pyx_L5:; + + /* "View.MemoryView":433 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":434 + * + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + */ + __pyx_t_7 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":435 + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< + * item, self.dtype_is_object) + * free(tmp) + */ + __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); + + /* "View.MemoryView":437 + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + * free(tmp) # <<<<<<<<<<<<<< + * + * cdef setitem_indexed(self, index, value): + */ + free(__pyx_v_tmp); + + /* "View.MemoryView":405 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":439 + * free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_indexed", 0); + + /* "View.MemoryView":440 + * + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< + * self.assign_item_from_object(itemp, value) + * + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_1; + + /* "View.MemoryView":441 + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":439 + * free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":443 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_v_struct = NULL; + PyObject *__pyx_v_bytesitem = 0; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":446 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef bytes bytesitem + * + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":449 + * cdef bytes bytesitem + * + * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< + * try: + * result = struct.unpack(self.view.format, bytesitem) + */ + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":450 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":451 + * bytesitem = itemp[:self.view.itemsize] + * try: + * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< + * except struct.error: + * raise ValueError("Unable to convert item to object") + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_bytesitem); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_v_bytesitem); + __Pyx_GIVEREF(__pyx_v_bytesitem); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + } + /*else:*/ { + + /* "View.MemoryView":455 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + __pyx_t_7 = strlen(__pyx_v_self->view.format); + __pyx_t_8 = ((__pyx_t_7 == 1) != 0); + if (__pyx_t_8) { + + /* "View.MemoryView":456 + * else: + * if len(self.view.format) == 1: + * return result[0] # <<<<<<<<<<<<<< + * return result + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}; + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L6_except_return; + } + + /* "View.MemoryView":457 + * if len(self.view.format) == 1: + * return result[0] + * return result # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L6_except_return; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L10_try_end; + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":452 + * try: + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: # <<<<<<<<<<<<<< + * raise ValueError("Unable to convert item to object") + * else: + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_1); + + /* "View.MemoryView":453 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_t_10 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__26, NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L4_exception_handled; + } + goto __pyx_L5_except_error; + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L6_except_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + __pyx_L4_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L10_try_end:; + } + + /* "View.MemoryView":443 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesitem); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":459 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_v_struct = NULL; + char __pyx_v_c; + PyObject *__pyx_v_bytesvalue = 0; + Py_ssize_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + char *__pyx_t_10; + char *__pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":462 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef char c + * cdef bytes bytesvalue + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":467 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + __pyx_t_2 = PyTuple_Check(__pyx_v_value); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":468 + * + * if isinstance(value, tuple): + * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< + * else: + * bytesvalue = struct.pack(self.view.format, value) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":470 + * bytesvalue = struct.pack(self.view.format, *value) + * else: + * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< + * + * for i, c in enumerate(bytesvalue): + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_INCREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_1, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_6)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":472 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = 0; + if (unlikely(__pyx_v_bytesvalue == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 472; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_INCREF(__pyx_v_bytesvalue); + __pyx_t_8 = __pyx_v_bytesvalue; + __pyx_t_10 = PyBytes_AS_STRING(__pyx_t_8); + __pyx_t_11 = (__pyx_t_10 + PyBytes_GET_SIZE(__pyx_t_8)); + for (__pyx_t_12 = __pyx_t_10; __pyx_t_12 < __pyx_t_11; __pyx_t_12++) { + __pyx_t_9 = __pyx_t_12; + __pyx_v_c = (__pyx_t_9[0]); + + /* "View.MemoryView":473 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + __pyx_v_i = __pyx_t_7; + + /* "View.MemoryView":472 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":473 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "View.MemoryView":459 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":476 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + char *__pyx_t_3; + void *__pyx_t_4; + int __pyx_t_5; + Py_ssize_t __pyx_t_6; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":477 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":478 + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape # <<<<<<<<<<<<<< + * else: + * info.shape = NULL + */ + __pyx_t_2 = __pyx_v_self->view.shape; + __pyx_v_info->shape = __pyx_t_2; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":480 + * info.shape = self.view.shape + * else: + * info.shape = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_STRIDES: + */ + __pyx_v_info->shape = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":482 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":483 + * + * if flags & PyBUF_STRIDES: + * info.strides = self.view.strides # <<<<<<<<<<<<<< + * else: + * info.strides = NULL + */ + __pyx_t_2 = __pyx_v_self->view.strides; + __pyx_v_info->strides = __pyx_t_2; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":485 + * info.strides = self.view.strides + * else: + * info.strides = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_INDIRECT: + */ + __pyx_v_info->strides = NULL; + } + __pyx_L4:; + + /* "View.MemoryView":487 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":488 + * + * if flags & PyBUF_INDIRECT: + * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< + * else: + * info.suboffsets = NULL + */ + __pyx_t_2 = __pyx_v_self->view.suboffsets; + __pyx_v_info->suboffsets = __pyx_t_2; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":490 + * info.suboffsets = self.view.suboffsets + * else: + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->suboffsets = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":492 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":493 + * + * if flags & PyBUF_FORMAT: + * info.format = self.view.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_3 = __pyx_v_self->view.format; + __pyx_v_info->format = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":495 + * info.format = self.view.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.buf = self.view.buf + */ + __pyx_v_info->format = NULL; + } + __pyx_L6:; + + /* "View.MemoryView":497 + * info.format = NULL + * + * info.buf = self.view.buf # <<<<<<<<<<<<<< + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + */ + __pyx_t_4 = __pyx_v_self->view.buf; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":498 + * + * info.buf = self.view.buf + * info.ndim = self.view.ndim # <<<<<<<<<<<<<< + * info.itemsize = self.view.itemsize + * info.len = self.view.len + */ + __pyx_t_5 = __pyx_v_self->view.ndim; + __pyx_v_info->ndim = __pyx_t_5; + + /* "View.MemoryView":499 + * info.buf = self.view.buf + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< + * info.len = self.view.len + * info.readonly = 0 + */ + __pyx_t_6 = __pyx_v_self->view.itemsize; + __pyx_v_info->itemsize = __pyx_t_6; + + /* "View.MemoryView":500 + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + * info.len = self.view.len # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.obj = self + */ + __pyx_t_6 = __pyx_v_self->view.len; + __pyx_v_info->len = __pyx_t_6; + + /* "View.MemoryView":501 + * info.itemsize = self.view.itemsize + * info.len = self.view.len + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.obj = self + * + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":502 + * info.len = self.view.len + * info.readonly = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "View.MemoryView":476 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + + /* function exit code */ + __pyx_r = 0; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":509 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":510 + * @cname('__pyx_memoryview_transpose') + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< + * transpose_memslice(&result.from_slice) + * return result + */ + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":511 + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":512 + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + * return result # <<<<<<<<<<<<<< + * + * property base: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":509 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":516 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":517 + * @cname('__pyx_memoryview__get__base') + * def __get__(self): + * return self.obj # <<<<<<<<<<<<<< + * + * property shape: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->obj); + __pyx_r = __pyx_v_self->obj; + goto __pyx_L0; + + /* "View.MemoryView":516 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":521 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":522 + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property strides: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_v_self->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->view.shape[__pyx_v_i])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __pyx_t_4 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + + /* "View.MemoryView":521 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":526 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":527 + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":529 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__27, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":531 + * raise ValueError("Buffer view does not expose strides") + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property suboffsets: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.strides[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":526 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":535 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":536 + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return [-1] * self.view.ndim + * + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":537 + * def __get__(self): + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(1 * ((__pyx_v_self->view.ndim<0) ? 0:__pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_self->view.ndim; __pyx_temp++) { + __Pyx_INCREF(__pyx_int_neg_1); + PyList_SET_ITEM(__pyx_t_2, __pyx_temp, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + } + } + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":539 + * return [-1] * self.view.ndim + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property ndim: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.suboffsets[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":535 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":543 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":544 + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): + * return self.view.ndim # <<<<<<<<<<<<<< + * + * property itemsize: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 544; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":543 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":548 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":549 + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): + * return self.view.itemsize # <<<<<<<<<<<<<< + * + * property nbytes: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 549; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":548 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":553 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":554 + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): + * return self.size * self.view.itemsize # <<<<<<<<<<<<<< + * + * property size: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":553 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":558 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":559 + * @cname('__pyx_memoryview_get_size') + * def __get__(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + __pyx_t_1 = (__pyx_v_self->_size == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":560 + * def __get__(self): + * if self._size is None: + * result = 1 # <<<<<<<<<<<<<< + * + * for length in self.shape: + */ + __Pyx_INCREF(__pyx_int_1); + __pyx_v_result = __pyx_int_1; + + /* "View.MemoryView":562 + * result = 1 + * + * for length in self.shape: # <<<<<<<<<<<<<< + * result *= length + * + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyList_CheckExact(__pyx_t_3) || PyTuple_CheckExact(__pyx_t_3)) { + __pyx_t_4 = __pyx_t_3; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_3 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_3)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":563 + * + * for length in self.shape: + * result *= length # <<<<<<<<<<<<<< + * + * self._size = result + */ + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_3); + __pyx_t_3 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "View.MemoryView":565 + * result *= length + * + * self._size = result # <<<<<<<<<<<<<< + * + * return self._size + */ + __Pyx_INCREF(__pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __Pyx_GOTREF(__pyx_v_self->_size); + __Pyx_DECREF(__pyx_v_self->_size); + __pyx_v_self->_size = __pyx_v_result; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":567 + * self._size = result + * + * return self._size # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->_size); + __pyx_r = __pyx_v_self->_size; + goto __pyx_L0; + + /* "View.MemoryView":558 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":569 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + +/* Python wrapper */ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__len__", 0); + + /* "View.MemoryView":570 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":571 + * def __len__(self): + * if self.view.ndim >= 1: + * return self.view.shape[0] # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_r = (__pyx_v_self->view.shape[0]); + goto __pyx_L0; + } + + /* "View.MemoryView":573 + * return self.view.shape[0] + * + * return 0 # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":569 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":575 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":576 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":577 + * def __repr__(self): + * return "" % (self.base.__class__.__name__, + * id(self)) # <<<<<<<<<<<<<< + * + * def __str__(self): + */ + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 577; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_id, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 577; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":576 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":575 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":579 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__str__", 0); + + /* "View.MemoryView":580 + * + * def __str__(self): + * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":579 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":583 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_c_contig", 0); + + /* "View.MemoryView":586 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":587 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< + * + * def is_f_contig(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 587; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":583 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":589 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_f_contig", 0); + + /* "View.MemoryView":592 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":593 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< + * + * def copy(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":589 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":595 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_mslice; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "View.MemoryView":597 + * def copy(self): + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &mslice) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); + + /* "View.MemoryView":599 + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + * + * slice_copy(self, &mslice) # <<<<<<<<<<<<<< + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); + + /* "View.MemoryView":600 + * + * slice_copy(self, &mslice) + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_C_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k_c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":605 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< + * + * def copy_fortran(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 605; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":595 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":607 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy_fortran", 0); + + /* "View.MemoryView":609 + * def copy_fortran(self): + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &src) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); + + /* "View.MemoryView":611 + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + * + * slice_copy(self, &src) # <<<<<<<<<<<<<< + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); + + /* "View.MemoryView":612 + * + * slice_copy(self, &src) + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_F_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k_fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dst = __pyx_t_1; + + /* "View.MemoryView":617 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 617; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":607 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":621 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + +static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { + struct __pyx_memoryview_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); + + /* "View.MemoryView":622 + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< + * result.typeinfo = typeinfo + * return result + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); + __Pyx_GIVEREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":623 + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_v_result->typeinfo = __pyx_v_typeinfo; + + /* "View.MemoryView":624 + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_check') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":621 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":627 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("memoryview_check", 0); + + /* "View.MemoryView":628 + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): + * return isinstance(o, memoryview) # <<<<<<<<<<<<<< + * + * cdef tuple _unellipsify(object index, int ndim): + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type)); + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + /* "View.MemoryView":627 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":630 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + +static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { + PyObject *__pyx_v_tup = NULL; + PyObject *__pyx_v_result = NULL; + int __pyx_v_have_slices; + int __pyx_v_seen_ellipsis; + CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_item = NULL; + Py_ssize_t __pyx_v_nslices; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + int __pyx_t_10; + int __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_unellipsify", 0); + + /* "View.MemoryView":635 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + __pyx_t_1 = PyTuple_Check(__pyx_v_index); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":636 + * """ + * if not isinstance(index, tuple): + * tup = (index,) # <<<<<<<<<<<<<< + * else: + * tup = index + */ + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 636; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_index); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); + __Pyx_GIVEREF(__pyx_v_index); + __pyx_v_tup = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":638 + * tup = (index,) + * else: + * tup = index # <<<<<<<<<<<<<< + * + * result = [] + */ + __Pyx_INCREF(__pyx_v_index); + __pyx_v_tup = __pyx_v_index; + } + __pyx_L3:; + + /* "View.MemoryView":640 + * tup = index + * + * result = [] # <<<<<<<<<<<<<< + * have_slices = False + * seen_ellipsis = False + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_result = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":641 + * + * result = [] + * have_slices = False # <<<<<<<<<<<<<< + * seen_ellipsis = False + * for idx, item in enumerate(tup): + */ + __pyx_v_have_slices = 0; + + /* "View.MemoryView":642 + * result = [] + * have_slices = False + * seen_ellipsis = False # <<<<<<<<<<<<<< + * for idx, item in enumerate(tup): + * if item is Ellipsis: + */ + __pyx_v_seen_ellipsis = 0; + + /* "View.MemoryView":643 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_3 = __pyx_int_0; + if (PyList_CheckExact(__pyx_v_tup) || PyTuple_CheckExact(__pyx_v_tup)) { + __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_7 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_7)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); + __pyx_t_7 = 0; + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); + __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_t_7; + __pyx_t_7 = 0; + + /* "View.MemoryView":644 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ + __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":645 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ + __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":646 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__28, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { + __Pyx_INCREF(__pyx_t_7); + PyList_SET_ITEM(__pyx_t_9, __pyx_temp, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + } + } + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_10 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_9); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "View.MemoryView":647 + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True # <<<<<<<<<<<<<< + * else: + * result.append(slice(None)) + */ + __pyx_v_seen_ellipsis = 1; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":649 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_t_9 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__29, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = __Pyx_PyList_Append(__pyx_v_result, __pyx_t_9); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + __pyx_L7:; + + /* "View.MemoryView":650 + * else: + * result.append(slice(None)) + * have_slices = True # <<<<<<<<<<<<<< + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + */ + __pyx_v_have_slices = 1; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":652 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ + __pyx_t_1 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_1 = ((!(__Pyx_PyIndex_Check(__pyx_v_item) != 0)) != 0); + __pyx_t_11 = __pyx_t_1; + } else { + __pyx_t_11 = __pyx_t_2; + } + if (__pyx_t_11) { + + /* "View.MemoryView":653 + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< + * + * have_slices = have_slices or isinstance(item, slice) + */ + __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_7, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":655 + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< + * result.append(item) + * + */ + if (!__pyx_v_have_slices) { + __pyx_t_11 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = __pyx_t_11; + } else { + __pyx_t_2 = __pyx_v_have_slices; + } + __pyx_v_have_slices = __pyx_t_2; + + /* "View.MemoryView":656 + * + * have_slices = have_slices or isinstance(item, slice) + * result.append(item) # <<<<<<<<<<<<<< + * + * nslices = ndim - len(result) + */ + __pyx_t_10 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":658 + * result.append(item) + * + * nslices = ndim - len(result) # <<<<<<<<<<<<<< + * if nslices: + * result.extend([slice(None)] * nslices) + */ + __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 658; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); + + /* "View.MemoryView":659 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + __pyx_t_2 = (__pyx_v_nslices != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":660 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__30, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { + __Pyx_INCREF(__pyx_t_3); + PyList_SET_ITEM(__pyx_t_4, __pyx_temp, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + } + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_10 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_4); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":662 + * result.extend([slice(None)] * nslices) + * + * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 662; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 662; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_2) { + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 662; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_9 = __pyx_t_3; + __pyx_t_3 = 0; + } else { + __pyx_t_9 = __pyx_t_4; + __pyx_t_4 = 0; + } + __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 662; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 662; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_9 = 0; + __pyx_t_4 = 0; + __pyx_r = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":630 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_tup); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_item); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":664 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + +static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); + + /* "View.MemoryView":666 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * cdef int i + * for i in range(ndim): # <<<<<<<<<<<<<< + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":667 + * cdef int i + * for i in range(ndim): + * if suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ + __pyx_t_3 = (((__pyx_v_suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":668 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__31, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + + /* "View.MemoryView":664 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":675 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { + int __pyx_v_new_ndim; + int __pyx_v_suboffset_dim; + int __pyx_v_dim; + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + __Pyx_memviewslice *__pyx_v_p_src; + struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; + __Pyx_memviewslice *__pyx_v_p_dst; + int *__pyx_v_p_suboffset_dim; + Py_ssize_t __pyx_v_start; + Py_ssize_t __pyx_v_stop; + Py_ssize_t __pyx_v_step; + int __pyx_v_have_start; + int __pyx_v_have_stop; + int __pyx_v_have_step; + PyObject *__pyx_v_index = NULL; + struct __pyx_memoryview_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + struct __pyx_memoryview_obj *__pyx_t_4; + char *__pyx_t_5; + int __pyx_t_6; + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + PyObject *__pyx_t_12 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memview_slice", 0); + + /* "View.MemoryView":676 + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): + * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< + * cdef bint negative_step + * cdef __Pyx_memviewslice src, dst + */ + __pyx_v_new_ndim = 0; + __pyx_v_suboffset_dim = -1; + + /* "View.MemoryView":683 + * + * + * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< + * + * cdef _memoryviewslice memviewsliceobj + */ + memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); + + /* "View.MemoryView":687 + * cdef _memoryviewslice memviewsliceobj + * + * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "View.MemoryView":689 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":690 + * + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview # <<<<<<<<<<<<<< + * p_src = &memviewsliceobj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 690; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":691 + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, &src) + */ + __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":693 + * p_src = &memviewsliceobj.from_slice + * else: + * slice_copy(memview, &src) # <<<<<<<<<<<<<< + * p_src = &src + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); + + /* "View.MemoryView":694 + * else: + * slice_copy(memview, &src) + * p_src = &src # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_src = (&__pyx_v_src); + } + __pyx_L3:; + + /* "View.MemoryView":700 + * + * + * dst.memview = p_src.memview # <<<<<<<<<<<<<< + * dst.data = p_src.data + * + */ + __pyx_t_4 = __pyx_v_p_src->memview; + __pyx_v_dst.memview = __pyx_t_4; + + /* "View.MemoryView":701 + * + * dst.memview = p_src.memview + * dst.data = p_src.data # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_v_p_src->data; + __pyx_v_dst.data = __pyx_t_5; + + /* "View.MemoryView":706 + * + * + * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< + * cdef int *p_suboffset_dim = &suboffset_dim + * cdef Py_ssize_t start, stop, step + */ + __pyx_v_p_dst = (&__pyx_v_dst); + + /* "View.MemoryView":707 + * + * cdef __Pyx_memviewslice *p_dst = &dst + * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< + * cdef Py_ssize_t start, stop, step + * cdef bint have_start, have_stop, have_step + */ + __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); + + /* "View.MemoryView":711 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + __pyx_t_6 = 0; + if (PyList_CheckExact(__pyx_v_indices) || PyTuple_CheckExact(__pyx_v_indices)) { + __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; + } + for (;;) { + if (!__pyx_t_8 && PyList_CheckExact(__pyx_t_3)) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_8 && PyTuple_CheckExact(__pyx_t_3)) { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_9 = __pyx_t_8(__pyx_t_3); + if (unlikely(!__pyx_t_9)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_9); + } + __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); + __pyx_t_9 = 0; + __pyx_v_dim = __pyx_t_6; + __pyx_t_6 = (__pyx_t_6 + 1); + + /* "View.MemoryView":712 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ + __pyx_t_2 = (__Pyx_PyIndex_Check(__pyx_v_index) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":716 + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< + * 0, 0, 0, # have_{start,stop,step} + * False) + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":713 + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + + /* "View.MemoryView":719 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ + __pyx_t_2 = (__pyx_v_index == Py_None); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":720 + * False) + * elif index is None: + * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + */ + (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; + + /* "View.MemoryView":721 + * elif index is None: + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 + */ + (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; + + /* "View.MemoryView":722 + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< + * new_ndim += 1 + * else: + */ + (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1; + + /* "View.MemoryView":723 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 # <<<<<<<<<<<<<< + * else: + * start = index.start or 0 + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":725 + * new_ndim += 1 + * else: + * start = index.start or 0 # <<<<<<<<<<<<<< + * stop = index.stop or 0 + * step = index.step or 0 + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_start = __pyx_t_10; + + /* "View.MemoryView":726 + * else: + * start = index.start or 0 + * stop = index.stop or 0 # <<<<<<<<<<<<<< + * step = index.step or 0 + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 726; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_12); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 726; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_9 = __pyx_int_0; + } else { + __pyx_t_9 = __pyx_t_12; + __pyx_t_12 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 726; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_stop = __pyx_t_10; + + /* "View.MemoryView":727 + * start = index.start or 0 + * stop = index.stop or 0 + * step = index.step or 0 # <<<<<<<<<<<<<< + * + * have_start = index.start is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 727; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 727; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 727; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_step = __pyx_t_10; + + /* "View.MemoryView":729 + * step = index.step or 0 + * + * have_start = index.start is not None # <<<<<<<<<<<<<< + * have_stop = index.stop is not None + * have_step = index.step is not None + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 729; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_start = __pyx_t_1; + + /* "View.MemoryView":730 + * + * have_start = index.start is not None + * have_stop = index.stop is not None # <<<<<<<<<<<<<< + * have_step = index.step is not None + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 730; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_stop = __pyx_t_1; + + /* "View.MemoryView":731 + * have_start = index.start is not None + * have_stop = index.stop is not None + * have_step = index.step is not None # <<<<<<<<<<<<<< + * + * slice_memviewslice( + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 731; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_step = __pyx_t_1; + + /* "View.MemoryView":733 + * have_step = index.step is not None + * + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 733; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":739 + * have_start, have_stop, have_step, + * True) + * new_ndim += 1 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":741 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":742 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":743 + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 743; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":744 + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * else: + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 744; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":742 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 742; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 742; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":747 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":748 + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 747; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":747 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 747; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":675 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":772 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { + Py_ssize_t __pyx_v_new_shape; + int __pyx_v_negative_step; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":792 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":794 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + __pyx_t_1 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":795 + * + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":796 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + __pyx_t_1 = (0 <= __pyx_v_start); + if (__pyx_t_1) { + __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); + } + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":797 + * start += shape + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< + * else: + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_Index_out_of_bounds_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":800 + * else: + * + * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< + * + * if have_step and step == 0: + */ + __pyx_t_2 = (__pyx_v_have_step != 0); + if (__pyx_t_2) { + __pyx_t_1 = (__pyx_v_step < 0); + __pyx_t_4 = __pyx_t_1; + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_v_negative_step = __pyx_t_4; + + /* "View.MemoryView":802 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + if ((__pyx_v_have_step != 0)) { + __pyx_t_4 = (__pyx_v_step == 0); + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = (__pyx_v_have_step != 0); + } + if (__pyx_t_2) { + + /* "View.MemoryView":803 + * + * if have_step and step == 0: + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Step_may_not_be_zero_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":806 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + __pyx_t_2 = (__pyx_v_have_start != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":807 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":808 + * if have_start: + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if start < 0: + * start = 0 + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":809 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":810 + * start += shape + * if start < 0: + * start = 0 # <<<<<<<<<<<<<< + * elif start >= shape: + * if negative_step: + */ + __pyx_v_start = 0; + goto __pyx_L9; + } + __pyx_L9:; + goto __pyx_L8; + } + + /* "View.MemoryView":811 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":812 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":813 + * elif start >= shape: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = shape + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L10; + } + /*else*/ { + + /* "View.MemoryView":815 + * start = shape - 1 + * else: + * start = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_start = __pyx_v_shape; + } + __pyx_L10:; + goto __pyx_L8; + } + __pyx_L8:; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":817 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":818 + * else: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = 0 + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":820 + * start = shape - 1 + * else: + * start = 0 # <<<<<<<<<<<<<< + * + * if have_stop: + */ + __pyx_v_start = 0; + } + __pyx_L11:; + } + __pyx_L7:; + + /* "View.MemoryView":822 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + __pyx_t_2 = (__pyx_v_have_stop != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":823 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":824 + * if have_stop: + * if stop < 0: + * stop += shape # <<<<<<<<<<<<<< + * if stop < 0: + * stop = 0 + */ + __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); + + /* "View.MemoryView":825 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":826 + * stop += shape + * if stop < 0: + * stop = 0 # <<<<<<<<<<<<<< + * elif stop > shape: + * stop = shape + */ + __pyx_v_stop = 0; + goto __pyx_L14; + } + __pyx_L14:; + goto __pyx_L13; + } + + /* "View.MemoryView":827 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":828 + * stop = 0 + * elif stop > shape: + * stop = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_stop = __pyx_v_shape; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L12; + } + /*else*/ { + + /* "View.MemoryView":830 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":831 + * else: + * if negative_step: + * stop = -1 # <<<<<<<<<<<<<< + * else: + * stop = shape + */ + __pyx_v_stop = -1; + goto __pyx_L15; + } + /*else*/ { + + /* "View.MemoryView":833 + * stop = -1 + * else: + * stop = shape # <<<<<<<<<<<<<< + * + * if not have_step: + */ + __pyx_v_stop = __pyx_v_shape; + } + __pyx_L15:; + } + __pyx_L12:; + + /* "View.MemoryView":835 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":836 + * + * if not have_step: + * step = 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_step = 1; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":840 + * + * with cython.cdivision(True): + * new_shape = (stop - start) // step # <<<<<<<<<<<<<< + * + * if (stop - start) - step * new_shape: + */ + __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); + + /* "View.MemoryView":842 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":843 + * + * if (stop - start) - step * new_shape: + * new_shape += 1 # <<<<<<<<<<<<<< + * + * if new_shape < 0: + */ + __pyx_v_new_shape = (__pyx_v_new_shape + 1); + goto __pyx_L17; + } + __pyx_L17:; + + /* "View.MemoryView":845 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":846 + * + * if new_shape < 0: + * new_shape = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_new_shape = 0; + goto __pyx_L18; + } + __pyx_L18:; + + /* "View.MemoryView":849 + * + * + * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset + */ + (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); + + /* "View.MemoryView":850 + * + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< + * dst.suboffsets[new_ndim] = suboffset + * + */ + (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; + + /* "View.MemoryView":851 + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; + } + __pyx_L3:; + + /* "View.MemoryView":854 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":855 + * + * if suboffset_dim[0] < 0: + * dst.data += start * stride # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride + */ + __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); + goto __pyx_L19; + } + /*else*/ { + + /* "View.MemoryView":857 + * dst.data += start * stride + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< + * + * if suboffset >= 0: + */ + __pyx_t_3 = (__pyx_v_suboffset_dim[0]); + (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); + } + __pyx_L19:; + + /* "View.MemoryView":859 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":860 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":861 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":862 + * if not is_slice: + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + */ + __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); + goto __pyx_L22; + } + /*else*/ { + + /* "View.MemoryView":864 + * dst.data = ( dst.data)[0] + suboffset + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< + * "must be indexed and not sliced", dim) + * else: + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_All_dimensions_preceding_dimensi, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 864; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L22:; + goto __pyx_L21; + } + /*else*/ { + + /* "View.MemoryView":867 + * "must be indexed and not sliced", dim) + * else: + * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< + * + * return 0 + */ + (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; + } + __pyx_L21:; + goto __pyx_L20; + } + __pyx_L20:; + + /* "View.MemoryView":869 + * suboffset_dim[0] = new_ndim + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":772 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":875 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + +static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { + Py_ssize_t __pyx_v_shape; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_suboffset; + Py_ssize_t __pyx_v_itemsize; + char *__pyx_v_resultp; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pybuffer_index", 0); + + /* "View.MemoryView":877 + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< + * cdef Py_ssize_t itemsize = view.itemsize + * cdef char *resultp + */ + __pyx_v_suboffset = -1; + + /* "View.MemoryView":878 + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< + * cdef char *resultp + * + */ + __pyx_t_1 = __pyx_v_view->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":881 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":882 + * + * if view.ndim == 0: + * shape = view.len / itemsize # <<<<<<<<<<<<<< + * stride = itemsize + * else: + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_shape = (__pyx_v_view->len / __pyx_v_itemsize); + + /* "View.MemoryView":883 + * if view.ndim == 0: + * shape = view.len / itemsize + * stride = itemsize # <<<<<<<<<<<<<< + * else: + * shape = view.shape[dim] + */ + __pyx_v_stride = __pyx_v_itemsize; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":885 + * stride = itemsize + * else: + * shape = view.shape[dim] # <<<<<<<<<<<<<< + * stride = view.strides[dim] + * if view.suboffsets != NULL: + */ + __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); + + /* "View.MemoryView":886 + * else: + * shape = view.shape[dim] + * stride = view.strides[dim] # <<<<<<<<<<<<<< + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] + */ + __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); + + /* "View.MemoryView":887 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":888 + * stride = view.strides[dim] + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< + * + * if index < 0: + */ + __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); + goto __pyx_L4; + } + __pyx_L4:; + } + __pyx_L3:; + + /* "View.MemoryView":890 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":891 + * + * if index < 0: + * index += view.shape[dim] # <<<<<<<<<<<<<< + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + */ + __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); + + /* "View.MemoryView":892 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":893 + * index += view.shape[dim] + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * if index >= shape: + */ + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":895 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":896 + * + * if index >= shape: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * resultp = bufp + index * stride + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":898 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * resultp = bufp + index * stride # <<<<<<<<<<<<<< + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset + */ + __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); + + /* "View.MemoryView":899 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":900 + * resultp = bufp + index * stride + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< + * + * return resultp + */ + __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":902 + * resultp = ( resultp)[0] + suboffset + * + * return resultp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_resultp; + goto __pyx_L0; + + /* "View.MemoryView":875 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":908 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + +static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { + int __pyx_v_ndim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + int __pyx_v_i; + int __pyx_v_j; + int __pyx_r; + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + long __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":909 + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: + * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< + * + * cdef Py_ssize_t *shape = memslice.shape + */ + __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; + __pyx_v_ndim = __pyx_t_1; + + /* "View.MemoryView":911 + * cdef int ndim = memslice.memview.view.ndim + * + * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< + * cdef Py_ssize_t *strides = memslice.strides + * + */ + __pyx_t_2 = __pyx_v_memslice->shape; + __pyx_v_shape = __pyx_t_2; + + /* "View.MemoryView":912 + * + * cdef Py_ssize_t *shape = memslice.shape + * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_v_memslice->strides; + __pyx_v_strides = __pyx_t_2; + + /* "View.MemoryView":916 + * + * cdef int i, j + * for i in range(ndim / 2): # <<<<<<<<<<<<<< + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + */ + __pyx_t_3 = (__pyx_v_ndim / 2); + for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":917 + * cdef int i, j + * for i in range(ndim / 2): + * j = ndim - 1 - i # <<<<<<<<<<<<<< + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] + */ + __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); + + /* "View.MemoryView":918 + * for i in range(ndim / 2): + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< + * shape[i], shape[j] = shape[j], shape[i] + * + */ + __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); + __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); + (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; + (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; + + /* "View.MemoryView":919 + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + */ + __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); + __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); + (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; + (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; + + /* "View.MemoryView":921 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + __pyx_t_6 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); + if (!__pyx_t_6) { + __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); + __pyx_t_8 = __pyx_t_7; + } else { + __pyx_t_8 = __pyx_t_6; + } + if (__pyx_t_8) { + + /* "View.MemoryView":922 + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< + * + * return 1 + */ + __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_Cannot_transpose_memoryview_with); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "View.MemoryView":924 + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + * return 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 1; + goto __pyx_L0; + + /* "View.MemoryView":908 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":941 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + +/* Python wrapper */ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":942 + * + * def __dealloc__(self): + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); + + /* "View.MemoryView":941 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":944 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":945 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":946 + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) # <<<<<<<<<<<<<< + * else: + * return memoryview.convert_item_to_object(self, itemp) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":948 + * return self.to_object_func(itemp) + * else: + * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_vtabptr_memoryview->convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":944 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":950 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":951 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":952 + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< + * else: + * memoryview.assign_item_from_object(self, itemp, value) + */ + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 952; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":954 + * self.to_dtype_func(itemp, value) + * else: + * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< + * + * property base: + */ + __pyx_t_3 = __pyx_vtabptr_memoryview->assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 954; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":950 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":958 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":959 + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): + * return self.from_object # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->from_object); + __pyx_r = __pyx_v_self->from_object; + goto __pyx_L0; + + /* "View.MemoryView":958 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":965 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_TypeInfo *__pyx_t_4; + Py_buffer __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_fromslice", 0); + + /* "View.MemoryView":974 + * cdef int i + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":975 + * + * if memviewslice.memview == Py_None: + * return None # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + + /* "View.MemoryView":980 + * + * + * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< + * + * result.from_slice = memviewslice + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 980; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 980; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 980; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":982 + * result = _memoryviewslice(None, 0, dtype_is_object) + * + * result.from_slice = memviewslice # <<<<<<<<<<<<<< + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + */ + __pyx_v_result->from_slice = __pyx_v_memviewslice; + + /* "View.MemoryView":983 + * + * result.from_slice = memviewslice + * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< + * + * result.from_object = ( memviewslice.memview).base + */ + __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); + + /* "View.MemoryView":985 + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< + * result.typeinfo = memviewslice.memview.typeinfo + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_result->from_object); + __Pyx_DECREF(__pyx_v_result->from_object); + __pyx_v_result->from_object = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":986 + * + * result.from_object = ( memviewslice.memview).base + * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< + * + * result.view = memviewslice.memview.view + */ + __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; + __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; + + /* "View.MemoryView":988 + * result.typeinfo = memviewslice.memview.typeinfo + * + * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + */ + __pyx_t_5 = __pyx_v_memviewslice.memview->view; + __pyx_v_result->__pyx_base.view = __pyx_t_5; + + /* "View.MemoryView":989 + * + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + */ + __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); + + /* "View.MemoryView":990 + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data + * result.view.ndim = ndim # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; + + /* "View.MemoryView":991 + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; + + /* "View.MemoryView":992 + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * result.flags = PyBUF_RECORDS + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":994 + * Py_INCREF(Py_None) + * + * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< + * + * result.view.shape = result.from_slice.shape + */ + __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; + + /* "View.MemoryView":996 + * result.flags = PyBUF_RECORDS + * + * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets + */ + __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); + + /* "View.MemoryView":997 + * + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * + */ + __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); + + /* "View.MemoryView":998 + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + * + * result.view.len = result.view.itemsize + */ + __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + + /* "View.MemoryView":1000 + * result.view.suboffsets = result.from_slice.suboffsets + * + * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< + * for i in range(ndim): + * result.view.len *= result.view.shape[i] + */ + __pyx_t_6 = __pyx_v_result->__pyx_base.view.itemsize; + __pyx_v_result->__pyx_base.view.len = __pyx_t_6; + + /* "View.MemoryView":1001 + * + * result.view.len = result.view.itemsize + * for i in range(ndim): # <<<<<<<<<<<<<< + * result.view.len *= result.view.shape[i] + * + */ + __pyx_t_7 = __pyx_v_ndim; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "View.MemoryView":1002 + * result.view.len = result.view.itemsize + * for i in range(ndim): + * result.view.len *= result.view.shape[i] # <<<<<<<<<<<<<< + * + * result.to_object_func = to_object_func + */ + __pyx_v_result->__pyx_base.view.len = (__pyx_v_result->__pyx_base.view.len * (__pyx_v_result->__pyx_base.view.shape[__pyx_v_i])); + } + + /* "View.MemoryView":1004 + * result.view.len *= result.view.shape[i] + * + * result.to_object_func = to_object_func # <<<<<<<<<<<<<< + * result.to_dtype_func = to_dtype_func + * + */ + __pyx_v_result->to_object_func = __pyx_v_to_object_func; + + /* "View.MemoryView":1005 + * + * result.to_object_func = to_object_func + * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; + + /* "View.MemoryView":1007 + * result.to_dtype_func = to_dtype_func + * + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":965 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1010 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { + struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; + __Pyx_memviewslice *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_slice_from_memview", 0); + + /* "View.MemoryView":1013 + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1014 + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): + * obj = memview # <<<<<<<<<<<<<< + * return &obj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1014; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":1015 + * if isinstance(memview, _memoryviewslice): + * obj = memview + * return &obj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, mslice) + */ + __pyx_r = (&__pyx_v_obj->from_slice); + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1017 + * return &obj.from_slice + * else: + * slice_copy(memview, mslice) # <<<<<<<<<<<<<< + * return mslice + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); + + /* "View.MemoryView":1018 + * else: + * slice_copy(memview, mslice) + * return mslice # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_copy') + */ + __pyx_r = __pyx_v_mslice; + goto __pyx_L0; + } + + /* "View.MemoryView":1010 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_obj); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1021 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { + int __pyx_v_dim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + Py_ssize_t *__pyx_v_suboffsets; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + __Pyx_RefNannySetupContext("slice_copy", 0); + + /* "View.MemoryView":1025 + * cdef (Py_ssize_t*) shape, strides, suboffsets + * + * shape = memview.view.shape # <<<<<<<<<<<<<< + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets + */ + __pyx_t_1 = __pyx_v_memview->view.shape; + __pyx_v_shape = __pyx_t_1; + + /* "View.MemoryView":1026 + * + * shape = memview.view.shape + * strides = memview.view.strides # <<<<<<<<<<<<<< + * suboffsets = memview.view.suboffsets + * + */ + __pyx_t_1 = __pyx_v_memview->view.strides; + __pyx_v_strides = __pyx_t_1; + + /* "View.MemoryView":1027 + * shape = memview.view.shape + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< + * + * dst.memview = <__pyx_memoryview *> memview + */ + __pyx_t_1 = __pyx_v_memview->view.suboffsets; + __pyx_v_suboffsets = __pyx_t_1; + + /* "View.MemoryView":1029 + * suboffsets = memview.view.suboffsets + * + * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< + * dst.data = memview.view.buf + * + */ + __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); + + /* "View.MemoryView":1030 + * + * dst.memview = <__pyx_memoryview *> memview + * dst.data = memview.view.buf # <<<<<<<<<<<<<< + * + * for dim in range(memview.view.ndim): + */ + __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); + + /* "View.MemoryView":1032 + * dst.data = memview.view.buf + * + * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + */ + __pyx_t_2 = __pyx_v_memview->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_dim = __pyx_t_3; + + /* "View.MemoryView":1033 + * + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + */ + (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); + + /* "View.MemoryView":1034 + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 + */ + (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); + + /* "View.MemoryView":1035 + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: # <<<<<<<<<<<<<< + * dst.suboffsets[dim] = -1 + * else: + */ + __pyx_t_4 = ((__pyx_v_suboffsets == NULL) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":1036 + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[dim] = suboffsets[dim] + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = -1; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1038 + * dst.suboffsets[dim] = -1 + * else: + * dst.suboffsets[dim] = suboffsets[dim] # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object') + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = (__pyx_v_suboffsets[__pyx_v_dim]); + } + __pyx_L5:; + } + + /* "View.MemoryView":1021 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1041 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { + __Pyx_memviewslice __pyx_v_memviewslice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy", 0); + + /* "View.MemoryView":1044 + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< + * return memoryview_copy_from_slice(memview, &memviewslice) + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); + + /* "View.MemoryView":1045 + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) + * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object_from_slice') + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1041 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1048 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { + PyObject *(*__pyx_v_to_object_func)(char *); + int (*__pyx_v_to_dtype_func)(char *, PyObject *); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *(*__pyx_t_3)(char *); + int (*__pyx_t_4)(char *, PyObject *); + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); + + /* "View.MemoryView":1055 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1056 + * + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + */ + __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; + __pyx_v_to_object_func = __pyx_t_3; + + /* "View.MemoryView":1057 + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< + * else: + * to_object_func = NULL + */ + __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; + __pyx_v_to_dtype_func = __pyx_t_4; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1059 + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + * to_object_func = NULL # <<<<<<<<<<<<<< + * to_dtype_func = NULL + * + */ + __pyx_v_to_object_func = NULL; + + /* "View.MemoryView":1060 + * else: + * to_object_func = NULL + * to_dtype_func = NULL # <<<<<<<<<<<<<< + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + */ + __pyx_v_to_dtype_func = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":1062 + * to_dtype_func = NULL + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< + * to_object_func, to_dtype_func, + * memview.dtype_is_object) + */ + __Pyx_XDECREF(__pyx_r); + + /* "View.MemoryView":1064 + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + * to_object_func, to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1048 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1070 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + +static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { + Py_ssize_t __pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":1071 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + __pyx_t_1 = ((__pyx_v_arg < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1072 + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: + * return -arg # <<<<<<<<<<<<<< + * else: + * return arg + */ + __pyx_r = (-__pyx_v_arg); + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1074 + * return -arg + * else: + * return arg # <<<<<<<<<<<<<< + * + * @cname('__pyx_get_best_slice_order') + */ + __pyx_r = __pyx_v_arg; + goto __pyx_L0; + } + + /* "View.MemoryView":1070 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1077 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + +static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_c_stride; + Py_ssize_t __pyx_v_f_stride; + char __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1082 + * """ + * cdef int i + * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t f_stride = 0 + * + */ + __pyx_v_c_stride = 0; + + /* "View.MemoryView":1083 + * cdef int i + * cdef Py_ssize_t c_stride = 0 + * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_f_stride = 0; + + /* "View.MemoryView":1085 + * cdef Py_ssize_t f_stride = 0 + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1086 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1087 + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1088 + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + goto __pyx_L4_break; + } + } + __pyx_L4_break:; + + /* "View.MemoryView":1090 + * break + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1091 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1092 + * for i in range(ndim): + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1093 + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + */ + goto __pyx_L7_break; + } + } + __pyx_L7_break:; + + /* "View.MemoryView":1095 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1096 + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + * return 'C' # <<<<<<<<<<<<<< + * else: + * return 'F' + */ + __pyx_r = 'C'; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1098 + * return 'C' + * else: + * return 'F' # <<<<<<<<<<<<<< + * + * @cython.cdivision(True) + */ + __pyx_r = 'F'; + goto __pyx_L0; + } + + /* "View.MemoryView":1077 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1101 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + +static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; + Py_ssize_t __pyx_v_dst_extent; + Py_ssize_t __pyx_v_src_stride; + Py_ssize_t __pyx_v_dst_stride; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + + /* "View.MemoryView":1108 + * + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + */ + __pyx_v_src_extent = (__pyx_v_src_shape[0]); + + /* "View.MemoryView":1109 + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] + */ + __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); + + /* "View.MemoryView":1110 + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + */ + __pyx_v_src_stride = (__pyx_v_src_strides[0]); + + /* "View.MemoryView":1111 + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); + + /* "View.MemoryView":1113 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1114 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + __pyx_t_1 = ((__pyx_v_src_stride > 0) != 0); + if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1115 + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + */ + __pyx_t_3 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); + if (__pyx_t_3) { + __pyx_t_3 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); + } + __pyx_t_4 = (__pyx_t_3 != 0); + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = __pyx_t_1; + } + if (__pyx_t_2) { + + /* "View.MemoryView":1116 + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":1118 + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1119 + * else: + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); + + /* "View.MemoryView":1120 + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * else: + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1121 + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1123 + * dst_data += dst_stride + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * _copy_strided_to_strided(src_data, src_strides + 1, + * dst_data, dst_strides + 1, + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1124 + * else: + * for i in range(dst_extent): + * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< + * dst_data, dst_strides + 1, + * src_shape + 1, dst_shape + 1, + */ + _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); + + /* "View.MemoryView":1128 + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1129 + * ndim - 1, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1101 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + + /* function exit code */ +} + +/* "View.MemoryView":1131 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + +static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + + /* "View.MemoryView":1134 + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< + * src.shape, dst.shape, ndim, itemsize) + * + */ + _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1131 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1138 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_size; + Py_ssize_t __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1141 + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_size = __pyx_t_1; + + /* "View.MemoryView":1143 + * cdef Py_ssize_t size = src.memview.view.itemsize + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * size *= src.shape[i] + * + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1144 + * + * for i in range(ndim): + * size *= src.shape[i] # <<<<<<<<<<<<<< + * + * return size + */ + __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); + } + + /* "View.MemoryView":1146 + * size *= src.shape[i] + * + * return size # <<<<<<<<<<<<<< + * + * @cname('__pyx_fill_contig_strides_array') + */ + __pyx_r = __pyx_v_size; + goto __pyx_L0; + + /* "View.MemoryView":1138 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1149 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { + int __pyx_v_idx; + Py_ssize_t __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1158 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + __pyx_t_1 = ((__pyx_v_order == 'F') != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1159 + * + * if order == 'F': + * for idx in range(ndim): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_idx = __pyx_t_3; + + /* "View.MemoryView":1160 + * if order == 'F': + * for idx in range(ndim): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * else: + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1161 + * for idx in range(ndim): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * else: + * for idx in range(ndim - 1, -1, -1): + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1163 + * stride = stride * shape[idx] + * else: + * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { + __pyx_v_idx = __pyx_t_2; + + /* "View.MemoryView":1164 + * else: + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1165 + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * + * return stride + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + } + __pyx_L3:; + + /* "View.MemoryView":1167 + * stride = stride * shape[idx] + * + * return stride # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_data_to_temp') + */ + __pyx_r = __pyx_v_stride; + goto __pyx_L0; + + /* "View.MemoryView":1149 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1170 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { + int __pyx_v_i; + void *__pyx_v_result; + size_t __pyx_v_itemsize; + size_t __pyx_v_size; + void *__pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + struct __pyx_memoryview_obj *__pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1181 + * cdef void *result + * + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef size_t size = slice_get_size(src, ndim) + * + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1182 + * + * cdef size_t itemsize = src.memview.view.itemsize + * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< + * + * result = malloc(size) + */ + __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); + + /* "View.MemoryView":1184 + * cdef size_t size = slice_get_size(src, ndim) + * + * result = malloc(size) # <<<<<<<<<<<<<< + * if not result: + * _err(MemoryError, NULL) + */ + __pyx_v_result = malloc(__pyx_v_size); + + /* "View.MemoryView":1185 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1186 + * result = malloc(size) + * if not result: + * _err(MemoryError, NULL) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1189 + * + * + * tmpslice.data = result # <<<<<<<<<<<<<< + * tmpslice.memview = src.memview + * for i in range(ndim): + */ + __pyx_v_tmpslice->data = ((char *)__pyx_v_result); + + /* "View.MemoryView":1190 + * + * tmpslice.data = result + * tmpslice.memview = src.memview # <<<<<<<<<<<<<< + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + */ + __pyx_t_4 = __pyx_v_src->memview; + __pyx_v_tmpslice->memview = __pyx_t_4; + + /* "View.MemoryView":1191 + * tmpslice.data = result + * tmpslice.memview = src.memview + * for i in range(ndim): # <<<<<<<<<<<<<< + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1192 + * tmpslice.memview = src.memview + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< + * tmpslice.suboffsets[i] = -1 + * + */ + (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); + + /* "View.MemoryView":1193 + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + */ + (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1195 + * tmpslice.suboffsets[i] = -1 + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< + * ndim, order) + * + */ + __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); + + /* "View.MemoryView":1199 + * + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1200 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1201 + * for i in range(ndim): + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< + * + * if slice_is_contig(src, order, ndim): + */ + (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1203 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1204 + * + * if slice_is_contig(src, order, ndim): + * memcpy(result, src.data, size) # <<<<<<<<<<<<<< + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + */ + memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1206 + * memcpy(result, src.data, size) + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< + * + * return result + */ + copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); + } + __pyx_L9:; + + /* "View.MemoryView":1208 + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":1170 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = NULL; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1213 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + +static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_extents", 0); + + /* "View.MemoryView":1216 + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + * (i, extent1, extent2)) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err_dim') + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + + /* "View.MemoryView":1215 + * cdef int _err_extents(int i, Py_ssize_t extent1, + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< + * (i, extent1, extent2)) + * + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1213 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1219 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + +static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_dim", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1220 + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: + * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err') + */ + __pyx_t_1 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyUnicode_Format(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_v_error, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1219 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1223 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + +static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1224 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ + __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1225 + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: + * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< + * else: + * raise error + */ + __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_v_error, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + /*else*/ { + + /* "View.MemoryView":1227 + * raise error(msg.decode('ascii')) + * else: + * raise error # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_contents') + */ + __Pyx_Raise(__pyx_v_error, 0, 0, 0); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":1223 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1230 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { + void *__pyx_v_tmpdata; + size_t __pyx_v_itemsize; + int __pyx_v_i; + char __pyx_v_order; + int __pyx_v_broadcasting; + int __pyx_v_direct_copy; + __Pyx_memviewslice __pyx_v_tmp; + int __pyx_v_ndim; + int __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + void *__pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1238 + * Check for overlapping memory and verify the shapes. + * """ + * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + */ + __pyx_v_tmpdata = NULL; + + /* "View.MemoryView":1239 + * """ + * cdef void *tmpdata = NULL + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + */ + __pyx_t_1 = __pyx_v_src.memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1241 + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< + * cdef bint broadcasting = False + * cdef bint direct_copy = False + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); + + /* "View.MemoryView":1242 + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False # <<<<<<<<<<<<<< + * cdef bint direct_copy = False + * cdef __Pyx_memviewslice tmp + */ + __pyx_v_broadcasting = 0; + + /* "View.MemoryView":1243 + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False + * cdef bint direct_copy = False # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice tmp + * + */ + __pyx_v_direct_copy = 0; + + /* "View.MemoryView":1246 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ + __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1247 + * + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); + goto __pyx_L3; + } + + /* "View.MemoryView":1248 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ + __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1249 + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< + * + * cdef int ndim = max(src_ndim, dst_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1251 + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_3 = __pyx_v_dst_ndim; + __pyx_t_4 = __pyx_v_src_ndim; + if (((__pyx_t_3 > __pyx_t_4) != 0)) { + __pyx_t_5 = __pyx_t_3; + } else { + __pyx_t_5 = __pyx_t_4; + } + __pyx_v_ndim = __pyx_t_5; + + /* "View.MemoryView":1253 + * cdef int ndim = max(src_ndim, dst_ndim) + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1254 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1255 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1256 + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + * broadcasting = True # <<<<<<<<<<<<<< + * src.strides[i] = 0 + * else: + */ + __pyx_v_broadcasting = 1; + + /* "View.MemoryView":1257 + * if src.shape[i] == 1: + * broadcasting = True + * src.strides[i] = 0 # <<<<<<<<<<<<<< + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) + */ + (__pyx_v_src.strides[__pyx_v_i]) = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":1259 + * src.strides[i] = 0 + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< + * + * if src.suboffsets[i] >= 0: + */ + __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1259; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":1261 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ + __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1262 + * + * if src.suboffsets[i] >= 0: + * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< + * + * if slices_overlap(&src, &dst, ndim, itemsize): + */ + __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Dimension_d_is_not_direct, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1264 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(&src, order, ndim): + */ + __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1266 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1267 + * + * if not slice_is_contig(&src, order, ndim): + * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":1269 + * order = get_best_order(&dst, ndim) + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< + * src = tmp + * + */ + __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1269; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_tmpdata = __pyx_t_6; + + /* "View.MemoryView":1270 + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + * src = tmp # <<<<<<<<<<<<<< + * + * if not broadcasting: + */ + __pyx_v_src = __pyx_v_tmp; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":1272 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1275 + * + * + * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1276 + * + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); + goto __pyx_L12; + } + + /* "View.MemoryView":1277 + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1278 + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< + * + * if direct_copy: + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":1280 + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_2 = (__pyx_v_direct_copy != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1282 + * if direct_copy: + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1283 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * return 0 + */ + memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); + + /* "View.MemoryView":1284 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1285 + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + * return 0 # <<<<<<<<<<<<<< + * + * if order == 'F' == get_best_order(&dst, ndim): + */ + __pyx_r = 0; + goto __pyx_L0; + } + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":1287 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = (__pyx_v_order == 'F'); + if (__pyx_t_2) { + __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); + } + __pyx_t_7 = (__pyx_t_2 != 0); + if (__pyx_t_7) { + + /* "View.MemoryView":1290 + * + * + * transpose_memslice(&src) # <<<<<<<<<<<<<< + * transpose_memslice(&dst) + * + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1291 + * + * transpose_memslice(&src) + * transpose_memslice(&dst) # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":1293 + * transpose_memslice(&dst) + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1294 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + */ + copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1295 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * free(tmpdata) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1297 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1298 + * + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_broadcast_leading') + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":1230 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1301 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice, int __pyx_v_ndim, int __pyx_v_ndim_other) { + int __pyx_v_i; + int __pyx_v_offset; + int __pyx_t_1; + int __pyx_t_2; + + /* "View.MemoryView":1305 + * int ndim_other) nogil: + * cdef int i + * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); + + /* "View.MemoryView":1307 + * cdef int offset = ndim_other - ndim + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1308 + * + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] # <<<<<<<<<<<<<< + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] + */ + (__pyx_v_slice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->shape[__pyx_v_i]); + + /* "View.MemoryView":1309 + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] # <<<<<<<<<<<<<< + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + */ + (__pyx_v_slice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->strides[__pyx_v_i]); + + /* "View.MemoryView":1310 + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] # <<<<<<<<<<<<<< + * + * for i in range(offset): + */ + (__pyx_v_slice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->suboffsets[__pyx_v_i]); + } + + /* "View.MemoryView":1312 + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + * for i in range(offset): # <<<<<<<<<<<<<< + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + */ + __pyx_t_1 = __pyx_v_offset; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1313 + * + * for i in range(offset): + * slice.shape[i] = 1 # <<<<<<<<<<<<<< + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 + */ + (__pyx_v_slice->shape[__pyx_v_i]) = 1; + + /* "View.MemoryView":1314 + * for i in range(offset): + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] # <<<<<<<<<<<<<< + * slice.suboffsets[i] = -1 + * + */ + (__pyx_v_slice->strides[__pyx_v_i]) = (__pyx_v_slice->strides[0]); + + /* "View.MemoryView":1315 + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_slice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1301 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1323 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { + int __pyx_t_1; + + /* "View.MemoryView":1327 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + __pyx_t_1 = (__pyx_v_dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1328 + * + * if dtype_is_object: + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< + * dst.strides, ndim, inc) + * + */ + __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1323 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + + /* function exit code */ +} + +/* "View.MemoryView":1332 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + __Pyx_RefNannyDeclarations + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); + + /* "View.MemoryView":1335 + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); + + /* "View.MemoryView":1332 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif +} + +/* "View.MemoryView":1338 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + +static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); + + /* "View.MemoryView":1342 + * cdef Py_ssize_t i + * + * for i in range(shape[0]): # <<<<<<<<<<<<<< + * if ndim == 1: + * if inc: + */ + __pyx_t_1 = (__pyx_v_shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1343 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1344 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + __pyx_t_3 = (__pyx_v_inc != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1345 + * if ndim == 1: + * if inc: + * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * Py_DECREF(( data)[0]) + */ + Py_INCREF((((PyObject **)__pyx_v_data)[0])); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":1347 + * Py_INCREF(( data)[0]) + * else: + * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + */ + Py_DECREF((((PyObject **)__pyx_v_data)[0])); + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1349 + * Py_DECREF(( data)[0]) + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, inc) + * + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); + } + __pyx_L5:; + + /* "View.MemoryView":1352 + * ndim - 1, inc) + * + * data += strides[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); + } + + /* "View.MemoryView":1338 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1358 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { + + /* "View.MemoryView":1361 + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1362 + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1364 + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1358 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1368 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + +static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_extent; + int __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + + /* "View.MemoryView":1372 + * size_t itemsize, void *item) nogil: + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t extent = shape[0] + * + */ + __pyx_v_stride = (__pyx_v_strides[0]); + + /* "View.MemoryView":1373 + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] + * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_extent = (__pyx_v_shape[0]); + + /* "View.MemoryView":1375 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1376 + * + * if ndim == 1: + * for i in range(extent): # <<<<<<<<<<<<<< + * memcpy(data, item, itemsize) + * data += stride + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1377 + * if ndim == 1: + * for i in range(extent): + * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< + * data += stride + * else: + */ + memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); + + /* "View.MemoryView":1378 + * for i in range(extent): + * memcpy(data, item, itemsize) + * data += stride # <<<<<<<<<<<<<< + * else: + * for i in range(extent): + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1380 + * data += stride + * else: + * for i in range(extent): # <<<<<<<<<<<<<< + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1381 + * else: + * for i in range(extent): + * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, itemsize, item) + * data += stride + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1383 + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + * data += stride # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1368 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + + /* function exit code */ +} + +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_array_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_array_obj *)o); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_array___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->mode); + Py_CLEAR(p->_format); + (*Py_TYPE(o)->tp_free)(o); +} +static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_array___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { + PyObject *v = PyObject_GenericGetAttr(o, n); + if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + v = __pyx_array___getattr__(o, n); + } + return v; +} + +static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { + return get_memview(o); +} + +static PyMethodDef __pyx_methods_array[] = { + {__Pyx_NAMESTR("__getattr__"), (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_array[] = { + {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_array = { + 0, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_array, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_array = { + 0, /*mp_length*/ + __pyx_array___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_array = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_array_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_array = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.metrics.pairwise_fast.array"), /*tp_name*/ + sizeof(struct __pyx_array_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_array, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + __pyx_tp_getattro_array, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_array, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_array, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_array, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_MemviewEnum_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_MemviewEnum_obj *)o); + p->name = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->name); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + if (p->name) { + e = (*v)(p->name, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_Enum(PyObject *o) { + PyObject* tmp; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + tmp = ((PyObject*)p->name); + p->name = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_Enum[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_MemviewEnum = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.metrics.pairwise_fast.Enum"), /*tp_name*/ + sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_Enum, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_MemviewEnum___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_Enum, /*tp_traverse*/ + __pyx_tp_clear_Enum, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_Enum, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_MemviewEnum___init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_Enum, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; + +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryview_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryview_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_memoryview; + p->obj = Py_None; Py_INCREF(Py_None); + p->_size = Py_None; Py_INCREF(Py_None); + p->_array_interface = Py_None; Py_INCREF(Py_None); + p->view.obj = NULL; + if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryview___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->obj); + Py_CLEAR(p->_size); + Py_CLEAR(p->_array_interface); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + if (p->obj) { + e = (*v)(p->obj, a); if (e) return e; + } + if (p->_size) { + e = (*v)(p->_size, a); if (e) return e; + } + if (p->_array_interface) { + e = (*v)(p->_array_interface, a); if (e) return e; + } + if (p->view.obj) { + e = (*v)(p->view.obj, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_memoryview(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + tmp = ((PyObject*)p->obj); + p->obj = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_size); + p->_size = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_array_interface); + p->_array_interface = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + Py_CLEAR(p->view.obj); + return 0; +} +static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_memoryview___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_transpose(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview__get__base(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_shape(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_strides(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_suboffsets(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_ndim(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_itemsize(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_nbytes(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_size(o); +} + +static PyMethodDef __pyx_methods_memoryview[] = { + {__Pyx_NAMESTR("is_c_contig"), (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("is_f_contig"), (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy"), (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy_fortran"), (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_memoryview[] = { + {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, + {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, + {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, + {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, + {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, + {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, + {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, + {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_memoryview = { + __pyx_memoryview___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_memoryview, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_memoryview = { + __pyx_memoryview___len__, /*mp_length*/ + __pyx_memoryview___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_memoryview = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_memoryview_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_memoryview = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.metrics.pairwise_fast.memoryview"), /*tp_name*/ + sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_memoryview___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_memoryview___str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_memoryview, /*tp_traverse*/ + __pyx_tp_clear_memoryview, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_memoryview, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_memoryview, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_memoryview, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; + +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryviewslice_obj *p; + PyObject *o = __pyx_tp_new_memoryview(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryviewslice_obj *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; + p->from_object = Py_None; Py_INCREF(Py_None); + p->from_slice.memview = NULL; + return o; +} + +static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryviewslice___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->from_object); + PyObject_GC_Track(o); + __pyx_tp_dealloc_memoryview(o); +} + +static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; + if (p->from_object) { + e = (*v)(p->from_object, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear__memoryviewslice(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + __pyx_tp_clear_memoryview(o); + tmp = ((PyObject*)p->from_object); + p->from_object = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + __PYX_XDEC_MEMVIEW(&p->from_slice, 1); + return 0; +} + +static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryviewslice__get__base(o); +} + +static PyMethodDef __pyx_methods__memoryviewslice[] = { + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { + {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_memoryviewslice = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.metrics.pairwise_fast._memoryviewslice"), /*tp_name*/ + sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___repr__, /*tp_repr*/ + #else + 0, /*tp_repr*/ + #endif + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___str__, /*tp_str*/ + #else + 0, /*tp_str*/ + #endif + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Internal class for passing memoryview slices to Python"), /*tp_doc*/ + __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ + __pyx_tp_clear__memoryviewslice, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods__memoryviewslice, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets__memoryviewslice, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new__memoryviewslice, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + __Pyx_NAMESTR("pairwise_fast"), + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_n_s_ASCII, __pyx_k_ASCII, sizeof(__pyx_k_ASCII), 0, 0, 1, 1}, + {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, + {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, + {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, + {&__pyx_n_s_D, __pyx_k_D, sizeof(__pyx_k_D), 0, 0, 1, 1}, + {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, + {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, + {&__pyx_kp_s_Expected_at_least_d_arguments, __pyx_k_Expected_at_least_d_arguments, sizeof(__pyx_k_Expected_at_least_d_arguments), 0, 0, 1, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_kp_s_Function_call_with_ambiguous_arg, __pyx_k_Function_call_with_ambiguous_arg, sizeof(__pyx_k_Function_call_with_ambiguous_arg), 0, 0, 1, 0}, + {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, + {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, + {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, + {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, + {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, + {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, + {&__pyx_kp_s_No_matching_signature_found, __pyx_k_No_matching_signature_found, sizeof(__pyx_k_No_matching_signature_found), 0, 0, 1, 0}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, + {&__pyx_n_s_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 1, 1}, + {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, + {&__pyx_kp_u_Pairwise_L1_distances_for_CSR_ma, __pyx_k_Pairwise_L1_distances_for_CSR_ma, sizeof(__pyx_k_Pairwise_L1_distances_for_CSR_ma), 0, 1, 0, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, + {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_n_s_X_data, __pyx_k_X_data, sizeof(__pyx_k_X_data), 0, 0, 1, 1}, + {&__pyx_n_s_X_indices, __pyx_k_X_indices, sizeof(__pyx_k_X_indices), 0, 0, 1, 1}, + {&__pyx_n_s_X_indptr, __pyx_k_X_indptr, sizeof(__pyx_k_X_indptr), 0, 0, 1, 1}, + {&__pyx_n_s_Y, __pyx_k_Y, sizeof(__pyx_k_Y), 0, 0, 1, 1}, + {&__pyx_n_s_Y_data, __pyx_k_Y_data, sizeof(__pyx_k_Y_data), 0, 0, 1, 1}, + {&__pyx_n_s_Y_indices, __pyx_k_Y_indices, sizeof(__pyx_k_Y_indices), 0, 0, 1, 1}, + {&__pyx_n_s_Y_indptr, __pyx_k_Y_indptr, sizeof(__pyx_k_Y_indptr), 0, 0, 1, 1}, + {&__pyx_kp_s__2, __pyx_k__2, sizeof(__pyx_k__2), 0, 0, 1, 0}, + {&__pyx_kp_s__4, __pyx_k__4, sizeof(__pyx_k__4), 0, 0, 1, 0}, + {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, + {&__pyx_n_s_args, __pyx_k_args, sizeof(__pyx_k_args), 0, 0, 1, 1}, + {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, + {&__pyx_n_b_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 0, 1}, + {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, + {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, + {&__pyx_n_s_chi2_kernel_fast, __pyx_k_chi2_kernel_fast, sizeof(__pyx_k_chi2_kernel_fast), 0, 0, 1, 1}, + {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, + {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_decode, __pyx_k_decode, sizeof(__pyx_k_decode), 0, 0, 1, 1}, + {&__pyx_n_s_defaults, __pyx_k_defaults, sizeof(__pyx_k_defaults), 0, 0, 1, 1}, + {&__pyx_n_s_denom, __pyx_k_denom, sizeof(__pyx_k_denom), 0, 0, 1, 1}, + {&__pyx_kp_s_double_1, __pyx_k_double_1, sizeof(__pyx_k_double_1), 0, 0, 1, 0}, + {&__pyx_n_s_double_array_2d_t, __pyx_k_double_array_2d_t, sizeof(__pyx_k_double_array_2d_t), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, + {&__pyx_n_s_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 0, 0, 1, 1}, + {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, + {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, + {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, + {&__pyx_n_s_f, __pyx_k_f, sizeof(__pyx_k_f), 0, 0, 1, 1}, + {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, + {&__pyx_kp_s_float_1, __pyx_k_float_1, sizeof(__pyx_k_float_1), 0, 0, 1, 0}, + {&__pyx_n_s_float_array_2d_t, __pyx_k_float_array_2d_t, sizeof(__pyx_k_float_array_2d_t), 0, 0, 1, 1}, + {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, + {&__pyx_n_b_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 0, 1}, + {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, + {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, + {&__pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_k_home_larsb_src_scikit_learn_skl, sizeof(__pyx_k_home_larsb_src_scikit_learn_skl), 0, 0, 1, 0}, + {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, + {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, + {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, + {&__pyx_n_s_ix, __pyx_k_ix, sizeof(__pyx_k_ix), 0, 0, 1, 1}, + {&__pyx_n_s_iy, __pyx_k_iy, sizeof(__pyx_k_iy), 0, 0, 1, 1}, + {&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, + {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1}, + {&__pyx_n_s_kind, __pyx_k_kind, sizeof(__pyx_k_kind), 0, 0, 1, 1}, + {&__pyx_n_s_kwargs, __pyx_k_kwargs, sizeof(__pyx_k_kwargs), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, + {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, + {&__pyx_n_s_n_features, __pyx_k_n_features, sizeof(__pyx_k_n_features), 0, 0, 1, 1}, + {&__pyx_n_s_n_samples_X, __pyx_k_n_samples_X, sizeof(__pyx_k_n_samples_X), 0, 0, 1, 1}, + {&__pyx_n_s_n_samples_Y, __pyx_k_n_samples_Y, sizeof(__pyx_k_n_samples_Y), 0, 0, 1, 1}, + {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, + {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, + {&__pyx_n_s_ndarray, __pyx_k_ndarray, sizeof(__pyx_k_ndarray), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, + {&__pyx_n_s_nom, __pyx_k_nom, sizeof(__pyx_k_nom), 0, 0, 1, 1}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, + {&__pyx_n_s_ord, __pyx_k_ord, sizeof(__pyx_k_ord), 0, 0, 1, 1}, + {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_releasebuffer, __pyx_k_pyx_releasebuffer, sizeof(__pyx_k_pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_res, __pyx_k_res, sizeof(__pyx_k_res), 0, 0, 1, 1}, + {&__pyx_n_s_result, __pyx_k_result, sizeof(__pyx_k_result), 0, 0, 1, 1}, + {&__pyx_n_s_row, __pyx_k_row, sizeof(__pyx_k_row), 0, 0, 1, 1}, + {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, + {&__pyx_n_s_signatures, __pyx_k_signatures, sizeof(__pyx_k_signatures), 0, 0, 1, 1}, + {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_metrics_pairwise_fast, __pyx_k_sklearn_metrics_pairwise_fast, sizeof(__pyx_k_sklearn_metrics_pairwise_fast), 0, 0, 1, 1}, + {&__pyx_n_s_sparse_manhattan, __pyx_k_sparse_manhattan, sizeof(__pyx_k_sparse_manhattan), 0, 0, 1, 1}, + {&__pyx_kp_u_sparse_manhattan_line_53, __pyx_k_sparse_manhattan_line_53, sizeof(__pyx_k_sparse_manhattan_line_53), 0, 1, 0, 0}, + {&__pyx_n_s_split, __pyx_k_split, sizeof(__pyx_k_split), 0, 0, 1, 1}, + {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, + {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, + {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, + {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_strip, __pyx_k_strip, sizeof(__pyx_k_strip), 0, 0, 1, 1}, + {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_u, __pyx_k_u, sizeof(__pyx_k_u), 0, 0, 1, 1}, + {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, + {&__pyx_kp_s_unable_to_allocate_shape_or_stri, __pyx_k_unable_to_allocate_shape_or_stri, sizeof(__pyx_k_unable_to_allocate_shape_or_stri), 0, 0, 1, 0}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, + {&__pyx_n_s_xrange, __pyx_k_xrange, sizeof(__pyx_k_xrange), 0, 0, 1, 1}, + {&__pyx_n_s_zip, __pyx_k_zip, sizeof(__pyx_k_zip), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ord = __Pyx_GetBuiltinName(__pyx_n_s_ord); if (!__pyx_builtin_ord) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_n_s_zip); if (!__pyx_builtin_zip) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 577; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "sklearn/metrics/pairwise_fast.pyx":32 + * + * + * def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<< + * floating_array_2d_t Y, + * floating_array_2d_t result): + */ + __pyx_tuple_ = PyTuple_Pack(2, __pyx_n_s_i, __pyx_n_s_u); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s__2); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s__4); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_No_matching_signature_found); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_Function_call_with_ambiguous_arg); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + + /* "sklearn/metrics/pairwise_fast.pyx":53 + * + * + * def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<< + * floating1d Y_data, int[:] Y_indices, int[:] Y_indptr, + * np.npy_intp n_features, double[:, ::1] D): + */ + __pyx_tuple__8 = PyTuple_Pack(2, __pyx_n_s_i, __pyx_n_s_u); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s__2); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s__4); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_No_matching_signature_found); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__11); + __Pyx_GIVEREF(__pyx_tuple__11); + __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_Function_call_with_ambiguous_arg); if (unlikely(!__pyx_tuple__12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__13); + __Pyx_GIVEREF(__pyx_tuple__13); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_tuple__14 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_GIVEREF(__pyx_tuple__14); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__15); + __Pyx_GIVEREF(__pyx_tuple__15); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__16); + __Pyx_GIVEREF(__pyx_tuple__16); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__17)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__17); + __Pyx_GIVEREF(__pyx_tuple__17); + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__18)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__18); + __Pyx_GIVEREF(__pyx_tuple__18); + + /* "View.MemoryView":124 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if self.itemsize <= 0: + */ + __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__19)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__19); + __Pyx_GIVEREF(__pyx_tuple__19); + + /* "View.MemoryView":127 + * + * if self.itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * encode = getattr(format, 'encode', None) + */ + __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__20)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__20); + __Pyx_GIVEREF(__pyx_tuple__20); + + /* "View.MemoryView":131 + * encode = getattr(format, 'encode', None) + * if encode: + * format = encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format + * self.format = self._format + */ + __pyx_tuple__21 = PyTuple_Pack(1, __pyx_n_s_ASCII); if (unlikely(!__pyx_tuple__21)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__21); + __Pyx_GIVEREF(__pyx_tuple__21); + + /* "View.MemoryView":141 + * free(self._shape) + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__22 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_or_stri); if (unlikely(!__pyx_tuple__22)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__22); + __Pyx_GIVEREF(__pyx_tuple__22); + + /* "View.MemoryView":166 + * decode = getattr(mode, 'decode', None) + * if decode: + * mode = decode('ASCII') # <<<<<<<<<<<<<< + * self.mode = mode + * + */ + __pyx_tuple__23 = PyTuple_Pack(1, __pyx_n_s_ASCII); if (unlikely(!__pyx_tuple__23)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__23); + __Pyx_GIVEREF(__pyx_tuple__23); + + /* "View.MemoryView":174 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_tuple__24 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__24)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__24); + __Pyx_GIVEREF(__pyx_tuple__24); + + /* "View.MemoryView":190 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_tuple__25 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__25)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__25); + __Pyx_GIVEREF(__pyx_tuple__25); + + /* "View.MemoryView":453 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_tuple__26 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__26)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__26); + __Pyx_GIVEREF(__pyx_tuple__26); + + /* "View.MemoryView":529 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_tuple__27 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__27)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__27); + __Pyx_GIVEREF(__pyx_tuple__27); + + /* "View.MemoryView":646 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_tuple__28 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__28)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__28); + __Pyx_GIVEREF(__pyx_tuple__28); + + /* "View.MemoryView":649 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_tuple__29 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__29)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__29); + __Pyx_GIVEREF(__pyx_tuple__29); + + /* "View.MemoryView":660 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_tuple__30 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__30)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__30); + __Pyx_GIVEREF(__pyx_tuple__30); + + /* "View.MemoryView":668 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__31 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__31)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__31); + __Pyx_GIVEREF(__pyx_tuple__31); + + /* "sklearn/metrics/pairwise_fast.pyx":32 + * + * + * def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<< + * floating_array_2d_t Y, + * floating_array_2d_t result): + */ + __pyx_tuple__32 = PyTuple_Pack(12, __pyx_n_s_X, __pyx_n_s_Y, __pyx_n_s_result, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_n_samples_X, __pyx_n_s_n_samples_Y, __pyx_n_s_n_features, __pyx_n_s_res, __pyx_n_s_nom, __pyx_n_s_denom); if (unlikely(!__pyx_tuple__32)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__32); + __Pyx_GIVEREF(__pyx_tuple__32); + __pyx_codeobj__33 = (PyObject*)__Pyx_PyCode_New(3, 0, 12, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__32, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_chi2_kernel_fast, 32, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__33)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/metrics/pairwise_fast.pyx":53 + * + * + * def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<< + * floating1d Y_data, int[:] Y_indices, int[:] Y_indptr, + * np.npy_intp n_features, double[:, ::1] D): + */ + __pyx_tuple__34 = PyTuple_Pack(12, __pyx_n_s_X_data, __pyx_n_s_X_indices, __pyx_n_s_X_indptr, __pyx_n_s_Y_data, __pyx_n_s_Y_indices, __pyx_n_s_Y_indptr, __pyx_n_s_n_features, __pyx_n_s_D, __pyx_n_s_row, __pyx_n_s_ix, __pyx_n_s_iy, __pyx_n_s_j); if (unlikely(!__pyx_tuple__34)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__34); + __Pyx_GIVEREF(__pyx_tuple__34); + __pyx_codeobj__35 = (PyObject*)__Pyx_PyCode_New(8, 0, 12, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__34, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_sparse_manhattan, 53, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__35)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":282 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_tuple__36 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__36)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__36); + __Pyx_GIVEREF(__pyx_tuple__36); + + /* "View.MemoryView":283 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_tuple__37 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__37)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__37); + __Pyx_GIVEREF(__pyx_tuple__37); + + /* "View.MemoryView":284 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__38 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__38)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__38); + __Pyx_GIVEREF(__pyx_tuple__38); + + /* "View.MemoryView":287 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_tuple__39 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__39)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__39); + __Pyx_GIVEREF(__pyx_tuple__39); + + /* "View.MemoryView":288 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__40 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__40)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__40); + __Pyx_GIVEREF(__pyx_tuple__40); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_105 = PyInt_FromLong(105); if (unlikely(!__pyx_int_105)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC initpairwise_fast(void); /*proto*/ +PyMODINIT_FUNC initpairwise_fast(void) +#else +PyMODINIT_FUNC PyInit_pairwise_fast(void); /*proto*/ +PyMODINIT_FUNC PyInit_pairwise_fast(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_pairwise_fast(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("pairwise_fast"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__metrics__pairwise_fast) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.metrics.pairwise_fast")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.metrics.pairwise_fast", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + generic = Py_None; Py_INCREF(Py_None); + strided = Py_None; Py_INCREF(Py_None); + indirect = Py_None; Py_INCREF(Py_None); + contiguous = Py_None; Py_INCREF(Py_None); + indirect_contiguous = Py_None; Py_INCREF(Py_None); + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_array.tp_print = 0; + __pyx_array_type = &__pyx_type___pyx_array; + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_MemviewEnum.tp_print = 0; + __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; + __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; + __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; + __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; + __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; + __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; + __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; + __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; + __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; + if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_memoryview.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryview_type = &__pyx_type___pyx_memoryview; + __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; + __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; + __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; + __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; + __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 930; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_memoryviewslice.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 930; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/metrics/pairwise_fast.pyx":11 + * + * from libc.string cimport memset + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/metrics/pairwise_fast.pyx":29 + * + * + * np.import_array() # <<<<<<<<<<<<<< + * + * + */ + import_array(); + + /* "sklearn/metrics/pairwise_fast.pyx":32 + * + * + * def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<< + * floating_array_2d_t Y, + * floating_array_2d_t result): + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_0__pyx_mdef_7sklearn_7metrics_13pairwise_fast_5_chi2_kernel_fast, 0, __pyx_n_s_chi2_kernel_fast, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_float_array_2d_t, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_1__pyx_mdef_7sklearn_7metrics_13pairwise_fast_7_chi2_kernel_fast, 0, __pyx_n_s_chi2_kernel_fast, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_double_array_2d_t, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_mdef_7sklearn_7metrics_13pairwise_fast_1_chi2_kernel_fast, 0, __pyx_n_s_chi2_kernel_fast, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); + ((__pyx_FusedFunctionObject *) __pyx_t_2)->__signatures__ = __pyx_t_1; + __Pyx_GIVEREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_chi2_kernel_fast, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/metrics/pairwise_fast.pyx":53 + * + * + * def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<< + * floating1d Y_data, int[:] Y_indices, int[:] Y_indptr, + * np.npy_intp n_features, double[:, ::1] D): + */ + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_0__pyx_mdef_7sklearn_7metrics_13pairwise_fast_11_sparse_manhattan, 0, __pyx_n_s_sparse_manhattan, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple); + if (PyDict_SetItem(__pyx_t_3, __pyx_kp_s_float_1, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_1__pyx_mdef_7sklearn_7metrics_13pairwise_fast_13_sparse_manhattan, 0, __pyx_n_s_sparse_manhattan, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple); + if (PyDict_SetItem(__pyx_t_3, __pyx_kp_s_double_1, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_mdef_7sklearn_7metrics_13pairwise_fast_3_sparse_manhattan, 0, __pyx_n_s_sparse_manhattan, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple); + ((__pyx_FusedFunctionObject *) __pyx_t_4)->__signatures__ = __pyx_t_3; + __Pyx_GIVEREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_sparse_manhattan, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "sklearn/metrics/pairwise_fast.pyx":1 + * #cython: boundscheck=False # <<<<<<<<<<<<<< + * #cython: cdivision=True + * #cython: wraparound=False + */ + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_5, __pyx_kp_u_sparse_manhattan_line_53, __pyx_kp_u_Pairwise_L1_distances_for_CSR_ma) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":207 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * def __dealloc__(array self): + */ + __pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + PyType_Modified(__pyx_array_type); + + /* "View.MemoryView":282 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__36, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_XGOTREF(generic); + __Pyx_DECREF_SET(generic, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":283 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__37, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_XGOTREF(strided); + __Pyx_DECREF_SET(strided, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":284 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__38, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_XGOTREF(indirect); + __Pyx_DECREF_SET(indirect, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":287 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__39, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_XGOTREF(contiguous); + __Pyx_DECREF_SET(contiguous, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":288 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__40, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_XGOTREF(indirect_contiguous); + __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":504 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 504; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 504; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + PyType_Modified(__pyx_memoryview_type); + + /* "View.MemoryView":961 + * return self.from_object + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 961; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 961; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + PyType_Modified(__pyx_memoryviewslice_type); + + /* "__pyxutil":2 + * + * cdef extern from *: # <<<<<<<<<<<<<< + * void __pyx_PyErr_Clear "PyErr_Clear" () + * __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_float(object) + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.metrics.pairwise_fast", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.metrics.pairwise_fast"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +#else + PyErr_GetExcInfo(type, value, tb); +#endif +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(type, value, tb); +#endif +} + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } + #endif + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; +#endif + result = (*call)(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + Py_LeaveRecursiveCall(); +#endif + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { + #endif +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); + } +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + #if CYTHON_PEP393_ENABLED + if (unlikely(PyUnicode_READY(s1) < 0) || unlikely(PyUnicode_READY(s2) < 0)) + return -1; + #endif + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, length * kind); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif +} + +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { + int r; + if (!j) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { + PyObject* old = PyList_GET_ITEM(o, n); + Py_INCREF(v); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 1; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return -1; + } + } + return m->sq_ass_item(o, i, v); + } + } +#else +#if CYTHON_COMPILING_IN_PYPY + if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) { +#else + if (is_list || PySequence_Check(o)) { +#endif + return PySequence_SetItem(o, i, v); + } +#endif + return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); +} + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; /* Consume from buffer string */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; /* not a 'break' in the loop */ + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case 10: + case 13: + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } /* fall through */ + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 's': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + } else { + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + } + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (!buf) { + PyErr_SetString(PyExc_ValueError, + "buf is NULL."); + goto fail; + } else if (memviewslice->memview || memviewslice->data) { + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); + } + retval = 0; + goto no_fail; +fail: + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} +static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { + va_list vargs; + char msg[200]; + va_start(vargs, fmt); +#ifdef HAVE_STDARG_PROTOTYPES + va_start(vargs, fmt); +#else + va_start(vargs); +#endif + vsnprintf(msg, 200, fmt, vargs); + Py_FatalError(msg); + va_end(vargs); +} +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) +{ + int first_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview || (PyObject *) memview == Py_None) + return; /* allow uninitialized memoryview assignment */ + if (__pyx_get_slice_count(memview) < 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + first_time = __pyx_add_acquisition_count(memview) == 0; + if (first_time) { + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); + } + } +} +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, + int have_gil, int lineno) { + int last_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview ) { + return; + } else if ((PyObject *) memview == Py_None) { + memslice->memview = NULL; + return; + } + if (__pyx_get_slice_count(memview) <= 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; + if (last_time) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } + } else { + memslice->memview = NULL; + } +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(PyObject_TypeCheck(obj, type))) return 1; + } + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); + return 0; +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +#if CYTHON_COMPILING_IN_CPYTHON +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) +#else + if (likely(PyString_Check(n))) +#endif + return __Pyx_PyObject_GetAttrStr(o, n); +#endif + return PyObject_GetAttr(o, n); +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r = __Pyx_GetAttr(o, n); + if (unlikely(!r)) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + goto bad; + PyErr_Clear(); + r = d; + Py_INCREF(d); + } + return r; +bad: + return NULL; +} + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + length = strlen(cstring); + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, + int full_traceback) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + if (full_traceback) { + Py_XINCREF(old_exc); + Py_XINCREF(old_val); + Py_XINCREF(old_tb); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + PyErr_PrintEx(1); + } + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { + PyObject* fake_module; + PyTypeObject* cached_type = NULL; + fake_module = PyImport_AddModule((char*) "_cython_" CYTHON_ABI); + if (!fake_module) return NULL; + Py_INCREF(fake_module); + cached_type = (PyTypeObject*) PyObject_GetAttrString(fake_module, type->tp_name); + if (cached_type) { + if (!PyType_Check((PyObject*)cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", + type->tp_name); + goto bad; + } + if (cached_type->tp_basicsize != type->tp_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + type->tp_name); + goto bad; + } + } else { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; + PyErr_Clear(); + if (PyType_Ready(type) < 0) goto bad; + if (PyObject_SetAttrString(fake_module, type->tp_name, (PyObject*) type) < 0) + goto bad; + Py_INCREF(type); + cached_type = type; + } +done: + Py_DECREF(fake_module); + return cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} + +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *closure) +{ + if (unlikely(op->func_doc == NULL)) { + if (op->func.m_ml->ml_doc) { +#if PY_MAJOR_VERSION >= 3 + op->func_doc = PyUnicode_FromString(op->func.m_ml->ml_doc); +#else + op->func_doc = PyString_FromString(op->func.m_ml->ml_doc); +#endif + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static int +__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value) +{ + PyObject *tmp = op->func_doc; + if (value == NULL) + value = Py_None; /* Mark as deleted */ + Py_INCREF(value); + op->func_doc = value; + Py_XDECREF(tmp); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_name == NULL)) { +#if PY_MAJOR_VERSION >= 3 + op->func_name = PyUnicode_InternFromString(op->func.m_ml->ml_name); +#else + op->func_name = PyString_InternFromString(op->func.m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static int +__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value) +{ + PyObject *tmp; +#if PY_MAJOR_VERSION >= 3 + if (unlikely(value == NULL || !PyUnicode_Check(value))) { +#else + if (unlikely(value == NULL || !PyString_Check(value))) { +#endif + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + tmp = op->func_name; + Py_INCREF(value); + op->func_name = value; + Py_XDECREF(tmp); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op) +{ + Py_INCREF(op->func_qualname); + return op->func_qualname; +} +static int +__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value) +{ + PyObject *tmp; +#if PY_MAJOR_VERSION >= 3 + if (unlikely(value == NULL || !PyUnicode_Check(value))) { +#else + if (unlikely(value == NULL || !PyString_Check(value))) { +#endif + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + tmp = op->func_qualname; + Py_INCREF(value); + op->func_qualname = value; + Py_XDECREF(tmp); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_self(__pyx_CyFunctionObject *m, CYTHON_UNUSED void *closure) +{ + PyObject *self; + self = m->func_closure; + if (self == NULL) + self = Py_None; + Py_INCREF(self); + return self; +} +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +static int +__Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value) +{ + PyObject *tmp; + if (unlikely(value == NULL)) { + PyErr_SetString(PyExc_TypeError, + "function's dictionary may not be deleted"); + return -1; + } + if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "setting function's dictionary to a non-dict"); + return -1; + } + tmp = op->func_dict; + Py_INCREF(value); + op->func_dict = value; + Py_XDECREF(tmp); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op) +{ + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(CYTHON_UNUSED __pyx_CyFunctionObject *op) +{ + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op) +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + Py_DECREF(res); + return 0; +} +static int +__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value) { + PyObject* tmp; + if (!value) { + value = Py_None; + } else if (value != Py_None && !PyTuple_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + Py_INCREF(value); + tmp = op->defaults_tuple; + op->defaults_tuple = value; + Py_XDECREF(tmp); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_tuple; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value) { + PyObject* tmp; + if (!value) { + value = Py_None; + } else if (value != Py_None && !PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + Py_INCREF(value); + tmp = op->defaults_kwdict; + op->defaults_kwdict = value; + Py_XDECREF(tmp); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_kwdict; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value) { + PyObject* tmp; + if (!value || value == Py_None) { + value = NULL; + } else if (!PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + tmp = op->func_annotations; + op->func_annotations = value; + Py_XDECREF(tmp); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op) { + PyObject* result = op->func_annotations; + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {(char *) "func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {(char *) "__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {(char *) "func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {(char *) "__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {(char *) "__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, + {(char *) "__self__", (getter)__Pyx_CyFunction_get_self, 0, 0, 0}, + {(char *) "func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {(char *) "__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {(char *) "func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {(char *) "__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {(char *) "func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {(char *) "__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {(char *) "func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {(char *) "__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {(char *) "func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {(char *) "__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {(char *) "__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {0, 0, 0, 0, 0} +}; +#ifndef PY_WRITE_RESTRICTED /* < Py2.5 */ +#define PY_WRITE_RESTRICTED WRITE_RESTRICTED +#endif +static PyMemberDef __pyx_CyFunction_members[] = { + {(char *) "__module__", T_OBJECT, offsetof(__pyx_CyFunctionObject, func.m_module), PY_WRITE_RESTRICTED, 0}, + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, CYTHON_UNUSED PyObject *args) +{ +#if PY_MAJOR_VERSION >= 3 + return PyUnicode_FromString(m->func.m_ml->ml_name); +#else + return PyString_FromString(m->func.m_ml->ml_name); +#endif +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; +static PyObject *__Pyx_CyFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + __pyx_CyFunctionObject *op = PyObject_GC_New(__pyx_CyFunctionObject, type); + if (op == NULL) + return NULL; + op->flags = flags; + op->func_weakreflist = NULL; + op->func.m_ml = ml; + op->func.m_self = (PyObject *) op; + Py_XINCREF(closure); + op->func_closure = closure; + Py_XINCREF(module); + op->func.m_module = module; + op->func_dict = NULL; + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; + op->func_classobj = NULL; + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults_pyobjects = 0; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + PyObject_GC_Track(op); + return (PyObject *) op; +} +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); + Py_CLEAR(m->func.m_module); + Py_CLEAR(m->func_dict); + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); + Py_CLEAR(m->func_classobj); + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + if (m->defaults) { + PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + int i; + for (i = 0; i < m->defaults_pyobjects; i++) + Py_XDECREF(pydefaults[i]); + PyMem_Free(m->defaults); + m->defaults = NULL; + } + return 0; +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + if (m->func_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + PyObject_GC_Del(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + Py_VISIT(m->func_closure); + Py_VISIT(m->func.m_module); + Py_VISIT(m->func_dict); + Py_VISIT(m->func_name); + Py_VISIT(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + Py_VISIT(m->func_code); + Py_VISIT(m->func_classobj); + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + if (m->defaults) { + PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + int i; + for (i = 0; i < m->defaults_pyobjects; i++) + Py_VISIT(pydefaults[i]); + } + return 0; +} +static PyObject *__Pyx_CyFunction_descr_get(PyObject *func, PyObject *obj, PyObject *type) +{ + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + if (m->flags & __Pyx_CYFUNCTION_STATICMETHOD) { + Py_INCREF(func); + return func; + } + if (m->flags & __Pyx_CYFUNCTION_CLASSMETHOD) { + if (type == NULL) + type = (PyObject *)(Py_TYPE(obj)); + return PyMethod_New(func, + type, (PyObject *)(Py_TYPE(type))); + } + if (obj == Py_None) + obj = NULL; + return PyMethod_New(func, obj, type); +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ +#if PY_MAJOR_VERSION >= 3 + return PyUnicode_FromFormat("", + op->func_qualname, (void *)op); +#else + return PyString_FromFormat("", + PyString_AsString(op->func_qualname), (void *)op); +#endif +} +#if CYTHON_COMPILING_IN_PYPY +static PyObject * __Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = PyCFunction_GET_FUNCTION(func); + PyObject *self = PyCFunction_GET_SELF(func); + Py_ssize_t size; + switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) { + case METH_VARARGS: + if (likely(kw == NULL) || PyDict_Size(kw) == 0) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL) || PyDict_Size(kw) == 0) { + size = PyTuple_GET_SIZE(arg); + if (size == 0) + return (*meth)(self, NULL); + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%zd given)", + f->m_ml->ml_name, size); + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL) || PyDict_Size(kw) == 0) { + size = PyTuple_GET_SIZE(arg); + if (size == 1) + return (*meth)(self, PyTuple_GET_ITEM(arg, 0)); + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%zd given)", + f->m_ml->ml_name, size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags in " + "__Pyx_CyFunction_Call. METH_OLDARGS is no " + "longer supported!"); + return NULL; + } + PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", + f->m_ml->ml_name); + return NULL; +} +#else +static PyObject * __Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + return PyCFunction_Call(func, arg, kw); +} +#endif +static PyTypeObject __pyx_CyFunctionType_type = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("cython_function_or_method"), /*tp_name*/ + sizeof(__pyx_CyFunctionObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor) __Pyx_CyFunction_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ +#if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ +#else + 0, /*reserved*/ +#endif + (reprfunc) __Pyx_CyFunction_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + __Pyx_CyFunction_Call, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags*/ + 0, /*tp_doc*/ + (traverseproc) __Pyx_CyFunction_traverse, /*tp_traverse*/ + (inquiry) __Pyx_CyFunction_clear, /*tp_clear*/ + 0, /*tp_richcompare*/ + offsetof(__pyx_CyFunctionObject, func_weakreflist), /* tp_weaklistoffse */ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_CyFunction_methods, /*tp_methods*/ + __pyx_CyFunction_members, /*tp_members*/ + __pyx_CyFunction_getsets, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + __Pyx_CyFunction_descr_get, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + offsetof(__pyx_CyFunctionObject, func_dict),/*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ +#if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ +#endif +#if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ +#endif +}; +static int __Pyx_CyFunction_init(void) { +#if !CYTHON_COMPILING_IN_PYPY + __pyx_CyFunctionType_type.tp_call = PyCFunction_Call; +#endif + __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); + if (__pyx_CyFunctionType == NULL) { + return -1; + } + return 0; +} +static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyMem_Malloc(size); + if (!m->defaults) + return PyErr_NoMemory(); + memset(m->defaults, 0, size); + m->defaults_pyobjects = pyobjects; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +static PyObject * +__pyx_FusedFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags, + PyObject *qualname, PyObject *self, + PyObject *module, PyObject *globals, + PyObject *code) +{ + __pyx_FusedFunctionObject *fusedfunc = + (__pyx_FusedFunctionObject *) __Pyx_CyFunction_New(type, ml, flags, qualname, + self, module, globals, code); + if (!fusedfunc) + return NULL; + fusedfunc->__signatures__ = NULL; + fusedfunc->type = NULL; + fusedfunc->self = NULL; + return (PyObject *) fusedfunc; +} +static void __pyx_FusedFunction_dealloc(__pyx_FusedFunctionObject *self) { + __pyx_FusedFunction_clear(self); + __pyx_FusedFunctionType->tp_free((PyObject *) self); +} +static int +__pyx_FusedFunction_traverse(__pyx_FusedFunctionObject *self, + visitproc visit, + void *arg) +{ + Py_VISIT(self->self); + Py_VISIT(self->type); + Py_VISIT(self->__signatures__); + return __Pyx_CyFunction_traverse((__pyx_CyFunctionObject *) self, visit, arg); +} +static int +__pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self) +{ + Py_CLEAR(self->self); + Py_CLEAR(self->type); + Py_CLEAR(self->__signatures__); + return __Pyx_CyFunction_clear((__pyx_CyFunctionObject *) self); +} +static PyObject * +__pyx_FusedFunction_descr_get(PyObject *self, PyObject *obj, PyObject *type) +{ + __pyx_FusedFunctionObject *func, *meth; + func = (__pyx_FusedFunctionObject *) self; + if (func->self || func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD) { + Py_INCREF(self); + return self; + } + if (obj == Py_None) + obj = NULL; + meth = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_NewEx( + ((PyCFunctionObject *) func)->m_ml, + ((__pyx_CyFunctionObject *) func)->flags, + ((__pyx_CyFunctionObject *) func)->func_qualname, + ((__pyx_CyFunctionObject *) func)->func_closure, + ((PyCFunctionObject *) func)->m_module, + ((__pyx_CyFunctionObject *) func)->func_globals, + ((__pyx_CyFunctionObject *) func)->func_code); + if (!meth) + return NULL; + Py_XINCREF(func->func.func_classobj); + meth->func.func_classobj = func->func.func_classobj; + Py_XINCREF(func->__signatures__); + meth->__signatures__ = func->__signatures__; + Py_XINCREF(type); + meth->type = type; + Py_XINCREF(func->func.defaults_tuple); + meth->func.defaults_tuple = func->func.defaults_tuple; + if (func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD) + obj = type; + Py_XINCREF(obj); + meth->self = obj; + return (PyObject *) meth; +} +static PyObject * +_obj_to_str(PyObject *obj) +{ + if (PyType_Check(obj)) + return PyObject_GetAttr(obj, __pyx_n_s_name_2); + else + return PyObject_Str(obj); +} +static PyObject * +__pyx_FusedFunction_getitem(__pyx_FusedFunctionObject *self, PyObject *idx) +{ + PyObject *signature = NULL; + PyObject *unbound_result_func; + PyObject *result_func = NULL; + if (self->__signatures__ == NULL) { + PyErr_SetString(PyExc_TypeError, "Function is not fused"); + return NULL; + } + if (PyTuple_Check(idx)) { + PyObject *list = PyList_New(0); + Py_ssize_t n = PyTuple_GET_SIZE(idx); + PyObject *string = NULL; + PyObject *sep = NULL; + int i; + if (!list) + return NULL; + for (i = 0; i < n; i++) { + PyObject *item = PyTuple_GET_ITEM(idx, i); + string = _obj_to_str(item); + if (!string || PyList_Append(list, string) < 0) + goto __pyx_err; + Py_DECREF(string); + } + sep = PyUnicode_FromString("|"); + if (sep) + signature = PyUnicode_Join(sep, list); +__pyx_err: +; + Py_DECREF(list); + Py_XDECREF(sep); + } else { + signature = _obj_to_str(idx); + } + if (!signature) + return NULL; + unbound_result_func = PyObject_GetItem(self->__signatures__, signature); + if (unbound_result_func) { + if (self->self || self->type) { + __pyx_FusedFunctionObject *unbound = (__pyx_FusedFunctionObject *) unbound_result_func; + Py_CLEAR(unbound->func.func_classobj); + Py_XINCREF(self->func.func_classobj); + unbound->func.func_classobj = self->func.func_classobj; + result_func = __pyx_FusedFunction_descr_get(unbound_result_func, + self->self, self->type); + } else { + result_func = unbound_result_func; + Py_INCREF(result_func); + } + } + Py_DECREF(signature); + Py_XDECREF(unbound_result_func); + return result_func; +} +static PyObject * +__pyx_FusedFunction_callfunction(PyObject *func, PyObject *args, PyObject *kw) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; + PyObject *result; + int static_specialized = (cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD && + !((__pyx_FusedFunctionObject *) func)->__signatures__); + if (cyfunc->flags & __Pyx_CYFUNCTION_CCLASS && !static_specialized) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; + PyObject *m_self; + argc = PyTuple_GET_SIZE(args); + new_args = PyTuple_GetSlice(args, 1, argc); + if (!new_args) + return NULL; + self = PyTuple_GetItem(args, 0); + if (!self) + return NULL; + m_self = cyfunc->func.m_self; + cyfunc->func.m_self = self; + result = __Pyx_CyFunction_Call(func, new_args, kw); + cyfunc->func.m_self = m_self; + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +/* Note: the 'self' from method binding is passed in in the args tuple, + whereas PyCFunctionObject's m_self is passed in as the first + argument to the C function. For extension methods we need + to pass 'self' as 'm_self' and not as the first element of the + args tuple. +*/ +static PyObject * +__pyx_FusedFunction_call(PyObject *func, PyObject *args, PyObject *kw) +{ + __pyx_FusedFunctionObject *binding_func = (__pyx_FusedFunctionObject *) func; + Py_ssize_t argc = PyTuple_GET_SIZE(args); + PyObject *new_args = NULL; + __pyx_FusedFunctionObject *new_func = NULL; + PyObject *result = NULL; + PyObject *self = NULL; + int is_staticmethod = binding_func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD; + int is_classmethod = binding_func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD; + if (binding_func->self) { + Py_ssize_t i; + new_args = PyTuple_New(argc + 1); + if (!new_args) + return NULL; + self = binding_func->self; + Py_INCREF(self); + PyTuple_SET_ITEM(new_args, 0, self); + for (i = 0; i < argc; i++) { + PyObject *item = PyTuple_GET_ITEM(args, i); + Py_INCREF(item); + PyTuple_SET_ITEM(new_args, i + 1, item); + } + args = new_args; + } else if (binding_func->type) { + if (argc < 1) { + PyErr_SetString(PyExc_TypeError, "Need at least one argument, 0 given."); + return NULL; + } + self = PyTuple_GET_ITEM(args, 0); + } + if (self && !is_classmethod && !is_staticmethod && + !PyObject_IsInstance(self, binding_func->type)) { + PyErr_Format(PyExc_TypeError, + "First argument should be of type %.200s, got %.200s.", + ((PyTypeObject *) binding_func->type)->tp_name, + self->ob_type->tp_name); + goto __pyx_err; + } + if (binding_func->__signatures__) { + PyObject *tup = PyTuple_Pack(4, binding_func->__signatures__, args, + kw == NULL ? Py_None : kw, + binding_func->func.defaults_tuple); + if (!tup) + goto __pyx_err; + new_func = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_callfunction(func, tup, NULL); + Py_DECREF(tup); + if (!new_func) + goto __pyx_err; + Py_XINCREF(binding_func->func.func_classobj); + Py_CLEAR(new_func->func.func_classobj); + new_func->func.func_classobj = binding_func->func.func_classobj; + func = (PyObject *) new_func; + } + result = __pyx_FusedFunction_callfunction(func, args, kw); +__pyx_err: + Py_XDECREF(new_args); + Py_XDECREF((PyObject *) new_func); + return result; +} +static PyMemberDef __pyx_FusedFunction_members[] = { + {(char *) "__signatures__", + T_OBJECT, + offsetof(__pyx_FusedFunctionObject, __signatures__), + READONLY, + __Pyx_DOCSTR(0)}, + {0, 0, 0, 0, 0}, +}; +static PyMappingMethods __pyx_FusedFunction_mapping_methods = { + 0, + (binaryfunc) __pyx_FusedFunction_getitem, + 0, +}; +static PyTypeObject __pyx_FusedFunctionType_type = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("fused_cython_function"), /*tp_name*/ + sizeof(__pyx_FusedFunctionObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor) __pyx_FusedFunction_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ +#if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ +#else + 0, /*reserved*/ +#endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + &__pyx_FusedFunction_mapping_methods, /*tp_as_mapping*/ + 0, /*tp_hash*/ + (ternaryfunc) __pyx_FusedFunction_call, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags*/ + 0, /*tp_doc*/ + (traverseproc) __pyx_FusedFunction_traverse, /*tp_traverse*/ + (inquiry) __pyx_FusedFunction_clear,/*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + __pyx_FusedFunction_members, /*tp_members*/ + __pyx_CyFunction_getsets, /*tp_getset*/ + &__pyx_CyFunctionType_type, /*tp_base*/ + 0, /*tp_dict*/ + __pyx_FusedFunction_descr_get, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ +#if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ +#endif +#if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ +#endif +}; +static int __pyx_FusedFunction_init(void) { + __pyx_FusedFunctionType = __Pyx_FetchCommonType(&__pyx_FusedFunctionType_type); + if (__pyx_FusedFunctionType == NULL) { + return -1; + } + return 0; +} + +static int +__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) +{ + int i; + if (!a || !b) + return 0; + if (a == b) + return 1; + if (a->size != b->size || a->typegroup != b->typegroup || + a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { + if (a->typegroup == 'H' || b->typegroup == 'H') { + return a->size == b->size; + } else { + return 0; + } + } + if (a->ndim) { + for (i = 0; i < a->ndim; i++) + if (a->arraysize[i] != b->arraysize[i]) + return 0; + } + if (a->typegroup == 'S') { + if (a->flags != b->flags) + return 0; + if (a->fields || b->fields) { + if (!(a->fields && b->fields)) + return 0; + for (i = 0; a->fields[i].type && b->fields[i].type; i++) { + __Pyx_StructField *field_a = a->fields + i; + __Pyx_StructField *field_b = b->fields + i; + if (field_a->offset != field_b->offset || + !__pyx_typeinfo_cmp(field_a->type, field_b->type)) + return 0; + } + return !a->fields[i].type && !b->fields[i].type; + } + } + return 1; +} + +static int +__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) +{ + if (buf->shape[dim] <= 1) + return 1; + if (buf->strides) { + if (spec & __Pyx_MEMVIEW_CONTIG) { + if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { + if (buf->strides[dim] != sizeof(void *)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly contiguous " + "in dimension %d.", dim); + goto fail; + } + } else if (buf->strides[dim] != buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_FOLLOW) { + Py_ssize_t stride = buf->strides[dim]; + if (stride < 0) + stride = -stride; + if (stride < buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + } else { + if (spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not contiguous in " + "dimension %d", dim); + goto fail; + } else if (spec & (__Pyx_MEMVIEW_PTR)) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not indirect in " + "dimension %d", dim); + goto fail; + } else if (buf->suboffsets) { + PyErr_SetString(PyExc_ValueError, + "Buffer exposes suboffsets but no strides"); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) +{ + if (spec & __Pyx_MEMVIEW_DIRECT) { + if (buf->suboffsets && buf->suboffsets[dim] >= 0) { + PyErr_Format(PyExc_ValueError, + "Buffer not compatible with direct access " + "in dimension %d.", dim); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_PTR) { + if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly accessible " + "in dimension %d.", dim); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) +{ + int i; + if (c_or_f_flag & __Pyx_IS_F_CONTIG) { + Py_ssize_t stride = 1; + for (i = 0; i < ndim; i++) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) + { + PyErr_SetString(PyExc_ValueError, + "Buffer not fortran contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { + Py_ssize_t stride = 1; + for (i = ndim - 1; i >- 1; i--) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) { + PyErr_SetString(PyExc_ValueError, + "Buffer not C contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } + return 1; +fail: + return 0; +} +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj) +{ + struct __pyx_memoryview_obj *memview, *new_memview; + __Pyx_RefNannyDeclarations + Py_buffer *buf; + int i, spec = 0, retval = -1; + __Pyx_BufFmt_Context ctx; + int from_memoryview = __pyx_memoryview_check(original_obj); + __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); + if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) + original_obj)->typeinfo)) { + memview = (struct __pyx_memoryview_obj *) original_obj; + new_memview = NULL; + } else { + memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + original_obj, buf_flags, 0, dtype); + new_memview = memview; + if (unlikely(!memview)) + goto fail; + } + buf = &memview->view; + if (buf->ndim != ndim) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + ndim, buf->ndim); + goto fail; + } + if (new_memview) { + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned) buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " + "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", + buf->itemsize, + (buf->itemsize > 1) ? "s" : "", + dtype->name, + dtype->size, + (dtype->size > 1) ? "s" : ""); + goto fail; + } + for (i = 0; i < ndim; i++) { + spec = axes_specs[i]; + if (!__pyx_check_strides(buf, i, ndim, spec)) + goto fail; + if (!__pyx_check_suboffsets(buf, i, ndim, spec)) + goto fail; + } + if (buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, + new_memview != NULL) == -1)) { + goto fail; + } + retval = 0; + goto no_fail; +fail: + Py_XDECREF(new_memview); + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_float(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS, 2, + &__Pyx_TypeInfo_float, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS, 2, + &__Pyx_TypeInfo_double, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_float(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_float, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_double(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_double, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } + } + #endif + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: + Py_DECREF(obj); + view->obj = NULL; +} +#endif /* PY_MAJOR_VERSION < 3 */ + + + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS, 1, + &__Pyx_TypeInfo_int, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \ + { \ + func_type value = func(x); \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + PyErr_SetString(PyExc_OverflowError, \ + (is_unsigned && unlikely(value < zero)) ? \ + "can't convert negative value to " #target_type : \ + "value too large to convert to " #target_type); \ + return (target_type) -1; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *x) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; + } + return (Py_intptr_t) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(Py_intptr_t)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; + } + if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(Py_intptr_t)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(Py_intptr_t) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyLong_AsLong) + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + Py_intptr_t val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (Py_intptr_t) -1; + } + } else { + Py_intptr_t val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (Py_intptr_t) -1; + val = __Pyx_PyInt_As_Py_intptr_t(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2, + &__Pyx_TypeInfo_double, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { + const char neg_one = (char) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(char) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to char"); + return (char) -1; + } + return (char) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(char)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (char) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to char"); + return (char) -1; + } + if (sizeof(char) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(char) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(char)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(char) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(char) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(char) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyLong_AsLong) + } else if (sizeof(char) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(char, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + char val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (char) -1; + } + } else { + char val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (char) -1; + val = __Pyx_PyInt_As_char(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_char(char value) { + const char neg_one = (char) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(char) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(char) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(char) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(char) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(char) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(char), + little, !is_unsigned); + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(Py_intptr_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(int) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +} + +static int +__pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim) +{ + int i, index, step, start; + Py_ssize_t itemsize = mvs->memview->view.itemsize; + if (order == 'F') { + step = 1; + start = 0; + } else { + step = -1; + start = ndim - 1; + } + for (i = 0; i < ndim; i++) { + index = start + step * i; + if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) + return 0; + itemsize *= mvs->shape[index]; + } + return 1; +} + +static void +__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + start = end = slice->data; + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + if (extent == 0) { + *out_start = *out_end = start; + return; + } else { + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); + } + } + *out_start = start; + *out_end = end + itemsize; +} +static int +__pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize) +{ + void *start1, *end1, *start2, *end2; + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + return (start1 < end2) && (start2 < end1); +} + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + for (i = 0; i < ndim; i++) { + if (from_mvs->suboffsets[i] >= 0) { + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; + } + } + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; + } + __Pyx_GOTREF(shape_tuple); + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; + } else { + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; + } + } + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + goto no_fail; +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; +} + +static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) +{ + PyObject *cobj; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); +#endif + return cobj; +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; + } + return (long) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); + Py_DECREF(tmp); + return val; + } +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + #if PY_VERSION_HEX < 0x02050000 + if (PyErr_Warn(NULL, warning) < 0) goto bad; + #else + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + #endif + } + else if ((size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ +#if !CYTHON_COMPILING_IN_PYPY +#if PY_VERSION_HEX >= 0x02060000 + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_MAJOR_VERSION < 3 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%.4s__ returned non-%.4s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + #if PY_VERSION_HEX < 0x02060000 + return PyInt_AsSsize_t(b); + #else + return PyLong_AsSsize_t(b); + #endif + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/metrics/pairwise_fast.pyx b/sklearn/metrics/pairwise_fast.pyx new file mode 100644 index 0000000000000..e5b310a30debe --- /dev/null +++ b/sklearn/metrics/pairwise_fast.pyx @@ -0,0 +1,79 @@ +#cython: boundscheck=False +#cython: cdivision=True +#cython: wraparound=False + +# Author: Andreas Mueller +# Lars Buitinck +# +# Licence: BSD 3 clause + +from libc.string cimport memset +import numpy as np +cimport numpy as np + +cdef extern from "cblas.h": + double cblas_dasum(int, const double *, int) nogil + +ctypedef float [:, :] float_array_2d_t +ctypedef double [:, :] double_array_2d_t + +cdef fused floating1d: + float[::1] + double[::1] + +cdef fused floating_array_2d_t: + float_array_2d_t + double_array_2d_t + + +np.import_array() + + +def _chi2_kernel_fast(floating_array_2d_t X, + floating_array_2d_t Y, + floating_array_2d_t result): + cdef np.npy_intp i, j, k + cdef np.npy_intp n_samples_X = X.shape[0] + cdef np.npy_intp n_samples_Y = Y.shape[0] + cdef np.npy_intp n_features = X.shape[1] + cdef double res, nom, denom + + with nogil: + for i in range(n_samples_X): + for j in range(n_samples_Y): + res = 0 + for k in range(n_features): + denom = (X[i, k] - Y[j, k]) + nom = (X[i, k] + Y[j, k]) + if nom != 0: + res += denom * denom / nom + result[i, j] = -res + + +def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, + floating1d Y_data, int[:] Y_indices, int[:] Y_indptr, + np.npy_intp n_features, double[:, ::1] D): + """Pairwise L1 distances for CSR matrices. + + Usage: + + >>> D = np.zeros(X.shape[0], Y.shape[0]) + >>> sparse_manhattan(X.data, X.indices, X.indptr, + ... Y.data, Y.indices, Y.indptr, + ... X.shape[1], D) + """ + cdef double[::1] row = np.empty(n_features) + cdef np.npy_intp ix, iy, j + + with nogil: + for ix in range(D.shape[0]): + for iy in range(D.shape[1]): + # Simple strategy: densify current row of X, then subtract the + # corresponding row of Y. + memset(&row[0], 0, n_features * sizeof(double)) + for j in range(X_indptr[ix], X_indptr[ix + 1]): + row[X_indices[j]] = X_data[j] + for j in range(Y_indptr[iy], Y_indptr[iy + 1]): + row[Y_indices[j]] -= Y_data[j] + + D[ix, iy] = cblas_dasum(n_features, &row[0], 1) diff --git a/sklearn/metrics/ranking.py b/sklearn/metrics/ranking.py new file mode 100644 index 0000000000000..ee50c8bfd74c8 --- /dev/null +++ b/sklearn/metrics/ranking.py @@ -0,0 +1,626 @@ +"""Metrics to assess performance on classification task given scores + +Functions named as ``*_score`` return a scalar value to maximize: the higher +the better + +Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: +the lower the better +""" + +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Olivier Grisel +# Arnaud Joly +# Jochen Wersdorfer +# Lars Buitinck +# Joel Nothman +# Noel Dawe +# License: BSD 3 clause + +from __future__ import division + +import warnings +import numpy as np +from scipy.sparse import csr_matrix + +from ..utils import check_consistent_length +from ..utils import column_or_1d, check_array +from ..utils.multiclass import type_of_target +from ..utils.fixes import isclose +from ..utils.stats import rankdata + +from .base import _average_binary_score +from .base import UndefinedMetricWarning + + +def auc(x, y, reorder=False): + """Compute Area Under the Curve (AUC) using the trapezoidal rule + + This is a general function, given points on a curve. For computing the + area under the ROC-curve, see :func:`roc_auc_score`. + + Parameters + ---------- + x : array, shape = [n] + x coordinates. + + y : array, shape = [n] + y coordinates. + + reorder : boolean, optional (default=False) + If True, assume that the curve is ascending in the case of ties, as for + an ROC curve. If the curve is non-ascending, the result will be wrong. + + Returns + ------- + auc : float + + Examples + -------- + >>> import numpy as np + >>> from sklearn import metrics + >>> y = np.array([1, 1, 2, 2]) + >>> pred = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=2) + >>> metrics.auc(fpr, tpr) + 0.75 + + See also + -------- + roc_auc_score : Computes the area under the ROC curve + + precision_recall_curve : + Compute precision-recall pairs for different probability thresholds + + """ + check_consistent_length(x, y) + x = column_or_1d(x) + y = column_or_1d(y) + + if x.shape[0] < 2: + raise ValueError('At least 2 points are needed to compute' + ' area under curve, but x.shape = %s' % x.shape) + + direction = 1 + if reorder: + # reorder the data points according to the x axis and using y to + # break ties + order = np.lexsort((y, x)) + x, y = x[order], y[order] + else: + dx = np.diff(x) + if np.any(dx < 0): + if np.all(dx <= 0): + direction = -1 + else: + raise ValueError("Reordering is not turned on, and " + "the x array is not increasing: %s" % x) + + area = direction * np.trapz(y, x) + + return area + + +def average_precision_score(y_true, y_score, average="macro", + sample_weight=None): + """Compute average precision (AP) from prediction scores + + This score corresponds to the area under the precision-recall curve. + + Note: this implementation is restricted to the binary classification task + or multilabel classification task. + + Parameters + ---------- + y_true : array, shape = [n_samples] or [n_samples, n_classes] + True binary labels in binary label indicators. + + y_score : array, shape = [n_samples] or [n_samples, n_classes] + Target scores, can either be probability estimates of the positive + class, confidence values, or binary decisions. + + average : string, [None, 'micro', 'macro' (default), 'samples', 'weighted'] + If ``None``, the scores for each class are returned. Otherwise, + this determines the type of averaging performed on the data: + + ``'micro'``: + Calculate metrics globally by considering each element of the label + indicator matrix as a label. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). + ``'samples'``: + Calculate metrics for each instance, and find their average. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + average_precision : float + + References + ---------- + .. [1] `Wikipedia entry for the Average precision + `_ + + See also + -------- + roc_auc_score : Area under the ROC curve + + precision_recall_curve : + Compute precision-recall pairs for different probability thresholds + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import average_precision_score + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> average_precision_score(y_true, y_scores) # doctest: +ELLIPSIS + 0.79... + + """ + def _binary_average_precision(y_true, y_score, sample_weight=None): + precision, recall, thresholds = precision_recall_curve( + y_true, y_score, sample_weight=sample_weight) + return auc(recall, precision) + + return _average_binary_score(_binary_average_precision, y_true, y_score, + average, sample_weight=sample_weight) + + +def roc_auc_score(y_true, y_score, average="macro", sample_weight=None): + """Compute Area Under the Curve (AUC) from prediction scores + + Note: this implementation is restricted to the binary classification task + or multilabel classification task in label indicator format. + + Parameters + ---------- + y_true : array, shape = [n_samples] or [n_samples, n_classes] + True binary labels in binary label indicators. + + y_score : array, shape = [n_samples] or [n_samples, n_classes] + Target scores, can either be probability estimates of the positive + class, confidence values, or binary decisions. + + average : string, [None, 'micro', 'macro' (default), 'samples', 'weighted'] + If ``None``, the scores for each class are returned. Otherwise, + this determines the type of averaging performed on the data: + + ``'micro'``: + Calculate metrics globally by considering each element of the label + indicator matrix as a label. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). + ``'samples'``: + Calculate metrics for each instance, and find their average. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + auc : float + + References + ---------- + .. [1] `Wikipedia entry for the Receiver operating characteristic + `_ + + See also + -------- + average_precision_score : Area under the precision-recall curve + + roc_curve : Compute Receiver operating characteristic (ROC) + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import roc_auc_score + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> roc_auc_score(y_true, y_scores) + 0.75 + + """ + def _binary_roc_auc_score(y_true, y_score, sample_weight=None): + if len(np.unique(y_true)) != 2: + raise ValueError("Only one class present in y_true. ROC AUC score " + "is not defined in that case.") + + fpr, tpr, tresholds = roc_curve(y_true, y_score, + sample_weight=sample_weight) + return auc(fpr, tpr, reorder=True) + + return _average_binary_score( + _binary_roc_auc_score, y_true, y_score, average, + sample_weight=sample_weight) + + +def _binary_clf_curve(y_true, y_score, pos_label=None, sample_weight=None): + """Calculate true and false positives per binary classification threshold. + + Parameters + ---------- + y_true : array, shape = [n_samples] + True targets of binary classification + + y_score : array, shape = [n_samples] + Estimated probabilities or decision function + + pos_label : int, optional (default=None) + The label of the positive class + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + fps : array, shape = [n_thresholds] + A count of false positives, at index i being the number of negative + samples assigned a score >= thresholds[i]. The total number of + negative samples is equal to fps[-1] (thus true negatives are given by + fps[-1] - fps). + + tps : array, shape = [n_thresholds := len(np.unique(y_score))] + An increasing count of true positives, at index i being the number + of positive samples assigned a score >= thresholds[i]. The total + number of positive samples is equal to tps[-1] (thus false negatives + are given by tps[-1] - tps). + + thresholds : array, shape = [n_thresholds] + Decreasing score values. + """ + check_consistent_length(y_true, y_score) + y_true = column_or_1d(y_true) + y_score = column_or_1d(y_score) + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + + # ensure binary classification if pos_label is not specified + classes = np.unique(y_true) + if (pos_label is None and + not (np.all(classes == [0, 1]) or + np.all(classes == [-1, 1]) or + np.all(classes == [0]) or + np.all(classes == [-1]) or + np.all(classes == [1]))): + raise ValueError("Data is not binary and pos_label is not specified") + elif pos_label is None: + pos_label = 1. + + # make y_true a boolean vector + y_true = (y_true == pos_label) + + # sort scores and corresponding truth values + desc_score_indices = np.argsort(y_score, kind="mergesort")[::-1] + y_score = y_score[desc_score_indices] + y_true = y_true[desc_score_indices] + if sample_weight is not None: + weight = sample_weight[desc_score_indices] + else: + weight = 1. + + # y_score typically has many tied values. Here we extract + # the indices associated with the distinct values. We also + # concatenate a value for the end of the curve. + # We need to use isclose to avoid spurious repeated thresholds + # stemming from floating point roundoff errors. + distinct_value_indices = np.where(np.logical_not(isclose( + np.diff(y_score), 0)))[0] + threshold_idxs = np.r_[distinct_value_indices, y_true.size - 1] + + # accumulate the true positives with decreasing threshold + tps = (y_true * weight).cumsum()[threshold_idxs] + if sample_weight is not None: + fps = weight.cumsum()[threshold_idxs] - tps + else: + fps = 1 + threshold_idxs - tps + return fps, tps, y_score[threshold_idxs] + + +def precision_recall_curve(y_true, probas_pred, pos_label=None, + sample_weight=None): + """Compute precision-recall pairs for different probability thresholds + + Note: this implementation is restricted to the binary classification task. + + The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of + true positives and ``fp`` the number of false positives. The precision is + intuitively the ability of the classifier not to label as positive a sample + that is negative. + + The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of + true positives and ``fn`` the number of false negatives. The recall is + intuitively the ability of the classifier to find all the positive samples. + + The last precision and recall values are 1. and 0. respectively and do not + have a corresponding threshold. This ensures that the graph starts on the + x axis. + + Parameters + ---------- + y_true : array, shape = [n_samples] + True targets of binary classification in range {-1, 1} or {0, 1}. + + probas_pred : array, shape = [n_samples] + Estimated probabilities or decision function. + + pos_label : int, optional (default=None) + The label of the positive class + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + precision : array, shape = [n_thresholds + 1] + Precision values such that element i is the precision of + predictions with score >= thresholds[i] and the last element is 1. + + recall : array, shape = [n_thresholds + 1] + Decreasing recall values such that element i is the recall of + predictions with score >= thresholds[i] and the last element is 0. + + thresholds : array, shape = [n_thresholds := len(np.unique(probas_pred))] + Increasing thresholds on the decision function used to compute + precision and recall. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import precision_recall_curve + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> precision, recall, thresholds = precision_recall_curve( + ... y_true, y_scores) + >>> precision # doctest: +ELLIPSIS + array([ 0.66..., 0.5 , 1. , 1. ]) + >>> recall + array([ 1. , 0.5, 0.5, 0. ]) + >>> thresholds + array([ 0.35, 0.4 , 0.8 ]) + + """ + fps, tps, thresholds = _binary_clf_curve(y_true, probas_pred, + pos_label=pos_label, + sample_weight=sample_weight) + + precision = tps / (tps + fps) + recall = tps / tps[-1] + + # stop when full recall attained + # and reverse the outputs so recall is decreasing + last_ind = tps.searchsorted(tps[-1]) + sl = slice(last_ind, None, -1) + return np.r_[precision[sl], 1], np.r_[recall[sl], 0], thresholds[sl] + + +def roc_curve(y_true, y_score, pos_label=None, sample_weight=None): + """Compute Receiver operating characteristic (ROC) + + Note: this implementation is restricted to the binary classification task. + + Parameters + ---------- + + y_true : array, shape = [n_samples] + True binary labels in range {0, 1} or {-1, 1}. If labels are not + binary, pos_label should be explicitly given. + + y_score : array, shape = [n_samples] + Target scores, can either be probability estimates of the positive + class or confidence values. + + pos_label : int + Label considered as positive and others are considered negative. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + fpr : array, shape = [>2] + Increasing false positive rates such that element i is the false + positive rate of predictions with score >= thresholds[i]. + + tpr : array, shape = [>2] + Increasing true positive rates such that element i is the true + positive rate of predictions with score >= thresholds[i]. + + thresholds : array, shape = [n_thresholds] + Decreasing thresholds on the decision function used to compute + fpr and tpr. `thresholds[0]` represents no instances being predicted + and is arbitrarily set to `max(y_score) + 1`. + + See also + -------- + roc_auc_score : Compute Area Under the Curve (AUC) from prediction scores + + Notes + ----- + Since the thresholds are sorted from low to high values, they + are reversed upon returning them to ensure they correspond to both ``fpr`` + and ``tpr``, which are sorted in reversed order during their calculation. + + References + ---------- + .. [1] `Wikipedia entry for the Receiver operating characteristic + `_ + + + Examples + -------- + >>> import numpy as np + >>> from sklearn import metrics + >>> y = np.array([1, 1, 2, 2]) + >>> scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2) + >>> fpr + array([ 0. , 0.5, 0.5, 1. ]) + >>> tpr + array([ 0.5, 0.5, 1. , 1. ]) + >>> thresholds + array([ 0.8 , 0.4 , 0.35, 0.1 ]) + + """ + fps, tps, thresholds = _binary_clf_curve( + y_true, y_score, pos_label=pos_label, sample_weight=sample_weight) + + if tps.size == 0 or fps[0] != 0: + # Add an extra threshold position if necessary + tps = np.r_[0, tps] + fps = np.r_[0, fps] + thresholds = np.r_[thresholds[0] + 1, thresholds] + + if fps[-1] <= 0: + warnings.warn("No negative samples in y_true, " + "false positive value should be meaningless", + UndefinedMetricWarning) + fpr = np.repeat(np.nan, fps.shape) + else: + fpr = fps / fps[-1] + + if tps[-1] <= 0: + warnings.warn("No positive samples in y_true, " + "true positive value should be meaningless", + UndefinedMetricWarning) + tpr = np.repeat(np.nan, tps.shape) + else: + tpr = tps / tps[-1] + + return fpr, tpr, thresholds + + +def label_ranking_average_precision_score(y_true, y_score): + """Compute ranking-based average precision + + Label ranking average precision (LRAP) is the average over each ground + truth label assigned to each sample, of the ratio of true vs. total + labels with lower score. + + This metric is used in multilabel ranking problem, where the goal + is to give better rank to the labels associated to each sample. + + The obtained score is always strictly greater than 0 and + the best value is 1. + + Parameters + ---------- + y_true : array or sparse matrix, shape = [n_samples, n_labels] + True binary labels in binary indicator format. + + y_score : array, shape = [n_samples, n_labels] + Target scores, can either be probability estimates of the positive + class, confidence values, or binary decisions. + + Returns + ------- + score : float + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import label_ranking_average_precision_score + >>> y_true = np.array([[1, 0, 0], [0, 0, 1]]) + >>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]]) + >>> label_ranking_average_precision_score(y_true, y_score) \ + # doctest: +ELLIPSIS + 0.416... + + """ + check_consistent_length(y_true, y_score) + y_true = check_array(y_true, ensure_2d=False) + y_score = check_array(y_score, ensure_2d=False) + + if y_true.shape != y_score.shape: + raise ValueError("y_true and y_score have different shape") + + # Handle badly formated array and the degenerate case with one label + y_type = type_of_target(y_true) + if (y_type != "multilabel-indicator" and + not (y_type == "binary" and y_true.ndim == 2)): + raise ValueError("{0} format is not supported".format(y_type)) + + y_true = csr_matrix(y_true) + y_score = -y_score + + n_samples, n_labels = y_true.shape + + out = 0. + for i, (start, stop) in enumerate(zip(y_true.indptr, y_true.indptr[1:])): + relevant = y_true.indices[start:stop] + + if (relevant.size == 0 or relevant.size == n_labels): + # If all labels are relevant or unrelevant, the score is also + # equal to 1. The label ranking has no meaning. + out += 1. + continue + + scores_i = y_score[i] + rank = rankdata(scores_i, 'max')[relevant] + L = rankdata(scores_i[relevant], 'max') + out += (L / rank).mean() + + return out / n_samples + + +def coverage_error(y_true, y_score, sample_weight=None): + """Coverage error measure + + Compute how far we need to go through the ranked scores to cover all + true labels. The best value is equal to the average number + of labels in ``y_true`` per sample. + + Ties in ``y_scores`` are broken by giving maximal rank that would have + been assigned to all tied values. + + Parameters + ---------- + y_true : array, shape = [n_samples, n_labels] + True binary labels in binary indicator format. + + y_score : array, shape = [n_samples, n_labels] + Target scores, can either be probability estimates of the positive + class, confidence values, or binary decisions. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + coverage_error : float + + References + ---------- + .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). + Mining multi-label data. In Data mining and knowledge discovery + handbook (pp. 667-685). Springer US. + + """ + y_true = check_array(y_true, ensure_2d=False) + y_score = check_array(y_score, ensure_2d=False) + check_consistent_length(y_true, y_score, sample_weight) + + y_type = type_of_target(y_true) + if y_type != "multilabel-indicator": + raise ValueError("{0} format is not supported".format(y_type)) + + if y_true.shape != y_score.shape: + raise ValueError("y_true and y_score have different shape") + + y_score_mask = np.ma.masked_array(y_score, mask=np.logical_not(y_true)) + y_min_relevant = y_score_mask.min(axis=1).reshape((-1, 1)) + coverage = (y_score >= y_min_relevant).sum(axis=1) + coverage = coverage.filled(0) + + return np.average(coverage, weights=sample_weight) diff --git a/sklearn/metrics/regression.py b/sklearn/metrics/regression.py new file mode 100644 index 0000000000000..c915601f2ed64 --- /dev/null +++ b/sklearn/metrics/regression.py @@ -0,0 +1,329 @@ +"""Metrics to assess performance on regression task + +Functions named as ``*_score`` return a scalar value to maximize: the higher +the better + +Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: +the lower the better +""" + +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Olivier Grisel +# Arnaud Joly +# Jochen Wersdorfer +# Lars Buitinck +# Joel Nothman +# Noel Dawe +# License: BSD 3 clause + +from __future__ import division + +import numpy as np + +from ..utils.validation import check_array, check_consistent_length +from ..utils.validation import column_or_1d + +__ALL__ = [ + "mean_absolute_error", + "mean_squared_error", + "median_absolute_error", + "r2_score", + "explained_variance_score" +] + + +def _check_reg_targets(y_true, y_pred): + """Check that y_true and y_pred belong to the same regression task + + Parameters + ---------- + y_true : array-like, + + y_pred : array-like, + + Returns + ------- + type_true : one of {'continuous', continuous-multioutput'} + The type of the true target data, as output by + ``utils.multiclass.type_of_target`` + + y_true : array-like of shape = [n_samples, n_outputs] + Ground truth (correct) target values. + + y_pred : array-like of shape = [n_samples, n_outputs] + Estimated target values. + """ + check_consistent_length(y_true, y_pred) + y_true = check_array(y_true, ensure_2d=False) + y_pred = check_array(y_pred, ensure_2d=False) + + if y_true.ndim == 1: + y_true = y_true.reshape((-1, 1)) + + if y_pred.ndim == 1: + y_pred = y_pred.reshape((-1, 1)) + + if y_true.shape[1] != y_pred.shape[1]: + raise ValueError("y_true and y_pred have different number of output " + "({0}!={1})".format(y_true.shape[1], y_pred.shape[1])) + + y_type = 'continuous' if y_true.shape[1] == 1 else 'continuous-multioutput' + + return y_type, y_true, y_pred + + +def _average_and_variance(values, sample_weight=None): + """ + Compute the (weighted) average and variance. + + Parameters + ---------- + values : array-like of shape = [n_samples] or [n_samples, n_outputs] + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + average : float + The weighted average + + variance : float + The weighted variance + """ + values = np.asarray(values) + if values.ndim == 1: + values = values.reshape((-1, 1)) + if sample_weight is not None: + sample_weight = np.asarray(sample_weight) + if sample_weight.ndim == 1: + sample_weight = sample_weight.reshape((-1, 1)) + average = np.average(values, weights=sample_weight) + variance = np.average((values - average)**2, weights=sample_weight) + return average, variance + + +def mean_absolute_error(y_true, y_pred, sample_weight=None): + """Mean absolute error regression loss + + Parameters + ---------- + y_true : array-like of shape = [n_samples] or [n_samples, n_outputs] + Ground truth (correct) target values. + + y_pred : array-like of shape = [n_samples] or [n_samples, n_outputs] + Estimated target values. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + loss : float + A positive floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import mean_absolute_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_absolute_error(y_true, y_pred) + 0.5 + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> mean_absolute_error(y_true, y_pred) + 0.75 + + """ + y_type, y_true, y_pred = _check_reg_targets(y_true, y_pred) + return np.average(np.abs(y_pred - y_true).mean(axis=1), + weights=sample_weight) + + +def mean_squared_error(y_true, y_pred, sample_weight=None): + """Mean squared error regression loss + + Parameters + ---------- + y_true : array-like of shape = [n_samples] or [n_samples, n_outputs] + Ground truth (correct) target values. + + y_pred : array-like of shape = [n_samples] or [n_samples, n_outputs] + Estimated target values. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + loss : float + A positive floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import mean_squared_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_squared_error(y_true, y_pred) + 0.375 + >>> y_true = [[0.5, 1],[-1, 1],[7, -6]] + >>> y_pred = [[0, 2],[-1, 2],[8, -5]] + >>> mean_squared_error(y_true, y_pred) # doctest: +ELLIPSIS + 0.708... + + """ + y_type, y_true, y_pred = _check_reg_targets(y_true, y_pred) + return np.average(((y_pred - y_true) ** 2).mean(axis=1), + weights=sample_weight) + + +def median_absolute_error(y_true, y_pred): + """Median absolute error regression loss + + Parameters + ---------- + y_true : array-like of shape = [n_samples] or [n_samples, n_outputs] + Ground truth (correct) target values. + + y_pred : array-like of shape = [n_samples] or [n_samples, n_outputs] + Estimated target values. + + Returns + ------- + loss : float + A positive floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import median_absolute_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> median_absolute_error(y_true, y_pred) + 0.5 + + """ + y_type, y_true, y_pred = _check_reg_targets(y_true, y_pred) + if y_type == 'continuous-multioutput': + raise ValueError("Multioutput not supported in median_absolute_error") + return np.median(np.abs(y_pred - y_true)) + + +def explained_variance_score(y_true, y_pred, sample_weight=None): + """Explained variance regression score function + + Best possible score is 1.0, lower values are worse. + + Parameters + ---------- + y_true : array-like + Ground truth (correct) target values. + + y_pred : array-like + Estimated target values. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + score : float + The explained variance. + + Notes + ----- + This is not a symmetric function. + + Examples + -------- + >>> from sklearn.metrics import explained_variance_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> explained_variance_score(y_true, y_pred) # doctest: +ELLIPSIS + 0.957... + + """ + y_type, y_true, y_pred = _check_reg_targets(y_true, y_pred) + + if y_type != "continuous": + raise ValueError("{0} is not supported".format(y_type)) + + _, numerator = _average_and_variance(y_true - y_pred, sample_weight) + _, denominator = _average_and_variance(y_true, sample_weight) + if denominator == 0.0: + if numerator == 0.0: + return 1.0 + else: + # arbitrary set to zero to avoid -inf scores, having a constant + # y_true is not interesting for scoring a regression anyway + return 0.0 + return 1 - numerator / denominator + + +def r2_score(y_true, y_pred, sample_weight=None): + """R^2 (coefficient of determination) regression score function. + + Best possible score is 1.0, lower values are worse. + + Parameters + ---------- + y_true : array-like of shape = [n_samples] or [n_samples, n_outputs] + Ground truth (correct) target values. + + y_pred : array-like of shape = [n_samples] or [n_samples, n_outputs] + Estimated target values. + + sample_weight : array-like of shape = [n_samples], optional + Sample weights. + + Returns + ------- + z : float + The R^2 score. + + Notes + ----- + This is not a symmetric function. + + Unlike most other scores, R^2 score may be negative (it need not actually + be the square of a quantity R). + + References + ---------- + .. [1] `Wikipedia entry on the Coefficient of determination + `_ + + Examples + -------- + >>> from sklearn.metrics import r2_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> r2_score(y_true, y_pred) # doctest: +ELLIPSIS + 0.948... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> r2_score(y_true, y_pred) # doctest: +ELLIPSIS + 0.938... + + """ + y_type, y_true, y_pred = _check_reg_targets(y_true, y_pred) + + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + weight = sample_weight[:, np.newaxis] + else: + weight = 1. + + numerator = (weight * (y_true - y_pred) ** 2).sum(dtype=np.float64) + denominator = (weight * (y_true - np.average( + y_true, axis=0, weights=sample_weight)) ** 2).sum(dtype=np.float64) + + if denominator == 0.0: + if numerator == 0.0: + return 1.0 + else: + # arbitrary set to zero to avoid -inf scores, having a constant + # y_true is not interesting for scoring a regression anyway + return 0.0 + + return 1 - numerator / denominator diff --git a/sklearn/metrics/scorer.py b/sklearn/metrics/scorer.py new file mode 100644 index 0000000000000..22d796fec1f5e --- /dev/null +++ b/sklearn/metrics/scorer.py @@ -0,0 +1,352 @@ +""" +The :mod:`sklearn.metrics.scorer` submodule implements a flexible +interface for model selection and evaluation using +arbitrary score functions. + +A scorer object is a callable that can be passed to +:class:`sklearn.grid_search.GridSearchCV` or +:func:`sklearn.cross_validation.cross_val_score` as the ``scoring`` parameter, +to specify how a model should be evaluated. + +The signature of the call is ``(estimator, X, y)`` where ``estimator`` +is the model to be evaluated, ``X`` is the test data and ``y`` is the +ground truth labeling (or ``None`` in the case of unsupervised models). +""" + +# Authors: Andreas Mueller +# Lars Buitinck +# Arnaud Joly +# License: Simplified BSD + +from abc import ABCMeta, abstractmethod +from functools import partial + +import numpy as np + +from . import (r2_score, median_absolute_error, mean_absolute_error, + mean_squared_error, accuracy_score, f1_score, + roc_auc_score, average_precision_score, + precision_score, recall_score, log_loss) +from .cluster import adjusted_rand_score +from ..utils.multiclass import type_of_target +from ..externals import six + + +class _BaseScorer(six.with_metaclass(ABCMeta, object)): + def __init__(self, score_func, sign, kwargs): + self._kwargs = kwargs + self._score_func = score_func + self._sign = sign + + @abstractmethod + def __call__(self, estimator, X, y, sample_weight=None): + pass + + def __repr__(self): + kwargs_string = "".join([", %s=%s" % (str(k), str(v)) + for k, v in self._kwargs.items()]) + return ("make_scorer(%s%s%s%s)" + % (self._score_func.__name__, + "" if self._sign > 0 else ", greater_is_better=False", + self._factory_args(), kwargs_string)) + + def _factory_args(self): + """Return non-default make_scorer arguments for repr.""" + return "" + + +class _PredictScorer(_BaseScorer): + def __call__(self, estimator, X, y_true, sample_weight=None): + """Evaluate predicted target values for X relative to y_true. + + Parameters + ---------- + estimator : object + Trained estimator to use for scoring. Must have a predict_proba + method; the output of that is used to compute the score. + + X : array-like or sparse matrix + Test data that will be fed to estimator.predict. + + y_true : array-like + Gold standard target values for X. + + sample_weight : array-like, optional (default=None) + Sample weights. + + Returns + ------- + score : float + Score function applied to prediction of estimator on X. + """ + y_pred = estimator.predict(X) + if sample_weight is not None: + return self._sign * self._score_func(y_true, y_pred, + sample_weight=sample_weight, + **self._kwargs) + else: + return self._sign * self._score_func(y_true, y_pred, + **self._kwargs) + + +class _ProbaScorer(_BaseScorer): + def __call__(self, clf, X, y, sample_weight=None): + """Evaluate predicted probabilities for X relative to y_true. + + Parameters + ---------- + clf : object + Trained classifier to use for scoring. Must have a predict_proba + method; the output of that is used to compute the score. + + X : array-like or sparse matrix + Test data that will be fed to clf.predict_proba. + + y : array-like + Gold standard target values for X. These must be class labels, + not probabilities. + + sample_weight : array-like, optional (default=None) + Sample weights. + + Returns + ------- + score : float + Score function applied to prediction of estimator on X. + """ + y_pred = clf.predict_proba(X) + if sample_weight is not None: + return self._sign * self._score_func(y, y_pred, + sample_weight=sample_weight, + **self._kwargs) + else: + return self._sign * self._score_func(y, y_pred, **self._kwargs) + + def _factory_args(self): + return ", needs_proba=True" + + +class _ThresholdScorer(_BaseScorer): + def __call__(self, clf, X, y, sample_weight=None): + """Evaluate decision function output for X relative to y_true. + + Parameters + ---------- + clf : object + Trained classifier to use for scoring. Must have either a + decision_function method or a predict_proba method; the output of + that is used to compute the score. + + X : array-like or sparse matrix + Test data that will be fed to clf.decision_function or + clf.predict_proba. + + y : array-like + Gold standard target values for X. These must be class labels, + not decision function values. + + sample_weight : array-like, optional (default=None) + Sample weights. + + Returns + ------- + score : float + Score function applied to prediction of estimator on X. + """ + y_type = type_of_target(y) + if y_type not in ("binary", "multilabel-indicator"): + raise ValueError("{0} format is not supported".format(y_type)) + + try: + y_pred = clf.decision_function(X) + + # For multi-output multi-class estimator + if isinstance(y_pred, list): + y_pred = np.vstack(p for p in y_pred).T + + except (NotImplementedError, AttributeError): + y_pred = clf.predict_proba(X) + + if y_type == "binary": + y_pred = y_pred[:, 1] + elif isinstance(y_pred, list): + y_pred = np.vstack([p[:, -1] for p in y_pred]).T + + if sample_weight is not None: + return self._sign * self._score_func(y, y_pred, + sample_weight=sample_weight, + **self._kwargs) + else: + return self._sign * self._score_func(y, y_pred, **self._kwargs) + + def _factory_args(self): + return ", needs_threshold=True" + + +def get_scorer(scoring): + if isinstance(scoring, six.string_types): + try: + scorer = SCORERS[scoring] + except KeyError: + raise ValueError('%r is not a valid scoring value. ' + 'Valid options are %s' + % (scoring, sorted(SCORERS.keys()))) + else: + scorer = scoring + return scorer + + +def _passthrough_scorer(estimator, *args, **kwargs): + """Function that wraps estimator.score""" + return estimator.score(*args, **kwargs) + + +def check_scoring(estimator, scoring=None, allow_none=False): + """Determine scorer from user options. + + A TypeError will be thrown if the estimator cannot be scored. + + Parameters + ---------- + estimator : estimator object implementing 'fit' + The object to use to fit the data. + + scoring : string, callable or None, optional, default: None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. + + allow_none : boolean, optional, default: False + If no scoring is specified and the estimator has no score function, we + can either return None or raise an exception. + + Returns + ------- + scoring : callable + A scorer callable object / function with signature + ``scorer(estimator, X, y)``. + """ + has_scoring = scoring is not None + if not hasattr(estimator, 'fit'): + raise TypeError("estimator should a be an estimator implementing " + "'fit' method, %r was passed" % estimator) + elif has_scoring: + return get_scorer(scoring) + elif hasattr(estimator, 'score'): + return _passthrough_scorer + elif allow_none: + return None + else: + raise TypeError( + "If no scoring is specified, the estimator passed should " + "have a 'score' method. The estimator %r does not." % estimator) + + +def make_scorer(score_func, greater_is_better=True, needs_proba=False, + needs_threshold=False, **kwargs): + """Make a scorer from a performance metric or loss function. + + This factory function wraps scoring functions for use in GridSearchCV + and cross_val_score. It takes a score function, such as ``accuracy_score``, + ``mean_squared_error``, ``adjusted_rand_index`` or ``average_precision`` + and returns a callable that scores an estimator's output. + + Parameters + ---------- + score_func : callable, + Score function (or loss function) with signature + ``score_func(y, y_pred, **kwargs)``. + + greater_is_better : boolean, default=True + Whether score_func is a score function (default), meaning high is good, + or a loss function, meaning low is good. In the latter case, the + scorer object will sign-flip the outcome of the score_func. + + needs_proba : boolean, default=False + Whether score_func requires predict_proba to get probability estimates + out of a classifier. + + needs_threshold : boolean, default=False + Whether score_func takes a continuous decision certainty. + This only works for binary classification using estimators that + have either a decision_function or predict_proba method. + + For example ``average_precision`` or the area under the roc curve + can not be computed using discrete predictions alone. + + **kwargs : additional arguments + Additional parameters to be passed to score_func. + + Returns + ------- + scorer : callable + Callable object that returns a scalar score; greater is better. + + Examples + -------- + >>> from sklearn.metrics import fbeta_score, make_scorer + >>> ftwo_scorer = make_scorer(fbeta_score, beta=2) + >>> ftwo_scorer + make_scorer(fbeta_score, beta=2) + >>> from sklearn.grid_search import GridSearchCV + >>> from sklearn.svm import LinearSVC + >>> grid = GridSearchCV(LinearSVC(), param_grid={'C': [1, 10]}, + ... scoring=ftwo_scorer) + """ + sign = 1 if greater_is_better else -1 + if needs_proba and needs_threshold: + raise ValueError("Set either needs_proba or needs_threshold to True," + " but not both.") + if needs_proba: + cls = _ProbaScorer + elif needs_threshold: + cls = _ThresholdScorer + else: + cls = _PredictScorer + return cls(score_func, sign, kwargs) + + +# Standard regression scores +r2_scorer = make_scorer(r2_score) +mean_squared_error_scorer = make_scorer(mean_squared_error, + greater_is_better=False) +mean_absolute_error_scorer = make_scorer(mean_absolute_error, + greater_is_better=False) +median_absolute_error_scorer = make_scorer(median_absolute_error, + greater_is_better=False) + +# Standard Classification Scores +accuracy_scorer = make_scorer(accuracy_score) +f1_scorer = make_scorer(f1_score) + +# Score functions that need decision values +roc_auc_scorer = make_scorer(roc_auc_score, greater_is_better=True, + needs_threshold=True) +average_precision_scorer = make_scorer(average_precision_score, + needs_threshold=True) +precision_scorer = make_scorer(precision_score) +recall_scorer = make_scorer(recall_score) + +# Score function for probabilistic classification +log_loss_scorer = make_scorer(log_loss, greater_is_better=False, + needs_proba=True) + +# Clustering scores +adjusted_rand_scorer = make_scorer(adjusted_rand_score) + +SCORERS = dict(r2=r2_scorer, + median_absolute_error=median_absolute_error_scorer, + mean_absolute_error=mean_absolute_error_scorer, + mean_squared_error=mean_squared_error_scorer, + accuracy=accuracy_scorer, roc_auc=roc_auc_scorer, + average_precision=average_precision_scorer, + log_loss=log_loss_scorer, + adjusted_rand_score=adjusted_rand_scorer) + +for name, metric in [('precision', precision_score), + ('recall', recall_score), ('f1', f1_score)]: + SCORERS[name] = make_scorer(metric) + for average in ['macro', 'micro', 'samples', 'weighted']: + qualified_name = '{0}_{1}'.format(name, average) + SCORERS[qualified_name] = make_scorer(partial(metric, pos_label=None, + average=average)) diff --git a/sklearn/metrics/setup.py b/sklearn/metrics/setup.py new file mode 100644 index 0000000000000..f5a6ce27f2ce6 --- /dev/null +++ b/sklearn/metrics/setup.py @@ -0,0 +1,31 @@ +import os +import os.path + +import numpy +from numpy.distutils.misc_util import Configuration + +from sklearn._build_utils import get_blas_info + + +def configuration(parent_package="", top_path=None): + config = Configuration("metrics", parent_package, top_path) + + cblas_libs, blas_info = get_blas_info() + if os.name == 'posix': + cblas_libs.append('m') + + config.add_extension("pairwise_fast", + sources=["pairwise_fast.c"], + include_dirs=[os.path.join('..', 'src', 'cblas'), + numpy.get_include(), + blas_info.pop('include_dirs', [])], + libraries=cblas_libs, + extra_compile_args=blas_info.pop('extra_compile_args', + []), + **blas_info) + + return config + +if __name__ == "__main__": + from numpy.distutils.core import setup + setup(**configuration().todict()) diff --git a/sklearn/metrics/tests/test_classification.py b/sklearn/metrics/tests/test_classification.py new file mode 100644 index 0000000000000..5f70e235a9c33 --- /dev/null +++ b/sklearn/metrics/tests/test_classification.py @@ -0,0 +1,1290 @@ +from __future__ import division, print_function + +import numpy as np +from scipy import linalg +from functools import partial +from itertools import product +import warnings + +from sklearn import datasets +from sklearn import svm + +from sklearn.datasets import make_multilabel_classification +from sklearn.preprocessing import LabelBinarizer, MultiLabelBinarizer +from sklearn.utils.fixes import np_version +from sklearn.utils.validation import check_random_state + +from sklearn.utils.testing import assert_raises, clean_warning_registry +from sklearn.utils.testing import assert_raise_message +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import assert_no_warnings +from sklearn.utils.testing import assert_warns_message +from sklearn.utils.testing import assert_not_equal +from sklearn.utils.testing import ignore_warnings + +from sklearn.metrics import accuracy_score +from sklearn.metrics import average_precision_score +from sklearn.metrics import classification_report +from sklearn.metrics import confusion_matrix +from sklearn.metrics import f1_score +from sklearn.metrics import fbeta_score +from sklearn.metrics import hamming_loss +from sklearn.metrics import hinge_loss +from sklearn.metrics import jaccard_similarity_score +from sklearn.metrics import log_loss +from sklearn.metrics import matthews_corrcoef +from sklearn.metrics import precision_recall_fscore_support +from sklearn.metrics import precision_score +from sklearn.metrics import recall_score +from sklearn.metrics import zero_one_loss +from sklearn.metrics import brier_score_loss + + +from sklearn.metrics.classification import _check_targets +from sklearn.metrics.base import UndefinedMetricWarning + + +############################################################################### +# Utilities for testing + +def make_prediction(dataset=None, binary=False): + """Make some classification predictions on a toy dataset using a SVC + + If binary is True restrict to a binary classification problem instead of a + multiclass classification problem + """ + + if dataset is None: + # import some data to play with + dataset = datasets.load_iris() + + X = dataset.data + y = dataset.target + + if binary: + # restrict to a binary classification task + X, y = X[y < 2], y[y < 2] + + n_samples, n_features = X.shape + p = np.arange(n_samples) + + rng = check_random_state(37) + rng.shuffle(p) + X, y = X[p], y[p] + half = int(n_samples / 2) + + # add noisy features to make the problem harder and avoid perfect results + rng = np.random.RandomState(0) + X = np.c_[X, rng.randn(n_samples, 200 * n_features)] + + # run classifier, get class probabilities and label predictions + clf = svm.SVC(kernel='linear', probability=True, random_state=0) + probas_pred = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) + + if binary: + # only interested in probabilities of the positive case + # XXX: do we really want a special API for the binary case? + probas_pred = probas_pred[:, 1] + + y_pred = clf.predict(X[half:]) + y_true = y[half:] + return y_true, y_pred, probas_pred + + +############################################################################### +# Tests + + +def test_multilabel_accuracy_score_subset_accuracy(): + # Dense label indicator matrix format + y1 = np.array([[0, 1, 1], [1, 0, 1]]) + y2 = np.array([[0, 0, 1], [1, 0, 1]]) + + assert_equal(accuracy_score(y1, y2), 0.5) + assert_equal(accuracy_score(y1, y1), 1) + assert_equal(accuracy_score(y2, y2), 1) + assert_equal(accuracy_score(y2, np.logical_not(y2)), 0) + assert_equal(accuracy_score(y1, np.logical_not(y1)), 0) + assert_equal(accuracy_score(y1, np.zeros(y1.shape)), 0) + assert_equal(accuracy_score(y2, np.zeros(y1.shape)), 0) + + with ignore_warnings(): # sequence of sequences is deprecated + # List of tuple of label + y1 = [(1, 2,), (0, 2,)] + y2 = [(2,), (0, 2,)] + + assert_equal(accuracy_score(y1, y2), 0.5) + assert_equal(accuracy_score(y1, y1), 1) + assert_equal(accuracy_score(y2, y2), 1) + assert_equal(accuracy_score(y2, [(), ()]), 0) + assert_equal(accuracy_score(y1, y2, normalize=False), 1) + assert_equal(accuracy_score(y1, y1, normalize=False), 2) + assert_equal(accuracy_score(y2, y2, normalize=False), 2) + assert_equal(accuracy_score(y2, [(), ()], normalize=False), 0) + + +def test_precision_recall_f1_score_binary(): + """Test Precision Recall and F1 Score for binary classification task""" + y_true, y_pred, _ = make_prediction(binary=True) + + # detailed measures for each class + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) + assert_array_almost_equal(p, [0.73, 0.85], 2) + assert_array_almost_equal(r, [0.88, 0.68], 2) + assert_array_almost_equal(f, [0.80, 0.76], 2) + assert_array_equal(s, [25, 25]) + + # individual scoring function that can be used for grid search: in the + # binary class case the score is the value of the measure for the positive + # class (e.g. label == 1). This is deprecated for average != 'binary'. + assert_dep_warning = partial(assert_warns, DeprecationWarning) + for kwargs, my_assert in [({}, assert_no_warnings), + ({'average': 'binary'}, assert_no_warnings), + ({'average': 'micro'}, assert_dep_warning)]: + ps = my_assert(precision_score, y_true, y_pred, **kwargs) + assert_array_almost_equal(ps, 0.85, 2) + + rs = my_assert(recall_score, y_true, y_pred, **kwargs) + assert_array_almost_equal(rs, 0.68, 2) + + fs = my_assert(f1_score, y_true, y_pred, **kwargs) + assert_array_almost_equal(fs, 0.76, 2) + + assert_almost_equal(my_assert(fbeta_score, y_true, y_pred, beta=2, + **kwargs), + (1 + 2 ** 2) * ps * rs / (2 ** 2 * ps + rs), 2) + + +@ignore_warnings +def test_precision_recall_f_binary_single_class(): + """Test precision, recall and F1 score behave with a single positive or + negative class + + Such a case may occur with non-stratified cross-validation""" + assert_equal(1., precision_score([1, 1], [1, 1])) + assert_equal(1., recall_score([1, 1], [1, 1])) + assert_equal(1., f1_score([1, 1], [1, 1])) + + assert_equal(0., precision_score([-1, -1], [-1, -1])) + assert_equal(0., recall_score([-1, -1], [-1, -1])) + assert_equal(0., f1_score([-1, -1], [-1, -1])) + + +def test_average_precision_score_score_non_binary_class(): + """Test that average_precision_score function returns an error when trying + to compute average_precision_score for multiclass task. + """ + rng = check_random_state(404) + y_pred = rng.rand(10) + + # y_true contains three different class values + y_true = rng.randint(0, 3, size=10) + assert_raise_message(ValueError, "multiclass format is not supported", + average_precision_score, y_true, y_pred) + + +def test_average_precision_score_duplicate_values(): + # Duplicate values with precision-recall require a different + # processing than when computing the AUC of a ROC, because the + # precision-recall curve is a decreasing curve + # The following situtation corresponds to a perfect + # test statistic, the average_precision_score should be 1 + y_true = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1] + y_score = [0, .1, .1, .4, .5, .6, .6, .9, .9, 1, 1] + assert_equal(average_precision_score(y_true, y_score), 1) + + +def test_average_precision_score_tied_values(): + # Here if we go from left to right in y_true, the 0 values are + # are separated from the 1 values, so it appears that we've + # Correctly sorted our classifications. But in fact the first two + # values have the same score (0.5) and so the first two values + # could be swapped around, creating an imperfect sorting. This + # imperfection should come through in the end score, making it less + # than one. + y_true = [0, 1, 1] + y_score = [.5, .5, .6] + assert_not_equal(average_precision_score(y_true, y_score), 1.) + + +@ignore_warnings +def test_precision_recall_fscore_support_errors(): + y_true, y_pred, _ = make_prediction(binary=True) + + # Bad beta + assert_raises(ValueError, precision_recall_fscore_support, + y_true, y_pred, beta=0.0) + + # Bad pos_label + assert_raises(ValueError, precision_recall_fscore_support, + y_true, y_pred, pos_label=2, average='macro') + + # Bad average option + assert_raises(ValueError, precision_recall_fscore_support, + [0, 1, 2], [1, 2, 0], average='mega') + + +def test_confusion_matrix_binary(): + """Test confusion matrix - binary classification case""" + y_true, y_pred, _ = make_prediction(binary=True) + + def test(y_true, y_pred): + cm = confusion_matrix(y_true, y_pred) + assert_array_equal(cm, [[22, 3], [8, 17]]) + + tp, fp, fn, tn = cm.flatten() + num = (tp * tn - fp * fn) + den = np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) + + true_mcc = 0 if den == 0 else num / den + mcc = matthews_corrcoef(y_true, y_pred) + assert_array_almost_equal(mcc, true_mcc, decimal=2) + assert_array_almost_equal(mcc, 0.57, decimal=2) + + test(y_true, y_pred) + test([str(y) for y in y_true], + [str(y) for y in y_pred]) + + +@ignore_warnings +def test_matthews_corrcoef_nan(): + assert_equal(matthews_corrcoef([0], [1]), 0.0) + assert_equal(matthews_corrcoef([0, 0], [0, 1]), 0.0) + + +def test_precision_recall_f1_score_multiclass(): + """Test Precision Recall and F1 Score for multiclass classification task""" + y_true, y_pred, _ = make_prediction(binary=False) + + # compute scores with default labels introspection + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) + assert_array_almost_equal(p, [0.83, 0.33, 0.42], 2) + assert_array_almost_equal(r, [0.79, 0.09, 0.90], 2) + assert_array_almost_equal(f, [0.81, 0.15, 0.57], 2) + assert_array_equal(s, [24, 31, 20]) + + # averaging tests + ps = precision_score(y_true, y_pred, pos_label=1, average='micro') + assert_array_almost_equal(ps, 0.53, 2) + + rs = recall_score(y_true, y_pred, average='micro') + assert_array_almost_equal(rs, 0.53, 2) + + fs = f1_score(y_true, y_pred, average='micro') + assert_array_almost_equal(fs, 0.53, 2) + + ps = precision_score(y_true, y_pred, average='macro') + assert_array_almost_equal(ps, 0.53, 2) + + rs = recall_score(y_true, y_pred, average='macro') + assert_array_almost_equal(rs, 0.60, 2) + + fs = f1_score(y_true, y_pred, average='macro') + assert_array_almost_equal(fs, 0.51, 2) + + ps = precision_score(y_true, y_pred, average='weighted') + assert_array_almost_equal(ps, 0.51, 2) + + rs = recall_score(y_true, y_pred, average='weighted') + assert_array_almost_equal(rs, 0.53, 2) + + fs = f1_score(y_true, y_pred, average='weighted') + assert_array_almost_equal(fs, 0.47, 2) + + assert_raises(ValueError, precision_score, y_true, y_pred, + average="samples") + assert_raises(ValueError, recall_score, y_true, y_pred, average="samples") + assert_raises(ValueError, f1_score, y_true, y_pred, average="samples") + assert_raises(ValueError, fbeta_score, y_true, y_pred, average="samples", + beta=0.5) + + # same prediction but with and explicit label ordering + p, r, f, s = precision_recall_fscore_support( + y_true, y_pred, labels=[0, 2, 1], average=None) + assert_array_almost_equal(p, [0.83, 0.41, 0.33], 2) + assert_array_almost_equal(r, [0.79, 0.90, 0.10], 2) + assert_array_almost_equal(f, [0.81, 0.57, 0.15], 2) + assert_array_equal(s, [24, 20, 31]) + + +def test_precision_refcall_f1_score_multilabel_unordered_labels(): + # test that labels need not be sorted in the multilabel case + y_true = np.array([[1, 1, 0, 0]]) + y_pred = np.array([[0, 0, 1, 1]]) + for average in ['samples', 'micro', 'macro', 'weighted', None]: + p, r, f, s = precision_recall_fscore_support( + y_true, y_pred, labels=[4, 1, 2, 3], warn_for=[], average=average) + assert_array_equal(p, 0) + assert_array_equal(r, 0) + assert_array_equal(f, 0) + if average is None: + assert_array_equal(s, [0, 1, 1, 0]) + + +def test_precision_recall_f1_score_multiclass_pos_label_none(): + """Test Precision Recall and F1 Score for multiclass classification task + + GH Issue #1296 + """ + # initialize data + y_true = np.array([0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1]) + y_pred = np.array([1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1]) + + # compute scores with default labels introspection + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + pos_label=None, + average='weighted') + + +def test_zero_precision_recall(): + """Check that pathological cases do not bring NaNs""" + + old_error_settings = np.seterr(all='raise') + + try: + y_true = np.array([0, 1, 2, 0, 1, 2]) + y_pred = np.array([2, 0, 1, 1, 2, 0]) + + assert_almost_equal(precision_score(y_true, y_pred, + average='weighted'), 0.0, 2) + assert_almost_equal(recall_score(y_true, y_pred, average='weighted'), + 0.0, 2) + assert_almost_equal(f1_score(y_true, y_pred, average='weighted'), + 0.0, 2) + + finally: + np.seterr(**old_error_settings) + + +def test_confusion_matrix_multiclass(): + """Test confusion matrix - multi-class case""" + y_true, y_pred, _ = make_prediction(binary=False) + + def test(y_true, y_pred, string_type=False): + # compute confusion matrix with default labels introspection + cm = confusion_matrix(y_true, y_pred) + assert_array_equal(cm, [[19, 4, 1], + [4, 3, 24], + [0, 2, 18]]) + + # compute confusion matrix with explicit label ordering + labels = ['0', '2', '1'] if string_type else [0, 2, 1] + cm = confusion_matrix(y_true, + y_pred, + labels=labels) + assert_array_equal(cm, [[19, 1, 4], + [0, 18, 2], + [4, 24, 3]]) + + test(y_true, y_pred) + test(list(str(y) for y in y_true), + list(str(y) for y in y_pred), + string_type=True) + + +def test_confusion_matrix_multiclass_subset_labels(): + """Test confusion matrix - multi-class case with subset of labels""" + y_true, y_pred, _ = make_prediction(binary=False) + + # compute confusion matrix with only first two labels considered + cm = confusion_matrix(y_true, y_pred, labels=[0, 1]) + assert_array_equal(cm, [[19, 4], + [4, 3]]) + + # compute confusion matrix with explicit label ordering for only subset + # of labels + cm = confusion_matrix(y_true, y_pred, labels=[2, 1]) + assert_array_equal(cm, [[18, 2], + [24, 3]]) + + +def test_classification_report_multiclass(): + """Test performance report""" + iris = datasets.load_iris() + y_true, y_pred, _ = make_prediction(dataset=iris, binary=False) + + # print classification report with class names + expected_report = """\ + precision recall f1-score support + + setosa 0.83 0.79 0.81 24 + versicolor 0.33 0.10 0.15 31 + virginica 0.42 0.90 0.57 20 + +avg / total 0.51 0.53 0.47 75 +""" + report = classification_report( + y_true, y_pred, labels=np.arange(len(iris.target_names)), + target_names=iris.target_names) + assert_equal(report, expected_report) + + # print classification report with label detection + expected_report = """\ + precision recall f1-score support + + 0 0.83 0.79 0.81 24 + 1 0.33 0.10 0.15 31 + 2 0.42 0.90 0.57 20 + +avg / total 0.51 0.53 0.47 75 +""" + report = classification_report(y_true, y_pred) + assert_equal(report, expected_report) + + +def test_classification_report_multiclass_with_digits(): + """Test performance report with added digits in floating point values""" + iris = datasets.load_iris() + y_true, y_pred, _ = make_prediction(dataset=iris, binary=False) + + # print classification report with class names + expected_report = """\ + precision recall f1-score support + + setosa 0.82609 0.79167 0.80851 24 + versicolor 0.33333 0.09677 0.15000 31 + virginica 0.41860 0.90000 0.57143 20 + +avg / total 0.51375 0.53333 0.47310 75 +""" + report = classification_report( + y_true, y_pred, labels=np.arange(len(iris.target_names)), + target_names=iris.target_names, digits=5) + assert_equal(report, expected_report) + + # print classification report with label detection + expected_report = """\ + precision recall f1-score support + + 0 0.83 0.79 0.81 24 + 1 0.33 0.10 0.15 31 + 2 0.42 0.90 0.57 20 + +avg / total 0.51 0.53 0.47 75 +""" + report = classification_report(y_true, y_pred) + assert_equal(report, expected_report) + + +def test_classification_report_multiclass_with_string_label(): + y_true, y_pred, _ = make_prediction(binary=False) + + y_true = np.array(["blue", "green", "red"])[y_true] + y_pred = np.array(["blue", "green", "red"])[y_pred] + + expected_report = """\ + precision recall f1-score support + + blue 0.83 0.79 0.81 24 + green 0.33 0.10 0.15 31 + red 0.42 0.90 0.57 20 + +avg / total 0.51 0.53 0.47 75 +""" + report = classification_report(y_true, y_pred) + assert_equal(report, expected_report) + + expected_report = """\ + precision recall f1-score support + + a 0.83 0.79 0.81 24 + b 0.33 0.10 0.15 31 + c 0.42 0.90 0.57 20 + +avg / total 0.51 0.53 0.47 75 +""" + report = classification_report(y_true, y_pred, + target_names=["a", "b", "c"]) + assert_equal(report, expected_report) + + +def test_classification_report_multiclass_with_unicode_label(): + y_true, y_pred, _ = make_prediction(binary=False) + + labels = np.array([u"blue\xa2", u"green\xa2", u"red\xa2"]) + y_true = labels[y_true] + y_pred = labels[y_pred] + + expected_report = u"""\ + precision recall f1-score support + + blue\xa2 0.83 0.79 0.81 24 + green\xa2 0.33 0.10 0.15 31 + red\xa2 0.42 0.90 0.57 20 + +avg / total 0.51 0.53 0.47 75 +""" + if np_version[:3] < (1, 7, 0): + expected_message = ("NumPy < 1.7.0 does not implement" + " searchsorted on unicode data correctly.") + assert_raise_message(RuntimeError, expected_message, + classification_report, y_true, y_pred) + else: + report = classification_report(y_true, y_pred) + assert_equal(report, expected_report) + + +@ignore_warnings # sequence of sequences is deprecated +def test_multilabel_classification_report(): + n_classes = 4 + n_samples = 50 + make_ml = make_multilabel_classification + _, y_true_ll = make_ml(n_features=1, n_classes=n_classes, random_state=0, + n_samples=n_samples) + _, y_pred_ll = make_ml(n_features=1, n_classes=n_classes, random_state=1, + n_samples=n_samples) + + expected_report = """\ + precision recall f1-score support + + 0 0.50 0.67 0.57 24 + 1 0.51 0.74 0.61 27 + 2 0.29 0.08 0.12 26 + 3 0.52 0.56 0.54 27 + +avg / total 0.45 0.51 0.46 104 +""" + + lb = MultiLabelBinarizer() + lb.fit([range(4)]) + y_true_bi = lb.transform(y_true_ll) + y_pred_bi = lb.transform(y_pred_ll) + + for y_true, y_pred in [(y_true_ll, y_pred_ll), (y_true_bi, y_pred_bi)]: + report = classification_report(y_true, y_pred) + assert_equal(report, expected_report) + + +def test_multilabel_zero_one_loss_subset(): + # Dense label indicator matrix format + y1 = np.array([[0, 1, 1], [1, 0, 1]]) + y2 = np.array([[0, 0, 1], [1, 0, 1]]) + + assert_equal(zero_one_loss(y1, y2), 0.5) + assert_equal(zero_one_loss(y1, y1), 0) + assert_equal(zero_one_loss(y2, y2), 0) + assert_equal(zero_one_loss(y2, np.logical_not(y2)), 1) + assert_equal(zero_one_loss(y1, np.logical_not(y1)), 1) + assert_equal(zero_one_loss(y1, np.zeros(y1.shape)), 1) + assert_equal(zero_one_loss(y2, np.zeros(y1.shape)), 1) + + with ignore_warnings(): # sequence of sequences is deprecated + # List of tuple of label + y1 = [(1, 2,), (0, 2,)] + y2 = [(2,), (0, 2,)] + + assert_equal(zero_one_loss(y1, y2), 0.5) + assert_equal(zero_one_loss(y1, y1), 0) + assert_equal(zero_one_loss(y2, y2), 0) + assert_equal(zero_one_loss(y2, [(), ()]), 1) + assert_equal(zero_one_loss(y2, [tuple(), (10, )]), 1) + + +def test_multilabel_hamming_loss(): + # Dense label indicator matrix format + y1 = np.array([[0, 1, 1], [1, 0, 1]]) + y2 = np.array([[0, 0, 1], [1, 0, 1]]) + + assert_equal(hamming_loss(y1, y2), 1 / 6) + assert_equal(hamming_loss(y1, y1), 0) + assert_equal(hamming_loss(y2, y2), 0) + assert_equal(hamming_loss(y2, np.logical_not(y2)), 1) + assert_equal(hamming_loss(y1, np.logical_not(y1)), 1) + assert_equal(hamming_loss(y1, np.zeros(y1.shape)), 4 / 6) + assert_equal(hamming_loss(y2, np.zeros(y1.shape)), 0.5) + + with ignore_warnings(): # sequence of sequences is deprecated + # List of tuple of label + y1 = [(1, 2,), (0, 2,)] + y2 = [(2,), (0, 2,)] + + assert_equal(hamming_loss(y1, y2), 1 / 6) + assert_equal(hamming_loss(y1, y1), 0) + assert_equal(hamming_loss(y2, y2), 0) + assert_equal(hamming_loss(y2, [(), ()]), 0.75) + assert_equal(hamming_loss(y1, [tuple(), (10, )]), 0.625) + assert_almost_equal(hamming_loss(y2, [tuple(), (10, )], + classes=np.arange(11)), 0.1818, 2) + + +def test_multilabel_jaccard_similarity_score(): + # Dense label indicator matrix format + y1 = np.array([[0, 1, 1], [1, 0, 1]]) + y2 = np.array([[0, 0, 1], [1, 0, 1]]) + + # size(y1 \inter y2) = [1, 2] + # size(y1 \union y2) = [2, 2] + + assert_equal(jaccard_similarity_score(y1, y2), 0.75) + assert_equal(jaccard_similarity_score(y1, y1), 1) + assert_equal(jaccard_similarity_score(y2, y2), 1) + assert_equal(jaccard_similarity_score(y2, np.logical_not(y2)), 0) + assert_equal(jaccard_similarity_score(y1, np.logical_not(y1)), 0) + assert_equal(jaccard_similarity_score(y1, np.zeros(y1.shape)), 0) + assert_equal(jaccard_similarity_score(y2, np.zeros(y1.shape)), 0) + + with ignore_warnings(): # sequence of sequences is deprecated + # List of tuple of label + y1 = [(1, 2,), (0, 2,)] + y2 = [(2,), (0, 2,)] + + assert_equal(jaccard_similarity_score(y1, y2), 0.75) + assert_equal(jaccard_similarity_score(y1, y1), 1) + assert_equal(jaccard_similarity_score(y2, y2), 1) + assert_equal(jaccard_similarity_score(y2, [(), ()]), 0) + + # |y3 inter y4 | = [0, 1, 1] + # |y3 union y4 | = [2, 1, 3] + y3 = [(0,), (1,), (3,)] + y4 = [(4,), (4,), (5, 6)] + assert_almost_equal(jaccard_similarity_score(y3, y4), 0) + + # |y5 inter y6 | = [0, 1, 1] + # |y5 union y6 | = [2, 1, 3] + y5 = [(0,), (1,), (2, 3)] + y6 = [(1,), (1,), (2, 0)] + + assert_almost_equal(jaccard_similarity_score(y5, y6), (1 + 1 / 3) / 3) + + +@ignore_warnings +def test_precision_recall_f1_score_multilabel_1(): + """ Test precision_recall_f1_score on a crafted multilabel example + """ + # First crafted example + y_true_ll = [(0,), (1,), (2, 3)] + y_pred_ll = [(1,), (1,), (2, 0)] + lb = LabelBinarizer() + lb.fit([range(4)]) + y_true_bi = lb.transform(y_true_ll) + y_pred_bi = lb.transform(y_pred_ll) + + for y_true, y_pred in [(y_true_ll, y_pred_ll), (y_true_bi, y_pred_bi)]: + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average=None) + #tp = [0, 1, 1, 0] + #fn = [1, 0, 0, 1] + #fp = [1, 1, 0, 0] + # Check per class + + assert_array_almost_equal(p, [0.0, 0.5, 1.0, 0.0], 2) + assert_array_almost_equal(r, [0.0, 1.0, 1.0, 0.0], 2) + assert_array_almost_equal(f, [0.0, 1 / 1.5, 1, 0.0], 2) + assert_array_almost_equal(s, [1, 1, 1, 1], 2) + + f2 = fbeta_score(y_true, y_pred, beta=2, average=None) + support = s + assert_array_almost_equal(f2, [0, 0.83, 1, 0], 2) + + # Check macro + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="macro") + assert_almost_equal(p, 1.5 / 4) + assert_almost_equal(r, 0.5) + assert_almost_equal(f, 2.5 / 1.5 * 0.25) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="macro"), + np.mean(f2)) + + # Check micro + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="micro") + assert_almost_equal(p, 0.5) + assert_almost_equal(r, 0.5) + assert_almost_equal(f, 0.5) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="micro"), + (1 + 4) * p * r / (4 * p + r)) + + # Check weigted + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="weighted") + assert_almost_equal(p, 1.5 / 4) + assert_almost_equal(r, 0.5) + assert_almost_equal(f, 2.5 / 1.5 * 0.25) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="weighted"), + np.average(f2, weights=support)) + # Check weigted + # |h(x_i) inter y_i | = [0, 1, 1] + # |y_i| = [1, 1, 2] + # |h(x_i)| = [1, 1, 2] + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="samples") + assert_almost_equal(p, 0.5) + assert_almost_equal(r, 0.5) + assert_almost_equal(f, 0.5) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="samples"), + 0.5) + + +@ignore_warnings +def test_precision_recall_f1_score_multilabel_2(): + """ Test precision_recall_f1_score on a crafted multilabel example 2 + """ + # Second crafted example + y_true_ll = [(1,), (2,), (2, 3)] + y_pred_ll = [(4,), (4,), (2, 1)] + lb = LabelBinarizer() + lb.fit([range(1, 5)]) + y_true_bi = lb.transform(y_true_ll) + y_pred_bi = lb.transform(y_pred_ll) + + for y_true, y_pred in [(y_true_ll, y_pred_ll), (y_true_bi, y_pred_bi)]: + # tp = [ 0. 1. 0. 0.] + # fp = [ 1. 0. 0. 2.] + # fn = [ 1. 1. 1. 0.] + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average=None) + assert_array_almost_equal(p, [0.0, 1.0, 0.0, 0.0], 2) + assert_array_almost_equal(r, [0.0, 0.5, 0.0, 0.0], 2) + assert_array_almost_equal(f, [0.0, 0.66, 0.0, 0.0], 2) + assert_array_almost_equal(s, [1, 2, 1, 0], 2) + + f2 = fbeta_score(y_true, y_pred, beta=2, average=None) + support = s + assert_array_almost_equal(f2, [0, 0.55, 0, 0], 2) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="micro") + assert_almost_equal(p, 0.25) + assert_almost_equal(r, 0.25) + assert_almost_equal(f, 2 * 0.25 * 0.25 / 0.5) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="micro"), + (1 + 4) * p * r / (4 * p + r)) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="macro") + assert_almost_equal(p, 0.25) + assert_almost_equal(r, 0.125) + assert_almost_equal(f, 2 / 12) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="macro"), + np.mean(f2)) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="weighted") + assert_almost_equal(p, 2 / 4) + assert_almost_equal(r, 1 / 4) + assert_almost_equal(f, 2 / 3 * 2 / 4) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="weighted"), + np.average(f2, weights=support)) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="samples") + # Check weigted + # |h(x_i) inter y_i | = [0, 0, 1] + # |y_i| = [1, 1, 2] + # |h(x_i)| = [1, 1, 2] + + assert_almost_equal(p, 1 / 6) + assert_almost_equal(r, 1 / 6) + assert_almost_equal(f, 2 / 4 * 1 / 3) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="samples"), + 0.1666, 2) + + +@ignore_warnings +def test_precision_recall_f1_score_with_an_empty_prediction(): + y_true_ll = [(1,), (0,), (2, 1,)] + y_pred_ll = [tuple(), (3,), (2, 1)] + + lb = LabelBinarizer() + lb.fit([range(4)]) + y_true_bi = lb.transform(y_true_ll) + y_pred_bi = lb.transform(y_pred_ll) + + for y_true, y_pred in [(y_true_ll, y_pred_ll), (y_true_bi, y_pred_bi)]: + # true_pos = [ 0. 1. 1. 0.] + # false_pos = [ 0. 0. 0. 1.] + # false_neg = [ 1. 1. 0. 0.] + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average=None) + assert_array_almost_equal(p, [0.0, 1.0, 1.0, 0.0], 2) + assert_array_almost_equal(r, [0.0, 0.5, 1.0, 0.0], 2) + assert_array_almost_equal(f, [0.0, 1 / 1.5, 1, 0.0], 2) + assert_array_almost_equal(s, [1, 2, 1, 0], 2) + + f2 = fbeta_score(y_true, y_pred, beta=2, average=None) + support = s + assert_array_almost_equal(f2, [0, 0.55, 1, 0], 2) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="macro") + assert_almost_equal(p, 0.5) + assert_almost_equal(r, 1.5 / 4) + assert_almost_equal(f, 2.5 / (4 * 1.5)) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="macro"), + np.mean(f2)) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="micro") + assert_almost_equal(p, 2 / 3) + assert_almost_equal(r, 0.5) + assert_almost_equal(f, 2 / 3 / (2 / 3 + 0.5)) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="micro"), + (1 + 4) * p * r / (4 * p + r)) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="weighted") + assert_almost_equal(p, 3 / 4) + assert_almost_equal(r, 0.5) + assert_almost_equal(f, (2 / 1.5 + 1) / 4) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="weighted"), + np.average(f2, weights=support)) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, + average="samples") + # |h(x_i) inter y_i | = [0, 0, 2] + # |y_i| = [1, 1, 2] + # |h(x_i)| = [0, 1, 2] + assert_almost_equal(p, 1 / 3) + assert_almost_equal(r, 1 / 3) + assert_almost_equal(f, 1 / 3) + assert_equal(s, None) + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, + average="samples"), + 0.333, 2) + + +def test_precision_recall_f1_no_labels(): + y_true = np.zeros((20, 3)) + y_pred = np.zeros_like(y_true) + + # tp = [0, 0, 0] + # fn = [0, 0, 0] + # fp = [0, 0, 0] + # support = [0, 0, 0] + # |y_hat_i inter y_i | = [0, 0, 0] + # |y_i| = [0, 0, 0] + # |y_hat_i| = [0, 0, 0] + + for beta in [1]: + p, r, f, s = assert_warns(UndefinedMetricWarning, + precision_recall_fscore_support, + y_true, y_pred, average=None, beta=beta) + assert_array_almost_equal(p, [0, 0, 0], 2) + assert_array_almost_equal(r, [0, 0, 0], 2) + assert_array_almost_equal(f, [0, 0, 0], 2) + assert_array_almost_equal(s, [0, 0, 0], 2) + + fbeta = assert_warns(UndefinedMetricWarning, fbeta_score, + y_true, y_pred, beta=beta, average=None) + assert_array_almost_equal(fbeta, [0, 0, 0], 2) + + for average in ["macro", "micro", "weighted", "samples"]: + p, r, f, s = assert_warns(UndefinedMetricWarning, + precision_recall_fscore_support, + y_true, y_pred, average=average, + beta=beta) + assert_almost_equal(p, 0) + assert_almost_equal(r, 0) + assert_almost_equal(f, 0) + assert_equal(s, None) + + fbeta = assert_warns(UndefinedMetricWarning, fbeta_score, + y_true, y_pred, + beta=beta, average=average) + assert_almost_equal(fbeta, 0) + + +def test_prf_warnings(): + + # average of per-label scores + f, w = precision_recall_fscore_support, UndefinedMetricWarning + my_assert = assert_warns_message + for average in [None, 'weighted', 'macro']: + msg = ('Precision and F-score are ill-defined and ' + 'being set to 0.0 in labels with no predicted samples.') + my_assert(w, msg, f, [0, 1, 2], [1, 1, 2], average=average) + + msg = ('Recall and F-score are ill-defined and ' + 'being set to 0.0 in labels with no true samples.') + my_assert(w, msg, f, [1, 1, 2], [0, 1, 2], average=average) + + # average of per-sample scores + msg = ('Precision and F-score are ill-defined and ' + 'being set to 0.0 in samples with no predicted labels.') + my_assert(w, msg, f, np.array([[1, 0], [1, 0]]), + np.array([[1, 0], [0, 0]]), average='samples') + + msg = ('Recall and F-score are ill-defined and ' + 'being set to 0.0 in samples with no true labels.') + my_assert(w, msg, f, np.array([[1, 0], [0, 0]]), + np.array([[1, 0], [1, 0]]), + average='samples') + + # single score: micro-average + msg = ('Precision and F-score are ill-defined and ' + 'being set to 0.0 due to no predicted samples.') + my_assert(w, msg, f, np.array([[1, 1], [1, 1]]), + np.array([[0, 0], [0, 0]]), average='micro') + + msg = ('Recall and F-score are ill-defined and ' + 'being set to 0.0 due to no true samples.') + my_assert(w, msg, f, np.array([[0, 0], [0, 0]]), + np.array([[1, 1], [1, 1]]), average='micro') + + # single postive label + msg = ('Precision and F-score are ill-defined and ' + 'being set to 0.0 due to no predicted samples.') + my_assert(w, msg, f, [1, 1], [-1, -1], average='macro') + + msg = ('Recall and F-score are ill-defined and ' + 'being set to 0.0 due to no true samples.') + my_assert(w, msg, f, [-1, -1], [1, 1], average='macro') + + +def test_recall_warnings(): + assert_no_warnings(recall_score, + np.array([[1, 1], [1, 1]]), + np.array([[0, 0], [0, 0]]), + average='micro') + clean_warning_registry() + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter('always') + recall_score(np.array([[0, 0], [0, 0]]), + np.array([[1, 1], [1, 1]]), + average='micro') + assert_equal(str(record.pop().message), + 'Recall is ill-defined and ' + 'being set to 0.0 due to no true samples.') + + +def test_precision_warnings(): + clean_warning_registry() + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter('always') + + precision_score(np.array([[1, 1], [1, 1]]), + np.array([[0, 0], [0, 0]]), + average='micro') + assert_equal(str(record.pop().message), + 'Precision is ill-defined and ' + 'being set to 0.0 due to no predicted samples.') + + assert_no_warnings(precision_score, + np.array([[0, 0], [0, 0]]), + np.array([[1, 1], [1, 1]]), + average='micro') + + +def test_fscore_warnings(): + clean_warning_registry() + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter('always') + + for score in [f1_score, partial(fbeta_score, beta=2)]: + score(np.array([[1, 1], [1, 1]]), + np.array([[0, 0], [0, 0]]), + average='micro') + assert_equal(str(record.pop().message), + 'F-score is ill-defined and ' + 'being set to 0.0 due to no predicted samples.') + score(np.array([[0, 0], [0, 0]]), + np.array([[1, 1], [1, 1]]), + average='micro') + assert_equal(str(record.pop().message), + 'F-score is ill-defined and ' + 'being set to 0.0 due to no true samples.') + + +def test_prf_average_compat(): + """Ensure warning if f1_score et al.'s average is implicit for multiclass + """ + y_true = [1, 2, 3, 3] + y_pred = [1, 2, 3, 1] + y_true_bin = [0, 1, 1] + y_pred_bin = [0, 1, 0] + + for metric in [precision_score, recall_score, f1_score, + partial(fbeta_score, beta=2)]: + score = assert_warns(DeprecationWarning, metric, y_true, y_pred) + score_weighted = assert_no_warnings(metric, y_true, y_pred, + average='weighted') + assert_equal(score, score_weighted, + 'average does not act like "weighted" by default') + + # check binary passes without warning + assert_no_warnings(metric, y_true_bin, y_pred_bin) + + # but binary with pos_label=None should behave like multiclass + score = assert_warns(DeprecationWarning, metric, + y_true_bin, y_pred_bin, pos_label=None) + score_weighted = assert_no_warnings(metric, y_true_bin, y_pred_bin, + pos_label=None, average='weighted') + assert_equal(score, score_weighted, + 'average does not act like "weighted" by default with ' + 'binary data and pos_label=None') + + +@ignore_warnings # sequence of sequences is deprecated +def test__check_targets(): + """Check that _check_targets correctly merges target types, squeezes + output and fails if input lengths differ.""" + IND = 'multilabel-indicator' + SEQ = 'multilabel-sequences' + MC = 'multiclass' + BIN = 'binary' + CNT = 'continuous' + MMC = 'multiclass-multioutput' + MCN = 'continuous-multioutput' + # all of length 3 + EXAMPLES = [ + (IND, np.array([[0, 1, 1], [1, 0, 0], [0, 0, 1]])), + # must not be considered binary + (IND, np.array([[0, 1], [1, 0], [1, 1]])), + (SEQ, [[2, 3], [1], [3]]), + (MC, [2, 3, 1]), + (BIN, [0, 1, 1]), + (CNT, [0., 1.5, 1.]), + (MC, np.array([[2], [3], [1]])), + (BIN, np.array([[0], [1], [1]])), + (CNT, np.array([[0.], [1.5], [1.]])), + (MMC, np.array([[0, 2], [1, 3], [2, 3]])), + (MCN, np.array([[0.5, 2.], [1.1, 3.], [2., 3.]])), + ] + # expected type given input types, or None for error + # (types will be tried in either order) + EXPECTED = { + (IND, IND): IND, + (SEQ, SEQ): IND, + (MC, MC): MC, + (BIN, BIN): BIN, + + (IND, SEQ): None, + (MC, SEQ): None, + (BIN, SEQ): None, + (MC, IND): None, + (BIN, IND): None, + (BIN, MC): MC, + + # Disallowed types + (CNT, CNT): None, + (MMC, MMC): None, + (MCN, MCN): None, + (IND, CNT): None, + (SEQ, CNT): None, + (MC, CNT): None, + (BIN, CNT): None, + (MMC, CNT): None, + (MCN, CNT): None, + (IND, MMC): None, + (SEQ, MMC): None, + (MC, MMC): None, + (BIN, MMC): None, + (MCN, MMC): None, + (IND, MCN): None, + (SEQ, MCN): None, + (MC, MCN): None, + (BIN, MCN): None, + } + + for (type1, y1), (type2, y2) in product(EXAMPLES, repeat=2): + try: + expected = EXPECTED[type1, type2] + except KeyError: + expected = EXPECTED[type2, type1] + if expected is None: + assert_raises(ValueError, _check_targets, y1, y2) + + if type1 != type2: + assert_raise_message( + ValueError, + "Can't handle mix of {0} and {1}".format(type1, type2), + _check_targets, y1, y2) + + else: + if type1 not in (BIN, MC, SEQ, IND): + assert_raise_message(ValueError, + "{0} is not supported".format(type1), + _check_targets, y1, y2) + + else: + merged_type, y1out, y2out = _check_targets(y1, y2) + assert_equal(merged_type, expected) + if merged_type.startswith('multilabel'): + assert_equal(y1out.format, 'csr') + assert_equal(y2out.format, 'csr') + else: + assert_array_equal(y1out, np.squeeze(y1)) + assert_array_equal(y2out, np.squeeze(y2)) + assert_raises(ValueError, _check_targets, y1[:-1], y2) + + +def test_hinge_loss_binary(): + y_true = np.array([-1, 1, 1, -1]) + pred_decision = np.array([-8.5, 0.5, 1.5, -0.3]) + assert_equal(hinge_loss(y_true, pred_decision), 1.2 / 4) + + y_true = np.array([0, 2, 2, 0]) + pred_decision = np.array([-8.5, 0.5, 1.5, -0.3]) + assert_equal(hinge_loss(y_true, pred_decision), 1.2 / 4) + + +def test_hinge_loss_multiclass(): + pred_decision = np.array([ + [0.36, -0.17, -0.58, -0.99], + [-0.54, -0.37, -0.48, -0.58], + [-1.45, -0.58, -0.38, -0.17], + [-0.54, -0.38, -0.48, -0.58], + [-2.36, -0.79, -0.27, 0.24], + [-1.45, -0.58, -0.38, -0.17] + ]) + y_true = np.array([0, 1, 2, 1, 3, 2]) + dummy_losses = np.array([ + 1 - pred_decision[0][0] + pred_decision[0][1], + 1 - pred_decision[1][1] + pred_decision[1][2], + 1 - pred_decision[2][2] + pred_decision[2][3], + 1 - pred_decision[3][1] + pred_decision[3][2], + 1 - pred_decision[4][3] + pred_decision[4][2], + 1 - pred_decision[5][2] + pred_decision[5][3] + ]) + dummy_losses[dummy_losses <= 0] = 0 + dummy_hinge_loss = np.mean(dummy_losses) + assert_equal(hinge_loss(y_true, pred_decision), + dummy_hinge_loss) + + +def test_hinge_loss_multiclass_missing_labels_with_labels_none(): + y_true = np.array([0, 1, 2, 2]) + pred_decision = np.array([ + [1.27, 0.034, -0.68, -1.40], + [-1.45, -0.58, -0.38, -0.17], + [-2.36, -0.79, -0.27, 0.24], + [-2.36, -0.79, -0.27, 0.24] + ]) + error_message = ("Please include all labels in y_true " + "or pass labels as third argument") + assert_raise_message(ValueError, + error_message, + hinge_loss, y_true, pred_decision) + + +def test_hinge_loss_multiclass_with_missing_labels(): + pred_decision = np.array([ + [0.36, -0.17, -0.58, -0.99], + [-0.55, -0.38, -0.48, -0.58], + [-1.45, -0.58, -0.38, -0.17], + [-0.55, -0.38, -0.48, -0.58], + [-1.45, -0.58, -0.38, -0.17] + ]) + y_true = np.array([0, 1, 2, 1, 2]) + labels = np.array([0, 1, 2, 3]) + dummy_losses = np.array([ + 1 - pred_decision[0][0] + pred_decision[0][1], + 1 - pred_decision[1][1] + pred_decision[1][2], + 1 - pred_decision[2][2] + pred_decision[2][3], + 1 - pred_decision[3][1] + pred_decision[3][2], + 1 - pred_decision[4][2] + pred_decision[4][3] + ]) + dummy_losses[dummy_losses <= 0] = 0 + dummy_hinge_loss = np.mean(dummy_losses) + assert_equal(hinge_loss(y_true, pred_decision, labels=labels), + dummy_hinge_loss) + + +def test_hinge_loss_multiclass_invariance_lists(): + # Currently, invariance of string and integer labels cannot be tested + # in common invariance tests because invariance tests for multiclass + # decision functions is not implemented yet. + y_true = ['blue', 'green', 'red', + 'green', 'white', 'red'] + pred_decision = [ + [0.36, -0.17, -0.58, -0.99], + [-0.55, -0.38, -0.48, -0.58], + [-1.45, -0.58, -0.38, -0.17], + [-0.55, -0.38, -0.48, -0.58], + [-2.36, -0.79, -0.27, 0.24], + [-1.45, -0.58, -0.38, -0.17]] + dummy_losses = np.array([ + 1 - pred_decision[0][0] + pred_decision[0][1], + 1 - pred_decision[1][1] + pred_decision[1][2], + 1 - pred_decision[2][2] + pred_decision[2][3], + 1 - pred_decision[3][1] + pred_decision[3][2], + 1 - pred_decision[4][3] + pred_decision[4][2], + 1 - pred_decision[5][2] + pred_decision[5][3] + ]) + dummy_losses[dummy_losses <= 0] = 0 + dummy_hinge_loss = np.mean(dummy_losses) + assert_equal(hinge_loss(y_true, pred_decision), + dummy_hinge_loss) + + +def test_log_loss(): + # binary case with symbolic labels ("no" < "yes") + y_true = ["no", "no", "no", "yes", "yes", "yes"] + y_pred = np.array([[0.5, 0.5], [0.1, 0.9], [0.01, 0.99], + [0.9, 0.1], [0.75, 0.25], [0.001, 0.999]]) + loss = log_loss(y_true, y_pred) + assert_almost_equal(loss, 1.8817971) + + # multiclass case; adapted from http://bit.ly/RJJHWA + y_true = [1, 0, 2] + y_pred = [[0.2, 0.7, 0.1], [0.6, 0.2, 0.2], [0.6, 0.1, 0.3]] + loss = log_loss(y_true, y_pred, normalize=True) + assert_almost_equal(loss, 0.6904911) + + # check that we got all the shapes and axes right + # by doubling the length of y_true and y_pred + y_true *= 2 + y_pred *= 2 + loss = log_loss(y_true, y_pred, normalize=False) + assert_almost_equal(loss, 0.6904911 * 6, decimal=6) + + # check eps and handling of absolute zero and one probabilities + y_pred = np.asarray(y_pred) > .5 + loss = log_loss(y_true, y_pred, normalize=True, eps=.1) + assert_almost_equal(loss, log_loss(y_true, np.clip(y_pred, .1, .9))) + + # raise error if number of classes are not equal. + y_true = [1, 0, 2] + y_pred = [[0.2, 0.7], [0.6, 0.5], [0.4, 0.1]] + assert_raises(ValueError, log_loss, y_true, y_pred) + + # case when y_true is a string array object + y_true = ["ham", "spam", "spam", "ham"] + y_pred = [[0.2, 0.7], [0.6, 0.5], [0.4, 0.1], [0.7, 0.2]] + loss = log_loss(y_true, y_pred) + assert_almost_equal(loss, 1.0383217, decimal=6) + + +def test_brier_score_loss(): + """Check brier_score_loss function""" + y_true = np.array([0, 1, 1, 0, 1, 1]) + y_pred = np.array([0.1, 0.8, 0.9, 0.3, 1., 0.95]) + true_score = linalg.norm(y_true - y_pred) ** 2 / len(y_true) + + assert_almost_equal(brier_score_loss(y_true, y_true), 0.0) + assert_almost_equal(brier_score_loss(y_true, y_pred), true_score) + assert_almost_equal(brier_score_loss(1. + y_true, y_pred), + true_score) + assert_almost_equal(brier_score_loss(2 * y_true - 1, y_pred), + true_score) + assert_raises(ValueError, brier_score_loss, y_true, y_pred[1:]) + assert_raises(ValueError, brier_score_loss, y_true, y_pred + 1.) + assert_raises(ValueError, brier_score_loss, y_true, y_pred - 1.) diff --git a/sklearn/metrics/tests/test_common.py b/sklearn/metrics/tests/test_common.py new file mode 100644 index 0000000000000..d04784f305538 --- /dev/null +++ b/sklearn/metrics/tests/test_common.py @@ -0,0 +1,1102 @@ +from __future__ import division, print_function + +from functools import partial +from itertools import product + +import numpy as np +import scipy.sparse as sp + +from sklearn.datasets import make_multilabel_classification +from sklearn.preprocessing import LabelBinarizer, MultiLabelBinarizer +from sklearn.utils.multiclass import type_of_target +from sklearn.utils.validation import check_random_state +from sklearn.utils import shuffle + +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_not_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import ignore_warnings + +from sklearn.metrics import accuracy_score +from sklearn.metrics import average_precision_score +from sklearn.metrics import brier_score_loss +from sklearn.metrics import confusion_matrix +from sklearn.metrics import coverage_error +from sklearn.metrics import explained_variance_score +from sklearn.metrics import f1_score +from sklearn.metrics import fbeta_score +from sklearn.metrics import hamming_loss +from sklearn.metrics import hinge_loss +from sklearn.metrics import jaccard_similarity_score +from sklearn.metrics import label_ranking_average_precision_score +from sklearn.metrics import log_loss +from sklearn.metrics import matthews_corrcoef +from sklearn.metrics import mean_absolute_error +from sklearn.metrics import mean_squared_error +from sklearn.metrics import median_absolute_error +from sklearn.metrics import precision_score +from sklearn.metrics import r2_score +from sklearn.metrics import recall_score +from sklearn.metrics import roc_auc_score +from sklearn.metrics import zero_one_loss + +# TODO Curve are currently not coverd by invariance test +# from sklearn.metrics import precision_recall_curve +# from sklearn.metrics import roc_curve + + +from sklearn.metrics.base import _average_binary_score + + +# Note toward developers about metric testing +# ------------------------------------------- +# It is often possible to write one general test for several metrics: +# +# - invariance properties, e.g. invariance to sample order +# - common behavior for an argument, e.g. the "normalize" with value True +# will return the mean of the metrics and with value False will return +# the sum of the metrics. +# +# In order to improve the overall metric testing, it is a good idea to write +# first a specific test for the given metric and then add a general test for +# all metrics that have the same behavior. +# +# Two types of datastructures are used in order to implement this system: +# dictionaries of metrics and lists of metrics wit common properties. +# +# Dictionaries of metrics +# ------------------------ +# The goal of having those dictionaries is to have an easy way to call a +# particular metric and associate a name to each function: +# +# - REGRESSION_METRICS: all regression metrics. +# - CLASSIFICATION_METRICS: all classification metrics +# which compare a ground truth and the estimated targets as returned by a +# classifier. +# - THRESHOLDED_METRICS: all classification metrics which +# compare a ground truth and a score, e.g. estimated probabilities or +# decision function (format might vary) +# +# Those dictionaries will be used to test systematically some invariance +# properties, e.g. invariance toward several input layout. +# + +REGRESSION_METRICS = { + "mean_absolute_error": mean_absolute_error, + "mean_squared_error": mean_squared_error, + "median_absolute_error": median_absolute_error, + "explained_variance_score": explained_variance_score, + "r2_score": r2_score, +} + +CLASSIFICATION_METRICS = { + "accuracy_score": accuracy_score, + "unnormalized_accuracy_score": partial(accuracy_score, normalize=False), + "confusion_matrix": confusion_matrix, + "hamming_loss": hamming_loss, + + "jaccard_similarity_score": jaccard_similarity_score, + "unnormalized_jaccard_similarity_score": + partial(jaccard_similarity_score, normalize=False), + + "zero_one_loss": zero_one_loss, + "unnormalized_zero_one_loss": partial(zero_one_loss, normalize=False), + + # These are needed to test averaging + "precision_score": precision_score, + "recall_score": recall_score, + "f1_score": f1_score, + "f2_score": partial(fbeta_score, beta=2), + "f0.5_score": partial(fbeta_score, beta=0.5), + "matthews_corrcoef_score": matthews_corrcoef, + + "weighted_f0.5_score": partial(fbeta_score, average="weighted", beta=0.5), + "weighted_f1_score": partial(f1_score, average="weighted"), + "weighted_f2_score": partial(fbeta_score, average="weighted", beta=2), + "weighted_precision_score": partial(precision_score, average="weighted"), + "weighted_recall_score": partial(recall_score, average="weighted"), + + "micro_f0.5_score": partial(fbeta_score, average="micro", beta=0.5), + "micro_f1_score": partial(f1_score, average="micro"), + "micro_f2_score": partial(fbeta_score, average="micro", beta=2), + "micro_precision_score": partial(precision_score, average="micro"), + "micro_recall_score": partial(recall_score, average="micro"), + + "macro_f0.5_score": partial(fbeta_score, average="macro", beta=0.5), + "macro_f1_score": partial(f1_score, average="macro"), + "macro_f2_score": partial(fbeta_score, average="macro", beta=2), + "macro_precision_score": partial(precision_score, average="macro"), + "macro_recall_score": partial(recall_score, average="macro"), + + "samples_f0.5_score": partial(fbeta_score, average="samples", beta=0.5), + "samples_f1_score": partial(f1_score, average="samples"), + "samples_f2_score": partial(fbeta_score, average="samples", beta=2), + "samples_precision_score": partial(precision_score, average="samples"), + "samples_recall_score": partial(recall_score, average="samples"), +} + +THRESHOLDED_METRICS = { + "coverage_error": coverage_error, + + "log_loss": log_loss, + "unnormalized_log_loss": partial(log_loss, normalize=False), + + "hinge_loss": hinge_loss, + + "brier_score_loss": brier_score_loss, + + "roc_auc_score": roc_auc_score, + "weighted_roc_auc": partial(roc_auc_score, average="weighted"), + "samples_roc_auc": partial(roc_auc_score, average="samples"), + "micro_roc_auc": partial(roc_auc_score, average="micro"), + "macro_roc_auc": partial(roc_auc_score, average="macro"), + + "average_precision_score": average_precision_score, + "weighted_average_precision_score": + partial(average_precision_score, average="weighted"), + "samples_average_precision_score": + partial(average_precision_score, average="samples"), + "micro_average_precision_score": + partial(average_precision_score, average="micro"), + "macro_average_precision_score": + partial(average_precision_score, average="macro"), + "label_ranking_average_precision_score": + label_ranking_average_precision_score, +} + +ALL_METRICS = dict() +ALL_METRICS.update(THRESHOLDED_METRICS) +ALL_METRICS.update(CLASSIFICATION_METRICS) +ALL_METRICS.update(REGRESSION_METRICS) + +# Lists of metrics with common properties +# --------------------------------------- +# Lists of metrics with common properties are used to test systematically some +# functionalities and invariance, e.g. SYMMETRIC_METRICS lists all metrics that +# are symmetric with respect to their input argument y_true and y_pred. +# +# When you add a new metric or functionality, check if a general test +# is already written. + +# Metric undefined with "binary" or "multiclass" input +METRIC_UNDEFINED_MULTICLASS = [ + "samples_f0.5_score", "samples_f1_score", "samples_f2_score", + "samples_precision_score", "samples_recall_score", + + # Those metrics don't support multiclass outputs + "average_precision_score", "weighted_average_precision_score", + "micro_average_precision_score", "macro_average_precision_score", + "samples_average_precision_score", + + "label_ranking_average_precision_score", + + "roc_auc_score", "micro_roc_auc", "weighted_roc_auc", + "macro_roc_auc", "samples_roc_auc", + + "coverage_error", + "brier_score_loss" +] + +# Metrics with an "average" argument +METRICS_WITH_AVERAGING = [ + "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score" +] + +# Treshold-based metrics with an "average" argument +THRESHOLDED_METRICS_WITH_AVERAGING = [ + "roc_auc_score", "average_precision_score", +] + +# Metrics with a "pos_label" argument +METRICS_WITH_POS_LABEL = [ + "roc_curve", + + "brier_score_loss", + + "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", + + # pos_label support deprecated; to be removed in 0.18: + "weighted_f0.5_score", "weighted_f1_score", "weighted_f2_score", + "weighted_precision_score", "weighted_recall_score", + + "micro_f0.5_score", "micro_f1_score", "micro_f2_score", + "micro_precision_score", "micro_recall_score", + + "macro_f0.5_score", "macro_f1_score", "macro_f2_score", + "macro_precision_score", "macro_recall_score", +] + +# Metrics with a "labels" argument +# TODO: Handle multi_class metrics that has a labels argument as well as a +# decision function argument. e.g hinge_loss +METRICS_WITH_LABELS = [ + "confusion_matrix", + + "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", + + "weighted_f0.5_score", "weighted_f1_score", "weighted_f2_score", + "weighted_precision_score", "weighted_recall_score", + + "micro_f0.5_score", "micro_f1_score", "micro_f2_score", + "micro_precision_score", "micro_recall_score", + + "macro_f0.5_score", "macro_f1_score", "macro_f2_score", + "macro_precision_score", "macro_recall_score", +] + +# Metrics with a "normalize" option +METRICS_WITH_NORMALIZE_OPTION = [ + "accuracy_score", + "jaccard_similarity_score", + "zero_one_loss", +] + +# Threshold-based metrics with "multilabel-indicator" format support +THRESHOLDED_MULTILABEL_METRICS = [ + "log_loss", + "unnormalized_log_loss", + + "roc_auc_score", "weighted_roc_auc", "samples_roc_auc", + "micro_roc_auc", "macro_roc_auc", + + "average_precision_score", "weighted_average_precision_score", + "samples_average_precision_score", "micro_average_precision_score", + "macro_average_precision_score", + + "coverage_error", +] + +# Classification metrics with "multilabel-indicator" and +# "multilabel-sequence" format support +MULTILABELS_METRICS = [ + "accuracy_score", "unnormalized_accuracy_score", + "hamming_loss", + "jaccard_similarity_score", "unnormalized_jaccard_similarity_score", + "zero_one_loss", "unnormalized_zero_one_loss", + + "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", + + "weighted_f0.5_score", "weighted_f1_score", "weighted_f2_score", + "weighted_precision_score", "weighted_recall_score", + + "micro_f0.5_score", "micro_f1_score", "micro_f2_score", + "micro_precision_score", "micro_recall_score", + + "macro_f0.5_score", "macro_f1_score", "macro_f2_score", + "macro_precision_score", "macro_recall_score", + + "samples_f0.5_score", "samples_f1_score", "samples_f2_score", + "samples_precision_score", "samples_recall_score", +] + +# Regression metrics with "multioutput-continuous" format support +MULTIOUTPUT_METRICS = [ + "mean_absolute_error", "mean_squared_error", "r2_score", +] + +# Symmetric with respect to their input arguments y_true and y_pred +# metric(y_true, y_pred) == metric(y_pred, y_true). +SYMMETRIC_METRICS = [ + "accuracy_score", "unnormalized_accuracy_score", + "hamming_loss", + "jaccard_similarity_score", "unnormalized_jaccard_similarity_score", + "zero_one_loss", "unnormalized_zero_one_loss", + + "f1_score", "weighted_f1_score", "micro_f1_score", "macro_f1_score", + + "matthews_corrcoef_score", "mean_absolute_error", "mean_squared_error", + "median_absolute_error" + +] + +# Asymmetric with respect to their input arguments y_true and y_pred +# metric(y_true, y_pred) != metric(y_pred, y_true). +NOT_SYMMETRIC_METRICS = [ + "explained_variance_score", + "r2_score", + "confusion_matrix", + + "precision_score", "recall_score", "f2_score", "f0.5_score", + + "weighted_f0.5_score", "weighted_f2_score", "weighted_precision_score", + "weighted_recall_score", + + "micro_f0.5_score", "micro_f2_score", "micro_precision_score", + "micro_recall_score", + + "macro_f0.5_score", "macro_f2_score", "macro_precision_score", + "macro_recall_score", "log_loss", "hinge_loss" +] + + +# No Sample weight support +METRICS_WITHOUT_SAMPLE_WEIGHT = [ + "confusion_matrix", + "hamming_loss", + "matthews_corrcoef_score", + "median_absolute_error", +] + + +@ignore_warnings +def test_symmetry(): + """Test the symmetry of score and loss functions""" + random_state = check_random_state(0) + y_true = random_state.randint(0, 2, size=(20, )) + y_pred = random_state.randint(0, 2, size=(20, )) + + # We shouldn't forget any metrics + assert_equal(set(SYMMETRIC_METRICS).union(NOT_SYMMETRIC_METRICS, + THRESHOLDED_METRICS, + METRIC_UNDEFINED_MULTICLASS), + set(ALL_METRICS)) + + assert_equal( + set(SYMMETRIC_METRICS).intersection(set(NOT_SYMMETRIC_METRICS)), + set([])) + + # Symmetric metric + for name in SYMMETRIC_METRICS: + metric = ALL_METRICS[name] + assert_almost_equal(metric(y_true, y_pred), + metric(y_pred, y_true), + err_msg="%s is not symmetric" % name) + + # Not symmetric metrics + for name in NOT_SYMMETRIC_METRICS: + metric = ALL_METRICS[name] + assert_true(np.any(metric(y_true, y_pred) != metric(y_pred, y_true)), + msg="%s seems to be symmetric" % name) + + +@ignore_warnings +def test_sample_order_invariance(): + random_state = check_random_state(0) + y_true = random_state.randint(0, 2, size=(20, )) + y_pred = random_state.randint(0, 2, size=(20, )) + y_true_shuffle, y_pred_shuffle = shuffle(y_true, y_pred, random_state=0) + + for name, metric in ALL_METRICS.items(): + if name in METRIC_UNDEFINED_MULTICLASS: + continue + + assert_almost_equal(metric(y_true, y_pred), + metric(y_true_shuffle, y_pred_shuffle), + err_msg="%s is not sample order invariant" + % name) + + +@ignore_warnings +def test_sample_order_invariance_multilabel_and_multioutput(): + random_state = check_random_state(0) + + # Generate some data + y_true = random_state.randint(0, 2, size=(20, 25)) + y_pred = random_state.randint(0, 2, size=(20, 25)) + y_score = random_state.normal(size=y_true.shape) + + y_true_shuffle, y_pred_shuffle, y_score_shuffle = shuffle(y_true, + y_pred, + y_score, + random_state=0) + + for name in MULTILABELS_METRICS: + metric = ALL_METRICS[name] + assert_almost_equal(metric(y_true, y_pred), + metric(y_true_shuffle, y_pred_shuffle), + err_msg="%s is not sample order invariant" + % name) + + for name in THRESHOLDED_MULTILABEL_METRICS: + metric = ALL_METRICS[name] + assert_almost_equal(metric(y_true, y_score), + metric(y_true_shuffle, y_score_shuffle), + err_msg="%s is not sample order invariant" + % name) + + for name in MULTIOUTPUT_METRICS: + metric = ALL_METRICS[name] + assert_almost_equal(metric(y_true, y_score), + metric(y_true_shuffle, y_score_shuffle), + err_msg="%s is not sample order invariant" + % name) + assert_almost_equal(metric(y_true, y_pred), + metric(y_true_shuffle, y_pred_shuffle), + err_msg="%s is not sample order invariant" + % name) + + +@ignore_warnings +def test_format_invariance_with_1d_vectors(): + random_state = check_random_state(0) + y1 = random_state.randint(0, 2, size=(20, )) + y2 = random_state.randint(0, 2, size=(20, )) + + y1_list = list(y1) + y2_list = list(y2) + + y1_1d, y2_1d = np.array(y1), np.array(y2) + assert_equal(y1_1d.ndim, 1) + assert_equal(y2_1d.ndim, 1) + y1_column = np.reshape(y1_1d, (-1, 1)) + y2_column = np.reshape(y2_1d, (-1, 1)) + y1_row = np.reshape(y1_1d, (1, -1)) + y2_row = np.reshape(y2_1d, (1, -1)) + + for name, metric in ALL_METRICS.items(): + if name in METRIC_UNDEFINED_MULTICLASS: + continue + + measure = metric(y1, y2) + + assert_almost_equal(metric(y1_list, y2_list), measure, + err_msg="%s is not representation invariant " + "with list" % name) + + assert_almost_equal(metric(y1_1d, y2_1d), measure, + err_msg="%s is not representation invariant " + "with np-array-1d" % name) + + assert_almost_equal(metric(y1_column, y2_column), measure, + err_msg="%s is not representation invariant " + "with np-array-column" % name) + + # Mix format support + assert_almost_equal(metric(y1_1d, y2_list), measure, + err_msg="%s is not representation invariant " + "with mix np-array-1d and list" % name) + + assert_almost_equal(metric(y1_list, y2_1d), measure, + err_msg="%s is not representation invariant " + "with mix np-array-1d and list" % name) + + assert_almost_equal(metric(y1_1d, y2_column), measure, + err_msg="%s is not representation invariant " + "with mix np-array-1d and np-array-column" + % name) + + assert_almost_equal(metric(y1_column, y2_1d), measure, + err_msg="%s is not representation invariant " + "with mix np-array-1d and np-array-column" + % name) + + assert_almost_equal(metric(y1_list, y2_column), measure, + err_msg="%s is not representation invariant " + "with mix list and np-array-column" + % name) + + assert_almost_equal(metric(y1_column, y2_list), measure, + err_msg="%s is not representation invariant " + "with mix list and np-array-column" + % name) + + # These mix representations aren't allowed + assert_raises(ValueError, metric, y1_1d, y2_row) + assert_raises(ValueError, metric, y1_row, y2_1d) + assert_raises(ValueError, metric, y1_list, y2_row) + assert_raises(ValueError, metric, y1_row, y2_list) + assert_raises(ValueError, metric, y1_column, y2_row) + assert_raises(ValueError, metric, y1_row, y2_column) + + # NB: We do not test for y1_row, y2_row as these may be + # interpreted as multilabel or multioutput data. + if (name not in (MULTIOUTPUT_METRICS + THRESHOLDED_MULTILABEL_METRICS + + MULTILABELS_METRICS)): + assert_raises(ValueError, metric, y1_row, y2_row) + + +@ignore_warnings +def test_invariance_string_vs_numbers_labels(): + """Ensure that classification metrics with string labels""" + random_state = check_random_state(0) + y1 = random_state.randint(0, 2, size=(20, )) + y2 = random_state.randint(0, 2, size=(20, )) + + y1_str = np.array(["eggs", "spam"])[y1] + y2_str = np.array(["eggs", "spam"])[y2] + + pos_label_str = "spam" + labels_str = ["eggs", "spam"] + + for name, metric in CLASSIFICATION_METRICS.items(): + if name in METRIC_UNDEFINED_MULTICLASS: + continue + + measure_with_number = metric(y1, y2) + + # Ugly, but handle case with a pos_label and label + metric_str = metric + if name in METRICS_WITH_POS_LABEL: + metric_str = partial(metric_str, pos_label=pos_label_str) + + measure_with_str = metric_str(y1_str, y2_str) + + assert_array_equal(measure_with_number, measure_with_str, + err_msg="{0} failed string vs number invariance " + "test".format(name)) + + measure_with_strobj = metric_str(y1_str.astype('O'), + y2_str.astype('O')) + assert_array_equal(measure_with_number, measure_with_strobj, + err_msg="{0} failed string object vs number " + "invariance test".format(name)) + + if name in METRICS_WITH_LABELS: + metric_str = partial(metric_str, labels=labels_str) + measure_with_str = metric_str(y1_str, y2_str) + assert_array_equal(measure_with_number, measure_with_str, + err_msg="{0} failed string vs number " + "invariance test".format(name)) + + measure_with_strobj = metric_str(y1_str.astype('O'), + y2_str.astype('O')) + assert_array_equal(measure_with_number, measure_with_strobj, + err_msg="{0} failed string vs number " + "invariance test".format(name)) + + for name, metric in THRESHOLDED_METRICS.items(): + if name in ("log_loss", "hinge_loss", "unnormalized_log_loss", + "brier_score_loss"): + # Ugly, but handle case with a pos_label and label + metric_str = metric + if name in METRICS_WITH_POS_LABEL: + metric_str = partial(metric_str, pos_label=pos_label_str) + + measure_with_number = metric(y1, y2) + measure_with_str = metric_str(y1_str, y2) + assert_array_equal(measure_with_number, measure_with_str, + err_msg="{0} failed string vs number " + "invariance test".format(name)) + + measure_with_strobj = metric(y1_str.astype('O'), y2) + assert_array_equal(measure_with_number, measure_with_strobj, + err_msg="{0} failed string object vs number " + "invariance test".format(name)) + else: + # TODO those metrics doesn't support string label yet + assert_raises(ValueError, metric, y1_str, y2) + assert_raises(ValueError, metric, y1_str.astype('O'), y2) + + +@ignore_warnings +def check_single_sample(name): + """Non-regression test: scores should work with a single sample. + + This is important for leave-one-out cross validation. + Score functions tested are those that formerly called np.squeeze, + which turns an array of size 1 into a 0-d array (!). + """ + metric = ALL_METRICS[name] + + # assert that no exception is thrown + for i, j in product([0, 1], repeat=2): + metric([i], [j]) + + +@ignore_warnings +def check_single_sample_multioutput(name): + metric = ALL_METRICS[name] + for i, j, k, l in product([0, 1], repeat=4): + metric(np.array([[i, j]]), np.array([[k, l]])) + + +def test_single_sample(): + for name in ALL_METRICS: + if name in METRIC_UNDEFINED_MULTICLASS or name in THRESHOLDED_METRICS: + # Those metrics are not always defined with one sample + # or in multiclass classification + continue + + yield check_single_sample, name + + for name in MULTIOUTPUT_METRICS + MULTILABELS_METRICS: + yield check_single_sample_multioutput, name + + +def test_multioutput_number_of_output_differ(): + y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]]) + y_pred = np.array([[0, 0], [1, 0], [0, 0]]) + + for name in MULTIOUTPUT_METRICS: + metric = ALL_METRICS[name] + assert_raises(ValueError, metric, y_true, y_pred) + + +def test_multioutput_regression_invariance_to_dimension_shuffling(): + # test invariance to dimension shuffling + random_state = check_random_state(0) + y_true = random_state.uniform(0, 2, size=(20, 5)) + y_pred = random_state.uniform(0, 2, size=(20, 5)) + + for name in MULTIOUTPUT_METRICS: + metric = ALL_METRICS[name] + error = metric(y_true, y_pred) + + for _ in range(3): + perm = random_state.permutation(y_true.shape[1]) + assert_almost_equal(metric(y_true[:, perm], y_pred[:, perm]), + error, + err_msg="%s is not dimension shuffling " + "invariant" % name) + + +@ignore_warnings +def test_multilabel_representation_invariance(): + # Generate some data + n_classes = 4 + n_samples = 50 + # using sequence of sequences is deprecated, but still tested + make_ml = ignore_warnings(make_multilabel_classification) + _, y1 = make_ml(n_features=1, n_classes=n_classes, random_state=0, + n_samples=n_samples) + _, y2 = make_ml(n_features=1, n_classes=n_classes, random_state=1, + n_samples=n_samples) + + # Be sure to have at least one empty label + y1 += ([], ) + y2 += ([], ) + + # NOTE: The "sorted" trick is necessary to shuffle labels, because it + # allows to return the shuffled tuple. + rng = check_random_state(42) + shuffled = lambda x: sorted(x, key=lambda *args: rng.rand()) + y1_shuffle = [shuffled(x) for x in y1] + y2_shuffle = [shuffled(x) for x in y2] + + # Let's have redundant labels + y2_redundant = [x * rng.randint(1, 4) for x in y2] + + # Binary indicator matrix format + lb = MultiLabelBinarizer().fit([range(n_classes)]) + y1_binary_indicator = lb.transform(y1) + y2_binary_indicator = lb.transform(y2) + + y1_sparse_indicator = sp.coo_matrix(y1_binary_indicator) + y2_sparse_indicator = sp.coo_matrix(y2_binary_indicator) + + y1_shuffle_binary_indicator = lb.transform(y1_shuffle) + y2_shuffle_binary_indicator = lb.transform(y2_shuffle) + + for name in MULTILABELS_METRICS: + metric = ALL_METRICS[name] + + # XXX cruel hack to work with partial functions + if isinstance(metric, partial): + metric.__module__ = 'tmp' + metric.__name__ = name + + measure = metric(y1_binary_indicator, y2_binary_indicator) + + # Check representation invariance + assert_almost_equal(metric(y1_sparse_indicator, + y2_sparse_indicator), + measure, + err_msg="%s failed representation invariance " + "between dense and sparse indicator " + "formats." % name) + + # Check shuffling invariance with dense binary indicator matrix + assert_almost_equal(metric(y1_shuffle_binary_indicator, + y2_shuffle_binary_indicator), measure, + err_msg="%s failed shuffling invariance " + " with dense binary indicator format." + % name) + + # Check deprecation warnings related to sequence of sequences + deprecated_metric = partial(assert_warns, DeprecationWarning, metric) + + # Check representation invariance + assert_almost_equal(deprecated_metric(y1, y2), + measure, + err_msg="%s failed representation invariance " + "between list of list of labels " + "format and dense binary indicator " + "format." % name) + + # Check invariance with redundant labels with list of labels + assert_almost_equal(deprecated_metric(y1, y2_redundant), measure, + err_msg="%s failed rendundant label invariance" + % name) + + # Check shuffling invariance with list of labels + assert_almost_equal(deprecated_metric(y1_shuffle, y2_shuffle), measure, + err_msg="%s failed shuffling invariance " + "with list of list of labels format." + % name) + + # Check raises error with mix input representation + assert_raises(ValueError, deprecated_metric, y1, y2_binary_indicator) + assert_raises(ValueError, deprecated_metric, y1_binary_indicator, y2) + + +def test_normalize_option_binary_classification(n_samples=20): + # Test in the binary case + random_state = check_random_state(0) + y_true = random_state.randint(0, 2, size=(n_samples, )) + y_pred = random_state.randint(0, 2, size=(n_samples, )) + + for name in METRICS_WITH_NORMALIZE_OPTION: + metrics = ALL_METRICS[name] + measure = metrics(y_true, y_pred, normalize=True) + assert_greater(measure, 0, + msg="We failed to test correctly the normalize option") + assert_almost_equal(metrics(y_true, y_pred, normalize=False) + / n_samples, measure) + + +def test_normalize_option_multiclasss_classification(): + # Test in the multiclass case + random_state = check_random_state(0) + y_true = random_state.randint(0, 4, size=(20, )) + y_pred = random_state.randint(0, 4, size=(20, )) + n_samples = y_true.shape[0] + + for name in METRICS_WITH_NORMALIZE_OPTION: + metrics = ALL_METRICS[name] + measure = metrics(y_true, y_pred, normalize=True) + assert_greater(measure, 0, + msg="We failed to test correctly the normalize option") + assert_almost_equal(metrics(y_true, y_pred, normalize=False) + / n_samples, measure) + + +def test_normalize_option_multilabel_classification(): + # Test in the multilabel case + n_classes = 4 + n_samples = 100 + # using sequence of sequences is deprecated, but still tested + make_ml = ignore_warnings(make_multilabel_classification) + _, y_true = make_ml(n_features=1, n_classes=n_classes, + random_state=0, n_samples=n_samples) + _, y_pred = make_ml(n_features=1, n_classes=n_classes, + random_state=1, n_samples=n_samples) + + # Be sure to have at least one empty label + y_true += ([], ) + y_pred += ([], ) + n_samples += 1 + + lb = MultiLabelBinarizer().fit([range(n_classes)]) + y_true_binary_indicator = lb.transform(y_true) + y_pred_binary_indicator = lb.transform(y_pred) + + for name in METRICS_WITH_NORMALIZE_OPTION: + metrics = ALL_METRICS[name] + + # List of list of labels + measure = assert_warns(DeprecationWarning, metrics, y_true, y_pred, + normalize=True) + assert_greater(measure, 0, + msg="We failed to test correctly the normalize option") + assert_almost_equal(ignore_warnings(metrics)(y_true, y_pred, + normalize=False) + / n_samples, measure, + err_msg="Failed with %s" % name) + + # Indicator matrix format + measure = metrics(y_true_binary_indicator, + y_pred_binary_indicator, normalize=True) + assert_greater(measure, 0, + msg="We failed to test correctly the normalize option") + assert_almost_equal(metrics(y_true_binary_indicator, + y_pred_binary_indicator, normalize=False) + / n_samples, measure, + err_msg="Failed with %s" % name) + + +@ignore_warnings +def _check_averaging(metric, y_true, y_pred, y_true_binarize, y_pred_binarize, + is_multilabel): + n_samples, n_classes = y_true_binarize.shape + + # No averaging + label_measure = metric(y_true, y_pred, average=None) + assert_array_almost_equal(label_measure, + [metric(y_true_binarize[:, i], + y_pred_binarize[:, i]) + for i in range(n_classes)]) + + # Micro measure + micro_measure = metric(y_true, y_pred, average="micro") + assert_almost_equal(micro_measure, metric(y_true_binarize.ravel(), + y_pred_binarize.ravel())) + + # Macro measure + macro_measure = metric(y_true, y_pred, average="macro") + assert_almost_equal(macro_measure, np.mean(label_measure)) + + # Weighted measure + weights = np.sum(y_true_binarize, axis=0, dtype=int) + + if np.sum(weights) != 0: + weighted_measure = metric(y_true, y_pred, average="weighted") + assert_almost_equal(weighted_measure, np.average(label_measure, + weights=weights)) + else: + weighted_measure = metric(y_true, y_pred, average="weighted") + assert_almost_equal(weighted_measure, 0) + + # Sample measure + if is_multilabel: + sample_measure = metric(y_true, y_pred, average="samples") + assert_almost_equal(sample_measure, + np.mean([metric(y_true_binarize[i], + y_pred_binarize[i]) + for i in range(n_samples)])) + + assert_raises(ValueError, metric, y_true, y_pred, average="unknown") + assert_raises(ValueError, metric, y_true, y_pred, average="garbage") + + +def check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, + y_score): + is_multilabel = type_of_target(y_true).startswith("multilabel") + + metric = ALL_METRICS[name] + + if name in METRICS_WITH_AVERAGING: + _check_averaging(metric, y_true, y_pred, y_true_binarize, + y_pred_binarize, is_multilabel) + elif name in THRESHOLDED_METRICS_WITH_AVERAGING: + _check_averaging(metric, y_true, y_score, y_true_binarize, + y_score, is_multilabel) + else: + raise ValueError("Metric is not recorded as having an average option") + + +def test_averaging_multiclass(n_samples=50, n_classes=3): + random_state = check_random_state(0) + y_true = random_state.randint(0, n_classes, size=(n_samples, )) + y_pred = random_state.randint(0, n_classes, size=(n_samples, )) + y_score = random_state.uniform(size=(n_samples, n_classes)) + + lb = LabelBinarizer().fit(y_true) + y_true_binarize = lb.transform(y_true) + y_pred_binarize = lb.transform(y_pred) + + for name in METRICS_WITH_AVERAGING: + yield (check_averaging, name, y_true, y_true_binarize, y_pred, + y_pred_binarize, y_score) + + +def test_averaging_multilabel(n_classes=5, n_samples=40): + _, y = make_multilabel_classification(n_features=1, n_classes=n_classes, + random_state=5, n_samples=n_samples, + return_indicator=True, + allow_unlabeled=False) + y_true = y[:20] + y_pred = y[20:] + y_score = check_random_state(0).normal(size=(20, n_classes)) + y_true_binarize = y_true + y_pred_binarize = y_pred + + for name in METRICS_WITH_AVERAGING + THRESHOLDED_METRICS_WITH_AVERAGING: + yield (check_averaging, name, y_true, y_true_binarize, y_pred, + y_pred_binarize, y_score) + + +def test_averaging_multilabel_all_zeroes(): + y_true = np.zeros((20, 3)) + y_pred = np.zeros((20, 3)) + y_score = np.zeros((20, 3)) + y_true_binarize = y_true + y_pred_binarize = y_pred + + for name in METRICS_WITH_AVERAGING: + yield (check_averaging, name, y_true, y_true_binarize, y_pred, + y_pred_binarize, y_score) + + # Test _average_binary_score for weight.sum() == 0 + binary_metric = (lambda y_true, y_score, average="macro": + _average_binary_score( + precision_score, y_true, y_score, average)) + _check_averaging(binary_metric, y_true, y_pred, y_true_binarize, + y_pred_binarize, is_multilabel=True) + + +def test_averaging_multilabel_all_ones(): + y_true = np.ones((20, 3)) + y_pred = np.ones((20, 3)) + y_score = np.ones((20, 3)) + y_true_binarize = y_true + y_pred_binarize = y_pred + + for name in METRICS_WITH_AVERAGING: + yield (check_averaging, name, y_true, y_true_binarize, y_pred, + y_pred_binarize, y_score) + + +@ignore_warnings +def check_sample_weight_invariance(name, metric, y1, y2): + rng = np.random.RandomState(0) + sample_weight = rng.randint(1, 10, size=len(y1)) + + # check that unit weights gives the same score as no weight + unweighted_score = metric(y1, y2, sample_weight=None) + assert_almost_equal( + unweighted_score, + metric(y1, y2, sample_weight=np.ones(shape=len(y1))), + err_msg="For %s sample_weight=None is not equivalent to " + "sample_weight=ones" % name) + + # check that the weighted and unweighted scores are unequal + weighted_score = metric(y1, y2, sample_weight=sample_weight) + assert_not_equal( + unweighted_score, weighted_score, + msg="Unweighted and weighted scores are unexpectedly " + "equal (%f) for %s" % (weighted_score, name)) + + # check that sample_weight can be a list + weighted_score_list = metric(y1, y2, + sample_weight=sample_weight.tolist()) + assert_almost_equal( + weighted_score, weighted_score_list, + err_msg="Weighted scores for array and list sample_weight input are " + "not equal (%f != %f) for %s" % ( + weighted_score, weighted_score_list, name)) + + # check that integer weights is the same as repeated samples + repeat_weighted_score = metric( + np.repeat(y1, sample_weight, axis=0), + np.repeat(y2, sample_weight, axis=0), sample_weight=None) + assert_almost_equal( + weighted_score, repeat_weighted_score, + err_msg="Weighting %s is not equal to repeating samples" % name) + + # check that ignoring a fraction of the samples is equivalent to setting + # the corresponding weights to zero + sample_weight_subset = sample_weight[1::2] + sample_weight_zeroed = np.copy(sample_weight) + sample_weight_zeroed[::2] = 0 + y1_subset = y1[1::2] + y2_subset = y2[1::2] + weighted_score_subset = metric(y1_subset, y2_subset, + sample_weight=sample_weight_subset) + weighted_score_zeroed = metric(y1, y2, + sample_weight=sample_weight_zeroed) + assert_almost_equal( + weighted_score_subset, weighted_score_zeroed, + err_msg=("Zeroing weights does not give the same result as " + "removing the corresponding samples (%f != %f) for %s" % + (weighted_score_zeroed, weighted_score_subset, name))) + + if not name.startswith('unnormalized'): + # check that the score is invariant under scaling of the weights by a + # common factor + for scaling in [2, 0.3]: + assert_almost_equal( + weighted_score, + metric(y1, y2, sample_weight=sample_weight * scaling), + err_msg="%s sample_weight is not invariant " + "under scaling" % name) + + # Check that if sample_weight.shape[0] != y_true.shape[0], it raised an + # error + assert_raises(Exception, metric, y1, y2, + sample_weight=np.hstack([sample_weight, sample_weight])) + + +def test_sample_weight_invariance(n_samples=50): + random_state = check_random_state(0) + + # binary output + random_state = check_random_state(0) + y_true = random_state.randint(0, 2, size=(n_samples, )) + y_pred = random_state.randint(0, 2, size=(n_samples, )) + y_score = random_state.random_sample(size=(n_samples,)) + for name in ALL_METRICS: + if (name in METRICS_WITHOUT_SAMPLE_WEIGHT or + name in METRIC_UNDEFINED_MULTICLASS): + continue + metric = ALL_METRICS[name] + if name in THRESHOLDED_METRICS: + yield check_sample_weight_invariance, name, metric, y_true, y_score + else: + yield check_sample_weight_invariance, name, metric, y_true, y_pred + + # multiclass + random_state = check_random_state(0) + y_true = random_state.randint(0, 5, size=(n_samples, )) + y_pred = random_state.randint(0, 5, size=(n_samples, )) + y_score = random_state.random_sample(size=(n_samples, 5)) + for name in ALL_METRICS: + if (name in METRICS_WITHOUT_SAMPLE_WEIGHT or + name in METRIC_UNDEFINED_MULTICLASS): + continue + metric = ALL_METRICS[name] + if name in THRESHOLDED_METRICS: + yield check_sample_weight_invariance, name, metric, y_true, y_score + else: + yield check_sample_weight_invariance, name, metric, y_true, y_pred + + # multilabel sequence + y_true = 2 * [(1, 2, ), (1, ), (0, ), (0, 1), (1, 2)] + y_pred = 2 * [(0, 2, ), (2, ), (0, ), (2, ), (1,)] + y_score = random_state.randn(10, 3) + + for name in MULTILABELS_METRICS: + if name in METRICS_WITHOUT_SAMPLE_WEIGHT: + continue + metric = ALL_METRICS[name] + + if name in THRESHOLDED_METRICS: + yield (check_sample_weight_invariance, name, metric, y_true, + y_score) + else: + yield (check_sample_weight_invariance, name, metric, y_true, + y_pred) + + # multilabel indicator + _, ya = make_multilabel_classification( + n_features=1, n_classes=20, + random_state=0, n_samples=100, + return_indicator=True, allow_unlabeled=False) + _, yb = make_multilabel_classification( + n_features=1, n_classes=20, + random_state=1, n_samples=100, + return_indicator=True, allow_unlabeled=False) + y_true = np.vstack([ya, yb]) + y_pred = np.vstack([ya, ya]) + y_score = random_state.randint(1, 4, size=y_true.shape) + + for name in (MULTILABELS_METRICS + THRESHOLDED_MULTILABEL_METRICS + + MULTIOUTPUT_METRICS): + if name in METRICS_WITHOUT_SAMPLE_WEIGHT: + continue + + metric = ALL_METRICS[name] + if name in THRESHOLDED_METRICS: + yield (check_sample_weight_invariance, name, metric, y_true, + y_score) + else: + yield (check_sample_weight_invariance, name, metric, y_true, + y_pred) + + +def test_no_averaging_labels(): + # test labels argument when not using averaging + # in multi-class and multi-label cases + y_true_multilabel = np.array([[1, 1, 0, 0], [1, 1, 0, 0]]) + y_pred_multilabel = np.array([[0, 0, 1, 1], [0, 1, 1, 0]]) + y_true_multiclass = np.array([1, 2, 3]) + y_pred_multiclass = np.array([1, 3, 4]) + labels = np.array([4, 1, 2, 3]) + _, inverse_labels = np.unique(labels, return_inverse=True) + + for name in METRICS_WITH_AVERAGING: + for y_true, y_pred in [[y_true_multiclass, y_pred_multiclass], + [y_true_multilabel, y_pred_multilabel]]: + if name not in MULTILABELS_METRICS and y_pred.shape[1] > 0: + continue + + metric = ALL_METRICS[name] + + score_labels = metric(y_true, y_pred, labels=labels, average=None) + score = metric(y_true, y_pred, average=None) + assert_array_equal(score_labels, score[inverse_labels]) diff --git a/sklearn/metrics/tests/test_metrics.py b/sklearn/metrics/tests/test_metrics.py deleted file mode 100644 index e111b2d475fd9..0000000000000 --- a/sklearn/metrics/tests/test_metrics.py +++ /dev/null @@ -1,405 +0,0 @@ -import random -import numpy as np - -from nose.tools import raises -from nose.tools import assert_true, assert_raises -from numpy.testing import assert_array_almost_equal -from numpy.testing import assert_array_equal -from numpy.testing import assert_equal, assert_almost_equal - -from ... import datasets -from ... import svm -from ..metrics import auc -from ..metrics import classification_report -from ..metrics import confusion_matrix -from ..metrics import explained_variance_score -from ..metrics import r2_score -from ..metrics import f1_score -from ..metrics import matthews_corrcoef -from ..metrics import mean_squared_error -from ..metrics import precision_recall_curve -from ..metrics import precision_recall_fscore_support -from ..metrics import precision_score -from ..metrics import recall_score -from ..metrics import roc_curve -from ..metrics import auc_score -from ..metrics import average_precision_score -from ..metrics import zero_one -from ..metrics import hinge_loss - - -def make_prediction(dataset=None, binary=False): - """Make some classification predictions on a toy dataset using a SVC - - If binary is True restrict to a binary classification problem instead of a - multiclass classification problem - """ - - if dataset is None: - # import some data to play with - dataset = datasets.load_iris() - - X = dataset.data - y = dataset.target - - if binary: - # restrict to a binary classification task - X, y = X[y < 2], y[y < 2] - - n_samples, n_features = X.shape - p = range(n_samples) - - random.seed(0) - random.shuffle(p) - X, y = X[p], y[p] - half = int(n_samples / 2) - - # add noisy features to make the problem harder and avoid perfect results - rng = np.random.RandomState(0) - X = np.c_[X, rng.randn(n_samples, 200 * n_features)] - - # run classifier, get class probabilities and label predictions - clf = svm.SVC(kernel='linear', probability=True) - probas_pred = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) - - if binary: - # only interested in probabilities of the positive case - # XXX: do we really want a special API for the binary case? - probas_pred = probas_pred[:, 1] - - y_pred = clf.predict(X[half:]) - y_true = y[half:] - return y_true, y_pred, probas_pred - - -def test_roc_curve(): - """Test Area under Receiver Operating Characteristic (ROC) curve""" - y_true, _, probas_pred = make_prediction(binary=True) - - fpr, tpr, thresholds = roc_curve(y_true, probas_pred) - roc_auc = auc(fpr, tpr) - assert_array_almost_equal(roc_auc, 0.80, decimal=2) - assert_almost_equal(roc_auc, auc_score(y_true, probas_pred)) - - -def test_roc_returns_consistency(): - """Test whether the returned threshold matches up with tpr""" - # make small toy dataset - y_true, _, probas_pred = make_prediction(binary=True) - fpr, tpr, thresholds = roc_curve(y_true, probas_pred) - - # use the given thresholds to determine the tpr - tpr_correct = [] - for t in range(len(thresholds)): - tp = np.sum((probas_pred >= thresholds[t]) & y_true) - p = np.sum(y_true) - tpr_correct.append(1.0 * tp / p) - - # compare tpr and tpr_correct to see if the thresholds' order was correct - assert_array_almost_equal(tpr, tpr_correct, decimal=2) - - -@raises(ValueError) -def test_roc_curve_multi(): - """roc_curve not applicable for multi-class problems""" - y_true, _, probas_pred = make_prediction(binary=False) - - fpr, tpr, thresholds = roc_curve(y_true, probas_pred) - - -def test_roc_curve_confidence(): - """roc_curve for confidence scores""" - y_true, _, probas_pred = make_prediction(binary=True) - - fpr, tpr, thresholds = roc_curve(y_true, probas_pred - 0.5) - roc_auc = auc(fpr, tpr) - assert_array_almost_equal(roc_auc, 0.80, decimal=2) - - -def test_roc_curve_hard(): - """roc_curve for hard decisions""" - y_true, pred, probas_pred = make_prediction(binary=True) - - # always predict one - trivial_pred = np.ones(y_true.shape) - fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) - roc_auc = auc(fpr, tpr) - assert_array_almost_equal(roc_auc, 0.50, decimal=2) - - # always predict zero - trivial_pred = np.zeros(y_true.shape) - fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) - roc_auc = auc(fpr, tpr) - assert_array_almost_equal(roc_auc, 0.50, decimal=2) - - # hard decisions - fpr, tpr, thresholds = roc_curve(y_true, pred) - roc_auc = auc(fpr, tpr) - assert_array_almost_equal(roc_auc, 0.74, decimal=2) - - -def test_auc(): - """Test Area Under Curve (AUC) computation""" - x = [0, 1] - y = [0, 1] - assert_array_almost_equal(auc(x, y), 0.5) - x = [1, 0] - y = [0, 1] - assert_array_almost_equal(auc(x, y), 0.5) - x = [0, 1] - y = [1, 1] - assert_array_almost_equal(auc(x, y), 1) - x = [0, 0.5, 1] - y = [0, 0.5, 1] - assert_array_almost_equal(auc(x, y), 0.5) - - -def test_auc_duplicate_values(): - """Test Area Under Curve (AUC) computation with duplicate values - - auc() was previously sorting the x and y arrays according to the indices - from numpy.argsort(x), which was reordering the tied 0's in this example - and resulting in an incorrect area computation. This test detects the - error. - """ - x = [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.5, 1.] - y = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, - 1., 1., 1., 1., 1., 1., 1., 1.] - assert_array_almost_equal(auc(x, y), 1.) - - -def test_precision_recall_f1_score_binary(): - """Test Precision Recall and F1 Score for binary classification task""" - y_true, y_pred, _ = make_prediction(binary=True) - - # detailed measures for each class - p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) - assert_array_almost_equal(p, [0.73, 0.75], 2) - assert_array_almost_equal(r, [0.76, 0.72], 2) - assert_array_almost_equal(f, [0.75, 0.74], 2) - assert_array_equal(s, [25, 25]) - - # individual scoring function that can be used for grid search: in the - # binary class case the score is the value of the measure for the positive - # class (e.g. label == 1) - ps = precision_score(y_true, y_pred) - assert_array_almost_equal(ps, 0.75, 2) - - rs = recall_score(y_true, y_pred) - assert_array_almost_equal(rs, 0.72, 2) - - fs = f1_score(y_true, y_pred) - assert_array_almost_equal(fs, 0.74, 2) - - -def test_confusion_matrix_binary(): - """Test confusion matrix - binary classification case""" - y_true, y_pred, _ = make_prediction(binary=True) - - cm = confusion_matrix(y_true, y_pred) - assert_array_equal(cm, [[19, 6], [7, 18]]) - - tp = cm[0, 0] - tn = cm[1, 1] - fp = cm[0, 1] - fn = cm[1, 0] - num = (tp * tn - fp * fn) - den = np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) - if den == 0.: - true_mcc = 0 - else: - true_mcc = num / den - mcc = matthews_corrcoef(y_true, y_pred) - assert_array_almost_equal(mcc, true_mcc, decimal=2) - assert_array_almost_equal(mcc, 0.48, decimal=2) - - -def test_precision_recall_f1_score_multiclass(): - """Test Precision Recall and F1 Score for multiclass classification task""" - y_true, y_pred, _ = make_prediction(binary=False) - - # compute scores with default labels introspection - p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) - assert_array_almost_equal(p, [0.82, 0.55, 0.47], 2) - assert_array_almost_equal(r, [0.92, 0.17, 0.90], 2) - assert_array_almost_equal(f, [0.87, 0.26, 0.62], 2) - assert_array_equal(s, [25, 30, 20]) - - # averaging tests - ps = precision_score(y_true, y_pred, pos_label=1, average='micro') - assert_array_almost_equal(ps, 0.61, 2) - - rs = recall_score(y_true, y_pred, average='micro') - assert_array_almost_equal(rs, 0.61, 2) - - fs = f1_score(y_true, y_pred, average='micro') - assert_array_almost_equal(fs, 0.61, 2) - - ps = precision_score(y_true, y_pred, average='macro') - assert_array_almost_equal(ps, 0.62, 2) - - rs = recall_score(y_true, y_pred, average='macro') - assert_array_almost_equal(rs, 0.66, 2) - - fs = f1_score(y_true, y_pred, average='macro') - assert_array_almost_equal(fs, 0.58, 2) - - ps = precision_score(y_true, y_pred, average='weighted') - assert_array_almost_equal(ps, 0.62, 2) - - rs = recall_score(y_true, y_pred, average='weighted') - assert_array_almost_equal(rs, 0.61, 2) - - fs = f1_score(y_true, y_pred, average='weighted') - assert_array_almost_equal(fs, 0.55, 2) - - # same prediction but with and explicit label ordering - p, r, f, s = precision_recall_fscore_support( - y_true, y_pred, labels=[0, 2, 1], average=None) - assert_array_almost_equal(p, [0.82, 0.47, 0.55], 2) - assert_array_almost_equal(r, [0.92, 0.90, 0.17], 2) - assert_array_almost_equal(f, [0.87, 0.62, 0.26], 2) - assert_array_equal(s, [25, 20, 30]) - - -def test_zero_precision_recall(): - """Check that pathological cases do not bring NaNs""" - - try: - old_error_settings = np.seterr(all='raise') - - y_true = np.array([0, 1, 2, 0, 1, 2]) - y_pred = np.array([2, 0, 1, 1, 2, 0]) - - assert_almost_equal(precision_score(y_true, y_pred, - average='weighted'), 0.0, 2) - assert_almost_equal(recall_score(y_true, y_pred, average='weighted'), - 0.0, 2) - assert_almost_equal(f1_score(y_true, y_pred, average='weighted'), - 0.0, 2) - - finally: - np.seterr(**old_error_settings) - - -def test_confusion_matrix_multiclass(): - """Test confusion matrix - multi-class case""" - y_true, y_pred, _ = make_prediction(binary=False) - - # compute confusion matrix with default labels introspection - cm = confusion_matrix(y_true, y_pred) - assert_array_equal(cm, [[23, 2, 0], - [5, 5, 20], - [0, 2, 18]]) - - # compute confusion matrix with explicit label ordering - cm = confusion_matrix(y_true, y_pred, labels=[0, 2, 1]) - assert_array_equal(cm, [[23, 0, 2], - [0, 18, 2], - [5, 20, 5]]) - - -def test_classification_report(): - """Test performance report""" - iris = datasets.load_iris() - y_true, y_pred, _ = make_prediction(dataset=iris, binary=False) - - # print classification report with class names - expected_report = """\ - precision recall f1-score support - - setosa 0.82 0.92 0.87 25 - versicolor 0.56 0.17 0.26 30 - virginica 0.47 0.90 0.62 20 - -avg / total 0.62 0.61 0.56 75 -""" - report = classification_report( - y_true, y_pred, labels=range(len(iris.target_names)), - target_names=iris.target_names) - assert_equal(report, expected_report) - - # print classification report with label detection - expected_report = """\ - precision recall f1-score support - - 0 0.82 0.92 0.87 25 - 1 0.56 0.17 0.26 30 - 2 0.47 0.90 0.62 20 - -avg / total 0.62 0.61 0.56 75 -""" - report = classification_report(y_true, y_pred) - assert_equal(report, expected_report) - - -def test_precision_recall_curve(): - """Test Precision-Recall and aread under PR curve""" - y_true, _, probas_pred = make_prediction(binary=True) - - p, r, thresholds = precision_recall_curve(y_true, probas_pred) - precision_recall_auc = auc(r, p) - assert_array_almost_equal(precision_recall_auc, 0.82, 2) - assert_array_almost_equal(precision_recall_auc, - average_precision_score(y_true, probas_pred)) - # Smoke test in the case of proba having only one value - p, r, thresholds = precision_recall_curve(y_true, - np.zeros_like(probas_pred)) - precision_recall_auc = auc(r, p) - assert_array_almost_equal(precision_recall_auc, 0.75, 3) - - -def test_losses(): - """Test loss functions""" - y_true, y_pred, _ = make_prediction(binary=True) - n = y_true.shape[0] - - assert_equal(zero_one(y_true, y_pred), 13) - assert_almost_equal(mean_squared_error(y_true, y_pred), 12.999 / n, 2) - assert_almost_equal(mean_squared_error(y_true, y_true), 0.00, 2) - - assert_almost_equal(explained_variance_score(y_true, y_pred), -0.04, 2) - assert_almost_equal(explained_variance_score(y_true, y_true), 1.00, 2) - - assert_almost_equal(r2_score(y_true, y_pred), -0.04, 2) - assert_almost_equal(r2_score(y_true, y_true), 1.00, 2) - - -def test_losses_at_limits(): - # test limit cases - assert_almost_equal(mean_squared_error([0.], [0.]), 0.00, 2) - assert_almost_equal(explained_variance_score([0.], [0.]), 1.00, 2) - assert_almost_equal(r2_score([0., 1], [0., 1]), 1.00, 2) - - -def test_r2_one_case_error(): - # test whether r2_score raises error given one point - assert_raises(ValueError, r2_score, [0], [0]) - - -def test_symmetry(): - """Test the symmetry of score and loss functions""" - y_true, y_pred, _ = make_prediction(binary=True) - - # symmetric - assert_equal(zero_one(y_true, y_pred), - zero_one(y_pred, y_true)) - assert_almost_equal(mean_squared_error(y_true, y_pred), - mean_squared_error(y_pred, y_true)) - # not symmetric - assert_true(explained_variance_score(y_true, y_pred) != \ - explained_variance_score(y_pred, y_true)) - assert_true(r2_score(y_true, y_pred) != \ - r2_score(y_pred, y_true)) - # FIXME: precision and recall aren't symmetric either - - -def test_hinge_loss_binary(): - y_true = np.array([-1, 1, 1, -1]) - pred_decision = np.array([-8.5, 0.5, 1.5, -0.3]) - assert_equal(1.2 / 4, hinge_loss(y_true, pred_decision)) - - y_true = np.array([0, 2, 2, 0]) - pred_decision = np.array([-8.5, 0.5, 1.5, -0.3]) - assert_equal(1.2 / 4, - hinge_loss(y_true, pred_decision, pos_label=2, neg_label=0)) diff --git a/sklearn/metrics/tests/test_pairwise.py b/sklearn/metrics/tests/test_pairwise.py index 43c0ee25e3d80..b5a375be361d2 100644 --- a/sklearn/metrics/tests/test_pairwise.py +++ b/sklearn/metrics/tests/test_pairwise.py @@ -1,21 +1,42 @@ import numpy as np from numpy import linalg -from numpy.testing import assert_array_almost_equal -from numpy.testing import assert_equal -from nose.tools import assert_raises -from nose.tools import assert_true -from scipy.sparse import csr_matrix -from scipy.spatial.distance import cosine, cityblock, minkowski - -from ..pairwise import euclidean_distances -from ..pairwise import linear_kernel -from ..pairwise import polynomial_kernel -from ..pairwise import rbf_kernel -from ..pairwise import sigmoid_kernel -from .. import pairwise_distances, pairwise_kernels -from ..pairwise import pairwise_kernel_functions -from ..pairwise import check_pairwise_arrays -from ..pairwise import _parallel_pairwise + +from scipy.sparse import dok_matrix, csr_matrix, issparse +from scipy.spatial.distance import cosine, cityblock, minkowski, wminkowski + +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_true + +from sklearn.externals.six import iteritems + +from sklearn.metrics.pairwise import euclidean_distances +from sklearn.metrics.pairwise import manhattan_distances +from sklearn.metrics.pairwise import linear_kernel +from sklearn.metrics.pairwise import chi2_kernel, additive_chi2_kernel +from sklearn.metrics.pairwise import polynomial_kernel +from sklearn.metrics.pairwise import rbf_kernel +from sklearn.metrics.pairwise import sigmoid_kernel +from sklearn.metrics.pairwise import cosine_similarity +from sklearn.metrics.pairwise import cosine_distances +from sklearn.metrics.pairwise import pairwise_distances +from sklearn.metrics.pairwise import pairwise_distances_argmin_min +from sklearn.metrics.pairwise import pairwise_distances_argmin +from sklearn.metrics.pairwise import pairwise_kernels +from sklearn.metrics.pairwise import PAIRWISE_KERNEL_FUNCTIONS +from sklearn.metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS +from sklearn.metrics.pairwise import PAIRED_DISTANCES +from sklearn.metrics.pairwise import check_pairwise_arrays +from sklearn.metrics.pairwise import check_paired_arrays +from sklearn.metrics.pairwise import _parallel_pairwise +from sklearn.metrics.pairwise import paired_distances +from sklearn.metrics.pairwise import paired_euclidean_distances +from sklearn.metrics.pairwise import paired_manhattan_distances +from sklearn.preprocessing import normalize def test_pairwise_distances(): @@ -48,7 +69,12 @@ def test_pairwise_distances(): assert_equal(S.shape[0], X.shape[0]) assert_equal(S.shape[1], Y.shape[0]) assert_array_almost_equal(S, S2) + # Low-level function for manhattan can divide in blocks to avoid + # using too much memory during the broadcasting + S3 = manhattan_distances(X, Y, size_threshold=10) + assert_array_almost_equal(S, S3) # Test cosine as a string metric versus cosine callable + # "cosine" uses sklearn metric, cosine (function) is scipy.spatial S = pairwise_distances(X, Y, metric="cosine") S2 = pairwise_distances(X, Y, metric=cosine) assert_equal(S.shape[0], X.shape[0]) @@ -58,47 +84,103 @@ def test_pairwise_distances(): S = np.dot(X, X.T) S2 = pairwise_distances(S, metric="precomputed") assert_true(S is S2) - # Test with sparse X and Y + # Test with sparse X and Y, + # currently only supported for Euclidean, L1 and cosine. X_sparse = csr_matrix(X) Y_sparse = csr_matrix(Y) S = pairwise_distances(X_sparse, Y_sparse, metric="euclidean") S2 = euclidean_distances(X_sparse, Y_sparse) assert_array_almost_equal(S, S2) + S = pairwise_distances(X_sparse, Y_sparse, metric="cosine") + S2 = cosine_distances(X_sparse, Y_sparse) + assert_array_almost_equal(S, S2) + S = pairwise_distances(X_sparse, Y_sparse.tocsc(), metric="manhattan") + S2 = manhattan_distances(X_sparse.tobsr(), Y_sparse.tocoo()) + assert_array_almost_equal(S, S2) + S2 = manhattan_distances(X, Y) + assert_array_almost_equal(S, S2) # Test with scipy.spatial.distance metric, with a kwd kwds = {"p": 2.0} S = pairwise_distances(X, Y, metric="minkowski", **kwds) S2 = pairwise_distances(X, Y, metric=minkowski, **kwds) assert_array_almost_equal(S, S2) + # same with Y = None + kwds = {"p": 2.0} + S = pairwise_distances(X, metric="minkowski", **kwds) + S2 = pairwise_distances(X, metric=minkowski, **kwds) + assert_array_almost_equal(S, S2) # Test that scipy distance metrics throw an error if sparse matrix given assert_raises(TypeError, pairwise_distances, X_sparse, metric="minkowski") assert_raises(TypeError, pairwise_distances, X, Y_sparse, metric="minkowski") + # Test that a value error is raised if the metric is unkown + assert_raises(ValueError, pairwise_distances, X, Y, metric="blah") -def test_pairwise_parallel(): - rng = np.random.RandomState(0) - for func in (np.array, csr_matrix): - X = func(rng.random_sample((5, 4))) - Y = func(rng.random_sample((3, 4))) - S = euclidean_distances(X) - S2 = _parallel_pairwise(X, None, euclidean_distances, n_jobs=-1) +def check_pairwise_parallel(func, metric, kwds): + rng = np.random.RandomState(0) + for make_data in (np.array, csr_matrix): + X = make_data(rng.random_sample((5, 4))) + Y = make_data(rng.random_sample((3, 4))) + + try: + S = func(X, metric=metric, n_jobs=1, **kwds) + except (TypeError, ValueError) as exc: + # Not all metrics support sparse input + # ValueError may be triggered by bad callable + if make_data is csr_matrix: + assert_raises(type(exc), func, X, metric=metric, + n_jobs=2, **kwds) + continue + else: + raise + S2 = func(X, metric=metric, n_jobs=2, **kwds) assert_array_almost_equal(S, S2) - S = euclidean_distances(X, Y) - S2 = _parallel_pairwise(X, Y, euclidean_distances, n_jobs=-1) + S = func(X, Y, metric=metric, n_jobs=1, **kwds) + S2 = func(X, Y, metric=metric, n_jobs=2, **kwds) assert_array_almost_equal(S, S2) +def test_pairwise_parallel(): + wminkowski_kwds = {'w': np.arange(1, 5).astype('double'), 'p': 1} + metrics = [(pairwise_distances, 'euclidean', {}), + (pairwise_distances, wminkowski, wminkowski_kwds), + (pairwise_distances, 'wminkowski', wminkowski_kwds), + (pairwise_kernels, 'polynomial', {'degree': 1}), + (pairwise_kernels, callable_rbf_kernel, {'gamma': .1}), + ] + for func, metric, kwds in metrics: + yield check_pairwise_parallel, func, metric, kwds + + +def test_pairwise_callable_nonstrict_metric(): + """paired_distances should allow callable metric where metric(x, x) != 0 + + Knowing that the callable is a strict metric would allow the diagonal to + be left uncalculated and set to 0. + """ + assert_equal(pairwise_distances([[1]], metric=lambda x, y: 5)[0, 0], 5) + + +def callable_rbf_kernel(x, y, **kwds): + """ Callable version of pairwise.rbf_kernel. """ + K = rbf_kernel(np.atleast_2d(x), np.atleast_2d(y), **kwds) + return K + + def test_pairwise_kernels(): """ Test the pairwise_kernels helper function. """ + rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((2, 4)) - # Test with all metrics that should be in pairwise_kernel_functions. - test_metrics = ["rbf", "sigmoid", "polynomial", "linear"] + # Test with all metrics that should be in PAIRWISE_KERNEL_FUNCTIONS. + test_metrics = ["rbf", "sigmoid", "polynomial", "linear", "chi2", + "additive_chi2"] for metric in test_metrics: - function = pairwise_kernel_functions[metric] + function = PAIRWISE_KERNEL_FUNCTIONS[metric] # Test with Y=None K1 = pairwise_kernels(X, metric=metric) K2 = function(X) @@ -112,19 +194,30 @@ def test_pairwise_kernels(): Y_tuples = tuple([tuple([v for v in row]) for row in Y]) K2 = pairwise_kernels(X_tuples, Y_tuples, metric=metric) assert_array_almost_equal(K1, K2) + # Test with sparse X and Y X_sparse = csr_matrix(X) Y_sparse = csr_matrix(Y) + if metric in ["chi2", "additive_chi2"]: + # these don't support sparse matrices yet + assert_raises(ValueError, pairwise_kernels, + X_sparse, Y=Y_sparse, metric=metric) + continue K1 = pairwise_kernels(X_sparse, Y=Y_sparse, metric=metric) assert_array_almost_equal(K1, K2) # Test with a callable function, with given keywords. metric = callable_rbf_kernel kwds = {} - kwds['gamma'] = 0. + kwds['gamma'] = 0.1 K1 = pairwise_kernels(X, Y=Y, metric=metric, **kwds) K2 = rbf_kernel(X, Y=Y, **kwds) assert_array_almost_equal(K1, K2) + # callable function, X=Y + K1 = pairwise_kernels(X, Y=X, metric=metric, **kwds) + K2 = rbf_kernel(X, Y=X, **kwds) + assert_array_almost_equal(K1, K2) + def test_pairwise_kernels_filter_param(): rng = np.random.RandomState(0) @@ -138,10 +231,97 @@ def test_pairwise_kernels_filter_param(): assert_raises(TypeError, pairwise_kernels, X, Y, "rbf", **params) -def callable_rbf_kernel(x, y, **kwds): - """ Callable version of pairwise.rbf_kernel. """ - K = rbf_kernel(np.atleast_2d(x), np.atleast_2d(y), **kwds) - return K +def test_paired_distances(): + """ Test the pairwise_distance helper function. """ + rng = np.random.RandomState(0) + # Euclidean distance should be equivalent to calling the function. + X = rng.random_sample((5, 4)) + # Euclidean distance, with Y != X. + Y = rng.random_sample((5, 4)) + for metric, func in iteritems(PAIRED_DISTANCES): + S = paired_distances(X, Y, metric=metric) + S2 = func(X, Y) + assert_array_almost_equal(S, S2) + S3 = func(csr_matrix(X), csr_matrix(Y)) + assert_array_almost_equal(S, S3) + if metric in PAIRWISE_DISTANCE_FUNCTIONS: + # Check the the pairwise_distances implementation + # gives the same value + distances = PAIRWISE_DISTANCE_FUNCTIONS[metric](X, Y) + distances = np.diag(distances) + assert_array_almost_equal(distances, S) + + # Check the callable implementation + S = paired_distances(X, Y, metric='manhattan') + S2 = paired_distances(X, Y, metric=lambda x, y: np.abs(x - y).sum(axis=0)) + assert_array_almost_equal(S, S2) + + # Test that a value error is raised when the lengths of X and Y should not + # differ + Y = rng.random_sample((3, 4)) + assert_raises(ValueError, paired_distances, X, Y) + + +def test_pairwise_distances_argmin_min(): + """ Check pairwise minimum distances computation for any metric""" + X = [[0], [1]] + Y = [[-1], [2]] + + Xsp = dok_matrix(X) + Ysp = csr_matrix(Y, dtype=np.float32) + + # euclidean metric + D, E = pairwise_distances_argmin_min(X, Y, metric="euclidean") + D2 = pairwise_distances_argmin(X, Y, metric="euclidean") + assert_array_almost_equal(D, [0, 1]) + assert_array_almost_equal(D2, [0, 1]) + assert_array_almost_equal(D, [0, 1]) + assert_array_almost_equal(E, [1., 1.]) + + # sparse matrix case + Dsp, Esp = pairwise_distances_argmin_min(Xsp, Ysp, metric="euclidean") + assert_array_equal(Dsp, D) + assert_array_equal(Esp, E) + # We don't want np.matrix here + assert_equal(type(Dsp), np.ndarray) + assert_equal(type(Esp), np.ndarray) + + # Non-euclidean sklearn metric + D, E = pairwise_distances_argmin_min(X, Y, metric="manhattan") + D2 = pairwise_distances_argmin(X, Y, metric="manhattan") + assert_array_almost_equal(D, [0, 1]) + assert_array_almost_equal(D2, [0, 1]) + assert_array_almost_equal(E, [1., 1.]) + D, E = pairwise_distances_argmin_min(Xsp, Ysp, metric="manhattan") + D2 = pairwise_distances_argmin(Xsp, Ysp, metric="manhattan") + assert_array_almost_equal(D, [0, 1]) + assert_array_almost_equal(E, [1., 1.]) + + # Non-euclidean Scipy distance (callable) + D, E = pairwise_distances_argmin_min(X, Y, metric=minkowski, + metric_kwargs={"p": 2}) + assert_array_almost_equal(D, [0, 1]) + assert_array_almost_equal(E, [1., 1.]) + + # Non-euclidean Scipy distance (string) + D, E = pairwise_distances_argmin_min(X, Y, metric="minkowski", + metric_kwargs={"p": 2}) + assert_array_almost_equal(D, [0, 1]) + assert_array_almost_equal(E, [1., 1.]) + + # Compare with naive implementation + rng = np.random.RandomState(0) + X = rng.randn(97, 149) + Y = rng.randn(111, 149) + + dist = pairwise_distances(X, Y, metric="manhattan") + dist_orig_ind = dist.argmin(axis=0) + dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))] + + dist_chunked_ind, dist_chunked_val = pairwise_distances_argmin_min( + X, Y, axis=0, metric="manhattan", batch_size=50) + np.testing.assert_almost_equal(dist_orig_ind, dist_chunked_ind, decimal=7) + np.testing.assert_almost_equal(dist_orig_val, dist_chunked_val, decimal=7) def test_euclidean_distances(): @@ -157,12 +337,85 @@ def test_euclidean_distances(): assert_array_almost_equal(D, [[1., 2.]]) +# Paired distances + +def test_paired_euclidean_distances(): + """ Check the paired Euclidean distances computation""" + X = [[0], [0]] + Y = [[1], [2]] + D = paired_euclidean_distances(X, Y) + assert_array_almost_equal(D, [1., 2.]) + + +def test_paired_manhattan_distances(): + """ Check the paired manhattan distances computation""" + X = [[0], [0]] + Y = [[1], [2]] + D = paired_manhattan_distances(X, Y) + assert_array_almost_equal(D, [1., 2.]) + + +def test_chi_square_kernel(): + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + Y = rng.random_sample((10, 4)) + K_add = additive_chi2_kernel(X, Y) + gamma = 0.1 + K = chi2_kernel(X, Y, gamma=gamma) + assert_equal(K.dtype, np.float) + for i, x in enumerate(X): + for j, y in enumerate(Y): + chi2 = -np.sum((x - y) ** 2 / (x + y)) + chi2_exp = np.exp(gamma * chi2) + assert_almost_equal(K_add[i, j], chi2) + assert_almost_equal(K[i, j], chi2_exp) + + # check diagonal is ones for data with itself + K = chi2_kernel(Y) + assert_array_equal(np.diag(K), 1) + # check off-diagonal is < 1 but > 0: + assert_true(np.all(K > 0)) + assert_true(np.all(K - np.diag(np.diag(K)) < 1)) + # check that float32 is preserved + X = rng.random_sample((5, 4)).astype(np.float32) + Y = rng.random_sample((10, 4)).astype(np.float32) + K = chi2_kernel(X, Y) + assert_equal(K.dtype, np.float32) + + # check integer type gets converted, + # check that zeros are handled + X = rng.random_sample((10, 4)).astype(np.int32) + K = chi2_kernel(X, X) + assert_true(np.isfinite(K).all()) + assert_equal(K.dtype, np.float) + + # check that kernel of similar things is greater than dissimilar ones + X = [[.3, .7], [1., 0]] + Y = [[0, 1], [.9, .1]] + K = chi2_kernel(X, Y) + assert_greater(K[0, 0], K[0, 1]) + assert_greater(K[1, 1], K[1, 0]) + + # test negative input + assert_raises(ValueError, chi2_kernel, [[0, -1]]) + assert_raises(ValueError, chi2_kernel, [[0, -1]], [[-1, -1]]) + assert_raises(ValueError, chi2_kernel, [[0, 1]], [[-1, -1]]) + + # different n_features in X and Y + assert_raises(ValueError, chi2_kernel, [[0, 1]], [[.2, .2, .6]]) + + # sparse matrices + assert_raises(ValueError, chi2_kernel, csr_matrix(X), csr_matrix(Y)) + assert_raises(ValueError, additive_chi2_kernel, + csr_matrix(X), csr_matrix(Y)) + + def test_kernel_symmetry(): """ Valid kernels should be symmetric""" rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) for kernel in (linear_kernel, polynomial_kernel, rbf_kernel, - sigmoid_kernel): + sigmoid_kernel, cosine_similarity): K = kernel(X, X) assert_array_almost_equal(K, K.T, 15) @@ -172,7 +425,7 @@ def test_kernel_sparse(): X = rng.random_sample((5, 4)) X_sparse = csr_matrix(X) for kernel in (linear_kernel, polynomial_kernel, rbf_kernel, - sigmoid_kernel): + sigmoid_kernel, cosine_similarity): K = kernel(X, X) K2 = kernel(X_sparse, X_sparse) assert_array_almost_equal(K, K2) @@ -194,13 +447,34 @@ def test_rbf_kernel(): assert_array_almost_equal(K.flat[::6], np.ones(5)) +def test_cosine_similarity(): + """ Test the cosine_similarity. """ + + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + Y = rng.random_sample((3, 4)) + Xcsr = csr_matrix(X) + Ycsr = csr_matrix(Y) + + for X_, Y_ in ((X, None), (X, Y), + (Xcsr, None), (Xcsr, Ycsr)): + # Test that the cosine is kernel is equal to a linear kernel when data + # has been previously normalized by L2-norm. + K1 = pairwise_kernels(X_, Y=Y_, metric="cosine") + X_ = normalize(X_) + if Y_ is not None: + Y_ = normalize(Y_) + K2 = pairwise_kernels(X_, Y=Y_, metric="linear") + assert_array_almost_equal(K1, K2) + + def test_check_dense_matrices(): """ Ensure that pairwise array check works for dense matrices.""" # Check that if XB is None, XB is returned as reference to XA XA = np.resize(np.arange(40), (5, 8)) XA_checked, XB_checked = check_pairwise_arrays(XA, None) assert_true(XA_checked is XB_checked) - assert_equal(XA, XA_checked) + assert_array_equal(XA, XA_checked) def test_check_XB_returned(): @@ -210,8 +484,13 @@ def test_check_XB_returned(): XA = np.resize(np.arange(40), (5, 8)) XB = np.resize(np.arange(32), (4, 8)) XA_checked, XB_checked = check_pairwise_arrays(XA, XB) - assert_equal(XA, XA_checked) - assert_equal(XB, XB_checked) + assert_array_equal(XA, XA_checked) + assert_array_equal(XB, XB_checked) + + XB = np.resize(np.arange(40), (5, 8)) + XA_checked, XB_checked = check_paired_arrays(XA, XB) + assert_array_equal(XA, XA_checked) + assert_array_equal(XB, XB_checked) def test_check_different_dimensions(): @@ -220,6 +499,9 @@ def test_check_different_dimensions(): XB = np.resize(np.arange(32), (4, 8)) assert_raises(ValueError, check_pairwise_arrays, XA, XB) + XB = np.resize(np.arange(4 * 9), (4, 9)) + assert_raises(ValueError, check_paired_arrays, XA, XB) + def test_check_invalid_dimensions(): """ Ensure an error is raised on 1D input arrays. """ @@ -239,8 +521,18 @@ def test_check_sparse_arrays(): XB = rng.random_sample((5, 4)) XB_sparse = csr_matrix(XB) XA_checked, XB_checked = check_pairwise_arrays(XA_sparse, XB_sparse) - assert_equal(XA_sparse, XA_checked) - assert_equal(XB_sparse, XB_checked) + # compare their difference because testing csr matrices for + # equality with '==' does not work as expected. + assert_true(issparse(XA_checked)) + assert_equal(abs(XA_sparse - XA_checked).sum(), 0) + assert_true(issparse(XB_checked)) + assert_equal(abs(XB_sparse - XB_checked).sum(), 0) + + XA_checked, XA_2_checked = check_pairwise_arrays(XA_sparse, XA_sparse) + assert_true(issparse(XA_checked)) + assert_equal(abs(XA_sparse - XA_checked).sum(), 0) + assert_true(issparse(XA_2_checked)) + assert_equal(abs(XA_2_checked - XA_checked).sum(), 0) def tuplify(X): @@ -262,5 +554,31 @@ def test_check_tuple_input(): XB = rng.random_sample((5, 4)) XB_tuples = tuplify(XB) XA_checked, XB_checked = check_pairwise_arrays(XA_tuples, XB_tuples) - assert_equal(XA_tuples, XA_checked) - assert_equal(XB_tuples, XB_checked) + assert_array_equal(XA_tuples, XA_checked) + assert_array_equal(XB_tuples, XB_checked) + + +def test_check_preserve_type(): + """ Ensures that type float32 is preserved. """ + XA = np.resize(np.arange(40), (5, 8)).astype(np.float32) + XB = np.resize(np.arange(40), (5, 8)).astype(np.float32) + + XA_checked, XB_checked = check_pairwise_arrays(XA, None) + assert_equal(XA_checked.dtype, np.float32) + + # both float32 + XA_checked, XB_checked = check_pairwise_arrays(XA, XB) + assert_equal(XA_checked.dtype, np.float32) + assert_equal(XB_checked.dtype, np.float32) + + # mismatched A + XA_checked, XB_checked = check_pairwise_arrays(XA.astype(np.float), + XB) + assert_equal(XA_checked.dtype, np.float) + assert_equal(XB_checked.dtype, np.float) + + # mismatched B + XA_checked, XB_checked = check_pairwise_arrays(XA, + XB.astype(np.float)) + assert_equal(XA_checked.dtype, np.float) + assert_equal(XB_checked.dtype, np.float) diff --git a/sklearn/metrics/tests/test_ranking.py b/sklearn/metrics/tests/test_ranking.py new file mode 100644 index 0000000000000..40ce6f659c569 --- /dev/null +++ b/sklearn/metrics/tests/test_ranking.py @@ -0,0 +1,899 @@ +from __future__ import division, print_function + +import numpy as np +from itertools import product +import warnings + +from sklearn import datasets +from sklearn import svm +from sklearn import ensemble + +from sklearn.datasets import make_multilabel_classification +from sklearn.random_projection import sparse_random_matrix +from sklearn.utils.validation import check_array, check_consistent_length +from sklearn.utils.validation import check_random_state + +from sklearn.utils.testing import assert_raises, clean_warning_registry +from sklearn.utils.testing import assert_raise_message +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import ignore_warnings + +from sklearn.metrics import auc +from sklearn.metrics import average_precision_score +from sklearn.metrics import coverage_error +from sklearn.metrics import label_ranking_average_precision_score +from sklearn.metrics import precision_recall_curve +from sklearn.metrics import roc_auc_score +from sklearn.metrics import roc_curve + +from sklearn.metrics.base import UndefinedMetricWarning + + +############################################################################### +# Utilities for testing + +def make_prediction(dataset=None, binary=False): + """Make some classification predictions on a toy dataset using a SVC + + If binary is True restrict to a binary classification problem instead of a + multiclass classification problem + """ + + if dataset is None: + # import some data to play with + dataset = datasets.load_iris() + + X = dataset.data + y = dataset.target + + if binary: + # restrict to a binary classification task + X, y = X[y < 2], y[y < 2] + + n_samples, n_features = X.shape + p = np.arange(n_samples) + + rng = check_random_state(37) + rng.shuffle(p) + X, y = X[p], y[p] + half = int(n_samples / 2) + + # add noisy features to make the problem harder and avoid perfect results + rng = np.random.RandomState(0) + X = np.c_[X, rng.randn(n_samples, 200 * n_features)] + + # run classifier, get class probabilities and label predictions + clf = svm.SVC(kernel='linear', probability=True, random_state=0) + probas_pred = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) + + if binary: + # only interested in probabilities of the positive case + # XXX: do we really want a special API for the binary case? + probas_pred = probas_pred[:, 1] + + y_pred = clf.predict(X[half:]) + y_true = y[half:] + return y_true, y_pred, probas_pred + + +############################################################################### +# Tests + +def _auc(y_true, y_score): + """Alternative implementation to check for correctness of + `roc_auc_score`.""" + pos_label = np.unique(y_true)[1] + + # Count the number of times positive samples are correctly ranked above + # negative samples. + pos = y_score[y_true == pos_label] + neg = y_score[y_true != pos_label] + diff_matrix = pos.reshape(1, -1) - neg.reshape(-1, 1) + n_correct = np.sum(diff_matrix > 0) + + return n_correct / float(len(pos) * len(neg)) + + +def _average_precision(y_true, y_score): + """Alternative implementation to check for correctness of + `average_precision_score`.""" + pos_label = np.unique(y_true)[1] + n_pos = np.sum(y_true == pos_label) + order = np.argsort(y_score)[::-1] + y_score = y_score[order] + y_true = y_true[order] + + score = 0 + for i in range(len(y_score)): + if y_true[i] == pos_label: + # Compute precision up to document i + # i.e, percentage of relevant documents up to document i. + prec = 0 + for j in range(0, i + 1): + if y_true[j] == pos_label: + prec += 1.0 + prec /= (i + 1.0) + score += prec + + return score / n_pos + + +def test_roc_curve(): + """Test Area under Receiver Operating Characteristic (ROC) curve""" + y_true, _, probas_pred = make_prediction(binary=True) + + fpr, tpr, thresholds = roc_curve(y_true, probas_pred) + roc_auc = auc(fpr, tpr) + expected_auc = _auc(y_true, probas_pred) + assert_array_almost_equal(roc_auc, expected_auc, decimal=2) + assert_almost_equal(roc_auc, roc_auc_score(y_true, probas_pred)) + assert_equal(fpr.shape, tpr.shape) + assert_equal(fpr.shape, thresholds.shape) + + +def test_roc_curve_end_points(): + # Make sure that roc_curve returns a curve start at 0 and ending and + # 1 even in corner cases + rng = np.random.RandomState(0) + y_true = np.array([0] * 50 + [1] * 50) + y_pred = rng.randint(3, size=100) + fpr, tpr, thr = roc_curve(y_true, y_pred) + assert_equal(fpr[0], 0) + assert_equal(fpr[-1], 1) + assert_equal(fpr.shape, tpr.shape) + assert_equal(fpr.shape, thr.shape) + + +def test_roc_returns_consistency(): + """Test whether the returned threshold matches up with tpr""" + # make small toy dataset + y_true, _, probas_pred = make_prediction(binary=True) + fpr, tpr, thresholds = roc_curve(y_true, probas_pred) + + # use the given thresholds to determine the tpr + tpr_correct = [] + for t in thresholds: + tp = np.sum((probas_pred >= t) & y_true) + p = np.sum(y_true) + tpr_correct.append(1.0 * tp / p) + + # compare tpr and tpr_correct to see if the thresholds' order was correct + assert_array_almost_equal(tpr, tpr_correct, decimal=2) + assert_equal(fpr.shape, tpr.shape) + assert_equal(fpr.shape, thresholds.shape) + + +def test_roc_nonrepeating_thresholds(): + """Test to ensure that we don't return spurious repeating thresholds. + + Duplicated thresholds can arise due to machine precision issues. + """ + dataset = datasets.load_digits() + X = dataset['data'] + y = dataset['target'] + + # This random forest classifier can only return probabilities + # significant to two decimal places + clf = ensemble.RandomForestClassifier(n_estimators=100, random_state=0) + + # How well can the classifier predict whether a digit is less than 5? + # This task contributes floating point roundoff errors to the probabilities + train, test = slice(None, None, 2), slice(1, None, 2) + probas_pred = clf.fit(X[train], y[train]).predict_proba(X[test]) + y_score = probas_pred[:, :5].sum(axis=1) # roundoff errors begin here + y_true = [yy < 5 for yy in y[test]] + + # Check for repeating values in the thresholds + fpr, tpr, thresholds = roc_curve(y_true, y_score) + assert_equal(thresholds.size, np.unique(np.round(thresholds, 2)).size) + + +def test_roc_curve_multi(): + """roc_curve not applicable for multi-class problems""" + y_true, _, probas_pred = make_prediction(binary=False) + + assert_raises(ValueError, roc_curve, y_true, probas_pred) + + +def test_roc_curve_confidence(): + """roc_curve for confidence scores""" + y_true, _, probas_pred = make_prediction(binary=True) + + fpr, tpr, thresholds = roc_curve(y_true, probas_pred - 0.5) + roc_auc = auc(fpr, tpr) + assert_array_almost_equal(roc_auc, 0.90, decimal=2) + assert_equal(fpr.shape, tpr.shape) + assert_equal(fpr.shape, thresholds.shape) + + +def test_roc_curve_hard(): + """roc_curve for hard decisions""" + y_true, pred, probas_pred = make_prediction(binary=True) + + # always predict one + trivial_pred = np.ones(y_true.shape) + fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) + roc_auc = auc(fpr, tpr) + assert_array_almost_equal(roc_auc, 0.50, decimal=2) + assert_equal(fpr.shape, tpr.shape) + assert_equal(fpr.shape, thresholds.shape) + + # always predict zero + trivial_pred = np.zeros(y_true.shape) + fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) + roc_auc = auc(fpr, tpr) + assert_array_almost_equal(roc_auc, 0.50, decimal=2) + assert_equal(fpr.shape, tpr.shape) + assert_equal(fpr.shape, thresholds.shape) + + # hard decisions + fpr, tpr, thresholds = roc_curve(y_true, pred) + roc_auc = auc(fpr, tpr) + assert_array_almost_equal(roc_auc, 0.78, decimal=2) + assert_equal(fpr.shape, tpr.shape) + assert_equal(fpr.shape, thresholds.shape) + + +def test_roc_curve_one_label(): + y_true = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + y_pred = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + # assert there are warnings + w = UndefinedMetricWarning + fpr, tpr, thresholds = assert_warns(w, roc_curve, y_true, y_pred) + # all true labels, all fpr should be nan + assert_array_equal(fpr, + np.nan * np.ones(len(thresholds))) + assert_equal(fpr.shape, tpr.shape) + assert_equal(fpr.shape, thresholds.shape) + + # assert there are warnings + fpr, tpr, thresholds = assert_warns(w, roc_curve, + [1 - x for x in y_true], + y_pred) + # all negative labels, all tpr should be nan + assert_array_equal(tpr, + np.nan * np.ones(len(thresholds))) + assert_equal(fpr.shape, tpr.shape) + assert_equal(fpr.shape, thresholds.shape) + + +def test_roc_curve_toydata(): + # Binary classification + y_true = [0, 1] + y_score = [0, 1] + tpr, fpr, _ = roc_curve(y_true, y_score) + roc_auc = roc_auc_score(y_true, y_score) + assert_array_almost_equal(tpr, [0, 1]) + assert_array_almost_equal(fpr, [1, 1]) + assert_almost_equal(roc_auc, 1.) + + y_true = [0, 1] + y_score = [1, 0] + tpr, fpr, _ = roc_curve(y_true, y_score) + roc_auc = roc_auc_score(y_true, y_score) + assert_array_almost_equal(tpr, [0, 1, 1]) + assert_array_almost_equal(fpr, [0, 0, 1]) + assert_almost_equal(roc_auc, 0.) + + y_true = [1, 0] + y_score = [1, 1] + tpr, fpr, _ = roc_curve(y_true, y_score) + roc_auc = roc_auc_score(y_true, y_score) + assert_array_almost_equal(tpr, [0, 1]) + assert_array_almost_equal(fpr, [0, 1]) + assert_almost_equal(roc_auc, 0.5) + + y_true = [1, 0] + y_score = [1, 0] + tpr, fpr, _ = roc_curve(y_true, y_score) + roc_auc = roc_auc_score(y_true, y_score) + assert_array_almost_equal(tpr, [0, 1]) + assert_array_almost_equal(fpr, [1, 1]) + assert_almost_equal(roc_auc, 1.) + + y_true = [1, 0] + y_score = [0.5, 0.5] + tpr, fpr, _ = roc_curve(y_true, y_score) + roc_auc = roc_auc_score(y_true, y_score) + assert_array_almost_equal(tpr, [0, 1]) + assert_array_almost_equal(fpr, [0, 1]) + assert_almost_equal(roc_auc, .5) + + y_true = [0, 0] + y_score = [0.25, 0.75] + tpr, fpr, _ = roc_curve(y_true, y_score) + assert_raises(ValueError, roc_auc_score, y_true, y_score) + assert_array_almost_equal(tpr, [0., 0.5, 1.]) + assert_array_almost_equal(fpr, [np.nan, np.nan, np.nan]) + + y_true = [1, 1] + y_score = [0.25, 0.75] + tpr, fpr, _ = roc_curve(y_true, y_score) + assert_raises(ValueError, roc_auc_score, y_true, y_score) + assert_array_almost_equal(tpr, [np.nan, np.nan]) + assert_array_almost_equal(fpr, [0.5, 1.]) + + # Multi-label classification task + y_true = np.array([[0, 1], [0, 1]]) + y_score = np.array([[0, 1], [0, 1]]) + assert_raises(ValueError, roc_auc_score, y_true, y_score, average="macro") + assert_raises(ValueError, roc_auc_score, y_true, y_score, + average="weighted") + assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 1.) + assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 1.) + + y_true = np.array([[0, 1], [0, 1]]) + y_score = np.array([[0, 1], [1, 0]]) + assert_raises(ValueError, roc_auc_score, y_true, y_score, average="macro") + assert_raises(ValueError, roc_auc_score, y_true, y_score, + average="weighted") + assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 0.5) + assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 0.5) + + y_true = np.array([[1, 0], [0, 1]]) + y_score = np.array([[0, 1], [1, 0]]) + assert_almost_equal(roc_auc_score(y_true, y_score, average="macro"), 0) + assert_almost_equal(roc_auc_score(y_true, y_score, average="weighted"), 0) + assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 0) + assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 0) + + y_true = np.array([[1, 0], [0, 1]]) + y_score = np.array([[0.5, 0.5], [0.5, 0.5]]) + assert_almost_equal(roc_auc_score(y_true, y_score, average="macro"), .5) + assert_almost_equal(roc_auc_score(y_true, y_score, average="weighted"), .5) + assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), .5) + assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), .5) + + +def test_auc(): + """Test Area Under Curve (AUC) computation""" + x = [0, 1] + y = [0, 1] + assert_array_almost_equal(auc(x, y), 0.5) + x = [1, 0] + y = [0, 1] + assert_array_almost_equal(auc(x, y), 0.5) + x = [1, 0, 0] + y = [0, 1, 1] + assert_array_almost_equal(auc(x, y), 0.5) + x = [0, 1] + y = [1, 1] + assert_array_almost_equal(auc(x, y), 1) + x = [0, 0.5, 1] + y = [0, 0.5, 1] + assert_array_almost_equal(auc(x, y), 0.5) + + +def test_auc_duplicate_values(): + # Test Area Under Curve (AUC) computation with duplicate values + + # auc() was previously sorting the x and y arrays according to the indices + # from numpy.argsort(x), which was reordering the tied 0's in this example + # and resulting in an incorrect area computation. This test detects the + # error. + x = [-2.0, 0.0, 0.0, 0.0, 1.0] + y1 = [2.0, 0.0, 0.5, 1.0, 1.0] + y2 = [2.0, 1.0, 0.0, 0.5, 1.0] + y3 = [2.0, 1.0, 0.5, 0.0, 1.0] + + for y in (y1, y2, y3): + assert_array_almost_equal(auc(x, y, reorder=True), 3.0) + + +def test_auc_errors(): + # Incompatible shapes + assert_raises(ValueError, auc, [0.0, 0.5, 1.0], [0.1, 0.2]) + + # Too few x values + assert_raises(ValueError, auc, [0.0], [0.1]) + + # x is not in order + assert_raises(ValueError, auc, [1.0, 0.0, 0.5], [0.0, 0.0, 0.0]) + + +def test_auc_score_non_binary_class(): + """Test that roc_auc_score function returns an error when trying + to compute AUC for non-binary class values. + """ + rng = check_random_state(404) + y_pred = rng.rand(10) + # y_true contains only one class value + y_true = np.zeros(10, dtype="int") + assert_raise_message(ValueError, "ROC AUC score is not defined", + roc_auc_score, y_true, y_pred) + y_true = np.ones(10, dtype="int") + assert_raise_message(ValueError, "ROC AUC score is not defined", + roc_auc_score, y_true, y_pred) + y_true = -np.ones(10, dtype="int") + assert_raise_message(ValueError, "ROC AUC score is not defined", + roc_auc_score, y_true, y_pred) + # y_true contains three different class values + y_true = rng.randint(0, 3, size=10) + assert_raise_message(ValueError, "multiclass format is not supported", + roc_auc_score, y_true, y_pred) + + clean_warning_registry() + with warnings.catch_warnings(record=True): + rng = check_random_state(404) + y_pred = rng.rand(10) + # y_true contains only one class value + y_true = np.zeros(10, dtype="int") + assert_raise_message(ValueError, "ROC AUC score is not defined", + roc_auc_score, y_true, y_pred) + y_true = np.ones(10, dtype="int") + assert_raise_message(ValueError, "ROC AUC score is not defined", + roc_auc_score, y_true, y_pred) + y_true = -np.ones(10, dtype="int") + assert_raise_message(ValueError, "ROC AUC score is not defined", + roc_auc_score, y_true, y_pred) + + # y_true contains three different class values + y_true = rng.randint(0, 3, size=10) + assert_raise_message(ValueError, "multiclass format is not supported", + roc_auc_score, y_true, y_pred) + + +def test_precision_recall_curve(): + y_true, _, probas_pred = make_prediction(binary=True) + _test_precision_recall_curve(y_true, probas_pred) + + # Use {-1, 1} for labels; make sure original labels aren't modified + y_true[np.where(y_true == 0)] = -1 + y_true_copy = y_true.copy() + _test_precision_recall_curve(y_true, probas_pred) + assert_array_equal(y_true_copy, y_true) + + labels = [1, 0, 0, 1] + predict_probas = [1, 2, 3, 4] + p, r, t = precision_recall_curve(labels, predict_probas) + assert_array_almost_equal(p, np.array([0.5, 0.33333333, 0.5, 1., 1.])) + assert_array_almost_equal(r, np.array([1., 0.5, 0.5, 0.5, 0.])) + assert_array_almost_equal(t, np.array([1, 2, 3, 4])) + assert_equal(p.size, r.size) + assert_equal(p.size, t.size + 1) + + +def test_precision_recall_curve_pos_label(): + y_true, _, probas_pred = make_prediction(binary=False) + pos_label = 2 + p, r, thresholds = precision_recall_curve(y_true, + probas_pred[:, pos_label], + pos_label=pos_label) + p2, r2, thresholds2 = precision_recall_curve(y_true == pos_label, + probas_pred[:, pos_label]) + assert_array_almost_equal(p, p2) + assert_array_almost_equal(r, r2) + assert_array_almost_equal(thresholds, thresholds2) + assert_equal(p.size, r.size) + assert_equal(p.size, thresholds.size + 1) + + +def _test_precision_recall_curve(y_true, probas_pred): + """Test Precision-Recall and aread under PR curve""" + p, r, thresholds = precision_recall_curve(y_true, probas_pred) + precision_recall_auc = auc(r, p) + assert_array_almost_equal(precision_recall_auc, 0.85, 2) + assert_array_almost_equal(precision_recall_auc, + average_precision_score(y_true, probas_pred)) + assert_almost_equal(_average_precision(y_true, probas_pred), + precision_recall_auc, 1) + assert_equal(p.size, r.size) + assert_equal(p.size, thresholds.size + 1) + # Smoke test in the case of proba having only one value + p, r, thresholds = precision_recall_curve(y_true, + np.zeros_like(probas_pred)) + precision_recall_auc = auc(r, p) + assert_array_almost_equal(precision_recall_auc, 0.75, 3) + assert_equal(p.size, r.size) + assert_equal(p.size, thresholds.size + 1) + + +def test_precision_recall_curve_errors(): + # Contains non-binary labels + assert_raises(ValueError, precision_recall_curve, + [0, 1, 2], [[0.0], [1.0], [1.0]]) + + +def test_precision_recall_curve_toydata(): + with np.errstate(all="raise"): + # Binary classification + y_true = [0, 1] + y_score = [0, 1] + p, r, _ = precision_recall_curve(y_true, y_score) + auc_prc = average_precision_score(y_true, y_score) + assert_array_almost_equal(p, [1, 1]) + assert_array_almost_equal(r, [1, 0]) + assert_almost_equal(auc_prc, 1.) + + y_true = [0, 1] + y_score = [1, 0] + p, r, _ = precision_recall_curve(y_true, y_score) + auc_prc = average_precision_score(y_true, y_score) + assert_array_almost_equal(p, [0.5, 0., 1.]) + assert_array_almost_equal(r, [1., 0., 0.]) + assert_almost_equal(auc_prc, 0.25) + + y_true = [1, 0] + y_score = [1, 1] + p, r, _ = precision_recall_curve(y_true, y_score) + auc_prc = average_precision_score(y_true, y_score) + assert_array_almost_equal(p, [0.5, 1]) + assert_array_almost_equal(r, [1., 0]) + assert_almost_equal(auc_prc, .75) + + y_true = [1, 0] + y_score = [1, 0] + p, r, _ = precision_recall_curve(y_true, y_score) + auc_prc = average_precision_score(y_true, y_score) + assert_array_almost_equal(p, [1, 1]) + assert_array_almost_equal(r, [1, 0]) + assert_almost_equal(auc_prc, 1.) + + y_true = [1, 0] + y_score = [0.5, 0.5] + p, r, _ = precision_recall_curve(y_true, y_score) + auc_prc = average_precision_score(y_true, y_score) + assert_array_almost_equal(p, [0.5, 1]) + assert_array_almost_equal(r, [1, 0.]) + assert_almost_equal(auc_prc, .75) + + y_true = [0, 0] + y_score = [0.25, 0.75] + assert_raises(Exception, precision_recall_curve, y_true, y_score) + assert_raises(Exception, average_precision_score, y_true, y_score) + + y_true = [1, 1] + y_score = [0.25, 0.75] + p, r, _ = precision_recall_curve(y_true, y_score) + assert_almost_equal(average_precision_score(y_true, y_score), 1.) + assert_array_almost_equal(p, [1., 1., 1.]) + assert_array_almost_equal(r, [1, 0.5, 0.]) + + # Multi-label classification task + y_true = np.array([[0, 1], [0, 1]]) + y_score = np.array([[0, 1], [0, 1]]) + assert_raises(Exception, average_precision_score, y_true, y_score, + average="macro") + assert_raises(Exception, average_precision_score, y_true, y_score, + average="weighted") + assert_almost_equal(average_precision_score(y_true, y_score, + average="samples"), 1.) + assert_almost_equal(average_precision_score(y_true, y_score, + average="micro"), 1.) + + y_true = np.array([[0, 1], [0, 1]]) + y_score = np.array([[0, 1], [1, 0]]) + assert_raises(Exception, average_precision_score, y_true, y_score, + average="macro") + assert_raises(Exception, average_precision_score, y_true, y_score, + average="weighted") + assert_almost_equal(average_precision_score(y_true, y_score, + average="samples"), 0.625) + assert_almost_equal(average_precision_score(y_true, y_score, + average="micro"), 0.625) + + y_true = np.array([[1, 0], [0, 1]]) + y_score = np.array([[0, 1], [1, 0]]) + assert_almost_equal(average_precision_score(y_true, y_score, + average="macro"), 0.25) + assert_almost_equal(average_precision_score(y_true, y_score, + average="weighted"), 0.25) + assert_almost_equal(average_precision_score(y_true, y_score, + average="samples"), 0.25) + assert_almost_equal(average_precision_score(y_true, y_score, + average="micro"), 0.25) + + y_true = np.array([[1, 0], [0, 1]]) + y_score = np.array([[0.5, 0.5], [0.5, 0.5]]) + assert_almost_equal(average_precision_score(y_true, y_score, + average="macro"), 0.75) + assert_almost_equal(average_precision_score(y_true, y_score, + average="weighted"), 0.75) + assert_almost_equal(average_precision_score(y_true, y_score, + average="samples"), 0.75) + assert_almost_equal(average_precision_score(y_true, y_score, + average="micro"), 0.75) + + +def test_score_scale_invariance(): + # Test that average_precision_score and roc_auc_score are invariant by + # the scaling or shifting of probabilities + y_true, _, probas_pred = make_prediction(binary=True) + + roc_auc = roc_auc_score(y_true, probas_pred) + roc_auc_scaled = roc_auc_score(y_true, 100 * probas_pred) + roc_auc_shifted = roc_auc_score(y_true, probas_pred - 10) + assert_equal(roc_auc, roc_auc_scaled) + assert_equal(roc_auc, roc_auc_shifted) + + pr_auc = average_precision_score(y_true, probas_pred) + pr_auc_scaled = average_precision_score(y_true, 100 * probas_pred) + pr_auc_shifted = average_precision_score(y_true, probas_pred - 10) + assert_equal(pr_auc, pr_auc_scaled) + assert_equal(pr_auc, pr_auc_shifted) + + +def check_lrap_toy(lrap_score): + """Check on several small example that it works """ + assert_almost_equal(lrap_score([[0, 1]], [[0.25, 0.75]]), 1) + assert_almost_equal(lrap_score([[0, 1]], [[0.75, 0.25]]), 1 / 2) + assert_almost_equal(lrap_score([[1, 1]], [[0.75, 0.25]]), 1) + + assert_almost_equal(lrap_score([[0, 0, 1]], [[0.25, 0.5, 0.75]]), 1) + assert_almost_equal(lrap_score([[0, 1, 0]], [[0.25, 0.5, 0.75]]), 1 / 2) + assert_almost_equal(lrap_score([[0, 1, 1]], [[0.25, 0.5, 0.75]]), 1) + assert_almost_equal(lrap_score([[1, 0, 0]], [[0.25, 0.5, 0.75]]), 1 / 3) + assert_almost_equal(lrap_score([[1, 0, 1]], [[0.25, 0.5, 0.75]]), + (2 / 3 + 1 / 1) / 2) + assert_almost_equal(lrap_score([[1, 1, 0]], [[0.25, 0.5, 0.75]]), + (2 / 3 + 1 / 2) / 2) + + assert_almost_equal(lrap_score([[0, 0, 1]], [[0.75, 0.5, 0.25]]), 1 / 3) + assert_almost_equal(lrap_score([[0, 1, 0]], [[0.75, 0.5, 0.25]]), 1 / 2) + assert_almost_equal(lrap_score([[0, 1, 1]], [[0.75, 0.5, 0.25]]), + (1 / 2 + 2 / 3) / 2) + assert_almost_equal(lrap_score([[1, 0, 0]], [[0.75, 0.5, 0.25]]), 1) + assert_almost_equal(lrap_score([[1, 0, 1]], [[0.75, 0.5, 0.25]]), + (1 + 2 / 3) / 2) + assert_almost_equal(lrap_score([[1, 1, 0]], [[0.75, 0.5, 0.25]]), 1) + assert_almost_equal(lrap_score([[1, 1, 1]], [[0.75, 0.5, 0.25]]), 1) + + assert_almost_equal(lrap_score([[0, 0, 1]], [[0.5, 0.75, 0.25]]), 1 / 3) + assert_almost_equal(lrap_score([[0, 1, 0]], [[0.5, 0.75, 0.25]]), 1) + assert_almost_equal(lrap_score([[0, 1, 1]], [[0.5, 0.75, 0.25]]), + (1 + 2 / 3) / 2) + assert_almost_equal(lrap_score([[1, 0, 0]], [[0.5, 0.75, 0.25]]), 1 / 2) + assert_almost_equal(lrap_score([[1, 0, 1]], [[0.5, 0.75, 0.25]]), + (1 / 2 + 2 / 3) / 2) + assert_almost_equal(lrap_score([[1, 1, 0]], [[0.5, 0.75, 0.25]]), 1) + assert_almost_equal(lrap_score([[1, 1, 1]], [[0.5, 0.75, 0.25]]), 1) + + # Tie handling + assert_almost_equal(lrap_score([[1, 0]], [[0.5, 0.5]]), 0.5) + assert_almost_equal(lrap_score([[0, 1]], [[0.5, 0.5]]), 0.5) + assert_almost_equal(lrap_score([[1, 1]], [[0.5, 0.5]]), 1) + + assert_almost_equal(lrap_score([[0, 0, 1]], [[0.25, 0.5, 0.5]]), 0.5) + assert_almost_equal(lrap_score([[0, 1, 0]], [[0.25, 0.5, 0.5]]), 0.5) + assert_almost_equal(lrap_score([[0, 1, 1]], [[0.25, 0.5, 0.5]]), 1) + assert_almost_equal(lrap_score([[1, 0, 0]], [[0.25, 0.5, 0.5]]), 1 / 3) + assert_almost_equal(lrap_score([[1, 0, 1]], [[0.25, 0.5, 0.5]]), + (2 / 3 + 1 / 2) / 2) + assert_almost_equal(lrap_score([[1, 1, 0]], [[0.25, 0.5, 0.5]]), + (2 / 3 + 1 / 2) / 2) + assert_almost_equal(lrap_score([[1, 1, 1]], [[0.25, 0.5, 0.5]]), 1) + + assert_almost_equal(lrap_score([[1, 1, 0]], [[0.5, 0.5, 0.5]]), 2 / 3) + + assert_almost_equal(lrap_score([[1, 1, 1, 0]], [[0.5, 0.5, 0.5, 0.5]]), + 3 / 4) + + +def check_zero_or_all_relevant_labels(lrap_score): + random_state = check_random_state(0) + + for n_labels in range(2, 5): + y_score = random_state.uniform(size=(1, n_labels)) + y_score_ties = np.zeros_like(y_score) + + # No relevant labels + y_true = np.zeros((1, n_labels)) + assert_equal(lrap_score(y_true, y_score), 1.) + assert_equal(lrap_score(y_true, y_score_ties), 1.) + + # Only relevant labels + y_true = np.ones((1, n_labels)) + assert_equal(lrap_score(y_true, y_score), 1.) + assert_equal(lrap_score(y_true, y_score_ties), 1.) + + # Degenerate case: only one label + assert_almost_equal(lrap_score([[1], [0], [1], [0]], + [[0.5], [0.5], [0.5], [0.5]]), 1.) + + +def check_lrap_error_raised(lrap_score): + # Raise value error if not appropriate format + assert_raises(ValueError, lrap_score, + [0, 1, 0], [0.25, 0.3, 0.2]) + assert_raises(ValueError, lrap_score, [0, 1, 2], + [[0.25, 0.75, 0.0], [0.7, 0.3, 0.0], [0.8, 0.2, 0.0]]) + assert_raises(ValueError, lrap_score, [(0), (1), (2)], + [[0.25, 0.75, 0.0], [0.7, 0.3, 0.0], [0.8, 0.2, 0.0]]) + + # Check that that y_true.shape != y_score.shape raise the proper exception + assert_raises(ValueError, lrap_score, [[0, 1], [0, 1]], [0, 1]) + assert_raises(ValueError, lrap_score, [[0, 1], [0, 1]], [[0, 1]]) + assert_raises(ValueError, lrap_score, [[0, 1], [0, 1]], [[0], [1]]) + assert_raises(ValueError, lrap_score, [[0, 1]], [[0, 1], [0, 1]]) + assert_raises(ValueError, lrap_score, [[0], [1]], [[0, 1], [0, 1]]) + assert_raises(ValueError, lrap_score, [[0, 1], [0, 1]], [[0], [1]]) + + +def check_lrap_only_ties(lrap_score): + """Check tie handling in score""" + # Basic check with only ties and increasing label space + for n_labels in range(2, 10): + y_score = np.ones((1, n_labels)) + + # Check for growing number of consecutive relevant + for n_relevant in range(1, n_labels): + # Check for a bunch of positions + for pos in range(n_labels - n_relevant): + y_true = np.zeros((1, n_labels)) + y_true[0, pos:pos + n_relevant] = 1 + assert_almost_equal(lrap_score(y_true, y_score), + n_relevant / n_labels) + + +def check_lrap_without_tie_and_increasing_score(lrap_score): + """ Check that Label ranking average precision works for various""" + # Basic check with increasing label space size and decreasing score + for n_labels in range(2, 10): + y_score = n_labels - (np.arange(n_labels).reshape((1, n_labels)) + 1) + + # First and last + y_true = np.zeros((1, n_labels)) + y_true[0, 0] = 1 + y_true[0, -1] = 1 + assert_almost_equal(lrap_score(y_true, y_score), + (2 / n_labels + 1) / 2) + + # Check for growing number of consecutive relevant label + for n_relevant in range(1, n_labels): + # Check for a bunch of position + for pos in range(n_labels - n_relevant): + y_true = np.zeros((1, n_labels)) + y_true[0, pos:pos + n_relevant] = 1 + assert_almost_equal(lrap_score(y_true, y_score), + sum((r + 1) / ((pos + r + 1) * n_relevant) + for r in range(n_relevant))) + + +def _my_lrap(y_true, y_score): + """Simple implementation of label ranking average precision""" + check_consistent_length(y_true, y_score) + y_true = check_array(y_true) + y_score = check_array(y_score) + n_samples, n_labels = y_true.shape + score = np.empty((n_samples, )) + for i in range(n_samples): + # The best rank correspond to 1. Rank higher than 1 are worse. + # The best inverse ranking correspond to n_labels. + unique_rank, inv_rank = np.unique(y_score[i], return_inverse=True) + n_ranks = unique_rank.size + rank = n_ranks - inv_rank + + # Rank need to be corrected to take into account ties + # ex: rank 1 ex aequo means that both label are rank 2. + corr_rank = np.bincount(rank, minlength=n_ranks + 1).cumsum() + rank = corr_rank[rank] + + relevant = y_true[i].nonzero()[0] + if relevant.size == 0 or relevant.size == n_labels: + score[i] = 1 + continue + + score[i] = 0. + for label in relevant: + # Let's count the number of relevant label with better rank + # (smaller rank). + n_ranked_above = sum(rank[r] <= rank[label] for r in relevant) + + # Weight by the rank of the actual label + score[i] += n_ranked_above / rank[label] + + score[i] /= relevant.size + + return score.mean() + + +def check_alternative_lrap_implementation(lrap_score, n_classes=5, + n_samples=20, random_state=0): + _, y_true = make_multilabel_classification(n_features=1, + allow_unlabeled=False, + return_indicator=True, + random_state=random_state, + n_classes=n_classes, + n_samples=n_samples) + + # Score with ties + y_score = sparse_random_matrix(n_components=y_true.shape[0], + n_features=y_true.shape[1], + random_state=random_state) + + if hasattr(y_score, "toarray"): + y_score = y_score.toarray() + score_lrap = label_ranking_average_precision_score(y_true, y_score) + score_my_lrap = _my_lrap(y_true, y_score) + assert_almost_equal(score_lrap, score_my_lrap) + + # Uniform score + random_state = check_random_state(random_state) + y_score = random_state.uniform(size=(n_samples, n_classes)) + score_lrap = label_ranking_average_precision_score(y_true, y_score) + score_my_lrap = _my_lrap(y_true, y_score) + assert_almost_equal(score_lrap, score_my_lrap) + + +def test_label_ranking_avp(): + for fn in [label_ranking_average_precision_score, _my_lrap]: + yield check_lrap_toy, fn + yield check_lrap_without_tie_and_increasing_score, fn + yield check_lrap_only_ties, fn + yield check_zero_or_all_relevant_labels, fn + yield check_lrap_error_raised, label_ranking_average_precision_score + + for n_samples, n_classes, random_state in product((1, 2, 8, 20), + (2, 5, 10), + range(1)): + yield (check_alternative_lrap_implementation, + label_ranking_average_precision_score, + n_classes, n_samples, random_state) + + +def test_coverage_error(): + # Toy case + assert_almost_equal(coverage_error([[0, 1]], [[0.25, 0.75]]), 1) + assert_almost_equal(coverage_error([[0, 1]], [[0.75, 0.25]]), 2) + assert_almost_equal(coverage_error([[1, 1]], [[0.75, 0.25]]), 2) + assert_almost_equal(coverage_error([[0, 0]], [[0.75, 0.25]]), 0) + + assert_almost_equal(coverage_error([[0, 0, 0]], [[0.25, 0.5, 0.75]]), 0) + assert_almost_equal(coverage_error([[0, 0, 1]], [[0.25, 0.5, 0.75]]), 1) + assert_almost_equal(coverage_error([[0, 1, 0]], [[0.25, 0.5, 0.75]]), 2) + assert_almost_equal(coverage_error([[0, 1, 1]], [[0.25, 0.5, 0.75]]), 2) + assert_almost_equal(coverage_error([[1, 0, 0]], [[0.25, 0.5, 0.75]]), 3) + assert_almost_equal(coverage_error([[1, 0, 1]], [[0.25, 0.5, 0.75]]), 3) + assert_almost_equal(coverage_error([[1, 1, 0]], [[0.25, 0.5, 0.75]]), 3) + assert_almost_equal(coverage_error([[1, 1, 1]], [[0.25, 0.5, 0.75]]), 3) + + assert_almost_equal(coverage_error([[0, 0, 0]], [[0.75, 0.5, 0.25]]), 0) + assert_almost_equal(coverage_error([[0, 0, 1]], [[0.75, 0.5, 0.25]]), 3) + assert_almost_equal(coverage_error([[0, 1, 0]], [[0.75, 0.5, 0.25]]), 2) + assert_almost_equal(coverage_error([[0, 1, 1]], [[0.75, 0.5, 0.25]]), 3) + assert_almost_equal(coverage_error([[1, 0, 0]], [[0.75, 0.5, 0.25]]), 1) + assert_almost_equal(coverage_error([[1, 0, 1]], [[0.75, 0.5, 0.25]]), 3) + assert_almost_equal(coverage_error([[1, 1, 0]], [[0.75, 0.5, 0.25]]), 2) + assert_almost_equal(coverage_error([[1, 1, 1]], [[0.75, 0.5, 0.25]]), 3) + + assert_almost_equal(coverage_error([[0, 0, 0]], [[0.5, 0.75, 0.25]]), 0) + assert_almost_equal(coverage_error([[0, 0, 1]], [[0.5, 0.75, 0.25]]), 3) + assert_almost_equal(coverage_error([[0, 1, 0]], [[0.5, 0.75, 0.25]]), 1) + assert_almost_equal(coverage_error([[0, 1, 1]], [[0.5, 0.75, 0.25]]), 3) + assert_almost_equal(coverage_error([[1, 0, 0]], [[0.5, 0.75, 0.25]]), 2) + assert_almost_equal(coverage_error([[1, 0, 1]], [[0.5, 0.75, 0.25]]), 3) + assert_almost_equal(coverage_error([[1, 1, 0]], [[0.5, 0.75, 0.25]]), 2) + assert_almost_equal(coverage_error([[1, 1, 1]], [[0.5, 0.75, 0.25]]), 3) + + # Non trival case + assert_almost_equal(coverage_error([[0, 1, 0], [1, 1, 0]], + [[0.1, 10., -3], [0, 1, 3]]), + (1 + 3) / 2.) + + assert_almost_equal(coverage_error([[0, 1, 0], [1, 1, 0], [0, 1, 1]], + [[0.1, 10, -3], [0, 1, 3], [0, 2, 0]]), + (1 + 3 + 3) / 3.) + + assert_almost_equal(coverage_error([[0, 1, 0], [1, 1, 0], [0, 1, 1]], + [[0.1, 10, -3], [3, 1, 3], [0, 2, 0]]), + (1 + 3 + 3) / 3.) + + +def test_coverage_tie_handling(): + assert_almost_equal(coverage_error([[0, 0]], [[0.5, 0.5]]), 0) + assert_almost_equal(coverage_error([[1, 0]], [[0.5, 0.5]]), 2) + assert_almost_equal(coverage_error([[0, 1]], [[0.5, 0.5]]), 2) + assert_almost_equal(coverage_error([[1, 1]], [[0.5, 0.5]]), 2) + + assert_almost_equal(coverage_error([[0, 0, 0]], [[0.25, 0.5, 0.5]]), 0) + assert_almost_equal(coverage_error([[0, 0, 1]], [[0.25, 0.5, 0.5]]), 2) + assert_almost_equal(coverage_error([[0, 1, 0]], [[0.25, 0.5, 0.5]]), 2) + assert_almost_equal(coverage_error([[0, 1, 1]], [[0.25, 0.5, 0.5]]), 2) + assert_almost_equal(coverage_error([[1, 0, 0]], [[0.25, 0.5, 0.5]]), 3) + assert_almost_equal(coverage_error([[1, 0, 1]], [[0.25, 0.5, 0.5]]), 3) + assert_almost_equal(coverage_error([[1, 1, 0]], [[0.25, 0.5, 0.5]]), 3) + assert_almost_equal(coverage_error([[1, 1, 1]], [[0.25, 0.5, 0.5]]), 3) diff --git a/sklearn/metrics/tests/test_regression.py b/sklearn/metrics/tests/test_regression.py new file mode 100644 index 0000000000000..4fdcc446efd46 --- /dev/null +++ b/sklearn/metrics/tests/test_regression.py @@ -0,0 +1,78 @@ +from __future__ import division, print_function + +import numpy as np +from itertools import product + +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_equal + +from sklearn.metrics import explained_variance_score +from sklearn.metrics import mean_absolute_error +from sklearn.metrics import mean_squared_error +from sklearn.metrics import median_absolute_error +from sklearn.metrics import r2_score + +from sklearn.metrics.regression import _check_reg_targets + + +def test_regression_metrics(n_samples=50): + y_true = np.arange(n_samples) + y_pred = y_true + 1 + + assert_almost_equal(mean_squared_error(y_true, y_pred), 1.) + assert_almost_equal(mean_absolute_error(y_true, y_pred), 1.) + assert_almost_equal(median_absolute_error(y_true, y_pred), 1.) + assert_almost_equal(r2_score(y_true, y_pred), 0.995, 2) + assert_almost_equal(explained_variance_score(y_true, y_pred), 1.) + + +def test_multioutput_regression(): + y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]]) + y_pred = np.array([[0, 0, 0, 1], [1, 0, 1, 1], [0, 0, 0, 1]]) + + error = mean_squared_error(y_true, y_pred) + assert_almost_equal(error, (1. / 3 + 2. / 3 + 2. / 3) / 4.) + + # mean_absolute_error and mean_squared_error are equal because + # it is a binary problem. + error = mean_absolute_error(y_true, y_pred) + assert_almost_equal(error, (1. / 3 + 2. / 3 + 2. / 3) / 4.) + + error = r2_score(y_true, y_pred) + assert_almost_equal(error, 1 - 5. / 2) + + +def test_regression_metrics_at_limits(): + assert_almost_equal(mean_squared_error([0.], [0.]), 0.00, 2) + assert_almost_equal(mean_absolute_error([0.], [0.]), 0.00, 2) + assert_almost_equal(median_absolute_error([0.], [0.]), 0.00, 2) + assert_almost_equal(explained_variance_score([0.], [0.]), 1.00, 2) + assert_almost_equal(r2_score([0., 1], [0., 1]), 1.00, 2) + + +def test__check_reg_targets(): + # All of length 3 + EXAMPLES = [ + ("continuous", [1, 2, 3], 1), + ("continuous", [[1], [2], [3]], 1), + ("continuous-multioutput", [[1, 1], [2, 2], [3, 1]], 2), + ("continuous-multioutput", [[5, 1], [4, 2], [3, 1]], 2), + ("continuous-multioutput", [[1, 3, 4], [2, 2, 2], [3, 1, 1]], 3), + ] + + for (type1, y1, n_out1), (type2, y2, n_out2) in product(EXAMPLES, + repeat=2): + + if type1 == type2 and n_out1 == n_out2: + y_type, y_check1, y_check2 = _check_reg_targets(y1, y2) + assert_equal(type1, y_type) + if type1 == 'continuous': + assert_array_equal(y_check1, np.reshape(y1, (-1, 1))) + assert_array_equal(y_check2, np.reshape(y2, (-1, 1))) + else: + assert_array_equal(y_check1, y1) + assert_array_equal(y_check2, y2) + else: + assert_raises(ValueError, _check_reg_targets, y1, y2) diff --git a/sklearn/metrics/tests/test_score_objects.py b/sklearn/metrics/tests/test_score_objects.py new file mode 100644 index 0000000000000..3c97dd66e7c02 --- /dev/null +++ b/sklearn/metrics/tests/test_score_objects.py @@ -0,0 +1,353 @@ +import pickle + +import numpy as np + +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_raises_regexp +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import ignore_warnings +from sklearn.utils.testing import assert_not_equal + +from sklearn.base import BaseEstimator +from sklearn.metrics import (f1_score, r2_score, roc_auc_score, fbeta_score, + log_loss, precision_score, recall_score) +from sklearn.metrics.cluster import adjusted_rand_score +from sklearn.metrics.scorer import (check_scoring, _PredictScorer, + _passthrough_scorer) +from sklearn.metrics import make_scorer, get_scorer, SCORERS +from sklearn.svm import LinearSVC +from sklearn.pipeline import make_pipeline +from sklearn.cluster import KMeans +from sklearn.dummy import DummyRegressor +from sklearn.linear_model import Ridge, LogisticRegression +from sklearn.tree import DecisionTreeClassifier +from sklearn.datasets import make_blobs +from sklearn.datasets import make_classification +from sklearn.datasets import make_multilabel_classification +from sklearn.datasets import load_diabetes +from sklearn.cross_validation import train_test_split, cross_val_score +from sklearn.grid_search import GridSearchCV +from sklearn.multiclass import OneVsRestClassifier + + +REGRESSION_SCORERS = ['r2', 'mean_absolute_error', 'mean_squared_error', + 'median_absolute_error'] + +CLF_SCORERS = ['accuracy', 'f1', 'f1_weighted', 'f1_macro', 'f1_micro', + 'roc_auc', 'average_precision', 'precision', + 'precision_weighted', 'precision_macro', 'precision_micro', + 'recall', 'recall_weighted', 'recall_macro', 'recall_micro', + 'log_loss', + 'adjusted_rand_score' # not really, but works + ] + +MULTILABEL_ONLY_SCORERS = ['precision_samples', 'recall_samples', 'f1_samples'] + + +class EstimatorWithoutFit(object): + """Dummy estimator to test check_scoring""" + pass + + +class EstimatorWithFit(BaseEstimator): + """Dummy estimator to test check_scoring""" + def fit(self, X, y): + return self + + +class EstimatorWithFitAndScore(object): + """Dummy estimator to test check_scoring""" + def fit(self, X, y): + return self + + def score(self, X, y): + return 1.0 + + +class EstimatorWithFitAndPredict(object): + """Dummy estimator to test check_scoring""" + def fit(self, X, y): + self.y = y + return self + + def predict(self, X): + return self.y + + +class DummyScorer(object): + """Dummy scorer that always returns 1.""" + def __call__(self, est, X, y): + return 1 + + +def test_check_scoring(): + """Test all branches of check_scoring""" + estimator = EstimatorWithoutFit() + pattern = (r"estimator should a be an estimator implementing 'fit' method," + r" .* was passed") + assert_raises_regexp(TypeError, pattern, check_scoring, estimator) + + estimator = EstimatorWithFitAndScore() + estimator.fit([[1]], [1]) + scorer = check_scoring(estimator) + assert_true(scorer is _passthrough_scorer) + assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) + + estimator = EstimatorWithFitAndPredict() + estimator.fit([[1]], [1]) + pattern = (r"If no scoring is specified, the estimator passed should have" + r" a 'score' method\. The estimator .* does not\.") + assert_raises_regexp(TypeError, pattern, check_scoring, estimator) + + scorer = check_scoring(estimator, "accuracy") + assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) + + estimator = EstimatorWithFit() + scorer = check_scoring(estimator, "accuracy") + assert_true(isinstance(scorer, _PredictScorer)) + + estimator = EstimatorWithFit() + scorer = check_scoring(estimator, allow_none=True) + assert_true(scorer is None) + + +def test_check_scoring_gridsearchcv(): + # test that check_scoring works on GridSearchCV and pipeline. + # slightly redundant non-regression test. + + grid = GridSearchCV(LinearSVC(), param_grid={'C': [.1, 1]}) + scorer = check_scoring(grid, "f1") + assert_true(isinstance(scorer, _PredictScorer)) + + pipe = make_pipeline(LinearSVC()) + scorer = check_scoring(pipe, "f1") + assert_true(isinstance(scorer, _PredictScorer)) + + # check that cross_val_score definitely calls the scorer + # and doesn't make any assumptions about the estimator apart from having a + # fit. + scores = cross_val_score(EstimatorWithFit(), [[1], [2], [3]], [1, 0, 1], + scoring=DummyScorer()) + assert_array_equal(scores, 1) + + +def test_make_scorer(): + """Sanity check on the make_scorer factory function.""" + f = lambda *args: 0 + assert_raises(ValueError, make_scorer, f, needs_threshold=True, + needs_proba=True) + + +def test_classification_scores(): + """Test classification scorers.""" + X, y = make_blobs(random_state=0, centers=2) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + clf = LinearSVC(random_state=0) + clf.fit(X_train, y_train) + + for prefix, metric in [('f1', f1_score), ('precision', precision_score), + ('recall', recall_score)]: + + score1 = get_scorer('%s_weighted' % prefix)(clf, X_test, y_test) + score2 = metric(y_test, clf.predict(X_test), pos_label=None, + average='weighted') + assert_almost_equal(score1, score2) + + score1 = get_scorer('%s_macro' % prefix)(clf, X_test, y_test) + score2 = metric(y_test, clf.predict(X_test), pos_label=None, + average='macro') + assert_almost_equal(score1, score2) + + score1 = get_scorer('%s_micro' % prefix)(clf, X_test, y_test) + score2 = metric(y_test, clf.predict(X_test), pos_label=None, + average='micro') + assert_almost_equal(score1, score2) + + score1 = get_scorer('%s' % prefix)(clf, X_test, y_test) + score2 = metric(y_test, clf.predict(X_test), pos_label=1) + assert_almost_equal(score1, score2) + + # test fbeta score that takes an argument + scorer = make_scorer(fbeta_score, beta=2) + score1 = scorer(clf, X_test, y_test) + score2 = fbeta_score(y_test, clf.predict(X_test), beta=2) + assert_almost_equal(score1, score2) + + # test that custom scorer can be pickled + unpickled_scorer = pickle.loads(pickle.dumps(scorer)) + score3 = unpickled_scorer(clf, X_test, y_test) + assert_almost_equal(score1, score3) + + # smoke test the repr: + repr(fbeta_score) + + +def test_regression_scorers(): + """Test regression scorers.""" + diabetes = load_diabetes() + X, y = diabetes.data, diabetes.target + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + clf = Ridge() + clf.fit(X_train, y_train) + score1 = get_scorer('r2')(clf, X_test, y_test) + score2 = r2_score(y_test, clf.predict(X_test)) + assert_almost_equal(score1, score2) + + +def test_thresholded_scorers(): + """Test scorers that take thresholds.""" + X, y = make_blobs(random_state=0, centers=2) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + clf = LogisticRegression(random_state=0) + clf.fit(X_train, y_train) + score1 = get_scorer('roc_auc')(clf, X_test, y_test) + score2 = roc_auc_score(y_test, clf.decision_function(X_test)) + score3 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) + assert_almost_equal(score1, score2) + assert_almost_equal(score1, score3) + + logscore = get_scorer('log_loss')(clf, X_test, y_test) + logloss = log_loss(y_test, clf.predict_proba(X_test)) + assert_almost_equal(-logscore, logloss) + + # same for an estimator without decision_function + clf = DecisionTreeClassifier() + clf.fit(X_train, y_train) + score1 = get_scorer('roc_auc')(clf, X_test, y_test) + score2 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) + assert_almost_equal(score1, score2) + + # Test that an exception is raised on more than two classes + X, y = make_blobs(random_state=0, centers=3) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + clf.fit(X_train, y_train) + assert_raises(ValueError, get_scorer('roc_auc'), clf, X_test, y_test) + + +def test_thresholded_scorers_multilabel_indicator_data(): + """Test that the scorer work with multilabel-indicator format + for multilabel and multi-output multi-class classifier + """ + X, y = make_multilabel_classification(return_indicator=True, + allow_unlabeled=False, + random_state=0) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + + # Multi-output multi-class predict_proba + clf = DecisionTreeClassifier() + clf.fit(X_train, y_train) + y_proba = clf.predict_proba(X_test) + score1 = get_scorer('roc_auc')(clf, X_test, y_test) + score2 = roc_auc_score(y_test, np.vstack(p[:, -1] for p in y_proba).T) + assert_almost_equal(score1, score2) + + # Multi-output multi-class decision_function + # TODO Is there any yet? + clf = DecisionTreeClassifier() + clf.fit(X_train, y_train) + clf._predict_proba = clf.predict_proba + clf.predict_proba = None + clf.decision_function = lambda X: [p[:, 1] for p in clf._predict_proba(X)] + + y_proba = clf.decision_function(X_test) + score1 = get_scorer('roc_auc')(clf, X_test, y_test) + score2 = roc_auc_score(y_test, np.vstack(p for p in y_proba).T) + assert_almost_equal(score1, score2) + + # Multilabel predict_proba + clf = OneVsRestClassifier(DecisionTreeClassifier()) + clf.fit(X_train, y_train) + score1 = get_scorer('roc_auc')(clf, X_test, y_test) + score2 = roc_auc_score(y_test, clf.predict_proba(X_test)) + assert_almost_equal(score1, score2) + + # Multilabel decision function + clf = OneVsRestClassifier(LinearSVC(random_state=0)) + clf.fit(X_train, y_train) + score1 = get_scorer('roc_auc')(clf, X_test, y_test) + score2 = roc_auc_score(y_test, clf.decision_function(X_test)) + assert_almost_equal(score1, score2) + + +def test_unsupervised_scorers(): + """Test clustering scorers against gold standard labeling.""" + # We don't have any real unsupervised Scorers yet. + X, y = make_blobs(random_state=0, centers=2) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + km = KMeans(n_clusters=3) + km.fit(X_train) + score1 = get_scorer('adjusted_rand_score')(km, X_test, y_test) + score2 = adjusted_rand_score(y_test, km.predict(X_test)) + assert_almost_equal(score1, score2) + + +@ignore_warnings +def test_raises_on_score_list(): + """Test that when a list of scores is returned, we raise proper errors.""" + X, y = make_blobs(random_state=0) + f1_scorer_no_average = make_scorer(f1_score, average=None) + clf = DecisionTreeClassifier() + assert_raises(ValueError, cross_val_score, clf, X, y, + scoring=f1_scorer_no_average) + grid_search = GridSearchCV(clf, scoring=f1_scorer_no_average, + param_grid={'max_depth': [1, 2]}) + assert_raises(ValueError, grid_search.fit, X, y) + + +@ignore_warnings +def test_scorer_sample_weight(): + """Test that scorers support sample_weight or raise sensible errors""" + + # Unlike the metrics invariance test, in the scorer case it's harder + # to ensure that, on the classifier output, weighted and unweighted + # scores really should be unequal. + X, y = make_classification(random_state=0) + _, y_ml = make_multilabel_classification(n_samples=X.shape[0], + return_indicator=True, + random_state=0) + split = train_test_split(X, y, y_ml, random_state=0) + X_train, X_test, y_train, y_test, y_ml_train, y_ml_test = split + + sample_weight = np.ones_like(y_test) + sample_weight[:10] = 0 + + # get sensible estimators for each metric + sensible_regr = DummyRegressor(strategy='median') + sensible_regr.fit(X_train, y_train) + sensible_clf = DecisionTreeClassifier(random_state=0) + sensible_clf.fit(X_train, y_train) + sensible_ml_clf = DecisionTreeClassifier(random_state=0) + sensible_ml_clf.fit(X_train, y_ml_train) + estimator = dict([(name, sensible_regr) + for name in REGRESSION_SCORERS] + + [(name, sensible_clf) + for name in CLF_SCORERS] + + [(name, sensible_ml_clf) + for name in MULTILABEL_ONLY_SCORERS]) + + for name, scorer in SCORERS.items(): + if name in MULTILABEL_ONLY_SCORERS: + target = y_ml_test + else: + target = y_test + try: + weighted = scorer(estimator[name], X_test, target, + sample_weight=sample_weight) + ignored = scorer(estimator[name], X_test[10:], target[10:]) + unweighted = scorer(estimator[name], X_test, target) + assert_not_equal(weighted, unweighted, + msg="scorer {0} behaves identically when " + "called with sample weights: {1} vs " + "{2}".format(name, weighted, unweighted)) + assert_almost_equal(weighted, ignored, + err_msg="scorer {0} behaves differently when " + "ignoring samples and setting sample_weight to" + " 0: {1} vs {2}".format(name, weighted, + ignored)) + + except TypeError as e: + assert_true("sample_weight" in str(e), + "scorer {0} raises unhelpful exception when called " + "with sample weights: {1}".format(name, str(e))) diff --git a/sklearn/mixture/dpgmm.py b/sklearn/mixture/dpgmm.py index 227c96913727a..2ca6694df36bb 100644 --- a/sklearn/mixture/dpgmm.py +++ b/sklearn/mixture/dpgmm.py @@ -1,5 +1,6 @@ """Bayesian Gaussian Mixture Models and Dirichlet Process Gaussian Mixture Models""" +from __future__ import print_function # Author: Alexandre Passos (alexandre.tp@gmail.com) # Bertrand Thirion @@ -10,21 +11,18 @@ # import numpy as np -import warnings from scipy.special import digamma as _digamma, gammaln as _gammaln from scipy import linalg from scipy.spatial.distance import cdist -from ..utils import check_random_state -from ..utils.extmath import norm, logsumexp, pinvh +from ..externals.six.moves import xrange +from ..utils import check_random_state, check_array +from ..utils.extmath import logsumexp, pinvh, squared_norm +from ..utils.validation import check_is_fitted from .. import cluster from .gmm import GMM -def sqnorm(v): - return norm(v) ** 2 - - def digamma(x): return _digamma(x + np.finfo(np.float32).eps) @@ -96,14 +94,14 @@ def _bound_state_log_lik(X, initial_bound, precs, means, covariance_type): bound = np.empty((n_samples, n_components)) bound[:] = initial_bound if covariance_type in ['diag', 'spherical']: - for k in xrange(n_components): + for k in range(n_components): d = X - means[k] bound[:, k] -= 0.5 * np.sum(d * d * precs[k], axis=1) elif covariance_type == 'tied': - for k in xrange(n_components): + for k in range(n_components): bound[:, k] -= 0.5 * _sym_quad_form(X, means[k], precs) elif covariance_type == 'full': - for k in xrange(n_components): + for k in range(n_components): bound[:, k] -= 0.5 * _sym_quad_form(X, means[k], precs[k]) return bound @@ -129,35 +127,40 @@ class DPGMM(GMM): Parameters ---------- - n_components: int, optional - Number of mixture components. Defaults to 1. + n_components: int, default 1 + Number of mixture components. - covariance_type: string, optional + covariance_type: string, default 'diag' String describing the type of covariance parameters to use. Must be one of 'spherical', 'tied', 'diag', 'full'. - Defaults to 'diag'. - alpha: float, optional + alpha: float, default 1 Real number representing the concentration parameter of the dirichlet process. Intuitively, the Dirichlet Process is as likely to start a new cluster for a point as it is to add that point to a cluster with alpha elements. A higher alpha means more clusters, as the expected number - of clusters is ``alpha*log(N)``. Defaults to 1. + of clusters is ``alpha*log(N)``. - thresh : float, optional + tol : float, default 1e-3 Convergence threshold. - n_iter : int, optional + + n_iter : int, default 10 Maximum number of iterations to perform before convergence. - params : string, optional + + params : string, default 'wmc' Controls which parameters are updated in the training process. Can contain any combination of 'w' for weights, - 'm' for means, and 'c' for covars. Defaults to 'wmc'. - init_params : string, optional + 'm' for means, and 'c' for covars. + + init_params : string, default 'wmc' Controls which parameters are updated in the initialization process. Can contain any combination of 'w' for weights, 'm' for means, and 'c' for covars. Defaults to 'wmc'. + verbose : boolean, default False + Controls output verbosity. + Attributes ---------- covariance_type : string @@ -167,13 +170,13 @@ class DPGMM(GMM): n_components : int Number of mixture components. - `weights_` : array, shape (`n_components`,) + weights_ : array, shape (`n_components`,) Mixing weights for each mixture component. - `means_` : array, shape (`n_components`, `n_features`) + means_ : array, shape (`n_components`, `n_features`) Mean parameters for each mixture component. - `precisions_` : array + precs_ : array Precision (inverse covariance) parameters for each mixture component. The shape depends on `covariance_type`:: @@ -182,7 +185,7 @@ class DPGMM(GMM): (`n_components`, `n_features`) if 'diag', (`n_components`, `n_features`, `n_features`) if 'full' - `converged_` : bool + converged_ : bool True when convergence was reached in fit(), False otherwise. See Also @@ -195,13 +198,13 @@ class DPGMM(GMM): """ def __init__(self, n_components=1, covariance_type='diag', alpha=1.0, - random_state=None, thresh=1e-2, verbose=False, + random_state=None, thresh=None, tol=1e-3, verbose=False, min_covar=None, n_iter=10, params='wmc', init_params='wmc'): self.alpha = alpha self.verbose = verbose super(DPGMM, self).__init__(n_components, covariance_type, - random_state=random_state, - thresh=thresh, min_covar=min_covar, + random_state=random_state, thresh=thresh, + tol=tol, min_covar=min_covar, n_iter=n_iter, params=params, init_params=init_params) @@ -221,8 +224,8 @@ def _set_covars(self, covars): raise NotImplementedError("""The variational algorithm does not support setting the covariance parameters.""") - def eval(self, X): - """Evaluate the model on data + def score_samples(self, X): + """Return the likelihood of the data under the model. Compute the bound on log probability of X under the model and return the posterior distribution (responsibilities) of @@ -245,7 +248,9 @@ def eval(self, X): Posterior probabilities of each mixture component for each observation """ - X = np.asarray(X) + check_is_fitted(self, 'gamma_') + + X = check_array(X) if X.ndim == 1: X = X[:, np.newaxis] z = np.zeros((X.shape[0], self.n_components)) @@ -254,7 +259,7 @@ def eval(self, X): dgamma2 = np.zeros(self.n_components) dgamma2[0] = digamma(self.gamma_[0, 2]) - digamma(self.gamma_[0, 1] + self.gamma_[0, 2]) - for j in xrange(1, self.n_components): + for j in range(1, self.n_components): dgamma2[j] = dgamma2[j - 1] + digamma(self.gamma_[j - 1, 2]) dgamma2[j] -= sd[j - 1] dgamma = dgamma1 + dgamma2 @@ -277,14 +282,14 @@ def _update_concentration(self, z): sz = np.sum(z, axis=0) self.gamma_.T[1] = 1. + sz self.gamma_.T[2].fill(0) - for i in xrange(self.n_components - 2, -1, -1): + for i in range(self.n_components - 2, -1, -1): self.gamma_[i, 2] = self.gamma_[i + 1, 2] + sz[i] self.gamma_.T[2] += self.alpha def _update_means(self, X, z): """Update the variational distributions for the means""" n_features = X.shape[1] - for k in xrange(self.n_components): + for k in range(self.n_components): if self.covariance_type in ['spherical', 'diag']: num = np.sum(z.T[k].reshape((-1, 1)) * X, axis=0) num *= self.precs_[k] @@ -305,7 +310,7 @@ def _update_precisions(self, X, z): n_features = X.shape[1] if self.covariance_type == 'spherical': self.dof_ = 0.5 * n_features * np.sum(z, axis=0) - for k in xrange(self.n_components): + for k in range(self.n_components): # could be more memory efficient ? sq_diff = np.sum((X - self.means_[k]) ** 2, axis=1) self.scale_[k] = 1. @@ -316,22 +321,22 @@ def _update_precisions(self, X, z): self.precs_ = np.tile(self.dof_ / self.scale_, [n_features, 1]).T elif self.covariance_type == 'diag': - for k in xrange(self.n_components): + for k in range(self.n_components): self.dof_[k].fill(1. + 0.5 * np.sum(z.T[k], axis=0)) sq_diff = (X - self.means_[k]) ** 2 # see comment above self.scale_[k] = np.ones(n_features) + 0.5 * np.dot( z.T[k], (sq_diff + 1)) self.precs_[k] = self.dof_[k] / self.scale_[k] self.bound_prec_[k] = 0.5 * np.sum(digamma(self.dof_[k]) - - np.log(self.scale_[k])) + - np.log(self.scale_[k])) self.bound_prec_[k] -= 0.5 * np.sum(self.precs_[k]) elif self.covariance_type == 'tied': self.dof_ = 2 + X.shape[0] + n_features self.scale_ = (X.shape[0] + 1) * np.identity(n_features) - for k in xrange(self.n_components): - diff = X - self.means_[k] - self.scale_ += np.dot(diff.T, z[:, k:k + 1] * diff) + for k in range(self.n_components): + diff = X - self.means_[k] + self.scale_ += np.dot(diff.T, z[:, k:k + 1] * diff) self.scale_ = pinvh(self.scale_) self.precs_ = self.dof_ * self.scale_ self.det_scale_ = linalg.det(self.scale_) @@ -340,7 +345,7 @@ def _update_precisions(self, X, z): self.bound_prec_ -= 0.5 * self.dof_ * np.trace(self.scale_) elif self.covariance_type == 'full': - for k in xrange(self.n_components): + for k in range(self.n_components): sum_resp = np.sum(z.T[k]) self.dof_[k] = 2 + sum_resp + n_features self.scale_[k] = (sum_resp + 1) * np.identity(n_features) @@ -349,10 +354,9 @@ def _update_precisions(self, X, z): self.scale_[k] = pinvh(self.scale_[k]) self.precs_[k] = self.dof_[k] * self.scale_[k] self.det_scale_[k] = linalg.det(self.scale_[k]) - self.bound_prec_[k] = 0.5 * wishart_log_det(self.dof_[k], - self.scale_[k], - self.det_scale_[k], - n_features) + self.bound_prec_[k] = 0.5 * wishart_log_det( + self.dof_[k], self.scale_[k], self.det_scale_[k], + n_features) self.bound_prec_[k] -= 0.5 * self.dof_[k] * np.trace( self.scale_[k]) @@ -364,10 +368,10 @@ def _monitor(self, X, z, n, end=False): Note: this is very expensive and should not be used by default.""" if self.verbose: - print "Bound after updating %8s: %f" % (n, self.lower_bound(X, z)) - if end == True: - print "Cluster proportions:", self.gamma_.T[1] - print "covariance_type:", self.covariance_type + print("Bound after updating %8s: %f" % (n, self.lower_bound(X, z))) + if end: + print("Cluster proportions:", self.gamma_.T[1]) + print("covariance_type:", self.covariance_type) def _do_mstep(self, X, z, params): """Maximize the variational lower bound @@ -391,23 +395,23 @@ def _bound_concentration(self): """The variational lower bound for the concentration parameter.""" logprior = gammaln(self.alpha) * self.n_components logprior += np.sum((self.alpha - 1) * ( - digamma(self.gamma_.T[2]) - digamma(self.gamma_.T[1] + - self.gamma_.T[2]))) + digamma(self.gamma_.T[2]) - digamma(self.gamma_.T[1] + + self.gamma_.T[2]))) logprior += np.sum(- gammaln(self.gamma_.T[1] + self.gamma_.T[2])) logprior += np.sum(gammaln(self.gamma_.T[1]) + gammaln(self.gamma_.T[2])) logprior -= np.sum((self.gamma_.T[1] - 1) * ( - digamma(self.gamma_.T[1]) - digamma(self.gamma_.T[1] + - self.gamma_.T[2]))) + digamma(self.gamma_.T[1]) - digamma(self.gamma_.T[1] + + self.gamma_.T[2]))) logprior -= np.sum((self.gamma_.T[2] - 1) * ( - digamma(self.gamma_.T[2]) - digamma(self.gamma_.T[1] + - self.gamma_.T[2]))) + digamma(self.gamma_.T[2]) - digamma(self.gamma_.T[1] + + self.gamma_.T[2]))) return logprior def _bound_means(self): "The variational lower bound for the mean parameters" logprior = 0. - logprior -= 0.5 * sqnorm(self.means_) + logprior -= 0.5 * squared_norm(self.means_) logprior -= 0.5 * self.means_.shape[1] * self.n_components return logprior @@ -418,8 +422,8 @@ def _bound_precisions(self): logprior += np.sum(gammaln(self.dof_)) logprior -= np.sum( (self.dof_ - 1) * digamma(np.maximum(0.5, self.dof_))) - logprior += np.sum(- np.log(self.scale_) + self.dof_ -\ - self.precs_[:, 0]) + logprior += np.sum(- np.log(self.scale_) + self.dof_ + - self.precs_[:, 0]) elif self.covariance_type == 'diag': logprior += np.sum(gammaln(self.dof_)) logprior -= np.sum( @@ -428,7 +432,7 @@ def _bound_precisions(self): elif self.covariance_type == 'tied': logprior += _bound_wishart(self.dof_, self.scale_, self.det_scale_) elif self.covariance_type == 'full': - for k in xrange(self.n_components): + for k in range(self.n_components): logprior += _bound_wishart(self.dof_[k], self.scale_[k], self.det_scale_[k]) @@ -456,25 +460,34 @@ def _logprior(self, z): def lower_bound(self, X, z): """returns a lower bound on model evidence based on X and membership""" + check_is_fitted(self, 'means_') + if self.covariance_type not in ['full', 'tied', 'diag', 'spherical']: raise NotImplementedError("This ctype is not implemented: %s" % self.covariance_type) - X = np.asarray(X) if X.ndim == 1: X = X[:, np.newaxis] - c = np.sum(z * _bound_state_log_lik( - X, self._initial_bound + self.bound_prec_, - self.precs_, self.means_, self.covariance_type)) + c = np.sum(z * _bound_state_log_lik(X, self._initial_bound + + self.bound_prec_, self.precs_, + self.means_, self.covariance_type)) return c + self._logprior(z) - def fit(self, X, **kwargs): + def _set_weights(self): + for i in xrange(self.n_components): + self.weights_[i] = self.gamma_[i, 1] / (self.gamma_[i, 1] + + self.gamma_[i, 2]) + self.weights_ /= np.sum(self.weights_) + + def fit(self, X, y=None): """Estimate model parameters with the variational algorithm. For a full derivation and description of the algorithm see - doc/dp-derivation/dp-derivation.tex + doc/modules/dp-derivation.rst + or + http://scikit-learn.org/stable/modules/dp-derivation.html A initialization step is performed before entering the em algorithm. If you want to avoid this step, set the keyword @@ -488,27 +501,15 @@ def fit(self, X, **kwargs): List of n_features-dimensional data points. Each row corresponds to a single data point. """ - self.random_state = check_random_state(self.random_state) - if kwargs: - warnings.warn("Setting parameters in the 'fit' method is" - "deprecated. Set it on initialization instead.", - DeprecationWarning) - # initialisations for in case the user still adds parameters to fit - # so things don't break - if 'n_iter' in kwargs: - self.n_iter = kwargs['n_iter'] - if 'params' in kwargs: - self.params = kwargs['params'] - if 'init_params' in kwargs: - self.init_params = kwargs['init_params'] - - ## initialization step - X = np.asarray(X) + self.random_state_ = check_random_state(self.random_state) + + # initialization step + X = check_array(X) if X.ndim == 1: X = X[:, np.newaxis] - n_features = X.shape[1] - z = np.ones((X.shape[0], self.n_components)) + n_samples, n_features = X.shape + z = np.ones((n_samples, self.n_components)) z /= self.n_components self._initial_bound = - 0.5 * n_features * np.log(2 * np.pi) @@ -520,7 +521,7 @@ def fit(self, X, **kwargs): if 'm' in self.init_params or not hasattr(self, 'means_'): self.means_ = cluster.KMeans( n_clusters=self.n_components, - random_state=self.random_state).fit(X).cluster_centers_[::-1] + random_state=self.random_state_).fit(X).cluster_centers_[::-1] if 'w' in self.init_params or not hasattr(self, 'weights_'): self.weights_ = np.tile(1.0 / self.n_components, self.n_components) @@ -549,15 +550,15 @@ def fit(self, X, **kwargs): self.dof_, self.scale_, self.det_scale_, n_features) self.bound_prec_ -= 0.5 * self.dof_ * np.trace(self.scale_) elif self.covariance_type == 'full': - self.dof_ = (1 + self.n_components + X.shape[0]) + self.dof_ = (1 + self.n_components + n_samples) self.dof_ *= np.ones(self.n_components) self.scale_ = [2 * np.identity(n_features) - for i in xrange(self.n_components)] + for _ in range(self.n_components)] self.precs_ = [np.identity(n_features) - for i in xrange(self.n_components)] + for _ in range(self.n_components)] self.det_scale_ = np.ones(self.n_components) self.bound_prec_ = np.zeros(self.n_components) - for k in xrange(self.n_components): + for k in range(self.n_components): self.bound_prec_[k] = wishart_log_det( self.dof_[k], self.scale_[k], self.det_scale_[k], n_features) @@ -565,22 +566,37 @@ def fit(self, X, **kwargs): np.trace(self.scale_[k])) self.bound_prec_ *= 0.5 - logprob = [] + # EM algorithms + current_log_likelihood = None # reset self.converged_ to False self.converged_ = False - for i in xrange(self.n_iter): + + # this line should be removed when 'thresh' is removed in v0.18 + tol = (self.tol if self.thresh is None + else self.thresh / float(n_samples)) + + for i in range(self.n_iter): + prev_log_likelihood = current_log_likelihood # Expectation step - curr_logprob, z = self.eval(X) - logprob.append(curr_logprob.sum() + self._logprior(z)) + curr_logprob, z = self.score_samples(X) + + current_log_likelihood = ( + curr_logprob.mean() + self._logprior(z) / n_samples) # Check for convergence. - if i > 0 and abs(logprob[-1] - logprob[-2]) < self.thresh: - self.converged_ = True - break + # (should compare to self.tol when dreprecated 'thresh' is + # removed in v0.18) + if prev_log_likelihood is not None: + change = abs(current_log_likelihood - prev_log_likelihood) + if change < tol: + self.converged_ = True + break # Maximization step self._do_mstep(X, z, self.params) + self._set_weights() + return self @@ -597,21 +613,37 @@ class VBGMM(DPGMM): Parameters ---------- - n_components: int, optional - Number of mixture components. Defaults to 1. + n_components: int, default 1 + Number of mixture components. - covariance_type: string, optional + covariance_type: string, default 'diag' String describing the type of covariance parameters to use. Must be one of 'spherical', 'tied', 'diag', 'full'. - Defaults to 'diag'. - alpha: float, optional + alpha: float, default 1 Real number representing the concentration parameter of the dirichlet distribution. Intuitively, the higher the value of alpha the more likely the variational mixture of - Gaussians model will use all components it can. Defaults - to 1. + Gaussians model will use all components it can. + + tol : float, default 1e-3 + Convergence threshold. + + n_iter : int, default 10 + Maximum number of iterations to perform before convergence. + + params : string, default 'wmc' + Controls which parameters are updated in the training + process. Can contain any combination of 'w' for weights, + 'm' for means, and 'c' for covars. + + init_params : string, default 'wmc' + Controls which parameters are updated in the initialization + process. Can contain any combination of 'w' for weights, + 'm' for means, and 'c' for covars. Defaults to 'wmc'. + verbose : boolean, default False + Controls output verbosity. Attributes ---------- @@ -625,13 +657,13 @@ class VBGMM(DPGMM): n_components : int (read-only) Number of mixture components. - `weights_` : array, shape (`n_components`,) + weights_ : array, shape (`n_components`,) Mixing weights for each mixture component. - `means_` : array, shape (`n_components`, `n_features`) + means_ : array, shape (`n_components`, `n_features`) Mean parameters for each mixture component. - `precisions_` : array + precs_ : array Precision (inverse covariance) parameters for each mixture component. The shape depends on `covariance_type`:: @@ -640,28 +672,28 @@ class VBGMM(DPGMM): (`n_components`, `n_features`) if 'diag', (`n_components`, `n_features`, `n_features`) if 'full' - `converged_` : bool + converged_ : bool True when convergence was reached in fit(), False otherwise. See Also -------- GMM : Finite Gaussian mixture model fit with EM - DPGMM : Ininite Gaussian mixture model, using the dirichlet + DPGMM : Infinite Gaussian mixture model, using the dirichlet process, fit with a variational algorithm """ def __init__(self, n_components=1, covariance_type='diag', alpha=1.0, - random_state=None, thresh=1e-2, verbose=False, + random_state=None, thresh=None, tol=1e-3, verbose=False, min_covar=None, n_iter=10, params='wmc', init_params='wmc'): super(VBGMM, self).__init__( n_components, covariance_type, random_state=random_state, - thresh=thresh, verbose=verbose, min_covar=min_covar, + thresh=thresh, tol=tol, verbose=verbose, min_covar=min_covar, n_iter=n_iter, params=params, init_params=init_params) self.alpha = float(alpha) / n_components - def eval(self, X): - """Evaluate the model on data + def score_samples(self, X): + """Return the likelihood of the data under the model. Compute the bound on log probability of X under the model and return the posterior distribution (responsibilities) of @@ -684,20 +716,19 @@ def eval(self, X): Posterior probabilities of each mixture component for each observation """ - X = np.asarray(X) + check_is_fitted(self, 'gamma_') + + X = check_array(X) if X.ndim == 1: X = X[:, np.newaxis] - z = np.zeros((X.shape[0], self.n_components)) - p = np.zeros(self.n_components) - bound = np.zeros(X.shape[0]) dg = digamma(self.gamma_) - digamma(np.sum(self.gamma_)) if self.covariance_type not in ['full', 'tied', 'diag', 'spherical']: raise NotImplementedError("This ctype is not implemented: %s" % self.covariance_type) - p = _bound_state_log_lik( - X, self._initial_bound + self.bound_prec_, - self.precs_, self.means_, self.covariance_type) + p = _bound_state_log_lik(X, self._initial_bound + self.bound_prec_, + self.precs_, self.means_, + self.covariance_type) z = p + dg z = log_normalize(z, axis=-1) @@ -705,7 +736,7 @@ def eval(self, X): return bound, z def _update_concentration(self, z): - for i in xrange(self.n_components): + for i in range(self.n_components): self.gamma_[i] = self.alpha + np.sum(z.T[i]) def _initialize_gamma(self): @@ -738,7 +769,11 @@ def _monitor(self, X, z, n, end=False): Note: this is very expensive and should not be used by default.""" if self.verbose: - print "Bound after updating %8s: %f" % (n, self.lower_bound(X, z)) - if end == True: - print "Cluster proportions:", self.gamma_ - print "covariance_type:", self.covariance_type + print("Bound after updating %8s: %f" % (n, self.lower_bound(X, z))) + if end: + print("Cluster proportions:", self.gamma_) + print("covariance_type:", self.covariance_type) + + def _set_weights(self): + self.weights_[:] = self.gamma_ + self.weights_ /= np.sum(self.weights_) diff --git a/sklearn/mixture/gmm.py b/sklearn/mixture/gmm.py index 1e335ab798ce8..dd46ac2b49a16 100644 --- a/sklearn/mixture/gmm.py +++ b/sklearn/mixture/gmm.py @@ -9,13 +9,18 @@ # Fabian Pedregosa # Bertrand Thirion +import warnings import numpy as np +from scipy import linalg from ..base import BaseEstimator -from ..utils import check_random_state -from ..utils.extmath import logsumexp, pinvh +from ..utils import check_random_state, check_array +from ..utils.extmath import logsumexp +from ..utils.validation import check_is_fitted from .. import cluster +from sklearn.externals.six.moves import zip + EPS = np.finfo(float).eps @@ -65,7 +70,7 @@ def sample_gaussian(mean, covar, covariance_type='diag', n_samples=1, mean : array_like, shape (n_features,) Mean of the distribution. - covars : array_like, optional + covar : array_like, optional Covariance of the distribution. The shape depends on `covariance_type`: scalar if 'spherical', (n_features) if 'diag', @@ -94,11 +99,11 @@ def sample_gaussian(mean, covar, covariance_type='diag', n_samples=1, elif covariance_type == 'diag': rand = np.dot(np.diag(np.sqrt(covar)), rand) else: - from scipy import linalg - U, s, V = linalg.svd(covar) - sqrtS = np.diag(np.sqrt(s)) - sqrt_covar = np.dot(U, np.dot(sqrtS, V)) - rand = np.dot(sqrt_covar, rand) + s, U = linalg.eigh(covar) + s.clip(0, out=s) # get rid of tiny negatives + np.sqrt(s, out=s) + U *= s + rand = np.dot(U, rand) return (rand.T + mean).T @@ -124,15 +129,16 @@ class GMM(BaseEstimator): use. Must be one of 'spherical', 'tied', 'diag', 'full'. Defaults to 'diag'. - random_state: RandomState or an int seed (0 by default) + random_state: RandomState or an int seed (None by default) A random number generator instance min_covar : float, optional Floor on the diagonal of the covariance matrix to prevent overfitting. Defaults to 1e-3. - thresh : float, optional - Convergence threshold. + tol : float, optional + Convergence threshold. EM iterations will stop when average + gain in log-likelihood is below this threshold. Defaults to 1e-3. n_iter : int, optional Number of EM iterations to perform. @@ -152,22 +158,22 @@ class GMM(BaseEstimator): Attributes ---------- - `weights_` : array, shape (`n_components`,) + weights_ : array, shape (`n_components`,) This attribute stores the mixing weights for each mixture component. - `means_` : array, shape (`n_components`, `n_features`) + means_ : array, shape (`n_components`, `n_features`) Mean parameters for each mixture component. - `covars_` : array + covars_ : array Covariance parameters for each mixture component. The shape depends on `covariance_type`:: - (n_components,) if 'spherical', + (n_components, n_features) if 'spherical', (n_features, n_features) if 'tied', (n_components, n_features) if 'diag', (n_components, n_features, n_features) if 'full' - `converged_` : bool + converged_ : bool True when convergence was reached in fit(), False otherwise. @@ -175,7 +181,7 @@ class GMM(BaseEstimator): See Also -------- - DPGMM : Ininite gaussian mixture model, using the dirichlet + DPGMM : Infinite gaussian mixture model, using the dirichlet process, fit with a variational algorithm @@ -197,7 +203,7 @@ class GMM(BaseEstimator): >>> g.fit(obs) # doctest: +NORMALIZE_WHITESPACE GMM(covariance_type='diag', init_params='wmc', min_covar=0.001, n_components=2, n_init=1, n_iter=100, params='wmc', - random_state=None, thresh=0.01) + random_state=None, thresh=None, tol=0.001) >>> np.round(g.weights_, 2) array([ 0.75, 0.25]) >>> np.round(g.means_, 2) @@ -215,18 +221,23 @@ class GMM(BaseEstimator): >>> g.fit(20 * [[0]] + 20 * [[10]]) # doctest: +NORMALIZE_WHITESPACE GMM(covariance_type='diag', init_params='wmc', min_covar=0.001, n_components=2, n_init=1, n_iter=100, params='wmc', - random_state=None, thresh=0.01) + random_state=None, thresh=None, tol=0.001) >>> np.round(g.weights_, 2) array([ 0.5, 0.5]) """ def __init__(self, n_components=1, covariance_type='diag', - random_state=None, thresh=1e-2, min_covar=1e-3, + random_state=None, thresh=None, tol=1e-3, min_covar=1e-3, n_iter=100, n_init=1, params='wmc', init_params='wmc'): + if thresh is not None: + warnings.warn("'thresh' has been replaced by 'tol' in 0.16 " + " and will be removed in 0.18.", + DeprecationWarning) self.n_components = n_components self.covariance_type = covariance_type self.thresh = thresh + self.tol = tol self.min_covar = min_covar self.random_state = random_state self.n_iter = n_iter @@ -234,9 +245,9 @@ def __init__(self, n_components=1, covariance_type='diag', self.params = params self.init_params = init_params - if not covariance_type in ['spherical', 'tied', 'diag', 'full']: + if covariance_type not in ['spherical', 'tied', 'diag', 'full']: raise ValueError('Invalid value for covariance_type: %s' % - covariance_type) + covariance_type) if n_init < 1: raise ValueError('GMM estimation requires at least one run') @@ -271,8 +282,8 @@ def _set_covars(self, covars): _validate_covars(covars, self.covariance_type, self.n_components) self.covars_ = covars - def eval(self, X): - """Evaluate the model on data + def score_samples(self, X): + """Return the per-sample likelihood of the data under the model. Compute the log probability of X under the model and return the posterior distribution (responsibilities) of each @@ -281,33 +292,36 @@ def eval(self, X): Parameters ---------- X: array_like, shape (n_samples, n_features) - List of n_features-dimensional data points. Each row + List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- - logprob: array_like, shape (n_samples,) - Log probabilities of each data point in X - responsibilities: array_like, shape (n_samples, n_components) + logprob : array_like, shape (n_samples,) + Log probabilities of each data point in X. + + responsibilities : array_like, shape (n_samples, n_components) Posterior probabilities of each mixture component for each observation """ - X = np.asarray(X) + check_is_fitted(self, 'means_') + + X = check_array(X) if X.ndim == 1: X = X[:, np.newaxis] if X.size == 0: return np.array([]), np.empty((0, self.n_components)) if X.shape[1] != self.means_.shape[1]: - raise ValueError('the shape of X is not compatible with self') + raise ValueError('The shape of X is not compatible with self') - lpr = (log_multivariate_normal_density( - X, self.means_, self.covars_, self.covariance_type) + lpr = (log_multivariate_normal_density(X, self.means_, self.covars_, + self.covariance_type) + np.log(self.weights_)) logprob = logsumexp(lpr, axis=1) responsibilities = np.exp(lpr - logprob[:, np.newaxis]) return logprob, responsibilities - def score(self, X): + def score(self, X, y=None): """Compute the log probability under the model. Parameters @@ -321,7 +335,7 @@ def score(self, X): logprob : array_like, shape (n_samples,) Log probabilities of each data point in X """ - logprob, _ = self.eval(X) + logprob, _ = self.score_samples(X) return logprob def predict(self, X): @@ -335,7 +349,7 @@ def predict(self, X): ------- C : array, shape = (n_samples,) """ - logprob, responsibilities = self.eval(X) + logprob, responsibilities = self.score_samples(X) return responsibilities.argmax(axis=1) def predict_proba(self, X): @@ -352,7 +366,7 @@ def predict_proba(self, X): Returns the probability of the sample for each Gaussian (state) in the model. """ - logprob, responsibilities = self.eval(X) + logprob, responsibilities = self.score_samples(X) return responsibilities def sample(self, n_samples=1, random_state=None): @@ -368,6 +382,8 @@ def sample(self, n_samples=1, random_state=None): X : array_like, shape (n_samples, n_features) List of samples """ + check_is_fitted(self, 'means_') + if random_state is None: random_state = self.random_state random_state = check_random_state(random_state) @@ -378,7 +394,7 @@ def sample(self, n_samples=1, random_state=None): # decide which component to use for each sample comps = weight_cdf.searchsorted(rand) # for each component, generate all needed samples - for comp in xrange(self.n_components): + for comp in range(self.n_components): # occurrences of current component in X comp_in_X = (comp == comps) # number of those occurrences @@ -395,7 +411,7 @@ def sample(self, n_samples=1, random_state=None): num_comp_in_X, random_state=random_state).T return X - def fit(self, X): + def fit(self, X, y=None): """Estimate model parameters with the expectation-maximization algorithm. @@ -411,10 +427,8 @@ def fit(self, X): List of n_features-dimensional data points. Each row corresponds to a single data point. """ - ## initialization step - X = np.asarray(X, dtype=np.float) - if X.ndim == 1: - X = X[:, np.newaxis] + # initialization step + X = check_array(X, dtype=np.float64) if X.shape[0] < self.n_components: raise ValueError( 'GMM estimation with %s components, but got only %s samples' % @@ -425,7 +439,8 @@ def fit(self, X): for _ in range(self.n_init): if 'm' in self.init_params or not hasattr(self, 'means_'): self.means_ = cluster.KMeans( - n_clusters=self.n_components).fit(X).cluster_centers_ + n_clusters=self.n_components, + random_state=self.random_state).fit(X).cluster_centers_ if 'w' in self.init_params or not hasattr(self, 'weights_'): self.weights_ = np.tile(1.0 / self.n_components, @@ -437,31 +452,40 @@ def fit(self, X): cv.shape = (1, 1) self.covars_ = \ distribute_covar_matrix_to_match_covariance_type( - cv, self.covariance_type, self.n_components) + cv, self.covariance_type, self.n_components) # EM algorithms - log_likelihood = [] + current_log_likelihood = None # reset self.converged_ to False self.converged_ = False - for i in xrange(self.n_iter): + + # this line should be removed when 'thresh' is removed in v0.18 + tol = (self.tol if self.thresh is None + else self.thresh / float(X.shape[0])) + + for i in range(self.n_iter): + prev_log_likelihood = current_log_likelihood # Expectation step - curr_log_likelihood, responsibilities = self.eval(X) - log_likelihood.append(curr_log_likelihood.sum()) + log_likelihoods, responsibilities = self.score_samples(X) + current_log_likelihood = log_likelihoods.mean() # Check for convergence. - if i > 0 and abs(log_likelihood[-1] - log_likelihood[-2]) < \ - self.thresh: - self.converged_ = True - break + # (should compare to self.tol when dreprecated 'thresh' is + # removed in v0.18) + if prev_log_likelihood is not None: + change = abs(current_log_likelihood - prev_log_likelihood) + if change < tol: + self.converged_ = True + break # Maximization step self._do_mstep(X, responsibilities, self.params, - self.min_covar) + self.min_covar) # if the results are better, keep it if self.n_iter: - if log_likelihood[-1] > max_log_prob: - max_log_prob = log_likelihood[-1] + if current_log_likelihood > max_log_prob: + max_log_prob = current_log_likelihood best_params = {'weights': self.weights_, 'means': self.means_, 'covars': self.covars_} @@ -509,7 +533,7 @@ def _n_parameters(self): elif self.covariance_type == 'spherical': cov_params = self.n_components mean_params = ndim * self.n_components - return int(cov_params + mean_params + self.n_components - 1) + return int(cov_params + mean_params + self.n_components - 1) def bic(self, X): """Bayesian information criterion for the current model fit @@ -523,8 +547,8 @@ def bic(self, X): ------- bic: float (the lower the better) """ - return (- 2 * self.score(X).sum() + - self._n_parameters() * np.log(X.shape[0])) + return (-2 * self.score(X).sum() + + self._n_parameters() * np.log(X.shape[0])) def aic(self, X): """Akaike information criterion for the current model fit @@ -546,7 +570,7 @@ def aic(self, X): ######################################################################### -def _log_multivariate_normal_density_diag(X, means=0.0, covars=1.0): +def _log_multivariate_normal_density_diag(X, means, covars): """Compute Gaussian log-density at X for a diagonal model""" n_samples, n_dim = X.shape lpr = -0.5 * (n_dim * np.log(2 * np.pi) + np.sum(np.log(covars), 1) @@ -556,7 +580,7 @@ def _log_multivariate_normal_density_diag(X, means=0.0, covars=1.0): return lpr -def _log_multivariate_normal_density_spherical(X, means=0.0, covars=1.0): +def _log_multivariate_normal_density_spherical(X, means, covars): """Compute Gaussian log-density at X for a spherical model""" cv = covars.copy() if covars.ndim == 1: @@ -568,42 +592,28 @@ def _log_multivariate_normal_density_spherical(X, means=0.0, covars=1.0): def _log_multivariate_normal_density_tied(X, means, covars): """Compute Gaussian log-density at X for a tied model""" - from scipy import linalg - n_samples, n_dim = X.shape - icv = pinvh(covars) - lpr = -0.5 * (n_dim * np.log(2 * np.pi) + np.log(linalg.det(covars) + 0.1) - + np.sum(X * np.dot(X, icv), 1)[:, np.newaxis] - - 2 * np.dot(np.dot(X, icv), means.T) - + np.sum(means * np.dot(means, icv), 1)) - return lpr + cv = np.tile(covars, (means.shape[0], 1, 1)) + return _log_multivariate_normal_density_full(X, means, cv) def _log_multivariate_normal_density_full(X, means, covars, min_covar=1.e-7): """Log probability for full covariance matrices. """ - from scipy import linalg - import itertools - if hasattr(linalg, 'solve_triangular'): - # only in scipy since 0.9 - solve_triangular = linalg.solve_triangular - else: - # slower, but works - solve_triangular = linalg.solve n_samples, n_dim = X.shape nmix = len(means) log_prob = np.empty((n_samples, nmix)) - for c, (mu, cv) in enumerate(itertools.izip(means, covars)): + for c, (mu, cv) in enumerate(zip(means, covars)): try: cv_chol = linalg.cholesky(cv, lower=True) except linalg.LinAlgError: - # The model is most probabily stuck in a component with too + # The model is most probably stuck in a component with too # few observations, we need to reinitialize this components cv_chol = linalg.cholesky(cv + min_covar * np.eye(n_dim), lower=True) cv_log_det = 2 * np.sum(np.log(np.diagonal(cv_chol))) - cv_sol = solve_triangular(cv_chol, (X - mu).T, lower=True).T - log_prob[:, c] = - .5 * (np.sum(cv_sol ** 2, axis=1) + \ - n_dim * np.log(2 * np.pi) + cv_log_det) + cv_sol = linalg.solve_triangular(cv_chol, (X - mu).T, lower=True).T + log_prob[:, c] = - .5 * (np.sum(cv_sol ** 2, axis=1) + + n_dim * np.log(2 * np.pi) + cv_log_det) return log_prob @@ -626,7 +636,7 @@ def _validate_covars(covars, covariance_type, n_components): "positive-definite") elif covariance_type == 'diag': if len(covars.shape) != 2: - raise ValueError("'diag' covars must have shape" + raise ValueError("'diag' covars must have shape " "(n_components, n_dim)") elif np.any(covars <= 0): raise ValueError("'diag' covars must be non-negative") @@ -639,7 +649,7 @@ def _validate_covars(covars, covariance_type, n_components): "(n_components, n_dim, n_dim)") for n, cv in enumerate(covars): if (not np.allclose(cv, cv.T) - or np.any(linalg.eigvalsh(cv) <= 0)): + or np.any(linalg.eigvalsh(cv) <= 0)): raise ValueError("component %d of 'full' covars must be " "symmetric, positive-definite" % n) else: @@ -648,7 +658,7 @@ def _validate_covars(covars, covariance_type, n_components): def distribute_covar_matrix_to_match_covariance_type( - tied_cv, covariance_type, n_components): + tied_cv, covariance_type, n_components): """Create all the covariance matrices from a given template """ if covariance_type == 'spherical': @@ -688,24 +698,27 @@ def _covar_mstep_full(gmm, X, responsibilities, weighted_X_sum, norm, # Distribution" n_features = X.shape[1] cv = np.empty((gmm.n_components, n_features, n_features)) - for c in xrange(gmm.n_components): + for c in range(gmm.n_components): post = responsibilities[:, c] - # Underflow Errors in doing post * X.T are not important - np.seterr(under='ignore') - avg_cv = np.dot(post * X.T, X) / (post.sum() + 10 * EPS) - mu = gmm.means_[c][np.newaxis] - cv[c] = (avg_cv - np.dot(mu.T, mu) + min_covar * np.eye(n_features)) + mu = gmm.means_[c] + diff = X - mu + with np.errstate(under='ignore'): + # Underflow Errors in doing post * X.T are not important + avg_cv = np.dot(post * diff.T, diff) / (post.sum() + 10 * EPS) + cv[c] = avg_cv + min_covar * np.eye(n_features) return cv def _covar_mstep_tied(gmm, X, responsibilities, weighted_X_sum, norm, min_covar): # Eq. 15 from K. Murphy, "Fitting a Conditional Linear Gaussian - n_features = X.shape[1] + # Distribution" avg_X2 = np.dot(X.T, X) avg_means2 = np.dot(gmm.means_.T, weighted_X_sum) - return (avg_X2 - avg_means2 + min_covar * np.eye(n_features)) / X.shape[0] - + out = avg_X2 - avg_means2 + out *= 1. / X.shape[0] + out.flat[::len(out) + 1] += min_covar + return out _covar_mstep_funcs = {'spherical': _covar_mstep_spherical, 'diag': _covar_mstep_diag, diff --git a/sklearn/mixture/tests/test_dpgmm.py b/sklearn/mixture/tests/test_dpgmm.py index a1a9475178d9e..8c848fc58d66c 100644 --- a/sklearn/mixture/tests/test_dpgmm.py +++ b/sklearn/mixture/tests/test_dpgmm.py @@ -6,11 +6,30 @@ from sklearn.mixture import DPGMM, VBGMM from sklearn.mixture.dpgmm import log_normalize -from .test_gmm import GMMTester +from sklearn.datasets import make_blobs +from sklearn.utils.testing import assert_array_less +from sklearn.mixture.tests.test_gmm import GMMTester np.seterr(all='warn') +def test_class_weights(): + # check that the class weights are updated + # simple 3 cluster dataset + X, y = make_blobs(random_state=1) + for Model in [DPGMM, VBGMM]: + dpgmm = Model(n_components=10, random_state=1, alpha=20, n_iter=50) + dpgmm.fit(X) + # get indices of components that are used: + indices = np.unique(dpgmm.predict(X)) + active = np.zeros(10, dtype=np.bool) + active[indices] = True + # used components are important + assert_array_less(.1, dpgmm.weights_[active]) + # others are not + assert_array_less(dpgmm.weights_[~active], .05) + + def test_log_normalize(): v = np.array([0.1, 0.8, 0.01, 0.09]) a = np.log(2 * v) @@ -26,7 +45,7 @@ class DPGMMTester(GMMTester): do_test_eval = False def score(self, g, train_obs): - _, z = g.eval(train_obs) + _, z = g.score_samples(train_obs) return g.lower_bound(train_obs, z) @@ -55,7 +74,7 @@ class VBGMMTester(GMMTester): do_test_eval = False def score(self, g, train_obs): - _, z = g.eval(train_obs) + _, z = g.score_samples(train_obs) return g.lower_bound(train_obs, z) diff --git a/sklearn/mixture/tests/test_gmm.py b/sklearn/mixture/tests/test_gmm.py index 87e351b4a812b..984218c4fae24 100644 --- a/sklearn/mixture/tests/test_gmm.py +++ b/sklearn/mixture/tests/test_gmm.py @@ -1,13 +1,13 @@ -import itertools import unittest from nose.tools import assert_true import numpy as np -from numpy.testing import assert_array_equal, assert_array_almost_equal, \ - assert_raises +from numpy.testing import (assert_array_equal, assert_array_almost_equal, + assert_raises) from scipy import stats from sklearn import mixture from sklearn.datasets.samples_generator import make_spd_matrix +from sklearn.utils.testing import assert_greater rng = np.random.RandomState(0) @@ -46,12 +46,20 @@ def test_sample_gaussian(): assert_true(np.allclose(samples.mean(axis), mu, atol=1.3)) assert_true(np.allclose(np.cov(samples), cv, atol=2.5)) + # Numerical stability check: in SciPy 0.12.0 at least, eigh may return + # tiny negative values in its second return value. + from sklearn.mixture import sample_gaussian + x = sample_gaussian([0, 0], [[4, 3], [1, .1]], + covariance_type='full', random_state=42) + print(x) + assert_true(np.isfinite(x).all()) + def _naive_lmvnpdf_diag(X, mu, cv): # slow and naive implementation of lmvnpdf ref = np.empty((len(X), len(mu))) stds = np.sqrt(cv) - for i, (m, std) in enumerate(itertools.izip(mu, stds)): + for i, (m, std) in enumerate(zip(mu, stds)): ref[:, i] = np.log(stats.norm.pdf(X, m, std)).sum(axis=1) return ref @@ -138,15 +146,15 @@ def _setUp(self): self.means = rng.randint(-20, 20, (self.n_components, self.n_features)) self.threshold = -0.5 self.I = np.eye(self.n_features) - self.covars = {'spherical': (0.1 + 2 * \ - rng.rand(self.n_components, self.n_features)) ** 2, - 'tied': make_spd_matrix(self.n_features, random_state=0) +\ - 5 * self.I, - 'diag': (0.1 + 2 * rng.rand(self.n_components,\ - self.n_features)) ** 2, - 'full': np.array([make_spd_matrix(self.n_features,\ - random_state=0) - + 5 * self.I for x in range(self.n_components)])} + self.covars = { + 'spherical': (0.1 + 2 * rng.rand(self.n_components, + self.n_features)) ** 2, + 'tied': (make_spd_matrix(self.n_features, random_state=0) + + 5 * self.I), + 'diag': (0.1 + 2 * rng.rand(self.n_components, + self.n_features)) ** 2, + 'full': np.array([make_spd_matrix(self.n_features, random_state=0) + + 5 * self.I for x in range(self.n_components)])} def test_eval(self): if not self.do_test_eval: @@ -162,11 +170,11 @@ def test_eval(self): g.covars_ = self.covars[self.covariance_type] g.weights_ = self.weights - gaussidx = np.repeat(range(self.n_components), 5) + gaussidx = np.repeat(np.arange(self.n_components), 5) n_samples = len(gaussidx) X = rng.randn(n_samples, self.n_features) + g.means_[gaussidx] - ll, responsibilities = g.eval(X) + ll, responsibilities = g.score_samples(X) self.assertEqual(len(ll), n_samples) self.assertEqual(responsibilities.shape, @@ -185,7 +193,7 @@ def test_sample(self, n=100): g.weights_ = self.weights samples = g.sample(n) - self.assertEquals(samples.shape, (n, self.n_features)) + self.assertEqual(samples.shape, (n, self.n_features)) def test_train(self, params='wmc'): g = mixture.GMM(n_components=self.n_components, @@ -206,7 +214,7 @@ def test_train(self, params='wmc'): # the log likelihood to make sure that it increases after each # iteration. trainll = [] - for iter in xrange(5): + for _ in range(5): g.params = params g.init_params = '' g.fit(X) @@ -309,6 +317,24 @@ def test_n_parameters(): assert_true(g._n_parameters() == n_params[cv_type]) +def test_1d_1component(): + """ + Test all of the covariance_types return the same BIC score for + 1-dimensional, 1 component fits. + """ + n_samples, n_dim, n_components = 100, 1, 1 + X = rng.randn(n_samples, n_dim) + g_full = mixture.GMM(n_components=n_components, covariance_type='full', + random_state=rng, min_covar=1e-7, n_iter=1) + g_full.fit(X) + g_full_bic = g_full.bic(X) + for cv_type in ['tied', 'diag', 'spherical']: + g = mixture.GMM(n_components=n_components, covariance_type=cv_type, + random_state=rng, min_covar=1e-7, n_iter=1) + g.fit(X) + assert_array_almost_equal(g.bic(X), g_full_bic) + + def test_aic(): """ Test the aic and bic criteria""" n_samples, n_dim, n_components = 50, 3, 2 @@ -327,6 +353,57 @@ def test_aic(): assert_true(np.abs(g.bic(X) - bic) / n_samples < bound) +def check_positive_definite_covars(covariance_type): + r"""Test that covariance matrices do not become non positive definite + + Due to the accumulation of round-off errors, the computation of the + covariance matrices during the learning phase could lead to non-positive + definite covariance matrices. Namely the use of the formula: + + .. math:: C = (\sum_i w_i x_i x_i^T) - \mu \mu^T + + instead of: + + .. math:: C = \sum_i w_i (x_i - \mu)(x_i - \mu)^T + + while mathematically equivalent, was observed a ``LinAlgError`` exception, + when computing a ``GMM`` with full covariance matrices and fixed mean. + + This function ensures that some later optimization will not introduce the + problem again. + """ + rng = np.random.RandomState(1) + # we build a dataset with 2 2d component. The components are unbalanced + # (respective weights 0.9 and 0.1) + X = rng.randn(100, 2) + X[-10:] += (3, 3) # Shift the 10 last points + + gmm = mixture.GMM(2, params="wc", covariance_type=covariance_type, + min_covar=1e-3) + + # This is a non-regression test for issue #2640. The following call used + # to trigger: + # numpy.linalg.linalg.LinAlgError: 2-th leading minor not positive definite + gmm.fit(X) + + if covariance_type == "diag" or covariance_type == "spherical": + assert_greater(gmm.covars_.min(), 0) + else: + if covariance_type == "tied": + covs = [gmm.covars_] + else: + covs = gmm.covars_ + + for c in covs: + assert_greater(np.linalg.det(c), 0) + + +def test_positive_definite_covars(): + # Check positive definiteness for all covariance types + for covariance_type in ["full", "tied", "diag", "spherical"]: + yield check_positive_definite_covars, covariance_type + + if __name__ == '__main__': import nose nose.runmodule() diff --git a/sklearn/multiclass.py b/sklearn/multiclass.py index e14c99099c516..2d710af4917f0 100644 --- a/sklearn/multiclass.py +++ b/sklearn/multiclass.py @@ -13,20 +13,48 @@ multiclass classifier. It is also possible to use these estimators with multiclass estimators in the hope that their accuracy or runtime performance improves. + +All classifiers in scikit-learn implement multiclass classification; you +only need to use this module if you want to experiment with custom multiclass +strategies. + +The one-vs-the-rest meta-classifier also implements a `predict_proba` method, +so long as such a method is implemented by the base classifier. This method +returns probabilities of class membership in both the single label and +multilabel case. Note that in the multilabel case, probabilities are the +marginal probability that a given sample falls in the given class. As such, in +the multilabel case the sum of these probabilities over all possible labels +for a given sample *will not* sum to unity, as they do in the single label +case. """ # Author: Mathieu Blondel +# Author: Hamzeh Alsalhi <93hamsal@gmail.com> # -# License: BSD Style. +# License: BSD 3 clause +import array import numpy as np import warnings +import scipy.sparse as sp from .base import BaseEstimator, ClassifierMixin, clone, is_classifier from .base import MetaEstimatorMixin from .preprocessing import LabelBinarizer from .metrics.pairwise import euclidean_distances from .utils import check_random_state +from .utils.validation import _num_samples +from .utils.validation import check_consistent_length +from .utils.validation import check_is_fitted +from .utils import deprecated +from .externals.joblib import Parallel +from .externals.joblib import delayed + +__all__ = [ + "OneVsRestClassifier", + "OneVsOneClassifier", + "OutputCodeClassifier", +] def _fit_binary(estimator, X, y, classes=None): @@ -39,7 +67,7 @@ def _fit_binary(estimator, X, y, classes=None): else: c = y[0] warnings.warn("Label %s is present in all training examples." % - str(classes[c])) + str(classes[c])) estimator = _ConstantPredictor().fit(X, unique_y) else: estimator = clone(estimator) @@ -49,52 +77,128 @@ def _fit_binary(estimator, X, y, classes=None): def _predict_binary(estimator, X): """Make predictions using a single binary estimator.""" - if hasattr(estimator, "decision_function"): - return np.ravel(estimator.decision_function(X)) - else: + try: + score = np.ravel(estimator.decision_function(X)) + except (AttributeError, NotImplementedError): # probabilities of the positive class - return estimator.predict_proba(X)[:, 1] + score = estimator.predict_proba(X)[:, 1] + return score def _check_estimator(estimator): """Make sure that an estimator implements the necessary methods.""" - if not hasattr(estimator, "decision_function") and \ - not hasattr(estimator, "predict_proba"): + if (not hasattr(estimator, "decision_function") and + not hasattr(estimator, "predict_proba")): raise ValueError("The base estimator should implement " "decision_function or predict_proba!") -def fit_ovr(estimator, X, y): - """Fit a one-vs-the-rest strategy.""" - _check_estimator(estimator) +@deprecated("fit_ovr is deprecated and will be removed in 0.18." + "Use the OneVsRestClassifier instead.") +def fit_ovr(estimator, X, y, n_jobs=1): + """Fit a one-vs-the-rest strategy. + + Parameters + ---------- + estimator : estimator object + An estimator object implementing `fit` and one of `decision_function` + or `predict_proba`. + + X : (sparse) array-like, shape = [n_samples, n_features] + Data. + + y : (sparse) array-like, shape = [n_samples] or [n_samples, n_classes] + Multi-class targets. An indicator matrix turns on multilabel + classification. + + Returns + ------- + estimators : list of estimators object + The list of fitted estimator. + + lb : fitted LabelBinarizer - lb = LabelBinarizer() - Y = lb.fit_transform(y) - estimators = [_fit_binary(estimator, X, Y[:, i], - classes=["not %s" % str(i), i]) - for i in range(Y.shape[1])] - return estimators, lb + """ + ovr = OneVsRestClassifier(estimator, n_jobs=n_jobs).fit(X, y) + return ovr.estimators_, ovr.label_binarizer_ +@deprecated("predict_ovr is deprecated and will be removed in 0.18." + "Use the OneVsRestClassifier instead.") def predict_ovr(estimators, label_binarizer, X): - """Make predictions using the one-vs-the-rest strategy.""" - Y = np.array([_predict_binary(e, X) for e in estimators]) - e = estimators[0] - thresh = 0 if hasattr(e, "decision_function") and is_classifier(e) else .5 - return label_binarizer.inverse_transform(Y.T, threshold=thresh) + """Predict multi-class targets using the one vs rest strategy. + + Parameters + ---------- + estimators : list of `n_classes` estimators, Estimators used for + predictions. The list must be homogeneous with respect to the type of + estimators. fit_ovr supplies this list as part of its output. + + label_binarizer : LabelBinarizer object, Object used to transform + multiclass labels to binary labels and vice-versa. fit_ovr supplies + this object as part of its output. + + X : (sparse) array-like, shape = [n_samples, n_features] + Data. + + Returns + ------- + y : (sparse) array-like, shape = [n_samples] or [n_samples, n_classes]. + Predicted multi-class targets. + """ + e_types = set([type(e) for e in estimators if not + isinstance(e, _ConstantPredictor)]) + if len(e_types) > 1: + raise ValueError("List of estimators must contain estimators of the" + " same type but contains types {0}".format(e_types)) + + ovr = OneVsRestClassifier(clone(estimators[0])) + ovr.estimators_ = estimators + ovr.label_binarizer_ = label_binarizer + + return ovr.predict(X) + + +@deprecated("predict_proba_ovr is deprecated and will be removed in 0.18." + "Use the OneVsRestClassifier instead.") +def predict_proba_ovr(estimators, X, is_multilabel): + e_types = set([type(e) for e in estimators if not + isinstance(e, _ConstantPredictor)]) + if len(e_types) > 1: + raise ValueError("List of estimators must contain estimators of the" + " same type but contains types {0}".format(e_types)) + + Y = np.array([e.predict_proba(X)[:, 1] for e in estimators]).T + + if not is_multilabel: + # Then, probabilities should be normalized to 1. + Y /= np.sum(Y, axis=1)[:, np.newaxis] + + return Y class _ConstantPredictor(BaseEstimator): + def fit(self, X, y): self.y_ = y return self def predict(self, X): + check_is_fitted(self, 'y_') + return np.repeat(self.y_, X.shape[0]) def decision_function(self, X): + check_is_fitted(self, 'y_') + return np.repeat(self.y_, X.shape[0]) + def predict_proba(self, X): + check_is_fitted(self, 'y_') + + return np.repeat([np.hstack([1 - self.y_, self.y_])], + X.shape[0], axis=0) + class OneVsRestClassifier(BaseEstimator, ClassifierMixin, MetaEstimatorMixin): """One-vs-the-rest (OvR) multiclass/multilabel strategy @@ -109,10 +213,8 @@ class OneVsRestClassifier(BaseEstimator, ClassifierMixin, MetaEstimatorMixin): multiclass classification and is a fair default choice. This strategy can also be used for multilabel learning, where a classifier - is used to predict multiple labels for instance, by fitting on a sequence - of sequences of labels (e.g., a list of tuples) rather than a single - target vector. For multilabel learning, the number of classes must be at - least three, since otherwise OvR reduces to binary classification. + is used to predict multiple labels for instance, by fitting on a 2-d matrix + in which cell [i, j] is 1 if sample i has label j and 0 otherwise. In the multilabel learning literature, OvR is also known as the binary relevance method. @@ -123,75 +225,168 @@ class OneVsRestClassifier(BaseEstimator, ClassifierMixin, MetaEstimatorMixin): An estimator object implementing `fit` and one of `decision_function` or `predict_proba`. + n_jobs : int, optional, default: 1 + The number of jobs to use for the computation. If -1 all CPUs are used. + If 1 is given, no parallel computing code is used at all, which is + useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are + used. Thus for n_jobs = -2, all CPUs but one are used. + Attributes ---------- - `estimators_` : list of `n_classes` estimators + estimators_ : list of `n_classes` estimators Estimators used for predictions. - `classes_` : array, shape = [`n_classes`] + classes_ : array, shape = [`n_classes`] Class labels. - `label_binarizer_` : LabelBinarizer object + label_binarizer_ : LabelBinarizer object Object used to transform multiclass labels to binary labels and vice-versa. - `multilabel_` : boolean + multilabel_ : boolean Whether a OneVsRestClassifier is a multilabel classifier. """ - def __init__(self, estimator): + def __init__(self, estimator, n_jobs=1): self.estimator = estimator + self.n_jobs = n_jobs def fit(self, X, y): """Fit underlying estimators. Parameters ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] + X : (sparse) array-like, shape = [n_samples, n_features] Data. - y : array-like, shape = [n_samples] - or sequence of sequences, len = n_samples - Multi-class targets. A sequence of sequences turns on multilabel + y : (sparse) array-like, shape = [n_samples] or [n_samples, n_classes] + Multi-class targets. An indicator matrix turns on multilabel classification. Returns ------- self """ - self.estimators_, self.label_binarizer_ = fit_ovr(self.estimator, X, y) - return self + # A sparse LabelBinarizer, with sparse_output=True, has been shown to + # outpreform or match a dense label binarizer in all cases and has also + # resulted in less or equal memory consumption in the fit_ovr function + # overall. + self.label_binarizer_ = LabelBinarizer(sparse_output=True) + Y = self.label_binarizer_.fit_transform(y) + Y = Y.tocsc() + columns = (col.toarray().ravel() for col in Y.T) + # In cases where individual estimators are very fast to train setting + # n_jobs > 1 in can results in slower performance due to the overhead + # of spawning threads. See joblib issue #112. + self.estimators_ = Parallel(n_jobs=self.n_jobs)(delayed(_fit_binary) + (self.estimator, X, column, + classes=["not %s" % self.label_binarizer_.classes_[i], + self.label_binarizer_.classes_[i]]) + for i, column in enumerate(columns)) - def _check_is_fitted(self): - if not hasattr(self, "estimators_"): - raise ValueError("The object hasn't been fitted yet!") + return self def predict(self, X): """Predict multi-class targets using underlying estimators. Parameters ---------- - X: {array-like, sparse matrix}, shape = [n_samples, n_features] + X : (sparse) array-like, shape = [n_samples, n_features] Data. Returns ------- - y : array-like, shape = [n_samples] + y : (sparse) array-like, shape = [n_samples] or [n_samples, n_classes]. Predicted multi-class targets. """ - self._check_is_fitted() + check_is_fitted(self, 'estimators_') + if (hasattr(self.estimators_[0], "decision_function") and + is_classifier(self.estimators_[0])): + thresh = 0 + else: + thresh = .5 + + n_samples = _num_samples(X) + if self.label_binarizer_.y_type_ == "multiclass": + maxima = np.empty(n_samples, dtype=float) + maxima.fill(-np.inf) + argmaxima = np.zeros(n_samples, dtype=int) + for i, e in enumerate(self.estimators_): + pred = _predict_binary(e, X) + np.maximum(maxima, pred, out=maxima) + argmaxima[maxima == pred] = i + return self.label_binarizer_.classes_[np.array(argmaxima.T)] + else: + indices = array.array('i') + indptr = array.array('i', [0]) + for e in self.estimators_: + indices.extend(np.where(_predict_binary(e, X) > thresh)[0]) + indptr.append(len(indices)) + data = np.ones(len(indices), dtype=int) + indicator = sp.csc_matrix((data, indices, indptr), + shape=(n_samples, len(self.estimators_))) + return self.label_binarizer_.inverse_transform(indicator) + + def predict_proba(self, X): + """Probability estimates. + + The returned estimates for all classes are ordered by label of classes. + + Note that in the multilabel case, each sample can have any number of + labels. This returns the marginal probability that the given sample has + the label in question. For example, it is entirely consistent that two + labels both have a 90% probability of applying to a given sample. + + In the single label multiclass case, the rows of the returned matrix + sum to 1. + + Parameters + ---------- + X : array-like, shape = [n_samples, n_features] + + Returns + ------- + T : (sparse) array-like, shape = [n_samples, n_classes] + Returns the probability of the sample for each class in the model, + where classes are ordered as they are in `self.classes_`. + """ + check_is_fitted(self, 'estimators_') + # Y[i,j] gives the probability that sample i has the label j. + # In the multi-label case, these are not disjoint. + Y = np.array([e.predict_proba(X)[:, 1] for e in self.estimators_]).T + + if len(self.estimators_) == 1: + # Only one estimator, but we still want to return probabilities + # for two classes. + Y = np.concatenate(((1 - Y), Y), axis=1) + + if not self.multilabel_: + # Then, probabilities should be normalized to 1. + Y /= np.sum(Y, axis=1)[:, np.newaxis] + return Y + + def decision_function(self, X): + """Returns the distance of each sample from the decision boundary for + each class. This can only be used with estimators which implement the + decision_function method. + + Parameters + ---------- + X : array-like, shape = [n_samples, n_features] - return predict_ovr(self.estimators_, self.label_binarizer_, X) + Returns + ------- + T : array-like, shape = [n_samples, n_classes] + """ + check_is_fitted(self, 'estimators_') + if not hasattr(self.estimators_[0], "decision_function"): + raise AttributeError( + "Base estimator doesn't have a decision_function attribute.") + return np.array([est.decision_function(X).ravel() + for est in self.estimators_]).T @property def multilabel_(self): """Whether this is a multilabel classifier""" - return self.label_binarizer_.multilabel - - def score(self, X, y): - if self.multilabel_: - raise NotImplementedError( - "score is not supported for multilabel classifiers") - else: - return super(OneVsRestClassifier, self).score(X, y) + return self.label_binarizer_.y_type_.startswith('multilabel') @property def classes_(self): @@ -199,7 +394,7 @@ def classes_(self): @property def coef_(self): - self._check_is_fitted() + check_is_fitted(self, 'estimators_') if not hasattr(self.estimators_[0], "coef_"): raise AttributeError( "Base estimator doesn't have a coef_ attribute.") @@ -207,7 +402,7 @@ def coef_(self): @property def intercept_(self): - self._check_is_fitted() + check_is_fitted(self, 'estimators_') if not hasattr(self.estimators_[0], "intercept_"): raise AttributeError( "Base estimator doesn't have an intercept_ attribute.") @@ -218,37 +413,35 @@ def _fit_ovo_binary(estimator, X, y, i, j): """Fit a single binary estimator (one-vs-one).""" cond = np.logical_or(y == i, y == j) y = y[cond] - y[y == i] = 0 - y[y == j] = 1 + y_binary = np.empty(y.shape, np.int) + y_binary[y == i] = 0 + y_binary[y == j] = 1 ind = np.arange(X.shape[0]) - return _fit_binary(estimator, X[ind[cond]], y, classes=[i, j]) - + return _fit_binary(estimator, X[ind[cond]], y_binary, classes=[i, j]) -def fit_ovo(estimator, X, y): - """Fit a one-vs-one strategy.""" - classes = np.unique(y) - n_classes = classes.shape[0] - estimators = [_fit_ovo_binary(estimator, X, y, classes[i], classes[j]) - for i in range(n_classes) for j in range(i + 1, n_classes)] - return estimators, classes +@deprecated("fit_ovo is deprecated and will be removed in 0.18." + "Use the OneVsOneClassifier instead.") +def fit_ovo(estimator, X, y, n_jobs=1): + ovo = OneVsOneClassifier(estimator, n_jobs=n_jobs).fit(X, y) + return ovo.estimators_, ovo.classes_ +@deprecated("predict_ovo is deprecated and will be removed in 0.18." + "Use the OneVsOneClassifier instead.") def predict_ovo(estimators, classes, X): """Make predictions using the one-vs-one strategy.""" - n_samples = X.shape[0] - n_classes = classes.shape[0] - votes = np.zeros((n_samples, n_classes)) - k = 0 - for i in range(n_classes): - for j in range(i + 1, n_classes): - pred = estimators[k].predict(X) - votes[pred == 0, i] += 1 - votes[pred == 1, j] += 1 - k += 1 + e_types = set([type(e) for e in estimators if not + isinstance(e, _ConstantPredictor)]) + if len(e_types) > 1: + raise ValueError("List of estimators must contain estimators of the" + " same type but contains types {0}".format(e_types)) - return classes[votes.argmax(axis=1)] + ovo = OneVsOneClassifier(clone(estimators[0])) + ovo.estimators_ = estimators + ovo.classes_ = classes + return ovo.predict(X) class OneVsOneClassifier(BaseEstimator, ClassifierMixin, MetaEstimatorMixin): @@ -267,44 +460,65 @@ class OneVsOneClassifier(BaseEstimator, ClassifierMixin, MetaEstimatorMixin): Parameters ---------- estimator : estimator object - An estimator object implementing `fit` and `predict`. + An estimator object implementing `fit` and one of `decision_function` + or `predict_proba`. + + n_jobs : int, optional, default: 1 + The number of jobs to use for the computation. If -1 all CPUs are used. + If 1 is given, no parallel computing code is used at all, which is + useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are + used. Thus for n_jobs = -2, all CPUs but one are used. Attributes ---------- - `estimators_` : list of `n_classes * (n_classes - 1) / 2` estimators + estimators_ : list of `n_classes * (n_classes - 1) / 2` estimators Estimators used for predictions. - `classes_` : numpy array of shape [n_classes] + classes_ : numpy array of shape [n_classes] Array containing labels. """ - def __init__(self, estimator): + def __init__(self, estimator, n_jobs=1): self.estimator = estimator + self.n_jobs = n_jobs def fit(self, X, y): """Fit underlying estimators. Parameters ---------- - X: {array-like, sparse matrix}, shape = [n_samples, n_features] + X : (sparse) array-like, shape = [n_samples, n_features] Data. - y : numpy array of shape [n_samples] + y : array-like, shape = [n_samples] Multi-class targets. Returns ------- self """ - self.estimators_, self.classes_ = fit_ovo(self.estimator, X, y) + y = np.asarray(y) + check_consistent_length(X, y) + + self.classes_ = np.unique(y) + n_classes = self.classes_.shape[0] + self.estimators_ = Parallel(n_jobs=self.n_jobs)( + delayed(_fit_ovo_binary)( + self.estimator, X, y, self.classes_[i], self.classes_[j]) + for i in range(n_classes) for j in range(i + 1, n_classes)) + return self def predict(self, X): - """Predict multi-class targets using underlying estimators. + """Estimate the best class label for each sample in X. + + This is implemented as ``argmax(decision_function(X), axis=1)`` which + will return the label of the class with most votes by estimators + predicting the outcome of a decision for each possible class pair. Parameters ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] + X : (sparse) array-like, shape = [n_samples, n_features] Data. Returns @@ -312,15 +526,58 @@ def predict(self, X): y : numpy array of shape [n_samples] Predicted multi-class targets. """ - if not hasattr(self, "estimators_"): - raise ValueError("The object hasn't been fitted yet!") + Y = self.decision_function(X) + return self.classes_[Y.argmax(axis=1)] - return predict_ovo(self.estimators_, self.classes_, X) + def decision_function(self, X): + """Decision function for the OneVsOneClassifier. + The decision values for the samples are computed by adding the + normalized sum of pair-wise classification confidence levels to the + votes in order to disambiguate between the decision values when the + votes for all the classes are equal leading to a tie. -def fit_ecoc(estimator, X, y, code_size=1.5, random_state=None): - """ - Fit an error-correcting output-code strategy. + Parameters + ---------- + X : array-like, shape = [n_samples, n_features] + + Returns + ------- + Y : array-like, shape = [n_samples, n_classes] + """ + check_is_fitted(self, 'estimators_') + + n_samples = X.shape[0] + n_classes = self.classes_.shape[0] + votes = np.zeros((n_samples, n_classes)) + sum_of_confidences = np.zeros((n_samples, n_classes)) + + k = 0 + for i in range(n_classes): + for j in range(i + 1, n_classes): + pred = self.estimators_[k].predict(X) + confidence_levels_ij = _predict_binary(self.estimators_[k], X) + sum_of_confidences[:, i] -= confidence_levels_ij + sum_of_confidences[:, j] += confidence_levels_ij + votes[pred == 0, i] += 1 + votes[pred == 1, j] += 1 + k += 1 + + max_confidences = sum_of_confidences.max() + min_confidences = sum_of_confidences.min() + + if max_confidences == min_confidences: + return votes + + # Scale the sum_of_confidences to [-0.4, 0.4] and add it with votes + return votes + sum_of_confidences * \ + (0.4 / max(abs(max_confidences), abs(min_confidences))) + + +@deprecated("fit_ecoc is deprecated and will be removed in 0.18." + "Use the OutputCodeClassifier instead.") +def fit_ecoc(estimator, X, y, code_size=1.5, random_state=None, n_jobs=1): + """Fit an error-correcting output-code strategy. Parameters ---------- @@ -328,10 +585,10 @@ def fit_ecoc(estimator, X, y, code_size=1.5, random_state=None): An estimator object implementing `fit` and one of `decision_function` or `predict_proba`. - code_size: float, optional + code_size : float, optional Percentage of the number of classes to be used to create the code book. - random_state: numpy.RandomState, optional + random_state : numpy.RandomState, optional The generator used to initialize the codebook. Defaults to numpy.random. @@ -344,42 +601,24 @@ def fit_ecoc(estimator, X, y, code_size=1.5, random_state=None): classes : numpy array of shape [n_classes] Array containing labels. - `code_book_`: numpy array of shape [n_classes, code_size] + code_book_ : numpy array of shape [n_classes, code_size] Binary array containing the code of each class. """ - _check_estimator(estimator) - random_state = check_random_state(random_state) - - classes = np.unique(y) - n_classes = classes.shape[0] - code_size = int(n_classes * code_size) - - # FIXME: there are more elaborate methods than generating the codebook - # randomly. - code_book = random_state.random_sample((n_classes, code_size)) - code_book[code_book > 0.5] = 1 - - if hasattr(estimator, "decision_function"): - code_book[code_book != 1] = -1 - else: - code_book[code_book != 1] = 0 - - cls_idx = dict((c, i) for i, c in enumerate(classes)) - - Y = np.array([code_book[cls_idx[y[i]]] for i in xrange(X.shape[0])], - dtype=np.int) - - estimators = [_fit_binary(estimator, X, Y[:, i]) - for i in range(Y.shape[1])] - - return estimators, classes, code_book + ecoc = OutputCodeClassifier(estimator, random_state=random_state, + n_jobs=n_jobs).fit(X, y) + return ecoc.estimators_, ecoc.classes_, ecoc.code_book_ +@deprecated("predict_ecoc is deprecated and will be removed in 0.18." + "Use the OutputCodeClassifier instead.") def predict_ecoc(estimators, classes, code_book, X): """Make predictions using the error-correcting output-code strategy.""" - Y = np.array([_predict_binary(e, X) for e in estimators]).T - pred = euclidean_distances(Y, code_book).argmin(axis=1) - return classes[pred] + ecoc = OutputCodeClassifier(clone(estimators[0])) + ecoc.classes_ = classes + ecoc.estimators_ = estimators + ecoc.code_book_ = code_book + + return ecoc.predict(X) class OutputCodeClassifier(BaseEstimator, ClassifierMixin, MetaEstimatorMixin): @@ -410,15 +649,21 @@ class OutputCodeClassifier(BaseEstimator, ClassifierMixin, MetaEstimatorMixin): The generator used to initialize the codebook. Defaults to numpy.random. + n_jobs : int, optional, default: 1 + The number of jobs to use for the computation. If -1 all CPUs are used. + If 1 is given, no parallel computing code is used at all, which is + useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are + used. Thus for n_jobs = -2, all CPUs but one are used. + Attributes ---------- - `estimators_` : list of `int(n_classes * code_size)` estimators + estimators_ : list of `int(n_classes * code_size)` estimators Estimators used for predictions. - `classes_` : numpy array of shape [n_classes] + classes_ : numpy array of shape [n_classes] Array containing labels. - `code_book_` : numpy array of shape [n_classes, code_size] + code_book_ : numpy array of shape [n_classes, code_size] Binary array containing the code of each class. References @@ -440,20 +685,18 @@ class OutputCodeClassifier(BaseEstimator, ClassifierMixin, MetaEstimatorMixin): 2008. """ - def __init__(self, estimator, code_size=1.5, random_state=None): - if (code_size <= 0): - raise ValueError("code_size should be greater than 0!") - + def __init__(self, estimator, code_size=1.5, random_state=None, n_jobs=1): self.estimator = estimator self.code_size = code_size self.random_state = random_state + self.n_jobs = n_jobs def fit(self, X, y): """Fit underlying estimators. Parameters ---------- - X: {array-like, sparse matrix}, shape = [n_samples, n_features] + X : (sparse) array-like, shape = [n_samples, n_features] Data. y : numpy array of shape [n_samples] @@ -463,8 +706,36 @@ def fit(self, X, y): ------- self """ - self.estimators_, self.classes_, self.code_book_ = \ - fit_ecoc(self.estimator, X, y, self.code_size, self.random_state) + if self.code_size <= 0: + raise ValueError("code_size should be greater than 0, got {1}" + "".format(self.code_size)) + + _check_estimator(self.estimator) + random_state = check_random_state(self.random_state) + + self.classes_ = np.unique(y) + n_classes = self.classes_.shape[0] + code_size_ = int(n_classes * self.code_size) + + # FIXME: there are more elaborate methods than generating the codebook + # randomly. + self.code_book_ = random_state.random_sample((n_classes, code_size_)) + self.code_book_[self.code_book_ > 0.5] = 1 + + if hasattr(self.estimator, "decision_function"): + self.code_book_[self.code_book_ != 1] = -1 + else: + self.code_book_[self.code_book_ != 1] = 0 + + classes_index = dict((c, i) for i, c in enumerate(self.classes_)) + + Y = np.array([self.code_book_[classes_index[y[i]]] + for i in range(X.shape[0])], dtype=np.int) + + self.estimators_ = Parallel(n_jobs=self.n_jobs)( + delayed(_fit_binary)(self.estimator, X, Y[:, i]) + for i in range(Y.shape[1])) + return self def predict(self, X): @@ -472,7 +743,7 @@ def predict(self, X): Parameters ---------- - X: {array-like, sparse matrix}, shape = [n_samples, n_features] + X : (sparse) array-like, shape = [n_samples, n_features] Data. Returns @@ -480,8 +751,7 @@ def predict(self, X): y : numpy array of shape [n_samples] Predicted multi-class targets. """ - if not hasattr(self, "estimators_"): - raise ValueError("The object hasn't been fitted yet!") - - return predict_ecoc(self.estimators_, self.classes_, - self.code_book_, X) + check_is_fitted(self, 'estimators_') + Y = np.array([_predict_binary(e, X) for e in self.estimators_]).T + pred = euclidean_distances(Y, self.code_book_).argmin(axis=1) + return self.classes_[pred] diff --git a/sklearn/naive_bayes.py b/sklearn/naive_bayes.py index 6f168595465a0..1ecf4ad5bcc5f 100644 --- a/sklearn/naive_bayes.py +++ b/sklearn/naive_bayes.py @@ -11,9 +11,10 @@ # Amit Aides # Yehuda Finkelstein # Lars Buitinck +# Jan Hendrik Metzen # (parts based on earlier work by Mathieu Blondel) # -# License: BSD Style. +# License: BSD 3 clause from abc import ABCMeta, abstractmethod @@ -21,19 +22,22 @@ from scipy.sparse import issparse from .base import BaseEstimator, ClassifierMixin -from .preprocessing import binarize, LabelBinarizer -from .utils import array2d, atleast2d_or_csr +from .preprocessing import binarize +from .preprocessing import LabelBinarizer +from .preprocessing import label_binarize +from .utils import check_X_y, check_array from .utils.extmath import safe_sparse_dot, logsumexp -from .utils import check_arrays +from .utils.multiclass import _check_partial_fit_first_call +from .utils.fixes import in1d +from .utils.validation import check_is_fitted +from .externals import six __all__ = ['BernoulliNB', 'GaussianNB', 'MultinomialNB'] -class BaseNB(BaseEstimator, ClassifierMixin): +class BaseNB(six.with_metaclass(ABCMeta, BaseEstimator, ClassifierMixin)): """Abstract base class for naive Bayes estimators""" - __metaclass__ = ABCMeta - @abstractmethod def _joint_log_likelihood(self, X): """Compute the unnormalized posterior log probability of X @@ -72,8 +76,9 @@ def predict_log_proba(self, X): Returns ------- C : array-like, shape = [n_samples, n_classes] - Returns the log-probability of the sample for each class - in the model, where classes are ordered arithmetically. + Returns the log-probability of the samples for each class in + the model. The columns correspond to the classes in sorted + order, as they appear in the attribute `classes_`. """ jll = self._joint_log_likelihood(X) # normalize by P(x) = P(f_1, ..., f_n) @@ -91,8 +96,9 @@ def predict_proba(self, X): Returns ------- C : array-like, shape = [n_samples, n_classes] - Returns the probability of the sample for each class in - the model, where classes are ordered arithmetically. + Returns the probability of the samples for each class in + the model. The columns correspond to the classes in sorted + order, as they appear in the attribute `classes_`. """ return np.exp(self.predict_log_proba(X)) @@ -101,24 +107,24 @@ class GaussianNB(BaseNB): """ Gaussian Naive Bayes (GaussianNB) - Parameters - ---------- - X : array-like, shape = [n_samples, n_features] - Training vector, where n_samples in the number of samples and - n_features is the number of features. + Can perform online updates to model parameters via `partial_fit` method. + For details on algorithm used to update feature means and variance online, + see Stanford CS tech report STAN-CS-79-773 by Chan, Golub, and LeVeque: - y : array, shape = [n_samples] - Target vector relative to X + http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf Attributes ---------- - `class_prior_` : array, shape = [n_classes] + class_prior_ : array, shape (n_classes,) probability of each class. - `theta_` : array, shape = [n_classes, n_features] + class_count_ : array, shape (n_classes,) + number of training samples observed in each class. + + theta_ : array, shape (n_classes, n_features) mean of each feature per class - `sigma_` : array, shape = [n_classes, n_features] + sigma_ : array, shape (n_classes, n_features) variance of each feature per class Examples @@ -132,53 +138,249 @@ class GaussianNB(BaseNB): GaussianNB() >>> print(clf.predict([[-0.8, -1]])) [1] + >>> clf_pf = GaussianNB() + >>> clf_pf.partial_fit(X, Y, np.unique(Y)) + GaussianNB() + >>> print(clf_pf.predict([[-0.8, -1]])) + [1] """ - def fit(self, X, y): + def fit(self, X, y, sample_weight=None): """Fit Gaussian Naive Bayes according to X, y Parameters ---------- - X : array-like, shape = [n_samples, n_features] + X : array-like, shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. - y : array-like, shape = [n_samples] + y : array-like, shape (n_samples,) + Target values. + + sample_weight : array-like, shape (n_samples,), optional + Weights applied to individual samples (1. for unweighted). + + Returns + ------- + self : object + Returns self. + """ + X, y = check_X_y(X, y) + return self._partial_fit(X, y, np.unique(y), _refit=True, + sample_weight=sample_weight) + + @staticmethod + def _update_mean_variance(n_past, mu, var, X, sample_weight=None): + """Compute online update of Gaussian mean and variance. + + Given starting sample count, mean, and variance, a new set of + points X, and optionally sample weights, return the updated mean and + variance. (NB - each dimension (column) in X is treated as independent + -- you get variance, not covariance). + + Can take scalar mean and variance, or vector mean and variance to + simultaneously update a number of independent Gaussians. + + See Stanford CS tech report STAN-CS-79-773 by Chan, Golub, and LeVeque: + + http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf + + Parameters + ---------- + n_past : int + Number of samples represented in old mean and variance. If sample + weights were given, this should contain the sum of sample + weights represented in old mean and variance. + + mu : array-like, shape (number of Gaussians,) + Means for Gaussians in original set. + + var : array-like, shape (number of Gaussians,) + Variances for Gaussians in original set. + + sample_weight : array-like, shape (n_samples,), optional + Weights applied to individual samples (1. for unweighted). + + Returns + ------- + total_mu : array-like, shape (number of Gaussians,) + Updated mean for each Gaussian over the combined set. + + total_var : array-like, shape (number of Gaussians,) + Updated variance for each Gaussian over the combined set. + """ + if X.shape[0] == 0: + return mu, var + + # Compute (potentially weighted) mean and variance of new datapoints + if sample_weight is not None: + n_new = float(sample_weight.sum()) + new_mu = np.average(X, axis=0, weights=sample_weight / n_new) + new_var = np.average((X - new_mu) ** 2, axis=0, + weights=sample_weight / n_new) + else: + n_new = X.shape[0] + new_var = np.var(X, axis=0) + new_mu = np.mean(X, axis=0) + + if n_past == 0: + return new_mu, new_var + + n_total = float(n_past + n_new) + + # Combine mean of old and new data, taking into consideration + # (weighted) number of observations + total_mu = (n_new * new_mu + n_past * mu) / n_total + + # Combine variance of old and new data, taking into consideration + # (weighted) number of observations. This is achieved by combining + # the sum-of-squared-differences (ssd) + old_ssd = n_past * var + new_ssd = n_new * new_var + total_ssd = (old_ssd + new_ssd + + (n_past / float(n_new * n_total)) * + (n_new * mu - n_new * new_mu) ** 2) + total_var = total_ssd / n_total + + return total_mu, total_var + + def partial_fit(self, X, y, classes=None, sample_weight=None): + """Incremental fit on a batch of samples. + + This method is expected to be called several times consecutively + on different chunks of a dataset so as to implement out-of-core + or online learning. + + This is especially useful when the whole dataset is too big to fit in + memory at once. + + This method has some performance and numerical stability overhead, + hence it is better to call partial_fit on chunks of data that are + as large as possible (as long as fitting in the memory budget) to + hide the overhead. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training vectors, where n_samples is the number of samples and + n_features is the number of features. + + y : array-like, shape (n_samples,) Target values. + classes : array-like, shape (n_classes,) + List of all the classes that can possibly appear in the y vector. + + Must be provided at the first call to partial_fit, can be omitted + in subsequent calls. + + sample_weight : array-like, shape (n_samples,), optional + Weights applied to individual samples (1. for unweighted). + Returns ------- self : object Returns self. """ + return self._partial_fit(X, y, classes, _refit=False, + sample_weight=sample_weight) - X, y = check_arrays(X, y, sparse_format='dense') + def _partial_fit(self, X, y, classes=None, _refit=False, + sample_weight=None): + """Actual implementation of Gaussian NB fitting. - n_samples, n_features = X.shape + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training vectors, where n_samples is the number of samples and + n_features is the number of features. + + y : array-like, shape (n_samples,) + Target values. + + classes : array-like, shape (n_classes,) + List of all the classes that can possibly appear in the y vector. - if n_samples != y.shape[0]: - raise ValueError("X and y have incompatible shapes") + Must be provided at the first call to partial_fit, can be omitted + in subsequent calls. - self.classes_ = unique_y = np.unique(y) - n_classes = unique_y.shape[0] + _refit: bool + If true, act as though this were the first time we called + _partial_fit (ie, throw away any past fitting and start over). - self.theta_ = np.zeros((n_classes, n_features)) - self.sigma_ = np.zeros((n_classes, n_features)) - self.class_prior_ = np.zeros(n_classes) + sample_weight : array-like, shape (n_samples,), optional + Weights applied to individual samples (1. for unweighted). + + Returns + ------- + self : object + Returns self. + """ + + X, y = check_X_y(X, y) epsilon = 1e-9 - for i, y_i in enumerate(unique_y): - self.theta_[i, :] = np.mean(X[y == y_i, :], axis=0) - self.sigma_[i, :] = np.var(X[y == y_i, :], axis=0) + epsilon - self.class_prior_[i] = np.float(np.sum(y == y_i)) / n_samples + + if _refit: + self.classes_ = None + + if _check_partial_fit_first_call(self, classes): + # This is the first call to partial_fit: + # initialize various cumulative counters + n_features = X.shape[1] + n_classes = len(self.classes_) + self.theta_ = np.zeros((n_classes, n_features)) + self.sigma_ = np.zeros((n_classes, n_features)) + self.class_prior_ = np.zeros(n_classes) + self.class_count_ = np.zeros(n_classes) + else: + if X.shape[1] != self.theta_.shape[1]: + msg = "Number of features %d does not match previous data %d." + raise ValueError(msg % (X.shape[1], self.theta_.shape[1])) + # Put epsilon back in each time + self.sigma_[:, :] -= epsilon + + classes = self.classes_ + + unique_y = np.unique(y) + unique_y_in_classes = in1d(unique_y, classes) + + if not np.all(unique_y_in_classes): + raise ValueError("The target label(s) %s in y do not exist in the " + "initial classes %s" % + (y[~unique_y_in_classes], classes)) + + for y_i in unique_y: + i = classes.searchsorted(y_i) + X_i = X[y == y_i, :] + + if sample_weight is not None: + sw_i = sample_weight[y == y_i] + N_i = sw_i.sum() + else: + sw_i = None + N_i = X_i.shape[0] + + new_theta, new_sigma = self._update_mean_variance( + self.class_count_[i], self.theta_[i, :], self.sigma_[i, :], + X_i, sw_i) + + self.theta_[i, :] = new_theta + self.sigma_[i, :] = new_sigma + self.class_count_[i] += N_i + + self.sigma_[:, :] += epsilon + self.class_prior_[:] = self.class_count_ / np.sum(self.class_count_) return self def _joint_log_likelihood(self, X): - X = array2d(X) + check_is_fitted(self, "classes_") + + X = check_array(X) joint_log_likelihood = [] - for i in xrange(np.size(self.classes_)): + for i in range(np.size(self.classes_)): jointi = np.log(self.class_prior_[i]) - n_ij = - 0.5 * np.sum(np.log(np.pi * self.sigma_[i, :])) - n_ij -= 0.5 * np.sum(((X - self.theta_[i, :]) ** 2) / \ + n_ij = - 0.5 * np.sum(np.log(2. * np.pi * self.sigma_[i, :])) + n_ij -= 0.5 * np.sum(((X - self.theta_[i, :]) ** 2) / (self.sigma_[i, :]), 1) joint_log_likelihood.append(jointi + n_ij) @@ -195,8 +397,33 @@ class BaseDiscreteNB(BaseNB): _joint_log_likelihood(X) as per BaseNB """ - def fit(self, X, y, sample_weight=None, class_prior=None): - """Fit Naive Bayes classifier according to X, y + def _update_class_log_prior(self, class_prior=None): + n_classes = len(self.classes_) + if class_prior is not None: + if len(class_prior) != n_classes: + raise ValueError("Number of priors must match number of" + " classes.") + self.class_log_prior_ = np.log(class_prior) + elif self.fit_prior: + # empirical prior, with sample_weight taken into account + self.class_log_prior_ = (np.log(self.class_count_) + - np.log(self.class_count_.sum())) + else: + self.class_log_prior_ = np.zeros(n_classes) - np.log(n_classes) + + def partial_fit(self, X, y, classes=None, sample_weight=None): + """Incremental fit on a batch of samples. + + This method is expected to be called several times consecutively + on different chunks of a dataset so as to implement out-of-core + or online learning. + + This is especially useful when the whole dataset is too big to fit in + memory at once. + + This method has some performance overhead hence it is better to call + partial_fit on chunks of data that are as large as possible + (as long as fitting in the memory budget) to hide the overhead. Parameters ---------- @@ -207,81 +434,120 @@ def fit(self, X, y, sample_weight=None, class_prior=None): y : array-like, shape = [n_samples] Target values. + classes : array-like, shape = [n_classes] + List of all the classes that can possibly appear in the y vector. + + Must be provided at the first call to partial_fit, can be omitted + in subsequent calls. + sample_weight : array-like, shape = [n_samples], optional Weights applied to individual samples (1. for unweighted). - class_prior : array, shape [n_classes] - Custom prior probability per class. - Overrides the fit_prior parameter. - Returns ------- self : object Returns self. """ - X = atleast2d_or_csr(X) - - labelbin = LabelBinarizer() - Y = labelbin.fit_transform(y) - self.classes_ = labelbin.classes_ - n_classes = len(self.classes_) + X = check_array(X, accept_sparse='csr', dtype=np.float64) + _, n_features = X.shape + + if _check_partial_fit_first_call(self, classes): + # This is the first call to partial_fit: + # initialize various cumulative counters + n_effective_classes = len(classes) if len(classes) > 1 else 2 + self.class_count_ = np.zeros(n_effective_classes, dtype=np.float64) + self.feature_count_ = np.zeros((n_effective_classes, n_features), + dtype=np.float64) + elif n_features != self.coef_.shape[1]: + msg = "Number of features %d does not match previous data %d." + raise ValueError(msg % (n_features, self.coef_.shape[-1])) + + Y = label_binarize(y, classes=self.classes_) if Y.shape[1] == 1: Y = np.concatenate((1 - Y, Y), axis=1) + n_samples, n_classes = Y.shape + if X.shape[0] != Y.shape[0]: - msg = "X and y have incompatible shapes." - if issparse(X): - msg += "\nNote: Sparse matrices cannot be indexed w/ boolean \ - masks (use `indices=True` in CV)." - raise ValueError(msg) + msg = "X.shape[0]=%d and y.shape[0]=%d are incompatible." + raise ValueError(msg % (X.shape[0], y.shape[0])) + # convert to float to support sample weight consistently + Y = Y.astype(np.float64) if sample_weight is not None: - Y *= array2d(sample_weight).T - - if class_prior: - if len(class_prior) != n_classes: - raise ValueError( - "Number of priors must match number of classes") - self.class_log_prior_ = np.log(class_prior) - elif self.fit_prior: - # empirical prior, with sample_weight taken into account - y_freq = Y.sum(axis=0) - self.class_log_prior_ = np.log(y_freq) - np.log(y_freq.sum()) - else: - self.class_log_prior_ = np.zeros(n_classes) - np.log(n_classes) + Y *= check_array(sample_weight).T - N_c, N_c_i = self._count(X, Y) + class_prior = self.class_prior - self.feature_log_prob_ = (np.log(N_c_i + self.alpha) - - np.log(N_c.reshape(-1, 1) - + self.alpha * X.shape[1])) + # Count raw events from data before updating the class log prior + # and feature log probas + self._count(X, Y) + # XXX: OPTIM: we could introduce a public finalization method to + # be called by the user explicitly just once after several consecutive + # calls to partial_fit and prior any call to predict[_[log_]proba] + # to avoid computing the smooth log probas at each call to partial fit + self._update_feature_log_prob() + self._update_class_log_prior(class_prior=class_prior) return self - @staticmethod - def _count(X, Y): - """Count feature occurrences. + def fit(self, X, y, sample_weight=None): + """Fit Naive Bayes classifier according to X, y + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Training vectors, where n_samples is the number of samples and + n_features is the number of features. + + y : array-like, shape = [n_samples] + Target values. - Returns (N_c, N_c_i), where - N_c is the count of all features in all samples of class c; - N_c_i is the count of feature i in all samples of class c. + sample_weight : array-like, shape = [n_samples], optional + Weights applied to individual samples (1. for unweighted). + + Returns + ------- + self : object + Returns self. """ - if np.any((X.data if issparse(X) else X) < 0): - raise ValueError("Input X must be non-negative.") - N_c_i = safe_sparse_dot(Y.T, X) - N_c = np.sum(N_c_i, axis=1) + X, y = check_X_y(X, y, 'csr') + _, n_features = X.shape - return N_c, N_c_i + labelbin = LabelBinarizer() + Y = labelbin.fit_transform(y) + self.classes_ = labelbin.classes_ + if Y.shape[1] == 1: + Y = np.concatenate((1 - Y, Y), axis=1) + + # convert to float to support sample weight consistently; + # this means we also don't have to cast X to floating point + Y = Y.astype(np.float64) + if sample_weight is not None: + Y *= check_array(sample_weight).T + + class_prior = self.class_prior + + # Count raw events from data before updating the class log prior + # and feature log probas + n_effective_classes = Y.shape[1] + self.class_count_ = np.zeros(n_effective_classes, dtype=np.float64) + self.feature_count_ = np.zeros((n_effective_classes, n_features), + dtype=np.float64) + self._count(X, Y) + self._update_feature_log_prob() + self._update_class_log_prior(class_prior=class_prior) + return self # XXX The following is a stopgap measure; we need to set the dimensions # of class_log_prior_ and feature_log_prob_ correctly. def _get_coef(self): - return self.feature_log_prob_[1] if len(self.classes_) == 2 \ - else self.feature_log_prob_ + return (self.feature_log_prob_[1:] + if len(self.classes_) == 2 else self.feature_log_prob_) def _get_intercept(self): - return self.class_log_prior_[1] if len(self.classes_) == 2 \ - else self.class_log_prior_ + return (self.class_log_prior_[1:] + if len(self.classes_) == 2 else self.class_log_prior_) coef_ = property(_get_coef) intercept_ = property(_get_intercept) @@ -298,35 +564,53 @@ class MultinomialNB(BaseDiscreteNB): Parameters ---------- - alpha: float, optional (default=1.0) + alpha : float, optional (default=1.0) Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing). - fit_prior: boolean + + fit_prior : boolean Whether to learn class prior probabilities or not. If false, a uniform prior will be used. + class_prior : array-like, size (n_classes,) + Prior probabilities of the classes. If specified the priors are not + adjusted according to the data. + Attributes ---------- - `intercept_`, `class_log_prior_` : array, shape = [n_classes] + class_log_prior_ : array, shape (n_classes, ) Smoothed empirical log probability for each class. - `feature_log_prob_`, `coef_` : array, shape = [n_classes, n_features] + intercept_ : property + Mirrors ``class_log_prior_`` for interpreting MultinomialNB + as a linear model. + + feature_log_prob_ : array, shape (n_classes, n_features) Empirical log probability of features - given a class, P(x_i|y). + given a class, ``P(x_i|y)``. - (`intercept_` and `coef_` are properties - referring to `class_log_prior_` and - `feature_log_prob_`, respectively.) + coef_ : property + Mirrors ``feature_log_prob_`` for interpreting MultinomialNB + as a linear model. + + class_count_ : array, shape (n_classes,) + Number of samples encountered for each class during fitting. This + value is weighted by the sample weight when provided. + + feature_count_ : array, shape (n_classes, n_features) + Number of samples encountered for each (class, feature) + during fitting. This value is weighted by the sample weight when + provided. Examples -------- >>> import numpy as np >>> X = np.random.randint(5, size=(6, 100)) - >>> Y = np.array([1, 2, 3, 4, 5, 6]) + >>> y = np.array([1, 2, 3, 4, 5, 6]) >>> from sklearn.naive_bayes import MultinomialNB >>> clf = MultinomialNB() - >>> clf.fit(X, Y) - MultinomialNB(alpha=1.0, fit_prior=True) + >>> clf.fit(X, y) + MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True) >>> print(clf.predict(X[2])) [3] @@ -335,17 +619,41 @@ class MultinomialNB(BaseDiscreteNB): For the rationale behind the names `coef_` and `intercept_`, i.e. naive Bayes as a linear classifier, see J. Rennie et al. (2003), Tackling the poor assumptions of naive Bayes text classifiers, ICML. + + References + ---------- + C.D. Manning, P. Raghavan and H. Schuetze (2008). Introduction to + Information Retrieval. Cambridge University Press, pp. 234-265. + http://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html """ - def __init__(self, alpha=1.0, fit_prior=True): + def __init__(self, alpha=1.0, fit_prior=True, class_prior=None): self.alpha = alpha self.fit_prior = fit_prior + self.class_prior = class_prior + + def _count(self, X, Y): + """Count and smooth feature occurrences.""" + if np.any((X.data if issparse(X) else X) < 0): + raise ValueError("Input X must be non-negative") + self.feature_count_ += safe_sparse_dot(Y.T, X) + self.class_count_ += Y.sum(axis=0) + + def _update_feature_log_prob(self): + """Apply smoothing to raw counts and recompute log probabilities""" + smoothed_fc = self.feature_count_ + self.alpha + smoothed_cc = smoothed_fc.sum(axis=1) + + self.feature_log_prob_ = (np.log(smoothed_fc) + - np.log(smoothed_cc.reshape(-1, 1))) def _joint_log_likelihood(self, X): """Calculate the posterior log probability of the samples X""" - X = atleast2d_or_csr(X) + check_is_fitted(self, "classes_") + + X = check_array(X, accept_sparse='csr') return (safe_sparse_dot(X, self.feature_log_prob_.T) - + self.class_log_prior_) + + self.class_log_prior_) class BernoulliNB(BaseDiscreteNB): @@ -357,24 +665,39 @@ class BernoulliNB(BaseDiscreteNB): Parameters ---------- - alpha: float, optional (default=1.0) + alpha : float, optional (default=1.0) Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing). - binarize: float or None, optional + + binarize : float or None, optional Threshold for binarizing (mapping to booleans) of sample features. If None, input is presumed to already consist of binary vectors. - fit_prior: boolean + + fit_prior : boolean Whether to learn class prior probabilities or not. If false, a uniform prior will be used. + class_prior : array-like, size=[n_classes,] + Prior probabilities of the classes. If specified the priors are not + adjusted according to the data. + Attributes ---------- - `class_log_prior_` : array, shape = [n_classes] + class_log_prior_ : array, shape = [n_classes] Log probability of each class (smoothed). - `feature_log_prob_` : array, shape = [n_classes, n_features] + feature_log_prob_ : array, shape = [n_classes, n_features] Empirical log probability of features given a class, P(x_i|y). + class_count_ : array, shape = [n_classes] + Number of samples encountered for each class during fitting. This + value is weighted by the sample weight when provided. + + feature_count_ : array, shape = [n_classes, n_features] + Number of samples encountered for each (class, feature) + during fitting. This value is weighted by the sample weight when + provided. + Examples -------- >>> import numpy as np @@ -383,38 +706,52 @@ class BernoulliNB(BaseDiscreteNB): >>> from sklearn.naive_bayes import BernoulliNB >>> clf = BernoulliNB() >>> clf.fit(X, Y) - BernoulliNB(alpha=1.0, binarize=0.0, fit_prior=True) + BernoulliNB(alpha=1.0, binarize=0.0, class_prior=None, fit_prior=True) >>> print(clf.predict(X[2])) [3] References ---------- - C.D. Manning, P. Raghavan and H. Schütze (2008). Introduction to - Information Retrieval. Cambridge University Press, pp. 234–265. + C.D. Manning, P. Raghavan and H. Schuetze (2008). Introduction to + Information Retrieval. Cambridge University Press, pp. 234-265. + http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html A. McCallum and K. Nigam (1998). A comparison of event models for naive Bayes text classification. Proc. AAAI/ICML-98 Workshop on Learning for - Text Categorization, pp. 41–48. + Text Categorization, pp. 41-48. V. Metsis, I. Androutsopoulos and G. Paliouras (2006). Spam filtering with naive Bayes -- Which naive Bayes? 3rd Conf. on Email and Anti-Spam (CEAS). """ - def __init__(self, alpha=1.0, binarize=.0, fit_prior=True): + def __init__(self, alpha=1.0, binarize=.0, fit_prior=True, + class_prior=None): self.alpha = alpha self.binarize = binarize self.fit_prior = fit_prior + self.class_prior = class_prior def _count(self, X, Y): + """Count and smooth feature occurrences.""" if self.binarize is not None: X = binarize(X, threshold=self.binarize) - return super(BernoulliNB, self)._count(X, Y) + self.feature_count_ += safe_sparse_dot(Y.T, X) + self.class_count_ += Y.sum(axis=0) + + def _update_feature_log_prob(self): + """Apply smoothing to raw counts and recompute log probabilities""" + smoothed_fc = self.feature_count_ + self.alpha + smoothed_cc = self.class_count_ + self.alpha * 2 + + self.feature_log_prob_ = (np.log(smoothed_fc) + - np.log(smoothed_cc.reshape(-1, 1))) def _joint_log_likelihood(self, X): """Calculate the posterior log probability of the samples X""" + check_is_fitted(self, "classes_") - X = atleast2d_or_csr(X) + X = check_array(X, accept_sparse='csr') if self.binarize is not None: X = binarize(X, threshold=self.binarize) @@ -428,8 +765,7 @@ def _joint_log_likelihood(self, X): neg_prob = np.log(1 - np.exp(self.feature_log_prob_)) # Compute neg_prob · (1 - X).T as ∑neg_prob - X · neg_prob - X_neg_prob = (neg_prob.sum(axis=1) - - safe_sparse_dot(X, neg_prob.T)) - jll = safe_sparse_dot(X, self.feature_log_prob_.T) + X_neg_prob + jll = safe_sparse_dot(X, (self.feature_log_prob_ - neg_prob).T) + jll += self.class_log_prior_ + neg_prob.sum(axis=1) - return jll + self.class_log_prior_ + return jll diff --git a/sklearn/neighbors/__init__.py b/sklearn/neighbors/__init__.py index 1c88f3250d14e..14f62a4b6ee89 100644 --- a/sklearn/neighbors/__init__.py +++ b/sklearn/neighbors/__init__.py @@ -4,13 +4,19 @@ """ from .ball_tree import BallTree +from .kd_tree import KDTree +from .dist_metrics import DistanceMetric from .graph import kneighbors_graph, radius_neighbors_graph from .unsupervised import NearestNeighbors from .classification import KNeighborsClassifier, RadiusNeighborsClassifier from .regression import KNeighborsRegressor, RadiusNeighborsRegressor from .nearest_centroid import NearestCentroid +from .kde import KernelDensity +from .approximate import LSHForest __all__ = ['BallTree', + 'DistanceMetric', + 'KDTree', 'KNeighborsClassifier', 'KNeighborsRegressor', 'NearestCentroid', @@ -18,4 +24,6 @@ 'RadiusNeighborsClassifier', 'RadiusNeighborsRegressor', 'kneighbors_graph', - 'radius_neighbors_graph'] + 'radius_neighbors_graph', + 'KernelDensity', + 'LSHForest'] diff --git a/sklearn/neighbors/approximate.py b/sklearn/neighbors/approximate.py new file mode 100644 index 0000000000000..57182cc5e5552 --- /dev/null +++ b/sklearn/neighbors/approximate.py @@ -0,0 +1,541 @@ +"""Approximate nearest neighbor search""" +# Author: Maheshakya Wijewardena +# Joel Nothman + +import numpy as np +import warnings + +from scipy import sparse + +from .base import KNeighborsMixin, RadiusNeighborsMixin +from ..base import BaseEstimator +from ..utils.validation import check_array +from ..utils import check_random_state +from ..metrics.pairwise import pairwise_distances + +from ..random_projection import GaussianRandomProjection + +__all__ = ["LSHForest"] + +HASH_DTYPE = '>u4' +MAX_HASH_SIZE = np.dtype(HASH_DTYPE).itemsize * 8 + + +def _find_matching_indices(tree, bin_X, left_mask, right_mask): + """Finds indices in sorted array of integers. + + Most significant h bits in the binary representations of the + integers are matched with the items' most significant h bits. + """ + left_index = np.searchsorted(tree, bin_X & left_mask) + right_index = np.searchsorted(tree, bin_X | right_mask, + side='right') + return left_index, right_index + + +def _find_longest_prefix_match(tree, bin_X, hash_size, + left_masks, right_masks): + """Find the longest prefix match in tree for each query in bin_X + + Most significant bits are considered as the prefix. + """ + hi = np.empty_like(bin_X, dtype=np.intp) + hi.fill(hash_size) + lo = np.zeros_like(bin_X, dtype=np.intp) + res = np.empty_like(bin_X, dtype=np.intp) + + left_idx, right_idx = _find_matching_indices(tree, bin_X, + left_masks[hi], + right_masks[hi]) + found = right_idx > left_idx + res[found] = lo[found] = hash_size + + r = np.arange(bin_X.shape[0]) + kept = r[lo < hi] # indices remaining in bin_X mask + while kept.shape[0]: + mid = (lo.take(kept) + hi.take(kept)) // 2 + + left_idx, right_idx = _find_matching_indices(tree, + bin_X.take(kept), + left_masks[mid], + right_masks[mid]) + found = right_idx > left_idx + mid_found = mid[found] + lo[kept[found]] = mid_found + 1 + res[kept[found]] = mid_found + hi[kept[~found]] = mid[~found] + + kept = r[lo < hi] + + return res + + +class ProjectionToHashMixin(object): + """Turn a transformed real-valued array into a hash""" + @staticmethod + def _to_hash(projected): + if projected.shape[1] % 8 != 0: + raise ValueError('Require reduced dimensionality to be a multiple ' + 'of 8 for hashing') + # XXX: perhaps non-copying operation better + out = np.packbits((projected > 0).astype(int)).view(dtype=HASH_DTYPE) + return out.reshape(projected.shape[0], -1) + + def fit_transform(self, X, y=None): + self.fit(X) + return self.transform(X) + + def transform(self, X, y=None): + return self._to_hash(super(ProjectionToHashMixin, self).transform(X)) + + +class GaussianRandomProjectionHash(ProjectionToHashMixin, + GaussianRandomProjection): + """Use GaussianRandomProjection to produce a cosine LSH fingerprint""" + def __init__(self, + n_components=8, + random_state=None): + super(GaussianRandomProjectionHash, self).__init__( + n_components=n_components, + random_state=random_state) + + +def _array_of_arrays(list_of_arrays): + """Creates an array of array from list of arrays.""" + out = np.empty(len(list_of_arrays), dtype=object) + out[:] = list_of_arrays + return out + + +class LSHForest(BaseEstimator, KNeighborsMixin, RadiusNeighborsMixin): + """Performs approximate nearest neighbor search using LSH forest. + + LSH Forest: Locality Sensitive Hashing forest [1] is an alternative + method for vanilla approximate nearest neighbor search methods. + LSH forest data structure has been implemented using sorted + arrays and binary search and 32 bit fixed-length hashes. + Random projection is used as the hash family which approximates + cosine distance. + + The cosine distance is defined as ``1 - cosine_similarity``: the lowest + value is 0 (identical point) but it is bounded above by 2 for the farthest + points. Its value does not depend on the norm of the vector points but + only on their relative angles. + + Parameters + ---------- + + n_estimators : int (default = 10) + Number of trees in the LSH Forest. + + min_hash_match : int (default = 4) + lowest hash length to be searched when candidate selection is + performed for nearest neighbors. + + n_candidates : int (default = 10) + Minimum number of candidates evaluated per estimator, assuming enough + items meet the `min_hash_match` constraint. + + n_neighbors : int (default = 5) + Number of neighbors to be returned from query function when + it is not provided to the :meth:`kneighbors` method. + + radius : float, optinal (default = 1.0) + Radius from the data point to its neighbors. This is the parameter + space to use by default for the :meth`radius_neighbors` queries. + + radius_cutoff_ratio : float, optional (default = 0.9) + A value ranges from 0 to 1. Radius neighbors will be searched until + the ratio between total neighbors within the radius and the total + candidates becomes less than this value unless it is terminated by + hash length reaching `min_hash_match`. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + Attributes + ---------- + + hash_functions_ : list of GaussianRandomProjectionHash objects + Hash function g(p,x) for a tree is an array of 32 randomly generated + float arrays with the same dimenstion as the data set. This array is + stored in GaussianRandomProjectionHash object and can be obtained + from ``components_`` attribute. + + trees_ : array, shape (n_estimators, n_samples) + Each tree (corresponding to a hash function) contains an array of + sorted hashed values. The array representation may change in future + versions. + + original_indices_ : array, shape (n_estimators, n_samples) + Original indices of sorted hashed values in the fitted index. + + References + ---------- + + .. [1] M. Bawa, T. Condie and P. Ganesan, "LSH Forest: Self-Tuning + Indexes for Similarity Search", WWW '05 Proceedings of the + 14th international conference on World Wide Web, 651-660, + 2005. + + Examples + -------- + >>> from sklearn.neighbors import LSHForest + + >>> X_train = [[5, 5, 2], [21, 5, 5], [1, 1, 1], [8, 9, 1], [6, 10, 2]] + >>> X_test = [[9, 1, 6], [3, 1, 10], [7, 10, 3]] + >>> lshf = LSHForest() + >>> lshf.fit(X_train) # doctest: +NORMALIZE_WHITESPACE + LSHForest(min_hash_match=4, n_candidates=50, n_estimators=10, + n_neighbors=5, radius=1.0, radius_cutoff_ratio=0.9, + random_state=None) + >>> distances, indices = lshf.kneighbors(X_test, n_neighbors=2) + >>> distances # doctest: +ELLIPSIS + array([[ 0.069..., 0.149...], + [ 0.229..., 0.481...], + [ 0.004..., 0.014...]]) + >>> indices + array([[1, 2], + [2, 0], + [4, 0]]) + + """ + + def __init__(self, n_estimators=10, radius=1.0, n_candidates=50, + n_neighbors=5, min_hash_match=4, radius_cutoff_ratio=.9, + random_state=None): + self.n_estimators = n_estimators + self.radius = radius + self.random_state = random_state + self.n_candidates = n_candidates + self.n_neighbors = n_neighbors + self.min_hash_match = min_hash_match + self.radius_cutoff_ratio = radius_cutoff_ratio + + def _compute_distances(self, query, candidates): + """Computes the cosine distance. + + Distance is from the query to points in the candidates array. + Returns argsort of distances in the candidates + array and sorted distances. + """ + if candidates.shape == (0,): + # needed since _fit_X[np.array([])] doesn't work if _fit_X sparse + return np.empty(0, dtype=np.int), np.empty(0, dtype=float) + + distances = pairwise_distances(query, self._fit_X[candidates], + metric='cosine')[0] + distance_positions = np.argsort(distances) + return distance_positions, distances[distance_positions] + + def _generate_masks(self): + """Creates left and right masks for all hash lengths.""" + tri_size = MAX_HASH_SIZE + 1 + # Called once on fitting, output is independent of hashes + left_mask = np.tril(np.ones((tri_size, tri_size), dtype=int))[:, 1:] + right_mask = left_mask[::-1, ::-1] + + self._left_mask = np.packbits(left_mask).view(dtype=HASH_DTYPE) + self._right_mask = np.packbits(right_mask).view(dtype=HASH_DTYPE) + + def _get_candidates(self, query, max_depth, bin_queries, n_neighbors): + """Performs the Synchronous ascending phase. + + Returns an array of candidates, their distance ranks and + distances. + """ + index_size = self._fit_X.shape[0] + # Number of candidates considered including duplicates + # XXX: not sure whether this is being calculated correctly wrt + # duplicates from different iterations through a single tree + n_candidates = 0 + candidate_set = set() + min_candidates = self.n_candidates * self.n_estimators + while (max_depth > self.min_hash_match and + (n_candidates < min_candidates or + len(candidate_set) < n_neighbors)): + + left_mask = self._left_mask[max_depth] + right_mask = self._right_mask[max_depth] + for i in range(self.n_estimators): + start, stop = _find_matching_indices(self.trees_[i], + bin_queries[i], + left_mask, right_mask) + n_candidates += stop - start + candidate_set.update( + self.original_indices_[i][start:stop].tolist()) + max_depth -= 1 + + candidates = np.fromiter(candidate_set, count=len(candidate_set), + dtype=np.intp) + # For insufficient candidates, candidates are filled. + # Candidates are filled from unselected indices uniformly. + if candidates.shape[0] < n_neighbors: + warnings.warn( + "Number of candidates is not sufficient to retrieve" + " %i neighbors with" + " min_hash_match = %i. Candidates are filled up" + " uniformly from unselected" + " indices." % (n_neighbors, self.min_hash_match)) + remaining = np.setdiff1d(np.arange(0, index_size), candidates) + to_fill = n_neighbors - candidates.shape[0] + candidates = np.concatenate((candidates, remaining[:to_fill])) + + ranks, distances = self._compute_distances(query, + candidates.astype(int)) + + return (candidates[ranks[:n_neighbors]], + distances[:n_neighbors]) + + def _get_radius_neighbors(self, query, max_depth, bin_queries, radius): + """Finds radius neighbors from the candidates obtained. + + Their distances from query are smaller than radius. + Returns radius neighbors and distances. + """ + ratio_within_radius = 1 + threshold = 1 - self.radius_cutoff_ratio + total_candidates = np.array([], dtype=int) + total_neighbors = np.array([], dtype=int) + total_distances = np.array([], dtype=float) + + while (max_depth > self.min_hash_match and + ratio_within_radius > threshold): + left_mask = self._left_mask[max_depth] + right_mask = self._right_mask[max_depth] + candidates = [] + for i in range(self.n_estimators): + start, stop = _find_matching_indices(self.trees_[i], + bin_queries[i], + left_mask, right_mask) + candidates.extend( + self.original_indices_[i][start:stop].tolist()) + candidates = np.setdiff1d(candidates, total_candidates) + total_candidates = np.append(total_candidates, candidates) + ranks, distances = self._compute_distances(query, candidates) + m = np.searchsorted(distances, radius, side='right') + positions = np.searchsorted(total_distances, distances[:m]) + total_neighbors = np.insert(total_neighbors, positions, + candidates[ranks[:m]]) + total_distances = np.insert(total_distances, positions, + distances[:m]) + ratio_within_radius = (total_neighbors.shape[0] / + float(total_candidates.shape[0])) + max_depth = max_depth - 1 + return total_neighbors, total_distances + + def fit(self, X, y=None): + """Fit the LSH forest on the data. + + This creates binary hashes of input data points by getting the + dot product of input points and hash_function then + transforming the projection into a binary string array based + on the sign (positive/negative) of the projection. + A sorted array of binary hashes is created. + + Parameters + ---------- + X : array_like or sparse (CSR) matrix, shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single data point. + + Returns + ------- + self : object + Returns self. + """ + + self._fit_X = check_array(X, accept_sparse='csr') + + # Creates a g(p,x) for each tree + self.hash_functions_ = [] + self.trees_ = [] + self.original_indices_ = [] + + rng = check_random_state(self.random_state) + int_max = np.iinfo(np.int32).max + + for i in range(self.n_estimators): + # This is g(p,x) for a particular tree. + # Builds a single tree. Hashing is done on an array of data points. + # `GaussianRandomProjection` is used for hashing. + # `n_components=hash size and n_features=n_dim. + hasher = GaussianRandomProjectionHash(MAX_HASH_SIZE, + rng.randint(0, int_max)) + hashes = hasher.fit_transform(self._fit_X)[:, 0] + original_index = np.argsort(hashes) + bin_hashes = hashes[original_index] + self.original_indices_.append(original_index) + self.trees_.append(bin_hashes) + self.hash_functions_.append(hasher) + + self._generate_masks() + + return self + + def _query(self, X): + """Performs descending phase to find maximum depth.""" + # Calculate hashes of shape (n_samples, n_estimators, [hash_size]) + bin_queries = np.asarray([hasher.transform(X)[:, 0] + for hasher in self.hash_functions_]) + bin_queries = np.rollaxis(bin_queries, 1) + + # descend phase + depths = [_find_longest_prefix_match(tree, tree_queries, MAX_HASH_SIZE, + self._left_mask, self._right_mask) + for tree, tree_queries in zip(self.trees_, + np.rollaxis(bin_queries, 1))] + + return bin_queries, np.max(depths, axis=0) + + def kneighbors(self, X, n_neighbors=None, return_distance=True): + """Returns n_neighbors of approximate nearest neighbors. + + Parameters + ---------- + X : array_like or sparse (CSR) matrix, shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single query. + + n_neighbors : int, opitonal (default = None) + Number of neighbors required. If not provided, this will + return the number specified at the initialization. + + return_distance : boolean, optional (default = False) + Returns the distances of neighbors if set to True. + + Returns + ------- + dist : array, shape (n_samples, n_neighbors) + Array representing the cosine distances to each point, + only present if return_distance=True. + + ind : array, shape (n_samples, n_neighbors) + Indices of the approximate nearest points in the population + matrix. + """ + if not hasattr(self, 'hash_functions_'): + raise ValueError("estimator should be fitted.") + + if n_neighbors is None: + n_neighbors = self.n_neighbors + + X = check_array(X, accept_sparse='csr') + + neighbors, distances = [], [] + bin_queries, max_depth = self._query(X) + for i in range(X.shape[0]): + neighs, dists = self._get_candidates(X[i], max_depth[i], + bin_queries[i], + n_neighbors) + neighbors.append(neighs) + distances.append(dists) + + if return_distance: + return np.array(distances), np.array(neighbors) + else: + return np.array(neighbors) + + def radius_neighbors(self, X, radius=None, return_distance=True): + """Finds the neighbors within a given radius of a point or points. + + Return the indices and distances of some points from the dataset + lying in a ball with size ``radius`` around the points of the query + array. Points lying on the boundary are included in the results. + + The result points are *not* necessarily sorted by distance to their + query point. + + LSH Forest being an approximate method, some true neighbors from the + indexed dataset might be missing from the results. + + Parameters + ---------- + X : array_like or sparse (CSR) matrix, shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single query. + + radius : float + Limiting distance of neighbors to return. + (default is the value passed to the constructor). + + return_distance : boolean, optional (default = False) + Returns the distances of neighbors if set to True. + + Returns + ------- + dist : array, shape (n_samples,) of arrays + Each element is an array representing the cosine distances + to some points found within ``radius`` of the respective query. + Only present if ``return_distance=True``. + + ind : array, shape (n_samples,) of arrays + Each element is an array of indices for neighbors within ``radius`` + of the respective query. + """ + if not hasattr(self, 'hash_functions_'): + raise ValueError("estimator should be fitted.") + + if radius is None: + radius = self.radius + + X = check_array(X, accept_sparse='csr') + + neighbors, distances = [], [] + bin_queries, max_depth = self._query(X) + for i in range(X.shape[0]): + neighs, dists = self._get_radius_neighbors(X[i], max_depth[i], + bin_queries[i], radius) + neighbors.append(neighs) + distances.append(dists) + + if return_distance: + return _array_of_arrays(distances), _array_of_arrays(neighbors) + else: + return _array_of_arrays(neighbors) + + def partial_fit(self, X, y=None): + """ + Inserts new data into the already fitted LSH Forest. + Cost is proportional to new total size, so additions + should be batched. + + Parameters + ---------- + X : array_like or sparse (CSR) matrix, shape (n_samples, n_features) + New data point to be inserted into the LSH Forest. + """ + X = check_array(X, accept_sparse='csr') + if not hasattr(self, 'hash_functions_'): + return self.fit(X) + + if X.shape[1] != self._fit_X.shape[1]: + raise ValueError("Number of features in X and" + " fitted array does not match.") + n_samples = X.shape[0] + n_indexed = self._fit_X.shape[0] + + for i in range(self.n_estimators): + bin_X = self.hash_functions_[i].transform(X)[:, 0] + # gets the position to be added in the tree. + positions = self.trees_[i].searchsorted(bin_X) + # adds the hashed value into the tree. + self.trees_[i] = np.insert(self.trees_[i], + positions, bin_X) + # add the entry into the original_indices_. + self.original_indices_[i] = np.insert(self.original_indices_[i], + positions, + np.arange(n_indexed, + n_indexed + + n_samples)) + + # adds the entry into the input_array. + if sparse.issparse(X) or sparse.issparse(self._fit_X): + self._fit_X = sparse.vstack((self._fit_X, X)) + else: + self._fit_X = np.row_stack((self._fit_X, X)) + + return self diff --git a/sklearn/neighbors/ball_tree.c b/sklearn/neighbors/ball_tree.c index c743ec8d3c5c5..6e1ff40bf21a7 100644 --- a/sklearn/neighbors/ball_tree.c +++ b/sklearn/neighbors/ball_tree.c @@ -1,16 +1,29 @@ -/* Generated by Cython 0.15.1 on Thu Jan 26 09:36:33 2012 */ +/* Generated by Cython 0.20.1post0 (Debian 0.20.1+git90-g0e6e38e-1ubuntu2) on Thu Nov 27 09:11:52 2014 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. #else - +#define CYTHON_ABI "0_20_1post0" #include /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -22,36 +35,50 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - -#if PY_VERSION_HEX < 0x02040000 - #define METH_COEXIST 0 - #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) - #define PyDict_Contains(d,o) PySequence_Contains(d,o) +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if CYTHON_COMPILING_IN_PYPY +#define Py_OptimizeFlag 0 #endif - #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -59,7 +86,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -73,7 +99,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -83,24 +108,74 @@ #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT) + #define Py_TPFLAGS_IS_ABSTRACT 0 +#endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -108,7 +183,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -127,7 +201,14 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -135,9 +216,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -153,13 +232,12 @@ #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - -#if PY_VERSION_HEX < 0x03020000 +#if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong @@ -167,16 +245,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -195,11 +263,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -209,7 +275,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -217,6 +282,55 @@ #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#ifdef __cplusplus +template +void __Pyx_call_destructor(T* x) { + x->~T(); +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus @@ -232,10 +346,14 @@ #include #define __PYX_HAVE__sklearn__neighbors__ball_tree #define __PYX_HAVE_API__sklearn__neighbors__ball_tree +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" +#include "math.h" +#include "pythread.h" +#include "pystate.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -244,21 +362,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -266,48 +369,161 @@ # else # define CYTHON_UNUSED # endif -# elif defined(__ICC) || defined(__INTEL_COMPILER) +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif -#ifdef __GNUC__ - /* Test for GCC > 2.95 */ - #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) - #else /* __GNUC__ > 2 ... */ - #define likely(x) (x) - #define unlikely(x) (x) - #endif /* __GNUC__ > 2 ... */ -#else /* __GNUC__ */ +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -316,7 +532,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -326,7 +541,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -334,18 +548,114 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { + "binary_tree.pxi", "ball_tree.pyx", - "numpy.pxd", + "__init__.pxd", + "stringsource", + "stringsource", + "type.pxd", + "dist_metrics.pxd", }; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + +struct __pyx_memoryview_obj; +typedef struct { + struct __pyx_memoryview_obj *memview; + char *data; + Py_ssize_t shape[8]; + Py_ssize_t strides[8]; + Py_ssize_t suboffsets[8]; +} __Pyx_memviewslice; + +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __pyx_atomic_int_type int +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ + !defined(__i386__) + #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && MSC_VER + #include + #define __pyx_atomic_int_type LONG + #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using MSVC atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 + #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using Intel atomics" + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif +typedef volatile __pyx_atomic_int_type __pyx_atomic_int; +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview) \ + __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) +#else + #define __pyx_add_acquisition_count(memview) \ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif + -/* "numpy.pxd":719 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -354,7 +664,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -363,7 +673,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -372,7 +682,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -381,7 +691,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -390,7 +700,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -399,7 +709,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -408,7 +718,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -417,7 +727,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -426,7 +736,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -435,7 +745,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -444,7 +754,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -453,7 +763,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -462,7 +772,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -471,7 +781,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -480,7 +790,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -489,7 +799,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -498,7 +808,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -507,7 +817,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -516,7 +826,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -525,7 +835,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -534,24 +844,23 @@ typedef npy_double __pyx_t_5numpy_double_t; */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; -/* "sklearn/neighbors/ball_tree.pyx":203 - * # type used for data - * DTYPE = np.float64 - * ctypedef np.float64_t DTYPE_t # <<<<<<<<<<<<<< +/* "typedefs.pxd":5 * - * # type used for indices & counts + * # Floating point/data type + * ctypedef np.float64_t DTYPE_t # WARNING: should match DTYPE in typedefs.pyx # <<<<<<<<<<<<<< + * + * cdef enum: */ -typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t; +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t; -/* "sklearn/neighbors/ball_tree.pyx":208 - * # warning: there will be problems if this is switched to an unsigned type! - * ITYPE = np.int32 - * ctypedef np.int32_t ITYPE_t # <<<<<<<<<<<<<< +/* "typedefs.pxd":13 + * # Index/integer type. + * # WARNING: ITYPE_t must be a signed integer type or you will have a bad time! + * ctypedef np.intp_t ITYPE_t # WARNING: should match ITYPE in typedefs.pyx # <<<<<<<<<<<<<< * - * # infinity + * # Fused type for certain operations */ -typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t; - +typedef __pyx_t_5numpy_intp_t __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t; #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -572,10 +881,19 @@ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t; typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric; +struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap; +struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap; +struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree; struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree; +struct __pyx_array_obj; +struct __pyx_MemviewEnum_obj; +struct __pyx_memoryview_obj; +struct __pyx_memoryviewslice_obj; -/* "numpy.pxd":758 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -584,7 +902,7 @@ struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -593,7 +911,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -602,7 +920,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -610,86 +928,375 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; -struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo; -struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item; -struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack; - -/* "sklearn/neighbors/ball_tree.pyx":326 - * # array for efficiency. This is a hybrid of the "Array of Structures" - * # and "Structure of Arrays" styles. - * cdef struct NodeInfo: # <<<<<<<<<<<<<< + +/* "typedefs.pxd":7 + * ctypedef np.float64_t DTYPE_t # WARNING: should match DTYPE in typedefs.pyx + * + * cdef enum: # <<<<<<<<<<<<<< + * DTYPECODE = np.NPY_FLOAT64 + * ITYPECODE = np.NPY_INTP + */ +enum { + + /* "typedefs.pxd":9 + * cdef enum: + * DTYPECODE = np.NPY_FLOAT64 + * ITYPECODE = np.NPY_INTP # <<<<<<<<<<<<<< + * + * # Index/integer type. + */ + __pyx_e_7sklearn_9neighbors_8typedefs_DTYPECODE = NPY_FLOAT64, + __pyx_e_7sklearn_9neighbors_8typedefs_ITYPECODE = NPY_INTP +}; +struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t; +struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t; + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":385 + * # for all valid d and h. Note that for precision, the log of both + * # the kernel and kernel norm is returned. + * cdef enum KernelType: # <<<<<<<<<<<<<< + * GAUSSIAN_KERNEL = 1 + * TOPHAT_KERNEL = 2 + */ +enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType { + __pyx_e_7sklearn_9neighbors_9ball_tree_GAUSSIAN_KERNEL = 1, + __pyx_e_7sklearn_9neighbors_9ball_tree_TOPHAT_KERNEL = 2, + __pyx_e_7sklearn_9neighbors_9ball_tree_EPANECHNIKOV_KERNEL = 3, + __pyx_e_7sklearn_9neighbors_9ball_tree_EXPONENTIAL_KERNEL = 4, + __pyx_e_7sklearn_9neighbors_9ball_tree_LINEAR_KERNEL = 5, + __pyx_e_7sklearn_9neighbors_9ball_tree_COSINE_KERNEL = 6 +}; + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":169 + * + * # Some compound datatypes used below: + * cdef struct NodeHeapData_t: # <<<<<<<<<<<<<< + * DTYPE_t val + * ITYPE_t i1 + */ +struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t val; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t i2; +}; + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":188 + * 'itemsize': sizeof(NodeHeapData_t)}) + * + * cdef struct NodeData_t: # <<<<<<<<<<<<<< * ITYPE_t idx_start * ITYPE_t idx_end */ -struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t idx_start; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t idx_end; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t is_leaf; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t radius; +struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t idx_start; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t idx_end; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t is_leaf; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t radius; }; -/* "sklearn/neighbors/ball_tree.pyx":336 - * # stack struct - * # This is used to keep track of the recursion stack in Node_query - * cdef struct stack_item: # <<<<<<<<<<<<<< - * ITYPE_t i_node - * DTYPE_t dist_p_LB +/* "dist_metrics.pxd":48 + * ###################################################################### + * # DistanceMetric base class + * cdef class DistanceMetric: # <<<<<<<<<<<<<< + * # The following attributes are required for a few of the subclasses. + * # we must define them here so that cython's limited polymorphism will work. */ -struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t i_node; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t dist_p_LB; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_vtab; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t p; + PyArrayObject *vec; + PyArrayObject *mat; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *vec_ptr; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *mat_ptr; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t size; + PyObject *func; + PyObject *kwargs; }; -/* "sklearn/neighbors/ball_tree.pyx":341 + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":560 * * - * cdef struct stack: # <<<<<<<<<<<<<< - * int n - * stack_item* heap + * cdef class NeighborsHeap: # <<<<<<<<<<<<<< + * """A max-heap structure to keep track of distances/indices of neighbors + * */ -struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack { - int n; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item *heap; - int size; +struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_vtab; + PyArrayObject *distances_arr; + PyArrayObject *indices_arr; + __Pyx_memviewslice distances; + __Pyx_memviewslice indices; }; -/* "sklearn/neighbors/ball_tree.pyx":398 - * # BallTree class - * # - * cdef class BallTree(object): # <<<<<<<<<<<<<< - * """ - * Ball Tree for fast nearest-neighbor searches : + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":860 + * + * + * cdef class NodeHeap: # <<<<<<<<<<<<<< + * """NodeHeap + * + */ +struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_vtab; + PyArrayObject *data_arr; + __Pyx_memviewslice data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t n; +}; + + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":997 + * ###################################################################### + * # Binary Tree class + * cdef class BinaryTree: # <<<<<<<<<<<<<< + * + * cdef np.ndarray data_arr + */ +struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_vtab; + PyArrayObject *data_arr; + PyArrayObject *idx_array_arr; + PyArrayObject *node_data_arr; + PyArrayObject *node_bounds_arr; + __Pyx_memviewslice data; + __Pyx_memviewslice idx_array; + __Pyx_memviewslice node_data; + __Pyx_memviewslice node_bounds; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t leaf_size; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t n_levels; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t n_nodes; + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *dist_metric; + int euclidean; + int n_trims; + int n_leaves; + int n_splits; + int n_calls; +}; + + +/* "sklearn/neighbors/ball_tree.pyx":28 + * + * # Inherit BallTree from BinaryTree + * cdef class BallTree(BinaryTree): # <<<<<<<<<<<<<< + * __doc__ = CLASS_DOC.format(**DOC_DICT) + * pass */ struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree { + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree __pyx_base; +}; + + +/* "View.MemoryView":99 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ +struct __pyx_array_obj { + PyObject_HEAD + char *data; + Py_ssize_t len; + char *format; + int ndim; + Py_ssize_t *_shape; + Py_ssize_t *_strides; + Py_ssize_t itemsize; + PyObject *mode; + PyObject *_format; + void (*callback_free_data)(void *); + int free_data; + int dtype_is_object; +}; + + +/* "View.MemoryView":269 + * + * @cname('__pyx_MemviewEnum') + * cdef class Enum(object): # <<<<<<<<<<<<<< + * cdef object name + * def __init__(self, name): + */ +struct __pyx_MemviewEnum_obj { + PyObject_HEAD + PyObject *name; +}; + + +/* "View.MemoryView":302 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ +struct __pyx_memoryview_obj { PyObject_HEAD - struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree *__pyx_vtab; - PyArrayObject *data; - PyArrayObject *idx_array; - PyArrayObject *node_centroid_arr; - PyArrayObject *node_info_arr; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t p; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t leaf_size; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t n_levels; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t n_nodes; - int warning_flag; + struct __pyx_vtabstruct_memoryview *__pyx_vtab; + PyObject *obj; + PyObject *_size; + PyObject *_array_interface; + PyThread_type_lock lock; + __pyx_atomic_int acquisition_count[2]; + __pyx_atomic_int *acquisition_count_aligned_p; + Py_buffer view; + int flags; + int dtype_is_object; + __Pyx_TypeInfo *typeinfo; +}; + + +/* "View.MemoryView":922 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ +struct __pyx_memoryviewslice_obj { + struct __pyx_memoryview_obj __pyx_base; + __Pyx_memviewslice from_slice; + PyObject *from_object; + PyObject *(*to_object_func)(char *); + int (*to_dtype_func)(char *, PyObject *); +}; + + + +/* "dist_metrics.pxd":48 + * ###################################################################### + * # DistanceMetric base class + * cdef class DistanceMetric: # <<<<<<<<<<<<<< + * # The following attributes are required for a few of the subclasses. + * # we must define them here so that cython's limited polymorphism will work. + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*dist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*rdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*pdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __Pyx_memviewslice, __Pyx_memviewslice); + int (*cdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*_rdist_to_dist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*_dist_to_rdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":560 + * + * + * cdef class NeighborsHeap: # <<<<<<<<<<<<<< + * """A max-heap structure to keep track of distances/indices of neighbors + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NeighborsHeap { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*largest)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*push)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, int __pyx_skip_dispatch); + int (*_sort)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *); +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_vtabptr_7sklearn_9neighbors_9ball_tree_NeighborsHeap; +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":860 + * + * + * cdef class NodeHeap: # <<<<<<<<<<<<<< + * """NodeHeap + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap { + int (*resize)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*push)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *, struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t); + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t (*peek)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *); + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t (*pop)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *); + void (*clear)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *); +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_vtabptr_7sklearn_9neighbors_9ball_tree_NodeHeap; + + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":997 + * ###################################################################### + * # Binary Tree class + * cdef class BinaryTree: # <<<<<<<<<<<<<< + * + * cdef np.ndarray data_arr + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*dist)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*rdist)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*_recursive_build)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*_query_single_depthfirst)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + int (*_query_single_breadthfirst)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *); + int (*_query_dual_depthfirst)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __Pyx_memviewslice, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + int (*_query_dual_breadthfirst)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *); + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t (*_query_radius_single)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, int, int); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*_kde_single_breadthfirst)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); + int (*_kde_single_depthfirst)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); + int (*_two_point_single)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*_two_point_dual)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); }; +static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BinaryTree; +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_rdist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); +/* "sklearn/neighbors/ball_tree.pyx":28 + * + * # Inherit BallTree from BinaryTree + * cdef class BallTree(BinaryTree): # <<<<<<<<<<<<<< + * __doc__ = CLASS_DOC.format(**DOC_DICT) + * pass + */ struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree { - void (*build_tree_)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *); - void (*query_one_)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t (*query_radius_count_)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *); - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t (*query_radius_idx_only_)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *); - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t (*query_radius_distances_)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *); + struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree __pyx_base; }; static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree *__pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BallTree; +/* "View.MemoryView":302 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ + +struct __pyx_vtabstruct_memoryview { + char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); + PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); +}; +static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; + + +/* "View.MemoryView":922 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ + +struct __pyx_vtabstruct__memoryviewslice { + struct __pyx_vtabstruct_memoryview __pyx_base; +}; +static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -702,9 +1309,22 @@ static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree *__pyx_vt static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -714,7 +1334,7 @@ static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree *__pyx_vt #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -725,124 +1345,336 @@ static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree *__pyx_vt #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d +#define __Pyx_MEMVIEW_DIRECT 1 +#define __Pyx_MEMVIEW_PTR 2 +#define __Pyx_MEMVIEW_FULL 4 +#define __Pyx_MEMVIEW_CONTIG 8 +#define __Pyx_MEMVIEW_STRIDED 16 +#define __Pyx_MEMVIEW_FOLLOW 32 +#define __Pyx_IS_C_CONTIG 1 +#define __Pyx_IS_F_CONTIG 2 +static int __Pyx_init_memviewslice( + struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference); +static CYTHON_INLINE int __pyx_add_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) +#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) +#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) +#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) +static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ -static CYTHON_INLINE int __Pyx_CheckKeywordStrings(PyObject *kwdict, - const char* function_name, int kw_allowed); /*proto*/ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ +#include -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ -static CYTHON_INLINE long __Pyx_div_long(long, long); /* proto */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ -#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals +#else +#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals +#endif +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; +static CYTHON_INLINE int __Pyx_CheckKeywordStrings(PyObject *kwdict, const char* function_name, int kw_allowed); /*proto*/ + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename, + int full_traceback); /*proto*/ + +static CYTHON_INLINE int __Pyx_PySequence_Contains(PyObject* item, PyObject* seq, int eq) { + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); } +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); -#define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_List_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); + +#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) : \ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck); + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); /*proto*/ + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) + +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /*proto*/ + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); + return PyList_Append(list, x); } +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif -#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Tuple_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject* none = _PyList_Extend((PyListObject*)L, v); + if (unlikely(!none)) + return -1; + Py_DECREF(none); + return 0; +#else + return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); +#endif +} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); + return PyList_Append(list, x); } +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +#if PY_MAJOR_VERSION < 3 +#define __Pyx_PyString_Join __Pyx_PyBytes_Join +#define __Pyx_PyBaseString_Join(s, v) (PyUnicode_CheckExact(s) ? PyUnicode_Join(s, v) : __Pyx_PyBytes_Join(s, v)) +#else +#define __Pyx_PyString_Join PyUnicode_Join +#define __Pyx_PyBaseString_Join PyUnicode_Join +#endif +#if CYTHON_COMPILING_IN_CPYTHON + #if PY_MAJOR_VERSION < 3 + #define __Pyx_PyBytes_Join _PyString_Join + #else + #define __Pyx_PyBytes_Join _PyBytes_Join + #endif +#else +static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values); /*proto*/ +#endif -#define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { - PyObject *r; - if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) { - r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - } - else if (PyTuple_CheckExact(o) && ((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - } - else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0))) { - r = PySequence_GetItem(o, i); - } - else { - r = __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); - } - return r; -} +static void* __Pyx_GetVtable(PyObject *dict); /*proto*/ -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /*proto*/ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj); -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *); + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *); -static CYTHON_INLINE npy_int32 __Pyx_PyInt_from_py_npy_int32(PyObject *); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); + +static PyObject *__pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(const char *itemp); /* proto */ +static int __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(const char *itemp, PyObject *obj); /* proto */ static CYTHON_INLINE long __Pyx_pow_long(long, long); /* proto */ -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32); +static PyObject *__pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(const char *itemp); /* proto */ +static int __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(const char *itemp, PyObject *obj); /* proto */ -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t); +struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t; +static PyObject* __pyx_convert__to_py___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t s); +struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t; +static struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_convert__from_py___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(PyObject *); + +static PyObject *__pyx_memview_get_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(const char *itemp); /* proto */ +static int __pyx_memview_set_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(const char *itemp, PyObject *obj); /* proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -856,8 +1688,7 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - -#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else @@ -943,62 +1774,88 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); +static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim); -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); +static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize); -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object); -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); +struct __pyx_typeinfo_string { + char string[3]; +}; +static struct __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *type); -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t(PyObject *); -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); +static int __Pyx_check_binary_version(void); -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename); /*proto*/ +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); /*proto*/ -static int __Pyx_check_binary_version(void); +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); -static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ +/* Module declarations from 'cython.view' */ +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ +/* Module declarations from 'cython' */ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -1009,1503 +1866,2391 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ -/* Module declarations from 'cython.cython.view' */ +/* Module declarations from 'libc.math' */ -/* Module declarations from 'cython' */ +/* Module declarations from 'sklearn.utils.lgamma' */ +static double (*__pyx_f_7sklearn_5utils_6lgamma_lgamma)(double); /*proto*/ + +/* Module declarations from 'sklearn.neighbors.typedefs' */ -/* Module declarations from 'libc' */ +/* Module declarations from 'sklearn.neighbors.dist_metrics' */ +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric = 0; +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist_to_rdist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist_to_dist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ /* Module declarations from 'sklearn.neighbors.ball_tree' */ +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_9ball_tree_NeighborsHeap = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_9ball_tree_NodeHeap = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree = 0; static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_9ball_tree_BallTree = 0; -static __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_7sklearn_9neighbors_9ball_tree_infinity; -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dmax(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t); /*proto*/ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dmin(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t); /*proto*/ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dabs(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t); /*proto*/ -static __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dist(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t); /*proto*/ -static __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t); /*proto*/ -static __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dist_from_dist_p(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t); /*proto*/ -static __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p_from_dist(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t); /*proto*/ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_stack_create(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *, int); /*proto*/ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_stack_destroy(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *); /*proto*/ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_stack_resize(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *, int); /*proto*/ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item); /*proto*/ -static CYTHON_INLINE struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item __pyx_f_7sklearn_9neighbors_9ball_tree_stack_pop(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *); /*proto*/ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_copy_array(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static void __pyx_f_7sklearn_9neighbors_9ball_tree_compute_centroid(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_find_split_dim(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_iswap(__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_dswap(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static void __pyx_f_7sklearn_9neighbors_9ball_tree_partition_indices(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_calc_dist_LB(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t); /*proto*/ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_calc_dist_p_LB(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t); /*proto*/ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_pqueue_largest(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_pqueue_idx_largest(__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_pqueue_insert(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_max_heap_largest(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_max_heap_idx_largest(__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static void __pyx_f_7sklearn_9neighbors_9ball_tree_max_heap_insert(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static void __pyx_f_7sklearn_9neighbors_9ball_tree_sort_dist_idx(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ -static __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_partition_dist_idx(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); /*proto*/ +static PyTypeObject *__pyx_array_type = 0; +static PyTypeObject *__pyx_MemviewEnum_type = 0; +static PyTypeObject *__pyx_memoryview_type = 0; +static PyTypeObject *__pyx_memoryviewslice_type = 0; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_9ball_tree_INF; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_9ball_tree_NEG_INF; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_9ball_tree_PI; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_9ball_tree_ROOT_2PI; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_9ball_tree_LOG_PI; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_9ball_tree_LOG_2PI; +static struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_v_7sklearn_9neighbors_9ball_tree_nhd_tmp; +static struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_7sklearn_9neighbors_9ball_tree_nd_tmp; +static PyObject *generic = 0; +static PyObject *strided = 0; +static PyObject *indirect = 0; +static PyObject *contiguous = 0; +static PyObject *indirect_contiguous = 0; +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_1D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_2D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_3D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_1D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_2D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_NodeHeapData_1D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_NodeData_1D(PyArrayObject *); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_gaussian_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_tophat_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_epanechnikov_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_exponential_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_linear_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_cosine_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_logVn(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_logSn(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree__log_kernel_norm(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType); /*proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_dual_swap(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static int __pyx_f_7sklearn_9neighbors_9ball_tree__simultaneous_sort(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_find_node_split_dim(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static int __pyx_f_7sklearn_9neighbors_9ball_tree_partition_node_indices(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_swap_nodes(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE double __pyx_f_7sklearn_9neighbors_9ball_tree_fmin(double, double); /*proto*/ +static CYTHON_INLINE double __pyx_f_7sklearn_9neighbors_9ball_tree_fmax(double, double); /*proto*/ +static int __pyx_f_7sklearn_9neighbors_9ball_tree_allocate_data(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static int __pyx_f_7sklearn_9neighbors_9ball_tree_init_node(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_min_dist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_max_dist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); /*proto*/ +static CYTHON_INLINE int __pyx_f_7sklearn_9neighbors_9ball_tree_min_max_dist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_min_dist_dual(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_max_dist_dual(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist_dual(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE void __pyx_fuse_0__pyx_f_7sklearn_9neighbors_9ball_tree_swap(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, int, int); /*proto*/ +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ +static void *__pyx_align_pointer(void *, size_t); /*proto*/ +static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ +static PyObject *_unellipsify(PyObject *, int); /*proto*/ +static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ +static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ +static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ +static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ +static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ +static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ +static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ +static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ +static PyObject *__pyx_format_from_typeinfo(__Pyx_TypeInfo *); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t = { "ITYPE_t", NULL, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t), 0 }; +static __Pyx_StructField __Pyx_StructFields_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t[] = { + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, "val", offsetof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t, val)}, + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, "i1", offsetof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t, i1)}, + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, "i2", offsetof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t, i2)}, + {NULL, NULL, 0} +}; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t = { "NodeHeapData_t", __Pyx_StructFields_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t, sizeof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t), { 0 }, 0, 'S', 0, 0 }; +static __Pyx_StructField __Pyx_StructFields_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t[] = { + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, "idx_start", offsetof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t, idx_start)}, + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, "idx_end", offsetof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t, idx_end)}, + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, "is_leaf", offsetof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t, is_leaf)}, + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, "radius", offsetof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t, radius)}, + {NULL, NULL, 0} +}; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t = { "NodeData_t", __Pyx_StructFields_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t, sizeof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t), { 0 }, 0, 'S', 0, 0 }; #define __Pyx_MODULE_NAME "sklearn.neighbors.ball_tree" int __pyx_module_is_main_sklearn__neighbors__ball_tree = 0; /* Implementation of 'sklearn.neighbors.ball_tree' */ -static PyObject *__pyx_builtin_ValueError; -static PyObject *__pyx_builtin_enumerate; static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; -static char __pyx_k_1[] = "new_size smaller than current"; -static char __pyx_k_3[] = "popping empty stack"; -static char __pyx_k_11[] = "X is an empty array"; -static char __pyx_k_13[] = "X should have two dimensions"; -static char __pyx_k_15[] = "p must be greater than or equal to 1"; -static char __pyx_k_17[] = "leaf_size must be greater than or equal to 1"; -static char __pyx_k_20[] = "query data dimension must match BallTree data dimension"; -static char __pyx_k_22[] = "k must be less than or equal to the number of training points"; -static char __pyx_k_29[] = "count_only and return_distance cannot both be true"; -static char __pyx_k_31[] = "return_distance must be True if sort_distances is True"; -static char __pyx_k_35[] = "r must be broadcastable to X.shape"; -static char __pyx_k_38[] = "Fatal: parent is a leaf. Memory allocation is flawed"; -static char __pyx_k_40[] = "zero-sized node"; -static char __pyx_k_42[] = "ndarray is not C contiguous"; -static char __pyx_k_44[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_46[] = "Non-native byte order not supported"; -static char __pyx_k_48[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_49[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_52[] = "Format string allocated too short."; -static char __pyx_k_54[] = "\n=========\nBall Tree\n=========\nA ball tree is a data object which speeds up nearest neighbor\nsearches in high dimensions (see scikit-learn neighbors module\ndocumentation for an overview of neighbor trees). There are many\ntypes of ball trees. This package provides a basic implementation\nin cython.\n\nImplementation Notes\n--------------------\n\nA ball tree can be thought of as a collection of nodes. Each node\nstores a centroid, a radius, and the pointers to two child nodes.\n\n* centroid : the centroid of a node is the mean of all the locations\n of points within the node\n* radius : the radius of a node is the distance from the centroid\n to the furthest point in the node.\n* subnodes : each node has a maximum of 2 child nodes. The data within\n the parent node is divided between the two child nodes.\n\nIn a typical tree implementation, nodes may be classes or structures which\nare dynamically allocated as needed. This offers flexibility in the number\nof nodes, and leads to very straightforward and readable code. It also means\nthat the tree can be dynamically augmented or pruned with new data, in an\nin-line fashion. This approach generally leads to recursive code: upon\nconstruction, the head node constructs its child nodes, the child nodes\nconstruct their child nodes, and so-on.\n\nThe current package uses a different approach: all node data is stored in\na set of numpy arrays which are pre-allocated. The main advantage of this\napproach is that the whole object can be quickly and easily saved to disk\nand reconstructed from disk. This also allows for an iterative interface\nwhich gives more control over the heap, and leads to speed. There are a\nfew disadvantages, however: once the tree is built, augmenting or pruning it\nis not as straightforward. Also, the size of the tree must be known from the\nstart, so there is not as much flexibility in building it.\n\nBallTree Pseudo-code\n~~~~~~~~~~~~~~~~~~~~\nBecause understanding a ball ""tree is simpler with recursive code, here is some\npseudo-code to show the structure of the main functionality\n\n # Ball Tree pseudo code\n\n class Node:\n #class data:\n centroid\n radius\n child1, child2\n\n #class methods:\n def construct(data):\n centroid = compute_centroid(data)\n radius = compute_radius(centroid, data)\n\n # Divide the data into two approximately equal sets.\n # This is often done by splitting along a single dimension.\n data1, data2 = divide(data)\n\n if number_of_points(data1) > 0:\n child1.construct(data1)\n\n if number_of_points(data2) > 0:\n child2.construct(data2)\n\n def query(pt, neighbors_heap):\n # compute the minimum distance from pt to any point in this node\n d = distance(point, centroid)\n if d < radius:\n min_distance = 0\n else:\n min_distance = d - radius\n\n if min_distance > max_distance_in(neighbors_heap):\n # all these points are too far away. cut off the search here\n return\n elif node_size > 1:\n child1.query(pt, neighbors_heap)\n child2.query(pt, neighbors_heap)\n\n\n object BallTree:\n #class data:\n data\n root_node\n\n #class methods\n def construct(data, num_leaves):\n root_node.construct(data)\n\n def query(point, num_neighbors):\n neighbors_heap = empty_heap_of_size(num_neighbors)\n root_node.query(point, neighbors_heap)\n\nThis certainly is not a complete description, but should give the basic idea\nof the form of the algorithm. The implementation below is much faster than\nanything mirroring the pseudo-code above, but for that reason is much more\nopaque. Here's the basic idea:\n\nBallTree Storage\n~~~~~~~~~~~~~~~~""\nThe BallTree information is stored using a combination of\n\"Array of Structures\" and \"Structure of Arrays\" to maximize speed.\nGiven input data of size ``(n_samples, n_features)``, BallTree computes the\nexpected number of nodes ``n_nodes`` (see below), and allocates the\nfollowing arrays:\n\n* ``data`` : a float array of shape ``(n_samples, n_features)``\n This is simply the input data. If the input matrix is well-formed\n (contiguous, c-ordered, correct data type) then no copy is needed\n* ``idx_array`` : an integer array of size ``n_samples``\n This can be thought of as an array of pointers to the data in ``data``.\n Rather than shuffling around the data itself, we shuffle around pointers\n to the rows in data.\n* ``node_centroid_arr`` : a float array of shape ``(n_nodes, n_features)``\n This stores the centroid of the data in each node.\n* ``node_info_arr`` : a size-``n_nodes`` array of ``NodeInfo`` structures.\n This stores information associated with each node. Each ``NodeInfo``\n instance has the following attributes:\n - ``idx_start``\n - ``idx_end`` : ``idx_start`` and ``idx_end`` reference the part of\n ``idx_array`` which point to the data associated with the node.\n The data in node with index ``i_node`` is given by\n ``data[idx_array[idx_start:idx_end]]``\n - ``is_leaf`` : a boolean value which tells whether this node is a leaf:\n that is, whether or not it has children.\n - ``radius`` : a floating-point value which gives the distance from\n the node centroid to the furthest point in the node.\n\nOne feature here is that there are no stored pointers from parent nodes to\nchild nodes and vice-versa. These pointers are implemented implicitly:\nFor a node with index ``i``, the two children are found at indices\n``2 * i + 1`` and ``2 * i + 2``, while the parent is found at index\n``floor((i - 1) / 2)``. The root node has no parent.\n\nWith this data structure in place, the functionality ""of the above BallTree\npseudo-code can be implemented in a much more efficient manner.\nMost of the data passing done in this code uses raw data pointers.\nUsing numpy arrays would be preferable for safety, but the\noverhead of array slicing and sub-array construction leads to execution\ntime which is several orders of magnitude slower than the current\nimplementation.\n\nPriority Queue vs Max-heap\n~~~~~~~~~~~~~~~~~~~~~~~~~~\nWhen querying for more than one neighbor, the code must maintain a list of\nthe current k nearest points. The BallTree code implements this in two ways.\n\n- A priority queue: this is just a sorted list. When an item is added,\n it is inserted in the appropriate location. The cost of the search plus\n insert averages O[k].\n- A max-heap: this is a binary tree structure arranged such that each node is\n greater than its children. The cost of adding an item is O[log(k)].\n At the end of the iterations, the results must be sorted: a quicksort is\n used, which averages O[k log(k)]. Quicksort has worst-case O[k^2]\n performance, but because the input is already structured in a max-heap,\n the worst case will not be realized. Thus the sort is a one-time operation\n with cost O[k log(k)].\n\nEach insert is performed an average of log(N) times per query, where N is\nthe number of training points. Because of this, for a single query, the\npriority-queue approach costs O[k log(N)], and the max-heap approach costs\nO[log(k)log(N)] + O[k log(k)]. Tests show that for sufficiently large k,\nthe max-heap approach out-performs the priority queue approach by a factor\nof a few. In light of these tests, the code uses a priority queue for\nk < 5, and a max-heap otherwise.\n\nMemory Allocation\n~~~~~~~~~~~~~~~~~\nIt is desirable to construct a tree in as balanced a way as possible.\nGiven a training set with n_samples and a user-supplied leaf_size, if\nthe points in each node are divided as evenly as possible between the\ntwo children, the maximu""m depth needed so that leaf nodes satisfy\n``leaf_size <= n_points <= 2 * leaf_size`` is given by\n``n_levels = 1 + max(0, floor(log2((n_samples - 1) / leaf_size)))``\n(with the exception of the special case where ``n_samples < leaf_size``)\nFor a given number of levels, the number of points in a tree is given by\n``n_nodes = 2 ** n_levels - 1``. Both of these results can be shown\nby induction. Using them, the correct amount of memory can be pre-allocated\nfor a given ``n_samples`` and ``leaf_size``.\n"; -static char __pyx_k_55[] = "sklearn.neighbors.ball_tree"; -static char __pyx_k_56[] = "BallTree.query (line 565)"; -static char __pyx_k_57[] = "\n query(X, k=1, return_distance=True)\n\n query the Ball Tree for the k nearest neighbors\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n k : integer (default = 1)\n The number of nearest neighbors to return\n return_distance : boolean (default = True)\n if True, return a tuple (d,i)\n if False, return array i\n\n Returns\n -------\n i : if return_distance == False\n (d,i) : if return_distance == True\n\n d : array of doubles - shape: x.shape[:-1] + (k,)\n each entry gives the list of distances to the\n neighbors of the corresponding point\n (note that distances are not sorted)\n\n i : array of integers - shape: x.shape[:-1] + (k,)\n each entry gives the list of indices of\n neighbors of the corresponding point\n (note that neighbors are not sorted)\n\n Examples\n --------\n Query for k-nearest neighbors\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10,3)) # 10 points in 3 dimensions\n >>> ball_tree = BallTree(X, leaf_size=2) # doctest: +SKIP\n >>> dist, ind = ball_tree.query(X[0], k=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors\n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n "; -static char __pyx_k_58[] = "BallTree.query_radius (line 672)"; -static char __pyx_k_59[] = "\n query_radius(self, X, r, count_only = False):\n\n query the Ball Tree for neighbors within a ball of size r\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n r : distance within which neighbors are returned\n r can be a single value, or an array of values of shape\n x.shape[:-1] if different radii are desired for each point.\n return_distance : boolean (default = False)\n if True, return distances to neighbors of each point\n if False, return only neighbors\n Note that unlike BallTree.query(), setting return_distance=True\n adds to the computation time. Not all distances need to be\n calculated explicitly for return_distance=False. Results are\n not sorted by default: see ``sort_results`` keyword.\n count_only : boolean (default = False)\n if True, return only the count of points within distance r\n if False, return the indices of all points within distance r\n If return_distance==True, setting count_only=True will\n result in an error.\n sort_results : boolean (default = False)\n if True, the distances and indices will be sorted before being\n returned. If False, the results will not be sorted. If\n return_distance == False, setting sort_results = True will\n result in an error.\n\n Returns\n -------\n count : if count_only == True\n ind : if count_only == False and return_distance == False\n (ind, dist) : if count_only == False and return_distance == True\n\n count : array of integers, shape = X.shape[:-1]\n each entry gives the number of neighbors within\n a distance r of the corresponding point.\n\n ind : array of objects, shape = X.shape[:-1]\n each element is a"" numpy integer array listing the indices of\n neighbors of the corresponding point. Note that unlike\n the results of BallTree.query(), the returned neighbors\n are not sorted by distance\n\n dist : array of objects, shape = X.shape[:-1]\n each element is a numpy double array\n listing the distances corresponding to indices in i.\n\n Examples\n --------\n Query for neighbors in a given radius\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10,3)) # 10 points in 3 dimensions\n >>> ball_tree = BallTree(X, leaf_size=2) # doctest: +SKIP\n >>> print ball_tree.query_radius(X[0], r=0.3, count_only=True)\n 3\n >>> ind = ball_tree.query_radius(X[0], r=0.3) # doctest: +SKIP\n >>> print ind # indices of neighbors within distance 0.3\n [3 0 1]\n "; -static char __pyx_k__B[] = "B"; -static char __pyx_k__C[] = "C"; -static char __pyx_k__H[] = "H"; -static char __pyx_k__I[] = "I"; -static char __pyx_k__L[] = "L"; -static char __pyx_k__O[] = "O"; -static char __pyx_k__Q[] = "Q"; -static char __pyx_k__X[] = "X"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__c[] = "c"; -static char __pyx_k__d[] = "d"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__g[] = "g"; -static char __pyx_k__h[] = "h"; -static char __pyx_k__i[] = "i"; -static char __pyx_k__k[] = "k"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__p[] = "p"; -static char __pyx_k__q[] = "q"; -static char __pyx_k__r[] = "r"; -static char __pyx_k__Zd[] = "Zd"; -static char __pyx_k__Zf[] = "Zf"; -static char __pyx_k__Zg[] = "Zg"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__inf[] = "inf"; -static char __pyx_k__copy[] = "copy"; -static char __pyx_k__fill[] = "fill"; -static char __pyx_k__log2[] = "log2"; -static char __pyx_k__ones[] = "ones"; -static char __pyx_k__size[] = "size"; -static char __pyx_k__DTYPE[] = "DTYPE"; -static char __pyx_k__ITYPE[] = "ITYPE"; -static char __pyx_k__dtype[] = "dtype"; -static char __pyx_k__empty[] = "empty"; -static char __pyx_k__int32[] = "int32"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__order[] = "order"; -static char __pyx_k__range[] = "range"; -static char __pyx_k__shape[] = "shape"; -static char __pyx_k__utils[] = "utils"; -static char __pyx_k__zeros[] = "zeros"; -static char __pyx_k__arange[] = "arange"; -static char __pyx_k__double[] = "double"; -static char __pyx_k__newObj[] = "newObj"; -static char __pyx_k__object[] = "object"; -static char __pyx_k____new__[] = "__new__"; -static char __pyx_k__array2d[] = "array2d"; -static char __pyx_k__asarray[] = "asarray"; -static char __pyx_k__float64[] = "float64"; -static char __pyx_k__reshape[] = "reshape"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__enumerate[] = "enumerate"; -static char __pyx_k__leaf_size[] = "leaf_size"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__atleast_1d[] = "atleast_1d"; -static char __pyx_k__count_only[] = "count_only"; -static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k____getstate__[] = "__getstate__"; -static char __pyx_k__sort_results[] = "sort_results"; -static char __pyx_k__return_distance[] = "return_distance"; -static PyObject *__pyx_kp_s_1; -static PyObject *__pyx_kp_s_11; -static PyObject *__pyx_kp_s_13; -static PyObject *__pyx_kp_s_15; -static PyObject *__pyx_kp_s_17; -static PyObject *__pyx_kp_s_20; -static PyObject *__pyx_kp_s_22; -static PyObject *__pyx_kp_s_29; -static PyObject *__pyx_kp_s_3; -static PyObject *__pyx_kp_s_31; -static PyObject *__pyx_kp_s_35; -static PyObject *__pyx_kp_s_38; -static PyObject *__pyx_kp_s_40; -static PyObject *__pyx_kp_u_42; -static PyObject *__pyx_kp_u_44; -static PyObject *__pyx_kp_u_46; -static PyObject *__pyx_kp_u_48; -static PyObject *__pyx_kp_u_49; -static PyObject *__pyx_kp_u_52; -static PyObject *__pyx_n_s_55; -static PyObject *__pyx_kp_u_56; -static PyObject *__pyx_kp_u_57; -static PyObject *__pyx_kp_u_58; -static PyObject *__pyx_kp_u_59; -static PyObject *__pyx_n_s__C; -static PyObject *__pyx_n_s__DTYPE; -static PyObject *__pyx_n_s__ITYPE; -static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s__X; -static PyObject *__pyx_n_s____getstate__; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____new__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__arange; -static PyObject *__pyx_n_s__array2d; -static PyObject *__pyx_n_s__asarray; -static PyObject *__pyx_n_s__atleast_1d; -static PyObject *__pyx_n_s__c; -static PyObject *__pyx_n_s__copy; -static PyObject *__pyx_n_s__count_only; -static PyObject *__pyx_n_s__double; -static PyObject *__pyx_n_s__dtype; -static PyObject *__pyx_n_s__empty; -static PyObject *__pyx_n_s__enumerate; -static PyObject *__pyx_n_s__fill; -static PyObject *__pyx_n_s__float64; -static PyObject *__pyx_n_s__inf; -static PyObject *__pyx_n_s__int32; -static PyObject *__pyx_n_s__k; -static PyObject *__pyx_n_s__leaf_size; -static PyObject *__pyx_n_s__log2; -static PyObject *__pyx_n_s__newObj; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__object; -static PyObject *__pyx_n_s__ones; -static PyObject *__pyx_n_s__order; -static PyObject *__pyx_n_s__p; -static PyObject *__pyx_n_s__r; -static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__reshape; -static PyObject *__pyx_n_s__return_distance; -static PyObject *__pyx_n_s__shape; -static PyObject *__pyx_n_s__size; -static PyObject *__pyx_n_s__sort_results; -static PyObject *__pyx_n_s__utils; -static PyObject *__pyx_n_s__zeros; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_Ellipsis; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_xrange; +static PyObject *__pyx_builtin_id; +static PyObject *__pyx_builtin_IndexError; +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_kernel_norm(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_h, PyObject *__pyx_v_d, PyObject *__pyx_v_kernel, PyObject *__pyx_v_return_log); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap___cinit__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_2__init__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_self, PyObject *__pyx_v_n_pts, PyObject *__pyx_v_n_nbrs); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_4get_arrays(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_self, PyObject *__pyx_v_sort); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_6push(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_val, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_val); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_8NodeHeap___cinit__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_8NodeHeap_2__init__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_self, PyObject *__pyx_v_size_guess); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_2newObj(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_obj); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree___cinit__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_2__init__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_data, PyObject *__pyx_v_leaf_size, PyObject *__pyx_v_metric, PyObject *__pyx_v_kwargs); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_4__reduce__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_6__getstate__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_8__setstate__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_state); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_10get_tree_stats(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_12reset_n_calls(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_14get_n_calls(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_16get_arrays(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_18query(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_k, PyObject *__pyx_v_return_distance, PyObject *__pyx_v_dualtree, PyObject *__pyx_v_breadth_first, PyObject *__pyx_v_sort_results); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_20query_radius(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_r, PyObject *__pyx_v_return_distance, int __pyx_v_count_only, int __pyx_v_sort_results); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_22kernel_density(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_h, PyObject *__pyx_v_kernel, PyObject *__pyx_v_atol, PyObject *__pyx_v_rtol, PyObject *__pyx_v_breadth_first, PyObject *__pyx_v_return_log); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_24two_point_correlation(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_r, PyObject *__pyx_v_dualtree); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_4data___get__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array___get__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array_2__set__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data___get__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data_2__set__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds___get__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds_2__set__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_4load_heap(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_k); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_6simultaneous_sort(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_distances, __Pyx_memviewslice __pyx_v_indices); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8nodeheap_sort(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_vals); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_9ball_tree_NeighborsHeap(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_9ball_tree_NodeHeap(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_9ball_tree_BinaryTree(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_9ball_tree_BallTree(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_B[] = "B"; +static char __pyx_k_C[] = "C"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_T[] = "T{"; + static char __pyx_k_X[] = "X"; + static char __pyx_k_b[] = "b"; + static char __pyx_k_c[] = "c"; + static char __pyx_k_d[] = "d"; + static char __pyx_k_f[] = "f"; + static char __pyx_k_g[] = "g"; + static char __pyx_k_h[] = "h"; + static char __pyx_k_i[] = "i"; + static char __pyx_k_j[] = "j"; + static char __pyx_k_k[] = "k"; + static char __pyx_k_l[] = "l"; + static char __pyx_k_q[] = "q"; + static char __pyx_k_r[] = "r"; + static char __pyx_k_s[] = "(%s)"; + static char __pyx_k_Zd[] = "Zd"; + static char __pyx_k_Zf[] = "Zf"; + static char __pyx_k_Zg[] = "Zg"; + static char __pyx_k_i1[] = "i1"; + static char __pyx_k_i2[] = "i2"; + static char __pyx_k_id[] = "id"; + static char __pyx_k_np[] = "np"; + static char __pyx_k_pi[] = "pi"; + static char __pyx_k__50[] = "^"; + static char __pyx_k__51[] = ""; + static char __pyx_k__52[] = ":"; +static char __pyx_k__53[] = "}"; +static char __pyx_k__54[] = ","; +static char __pyx_k_all[] = "__all__"; +static char __pyx_k_doc[] = "__doc__"; +static char __pyx_k_exp[] = "exp"; +static char __pyx_k_inf[] = "inf"; +static char __pyx_k_new[] = "__new__"; +static char __pyx_k_obj[] = "obj"; +static char __pyx_k_row[] = "row"; +static char __pyx_k_val[] = "val"; +static char __pyx_k_atol[] = "atol"; +static char __pyx_k_base[] = "base"; +static char __pyx_k_copy[] = "copy"; +static char __pyx_k_data[] = "data"; +static char __pyx_k_heap[] = "heap"; +static char __pyx_k_join[] = "join"; +static char __pyx_k_log2[] = "log2"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_mode[] = "mode"; +static char __pyx_k_name[] = "__name__"; +static char __pyx_k_ndim[] = "ndim"; +static char __pyx_k_pack[] = "pack"; +static char __pyx_k_push[] = "push"; +static char __pyx_k_rtol[] = "rtol"; +static char __pyx_k_size[] = "size"; +static char __pyx_k_sort[] = "sort"; +static char __pyx_k_step[] = "step"; +static char __pyx_k_stop[] = "stop"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_vals[] = "vals"; +static char __pyx_k_warn[] = "warn"; +static char __pyx_k_DTYPE[] = "DTYPE"; +static char __pyx_k_ITYPE[] = "ITYPE"; +static char __pyx_k_class[] = "__class__"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_empty[] = "empty"; +static char __pyx_k_error[] = "error"; +static char __pyx_k_flags[] = "flags"; +static char __pyx_k_i_val[] = "i_val"; +static char __pyx_k_n_pts[] = "n_pts"; +static char __pyx_k_names[] = "names"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_order[] = "order"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_shape[] = "shape"; +static char __pyx_k_start[] = "start"; +static char __pyx_k_utils[] = "utils"; +static char __pyx_k_zeros[] = "zeros"; +static char __pyx_k_arange[] = "arange"; +static char __pyx_k_cosine[] = "cosine"; +static char __pyx_k_format[] = "format"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_kernel[] = "kernel"; +static char __pyx_k_linear[] = "linear"; +static char __pyx_k_metric[] = "metric"; +static char __pyx_k_n_nbrs[] = "n_nbrs"; +static char __pyx_k_name_2[] = "name"; +static char __pyx_k_newObj[] = "newObj"; +static char __pyx_k_object[] = "object"; +static char __pyx_k_radius[] = "radius"; +static char __pyx_k_result[] = "result"; +static char __pyx_k_struct[] = "struct"; +static char __pyx_k_tophat[] = "tophat"; +static char __pyx_k_unpack[] = "unpack"; +static char __pyx_k_xrange[] = "xrange"; +static char __pyx_k_argsort[] = "argsort"; +static char __pyx_k_asarray[] = "asarray"; +static char __pyx_k_formats[] = "formats"; +static char __pyx_k_fortran[] = "fortran"; +static char __pyx_k_idx_end[] = "idx_end"; +static char __pyx_k_indices[] = "indices"; +static char __pyx_k_is_leaf[] = "is_leaf"; +static char __pyx_k_memview[] = "memview"; +static char __pyx_k_offsets[] = "offsets"; +static char __pyx_k_reshape[] = "reshape"; +static char __pyx_k_BallTree[] = "BallTree"; +static char __pyx_k_DOC_DICT[] = "DOC_DICT"; +static char __pyx_k_Ellipsis[] = "Ellipsis"; +static char __pyx_k_NodeData[] = "NodeData"; +static char __pyx_k_dualtree[] = "dualtree"; +static char __pyx_k_gaussian[] = "gaussian"; +static char __pyx_k_getstate[] = "__getstate__"; +static char __pyx_k_itemsize[] = "itemsize"; +static char __pyx_k_typedefs[] = "typedefs"; +static char __pyx_k_warnings[] = "warnings"; +static char __pyx_k_CLASS_DOC[] = "CLASS_DOC"; +static char __pyx_k_TypeError[] = "TypeError"; +static char __pyx_k_ball_tree[] = "ball_tree"; +static char __pyx_k_distances[] = "distances"; +static char __pyx_k_enumerate[] = "enumerate"; +static char __pyx_k_idx_start[] = "idx_start"; +static char __pyx_k_leaf_size[] = "leaf_size"; +static char __pyx_k_load_heap[] = "load_heap"; +static char __pyx_k_minkowski[] = "minkowski"; +static char __pyx_k_node_data[] = "node_data"; +static char __pyx_k_BinaryTree[] = "BinaryTree"; +static char __pyx_k_IndexError[] = "IndexError"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_atleast_1d[] = "atleast_1d"; +static char __pyx_k_count_only[] = "count_only"; +static char __pyx_k_get_arrays[] = "get_arrays"; +static char __pyx_k_get_metric[] = "get_metric"; +static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static char __pyx_k_return_log[] = "return_log"; +static char __pyx_k_size_guess[] = "size_guess"; +static char __pyx_k_zeros_like[] = "zeros_like"; +static char __pyx_k_MemoryError[] = "MemoryError"; +static char __pyx_k_binary_tree[] = "binary_tree"; +static char __pyx_k_check_array[] = "check_array"; +static char __pyx_k_exponential[] = "exponential"; +static char __pyx_k_kernel_norm[] = "kernel_norm"; +static char __pyx_k_vals_sorted[] = "vals_sorted"; +static char __pyx_k_DiceDistance[] = "DiceDistance"; +static char __pyx_k_NodeHeapData[] = "NodeHeapData"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_dist_metrics[] = "dist_metrics"; +static char __pyx_k_epanechnikov[] = "epanechnikov"; +static char __pyx_k_sort_results[] = "sort_results"; +static char __pyx_k_VALID_METRICS[] = "VALID_METRICS"; +static char __pyx_k_breadth_first[] = "breadth_first"; +static char __pyx_k_nodeheap_sort[] = "nodeheap_sort"; +static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k_rdist_to_dist[] = "rdist_to_dist"; +static char __pyx_k_valid_metrics[] = "valid_metrics"; +static char __pyx_k_PyFuncDistance[] = "PyFuncDistance"; +static char __pyx_k_HammingDistance[] = "HammingDistance"; +static char __pyx_k_JaccardDistance[] = "JaccardDistance"; +static char __pyx_k_allocate_buffer[] = "allocate_buffer"; +static char __pyx_k_dtype_is_object[] = "dtype_is_object"; +static char __pyx_k_return_distance[] = "return_distance"; +static char __pyx_k_CanberraDistance[] = "CanberraDistance"; +static char __pyx_k_MatchingDistance[] = "MatchingDistance"; +static char __pyx_k_VALID_METRIC_IDS[] = "VALID_METRIC_IDS"; +static char __pyx_k_ChebyshevDistance[] = "ChebyshevDistance"; +static char __pyx_k_EuclideanDistance[] = "EuclideanDistance"; +static char __pyx_k_HaversineDistance[] = "HaversineDistance"; +static char __pyx_k_KulsinskiDistance[] = "KulsinskiDistance"; +static char __pyx_k_ManhattanDistance[] = "ManhattanDistance"; +static char __pyx_k_MinkowskiDistance[] = "MinkowskiDistance"; +static char __pyx_k_pyx_releasebuffer[] = "__pyx_releasebuffer"; +static char __pyx_k_simultaneous_sort[] = "simultaneous_sort"; +static char __pyx_k_BrayCurtisDistance[] = "BrayCurtisDistance"; +static char __pyx_k_RussellRaoDistance[] = "RussellRaoDistance"; +static char __pyx_k_SEuclideanDistance[] = "SEuclideanDistance"; +static char __pyx_k_WMinkowskiDistance[] = "WMinkowskiDistance"; +static char __pyx_k_strided_and_direct[] = ""; +static char __pyx_k_MahalanobisDistance[] = "MahalanobisDistance"; +static char __pyx_k_SokalSneathDistance[] = "SokalSneathDistance"; +static char __pyx_k_X_is_an_empty_array[] = "X is an empty array"; +static char __pyx_k_get_valid_metric_ids[] = "get_valid_metric_ids"; +static char __pyx_k_strided_and_indirect[] = ""; +static char __pyx_k_SokalMichenerDistance[] = "SokalMichenerDistance"; +static char __pyx_k_contiguous_and_direct[] = ""; +static char __pyx_k_kernel_not_recognized[] = "kernel not recognized"; +static char __pyx_k_MemoryView_of_r_object[] = ""; +static char __pyx_k_RogersTanimotoDistance[] = "RogersTanimotoDistance"; +static char __pyx_k_MemoryView_of_r_at_0x_x[] = ""; +static char __pyx_k_contiguous_and_indirect[] = ""; +static char __pyx_k_kernel_s_not_recognized[] = "kernel = '%s' not recognized"; +static char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; +static char __pyx_k_cannot_pop_on_empty_heap[] = "cannot pop on empty heap"; +static char __pyx_k_getbuffer_obj_view_flags[] = "getbuffer(obj, view, flags)"; +static char __pyx_k_Dimension_d_is_not_direct[] = "Dimension %d is not direct"; +static char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; +static char __pyx_k_BinaryTree_query_line_1228[] = "BinaryTree.query (line 1228)"; +static char __pyx_k_Index_out_of_bounds_axis_d[] = "Index out of bounds (axis %d)"; +static char __pyx_k_Kernel_code_not_recognized[] = "Kernel code not recognized"; +static char __pyx_k_Step_may_not_be_zero_axis_d[] = "Step may not be zero (axis %d)"; +static char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_sklearn_neighbors_ball_tree[] = "sklearn.neighbors.ball_tree"; +static char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; +static char __pyx_k_kernel_density_self_X_h_kernel[] = "\n kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1E-8,\n breadth_first=True, return_log=False)\n\n Compute the kernel density estimate at points X with the given kernel,\n using the distance metric specified at tree creation.\n\n Parameters\n ----------\n X : array_like\n An array of points to query. Last dimension should match dimension\n of training data.\n h : float\n the bandwidth of the kernel\n kernel : string\n specify the kernel to use. Options are\n - 'gaussian'\n - 'tophat'\n - 'epanechnikov'\n - 'exponential'\n - 'linear'\n - 'cosine'\n Default is kernel = 'gaussian'\n atol, rtol : float (default = 0)\n Specify the desired relative and absolute tolerance of the result.\n If the true result is K_true, then the returned result K_ret\n satisfies ``abs(K_true - K_ret) < atol + rtol * K_ret``\n The default is zero (i.e. machine precision) for both.\n breadth_first : boolean (default = False)\n if True, use a breadth-first search. If False (default) use a\n depth-first search. Breadth-first is generally faster for\n compact kernels and/or high tolerances.\n return_log : boolean (default = False)\n return the logarithm of the result. This can be more accurate\n than returning the result itself for narrow kernels.\n\n Returns\n -------\n density : ndarray\n The array of (log)-density evaluations, shape = X.shape[:-1]\n\n Examples\n --------\n Compute a gaussian kernel density estimate:\n\n >>> import numpy as np\n >>> np.random.seed(1)\n >>> X = np.random.random((100, 3))\n >>> tree = BinaryTree(X) # doctest: +SKIP\n >>> tree.kernel_den""sity(X[:3], h=0.1, kernel='gaussian')\n array([ 6.94114649, 7.83281226, 7.2071716 ])\n "; +static char __pyx_k_strided_and_direct_or_indirect[] = ""; +static char __pyx_k_BinaryTree_for_fast_generalized[] = "{BinaryTree} for fast generalized N-point problems\n\n{BinaryTree}(X, leaf_size=40, metric='minkowski', **kwargs)\n\nParameters\n----------\nX : array-like, shape = [n_samples, n_features]\n n_samples is the number of points in the data set, and\n n_features is the dimension of the parameter space.\n Note: if X is a C-contiguous array of doubles then data will\n not be copied. Otherwise, an internal copy will be made.\n\nleaf_size : positive integer (default = 20)\n Number of points at which to switch to brute-force. Changing\n leaf_size will not affect the results of a query, but can\n significantly impact the speed of a query and the memory required\n to store the constructed tree. The amount of memory needed to\n store the tree scales as approximately n_samples / leaf_size.\n For a specified ``leaf_size``, a leaf node is guaranteed to\n satisfy ``leaf_size <= n_points <= 2 * leaf_size``, except in\n the case that ``n_samples < leaf_size``.\n\nmetric : string or DistanceMetric object\n the distance metric to use for the tree. Default='minkowski'\n with p=2 (that is, a euclidean metric). See the documentation\n of the DistanceMetric class for a list of available metrics.\n {binary_tree}.valid_metrics gives a list of the metrics which\n are valid for {BinaryTree}.\n\nAdditional keywords are passed to the distance metric class.\n\nAttributes\n----------\ndata : np.ndarray\n The training data\n\nExamples\n--------\nQuery for k-nearest neighbors\n\n >>> import numpy as np\n\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions\n >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP\n >>> dist, ind = tree.query(X[0], k=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors\n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n\nPickle and Unpickle a tree. Not""e that the state of the tree is saved in the\npickle operation: the tree needs not be rebuilt upon unpickling.\n\n >>> import numpy as np\n >>> import pickle\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions\n >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP\n >>> s = pickle.dumps(tree) # doctest: +SKIP\n >>> tree_copy = pickle.loads(s) # doctest: +SKIP\n >>> dist, ind = tree_copy.query(X[0], k=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors\n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n\nQuery for neighbors within a given radius\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions\n >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP\n >>> print tree.query_radius(X[0], r=0.3, count_only=True)\n 3\n >>> ind = tree.query_radius(X[0], r=0.3) # doctest: +SKIP\n >>> print ind # indices of neighbors within distance 0.3\n [3 0 1]\n\n\nCompute a gaussian kernel density estimate:\n\n >>> import numpy as np\n >>> np.random.seed(1)\n >>> X = np.random.random((100, 3))\n >>> tree = {BinaryTree}(X) # doctest: +SKIP\n >>> tree.kernel_density(X[:3], h=0.1, kernel='gaussian')\n array([ 6.94114649, 7.83281226, 7.2071716 ])\n\nCompute a two-point auto-correlation function\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((30, 3))\n >>> r = np.linspace(0, 1, 5)\n >>> tree = {BinaryTree}(X) # doctest: +SKIP\n >>> tree.two_point_correlation(X, r)\n array([ 30, 62, 278, 580, 820])\n\n"; +static char __pyx_k_Fatal_count_too_big_this_should[] = "Fatal: count too big: this should never happen"; +static char __pyx_k_home_manoj_scikit_learn_sklearn[] = "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi"; +static char __pyx_k_k_must_be_less_than_or_equal_to[] = "k must be less than or equal to the number of training points"; +static char __pyx_k_query_X_k_1_return_distance_Tru[] = "\n query(X, k=1, return_distance=True,\n dualtree=False, breadth_first=False)\n\n query the tree for the k nearest neighbors\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n k : integer (default = 1)\n The number of nearest neighbors to return\n return_distance : boolean (default = True)\n if True, return a tuple (d, i) of distances and indices\n if False, return array i\n dualtree : boolean (default = False)\n if True, use the dual tree formalism for the query: a tree is\n built for the query points, and the pair of trees is used to\n efficiently search this space. This can lead to better\n performance as the number of points grows large.\n breadth_first : boolean (default = False)\n if True, then query the nodes in a breadth-first manner.\n Otherwise, query the nodes in a depth-first manner.\n sort_results : boolean (default = True)\n if True, then distances and indices of each point are sorted\n on return, so that the first column contains the closest points.\n Otherwise, neighbors are returned in an arbitrary order.\n\n Returns\n -------\n i : if return_distance == False\n (d,i) : if return_distance == True\n\n d : array of doubles - shape: x.shape[:-1] + (k,)\n each entry gives the list of distances to the\n neighbors of the corresponding point\n\n i : array of integers - shape: x.shape[:-1] + (k,)\n each entry gives the list of indices of\n neighbors of the corresponding point\n\n Examples\n --------\n Query for k-nearest neighbors\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimension""s\n >>> tree = BinaryTree(X, leaf_size=2) # doctest: +SKIP\n >>> dist, ind = tree.query(X[0], k=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors\n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n "; +static char __pyx_k_query_data_dimension_must_match[] = "query data dimension must match training data dimension"; +static char __pyx_k_query_radius_self_X_r_count_onl[] = "\n query_radius(self, X, r, count_only = False):\n\n query the tree for neighbors within a radius r\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n r : distance within which neighbors are returned\n r can be a single value, or an array of values of shape\n x.shape[:-1] if different radii are desired for each point.\n return_distance : boolean (default = False)\n if True, return distances to neighbors of each point\n if False, return only neighbors\n Note that unlike the query() method, setting return_distance=True\n here adds to the computation time. Not all distances need to be\n calculated explicitly for return_distance=False. Results are\n not sorted by default: see ``sort_results`` keyword.\n count_only : boolean (default = False)\n if True, return only the count of points within distance r\n if False, return the indices of all points within distance r\n If return_distance==True, setting count_only=True will\n result in an error.\n sort_results : boolean (default = False)\n if True, the distances and indices will be sorted before being\n returned. If False, the results will not be sorted. If\n return_distance == False, setting sort_results = True will\n result in an error.\n\n Returns\n -------\n count : if count_only == True\n ind : if count_only == False and return_distance == False\n (ind, dist) : if count_only == False and return_distance == True\n\n count : array of integers, shape = X.shape[:-1]\n each entry gives the number of neighbors within\n a distance r of the corresponding point.\n\n ind : array of objects, shape = X.shape[:-1]\n each element is a num""py integer array listing the indices of\n neighbors of the corresponding point. Note that unlike\n the results of a k-neighbors query, the returned neighbors\n are not sorted by distance by default.\n\n dist : array of objects, shape = X.shape[:-1]\n each element is a numpy double array\n listing the distances corresponding to indices in i.\n\n Examples\n --------\n Query for neighbors in a given radius\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions\n >>> tree = BinaryTree(X, leaf_size=2) # doctest: +SKIP\n >>> print tree.query_radius(X[0], r=0.3, count_only=True)\n 3\n >>> ind = tree.query_radius(X[0], r=0.3) # doctest: +SKIP\n >>> print ind # indices of neighbors within distance 0.3\n [3 0 1]\n "; +static char __pyx_k_r_must_be_a_1_dimensional_array[] = "r must be a 1-dimensional array"; +static char __pyx_k_return_distance_must_be_True_if[] = "return_distance must be True if sort_results is True"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_All_dimensions_preceding_dimensi[] = "All dimensions preceding dimension %d must be indexed and not sliced"; +static char __pyx_k_BinaryTree_kernel_density_line_1[] = "BinaryTree.kernel_density (line 1499)"; +static char __pyx_k_BinaryTree_query_radius_line_135[] = "BinaryTree.query_radius (line 1353)"; +static char __pyx_k_BinaryTree_two_point_correlation[] = "BinaryTree.two_point_correlation (line 1650)"; +static char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; +static char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; +static char __pyx_k_Cannot_transpose_memoryview_with[] = "Cannot transpose memoryview with indirect dimensions"; +static char __pyx_k_Compute_the_two_point_correlatio[] = "Compute the two-point correlation function\n\n Parameters\n ----------\n X : array_like\n An array of points to query. Last dimension should match dimension\n of training data.\n r : array_like\n A one-dimensional array of distances\n dualtree : boolean (default = False)\n If true, use a dualtree algorithm. Otherwise, use a single-tree\n algorithm. Dual tree algorithms can have better scaling for\n large N.\n\n Returns\n -------\n counts : ndarray\n counts[i] contains the number of pairs of points with distance\n less than or equal to r[i]\n\n Examples\n --------\n Compute the two-point autocorrelation function of X:\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((30, 3))\n >>> r = np.linspace(0, 1, 5)\n >>> tree = BinaryTree(X) # doctest: +SKIP\n >>> tree.two_point_correlation(X, r)\n array([ 30, 62, 278, 580, 820])\n "; +static char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; +static char __pyx_k_Fatal_count_out_of_range_This_sh[] = "Fatal: count out of range. This should never happen."; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; +static char __pyx_k_Internal_memory_layout_is_flawed[] = "Internal: memory layout is flawed: not enough nodes allocated"; +static char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; +static char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; +static char __pyx_k_count_only_and_return_distance_c[] = "count_only and return_distance cannot both be true"; +static char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; +static char __pyx_k_leaf_size_must_be_greater_than_o[] = "leaf_size must be greater than or equal to 1"; +static char __pyx_k_metric_metric_is_not_valid_for_B[] = "metric {metric} is not valid for {BinaryTree}"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_r_must_be_broadcastable_to_X_sha[] = "r must be broadcastable to X.shape"; +static char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static char __pyx_k_Internal_memory_layout_is_flawed_2[] = "Internal: memory layout is flawed: too many nodes allocated"; +static PyObject *__pyx_n_s_BallTree; +static PyObject *__pyx_n_s_BinaryTree; +static PyObject *__pyx_kp_s_BinaryTree_for_fast_generalized; +static PyObject *__pyx_kp_u_BinaryTree_kernel_density_line_1; +static PyObject *__pyx_kp_u_BinaryTree_query_line_1228; +static PyObject *__pyx_kp_u_BinaryTree_query_radius_line_135; +static PyObject *__pyx_kp_u_BinaryTree_two_point_correlation; +static PyObject *__pyx_n_s_BrayCurtisDistance; +static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; +static PyObject *__pyx_n_s_C; +static PyObject *__pyx_n_s_CLASS_DOC; +static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; +static PyObject *__pyx_n_s_CanberraDistance; +static PyObject *__pyx_kp_s_Cannot_index_with_type_s; +static PyObject *__pyx_n_s_ChebyshevDistance; +static PyObject *__pyx_kp_u_Compute_the_two_point_correlatio; +static PyObject *__pyx_n_s_DOC_DICT; +static PyObject *__pyx_n_s_DTYPE; +static PyObject *__pyx_n_s_DiceDistance; +static PyObject *__pyx_n_s_Ellipsis; +static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; +static PyObject *__pyx_n_s_EuclideanDistance; +static PyObject *__pyx_kp_s_Fatal_count_out_of_range_This_sh; +static PyObject *__pyx_kp_s_Fatal_count_too_big_this_should; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_n_s_HammingDistance; +static PyObject *__pyx_n_s_HaversineDistance; +static PyObject *__pyx_n_s_ITYPE; +static PyObject *__pyx_n_s_IndexError; +static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; +static PyObject *__pyx_kp_s_Internal_memory_layout_is_flawed; +static PyObject *__pyx_kp_s_Internal_memory_layout_is_flawed_2; +static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; +static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; +static PyObject *__pyx_n_s_JaccardDistance; +static PyObject *__pyx_kp_s_Kernel_code_not_recognized; +static PyObject *__pyx_n_s_KulsinskiDistance; +static PyObject *__pyx_n_s_MahalanobisDistance; +static PyObject *__pyx_n_s_ManhattanDistance; +static PyObject *__pyx_n_s_MatchingDistance; +static PyObject *__pyx_n_s_MemoryError; +static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; +static PyObject *__pyx_kp_s_MemoryView_of_r_object; +static PyObject *__pyx_n_s_MinkowskiDistance; +static PyObject *__pyx_n_s_NodeData; +static PyObject *__pyx_n_s_NodeHeapData; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_b_O; +static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; +static PyObject *__pyx_n_s_PyFuncDistance; +static PyObject *__pyx_n_s_RogersTanimotoDistance; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_RussellRaoDistance; +static PyObject *__pyx_n_s_SEuclideanDistance; +static PyObject *__pyx_n_s_SokalMichenerDistance; +static PyObject *__pyx_n_s_SokalSneathDistance; +static PyObject *__pyx_kp_b_T; +static PyObject *__pyx_n_s_TypeError; +static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; +static PyObject *__pyx_n_s_VALID_METRICS; +static PyObject *__pyx_n_s_VALID_METRIC_IDS; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_WMinkowskiDistance; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_kp_s_X_is_an_empty_array; +static PyObject *__pyx_kp_b__50; +static PyObject *__pyx_kp_b__51; +static PyObject *__pyx_kp_b__52; +static PyObject *__pyx_kp_b__53; +static PyObject *__pyx_kp_u__54; +static PyObject *__pyx_n_s_all; +static PyObject *__pyx_n_s_allocate_buffer; +static PyObject *__pyx_n_s_arange; +static PyObject *__pyx_n_s_argsort; +static PyObject *__pyx_n_s_asarray; +static PyObject *__pyx_n_s_atleast_1d; +static PyObject *__pyx_n_s_atol; +static PyObject *__pyx_n_s_ball_tree; +static PyObject *__pyx_n_s_base; +static PyObject *__pyx_n_s_binary_tree; +static PyObject *__pyx_n_s_breadth_first; +static PyObject *__pyx_n_s_c; +static PyObject *__pyx_n_u_c; +static PyObject *__pyx_kp_s_cannot_pop_on_empty_heap; +static PyObject *__pyx_n_s_check_array; +static PyObject *__pyx_n_s_class; +static PyObject *__pyx_kp_s_contiguous_and_direct; +static PyObject *__pyx_kp_s_contiguous_and_indirect; +static PyObject *__pyx_n_s_copy; +static PyObject *__pyx_n_s_cosine; +static PyObject *__pyx_n_s_count_only; +static PyObject *__pyx_kp_s_count_only_and_return_distance_c; +static PyObject *__pyx_n_s_d; +static PyObject *__pyx_n_s_data; +static PyObject *__pyx_n_s_dist_metrics; +static PyObject *__pyx_n_s_distances; +static PyObject *__pyx_n_s_doc; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_dtype_is_object; +static PyObject *__pyx_n_s_dualtree; +static PyObject *__pyx_n_s_empty; +static PyObject *__pyx_n_s_enumerate; +static PyObject *__pyx_n_s_epanechnikov; +static PyObject *__pyx_n_s_error; +static PyObject *__pyx_n_s_exp; +static PyObject *__pyx_n_s_exponential; +static PyObject *__pyx_n_s_flags; +static PyObject *__pyx_n_s_format; +static PyObject *__pyx_n_s_formats; +static PyObject *__pyx_n_s_fortran; +static PyObject *__pyx_n_u_fortran; +static PyObject *__pyx_n_s_gaussian; +static PyObject *__pyx_n_s_get_arrays; +static PyObject *__pyx_n_s_get_metric; +static PyObject *__pyx_n_s_get_valid_metric_ids; +static PyObject *__pyx_n_s_getstate; +static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; +static PyObject *__pyx_n_s_h; +static PyObject *__pyx_n_s_heap; +static PyObject *__pyx_kp_s_home_manoj_scikit_learn_sklearn; +static PyObject *__pyx_n_s_i; +static PyObject *__pyx_n_s_i1; +static PyObject *__pyx_n_s_i2; +static PyObject *__pyx_n_s_i_val; +static PyObject *__pyx_n_s_id; +static PyObject *__pyx_n_s_idx_end; +static PyObject *__pyx_n_s_idx_start; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_indices; +static PyObject *__pyx_n_s_inf; +static PyObject *__pyx_n_s_is_leaf; +static PyObject *__pyx_n_s_itemsize; +static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; +static PyObject *__pyx_n_s_j; +static PyObject *__pyx_n_s_join; +static PyObject *__pyx_n_s_k; +static PyObject *__pyx_kp_s_k_must_be_less_than_or_equal_to; +static PyObject *__pyx_n_s_kernel; +static PyObject *__pyx_kp_u_kernel_density_self_X_h_kernel; +static PyObject *__pyx_n_s_kernel_norm; +static PyObject *__pyx_kp_s_kernel_not_recognized; +static PyObject *__pyx_kp_s_kernel_s_not_recognized; +static PyObject *__pyx_n_s_leaf_size; +static PyObject *__pyx_kp_s_leaf_size_must_be_greater_than_o; +static PyObject *__pyx_n_s_linear; +static PyObject *__pyx_n_s_load_heap; +static PyObject *__pyx_n_s_log2; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_memview; +static PyObject *__pyx_n_s_metric; +static PyObject *__pyx_kp_s_metric_metric_is_not_valid_for_B; +static PyObject *__pyx_n_s_minkowski; +static PyObject *__pyx_n_s_mode; +static PyObject *__pyx_n_s_n_nbrs; +static PyObject *__pyx_n_s_n_pts; +static PyObject *__pyx_n_s_name; +static PyObject *__pyx_n_s_name_2; +static PyObject *__pyx_n_s_names; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_ndim; +static PyObject *__pyx_n_s_new; +static PyObject *__pyx_n_s_newObj; +static PyObject *__pyx_n_s_node_data; +static PyObject *__pyx_n_s_nodeheap_sort; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_obj; +static PyObject *__pyx_n_s_object; +static PyObject *__pyx_n_s_offsets; +static PyObject *__pyx_n_s_order; +static PyObject *__pyx_n_s_pack; +static PyObject *__pyx_n_s_pi; +static PyObject *__pyx_n_s_push; +static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_releasebuffer; +static PyObject *__pyx_n_s_pyx_vtable; +static PyObject *__pyx_kp_u_query_X_k_1_return_distance_Tru; +static PyObject *__pyx_kp_s_query_data_dimension_must_match; +static PyObject *__pyx_kp_u_query_radius_self_X_r_count_onl; +static PyObject *__pyx_n_s_r; +static PyObject *__pyx_kp_s_r_must_be_a_1_dimensional_array; +static PyObject *__pyx_kp_s_r_must_be_broadcastable_to_X_sha; +static PyObject *__pyx_n_s_radius; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_rdist_to_dist; +static PyObject *__pyx_n_s_reshape; +static PyObject *__pyx_n_s_result; +static PyObject *__pyx_n_s_return_distance; +static PyObject *__pyx_kp_s_return_distance_must_be_True_if; +static PyObject *__pyx_n_s_return_log; +static PyObject *__pyx_n_s_row; +static PyObject *__pyx_n_s_rtol; +static PyObject *__pyx_kp_u_s; +static PyObject *__pyx_n_s_shape; +static PyObject *__pyx_n_s_simultaneous_sort; +static PyObject *__pyx_n_s_size; +static PyObject *__pyx_n_s_size_guess; +static PyObject *__pyx_n_s_sklearn_neighbors_ball_tree; +static PyObject *__pyx_n_s_sort; +static PyObject *__pyx_n_s_sort_results; +static PyObject *__pyx_n_s_start; +static PyObject *__pyx_n_s_step; +static PyObject *__pyx_n_s_stop; +static PyObject *__pyx_kp_s_strided_and_direct; +static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; +static PyObject *__pyx_kp_s_strided_and_indirect; +static PyObject *__pyx_n_s_struct; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_n_s_tophat; +static PyObject *__pyx_n_s_typedefs; +static PyObject *__pyx_kp_s_unable_to_allocate_array_data; +static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_unpack; +static PyObject *__pyx_n_s_utils; +static PyObject *__pyx_n_s_val; +static PyObject *__pyx_n_s_valid_metrics; +static PyObject *__pyx_n_s_vals; +static PyObject *__pyx_n_s_vals_sorted; +static PyObject *__pyx_n_s_warn; +static PyObject *__pyx_n_s_warnings; +static PyObject *__pyx_n_s_xrange; +static PyObject *__pyx_n_s_zeros; +static PyObject *__pyx_n_s_zeros_like; +static PyObject *__pyx_float_1Eneg_8; static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; -static PyObject *__pyx_int_5; +static PyObject *__pyx_int_40; +static PyObject *__pyx_int_100; static PyObject *__pyx_int_neg_1; -static PyObject *__pyx_int_15; -static PyObject *__pyx_int_neg_9999; -static PyObject *__pyx_k_19; -static PyObject *__pyx_k_26; -static PyObject *__pyx_k_27; -static PyObject *__pyx_k_28; -static PyObject *__pyx_k_tuple_2; -static PyObject *__pyx_k_tuple_4; -static PyObject *__pyx_k_tuple_5; -static PyObject *__pyx_k_tuple_6; -static PyObject *__pyx_k_tuple_7; -static PyObject *__pyx_k_tuple_8; -static PyObject *__pyx_k_tuple_9; -static PyObject *__pyx_k_tuple_10; -static PyObject *__pyx_k_tuple_12; -static PyObject *__pyx_k_tuple_14; -static PyObject *__pyx_k_tuple_16; -static PyObject *__pyx_k_tuple_18; -static PyObject *__pyx_k_tuple_21; -static PyObject *__pyx_k_tuple_23; -static PyObject *__pyx_k_tuple_24; -static PyObject *__pyx_k_tuple_25; -static PyObject *__pyx_k_tuple_30; -static PyObject *__pyx_k_tuple_32; -static PyObject *__pyx_k_tuple_33; -static PyObject *__pyx_k_tuple_34; -static PyObject *__pyx_k_tuple_36; -static PyObject *__pyx_k_tuple_37; -static PyObject *__pyx_k_tuple_39; -static PyObject *__pyx_k_tuple_41; -static PyObject *__pyx_k_tuple_43; -static PyObject *__pyx_k_tuple_45; -static PyObject *__pyx_k_tuple_47; -static PyObject *__pyx_k_tuple_50; -static PyObject *__pyx_k_tuple_51; -static PyObject *__pyx_k_tuple_53; - -/* "sklearn/neighbors/ball_tree.pyx":218 - * # - * @cython.profile(False) - * cdef inline DTYPE_t dmax(DTYPE_t x, DTYPE_t y): # <<<<<<<<<<<<<< - * if x >= y: - * return x - */ - -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dmax(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_x, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_y) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("dmax"); - - /* "sklearn/neighbors/ball_tree.pyx":219 - * @cython.profile(False) - * cdef inline DTYPE_t dmax(DTYPE_t x, DTYPE_t y): - * if x >= y: # <<<<<<<<<<<<<< - * return x - * else: +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__8; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_tuple__10; +static PyObject *__pyx_tuple__11; +static PyObject *__pyx_tuple__12; +static PyObject *__pyx_tuple__13; +static PyObject *__pyx_tuple__14; +static PyObject *__pyx_tuple__15; +static PyObject *__pyx_tuple__16; +static PyObject *__pyx_tuple__17; +static PyObject *__pyx_tuple__18; +static PyObject *__pyx_tuple__19; +static PyObject *__pyx_tuple__20; +static PyObject *__pyx_tuple__21; +static PyObject *__pyx_tuple__22; +static PyObject *__pyx_tuple__23; +static PyObject *__pyx_tuple__24; +static PyObject *__pyx_tuple__25; +static PyObject *__pyx_tuple__26; +static PyObject *__pyx_tuple__27; +static PyObject *__pyx_tuple__28; +static PyObject *__pyx_tuple__29; +static PyObject *__pyx_tuple__30; +static PyObject *__pyx_tuple__31; +static PyObject *__pyx_tuple__32; +static PyObject *__pyx_tuple__33; +static PyObject *__pyx_tuple__34; +static PyObject *__pyx_tuple__35; +static PyObject *__pyx_tuple__36; +static PyObject *__pyx_tuple__37; +static PyObject *__pyx_tuple__38; +static PyObject *__pyx_tuple__39; +static PyObject *__pyx_tuple__40; +static PyObject *__pyx_tuple__41; +static PyObject *__pyx_tuple__42; +static PyObject *__pyx_tuple__43; +static PyObject *__pyx_tuple__44; +static PyObject *__pyx_tuple__45; +static PyObject *__pyx_tuple__46; +static PyObject *__pyx_tuple__47; +static PyObject *__pyx_tuple__48; +static PyObject *__pyx_tuple__49; +static PyObject *__pyx_tuple__55; +static PyObject *__pyx_tuple__57; +static PyObject *__pyx_tuple__59; +static PyObject *__pyx_tuple__61; +static PyObject *__pyx_tuple__63; +static PyObject *__pyx_tuple__65; +static PyObject *__pyx_tuple__66; +static PyObject *__pyx_tuple__67; +static PyObject *__pyx_tuple__68; +static PyObject *__pyx_tuple__69; +static PyObject *__pyx_codeobj__56; +static PyObject *__pyx_codeobj__58; +static PyObject *__pyx_codeobj__60; +static PyObject *__pyx_codeobj__62; +static PyObject *__pyx_codeobj__64; + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":212 + * ###################################################################### + * # Numpy 1.3-1.4 compatibility utilities + * cdef DTYPE_t[::1] get_memview_DTYPE_1D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=1, mode='c'] X): + * return ( X.data) */ - __pyx_t_1 = (__pyx_v_x >= __pyx_v_y); - if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":220 - * cdef inline DTYPE_t dmax(DTYPE_t x, DTYPE_t y): - * if x >= y: - * return x # <<<<<<<<<<<<<< - * else: - * return y - */ - __pyx_r = __pyx_v_x; - goto __pyx_L0; - goto __pyx_L3; +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_1D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_DTYPE_1D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - /*else*/ { + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; - /* "sklearn/neighbors/ball_tree.pyx":222 - * return x - * else: - * return y # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":214 + * cdef DTYPE_t[::1] get_memview_DTYPE_1D( + * np.ndarray[DTYPE_t, ndim=1, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< * * */ - __pyx_r = __pyx_v_y; - goto __pyx_L0; + __pyx_t_1 = ((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L3:; + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "fortran", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; - __pyx_r = 0; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":212 + * ###################################################################### + * # Numpy 1.3-1.4 compatibility utilities + * cdef DTYPE_t[::1] get_memview_DTYPE_1D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=1, mode='c'] X): + * return ( X.data) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.get_memview_DTYPE_1D", __pyx_clineno, __pyx_lineno, __pyx_filename); + + goto __pyx_L2; __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":226 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":217 + * * - * @cython.profile(False) - * cdef inline DTYPE_t dmin(DTYPE_t x, DTYPE_t y): # <<<<<<<<<<<<<< - * if x <= y: - * return x + * cdef DTYPE_t[:, ::1] get_memview_DTYPE_2D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X): + * return ( X.data) */ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dmin(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_x, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_y) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_r; +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_2D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("dmin"); - - /* "sklearn/neighbors/ball_tree.pyx":227 - * @cython.profile(False) - * cdef inline DTYPE_t dmin(DTYPE_t x, DTYPE_t y): - * if x <= y: # <<<<<<<<<<<<<< - * return x - * else: - */ - __pyx_t_1 = (__pyx_v_x <= __pyx_v_y); - if (__pyx_t_1) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_DTYPE_2D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; - /* "sklearn/neighbors/ball_tree.pyx":228 - * cdef inline DTYPE_t dmin(DTYPE_t x, DTYPE_t y): - * if x <= y: - * return x # <<<<<<<<<<<<<< - * else: - * return y + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":219 + * cdef DTYPE_t[:, ::1] get_memview_DTYPE_2D( + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * + * */ - __pyx_r = __pyx_v_x; - goto __pyx_L0; - goto __pyx_L3; + __pyx_t_1 = ((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - /*else*/ { + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0])), ((Py_ssize_t)(__pyx_v_X->dimensions[1]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "c", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":230 - * return x - * else: - * return y # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":217 * * + * cdef DTYPE_t[:, ::1] get_memview_DTYPE_2D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X): + * return ( X.data) */ - __pyx_r = __pyx_v_y; - goto __pyx_L0; - } - __pyx_L3:; - __pyx_r = 0; + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.get_memview_DTYPE_2D", __pyx_clineno, __pyx_lineno, __pyx_filename); + + goto __pyx_L2; __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":234 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":222 + * * - * @cython.profile(False) - * cdef inline DTYPE_t dabs(DTYPE_t x): # <<<<<<<<<<<<<< - * if x >= 0: - * return x + * cdef DTYPE_t[:, :, ::1] get_memview_DTYPE_3D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=3, mode='c'] X): + * return \ */ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dabs(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_x) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_r; +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_3D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("dabs"); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_DTYPE_3D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 3, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_X.diminfo[2].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_X.diminfo[2].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[2]; - /* "sklearn/neighbors/ball_tree.pyx":235 - * @cython.profile(False) - * cdef inline DTYPE_t dabs(DTYPE_t x): - * if x >= 0: # <<<<<<<<<<<<<< - * return x - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":225 + * np.ndarray[DTYPE_t, ndim=3, mode='c'] X): + * return \ + * ( X.data) # <<<<<<<<<<<<<< + * + * */ - __pyx_t_1 = (__pyx_v_x >= 0.0); - if (__pyx_t_1) { + __pyx_t_1 = ((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *)__pyx_v_X->data); - /* "sklearn/neighbors/ball_tree.pyx":236 - * cdef inline DTYPE_t dabs(DTYPE_t x): - * if x >= 0: - * return x # <<<<<<<<<<<<<< - * else: - * return -x + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":224 + * cdef DTYPE_t[:, :, ::1] get_memview_DTYPE_3D( + * np.ndarray[DTYPE_t, ndim=3, mode='c'] X): + * return \ # <<<<<<<<<<<<<< + * ( X.data) + * */ - __pyx_r = __pyx_v_x; - goto __pyx_L0; - goto __pyx_L3; + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - /*else*/ { + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T __PYX_BUILD_PY_SSIZE_T __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0])), ((Py_ssize_t)(__pyx_v_X->dimensions[1])), ((Py_ssize_t)(__pyx_v_X->dimensions[2]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "c", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":238 - * return x - * else: - * return -x # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":222 * * + * cdef DTYPE_t[:, :, ::1] get_memview_DTYPE_3D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=3, mode='c'] X): + * return \ */ - __pyx_r = (-__pyx_v_x); - goto __pyx_L0; - } - __pyx_L3:; - __pyx_r = 0; + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.get_memview_DTYPE_3D", __pyx_clineno, __pyx_lineno, __pyx_filename); + + goto __pyx_L2; __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":251 - * # which convert between these forms. - * @cython.cdivision(True) - * cdef DTYPE_t dist(DTYPE_t *x1, DTYPE_t *x2, ITYPE_t n, DTYPE_t p): # <<<<<<<<<<<<<< - * cdef ITYPE_t i - * cdef DTYPE_t r, d +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":228 + * + * + * cdef ITYPE_t[::1] get_memview_ITYPE_1D( # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1, mode='c'] X): + * return ( X.data) */ -static __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dist(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p) { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_r; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_d; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_r; +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_1D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_RefNannyDeclarations - int __pyx_t_1; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_2; - __Pyx_RefNannySetupContext("dist"); - - /* "sklearn/neighbors/ball_tree.pyx":254 - * cdef ITYPE_t i - * cdef DTYPE_t r, d - * r = 0 # <<<<<<<<<<<<<< - * if p == 2: - * for i from 0 <= i < n: - */ - __pyx_v_r = 0.0; - - /* "sklearn/neighbors/ball_tree.pyx":255 - * cdef DTYPE_t r, d - * r = 0 - * if p == 2: # <<<<<<<<<<<<<< - * for i from 0 <= i < n: - * d = x1[i] - x2[i] - */ - __pyx_t_1 = (__pyx_v_p == 2.0); - if (__pyx_t_1) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_ITYPE_1D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; - /* "sklearn/neighbors/ball_tree.pyx":256 - * r = 0 - * if p == 2: - * for i from 0 <= i < n: # <<<<<<<<<<<<<< - * d = x1[i] - x2[i] - * r += d * d + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":230 + * cdef ITYPE_t[::1] get_memview_ITYPE_1D( + * np.ndarray[ITYPE_t, ndim=1, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * + * */ - __pyx_t_2 = __pyx_v_n; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { + __pyx_t_1 = ((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "fortran", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":257 - * if p == 2: - * for i from 0 <= i < n: - * d = x1[i] - x2[i] # <<<<<<<<<<<<<< - * r += d * d - * r = r ** 0.5 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":228 + * + * + * cdef ITYPE_t[::1] get_memview_ITYPE_1D( # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1, mode='c'] X): + * return ( X.data) */ - __pyx_v_d = ((__pyx_v_x1[__pyx_v_i]) - (__pyx_v_x2[__pyx_v_i])); - /* "sklearn/neighbors/ball_tree.pyx":258 - * for i from 0 <= i < n: - * d = x1[i] - x2[i] - * r += d * d # <<<<<<<<<<<<<< - * r = r ** 0.5 - * elif p == infinity: - */ - __pyx_v_r = (__pyx_v_r + (__pyx_v_d * __pyx_v_d)); - } + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.get_memview_ITYPE_1D", __pyx_clineno, __pyx_lineno, __pyx_filename); - /* "sklearn/neighbors/ball_tree.pyx":259 - * d = x1[i] - x2[i] - * r += d * d - * r = r ** 0.5 # <<<<<<<<<<<<<< - * elif p == infinity: - * for i from 0 <= i < n: - */ - __pyx_v_r = pow(((double)__pyx_v_r), 0.5); - goto __pyx_L3; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":260 - * r += d * d - * r = r ** 0.5 - * elif p == infinity: # <<<<<<<<<<<<<< - * for i from 0 <= i < n: - * r = dmax(r, dabs(x1[i] - x2[i])) +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":233 + * + * + * cdef ITYPE_t[:, ::1] get_memview_ITYPE_2D( # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=2, mode='c'] X): + * return ( X.data) */ - __pyx_t_1 = (__pyx_v_p == __pyx_v_7sklearn_9neighbors_9ball_tree_infinity); - if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":261 - * r = r ** 0.5 - * elif p == infinity: - * for i from 0 <= i < n: # <<<<<<<<<<<<<< - * r = dmax(r, dabs(x1[i] - x2[i])) - * elif p == 1: - */ - __pyx_t_2 = __pyx_v_n; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_2D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_ITYPE_2D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; - /* "sklearn/neighbors/ball_tree.pyx":262 - * elif p == infinity: - * for i from 0 <= i < n: - * r = dmax(r, dabs(x1[i] - x2[i])) # <<<<<<<<<<<<<< - * elif p == 1: - * for i from 0 <= i < n: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":235 + * cdef ITYPE_t[:, ::1] get_memview_ITYPE_2D( + * np.ndarray[ITYPE_t, ndim=2, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * + * */ - __pyx_v_r = __pyx_f_7sklearn_9neighbors_9ball_tree_dmax(__pyx_v_r, __pyx_f_7sklearn_9neighbors_9ball_tree_dabs(((__pyx_v_x1[__pyx_v_i]) - (__pyx_v_x2[__pyx_v_i])))); - } - goto __pyx_L3; + __pyx_t_1 = ((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0])), ((Py_ssize_t)(__pyx_v_X->dimensions[1]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "c", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":263 - * for i from 0 <= i < n: - * r = dmax(r, dabs(x1[i] - x2[i])) - * elif p == 1: # <<<<<<<<<<<<<< - * for i from 0 <= i < n: - * r += dabs(x1[i] - x2[i]) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":233 + * + * + * cdef ITYPE_t[:, ::1] get_memview_ITYPE_2D( # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=2, mode='c'] X): + * return ( X.data) */ - __pyx_t_1 = (__pyx_v_p == 1.0); - if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":264 - * r = dmax(r, dabs(x1[i] - x2[i])) - * elif p == 1: - * for i from 0 <= i < n: # <<<<<<<<<<<<<< - * r += dabs(x1[i] - x2[i]) - * else: - */ - __pyx_t_2 = __pyx_v_n; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.get_memview_ITYPE_2D", __pyx_clineno, __pyx_lineno, __pyx_filename); - /* "sklearn/neighbors/ball_tree.pyx":265 - * elif p == 1: - * for i from 0 <= i < n: - * r += dabs(x1[i] - x2[i]) # <<<<<<<<<<<<<< - * else: - * for i from 0 <= i < n: - */ - __pyx_v_r = (__pyx_v_r + __pyx_f_7sklearn_9neighbors_9ball_tree_dabs(((__pyx_v_x1[__pyx_v_i]) - (__pyx_v_x2[__pyx_v_i])))); - } - goto __pyx_L3; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); } - /*else*/ { - - /* "sklearn/neighbors/ball_tree.pyx":267 - * r += dabs(x1[i] - x2[i]) - * else: - * for i from 0 <= i < n: # <<<<<<<<<<<<<< - * d = dabs(x1[i] - x2[i]) - * r += d ** p - */ - __pyx_t_2 = __pyx_v_n; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":268 - * else: - * for i from 0 <= i < n: - * d = dabs(x1[i] - x2[i]) # <<<<<<<<<<<<<< - * r += d ** p - * r = r ** (1. / p) +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":238 + * + * + * cdef NodeHeapData_t[::1] get_memview_NodeHeapData_1D( # <<<<<<<<<<<<<< + * np.ndarray[NodeHeapData_t, ndim=1, mode='c'] X): + * return ( X.data) */ - __pyx_v_d = __pyx_f_7sklearn_9neighbors_9ball_tree_dabs(((__pyx_v_x1[__pyx_v_i]) - (__pyx_v_x2[__pyx_v_i]))); - /* "sklearn/neighbors/ball_tree.pyx":269 - * for i from 0 <= i < n: - * d = dabs(x1[i] - x2[i]) - * r += d ** p # <<<<<<<<<<<<<< - * r = r ** (1. / p) - * return r - */ - __pyx_v_r = (__pyx_v_r + pow(__pyx_v_d, __pyx_v_p)); - } +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_NodeHeapData_1D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_RefNannyDeclarations + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_NodeHeapData_1D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[2]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; - /* "sklearn/neighbors/ball_tree.pyx":270 - * d = dabs(x1[i] - x2[i]) - * r += d ** p - * r = r ** (1. / p) # <<<<<<<<<<<<<< - * return r + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":240 + * cdef NodeHeapData_t[::1] get_memview_NodeHeapData_1D( + * np.ndarray[NodeHeapData_t, ndim=1, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * * */ - __pyx_v_r = pow(__pyx_v_r, (1. / __pyx_v_p)); + __pyx_t_1 = ((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L3:; + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "fortran", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":271 - * r += d ** p - * r = r ** (1. / p) - * return r # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":238 * * + * cdef NodeHeapData_t[::1] get_memview_NodeHeapData_1D( # <<<<<<<<<<<<<< + * np.ndarray[NodeHeapData_t, ndim=1, mode='c'] X): + * return ( X.data) */ - __pyx_r = __pyx_v_r; - goto __pyx_L0; - __pyx_r = 0; + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.get_memview_NodeHeapData_1D", __pyx_clineno, __pyx_lineno, __pyx_filename); + + goto __pyx_L2; __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":275 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":243 * - * @cython.cdivision(True) - * cdef DTYPE_t dist_p(DTYPE_t *x1, DTYPE_t *x2, ITYPE_t n, DTYPE_t p): # <<<<<<<<<<<<<< - * cdef ITYPE_t i - * cdef DTYPE_t r, d + * + * cdef NodeData_t[::1] get_memview_NodeData_1D( # <<<<<<<<<<<<<< + * np.ndarray[NodeData_t, ndim=1, mode='c'] X): + * return ( X.data) */ -static __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p) { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_r; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_d; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_r; +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_NodeData_1D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_RefNannyDeclarations - int __pyx_t_1; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_2; - __Pyx_RefNannySetupContext("dist_p"); - - /* "sklearn/neighbors/ball_tree.pyx":278 - * cdef ITYPE_t i - * cdef DTYPE_t r, d - * r = 0 # <<<<<<<<<<<<<< - * if p == 2: - * for i from 0 <= i < n: - */ - __pyx_v_r = 0.0; - - /* "sklearn/neighbors/ball_tree.pyx":279 - * cdef DTYPE_t r, d - * r = 0 - * if p == 2: # <<<<<<<<<<<<<< - * for i from 0 <= i < n: - * d = x1[i] - x2[i] - */ - __pyx_t_1 = (__pyx_v_p == 2.0); - if (__pyx_t_1) { - - /* "sklearn/neighbors/ball_tree.pyx":280 - * r = 0 - * if p == 2: - * for i from 0 <= i < n: # <<<<<<<<<<<<<< - * d = x1[i] - x2[i] - * r += d * d - */ - __pyx_t_2 = __pyx_v_n; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { - - /* "sklearn/neighbors/ball_tree.pyx":281 - * if p == 2: - * for i from 0 <= i < n: - * d = x1[i] - x2[i] # <<<<<<<<<<<<<< - * r += d * d - * elif p == infinity: - */ - __pyx_v_d = ((__pyx_v_x1[__pyx_v_i]) - (__pyx_v_x2[__pyx_v_i])); + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_NodeData_1D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[2]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; - /* "sklearn/neighbors/ball_tree.pyx":282 - * for i from 0 <= i < n: - * d = x1[i] - x2[i] - * r += d * d # <<<<<<<<<<<<<< - * elif p == infinity: - * for i from 0 <= i < n: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":245 + * cdef NodeData_t[::1] get_memview_NodeData_1D( + * np.ndarray[NodeData_t, ndim=1, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * + * ###################################################################### */ - __pyx_v_r = (__pyx_v_r + (__pyx_v_d * __pyx_v_d)); - } - goto __pyx_L3; + __pyx_t_1 = ((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "fortran", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":283 - * d = x1[i] - x2[i] - * r += d * d - * elif p == infinity: # <<<<<<<<<<<<<< - * for i from 0 <= i < n: - * r = dmax(r, dabs(x1[i] - x2[i])) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":243 + * + * + * cdef NodeData_t[::1] get_memview_NodeData_1D( # <<<<<<<<<<<<<< + * np.ndarray[NodeData_t, ndim=1, mode='c'] X): + * return ( X.data) */ - __pyx_t_1 = (__pyx_v_p == __pyx_v_7sklearn_9neighbors_9ball_tree_infinity); - if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":284 - * r += d * d - * elif p == infinity: - * for i from 0 <= i < n: # <<<<<<<<<<<<<< - * r = dmax(r, dabs(x1[i] - x2[i])) - * elif p == 1: - */ - __pyx_t_2 = __pyx_v_n; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.get_memview_NodeData_1D", __pyx_clineno, __pyx_lineno, __pyx_filename); - /* "sklearn/neighbors/ball_tree.pyx":285 - * elif p == infinity: - * for i from 0 <= i < n: - * r = dmax(r, dabs(x1[i] - x2[i])) # <<<<<<<<<<<<<< - * elif p == 1: - * for i from 0 <= i < n: - */ - __pyx_v_r = __pyx_f_7sklearn_9neighbors_9ball_tree_dmax(__pyx_v_r, __pyx_f_7sklearn_9neighbors_9ball_tree_dabs(((__pyx_v_x1[__pyx_v_i]) - (__pyx_v_x2[__pyx_v_i])))); - } - goto __pyx_L3; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":286 - * for i from 0 <= i < n: - * r = dmax(r, dabs(x1[i] - x2[i])) - * elif p == 1: # <<<<<<<<<<<<<< - * for i from 0 <= i < n: - * r += dabs(x1[i] - x2[i]) +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":359 + * ###################################################################### + * # Utility functions + * cdef DTYPE_t logaddexp(DTYPE_t x1, DTYPE_t x2): # <<<<<<<<<<<<<< + * """logaddexp(x1, x2) -> log(exp(x1) + exp(x2))""" + * cdef DTYPE_t a = fmax(x1, x2) */ - __pyx_t_1 = (__pyx_v_p == 1.0); - if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":287 - * r = dmax(r, dabs(x1[i] - x2[i])) - * elif p == 1: - * for i from 0 <= i < n: # <<<<<<<<<<<<<< - * r += dabs(x1[i] - x2[i]) +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_x2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_a; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("logaddexp", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":361 + * cdef DTYPE_t logaddexp(DTYPE_t x1, DTYPE_t x2): + * """logaddexp(x1, x2) -> log(exp(x1) + exp(x2))""" + * cdef DTYPE_t a = fmax(x1, x2) # <<<<<<<<<<<<<< + * if a == NEG_INF: + * return NEG_INF + */ + __pyx_v_a = __pyx_f_7sklearn_9neighbors_9ball_tree_fmax(__pyx_v_x1, __pyx_v_x2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":362 + * """logaddexp(x1, x2) -> log(exp(x1) + exp(x2))""" + * cdef DTYPE_t a = fmax(x1, x2) + * if a == NEG_INF: # <<<<<<<<<<<<<< + * return NEG_INF * else: */ - __pyx_t_2 = __pyx_v_n; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { + __pyx_t_1 = ((__pyx_v_a == __pyx_v_7sklearn_9neighbors_9ball_tree_NEG_INF) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":288 - * elif p == 1: - * for i from 0 <= i < n: - * r += dabs(x1[i] - x2[i]) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":363 + * cdef DTYPE_t a = fmax(x1, x2) + * if a == NEG_INF: + * return NEG_INF # <<<<<<<<<<<<<< * else: - * for i from 0 <= i < n: + * return a + log(exp(x1 - a) + exp(x2 - a)) */ - __pyx_v_r = (__pyx_v_r + __pyx_f_7sklearn_9neighbors_9ball_tree_dabs(((__pyx_v_x1[__pyx_v_i]) - (__pyx_v_x2[__pyx_v_i])))); - } - goto __pyx_L3; + __pyx_r = __pyx_v_7sklearn_9neighbors_9ball_tree_NEG_INF; + goto __pyx_L0; } /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":290 - * r += dabs(x1[i] - x2[i]) - * else: - * for i from 0 <= i < n: # <<<<<<<<<<<<<< - * d = dabs(x1[i] - x2[i]) - * r += d ** p - */ - __pyx_t_2 = __pyx_v_n; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { - - /* "sklearn/neighbors/ball_tree.pyx":291 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":365 + * return NEG_INF * else: - * for i from 0 <= i < n: - * d = dabs(x1[i] - x2[i]) # <<<<<<<<<<<<<< - * r += d ** p - * return r - */ - __pyx_v_d = __pyx_f_7sklearn_9neighbors_9ball_tree_dabs(((__pyx_v_x1[__pyx_v_i]) - (__pyx_v_x2[__pyx_v_i]))); - - /* "sklearn/neighbors/ball_tree.pyx":292 - * for i from 0 <= i < n: - * d = dabs(x1[i] - x2[i]) - * r += d ** p # <<<<<<<<<<<<<< - * return r + * return a + log(exp(x1 - a) + exp(x2 - a)) # <<<<<<<<<<<<<< * + * cdef DTYPE_t logsubexp(DTYPE_t x1, DTYPE_t x2): */ - __pyx_v_r = (__pyx_v_r + pow(__pyx_v_d, __pyx_v_p)); - } + __pyx_r = (__pyx_v_a + log((exp((__pyx_v_x1 - __pyx_v_a)) + exp((__pyx_v_x2 - __pyx_v_a))))); + goto __pyx_L0; } - __pyx_L3:; - /* "sklearn/neighbors/ball_tree.pyx":293 - * d = dabs(x1[i] - x2[i]) - * r += d ** p - * return r # <<<<<<<<<<<<<< - * - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":359 + * ###################################################################### + * # Utility functions + * cdef DTYPE_t logaddexp(DTYPE_t x1, DTYPE_t x2): # <<<<<<<<<<<<<< + * """logaddexp(x1, x2) -> log(exp(x1) + exp(x2))""" + * cdef DTYPE_t a = fmax(x1, x2) */ - __pyx_r = __pyx_v_r; - goto __pyx_L0; - __pyx_r = 0; + /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":297 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":367 + * return a + log(exp(x1 - a) + exp(x2 - a)) * - * @cython.cdivision(True) - * cdef DTYPE_t dist_from_dist_p(DTYPE_t r, DTYPE_t p): # <<<<<<<<<<<<<< - * if p == 2: - * return r ** 0.5 + * cdef DTYPE_t logsubexp(DTYPE_t x1, DTYPE_t x2): # <<<<<<<<<<<<<< + * """logsubexp(x1, x2) -> log(exp(x1) - exp(x2))""" + * if x1 <= x2: */ -static __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dist_from_dist_p(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_r, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_r; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_x2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("dist_from_dist_p"); - - /* "sklearn/neighbors/ball_tree.pyx":298 - * @cython.cdivision(True) - * cdef DTYPE_t dist_from_dist_p(DTYPE_t r, DTYPE_t p): - * if p == 2: # <<<<<<<<<<<<<< - * return r ** 0.5 - * elif p == infinity: - */ - __pyx_t_1 = (__pyx_v_p == 2.0); - if (__pyx_t_1) { - - /* "sklearn/neighbors/ball_tree.pyx":299 - * cdef DTYPE_t dist_from_dist_p(DTYPE_t r, DTYPE_t p): - * if p == 2: - * return r ** 0.5 # <<<<<<<<<<<<<< - * elif p == infinity: - * return r - */ - __pyx_r = pow(((double)__pyx_v_r), 0.5); - goto __pyx_L0; - goto __pyx_L3; - } - - /* "sklearn/neighbors/ball_tree.pyx":300 - * if p == 2: - * return r ** 0.5 - * elif p == infinity: # <<<<<<<<<<<<<< - * return r - * elif p == 1: - */ - __pyx_t_1 = (__pyx_v_p == __pyx_v_7sklearn_9neighbors_9ball_tree_infinity); - if (__pyx_t_1) { - - /* "sklearn/neighbors/ball_tree.pyx":301 - * return r ** 0.5 - * elif p == infinity: - * return r # <<<<<<<<<<<<<< - * elif p == 1: - * return r - */ - __pyx_r = __pyx_v_r; - goto __pyx_L0; - goto __pyx_L3; - } + __Pyx_RefNannySetupContext("logsubexp", 0); - /* "sklearn/neighbors/ball_tree.pyx":302 - * elif p == infinity: - * return r - * elif p == 1: # <<<<<<<<<<<<<< - * return r + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":369 + * cdef DTYPE_t logsubexp(DTYPE_t x1, DTYPE_t x2): + * """logsubexp(x1, x2) -> log(exp(x1) - exp(x2))""" + * if x1 <= x2: # <<<<<<<<<<<<<< + * return NEG_INF * else: */ - __pyx_t_1 = (__pyx_v_p == 1.0); + __pyx_t_1 = ((__pyx_v_x1 <= __pyx_v_x2) != 0); if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":303 - * return r - * elif p == 1: - * return r # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":370 + * """logsubexp(x1, x2) -> log(exp(x1) - exp(x2))""" + * if x1 <= x2: + * return NEG_INF # <<<<<<<<<<<<<< * else: - * return r ** (1. / p) + * return x1 + log(1 - exp(x2 - x1)) */ - __pyx_r = __pyx_v_r; + __pyx_r = __pyx_v_7sklearn_9neighbors_9ball_tree_NEG_INF; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":305 - * return r + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":372 + * return NEG_INF * else: - * return r ** (1. / p) # <<<<<<<<<<<<<< + * return x1 + log(1 - exp(x2 - x1)) # <<<<<<<<<<<<<< * * */ - __pyx_r = pow(__pyx_v_r, (1. / __pyx_v_p)); + __pyx_r = (__pyx_v_x1 + log((1.0 - exp((__pyx_v_x2 - __pyx_v_x1))))); goto __pyx_L0; } - __pyx_L3:; - __pyx_r = 0; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":367 + * return a + log(exp(x1 - a) + exp(x2 - a)) + * + * cdef DTYPE_t logsubexp(DTYPE_t x1, DTYPE_t x2): # <<<<<<<<<<<<<< + * """logsubexp(x1, x2) -> log(exp(x1) - exp(x2))""" + * if x1 <= x2: + */ + + /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":309 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":394 * - * @cython.cdivision(True) - * cdef DTYPE_t dist_p_from_dist(DTYPE_t r, DTYPE_t p): # <<<<<<<<<<<<<< - * if p == 2: - * return r ** 2 + * + * cdef inline DTYPE_t log_gaussian_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the gaussian kernel for bandwidth h (unnormalized)""" + * return -0.5 * (dist * dist) / (h * h) */ -static __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p_from_dist(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_r, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_r; +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_gaussian_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("dist_p_from_dist"); + __Pyx_RefNannySetupContext("log_gaussian_kernel", 0); - /* "sklearn/neighbors/ball_tree.pyx":310 - * @cython.cdivision(True) - * cdef DTYPE_t dist_p_from_dist(DTYPE_t r, DTYPE_t p): - * if p == 2: # <<<<<<<<<<<<<< - * return r ** 2 - * elif p == infinity: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":396 + * cdef inline DTYPE_t log_gaussian_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the gaussian kernel for bandwidth h (unnormalized)""" + * return -0.5 * (dist * dist) / (h * h) # <<<<<<<<<<<<<< + * + * */ - __pyx_t_1 = (__pyx_v_p == 2.0); - if (__pyx_t_1) { + __pyx_r = ((-0.5 * (__pyx_v_dist * __pyx_v_dist)) / (__pyx_v_h * __pyx_v_h)); + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":311 - * cdef DTYPE_t dist_p_from_dist(DTYPE_t r, DTYPE_t p): - * if p == 2: - * return r ** 2 # <<<<<<<<<<<<<< - * elif p == infinity: - * return r + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":394 + * + * + * cdef inline DTYPE_t log_gaussian_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the gaussian kernel for bandwidth h (unnormalized)""" + * return -0.5 * (dist * dist) / (h * h) */ - __pyx_r = pow(__pyx_v_r, 2.0); - goto __pyx_L0; - goto __pyx_L3; - } - /* "sklearn/neighbors/ball_tree.pyx":312 - * if p == 2: - * return r ** 2 - * elif p == infinity: # <<<<<<<<<<<<<< - * return r - * elif p == 1: - */ - __pyx_t_1 = (__pyx_v_p == __pyx_v_7sklearn_9neighbors_9ball_tree_infinity); - if (__pyx_t_1) { + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":313 - * return r ** 2 - * elif p == infinity: - * return r # <<<<<<<<<<<<<< - * elif p == 1: - * return r +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":399 + * + * + * cdef inline DTYPE_t log_tophat_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the tophat kernel for bandwidth h (unnormalized)""" + * if dist < h: */ - __pyx_r = __pyx_v_r; - goto __pyx_L0; - goto __pyx_L3; - } - /* "sklearn/neighbors/ball_tree.pyx":314 - * elif p == infinity: - * return r - * elif p == 1: # <<<<<<<<<<<<<< - * return r +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_tophat_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("log_tophat_kernel", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":401 + * cdef inline DTYPE_t log_tophat_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the tophat kernel for bandwidth h (unnormalized)""" + * if dist < h: # <<<<<<<<<<<<<< + * return 0.0 * else: */ - __pyx_t_1 = (__pyx_v_p == 1.0); + __pyx_t_1 = ((__pyx_v_dist < __pyx_v_h) != 0); if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":315 - * return r - * elif p == 1: - * return r # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":402 + * """log of the tophat kernel for bandwidth h (unnormalized)""" + * if dist < h: + * return 0.0 # <<<<<<<<<<<<<< * else: - * return r ** p + * return NEG_INF */ - __pyx_r = __pyx_v_r; + __pyx_r = 0.0; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":317 - * return r + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":404 + * return 0.0 * else: - * return r ** p # <<<<<<<<<<<<<< + * return NEG_INF # <<<<<<<<<<<<<< * * */ - __pyx_r = pow(__pyx_v_r, __pyx_v_p); + __pyx_r = __pyx_v_7sklearn_9neighbors_9ball_tree_NEG_INF; goto __pyx_L0; } - __pyx_L3:; - __pyx_r = 0; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":399 + * + * + * cdef inline DTYPE_t log_tophat_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the tophat kernel for bandwidth h (unnormalized)""" + * if dist < h: + */ + + /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":348 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":407 * - * @cython.profile(False) - * cdef inline void stack_create(stack* self, int size): # <<<<<<<<<<<<<< - * self.size = size - * self.heap = stdlib.malloc(sizeof(stack_item) * size) + * + * cdef inline DTYPE_t log_epanechnikov_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the epanechnikov kernel for bandwidth h (unnormalized)""" + * if dist < h: */ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_stack_create(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *__pyx_v_self, int __pyx_v_size) { +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_epanechnikov_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("stack_create"); + int __pyx_t_1; + __Pyx_RefNannySetupContext("log_epanechnikov_kernel", 0); - /* "sklearn/neighbors/ball_tree.pyx":349 - * @cython.profile(False) - * cdef inline void stack_create(stack* self, int size): - * self.size = size # <<<<<<<<<<<<<< - * self.heap = stdlib.malloc(sizeof(stack_item) * size) - * self.n = 0 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":409 + * cdef inline DTYPE_t log_epanechnikov_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the epanechnikov kernel for bandwidth h (unnormalized)""" + * if dist < h: # <<<<<<<<<<<<<< + * return log(1.0 - (dist * dist) / (h * h)) + * else: */ - __pyx_v_self->size = __pyx_v_size; + __pyx_t_1 = ((__pyx_v_dist < __pyx_v_h) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":350 - * cdef inline void stack_create(stack* self, int size): - * self.size = size - * self.heap = stdlib.malloc(sizeof(stack_item) * size) # <<<<<<<<<<<<<< - * self.n = 0 - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":410 + * """log of the epanechnikov kernel for bandwidth h (unnormalized)""" + * if dist < h: + * return log(1.0 - (dist * dist) / (h * h)) # <<<<<<<<<<<<<< + * else: + * return NEG_INF */ - __pyx_v_self->heap = ((struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item *)malloc(((sizeof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item)) * __pyx_v_size))); + __pyx_r = log((1.0 - ((__pyx_v_dist * __pyx_v_dist) / (__pyx_v_h * __pyx_v_h)))); + goto __pyx_L0; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":351 - * self.size = size - * self.heap = stdlib.malloc(sizeof(stack_item) * size) - * self.n = 0 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":412 + * return log(1.0 - (dist * dist) / (h * h)) + * else: + * return NEG_INF # <<<<<<<<<<<<<< * * */ - __pyx_v_self->n = 0; + __pyx_r = __pyx_v_7sklearn_9neighbors_9ball_tree_NEG_INF; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":407 + * + * + * cdef inline DTYPE_t log_epanechnikov_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the epanechnikov kernel for bandwidth h (unnormalized)""" + * if dist < h: + */ + /* function exit code */ + __pyx_L0:; __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":355 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":415 * - * @cython.profile(False) - * cdef inline void stack_destroy(stack* self): # <<<<<<<<<<<<<< - * stdlib.free(self.heap) * + * cdef inline DTYPE_t log_exponential_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the exponential kernel for bandwidth h (unnormalized)""" + * return -dist / h */ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_stack_destroy(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *__pyx_v_self) { +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_exponential_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("stack_destroy"); + __Pyx_RefNannySetupContext("log_exponential_kernel", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":417 + * cdef inline DTYPE_t log_exponential_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the exponential kernel for bandwidth h (unnormalized)""" + * return -dist / h # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((-__pyx_v_dist) / __pyx_v_h); + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":356 - * @cython.profile(False) - * cdef inline void stack_destroy(stack* self): - * stdlib.free(self.heap) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":415 * * + * cdef inline DTYPE_t log_exponential_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the exponential kernel for bandwidth h (unnormalized)""" + * return -dist / h */ - free(__pyx_v_self->heap); + /* function exit code */ + __pyx_L0:; __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":360 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":420 * - * @cython.profile(False) - * cdef inline void stack_resize(stack* self, int new_size): # <<<<<<<<<<<<<< - * #print "resize", self.n, new_size - * if new_size < self.n: + * + * cdef inline DTYPE_t log_linear_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the linear kernel for bandwidth h (unnormalized)""" + * if dist < h: */ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_stack_resize(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *__pyx_v_self, int __pyx_v_new_size) { +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_linear_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("stack_resize"); + __Pyx_RefNannySetupContext("log_linear_kernel", 0); - /* "sklearn/neighbors/ball_tree.pyx":362 - * cdef inline void stack_resize(stack* self, int new_size): - * #print "resize", self.n, new_size - * if new_size < self.n: # <<<<<<<<<<<<<< - * raise ValueError("new_size smaller than current") - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":422 + * cdef inline DTYPE_t log_linear_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the linear kernel for bandwidth h (unnormalized)""" + * if dist < h: # <<<<<<<<<<<<<< + * return log(1 - dist / h) + * else: */ - __pyx_t_1 = (__pyx_v_new_size < __pyx_v_self->n); + __pyx_t_1 = ((__pyx_v_dist < __pyx_v_h) != 0); if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":363 - * #print "resize", self.n, new_size - * if new_size < self.n: - * raise ValueError("new_size smaller than current") # <<<<<<<<<<<<<< - * - * self.size = new_size + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":423 + * """log of the linear kernel for bandwidth h (unnormalized)""" + * if dist < h: + * return log(1 - dist / h) # <<<<<<<<<<<<<< + * else: + * return NEG_INF */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; + __pyx_r = log((1.0 - (__pyx_v_dist / __pyx_v_h))); + goto __pyx_L0; } - __pyx_L3:; + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":365 - * raise ValueError("new_size smaller than current") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":425 + * return log(1 - dist / h) + * else: + * return NEG_INF # <<<<<<<<<<<<<< + * * - * self.size = new_size # <<<<<<<<<<<<<< - * self.heap = stdlib.realloc( self.heap, - * new_size * sizeof(stack_item)) */ - __pyx_v_self->size = __pyx_v_new_size; + __pyx_r = __pyx_v_7sklearn_9neighbors_9ball_tree_NEG_INF; + goto __pyx_L0; + } - /* "sklearn/neighbors/ball_tree.pyx":366 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":420 * - * self.size = new_size - * self.heap = stdlib.realloc( self.heap, # <<<<<<<<<<<<<< - * new_size * sizeof(stack_item)) * + * cdef inline DTYPE_t log_linear_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the linear kernel for bandwidth h (unnormalized)""" + * if dist < h: */ - __pyx_v_self->heap = ((struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item *)realloc(((void *)__pyx_v_self->heap), (__pyx_v_new_size * (sizeof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item))))); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_WriteUnraisable("sklearn.neighbors.ball_tree.stack_resize", __pyx_clineno, __pyx_lineno, __pyx_filename); + /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":371 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":428 * - * @cython.profile(False) - * cdef inline void stack_push(stack* self, stack_item item): # <<<<<<<<<<<<<< - * if self.n >= self.size: - * stack_resize(self, 2 * self.size + 1) + * + * cdef inline DTYPE_t log_cosine_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the cosine kernel for bandwidth h (unnormalized)""" + * if dist < h: */ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *__pyx_v_self, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item __pyx_v_item) { +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_log_cosine_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("stack_push"); + __Pyx_RefNannySetupContext("log_cosine_kernel", 0); - /* "sklearn/neighbors/ball_tree.pyx":372 - * @cython.profile(False) - * cdef inline void stack_push(stack* self, stack_item item): - * if self.n >= self.size: # <<<<<<<<<<<<<< - * stack_resize(self, 2 * self.size + 1) - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":430 + * cdef inline DTYPE_t log_cosine_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the cosine kernel for bandwidth h (unnormalized)""" + * if dist < h: # <<<<<<<<<<<<<< + * return log(cos(0.5 * PI * dist / h)) + * else: */ - __pyx_t_1 = (__pyx_v_self->n >= __pyx_v_self->size); + __pyx_t_1 = ((__pyx_v_dist < __pyx_v_h) != 0); if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":373 - * cdef inline void stack_push(stack* self, stack_item item): - * if self.n >= self.size: - * stack_resize(self, 2 * self.size + 1) # <<<<<<<<<<<<<< - * - * self.heap[self.n] = item + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":431 + * """log of the cosine kernel for bandwidth h (unnormalized)""" + * if dist < h: + * return log(cos(0.5 * PI * dist / h)) # <<<<<<<<<<<<<< + * else: + * return NEG_INF */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_resize(__pyx_v_self, ((2 * __pyx_v_self->size) + 1)); - goto __pyx_L3; + __pyx_r = log(cos((((0.5 * __pyx_v_7sklearn_9neighbors_9ball_tree_PI) * __pyx_v_dist) / __pyx_v_h))); + goto __pyx_L0; } - __pyx_L3:; + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":375 - * stack_resize(self, 2 * self.size + 1) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":433 + * return log(cos(0.5 * PI * dist / h)) + * else: + * return NEG_INF # <<<<<<<<<<<<<< * - * self.heap[self.n] = item # <<<<<<<<<<<<<< - * self.n += 1 * */ - (__pyx_v_self->heap[__pyx_v_self->n]) = __pyx_v_item; + __pyx_r = __pyx_v_7sklearn_9neighbors_9ball_tree_NEG_INF; + goto __pyx_L0; + } - /* "sklearn/neighbors/ball_tree.pyx":376 - * - * self.heap[self.n] = item - * self.n += 1 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":428 * * + * cdef inline DTYPE_t log_cosine_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the cosine kernel for bandwidth h (unnormalized)""" + * if dist < h: */ - __pyx_v_self->n = (__pyx_v_self->n + 1); + /* function exit code */ + __pyx_L0:; __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":380 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":436 * - * @cython.profile(False) - * cdef inline stack_item stack_pop(stack* self): # <<<<<<<<<<<<<< - * if self.n == 0: - * raise ValueError("popping empty stack") + * + * cdef inline DTYPE_t compute_log_kernel(DTYPE_t dist, DTYPE_t h, # <<<<<<<<<<<<<< + * KernelType kernel): + * """Given a KernelType enumeration, compute the appropriate log-kernel""" */ -static CYTHON_INLINE struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item __pyx_f_7sklearn_9neighbors_9ball_tree_stack_pop(struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *__pyx_v_self) { - struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item __pyx_r; +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h, enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType __pyx_v_kernel) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("stack_pop"); + __Pyx_RefNannySetupContext("compute_log_kernel", 0); - /* "sklearn/neighbors/ball_tree.pyx":381 - * @cython.profile(False) - * cdef inline stack_item stack_pop(stack* self): - * if self.n == 0: # <<<<<<<<<<<<<< - * raise ValueError("popping empty stack") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":449 + * elif kernel == LINEAR_KERNEL: + * return log_linear_kernel(dist, h) + * elif kernel == COSINE_KERNEL: # <<<<<<<<<<<<<< + * return log_cosine_kernel(dist, h) * */ - __pyx_t_1 = (__pyx_v_self->n == 0); - if (__pyx_t_1) { + switch (__pyx_v_kernel) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":439 + * KernelType kernel): + * """Given a KernelType enumeration, compute the appropriate log-kernel""" + * if kernel == GAUSSIAN_KERNEL: # <<<<<<<<<<<<<< + * return log_gaussian_kernel(dist, h) + * elif kernel == TOPHAT_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_9ball_tree_GAUSSIAN_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":440 + * """Given a KernelType enumeration, compute the appropriate log-kernel""" + * if kernel == GAUSSIAN_KERNEL: + * return log_gaussian_kernel(dist, h) # <<<<<<<<<<<<<< + * elif kernel == TOPHAT_KERNEL: + * return log_tophat_kernel(dist, h) + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_9ball_tree_log_gaussian_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":441 + * if kernel == GAUSSIAN_KERNEL: + * return log_gaussian_kernel(dist, h) + * elif kernel == TOPHAT_KERNEL: # <<<<<<<<<<<<<< + * return log_tophat_kernel(dist, h) + * elif kernel == EPANECHNIKOV_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_9ball_tree_TOPHAT_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":442 + * return log_gaussian_kernel(dist, h) + * elif kernel == TOPHAT_KERNEL: + * return log_tophat_kernel(dist, h) # <<<<<<<<<<<<<< + * elif kernel == EPANECHNIKOV_KERNEL: + * return log_epanechnikov_kernel(dist, h) + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_9ball_tree_log_tophat_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":443 + * elif kernel == TOPHAT_KERNEL: + * return log_tophat_kernel(dist, h) + * elif kernel == EPANECHNIKOV_KERNEL: # <<<<<<<<<<<<<< + * return log_epanechnikov_kernel(dist, h) + * elif kernel == EXPONENTIAL_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_9ball_tree_EPANECHNIKOV_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":444 + * return log_tophat_kernel(dist, h) + * elif kernel == EPANECHNIKOV_KERNEL: + * return log_epanechnikov_kernel(dist, h) # <<<<<<<<<<<<<< + * elif kernel == EXPONENTIAL_KERNEL: + * return log_exponential_kernel(dist, h) + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_9ball_tree_log_epanechnikov_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":445 + * elif kernel == EPANECHNIKOV_KERNEL: + * return log_epanechnikov_kernel(dist, h) + * elif kernel == EXPONENTIAL_KERNEL: # <<<<<<<<<<<<<< + * return log_exponential_kernel(dist, h) + * elif kernel == LINEAR_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_9ball_tree_EXPONENTIAL_KERNEL: - /* "sklearn/neighbors/ball_tree.pyx":382 - * cdef inline stack_item stack_pop(stack* self): - * if self.n == 0: - * raise ValueError("popping empty stack") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":446 + * return log_epanechnikov_kernel(dist, h) + * elif kernel == EXPONENTIAL_KERNEL: + * return log_exponential_kernel(dist, h) # <<<<<<<<<<<<<< + * elif kernel == LINEAR_KERNEL: + * return log_linear_kernel(dist, h) + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_9ball_tree_log_exponential_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":447 + * elif kernel == EXPONENTIAL_KERNEL: + * return log_exponential_kernel(dist, h) + * elif kernel == LINEAR_KERNEL: # <<<<<<<<<<<<<< + * return log_linear_kernel(dist, h) + * elif kernel == COSINE_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_9ball_tree_LINEAR_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":448 + * return log_exponential_kernel(dist, h) + * elif kernel == LINEAR_KERNEL: + * return log_linear_kernel(dist, h) # <<<<<<<<<<<<<< + * elif kernel == COSINE_KERNEL: + * return log_cosine_kernel(dist, h) + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_9ball_tree_log_linear_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":449 + * elif kernel == LINEAR_KERNEL: + * return log_linear_kernel(dist, h) + * elif kernel == COSINE_KERNEL: # <<<<<<<<<<<<<< + * return log_cosine_kernel(dist, h) * - * self.n -= 1 */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; - } - __pyx_L3:; + case __pyx_e_7sklearn_9neighbors_9ball_tree_COSINE_KERNEL: - /* "sklearn/neighbors/ball_tree.pyx":384 - * raise ValueError("popping empty stack") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":450 + * return log_linear_kernel(dist, h) + * elif kernel == COSINE_KERNEL: + * return log_cosine_kernel(dist, h) # <<<<<<<<<<<<<< * - * self.n -= 1 # <<<<<<<<<<<<<< - * return self.heap[self.n] * */ - __pyx_v_self->n = (__pyx_v_self->n - 1); + __pyx_r = __pyx_f_7sklearn_9neighbors_9ball_tree_log_cosine_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + default: break; + } - /* "sklearn/neighbors/ball_tree.pyx":385 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":436 + * * - * self.n -= 1 - * return self.heap[self.n] # <<<<<<<<<<<<<< + * cdef inline DTYPE_t compute_log_kernel(DTYPE_t dist, DTYPE_t h, # <<<<<<<<<<<<<< + * KernelType kernel): + * """Given a KernelType enumeration, compute the appropriate log-kernel""" + */ + + /* function exit code */ + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":456 + * # Kernel norms are defined via the volume element V_n + * # and surface element S_(n-1) of an n-sphere. + * cdef DTYPE_t logVn(ITYPE_t n): # <<<<<<<<<<<<<< + * """V_n = pi^(n/2) / gamma(n/2 - 1)""" + * return 0.5 * n * LOG_PI - lgamma(0.5 * n + 1) + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_logVn(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("logVn", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":458 + * cdef DTYPE_t logVn(ITYPE_t n): + * """V_n = pi^(n/2) / gamma(n/2 - 1)""" + * return 0.5 * n * LOG_PI - lgamma(0.5 * n + 1) # <<<<<<<<<<<<<< * * */ - __pyx_r = (__pyx_v_self->heap[__pyx_v_self->n]); + __pyx_r = (((0.5 * __pyx_v_n) * __pyx_v_7sklearn_9neighbors_9ball_tree_LOG_PI) - __pyx_f_7sklearn_5utils_6lgamma_lgamma(((0.5 * __pyx_v_n) + 1.0))); goto __pyx_L0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_WriteUnraisable("sklearn.neighbors.ball_tree.stack_pop", __pyx_clineno, __pyx_lineno, __pyx_filename); + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":456 + * # Kernel norms are defined via the volume element V_n + * # and surface element S_(n-1) of an n-sphere. + * cdef DTYPE_t logVn(ITYPE_t n): # <<<<<<<<<<<<<< + * """V_n = pi^(n/2) / gamma(n/2 - 1)""" + * return 0.5 * n * LOG_PI - lgamma(0.5 * n + 1) + */ + + /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":391 - * # newObj function - * # this is a helper function for pickling - * def newObj(obj): # <<<<<<<<<<<<<< - * return obj.__new__(obj) +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":461 + * * + * cdef DTYPE_t logSn(ITYPE_t n): # <<<<<<<<<<<<<< + * """V_(n+1) = int_0^1 S_n r^n dr""" + * return LOG_2PI + logVn(n - 1) */ -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_newObj(PyObject *__pyx_self, PyObject *__pyx_v_obj); /*proto*/ -static PyMethodDef __pyx_mdef_7sklearn_9neighbors_9ball_tree_newObj = {__Pyx_NAMESTR("newObj"), (PyCFunction)__pyx_pf_7sklearn_9neighbors_9ball_tree_newObj, METH_O, __Pyx_DOCSTR(0)}; -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_newObj(PyObject *__pyx_self, PyObject *__pyx_v_obj) { - PyObject *__pyx_r = NULL; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_logSn(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("newObj"); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("logSn", 0); - /* "sklearn/neighbors/ball_tree.pyx":392 - * # this is a helper function for pickling - * def newObj(obj): - * return obj.__new__(obj) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":463 + * cdef DTYPE_t logSn(ITYPE_t n): + * """V_(n+1) = int_0^1 S_n r^n dr""" + * return LOG_2PI + logVn(n - 1) # <<<<<<<<<<<<<< * * */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyObject_GetAttr(__pyx_v_obj, __pyx_n_s____new__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(__pyx_v_obj); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_obj); - __Pyx_GIVEREF(__pyx_v_obj); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_r = (__pyx_v_7sklearn_9neighbors_9ball_tree_LOG_2PI + __pyx_f_7sklearn_9neighbors_9ball_tree_logVn((__pyx_v_n - 1))); goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.newObj", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":461 + * + * + * cdef DTYPE_t logSn(ITYPE_t n): # <<<<<<<<<<<<<< + * """V_(n+1) = int_0^1 S_n r^n dr""" + * return LOG_2PI + logVn(n - 1) + */ + + /* function exit code */ __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":488 - * cdef readonly int warning_flag +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":466 * - * def __cinit__(self): # <<<<<<<<<<<<<< - * """ - * initialize all arrays to empty. This will prevent memory errors + * + * cdef DTYPE_t _log_kernel_norm(DTYPE_t h, ITYPE_t d, # <<<<<<<<<<<<<< + * KernelType kernel) except -1: + * """Given a KernelType enumeration, compute the kernel normalization. */ -static int __pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - int __pyx_r; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree__log_kernel_norm(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_d, enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType __pyx_v_kernel) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_tmp; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_factor; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_k; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; + long __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__"); - if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} - if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; + __Pyx_RefNannySetupContext("_log_kernel_norm", 0); - /* "sklearn/neighbors/ball_tree.pyx":493 - * in rare cases where __init__ is not called - * """ - * self.data = np.empty((0,0), dtype=DTYPE) # <<<<<<<<<<<<<< - * self.idx_array = np.empty(0, dtype=ITYPE) - * self.node_centroid_arr = np.empty((0,0), dtype=DTYPE) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":472 + * h is the bandwidth, d is the dimension. + * """ + * cdef DTYPE_t tmp, factor = 0 # <<<<<<<<<<<<<< + * cdef ITYPE_t k + * if kernel == GAUSSIAN_KERNEL: + */ + __pyx_v_factor = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":484 + * elif kernel == LINEAR_KERNEL: + * factor = logVn(d) - log(d + 1.) + * elif kernel == COSINE_KERNEL: # <<<<<<<<<<<<<< + * # this is derived from a chain rule integration + * factor = 0 + */ + switch (__pyx_v_kernel) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":474 + * cdef DTYPE_t tmp, factor = 0 + * cdef ITYPE_t k + * if kernel == GAUSSIAN_KERNEL: # <<<<<<<<<<<<<< + * factor = 0.5 * d * LOG_2PI + * elif kernel == TOPHAT_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_9ball_tree_GAUSSIAN_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":475 + * cdef ITYPE_t k + * if kernel == GAUSSIAN_KERNEL: + * factor = 0.5 * d * LOG_2PI # <<<<<<<<<<<<<< + * elif kernel == TOPHAT_KERNEL: + * factor = logVn(d) + */ + __pyx_v_factor = ((0.5 * __pyx_v_d) * __pyx_v_7sklearn_9neighbors_9ball_tree_LOG_2PI); + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":476 + * if kernel == GAUSSIAN_KERNEL: + * factor = 0.5 * d * LOG_2PI + * elif kernel == TOPHAT_KERNEL: # <<<<<<<<<<<<<< + * factor = logVn(d) + * elif kernel == EPANECHNIKOV_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_9ball_tree_TOPHAT_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":477 + * factor = 0.5 * d * LOG_2PI + * elif kernel == TOPHAT_KERNEL: + * factor = logVn(d) # <<<<<<<<<<<<<< + * elif kernel == EPANECHNIKOV_KERNEL: + * factor = logVn(d) + log(2. / (d + 2.)) + */ + __pyx_v_factor = __pyx_f_7sklearn_9neighbors_9ball_tree_logVn(__pyx_v_d); + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":478 + * elif kernel == TOPHAT_KERNEL: + * factor = logVn(d) + * elif kernel == EPANECHNIKOV_KERNEL: # <<<<<<<<<<<<<< + * factor = logVn(d) + log(2. / (d + 2.)) + * elif kernel == EXPONENTIAL_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_9ball_tree_EPANECHNIKOV_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":479 + * factor = logVn(d) + * elif kernel == EPANECHNIKOV_KERNEL: + * factor = logVn(d) + log(2. / (d + 2.)) # <<<<<<<<<<<<<< + * elif kernel == EXPONENTIAL_KERNEL: + * factor = logSn(d - 1) + lgamma(d) + */ + __pyx_v_factor = (__pyx_f_7sklearn_9neighbors_9ball_tree_logVn(__pyx_v_d) + log((2. / (__pyx_v_d + 2.)))); + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":480 + * elif kernel == EPANECHNIKOV_KERNEL: + * factor = logVn(d) + log(2. / (d + 2.)) + * elif kernel == EXPONENTIAL_KERNEL: # <<<<<<<<<<<<<< + * factor = logSn(d - 1) + lgamma(d) + * elif kernel == LINEAR_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_9ball_tree_EXPONENTIAL_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":481 + * factor = logVn(d) + log(2. / (d + 2.)) + * elif kernel == EXPONENTIAL_KERNEL: + * factor = logSn(d - 1) + lgamma(d) # <<<<<<<<<<<<<< + * elif kernel == LINEAR_KERNEL: + * factor = logVn(d) - log(d + 1.) + */ + __pyx_v_factor = (__pyx_f_7sklearn_9neighbors_9ball_tree_logSn((__pyx_v_d - 1)) + __pyx_f_7sklearn_5utils_6lgamma_lgamma(__pyx_v_d)); + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":482 + * elif kernel == EXPONENTIAL_KERNEL: + * factor = logSn(d - 1) + lgamma(d) + * elif kernel == LINEAR_KERNEL: # <<<<<<<<<<<<<< + * factor = logVn(d) - log(d + 1.) + * elif kernel == COSINE_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_9ball_tree_LINEAR_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":483 + * factor = logSn(d - 1) + lgamma(d) + * elif kernel == LINEAR_KERNEL: + * factor = logVn(d) - log(d + 1.) # <<<<<<<<<<<<<< + * elif kernel == COSINE_KERNEL: + * # this is derived from a chain rule integration + */ + __pyx_v_factor = (__pyx_f_7sklearn_9neighbors_9ball_tree_logVn(__pyx_v_d) - log((__pyx_v_d + 1.))); + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":484 + * elif kernel == LINEAR_KERNEL: + * factor = logVn(d) - log(d + 1.) + * elif kernel == COSINE_KERNEL: # <<<<<<<<<<<<<< + * # this is derived from a chain rule integration + * factor = 0 + */ + case __pyx_e_7sklearn_9neighbors_9ball_tree_COSINE_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":486 + * elif kernel == COSINE_KERNEL: + * # this is derived from a chain rule integration + * factor = 0 # <<<<<<<<<<<<<< + * tmp = 2. / PI + * for k in range(1, d + 1, 2): + */ + __pyx_v_factor = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":487 + * # this is derived from a chain rule integration + * factor = 0 + * tmp = 2. / PI # <<<<<<<<<<<<<< + * for k in range(1, d + 1, 2): + * factor += tmp + */ + __pyx_v_tmp = (2. / __pyx_v_7sklearn_9neighbors_9ball_tree_PI); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":488 + * factor = 0 + * tmp = 2. / PI + * for k in range(1, d + 1, 2): # <<<<<<<<<<<<<< + * factor += tmp + * tmp *= -(d - k) * (d - k - 1) * (2. / PI) ** 2 + */ + __pyx_t_1 = (__pyx_v_d + 1); + for (__pyx_t_2 = 1; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=2) { + __pyx_v_k = __pyx_t_2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":489 + * tmp = 2. / PI + * for k in range(1, d + 1, 2): + * factor += tmp # <<<<<<<<<<<<<< + * tmp *= -(d - k) * (d - k - 1) * (2. / PI) ** 2 + * factor = log(factor) + logSn(d - 1) + */ + __pyx_v_factor = (__pyx_v_factor + __pyx_v_tmp); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":490 + * for k in range(1, d + 1, 2): + * factor += tmp + * tmp *= -(d - k) * (d - k - 1) * (2. / PI) ** 2 # <<<<<<<<<<<<<< + * factor = log(factor) + logSn(d - 1) + * else: */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_k_tuple_6), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; + __pyx_v_tmp = (__pyx_v_tmp * (((-(__pyx_v_d - __pyx_v_k)) * ((__pyx_v_d - __pyx_v_k) - 1)) * pow((2. / __pyx_v_7sklearn_9neighbors_9ball_tree_PI), 2.0))); + } - /* "sklearn/neighbors/ball_tree.pyx":494 - * """ - * self.data = np.empty((0,0), dtype=DTYPE) - * self.idx_array = np.empty(0, dtype=ITYPE) # <<<<<<<<<<<<<< - * self.node_centroid_arr = np.empty((0,0), dtype=DTYPE) - * self.node_info_arr = np.empty(0, dtype='c') + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":491 + * factor += tmp + * tmp *= -(d - k) * (d - k - 1) * (2. / PI) ** 2 + * factor = log(factor) + logSn(d - 1) # <<<<<<<<<<<<<< + * else: + * raise ValueError("Kernel code not recognized") */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_k_tuple_7), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; + __pyx_v_factor = (log(__pyx_v_factor) + __pyx_f_7sklearn_9neighbors_9ball_tree_logSn((__pyx_v_d - 1))); + break; + default: - /* "sklearn/neighbors/ball_tree.pyx":495 - * self.data = np.empty((0,0), dtype=DTYPE) - * self.idx_array = np.empty(0, dtype=ITYPE) - * self.node_centroid_arr = np.empty((0,0), dtype=DTYPE) # <<<<<<<<<<<<<< - * self.node_info_arr = np.empty(0, dtype='c') + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":493 + * factor = log(factor) + logSn(d - 1) + * else: + * raise ValueError("Kernel code not recognized") # <<<<<<<<<<<<<< + * return -factor - d * log(h) * */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyEval_CallObjectWithKeywords(__pyx_t_3, ((PyObject *)__pyx_k_tuple_9), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } - /* "sklearn/neighbors/ball_tree.pyx":496 - * self.idx_array = np.empty(0, dtype=ITYPE) - * self.node_centroid_arr = np.empty((0,0), dtype=DTYPE) - * self.node_info_arr = np.empty(0, dtype='c') # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":494 + * else: + * raise ValueError("Kernel code not recognized") + * return -factor - d * log(h) # <<<<<<<<<<<<<< + * * - * def __init__(self, X, ITYPE_t leaf_size=20, DTYPE_t p=2): */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), ((PyObject *)__pyx_n_s__c)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_k_tuple_10), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - __pyx_r = 0; + __pyx_r = ((-__pyx_v_factor) - (__pyx_v_d * log(__pyx_v_h))); goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":466 + * + * + * cdef DTYPE_t _log_kernel_norm(DTYPE_t h, ITYPE_t d, # <<<<<<<<<<<<<< + * KernelType kernel) except -1: + * """Given a KernelType enumeration, compute the kernel normalization. + */ + + /* function exit code */ __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BallTree.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree._log_kernel_norm", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":498 - * self.node_info_arr = np.empty(0, dtype='c') +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":497 + * + * + * def kernel_norm(h, d, kernel, return_log=False): # <<<<<<<<<<<<<< + * """Given a string specification of a kernel, compute the normalization. * - * def __init__(self, X, ITYPE_t leaf_size=20, DTYPE_t p=2): # <<<<<<<<<<<<<< - * self.data = np.asarray(X, dtype=DTYPE, order='C') - * self.warning_flag = True */ -static int __pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_X = 0; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_leaf_size; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_samples; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_features; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - long __pyx_t_6; - long __pyx_t_7; - long __pyx_t_8; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_9; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_1kernel_norm(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_kernel_norm[] = "Given a string specification of a kernel, compute the normalization.\n\n Parameters\n ----------\n h : float\n the bandwidth of the kernel\n d : int\n the dimension of the space in which the kernel norm is computed\n kernel : string\n The kernel identifier. Must be one of\n ['gaussian'|'tophat'|'epanechnikov'|\n 'exponential'|'linear'|'cosine']\n return_log : boolean\n if True, return the log of the kernel norm. Otherwise, return the\n kernel norm.\n Returns\n -------\n knorm or log_knorm : float\n the kernel norm or logarithm of the kernel norm.\n "; +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_9ball_tree_1kernel_norm = {__Pyx_NAMESTR("kernel_norm"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_1kernel_norm, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_kernel_norm)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_1kernel_norm(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_h = 0; + PyObject *__pyx_v_d = 0; + PyObject *__pyx_v_kernel = 0; + PyObject *__pyx_v_return_log = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__leaf_size,&__pyx_n_s__p,0}; - __Pyx_RefNannySetupContext("__init__"); + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("kernel_norm (wrapper)", 0); { - PyObject* values[3] = {0,0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_h,&__pyx_n_s_d,&__pyx_n_s_kernel,&__pyx_n_s_return_log,0}; + PyObject* values[4] = {0,0,0,0}; + values[3] = ((PyObject *)Py_False); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); @@ -2513,642 +4258,981 @@ static int __pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_1__init__(PyObject default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_h)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__leaf_size); - if (value) { values[1] = value; kw_args--; } + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_d)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("kernel_norm", 0, 3, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kernel)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("kernel_norm", 0, 3, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (value) { values[2] = value; kw_args--; } + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_return_log); + if (value) { values[3] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 498; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "kernel_norm") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } - __pyx_v_X = values[0]; - if (values[1]) { - __pyx_v_leaf_size = __Pyx_PyInt_from_py_npy_int32(values[1]); if (unlikely((__pyx_v_leaf_size == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 498; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_leaf_size = ((__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t)20); - } - if (values[2]) { - __pyx_v_p = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_p == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 498; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_p = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t)2.0); - } + __pyx_v_h = values[0]; + __pyx_v_d = values[1]; + __pyx_v_kernel = values[2]; + __pyx_v_return_log = values[3]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 498; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("kernel_norm", 0, 3, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BallTree.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.kernel_norm", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); - return -1; + return NULL; __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_kernel_norm(__pyx_self, __pyx_v_h, __pyx_v_d, __pyx_v_kernel, __pyx_v_return_log); - /* "sklearn/neighbors/ball_tree.pyx":499 - * - * def __init__(self, X, ITYPE_t leaf_size=20, DTYPE_t p=2): - * self.data = np.asarray(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< - * self.warning_flag = True - * + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_kernel_norm(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_h, PyObject *__pyx_v_d, PyObject *__pyx_v_kernel, PyObject *__pyx_v_return_log) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("kernel_norm", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":518 + * the kernel norm or logarithm of the kernel norm. + * """ + * if kernel == 'gaussian': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, GAUSSIAN_KERNEL) + * elif kernel == 'tophat': */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(__pyx_v_X); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_X); - __Pyx_GIVEREF(__pyx_v_X); - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_4); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_gaussian, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 518; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":500 - * def __init__(self, X, ITYPE_t leaf_size=20, DTYPE_t p=2): - * self.data = np.asarray(X, dtype=DTYPE, order='C') - * self.warning_flag = True # <<<<<<<<<<<<<< - * - * if X.size == 0: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":519 + * """ + * if kernel == 'gaussian': + * result = _log_kernel_norm(h, d, GAUSSIAN_KERNEL) # <<<<<<<<<<<<<< + * elif kernel == 'tophat': + * result = _log_kernel_norm(h, d, TOPHAT_KERNEL) + */ + __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_2 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree__log_kernel_norm(__pyx_t_2, __pyx_t_3, __pyx_e_7sklearn_9neighbors_9ball_tree_GAUSSIAN_KERNEL); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":520 + * if kernel == 'gaussian': + * result = _log_kernel_norm(h, d, GAUSSIAN_KERNEL) + * elif kernel == 'tophat': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, TOPHAT_KERNEL) + * elif kernel == 'epanechnikov': */ - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->warning_flag = 1; + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_tophat, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":502 - * self.warning_flag = True - * - * if X.size == 0: # <<<<<<<<<<<<<< - * raise ValueError("X is an empty array") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":521 + * result = _log_kernel_norm(h, d, GAUSSIAN_KERNEL) + * elif kernel == 'tophat': + * result = _log_kernel_norm(h, d, TOPHAT_KERNEL) # <<<<<<<<<<<<<< + * elif kernel == 'epanechnikov': + * result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) + */ + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_9ball_tree__log_kernel_norm(__pyx_t_4, __pyx_t_3, __pyx_e_7sklearn_9neighbors_9ball_tree_TOPHAT_KERNEL); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":522 + * elif kernel == 'tophat': + * result = _log_kernel_norm(h, d, TOPHAT_KERNEL) + * elif kernel == 'epanechnikov': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) + * elif kernel == 'exponential': + */ + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_epanechnikov, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":523 + * result = _log_kernel_norm(h, d, TOPHAT_KERNEL) + * elif kernel == 'epanechnikov': + * result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) # <<<<<<<<<<<<<< + * elif kernel == 'exponential': + * result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) + */ + __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_2 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree__log_kernel_norm(__pyx_t_2, __pyx_t_3, __pyx_e_7sklearn_9neighbors_9ball_tree_EPANECHNIKOV_KERNEL); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":524 + * elif kernel == 'epanechnikov': + * result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) + * elif kernel == 'exponential': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) + * elif kernel == 'linear': + */ + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_exponential, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":525 + * result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) + * elif kernel == 'exponential': + * result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) # <<<<<<<<<<<<<< + * elif kernel == 'linear': + * result = _log_kernel_norm(h, d, LINEAR_KERNEL) + */ + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_9ball_tree__log_kernel_norm(__pyx_t_4, __pyx_t_3, __pyx_e_7sklearn_9neighbors_9ball_tree_EXPONENTIAL_KERNEL); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":526 + * elif kernel == 'exponential': + * result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) + * elif kernel == 'linear': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, LINEAR_KERNEL) + * elif kernel == 'cosine': + */ + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_linear, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":527 + * result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) + * elif kernel == 'linear': + * result = _log_kernel_norm(h, d, LINEAR_KERNEL) # <<<<<<<<<<<<<< + * elif kernel == 'cosine': + * result = _log_kernel_norm(h, d, COSINE_KERNEL) + */ + __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_2 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree__log_kernel_norm(__pyx_t_2, __pyx_t_3, __pyx_e_7sklearn_9neighbors_9ball_tree_LINEAR_KERNEL); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":528 + * elif kernel == 'linear': + * result = _log_kernel_norm(h, d, LINEAR_KERNEL) + * elif kernel == 'cosine': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, COSINE_KERNEL) + * else: + */ + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_cosine, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":529 + * result = _log_kernel_norm(h, d, LINEAR_KERNEL) + * elif kernel == 'cosine': + * result = _log_kernel_norm(h, d, COSINE_KERNEL) # <<<<<<<<<<<<<< + * else: + * raise ValueError('kernel not recognized') + */ + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_9ball_tree__log_kernel_norm(__pyx_t_4, __pyx_t_3, __pyx_e_7sklearn_9neighbors_9ball_tree_COSINE_KERNEL); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":531 + * result = _log_kernel_norm(h, d, COSINE_KERNEL) + * else: + * raise ValueError('kernel not recognized') # <<<<<<<<<<<<<< * + * if return_log: */ - __pyx_t_4 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__size); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_4, __pyx_int_0, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_5) { + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; - /* "sklearn/neighbors/ball_tree.pyx":503 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":533 + * raise ValueError('kernel not recognized') * - * if X.size == 0: - * raise ValueError("X is an empty array") # <<<<<<<<<<<<<< + * if return_log: # <<<<<<<<<<<<<< + * return result + * else: + */ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_return_log); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":534 * - * if self.data.ndim != 2: + * if return_log: + * return result # <<<<<<<<<<<<<< + * else: + * return np.exp(result) */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L0; } - __pyx_L6:; + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":505 - * raise ValueError("X is an empty array") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":536 + * return result + * else: + * return np.exp(result) # <<<<<<<<<<<<<< * - * if self.data.ndim != 2: # <<<<<<<<<<<<<< - * raise ValueError("X should have two dimensions") * */ - __pyx_t_5 = (((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data->nd != 2); - if (__pyx_t_5) { + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_exp); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_result); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_5, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_r = __pyx_t_7; + __pyx_t_7 = 0; + goto __pyx_L0; + } - /* "sklearn/neighbors/ball_tree.pyx":506 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":497 + * * - * if self.data.ndim != 2: - * raise ValueError("X should have two dimensions") # <<<<<<<<<<<<<< + * def kernel_norm(h, d, kernel, return_log=False): # <<<<<<<<<<<<<< + * """Given a string specification of a kernel, compute the normalization. * - * if p < 1: */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - /* "sklearn/neighbors/ball_tree.pyx":508 - * raise ValueError("X should have two dimensions") + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.kernel_norm", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":541 + * ###################################################################### + * # Tree Utility Routines + * cdef inline void swap(DITYPE_t* arr, ITYPE_t i1, ITYPE_t i2): # <<<<<<<<<<<<<< + * """swap the values at index i1 and i2 of arr""" + * cdef DITYPE_t tmp = arr[i1] + */ + +static CYTHON_INLINE void __pyx_fuse_0__pyx_f_7sklearn_9neighbors_9ball_tree_swap(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_arr, int __pyx_v_i1, int __pyx_v_i2) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_tmp; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_fuse_0swap", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":543 + * cdef inline void swap(DITYPE_t* arr, ITYPE_t i1, ITYPE_t i2): + * """swap the values at index i1 and i2 of arr""" + * cdef DITYPE_t tmp = arr[i1] # <<<<<<<<<<<<<< + * arr[i1] = arr[i2] + * arr[i2] = tmp + */ + __pyx_v_tmp = (__pyx_v_arr[__pyx_v_i1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":544 + * """swap the values at index i1 and i2 of arr""" + * cdef DITYPE_t tmp = arr[i1] + * arr[i1] = arr[i2] # <<<<<<<<<<<<<< + * arr[i2] = tmp * - * if p < 1: # <<<<<<<<<<<<<< - * raise ValueError("p must be greater than or equal to 1") - * self.p = p */ - __pyx_t_5 = (__pyx_v_p < 1.0); - if (__pyx_t_5) { + (__pyx_v_arr[__pyx_v_i1]) = (__pyx_v_arr[__pyx_v_i2]); - /* "sklearn/neighbors/ball_tree.pyx":509 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":545 + * cdef DITYPE_t tmp = arr[i1] + * arr[i1] = arr[i2] + * arr[i2] = tmp # <<<<<<<<<<<<<< * - * if p < 1: - * raise ValueError("p must be greater than or equal to 1") # <<<<<<<<<<<<<< - * self.p = p * */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; - } - __pyx_L8:; + (__pyx_v_arr[__pyx_v_i2]) = __pyx_v_tmp; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":541 + * ###################################################################### + * # Tree Utility Routines + * cdef inline void swap(DITYPE_t* arr, ITYPE_t i1, ITYPE_t i2): # <<<<<<<<<<<<<< + * """swap the values at index i1 and i2 of arr""" + * cdef DITYPE_t tmp = arr[i1] + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} - /* "sklearn/neighbors/ball_tree.pyx":510 - * if p < 1: - * raise ValueError("p must be greater than or equal to 1") - * self.p = p # <<<<<<<<<<<<<< +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":548 * - * if leaf_size < 1: + * + * cdef inline void dual_swap(DTYPE_t* darr, ITYPE_t* iarr, # <<<<<<<<<<<<<< + * ITYPE_t i1, ITYPE_t i2): + * """swap the values at inex i1 and i2 of both darr and iarr""" + */ + +static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_dual_swap(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_darr, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_iarr, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dtmp; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_itmp; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dual_swap", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":551 + * ITYPE_t i1, ITYPE_t i2): + * """swap the values at inex i1 and i2 of both darr and iarr""" + * cdef DTYPE_t dtmp = darr[i1] # <<<<<<<<<<<<<< + * darr[i1] = darr[i2] + * darr[i2] = dtmp */ - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->p = __pyx_v_p; + __pyx_v_dtmp = (__pyx_v_darr[__pyx_v_i1]); - /* "sklearn/neighbors/ball_tree.pyx":512 - * self.p = p + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":552 + * """swap the values at inex i1 and i2 of both darr and iarr""" + * cdef DTYPE_t dtmp = darr[i1] + * darr[i1] = darr[i2] # <<<<<<<<<<<<<< + * darr[i2] = dtmp * - * if leaf_size < 1: # <<<<<<<<<<<<<< - * raise ValueError("leaf_size must be greater than or equal to 1") - * self.leaf_size = leaf_size */ - __pyx_t_5 = (__pyx_v_leaf_size < 1); - if (__pyx_t_5) { + (__pyx_v_darr[__pyx_v_i1]) = (__pyx_v_darr[__pyx_v_i2]); - /* "sklearn/neighbors/ball_tree.pyx":513 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":553 + * cdef DTYPE_t dtmp = darr[i1] + * darr[i1] = darr[i2] + * darr[i2] = dtmp # <<<<<<<<<<<<<< * - * if leaf_size < 1: - * raise ValueError("leaf_size must be greater than or equal to 1") # <<<<<<<<<<<<<< - * self.leaf_size = leaf_size + * cdef ITYPE_t itmp = iarr[i1] + */ + (__pyx_v_darr[__pyx_v_i2]) = __pyx_v_dtmp; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":555 + * darr[i2] = dtmp * + * cdef ITYPE_t itmp = iarr[i1] # <<<<<<<<<<<<<< + * iarr[i1] = iarr[i2] + * iarr[i2] = itmp */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_18), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L9; - } - __pyx_L9:; + __pyx_v_itmp = (__pyx_v_iarr[__pyx_v_i1]); - /* "sklearn/neighbors/ball_tree.pyx":514 - * if leaf_size < 1: - * raise ValueError("leaf_size must be greater than or equal to 1") - * self.leaf_size = leaf_size # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":556 + * + * cdef ITYPE_t itmp = iarr[i1] + * iarr[i1] = iarr[i2] # <<<<<<<<<<<<<< + * iarr[i2] = itmp * - * cdef ITYPE_t n_samples = self.data.shape[0] */ - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->leaf_size = __pyx_v_leaf_size; + (__pyx_v_iarr[__pyx_v_i1]) = (__pyx_v_iarr[__pyx_v_i2]); - /* "sklearn/neighbors/ball_tree.pyx":516 - * self.leaf_size = leaf_size + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":557 + * cdef ITYPE_t itmp = iarr[i1] + * iarr[i1] = iarr[i2] + * iarr[i2] = itmp # <<<<<<<<<<<<<< * - * cdef ITYPE_t n_samples = self.data.shape[0] # <<<<<<<<<<<<<< - * cdef ITYPE_t n_features = self.data.shape[1] * */ - __pyx_v_n_samples = (((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data->dimensions[0]); + (__pyx_v_iarr[__pyx_v_i2]) = __pyx_v_itmp; - /* "sklearn/neighbors/ball_tree.pyx":517 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":548 * - * cdef ITYPE_t n_samples = self.data.shape[0] - * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< * - * # determine number of levels in the ball tree, and from this + * cdef inline void dual_swap(DTYPE_t* darr, ITYPE_t* iarr, # <<<<<<<<<<<<<< + * ITYPE_t i1, ITYPE_t i2): + * """swap the values at inex i1 and i2 of both darr and iarr""" */ - __pyx_v_n_features = (((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data->dimensions[1]); - /* "sklearn/neighbors/ball_tree.pyx":521 - * # determine number of levels in the ball tree, and from this - * # the number of nodes in the ball tree - * self.n_levels = np.log2(max(1, (n_samples - 1)/self.leaf_size)) + 1 # <<<<<<<<<<<<<< - * self.n_nodes = (2 ** self.n_levels) - 1 + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":581 + * cdef ITYPE_t[:, ::1] indices + * + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} + if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap___cinit__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap___cinit__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":582 * + * def __cinit__(self): + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__log2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = (__pyx_v_n_samples - 1); - if (unlikely(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->leaf_size == 0)) { - PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - else if (sizeof(long) == sizeof(long) && unlikely(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->leaf_size == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_t_6))) { - PyErr_Format(PyExc_OverflowError, "value too large to perform division"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_7 = __Pyx_div_long(__pyx_t_6, ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->leaf_size); - __pyx_t_6 = 1; - if ((__pyx_t_7 > __pyx_t_6)) { - __pyx_t_8 = __pyx_t_7; - } else { - __pyx_t_8 = __pyx_t_6; - } - __pyx_t_3 = PyInt_FromLong(__pyx_t_8); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__4, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->distances_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->distances_arr)); + __pyx_v_self->distances_arr = ((PyArrayObject *)__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":583 + * def __cinit__(self): + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_9 = __Pyx_PyInt_from_py_npy_int32(__pyx_t_1); if (unlikely((__pyx_t_9 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_tuple__6, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->n_levels = __pyx_t_9; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_self->indices_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->indices_arr)); + __pyx_v_self->indices_arr = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; - /* "sklearn/neighbors/ball_tree.pyx":522 - * # the number of nodes in the ball tree - * self.n_levels = np.log2(max(1, (n_samples - 1)/self.leaf_size)) + 1 - * self.n_nodes = (2 ** self.n_levels) - 1 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":584 + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) # <<<<<<<<<<<<<< + * self.indices = get_memview_ITYPE_2D(self.indices_arr) * - * self.idx_array = np.arange(n_samples, dtype=ITYPE) */ - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->n_nodes = (__Pyx_pow_long(2, ((long)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->n_levels)) - 1); + __pyx_t_2 = ((PyObject *)__pyx_v_self->distances_arr); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_2)); if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->distances, 0); + __pyx_v_self->distances = __pyx_t_4; + __pyx_t_4.memview = NULL; + __pyx_t_4.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":524 - * self.n_nodes = (2 ** self.n_levels) - 1 - * - * self.idx_array = np.arange(n_samples, dtype=ITYPE) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":585 + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + * self.indices = get_memview_ITYPE_2D(self.indices_arr) # <<<<<<<<<<<<<< * - * self.node_centroid_arr = np.empty((self.n_nodes, n_features), + * def __init__(self, n_pts, n_nbrs): */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__arange); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyEval_CallObjectWithKeywords(__pyx_t_3, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "sklearn/neighbors/ball_tree.pyx":526 - * self.idx_array = np.arange(n_samples, dtype=ITYPE) - * - * self.node_centroid_arr = np.empty((self.n_nodes, n_features), # <<<<<<<<<<<<<< - * dtype=DTYPE, order='C') - * - */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyInt_to_py_npy_int32(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->n_nodes); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_n_features); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_2 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); - __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - - /* "sklearn/neighbors/ball_tree.pyx":527 - * - * self.node_centroid_arr = np.empty((self.n_nodes, n_features), - * dtype=DTYPE, order='C') # <<<<<<<<<<<<<< - * - * self.node_info_arr = np.empty(self.n_nodes * sizeof(NodeInfo), - */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((PyObject *)__pyx_v_self->indices_arr); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_2D(((PyArrayObject *)__pyx_t_2)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/neighbors/ball_tree.pyx":526 - * self.idx_array = np.arange(n_samples, dtype=ITYPE) - * - * self.node_centroid_arr = np.empty((self.n_nodes, n_features), # <<<<<<<<<<<<<< - * dtype=DTYPE, order='C') - * - */ - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "sklearn/neighbors/ball_tree.pyx":529 - * dtype=DTYPE, order='C') - * - * self.node_info_arr = np.empty(self.n_nodes * sizeof(NodeInfo), # <<<<<<<<<<<<<< - * dtype='c', order='C') - * self.build_tree_() - */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyInt_FromSize_t((((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->n_nodes * (sizeof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo)))); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), ((PyObject *)__pyx_n_s__c)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = PyEval_CallObjectWithKeywords(__pyx_t_3, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->indices, 0); + __pyx_v_self->indices = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":531 - * self.node_info_arr = np.empty(self.n_nodes * sizeof(NodeInfo), - * dtype='c', order='C') - * self.build_tree_() # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":581 + * cdef ITYPE_t[:, ::1] indices * - * def __reduce__(self): + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') */ - ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->__pyx_vtab)->build_tree_(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)); + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BallTree.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __PYX_XDEC_MEMVIEW(&__pyx_t_4, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NeighborsHeap.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":533 - * self.build_tree_() +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":587 + * self.indices = get_memview_ITYPE_2D(self.indices_arr) * - * def __reduce__(self): # <<<<<<<<<<<<<< - * """ - * reduce method used for pickling + * def __init__(self, n_pts, n_nbrs): # <<<<<<<<<<<<<< + * self.distances_arr = np.inf + np.zeros((n_pts, n_nbrs), dtype=DTYPE, + * order='C') */ -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_2__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7sklearn_9neighbors_9ball_tree_8BallTree_2__reduce__[] = "\n reduce method used for pickling\n "; -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_2__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = NULL; +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_n_pts = 0; + PyObject *__pyx_v_n_nbrs = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_n_pts,&__pyx_n_s_n_nbrs,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_pts)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_nbrs)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 587; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 587; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_n_pts = values[0]; + __pyx_v_n_nbrs = values[1]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 587; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NeighborsHeap.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_2__init__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_v_self), __pyx_v_n_pts, __pyx_v_n_nbrs); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_2__init__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_self, PyObject *__pyx_v_n_pts, PyObject *__pyx_v_n_nbrs) { + int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce__"); + __Pyx_RefNannySetupContext("__init__", 0); - /* "sklearn/neighbors/ball_tree.pyx":537 - * reduce method used for pickling - * """ - * return (newObj, (BallTree,), self.__getstate__()) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":588 * - * def __getstate__(self): + * def __init__(self, n_pts, n_nbrs): + * self.distances_arr = np.inf + np.zeros((n_pts, n_nbrs), dtype=DTYPE, # <<<<<<<<<<<<<< + * order='C') + * self.indices_arr = np.zeros((n_pts, n_nbrs), dtype=ITYPE, order='C') */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__newObj); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_9ball_tree_BallTree))); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_9ball_tree_BallTree))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_9ball_tree_BallTree))); - __pyx_t_3 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s____getstate__); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_n_pts); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_n_pts); + __Pyx_GIVEREF(__pyx_v_n_pts); + __Pyx_INCREF(__pyx_v_n_nbrs); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_n_nbrs); + __Pyx_GIVEREF(__pyx_v_n_nbrs); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_t_5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->distances_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->distances_arr)); + __pyx_v_self->distances_arr = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":590 + * self.distances_arr = np.inf + np.zeros((n_pts, n_nbrs), dtype=DTYPE, + * order='C') + * self.indices_arr = np.zeros((n_pts, n_nbrs), dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_n_pts); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_n_pts); + __Pyx_GIVEREF(__pyx_v_n_pts); + __Pyx_INCREF(__pyx_v_n_nbrs); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_n_nbrs); + __Pyx_GIVEREF(__pyx_v_n_nbrs); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->indices_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->indices_arr)); + __pyx_v_self->indices_arr = ((PyArrayObject *)__pyx_t_4); __pyx_t_4 = 0; - __pyx_r = ((PyObject *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":591 + * order='C') + * self.indices_arr = np.zeros((n_pts, n_nbrs), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) # <<<<<<<<<<<<<< + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + * + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->distances_arr); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_4)); if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->distances, 0); + __pyx_v_self->distances = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":592 + * self.indices_arr = np.zeros((n_pts, n_nbrs), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + * self.indices = get_memview_ITYPE_2D(self.indices_arr) # <<<<<<<<<<<<<< + * + * def get_arrays(self, sort=True): + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->indices_arr); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_2D(((PyArrayObject *)__pyx_t_4)); if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->indices, 0); + __pyx_v_self->indices = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":587 + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + * + * def __init__(self, n_pts, n_nbrs): # <<<<<<<<<<<<<< + * self.distances_arr = np.inf + np.zeros((n_pts, n_nbrs), dtype=DTYPE, + * order='C') + */ + + /* function exit code */ + __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BallTree.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __Pyx_XDECREF(__pyx_t_5); + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NeighborsHeap.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":539 - * return (newObj, (BallTree,), self.__getstate__()) +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":594 + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + * + * def get_arrays(self, sort=True): # <<<<<<<<<<<<<< + * """Get the arrays of distances and indices within the heap. * - * def __getstate__(self): # <<<<<<<<<<<<<< - * """ - * get state for pickling */ -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_3__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7sklearn_9neighbors_9ball_tree_8BallTree_3__getstate__[] = "\n get state for pickling\n "; -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_3__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_5get_arrays(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_4get_arrays[] = "Get the arrays of distances and indices within the heap.\n\n If sort=True, then simultaneously sort the indices and distances,\n so the closer points are listed first.\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_5get_arrays(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_sort = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_arrays (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_sort,0}; + PyObject* values[1] = {0}; + values[0] = ((PyObject *)Py_True); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sort); + if (value) { values[0] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "get_arrays") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 594; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_sort = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_arrays", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 594; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NeighborsHeap.get_arrays", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_4get_arrays(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_v_self), __pyx_v_sort); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_4get_arrays(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_self, PyObject *__pyx_v_sort) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; + int __pyx_t_1; + int __pyx_t_2; PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getstate__"); + __Pyx_RefNannySetupContext("get_arrays", 0); - /* "sklearn/neighbors/ball_tree.pyx":543 - * get state for pickling + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":600 + * so the closer points are listed first. * """ - * return (self.data, # <<<<<<<<<<<<<< - * self.idx_array, - * self.node_centroid_arr, + * if sort: # <<<<<<<<<<<<<< + * self._sort() + * return self.distances_arr, self.indices_arr */ - __Pyx_XDECREF(__pyx_r); - - /* "sklearn/neighbors/ball_tree.pyx":547 - * self.node_centroid_arr, - * self.node_info_arr, - * self.p, # <<<<<<<<<<<<<< - * self.leaf_size, - * self.n_levels, - */ - __pyx_t_1 = PyFloat_FromDouble(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->p); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 547; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_sort); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":548 - * self.node_info_arr, - * self.p, - * self.leaf_size, # <<<<<<<<<<<<<< - * self.n_levels, - * self.n_nodes) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":601 + * """ + * if sort: + * self._sort() # <<<<<<<<<<<<<< + * return self.distances_arr, self.indices_arr + * */ - __pyx_t_2 = __Pyx_PyInt_to_py_npy_int32(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->leaf_size); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_v_self->__pyx_vtab)->_sort(__pyx_v_self); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 601; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; - /* "sklearn/neighbors/ball_tree.pyx":549 - * self.p, - * self.leaf_size, - * self.n_levels, # <<<<<<<<<<<<<< - * self.n_nodes) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":602 + * if sort: + * self._sort() + * return self.distances_arr, self.indices_arr # <<<<<<<<<<<<<< * + * cdef inline DTYPE_t largest(self, ITYPE_t row) except -1: */ - __pyx_t_3 = __Pyx_PyInt_to_py_npy_int32(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->n_levels); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 549; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self->distances_arr)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self->distances_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->distances_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->indices_arr)); + PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_v_self->indices_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->indices_arr)); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":550 - * self.leaf_size, - * self.n_levels, - * self.n_nodes) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":594 + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + * + * def get_arrays(self, sort=True): # <<<<<<<<<<<<<< + * """Get the arrays of distances and indices within the heap. * - * def __setstate__(self, state): */ - __pyx_t_4 = __Pyx_PyInt_to_py_npy_int32(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->n_nodes); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(8); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __Pyx_INCREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data)); - __Pyx_GIVEREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data)); - __Pyx_INCREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array)); - PyTuple_SET_ITEM(__pyx_t_5, 1, ((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array)); - __Pyx_GIVEREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array)); - __Pyx_INCREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr)); - PyTuple_SET_ITEM(__pyx_t_5, 2, ((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr)); - __Pyx_GIVEREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr)); - __Pyx_INCREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr)); - PyTuple_SET_ITEM(__pyx_t_5, 3, ((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr)); - __Pyx_GIVEREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr)); - PyTuple_SET_ITEM(__pyx_t_5, 4, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_5, 5, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_5, 6, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_5, 7, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_r = ((PyObject *)__pyx_t_5); - __pyx_t_5 = 0; - goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BallTree.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NeighborsHeap.get_arrays", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); @@ -3156,907 +5240,478 @@ static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_3__getstate__ return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":552 - * self.n_nodes) +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":604 + * return self.distances_arr, self.indices_arr * - * def __setstate__(self, state): # <<<<<<<<<<<<<< - * """ - * set state for pickling + * cdef inline DTYPE_t largest(self, ITYPE_t row) except -1: # <<<<<<<<<<<<<< + * """Return the largest distance in the given row""" + * return self.distances[row, 0] */ -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_4__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_state); /*proto*/ -static char __pyx_doc_7sklearn_9neighbors_9ball_tree_8BallTree_4__setstate__[] = "\n set state for pickling\n "; -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_4__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_state) { - PyObject *__pyx_r = NULL; +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_t_2; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + Py_ssize_t __pyx_t_2; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate__"); + __Pyx_RefNannySetupContext("largest", 0); - /* "sklearn/neighbors/ball_tree.pyx":556 - * set state for pickling - * """ - * self.data = state[0] # <<<<<<<<<<<<<< - * self.idx_array = state[1] - * self.node_centroid_arr = state[2] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":606 + * cdef inline DTYPE_t largest(self, ITYPE_t row) except -1: + * """Return the largest distance in the given row""" + * return self.distances[row, 0] # <<<<<<<<<<<<<< + * + * cpdef int push(self, ITYPE_t row, DTYPE_t val, ITYPE_t i_val) except -1: */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 556; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 556; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; + if (unlikely(!__pyx_v_self->distances.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 606; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_v_row; + __pyx_t_2 = 0; + __pyx_r = (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->distances.data + __pyx_t_1 * __pyx_v_self->distances.strides[0]) )) + __pyx_t_2)) ))); + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":557 - * """ - * self.data = state[0] - * self.idx_array = state[1] # <<<<<<<<<<<<<< - * self.node_centroid_arr = state[2] - * self.node_info_arr = state[3] - */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 557; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 557; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->idx_array = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/neighbors/ball_tree.pyx":558 - * self.data = state[0] - * self.idx_array = state[1] - * self.node_centroid_arr = state[2] # <<<<<<<<<<<<<< - * self.node_info_arr = state[3] - * self.p = state[4] - */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 2, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 558; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 558; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_centroid_arr = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/neighbors/ball_tree.pyx":559 - * self.idx_array = state[1] - * self.node_centroid_arr = state[2] - * self.node_info_arr = state[3] # <<<<<<<<<<<<<< - * self.p = state[4] - * self.leaf_size = state[5] - */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 3, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr)); - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->node_info_arr = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "sklearn/neighbors/ball_tree.pyx":560 - * self.node_centroid_arr = state[2] - * self.node_info_arr = state[3] - * self.p = state[4] # <<<<<<<<<<<<<< - * self.leaf_size = state[5] - * self.n_levels = state[6] - */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 4, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_2 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->p = __pyx_t_2; - - /* "sklearn/neighbors/ball_tree.pyx":561 - * self.node_info_arr = state[3] - * self.p = state[4] - * self.leaf_size = state[5] # <<<<<<<<<<<<<< - * self.n_levels = state[6] - * self.n_nodes = state[7] - */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 5, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_from_py_npy_int32(__pyx_t_1); if (unlikely((__pyx_t_3 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->leaf_size = __pyx_t_3; - - /* "sklearn/neighbors/ball_tree.pyx":562 - * self.p = state[4] - * self.leaf_size = state[5] - * self.n_levels = state[6] # <<<<<<<<<<<<<< - * self.n_nodes = state[7] - * - */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 6, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_from_py_npy_int32(__pyx_t_1); if (unlikely((__pyx_t_3 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->n_levels = __pyx_t_3; - - /* "sklearn/neighbors/ball_tree.pyx":563 - * self.leaf_size = state[5] - * self.n_levels = state[6] - * self.n_nodes = state[7] # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":604 + * return self.distances_arr, self.indices_arr * - * def query(self, X, k=1, return_distance=True): + * cdef inline DTYPE_t largest(self, ITYPE_t row) except -1: # <<<<<<<<<<<<<< + * """Return the largest distance in the given row""" + * return self.distances[row, 0] */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 7, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_from_py_npy_int32(__pyx_t_1); if (unlikely((__pyx_t_3 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->n_nodes = __pyx_t_3; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BallTree.__setstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NeighborsHeap.largest", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":565 - * self.n_nodes = state[7] +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":608 + * return self.distances[row, 0] * - * def query(self, X, k=1, return_distance=True): # <<<<<<<<<<<<<< - * """ - * query(X, k=1, return_distance=True) + * cpdef int push(self, ITYPE_t row, DTYPE_t val, ITYPE_t i_val) except -1: # <<<<<<<<<<<<<< + * """push (val, i_val) into the given row""" + * cdef ITYPE_t i, ic1, ic2, i_swap */ -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_5query(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_9neighbors_9ball_tree_8BallTree_5query[] = "\n query(X, k=1, return_distance=True)\n\n query the Ball Tree for the k nearest neighbors\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n k : integer (default = 1)\n The number of nearest neighbors to return\n return_distance : boolean (default = True)\n if True, return a tuple (d,i)\n if False, return array i\n\n Returns\n -------\n i : if return_distance == False\n (d,i) : if return_distance == True\n\n d : array of doubles - shape: x.shape[:-1] + (k,)\n each entry gives the list of distances to the\n neighbors of the corresponding point\n (note that distances are not sorted)\n\n i : array of integers - shape: x.shape[:-1] + (k,)\n each entry gives the list of indices of\n neighbors of the corresponding point\n (note that neighbors are not sorted)\n\n Examples\n --------\n Query for k-nearest neighbors\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10,3)) # 10 points in 3 dimensions\n >>> ball_tree = BallTree(X, leaf_size=2) # doctest: +SKIP\n >>> dist, ind = ball_tree.query(X[0], k=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors\n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n "; -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_5query(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_X = 0; - PyObject *__pyx_v_k = 0; - PyObject *__pyx_v_return_distance = 0; - PyObject *__pyx_v_orig_shape = NULL; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_use_max_heap; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_neighbors; - PyArrayObject *__pyx_v_distances = 0; - PyArrayObject *__pyx_v_idx_array = 0; - PyArrayObject *__pyx_v_Xi = 0; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_dist_ptr; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx_ptr; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack __pyx_v_node_stack; - PyObject *__pyx_r = NULL; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_7push(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_push(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_val, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_val, int __pyx_skip_dispatch) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_ic1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_ic2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_swap; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_dist_arr; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_ind_arr; + int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_6; - Py_ssize_t __pyx_t_7; - PyObject *(*__pyx_t_8)(PyObject *); - PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__k,&__pyx_n_s__return_distance,0}; - __Pyx_RefNannySetupContext("query"); - { - PyObject* values[3] = {0,0,0}; - values[1] = ((PyObject *)__pyx_int_1); - values[2] = __pyx_k_19; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__k); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__return_distance); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "query") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } + __Pyx_RefNannySetupContext("push", 0); + /* Check if called by wrapper */ + if (unlikely(__pyx_skip_dispatch)) ; + /* Check if overridden in Python */ + else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_push); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_7push)) { + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_row); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_val); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_i_val); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyInt_As_int(__pyx_t_4); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_r = __pyx_t_6; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; } - __pyx_v_X = values[0]; - __pyx_v_k = values[1]; - __pyx_v_return_distance = values[2]; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("query", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BallTree.query", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __Pyx_INCREF(__pyx_v_X); - /* "sklearn/neighbors/ball_tree.pyx":610 - * [ 0. 0.19662693 0.29473397] - * """ - * self.warning_flag = False # <<<<<<<<<<<<<< - * - * X = array2d(X, dtype=DTYPE, order='C') + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":611 + * """push (val, i_val) into the given row""" + * cdef ITYPE_t i, ic1, ic2, i_swap + * cdef ITYPE_t size = self.distances.shape[1] # <<<<<<<<<<<<<< + * cdef DTYPE_t* dist_arr = &self.distances[row, 0] + * cdef ITYPE_t* ind_arr = &self.indices[row, 0] */ - ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->warning_flag = 0; + if (unlikely(!__pyx_v_self->distances.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 611; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_size = (__pyx_v_self->distances.shape[1]); - /* "sklearn/neighbors/ball_tree.pyx":612 - * self.warning_flag = False - * - * X = array2d(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":612 + * cdef ITYPE_t i, ic1, ic2, i_swap + * cdef ITYPE_t size = self.distances.shape[1] + * cdef DTYPE_t* dist_arr = &self.distances[row, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* ind_arr = &self.indices[row, 0] * - * if X.shape[-1] != self.data.shape[1]: */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__array2d); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(__pyx_v_X); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_X); - __Pyx_GIVEREF(__pyx_v_X); - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_v_X); - __pyx_v_X = __pyx_t_4; - __pyx_t_4 = 0; + if (unlikely(!__pyx_v_self->distances.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = __pyx_v_row; + __pyx_t_8 = 0; + __pyx_v_dist_arr = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->distances.data + __pyx_t_7 * __pyx_v_self->distances.strides[0]) )) + __pyx_t_8)) )))); - /* "sklearn/neighbors/ball_tree.pyx":614 - * X = array2d(X, dtype=DTYPE, order='C') + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":613 + * cdef ITYPE_t size = self.distances.shape[1] + * cdef DTYPE_t* dist_arr = &self.distances[row, 0] + * cdef ITYPE_t* ind_arr = &self.indices[row, 0] # <<<<<<<<<<<<<< * - * if X.shape[-1] != self.data.shape[1]: # <<<<<<<<<<<<<< - * raise ValueError("query data dimension must match BallTree " - * "data dimension") + * # check if val should be in heap */ - __pyx_t_4 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_4, -1, sizeof(long), PyInt_FromLong); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyInt_to_py_Py_intptr_t((((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data->dimensions[1])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyObject_RichCompare(__pyx_t_3, __pyx_t_4, Py_NE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_5) { + if (unlikely(!__pyx_v_self->indices.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 613; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = __pyx_v_row; + __pyx_t_10 = 0; + __pyx_v_ind_arr = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ (__pyx_v_self->indices.data + __pyx_t_9 * __pyx_v_self->indices.strides[0]) )) + __pyx_t_10)) )))); - /* "sklearn/neighbors/ball_tree.pyx":615 - * - * if X.shape[-1] != self.data.shape[1]: - * raise ValueError("query data dimension must match BallTree " # <<<<<<<<<<<<<< - * "data dimension") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":616 * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_21), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 615; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 615; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "sklearn/neighbors/ball_tree.pyx":618 - * "data dimension") + * # check if val should be in heap + * if val > dist_arr[0]: # <<<<<<<<<<<<<< + * return 0 * - * if k > self.data.shape[0]: # <<<<<<<<<<<<<< - * raise ValueError("k must be less than or equal " - * "to the number of training points") */ - __pyx_t_2 = __Pyx_PyInt_to_py_Py_intptr_t((((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data->dimensions[0])); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 618; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyObject_RichCompare(__pyx_v_k, __pyx_t_2, Py_GT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 618; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 618; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_5) { + __pyx_t_11 = ((__pyx_v_val > (__pyx_v_dist_arr[0])) != 0); + if (__pyx_t_11) { - /* "sklearn/neighbors/ball_tree.pyx":619 - * - * if k > self.data.shape[0]: - * raise ValueError("k must be less than or equal " # <<<<<<<<<<<<<< - * "to the number of training points") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":617 + * # check if val should be in heap + * if val > dist_arr[0]: + * return 0 # <<<<<<<<<<<<<< * + * # insert val at position zero */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_23), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + __pyx_r = 0; + goto __pyx_L0; } - __pyx_L7:; - /* "sklearn/neighbors/ball_tree.pyx":623 - * - * # flatten X for iteration - * orig_shape = X.shape # <<<<<<<<<<<<<< - * X = X.reshape((-1, X.shape[-1])) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":620 * - */ - __pyx_t_4 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 623; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_v_orig_shape = __pyx_t_4; - __pyx_t_4 = 0; - - /* "sklearn/neighbors/ball_tree.pyx":624 - * # flatten X for iteration - * orig_shape = X.shape - * X = X.reshape((-1, X.shape[-1])) # <<<<<<<<<<<<<< + * # insert val at position zero + * dist_arr[0] = val # <<<<<<<<<<<<<< + * ind_arr[0] = i_val * - * # for k less than 5, a priority queue is slightly faster */ - __pyx_t_4 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__reshape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_2, -1, sizeof(long), PyInt_FromLong); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(__pyx_int_neg_1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_int_neg_1); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 624; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_v_X); - __pyx_v_X = __pyx_t_2; - __pyx_t_2 = 0; + (__pyx_v_dist_arr[0]) = __pyx_v_val; - /* "sklearn/neighbors/ball_tree.pyx":628 - * # for k less than 5, a priority queue is slightly faster - * # for more neighbors, a max-heap implementation is faster - * cdef ITYPE_t use_max_heap = (k >= 5) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":621 + * # insert val at position zero + * dist_arr[0] = val + * ind_arr[0] = i_val # <<<<<<<<<<<<<< * - * cdef ITYPE_t i + * #descend the heap, swapping values until the max heap criterion is met */ - __pyx_t_2 = PyObject_RichCompare(__pyx_v_k, __pyx_int_5, Py_GE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = __Pyx_PyInt_from_py_npy_int32(__pyx_t_2); if (unlikely((__pyx_t_6 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_use_max_heap = __pyx_t_6; + (__pyx_v_ind_arr[0]) = __pyx_v_i_val; - /* "sklearn/neighbors/ball_tree.pyx":631 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":624 * - * cdef ITYPE_t i - * cdef ITYPE_t n_neighbors = k # <<<<<<<<<<<<<< - * cdef np.ndarray distances = np.empty((X.shape[0], n_neighbors), - * dtype=DTYPE) - */ - __pyx_t_6 = __Pyx_PyInt_from_py_npy_int32(__pyx_v_k); if (unlikely((__pyx_t_6 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 631; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_n_neighbors = __pyx_t_6; - - /* "sklearn/neighbors/ball_tree.pyx":632 - * cdef ITYPE_t i - * cdef ITYPE_t n_neighbors = k - * cdef np.ndarray distances = np.empty((X.shape[0], n_neighbors), # <<<<<<<<<<<<<< - * dtype=DTYPE) - * cdef np.ndarray idx_array = np.empty((X.shape[0], n_neighbors), + * #descend the heap, swapping values until the max heap criterion is met + * i = 0 # <<<<<<<<<<<<<< + * while True: + * ic1 = 2 * i + 1 */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_GetItemInt(__pyx_t_2, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_n_neighbors); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_4 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_1)); - __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_v_i = 0; - /* "sklearn/neighbors/ball_tree.pyx":633 - * cdef ITYPE_t n_neighbors = k - * cdef np.ndarray distances = np.empty((X.shape[0], n_neighbors), - * dtype=DTYPE) # <<<<<<<<<<<<<< - * cdef np.ndarray idx_array = np.empty((X.shape[0], n_neighbors), - * dtype=ITYPE) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":625 + * #descend the heap, swapping values until the max heap criterion is met + * i = 0 + * while True: # <<<<<<<<<<<<<< + * ic1 = 2 * i + 1 + * ic2 = ic1 + 1 */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 633; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyEval_CallObjectWithKeywords(__pyx_t_3, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_distances = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; + while (1) { - /* "sklearn/neighbors/ball_tree.pyx":634 - * cdef np.ndarray distances = np.empty((X.shape[0], n_neighbors), - * dtype=DTYPE) - * cdef np.ndarray idx_array = np.empty((X.shape[0], n_neighbors), # <<<<<<<<<<<<<< - * dtype=ITYPE) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":626 + * i = 0 + * while True: + * ic1 = 2 * i + 1 # <<<<<<<<<<<<<< + * ic2 = ic1 + 1 * */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_4, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_n_neighbors); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_2 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); - __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_v_ic1 = ((2 * __pyx_v_i) + 1); - /* "sklearn/neighbors/ball_tree.pyx":635 - * dtype=DTYPE) - * cdef np.ndarray idx_array = np.empty((X.shape[0], n_neighbors), - * dtype=ITYPE) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":627 + * while True: + * ic1 = 2 * i + 1 + * ic2 = ic1 + 1 # <<<<<<<<<<<<<< * - * # initialize arrays. This is only needed for correct behavior of + * if ic1 >= size: */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_idx_array = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; + __pyx_v_ic2 = (__pyx_v_ic1 + 1); - /* "sklearn/neighbors/ball_tree.pyx":639 - * # initialize arrays. This is only needed for correct behavior of - * # the warning flag. - * distances.fill(-9999) # <<<<<<<<<<<<<< - * idx_array.fill(-9999) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":629 + * ic2 = ic1 + 1 * + * if ic1 >= size: # <<<<<<<<<<<<<< + * break + * elif ic2 >= size: */ - __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_distances), __pyx_n_s__fill); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 639; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_k_tuple_24), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 639; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_11 = ((__pyx_v_ic1 >= __pyx_v_size) != 0); + if (__pyx_t_11) { - /* "sklearn/neighbors/ball_tree.pyx":640 - * # the warning flag. - * distances.fill(-9999) - * idx_array.fill(-9999) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":630 * - * cdef np.ndarray Xi + * if ic1 >= size: + * break # <<<<<<<<<<<<<< + * elif ic2 >= size: + * if dist_arr[ic1] > val: */ - __pyx_t_3 = PyObject_GetAttr(((PyObject *)__pyx_v_idx_array), __pyx_n_s__fill); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_k_tuple_25), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L5_break; + } - /* "sklearn/neighbors/ball_tree.pyx":644 - * cdef np.ndarray Xi - * - * distances[:] = np.inf # <<<<<<<<<<<<<< - * - * cdef DTYPE_t* dist_ptr = distances.data + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":631 + * if ic1 >= size: + * break + * elif ic2 >= size: # <<<<<<<<<<<<<< + * if dist_arr[ic1] > val: + * i_swap = ic1 */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__inf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_v_distances)) { __Pyx_RaiseUnboundLocalError("distances"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} }if (__Pyx_PySequence_SetSlice(((PyObject *)__pyx_v_distances), 0, PY_SSIZE_T_MAX, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_11 = ((__pyx_v_ic2 >= __pyx_v_size) != 0); + if (__pyx_t_11) { - /* "sklearn/neighbors/ball_tree.pyx":646 - * distances[:] = np.inf - * - * cdef DTYPE_t* dist_ptr = distances.data # <<<<<<<<<<<<<< - * cdef ITYPE_t* idx_ptr = idx_array.data - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":632 + * break + * elif ic2 >= size: + * if dist_arr[ic1] > val: # <<<<<<<<<<<<<< + * i_swap = ic1 + * else: */ - __pyx_v_dist_ptr = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_distances->data); + __pyx_t_11 = (((__pyx_v_dist_arr[__pyx_v_ic1]) > __pyx_v_val) != 0); + if (__pyx_t_11) { - /* "sklearn/neighbors/ball_tree.pyx":647 - * - * cdef DTYPE_t* dist_ptr = distances.data - * cdef ITYPE_t* idx_ptr = idx_array.data # <<<<<<<<<<<<<< - * - * cdef stack node_stack + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":633 + * elif ic2 >= size: + * if dist_arr[ic1] > val: + * i_swap = ic1 # <<<<<<<<<<<<<< + * else: + * break */ - __pyx_v_idx_ptr = ((__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *)__pyx_v_idx_array->data); + __pyx_v_i_swap = __pyx_v_ic1; + goto __pyx_L7; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":650 - * - * cdef stack node_stack - * stack_create(&node_stack, self.n_levels + 1) # <<<<<<<<<<<<<< - * - * for i, Xi in enumerate(X): + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":635 + * i_swap = ic1 + * else: + * break # <<<<<<<<<<<<<< + * elif dist_arr[ic1] >= dist_arr[ic2]: + * if val < dist_arr[ic1]: */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_create((&__pyx_v_node_stack), (((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->n_levels + 1)); - - /* "sklearn/neighbors/ball_tree.pyx":652 - * stack_create(&node_stack, self.n_levels + 1) - * - * for i, Xi in enumerate(X): # <<<<<<<<<<<<<< - * self.query_one_(Xi.data, n_neighbors, - * dist_ptr, idx_ptr, &node_stack, use_max_heap) + goto __pyx_L5_break; + } + __pyx_L7:; + goto __pyx_L6; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":636 + * else: + * break + * elif dist_arr[ic1] >= dist_arr[ic2]: # <<<<<<<<<<<<<< + * if val < dist_arr[ic1]: + * i_swap = ic1 + */ + __pyx_t_11 = (((__pyx_v_dist_arr[__pyx_v_ic1]) >= (__pyx_v_dist_arr[__pyx_v_ic2])) != 0); + if (__pyx_t_11) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":637 + * break + * elif dist_arr[ic1] >= dist_arr[ic2]: + * if val < dist_arr[ic1]: # <<<<<<<<<<<<<< + * i_swap = ic1 + * else: */ - __pyx_t_6 = 0; - if (PyList_CheckExact(__pyx_v_X) || PyTuple_CheckExact(__pyx_v_X)) { - __pyx_t_3 = __pyx_v_X; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; - __pyx_t_8 = NULL; - } else { - __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_X); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; - } - for (;;) { - if (PyList_CheckExact(__pyx_t_3)) { - if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; - __pyx_t_2 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_2); __pyx_t_7++; - } else if (PyTuple_CheckExact(__pyx_t_3)) { - if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_2); __pyx_t_7++; - } else { - __pyx_t_2 = __pyx_t_8(__pyx_t_3); - if (unlikely(!__pyx_t_2)) { - if (PyErr_Occurred()) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; + __pyx_t_11 = ((__pyx_v_val < (__pyx_v_dist_arr[__pyx_v_ic1])) != 0); + if (__pyx_t_11) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":638 + * elif dist_arr[ic1] >= dist_arr[ic2]: + * if val < dist_arr[ic1]: + * i_swap = ic1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_swap = __pyx_v_ic1; + goto __pyx_L8; } - __Pyx_GOTREF(__pyx_t_2); + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":640 + * i_swap = ic1 + * else: + * break # <<<<<<<<<<<<<< + * else: + * if val < dist_arr[ic2]: + */ + goto __pyx_L5_break; + } + __pyx_L8:; + goto __pyx_L6; } - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_Xi)); - __pyx_v_Xi = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - __pyx_v_i = __pyx_t_6; - __pyx_t_6 = (__pyx_t_6 + 1); + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":654 - * for i, Xi in enumerate(X): - * self.query_one_(Xi.data, n_neighbors, - * dist_ptr, idx_ptr, &node_stack, use_max_heap) # <<<<<<<<<<<<<< - * - * # if max-heap is used, results must be sorted + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":642 + * break + * else: + * if val < dist_arr[ic2]: # <<<<<<<<<<<<<< + * i_swap = ic2 + * else: */ - ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->__pyx_vtab)->query_one_(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self), ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_Xi->data), __pyx_v_n_neighbors, __pyx_v_dist_ptr, __pyx_v_idx_ptr, (&__pyx_v_node_stack), __pyx_v_use_max_heap); + __pyx_t_11 = ((__pyx_v_val < (__pyx_v_dist_arr[__pyx_v_ic2])) != 0); + if (__pyx_t_11) { - /* "sklearn/neighbors/ball_tree.pyx":657 - * - * # if max-heap is used, results must be sorted - * if use_max_heap: # <<<<<<<<<<<<<< - * sort_dist_idx(dist_ptr, idx_ptr, n_neighbors) - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":643 + * else: + * if val < dist_arr[ic2]: + * i_swap = ic2 # <<<<<<<<<<<<<< + * else: + * break */ - if (__pyx_v_use_max_heap) { + __pyx_v_i_swap = __pyx_v_ic2; + goto __pyx_L9; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":658 - * # if max-heap is used, results must be sorted - * if use_max_heap: - * sort_dist_idx(dist_ptr, idx_ptr, n_neighbors) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":645 + * i_swap = ic2 + * else: + * break # <<<<<<<<<<<<<< * - * dist_ptr += n_neighbors + * dist_arr[i] = dist_arr[i_swap] */ - __pyx_f_7sklearn_9neighbors_9ball_tree_sort_dist_idx(__pyx_v_dist_ptr, __pyx_v_idx_ptr, __pyx_v_n_neighbors); - goto __pyx_L10; + goto __pyx_L5_break; + } + __pyx_L9:; } - __pyx_L10:; + __pyx_L6:; - /* "sklearn/neighbors/ball_tree.pyx":660 - * sort_dist_idx(dist_ptr, idx_ptr, n_neighbors) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":647 + * break * - * dist_ptr += n_neighbors # <<<<<<<<<<<<<< - * idx_ptr += n_neighbors + * dist_arr[i] = dist_arr[i_swap] # <<<<<<<<<<<<<< + * ind_arr[i] = ind_arr[i_swap] * */ - __pyx_v_dist_ptr = (__pyx_v_dist_ptr + __pyx_v_n_neighbors); + (__pyx_v_dist_arr[__pyx_v_i]) = (__pyx_v_dist_arr[__pyx_v_i_swap]); - /* "sklearn/neighbors/ball_tree.pyx":661 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":648 * - * dist_ptr += n_neighbors - * idx_ptr += n_neighbors # <<<<<<<<<<<<<< + * dist_arr[i] = dist_arr[i_swap] + * ind_arr[i] = ind_arr[i_swap] # <<<<<<<<<<<<<< * - * stack_destroy(&node_stack) + * i = i_swap */ - __pyx_v_idx_ptr = (__pyx_v_idx_ptr + __pyx_v_n_neighbors); - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + (__pyx_v_ind_arr[__pyx_v_i]) = (__pyx_v_ind_arr[__pyx_v_i_swap]); - /* "sklearn/neighbors/ball_tree.pyx":663 - * idx_ptr += n_neighbors + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":650 + * ind_arr[i] = ind_arr[i_swap] * - * stack_destroy(&node_stack) # <<<<<<<<<<<<<< + * i = i_swap # <<<<<<<<<<<<<< * - * # deflatten results + * dist_arr[i] = val */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_destroy((&__pyx_v_node_stack)); + __pyx_v_i = __pyx_v_i_swap; + } + __pyx_L5_break:; - /* "sklearn/neighbors/ball_tree.pyx":666 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":652 + * i = i_swap + * + * dist_arr[i] = val # <<<<<<<<<<<<<< + * ind_arr[i] = i_val * - * # deflatten results - * if return_distance: # <<<<<<<<<<<<<< - * return (distances.reshape((orig_shape[:-1]) + (k,)), - * idx_array.reshape((orig_shape[:-1]) + (k,))) */ - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 666; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_5) { + (__pyx_v_dist_arr[__pyx_v_i]) = __pyx_v_val; - /* "sklearn/neighbors/ball_tree.pyx":667 - * # deflatten results - * if return_distance: - * return (distances.reshape((orig_shape[:-1]) + (k,)), # <<<<<<<<<<<<<< - * idx_array.reshape((orig_shape[:-1]) + (k,))) - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":653 + * + * dist_arr[i] = val + * ind_arr[i] = i_val # <<<<<<<<<<<<<< + * + * return 0 */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyObject_GetAttr(((PyObject *)__pyx_v_distances), __pyx_n_s__reshape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PySequence_GetSlice(__pyx_v_orig_shape, 0, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __Pyx_INCREF(__pyx_v_k); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_k); - __Pyx_GIVEREF(__pyx_v_k); - __pyx_t_1 = PyNumber_Add(__pyx_t_2, ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + (__pyx_v_ind_arr[__pyx_v_i]) = __pyx_v_i_val; - /* "sklearn/neighbors/ball_tree.pyx":668 - * if return_distance: - * return (distances.reshape((orig_shape[:-1]) + (k,)), - * idx_array.reshape((orig_shape[:-1]) + (k,))) # <<<<<<<<<<<<<< - * else: - * return idx_array.reshape((orig_shape[:-1]) + (k,)) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":655 + * ind_arr[i] = i_val + * + * return 0 # <<<<<<<<<<<<<< + * + * cdef int _sort(self) except -1: */ - __pyx_t_4 = PyObject_GetAttr(((PyObject *)__pyx_v_idx_array), __pyx_n_s__reshape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PySequence_GetSlice(__pyx_v_orig_shape, 0, -1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(__pyx_v_k); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_k); - __Pyx_GIVEREF(__pyx_v_k); - __pyx_t_9 = PyNumber_Add(__pyx_t_3, ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_9); - __pyx_t_9 = 0; - __pyx_t_9 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_9); - __pyx_t_1 = 0; - __pyx_t_9 = 0; - __pyx_r = ((PyObject *)__pyx_t_2); - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L11; - } - /*else*/ { + __pyx_r = 0; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":670 - * idx_array.reshape((orig_shape[:-1]) + (k,))) - * else: - * return idx_array.reshape((orig_shape[:-1]) + (k,)) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":608 + * return self.distances[row, 0] * - * def query_radius(self, X, r, return_distance=False, + * cpdef int push(self, ITYPE_t row, DTYPE_t val, ITYPE_t i_val) except -1: # <<<<<<<<<<<<<< + * """push (val, i_val) into the given row""" + * cdef ITYPE_t i, ic1, ic2, i_swap */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_idx_array), __pyx_n_s__reshape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 670; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_9 = __Pyx_PySequence_GetSlice(__pyx_v_orig_shape, 0, -1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 670; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 670; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(__pyx_v_k); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_k); - __Pyx_GIVEREF(__pyx_v_k); - __pyx_t_4 = PyNumber_Add(__pyx_t_9, ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 670; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 670; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 670; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - } - __pyx_L11:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BallTree.query", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NeighborsHeap.push", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; - __Pyx_XDECREF(__pyx_v_orig_shape); - __Pyx_XDECREF((PyObject *)__pyx_v_distances); - __Pyx_XDECREF((PyObject *)__pyx_v_idx_array); - __Pyx_XDECREF((PyObject *)__pyx_v_Xi); - __Pyx_XDECREF(__pyx_v_X); - __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":672 - * return idx_array.reshape((orig_shape[:-1]) + (k,)) - * - * def query_radius(self, X, r, return_distance=False, # <<<<<<<<<<<<<< - * count_only=False, sort_results=False): - * """ - */ - -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_6query_radius(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_9neighbors_9ball_tree_8BallTree_6query_radius[] = "\n query_radius(self, X, r, count_only = False):\n\n query the Ball Tree for neighbors within a ball of size r\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n r : distance within which neighbors are returned\n r can be a single value, or an array of values of shape\n x.shape[:-1] if different radii are desired for each point.\n return_distance : boolean (default = False)\n if True, return distances to neighbors of each point\n if False, return only neighbors\n Note that unlike BallTree.query(), setting return_distance=True\n adds to the computation time. Not all distances need to be\n calculated explicitly for return_distance=False. Results are\n not sorted by default: see ``sort_results`` keyword.\n count_only : boolean (default = False)\n if True, return only the count of points within distance r\n if False, return the indices of all points within distance r\n If return_distance==True, setting count_only=True will\n result in an error.\n sort_results : boolean (default = False)\n if True, the distances and indices will be sorted before being\n returned. If False, the results will not be sorted. If\n return_distance == False, setting sort_results = True will\n result in an error.\n\n Returns\n -------\n count : if count_only == True\n ind : if count_only == False and return_distance == False\n (ind, dist) : if count_only == False and return_distance == True\n\n count : array of integers, shape = X.shape[:-1]\n each entry gives the number of neighbors within\n a distance r of the corresponding point.\n\n ind : array of objects, shape = X.shape[:-1]\n each element is a"" numpy integer array listing the indices of\n neighbors of the corresponding point. Note that unlike\n the results of BallTree.query(), the returned neighbors\n are not sorted by distance\n\n dist : array of objects, shape = X.shape[:-1]\n each element is a numpy double array\n listing the distances corresponding to indices in i.\n\n Examples\n --------\n Query for neighbors in a given radius\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10,3)) # 10 points in 3 dimensions\n >>> ball_tree = BallTree(X, leaf_size=2) # doctest: +SKIP\n >>> print ball_tree.query_radius(X[0], r=0.3, count_only=True)\n 3\n >>> ind = ball_tree.query_radius(X[0], r=0.3) # doctest: +SKIP\n >>> print ind # indices of neighbors within distance 0.3\n [3 0 1]\n "; -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_6query_radius(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_X = 0; - PyObject *__pyx_v_r = 0; - PyObject *__pyx_v_return_distance = 0; - PyObject *__pyx_v_count_only = 0; - PyObject *__pyx_v_sort_results = 0; - PyArrayObject *__pyx_v_idx_array = 0; - PyArrayObject *__pyx_v_idx_array_i = 0; - PyArrayObject *__pyx_v_distances = 0; - PyArrayObject *__pyx_v_distances_i = 0; - PyArrayObject *__pyx_v_pt = 0; - PyArrayObject *__pyx_v_count = 0; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_count_i; - PyObject *__pyx_v_orig_shape = NULL; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack __pyx_v_node_stack; - PyObject *__pyx_v_pt_idx = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - Py_ssize_t __pyx_t_10; - PyObject *(*__pyx_t_11)(PyObject *); - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_t_12; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_7push(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_6push[] = "push (val, i_val) into the given row"; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_7push(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_val; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_val; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__r,&__pyx_n_s__return_distance,&__pyx_n_s__count_only,&__pyx_n_s__sort_results,0}; - __Pyx_RefNannySetupContext("query_radius"); + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("push (wrapper)", 0); { - PyObject* values[5] = {0,0,0,0,0}; - values[2] = __pyx_k_26; - values[3] = __pyx_k_27; - values[4] = __pyx_k_28; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_row,&__pyx_n_s_val,&__pyx_n_s_i_val,0}; + PyObject* values[3] = {0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); @@ -4064,3493 +5719,3888 @@ static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_6query_radius default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_row)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__r); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_val)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("query_radius", 0, 2, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 672; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("push", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__return_distance); - if (value) { values[2] = value; kw_args--; } - } - case 3: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__count_only); - if (value) { values[3] = value; kw_args--; } - } - case 4: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sort_results); - if (value) { values[4] = value; kw_args--; } + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_i_val)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("push", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "query_radius") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 672; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "push") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_X = values[0]; - __pyx_v_r = values[1]; - __pyx_v_return_distance = values[2]; - __pyx_v_count_only = values[3]; - __pyx_v_sort_results = values[4]; + __pyx_v_row = __Pyx_PyInt_As_Py_intptr_t(values[0]); if (unlikely((__pyx_v_row == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_val = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_val == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_i_val = __Pyx_PyInt_As_Py_intptr_t(values[2]); if (unlikely((__pyx_v_i_val == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("query_radius", 0, 2, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 672; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("push", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BallTree.query_radius", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NeighborsHeap.push", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __Pyx_INCREF(__pyx_v_X); - __Pyx_INCREF(__pyx_v_r); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_6push(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_v_self), __pyx_v_row, __pyx_v_val, __pyx_v_i_val); - /* "sklearn/neighbors/ball_tree.pyx":738 - * [3 0 1] - * """ - * if count_only and return_distance: # <<<<<<<<<<<<<< - * raise ValueError("count_only and return_distance " - * "cannot both be true") - */ - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_count_only); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 738; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_1) { - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 738; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __pyx_t_2; - } else { - __pyx_t_3 = __pyx_t_1; - } - if (__pyx_t_3) { + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":739 - * """ - * if count_only and return_distance: - * raise ValueError("count_only and return_distance " # <<<<<<<<<<<<<< - * "cannot both be true") +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_6push(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_val, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_val) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("push", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_v_self->__pyx_vtab)->push(__pyx_v_self, __pyx_v_row, __pyx_v_val, __pyx_v_i_val, 1); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NeighborsHeap.push", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":657 + * return 0 * + * cdef int _sort(self) except -1: # <<<<<<<<<<<<<< + * """simultaneously sort the distances and indices""" + * cdef DTYPE_t[:, ::1] distances = self.distances */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_30), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + +static int __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap__sort(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_distances = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_indices = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_2 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_sort", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":659 + * cdef int _sort(self) except -1: + * """simultaneously sort the distances and indices""" + * cdef DTYPE_t[:, ::1] distances = self.distances # <<<<<<<<<<<<<< + * cdef ITYPE_t[:, ::1] indices = self.indices + * cdef ITYPE_t row + */ + if (unlikely(!__pyx_v_self->distances.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_v_self->distances; + __PYX_INC_MEMVIEW(&__pyx_t_1, 1); + __pyx_v_distances = __pyx_t_1; + __pyx_t_1.memview = NULL; + __pyx_t_1.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":660 + * """simultaneously sort the distances and indices""" + * cdef DTYPE_t[:, ::1] distances = self.distances + * cdef ITYPE_t[:, ::1] indices = self.indices # <<<<<<<<<<<<<< + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + */ + if (unlikely(!__pyx_v_self->indices.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = __pyx_v_self->indices; + __PYX_INC_MEMVIEW(&__pyx_t_2, 1); + __pyx_v_indices = __pyx_t_2; + __pyx_t_2.memview = NULL; + __pyx_t_2.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":662 + * cdef ITYPE_t[:, ::1] indices = self.indices + * cdef ITYPE_t row + * for row in range(distances.shape[0]): # <<<<<<<<<<<<<< + * _simultaneous_sort(&distances[row, 0], + * &indices[row, 0], + */ + __pyx_t_3 = (__pyx_v_distances.shape[0]); + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_row = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":663 + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], # <<<<<<<<<<<<<< + * &indices[row, 0], + * distances.shape[1]) + */ + __pyx_t_5 = __pyx_v_row; + __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":664 + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], + * &indices[row, 0], # <<<<<<<<<<<<<< + * distances.shape[1]) + * return 0 + */ + __pyx_t_7 = __pyx_v_row; + __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":663 + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], # <<<<<<<<<<<<<< + * &indices[row, 0], + * distances.shape[1]) + */ + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_9ball_tree__simultaneous_sort((&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_distances.data + __pyx_t_5 * __pyx_v_distances.strides[0]) )) + __pyx_t_6)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ (__pyx_v_indices.data + __pyx_t_7 * __pyx_v_indices.strides[0]) )) + __pyx_t_8)) )))), (__pyx_v_distances.shape[1])); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 663; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; - /* "sklearn/neighbors/ball_tree.pyx":742 - * "cannot both be true") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":666 + * &indices[row, 0], + * distances.shape[1]) + * return 0 # <<<<<<<<<<<<<< + * * - * if sort_results and not return_distance: # <<<<<<<<<<<<<< - * raise ValueError("return_distance must be True if sort_distances " - * "is True") */ - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_sort_results); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 742; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 742; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = (!__pyx_t_1); - __pyx_t_1 = __pyx_t_2; - } else { - __pyx_t_1 = __pyx_t_3; - } - if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":743 - * - * if sort_results and not return_distance: - * raise ValueError("return_distance must be True if sort_distances " # <<<<<<<<<<<<<< - * "is True") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":657 + * return 0 * + * cdef int _sort(self) except -1: # <<<<<<<<<<<<<< + * """simultaneously sort the distances and indices""" + * cdef DTYPE_t[:, ::1] distances = self.distances */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_32), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 743; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 743; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - /* "sklearn/neighbors/ball_tree.pyx":751 + /* function exit code */ + __pyx_L1_error:; + __PYX_XDEC_MEMVIEW(&__pyx_t_1, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_2, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NeighborsHeap._sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_distances, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_indices, 1); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":669 + * * - * # prepare X for query - * X = array2d(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< - * if X.shape[-1] != self.data.shape[1]: - * raise ValueError("query data dimension must match BallTree " + * cdef int _simultaneous_sort(DTYPE_t* dist, ITYPE_t* idx, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """ */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__array2d); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __Pyx_INCREF(__pyx_v_X); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_X); - __Pyx_GIVEREF(__pyx_v_X); - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = PyEval_CallObjectWithKeywords(__pyx_t_4, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_v_X); - __pyx_v_X = __pyx_t_7; - __pyx_t_7 = 0; - /* "sklearn/neighbors/ball_tree.pyx":752 - * # prepare X for query - * X = array2d(X, dtype=DTYPE, order='C') - * if X.shape[-1] != self.data.shape[1]: # <<<<<<<<<<<<<< - * raise ValueError("query data dimension must match BallTree " - * "data dimension") - */ - __pyx_t_7 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 752; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_6 = __Pyx_GetItemInt(__pyx_t_7, -1, sizeof(long), PyInt_FromLong); if (!__pyx_t_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 752; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyInt_to_py_Py_intptr_t((((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data->dimensions[1])); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 752; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_5 = PyObject_RichCompare(__pyx_t_6, __pyx_t_7, Py_NE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 752; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 752; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_1) { +static int __pyx_f_7sklearn_9neighbors_9ball_tree__simultaneous_sort(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_pivot_idx; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_store_idx; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_pivot_val; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + long __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_simultaneous_sort", 0); - /* "sklearn/neighbors/ball_tree.pyx":753 - * X = array2d(X, dtype=DTYPE, order='C') - * if X.shape[-1] != self.data.shape[1]: - * raise ValueError("query data dimension must match BallTree " # <<<<<<<<<<<<<< - * "data dimension") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":684 * + * # in the small-array case, do things efficiently + * if size <= 1: # <<<<<<<<<<<<<< + * pass + * elif size == 2: */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_33), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 753; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 753; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + __pyx_t_1 = ((__pyx_v_size <= 1) != 0); + if (__pyx_t_1) { + goto __pyx_L3; } - __pyx_L8:; - /* "sklearn/neighbors/ball_tree.pyx":757 - * - * # prepare r for query - * r = np.asarray(r, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< - * r = np.atleast_1d(r) - * if r.shape == (1,): + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":686 + * if size <= 1: + * pass + * elif size == 2: # <<<<<<<<<<<<<< + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__asarray); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __Pyx_INCREF(__pyx_v_r); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_r); - __Pyx_GIVEREF(__pyx_v_r); - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PyEval_CallObjectWithKeywords(__pyx_t_7, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_v_r); - __pyx_v_r = __pyx_t_4; - __pyx_t_4 = 0; + __pyx_t_1 = ((__pyx_v_size == 2) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":758 - * # prepare r for query - * r = np.asarray(r, dtype=DTYPE, order='C') - * r = np.atleast_1d(r) # <<<<<<<<<<<<<< - * if r.shape == (1,): - * r = r[0] * np.ones(X.shape[:-1], dtype=np.double) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":687 + * pass + * elif size == 2: + * if dist[0] > dist[1]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 0, 1) + * elif size == 3: */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 758; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__atleast_1d); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 758; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 758; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __Pyx_INCREF(__pyx_v_r); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_r); - __Pyx_GIVEREF(__pyx_v_r); - __pyx_t_5 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 758; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_v_r); - __pyx_v_r = __pyx_t_5; - __pyx_t_5 = 0; + __pyx_t_1 = (((__pyx_v_dist[0]) > (__pyx_v_dist[1])) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":759 - * r = np.asarray(r, dtype=DTYPE, order='C') - * r = np.atleast_1d(r) - * if r.shape == (1,): # <<<<<<<<<<<<<< - * r = r[0] * np.ones(X.shape[:-1], dtype=np.double) - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":688 + * elif size == 2: + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) # <<<<<<<<<<<<<< + * elif size == 3: + * if dist[0] > dist[1]: */ - __pyx_t_5 = PyObject_GetAttr(__pyx_v_r, __pyx_n_s__shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 759; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_4 = PyObject_RichCompare(__pyx_t_5, ((PyObject *)__pyx_k_tuple_34), Py_EQ); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 759; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 759; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_f_7sklearn_9neighbors_9ball_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 0, 1); + goto __pyx_L4; + } + __pyx_L4:; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":689 + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) + * elif size == 3: # <<<<<<<<<<<<<< + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) + */ + __pyx_t_1 = ((__pyx_v_size == 3) != 0); if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":760 - * r = np.atleast_1d(r) - * if r.shape == (1,): - * r = r[0] * np.ones(X.shape[:-1], dtype=np.double) # <<<<<<<<<<<<<< - * else: - * if r.shape != X.shape[:-1]: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":690 + * dual_swap(dist, idx, 0, 1) + * elif size == 3: + * if dist[0] > dist[1]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 0, 1) + * if dist[1] > dist[2]: */ - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_r, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__ones); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_7 = __Pyx_PySequence_GetSlice(__pyx_t_5, 0, -1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __pyx_t_8 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_9 = PyObject_GetAttr(__pyx_t_8, __pyx_n_s__double); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = PyEval_CallObjectWithKeywords(__pyx_t_6, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __pyx_t_7 = PyNumber_Multiply(__pyx_t_4, __pyx_t_9); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_v_r); - __pyx_v_r = __pyx_t_7; - __pyx_t_7 = 0; - goto __pyx_L9; + __pyx_t_1 = (((__pyx_v_dist[0]) > (__pyx_v_dist[1])) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":691 + * elif size == 3: + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) # <<<<<<<<<<<<<< + * if dist[1] > dist[2]: + * dual_swap(dist, idx, 1, 2) + */ + __pyx_f_7sklearn_9neighbors_9ball_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 0, 1); + goto __pyx_L5; + } + __pyx_L5:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":692 + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) + * if dist[1] > dist[2]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 1, 2) + * if dist[0] > dist[1]: + */ + __pyx_t_1 = (((__pyx_v_dist[1]) > (__pyx_v_dist[2])) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":693 + * dual_swap(dist, idx, 0, 1) + * if dist[1] > dist[2]: + * dual_swap(dist, idx, 1, 2) # <<<<<<<<<<<<<< + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) + */ + __pyx_f_7sklearn_9neighbors_9ball_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 1, 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":694 + * if dist[1] > dist[2]: + * dual_swap(dist, idx, 1, 2) + * if dist[0] > dist[1]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 0, 1) + * else: + */ + __pyx_t_1 = (((__pyx_v_dist[0]) > (__pyx_v_dist[1])) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":695 + * dual_swap(dist, idx, 1, 2) + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) # <<<<<<<<<<<<<< + * else: + * # Determine the pivot using the median-of-three rule. + */ + __pyx_f_7sklearn_9neighbors_9ball_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 0, 1); + goto __pyx_L7; + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + goto __pyx_L3; } /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":762 - * r = r[0] * np.ones(X.shape[:-1], dtype=np.double) - * else: - * if r.shape != X.shape[:-1]: # <<<<<<<<<<<<<< - * raise ValueError("r must be broadcastable to X.shape") - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":701 + * # the middle (the pivot value) is moved to the end, and the largest + * # is moved to the pivot index. + * pivot_idx = size / 2 # <<<<<<<<<<<<<< + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) */ - __pyx_t_7 = PyObject_GetAttr(__pyx_v_r, __pyx_n_s__shape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 762; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 762; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_4 = __Pyx_PySequence_GetSlice(__pyx_t_9, 0, -1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 762; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = PyObject_RichCompare(__pyx_t_7, __pyx_t_4, Py_NE); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 762; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 762; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_pivot_idx = (__pyx_v_size / 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":702 + * # is moved to the pivot index. + * pivot_idx = size / 2 + * if dist[0] > dist[size - 1]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 0, size - 1) + * if dist[size - 1] > dist[pivot_idx]: + */ + __pyx_t_1 = (((__pyx_v_dist[0]) > (__pyx_v_dist[(__pyx_v_size - 1)])) != 0); if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":763 - * else: - * if r.shape != X.shape[:-1]: - * raise ValueError("r must be broadcastable to X.shape") # <<<<<<<<<<<<<< - * - * # flatten X and r for iteration + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":703 + * pivot_idx = size / 2 + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) # <<<<<<<<<<<<<< + * if dist[size - 1] > dist[pivot_idx]: + * dual_swap(dist, idx, size - 1, pivot_idx) */ - __pyx_t_9 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_36), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 763; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_Raise(__pyx_t_9, 0, 0, 0); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 763; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + __pyx_f_7sklearn_9neighbors_9ball_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 0, (__pyx_v_size - 1)); + goto __pyx_L8; } - __pyx_L10:; - } - __pyx_L9:; + __pyx_L8:; - /* "sklearn/neighbors/ball_tree.pyx":766 - * - * # flatten X and r for iteration - * orig_shape = X.shape # <<<<<<<<<<<<<< - * X = X.reshape((-1, X.shape[-1])) - * r = r.reshape(-1) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":704 + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) + * if dist[size - 1] > dist[pivot_idx]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, size - 1, pivot_idx) + * if dist[0] > dist[size - 1]: */ - __pyx_t_9 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 766; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_v_orig_shape = __pyx_t_9; - __pyx_t_9 = 0; + __pyx_t_1 = (((__pyx_v_dist[(__pyx_v_size - 1)]) > (__pyx_v_dist[__pyx_v_pivot_idx])) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":767 - * # flatten X and r for iteration - * orig_shape = X.shape - * X = X.reshape((-1, X.shape[-1])) # <<<<<<<<<<<<<< - * r = r.reshape(-1) - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":705 + * dual_swap(dist, idx, 0, size - 1) + * if dist[size - 1] > dist[pivot_idx]: + * dual_swap(dist, idx, size - 1, pivot_idx) # <<<<<<<<<<<<<< + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) */ - __pyx_t_9 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__reshape); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_4 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_7 = __Pyx_GetItemInt(__pyx_t_4, -1, sizeof(long), PyInt_FromLong); if (!__pyx_t_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __Pyx_INCREF(__pyx_int_neg_1); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_int_neg_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - PyTuple_SET_ITEM(__pyx_t_7, 0, ((PyObject *)__pyx_t_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_9, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_v_X); - __pyx_v_X = __pyx_t_4; - __pyx_t_4 = 0; + __pyx_f_7sklearn_9neighbors_9ball_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, (__pyx_v_size - 1), __pyx_v_pivot_idx); - /* "sklearn/neighbors/ball_tree.pyx":768 - * orig_shape = X.shape - * X = X.reshape((-1, X.shape[-1])) - * r = r.reshape(-1) # <<<<<<<<<<<<<< - * - * cdef stack node_stack + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":706 + * if dist[size - 1] > dist[pivot_idx]: + * dual_swap(dist, idx, size - 1, pivot_idx) + * if dist[0] > dist[size - 1]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 0, size - 1) + * pivot_val = dist[size - 1] */ - __pyx_t_4 = PyObject_GetAttr(__pyx_v_r, __pyx_n_s__reshape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_7 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_k_tuple_37), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_v_r); - __pyx_v_r = __pyx_t_7; - __pyx_t_7 = 0; + __pyx_t_1 = (((__pyx_v_dist[0]) > (__pyx_v_dist[(__pyx_v_size - 1)])) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":771 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":707 + * dual_swap(dist, idx, size - 1, pivot_idx) + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) # <<<<<<<<<<<<<< + * pivot_val = dist[size - 1] * - * cdef stack node_stack - * stack_create(&node_stack, self.n_levels + 1) # <<<<<<<<<<<<<< - * - * if count_only: */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_create((&__pyx_v_node_stack), (((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->n_levels + 1)); + __pyx_f_7sklearn_9neighbors_9ball_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 0, (__pyx_v_size - 1)); + goto __pyx_L10; + } + __pyx_L10:; + goto __pyx_L9; + } + __pyx_L9:; - /* "sklearn/neighbors/ball_tree.pyx":773 - * stack_create(&node_stack, self.n_levels + 1) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":708 + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) + * pivot_val = dist[size - 1] # <<<<<<<<<<<<<< * - * if count_only: # <<<<<<<<<<<<<< - * count = np.zeros(X.shape[0], ITYPE) - * for pt_idx, pt in enumerate(X): + * # partition indices about pivot. At the end of this operation, */ - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_count_only); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 773; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_1) { + __pyx_v_pivot_val = (__pyx_v_dist[(__pyx_v_size - 1)]); - /* "sklearn/neighbors/ball_tree.pyx":774 - * - * if count_only: - * count = np.zeros(X.shape[0], ITYPE) # <<<<<<<<<<<<<< - * for pt_idx, pt in enumerate(X): - * count[pt_idx] = self.query_radius_count_(pt.data, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":713 + * # pivot_idx will contain the pivot value, everything to the left + * # will be smaller, and everything to the right will be larger. + * store_idx = 0 # <<<<<<<<<<<<<< + * for i in range(size - 1): + * if dist[i] < pivot_val: */ - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__zeros); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = __Pyx_GetItemInt(__pyx_t_7, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_9 = 0; - __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_count = ((PyArrayObject *)__pyx_t_7); - __pyx_t_7 = 0; + __pyx_v_store_idx = 0; - /* "sklearn/neighbors/ball_tree.pyx":775 - * if count_only: - * count = np.zeros(X.shape[0], ITYPE) - * for pt_idx, pt in enumerate(X): # <<<<<<<<<<<<<< - * count[pt_idx] = self.query_radius_count_(pt.data, - * r[pt_idx], - */ - __Pyx_INCREF(__pyx_int_0); - __pyx_t_7 = __pyx_int_0; - if (PyList_CheckExact(__pyx_v_X) || PyTuple_CheckExact(__pyx_v_X)) { - __pyx_t_5 = __pyx_v_X; __Pyx_INCREF(__pyx_t_5); __pyx_t_10 = 0; - __pyx_t_11 = NULL; - } else { - __pyx_t_10 = -1; __pyx_t_5 = PyObject_GetIter(__pyx_v_X); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_11 = Py_TYPE(__pyx_t_5)->tp_iternext; - } - for (;;) { - if (PyList_CheckExact(__pyx_t_5)) { - if (__pyx_t_10 >= PyList_GET_SIZE(__pyx_t_5)) break; - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_5, __pyx_t_10); __Pyx_INCREF(__pyx_t_4); __pyx_t_10++; - } else if (PyTuple_CheckExact(__pyx_t_5)) { - if (__pyx_t_10 >= PyTuple_GET_SIZE(__pyx_t_5)) break; - __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_5, __pyx_t_10); __Pyx_INCREF(__pyx_t_4); __pyx_t_10++; - } else { - __pyx_t_4 = __pyx_t_11(__pyx_t_5); - if (unlikely(!__pyx_t_4)) { - if (PyErr_Occurred()) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_4); - } - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_pt)); - __pyx_v_pt = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; - __Pyx_INCREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_v_pt_idx); - __pyx_v_pt_idx = __pyx_t_7; - __pyx_t_4 = PyNumber_Add(__pyx_t_7, __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_7); - __pyx_t_7 = __pyx_t_4; - __pyx_t_4 = 0; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":714 + * # will be smaller, and everything to the right will be larger. + * store_idx = 0 + * for i in range(size - 1): # <<<<<<<<<<<<<< + * if dist[i] < pivot_val: + * dual_swap(dist, idx, i, store_idx) + */ + __pyx_t_2 = (__pyx_v_size - 1); + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; - /* "sklearn/neighbors/ball_tree.pyx":777 - * for pt_idx, pt in enumerate(X): - * count[pt_idx] = self.query_radius_count_(pt.data, - * r[pt_idx], # <<<<<<<<<<<<<< - * &node_stack) - * elif not return_distance: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":715 + * store_idx = 0 + * for i in range(size - 1): + * if dist[i] < pivot_val: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, i, store_idx) + * store_idx += 1 */ - __pyx_t_4 = PyObject_GetItem(__pyx_v_r, __pyx_v_pt_idx); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_12 = __pyx_PyFloat_AsDouble(__pyx_t_4); if (unlikely((__pyx_t_12 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_1 = (((__pyx_v_dist[__pyx_v_i]) < __pyx_v_pivot_val) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":778 - * count[pt_idx] = self.query_radius_count_(pt.data, - * r[pt_idx], - * &node_stack) # <<<<<<<<<<<<<< - * elif not return_distance: - * idx_array = np.empty(X.shape[0], dtype='object') + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":716 + * for i in range(size - 1): + * if dist[i] < pivot_val: + * dual_swap(dist, idx, i, store_idx) # <<<<<<<<<<<<<< + * store_idx += 1 + * dual_swap(dist, idx, store_idx, size - 1) */ - __pyx_t_4 = __Pyx_PyInt_to_py_npy_int32(((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->__pyx_vtab)->query_radius_count_(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self), ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_pt->data), __pyx_t_12, (&__pyx_v_node_stack))); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_f_7sklearn_9neighbors_9ball_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, __pyx_v_i, __pyx_v_store_idx); - /* "sklearn/neighbors/ball_tree.pyx":776 - * count = np.zeros(X.shape[0], ITYPE) - * for pt_idx, pt in enumerate(X): - * count[pt_idx] = self.query_radius_count_(pt.data, # <<<<<<<<<<<<<< - * r[pt_idx], - * &node_stack) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":717 + * if dist[i] < pivot_val: + * dual_swap(dist, idx, i, store_idx) + * store_idx += 1 # <<<<<<<<<<<<<< + * dual_swap(dist, idx, store_idx, size - 1) + * pivot_idx = store_idx */ - if (PyObject_SetItem(((PyObject *)__pyx_v_count), __pyx_v_pt_idx, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_store_idx = (__pyx_v_store_idx + 1); + goto __pyx_L13; + } + __pyx_L13:; } - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L11; - } - /* "sklearn/neighbors/ball_tree.pyx":779 - * r[pt_idx], - * &node_stack) - * elif not return_distance: # <<<<<<<<<<<<<< - * idx_array = np.empty(X.shape[0], dtype='object') - * idx_array_i = np.empty(self.data.shape[0], dtype=ITYPE) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":718 + * dual_swap(dist, idx, i, store_idx) + * store_idx += 1 + * dual_swap(dist, idx, store_idx, size - 1) # <<<<<<<<<<<<<< + * pivot_idx = store_idx + * */ - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 779; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = (!__pyx_t_1); - if (__pyx_t_3) { + __pyx_f_7sklearn_9neighbors_9ball_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, __pyx_v_store_idx, (__pyx_v_size - 1)); - /* "sklearn/neighbors/ball_tree.pyx":780 - * &node_stack) - * elif not return_distance: - * idx_array = np.empty(X.shape[0], dtype='object') # <<<<<<<<<<<<<< - * idx_array_i = np.empty(self.data.shape[0], dtype=ITYPE) - * for pt_idx, pt in enumerate(X): + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":719 + * store_idx += 1 + * dual_swap(dist, idx, store_idx, size - 1) + * pivot_idx = store_idx # <<<<<<<<<<<<<< + * + * # recursively sort each side of the pivot */ - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = __Pyx_GetItemInt(__pyx_t_7, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), ((PyObject *)__pyx_n_s__object)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_9 = PyEval_CallObjectWithKeywords(__pyx_t_5, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_9) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_9, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_idx_array = ((PyArrayObject *)__pyx_t_9); - __pyx_t_9 = 0; + __pyx_v_pivot_idx = __pyx_v_store_idx; - /* "sklearn/neighbors/ball_tree.pyx":781 - * elif not return_distance: - * idx_array = np.empty(X.shape[0], dtype='object') - * idx_array_i = np.empty(self.data.shape[0], dtype=ITYPE) # <<<<<<<<<<<<<< - * for pt_idx, pt in enumerate(X): - * count_i = self.query_radius_idx_only_( + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":722 + * + * # recursively sort each side of the pivot + * if pivot_idx > 1: # <<<<<<<<<<<<<< + * _simultaneous_sort(dist, idx, pivot_idx) + * if pivot_idx + 2 < size: */ - __pyx_t_9 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_9, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = __Pyx_PyInt_to_py_Py_intptr_t((((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data->dimensions[0])); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_9); - __pyx_t_9 = 0; - __pyx_t_9 = PyDict_New(); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_9)); - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - if (PyDict_SetItem(__pyx_t_9, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyEval_CallObjectWithKeywords(__pyx_t_4, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_9)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_idx_array_i = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; + __pyx_t_1 = ((__pyx_v_pivot_idx > 1) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":782 - * idx_array = np.empty(X.shape[0], dtype='object') - * idx_array_i = np.empty(self.data.shape[0], dtype=ITYPE) - * for pt_idx, pt in enumerate(X): # <<<<<<<<<<<<<< - * count_i = self.query_radius_idx_only_( - * pt.data, - */ - __Pyx_INCREF(__pyx_int_0); - __pyx_t_5 = __pyx_int_0; - if (PyList_CheckExact(__pyx_v_X) || PyTuple_CheckExact(__pyx_v_X)) { - __pyx_t_9 = __pyx_v_X; __Pyx_INCREF(__pyx_t_9); __pyx_t_10 = 0; - __pyx_t_11 = NULL; - } else { - __pyx_t_10 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_v_X); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 782; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_11 = Py_TYPE(__pyx_t_9)->tp_iternext; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":723 + * # recursively sort each side of the pivot + * if pivot_idx > 1: + * _simultaneous_sort(dist, idx, pivot_idx) # <<<<<<<<<<<<<< + * if pivot_idx + 2 < size: + * _simultaneous_sort(dist + pivot_idx + 1, + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree__simultaneous_sort(__pyx_v_dist, __pyx_v_idx, __pyx_v_pivot_idx); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; } - for (;;) { - if (PyList_CheckExact(__pyx_t_9)) { - if (__pyx_t_10 >= PyList_GET_SIZE(__pyx_t_9)) break; - __pyx_t_7 = PyList_GET_ITEM(__pyx_t_9, __pyx_t_10); __Pyx_INCREF(__pyx_t_7); __pyx_t_10++; - } else if (PyTuple_CheckExact(__pyx_t_9)) { - if (__pyx_t_10 >= PyTuple_GET_SIZE(__pyx_t_9)) break; - __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_10); __Pyx_INCREF(__pyx_t_7); __pyx_t_10++; - } else { - __pyx_t_7 = __pyx_t_11(__pyx_t_9); - if (unlikely(!__pyx_t_7)) { - if (PyErr_Occurred()) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 782; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_7); - } - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 782; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_pt)); - __pyx_v_pt = ((PyArrayObject *)__pyx_t_7); - __pyx_t_7 = 0; - __Pyx_INCREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_v_pt_idx); - __pyx_v_pt_idx = __pyx_t_5; - __pyx_t_7 = PyNumber_Add(__pyx_t_5, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 782; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); - __pyx_t_5 = __pyx_t_7; - __pyx_t_7 = 0; + __pyx_L14:; - /* "sklearn/neighbors/ball_tree.pyx":785 - * count_i = self.query_radius_idx_only_( - * pt.data, - * r[pt_idx], # <<<<<<<<<<<<<< - * idx_array_i.data, - * &node_stack) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":724 + * if pivot_idx > 1: + * _simultaneous_sort(dist, idx, pivot_idx) + * if pivot_idx + 2 < size: # <<<<<<<<<<<<<< + * _simultaneous_sort(dist + pivot_idx + 1, + * idx + pivot_idx + 1, */ - __pyx_t_7 = PyObject_GetItem(__pyx_v_r, __pyx_v_pt_idx); if (!__pyx_t_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 785; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_12 = __pyx_PyFloat_AsDouble(__pyx_t_7); if (unlikely((__pyx_t_12 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 785; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_1 = (((__pyx_v_pivot_idx + 2) < __pyx_v_size) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":725 + * _simultaneous_sort(dist, idx, pivot_idx) + * if pivot_idx + 2 < size: + * _simultaneous_sort(dist + pivot_idx + 1, # <<<<<<<<<<<<<< + * idx + pivot_idx + 1, + * size - pivot_idx - 1) + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree__simultaneous_sort(((__pyx_v_dist + __pyx_v_pivot_idx) + 1), ((__pyx_v_idx + __pyx_v_pivot_idx) + 1), ((__pyx_v_size - __pyx_v_pivot_idx) - 1)); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L15; + } + __pyx_L15:; + } + __pyx_L3:; - /* "sklearn/neighbors/ball_tree.pyx":787 - * r[pt_idx], - * idx_array_i.data, - * &node_stack) # <<<<<<<<<<<<<< - * idx_array[pt_idx] = idx_array_i[:count_i].copy() + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":728 + * idx + pivot_idx + 1, + * size - pivot_idx - 1) + * return 0 # <<<<<<<<<<<<<< * + * #------------------------------------------------------------ */ - __pyx_v_count_i = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->__pyx_vtab)->query_radius_idx_only_(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self), ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_pt->data), __pyx_t_12, ((__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *)__pyx_v_idx_array_i->data), (&__pyx_v_node_stack)); + __pyx_r = 0; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":788 - * idx_array_i.data, - * &node_stack) - * idx_array[pt_idx] = idx_array_i[:count_i].copy() # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":669 * - * else: + * + * cdef int _simultaneous_sort(DTYPE_t* dist, ITYPE_t* idx, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """ */ - __pyx_t_7 = __Pyx_PySequence_GetSlice(((PyObject *)__pyx_v_idx_array_i), 0, __pyx_v_count_i); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 788; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__copy); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 788; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 788; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyObject_SetItem(((PyObject *)__pyx_v_idx_array), __pyx_v_pt_idx, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 788; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L11; - } - /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":791 + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree._simultaneous_sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":734 + * # this computes the equivalent of + * # j_max = np.argmax(np.max(data, 0) - np.min(data, 0)) + * cdef ITYPE_t find_node_split_dim(DTYPE_t* data, # <<<<<<<<<<<<<< + * ITYPE_t* node_indices, + * ITYPE_t n_features, + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_find_node_split_dim(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_node_indices, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_points) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_min_val; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_max_val; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_val; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_max_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j_max; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + int __pyx_t_5; + __Pyx_RefNannySetupContext("find_node_split_dim", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":767 + * cdef ITYPE_t i, j, j_max + * + * j_max = 0 # <<<<<<<<<<<<<< + * max_spread = 0 * - * else: - * idx_array = np.empty(X.shape[0], dtype='object') # <<<<<<<<<<<<<< - * distances = np.empty(X.shape[0], dtype='object') - * idx_array_i = np.empty(self.data.shape[0], dtype=ITYPE) */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_9 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_7 = __Pyx_GetItemInt(__pyx_t_5, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), ((PyObject *)__pyx_n_s__object)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PyEval_CallObjectWithKeywords(__pyx_t_9, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_idx_array = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; + __pyx_v_j_max = 0; - /* "sklearn/neighbors/ball_tree.pyx":792 - * else: - * idx_array = np.empty(X.shape[0], dtype='object') - * distances = np.empty(X.shape[0], dtype='object') # <<<<<<<<<<<<<< - * idx_array_i = np.empty(self.data.shape[0], dtype=ITYPE) - * distances_i = np.empty(self.data.shape[0], dtype=DTYPE) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":768 + * + * j_max = 0 + * max_spread = 0 # <<<<<<<<<<<<<< + * + * for j in range(n_features): */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_4, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), ((PyObject *)__pyx_n_s__object)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_9 = PyEval_CallObjectWithKeywords(__pyx_t_7, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_9) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_9, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_distances = ((PyArrayObject *)__pyx_t_9); - __pyx_t_9 = 0; + __pyx_v_max_spread = 0.0; - /* "sklearn/neighbors/ball_tree.pyx":793 - * idx_array = np.empty(X.shape[0], dtype='object') - * distances = np.empty(X.shape[0], dtype='object') - * idx_array_i = np.empty(self.data.shape[0], dtype=ITYPE) # <<<<<<<<<<<<<< - * distances_i = np.empty(self.data.shape[0], dtype=DTYPE) - * for pt_idx, pt in enumerate(X): + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":770 + * max_spread = 0 + * + * for j in range(n_features): # <<<<<<<<<<<<<< + * max_val = data[node_indices[0] * n_features + j] + * min_val = max_val */ - __pyx_t_9 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_9, __pyx_n_s__empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = __Pyx_PyInt_to_py_Py_intptr_t((((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data->dimensions[0])); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_9); - __pyx_t_9 = 0; - __pyx_t_9 = PyDict_New(); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_9)); - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - if (PyDict_SetItem(__pyx_t_9, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyEval_CallObjectWithKeywords(__pyx_t_5, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_9)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_idx_array_i = ((PyArrayObject *)__pyx_t_7); - __pyx_t_7 = 0; + __pyx_t_1 = __pyx_v_n_features; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; - /* "sklearn/neighbors/ball_tree.pyx":794 - * distances = np.empty(X.shape[0], dtype='object') - * idx_array_i = np.empty(self.data.shape[0], dtype=ITYPE) - * distances_i = np.empty(self.data.shape[0], dtype=DTYPE) # <<<<<<<<<<<<<< - * for pt_idx, pt in enumerate(X): - * count_i = self.query_radius_distances_( + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":771 + * + * for j in range(n_features): + * max_val = data[node_indices[0] * n_features + j] # <<<<<<<<<<<<<< + * min_val = max_val + * for i in range(1, n_points): */ - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__empty); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyInt_to_py_Py_intptr_t((((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data->dimensions[0])); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyEval_CallObjectWithKeywords(__pyx_t_9, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_distances_i = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; + __pyx_v_max_val = (__pyx_v_data[(((__pyx_v_node_indices[0]) * __pyx_v_n_features) + __pyx_v_j)]); - /* "sklearn/neighbors/ball_tree.pyx":795 - * idx_array_i = np.empty(self.data.shape[0], dtype=ITYPE) - * distances_i = np.empty(self.data.shape[0], dtype=DTYPE) - * for pt_idx, pt in enumerate(X): # <<<<<<<<<<<<<< - * count_i = self.query_radius_distances_( - * pt.data, - */ - __Pyx_INCREF(__pyx_int_0); - __pyx_t_5 = __pyx_int_0; - if (PyList_CheckExact(__pyx_v_X) || PyTuple_CheckExact(__pyx_v_X)) { - __pyx_t_7 = __pyx_v_X; __Pyx_INCREF(__pyx_t_7); __pyx_t_10 = 0; - __pyx_t_11 = NULL; - } else { - __pyx_t_10 = -1; __pyx_t_7 = PyObject_GetIter(__pyx_v_X); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_11 = Py_TYPE(__pyx_t_7)->tp_iternext; - } - for (;;) { - if (PyList_CheckExact(__pyx_t_7)) { - if (__pyx_t_10 >= PyList_GET_SIZE(__pyx_t_7)) break; - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_7, __pyx_t_10); __Pyx_INCREF(__pyx_t_4); __pyx_t_10++; - } else if (PyTuple_CheckExact(__pyx_t_7)) { - if (__pyx_t_10 >= PyTuple_GET_SIZE(__pyx_t_7)) break; - __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_7, __pyx_t_10); __Pyx_INCREF(__pyx_t_4); __pyx_t_10++; - } else { - __pyx_t_4 = __pyx_t_11(__pyx_t_7); - if (unlikely(!__pyx_t_4)) { - if (PyErr_Occurred()) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_4); - } - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_pt)); - __pyx_v_pt = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; - __Pyx_INCREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_v_pt_idx); - __pyx_v_pt_idx = __pyx_t_5; - __pyx_t_4 = PyNumber_Add(__pyx_t_5, __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); - __pyx_t_5 = __pyx_t_4; - __pyx_t_4 = 0; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":772 + * for j in range(n_features): + * max_val = data[node_indices[0] * n_features + j] + * min_val = max_val # <<<<<<<<<<<<<< + * for i in range(1, n_points): + * val = data[node_indices[i] * n_features + j] + */ + __pyx_v_min_val = __pyx_v_max_val; - /* "sklearn/neighbors/ball_tree.pyx":798 - * count_i = self.query_radius_distances_( - * pt.data, - * r[pt_idx], # <<<<<<<<<<<<<< - * idx_array_i.data, - * distances_i.data, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":773 + * max_val = data[node_indices[0] * n_features + j] + * min_val = max_val + * for i in range(1, n_points): # <<<<<<<<<<<<<< + * val = data[node_indices[i] * n_features + j] + * max_val = fmax(max_val, val) */ - __pyx_t_4 = PyObject_GetItem(__pyx_v_r, __pyx_v_pt_idx); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_12 = __pyx_PyFloat_AsDouble(__pyx_t_4); if (unlikely((__pyx_t_12 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_3 = __pyx_v_n_points; + for (__pyx_t_4 = 1; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; - /* "sklearn/neighbors/ball_tree.pyx":801 - * idx_array_i.data, - * distances_i.data, - * &node_stack) # <<<<<<<<<<<<<< - * if sort_results: - * sort_dist_idx(distances_i.data, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":774 + * min_val = max_val + * for i in range(1, n_points): + * val = data[node_indices[i] * n_features + j] # <<<<<<<<<<<<<< + * max_val = fmax(max_val, val) + * min_val = fmin(min_val, val) */ - __pyx_v_count_i = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->__pyx_vtab)->query_radius_distances_(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self), ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_pt->data), __pyx_t_12, ((__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *)__pyx_v_idx_array_i->data), ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_distances_i->data), (&__pyx_v_node_stack)); + __pyx_v_val = (__pyx_v_data[(((__pyx_v_node_indices[__pyx_v_i]) * __pyx_v_n_features) + __pyx_v_j)]); - /* "sklearn/neighbors/ball_tree.pyx":802 - * distances_i.data, - * &node_stack) - * if sort_results: # <<<<<<<<<<<<<< - * sort_dist_idx(distances_i.data, - * idx_array_i.data, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":775 + * for i in range(1, n_points): + * val = data[node_indices[i] * n_features + j] + * max_val = fmax(max_val, val) # <<<<<<<<<<<<<< + * min_val = fmin(min_val, val) + * spread = max_val - min_val */ - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_sort_results); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_3) { + __pyx_v_max_val = __pyx_f_7sklearn_9neighbors_9ball_tree_fmax(__pyx_v_max_val, __pyx_v_val); - /* "sklearn/neighbors/ball_tree.pyx":805 - * sort_dist_idx(distances_i.data, - * idx_array_i.data, - * count_i) # <<<<<<<<<<<<<< - * - * idx_array[pt_idx] = idx_array_i[:count_i].copy() + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":776 + * val = data[node_indices[i] * n_features + j] + * max_val = fmax(max_val, val) + * min_val = fmin(min_val, val) # <<<<<<<<<<<<<< + * spread = max_val - min_val + * if spread > max_spread: */ - __pyx_f_7sklearn_9neighbors_9ball_tree_sort_dist_idx(((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_distances_i->data), ((__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *)__pyx_v_idx_array_i->data), __pyx_v_count_i); - goto __pyx_L18; - } - __pyx_L18:; + __pyx_v_min_val = __pyx_f_7sklearn_9neighbors_9ball_tree_fmin(__pyx_v_min_val, __pyx_v_val); + } - /* "sklearn/neighbors/ball_tree.pyx":807 - * count_i) - * - * idx_array[pt_idx] = idx_array_i[:count_i].copy() # <<<<<<<<<<<<<< - * distances[pt_idx] = distances_i[:count_i].copy() - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":777 + * max_val = fmax(max_val, val) + * min_val = fmin(min_val, val) + * spread = max_val - min_val # <<<<<<<<<<<<<< + * if spread > max_spread: + * max_spread = spread */ - __pyx_t_4 = __Pyx_PySequence_GetSlice(((PyObject *)__pyx_v_idx_array_i), 0, __pyx_v_count_i); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_9 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__copy); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_9, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - if (PyObject_SetItem(((PyObject *)__pyx_v_idx_array), __pyx_v_pt_idx, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_spread = (__pyx_v_max_val - __pyx_v_min_val); - /* "sklearn/neighbors/ball_tree.pyx":808 - * - * idx_array[pt_idx] = idx_array_i[:count_i].copy() - * distances[pt_idx] = distances_i[:count_i].copy() # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":778 + * min_val = fmin(min_val, val) + * spread = max_val - min_val + * if spread > max_spread: # <<<<<<<<<<<<<< + * max_spread = spread + * j_max = j + */ + __pyx_t_5 = ((__pyx_v_spread > __pyx_v_max_spread) != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":779 + * spread = max_val - min_val + * if spread > max_spread: + * max_spread = spread # <<<<<<<<<<<<<< + * j_max = j + * return j_max + */ + __pyx_v_max_spread = __pyx_v_spread; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":780 + * if spread > max_spread: + * max_spread = spread + * j_max = j # <<<<<<<<<<<<<< + * return j_max * - * stack_destroy(&node_stack) */ - __pyx_t_4 = __Pyx_PySequence_GetSlice(((PyObject *)__pyx_v_distances_i), 0, __pyx_v_count_i); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 808; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_9 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__copy); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 808; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_9, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 808; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - if (PyObject_SetItem(((PyObject *)__pyx_v_distances), __pyx_v_pt_idx, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 808; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_j_max = __pyx_v_j; + goto __pyx_L7; } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_L7:; } - __pyx_L11:; - /* "sklearn/neighbors/ball_tree.pyx":810 - * distances[pt_idx] = distances_i[:count_i].copy() + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":781 + * max_spread = spread + * j_max = j + * return j_max # <<<<<<<<<<<<<< * - * stack_destroy(&node_stack) # <<<<<<<<<<<<<< * - * # deflatten results */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_destroy((&__pyx_v_node_stack)); + __pyx_r = __pyx_v_j_max; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":734 + * # this computes the equivalent of + * # j_max = np.argmax(np.max(data, 0) - np.min(data, 0)) + * cdef ITYPE_t find_node_split_dim(DTYPE_t* data, # <<<<<<<<<<<<<< + * ITYPE_t* node_indices, + * ITYPE_t n_features, + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":813 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":784 * - * # deflatten results - * if count_only: # <<<<<<<<<<<<<< - * return count.reshape(orig_shape[:-1]) - * elif return_distance: + * + * cdef int partition_node_indices(DTYPE_t* data, # <<<<<<<<<<<<<< + * ITYPE_t* node_indices, + * ITYPE_t split_dim, */ - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_count_only); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_3) { - /* "sklearn/neighbors/ball_tree.pyx":814 - * # deflatten results - * if count_only: - * return count.reshape(orig_shape[:-1]) # <<<<<<<<<<<<<< - * elif return_distance: - * return (idx_array.reshape(orig_shape[:-1]), +static int __pyx_f_7sklearn_9neighbors_9ball_tree_partition_node_indices(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_node_indices, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_split_dim, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_split_index, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_points) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_left; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_right; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_midindex; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d2; + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("partition_node_indices", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":829 + * cdef ITYPE_t left, right, midindex, i + * cdef DTYPE_t d1, d2 + * left = 0 # <<<<<<<<<<<<<< + * right = n_points - 1 + * */ - __Pyx_XDECREF(__pyx_r); - if (unlikely(!__pyx_v_count)) { __Pyx_RaiseUnboundLocalError("count"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 814; __pyx_clineno = __LINE__; goto __pyx_L1_error;} }__pyx_t_5 = PyObject_GetAttr(((PyObject *)__pyx_v_count), __pyx_n_s__reshape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 814; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_7 = __Pyx_PySequence_GetSlice(__pyx_v_orig_shape, 0, -1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 814; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 814; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 814; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_r = __pyx_t_7; - __pyx_t_7 = 0; - goto __pyx_L0; - goto __pyx_L19; - } + __pyx_v_left = 0; - /* "sklearn/neighbors/ball_tree.pyx":815 - * if count_only: - * return count.reshape(orig_shape[:-1]) - * elif return_distance: # <<<<<<<<<<<<<< - * return (idx_array.reshape(orig_shape[:-1]), - * distances.reshape(orig_shape[:-1])) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":830 + * cdef DTYPE_t d1, d2 + * left = 0 + * right = n_points - 1 # <<<<<<<<<<<<<< + * + * while True: */ - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 815; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_3) { + __pyx_v_right = (__pyx_v_n_points - 1); - /* "sklearn/neighbors/ball_tree.pyx":816 - * return count.reshape(orig_shape[:-1]) - * elif return_distance: - * return (idx_array.reshape(orig_shape[:-1]), # <<<<<<<<<<<<<< - * distances.reshape(orig_shape[:-1])) - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":832 + * right = n_points - 1 + * + * while True: # <<<<<<<<<<<<<< + * midindex = left + * for i in range(left, right): */ - __Pyx_XDECREF(__pyx_r); - if (unlikely(!__pyx_v_idx_array)) { __Pyx_RaiseUnboundLocalError("idx_array"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} }__pyx_t_7 = PyObject_GetAttr(((PyObject *)__pyx_v_idx_array), __pyx_n_s__reshape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = __Pyx_PySequence_GetSlice(__pyx_v_orig_shape, 0, -1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (unlikely(!__pyx_v_distances)) { __Pyx_RaiseUnboundLocalError("distances"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} }__pyx_t_5 = PyObject_GetAttr(((PyObject *)__pyx_v_distances), __pyx_n_s__reshape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/neighbors/ball_tree.pyx":817 - * elif return_distance: - * return (idx_array.reshape(orig_shape[:-1]), - * distances.reshape(orig_shape[:-1])) # <<<<<<<<<<<<<< - * else: - * return idx_array.reshape(orig_shape[:-1]) - */ - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_7 = __Pyx_PySequence_GetSlice(__pyx_v_orig_shape, 0, -1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_9)); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; - __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_9)); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_4 = 0; - __pyx_t_7 = 0; - __pyx_r = ((PyObject *)__pyx_t_9); - __pyx_t_9 = 0; - goto __pyx_L0; - goto __pyx_L19; - } - /*else*/ { + while (1) { - /* "sklearn/neighbors/ball_tree.pyx":819 - * distances.reshape(orig_shape[:-1])) - * else: - * return idx_array.reshape(orig_shape[:-1]) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":833 * - * @cython.cdivision(True) + * while True: + * midindex = left # <<<<<<<<<<<<<< + * for i in range(left, right): + * d1 = data[node_indices[i] * n_features + split_dim] */ - __Pyx_XDECREF(__pyx_r); - if (unlikely(!__pyx_v_idx_array)) { __Pyx_RaiseUnboundLocalError("idx_array"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} }__pyx_t_9 = PyObject_GetAttr(((PyObject *)__pyx_v_idx_array), __pyx_n_s__reshape); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_7 = __Pyx_PySequence_GetSlice(__pyx_v_orig_shape, 0, -1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_9, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_r = __pyx_t_7; - __pyx_t_7 = 0; - goto __pyx_L0; - } - __pyx_L19:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BallTree.query_radius", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_idx_array); - __Pyx_XDECREF((PyObject *)__pyx_v_idx_array_i); - __Pyx_XDECREF((PyObject *)__pyx_v_distances); - __Pyx_XDECREF((PyObject *)__pyx_v_distances_i); - __Pyx_XDECREF((PyObject *)__pyx_v_pt); - __Pyx_XDECREF((PyObject *)__pyx_v_count); - __Pyx_XDECREF(__pyx_v_orig_shape); - __Pyx_XDECREF(__pyx_v_pt_idx); - __Pyx_XDECREF(__pyx_v_X); - __Pyx_XDECREF(__pyx_v_r); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_v_midindex = __pyx_v_left; -/* "sklearn/neighbors/ball_tree.pyx":822 - * - * @cython.cdivision(True) - * cdef void build_tree_(BallTree self): # <<<<<<<<<<<<<< - * cdef DTYPE_t* data = self.data.data - * cdef ITYPE_t* idx_array = self.idx_array.data + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":834 + * while True: + * midindex = left + * for i in range(left, right): # <<<<<<<<<<<<<< + * d1 = data[node_indices[i] * n_features + split_dim] + * d2 = data[node_indices[right] * n_features + split_dim] */ + __pyx_t_1 = __pyx_v_right; + for (__pyx_t_2 = __pyx_v_left; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; -static void __pyx_f_7sklearn_9neighbors_9ball_tree_8BallTree_build_tree_(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *__pyx_v_self) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_data; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx_array; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_node_centroid_arr; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *__pyx_v_node_info_arr; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_samples; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_features; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_idx_start; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_idx_end; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_points; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_radius; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_node; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_parent; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_centroid; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *__pyx_v_node_info; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *__pyx_v_parent_info; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_max; - __Pyx_RefNannyDeclarations - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("build_tree_"); - - /* "sklearn/neighbors/ball_tree.pyx":823 - * @cython.cdivision(True) - * cdef void build_tree_(BallTree self): - * cdef DTYPE_t* data = self.data.data # <<<<<<<<<<<<<< - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":835 + * midindex = left + * for i in range(left, right): + * d1 = data[node_indices[i] * n_features + split_dim] # <<<<<<<<<<<<<< + * d2 = data[node_indices[right] * n_features + split_dim] + * if d1 < d2: */ - __pyx_v_data = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_self->data->data); + __pyx_v_d1 = (__pyx_v_data[(((__pyx_v_node_indices[__pyx_v_i]) * __pyx_v_n_features) + __pyx_v_split_dim)]); - /* "sklearn/neighbors/ball_tree.pyx":824 - * cdef void build_tree_(BallTree self): - * cdef DTYPE_t* data = self.data.data - * cdef ITYPE_t* idx_array = self.idx_array.data # <<<<<<<<<<<<<< - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":836 + * for i in range(left, right): + * d1 = data[node_indices[i] * n_features + split_dim] + * d2 = data[node_indices[right] * n_features + split_dim] # <<<<<<<<<<<<<< + * if d1 < d2: + * swap(node_indices, i, midindex) */ - __pyx_v_idx_array = ((__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *)__pyx_v_self->idx_array->data); + __pyx_v_d2 = (__pyx_v_data[(((__pyx_v_node_indices[__pyx_v_right]) * __pyx_v_n_features) + __pyx_v_split_dim)]); - /* "sklearn/neighbors/ball_tree.pyx":825 - * cdef DTYPE_t* data = self.data.data - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data # <<<<<<<<<<<<<< - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":837 + * d1 = data[node_indices[i] * n_features + split_dim] + * d2 = data[node_indices[right] * n_features + split_dim] + * if d1 < d2: # <<<<<<<<<<<<<< + * swap(node_indices, i, midindex) + * midindex += 1 */ - __pyx_v_node_centroid_arr = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_self->node_centroid_arr->data); + __pyx_t_3 = ((__pyx_v_d1 < __pyx_v_d2) != 0); + if (__pyx_t_3) { - /* "sklearn/neighbors/ball_tree.pyx":826 - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data # <<<<<<<<<<<<<< - * - * cdef DTYPE_t p = self.p + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":838 + * d2 = data[node_indices[right] * n_features + split_dim] + * if d1 < d2: + * swap(node_indices, i, midindex) # <<<<<<<<<<<<<< + * midindex += 1 + * swap(node_indices, midindex, right) */ - __pyx_v_node_info_arr = ((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *)__pyx_v_self->node_info_arr->data); + __pyx_fuse_0__pyx_f_7sklearn_9neighbors_9ball_tree_swap(__pyx_v_node_indices, __pyx_v_i, __pyx_v_midindex); - /* "sklearn/neighbors/ball_tree.pyx":828 - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - * - * cdef DTYPE_t p = self.p # <<<<<<<<<<<<<< - * cdef ITYPE_t n_samples = self.data.shape[0] - * cdef ITYPE_t n_features = self.data.shape[1] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":839 + * if d1 < d2: + * swap(node_indices, i, midindex) + * midindex += 1 # <<<<<<<<<<<<<< + * swap(node_indices, midindex, right) + * if midindex == split_index: */ - __pyx_v_p = __pyx_v_self->p; + __pyx_v_midindex = (__pyx_v_midindex + 1); + goto __pyx_L7; + } + __pyx_L7:; + } - /* "sklearn/neighbors/ball_tree.pyx":829 - * - * cdef DTYPE_t p = self.p - * cdef ITYPE_t n_samples = self.data.shape[0] # <<<<<<<<<<<<<< - * cdef ITYPE_t n_features = self.data.shape[1] - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":840 + * swap(node_indices, i, midindex) + * midindex += 1 + * swap(node_indices, midindex, right) # <<<<<<<<<<<<<< + * if midindex == split_index: + * break */ - __pyx_v_n_samples = (__pyx_v_self->data->dimensions[0]); + __pyx_fuse_0__pyx_f_7sklearn_9neighbors_9ball_tree_swap(__pyx_v_node_indices, __pyx_v_midindex, __pyx_v_right); - /* "sklearn/neighbors/ball_tree.pyx":830 - * cdef DTYPE_t p = self.p - * cdef ITYPE_t n_samples = self.data.shape[0] - * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< - * - * cdef ITYPE_t idx_start, idx_end, n_points + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":841 + * midindex += 1 + * swap(node_indices, midindex, right) + * if midindex == split_index: # <<<<<<<<<<<<<< + * break + * elif midindex < split_index: */ - __pyx_v_n_features = (__pyx_v_self->data->dimensions[1]); + __pyx_t_3 = ((__pyx_v_midindex == __pyx_v_split_index) != 0); + if (__pyx_t_3) { - /* "sklearn/neighbors/ball_tree.pyx":836 - * cdef ITYPE_t i, i_node, i_parent - * - * cdef DTYPE_t* centroid = node_centroid_arr # <<<<<<<<<<<<<< - * cdef NodeInfo* node_info = node_info_arr - * cdef NodeInfo* parent_info + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":842 + * swap(node_indices, midindex, right) + * if midindex == split_index: + * break # <<<<<<<<<<<<<< + * elif midindex < split_index: + * left = midindex + 1 */ - __pyx_v_centroid = __pyx_v_node_centroid_arr; + goto __pyx_L4_break; + } - /* "sklearn/neighbors/ball_tree.pyx":837 - * - * cdef DTYPE_t* centroid = node_centroid_arr - * cdef NodeInfo* node_info = node_info_arr # <<<<<<<<<<<<<< - * cdef NodeInfo* parent_info - * cdef DTYPE_t* point + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":843 + * if midindex == split_index: + * break + * elif midindex < split_index: # <<<<<<<<<<<<<< + * left = midindex + 1 + * else: */ - __pyx_v_node_info = __pyx_v_node_info_arr; + __pyx_t_3 = ((__pyx_v_midindex < __pyx_v_split_index) != 0); + if (__pyx_t_3) { - /* "sklearn/neighbors/ball_tree.pyx":843 - * #------------------------------------------------------------ - * # take care of the root node - * node_info.idx_start = 0 # <<<<<<<<<<<<<< - * node_info.idx_end = n_samples - * n_points = n_samples + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":844 + * break + * elif midindex < split_index: + * left = midindex + 1 # <<<<<<<<<<<<<< + * else: + * right = midindex - 1 */ - __pyx_v_node_info->idx_start = 0; + __pyx_v_left = (__pyx_v_midindex + 1); + goto __pyx_L8; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":844 - * # take care of the root node - * node_info.idx_start = 0 - * node_info.idx_end = n_samples # <<<<<<<<<<<<<< - * n_points = n_samples + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":846 + * left = midindex + 1 + * else: + * right = midindex - 1 # <<<<<<<<<<<<<< * + * return 0 */ - __pyx_v_node_info->idx_end = __pyx_v_n_samples; + __pyx_v_right = (__pyx_v_midindex - 1); + } + __pyx_L8:; + } + __pyx_L4_break:; - /* "sklearn/neighbors/ball_tree.pyx":845 - * node_info.idx_start = 0 - * node_info.idx_end = n_samples - * n_points = n_samples # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":848 + * right = midindex - 1 + * + * return 0 # <<<<<<<<<<<<<< * - * # determine Node centroid - */ - __pyx_v_n_points = __pyx_v_n_samples; - - /* "sklearn/neighbors/ball_tree.pyx":849 - * # determine Node centroid - * compute_centroid(centroid, data, idx_array, - * n_features, n_samples) # <<<<<<<<<<<<<< * - * # determine Node radius */ - __pyx_f_7sklearn_9neighbors_9ball_tree_compute_centroid(__pyx_v_centroid, __pyx_v_data, __pyx_v_idx_array, __pyx_v_n_features, __pyx_v_n_samples); + __pyx_r = 0; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":852 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":784 + * * - * # determine Node radius - * radius = 0 # <<<<<<<<<<<<<< - * for i from node_info.idx_start <= i < node_info.idx_end: - * radius = dmax(radius, + * cdef int partition_node_indices(DTYPE_t* data, # <<<<<<<<<<<<<< + * ITYPE_t* node_indices, + * ITYPE_t split_dim, */ - __pyx_v_radius = 0.0; - /* "sklearn/neighbors/ball_tree.pyx":853 - * # determine Node radius - * radius = 0 - * for i from node_info.idx_start <= i < node_info.idx_end: # <<<<<<<<<<<<<< - * radius = dmax(radius, - * dist_p(centroid, data + n_features * idx_array[i], - */ - __pyx_t_1 = __pyx_v_node_info->idx_end; - for (__pyx_v_i = __pyx_v_node_info->idx_start; __pyx_v_i < __pyx_t_1; __pyx_v_i++) { + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":856 - * radius = dmax(radius, - * dist_p(centroid, data + n_features * idx_array[i], - * n_features, p)) # <<<<<<<<<<<<<< - * node_info.radius = dist_from_dist_p(radius, p) - * +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":854 + * # NodeHeap : min-heap used to keep track of nodes during + * # breadth-first query + * cdef inline void swap_nodes(NodeHeapData_t* arr, ITYPE_t i1, ITYPE_t i2): # <<<<<<<<<<<<<< + * cdef NodeHeapData_t tmp = arr[i1] + * arr[i1] = arr[i2] */ - __pyx_v_radius = __pyx_f_7sklearn_9neighbors_9ball_tree_dmax(__pyx_v_radius, __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p(__pyx_v_centroid, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features, __pyx_v_p)); - } - /* "sklearn/neighbors/ball_tree.pyx":857 - * dist_p(centroid, data + n_features * idx_array[i], - * n_features, p)) - * node_info.radius = dist_from_dist_p(radius, p) # <<<<<<<<<<<<<< - * - * # check if this is a leaf - */ - __pyx_v_node_info->radius = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_from_dist_p(__pyx_v_radius, __pyx_v_p); +static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_swap_nodes(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *__pyx_v_arr, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2) { + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_v_tmp; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("swap_nodes", 0); - /* "sklearn/neighbors/ball_tree.pyx":860 - * - * # check if this is a leaf - * if self.n_nodes == 1: # <<<<<<<<<<<<<< - * node_info.is_leaf = 1 - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":855 + * # breadth-first query + * cdef inline void swap_nodes(NodeHeapData_t* arr, ITYPE_t i1, ITYPE_t i2): + * cdef NodeHeapData_t tmp = arr[i1] # <<<<<<<<<<<<<< + * arr[i1] = arr[i2] + * arr[i2] = tmp */ - __pyx_t_2 = (__pyx_v_self->n_nodes == 1); - if (__pyx_t_2) { + __pyx_v_tmp = (__pyx_v_arr[__pyx_v_i1]); - /* "sklearn/neighbors/ball_tree.pyx":861 - * # check if this is a leaf - * if self.n_nodes == 1: - * node_info.is_leaf = 1 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":856 + * cdef inline void swap_nodes(NodeHeapData_t* arr, ITYPE_t i1, ITYPE_t i2): + * cdef NodeHeapData_t tmp = arr[i1] + * arr[i1] = arr[i2] # <<<<<<<<<<<<<< + * arr[i2] = tmp * - * else: */ - __pyx_v_node_info->is_leaf = 1; - goto __pyx_L5; - } - /*else*/ { + (__pyx_v_arr[__pyx_v_i1]) = (__pyx_v_arr[__pyx_v_i2]); - /* "sklearn/neighbors/ball_tree.pyx":864 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":857 + * cdef NodeHeapData_t tmp = arr[i1] + * arr[i1] = arr[i2] + * arr[i2] = tmp # <<<<<<<<<<<<<< * - * else: - * node_info.is_leaf = 0 # <<<<<<<<<<<<<< * - * # find dimension with largest spread */ - __pyx_v_node_info->is_leaf = 0; + (__pyx_v_arr[__pyx_v_i2]) = __pyx_v_tmp; - /* "sklearn/neighbors/ball_tree.pyx":868 - * # find dimension with largest spread - * i_max = find_split_dim(data, idx_array + node_info.idx_start, - * n_features, n_points) # <<<<<<<<<<<<<< - * - * # sort idx_array along this dimension + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":854 + * # NodeHeap : min-heap used to keep track of nodes during + * # breadth-first query + * cdef inline void swap_nodes(NodeHeapData_t* arr, ITYPE_t i1, ITYPE_t i2): # <<<<<<<<<<<<<< + * cdef NodeHeapData_t tmp = arr[i1] + * arr[i1] = arr[i2] */ - __pyx_v_i_max = __pyx_f_7sklearn_9neighbors_9ball_tree_find_split_dim(__pyx_v_data, (__pyx_v_idx_array + __pyx_v_node_info->idx_start), __pyx_v_n_features, __pyx_v_n_points); - /* "sklearn/neighbors/ball_tree.pyx":876 - * n_points / 2, - * n_features, - * n_points) # <<<<<<<<<<<<<< + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":877 + * cdef ITYPE_t n * - * #------------------------------------------------------------ + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.data_arr = np.zeros(1, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) */ - __pyx_f_7sklearn_9neighbors_9ball_tree_partition_indices(__pyx_v_data, (__pyx_v_idx_array + __pyx_v_node_info->idx_start), __pyx_v_i_max, (__pyx_v_n_points / 2), __pyx_v_n_features, __pyx_v_n_points); - } - __pyx_L5:; - /* "sklearn/neighbors/ball_tree.pyx":880 - * #------------------------------------------------------------ - * # cycle through all child nodes - * for i_node from 1 <= i_node < self.n_nodes: # <<<<<<<<<<<<<< - * i_parent = (i_node - 1) / 2 - * parent_info = node_info_arr + i_parent - */ - __pyx_t_1 = __pyx_v_self->n_nodes; - for (__pyx_v_i_node = 1; __pyx_v_i_node < __pyx_t_1; __pyx_v_i_node++) { +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_8NodeHeap_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_8NodeHeap_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} + if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_8NodeHeap___cinit__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_self)); - /* "sklearn/neighbors/ball_tree.pyx":881 - * # cycle through all child nodes - * for i_node from 1 <= i_node < self.n_nodes: - * i_parent = (i_node - 1) / 2 # <<<<<<<<<<<<<< - * parent_info = node_info_arr + i_parent - * - */ - __pyx_v_i_parent = ((__pyx_v_i_node - 1) / 2); + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":882 - * for i_node from 1 <= i_node < self.n_nodes: - * i_parent = (i_node - 1) / 2 - * parent_info = node_info_arr + i_parent # <<<<<<<<<<<<<< - * - * node_info = node_info_arr + i_node - */ - __pyx_v_parent_info = (__pyx_v_node_info_arr + __pyx_v_i_parent); +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_8NodeHeap___cinit__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); - /* "sklearn/neighbors/ball_tree.pyx":884 - * parent_info = node_info_arr + i_parent + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":878 * - * node_info = node_info_arr + i_node # <<<<<<<<<<<<<< + * def __cinit__(self): + * self.data_arr = np.zeros(1, dtype=NodeHeapData, order='C') # <<<<<<<<<<<<<< + * self.data = get_memview_NodeHeapData_1D(self.data_arr) * - * if parent_info.is_leaf: */ - __pyx_v_node_info = (__pyx_v_node_info_arr + __pyx_v_i_node); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_NodeHeapData); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__7, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; - /* "sklearn/neighbors/ball_tree.pyx":886 - * node_info = node_info_arr + i_node + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":879 + * def __cinit__(self): + * self.data_arr = np.zeros(1, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) # <<<<<<<<<<<<<< * - * if parent_info.is_leaf: # <<<<<<<<<<<<<< - * raise ValueError("Fatal: parent is a leaf. Memory " - * "allocation is flawed") + * def __init__(self, size_guess=100): */ - if (__pyx_v_parent_info->is_leaf) { + __pyx_t_3 = ((PyObject *)__pyx_v_self->data_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_NodeHeapData_1D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 879; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __pyx_v_self->data = __pyx_t_4; + __pyx_t_4.memview = NULL; + __pyx_t_4.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":887 - * - * if parent_info.is_leaf: - * raise ValueError("Fatal: parent is a leaf. Memory " # <<<<<<<<<<<<<< - * "allocation is flawed") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":877 + * cdef ITYPE_t n * + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.data_arr = np.zeros(1, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_39), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; - } - __pyx_L8:; - /* "sklearn/neighbors/ball_tree.pyx":890 - * "allocation is flawed") - * - * if i_node < self.n_nodes / 2: # <<<<<<<<<<<<<< - * node_info.is_leaf = 0 - * else: - */ - __pyx_t_2 = (__pyx_v_i_node < (__pyx_v_self->n_nodes / 2)); - if (__pyx_t_2) { + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __PYX_XDEC_MEMVIEW(&__pyx_t_4, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NodeHeap.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":891 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":881 + * self.data = get_memview_NodeHeapData_1D(self.data_arr) * - * if i_node < self.n_nodes / 2: - * node_info.is_leaf = 0 # <<<<<<<<<<<<<< - * else: - * node_info.is_leaf = 1 + * def __init__(self, size_guess=100): # <<<<<<<<<<<<<< + * size_guess = max(size_guess, 1) # need space for at least one item + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') */ - __pyx_v_node_info->is_leaf = 0; - goto __pyx_L9; - } - /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":893 - * node_info.is_leaf = 0 - * else: - * node_info.is_leaf = 1 # <<<<<<<<<<<<<< - * - * centroid = node_centroid_arr + i_node * n_features - */ - __pyx_v_node_info->is_leaf = 1; +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_8NodeHeap_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_8NodeHeap_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_size_guess = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_size_guess,0}; + PyObject* values[1] = {0}; + values[0] = ((PyObject *)__pyx_int_100); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_size_guess); + if (value) { values[0] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 881; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } } - __pyx_L9:; + __pyx_v_size_guess = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 881; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NodeHeap.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_8NodeHeap_2__init__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_self), __pyx_v_size_guess); - /* "sklearn/neighbors/ball_tree.pyx":895 - * node_info.is_leaf = 1 - * - * centroid = node_centroid_arr + i_node * n_features # <<<<<<<<<<<<<< - * - * # find indices for this node - */ - __pyx_v_centroid = (__pyx_v_node_centroid_arr + (__pyx_v_i_node * __pyx_v_n_features)); + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":898 - * - * # find indices for this node - * idx_start = parent_info.idx_start # <<<<<<<<<<<<<< - * idx_end = parent_info.idx_end +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_8NodeHeap_2__init__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_self, PyObject *__pyx_v_size_guess) { + int __pyx_r; + __Pyx_RefNannyDeclarations + long __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_INCREF(__pyx_v_size_guess); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":882 * + * def __init__(self, size_guess=100): + * size_guess = max(size_guess, 1) # need space for at least one item # <<<<<<<<<<<<<< + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) */ - __pyx_v_idx_start = __pyx_v_parent_info->idx_start; + __pyx_t_1 = 1; + __Pyx_INCREF(__pyx_v_size_guess); + __pyx_t_2 = __pyx_v_size_guess; + __pyx_t_4 = __Pyx_PyInt_From_long(__pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyObject_RichCompare(__pyx_t_4, __pyx_t_2, Py_GT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + __pyx_t_5 = __Pyx_PyInt_From_long(__pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __pyx_t_5; + __pyx_t_5 = 0; + } else { + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = __pyx_t_2; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_size_guess, __pyx_t_2); + __pyx_t_2 = 0; - /* "sklearn/neighbors/ball_tree.pyx":899 - * # find indices for this node - * idx_start = parent_info.idx_start - * idx_end = parent_info.idx_end # <<<<<<<<<<<<<< - * - * if i_node % 2 == 1: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":883 + * def __init__(self, size_guess=100): + * size_guess = max(size_guess, 1) # need space for at least one item + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') # <<<<<<<<<<<<<< + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + * self.n = size_guess */ - __pyx_v_idx_end = __pyx_v_parent_info->idx_end; + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_size_guess); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size_guess); + __Pyx_GIVEREF(__pyx_v_size_guess); + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_NodeHeapData); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_2, __pyx_t_5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; - /* "sklearn/neighbors/ball_tree.pyx":901 - * idx_end = parent_info.idx_end - * - * if i_node % 2 == 1: # <<<<<<<<<<<<<< - * idx_start = (idx_start + idx_end) / 2 - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":884 + * size_guess = max(size_guess, 1) # need space for at least one item + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) # <<<<<<<<<<<<<< + * self.n = size_guess + * self.clear() */ - __pyx_t_2 = ((__pyx_v_i_node % 2) == 1); - if (__pyx_t_2) { + __pyx_t_4 = ((PyObject *)__pyx_v_self->data_arr); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_NodeHeapData_1D(((PyArrayObject *)__pyx_t_4)); if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __pyx_v_self->data = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":902 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":885 + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + * self.n = size_guess # <<<<<<<<<<<<<< + * self.clear() * - * if i_node % 2 == 1: - * idx_start = (idx_start + idx_end) / 2 # <<<<<<<<<<<<<< - * else: - * idx_end = (idx_start + idx_end) / 2 */ - __pyx_v_idx_start = ((__pyx_v_idx_start + __pyx_v_idx_end) / 2); - goto __pyx_L10; - } - /*else*/ { + __pyx_t_8 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_size_guess); if (unlikely((__pyx_t_8 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->n = __pyx_t_8; - /* "sklearn/neighbors/ball_tree.pyx":904 - * idx_start = (idx_start + idx_end) / 2 - * else: - * idx_end = (idx_start + idx_end) / 2 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":886 + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + * self.n = size_guess + * self.clear() # <<<<<<<<<<<<<< * - * node_info.idx_start = idx_start + * cdef int resize(self, ITYPE_t new_size) except -1: */ - __pyx_v_idx_end = ((__pyx_v_idx_start + __pyx_v_idx_end) / 2); - } - __pyx_L10:; + ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_self->__pyx_vtab)->clear(__pyx_v_self); - /* "sklearn/neighbors/ball_tree.pyx":906 - * idx_end = (idx_start + idx_end) / 2 - * - * node_info.idx_start = idx_start # <<<<<<<<<<<<<< - * node_info.idx_end = idx_end + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":881 + * self.data = get_memview_NodeHeapData_1D(self.data_arr) * + * def __init__(self, size_guess=100): # <<<<<<<<<<<<<< + * size_guess = max(size_guess, 1) # need space for at least one item + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') */ - __pyx_v_node_info->idx_start = __pyx_v_idx_start; - /* "sklearn/neighbors/ball_tree.pyx":907 - * - * node_info.idx_start = idx_start - * node_info.idx_end = idx_end # <<<<<<<<<<<<<< + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NodeHeap.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_size_guess); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":888 + * self.clear() * - * n_points = idx_end - idx_start + * cdef int resize(self, ITYPE_t new_size) except -1: # <<<<<<<<<<<<<< + * """Resize the heap to be either larger or smaller""" + * cdef NodeHeapData_t *data_ptr, *new_data_ptr */ - __pyx_v_node_info->idx_end = __pyx_v_idx_end; - /* "sklearn/neighbors/ball_tree.pyx":909 - * node_info.idx_end = idx_end - * - * n_points = idx_end - idx_start # <<<<<<<<<<<<<< - * - * if n_points == 0: +static int __pyx_f_7sklearn_9neighbors_9ball_tree_8NodeHeap_resize(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_new_size) { + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *__pyx_v_data_ptr; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *__pyx_v_new_data_ptr; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size; + PyArrayObject *__pyx_v_new_data_arr = 0; + __Pyx_memviewslice __pyx_v_new_data = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("resize", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":892 + * cdef NodeHeapData_t *data_ptr, *new_data_ptr + * cdef ITYPE_t i + * cdef ITYPE_t size = self.data.shape[0] # <<<<<<<<<<<<<< + * cdef np.ndarray new_data_arr = np.zeros(new_size, + * dtype=NodeHeapData) */ - __pyx_v_n_points = (__pyx_v_idx_end - __pyx_v_idx_start); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 892; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_size = (__pyx_v_self->data.shape[0]); - /* "sklearn/neighbors/ball_tree.pyx":914 - * raise ValueError("zero-sized node") - * - * elif n_points == 1: # <<<<<<<<<<<<<< - * #copy this point to centroid - * copy_array(centroid, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":893 + * cdef ITYPE_t i + * cdef ITYPE_t size = self.data.shape[0] + * cdef np.ndarray new_data_arr = np.zeros(new_size, # <<<<<<<<<<<<<< + * dtype=NodeHeapData) + * cdef NodeHeapData_t[::1] new_data =\ */ - switch (__pyx_v_n_points) { + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_new_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); - /* "sklearn/neighbors/ball_tree.pyx":911 - * n_points = idx_end - idx_start - * - * if n_points == 0: # <<<<<<<<<<<<<< - * raise ValueError("zero-sized node") - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":894 + * cdef ITYPE_t size = self.data.shape[0] + * cdef np.ndarray new_data_arr = np.zeros(new_size, + * dtype=NodeHeapData) # <<<<<<<<<<<<<< + * cdef NodeHeapData_t[::1] new_data =\ + * get_memview_NodeHeapData_1D(new_data_arr) */ - case 0: + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_NodeHeapData); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 894; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - /* "sklearn/neighbors/ball_tree.pyx":912 - * - * if n_points == 0: - * raise ValueError("zero-sized node") # <<<<<<<<<<<<<< - * - * elif n_points == 1: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":893 + * cdef ITYPE_t i + * cdef ITYPE_t size = self.data.shape[0] + * cdef np.ndarray new_data_arr = np.zeros(new_size, # <<<<<<<<<<<<<< + * dtype=NodeHeapData) + * cdef NodeHeapData_t[::1] new_data =\ */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_41), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 912; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 912; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - break; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_new_data_arr = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; - /* "sklearn/neighbors/ball_tree.pyx":914 - * raise ValueError("zero-sized node") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":896 + * dtype=NodeHeapData) + * cdef NodeHeapData_t[::1] new_data =\ + * get_memview_NodeHeapData_1D(new_data_arr) # <<<<<<<<<<<<<< * - * elif n_points == 1: # <<<<<<<<<<<<<< - * #copy this point to centroid - * copy_array(centroid, + * if size > 0 and new_size > 0: */ - case 1: + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_NodeHeapData_1D(((PyArrayObject *)__pyx_v_new_data_arr)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_new_data = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":918 - * copy_array(centroid, - * data + idx_array[idx_start] * n_features, - * n_features) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":898 + * get_memview_NodeHeapData_1D(new_data_arr) * - * #store radius in array + * if size > 0 and new_size > 0: # <<<<<<<<<<<<<< + * data_ptr = &self.data[0] + * new_data_ptr = &new_data[0] */ - __pyx_f_7sklearn_9neighbors_9ball_tree_copy_array(__pyx_v_centroid, (__pyx_v_data + ((__pyx_v_idx_array[__pyx_v_idx_start]) * __pyx_v_n_features)), __pyx_v_n_features); + __pyx_t_6 = ((__pyx_v_size > 0) != 0); + if (__pyx_t_6) { + __pyx_t_7 = ((__pyx_v_new_size > 0) != 0); + __pyx_t_8 = __pyx_t_7; + } else { + __pyx_t_8 = __pyx_t_6; + } + if (__pyx_t_8) { - /* "sklearn/neighbors/ball_tree.pyx":921 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":899 * - * #store radius in array - * node_info.radius = 0 # <<<<<<<<<<<<<< - * - * #is a leaf + * if size > 0 and new_size > 0: + * data_ptr = &self.data[0] # <<<<<<<<<<<<<< + * new_data_ptr = &new_data[0] + * for i in range(min(size, new_size)): */ - __pyx_v_node_info->radius = 0.0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 899; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = 0; + __pyx_v_data_ptr = (&(*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *) __pyx_v_self->data.data) + __pyx_t_9)) )))); - /* "sklearn/neighbors/ball_tree.pyx":924 - * - * #is a leaf - * node_info.is_leaf = 1 # <<<<<<<<<<<<<< - * - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":900 + * if size > 0 and new_size > 0: + * data_ptr = &self.data[0] + * new_data_ptr = &new_data[0] # <<<<<<<<<<<<<< + * for i in range(min(size, new_size)): + * new_data_ptr[i] = data_ptr[i] */ - __pyx_v_node_info->is_leaf = 1; - break; - default: + __pyx_t_10 = 0; + __pyx_v_new_data_ptr = (&(*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *) __pyx_v_new_data.data) + __pyx_t_10)) )))); - /* "sklearn/neighbors/ball_tree.pyx":929 - * # determine Node centroid - * compute_centroid(centroid, data, idx_array + idx_start, - * n_features, n_points) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":901 + * data_ptr = &self.data[0] + * new_data_ptr = &new_data[0] + * for i in range(min(size, new_size)): # <<<<<<<<<<<<<< + * new_data_ptr[i] = data_ptr[i] * - * # determine Node radius */ - __pyx_f_7sklearn_9neighbors_9ball_tree_compute_centroid(__pyx_v_centroid, __pyx_v_data, (__pyx_v_idx_array + __pyx_v_idx_start), __pyx_v_n_features, __pyx_v_n_points); + __pyx_t_11 = __pyx_v_new_size; + __pyx_t_12 = __pyx_v_size; + if (((__pyx_t_11 < __pyx_t_12) != 0)) { + __pyx_t_13 = __pyx_t_11; + } else { + __pyx_t_13 = __pyx_t_12; + } + __pyx_t_11 = __pyx_t_13; + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_11; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; - /* "sklearn/neighbors/ball_tree.pyx":932 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":902 + * new_data_ptr = &new_data[0] + * for i in range(min(size, new_size)): + * new_data_ptr[i] = data_ptr[i] # <<<<<<<<<<<<<< * - * # determine Node radius - * radius = 0 # <<<<<<<<<<<<<< - * for i from idx_start <= i < idx_end: - * radius = dmax(radius, + * if new_size < size: */ - __pyx_v_radius = 0.0; + (__pyx_v_new_data_ptr[__pyx_v_i]) = (__pyx_v_data_ptr[__pyx_v_i]); + } + goto __pyx_L3; + } + __pyx_L3:; - /* "sklearn/neighbors/ball_tree.pyx":933 - * # determine Node radius - * radius = 0 - * for i from idx_start <= i < idx_end: # <<<<<<<<<<<<<< - * radius = dmax(radius, - * dist_p(centroid, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":904 + * new_data_ptr[i] = data_ptr[i] + * + * if new_size < size: # <<<<<<<<<<<<<< + * self.n = new_size + * */ - __pyx_t_4 = __pyx_v_idx_end; - for (__pyx_v_i = __pyx_v_idx_start; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { + __pyx_t_8 = ((__pyx_v_new_size < __pyx_v_size) != 0); + if (__pyx_t_8) { - /* "sklearn/neighbors/ball_tree.pyx":937 - * dist_p(centroid, - * data + n_features * idx_array[i], - * n_features, p)) # <<<<<<<<<<<<<< - * node_info.radius = dist_from_dist_p(radius, p) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":905 * + * if new_size < size: + * self.n = new_size # <<<<<<<<<<<<<< + * + * self.data = new_data */ - __pyx_v_radius = __pyx_f_7sklearn_9neighbors_9ball_tree_dmax(__pyx_v_radius, __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p(__pyx_v_centroid, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features, __pyx_v_p)); - } + __pyx_v_self->n = __pyx_v_new_size; + goto __pyx_L6; + } + __pyx_L6:; - /* "sklearn/neighbors/ball_tree.pyx":938 - * data + n_features * idx_array[i], - * n_features, p)) - * node_info.radius = dist_from_dist_p(radius, p) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":907 + * self.n = new_size * - * if not node_info.is_leaf: + * self.data = new_data # <<<<<<<<<<<<<< + * self.data_arr = new_data_arr + * return 0 */ - __pyx_v_node_info->radius = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_from_dist_p(__pyx_v_radius, __pyx_v_p); + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __PYX_INC_MEMVIEW(&__pyx_v_new_data, 0); + __pyx_v_self->data = __pyx_v_new_data; - /* "sklearn/neighbors/ball_tree.pyx":940 - * node_info.radius = dist_from_dist_p(radius, p) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":908 + * + * self.data = new_data + * self.data_arr = new_data_arr # <<<<<<<<<<<<<< + * return 0 * - * if not node_info.is_leaf: # <<<<<<<<<<<<<< - * # find dimension with largest spread - * i_max = find_split_dim(data, idx_array + idx_start, */ - __pyx_t_2 = (!__pyx_v_node_info->is_leaf); - if (__pyx_t_2) { + __Pyx_INCREF(((PyObject *)__pyx_v_new_data_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_new_data_arr)); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = __pyx_v_new_data_arr; - /* "sklearn/neighbors/ball_tree.pyx":943 - * # find dimension with largest spread - * i_max = find_split_dim(data, idx_array + idx_start, - * n_features, n_points) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":909 + * self.data = new_data + * self.data_arr = new_data_arr + * return 0 # <<<<<<<<<<<<<< * - * # sort indices along this dimension + * cdef int push(self, NodeHeapData_t data) except -1: */ - __pyx_v_i_max = __pyx_f_7sklearn_9neighbors_9ball_tree_find_split_dim(__pyx_v_data, (__pyx_v_idx_array + __pyx_v_idx_start), __pyx_v_n_features, __pyx_v_n_points); + __pyx_r = 0; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":951 - * n_points / 2, - * n_features, - * n_points) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":888 + * self.clear() * - * cdef void query_one_(BallTree self, + * cdef int resize(self, ITYPE_t new_size) except -1: # <<<<<<<<<<<<<< + * """Resize the heap to be either larger or smaller""" + * cdef NodeHeapData_t *data_ptr, *new_data_ptr */ - __pyx_f_7sklearn_9neighbors_9ball_tree_partition_indices(__pyx_v_data, (__pyx_v_idx_array + __pyx_v_idx_start), __pyx_v_i_max, (__pyx_v_n_points / 2), __pyx_v_n_features, __pyx_v_n_points); - goto __pyx_L13; - } - __pyx_L13:; - break; - } - } - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_WriteUnraisable("sklearn.neighbors.ball_tree.BallTree.build_tree_", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_RefNannyFinishContext(); -} - -/* "sklearn/neighbors/ball_tree.pyx":953 - * n_points) - * - * cdef void query_one_(BallTree self, # <<<<<<<<<<<<<< - * DTYPE_t* pt, - * ITYPE_t k, - */ - -static void __pyx_f_7sklearn_9neighbors_9ball_tree_8BallTree_query_one_(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_k, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_near_set_dist, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_near_set_indx, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *__pyx_v_node_stack, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_use_max_heap) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_data; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx_array; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_node_centroid_arr; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *__pyx_v_node_info_arr; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *__pyx_v_node_info; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_features; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_dmax; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_dist_pt; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_dist_p_LB; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_dist_p_LB_1; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_dist_p_LB_2; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i1; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i2; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_node; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item __pyx_v_item; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_check_index; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t (*__pyx_v_heapqueue_largest)(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t (*__pyx_v_heapqueue_idx_largest)(__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); - void (*__pyx_v_heapqueue_insert)(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t); - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_2; - __Pyx_RefNannySetupContext("query_one_"); - - /* "sklearn/neighbors/ball_tree.pyx":960 - * stack* node_stack, - * ITYPE_t use_max_heap): - * cdef DTYPE_t* data = self.data.data # <<<<<<<<<<<<<< - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - */ - __pyx_v_data = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_self->data->data); - - /* "sklearn/neighbors/ball_tree.pyx":961 - * ITYPE_t use_max_heap): - * cdef DTYPE_t* data = self.data.data - * cdef ITYPE_t* idx_array = self.idx_array.data # <<<<<<<<<<<<<< - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - */ - __pyx_v_idx_array = ((__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *)__pyx_v_self->idx_array->data); - - /* "sklearn/neighbors/ball_tree.pyx":962 - * cdef DTYPE_t* data = self.data.data - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data # <<<<<<<<<<<<<< - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - * cdef NodeInfo* node_info = node_info_arr - */ - __pyx_v_node_centroid_arr = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_self->node_centroid_arr->data); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NodeHeap.resize", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_new_data_arr); + __PYX_XDEC_MEMVIEW(&__pyx_v_new_data, 1); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":963 - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data # <<<<<<<<<<<<<< - * cdef NodeInfo* node_info = node_info_arr +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":911 + * return 0 * + * cdef int push(self, NodeHeapData_t data) except -1: # <<<<<<<<<<<<<< + * """Push a new item onto the heap""" + * cdef ITYPE_t i, i_parent */ - __pyx_v_node_info_arr = ((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *)__pyx_v_self->node_info_arr->data); - /* "sklearn/neighbors/ball_tree.pyx":964 - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - * cdef NodeInfo* node_info = node_info_arr # <<<<<<<<<<<<<< - * - * cdef DTYPE_t p = self.p - */ - __pyx_v_node_info = __pyx_v_node_info_arr; +static int __pyx_f_7sklearn_9neighbors_9ball_tree_8NodeHeap_push(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_self, struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_v_data) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_parent; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *__pyx_v_data_arr; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + Py_ssize_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("push", 0); - /* "sklearn/neighbors/ball_tree.pyx":966 - * cdef NodeInfo* node_info = node_info_arr - * - * cdef DTYPE_t p = self.p # <<<<<<<<<<<<<< - * cdef ITYPE_t n_features = self.data.shape[1] - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":915 + * cdef ITYPE_t i, i_parent + * cdef NodeHeapData_t* data_arr + * self.n += 1 # <<<<<<<<<<<<<< + * if self.n > self.data.shape[0]: + * self.resize(2 * self.n) */ - __pyx_v_p = __pyx_v_self->p; + __pyx_v_self->n = (__pyx_v_self->n + 1); - /* "sklearn/neighbors/ball_tree.pyx":967 - * - * cdef DTYPE_t p = self.p - * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":916 + * cdef NodeHeapData_t* data_arr + * self.n += 1 + * if self.n > self.data.shape[0]: # <<<<<<<<<<<<<< + * self.resize(2 * self.n) * - * cdef DTYPE_t dmax, dist_pt, dist_p_LB, dist_p_LB_1, dist_p_LB_2 */ - __pyx_v_n_features = (__pyx_v_self->data->dimensions[1]); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 916; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = ((__pyx_v_self->n > (__pyx_v_self->data.shape[0])) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":977 - * # the end of the tree traversal, this index is in the last position, - * # then the warning flag will be set. - * cdef ITYPE_t check_index = -1 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":917 + * self.n += 1 + * if self.n > self.data.shape[0]: + * self.resize(2 * self.n) # <<<<<<<<<<<<<< * - * item.i_node = 0 + * # put the new element at the end, */ - __pyx_v_check_index = -1; + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_self->__pyx_vtab)->resize(__pyx_v_self, (2 * __pyx_v_self->n)); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 917; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; - /* "sklearn/neighbors/ball_tree.pyx":979 - * cdef ITYPE_t check_index = -1 - * - * item.i_node = 0 # <<<<<<<<<<<<<< - * item.dist_p_LB = calc_dist_p_LB(pt, node_centroid_arr, - * node_info.radius, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":921 + * # put the new element at the end, + * # and then perform swaps until the heap is in order + * data_arr = &self.data[0] # <<<<<<<<<<<<<< + * i = self.n - 1 + * data_arr[i] = data */ - __pyx_v_item.i_node = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 921; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_data_arr = (&(*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *) __pyx_v_self->data.data) + __pyx_t_3)) )))); - /* "sklearn/neighbors/ball_tree.pyx":980 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":922 + * # and then perform swaps until the heap is in order + * data_arr = &self.data[0] + * i = self.n - 1 # <<<<<<<<<<<<<< + * data_arr[i] = data * - * item.i_node = 0 - * item.dist_p_LB = calc_dist_p_LB(pt, node_centroid_arr, # <<<<<<<<<<<<<< - * node_info.radius, - * n_features, p) */ - __pyx_v_item.dist_p_LB = __pyx_f_7sklearn_9neighbors_9ball_tree_calc_dist_p_LB(__pyx_v_pt, __pyx_v_node_centroid_arr, __pyx_v_node_info->radius, __pyx_v_n_features, __pyx_v_p); + __pyx_v_i = (__pyx_v_self->n - 1); - /* "sklearn/neighbors/ball_tree.pyx":983 - * node_info.radius, - * n_features, p) - * stack_push(node_stack, item) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":923 + * data_arr = &self.data[0] + * i = self.n - 1 + * data_arr[i] = data # <<<<<<<<<<<<<< * - * # create pointers to the priority-queue/max-heap functions. + * while i > 0: */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); + (__pyx_v_data_arr[__pyx_v_i]) = __pyx_v_data; - /* "sklearn/neighbors/ball_tree.pyx":992 - * ITYPE_t*, ITYPE_t) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":925 + * data_arr[i] = data * - * if use_max_heap: # <<<<<<<<<<<<<< - * heapqueue_largest = &max_heap_largest - * heapqueue_idx_largest = &max_heap_idx_largest + * while i > 0: # <<<<<<<<<<<<<< + * i_parent = (i - 1) // 2 + * if data_arr[i_parent].val <= data_arr[i].val: */ - if (__pyx_v_use_max_heap) { + while (1) { + __pyx_t_1 = ((__pyx_v_i > 0) != 0); + if (!__pyx_t_1) break; - /* "sklearn/neighbors/ball_tree.pyx":993 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":926 * - * if use_max_heap: - * heapqueue_largest = &max_heap_largest # <<<<<<<<<<<<<< - * heapqueue_idx_largest = &max_heap_idx_largest - * heapqueue_insert = &max_heap_insert - */ - __pyx_v_heapqueue_largest = (&__pyx_f_7sklearn_9neighbors_9ball_tree_max_heap_largest); - - /* "sklearn/neighbors/ball_tree.pyx":994 - * if use_max_heap: - * heapqueue_largest = &max_heap_largest - * heapqueue_idx_largest = &max_heap_idx_largest # <<<<<<<<<<<<<< - * heapqueue_insert = &max_heap_insert - * else: + * while i > 0: + * i_parent = (i - 1) // 2 # <<<<<<<<<<<<<< + * if data_arr[i_parent].val <= data_arr[i].val: + * break */ - __pyx_v_heapqueue_idx_largest = (&__pyx_f_7sklearn_9neighbors_9ball_tree_max_heap_idx_largest); + __pyx_v_i_parent = ((__pyx_v_i - 1) / 2); - /* "sklearn/neighbors/ball_tree.pyx":995 - * heapqueue_largest = &max_heap_largest - * heapqueue_idx_largest = &max_heap_idx_largest - * heapqueue_insert = &max_heap_insert # <<<<<<<<<<<<<< - * else: - * heapqueue_largest = &pqueue_largest + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":927 + * while i > 0: + * i_parent = (i - 1) // 2 + * if data_arr[i_parent].val <= data_arr[i].val: # <<<<<<<<<<<<<< + * break + * else: */ - __pyx_v_heapqueue_insert = (&__pyx_f_7sklearn_9neighbors_9ball_tree_max_heap_insert); - goto __pyx_L3; - } - /*else*/ { + __pyx_t_1 = (((__pyx_v_data_arr[__pyx_v_i_parent]).val <= (__pyx_v_data_arr[__pyx_v_i]).val) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":997 - * heapqueue_insert = &max_heap_insert - * else: - * heapqueue_largest = &pqueue_largest # <<<<<<<<<<<<<< - * heapqueue_idx_largest = &pqueue_idx_largest - * heapqueue_insert = &pqueue_insert + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":928 + * i_parent = (i - 1) // 2 + * if data_arr[i_parent].val <= data_arr[i].val: + * break # <<<<<<<<<<<<<< + * else: + * swap_nodes(data_arr, i, i_parent) */ - __pyx_v_heapqueue_largest = (&__pyx_f_7sklearn_9neighbors_9ball_tree_pqueue_largest); + goto __pyx_L5_break; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":998 - * else: - * heapqueue_largest = &pqueue_largest - * heapqueue_idx_largest = &pqueue_idx_largest # <<<<<<<<<<<<<< - * heapqueue_insert = &pqueue_insert - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":930 + * break + * else: + * swap_nodes(data_arr, i, i_parent) # <<<<<<<<<<<<<< + * i = i_parent + * return 0 */ - __pyx_v_heapqueue_idx_largest = (&__pyx_f_7sklearn_9neighbors_9ball_tree_pqueue_idx_largest); + __pyx_f_7sklearn_9neighbors_9ball_tree_swap_nodes(__pyx_v_data_arr, __pyx_v_i, __pyx_v_i_parent); - /* "sklearn/neighbors/ball_tree.pyx":999 - * heapqueue_largest = &pqueue_largest - * heapqueue_idx_largest = &pqueue_idx_largest - * heapqueue_insert = &pqueue_insert # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":931 + * else: + * swap_nodes(data_arr, i, i_parent) + * i = i_parent # <<<<<<<<<<<<<< + * return 0 * - * while(node_stack.n > 0): */ - __pyx_v_heapqueue_insert = (&__pyx_f_7sklearn_9neighbors_9ball_tree_pqueue_insert); + __pyx_v_i = __pyx_v_i_parent; + } } - __pyx_L3:; + __pyx_L5_break:; - /* "sklearn/neighbors/ball_tree.pyx":1001 - * heapqueue_insert = &pqueue_insert + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":932 + * swap_nodes(data_arr, i, i_parent) + * i = i_parent + * return 0 # <<<<<<<<<<<<<< * - * while(node_stack.n > 0): # <<<<<<<<<<<<<< - * item = stack_pop(node_stack) - * i_node = item.i_node + * cdef NodeHeapData_t peek(self): */ - while (1) { - __pyx_t_1 = (__pyx_v_node_stack->n > 0); - if (!__pyx_t_1) break; + __pyx_r = 0; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":1002 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":911 + * return 0 * - * while(node_stack.n > 0): - * item = stack_pop(node_stack) # <<<<<<<<<<<<<< - * i_node = item.i_node - * dist_p_LB = item.dist_p_LB + * cdef int push(self, NodeHeapData_t data) except -1: # <<<<<<<<<<<<<< + * """Push a new item onto the heap""" + * cdef ITYPE_t i, i_parent */ - __pyx_v_item = __pyx_f_7sklearn_9neighbors_9ball_tree_stack_pop(__pyx_v_node_stack); - /* "sklearn/neighbors/ball_tree.pyx":1003 - * while(node_stack.n > 0): - * item = stack_pop(node_stack) - * i_node = item.i_node # <<<<<<<<<<<<<< - * dist_p_LB = item.dist_p_LB - * - */ - __pyx_v_i_node = __pyx_v_item.i_node; - - /* "sklearn/neighbors/ball_tree.pyx":1004 - * item = stack_pop(node_stack) - * i_node = item.i_node - * dist_p_LB = item.dist_p_LB # <<<<<<<<<<<<<< - * - * node_info = node_info_arr + i_node - */ - __pyx_v_dist_p_LB = __pyx_v_item.dist_p_LB; + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.NodeHeap.push", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":1006 - * dist_p_LB = item.dist_p_LB - * - * node_info = node_info_arr + i_node # <<<<<<<<<<<<<< +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":934 + * return 0 * - * #------------------------------------------------------------ + * cdef NodeHeapData_t peek(self): # <<<<<<<<<<<<<< + * """Peek at the root of the heap, without removing it""" + * return self.data[0] */ - __pyx_v_node_info = (__pyx_v_node_info_arr + __pyx_v_i_node); - /* "sklearn/neighbors/ball_tree.pyx":1011 - * # Case 0: query point is exactly on the boundary. Set - * # warning flag - * if dist_p_LB == heapqueue_largest(near_set_dist, k): # <<<<<<<<<<<<<< - * # store index of point with same distance: - * # we'll check it later - */ - __pyx_t_1 = (__pyx_v_dist_p_LB == __pyx_v_heapqueue_largest(__pyx_v_near_set_dist, __pyx_v_k)); - if (__pyx_t_1) { +static struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_f_7sklearn_9neighbors_9ball_tree_8NodeHeap_peek(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_self) { + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("peek", 0); - /* "sklearn/neighbors/ball_tree.pyx":1014 - * # store index of point with same distance: - * # we'll check it later - * check_index = heapqueue_idx_largest(near_set_indx, k) # <<<<<<<<<<<<<< - * continue + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":936 + * cdef NodeHeapData_t peek(self): + * """Peek at the root of the heap, without removing it""" + * return self.data[0] # <<<<<<<<<<<<<< * + * cdef NodeHeapData_t pop(self): */ - __pyx_v_check_index = __pyx_v_heapqueue_idx_largest(__pyx_v_near_set_indx, __pyx_v_k); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 936; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_r = (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *) __pyx_v_self->data.data) + __pyx_t_1)) ))); + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":1015 - * # we'll check it later - * check_index = heapqueue_idx_largest(near_set_indx, k) - * continue # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":934 + * return 0 * - * #------------------------------------------------------------ + * cdef NodeHeapData_t peek(self): # <<<<<<<<<<<<<< + * """Peek at the root of the heap, without removing it""" + * return self.data[0] */ - goto __pyx_L4_continue; - goto __pyx_L6; - } - /* "sklearn/neighbors/ball_tree.pyx":1019 - * #------------------------------------------------------------ - * # Case 1: query point is outside node radius - * elif dist_p_LB > heapqueue_largest(near_set_dist, k): # <<<<<<<<<<<<<< - * continue - * - */ - __pyx_t_1 = (__pyx_v_dist_p_LB > __pyx_v_heapqueue_largest(__pyx_v_near_set_dist, __pyx_v_k)); - if (__pyx_t_1) { + /* function exit code */ + __pyx_L1_error:; + __Pyx_WriteUnraisable("sklearn.neighbors.ball_tree.NodeHeap.peek", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":1020 - * # Case 1: query point is outside node radius - * elif dist_p_LB > heapqueue_largest(near_set_dist, k): - * continue # <<<<<<<<<<<<<< +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":938 + * return self.data[0] * - * #------------------------------------------------------------ + * cdef NodeHeapData_t pop(self): # <<<<<<<<<<<<<< + * """Remove the root of the heap, and update the remaining nodes""" + * if self.n == 0: */ - goto __pyx_L4_continue; - goto __pyx_L6; - } - - /* "sklearn/neighbors/ball_tree.pyx":1024 - * #------------------------------------------------------------ - * # Case 2: this is a leaf node. Update set of nearby points - * elif node_info.is_leaf: # <<<<<<<<<<<<<< - * for i from node_info.idx_start <= i < node_info.idx_end: - * dist_pt = dist_p(pt, - */ - if (__pyx_v_node_info->is_leaf) { - /* "sklearn/neighbors/ball_tree.pyx":1025 - * # Case 2: this is a leaf node. Update set of nearby points - * elif node_info.is_leaf: - * for i from node_info.idx_start <= i < node_info.idx_end: # <<<<<<<<<<<<<< - * dist_pt = dist_p(pt, - * data + n_features * idx_array[i], - */ - __pyx_t_2 = __pyx_v_node_info->idx_end; - for (__pyx_v_i = __pyx_v_node_info->idx_start; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { +static struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_f_7sklearn_9neighbors_9ball_tree_8NodeHeap_pop(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_self) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_child1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_child2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_swap; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *__pyx_v_data_arr; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_v_popped_element; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pop", 0); - /* "sklearn/neighbors/ball_tree.pyx":1028 - * dist_pt = dist_p(pt, - * data + n_features * idx_array[i], - * n_features, p) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":940 + * cdef NodeHeapData_t pop(self): + * """Remove the root of the heap, and update the remaining nodes""" + * if self.n == 0: # <<<<<<<<<<<<<< + * raise ValueError('cannot pop on empty heap') * - * dmax = heapqueue_largest(near_set_dist, k) */ - __pyx_v_dist_pt = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p(__pyx_v_pt, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features, __pyx_v_p); + __pyx_t_1 = ((__pyx_v_self->n == 0) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":1030 - * n_features, p) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":941 + * """Remove the root of the heap, and update the remaining nodes""" + * if self.n == 0: + * raise ValueError('cannot pop on empty heap') # <<<<<<<<<<<<<< * - * dmax = heapqueue_largest(near_set_dist, k) # <<<<<<<<<<<<<< - * - * if dist_pt == dmax: + * cdef ITYPE_t i, i_child1, i_child2, i_swap */ - __pyx_v_dmax = __pyx_v_heapqueue_largest(__pyx_v_near_set_dist, __pyx_v_k); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 941; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 941; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "sklearn/neighbors/ball_tree.pyx":1032 - * dmax = heapqueue_largest(near_set_dist, k) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":944 * - * if dist_pt == dmax: # <<<<<<<<<<<<<< - * check_index = heapqueue_idx_largest(near_set_indx, k) + * cdef ITYPE_t i, i_child1, i_child2, i_swap + * cdef NodeHeapData_t* data_arr = &self.data[0] # <<<<<<<<<<<<<< + * cdef NodeHeapData_t popped_element = data_arr[0] * */ - __pyx_t_1 = (__pyx_v_dist_pt == __pyx_v_dmax); - if (__pyx_t_1) { + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 944; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_data_arr = (&(*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t *) __pyx_v_self->data.data) + __pyx_t_3)) )))); - /* "sklearn/neighbors/ball_tree.pyx":1033 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":945 + * cdef ITYPE_t i, i_child1, i_child2, i_swap + * cdef NodeHeapData_t* data_arr = &self.data[0] + * cdef NodeHeapData_t popped_element = data_arr[0] # <<<<<<<<<<<<<< * - * if dist_pt == dmax: - * check_index = heapqueue_idx_largest(near_set_indx, k) # <<<<<<<<<<<<<< - * - * elif dist_pt < dmax: + * # pop off the first element, move the last element to the front, */ - __pyx_v_check_index = __pyx_v_heapqueue_idx_largest(__pyx_v_near_set_indx, __pyx_v_k); - goto __pyx_L9; - } + __pyx_v_popped_element = (__pyx_v_data_arr[0]); - /* "sklearn/neighbors/ball_tree.pyx":1035 - * check_index = heapqueue_idx_largest(near_set_indx, k) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":949 + * # pop off the first element, move the last element to the front, + * # and then perform swaps until the heap is back in order + * data_arr[0] = data_arr[self.n - 1] # <<<<<<<<<<<<<< + * self.n -= 1 * - * elif dist_pt < dmax: # <<<<<<<<<<<<<< - * heapqueue_insert(dist_pt, idx_array[i], - * near_set_dist, near_set_indx, k) - */ - __pyx_t_1 = (__pyx_v_dist_pt < __pyx_v_dmax); - if (__pyx_t_1) { - - /* "sklearn/neighbors/ball_tree.pyx":1037 - * elif dist_pt < dmax: - * heapqueue_insert(dist_pt, idx_array[i], - * near_set_dist, near_set_indx, k) # <<<<<<<<<<<<<< - * if dmax == heapqueue_largest(near_set_dist, k): - * check_index = heapqueue_idx_largest(near_set_indx, - */ - __pyx_v_heapqueue_insert(__pyx_v_dist_pt, (__pyx_v_idx_array[__pyx_v_i]), __pyx_v_near_set_dist, __pyx_v_near_set_indx, __pyx_v_k); - - /* "sklearn/neighbors/ball_tree.pyx":1038 - * heapqueue_insert(dist_pt, idx_array[i], - * near_set_dist, near_set_indx, k) - * if dmax == heapqueue_largest(near_set_dist, k): # <<<<<<<<<<<<<< - * check_index = heapqueue_idx_largest(near_set_indx, - * k) */ - __pyx_t_1 = (__pyx_v_dmax == __pyx_v_heapqueue_largest(__pyx_v_near_set_dist, __pyx_v_k)); - if (__pyx_t_1) { + (__pyx_v_data_arr[0]) = (__pyx_v_data_arr[(__pyx_v_self->n - 1)]); - /* "sklearn/neighbors/ball_tree.pyx":1040 - * if dmax == heapqueue_largest(near_set_dist, k): - * check_index = heapqueue_idx_largest(near_set_indx, - * k) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":950 + * # and then perform swaps until the heap is back in order + * data_arr[0] = data_arr[self.n - 1] + * self.n -= 1 # <<<<<<<<<<<<<< * - * #------------------------------------------------------------ + * i = 0 */ - __pyx_v_check_index = __pyx_v_heapqueue_idx_largest(__pyx_v_near_set_indx, __pyx_v_k); - goto __pyx_L10; - } - __pyx_L10:; - goto __pyx_L9; - } - __pyx_L9:; - } - goto __pyx_L6; - } - /*else*/ { - - /* "sklearn/neighbors/ball_tree.pyx":1046 - * # starting with the one whose centroid is closest - * else: - * i1 = 2 * i_node + 1 # <<<<<<<<<<<<<< - * i2 = i1 + 1 - * dist_p_LB_1 = calc_dist_p_LB(pt, (node_centroid_arr - */ - __pyx_v_i1 = ((2 * __pyx_v_i_node) + 1); - - /* "sklearn/neighbors/ball_tree.pyx":1047 - * else: - * i1 = 2 * i_node + 1 - * i2 = i1 + 1 # <<<<<<<<<<<<<< - * dist_p_LB_1 = calc_dist_p_LB(pt, (node_centroid_arr - * + i1 * n_features), - */ - __pyx_v_i2 = (__pyx_v_i1 + 1); - - /* "sklearn/neighbors/ball_tree.pyx":1051 - * + i1 * n_features), - * node_info_arr[i1].radius, - * n_features, p) # <<<<<<<<<<<<<< - * dist_p_LB_2 = calc_dist_p_LB(pt, (node_centroid_arr - * + i2 * n_features), - */ - __pyx_v_dist_p_LB_1 = __pyx_f_7sklearn_9neighbors_9ball_tree_calc_dist_p_LB(__pyx_v_pt, (__pyx_v_node_centroid_arr + (__pyx_v_i1 * __pyx_v_n_features)), (__pyx_v_node_info_arr[__pyx_v_i1]).radius, __pyx_v_n_features, __pyx_v_p); + __pyx_v_self->n = (__pyx_v_self->n - 1); - /* "sklearn/neighbors/ball_tree.pyx":1055 - * + i2 * n_features), - * node_info_arr[i2].radius, - * n_features, p) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":952 + * self.n -= 1 * - * # append children to stack: last-in-first-out + * i = 0 # <<<<<<<<<<<<<< + * + * while (i < self.n): */ - __pyx_v_dist_p_LB_2 = __pyx_f_7sklearn_9neighbors_9ball_tree_calc_dist_p_LB(__pyx_v_pt, (__pyx_v_node_centroid_arr + (__pyx_v_i2 * __pyx_v_n_features)), (__pyx_v_node_info_arr[__pyx_v_i2]).radius, __pyx_v_n_features, __pyx_v_p); + __pyx_v_i = 0; - /* "sklearn/neighbors/ball_tree.pyx":1058 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":954 + * i = 0 * - * # append children to stack: last-in-first-out - * if dist_p_LB_2 <= dist_p_LB_1: # <<<<<<<<<<<<<< - * item.i_node = i1 - * item.dist_p_LB = dist_p_LB_1 + * while (i < self.n): # <<<<<<<<<<<<<< + * i_child1 = 2 * i + 1 + * i_child2 = 2 * i + 2 */ - __pyx_t_1 = (__pyx_v_dist_p_LB_2 <= __pyx_v_dist_p_LB_1); - if (__pyx_t_1) { + while (1) { + __pyx_t_1 = ((__pyx_v_i < __pyx_v_self->n) != 0); + if (!__pyx_t_1) break; - /* "sklearn/neighbors/ball_tree.pyx":1059 - * # append children to stack: last-in-first-out - * if dist_p_LB_2 <= dist_p_LB_1: - * item.i_node = i1 # <<<<<<<<<<<<<< - * item.dist_p_LB = dist_p_LB_1 - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":955 + * + * while (i < self.n): + * i_child1 = 2 * i + 1 # <<<<<<<<<<<<<< + * i_child2 = 2 * i + 2 + * i_swap = 0 */ - __pyx_v_item.i_node = __pyx_v_i1; + __pyx_v_i_child1 = ((2 * __pyx_v_i) + 1); - /* "sklearn/neighbors/ball_tree.pyx":1060 - * if dist_p_LB_2 <= dist_p_LB_1: - * item.i_node = i1 - * item.dist_p_LB = dist_p_LB_1 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":956 + * while (i < self.n): + * i_child1 = 2 * i + 1 + * i_child2 = 2 * i + 2 # <<<<<<<<<<<<<< + * i_swap = 0 * */ - __pyx_v_item.dist_p_LB = __pyx_v_dist_p_LB_1; + __pyx_v_i_child2 = ((2 * __pyx_v_i) + 2); - /* "sklearn/neighbors/ball_tree.pyx":1061 - * item.i_node = i1 - * item.dist_p_LB = dist_p_LB_1 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":957 + * i_child1 = 2 * i + 1 + * i_child2 = 2 * i + 2 + * i_swap = 0 # <<<<<<<<<<<<<< * - * item.i_node = i2 + * if i_child2 < self.n: */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); + __pyx_v_i_swap = 0; - /* "sklearn/neighbors/ball_tree.pyx":1063 - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":959 + * i_swap = 0 * - * item.i_node = i2 # <<<<<<<<<<<<<< - * item.dist_p_LB = dist_p_LB_2 - * stack_push(node_stack, item) + * if i_child2 < self.n: # <<<<<<<<<<<<<< + * if data_arr[i_child1].val <= data_arr[i_child2].val: + * i_swap = i_child1 */ - __pyx_v_item.i_node = __pyx_v_i2; + __pyx_t_1 = ((__pyx_v_i_child2 < __pyx_v_self->n) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":1064 - * - * item.i_node = i2 - * item.dist_p_LB = dist_p_LB_2 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":960 * + * if i_child2 < self.n: + * if data_arr[i_child1].val <= data_arr[i_child2].val: # <<<<<<<<<<<<<< + * i_swap = i_child1 + * else: */ - __pyx_v_item.dist_p_LB = __pyx_v_dist_p_LB_2; + __pyx_t_1 = (((__pyx_v_data_arr[__pyx_v_i_child1]).val <= (__pyx_v_data_arr[__pyx_v_i_child2]).val) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":1065 - * item.i_node = i2 - * item.dist_p_LB = dist_p_LB_2 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":961 + * if i_child2 < self.n: + * if data_arr[i_child1].val <= data_arr[i_child2].val: + * i_swap = i_child1 # <<<<<<<<<<<<<< * else: + * i_swap = i_child2 */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); - goto __pyx_L11; + __pyx_v_i_swap = __pyx_v_i_child1; + goto __pyx_L7; } /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":1068 - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":963 + * i_swap = i_child1 * else: - * item.i_node = i2 # <<<<<<<<<<<<<< - * item.dist_p_LB = dist_p_LB_2 - * stack_push(node_stack, item) + * i_swap = i_child2 # <<<<<<<<<<<<<< + * elif i_child1 < self.n: + * i_swap = i_child1 */ - __pyx_v_item.i_node = __pyx_v_i2; + __pyx_v_i_swap = __pyx_v_i_child2; + } + __pyx_L7:; + goto __pyx_L6; + } - /* "sklearn/neighbors/ball_tree.pyx":1069 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":964 * else: - * item.i_node = i2 - * item.dist_p_LB = dist_p_LB_2 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) - * + * i_swap = i_child2 + * elif i_child1 < self.n: # <<<<<<<<<<<<<< + * i_swap = i_child1 + * else: */ - __pyx_v_item.dist_p_LB = __pyx_v_dist_p_LB_2; + __pyx_t_1 = ((__pyx_v_i_child1 < __pyx_v_self->n) != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":1070 - * item.i_node = i2 - * item.dist_p_LB = dist_p_LB_2 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< - * - * item.i_node = i1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":965 + * i_swap = i_child2 + * elif i_child1 < self.n: + * i_swap = i_child1 # <<<<<<<<<<<<<< + * else: + * break */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); + __pyx_v_i_swap = __pyx_v_i_child1; + goto __pyx_L6; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":1072 - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":967 + * i_swap = i_child1 + * else: + * break # <<<<<<<<<<<<<< * - * item.i_node = i1 # <<<<<<<<<<<<<< - * item.dist_p_LB = dist_p_LB_1 - * stack_push(node_stack, item) + * if (i_swap > 0) and (data_arr[i_swap].val <= data_arr[i].val): */ - __pyx_v_item.i_node = __pyx_v_i1; + goto __pyx_L5_break; + } + __pyx_L6:; - /* "sklearn/neighbors/ball_tree.pyx":1073 - * - * item.i_node = i1 - * item.dist_p_LB = dist_p_LB_1 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":969 + * break * + * if (i_swap > 0) and (data_arr[i_swap].val <= data_arr[i].val): # <<<<<<<<<<<<<< + * swap_nodes(data_arr, i, i_swap) + * i = i_swap */ - __pyx_v_item.dist_p_LB = __pyx_v_dist_p_LB_1; + __pyx_t_1 = ((__pyx_v_i_swap > 0) != 0); + if (__pyx_t_1) { + __pyx_t_4 = (((__pyx_v_data_arr[__pyx_v_i_swap]).val <= (__pyx_v_data_arr[__pyx_v_i]).val) != 0); + __pyx_t_5 = __pyx_t_4; + } else { + __pyx_t_5 = __pyx_t_1; + } + if (__pyx_t_5) { - /* "sklearn/neighbors/ball_tree.pyx":1074 - * item.i_node = i1 - * item.dist_p_LB = dist_p_LB_1 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":970 * - * if check_index == heapqueue_idx_largest(near_set_indx, k): + * if (i_swap > 0) and (data_arr[i_swap].val <= data_arr[i].val): + * swap_nodes(data_arr, i, i_swap) # <<<<<<<<<<<<<< + * i = i_swap + * else: */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); - } - __pyx_L11:; - } - __pyx_L6:; - __pyx_L4_continue:; - } + __pyx_f_7sklearn_9neighbors_9ball_tree_swap_nodes(__pyx_v_data_arr, __pyx_v_i, __pyx_v_i_swap); - /* "sklearn/neighbors/ball_tree.pyx":1076 - * stack_push(node_stack, item) - * - * if check_index == heapqueue_idx_largest(near_set_indx, k): # <<<<<<<<<<<<<< - * self.warning_flag = True - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":971 + * if (i_swap > 0) and (data_arr[i_swap].val <= data_arr[i].val): + * swap_nodes(data_arr, i, i_swap) + * i = i_swap # <<<<<<<<<<<<<< + * else: + * break */ - __pyx_t_1 = (__pyx_v_check_index == __pyx_v_heapqueue_idx_largest(__pyx_v_near_set_indx, __pyx_v_k)); - if (__pyx_t_1) { + __pyx_v_i = __pyx_v_i_swap; + goto __pyx_L8; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":1077 - * - * if check_index == heapqueue_idx_largest(near_set_indx, k): - * self.warning_flag = True # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":973 + * i = i_swap + * else: + * break # <<<<<<<<<<<<<< * - * for i from 0 <= i < k: + * return popped_element */ - __pyx_v_self->warning_flag = 1; - goto __pyx_L12; + goto __pyx_L5_break; + } + __pyx_L8:; } - __pyx_L12:; + __pyx_L5_break:; - /* "sklearn/neighbors/ball_tree.pyx":1079 - * self.warning_flag = True + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":975 + * break * - * for i from 0 <= i < k: # <<<<<<<<<<<<<< - * near_set_dist[i] = dist_from_dist_p(near_set_dist[i], p) + * return popped_element # <<<<<<<<<<<<<< * + * cdef void clear(self): */ - __pyx_t_2 = __pyx_v_k; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { + __pyx_r = __pyx_v_popped_element; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":1080 - * - * for i from 0 <= i < k: - * near_set_dist[i] = dist_from_dist_p(near_set_dist[i], p) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":938 + * return self.data[0] * - * cdef ITYPE_t query_radius_count_(BallTree self, + * cdef NodeHeapData_t pop(self): # <<<<<<<<<<<<<< + * """Remove the root of the heap, and update the remaining nodes""" + * if self.n == 0: */ - (__pyx_v_near_set_dist[__pyx_v_i]) = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_from_dist_p((__pyx_v_near_set_dist[__pyx_v_i]), __pyx_v_p); - } + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_WriteUnraisable("sklearn.neighbors.ball_tree.NodeHeap.pop", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_L0:; __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":1082 - * near_set_dist[i] = dist_from_dist_p(near_set_dist[i], p) +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":977 + * return popped_element * - * cdef ITYPE_t query_radius_count_(BallTree self, # <<<<<<<<<<<<<< - * DTYPE_t* pt, DTYPE_t r, - * stack* node_stack): + * cdef void clear(self): # <<<<<<<<<<<<<< + * """Clear the heap""" + * self.n = 0 */ -static __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_8BallTree_query_radius_count_(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_r, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *__pyx_v_node_stack) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_data; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx_array; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_node_centroid_arr; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *__pyx_v_node_info_arr; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *__pyx_v_node_info; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_features; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_node; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_count; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_r_p; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_dist_pt; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item __pyx_v_item; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_r; +static void __pyx_f_7sklearn_9neighbors_9ball_tree_8NodeHeap_clear(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_self) { __Pyx_RefNannyDeclarations - int __pyx_t_1; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_2; - long __pyx_t_3; - __Pyx_RefNannySetupContext("query_radius_count_"); - - /* "sklearn/neighbors/ball_tree.pyx":1085 - * DTYPE_t* pt, DTYPE_t r, - * stack* node_stack): - * cdef DTYPE_t* data = self.data.data # <<<<<<<<<<<<<< - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - */ - __pyx_v_data = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_self->data->data); - - /* "sklearn/neighbors/ball_tree.pyx":1086 - * stack* node_stack): - * cdef DTYPE_t* data = self.data.data - * cdef ITYPE_t* idx_array = self.idx_array.data # <<<<<<<<<<<<<< - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - */ - __pyx_v_idx_array = ((__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *)__pyx_v_self->idx_array->data); - - /* "sklearn/neighbors/ball_tree.pyx":1087 - * cdef DTYPE_t* data = self.data.data - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data # <<<<<<<<<<<<<< - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - * cdef NodeInfo* node_info = node_info_arr - */ - __pyx_v_node_centroid_arr = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_self->node_centroid_arr->data); + __Pyx_RefNannySetupContext("clear", 0); - /* "sklearn/neighbors/ball_tree.pyx":1088 - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data # <<<<<<<<<<<<<< - * cdef NodeInfo* node_info = node_info_arr + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":979 + * cdef void clear(self): + * """Clear the heap""" + * self.n = 0 # <<<<<<<<<<<<<< * - */ - __pyx_v_node_info_arr = ((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *)__pyx_v_self->node_info_arr->data); - - /* "sklearn/neighbors/ball_tree.pyx":1089 - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - * cdef NodeInfo* node_info = node_info_arr # <<<<<<<<<<<<<< * - * cdef DTYPE_t p = self.p */ - __pyx_v_node_info = __pyx_v_node_info_arr; + __pyx_v_self->n = 0; - /* "sklearn/neighbors/ball_tree.pyx":1091 - * cdef NodeInfo* node_info = node_info_arr + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":977 + * return popped_element * - * cdef DTYPE_t p = self.p # <<<<<<<<<<<<<< - * cdef ITYPE_t n_features = self.data.shape[1] - * cdef ITYPE_t i, i_node + * cdef void clear(self): # <<<<<<<<<<<<<< + * """Clear the heap""" + * self.n = 0 */ - __pyx_v_p = __pyx_v_self->p; - /* "sklearn/neighbors/ball_tree.pyx":1092 + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":985 + * # newObj function + * # this is a helper function for pickling + * def newObj(obj): # <<<<<<<<<<<<<< + * return obj.__new__(obj) * - * cdef DTYPE_t p = self.p - * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< - * cdef ITYPE_t i, i_node - * cdef ITYPE_t count = 0 */ - __pyx_v_n_features = (__pyx_v_self->data->dimensions[1]); - /* "sklearn/neighbors/ball_tree.pyx":1094 - * cdef ITYPE_t n_features = self.data.shape[1] - * cdef ITYPE_t i, i_node - * cdef ITYPE_t count = 0 # <<<<<<<<<<<<<< - * cdef DTYPE_t r_p = dist_p_from_dist(r, p) - * cdef DTYPE_t dist_pt - */ - __pyx_v_count = 0; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_3newObj(PyObject *__pyx_self, PyObject *__pyx_v_obj); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_9ball_tree_3newObj = {__Pyx_NAMESTR("newObj"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_3newObj, METH_O, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_3newObj(PyObject *__pyx_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("newObj (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_2newObj(__pyx_self, ((PyObject *)__pyx_v_obj)); - /* "sklearn/neighbors/ball_tree.pyx":1095 - * cdef ITYPE_t i, i_node - * cdef ITYPE_t count = 0 - * cdef DTYPE_t r_p = dist_p_from_dist(r, p) # <<<<<<<<<<<<<< - * cdef DTYPE_t dist_pt - * - */ - __pyx_v_r_p = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p_from_dist(__pyx_v_r, __pyx_v_p); + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":1100 - * cdef stack_item item - * - * item.i_node = 0 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) - * - */ - __pyx_v_item.i_node = 0; +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_2newObj(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("newObj", 0); - /* "sklearn/neighbors/ball_tree.pyx":1101 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":986 + * # this is a helper function for pickling + * def newObj(obj): + * return obj.__new__(obj) # <<<<<<<<<<<<<< * - * item.i_node = 0 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< * - * while(node_stack.n > 0): */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_obj, __pyx_n_s_new); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 986; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 986; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 986; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":1103 - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":985 + * # newObj function + * # this is a helper function for pickling + * def newObj(obj): # <<<<<<<<<<<<<< + * return obj.__new__(obj) * - * while(node_stack.n > 0): # <<<<<<<<<<<<<< - * item = stack_pop(node_stack) - * i_node = item.i_node */ - while (1) { - __pyx_t_1 = (__pyx_v_node_stack->n > 0); - if (!__pyx_t_1) break; - /* "sklearn/neighbors/ball_tree.pyx":1104 - * - * while(node_stack.n > 0): - * item = stack_pop(node_stack) # <<<<<<<<<<<<<< - * i_node = item.i_node - * node_info = node_info_arr + i_node - */ - __pyx_v_item = __pyx_f_7sklearn_9neighbors_9ball_tree_stack_pop(__pyx_v_node_stack); + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.newObj", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":1105 - * while(node_stack.n > 0): - * item = stack_pop(node_stack) - * i_node = item.i_node # <<<<<<<<<<<<<< - * node_info = node_info_arr + i_node - * +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1026 + * # Use cinit to initialize all arrays to empty: this will prevent memory + * # errors and seg-faults in rare cases where __init__ is not called + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') */ - __pyx_v_i_node = __pyx_v_item.i_node; - /* "sklearn/neighbors/ball_tree.pyx":1106 - * item = stack_pop(node_stack) - * i_node = item.i_node - * node_info = node_info_arr + i_node # <<<<<<<<<<<<<< - * - * dist_pt = dist(pt, node_centroid_arr + n_features * i_node, - */ - __pyx_v_node_info = (__pyx_v_node_info_arr + __pyx_v_i_node); +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} + if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree___cinit__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self)); - /* "sklearn/neighbors/ball_tree.pyx":1109 - * - * dist_pt = dist(pt, node_centroid_arr + n_features * i_node, - * n_features, p) # <<<<<<<<<<<<<< - * - * #------------------------------------------------------------ - */ - __pyx_v_dist_pt = __pyx_f_7sklearn_9neighbors_9ball_tree_dist(__pyx_v_pt, (__pyx_v_node_centroid_arr + (__pyx_v_n_features * __pyx_v_i_node)), __pyx_v_n_features, __pyx_v_p); + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":1114 - * # Case 1: all node points are outside distance r. - * # prune this branch. - * if dist_pt - node_info.radius > r: # <<<<<<<<<<<<<< - * continue - * - */ - __pyx_t_1 = ((__pyx_v_dist_pt - __pyx_v_node_info->radius) > __pyx_v_r); - if (__pyx_t_1) { +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree___cinit__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); - /* "sklearn/neighbors/ball_tree.pyx":1115 - * # prune this branch. - * if dist_pt - node_info.radius > r: - * continue # <<<<<<<<<<<<<< - * - * #------------------------------------------------------------ + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1027 + * # errors and seg-faults in rare cases where __init__ is not called + * def __cinit__(self): + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') */ - goto __pyx_L3_continue; - goto __pyx_L5; - } + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__10, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1120 - * # Case 2: all node points are within distance r - * # add all points - * elif dist_pt + node_info.radius < r: # <<<<<<<<<<<<<< - * count += (node_info.idx_end - node_info.idx_start) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1028 + * def __cinit__(self): + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_tuple__11, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_self->idx_array_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->idx_array_arr)); + __pyx_v_self->idx_array_arr = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1029 + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') # <<<<<<<<<<<<<< + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) * */ - __pyx_t_1 = ((__pyx_v_dist_pt + __pyx_v_node_info->radius) < __pyx_v_r); - if (__pyx_t_1) { + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_NodeData); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_tuple__12, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->node_data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->node_data_arr)); + __pyx_v_self->node_data_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1121 - * # add all points - * elif dist_pt + node_info.radius < r: - * count += (node_info.idx_end - node_info.idx_start) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1030 + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) # <<<<<<<<<<<<<< * - * #------------------------------------------------------------ + * self.data = get_memview_DTYPE_2D(self.data_arr) */ - __pyx_v_count = (__pyx_v_count + (__pyx_v_node_info->idx_end - __pyx_v_node_info->idx_start)); - goto __pyx_L5; - } + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__14, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->node_bounds_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + __pyx_v_self->node_bounds_arr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1126 - * # Case 3: this is a leaf node. Go through all points to - * # determine if they fall within radius - * elif node_info.is_leaf: # <<<<<<<<<<<<<< - * for i from node_info.idx_start <= i < node_info.idx_end: - * dist_pt = dist_p(pt, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1032 + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) + * + * self.data = get_memview_DTYPE_2D(self.data_arr) # <<<<<<<<<<<<<< + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) */ - if (__pyx_v_node_info->is_leaf) { + __pyx_t_3 = ((PyObject *)__pyx_v_self->data_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1032; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __pyx_v_self->data = __pyx_t_4; + __pyx_t_4.memview = NULL; + __pyx_t_4.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1127 - * # determine if they fall within radius - * elif node_info.is_leaf: - * for i from node_info.idx_start <= i < node_info.idx_end: # <<<<<<<<<<<<<< - * dist_pt = dist_p(pt, - * data + idx_array[i] * n_features, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1033 + * + * self.data = get_memview_DTYPE_2D(self.data_arr) + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) # <<<<<<<<<<<<<< + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) */ - __pyx_t_2 = __pyx_v_node_info->idx_end; - for (__pyx_v_i = __pyx_v_node_info->idx_start; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { + __pyx_t_3 = ((PyObject *)__pyx_v_self->idx_array_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1033; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->idx_array, 0); + __pyx_v_self->idx_array = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1130 - * dist_pt = dist_p(pt, - * data + idx_array[i] * n_features, - * n_features, p) # <<<<<<<<<<<<<< - * if dist_pt <= r_p: - * count += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1034 + * self.data = get_memview_DTYPE_2D(self.data_arr) + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) # <<<<<<<<<<<<<< + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) + * */ - __pyx_v_dist_pt = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p(__pyx_v_pt, (__pyx_v_data + ((__pyx_v_idx_array[__pyx_v_i]) * __pyx_v_n_features)), __pyx_v_n_features, __pyx_v_p); + __pyx_t_3 = ((PyObject *)__pyx_v_self->node_data_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_NodeData_1D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1034; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_data, 0); + __pyx_v_self->node_data = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1131 - * data + idx_array[i] * n_features, - * n_features, p) - * if dist_pt <= r_p: # <<<<<<<<<<<<<< - * count += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1035 + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) # <<<<<<<<<<<<<< * + * self.leaf_size = 0 */ - __pyx_t_1 = (__pyx_v_dist_pt <= __pyx_v_r_p); - if (__pyx_t_1) { + __pyx_t_3 = ((PyObject *)__pyx_v_self->node_bounds_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_3D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1035; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_bounds, 0); + __pyx_v_self->node_bounds = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1132 - * n_features, p) - * if dist_pt <= r_p: - * count += 1 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1037 + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) * - * #------------------------------------------------------------ + * self.leaf_size = 0 # <<<<<<<<<<<<<< + * self.n_levels = 0 + * self.n_nodes = 0 */ - __pyx_v_count = (__pyx_v_count + 1); - goto __pyx_L8; - } - __pyx_L8:; - } - goto __pyx_L5; - } - /*else*/ { + __pyx_v_self->leaf_size = 0; - /* "sklearn/neighbors/ball_tree.pyx":1137 - * # Case 4: Node is not a leaf. Recursively query subnodes - * else: - * item.i_node = 2 * i_node + 1 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1038 + * + * self.leaf_size = 0 + * self.n_levels = 0 # <<<<<<<<<<<<<< + * self.n_nodes = 0 * */ - __pyx_v_item.i_node = ((2 * __pyx_v_i_node) + 1); + __pyx_v_self->n_levels = 0; - /* "sklearn/neighbors/ball_tree.pyx":1138 - * else: - * item.i_node = 2 * i_node + 1 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1039 + * self.leaf_size = 0 + * self.n_levels = 0 + * self.n_nodes = 0 # <<<<<<<<<<<<<< * - * item.i_node = i = 2 * i_node + 2 + * self.euclidean = False */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); + __pyx_v_self->n_nodes = 0; - /* "sklearn/neighbors/ball_tree.pyx":1140 - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1041 + * self.n_nodes = 0 * - * item.i_node = i = 2 * i_node + 2 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) + * self.euclidean = False # <<<<<<<<<<<<<< * + * self.n_trims = 0 */ - __pyx_t_3 = ((2 * __pyx_v_i_node) + 2); - __pyx_v_item.i_node = __pyx_t_3; - __pyx_v_i = __pyx_t_3; + __pyx_v_self->euclidean = 0; - /* "sklearn/neighbors/ball_tree.pyx":1141 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1043 + * self.euclidean = False * - * item.i_node = i = 2 * i_node + 2 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< + * self.n_trims = 0 # <<<<<<<<<<<<<< + * self.n_leaves = 0 + * self.n_splits = 0 + */ + __pyx_v_self->n_trims = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1044 * - * return count + * self.n_trims = 0 + * self.n_leaves = 0 # <<<<<<<<<<<<<< + * self.n_splits = 0 + * self.n_calls = 0 */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); - } - __pyx_L5:; - __pyx_L3_continue:; - } + __pyx_v_self->n_leaves = 0; - /* "sklearn/neighbors/ball_tree.pyx":1143 - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1045 + * self.n_trims = 0 + * self.n_leaves = 0 + * self.n_splits = 0 # <<<<<<<<<<<<<< + * self.n_calls = 0 * - * return count # <<<<<<<<<<<<<< + */ + __pyx_v_self->n_splits = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1046 + * self.n_leaves = 0 + * self.n_splits = 0 + * self.n_calls = 0 # <<<<<<<<<<<<<< * - * cdef ITYPE_t query_radius_idx_only_(BallTree self, + * def __init__(self, data, + */ + __pyx_v_self->n_calls = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1026 + * # Use cinit to initialize all arrays to empty: this will prevent memory + * # errors and seg-faults in rare cases where __init__ is not called + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') */ - __pyx_r = __pyx_v_count; - goto __pyx_L0; + /* function exit code */ __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __PYX_XDEC_MEMVIEW(&__pyx_t_4, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":1145 - * return count +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1048 + * self.n_calls = 0 * - * cdef ITYPE_t query_radius_idx_only_(BallTree self, # <<<<<<<<<<<<<< - * DTYPE_t* pt, DTYPE_t r, - * ITYPE_t* indices, - */ - -static __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_8BallTree_query_radius_idx_only_(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_r, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_indices, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *__pyx_v_node_stack) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_data; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx_array; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_node_centroid_arr; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *__pyx_v_node_info_arr; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *__pyx_v_node_info; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_features; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_node; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_idx_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_r_p; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_dist_pt; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item __pyx_v_item; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_r; + * def __init__(self, data, # <<<<<<<<<<<<<< + * leaf_size=40, metric='minkowski', **kwargs): + * self.data_arr = np.asarray(data, dtype=DTYPE, order='C') + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_data = 0; + PyObject *__pyx_v_leaf_size = 0; + PyObject *__pyx_v_metric = 0; + PyObject *__pyx_v_kwargs = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; __Pyx_RefNannyDeclarations - int __pyx_t_1; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_2; - long __pyx_t_3; - __Pyx_RefNannySetupContext("query_radius_idx_only_"); + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + __pyx_v_kwargs = PyDict_New(); if (unlikely(!__pyx_v_kwargs)) return -1; + __Pyx_GOTREF(__pyx_v_kwargs); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_data,&__pyx_n_s_leaf_size,&__pyx_n_s_metric,0}; + PyObject* values[3] = {0,0,0}; + values[1] = ((PyObject *)__pyx_int_40); + values[2] = ((PyObject *)__pyx_n_s_minkowski); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_data)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_leaf_size); + if (value) { values[1] = value; kw_args--; } + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_metric); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, __pyx_v_kwargs, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1048; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_data = values[0]; + __pyx_v_leaf_size = values[1]; + __pyx_v_metric = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1048; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_DECREF(__pyx_v_kwargs); __pyx_v_kwargs = 0; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_2__init__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self), __pyx_v_data, __pyx_v_leaf_size, __pyx_v_metric, __pyx_v_kwargs); - /* "sklearn/neighbors/ball_tree.pyx":1149 - * ITYPE_t* indices, - * stack* node_stack): - * cdef DTYPE_t* data = self.data.data # <<<<<<<<<<<<<< - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - */ - __pyx_v_data = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_self->data->data); + /* function exit code */ + __Pyx_XDECREF(__pyx_v_kwargs); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":1150 - * stack* node_stack): - * cdef DTYPE_t* data = self.data.data - * cdef ITYPE_t* idx_array = self.idx_array.data # <<<<<<<<<<<<<< - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - */ - __pyx_v_idx_array = ((__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *)__pyx_v_self->idx_array->data); +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_2__init__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_data, PyObject *__pyx_v_leaf_size, PyObject *__pyx_v_metric, PyObject *__pyx_v_kwargs) { + PyObject *__pyx_v_n_samples = NULL; + Py_ssize_t __pyx_v_n_features; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + double __pyx_t_10; + __Pyx_memviewslice __pyx_t_11 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_12 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_INCREF(__pyx_v_metric); - /* "sklearn/neighbors/ball_tree.pyx":1151 - * cdef DTYPE_t* data = self.data.data - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data # <<<<<<<<<<<<<< - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - * cdef NodeInfo* node_info = node_info_arr + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1050 + * def __init__(self, data, + * leaf_size=40, metric='minkowski', **kwargs): + * self.data_arr = np.asarray(data, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.data = get_memview_DTYPE_2D(self.data_arr) + * */ - __pyx_v_node_centroid_arr = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_self->node_centroid_arr->data); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_data); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_data); + __Pyx_GIVEREF(__pyx_v_data); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1152 - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data # <<<<<<<<<<<<<< - * cdef NodeInfo* node_info = node_info_arr + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1051 + * leaf_size=40, metric='minkowski', **kwargs): + * self.data_arr = np.asarray(data, dtype=DTYPE, order='C') + * self.data = get_memview_DTYPE_2D(self.data_arr) # <<<<<<<<<<<<<< * + * self.leaf_size = leaf_size */ - __pyx_v_node_info_arr = ((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *)__pyx_v_self->node_info_arr->data); + __pyx_t_4 = ((PyObject *)__pyx_v_self->data_arr); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_4)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __pyx_v_self->data = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1153 - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - * cdef NodeInfo* node_info = node_info_arr # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1053 + * self.data = get_memview_DTYPE_2D(self.data_arr) * - * cdef DTYPE_t p = self.p + * self.leaf_size = leaf_size # <<<<<<<<<<<<<< + * self.dist_metric = DistanceMetric.get_metric(metric, **kwargs) + * self.euclidean = (self.dist_metric.__class__.__name__ */ - __pyx_v_node_info = __pyx_v_node_info_arr; + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_leaf_size); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1053; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->leaf_size = __pyx_t_6; - /* "sklearn/neighbors/ball_tree.pyx":1155 - * cdef NodeInfo* node_info = node_info_arr + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1054 * - * cdef DTYPE_t p = self.p # <<<<<<<<<<<<<< - * cdef ITYPE_t n_features = self.data.shape[1] - * cdef ITYPE_t i, i_node + * self.leaf_size = leaf_size + * self.dist_metric = DistanceMetric.get_metric(metric, **kwargs) # <<<<<<<<<<<<<< + * self.euclidean = (self.dist_metric.__class__.__name__ + * == 'EuclideanDistance') */ - __pyx_v_p = __pyx_v_self->p; + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric)), __pyx_n_s_get_metric); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_metric); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_metric); + __Pyx_GIVEREF(__pyx_v_metric); + __pyx_t_1 = __pyx_v_kwargs; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_self->dist_metric); + __Pyx_DECREF(((PyObject *)__pyx_v_self->dist_metric)); + __pyx_v_self->dist_metric = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_t_2); + __pyx_t_2 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1156 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1055 + * self.leaf_size = leaf_size + * self.dist_metric = DistanceMetric.get_metric(metric, **kwargs) + * self.euclidean = (self.dist_metric.__class__.__name__ # <<<<<<<<<<<<<< + * == 'EuclideanDistance') * - * cdef DTYPE_t p = self.p - * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< - * cdef ITYPE_t i, i_node - * cdef ITYPE_t idx_i = 0 */ - __pyx_v_n_features = (__pyx_v_self->data->dimensions[1]); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->dist_metric), __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1055; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1055; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_RichCompare(__pyx_t_1, __pyx_n_s_EuclideanDistance, Py_EQ); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1056; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1158 - * cdef ITYPE_t n_features = self.data.shape[1] - * cdef ITYPE_t i, i_node - * cdef ITYPE_t idx_i = 0 # <<<<<<<<<<<<<< - * cdef DTYPE_t r_p = dist_p_from_dist(r, p) - * cdef DTYPE_t dist_pt + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1056 + * self.dist_metric = DistanceMetric.get_metric(metric, **kwargs) + * self.euclidean = (self.dist_metric.__class__.__name__ + * == 'EuclideanDistance') # <<<<<<<<<<<<<< + * + * metric = self.dist_metric.__class__.__name__ */ - __pyx_v_idx_i = 0; + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_2); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1056; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1159 - * cdef ITYPE_t i, i_node - * cdef ITYPE_t idx_i = 0 - * cdef DTYPE_t r_p = dist_p_from_dist(r, p) # <<<<<<<<<<<<<< - * cdef DTYPE_t dist_pt + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1055 + * self.leaf_size = leaf_size + * self.dist_metric = DistanceMetric.get_metric(metric, **kwargs) + * self.euclidean = (self.dist_metric.__class__.__name__ # <<<<<<<<<<<<<< + * == 'EuclideanDistance') * */ - __pyx_v_r_p = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p_from_dist(__pyx_v_r, __pyx_v_p); + __pyx_v_self->euclidean = __pyx_t_7; - /* "sklearn/neighbors/ball_tree.pyx":1164 - * cdef stack_item item - * - * item.i_node = 0 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1058 + * == 'EuclideanDistance') * + * metric = self.dist_metric.__class__.__name__ # <<<<<<<<<<<<<< + * if metric not in VALID_METRICS: + * raise ValueError('metric {metric} is not valid for ' */ - __pyx_v_item.i_node = 0; + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->dist_metric), __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1058; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1058; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_metric, __pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1165 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1059 * - * item.i_node = 0 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< - * - * while(node_stack.n > 0): + * metric = self.dist_metric.__class__.__name__ + * if metric not in VALID_METRICS: # <<<<<<<<<<<<<< + * raise ValueError('metric {metric} is not valid for ' + * '{BinaryTree}'.format(metric=metric, */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_VALID_METRICS); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_8 = (__Pyx_PySequence_Contains(__pyx_v_metric, __pyx_t_1, Py_NE)); if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_9 = (__pyx_t_8 != 0); + if (__pyx_t_9) { - /* "sklearn/neighbors/ball_tree.pyx":1167 - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1061 + * if metric not in VALID_METRICS: + * raise ValueError('metric {metric} is not valid for ' + * '{BinaryTree}'.format(metric=metric, # <<<<<<<<<<<<<< + * **DOC_DICT)) * - * while(node_stack.n > 0): # <<<<<<<<<<<<<< - * item = stack_pop(node_stack) - * i_node = item.i_node */ - while (1) { - __pyx_t_1 = (__pyx_v_node_stack->n > 0); - if (!__pyx_t_1) break; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_metric_metric_is_not_valid_for_B, __pyx_n_s_format); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); - /* "sklearn/neighbors/ball_tree.pyx":1168 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1062 + * raise ValueError('metric {metric} is not valid for ' + * '{BinaryTree}'.format(metric=metric, + * **DOC_DICT)) # <<<<<<<<<<<<<< * - * while(node_stack.n > 0): - * item = stack_pop(node_stack) # <<<<<<<<<<<<<< - * i_node = item.i_node - * node_info = node_info_arr + i_node + * # validate data */ - __pyx_v_item = __pyx_f_7sklearn_9neighbors_9ball_tree_stack_pop(__pyx_v_node_stack); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DOC_DICT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (unlikely(__pyx_t_3 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "argument after ** must be a mapping, not NoneType"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (likely(PyDict_Check(__pyx_t_3))) { + __pyx_t_2 = PyDict_Copy(__pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + } else { + __pyx_t_2 = PyObject_CallFunctionObjArgs((PyObject*)&PyDict_Type, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1169 - * while(node_stack.n > 0): - * item = stack_pop(node_stack) - * i_node = item.i_node # <<<<<<<<<<<<<< - * node_info = node_info_arr + i_node + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1061 + * if metric not in VALID_METRICS: + * raise ValueError('metric {metric} is not valid for ' + * '{BinaryTree}'.format(metric=metric, # <<<<<<<<<<<<<< + * **DOC_DICT)) * */ - __pyx_v_i_node = __pyx_v_item.i_node; + if (unlikely(PyDict_GetItem(__pyx_t_2, __pyx_n_s_metric))) { + __Pyx_RaiseDoubleKeywordsError("function", __pyx_n_s_metric); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_metric, __pyx_v_metric) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_empty_tuple, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1170 - * item = stack_pop(node_stack) - * i_node = item.i_node - * node_info = node_info_arr + i_node # <<<<<<<<<<<<<< - * - * dist_pt = dist(pt, node_centroid_arr + n_features * i_node, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1060 + * metric = self.dist_metric.__class__.__name__ + * if metric not in VALID_METRICS: + * raise ValueError('metric {metric} is not valid for ' # <<<<<<<<<<<<<< + * '{BinaryTree}'.format(metric=metric, + * **DOC_DICT)) */ - __pyx_v_node_info = (__pyx_v_node_info_arr + __pyx_v_i_node); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "sklearn/neighbors/ball_tree.pyx":1173 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1065 * - * dist_pt = dist(pt, node_centroid_arr + n_features * i_node, - * n_features, p) # <<<<<<<<<<<<<< + * # validate data + * if self.data.size == 0: # <<<<<<<<<<<<<< + * raise ValueError("X is an empty array") * - * #------------------------------------------------------------ */ - __pyx_v_dist_pt = __pyx_f_7sklearn_9neighbors_9ball_tree_dist(__pyx_v_pt, (__pyx_v_node_centroid_arr + (__pyx_v_n_features * __pyx_v_i_node)), __pyx_v_n_features, __pyx_v_p); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_self->data, 2, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_size); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_RichCompare(__pyx_t_2, __pyx_int_0, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_9) { - /* "sklearn/neighbors/ball_tree.pyx":1178 - * # Case 1: all node points are outside distance r. - * # prune this branch. - * if dist_pt - node_info.radius > r: # <<<<<<<<<<<<<< - * continue + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1066 + * # validate data + * if self.data.size == 0: + * raise ValueError("X is an empty array") # <<<<<<<<<<<<<< * + * if leaf_size < 1: */ - __pyx_t_1 = ((__pyx_v_dist_pt - __pyx_v_node_info->radius) > __pyx_v_r); - if (__pyx_t_1) { + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1066; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1066; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "sklearn/neighbors/ball_tree.pyx":1179 - * # prune this branch. - * if dist_pt - node_info.radius > r: - * continue # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1068 + * raise ValueError("X is an empty array") + * + * if leaf_size < 1: # <<<<<<<<<<<<<< + * raise ValueError("leaf_size must be greater than or equal to 1") * - * #------------------------------------------------------------ */ - goto __pyx_L3_continue; - goto __pyx_L5; - } + __pyx_t_3 = PyObject_RichCompare(__pyx_v_leaf_size, __pyx_int_1, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1068; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1068; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_9) { - /* "sklearn/neighbors/ball_tree.pyx":1184 - * # Case 2: all node points are within distance r - * # add all points - * elif dist_pt + node_info.radius < r: # <<<<<<<<<<<<<< - * for i from node_info.idx_start <= i < node_info.idx_end: - * indices[idx_i] = idx_array[i] - */ - __pyx_t_1 = ((__pyx_v_dist_pt + __pyx_v_node_info->radius) < __pyx_v_r); - if (__pyx_t_1) { - - /* "sklearn/neighbors/ball_tree.pyx":1185 - * # add all points - * elif dist_pt + node_info.radius < r: - * for i from node_info.idx_start <= i < node_info.idx_end: # <<<<<<<<<<<<<< - * indices[idx_i] = idx_array[i] - * idx_i += 1 - */ - __pyx_t_2 = __pyx_v_node_info->idx_end; - for (__pyx_v_i = __pyx_v_node_info->idx_start; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { - - /* "sklearn/neighbors/ball_tree.pyx":1186 - * elif dist_pt + node_info.radius < r: - * for i from node_info.idx_start <= i < node_info.idx_end: - * indices[idx_i] = idx_array[i] # <<<<<<<<<<<<<< - * idx_i += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1069 * - */ - (__pyx_v_indices[__pyx_v_idx_i]) = (__pyx_v_idx_array[__pyx_v_i]); - - /* "sklearn/neighbors/ball_tree.pyx":1187 - * for i from node_info.idx_start <= i < node_info.idx_end: - * indices[idx_i] = idx_array[i] - * idx_i += 1 # <<<<<<<<<<<<<< + * if leaf_size < 1: + * raise ValueError("leaf_size must be greater than or equal to 1") # <<<<<<<<<<<<<< * - * #------------------------------------------------------------ - */ - __pyx_v_idx_i = (__pyx_v_idx_i + 1); - } - goto __pyx_L5; - } - - /* "sklearn/neighbors/ball_tree.pyx":1192 - * # Case 3: this is a leaf node. Go through all points to - * # determine if they fall within radius - * elif node_info.is_leaf: # <<<<<<<<<<<<<< - * for i from node_info.idx_start <= i < node_info.idx_end: - * dist_pt = dist_p(pt, + * n_samples = self.data.shape[0] */ - if (__pyx_v_node_info->is_leaf) { + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "sklearn/neighbors/ball_tree.pyx":1193 - * # determine if they fall within radius - * elif node_info.is_leaf: - * for i from node_info.idx_start <= i < node_info.idx_end: # <<<<<<<<<<<<<< - * dist_pt = dist_p(pt, - * data + idx_array[i] * n_features, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1071 + * raise ValueError("leaf_size must be greater than or equal to 1") + * + * n_samples = self.data.shape[0] # <<<<<<<<<<<<<< + * n_features = self.data.shape[1] + * */ - __pyx_t_2 = __pyx_v_node_info->idx_end; - for (__pyx_v_i = __pyx_v_node_info->idx_start; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1071; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_self->data.shape[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1071; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_n_samples = __pyx_t_3; + __pyx_t_3 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1196 - * dist_pt = dist_p(pt, - * data + idx_array[i] * n_features, - * n_features, p) # <<<<<<<<<<<<<< - * if dist_pt <= r_p: - * indices[idx_i] = idx_array[i] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1072 + * + * n_samples = self.data.shape[0] + * n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * + * # determine number of levels in the tree, and from this */ - __pyx_v_dist_pt = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p(__pyx_v_pt, (__pyx_v_data + ((__pyx_v_idx_array[__pyx_v_i]) * __pyx_v_n_features)), __pyx_v_n_features, __pyx_v_p); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1072; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); - /* "sklearn/neighbors/ball_tree.pyx":1197 - * data + idx_array[i] * n_features, - * n_features, p) - * if dist_pt <= r_p: # <<<<<<<<<<<<<< - * indices[idx_i] = idx_array[i] - * idx_i += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1077 + * # the number of nodes in the tree. This results in leaf nodes + * # with numbers of points betweeen leaf_size and 2 * leaf_size + * self.n_levels = np.log2(fmax(1, (n_samples - 1) / self.leaf_size)) + 1 # <<<<<<<<<<<<<< + * self.n_nodes = (2 ** self.n_levels) - 1 + * */ - __pyx_t_1 = (__pyx_v_dist_pt <= __pyx_v_r_p); - if (__pyx_t_1) { + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_log2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_v_n_samples, __pyx_int_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->leaf_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyNumber_Divide(__pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_10 = __pyx_PyFloat_AsDouble(__pyx_t_4); if (unlikely((__pyx_t_10 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyFloat_FromDouble(__pyx_f_7sklearn_9neighbors_9ball_tree_fmax(1.0, __pyx_t_10)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_1, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Add(__pyx_t_4, __pyx_int_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_levels = __pyx_t_6; - /* "sklearn/neighbors/ball_tree.pyx":1198 - * n_features, p) - * if dist_pt <= r_p: - * indices[idx_i] = idx_array[i] # <<<<<<<<<<<<<< - * idx_i += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1078 + * # with numbers of points betweeen leaf_size and 2 * leaf_size + * self.n_levels = np.log2(fmax(1, (n_samples - 1) / self.leaf_size)) + 1 + * self.n_nodes = (2 ** self.n_levels) - 1 # <<<<<<<<<<<<<< * + * # allocate arrays for storage */ - (__pyx_v_indices[__pyx_v_idx_i]) = (__pyx_v_idx_array[__pyx_v_i]); + __pyx_v_self->n_nodes = (__Pyx_pow_long(2, ((long)__pyx_v_self->n_levels)) - 1); - /* "sklearn/neighbors/ball_tree.pyx":1199 - * if dist_pt <= r_p: - * indices[idx_i] = idx_array[i] - * idx_i += 1 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1081 + * + * # allocate arrays for storage + * self.idx_array_arr = np.arange(n_samples, dtype=ITYPE) # <<<<<<<<<<<<<< + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) * - * #------------------------------------------------------------ */ - __pyx_v_idx_i = (__pyx_v_idx_i + 1); - goto __pyx_L10; - } - __pyx_L10:; - } - goto __pyx_L5; - } - /*else*/ { + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_arange); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_n_samples); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_n_samples); + __Pyx_GIVEREF(__pyx_v_n_samples); + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->idx_array_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->idx_array_arr)); + __pyx_v_self->idx_array_arr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1204 - * # Case 4: Node is not a leaf. Recursively query subnodes - * else: - * item.i_node = 2 * i_node + 1 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1082 + * # allocate arrays for storage + * self.idx_array_arr = np.arange(n_samples, dtype=ITYPE) + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) # <<<<<<<<<<<<<< * + * self.node_data_arr = np.zeros(self.n_nodes, dtype=NodeData) */ - __pyx_v_item.i_node = ((2 * __pyx_v_i_node) + 1); + __pyx_t_3 = ((PyObject *)__pyx_v_self->idx_array_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_11 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_11.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1082; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->idx_array, 0); + __pyx_v_self->idx_array = __pyx_t_11; + __pyx_t_11.memview = NULL; + __pyx_t_11.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1205 - * else: - * item.i_node = 2 * i_node + 1 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1084 + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * + * self.node_data_arr = np.zeros(self.n_nodes, dtype=NodeData) # <<<<<<<<<<<<<< + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) * - * item.i_node = i = 2 * i_node + 2 */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_nodes); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_NodeData); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->node_data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->node_data_arr)); + __pyx_v_self->node_data_arr = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1207 - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1085 * - * item.i_node = i = 2 * i_node + 2 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) + * self.node_data_arr = np.zeros(self.n_nodes, dtype=NodeData) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) # <<<<<<<<<<<<<< * + * # Allocate tree-specific data */ - __pyx_t_3 = ((2 * __pyx_v_i_node) + 2); - __pyx_v_item.i_node = __pyx_t_3; - __pyx_v_i = __pyx_t_3; + __pyx_t_4 = ((PyObject *)__pyx_v_self->node_data_arr); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_NodeData_1D(((PyArrayObject *)__pyx_t_4)); if (unlikely(!__pyx_t_12.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_data, 0); + __pyx_v_self->node_data = __pyx_t_12; + __pyx_t_12.memview = NULL; + __pyx_t_12.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1208 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1088 * - * item.i_node = i = 2 * i_node + 2 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< + * # Allocate tree-specific data + * allocate_data(self, self.n_nodes, n_features) # <<<<<<<<<<<<<< + * self._recursive_build(0, 0, n_samples) * - * return idx_i */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); - } - __pyx_L5:; - __pyx_L3_continue:; - } + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_9ball_tree_allocate_data(__pyx_v_self, __pyx_v_self->n_nodes, __pyx_v_n_features); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1088; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/neighbors/ball_tree.pyx":1210 - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1089 + * # Allocate tree-specific data + * allocate_data(self, self.n_nodes, n_features) + * self._recursive_build(0, 0, n_samples) # <<<<<<<<<<<<<< * - * return idx_i # <<<<<<<<<<<<<< + * def __reduce__(self): + */ + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_n_samples); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1089; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_recursive_build(__pyx_v_self, 0, 0, __pyx_t_6); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1089; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1048 + * self.n_calls = 0 * - * cdef ITYPE_t query_radius_distances_(BallTree self, + * def __init__(self, data, # <<<<<<<<<<<<<< + * leaf_size=40, metric='minkowski', **kwargs): + * self.data_arr = np.asarray(data, dtype=DTYPE, order='C') */ - __pyx_r = __pyx_v_idx_i; - goto __pyx_L0; + /* function exit code */ __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_11, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; + __Pyx_XDECREF(__pyx_v_n_samples); + __Pyx_XDECREF(__pyx_v_metric); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":1212 - * return idx_i +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1091 + * self._recursive_build(0, 0, n_samples) * - * cdef ITYPE_t query_radius_distances_(BallTree self, # <<<<<<<<<<<<<< - * DTYPE_t* pt, DTYPE_t r, - * ITYPE_t* indices, + * def __reduce__(self): # <<<<<<<<<<<<<< + * """ + * reduce method used for pickling */ -static __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_8BallTree_query_radius_distances_(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_r, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_indices, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_distances, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *__pyx_v_node_stack) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_data; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx_array; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_node_centroid_arr; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *__pyx_v_node_info_arr; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *__pyx_v_node_info; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_features; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_node; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_idx_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_r_p; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_dist_pt; - struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack_item __pyx_v_item; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_r; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_4__reduce__[] = "\n reduce method used for pickling\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - int __pyx_t_1; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_2; - long __pyx_t_3; - __Pyx_RefNannySetupContext("query_radius_distances_"); - - /* "sklearn/neighbors/ball_tree.pyx":1217 - * DTYPE_t* distances, - * stack* node_stack): - * cdef DTYPE_t* data = self.data.data # <<<<<<<<<<<<<< - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - */ - __pyx_v_data = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_self->data->data); + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_4__reduce__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self)); - /* "sklearn/neighbors/ball_tree.pyx":1218 - * stack* node_stack): - * cdef DTYPE_t* data = self.data.data - * cdef ITYPE_t* idx_array = self.idx_array.data # <<<<<<<<<<<<<< - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - */ - __pyx_v_idx_array = ((__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *)__pyx_v_self->idx_array->data); + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":1219 - * cdef DTYPE_t* data = self.data.data - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data # <<<<<<<<<<<<<< - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - * cdef NodeInfo* node_info = node_info_arr - */ - __pyx_v_node_centroid_arr = ((__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *)__pyx_v_self->node_centroid_arr->data); +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_4__reduce__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce__", 0); - /* "sklearn/neighbors/ball_tree.pyx":1220 - * cdef ITYPE_t* idx_array = self.idx_array.data - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data # <<<<<<<<<<<<<< - * cdef NodeInfo* node_info = node_info_arr + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1095 + * reduce method used for pickling + * """ + * return (newObj, (BinaryTree,), self.__getstate__()) # <<<<<<<<<<<<<< * + * def __getstate__(self): */ - __pyx_v_node_info_arr = ((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeInfo *)__pyx_v_self->node_info_arr->data); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_newObj); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1095; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1095; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree))); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree))); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_getstate); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1095; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1095; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1095; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_4 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":1221 - * cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - * cdef NodeInfo* node_info_arr = self.node_info_arr.data - * cdef NodeInfo* node_info = node_info_arr # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1091 + * self._recursive_build(0, 0, n_samples) * - * cdef DTYPE_t p = self.p + * def __reduce__(self): # <<<<<<<<<<<<<< + * """ + * reduce method used for pickling */ - __pyx_v_node_info = __pyx_v_node_info_arr; - /* "sklearn/neighbors/ball_tree.pyx":1223 - * cdef NodeInfo* node_info = node_info_arr - * - * cdef DTYPE_t p = self.p # <<<<<<<<<<<<<< - * cdef ITYPE_t n_features = self.data.shape[1] - * cdef ITYPE_t i, i_node - */ - __pyx_v_p = __pyx_v_self->p; + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":1224 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1097 + * return (newObj, (BinaryTree,), self.__getstate__()) * - * cdef DTYPE_t p = self.p - * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< - * cdef ITYPE_t i, i_node - * cdef ITYPE_t idx_i = 0 + * def __getstate__(self): # <<<<<<<<<<<<<< + * """ + * get state for pickling */ - __pyx_v_n_features = (__pyx_v_self->data->dimensions[1]); - /* "sklearn/neighbors/ball_tree.pyx":1226 - * cdef ITYPE_t n_features = self.data.shape[1] - * cdef ITYPE_t i, i_node - * cdef ITYPE_t idx_i = 0 # <<<<<<<<<<<<<< - * cdef DTYPE_t r_p = dist_p_from_dist(r, p) - * cdef DTYPE_t dist_pt - */ - __pyx_v_idx_i = 0; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_6__getstate__[] = "\n get state for pickling\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_6__getstate__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self)); - /* "sklearn/neighbors/ball_tree.pyx":1227 - * cdef ITYPE_t i, i_node - * cdef ITYPE_t idx_i = 0 - * cdef DTYPE_t r_p = dist_p_from_dist(r, p) # <<<<<<<<<<<<<< - * cdef DTYPE_t dist_pt - * - */ - __pyx_v_r_p = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p_from_dist(__pyx_v_r, __pyx_v_p); + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":1232 - * cdef stack_item item - * - * item.i_node = 0 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) - * - */ - __pyx_v_item.i_node = 0; +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_6__getstate__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getstate__", 0); - /* "sklearn/neighbors/ball_tree.pyx":1233 - * - * item.i_node = 0 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< - * - * while(node_stack.n > 0): + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1101 + * get state for pickling + * """ + * return (self.data_arr, # <<<<<<<<<<<<<< + * self.idx_array_arr, + * self.node_data_arr, */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); + __Pyx_XDECREF(__pyx_r); - /* "sklearn/neighbors/ball_tree.pyx":1235 - * stack_push(node_stack, item) - * - * while(node_stack.n > 0): # <<<<<<<<<<<<<< - * item = stack_pop(node_stack) - * i_node = item.i_node + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1105 + * self.node_data_arr, + * self.node_bounds_arr, + * int(self.leaf_size), # <<<<<<<<<<<<<< + * int(self.n_levels), + * int(self.n_nodes), */ - while (1) { - __pyx_t_1 = (__pyx_v_node_stack->n > 0); - if (!__pyx_t_1) break; + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->leaf_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1236 - * - * while(node_stack.n > 0): - * item = stack_pop(node_stack) # <<<<<<<<<<<<<< - * i_node = item.i_node - * node_info = node_info_arr + i_node + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1106 + * self.node_bounds_arr, + * int(self.leaf_size), + * int(self.n_levels), # <<<<<<<<<<<<<< + * int(self.n_nodes), + * int(self.n_trims), */ - __pyx_v_item = __pyx_f_7sklearn_9neighbors_9ball_tree_stack_pop(__pyx_v_node_stack); + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_levels); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1237 - * while(node_stack.n > 0): - * item = stack_pop(node_stack) - * i_node = item.i_node # <<<<<<<<<<<<<< - * node_info = node_info_arr + i_node - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1107 + * int(self.leaf_size), + * int(self.n_levels), + * int(self.n_nodes), # <<<<<<<<<<<<<< + * int(self.n_trims), + * int(self.n_leaves), */ - __pyx_v_i_node = __pyx_v_item.i_node; + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_nodes); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1238 - * item = stack_pop(node_stack) - * i_node = item.i_node - * node_info = node_info_arr + i_node # <<<<<<<<<<<<<< - * - * dist_pt = dist(pt, node_centroid_arr + n_features * i_node, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1108 + * int(self.n_levels), + * int(self.n_nodes), + * int(self.n_trims), # <<<<<<<<<<<<<< + * int(self.n_leaves), + * int(self.n_splits), */ - __pyx_v_node_info = (__pyx_v_node_info_arr + __pyx_v_i_node); + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_self->n_trims); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1241 - * - * dist_pt = dist(pt, node_centroid_arr + n_features * i_node, - * n_features, p) # <<<<<<<<<<<<<< - * - * #------------------------------------------------------------ + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1109 + * int(self.n_nodes), + * int(self.n_trims), + * int(self.n_leaves), # <<<<<<<<<<<<<< + * int(self.n_splits), + * int(self.n_calls), */ - __pyx_v_dist_pt = __pyx_f_7sklearn_9neighbors_9ball_tree_dist(__pyx_v_pt, (__pyx_v_node_centroid_arr + (__pyx_v_n_features * __pyx_v_i_node)), __pyx_v_n_features, __pyx_v_p); + __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_self->n_leaves); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1246 - * # Case 1: all node points are outside distance r. - * # prune this branch. - * if dist_pt - node_info.radius > r: # <<<<<<<<<<<<<< - * continue - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1110 + * int(self.n_trims), + * int(self.n_leaves), + * int(self.n_splits), # <<<<<<<<<<<<<< + * int(self.n_calls), + * self.dist_metric) */ - __pyx_t_1 = ((__pyx_v_dist_pt - __pyx_v_node_info->radius) > __pyx_v_r); - if (__pyx_t_1) { + __pyx_t_6 = __Pyx_PyInt_From_int(__pyx_v_self->n_splits); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1247 - * # prune this branch. - * if dist_pt - node_info.radius > r: - * continue # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1111 + * int(self.n_leaves), + * int(self.n_splits), + * int(self.n_calls), # <<<<<<<<<<<<<< + * self.dist_metric) * - * #------------------------------------------------------------ */ - goto __pyx_L3_continue; - goto __pyx_L5; - } - - /* "sklearn/neighbors/ball_tree.pyx":1252 - * # Case 2: all node points are within distance r - * # add all points - * elif dist_pt + node_info.radius < r: # <<<<<<<<<<<<<< - * for i from node_info.idx_start <= i < node_info.idx_end: - * dist_pt = dist(pt, + __pyx_t_7 = __Pyx_PyInt_From_int(__pyx_v_self->n_calls); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1101 + * get state for pickling + * """ + * return (self.data_arr, # <<<<<<<<<<<<<< + * self.idx_array_arr, + * self.node_data_arr, + */ + __pyx_t_8 = PyTuple_New(12); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(((PyObject *)__pyx_v_self->data_arr)); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_v_self->data_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->data_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->idx_array_arr)); + PyTuple_SET_ITEM(__pyx_t_8, 1, ((PyObject *)__pyx_v_self->idx_array_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->idx_array_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->node_data_arr)); + PyTuple_SET_ITEM(__pyx_t_8, 2, ((PyObject *)__pyx_v_self->node_data_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->node_data_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + PyTuple_SET_ITEM(__pyx_t_8, 3, ((PyObject *)__pyx_v_self->node_bounds_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + PyTuple_SET_ITEM(__pyx_t_8, 4, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_8, 5, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_8, 6, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_8, 7, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_8, 8, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_8, 9, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 10, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __Pyx_INCREF(((PyObject *)__pyx_v_self->dist_metric)); + PyTuple_SET_ITEM(__pyx_t_8, 11, ((PyObject *)__pyx_v_self->dist_metric)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->dist_metric)); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_r = __pyx_t_8; + __pyx_t_8 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1097 + * return (newObj, (BinaryTree,), self.__getstate__()) + * + * def __getstate__(self): # <<<<<<<<<<<<<< + * """ + * get state for pickling */ - __pyx_t_1 = ((__pyx_v_dist_pt + __pyx_v_node_info->radius) < __pyx_v_r); - if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":1253 - * # add all points - * elif dist_pt + node_info.radius < r: - * for i from node_info.idx_start <= i < node_info.idx_end: # <<<<<<<<<<<<<< - * dist_pt = dist(pt, - * data + idx_array[i] * n_features, + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1114 + * self.dist_metric) + * + * def __setstate__(self, state): # <<<<<<<<<<<<<< + * """ + * set state for pickling */ - __pyx_t_2 = __pyx_v_node_info->idx_end; - for (__pyx_v_i = __pyx_v_node_info->idx_start; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { - /* "sklearn/neighbors/ball_tree.pyx":1256 - * dist_pt = dist(pt, - * data + idx_array[i] * n_features, - * n_features, p) # <<<<<<<<<<<<<< - * indices[idx_i] = idx_array[i] - * distances[idx_i] = dist_pt +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_state); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_8__setstate__[] = "\n set state for pickling\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_state) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_8__setstate__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self), ((PyObject *)__pyx_v_state)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_8__setstate__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __Pyx_memviewslice __pyx_t_2 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_3 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate__", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1118 + * set state for pickling + * """ + * self.data_arr = state[0] # <<<<<<<<<<<<<< + * self.idx_array_arr = state[1] + * self.node_data_arr = state[2] */ - __pyx_v_dist_pt = __pyx_f_7sklearn_9neighbors_9ball_tree_dist(__pyx_v_pt, (__pyx_v_data + ((__pyx_v_idx_array[__pyx_v_i]) * __pyx_v_n_features)), __pyx_v_n_features, __pyx_v_p); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1118; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1257 - * data + idx_array[i] * n_features, - * n_features, p) - * indices[idx_i] = idx_array[i] # <<<<<<<<<<<<<< - * distances[idx_i] = dist_pt - * idx_i += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1119 + * """ + * self.data_arr = state[0] + * self.idx_array_arr = state[1] # <<<<<<<<<<<<<< + * self.node_data_arr = state[2] + * self.node_bounds_arr = state[3] */ - (__pyx_v_indices[__pyx_v_idx_i]) = (__pyx_v_idx_array[__pyx_v_i]); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1119; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->idx_array_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->idx_array_arr)); + __pyx_v_self->idx_array_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1258 - * n_features, p) - * indices[idx_i] = idx_array[i] - * distances[idx_i] = dist_pt # <<<<<<<<<<<<<< - * idx_i += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1120 + * self.data_arr = state[0] + * self.idx_array_arr = state[1] + * self.node_data_arr = state[2] # <<<<<<<<<<<<<< + * self.node_bounds_arr = state[3] * */ - (__pyx_v_distances[__pyx_v_idx_i]) = __pyx_v_dist_pt; + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 2, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1120; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->node_data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->node_data_arr)); + __pyx_v_self->node_data_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1259 - * indices[idx_i] = idx_array[i] - * distances[idx_i] = dist_pt - * idx_i += 1 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1121 + * self.idx_array_arr = state[1] + * self.node_data_arr = state[2] + * self.node_bounds_arr = state[3] # <<<<<<<<<<<<<< * - * #------------------------------------------------------------ + * self.data = get_memview_DTYPE_2D(self.data_arr) */ - __pyx_v_idx_i = (__pyx_v_idx_i + 1); - } - goto __pyx_L5; - } + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 3, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1121; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->node_bounds_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + __pyx_v_self->node_bounds_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1264 - * # Case 3: this is a leaf node. Go through all points to - * # determine if they fall within radius - * elif node_info.is_leaf: # <<<<<<<<<<<<<< - * for i from node_info.idx_start <= i < node_info.idx_end: - * dist_pt = dist_p(pt, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1123 + * self.node_bounds_arr = state[3] + * + * self.data = get_memview_DTYPE_2D(self.data_arr) # <<<<<<<<<<<<<< + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) */ - if (__pyx_v_node_info->is_leaf) { + __pyx_t_1 = ((PyObject *)__pyx_v_self->data_arr); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_1)); if (unlikely(!__pyx_t_2.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __pyx_v_self->data = __pyx_t_2; + __pyx_t_2.memview = NULL; + __pyx_t_2.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1265 - * # determine if they fall within radius - * elif node_info.is_leaf: - * for i from node_info.idx_start <= i < node_info.idx_end: # <<<<<<<<<<<<<< - * dist_pt = dist_p(pt, - * data + idx_array[i] * n_features, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1124 + * + * self.data = get_memview_DTYPE_2D(self.data_arr) + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) # <<<<<<<<<<<<<< + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) */ - __pyx_t_2 = __pyx_v_node_info->idx_end; - for (__pyx_v_i = __pyx_v_node_info->idx_start; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { + __pyx_t_1 = ((PyObject *)__pyx_v_self->idx_array_arr); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_3 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_t_1)); if (unlikely(!__pyx_t_3.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->idx_array, 0); + __pyx_v_self->idx_array = __pyx_t_3; + __pyx_t_3.memview = NULL; + __pyx_t_3.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1268 - * dist_pt = dist_p(pt, - * data + idx_array[i] * n_features, - * n_features, p) # <<<<<<<<<<<<<< - * if dist_pt <= r_p: - * indices[idx_i] = idx_array[i] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1125 + * self.data = get_memview_DTYPE_2D(self.data_arr) + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) # <<<<<<<<<<<<<< + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) + * */ - __pyx_v_dist_pt = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p(__pyx_v_pt, (__pyx_v_data + ((__pyx_v_idx_array[__pyx_v_i]) * __pyx_v_n_features)), __pyx_v_n_features, __pyx_v_p); + __pyx_t_1 = ((PyObject *)__pyx_v_self->node_data_arr); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_NodeData_1D(((PyArrayObject *)__pyx_t_1)); if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_data, 0); + __pyx_v_self->node_data = __pyx_t_4; + __pyx_t_4.memview = NULL; + __pyx_t_4.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1269 - * data + idx_array[i] * n_features, - * n_features, p) - * if dist_pt <= r_p: # <<<<<<<<<<<<<< - * indices[idx_i] = idx_array[i] - * distances[idx_i] = dist_from_dist_p(dist_pt, p) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1126 + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) # <<<<<<<<<<<<<< + * + * self.leaf_size = state[4] */ - __pyx_t_1 = (__pyx_v_dist_pt <= __pyx_v_r_p); - if (__pyx_t_1) { + __pyx_t_1 = ((PyObject *)__pyx_v_self->node_bounds_arr); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_3D(((PyArrayObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_bounds, 0); + __pyx_v_self->node_bounds = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1270 - * n_features, p) - * if dist_pt <= r_p: - * indices[idx_i] = idx_array[i] # <<<<<<<<<<<<<< - * distances[idx_i] = dist_from_dist_p(dist_pt, p) - * idx_i += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1128 + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) + * + * self.leaf_size = state[4] # <<<<<<<<<<<<<< + * self.n_levels = state[5] + * self.n_nodes = state[6] */ - (__pyx_v_indices[__pyx_v_idx_i]) = (__pyx_v_idx_array[__pyx_v_i]); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 4, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1128; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->leaf_size = __pyx_t_6; - /* "sklearn/neighbors/ball_tree.pyx":1271 - * if dist_pt <= r_p: - * indices[idx_i] = idx_array[i] - * distances[idx_i] = dist_from_dist_p(dist_pt, p) # <<<<<<<<<<<<<< - * idx_i += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1129 * + * self.leaf_size = state[4] + * self.n_levels = state[5] # <<<<<<<<<<<<<< + * self.n_nodes = state[6] + * self.n_trims = state[7] */ - (__pyx_v_distances[__pyx_v_idx_i]) = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_from_dist_p(__pyx_v_dist_pt, __pyx_v_p); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 5, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1129; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_levels = __pyx_t_6; - /* "sklearn/neighbors/ball_tree.pyx":1272 - * indices[idx_i] = idx_array[i] - * distances[idx_i] = dist_from_dist_p(dist_pt, p) - * idx_i += 1 # <<<<<<<<<<<<<< - * - * #------------------------------------------------------------ + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1130 + * self.leaf_size = state[4] + * self.n_levels = state[5] + * self.n_nodes = state[6] # <<<<<<<<<<<<<< + * self.n_trims = state[7] + * self.n_leaves = state[8] */ - __pyx_v_idx_i = (__pyx_v_idx_i + 1); - goto __pyx_L10; - } - __pyx_L10:; - } - goto __pyx_L5; - } - /*else*/ { + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 6, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1130; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_nodes = __pyx_t_6; - /* "sklearn/neighbors/ball_tree.pyx":1277 - * # Case 4: Node is not a leaf. Recursively query subnodes - * else: - * item.i_node = 2 * i_node + 1 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1131 + * self.n_levels = state[5] + * self.n_nodes = state[6] + * self.n_trims = state[7] # <<<<<<<<<<<<<< + * self.n_leaves = state[8] + * self.n_splits = state[9] */ - __pyx_v_item.i_node = ((2 * __pyx_v_i_node) + 1); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 7, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1131; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_trims = __pyx_t_7; - /* "sklearn/neighbors/ball_tree.pyx":1278 - * else: - * item.i_node = 2 * i_node + 1 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< - * - * item.i_node = i = 2 * i_node + 2 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1132 + * self.n_nodes = state[6] + * self.n_trims = state[7] + * self.n_leaves = state[8] # <<<<<<<<<<<<<< + * self.n_splits = state[9] + * self.n_calls = state[10] */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 8, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1132; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_leaves = __pyx_t_7; - /* "sklearn/neighbors/ball_tree.pyx":1280 - * stack_push(node_stack, item) - * - * item.i_node = i = 2 * i_node + 2 # <<<<<<<<<<<<<< - * stack_push(node_stack, item) - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1133 + * self.n_trims = state[7] + * self.n_leaves = state[8] + * self.n_splits = state[9] # <<<<<<<<<<<<<< + * self.n_calls = state[10] + * self.dist_metric = state[11] */ - __pyx_t_3 = ((2 * __pyx_v_i_node) + 2); - __pyx_v_item.i_node = __pyx_t_3; - __pyx_v_i = __pyx_t_3; + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 9, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1133; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_splits = __pyx_t_7; - /* "sklearn/neighbors/ball_tree.pyx":1281 - * - * item.i_node = i = 2 * i_node + 2 - * stack_push(node_stack, item) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1134 + * self.n_leaves = state[8] + * self.n_splits = state[9] + * self.n_calls = state[10] # <<<<<<<<<<<<<< + * self.dist_metric = state[11] + * self.euclidean = (self.dist_metric.__class__.__name__ + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 10, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1134; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_calls = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1135 + * self.n_splits = state[9] + * self.n_calls = state[10] + * self.dist_metric = state[11] # <<<<<<<<<<<<<< + * self.euclidean = (self.dist_metric.__class__.__name__ + * == 'EuclideanDistance') + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 11, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1135; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->dist_metric); + __Pyx_DECREF(((PyObject *)__pyx_v_self->dist_metric)); + __pyx_v_self->dist_metric = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1136 + * self.n_calls = state[10] + * self.dist_metric = state[11] + * self.euclidean = (self.dist_metric.__class__.__name__ # <<<<<<<<<<<<<< + * == 'EuclideanDistance') * - * return idx_i */ - __pyx_f_7sklearn_9neighbors_9ball_tree_stack_push(__pyx_v_node_stack, __pyx_v_item); - } - __pyx_L5:; - __pyx_L3_continue:; - } + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->dist_metric), __pyx_n_s_class); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_name); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_RichCompare(__pyx_t_8, __pyx_n_s_EuclideanDistance, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1137; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1283 - * stack_push(node_stack, item) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1137 + * self.dist_metric = state[11] + * self.euclidean = (self.dist_metric.__class__.__name__ + * == 'EuclideanDistance') # <<<<<<<<<<<<<< * - * return idx_i # <<<<<<<<<<<<<< + * def get_tree_stats(self): + */ + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1137; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1136 + * self.n_calls = state[10] + * self.dist_metric = state[11] + * self.euclidean = (self.dist_metric.__class__.__name__ # <<<<<<<<<<<<<< + * == 'EuclideanDistance') * + */ + __pyx_v_self->euclidean = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1114 + * self.dist_metric) * + * def __setstate__(self, state): # <<<<<<<<<<<<<< + * """ + * set state for pickling */ - __pyx_r = __pyx_v_idx_i; - goto __pyx_L0; - __pyx_r = 0; + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __PYX_XDEC_MEMVIEW(&__pyx_t_2, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_3, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_4, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.__setstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":478 - * [ 0. 0.19662693 0.29473397] - * """ - * cdef readonly np.ndarray data # <<<<<<<<<<<<<< - * cdef np.ndarray idx_array - * cdef np.ndarray node_centroid_arr +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1139 + * == 'EuclideanDistance') + * + * def get_tree_stats(self): # <<<<<<<<<<<<<< + * return (self.n_trims, self.n_leaves, self.n_splits) + * */ -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_4data___get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_4data___get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = NULL; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_11get_tree_stats(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_11get_tree_stats(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__"); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data)); - __pyx_r = ((PyObject *)((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->data); - goto __pyx_L0; + __Pyx_RefNannySetupContext("get_tree_stats (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_10get_tree_stats(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self)); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":486 - * cdef ITYPE_t n_levels - * cdef ITYPE_t n_nodes - * cdef readonly int warning_flag # <<<<<<<<<<<<<< - * - * def __cinit__(self): - */ - -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_12warning_flag___get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_12warning_flag___get__(PyObject *__pyx_v_self) { +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_10get_tree_stats(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__"); + __Pyx_RefNannySetupContext("get_tree_stats", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1140 + * + * def get_tree_stats(self): + * return (self.n_trims, self.n_leaves, self.n_splits) # <<<<<<<<<<<<<< + * + * def reset_n_calls(self): + */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)__pyx_v_self)->warning_flag); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->n_trims); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->n_leaves); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_self->n_splits); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1139 + * == 'EuclideanDistance') + * + * def get_tree_stats(self): # <<<<<<<<<<<<<< + * return (self.n_trims, self.n_leaves, self.n_splits) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BallTree.warning_flag.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.get_tree_stats", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); @@ -7558,4956 +9608,29610 @@ static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_12warning_fla return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":1290 - * # - * @cython.profile(False) - * cdef inline void copy_array(DTYPE_t* x, DTYPE_t* y, ITYPE_t n): # <<<<<<<<<<<<<< - * # copy array y into array x - * cdef ITYPE_t i +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1142 + * return (self.n_trims, self.n_leaves, self.n_splits) + * + * def reset_n_calls(self): # <<<<<<<<<<<<<< + * self.n_calls = 0 + * */ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_copy_array(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_x, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_y, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n) { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_13reset_n_calls(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_13reset_n_calls(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_1; - __Pyx_RefNannySetupContext("copy_array"); + __Pyx_RefNannySetupContext("reset_n_calls (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_12reset_n_calls(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self)); - /* "sklearn/neighbors/ball_tree.pyx":1293 - * # copy array y into array x - * cdef ITYPE_t i - * for i from 0 <= i < n: # <<<<<<<<<<<<<< - * x[i] = y[i] + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_12reset_n_calls(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("reset_n_calls", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1143 * + * def reset_n_calls(self): + * self.n_calls = 0 # <<<<<<<<<<<<<< + * + * def get_n_calls(self): */ - __pyx_t_1 = __pyx_v_n; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_1; __pyx_v_i++) { + __pyx_v_self->n_calls = 0; - /* "sklearn/neighbors/ball_tree.pyx":1294 - * cdef ITYPE_t i - * for i from 0 <= i < n: - * x[i] = y[i] # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1142 + * return (self.n_trims, self.n_leaves, self.n_splits) * + * def reset_n_calls(self): # <<<<<<<<<<<<<< + * self.n_calls = 0 * */ - (__pyx_v_x[__pyx_v_i]) = (__pyx_v_y[__pyx_v_i]); - } + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":1298 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1145 + * self.n_calls = 0 + * + * def get_n_calls(self): # <<<<<<<<<<<<<< + * return self.n_calls * - * @cython.cdivision(True) - * cdef void compute_centroid(DTYPE_t* centroid, # <<<<<<<<<<<<<< - * DTYPE_t* data, - * ITYPE_t* node_indices, */ -static void __pyx_f_7sklearn_9neighbors_9ball_tree_compute_centroid(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_centroid, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_data, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_node_indices, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_features, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_points) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_this_pt; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_j; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_15get_n_calls(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_15get_n_calls(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_1; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_2; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_3; - __Pyx_RefNannySetupContext("compute_centroid"); + __Pyx_RefNannySetupContext("get_n_calls (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_14get_n_calls(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self)); - /* "sklearn/neighbors/ball_tree.pyx":1309 - * cdef ITYPE_t i, j - * - * for j from 0 <= j < n_features: # <<<<<<<<<<<<<< - * centroid[j] = 0 - * - */ - __pyx_t_1 = __pyx_v_n_features; - for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_1; __pyx_v_j++) { + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_14get_n_calls(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_n_calls", 0); - /* "sklearn/neighbors/ball_tree.pyx":1310 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1146 * - * for j from 0 <= j < n_features: - * centroid[j] = 0 # <<<<<<<<<<<<<< + * def get_n_calls(self): + * return self.n_calls # <<<<<<<<<<<<<< * - * for i from 0 <= i < n_points: + * def get_arrays(self): */ - (__pyx_v_centroid[__pyx_v_j]) = 0.0; - } + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->n_calls); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":1312 - * centroid[j] = 0 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1145 + * self.n_calls = 0 * - * for i from 0 <= i < n_points: # <<<<<<<<<<<<<< - * this_pt = data + n_features * node_indices[i] - * for j from 0 <= j < n_features: - */ - __pyx_t_1 = __pyx_v_n_points; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_1; __pyx_v_i++) { - - /* "sklearn/neighbors/ball_tree.pyx":1313 + * def get_n_calls(self): # <<<<<<<<<<<<<< + * return self.n_calls * - * for i from 0 <= i < n_points: - * this_pt = data + n_features * node_indices[i] # <<<<<<<<<<<<<< - * for j from 0 <= j < n_features: - * centroid[j] += this_pt[j] */ - __pyx_v_this_pt = (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_node_indices[__pyx_v_i]))); - /* "sklearn/neighbors/ball_tree.pyx":1314 - * for i from 0 <= i < n_points: - * this_pt = data + n_features * node_indices[i] - * for j from 0 <= j < n_features: # <<<<<<<<<<<<<< - * centroid[j] += this_pt[j] - * - */ - __pyx_t_2 = __pyx_v_n_features; - for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_2; __pyx_v_j++) { + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.get_n_calls", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":1315 - * this_pt = data + n_features * node_indices[i] - * for j from 0 <= j < n_features: - * centroid[j] += this_pt[j] # <<<<<<<<<<<<<< +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1148 + * return self.n_calls * - * for j from 0 <= j < n_features: + * def get_arrays(self): # <<<<<<<<<<<<<< + * return (self.data_arr, self.idx_array_arr, + * self.node_data_arr, self.node_bounds_arr) */ - __pyx_t_3 = __pyx_v_j; - (__pyx_v_centroid[__pyx_t_3]) = ((__pyx_v_centroid[__pyx_t_3]) + (__pyx_v_this_pt[__pyx_v_j])); - } - } - /* "sklearn/neighbors/ball_tree.pyx":1317 - * centroid[j] += this_pt[j] - * - * for j from 0 <= j < n_features: # <<<<<<<<<<<<<< - * centroid[j] /= n_points - * - */ - __pyx_t_1 = __pyx_v_n_features; - for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_1; __pyx_v_j++) { - - /* "sklearn/neighbors/ball_tree.pyx":1318 - * - * for j from 0 <= j < n_features: - * centroid[j] /= n_points # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = __pyx_v_j; - (__pyx_v_centroid[__pyx_t_2]) = ((__pyx_v_centroid[__pyx_t_2]) / __pyx_v_n_points); - } +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_17get_arrays(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_17get_arrays(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_arrays (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_16get_arrays(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self)); + /* function exit code */ __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":1321 - * - * - * cdef ITYPE_t find_split_dim(DTYPE_t* data, # <<<<<<<<<<<<<< - * ITYPE_t* node_indices, - * ITYPE_t n_features, - */ - -static __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_find_split_dim(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_data, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_node_indices, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_features, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_points) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_min_val; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_max_val; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_val; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_spread; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_max_spread; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_j; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_j_max; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_r; +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_16get_arrays(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_1; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_2; - int __pyx_t_3; - __Pyx_RefNannySetupContext("find_split_dim"); + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_arrays", 0); - /* "sklearn/neighbors/ball_tree.pyx":1330 - * cdef ITYPE_t i, j, j_max + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1149 * - * j_max = 0 # <<<<<<<<<<<<<< - * max_spread = 0 + * def get_arrays(self): + * return (self.data_arr, self.idx_array_arr, # <<<<<<<<<<<<<< + * self.node_data_arr, self.node_bounds_arr) * */ - __pyx_v_j_max = 0; + __Pyx_XDECREF(__pyx_r); - /* "sklearn/neighbors/ball_tree.pyx":1331 - * - * j_max = 0 - * max_spread = 0 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1150 + * def get_arrays(self): + * return (self.data_arr, self.idx_array_arr, + * self.node_data_arr, self.node_bounds_arr) # <<<<<<<<<<<<<< * - * for j from 0 <= j < n_features: + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, */ - __pyx_v_max_spread = 0.0; + __pyx_t_1 = PyTuple_New(4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_self->data_arr)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_self->data_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->data_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->idx_array_arr)); + PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_self->idx_array_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->idx_array_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->node_data_arr)); + PyTuple_SET_ITEM(__pyx_t_1, 2, ((PyObject *)__pyx_v_self->node_data_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->node_data_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + PyTuple_SET_ITEM(__pyx_t_1, 3, ((PyObject *)__pyx_v_self->node_bounds_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; - /* "sklearn/neighbors/ball_tree.pyx":1333 - * max_spread = 0 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1148 + * return self.n_calls * - * for j from 0 <= j < n_features: # <<<<<<<<<<<<<< - * max_val = data[node_indices[0] * n_features + j] - * min_val = max_val + * def get_arrays(self): # <<<<<<<<<<<<<< + * return (self.data_arr, self.idx_array_arr, + * self.node_data_arr, self.node_bounds_arr) */ - __pyx_t_1 = __pyx_v_n_features; - for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_1; __pyx_v_j++) { - /* "sklearn/neighbors/ball_tree.pyx":1334 + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.get_arrays", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1152 + * self.node_data_arr, self.node_bounds_arr) * - * for j from 0 <= j < n_features: - * max_val = data[node_indices[0] * n_features + j] # <<<<<<<<<<<<<< - * min_val = max_val - * for i from 1 <= i < n_points: + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """Compute the distance between arrays x1 and x2""" */ - __pyx_v_max_val = (__pyx_v_data[(((__pyx_v_node_indices[0]) * __pyx_v_n_features) + __pyx_v_j)]); - /* "sklearn/neighbors/ball_tree.pyx":1335 - * for j from 0 <= j < n_features: - * max_val = data[node_indices[0] * n_features + j] - * min_val = max_val # <<<<<<<<<<<<<< - * for i from 1 <= i < n_points: - * val = data[node_indices[i] * n_features + j] +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1155 + * ITYPE_t size) except -1: + * """Compute the distance between arrays x1 and x2""" + * self.n_calls += 1 # <<<<<<<<<<<<<< + * if self.euclidean: + * return euclidean_dist(x1, x2, size) + */ + __pyx_v_self->n_calls = (__pyx_v_self->n_calls + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1156 + * """Compute the distance between arrays x1 and x2""" + * self.n_calls += 1 + * if self.euclidean: # <<<<<<<<<<<<<< + * return euclidean_dist(x1, x2, size) + * else: */ - __pyx_v_min_val = __pyx_v_max_val; + __pyx_t_1 = (__pyx_v_self->euclidean != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":1336 - * max_val = data[node_indices[0] * n_features + j] - * min_val = max_val - * for i from 1 <= i < n_points: # <<<<<<<<<<<<<< - * val = data[node_indices[i] * n_features + j] - * max_val = dmax(max_val, val) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1157 + * self.n_calls += 1 + * if self.euclidean: + * return euclidean_dist(x1, x2, size) # <<<<<<<<<<<<<< + * else: + * return self.dist_metric.dist(x1, x2, size) */ - __pyx_t_2 = __pyx_v_n_points; - for (__pyx_v_i = 1; __pyx_v_i < __pyx_t_2; __pyx_v_i++) { + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist(__pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":1337 - * min_val = max_val - * for i from 1 <= i < n_points: - * val = data[node_indices[i] * n_features + j] # <<<<<<<<<<<<<< - * max_val = dmax(max_val, val) - * min_val = dmin(min_val, val) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1159 + * return euclidean_dist(x1, x2, size) + * else: + * return self.dist_metric.dist(x1, x2, size) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, */ - __pyx_v_val = (__pyx_v_data[(((__pyx_v_node_indices[__pyx_v_i]) * __pyx_v_n_features) + __pyx_v_j)]); + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->dist_metric->__pyx_vtab)->dist(__pyx_v_self->dist_metric, __pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } - /* "sklearn/neighbors/ball_tree.pyx":1338 - * for i from 1 <= i < n_points: - * val = data[node_indices[i] * n_features + j] - * max_val = dmax(max_val, val) # <<<<<<<<<<<<<< - * min_val = dmin(min_val, val) - * spread = max_val - min_val + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1152 + * self.node_data_arr, self.node_bounds_arr) + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """Compute the distance between arrays x1 and x2""" */ - __pyx_v_max_val = __pyx_f_7sklearn_9neighbors_9ball_tree_dmax(__pyx_v_max_val, __pyx_v_val); - /* "sklearn/neighbors/ball_tree.pyx":1339 - * val = data[node_indices[i] * n_features + j] - * max_val = dmax(max_val, val) - * min_val = dmin(min_val, val) # <<<<<<<<<<<<<< - * spread = max_val - min_val - * if spread > max_spread: + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1161 + * return self.dist_metric.dist(x1, x2, size) + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """Compute the reduced distance between arrays x1 and x2. */ - __pyx_v_min_val = __pyx_f_7sklearn_9neighbors_9ball_tree_dmin(__pyx_v_min_val, __pyx_v_val); - } - /* "sklearn/neighbors/ball_tree.pyx":1340 - * max_val = dmax(max_val, val) - * min_val = dmin(min_val, val) - * spread = max_val - min_val # <<<<<<<<<<<<<< - * if spread > max_spread: - * max_spread = spread +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_rdist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1170 + * distance for the Euclidean metric is the squared-euclidean distance. + * """ + * self.n_calls += 1 # <<<<<<<<<<<<<< + * if self.euclidean: + * return euclidean_rdist(x1, x2, size) */ - __pyx_v_spread = (__pyx_v_max_val - __pyx_v_min_val); + __pyx_v_self->n_calls = (__pyx_v_self->n_calls + 1); - /* "sklearn/neighbors/ball_tree.pyx":1341 - * min_val = dmin(min_val, val) - * spread = max_val - min_val - * if spread > max_spread: # <<<<<<<<<<<<<< - * max_spread = spread - * j_max = j + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1171 + * """ + * self.n_calls += 1 + * if self.euclidean: # <<<<<<<<<<<<<< + * return euclidean_rdist(x1, x2, size) + * else: */ - __pyx_t_3 = (__pyx_v_spread > __pyx_v_max_spread); - if (__pyx_t_3) { + __pyx_t_1 = (__pyx_v_self->euclidean != 0); + if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":1342 - * spread = max_val - min_val - * if spread > max_spread: - * max_spread = spread # <<<<<<<<<<<<<< - * j_max = j - * return j_max + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1172 + * self.n_calls += 1 + * if self.euclidean: + * return euclidean_rdist(x1, x2, size) # <<<<<<<<<<<<<< + * else: + * return self.dist_metric.rdist(x1, x2, size) */ - __pyx_v_max_spread = __pyx_v_spread; + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist(__pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":1343 - * if spread > max_spread: - * max_spread = spread - * j_max = j # <<<<<<<<<<<<<< - * return j_max + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1174 + * return euclidean_rdist(x1, x2, size) + * else: + * return self.dist_metric.rdist(x1, x2, size) # <<<<<<<<<<<<<< * + * cdef int _recursive_build(self, ITYPE_t i_node, ITYPE_t idx_start, */ - __pyx_v_j_max = __pyx_v_j; - goto __pyx_L7; - } - __pyx_L7:; + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->dist_metric->__pyx_vtab)->rdist(__pyx_v_self->dist_metric, __pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; } - /* "sklearn/neighbors/ball_tree.pyx":1344 - * max_spread = spread - * j_max = j - * return j_max # <<<<<<<<<<<<<< - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1161 + * return self.dist_metric.dist(x1, x2, size) * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """Compute the reduced distance between arrays x1 and x2. */ - __pyx_r = __pyx_v_j_max; - goto __pyx_L0; - __pyx_r = 0; + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":1348 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1176 + * return self.dist_metric.rdist(x1, x2, size) * - * @cython.profile(False) - * cdef inline void iswap(ITYPE_t* arr, ITYPE_t i1, ITYPE_t i2): # <<<<<<<<<<<<<< - * cdef ITYPE_t tmp = arr[i1] - * arr[i1] = arr[i2] + * cdef int _recursive_build(self, ITYPE_t i_node, ITYPE_t idx_start, # <<<<<<<<<<<<<< + * ITYPE_t idx_end) except -1: + * """Recursively build the tree. */ -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_iswap(__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_arr, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i1, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i2) { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_tmp; +static int __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__recursive_build(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_idx_start, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_idx_end) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_points; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_mid; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + PyObject *__pyx_v_warnings = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_max; + int __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("iswap"); + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_recursive_build", 0); - /* "sklearn/neighbors/ball_tree.pyx":1349 - * @cython.profile(False) - * cdef inline void iswap(ITYPE_t* arr, ITYPE_t i1, ITYPE_t i2): - * cdef ITYPE_t tmp = arr[i1] # <<<<<<<<<<<<<< - * arr[i1] = arr[i2] - * arr[i2] = tmp + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1189 + * """ + * cdef ITYPE_t imax + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_points = idx_end - idx_start + * cdef ITYPE_t n_mid = n_points / 2 */ - __pyx_v_tmp = (__pyx_v_arr[__pyx_v_i1]); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1189; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); - /* "sklearn/neighbors/ball_tree.pyx":1350 - * cdef inline void iswap(ITYPE_t* arr, ITYPE_t i1, ITYPE_t i2): - * cdef ITYPE_t tmp = arr[i1] - * arr[i1] = arr[i2] # <<<<<<<<<<<<<< - * arr[i2] = tmp - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1190 + * cdef ITYPE_t imax + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef ITYPE_t n_points = idx_end - idx_start # <<<<<<<<<<<<<< + * cdef ITYPE_t n_mid = n_points / 2 + * cdef ITYPE_t* idx_array = &self.idx_array[idx_start] */ - (__pyx_v_arr[__pyx_v_i1]) = (__pyx_v_arr[__pyx_v_i2]); + __pyx_v_n_points = (__pyx_v_idx_end - __pyx_v_idx_start); - /* "sklearn/neighbors/ball_tree.pyx":1351 - * cdef ITYPE_t tmp = arr[i1] - * arr[i1] = arr[i2] - * arr[i2] = tmp # <<<<<<<<<<<<<< - * - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1191 + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef ITYPE_t n_points = idx_end - idx_start + * cdef ITYPE_t n_mid = n_points / 2 # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array = &self.idx_array[idx_start] + * cdef DTYPE_t* data = &self.data[0, 0] */ - (__pyx_v_arr[__pyx_v_i2]) = __pyx_v_tmp; - - __Pyx_RefNannyFinishContext(); -} + __pyx_v_n_mid = (__pyx_v_n_points / 2); -/* "sklearn/neighbors/ball_tree.pyx":1355 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1192 + * cdef ITYPE_t n_points = idx_end - idx_start + * cdef ITYPE_t n_mid = n_points / 2 + * cdef ITYPE_t* idx_array = &self.idx_array[idx_start] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data = &self.data[0, 0] * - * @cython.profile(False) - * cdef inline void dswap(DTYPE_t* arr, ITYPE_t i1, ITYPE_t i2): # <<<<<<<<<<<<<< - * cdef DTYPE_t tmp = arr[i1] - * arr[i1] = arr[i2] - */ - -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_dswap(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_arr, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i1, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i2) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_tmp; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("dswap"); - - /* "sklearn/neighbors/ball_tree.pyx":1356 - * @cython.profile(False) - * cdef inline void dswap(DTYPE_t* arr, ITYPE_t i1, ITYPE_t i2): - * cdef DTYPE_t tmp = arr[i1] # <<<<<<<<<<<<<< - * arr[i1] = arr[i2] - * arr[i2] = tmp */ - __pyx_v_tmp = (__pyx_v_arr[__pyx_v_i1]); + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1192; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_v_idx_start; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_1)) )))); - /* "sklearn/neighbors/ball_tree.pyx":1357 - * cdef inline void dswap(DTYPE_t* arr, ITYPE_t i1, ITYPE_t i2): - * cdef DTYPE_t tmp = arr[i1] - * arr[i1] = arr[i2] # <<<<<<<<<<<<<< - * arr[i2] = tmp + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1193 + * cdef ITYPE_t n_mid = n_points / 2 + * cdef ITYPE_t* idx_array = &self.idx_array[idx_start] + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< * + * # initialize node data */ - (__pyx_v_arr[__pyx_v_i1]) = (__pyx_v_arr[__pyx_v_i2]); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1193; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_2 * __pyx_v_self->data.strides[0]) )) + __pyx_t_3)) )))); - /* "sklearn/neighbors/ball_tree.pyx":1358 - * cdef DTYPE_t tmp = arr[i1] - * arr[i1] = arr[i2] - * arr[i2] = tmp # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1196 * + * # initialize node data + * init_node(self, i_node, idx_start, idx_end) # <<<<<<<<<<<<<< * + * if 2 * i_node + 1 >= self.n_nodes: */ - (__pyx_v_arr[__pyx_v_i2]) = __pyx_v_tmp; + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_init_node(__pyx_v_self, __pyx_v_i_node, __pyx_v_idx_start, __pyx_v_idx_end); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_RefNannyFinishContext(); -} - -/* "sklearn/neighbors/ball_tree.pyx":1361 - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1198 + * init_node(self, i_node, idx_start, idx_end) * - * cdef void partition_indices(DTYPE_t* data, # <<<<<<<<<<<<<< - * ITYPE_t* node_indices, - * ITYPE_t split_dim, + * if 2 * i_node + 1 >= self.n_nodes: # <<<<<<<<<<<<<< + * self.node_data[i_node].is_leaf = True + * if idx_end - idx_start > 2 * self.leaf_size: */ + __pyx_t_5 = ((((2 * __pyx_v_i_node) + 1) >= __pyx_v_self->n_nodes) != 0); + if (__pyx_t_5) { -static void __pyx_f_7sklearn_9neighbors_9ball_tree_partition_indices(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_data, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_node_indices, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_split_dim, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_split_index, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_features, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_points) { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_left; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_right; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_midindex; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_d1; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_d2; - __Pyx_RefNannyDeclarations - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_1; - int __pyx_t_2; - __Pyx_RefNannySetupContext("partition_indices"); - - /* "sklearn/neighbors/ball_tree.pyx":1377 - * cdef ITYPE_t left, right, midindex, i - * cdef DTYPE_t d1, d2 - * left = 0 # <<<<<<<<<<<<<< - * right = n_points - 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1199 * + * if 2 * i_node + 1 >= self.n_nodes: + * self.node_data[i_node].is_leaf = True # <<<<<<<<<<<<<< + * if idx_end - idx_start > 2 * self.leaf_size: + * # this shouldn't happen if our memory allocation is correct */ - __pyx_v_left = 0; + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1199; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_6 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_6)) ))).is_leaf = 1; - /* "sklearn/neighbors/ball_tree.pyx":1378 - * cdef DTYPE_t d1, d2 - * left = 0 - * right = n_points - 1 # <<<<<<<<<<<<<< - * - * while True: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1200 + * if 2 * i_node + 1 >= self.n_nodes: + * self.node_data[i_node].is_leaf = True + * if idx_end - idx_start > 2 * self.leaf_size: # <<<<<<<<<<<<<< + * # this shouldn't happen if our memory allocation is correct + * # we'll proactively prevent memory errors, but raise a */ - __pyx_v_right = (__pyx_v_n_points - 1); + __pyx_t_5 = (((__pyx_v_idx_end - __pyx_v_idx_start) > (2 * __pyx_v_self->leaf_size)) != 0); + if (__pyx_t_5) { - /* "sklearn/neighbors/ball_tree.pyx":1380 - * right = n_points - 1 - * - * while True: # <<<<<<<<<<<<<< - * midindex = left - * for i from left <= i < right: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1204 + * # we'll proactively prevent memory errors, but raise a + * # warning saying we're doing so. + * import warnings # <<<<<<<<<<<<<< + * warnings.warn("Internal: memory layout is flawed: " + * "not enough nodes allocated") */ - while (1) { - if (!1) break; + __pyx_t_7 = __Pyx_Import(__pyx_n_s_warnings, 0, -1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_v_warnings = __pyx_t_7; + __pyx_t_7 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1381 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1205 + * # warning saying we're doing so. + * import warnings + * warnings.warn("Internal: memory layout is flawed: " # <<<<<<<<<<<<<< + * "not enough nodes allocated") * - * while True: - * midindex = left # <<<<<<<<<<<<<< - * for i from left <= i < right: - * d1 = data[node_indices[i] * n_features + split_dim] */ - __pyx_v_midindex = __pyx_v_left; + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_warnings, __pyx_n_s_warn); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L4; + } + __pyx_L4:; + goto __pyx_L3; + } - /* "sklearn/neighbors/ball_tree.pyx":1382 - * while True: - * midindex = left - * for i from left <= i < right: # <<<<<<<<<<<<<< - * d1 = data[node_indices[i] * n_features + split_dim] - * d2 = data[node_indices[right] * n_features + split_dim] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1208 + * "not enough nodes allocated") + * + * elif idx_end - idx_start < 2: # <<<<<<<<<<<<<< + * # again, this shouldn't happen if our memory allocation + * # is correct. Raise a warning. */ - __pyx_t_1 = __pyx_v_right; - for (__pyx_v_i = __pyx_v_left; __pyx_v_i < __pyx_t_1; __pyx_v_i++) { + __pyx_t_5 = (((__pyx_v_idx_end - __pyx_v_idx_start) < 2) != 0); + if (__pyx_t_5) { - /* "sklearn/neighbors/ball_tree.pyx":1383 - * midindex = left - * for i from left <= i < right: - * d1 = data[node_indices[i] * n_features + split_dim] # <<<<<<<<<<<<<< - * d2 = data[node_indices[right] * n_features + split_dim] - * if d1 < d2: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1211 + * # again, this shouldn't happen if our memory allocation + * # is correct. Raise a warning. + * import warnings # <<<<<<<<<<<<<< + * warnings.warn("Internal: memory layout is flawed: " + * "too many nodes allocated") */ - __pyx_v_d1 = (__pyx_v_data[(((__pyx_v_node_indices[__pyx_v_i]) * __pyx_v_n_features) + __pyx_v_split_dim)]); + __pyx_t_8 = __Pyx_Import(__pyx_n_s_warnings, 0, -1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_v_warnings = __pyx_t_8; + __pyx_t_8 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1384 - * for i from left <= i < right: - * d1 = data[node_indices[i] * n_features + split_dim] - * d2 = data[node_indices[right] * n_features + split_dim] # <<<<<<<<<<<<<< - * if d1 < d2: - * iswap(node_indices, i, midindex) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1212 + * # is correct. Raise a warning. + * import warnings + * warnings.warn("Internal: memory layout is flawed: " # <<<<<<<<<<<<<< + * "too many nodes allocated") + * self.node_data[i_node].is_leaf = True */ - __pyx_v_d2 = (__pyx_v_data[(((__pyx_v_node_indices[__pyx_v_right]) * __pyx_v_n_features) + __pyx_v_split_dim)]); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_warnings, __pyx_n_s_warn); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1385 - * d1 = data[node_indices[i] * n_features + split_dim] - * d2 = data[node_indices[right] * n_features + split_dim] - * if d1 < d2: # <<<<<<<<<<<<<< - * iswap(node_indices, i, midindex) - * midindex += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1214 + * warnings.warn("Internal: memory layout is flawed: " + * "too many nodes allocated") + * self.node_data[i_node].is_leaf = True # <<<<<<<<<<<<<< + * + * else: */ - __pyx_t_2 = (__pyx_v_d1 < __pyx_v_d2); - if (__pyx_t_2) { + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1214; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_9)) ))).is_leaf = 1; + goto __pyx_L3; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":1386 - * d2 = data[node_indices[right] * n_features + split_dim] - * if d1 < d2: - * iswap(node_indices, i, midindex) # <<<<<<<<<<<<<< - * midindex += 1 - * iswap(node_indices, midindex, right) - */ - __pyx_f_7sklearn_9neighbors_9ball_tree_iswap(__pyx_v_node_indices, __pyx_v_i, __pyx_v_midindex); - - /* "sklearn/neighbors/ball_tree.pyx":1387 - * if d1 < d2: - * iswap(node_indices, i, midindex) - * midindex += 1 # <<<<<<<<<<<<<< - * iswap(node_indices, midindex, right) - * if midindex == split_index: - */ - __pyx_v_midindex = (__pyx_v_midindex + 1); - goto __pyx_L7; - } - __pyx_L7:; - } - - /* "sklearn/neighbors/ball_tree.pyx":1388 - * iswap(node_indices, i, midindex) - * midindex += 1 - * iswap(node_indices, midindex, right) # <<<<<<<<<<<<<< - * if midindex == split_index: - * break - */ - __pyx_f_7sklearn_9neighbors_9ball_tree_iswap(__pyx_v_node_indices, __pyx_v_midindex, __pyx_v_right); - - /* "sklearn/neighbors/ball_tree.pyx":1389 - * midindex += 1 - * iswap(node_indices, midindex, right) - * if midindex == split_index: # <<<<<<<<<<<<<< - * break - * elif midindex < split_index: - */ - __pyx_t_2 = (__pyx_v_midindex == __pyx_v_split_index); - if (__pyx_t_2) { - - /* "sklearn/neighbors/ball_tree.pyx":1390 - * iswap(node_indices, midindex, right) - * if midindex == split_index: - * break # <<<<<<<<<<<<<< - * elif midindex < split_index: - * left = midindex + 1 - */ - goto __pyx_L4_break; - goto __pyx_L8; - } - - /* "sklearn/neighbors/ball_tree.pyx":1391 - * if midindex == split_index: - * break - * elif midindex < split_index: # <<<<<<<<<<<<<< - * left = midindex + 1 - * else: - */ - __pyx_t_2 = (__pyx_v_midindex < __pyx_v_split_index); - if (__pyx_t_2) { - - /* "sklearn/neighbors/ball_tree.pyx":1392 - * break - * elif midindex < split_index: - * left = midindex + 1 # <<<<<<<<<<<<<< - * else: - * right = midindex - 1 - */ - __pyx_v_left = (__pyx_v_midindex + 1); - goto __pyx_L8; - } - /*else*/ { - - /* "sklearn/neighbors/ball_tree.pyx":1394 - * left = midindex + 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1218 * else: - * right = midindex - 1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_right = (__pyx_v_midindex - 1); - } - __pyx_L8:; + * # split node and recursively construct child nodes. + * self.node_data[i_node].is_leaf = False # <<<<<<<<<<<<<< + * i_max = find_node_split_dim(data, idx_array, + * n_features, n_points) + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_10)) ))).is_leaf = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1219 + * # split node and recursively construct child nodes. + * self.node_data[i_node].is_leaf = False + * i_max = find_node_split_dim(data, idx_array, # <<<<<<<<<<<<<< + * n_features, n_points) + * partition_node_indices(data, idx_array, i_max, n_mid, + */ + __pyx_t_11 = __pyx_f_7sklearn_9neighbors_9ball_tree_find_node_split_dim(__pyx_v_data, __pyx_v_idx_array, __pyx_v_n_features, __pyx_v_n_points); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_i_max = __pyx_t_11; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1221 + * i_max = find_node_split_dim(data, idx_array, + * n_features, n_points) + * partition_node_indices(data, idx_array, i_max, n_mid, # <<<<<<<<<<<<<< + * n_features, n_points) + * self._recursive_build(2 * i_node + 1, + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_partition_node_indices(__pyx_v_data, __pyx_v_idx_array, __pyx_v_i_max, __pyx_v_n_mid, __pyx_v_n_features, __pyx_v_n_points); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1223 + * partition_node_indices(data, idx_array, i_max, n_mid, + * n_features, n_points) + * self._recursive_build(2 * i_node + 1, # <<<<<<<<<<<<<< + * idx_start, idx_start + n_mid) + * self._recursive_build(2 * i_node + 2, + */ + __pyx_t_4 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_recursive_build(__pyx_v_self, ((2 * __pyx_v_i_node) + 1), __pyx_v_idx_start, (__pyx_v_idx_start + __pyx_v_n_mid)); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1225 + * self._recursive_build(2 * i_node + 1, + * idx_start, idx_start + n_mid) + * self._recursive_build(2 * i_node + 2, # <<<<<<<<<<<<<< + * idx_start + n_mid, idx_end) + * + */ + __pyx_t_4 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_recursive_build(__pyx_v_self, ((2 * __pyx_v_i_node) + 2), (__pyx_v_idx_start + __pyx_v_n_mid), __pyx_v_idx_end); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L4_break:; - - __Pyx_RefNannyFinishContext(); -} - -/* "sklearn/neighbors/ball_tree.pyx":1402 - * # This calculates the lower-bound distance between a point and a node - * @cython.profile(False) - * cdef inline DTYPE_t calc_dist_LB(DTYPE_t* pt, # <<<<<<<<<<<<<< - * DTYPE_t* centroid, - * DTYPE_t radius, - */ - -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_calc_dist_LB(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_centroid, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_radius, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_features, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calc_dist_LB"); + __pyx_L3:; - /* "sklearn/neighbors/ball_tree.pyx":1408 - * DTYPE_t p): - * return dmax(0, (dist(pt, centroid, n_features, p) - * - radius)) # <<<<<<<<<<<<<< - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1176 + * return self.dist_metric.rdist(x1, x2, size) * + * cdef int _recursive_build(self, ITYPE_t i_node, ITYPE_t idx_start, # <<<<<<<<<<<<<< + * ITYPE_t idx_end) except -1: + * """Recursively build the tree. */ - __pyx_r = __pyx_f_7sklearn_9neighbors_9ball_tree_dmax(0.0, (__pyx_f_7sklearn_9neighbors_9ball_tree_dist(__pyx_v_pt, __pyx_v_centroid, __pyx_v_n_features, __pyx_v_p) - __pyx_v_radius)); - goto __pyx_L0; + /* function exit code */ __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree._recursive_build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; + __Pyx_XDECREF(__pyx_v_warnings); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":1412 +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1228 + * idx_start + n_mid, idx_end) * - * @cython.profile(False) - * cdef inline DTYPE_t calc_dist_p_LB(DTYPE_t* pt, # <<<<<<<<<<<<<< - * DTYPE_t* centroid, - * DTYPE_t radius, + * def query(self, X, k=1, return_distance=True, # <<<<<<<<<<<<<< + * dualtree=False, breadth_first=False, + * sort_results=True): */ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_calc_dist_p_LB(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_centroid, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_radius, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_n_features, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_p) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_r; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_19query(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_18query[] = "\n query(X, k=1, return_distance=True,\n dualtree=False, breadth_first=False)\n\n query the tree for the k nearest neighbors\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n k : integer (default = 1)\n The number of nearest neighbors to return\n return_distance : boolean (default = True)\n if True, return a tuple (d, i) of distances and indices\n if False, return array i\n dualtree : boolean (default = False)\n if True, use the dual tree formalism for the query: a tree is\n built for the query points, and the pair of trees is used to\n efficiently search this space. This can lead to better\n performance as the number of points grows large.\n breadth_first : boolean (default = False)\n if True, then query the nodes in a breadth-first manner.\n Otherwise, query the nodes in a depth-first manner.\n sort_results : boolean (default = True)\n if True, then distances and indices of each point are sorted\n on return, so that the first column contains the closest points.\n Otherwise, neighbors are returned in an arbitrary order.\n\n Returns\n -------\n i : if return_distance == False\n (d,i) : if return_distance == True\n\n d : array of doubles - shape: x.shape[:-1] + (k,)\n each entry gives the list of distances to the\n neighbors of the corresponding point\n\n i : array of integers - shape: x.shape[:-1] + (k,)\n each entry gives the list of indices of\n neighbors of the corresponding point\n\n Examples\n --------\n Query for k-nearest neighbors\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimension""s\n >>> tree = BinaryTree(X, leaf_size=2) # doctest: +SKIP\n >>> dist, ind = tree.query(X[0], k=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors\n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_19query(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_X = 0; + PyObject *__pyx_v_k = 0; + PyObject *__pyx_v_return_distance = 0; + PyObject *__pyx_v_dualtree = 0; + PyObject *__pyx_v_breadth_first = 0; + PyObject *__pyx_v_sort_results = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("calc_dist_p_LB"); + __Pyx_RefNannySetupContext("query (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_k,&__pyx_n_s_return_distance,&__pyx_n_s_dualtree,&__pyx_n_s_breadth_first,&__pyx_n_s_sort_results,0}; + PyObject* values[6] = {0,0,0,0,0,0}; + values[1] = ((PyObject *)__pyx_int_1); + values[2] = ((PyObject *)Py_True); - /* "sklearn/neighbors/ball_tree.pyx":1418 - * DTYPE_t p): - * return dist_p_from_dist(dmax(0, (dist(pt, centroid, n_features, p) - * - radius)), p) # <<<<<<<<<<<<<< - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1229 * + * def query(self, X, k=1, return_distance=True, + * dualtree=False, breadth_first=False, # <<<<<<<<<<<<<< + * sort_results=True): + * """ */ - __pyx_r = __pyx_f_7sklearn_9neighbors_9ball_tree_dist_p_from_dist(__pyx_f_7sklearn_9neighbors_9ball_tree_dmax(0.0, (__pyx_f_7sklearn_9neighbors_9ball_tree_dist(__pyx_v_pt, __pyx_v_centroid, __pyx_v_n_features, __pyx_v_p) - __pyx_v_radius)), __pyx_v_p); - goto __pyx_L0; + values[3] = ((PyObject *)Py_False); + values[4] = ((PyObject *)Py_False); - __pyx_r = 0; - __pyx_L0:; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1230 + * def query(self, X, k=1, return_distance=True, + * dualtree=False, breadth_first=False, + * sort_results=True): # <<<<<<<<<<<<<< + * """ + * query(X, k=1, return_distance=True, + */ + values[5] = ((PyObject *)Py_True); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_k); + if (value) { values[1] = value; kw_args--; } + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_return_distance); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dualtree); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_breadth_first); + if (value) { values[4] = value; kw_args--; } + } + case 5: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sort_results); + if (value) { values[5] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "query") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1228; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_X = values[0]; + __pyx_v_k = values[1]; + __pyx_v_return_distance = values[2]; + __pyx_v_dualtree = values[3]; + __pyx_v_breadth_first = values[4]; + __pyx_v_sort_results = values[5]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("query", 0, 1, 6, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1228; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.query", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_18query(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self), __pyx_v_X, __pyx_v_k, __pyx_v_return_distance, __pyx_v_dualtree, __pyx_v_breadth_first, __pyx_v_sort_results); -/* "sklearn/neighbors/ball_tree.pyx":1428 - * # are represented by infinities. - * @cython.profile(False) - * cdef inline DTYPE_t pqueue_largest(DTYPE_t* queue, ITYPE_t queue_size): # <<<<<<<<<<<<<< - * return queue[queue_size - 1] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1228 + * idx_start + n_mid, idx_end) * + * def query(self, X, k=1, return_distance=True, # <<<<<<<<<<<<<< + * dualtree=False, breadth_first=False, + * sort_results=True): */ -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_pqueue_largest(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_queue, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_queue_size) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_r; + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_18query(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_k, PyObject *__pyx_v_return_distance, PyObject *__pyx_v_dualtree, PyObject *__pyx_v_breadth_first, PyObject *__pyx_v_sort_results) { + PyObject *__pyx_v_np_Xarr = NULL; + __Pyx_memviewslice __pyx_v_Xarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt; + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_heap = 0; + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_nodeheap = 0; + __Pyx_memviewslice __pyx_v_bounds = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_other = NULL; + PyObject *__pyx_v_distances = NULL; + PyObject *__pyx_v_indices = NULL; + PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("pqueue_largest"); + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_8; + __Pyx_memviewslice __pyx_t_9 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + PyObject *(*__pyx_t_14)(PyObject *); + PyObject *__pyx_t_15 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("query", 0); + __Pyx_INCREF(__pyx_v_X); - /* "sklearn/neighbors/ball_tree.pyx":1429 - * @cython.profile(False) - * cdef inline DTYPE_t pqueue_largest(DTYPE_t* queue, ITYPE_t queue_size): - * return queue[queue_size - 1] # <<<<<<<<<<<<<< - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1287 + * """ + * # XXX: we should allow X to be a pre-built tree. + * X = check_array(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< * + * if X.shape[X.ndim - 1] != self.data.shape[1]: */ - __pyx_r = (__pyx_v_queue[(__pyx_v_queue_size - 1)]); - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_check_array); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_4); + __pyx_t_4 = 0; -/* "sklearn/neighbors/ball_tree.pyx":1432 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1289 + * X = check_array(X, dtype=DTYPE, order='C') * + * if X.shape[X.ndim - 1] != self.data.shape[1]: # <<<<<<<<<<<<<< + * raise ValueError("query data dimension must " + * "match training data dimension") + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyNumber_Subtract(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_GetItem(__pyx_t_4, __pyx_t_2); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_t_2, Py_NE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1290 * - * cdef inline ITYPE_t pqueue_idx_largest(ITYPE_t* idx_array, ITYPE_t queue_size): # <<<<<<<<<<<<<< - * return idx_array[queue_size - 1] + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") * */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_pqueue_idx_largest(__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx_array, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_queue_size) { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("pqueue_idx_largest"); - - /* "sklearn/neighbors/ball_tree.pyx":1433 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1293 + * "match training data dimension") * - * cdef inline ITYPE_t pqueue_idx_largest(ITYPE_t* idx_array, ITYPE_t queue_size): - * return idx_array[queue_size - 1] # <<<<<<<<<<<<<< + * if self.data.shape[0] < k: # <<<<<<<<<<<<<< + * raise ValueError("k must be less than or equal " + * "to the number of training points") + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1293; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->data.shape[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1293; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = PyObject_RichCompare(__pyx_t_4, __pyx_v_k, Py_LT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1293; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1293; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1294 * + * if self.data.shape[0] < k: + * raise ValueError("k must be less than or equal " # <<<<<<<<<<<<<< + * "to the number of training points") * */ - __pyx_r = (__pyx_v_idx_array[(__pyx_v_queue_size - 1)]); - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } -/* "sklearn/neighbors/ball_tree.pyx":1436 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1298 * - * - * cdef inline void pqueue_insert(DTYPE_t val, ITYPE_t i_val, # <<<<<<<<<<<<<< - * DTYPE_t* queue, ITYPE_t* idx_array, - * ITYPE_t queue_size): + * # flatten X, and save original shape information + * np_Xarr = X.reshape((-1, self.data.shape[1])) # <<<<<<<<<<<<<< + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(np_Xarr) + * cdef DTYPE_t reduced_dist_LB */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_reshape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_np_Xarr = __pyx_t_3; + __pyx_t_3 = 0; -static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_9ball_tree_pqueue_insert(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_val, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_val, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_queue, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx_array, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_queue_size) { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_lower; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_upper; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_mid; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_t_2; - __Pyx_RefNannySetupContext("pqueue_insert"); - - /* "sklearn/neighbors/ball_tree.pyx":1439 - * DTYPE_t* queue, ITYPE_t* idx_array, - * ITYPE_t queue_size): - * cdef ITYPE_t i_lower = 0 # <<<<<<<<<<<<<< - * cdef ITYPE_t i_upper = queue_size - 1 - * cdef ITYPE_t i_mid - */ - __pyx_v_i_lower = 0; - - /* "sklearn/neighbors/ball_tree.pyx":1440 - * ITYPE_t queue_size): - * cdef ITYPE_t i_lower = 0 - * cdef ITYPE_t i_upper = queue_size - 1 # <<<<<<<<<<<<<< - * cdef ITYPE_t i_mid - * cdef ITYPE_t i + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1299 + * # flatten X, and save original shape information + * np_Xarr = X.reshape((-1, self.data.shape[1])) + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(np_Xarr) # <<<<<<<<<<<<<< + * cdef DTYPE_t reduced_dist_LB + * cdef ITYPE_t i */ - __pyx_v_i_upper = (__pyx_v_queue_size - 1); + if (!(likely(((__pyx_v_np_Xarr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_np_Xarr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_v_np_Xarr)); if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_Xarr = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1444 - * cdef ITYPE_t i + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1305 + * + * # initialize heap for neighbors + * cdef NeighborsHeap heap = NeighborsHeap(Xarr.shape[0], k) # <<<<<<<<<<<<<< * - * if val >= queue[i_upper]: # <<<<<<<<<<<<<< - * return - * elif val <= queue[i_lower]: + * # node heap for breadth-first queries */ - __pyx_t_1 = (__pyx_v_val >= (__pyx_v_queue[__pyx_v_i_upper])); - if (__pyx_t_1) { + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_Xarr.shape[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_k); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_v_k); + __Pyx_GIVEREF(__pyx_v_k); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_9ball_tree_NeighborsHeap)), __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_heap = ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_t_3); + __pyx_t_3 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1445 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1309 + * # node heap for breadth-first queries + * cdef NodeHeap nodeheap + * if breadth_first: # <<<<<<<<<<<<<< + * nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) * - * if val >= queue[i_upper]: - * return # <<<<<<<<<<<<<< - * elif val <= queue[i_lower]: - * i_mid = i_lower */ - goto __pyx_L0; - goto __pyx_L3; - } - - /* "sklearn/neighbors/ball_tree.pyx":1446 - * if val >= queue[i_upper]: - * return - * elif val <= queue[i_lower]: # <<<<<<<<<<<<<< - * i_mid = i_lower - * else: - */ - __pyx_t_1 = (__pyx_v_val <= (__pyx_v_queue[__pyx_v_i_lower])); - if (__pyx_t_1) { + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_breadth_first); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1309; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { - /* "sklearn/neighbors/ball_tree.pyx":1447 - * return - * elif val <= queue[i_lower]: - * i_mid = i_lower # <<<<<<<<<<<<<< - * else: - * while True: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1310 + * cdef NodeHeap nodeheap + * if breadth_first: + * nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) # <<<<<<<<<<<<<< + * + * # bounds is needed for the dual tree algorithm */ - __pyx_v_i_mid = __pyx_v_i_lower; - goto __pyx_L3; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1310; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = PyInt_FromSsize_t(((__pyx_v_self->data.shape[0]) / __pyx_v_self->leaf_size)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_9ball_tree_NodeHeap)), __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_nodeheap = ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L5; } - /*else*/ { - - /* "sklearn/neighbors/ball_tree.pyx":1449 - * i_mid = i_lower - * else: - * while True: # <<<<<<<<<<<<<< - * if (i_upper - i_lower) < 2: - * i_mid = i_lower + 1 - */ - while (1) { - if (!1) break; - - /* "sklearn/neighbors/ball_tree.pyx":1450 - * else: - * while True: - * if (i_upper - i_lower) < 2: # <<<<<<<<<<<<<< - * i_mid = i_lower + 1 - * break - */ - __pyx_t_1 = ((__pyx_v_i_upper - __pyx_v_i_lower) < 2); - if (__pyx_t_1) { + __pyx_L5:; - /* "sklearn/neighbors/ball_tree.pyx":1451 - * while True: - * if (i_upper - i_lower) < 2: - * i_mid = i_lower + 1 # <<<<<<<<<<<<<< - * break - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1315 + * cdef DTYPE_t[::1] bounds + * + * self.n_trims = 0 # <<<<<<<<<<<<<< + * self.n_leaves = 0 + * self.n_splits = 0 */ - __pyx_v_i_mid = (__pyx_v_i_lower + 1); + __pyx_v_self->n_trims = 0; - /* "sklearn/neighbors/ball_tree.pyx":1452 - * if (i_upper - i_lower) < 2: - * i_mid = i_lower + 1 - * break # <<<<<<<<<<<<<< - * else: - * i_mid = (i_lower + i_upper) / 2 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1316 + * + * self.n_trims = 0 + * self.n_leaves = 0 # <<<<<<<<<<<<<< + * self.n_splits = 0 + * */ - goto __pyx_L5_break; - goto __pyx_L6; - } - /*else*/ { + __pyx_v_self->n_leaves = 0; - /* "sklearn/neighbors/ball_tree.pyx":1454 - * break - * else: - * i_mid = (i_lower + i_upper) / 2 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1317 + * self.n_trims = 0 + * self.n_leaves = 0 + * self.n_splits = 0 # <<<<<<<<<<<<<< * - * if i_mid == i_lower: + * if dualtree: */ - __pyx_v_i_mid = __Pyx_div_long((__pyx_v_i_lower + __pyx_v_i_upper), 2); - } - __pyx_L6:; + __pyx_v_self->n_splits = 0; - /* "sklearn/neighbors/ball_tree.pyx":1456 - * i_mid = (i_lower + i_upper) / 2 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1319 + * self.n_splits = 0 * - * if i_mid == i_lower: # <<<<<<<<<<<<<< - * i_mid += 1 - * break + * if dualtree: # <<<<<<<<<<<<<< + * other = self.__class__(np_Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) */ - __pyx_t_1 = (__pyx_v_i_mid == __pyx_v_i_lower); - if (__pyx_t_1) { + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_dualtree); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { - /* "sklearn/neighbors/ball_tree.pyx":1457 - * - * if i_mid == i_lower: - * i_mid += 1 # <<<<<<<<<<<<<< - * break + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1320 * + * if dualtree: + * other = self.__class__(np_Xarr, metric=self.dist_metric, # <<<<<<<<<<<<<< + * leaf_size=self.leaf_size) + * if breadth_first: */ - __pyx_v_i_mid = (__pyx_v_i_mid + 1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_class); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_np_Xarr); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_np_Xarr); + __Pyx_GIVEREF(__pyx_v_np_Xarr); + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_metric, ((PyObject *)__pyx_v_self->dist_metric)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/neighbors/ball_tree.pyx":1458 - * if i_mid == i_lower: - * i_mid += 1 - * break # <<<<<<<<<<<<<< - * - * if val >= queue[i_mid]: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1321 + * if dualtree: + * other = self.__class__(np_Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) # <<<<<<<<<<<<<< + * if breadth_first: + * self._query_dual_breadthfirst(other, heap, nodeheap) */ - goto __pyx_L5_break; - goto __pyx_L7; - } - __pyx_L7:; + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->leaf_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_leaf_size, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1460 - * break + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1320 * - * if val >= queue[i_mid]: # <<<<<<<<<<<<<< - * i_lower = i_mid - * else: + * if dualtree: + * other = self.__class__(np_Xarr, metric=self.dist_metric, # <<<<<<<<<<<<<< + * leaf_size=self.leaf_size) + * if breadth_first: */ - __pyx_t_1 = (__pyx_v_val >= (__pyx_v_queue[__pyx_v_i_mid])); - if (__pyx_t_1) { + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_other = __pyx_t_1; + __pyx_t_1 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1461 - * - * if val >= queue[i_mid]: - * i_lower = i_mid # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1322 + * other = self.__class__(np_Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) + * if breadth_first: # <<<<<<<<<<<<<< + * self._query_dual_breadthfirst(other, heap, nodeheap) * else: - * i_upper = i_mid */ - __pyx_v_i_lower = __pyx_v_i_mid; - goto __pyx_L8; - } - /*else*/ { + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_breadth_first); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1322; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { - /* "sklearn/neighbors/ball_tree.pyx":1463 - * i_lower = i_mid + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1323 + * leaf_size=self.leaf_size) + * if breadth_first: + * self._query_dual_breadthfirst(other, heap, nodeheap) # <<<<<<<<<<<<<< * else: - * i_upper = i_mid # <<<<<<<<<<<<<< - * - * for i from queue_size > i > i_mid: + * reduced_dist_LB = min_rdist_dual(self, 0, other, 0) */ - __pyx_v_i_upper = __pyx_v_i_mid; - } - __pyx_L8:; + if (!(likely(((__pyx_v_other) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_other, __pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__pyx_v_nodeheap)) { __Pyx_RaiseUnboundLocalError("nodeheap"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_breadthfirst(__pyx_v_self, ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_other), __pyx_v_heap, __pyx_v_nodeheap); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; } - __pyx_L5_break:; - } - __pyx_L3:; + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":1465 - * i_upper = i_mid - * - * for i from queue_size > i > i_mid: # <<<<<<<<<<<<<< - * queue[i] = queue[i - 1] - * idx_array[i] = idx_array[i - 1] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1325 + * self._query_dual_breadthfirst(other, heap, nodeheap) + * else: + * reduced_dist_LB = min_rdist_dual(self, 0, other, 0) # <<<<<<<<<<<<<< + * bounds = np.inf + np.zeros(other.node_data.shape[0]) + * self._query_dual_depthfirst(0, other, 0, bounds, */ - __pyx_t_2 = __pyx_v_i_mid; - for (__pyx_v_i = __pyx_v_queue_size-1; __pyx_v_i > __pyx_t_2; __pyx_v_i--) { + if (!(likely(((__pyx_v_other) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_other, __pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist_dual(__pyx_v_self, 0, ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_other), 0); if (unlikely(__pyx_t_8 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB = __pyx_t_8; - /* "sklearn/neighbors/ball_tree.pyx":1466 - * - * for i from queue_size > i > i_mid: - * queue[i] = queue[i - 1] # <<<<<<<<<<<<<< - * idx_array[i] = idx_array[i - 1] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1326 + * else: + * reduced_dist_LB = min_rdist_dual(self, 0, other, 0) + * bounds = np.inf + np.zeros(other.node_data.shape[0]) # <<<<<<<<<<<<<< + * self._query_dual_depthfirst(0, other, 0, bounds, + * heap, reduced_dist_LB) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_other, __pyx_n_s_node_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_3, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Add(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_9 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(__pyx_t_3); + if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_bounds = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1327 + * reduced_dist_LB = min_rdist_dual(self, 0, other, 0) + * bounds = np.inf + np.zeros(other.node_data.shape[0]) + * self._query_dual_depthfirst(0, other, 0, bounds, # <<<<<<<<<<<<<< + * heap, reduced_dist_LB) * */ - (__pyx_v_queue[__pyx_v_i]) = (__pyx_v_queue[(__pyx_v_i - 1)]); + if (!(likely(((__pyx_v_other) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_other, __pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/neighbors/ball_tree.pyx":1467 - * for i from queue_size > i > i_mid: - * queue[i] = queue[i - 1] - * idx_array[i] = idx_array[i - 1] # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1328 + * bounds = np.inf + np.zeros(other.node_data.shape[0]) + * self._query_dual_depthfirst(0, other, 0, bounds, + * heap, reduced_dist_LB) # <<<<<<<<<<<<<< * - * queue[i_mid] = val + * else: */ - (__pyx_v_idx_array[__pyx_v_i]) = (__pyx_v_idx_array[(__pyx_v_i - 1)]); + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, 0, ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_other), 0, __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + goto __pyx_L6; } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":1469 - * idx_array[i] = idx_array[i - 1] - * - * queue[i_mid] = val # <<<<<<<<<<<<<< - * idx_array[i_mid] = i_val + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1331 * + * else: + * pt = &Xarr[0, 0] # <<<<<<<<<<<<<< + * if breadth_first: + * for i in range(Xarr.shape[0]): */ - (__pyx_v_queue[__pyx_v_i_mid]) = __pyx_v_val; + __pyx_t_10 = 0; + __pyx_t_11 = 0; + __pyx_v_pt = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_Xarr.data + __pyx_t_10 * __pyx_v_Xarr.strides[0]) )) + __pyx_t_11)) )))); - /* "sklearn/neighbors/ball_tree.pyx":1470 - * - * queue[i_mid] = val - * idx_array[i_mid] = i_val # <<<<<<<<<<<<<< - * - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1332 + * else: + * pt = &Xarr[0, 0] + * if breadth_first: # <<<<<<<<<<<<<< + * for i in range(Xarr.shape[0]): + * self._query_single_breadthfirst(pt, i, heap, nodeheap) + */ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_breadth_first); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1332; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1333 + * pt = &Xarr[0, 0] + * if breadth_first: + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * self._query_single_breadthfirst(pt, i, heap, nodeheap) + * pt += Xarr.shape[1] + */ + __pyx_t_12 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1334 + * if breadth_first: + * for i in range(Xarr.shape[0]): + * self._query_single_breadthfirst(pt, i, heap, nodeheap) # <<<<<<<<<<<<<< + * pt += Xarr.shape[1] + * else: */ - (__pyx_v_idx_array[__pyx_v_i_mid]) = __pyx_v_i_val; - - __pyx_L0:; - __Pyx_RefNannyFinishContext(); -} + if (unlikely(!__pyx_v_nodeheap)) { __Pyx_RaiseUnboundLocalError("nodeheap"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_breadthfirst(__pyx_v_self, __pyx_v_pt, __pyx_v_i, __pyx_v_heap, __pyx_v_nodeheap); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} -/* "sklearn/neighbors/ball_tree.pyx":1496 - * # `sort_dist_idx()` - * @cython.profile(False) - * cdef inline DTYPE_t max_heap_largest(DTYPE_t* heap, ITYPE_t k): # <<<<<<<<<<<<<< - * return heap[0] - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1335 + * for i in range(Xarr.shape[0]): + * self._query_single_breadthfirst(pt, i, heap, nodeheap) + * pt += Xarr.shape[1] # <<<<<<<<<<<<<< + * else: + * for i in range(Xarr.shape[0]): */ + __pyx_v_pt = (__pyx_v_pt + (__pyx_v_Xarr.shape[1])); + } + goto __pyx_L8; + } + /*else*/ { -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_max_heap_largest(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_heap, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_k) { - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("max_heap_largest"); - - /* "sklearn/neighbors/ball_tree.pyx":1497 - * @cython.profile(False) - * cdef inline DTYPE_t max_heap_largest(DTYPE_t* heap, ITYPE_t k): - * return heap[0] # <<<<<<<<<<<<<< - * - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1337 + * pt += Xarr.shape[1] + * else: + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * reduced_dist_LB = min_rdist(self, 0, pt) + * self._query_single_depthfirst(0, pt, i, heap, */ - __pyx_r = (__pyx_v_heap[0]); - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_t_12 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; -/* "sklearn/neighbors/ball_tree.pyx":1501 - * - * @cython.profile(False) - * cdef inline ITYPE_t max_heap_idx_largest(ITYPE_t* idx_array, ITYPE_t k): # <<<<<<<<<<<<<< - * return idx_array[0] - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1338 + * else: + * for i in range(Xarr.shape[0]): + * reduced_dist_LB = min_rdist(self, 0, pt) # <<<<<<<<<<<<<< + * self._query_single_depthfirst(0, pt, i, heap, + * reduced_dist_LB) */ + __pyx_t_8 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist(__pyx_v_self, 0, __pyx_v_pt); if (unlikely(__pyx_t_8 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1338; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB = __pyx_t_8; -static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_max_heap_idx_largest(__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx_array, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_k) { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("max_heap_idx_largest"); - - /* "sklearn/neighbors/ball_tree.pyx":1502 - * @cython.profile(False) - * cdef inline ITYPE_t max_heap_idx_largest(ITYPE_t* idx_array, ITYPE_t k): - * return idx_array[0] # <<<<<<<<<<<<<< - * - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1339 + * for i in range(Xarr.shape[0]): + * reduced_dist_LB = min_rdist(self, 0, pt) + * self._query_single_depthfirst(0, pt, i, heap, # <<<<<<<<<<<<<< + * reduced_dist_LB) + * pt += Xarr.shape[1] */ - __pyx_r = (__pyx_v_idx_array[0]); - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_depthfirst(__pyx_v_self, 0, __pyx_v_pt, __pyx_v_i, __pyx_v_heap, __pyx_v_reduced_dist_LB); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1339; __pyx_clineno = __LINE__; goto __pyx_L1_error;} -/* "sklearn/neighbors/ball_tree.pyx":1505 - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1341 + * self._query_single_depthfirst(0, pt, i, heap, + * reduced_dist_LB) + * pt += Xarr.shape[1] # <<<<<<<<<<<<<< * - * cdef void max_heap_insert(DTYPE_t val, ITYPE_t i_val, # <<<<<<<<<<<<<< - * DTYPE_t* heap, - * ITYPE_t* idx_array, + * distances, indices = heap.get_arrays(sort=sort_results) */ + __pyx_v_pt = (__pyx_v_pt + (__pyx_v_Xarr.shape[1])); + } + } + __pyx_L8:; + } + __pyx_L6:; -static void __pyx_f_7sklearn_9neighbors_9ball_tree_max_heap_insert(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_val, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_val, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_heap, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx_array, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_heap_size) { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_ic1; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_ic2; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i_swap; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("max_heap_insert"); - - /* "sklearn/neighbors/ball_tree.pyx":1513 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1343 + * pt += Xarr.shape[1] * - * # check if val should be in heap - * if val > heap[0]: # <<<<<<<<<<<<<< - * return - * - */ - __pyx_t_1 = (__pyx_v_val > (__pyx_v_heap[0])); - if (__pyx_t_1) { - - /* "sklearn/neighbors/ball_tree.pyx":1514 - * # check if val should be in heap - * if val > heap[0]: - * return # <<<<<<<<<<<<<< + * distances, indices = heap.get_arrays(sort=sort_results) # <<<<<<<<<<<<<< + * distances = self.dist_metric.rdist_to_dist(distances) * - * # insert val at position zero */ - goto __pyx_L0; - goto __pyx_L3; + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_heap), __pyx_n_s_get_arrays); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_sort, __pyx_v_sort_results) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_empty_tuple, __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_1 = PyList_GET_ITEM(sequence, 0); + __pyx_t_3 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_14 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_1 = __pyx_t_14(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L13_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + index = 1; __pyx_t_3 = __pyx_t_14(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L13_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_14(__pyx_t_4), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = NULL; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L14_unpacking_done; + __pyx_L13_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_14 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L14_unpacking_done:; } - __pyx_L3:; + __pyx_v_distances = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_v_indices = __pyx_t_3; + __pyx_t_3 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1517 - * - * # insert val at position zero - * heap[0] = val # <<<<<<<<<<<<<< - * idx_array[0] = i_val + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1344 * - */ - (__pyx_v_heap[0]) = __pyx_v_val; - - /* "sklearn/neighbors/ball_tree.pyx":1518 - * # insert val at position zero - * heap[0] = val - * idx_array[0] = i_val # <<<<<<<<<<<<<< + * distances, indices = heap.get_arrays(sort=sort_results) + * distances = self.dist_metric.rdist_to_dist(distances) # <<<<<<<<<<<<<< * - * #descend the heap, swapping values until the max heap criterion is met + * # deflatten results */ - (__pyx_v_idx_array[0]) = __pyx_v_i_val; + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->dist_metric), __pyx_n_s_rdist_to_dist); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1344; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1344; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_distances); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_distances); + __Pyx_GIVEREF(__pyx_v_distances); + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1344; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_distances, __pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1521 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1347 * - * #descend the heap, swapping values until the max heap criterion is met - * i = 0 # <<<<<<<<<<<<<< - * while 1: - * ic1 = 2 * i + 1 + * # deflatten results + * if return_distance: # <<<<<<<<<<<<<< + * return (distances.reshape(X.shape[:X.ndim - 1] + (k,)), + * indices.reshape(X.shape[:X.ndim - 1] + (k,))) */ - __pyx_v_i = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { - /* "sklearn/neighbors/ball_tree.pyx":1522 - * #descend the heap, swapping values until the max heap criterion is met - * i = 0 - * while 1: # <<<<<<<<<<<<<< - * ic1 = 2 * i + 1 - * ic2 = ic1 + 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1348 + * # deflatten results + * if return_distance: + * return (distances.reshape(X.shape[:X.ndim - 1] + (k,)), # <<<<<<<<<<<<<< + * indices.reshape(X.shape[:X.ndim - 1] + (k,))) + * else: */ - while (1) { - if (!1) break; + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_distances, __pyx_n_s_reshape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyNumber_Subtract(__pyx_t_2, __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_t_3, 0, 0, NULL, &__pyx_t_4, NULL, 0, 0, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_k); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_k); + __Pyx_GIVEREF(__pyx_v_k); + __pyx_t_3 = PyNumber_Add(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1523 - * i = 0 - * while 1: - * ic1 = 2 * i + 1 # <<<<<<<<<<<<<< - * ic2 = ic1 + 1 - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1349 + * if return_distance: + * return (distances.reshape(X.shape[:X.ndim - 1] + (k,)), + * indices.reshape(X.shape[:X.ndim - 1] + (k,))) # <<<<<<<<<<<<<< + * else: + * return indices.reshape(X.shape[:X.ndim - 1] + (k,)) */ - __pyx_v_ic1 = ((2 * __pyx_v_i) + 1); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_indices, __pyx_n_s_reshape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_15 = PyNumber_Subtract(__pyx_t_2, __pyx_int_1); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_t_1, 0, 0, NULL, &__pyx_t_15, NULL, 0, 0, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_15 = PyTuple_New(1); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + __Pyx_INCREF(__pyx_v_k); + PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_v_k); + __Pyx_GIVEREF(__pyx_v_k); + __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_t_15); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_15 = PyTuple_New(1); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_15, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1524 - * while 1: - * ic1 = 2 * i + 1 - * ic2 = ic1 + 1 # <<<<<<<<<<<<<< - * - * if ic1 >= heap_size: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1348 + * # deflatten results + * if return_distance: + * return (distances.reshape(X.shape[:X.ndim - 1] + (k,)), # <<<<<<<<<<<<<< + * indices.reshape(X.shape[:X.ndim - 1] + (k,))) + * else: */ - __pyx_v_ic2 = (__pyx_v_ic1 + 1); + __pyx_t_15 = PyTuple_New(2); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_15, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_3 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_15; + __pyx_t_15 = 0; + goto __pyx_L0; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":1526 - * ic2 = ic1 + 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1351 + * indices.reshape(X.shape[:X.ndim - 1] + (k,))) + * else: + * return indices.reshape(X.shape[:X.ndim - 1] + (k,)) # <<<<<<<<<<<<<< * - * if ic1 >= heap_size: # <<<<<<<<<<<<<< - * break - * elif ic2 >= heap_size: + * def query_radius(self, X, r, return_distance=False, */ - __pyx_t_1 = (__pyx_v_ic1 >= __pyx_v_heap_size); - if (__pyx_t_1) { - - /* "sklearn/neighbors/ball_tree.pyx":1527 + __Pyx_XDECREF(__pyx_r); + __pyx_t_15 = __Pyx_PyObject_GetAttrStr(__pyx_v_indices, __pyx_n_s_reshape); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyNumber_Subtract(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_t_1, 0, 0, NULL, &__pyx_t_4, NULL, 0, 0, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_k); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_k); + __Pyx_GIVEREF(__pyx_v_k); + __pyx_t_1 = PyNumber_Add(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_15, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1228 + * idx_start + n_mid, idx_end) * - * if ic1 >= heap_size: - * break # <<<<<<<<<<<<<< - * elif ic2 >= heap_size: - * if heap[ic1] > val: + * def query(self, X, k=1, return_distance=True, # <<<<<<<<<<<<<< + * dualtree=False, breadth_first=False, + * sort_results=True): */ - goto __pyx_L5_break; - goto __pyx_L6; - } - /* "sklearn/neighbors/ball_tree.pyx":1528 - * if ic1 >= heap_size: - * break - * elif ic2 >= heap_size: # <<<<<<<<<<<<<< - * if heap[ic1] > val: - * i_swap = ic1 - */ - __pyx_t_1 = (__pyx_v_ic2 >= __pyx_v_heap_size); - if (__pyx_t_1) { + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_9, 1); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.query", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_np_Xarr); + __PYX_XDEC_MEMVIEW(&__pyx_v_Xarr, 1); + __Pyx_XDECREF((PyObject *)__pyx_v_heap); + __Pyx_XDECREF((PyObject *)__pyx_v_nodeheap); + __PYX_XDEC_MEMVIEW(&__pyx_v_bounds, 1); + __Pyx_XDECREF(__pyx_v_other); + __Pyx_XDECREF(__pyx_v_distances); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XDECREF(__pyx_v_X); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/neighbors/ball_tree.pyx":1529 - * break - * elif ic2 >= heap_size: - * if heap[ic1] > val: # <<<<<<<<<<<<<< - * i_swap = ic1 - * else: +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1353 + * return indices.reshape(X.shape[:X.ndim - 1] + (k,)) + * + * def query_radius(self, X, r, return_distance=False, # <<<<<<<<<<<<<< + * int count_only=False, int sort_results=False): + * """ */ - __pyx_t_1 = ((__pyx_v_heap[__pyx_v_ic1]) > __pyx_v_val); - if (__pyx_t_1) { - /* "sklearn/neighbors/ball_tree.pyx":1530 - * elif ic2 >= heap_size: - * if heap[ic1] > val: - * i_swap = ic1 # <<<<<<<<<<<<<< - * else: - * break - */ - __pyx_v_i_swap = __pyx_v_ic1; - goto __pyx_L7; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_21query_radius(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_20query_radius[] = "\n query_radius(self, X, r, count_only = False):\n\n query the tree for neighbors within a radius r\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n r : distance within which neighbors are returned\n r can be a single value, or an array of values of shape\n x.shape[:-1] if different radii are desired for each point.\n return_distance : boolean (default = False)\n if True, return distances to neighbors of each point\n if False, return only neighbors\n Note that unlike the query() method, setting return_distance=True\n here adds to the computation time. Not all distances need to be\n calculated explicitly for return_distance=False. Results are\n not sorted by default: see ``sort_results`` keyword.\n count_only : boolean (default = False)\n if True, return only the count of points within distance r\n if False, return the indices of all points within distance r\n If return_distance==True, setting count_only=True will\n result in an error.\n sort_results : boolean (default = False)\n if True, the distances and indices will be sorted before being\n returned. If False, the results will not be sorted. If\n return_distance == False, setting sort_results = True will\n result in an error.\n\n Returns\n -------\n count : if count_only == True\n ind : if count_only == False and return_distance == False\n (ind, dist) : if count_only == False and return_distance == True\n\n count : array of integers, shape = X.shape[:-1]\n each entry gives the number of neighbors within\n a distance r of the corresponding point.\n\n ind : array of objects, shape = X.shape[:-1]\n each element is a num""py integer array listing the indices of\n neighbors of the corresponding point. Note that unlike\n the results of a k-neighbors query, the returned neighbors\n are not sorted by distance by default.\n\n dist : array of objects, shape = X.shape[:-1]\n each element is a numpy double array\n listing the distances corresponding to indices in i.\n\n Examples\n --------\n Query for neighbors in a given radius\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions\n >>> tree = BinaryTree(X, leaf_size=2) # doctest: +SKIP\n >>> print tree.query_radius(X[0], r=0.3, count_only=True)\n 3\n >>> ind = tree.query_radius(X[0], r=0.3) # doctest: +SKIP\n >>> print ind # indices of neighbors within distance 0.3\n [3 0 1]\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_21query_radius(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_X = 0; + PyObject *__pyx_v_r = 0; + PyObject *__pyx_v_return_distance = 0; + int __pyx_v_count_only; + int __pyx_v_sort_results; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("query_radius (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_r,&__pyx_n_s_return_distance,&__pyx_n_s_count_only,&__pyx_n_s_sort_results,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[2] = ((PyObject *)Py_False); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; } - /*else*/ { - - /* "sklearn/neighbors/ball_tree.pyx":1532 - * i_swap = ic1 - * else: - * break # <<<<<<<<<<<<<< - * elif heap[ic1] >= heap[ic2]: - * if val < heap[ic1]: - */ - goto __pyx_L5_break; + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_r)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("query_radius", 0, 2, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1353; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_return_distance); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_count_only); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sort_results); + if (value) { values[4] = value; kw_args--; } + } } - __pyx_L7:; - goto __pyx_L6; - } - - /* "sklearn/neighbors/ball_tree.pyx":1533 - * else: - * break - * elif heap[ic1] >= heap[ic2]: # <<<<<<<<<<<<<< - * if val < heap[ic1]: - * i_swap = ic1 - */ - __pyx_t_1 = ((__pyx_v_heap[__pyx_v_ic1]) >= (__pyx_v_heap[__pyx_v_ic2])); - if (__pyx_t_1) { - - /* "sklearn/neighbors/ball_tree.pyx":1534 - * break - * elif heap[ic1] >= heap[ic2]: - * if val < heap[ic1]: # <<<<<<<<<<<<<< - * i_swap = ic1 - * else: - */ - __pyx_t_1 = (__pyx_v_val < (__pyx_v_heap[__pyx_v_ic1])); - if (__pyx_t_1) { - - /* "sklearn/neighbors/ball_tree.pyx":1535 - * elif heap[ic1] >= heap[ic2]: - * if val < heap[ic1]: - * i_swap = ic1 # <<<<<<<<<<<<<< - * else: - * break - */ - __pyx_v_i_swap = __pyx_v_ic1; - goto __pyx_L8; + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "query_radius") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1353; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - /*else*/ { - - /* "sklearn/neighbors/ball_tree.pyx":1537 - * i_swap = ic1 - * else: - * break # <<<<<<<<<<<<<< - * else: - * if val < heap[ic2]: - */ - goto __pyx_L5_break; + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; } - __pyx_L8:; - goto __pyx_L6; } - /*else*/ { - - /* "sklearn/neighbors/ball_tree.pyx":1539 - * break - * else: - * if val < heap[ic2]: # <<<<<<<<<<<<<< - * i_swap = ic2 - * else: - */ - __pyx_t_1 = (__pyx_v_val < (__pyx_v_heap[__pyx_v_ic2])); - if (__pyx_t_1) { - - /* "sklearn/neighbors/ball_tree.pyx":1540 - * else: - * if val < heap[ic2]: - * i_swap = ic2 # <<<<<<<<<<<<<< - * else: - * break - */ - __pyx_v_i_swap = __pyx_v_ic2; - goto __pyx_L9; - } - /*else*/ { + __pyx_v_X = values[0]; + __pyx_v_r = values[1]; + __pyx_v_return_distance = values[2]; + if (values[3]) { + __pyx_v_count_only = __Pyx_PyInt_As_int(values[3]); if (unlikely((__pyx_v_count_only == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1354; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { - /* "sklearn/neighbors/ball_tree.pyx":1542 - * i_swap = ic2 - * else: - * break # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1354 * - * heap[i] = heap[i_swap] + * def query_radius(self, X, r, return_distance=False, + * int count_only=False, int sort_results=False): # <<<<<<<<<<<<<< + * """ + * query_radius(self, X, r, count_only = False): */ - goto __pyx_L5_break; - } - __pyx_L9:; + __pyx_v_count_only = ((int)0); + } + if (values[4]) { + __pyx_v_sort_results = __Pyx_PyInt_As_int(values[4]); if (unlikely((__pyx_v_sort_results == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1354; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_sort_results = ((int)0); } - __pyx_L6:; - - /* "sklearn/neighbors/ball_tree.pyx":1544 - * break - * - * heap[i] = heap[i_swap] # <<<<<<<<<<<<<< - * idx_array[i] = idx_array[i_swap] - * - */ - (__pyx_v_heap[__pyx_v_i]) = (__pyx_v_heap[__pyx_v_i_swap]); - - /* "sklearn/neighbors/ball_tree.pyx":1545 - * - * heap[i] = heap[i_swap] - * idx_array[i] = idx_array[i_swap] # <<<<<<<<<<<<<< - * - * i = i_swap - */ - (__pyx_v_idx_array[__pyx_v_i]) = (__pyx_v_idx_array[__pyx_v_i_swap]); - - /* "sklearn/neighbors/ball_tree.pyx":1547 - * idx_array[i] = idx_array[i_swap] - * - * i = i_swap # <<<<<<<<<<<<<< - * - * heap[i] = val - */ - __pyx_v_i = __pyx_v_i_swap; } - __pyx_L5_break:; - - /* "sklearn/neighbors/ball_tree.pyx":1549 - * i = i_swap - * - * heap[i] = val # <<<<<<<<<<<<<< - * idx_array[i] = i_val - * - */ - (__pyx_v_heap[__pyx_v_i]) = __pyx_v_val; + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("query_radius", 0, 2, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1353; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.query_radius", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_20query_radius(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self), __pyx_v_X, __pyx_v_r, __pyx_v_return_distance, __pyx_v_count_only, __pyx_v_sort_results); - /* "sklearn/neighbors/ball_tree.pyx":1550 - * - * heap[i] = val - * idx_array[i] = i_val # <<<<<<<<<<<<<< - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1353 + * return indices.reshape(X.shape[:X.ndim - 1] + (k,)) * + * def query_radius(self, X, r, return_distance=False, # <<<<<<<<<<<<<< + * int count_only=False, int sort_results=False): + * """ */ - (__pyx_v_idx_array[__pyx_v_i]) = __pyx_v_i_val; - __pyx_L0:; + /* function exit code */ __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "sklearn/neighbors/ball_tree.pyx":1557 - * # this is a quicksort implementation which sorts `dist` and - * # simultaneously performs the same swaps on `idx`. - * cdef void sort_dist_idx(DTYPE_t* dist, ITYPE_t* idx, ITYPE_t k): # <<<<<<<<<<<<<< - * cdef ITYPE_t pivot_idx - * if k > 1: - */ - -static void __pyx_f_7sklearn_9neighbors_9ball_tree_sort_dist_idx(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_dist, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_k) { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_pivot_idx; +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_20query_radius(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_r, PyObject *__pyx_v_return_distance, int __pyx_v_count_only, int __pyx_v_sort_results) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_count_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __Pyx_memviewslice __pyx_v_dist_arr_i = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_idx_arr_i = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_counts = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt; + __Pyx_memviewslice __pyx_v_Xarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_rarr_np = NULL; + __Pyx_memviewslice __pyx_v_rarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_indices = NULL; + PyObject *__pyx_v_distances = NULL; + PyObject *__pyx_v_np_idx_arr = NULL; + PyObject *__pyx_v_np_dist_arr = NULL; + PyObject *__pyx_v_counts_arr = NULL; + PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("sort_dist_idx"); + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_t_8 = NULL; + __Pyx_memviewslice __pyx_t_9 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_10 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + Py_ssize_t __pyx_t_16; + Py_ssize_t __pyx_t_17; + int __pyx_t_18; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_19; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_20; + Py_ssize_t __pyx_t_21; + Py_ssize_t __pyx_t_22; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_23; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_24; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("query_radius", 0); + __Pyx_INCREF(__pyx_v_X); + __Pyx_INCREF(__pyx_v_r); - /* "sklearn/neighbors/ball_tree.pyx":1559 - * cdef void sort_dist_idx(DTYPE_t* dist, ITYPE_t* idx, ITYPE_t k): - * cdef ITYPE_t pivot_idx - * if k > 1: # <<<<<<<<<<<<<< - * pivot_idx = partition_dist_idx(dist, idx, k) - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1419 + * [3 0 1] + * """ + * if count_only and return_distance: # <<<<<<<<<<<<<< + * raise ValueError("count_only and return_distance " + * "cannot both be true") */ - __pyx_t_1 = (__pyx_v_k > 1); - if (__pyx_t_1) { + if ((__pyx_v_count_only != 0)) { + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1419; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = (__pyx_v_count_only != 0); + } + if (__pyx_t_2) { - /* "sklearn/neighbors/ball_tree.pyx":1560 - * cdef ITYPE_t pivot_idx - * if k > 1: - * pivot_idx = partition_dist_idx(dist, idx, k) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1420 + * """ + * if count_only and return_distance: + * raise ValueError("count_only and return_distance " # <<<<<<<<<<<<<< + * "cannot both be true") * - * sort_dist_idx(dist, idx, pivot_idx) */ - __pyx_v_pivot_idx = __pyx_f_7sklearn_9neighbors_9ball_tree_partition_dist_idx(__pyx_v_dist, __pyx_v_idx, __pyx_v_k); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "sklearn/neighbors/ball_tree.pyx":1562 - * pivot_idx = partition_dist_idx(dist, idx, k) - * - * sort_dist_idx(dist, idx, pivot_idx) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1423 + * "cannot both be true") * - * sort_dist_idx(dist + pivot_idx + 1, + * if sort_results and not return_distance: # <<<<<<<<<<<<<< + * raise ValueError("return_distance must be True " + * "if sort_results is True") */ - __pyx_f_7sklearn_9neighbors_9ball_tree_sort_dist_idx(__pyx_v_dist, __pyx_v_idx, __pyx_v_pivot_idx); + if ((__pyx_v_sort_results != 0)) { + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (!__pyx_t_2); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = (__pyx_v_sort_results != 0); + } + if (__pyx_t_2) { - /* "sklearn/neighbors/ball_tree.pyx":1566 - * sort_dist_idx(dist + pivot_idx + 1, - * idx + pivot_idx + 1, - * k - pivot_idx - 1) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1424 * + * if sort_results and not return_distance: + * raise ValueError("return_distance must be True " # <<<<<<<<<<<<<< + * "if sort_results is True") * */ - __pyx_f_7sklearn_9neighbors_9ball_tree_sort_dist_idx(((__pyx_v_dist + __pyx_v_pivot_idx) + 1), ((__pyx_v_idx + __pyx_v_pivot_idx) + 1), ((__pyx_v_k - __pyx_v_pivot_idx) - 1)); - goto __pyx_L3; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__22, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L3:; - - __Pyx_RefNannyFinishContext(); -} -/* "sklearn/neighbors/ball_tree.pyx":1569 - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1427 + * "if sort_results is True") * - * cdef ITYPE_t partition_dist_idx(DTYPE_t* dist, ITYPE_t* idx, ITYPE_t k): # <<<<<<<<<<<<<< - * cdef ITYPE_t pivot_idx = k / 2 - * cdef DTYPE_t pivot_val = dist[pivot_idx] + * cdef ITYPE_t i, count_i = 0 # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef DTYPE_t[::1] dist_arr_i */ + __pyx_v_count_i = 0; -static __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_partition_dist_idx(__pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *__pyx_v_dist, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *__pyx_v_idx, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_k) { - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_pivot_idx; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_v_pivot_val; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_store_idx; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_v_i; - __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t __pyx_r; - __Pyx_RefNannyDeclarations - long __pyx_t_1; - int __pyx_t_2; - __Pyx_RefNannySetupContext("partition_dist_idx"); - - /* "sklearn/neighbors/ball_tree.pyx":1570 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1428 * - * cdef ITYPE_t partition_dist_idx(DTYPE_t* dist, ITYPE_t* idx, ITYPE_t k): - * cdef ITYPE_t pivot_idx = k / 2 # <<<<<<<<<<<<<< - * cdef DTYPE_t pivot_val = dist[pivot_idx] - * cdef ITYPE_t store_idx = 0 - */ - __pyx_v_pivot_idx = __Pyx_div_long(__pyx_v_k, 2); - - /* "sklearn/neighbors/ball_tree.pyx":1571 - * cdef ITYPE_t partition_dist_idx(DTYPE_t* dist, ITYPE_t* idx, ITYPE_t k): - * cdef ITYPE_t pivot_idx = k / 2 - * cdef DTYPE_t pivot_val = dist[pivot_idx] # <<<<<<<<<<<<<< - * cdef ITYPE_t store_idx = 0 - * cdef ITYPE_t i + * cdef ITYPE_t i, count_i = 0 + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] dist_arr_i + * cdef ITYPE_t[::1] idx_arr_i, counts */ - __pyx_v_pivot_val = (__pyx_v_dist[__pyx_v_pivot_idx]); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1428; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); - /* "sklearn/neighbors/ball_tree.pyx":1572 - * cdef ITYPE_t pivot_idx = k / 2 - * cdef DTYPE_t pivot_val = dist[pivot_idx] - * cdef ITYPE_t store_idx = 0 # <<<<<<<<<<<<<< - * cdef ITYPE_t i + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1434 * + * # validate X and prepare for query + * X = check_array(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: */ - __pyx_v_store_idx = 0; + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_check_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_6); + __pyx_t_6 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1575 - * cdef ITYPE_t i - * - * dswap(dist, pivot_idx, k - 1) # <<<<<<<<<<<<<< - * iswap(idx, pivot_idx, k - 1) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1436 + * X = check_array(X, dtype=DTYPE, order='C') * + * if X.shape[X.ndim - 1] != self.data.shape[1]: # <<<<<<<<<<<<<< + * raise ValueError("query data dimension must " + * "match training data dimension") */ - __pyx_f_7sklearn_9neighbors_9ball_tree_dswap(__pyx_v_dist, __pyx_v_pivot_idx, (__pyx_v_k - 1)); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyNumber_Subtract(__pyx_t_5, __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_GetItem(__pyx_t_6, __pyx_t_4); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_5, __pyx_t_4, Py_NE); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (__pyx_t_2) { - /* "sklearn/neighbors/ball_tree.pyx":1576 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1437 * - * dswap(dist, pivot_idx, k - 1) - * iswap(idx, pivot_idx, k - 1) # <<<<<<<<<<<<<< + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") * - * for i from 0 <= i < k - 1: */ - __pyx_f_7sklearn_9neighbors_9ball_tree_iswap(__pyx_v_idx, __pyx_v_pivot_idx, (__pyx_v_k - 1)); + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__23, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "sklearn/neighbors/ball_tree.pyx":1578 - * iswap(idx, pivot_idx, k - 1) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1441 * - * for i from 0 <= i < k - 1: # <<<<<<<<<<<<<< - * if dist[i] < pivot_val: - * dswap(dist, i, store_idx) + * cdef DTYPE_t[:, ::1] Xarr =\ + * get_memview_DTYPE_2D(X.reshape((-1, self.data.shape[1]))) # <<<<<<<<<<<<<< + * + * # prepare r for query */ - __pyx_t_1 = (__pyx_v_k - 1); - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_1; __pyx_v_i++) { + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_reshape); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_4, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_5)); if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_Xarr = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; - /* "sklearn/neighbors/ball_tree.pyx":1579 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1444 * - * for i from 0 <= i < k - 1: - * if dist[i] < pivot_val: # <<<<<<<<<<<<<< - * dswap(dist, i, store_idx) - * iswap(idx, i, store_idx) + * # prepare r for query + * r = np.asarray(r, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * r = np.atleast_1d(r) + * if r.shape == (1,): */ - __pyx_t_2 = ((__pyx_v_dist[__pyx_v_i]) < __pyx_v_pivot_val); - if (__pyx_t_2) { + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_asarray); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_r); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_r); + __Pyx_GIVEREF(__pyx_v_r); + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, __pyx_t_6); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF_SET(__pyx_v_r, __pyx_t_3); + __pyx_t_3 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1580 - * for i from 0 <= i < k - 1: - * if dist[i] < pivot_val: - * dswap(dist, i, store_idx) # <<<<<<<<<<<<<< - * iswap(idx, i, store_idx) - * store_idx += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1445 + * # prepare r for query + * r = np.asarray(r, dtype=DTYPE, order='C') + * r = np.atleast_1d(r) # <<<<<<<<<<<<<< + * if r.shape == (1,): + * r = r[0] + np.zeros(X.shape[:X.ndim - 1], dtype=DTYPE) */ - __pyx_f_7sklearn_9neighbors_9ball_tree_dswap(__pyx_v_dist, __pyx_v_i, __pyx_v_store_idx); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_atleast_1d); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_r); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_r); + __Pyx_GIVEREF(__pyx_v_r); + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_3, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_r, __pyx_t_5); + __pyx_t_5 = 0; - /* "sklearn/neighbors/ball_tree.pyx":1581 - * if dist[i] < pivot_val: - * dswap(dist, i, store_idx) - * iswap(idx, i, store_idx) # <<<<<<<<<<<<<< - * store_idx += 1 - * dswap(dist, store_idx, k - 1) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1446 + * r = np.asarray(r, dtype=DTYPE, order='C') + * r = np.atleast_1d(r) + * if r.shape == (1,): # <<<<<<<<<<<<<< + * r = r[0] + np.zeros(X.shape[:X.ndim - 1], dtype=DTYPE) + * else: */ - __pyx_f_7sklearn_9neighbors_9ball_tree_iswap(__pyx_v_idx, __pyx_v_i, __pyx_v_store_idx); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_r, __pyx_n_s_shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_tuple__24, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_2) { - /* "sklearn/neighbors/ball_tree.pyx":1582 - * dswap(dist, i, store_idx) - * iswap(idx, i, store_idx) - * store_idx += 1 # <<<<<<<<<<<<<< - * dswap(dist, store_idx, k - 1) - * iswap(idx, store_idx, k - 1) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1447 + * r = np.atleast_1d(r) + * if r.shape == (1,): + * r = r[0] + np.zeros(X.shape[:X.ndim - 1], dtype=DTYPE) # <<<<<<<<<<<<<< + * else: + * if r.shape != X.shape[:X.ndim - 1]: */ - __pyx_v_store_idx = (__pyx_v_store_idx + 1); - goto __pyx_L5; - } - __pyx_L5:; + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_r, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyNumber_Subtract(__pyx_t_4, __pyx_int_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetSlice(__pyx_t_5, 0, 0, NULL, &__pyx_t_8, NULL, 0, 0, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, __pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_Add(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF_SET(__pyx_v_r, __pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L6; } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":1583 - * iswap(idx, i, store_idx) - * store_idx += 1 - * dswap(dist, store_idx, k - 1) # <<<<<<<<<<<<<< - * iswap(idx, store_idx, k - 1) - * return store_idx - */ - __pyx_f_7sklearn_9neighbors_9ball_tree_dswap(__pyx_v_dist, __pyx_v_store_idx, (__pyx_v_k - 1)); - - /* "sklearn/neighbors/ball_tree.pyx":1584 - * store_idx += 1 - * dswap(dist, store_idx, k - 1) - * iswap(idx, store_idx, k - 1) # <<<<<<<<<<<<<< - * return store_idx - */ - __pyx_f_7sklearn_9neighbors_9ball_tree_iswap(__pyx_v_idx, __pyx_v_store_idx, (__pyx_v_k - 1)); - - /* "sklearn/neighbors/ball_tree.pyx":1585 - * dswap(dist, store_idx, k - 1) - * iswap(idx, store_idx, k - 1) - * return store_idx # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1449 + * r = r[0] + np.zeros(X.shape[:X.ndim - 1], dtype=DTYPE) + * else: + * if r.shape != X.shape[:X.ndim - 1]: # <<<<<<<<<<<<<< + * raise ValueError("r must be broadcastable to X.shape") + * */ - __pyx_r = __pyx_v_store_idx; - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_r, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = PyNumber_Subtract(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_t_5, 0, 0, NULL, &__pyx_t_8, NULL, 0, 0, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyObject_RichCompare(__pyx_t_4, __pyx_t_3, Py_NE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (__pyx_t_2) { -/* "numpy.pxd":190 - * # experimental exception made for __getbuffer__ and __releasebuffer__ - * # -- the details of this may change. - * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< - * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP. + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1450 + * else: + * if r.shape != X.shape[:X.ndim - 1]: + * raise ValueError("r must be broadcastable to X.shape") # <<<<<<<<<<<<<< + * + * rarr_np = r.reshape(-1) # store explicitly to keep in scope */ - -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_v_copy_shape; - int __pyx_v_i; - int __pyx_v_ndim; - int __pyx_v_endian_detector; - int __pyx_v_little_endian; - int __pyx_v_t; - char *__pyx_v_f; - PyArray_Descr *__pyx_v_descr = 0; - int __pyx_v_offset; - int __pyx_v_hasfields; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - char *__pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__"); - if (__pyx_v_info != NULL) { - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__25, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } } + __pyx_L6:; - /* "numpy.pxd":196 - * # of flags + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1452 + * raise ValueError("r must be broadcastable to X.shape") * - * if info == NULL: return # <<<<<<<<<<<<<< + * rarr_np = r.reshape(-1) # store explicitly to keep in scope # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) * - * cdef int copy_shape, i, ndim */ - __pyx_t_1 = (__pyx_v_info == NULL); - if (__pyx_t_1) { - __pyx_r = 0; - goto __pyx_L0; - goto __pyx_L5; - } - __pyx_L5:; + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_r, __pyx_n_s_reshape); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__26, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_rarr_np = __pyx_t_3; + __pyx_t_3 = 0; - /* "numpy.pxd":199 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1453 * - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) + * rarr_np = r.reshape(-1) # store explicitly to keep in scope + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) # <<<<<<<<<<<<<< * + * # prepare variables for iteration */ - __pyx_v_endian_detector = 1; + if (!(likely(((__pyx_v_rarr_np) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_rarr_np, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_rarr_np)); if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_rarr = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; - /* "numpy.pxd":200 - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1456 * - * ndim = PyArray_NDIM(self) + * # prepare variables for iteration + * if not count_only: # <<<<<<<<<<<<<< + * indices = np.zeros(Xarr.shape[0], dtype='object') + * if return_distance: */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + __pyx_t_2 = ((!(__pyx_v_count_only != 0)) != 0); + if (__pyx_t_2) { - /* "numpy.pxd":202 - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * - * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< - * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1457 + * # prepare variables for iteration + * if not count_only: + * indices = np.zeros(Xarr.shape[0], dtype='object') # <<<<<<<<<<<<<< + * if return_distance: + * distances = np.zeros(Xarr.shape[0], dtype='object') */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_Xarr.shape[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_n_s_object) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; - /* "numpy.pxd":204 - * ndim = PyArray_NDIM(self) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1458 + * if not count_only: + * indices = np.zeros(Xarr.shape[0], dtype='object') + * if return_distance: # <<<<<<<<<<<<<< + * distances = np.zeros(Xarr.shape[0], dtype='object') * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * copy_shape = 1 - * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); - if (__pyx_t_1) { + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1458; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { - /* "numpy.pxd":205 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1459 + * indices = np.zeros(Xarr.shape[0], dtype='object') + * if return_distance: + * distances = np.zeros(Xarr.shape[0], dtype='object') # <<<<<<<<<<<<<< * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * copy_shape = 1 # <<<<<<<<<<<<<< - * else: - * copy_shape = 0 + * np_idx_arr = np.zeros(self.data.shape[0], dtype=ITYPE) */ - __pyx_v_copy_shape = 1; - goto __pyx_L6; + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_Xarr.shape[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_n_s_object) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_distances = __pyx_t_8; + __pyx_t_8 = 0; + goto __pyx_L9; + } + __pyx_L9:; + goto __pyx_L8; } - /*else*/ { + __pyx_L8:; - /* "numpy.pxd":207 - * copy_shape = 1 - * else: - * copy_shape = 0 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1461 + * distances = np.zeros(Xarr.shape[0], dtype='object') + * + * np_idx_arr = np.zeros(self.data.shape[0], dtype=ITYPE) # <<<<<<<<<<<<<< + * idx_arr_i = get_memview_ITYPE_1D(np_idx_arr) * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ - __pyx_v_copy_shape = 0; - } - __pyx_L6:; + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_zeros); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_8 = PyInt_FromSsize_t((__pyx_v_self->data.shape[0])); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = PyDict_New(); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_8, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_8); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_np_idx_arr = __pyx_t_3; + __pyx_t_3 = 0; - /* "numpy.pxd":209 - * copy_shape = 0 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1462 * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") + * np_idx_arr = np.zeros(self.data.shape[0], dtype=ITYPE) + * idx_arr_i = get_memview_ITYPE_1D(np_idx_arr) # <<<<<<<<<<<<<< + * + * np_dist_arr = np.zeros(self.data.shape[0], dtype=DTYPE) */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); - if (__pyx_t_1) { + if (!(likely(((__pyx_v_np_idx_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_np_idx_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_v_np_idx_arr)); if (unlikely(!__pyx_t_10.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_idx_arr_i = __pyx_t_10; + __pyx_t_10.memview = NULL; + __pyx_t_10.data = NULL; - /* "numpy.pxd":210 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1464 + * idx_arr_i = get_memview_ITYPE_1D(np_idx_arr) * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not C contiguous") + * np_dist_arr = np.zeros(self.data.shape[0], dtype=DTYPE) # <<<<<<<<<<<<<< + * dist_arr_i = get_memview_DTYPE_1D(np_dist_arr) * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); - __pyx_t_3 = __pyx_t_2; - } else { - __pyx_t_3 = __pyx_t_1; - } - if (__pyx_t_3) { + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_self->data.shape[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_np_dist_arr = __pyx_t_5; + __pyx_t_5 = 0; - /* "numpy.pxd":211 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1465 * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * np_dist_arr = np.zeros(self.data.shape[0], dtype=DTYPE) + * dist_arr_i = get_memview_DTYPE_1D(np_dist_arr) # <<<<<<<<<<<<<< + * + * counts_arr = np.zeros(Xarr.shape[0], dtype=ITYPE) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_43), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; + if (!(likely(((__pyx_v_np_dist_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_np_dist_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1465; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_np_dist_arr)); if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1465; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_arr_i = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; - /* "numpy.pxd":213 - * raise ValueError(u"ndarray is not C contiguous") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1467 + * dist_arr_i = get_memview_DTYPE_1D(np_dist_arr) + * + * counts_arr = np.zeros(Xarr.shape[0], dtype=ITYPE) # <<<<<<<<<<<<<< + * counts = get_memview_ITYPE_1D(counts_arr) * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); - if (__pyx_t_3) { + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_Xarr.shape[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_counts_arr = __pyx_t_8; + __pyx_t_8 = 0; - /* "numpy.pxd":214 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1468 * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not Fortran contiguous") + * counts_arr = np.zeros(Xarr.shape[0], dtype=ITYPE) + * counts = get_memview_ITYPE_1D(counts_arr) # <<<<<<<<<<<<<< * + * pt = &Xarr[0, 0] */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); - __pyx_t_2 = __pyx_t_1; - } else { - __pyx_t_2 = __pyx_t_3; - } - if (__pyx_t_2) { + if (!(likely(((__pyx_v_counts_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_counts_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_v_counts_arr)); if (unlikely(!__pyx_t_10.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_counts = __pyx_t_10; + __pyx_t_10.memview = NULL; + __pyx_t_10.data = NULL; - /* "numpy.pxd":215 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1470 + * counts = get_memview_ITYPE_1D(counts_arr) * - * info.buf = PyArray_DATA(self) + * pt = &Xarr[0, 0] # <<<<<<<<<<<<<< + * for i in range(Xarr.shape[0]): + * counts[i] = self._query_radius_single(0, pt, rarr[i], */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_45), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; - } - __pyx_L8:; + __pyx_t_11 = 0; + __pyx_t_12 = 0; + __pyx_v_pt = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_Xarr.data + __pyx_t_11 * __pyx_v_Xarr.strides[0]) )) + __pyx_t_12)) )))); - /* "numpy.pxd":217 - * raise ValueError(u"ndarray is not Fortran contiguous") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1471 * - * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< - * info.ndim = ndim - * if copy_shape: + * pt = &Xarr[0, 0] + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * counts[i] = self._query_radius_single(0, pt, rarr[i], + * &idx_arr_i[0], */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_t_13 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_14 = 0; __pyx_t_14 < __pyx_t_13; __pyx_t_14+=1) { + __pyx_v_i = __pyx_t_14; - /* "numpy.pxd":218 - * - * info.buf = PyArray_DATA(self) - * info.ndim = ndim # <<<<<<<<<<<<<< - * if copy_shape: - * # Allocate new buffer for strides and shape info. + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1472 + * pt = &Xarr[0, 0] + * for i in range(Xarr.shape[0]): + * counts[i] = self._query_radius_single(0, pt, rarr[i], # <<<<<<<<<<<<<< + * &idx_arr_i[0], + * &dist_arr_i[0], */ - __pyx_v_info->ndim = __pyx_v_ndim; + __pyx_t_15 = __pyx_v_i; - /* "numpy.pxd":219 - * info.buf = PyArray_DATA(self) - * info.ndim = ndim - * if copy_shape: # <<<<<<<<<<<<<< - * # Allocate new buffer for strides and shape info. - * # This is allocated as one block, strides first. + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1473 + * for i in range(Xarr.shape[0]): + * counts[i] = self._query_radius_single(0, pt, rarr[i], + * &idx_arr_i[0], # <<<<<<<<<<<<<< + * &dist_arr_i[0], + * 0, count_only, */ - if (__pyx_v_copy_shape) { + __pyx_t_16 = 0; - /* "numpy.pxd":222 - * # Allocate new buffer for strides and shape info. - * # This is allocated as one block, strides first. - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< - * info.shape = info.strides + ndim - * for i in range(ndim): + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1474 + * counts[i] = self._query_radius_single(0, pt, rarr[i], + * &idx_arr_i[0], + * &dist_arr_i[0], # <<<<<<<<<<<<<< + * 0, count_only, + * return_distance) */ - __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + __pyx_t_17 = 0; - /* "numpy.pxd":223 - * # This is allocated as one block, strides first. - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) - * info.shape = info.strides + ndim # <<<<<<<<<<<<<< - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1476 + * &dist_arr_i[0], + * 0, count_only, + * return_distance) # <<<<<<<<<<<<<< + * pt += n_features + * */ - __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + __pyx_t_18 = __Pyx_PyInt_As_int(__pyx_v_return_distance); if (unlikely((__pyx_t_18 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "numpy.pxd":224 - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) - * info.shape = info.strides + ndim - * for i in range(ndim): # <<<<<<<<<<<<<< - * info.strides[i] = PyArray_STRIDES(self)[i] - * info.shape[i] = PyArray_DIMS(self)[i] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1472 + * pt = &Xarr[0, 0] + * for i in range(Xarr.shape[0]): + * counts[i] = self._query_radius_single(0, pt, rarr[i], # <<<<<<<<<<<<<< + * &idx_arr_i[0], + * &dist_arr_i[0], */ - __pyx_t_5 = __pyx_v_ndim; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; + __pyx_t_19 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_radius_single(__pyx_v_self, 0, __pyx_v_pt, (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_rarr.data) + __pyx_t_15)) ))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_idx_arr_i.data) + __pyx_t_16)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_dist_arr_i.data) + __pyx_t_17)) )))), 0, __pyx_v_count_only, __pyx_t_18); if (unlikely(__pyx_t_19 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1472; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_20 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_counts.data) + __pyx_t_20)) )) = __pyx_t_19; - /* "numpy.pxd":225 - * info.shape = info.strides + ndim - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< - * info.shape[i] = PyArray_DIMS(self)[i] - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1477 + * 0, count_only, + * return_distance) + * pt += n_features # <<<<<<<<<<<<<< + * + * if count_only: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + __pyx_v_pt = (__pyx_v_pt + __pyx_v_n_features); - /* "numpy.pxd":226 - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] - * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1479 + * pt += n_features + * + * if count_only: # <<<<<<<<<<<<<< + * pass * else: - * info.strides = PyArray_STRIDES(self) */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + __pyx_t_2 = (__pyx_v_count_only != 0); + if (__pyx_t_2) { + goto __pyx_L12; } - goto __pyx_L9; - } - /*else*/ { + /*else*/ { - /* "numpy.pxd":228 - * info.shape[i] = PyArray_DIMS(self)[i] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1482 + * pass * else: - * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL + * if sort_results: # <<<<<<<<<<<<<< + * _simultaneous_sort(&dist_arr_i[0], &idx_arr_i[0], + * counts[i]) */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_t_2 = (__pyx_v_sort_results != 0); + if (__pyx_t_2) { - /* "numpy.pxd":229 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1483 * else: - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) - */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); - } - __pyx_L9:; - - /* "numpy.pxd":230 - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * info.itemsize = PyArray_ITEMSIZE(self) - * info.readonly = not PyArray_ISWRITEABLE(self) + * if sort_results: + * _simultaneous_sort(&dist_arr_i[0], &idx_arr_i[0], # <<<<<<<<<<<<<< + * counts[i]) + * */ - __pyx_v_info->suboffsets = NULL; + __pyx_t_21 = 0; + __pyx_t_22 = 0; - /* "numpy.pxd":231 - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< - * info.readonly = not PyArray_ISWRITEABLE(self) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1484 + * if sort_results: + * _simultaneous_sort(&dist_arr_i[0], &idx_arr_i[0], + * counts[i]) # <<<<<<<<<<<<<< * + * indices[i] = np_idx_arr[:counts[i]].copy() */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_t_19 = __pyx_v_i; - /* "numpy.pxd":232 - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) - * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1483 + * else: + * if sort_results: + * _simultaneous_sort(&dist_arr_i[0], &idx_arr_i[0], # <<<<<<<<<<<<<< + * counts[i]) * - * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_t_18 = __pyx_f_7sklearn_9neighbors_9ball_tree__simultaneous_sort((&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_dist_arr_i.data) + __pyx_t_21)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_idx_arr_i.data) + __pyx_t_22)) )))), (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_counts.data) + __pyx_t_19)) )))); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L13; + } + __pyx_L13:; - /* "numpy.pxd":235 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1486 + * counts[i]) * - * cdef int t - * cdef char* f = NULL # <<<<<<<<<<<<<< - * cdef dtype descr = self.descr - * cdef list stack + * indices[i] = np_idx_arr[:counts[i]].copy() # <<<<<<<<<<<<<< + * if return_distance: + * distances[i] = np_dist_arr[:counts[i]].copy() */ - __pyx_v_f = NULL; + __pyx_t_23 = __pyx_v_i; + __pyx_t_8 = __Pyx_PyObject_GetSlice(__pyx_v_np_idx_arr, 0, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_counts.data) + __pyx_t_23)) ))), NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_copy); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_v_indices)) { __Pyx_RaiseUnboundLocalError("indices"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + if (unlikely(__Pyx_SetItemInt(__pyx_v_indices, __pyx_v_i, __pyx_t_8, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, 1, __Pyx_PyInt_From_Py_intptr_t, 0, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - /* "numpy.pxd":236 - * cdef int t - * cdef char* f = NULL - * cdef dtype descr = self.descr # <<<<<<<<<<<<<< - * cdef list stack - * cdef int offset + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1487 + * + * indices[i] = np_idx_arr[:counts[i]].copy() + * if return_distance: # <<<<<<<<<<<<<< + * distances[i] = np_dist_arr[:counts[i]].copy() + * */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { - /* "numpy.pxd":240 - * cdef int offset - * - * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1488 + * indices[i] = np_idx_arr[:counts[i]].copy() + * if return_distance: + * distances[i] = np_dist_arr[:counts[i]].copy() # <<<<<<<<<<<<<< * - * if not hasfields and not copy_shape: + * # deflatten results */ - __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + __pyx_t_24 = __pyx_v_i; + __pyx_t_8 = __Pyx_PyObject_GetSlice(__pyx_v_np_dist_arr, 0, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_counts.data) + __pyx_t_24)) ))), NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_copy); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_v_distances)) { __Pyx_RaiseUnboundLocalError("distances"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + if (unlikely(__Pyx_SetItemInt(__pyx_v_distances, __pyx_v_i, __pyx_t_8, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, 1, __Pyx_PyInt_From_Py_intptr_t, 0, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L14; + } + __pyx_L14:; + } + __pyx_L12:; + } - /* "numpy.pxd":242 - * cdef bint hasfields = PyDataType_HASFIELDS(descr) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1491 * - * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< - * # do not call releasebuffer - * info.obj = None + * # deflatten results + * if count_only: # <<<<<<<<<<<<<< + * return counts_arr.reshape(X.shape[:X.ndim - 1]) + * elif return_distance: */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = (__pyx_v_count_only != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); - __pyx_t_1 = __pyx_t_3; - } else { - __pyx_t_1 = __pyx_t_2; - } - if (__pyx_t_1) { - /* "numpy.pxd":244 - * if not hasfields and not copy_shape: - * # do not call releasebuffer - * info.obj = None # <<<<<<<<<<<<<< - * else: - * # need to call releasebuffer + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1492 + * # deflatten results + * if count_only: + * return counts_arr.reshape(X.shape[:X.ndim - 1]) # <<<<<<<<<<<<<< + * elif return_distance: + * return (indices.reshape(X.shape[:X.ndim - 1]), */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = Py_None; - goto __pyx_L12; + __Pyx_XDECREF(__pyx_r); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_counts_arr, __pyx_n_s_reshape); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_int_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetSlice(__pyx_t_5, 0, 0, NULL, &__pyx_t_3, NULL, 0, 0, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; } - /*else*/ { - /* "numpy.pxd":247 - * else: - * # need to call releasebuffer - * info.obj = self # <<<<<<<<<<<<<< - * - * if not hasfields: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1493 + * if count_only: + * return counts_arr.reshape(X.shape[:X.ndim - 1]) + * elif return_distance: # <<<<<<<<<<<<<< + * return (indices.reshape(X.shape[:X.ndim - 1]), + * distances.reshape(X.shape[:X.ndim - 1])) */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1494 + * return counts_arr.reshape(X.shape[:X.ndim - 1]) + * elif return_distance: + * return (indices.reshape(X.shape[:X.ndim - 1]), # <<<<<<<<<<<<<< + * distances.reshape(X.shape[:X.ndim - 1])) + * else: + */ + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_indices)) { __Pyx_RaiseUnboundLocalError("indices"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_indices, __pyx_n_s_reshape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = PyNumber_Subtract(__pyx_t_8, __pyx_int_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_GetSlice(__pyx_t_3, 0, 0, NULL, &__pyx_t_5, NULL, 0, 0, 0); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1495 + * elif return_distance: + * return (indices.reshape(X.shape[:X.ndim - 1]), + * distances.reshape(X.shape[:X.ndim - 1])) # <<<<<<<<<<<<<< + * else: + * return indices.reshape(X.shape[:X.ndim - 1]) + */ + if (unlikely(!__pyx_v_distances)) { __Pyx_RaiseUnboundLocalError("distances"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_distances, __pyx_n_s_reshape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = PyNumber_Subtract(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_t_4, 0, 0, NULL, &__pyx_t_6, NULL, 0, 0, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1494 + * return counts_arr.reshape(X.shape[:X.ndim - 1]) + * elif return_distance: + * return (indices.reshape(X.shape[:X.ndim - 1]), # <<<<<<<<<<<<<< + * distances.reshape(X.shape[:X.ndim - 1])) + * else: + */ + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_8 = 0; + __pyx_t_3 = 0; + __pyx_r = __pyx_t_6; + __pyx_t_6 = 0; + goto __pyx_L0; } - __pyx_L12:; + /*else*/ { - /* "numpy.pxd":249 - * info.obj = self + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1497 + * distances.reshape(X.shape[:X.ndim - 1])) + * else: + * return indices.reshape(X.shape[:X.ndim - 1]) # <<<<<<<<<<<<<< * - * if not hasfields: # <<<<<<<<<<<<<< - * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * def kernel_density(self, X, h, kernel='gaussian', */ - __pyx_t_1 = (!__pyx_v_hasfields); - if (__pyx_t_1) { + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_indices)) { __Pyx_RaiseUnboundLocalError("indices"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_indices, __pyx_n_s_reshape); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = PyNumber_Subtract(__pyx_t_8, __pyx_int_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_GetSlice(__pyx_t_3, 0, 0, NULL, &__pyx_t_5, NULL, 0, 0, 0); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_5, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_r = __pyx_t_8; + __pyx_t_8 = 0; + goto __pyx_L0; + } - /* "numpy.pxd":250 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1353 + * return indices.reshape(X.shape[:X.ndim - 1] + (k,)) * - * if not hasfields: - * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * def query_radius(self, X, r, return_distance=False, # <<<<<<<<<<<<<< + * int count_only=False, int sort_results=False): + * """ */ - __pyx_v_t = __pyx_v_descr->type_num; - /* "numpy.pxd":251 - * if not hasfields: - * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __Pyx_XDECREF(__pyx_t_8); + __PYX_XDEC_MEMVIEW(&__pyx_t_9, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_10, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.query_radius", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_dist_arr_i, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_idx_arr_i, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_counts, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Xarr, 1); + __Pyx_XDECREF(__pyx_v_rarr_np); + __PYX_XDEC_MEMVIEW(&__pyx_v_rarr, 1); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XDECREF(__pyx_v_distances); + __Pyx_XDECREF(__pyx_v_np_idx_arr); + __Pyx_XDECREF(__pyx_v_np_dist_arr); + __Pyx_XDECREF(__pyx_v_counts_arr); + __Pyx_XDECREF(__pyx_v_X); + __Pyx_XDECREF(__pyx_v_r); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1499 + * return indices.reshape(X.shape[:X.ndim - 1]) + * + * def kernel_density(self, X, h, kernel='gaussian', # <<<<<<<<<<<<<< + * atol=0, rtol=1E-8, + * breadth_first=True, return_log=False): */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); - if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; - } else { - __pyx_t_2 = __pyx_t_1; - } - if (!__pyx_t_2) { - /* "numpy.pxd":252 - * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_23kernel_density(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_22kernel_density[] = "\n kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1E-8,\n breadth_first=True, return_log=False)\n\n Compute the kernel density estimate at points X with the given kernel,\n using the distance metric specified at tree creation.\n\n Parameters\n ----------\n X : array_like\n An array of points to query. Last dimension should match dimension\n of training data.\n h : float\n the bandwidth of the kernel\n kernel : string\n specify the kernel to use. Options are\n - 'gaussian'\n - 'tophat'\n - 'epanechnikov'\n - 'exponential'\n - 'linear'\n - 'cosine'\n Default is kernel = 'gaussian'\n atol, rtol : float (default = 0)\n Specify the desired relative and absolute tolerance of the result.\n If the true result is K_true, then the returned result K_ret\n satisfies ``abs(K_true - K_ret) < atol + rtol * K_ret``\n The default is zero (i.e. machine precision) for both.\n breadth_first : boolean (default = False)\n if True, use a breadth-first search. If False (default) use a\n depth-first search. Breadth-first is generally faster for\n compact kernels and/or high tolerances.\n return_log : boolean (default = False)\n return the logarithm of the result. This can be more accurate\n than returning the result itself for narrow kernels.\n\n Returns\n -------\n density : ndarray\n The array of (log)-density evaluations, shape = X.shape[:-1]\n\n Examples\n --------\n Compute a gaussian kernel density estimate:\n\n >>> import numpy as np\n >>> np.random.seed(1)\n >>> X = np.random.random((100, 3))\n >>> tree = BinaryTree(X) # doctest: +SKIP\n >>> tree.kernel_den""sity(X[:3], h=0.1, kernel='gaussian')\n array([ 6.94114649, 7.83281226, 7.2071716 ])\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_23kernel_density(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_X = 0; + PyObject *__pyx_v_h = 0; + PyObject *__pyx_v_kernel = 0; + PyObject *__pyx_v_atol = 0; + PyObject *__pyx_v_rtol = 0; + PyObject *__pyx_v_breadth_first = 0; + PyObject *__pyx_v_return_log = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("kernel_density (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_h,&__pyx_n_s_kernel,&__pyx_n_s_atol,&__pyx_n_s_rtol,&__pyx_n_s_breadth_first,&__pyx_n_s_return_log,0}; + PyObject* values[7] = {0,0,0,0,0,0,0}; + values[2] = ((PyObject *)__pyx_n_s_gaussian); + values[3] = ((PyObject *)__pyx_int_0); + values[4] = ((PyObject *)__pyx_float_1Eneg_8); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1501 + * def kernel_density(self, X, h, kernel='gaussian', + * atol=0, rtol=1E-8, + * breadth_first=True, return_log=False): # <<<<<<<<<<<<<< + * """ + * kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1E-8, */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); - if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); - __pyx_t_7 = __pyx_t_3; - } else { - __pyx_t_7 = __pyx_t_1; + values[5] = ((PyObject *)Py_True); + values[6] = ((PyObject *)Py_False); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_h)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("kernel_density", 0, 2, 7, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1499; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kernel); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_atol); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_rtol); + if (value) { values[4] = value; kw_args--; } + } + case 5: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_breadth_first); + if (value) { values[5] = value; kw_args--; } + } + case 6: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_return_log); + if (value) { values[6] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "kernel_density") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1499; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - __pyx_t_1 = __pyx_t_7; } else { - __pyx_t_1 = __pyx_t_2; + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } } - if (__pyx_t_1) { + __pyx_v_X = values[0]; + __pyx_v_h = values[1]; + __pyx_v_kernel = values[2]; + __pyx_v_atol = values[3]; + __pyx_v_rtol = values[4]; + __pyx_v_breadth_first = values[5]; + __pyx_v_return_log = values[6]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("kernel_density", 0, 2, 7, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1499; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.kernel_density", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_22kernel_density(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self), __pyx_v_X, __pyx_v_h, __pyx_v_kernel, __pyx_v_atol, __pyx_v_rtol, __pyx_v_breadth_first, __pyx_v_return_log); - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1499 + * return indices.reshape(X.shape[:X.ndim - 1]) + * + * def kernel_density(self, X, h, kernel='gaussian', # <<<<<<<<<<<<<< + * atol=0, rtol=1E-8, + * breadth_first=True, return_log=False): */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_47), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; - } - __pyx_L14:; - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" - */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__b; - goto __pyx_L15; - } + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "numpy.pxd":255 - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_22kernel_density(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_h, PyObject *__pyx_v_kernel, PyObject *__pyx_v_atol, PyObject *__pyx_v_rtol, PyObject *__pyx_v_breadth_first, PyObject *__pyx_v_return_log) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h_c; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_atol; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_rtol; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_min_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_max_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_bound_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_samples; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType __pyx_v_kernel_c; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_knorm; + PyObject *__pyx_v_Xarr_np = NULL; + __Pyx_memviewslice __pyx_v_Xarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_log_density_arr = NULL; + __Pyx_memviewslice __pyx_v_log_density = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt; + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_nodeheap = 0; + __Pyx_memviewslice __pyx_v_node_log_min_bounds = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_node_bound_widths = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_node_log_min_bounds_arr = NULL; + PyObject *__pyx_v_node_bound_widths_arr = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_1; + double __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + __Pyx_memviewslice __pyx_t_8 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_9 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + Py_ssize_t __pyx_t_14; + Py_ssize_t __pyx_t_15; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_16; + int __pyx_t_17; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_18; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_19; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("kernel_density", 0); + __Pyx_INCREF(__pyx_v_X); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1554 + * array([ 6.94114649, 7.83281226, 7.2071716 ]) + * """ + * cdef DTYPE_t h_c = h # <<<<<<<<<<<<<< + * cdef DTYPE_t log_atol = log(atol) + * cdef DTYPE_t log_rtol = log(rtol) */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__B; - goto __pyx_L15; - } + __pyx_t_1 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_1 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_h_c = __pyx_t_1; - /* "numpy.pxd":256 - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1555 + * """ + * cdef DTYPE_t h_c = h + * cdef DTYPE_t log_atol = log(atol) # <<<<<<<<<<<<<< + * cdef DTYPE_t log_rtol = log(rtol) + * cdef DTYPE_t log_min_bound, log_max_bound, log_bound_spread */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__h; - goto __pyx_L15; - } + __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_v_atol); if (unlikely((__pyx_t_2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1555; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_log_atol = log(__pyx_t_2); - /* "numpy.pxd":257 - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1556 + * cdef DTYPE_t h_c = h + * cdef DTYPE_t log_atol = log(atol) + * cdef DTYPE_t log_rtol = log(rtol) # <<<<<<<<<<<<<< + * cdef DTYPE_t log_min_bound, log_max_bound, log_bound_spread + * cdef DTYPE_t dist_LB = 0, dist_UB = 0 */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__H; - goto __pyx_L15; - } + __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_v_rtol); if (unlikely((__pyx_t_2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1556; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_log_rtol = log(__pyx_t_2); - /* "numpy.pxd":258 - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1558 + * cdef DTYPE_t log_rtol = log(rtol) + * cdef DTYPE_t log_min_bound, log_max_bound, log_bound_spread + * cdef DTYPE_t dist_LB = 0, dist_UB = 0 # <<<<<<<<<<<<<< + * + * cdef ITYPE_t n_samples = self.data.shape[0] */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__i; - goto __pyx_L15; - } + __pyx_v_dist_LB = 0.0; + __pyx_v_dist_UB = 0.0; - /* "numpy.pxd":259 - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1560 + * cdef DTYPE_t dist_LB = 0, dist_UB = 0 + * + * cdef ITYPE_t n_samples = self.data.shape[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef ITYPE_t i */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__I; - goto __pyx_L15; - } + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1560; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_samples = (__pyx_v_self->data.shape[0]); - /* "numpy.pxd":260 - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1561 + * + * cdef ITYPE_t n_samples = self.data.shape[0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef ITYPE_t i + * cdef KernelType kernel_c */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__l; - goto __pyx_L15; - } + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1561; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); - /* "numpy.pxd":261 - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" - */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__L; - goto __pyx_L15; - } - - /* "numpy.pxd":262 - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1566 + * + * # validate kernel + * if kernel == 'gaussian': # <<<<<<<<<<<<<< + * kernel_c = GAUSSIAN_KERNEL + * elif kernel == 'tophat': */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__q; - goto __pyx_L15; - } + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_gaussian, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { - /* "numpy.pxd":263 - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1567 + * # validate kernel + * if kernel == 'gaussian': + * kernel_c = GAUSSIAN_KERNEL # <<<<<<<<<<<<<< + * elif kernel == 'tophat': + * kernel_c = TOPHAT_KERNEL */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; - } + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_9ball_tree_GAUSSIAN_KERNEL; + goto __pyx_L3; + } - /* "numpy.pxd":264 - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1568 + * if kernel == 'gaussian': + * kernel_c = GAUSSIAN_KERNEL + * elif kernel == 'tophat': # <<<<<<<<<<<<<< + * kernel_c = TOPHAT_KERNEL + * elif kernel == 'epanechnikov': */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__f; - goto __pyx_L15; - } + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_tophat, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { - /* "numpy.pxd":265 - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1569 + * kernel_c = GAUSSIAN_KERNEL + * elif kernel == 'tophat': + * kernel_c = TOPHAT_KERNEL # <<<<<<<<<<<<<< + * elif kernel == 'epanechnikov': + * kernel_c = EPANECHNIKOV_KERNEL */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__d; - goto __pyx_L15; - } + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_9ball_tree_TOPHAT_KERNEL; + goto __pyx_L3; + } - /* "numpy.pxd":266 - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1570 + * elif kernel == 'tophat': + * kernel_c = TOPHAT_KERNEL + * elif kernel == 'epanechnikov': # <<<<<<<<<<<<<< + * kernel_c = EPANECHNIKOV_KERNEL + * elif kernel == 'exponential': */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__g; - goto __pyx_L15; - } + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_epanechnikov, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { - /* "numpy.pxd":267 - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1571 + * kernel_c = TOPHAT_KERNEL + * elif kernel == 'epanechnikov': + * kernel_c = EPANECHNIKOV_KERNEL # <<<<<<<<<<<<<< + * elif kernel == 'exponential': + * kernel_c = EXPONENTIAL_KERNEL */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; - } + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_9ball_tree_EPANECHNIKOV_KERNEL; + goto __pyx_L3; + } - /* "numpy.pxd":268 - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< - * elif t == NPY_CLONGDOUBLE: f = "Zg" - * elif t == NPY_OBJECT: f = "O" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1572 + * elif kernel == 'epanechnikov': + * kernel_c = EPANECHNIKOV_KERNEL + * elif kernel == 'exponential': # <<<<<<<<<<<<<< + * kernel_c = EXPONENTIAL_KERNEL + * elif kernel == 'linear': */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; - } + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_exponential, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { - /* "numpy.pxd":269 - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< - * elif t == NPY_OBJECT: f = "O" - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1573 + * kernel_c = EPANECHNIKOV_KERNEL + * elif kernel == 'exponential': + * kernel_c = EXPONENTIAL_KERNEL # <<<<<<<<<<<<<< + * elif kernel == 'linear': + * kernel_c = LINEAR_KERNEL */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; - } + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_9ball_tree_EXPONENTIAL_KERNEL; + goto __pyx_L3; + } - /* "numpy.pxd":270 - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" - * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1574 + * elif kernel == 'exponential': + * kernel_c = EXPONENTIAL_KERNEL + * elif kernel == 'linear': # <<<<<<<<<<<<<< + * kernel_c = LINEAR_KERNEL + * elif kernel == 'cosine': */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L15; - } - /*else*/ { + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_linear, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { - /* "numpy.pxd":272 - * elif t == NPY_OBJECT: f = "O" - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< - * info.format = f - * return + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1575 + * kernel_c = EXPONENTIAL_KERNEL + * elif kernel == 'linear': + * kernel_c = LINEAR_KERNEL # <<<<<<<<<<<<<< + * elif kernel == 'cosine': + * kernel_c = COSINE_KERNEL */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_48), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); - __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L15:; + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_9ball_tree_LINEAR_KERNEL; + goto __pyx_L3; + } - /* "numpy.pxd":273 - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * info.format = f # <<<<<<<<<<<<<< - * return - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1576 + * elif kernel == 'linear': + * kernel_c = LINEAR_KERNEL + * elif kernel == 'cosine': # <<<<<<<<<<<<<< + * kernel_c = COSINE_KERNEL + * else: */ - __pyx_v_info->format = __pyx_v_f; + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_cosine, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { - /* "numpy.pxd":274 - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * info.format = f - * return # <<<<<<<<<<<<<< - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1577 + * kernel_c = LINEAR_KERNEL + * elif kernel == 'cosine': + * kernel_c = COSINE_KERNEL # <<<<<<<<<<<<<< + * else: + * raise ValueError("kernel = '%s' not recognized" % kernel) */ - __pyx_r = 0; - goto __pyx_L0; - goto __pyx_L13; + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_9ball_tree_COSINE_KERNEL; + goto __pyx_L3; } /*else*/ { - /* "numpy.pxd":276 - * return - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment - * offset = 0 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1579 + * kernel_c = COSINE_KERNEL + * else: + * raise ValueError("kernel = '%s' not recognized" % kernel) # <<<<<<<<<<<<<< + * + * cdef DTYPE_t log_knorm = _log_kernel_norm(h_c, n_features, kernel_c) */ - __pyx_v_info->format = ((char *)malloc(255)); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_kernel_s_not_recognized, __pyx_v_kernel); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; - /* "numpy.pxd":277 - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< - * offset = 0 - * f = _util_dtypestring(descr, info.format + 1, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1581 + * raise ValueError("kernel = '%s' not recognized" % kernel) + * + * cdef DTYPE_t log_knorm = _log_kernel_norm(h_c, n_features, kernel_c) # <<<<<<<<<<<<<< + * + * # validate X and prepare for query */ - (__pyx_v_info->format[0]) = '^'; + __pyx_t_1 = __pyx_f_7sklearn_9neighbors_9ball_tree__log_kernel_norm(__pyx_v_h_c, __pyx_v_n_features, __pyx_v_kernel_c); if (unlikely(__pyx_t_1 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1581; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_log_knorm = __pyx_t_1; - /* "numpy.pxd":278 - * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment - * offset = 0 # <<<<<<<<<<<<<< - * f = _util_dtypestring(descr, info.format + 1, - * info.format + _buffer_format_string_len, + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1584 + * + * # validate X and prepare for query + * X = check_array(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * + * if X.shape[X.ndim - 1] != n_features: */ - __pyx_v_offset = 0; + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_check_array); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, __pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_7); + __pyx_t_7 = 0; - /* "numpy.pxd":281 - * f = _util_dtypestring(descr, info.format + 1, - * info.format + _buffer_format_string_len, - * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1586 + * X = check_array(X, dtype=DTYPE, order='C') * + * if X.shape[X.ndim - 1] != n_features: # <<<<<<<<<<<<<< + * raise ValueError("query data dimension must " + * "match training data dimension") */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_9; + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = PyNumber_Subtract(__pyx_t_6, __pyx_int_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyObject_GetItem(__pyx_t_7, __pyx_t_5); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_features); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = PyObject_RichCompare(__pyx_t_6, __pyx_t_5, Py_NE); __Pyx_XGOTREF(__pyx_t_7); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (__pyx_t_3) { - /* "numpy.pxd":282 - * info.format + _buffer_format_string_len, - * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1587 * - * def __releasebuffer__(ndarray self, Py_buffer* info): + * if X.shape[X.ndim - 1] != n_features: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * Xarr_np = X.reshape((-1, n_features)) */ - (__pyx_v_f[0]) = 0; - } - __pyx_L13:; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; - } - goto __pyx_L2; - __pyx_L0:; - if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { - __Pyx_GOTREF(Py_None); - __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__27, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1587; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_Raise(__pyx_t_7, 0, 0, 0); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1587; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_descr); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1589 + * raise ValueError("query data dimension must " + * "match training data dimension") + * Xarr_np = X.reshape((-1, n_features)) # <<<<<<<<<<<<<< + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(Xarr_np) * - * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_reshape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_features); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_INCREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_5, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_Xarr_np = __pyx_t_6; + __pyx_t_6 = 0; -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__"); - - /* "numpy.pxd":285 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1590 + * "match training data dimension") + * Xarr_np = X.reshape((-1, n_features)) + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(Xarr_np) # <<<<<<<<<<<<<< * - * def __releasebuffer__(ndarray self, Py_buffer* info): - * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< - * stdlib.free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * log_density_arr = np.zeros(Xarr.shape[0], dtype=DTYPE) */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); - if (__pyx_t_1) { + if (!(likely(((__pyx_v_Xarr_np) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_Xarr_np, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_v_Xarr_np)); if (unlikely(!__pyx_t_8.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_Xarr = __pyx_t_8; + __pyx_t_8.memview = NULL; + __pyx_t_8.data = NULL; - /* "numpy.pxd":286 - * def __releasebuffer__(ndarray self, Py_buffer* info): - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) # <<<<<<<<<<<<<< - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * stdlib.free(info.strides) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1592 + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(Xarr_np) + * + * log_density_arr = np.zeros(Xarr.shape[0], dtype=DTYPE) # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] log_density = get_memview_DTYPE_1D(log_density_arr) + * */ - free(__pyx_v_info->format); - goto __pyx_L5; - } - __pyx_L5:; - - /* "numpy.pxd":287 - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * stdlib.free(info.strides) - * # info.shape was stored after info.strides in the same block - */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); - if (__pyx_t_1) { + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_zeros); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyInt_FromSsize_t((__pyx_v_Xarr.shape[0])); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_7, __pyx_t_6); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_log_density_arr = __pyx_t_4; + __pyx_t_4 = 0; - /* "numpy.pxd":288 - * stdlib.free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * stdlib.free(info.strides) # <<<<<<<<<<<<<< - * # info.shape was stored after info.strides in the same block + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1593 * + * log_density_arr = np.zeros(Xarr.shape[0], dtype=DTYPE) + * cdef DTYPE_t[::1] log_density = get_memview_DTYPE_1D(log_density_arr) # <<<<<<<<<<<<<< + * + * cdef DTYPE_t* pt = &Xarr[0, 0] */ - free(__pyx_v_info->strides); - goto __pyx_L6; - } - __pyx_L6:; - - __Pyx_RefNannyFinishContext(); -} + if (!(likely(((__pyx_v_log_density_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_log_density_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_log_density_arr)); if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_log_density = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; -/* "numpy.pxd":764 - * ctypedef npy_cdouble complex_t + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1595 + * cdef DTYPE_t[::1] log_density = get_memview_DTYPE_1D(log_density_arr) * - * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(1, a) + * cdef DTYPE_t* pt = &Xarr[0, 0] # <<<<<<<<<<<<<< * + * cdef NodeHeap nodeheap */ + __pyx_t_10 = 0; + __pyx_t_11 = 0; + __pyx_v_pt = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_Xarr.data + __pyx_t_10 * __pyx_v_Xarr.strides[0]) )) + __pyx_t_11)) )))); -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); - - /* "numpy.pxd":765 - * - * cdef inline object PyArray_MultiIterNew1(a): - * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1598 * - * cdef inline object PyArray_MultiIterNew2(a, b): + * cdef NodeHeap nodeheap + * if breadth_first: # <<<<<<<<<<<<<< + * nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) + * cdef DTYPE_t[::1] node_log_min_bounds */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_breadth_first); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1599 + * cdef NodeHeap nodeheap + * if breadth_first: + * nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] node_log_min_bounds + * cdef DTYPE_t[::1] node_bound_widths + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = PyInt_FromSsize_t(((__pyx_v_self->data.shape[0]) / __pyx_v_self->leaf_size)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_9ball_tree_NodeHeap)), __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_nodeheap = ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L5; + } + __pyx_L5:; -/* "numpy.pxd":767 - * return PyArray_MultiIterNew(1, a) - * - * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(2, a, b) - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1605 + * # this is difficult because of the need to cache values + * # computed between node pairs. + * if breadth_first: # <<<<<<<<<<<<<< + * node_log_min_bounds_arr = -np.inf + np.zeros(self.n_nodes) + * node_log_min_bounds = get_memview_DTYPE_1D(node_log_min_bounds_arr) */ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_breadth_first); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1605; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1606 + * # computed between node pairs. + * if breadth_first: + * node_log_min_bounds_arr = -np.inf + np.zeros(self.n_nodes) # <<<<<<<<<<<<<< + * node_log_min_bounds = get_memview_DTYPE_1D(node_log_min_bounds_arr) + * node_bound_widths_arr = np.zeros(self.n_nodes) + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_inf); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_Negative(__pyx_t_6); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_zeros); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_nodes); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_5, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyNumber_Add(__pyx_t_4, __pyx_t_6); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_node_log_min_bounds_arr = __pyx_t_5; + __pyx_t_5 = 0; - /* "numpy.pxd":768 - * - * cdef inline object PyArray_MultiIterNew2(a, b): - * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1607 + * if breadth_first: + * node_log_min_bounds_arr = -np.inf + np.zeros(self.n_nodes) + * node_log_min_bounds = get_memview_DTYPE_1D(node_log_min_bounds_arr) # <<<<<<<<<<<<<< + * node_bound_widths_arr = np.zeros(self.n_nodes) + * node_bound_widths = get_memview_DTYPE_1D(node_bound_widths_arr) + */ + if (!(likely(((__pyx_v_node_log_min_bounds_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_node_log_min_bounds_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1607; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_node_log_min_bounds_arr)); if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1607; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_node_log_min_bounds = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1608 + * node_log_min_bounds_arr = -np.inf + np.zeros(self.n_nodes) + * node_log_min_bounds = get_memview_DTYPE_1D(node_log_min_bounds_arr) + * node_bound_widths_arr = np.zeros(self.n_nodes) # <<<<<<<<<<<<<< + * node_bound_widths = get_memview_DTYPE_1D(node_bound_widths_arr) + * for i in range(Xarr.shape[0]): + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_nodes); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_4, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_node_bound_widths_arr = __pyx_t_5; + __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1609 + * node_log_min_bounds = get_memview_DTYPE_1D(node_log_min_bounds_arr) + * node_bound_widths_arr = np.zeros(self.n_nodes) + * node_bound_widths = get_memview_DTYPE_1D(node_bound_widths_arr) # <<<<<<<<<<<<<< + * for i in range(Xarr.shape[0]): + * log_density[i] = self._kde_single_breadthfirst( + */ + if (!(likely(((__pyx_v_node_bound_widths_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_node_bound_widths_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_node_bound_widths_arr)); if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_node_bound_widths = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1610 + * node_bound_widths_arr = np.zeros(self.n_nodes) + * node_bound_widths = get_memview_DTYPE_1D(node_bound_widths_arr) + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * log_density[i] = self._kde_single_breadthfirst( + * pt, kernel_c, h_c, + */ + __pyx_t_12 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1614 + * pt, kernel_c, h_c, + * log_knorm, log_atol, log_rtol, + * nodeheap, # <<<<<<<<<<<<<< + * &node_log_min_bounds[0], + * &node_bound_widths[0]) + */ + if (unlikely(!__pyx_v_nodeheap)) { __Pyx_RaiseUnboundLocalError("nodeheap"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1615 + * log_knorm, log_atol, log_rtol, + * nodeheap, + * &node_log_min_bounds[0], # <<<<<<<<<<<<<< + * &node_bound_widths[0]) + * pt += n_features + */ + __pyx_t_14 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1616 + * nodeheap, + * &node_log_min_bounds[0], + * &node_bound_widths[0]) # <<<<<<<<<<<<<< + * pt += n_features + * else: */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_t_15 = 0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1611 + * node_bound_widths = get_memview_DTYPE_1D(node_bound_widths_arr) + * for i in range(Xarr.shape[0]): + * log_density[i] = self._kde_single_breadthfirst( # <<<<<<<<<<<<<< + * pt, kernel_c, h_c, + * log_knorm, log_atol, log_rtol, + */ + __pyx_t_16 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_log_density.data) + __pyx_t_16)) )) = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_kde_single_breadthfirst(__pyx_v_self, __pyx_v_pt, __pyx_v_kernel_c, __pyx_v_h_c, __pyx_v_log_knorm, __pyx_v_log_atol, __pyx_v_log_rtol, __pyx_v_nodeheap, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_node_log_min_bounds.data) + __pyx_t_14)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_node_bound_widths.data) + __pyx_t_15)) ))))); -/* "numpy.pxd":770 - * return PyArray_MultiIterNew(2, a, b) - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(3, a, b, c) - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1617 + * &node_log_min_bounds[0], + * &node_bound_widths[0]) + * pt += n_features # <<<<<<<<<<<<<< + * else: + * for i in range(Xarr.shape[0]): */ + __pyx_v_pt = (__pyx_v_pt + __pyx_v_n_features); + } + goto __pyx_L6; + } + /*else*/ { -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1619 + * pt += n_features + * else: + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * min_max_dist(self, 0, pt, &dist_LB, &dist_UB) + * # compute max & min bounds on density within top node + */ + __pyx_t_12 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1620 + * else: + * for i in range(Xarr.shape[0]): + * min_max_dist(self, 0, pt, &dist_LB, &dist_UB) # <<<<<<<<<<<<<< + * # compute max & min bounds on density within top node + * log_min_bound = (log(n_samples) + + */ + __pyx_t_17 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_max_dist(__pyx_v_self, 0, __pyx_v_pt, (&__pyx_v_dist_LB), (&__pyx_v_dist_UB)); if (unlikely(__pyx_t_17 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1620; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1622 + * min_max_dist(self, 0, pt, &dist_LB, &dist_UB) + * # compute max & min bounds on density within top node + * log_min_bound = (log(n_samples) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_UB, + * h_c, kernel_c)) + */ + __pyx_v_log_min_bound = (log(__pyx_v_n_samples) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_UB, __pyx_v_h_c, __pyx_v_kernel_c)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1625 + * compute_log_kernel(dist_UB, + * h_c, kernel_c)) + * log_max_bound = (log(n_samples) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_LB, + * h_c, kernel_c)) + */ + __pyx_v_log_max_bound = (log(__pyx_v_n_samples) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_LB, __pyx_v_h_c, __pyx_v_kernel_c)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1628 + * compute_log_kernel(dist_LB, + * h_c, kernel_c)) + * log_bound_spread = logsubexp(log_max_bound, log_min_bound) # <<<<<<<<<<<<<< + * self._kde_single_depthfirst(0, pt, kernel_c, h_c, + * log_knorm, log_atol, log_rtol, + */ + __pyx_v_log_bound_spread = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp(__pyx_v_log_max_bound, __pyx_v_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1629 + * h_c, kernel_c)) + * log_bound_spread = logsubexp(log_max_bound, log_min_bound) + * self._kde_single_depthfirst(0, pt, kernel_c, h_c, # <<<<<<<<<<<<<< + * log_knorm, log_atol, log_rtol, + * log_min_bound, + */ + __pyx_t_17 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_kde_single_depthfirst(__pyx_v_self, 0, __pyx_v_pt, __pyx_v_kernel_c, __pyx_v_h_c, __pyx_v_log_knorm, __pyx_v_log_atol, __pyx_v_log_rtol, __pyx_v_log_min_bound, __pyx_v_log_bound_spread, (&__pyx_v_log_min_bound), (&__pyx_v_log_bound_spread)); if (unlikely(__pyx_t_17 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1629; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1635 + * &log_min_bound, + * &log_bound_spread) + * log_density[i] = logaddexp(log_min_bound, # <<<<<<<<<<<<<< + * log_bound_spread - log(2)) + * pt += n_features + */ + __pyx_t_18 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_log_density.data) + __pyx_t_18)) )) = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_v_log_min_bound, (__pyx_v_log_bound_spread - log(2.0))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1637 + * log_density[i] = logaddexp(log_min_bound, + * log_bound_spread - log(2)) + * pt += n_features # <<<<<<<<<<<<<< + * + * # normalize the results + */ + __pyx_v_pt = (__pyx_v_pt + __pyx_v_n_features); + } + } + __pyx_L6:; - /* "numpy.pxd":771 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1640 * - * cdef inline object PyArray_MultiIterNew3(a, b, c): - * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * # normalize the results + * for i in range(log_density.shape[0]): # <<<<<<<<<<<<<< + * log_density[i] += log_knorm * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_t_12 = (__pyx_v_log_density.shape[0]); + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1641 + * # normalize the results + * for i in range(log_density.shape[0]): + * log_density[i] += log_knorm # <<<<<<<<<<<<<< + * + * log_density_arr = log_density_arr.reshape(X.shape[:X.ndim - 1]) + */ + __pyx_t_19 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_log_density.data) + __pyx_t_19)) )) += __pyx_v_log_knorm; + } -/* "numpy.pxd":773 - * return PyArray_MultiIterNew(3, a, b, c) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1643 + * log_density[i] += log_knorm * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(4, a, b, c, d) + * log_density_arr = log_density_arr.reshape(X.shape[:X.ndim - 1]) # <<<<<<<<<<<<<< + * + * if return_log: + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_log_density_arr, __pyx_n_s_reshape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyNumber_Subtract(__pyx_t_6, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_GetSlice(__pyx_t_4, 0, 0, NULL, &__pyx_t_7, NULL, 0, 0, 0); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF_SET(__pyx_v_log_density_arr, __pyx_t_6); + __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1645 + * log_density_arr = log_density_arr.reshape(X.shape[:X.ndim - 1]) * + * if return_log: # <<<<<<<<<<<<<< + * return log_density_arr + * else: */ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_return_log); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1646 + * + * if return_log: + * return log_density_arr # <<<<<<<<<<<<<< + * else: + * return np.exp(log_density_arr) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_log_density_arr); + __pyx_r = __pyx_v_log_density_arr; + goto __pyx_L0; + } + /*else*/ { - /* "numpy.pxd":774 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1648 + * return log_density_arr + * else: + * return np.exp(log_density_arr) # <<<<<<<<<<<<<< * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): - * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * def two_point_correlation(self, X, r, dualtree=False): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_exp); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_INCREF(__pyx_v_log_density_arr); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_v_log_density_arr); + __Pyx_GIVEREF(__pyx_v_log_density_arr); + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1499 + * return indices.reshape(X.shape[:X.ndim - 1]) * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * def kernel_density(self, X, h, kernel='gaussian', # <<<<<<<<<<<<<< + * atol=0, rtol=1E-8, + * breadth_first=True, return_log=False): */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __PYX_XDEC_MEMVIEW(&__pyx_t_8, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_9, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.kernel_density", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; __pyx_L0:; + __Pyx_XDECREF(__pyx_v_Xarr_np); + __PYX_XDEC_MEMVIEW(&__pyx_v_Xarr, 1); + __Pyx_XDECREF(__pyx_v_log_density_arr); + __PYX_XDEC_MEMVIEW(&__pyx_v_log_density, 1); + __Pyx_XDECREF((PyObject *)__pyx_v_nodeheap); + __PYX_XDEC_MEMVIEW(&__pyx_v_node_log_min_bounds, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_node_bound_widths, 1); + __Pyx_XDECREF(__pyx_v_node_log_min_bounds_arr); + __Pyx_XDECREF(__pyx_v_node_bound_widths_arr); + __Pyx_XDECREF(__pyx_v_X); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":776 - * return PyArray_MultiIterNew(4, a, b, c, d) +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1650 + * return np.exp(log_density_arr) * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(5, a, b, c, d, e) + * def two_point_correlation(self, X, r, dualtree=False): # <<<<<<<<<<<<<< + * """Compute the two-point correlation function * */ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_25two_point_correlation(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_24two_point_correlation[] = "Compute the two-point correlation function\n\n Parameters\n ----------\n X : array_like\n An array of points to query. Last dimension should match dimension\n of training data.\n r : array_like\n A one-dimensional array of distances\n dualtree : boolean (default = False)\n If true, use a dualtree algorithm. Otherwise, use a single-tree\n algorithm. Dual tree algorithms can have better scaling for\n large N.\n\n Returns\n -------\n counts : ndarray\n counts[i] contains the number of pairs of points with distance\n less than or equal to r[i]\n\n Examples\n --------\n Compute the two-point autocorrelation function of X:\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((30, 3))\n >>> r = np.linspace(0, 1, 5)\n >>> tree = BinaryTree(X) # doctest: +SKIP\n >>> tree.two_point_correlation(X, r)\n array([ 30, 62, 278, 580, 820])\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_25two_point_correlation(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_X = 0; + PyObject *__pyx_v_r = 0; + PyObject *__pyx_v_dualtree = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); - - /* "numpy.pxd":777 - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): - * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< - * - * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("two_point_correlation (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_r,&__pyx_n_s_dualtree,0}; + PyObject* values[3] = {0,0,0}; + values[2] = ((PyObject *)Py_False); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_r)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("two_point_correlation", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1650; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dualtree); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "two_point_correlation") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1650; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_X = values[0]; + __pyx_v_r = values[1]; + __pyx_v_dualtree = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("two_point_correlation", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1650; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.two_point_correlation", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_24two_point_correlation(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self), __pyx_v_X, __pyx_v_r, __pyx_v_dualtree); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":779 - * return PyArray_MultiIterNew(5, a, b, c, d, e) - * - * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< - * # Recursive utility function used in __getbuffer__ to get format - * # string. The new location in the format string is returned. - */ - -static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { - PyArray_Descr *__pyx_v_child = 0; - int __pyx_v_endian_detector; - int __pyx_v_little_endian; - PyObject *__pyx_v_fields = 0; - PyObject *__pyx_v_childname = NULL; - PyObject *__pyx_v_new_offset = NULL; - PyObject *__pyx_v_t = NULL; - char *__pyx_r; +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_24two_point_correlation(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_r, PyObject *__pyx_v_dualtree) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + PyObject *__pyx_v_np_Xarr = NULL; + __Pyx_memviewslice __pyx_v_Xarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_i_rsort = NULL; + PyObject *__pyx_v_rarr_np = NULL; + __Pyx_memviewslice __pyx_v_rarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_count = NULL; + __Pyx_memviewslice __pyx_v_carr = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt; + PyObject *__pyx_v_other = NULL; + PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; + int __pyx_t_5; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_8 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + int __pyx_t_13; + Py_ssize_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + Py_ssize_t __pyx_t_16; + Py_ssize_t __pyx_t_17; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring"); - - /* "numpy.pxd":786 - * cdef int delta_offset - * cdef tuple i - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * cdef tuple fields - */ - __pyx_v_endian_detector = 1; - - /* "numpy.pxd":787 - * cdef tuple i - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< - * cdef tuple fields - * - */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + __Pyx_RefNannySetupContext("two_point_correlation", 0); + __Pyx_INCREF(__pyx_v_X); + __Pyx_INCREF(__pyx_v_r); - /* "numpy.pxd":790 - * cdef tuple fields + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1683 + * array([ 30, 62, 278, 580, 820]) + * """ + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef ITYPE_t i * - * for childname in descr.names: # <<<<<<<<<<<<<< - * fields = descr.fields[childname] - * child, new_offset = fields */ - if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; - __pyx_t_3 = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1683; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); - /* "numpy.pxd":791 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1687 * - * for childname in descr.names: - * fields = descr.fields[childname] # <<<<<<<<<<<<<< - * child, new_offset = fields + * # validate X and prepare for query + * X = check_array(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< * + * if X.shape[X.ndim - 1] != self.data.shape[1]: */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_check_array); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":792 - * for childname in descr.names: - * fields = descr.fields[childname] - * child, new_offset = fields # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1689 + * X = check_array(X, dtype=DTYPE, order='C') * - * if (end - f) - (new_offset - offset[0]) < 15: + * if X.shape[X.ndim - 1] != self.data.shape[1]: # <<<<<<<<<<<<<< + * raise ValueError("query data dimension must " + * "match training data dimension") */ - if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { - PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); - __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; - __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyNumber_Subtract(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_GetItem(__pyx_t_4, __pyx_t_2); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_t_2, Py_NE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_5) { - /* "numpy.pxd":794 - * child, new_offset = fields + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1690 * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__28, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1690; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1690; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "numpy.pxd":795 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1693 + * "match training data dimension") * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * np_Xarr = X.reshape((-1, self.data.shape[1])) # <<<<<<<<<<<<<< + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(np_Xarr) * - * if ((child.byteorder == '>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_50), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_reshape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_np_Xarr = __pyx_t_3; + __pyx_t_3 = 0; - /* "numpy.pxd":797 - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1694 * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; - } else { - __pyx_t_7 = __pyx_t_6; - } - if (!__pyx_t_7) { - - /* "numpy.pxd":798 + * np_Xarr = X.reshape((-1, self.data.shape[1])) + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(np_Xarr) # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< - * raise ValueError(u"Non-native byte order not supported") - * # One could encode it in the format string and have Cython + * # prepare r for query */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; - } else { - __pyx_t_9 = __pyx_t_6; - } - __pyx_t_6 = __pyx_t_9; - } else { - __pyx_t_6 = __pyx_t_7; - } - if (__pyx_t_6) { + if (!(likely(((__pyx_v_np_Xarr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_np_Xarr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1694; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_v_np_Xarr)); if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1694; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_Xarr = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * # One could encode it in the format string and have Cython - * # complain instead, BUT: < and > in format strings also imply + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1697 + * + * # prepare r for query + * r = np.asarray(r, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * r = np.atleast_1d(r) + * if r.ndim != 1: */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_51), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_r); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_r); + __Pyx_GIVEREF(__pyx_v_r); + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF_SET(__pyx_v_r, __pyx_t_1); + __pyx_t_1 = 0; - /* "numpy.pxd":809 - * - * # Output padding bytes - * while offset[0] < new_offset: # <<<<<<<<<<<<<< - * f[0] = 120 # "x"; pad byte - * f += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1698 + * # prepare r for query + * r = np.asarray(r, dtype=DTYPE, order='C') + * r = np.atleast_1d(r) # <<<<<<<<<<<<<< + * if r.ndim != 1: + * raise ValueError("r must be a 1-dimensional array") */ - while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!__pyx_t_6) break; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_atleast_1d); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_r); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_r); + __Pyx_GIVEREF(__pyx_v_r); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_1, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF_SET(__pyx_v_r, __pyx_t_3); + __pyx_t_3 = 0; - /* "numpy.pxd":810 - * # Output padding bytes - * while offset[0] < new_offset: - * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< - * f += 1 - * offset[0] += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1699 + * r = np.asarray(r, dtype=DTYPE, order='C') + * r = np.atleast_1d(r) + * if r.ndim != 1: # <<<<<<<<<<<<<< + * raise ValueError("r must be a 1-dimensional array") + * i_rsort = np.argsort(r) */ - (__pyx_v_f[0]) = 120; + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_r, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyObject_RichCompare(__pyx_t_3, __pyx_int_1, Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_5) { - /* "numpy.pxd":811 - * while offset[0] < new_offset: - * f[0] = 120 # "x"; pad byte - * f += 1 # <<<<<<<<<<<<<< - * offset[0] += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1700 + * r = np.atleast_1d(r) + * if r.ndim != 1: + * raise ValueError("r must be a 1-dimensional array") # <<<<<<<<<<<<<< + * i_rsort = np.argsort(r) + * rarr_np = r[i_rsort] # needed to keep memory in scope + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__29, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1701 + * if r.ndim != 1: + * raise ValueError("r must be a 1-dimensional array") + * i_rsort = np.argsort(r) # <<<<<<<<<<<<<< + * rarr_np = r[i_rsort] # needed to keep memory in scope + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1701; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_argsort); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1701; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1701; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_r); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_r); + __Pyx_GIVEREF(__pyx_v_r); + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_1, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1701; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_i_rsort = __pyx_t_4; + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1702 + * raise ValueError("r must be a 1-dimensional array") + * i_rsort = np.argsort(r) + * rarr_np = r[i_rsort] # needed to keep memory in scope # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) * */ - __pyx_v_f = (__pyx_v_f + 1); + __pyx_t_4 = PyObject_GetItem(__pyx_v_r, __pyx_v_i_rsort); if (unlikely(__pyx_t_4 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1702; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_rarr_np = __pyx_t_4; + __pyx_t_4 = 0; - /* "numpy.pxd":812 - * f[0] = 120 # "x"; pad byte - * f += 1 - * offset[0] += 1 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1703 + * i_rsort = np.argsort(r) + * rarr_np = r[i_rsort] # needed to keep memory in scope + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) # <<<<<<<<<<<<<< * - * offset[0] += child.itemsize + * # create array to hold counts */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); - } + if (!(likely(((__pyx_v_rarr_np) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_rarr_np, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_rarr_np)); if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_rarr = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; - /* "numpy.pxd":814 - * offset[0] += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1706 * - * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * # create array to hold counts + * count = np.zeros(r.shape[0], dtype=ITYPE) # <<<<<<<<<<<<<< + * cdef ITYPE_t[::1] carr = get_memview_ITYPE_1D(count) * - * if not PyDataType_HASFIELDS(child): */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_r, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_4, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_count = __pyx_t_2; + __pyx_t_2 = 0; - /* "numpy.pxd":816 - * offset[0] += child.itemsize + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1707 + * # create array to hold counts + * count = np.zeros(r.shape[0], dtype=ITYPE) + * cdef ITYPE_t[::1] carr = get_memview_ITYPE_1D(count) # <<<<<<<<<<<<<< * - * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< - * t = child.type_num - * if end - f < 5: + * cdef DTYPE_t* pt = &Xarr[0, 0] */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); - if (__pyx_t_6) { + if (!(likely(((__pyx_v_count) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_count, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1707; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_v_count)); if (unlikely(!__pyx_t_8.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1707; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_carr = __pyx_t_8; + __pyx_t_8.memview = NULL; + __pyx_t_8.data = NULL; - /* "numpy.pxd":817 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1709 + * cdef ITYPE_t[::1] carr = get_memview_ITYPE_1D(count) * - * if not PyDataType_HASFIELDS(child): - * t = child.type_num # <<<<<<<<<<<<<< - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") + * cdef DTYPE_t* pt = &Xarr[0, 0] # <<<<<<<<<<<<<< + * + * if dualtree: */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_9 = 0; + __pyx_t_10 = 0; + __pyx_v_pt = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_Xarr.data + __pyx_t_9 * __pyx_v_Xarr.strides[0]) )) + __pyx_t_10)) )))); - /* "numpy.pxd":818 - * if not PyDataType_HASFIELDS(child): - * t = child.type_num - * if end - f < 5: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short.") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1711 + * cdef DTYPE_t* pt = &Xarr[0, 0] * + * if dualtree: # <<<<<<<<<<<<<< + * other = self.__class__(Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); - if (__pyx_t_6) { + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_dualtree); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1711; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { - /* "numpy.pxd":819 - * t = child.type_num - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1712 * - * # Until ticket #99 is fixed, use integers to avoid warnings + * if dualtree: + * other = self.__class__(Xarr, metric=self.dist_metric, # <<<<<<<<<<<<<< + * leaf_size=self.leaf_size) + * self._two_point_dual(0, other, 0, &rarr[0], &carr[0], */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_53), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; - } - __pyx_L10:; + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_Xarr, 2, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_metric, ((PyObject *)__pyx_v_self->dist_metric)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1713 + * if dualtree: + * other = self.__class__(Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) # <<<<<<<<<<<<<< + * self._two_point_dual(0, other, 0, &rarr[0], &carr[0], + * 0, rarr.shape[0]) + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->leaf_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_leaf_size, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":822 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1712 * - * # Until ticket #99 is fixed, use integers to avoid warnings - * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" + * if dualtree: + * other = self.__class__(Xarr, metric=self.dist_metric, # <<<<<<<<<<<<<< + * leaf_size=self.leaf_size) + * self._two_point_dual(0, other, 0, &rarr[0], &carr[0], */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 98; - goto __pyx_L11; - } + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_other = __pyx_t_1; + __pyx_t_1 = 0; - /* "numpy.pxd":823 - * # Until ticket #99 is fixed, use integers to avoid warnings - * if t == NPY_BYTE: f[0] = 98 #"b" - * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1714 + * other = self.__class__(Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) + * self._two_point_dual(0, other, 0, &rarr[0], &carr[0], # <<<<<<<<<<<<<< + * 0, rarr.shape[0]) + * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 66; - goto __pyx_L11; - } + if (!(likely(((__pyx_v_other) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_other, __pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1714; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = 0; + __pyx_t_12 = 0; - /* "numpy.pxd":824 - * if t == NPY_BYTE: f[0] = 98 #"b" - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1715 + * leaf_size=self.leaf_size) + * self._two_point_dual(0, other, 0, &rarr[0], &carr[0], + * 0, rarr.shape[0]) # <<<<<<<<<<<<<< + * else: + * for i in range(Xarr.shape[0]): */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 104; - goto __pyx_L11; - } + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_dual(__pyx_v_self, 0, ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_other), 0, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_rarr.data) + __pyx_t_11)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_carr.data) + __pyx_t_12)) )))), 0, (__pyx_v_rarr.shape[0])); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1714; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + /*else*/ { - /* "numpy.pxd":825 - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1717 + * 0, rarr.shape[0]) + * else: + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * self._two_point_single(0, pt, &rarr[0], &carr[0], + * 0, rarr.shape[0]) */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 72; - goto __pyx_L11; - } + __pyx_t_14 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_15 = 0; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { + __pyx_v_i = __pyx_t_15; - /* "numpy.pxd":826 - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1718 + * else: + * for i in range(Xarr.shape[0]): + * self._two_point_single(0, pt, &rarr[0], &carr[0], # <<<<<<<<<<<<<< + * 0, rarr.shape[0]) + * pt += n_features */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 105; - goto __pyx_L11; - } + __pyx_t_16 = 0; + __pyx_t_17 = 0; - /* "numpy.pxd":827 - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1719 + * for i in range(Xarr.shape[0]): + * self._two_point_single(0, pt, &rarr[0], &carr[0], + * 0, rarr.shape[0]) # <<<<<<<<<<<<<< + * pt += n_features + * */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 73; - goto __pyx_L11; - } + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_single(__pyx_v_self, 0, __pyx_v_pt, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_rarr.data) + __pyx_t_16)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_carr.data) + __pyx_t_17)) )))), 0, (__pyx_v_rarr.shape[0])); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "numpy.pxd":828 - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1720 + * self._two_point_single(0, pt, &rarr[0], &carr[0], + * 0, rarr.shape[0]) + * pt += n_features # <<<<<<<<<<<<<< + * + * return count */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 108; - goto __pyx_L11; - } + __pyx_v_pt = (__pyx_v_pt + __pyx_v_n_features); + } + } + __pyx_L5:; - /* "numpy.pxd":829 - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1722 + * pt += n_features + * + * return count # <<<<<<<<<<<<<< + * + * cdef int _query_single_depthfirst(self, ITYPE_t i_node, */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 76; - goto __pyx_L11; - } + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_count); + __pyx_r = __pyx_v_count; + goto __pyx_L0; - /* "numpy.pxd":830 - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1650 + * return np.exp(log_density_arr) + * + * def two_point_correlation(self, X, r, dualtree=False): # <<<<<<<<<<<<<< + * """Compute the two-point correlation function + * */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 113; - goto __pyx_L11; - } - /* "numpy.pxd":831 - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_8, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.two_point_correlation", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_np_Xarr); + __PYX_XDEC_MEMVIEW(&__pyx_v_Xarr, 1); + __Pyx_XDECREF(__pyx_v_i_rsort); + __Pyx_XDECREF(__pyx_v_rarr_np); + __PYX_XDEC_MEMVIEW(&__pyx_v_rarr, 1); + __Pyx_XDECREF(__pyx_v_count); + __PYX_XDEC_MEMVIEW(&__pyx_v_carr, 1); + __Pyx_XDECREF(__pyx_v_other); + __Pyx_XDECREF(__pyx_v_X); + __Pyx_XDECREF(__pyx_v_r); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1724 + * return count + * + * cdef int _query_single_depthfirst(self, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt, ITYPE_t i_pt, + * NeighborsHeap heap, */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 81; - goto __pyx_L11; - } - /* "numpy.pxd":832 - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" +static int __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__query_single_depthfirst(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_pt, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_heap, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB) { + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + int __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_query_single_depthfirst", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1729 + * DTYPE_t reduced_dist_LB) except -1: + * """Recursive Single-tree k-neighbors query, depth-first approach""" + * cdef NodeData_t node_info = self.node_data[i_node] # <<<<<<<<<<<<<< + * + * cdef DTYPE_t dist_pt, reduced_dist_LB_1, reduced_dist_LB_2 */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 102; - goto __pyx_L11; - } + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1729; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_v_i_node; + __pyx_v_node_info = (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_1)) ))); - /* "numpy.pxd":833 - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1734 + * cdef ITYPE_t i, i1, i2 + * + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 100; - goto __pyx_L11; - } + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1734; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_2 * __pyx_v_self->data.strides[0]) )) + __pyx_t_3)) )))); - /* "numpy.pxd":834 - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1739 + * # Case 1: query point is outside node radius: + * # trim it from the query + * if reduced_dist_LB > heap.largest(i_pt): # <<<<<<<<<<<<<< + * self.n_trims += 1 + * */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 103; - goto __pyx_L11; - } + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = ((__pyx_v_reduced_dist_LB > __pyx_t_4) != 0); + if (__pyx_t_5) { - /* "numpy.pxd":835 - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1740 + * # trim it from the query + * if reduced_dist_LB > heap.largest(i_pt): + * self.n_trims += 1 # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 102; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; - } + __pyx_v_self->n_trims = (__pyx_v_self->n_trims + 1); + goto __pyx_L3; + } - /* "numpy.pxd":836 - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg - * elif t == NPY_OBJECT: f[0] = 79 #"O" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1744 + * #------------------------------------------------------------ + * # Case 2: this is a leaf node. Update set of nearby points + * elif node_info.is_leaf: # <<<<<<<<<<<<<< + * self.n_leaves += 1 + * for i in range(node_info.idx_start, node_info.idx_end): */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 100; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; - } + __pyx_t_5 = (__pyx_v_node_info.is_leaf != 0); + if (__pyx_t_5) { - /* "numpy.pxd":837 - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< - * elif t == NPY_OBJECT: f[0] = 79 #"O" - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1745 + * # Case 2: this is a leaf node. Update set of nearby points + * elif node_info.is_leaf: + * self.n_leaves += 1 # <<<<<<<<<<<<<< + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.rdist(pt, + */ + __pyx_v_self->n_leaves = (__pyx_v_self->n_leaves + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1746 + * elif node_info.is_leaf: + * self.n_leaves += 1 + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], + */ + __pyx_t_6 = __pyx_v_node_info.idx_end; + for (__pyx_t_7 = __pyx_v_node_info.idx_start; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1748 + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], # <<<<<<<<<<<<<< + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1748; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1748; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_8 = __pyx_v_i; + __pyx_t_9 = (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_8)) ))); + __pyx_t_10 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1749 + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) # <<<<<<<<<<<<<< + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i]) */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 103; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; - } + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1749; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} - /* "numpy.pxd":838 - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg - * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1747 + * self.n_leaves += 1 + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.rdist(pt, # <<<<<<<<<<<<<< + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 79; - goto __pyx_L11; + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_rdist(__pyx_v_self, __pyx_v_pt, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_9 * __pyx_v_self->data.strides[0]) )) + __pyx_t_10)) )))), (__pyx_v_self->data.shape[1])); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1747; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1750 + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): # <<<<<<<<<<<<<< + * heap.push(i_pt, dist_pt, self.idx_array[i]) + * + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1750; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = ((__pyx_v_dist_pt < __pyx_t_4) != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1751 + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i]) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1751; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_11 = __pyx_v_i; + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_i_pt, __pyx_v_dist_pt, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_11)) ))), 0); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; } - /*else*/ { + __pyx_L6:; + } + goto __pyx_L3; + } + /*else*/ { - /* "numpy.pxd":840 - * elif t == NPY_OBJECT: f[0] = 79 #"O" - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< - * f += 1 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1757 + * # starting with the closest * else: + * self.n_splits += 1 # <<<<<<<<<<<<<< + * i1 = 2 * i_node + 1 + * i2 = i1 + 1 */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_48), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L11:; + __pyx_v_self->n_splits = (__pyx_v_self->n_splits + 1); - /* "numpy.pxd":841 - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * f += 1 # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1758 * else: - * # Cython ignores struct boundary information ("T{...}"), + * self.n_splits += 1 + * i1 = 2 * i_node + 1 # <<<<<<<<<<<<<< + * i2 = i1 + 1 + * reduced_dist_LB_1 = min_rdist(self, i1, pt) */ - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; + __pyx_v_i1 = ((2 * __pyx_v_i_node) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1759 + * self.n_splits += 1 + * i1 = 2 * i_node + 1 + * i2 = i1 + 1 # <<<<<<<<<<<<<< + * reduced_dist_LB_1 = min_rdist(self, i1, pt) + * reduced_dist_LB_2 = min_rdist(self, i2, pt) + */ + __pyx_v_i2 = (__pyx_v_i1 + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1760 + * i1 = 2 * i_node + 1 + * i2 = i1 + 1 + * reduced_dist_LB_1 = min_rdist(self, i1, pt) # <<<<<<<<<<<<<< + * reduced_dist_LB_2 = min_rdist(self, i2, pt) + * + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist(__pyx_v_self, __pyx_v_i1, __pyx_v_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB_1 = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1761 + * i2 = i1 + 1 + * reduced_dist_LB_1 = min_rdist(self, i1, pt) + * reduced_dist_LB_2 = min_rdist(self, i2, pt) # <<<<<<<<<<<<<< + * + * # recursively query subnodes + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist(__pyx_v_self, __pyx_v_i2, __pyx_v_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1761; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB_2 = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1764 + * + * # recursively query subnodes + * if reduced_dist_LB_1 <= reduced_dist_LB_2: # <<<<<<<<<<<<<< + * self._query_single_depthfirst(i1, pt, i_pt, heap, + * reduced_dist_LB_1) + */ + __pyx_t_5 = ((__pyx_v_reduced_dist_LB_1 <= __pyx_v_reduced_dist_LB_2) != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1765 + * # recursively query subnodes + * if reduced_dist_LB_1 <= reduced_dist_LB_2: + * self._query_single_depthfirst(i1, pt, i_pt, heap, # <<<<<<<<<<<<<< + * reduced_dist_LB_1) + * self._query_single_depthfirst(i2, pt, i_pt, heap, + */ + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_depthfirst(__pyx_v_self, __pyx_v_i1, __pyx_v_pt, __pyx_v_i_pt, __pyx_v_heap, __pyx_v_reduced_dist_LB_1); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1767 + * self._query_single_depthfirst(i1, pt, i_pt, heap, + * reduced_dist_LB_1) + * self._query_single_depthfirst(i2, pt, i_pt, heap, # <<<<<<<<<<<<<< + * reduced_dist_LB_2) + * else: + */ + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_depthfirst(__pyx_v_self, __pyx_v_i2, __pyx_v_pt, __pyx_v_i_pt, __pyx_v_heap, __pyx_v_reduced_dist_LB_2); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; } /*else*/ { - /* "numpy.pxd":845 - * # Cython ignores struct boundary information ("T{...}"), - * # so don't output it - * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< - * return f - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1770 + * reduced_dist_LB_2) + * else: + * self._query_single_depthfirst(i2, pt, i_pt, heap, # <<<<<<<<<<<<<< + * reduced_dist_LB_2) + * self._query_single_depthfirst(i1, pt, i_pt, heap, */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_depthfirst(__pyx_v_self, __pyx_v_i2, __pyx_v_pt, __pyx_v_i_pt, __pyx_v_heap, __pyx_v_reduced_dist_LB_2); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1770; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1772 + * self._query_single_depthfirst(i2, pt, i_pt, heap, + * reduced_dist_LB_2) + * self._query_single_depthfirst(i1, pt, i_pt, heap, # <<<<<<<<<<<<<< + * reduced_dist_LB_1) + * return 0 + */ + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_depthfirst(__pyx_v_self, __pyx_v_i1, __pyx_v_pt, __pyx_v_i_pt, __pyx_v_heap, __pyx_v_reduced_dist_LB_1); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L9:; + __pyx_L7:; } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_L3:; - /* "numpy.pxd":846 - * # so don't output it - * f = _util_dtypestring(child, f, end, offset) - * return f # <<<<<<<<<<<<<< - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1774 + * self._query_single_depthfirst(i1, pt, i_pt, heap, + * reduced_dist_LB_1) + * return 0 # <<<<<<<<<<<<<< * + * cdef int _query_single_breadthfirst(self, DTYPE_t* pt, */ - __pyx_r = __pyx_v_f; - goto __pyx_L0; - __pyx_r = 0; goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1724 + * return count + * + * cdef int _query_single_depthfirst(self, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt, ITYPE_t i_pt, + * NeighborsHeap heap, + */ + + /* function exit code */ __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree._query_single_depthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_child); - __Pyx_XDECREF(__pyx_v_fields); - __Pyx_XDECREF(__pyx_v_childname); - __Pyx_XDECREF(__pyx_v_new_offset); - __Pyx_XDECREF(__pyx_v_t); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":961 - * +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1776 + * return 0 * - * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< - * cdef PyObject* baseptr - * if base is None: + * cdef int _query_single_breadthfirst(self, DTYPE_t* pt, # <<<<<<<<<<<<<< + * ITYPE_t i_pt, + * NeighborsHeap heap, */ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { - PyObject *__pyx_v_baseptr; +static int __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__query_single_breadthfirst(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_pt, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_heap, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_nodeheap) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *__pyx_v_node_data; + CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_v_nodeheap_item; + CYTHON_UNUSED struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info; + int __pyx_r; __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base"); + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + long __pyx_t_13; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_query_single_breadthfirst", 0); - /* "numpy.pxd":963 - * cdef inline void set_array_base(ndarray arr, object base): - * cdef PyObject* baseptr - * if base is None: # <<<<<<<<<<<<<< - * baseptr = NULL - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1783 + * cdef ITYPE_t i, i_node + * cdef DTYPE_t dist_pt, reduced_dist_LB + * cdef NodeData_t* node_data = &self.node_data[0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data = &self.data[0, 0] + * */ - __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1783; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_v_node_data = (&(*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_1)) )))); - /* "numpy.pxd":964 - * cdef PyObject* baseptr - * if base is None: - * baseptr = NULL # <<<<<<<<<<<<<< - * else: - * Py_INCREF(base) # important to do this before decref below! + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1784 + * cdef DTYPE_t dist_pt, reduced_dist_LB + * cdef NodeData_t* node_data = &self.node_data[0] + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * + * # Set up the node heap and push the head node onto it */ - __pyx_v_baseptr = NULL; - goto __pyx_L3; - } - /*else*/ { + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1784; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_2 * __pyx_v_self->data.strides[0]) )) + __pyx_t_3)) )))); - /* "numpy.pxd":966 - * baseptr = NULL - * else: - * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< - * baseptr = base - * Py_XDECREF(arr.base) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1788 + * # Set up the node heap and push the head node onto it + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_rdist(self, 0, pt) # <<<<<<<<<<<<<< + * nodeheap_item.i1 = 0 + * nodeheap.push(nodeheap_item) */ - Py_INCREF(__pyx_v_base); + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist(__pyx_v_self, 0, __pyx_v_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1788; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_4; - /* "numpy.pxd":967 - * else: - * Py_INCREF(base) # important to do this before decref below! - * baseptr = base # <<<<<<<<<<<<<< - * Py_XDECREF(arr.base) - * arr.base = baseptr + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1789 + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_rdist(self, 0, pt) + * nodeheap_item.i1 = 0 # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) + * */ - __pyx_v_baseptr = ((PyObject *)__pyx_v_base); - } - __pyx_L3:; + __pyx_v_nodeheap_item.i1 = 0; - /* "numpy.pxd":968 - * Py_INCREF(base) # important to do this before decref below! - * baseptr = base - * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< - * arr.base = baseptr + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1790 + * nodeheap_item.val = min_rdist(self, 0, pt) + * nodeheap_item.i1 = 0 + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< * + * while nodeheap.n > 0: */ - Py_XDECREF(__pyx_v_arr->base); + __pyx_t_5 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "numpy.pxd":969 - * baseptr = base - * Py_XDECREF(arr.base) - * arr.base = baseptr # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1792 + * nodeheap.push(nodeheap_item) * - * cdef inline object get_array_base(ndarray arr): + * while nodeheap.n > 0: # <<<<<<<<<<<<<< + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val */ - __pyx_v_arr->base = __pyx_v_baseptr; + while (1) { + __pyx_t_6 = ((__pyx_v_nodeheap->n > 0) != 0); + if (!__pyx_t_6) break; - __Pyx_RefNannyFinishContext(); -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1793 + * + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() # <<<<<<<<<<<<<< + * reduced_dist_LB = nodeheap_item.val + * i_node = nodeheap_item.i1 + */ + __pyx_v_nodeheap_item = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->pop(__pyx_v_nodeheap); -/* "numpy.pxd":971 - * arr.base = baseptr + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1794 + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val # <<<<<<<<<<<<<< + * i_node = nodeheap_item.i1 + * node_info = node_data[i_node] + */ + __pyx_t_4 = __pyx_v_nodeheap_item.val; + __pyx_v_reduced_dist_LB = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1795 + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val + * i_node = nodeheap_item.i1 # <<<<<<<<<<<<<< + * node_info = node_data[i_node] * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * if arr.base is NULL: - * return None */ + __pyx_t_7 = __pyx_v_nodeheap_item.i1; + __pyx_v_i_node = __pyx_t_7; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base"); + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1796 + * reduced_dist_LB = nodeheap_item.val + * i_node = nodeheap_item.i1 + * node_info = node_data[i_node] # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_v_node_info = (__pyx_v_node_data[__pyx_v_i_node]); - /* "numpy.pxd":972 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1801 + * # Case 1: query point is outside node radius: + * # trim it from the query + * if reduced_dist_LB > heap.largest(i_pt): # <<<<<<<<<<<<<< + * self.n_trims += 1 * - * cdef inline object get_array_base(ndarray arr): - * if arr.base is NULL: # <<<<<<<<<<<<<< - * return None - * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); - if (__pyx_t_1) { + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((__pyx_v_reduced_dist_LB > __pyx_t_4) != 0); + if (__pyx_t_6) { - /* "numpy.pxd":973 - * cdef inline object get_array_base(ndarray arr): - * if arr.base is NULL: - * return None # <<<<<<<<<<<<<< - * else: - * return arr.base + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1802 + * # trim it from the query + * if reduced_dist_LB > heap.largest(i_pt): + * self.n_trims += 1 # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_None); - __pyx_r = Py_None; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { + __pyx_v_self->n_trims = (__pyx_v_self->n_trims + 1); + goto __pyx_L5; + } - /* "numpy.pxd":975 - * return None - * else: - * return arr.base # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1806 + * #------------------------------------------------------------ + * # Case 2: this is a leaf node. Update set of nearby points + * elif node_data[i_node].is_leaf: # <<<<<<<<<<<<<< + * self.n_leaves += 1 + * for i in range(node_data[i_node].idx_start, */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); - __pyx_r = ((PyObject *)__pyx_v_arr->base); - goto __pyx_L0; + __pyx_t_6 = ((__pyx_v_node_data[__pyx_v_i_node]).is_leaf != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1807 + * # Case 2: this is a leaf node. Update set of nearby points + * elif node_data[i_node].is_leaf: + * self.n_leaves += 1 # <<<<<<<<<<<<<< + * for i in range(node_data[i_node].idx_start, + * node_data[i_node].idx_end): + */ + __pyx_v_self->n_leaves = (__pyx_v_self->n_leaves + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1809 + * self.n_leaves += 1 + * for i in range(node_data[i_node].idx_start, + * node_data[i_node].idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], + */ + __pyx_t_7 = (__pyx_v_node_data[__pyx_v_i_node]).idx_end; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1808 + * elif node_data[i_node].is_leaf: + * self.n_leaves += 1 + * for i in range(node_data[i_node].idx_start, # <<<<<<<<<<<<<< + * node_data[i_node].idx_end): + * dist_pt = self.rdist(pt, + */ + for (__pyx_t_8 = (__pyx_v_node_data[__pyx_v_i_node]).idx_start; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1811 + * node_data[i_node].idx_end): + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], # <<<<<<<<<<<<<< + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1811; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1811; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = __pyx_v_i; + __pyx_t_10 = (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_9)) ))); + __pyx_t_11 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1812 + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) # <<<<<<<<<<<<<< + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i]) + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1812; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1810 + * for i in range(node_data[i_node].idx_start, + * node_data[i_node].idx_end): + * dist_pt = self.rdist(pt, # <<<<<<<<<<<<<< + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_rdist(__pyx_v_self, __pyx_v_pt, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_10 * __pyx_v_self->data.strides[0]) )) + __pyx_t_11)) )))), (__pyx_v_self->data.shape[1])); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1810; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1813 + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): # <<<<<<<<<<<<<< + * heap.push(i_pt, dist_pt, self.idx_array[i]) + * + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((__pyx_v_dist_pt < __pyx_t_4) != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1814 + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i]) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1814; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_12 = __pyx_v_i; + __pyx_t_5 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_i_pt, __pyx_v_dist_pt, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_12)) ))), 0); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1814; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + } + goto __pyx_L5; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1819 + * # Case 3: Node is not a leaf. Add subnodes to the node heap + * else: + * self.n_splits += 1 # <<<<<<<<<<<<<< + * for i in range(2 * i_node + 1, 2 * i_node + 3): + * nodeheap_item.i1 = i + */ + __pyx_v_self->n_splits = (__pyx_v_self->n_splits + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1820 + * else: + * self.n_splits += 1 + * for i in range(2 * i_node + 1, 2 * i_node + 3): # <<<<<<<<<<<<<< + * nodeheap_item.i1 = i + * nodeheap_item.val = min_rdist(self, i, pt) + */ + __pyx_t_13 = ((2 * __pyx_v_i_node) + 3); + for (__pyx_t_7 = ((2 * __pyx_v_i_node) + 1); __pyx_t_7 < __pyx_t_13; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1821 + * self.n_splits += 1 + * for i in range(2 * i_node + 1, 2 * i_node + 3): + * nodeheap_item.i1 = i # <<<<<<<<<<<<<< + * nodeheap_item.val = min_rdist(self, i, pt) + * nodeheap.push(nodeheap_item) + */ + __pyx_v_nodeheap_item.i1 = __pyx_v_i; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1822 + * for i in range(2 * i_node + 1, 2 * i_node + 3): + * nodeheap_item.i1 = i + * nodeheap_item.val = min_rdist(self, i, pt) # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) + * return 0 + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist(__pyx_v_self, __pyx_v_i, __pyx_v_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1823 + * nodeheap_item.i1 = i + * nodeheap_item.val = min_rdist(self, i, pt) + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + __pyx_L5:; } - __pyx_L3:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1824 + * nodeheap_item.val = min_rdist(self, i, pt) + * nodeheap.push(nodeheap_item) + * return 0 # <<<<<<<<<<<<<< + * + * cdef int _query_dual_depthfirst(self, ITYPE_t i_node1, + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1776 + * return 0 + * + * cdef int _query_single_breadthfirst(self, DTYPE_t* pt, # <<<<<<<<<<<<<< + * ITYPE_t i_pt, + * NeighborsHeap heap, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree._query_single_breadthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree __pyx_vtable_7sklearn_9neighbors_9ball_tree_BallTree; -static PyObject *__pyx_tp_new_7sklearn_9neighbors_9ball_tree_BallTree(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *p; - PyObject *o = (*t->tp_alloc)(t, 0); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)o); - p->__pyx_vtab = __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BallTree; - p->data = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - p->idx_array = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - p->node_centroid_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - p->node_info_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - if (__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree___cinit__(o, __pyx_empty_tuple, NULL) < 0) { - Py_DECREF(o); o = 0; - } - return o; -} +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1826 + * return 0 + * + * cdef int _query_dual_depthfirst(self, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree other, ITYPE_t i_node2, + * DTYPE_t[::1] bounds, + */ + +static int __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__query_dual_depthfirst(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_other, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2, __Pyx_memviewslice __pyx_v_bounds, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_heap, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB) { + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info1; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_bound_max; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_parent; + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + int __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_16; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_17; + int __pyx_t_18; + long __pyx_t_19; + long __pyx_t_20; + int __pyx_t_21; + int __pyx_t_22; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_query_dual_depthfirst", 0); -static void __pyx_tp_dealloc_7sklearn_9neighbors_9ball_tree_BallTree(PyObject *o) { - struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)o; - Py_XDECREF(((PyObject *)p->data)); - Py_XDECREF(((PyObject *)p->idx_array)); - Py_XDECREF(((PyObject *)p->node_centroid_arr)); - Py_XDECREF(((PyObject *)p->node_info_arr)); - (*Py_TYPE(o)->tp_free)(o); -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1835 + * # bounds[i] is the largest distance among any of the + * # current neighbors in node i of the other tree. + * cdef NodeData_t node_info1 = self.node_data[i_node1] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info2 = other.node_data[i_node2] + * + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1835; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_v_i_node1; + __pyx_v_node_info1 = (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_1)) ))); -static int __pyx_tp_traverse_7sklearn_9neighbors_9ball_tree_BallTree(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)o; - if (p->data) { - e = (*v)(((PyObject*)p->data), a); if (e) return e; - } - if (p->idx_array) { - e = (*v)(((PyObject*)p->idx_array), a); if (e) return e; - } - if (p->node_centroid_arr) { - e = (*v)(((PyObject*)p->node_centroid_arr), a); if (e) return e; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1836 + * # current neighbors in node i of the other tree. + * cdef NodeData_t node_info1 = self.node_data[i_node1] + * cdef NodeData_t node_info2 = other.node_data[i_node2] # <<<<<<<<<<<<<< + * + * cdef DTYPE_t* data1 = &self.data[0, 0] + */ + if (unlikely(!__pyx_v_other->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1836; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = __pyx_v_i_node2; + __pyx_v_node_info2 = (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_other->node_data.data) + __pyx_t_2)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1838 + * cdef NodeData_t node_info2 = other.node_data[i_node2] + * + * cdef DTYPE_t* data1 = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1838; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_v_data1 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_3 * __pyx_v_self->data.strides[0]) )) + __pyx_t_4)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1839 + * + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * + */ + if (unlikely(!__pyx_v_other->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1839; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_v_data2 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_other->data.data + __pyx_t_5 * __pyx_v_other->data.strides[0]) )) + __pyx_t_6)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1840 + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * + * cdef DTYPE_t bound_max, dist_pt, reduced_dist_LB1, reduced_dist_LB2 + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1840; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1848 + * # Case 1: nodes are further apart than the current bound: + * # trim both from the query + * if reduced_dist_LB > bounds[i_node2]: # <<<<<<<<<<<<<< + * pass + * + */ + __pyx_t_7 = __pyx_v_i_node2; + __pyx_t_8 = ((__pyx_v_reduced_dist_LB > (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_7)) )))) != 0); + if (__pyx_t_8) { + goto __pyx_L3; } - if (p->node_info_arr) { - e = (*v)(((PyObject*)p->node_info_arr), a); if (e) return e; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1854 + * # Case 2: both nodes are leaves: + * # do a brute-force search comparing all pairs + * elif node_info1.is_leaf and node_info2.is_leaf: # <<<<<<<<<<<<<< + * bounds[i_node2] = 0 + * + */ + if ((__pyx_v_node_info1.is_leaf != 0)) { + __pyx_t_8 = (__pyx_v_node_info2.is_leaf != 0); + } else { + __pyx_t_8 = (__pyx_v_node_info1.is_leaf != 0); } - return 0; -} + if (__pyx_t_8) { -static int __pyx_tp_clear_7sklearn_9neighbors_9ball_tree_BallTree(PyObject *o) { - struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)o; - PyObject* tmp; - tmp = ((PyObject*)p->data); - p->data = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->idx_array); - p->idx_array = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->node_centroid_arr); - p->node_centroid_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->node_info_arr); - p->node_info_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1855 + * # do a brute-force search comparing all pairs + * elif node_info1.is_leaf and node_info2.is_leaf: + * bounds[i_node2] = 0 # <<<<<<<<<<<<<< + * + * for i2 in range(node_info2.idx_start, node_info2.idx_end): + */ + __pyx_t_9 = __pyx_v_i_node2; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_9)) )) = 0.0; -static PyObject *__pyx_getprop_7sklearn_9neighbors_9ball_tree_8BallTree_data(PyObject *o, void *x) { - return __pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_4data___get__(o); -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1857 + * bounds[i_node2] = 0 + * + * for i2 in range(node_info2.idx_start, node_info2.idx_end): # <<<<<<<<<<<<<< + * i_pt = other.idx_array[i2] + * + */ + __pyx_t_10 = __pyx_v_node_info2.idx_end; + for (__pyx_t_11 = __pyx_v_node_info2.idx_start; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) { + __pyx_v_i2 = __pyx_t_11; -static PyObject *__pyx_getprop_7sklearn_9neighbors_9ball_tree_8BallTree_warning_flag(PyObject *o, void *x) { - return __pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_12warning_flag___get__(o); -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1858 + * + * for i2 in range(node_info2.idx_start, node_info2.idx_end): + * i_pt = other.idx_array[i2] # <<<<<<<<<<<<<< + * + * if heap.largest(i_pt) <= reduced_dist_LB: + */ + if (unlikely(!__pyx_v_other->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1858; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_12 = __pyx_v_i2; + __pyx_v_i_pt = (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_other->idx_array.data) + __pyx_t_12)) ))); -static PyMethodDef __pyx_methods_7sklearn_9neighbors_9ball_tree_BallTree[] = { - {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_2__reduce__, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_8BallTree_2__reduce__)}, - {__Pyx_NAMESTR("__getstate__"), (PyCFunction)__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_3__getstate__, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_8BallTree_3__getstate__)}, - {__Pyx_NAMESTR("__setstate__"), (PyCFunction)__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_4__setstate__, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_8BallTree_4__setstate__)}, - {__Pyx_NAMESTR("query"), (PyCFunction)__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_5query, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_8BallTree_5query)}, - {__Pyx_NAMESTR("query_radius"), (PyCFunction)__pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_6query_radius, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_8BallTree_6query_radius)}, - {0, 0, 0, 0} -}; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1860 + * i_pt = other.idx_array[i2] + * + * if heap.largest(i_pt) <= reduced_dist_LB: # <<<<<<<<<<<<<< + * continue + * + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((__pyx_t_13 <= __pyx_v_reduced_dist_LB) != 0); + if (__pyx_t_8) { -static struct PyGetSetDef __pyx_getsets_7sklearn_9neighbors_9ball_tree_BallTree[] = { - {(char *)"data", __pyx_getprop_7sklearn_9neighbors_9ball_tree_8BallTree_data, 0, 0, 0}, - {(char *)"warning_flag", __pyx_getprop_7sklearn_9neighbors_9ball_tree_8BallTree_warning_flag, 0, 0, 0}, - {0, 0, 0, 0, 0} -}; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1861 + * + * if heap.largest(i_pt) <= reduced_dist_LB: + * continue # <<<<<<<<<<<<<< + * + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + */ + goto __pyx_L4_continue; + } -static PyNumberMethods __pyx_tp_as_number_BallTree = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1863 + * continue + * + * for i1 in range(node_info1.idx_start, node_info1.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.rdist( + * data1 + n_features * self.idx_array[i1], + */ + __pyx_t_14 = __pyx_v_node_info1.idx_end; + for (__pyx_t_15 = __pyx_v_node_info1.idx_start; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { + __pyx_v_i1 = __pyx_t_15; -static PySequenceMethods __pyx_tp_as_sequence_BallTree = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1865 + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * dist_pt = self.rdist( + * data1 + n_features * self.idx_array[i1], # <<<<<<<<<<<<<< + * data2 + n_features * i_pt, + * n_features) + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1865; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_16 = __pyx_v_i1; -static PyMappingMethods __pyx_tp_as_mapping_BallTree = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1864 + * + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * dist_pt = self.rdist( # <<<<<<<<<<<<<< + * data1 + n_features * self.idx_array[i1], + * data2 + n_features * i_pt, + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_rdist(__pyx_v_self, (__pyx_v_data1 + (__pyx_v_n_features * (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_16)) ))))), (__pyx_v_data2 + (__pyx_v_n_features * __pyx_v_i_pt)), __pyx_v_n_features); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1864; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_13; -static PyBufferProcs __pyx_tp_as_buffer_BallTree = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1868 + * data2 + n_features * i_pt, + * n_features) + * if dist_pt < heap.largest(i_pt): # <<<<<<<<<<<<<< + * heap.push(i_pt, dist_pt, self.idx_array[i1]) + * + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1868; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((__pyx_v_dist_pt < __pyx_t_13) != 0); + if (__pyx_t_8) { -static PyTypeObject __pyx_type_7sklearn_9neighbors_9ball_tree_BallTree = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.neighbors.ball_tree.BallTree"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_9neighbors_9ball_tree_BallTree, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_BallTree, /*tp_as_number*/ - &__pyx_tp_as_sequence_BallTree, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_BallTree, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_BallTree, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - __Pyx_DOCSTR("\n Ball Tree for fast nearest-neighbor searches :\n\n BallTree(X, leaf_size=20, p=2.0)\n\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n n_samples is the number of points in the data set, and\n n_features is the dimension of the parameter space.\n Note: if X is a C-contiguous array of doubles then data will\n not be copied. Otherwise, an internal copy will be made.\n\n leaf_size : positive integer (default = 20)\n Number of points at which to switch to brute-force. Changing\n leaf_size will not affect the results of a query, but can\n significantly impact the speed of a query and the memory required\n to store the built ball tree. The amount of memory needed to\n store the tree scales as\n 2 ** (1 + floor(log2((n_samples - 1) / leaf_size))) - 1\n For a specified ``leaf_size``, a leaf node is guaranteed to\n satisfy ``leaf_size <= n_points <= 2 * leaf_size``, except in\n the case that ``n_samples < leaf_size``.\n\n p : distance metric for the BallTree. ``p`` encodes the Minkowski\n p-distance::\n\n D = sum((X[i] - X[j]) ** p) ** (1. / p)\n\n p must be greater than or equal to 1, so that the triangle\n inequality will hold. If ``p == np.inf``, then the distance is\n equivalent to::\n\n D = max(X[i] - X[j])\n\n Attributes\n ----------\n data : np.ndarray\n The training data\n\n warning_flag : bool\n Warning flag is set to true during query(...) if results are\n dependent on the order of the training cases.\n For classification or regression based on k-neighbors, if\n neighbor k and neighbor k+1 have identical distances but different\n labels, then the result will be dependent on the ordering of the\n training data. In this case, ``warning_flag`` will be set to True.\n\n Examples\n --------\n Query for k-nearest neighbors\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10,3)) # 10 points in 3 dimensions\n >>> ball_tree = BallTree(X, leaf_size=2) # doctest: +SKIP\n >>> dist, ind = ball_tree.query(X[0], n_neighbors=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors\n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n\n Pickle and Unpickle a ball tree (using protocol = 2). Note that the\n state of the tree is saved in the pickle operation: the tree is not\n rebuilt on un-pickling\n\n >>> import numpy as np\n >>> import pickle\n >>> np.random.seed(0)\n >>> X = np.random.random((10,3)) # 10 points in 3 dimensions\n >>> ball_tree = BallTree(X, leaf_size=2) # doctest: +SKIP\n >>> s = pickle.dumps(ball_tree, protocol=2) # doctest: +SKIP\n >>> ball_tree_copy = pickle.loads(s) # doctest: +SKIP\n >>> dist, ind = ball_tree_copy.query(X[0], k=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors \n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n "), /*tp_doc*/ - __pyx_tp_traverse_7sklearn_9neighbors_9ball_tree_BallTree, /*tp_traverse*/ - __pyx_tp_clear_7sklearn_9neighbors_9ball_tree_BallTree, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_9neighbors_9ball_tree_BallTree, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets_7sklearn_9neighbors_9ball_tree_BallTree, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pf_7sklearn_9neighbors_9ball_tree_8BallTree_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_9neighbors_9ball_tree_BallTree, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; - -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - __Pyx_NAMESTR("ball_tree"), - __Pyx_DOCSTR(__pyx_k_54), /* m_doc */ - -1, /* m_size */ - __pyx_methods /* m_methods */, - NULL, /* m_reload */ - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 0}, - {&__pyx_kp_s_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 0, 1, 0}, - {&__pyx_kp_s_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 0, 1, 0}, - {&__pyx_kp_s_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 0, 1, 0}, - {&__pyx_kp_s_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 0, 1, 0}, - {&__pyx_kp_s_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 1, 0}, - {&__pyx_kp_s_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 1, 0}, - {&__pyx_kp_s_29, __pyx_k_29, sizeof(__pyx_k_29), 0, 0, 1, 0}, - {&__pyx_kp_s_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 0, 1, 0}, - {&__pyx_kp_s_31, __pyx_k_31, sizeof(__pyx_k_31), 0, 0, 1, 0}, - {&__pyx_kp_s_35, __pyx_k_35, sizeof(__pyx_k_35), 0, 0, 1, 0}, - {&__pyx_kp_s_38, __pyx_k_38, sizeof(__pyx_k_38), 0, 0, 1, 0}, - {&__pyx_kp_s_40, __pyx_k_40, sizeof(__pyx_k_40), 0, 0, 1, 0}, - {&__pyx_kp_u_42, __pyx_k_42, sizeof(__pyx_k_42), 0, 1, 0, 0}, - {&__pyx_kp_u_44, __pyx_k_44, sizeof(__pyx_k_44), 0, 1, 0, 0}, - {&__pyx_kp_u_46, __pyx_k_46, sizeof(__pyx_k_46), 0, 1, 0, 0}, - {&__pyx_kp_u_48, __pyx_k_48, sizeof(__pyx_k_48), 0, 1, 0, 0}, - {&__pyx_kp_u_49, __pyx_k_49, sizeof(__pyx_k_49), 0, 1, 0, 0}, - {&__pyx_kp_u_52, __pyx_k_52, sizeof(__pyx_k_52), 0, 1, 0, 0}, - {&__pyx_n_s_55, __pyx_k_55, sizeof(__pyx_k_55), 0, 0, 1, 1}, - {&__pyx_kp_u_56, __pyx_k_56, sizeof(__pyx_k_56), 0, 1, 0, 0}, - {&__pyx_kp_u_57, __pyx_k_57, sizeof(__pyx_k_57), 0, 1, 0, 0}, - {&__pyx_kp_u_58, __pyx_k_58, sizeof(__pyx_k_58), 0, 1, 0, 0}, - {&__pyx_kp_u_59, __pyx_k_59, sizeof(__pyx_k_59), 0, 1, 0, 0}, - {&__pyx_n_s__C, __pyx_k__C, sizeof(__pyx_k__C), 0, 0, 1, 1}, - {&__pyx_n_s__DTYPE, __pyx_k__DTYPE, sizeof(__pyx_k__DTYPE), 0, 0, 1, 1}, - {&__pyx_n_s__ITYPE, __pyx_k__ITYPE, sizeof(__pyx_k__ITYPE), 0, 0, 1, 1}, - {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, - {&__pyx_n_s____getstate__, __pyx_k____getstate__, sizeof(__pyx_k____getstate__), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____new__, __pyx_k____new__, sizeof(__pyx_k____new__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__arange, __pyx_k__arange, sizeof(__pyx_k__arange), 0, 0, 1, 1}, - {&__pyx_n_s__array2d, __pyx_k__array2d, sizeof(__pyx_k__array2d), 0, 0, 1, 1}, - {&__pyx_n_s__asarray, __pyx_k__asarray, sizeof(__pyx_k__asarray), 0, 0, 1, 1}, - {&__pyx_n_s__atleast_1d, __pyx_k__atleast_1d, sizeof(__pyx_k__atleast_1d), 0, 0, 1, 1}, - {&__pyx_n_s__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 0, 1, 1}, - {&__pyx_n_s__copy, __pyx_k__copy, sizeof(__pyx_k__copy), 0, 0, 1, 1}, - {&__pyx_n_s__count_only, __pyx_k__count_only, sizeof(__pyx_k__count_only), 0, 0, 1, 1}, - {&__pyx_n_s__double, __pyx_k__double, sizeof(__pyx_k__double), 0, 0, 1, 1}, - {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, - {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, - {&__pyx_n_s__enumerate, __pyx_k__enumerate, sizeof(__pyx_k__enumerate), 0, 0, 1, 1}, - {&__pyx_n_s__fill, __pyx_k__fill, sizeof(__pyx_k__fill), 0, 0, 1, 1}, - {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, - {&__pyx_n_s__inf, __pyx_k__inf, sizeof(__pyx_k__inf), 0, 0, 1, 1}, - {&__pyx_n_s__int32, __pyx_k__int32, sizeof(__pyx_k__int32), 0, 0, 1, 1}, - {&__pyx_n_s__k, __pyx_k__k, sizeof(__pyx_k__k), 0, 0, 1, 1}, - {&__pyx_n_s__leaf_size, __pyx_k__leaf_size, sizeof(__pyx_k__leaf_size), 0, 0, 1, 1}, - {&__pyx_n_s__log2, __pyx_k__log2, sizeof(__pyx_k__log2), 0, 0, 1, 1}, - {&__pyx_n_s__newObj, __pyx_k__newObj, sizeof(__pyx_k__newObj), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__object, __pyx_k__object, sizeof(__pyx_k__object), 0, 0, 1, 1}, - {&__pyx_n_s__ones, __pyx_k__ones, sizeof(__pyx_k__ones), 0, 0, 1, 1}, - {&__pyx_n_s__order, __pyx_k__order, sizeof(__pyx_k__order), 0, 0, 1, 1}, - {&__pyx_n_s__p, __pyx_k__p, sizeof(__pyx_k__p), 0, 0, 1, 1}, - {&__pyx_n_s__r, __pyx_k__r, sizeof(__pyx_k__r), 0, 0, 1, 1}, - {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__reshape, __pyx_k__reshape, sizeof(__pyx_k__reshape), 0, 0, 1, 1}, - {&__pyx_n_s__return_distance, __pyx_k__return_distance, sizeof(__pyx_k__return_distance), 0, 0, 1, 1}, - {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, - {&__pyx_n_s__size, __pyx_k__size, sizeof(__pyx_k__size), 0, 0, 1, 1}, - {&__pyx_n_s__sort_results, __pyx_k__sort_results, sizeof(__pyx_k__sort_results), 0, 0, 1, 1}, - {&__pyx_n_s__utils, __pyx_k__utils, sizeof(__pyx_k__utils), 0, 0, 1, 1}, - {&__pyx_n_s__zeros, __pyx_k__zeros, sizeof(__pyx_k__zeros), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_enumerate = __Pyx_GetName(__pyx_b, __pyx_n_s__enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - return 0; - __pyx_L1_error:; - return -1; -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1869 + * n_features) + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i1]) # <<<<<<<<<<<<<< + * + * # keep track of node bound + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1869; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_17 = __pyx_v_i1; + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_i_pt, __pyx_v_dist_pt, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_17)) ))), 0); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1869; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L9; + } + __pyx_L9:; + } -static int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1872 + * + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], # <<<<<<<<<<<<<< + * heap.largest(i_pt)) + * + */ + __pyx_t_14 = __pyx_v_i_node2; - /* "sklearn/neighbors/ball_tree.pyx":363 - * #print "resize", self.n, new_size - * if new_size < self.n: - * raise ValueError("new_size smaller than current") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1873 + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], + * heap.largest(i_pt)) # <<<<<<<<<<<<<< * - * self.size = new_size + * # update bounds up the tree */ - __pyx_k_tuple_2 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_2)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_1)); - PyTuple_SET_ITEM(__pyx_k_tuple_2, 0, ((PyObject *)__pyx_kp_s_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1873; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/neighbors/ball_tree.pyx":382 - * cdef inline stack_item stack_pop(stack* self): - * if self.n == 0: - * raise ValueError("popping empty stack") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1872 + * + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], # <<<<<<<<<<<<<< + * heap.largest(i_pt)) * - * self.n -= 1 */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_4)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_3)); - PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_s_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); + __pyx_t_15 = __pyx_v_i_node2; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_15)) )) = __pyx_f_7sklearn_9neighbors_9ball_tree_fmax((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_14)) ))), __pyx_t_13); + __pyx_L4_continue:; + } - /* "sklearn/neighbors/ball_tree.pyx":493 - * in rare cases where __init__ is not called - * """ - * self.data = np.empty((0,0), dtype=DTYPE) # <<<<<<<<<<<<<< - * self.idx_array = np.empty(0, dtype=ITYPE) - * self.node_centroid_arr = np.empty((0,0), dtype=DTYPE) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1876 + * + * # update bounds up the tree + * while i_node2 > 0: # <<<<<<<<<<<<<< + * i_parent = (i_node2 - 1) // 2 + * bound_max = fmax(bounds[2 * i_parent + 1], */ - __pyx_k_tuple_5 = PyTuple_New(2); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_5)); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_5, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_5, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_6)); - __Pyx_INCREF(((PyObject *)__pyx_k_tuple_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_k_tuple_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); - - /* "sklearn/neighbors/ball_tree.pyx":494 - * """ - * self.data = np.empty((0,0), dtype=DTYPE) - * self.idx_array = np.empty(0, dtype=ITYPE) # <<<<<<<<<<<<<< - * self.node_centroid_arr = np.empty((0,0), dtype=DTYPE) - * self.node_info_arr = np.empty(0, dtype='c') + while (1) { + __pyx_t_8 = ((__pyx_v_i_node2 > 0) != 0); + if (!__pyx_t_8) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1877 + * # update bounds up the tree + * while i_node2 > 0: + * i_parent = (i_node2 - 1) // 2 # <<<<<<<<<<<<<< + * bound_max = fmax(bounds[2 * i_parent + 1], + * bounds[2 * i_parent + 2]) + */ + __pyx_v_i_parent = ((__pyx_v_i_node2 - 1) / 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1878 + * while i_node2 > 0: + * i_parent = (i_node2 - 1) // 2 + * bound_max = fmax(bounds[2 * i_parent + 1], # <<<<<<<<<<<<<< + * bounds[2 * i_parent + 2]) + * if bound_max < bounds[i_parent]: + */ + __pyx_t_19 = ((2 * __pyx_v_i_parent) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1879 + * i_parent = (i_node2 - 1) // 2 + * bound_max = fmax(bounds[2 * i_parent + 1], + * bounds[2 * i_parent + 2]) # <<<<<<<<<<<<<< + * if bound_max < bounds[i_parent]: + * bounds[i_parent] = bound_max + */ + __pyx_t_20 = ((2 * __pyx_v_i_parent) + 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1878 + * while i_node2 > 0: + * i_parent = (i_node2 - 1) // 2 + * bound_max = fmax(bounds[2 * i_parent + 1], # <<<<<<<<<<<<<< + * bounds[2 * i_parent + 2]) + * if bound_max < bounds[i_parent]: + */ + __pyx_v_bound_max = __pyx_f_7sklearn_9neighbors_9ball_tree_fmax((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_19)) ))), (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_20)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1880 + * bound_max = fmax(bounds[2 * i_parent + 1], + * bounds[2 * i_parent + 2]) + * if bound_max < bounds[i_parent]: # <<<<<<<<<<<<<< + * bounds[i_parent] = bound_max + * i_node2 = i_parent + */ + __pyx_t_10 = __pyx_v_i_parent; + __pyx_t_8 = ((__pyx_v_bound_max < (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_10)) )))) != 0); + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1881 + * bounds[2 * i_parent + 2]) + * if bound_max < bounds[i_parent]: + * bounds[i_parent] = bound_max # <<<<<<<<<<<<<< + * i_node2 = i_parent + * else: */ - __pyx_k_tuple_7 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_7)); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_7, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); + __pyx_t_11 = __pyx_v_i_parent; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_11)) )) = __pyx_v_bound_max; - /* "sklearn/neighbors/ball_tree.pyx":495 - * self.data = np.empty((0,0), dtype=DTYPE) - * self.idx_array = np.empty(0, dtype=ITYPE) - * self.node_centroid_arr = np.empty((0,0), dtype=DTYPE) # <<<<<<<<<<<<<< - * self.node_info_arr = np.empty(0, dtype='c') - * + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1882 + * if bound_max < bounds[i_parent]: + * bounds[i_parent] = bound_max + * i_node2 = i_parent # <<<<<<<<<<<<<< + * else: + * break */ - __pyx_k_tuple_8 = PyTuple_New(2); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_8)); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_8, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_8, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); - __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_9)); - __Pyx_INCREF(((PyObject *)__pyx_k_tuple_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_k_tuple_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); - - /* "sklearn/neighbors/ball_tree.pyx":496 - * self.idx_array = np.empty(0, dtype=ITYPE) - * self.node_centroid_arr = np.empty((0,0), dtype=DTYPE) - * self.node_info_arr = np.empty(0, dtype='c') # <<<<<<<<<<<<<< - * - * def __init__(self, X, ITYPE_t leaf_size=20, DTYPE_t p=2): - */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_10)); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + __pyx_v_i_node2 = __pyx_v_i_parent; + goto __pyx_L12; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":503 - * - * if X.size == 0: - * raise ValueError("X is an empty array") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1884 + * i_node2 = i_parent + * else: + * break # <<<<<<<<<<<<<< * - * if self.data.ndim != 2: + * #------------------------------------------------------------ */ - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_12)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_11)); - PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_s_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + goto __pyx_L11_break; + } + __pyx_L12:; + } + __pyx_L11_break:; + goto __pyx_L3; + } - /* "sklearn/neighbors/ball_tree.pyx":506 - * - * if self.data.ndim != 2: - * raise ValueError("X should have two dimensions") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1889 + * # Case 3a: node 1 is a leaf or is smaller: split node 2 and + * # recursively query, starting with the nearest subnode + * elif node_info1.is_leaf or (not node_info2.is_leaf # <<<<<<<<<<<<<< + * and node_info2.radius > node_info1.radius): + * reduced_dist_LB1 = min_rdist_dual(self, i_node1, + */ + if (!(__pyx_v_node_info1.is_leaf != 0)) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1890 + * # recursively query, starting with the nearest subnode + * elif node_info1.is_leaf or (not node_info2.is_leaf + * and node_info2.radius > node_info1.radius): # <<<<<<<<<<<<<< + * reduced_dist_LB1 = min_rdist_dual(self, i_node1, + * other, 2 * i_node2 + 1) + */ + __pyx_t_8 = (!(__pyx_v_node_info2.is_leaf != 0)); + if (__pyx_t_8) { + __pyx_t_21 = (__pyx_v_node_info2.radius > __pyx_v_node_info1.radius); + __pyx_t_22 = __pyx_t_21; + } else { + __pyx_t_22 = __pyx_t_8; + } + __pyx_t_8 = __pyx_t_22; + } else { + __pyx_t_8 = (__pyx_v_node_info1.is_leaf != 0); + } + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1891 + * elif node_info1.is_leaf or (not node_info2.is_leaf + * and node_info2.radius > node_info1.radius): + * reduced_dist_LB1 = min_rdist_dual(self, i_node1, # <<<<<<<<<<<<<< + * other, 2 * i_node2 + 1) + * reduced_dist_LB2 = min_rdist_dual(self, i_node1, + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 1)); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1891; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB1 = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1893 + * reduced_dist_LB1 = min_rdist_dual(self, i_node1, + * other, 2 * i_node2 + 1) + * reduced_dist_LB2 = min_rdist_dual(self, i_node1, # <<<<<<<<<<<<<< + * other, 2 * i_node2 + 2) * - * if p < 1: */ - __pyx_k_tuple_14 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_14)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_13)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, ((PyObject *)__pyx_kp_s_13)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_13)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 2)); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB2 = __pyx_t_13; - /* "sklearn/neighbors/ball_tree.pyx":509 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1896 + * other, 2 * i_node2 + 2) * - * if p < 1: - * raise ValueError("p must be greater than or equal to 1") # <<<<<<<<<<<<<< - * self.p = p + * if reduced_dist_LB1 < reduced_dist_LB2: # <<<<<<<<<<<<<< + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, + * bounds, heap, reduced_dist_LB1) + */ + __pyx_t_8 = ((__pyx_v_reduced_dist_LB1 < __pyx_v_reduced_dist_LB2) != 0); + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1897 * + * if reduced_dist_LB1 < reduced_dist_LB2: + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB1) + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 1), __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB1); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1897; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1899 + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, + * bounds, heap, reduced_dist_LB1) + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB2) + * else: + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 2), __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB2); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1899; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L13; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1902 + * bounds, heap, reduced_dist_LB2) + * else: + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB2) + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, */ - __pyx_k_tuple_16 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_16)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_15)); - PyTuple_SET_ITEM(__pyx_k_tuple_16, 0, ((PyObject *)__pyx_kp_s_15)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_15)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 2), __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB2); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/neighbors/ball_tree.pyx":513 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1904 + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, + * bounds, heap, reduced_dist_LB2) + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB1) * - * if leaf_size < 1: - * raise ValueError("leaf_size must be greater than or equal to 1") # <<<<<<<<<<<<<< - * self.leaf_size = leaf_size + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 1), __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB1); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1904; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L13:; + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1911 + * # recursively query, starting with the nearest subnode + * else: + * reduced_dist_LB1 = min_rdist_dual(self, 2 * i_node1 + 1, # <<<<<<<<<<<<<< + * other, i_node2) + * reduced_dist_LB2 = min_rdist_dual(self, 2 * i_node1 + 2, + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist_dual(__pyx_v_self, ((2 * __pyx_v_i_node1) + 1), __pyx_v_other, __pyx_v_i_node2); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1911; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB1 = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1913 + * reduced_dist_LB1 = min_rdist_dual(self, 2 * i_node1 + 1, + * other, i_node2) + * reduced_dist_LB2 = min_rdist_dual(self, 2 * i_node1 + 2, # <<<<<<<<<<<<<< + * other, i_node2) * */ - __pyx_k_tuple_18 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_18)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_17)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 0, ((PyObject *)__pyx_kp_s_17)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_17)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_18)); + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist_dual(__pyx_v_self, ((2 * __pyx_v_i_node1) + 2), __pyx_v_other, __pyx_v_i_node2); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1913; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB2 = __pyx_t_13; - /* "sklearn/neighbors/ball_tree.pyx":615 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1916 + * other, i_node2) * - * if X.shape[-1] != self.data.shape[1]: - * raise ValueError("query data dimension must match BallTree " # <<<<<<<<<<<<<< - * "data dimension") + * if reduced_dist_LB1 < reduced_dist_LB2: # <<<<<<<<<<<<<< + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, + * bounds, heap, reduced_dist_LB1) + */ + __pyx_t_8 = ((__pyx_v_reduced_dist_LB1 < __pyx_v_reduced_dist_LB2) != 0); + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1917 * + * if reduced_dist_LB1 < reduced_dist_LB2: + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB1) + * self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, ((2 * __pyx_v_i_node1) + 1), __pyx_v_other, __pyx_v_i_node2, __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB1); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1917; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1919 + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, + * bounds, heap, reduced_dist_LB1) + * self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB2) + * else: + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, ((2 * __pyx_v_i_node1) + 2), __pyx_v_other, __pyx_v_i_node2, __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB2); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1919; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1922 + * bounds, heap, reduced_dist_LB2) + * else: + * self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB2) + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, */ - __pyx_k_tuple_21 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_21)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 615; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_21)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_20)); - PyTuple_SET_ITEM(__pyx_k_tuple_21, 0, ((PyObject *)__pyx_kp_s_20)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_20)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_21)); + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, ((2 * __pyx_v_i_node1) + 2), __pyx_v_other, __pyx_v_i_node2, __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB2); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/neighbors/ball_tree.pyx":619 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1924 + * self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, + * bounds, heap, reduced_dist_LB2) + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB1) + * return 0 + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, ((2 * __pyx_v_i_node1) + 1), __pyx_v_other, __pyx_v_i_node2, __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB1); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1924; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L14:; + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1926 + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, + * bounds, heap, reduced_dist_LB1) + * return 0 # <<<<<<<<<<<<<< * - * if k > self.data.shape[0]: - * raise ValueError("k must be less than or equal " # <<<<<<<<<<<<<< - * "to the number of training points") + * cdef int _query_dual_breadthfirst(self, BinaryTree other, + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1826 + * return 0 * + * cdef int _query_dual_depthfirst(self, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree other, ITYPE_t i_node2, + * DTYPE_t[::1] bounds, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree._query_dual_depthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1928 + * return 0 + * + * cdef int _query_dual_breadthfirst(self, BinaryTree other, # <<<<<<<<<<<<<< + * NeighborsHeap heap, + * NodeHeap nodeheap) except -1: + */ + +static int __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__query_dual_breadthfirst(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_other, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_heap, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_nodeheap) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB; + __Pyx_memviewslice __pyx_v_bounds = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *__pyx_v_node_data1; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *__pyx_v_node_data2; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info1; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_v_nodeheap_item; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_6; + Py_ssize_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_16; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_17; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_18; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_19; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_20; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_21; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_22; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_23; + int __pyx_t_24; + int __pyx_t_25; + long __pyx_t_26; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_query_dual_breadthfirst", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1934 + * cdef ITYPE_t i, i1, i2, i_node1, i_node2, i_pt + * cdef DTYPE_t dist_pt, reduced_dist_LB + * cdef DTYPE_t[::1] bounds = np.inf + np.zeros(other.node_data.shape[0]) # <<<<<<<<<<<<<< + * cdef NodeData_t* node_data1 = &self.node_data[0] + * cdef NodeData_t* node_data2 = &other.node_data[0] + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_v_other->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = PyInt_FromSsize_t((__pyx_v_other->node_data.shape[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_Add(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(__pyx_t_4); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_bounds = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1935 + * cdef DTYPE_t dist_pt, reduced_dist_LB + * cdef DTYPE_t[::1] bounds = np.inf + np.zeros(other.node_data.shape[0]) + * cdef NodeData_t* node_data1 = &self.node_data[0] # <<<<<<<<<<<<<< + * cdef NodeData_t* node_data2 = &other.node_data[0] + * cdef NodeData_t node_info1, node_info2 + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1935; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_6 = 0; + __pyx_v_node_data1 = (&(*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_6)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1936 + * cdef DTYPE_t[::1] bounds = np.inf + np.zeros(other.node_data.shape[0]) + * cdef NodeData_t* node_data1 = &self.node_data[0] + * cdef NodeData_t* node_data2 = &other.node_data[0] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info1, node_info2 + * cdef DTYPE_t* data1 = &self.data[0, 0] + */ + if (unlikely(!__pyx_v_other->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1936; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = 0; + __pyx_v_node_data2 = (&(*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_other->node_data.data) + __pyx_t_7)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1938 + * cdef NodeData_t* node_data2 = &other.node_data[0] + * cdef NodeData_t node_info1, node_info2 + * cdef DTYPE_t* data1 = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t n_features = self.data.shape[1] */ - __pyx_k_tuple_23 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_23)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_22)); - PyTuple_SET_ITEM(__pyx_k_tuple_23, 0, ((PyObject *)__pyx_kp_s_22)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_22)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_23)); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1938; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_8 = 0; + __pyx_t_9 = 0; + __pyx_v_data1 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_8 * __pyx_v_self->data.strides[0]) )) + __pyx_t_9)) )))); - /* "sklearn/neighbors/ball_tree.pyx":639 - * # initialize arrays. This is only needed for correct behavior of - * # the warning flag. - * distances.fill(-9999) # <<<<<<<<<<<<<< - * idx_array.fill(-9999) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1939 + * cdef NodeData_t node_info1, node_info2 + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] * */ - __pyx_k_tuple_24 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 639; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_24)); - __Pyx_INCREF(__pyx_int_neg_9999); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 0, __pyx_int_neg_9999); - __Pyx_GIVEREF(__pyx_int_neg_9999); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_24)); + if (unlikely(!__pyx_v_other->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1939; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = 0; + __pyx_t_11 = 0; + __pyx_v_data2 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_other->data.data + __pyx_t_10 * __pyx_v_other->data.strides[0]) )) + __pyx_t_11)) )))); - /* "sklearn/neighbors/ball_tree.pyx":640 - * # the warning flag. - * distances.fill(-9999) - * idx_array.fill(-9999) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1940 + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< * - * cdef np.ndarray Xi + * # Set up the node heap and push the head nodes onto it */ - __pyx_k_tuple_25 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_25)); - __Pyx_INCREF(__pyx_int_neg_9999); - PyTuple_SET_ITEM(__pyx_k_tuple_25, 0, __pyx_int_neg_9999); - __Pyx_GIVEREF(__pyx_int_neg_9999); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_25)); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1940; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); - /* "sklearn/neighbors/ball_tree.pyx":739 - * """ - * if count_only and return_distance: - * raise ValueError("count_only and return_distance " # <<<<<<<<<<<<<< - * "cannot both be true") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1944 + * # Set up the node heap and push the head nodes onto it + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_rdist_dual(self, 0, other, 0) # <<<<<<<<<<<<<< + * nodeheap_item.i1 = 0 + * nodeheap_item.i2 = 0 + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist_dual(__pyx_v_self, 0, __pyx_v_other, 0); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1945 + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_rdist_dual(self, 0, other, 0) + * nodeheap_item.i1 = 0 # <<<<<<<<<<<<<< + * nodeheap_item.i2 = 0 + * nodeheap.push(nodeheap_item) + */ + __pyx_v_nodeheap_item.i1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1946 + * nodeheap_item.val = min_rdist_dual(self, 0, other, 0) + * nodeheap_item.i1 = 0 + * nodeheap_item.i2 = 0 # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) * */ - __pyx_k_tuple_30 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_30)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_30)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_29)); - PyTuple_SET_ITEM(__pyx_k_tuple_30, 0, ((PyObject *)__pyx_kp_s_29)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_29)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_30)); + __pyx_v_nodeheap_item.i2 = 0; - /* "sklearn/neighbors/ball_tree.pyx":743 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1947 + * nodeheap_item.i1 = 0 + * nodeheap_item.i2 = 0 + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< * - * if sort_results and not return_distance: - * raise ValueError("return_distance must be True if sort_distances " # <<<<<<<<<<<<<< - * "is True") + * while nodeheap.n > 0: + */ + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1947; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1949 + * nodeheap.push(nodeheap_item) * + * while nodeheap.n > 0: # <<<<<<<<<<<<<< + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val */ - __pyx_k_tuple_32 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_32)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 743; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_32)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_31)); - PyTuple_SET_ITEM(__pyx_k_tuple_32, 0, ((PyObject *)__pyx_kp_s_31)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_31)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_32)); + while (1) { + __pyx_t_14 = ((__pyx_v_nodeheap->n > 0) != 0); + if (!__pyx_t_14) break; - /* "sklearn/neighbors/ball_tree.pyx":753 - * X = array2d(X, dtype=DTYPE, order='C') - * if X.shape[-1] != self.data.shape[1]: - * raise ValueError("query data dimension must match BallTree " # <<<<<<<<<<<<<< - * "data dimension") + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1950 * + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() # <<<<<<<<<<<<<< + * reduced_dist_LB = nodeheap_item.val + * i_node1 = nodeheap_item.i1 */ - __pyx_k_tuple_33 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_33)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 753; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_33)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_20)); - PyTuple_SET_ITEM(__pyx_k_tuple_33, 0, ((PyObject *)__pyx_kp_s_20)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_20)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_33)); + __pyx_v_nodeheap_item = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->pop(__pyx_v_nodeheap); - /* "sklearn/neighbors/ball_tree.pyx":759 - * r = np.asarray(r, dtype=DTYPE, order='C') - * r = np.atleast_1d(r) - * if r.shape == (1,): # <<<<<<<<<<<<<< - * r = r[0] * np.ones(X.shape[:-1], dtype=np.double) - * else: + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1951 + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val # <<<<<<<<<<<<<< + * i_node1 = nodeheap_item.i1 + * i_node2 = nodeheap_item.i2 */ - __pyx_k_tuple_34 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_34)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 759; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_34)); - __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_k_tuple_34, 0, __pyx_int_1); - __Pyx_GIVEREF(__pyx_int_1); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_34)); + __pyx_t_12 = __pyx_v_nodeheap_item.val; + __pyx_v_reduced_dist_LB = __pyx_t_12; - /* "sklearn/neighbors/ball_tree.pyx":763 - * else: - * if r.shape != X.shape[:-1]: - * raise ValueError("r must be broadcastable to X.shape") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1952 + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val + * i_node1 = nodeheap_item.i1 # <<<<<<<<<<<<<< + * i_node2 = nodeheap_item.i2 * - * # flatten X and r for iteration */ - __pyx_k_tuple_36 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_36)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 763; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_36)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_35)); - PyTuple_SET_ITEM(__pyx_k_tuple_36, 0, ((PyObject *)__pyx_kp_s_35)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_35)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_36)); + __pyx_t_15 = __pyx_v_nodeheap_item.i1; + __pyx_v_i_node1 = __pyx_t_15; - /* "sklearn/neighbors/ball_tree.pyx":768 - * orig_shape = X.shape - * X = X.reshape((-1, X.shape[-1])) - * r = r.reshape(-1) # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1953 + * reduced_dist_LB = nodeheap_item.val + * i_node1 = nodeheap_item.i1 + * i_node2 = nodeheap_item.i2 # <<<<<<<<<<<<<< * - * cdef stack node_stack + * node_info1 = node_data1[i_node1] */ - __pyx_k_tuple_37 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_37)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_37)); - __Pyx_INCREF(__pyx_int_neg_1); - PyTuple_SET_ITEM(__pyx_k_tuple_37, 0, __pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_int_neg_1); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_37)); + __pyx_t_15 = __pyx_v_nodeheap_item.i2; + __pyx_v_i_node2 = __pyx_t_15; - /* "sklearn/neighbors/ball_tree.pyx":887 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1955 + * i_node2 = nodeheap_item.i2 * - * if parent_info.is_leaf: - * raise ValueError("Fatal: parent is a leaf. Memory " # <<<<<<<<<<<<<< - * "allocation is flawed") + * node_info1 = node_data1[i_node1] # <<<<<<<<<<<<<< + * node_info2 = node_data2[i_node2] * */ - __pyx_k_tuple_39 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_39)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_39)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_38)); - PyTuple_SET_ITEM(__pyx_k_tuple_39, 0, ((PyObject *)__pyx_kp_s_38)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_38)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_39)); + __pyx_v_node_info1 = (__pyx_v_node_data1[__pyx_v_i_node1]); - /* "sklearn/neighbors/ball_tree.pyx":912 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1956 * - * if n_points == 0: - * raise ValueError("zero-sized node") # <<<<<<<<<<<<<< + * node_info1 = node_data1[i_node1] + * node_info2 = node_data2[i_node2] # <<<<<<<<<<<<<< * - * elif n_points == 1: + * #------------------------------------------------------------ */ - __pyx_k_tuple_41 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_41)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 912; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_41)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_40)); - PyTuple_SET_ITEM(__pyx_k_tuple_41, 0, ((PyObject *)__pyx_kp_s_40)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_40)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_41)); + __pyx_v_node_info2 = (__pyx_v_node_data2[__pyx_v_i_node2]); - /* "numpy.pxd":211 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1961 + * # Case 1: nodes are further apart than the current bound: + * # trim both from the query + * if reduced_dist_LB > bounds[i_node2]: # <<<<<<<<<<<<<< + * pass * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_43 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_43)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_43)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_42)); - PyTuple_SET_ITEM(__pyx_k_tuple_43, 0, ((PyObject *)__pyx_kp_u_42)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_42)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_43)); + __pyx_t_15 = __pyx_v_i_node2; + __pyx_t_14 = ((__pyx_v_reduced_dist_LB > (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_15)) )))) != 0); + if (__pyx_t_14) { + goto __pyx_L5; + } - /* "numpy.pxd":215 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1967 + * # Case 2: both nodes are leaves: + * # do a brute-force search comparing all pairs + * elif node_info1.is_leaf and node_info2.is_leaf: # <<<<<<<<<<<<<< + * bounds[i_node2] = -1 * - * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_45 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_45)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_45)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_44)); - PyTuple_SET_ITEM(__pyx_k_tuple_45, 0, ((PyObject *)__pyx_kp_u_44)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_44)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_45)); + if ((__pyx_v_node_info1.is_leaf != 0)) { + __pyx_t_14 = (__pyx_v_node_info2.is_leaf != 0); + } else { + __pyx_t_14 = (__pyx_v_node_info1.is_leaf != 0); + } + if (__pyx_t_14) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1968 + * # do a brute-force search comparing all pairs + * elif node_info1.is_leaf and node_info2.is_leaf: + * bounds[i_node2] = -1 # <<<<<<<<<<<<<< + * + * for i2 in range(node_info2.idx_start, node_info2.idx_end): */ - __pyx_k_tuple_47 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_47)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_47)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_46)); - PyTuple_SET_ITEM(__pyx_k_tuple_47, 0, ((PyObject *)__pyx_kp_u_46)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_46)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_47)); + __pyx_t_16 = __pyx_v_i_node2; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_16)) )) = -1.0; - /* "numpy.pxd":795 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1970 + * bounds[i_node2] = -1 * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * for i2 in range(node_info2.idx_start, node_info2.idx_end): # <<<<<<<<<<<<<< + * i_pt = other.idx_array[i2] * - * if ((child.byteorder == '>' and little_endian) or */ - __pyx_k_tuple_50 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_50)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_50)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_49)); - PyTuple_SET_ITEM(__pyx_k_tuple_50, 0, ((PyObject *)__pyx_kp_u_49)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_49)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_50)); + __pyx_t_17 = __pyx_v_node_info2.idx_end; + for (__pyx_t_18 = __pyx_v_node_info2.idx_start; __pyx_t_18 < __pyx_t_17; __pyx_t_18+=1) { + __pyx_v_i2 = __pyx_t_18; - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * # One could encode it in the format string and have Cython - * # complain instead, BUT: < and > in format strings also imply + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1971 + * + * for i2 in range(node_info2.idx_start, node_info2.idx_end): + * i_pt = other.idx_array[i2] # <<<<<<<<<<<<<< + * + * if heap.largest(i_pt) <= reduced_dist_LB: */ - __pyx_k_tuple_51 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_51)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_51)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_46)); - PyTuple_SET_ITEM(__pyx_k_tuple_51, 0, ((PyObject *)__pyx_kp_u_46)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_46)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_51)); + if (unlikely(!__pyx_v_other->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1971; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_19 = __pyx_v_i2; + __pyx_v_i_pt = (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_other->idx_array.data) + __pyx_t_19)) ))); - /* "numpy.pxd":819 - * t = child.type_num - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1973 + * i_pt = other.idx_array[i2] + * + * if heap.largest(i_pt) <= reduced_dist_LB: # <<<<<<<<<<<<<< + * continue * - * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_53 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_53)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_53)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_52)); - PyTuple_SET_ITEM(__pyx_k_tuple_53, 0, ((PyObject *)__pyx_kp_u_52)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_52)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_53)); - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_5 = PyInt_FromLong(5); if (unlikely(!__pyx_int_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_neg_9999 = PyInt_FromLong(-9999); if (unlikely(!__pyx_int_neg_9999)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - return 0; - __pyx_L1_error:; - return -1; -} - -#if PY_MAJOR_VERSION < 3 -PyMODINIT_FUNC initball_tree(void); /*proto*/ -PyMODINIT_FUNC initball_tree(void) -#else -PyMODINIT_FUNC PyInit_ball_tree(void); /*proto*/ -PyMODINIT_FUNC PyInit_ball_tree(void) -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t __pyx_t_3; - __Pyx_RefNannyDeclarations - #if CYTHON_REFNANNY - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); - if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); - } - #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_ball_tree(void)"); - if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __pyx_binding_PyCFunctionType_USED - if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #endif - /*--- Module creation code ---*/ - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("ball_tree"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_54), 0, PYTHON_API_VERSION); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); - #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - /*--- Initialize various global constants etc. ---*/ - if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_module_is_main_sklearn__neighbors__ball_tree) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - } - /*--- Builtin init code ---*/ - if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Constants init code ---*/ - if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Global init code ---*/ - /*--- Variable export code ---*/ - /*--- Function export code ---*/ - /*--- Type init code ---*/ - __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BallTree = &__pyx_vtable_7sklearn_9neighbors_9ball_tree_BallTree; - __pyx_vtable_7sklearn_9neighbors_9ball_tree_BallTree.build_tree_ = (void (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *))__pyx_f_7sklearn_9neighbors_9ball_tree_8BallTree_build_tree_; - __pyx_vtable_7sklearn_9neighbors_9ball_tree_BallTree.query_one_ = (void (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t))__pyx_f_7sklearn_9neighbors_9ball_tree_8BallTree_query_one_; - __pyx_vtable_7sklearn_9neighbors_9ball_tree_BallTree.query_radius_count_ = (__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *))__pyx_f_7sklearn_9neighbors_9ball_tree_8BallTree_query_radius_count_; - __pyx_vtable_7sklearn_9neighbors_9ball_tree_BallTree.query_radius_idx_only_ = (__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *))__pyx_f_7sklearn_9neighbors_9ball_tree_8BallTree_query_radius_idx_only_; - __pyx_vtable_7sklearn_9neighbors_9ball_tree_BallTree.query_radius_distances_ = (__pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t, __pyx_t_7sklearn_9neighbors_9ball_tree_ITYPE_t *, __pyx_t_7sklearn_9neighbors_9ball_tree_DTYPE_t *, struct __pyx_t_7sklearn_9neighbors_9ball_tree_stack *))__pyx_f_7sklearn_9neighbors_9ball_tree_8BallTree_query_radius_distances_; - if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_9ball_tree_BallTree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_9ball_tree_BallTree.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BallTree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "BallTree", (PyObject *)&__pyx_type_7sklearn_9neighbors_9ball_tree_BallTree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_9neighbors_9ball_tree_BallTree = &__pyx_type_7sklearn_9neighbors_9ball_tree_BallTree; - /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Variable import code ---*/ - /*--- Function import code ---*/ - /*--- Execution code ---*/ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1973; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = ((__pyx_t_12 <= __pyx_v_reduced_dist_LB) != 0); + if (__pyx_t_14) { - /* "sklearn/neighbors/ball_tree.pyx":190 - * """ + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1974 * - * import numpy as np # <<<<<<<<<<<<<< + * if heap.largest(i_pt) <= reduced_dist_LB: + * continue # <<<<<<<<<<<<<< * - * cimport numpy as np + * for i1 in range(node_info1.idx_start, node_info1.idx_end): */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L6_continue; + } - /* "sklearn/neighbors/ball_tree.pyx":196 - * from libc cimport stdlib + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1976 + * continue * - * from ..utils import array2d # <<<<<<<<<<<<<< - * - * ###################################################################### + * for i1 in range(node_info1.idx_start, node_info1.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.rdist( + * data1 + n_features * self.idx_array[i1], */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__array2d)); - PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s__array2d)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__array2d)); - __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s__utils), ((PyObject *)__pyx_t_1), 2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__array2d); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__array2d, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_20 = __pyx_v_node_info1.idx_end; + for (__pyx_t_21 = __pyx_v_node_info1.idx_start; __pyx_t_21 < __pyx_t_20; __pyx_t_21+=1) { + __pyx_v_i1 = __pyx_t_21; - /* "sklearn/neighbors/ball_tree.pyx":202 - * # - * # type used for data - * DTYPE = np.float64 # <<<<<<<<<<<<<< - * ctypedef np.float64_t DTYPE_t + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1978 + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * dist_pt = self.rdist( + * data1 + n_features * self.idx_array[i1], # <<<<<<<<<<<<<< + * data2 + n_features * i_pt, + * n_features) + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1978; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_22 = __pyx_v_i1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1977 * + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * dist_pt = self.rdist( # <<<<<<<<<<<<<< + * data1 + n_features * self.idx_array[i1], + * data2 + n_features * i_pt, */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__DTYPE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_rdist(__pyx_v_self, (__pyx_v_data1 + (__pyx_v_n_features * (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_22)) ))))), (__pyx_v_data2 + (__pyx_v_n_features * __pyx_v_i_pt)), __pyx_v_n_features); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_12; - /* "sklearn/neighbors/ball_tree.pyx":207 - * # type used for indices & counts - * # warning: there will be problems if this is switched to an unsigned type! - * ITYPE = np.int32 # <<<<<<<<<<<<<< - * ctypedef np.int32_t ITYPE_t + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1981 + * data2 + n_features * i_pt, + * n_features) + * if dist_pt < heap.largest(i_pt): # <<<<<<<<<<<<<< + * heap.push(i_pt, dist_pt, self.idx_array[i1]) * */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__int32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__ITYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1981; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = ((__pyx_v_dist_pt < __pyx_t_12) != 0); + if (__pyx_t_14) { - /* "sklearn/neighbors/ball_tree.pyx":211 + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1982 + * n_features) + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i1]) # <<<<<<<<<<<<<< * - * # infinity - * cdef DTYPE_t infinity = np.inf # <<<<<<<<<<<<<< + * # keep track of node bound + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1982; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_23 = __pyx_v_i1; + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_i_pt, __pyx_v_dist_pt, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_23)) ))), 0); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1982; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L11; + } + __pyx_L11:; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1985 * + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], # <<<<<<<<<<<<<< + * heap.largest(i_pt)) * */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__inf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_3 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_3 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_7sklearn_9neighbors_9ball_tree_infinity = __pyx_t_3; + __pyx_t_20 = __pyx_v_i_node2; - /* "sklearn/neighbors/ball_tree.pyx":391 - * # newObj function - * # this is a helper function for pickling - * def newObj(obj): # <<<<<<<<<<<<<< - * return obj.__new__(obj) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1986 + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], + * heap.largest(i_pt)) # <<<<<<<<<<<<<< * + * #------------------------------------------------------------ */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_9ball_tree_newObj, NULL, __pyx_n_s_55); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__newObj, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1986; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/neighbors/ball_tree.pyx":565 - * self.n_nodes = state[7] + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1985 + * + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], # <<<<<<<<<<<<<< + * heap.largest(i_pt)) * - * def query(self, X, k=1, return_distance=True): # <<<<<<<<<<<<<< - * """ - * query(X, k=1, return_distance=True) */ - __pyx_t_1 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_k_19 = __pyx_t_1; - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; + __pyx_t_21 = __pyx_v_i_node2; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_21)) )) = __pyx_f_7sklearn_9neighbors_9ball_tree_fmax((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_20)) ))), __pyx_t_12); + __pyx_L6_continue:; + } + goto __pyx_L5; + } - /* "sklearn/neighbors/ball_tree.pyx":672 - * return idx_array.reshape((orig_shape[:-1]) + (k,)) + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1991 + * # Case 3a: node 1 is a leaf or is smaller: split node 2 and + * # recursively query, starting with the nearest subnode + * elif node_info1.is_leaf or (not node_info2.is_leaf # <<<<<<<<<<<<<< + * and (node_info2.radius + * > node_info1.radius)): + */ + if (!(__pyx_v_node_info1.is_leaf != 0)) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1992 + * # recursively query, starting with the nearest subnode + * elif node_info1.is_leaf or (not node_info2.is_leaf + * and (node_info2.radius # <<<<<<<<<<<<<< + * > node_info1.radius)): + * nodeheap_item.i1 = i_node1 + */ + __pyx_t_14 = (!(__pyx_v_node_info2.is_leaf != 0)); + if (__pyx_t_14) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1993 + * elif node_info1.is_leaf or (not node_info2.is_leaf + * and (node_info2.radius + * > node_info1.radius)): # <<<<<<<<<<<<<< + * nodeheap_item.i1 = i_node1 + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + */ + __pyx_t_24 = (__pyx_v_node_info2.radius > __pyx_v_node_info1.radius); + __pyx_t_25 = __pyx_t_24; + } else { + __pyx_t_25 = __pyx_t_14; + } + __pyx_t_14 = __pyx_t_25; + } else { + __pyx_t_14 = (__pyx_v_node_info1.is_leaf != 0); + } + if (__pyx_t_14) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1994 + * and (node_info2.radius + * > node_info1.radius)): + * nodeheap_item.i1 = i_node1 # <<<<<<<<<<<<<< + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * nodeheap_item.i2 = i2 + */ + __pyx_v_nodeheap_item.i1 = __pyx_v_i_node1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1995 + * > node_info1.radius)): + * nodeheap_item.i1 = i_node1 + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): # <<<<<<<<<<<<<< + * nodeheap_item.i2 = i2 + * nodeheap_item.val = min_rdist_dual(self, i_node1, + */ + __pyx_t_26 = ((2 * __pyx_v_i_node2) + 3); + for (__pyx_t_17 = ((2 * __pyx_v_i_node2) + 1); __pyx_t_17 < __pyx_t_26; __pyx_t_17+=1) { + __pyx_v_i2 = __pyx_t_17; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1996 + * nodeheap_item.i1 = i_node1 + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * nodeheap_item.i2 = i2 # <<<<<<<<<<<<<< + * nodeheap_item.val = min_rdist_dual(self, i_node1, + * other, i2) + */ + __pyx_v_nodeheap_item.i2 = __pyx_v_i2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1997 + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * nodeheap_item.i2 = i2 + * nodeheap_item.val = min_rdist_dual(self, i_node1, # <<<<<<<<<<<<<< + * other, i2) + * nodeheap.push(nodeheap_item) + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, __pyx_v_i2); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1999 + * nodeheap_item.val = min_rdist_dual(self, i_node1, + * other, i2) + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< * - * def query_radius(self, X, r, return_distance=False, # <<<<<<<<<<<<<< - * count_only=False, sort_results=False): - * """ + * #------------------------------------------------------------ */ - __pyx_t_1 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 672; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_k_26 = __pyx_t_1; - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1999; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L5; + } + /*else*/ { - /* "sklearn/neighbors/ball_tree.pyx":673 - * - * def query_radius(self, X, r, return_distance=False, - * count_only=False, sort_results=False): # <<<<<<<<<<<<<< - * """ - * query_radius(self, X, r, count_only = False): + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2005 + * # recursively query, starting with the nearest subnode + * else: + * nodeheap_item.i2 = i_node2 # <<<<<<<<<<<<<< + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * nodeheap_item.i1 = i1 */ - __pyx_t_1 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 673; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_k_27 = __pyx_t_1; - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 673; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_k_28 = __pyx_t_1; - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; + __pyx_v_nodeheap_item.i2 = __pyx_v_i_node2; - /* "sklearn/neighbors/ball_tree.pyx":2 - * - * # Author: Jake Vanderplas # <<<<<<<<<<<<<< - * # License: BSD + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2006 + * else: + * nodeheap_item.i2 = i_node2 + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): # <<<<<<<<<<<<<< + * nodeheap_item.i1 = i1 + * nodeheap_item.val = min_rdist_dual(self, i1, + */ + __pyx_t_26 = ((2 * __pyx_v_i_node1) + 3); + for (__pyx_t_17 = ((2 * __pyx_v_i_node1) + 1); __pyx_t_17 < __pyx_t_26; __pyx_t_17+=1) { + __pyx_v_i1 = __pyx_t_17; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2007 + * nodeheap_item.i2 = i_node2 + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * nodeheap_item.i1 = i1 # <<<<<<<<<<<<<< + * nodeheap_item.val = min_rdist_dual(self, i1, + * other, i_node2) + */ + __pyx_v_nodeheap_item.i1 = __pyx_v_i1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2008 + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * nodeheap_item.i1 = i1 + * nodeheap_item.val = min_rdist_dual(self, i1, # <<<<<<<<<<<<<< + * other, i_node2) + * nodeheap.push(nodeheap_item) + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist_dual(__pyx_v_self, __pyx_v_i1, __pyx_v_other, __pyx_v_i_node2); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2008; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2010 + * nodeheap_item.val = min_rdist_dual(self, i1, + * other, i_node2) + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2010; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + __pyx_L5:; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2011 + * other, i_node2) + * nodeheap.push(nodeheap_item) + * return 0 # <<<<<<<<<<<<<< * + * cdef ITYPE_t _query_radius_single(self, */ - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_56), ((PyObject *)__pyx_kp_u_57)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_58), ((PyObject *)__pyx_kp_u_59)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_r = 0; + goto __pyx_L0; - /* "numpy.pxd":971 - * arr.base = baseptr + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1928 + * return 0 * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * if arr.base is NULL: - * return None + * cdef int _query_dual_breadthfirst(self, BinaryTree other, # <<<<<<<<<<<<<< + * NeighborsHeap heap, + * NodeHeap nodeheap) except -1: */ - goto __pyx_L0; + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); - if (__pyx_m) { - __Pyx_AddTraceback("init sklearn.neighbors.ball_tree", __pyx_clineno, __pyx_lineno, __pyx_filename); - Py_DECREF(__pyx_m); __pyx_m = 0; - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init sklearn.neighbors.ball_tree"); - } + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree._query_dual_breadthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_bounds, 1); __Pyx_RefNannyFinishContext(); - #if PY_MAJOR_VERSION < 3 - return; - #else - return __pyx_m; - #endif + return __pyx_r; } -/* Runtime support code */ +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2013 + * return 0 + * + * cdef ITYPE_t _query_radius_single(self, # <<<<<<<<<<<<<< + * ITYPE_t i_node, + * DTYPE_t* pt, DTYPE_t r, + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__query_radius_single(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_r, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_indices, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_distances, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_count, int __pyx_v_count_only, int __pyx_v_return_distance) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_r; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + PyObject *__pyx_t_11 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_query_radius_single", 0); -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule((char *)modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif /* CYTHON_REFNANNY */ + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2022 + * int return_distance) except -1: + * """recursive single-tree radius query, depth-first""" + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2022; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_1 * __pyx_v_self->data.strides[0]) )) + __pyx_t_2)) )))); -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } - } - return result; -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2023 + * """recursive single-tree radius query, depth-first""" + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef NodeData_t node_info = self.node_data[i_node] + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2023; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_3)) )))); -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2024 + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info = self.node_data[i_node] + * + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2024; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2025 + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef NodeData_t node_info = self.node_data[i_node] # <<<<<<<<<<<<<< + * + * cdef ITYPE_t i + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2025; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = __pyx_v_i_node; + __pyx_v_node_info = (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_4)) ))); -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { - PyThreadState *tstate = PyThreadState_GET(); - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2030 + * cdef DTYPE_t reduced_r + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 # <<<<<<<<<<<<<< + * min_max_dist(self, i_node, pt, &dist_LB, &dist_UB) + * + */ + __pyx_v_dist_LB = 0.0; + __pyx_v_dist_UB = 0.0; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2031 + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 + * min_max_dist(self, i_node, pt, &dist_LB, &dist_UB) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_max_dist(__pyx_v_self, __pyx_v_i_node, __pyx_v_pt, (&__pyx_v_dist_LB), (&__pyx_v_dist_UB)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2031; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2036 + * # Case 1: all node points are outside distance r. + * # prune this branch. + * if dist_LB > r: # <<<<<<<<<<<<<< + * pass + * + */ + __pyx_t_6 = ((__pyx_v_dist_LB > __pyx_v_r) != 0); + if (__pyx_t_6) { + goto __pyx_L3; + } -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ - Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2042 + * # Case 2: all node points are within distance r + * # add all points to neighbors + * elif dist_UB <= r: # <<<<<<<<<<<<<< + * if count_only: + * count += (node_info.idx_end - node_info.idx_start) + */ + __pyx_t_6 = ((__pyx_v_dist_UB <= __pyx_v_r) != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2043 + * # add all points to neighbors + * elif dist_UB <= r: + * if count_only: # <<<<<<<<<<<<<< + * count += (node_info.idx_end - node_info.idx_start) + * else: + */ + __pyx_t_6 = (__pyx_v_count_only != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2044 + * elif dist_UB <= r: + * if count_only: + * count += (node_info.idx_end - node_info.idx_start) # <<<<<<<<<<<<<< + * else: + * for i in range(node_info.idx_start, node_info.idx_end): + */ + __pyx_v_count = (__pyx_v_count + (__pyx_v_node_info.idx_end - __pyx_v_node_info.idx_start)); + goto __pyx_L4; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2046 + * count += (node_info.idx_end - node_info.idx_start) + * else: + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count too big: " + */ + __pyx_t_7 = __pyx_v_node_info.idx_end; + for (__pyx_t_8 = __pyx_v_node_info.idx_start; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2047 + * else: + * for i in range(node_info.idx_start, node_info.idx_end): + * if (count < 0) or (count >= self.data.shape[0]): # <<<<<<<<<<<<<< + * raise ValueError("Fatal: count too big: " + * "this should never happen") + */ + __pyx_t_6 = ((__pyx_v_count < 0) != 0); + if (!__pyx_t_6) { + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2047; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = ((__pyx_v_count >= (__pyx_v_self->data.shape[0])) != 0); + __pyx_t_10 = __pyx_t_9; + } else { + __pyx_t_10 = __pyx_t_6; + } + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2048 + * for i in range(node_info.idx_start, node_info.idx_end): + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count too big: " # <<<<<<<<<<<<<< + * "this should never happen") + * indices[count] = idx_array[i] + */ + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__30, NULL); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2048; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + __Pyx_Raise(__pyx_t_11, 0, 0, 0); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2048; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2050 + * raise ValueError("Fatal: count too big: " + * "this should never happen") + * indices[count] = idx_array[i] # <<<<<<<<<<<<<< + * if return_distance: + * distances[count] = self.dist(pt, (data + n_features + */ + (__pyx_v_indices[__pyx_v_count]) = (__pyx_v_idx_array[__pyx_v_i]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2051 + * "this should never happen") + * indices[count] = idx_array[i] + * if return_distance: # <<<<<<<<<<<<<< + * distances[count] = self.dist(pt, (data + n_features + * * idx_array[i]), + */ + __pyx_t_10 = (__pyx_v_return_distance != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2052 + * indices[count] = idx_array[i] + * if return_distance: + * distances[count] = self.dist(pt, (data + n_features # <<<<<<<<<<<<<< + * * idx_array[i]), + * n_features) + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(__pyx_v_self, __pyx_v_pt, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2052; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + (__pyx_v_distances[__pyx_v_count]) = __pyx_t_12; + goto __pyx_L8; + } + __pyx_L8:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2055 + * * idx_array[i]), + * n_features) + * count += 1 # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_v_count = (__pyx_v_count + 1); + } + } + __pyx_L4:; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2060 + * # Case 3: this is a leaf node. Go through all points to + * # determine if they fall within radius + * elif node_info.is_leaf: # <<<<<<<<<<<<<< + * reduced_r = self.dist_metric._dist_to_rdist(r) + * + */ + __pyx_t_10 = (__pyx_v_node_info.is_leaf != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2061 + * # determine if they fall within radius + * elif node_info.is_leaf: + * reduced_r = self.dist_metric._dist_to_rdist(r) # <<<<<<<<<<<<<< + * + * for i in range(node_info.idx_start, node_info.idx_end): + */ + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->dist_metric->__pyx_vtab)->_dist_to_rdist(__pyx_v_self->dist_metric, __pyx_v_r); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_r = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2063 + * reduced_r = self.dist_metric._dist_to_rdist(r) + * + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.rdist(pt, (data + n_features * idx_array[i]), + * n_features) + */ + __pyx_t_7 = __pyx_v_node_info.idx_end; + for (__pyx_t_8 = __pyx_v_node_info.idx_start; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2064 + * + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.rdist(pt, (data + n_features * idx_array[i]), # <<<<<<<<<<<<<< + * n_features) + * if dist_pt <= reduced_r: + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_rdist(__pyx_v_self, __pyx_v_pt, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2064; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2066 + * dist_pt = self.rdist(pt, (data + n_features * idx_array[i]), + * n_features) + * if dist_pt <= reduced_r: # <<<<<<<<<<<<<< + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count out of range. " + */ + __pyx_t_10 = ((__pyx_v_dist_pt <= __pyx_v_reduced_r) != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2067 + * n_features) + * if dist_pt <= reduced_r: + * if (count < 0) or (count >= self.data.shape[0]): # <<<<<<<<<<<<<< + * raise ValueError("Fatal: count out of range. " + * "This should never happen.") + */ + __pyx_t_10 = ((__pyx_v_count < 0) != 0); + if (!__pyx_t_10) { + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2067; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_6 = ((__pyx_v_count >= (__pyx_v_self->data.shape[0])) != 0); + __pyx_t_9 = __pyx_t_6; + } else { + __pyx_t_9 = __pyx_t_10; + } + if (__pyx_t_9) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2068 + * if dist_pt <= reduced_r: + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count out of range. " # <<<<<<<<<<<<<< + * "This should never happen.") + * if count_only: + */ + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__31, NULL); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2068; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + __Pyx_Raise(__pyx_t_11, 0, 0, 0); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2068; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2070 + * raise ValueError("Fatal: count out of range. " + * "This should never happen.") + * if count_only: # <<<<<<<<<<<<<< + * pass + * else: + */ + __pyx_t_9 = (__pyx_v_count_only != 0); + if (__pyx_t_9) { + goto __pyx_L13; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2073 + * pass + * else: + * indices[count] = idx_array[i] # <<<<<<<<<<<<<< + * if return_distance: + * distances[count] =\ + */ + (__pyx_v_indices[__pyx_v_count]) = (__pyx_v_idx_array[__pyx_v_i]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2074 + * else: + * indices[count] = idx_array[i] + * if return_distance: # <<<<<<<<<<<<<< + * distances[count] =\ + * self.dist_metric._rdist_to_dist(dist_pt) + */ + __pyx_t_9 = (__pyx_v_return_distance != 0); + if (__pyx_t_9) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2076 + * if return_distance: + * distances[count] =\ + * self.dist_metric._rdist_to_dist(dist_pt) # <<<<<<<<<<<<<< + * count += 1 + * + */ + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->dist_metric->__pyx_vtab)->_rdist_to_dist(__pyx_v_self->dist_metric, __pyx_v_dist_pt); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2075 + * indices[count] = idx_array[i] + * if return_distance: + * distances[count] =\ # <<<<<<<<<<<<<< + * self.dist_metric._rdist_to_dist(dist_pt) + * count += 1 + */ + (__pyx_v_distances[__pyx_v_count]) = __pyx_t_12; + goto __pyx_L14; + } + __pyx_L14:; + } + __pyx_L13:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2077 + * distances[count] =\ + * self.dist_metric._rdist_to_dist(dist_pt) + * count += 1 # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_v_count = (__pyx_v_count + 1); + goto __pyx_L11; + } + __pyx_L11:; + } + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2082 + * # Case 4: Node is not a leaf. Recursively query subnodes + * else: + * count = self._query_radius_single(2 * i_node + 1, pt, r, # <<<<<<<<<<<<<< + * indices, distances, count, + * count_only, return_distance) + */ + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_radius_single(__pyx_v_self, ((2 * __pyx_v_i_node) + 1), __pyx_v_pt, __pyx_v_r, __pyx_v_indices, __pyx_v_distances, __pyx_v_count, __pyx_v_count_only, __pyx_v_return_distance); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2082; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_count = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2085 + * indices, distances, count, + * count_only, return_distance) + * count = self._query_radius_single(2 * i_node + 2, pt, r, # <<<<<<<<<<<<<< + * indices, distances, count, + * count_only, return_distance) + */ + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_radius_single(__pyx_v_self, ((2 * __pyx_v_i_node) + 2), __pyx_v_pt, __pyx_v_r, __pyx_v_indices, __pyx_v_distances, __pyx_v_count, __pyx_v_count_only, __pyx_v_return_distance); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_count = __pyx_t_7; + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2089 + * count_only, return_distance) + * + * return count # <<<<<<<<<<<<<< + * + * cdef DTYPE_t _kde_single_breadthfirst(self, DTYPE_t* pt, + */ + __pyx_r = __pyx_v_count; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2013 + * return 0 + * + * cdef ITYPE_t _query_radius_single(self, # <<<<<<<<<<<<<< + * ITYPE_t i_node, + * DTYPE_t* pt, DTYPE_t r, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_11); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree._query_radius_single", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2091 + * return count + * + * cdef DTYPE_t _kde_single_breadthfirst(self, DTYPE_t* pt, # <<<<<<<<<<<<<< + * KernelType kernel, DTYPE_t h, + * DTYPE_t log_knorm, + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__kde_single_breadthfirst(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType __pyx_v_kernel, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_knorm, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_atol, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_rtol, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_nodeheap, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_node_log_min_bounds, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_node_log_bound_spreads) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_N1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_N2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_global_log_min_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_global_log_bound_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_global_log_max_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *__pyx_v_node_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_N; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_density; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB_2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB_2; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_v_nodeheap_item; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_kde_single_breadthfirst", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2110 + * cdef DTYPE_t global_log_max_bound + * + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef NodeData_t* node_data = &self.node_data[0] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2110; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_1 * __pyx_v_self->data.strides[0]) )) + __pyx_t_2)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2111 + * + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] # <<<<<<<<<<<<<< + * cdef NodeData_t* node_data = &self.node_data[0] + * cdef ITYPE_t N = self.data.shape[0] + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2111; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2112 + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef NodeData_t* node_data = &self.node_data[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t N = self.data.shape[0] + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2112; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = 0; + __pyx_v_node_data = (&(*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_4)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2113 + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef NodeData_t* node_data = &self.node_data[0] + * cdef ITYPE_t N = self.data.shape[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2113; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_N = (__pyx_v_self->data.shape[0]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2114 + * cdef NodeData_t* node_data = &self.node_data[0] + * cdef ITYPE_t N = self.data.shape[0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * + * cdef NodeData_t node_info + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2114; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2118 + * cdef NodeData_t node_info + * cdef DTYPE_t dist_pt, log_density + * cdef DTYPE_t dist_LB_1 = 0, dist_LB_2 = 0 # <<<<<<<<<<<<<< + * cdef DTYPE_t dist_UB_1 = 0, dist_UB_2 = 0 + * + */ + __pyx_v_dist_LB_1 = 0.0; + __pyx_v_dist_LB_2 = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2119 + * cdef DTYPE_t dist_pt, log_density + * cdef DTYPE_t dist_LB_1 = 0, dist_LB_2 = 0 + * cdef DTYPE_t dist_UB_1 = 0, dist_UB_2 = 0 # <<<<<<<<<<<<<< + * + * cdef DTYPE_t dist_UB, dist_LB + */ + __pyx_v_dist_UB_1 = 0.0; + __pyx_v_dist_UB_2 = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2125 + * # push the top node to the heap + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_dist(self, 0, pt) # <<<<<<<<<<<<<< + * nodeheap_item.i1 = 0 + * nodeheap.push(nodeheap_item) + */ + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_dist(__pyx_v_self, 0, __pyx_v_pt); if (unlikely(__pyx_t_5 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_5; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2126 + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_dist(self, 0, pt) + * nodeheap_item.i1 = 0 # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) + * + */ + __pyx_v_nodeheap_item.i1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2127 + * nodeheap_item.val = min_dist(self, 0, pt) + * nodeheap_item.i1 = 0 + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * + * global_log_min_bound = log(N) + compute_log_kernel(max_dist(self, + */ + __pyx_t_6 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2129 + * nodeheap.push(nodeheap_item) + * + * global_log_min_bound = log(N) + compute_log_kernel(max_dist(self, # <<<<<<<<<<<<<< + * 0, pt), + * h, kernel) + */ + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_9ball_tree_max_dist(__pyx_v_self, 0, __pyx_v_pt); if (unlikely(__pyx_t_5 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2131 + * global_log_min_bound = log(N) + compute_log_kernel(max_dist(self, + * 0, pt), + * h, kernel) # <<<<<<<<<<<<<< + * global_log_max_bound = log(N) + compute_log_kernel(nodeheap_item.val, + * h, kernel) + */ + __pyx_v_global_log_min_bound = (log(__pyx_v_N) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_t_5, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2132 + * 0, pt), + * h, kernel) + * global_log_max_bound = log(N) + compute_log_kernel(nodeheap_item.val, # <<<<<<<<<<<<<< + * h, kernel) + * global_log_bound_spread = logsubexp(global_log_max_bound, + */ + __pyx_v_global_log_max_bound = (log(__pyx_v_N) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_nodeheap_item.val, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2134 + * global_log_max_bound = log(N) + compute_log_kernel(nodeheap_item.val, + * h, kernel) + * global_log_bound_spread = logsubexp(global_log_max_bound, # <<<<<<<<<<<<<< + * global_log_min_bound) + * + */ + __pyx_v_global_log_bound_spread = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp(__pyx_v_global_log_max_bound, __pyx_v_global_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2137 + * global_log_min_bound) + * + * node_log_min_bounds[0] = global_log_min_bound # <<<<<<<<<<<<<< + * node_log_bound_spreads[0] = global_log_bound_spread + * + */ + (__pyx_v_node_log_min_bounds[0]) = __pyx_v_global_log_min_bound; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2138 + * + * node_log_min_bounds[0] = global_log_min_bound + * node_log_bound_spreads[0] = global_log_bound_spread # <<<<<<<<<<<<<< + * + * while nodeheap.n > 0: + */ + (__pyx_v_node_log_bound_spreads[0]) = __pyx_v_global_log_bound_spread; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2140 + * node_log_bound_spreads[0] = global_log_bound_spread + * + * while nodeheap.n > 0: # <<<<<<<<<<<<<< + * nodeheap_item = nodeheap.pop() + * i_node = nodeheap_item.i1 + */ + while (1) { + __pyx_t_7 = ((__pyx_v_nodeheap->n > 0) != 0); + if (!__pyx_t_7) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2141 + * + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() # <<<<<<<<<<<<<< + * i_node = nodeheap_item.i1 + * + */ + __pyx_v_nodeheap_item = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->pop(__pyx_v_nodeheap); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2142 + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() + * i_node = nodeheap_item.i1 # <<<<<<<<<<<<<< + * + * node_info = node_data[i_node] + */ + __pyx_t_8 = __pyx_v_nodeheap_item.i1; + __pyx_v_i_node = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2144 + * i_node = nodeheap_item.i1 + * + * node_info = node_data[i_node] # <<<<<<<<<<<<<< + * N1 = node_info.idx_end - node_info.idx_start + * + */ + __pyx_v_node_info = (__pyx_v_node_data[__pyx_v_i_node]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2145 + * + * node_info = node_data[i_node] + * N1 = node_info.idx_end - node_info.idx_start # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_v_N1 = (__pyx_v_node_info.idx_end - __pyx_v_node_info.idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2150 + * # Case 1: local bounds are equal to within per-point tolerance. + * if (log_knorm + node_log_bound_spreads[i_node] - log(N1) + log(N) + * <= logaddexp(log_atol, (log_rtol + log_knorm # <<<<<<<<<<<<<< + * + node_log_min_bounds[i_node]))): + * pass + */ + __pyx_t_7 = (((((__pyx_v_log_knorm + (__pyx_v_node_log_bound_spreads[__pyx_v_i_node])) - log(__pyx_v_N1)) + log(__pyx_v_N)) <= __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_v_log_atol, ((__pyx_v_log_rtol + __pyx_v_log_knorm) + (__pyx_v_node_log_min_bounds[__pyx_v_i_node])))) != 0); + if (__pyx_t_7) { + goto __pyx_L5; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2157 + * # Case 2: global bounds are within rtol & atol. + * elif (log_knorm + global_log_bound_spread + * <= logaddexp(log_atol, # <<<<<<<<<<<<<< + * log_rtol + log_knorm + global_log_min_bound)): + * break + */ + __pyx_t_7 = (((__pyx_v_log_knorm + __pyx_v_global_log_bound_spread) <= __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_v_log_atol, ((__pyx_v_log_rtol + __pyx_v_log_knorm) + __pyx_v_global_log_min_bound))) != 0); + if (__pyx_t_7) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2159 + * <= logaddexp(log_atol, + * log_rtol + log_knorm + global_log_min_bound)): + * break # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + goto __pyx_L4_break; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2163 + * #------------------------------------------------------------ + * # Case 3: node is a leaf. Count contributions from all points + * elif node_info.is_leaf: # <<<<<<<<<<<<<< + * global_log_min_bound =\ + * logsubexp(global_log_min_bound, + */ + __pyx_t_7 = (__pyx_v_node_info.is_leaf != 0); + if (__pyx_t_7) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2165 + * elif node_info.is_leaf: + * global_log_min_bound =\ + * logsubexp(global_log_min_bound, # <<<<<<<<<<<<<< + * node_log_min_bounds[i_node]) + * global_log_bound_spread =\ + */ + __pyx_v_global_log_min_bound = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp(__pyx_v_global_log_min_bound, (__pyx_v_node_log_min_bounds[__pyx_v_i_node])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2168 + * node_log_min_bounds[i_node]) + * global_log_bound_spread =\ + * logsubexp(global_log_bound_spread, # <<<<<<<<<<<<<< + * node_log_bound_spreads[i_node]) + * for i in range(node_info.idx_start, node_info.idx_end): + */ + __pyx_v_global_log_bound_spread = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp(__pyx_v_global_log_bound_spread, (__pyx_v_node_log_bound_spreads[__pyx_v_i_node])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2170 + * logsubexp(global_log_bound_spread, + * node_log_bound_spreads[i_node]) + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.dist(pt, data + n_features * idx_array[i], + * n_features) + */ + __pyx_t_8 = __pyx_v_node_info.idx_end; + for (__pyx_t_9 = __pyx_v_node_info.idx_start; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { + __pyx_v_i = __pyx_t_9; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2171 + * node_log_bound_spreads[i_node]) + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.dist(pt, data + n_features * idx_array[i], # <<<<<<<<<<<<<< + * n_features) + * log_density = compute_log_kernel(dist_pt, h, kernel) + */ + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(__pyx_v_self, __pyx_v_pt, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features); if (unlikely(__pyx_t_5 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_5; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2173 + * dist_pt = self.dist(pt, data + n_features * idx_array[i], + * n_features) + * log_density = compute_log_kernel(dist_pt, h, kernel) # <<<<<<<<<<<<<< + * global_log_min_bound = logaddexp(global_log_min_bound, + * log_density) + */ + __pyx_v_log_density = __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_pt, __pyx_v_h, __pyx_v_kernel); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2174 + * n_features) + * log_density = compute_log_kernel(dist_pt, h, kernel) + * global_log_min_bound = logaddexp(global_log_min_bound, # <<<<<<<<<<<<<< + * log_density) + * + */ + __pyx_v_global_log_min_bound = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_v_global_log_min_bound, __pyx_v_log_density); + } + goto __pyx_L5; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2180 + * # Case 4: split node and query subnodes + * else: + * i1 = 2 * i_node + 1 # <<<<<<<<<<<<<< + * i2 = 2 * i_node + 2 + * + */ + __pyx_v_i1 = ((2 * __pyx_v_i_node) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2181 + * else: + * i1 = 2 * i_node + 1 + * i2 = 2 * i_node + 2 # <<<<<<<<<<<<<< + * + * N1 = node_data[i1].idx_end - node_data[i1].idx_start + */ + __pyx_v_i2 = ((2 * __pyx_v_i_node) + 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2183 + * i2 = 2 * i_node + 2 + * + * N1 = node_data[i1].idx_end - node_data[i1].idx_start # <<<<<<<<<<<<<< + * N2 = node_data[i2].idx_end - node_data[i2].idx_start + * + */ + __pyx_v_N1 = ((__pyx_v_node_data[__pyx_v_i1]).idx_end - (__pyx_v_node_data[__pyx_v_i1]).idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2184 + * + * N1 = node_data[i1].idx_end - node_data[i1].idx_start + * N2 = node_data[i2].idx_end - node_data[i2].idx_start # <<<<<<<<<<<<<< + * + * min_max_dist(self, i1, pt, &dist_LB_1, &dist_UB_1) + */ + __pyx_v_N2 = ((__pyx_v_node_data[__pyx_v_i2]).idx_end - (__pyx_v_node_data[__pyx_v_i2]).idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2186 + * N2 = node_data[i2].idx_end - node_data[i2].idx_start + * + * min_max_dist(self, i1, pt, &dist_LB_1, &dist_UB_1) # <<<<<<<<<<<<<< + * min_max_dist(self, i2, pt, &dist_LB_2, &dist_UB_2) + * + */ + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_max_dist(__pyx_v_self, __pyx_v_i1, __pyx_v_pt, (&__pyx_v_dist_LB_1), (&__pyx_v_dist_UB_1)); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2187 + * + * min_max_dist(self, i1, pt, &dist_LB_1, &dist_UB_1) + * min_max_dist(self, i2, pt, &dist_LB_2, &dist_UB_2) # <<<<<<<<<<<<<< + * + * node_log_min_bounds[i1] = (log(N1) + + */ + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_max_dist(__pyx_v_self, __pyx_v_i2, __pyx_v_pt, (&__pyx_v_dist_LB_2), (&__pyx_v_dist_UB_2)); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2189 + * min_max_dist(self, i2, pt, &dist_LB_2, &dist_UB_2) + * + * node_log_min_bounds[i1] = (log(N1) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_UB_1, + * h, kernel)) + */ + (__pyx_v_node_log_min_bounds[__pyx_v_i1]) = (log(__pyx_v_N1) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_UB_1, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2192 + * compute_log_kernel(dist_UB_1, + * h, kernel)) + * node_log_bound_spreads[i1] = (log(N1) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_LB_1, + * h, kernel)) + */ + (__pyx_v_node_log_bound_spreads[__pyx_v_i1]) = (log(__pyx_v_N1) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_LB_1, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2196 + * h, kernel)) + * + * node_log_min_bounds[i2] = (log(N2) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_UB_2, + * h, kernel)) + */ + (__pyx_v_node_log_min_bounds[__pyx_v_i2]) = (log(__pyx_v_N2) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_UB_2, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2199 + * compute_log_kernel(dist_UB_2, + * h, kernel)) + * node_log_bound_spreads[i2] = (log(N2) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_LB_2, + * h, kernel)) + */ + (__pyx_v_node_log_bound_spreads[__pyx_v_i2]) = (log(__pyx_v_N2) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_LB_2, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2203 + * h, kernel)) + * + * global_log_min_bound = logsubexp(global_log_min_bound, # <<<<<<<<<<<<<< + * node_log_min_bounds[i_node]) + * global_log_min_bound = logaddexp(global_log_min_bound, + */ + __pyx_v_global_log_min_bound = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp(__pyx_v_global_log_min_bound, (__pyx_v_node_log_min_bounds[__pyx_v_i_node])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2205 + * global_log_min_bound = logsubexp(global_log_min_bound, + * node_log_min_bounds[i_node]) + * global_log_min_bound = logaddexp(global_log_min_bound, # <<<<<<<<<<<<<< + * node_log_min_bounds[i1]) + * global_log_min_bound = logaddexp(global_log_min_bound, + */ + __pyx_v_global_log_min_bound = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_v_global_log_min_bound, (__pyx_v_node_log_min_bounds[__pyx_v_i1])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2207 + * global_log_min_bound = logaddexp(global_log_min_bound, + * node_log_min_bounds[i1]) + * global_log_min_bound = logaddexp(global_log_min_bound, # <<<<<<<<<<<<<< + * node_log_min_bounds[i2]) + * + */ + __pyx_v_global_log_min_bound = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_v_global_log_min_bound, (__pyx_v_node_log_min_bounds[__pyx_v_i2])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2211 + * + * global_log_bound_spread =\ + * logsubexp(global_log_bound_spread, # <<<<<<<<<<<<<< + * node_log_bound_spreads[i_node]) + * global_log_bound_spread = logaddexp(global_log_bound_spread, + */ + __pyx_v_global_log_bound_spread = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp(__pyx_v_global_log_bound_spread, (__pyx_v_node_log_bound_spreads[__pyx_v_i_node])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2213 + * logsubexp(global_log_bound_spread, + * node_log_bound_spreads[i_node]) + * global_log_bound_spread = logaddexp(global_log_bound_spread, # <<<<<<<<<<<<<< + * node_log_bound_spreads[i1]) + * global_log_bound_spread = logaddexp(global_log_bound_spread, + */ + __pyx_v_global_log_bound_spread = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_v_global_log_bound_spread, (__pyx_v_node_log_bound_spreads[__pyx_v_i1])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2215 + * global_log_bound_spread = logaddexp(global_log_bound_spread, + * node_log_bound_spreads[i1]) + * global_log_bound_spread = logaddexp(global_log_bound_spread, # <<<<<<<<<<<<<< + * node_log_bound_spreads[i2]) + * + */ + __pyx_v_global_log_bound_spread = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_v_global_log_bound_spread, (__pyx_v_node_log_bound_spreads[__pyx_v_i2])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2219 + * + * # TODO: rank by the spread rather than the distance? + * nodeheap_item.val = dist_LB_1 # <<<<<<<<<<<<<< + * nodeheap_item.i1 = i1 + * nodeheap.push(nodeheap_item) + */ + __pyx_v_nodeheap_item.val = __pyx_v_dist_LB_1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2220 + * # TODO: rank by the spread rather than the distance? + * nodeheap_item.val = dist_LB_1 + * nodeheap_item.i1 = i1 # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) + * + */ + __pyx_v_nodeheap_item.i1 = __pyx_v_i1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2221 + * nodeheap_item.val = dist_LB_1 + * nodeheap_item.i1 = i1 + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * + * nodeheap_item.val = dist_LB_2 + */ + __pyx_t_6 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2223 + * nodeheap.push(nodeheap_item) + * + * nodeheap_item.val = dist_LB_2 # <<<<<<<<<<<<<< + * nodeheap_item.i1 = i2 + * nodeheap.push(nodeheap_item) + */ + __pyx_v_nodeheap_item.val = __pyx_v_dist_LB_2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2224 + * + * nodeheap_item.val = dist_LB_2 + * nodeheap_item.i1 = i2 # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) + * + */ + __pyx_v_nodeheap_item.i1 = __pyx_v_i2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2225 + * nodeheap_item.val = dist_LB_2 + * nodeheap_item.i1 = i2 + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * + * nodeheap.clear() + */ + __pyx_t_6 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L5:; + } + __pyx_L4_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2227 + * nodeheap.push(nodeheap_item) + * + * nodeheap.clear() # <<<<<<<<<<<<<< + * return logaddexp(global_log_min_bound, + * global_log_bound_spread - log(2)) + */ + ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->clear(__pyx_v_nodeheap); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2228 + * + * nodeheap.clear() + * return logaddexp(global_log_min_bound, # <<<<<<<<<<<<<< + * global_log_bound_spread - log(2)) + * + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_v_global_log_min_bound, (__pyx_v_global_log_bound_spread - log(2.0))); + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2091 + * return count + * + * cdef DTYPE_t _kde_single_breadthfirst(self, DTYPE_t* pt, # <<<<<<<<<<<<<< + * KernelType kernel, DTYPE_t h, + * DTYPE_t log_knorm, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_WriteUnraisable("sklearn.neighbors.ball_tree.BinaryTree._kde_single_breadthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2231 + * global_log_bound_spread - log(2)) + * + * cdef int _kde_single_depthfirst( # <<<<<<<<<<<<<< + * self, ITYPE_t i_node, DTYPE_t* pt, + * KernelType kernel, DTYPE_t h, + */ + +static int __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__kde_single_depthfirst(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType __pyx_v_kernel, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_knorm, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_atol, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_rtol, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_local_log_min_bound, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_local_log_bound_spread, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_global_log_min_bound, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_global_log_bound_spread) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_N1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_N2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_dens_contribution; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_child1_log_min_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_child2_log_min_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_child1_log_bound_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_child2_log_bound_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + int __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_10; + int __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_kde_single_depthfirst", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2248 + * cdef ITYPE_t i, i1, i2, N1, N2 + * + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2248; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_1 * __pyx_v_self->data.strides[0]) )) + __pyx_t_2)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2249 + * + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2249; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2250 + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * + * cdef NodeData_t node_info = self.node_data[i_node] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2250; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2252 + * cdef ITYPE_t n_features = self.data.shape[1] + * + * cdef NodeData_t node_info = self.node_data[i_node] # <<<<<<<<<<<<<< + * cdef DTYPE_t dist_pt, log_dens_contribution + * + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2252; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = __pyx_v_i_node; + __pyx_v_node_info = (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_4)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2257 + * cdef DTYPE_t child1_log_min_bound, child2_log_min_bound + * cdef DTYPE_t child1_log_bound_spread, child2_log_bound_spread + * cdef DTYPE_t dist_UB = 0, dist_LB = 0 # <<<<<<<<<<<<<< + * + * N1 = node_info.idx_end - node_info.idx_start + */ + __pyx_v_dist_UB = 0.0; + __pyx_v_dist_LB = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2259 + * cdef DTYPE_t dist_UB = 0, dist_LB = 0 + * + * N1 = node_info.idx_end - node_info.idx_start # <<<<<<<<<<<<<< + * N2 = self.data.shape[0] + * + */ + __pyx_v_N1 = (__pyx_v_node_info.idx_end - __pyx_v_node_info.idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2260 + * + * N1 = node_info.idx_end - node_info.idx_start + * N2 = self.data.shape[0] # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2260; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_N2 = (__pyx_v_self->data.shape[0]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2265 + * # Case 1: local bounds are equal to within errors. Return + * if (log_knorm + local_log_bound_spread - log(N1) + log(N2) + * <= logaddexp(log_atol, (log_rtol + log_knorm # <<<<<<<<<<<<<< + * + local_log_min_bound))): + * pass + */ + __pyx_t_5 = (((((__pyx_v_log_knorm + __pyx_v_local_log_bound_spread) - log(__pyx_v_N1)) + log(__pyx_v_N2)) <= __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_v_log_atol, ((__pyx_v_log_rtol + __pyx_v_log_knorm) + __pyx_v_local_log_min_bound))) != 0); + if (__pyx_t_5) { + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2272 + * # Case 2: global bounds are within rtol & atol. Return + * elif (log_knorm + global_log_bound_spread[0] + * <= logaddexp(log_atol, (log_rtol + log_knorm # <<<<<<<<<<<<<< + * + global_log_min_bound[0]))): + * pass + */ + __pyx_t_5 = (((__pyx_v_log_knorm + (__pyx_v_global_log_bound_spread[0])) <= __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp(__pyx_v_log_atol, ((__pyx_v_log_rtol + __pyx_v_log_knorm) + (__pyx_v_global_log_min_bound[0])))) != 0); + if (__pyx_t_5) { + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2278 + * #------------------------------------------------------------ + * # Case 3: node is a leaf. Count contributions from all points + * elif node_info.is_leaf: # <<<<<<<<<<<<<< + * global_log_min_bound[0] = logsubexp(global_log_min_bound[0], + * local_log_min_bound) + */ + __pyx_t_5 = (__pyx_v_node_info.is_leaf != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2279 + * # Case 3: node is a leaf. Count contributions from all points + * elif node_info.is_leaf: + * global_log_min_bound[0] = logsubexp(global_log_min_bound[0], # <<<<<<<<<<<<<< + * local_log_min_bound) + * global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], + */ + (__pyx_v_global_log_min_bound[0]) = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp((__pyx_v_global_log_min_bound[0]), __pyx_v_local_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2281 + * global_log_min_bound[0] = logsubexp(global_log_min_bound[0], + * local_log_min_bound) + * global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], # <<<<<<<<<<<<<< + * local_log_bound_spread) + * for i in range(node_info.idx_start, node_info.idx_end): + */ + (__pyx_v_global_log_bound_spread[0]) = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp((__pyx_v_global_log_bound_spread[0]), __pyx_v_local_log_bound_spread); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2283 + * global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], + * local_log_bound_spread) + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + * n_features) + */ + __pyx_t_6 = __pyx_v_node_info.idx_end; + for (__pyx_t_7 = __pyx_v_node_info.idx_start; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2284 + * local_log_bound_spread) + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), # <<<<<<<<<<<<<< + * n_features) + * log_dens_contribution = compute_log_kernel(dist_pt, h, kernel) + */ + __pyx_t_8 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(__pyx_v_self, __pyx_v_pt, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features); if (unlikely(__pyx_t_8 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2286 + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + * n_features) + * log_dens_contribution = compute_log_kernel(dist_pt, h, kernel) # <<<<<<<<<<<<<< + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + * log_dens_contribution) + */ + __pyx_v_log_dens_contribution = __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_pt, __pyx_v_h, __pyx_v_kernel); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2287 + * n_features) + * log_dens_contribution = compute_log_kernel(dist_pt, h, kernel) + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], # <<<<<<<<<<<<<< + * log_dens_contribution) + * + */ + (__pyx_v_global_log_min_bound[0]) = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp((__pyx_v_global_log_min_bound[0]), __pyx_v_log_dens_contribution); + } + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2293 + * # Case 4: split node and query subnodes + * else: + * i1 = 2 * i_node + 1 # <<<<<<<<<<<<<< + * i2 = 2 * i_node + 2 + * + */ + __pyx_v_i1 = ((2 * __pyx_v_i_node) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2294 + * else: + * i1 = 2 * i_node + 1 + * i2 = 2 * i_node + 2 # <<<<<<<<<<<<<< + * + * N1 = self.node_data[i1].idx_end - self.node_data[i1].idx_start + */ + __pyx_v_i2 = ((2 * __pyx_v_i_node) + 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2296 + * i2 = 2 * i_node + 2 + * + * N1 = self.node_data[i1].idx_end - self.node_data[i1].idx_start # <<<<<<<<<<<<<< + * N2 = self.node_data[i2].idx_end - self.node_data[i2].idx_start + * + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2296; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_6 = __pyx_v_i1; + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2296; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = __pyx_v_i1; + __pyx_v_N1 = ((*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_6)) ))).idx_end - (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_7)) ))).idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2297 + * + * N1 = self.node_data[i1].idx_end - self.node_data[i1].idx_start + * N2 = self.node_data[i2].idx_end - self.node_data[i2].idx_start # <<<<<<<<<<<<<< + * + * min_max_dist(self, i1, pt, &dist_LB, &dist_UB) + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2297; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = __pyx_v_i2; + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2297; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = __pyx_v_i2; + __pyx_v_N2 = ((*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_9)) ))).idx_end - (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_10)) ))).idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2299 + * N2 = self.node_data[i2].idx_end - self.node_data[i2].idx_start + * + * min_max_dist(self, i1, pt, &dist_LB, &dist_UB) # <<<<<<<<<<<<<< + * child1_log_min_bound = log(N1) + compute_log_kernel(dist_UB, h, + * kernel) + */ + __pyx_t_11 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_max_dist(__pyx_v_self, __pyx_v_i1, __pyx_v_pt, (&__pyx_v_dist_LB), (&__pyx_v_dist_UB)); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2300 + * + * min_max_dist(self, i1, pt, &dist_LB, &dist_UB) + * child1_log_min_bound = log(N1) + compute_log_kernel(dist_UB, h, # <<<<<<<<<<<<<< + * kernel) + * child1_log_bound_spread = logsubexp(log(N1) + + */ + __pyx_v_child1_log_min_bound = (log(__pyx_v_N1) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_UB, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2302 + * child1_log_min_bound = log(N1) + compute_log_kernel(dist_UB, h, + * kernel) + * child1_log_bound_spread = logsubexp(log(N1) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_LB, h, + * kernel), + */ + __pyx_v_child1_log_bound_spread = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp((log(__pyx_v_N1) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_LB, __pyx_v_h, __pyx_v_kernel)), __pyx_v_child1_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2307 + * child1_log_min_bound) + * + * min_max_dist(self, i2, pt, &dist_LB, &dist_UB) # <<<<<<<<<<<<<< + * child2_log_min_bound = log(N2) + compute_log_kernel(dist_UB, h, + * kernel) + */ + __pyx_t_11 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_max_dist(__pyx_v_self, __pyx_v_i2, __pyx_v_pt, (&__pyx_v_dist_LB), (&__pyx_v_dist_UB)); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2307; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2308 + * + * min_max_dist(self, i2, pt, &dist_LB, &dist_UB) + * child2_log_min_bound = log(N2) + compute_log_kernel(dist_UB, h, # <<<<<<<<<<<<<< + * kernel) + * child2_log_bound_spread = logsubexp(log(N2) + + */ + __pyx_v_child2_log_min_bound = (log(__pyx_v_N2) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_UB, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2310 + * child2_log_min_bound = log(N2) + compute_log_kernel(dist_UB, h, + * kernel) + * child2_log_bound_spread = logsubexp(log(N2) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_LB, h, + * kernel), + */ + __pyx_v_child2_log_bound_spread = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp((log(__pyx_v_N2) + __pyx_f_7sklearn_9neighbors_9ball_tree_compute_log_kernel(__pyx_v_dist_LB, __pyx_v_h, __pyx_v_kernel)), __pyx_v_child2_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2315 + * child2_log_min_bound) + * + * global_log_min_bound[0] = logsubexp(global_log_min_bound[0], # <<<<<<<<<<<<<< + * local_log_min_bound) + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + */ + (__pyx_v_global_log_min_bound[0]) = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp((__pyx_v_global_log_min_bound[0]), __pyx_v_local_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2317 + * global_log_min_bound[0] = logsubexp(global_log_min_bound[0], + * local_log_min_bound) + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], # <<<<<<<<<<<<<< + * child1_log_min_bound) + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + */ + (__pyx_v_global_log_min_bound[0]) = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp((__pyx_v_global_log_min_bound[0]), __pyx_v_child1_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2319 + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + * child1_log_min_bound) + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], # <<<<<<<<<<<<<< + * child2_log_min_bound) + * + */ + (__pyx_v_global_log_min_bound[0]) = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp((__pyx_v_global_log_min_bound[0]), __pyx_v_child2_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2322 + * child2_log_min_bound) + * + * global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], # <<<<<<<<<<<<<< + * local_log_bound_spread) + * global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], + */ + (__pyx_v_global_log_bound_spread[0]) = __pyx_f_7sklearn_9neighbors_9ball_tree_logsubexp((__pyx_v_global_log_bound_spread[0]), __pyx_v_local_log_bound_spread); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2324 + * global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], + * local_log_bound_spread) + * global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], # <<<<<<<<<<<<<< + * child1_log_bound_spread) + * global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], + */ + (__pyx_v_global_log_bound_spread[0]) = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp((__pyx_v_global_log_bound_spread[0]), __pyx_v_child1_log_bound_spread); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2326 + * global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], + * child1_log_bound_spread) + * global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], # <<<<<<<<<<<<<< + * child2_log_bound_spread) + * + */ + (__pyx_v_global_log_bound_spread[0]) = __pyx_f_7sklearn_9neighbors_9ball_tree_logaddexp((__pyx_v_global_log_bound_spread[0]), __pyx_v_child2_log_bound_spread); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2329 + * child2_log_bound_spread) + * + * self._kde_single_depthfirst(i1, pt, kernel, h, log_knorm, # <<<<<<<<<<<<<< + * log_atol, log_rtol, + * child1_log_min_bound, + */ + __pyx_t_11 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_kde_single_depthfirst(__pyx_v_self, __pyx_v_i1, __pyx_v_pt, __pyx_v_kernel, __pyx_v_h, __pyx_v_log_knorm, __pyx_v_log_atol, __pyx_v_log_rtol, __pyx_v_child1_log_min_bound, __pyx_v_child1_log_bound_spread, __pyx_v_global_log_min_bound, __pyx_v_global_log_bound_spread); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2335 + * global_log_min_bound, + * global_log_bound_spread) + * self._kde_single_depthfirst(i2, pt, kernel, h, log_knorm, # <<<<<<<<<<<<<< + * log_atol, log_rtol, + * child2_log_min_bound, + */ + __pyx_t_11 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_kde_single_depthfirst(__pyx_v_self, __pyx_v_i2, __pyx_v_pt, __pyx_v_kernel, __pyx_v_h, __pyx_v_log_knorm, __pyx_v_log_atol, __pyx_v_log_rtol, __pyx_v_child2_log_min_bound, __pyx_v_child2_log_bound_spread, __pyx_v_global_log_min_bound, __pyx_v_global_log_bound_spread); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2341 + * global_log_min_bound, + * global_log_bound_spread) + * return 0 # <<<<<<<<<<<<<< + * + * cdef int _two_point_single(self, ITYPE_t i_node, DTYPE_t* pt, DTYPE_t* r, + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2231 + * global_log_bound_spread - log(2)) + * + * cdef int _kde_single_depthfirst( # <<<<<<<<<<<<<< + * self, ITYPE_t i_node, DTYPE_t* pt, + * KernelType kernel, DTYPE_t h, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree._kde_single_depthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2343 + * return 0 + * + * cdef int _two_point_single(self, ITYPE_t i_node, DTYPE_t* pt, DTYPE_t* r, # <<<<<<<<<<<<<< + * ITYPE_t* count, ITYPE_t i_min, + * ITYPE_t i_max) except -1: + */ + +static int __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__two_point_single(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_r, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_count, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_min, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_max) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_Npts; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + long __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_two_point_single", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2347 + * ITYPE_t i_max) except -1: + * """recursive single-tree two-point correlation function query""" + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2347; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_1 * __pyx_v_self->data.strides[0]) )) + __pyx_t_2)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2348 + * """recursive single-tree two-point correlation function query""" + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef NodeData_t node_info = self.node_data[i_node] + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2348; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2349 + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info = self.node_data[i_node] + * + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2349; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2350 + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef NodeData_t node_info = self.node_data[i_node] # <<<<<<<<<<<<<< + * + * cdef ITYPE_t i, j, Npts + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2350; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = __pyx_v_i_node; + __pyx_v_node_info = (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_4)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2355 + * cdef DTYPE_t reduced_r + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 # <<<<<<<<<<<<<< + * min_max_dist(self, i_node, pt, &dist_LB, &dist_UB) + * + */ + __pyx_v_dist_LB = 0.0; + __pyx_v_dist_UB = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2356 + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 + * min_max_dist(self, i_node, pt, &dist_LB, &dist_UB) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_max_dist(__pyx_v_self, __pyx_v_i_node, __pyx_v_pt, (&__pyx_v_dist_LB), (&__pyx_v_dist_UB)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2360 + * #------------------------------------------------------------ + * # Go through bounds and check for cuts + * while i_min < i_max: # <<<<<<<<<<<<<< + * if dist_LB > r[i_min]: + * i_min += 1 + */ + while (1) { + __pyx_t_6 = ((__pyx_v_i_min < __pyx_v_i_max) != 0); + if (!__pyx_t_6) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2361 + * # Go through bounds and check for cuts + * while i_min < i_max: + * if dist_LB > r[i_min]: # <<<<<<<<<<<<<< + * i_min += 1 + * else: + */ + __pyx_t_6 = ((__pyx_v_dist_LB > (__pyx_v_r[__pyx_v_i_min])) != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2362 + * while i_min < i_max: + * if dist_LB > r[i_min]: + * i_min += 1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_min = (__pyx_v_i_min + 1); + goto __pyx_L5; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2364 + * i_min += 1 + * else: + * break # <<<<<<<<<<<<<< + * + * while i_max > i_min: + */ + goto __pyx_L4_break; + } + __pyx_L5:; + } + __pyx_L4_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2366 + * break + * + * while i_max > i_min: # <<<<<<<<<<<<<< + * Npts = (node_info.idx_end - node_info.idx_start) + * if dist_UB <= r[i_max - 1]: + */ + while (1) { + __pyx_t_6 = ((__pyx_v_i_max > __pyx_v_i_min) != 0); + if (!__pyx_t_6) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2367 + * + * while i_max > i_min: + * Npts = (node_info.idx_end - node_info.idx_start) # <<<<<<<<<<<<<< + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts + */ + __pyx_v_Npts = (__pyx_v_node_info.idx_end - __pyx_v_node_info.idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2368 + * while i_max > i_min: + * Npts = (node_info.idx_end - node_info.idx_start) + * if dist_UB <= r[i_max - 1]: # <<<<<<<<<<<<<< + * count[i_max - 1] += Npts + * i_max -= 1 + */ + __pyx_t_6 = ((__pyx_v_dist_UB <= (__pyx_v_r[(__pyx_v_i_max - 1)])) != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2369 + * Npts = (node_info.idx_end - node_info.idx_start) + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts # <<<<<<<<<<<<<< + * i_max -= 1 + * else: + */ + __pyx_t_7 = (__pyx_v_i_max - 1); + (__pyx_v_count[__pyx_t_7]) = ((__pyx_v_count[__pyx_t_7]) + __pyx_v_Npts); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2370 + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts + * i_max -= 1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_max = (__pyx_v_i_max - 1); + goto __pyx_L8; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2372 + * i_max -= 1 + * else: + * break # <<<<<<<<<<<<<< + * + * if i_min < i_max: + */ + goto __pyx_L7_break; + } + __pyx_L8:; + } + __pyx_L7_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2374 + * break + * + * if i_min < i_max: # <<<<<<<<<<<<<< + * # If node is a leaf, go through all points + * if node_info.is_leaf: + */ + __pyx_t_6 = ((__pyx_v_i_min < __pyx_v_i_max) != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2376 + * if i_min < i_max: + * # If node is a leaf, go through all points + * if node_info.is_leaf: # <<<<<<<<<<<<<< + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + */ + __pyx_t_6 = (__pyx_v_node_info.is_leaf != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2377 + * # If node is a leaf, go through all points + * if node_info.is_leaf: + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + * n_features) + */ + __pyx_t_8 = __pyx_v_node_info.idx_end; + for (__pyx_t_9 = __pyx_v_node_info.idx_start; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { + __pyx_v_i = __pyx_t_9; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2378 + * if node_info.is_leaf: + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), # <<<<<<<<<<<<<< + * n_features) + * j = i_max - 1 + */ + __pyx_t_10 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(__pyx_v_self, __pyx_v_pt, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features); if (unlikely(__pyx_t_10 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_10; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2380 + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + * n_features) + * j = i_max - 1 # <<<<<<<<<<<<<< + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 + */ + __pyx_v_j = (__pyx_v_i_max - 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2381 + * n_features) + * j = i_max - 1 + * while (j >= i_min) and (dist_pt <= r[j]): # <<<<<<<<<<<<<< + * count[j] += 1 + * j -= 1 + */ + while (1) { + __pyx_t_6 = ((__pyx_v_j >= __pyx_v_i_min) != 0); + if (__pyx_t_6) { + __pyx_t_11 = ((__pyx_v_dist_pt <= (__pyx_v_r[__pyx_v_j])) != 0); + __pyx_t_12 = __pyx_t_11; + } else { + __pyx_t_12 = __pyx_t_6; + } + if (!__pyx_t_12) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2382 + * j = i_max - 1 + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 # <<<<<<<<<<<<<< + * j -= 1 + * + */ + __pyx_t_13 = __pyx_v_j; + (__pyx_v_count[__pyx_t_13]) = ((__pyx_v_count[__pyx_t_13]) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2383 + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 + * j -= 1 # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_v_j = (__pyx_v_j - 1); + } + } + goto __pyx_L10; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2386 + * + * else: + * self._two_point_single(2 * i_node + 1, pt, r, # <<<<<<<<<<<<<< + * count, i_min, i_max) + * self._two_point_single(2 * i_node + 2, pt, r, + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_single(__pyx_v_self, ((2 * __pyx_v_i_node) + 1), __pyx_v_pt, __pyx_v_r, __pyx_v_count, __pyx_v_i_min, __pyx_v_i_max); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2388 + * self._two_point_single(2 * i_node + 1, pt, r, + * count, i_min, i_max) + * self._two_point_single(2 * i_node + 2, pt, r, # <<<<<<<<<<<<<< + * count, i_min, i_max) + * return 0 + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_single(__pyx_v_self, ((2 * __pyx_v_i_node) + 2), __pyx_v_pt, __pyx_v_r, __pyx_v_count, __pyx_v_i_min, __pyx_v_i_max); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2388; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L10:; + goto __pyx_L9; + } + __pyx_L9:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2390 + * self._two_point_single(2 * i_node + 2, pt, r, + * count, i_min, i_max) + * return 0 # <<<<<<<<<<<<<< + * + * cdef int _two_point_dual(self, ITYPE_t i_node1, + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2343 + * return 0 + * + * cdef int _two_point_single(self, ITYPE_t i_node, DTYPE_t* pt, DTYPE_t* r, # <<<<<<<<<<<<<< + * ITYPE_t* count, ITYPE_t i_min, + * ITYPE_t i_max) except -1: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree._two_point_single", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2392 + * return 0 + * + * cdef int _two_point_dual(self, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree other, ITYPE_t i_node2, + * DTYPE_t* r, ITYPE_t* count, + */ + +static int __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__two_point_dual(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_other, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_r, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_count, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_min, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_max) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array2; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info1; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_v_node_info2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_Npts; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_9; + int __pyx_t_10; + long __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + int __pyx_t_16; + int __pyx_t_17; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_18; + int __pyx_t_19; + long __pyx_t_20; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_two_point_dual", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2397 + * ITYPE_t i_min, ITYPE_t i_max) except -1: + * """recursive dual-tree two-point correlation function query""" + * cdef DTYPE_t* data1 = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t* idx_array1 = &self.idx_array[0] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2397; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_v_data1 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_1 * __pyx_v_self->data.strides[0]) )) + __pyx_t_2)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2398 + * """recursive dual-tree two-point correlation function query""" + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array1 = &self.idx_array[0] + * cdef ITYPE_t* idx_array2 = &other.idx_array[0] + */ + if (unlikely(!__pyx_v_other->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2398; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_v_data2 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_other->data.data + __pyx_t_3 * __pyx_v_other->data.strides[0]) )) + __pyx_t_4)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2399 + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t* idx_array1 = &self.idx_array[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array2 = &other.idx_array[0] + * cdef NodeData_t node_info1 = self.node_data[i_node1] + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2399; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_5 = 0; + __pyx_v_idx_array1 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_5)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2400 + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t* idx_array1 = &self.idx_array[0] + * cdef ITYPE_t* idx_array2 = &other.idx_array[0] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info1 = self.node_data[i_node1] + * cdef NodeData_t node_info2 = other.node_data[i_node2] + */ + if (unlikely(!__pyx_v_other->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2400; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_6 = 0; + __pyx_v_idx_array2 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_other->idx_array.data) + __pyx_t_6)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2401 + * cdef ITYPE_t* idx_array1 = &self.idx_array[0] + * cdef ITYPE_t* idx_array2 = &other.idx_array[0] + * cdef NodeData_t node_info1 = self.node_data[i_node1] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info2 = other.node_data[i_node2] + * + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2401; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = __pyx_v_i_node1; + __pyx_v_node_info1 = (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_7)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2402 + * cdef ITYPE_t* idx_array2 = &other.idx_array[0] + * cdef NodeData_t node_info1 = self.node_data[i_node1] + * cdef NodeData_t node_info2 = other.node_data[i_node2] # <<<<<<<<<<<<<< + * + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_other->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2402; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_8 = __pyx_v_i_node2; + __pyx_v_node_info2 = (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_other->node_data.data) + __pyx_t_8)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2404 + * cdef NodeData_t node_info2 = other.node_data[i_node2] + * + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * + * cdef ITYPE_t i1, i2, j, Npts + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2404; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2409 + * cdef DTYPE_t reduced_r + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 # <<<<<<<<<<<<<< + * dist_LB = min_dist_dual(self, i_node1, other, i_node2) + * dist_UB = max_dist_dual(self, i_node1, other, i_node2) + */ + __pyx_v_dist_LB = 0.0; + __pyx_v_dist_UB = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2410 + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 + * dist_LB = min_dist_dual(self, i_node1, other, i_node2) # <<<<<<<<<<<<<< + * dist_UB = max_dist_dual(self, i_node1, other, i_node2) + * + */ + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_dist_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, __pyx_v_i_node2); if (unlikely(__pyx_t_9 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_LB = __pyx_t_9; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2411 + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 + * dist_LB = min_dist_dual(self, i_node1, other, i_node2) + * dist_UB = max_dist_dual(self, i_node1, other, i_node2) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_9ball_tree_max_dist_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, __pyx_v_i_node2); if (unlikely(__pyx_t_9 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_UB = __pyx_t_9; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2415 + * #------------------------------------------------------------ + * # Go through bounds and check for cuts + * while i_min < i_max: # <<<<<<<<<<<<<< + * if dist_LB > r[i_min]: + * i_min += 1 + */ + while (1) { + __pyx_t_10 = ((__pyx_v_i_min < __pyx_v_i_max) != 0); + if (!__pyx_t_10) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2416 + * # Go through bounds and check for cuts + * while i_min < i_max: + * if dist_LB > r[i_min]: # <<<<<<<<<<<<<< + * i_min += 1 + * else: + */ + __pyx_t_10 = ((__pyx_v_dist_LB > (__pyx_v_r[__pyx_v_i_min])) != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2417 + * while i_min < i_max: + * if dist_LB > r[i_min]: + * i_min += 1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_min = (__pyx_v_i_min + 1); + goto __pyx_L5; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2419 + * i_min += 1 + * else: + * break # <<<<<<<<<<<<<< + * + * while i_max > i_min: + */ + goto __pyx_L4_break; + } + __pyx_L5:; + } + __pyx_L4_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2421 + * break + * + * while i_max > i_min: # <<<<<<<<<<<<<< + * Npts = ((node_info1.idx_end - node_info1.idx_start) + * * (node_info2.idx_end - node_info2.idx_start)) + */ + while (1) { + __pyx_t_10 = ((__pyx_v_i_max > __pyx_v_i_min) != 0); + if (!__pyx_t_10) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2423 + * while i_max > i_min: + * Npts = ((node_info1.idx_end - node_info1.idx_start) + * * (node_info2.idx_end - node_info2.idx_start)) # <<<<<<<<<<<<<< + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts + */ + __pyx_v_Npts = ((__pyx_v_node_info1.idx_end - __pyx_v_node_info1.idx_start) * (__pyx_v_node_info2.idx_end - __pyx_v_node_info2.idx_start)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2424 + * Npts = ((node_info1.idx_end - node_info1.idx_start) + * * (node_info2.idx_end - node_info2.idx_start)) + * if dist_UB <= r[i_max - 1]: # <<<<<<<<<<<<<< + * count[i_max - 1] += Npts + * i_max -= 1 + */ + __pyx_t_10 = ((__pyx_v_dist_UB <= (__pyx_v_r[(__pyx_v_i_max - 1)])) != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2425 + * * (node_info2.idx_end - node_info2.idx_start)) + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts # <<<<<<<<<<<<<< + * i_max -= 1 + * else: + */ + __pyx_t_11 = (__pyx_v_i_max - 1); + (__pyx_v_count[__pyx_t_11]) = ((__pyx_v_count[__pyx_t_11]) + __pyx_v_Npts); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2426 + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts + * i_max -= 1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_max = (__pyx_v_i_max - 1); + goto __pyx_L8; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2428 + * i_max -= 1 + * else: + * break # <<<<<<<<<<<<<< + * + * if i_min < i_max: + */ + goto __pyx_L7_break; + } + __pyx_L8:; + } + __pyx_L7_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2430 + * break + * + * if i_min < i_max: # <<<<<<<<<<<<<< + * if node_info1.is_leaf and node_info2.is_leaf: + * # If both nodes are leaves, go through all points + */ + __pyx_t_10 = ((__pyx_v_i_min < __pyx_v_i_max) != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2431 + * + * if i_min < i_max: + * if node_info1.is_leaf and node_info2.is_leaf: # <<<<<<<<<<<<<< + * # If both nodes are leaves, go through all points + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + */ + if ((__pyx_v_node_info1.is_leaf != 0)) { + __pyx_t_10 = (__pyx_v_node_info2.is_leaf != 0); + } else { + __pyx_t_10 = (__pyx_v_node_info1.is_leaf != 0); + } + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2433 + * if node_info1.is_leaf and node_info2.is_leaf: + * # If both nodes are leaves, go through all points + * for i1 in range(node_info1.idx_start, node_info1.idx_end): # <<<<<<<<<<<<<< + * for i2 in range(node_info2.idx_start, node_info2.idx_end): + * dist_pt = self.dist((data1 + n_features + */ + __pyx_t_12 = __pyx_v_node_info1.idx_end; + for (__pyx_t_13 = __pyx_v_node_info1.idx_start; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i1 = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2434 + * # If both nodes are leaves, go through all points + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * for i2 in range(node_info2.idx_start, node_info2.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.dist((data1 + n_features + * * idx_array1[i1]), + */ + __pyx_t_14 = __pyx_v_node_info2.idx_end; + for (__pyx_t_15 = __pyx_v_node_info2.idx_start; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { + __pyx_v_i2 = __pyx_t_15; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2435 + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * for i2 in range(node_info2.idx_start, node_info2.idx_end): + * dist_pt = self.dist((data1 + n_features # <<<<<<<<<<<<<< + * * idx_array1[i1]), + * (data2 + n_features + */ + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(__pyx_v_self, (__pyx_v_data1 + (__pyx_v_n_features * (__pyx_v_idx_array1[__pyx_v_i1]))), (__pyx_v_data2 + (__pyx_v_n_features * (__pyx_v_idx_array2[__pyx_v_i2]))), __pyx_v_n_features); if (unlikely(__pyx_t_9 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_9; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2440 + * * idx_array2[i2]), + * n_features) + * j = i_max - 1 # <<<<<<<<<<<<<< + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 + */ + __pyx_v_j = (__pyx_v_i_max - 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2441 + * n_features) + * j = i_max - 1 + * while (j >= i_min) and (dist_pt <= r[j]): # <<<<<<<<<<<<<< + * count[j] += 1 + * j -= 1 + */ + while (1) { + __pyx_t_10 = ((__pyx_v_j >= __pyx_v_i_min) != 0); + if (__pyx_t_10) { + __pyx_t_16 = ((__pyx_v_dist_pt <= (__pyx_v_r[__pyx_v_j])) != 0); + __pyx_t_17 = __pyx_t_16; + } else { + __pyx_t_17 = __pyx_t_10; + } + if (!__pyx_t_17) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2442 + * j = i_max - 1 + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 # <<<<<<<<<<<<<< + * j -= 1 + * + */ + __pyx_t_18 = __pyx_v_j; + (__pyx_v_count[__pyx_t_18]) = ((__pyx_v_count[__pyx_t_18]) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2443 + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 + * j -= 1 # <<<<<<<<<<<<<< + * + * elif node_info1.is_leaf: + */ + __pyx_v_j = (__pyx_v_j - 1); + } + } + } + goto __pyx_L10; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2445 + * j -= 1 + * + * elif node_info1.is_leaf: # <<<<<<<<<<<<<< + * # If only one is a leaf, split the other + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + */ + __pyx_t_17 = (__pyx_v_node_info1.is_leaf != 0); + if (__pyx_t_17) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2447 + * elif node_info1.is_leaf: + * # If only one is a leaf, split the other + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): # <<<<<<<<<<<<<< + * self._two_point_dual(i_node1, other, i2, + * r, count, i_min, i_max) + */ + __pyx_t_11 = ((2 * __pyx_v_i_node2) + 3); + for (__pyx_t_12 = ((2 * __pyx_v_i_node2) + 1); __pyx_t_12 < __pyx_t_11; __pyx_t_12+=1) { + __pyx_v_i2 = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2448 + * # If only one is a leaf, split the other + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * self._two_point_dual(i_node1, other, i2, # <<<<<<<<<<<<<< + * r, count, i_min, i_max) + * + */ + __pyx_t_19 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, __pyx_v_i2, __pyx_v_r, __pyx_v_count, __pyx_v_i_min, __pyx_v_i_max); if (unlikely(__pyx_t_19 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2448; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L10; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2451 + * r, count, i_min, i_max) + * + * elif node_info2.is_leaf: # <<<<<<<<<<<<<< + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * self._two_point_dual(i1, other, i_node2, + */ + __pyx_t_17 = (__pyx_v_node_info2.is_leaf != 0); + if (__pyx_t_17) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2452 + * + * elif node_info2.is_leaf: + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): # <<<<<<<<<<<<<< + * self._two_point_dual(i1, other, i_node2, + * r, count, i_min, i_max) + */ + __pyx_t_11 = ((2 * __pyx_v_i_node1) + 3); + for (__pyx_t_12 = ((2 * __pyx_v_i_node1) + 1); __pyx_t_12 < __pyx_t_11; __pyx_t_12+=1) { + __pyx_v_i1 = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2453 + * elif node_info2.is_leaf: + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * self._two_point_dual(i1, other, i_node2, # <<<<<<<<<<<<<< + * r, count, i_min, i_max) + * + */ + __pyx_t_19 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_dual(__pyx_v_self, __pyx_v_i1, __pyx_v_other, __pyx_v_i_node2, __pyx_v_r, __pyx_v_count, __pyx_v_i_min, __pyx_v_i_max); if (unlikely(__pyx_t_19 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L10; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2458 + * else: + * # neither is a leaf: split & query both + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): # <<<<<<<<<<<<<< + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * self._two_point_dual(i1, other, i2, + */ + __pyx_t_11 = ((2 * __pyx_v_i_node1) + 3); + for (__pyx_t_12 = ((2 * __pyx_v_i_node1) + 1); __pyx_t_12 < __pyx_t_11; __pyx_t_12+=1) { + __pyx_v_i1 = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2459 + * # neither is a leaf: split & query both + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): # <<<<<<<<<<<<<< + * self._two_point_dual(i1, other, i2, + * r, count, i_min, i_max) + */ + __pyx_t_20 = ((2 * __pyx_v_i_node2) + 3); + for (__pyx_t_13 = ((2 * __pyx_v_i_node2) + 1); __pyx_t_13 < __pyx_t_20; __pyx_t_13+=1) { + __pyx_v_i2 = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2460 + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * self._two_point_dual(i1, other, i2, # <<<<<<<<<<<<<< + * r, count, i_min, i_max) + * return 0 + */ + __pyx_t_19 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_dual(__pyx_v_self, __pyx_v_i1, __pyx_v_other, __pyx_v_i2, __pyx_v_r, __pyx_v_count, __pyx_v_i_min, __pyx_v_i_max); if (unlikely(__pyx_t_19 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + } + __pyx_L10:; + goto __pyx_L9; + } + __pyx_L9:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2462 + * self._two_point_dual(i1, other, i2, + * r, count, i_min, i_max) + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2392 + * return 0 + * + * cdef int _two_point_dual(self, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree other, ITYPE_t i_node2, + * DTYPE_t* r, ITYPE_t* count, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree._two_point_dual", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1004 + * cdef np.ndarray node_bounds_arr + * + * cdef readonly DTYPE_t[:, ::1] data # <<<<<<<<<<<<<< + * cdef public ITYPE_t[::1] idx_array + * cdef public NodeData_t[::1] node_data + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_4data_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_4data_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_4data___get__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_4data___get__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1004; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_self->data, 2, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1004; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.data.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1005 + * + * cdef readonly DTYPE_t[:, ::1] data + * cdef public ITYPE_t[::1] idx_array # <<<<<<<<<<<<<< + * cdef public NodeData_t[::1] node_data + * cdef public DTYPE_t[:, :, ::1] node_bounds + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array___get__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array___get__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1005; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_self->idx_array, 1, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, 0);; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1005; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.idx_array.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array_2__set__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array_2__set__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(__pyx_v_value); + if (unlikely(!__pyx_t_1.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1005; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_XDEC_MEMVIEW(&__pyx_v_self->idx_array, 0); + __pyx_v_self->idx_array = __pyx_t_1; + __pyx_t_1.memview = NULL; + __pyx_t_1.data = NULL; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __PYX_XDEC_MEMVIEW(&__pyx_t_1, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.idx_array.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1006 + * cdef readonly DTYPE_t[:, ::1] data + * cdef public ITYPE_t[::1] idx_array + * cdef public NodeData_t[::1] node_data # <<<<<<<<<<<<<< + * cdef public DTYPE_t[:, :, ::1] node_bounds + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data___get__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data___get__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_self->node_data, 1, (PyObject *(*)(char *)) __pyx_memview_get_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t, 0);; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.node_data.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data_2__set__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data_2__set__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(__pyx_v_value); + if (unlikely(!__pyx_t_1.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_data, 0); + __pyx_v_self->node_data = __pyx_t_1; + __pyx_t_1.memview = NULL; + __pyx_t_1.data = NULL; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __PYX_XDEC_MEMVIEW(&__pyx_t_1, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.node_data.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1007 + * cdef public ITYPE_t[::1] idx_array + * cdef public NodeData_t[::1] node_data + * cdef public DTYPE_t[:, :, ::1] node_bounds # <<<<<<<<<<<<<< + * + * cdef ITYPE_t leaf_size + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds___get__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds___get__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_self->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1007; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_self->node_bounds, 3, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1007; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.node_bounds.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds_2__set__(((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds_2__set__(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(__pyx_v_value); + if (unlikely(!__pyx_t_1.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1007; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_bounds, 0); + __pyx_v_self->node_bounds = __pyx_t_1; + __pyx_t_1.memview = NULL; + __pyx_t_1.data = NULL; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __PYX_XDEC_MEMVIEW(&__pyx_t_1, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.BinaryTree.node_bounds.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2468 + * # Python functions for benchmarking and testing C implementations + * + * def load_heap(DTYPE_t[:, ::1] X, ITYPE_t k): # <<<<<<<<<<<<<< + * """test fully loading the heap""" + * assert k <= X.shape[1] + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_5load_heap(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_4load_heap[] = "test fully loading the heap"; +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_9ball_tree_5load_heap = {__Pyx_NAMESTR("load_heap"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_5load_heap, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_4load_heap)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_5load_heap(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_k; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("load_heap (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_k,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_k)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("load_heap", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "load_heap") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_k = __Pyx_PyInt_As_Py_intptr_t(values[1]); if (unlikely((__pyx_v_k == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("load_heap", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.load_heap", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_4load_heap(__pyx_self, __pyx_v_X, __pyx_v_k); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_4load_heap(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_k) { + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *__pyx_v_heap = 0; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + int __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("load_heap", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2470 + * def load_heap(DTYPE_t[:, ::1] X, ITYPE_t k): + * """test fully loading the heap""" + * assert k <= X.shape[1] # <<<<<<<<<<<<<< + * cdef NeighborsHeap heap = NeighborsHeap(X.shape[0], k) + * cdef ITYPE_t i, j + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!((__pyx_v_k <= (__pyx_v_X.shape[1])) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2471 + * """test fully loading the heap""" + * assert k <= X.shape[1] + * cdef NeighborsHeap heap = NeighborsHeap(X.shape[0], k) # <<<<<<<<<<<<<< + * cdef ITYPE_t i, j + * for i in range(X.shape[0]): + */ + __pyx_t_1 = PyInt_FromSsize_t((__pyx_v_X.shape[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_k); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_9ball_tree_NeighborsHeap)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_heap = ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2473 + * cdef NeighborsHeap heap = NeighborsHeap(X.shape[0], k) + * cdef ITYPE_t i, j + * for i in range(X.shape[0]): # <<<<<<<<<<<<<< + * for j in range(X.shape[1]): + * heap.push(i, X[i, j], j) + */ + __pyx_t_4 = (__pyx_v_X.shape[0]); + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2474 + * cdef ITYPE_t i, j + * for i in range(X.shape[0]): + * for j in range(X.shape[1]): # <<<<<<<<<<<<<< + * heap.push(i, X[i, j], j) + * return heap.get_arrays() + */ + __pyx_t_6 = (__pyx_v_X.shape[1]); + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_j = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2475 + * for i in range(X.shape[0]): + * for j in range(X.shape[1]): + * heap.push(i, X[i, j], j) # <<<<<<<<<<<<<< + * return heap.get_arrays() + * + */ + __pyx_t_8 = __pyx_v_i; + __pyx_t_9 = __pyx_v_j; + __pyx_t_10 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_i, (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_X.data + __pyx_t_8 * __pyx_v_X.strides[0]) )) + __pyx_t_9)) ))), __pyx_v_j, 0); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2476 + * for j in range(X.shape[1]): + * heap.push(i, X[i, j], j) + * return heap.get_arrays() # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_heap), __pyx_n_s_get_arrays); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2468 + * # Python functions for benchmarking and testing C implementations + * + * def load_heap(DTYPE_t[:, ::1] X, ITYPE_t k): # <<<<<<<<<<<<<< + * """test fully loading the heap""" + * assert k <= X.shape[1] + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.load_heap", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_heap); + __PYX_XDEC_MEMVIEW(&__pyx_v_X, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2479 + * + * + * def simultaneous_sort(DTYPE_t[:, ::1] distances, ITYPE_t[:, ::1] indices): # <<<<<<<<<<<<<< + * """In-place simultaneous sort the given row of the arrays + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_7simultaneous_sort(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_6simultaneous_sort[] = "In-place simultaneous sort the given row of the arrays\n\n This python wrapper exists primarily to enable unit testing\n of the _simultaneous_sort C routine.\n "; +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_9ball_tree_7simultaneous_sort = {__Pyx_NAMESTR("simultaneous_sort"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_7simultaneous_sort, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_6simultaneous_sort)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_7simultaneous_sort(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __Pyx_memviewslice __pyx_v_distances = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_indices = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("simultaneous_sort (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_distances,&__pyx_n_s_indices,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_distances)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_indices)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("simultaneous_sort", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "simultaneous_sort") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_distances = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(values[0]); if (unlikely(!__pyx_v_distances.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_indices = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(values[1]); if (unlikely(!__pyx_v_indices.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("simultaneous_sort", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.simultaneous_sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_6simultaneous_sort(__pyx_self, __pyx_v_distances, __pyx_v_indices); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_6simultaneous_sort(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_distances, __Pyx_memviewslice __pyx_v_indices) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("simultaneous_sort", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2485 + * of the _simultaneous_sort C routine. + * """ + * assert distances.shape[0] == indices.shape[0] # <<<<<<<<<<<<<< + * assert distances.shape[1] == indices.shape[1] + * cdef ITYPE_t row + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_distances.shape[0]) == (__pyx_v_indices.shape[0])) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2486 + * """ + * assert distances.shape[0] == indices.shape[0] + * assert distances.shape[1] == indices.shape[1] # <<<<<<<<<<<<<< + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_distances.shape[1]) == (__pyx_v_indices.shape[1])) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2488 + * assert distances.shape[1] == indices.shape[1] + * cdef ITYPE_t row + * for row in range(distances.shape[0]): # <<<<<<<<<<<<<< + * _simultaneous_sort(&distances[row, 0], + * &indices[row, 0], + */ + __pyx_t_1 = (__pyx_v_distances.shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_row = __pyx_t_2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2489 + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], # <<<<<<<<<<<<<< + * &indices[row, 0], + * distances.shape[1]) + */ + __pyx_t_3 = __pyx_v_row; + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2490 + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], + * &indices[row, 0], # <<<<<<<<<<<<<< + * distances.shape[1]) + * + */ + __pyx_t_5 = __pyx_v_row; + __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2489 + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], # <<<<<<<<<<<<<< + * &indices[row, 0], + * distances.shape[1]) + */ + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_9ball_tree__simultaneous_sort((&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_distances.data + __pyx_t_3 * __pyx_v_distances.strides[0]) )) + __pyx_t_4)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ (__pyx_v_indices.data + __pyx_t_5 * __pyx_v_indices.strides[0]) )) + __pyx_t_6)) )))), (__pyx_v_distances.shape[1])); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2489; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2479 + * + * + * def simultaneous_sort(DTYPE_t[:, ::1] distances, ITYPE_t[:, ::1] indices): # <<<<<<<<<<<<<< + * """In-place simultaneous sort the given row of the arrays + * + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.simultaneous_sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_distances, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_indices, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2494 + * + * + * def nodeheap_sort(DTYPE_t[::1] vals): # <<<<<<<<<<<<<< + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_9nodeheap_sort(PyObject *__pyx_self, PyObject *__pyx_arg_vals); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_9ball_tree_8nodeheap_sort[] = "In-place reverse sort of vals using NodeHeap"; +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_9ball_tree_9nodeheap_sort = {__Pyx_NAMESTR("nodeheap_sort"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_9nodeheap_sort, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_8nodeheap_sort)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_9ball_tree_9nodeheap_sort(PyObject *__pyx_self, PyObject *__pyx_arg_vals) { + __Pyx_memviewslice __pyx_v_vals = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("nodeheap_sort (wrapper)", 0); + assert(__pyx_arg_vals); { + __pyx_v_vals = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(__pyx_arg_vals); if (unlikely(!__pyx_v_vals.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2494; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.nodeheap_sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_9ball_tree_8nodeheap_sort(__pyx_self, __pyx_v_vals); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_9ball_tree_8nodeheap_sort(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_vals) { + __Pyx_memviewslice __pyx_v_indices = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_vals_sorted = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *__pyx_v_heap = 0; + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t __pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + int __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("nodeheap_sort", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2496 + * def nodeheap_sort(DTYPE_t[::1] vals): + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] vals_sorted = np.zeros_like(vals) + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyInt_FromSsize_t((__pyx_v_vals.shape[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(__pyx_t_4); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2497 + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) + * cdef DTYPE_t[::1] vals_sorted = np.zeros_like(vals) # <<<<<<<<<<<<<< + * + * # use initial size 0 to check corner case + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros_like); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_vals, 1, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(__pyx_t_4); + if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_vals_sorted = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2500 + * + * # use initial size 0 to check corner case + * cdef NodeHeap heap = NodeHeap(0) # <<<<<<<<<<<<<< + * cdef NodeHeapData_t data + * cdef ITYPE_t i + */ + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_9ball_tree_NodeHeap)), __pyx_tuple__32, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2500; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_heap = ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2503 + * cdef NodeHeapData_t data + * cdef ITYPE_t i + * for i in range(vals.shape[0]): # <<<<<<<<<<<<<< + * data.val = vals[i] + * data.i1 = i + */ + __pyx_t_7 = (__pyx_v_vals.shape[0]); + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2504 + * cdef ITYPE_t i + * for i in range(vals.shape[0]): + * data.val = vals[i] # <<<<<<<<<<<<<< + * data.i1 = i + * data.i2 = i + 1 + */ + __pyx_t_9 = __pyx_v_i; + __pyx_v_data.val = (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_vals.data) + __pyx_t_9)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2505 + * for i in range(vals.shape[0]): + * data.val = vals[i] + * data.i1 = i # <<<<<<<<<<<<<< + * data.i2 = i + 1 + * heap.push(data) + */ + __pyx_v_data.i1 = __pyx_v_i; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2506 + * data.val = vals[i] + * data.i1 = i + * data.i2 = i + 1 # <<<<<<<<<<<<<< + * heap.push(data) + * + */ + __pyx_v_data.i2 = (__pyx_v_i + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2507 + * data.i1 = i + * data.i2 = i + 1 + * heap.push(data) # <<<<<<<<<<<<<< + * + * for i in range(vals.shape[0]): + */ + __pyx_t_10 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_data); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2509 + * heap.push(data) + * + * for i in range(vals.shape[0]): # <<<<<<<<<<<<<< + * data = heap.pop() + * vals_sorted[i] = data.val + */ + __pyx_t_7 = (__pyx_v_vals.shape[0]); + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2510 + * + * for i in range(vals.shape[0]): + * data = heap.pop() # <<<<<<<<<<<<<< + * vals_sorted[i] = data.val + * indices[i] = data.i1 + */ + __pyx_v_data = ((struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap *)__pyx_v_heap->__pyx_vtab)->pop(__pyx_v_heap); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2511 + * for i in range(vals.shape[0]): + * data = heap.pop() + * vals_sorted[i] = data.val # <<<<<<<<<<<<<< + * indices[i] = data.i1 + * + */ + __pyx_t_11 = __pyx_v_data.val; + __pyx_t_12 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_vals_sorted.data) + __pyx_t_12)) )) = __pyx_t_11; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2512 + * data = heap.pop() + * vals_sorted[i] = data.val + * indices[i] = data.i1 # <<<<<<<<<<<<<< + * + * return np.asarray(vals_sorted), np.asarray(indices) + */ + __pyx_t_13 = __pyx_v_data.i1; + __pyx_t_14 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_indices.data) + __pyx_t_14)) )) = __pyx_t_13; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2514 + * indices[i] = data.i1 + * + * return np.asarray(vals_sorted), np.asarray(indices) # <<<<<<<<<<<<<< + * + * # Reimplementation for MSVC support + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_asarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_vals_sorted, 1, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_1, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_asarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_indices, 1, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, 0);; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_4 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2494 + * + * + * def nodeheap_sort(DTYPE_t[::1] vals): # <<<<<<<<<<<<<< + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.nodeheap_sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_vals, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_indices, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_vals_sorted, 1); + __Pyx_XDECREF((PyObject *)__pyx_v_heap); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2517 + * + * # Reimplementation for MSVC support + * cdef inline double fmin(double a, double b): # <<<<<<<<<<<<<< + * return min(a, b) + * + */ + +static CYTHON_INLINE double __pyx_f_7sklearn_9neighbors_9ball_tree_fmin(double __pyx_v_a, double __pyx_v_b) { + double __pyx_r; + __Pyx_RefNannyDeclarations + double __pyx_t_1; + double __pyx_t_2; + double __pyx_t_3; + __Pyx_RefNannySetupContext("fmin", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2518 + * # Reimplementation for MSVC support + * cdef inline double fmin(double a, double b): + * return min(a, b) # <<<<<<<<<<<<<< + * + * cdef inline double fmax(double a, double b): + */ + __pyx_t_1 = __pyx_v_b; + __pyx_t_2 = __pyx_v_a; + if (((__pyx_t_1 < __pyx_t_2) != 0)) { + __pyx_t_3 = __pyx_t_1; + } else { + __pyx_t_3 = __pyx_t_2; + } + __pyx_r = __pyx_t_3; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2517 + * + * # Reimplementation for MSVC support + * cdef inline double fmin(double a, double b): # <<<<<<<<<<<<<< + * return min(a, b) + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2520 + * return min(a, b) + * + * cdef inline double fmax(double a, double b): # <<<<<<<<<<<<<< + * return max(a, b) + */ + +static CYTHON_INLINE double __pyx_f_7sklearn_9neighbors_9ball_tree_fmax(double __pyx_v_a, double __pyx_v_b) { + double __pyx_r; + __Pyx_RefNannyDeclarations + double __pyx_t_1; + double __pyx_t_2; + double __pyx_t_3; + __Pyx_RefNannySetupContext("fmax", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2521 + * + * cdef inline double fmax(double a, double b): + * return max(a, b) # <<<<<<<<<<<<<< + */ + __pyx_t_1 = __pyx_v_b; + __pyx_t_2 = __pyx_v_a; + if (((__pyx_t_1 > __pyx_t_2) != 0)) { + __pyx_t_3 = __pyx_t_1; + } else { + __pyx_t_3 = __pyx_t_2; + } + __pyx_r = __pyx_t_3; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2520 + * return min(a, b) + * + * cdef inline double fmax(double a, double b): # <<<<<<<<<<<<<< + * return max(a, b) + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/ball_tree.pyx":43 + * + * + * cdef int allocate_data(BinaryTree tree, ITYPE_t n_nodes, # <<<<<<<<<<<<<< + * ITYPE_t n_features) except -1: + * """Allocate arrays needed for the KD Tree""" + */ + +static int __pyx_f_7sklearn_9neighbors_9ball_tree_allocate_data(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_nodes, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("allocate_data", 0); + + /* "sklearn/neighbors/ball_tree.pyx":46 + * ITYPE_t n_features) except -1: + * """Allocate arrays needed for the KD Tree""" + * tree.node_bounds_arr = np.zeros((1, n_nodes, n_features), dtype=DTYPE) # <<<<<<<<<<<<<< + * tree.node_bounds = get_memview_DTYPE_3D(tree.node_bounds_arr) + * return 0 + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_nodes); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_features); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_int_1); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_int_1); + __Pyx_GIVEREF(__pyx_int_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_tree->node_bounds_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_tree->node_bounds_arr)); + __pyx_v_tree->node_bounds_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/neighbors/ball_tree.pyx":47 + * """Allocate arrays needed for the KD Tree""" + * tree.node_bounds_arr = np.zeros((1, n_nodes, n_features), dtype=DTYPE) + * tree.node_bounds = get_memview_DTYPE_3D(tree.node_bounds_arr) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_t_1 = ((PyObject *)__pyx_v_tree->node_bounds_arr); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_9ball_tree_get_memview_DTYPE_3D(((PyArrayObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_tree->node_bounds, 0); + __pyx_v_tree->node_bounds = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + + /* "sklearn/neighbors/ball_tree.pyx":48 + * tree.node_bounds_arr = np.zeros((1, n_nodes, n_features), dtype=DTYPE) + * tree.node_bounds = get_memview_DTYPE_3D(tree.node_bounds_arr) + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/neighbors/ball_tree.pyx":43 + * + * + * cdef int allocate_data(BinaryTree tree, ITYPE_t n_nodes, # <<<<<<<<<<<<<< + * ITYPE_t n_features) except -1: + * """Allocate arrays needed for the KD Tree""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.allocate_data", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/ball_tree.pyx":51 + * + * + * cdef int init_node(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * ITYPE_t idx_start, ITYPE_t idx_end) except -1: + * """Initialize the node for the dataset stored in tree.data""" + */ + +static int __pyx_f_7sklearn_9neighbors_9ball_tree_init_node(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_idx_start, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_idx_end) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_points; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_radius; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_this_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_centroid; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("init_node", 0); + + /* "sklearn/neighbors/ball_tree.pyx":54 + * ITYPE_t idx_start, ITYPE_t idx_end) except -1: + * """Initialize the node for the dataset stored in tree.data""" + * cdef ITYPE_t n_features = tree.data.shape[1] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_points = idx_end - idx_start + * + */ + if (unlikely(!__pyx_v_tree->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_tree->data.shape[1]); + + /* "sklearn/neighbors/ball_tree.pyx":55 + * """Initialize the node for the dataset stored in tree.data""" + * cdef ITYPE_t n_features = tree.data.shape[1] + * cdef ITYPE_t n_points = idx_end - idx_start # <<<<<<<<<<<<<< + * + * cdef ITYPE_t i, j + */ + __pyx_v_n_points = (__pyx_v_idx_end - __pyx_v_idx_start); + + /* "sklearn/neighbors/ball_tree.pyx":61 + * cdef DTYPE_t *this_pt + * + * cdef ITYPE_t* idx_array = &tree.idx_array[0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data = &tree.data[0, 0] + * cdef DTYPE_t* centroid = &tree.node_bounds[0, i_node, 0] + */ + if (unlikely(!__pyx_v_tree->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_tree->idx_array.data) + __pyx_t_1)) )))); + + /* "sklearn/neighbors/ball_tree.pyx":62 + * + * cdef ITYPE_t* idx_array = &tree.idx_array[0] + * cdef DTYPE_t* data = &tree.data[0, 0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* centroid = &tree.node_bounds[0, i_node, 0] + * + */ + if (unlikely(!__pyx_v_tree->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_tree->data.data + __pyx_t_2 * __pyx_v_tree->data.strides[0]) )) + __pyx_t_3)) )))); + + /* "sklearn/neighbors/ball_tree.pyx":63 + * cdef ITYPE_t* idx_array = &tree.idx_array[0] + * cdef DTYPE_t* data = &tree.data[0, 0] + * cdef DTYPE_t* centroid = &tree.node_bounds[0, i_node, 0] # <<<<<<<<<<<<<< + * + * # determine Node centroid + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = 0; + __pyx_t_5 = __pyx_v_i_node; + __pyx_t_6 = 0; + __pyx_v_centroid = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_4 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_5 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_6)) )))); + + /* "sklearn/neighbors/ball_tree.pyx":66 + * + * # determine Node centroid + * for j in range(n_features): # <<<<<<<<<<<<<< + * centroid[j] = 0 + * + */ + __pyx_t_7 = __pyx_v_n_features; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_j = __pyx_t_8; + + /* "sklearn/neighbors/ball_tree.pyx":67 + * # determine Node centroid + * for j in range(n_features): + * centroid[j] = 0 # <<<<<<<<<<<<<< + * + * for i in range(idx_start, idx_end): + */ + (__pyx_v_centroid[__pyx_v_j]) = 0.0; + } + + /* "sklearn/neighbors/ball_tree.pyx":69 + * centroid[j] = 0 + * + * for i in range(idx_start, idx_end): # <<<<<<<<<<<<<< + * this_pt = data + n_features * idx_array[i] + * for j from 0 <= j < n_features: + */ + __pyx_t_7 = __pyx_v_idx_end; + for (__pyx_t_8 = __pyx_v_idx_start; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "sklearn/neighbors/ball_tree.pyx":70 + * + * for i in range(idx_start, idx_end): + * this_pt = data + n_features * idx_array[i] # <<<<<<<<<<<<<< + * for j from 0 <= j < n_features: + * centroid[j] += this_pt[j] + */ + __pyx_v_this_pt = (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))); + + /* "sklearn/neighbors/ball_tree.pyx":71 + * for i in range(idx_start, idx_end): + * this_pt = data + n_features * idx_array[i] + * for j from 0 <= j < n_features: # <<<<<<<<<<<<<< + * centroid[j] += this_pt[j] + * + */ + __pyx_t_9 = __pyx_v_n_features; + for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_9; __pyx_v_j++) { + + /* "sklearn/neighbors/ball_tree.pyx":72 + * this_pt = data + n_features * idx_array[i] + * for j from 0 <= j < n_features: + * centroid[j] += this_pt[j] # <<<<<<<<<<<<<< + * + * for j in range(n_features): + */ + __pyx_t_10 = __pyx_v_j; + (__pyx_v_centroid[__pyx_t_10]) = ((__pyx_v_centroid[__pyx_t_10]) + (__pyx_v_this_pt[__pyx_v_j])); + } + } + + /* "sklearn/neighbors/ball_tree.pyx":74 + * centroid[j] += this_pt[j] + * + * for j in range(n_features): # <<<<<<<<<<<<<< + * centroid[j] /= n_points + * + */ + __pyx_t_7 = __pyx_v_n_features; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_j = __pyx_t_8; + + /* "sklearn/neighbors/ball_tree.pyx":75 + * + * for j in range(n_features): + * centroid[j] /= n_points # <<<<<<<<<<<<<< + * + * # determine Node radius + */ + __pyx_t_9 = __pyx_v_j; + (__pyx_v_centroid[__pyx_t_9]) = ((__pyx_v_centroid[__pyx_t_9]) / __pyx_v_n_points); + } + + /* "sklearn/neighbors/ball_tree.pyx":78 + * + * # determine Node radius + * radius = 0 # <<<<<<<<<<<<<< + * for i in range(idx_start, idx_end): + * radius = fmax(radius, + */ + __pyx_v_radius = 0.0; + + /* "sklearn/neighbors/ball_tree.pyx":79 + * # determine Node radius + * radius = 0 + * for i in range(idx_start, idx_end): # <<<<<<<<<<<<<< + * radius = fmax(radius, + * tree.rdist(centroid, + */ + __pyx_t_7 = __pyx_v_idx_end; + for (__pyx_t_8 = __pyx_v_idx_start; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "sklearn/neighbors/ball_tree.pyx":81 + * for i in range(idx_start, idx_end): + * radius = fmax(radius, + * tree.rdist(centroid, # <<<<<<<<<<<<<< + * data + n_features * idx_array[i], + * n_features)) + */ + __pyx_t_11 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_rdist(__pyx_v_tree, __pyx_v_centroid, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features); if (unlikely(__pyx_t_11 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/ball_tree.pyx":80 + * radius = 0 + * for i in range(idx_start, idx_end): + * radius = fmax(radius, # <<<<<<<<<<<<<< + * tree.rdist(centroid, + * data + n_features * idx_array[i], + */ + __pyx_v_radius = __pyx_f_7sklearn_9neighbors_9ball_tree_fmax(__pyx_v_radius, __pyx_t_11); + } + + /* "sklearn/neighbors/ball_tree.pyx":85 + * n_features)) + * + * tree.node_data[i_node].radius = tree.dist_metric._rdist_to_dist(radius) # <<<<<<<<<<<<<< + * tree.node_data[i_node].idx_start = idx_start + * tree.node_data[i_node].idx_end = idx_end + */ + __pyx_t_11 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_tree->dist_metric->__pyx_vtab)->_rdist_to_dist(__pyx_v_tree->dist_metric, __pyx_v_radius); if (unlikely(__pyx_t_11 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__pyx_v_tree->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_tree->node_data.data) + __pyx_t_7)) ))).radius = __pyx_t_11; + + /* "sklearn/neighbors/ball_tree.pyx":86 + * + * tree.node_data[i_node].radius = tree.dist_metric._rdist_to_dist(radius) + * tree.node_data[i_node].idx_start = idx_start # <<<<<<<<<<<<<< + * tree.node_data[i_node].idx_end = idx_end + * return 0 + */ + if (unlikely(!__pyx_v_tree->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_8 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_tree->node_data.data) + __pyx_t_8)) ))).idx_start = __pyx_v_idx_start; + + /* "sklearn/neighbors/ball_tree.pyx":87 + * tree.node_data[i_node].radius = tree.dist_metric._rdist_to_dist(radius) + * tree.node_data[i_node].idx_start = idx_start + * tree.node_data[i_node].idx_end = idx_end # <<<<<<<<<<<<<< + * return 0 + * + */ + if (unlikely(!__pyx_v_tree->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_tree->node_data.data) + __pyx_t_9)) ))).idx_end = __pyx_v_idx_end; + + /* "sklearn/neighbors/ball_tree.pyx":88 + * tree.node_data[i_node].idx_start = idx_start + * tree.node_data[i_node].idx_end = idx_end + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/neighbors/ball_tree.pyx":51 + * + * + * cdef int init_node(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * ITYPE_t idx_start, ITYPE_t idx_end) except -1: + * """Initialize the node for the dataset stored in tree.data""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.init_node", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/ball_tree.pyx":91 + * + * + * cdef inline DTYPE_t min_dist(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt) except -1: + * """Compute the minimum distance between a point and a node""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_min_dist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("min_dist", 0); + + /* "sklearn/neighbors/ball_tree.pyx":94 + * DTYPE_t* pt) except -1: + * """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]) + * return fmax(0, dist_pt - tree.node_data[i_node].radius) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = __pyx_v_i_node; + __pyx_t_3 = 0; + + /* "sklearn/neighbors/ball_tree.pyx":95 + * """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]) # <<<<<<<<<<<<<< + * return fmax(0, dist_pt - tree.node_data[i_node].radius) + * + */ + if (unlikely(!__pyx_v_tree->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + + /* "sklearn/neighbors/ball_tree.pyx":94 + * DTYPE_t* pt) except -1: + * """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]) + * return fmax(0, dist_pt - tree.node_data[i_node].radius) + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(__pyx_v_tree, __pyx_v_pt, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_1 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_2 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_3)) )))), (__pyx_v_tree->data.shape[1])); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_4; + + /* "sklearn/neighbors/ball_tree.pyx":96 + * cdef DTYPE_t dist_pt = tree.dist(pt, &tree.node_bounds[0, i_node, 0], + * tree.data.shape[1]) + * return fmax(0, dist_pt - tree.node_data[i_node].radius) # <<<<<<<<<<<<<< + * + * + */ + if (unlikely(!__pyx_v_tree->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_5 = __pyx_v_i_node; + __pyx_r = __pyx_f_7sklearn_9neighbors_9ball_tree_fmax(0.0, (__pyx_v_dist_pt - (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_tree->node_data.data) + __pyx_t_5)) ))).radius)); + goto __pyx_L0; + + /* "sklearn/neighbors/ball_tree.pyx":91 + * + * + * cdef inline DTYPE_t min_dist(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt) except -1: + * """Compute the minimum distance between a point and a node""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.min_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/ball_tree.pyx":99 + * + * + * cdef inline DTYPE_t max_dist(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt) except -1: + * """Compute the maximum distance between a point and a node""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_max_dist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("max_dist", 0); + + /* "sklearn/neighbors/ball_tree.pyx":102 + * DTYPE_t* pt) except -1: + * """Compute the 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]) + * return dist_pt + tree.node_data[i_node].radius + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = __pyx_v_i_node; + __pyx_t_3 = 0; + + /* "sklearn/neighbors/ball_tree.pyx":103 + * """Compute the 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]) # <<<<<<<<<<<<<< + * return dist_pt + tree.node_data[i_node].radius + * + */ + if (unlikely(!__pyx_v_tree->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + + /* "sklearn/neighbors/ball_tree.pyx":102 + * DTYPE_t* pt) except -1: + * """Compute the 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]) + * return dist_pt + tree.node_data[i_node].radius + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(__pyx_v_tree, __pyx_v_pt, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_1 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_2 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_3)) )))), (__pyx_v_tree->data.shape[1])); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_4; + + /* "sklearn/neighbors/ball_tree.pyx":104 + * cdef DTYPE_t dist_pt = tree.dist(pt, &tree.node_bounds[0, i_node, 0], + * tree.data.shape[1]) + * return dist_pt + tree.node_data[i_node].radius # <<<<<<<<<<<<<< + * + * + */ + if (unlikely(!__pyx_v_tree->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_5 = __pyx_v_i_node; + __pyx_r = (__pyx_v_dist_pt + (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_tree->node_data.data) + __pyx_t_5)) ))).radius); + goto __pyx_L0; + + /* "sklearn/neighbors/ball_tree.pyx":99 + * + * + * cdef inline DTYPE_t max_dist(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt) except -1: + * """Compute the maximum distance between a point and a node""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.max_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/ball_tree.pyx":107 + * + * + * cdef inline int min_max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt, # <<<<<<<<<<<<<< + * DTYPE_t* min_dist, DTYPE_t* max_dist) except -1: + * """Compute the minimum and maximum distance between a point and a node""" + */ + +static CYTHON_INLINE int __pyx_f_7sklearn_9neighbors_9ball_tree_min_max_dist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_min_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_max_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rad; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("min_max_dist", 0); + + /* "sklearn/neighbors/ball_tree.pyx":110 + * DTYPE_t* min_dist, DTYPE_t* max_dist) except -1: + * """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]) + * cdef DTYPE_t rad = tree.node_data[i_node].radius + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = __pyx_v_i_node; + __pyx_t_3 = 0; + + /* "sklearn/neighbors/ball_tree.pyx":111 + * """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]) # <<<<<<<<<<<<<< + * cdef DTYPE_t rad = tree.node_data[i_node].radius + * min_dist[0] = fmax(0, dist_pt - rad) + */ + if (unlikely(!__pyx_v_tree->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + + /* "sklearn/neighbors/ball_tree.pyx":110 + * DTYPE_t* min_dist, DTYPE_t* max_dist) except -1: + * """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]) + * cdef DTYPE_t rad = tree.node_data[i_node].radius + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(__pyx_v_tree, __pyx_v_pt, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_1 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_2 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_3)) )))), (__pyx_v_tree->data.shape[1])); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_4; + + /* "sklearn/neighbors/ball_tree.pyx":112 + * cdef DTYPE_t dist_pt = tree.dist(pt, &tree.node_bounds[0, i_node, 0], + * tree.data.shape[1]) + * cdef DTYPE_t rad = tree.node_data[i_node].radius # <<<<<<<<<<<<<< + * min_dist[0] = fmax(0, dist_pt - rad) + * max_dist[0] = dist_pt + rad + */ + if (unlikely(!__pyx_v_tree->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_5 = __pyx_v_i_node; + __pyx_t_4 = (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_tree->node_data.data) + __pyx_t_5)) ))).radius; + __pyx_v_rad = __pyx_t_4; + + /* "sklearn/neighbors/ball_tree.pyx":113 + * tree.data.shape[1]) + * cdef DTYPE_t rad = tree.node_data[i_node].radius + * min_dist[0] = fmax(0, dist_pt - rad) # <<<<<<<<<<<<<< + * max_dist[0] = dist_pt + rad + * return 0 + */ + (__pyx_v_min_dist[0]) = __pyx_f_7sklearn_9neighbors_9ball_tree_fmax(0.0, (__pyx_v_dist_pt - __pyx_v_rad)); + + /* "sklearn/neighbors/ball_tree.pyx":114 + * cdef DTYPE_t rad = tree.node_data[i_node].radius + * min_dist[0] = fmax(0, dist_pt - rad) + * max_dist[0] = dist_pt + rad # <<<<<<<<<<<<<< + * return 0 + * + */ + (__pyx_v_max_dist[0]) = (__pyx_v_dist_pt + __pyx_v_rad); + + /* "sklearn/neighbors/ball_tree.pyx":115 + * min_dist[0] = fmax(0, dist_pt - rad) + * max_dist[0] = dist_pt + rad + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/neighbors/ball_tree.pyx":107 + * + * + * cdef inline int min_max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt, # <<<<<<<<<<<<<< + * DTYPE_t* min_dist, DTYPE_t* max_dist) except -1: + * """Compute the minimum and maximum distance between a point and a node""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.min_max_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/ball_tree.pyx":118 + * + * + * cdef inline DTYPE_t min_rdist(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt) except -1: + * """Compute the minimum reduced-distance between a point and a node""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("min_rdist", 0); + + /* "sklearn/neighbors/ball_tree.pyx":121 + * DTYPE_t* pt) except -1: + * """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)) + * else: + */ + __pyx_t_1 = (__pyx_v_tree->euclidean != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/ball_tree.pyx":122 + * """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)) # <<<<<<<<<<<<<< + * else: + * return tree.dist_metric._dist_to_rdist(min_dist(tree, i_node, pt)) + */ + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_dist(__pyx_v_tree, __pyx_v_i_node, __pyx_v_pt); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist_to_rdist(__pyx_t_2); if (unlikely(__pyx_t_3 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_3; + goto __pyx_L0; + } + /*else*/ { + + /* "sklearn/neighbors/ball_tree.pyx":124 + * return euclidean_dist_to_rdist(min_dist(tree, i_node, pt)) + * else: + * return tree.dist_metric._dist_to_rdist(min_dist(tree, i_node, pt)) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_dist(__pyx_v_tree, __pyx_v_i_node, __pyx_v_pt); if (unlikely(__pyx_t_3 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_tree->dist_metric->__pyx_vtab)->_dist_to_rdist(__pyx_v_tree->dist_metric, __pyx_t_3); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + + /* "sklearn/neighbors/ball_tree.pyx":118 + * + * + * cdef inline DTYPE_t min_rdist(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt) except -1: + * """Compute the minimum reduced-distance between a point and a node""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.min_rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/ball_tree.pyx":127 + * + * + * cdef inline DTYPE_t max_rdist(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt) except -1: + * """Compute the maximum reduced-distance between a point and a node""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_max_rdist(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("max_rdist", 0); + + /* "sklearn/neighbors/ball_tree.pyx":130 + * DTYPE_t* pt) except -1: + * """Compute the maximum reduced-distance between a point and a node""" + * if tree.euclidean: # <<<<<<<<<<<<<< + * return euclidean_dist_to_rdist(max_dist(tree, i_node, pt)) + * else: + */ + __pyx_t_1 = (__pyx_v_tree->euclidean != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/ball_tree.pyx":131 + * """Compute the maximum reduced-distance between a point and a node""" + * if tree.euclidean: + * return euclidean_dist_to_rdist(max_dist(tree, i_node, pt)) # <<<<<<<<<<<<<< + * else: + * return tree.dist_metric._dist_to_rdist(max_dist(tree, i_node, pt)) + */ + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_9ball_tree_max_dist(__pyx_v_tree, __pyx_v_i_node, __pyx_v_pt); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist_to_rdist(__pyx_t_2); if (unlikely(__pyx_t_3 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_3; + goto __pyx_L0; + } + /*else*/ { + + /* "sklearn/neighbors/ball_tree.pyx":133 + * return euclidean_dist_to_rdist(max_dist(tree, i_node, pt)) + * else: + * return tree.dist_metric._dist_to_rdist(max_dist(tree, i_node, pt)) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_f_7sklearn_9neighbors_9ball_tree_max_dist(__pyx_v_tree, __pyx_v_i_node, __pyx_v_pt); if (unlikely(__pyx_t_3 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_tree->dist_metric->__pyx_vtab)->_dist_to_rdist(__pyx_v_tree->dist_metric, __pyx_t_3); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + + /* "sklearn/neighbors/ball_tree.pyx":127 + * + * + * cdef inline DTYPE_t max_rdist(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt) except -1: + * """Compute the maximum reduced-distance between a point and a node""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.max_rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/ball_tree.pyx":136 + * + * + * cdef inline DTYPE_t min_dist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the minimum distance between two nodes""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_min_dist_dual(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("min_dist_dual", 0); + + /* "sklearn/neighbors/ball_tree.pyx":139 + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the minimum distance between two nodes""" + * cdef DTYPE_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], # <<<<<<<<<<<<<< + * &tree1.node_bounds[0, i_node1, 0], + * tree1.data.shape[1]) + */ + if (unlikely(!__pyx_v_tree2->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = __pyx_v_i_node2; + __pyx_t_3 = 0; + + /* "sklearn/neighbors/ball_tree.pyx":140 + * """compute the minimum distance between two nodes""" + * cdef DTYPE_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], + * &tree1.node_bounds[0, i_node1, 0], # <<<<<<<<<<<<<< + * tree1.data.shape[1]) + * return fmax(0, (dist_pt - tree1.node_data[i_node1].radius + */ + if (unlikely(!__pyx_v_tree1->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = 0; + __pyx_t_5 = __pyx_v_i_node1; + __pyx_t_6 = 0; + + /* "sklearn/neighbors/ball_tree.pyx":141 + * cdef DTYPE_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], + * &tree1.node_bounds[0, i_node1, 0], + * tree1.data.shape[1]) # <<<<<<<<<<<<<< + * return fmax(0, (dist_pt - tree1.node_data[i_node1].radius + * - tree2.node_data[i_node2].radius)) + */ + if (unlikely(!__pyx_v_tree1->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + + /* "sklearn/neighbors/ball_tree.pyx":139 + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the minimum distance between two nodes""" + * cdef DTYPE_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], # <<<<<<<<<<<<<< + * &tree1.node_bounds[0, i_node1, 0], + * tree1.data.shape[1]) + */ + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(__pyx_v_tree1, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree2->node_bounds.data + __pyx_t_1 * __pyx_v_tree2->node_bounds.strides[0]) ) + __pyx_t_2 * __pyx_v_tree2->node_bounds.strides[1]) )) + __pyx_t_3)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree1->node_bounds.data + __pyx_t_4 * __pyx_v_tree1->node_bounds.strides[0]) ) + __pyx_t_5 * __pyx_v_tree1->node_bounds.strides[1]) )) + __pyx_t_6)) )))), (__pyx_v_tree1->data.shape[1])); if (unlikely(__pyx_t_7 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_7; + + /* "sklearn/neighbors/ball_tree.pyx":142 + * &tree1.node_bounds[0, i_node1, 0], + * tree1.data.shape[1]) + * return fmax(0, (dist_pt - tree1.node_data[i_node1].radius # <<<<<<<<<<<<<< + * - tree2.node_data[i_node2].radius)) + * + */ + if (unlikely(!__pyx_v_tree1->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_8 = __pyx_v_i_node1; + + /* "sklearn/neighbors/ball_tree.pyx":143 + * tree1.data.shape[1]) + * return fmax(0, (dist_pt - tree1.node_data[i_node1].radius + * - tree2.node_data[i_node2].radius)) # <<<<<<<<<<<<<< + * + * + */ + if (unlikely(!__pyx_v_tree2->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = __pyx_v_i_node2; + + /* "sklearn/neighbors/ball_tree.pyx":142 + * &tree1.node_bounds[0, i_node1, 0], + * tree1.data.shape[1]) + * return fmax(0, (dist_pt - tree1.node_data[i_node1].radius # <<<<<<<<<<<<<< + * - tree2.node_data[i_node2].radius)) + * + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_9ball_tree_fmax(0.0, ((__pyx_v_dist_pt - (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_tree1->node_data.data) + __pyx_t_8)) ))).radius) - (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_tree2->node_data.data) + __pyx_t_9)) ))).radius)); + goto __pyx_L0; + + /* "sklearn/neighbors/ball_tree.pyx":136 + * + * + * cdef inline DTYPE_t min_dist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the minimum distance between two nodes""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.min_dist_dual", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/ball_tree.pyx":146 + * + * + * cdef inline DTYPE_t max_dist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the maximum distance between two nodes""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_max_dist_dual(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("max_dist_dual", 0); + + /* "sklearn/neighbors/ball_tree.pyx":149 + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the maximum distance between two nodes""" + * cdef DTYPE_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], # <<<<<<<<<<<<<< + * &tree1.node_bounds[0, i_node1, 0], + * tree1.data.shape[1]) + */ + if (unlikely(!__pyx_v_tree2->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = __pyx_v_i_node2; + __pyx_t_3 = 0; + + /* "sklearn/neighbors/ball_tree.pyx":150 + * """compute the maximum distance between two nodes""" + * cdef DTYPE_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], + * &tree1.node_bounds[0, i_node1, 0], # <<<<<<<<<<<<<< + * tree1.data.shape[1]) + * return (dist_pt + tree1.node_data[i_node1].radius + */ + if (unlikely(!__pyx_v_tree1->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = 0; + __pyx_t_5 = __pyx_v_i_node1; + __pyx_t_6 = 0; + + /* "sklearn/neighbors/ball_tree.pyx":151 + * cdef DTYPE_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], + * &tree1.node_bounds[0, i_node1, 0], + * tree1.data.shape[1]) # <<<<<<<<<<<<<< + * return (dist_pt + tree1.node_data[i_node1].radius + * + tree2.node_data[i_node2].radius) + */ + if (unlikely(!__pyx_v_tree1->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + + /* "sklearn/neighbors/ball_tree.pyx":149 + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the maximum distance between two nodes""" + * cdef DTYPE_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], # <<<<<<<<<<<<<< + * &tree1.node_bounds[0, i_node1, 0], + * tree1.data.shape[1]) + */ + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist(__pyx_v_tree1, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree2->node_bounds.data + __pyx_t_1 * __pyx_v_tree2->node_bounds.strides[0]) ) + __pyx_t_2 * __pyx_v_tree2->node_bounds.strides[1]) )) + __pyx_t_3)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree1->node_bounds.data + __pyx_t_4 * __pyx_v_tree1->node_bounds.strides[0]) ) + __pyx_t_5 * __pyx_v_tree1->node_bounds.strides[1]) )) + __pyx_t_6)) )))), (__pyx_v_tree1->data.shape[1])); if (unlikely(__pyx_t_7 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_7; + + /* "sklearn/neighbors/ball_tree.pyx":152 + * &tree1.node_bounds[0, i_node1, 0], + * tree1.data.shape[1]) + * return (dist_pt + tree1.node_data[i_node1].radius # <<<<<<<<<<<<<< + * + tree2.node_data[i_node2].radius) + * + */ + if (unlikely(!__pyx_v_tree1->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_8 = __pyx_v_i_node1; + + /* "sklearn/neighbors/ball_tree.pyx":153 + * tree1.data.shape[1]) + * return (dist_pt + tree1.node_data[i_node1].radius + * + tree2.node_data[i_node2].radius) # <<<<<<<<<<<<<< + * + * + */ + if (unlikely(!__pyx_v_tree2->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = __pyx_v_i_node2; + __pyx_r = ((__pyx_v_dist_pt + (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_tree1->node_data.data) + __pyx_t_8)) ))).radius) + (*((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) __pyx_v_tree2->node_data.data) + __pyx_t_9)) ))).radius); + goto __pyx_L0; + + /* "sklearn/neighbors/ball_tree.pyx":146 + * + * + * cdef inline DTYPE_t max_dist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the maximum distance between two nodes""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.max_dist_dual", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/ball_tree.pyx":156 + * + * + * cdef inline DTYPE_t min_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the minimum reduced distance between two nodes""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_min_rdist_dual(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("min_rdist_dual", 0); + + /* "sklearn/neighbors/ball_tree.pyx":159 + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the minimum reduced distance between two nodes""" + * if tree1.euclidean: # <<<<<<<<<<<<<< + * return euclidean_dist_to_rdist(min_dist_dual(tree1, i_node1, + * tree2, i_node2)) + */ + __pyx_t_1 = (__pyx_v_tree1->euclidean != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/ball_tree.pyx":160 + * """compute the minimum reduced distance between two nodes""" + * if tree1.euclidean: + * return euclidean_dist_to_rdist(min_dist_dual(tree1, i_node1, # <<<<<<<<<<<<<< + * tree2, i_node2)) + * else: + */ + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_dist_dual(__pyx_v_tree1, __pyx_v_i_node1, __pyx_v_tree2, __pyx_v_i_node2); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist_to_rdist(__pyx_t_2); if (unlikely(__pyx_t_3 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_3; + goto __pyx_L0; + } + /*else*/ { + + /* "sklearn/neighbors/ball_tree.pyx":163 + * tree2, i_node2)) + * else: + * return tree1.dist_metric._dist_to_rdist(min_dist_dual(tree1, i_node1, # <<<<<<<<<<<<<< + * tree2, i_node2)) + * + */ + __pyx_t_3 = __pyx_f_7sklearn_9neighbors_9ball_tree_min_dist_dual(__pyx_v_tree1, __pyx_v_i_node1, __pyx_v_tree2, __pyx_v_i_node2); if (unlikely(__pyx_t_3 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_tree1->dist_metric->__pyx_vtab)->_dist_to_rdist(__pyx_v_tree1->dist_metric, __pyx_t_3); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + + /* "sklearn/neighbors/ball_tree.pyx":156 + * + * + * cdef inline DTYPE_t min_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the minimum reduced distance between two nodes""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.min_rdist_dual", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/ball_tree.pyx":167 + * + * + * cdef inline DTYPE_t max_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the maximum reduced distance between two nodes""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_9ball_tree_max_rdist_dual(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *__pyx_v_tree2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("max_rdist_dual", 0); + + /* "sklearn/neighbors/ball_tree.pyx":170 + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the maximum reduced distance between two nodes""" + * if tree1.euclidean: # <<<<<<<<<<<<<< + * return euclidean_dist_to_rdist(max_dist_dual(tree1, i_node1, + * tree2, i_node2)) + */ + __pyx_t_1 = (__pyx_v_tree1->euclidean != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/ball_tree.pyx":171 + * """compute the maximum reduced distance between two nodes""" + * if tree1.euclidean: + * return euclidean_dist_to_rdist(max_dist_dual(tree1, i_node1, # <<<<<<<<<<<<<< + * tree2, i_node2)) + * else: + */ + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_9ball_tree_max_dist_dual(__pyx_v_tree1, __pyx_v_i_node1, __pyx_v_tree2, __pyx_v_i_node2); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist_to_rdist(__pyx_t_2); if (unlikely(__pyx_t_3 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_3; + goto __pyx_L0; + } + /*else*/ { + + /* "sklearn/neighbors/ball_tree.pyx":174 + * tree2, i_node2)) + * else: + * return tree1.dist_metric._dist_to_rdist(max_dist_dual(tree1, i_node1, # <<<<<<<<<<<<<< + * tree2, i_node2)) + */ + __pyx_t_3 = __pyx_f_7sklearn_9neighbors_9ball_tree_max_dist_dual(__pyx_v_tree1, __pyx_v_i_node1, __pyx_v_tree2, __pyx_v_i_node2); if (unlikely(__pyx_t_3 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_tree1->dist_metric->__pyx_vtab)->_dist_to_rdist(__pyx_v_tree1->dist_metric, __pyx_t_3); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + + /* "sklearn/neighbors/ball_tree.pyx":167 + * + * + * cdef inline DTYPE_t max_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """compute the maximum reduced distance between two nodes""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.ball_tree.max_rdist_dual", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "dist_metrics.pxd":18 + * # We use these for the default (euclidean) case so that they can be + * # inlined. This leads to faster computation for the most common case + * cdef inline DTYPE_t euclidean_dist(DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_tmp; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("euclidean_dist", 0); + + /* "dist_metrics.pxd":20 + * cdef inline DTYPE_t euclidean_dist(DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "dist_metrics.pxd":22 + * cdef DTYPE_t tmp, d=0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tmp = x1[j] - x2[j] + * d += tmp * tmp + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "dist_metrics.pxd":23 + * cdef np.intp_t j + * for j in range(size): + * tmp = x1[j] - x2[j] # <<<<<<<<<<<<<< + * d += tmp * tmp + * return sqrt(d) + */ + __pyx_v_tmp = ((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j])); + + /* "dist_metrics.pxd":24 + * for j in range(size): + * tmp = x1[j] - x2[j] + * d += tmp * tmp # <<<<<<<<<<<<<< + * return sqrt(d) + * + */ + __pyx_v_d = (__pyx_v_d + (__pyx_v_tmp * __pyx_v_tmp)); + } + + /* "dist_metrics.pxd":25 + * tmp = x1[j] - x2[j] + * d += tmp * tmp + * return sqrt(d) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = sqrt(__pyx_v_d); + goto __pyx_L0; + + /* "dist_metrics.pxd":18 + * # We use these for the default (euclidean) case so that they can be + * # inlined. This leads to faster computation for the most common case + * cdef inline DTYPE_t euclidean_dist(DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "dist_metrics.pxd":28 + * + * + * cdef inline DTYPE_t euclidean_rdist(DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_tmp; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("euclidean_rdist", 0); + + /* "dist_metrics.pxd":30 + * cdef inline DTYPE_t euclidean_rdist(DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "dist_metrics.pxd":32 + * cdef DTYPE_t tmp, d=0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tmp = x1[j] - x2[j] + * d += tmp * tmp + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "dist_metrics.pxd":33 + * cdef np.intp_t j + * for j in range(size): + * tmp = x1[j] - x2[j] # <<<<<<<<<<<<<< + * d += tmp * tmp + * return d + */ + __pyx_v_tmp = ((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j])); + + /* "dist_metrics.pxd":34 + * for j in range(size): + * tmp = x1[j] - x2[j] + * d += tmp * tmp # <<<<<<<<<<<<<< + * return d + * + */ + __pyx_v_d = (__pyx_v_d + (__pyx_v_tmp * __pyx_v_tmp)); + } + + /* "dist_metrics.pxd":35 + * tmp = x1[j] - x2[j] + * d += tmp * tmp + * return d # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_d; + goto __pyx_L0; + + /* "dist_metrics.pxd":28 + * + * + * cdef inline DTYPE_t euclidean_rdist(DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "dist_metrics.pxd":38 + * + * + * cdef inline DTYPE_t euclidean_dist_to_rdist(DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return dist * dist + * + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist_to_rdist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("euclidean_dist_to_rdist", 0); + + /* "dist_metrics.pxd":39 + * + * cdef inline DTYPE_t euclidean_dist_to_rdist(DTYPE_t dist) except -1: + * return dist * dist # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (__pyx_v_dist * __pyx_v_dist); + goto __pyx_L0; + + /* "dist_metrics.pxd":38 + * + * + * cdef inline DTYPE_t euclidean_dist_to_rdist(DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return dist * dist + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "dist_metrics.pxd":42 + * + * + * cdef inline DTYPE_t euclidean_rdist_to_dist(DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return sqrt(dist) + * + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist_to_dist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("euclidean_rdist_to_dist", 0); + + /* "dist_metrics.pxd":43 + * + * cdef inline DTYPE_t euclidean_rdist_to_dist(DTYPE_t dist) except -1: + * return sqrt(dist) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = sqrt(__pyx_v_dist); + goto __pyx_L0; + + /* "dist_metrics.pxd":42 + * + * + * cdef inline DTYPE_t euclidean_rdist_to_dist(DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return sqrt(dist) + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__33, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_3) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__34, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":222 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":251 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); + if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_1) { + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__35, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< + * info.format + _buffer_format_string_len, + * &offset) + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + long __pyx_t_10; + char *__pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); + __pyx_t_3 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":798 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__36, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_6 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_6) { + __pyx_t_7 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_7 = __pyx_t_6; + } + if (!__pyx_t_7) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_6 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_6) { + __pyx_t_8 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_9 = __pyx_t_8; + } else { + __pyx_t_9 = __pyx_t_6; + } + __pyx_t_6 = __pyx_t_9; + } else { + __pyx_t_6 = __pyx_t_7; + } + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__37, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":813 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_6) break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":818 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":821 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__38, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L11; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L11:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L9; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_11; + } + __pyx_L9:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":968 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":969 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":971 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":972 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":973 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":974 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":977 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":978 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":980 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + +/* Python wrapper */ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_shape = 0; + Py_ssize_t __pyx_v_itemsize; + PyObject *__pyx_v_format = 0; + PyObject *__pyx_v_mode = 0; + int __pyx_v_allocate_buffer; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[3] = ((PyObject *)__pyx_n_s_c); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mode); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_allocate_buffer); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_shape = ((PyObject*)values[0]); + __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_format = values[2]; + __pyx_v_mode = values[3]; + if (values[4]) { + __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "View.MemoryView":117 + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, + * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_v_allocate_buffer = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { + PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_r = __pyx_array_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); + + /* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { + int __pyx_v_idx; + Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_dim; + PyObject **__pyx_v_p; + char __pyx_v_order; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + char *__pyx_t_5; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_INCREF(__pyx_v_format); + + /* "View.MemoryView":123 + * cdef PyObject **p + * + * self.ndim = len(shape) # <<<<<<<<<<<<<< + * self.itemsize = itemsize + * + */ + if (unlikely(__pyx_v_shape == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->ndim = ((int)__pyx_t_1); + + /* "View.MemoryView":124 + * + * self.ndim = len(shape) + * self.itemsize = itemsize # <<<<<<<<<<<<<< + * + * if not self.ndim: + */ + __pyx_v_self->itemsize = __pyx_v_itemsize; + + /* "View.MemoryView":126 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ + __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":127 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if itemsize <= 0: + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__39, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":129 + * raise ValueError("Empty shape tuple for cython.array") + * + * if itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ + __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":130 + * + * if itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * if isinstance(format, unicode): + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__40, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":132 + * raise ValueError("itemsize <= 0 for cython.array") + * + * if isinstance(format, unicode): # <<<<<<<<<<<<<< + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string + */ + __pyx_t_2 = PyUnicode_Check(__pyx_v_format); + __pyx_t_4 = (__pyx_t_2 != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":133 + * + * if isinstance(format, unicode): + * format = (format).encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format # keep a reference to the byte string + * self.format = self._format + */ + if (unlikely(__pyx_v_format == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", "encode"); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = PyUnicode_AsASCIIString(((PyObject*)__pyx_v_format)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":134 + * if isinstance(format, unicode): + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< + * self.format = self._format + * + */ + if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_v_format; + __Pyx_INCREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->_format); + __Pyx_DECREF(__pyx_v_self->_format); + __pyx_v_self->_format = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":135 + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string + * self.format = self._format # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __Pyx_PyObject_AsString(__pyx_v_self->_format); if (unlikely((!__pyx_t_5) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->format = __pyx_t_5; + + /* "View.MemoryView":138 + * + * + * self._shape = PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< + * self._strides = self._shape + self.ndim + * + */ + __pyx_v_self->_shape = ((Py_ssize_t *)PyMem_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); + + /* "View.MemoryView":139 + * + * self._shape = PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) + * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< + * + * if not self._shape: + */ + __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); + + /* "View.MemoryView":141 + * self._strides = self._shape + self.ndim + * + * if not self._shape: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape and strides.") + * + */ + __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":142 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__41, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":145 + * + * + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + __pyx_t_6 = 0; + __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; + for (;;) { + if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_7); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_t_8 = __Pyx_PyIndex_AsSsize_t(__pyx_t_7); if (unlikely((__pyx_t_8 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_dim = __pyx_t_8; + __pyx_v_idx = __pyx_t_6; + __pyx_t_6 = (__pyx_t_6 + 1); + + /* "View.MemoryView":146 + * + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim + */ + __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":147 + * for idx, dim in enumerate(shape): + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< + * self._shape[idx] = dim + * + */ + __pyx_t_7 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_7 = 0; + __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_10, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":148 + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim # <<<<<<<<<<<<<< + * + * cdef char order + */ + (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":151 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = b'F' + * self.mode = u'fortran' + */ + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":152 + * cdef char order + * if mode == 'fortran': + * order = b'F' # <<<<<<<<<<<<<< + * self.mode = u'fortran' + * elif mode == 'c': + */ + __pyx_v_order = 'F'; + + /* "View.MemoryView":153 + * if mode == 'fortran': + * order = b'F' + * self.mode = u'fortran' # <<<<<<<<<<<<<< + * elif mode == 'c': + * order = b'C' + */ + __Pyx_INCREF(__pyx_n_u_fortran); + __Pyx_GIVEREF(__pyx_n_u_fortran); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(__pyx_v_self->mode); + __pyx_v_self->mode = __pyx_n_u_fortran; + goto __pyx_L10; + } + + /* "View.MemoryView":154 + * order = b'F' + * self.mode = u'fortran' + * elif mode == 'c': # <<<<<<<<<<<<<< + * order = b'C' + * self.mode = u'c' + */ + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":155 + * self.mode = u'fortran' + * elif mode == 'c': + * order = b'C' # <<<<<<<<<<<<<< + * self.mode = u'c' + * else: + */ + __pyx_v_order = 'C'; + + /* "View.MemoryView":156 + * elif mode == 'c': + * order = b'C' + * self.mode = u'c' # <<<<<<<<<<<<<< + * else: + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + */ + __Pyx_INCREF(__pyx_n_u_c); + __Pyx_GIVEREF(__pyx_n_u_c); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(__pyx_v_self->mode); + __pyx_v_self->mode = __pyx_n_u_c; + goto __pyx_L10; + } + /*else*/ { + + /* "View.MemoryView":158 + * self.mode = u'c' + * else: + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< + * + * self.len = fill_contig_strides_array(self._shape, self._strides, + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L10:; + + /* "View.MemoryView":160 + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + * + * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< + * itemsize, self.ndim, order) + * + */ + __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); + + /* "View.MemoryView":163 + * itemsize, self.ndim, order) + * + * self.free_data = allocate_buffer # <<<<<<<<<<<<<< + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + */ + __pyx_v_self->free_data = __pyx_v_allocate_buffer; + + /* "View.MemoryView":164 + * + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< + * if allocate_buffer: + * + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_4; + + /* "View.MemoryView":165 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = (__pyx_v_allocate_buffer != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":168 + * + * + * self.data = malloc(self.len) # <<<<<<<<<<<<<< + * if not self.data: + * raise MemoryError("unable to allocate array data.") + */ + __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); + + /* "View.MemoryView":169 + * + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ + __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":170 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__42, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":172 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ + __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":173 + * + * if self.dtype_is_object: + * p = self.data # <<<<<<<<<<<<<< + * for i in range(self.len / itemsize): + * p[i] = Py_None + */ + __pyx_v_p = ((PyObject **)__pyx_v_self->data); + + /* "View.MemoryView":174 + * if self.dtype_is_object: + * p = self.data + * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< + * p[i] = Py_None + * Py_INCREF(Py_None) + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = (__pyx_v_self->len / __pyx_v_itemsize); + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_1; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "View.MemoryView":175 + * p = self.data + * for i in range(self.len / itemsize): + * p[i] = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + (__pyx_v_p[__pyx_v_i]) = Py_None; + + /* "View.MemoryView":176 + * for i in range(self.len / itemsize): + * p[i] = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + Py_INCREF(Py_None); + } + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_format); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":179 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == u"c": + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_bufmode; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + Py_ssize_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":180 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 # <<<<<<<<<<<<<< + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = -1; + + /* "View.MemoryView":181 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == u"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + */ + __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":182 + * cdef int bufmode = -1 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + + /* "View.MemoryView":183 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ + __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":184 + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + */ + __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":185 + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ + __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":186 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__43, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":187 + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data # <<<<<<<<<<<<<< + * info.len = self.len + * info.ndim = self.ndim + */ + __pyx_t_4 = __pyx_v_self->data; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":188 + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + * info.len = self.len # <<<<<<<<<<<<<< + * info.ndim = self.ndim + * info.shape = self._shape + */ + __pyx_t_5 = __pyx_v_self->len; + __pyx_v_info->len = __pyx_t_5; + + /* "View.MemoryView":189 + * info.buf = self.data + * info.len = self.len + * info.ndim = self.ndim # <<<<<<<<<<<<<< + * info.shape = self._shape + * info.strides = self._strides + */ + __pyx_t_6 = __pyx_v_self->ndim; + __pyx_v_info->ndim = __pyx_t_6; + + /* "View.MemoryView":190 + * info.len = self.len + * info.ndim = self.ndim + * info.shape = self._shape # <<<<<<<<<<<<<< + * info.strides = self._strides + * info.suboffsets = NULL + */ + __pyx_t_7 = __pyx_v_self->_shape; + __pyx_v_info->shape = __pyx_t_7; + + /* "View.MemoryView":191 + * info.ndim = self.ndim + * info.shape = self._shape + * info.strides = self._strides # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = self.itemsize + */ + __pyx_t_7 = __pyx_v_self->_strides; + __pyx_v_info->strides = __pyx_t_7; + + /* "View.MemoryView":192 + * info.shape = self._shape + * info.strides = self._strides + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = self.itemsize + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; + + /* "View.MemoryView":193 + * info.strides = self._strides + * info.suboffsets = NULL + * info.itemsize = self.itemsize # <<<<<<<<<<<<<< + * info.readonly = 0 + * + */ + __pyx_t_5 = __pyx_v_self->itemsize; + __pyx_v_info->itemsize = __pyx_t_5; + + /* "View.MemoryView":194 + * info.suboffsets = NULL + * info.itemsize = self.itemsize + * info.readonly = 0 # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":196 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":197 + * + * if flags & PyBUF_FORMAT: + * info.format = self.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_4 = __pyx_v_self->format; + __pyx_v_info->format = __pyx_t_4; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":199 + * info.format = self.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.obj = self + */ + __pyx_v_info->format = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":201 + * info.format = NULL + * + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "View.MemoryView":179 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == u"c": + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":205 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + +/* Python wrapper */ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_array_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":206 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ + __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":207 + * def __dealloc__(array self): + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) # <<<<<<<<<<<<<< + * elif self.free_data: + * if self.dtype_is_object: + */ + __pyx_v_self->callback_free_data(__pyx_v_self->data); + goto __pyx_L3; + } + + /* "View.MemoryView":208 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ + __pyx_t_1 = (__pyx_v_self->free_data != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":209 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":210 + * elif self.free_data: + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< + * self._strides, self.ndim, False) + * free(self.data) + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":212 + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + * free(self.data) # <<<<<<<<<<<<<< + * PyMem_Free(self._shape) + * + */ + free(__pyx_v_self->data); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":213 + * self._strides, self.ndim, False) + * free(self.data) + * PyMem_Free(self._shape) # <<<<<<<<<<<<<< + * + * property memview: + */ + PyMem_Free(__pyx_v_self->_shape); + + /* "View.MemoryView":205 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":217 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + +/* Python wrapper */ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = get_memview_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":219 + * def __get__(self): + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< + * return memoryview(self, flags, self.dtype_is_object) + * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":220 + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":217 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":223 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":224 + * + * def __getattr__(self, attr): + * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * + * def __getitem__(self, item): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":223 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":226 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":227 + * + * def __getitem__(self, item): + * return self.memview[item] # <<<<<<<<<<<<<< + * + * def __setitem__(self, item, value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":226 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":229 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + +/* Python wrapper */ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "View.MemoryView":230 + * + * def __setitem__(self, item, value): + * self.memview[item] = value # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":229 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":234 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + +static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { + struct __pyx_array_obj *__pyx_v_result = 0; + struct __pyx_array_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("array_cwrapper", 0); + + /* "View.MemoryView":238 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":239 + * + * if buf == NULL: + * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":241 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":242 + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) # <<<<<<<<<<<<<< + * result.data = buf + * + */ + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":241 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":243 + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) + * result.data = buf # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->data = __pyx_v_buf; + } + __pyx_L3:; + + /* "View.MemoryView":245 + * result.data = buf + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":234 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":271 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + +/* Python wrapper */ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_name = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name_2,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_name_2)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_name = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "View.MemoryView":272 + * cdef object name + * def __init__(self, name): + * self.name = name # <<<<<<<<<<<<<< + * def __repr__(self): + * return self.name + */ + __Pyx_INCREF(__pyx_v_name); + __Pyx_GIVEREF(__pyx_v_name); + __Pyx_GOTREF(__pyx_v_self->name); + __Pyx_DECREF(__pyx_v_self->name); + __pyx_v_self->name = __pyx_v_name; + + /* "View.MemoryView":271 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":273 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + +/* Python wrapper */ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":274 + * self.name = name + * def __repr__(self): + * return self.name # <<<<<<<<<<<<<< + * + * cdef generic = Enum("") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->name); + __pyx_r = __pyx_v_self->name; + goto __pyx_L0; + + /* "View.MemoryView":273 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":288 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + +static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { + Py_intptr_t __pyx_v_aligned_p; + size_t __pyx_v_offset; + void *__pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":290 + * cdef void *align_pointer(void *memory, size_t alignment) nogil: + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< + * cdef size_t offset + * + */ + __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + + /* "View.MemoryView":294 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":296 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + __pyx_t_1 = ((__pyx_v_offset > 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":297 + * + * if offset > 0: + * aligned_p += alignment - offset # <<<<<<<<<<<<<< + * + * return aligned_p + */ + __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":299 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview') + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + /* "View.MemoryView":288 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":317 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + +/* Python wrapper */ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_obj = 0; + int __pyx_v_flags; + int __pyx_v_dtype_is_object; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dtype_is_object); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_obj = values[0]; + __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[2]) { + __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_dtype_is_object = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_memoryview_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "View.MemoryView":318 + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj # <<<<<<<<<<<<<< + * self.flags = flags + * if type(self) is memoryview or obj is not None: + */ + __Pyx_INCREF(__pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __Pyx_GOTREF(__pyx_v_self->obj); + __Pyx_DECREF(__pyx_v_self->obj); + __pyx_v_self->obj = __pyx_v_obj; + + /* "View.MemoryView":319 + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj + * self.flags = flags # <<<<<<<<<<<<<< + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + */ + __pyx_v_self->flags = __pyx_v_flags; + + /* "View.MemoryView":320 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ + __pyx_t_1 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type))); + if (!(__pyx_t_1 != 0)) { + __pyx_t_2 = (__pyx_v_obj != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + } else { + __pyx_t_3 = (__pyx_t_1 != 0); + } + if (__pyx_t_3) { + + /* "View.MemoryView":321 + * self.flags = flags + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + */ + __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":322 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_t_3 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":323 + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; + + /* "View.MemoryView":324 + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * self.lock = PyThread_allocate_lock() + */ + Py_INCREF(Py_None); + goto __pyx_L4; + } + __pyx_L4:; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":326 + * Py_INCREF(Py_None) + * + * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< + * if self.lock == NULL: + * raise MemoryError + */ + __pyx_v_self->lock = PyThread_allocate_lock(); + + /* "View.MemoryView":327 + * + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + __pyx_t_3 = ((__pyx_v_self->lock == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":328 + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":330 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = self.view.format == b'O' + * else: + */ + __pyx_t_3 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":331 + * + * if flags & PyBUF_FORMAT: + * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< + * else: + * self.dtype_is_object = dtype_is_object + */ + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_5, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":333 + * self.dtype_is_object = self.view.format == b'O' + * else: + * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + */ + __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; + } + __pyx_L6:; + + /* "View.MemoryView":335 + * self.dtype_is_object = dtype_is_object + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL + */ + __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); + + /* "View.MemoryView":337 + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(memoryview self): + */ + __pyx_v_self->typeinfo = NULL; + + /* "View.MemoryView":317 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":339 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + +/* Python wrapper */ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":340 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< + * __Pyx_ReleaseBuffer(&self.view) + * + */ + __pyx_t_1 = (__pyx_v_self->obj != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":341 + * def __dealloc__(memoryview self): + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< + * + * if self.lock != NULL: + */ + __Pyx_ReleaseBuffer((&__pyx_v_self->view)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":343 + * __Pyx_ReleaseBuffer(&self.view) + * + * if self.lock != NULL: # <<<<<<<<<<<<<< + * PyThread_free_lock(self.lock) + * + */ + __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":344 + * + * if self.lock != NULL: + * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + */ + PyThread_free_lock(__pyx_v_self->lock); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":339 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":346 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + Py_ssize_t __pyx_v_dim; + char *__pyx_v_itemp; + PyObject *__pyx_v_idx = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_item_pointer", 0); + + /* "View.MemoryView":348 + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< + * + * for dim, idx in enumerate(index): + */ + __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); + + /* "View.MemoryView":350 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + __pyx_t_1 = 0; + if (PyList_CheckExact(__pyx_v_index) || PyTuple_CheckExact(__pyx_v_index)) { + __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; + } + for (;;) { + if (!__pyx_t_4 && PyList_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_4 && PyTuple_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); + __pyx_t_5 = 0; + __pyx_v_dim = __pyx_t_1; + __pyx_t_1 = (__pyx_t_1 + 1); + + /* "View.MemoryView":351 + * + * for dim, idx in enumerate(index): + * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< + * + * return itemp + */ + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_7; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":353 + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + * return itemp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_itemp; + goto __pyx_L0; + + /* "View.MemoryView":346 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":356 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_indices = NULL; + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + char *__pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":357 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":358 + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: + * return self # <<<<<<<<<<<<<< + * + * have_slices, indices = _unellipsify(index, self.view.ndim) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __pyx_r = ((PyObject *)__pyx_v_self); + goto __pyx_L0; + } + + /* "View.MemoryView":360 + * return self + * + * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * cdef char *itemp + */ + __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (likely(__pyx_t_3 != Py_None)) { + PyObject* sequence = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_have_slices = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; + + /* "View.MemoryView":363 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":364 + * cdef char *itemp + * if have_slices: + * return memview_slice(self, indices) # <<<<<<<<<<<<<< + * else: + * itemp = self.get_item_pointer(indices) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 364; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":366 + * return memview_slice(self, indices) + * else: + * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< + * return self.convert_item_to_object(itemp) + * + */ + __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_6; + + /* "View.MemoryView":367 + * else: + * itemp = self.get_item_pointer(indices) + * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< + * + * def __setitem__(memoryview self, object index, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 367; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":356 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":369 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + +/* Python wrapper */ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_obj = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_INCREF(__pyx_v_index); + + /* "View.MemoryView":370 + * + * def __setitem__(memoryview self, object index, object value): + * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * if have_slices: + */ + __pyx_t_1 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (likely(__pyx_t_1 != Py_None)) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_have_slices = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":372 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":373 + * + * if have_slices: + * obj = self.is_slice(value) # <<<<<<<<<<<<<< + * if obj: + * self.setitem_slice_assignment(self[index], obj) + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_obj = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":374 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":375 + * obj = self.is_slice(value) + * if obj: + * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< + * else: + * self.setitem_slice_assign_scalar(self[index], value) + */ + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":377 + * self.setitem_slice_assignment(self[index], obj) + * else: + * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< + * else: + * self.setitem_indexed(index, value) + */ + __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":379 + * self.setitem_slice_assign_scalar(self[index], value) + * else: + * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< + * + * cdef is_slice(self, obj): + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":369 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":381 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_slice", 0); + __Pyx_INCREF(__pyx_v_obj); + + /* "View.MemoryView":382 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type)); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":383 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + { + __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + /*try:*/ { + + /* "View.MemoryView":384 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_6 = __Pyx_PyInt_From_int((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":385 + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * except TypeError: + * return None + */ + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":384 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); + __pyx_t_7 = 0; + } + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L11_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":386 + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + * except TypeError: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":387 + * self.dtype_is_object) + * except TypeError: + * return None # <<<<<<<<<<<<<< + * + * return obj + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L7_except_return; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L5_exception_handled; + } + goto __pyx_L6_except_error; + __pyx_L6_except_error:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L1_error; + __pyx_L7_except_return:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L0; + __pyx_L5_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + __pyx_L11_try_end:; + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":389 + * return None + * + * return obj # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assignment(self, dst, src): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_obj); + __pyx_r = __pyx_v_obj; + goto __pyx_L0; + + /* "View.MemoryView":381 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":391 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { + __Pyx_memviewslice __pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_src_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); + + /* "View.MemoryView":395 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":396 + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< + * src.ndim, dst.ndim, self.dtype_is_object) + * + */ + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":397 + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":395 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":391 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":399 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { + int __pyx_v_array[128]; + void *__pyx_v_tmp; + void *__pyx_v_item; + __Pyx_memviewslice *__pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_tmp_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + char const *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); + + /* "View.MemoryView":401 + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + * cdef int array[128] + * cdef void *tmp = NULL # <<<<<<<<<<<<<< + * cdef void *item + * + */ + __pyx_v_tmp = NULL; + + /* "View.MemoryView":406 + * cdef __Pyx_memviewslice *dst_slice + * cdef __Pyx_memviewslice tmp_slice + * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< + * + * if self.view.itemsize > sizeof(array): + */ + __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); + + /* "View.MemoryView":408 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + */ + __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":409 + * + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError + */ + __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); + + /* "View.MemoryView":410 + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":411 + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * item = tmp + * else: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":412 + * if tmp == NULL: + * raise MemoryError + * item = tmp # <<<<<<<<<<<<<< + * else: + * item = array + */ + __pyx_v_item = __pyx_v_tmp; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":414 + * item = tmp + * else: + * item = array # <<<<<<<<<<<<<< + * + * try: + */ + __pyx_v_item = ((void *)__pyx_v_array); + } + __pyx_L3:; + + /* "View.MemoryView":416 + * item = array + * + * try: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * ( item)[0] = value + */ + /*try:*/ { + + /* "View.MemoryView":417 + * + * try: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":418 + * try: + * if self.dtype_is_object: + * ( item)[0] = value # <<<<<<<<<<<<<< + * else: + * self.assign_item_from_object( item, value) + */ + (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); + goto __pyx_L8; + } + /*else*/ { + + /* "View.MemoryView":420 + * ( item)[0] = value + * else: + * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_L8:; + + /* "View.MemoryView":424 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":425 + * + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + */ + __pyx_t_2 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":426 + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< + * item, self.dtype_is_object) + * finally: + */ + __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); + } + + /* "View.MemoryView":429 + * item, self.dtype_is_object) + * finally: + * PyMem_Free(tmp) # <<<<<<<<<<<<<< + * + * cdef setitem_indexed(self, index, value): + */ + /*finally:*/ { + /*normal exit:*/{ + PyMem_Free(__pyx_v_tmp); + goto __pyx_L7; + } + /*exception exit:*/{ + __pyx_L6_error:; + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8) < 0)) __Pyx_ErrFetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_11); + __pyx_t_3 = __pyx_lineno; __pyx_t_4 = __pyx_clineno; __pyx_t_5 = __pyx_filename; + { + PyMem_Free(__pyx_v_tmp); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } + __Pyx_XGIVEREF(__pyx_t_6); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_ErrRestore(__pyx_t_6, __pyx_t_7, __pyx_t_8); + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __pyx_lineno = __pyx_t_3; __pyx_clineno = __pyx_t_4; __pyx_filename = __pyx_t_5; + goto __pyx_L1_error; + } + __pyx_L7:; + } + + /* "View.MemoryView":399 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":431 + * PyMem_Free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_indexed", 0); + + /* "View.MemoryView":432 + * + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< + * self.assign_item_from_object(itemp, value) + * + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_1; + + /* "View.MemoryView":433 + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":431 + * PyMem_Free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":435 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_v_struct = NULL; + PyObject *__pyx_v_bytesitem = 0; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":438 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef bytes bytesitem + * + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":441 + * cdef bytes bytesitem + * + * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< + * try: + * result = struct.unpack(self.view.format, bytesitem) + */ + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":442 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":443 + * bytesitem = itemp[:self.view.itemsize] + * try: + * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< + * except struct.error: + * raise ValueError("Unable to convert item to object") + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_bytesitem); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_v_bytesitem); + __Pyx_GIVEREF(__pyx_v_bytesitem); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + } + /*else:*/ { + + /* "View.MemoryView":447 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + __pyx_t_7 = strlen(__pyx_v_self->view.format); + __pyx_t_8 = ((__pyx_t_7 == 1) != 0); + if (__pyx_t_8) { + + /* "View.MemoryView":448 + * else: + * if len(self.view.format) == 1: + * return result[0] # <<<<<<<<<<<<<< + * return result + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}; + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L6_except_return; + } + + /* "View.MemoryView":449 + * if len(self.view.format) == 1: + * return result[0] + * return result # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L6_except_return; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L10_try_end; + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":444 + * try: + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: # <<<<<<<<<<<<<< + * raise ValueError("Unable to convert item to object") + * else: + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_1) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_1); + + /* "View.MemoryView":445 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_t_10 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__44, NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L4_exception_handled; + } + goto __pyx_L5_except_error; + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L6_except_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + __pyx_L4_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L10_try_end:; + } + + /* "View.MemoryView":435 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesitem); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":451 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_v_struct = NULL; + char __pyx_v_c; + PyObject *__pyx_v_bytesvalue = 0; + Py_ssize_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + char *__pyx_t_10; + char *__pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":454 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef char c + * cdef bytes bytesvalue + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":459 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + __pyx_t_2 = PyTuple_Check(__pyx_v_value); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":460 + * + * if isinstance(value, tuple): + * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< + * else: + * bytesvalue = struct.pack(self.view.format, value) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":462 + * bytesvalue = struct.pack(self.view.format, *value) + * else: + * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< + * + * for i, c in enumerate(bytesvalue): + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_INCREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_1, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_6)->tp_name), 0))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":464 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = 0; + if (unlikely(__pyx_v_bytesvalue == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_INCREF(__pyx_v_bytesvalue); + __pyx_t_8 = __pyx_v_bytesvalue; + __pyx_t_10 = PyBytes_AS_STRING(__pyx_t_8); + __pyx_t_11 = (__pyx_t_10 + PyBytes_GET_SIZE(__pyx_t_8)); + for (__pyx_t_12 = __pyx_t_10; __pyx_t_12 < __pyx_t_11; __pyx_t_12++) { + __pyx_t_9 = __pyx_t_12; + __pyx_v_c = (__pyx_t_9[0]); + + /* "View.MemoryView":465 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + __pyx_v_i = __pyx_t_7; + + /* "View.MemoryView":464 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":465 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "View.MemoryView":451 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":468 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + char *__pyx_t_3; + void *__pyx_t_4; + int __pyx_t_5; + Py_ssize_t __pyx_t_6; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":469 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":470 + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape # <<<<<<<<<<<<<< + * else: + * info.shape = NULL + */ + __pyx_t_2 = __pyx_v_self->view.shape; + __pyx_v_info->shape = __pyx_t_2; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":472 + * info.shape = self.view.shape + * else: + * info.shape = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_STRIDES: + */ + __pyx_v_info->shape = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":474 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":475 + * + * if flags & PyBUF_STRIDES: + * info.strides = self.view.strides # <<<<<<<<<<<<<< + * else: + * info.strides = NULL + */ + __pyx_t_2 = __pyx_v_self->view.strides; + __pyx_v_info->strides = __pyx_t_2; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":477 + * info.strides = self.view.strides + * else: + * info.strides = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_INDIRECT: + */ + __pyx_v_info->strides = NULL; + } + __pyx_L4:; + + /* "View.MemoryView":479 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":480 + * + * if flags & PyBUF_INDIRECT: + * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< + * else: + * info.suboffsets = NULL + */ + __pyx_t_2 = __pyx_v_self->view.suboffsets; + __pyx_v_info->suboffsets = __pyx_t_2; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":482 + * info.suboffsets = self.view.suboffsets + * else: + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->suboffsets = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":484 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":485 + * + * if flags & PyBUF_FORMAT: + * info.format = self.view.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_3 = __pyx_v_self->view.format; + __pyx_v_info->format = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":487 + * info.format = self.view.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.buf = self.view.buf + */ + __pyx_v_info->format = NULL; + } + __pyx_L6:; + + /* "View.MemoryView":489 + * info.format = NULL + * + * info.buf = self.view.buf # <<<<<<<<<<<<<< + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + */ + __pyx_t_4 = __pyx_v_self->view.buf; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":490 + * + * info.buf = self.view.buf + * info.ndim = self.view.ndim # <<<<<<<<<<<<<< + * info.itemsize = self.view.itemsize + * info.len = self.view.len + */ + __pyx_t_5 = __pyx_v_self->view.ndim; + __pyx_v_info->ndim = __pyx_t_5; + + /* "View.MemoryView":491 + * info.buf = self.view.buf + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< + * info.len = self.view.len + * info.readonly = 0 + */ + __pyx_t_6 = __pyx_v_self->view.itemsize; + __pyx_v_info->itemsize = __pyx_t_6; + + /* "View.MemoryView":492 + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + * info.len = self.view.len # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.obj = self + */ + __pyx_t_6 = __pyx_v_self->view.len; + __pyx_v_info->len = __pyx_t_6; + + /* "View.MemoryView":493 + * info.itemsize = self.view.itemsize + * info.len = self.view.len + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.obj = self + * + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":494 + * info.len = self.view.len + * info.readonly = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "View.MemoryView":468 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + + /* function exit code */ + __pyx_r = 0; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":501 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":502 + * @cname('__pyx_memoryview_transpose') + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< + * transpose_memslice(&result.from_slice) + * return result + */ + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":503 + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":504 + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + * return result # <<<<<<<<<<<<<< + * + * property base: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":501 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":508 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":509 + * @cname('__pyx_memoryview__get__base') + * def __get__(self): + * return self.obj # <<<<<<<<<<<<<< + * + * property shape: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->obj); + __pyx_r = __pyx_v_self->obj; + goto __pyx_L0; + + /* "View.MemoryView":508 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":513 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":514 + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property strides: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_v_self->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->view.shape[__pyx_v_i])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __pyx_t_4 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + + /* "View.MemoryView":513 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":518 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":519 + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":521 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__45, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":523 + * raise ValueError("Buffer view does not expose strides") + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property suboffsets: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.strides[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":518 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":527 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":528 + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return [-1] * self.view.ndim + * + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":529 + * def __get__(self): + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(1 * ((__pyx_v_self->view.ndim<0) ? 0:__pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_self->view.ndim; __pyx_temp++) { + __Pyx_INCREF(__pyx_int_neg_1); + PyList_SET_ITEM(__pyx_t_2, __pyx_temp, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + } + } + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":531 + * return [-1] * self.view.ndim + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property ndim: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.suboffsets[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":527 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":535 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":536 + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): + * return self.view.ndim # <<<<<<<<<<<<<< + * + * property itemsize: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":535 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":540 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":541 + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): + * return self.view.itemsize # <<<<<<<<<<<<<< + * + * property nbytes: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 541; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":540 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":545 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":546 + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): + * return self.size * self.view.itemsize # <<<<<<<<<<<<<< + * + * property size: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":545 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":550 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":551 + * @cname('__pyx_memoryview_get_size') + * def __get__(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + __pyx_t_1 = (__pyx_v_self->_size == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":552 + * def __get__(self): + * if self._size is None: + * result = 1 # <<<<<<<<<<<<<< + * + * for length in self.shape: + */ + __Pyx_INCREF(__pyx_int_1); + __pyx_v_result = __pyx_int_1; + + /* "View.MemoryView":554 + * result = 1 + * + * for length in self.shape: # <<<<<<<<<<<<<< + * result *= length + * + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyList_CheckExact(__pyx_t_3) || PyTuple_CheckExact(__pyx_t_3)) { + __pyx_t_4 = __pyx_t_3; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_3 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_3)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":555 + * + * for length in self.shape: + * result *= length # <<<<<<<<<<<<<< + * + * self._size = result + */ + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 555; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_3); + __pyx_t_3 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "View.MemoryView":557 + * result *= length + * + * self._size = result # <<<<<<<<<<<<<< + * + * return self._size + */ + __Pyx_INCREF(__pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __Pyx_GOTREF(__pyx_v_self->_size); + __Pyx_DECREF(__pyx_v_self->_size); + __pyx_v_self->_size = __pyx_v_result; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":559 + * self._size = result + * + * return self._size # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->_size); + __pyx_r = __pyx_v_self->_size; + goto __pyx_L0; + + /* "View.MemoryView":550 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":561 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + +/* Python wrapper */ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__len__", 0); + + /* "View.MemoryView":562 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":563 + * def __len__(self): + * if self.view.ndim >= 1: + * return self.view.shape[0] # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_r = (__pyx_v_self->view.shape[0]); + goto __pyx_L0; + } + + /* "View.MemoryView":565 + * return self.view.shape[0] + * + * return 0 # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":561 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":567 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":568 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":569 + * def __repr__(self): + * return "" % (self.base.__class__.__name__, + * id(self)) # <<<<<<<<<<<<<< + * + * def __str__(self): + */ + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_id, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":568 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":567 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":571 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__str__", 0); + + /* "View.MemoryView":572 + * + * def __str__(self): + * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":571 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":575 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_c_contig", 0); + + /* "View.MemoryView":578 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":579 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< + * + * def is_f_contig(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":575 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":581 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_f_contig", 0); + + /* "View.MemoryView":584 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":585 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< + * + * def copy(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":581 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":587 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_mslice; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "View.MemoryView":589 + * def copy(self): + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &mslice) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); + + /* "View.MemoryView":591 + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + * + * slice_copy(self, &mslice) # <<<<<<<<<<<<<< + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); + + /* "View.MemoryView":592 + * + * slice_copy(self, &mslice) + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_C_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k_c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":597 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< + * + * def copy_fortran(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":587 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":599 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy_fortran", 0); + + /* "View.MemoryView":601 + * def copy_fortran(self): + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &src) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); + + /* "View.MemoryView":603 + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + * + * slice_copy(self, &src) # <<<<<<<<<<<<<< + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); + + /* "View.MemoryView":604 + * + * slice_copy(self, &src) + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_F_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k_fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dst = __pyx_t_1; + + /* "View.MemoryView":609 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":599 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":613 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + +static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { + struct __pyx_memoryview_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); + + /* "View.MemoryView":614 + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< + * result.typeinfo = typeinfo + * return result + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); + __Pyx_GIVEREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":615 + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_v_result->typeinfo = __pyx_v_typeinfo; + + /* "View.MemoryView":616 + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_check') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":613 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":619 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("memoryview_check", 0); + + /* "View.MemoryView":620 + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): + * return isinstance(o, memoryview) # <<<<<<<<<<<<<< + * + * cdef tuple _unellipsify(object index, int ndim): + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type)); + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + /* "View.MemoryView":619 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":622 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + +static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { + PyObject *__pyx_v_tup = NULL; + PyObject *__pyx_v_result = NULL; + int __pyx_v_have_slices; + int __pyx_v_seen_ellipsis; + CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_item = NULL; + Py_ssize_t __pyx_v_nslices; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + int __pyx_t_10; + int __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_unellipsify", 0); + + /* "View.MemoryView":627 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + __pyx_t_1 = PyTuple_Check(__pyx_v_index); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":628 + * """ + * if not isinstance(index, tuple): + * tup = (index,) # <<<<<<<<<<<<<< + * else: + * tup = index + */ + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_index); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); + __Pyx_GIVEREF(__pyx_v_index); + __pyx_v_tup = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":630 + * tup = (index,) + * else: + * tup = index # <<<<<<<<<<<<<< + * + * result = [] + */ + __Pyx_INCREF(__pyx_v_index); + __pyx_v_tup = __pyx_v_index; + } + __pyx_L3:; + + /* "View.MemoryView":632 + * tup = index + * + * result = [] # <<<<<<<<<<<<<< + * have_slices = False + * seen_ellipsis = False + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_result = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":633 + * + * result = [] + * have_slices = False # <<<<<<<<<<<<<< + * seen_ellipsis = False + * for idx, item in enumerate(tup): + */ + __pyx_v_have_slices = 0; + + /* "View.MemoryView":634 + * result = [] + * have_slices = False + * seen_ellipsis = False # <<<<<<<<<<<<<< + * for idx, item in enumerate(tup): + * if item is Ellipsis: + */ + __pyx_v_seen_ellipsis = 0; + + /* "View.MemoryView":635 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_3 = __pyx_int_0; + if (PyList_CheckExact(__pyx_v_tup) || PyTuple_CheckExact(__pyx_v_tup)) { + __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_7 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_7)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); + __pyx_t_7 = 0; + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); + __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_t_7; + __pyx_t_7 = 0; + + /* "View.MemoryView":636 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ + __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":637 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ + __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":638 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__46, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { + __Pyx_INCREF(__pyx_t_7); + PyList_SET_ITEM(__pyx_t_9, __pyx_temp, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + } + } + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_10 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_9); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "View.MemoryView":639 + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True # <<<<<<<<<<<<<< + * else: + * result.append(slice(None)) + */ + __pyx_v_seen_ellipsis = 1; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":641 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_t_9 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__47, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = __Pyx_PyList_Append(__pyx_v_result, __pyx_t_9); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + __pyx_L7:; + + /* "View.MemoryView":642 + * else: + * result.append(slice(None)) + * have_slices = True # <<<<<<<<<<<<<< + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + */ + __pyx_v_have_slices = 1; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":644 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ + __pyx_t_1 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_1 = ((!(__Pyx_PyIndex_Check(__pyx_v_item) != 0)) != 0); + __pyx_t_11 = __pyx_t_1; + } else { + __pyx_t_11 = __pyx_t_2; + } + if (__pyx_t_11) { + + /* "View.MemoryView":645 + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< + * + * have_slices = have_slices or isinstance(item, slice) + */ + __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_7, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":647 + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< + * result.append(item) + * + */ + if (!__pyx_v_have_slices) { + __pyx_t_11 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = __pyx_t_11; + } else { + __pyx_t_2 = __pyx_v_have_slices; + } + __pyx_v_have_slices = __pyx_t_2; + + /* "View.MemoryView":648 + * + * have_slices = have_slices or isinstance(item, slice) + * result.append(item) # <<<<<<<<<<<<<< + * + * nslices = ndim - len(result) + */ + __pyx_t_10 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":650 + * result.append(item) + * + * nslices = ndim - len(result) # <<<<<<<<<<<<<< + * if nslices: + * result.extend([slice(None)] * nslices) + */ + __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); + + /* "View.MemoryView":651 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + __pyx_t_2 = (__pyx_v_nslices != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":652 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__48, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { + __Pyx_INCREF(__pyx_t_3); + PyList_SET_ITEM(__pyx_t_4, __pyx_temp, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + } + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_10 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_4); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":654 + * result.extend([slice(None)] * nslices) + * + * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_2) { + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_9 = __pyx_t_3; + __pyx_t_3 = 0; + } else { + __pyx_t_9 = __pyx_t_4; + __pyx_t_4 = 0; + } + __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_9 = 0; + __pyx_t_4 = 0; + __pyx_r = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":622 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_tup); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_item); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":656 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + +static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); + + /* "View.MemoryView":658 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * cdef int i + * for i in range(ndim): # <<<<<<<<<<<<<< + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":659 + * cdef int i + * for i in range(ndim): + * if suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ + __pyx_t_3 = (((__pyx_v_suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":660 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__49, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + + /* "View.MemoryView":656 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":667 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { + int __pyx_v_new_ndim; + int __pyx_v_suboffset_dim; + int __pyx_v_dim; + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + __Pyx_memviewslice *__pyx_v_p_src; + struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; + __Pyx_memviewslice *__pyx_v_p_dst; + int *__pyx_v_p_suboffset_dim; + Py_ssize_t __pyx_v_start; + Py_ssize_t __pyx_v_stop; + Py_ssize_t __pyx_v_step; + int __pyx_v_have_start; + int __pyx_v_have_stop; + int __pyx_v_have_step; + PyObject *__pyx_v_index = NULL; + struct __pyx_memoryview_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + struct __pyx_memoryview_obj *__pyx_t_4; + char *__pyx_t_5; + int __pyx_t_6; + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + PyObject *__pyx_t_12 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memview_slice", 0); + + /* "View.MemoryView":668 + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): + * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< + * cdef bint negative_step + * cdef __Pyx_memviewslice src, dst + */ + __pyx_v_new_ndim = 0; + __pyx_v_suboffset_dim = -1; + + /* "View.MemoryView":675 + * + * + * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< + * + * cdef _memoryviewslice memviewsliceobj + */ + memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); + + /* "View.MemoryView":679 + * cdef _memoryviewslice memviewsliceobj + * + * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "View.MemoryView":681 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":682 + * + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview # <<<<<<<<<<<<<< + * p_src = &memviewsliceobj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 682; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":683 + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, &src) + */ + __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":685 + * p_src = &memviewsliceobj.from_slice + * else: + * slice_copy(memview, &src) # <<<<<<<<<<<<<< + * p_src = &src + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); + + /* "View.MemoryView":686 + * else: + * slice_copy(memview, &src) + * p_src = &src # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_src = (&__pyx_v_src); + } + __pyx_L3:; + + /* "View.MemoryView":692 + * + * + * dst.memview = p_src.memview # <<<<<<<<<<<<<< + * dst.data = p_src.data + * + */ + __pyx_t_4 = __pyx_v_p_src->memview; + __pyx_v_dst.memview = __pyx_t_4; + + /* "View.MemoryView":693 + * + * dst.memview = p_src.memview + * dst.data = p_src.data # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_v_p_src->data; + __pyx_v_dst.data = __pyx_t_5; + + /* "View.MemoryView":698 + * + * + * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< + * cdef int *p_suboffset_dim = &suboffset_dim + * cdef Py_ssize_t start, stop, step + */ + __pyx_v_p_dst = (&__pyx_v_dst); + + /* "View.MemoryView":699 + * + * cdef __Pyx_memviewslice *p_dst = &dst + * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< + * cdef Py_ssize_t start, stop, step + * cdef bint have_start, have_stop, have_step + */ + __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); + + /* "View.MemoryView":703 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + __pyx_t_6 = 0; + if (PyList_CheckExact(__pyx_v_indices) || PyTuple_CheckExact(__pyx_v_indices)) { + __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; + } + for (;;) { + if (!__pyx_t_8 && PyList_CheckExact(__pyx_t_3)) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_8 && PyTuple_CheckExact(__pyx_t_3)) { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_9 = __pyx_t_8(__pyx_t_3); + if (unlikely(!__pyx_t_9)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_9); + } + __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); + __pyx_t_9 = 0; + __pyx_v_dim = __pyx_t_6; + __pyx_t_6 = (__pyx_t_6 + 1); + + /* "View.MemoryView":704 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ + __pyx_t_2 = (__Pyx_PyIndex_Check(__pyx_v_index) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":708 + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< + * 0, 0, 0, # have_{start,stop,step} + * False) + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":705 + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 705; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + + /* "View.MemoryView":711 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ + __pyx_t_2 = (__pyx_v_index == Py_None); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":712 + * False) + * elif index is None: + * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + */ + (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; + + /* "View.MemoryView":713 + * elif index is None: + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 + */ + (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; + + /* "View.MemoryView":714 + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< + * new_ndim += 1 + * else: + */ + (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1; + + /* "View.MemoryView":715 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 # <<<<<<<<<<<<<< + * else: + * start = index.start or 0 + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":717 + * new_ndim += 1 + * else: + * start = index.start or 0 # <<<<<<<<<<<<<< + * stop = index.stop or 0 + * step = index.step or 0 + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_start = __pyx_t_10; + + /* "View.MemoryView":718 + * else: + * start = index.start or 0 + * stop = index.stop or 0 # <<<<<<<<<<<<<< + * step = index.step or 0 + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_12); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_9 = __pyx_int_0; + } else { + __pyx_t_9 = __pyx_t_12; + __pyx_t_12 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_stop = __pyx_t_10; + + /* "View.MemoryView":719 + * start = index.start or 0 + * stop = index.stop or 0 + * step = index.step or 0 # <<<<<<<<<<<<<< + * + * have_start = index.start is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_step = __pyx_t_10; + + /* "View.MemoryView":721 + * step = index.step or 0 + * + * have_start = index.start is not None # <<<<<<<<<<<<<< + * have_stop = index.stop is not None + * have_step = index.step is not None + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 721; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_start = __pyx_t_1; + + /* "View.MemoryView":722 + * + * have_start = index.start is not None + * have_stop = index.stop is not None # <<<<<<<<<<<<<< + * have_step = index.step is not None + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_stop = __pyx_t_1; + + /* "View.MemoryView":723 + * have_start = index.start is not None + * have_stop = index.stop is not None + * have_step = index.step is not None # <<<<<<<<<<<<<< + * + * slice_memviewslice( + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_step = __pyx_t_1; + + /* "View.MemoryView":725 + * have_step = index.step is not None + * + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":731 + * have_start, have_stop, have_step, + * True) + * new_ndim += 1 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":733 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":734 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":735 + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 735; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":736 + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * else: + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 736; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":734 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 734; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 734; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":739 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":740 + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":739 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":667 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":764 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { + Py_ssize_t __pyx_v_new_shape; + int __pyx_v_negative_step; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":784 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":786 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + __pyx_t_1 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":787 + * + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":788 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + __pyx_t_1 = (0 <= __pyx_v_start); + if (__pyx_t_1) { + __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); + } + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":789 + * start += shape + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< + * else: + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_Index_out_of_bounds_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 789; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":792 + * else: + * + * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< + * + * if have_step and step == 0: + */ + __pyx_t_2 = (__pyx_v_have_step != 0); + if (__pyx_t_2) { + __pyx_t_1 = (__pyx_v_step < 0); + __pyx_t_4 = __pyx_t_1; + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_v_negative_step = __pyx_t_4; + + /* "View.MemoryView":794 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + if ((__pyx_v_have_step != 0)) { + __pyx_t_4 = (__pyx_v_step == 0); + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = (__pyx_v_have_step != 0); + } + if (__pyx_t_2) { + + /* "View.MemoryView":795 + * + * if have_step and step == 0: + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Step_may_not_be_zero_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":798 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + __pyx_t_2 = (__pyx_v_have_start != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":799 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":800 + * if have_start: + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if start < 0: + * start = 0 + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":801 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":802 + * start += shape + * if start < 0: + * start = 0 # <<<<<<<<<<<<<< + * elif start >= shape: + * if negative_step: + */ + __pyx_v_start = 0; + goto __pyx_L9; + } + __pyx_L9:; + goto __pyx_L8; + } + + /* "View.MemoryView":803 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":804 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":805 + * elif start >= shape: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = shape + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L10; + } + /*else*/ { + + /* "View.MemoryView":807 + * start = shape - 1 + * else: + * start = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_start = __pyx_v_shape; + } + __pyx_L10:; + goto __pyx_L8; + } + __pyx_L8:; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":809 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":810 + * else: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = 0 + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":812 + * start = shape - 1 + * else: + * start = 0 # <<<<<<<<<<<<<< + * + * if have_stop: + */ + __pyx_v_start = 0; + } + __pyx_L11:; + } + __pyx_L7:; + + /* "View.MemoryView":814 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + __pyx_t_2 = (__pyx_v_have_stop != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":815 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":816 + * if have_stop: + * if stop < 0: + * stop += shape # <<<<<<<<<<<<<< + * if stop < 0: + * stop = 0 + */ + __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); + + /* "View.MemoryView":817 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":818 + * stop += shape + * if stop < 0: + * stop = 0 # <<<<<<<<<<<<<< + * elif stop > shape: + * stop = shape + */ + __pyx_v_stop = 0; + goto __pyx_L14; + } + __pyx_L14:; + goto __pyx_L13; + } + + /* "View.MemoryView":819 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":820 + * stop = 0 + * elif stop > shape: + * stop = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_stop = __pyx_v_shape; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L12; + } + /*else*/ { + + /* "View.MemoryView":822 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":823 + * else: + * if negative_step: + * stop = -1 # <<<<<<<<<<<<<< + * else: + * stop = shape + */ + __pyx_v_stop = -1; + goto __pyx_L15; + } + /*else*/ { + + /* "View.MemoryView":825 + * stop = -1 + * else: + * stop = shape # <<<<<<<<<<<<<< + * + * if not have_step: + */ + __pyx_v_stop = __pyx_v_shape; + } + __pyx_L15:; + } + __pyx_L12:; + + /* "View.MemoryView":827 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":828 + * + * if not have_step: + * step = 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_step = 1; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":832 + * + * with cython.cdivision(True): + * new_shape = (stop - start) // step # <<<<<<<<<<<<<< + * + * if (stop - start) - step * new_shape: + */ + __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); + + /* "View.MemoryView":834 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":835 + * + * if (stop - start) - step * new_shape: + * new_shape += 1 # <<<<<<<<<<<<<< + * + * if new_shape < 0: + */ + __pyx_v_new_shape = (__pyx_v_new_shape + 1); + goto __pyx_L17; + } + __pyx_L17:; + + /* "View.MemoryView":837 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":838 + * + * if new_shape < 0: + * new_shape = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_new_shape = 0; + goto __pyx_L18; + } + __pyx_L18:; + + /* "View.MemoryView":841 + * + * + * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset + */ + (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); + + /* "View.MemoryView":842 + * + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< + * dst.suboffsets[new_ndim] = suboffset + * + */ + (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; + + /* "View.MemoryView":843 + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; + } + __pyx_L3:; + + /* "View.MemoryView":846 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":847 + * + * if suboffset_dim[0] < 0: + * dst.data += start * stride # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride + */ + __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); + goto __pyx_L19; + } + /*else*/ { + + /* "View.MemoryView":849 + * dst.data += start * stride + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< + * + * if suboffset >= 0: + */ + __pyx_t_3 = (__pyx_v_suboffset_dim[0]); + (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); + } + __pyx_L19:; + + /* "View.MemoryView":851 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":852 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":853 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":854 + * if not is_slice: + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + */ + __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); + goto __pyx_L22; + } + /*else*/ { + + /* "View.MemoryView":856 + * dst.data = ( dst.data)[0] + suboffset + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< + * "must be indexed and not sliced", dim) + * else: + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_All_dimensions_preceding_dimensi, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 856; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L22:; + goto __pyx_L21; + } + /*else*/ { + + /* "View.MemoryView":859 + * "must be indexed and not sliced", dim) + * else: + * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< + * + * return 0 + */ + (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; + } + __pyx_L21:; + goto __pyx_L20; + } + __pyx_L20:; + + /* "View.MemoryView":861 + * suboffset_dim[0] = new_ndim + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":764 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":867 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + +static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { + Py_ssize_t __pyx_v_shape; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_suboffset; + Py_ssize_t __pyx_v_itemsize; + char *__pyx_v_resultp; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pybuffer_index", 0); + + /* "View.MemoryView":869 + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< + * cdef Py_ssize_t itemsize = view.itemsize + * cdef char *resultp + */ + __pyx_v_suboffset = -1; + + /* "View.MemoryView":870 + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< + * cdef char *resultp + * + */ + __pyx_t_1 = __pyx_v_view->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":873 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":874 + * + * if view.ndim == 0: + * shape = view.len / itemsize # <<<<<<<<<<<<<< + * stride = itemsize + * else: + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 874; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 874; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_shape = (__pyx_v_view->len / __pyx_v_itemsize); + + /* "View.MemoryView":875 + * if view.ndim == 0: + * shape = view.len / itemsize + * stride = itemsize # <<<<<<<<<<<<<< + * else: + * shape = view.shape[dim] + */ + __pyx_v_stride = __pyx_v_itemsize; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":877 + * stride = itemsize + * else: + * shape = view.shape[dim] # <<<<<<<<<<<<<< + * stride = view.strides[dim] + * if view.suboffsets != NULL: + */ + __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); + + /* "View.MemoryView":878 + * else: + * shape = view.shape[dim] + * stride = view.strides[dim] # <<<<<<<<<<<<<< + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] + */ + __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); + + /* "View.MemoryView":879 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":880 + * stride = view.strides[dim] + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< + * + * if index < 0: + */ + __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); + goto __pyx_L4; + } + __pyx_L4:; + } + __pyx_L3:; + + /* "View.MemoryView":882 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":883 + * + * if index < 0: + * index += view.shape[dim] # <<<<<<<<<<<<<< + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + */ + __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); + + /* "View.MemoryView":884 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":885 + * index += view.shape[dim] + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * if index >= shape: + */ + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":887 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":888 + * + * if index >= shape: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * resultp = bufp + index * stride + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":890 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * resultp = bufp + index * stride # <<<<<<<<<<<<<< + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset + */ + __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); + + /* "View.MemoryView":891 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":892 + * resultp = bufp + index * stride + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< + * + * return resultp + */ + __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":894 + * resultp = ( resultp)[0] + suboffset + * + * return resultp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_resultp; + goto __pyx_L0; + + /* "View.MemoryView":867 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":900 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + +static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { + int __pyx_v_ndim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + int __pyx_v_i; + int __pyx_v_j; + int __pyx_r; + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + long __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":901 + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: + * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< + * + * cdef Py_ssize_t *shape = memslice.shape + */ + __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; + __pyx_v_ndim = __pyx_t_1; + + /* "View.MemoryView":903 + * cdef int ndim = memslice.memview.view.ndim + * + * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< + * cdef Py_ssize_t *strides = memslice.strides + * + */ + __pyx_t_2 = __pyx_v_memslice->shape; + __pyx_v_shape = __pyx_t_2; + + /* "View.MemoryView":904 + * + * cdef Py_ssize_t *shape = memslice.shape + * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_v_memslice->strides; + __pyx_v_strides = __pyx_t_2; + + /* "View.MemoryView":908 + * + * cdef int i, j + * for i in range(ndim / 2): # <<<<<<<<<<<<<< + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + */ + __pyx_t_3 = (__pyx_v_ndim / 2); + for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":909 + * cdef int i, j + * for i in range(ndim / 2): + * j = ndim - 1 - i # <<<<<<<<<<<<<< + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] + */ + __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); + + /* "View.MemoryView":910 + * for i in range(ndim / 2): + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< + * shape[i], shape[j] = shape[j], shape[i] + * + */ + __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); + __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); + (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; + (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; + + /* "View.MemoryView":911 + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + */ + __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); + __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); + (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; + (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; + + /* "View.MemoryView":913 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + __pyx_t_6 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); + if (!__pyx_t_6) { + __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); + __pyx_t_8 = __pyx_t_7; + } else { + __pyx_t_8 = __pyx_t_6; + } + if (__pyx_t_8) { + + /* "View.MemoryView":914 + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< + * + * return 1 + */ + __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_Cannot_transpose_memoryview_with); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 914; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "View.MemoryView":916 + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + * return 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 1; + goto __pyx_L0; + + /* "View.MemoryView":900 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":933 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + +/* Python wrapper */ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":934 + * + * def __dealloc__(self): + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); + + /* "View.MemoryView":933 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":936 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":937 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":938 + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) # <<<<<<<<<<<<<< + * else: + * return memoryview.convert_item_to_object(self, itemp) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 938; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":940 + * return self.to_object_func(itemp) + * else: + * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_vtabptr_memoryview->convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 940; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":936 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":942 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":943 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":944 + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< + * else: + * memoryview.assign_item_from_object(self, itemp, value) + */ + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":946 + * self.to_dtype_func(itemp, value) + * else: + * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< + * + * property base: + */ + __pyx_t_3 = __pyx_vtabptr_memoryview->assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":942 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":950 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":951 + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): + * return self.from_object # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->from_object); + __pyx_r = __pyx_v_self->from_object; + goto __pyx_L0; + + /* "View.MemoryView":950 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":957 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_TypeInfo *__pyx_t_4; + Py_buffer __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_fromslice", 0); + + /* "View.MemoryView":966 + * cdef int i + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":967 + * + * if memviewslice.memview == Py_None: + * return None # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + + /* "View.MemoryView":972 + * + * + * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< + * + * result.from_slice = memviewslice + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":974 + * result = _memoryviewslice(None, 0, dtype_is_object) + * + * result.from_slice = memviewslice # <<<<<<<<<<<<<< + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + */ + __pyx_v_result->from_slice = __pyx_v_memviewslice; + + /* "View.MemoryView":975 + * + * result.from_slice = memviewslice + * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< + * + * result.from_object = ( memviewslice.memview).base + */ + __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); + + /* "View.MemoryView":977 + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< + * result.typeinfo = memviewslice.memview.typeinfo + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_result->from_object); + __Pyx_DECREF(__pyx_v_result->from_object); + __pyx_v_result->from_object = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":978 + * + * result.from_object = ( memviewslice.memview).base + * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< + * + * result.view = memviewslice.memview.view + */ + __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; + __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; + + /* "View.MemoryView":980 + * result.typeinfo = memviewslice.memview.typeinfo + * + * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + */ + __pyx_t_5 = __pyx_v_memviewslice.memview->view; + __pyx_v_result->__pyx_base.view = __pyx_t_5; + + /* "View.MemoryView":981 + * + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + */ + __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); + + /* "View.MemoryView":982 + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data + * result.view.ndim = ndim # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; + + /* "View.MemoryView":983 + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; + + /* "View.MemoryView":984 + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * result.flags = PyBUF_RECORDS + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":986 + * Py_INCREF(Py_None) + * + * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< + * + * result.view.shape = result.from_slice.shape + */ + __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; + + /* "View.MemoryView":988 + * result.flags = PyBUF_RECORDS + * + * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets + */ + __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); + + /* "View.MemoryView":989 + * + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * + */ + __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); + + /* "View.MemoryView":990 + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + * + * result.view.len = result.view.itemsize + */ + __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + + /* "View.MemoryView":992 + * result.view.suboffsets = result.from_slice.suboffsets + * + * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< + * for i in range(ndim): + * result.view.len *= result.view.shape[i] + */ + __pyx_t_6 = __pyx_v_result->__pyx_base.view.itemsize; + __pyx_v_result->__pyx_base.view.len = __pyx_t_6; + + /* "View.MemoryView":993 + * + * result.view.len = result.view.itemsize + * for i in range(ndim): # <<<<<<<<<<<<<< + * result.view.len *= result.view.shape[i] + * + */ + __pyx_t_7 = __pyx_v_ndim; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "View.MemoryView":994 + * result.view.len = result.view.itemsize + * for i in range(ndim): + * result.view.len *= result.view.shape[i] # <<<<<<<<<<<<<< + * + * result.to_object_func = to_object_func + */ + __pyx_v_result->__pyx_base.view.len = (__pyx_v_result->__pyx_base.view.len * (__pyx_v_result->__pyx_base.view.shape[__pyx_v_i])); + } + + /* "View.MemoryView":996 + * result.view.len *= result.view.shape[i] + * + * result.to_object_func = to_object_func # <<<<<<<<<<<<<< + * result.to_dtype_func = to_dtype_func + * + */ + __pyx_v_result->to_object_func = __pyx_v_to_object_func; + + /* "View.MemoryView":997 + * + * result.to_object_func = to_object_func + * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; + + /* "View.MemoryView":999 + * result.to_dtype_func = to_dtype_func + * + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":957 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1002 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { + struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; + __Pyx_memviewslice *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_slice_from_memview", 0); + + /* "View.MemoryView":1005 + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1006 + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): + * obj = memview # <<<<<<<<<<<<<< + * return &obj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":1007 + * if isinstance(memview, _memoryviewslice): + * obj = memview + * return &obj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, mslice) + */ + __pyx_r = (&__pyx_v_obj->from_slice); + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1009 + * return &obj.from_slice + * else: + * slice_copy(memview, mslice) # <<<<<<<<<<<<<< + * return mslice + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); + + /* "View.MemoryView":1010 + * else: + * slice_copy(memview, mslice) + * return mslice # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_copy') + */ + __pyx_r = __pyx_v_mslice; + goto __pyx_L0; + } + + /* "View.MemoryView":1002 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_obj); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1013 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { + int __pyx_v_dim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + Py_ssize_t *__pyx_v_suboffsets; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + __Pyx_RefNannySetupContext("slice_copy", 0); + + /* "View.MemoryView":1017 + * cdef (Py_ssize_t*) shape, strides, suboffsets + * + * shape = memview.view.shape # <<<<<<<<<<<<<< + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets + */ + __pyx_t_1 = __pyx_v_memview->view.shape; + __pyx_v_shape = __pyx_t_1; + + /* "View.MemoryView":1018 + * + * shape = memview.view.shape + * strides = memview.view.strides # <<<<<<<<<<<<<< + * suboffsets = memview.view.suboffsets + * + */ + __pyx_t_1 = __pyx_v_memview->view.strides; + __pyx_v_strides = __pyx_t_1; + + /* "View.MemoryView":1019 + * shape = memview.view.shape + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< + * + * dst.memview = <__pyx_memoryview *> memview + */ + __pyx_t_1 = __pyx_v_memview->view.suboffsets; + __pyx_v_suboffsets = __pyx_t_1; + + /* "View.MemoryView":1021 + * suboffsets = memview.view.suboffsets + * + * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< + * dst.data = memview.view.buf + * + */ + __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); + + /* "View.MemoryView":1022 + * + * dst.memview = <__pyx_memoryview *> memview + * dst.data = memview.view.buf # <<<<<<<<<<<<<< + * + * for dim in range(memview.view.ndim): + */ + __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); + + /* "View.MemoryView":1024 + * dst.data = memview.view.buf + * + * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + */ + __pyx_t_2 = __pyx_v_memview->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_dim = __pyx_t_3; + + /* "View.MemoryView":1025 + * + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + */ + (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); + + /* "View.MemoryView":1026 + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 + */ + (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); + + /* "View.MemoryView":1027 + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: # <<<<<<<<<<<<<< + * dst.suboffsets[dim] = -1 + * else: + */ + __pyx_t_4 = ((__pyx_v_suboffsets == NULL) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":1028 + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[dim] = suboffsets[dim] + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = -1; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1030 + * dst.suboffsets[dim] = -1 + * else: + * dst.suboffsets[dim] = suboffsets[dim] # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object') + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = (__pyx_v_suboffsets[__pyx_v_dim]); + } + __pyx_L5:; + } + + /* "View.MemoryView":1013 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1033 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { + __Pyx_memviewslice __pyx_v_memviewslice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy", 0); + + /* "View.MemoryView":1036 + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< + * return memoryview_copy_from_slice(memview, &memviewslice) + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); + + /* "View.MemoryView":1037 + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) + * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object_from_slice') + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1033 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1040 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { + PyObject *(*__pyx_v_to_object_func)(char *); + int (*__pyx_v_to_dtype_func)(char *, PyObject *); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *(*__pyx_t_3)(char *); + int (*__pyx_t_4)(char *, PyObject *); + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); + + /* "View.MemoryView":1047 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1048 + * + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + */ + __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; + __pyx_v_to_object_func = __pyx_t_3; + + /* "View.MemoryView":1049 + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< + * else: + * to_object_func = NULL + */ + __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; + __pyx_v_to_dtype_func = __pyx_t_4; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1051 + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + * to_object_func = NULL # <<<<<<<<<<<<<< + * to_dtype_func = NULL + * + */ + __pyx_v_to_object_func = NULL; + + /* "View.MemoryView":1052 + * else: + * to_object_func = NULL + * to_dtype_func = NULL # <<<<<<<<<<<<<< + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + */ + __pyx_v_to_dtype_func = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":1054 + * to_dtype_func = NULL + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< + * to_object_func, to_dtype_func, + * memview.dtype_is_object) + */ + __Pyx_XDECREF(__pyx_r); + + /* "View.MemoryView":1056 + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + * to_object_func, to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1040 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1062 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + +static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { + Py_ssize_t __pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":1063 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + __pyx_t_1 = ((__pyx_v_arg < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1064 + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: + * return -arg # <<<<<<<<<<<<<< + * else: + * return arg + */ + __pyx_r = (-__pyx_v_arg); + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1066 + * return -arg + * else: + * return arg # <<<<<<<<<<<<<< + * + * @cname('__pyx_get_best_slice_order') + */ + __pyx_r = __pyx_v_arg; + goto __pyx_L0; + } + + /* "View.MemoryView":1062 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1069 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + +static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_c_stride; + Py_ssize_t __pyx_v_f_stride; + char __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1074 + * """ + * cdef int i + * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t f_stride = 0 + * + */ + __pyx_v_c_stride = 0; + + /* "View.MemoryView":1075 + * cdef int i + * cdef Py_ssize_t c_stride = 0 + * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_f_stride = 0; + + /* "View.MemoryView":1077 + * cdef Py_ssize_t f_stride = 0 + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1078 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1079 + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1080 + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + goto __pyx_L4_break; + } + } + __pyx_L4_break:; + + /* "View.MemoryView":1082 + * break + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1083 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1084 + * for i in range(ndim): + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1085 + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + */ + goto __pyx_L7_break; + } + } + __pyx_L7_break:; + + /* "View.MemoryView":1087 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1088 + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + * return 'C' # <<<<<<<<<<<<<< + * else: + * return 'F' + */ + __pyx_r = 'C'; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1090 + * return 'C' + * else: + * return 'F' # <<<<<<<<<<<<<< + * + * @cython.cdivision(True) + */ + __pyx_r = 'F'; + goto __pyx_L0; + } + + /* "View.MemoryView":1069 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1093 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + +static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; + Py_ssize_t __pyx_v_dst_extent; + Py_ssize_t __pyx_v_src_stride; + Py_ssize_t __pyx_v_dst_stride; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + + /* "View.MemoryView":1100 + * + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + */ + __pyx_v_src_extent = (__pyx_v_src_shape[0]); + + /* "View.MemoryView":1101 + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] + */ + __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); + + /* "View.MemoryView":1102 + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + */ + __pyx_v_src_stride = (__pyx_v_src_strides[0]); + + /* "View.MemoryView":1103 + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); + + /* "View.MemoryView":1105 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1106 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + __pyx_t_1 = ((__pyx_v_src_stride > 0) != 0); + if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1107 + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + */ + __pyx_t_3 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); + if (__pyx_t_3) { + __pyx_t_3 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); + } + __pyx_t_4 = (__pyx_t_3 != 0); + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = __pyx_t_1; + } + if (__pyx_t_2) { + + /* "View.MemoryView":1108 + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":1110 + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1111 + * else: + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); + + /* "View.MemoryView":1112 + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * else: + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1113 + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1115 + * dst_data += dst_stride + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * _copy_strided_to_strided(src_data, src_strides + 1, + * dst_data, dst_strides + 1, + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1116 + * else: + * for i in range(dst_extent): + * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< + * dst_data, dst_strides + 1, + * src_shape + 1, dst_shape + 1, + */ + _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); + + /* "View.MemoryView":1120 + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1121 + * ndim - 1, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1093 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + + /* function exit code */ +} + +/* "View.MemoryView":1123 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + +static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + + /* "View.MemoryView":1126 + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< + * src.shape, dst.shape, ndim, itemsize) + * + */ + _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1123 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1130 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_size; + Py_ssize_t __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1133 + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_size = __pyx_t_1; + + /* "View.MemoryView":1135 + * cdef Py_ssize_t size = src.memview.view.itemsize + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * size *= src.shape[i] + * + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1136 + * + * for i in range(ndim): + * size *= src.shape[i] # <<<<<<<<<<<<<< + * + * return size + */ + __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); + } + + /* "View.MemoryView":1138 + * size *= src.shape[i] + * + * return size # <<<<<<<<<<<<<< + * + * @cname('__pyx_fill_contig_strides_array') + */ + __pyx_r = __pyx_v_size; + goto __pyx_L0; + + /* "View.MemoryView":1130 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1141 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { + int __pyx_v_idx; + Py_ssize_t __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1150 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + __pyx_t_1 = ((__pyx_v_order == 'F') != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1151 + * + * if order == 'F': + * for idx in range(ndim): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_idx = __pyx_t_3; + + /* "View.MemoryView":1152 + * if order == 'F': + * for idx in range(ndim): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * else: + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1153 + * for idx in range(ndim): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * else: + * for idx in range(ndim - 1, -1, -1): + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1155 + * stride = stride * shape[idx] + * else: + * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { + __pyx_v_idx = __pyx_t_2; + + /* "View.MemoryView":1156 + * else: + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1157 + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * + * return stride + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + } + __pyx_L3:; + + /* "View.MemoryView":1159 + * stride = stride * shape[idx] + * + * return stride # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_data_to_temp') + */ + __pyx_r = __pyx_v_stride; + goto __pyx_L0; + + /* "View.MemoryView":1141 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1162 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { + int __pyx_v_i; + void *__pyx_v_result; + size_t __pyx_v_itemsize; + size_t __pyx_v_size; + void *__pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + struct __pyx_memoryview_obj *__pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1173 + * cdef void *result + * + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef size_t size = slice_get_size(src, ndim) + * + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1174 + * + * cdef size_t itemsize = src.memview.view.itemsize + * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< + * + * result = malloc(size) + */ + __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); + + /* "View.MemoryView":1176 + * cdef size_t size = slice_get_size(src, ndim) + * + * result = malloc(size) # <<<<<<<<<<<<<< + * if not result: + * _err(MemoryError, NULL) + */ + __pyx_v_result = malloc(__pyx_v_size); + + /* "View.MemoryView":1177 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1178 + * result = malloc(size) + * if not result: + * _err(MemoryError, NULL) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1181 + * + * + * tmpslice.data = result # <<<<<<<<<<<<<< + * tmpslice.memview = src.memview + * for i in range(ndim): + */ + __pyx_v_tmpslice->data = ((char *)__pyx_v_result); + + /* "View.MemoryView":1182 + * + * tmpslice.data = result + * tmpslice.memview = src.memview # <<<<<<<<<<<<<< + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + */ + __pyx_t_4 = __pyx_v_src->memview; + __pyx_v_tmpslice->memview = __pyx_t_4; + + /* "View.MemoryView":1183 + * tmpslice.data = result + * tmpslice.memview = src.memview + * for i in range(ndim): # <<<<<<<<<<<<<< + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1184 + * tmpslice.memview = src.memview + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< + * tmpslice.suboffsets[i] = -1 + * + */ + (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); + + /* "View.MemoryView":1185 + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + */ + (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1187 + * tmpslice.suboffsets[i] = -1 + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< + * ndim, order) + * + */ + __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); + + /* "View.MemoryView":1191 + * + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1192 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1193 + * for i in range(ndim): + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< + * + * if slice_is_contig(src, order, ndim): + */ + (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1195 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1196 + * + * if slice_is_contig(src, order, ndim): + * memcpy(result, src.data, size) # <<<<<<<<<<<<<< + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + */ + memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1198 + * memcpy(result, src.data, size) + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< + * + * return result + */ + copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); + } + __pyx_L9:; + + /* "View.MemoryView":1200 + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":1162 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = NULL; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1205 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + +static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_extents", 0); + + /* "View.MemoryView":1208 + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + * (i, extent1, extent2)) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err_dim') + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + + /* "View.MemoryView":1207 + * cdef int _err_extents(int i, Py_ssize_t extent1, + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< + * (i, extent1, extent2)) + * + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1205 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1211 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + +static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_dim", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1212 + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: + * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err') + */ + __pyx_t_1 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyUnicode_Format(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_v_error, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1211 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1215 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + +static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1216 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ + __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1217 + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: + * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< + * else: + * raise error + */ + __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_v_error, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + /*else*/ { + + /* "View.MemoryView":1219 + * raise error(msg.decode('ascii')) + * else: + * raise error # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_contents') + */ + __Pyx_Raise(__pyx_v_error, 0, 0, 0); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":1215 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1222 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { + void *__pyx_v_tmpdata; + size_t __pyx_v_itemsize; + int __pyx_v_i; + char __pyx_v_order; + int __pyx_v_broadcasting; + int __pyx_v_direct_copy; + __Pyx_memviewslice __pyx_v_tmp; + int __pyx_v_ndim; + int __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + void *__pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1230 + * Check for overlapping memory and verify the shapes. + * """ + * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + */ + __pyx_v_tmpdata = NULL; + + /* "View.MemoryView":1231 + * """ + * cdef void *tmpdata = NULL + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + */ + __pyx_t_1 = __pyx_v_src.memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1233 + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< + * cdef bint broadcasting = False + * cdef bint direct_copy = False + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); + + /* "View.MemoryView":1234 + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False # <<<<<<<<<<<<<< + * cdef bint direct_copy = False + * cdef __Pyx_memviewslice tmp + */ + __pyx_v_broadcasting = 0; + + /* "View.MemoryView":1235 + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False + * cdef bint direct_copy = False # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice tmp + * + */ + __pyx_v_direct_copy = 0; + + /* "View.MemoryView":1238 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ + __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1239 + * + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); + goto __pyx_L3; + } + + /* "View.MemoryView":1240 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ + __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1241 + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< + * + * cdef int ndim = max(src_ndim, dst_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1243 + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_3 = __pyx_v_dst_ndim; + __pyx_t_4 = __pyx_v_src_ndim; + if (((__pyx_t_3 > __pyx_t_4) != 0)) { + __pyx_t_5 = __pyx_t_3; + } else { + __pyx_t_5 = __pyx_t_4; + } + __pyx_v_ndim = __pyx_t_5; + + /* "View.MemoryView":1245 + * cdef int ndim = max(src_ndim, dst_ndim) + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1246 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1247 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1248 + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + * broadcasting = True # <<<<<<<<<<<<<< + * src.strides[i] = 0 + * else: + */ + __pyx_v_broadcasting = 1; + + /* "View.MemoryView":1249 + * if src.shape[i] == 1: + * broadcasting = True + * src.strides[i] = 0 # <<<<<<<<<<<<<< + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) + */ + (__pyx_v_src.strides[__pyx_v_i]) = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":1251 + * src.strides[i] = 0 + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< + * + * if src.suboffsets[i] >= 0: + */ + __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":1253 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ + __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1254 + * + * if src.suboffsets[i] >= 0: + * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< + * + * if slices_overlap(&src, &dst, ndim, itemsize): + */ + __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Dimension_d_is_not_direct, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1256 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(&src, order, ndim): + */ + __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1258 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1259 + * + * if not slice_is_contig(&src, order, ndim): + * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":1261 + * order = get_best_order(&dst, ndim) + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< + * src = tmp + * + */ + __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_tmpdata = __pyx_t_6; + + /* "View.MemoryView":1262 + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + * src = tmp # <<<<<<<<<<<<<< + * + * if not broadcasting: + */ + __pyx_v_src = __pyx_v_tmp; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":1264 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1267 + * + * + * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1268 + * + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); + goto __pyx_L12; + } + + /* "View.MemoryView":1269 + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1270 + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< + * + * if direct_copy: + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":1272 + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_2 = (__pyx_v_direct_copy != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1274 + * if direct_copy: + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1275 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) + */ + memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); + + /* "View.MemoryView":1276 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * free(tmpdata) + * return 0 + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1277 + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1278 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * if order == 'F' == get_best_order(&dst, ndim): + */ + __pyx_r = 0; + goto __pyx_L0; + } + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":1280 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = (__pyx_v_order == 'F'); + if (__pyx_t_2) { + __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); + } + __pyx_t_7 = (__pyx_t_2 != 0); + if (__pyx_t_7) { + + /* "View.MemoryView":1283 + * + * + * transpose_memslice(&src) # <<<<<<<<<<<<<< + * transpose_memslice(&dst) + * + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1284 + * + * transpose_memslice(&src) + * transpose_memslice(&dst) # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":1286 + * transpose_memslice(&dst) + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1287 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + */ + copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1288 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * free(tmpdata) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1290 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1291 + * + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_broadcast_leading') + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":1222 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1294 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice, int __pyx_v_ndim, int __pyx_v_ndim_other) { + int __pyx_v_i; + int __pyx_v_offset; + int __pyx_t_1; + int __pyx_t_2; + + /* "View.MemoryView":1298 + * int ndim_other) nogil: + * cdef int i + * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); + + /* "View.MemoryView":1300 + * cdef int offset = ndim_other - ndim + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1301 + * + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] # <<<<<<<<<<<<<< + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] + */ + (__pyx_v_slice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->shape[__pyx_v_i]); + + /* "View.MemoryView":1302 + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] # <<<<<<<<<<<<<< + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + */ + (__pyx_v_slice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->strides[__pyx_v_i]); + + /* "View.MemoryView":1303 + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] # <<<<<<<<<<<<<< + * + * for i in range(offset): + */ + (__pyx_v_slice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->suboffsets[__pyx_v_i]); + } + + /* "View.MemoryView":1305 + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + * for i in range(offset): # <<<<<<<<<<<<<< + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + */ + __pyx_t_1 = __pyx_v_offset; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1306 + * + * for i in range(offset): + * slice.shape[i] = 1 # <<<<<<<<<<<<<< + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 + */ + (__pyx_v_slice->shape[__pyx_v_i]) = 1; + + /* "View.MemoryView":1307 + * for i in range(offset): + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] # <<<<<<<<<<<<<< + * slice.suboffsets[i] = -1 + * + */ + (__pyx_v_slice->strides[__pyx_v_i]) = (__pyx_v_slice->strides[0]); + + /* "View.MemoryView":1308 + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_slice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1294 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1316 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { + int __pyx_t_1; + + /* "View.MemoryView":1320 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + __pyx_t_1 = (__pyx_v_dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1321 + * + * if dtype_is_object: + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< + * dst.strides, ndim, inc) + * + */ + __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1316 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + + /* function exit code */ +} + +/* "View.MemoryView":1325 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + __Pyx_RefNannyDeclarations + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); + + /* "View.MemoryView":1328 + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); + + /* "View.MemoryView":1325 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif +} + +/* "View.MemoryView":1331 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + +static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); + + /* "View.MemoryView":1335 + * cdef Py_ssize_t i + * + * for i in range(shape[0]): # <<<<<<<<<<<<<< + * if ndim == 1: + * if inc: + */ + __pyx_t_1 = (__pyx_v_shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1336 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1337 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + __pyx_t_3 = (__pyx_v_inc != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1338 + * if ndim == 1: + * if inc: + * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * Py_DECREF(( data)[0]) + */ + Py_INCREF((((PyObject **)__pyx_v_data)[0])); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":1340 + * Py_INCREF(( data)[0]) + * else: + * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + */ + Py_DECREF((((PyObject **)__pyx_v_data)[0])); + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1342 + * Py_DECREF(( data)[0]) + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, inc) + * + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); + } + __pyx_L5:; + + /* "View.MemoryView":1345 + * ndim - 1, inc) + * + * data += strides[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); + } + + /* "View.MemoryView":1331 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1351 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { + + /* "View.MemoryView":1354 + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1355 + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1357 + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1351 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1361 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + +static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_extent; + int __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + + /* "View.MemoryView":1365 + * size_t itemsize, void *item) nogil: + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t extent = shape[0] + * + */ + __pyx_v_stride = (__pyx_v_strides[0]); + + /* "View.MemoryView":1366 + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] + * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_extent = (__pyx_v_shape[0]); + + /* "View.MemoryView":1368 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1369 + * + * if ndim == 1: + * for i in range(extent): # <<<<<<<<<<<<<< + * memcpy(data, item, itemsize) + * data += stride + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1370 + * if ndim == 1: + * for i in range(extent): + * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< + * data += stride + * else: + */ + memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); + + /* "View.MemoryView":1371 + * for i in range(extent): + * memcpy(data, item, itemsize) + * data += stride # <<<<<<<<<<<<<< + * else: + * for i in range(extent): + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1373 + * data += stride + * else: + * for i in range(extent): # <<<<<<<<<<<<<< + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1374 + * else: + * for i in range(extent): + * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, itemsize, item) + * data += stride + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1376 + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + * data += stride # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1361 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + + /* function exit code */ +} + +/* "BufferFormatFromTypeInfo":1417 + * + * @cname('__pyx_format_from_typeinfo') + * cdef bytes format_from_typeinfo(__Pyx_TypeInfo *type): # <<<<<<<<<<<<<< + * cdef __Pyx_StructField *field + * cdef __pyx_typeinfo_string fmt + */ + +static PyObject *__pyx_format_from_typeinfo(__Pyx_TypeInfo *__pyx_v_type) { + __Pyx_StructField *__pyx_v_field; + struct __pyx_typeinfo_string __pyx_v_fmt; + PyObject *__pyx_v_part = 0; + PyObject *__pyx_v_result = 0; + PyObject *__pyx_v_alignment = NULL; + PyObject *__pyx_v_parts = NULL; + PyObject *__pyx_v_extents = NULL; + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + __Pyx_StructField *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("format_from_typeinfo", 0); + + /* "BufferFormatFromTypeInfo":1422 + * cdef bytes part, result + * + * if type.typegroup == 'S': # <<<<<<<<<<<<<< + * assert type.fields != NULL and type.fields.type != NULL + * + */ + __pyx_t_1 = ((__pyx_v_type->typegroup == 'S') != 0); + if (__pyx_t_1) { + + /* "BufferFormatFromTypeInfo":1423 + * + * if type.typegroup == 'S': + * assert type.fields != NULL and type.fields.type != NULL # <<<<<<<<<<<<<< + * + * if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT: + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + __pyx_t_1 = ((__pyx_v_type->fields != NULL) != 0); + if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_type->fields->type != NULL) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (unlikely(!__pyx_t_3)) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "BufferFormatFromTypeInfo":1425 + * assert type.fields != NULL and type.fields.type != NULL + * + * if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT: # <<<<<<<<<<<<<< + * alignment = b'^' + * else: + */ + __pyx_t_3 = ((__pyx_v_type->flags & __PYX_BUF_FLAGS_PACKED_STRUCT) != 0); + if (__pyx_t_3) { + + /* "BufferFormatFromTypeInfo":1426 + * + * if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT: + * alignment = b'^' # <<<<<<<<<<<<<< + * else: + * alignment = b'' + */ + __Pyx_INCREF(__pyx_kp_b__50); + __pyx_v_alignment = __pyx_kp_b__50; + goto __pyx_L4; + } + /*else*/ { + + /* "BufferFormatFromTypeInfo":1428 + * alignment = b'^' + * else: + * alignment = b'' # <<<<<<<<<<<<<< + * + * parts = [b"T{"] + */ + __Pyx_INCREF(__pyx_kp_b__51); + __pyx_v_alignment = __pyx_kp_b__51; + } + __pyx_L4:; + + /* "BufferFormatFromTypeInfo":1430 + * alignment = b'' + * + * parts = [b"T{"] # <<<<<<<<<<<<<< + * field = type.fields + * + */ + __pyx_t_4 = PyList_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_kp_b_T); + PyList_SET_ITEM(__pyx_t_4, 0, __pyx_kp_b_T); + __Pyx_GIVEREF(__pyx_kp_b_T); + __pyx_v_parts = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "BufferFormatFromTypeInfo":1431 + * + * parts = [b"T{"] + * field = type.fields # <<<<<<<<<<<<<< + * + * while field.type: + */ + __pyx_t_5 = __pyx_v_type->fields; + __pyx_v_field = __pyx_t_5; + + /* "BufferFormatFromTypeInfo":1433 + * field = type.fields + * + * while field.type: # <<<<<<<<<<<<<< + * part = format_from_typeinfo(field.type) + * parts.append(part + b':' + field.name + b':') + */ + while (1) { + __pyx_t_3 = (__pyx_v_field->type != 0); + if (!__pyx_t_3) break; + + /* "BufferFormatFromTypeInfo":1434 + * + * while field.type: + * part = format_from_typeinfo(field.type) # <<<<<<<<<<<<<< + * parts.append(part + b':' + field.name + b':') + * field += 1 + */ + __pyx_t_4 = __pyx_format_from_typeinfo(__pyx_v_field->type); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_part, ((PyObject*)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "BufferFormatFromTypeInfo":1435 + * while field.type: + * part = format_from_typeinfo(field.type) + * parts.append(part + b':' + field.name + b':') # <<<<<<<<<<<<<< + * field += 1 + * + */ + __pyx_t_4 = PyNumber_Add(__pyx_v_part, __pyx_kp_b__52); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_field->name); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyNumber_Add(__pyx_t_4, __pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyNumber_Add(__pyx_t_7, __pyx_kp_b__52); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = __Pyx_PyList_Append(__pyx_v_parts, __pyx_t_6); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "BufferFormatFromTypeInfo":1436 + * part = format_from_typeinfo(field.type) + * parts.append(part + b':' + field.name + b':') + * field += 1 # <<<<<<<<<<<<<< + * + * result = alignment.join(parts) + b'}' + */ + __pyx_v_field = (__pyx_v_field + 1); + } + + /* "BufferFormatFromTypeInfo":1438 + * field += 1 + * + * result = alignment.join(parts) + b'}' # <<<<<<<<<<<<<< + * else: + * fmt = __Pyx_TypeInfoToFormat(type) + */ + __pyx_t_6 = __Pyx_PyBytes_Join(__pyx_v_alignment, __pyx_v_parts); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyNumber_Add(__pyx_t_6, __pyx_kp_b__53); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_7))||((__pyx_t_7) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_7)->tp_name), 0))) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "BufferFormatFromTypeInfo":1440 + * result = alignment.join(parts) + b'}' + * else: + * fmt = __Pyx_TypeInfoToFormat(type) # <<<<<<<<<<<<<< + * if type.arraysize[0]: + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] + */ + __pyx_v_fmt = __Pyx_TypeInfoToFormat(__pyx_v_type); + + /* "BufferFormatFromTypeInfo":1441 + * else: + * fmt = __Pyx_TypeInfoToFormat(type) + * if type.arraysize[0]: # <<<<<<<<<<<<<< + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string + */ + __pyx_t_3 = ((__pyx_v_type->arraysize[0]) != 0); + if (__pyx_t_3) { + + /* "BufferFormatFromTypeInfo":1442 + * fmt = __Pyx_TypeInfoToFormat(type) + * if type.arraysize[0]: + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] # <<<<<<<<<<<<<< + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string + * else: + */ + __pyx_t_7 = PyList_New(0); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = __pyx_v_type->ndim; + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { + __pyx_v_i = __pyx_t_10; + __pyx_t_6 = __Pyx_PyInt_FromSize_t((__pyx_v_type->arraysize[__pyx_v_i])); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyUnicode_Type))), __pyx_t_4, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(__Pyx_ListComp_Append(__pyx_t_7, (PyObject*)__pyx_t_6))) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __pyx_v_extents = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + + /* "BufferFormatFromTypeInfo":1443 + * if type.arraysize[0]: + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string # <<<<<<<<<<<<<< + * else: + * result = fmt.string + */ + __pyx_t_7 = PyUnicode_Join(__pyx_kp_u__54, __pyx_v_extents); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_s, __pyx_t_7); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyUnicode_AsASCIIString(((PyObject*)__pyx_t_6)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_fmt.string); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = PyNumber_Add(__pyx_t_7, __pyx_t_6); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "BufferFormatFromTypeInfo":1445 + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string + * else: + * result = fmt.string # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_fmt.string); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_result = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + } + __pyx_L7:; + } + __pyx_L3:; + + /* "BufferFormatFromTypeInfo":1447 + * result = fmt.string + * + * return result # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "BufferFormatFromTypeInfo":1417 + * + * @cname('__pyx_format_from_typeinfo') + * cdef bytes format_from_typeinfo(__Pyx_TypeInfo *type): # <<<<<<<<<<<<<< + * cdef __Pyx_StructField *field + * cdef __pyx_typeinfo_string fmt + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("BufferFormatFromTypeInfo.format_from_typeinfo", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_part); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_alignment); + __Pyx_XDECREF(__pyx_v_parts); + __Pyx_XDECREF(__pyx_v_extents); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NeighborsHeap __pyx_vtable_7sklearn_9neighbors_9ball_tree_NeighborsHeap; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_9ball_tree_NeighborsHeap(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_NeighborsHeap; + p->distances_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->indices_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->distances.data = NULL; + p->distances.memview = NULL; + p->indices.data = NULL; + p->indices.memview = NULL; + if (unlikely(__pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_1__cinit__(o, __pyx_empty_tuple, NULL) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_9neighbors_9ball_tree_NeighborsHeap(PyObject *o) { + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->distances_arr); + Py_CLEAR(p->indices_arr); + __PYX_XDEC_MEMVIEW(&p->distances, 1); + __PYX_XDEC_MEMVIEW(&p->indices, 1); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_7sklearn_9neighbors_9ball_tree_NeighborsHeap(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)o; + if (p->distances_arr) { + e = (*v)(((PyObject*)p->distances_arr), a); if (e) return e; + } + if (p->indices_arr) { + e = (*v)(((PyObject*)p->indices_arr), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_7sklearn_9neighbors_9ball_tree_NeighborsHeap(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *)o; + tmp = ((PyObject*)p->distances_arr); + p->distances_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->indices_arr); + p->indices_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_9ball_tree_NeighborsHeap[] = { + {__Pyx_NAMESTR("get_arrays"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_5get_arrays, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_4get_arrays)}, + {__Pyx_NAMESTR("push"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_7push, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_6push)}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_9ball_tree_NeighborsHeap = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.ball_tree.NeighborsHeap"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_9ball_tree_NeighborsHeap, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("A max-heap structure to keep track of distances/indices of neighbors\n\n This implements an efficient pre-allocated set of fixed-size heaps\n for chasing neighbors, holding both an index and a distance.\n When any row of the heap is full, adding an additional point will push\n the furthest point off the heap.\n\n Parameters\n ----------\n n_pts : int\n the number of heaps to use\n n_nbrs : int\n the size of each heap.\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_9ball_tree_NeighborsHeap, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_9ball_tree_NeighborsHeap, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_9ball_tree_NeighborsHeap, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_3__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_9ball_tree_NeighborsHeap, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_NodeHeap __pyx_vtable_7sklearn_9neighbors_9ball_tree_NodeHeap; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_9ball_tree_NodeHeap(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_NodeHeap; + p->data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->data.data = NULL; + p->data.memview = NULL; + if (unlikely(__pyx_pw_7sklearn_9neighbors_9ball_tree_8NodeHeap_1__cinit__(o, __pyx_empty_tuple, NULL) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_9neighbors_9ball_tree_NodeHeap(PyObject *o) { + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->data_arr); + __PYX_XDEC_MEMVIEW(&p->data, 1); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_7sklearn_9neighbors_9ball_tree_NodeHeap(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *)o; + if (p->data_arr) { + e = (*v)(((PyObject*)p->data_arr), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_7sklearn_9neighbors_9ball_tree_NodeHeap(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *)o; + tmp = ((PyObject*)p->data_arr); + p->data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_9ball_tree_NodeHeap[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_9ball_tree_NodeHeap = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.ball_tree.NodeHeap"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_9ball_tree_NodeHeap, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("NodeHeap\n\n This is a min-heap implementation for keeping track of nodes\n during a breadth-first search. Unlike the NeighborsHeap above,\n the NodeHeap does not have a fixed size and must be able to grow\n as elements are added.\n\n Internally, the data is stored in a simple binary heap which meets\n the min heap condition:\n\n heap[i].val < min(heap[2 * i + 1].val, heap[2 * i + 2].val)\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_9ball_tree_NodeHeap, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_9ball_tree_NodeHeap, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_9ball_tree_NodeHeap, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_9ball_tree_8NodeHeap_3__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_9ball_tree_NodeHeap, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_9ball_tree_BinaryTree(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BinaryTree; + p->data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->idx_array_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->node_data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->node_bounds_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->dist_metric = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)Py_None); Py_INCREF(Py_None); + p->data.data = NULL; + p->data.memview = NULL; + p->idx_array.data = NULL; + p->idx_array.memview = NULL; + p->node_data.data = NULL; + p->node_data.memview = NULL; + p->node_bounds.data = NULL; + p->node_bounds.memview = NULL; + if (unlikely(__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_1__cinit__(o, __pyx_empty_tuple, NULL) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_9neighbors_9ball_tree_BinaryTree(PyObject *o) { + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->data_arr); + Py_CLEAR(p->idx_array_arr); + Py_CLEAR(p->node_data_arr); + Py_CLEAR(p->node_bounds_arr); + Py_CLEAR(p->dist_metric); + __PYX_XDEC_MEMVIEW(&p->data, 1); + __PYX_XDEC_MEMVIEW(&p->idx_array, 1); + __PYX_XDEC_MEMVIEW(&p->node_data, 1); + __PYX_XDEC_MEMVIEW(&p->node_bounds, 1); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_7sklearn_9neighbors_9ball_tree_BinaryTree(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)o; + if (p->data_arr) { + e = (*v)(((PyObject*)p->data_arr), a); if (e) return e; + } + if (p->idx_array_arr) { + e = (*v)(((PyObject*)p->idx_array_arr), a); if (e) return e; + } + if (p->node_data_arr) { + e = (*v)(((PyObject*)p->node_data_arr), a); if (e) return e; + } + if (p->node_bounds_arr) { + e = (*v)(((PyObject*)p->node_bounds_arr), a); if (e) return e; + } + if (p->dist_metric) { + e = (*v)(((PyObject*)p->dist_metric), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_7sklearn_9neighbors_9ball_tree_BinaryTree(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *p = (struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *)o; + tmp = ((PyObject*)p->data_arr); + p->data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->idx_array_arr); + p->idx_array_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->node_data_arr); + p->node_data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->node_bounds_arr); + p->node_bounds_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->dist_metric); + p->dist_metric = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyObject *__pyx_getprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_data(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_4data_1__get__(o); +} + +static PyObject *__pyx_getprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_idx_array(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array_1__get__(o); +} + +static int __pyx_setprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_idx_array(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9idx_array_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_node_data(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data_1__get__(o); +} + +static int __pyx_setprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_node_data(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9node_data_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_node_bounds(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds_1__get__(o); +} + +static int __pyx_setprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_node_bounds(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_11node_bounds_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_9ball_tree_BinaryTree[] = { + {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_5__reduce__, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_4__reduce__)}, + {__Pyx_NAMESTR("__getstate__"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_7__getstate__, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_6__getstate__)}, + {__Pyx_NAMESTR("__setstate__"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_9__setstate__, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_8__setstate__)}, + {__Pyx_NAMESTR("get_tree_stats"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_11get_tree_stats, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("reset_n_calls"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_13reset_n_calls, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("get_n_calls"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_15get_n_calls, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("get_arrays"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_17get_arrays, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("query"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_19query, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_18query)}, + {__Pyx_NAMESTR("query_radius"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_21query_radius, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_20query_radius)}, + {__Pyx_NAMESTR("kernel_density"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_23kernel_density, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_22kernel_density)}, + {__Pyx_NAMESTR("two_point_correlation"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_25two_point_correlation, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_9ball_tree_10BinaryTree_24two_point_correlation)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_7sklearn_9neighbors_9ball_tree_BinaryTree[] = { + {(char *)"data", __pyx_getprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_data, 0, 0, 0}, + {(char *)"idx_array", __pyx_getprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_idx_array, __pyx_setprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_idx_array, 0, 0}, + {(char *)"node_data", __pyx_getprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_node_data, __pyx_setprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_node_data, 0, 0}, + {(char *)"node_bounds", __pyx_getprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_node_bounds, __pyx_setprop_7sklearn_9neighbors_9ball_tree_10BinaryTree_node_bounds, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_9ball_tree_BinaryTree = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.ball_tree.BinaryTree"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_9ball_tree_BinaryTree, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_9ball_tree_BinaryTree, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_9ball_tree_BinaryTree, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_9ball_tree_BinaryTree, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_7sklearn_9neighbors_9ball_tree_BinaryTree, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_3__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_9ball_tree_BinaryTree, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BallTree __pyx_vtable_7sklearn_9neighbors_9ball_tree_BallTree; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_9ball_tree_BallTree(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_9ball_tree_BinaryTree(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_9ball_tree_BinaryTree*)__pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BallTree; + return o; +} + +static PyTypeObject __pyx_type_7sklearn_9neighbors_9ball_tree_BallTree = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.ball_tree.BallTree"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BallTree), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_9ball_tree_BinaryTree, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_9ball_tree_BinaryTree, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_9ball_tree_BinaryTree, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_9ball_tree_10BinaryTree_3__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_9ball_tree_BallTree, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_array_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_array_obj *)o); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_array___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->mode); + Py_CLEAR(p->_format); + (*Py_TYPE(o)->tp_free)(o); +} +static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_array___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { + PyObject *v = PyObject_GenericGetAttr(o, n); + if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + v = __pyx_array___getattr__(o, n); + } + return v; +} + +static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { + return get_memview(o); +} + +static PyMethodDef __pyx_methods_array[] = { + {__Pyx_NAMESTR("__getattr__"), (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_array[] = { + {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_array = { + 0, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_array, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_array = { + 0, /*mp_length*/ + __pyx_array___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_array = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_array_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_array = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.ball_tree.array"), /*tp_name*/ + sizeof(struct __pyx_array_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_array, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + __pyx_tp_getattro_array, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_array, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_array, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_array, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_MemviewEnum_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_MemviewEnum_obj *)o); + p->name = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->name); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + if (p->name) { + e = (*v)(p->name, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_Enum(PyObject *o) { + PyObject* tmp; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + tmp = ((PyObject*)p->name); + p->name = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_Enum[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_MemviewEnum = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.ball_tree.Enum"), /*tp_name*/ + sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_Enum, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_MemviewEnum___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_Enum, /*tp_traverse*/ + __pyx_tp_clear_Enum, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_Enum, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_MemviewEnum___init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_Enum, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; + +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryview_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryview_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_memoryview; + p->obj = Py_None; Py_INCREF(Py_None); + p->_size = Py_None; Py_INCREF(Py_None); + p->_array_interface = Py_None; Py_INCREF(Py_None); + p->view.obj = NULL; + if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryview___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->obj); + Py_CLEAR(p->_size); + Py_CLEAR(p->_array_interface); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + if (p->obj) { + e = (*v)(p->obj, a); if (e) return e; + } + if (p->_size) { + e = (*v)(p->_size, a); if (e) return e; + } + if (p->_array_interface) { + e = (*v)(p->_array_interface, a); if (e) return e; + } + if (p->view.obj) { + e = (*v)(p->view.obj, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_memoryview(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + tmp = ((PyObject*)p->obj); + p->obj = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_size); + p->_size = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_array_interface); + p->_array_interface = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + Py_CLEAR(p->view.obj); + return 0; +} +static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_memoryview___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_transpose(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview__get__base(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_shape(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_strides(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_suboffsets(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_ndim(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_itemsize(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_nbytes(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_size(o); +} + +static PyMethodDef __pyx_methods_memoryview[] = { + {__Pyx_NAMESTR("is_c_contig"), (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("is_f_contig"), (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy"), (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy_fortran"), (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_memoryview[] = { + {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, + {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, + {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, + {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, + {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, + {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, + {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, + {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_memoryview = { + __pyx_memoryview___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_memoryview, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_memoryview = { + __pyx_memoryview___len__, /*mp_length*/ + __pyx_memoryview___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_memoryview = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_memoryview_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_memoryview = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.ball_tree.memoryview"), /*tp_name*/ + sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_memoryview___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_memoryview___str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_memoryview, /*tp_traverse*/ + __pyx_tp_clear_memoryview, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_memoryview, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_memoryview, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_memoryview, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; + +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryviewslice_obj *p; + PyObject *o = __pyx_tp_new_memoryview(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryviewslice_obj *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; + p->from_object = Py_None; Py_INCREF(Py_None); + p->from_slice.memview = NULL; + return o; +} + +static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryviewslice___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->from_object); + PyObject_GC_Track(o); + __pyx_tp_dealloc_memoryview(o); +} + +static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; + if (p->from_object) { + e = (*v)(p->from_object, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear__memoryviewslice(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + __pyx_tp_clear_memoryview(o); + tmp = ((PyObject*)p->from_object); + p->from_object = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + __PYX_XDEC_MEMVIEW(&p->from_slice, 1); + return 0; +} + +static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryviewslice__get__base(o); +} + +static PyMethodDef __pyx_methods__memoryviewslice[] = { + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { + {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_memoryviewslice = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.ball_tree._memoryviewslice"), /*tp_name*/ + sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___repr__, /*tp_repr*/ + #else + 0, /*tp_repr*/ + #endif + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___str__, /*tp_str*/ + #else + 0, /*tp_str*/ + #endif + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Internal class for passing memoryview slices to Python"), /*tp_doc*/ + __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ + __pyx_tp_clear__memoryviewslice, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods__memoryviewslice, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets__memoryviewslice, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new__memoryviewslice, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + __Pyx_NAMESTR("ball_tree"), + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_n_s_BallTree, __pyx_k_BallTree, sizeof(__pyx_k_BallTree), 0, 0, 1, 1}, + {&__pyx_n_s_BinaryTree, __pyx_k_BinaryTree, sizeof(__pyx_k_BinaryTree), 0, 0, 1, 1}, + {&__pyx_kp_s_BinaryTree_for_fast_generalized, __pyx_k_BinaryTree_for_fast_generalized, sizeof(__pyx_k_BinaryTree_for_fast_generalized), 0, 0, 1, 0}, + {&__pyx_kp_u_BinaryTree_kernel_density_line_1, __pyx_k_BinaryTree_kernel_density_line_1, sizeof(__pyx_k_BinaryTree_kernel_density_line_1), 0, 1, 0, 0}, + {&__pyx_kp_u_BinaryTree_query_line_1228, __pyx_k_BinaryTree_query_line_1228, sizeof(__pyx_k_BinaryTree_query_line_1228), 0, 1, 0, 0}, + {&__pyx_kp_u_BinaryTree_query_radius_line_135, __pyx_k_BinaryTree_query_radius_line_135, sizeof(__pyx_k_BinaryTree_query_radius_line_135), 0, 1, 0, 0}, + {&__pyx_kp_u_BinaryTree_two_point_correlation, __pyx_k_BinaryTree_two_point_correlation, sizeof(__pyx_k_BinaryTree_two_point_correlation), 0, 1, 0, 0}, + {&__pyx_n_s_BrayCurtisDistance, __pyx_k_BrayCurtisDistance, sizeof(__pyx_k_BrayCurtisDistance), 0, 0, 1, 1}, + {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, + {&__pyx_n_s_C, __pyx_k_C, sizeof(__pyx_k_C), 0, 0, 1, 1}, + {&__pyx_n_s_CLASS_DOC, __pyx_k_CLASS_DOC, sizeof(__pyx_k_CLASS_DOC), 0, 0, 1, 1}, + {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, + {&__pyx_n_s_CanberraDistance, __pyx_k_CanberraDistance, sizeof(__pyx_k_CanberraDistance), 0, 0, 1, 1}, + {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, + {&__pyx_n_s_ChebyshevDistance, __pyx_k_ChebyshevDistance, sizeof(__pyx_k_ChebyshevDistance), 0, 0, 1, 1}, + {&__pyx_kp_u_Compute_the_two_point_correlatio, __pyx_k_Compute_the_two_point_correlatio, sizeof(__pyx_k_Compute_the_two_point_correlatio), 0, 1, 0, 0}, + {&__pyx_n_s_DOC_DICT, __pyx_k_DOC_DICT, sizeof(__pyx_k_DOC_DICT), 0, 0, 1, 1}, + {&__pyx_n_s_DTYPE, __pyx_k_DTYPE, sizeof(__pyx_k_DTYPE), 0, 0, 1, 1}, + {&__pyx_n_s_DiceDistance, __pyx_k_DiceDistance, sizeof(__pyx_k_DiceDistance), 0, 0, 1, 1}, + {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, + {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, + {&__pyx_n_s_EuclideanDistance, __pyx_k_EuclideanDistance, sizeof(__pyx_k_EuclideanDistance), 0, 0, 1, 1}, + {&__pyx_kp_s_Fatal_count_out_of_range_This_sh, __pyx_k_Fatal_count_out_of_range_This_sh, sizeof(__pyx_k_Fatal_count_out_of_range_This_sh), 0, 0, 1, 0}, + {&__pyx_kp_s_Fatal_count_too_big_this_should, __pyx_k_Fatal_count_too_big_this_should, sizeof(__pyx_k_Fatal_count_too_big_this_should), 0, 0, 1, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_n_s_HammingDistance, __pyx_k_HammingDistance, sizeof(__pyx_k_HammingDistance), 0, 0, 1, 1}, + {&__pyx_n_s_HaversineDistance, __pyx_k_HaversineDistance, sizeof(__pyx_k_HaversineDistance), 0, 0, 1, 1}, + {&__pyx_n_s_ITYPE, __pyx_k_ITYPE, sizeof(__pyx_k_ITYPE), 0, 0, 1, 1}, + {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, + {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, + {&__pyx_kp_s_Internal_memory_layout_is_flawed, __pyx_k_Internal_memory_layout_is_flawed, sizeof(__pyx_k_Internal_memory_layout_is_flawed), 0, 0, 1, 0}, + {&__pyx_kp_s_Internal_memory_layout_is_flawed_2, __pyx_k_Internal_memory_layout_is_flawed_2, sizeof(__pyx_k_Internal_memory_layout_is_flawed_2), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, + {&__pyx_n_s_JaccardDistance, __pyx_k_JaccardDistance, sizeof(__pyx_k_JaccardDistance), 0, 0, 1, 1}, + {&__pyx_kp_s_Kernel_code_not_recognized, __pyx_k_Kernel_code_not_recognized, sizeof(__pyx_k_Kernel_code_not_recognized), 0, 0, 1, 0}, + {&__pyx_n_s_KulsinskiDistance, __pyx_k_KulsinskiDistance, sizeof(__pyx_k_KulsinskiDistance), 0, 0, 1, 1}, + {&__pyx_n_s_MahalanobisDistance, __pyx_k_MahalanobisDistance, sizeof(__pyx_k_MahalanobisDistance), 0, 0, 1, 1}, + {&__pyx_n_s_ManhattanDistance, __pyx_k_ManhattanDistance, sizeof(__pyx_k_ManhattanDistance), 0, 0, 1, 1}, + {&__pyx_n_s_MatchingDistance, __pyx_k_MatchingDistance, sizeof(__pyx_k_MatchingDistance), 0, 0, 1, 1}, + {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, + {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, + {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, + {&__pyx_n_s_MinkowskiDistance, __pyx_k_MinkowskiDistance, sizeof(__pyx_k_MinkowskiDistance), 0, 0, 1, 1}, + {&__pyx_n_s_NodeData, __pyx_k_NodeData, sizeof(__pyx_k_NodeData), 0, 0, 1, 1}, + {&__pyx_n_s_NodeHeapData, __pyx_k_NodeHeapData, sizeof(__pyx_k_NodeHeapData), 0, 0, 1, 1}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, + {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, + {&__pyx_n_s_PyFuncDistance, __pyx_k_PyFuncDistance, sizeof(__pyx_k_PyFuncDistance), 0, 0, 1, 1}, + {&__pyx_n_s_RogersTanimotoDistance, __pyx_k_RogersTanimotoDistance, sizeof(__pyx_k_RogersTanimotoDistance), 0, 0, 1, 1}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_RussellRaoDistance, __pyx_k_RussellRaoDistance, sizeof(__pyx_k_RussellRaoDistance), 0, 0, 1, 1}, + {&__pyx_n_s_SEuclideanDistance, __pyx_k_SEuclideanDistance, sizeof(__pyx_k_SEuclideanDistance), 0, 0, 1, 1}, + {&__pyx_n_s_SokalMichenerDistance, __pyx_k_SokalMichenerDistance, sizeof(__pyx_k_SokalMichenerDistance), 0, 0, 1, 1}, + {&__pyx_n_s_SokalSneathDistance, __pyx_k_SokalSneathDistance, sizeof(__pyx_k_SokalSneathDistance), 0, 0, 1, 1}, + {&__pyx_kp_b_T, __pyx_k_T, sizeof(__pyx_k_T), 0, 0, 0, 0}, + {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, + {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, + {&__pyx_n_s_VALID_METRICS, __pyx_k_VALID_METRICS, sizeof(__pyx_k_VALID_METRICS), 0, 0, 1, 1}, + {&__pyx_n_s_VALID_METRIC_IDS, __pyx_k_VALID_METRIC_IDS, sizeof(__pyx_k_VALID_METRIC_IDS), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_WMinkowskiDistance, __pyx_k_WMinkowskiDistance, sizeof(__pyx_k_WMinkowskiDistance), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_kp_s_X_is_an_empty_array, __pyx_k_X_is_an_empty_array, sizeof(__pyx_k_X_is_an_empty_array), 0, 0, 1, 0}, + {&__pyx_kp_b__50, __pyx_k__50, sizeof(__pyx_k__50), 0, 0, 0, 0}, + {&__pyx_kp_b__51, __pyx_k__51, sizeof(__pyx_k__51), 0, 0, 0, 0}, + {&__pyx_kp_b__52, __pyx_k__52, sizeof(__pyx_k__52), 0, 0, 0, 0}, + {&__pyx_kp_b__53, __pyx_k__53, sizeof(__pyx_k__53), 0, 0, 0, 0}, + {&__pyx_kp_u__54, __pyx_k__54, sizeof(__pyx_k__54), 0, 1, 0, 0}, + {&__pyx_n_s_all, __pyx_k_all, sizeof(__pyx_k_all), 0, 0, 1, 1}, + {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, + {&__pyx_n_s_arange, __pyx_k_arange, sizeof(__pyx_k_arange), 0, 0, 1, 1}, + {&__pyx_n_s_argsort, __pyx_k_argsort, sizeof(__pyx_k_argsort), 0, 0, 1, 1}, + {&__pyx_n_s_asarray, __pyx_k_asarray, sizeof(__pyx_k_asarray), 0, 0, 1, 1}, + {&__pyx_n_s_atleast_1d, __pyx_k_atleast_1d, sizeof(__pyx_k_atleast_1d), 0, 0, 1, 1}, + {&__pyx_n_s_atol, __pyx_k_atol, sizeof(__pyx_k_atol), 0, 0, 1, 1}, + {&__pyx_n_s_ball_tree, __pyx_k_ball_tree, sizeof(__pyx_k_ball_tree), 0, 0, 1, 1}, + {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, + {&__pyx_n_s_binary_tree, __pyx_k_binary_tree, sizeof(__pyx_k_binary_tree), 0, 0, 1, 1}, + {&__pyx_n_s_breadth_first, __pyx_k_breadth_first, sizeof(__pyx_k_breadth_first), 0, 0, 1, 1}, + {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, + {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, + {&__pyx_kp_s_cannot_pop_on_empty_heap, __pyx_k_cannot_pop_on_empty_heap, sizeof(__pyx_k_cannot_pop_on_empty_heap), 0, 0, 1, 0}, + {&__pyx_n_s_check_array, __pyx_k_check_array, sizeof(__pyx_k_check_array), 0, 0, 1, 1}, + {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, + {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_copy, __pyx_k_copy, sizeof(__pyx_k_copy), 0, 0, 1, 1}, + {&__pyx_n_s_cosine, __pyx_k_cosine, sizeof(__pyx_k_cosine), 0, 0, 1, 1}, + {&__pyx_n_s_count_only, __pyx_k_count_only, sizeof(__pyx_k_count_only), 0, 0, 1, 1}, + {&__pyx_kp_s_count_only_and_return_distance_c, __pyx_k_count_only_and_return_distance_c, sizeof(__pyx_k_count_only_and_return_distance_c), 0, 0, 1, 0}, + {&__pyx_n_s_d, __pyx_k_d, sizeof(__pyx_k_d), 0, 0, 1, 1}, + {&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1}, + {&__pyx_n_s_dist_metrics, __pyx_k_dist_metrics, sizeof(__pyx_k_dist_metrics), 0, 0, 1, 1}, + {&__pyx_n_s_distances, __pyx_k_distances, sizeof(__pyx_k_distances), 0, 0, 1, 1}, + {&__pyx_n_s_doc, __pyx_k_doc, sizeof(__pyx_k_doc), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, + {&__pyx_n_s_dualtree, __pyx_k_dualtree, sizeof(__pyx_k_dualtree), 0, 0, 1, 1}, + {&__pyx_n_s_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 0, 0, 1, 1}, + {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, + {&__pyx_n_s_epanechnikov, __pyx_k_epanechnikov, sizeof(__pyx_k_epanechnikov), 0, 0, 1, 1}, + {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, + {&__pyx_n_s_exp, __pyx_k_exp, sizeof(__pyx_k_exp), 0, 0, 1, 1}, + {&__pyx_n_s_exponential, __pyx_k_exponential, sizeof(__pyx_k_exponential), 0, 0, 1, 1}, + {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, + {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, + {&__pyx_n_s_formats, __pyx_k_formats, sizeof(__pyx_k_formats), 0, 0, 1, 1}, + {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, + {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, + {&__pyx_n_s_gaussian, __pyx_k_gaussian, sizeof(__pyx_k_gaussian), 0, 0, 1, 1}, + {&__pyx_n_s_get_arrays, __pyx_k_get_arrays, sizeof(__pyx_k_get_arrays), 0, 0, 1, 1}, + {&__pyx_n_s_get_metric, __pyx_k_get_metric, sizeof(__pyx_k_get_metric), 0, 0, 1, 1}, + {&__pyx_n_s_get_valid_metric_ids, __pyx_k_get_valid_metric_ids, sizeof(__pyx_k_get_valid_metric_ids), 0, 0, 1, 1}, + {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, + {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, + {&__pyx_n_s_h, __pyx_k_h, sizeof(__pyx_k_h), 0, 0, 1, 1}, + {&__pyx_n_s_heap, __pyx_k_heap, sizeof(__pyx_k_heap), 0, 0, 1, 1}, + {&__pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_k_home_manoj_scikit_learn_sklearn, sizeof(__pyx_k_home_manoj_scikit_learn_sklearn), 0, 0, 1, 0}, + {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, + {&__pyx_n_s_i1, __pyx_k_i1, sizeof(__pyx_k_i1), 0, 0, 1, 1}, + {&__pyx_n_s_i2, __pyx_k_i2, sizeof(__pyx_k_i2), 0, 0, 1, 1}, + {&__pyx_n_s_i_val, __pyx_k_i_val, sizeof(__pyx_k_i_val), 0, 0, 1, 1}, + {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, + {&__pyx_n_s_idx_end, __pyx_k_idx_end, sizeof(__pyx_k_idx_end), 0, 0, 1, 1}, + {&__pyx_n_s_idx_start, __pyx_k_idx_start, sizeof(__pyx_k_idx_start), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_indices, __pyx_k_indices, sizeof(__pyx_k_indices), 0, 0, 1, 1}, + {&__pyx_n_s_inf, __pyx_k_inf, sizeof(__pyx_k_inf), 0, 0, 1, 1}, + {&__pyx_n_s_is_leaf, __pyx_k_is_leaf, sizeof(__pyx_k_is_leaf), 0, 0, 1, 1}, + {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, + {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, + {&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, + {&__pyx_n_s_join, __pyx_k_join, sizeof(__pyx_k_join), 0, 0, 1, 1}, + {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1}, + {&__pyx_kp_s_k_must_be_less_than_or_equal_to, __pyx_k_k_must_be_less_than_or_equal_to, sizeof(__pyx_k_k_must_be_less_than_or_equal_to), 0, 0, 1, 0}, + {&__pyx_n_s_kernel, __pyx_k_kernel, sizeof(__pyx_k_kernel), 0, 0, 1, 1}, + {&__pyx_kp_u_kernel_density_self_X_h_kernel, __pyx_k_kernel_density_self_X_h_kernel, sizeof(__pyx_k_kernel_density_self_X_h_kernel), 0, 1, 0, 0}, + {&__pyx_n_s_kernel_norm, __pyx_k_kernel_norm, sizeof(__pyx_k_kernel_norm), 0, 0, 1, 1}, + {&__pyx_kp_s_kernel_not_recognized, __pyx_k_kernel_not_recognized, sizeof(__pyx_k_kernel_not_recognized), 0, 0, 1, 0}, + {&__pyx_kp_s_kernel_s_not_recognized, __pyx_k_kernel_s_not_recognized, sizeof(__pyx_k_kernel_s_not_recognized), 0, 0, 1, 0}, + {&__pyx_n_s_leaf_size, __pyx_k_leaf_size, sizeof(__pyx_k_leaf_size), 0, 0, 1, 1}, + {&__pyx_kp_s_leaf_size_must_be_greater_than_o, __pyx_k_leaf_size_must_be_greater_than_o, sizeof(__pyx_k_leaf_size_must_be_greater_than_o), 0, 0, 1, 0}, + {&__pyx_n_s_linear, __pyx_k_linear, sizeof(__pyx_k_linear), 0, 0, 1, 1}, + {&__pyx_n_s_load_heap, __pyx_k_load_heap, sizeof(__pyx_k_load_heap), 0, 0, 1, 1}, + {&__pyx_n_s_log2, __pyx_k_log2, sizeof(__pyx_k_log2), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, + {&__pyx_n_s_metric, __pyx_k_metric, sizeof(__pyx_k_metric), 0, 0, 1, 1}, + {&__pyx_kp_s_metric_metric_is_not_valid_for_B, __pyx_k_metric_metric_is_not_valid_for_B, sizeof(__pyx_k_metric_metric_is_not_valid_for_B), 0, 0, 1, 0}, + {&__pyx_n_s_minkowski, __pyx_k_minkowski, sizeof(__pyx_k_minkowski), 0, 0, 1, 1}, + {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, + {&__pyx_n_s_n_nbrs, __pyx_k_n_nbrs, sizeof(__pyx_k_n_nbrs), 0, 0, 1, 1}, + {&__pyx_n_s_n_pts, __pyx_k_n_pts, sizeof(__pyx_k_n_pts), 0, 0, 1, 1}, + {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, + {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, + {&__pyx_n_s_names, __pyx_k_names, sizeof(__pyx_k_names), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, + {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, + {&__pyx_n_s_newObj, __pyx_k_newObj, sizeof(__pyx_k_newObj), 0, 0, 1, 1}, + {&__pyx_n_s_node_data, __pyx_k_node_data, sizeof(__pyx_k_node_data), 0, 0, 1, 1}, + {&__pyx_n_s_nodeheap_sort, __pyx_k_nodeheap_sort, sizeof(__pyx_k_nodeheap_sort), 0, 0, 1, 1}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, + {&__pyx_n_s_object, __pyx_k_object, sizeof(__pyx_k_object), 0, 0, 1, 1}, + {&__pyx_n_s_offsets, __pyx_k_offsets, sizeof(__pyx_k_offsets), 0, 0, 1, 1}, + {&__pyx_n_s_order, __pyx_k_order, sizeof(__pyx_k_order), 0, 0, 1, 1}, + {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, + {&__pyx_n_s_pi, __pyx_k_pi, sizeof(__pyx_k_pi), 0, 0, 1, 1}, + {&__pyx_n_s_push, __pyx_k_push, sizeof(__pyx_k_push), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_releasebuffer, __pyx_k_pyx_releasebuffer, sizeof(__pyx_k_pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_kp_u_query_X_k_1_return_distance_Tru, __pyx_k_query_X_k_1_return_distance_Tru, sizeof(__pyx_k_query_X_k_1_return_distance_Tru), 0, 1, 0, 0}, + {&__pyx_kp_s_query_data_dimension_must_match, __pyx_k_query_data_dimension_must_match, sizeof(__pyx_k_query_data_dimension_must_match), 0, 0, 1, 0}, + {&__pyx_kp_u_query_radius_self_X_r_count_onl, __pyx_k_query_radius_self_X_r_count_onl, sizeof(__pyx_k_query_radius_self_X_r_count_onl), 0, 1, 0, 0}, + {&__pyx_n_s_r, __pyx_k_r, sizeof(__pyx_k_r), 0, 0, 1, 1}, + {&__pyx_kp_s_r_must_be_a_1_dimensional_array, __pyx_k_r_must_be_a_1_dimensional_array, sizeof(__pyx_k_r_must_be_a_1_dimensional_array), 0, 0, 1, 0}, + {&__pyx_kp_s_r_must_be_broadcastable_to_X_sha, __pyx_k_r_must_be_broadcastable_to_X_sha, sizeof(__pyx_k_r_must_be_broadcastable_to_X_sha), 0, 0, 1, 0}, + {&__pyx_n_s_radius, __pyx_k_radius, sizeof(__pyx_k_radius), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_rdist_to_dist, __pyx_k_rdist_to_dist, sizeof(__pyx_k_rdist_to_dist), 0, 0, 1, 1}, + {&__pyx_n_s_reshape, __pyx_k_reshape, sizeof(__pyx_k_reshape), 0, 0, 1, 1}, + {&__pyx_n_s_result, __pyx_k_result, sizeof(__pyx_k_result), 0, 0, 1, 1}, + {&__pyx_n_s_return_distance, __pyx_k_return_distance, sizeof(__pyx_k_return_distance), 0, 0, 1, 1}, + {&__pyx_kp_s_return_distance_must_be_True_if, __pyx_k_return_distance_must_be_True_if, sizeof(__pyx_k_return_distance_must_be_True_if), 0, 0, 1, 0}, + {&__pyx_n_s_return_log, __pyx_k_return_log, sizeof(__pyx_k_return_log), 0, 0, 1, 1}, + {&__pyx_n_s_row, __pyx_k_row, sizeof(__pyx_k_row), 0, 0, 1, 1}, + {&__pyx_n_s_rtol, __pyx_k_rtol, sizeof(__pyx_k_rtol), 0, 0, 1, 1}, + {&__pyx_kp_u_s, __pyx_k_s, sizeof(__pyx_k_s), 0, 1, 0, 0}, + {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, + {&__pyx_n_s_simultaneous_sort, __pyx_k_simultaneous_sort, sizeof(__pyx_k_simultaneous_sort), 0, 0, 1, 1}, + {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, + {&__pyx_n_s_size_guess, __pyx_k_size_guess, sizeof(__pyx_k_size_guess), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_neighbors_ball_tree, __pyx_k_sklearn_neighbors_ball_tree, sizeof(__pyx_k_sklearn_neighbors_ball_tree), 0, 0, 1, 1}, + {&__pyx_n_s_sort, __pyx_k_sort, sizeof(__pyx_k_sort), 0, 0, 1, 1}, + {&__pyx_n_s_sort_results, __pyx_k_sort_results, sizeof(__pyx_k_sort_results), 0, 0, 1, 1}, + {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, + {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, + {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, + {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_tophat, __pyx_k_tophat, sizeof(__pyx_k_tophat), 0, 0, 1, 1}, + {&__pyx_n_s_typedefs, __pyx_k_typedefs, sizeof(__pyx_k_typedefs), 0, 0, 1, 1}, + {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, + {&__pyx_kp_s_unable_to_allocate_shape_and_str, __pyx_k_unable_to_allocate_shape_and_str, sizeof(__pyx_k_unable_to_allocate_shape_and_str), 0, 0, 1, 0}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, + {&__pyx_n_s_utils, __pyx_k_utils, sizeof(__pyx_k_utils), 0, 0, 1, 1}, + {&__pyx_n_s_val, __pyx_k_val, sizeof(__pyx_k_val), 0, 0, 1, 1}, + {&__pyx_n_s_valid_metrics, __pyx_k_valid_metrics, sizeof(__pyx_k_valid_metrics), 0, 0, 1, 1}, + {&__pyx_n_s_vals, __pyx_k_vals, sizeof(__pyx_k_vals), 0, 0, 1, 1}, + {&__pyx_n_s_vals_sorted, __pyx_k_vals_sorted, sizeof(__pyx_k_vals_sorted), 0, 0, 1, 1}, + {&__pyx_n_s_warn, __pyx_k_warn, sizeof(__pyx_k_warn), 0, 0, 1, 1}, + {&__pyx_n_s_warnings, __pyx_k_warnings, sizeof(__pyx_k_warnings), 0, 0, 1, 1}, + {&__pyx_n_s_xrange, __pyx_k_xrange, sizeof(__pyx_k_xrange), 0, 0, 1, 1}, + {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, + {&__pyx_n_s_zeros_like, __pyx_k_zeros_like, sizeof(__pyx_k_zeros_like), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 789; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":493 + * factor = log(factor) + logSn(d - 1) + * else: + * raise ValueError("Kernel code not recognized") # <<<<<<<<<<<<<< + * return -factor - d * log(h) + * + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_s_Kernel_code_not_recognized); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":531 + * result = _log_kernel_norm(h, d, COSINE_KERNEL) + * else: + * raise ValueError('kernel not recognized') # <<<<<<<<<<<<<< + * + * if return_log: + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_kernel_not_recognized); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":582 + * + * def __cinit__(self): + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + */ + __pyx_tuple__3 = PyTuple_Pack(2, __pyx_int_1, __pyx_int_1); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_tuple__3); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":583 + * def __cinit__(self): + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + */ + __pyx_tuple__5 = PyTuple_Pack(2, __pyx_int_1, __pyx_int_1); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_tuple__5); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":878 + * + * def __cinit__(self): + * self.data_arr = np.zeros(1, dtype=NodeHeapData, order='C') # <<<<<<<<<<<<<< + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + * + */ + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_int_1); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":941 + * """Remove the root of the heap, and update the remaining nodes""" + * if self.n == 0: + * raise ValueError('cannot pop on empty heap') # <<<<<<<<<<<<<< + * + * cdef ITYPE_t i, i_child1, i_child2, i_swap + */ + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_cannot_pop_on_empty_heap); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 941; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1027 + * # errors and seg-faults in rare cases where __init__ is not called + * def __cinit__(self): + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + */ + __pyx_tuple__9 = PyTuple_Pack(2, __pyx_int_1, __pyx_int_1); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + __pyx_tuple__10 = PyTuple_Pack(1, __pyx_tuple__9); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1028 + * def __cinit__(self): + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) + */ + __pyx_tuple__11 = PyTuple_Pack(1, __pyx_int_1); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__11); + __Pyx_GIVEREF(__pyx_tuple__11); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1029 + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') # <<<<<<<<<<<<<< + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) + * + */ + __pyx_tuple__12 = PyTuple_Pack(1, __pyx_int_1); if (unlikely(!__pyx_tuple__12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1030 + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) # <<<<<<<<<<<<<< + * + * self.data = get_memview_DTYPE_2D(self.data_arr) + */ + __pyx_tuple__13 = PyTuple_Pack(3, __pyx_int_1, __pyx_int_1, __pyx_int_1); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__13); + __Pyx_GIVEREF(__pyx_tuple__13); + __pyx_tuple__14 = PyTuple_Pack(1, __pyx_tuple__13); if (unlikely(!__pyx_tuple__14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_GIVEREF(__pyx_tuple__14); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1066 + * # validate data + * if self.data.size == 0: + * raise ValueError("X is an empty array") # <<<<<<<<<<<<<< + * + * if leaf_size < 1: + */ + __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_X_is_an_empty_array); if (unlikely(!__pyx_tuple__15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1066; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__15); + __Pyx_GIVEREF(__pyx_tuple__15); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1069 + * + * if leaf_size < 1: + * raise ValueError("leaf_size must be greater than or equal to 1") # <<<<<<<<<<<<<< + * + * n_samples = self.data.shape[0] + */ + __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_leaf_size_must_be_greater_than_o); if (unlikely(!__pyx_tuple__16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__16); + __Pyx_GIVEREF(__pyx_tuple__16); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1205 + * # warning saying we're doing so. + * import warnings + * warnings.warn("Internal: memory layout is flawed: " # <<<<<<<<<<<<<< + * "not enough nodes allocated") + * + */ + __pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_s_Internal_memory_layout_is_flawed); if (unlikely(!__pyx_tuple__17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__17); + __Pyx_GIVEREF(__pyx_tuple__17); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1212 + * # is correct. Raise a warning. + * import warnings + * warnings.warn("Internal: memory layout is flawed: " # <<<<<<<<<<<<<< + * "too many nodes allocated") + * self.node_data[i_node].is_leaf = True + */ + __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_Internal_memory_layout_is_flawed_2); if (unlikely(!__pyx_tuple__18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__18); + __Pyx_GIVEREF(__pyx_tuple__18); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1290 + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * + */ + __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_query_data_dimension_must_match); if (unlikely(!__pyx_tuple__19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__19); + __Pyx_GIVEREF(__pyx_tuple__19); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1294 + * + * if self.data.shape[0] < k: + * raise ValueError("k must be less than or equal " # <<<<<<<<<<<<<< + * "to the number of training points") + * + */ + __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_k_must_be_less_than_or_equal_to); if (unlikely(!__pyx_tuple__20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__20); + __Pyx_GIVEREF(__pyx_tuple__20); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1420 + * """ + * if count_only and return_distance: + * raise ValueError("count_only and return_distance " # <<<<<<<<<<<<<< + * "cannot both be true") + * + */ + __pyx_tuple__21 = PyTuple_Pack(1, __pyx_kp_s_count_only_and_return_distance_c); if (unlikely(!__pyx_tuple__21)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__21); + __Pyx_GIVEREF(__pyx_tuple__21); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1424 + * + * if sort_results and not return_distance: + * raise ValueError("return_distance must be True " # <<<<<<<<<<<<<< + * "if sort_results is True") + * + */ + __pyx_tuple__22 = PyTuple_Pack(1, __pyx_kp_s_return_distance_must_be_True_if); if (unlikely(!__pyx_tuple__22)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__22); + __Pyx_GIVEREF(__pyx_tuple__22); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1437 + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * + */ + __pyx_tuple__23 = PyTuple_Pack(1, __pyx_kp_s_query_data_dimension_must_match); if (unlikely(!__pyx_tuple__23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__23); + __Pyx_GIVEREF(__pyx_tuple__23); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1446 + * r = np.asarray(r, dtype=DTYPE, order='C') + * r = np.atleast_1d(r) + * if r.shape == (1,): # <<<<<<<<<<<<<< + * r = r[0] + np.zeros(X.shape[:X.ndim - 1], dtype=DTYPE) + * else: + */ + __pyx_tuple__24 = PyTuple_Pack(1, __pyx_int_1); if (unlikely(!__pyx_tuple__24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__24); + __Pyx_GIVEREF(__pyx_tuple__24); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1450 + * else: + * if r.shape != X.shape[:X.ndim - 1]: + * raise ValueError("r must be broadcastable to X.shape") # <<<<<<<<<<<<<< + * + * rarr_np = r.reshape(-1) # store explicitly to keep in scope + */ + __pyx_tuple__25 = PyTuple_Pack(1, __pyx_kp_s_r_must_be_broadcastable_to_X_sha); if (unlikely(!__pyx_tuple__25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__25); + __Pyx_GIVEREF(__pyx_tuple__25); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1452 + * raise ValueError("r must be broadcastable to X.shape") + * + * rarr_np = r.reshape(-1) # store explicitly to keep in scope # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) + * + */ + __pyx_tuple__26 = PyTuple_Pack(1, __pyx_int_neg_1); if (unlikely(!__pyx_tuple__26)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__26); + __Pyx_GIVEREF(__pyx_tuple__26); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1587 + * + * if X.shape[X.ndim - 1] != n_features: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * Xarr_np = X.reshape((-1, n_features)) + */ + __pyx_tuple__27 = PyTuple_Pack(1, __pyx_kp_s_query_data_dimension_must_match); if (unlikely(!__pyx_tuple__27)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1587; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__27); + __Pyx_GIVEREF(__pyx_tuple__27); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1690 + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * + */ + __pyx_tuple__28 = PyTuple_Pack(1, __pyx_kp_s_query_data_dimension_must_match); if (unlikely(!__pyx_tuple__28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1690; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__28); + __Pyx_GIVEREF(__pyx_tuple__28); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1700 + * r = np.atleast_1d(r) + * if r.ndim != 1: + * raise ValueError("r must be a 1-dimensional array") # <<<<<<<<<<<<<< + * i_rsort = np.argsort(r) + * rarr_np = r[i_rsort] # needed to keep memory in scope + */ + __pyx_tuple__29 = PyTuple_Pack(1, __pyx_kp_s_r_must_be_a_1_dimensional_array); if (unlikely(!__pyx_tuple__29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__29); + __Pyx_GIVEREF(__pyx_tuple__29); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2048 + * for i in range(node_info.idx_start, node_info.idx_end): + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count too big: " # <<<<<<<<<<<<<< + * "this should never happen") + * indices[count] = idx_array[i] + */ + __pyx_tuple__30 = PyTuple_Pack(1, __pyx_kp_s_Fatal_count_too_big_this_should); if (unlikely(!__pyx_tuple__30)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2048; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__30); + __Pyx_GIVEREF(__pyx_tuple__30); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2068 + * if dist_pt <= reduced_r: + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count out of range. " # <<<<<<<<<<<<<< + * "This should never happen.") + * if count_only: + */ + __pyx_tuple__31 = PyTuple_Pack(1, __pyx_kp_s_Fatal_count_out_of_range_This_sh); if (unlikely(!__pyx_tuple__31)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2068; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__31); + __Pyx_GIVEREF(__pyx_tuple__31); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2500 + * + * # use initial size 0 to check corner case + * cdef NodeHeap heap = NodeHeap(0) # <<<<<<<<<<<<<< + * cdef NodeHeapData_t data + * cdef ITYPE_t i + */ + __pyx_tuple__32 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__32)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2500; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__32); + __Pyx_GIVEREF(__pyx_tuple__32); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_tuple__33 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__33)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__33); + __Pyx_GIVEREF(__pyx_tuple__33); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_tuple__34 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__34)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__34); + __Pyx_GIVEREF(__pyx_tuple__34); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_tuple__35 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__35)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__35); + __Pyx_GIVEREF(__pyx_tuple__35); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_tuple__36 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__36)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__36); + __Pyx_GIVEREF(__pyx_tuple__36); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_tuple__37 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__37)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__37); + __Pyx_GIVEREF(__pyx_tuple__37); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_tuple__38 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__38)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__38); + __Pyx_GIVEREF(__pyx_tuple__38); + + /* "View.MemoryView":127 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if itemsize <= 0: + */ + __pyx_tuple__39 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__39)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__39); + __Pyx_GIVEREF(__pyx_tuple__39); + + /* "View.MemoryView":130 + * + * if itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * if isinstance(format, unicode): + */ + __pyx_tuple__40 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__40)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__40); + __Pyx_GIVEREF(__pyx_tuple__40); + + /* "View.MemoryView":142 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__41 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__41)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__41); + __Pyx_GIVEREF(__pyx_tuple__41); + + /* "View.MemoryView":170 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_tuple__42 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__42)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__42); + __Pyx_GIVEREF(__pyx_tuple__42); + + /* "View.MemoryView":186 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_tuple__43 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__43)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__43); + __Pyx_GIVEREF(__pyx_tuple__43); + + /* "View.MemoryView":445 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_tuple__44 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__44)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__44); + __Pyx_GIVEREF(__pyx_tuple__44); + + /* "View.MemoryView":521 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_tuple__45 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__45)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__45); + __Pyx_GIVEREF(__pyx_tuple__45); + + /* "View.MemoryView":638 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_tuple__46 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__46)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__46); + __Pyx_GIVEREF(__pyx_tuple__46); + + /* "View.MemoryView":641 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_tuple__47 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__47)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__47); + __Pyx_GIVEREF(__pyx_tuple__47); + + /* "View.MemoryView":652 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_tuple__48 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__48)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__48); + __Pyx_GIVEREF(__pyx_tuple__48); + + /* "View.MemoryView":660 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__49 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__49)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__49); + __Pyx_GIVEREF(__pyx_tuple__49); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":497 + * + * + * def kernel_norm(h, d, kernel, return_log=False): # <<<<<<<<<<<<<< + * """Given a string specification of a kernel, compute the normalization. + * + */ + __pyx_tuple__55 = PyTuple_Pack(5, __pyx_n_s_h, __pyx_n_s_d, __pyx_n_s_kernel, __pyx_n_s_return_log, __pyx_n_s_result); if (unlikely(!__pyx_tuple__55)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__55); + __Pyx_GIVEREF(__pyx_tuple__55); + __pyx_codeobj__56 = (PyObject*)__Pyx_PyCode_New(4, 0, 5, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__55, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_n_s_kernel_norm, 497, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__56)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":985 + * # newObj function + * # this is a helper function for pickling + * def newObj(obj): # <<<<<<<<<<<<<< + * return obj.__new__(obj) + * + */ + __pyx_tuple__57 = PyTuple_Pack(1, __pyx_n_s_obj); if (unlikely(!__pyx_tuple__57)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__57); + __Pyx_GIVEREF(__pyx_tuple__57); + __pyx_codeobj__58 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__57, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_n_s_newObj, 985, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__58)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2468 + * # Python functions for benchmarking and testing C implementations + * + * def load_heap(DTYPE_t[:, ::1] X, ITYPE_t k): # <<<<<<<<<<<<<< + * """test fully loading the heap""" + * assert k <= X.shape[1] + */ + __pyx_tuple__59 = PyTuple_Pack(5, __pyx_n_s_X, __pyx_n_s_k, __pyx_n_s_heap, __pyx_n_s_i, __pyx_n_s_j); if (unlikely(!__pyx_tuple__59)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__59); + __Pyx_GIVEREF(__pyx_tuple__59); + __pyx_codeobj__60 = (PyObject*)__Pyx_PyCode_New(2, 0, 5, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__59, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_n_s_load_heap, 2468, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__60)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2479 + * + * + * def simultaneous_sort(DTYPE_t[:, ::1] distances, ITYPE_t[:, ::1] indices): # <<<<<<<<<<<<<< + * """In-place simultaneous sort the given row of the arrays + * + */ + __pyx_tuple__61 = PyTuple_Pack(3, __pyx_n_s_distances, __pyx_n_s_indices, __pyx_n_s_row); if (unlikely(!__pyx_tuple__61)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__61); + __Pyx_GIVEREF(__pyx_tuple__61); + __pyx_codeobj__62 = (PyObject*)__Pyx_PyCode_New(2, 0, 3, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__61, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_n_s_simultaneous_sort, 2479, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__62)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2494 + * + * + * def nodeheap_sort(DTYPE_t[::1] vals): # <<<<<<<<<<<<<< + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) + */ + __pyx_tuple__63 = PyTuple_Pack(7, __pyx_n_s_vals, __pyx_n_s_vals, __pyx_n_s_indices, __pyx_n_s_vals_sorted, __pyx_n_s_heap, __pyx_n_s_data, __pyx_n_s_i); if (unlikely(!__pyx_tuple__63)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__63); + __Pyx_GIVEREF(__pyx_tuple__63); + __pyx_codeobj__64 = (PyObject*)__Pyx_PyCode_New(1, 0, 7, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__63, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_n_s_nodeheap_sort, 2494, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__64)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":276 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_tuple__65 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__65)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__65); + __Pyx_GIVEREF(__pyx_tuple__65); + + /* "View.MemoryView":277 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_tuple__66 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__66)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__66); + __Pyx_GIVEREF(__pyx_tuple__66); + + /* "View.MemoryView":278 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__67 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__67)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__67); + __Pyx_GIVEREF(__pyx_tuple__67); + + /* "View.MemoryView":281 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_tuple__68 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__68)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__68); + __Pyx_GIVEREF(__pyx_tuple__68); + + /* "View.MemoryView":282 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__69 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__69)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__69); + __Pyx_GIVEREF(__pyx_tuple__69); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_float_1Eneg_8 = PyFloat_FromDouble(1E-8); if (unlikely(!__pyx_float_1Eneg_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_40 = PyInt_FromLong(40); if (unlikely(!__pyx_int_40)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_100 = PyInt_FromLong(100); if (unlikely(!__pyx_int_100)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC initball_tree(void); /*proto*/ +PyMODINIT_FUNC initball_tree(void) +#else +PyMODINIT_FUNC PyInit_ball_tree(void); /*proto*/ +PyMODINIT_FUNC PyInit_ball_tree(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_ball_tree(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("ball_tree"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__neighbors__ball_tree) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.neighbors.ball_tree")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.neighbors.ball_tree", __pyx_m) < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + generic = Py_None; Py_INCREF(Py_None); + strided = Py_None; Py_INCREF(Py_None); + indirect = Py_None; Py_INCREF(Py_None); + contiguous = Py_None; Py_INCREF(Py_None); + indirect_contiguous = Py_None; Py_INCREF(Py_None); + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_NeighborsHeap = &__pyx_vtable_7sklearn_9neighbors_9ball_tree_NeighborsHeap; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_NeighborsHeap.largest = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_largest; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_NeighborsHeap.push = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, int __pyx_skip_dispatch))__pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap_push; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_NeighborsHeap._sort = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *))__pyx_f_7sklearn_9neighbors_9ball_tree_13NeighborsHeap__sort; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_9ball_tree_NeighborsHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_9neighbors_9ball_tree_NeighborsHeap.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_9ball_tree_NeighborsHeap.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_NeighborsHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "NeighborsHeap", (PyObject *)&__pyx_type_7sklearn_9neighbors_9ball_tree_NeighborsHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_9ball_tree_NeighborsHeap = &__pyx_type_7sklearn_9neighbors_9ball_tree_NeighborsHeap; + __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_NodeHeap = &__pyx_vtable_7sklearn_9neighbors_9ball_tree_NodeHeap; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_NodeHeap.resize = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_9ball_tree_8NodeHeap_resize; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_NodeHeap.push = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *, struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t))__pyx_f_7sklearn_9neighbors_9ball_tree_8NodeHeap_push; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_NodeHeap.peek = (struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *))__pyx_f_7sklearn_9neighbors_9ball_tree_8NodeHeap_peek; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_NodeHeap.pop = (struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *))__pyx_f_7sklearn_9neighbors_9ball_tree_8NodeHeap_pop; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_NodeHeap.clear = (void (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *))__pyx_f_7sklearn_9neighbors_9ball_tree_8NodeHeap_clear; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_9ball_tree_NodeHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_9neighbors_9ball_tree_NodeHeap.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_9ball_tree_NodeHeap.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_NodeHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "NodeHeap", (PyObject *)&__pyx_type_7sklearn_9neighbors_9ball_tree_NodeHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_9ball_tree_NodeHeap = &__pyx_type_7sklearn_9neighbors_9ball_tree_NodeHeap; + __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BinaryTree = &__pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_dist; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree.rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree_rdist; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree._recursive_build = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__recursive_build; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree._query_single_depthfirst = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__query_single_depthfirst; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree._query_single_breadthfirst = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__query_single_breadthfirst; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree._query_dual_depthfirst = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __Pyx_memviewslice, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__query_dual_depthfirst; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree._query_dual_breadthfirst = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NeighborsHeap *, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__query_dual_breadthfirst; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree._query_radius_single = (__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, int, int))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__query_radius_single; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree._kde_single_breadthfirst = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_NodeHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__kde_single_breadthfirst; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree._kde_single_depthfirst = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, enum __pyx_t_7sklearn_9neighbors_9ball_tree_KernelType, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__kde_single_depthfirst; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree._two_point_single = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__two_point_single; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BinaryTree._two_point_dual = (int (*)(struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_9ball_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_9ball_tree_10BinaryTree__two_point_dual; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_9ball_tree_BinaryTree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_9neighbors_9ball_tree_BinaryTree.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_9ball_tree_BinaryTree.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BinaryTree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "BinaryTree", (PyObject *)&__pyx_type_7sklearn_9neighbors_9ball_tree_BinaryTree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree = &__pyx_type_7sklearn_9neighbors_9ball_tree_BinaryTree; + __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BallTree = &__pyx_vtable_7sklearn_9neighbors_9ball_tree_BallTree; + __pyx_vtable_7sklearn_9neighbors_9ball_tree_BallTree.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BinaryTree; + __pyx_type_7sklearn_9neighbors_9ball_tree_BallTree.tp_base = __pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_9ball_tree_BallTree) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_9neighbors_9ball_tree_BallTree.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_9ball_tree_BallTree.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_9ball_tree_BallTree) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "BallTree", (PyObject *)&__pyx_type_7sklearn_9neighbors_9ball_tree_BallTree) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_9ball_tree_BallTree = &__pyx_type_7sklearn_9neighbors_9ball_tree_BallTree; + if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_array.tp_print = 0; + __pyx_array_type = &__pyx_type___pyx_array; + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_MemviewEnum.tp_print = 0; + __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; + __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; + __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; + __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; + __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; + __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; + __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; + __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; + __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; + if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_memoryview.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryview_type = &__pyx_type___pyx_memoryview; + __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; + __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; + __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; + __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; + __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_memoryviewslice.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[5]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric = __Pyx_ImportType("sklearn.neighbors.dist_metrics", "DistanceMetric", sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric), 1); if (unlikely(!__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric)) {__pyx_filename = __pyx_f[6]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__Pyx_GetVtable(__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric)) {__pyx_filename = __pyx_f[6]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + __pyx_t_1 = __Pyx_ImportModule("sklearn.utils.lgamma"); if (!__pyx_t_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_ImportFunction(__pyx_t_1, "lgamma", (void (**)(void))&__pyx_f_7sklearn_5utils_6lgamma_lgamma, "double (double)") < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /*--- Execution code ---*/ + + /* "sklearn/neighbors/ball_tree.pyx":9 + * # Licence: BSD 3 clause + * + * __all__ = ['BallTree'] # <<<<<<<<<<<<<< + * + * DOC_DICT = {'BinaryTree': 'BallTree', 'binary_tree': 'ball_tree'} + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_BallTree); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_BallTree); + __Pyx_GIVEREF(__pyx_n_s_BallTree); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_all, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/neighbors/ball_tree.pyx":11 + * __all__ = ['BallTree'] + * + * DOC_DICT = {'BinaryTree': 'BallTree', 'binary_tree': 'ball_tree'} # <<<<<<<<<<<<<< + * + * VALID_METRICS = ['EuclideanDistance', 'SEuclideanDistance', + */ + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_BinaryTree, __pyx_n_s_BallTree) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_binary_tree, __pyx_n_s_ball_tree) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_DOC_DICT, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/neighbors/ball_tree.pyx":13 + * DOC_DICT = {'BinaryTree': 'BallTree', 'binary_tree': 'ball_tree'} + * + * VALID_METRICS = ['EuclideanDistance', 'SEuclideanDistance', # <<<<<<<<<<<<<< + * 'ManhattanDistance', 'ChebyshevDistance', + * 'MinkowskiDistance', 'WMinkowskiDistance', + */ + __pyx_t_2 = PyList_New(20); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_EuclideanDistance); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_EuclideanDistance); + __Pyx_GIVEREF(__pyx_n_s_EuclideanDistance); + __Pyx_INCREF(__pyx_n_s_SEuclideanDistance); + PyList_SET_ITEM(__pyx_t_2, 1, __pyx_n_s_SEuclideanDistance); + __Pyx_GIVEREF(__pyx_n_s_SEuclideanDistance); + __Pyx_INCREF(__pyx_n_s_ManhattanDistance); + PyList_SET_ITEM(__pyx_t_2, 2, __pyx_n_s_ManhattanDistance); + __Pyx_GIVEREF(__pyx_n_s_ManhattanDistance); + __Pyx_INCREF(__pyx_n_s_ChebyshevDistance); + PyList_SET_ITEM(__pyx_t_2, 3, __pyx_n_s_ChebyshevDistance); + __Pyx_GIVEREF(__pyx_n_s_ChebyshevDistance); + __Pyx_INCREF(__pyx_n_s_MinkowskiDistance); + PyList_SET_ITEM(__pyx_t_2, 4, __pyx_n_s_MinkowskiDistance); + __Pyx_GIVEREF(__pyx_n_s_MinkowskiDistance); + __Pyx_INCREF(__pyx_n_s_WMinkowskiDistance); + PyList_SET_ITEM(__pyx_t_2, 5, __pyx_n_s_WMinkowskiDistance); + __Pyx_GIVEREF(__pyx_n_s_WMinkowskiDistance); + __Pyx_INCREF(__pyx_n_s_MahalanobisDistance); + PyList_SET_ITEM(__pyx_t_2, 6, __pyx_n_s_MahalanobisDistance); + __Pyx_GIVEREF(__pyx_n_s_MahalanobisDistance); + __Pyx_INCREF(__pyx_n_s_HammingDistance); + PyList_SET_ITEM(__pyx_t_2, 7, __pyx_n_s_HammingDistance); + __Pyx_GIVEREF(__pyx_n_s_HammingDistance); + __Pyx_INCREF(__pyx_n_s_CanberraDistance); + PyList_SET_ITEM(__pyx_t_2, 8, __pyx_n_s_CanberraDistance); + __Pyx_GIVEREF(__pyx_n_s_CanberraDistance); + __Pyx_INCREF(__pyx_n_s_BrayCurtisDistance); + PyList_SET_ITEM(__pyx_t_2, 9, __pyx_n_s_BrayCurtisDistance); + __Pyx_GIVEREF(__pyx_n_s_BrayCurtisDistance); + __Pyx_INCREF(__pyx_n_s_JaccardDistance); + PyList_SET_ITEM(__pyx_t_2, 10, __pyx_n_s_JaccardDistance); + __Pyx_GIVEREF(__pyx_n_s_JaccardDistance); + __Pyx_INCREF(__pyx_n_s_MatchingDistance); + PyList_SET_ITEM(__pyx_t_2, 11, __pyx_n_s_MatchingDistance); + __Pyx_GIVEREF(__pyx_n_s_MatchingDistance); + __Pyx_INCREF(__pyx_n_s_DiceDistance); + PyList_SET_ITEM(__pyx_t_2, 12, __pyx_n_s_DiceDistance); + __Pyx_GIVEREF(__pyx_n_s_DiceDistance); + __Pyx_INCREF(__pyx_n_s_KulsinskiDistance); + PyList_SET_ITEM(__pyx_t_2, 13, __pyx_n_s_KulsinskiDistance); + __Pyx_GIVEREF(__pyx_n_s_KulsinskiDistance); + __Pyx_INCREF(__pyx_n_s_RogersTanimotoDistance); + PyList_SET_ITEM(__pyx_t_2, 14, __pyx_n_s_RogersTanimotoDistance); + __Pyx_GIVEREF(__pyx_n_s_RogersTanimotoDistance); + __Pyx_INCREF(__pyx_n_s_RussellRaoDistance); + PyList_SET_ITEM(__pyx_t_2, 15, __pyx_n_s_RussellRaoDistance); + __Pyx_GIVEREF(__pyx_n_s_RussellRaoDistance); + __Pyx_INCREF(__pyx_n_s_SokalMichenerDistance); + PyList_SET_ITEM(__pyx_t_2, 16, __pyx_n_s_SokalMichenerDistance); + __Pyx_GIVEREF(__pyx_n_s_SokalMichenerDistance); + __Pyx_INCREF(__pyx_n_s_SokalSneathDistance); + PyList_SET_ITEM(__pyx_t_2, 17, __pyx_n_s_SokalSneathDistance); + __Pyx_GIVEREF(__pyx_n_s_SokalSneathDistance); + __Pyx_INCREF(__pyx_n_s_PyFuncDistance); + PyList_SET_ITEM(__pyx_t_2, 18, __pyx_n_s_PyFuncDistance); + __Pyx_GIVEREF(__pyx_n_s_PyFuncDistance); + __Pyx_INCREF(__pyx_n_s_HaversineDistance); + PyList_SET_ITEM(__pyx_t_2, 19, __pyx_n_s_HaversineDistance); + __Pyx_GIVEREF(__pyx_n_s_HaversineDistance); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_VALID_METRICS, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":149 + * from sklearn.utils.lgamma cimport lgamma + * + * import numpy as np # <<<<<<<<<<<<<< + * import warnings + * from ..utils import check_array + */ + __pyx_t_2 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":150 + * + * import numpy as np + * import warnings # <<<<<<<<<<<<<< + * from ..utils import check_array + * + */ + __pyx_t_2 = __Pyx_Import(__pyx_n_s_warnings, 0, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_warnings, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":151 + * import numpy as np + * import warnings + * from ..utils import check_array # <<<<<<<<<<<<<< + * + * from typedefs cimport DTYPE_t, ITYPE_t, DITYPE_t + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_check_array); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_check_array); + __Pyx_GIVEREF(__pyx_n_s_check_array); + __pyx_t_3 = __Pyx_Import(__pyx_n_s_utils, __pyx_t_2, 2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_check_array); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_check_array, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":154 + * + * from typedefs cimport DTYPE_t, ITYPE_t, DITYPE_t + * from typedefs import DTYPE, ITYPE # <<<<<<<<<<<<<< + * + * from dist_metrics cimport (DistanceMetric, euclidean_dist, euclidean_rdist, + */ + __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_n_s_DTYPE); + PyList_SET_ITEM(__pyx_t_3, 0, __pyx_n_s_DTYPE); + __Pyx_GIVEREF(__pyx_n_s_DTYPE); + __Pyx_INCREF(__pyx_n_s_ITYPE); + PyList_SET_ITEM(__pyx_t_3, 1, __pyx_n_s_ITYPE); + __Pyx_GIVEREF(__pyx_n_s_ITYPE); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_typedefs, __pyx_t_3, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_ITYPE, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":160 + * + * # some handy constants + * cdef DTYPE_t INF = np.inf # <<<<<<<<<<<<<< + * cdef DTYPE_t NEG_INF = -np.inf + * cdef DTYPE_t PI = np.pi + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_inf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_7sklearn_9neighbors_9ball_tree_INF = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":161 + * # some handy constants + * cdef DTYPE_t INF = np.inf + * cdef DTYPE_t NEG_INF = -np.inf # <<<<<<<<<<<<<< + * cdef DTYPE_t PI = np.pi + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Negative(__pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_7sklearn_9neighbors_9ball_tree_NEG_INF = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":162 + * cdef DTYPE_t INF = np.inf + * cdef DTYPE_t NEG_INF = -np.inf + * cdef DTYPE_t PI = np.pi # <<<<<<<<<<<<<< + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) + * cdef DTYPE_t LOG_PI = log(PI) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_pi); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_7sklearn_9neighbors_9ball_tree_PI = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":163 + * cdef DTYPE_t NEG_INF = -np.inf + * cdef DTYPE_t PI = np.pi + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) # <<<<<<<<<<<<<< + * cdef DTYPE_t LOG_PI = log(PI) + * cdef DTYPE_t LOG_2PI = log(2 * PI) + */ + __pyx_v_7sklearn_9neighbors_9ball_tree_ROOT_2PI = sqrt((2.0 * __pyx_v_7sklearn_9neighbors_9ball_tree_PI)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":164 + * cdef DTYPE_t PI = np.pi + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) + * cdef DTYPE_t LOG_PI = log(PI) # <<<<<<<<<<<<<< + * cdef DTYPE_t LOG_2PI = log(2 * PI) + * + */ + __pyx_v_7sklearn_9neighbors_9ball_tree_LOG_PI = log(__pyx_v_7sklearn_9neighbors_9ball_tree_PI); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":165 + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) + * cdef DTYPE_t LOG_PI = log(PI) + * cdef DTYPE_t LOG_2PI = log(2 * PI) # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_7sklearn_9neighbors_9ball_tree_LOG_2PI = log((2.0 * __pyx_v_7sklearn_9neighbors_9ball_tree_PI)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":180 + * # NodeHeapData = np.asarray((&nhd_tmp)).dtype + * cdef NodeHeapData_t nhd_tmp + * offsets = [&(nhd_tmp.val) - &nhd_tmp, # <<<<<<<<<<<<<< + * &(nhd_tmp.i1) - &nhd_tmp, + * &(nhd_tmp.i2) - &nhd_tmp] + */ + __pyx_t_2 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nhd_tmp.val)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nhd_tmp)))); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":181 + * cdef NodeHeapData_t nhd_tmp + * offsets = [&(nhd_tmp.val) - &nhd_tmp, + * &(nhd_tmp.i1) - &nhd_tmp, # <<<<<<<<<<<<<< + * &(nhd_tmp.i2) - &nhd_tmp] + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], + */ + __pyx_t_3 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nhd_tmp.i1)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nhd_tmp)))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":182 + * offsets = [&(nhd_tmp.val) - &nhd_tmp, + * &(nhd_tmp.i1) - &nhd_tmp, + * &(nhd_tmp.i2) - &nhd_tmp] # <<<<<<<<<<<<<< + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], + * 'formats': [DTYPE, ITYPE, ITYPE], + */ + __pyx_t_5 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nhd_tmp.i2)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nhd_tmp)))); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":180 + * # NodeHeapData = np.asarray((&nhd_tmp)).dtype + * cdef NodeHeapData_t nhd_tmp + * offsets = [&(nhd_tmp.val) - &nhd_tmp, # <<<<<<<<<<<<<< + * &(nhd_tmp.i1) - &nhd_tmp, + * &(nhd_tmp.i2) - &nhd_tmp] + */ + __pyx_t_6 = PyList_New(3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyList_SET_ITEM(__pyx_t_6, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyList_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyList_SET_ITEM(__pyx_t_6, 2, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_offsets, __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":183 + * &(nhd_tmp.i1) - &nhd_tmp, + * &(nhd_tmp.i2) - &nhd_tmp] + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], # <<<<<<<<<<<<<< + * 'formats': [DTYPE, ITYPE, ITYPE], + * 'offsets': offsets, + */ + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = PyList_New(3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_n_s_val); + PyList_SET_ITEM(__pyx_t_5, 0, __pyx_n_s_val); + __Pyx_GIVEREF(__pyx_n_s_val); + __Pyx_INCREF(__pyx_n_s_i1); + PyList_SET_ITEM(__pyx_t_5, 1, __pyx_n_s_i1); + __Pyx_GIVEREF(__pyx_n_s_i1); + __Pyx_INCREF(__pyx_n_s_i2); + PyList_SET_ITEM(__pyx_t_5, 2, __pyx_n_s_i2); + __Pyx_GIVEREF(__pyx_n_s_i2); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_names, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":184 + * &(nhd_tmp.i2) - &nhd_tmp] + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], + * 'formats': [DTYPE, ITYPE, ITYPE], # <<<<<<<<<<<<<< + * 'offsets': offsets, + * 'itemsize': sizeof(NodeHeapData_t)}) + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = PyList_New(3); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyList_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyList_SET_ITEM(__pyx_t_7, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyList_SET_ITEM(__pyx_t_7, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_formats, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":185 + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], + * 'formats': [DTYPE, ITYPE, ITYPE], + * 'offsets': offsets, # <<<<<<<<<<<<<< + * 'itemsize': sizeof(NodeHeapData_t)}) + * + */ + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_offsets); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_offsets, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":186 + * 'formats': [DTYPE, ITYPE, ITYPE], + * 'offsets': offsets, + * 'itemsize': sizeof(NodeHeapData_t)}) # <<<<<<<<<<<<<< + * + * cdef struct NodeData_t: + */ + __pyx_t_7 = __Pyx_PyInt_FromSize_t((sizeof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_itemsize, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":183 + * &(nhd_tmp.i1) - &nhd_tmp, + * &(nhd_tmp.i2) - &nhd_tmp] + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], # <<<<<<<<<<<<<< + * 'formats': [DTYPE, ITYPE, ITYPE], + * 'offsets': offsets, + */ + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_5numpy_dtype)), __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_NodeHeapData, __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":200 + * # NodeData = np.asarray((&nd_tmp)).dtype + * cdef NodeData_t nd_tmp + * offsets = [&(nd_tmp.idx_start) - &nd_tmp, # <<<<<<<<<<<<<< + * &(nd_tmp.idx_end) - &nd_tmp, + * &(nd_tmp.is_leaf) - &nd_tmp, + */ + __pyx_t_6 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nd_tmp.idx_start)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nd_tmp)))); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":201 + * cdef NodeData_t nd_tmp + * offsets = [&(nd_tmp.idx_start) - &nd_tmp, + * &(nd_tmp.idx_end) - &nd_tmp, # <<<<<<<<<<<<<< + * &(nd_tmp.is_leaf) - &nd_tmp, + * &(nd_tmp.radius) - &nd_tmp] + */ + __pyx_t_7 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nd_tmp.idx_end)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nd_tmp)))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":202 + * offsets = [&(nd_tmp.idx_start) - &nd_tmp, + * &(nd_tmp.idx_end) - &nd_tmp, + * &(nd_tmp.is_leaf) - &nd_tmp, # <<<<<<<<<<<<<< + * &(nd_tmp.radius) - &nd_tmp] + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], + */ + __pyx_t_2 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nd_tmp.is_leaf)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nd_tmp)))); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":203 + * &(nd_tmp.idx_end) - &nd_tmp, + * &(nd_tmp.is_leaf) - &nd_tmp, + * &(nd_tmp.radius) - &nd_tmp] # <<<<<<<<<<<<<< + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], + */ + __pyx_t_3 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nd_tmp.radius)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_9ball_tree_nd_tmp)))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":200 + * # NodeData = np.asarray((&nd_tmp)).dtype + * cdef NodeData_t nd_tmp + * offsets = [&(nd_tmp.idx_start) - &nd_tmp, # <<<<<<<<<<<<<< + * &(nd_tmp.idx_end) - &nd_tmp, + * &(nd_tmp.is_leaf) - &nd_tmp, + */ + __pyx_t_5 = PyList_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyList_SET_ITEM(__pyx_t_5, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyList_SET_ITEM(__pyx_t_5, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_offsets, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":204 + * &(nd_tmp.is_leaf) - &nd_tmp, + * &(nd_tmp.radius) - &nd_tmp] + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], # <<<<<<<<<<<<<< + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], + * 'offsets': offsets, + */ + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyList_New(4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_n_s_idx_start); + PyList_SET_ITEM(__pyx_t_3, 0, __pyx_n_s_idx_start); + __Pyx_GIVEREF(__pyx_n_s_idx_start); + __Pyx_INCREF(__pyx_n_s_idx_end); + PyList_SET_ITEM(__pyx_t_3, 1, __pyx_n_s_idx_end); + __Pyx_GIVEREF(__pyx_n_s_idx_end); + __Pyx_INCREF(__pyx_n_s_is_leaf); + PyList_SET_ITEM(__pyx_t_3, 2, __pyx_n_s_is_leaf); + __Pyx_GIVEREF(__pyx_n_s_is_leaf); + __Pyx_INCREF(__pyx_n_s_radius); + PyList_SET_ITEM(__pyx_t_3, 3, __pyx_n_s_radius); + __Pyx_GIVEREF(__pyx_n_s_radius); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_names, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":205 + * &(nd_tmp.radius) - &nd_tmp] + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], # <<<<<<<<<<<<<< + * 'offsets': offsets, + * 'itemsize': sizeof(NodeData_t)}) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = PyList_New(4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_8, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyList_SET_ITEM(__pyx_t_8, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyList_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyList_SET_ITEM(__pyx_t_8, 3, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_3 = 0; + __pyx_t_2 = 0; + __pyx_t_7 = 0; + __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_formats, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":206 + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], + * 'offsets': offsets, # <<<<<<<<<<<<<< + * 'itemsize': sizeof(NodeData_t)}) + * + */ + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_offsets); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_offsets, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":207 + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], + * 'offsets': offsets, + * 'itemsize': sizeof(NodeData_t)}) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __Pyx_PyInt_FromSize_t((sizeof(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t))); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_itemsize, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":204 + * &(nd_tmp.is_leaf) - &nd_tmp, + * &(nd_tmp.radius) - &nd_tmp] + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], # <<<<<<<<<<<<<< + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], + * 'offsets': offsets, + */ + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_5numpy_dtype)), __pyx_t_8, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_NodeData, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":255 + * # the DOC_DICT variable defined in the pyx files. + * CLASS_DOC = \ + * """{BinaryTree} for fast generalized N-point problems # <<<<<<<<<<<<<< + * + * {BinaryTree}(X, leaf_size=40, metric='minkowski', **kwargs) + */ + if (PyDict_SetItem(__pyx_d, __pyx_n_s_CLASS_DOC, __pyx_kp_s_BinaryTree_for_fast_generalized) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":497 + * + * + * def kernel_norm(h, d, kernel, return_log=False): # <<<<<<<<<<<<<< + * """Given a string specification of a kernel, compute the normalization. + * + */ + __pyx_t_5 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_9ball_tree_1kernel_norm, NULL, __pyx_n_s_sklearn_neighbors_ball_tree); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_kernel_norm, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":985 + * # newObj function + * # this is a helper function for pickling + * def newObj(obj): # <<<<<<<<<<<<<< + * return obj.__new__(obj) + * + */ + __pyx_t_5 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_9ball_tree_3newObj, NULL, __pyx_n_s_sklearn_neighbors_ball_tree); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_newObj, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":991 + * ###################################################################### + * # define the reverse mapping of VALID_METRICS + * from dist_metrics import get_valid_metric_ids # <<<<<<<<<<<<<< + * VALID_METRIC_IDS = get_valid_metric_ids(VALID_METRICS) + * + */ + __pyx_t_5 = PyList_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 991; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_n_s_get_valid_metric_ids); + PyList_SET_ITEM(__pyx_t_5, 0, __pyx_n_s_get_valid_metric_ids); + __Pyx_GIVEREF(__pyx_n_s_get_valid_metric_ids); + __pyx_t_8 = __Pyx_Import(__pyx_n_s_dist_metrics, __pyx_t_5, -1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 991; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_ImportFrom(__pyx_t_8, __pyx_n_s_get_valid_metric_ids); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 991; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_get_valid_metric_ids, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 991; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":992 + * # define the reverse mapping of VALID_METRICS + * from dist_metrics import get_valid_metric_ids + * VALID_METRIC_IDS = get_valid_metric_ids(VALID_METRICS) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_get_valid_metric_ids); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_VALID_METRICS); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_VALID_METRIC_IDS, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1022 + * cdef int n_calls + * + * valid_metrics = VALID_METRIC_IDS # <<<<<<<<<<<<<< + * + * # Use cinit to initialize all arrays to empty: this will prevent memory + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_VALID_METRIC_IDS); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem((PyObject *)__pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree->tp_dict, __pyx_n_s_valid_metrics, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + PyType_Modified(__pyx_ptype_7sklearn_9neighbors_9ball_tree_BinaryTree); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2468 + * # Python functions for benchmarking and testing C implementations + * + * def load_heap(DTYPE_t[:, ::1] X, ITYPE_t k): # <<<<<<<<<<<<<< + * """test fully loading the heap""" + * assert k <= X.shape[1] + */ + __pyx_t_5 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_9ball_tree_5load_heap, NULL, __pyx_n_s_sklearn_neighbors_ball_tree); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_load_heap, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2479 + * + * + * def simultaneous_sort(DTYPE_t[:, ::1] distances, ITYPE_t[:, ::1] indices): # <<<<<<<<<<<<<< + * """In-place simultaneous sort the given row of the arrays + * + */ + __pyx_t_5 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_9ball_tree_7simultaneous_sort, NULL, __pyx_n_s_sklearn_neighbors_ball_tree); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_simultaneous_sort, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2494 + * + * + * def nodeheap_sort(DTYPE_t[::1] vals): # <<<<<<<<<<<<<< + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) + */ + __pyx_t_5 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_9ball_tree_9nodeheap_sort, NULL, __pyx_n_s_sklearn_neighbors_ball_tree); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_nodeheap_sort, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "sklearn/neighbors/ball_tree.pyx":29 + * # Inherit BallTree from BinaryTree + * cdef class BallTree(BinaryTree): + * __doc__ = CLASS_DOC.format(**DOC_DICT) # <<<<<<<<<<<<<< + * pass + * + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_CLASS_DOC); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_DOC_DICT); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (unlikely(__pyx_t_8 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "argument after ** must be a mapping, not NoneType"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (likely(PyDict_Check(__pyx_t_8))) { + __pyx_t_5 = __pyx_t_8; + __Pyx_INCREF(__pyx_t_5); + } else { + __pyx_t_5 = PyObject_CallFunctionObjArgs((PyObject*)&PyDict_Type, __pyx_t_8, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_empty_tuple, __pyx_t_5); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem((PyObject *)__pyx_ptype_7sklearn_9neighbors_9ball_tree_BallTree->tp_dict, __pyx_n_s_doc, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + PyType_Modified(__pyx_ptype_7sklearn_9neighbors_9ball_tree_BallTree); + + /* "sklearn/neighbors/ball_tree.pyx":1 + * #!python # <<<<<<<<<<<<<< + * #cython: boundscheck=False + * #cython: wraparound=False + */ + __pyx_t_8 = PyDict_New(); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_t_8, __pyx_kp_u_BinaryTree_query_line_1228, __pyx_kp_u_query_X_k_1_return_distance_Tru) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_8, __pyx_kp_u_BinaryTree_query_radius_line_135, __pyx_kp_u_query_radius_self_X_r_count_onl) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_8, __pyx_kp_u_BinaryTree_kernel_density_line_1, __pyx_kp_u_kernel_density_self_X_h_kernel) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_8, __pyx_kp_u_BinaryTree_two_point_correlation, __pyx_kp_u_Compute_the_two_point_correlatio) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "View.MemoryView":203 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * def __dealloc__(array self): + */ + __pyx_t_8 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + PyType_Modified(__pyx_array_type); + + /* "View.MemoryView":276 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_t_8 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__65, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XGOTREF(generic); + __Pyx_DECREF_SET(generic, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + + /* "View.MemoryView":277 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_t_8 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__66, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XGOTREF(strided); + __Pyx_DECREF_SET(strided, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + + /* "View.MemoryView":278 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__67, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XGOTREF(indirect); + __Pyx_DECREF_SET(indirect, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + + /* "View.MemoryView":281 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_t_8 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__68, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XGOTREF(contiguous); + __Pyx_DECREF_SET(contiguous, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + + /* "View.MemoryView":282 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__69, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XGOTREF(indirect_contiguous); + __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + + /* "View.MemoryView":496 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + PyType_Modified(__pyx_memoryview_type); + + /* "View.MemoryView":953 + * return self.from_object + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + PyType_Modified(__pyx_memoryviewslice_type); + + /* "BufferFormatFromTypeInfo":1417 + * + * @cname('__pyx_format_from_typeinfo') + * cdef bytes format_from_typeinfo(__Pyx_TypeInfo *type): # <<<<<<<<<<<<<< + * cdef __Pyx_StructField *field + * cdef __pyx_typeinfo_string fmt + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.neighbors.ball_tree", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.neighbors.ball_tree"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; /* Consume from buffer string */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; /* not a 'break' in the loop */ + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case '\r': + case '\n': + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; + } + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (!buf) { + PyErr_SetString(PyExc_ValueError, + "buf is NULL."); + goto fail; + } else if (memviewslice->memview || memviewslice->data) { + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); + } + retval = 0; + goto no_fail; +fail: + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} +static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { + va_list vargs; + char msg[200]; + va_start(vargs, fmt); +#ifdef HAVE_STDARG_PROTOTYPES + va_start(vargs, fmt); +#else + va_start(vargs); +#endif + vsnprintf(msg, 200, fmt, vargs); + Py_FatalError(msg); + va_end(vargs); +} +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) +{ + int first_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview || (PyObject *) memview == Py_None) + return; /* allow uninitialized memoryview assignment */ + if (__pyx_get_slice_count(memview) < 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + first_time = __pyx_add_acquisition_count(memview) == 0; + if (first_time) { + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); + } + } +} +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, + int have_gil, int lineno) { + int last_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview ) { + return; + } else if ((PyObject *) memview == Py_None) { + memslice->memview = NULL; + return; + } + if (__pyx_get_slice_count(memview) <= 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; + if (last_time) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } + } else { + memslice->memview = NULL; + } +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; +#endif + result = (*call)(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + Py_LeaveRecursiveCall(); +#endif + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { + #endif +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); + } +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + #if CYTHON_PEP393_ENABLED + if (unlikely(PyUnicode_READY(s1) < 0) || unlikely(PyUnicode_READY(s2) < 0)) + return -1; + #endif + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, length * kind); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static CYTHON_INLINE int __Pyx_CheckKeywordStrings( + PyObject *kwdict, + const char* function_name, + int kw_allowed) +{ + PyObject* key = 0; + Py_ssize_t pos = 0; +#if CPYTHON_COMPILING_IN_PYPY + if (!kw_allowed && PyDict_Next(kwdict, &pos, &key, 0)) + goto invalid_keyword; + return 1; +#else + while (PyDict_Next(kwdict, &pos, &key, 0)) { + #if PY_MAJOR_VERSION < 3 + if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) + #endif + if (unlikely(!PyUnicode_Check(key))) + goto invalid_keyword_type; + } + if ((!kw_allowed) && unlikely(key)) + goto invalid_keyword; + return 1; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + return 0; +#endif +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif + return 0; +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, + int full_traceback) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + if (full_traceback) { + Py_XINCREF(old_exc); + Py_XINCREF(old_val); + Py_XINCREF(old_tb); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + PyErr_PrintEx(1); + } + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); } - #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) - #else - if (!PyType_Check(type)) - #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { +#if CYTHON_COMPILING_IN_CPYTHON + PyMappingMethods* mp; +#if PY_MAJOR_VERSION < 3 + PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; + if (likely(ms && ms->sq_slice)) { + if (!has_cstart) { + if (_py_start && (*_py_start != Py_None)) { + cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); + if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstart = 0; } - /* Normalize to raise , */ - Py_DECREF(value); - value = type; - #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); + if (!has_cstop) { + if (_py_stop && (*_py_stop != Py_None)) { + cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); + if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstop = PY_SSIZE_T_MAX; + } + if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { + Py_ssize_t l = ms->sq_length(obj); + if (likely(l >= 0)) { + if (cstop < 0) { + cstop += l; + if (cstop < 0) cstop = 0; + } + if (cstart < 0) { + cstart += l; + if (cstart < 0) cstart = 0; + } + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + goto bad; } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; + } + return ms->sq_slice(obj, cstart, cstop); + } +#endif + mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_subscript)) +#endif + { + PyObject* result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyInt_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; } - #else - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyInt_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_COMPILING_IN_CPYTHON + result = mp->mp_subscript(obj, py_slice); +#else + result = PyObject_GetItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } + PyErr_Format(PyExc_TypeError, + "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); +bad: + return NULL; +} + +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { + int r; + if (!j) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { + PyObject* old = PyList_GET_ITEM(o, n); + Py_INCREF(v); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 1; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return -1; + } } + return m->sq_ass_item(o, i, v); + } + } +#else +#if CYTHON_COMPILING_IN_PYPY + if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) { +#else + if (is_list || PySequence_Check(o)) { +#endif + return PySequence_SetItem(o, i, v); + } +#endif + return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } + else { + if (likely(PyObject_TypeCheck(obj, type))) return 1; + } + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); + return 0; +} - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +#if CYTHON_COMPILING_IN_CPYTHON +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) +#else + if (likely(PyString_Check(n))) +#endif + return __Pyx_PyObject_GetAttrStr(o, n); +#endif + return PyObject_GetAttr(o, n); +} + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + length = strlen(cstring); + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +#else + PyErr_GetExcInfo(type, value, tb); +#endif +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(type, value, tb); +#endif +} + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } + #endif + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; +#else + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); +#endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} + +#if !CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values) { + return PyObject_CallMethodObjArgs(sep, __pyx_n_s_join, values, NULL); +} +#endif + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +static void* __Pyx_GetVtable(PyObject *dict) { + void* ptr; + PyObject *ob = PyObject_GetItem(dict, __pyx_n_s_pyx_vtable); + if (!ob) + goto bad; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + ptr = PyCapsule_GetPointer(ob, 0); +#else + ptr = PyCObject_AsVoidPtr(ob); +#endif + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif + } + return value; +} + +static int +__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) +{ + int i; + if (!a || !b) + return 0; + if (a == b) + return 1; + if (a->size != b->size || a->typegroup != b->typegroup || + a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { + if (a->typegroup == 'H' || b->typegroup == 'H') { + return a->size == b->size; + } else { + return 0; + } + } + if (a->ndim) { + for (i = 0; i < a->ndim; i++) + if (a->arraysize[i] != b->arraysize[i]) + return 0; + } + if (a->typegroup == 'S') { + if (a->flags != b->flags) + return 0; + if (a->fields || b->fields) { + if (!(a->fields && b->fields)) + return 0; + for (i = 0; a->fields[i].type && b->fields[i].type; i++) { + __Pyx_StructField *field_a = a->fields + i; + __Pyx_StructField *field_b = b->fields + i; + if (field_a->offset != field_b->offset || + !__pyx_typeinfo_cmp(field_a->type, field_b->type)) + return 0; + } + return !a->fields[i].type && !b->fields[i].type; + } + } + return 1; +} + +static int +__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) +{ + if (buf->shape[dim] <= 1) + return 1; + if (buf->strides) { + if (spec & __Pyx_MEMVIEW_CONTIG) { + if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { + if (buf->strides[dim] != sizeof(void *)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly contiguous " + "in dimension %d.", dim); + goto fail; + } + } else if (buf->strides[dim] != buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_FOLLOW) { + Py_ssize_t stride = buf->strides[dim]; + if (stride < 0) + stride = -stride; + if (stride < buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + } else { + if (spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not contiguous in " + "dimension %d", dim); + goto fail; + } else if (spec & (__Pyx_MEMVIEW_PTR)) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not indirect in " + "dimension %d", dim); + goto fail; + } else if (buf->suboffsets) { + PyErr_SetString(PyExc_ValueError, + "Buffer exposes suboffsets but no strides"); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) +{ + if (spec & __Pyx_MEMVIEW_DIRECT) { + if (buf->suboffsets && buf->suboffsets[dim] >= 0) { + PyErr_Format(PyExc_ValueError, + "Buffer not compatible with direct access " + "in dimension %d.", dim); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_PTR) { + if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly accessible " + "in dimension %d.", dim); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) +{ + int i; + if (c_or_f_flag & __Pyx_IS_F_CONTIG) { + Py_ssize_t stride = 1; + for (i = 0; i < ndim; i++) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) + { + PyErr_SetString(PyExc_ValueError, + "Buffer not fortran contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { + Py_ssize_t stride = 1; + for (i = ndim - 1; i >- 1; i--) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) { + PyErr_SetString(PyExc_ValueError, + "Buffer not C contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } + return 1; +fail: + return 0; +} +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj) +{ + struct __pyx_memoryview_obj *memview, *new_memview; + __Pyx_RefNannyDeclarations + Py_buffer *buf; + int i, spec = 0, retval = -1; + __Pyx_BufFmt_Context ctx; + int from_memoryview = __pyx_memoryview_check(original_obj); + __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); + if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) + original_obj)->typeinfo)) { + memview = (struct __pyx_memoryview_obj *) original_obj; + new_memview = NULL; + } else { + memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + original_obj, buf_flags, 0, dtype); + new_memview = memview; + if (unlikely(!memview)) + goto fail; + } + buf = &memview->view; + if (buf->ndim != ndim) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + ndim, buf->ndim); + goto fail; + } + if (new_memview) { + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned) buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " + "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", + buf->itemsize, + (buf->itemsize > 1) ? "s" : "", + dtype->name, + dtype->size, + (dtype->size > 1) ? "s" : ""); + goto fail; + } + for (i = 0; i < ndim; i++) { + spec = axes_specs[i]; + if (!__pyx_check_strides(buf, i, ndim, spec)) + goto fail; + if (!__pyx_check_suboffsets(buf, i, ndim, spec)) + goto fail; + } + if (buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, + new_memview != NULL) == -1)) { + goto fail; + } + retval = 0; + goto no_fail; +fail: + Py_XDECREF(new_memview); + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[2]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 3, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } + } + #endif + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: + Py_DECREF(obj); + view->obj = NULL; } +#endif /* PY_MAJOR_VERSION < 3 */ -#else /* Python 3+ */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) goto bad; - } - if (value == Py_None) - value = 0; - - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; + list = empty_list; } - - if (cause) { - PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } - else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } - else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ } - if (!value) { - value = PyObject_CallObject(type, NULL); + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif } - PyException_SetCause(value, fixed_cause); } - - PyErr_SetObject(type, value); - - if (tb) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; } - + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif bad: - return; + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; } -#endif - -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } } else { - num_expected = num_max; - more_or_less = "at most"; + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } } - if (exact) { - more_or_less = "exactly"; + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); } - PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); } -static CYTHON_INLINE int __Pyx_CheckKeywordStrings( - PyObject *kwdict, - const char* function_name, - int kw_allowed) -{ - PyObject* key = 0; - Py_ssize_t pos = 0; - while (PyDict_Next(kwdict, &pos, &key, 0)) { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) - #endif - goto invalid_keyword_type; +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \ + { \ + func_type value = func(x); \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + PyErr_SetString(PyExc_OverflowError, \ + (is_unsigned && unlikely(value < zero)) ? \ + "can't convert negative value to " #target_type : \ + "value too large to convert to " #target_type); \ + return (target_type) -1; \ + } \ + } \ + return (target_type) value; \ } - if ((!kw_allowed) && unlikely(key)) - goto invalid_keyword; - return 1; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - return 0; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif - return 0; -} -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *x) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; + } + return (Py_intptr_t) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(Py_intptr_t)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; + } + if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(Py_intptr_t)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(Py_intptr_t) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyLong_AsLong) + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + Py_intptr_t val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (Py_intptr_t) -1; + } + } else { + Py_intptr_t val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (Py_intptr_t) -1; + val = __Pyx_PyInt_As_Py_intptr_t(tmp); + Py_DECREF(tmp); + return val; } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); - #endif } -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG) } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (int) ((PyLongObject*)x)->ob_digit[0]; } - if (*name) { - values[name-argnames] = value; - } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(int) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(int) ((PyLongObject*)x)->ob_digit[0]; } } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -static CYTHON_INLINE long __Pyx_div_long(long a, long b) { - long q = a / b; - long r = a - q*b; - q -= ((r != 0) & ((r ^ b) < 0)); - return q; -} - - -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { - PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); -} - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); } -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; } -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); - } else { - __Pyx_RaiseTooManyValuesError(index); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; } -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); - if (!py_import) - goto bad; - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - #if PY_VERSION_HEX >= 0x02050000 { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - } - #else - if (level>0) { - PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); - goto bad; + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); } - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, NULL); - #endif -bad: - Py_XDECREF(empty_list); - Py_XDECREF(py_import); - Py_XDECREF(empty_dict); - return module; } -static CYTHON_INLINE npy_int32 __Pyx_PyInt_from_py_npy_int32(PyObject* x) { - const npy_int32 neg_one = (npy_int32)-1, const_zero = (npy_int32)0; - const int is_unsigned = const_zero < neg_one; - if (sizeof(npy_int32) == sizeof(char)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedChar(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedChar(x); - } else if (sizeof(npy_int32) == sizeof(short)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedShort(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedShort(x); - } else if (sizeof(npy_int32) == sizeof(int)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedInt(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedInt(x); - } else if (sizeof(npy_int32) == sizeof(long)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedLong(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedLong(x); - } else if (sizeof(npy_int32) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedLongLong(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedLongLong(x); - } else { - npy_int32 val; - PyObject *v = __Pyx_PyNumber_Int(x); - #if PY_VERSION_HEX < 0x03000000 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; + } else { + if (sizeof(Py_intptr_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); } - return (npy_int32)-1; } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); + } +} + +static PyObject *__pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(const char *itemp) { + return (PyObject *) PyFloat_FromDouble(*(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) itemp); +} +static int __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(const char *itemp, PyObject *obj) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t value = __pyx_PyFloat_AsDouble(obj); + if ((value == (npy_float64)-1) && PyErr_Occurred()) + return 0; + *(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) itemp = value; + return 1; } static CYTHON_INLINE long __Pyx_pow_long(long b, long e) { @@ -12522,7 +39226,9 @@ static CYTHON_INLINE long __Pyx_pow_long(long b, long e) { case 0: return 1; } + #if 1 if (unlikely(e<0)) return 0; + #endif t = 1; while (likely(e)) { t *= (b * (e&1)) | ((~e)&1); /* 1 or b */ @@ -12532,54 +39238,101 @@ static CYTHON_INLINE long __Pyx_pow_long(long b, long e) { return t; } -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32 val) { - const npy_int32 neg_one = (npy_int32)-1, const_zero = (npy_int32)0; - const int is_unsigned = const_zero < neg_one; - if ((sizeof(npy_int32) == sizeof(char)) || - (sizeof(npy_int32) == sizeof(short))) { - return PyInt_FromLong((long)val); - } else if ((sizeof(npy_int32) == sizeof(int)) || - (sizeof(npy_int32) == sizeof(long))) { - if (is_unsigned) - return PyLong_FromUnsignedLong((unsigned long)val); - else - return PyInt_FromLong((long)val); - } else if (sizeof(npy_int32) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); - else - return PyLong_FromLongLong((PY_LONG_LONG)val); - } else { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - return _PyLong_FromByteArray(bytes, sizeof(npy_int32), - little, !is_unsigned); - } +static PyObject *__pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(const char *itemp) { + return (PyObject *) __Pyx_PyInt_From_Py_intptr_t(*(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) itemp); +} +static int __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(const char *itemp, PyObject *obj) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t value = __Pyx_PyInt_As_Py_intptr_t(obj); + if ((value == (npy_intp)-1) && PyErr_Occurred()) + return 0; + *(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) itemp = value; + return 1; } -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t val) { - const Py_intptr_t neg_one = (Py_intptr_t)-1, const_zero = (Py_intptr_t)0; - const int is_unsigned = const_zero < neg_one; - if ((sizeof(Py_intptr_t) == sizeof(char)) || - (sizeof(Py_intptr_t) == sizeof(short))) { - return PyInt_FromLong((long)val); - } else if ((sizeof(Py_intptr_t) == sizeof(int)) || - (sizeof(Py_intptr_t) == sizeof(long))) { - if (is_unsigned) - return PyLong_FromUnsignedLong((unsigned long)val); - else - return PyInt_FromLong((long)val); - } else if (sizeof(Py_intptr_t) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); - else - return PyLong_FromLongLong((PY_LONG_LONG)val); - } else { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), - little, !is_unsigned); +static PyObject* __pyx_convert__to_py___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t s) { + PyObject* res; + PyObject* member; + res = PyDict_New(); if (res == NULL) return NULL; + member = __Pyx_PyInt_From_Py_intptr_t(s.idx_start); if (member == NULL) goto bad; + if (PyDict_SetItem(res, __pyx_n_s_idx_start, member) < 0) goto bad; + Py_DECREF(member); + member = __Pyx_PyInt_From_Py_intptr_t(s.idx_end); if (member == NULL) goto bad; + if (PyDict_SetItem(res, __pyx_n_s_idx_end, member) < 0) goto bad; + Py_DECREF(member); + member = __Pyx_PyInt_From_Py_intptr_t(s.is_leaf); if (member == NULL) goto bad; + if (PyDict_SetItem(res, __pyx_n_s_is_leaf, member) < 0) goto bad; + Py_DECREF(member); + member = PyFloat_FromDouble(s.radius); if (member == NULL) goto bad; + if (PyDict_SetItem(res, __pyx_n_s_radius, member) < 0) goto bad; + Py_DECREF(member); + return res; + bad: + Py_XDECREF(member); + Py_DECREF(res); + return NULL; + } + static struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t __pyx_convert__from_py___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(PyObject * o) { + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t result; + PyObject *value = NULL; + if (!PyMapping_Check(o)) { + PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "a mapping", Py_TYPE(o)->tp_name); + goto bad; } + value = PyObject_GetItem(o, __pyx_n_s_idx_start); + if (!value) { + PyErr_Format(PyExc_ValueError, \ + "No value specified for struct attribute '%.200s'", "idx_start"); + goto bad; + } + result.idx_start = __Pyx_PyInt_As_Py_intptr_t(value); + if ((result.idx_start == (npy_intp)-1) && PyErr_Occurred()) + goto bad; + Py_DECREF(value); + value = PyObject_GetItem(o, __pyx_n_s_idx_end); + if (!value) { + PyErr_Format(PyExc_ValueError, \ + "No value specified for struct attribute '%.200s'", "idx_end"); + goto bad; + } + result.idx_end = __Pyx_PyInt_As_Py_intptr_t(value); + if ((result.idx_end == (npy_intp)-1) && PyErr_Occurred()) + goto bad; + Py_DECREF(value); + value = PyObject_GetItem(o, __pyx_n_s_is_leaf); + if (!value) { + PyErr_Format(PyExc_ValueError, \ + "No value specified for struct attribute '%.200s'", "is_leaf"); + goto bad; + } + result.is_leaf = __Pyx_PyInt_As_Py_intptr_t(value); + if ((result.is_leaf == (npy_intp)-1) && PyErr_Occurred()) + goto bad; + Py_DECREF(value); + value = PyObject_GetItem(o, __pyx_n_s_radius); + if (!value) { + PyErr_Format(PyExc_ValueError, \ + "No value specified for struct attribute '%.200s'", "radius"); + goto bad; + } + result.radius = __pyx_PyFloat_AsDouble(value); + if ((result.radius == (npy_float64)-1) && PyErr_Occurred()) + goto bad; + Py_DECREF(value); + return result; +bad: + Py_XDECREF(value); + return result; +} + +static PyObject *__pyx_memview_get_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(const char *itemp) { + return (PyObject *) __pyx_convert__to_py___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(*(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) itemp); +} +static int __pyx_memview_set_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(const char *itemp, PyObject *obj) { + struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t value = __pyx_convert__from_py___pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t(obj); + if (PyErr_Occurred()) + return 0; + *(struct __pyx_t_7sklearn_9neighbors_9ball_tree_NodeData_t *) itemp = value; + return 1; } #if CYTHON_CCOMPLEX @@ -12821,424 +39574,407 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t val) { } #endif #endif - -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; - } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; - } - return (unsigned short)val; - } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; - } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; - } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; - } - return (short)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; - } - return (signed char)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; - } - return (signed short)val; - } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; - } - return (signed int)val; - } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)PyLong_AsUnsignedLong(x); - } else { - return (unsigned long)PyLong_AsLong(x); - } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); - } + +static int +__pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim) +{ + int i, index, step, start; + Py_ssize_t itemsize = mvs->memview->view.itemsize; + if (order == 'F') { + step = 1; + start = 0; } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; + step = -1; + start = ndim - 1; + } + for (i = 0; i < ndim; i++) { + index = start + step * i; + if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) + return 0; + itemsize *= mvs->shape[index]; } + return 1; } -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)PyLong_AsUnsignedLong(x); +static void +__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + start = end = slice->data; + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + if (extent == 0) { + *out_start = *out_end = start; + return; } else { - return (long)PyLong_AsLong(x); + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); - Py_DECREF(tmp); - return val; } + *out_start = start; + *out_end = end + itemsize; +} +static int +__pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize) +{ + void *start1, *end1, *start2, *end2; + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + return (start1 < end2) && (start2 < end1); } -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + for (i = 0; i < ndim; i++) { + if (from_mvs->suboffsets[i] >= 0) { + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; } - return (PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; + } + __Pyx_GOTREF(shape_tuple); + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; } else { - return (PY_LONG_LONG)PyLong_AsLongLong(x); + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; } - } else { - PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); - Py_DECREF(tmp); - return val; } + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + goto no_fail; +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; +} + +static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) +{ + PyObject *cobj; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); +#endif + return cobj; } -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { + const char neg_one = (char) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; + if (sizeof(char) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to char"); + return (char) -1; + } + return (char) val; } - return (signed long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(char)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (char) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; + "can't convert negative value to char"); + return (char) -1; + } + if (sizeof(char) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(char) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long long, PyLong_AsUnsignedLongLong) } - return (signed long)PyLong_AsUnsignedLong(x); } else { - return (signed long)PyLong_AsLong(x); +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(char)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(char) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(char) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(char) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyLong_AsLong) + } else if (sizeof(char) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(char, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + char val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (char) -1; } } else { - signed long val; + char val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); + if (!tmp) return (char) -1; + val = __Pyx_PyInt_As_char(tmp); Py_DECREF(tmp); return val; } } -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; +static struct __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *type) { + struct __pyx_typeinfo_string result = { {0} }; + char *buf = (char *) result.string; + size_t size = type->size; + switch (type->typegroup) { + case 'H': + *buf = 'c'; + break; + case 'I': + case 'U': + if (size == 1) + *buf = 'b'; + else if (size == 2) + *buf = 'h'; + else if (size == 4) + *buf = 'i'; + else if (size == 8) + *buf = 'q'; + if (type->is_unsigned) + *buf = toupper(*buf); + break; + case 'P': + *buf = 'P'; + break; + case 'C': + { + __Pyx_TypeInfo complex_type = *type; + complex_type.typegroup = 'R'; + complex_type.size /= 2; + *buf++ = 'Z'; + *buf = __Pyx_TypeInfoToFormat(&complex_type).string[0]; + break; + } + case 'R': + if (size == 4) + *buf = 'f'; + else if (size == 8) + *buf = 'd'; + else + *buf = 'g'; + break; + } + return result; +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; + } + return (long) val; } - return (signed PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + "can't convert negative value to long"); + return (long) -1; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong) } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; } } else { - signed PY_LONG_LONG val; + long val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } } -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename) { - PyObject *old_exc, *old_val, *old_tb; - PyObject *ctx; - __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); - #if PY_MAJOR_VERSION < 3 - ctx = PyString_FromString(name); - #else - ctx = PyUnicode_FromString(name); - #endif - __Pyx_ErrRestore(old_exc, old_val, old_tb); - if (!ctx) { - PyErr_WriteUnraisable(Py_None); - } else { - PyErr_WriteUnraisable(ctx); - Py_DECREF(ctx); +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[2]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_9ball_tree_NodeHeapData_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; } static int __Pyx_check_binary_version(void) { @@ -13260,22 +39996,22 @@ static int __Pyx_check_binary_version(void) { return 0; } -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItemString(dict, "__pyx_vtable__", ob) < 0) +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) goto bad; - Py_DECREF(ob); - return 0; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; bad: - Py_XDECREF(ob); - return -1; + Py_XDECREF(py_name); + return 0; } +#endif #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType @@ -13286,15 +40022,14 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(class_name); - #else - py_name = PyUnicode_FromString(class_name); - #endif + py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); @@ -13306,11 +40041,23 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", + "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -13320,9 +40067,9 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", + "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } @@ -13334,51 +40081,158 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(name); - #else - py_name = PyUnicode_FromString(name); - #endif - if (!py_name) +#ifndef __PYX_HAVE_RT_ImportFunction +#define __PYX_HAVE_RT_ImportFunction +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); + if (!d) goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); + cobj = PyDict_GetItemString(d, funcname); + if (!cobj) { + PyErr_Format(PyExc_ImportError, + "%.200s does not export expected C function %.200s", + PyModule_GetName(module), funcname); + goto bad; + } +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3 && PY_MINOR_VERSION==0) + if (!PyCapsule_IsValid(cobj, sig)) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); + goto bad; + } + tmp.p = PyCapsule_GetPointer(cobj, sig); +#else + {const char *desc, *s1, *s2; + desc = (const char *)PyCObject_GetDesc(cobj); + if (!desc) + goto bad; + s1 = desc; s2 = sig; + while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } + if (*s1 != *s2) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, desc); + goto bad; + } + tmp.p = PyCObject_AsVoidPtr(cobj);} +#endif + *f = tmp.fp; + if (!(*f)) + goto bad; + Py_DECREF(d); return 0; +bad: + Py_XDECREF(d); + return -1; } #endif +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + #include "compile.h" #include "frameobject.h" #include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); + py_srcfile = PyString_FromString(filename); #else - py_srcfile = PyUnicode_FromString(__pyx_filename); + py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; - if (__pyx_clineno) { + if (c_line) { #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { @@ -13389,28 +40243,45 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, #endif } if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_code = PyCode_New( + py_code = __Pyx_PyCode_New( 0, /*int argcount,*/ - #if PY_MAJOR_VERSION >= 3 0, /*int kwonlyargcount,*/ - #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ + py_line, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); - if (!py_code) goto bad; + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ @@ -13418,11 +40289,9 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; + py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); } @@ -13457,26 +40326,90 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ +#if !CYTHON_COMPILING_IN_PYPY +#if PY_VERSION_HEX >= 0x02060000 + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -13492,13 +40425,13 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", + "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; @@ -13510,16 +40443,40 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + #if PY_VERSION_HEX < 0x02060000 + return PyInt_AsSsize_t(b); + #else + return PyLong_AsSsize_t(b); + #endif + } + x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) @@ -13534,17 +40491,5 @@ static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #endif } -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; -} - #endif /* Py_PYTHON_H */ diff --git a/sklearn/neighbors/ball_tree.pyx b/sklearn/neighbors/ball_tree.pyx index 50643300d7738..850aa0d9ac45a 100644 --- a/sklearn/neighbors/ball_tree.pyx +++ b/sklearn/neighbors/ball_tree.pyx @@ -1,1585 +1,175 @@ +#!python +#cython: boundscheck=False +#cython: wraparound=False +#cython: cdivision=True # Author: Jake Vanderplas -# License: BSD +# Licence: BSD 3 clause -""" -========= -Ball Tree -========= -A ball tree is a data object which speeds up nearest neighbor -searches in high dimensions (see scikit-learn neighbors module -documentation for an overview of neighbor trees). There are many -types of ball trees. This package provides a basic implementation -in cython. +__all__ = ['BallTree'] -Implementation Notes --------------------- +DOC_DICT = {'BinaryTree': 'BallTree', 'binary_tree': 'ball_tree'} -A ball tree can be thought of as a collection of nodes. Each node -stores a centroid, a radius, and the pointers to two child nodes. +VALID_METRICS = ['EuclideanDistance', 'SEuclideanDistance', + 'ManhattanDistance', 'ChebyshevDistance', + 'MinkowskiDistance', 'WMinkowskiDistance', + 'MahalanobisDistance', 'HammingDistance', + 'CanberraDistance', 'BrayCurtisDistance', + 'JaccardDistance', 'MatchingDistance', + 'DiceDistance', 'KulsinskiDistance', + 'RogersTanimotoDistance', 'RussellRaoDistance', + 'SokalMichenerDistance', 'SokalSneathDistance', + 'PyFuncDistance', 'HaversineDistance'] -* centroid : the centroid of a node is the mean of all the locations - of points within the node -* radius : the radius of a node is the distance from the centroid - to the furthest point in the node. -* subnodes : each node has a maximum of 2 child nodes. The data within - the parent node is divided between the two child nodes. -In a typical tree implementation, nodes may be classes or structures which -are dynamically allocated as needed. This offers flexibility in the number -of nodes, and leads to very straightforward and readable code. It also means -that the tree can be dynamically augmented or pruned with new data, in an -in-line fashion. This approach generally leads to recursive code: upon -construction, the head node constructs its child nodes, the child nodes -construct their child nodes, and so-on. +include "binary_tree.pxi" -The current package uses a different approach: all node data is stored in -a set of numpy arrays which are pre-allocated. The main advantage of this -approach is that the whole object can be quickly and easily saved to disk -and reconstructed from disk. This also allows for an iterative interface -which gives more control over the heap, and leads to speed. There are a -few disadvantages, however: once the tree is built, augmenting or pruning it -is not as straightforward. Also, the size of the tree must be known from the -start, so there is not as much flexibility in building it. +# Inherit BallTree from BinaryTree +cdef class BallTree(BinaryTree): + __doc__ = CLASS_DOC.format(**DOC_DICT) + pass -BallTree Pseudo-code -~~~~~~~~~~~~~~~~~~~~ -Because understanding a ball tree is simpler with recursive code, here is some -pseudo-code to show the structure of the main functionality - - # Ball Tree pseudo code - - class Node: - #class data: - centroid - radius - child1, child2 - - #class methods: - def construct(data): - centroid = compute_centroid(data) - radius = compute_radius(centroid, data) - - # Divide the data into two approximately equal sets. - # This is often done by splitting along a single dimension. - data1, data2 = divide(data) - - if number_of_points(data1) > 0: - child1.construct(data1) - - if number_of_points(data2) > 0: - child2.construct(data2) - - def query(pt, neighbors_heap): - # compute the minimum distance from pt to any point in this node - d = distance(point, centroid) - if d < radius: - min_distance = 0 - else: - min_distance = d - radius - - if min_distance > max_distance_in(neighbors_heap): - # all these points are too far away. cut off the search here - return - elif node_size > 1: - child1.query(pt, neighbors_heap) - child2.query(pt, neighbors_heap) - - - object BallTree: - #class data: - data - root_node - - #class methods - def construct(data, num_leaves): - root_node.construct(data) - - def query(point, num_neighbors): - neighbors_heap = empty_heap_of_size(num_neighbors) - root_node.query(point, neighbors_heap) - -This certainly is not a complete description, but should give the basic idea -of the form of the algorithm. The implementation below is much faster than -anything mirroring the pseudo-code above, but for that reason is much more -opaque. Here's the basic idea: - -BallTree Storage -~~~~~~~~~~~~~~~~ -The BallTree information is stored using a combination of -"Array of Structures" and "Structure of Arrays" to maximize speed. -Given input data of size ``(n_samples, n_features)``, BallTree computes the -expected number of nodes ``n_nodes`` (see below), and allocates the -following arrays: - -* ``data`` : a float array of shape ``(n_samples, n_features)`` - This is simply the input data. If the input matrix is well-formed - (contiguous, c-ordered, correct data type) then no copy is needed -* ``idx_array`` : an integer array of size ``n_samples`` - This can be thought of as an array of pointers to the data in ``data``. - Rather than shuffling around the data itself, we shuffle around pointers - to the rows in data. -* ``node_centroid_arr`` : a float array of shape ``(n_nodes, n_features)`` - This stores the centroid of the data in each node. -* ``node_info_arr`` : a size-``n_nodes`` array of ``NodeInfo`` structures. - This stores information associated with each node. Each ``NodeInfo`` - instance has the following attributes: - - ``idx_start`` - - ``idx_end`` : ``idx_start`` and ``idx_end`` reference the part of - ``idx_array`` which point to the data associated with the node. - The data in node with index ``i_node`` is given by - ``data[idx_array[idx_start:idx_end]]`` - - ``is_leaf`` : a boolean value which tells whether this node is a leaf: - that is, whether or not it has children. - - ``radius`` : a floating-point value which gives the distance from - the node centroid to the furthest point in the node. - -One feature here is that there are no stored pointers from parent nodes to -child nodes and vice-versa. These pointers are implemented implicitly: -For a node with index ``i``, the two children are found at indices -``2 * i + 1`` and ``2 * i + 2``, while the parent is found at index -``floor((i - 1) / 2)``. The root node has no parent. - -With this data structure in place, the functionality of the above BallTree -pseudo-code can be implemented in a much more efficient manner. -Most of the data passing done in this code uses raw data pointers. -Using numpy arrays would be preferable for safety, but the -overhead of array slicing and sub-array construction leads to execution -time which is several orders of magnitude slower than the current -implementation. - -Priority Queue vs Max-heap -~~~~~~~~~~~~~~~~~~~~~~~~~~ -When querying for more than one neighbor, the code must maintain a list of -the current k nearest points. The BallTree code implements this in two ways. - -- A priority queue: this is just a sorted list. When an item is added, - it is inserted in the appropriate location. The cost of the search plus - insert averages O[k]. -- A max-heap: this is a binary tree structure arranged such that each node is - greater than its children. The cost of adding an item is O[log(k)]. - At the end of the iterations, the results must be sorted: a quicksort is - used, which averages O[k log(k)]. Quicksort has worst-case O[k^2] - performance, but because the input is already structured in a max-heap, - the worst case will not be realized. Thus the sort is a one-time operation - with cost O[k log(k)]. - -Each insert is performed an average of log(N) times per query, where N is -the number of training points. Because of this, for a single query, the -priority-queue approach costs O[k log(N)], and the max-heap approach costs -O[log(k)log(N)] + O[k log(k)]. Tests show that for sufficiently large k, -the max-heap approach out-performs the priority queue approach by a factor -of a few. In light of these tests, the code uses a priority queue for -k < 5, and a max-heap otherwise. - -Memory Allocation -~~~~~~~~~~~~~~~~~ -It is desirable to construct a tree in as balanced a way as possible. -Given a training set with n_samples and a user-supplied leaf_size, if -the points in each node are divided as evenly as possible between the -two children, the maximum depth needed so that leaf nodes satisfy -``leaf_size <= n_points <= 2 * leaf_size`` is given by -``n_levels = 1 + max(0, floor(log2((n_samples - 1) / leaf_size)))`` -(with the exception of the special case where ``n_samples < leaf_size``) -For a given number of levels, the number of points in a tree is given by -``n_nodes = 2 ** n_levels - 1``. Both of these results can be shown -by induction. Using them, the correct amount of memory can be pre-allocated -for a given ``n_samples`` and ``leaf_size``. -""" - -import numpy as np - -cimport numpy as np -cimport cython -from libc cimport stdlib - -from ..utils import array2d - -###################################################################### -# global definitions -# -# type used for data -DTYPE = np.float64 -ctypedef np.float64_t DTYPE_t - -# type used for indices & counts -# warning: there will be problems if this is switched to an unsigned type! -ITYPE = np.int32 -ctypedef np.int32_t ITYPE_t - -# infinity -cdef DTYPE_t infinity = np.inf - - -###################################################################### -# utility functions: fast max, min, and absolute value -# -@cython.profile(False) -cdef inline DTYPE_t dmax(DTYPE_t x, DTYPE_t y): - if x >= y: - return x - else: - return y - - -@cython.profile(False) -cdef inline DTYPE_t dmin(DTYPE_t x, DTYPE_t y): - if x <= y: - return x - else: - return y - - -@cython.profile(False) -cdef inline DTYPE_t dabs(DTYPE_t x): - if x >= 0: - return x - else: - return -x - - -###################################################################### -# distance functions -# These implement the Minkowski p-distance given by -# dist = sum((x - y) ** p) ** (1 / p) -# To compare distances, the raising to the (1 / p) is not necessary -# therefore, for speed, we also define a function dist_p() given by -# dist_p = sum((x - y) ** p) -# there are also functions dist_from_dist_p() and dist_p_from_dist() -# which convert between these forms. -@cython.cdivision(True) -cdef DTYPE_t dist(DTYPE_t *x1, DTYPE_t *x2, ITYPE_t n, DTYPE_t p): - cdef ITYPE_t i - cdef DTYPE_t r, d - r = 0 - if p == 2: - for i from 0 <= i < n: - d = x1[i] - x2[i] - r += d * d - r = r ** 0.5 - elif p == infinity: - for i from 0 <= i < n: - r = dmax(r, dabs(x1[i] - x2[i])) - elif p == 1: - for i from 0 <= i < n: - r += dabs(x1[i] - x2[i]) - else: - for i from 0 <= i < n: - d = dabs(x1[i] - x2[i]) - r += d ** p - r = r ** (1. / p) - return r - - -@cython.cdivision(True) -cdef DTYPE_t dist_p(DTYPE_t *x1, DTYPE_t *x2, ITYPE_t n, DTYPE_t p): - cdef ITYPE_t i - cdef DTYPE_t r, d - r = 0 - if p == 2: - for i from 0 <= i < n: - d = x1[i] - x2[i] - r += d * d - elif p == infinity: - for i from 0 <= i < n: - r = dmax(r, dabs(x1[i] - x2[i])) - elif p == 1: - for i from 0 <= i < n: - r += dabs(x1[i] - x2[i]) - else: - for i from 0 <= i < n: - d = dabs(x1[i] - x2[i]) - r += d ** p - return r - - -@cython.cdivision(True) -cdef DTYPE_t dist_from_dist_p(DTYPE_t r, DTYPE_t p): - if p == 2: - return r ** 0.5 - elif p == infinity: - return r - elif p == 1: - return r - else: - return r ** (1. / p) - - -@cython.cdivision(True) -cdef DTYPE_t dist_p_from_dist(DTYPE_t r, DTYPE_t p): - if p == 2: - return r ** 2 - elif p == infinity: - return r - elif p == 1: - return r - else: - return r ** p - - -###################################################################### -# NodeInfo struct -# used to keep track of node information. -# there is also a centroid for each node: this is kept in a separate -# array for efficiency. This is a hybrid of the "Array of Structures" -# and "Structure of Arrays" styles. -cdef struct NodeInfo: - ITYPE_t idx_start - ITYPE_t idx_end - ITYPE_t is_leaf - DTYPE_t radius - - -###################################################################### -# stack struct -# This is used to keep track of the recursion stack in Node_query -cdef struct stack_item: - ITYPE_t i_node - DTYPE_t dist_p_LB - - -cdef struct stack: - int n - stack_item* heap - int size - - -@cython.profile(False) -cdef inline void stack_create(stack* self, int size): - self.size = size - self.heap = stdlib.malloc(sizeof(stack_item) * size) - self.n = 0 - - -@cython.profile(False) -cdef inline void stack_destroy(stack* self): - stdlib.free(self.heap) - - -@cython.profile(False) -cdef inline void stack_resize(stack* self, int new_size): - #print "resize", self.n, new_size - if new_size < self.n: - raise ValueError("new_size smaller than current") - - self.size = new_size - self.heap = stdlib.realloc( self.heap, - new_size * sizeof(stack_item)) - - -@cython.profile(False) -cdef inline void stack_push(stack* self, stack_item item): - if self.n >= self.size: - stack_resize(self, 2 * self.size + 1) - - self.heap[self.n] = item - self.n += 1 - - -@cython.profile(False) -cdef inline stack_item stack_pop(stack* self): - if self.n == 0: - raise ValueError("popping empty stack") - - self.n -= 1 - return self.heap[self.n] - - -###################################################################### -# newObj function -# this is a helper function for pickling -def newObj(obj): - return obj.__new__(obj) - - -###################################################################### -# BallTree class +#---------------------------------------------------------------------- +# The functions below specialized the Binary Tree as a Ball Tree # -cdef class BallTree(object): - """ - Ball Tree for fast nearest-neighbor searches : - - BallTree(X, leaf_size=20, p=2.0) - - Parameters - ---------- - X : array-like, shape = [n_samples, n_features] - n_samples is the number of points in the data set, and - n_features is the dimension of the parameter space. - Note: if X is a C-contiguous array of doubles then data will - not be copied. Otherwise, an internal copy will be made. - - leaf_size : positive integer (default = 20) - Number of points at which to switch to brute-force. Changing - leaf_size will not affect the results of a query, but can - significantly impact the speed of a query and the memory required - to store the built ball tree. The amount of memory needed to - store the tree scales as - 2 ** (1 + floor(log2((n_samples - 1) / leaf_size))) - 1 - For a specified ``leaf_size``, a leaf node is guaranteed to - satisfy ``leaf_size <= n_points <= 2 * leaf_size``, except in - the case that ``n_samples < leaf_size``. - - p : distance metric for the BallTree. ``p`` encodes the Minkowski - p-distance:: - - D = sum((X[i] - X[j]) ** p) ** (1. / p) - - p must be greater than or equal to 1, so that the triangle - inequality will hold. If ``p == np.inf``, then the distance is - equivalent to:: - - D = max(X[i] - X[j]) - - Attributes - ---------- - data : np.ndarray - The training data - - warning_flag : bool - Warning flag is set to true during query(...) if results are - dependent on the order of the training cases. - For classification or regression based on k-neighbors, if - neighbor k and neighbor k+1 have identical distances but different - labels, then the result will be dependent on the ordering of the - training data. In this case, ``warning_flag`` will be set to True. - - Examples - -------- - Query for k-nearest neighbors - - >>> import numpy as np - >>> np.random.seed(0) - >>> X = np.random.random((10,3)) # 10 points in 3 dimensions - >>> ball_tree = BallTree(X, leaf_size=2) # doctest: +SKIP - >>> dist, ind = ball_tree.query(X[0], n_neighbors=3) # doctest: +SKIP - >>> print ind # indices of 3 closest neighbors - [0 3 1] - >>> print dist # distances to 3 closest neighbors - [ 0. 0.19662693 0.29473397] - - Pickle and Unpickle a ball tree (using protocol = 2). Note that the - state of the tree is saved in the pickle operation: the tree is not - rebuilt on un-pickling - - >>> import numpy as np - >>> import pickle - >>> np.random.seed(0) - >>> X = np.random.random((10,3)) # 10 points in 3 dimensions - >>> ball_tree = BallTree(X, leaf_size=2) # doctest: +SKIP - >>> s = pickle.dumps(ball_tree, protocol=2) # doctest: +SKIP - >>> ball_tree_copy = pickle.loads(s) # doctest: +SKIP - >>> dist, ind = ball_tree_copy.query(X[0], k=3) # doctest: +SKIP - >>> print ind # indices of 3 closest neighbors - [0 3 1] - >>> print dist # distances to 3 closest neighbors - [ 0. 0.19662693 0.29473397] - """ - cdef readonly np.ndarray data - cdef np.ndarray idx_array - cdef np.ndarray node_centroid_arr - cdef np.ndarray node_info_arr - cdef DTYPE_t p - cdef ITYPE_t leaf_size - cdef ITYPE_t n_levels - cdef ITYPE_t n_nodes - cdef readonly int warning_flag - - def __cinit__(self): - """ - initialize all arrays to empty. This will prevent memory errors - in rare cases where __init__ is not called - """ - self.data = np.empty((0,0), dtype=DTYPE) - self.idx_array = np.empty(0, dtype=ITYPE) - self.node_centroid_arr = np.empty((0,0), dtype=DTYPE) - self.node_info_arr = np.empty(0, dtype='c') - - def __init__(self, X, ITYPE_t leaf_size=20, DTYPE_t p=2): - self.data = np.asarray(X, dtype=DTYPE, order='C') - self.warning_flag = True - - if X.size == 0: - raise ValueError("X is an empty array") - - if self.data.ndim != 2: - raise ValueError("X should have two dimensions") - - if p < 1: - raise ValueError("p must be greater than or equal to 1") - self.p = p - - if leaf_size < 1: - raise ValueError("leaf_size must be greater than or equal to 1") - self.leaf_size = leaf_size - - cdef ITYPE_t n_samples = self.data.shape[0] - cdef ITYPE_t n_features = self.data.shape[1] - - # determine number of levels in the ball tree, and from this - # the number of nodes in the ball tree - self.n_levels = np.log2(max(1, (n_samples - 1)/self.leaf_size)) + 1 - self.n_nodes = (2 ** self.n_levels) - 1 - - self.idx_array = np.arange(n_samples, dtype=ITYPE) - - self.node_centroid_arr = np.empty((self.n_nodes, n_features), - dtype=DTYPE, order='C') - - self.node_info_arr = np.empty(self.n_nodes * sizeof(NodeInfo), - dtype='c', order='C') - self.build_tree_() - - def __reduce__(self): - """ - reduce method used for pickling - """ - return (newObj, (BallTree,), self.__getstate__()) - - def __getstate__(self): - """ - get state for pickling - """ - return (self.data, - self.idx_array, - self.node_centroid_arr, - self.node_info_arr, - self.p, - self.leaf_size, - self.n_levels, - self.n_nodes) - - def __setstate__(self, state): - """ - set state for pickling - """ - self.data = state[0] - self.idx_array = state[1] - self.node_centroid_arr = state[2] - self.node_info_arr = state[3] - self.p = state[4] - self.leaf_size = state[5] - self.n_levels = state[6] - self.n_nodes = state[7] - - def query(self, X, k=1, return_distance=True): - """ - query(X, k=1, return_distance=True) - - query the Ball Tree for the k nearest neighbors - - Parameters - ---------- - X : array-like, last dimension self.dim - An array of points to query - k : integer (default = 1) - The number of nearest neighbors to return - return_distance : boolean (default = True) - if True, return a tuple (d,i) - if False, return array i - - Returns - ------- - i : if return_distance == False - (d,i) : if return_distance == True - - d : array of doubles - shape: x.shape[:-1] + (k,) - each entry gives the list of distances to the - neighbors of the corresponding point - (note that distances are not sorted) - - i : array of integers - shape: x.shape[:-1] + (k,) - each entry gives the list of indices of - neighbors of the corresponding point - (note that neighbors are not sorted) - - Examples - -------- - Query for k-nearest neighbors - - >>> import numpy as np - >>> np.random.seed(0) - >>> X = np.random.random((10,3)) # 10 points in 3 dimensions - >>> ball_tree = BallTree(X, leaf_size=2) # doctest: +SKIP - >>> dist, ind = ball_tree.query(X[0], k=3) # doctest: +SKIP - >>> print ind # indices of 3 closest neighbors - [0 3 1] - >>> print dist # distances to 3 closest neighbors - [ 0. 0.19662693 0.29473397] - """ - self.warning_flag = False - - X = array2d(X, dtype=DTYPE, order='C') - - if X.shape[-1] != self.data.shape[1]: - raise ValueError("query data dimension must match BallTree " - "data dimension") - - if k > self.data.shape[0]: - raise ValueError("k must be less than or equal " - "to the number of training points") - - # flatten X for iteration - orig_shape = X.shape - X = X.reshape((-1, X.shape[-1])) - - # for k less than 5, a priority queue is slightly faster - # for more neighbors, a max-heap implementation is faster - cdef ITYPE_t use_max_heap = (k >= 5) - - cdef ITYPE_t i - cdef ITYPE_t n_neighbors = k - cdef np.ndarray distances = np.empty((X.shape[0], n_neighbors), - dtype=DTYPE) - cdef np.ndarray idx_array = np.empty((X.shape[0], n_neighbors), - dtype=ITYPE) - - # initialize arrays. This is only needed for correct behavior of - # the warning flag. - distances.fill(-9999) - idx_array.fill(-9999) - - cdef np.ndarray Xi - - distances[:] = np.inf - - cdef DTYPE_t* dist_ptr = distances.data - cdef ITYPE_t* idx_ptr = idx_array.data - - cdef stack node_stack - stack_create(&node_stack, self.n_levels + 1) - - for i, Xi in enumerate(X): - self.query_one_(Xi.data, n_neighbors, - dist_ptr, idx_ptr, &node_stack, use_max_heap) - - # if max-heap is used, results must be sorted - if use_max_heap: - sort_dist_idx(dist_ptr, idx_ptr, n_neighbors) - - dist_ptr += n_neighbors - idx_ptr += n_neighbors - - stack_destroy(&node_stack) - - # deflatten results - if return_distance: - return (distances.reshape((orig_shape[:-1]) + (k,)), - idx_array.reshape((orig_shape[:-1]) + (k,))) - else: - return idx_array.reshape((orig_shape[:-1]) + (k,)) - - def query_radius(self, X, r, return_distance=False, - count_only=False, sort_results=False): - """ - query_radius(self, X, r, count_only = False): - - query the Ball Tree for neighbors within a ball of size r - - Parameters - ---------- - X : array-like, last dimension self.dim - An array of points to query - r : distance within which neighbors are returned - r can be a single value, or an array of values of shape - x.shape[:-1] if different radii are desired for each point. - return_distance : boolean (default = False) - if True, return distances to neighbors of each point - if False, return only neighbors - Note that unlike BallTree.query(), setting return_distance=True - adds to the computation time. Not all distances need to be - calculated explicitly for return_distance=False. Results are - not sorted by default: see ``sort_results`` keyword. - count_only : boolean (default = False) - if True, return only the count of points within distance r - if False, return the indices of all points within distance r - If return_distance==True, setting count_only=True will - result in an error. - sort_results : boolean (default = False) - if True, the distances and indices will be sorted before being - returned. If False, the results will not be sorted. If - return_distance == False, setting sort_results = True will - result in an error. - - Returns - ------- - count : if count_only == True - ind : if count_only == False and return_distance == False - (ind, dist) : if count_only == False and return_distance == True - - count : array of integers, shape = X.shape[:-1] - each entry gives the number of neighbors within - a distance r of the corresponding point. - - ind : array of objects, shape = X.shape[:-1] - each element is a numpy integer array listing the indices of - neighbors of the corresponding point. Note that unlike - the results of BallTree.query(), the returned neighbors - are not sorted by distance - - dist : array of objects, shape = X.shape[:-1] - each element is a numpy double array - listing the distances corresponding to indices in i. - - Examples - -------- - Query for neighbors in a given radius - - >>> import numpy as np - >>> np.random.seed(0) - >>> X = np.random.random((10,3)) # 10 points in 3 dimensions - >>> ball_tree = BallTree(X, leaf_size=2) # doctest: +SKIP - >>> print ball_tree.query_radius(X[0], r=0.3, count_only=True) - 3 - >>> ind = ball_tree.query_radius(X[0], r=0.3) # doctest: +SKIP - >>> print ind # indices of neighbors within distance 0.3 - [3 0 1] - """ - if count_only and return_distance: - raise ValueError("count_only and return_distance " - "cannot both be true") - - if sort_results and not return_distance: - raise ValueError("return_distance must be True if sort_distances " - "is True") - - cdef np.ndarray idx_array, idx_array_i, distances, distances_i - cdef np.ndarray pt, count - cdef ITYPE_t count_i - - # prepare X for query - X = array2d(X, dtype=DTYPE, order='C') - if X.shape[-1] != self.data.shape[1]: - raise ValueError("query data dimension must match BallTree " - "data dimension") - - # prepare r for query - r = np.asarray(r, dtype=DTYPE, order='C') - r = np.atleast_1d(r) - if r.shape == (1,): - r = r[0] * np.ones(X.shape[:-1], dtype=np.double) - else: - if r.shape != X.shape[:-1]: - raise ValueError("r must be broadcastable to X.shape") - - # flatten X and r for iteration - orig_shape = X.shape - X = X.reshape((-1, X.shape[-1])) - r = r.reshape(-1) - - cdef stack node_stack - stack_create(&node_stack, self.n_levels + 1) - - if count_only: - count = np.zeros(X.shape[0], ITYPE) - for pt_idx, pt in enumerate(X): - count[pt_idx] = self.query_radius_count_(pt.data, - r[pt_idx], - &node_stack) - elif not return_distance: - idx_array = np.empty(X.shape[0], dtype='object') - idx_array_i = np.empty(self.data.shape[0], dtype=ITYPE) - for pt_idx, pt in enumerate(X): - count_i = self.query_radius_idx_only_( - pt.data, - r[pt_idx], - idx_array_i.data, - &node_stack) - idx_array[pt_idx] = idx_array_i[:count_i].copy() - - else: - idx_array = np.empty(X.shape[0], dtype='object') - distances = np.empty(X.shape[0], dtype='object') - idx_array_i = np.empty(self.data.shape[0], dtype=ITYPE) - distances_i = np.empty(self.data.shape[0], dtype=DTYPE) - for pt_idx, pt in enumerate(X): - count_i = self.query_radius_distances_( - pt.data, - r[pt_idx], - idx_array_i.data, - distances_i.data, - &node_stack) - if sort_results: - sort_dist_idx(distances_i.data, - idx_array_i.data, - count_i) - - idx_array[pt_idx] = idx_array_i[:count_i].copy() - distances[pt_idx] = distances_i[:count_i].copy() +# Note that these functions use the concept of "reduced distance". +# The reduced distance, defined for some metrics, is a quantity which +# is more efficient to compute than the distance, but preserves the +# relative rankings of the true distance. For example, the reduced +# distance for the Euclidean metric is the squared-euclidean distance. +# For some metrics, the reduced distance is simply the distance. - stack_destroy(&node_stack) - # deflatten results - if count_only: - return count.reshape(orig_shape[:-1]) - elif return_distance: - return (idx_array.reshape(orig_shape[:-1]), - distances.reshape(orig_shape[:-1])) - else: - return idx_array.reshape(orig_shape[:-1]) +cdef int allocate_data(BinaryTree tree, ITYPE_t n_nodes, + ITYPE_t n_features) except -1: + """Allocate arrays needed for the KD Tree""" + tree.node_bounds_arr = np.zeros((1, n_nodes, n_features), dtype=DTYPE) + tree.node_bounds = get_memview_DTYPE_3D(tree.node_bounds_arr) + return 0 - @cython.cdivision(True) - cdef void build_tree_(BallTree self): - cdef DTYPE_t* data = self.data.data - cdef ITYPE_t* idx_array = self.idx_array.data - cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - cdef NodeInfo* node_info_arr = self.node_info_arr.data - cdef DTYPE_t p = self.p - cdef ITYPE_t n_samples = self.data.shape[0] - cdef ITYPE_t n_features = self.data.shape[1] +cdef int init_node(BinaryTree tree, ITYPE_t i_node, + ITYPE_t idx_start, ITYPE_t idx_end) except -1: + """Initialize the node for the dataset stored in tree.data""" + cdef ITYPE_t n_features = tree.data.shape[1] + cdef ITYPE_t n_points = idx_end - idx_start - cdef ITYPE_t idx_start, idx_end, n_points - cdef DTYPE_t radius - cdef ITYPE_t i, i_node, i_parent - - cdef DTYPE_t* centroid = node_centroid_arr - cdef NodeInfo* node_info = node_info_arr - cdef NodeInfo* parent_info - cdef DTYPE_t* point - - #------------------------------------------------------------ - # take care of the root node - node_info.idx_start = 0 - node_info.idx_end = n_samples - n_points = n_samples - - # determine Node centroid - compute_centroid(centroid, data, idx_array, - n_features, n_samples) - - # determine Node radius - radius = 0 - for i from node_info.idx_start <= i < node_info.idx_end: - radius = dmax(radius, - dist_p(centroid, data + n_features * idx_array[i], - n_features, p)) - node_info.radius = dist_from_dist_p(radius, p) - - # check if this is a leaf - if self.n_nodes == 1: - node_info.is_leaf = 1 - - else: - node_info.is_leaf = 0 - - # find dimension with largest spread - i_max = find_split_dim(data, idx_array + node_info.idx_start, - n_features, n_points) - - # sort idx_array along this dimension - partition_indices(data, - idx_array + node_info.idx_start, - i_max, - n_points / 2, - n_features, - n_points) - - #------------------------------------------------------------ - # cycle through all child nodes - for i_node from 1 <= i_node < self.n_nodes: - i_parent = (i_node - 1) / 2 - parent_info = node_info_arr + i_parent - - node_info = node_info_arr + i_node - - if parent_info.is_leaf: - raise ValueError("Fatal: parent is a leaf. Memory " - "allocation is flawed") - - if i_node < self.n_nodes / 2: - node_info.is_leaf = 0 - else: - node_info.is_leaf = 1 - - centroid = node_centroid_arr + i_node * n_features - - # find indices for this node - idx_start = parent_info.idx_start - idx_end = parent_info.idx_end - - if i_node % 2 == 1: - idx_start = (idx_start + idx_end) / 2 - else: - idx_end = (idx_start + idx_end) / 2 - - node_info.idx_start = idx_start - node_info.idx_end = idx_end - - n_points = idx_end - idx_start - - if n_points == 0: - raise ValueError("zero-sized node") - - elif n_points == 1: - #copy this point to centroid - copy_array(centroid, - data + idx_array[idx_start] * n_features, - n_features) - - #store radius in array - node_info.radius = 0 - - #is a leaf - node_info.is_leaf = 1 - - else: - # determine Node centroid - compute_centroid(centroid, data, idx_array + idx_start, - n_features, n_points) - - # determine Node radius - radius = 0 - for i from idx_start <= i < idx_end: - radius = dmax(radius, - dist_p(centroid, - data + n_features * idx_array[i], - n_features, p)) - node_info.radius = dist_from_dist_p(radius, p) - - if not node_info.is_leaf: - # find dimension with largest spread - i_max = find_split_dim(data, idx_array + idx_start, - n_features, n_points) - - # sort indices along this dimension - partition_indices(data, - idx_array + idx_start, - i_max, - n_points / 2, - n_features, - n_points) - - cdef void query_one_(BallTree self, - DTYPE_t* pt, - ITYPE_t k, - DTYPE_t* near_set_dist, - ITYPE_t* near_set_indx, - stack* node_stack, - ITYPE_t use_max_heap): - cdef DTYPE_t* data = self.data.data - cdef ITYPE_t* idx_array = self.idx_array.data - cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - cdef NodeInfo* node_info_arr = self.node_info_arr.data - cdef NodeInfo* node_info = node_info_arr - - cdef DTYPE_t p = self.p - cdef ITYPE_t n_features = self.data.shape[1] - - cdef DTYPE_t dmax, dist_pt, dist_p_LB, dist_p_LB_1, dist_p_LB_2 - cdef ITYPE_t i, i1, i2, i_node - - cdef stack_item item - - # This will keep track of any indices with distances values. If at - # the end of the tree traversal, this index is in the last position, - # then the warning flag will be set. - cdef ITYPE_t check_index = -1 - - item.i_node = 0 - item.dist_p_LB = calc_dist_p_LB(pt, node_centroid_arr, - node_info.radius, - n_features, p) - stack_push(node_stack, item) - - # create pointers to the priority-queue/max-heap functions. - # they both can operate on near_set_dist and near_set_indx - cdef DTYPE_t (*heapqueue_largest)(DTYPE_t*, ITYPE_t) - cdef ITYPE_t (*heapqueue_idx_largest)(ITYPE_t*, ITYPE_t) - cdef void (*heapqueue_insert)(DTYPE_t, ITYPE_t, DTYPE_t*, - ITYPE_t*, ITYPE_t) - - if use_max_heap: - heapqueue_largest = &max_heap_largest - heapqueue_idx_largest = &max_heap_idx_largest - heapqueue_insert = &max_heap_insert - else: - heapqueue_largest = &pqueue_largest - heapqueue_idx_largest = &pqueue_idx_largest - heapqueue_insert = &pqueue_insert - - while(node_stack.n > 0): - item = stack_pop(node_stack) - i_node = item.i_node - dist_p_LB = item.dist_p_LB - - node_info = node_info_arr + i_node - - #------------------------------------------------------------ - # Case 0: query point is exactly on the boundary. Set - # warning flag - if dist_p_LB == heapqueue_largest(near_set_dist, k): - # store index of point with same distance: - # we'll check it later - check_index = heapqueue_idx_largest(near_set_indx, k) - continue - - #------------------------------------------------------------ - # Case 1: query point is outside node radius - elif dist_p_LB > heapqueue_largest(near_set_dist, k): - continue - - #------------------------------------------------------------ - # Case 2: this is a leaf node. Update set of nearby points - elif node_info.is_leaf: - for i from node_info.idx_start <= i < node_info.idx_end: - dist_pt = dist_p(pt, - data + n_features * idx_array[i], - n_features, p) - - dmax = heapqueue_largest(near_set_dist, k) - - if dist_pt == dmax: - check_index = heapqueue_idx_largest(near_set_indx, k) - - elif dist_pt < dmax: - heapqueue_insert(dist_pt, idx_array[i], - near_set_dist, near_set_indx, k) - if dmax == heapqueue_largest(near_set_dist, k): - check_index = heapqueue_idx_largest(near_set_indx, - k) - - #------------------------------------------------------------ - # Case 3: Node is not a leaf. Recursively query subnodes - # starting with the one whose centroid is closest - else: - i1 = 2 * i_node + 1 - i2 = i1 + 1 - dist_p_LB_1 = calc_dist_p_LB(pt, (node_centroid_arr - + i1 * n_features), - node_info_arr[i1].radius, - n_features, p) - dist_p_LB_2 = calc_dist_p_LB(pt, (node_centroid_arr - + i2 * n_features), - node_info_arr[i2].radius, - n_features, p) - - # append children to stack: last-in-first-out - if dist_p_LB_2 <= dist_p_LB_1: - item.i_node = i1 - item.dist_p_LB = dist_p_LB_1 - stack_push(node_stack, item) - - item.i_node = i2 - item.dist_p_LB = dist_p_LB_2 - stack_push(node_stack, item) - - else: - item.i_node = i2 - item.dist_p_LB = dist_p_LB_2 - stack_push(node_stack, item) - - item.i_node = i1 - item.dist_p_LB = dist_p_LB_1 - stack_push(node_stack, item) - - if check_index == heapqueue_idx_largest(near_set_indx, k): - self.warning_flag = True - - for i from 0 <= i < k: - near_set_dist[i] = dist_from_dist_p(near_set_dist[i], p) - - cdef ITYPE_t query_radius_count_(BallTree self, - DTYPE_t* pt, DTYPE_t r, - stack* node_stack): - cdef DTYPE_t* data = self.data.data - cdef ITYPE_t* idx_array = self.idx_array.data - cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - cdef NodeInfo* node_info_arr = self.node_info_arr.data - cdef NodeInfo* node_info = node_info_arr - - cdef DTYPE_t p = self.p - cdef ITYPE_t n_features = self.data.shape[1] - cdef ITYPE_t i, i_node - cdef ITYPE_t count = 0 - cdef DTYPE_t r_p = dist_p_from_dist(r, p) - cdef DTYPE_t dist_pt - - cdef stack_item item - - item.i_node = 0 - stack_push(node_stack, item) - - while(node_stack.n > 0): - item = stack_pop(node_stack) - i_node = item.i_node - node_info = node_info_arr + i_node - - dist_pt = dist(pt, node_centroid_arr + n_features * i_node, - n_features, p) - - #------------------------------------------------------------ - # Case 1: all node points are outside distance r. - # prune this branch. - if dist_pt - node_info.radius > r: - continue - - #------------------------------------------------------------ - # Case 2: all node points are within distance r - # add all points - elif dist_pt + node_info.radius < r: - count += (node_info.idx_end - node_info.idx_start) - - #------------------------------------------------------------ - # Case 3: this is a leaf node. Go through all points to - # determine if they fall within radius - elif node_info.is_leaf: - for i from node_info.idx_start <= i < node_info.idx_end: - dist_pt = dist_p(pt, - data + idx_array[i] * n_features, - n_features, p) - if dist_pt <= r_p: - count += 1 - - #------------------------------------------------------------ - # Case 4: Node is not a leaf. Recursively query subnodes - else: - item.i_node = 2 * i_node + 1 - stack_push(node_stack, item) - - item.i_node = i = 2 * i_node + 2 - stack_push(node_stack, item) - - return count - - cdef ITYPE_t query_radius_idx_only_(BallTree self, - DTYPE_t* pt, DTYPE_t r, - ITYPE_t* indices, - stack* node_stack): - cdef DTYPE_t* data = self.data.data - cdef ITYPE_t* idx_array = self.idx_array.data - cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - cdef NodeInfo* node_info_arr = self.node_info_arr.data - cdef NodeInfo* node_info = node_info_arr - - cdef DTYPE_t p = self.p - cdef ITYPE_t n_features = self.data.shape[1] - cdef ITYPE_t i, i_node - cdef ITYPE_t idx_i = 0 - cdef DTYPE_t r_p = dist_p_from_dist(r, p) - cdef DTYPE_t dist_pt - - cdef stack_item item - - item.i_node = 0 - stack_push(node_stack, item) - - while(node_stack.n > 0): - item = stack_pop(node_stack) - i_node = item.i_node - node_info = node_info_arr + i_node - - dist_pt = dist(pt, node_centroid_arr + n_features * i_node, - n_features, p) - - #------------------------------------------------------------ - # Case 1: all node points are outside distance r. - # prune this branch. - if dist_pt - node_info.radius > r: - continue - - #------------------------------------------------------------ - # Case 2: all node points are within distance r - # add all points - elif dist_pt + node_info.radius < r: - for i from node_info.idx_start <= i < node_info.idx_end: - indices[idx_i] = idx_array[i] - idx_i += 1 - - #------------------------------------------------------------ - # Case 3: this is a leaf node. Go through all points to - # determine if they fall within radius - elif node_info.is_leaf: - for i from node_info.idx_start <= i < node_info.idx_end: - dist_pt = dist_p(pt, - data + idx_array[i] * n_features, - n_features, p) - if dist_pt <= r_p: - indices[idx_i] = idx_array[i] - idx_i += 1 - - #------------------------------------------------------------ - # Case 4: Node is not a leaf. Recursively query subnodes - else: - item.i_node = 2 * i_node + 1 - stack_push(node_stack, item) - - item.i_node = i = 2 * i_node + 2 - stack_push(node_stack, item) - - return idx_i - - cdef ITYPE_t query_radius_distances_(BallTree self, - DTYPE_t* pt, DTYPE_t r, - ITYPE_t* indices, - DTYPE_t* distances, - stack* node_stack): - cdef DTYPE_t* data = self.data.data - cdef ITYPE_t* idx_array = self.idx_array.data - cdef DTYPE_t* node_centroid_arr = self.node_centroid_arr.data - cdef NodeInfo* node_info_arr = self.node_info_arr.data - cdef NodeInfo* node_info = node_info_arr - - cdef DTYPE_t p = self.p - cdef ITYPE_t n_features = self.data.shape[1] - cdef ITYPE_t i, i_node - cdef ITYPE_t idx_i = 0 - cdef DTYPE_t r_p = dist_p_from_dist(r, p) - cdef DTYPE_t dist_pt - - cdef stack_item item - - item.i_node = 0 - stack_push(node_stack, item) - - while(node_stack.n > 0): - item = stack_pop(node_stack) - i_node = item.i_node - node_info = node_info_arr + i_node - - dist_pt = dist(pt, node_centroid_arr + n_features * i_node, - n_features, p) - - #------------------------------------------------------------ - # Case 1: all node points are outside distance r. - # prune this branch. - if dist_pt - node_info.radius > r: - continue - - #------------------------------------------------------------ - # Case 2: all node points are within distance r - # add all points - elif dist_pt + node_info.radius < r: - for i from node_info.idx_start <= i < node_info.idx_end: - dist_pt = dist(pt, - data + idx_array[i] * n_features, - n_features, p) - indices[idx_i] = idx_array[i] - distances[idx_i] = dist_pt - idx_i += 1 - - #------------------------------------------------------------ - # Case 3: this is a leaf node. Go through all points to - # determine if they fall within radius - elif node_info.is_leaf: - for i from node_info.idx_start <= i < node_info.idx_end: - dist_pt = dist_p(pt, - data + idx_array[i] * n_features, - n_features, p) - if dist_pt <= r_p: - indices[idx_i] = idx_array[i] - distances[idx_i] = dist_from_dist_p(dist_pt, p) - idx_i += 1 - - #------------------------------------------------------------ - # Case 4: Node is not a leaf. Recursively query subnodes - else: - item.i_node = 2 * i_node + 1 - stack_push(node_stack, item) - - item.i_node = i = 2 * i_node + 2 - stack_push(node_stack, item) - - return idx_i - - -###################################################################### -# Helper functions for building and querying -# -@cython.profile(False) -cdef inline void copy_array(DTYPE_t* x, DTYPE_t* y, ITYPE_t n): - # copy array y into array x - cdef ITYPE_t i - for i from 0 <= i < n: - x[i] = y[i] - - -@cython.cdivision(True) -cdef void compute_centroid(DTYPE_t* centroid, - DTYPE_t* data, - ITYPE_t* node_indices, - ITYPE_t n_features, - ITYPE_t n_points): - # `centroid` points to an array of length n_features - # `data` points to an array of length n_samples * n_features - # `node_indices` = idx_array + idx_start - cdef DTYPE_t *this_pt cdef ITYPE_t i, j + cdef DTYPE_t radius + cdef DTYPE_t *this_pt + + cdef ITYPE_t* idx_array = &tree.idx_array[0] + cdef DTYPE_t* data = &tree.data[0, 0] + cdef DTYPE_t* centroid = &tree.node_bounds[0, i_node, 0] - for j from 0 <= j < n_features: + # determine Node centroid + for j in range(n_features): centroid[j] = 0 - for i from 0 <= i < n_points: - this_pt = data + n_features * node_indices[i] + for i in range(idx_start, idx_end): + this_pt = data + n_features * idx_array[i] for j from 0 <= j < n_features: centroid[j] += this_pt[j] - for j from 0 <= j < n_features: + for j in range(n_features): centroid[j] /= n_points - -cdef ITYPE_t find_split_dim(DTYPE_t* data, - ITYPE_t* node_indices, - ITYPE_t n_features, - ITYPE_t n_points): - # this computes the following - # j_max = np.argmax(np.max(data, 0) - np.min(data, 0)) - cdef DTYPE_t min_val, max_val, val, spread, max_spread - cdef ITYPE_t i, j, j_max - - j_max = 0 - max_spread = 0 - - for j from 0 <= j < n_features: - max_val = data[node_indices[0] * n_features + j] - min_val = max_val - for i from 1 <= i < n_points: - val = data[node_indices[i] * n_features + j] - max_val = dmax(max_val, val) - min_val = dmin(min_val, val) - spread = max_val - min_val - if spread > max_spread: - max_spread = spread - j_max = j - return j_max - - -@cython.profile(False) -cdef inline void iswap(ITYPE_t* arr, ITYPE_t i1, ITYPE_t i2): - cdef ITYPE_t tmp = arr[i1] - arr[i1] = arr[i2] - arr[i2] = tmp - - -@cython.profile(False) -cdef inline void dswap(DTYPE_t* arr, ITYPE_t i1, ITYPE_t i2): - cdef DTYPE_t tmp = arr[i1] - arr[i1] = arr[i2] - arr[i2] = tmp - - -cdef void partition_indices(DTYPE_t* data, - ITYPE_t* node_indices, - ITYPE_t split_dim, - ITYPE_t split_index, - ITYPE_t n_features, - ITYPE_t n_points): - # partition_indices will modify the array node_indices between - # indices 0 and n_points. Upon return (assuming numpy-style slicing) - # data[node_indices[0:split_index], split_dim] - # <= data[node_indices[split_index], split_dim] - # and - # data[node_indices[split_index], split_dim] - # <= data[node_indices[split_index:n_points], split_dim] - # will hold. The algorithm amounts to a partial quicksort - cdef ITYPE_t left, right, midindex, i - cdef DTYPE_t d1, d2 - left = 0 - right = n_points - 1 - - while True: - midindex = left - for i from left <= i < right: - d1 = data[node_indices[i] * n_features + split_dim] - d2 = data[node_indices[right] * n_features + split_dim] - if d1 < d2: - iswap(node_indices, i, midindex) - midindex += 1 - iswap(node_indices, midindex, right) - if midindex == split_index: - break - elif midindex < split_index: - left = midindex + 1 - else: - right = midindex - 1 - - -###################################################################### -# calc_dist_LB -# calc_dist_p_LB -# This calculates the lower-bound distance between a point and a node -@cython.profile(False) -cdef inline DTYPE_t calc_dist_LB(DTYPE_t* pt, - DTYPE_t* centroid, - DTYPE_t radius, - ITYPE_t n_features, - DTYPE_t p): - return dmax(0, (dist(pt, centroid, n_features, p) - - radius)) - - -@cython.profile(False) -cdef inline DTYPE_t calc_dist_p_LB(DTYPE_t* pt, - DTYPE_t* centroid, - DTYPE_t radius, - ITYPE_t n_features, - DTYPE_t p): - return dist_p_from_dist(dmax(0, (dist(pt, centroid, n_features, p) - - radius)), p) - - -###################################################################### -# priority queue -# This is used to keep track of the neighbors as they are found. -# It keeps the list of neighbors sorted, and inserts each new item -# into the list. In this fixed-size implementation, empty elements -# are represented by infinities. -@cython.profile(False) -cdef inline DTYPE_t pqueue_largest(DTYPE_t* queue, ITYPE_t queue_size): - return queue[queue_size - 1] - - -cdef inline ITYPE_t pqueue_idx_largest(ITYPE_t* idx_array, ITYPE_t queue_size): - return idx_array[queue_size - 1] - - -cdef inline void pqueue_insert(DTYPE_t val, ITYPE_t i_val, - DTYPE_t* queue, ITYPE_t* idx_array, - ITYPE_t queue_size): - cdef ITYPE_t i_lower = 0 - cdef ITYPE_t i_upper = queue_size - 1 - cdef ITYPE_t i_mid - cdef ITYPE_t i - - if val >= queue[i_upper]: - return - elif val <= queue[i_lower]: - i_mid = i_lower + # determine Node radius + radius = 0 + for i in range(idx_start, idx_end): + radius = fmax(radius, + tree.rdist(centroid, + data + n_features * idx_array[i], + n_features)) + + tree.node_data[i_node].radius = tree.dist_metric._rdist_to_dist(radius) + tree.node_data[i_node].idx_start = idx_start + tree.node_data[i_node].idx_end = idx_end + return 0 + + +cdef inline DTYPE_t min_dist(BinaryTree tree, ITYPE_t i_node, + DTYPE_t* pt) except -1: + """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]) + return fmax(0, dist_pt - tree.node_data[i_node].radius) + + +cdef inline DTYPE_t max_dist(BinaryTree tree, ITYPE_t i_node, + DTYPE_t* pt) except -1: + """Compute the 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]) + return dist_pt + tree.node_data[i_node].radius + + +cdef inline int min_max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt, + DTYPE_t* min_dist, DTYPE_t* max_dist) except -1: + """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]) + cdef DTYPE_t rad = tree.node_data[i_node].radius + min_dist[0] = fmax(0, dist_pt - rad) + max_dist[0] = dist_pt + rad + return 0 + + +cdef inline DTYPE_t min_rdist(BinaryTree tree, ITYPE_t i_node, + DTYPE_t* pt) except -1: + """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)) else: - while True: - if (i_upper - i_lower) < 2: - i_mid = i_lower + 1 - break - else: - i_mid = (i_lower + i_upper) / 2 - - if i_mid == i_lower: - i_mid += 1 - break - - if val >= queue[i_mid]: - i_lower = i_mid - else: - i_upper = i_mid - - for i from queue_size > i > i_mid: - queue[i] = queue[i - 1] - idx_array[i] = idx_array[i - 1] - - queue[i_mid] = val - idx_array[i_mid] = i_val - - -###################################################################### -# max_heap -# -# This is a basic implementation of a fixed-size binary max-heap. -# It can be used in place of priority_queue to keep track of the -# k-nearest neighbors in a query. The implementation is faster than -# priority_queue for a very large number of neighbors (k > 50 or so). -# The implementation is slower than priority_queue for fewer neighbors. -# The other disadvantage is that for max_heap, the indices/distances must -# be sorted upon completion of the query. In priority_queue, the indices -# and distances are sorted without an extra call. -# -# The root node is at heap[0]. The two child nodes of node i are at -# (2 * i + 1) and (2 * i + 2). -# The parent node of node i is node floor((i-1)/2). Node 0 has no parent. -# A max heap has (heap[i] >= heap[2 * i + 1]) and (heap[i] >= heap[2 * i + 2]) -# for all valid indices. -# -# In this implementation, an empty heap should be full of infinities -# -# As part of this implementation, there is a quicksort provided with -# `sort_dist_idx()` -@cython.profile(False) -cdef inline DTYPE_t max_heap_largest(DTYPE_t* heap, ITYPE_t k): - return heap[0] - + return tree.dist_metric._dist_to_rdist(min_dist(tree, i_node, pt)) -@cython.profile(False) -cdef inline ITYPE_t max_heap_idx_largest(ITYPE_t* idx_array, ITYPE_t k): - return idx_array[0] +cdef inline DTYPE_t max_rdist(BinaryTree tree, ITYPE_t i_node, + DTYPE_t* pt) except -1: + """Compute the maximum reduced-distance between a point and a node""" + if tree.euclidean: + return euclidean_dist_to_rdist(max_dist(tree, i_node, pt)) + else: + return tree.dist_metric._dist_to_rdist(max_dist(tree, i_node, pt)) + + +cdef inline DTYPE_t min_dist_dual(BinaryTree tree1, ITYPE_t i_node1, + BinaryTree tree2, ITYPE_t i_node2) except -1: + """compute the minimum distance between two nodes""" + cdef DTYPE_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], + &tree1.node_bounds[0, i_node1, 0], + tree1.data.shape[1]) + return fmax(0, (dist_pt - tree1.node_data[i_node1].radius + - tree2.node_data[i_node2].radius)) + + +cdef inline DTYPE_t max_dist_dual(BinaryTree tree1, ITYPE_t i_node1, + BinaryTree tree2, ITYPE_t i_node2) except -1: + """compute the maximum distance between two nodes""" + cdef DTYPE_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], + &tree1.node_bounds[0, i_node1, 0], + tree1.data.shape[1]) + return (dist_pt + tree1.node_data[i_node1].radius + + tree2.node_data[i_node2].radius) + + +cdef inline DTYPE_t min_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, + BinaryTree tree2, ITYPE_t i_node2) except -1: + """compute the minimum reduced distance between two nodes""" + if tree1.euclidean: + return euclidean_dist_to_rdist(min_dist_dual(tree1, i_node1, + tree2, i_node2)) + else: + return tree1.dist_metric._dist_to_rdist(min_dist_dual(tree1, i_node1, + tree2, i_node2)) -cdef void max_heap_insert(DTYPE_t val, ITYPE_t i_val, - DTYPE_t* heap, - ITYPE_t* idx_array, - ITYPE_t heap_size): - cdef ITYPE_t i, ic1, ic2, i_tmp - cdef DTYPE_t d_tmp - - # check if val should be in heap - if val > heap[0]: - return - - # insert val at position zero - heap[0] = val - idx_array[0] = i_val - - #descend the heap, swapping values until the max heap criterion is met - i = 0 - while 1: - ic1 = 2 * i + 1 - ic2 = ic1 + 1 - - if ic1 >= heap_size: - break - elif ic2 >= heap_size: - if heap[ic1] > val: - i_swap = ic1 - else: - break - elif heap[ic1] >= heap[ic2]: - if val < heap[ic1]: - i_swap = ic1 - else: - break - else: - if val < heap[ic2]: - i_swap = ic2 - else: - break - - heap[i] = heap[i_swap] - idx_array[i] = idx_array[i_swap] - - i = i_swap - - heap[i] = val - idx_array[i] = i_val - - -###################################################################### -# sort_dist_idx : -# this is a quicksort implementation which sorts `dist` and -# simultaneously performs the same swaps on `idx`. -cdef void sort_dist_idx(DTYPE_t* dist, ITYPE_t* idx, ITYPE_t k): - cdef ITYPE_t pivot_idx - if k > 1: - pivot_idx = partition_dist_idx(dist, idx, k) - - sort_dist_idx(dist, idx, pivot_idx) - - sort_dist_idx(dist + pivot_idx + 1, - idx + pivot_idx + 1, - k - pivot_idx - 1) - - -cdef ITYPE_t partition_dist_idx(DTYPE_t* dist, ITYPE_t* idx, ITYPE_t k): - cdef ITYPE_t pivot_idx = k / 2 - cdef DTYPE_t pivot_val = dist[pivot_idx] - cdef ITYPE_t store_idx = 0 - cdef ITYPE_t i - - dswap(dist, pivot_idx, k - 1) - iswap(idx, pivot_idx, k - 1) - for i from 0 <= i < k - 1: - if dist[i] < pivot_val: - dswap(dist, i, store_idx) - iswap(idx, i, store_idx) - store_idx += 1 - dswap(dist, store_idx, k - 1) - iswap(idx, store_idx, k - 1) - return store_idx +cdef inline DTYPE_t max_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, + BinaryTree tree2, ITYPE_t i_node2) except -1: + """compute the maximum reduced distance between two nodes""" + if tree1.euclidean: + return euclidean_dist_to_rdist(max_dist_dual(tree1, i_node1, + tree2, i_node2)) + else: + return tree1.dist_metric._dist_to_rdist(max_dist_dual(tree1, i_node1, + tree2, i_node2)) diff --git a/sklearn/neighbors/base.py b/sklearn/neighbors/base.py index 10cea9bccfbe4..35e4a9201603e 100644 --- a/sklearn/neighbors/base.py +++ b/sklearn/neighbors/base.py @@ -3,34 +3,54 @@ # Fabian Pedregosa # Alexandre Gramfort # Sparseness support by Lars Buitinck +# Multi-output support by Arnaud Joly # -# License: BSD, (C) INRIA, University of Amsterdam +# License: BSD 3 clause (C) INRIA, University of Amsterdam import warnings +from abc import ABCMeta, abstractmethod import numpy as np -from abc import ABCMeta, abstractmethod from scipy.sparse import csr_matrix, issparse -from scipy.spatial.ckdtree import cKDTree from .ball_tree import BallTree +from .kd_tree import KDTree from ..base import BaseEstimator from ..metrics import pairwise_distances -from ..utils import safe_asarray, atleast2d_or_csr, check_arrays +from ..metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS +from ..utils import check_X_y, check_array +from ..utils.fixes import argpartition +from ..utils.validation import DataConversionWarning +from ..utils.validation import NotFittedError +from ..externals import six + + +VALID_METRICS = dict(ball_tree=BallTree.valid_metrics, + kd_tree=KDTree.valid_metrics, + # The following list comes from the + # sklearn.metrics.pairwise doc string + brute=(list(PAIRWISE_DISTANCE_FUNCTIONS.keys()) + + ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'cosine', 'dice', 'hamming', + 'jaccard', 'kulsinski', 'mahalanobis', + 'matching', 'minkowski', 'rogerstanimoto', + 'russellrao', 'seuclidean', 'sokalmichener', + 'sokalsneath', 'sqeuclidean', + 'yule', 'wminkowski'])) + + +VALID_METRICS_SPARSE = dict(ball_tree=[], + kd_tree=[], + brute=PAIRWISE_DISTANCE_FUNCTIONS.keys()) class NeighborsWarning(UserWarning): pass + # Make sure that NeighborsWarning are displayed more than once warnings.simplefilter("always", NeighborsWarning) -def warn_equidistant(): - msg = ("kneighbors: neighbor k+1 and neighbor k have the same " - "distance: results will be dependent on data order.") - warnings.warn(msg, NeighborsWarning, stacklevel=3) - - def _check_weights(weights): """Check to make sure weights are valid""" if weights in (None, 'uniform', 'distance'): @@ -60,47 +80,120 @@ def _get_weights(dist, weights): if weights in (None, 'uniform'): return None elif weights == 'distance': - with np.errstate(divide='ignore'): - dist = 1. / dist + # if user attempts to classify a point that was zero distance from one + # or more training points, those training points are weighted as 1.0 + # and the other points as 0.0 + if dist.dtype is np.dtype(object): + for point_dist_i, point_dist in enumerate(dist): + # check if point_dist is iterable + # (ex: RadiusNeighborClassifier.predict may set an element of + # dist to 1e-6 to represent an 'outlier') + if hasattr(point_dist, '__contains__') and 0. in point_dist: + dist[point_dist_i] = point_dist == 0. + else: + dist[point_dist_i] = 1. / point_dist + else: + with np.errstate(divide='ignore'): + dist = 1. / dist + inf_mask = np.isinf(dist) + inf_row = np.any(inf_mask, axis=1) + dist[inf_row] = inf_mask[inf_row] return dist elif callable(weights): return weights(dist) else: raise ValueError("weights not recognized: should be 'uniform', " - "'distance', or a callable function") + "'distance', or a callable function") -class NeighborsBase(BaseEstimator): +class NeighborsBase(six.with_metaclass(ABCMeta, BaseEstimator)): """Base class for nearest neighbors estimators.""" - __metaclass__ = ABCMeta @abstractmethod def __init__(self): pass - #FIXME: include float parameter p for using different distance metrics. - # this can be passed directly to BallTree and cKDTree. Brute-force will - # rely on soon-to-be-updated functionality in the pairwise module. def _init_params(self, n_neighbors=None, radius=None, - algorithm='auto', leaf_size=30, - warn_on_equidistant=True, p=2): + algorithm='auto', leaf_size=30, metric='minkowski', + p=2, metric_params=None, **kwargs): + if kwargs: + warnings.warn("Passing additional arguments to the metric " + "function as **kwargs is deprecated " + "and will no longer be supported in 0.18. " + "Use metric_params instead.", + DeprecationWarning, stacklevel=3) + if metric_params is None: + metric_params = {} + metric_params.update(kwargs) + self.n_neighbors = n_neighbors self.radius = radius self.algorithm = algorithm self.leaf_size = leaf_size - self.warn_on_equidistant = warn_on_equidistant + self.metric = metric + self.metric_params = metric_params self.p = p - if algorithm not in ['auto', 'brute', 'kd_tree', 'ball_tree']: + if algorithm not in ['auto', 'brute', + 'kd_tree', 'ball_tree']: raise ValueError("unrecognized algorithm: '%s'" % algorithm) - if p < 1: - raise ValueError("p must be greater than or equal to 1") + + if algorithm == 'auto': + alg_check = 'ball_tree' + else: + alg_check = algorithm + + if callable(metric): + if algorithm == 'kd_tree': + # callable metric is only valid for brute force and ball_tree + raise ValueError( + "kd_tree algorithm does not support callable metric '%s'" + % metric) + elif metric not in VALID_METRICS[alg_check]: + raise ValueError("Metric '%s' not valid for algorithm '%s'" + % (metric, algorithm)) + + if self.metric_params is not None and 'p' in self.metric_params: + warnings.warn("Parameter p is found in metric_params. " + "The corresponding parameter from __init__ " + "is ignored.", SyntaxWarning, stacklevel=3) + effective_p = metric_params['p'] + else: + effective_p = self.p + + if self.metric in ['wminkowski', 'minkowski'] and effective_p < 1: + raise ValueError("p must be greater than one for minkowski metric") self._fit_X = None self._tree = None self._fit_method = None def _fit(self, X): + if self.metric_params is None: + self.effective_metric_params_ = {} + else: + self.effective_metric_params_ = self.metric_params.copy() + + effective_p = self.effective_metric_params_.get('p', self.p) + if self.metric in ['wminkowski', 'minkowski']: + self.effective_metric_params_['p'] = effective_p + + self.effective_metric_ = self.metric + # For minkowski distance, use more efficient methods where available + if self.metric == 'minkowski': + p = self.effective_metric_params_.pop('p', 2) + if p < 1: + raise ValueError("p must be greater than one " + "for minkowski metric") + elif p == 1: + self.effective_metric_ = 'manhattan' + elif p == 2: + self.effective_metric_ = 'euclidean' + elif p == np.inf: + self.effective_metric_ = 'chebyshev' + else: + self.effective_metric_params_['p'] = p + if isinstance(X, NeighborsBase): self._fit_X = X._fit_X self._tree = X._tree @@ -113,22 +206,26 @@ def _fit(self, X): self._fit_method = 'ball_tree' return self - elif isinstance(X, cKDTree): + elif isinstance(X, KDTree): self._fit_X = X.data self._tree = X self._fit_method = 'kd_tree' return self - X = safe_asarray(X) + X = check_array(X, accept_sparse='csr') - if X.ndim != 2: - raise ValueError("data type not understood") + n_samples = X.shape[0] + if n_samples == 0: + raise ValueError("n_samples must be greater than 0") if issparse(X): if self.algorithm not in ('auto', 'brute'): warnings.warn("cannot use tree with sparse input: " "using brute force") - self._fit_X = X.tocsr() + if self.effective_metric_ not in VALID_METRICS_SPARSE['brute']: + raise ValueError("metric '%s' not valid for sparse input" + % self.effective_metric_) + self._fit_X = X.copy() self._tree = None self._fit_method = 'brute' return self @@ -137,18 +234,25 @@ def _fit(self, X): self._fit_X = X if self._fit_method == 'auto': - # BallTree outperforms the others in nearly any circumstance. - if self.n_neighbors is None: - self._fit_method = 'ball_tree' - elif self.n_neighbors < self._fit_X.shape[0] // 2: - self._fit_method = 'ball_tree' + # A tree approach is better for small number of neighbors, + # and KDTree is generally faster when available + if (self.n_neighbors is None + or self.n_neighbors < self._fit_X.shape[0] // 2): + if self.effective_metric_ in VALID_METRICS['kd_tree']: + self._fit_method = 'kd_tree' + else: + self._fit_method = 'ball_tree' else: self._fit_method = 'brute' - if self._fit_method == 'kd_tree': - self._tree = cKDTree(X, self.leaf_size) - elif self._fit_method == 'ball_tree': - self._tree = BallTree(X, self.leaf_size, p=self.p) + if self._fit_method == 'ball_tree': + self._tree = BallTree(X, self.leaf_size, + metric=self.effective_metric_, + **self.effective_metric_params_) + elif self._fit_method == 'kd_tree': + self._tree = KDTree(X, self.leaf_size, + metric=self.effective_metric_, + **self.effective_metric_params_) elif self._fit_method == 'brute': self._tree = None else: @@ -160,15 +264,17 @@ def _fit(self, X): class KNeighborsMixin(object): """Mixin for k-neighbors searches""" - def kneighbors(self, X, n_neighbors=None, return_distance=True): + def kneighbors(self, X=None, n_neighbors=None, return_distance=True): """Finds the K-neighbors of a point. Returns distance Parameters ---------- - X : array-like, last dimension same as that of fit data - The new point. + X : array-like, last dimension same as that of fit data, optional + The query point or points. + If not provided, neighbors of each indexed point are returned. + In this case, the query point is not considered its own neighbor. n_neighbors : int Number of neighbors to get (default is the value @@ -180,7 +286,7 @@ def kneighbors(self, X, n_neighbors=None, return_distance=True): Returns ------- dist : array - Array representing the lengths to point, only present if + Array representing the lengths to points, only present if return_distance=True ind : array @@ -210,69 +316,105 @@ class from an array representing our data set and ask who's [2]]...) """ - if self._fit_method == None: - raise ValueError("must fit neighbors before querying") - - X = atleast2d_or_csr(X) + if self._fit_method is None: + raise NotFittedError("Must fit neighbors before querying.") if n_neighbors is None: n_neighbors = self.n_neighbors + if X is not None: + query_is_train = False + X = check_array(X, accept_sparse='csr') + else: + query_is_train = True + X = self._fit_X + # Include an extra neighbor to account for the sample itself being + # returned, which is removed later + n_neighbors += 1 + + train_size = self._fit_X.shape[0] + if n_neighbors > train_size: + raise ValueError( + "Expected n_neighbors <= %d. Got %d" % + (train_size, n_neighbors) + ) + n_samples, _ = X.shape + sample_range = np.arange(n_samples)[:, None] + if self._fit_method == 'brute': - if self.p == 1: - dist = pairwise_distances(X, self._fit_X, 'manhattan') - elif self.p == 2: + # for efficiency, use squared euclidean distances + if self.effective_metric_ == 'euclidean': dist = pairwise_distances(X, self._fit_X, 'euclidean', squared=True) - elif self.p == np.inf: - dist = pairwise_distances(X, self._fit_X, 'chebyshev') else: - dist = pairwise_distances(X, self._fit_X, 'minkowski', - p=self.p) - # XXX: should be implemented with a partial sort - neigh_ind = dist.argsort(axis=1) - if self.warn_on_equidistant and n_neighbors < self._fit_X.shape[0]: - ii = np.arange(dist.shape[0]) - ind_k = neigh_ind[:, n_neighbors - 1] - ind_k1 = neigh_ind[:, n_neighbors] - if np.any(dist[ii, ind_k] == dist[ii, ind_k1]): - warn_equidistant() + dist = pairwise_distances(X, self._fit_X, + self.effective_metric_, + **self.effective_metric_params_) + + neigh_ind = argpartition(dist, n_neighbors - 1, axis=1) neigh_ind = neigh_ind[:, :n_neighbors] + # argpartition doesn't guarantee sorted order, so we sort again + neigh_ind = neigh_ind[ + sample_range, np.argsort(dist[sample_range, neigh_ind])] + if return_distance: - j = np.arange(neigh_ind.shape[0])[:, None] - if self.p == 2: - return np.sqrt(dist[j, neigh_ind]), neigh_ind + if self.effective_metric_ == 'euclidean': + result = np.sqrt(dist[sample_range, neigh_ind]), neigh_ind else: - return dist[j, neigh_ind], neigh_ind + result = dist[sample_range, neigh_ind], neigh_ind else: - return neigh_ind - elif self._fit_method == 'ball_tree': + result = neigh_ind + + elif self._fit_method in ['ball_tree', 'kd_tree']: + if issparse(X): + raise ValueError( + "%s does not work with sparse matrices. Densify the data, " + "or set algorithm='brute'" % self._fit_method) result = self._tree.query(X, n_neighbors, return_distance=return_distance) - if self.warn_on_equidistant and self._tree.warning_flag: - warn_equidistant() + else: + raise ValueError("internal: _fit_method not recognized") + + if not query_is_train: return result - elif self._fit_method == 'kd_tree': - dist, ind = self._tree.query(X, n_neighbors, p=self.p) - # kd_tree returns a 1D array for n_neighbors = 1 - if n_neighbors == 1: - dist = dist[:, None] - ind = ind[:, None] + + else: + # If the query data is the same as the indexed data, we would like + # to ignore the first nearest neighbor of every sample, i.e + # the sample itself. if return_distance: - return dist, ind + dist, neigh_ind = result else: - return ind - else: - raise ValueError("internal: _fit_method not recognized") + neigh_ind = result + + sample_mask = neigh_ind != sample_range + + # Corner case: When the number of duplicates are more + # than the number of neighbors, the first NN will not + # be the sample, but a duplicate. + # In that case mask the first duplicate. + dup_gr_nbrs = np.all(sample_mask, axis=1) + sample_mask[:, 0][dup_gr_nbrs] = False + + neigh_ind = np.reshape( + neigh_ind[sample_mask], (n_samples, n_neighbors - 1)) + + if return_distance: + dist = np.reshape( + dist[sample_mask], (n_samples, n_neighbors - 1)) + return dist, neigh_ind + return neigh_ind - def kneighbors_graph(self, X, n_neighbors=None, + def kneighbors_graph(self, X=None, n_neighbors=None, mode='connectivity'): """Computes the (weighted) graph of k-Neighbors for points in X Parameters ---------- - X : array-like, shape = [n_samples, n_features] - Sample data + X : array-like, last dimension same as that of fit data, optional + The query point or points. + If not provided, neighbors of each indexed point are returned. + In this case, the query point is not considered its own neighbor. n_neighbors : int Number of neighbors for each sample. @@ -297,56 +439,69 @@ def kneighbors_graph(self, X, n_neighbors=None, >>> neigh.fit(X) # doctest: +ELLIPSIS NearestNeighbors(algorithm='auto', leaf_size=30, ...) >>> A = neigh.kneighbors_graph(X) - >>> A.todense() - matrix([[ 1., 0., 1.], - [ 0., 1., 1.], - [ 1., 0., 1.]]) + >>> A.toarray() + array([[ 1., 0., 1.], + [ 0., 1., 1.], + [ 1., 0., 1.]]) See also -------- NearestNeighbors.radius_neighbors_graph """ - X = np.asarray(X) - if n_neighbors is None: n_neighbors = self.n_neighbors - n_samples1 = X.shape[0] + # kneighbors does the None handling. + if X is not None: + X = check_array(X, accept_sparse='csr') + n_samples1 = X.shape[0] + else: + n_samples1 = self._fit_X.shape[0] + n_samples2 = self._fit_X.shape[0] n_nonzero = n_samples1 * n_neighbors A_indptr = np.arange(0, n_nonzero + 1, n_neighbors) # construct CSR matrix representation of the k-NN graph if mode == 'connectivity': - A_data = np.ones((n_samples1, n_neighbors)) + A_data = np.ones(n_samples1 * n_neighbors) A_ind = self.kneighbors(X, n_neighbors, return_distance=False) elif mode == 'distance': - data, ind = self.kneighbors(X, n_neighbors + 1, - return_distance=True) - A_data, A_ind = data[:, 1:], ind[:, 1:] + A_data, A_ind = self.kneighbors( + X, n_neighbors, return_distance=True) + A_data = np.ravel(A_data) else: raise ValueError( 'Unsupported mode, must be one of "connectivity" ' 'or "distance" but got "%s" instead' % mode) - return csr_matrix((A_data.ravel(), A_ind.ravel(), A_indptr), - shape=(n_samples1, n_samples2)) + kneighbors_graph = csr_matrix((A_data, A_ind.ravel(), A_indptr), + shape=(n_samples1, n_samples2)) + + return kneighbors_graph class RadiusNeighborsMixin(object): """Mixin for radius-based neighbors searches""" - def radius_neighbors(self, X, radius=None, return_distance=True): - """Finds the neighbors of a point within a given radius. + def radius_neighbors(self, X=None, radius=None, return_distance=True): + """Finds the neighbors within a given radius of a point or points. - Returns distance + Return the indices and distances of each point from the dataset + lying in a ball with size ``radius`` around the points of the query + array. Points lying on the boundary are included in the results. + + The result points are *not* necessarily sorted by distance to their + query point. Parameters ---------- - X : array-like, last dimension same as that of fit data - The new point. + X : array-like, (n_samples, n_features), optional + The query point or points. + If not provided, neighbors of each indexed point are returned. + In this case, the query point is not considered its own neighbor. radius : float Limiting distance of neighbors to return. @@ -357,118 +512,127 @@ def radius_neighbors(self, X, radius=None, return_distance=True): Returns ------- - dist : array - Array representing the lengths to point, only present if - return_distance=True + dist : array, shape (n_samples,) of arrays + Array representing the distances to each point, only present if + return_distance=True. The distance values are computed according + to the ``metric`` constructor parameter. - ind : array - Indices of the nearest points in the population matrix. + ind : array, shape (n_samples,) of arrays + An array of arrays of indices of the approximate nearest points + from the population matrix that lie within a ball of size + ``radius`` around the query points. Examples -------- - In the following example, we construnct a NeighborsClassifier + In the following example, we construct a NeighborsClassifier class from an array representing our data set and ask who's - the closest point to [1,1,1] + the closest point to [1, 1, 1]: + >>> import numpy as np >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(radius=1.6) >>> neigh.fit(samples) # doctest: +ELLIPSIS NearestNeighbors(algorithm='auto', leaf_size=30, ...) - >>> print(neigh.radius_neighbors([1., 1., 1.])) # doctest: +ELLIPSIS - (array([[ 1.5, 0.5]]...), array([[1, 2]]...) + >>> rng = neigh.radius_neighbors([1., 1., 1.]) + >>> print(np.asarray(rng[0][0])) # doctest: +ELLIPSIS + [ 1.5 0.5] + >>> print(np.asarray(rng[1][0])) # doctest: +ELLIPSIS + [1 2] The first array returned contains the distances to all points which are closer than 1.6, while the second array returned contains their indices. In general, multiple points can be queried at the same time. + + Notes + ----- Because the number of neighbors of each point is not necessarily - equal, `radius_neighbors` returns an array of objects, where each - object is a 1D array of indices. + equal, the results for multiple query points cannot be fit in a + standard data array. + For efficiency, `radius_neighbors` returns arrays of objects, where + each object is a 1D array of indices or distances. """ + if self._fit_method is None: + raise NotFittedError("Must fit neighbors before querying.") - if self._fit_method == None: - raise ValueError("must fit neighbors before querying") - - X = atleast2d_or_csr(X) + if X is not None: + query_is_train = False + X = check_array(X, accept_sparse='csr') + else: + query_is_train = True + X = self._fit_X if radius is None: radius = self.radius + n_samples = X.shape[0] if self._fit_method == 'brute': - if self.p == 1: - dist = pairwise_distances(X, self._fit_X, 'manhattan') - elif self.p == 2: + # for efficiency, use squared euclidean distances + if self.effective_metric_ == 'euclidean': dist = pairwise_distances(X, self._fit_X, 'euclidean', squared=True) radius *= radius - elif self.p == np.inf: - dist = pairwise_distances(X, self._fit_X, 'chebyshev') else: - dist = pairwise_distances(X, self._fit_X, 'minkowski', - p=self.p) + dist = pairwise_distances(X, self._fit_X, + self.effective_metric_, + **self.effective_metric_params_) - neigh_ind = [np.where(d < radius)[0] for d in dist] + neigh_ind_list = [np.where(d <= radius)[0] for d in dist] - # if there are the same number of neighbors for each point, - # we can do a normal array. Otherwise, we return an object - # array with elements that are numpy arrays - try: - neigh_ind = np.asarray(neigh_ind, dtype=int) - dtype_F = float - except ValueError: - neigh_ind = np.asarray(neigh_ind, dtype='object') - dtype_F = object + # See https://github.com/numpy/numpy/issues/5456 + # if you want to understand why this is initialized this way. + neigh_ind = np.empty(n_samples, dtype='object') + neigh_ind[:] = neigh_ind_list if return_distance: - if self.p == 2: - dist = np.array([np.sqrt(d[neigh_ind[i]]) \ - for i, d in enumerate(dist)], - dtype=dtype_F) + dist_array = np.empty(n_samples, dtype='object') + if self.effective_metric_ == 'euclidean': + dist_list = [np.sqrt(d[neigh_ind[i]]) + for i, d in enumerate(dist)] else: - dist = np.array([d[neigh_ind[i]] \ - for i, d in enumerate(dist)], - dtype=dtype_F) - return dist, neigh_ind + dist_list = [d[neigh_ind[i]] + for i, d in enumerate(dist)] + dist_array[:] = dist_list + + results = dist_array, neigh_ind else: - return neigh_ind - elif self._fit_method == 'ball_tree': + results = neigh_ind + + elif self._fit_method in ['ball_tree', 'kd_tree']: + if issparse(X): + raise ValueError( + "%s does not work with sparse matrices. Densify the data, " + "or set algorithm='brute'" % self._fit_method) + results = self._tree.query_radius(X, radius, + return_distance=return_distance) if return_distance: - ind, dist = self._tree.query_radius(X, radius, - return_distance=True) - return dist, ind - else: - ind = self._tree.query_radius(X, radius, - return_distance=False) - return ind - elif self._fit_method == 'kd_tree': - Npts = self._fit_X.shape[0] - dist, ind = self._tree.query(X, Npts, - distance_upper_bound=radius, - p=self.p) - - ind = [ind_i[:ind_i.searchsorted(Npts)] for ind_i in ind] - - # if there are the same number of neighbors for each point, - # we can do a normal array. Otherwise, we return an object - # array with elements that are numpy arrays - try: - ind = np.asarray(ind, dtype=int) - dtype_F = float - except ValueError: - ind = np.asarray(ind, dtype='object') - dtype_F = object + results = results[::-1] + else: + raise ValueError("internal: _fit_method not recognized") + if not query_is_train: + return results + else: + # If the query data is the same as the indexed data, we would like + # to ignore the first nearest neighbor of every sample, i.e + # the sample itself. if return_distance: - dist = np.array([dist_i[:len(ind[i])] - for i, dist_i in enumerate(dist)], - dtype=dtype_F) - return dist, ind + dist, neigh_ind = results else: - return ind - else: - raise ValueError("internal: _fit_method not recognized") + neigh_ind = results - def radius_neighbors_graph(self, X, radius=None, mode='connectivity'): + for ind, ind_neighbor in enumerate(neigh_ind): + mask = ind_neighbor != ind + + neigh_ind[ind] = ind_neighbor[mask] + if return_distance: + dist[ind] = dist[ind][mask] + + if return_distance: + return dist, neigh_ind + return neigh_ind + + def radius_neighbors_graph(self, X=None, radius=None, mode='connectivity'): """Computes the (weighted) graph of Neighbors for points in X Neighborhoods are restricted the points at a distance lower than @@ -476,8 +640,10 @@ def radius_neighbors_graph(self, X, radius=None, mode='connectivity'): Parameters ---------- - X : array-like, shape = [n_samples, n_features] - Sample data + X : array-like, shape = [n_samples, n_features], optional + The query point or points. + If not provided, neighbors of each indexed point are returned. + In this case, the query point is not considered its own neighbor. radius : float Radius of neighborhoods. @@ -501,23 +667,22 @@ def radius_neighbors_graph(self, X, radius=None, mode='connectivity'): >>> neigh.fit(X) # doctest: +ELLIPSIS NearestNeighbors(algorithm='auto', leaf_size=30, ...) >>> A = neigh.radius_neighbors_graph(X) - >>> A.todense() - matrix([[ 1., 0., 1.], - [ 0., 1., 0.], - [ 1., 0., 1.]]) + >>> A.toarray() + array([[ 1., 0., 1.], + [ 0., 1., 0.], + [ 1., 0., 1.]]) See also -------- kneighbors_graph """ - X = np.asarray(X) + if X is not None: + X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) + n_samples2 = self._fit_X.shape[0] if radius is None: radius = self.radius - n_samples1 = X.shape[0] - n_samples2 = self._fit_X.shape[0] - # construct CSR matrix representation of the NN graph if mode == 'connectivity': A_ind = self.radius_neighbors(X, radius, @@ -532,11 +697,11 @@ def radius_neighbors_graph(self, X, radius=None, mode='connectivity'): 'Unsupported mode, must be one of "connectivity", ' 'or "distance" but got %s instead' % mode) + n_samples1 = A_ind.shape[0] n_neighbors = np.array([len(a) for a in A_ind]) - n_nonzero = np.sum(n_neighbors) - if A_data is None: - A_data = np.ones(n_nonzero) A_ind = np.concatenate(list(A_ind)) + if A_data is None: + A_data = np.ones(len(A_ind)) A_indptr = np.concatenate((np.zeros(1, dtype=int), np.cumsum(n_neighbors))) @@ -550,14 +715,15 @@ def fit(self, X, y): Parameters ---------- - X : {array-like, sparse matrix, BallTree, cKDTree} - Training data. If array or matrix, then the shape - is [n_samples, n_features] + X : {array-like, sparse matrix, BallTree, KDTree} + Training data. If array or matrix, shape = [n_samples, n_features] - y : {array-like, sparse matrix}, shape = [n_samples] - Target values, array of float values. + y : {array-like, sparse matrix} + Target values, array of float values, shape = [n_samples] + or [n_samples, n_outputs] """ - X, y = check_arrays(X, y, sparse_format="csr") + if not isinstance(X, (KDTree, BallTree)): + X, y = check_X_y(X, y, "csr", multi_output=True) self._y = y return self._fit(X) @@ -568,16 +734,38 @@ def fit(self, X, y): Parameters ---------- - X : {array-like, sparse matrix, BallTree, cKDTree} - Training data. If array or matrix, then the shape - is [n_samples, n_features] + X : {array-like, sparse matrix, BallTree, KDTree} + Training data. If array or matrix, shape = [n_samples, n_features] + + y : {array-like, sparse matrix} + Target values of shape = [n_samples] or [n_samples, n_outputs] - y : {array-like, sparse matrix}, shape = [n_samples] - Target values, array of integer values. """ - X, y = check_arrays(X, y, sparse_format="csr") - self._y = y - self._classes = np.sort(np.unique(y)) + if not isinstance(X, (KDTree, BallTree)): + X, y = check_X_y(X, y, "csr", multi_output=True) + + if y.ndim == 1 or y.ndim == 2 and y.shape[1] == 1: + if y.ndim != 1: + warnings.warn("A column-vector y was passed when a 1d array " + "was expected. Please change the shape of y to " + "(n_samples, ), for example using ravel().", + DataConversionWarning, stacklevel=2) + + self.outputs_2d_ = False + y = y.reshape((-1, 1)) + else: + self.outputs_2d_ = True + + self.classes_ = [] + self._y = np.empty(y.shape, dtype=np.int) + for k in range(self._y.shape[1]): + classes, self._y[:, k] = np.unique(y[:, k], return_inverse=True) + self.classes_.append(classes) + + if not self.outputs_2d_: + self.classes_ = self.classes_[0] + self._y = self._y.ravel() + return self._fit(X) @@ -587,7 +775,7 @@ def fit(self, X, y=None): Parameters ---------- - X : {array-like, sparse matrix, BallTree, cKDTree} + X : {array-like, sparse matrix, BallTree, KDTree} Training data. If array or matrix, shape = [n_samples, n_features] """ return self._fit(X) diff --git a/sklearn/neighbors/binary_tree.pxi b/sklearn/neighbors/binary_tree.pxi new file mode 100644 index 0000000000000..099b46465f7b4 --- /dev/null +++ b/sklearn/neighbors/binary_tree.pxi @@ -0,0 +1,2521 @@ +#!python + +# KD Tree and Ball Tree +# ===================== +# +# Author: Jake Vanderplas , 2012-2013 +# License: BSD +# +# This file is meant to be a literal include in a pyx file. +# See ball_tree.pyx and kd_tree.pyx +# +# The routines here are the core algorithms of the KDTree and BallTree +# structures. If Cython supported polymorphism, we would be able to +# create a subclass and derive KDTree and BallTree from it. Because +# polymorphism is not an option, we use this single BinaryTree class +# as a literal include to avoid duplicating the entire file. +# +# A series of functions are implemented in kd_tree.pyx and ball_tree.pyx +# which use the information here to calculate the lower and upper bounds +# between a node and a point, and between two nodes. These functions are +# used here, and are all that are needed to differentiate between the two +# tree types. +# +# Description of Binary Tree Algorithms +# ------------------------------------- +# A binary tree can be thought of as a collection of nodes. The top node +# contains all the points. The next level consists of two nodes with half +# the points in each, and this continues recursively. Each node contains +# metadata which allow fast computation of distance bounds: in the case of +# a ball tree, the metadata is a center and a radius. In the case of a +# KD tree, the metadata is the minimum and maximum bound along each dimension. +# +# In a typical KD Tree or Ball Tree implementation, the nodes are implemented +# as dynamically allocated structures with pointers linking them. Here we +# take a different approach, storing all relevant data in a set of arrays +# so that the entire tree object can be saved in a pickle file. For efficiency, +# the data can be stored in such a way that explicit pointers are not +# necessary: for node data stored at index i, the two child nodes are at +# index (2 * i + 1) and (2 * i + 2); the parent node is (i - 1) // 2 +# (where // indicates integer division). +# +# The data arrays used here are as follows: +# data : the [n_samples x n_features] array of data from which the tree +# is built +# idx_array : the length n_samples array used to keep track of the indices +# of data within each node. Each node has values idx_start and +# idx_end: the points within the node are given by (using numpy +# syntax) data[idx_array[idx_start:idx_end]]. +# node_data : the length n_nodes array of structures which store the node +# indices, node radii, and leaf information for each node. +# node_bounds : the [* x n_nodes x n_features] array containing the node +# bound information. For ball tree, the first dimension is 1, and +# each row contains the centroid of the node. For kd tree, the first +# dimension is 2 and the rows for each point contain the arrays of +# lower bounds and upper bounds in each direction. +# +# The lack of dynamic allocation means the number of nodes must be computed +# before the building of the tree. This can be done assuming the points are +# divided equally between child nodes at each step; although this removes +# some flexibility in tree creation, it ensures a balanced tree and ensures +# that the number of nodes required can be computed beforehand. Given a +# specified leaf_size (the minimum number of points in any node), it is +# possible to show that a balanced tree will have +# +# n_levels = 1 + max(0, floor(log2((n_samples - 1) / leaf_size))) +# +# in order to satisfy +# +# leaf_size <= min(n_points) <= 2 * leaf_size +# +# with the exception of the special case where n_samples < leaf_size. +# for a given number of levels, the number of nodes in the tree is given by +# +# n_nodes = 2 ** n_levels - 1 +# +# both these results can be straightforwardly shown by induction. The +# following code uses these values in the construction of the tree. +# +# Distance Metrics +# ---------------- +# For flexibility, the trees can be built using a variety of distance metrics. +# The metrics are described in the DistanceMetric class: the standard +# Euclidean distance is the default, and is inlined to be faster than other +# metrics. In addition, each metric defines both a distance and a +# "reduced distance", which is often faster to compute, and is therefore +# used in the query architecture whenever possible. (For example, in the +# case of the standard Euclidean distance, the reduced distance is the +# squared-distance). +# +# Implementation Notes +# -------------------- +# This implementation uses the common object-oriented approach of having an +# abstract base class which is extended by the KDTree and BallTree +# specializations. +# +# The BinaryTree "base class" is defined here and then subclassed in the BallTree +# and KDTree pyx files. These files include implementations of the +# "abstract" methods. + +# Necessary Helper Functions +# -------------------------- +# These are the names and descriptions of the "abstract" functions which are +# defined in kd_tree.pyx and ball_tree.pyx: + +# cdef int allocate_data(BinaryTree tree, ITYPE_t n_nodes, ITYPE_t n_features): +# """Allocate arrays needed for the KD Tree""" + +# cdef int init_node(BinaryTree tree, ITYPE_t i_node, +# ITYPE_t idx_start, ITYPE_t idx_end): +# """Initialize the node for the dataset stored in tree.data""" + +# cdef DTYPE_t min_rdist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt): +# """Compute the minimum reduced-distance between a point and a node""" + +# cdef DTYPE_t min_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt): +# """Compute the minimum distance between a point and a node""" + +# cdef DTYPE_t max_rdist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt): +# """Compute the maximum reduced-distance between a point and a node""" + +# cdef DTYPE_t max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt): +# """Compute the maximum distance between a point and a node""" + +# cdef inline int min_max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt, +# DTYPE_t* min_dist, DTYPE_t* max_dist): +# """Compute the minimum and maximum distance between a point and a node""" + +# cdef inline DTYPE_t min_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, +# BinaryTree tree2, ITYPE_t i_node2): +# """Compute the minimum reduced distance between two nodes""" + +# cdef inline DTYPE_t min_dist_dual(BinaryTree tree1, ITYPE_t i_node1, +# BinaryTree tree2, ITYPE_t i_node2): +# """Compute the minimum distance between two nodes""" + +# cdef inline DTYPE_t max_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, +# BinaryTree tree2, ITYPE_t i_node2): +# """Compute the maximum reduced distance between two nodes""" + +# cdef inline DTYPE_t max_dist_dual(BinaryTree tree1, ITYPE_t i_node1, +# BinaryTree tree2, ITYPE_t i_node2): +# """Compute the maximum distance between two nodes""" + +cimport cython +cimport numpy as np +from libc.math cimport fabs, sqrt, exp, cos, pow, log +from sklearn.utils.lgamma cimport lgamma + +import numpy as np +import warnings +from ..utils import check_array + +from typedefs cimport DTYPE_t, ITYPE_t, DITYPE_t +from typedefs import DTYPE, ITYPE + +from dist_metrics cimport (DistanceMetric, euclidean_dist, euclidean_rdist, + euclidean_dist_to_rdist, euclidean_rdist_to_dist) + +# some handy constants +cdef DTYPE_t INF = np.inf +cdef DTYPE_t NEG_INF = -np.inf +cdef DTYPE_t PI = np.pi +cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) +cdef DTYPE_t LOG_PI = log(PI) +cdef DTYPE_t LOG_2PI = log(2 * PI) + + +# Some compound datatypes used below: +cdef struct NodeHeapData_t: + DTYPE_t val + ITYPE_t i1 + ITYPE_t i2 + +# build the corresponding numpy dtype for NodeHeapData +# There is no offsetof() function in cython, so we hack it. +# If we can ensure numpy 1.5 or greater, a cleaner way is to do +# cdef NodeHeapData_t nhd_tmp +# NodeHeapData = np.asarray((&nhd_tmp)).dtype +cdef NodeHeapData_t nhd_tmp +offsets = [&(nhd_tmp.val) - &nhd_tmp, + &(nhd_tmp.i1) - &nhd_tmp, + &(nhd_tmp.i2) - &nhd_tmp] +NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], + 'formats': [DTYPE, ITYPE, ITYPE], + 'offsets': offsets, + 'itemsize': sizeof(NodeHeapData_t)}) + +cdef struct NodeData_t: + ITYPE_t idx_start + ITYPE_t idx_end + ITYPE_t is_leaf + DTYPE_t radius + +# build the corresponding numpy dtype for NodeData +# There is no offsetof() function in cython, so we hack it. +# If we can ensure numpy 1.5 or greater, a cleaner way is to do +# cdef NodeData_t nd_tmp +# NodeData = np.asarray((&nd_tmp)).dtype +cdef NodeData_t nd_tmp +offsets = [&(nd_tmp.idx_start) - &nd_tmp, + &(nd_tmp.idx_end) - &nd_tmp, + &(nd_tmp.is_leaf) - &nd_tmp, + &(nd_tmp.radius) - &nd_tmp] +NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], + 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], + 'offsets': offsets, + 'itemsize': sizeof(NodeData_t)}) + + +###################################################################### +# Numpy 1.3-1.4 compatibility utilities +cdef DTYPE_t[::1] get_memview_DTYPE_1D( + np.ndarray[DTYPE_t, ndim=1, mode='c'] X): + return ( X.data) + + +cdef DTYPE_t[:, ::1] get_memview_DTYPE_2D( + np.ndarray[DTYPE_t, ndim=2, mode='c'] X): + return ( X.data) + + +cdef DTYPE_t[:, :, ::1] get_memview_DTYPE_3D( + np.ndarray[DTYPE_t, ndim=3, mode='c'] X): + return \ + ( X.data) + + +cdef ITYPE_t[::1] get_memview_ITYPE_1D( + np.ndarray[ITYPE_t, ndim=1, mode='c'] X): + return ( X.data) + + +cdef ITYPE_t[:, ::1] get_memview_ITYPE_2D( + np.ndarray[ITYPE_t, ndim=2, mode='c'] X): + return ( X.data) + + +cdef NodeHeapData_t[::1] get_memview_NodeHeapData_1D( + np.ndarray[NodeHeapData_t, ndim=1, mode='c'] X): + return ( X.data) + + +cdef NodeData_t[::1] get_memview_NodeData_1D( + np.ndarray[NodeData_t, ndim=1, mode='c'] X): + return ( X.data) + +###################################################################### + + + +###################################################################### +# Define doc strings, substituting the appropriate class name using +# the DOC_DICT variable defined in the pyx files. +CLASS_DOC = \ +"""{BinaryTree} for fast generalized N-point problems + +{BinaryTree}(X, leaf_size=40, metric='minkowski', **kwargs) + +Parameters +---------- +X : array-like, shape = [n_samples, n_features] + n_samples is the number of points in the data set, and + n_features is the dimension of the parameter space. + Note: if X is a C-contiguous array of doubles then data will + not be copied. Otherwise, an internal copy will be made. + +leaf_size : positive integer (default = 20) + Number of points at which to switch to brute-force. Changing + leaf_size will not affect the results of a query, but can + significantly impact the speed of a query and the memory required + to store the constructed tree. The amount of memory needed to + store the tree scales as approximately n_samples / leaf_size. + For a specified ``leaf_size``, a leaf node is guaranteed to + satisfy ``leaf_size <= n_points <= 2 * leaf_size``, except in + the case that ``n_samples < leaf_size``. + +metric : string or DistanceMetric object + the distance metric to use for the tree. Default='minkowski' + with p=2 (that is, a euclidean metric). See the documentation + of the DistanceMetric class for a list of available metrics. + {binary_tree}.valid_metrics gives a list of the metrics which + are valid for {BinaryTree}. + +Additional keywords are passed to the distance metric class. + +Attributes +---------- +data : np.ndarray + The training data + +Examples +-------- +Query for k-nearest neighbors + + >>> import numpy as np + + >>> np.random.seed(0) + >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions + >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP + >>> dist, ind = tree.query(X[0], k=3) # doctest: +SKIP + >>> print ind # indices of 3 closest neighbors + [0 3 1] + >>> print dist # distances to 3 closest neighbors + [ 0. 0.19662693 0.29473397] + +Pickle and Unpickle a tree. Note that the state of the tree is saved in the +pickle operation: the tree needs not be rebuilt upon unpickling. + + >>> import numpy as np + >>> import pickle + >>> np.random.seed(0) + >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions + >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP + >>> s = pickle.dumps(tree) # doctest: +SKIP + >>> tree_copy = pickle.loads(s) # doctest: +SKIP + >>> dist, ind = tree_copy.query(X[0], k=3) # doctest: +SKIP + >>> print ind # indices of 3 closest neighbors + [0 3 1] + >>> print dist # distances to 3 closest neighbors + [ 0. 0.19662693 0.29473397] + +Query for neighbors within a given radius + + >>> import numpy as np + >>> np.random.seed(0) + >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions + >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP + >>> print tree.query_radius(X[0], r=0.3, count_only=True) + 3 + >>> ind = tree.query_radius(X[0], r=0.3) # doctest: +SKIP + >>> print ind # indices of neighbors within distance 0.3 + [3 0 1] + + +Compute a gaussian kernel density estimate: + + >>> import numpy as np + >>> np.random.seed(1) + >>> X = np.random.random((100, 3)) + >>> tree = {BinaryTree}(X) # doctest: +SKIP + >>> tree.kernel_density(X[:3], h=0.1, kernel='gaussian') + array([ 6.94114649, 7.83281226, 7.2071716 ]) + +Compute a two-point auto-correlation function + + >>> import numpy as np + >>> np.random.seed(0) + >>> X = np.random.random((30, 3)) + >>> r = np.linspace(0, 1, 5) + >>> tree = {BinaryTree}(X) # doctest: +SKIP + >>> tree.two_point_correlation(X, r) + array([ 30, 62, 278, 580, 820]) + +""" + + +###################################################################### +# Utility functions +cdef DTYPE_t logaddexp(DTYPE_t x1, DTYPE_t x2): + """logaddexp(x1, x2) -> log(exp(x1) + exp(x2))""" + cdef DTYPE_t a = fmax(x1, x2) + if a == NEG_INF: + return NEG_INF + else: + return a + log(exp(x1 - a) + exp(x2 - a)) + +cdef DTYPE_t logsubexp(DTYPE_t x1, DTYPE_t x2): + """logsubexp(x1, x2) -> log(exp(x1) - exp(x2))""" + if x1 <= x2: + return NEG_INF + else: + return x1 + log(1 - exp(x2 - x1)) + + +###################################################################### +# Kernel functions +# +# Note: Kernels assume dist is non-negative and and h is positive +# All kernel functions are normalized such that K(0, h) = 1. +# The fully normalized kernel is: +# K = exp[kernel_norm(h, d, kernel) + compute_kernel(dist, h, kernel)] +# The code only works with non-negative kernels: i.e. K(d, h) >= 0 +# for all valid d and h. Note that for precision, the log of both +# the kernel and kernel norm is returned. +cdef enum KernelType: + GAUSSIAN_KERNEL = 1 + TOPHAT_KERNEL = 2 + EPANECHNIKOV_KERNEL = 3 + EXPONENTIAL_KERNEL = 4 + LINEAR_KERNEL = 5 + COSINE_KERNEL = 6 + + +cdef inline DTYPE_t log_gaussian_kernel(DTYPE_t dist, DTYPE_t h): + """log of the gaussian kernel for bandwidth h (unnormalized)""" + return -0.5 * (dist * dist) / (h * h) + + +cdef inline DTYPE_t log_tophat_kernel(DTYPE_t dist, DTYPE_t h): + """log of the tophat kernel for bandwidth h (unnormalized)""" + if dist < h: + return 0.0 + else: + return NEG_INF + + +cdef inline DTYPE_t log_epanechnikov_kernel(DTYPE_t dist, DTYPE_t h): + """log of the epanechnikov kernel for bandwidth h (unnormalized)""" + if dist < h: + return log(1.0 - (dist * dist) / (h * h)) + else: + return NEG_INF + + +cdef inline DTYPE_t log_exponential_kernel(DTYPE_t dist, DTYPE_t h): + """log of the exponential kernel for bandwidth h (unnormalized)""" + return -dist / h + + +cdef inline DTYPE_t log_linear_kernel(DTYPE_t dist, DTYPE_t h): + """log of the linear kernel for bandwidth h (unnormalized)""" + if dist < h: + return log(1 - dist / h) + else: + return NEG_INF + + +cdef inline DTYPE_t log_cosine_kernel(DTYPE_t dist, DTYPE_t h): + """log of the cosine kernel for bandwidth h (unnormalized)""" + if dist < h: + return log(cos(0.5 * PI * dist / h)) + else: + return NEG_INF + + +cdef inline DTYPE_t compute_log_kernel(DTYPE_t dist, DTYPE_t h, + KernelType kernel): + """Given a KernelType enumeration, compute the appropriate log-kernel""" + if kernel == GAUSSIAN_KERNEL: + return log_gaussian_kernel(dist, h) + elif kernel == TOPHAT_KERNEL: + return log_tophat_kernel(dist, h) + elif kernel == EPANECHNIKOV_KERNEL: + return log_epanechnikov_kernel(dist, h) + elif kernel == EXPONENTIAL_KERNEL: + return log_exponential_kernel(dist, h) + elif kernel == LINEAR_KERNEL: + return log_linear_kernel(dist, h) + elif kernel == COSINE_KERNEL: + return log_cosine_kernel(dist, h) + + +#------------------------------------------------------------ +# Kernel norms are defined via the volume element V_n +# and surface element S_(n-1) of an n-sphere. +cdef DTYPE_t logVn(ITYPE_t n): + """V_n = pi^(n/2) / gamma(n/2 - 1)""" + return 0.5 * n * LOG_PI - lgamma(0.5 * n + 1) + + +cdef DTYPE_t logSn(ITYPE_t n): + """V_(n+1) = int_0^1 S_n r^n dr""" + return LOG_2PI + logVn(n - 1) + + +cdef DTYPE_t _log_kernel_norm(DTYPE_t h, ITYPE_t d, + KernelType kernel) except -1: + """Given a KernelType enumeration, compute the kernel normalization. + + h is the bandwidth, d is the dimension. + """ + cdef DTYPE_t tmp, factor = 0 + cdef ITYPE_t k + if kernel == GAUSSIAN_KERNEL: + factor = 0.5 * d * LOG_2PI + elif kernel == TOPHAT_KERNEL: + factor = logVn(d) + elif kernel == EPANECHNIKOV_KERNEL: + factor = logVn(d) + log(2. / (d + 2.)) + elif kernel == EXPONENTIAL_KERNEL: + factor = logSn(d - 1) + lgamma(d) + elif kernel == LINEAR_KERNEL: + factor = logVn(d) - log(d + 1.) + elif kernel == COSINE_KERNEL: + # this is derived from a chain rule integration + factor = 0 + tmp = 2. / PI + for k in range(1, d + 1, 2): + factor += tmp + tmp *= -(d - k) * (d - k - 1) * (2. / PI) ** 2 + factor = log(factor) + logSn(d - 1) + else: + raise ValueError("Kernel code not recognized") + return -factor - d * log(h) + + +def kernel_norm(h, d, kernel, return_log=False): + """Given a string specification of a kernel, compute the normalization. + + Parameters + ---------- + h : float + the bandwidth of the kernel + d : int + the dimension of the space in which the kernel norm is computed + kernel : string + The kernel identifier. Must be one of + ['gaussian'|'tophat'|'epanechnikov'| + 'exponential'|'linear'|'cosine'] + return_log : boolean + if True, return the log of the kernel norm. Otherwise, return the + kernel norm. + Returns + ------- + knorm or log_knorm : float + the kernel norm or logarithm of the kernel norm. + """ + if kernel == 'gaussian': + result = _log_kernel_norm(h, d, GAUSSIAN_KERNEL) + elif kernel == 'tophat': + result = _log_kernel_norm(h, d, TOPHAT_KERNEL) + elif kernel == 'epanechnikov': + result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) + elif kernel == 'exponential': + result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) + elif kernel == 'linear': + result = _log_kernel_norm(h, d, LINEAR_KERNEL) + elif kernel == 'cosine': + result = _log_kernel_norm(h, d, COSINE_KERNEL) + else: + raise ValueError('kernel not recognized') + + if return_log: + return result + else: + return np.exp(result) + + +###################################################################### +# Tree Utility Routines +cdef inline void swap(DITYPE_t* arr, ITYPE_t i1, ITYPE_t i2): + """swap the values at index i1 and i2 of arr""" + cdef DITYPE_t tmp = arr[i1] + arr[i1] = arr[i2] + arr[i2] = tmp + + +cdef inline void dual_swap(DTYPE_t* darr, ITYPE_t* iarr, + ITYPE_t i1, ITYPE_t i2): + """swap the values at inex i1 and i2 of both darr and iarr""" + cdef DTYPE_t dtmp = darr[i1] + darr[i1] = darr[i2] + darr[i2] = dtmp + + cdef ITYPE_t itmp = iarr[i1] + iarr[i1] = iarr[i2] + iarr[i2] = itmp + + +cdef class NeighborsHeap: + """A max-heap structure to keep track of distances/indices of neighbors + + This implements an efficient pre-allocated set of fixed-size heaps + for chasing neighbors, holding both an index and a distance. + When any row of the heap is full, adding an additional point will push + the furthest point off the heap. + + Parameters + ---------- + n_pts : int + the number of heaps to use + n_nbrs : int + the size of each heap. + """ + cdef np.ndarray distances_arr + cdef np.ndarray indices_arr + + cdef DTYPE_t[:, ::1] distances + cdef ITYPE_t[:, ::1] indices + + def __cinit__(self): + self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') + self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + self.distances = get_memview_DTYPE_2D(self.distances_arr) + self.indices = get_memview_ITYPE_2D(self.indices_arr) + + def __init__(self, n_pts, n_nbrs): + self.distances_arr = np.inf + np.zeros((n_pts, n_nbrs), dtype=DTYPE, + order='C') + self.indices_arr = np.zeros((n_pts, n_nbrs), dtype=ITYPE, order='C') + self.distances = get_memview_DTYPE_2D(self.distances_arr) + self.indices = get_memview_ITYPE_2D(self.indices_arr) + + def get_arrays(self, sort=True): + """Get the arrays of distances and indices within the heap. + + If sort=True, then simultaneously sort the indices and distances, + so the closer points are listed first. + """ + if sort: + self._sort() + return self.distances_arr, self.indices_arr + + cdef inline DTYPE_t largest(self, ITYPE_t row) except -1: + """Return the largest distance in the given row""" + return self.distances[row, 0] + + cpdef int push(self, ITYPE_t row, DTYPE_t val, ITYPE_t i_val) except -1: + """push (val, i_val) into the given row""" + cdef ITYPE_t i, ic1, ic2, i_swap + cdef ITYPE_t size = self.distances.shape[1] + cdef DTYPE_t* dist_arr = &self.distances[row, 0] + cdef ITYPE_t* ind_arr = &self.indices[row, 0] + + # check if val should be in heap + if val > dist_arr[0]: + return 0 + + # insert val at position zero + dist_arr[0] = val + ind_arr[0] = i_val + + #descend the heap, swapping values until the max heap criterion is met + i = 0 + while True: + ic1 = 2 * i + 1 + ic2 = ic1 + 1 + + if ic1 >= size: + break + elif ic2 >= size: + if dist_arr[ic1] > val: + i_swap = ic1 + else: + break + elif dist_arr[ic1] >= dist_arr[ic2]: + if val < dist_arr[ic1]: + i_swap = ic1 + else: + break + else: + if val < dist_arr[ic2]: + i_swap = ic2 + else: + break + + dist_arr[i] = dist_arr[i_swap] + ind_arr[i] = ind_arr[i_swap] + + i = i_swap + + dist_arr[i] = val + ind_arr[i] = i_val + + return 0 + + cdef int _sort(self) except -1: + """simultaneously sort the distances and indices""" + cdef DTYPE_t[:, ::1] distances = self.distances + cdef ITYPE_t[:, ::1] indices = self.indices + cdef ITYPE_t row + for row in range(distances.shape[0]): + _simultaneous_sort(&distances[row, 0], + &indices[row, 0], + distances.shape[1]) + return 0 + + +cdef int _simultaneous_sort(DTYPE_t* dist, ITYPE_t* idx, + ITYPE_t size) except -1: + """ + Perform a recursive quicksort on the dist array, simultaneously + performing the same swaps on the idx array. The equivalent in + numpy (though quite a bit slower) is + + def simultaneous_sort(dist, idx): + i = np.argsort(dist) + return dist[i], idx[i] + """ + cdef ITYPE_t pivot_idx, i, store_idx + cdef DTYPE_t pivot_val + + # in the small-array case, do things efficiently + if size <= 1: + pass + elif size == 2: + if dist[0] > dist[1]: + dual_swap(dist, idx, 0, 1) + elif size == 3: + if dist[0] > dist[1]: + dual_swap(dist, idx, 0, 1) + if dist[1] > dist[2]: + dual_swap(dist, idx, 1, 2) + if dist[0] > dist[1]: + dual_swap(dist, idx, 0, 1) + else: + # Determine the pivot using the median-of-three rule. + # The smallest of the three is moved to the beginning of the array, + # the middle (the pivot value) is moved to the end, and the largest + # is moved to the pivot index. + pivot_idx = size / 2 + if dist[0] > dist[size - 1]: + dual_swap(dist, idx, 0, size - 1) + if dist[size - 1] > dist[pivot_idx]: + dual_swap(dist, idx, size - 1, pivot_idx) + if dist[0] > dist[size - 1]: + dual_swap(dist, idx, 0, size - 1) + pivot_val = dist[size - 1] + + # partition indices about pivot. At the end of this operation, + # pivot_idx will contain the pivot value, everything to the left + # will be smaller, and everything to the right will be larger. + store_idx = 0 + for i in range(size - 1): + if dist[i] < pivot_val: + dual_swap(dist, idx, i, store_idx) + store_idx += 1 + dual_swap(dist, idx, store_idx, size - 1) + pivot_idx = store_idx + + # recursively sort each side of the pivot + if pivot_idx > 1: + _simultaneous_sort(dist, idx, pivot_idx) + if pivot_idx + 2 < size: + _simultaneous_sort(dist + pivot_idx + 1, + idx + pivot_idx + 1, + size - pivot_idx - 1) + return 0 + +#------------------------------------------------------------ +# find_node_split_dim: +# this computes the equivalent of +# j_max = np.argmax(np.max(data, 0) - np.min(data, 0)) +cdef ITYPE_t find_node_split_dim(DTYPE_t* data, + ITYPE_t* node_indices, + ITYPE_t n_features, + ITYPE_t n_points) except -1: + """Find the dimension with the largest spread. + + Parameters + ---------- + data : double pointer + Pointer to a 2D array of the training data, of shape [N, n_features]. + N must be greater than any of the values in node_indices. + node_indices : int pointer + Pointer to a 1D array of length n_points. This lists the indices of + each of the points within the current node. + + Returns + ------- + i_max : int + The index of the feature (dimension) within the node that has the + largest spread. + + Notes + ----- + In numpy, this operation is equivalent to + + def find_node_split_dim(data, node_indices): + return np.argmax(data[node_indices].max(0) - data[node_indices].min(0)) + + The cython version is much more efficient in both computation and memory. + """ + cdef DTYPE_t min_val, max_val, val, spread, max_spread + cdef ITYPE_t i, j, j_max + + j_max = 0 + max_spread = 0 + + for j in range(n_features): + max_val = data[node_indices[0] * n_features + j] + min_val = max_val + for i in range(1, n_points): + val = data[node_indices[i] * n_features + j] + max_val = fmax(max_val, val) + min_val = fmin(min_val, val) + spread = max_val - min_val + if spread > max_spread: + max_spread = spread + j_max = j + return j_max + + +cdef int partition_node_indices(DTYPE_t* data, + ITYPE_t* node_indices, + ITYPE_t split_dim, + ITYPE_t split_index, + ITYPE_t n_features, + ITYPE_t n_points) except -1: + """Partition points in the node into two equal-sized groups. + + Upon return, the values in node_indices will be rearranged such that + (assuming numpy-style indexing): + + data[node_indices[0:split_index], split_dim] + <= data[node_indices[split_index], split_dim] + + and + + data[node_indices[split_index], split_dim] + <= data[node_indices[split_index:n_points], split_dim] + + The algorithm is essentially a partial in-place quicksort around a + set pivot. + + Parameters + ---------- + data : double pointer + Pointer to a 2D array of the training data, of shape [N, n_features]. + N must be greater than any of the values in node_indices. + node_indices : int pointer + Pointer to a 1D array of length n_points. This lists the indices of + each of the points within the current node. This will be modified + in-place. + split_dim : int + the dimension on which to split. This will usually be computed via + the routine ``find_node_split_dim`` + split_index : int + the index within node_indices around which to split the points. + + Returns + ------- + status : int + integer exit status. On return, the contents of node_indices are + modified as noted above. + """ + cdef ITYPE_t left, right, midindex, i + cdef DTYPE_t d1, d2 + left = 0 + right = n_points - 1 + + while True: + midindex = left + for i in range(left, right): + d1 = data[node_indices[i] * n_features + split_dim] + d2 = data[node_indices[right] * n_features + split_dim] + if d1 < d2: + swap(node_indices, i, midindex) + midindex += 1 + swap(node_indices, midindex, right) + if midindex == split_index: + break + elif midindex < split_index: + left = midindex + 1 + else: + right = midindex - 1 + + return 0 + + +###################################################################### +# NodeHeap : min-heap used to keep track of nodes during +# breadth-first query +cdef inline void swap_nodes(NodeHeapData_t* arr, ITYPE_t i1, ITYPE_t i2): + cdef NodeHeapData_t tmp = arr[i1] + arr[i1] = arr[i2] + arr[i2] = tmp + + +cdef class NodeHeap: + """NodeHeap + + This is a min-heap implementation for keeping track of nodes + during a breadth-first search. Unlike the NeighborsHeap above, + the NodeHeap does not have a fixed size and must be able to grow + as elements are added. + + Internally, the data is stored in a simple binary heap which meets + the min heap condition: + + heap[i].val < min(heap[2 * i + 1].val, heap[2 * i + 2].val) + """ + cdef np.ndarray data_arr + cdef NodeHeapData_t[::1] data + cdef ITYPE_t n + + def __cinit__(self): + self.data_arr = np.zeros(1, dtype=NodeHeapData, order='C') + self.data = get_memview_NodeHeapData_1D(self.data_arr) + + def __init__(self, size_guess=100): + size_guess = max(size_guess, 1) # need space for at least one item + self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') + self.data = get_memview_NodeHeapData_1D(self.data_arr) + self.n = size_guess + self.clear() + + cdef int resize(self, ITYPE_t new_size) except -1: + """Resize the heap to be either larger or smaller""" + cdef NodeHeapData_t *data_ptr, *new_data_ptr + cdef ITYPE_t i + cdef ITYPE_t size = self.data.shape[0] + cdef np.ndarray new_data_arr = np.zeros(new_size, + dtype=NodeHeapData) + cdef NodeHeapData_t[::1] new_data =\ + get_memview_NodeHeapData_1D(new_data_arr) + + if size > 0 and new_size > 0: + data_ptr = &self.data[0] + new_data_ptr = &new_data[0] + for i in range(min(size, new_size)): + new_data_ptr[i] = data_ptr[i] + + if new_size < size: + self.n = new_size + + self.data = new_data + self.data_arr = new_data_arr + return 0 + + cdef int push(self, NodeHeapData_t data) except -1: + """Push a new item onto the heap""" + cdef ITYPE_t i, i_parent + cdef NodeHeapData_t* data_arr + self.n += 1 + if self.n > self.data.shape[0]: + self.resize(2 * self.n) + + # put the new element at the end, + # and then perform swaps until the heap is in order + data_arr = &self.data[0] + i = self.n - 1 + data_arr[i] = data + + while i > 0: + i_parent = (i - 1) // 2 + if data_arr[i_parent].val <= data_arr[i].val: + break + else: + swap_nodes(data_arr, i, i_parent) + i = i_parent + return 0 + + cdef NodeHeapData_t peek(self): + """Peek at the root of the heap, without removing it""" + return self.data[0] + + cdef NodeHeapData_t pop(self): + """Remove the root of the heap, and update the remaining nodes""" + if self.n == 0: + raise ValueError('cannot pop on empty heap') + + cdef ITYPE_t i, i_child1, i_child2, i_swap + cdef NodeHeapData_t* data_arr = &self.data[0] + cdef NodeHeapData_t popped_element = data_arr[0] + + # pop off the first element, move the last element to the front, + # and then perform swaps until the heap is back in order + data_arr[0] = data_arr[self.n - 1] + self.n -= 1 + + i = 0 + + while (i < self.n): + i_child1 = 2 * i + 1 + i_child2 = 2 * i + 2 + i_swap = 0 + + if i_child2 < self.n: + if data_arr[i_child1].val <= data_arr[i_child2].val: + i_swap = i_child1 + else: + i_swap = i_child2 + elif i_child1 < self.n: + i_swap = i_child1 + else: + break + + if (i_swap > 0) and (data_arr[i_swap].val <= data_arr[i].val): + swap_nodes(data_arr, i, i_swap) + i = i_swap + else: + break + + return popped_element + + cdef void clear(self): + """Clear the heap""" + self.n = 0 + + +###################################################################### +# newObj function +# this is a helper function for pickling +def newObj(obj): + return obj.__new__(obj) + + +###################################################################### +# define the reverse mapping of VALID_METRICS +from dist_metrics import get_valid_metric_ids +VALID_METRIC_IDS = get_valid_metric_ids(VALID_METRICS) + + +###################################################################### +# Binary Tree class +cdef class BinaryTree: + + cdef np.ndarray data_arr + cdef np.ndarray idx_array_arr + cdef np.ndarray node_data_arr + cdef np.ndarray node_bounds_arr + + cdef readonly DTYPE_t[:, ::1] data + cdef public ITYPE_t[::1] idx_array + cdef public NodeData_t[::1] node_data + cdef public DTYPE_t[:, :, ::1] node_bounds + + cdef ITYPE_t leaf_size + cdef ITYPE_t n_levels + cdef ITYPE_t n_nodes + + cdef DistanceMetric dist_metric + cdef int euclidean + + # variables to keep track of building & querying stats + cdef int n_trims + cdef int n_leaves + cdef int n_splits + cdef int n_calls + + valid_metrics = VALID_METRIC_IDS + + # Use cinit to initialize all arrays to empty: this will prevent memory + # errors and seg-faults in rare cases where __init__ is not called + def __cinit__(self): + self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) + + self.data = get_memview_DTYPE_2D(self.data_arr) + self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + self.node_data = get_memview_NodeData_1D(self.node_data_arr) + self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) + + self.leaf_size = 0 + self.n_levels = 0 + self.n_nodes = 0 + + self.euclidean = False + + self.n_trims = 0 + self.n_leaves = 0 + self.n_splits = 0 + self.n_calls = 0 + + def __init__(self, data, + leaf_size=40, metric='minkowski', **kwargs): + self.data_arr = np.asarray(data, dtype=DTYPE, order='C') + self.data = get_memview_DTYPE_2D(self.data_arr) + + self.leaf_size = leaf_size + self.dist_metric = DistanceMetric.get_metric(metric, **kwargs) + self.euclidean = (self.dist_metric.__class__.__name__ + == 'EuclideanDistance') + + metric = self.dist_metric.__class__.__name__ + if metric not in VALID_METRICS: + raise ValueError('metric {metric} is not valid for ' + '{BinaryTree}'.format(metric=metric, + **DOC_DICT)) + + # validate data + if self.data.size == 0: + raise ValueError("X is an empty array") + + if leaf_size < 1: + raise ValueError("leaf_size must be greater than or equal to 1") + + n_samples = self.data.shape[0] + n_features = self.data.shape[1] + + # determine number of levels in the tree, and from this + # the number of nodes in the tree. This results in leaf nodes + # with numbers of points betweeen leaf_size and 2 * leaf_size + self.n_levels = np.log2(fmax(1, (n_samples - 1) / self.leaf_size)) + 1 + self.n_nodes = (2 ** self.n_levels) - 1 + + # allocate arrays for storage + self.idx_array_arr = np.arange(n_samples, dtype=ITYPE) + self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + + self.node_data_arr = np.zeros(self.n_nodes, dtype=NodeData) + self.node_data = get_memview_NodeData_1D(self.node_data_arr) + + # Allocate tree-specific data + allocate_data(self, self.n_nodes, n_features) + self._recursive_build(0, 0, n_samples) + + def __reduce__(self): + """ + reduce method used for pickling + """ + return (newObj, (BinaryTree,), self.__getstate__()) + + def __getstate__(self): + """ + get state for pickling + """ + return (self.data_arr, + self.idx_array_arr, + self.node_data_arr, + self.node_bounds_arr, + int(self.leaf_size), + int(self.n_levels), + int(self.n_nodes), + int(self.n_trims), + int(self.n_leaves), + int(self.n_splits), + int(self.n_calls), + self.dist_metric) + + def __setstate__(self, state): + """ + set state for pickling + """ + self.data_arr = state[0] + self.idx_array_arr = state[1] + self.node_data_arr = state[2] + self.node_bounds_arr = state[3] + + self.data = get_memview_DTYPE_2D(self.data_arr) + self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + self.node_data = get_memview_NodeData_1D(self.node_data_arr) + self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) + + self.leaf_size = state[4] + self.n_levels = state[5] + self.n_nodes = state[6] + self.n_trims = state[7] + self.n_leaves = state[8] + self.n_splits = state[9] + self.n_calls = state[10] + self.dist_metric = state[11] + self.euclidean = (self.dist_metric.__class__.__name__ + == 'EuclideanDistance') + + def get_tree_stats(self): + return (self.n_trims, self.n_leaves, self.n_splits) + + def reset_n_calls(self): + self.n_calls = 0 + + def get_n_calls(self): + return self.n_calls + + def get_arrays(self): + return (self.data_arr, self.idx_array_arr, + self.node_data_arr, self.node_bounds_arr) + + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + """Compute the distance between arrays x1 and x2""" + self.n_calls += 1 + if self.euclidean: + return euclidean_dist(x1, x2, size) + else: + return self.dist_metric.dist(x1, x2, size) + + cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + """Compute the reduced distance between arrays x1 and x2. + + The reduced distance, defined for some metrics, is a quantity which + is more efficient to compute than the distance, but preserves the + relative rankings of the true distance. For example, the reduced + distance for the Euclidean metric is the squared-euclidean distance. + """ + self.n_calls += 1 + if self.euclidean: + return euclidean_rdist(x1, x2, size) + else: + return self.dist_metric.rdist(x1, x2, size) + + cdef int _recursive_build(self, ITYPE_t i_node, ITYPE_t idx_start, + ITYPE_t idx_end) except -1: + """Recursively build the tree. + + Parameters + ---------- + i_node : int + the node for the current step + idx_start, idx_end : int + the bounding indices in the idx_array which define the points that + belong to this node. + """ + cdef ITYPE_t imax + cdef ITYPE_t n_features = self.data.shape[1] + cdef ITYPE_t n_points = idx_end - idx_start + cdef ITYPE_t n_mid = n_points / 2 + cdef ITYPE_t* idx_array = &self.idx_array[idx_start] + cdef DTYPE_t* data = &self.data[0, 0] + + # initialize node data + init_node(self, i_node, idx_start, idx_end) + + if 2 * i_node + 1 >= self.n_nodes: + self.node_data[i_node].is_leaf = True + if idx_end - idx_start > 2 * self.leaf_size: + # this shouldn't happen if our memory allocation is correct + # we'll proactively prevent memory errors, but raise a + # warning saying we're doing so. + import warnings + warnings.warn("Internal: memory layout is flawed: " + "not enough nodes allocated") + + elif idx_end - idx_start < 2: + # again, this shouldn't happen if our memory allocation + # is correct. Raise a warning. + import warnings + warnings.warn("Internal: memory layout is flawed: " + "too many nodes allocated") + self.node_data[i_node].is_leaf = True + + else: + # split node and recursively construct child nodes. + self.node_data[i_node].is_leaf = False + i_max = find_node_split_dim(data, idx_array, + n_features, n_points) + partition_node_indices(data, idx_array, i_max, n_mid, + n_features, n_points) + self._recursive_build(2 * i_node + 1, + idx_start, idx_start + n_mid) + self._recursive_build(2 * i_node + 2, + idx_start + n_mid, idx_end) + + def query(self, X, k=1, return_distance=True, + dualtree=False, breadth_first=False, + sort_results=True): + """ + query(X, k=1, return_distance=True, + dualtree=False, breadth_first=False) + + query the tree for the k nearest neighbors + + Parameters + ---------- + X : array-like, last dimension self.dim + An array of points to query + k : integer (default = 1) + The number of nearest neighbors to return + return_distance : boolean (default = True) + if True, return a tuple (d, i) of distances and indices + if False, return array i + dualtree : boolean (default = False) + if True, use the dual tree formalism for the query: a tree is + built for the query points, and the pair of trees is used to + efficiently search this space. This can lead to better + performance as the number of points grows large. + breadth_first : boolean (default = False) + if True, then query the nodes in a breadth-first manner. + Otherwise, query the nodes in a depth-first manner. + sort_results : boolean (default = True) + if True, then distances and indices of each point are sorted + on return, so that the first column contains the closest points. + Otherwise, neighbors are returned in an arbitrary order. + + Returns + ------- + i : if return_distance == False + (d,i) : if return_distance == True + + d : array of doubles - shape: x.shape[:-1] + (k,) + each entry gives the list of distances to the + neighbors of the corresponding point + + i : array of integers - shape: x.shape[:-1] + (k,) + each entry gives the list of indices of + neighbors of the corresponding point + + Examples + -------- + Query for k-nearest neighbors + + >>> import numpy as np + >>> np.random.seed(0) + >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions + >>> tree = BinaryTree(X, leaf_size=2) # doctest: +SKIP + >>> dist, ind = tree.query(X[0], k=3) # doctest: +SKIP + >>> print ind # indices of 3 closest neighbors + [0 3 1] + >>> print dist # distances to 3 closest neighbors + [ 0. 0.19662693 0.29473397] + """ + # XXX: we should allow X to be a pre-built tree. + X = check_array(X, dtype=DTYPE, order='C') + + if X.shape[X.ndim - 1] != self.data.shape[1]: + raise ValueError("query data dimension must " + "match training data dimension") + + if self.data.shape[0] < k: + raise ValueError("k must be less than or equal " + "to the number of training points") + + # flatten X, and save original shape information + np_Xarr = X.reshape((-1, self.data.shape[1])) + cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(np_Xarr) + cdef DTYPE_t reduced_dist_LB + cdef ITYPE_t i + cdef DTYPE_t* pt + + # initialize heap for neighbors + cdef NeighborsHeap heap = NeighborsHeap(Xarr.shape[0], k) + + # node heap for breadth-first queries + cdef NodeHeap nodeheap + if breadth_first: + nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) + + # bounds is needed for the dual tree algorithm + cdef DTYPE_t[::1] bounds + + self.n_trims = 0 + self.n_leaves = 0 + self.n_splits = 0 + + if dualtree: + other = self.__class__(np_Xarr, metric=self.dist_metric, + leaf_size=self.leaf_size) + if breadth_first: + self._query_dual_breadthfirst(other, heap, nodeheap) + else: + reduced_dist_LB = min_rdist_dual(self, 0, other, 0) + bounds = np.inf + np.zeros(other.node_data.shape[0]) + self._query_dual_depthfirst(0, other, 0, bounds, + heap, reduced_dist_LB) + + else: + pt = &Xarr[0, 0] + if breadth_first: + for i in range(Xarr.shape[0]): + self._query_single_breadthfirst(pt, i, heap, nodeheap) + pt += Xarr.shape[1] + else: + for i in range(Xarr.shape[0]): + reduced_dist_LB = min_rdist(self, 0, pt) + self._query_single_depthfirst(0, pt, i, heap, + reduced_dist_LB) + pt += Xarr.shape[1] + + distances, indices = heap.get_arrays(sort=sort_results) + distances = self.dist_metric.rdist_to_dist(distances) + + # deflatten results + if return_distance: + return (distances.reshape(X.shape[:X.ndim - 1] + (k,)), + indices.reshape(X.shape[:X.ndim - 1] + (k,))) + else: + return indices.reshape(X.shape[:X.ndim - 1] + (k,)) + + def query_radius(self, X, r, return_distance=False, + int count_only=False, int sort_results=False): + """ + query_radius(self, X, r, count_only = False): + + query the tree for neighbors within a radius r + + Parameters + ---------- + X : array-like, last dimension self.dim + An array of points to query + r : distance within which neighbors are returned + r can be a single value, or an array of values of shape + x.shape[:-1] if different radii are desired for each point. + return_distance : boolean (default = False) + if True, return distances to neighbors of each point + if False, return only neighbors + Note that unlike the query() method, setting return_distance=True + here adds to the computation time. Not all distances need to be + calculated explicitly for return_distance=False. Results are + not sorted by default: see ``sort_results`` keyword. + count_only : boolean (default = False) + if True, return only the count of points within distance r + if False, return the indices of all points within distance r + If return_distance==True, setting count_only=True will + result in an error. + sort_results : boolean (default = False) + if True, the distances and indices will be sorted before being + returned. If False, the results will not be sorted. If + return_distance == False, setting sort_results = True will + result in an error. + + Returns + ------- + count : if count_only == True + ind : if count_only == False and return_distance == False + (ind, dist) : if count_only == False and return_distance == True + + count : array of integers, shape = X.shape[:-1] + each entry gives the number of neighbors within + a distance r of the corresponding point. + + ind : array of objects, shape = X.shape[:-1] + each element is a numpy integer array listing the indices of + neighbors of the corresponding point. Note that unlike + the results of a k-neighbors query, the returned neighbors + are not sorted by distance by default. + + dist : array of objects, shape = X.shape[:-1] + each element is a numpy double array + listing the distances corresponding to indices in i. + + Examples + -------- + Query for neighbors in a given radius + + >>> import numpy as np + >>> np.random.seed(0) + >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions + >>> tree = BinaryTree(X, leaf_size=2) # doctest: +SKIP + >>> print tree.query_radius(X[0], r=0.3, count_only=True) + 3 + >>> ind = tree.query_radius(X[0], r=0.3) # doctest: +SKIP + >>> print ind # indices of neighbors within distance 0.3 + [3 0 1] + """ + if count_only and return_distance: + raise ValueError("count_only and return_distance " + "cannot both be true") + + if sort_results and not return_distance: + raise ValueError("return_distance must be True " + "if sort_results is True") + + cdef ITYPE_t i, count_i = 0 + cdef ITYPE_t n_features = self.data.shape[1] + cdef DTYPE_t[::1] dist_arr_i + cdef ITYPE_t[::1] idx_arr_i, counts + cdef DTYPE_t* pt + + # validate X and prepare for query + X = check_array(X, dtype=DTYPE, order='C') + + if X.shape[X.ndim - 1] != self.data.shape[1]: + raise ValueError("query data dimension must " + "match training data dimension") + + cdef DTYPE_t[:, ::1] Xarr =\ + get_memview_DTYPE_2D(X.reshape((-1, self.data.shape[1]))) + + # prepare r for query + r = np.asarray(r, dtype=DTYPE, order='C') + r = np.atleast_1d(r) + if r.shape == (1,): + r = r[0] + np.zeros(X.shape[:X.ndim - 1], dtype=DTYPE) + else: + if r.shape != X.shape[:X.ndim - 1]: + raise ValueError("r must be broadcastable to X.shape") + + rarr_np = r.reshape(-1) # store explicitly to keep in scope + cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) + + # prepare variables for iteration + if not count_only: + indices = np.zeros(Xarr.shape[0], dtype='object') + if return_distance: + distances = np.zeros(Xarr.shape[0], dtype='object') + + np_idx_arr = np.zeros(self.data.shape[0], dtype=ITYPE) + idx_arr_i = get_memview_ITYPE_1D(np_idx_arr) + + np_dist_arr = np.zeros(self.data.shape[0], dtype=DTYPE) + dist_arr_i = get_memview_DTYPE_1D(np_dist_arr) + + counts_arr = np.zeros(Xarr.shape[0], dtype=ITYPE) + counts = get_memview_ITYPE_1D(counts_arr) + + pt = &Xarr[0, 0] + for i in range(Xarr.shape[0]): + counts[i] = self._query_radius_single(0, pt, rarr[i], + &idx_arr_i[0], + &dist_arr_i[0], + 0, count_only, + return_distance) + pt += n_features + + if count_only: + pass + else: + if sort_results: + _simultaneous_sort(&dist_arr_i[0], &idx_arr_i[0], + counts[i]) + + indices[i] = np_idx_arr[:counts[i]].copy() + if return_distance: + distances[i] = np_dist_arr[:counts[i]].copy() + + # deflatten results + if count_only: + return counts_arr.reshape(X.shape[:X.ndim - 1]) + elif return_distance: + return (indices.reshape(X.shape[:X.ndim - 1]), + distances.reshape(X.shape[:X.ndim - 1])) + else: + return indices.reshape(X.shape[:X.ndim - 1]) + + def kernel_density(self, X, h, kernel='gaussian', + atol=0, rtol=1E-8, + breadth_first=True, return_log=False): + """ + kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1E-8, + breadth_first=True, return_log=False) + + Compute the kernel density estimate at points X with the given kernel, + using the distance metric specified at tree creation. + + Parameters + ---------- + X : array_like + An array of points to query. Last dimension should match dimension + of training data. + h : float + the bandwidth of the kernel + kernel : string + specify the kernel to use. Options are + - 'gaussian' + - 'tophat' + - 'epanechnikov' + - 'exponential' + - 'linear' + - 'cosine' + Default is kernel = 'gaussian' + atol, rtol : float (default = 0) + Specify the desired relative and absolute tolerance of the result. + If the true result is K_true, then the returned result K_ret + satisfies ``abs(K_true - K_ret) < atol + rtol * K_ret`` + The default is zero (i.e. machine precision) for both. + breadth_first : boolean (default = False) + if True, use a breadth-first search. If False (default) use a + depth-first search. Breadth-first is generally faster for + compact kernels and/or high tolerances. + return_log : boolean (default = False) + return the logarithm of the result. This can be more accurate + than returning the result itself for narrow kernels. + + Returns + ------- + density : ndarray + The array of (log)-density evaluations, shape = X.shape[:-1] + + Examples + -------- + Compute a gaussian kernel density estimate: + + >>> import numpy as np + >>> np.random.seed(1) + >>> X = np.random.random((100, 3)) + >>> tree = BinaryTree(X) # doctest: +SKIP + >>> tree.kernel_density(X[:3], h=0.1, kernel='gaussian') + array([ 6.94114649, 7.83281226, 7.2071716 ]) + """ + cdef DTYPE_t h_c = h + cdef DTYPE_t log_atol = log(atol) + cdef DTYPE_t log_rtol = log(rtol) + cdef DTYPE_t log_min_bound, log_max_bound, log_bound_spread + cdef DTYPE_t dist_LB = 0, dist_UB = 0 + + cdef ITYPE_t n_samples = self.data.shape[0] + cdef ITYPE_t n_features = self.data.shape[1] + cdef ITYPE_t i + cdef KernelType kernel_c + + # validate kernel + if kernel == 'gaussian': + kernel_c = GAUSSIAN_KERNEL + elif kernel == 'tophat': + kernel_c = TOPHAT_KERNEL + elif kernel == 'epanechnikov': + kernel_c = EPANECHNIKOV_KERNEL + elif kernel == 'exponential': + kernel_c = EXPONENTIAL_KERNEL + elif kernel == 'linear': + kernel_c = LINEAR_KERNEL + elif kernel == 'cosine': + kernel_c = COSINE_KERNEL + else: + raise ValueError("kernel = '%s' not recognized" % kernel) + + cdef DTYPE_t log_knorm = _log_kernel_norm(h_c, n_features, kernel_c) + + # validate X and prepare for query + X = check_array(X, dtype=DTYPE, order='C') + + if X.shape[X.ndim - 1] != n_features: + raise ValueError("query data dimension must " + "match training data dimension") + Xarr_np = X.reshape((-1, n_features)) + cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(Xarr_np) + + log_density_arr = np.zeros(Xarr.shape[0], dtype=DTYPE) + cdef DTYPE_t[::1] log_density = get_memview_DTYPE_1D(log_density_arr) + + cdef DTYPE_t* pt = &Xarr[0, 0] + + cdef NodeHeap nodeheap + if breadth_first: + nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) + cdef DTYPE_t[::1] node_log_min_bounds + cdef DTYPE_t[::1] node_bound_widths + # TODO: implement dual tree approach. + # this is difficult because of the need to cache values + # computed between node pairs. + if breadth_first: + node_log_min_bounds_arr = -np.inf + np.zeros(self.n_nodes) + node_log_min_bounds = get_memview_DTYPE_1D(node_log_min_bounds_arr) + node_bound_widths_arr = np.zeros(self.n_nodes) + node_bound_widths = get_memview_DTYPE_1D(node_bound_widths_arr) + for i in range(Xarr.shape[0]): + log_density[i] = self._kde_single_breadthfirst( + pt, kernel_c, h_c, + log_knorm, log_atol, log_rtol, + nodeheap, + &node_log_min_bounds[0], + &node_bound_widths[0]) + pt += n_features + else: + for i in range(Xarr.shape[0]): + min_max_dist(self, 0, pt, &dist_LB, &dist_UB) + # compute max & min bounds on density within top node + log_min_bound = (log(n_samples) + + compute_log_kernel(dist_UB, + h_c, kernel_c)) + log_max_bound = (log(n_samples) + + compute_log_kernel(dist_LB, + h_c, kernel_c)) + log_bound_spread = logsubexp(log_max_bound, log_min_bound) + self._kde_single_depthfirst(0, pt, kernel_c, h_c, + log_knorm, log_atol, log_rtol, + log_min_bound, + log_bound_spread, + &log_min_bound, + &log_bound_spread) + log_density[i] = logaddexp(log_min_bound, + log_bound_spread - log(2)) + pt += n_features + + # normalize the results + for i in range(log_density.shape[0]): + log_density[i] += log_knorm + + log_density_arr = log_density_arr.reshape(X.shape[:X.ndim - 1]) + + if return_log: + return log_density_arr + else: + return np.exp(log_density_arr) + + def two_point_correlation(self, X, r, dualtree=False): + """Compute the two-point correlation function + + Parameters + ---------- + X : array_like + An array of points to query. Last dimension should match dimension + of training data. + r : array_like + A one-dimensional array of distances + dualtree : boolean (default = False) + If true, use a dualtree algorithm. Otherwise, use a single-tree + algorithm. Dual tree algorithms can have better scaling for + large N. + + Returns + ------- + counts : ndarray + counts[i] contains the number of pairs of points with distance + less than or equal to r[i] + + Examples + -------- + Compute the two-point autocorrelation function of X: + + >>> import numpy as np + >>> np.random.seed(0) + >>> X = np.random.random((30, 3)) + >>> r = np.linspace(0, 1, 5) + >>> tree = BinaryTree(X) # doctest: +SKIP + >>> tree.two_point_correlation(X, r) + array([ 30, 62, 278, 580, 820]) + """ + cdef ITYPE_t n_features = self.data.shape[1] + cdef ITYPE_t i + + # validate X and prepare for query + X = check_array(X, dtype=DTYPE, order='C') + + if X.shape[X.ndim - 1] != self.data.shape[1]: + raise ValueError("query data dimension must " + "match training data dimension") + + np_Xarr = X.reshape((-1, self.data.shape[1])) + cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(np_Xarr) + + # prepare r for query + r = np.asarray(r, dtype=DTYPE, order='C') + r = np.atleast_1d(r) + if r.ndim != 1: + raise ValueError("r must be a 1-dimensional array") + i_rsort = np.argsort(r) + rarr_np = r[i_rsort] # needed to keep memory in scope + cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) + + # create array to hold counts + count = np.zeros(r.shape[0], dtype=ITYPE) + cdef ITYPE_t[::1] carr = get_memview_ITYPE_1D(count) + + cdef DTYPE_t* pt = &Xarr[0, 0] + + if dualtree: + other = self.__class__(Xarr, metric=self.dist_metric, + leaf_size=self.leaf_size) + self._two_point_dual(0, other, 0, &rarr[0], &carr[0], + 0, rarr.shape[0]) + else: + for i in range(Xarr.shape[0]): + self._two_point_single(0, pt, &rarr[0], &carr[0], + 0, rarr.shape[0]) + pt += n_features + + return count + + cdef int _query_single_depthfirst(self, ITYPE_t i_node, + DTYPE_t* pt, ITYPE_t i_pt, + NeighborsHeap heap, + DTYPE_t reduced_dist_LB) except -1: + """Recursive Single-tree k-neighbors query, depth-first approach""" + cdef NodeData_t node_info = self.node_data[i_node] + + cdef DTYPE_t dist_pt, reduced_dist_LB_1, reduced_dist_LB_2 + cdef ITYPE_t i, i1, i2 + + cdef DTYPE_t* data = &self.data[0, 0] + + #------------------------------------------------------------ + # Case 1: query point is outside node radius: + # trim it from the query + if reduced_dist_LB > heap.largest(i_pt): + self.n_trims += 1 + + #------------------------------------------------------------ + # Case 2: this is a leaf node. Update set of nearby points + elif node_info.is_leaf: + self.n_leaves += 1 + for i in range(node_info.idx_start, node_info.idx_end): + dist_pt = self.rdist(pt, + &self.data[self.idx_array[i], 0], + self.data.shape[1]) + if dist_pt < heap.largest(i_pt): + heap.push(i_pt, dist_pt, self.idx_array[i]) + + #------------------------------------------------------------ + # Case 3: Node is not a leaf. Recursively query subnodes + # starting with the closest + else: + self.n_splits += 1 + i1 = 2 * i_node + 1 + i2 = i1 + 1 + reduced_dist_LB_1 = min_rdist(self, i1, pt) + reduced_dist_LB_2 = min_rdist(self, i2, pt) + + # recursively query subnodes + if reduced_dist_LB_1 <= reduced_dist_LB_2: + self._query_single_depthfirst(i1, pt, i_pt, heap, + reduced_dist_LB_1) + self._query_single_depthfirst(i2, pt, i_pt, heap, + reduced_dist_LB_2) + else: + self._query_single_depthfirst(i2, pt, i_pt, heap, + reduced_dist_LB_2) + self._query_single_depthfirst(i1, pt, i_pt, heap, + reduced_dist_LB_1) + return 0 + + cdef int _query_single_breadthfirst(self, DTYPE_t* pt, + ITYPE_t i_pt, + NeighborsHeap heap, + NodeHeap nodeheap) except -1: + """Non-recursive single-tree k-neighbors query, breadth-first search""" + cdef ITYPE_t i, i_node + cdef DTYPE_t dist_pt, reduced_dist_LB + cdef NodeData_t* node_data = &self.node_data[0] + cdef DTYPE_t* data = &self.data[0, 0] + + # Set up the node heap and push the head node onto it + cdef NodeHeapData_t nodeheap_item + nodeheap_item.val = min_rdist(self, 0, pt) + nodeheap_item.i1 = 0 + nodeheap.push(nodeheap_item) + + while nodeheap.n > 0: + nodeheap_item = nodeheap.pop() + reduced_dist_LB = nodeheap_item.val + i_node = nodeheap_item.i1 + node_info = node_data[i_node] + + #------------------------------------------------------------ + # Case 1: query point is outside node radius: + # trim it from the query + if reduced_dist_LB > heap.largest(i_pt): + self.n_trims += 1 + + #------------------------------------------------------------ + # Case 2: this is a leaf node. Update set of nearby points + elif node_data[i_node].is_leaf: + self.n_leaves += 1 + for i in range(node_data[i_node].idx_start, + node_data[i_node].idx_end): + dist_pt = self.rdist(pt, + &self.data[self.idx_array[i], 0], + self.data.shape[1]) + if dist_pt < heap.largest(i_pt): + heap.push(i_pt, dist_pt, self.idx_array[i]) + + #------------------------------------------------------------ + # Case 3: Node is not a leaf. Add subnodes to the node heap + else: + self.n_splits += 1 + for i in range(2 * i_node + 1, 2 * i_node + 3): + nodeheap_item.i1 = i + nodeheap_item.val = min_rdist(self, i, pt) + nodeheap.push(nodeheap_item) + return 0 + + cdef int _query_dual_depthfirst(self, ITYPE_t i_node1, + BinaryTree other, ITYPE_t i_node2, + DTYPE_t[::1] bounds, + NeighborsHeap heap, + DTYPE_t reduced_dist_LB) except -1: + """Recursive dual-tree k-neighbors query, depth-first""" + # note that the array `bounds` is maintained such that + # bounds[i] is the largest distance among any of the + # current neighbors in node i of the other tree. + cdef NodeData_t node_info1 = self.node_data[i_node1] + cdef NodeData_t node_info2 = other.node_data[i_node2] + + cdef DTYPE_t* data1 = &self.data[0, 0] + cdef DTYPE_t* data2 = &other.data[0, 0] + cdef ITYPE_t n_features = self.data.shape[1] + + cdef DTYPE_t bound_max, dist_pt, reduced_dist_LB1, reduced_dist_LB2 + cdef ITYPE_t i1, i2, i_pt, i_parent + + #------------------------------------------------------------ + # Case 1: nodes are further apart than the current bound: + # trim both from the query + if reduced_dist_LB > bounds[i_node2]: + pass + + #------------------------------------------------------------ + # Case 2: both nodes are leaves: + # do a brute-force search comparing all pairs + elif node_info1.is_leaf and node_info2.is_leaf: + bounds[i_node2] = 0 + + for i2 in range(node_info2.idx_start, node_info2.idx_end): + i_pt = other.idx_array[i2] + + if heap.largest(i_pt) <= reduced_dist_LB: + continue + + for i1 in range(node_info1.idx_start, node_info1.idx_end): + dist_pt = self.rdist( + data1 + n_features * self.idx_array[i1], + data2 + n_features * i_pt, + n_features) + if dist_pt < heap.largest(i_pt): + heap.push(i_pt, dist_pt, self.idx_array[i1]) + + # keep track of node bound + bounds[i_node2] = fmax(bounds[i_node2], + heap.largest(i_pt)) + + # update bounds up the tree + while i_node2 > 0: + i_parent = (i_node2 - 1) // 2 + bound_max = fmax(bounds[2 * i_parent + 1], + bounds[2 * i_parent + 2]) + if bound_max < bounds[i_parent]: + bounds[i_parent] = bound_max + i_node2 = i_parent + else: + break + + #------------------------------------------------------------ + # Case 3a: node 1 is a leaf or is smaller: split node 2 and + # recursively query, starting with the nearest subnode + elif node_info1.is_leaf or (not node_info2.is_leaf + and node_info2.radius > node_info1.radius): + reduced_dist_LB1 = min_rdist_dual(self, i_node1, + other, 2 * i_node2 + 1) + reduced_dist_LB2 = min_rdist_dual(self, i_node1, + other, 2 * i_node2 + 2) + + if reduced_dist_LB1 < reduced_dist_LB2: + self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, + bounds, heap, reduced_dist_LB1) + self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, + bounds, heap, reduced_dist_LB2) + else: + self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, + bounds, heap, reduced_dist_LB2) + self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, + bounds, heap, reduced_dist_LB1) + + #------------------------------------------------------------ + # Case 3b: node 2 is a leaf or is smaller: split node 1 and + # recursively query, starting with the nearest subnode + else: + reduced_dist_LB1 = min_rdist_dual(self, 2 * i_node1 + 1, + other, i_node2) + reduced_dist_LB2 = min_rdist_dual(self, 2 * i_node1 + 2, + other, i_node2) + + if reduced_dist_LB1 < reduced_dist_LB2: + self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, + bounds, heap, reduced_dist_LB1) + self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, + bounds, heap, reduced_dist_LB2) + else: + self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, + bounds, heap, reduced_dist_LB2) + self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, + bounds, heap, reduced_dist_LB1) + return 0 + + cdef int _query_dual_breadthfirst(self, BinaryTree other, + NeighborsHeap heap, + NodeHeap nodeheap) except -1: + """Non-recursive dual-tree k-neighbors query, breadth-first""" + cdef ITYPE_t i, i1, i2, i_node1, i_node2, i_pt + cdef DTYPE_t dist_pt, reduced_dist_LB + cdef DTYPE_t[::1] bounds = np.inf + np.zeros(other.node_data.shape[0]) + cdef NodeData_t* node_data1 = &self.node_data[0] + cdef NodeData_t* node_data2 = &other.node_data[0] + cdef NodeData_t node_info1, node_info2 + cdef DTYPE_t* data1 = &self.data[0, 0] + cdef DTYPE_t* data2 = &other.data[0, 0] + cdef ITYPE_t n_features = self.data.shape[1] + + # Set up the node heap and push the head nodes onto it + cdef NodeHeapData_t nodeheap_item + nodeheap_item.val = min_rdist_dual(self, 0, other, 0) + nodeheap_item.i1 = 0 + nodeheap_item.i2 = 0 + nodeheap.push(nodeheap_item) + + while nodeheap.n > 0: + nodeheap_item = nodeheap.pop() + reduced_dist_LB = nodeheap_item.val + i_node1 = nodeheap_item.i1 + i_node2 = nodeheap_item.i2 + + node_info1 = node_data1[i_node1] + node_info2 = node_data2[i_node2] + + #------------------------------------------------------------ + # Case 1: nodes are further apart than the current bound: + # trim both from the query + if reduced_dist_LB > bounds[i_node2]: + pass + + #------------------------------------------------------------ + # Case 2: both nodes are leaves: + # do a brute-force search comparing all pairs + elif node_info1.is_leaf and node_info2.is_leaf: + bounds[i_node2] = -1 + + for i2 in range(node_info2.idx_start, node_info2.idx_end): + i_pt = other.idx_array[i2] + + if heap.largest(i_pt) <= reduced_dist_LB: + continue + + for i1 in range(node_info1.idx_start, node_info1.idx_end): + dist_pt = self.rdist( + data1 + n_features * self.idx_array[i1], + data2 + n_features * i_pt, + n_features) + if dist_pt < heap.largest(i_pt): + heap.push(i_pt, dist_pt, self.idx_array[i1]) + + # keep track of node bound + bounds[i_node2] = fmax(bounds[i_node2], + heap.largest(i_pt)) + + #------------------------------------------------------------ + # Case 3a: node 1 is a leaf or is smaller: split node 2 and + # recursively query, starting with the nearest subnode + elif node_info1.is_leaf or (not node_info2.is_leaf + and (node_info2.radius + > node_info1.radius)): + nodeheap_item.i1 = i_node1 + for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + nodeheap_item.i2 = i2 + nodeheap_item.val = min_rdist_dual(self, i_node1, + other, i2) + nodeheap.push(nodeheap_item) + + #------------------------------------------------------------ + # Case 3b: node 2 is a leaf or is smaller: split node 1 and + # recursively query, starting with the nearest subnode + else: + nodeheap_item.i2 = i_node2 + for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + nodeheap_item.i1 = i1 + nodeheap_item.val = min_rdist_dual(self, i1, + other, i_node2) + nodeheap.push(nodeheap_item) + return 0 + + cdef ITYPE_t _query_radius_single(self, + ITYPE_t i_node, + DTYPE_t* pt, DTYPE_t r, + ITYPE_t* indices, + DTYPE_t* distances, + ITYPE_t count, + int count_only, + int return_distance) except -1: + """recursive single-tree radius query, depth-first""" + cdef DTYPE_t* data = &self.data[0, 0] + cdef ITYPE_t* idx_array = &self.idx_array[0] + cdef ITYPE_t n_features = self.data.shape[1] + cdef NodeData_t node_info = self.node_data[i_node] + + cdef ITYPE_t i + cdef DTYPE_t reduced_r + + cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 + min_max_dist(self, i_node, pt, &dist_LB, &dist_UB) + + #------------------------------------------------------------ + # Case 1: all node points are outside distance r. + # prune this branch. + if dist_LB > r: + pass + + #------------------------------------------------------------ + # Case 2: all node points are within distance r + # add all points to neighbors + elif dist_UB <= r: + if count_only: + count += (node_info.idx_end - node_info.idx_start) + else: + for i in range(node_info.idx_start, node_info.idx_end): + if (count < 0) or (count >= self.data.shape[0]): + raise ValueError("Fatal: count too big: " + "this should never happen") + indices[count] = idx_array[i] + if return_distance: + distances[count] = self.dist(pt, (data + n_features + * idx_array[i]), + n_features) + count += 1 + + #------------------------------------------------------------ + # Case 3: this is a leaf node. Go through all points to + # determine if they fall within radius + elif node_info.is_leaf: + reduced_r = self.dist_metric._dist_to_rdist(r) + + for i in range(node_info.idx_start, node_info.idx_end): + dist_pt = self.rdist(pt, (data + n_features * idx_array[i]), + n_features) + if dist_pt <= reduced_r: + if (count < 0) or (count >= self.data.shape[0]): + raise ValueError("Fatal: count out of range. " + "This should never happen.") + if count_only: + pass + else: + indices[count] = idx_array[i] + if return_distance: + distances[count] =\ + self.dist_metric._rdist_to_dist(dist_pt) + count += 1 + + #------------------------------------------------------------ + # Case 4: Node is not a leaf. Recursively query subnodes + else: + count = self._query_radius_single(2 * i_node + 1, pt, r, + indices, distances, count, + count_only, return_distance) + count = self._query_radius_single(2 * i_node + 2, pt, r, + indices, distances, count, + count_only, return_distance) + + return count + + cdef DTYPE_t _kde_single_breadthfirst(self, DTYPE_t* pt, + KernelType kernel, DTYPE_t h, + DTYPE_t log_knorm, + DTYPE_t log_atol, DTYPE_t log_rtol, + NodeHeap nodeheap, + DTYPE_t* node_log_min_bounds, + DTYPE_t* node_log_bound_spreads): + """non-recursive single-tree kernel density estimation""" + # For the given point, node_log_min_bounds and node_log_bound_spreads + # will encode the current bounds on the density between the point + # and the associated node. + # The variables global_log_min_bound and global_log_bound_spread + # keep track of the global bounds on density. The procedure here is + # to split nodes, updating these bounds, until the bounds are within + # atol & rtol. + cdef ITYPE_t i, i1, i2, N1, N2, i_node + cdef DTYPE_t global_log_min_bound, global_log_bound_spread + cdef DTYPE_t global_log_max_bound + + cdef DTYPE_t* data = &self.data[0, 0] + cdef ITYPE_t* idx_array = &self.idx_array[0] + cdef NodeData_t* node_data = &self.node_data[0] + cdef ITYPE_t N = self.data.shape[0] + cdef ITYPE_t n_features = self.data.shape[1] + + cdef NodeData_t node_info + cdef DTYPE_t dist_pt, log_density + cdef DTYPE_t dist_LB_1 = 0, dist_LB_2 = 0 + cdef DTYPE_t dist_UB_1 = 0, dist_UB_2 = 0 + + cdef DTYPE_t dist_UB, dist_LB + + # push the top node to the heap + cdef NodeHeapData_t nodeheap_item + nodeheap_item.val = min_dist(self, 0, pt) + nodeheap_item.i1 = 0 + nodeheap.push(nodeheap_item) + + global_log_min_bound = log(N) + compute_log_kernel(max_dist(self, + 0, pt), + h, kernel) + global_log_max_bound = log(N) + compute_log_kernel(nodeheap_item.val, + h, kernel) + global_log_bound_spread = logsubexp(global_log_max_bound, + global_log_min_bound) + + node_log_min_bounds[0] = global_log_min_bound + node_log_bound_spreads[0] = global_log_bound_spread + + while nodeheap.n > 0: + nodeheap_item = nodeheap.pop() + i_node = nodeheap_item.i1 + + node_info = node_data[i_node] + N1 = node_info.idx_end - node_info.idx_start + + #------------------------------------------------------------ + # Case 1: local bounds are equal to within per-point tolerance. + if (log_knorm + node_log_bound_spreads[i_node] - log(N1) + log(N) + <= logaddexp(log_atol, (log_rtol + log_knorm + + node_log_min_bounds[i_node]))): + pass + + #------------------------------------------------------------ + # Case 2: global bounds are within rtol & atol. + elif (log_knorm + global_log_bound_spread + <= logaddexp(log_atol, + log_rtol + log_knorm + global_log_min_bound)): + break + + #------------------------------------------------------------ + # Case 3: node is a leaf. Count contributions from all points + elif node_info.is_leaf: + global_log_min_bound =\ + logsubexp(global_log_min_bound, + node_log_min_bounds[i_node]) + global_log_bound_spread =\ + logsubexp(global_log_bound_spread, + node_log_bound_spreads[i_node]) + for i in range(node_info.idx_start, node_info.idx_end): + dist_pt = self.dist(pt, data + n_features * idx_array[i], + n_features) + log_density = compute_log_kernel(dist_pt, h, kernel) + global_log_min_bound = logaddexp(global_log_min_bound, + log_density) + + #------------------------------------------------------------ + # Case 4: split node and query subnodes + else: + i1 = 2 * i_node + 1 + i2 = 2 * i_node + 2 + + N1 = node_data[i1].idx_end - node_data[i1].idx_start + N2 = node_data[i2].idx_end - node_data[i2].idx_start + + min_max_dist(self, i1, pt, &dist_LB_1, &dist_UB_1) + min_max_dist(self, i2, pt, &dist_LB_2, &dist_UB_2) + + node_log_min_bounds[i1] = (log(N1) + + compute_log_kernel(dist_UB_1, + h, kernel)) + node_log_bound_spreads[i1] = (log(N1) + + compute_log_kernel(dist_LB_1, + h, kernel)) + + node_log_min_bounds[i2] = (log(N2) + + compute_log_kernel(dist_UB_2, + h, kernel)) + node_log_bound_spreads[i2] = (log(N2) + + compute_log_kernel(dist_LB_2, + h, kernel)) + + global_log_min_bound = logsubexp(global_log_min_bound, + node_log_min_bounds[i_node]) + global_log_min_bound = logaddexp(global_log_min_bound, + node_log_min_bounds[i1]) + global_log_min_bound = logaddexp(global_log_min_bound, + node_log_min_bounds[i2]) + + global_log_bound_spread =\ + logsubexp(global_log_bound_spread, + node_log_bound_spreads[i_node]) + global_log_bound_spread = logaddexp(global_log_bound_spread, + node_log_bound_spreads[i1]) + global_log_bound_spread = logaddexp(global_log_bound_spread, + node_log_bound_spreads[i2]) + + # TODO: rank by the spread rather than the distance? + nodeheap_item.val = dist_LB_1 + nodeheap_item.i1 = i1 + nodeheap.push(nodeheap_item) + + nodeheap_item.val = dist_LB_2 + nodeheap_item.i1 = i2 + nodeheap.push(nodeheap_item) + + nodeheap.clear() + return logaddexp(global_log_min_bound, + global_log_bound_spread - log(2)) + + cdef int _kde_single_depthfirst( + self, ITYPE_t i_node, DTYPE_t* pt, + KernelType kernel, DTYPE_t h, + DTYPE_t log_knorm, + DTYPE_t log_atol, DTYPE_t log_rtol, + DTYPE_t local_log_min_bound, + DTYPE_t local_log_bound_spread, + DTYPE_t* global_log_min_bound, + DTYPE_t* global_log_bound_spread) except -1: + """recursive single-tree kernel density estimate, depth-first""" + # For the given point, local_min_bound and local_max_bound give the + # minimum and maximum density for the current node, while + # global_min_bound and global_max_bound give the minimum and maximum + # density over the entire tree. We recurse down until global_min_bound + # and global_max_bound are within rtol and atol. + cdef ITYPE_t i, i1, i2, N1, N2 + + cdef DTYPE_t* data = &self.data[0, 0] + cdef ITYPE_t* idx_array = &self.idx_array[0] + cdef ITYPE_t n_features = self.data.shape[1] + + cdef NodeData_t node_info = self.node_data[i_node] + cdef DTYPE_t dist_pt, log_dens_contribution + + cdef DTYPE_t child1_log_min_bound, child2_log_min_bound + cdef DTYPE_t child1_log_bound_spread, child2_log_bound_spread + cdef DTYPE_t dist_UB = 0, dist_LB = 0 + + N1 = node_info.idx_end - node_info.idx_start + N2 = self.data.shape[0] + + #------------------------------------------------------------ + # Case 1: local bounds are equal to within errors. Return + if (log_knorm + local_log_bound_spread - log(N1) + log(N2) + <= logaddexp(log_atol, (log_rtol + log_knorm + + local_log_min_bound))): + pass + + #------------------------------------------------------------ + # Case 2: global bounds are within rtol & atol. Return + elif (log_knorm + global_log_bound_spread[0] + <= logaddexp(log_atol, (log_rtol + log_knorm + + global_log_min_bound[0]))): + pass + + #------------------------------------------------------------ + # Case 3: node is a leaf. Count contributions from all points + elif node_info.is_leaf: + global_log_min_bound[0] = logsubexp(global_log_min_bound[0], + local_log_min_bound) + global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], + local_log_bound_spread) + for i in range(node_info.idx_start, node_info.idx_end): + dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + n_features) + log_dens_contribution = compute_log_kernel(dist_pt, h, kernel) + global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + log_dens_contribution) + + #------------------------------------------------------------ + # Case 4: split node and query subnodes + else: + i1 = 2 * i_node + 1 + i2 = 2 * i_node + 2 + + N1 = self.node_data[i1].idx_end - self.node_data[i1].idx_start + N2 = self.node_data[i2].idx_end - self.node_data[i2].idx_start + + min_max_dist(self, i1, pt, &dist_LB, &dist_UB) + child1_log_min_bound = log(N1) + compute_log_kernel(dist_UB, h, + kernel) + child1_log_bound_spread = logsubexp(log(N1) + + compute_log_kernel(dist_LB, h, + kernel), + child1_log_min_bound) + + min_max_dist(self, i2, pt, &dist_LB, &dist_UB) + child2_log_min_bound = log(N2) + compute_log_kernel(dist_UB, h, + kernel) + child2_log_bound_spread = logsubexp(log(N2) + + compute_log_kernel(dist_LB, h, + kernel), + child2_log_min_bound) + + global_log_min_bound[0] = logsubexp(global_log_min_bound[0], + local_log_min_bound) + global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + child1_log_min_bound) + global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + child2_log_min_bound) + + global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], + local_log_bound_spread) + global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], + child1_log_bound_spread) + global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], + child2_log_bound_spread) + + self._kde_single_depthfirst(i1, pt, kernel, h, log_knorm, + log_atol, log_rtol, + child1_log_min_bound, + child1_log_bound_spread, + global_log_min_bound, + global_log_bound_spread) + self._kde_single_depthfirst(i2, pt, kernel, h, log_knorm, + log_atol, log_rtol, + child2_log_min_bound, + child2_log_bound_spread, + global_log_min_bound, + global_log_bound_spread) + return 0 + + cdef int _two_point_single(self, ITYPE_t i_node, DTYPE_t* pt, DTYPE_t* r, + ITYPE_t* count, ITYPE_t i_min, + ITYPE_t i_max) except -1: + """recursive single-tree two-point correlation function query""" + cdef DTYPE_t* data = &self.data[0, 0] + cdef ITYPE_t* idx_array = &self.idx_array[0] + cdef ITYPE_t n_features = self.data.shape[1] + cdef NodeData_t node_info = self.node_data[i_node] + + cdef ITYPE_t i, j, Npts + cdef DTYPE_t reduced_r + + cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 + min_max_dist(self, i_node, pt, &dist_LB, &dist_UB) + + #------------------------------------------------------------ + # Go through bounds and check for cuts + while i_min < i_max: + if dist_LB > r[i_min]: + i_min += 1 + else: + break + + while i_max > i_min: + Npts = (node_info.idx_end - node_info.idx_start) + if dist_UB <= r[i_max - 1]: + count[i_max - 1] += Npts + i_max -= 1 + else: + break + + if i_min < i_max: + # If node is a leaf, go through all points + if node_info.is_leaf: + for i in range(node_info.idx_start, node_info.idx_end): + dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + n_features) + j = i_max - 1 + while (j >= i_min) and (dist_pt <= r[j]): + count[j] += 1 + j -= 1 + + else: + self._two_point_single(2 * i_node + 1, pt, r, + count, i_min, i_max) + self._two_point_single(2 * i_node + 2, pt, r, + count, i_min, i_max) + return 0 + + cdef int _two_point_dual(self, ITYPE_t i_node1, + BinaryTree other, ITYPE_t i_node2, + DTYPE_t* r, ITYPE_t* count, + ITYPE_t i_min, ITYPE_t i_max) except -1: + """recursive dual-tree two-point correlation function query""" + cdef DTYPE_t* data1 = &self.data[0, 0] + cdef DTYPE_t* data2 = &other.data[0, 0] + cdef ITYPE_t* idx_array1 = &self.idx_array[0] + cdef ITYPE_t* idx_array2 = &other.idx_array[0] + cdef NodeData_t node_info1 = self.node_data[i_node1] + cdef NodeData_t node_info2 = other.node_data[i_node2] + + cdef ITYPE_t n_features = self.data.shape[1] + + cdef ITYPE_t i1, i2, j, Npts + cdef DTYPE_t reduced_r + + cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 + dist_LB = min_dist_dual(self, i_node1, other, i_node2) + dist_UB = max_dist_dual(self, i_node1, other, i_node2) + + #------------------------------------------------------------ + # Go through bounds and check for cuts + while i_min < i_max: + if dist_LB > r[i_min]: + i_min += 1 + else: + break + + while i_max > i_min: + Npts = ((node_info1.idx_end - node_info1.idx_start) + * (node_info2.idx_end - node_info2.idx_start)) + if dist_UB <= r[i_max - 1]: + count[i_max - 1] += Npts + i_max -= 1 + else: + break + + if i_min < i_max: + if node_info1.is_leaf and node_info2.is_leaf: + # If both nodes are leaves, go through all points + for i1 in range(node_info1.idx_start, node_info1.idx_end): + for i2 in range(node_info2.idx_start, node_info2.idx_end): + dist_pt = self.dist((data1 + n_features + * idx_array1[i1]), + (data2 + n_features + * idx_array2[i2]), + n_features) + j = i_max - 1 + while (j >= i_min) and (dist_pt <= r[j]): + count[j] += 1 + j -= 1 + + elif node_info1.is_leaf: + # If only one is a leaf, split the other + for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + self._two_point_dual(i_node1, other, i2, + r, count, i_min, i_max) + + elif node_info2.is_leaf: + for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + self._two_point_dual(i1, other, i_node2, + r, count, i_min, i_max) + + else: + # neither is a leaf: split & query both + for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + self._two_point_dual(i1, other, i2, + r, count, i_min, i_max) + return 0 + + +###################################################################### +# Python functions for benchmarking and testing C implementations + +def load_heap(DTYPE_t[:, ::1] X, ITYPE_t k): + """test fully loading the heap""" + assert k <= X.shape[1] + cdef NeighborsHeap heap = NeighborsHeap(X.shape[0], k) + cdef ITYPE_t i, j + for i in range(X.shape[0]): + for j in range(X.shape[1]): + heap.push(i, X[i, j], j) + return heap.get_arrays() + + +def simultaneous_sort(DTYPE_t[:, ::1] distances, ITYPE_t[:, ::1] indices): + """In-place simultaneous sort the given row of the arrays + + This python wrapper exists primarily to enable unit testing + of the _simultaneous_sort C routine. + """ + assert distances.shape[0] == indices.shape[0] + assert distances.shape[1] == indices.shape[1] + cdef ITYPE_t row + for row in range(distances.shape[0]): + _simultaneous_sort(&distances[row, 0], + &indices[row, 0], + distances.shape[1]) + + +def nodeheap_sort(DTYPE_t[::1] vals): + """In-place reverse sort of vals using NodeHeap""" + cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) + cdef DTYPE_t[::1] vals_sorted = np.zeros_like(vals) + + # use initial size 0 to check corner case + cdef NodeHeap heap = NodeHeap(0) + cdef NodeHeapData_t data + cdef ITYPE_t i + for i in range(vals.shape[0]): + data.val = vals[i] + data.i1 = i + data.i2 = i + 1 + heap.push(data) + + for i in range(vals.shape[0]): + data = heap.pop() + vals_sorted[i] = data.val + indices[i] = data.i1 + + return np.asarray(vals_sorted), np.asarray(indices) + +# Reimplementation for MSVC support +cdef inline double fmin(double a, double b): + return min(a, b) + +cdef inline double fmax(double a, double b): + return max(a, b) diff --git a/sklearn/neighbors/classification.py b/sklearn/neighbors/classification.py index 4f2ada47460e4..43f67f06d5ee3 100644 --- a/sklearn/neighbors/classification.py +++ b/sklearn/neighbors/classification.py @@ -4,8 +4,9 @@ # Fabian Pedregosa # Alexandre Gramfort # Sparseness support by Lars Buitinck +# Multi-output support by Arnaud Joly # -# License: BSD, (C) INRIA, University of Amsterdam +# License: BSD 3 clause (C) INRIA, University of Amsterdam import numpy as np from scipy import stats @@ -16,7 +17,7 @@ NeighborsBase, KNeighborsMixin,\ RadiusNeighborsMixin, SupervisedIntegerMixin from ..base import ClassifierMixin -from ..utils import atleast2d_or_csr +from ..utils import check_array class KNeighborsClassifier(NeighborsBase, KNeighborsMixin, @@ -46,7 +47,7 @@ class KNeighborsClassifier(NeighborsBase, KNeighborsMixin, Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - - 'kd_tree' will use :class:`scipy.spatial.cKDtree` + - 'kd_tree' will use :class:`KDTree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. @@ -55,25 +56,25 @@ class KNeighborsClassifier(NeighborsBase, KNeighborsMixin, this parameter, using brute force. leaf_size : int, optional (default = 30) - Leaf size passed to BallTree or cKDTree. This can affect the + Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. - warn_on_equidistant : boolean, optional. Defaults to True. - Generate a warning if equidistant neighbors are discarded. - For classification or regression based on k-neighbors, if - neighbor k and neighbor k+1 have identical distances but - different labels, then the result will be dependent on the - ordering of the training data. - If the fit method is ``'kd_tree'``, no warnings will be generated. - - p: integer, optional (default = 2) - Parameter for the Minkowski metric from - sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is + metric : string or DistanceMetric object (default = 'minkowski') + the distance metric to use for the tree. The default metric is + minkowski, and with p=2 is equivalent to the standard Euclidean + metric. See the documentation of the DistanceMetric class for a + list of available metrics. + + p : integer, optional (default = 2) + Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + metric_params: dict, optional (default = None) + additional keyword arguments for the metric function. + Examples -------- >>> X = [[0], [1], [2], [3]] @@ -99,18 +100,24 @@ class KNeighborsClassifier(NeighborsBase, KNeighborsMixin, See :ref:`Nearest Neighbors ` in the online documentation for a discussion of the choice of ``algorithm`` and ``leaf_size``. + .. warning:: + + Regarding the Nearest Neighbors algorithms, if it is found that two + neighbors, neighbor `k+1` and `k`, have identical distances but + but different labels, the results will depend on the ordering of the + training data. + http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm """ def __init__(self, n_neighbors=5, - weights='uniform', - algorithm='auto', leaf_size=30, - warn_on_equidistant=True, p=2): + weights='uniform', algorithm='auto', leaf_size=30, + p=2, metric='minkowski', metric_params=None, **kwargs): + self._init_params(n_neighbors=n_neighbors, algorithm=algorithm, - leaf_size=leaf_size, - warn_on_equidistant=warn_on_equidistant, - p=p) + leaf_size=leaf_size, metric=metric, p=p, + metric_params=metric_params, **kwargs) self.weights = _check_weights(weights) def predict(self, X): @@ -118,69 +125,93 @@ def predict(self, X): Parameters ---------- - X: array + X : array of shape [n_samples, n_features] A 2-D array representing the test points. Returns ------- - labels: array - List of class labels (one for each data sample). + y : array of shape [n_samples] or [n_samples, n_outputs] + Class labels for each data sample. """ - X = atleast2d_or_csr(X) + X = check_array(X, accept_sparse='csr') neigh_dist, neigh_ind = self.kneighbors(X) - pred_labels = self._y[neigh_ind] + classes_ = self.classes_ + _y = self._y + if not self.outputs_2d_: + _y = self._y.reshape((-1, 1)) + classes_ = [self.classes_] + + n_outputs = len(classes_) + n_samples = X.shape[0] weights = _get_weights(neigh_dist, self.weights) - if weights is None: - mode, _ = stats.mode(pred_labels, axis=1) - else: - mode, _ = weighted_mode(pred_labels, weights, axis=1) + y_pred = np.empty((n_samples, n_outputs), dtype=classes_[0].dtype) + for k, classes_k in enumerate(classes_): + if weights is None: + mode, _ = stats.mode(_y[neigh_ind, k], axis=1) + else: + mode, _ = weighted_mode(_y[neigh_ind, k], weights, axis=1) + + mode = np.asarray(mode.ravel(), dtype=np.intp) + y_pred[:, k] = classes_k.take(mode) - return mode.flatten().astype(np.int) + if not self.outputs_2d_: + y_pred = y_pred.ravel() + + return y_pred def predict_proba(self, X): """Return probability estimates for the test data X. Parameters ---------- - X: array, shape = (n_samples, n_features) + X : array, shape = (n_samples, n_features) A 2-D array representing the test points. Returns ------- - probabilities : array, shape = [n_samples, n_classes] - Probabilities of the samples for each class in the model, - where classes are ordered arithmetically. + p : array of shape = [n_samples, n_classes], or a list of n_outputs + of such arrays if n_outputs > 1. + The class probabilities of the input samples. Classes are ordered + by lexicographic order. """ - X = atleast2d_or_csr(X) + X = check_array(X, accept_sparse='csr') neigh_dist, neigh_ind = self.kneighbors(X) - pred_labels = self._y[neigh_ind] - weights = _get_weights(neigh_dist, self.weights) + classes_ = self.classes_ + _y = self._y + if not self.outputs_2d_: + _y = self._y.reshape((-1, 1)) + classes_ = [self.classes_] + + n_samples = X.shape[0] + weights = _get_weights(neigh_dist, self.weights) if weights is None: - weights = np.ones_like(pred_labels) + weights = np.ones_like(neigh_ind) - probabilities = np.zeros((X.shape[0], self._classes.size)) + all_rows = np.arange(X.shape[0]) + probabilities = [] + for k, classes_k in enumerate(classes_): + pred_labels = _y[:, k][neigh_ind] + proba_k = np.zeros((n_samples, classes_k.size)) - # Translate class label to a column index in probabilities array. - # This may not be needed provided classes labels are guaranteed to be - # np.arange(n_classes) (e.g. consecutive and starting with 0) - pred_indices = pred_labels.copy() - for k, c in enumerate(self._classes): - pred_indices[pred_labels == c] = k + # a simple ':' index doesn't work right + for i, idx in enumerate(pred_labels.T): # loop is O(n_neighbors) + proba_k[all_rows, idx] += weights[:, i] - # a simple ':' index doesn't work right - all_rows = np.arange(X.shape[0]) + # normalize 'votes' into real [0,1] probabilities + normalizer = proba_k.sum(axis=1)[:, np.newaxis] + normalizer[normalizer == 0.0] = 1.0 + proba_k /= normalizer - for i, idx in enumerate(pred_indices.T): # loop is O(n_neighbors) - probabilities[all_rows, idx] += weights[:, i] + probabilities.append(proba_k) - # normalize 'votes' into real [0,1] probabilities - probabilities = (probabilities.T / probabilities.sum(axis=1)).T + if not self.outputs_2d_: + probabilities = probabilities[0] return probabilities @@ -213,7 +244,7 @@ class RadiusNeighborsClassifier(NeighborsBase, RadiusNeighborsMixin, Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - - 'kd_tree' will use :class:`scipy.spatial.cKDtree` + - 'kd_tree' will use :class:`KDtree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. @@ -222,22 +253,30 @@ class RadiusNeighborsClassifier(NeighborsBase, RadiusNeighborsMixin, this parameter, using brute force. leaf_size : int, optional (default = 30) - Leaf size passed to BallTree or cKDTree. This can affect the + Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. - p: integer, optional (default = 2) - Parameter for the Minkowski metric from - sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is + metric : string or DistanceMetric object (default='minkowski') + the distance metric to use for the tree. The default metric is + minkowski, and with p=2 is equivalent to the standard Euclidean + metric. See the documentation of the DistanceMetric class for a + list of available metrics. + + p : integer, optional (default = 2) + Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. - outlier_label: int, optional (default = None) + outlier_label : int, optional (default = None) Label, which is given for outlier samples (samples with no neighbors on given radius). If set to None, ValueError is raised, when outlier is detected. + metric_params: dict, optional (default = None) + additional keyword arguments for the metric function. + Examples -------- >>> X = [[0], [1], [2], [3]] @@ -265,11 +304,13 @@ class RadiusNeighborsClassifier(NeighborsBase, RadiusNeighborsMixin, """ def __init__(self, radius=1.0, weights='uniform', - algorithm='auto', leaf_size=30, p=2, outlier_label=None): + algorithm='auto', leaf_size=30, p=2, metric='minkowski', + outlier_label=None, metric_params=None, **kwargs): self._init_params(radius=radius, algorithm=algorithm, leaf_size=leaf_size, - p=p) + metric=metric, p=p, metric_params=metric_params, + **kwargs) self.weights = _check_weights(weights) self.outlier_label = outlier_label @@ -278,45 +319,61 @@ def predict(self, X): Parameters ---------- - X: array + X : array of shape [n_samples, n_features] A 2-D array representing the test points. Returns ------- - labels: array - List of class labels (one for each data sample). + y : array of shape [n_samples] or [n_samples, n_outputs] + Class labels for each data sample. + """ - X = atleast2d_or_csr(X) + X = check_array(X, accept_sparse='csr') + n_samples = X.shape[0] neigh_dist, neigh_ind = self.radius_neighbors(X) - pred_labels = [self._y[ind] for ind in neigh_ind] - - if self.outlier_label: - outlier_label = np.array((self.outlier_label, )) - small_value = np.array((1e-6, )) - for i, pl in enumerate(pred_labels): - # Check that all have at least 1 neighbor - if len(pl) < 1: - pred_labels[i] = outlier_label - neigh_dist[i] = small_value - else: - for pl in pred_labels: - # Check that all have at least 1 neighbor - if len(pl) < 1: - raise ValueError('no neighbors found for a test sample, ' - 'you can try using larger radius, ' - 'give a label for outliers, ' - 'or consider removing them in your ' - 'dataset') + inliers = [i for i, nind in enumerate(neigh_ind) if len(nind) != 0] + outliers = [i for i, nind in enumerate(neigh_ind) if len(nind) == 0] + + classes_ = self.classes_ + _y = self._y + if not self.outputs_2d_: + _y = self._y.reshape((-1, 1)) + classes_ = [self.classes_] + n_outputs = len(classes_) + + if self.outlier_label is not None: + neigh_dist[outliers] = 1e-6 + elif outliers: + raise ValueError('No neighbors found for test samples %r, ' + 'you can try using larger radius, ' + 'give a label for outliers, ' + 'or consider removing them from your dataset.' + % outliers) weights = _get_weights(neigh_dist, self.weights) - if weights is None: - mode = np.asarray([stats.mode(pl)[0] for pl in pred_labels], - dtype=np.int) - else: - mode = np.asarray([weighted_mode(pl, w)[0] - for (pl, w) in zip(pred_labels, weights)], - dtype=np.int) - - return mode.flatten().astype(np.int) + y_pred = np.empty((n_samples, n_outputs), dtype=classes_[0].dtype) + for k, classes_k in enumerate(classes_): + pred_labels = np.array([_y[ind, k] for ind in neigh_ind], + dtype=object) + if weights is None: + mode = np.array([stats.mode(pl)[0] + for pl in pred_labels[inliers]], dtype=np.int) + else: + mode = np.array([weighted_mode(pl, w)[0] + for (pl, w) + in zip(pred_labels[inliers], weights)], + dtype=np.int) + + mode = mode.ravel() + + y_pred[inliers, k] = classes_k.take(mode) + + if outliers: + y_pred[outliers, :] = self.outlier_label + + if not self.outputs_2d_: + y_pred = y_pred.ravel() + + return y_pred diff --git a/sklearn/neighbors/dist_metrics.c b/sklearn/neighbors/dist_metrics.c new file mode 100644 index 0000000000000..798286fccd47b --- /dev/null +++ b/sklearn/neighbors/dist_metrics.c @@ -0,0 +1,29402 @@ +/* Generated by Cython 0.19.1 on Sat Jun 7 15:44:25 2014 */ + +#define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_VERSION_HEX < 0x03020000 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__neighbors__dist_metrics +#define __PYX_HAVE_API__sklearn__neighbors__dist_metrics +#include "string.h" +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#include "math.h" +#include "arrayobject.h" +#include "pythread.h" +#include "pystate.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +#ifdef __GNUC__ + /* Test for GCC > 2.95 */ + #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) + #else /* __GNUC__ > 2 ... */ + #define likely(x) (x) + #define unlikely(x) (x) + #endif /* __GNUC__ > 2 ... */ +#else /* __GNUC__ */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "dist_metrics.pxd", + "dist_metrics.pyx", + "numpy.pxd", + "stringsource", + "stringsource", + "type.pxd", +}; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + +struct __pyx_memoryview_obj; +typedef struct { + struct __pyx_memoryview_obj *memview; + char *data; + Py_ssize_t shape[8]; + Py_ssize_t strides[8]; + Py_ssize_t suboffsets[8]; +} __Pyx_memviewslice; + +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __pyx_atomic_int_type int +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ + !defined(__i386__) + #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && MSC_VER + #include + #define __pyx_atomic_int_type LONG + #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using MSVC atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 + #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using Intel atomics" + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif +typedef volatile __pyx_atomic_int_type __pyx_atomic_int; +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview) \ + __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) +#else + #define __pyx_add_acquisition_count(memview) \ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif + + +/* "numpy.pxd":723 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "numpy.pxd":724 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "numpy.pxd":725 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "numpy.pxd":726 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "numpy.pxd":730 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "numpy.pxd":731 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "numpy.pxd":732 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "numpy.pxd":733 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "numpy.pxd":737 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "numpy.pxd":738 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "numpy.pxd":747 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "numpy.pxd":748 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "numpy.pxd":749 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "numpy.pxd":751 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "numpy.pxd":752 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "numpy.pxd":753 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "numpy.pxd":755 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "numpy.pxd":756 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "numpy.pxd":758 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "numpy.pxd":759 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "numpy.pxd":760 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; + +/* "typedefs.pxd":5 + * + * # Floating point/data type + * ctypedef np.float64_t DTYPE_t # WARNING: should match DTYPE in typedefs.pyx # <<<<<<<<<<<<<< + * + * cdef enum: + */ +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t; + +/* "typedefs.pxd":13 + * # Index/integer type. + * # WARNING: ITYPE_t must be a signed integer type or you will have a bad time! + * ctypedef np.intp_t ITYPE_t # WARNING: should match ITYPE in typedefs.pyx # <<<<<<<<<<<<<< + * + * # Fused type for certain operations + */ +typedef __pyx_t_5numpy_intp_t __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ +struct __pyx_MemviewEnum_obj; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric; +struct __pyx_memoryview_obj; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_JaccardDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HammingDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_CanberraDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ManhattanDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance; +struct __pyx_array_obj; +struct __pyx_memoryviewslice_obj; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_PyFuncDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MatchingDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance; +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DiceDistance; + +/* "numpy.pxd":762 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "numpy.pxd":763 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "numpy.pxd":764 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "numpy.pxd":766 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; + +/* "typedefs.pxd":7 + * ctypedef np.float64_t DTYPE_t # WARNING: should match DTYPE in typedefs.pyx + * + * cdef enum: # <<<<<<<<<<<<<< + * DTYPECODE = np.NPY_FLOAT64 + * ITYPECODE = np.NPY_INTP + */ +enum { + + /* "typedefs.pxd":9 + * cdef enum: + * DTYPECODE = np.NPY_FLOAT64 + * ITYPECODE = np.NPY_INTP # <<<<<<<<<<<<<< + * + * # Index/integer type. + */ + __pyx_e_7sklearn_9neighbors_8typedefs_DTYPECODE = NPY_FLOAT64, + __pyx_e_7sklearn_9neighbors_8typedefs_ITYPECODE = NPY_INTP +}; + +/* "View.MemoryView":275 + * + * @cname('__pyx_MemviewEnum') + * cdef class Enum(object): # <<<<<<<<<<<<<< + * cdef object name + * def __init__(self, name): + */ +struct __pyx_MemviewEnum_obj { + PyObject_HEAD + PyObject *name; +}; + + +/* "sklearn/neighbors/dist_metrics.pxd":48 + * ###################################################################### + * # DistanceMetric base class + * cdef class DistanceMetric: # <<<<<<<<<<<<<< + * # The following attributes are required for a few of the subclasses. + * # we must define them here so that cython's limited polymorphism will work. + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_vtab; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t p; + PyArrayObject *vec; + PyArrayObject *mat; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *vec_ptr; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *mat_ptr; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t size; + PyObject *func; + PyObject *kwargs; +}; + + +/* "View.MemoryView":308 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ +struct __pyx_memoryview_obj { + PyObject_HEAD + struct __pyx_vtabstruct_memoryview *__pyx_vtab; + PyObject *obj; + PyObject *_size; + PyObject *_array_interface; + PyThread_type_lock lock; + __pyx_atomic_int acquisition_count[2]; + __pyx_atomic_int *acquisition_count_aligned_p; + Py_buffer view; + int flags; + int dtype_is_object; + __Pyx_TypeInfo *typeinfo; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":832 + * # Kulsinski Distance (boolean) + * # D(x, y) = (ntf + nft - ntt + n) / (n_neq + n) + * cdef class KulsinskiDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Kulsinski Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":929 + * # Sokal-Sneath Distance (boolean) + * # D(x, y) = n_neq / (0.5 * n_tt + n_neq) + * cdef class SokalSneathDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Sokal-Sneath Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":429 + * # SEuclidean Distance + * # d = sqrt(sum((x_i - y_i2)^2 / v_i)) + * cdef class SEuclideanDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Standardized Euclidean Distance metric + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":758 + * # Jaccard Distance (boolean) + * # D(x, y) = N_unequal(x, y) / N_nonzero(x, y) + * cdef class JaccardDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Jaccard Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_JaccardDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":688 + * # Hamming Distance + * # d = N_unequal(x, y) / N_tot + * cdef class HammingDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Hamming Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HammingDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":733 + * # Bray-Curtis Distance + * # D(x, y) = sum[abs(x_i - y_i)] / sum[abs(x_i) + abs(y_i)] + * cdef class BrayCurtisDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Bray-Curtis Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":710 + * # Canberra Distance + * # D(x, y) = sum[ abs(x_i - y_i) / (abs(x_i) + abs(y_i)) ] + * cdef class CanberraDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Canberra Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_CanberraDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":881 + * # Russell-Rao Distance (boolean) + * # D(x, y) = (n - ntt) / n + * cdef class RussellRaoDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Russell-Rao Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":396 + * # Euclidean Distance + * # d = sqrt(sum(x_i^2 - y_i^2)) + * cdef class EuclideanDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Euclidean Distance metric + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":561 + * # W-Minkowski Distance + * # d = sum(w_i * (x_i^p - y_i^p)) ^ (1/p) + * cdef class WMinkowskiDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Weighted Minkowski Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":514 + * # Minkowski Distance + * # d = sum(x_i^p - y_i^p) ^ (1/p) + * cdef class MinkowskiDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Minkowski Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":619 + * # Mahalanobis Distance + * # d = sqrt( (x - y)^T V^-1 (x - y) ) + * cdef class MahalanobisDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Mahalanobis Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":472 + * # Manhattan Distance + * # d = sum(abs(x_i - y_i)) + * cdef class ManhattanDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Manhattan/City-block Distance metric + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ManhattanDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":905 + * # Sokal-Michener Distance (boolean) + * # D(x, y) = 2 * n_neq / (n + n_neq) + * cdef class SokalMichenerDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Sokal-Michener Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "View.MemoryView":96 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ +struct __pyx_array_obj { + PyObject_HEAD + char *data; + Py_ssize_t len; + char *format; + int ndim; + Py_ssize_t *_shape; + Py_ssize_t *_strides; + Py_ssize_t itemsize; + PyObject *mode; + PyObject *_format; + void (*callback_free_data)(void *); + int free_data; + int dtype_is_object; +}; + + +/* "View.MemoryView":927 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ +struct __pyx_memoryviewslice_obj { + struct __pyx_memoryview_obj __pyx_base; + __Pyx_memviewslice from_slice; + PyObject *from_object; + PyObject *(*to_object_func)(char *); + int (*to_dtype_func)(char *, PyObject *); +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":857 + * # Rogers-Tanimoto Distance (boolean) + * # D(x, y) = 2 * n_neq / (n + n_neq) + * cdef class RogersTanimotoDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Rogers-Tanimoto Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":1064 + * # User-defined distance + * # + * cdef class PyFuncDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """PyFunc Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_PyFuncDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":783 + * # Matching Distance (boolean) + * # D(x, y) = n_neq / n + * cdef class MatchingDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Matching Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MatchingDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":493 + * # Chebyshev Distance + * # d = max_i(abs(x_i), abs(y_i)) + * cdef class ChebyshevDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Chebyshev/Infinity Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":955 + * # D(x, y) = 2 arcsin{sqrt[sin^2 ((x1 - y1) / 2) + * # + cos(x1) cos(y1) sin^2 ((x2 - y2) / 2)]} + * cdef class HaversineDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Haversine (Spherical) Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + +/* "sklearn/neighbors/dist_metrics.pyx":807 + * # Dice Distance (boolean) + * # D(x, y) = n_neq / (2 * ntt + n_neq) + * cdef class DiceDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Dice Distance + * + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DiceDistance { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; + + + +/* "sklearn/neighbors/dist_metrics.pyx":107 + * ###################################################################### + * # Distance Metric Classes + * cdef class DistanceMetric: # <<<<<<<<<<<<<< + * """DistanceMetric class + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*dist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*rdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*pdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __Pyx_memviewslice, __Pyx_memviewslice); + int (*cdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*_rdist_to_dist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*_dist_to_rdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + + +/* "sklearn/neighbors/dist_metrics.pyx":905 + * # Sokal-Michener Distance (boolean) + * # D(x, y) = 2 * n_neq / (n + n_neq) + * cdef class SokalMichenerDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Sokal-Michener Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":688 + * # Hamming Distance + * # d = N_unequal(x, y) / N_tot + * cdef class HammingDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Hamming Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_HammingDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_HammingDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_HammingDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":493 + * # Chebyshev Distance + * # d = max_i(abs(x_i), abs(y_i)) + * cdef class ChebyshevDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Chebyshev/Infinity Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":396 + * # Euclidean Distance + * # d = sqrt(sum(x_i^2 - y_i^2)) + * cdef class EuclideanDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Euclidean Distance metric + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_EuclideanDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_EuclideanDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":514 + * # Minkowski Distance + * # d = sum(x_i^p - y_i^p) ^ (1/p) + * cdef class MinkowskiDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Minkowski Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":807 + * # Dice Distance (boolean) + * # D(x, y) = n_neq / (2 * ntt + n_neq) + * cdef class DiceDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Dice Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DiceDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DiceDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DiceDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":783 + * # Matching Distance (boolean) + * # D(x, y) = n_neq / n + * cdef class MatchingDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Matching Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_MatchingDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_MatchingDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MatchingDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":881 + * # Russell-Rao Distance (boolean) + * # D(x, y) = (n - ntt) / n + * cdef class RussellRaoDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Russell-Rao Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":472 + * # Manhattan Distance + * # d = sum(abs(x_i - y_i)) + * cdef class ManhattanDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Manhattan/City-block Distance metric + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_ManhattanDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_ManhattanDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_ManhattanDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":710 + * # Canberra Distance + * # D(x, y) = sum[ abs(x_i - y_i) / (abs(x_i) + abs(y_i)) ] + * cdef class CanberraDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Canberra Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_CanberraDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_CanberraDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_CanberraDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":758 + * # Jaccard Distance (boolean) + * # D(x, y) = N_unequal(x, y) / N_nonzero(x, y) + * cdef class JaccardDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Jaccard Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_JaccardDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_JaccardDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_JaccardDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":561 + * # W-Minkowski Distance + * # d = sum(w_i * (x_i^p - y_i^p)) ^ (1/p) + * cdef class WMinkowskiDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Weighted Minkowski Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":429 + * # SEuclidean Distance + * # d = sqrt(sum((x_i - y_i2)^2 / v_i)) + * cdef class SEuclideanDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Standardized Euclidean Distance metric + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance; + + + +/* "sklearn/neighbors/dist_metrics.pyx":1064 + * # User-defined distance + * # + * cdef class PyFuncDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """PyFunc Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_PyFuncDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_PyFuncDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_PyFuncDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":619 + * # Mahalanobis Distance + * # d = sqrt( (x - y)^T V^-1 (x - y) ) + * cdef class MahalanobisDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Mahalanobis Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":857 + * # Rogers-Tanimoto Distance (boolean) + * # D(x, y) = 2 * n_neq / (n + n_neq) + * cdef class RogersTanimotoDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Rogers-Tanimoto Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":955 + * # D(x, y) = 2 arcsin{sqrt[sin^2 ((x1 - y1) / 2) + * # + cos(x1) cos(y1) sin^2 ((x2 - y2) / 2)]} + * cdef class HaversineDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Haversine (Spherical) Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_HaversineDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_HaversineDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_HaversineDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":929 + * # Sokal-Sneath Distance (boolean) + * # D(x, y) = n_neq / (0.5 * n_tt + n_neq) + * cdef class SokalSneathDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Sokal-Sneath Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance; + + +/* "sklearn/neighbors/dist_metrics.pyx":733 + * # Bray-Curtis Distance + * # D(x, y) = sum[abs(x_i - y_i)] / sum[abs(x_i) + abs(y_i)] + * cdef class BrayCurtisDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Bray-Curtis Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance; + + +/* "View.MemoryView":308 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ + +struct __pyx_vtabstruct_memoryview { + char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); + PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); +}; +static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; + + +/* "View.MemoryView":927 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ + +struct __pyx_vtabstruct__memoryviewslice { + struct __pyx_vtabstruct_memoryview __pyx_base; +}; +static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; + + +/* "sklearn/neighbors/dist_metrics.pyx":832 + * # Kulsinski Distance (boolean) + * # D(x, y) = (ntf + nft - ntt + n) / (n_neq + n) + * cdef class KulsinskiDistance(DistanceMetric): # <<<<<<<<<<<<<< + * """Kulsinski Distance + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance { + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance; +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d +#define __Pyx_MEMVIEW_DIRECT 1 +#define __Pyx_MEMVIEW_PTR 2 +#define __Pyx_MEMVIEW_FULL 4 +#define __Pyx_MEMVIEW_CONTIG 8 +#define __Pyx_MEMVIEW_STRIDED 16 +#define __Pyx_MEMVIEW_FOLLOW 32 +#define __Pyx_IS_C_CONTIG 1 +#define __Pyx_IS_F_CONTIG 2 +static int __Pyx_init_memviewslice( + struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference); +static CYTHON_INLINE int __pyx_add_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) +#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) +#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) +#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) +static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +#define __Pyx_BufPtrCContig1d(type, buf, i0, s0) ((type)buf + i0) +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename); /*proto*/ + +#define __Pyx_BufPtrCContig2d(type, buf, i0, s0, i1, s1) ((type)((char*)buf + i0 * s0) + i1) +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +static CYTHON_INLINE int __Pyx_PySequence_Contains(PyObject* item, PyObject* seq, int eq) { + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static CYTHON_INLINE int __Pyx_CheckKeywordStrings(PyObject *kwdict, const char* function_name, int kw_allowed); /*proto*/ + +#define __Pyx_GetItemInt(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Fast(o, i, is_list, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +#define __Pyx_GetItemInt_List(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_List_Fast(o, i, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, i, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyCallable_Check(obj) ((obj)->ob_type->tp_call != NULL) +#else +#define __Pyx_PyCallable_Check(obj) PyCallable_Check(obj) +#endif + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ + +static double __Pyx__PyObject_AsDouble(PyObject* obj); /* proto */ +#if CYTHON_COMPILING_IN_PYPY +#define __Pyx_PyObject_AsDouble(obj) \ +(likely(PyFloat_CheckExact(obj)) ? PyFloat_AS_DOUBLE(obj) : \ + likely(PyInt_CheckExact(obj)) ? \ + PyFloat_AsDouble(obj) : __Pyx__PyObject_AsDouble(obj)) +#else +#define __Pyx_PyObject_AsDouble(obj) \ +((likely(PyFloat_CheckExact(obj))) ? \ + PyFloat_AS_DOUBLE(obj) : __Pyx__PyObject_AsDouble(obj)) +#endif + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/ + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) + +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +#include + +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); + +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /*proto*/ + +static PyObject *__Pyx_GetNameInClass(PyObject *nmspace, PyObject *name); /*proto*/ + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t); + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_from_py_Py_intptr_t(PyObject *); + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +#include "descrobject.h" +static PyObject* __Pyx_Method_ClassMethod(PyObject *method); /*proto*/ + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim); + +static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize); + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object); + +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); + +struct __pyx_typeinfo_string { + char string[3]; +}; +static struct __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *type); + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); + +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); + +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); + +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); + +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); + +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); + +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); + +static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); + +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *); + +static int __Pyx_check_binary_version(void); + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'cython.view' */ +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ + +/* Module declarations from 'cython' */ + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'libc.math' */ + +/* Module declarations from 'sklearn.neighbors.typedefs' */ + +/* Module declarations from 'sklearn.neighbors.dist_metrics' */ +static PyTypeObject *__pyx_MemviewEnum_type = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric = 0; +static PyTypeObject *__pyx_memoryview_type = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_JaccardDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_HammingDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_CanberraDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_EuclideanDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_ManhattanDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance = 0; +static PyTypeObject *__pyx_array_type = 0; +static PyTypeObject *__pyx_memoryviewslice_type = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_PyFuncDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_MatchingDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_HaversineDistance = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DiceDistance = 0; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_12dist_metrics_INF; +static PyObject *generic = 0; +static PyObject *strided = 0; +static PyObject *indirect = 0; +static PyObject *contiguous = 0; +static PyObject *indirect_contiguous = 0; +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_12dist_metrics_get_memview_DTYPE_2D(PyArrayObject *); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_f_7sklearn_9neighbors_12dist_metrics_get_vec_ptr(PyArrayObject *); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_f_7sklearn_9neighbors_12dist_metrics_get_mat_ptr(PyArrayObject *); /*proto*/ +static CYTHON_INLINE PyArrayObject *__pyx_f_7sklearn_9neighbors_12dist_metrics__buffer_to_ndarray(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, npy_intp); /*proto*/ +static CYTHON_INLINE double __pyx_f_7sklearn_9neighbors_12dist_metrics_fmax(double, double); /*proto*/ +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ +static void *__pyx_align_pointer(void *, size_t); /*proto*/ +static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ +static PyObject *_unellipsify(PyObject *, int); /*proto*/ +static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ +static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, int); /*proto*/ +static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ +static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ +static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ +static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ +static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ +static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ +static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ +static PyObject *__pyx_format_from_typeinfo(__Pyx_TypeInfo *); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; +#define __Pyx_MODULE_NAME "sklearn.neighbors.dist_metrics" +int __pyx_module_is_main_sklearn__neighbors__dist_metrics = 0; + +/* Implementation of 'sklearn.neighbors.dist_metrics' */ +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_NotImplementedError; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_Ellipsis; +static PyObject *__pyx_builtin_xrange; +static PyObject *__pyx_builtin_id; +static PyObject *__pyx_builtin_IndexError; +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_newObj(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_obj); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_2get_valid_metric_ids(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_L); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric___cinit__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_2__reduce__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_4__getstate__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_6__setstate__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, PyObject *__pyx_v_state); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_8get_metric(CYTHON_UNUSED PyObject *__pyx_v_cls, PyObject *__pyx_v_metric, PyObject *__pyx_v_kwargs); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_10__init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_12rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, PyObject *__pyx_v_rdist); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_14dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, PyObject *__pyx_v_dist); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_16pairwise(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_Y); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_2rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *__pyx_v_self, PyObject *__pyx_v_rdist); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_4dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *__pyx_v_self, PyObject *__pyx_v_dist); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *__pyx_v_self, PyObject *__pyx_v_V); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_2rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *__pyx_v_self, PyObject *__pyx_v_rdist); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_4dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *__pyx_v_self, PyObject *__pyx_v_dist); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_17ManhattanDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ManhattanDistance *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_17ChebyshevDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_p); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_2rdist_to_dist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_rdist); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_4dist_to_rdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_dist); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_p, PyObject *__pyx_v_w); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_2rdist_to_dist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_rdist); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_4dist_to_rdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_dist); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *__pyx_v_self, PyObject *__pyx_v_V, PyObject *__pyx_v_VI); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_2rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *__pyx_v_self, PyObject *__pyx_v_rdist); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_4dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *__pyx_v_self, PyObject *__pyx_v_dist); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *__pyx_v_self, PyObject *__pyx_v_rdist); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_2dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *__pyx_v_self, PyObject *__pyx_v_dist); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_14PyFuncDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_PyFuncDistance *__pyx_v_self, PyObject *__pyx_v_func, PyObject *__pyx_v_kwargs); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_JaccardDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_HammingDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_CanberraDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_EuclideanDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_ManhattanDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_PyFuncDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_MatchingDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_HaversineDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DiceDistance(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_4[] = "Unrecognized metric '%s'"; +static char __pyx_k_6[] = "DistanceMetric is an abstract class"; +static char __pyx_k_8[] = "X and Y must have the same second dimension"; +static char __pyx_k_10[] = "SEuclidean dist: size of V does not match"; +static char __pyx_k_12[] = "p must be greater than 1"; +static char __pyx_k_14[] = "MinkowskiDistance requires finite p. For p=inf, use ChebyshevDistance."; +static char __pyx_k_17[] = "WMinkowskiDistance requires finite p. For p=inf, use ChebyshevDistance."; +static char __pyx_k_19[] = "WMinkowskiDistance dist: size of w does not match"; +static char __pyx_k_21[] = "V/VI must be square"; +static char __pyx_k_23[] = "Mahalanobis dist: size of V does not match"; +static char __pyx_k_25[] = "Haversine distance only valid in 2 dimensions"; +static char __pyx_k_29[] = "func must be a callable taking two arrays"; +static char __pyx_k_31[] = "func must return a float"; +static char __pyx_k_33[] = "ndarray is not C contiguous"; +static char __pyx_k_35[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_37[] = "Non-native byte order not supported"; +static char __pyx_k_39[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_40[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_43[] = "Format string allocated too short."; +static char __pyx_k_45[] = "Empty shape tuple for cython.array"; +static char __pyx_k_47[] = "itemsize <= 0 for cython.array"; +static char __pyx_k_50[] = "unable to allocate shape or strides."; +static char __pyx_k_52[] = "Invalid shape in axis %d: %d."; +static char __pyx_k_53[] = "Invalid mode, expected 'c' or 'fortran', got %s"; +static char __pyx_k_55[] = "unable to allocate array data."; +static char __pyx_k_57[] = "Can only create a buffer that is contiguous in memory."; +static char __pyx_k_59[] = "Unable to convert item to object"; +static char __pyx_k_61[] = "Buffer view does not expose strides"; +static char __pyx_k_63[] = ""; +static char __pyx_k_64[] = ""; +static char __pyx_k_67[] = "Cannot index with type '%s'"; +static char __pyx_k_69[] = "Indirect dimensions not supported"; +static char __pyx_k_71[] = "Index out of bounds (axis %d)"; +static char __pyx_k_72[] = "Step may not be zero (axis %d)"; +static char __pyx_k_73[] = "All dimensions preceding dimension %d must be indexed and not sliced"; +static char __pyx_k_74[] = "Out of bounds on buffer access (axis %d)"; +static char __pyx_k_75[] = "Cannot transpose memoryview with indirect dimensions"; +static char __pyx_k_76[] = "got differing extents in dimension %d (got %d and %d)"; +static char __pyx_k_77[] = "Dimension %d is not direct"; +static char __pyx_k_78[] = "^"; +static char __pyx_k_79[] = ""; +static char __pyx_k_80[] = "T{"; + static char __pyx_k_81[] = ":"; +static char __pyx_k_82[] = "}"; +static char __pyx_k_83[] = "(%s)"; +static char __pyx_k_84[] = ","; +static char __pyx_k_87[] = "/home/andy/checkout/scikit-learn/sklearn/neighbors/dist_metrics.pyx"; +static char __pyx_k_88[] = "sklearn.neighbors.dist_metrics"; +static char __pyx_k_91[] = "get_valid_metric_ids"; +static char __pyx_k_92[] = "get_valid_metric_ids (line 92)"; +static char __pyx_k_93[] = "Given an iterable of metric class names or class identifiers,\n return a list of metric IDs which map to those classes.\n\n Example:\n >>> L = get_valid_metric_ids([EuclideanDistance, 'ManhattanDistance'])\n >>> sorted(L)\n ['cityblock', 'euclidean', 'l1', 'l2', 'manhattan']\n "; +static char __pyx_k_94[] = "getbuffer(obj, view, flags)"; +static char __pyx_k_95[] = ""; +static char __pyx_k_97[] = ""; +static char __pyx_k_99[] = ""; +static char __pyx_k__B[] = "B"; +static char __pyx_k__C[] = "C"; +static char __pyx_k__H[] = "H"; +static char __pyx_k__I[] = "I"; +static char __pyx_k__L[] = "L"; +static char __pyx_k__O[] = "O"; +static char __pyx_k__Q[] = "Q"; +static char __pyx_k__V[] = "V"; +static char __pyx_k__X[] = "X"; +static char __pyx_k__Y[] = "Y"; +static char __pyx_k__b[] = "b"; +static char __pyx_k__c[] = "c"; +static char __pyx_k__d[] = "d"; +static char __pyx_k__f[] = "f"; +static char __pyx_k__g[] = "g"; +static char __pyx_k__h[] = "h"; +static char __pyx_k__i[] = "i"; +static char __pyx_k__l[] = "l"; +static char __pyx_k__p[] = "p"; +static char __pyx_k__q[] = "q"; +static char __pyx_k__w[] = "w"; +static char __pyx_k_101[] = ""; +static char __pyx_k_103[] = ""; +static char __pyx_k__VI[] = "VI"; +static char __pyx_k__Zd[] = "Zd"; +static char __pyx_k__Zf[] = "Zf"; +static char __pyx_k__Zg[] = "Zg"; +static char __pyx_k__id[] = "id"; +static char __pyx_k__l1[] = "l1"; +static char __pyx_k__l2[] = "l2"; +static char __pyx_k__np[] = "np"; +static char __pyx_k__inf[] = "inf"; +static char __pyx_k__inv[] = "inv"; +static char __pyx_k__key[] = "key"; +static char __pyx_k__obj[] = "obj"; +static char __pyx_k__pop[] = "pop"; +static char __pyx_k__sin[] = "sin"; +static char __pyx_k__val[] = "val"; +static char __pyx_k__base[] = "base"; +static char __pyx_k__dice[] = "dice"; +static char __pyx_k__func[] = "func"; +static char __pyx_k__join[] = "join"; +static char __pyx_k__mode[] = "mode"; +static char __pyx_k__name[] = "name"; +static char __pyx_k__ndim[] = "ndim"; +static char __pyx_k__pack[] = "pack"; +static char __pyx_k__size[] = "size"; +static char __pyx_k__sqrt[] = "sqrt"; +static char __pyx_k__step[] = "step"; +static char __pyx_k__stop[] = "stop"; +static char __pyx_k__ASCII[] = "ASCII"; +static char __pyx_k__DTYPE[] = "DTYPE"; +static char __pyx_k__ITYPE[] = "ITYPE"; +static char __pyx_k__dtype[] = "dtype"; +static char __pyx_k__error[] = "error"; +static char __pyx_k__flags[] = "flags"; +static char __pyx_k__isinf[] = "isinf"; +static char __pyx_k__items[] = "items"; +static char __pyx_k__numpy[] = "numpy"; +static char __pyx_k__order[] = "order"; +static char __pyx_k__range[] = "range"; +static char __pyx_k__shape[] = "shape"; +static char __pyx_k__start[] = "start"; +static char __pyx_k__zeros[] = "zeros"; +static char __pyx_k__arcsin[] = "arcsin"; +static char __pyx_k__decode[] = "decode"; +static char __pyx_k__encode[] = "encode"; +static char __pyx_k__extend[] = "extend"; +static char __pyx_k__format[] = "format"; +static char __pyx_k__linalg[] = "linalg"; +static char __pyx_k__metric[] = "metric"; +static char __pyx_k__newObj[] = "newObj"; +static char __pyx_k__pyfunc[] = "pyfunc"; +static char __pyx_k__random[] = "random"; +static char __pyx_k__struct[] = "struct"; +static char __pyx_k__unpack[] = "unpack"; +static char __pyx_k__xrange[] = "xrange"; +static char __pyx_k____new__[] = "__new__"; +static char __pyx_k__asarray[] = "asarray"; +static char __pyx_k__fortran[] = "fortran"; +static char __pyx_k__hamming[] = "hamming"; +static char __pyx_k__jaccard[] = "jaccard"; +static char __pyx_k__memview[] = "memview"; +static char __pyx_k__Ellipsis[] = "Ellipsis"; +static char __pyx_k____main__[] = "__main__"; +static char __pyx_k____name__[] = "__name__"; +static char __pyx_k____test__[] = "__test__"; +static char __pyx_k__canberra[] = "canberra"; +static char __pyx_k__infinity[] = "infinity"; +static char __pyx_k__itemsize[] = "itemsize"; +static char __pyx_k__matching[] = "matching"; +static char __pyx_k__typedefs[] = "typedefs"; +static char __pyx_k__TypeError[] = "TypeError"; +static char __pyx_k____class__[] = "__class__"; +static char __pyx_k__chebyshev[] = "chebyshev"; +static char __pyx_k__cityblock[] = "cityblock"; +static char __pyx_k__enumerate[] = "enumerate"; +static char __pyx_k__euclidean[] = "euclidean"; +static char __pyx_k__haversine[] = "haversine"; +static char __pyx_k__kulsinski[] = "kulsinski"; +static char __pyx_k__manhattan[] = "manhattan"; +static char __pyx_k__minkowski[] = "minkowski"; +static char __pyx_k__IndexError[] = "IndexError"; +static char __pyx_k__ValueError[] = "ValueError"; +static char __pyx_k____import__[] = "__import__"; +static char __pyx_k__braycurtis[] = "braycurtis"; +static char __pyx_k__get_metric[] = "get_metric"; +static char __pyx_k__russellrao[] = "russellrao"; +static char __pyx_k__seuclidean[] = "seuclidean"; +static char __pyx_k__wminkowski[] = "wminkowski"; +static char __pyx_k__MemoryError[] = "MemoryError"; +static char __pyx_k__mahalanobis[] = "mahalanobis"; +static char __pyx_k__sokalsneath[] = "sokalsneath"; +static char __pyx_k__RuntimeError[] = "RuntimeError"; +static char __pyx_k____getstate__[] = "__getstate__"; +static char __pyx_k__sokalmichener[] = "sokalmichener"; +static char __pyx_k__METRIC_MAPPING[] = "METRIC_MAPPING"; +static char __pyx_k____pyx_vtable__[] = "__pyx_vtable__"; +static char __pyx_k__rogerstanimoto[] = "rogerstanimoto"; +static char __pyx_k____pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k__allocate_buffer[] = "allocate_buffer"; +static char __pyx_k__dtype_is_object[] = "dtype_is_object"; +static char __pyx_k__NotImplementedError[] = "NotImplementedError"; +static char __pyx_k____pyx_releasebuffer[] = "__pyx_releasebuffer"; +static PyObject *__pyx_kp_s_10; +static PyObject *__pyx_kp_s_101; +static PyObject *__pyx_kp_s_103; +static PyObject *__pyx_kp_s_12; +static PyObject *__pyx_kp_s_14; +static PyObject *__pyx_kp_s_17; +static PyObject *__pyx_kp_s_19; +static PyObject *__pyx_kp_s_21; +static PyObject *__pyx_kp_s_23; +static PyObject *__pyx_kp_s_25; +static PyObject *__pyx_kp_s_29; +static PyObject *__pyx_kp_s_31; +static PyObject *__pyx_kp_u_33; +static PyObject *__pyx_kp_u_35; +static PyObject *__pyx_kp_u_37; +static PyObject *__pyx_kp_u_39; +static PyObject *__pyx_kp_s_4; +static PyObject *__pyx_kp_u_40; +static PyObject *__pyx_kp_u_43; +static PyObject *__pyx_kp_s_45; +static PyObject *__pyx_kp_s_47; +static PyObject *__pyx_kp_s_50; +static PyObject *__pyx_kp_s_52; +static PyObject *__pyx_kp_s_53; +static PyObject *__pyx_kp_s_55; +static PyObject *__pyx_kp_s_57; +static PyObject *__pyx_kp_s_59; +static PyObject *__pyx_kp_s_6; +static PyObject *__pyx_kp_s_61; +static PyObject *__pyx_kp_s_63; +static PyObject *__pyx_kp_s_64; +static PyObject *__pyx_kp_s_67; +static PyObject *__pyx_kp_s_69; +static PyObject *__pyx_kp_s_74; +static PyObject *__pyx_kp_s_76; +static PyObject *__pyx_kp_b_78; +static PyObject *__pyx_kp_b_79; +static PyObject *__pyx_kp_s_8; +static PyObject *__pyx_kp_b_80; +static PyObject *__pyx_kp_b_81; +static PyObject *__pyx_kp_b_82; +static PyObject *__pyx_kp_u_83; +static PyObject *__pyx_kp_u_84; +static PyObject *__pyx_kp_s_87; +static PyObject *__pyx_n_s_88; +static PyObject *__pyx_n_s_91; +static PyObject *__pyx_kp_u_92; +static PyObject *__pyx_kp_u_93; +static PyObject *__pyx_kp_s_95; +static PyObject *__pyx_kp_s_97; +static PyObject *__pyx_kp_s_99; +static PyObject *__pyx_n_s__ASCII; +static PyObject *__pyx_n_s__C; +static PyObject *__pyx_n_s__DTYPE; +static PyObject *__pyx_n_s__Ellipsis; +static PyObject *__pyx_n_s__ITYPE; +static PyObject *__pyx_n_s__IndexError; +static PyObject *__pyx_n_s__L; +static PyObject *__pyx_n_s__METRIC_MAPPING; +static PyObject *__pyx_n_s__MemoryError; +static PyObject *__pyx_n_s__NotImplementedError; +static PyObject *__pyx_n_b__O; +static PyObject *__pyx_n_s__RuntimeError; +static PyObject *__pyx_n_s__TypeError; +static PyObject *__pyx_n_s__V; +static PyObject *__pyx_n_s__VI; +static PyObject *__pyx_n_s__ValueError; +static PyObject *__pyx_n_s__X; +static PyObject *__pyx_n_s__Y; +static PyObject *__pyx_n_s____class__; +static PyObject *__pyx_n_s____getstate__; +static PyObject *__pyx_n_s____import__; +static PyObject *__pyx_n_s____main__; +static PyObject *__pyx_n_s____name__; +static PyObject *__pyx_n_s____new__; +static PyObject *__pyx_n_s____pyx_getbuffer; +static PyObject *__pyx_n_s____pyx_releasebuffer; +static PyObject *__pyx_n_s____pyx_vtable__; +static PyObject *__pyx_n_s____test__; +static PyObject *__pyx_n_s__allocate_buffer; +static PyObject *__pyx_n_s__arcsin; +static PyObject *__pyx_n_s__asarray; +static PyObject *__pyx_n_s__base; +static PyObject *__pyx_n_s__braycurtis; +static PyObject *__pyx_n_b__c; +static PyObject *__pyx_n_s__c; +static PyObject *__pyx_n_u__c; +static PyObject *__pyx_n_s__canberra; +static PyObject *__pyx_n_s__chebyshev; +static PyObject *__pyx_n_s__cityblock; +static PyObject *__pyx_n_s__decode; +static PyObject *__pyx_n_s__dice; +static PyObject *__pyx_n_s__dtype; +static PyObject *__pyx_n_s__dtype_is_object; +static PyObject *__pyx_n_s__encode; +static PyObject *__pyx_n_s__enumerate; +static PyObject *__pyx_n_s__error; +static PyObject *__pyx_n_s__euclidean; +static PyObject *__pyx_n_s__extend; +static PyObject *__pyx_n_s__flags; +static PyObject *__pyx_n_s__format; +static PyObject *__pyx_n_b__fortran; +static PyObject *__pyx_n_s__fortran; +static PyObject *__pyx_n_s__func; +static PyObject *__pyx_n_s__get_metric; +static PyObject *__pyx_n_s__hamming; +static PyObject *__pyx_n_s__haversine; +static PyObject *__pyx_n_s__id; +static PyObject *__pyx_n_s__inf; +static PyObject *__pyx_n_s__infinity; +static PyObject *__pyx_n_s__inv; +static PyObject *__pyx_n_s__isinf; +static PyObject *__pyx_n_s__items; +static PyObject *__pyx_n_s__itemsize; +static PyObject *__pyx_n_s__jaccard; +static PyObject *__pyx_n_s__join; +static PyObject *__pyx_n_s__key; +static PyObject *__pyx_n_s__kulsinski; +static PyObject *__pyx_n_s__l1; +static PyObject *__pyx_n_s__l2; +static PyObject *__pyx_n_s__linalg; +static PyObject *__pyx_n_s__mahalanobis; +static PyObject *__pyx_n_s__manhattan; +static PyObject *__pyx_n_s__matching; +static PyObject *__pyx_n_s__memview; +static PyObject *__pyx_n_s__metric; +static PyObject *__pyx_n_s__minkowski; +static PyObject *__pyx_n_s__mode; +static PyObject *__pyx_n_s__name; +static PyObject *__pyx_n_s__ndim; +static PyObject *__pyx_n_s__newObj; +static PyObject *__pyx_n_s__np; +static PyObject *__pyx_n_s__numpy; +static PyObject *__pyx_n_s__obj; +static PyObject *__pyx_n_s__order; +static PyObject *__pyx_n_s__p; +static PyObject *__pyx_n_s__pack; +static PyObject *__pyx_n_s__pop; +static PyObject *__pyx_n_s__pyfunc; +static PyObject *__pyx_n_s__random; +static PyObject *__pyx_n_s__range; +static PyObject *__pyx_n_s__rogerstanimoto; +static PyObject *__pyx_n_s__russellrao; +static PyObject *__pyx_n_s__seuclidean; +static PyObject *__pyx_n_s__shape; +static PyObject *__pyx_n_s__sin; +static PyObject *__pyx_n_s__size; +static PyObject *__pyx_n_s__sokalmichener; +static PyObject *__pyx_n_s__sokalsneath; +static PyObject *__pyx_n_s__sqrt; +static PyObject *__pyx_n_s__start; +static PyObject *__pyx_n_s__step; +static PyObject *__pyx_n_s__stop; +static PyObject *__pyx_n_s__struct; +static PyObject *__pyx_n_s__typedefs; +static PyObject *__pyx_n_s__unpack; +static PyObject *__pyx_n_s__val; +static PyObject *__pyx_n_s__w; +static PyObject *__pyx_n_s__wminkowski; +static PyObject *__pyx_n_s__xrange; +static PyObject *__pyx_n_s__zeros; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_1; +static PyObject *__pyx_int_2; +static PyObject *__pyx_int_neg_1; +static PyObject *__pyx_int_10; +static PyObject *__pyx_int_15; +static PyObject *__pyx_k_tuple_1; +static PyObject *__pyx_k_tuple_2; +static PyObject *__pyx_k_tuple_3; +static PyObject *__pyx_k_tuple_5; +static PyObject *__pyx_k_tuple_7; +static PyObject *__pyx_k_tuple_9; +static PyObject *__pyx_k_tuple_11; +static PyObject *__pyx_k_tuple_13; +static PyObject *__pyx_k_tuple_15; +static PyObject *__pyx_k_tuple_16; +static PyObject *__pyx_k_tuple_18; +static PyObject *__pyx_k_tuple_20; +static PyObject *__pyx_k_tuple_22; +static PyObject *__pyx_k_tuple_24; +static PyObject *__pyx_k_tuple_26; +static PyObject *__pyx_k_tuple_27; +static PyObject *__pyx_k_tuple_28; +static PyObject *__pyx_k_tuple_30; +static PyObject *__pyx_k_tuple_32; +static PyObject *__pyx_k_tuple_34; +static PyObject *__pyx_k_tuple_36; +static PyObject *__pyx_k_tuple_38; +static PyObject *__pyx_k_tuple_41; +static PyObject *__pyx_k_tuple_42; +static PyObject *__pyx_k_tuple_44; +static PyObject *__pyx_k_tuple_46; +static PyObject *__pyx_k_tuple_48; +static PyObject *__pyx_k_tuple_49; +static PyObject *__pyx_k_tuple_51; +static PyObject *__pyx_k_tuple_54; +static PyObject *__pyx_k_tuple_56; +static PyObject *__pyx_k_tuple_58; +static PyObject *__pyx_k_tuple_60; +static PyObject *__pyx_k_tuple_62; +static PyObject *__pyx_k_tuple_65; +static PyObject *__pyx_k_tuple_66; +static PyObject *__pyx_k_tuple_68; +static PyObject *__pyx_k_tuple_70; +static PyObject *__pyx_k_tuple_85; +static PyObject *__pyx_k_tuple_89; +static PyObject *__pyx_k_tuple_96; +static PyObject *__pyx_k_tuple_98; +static PyObject *__pyx_k_tuple_100; +static PyObject *__pyx_k_tuple_102; +static PyObject *__pyx_k_tuple_104; +static PyObject *__pyx_k_codeobj_86; +static PyObject *__pyx_k_codeobj_90; + +/* "sklearn/neighbors/dist_metrics.pyx":17 + * ###################################################################### + * # Numpy 1.3-1.4 compatibility utilities + * cdef DTYPE_t[:, ::1] get_memview_DTYPE_2D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X): + * return ( X.data) + */ + +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_12dist_metrics_get_memview_DTYPE_2D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_DTYPE_2D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; + + /* "sklearn/neighbors/dist_metrics.pyx":19 + * cdef DTYPE_t[:, ::1] get_memview_DTYPE_2D( + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = ((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0])), ((Py_ssize_t)(__pyx_v_X->dimensions[1]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "c", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.get_memview_DTYPE_2D", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = __pyx_r; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":22 + * + * + * cdef DTYPE_t* get_vec_ptr(np.ndarray[DTYPE_t, ndim=1, mode='c'] vec): # <<<<<<<<<<<<<< + * return &vec[0] + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_f_7sklearn_9neighbors_12dist_metrics_get_vec_ptr(PyArrayObject *__pyx_v_vec) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_vec; + __Pyx_Buffer __pyx_pybuffer_vec; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_r; + __Pyx_RefNannyDeclarations + long __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_vec_ptr", 0); + __pyx_pybuffer_vec.pybuffer.buf = NULL; + __pyx_pybuffer_vec.refcount = 0; + __pyx_pybuffernd_vec.data = NULL; + __pyx_pybuffernd_vec.rcbuffer = &__pyx_pybuffer_vec; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_vec.rcbuffer->pybuffer, (PyObject*)__pyx_v_vec, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_vec.diminfo[0].strides = __pyx_pybuffernd_vec.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_vec.diminfo[0].shape = __pyx_pybuffernd_vec.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/neighbors/dist_metrics.pyx":23 + * + * cdef DTYPE_t* get_vec_ptr(np.ndarray[DTYPE_t, ndim=1, mode='c'] vec): + * return &vec[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = 0; + __pyx_r = (&(*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_pybuffernd_vec.rcbuffer->pybuffer.buf, __pyx_t_1, __pyx_pybuffernd_vec.diminfo[0].strides))); + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_vec.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_WriteUnraisable("sklearn.neighbors.dist_metrics.get_vec_ptr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_vec.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":26 + * + * + * cdef DTYPE_t* get_mat_ptr(np.ndarray[DTYPE_t, ndim=2, mode='c'] mat): # <<<<<<<<<<<<<< + * return &mat[0, 0] + * ###################################################################### + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_f_7sklearn_9neighbors_12dist_metrics_get_mat_ptr(PyArrayObject *__pyx_v_mat) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_mat; + __Pyx_Buffer __pyx_pybuffer_mat; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_r; + __Pyx_RefNannyDeclarations + long __pyx_t_1; + long __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_mat_ptr", 0); + __pyx_pybuffer_mat.pybuffer.buf = NULL; + __pyx_pybuffer_mat.refcount = 0; + __pyx_pybuffernd_mat.data = NULL; + __pyx_pybuffernd_mat.rcbuffer = &__pyx_pybuffer_mat; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_mat.rcbuffer->pybuffer, (PyObject*)__pyx_v_mat, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_mat.diminfo[0].strides = __pyx_pybuffernd_mat.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_mat.diminfo[0].shape = __pyx_pybuffernd_mat.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_mat.diminfo[1].strides = __pyx_pybuffernd_mat.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_mat.diminfo[1].shape = __pyx_pybuffernd_mat.rcbuffer->pybuffer.shape[1]; + + /* "sklearn/neighbors/dist_metrics.pyx":27 + * + * cdef DTYPE_t* get_mat_ptr(np.ndarray[DTYPE_t, ndim=2, mode='c'] mat): + * return &mat[0, 0] # <<<<<<<<<<<<<< + * ###################################################################### + * + */ + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_r = (&(*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_pybuffernd_mat.rcbuffer->pybuffer.buf, __pyx_t_1, __pyx_pybuffernd_mat.diminfo[0].strides, __pyx_t_2, __pyx_pybuffernd_mat.diminfo[1].strides))); + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mat.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_WriteUnraisable("sklearn.neighbors.dist_metrics.get_mat_ptr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mat.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":37 + * + * + * cdef inline np.ndarray _buffer_to_ndarray(DTYPE_t* x, np.npy_intp n): # <<<<<<<<<<<<<< + * # Wrap a memory buffer with an ndarray. Warning: this is not robust. + * # In particular, if x is deallocated before the returned array goes + */ + +static CYTHON_INLINE PyArrayObject *__pyx_f_7sklearn_9neighbors_12dist_metrics__buffer_to_ndarray(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x, npy_intp __pyx_v_n) { + PyArrayObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_buffer_to_ndarray", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":44 + * + * # Note: this Segfaults unless np.import_array() is called above + * return PyArray_SimpleNewFromData(1, &n, DTYPECODE, x) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __pyx_t_1 = PyArray_SimpleNewFromData(1, (&__pyx_v_n), __pyx_e_7sklearn_9neighbors_8typedefs_DTYPECODE, ((void *)__pyx_v_x)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics._buffer_to_ndarray", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_1newObj(PyObject *__pyx_self, PyObject *__pyx_v_obj); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_12dist_metrics_1newObj = {__Pyx_NAMESTR("newObj"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_1newObj, METH_O, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_1newObj(PyObject *__pyx_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("newObj (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_newObj(__pyx_self, ((PyObject *)__pyx_v_obj)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":58 + * # newObj function + * # this is a helper function for pickling + * def newObj(obj): # <<<<<<<<<<<<<< + * return obj.__new__(obj) + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_newObj(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("newObj", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":59 + * # this is a helper function for pickling + * def newObj(obj): + * return obj.__new__(obj) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_obj, __pyx_n_s____new__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.newObj", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_3get_valid_metric_ids(PyObject *__pyx_self, PyObject *__pyx_v_L); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_12dist_metrics_2get_valid_metric_ids[] = "Given an iterable of metric class names or class identifiers,\n return a list of metric IDs which map to those classes.\n\n Example:\n >>> L = get_valid_metric_ids([EuclideanDistance, 'ManhattanDistance'])\n >>> sorted(L)\n ['cityblock', 'euclidean', 'l1', 'l2', 'manhattan']\n "; +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_12dist_metrics_3get_valid_metric_ids = {__Pyx_NAMESTR("get_valid_metric_ids"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_3get_valid_metric_ids, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_12dist_metrics_2get_valid_metric_ids)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_3get_valid_metric_ids(PyObject *__pyx_self, PyObject *__pyx_v_L) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_valid_metric_ids (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_2get_valid_metric_ids(__pyx_self, ((PyObject *)__pyx_v_L)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":92 + * + * + * def get_valid_metric_ids(L): # <<<<<<<<<<<<<< + * """Given an iterable of metric class names or class identifiers, + * return a list of metric IDs which map to those classes. + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_2get_valid_metric_ids(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_L) { + PyObject *__pyx_v_key = NULL; + PyObject *__pyx_v_val = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + Py_ssize_t __pyx_t_4; + PyObject *(*__pyx_t_5)(PyObject *); + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *(*__pyx_t_9)(PyObject *); + int __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_valid_metric_ids", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":101 + * ['cityblock', 'euclidean', 'l1', 'l2', 'manhattan'] + * """ + * return [key for (key, val) in METRIC_MAPPING.items() # <<<<<<<<<<<<<< + * if (val.__name__ in L) or (val in L)] + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__METRIC_MAPPING); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__items); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyList_CheckExact(__pyx_t_2) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_3 = __pyx_t_2; __Pyx_INCREF(__pyx_t_3); __pyx_t_4 = 0; + __pyx_t_5 = NULL; + } else { + __pyx_t_4 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = Py_TYPE(__pyx_t_3)->tp_iternext; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (!__pyx_t_5 && PyList_CheckExact(__pyx_t_3)) { + if (__pyx_t_4 >= PyList_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_4); __Pyx_INCREF(__pyx_t_2); __pyx_t_4++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_3, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_5 && PyTuple_CheckExact(__pyx_t_3)) { + if (__pyx_t_4 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_4); __Pyx_INCREF(__pyx_t_2); __pyx_t_4++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_3, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_2 = __pyx_t_5(__pyx_t_3); + if (unlikely(!__pyx_t_2)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_2); + } + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_6 = PyList_GET_ITEM(sequence, 0); + __pyx_t_7 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_6); + __Pyx_INCREF(__pyx_t_7); + #else + __pyx_t_6 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else + { + Py_ssize_t index = -1; + __pyx_t_8 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_9 = Py_TYPE(__pyx_t_8)->tp_iternext; + index = 0; __pyx_t_6 = __pyx_t_9(__pyx_t_8); if (unlikely(!__pyx_t_6)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + index = 1; __pyx_t_7 = __pyx_t_9(__pyx_t_8); if (unlikely(!__pyx_t_7)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_7); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_9(__pyx_t_8), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = NULL; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_9 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; + } + __Pyx_XDECREF(__pyx_v_key); + __pyx_v_key = __pyx_t_6; + __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_v_val); + __pyx_v_val = __pyx_t_7; + __pyx_t_7 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":102 + * """ + * return [key for (key, val) in METRIC_MAPPING.items() + * if (val.__name__ in L) or (val in L)] # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_val, __pyx_n_s____name__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_10 = (__Pyx_PySequence_Contains(__pyx_t_2, __pyx_v_L, Py_EQ)); if (unlikely(__pyx_t_10 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(__pyx_t_10 != 0)) { + __pyx_t_11 = (__Pyx_PySequence_Contains(__pyx_v_val, __pyx_v_L, Py_EQ)); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = (__pyx_t_11 != 0); + } else { + __pyx_t_12 = (__pyx_t_10 != 0); + } + if (__pyx_t_12) { + + /* "sklearn/neighbors/dist_metrics.pyx":101 + * ['cityblock', 'euclidean', 'l1', 'l2', 'manhattan'] + * """ + * return [key for (key, val) in METRIC_MAPPING.items() # <<<<<<<<<<<<<< + * if (val.__name__ in L) or (val in L)] + * + */ + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_v_key))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.get_valid_metric_ids", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_key); + __Pyx_XDECREF(__pyx_v_val); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} + if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric___cinit__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":209 + * scaling as other distances. + * """ + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.p = 2 + * self.vec = np.zeros(1, dtype=DTYPE, order='c') + */ + +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric___cinit__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":210 + * """ + * def __cinit__(self): + * self.p = 2 # <<<<<<<<<<<<<< + * self.vec = np.zeros(1, dtype=DTYPE, order='c') + * self.mat = np.zeros((1, 1), dtype=DTYPE, order='c') + */ + __pyx_v_self->p = 2.0; + + /* "sklearn/neighbors/dist_metrics.pyx":211 + * def __cinit__(self): + * self.p = 2 + * self.vec = np.zeros(1, dtype=DTYPE, order='c') # <<<<<<<<<<<<<< + * self.mat = np.zeros((1, 1), dtype=DTYPE, order='c') + * self.vec_ptr = get_vec_ptr(self.vec) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__c)) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_k_tuple_1), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->vec); + __Pyx_DECREF(((PyObject *)__pyx_v_self->vec)); + __pyx_v_self->vec = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":212 + * self.p = 2 + * self.vec = np.zeros(1, dtype=DTYPE, order='c') + * self.mat = np.zeros((1, 1), dtype=DTYPE, order='c') # <<<<<<<<<<<<<< + * self.vec_ptr = get_vec_ptr(self.vec) + * self.mat_ptr = get_mat_ptr(self.mat) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__c)) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_3), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_self->mat); + __Pyx_DECREF(((PyObject *)__pyx_v_self->mat)); + __pyx_v_self->mat = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":213 + * self.vec = np.zeros(1, dtype=DTYPE, order='c') + * self.mat = np.zeros((1, 1), dtype=DTYPE, order='c') + * self.vec_ptr = get_vec_ptr(self.vec) # <<<<<<<<<<<<<< + * self.mat_ptr = get_mat_ptr(self.mat) + * self.size = 1 + */ + __pyx_t_2 = ((PyObject *)__pyx_v_self->vec); + __Pyx_INCREF(__pyx_t_2); + __pyx_v_self->vec_ptr = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_vec_ptr(((PyArrayObject *)__pyx_t_2)); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":214 + * self.mat = np.zeros((1, 1), dtype=DTYPE, order='c') + * self.vec_ptr = get_vec_ptr(self.vec) + * self.mat_ptr = get_mat_ptr(self.mat) # <<<<<<<<<<<<<< + * self.size = 1 + * + */ + __pyx_t_2 = ((PyObject *)__pyx_v_self->mat); + __Pyx_INCREF(__pyx_t_2); + __pyx_v_self->mat_ptr = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_mat_ptr(((PyArrayObject *)__pyx_t_2)); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":215 + * self.vec_ptr = get_vec_ptr(self.vec) + * self.mat_ptr = get_mat_ptr(self.mat) + * self.size = 1 # <<<<<<<<<<<<<< + * + * def __reduce__(self): + */ + __pyx_v_self->size = 1; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_2__reduce__[] = "\n reduce method used for pickling\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_3__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_2__reduce__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":217 + * self.size = 1 + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * """ + * reduce method used for pickling + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_2__reduce__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":221 + * reduce method used for pickling + * """ + * return (newObj, (self.__class__,), self.__getstate__()) # <<<<<<<<<<<<<< + * + * def __getstate__(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__newObj); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s____class__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s____getstate__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_r = ((PyObject *)__pyx_t_2); + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_5__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_4__getstate__[] = "\n get state for pickling\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_5__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_4__getstate__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":223 + * return (newObj, (self.__class__,), self.__getstate__()) + * + * def __getstate__(self): # <<<<<<<<<<<<<< + * """ + * get state for pickling + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_4__getstate__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getstate__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":227 + * get state for pickling + * """ + * return (float(self.p), self.vec, self.mat) # <<<<<<<<<<<<<< + * + * def __setstate__(self, state): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyFloat_FromDouble(((double)__pyx_v_self->p)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_self->vec)); + PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_self->vec)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->vec)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->mat)); + PyTuple_SET_ITEM(__pyx_t_2, 2, ((PyObject *)__pyx_v_self->mat)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->mat)); + __pyx_t_1 = 0; + __pyx_r = ((PyObject *)__pyx_t_2); + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_7__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_state); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_6__setstate__[] = "\n set state for pickling\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_7__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_state) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_6__setstate__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self), ((PyObject *)__pyx_v_state)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":229 + * return (float(self.p), self.vec, self.mat) + * + * def __setstate__(self, state): # <<<<<<<<<<<<<< + * """ + * set state for pickling + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_6__setstate__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, PyObject *__pyx_v_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":233 + * set state for pickling + * """ + * self.p = state[0] # <<<<<<<<<<<<<< + * self.vec = state[1] + * self.mat = state[2] + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 0, sizeof(long), PyInt_FromLong, 0, 0, 0); if (!__pyx_t_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_2 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->p = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":234 + * """ + * self.p = state[0] + * self.vec = state[1] # <<<<<<<<<<<<<< + * self.mat = state[2] + * self.vec_ptr = get_vec_ptr(self.vec) + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 1, sizeof(long), PyInt_FromLong, 0, 0, 0); if (!__pyx_t_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->vec); + __Pyx_DECREF(((PyObject *)__pyx_v_self->vec)); + __pyx_v_self->vec = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":235 + * self.p = state[0] + * self.vec = state[1] + * self.mat = state[2] # <<<<<<<<<<<<<< + * self.vec_ptr = get_vec_ptr(self.vec) + * self.mat_ptr = get_mat_ptr(self.mat) + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 2, sizeof(long), PyInt_FromLong, 0, 0, 0); if (!__pyx_t_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->mat); + __Pyx_DECREF(((PyObject *)__pyx_v_self->mat)); + __pyx_v_self->mat = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":236 + * self.vec = state[1] + * self.mat = state[2] + * self.vec_ptr = get_vec_ptr(self.vec) # <<<<<<<<<<<<<< + * self.mat_ptr = get_mat_ptr(self.mat) + * self.size = 1 + */ + __pyx_t_1 = ((PyObject *)__pyx_v_self->vec); + __Pyx_INCREF(__pyx_t_1); + __pyx_v_self->vec_ptr = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_vec_ptr(((PyArrayObject *)__pyx_t_1)); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":237 + * self.mat = state[2] + * self.vec_ptr = get_vec_ptr(self.vec) + * self.mat_ptr = get_mat_ptr(self.mat) # <<<<<<<<<<<<<< + * self.size = 1 + * + */ + __pyx_t_1 = ((PyObject *)__pyx_v_self->mat); + __Pyx_INCREF(__pyx_t_1); + __pyx_v_self->mat_ptr = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_mat_ptr(((PyArrayObject *)__pyx_t_1)); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":238 + * self.vec_ptr = get_vec_ptr(self.vec) + * self.mat_ptr = get_mat_ptr(self.mat) + * self.size = 1 # <<<<<<<<<<<<<< + * + * @classmethod + */ + __pyx_v_self->size = 1; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.__setstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_9get_metric(PyObject *__pyx_v_cls, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_8get_metric[] = "Get the given distance metric from the string identifier.\n\n See the docstring of DistanceMetric for a list of available metrics.\n\n Parameters\n ----------\n metric : string or class name\n The distance metric to use\n **kwargs\n additional arguments will be passed to the requested metric\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_9get_metric(PyObject *__pyx_v_cls, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_metric = 0; + PyObject *__pyx_v_kwargs = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_metric (wrapper)", 0); + __pyx_v_kwargs = PyDict_New(); if (unlikely(!__pyx_v_kwargs)) return NULL; + __Pyx_GOTREF(__pyx_v_kwargs); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__metric,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__metric)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, __pyx_v_kwargs, values, pos_args, "get_metric") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_metric = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_metric", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_DECREF(__pyx_v_kwargs); __pyx_v_kwargs = 0; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.get_metric", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_8get_metric(((PyObject*)__pyx_v_cls), __pyx_v_metric, __pyx_v_kwargs); + __Pyx_XDECREF(__pyx_v_kwargs); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":241 + * + * @classmethod + * def get_metric(cls, metric, **kwargs): # <<<<<<<<<<<<<< + * """Get the given distance metric from the string identifier. + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_8get_metric(CYTHON_UNUSED PyObject *__pyx_v_cls, PyObject *__pyx_v_metric, PyObject *__pyx_v_kwargs) { + PyObject *__pyx_v_p = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_metric", 0); + __Pyx_INCREF(__pyx_v_metric); + + /* "sklearn/neighbors/dist_metrics.pyx":253 + * additional arguments will be passed to the requested metric + * """ + * if isinstance(metric, DistanceMetric): # <<<<<<<<<<<<<< + * return metric + * + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_metric, ((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "sklearn/neighbors/dist_metrics.pyx":254 + * """ + * if isinstance(metric, DistanceMetric): + * return metric # <<<<<<<<<<<<<< + * + * if callable(metric): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_metric); + __pyx_r = __pyx_v_metric; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/neighbors/dist_metrics.pyx":256 + * return metric + * + * if callable(metric): # <<<<<<<<<<<<<< + * return PyFuncDistance(metric, **kwargs) + * + */ + __pyx_t_2 = __Pyx_PyCallable_Check(__pyx_v_metric); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/dist_metrics.pyx":257 + * + * if callable(metric): + * return PyFuncDistance(metric, **kwargs) # <<<<<<<<<<<<<< + * + * # Map the metric string ID to the metric class + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_metric); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_metric); + __Pyx_GIVEREF(__pyx_v_metric); + __pyx_t_4 = ((PyObject *)__pyx_v_kwargs); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_PyFuncDistance)), ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + goto __pyx_L4; + } + __pyx_L4:; + + /* "sklearn/neighbors/dist_metrics.pyx":260 + * + * # Map the metric string ID to the metric class + * if isinstance(metric, type) and issubclass(metric, DistanceMetric): # <<<<<<<<<<<<<< + * pass + * else: + */ + __pyx_t_1 = PyType_Check(__pyx_v_metric); + if ((__pyx_t_1 != 0)) { + __pyx_t_2 = PyObject_IsSubclass(__pyx_v_metric, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric))); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = (__pyx_t_2 != 0); + } else { + __pyx_t_6 = (__pyx_t_1 != 0); + } + if (__pyx_t_6) { + goto __pyx_L5; + } + /*else*/ { + + /* "sklearn/neighbors/dist_metrics.pyx":263 + * pass + * else: + * try: # <<<<<<<<<<<<<< + * metric = METRIC_MAPPING[metric] + * except: + */ + { + __Pyx_ExceptionSave(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + /*try:*/ { + + /* "sklearn/neighbors/dist_metrics.pyx":264 + * else: + * try: + * metric = METRIC_MAPPING[metric] # <<<<<<<<<<<<<< + * except: + * raise ValueError("Unrecognized metric '%s'" % metric) + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__METRIC_MAPPING); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 264; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyObject_GetItem(__pyx_t_5, __pyx_v_metric); if (!__pyx_t_4) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 264; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_v_metric); + __pyx_v_metric = __pyx_t_4; + __pyx_t_4 = 0; + } + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L13_try_end; + __pyx_L6_error:; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":265 + * try: + * metric = METRIC_MAPPING[metric] + * except: # <<<<<<<<<<<<<< + * raise ValueError("Unrecognized metric '%s'" % metric) + * + */ + /*except:*/ { + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.get_metric", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_4, &__pyx_t_5, &__pyx_t_3) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 265; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_3); + + /* "sklearn/neighbors/dist_metrics.pyx":266 + * metric = METRIC_MAPPING[metric] + * except: + * raise ValueError("Unrecognized metric '%s'" % metric) # <<<<<<<<<<<<<< + * + * # In Minkowski special cases, return more efficient methods + */ + __pyx_t_10 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_4), __pyx_v_metric); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_10)); + __pyx_t_11 = PyTuple_New(1); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_GOTREF(__pyx_t_11); + PyTuple_SET_ITEM(__pyx_t_11, 0, ((PyObject *)__pyx_t_10)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_10)); + __pyx_t_10 = 0; + __pyx_t_10 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_11), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(((PyObject *)__pyx_t_11)); __pyx_t_11 = 0; + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L7_exception_handled; + } + __pyx_L8_except_error:; + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_ExceptionReset(__pyx_t_7, __pyx_t_8, __pyx_t_9); + goto __pyx_L1_error; + __pyx_L7_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_ExceptionReset(__pyx_t_7, __pyx_t_8, __pyx_t_9); + __pyx_L13_try_end:; + } + } + __pyx_L5:; + + /* "sklearn/neighbors/dist_metrics.pyx":269 + * + * # In Minkowski special cases, return more efficient methods + * if metric is MinkowskiDistance: # <<<<<<<<<<<<<< + * p = kwargs.pop('p', 2) + * if p == 1: + */ + __pyx_t_6 = (__pyx_v_metric == ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance))); + __pyx_t_1 = (__pyx_t_6 != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/dist_metrics.pyx":270 + * # In Minkowski special cases, return more efficient methods + * if metric is MinkowskiDistance: + * p = kwargs.pop('p', 2) # <<<<<<<<<<<<<< + * if p == 1: + * return ManhattanDistance(**kwargs) + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_kwargs), __pyx_n_s__pop); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_k_tuple_5), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_p = __pyx_t_5; + __pyx_t_5 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":271 + * if metric is MinkowskiDistance: + * p = kwargs.pop('p', 2) + * if p == 1: # <<<<<<<<<<<<<< + * return ManhattanDistance(**kwargs) + * elif p == 2: + */ + __pyx_t_5 = PyObject_RichCompare(__pyx_v_p, __pyx_int_1, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_1) { + + /* "sklearn/neighbors/dist_metrics.pyx":272 + * p = kwargs.pop('p', 2) + * if p == 1: + * return ManhattanDistance(**kwargs) # <<<<<<<<<<<<<< + * elif p == 2: + * return EuclideanDistance(**kwargs) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = ((PyObject *)__pyx_v_kwargs); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_3 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_ManhattanDistance)), ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + goto __pyx_L17; + } + + /* "sklearn/neighbors/dist_metrics.pyx":273 + * if p == 1: + * return ManhattanDistance(**kwargs) + * elif p == 2: # <<<<<<<<<<<<<< + * return EuclideanDistance(**kwargs) + * elif np.isinf(p): + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_p, __pyx_int_2, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_1) { + + /* "sklearn/neighbors/dist_metrics.pyx":274 + * return ManhattanDistance(**kwargs) + * elif p == 2: + * return EuclideanDistance(**kwargs) # <<<<<<<<<<<<<< + * elif np.isinf(p): + * return ChebyshevDistance(**kwargs) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_v_kwargs); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_5 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_EuclideanDistance)), ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 274; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + goto __pyx_L17; + } + + /* "sklearn/neighbors/dist_metrics.pyx":275 + * elif p == 2: + * return EuclideanDistance(**kwargs) + * elif np.isinf(p): # <<<<<<<<<<<<<< + * return ChebyshevDistance(**kwargs) + * else: + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__isinf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_p); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_p); + __Pyx_GIVEREF(__pyx_v_p); + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_1) { + + /* "sklearn/neighbors/dist_metrics.pyx":276 + * return EuclideanDistance(**kwargs) + * elif np.isinf(p): + * return ChebyshevDistance(**kwargs) # <<<<<<<<<<<<<< + * else: + * return MinkowskiDistance(p, **kwargs) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_kwargs); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance)), ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + goto __pyx_L17; + } + /*else*/ { + + /* "sklearn/neighbors/dist_metrics.pyx":278 + * return ChebyshevDistance(**kwargs) + * else: + * return MinkowskiDistance(p, **kwargs) # <<<<<<<<<<<<<< + * else: + * return metric(**kwargs) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_p); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_p); + __Pyx_GIVEREF(__pyx_v_p); + __pyx_t_4 = ((PyObject *)__pyx_v_kwargs); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_3 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance)), ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + __pyx_L17:; + goto __pyx_L16; + } + /*else*/ { + + /* "sklearn/neighbors/dist_metrics.pyx":280 + * return MinkowskiDistance(p, **kwargs) + * else: + * return metric(**kwargs) # <<<<<<<<<<<<<< + * + * def __init__(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_v_kwargs); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = PyObject_Call(__pyx_v_metric, ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + } + __pyx_L16:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.get_metric", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_p); + __Pyx_XDECREF(__pyx_v_metric); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} + if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__init__", 0))) return -1; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_10__init__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":282 + * return metric(**kwargs) + * + * def __init__(self): # <<<<<<<<<<<<<< + * if self.__class__ is DistanceMetric: + * raise NotImplementedError("DistanceMetric is an abstract class") + */ + +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_10__init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":283 + * + * def __init__(self): + * if self.__class__ is DistanceMetric: # <<<<<<<<<<<<<< + * raise NotImplementedError("DistanceMetric is an abstract class") + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s____class__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = (__pyx_t_1 == ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric))); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "sklearn/neighbors/dist_metrics.pyx":284 + * def __init__(self): + * if self.__class__ is DistanceMetric: + * raise NotImplementedError("DistanceMetric is an abstract class") # <<<<<<<<<<<<<< + * + * cdef DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size) except -1: + */ + __pyx_t_1 = PyObject_Call(__pyx_builtin_NotImplementedError, ((PyObject *)__pyx_k_tuple_7), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":286 + * raise NotImplementedError("DistanceMetric is an abstract class") + * + * cdef DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size) except -1: # <<<<<<<<<<<<<< + * """Compute the distance between vectors x1 and x2 + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":291 + * This should be overridden in a base class. + * """ + * return -999 # <<<<<<<<<<<<<< + * + * cdef DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size) except -1: + */ + __pyx_r = -999.0; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":293 + * return -999 + * + * cdef DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size) except -1: # <<<<<<<<<<<<<< + * """Compute the reduced distance between vectors x1 and x2. + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_rdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":303 + * distance. + * """ + * return self.dist(x1, x2, size) # <<<<<<<<<<<<<< + * + * cdef int pdist(self, DTYPE_t[:, ::1] X, DTYPE_t[:, ::1] D) except -1: + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->__pyx_vtab)->dist(__pyx_v_self, __pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_1 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 303; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":305 + * return self.dist(x1, x2, size) + * + * cdef int pdist(self, DTYPE_t[:, ::1] X, DTYPE_t[:, ::1] D) except -1: # <<<<<<<<<<<<<< + * """compute the pairwise distances between points in X""" + * cdef ITYPE_t i1, i2 + */ + +static int __pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_pdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_D) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":308 + * """compute the pairwise distances between points in X""" + * cdef ITYPE_t i1, i2 + * for i1 in range(X.shape[0]): # <<<<<<<<<<<<<< + * for i2 in range(i1, X.shape[0]): + * D[i1, i2] = self.dist(&X[i1, 0], &X[i2, 0], X.shape[1]) + */ + __pyx_t_1 = (__pyx_v_X.shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i1 = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":309 + * cdef ITYPE_t i1, i2 + * for i1 in range(X.shape[0]): + * for i2 in range(i1, X.shape[0]): # <<<<<<<<<<<<<< + * D[i1, i2] = self.dist(&X[i1, 0], &X[i2, 0], X.shape[1]) + * D[i2, i1] = D[i1, i2] + */ + __pyx_t_3 = (__pyx_v_X.shape[0]); + for (__pyx_t_4 = __pyx_v_i1; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i2 = __pyx_t_4; + + /* "sklearn/neighbors/dist_metrics.pyx":310 + * for i1 in range(X.shape[0]): + * for i2 in range(i1, X.shape[0]): + * D[i1, i2] = self.dist(&X[i1, 0], &X[i2, 0], X.shape[1]) # <<<<<<<<<<<<<< + * D[i2, i1] = D[i1, i2] + * return 0 + */ + __pyx_t_5 = __pyx_v_i1; + __pyx_t_6 = 0; + __pyx_t_7 = __pyx_v_i2; + __pyx_t_8 = 0; + __pyx_t_9 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->__pyx_vtab)->dist(__pyx_v_self, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_X.data + __pyx_t_5 * __pyx_v_X.strides[0]) )) + __pyx_t_6)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_X.data + __pyx_t_7 * __pyx_v_X.strides[0]) )) + __pyx_t_8)) )))), (__pyx_v_X.shape[1])); if (unlikely(__pyx_t_9 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_v_i1; + __pyx_t_11 = __pyx_v_i2; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_D.data + __pyx_t_10 * __pyx_v_D.strides[0]) )) + __pyx_t_11)) )) = __pyx_t_9; + + /* "sklearn/neighbors/dist_metrics.pyx":311 + * for i2 in range(i1, X.shape[0]): + * D[i1, i2] = self.dist(&X[i1, 0], &X[i2, 0], X.shape[1]) + * D[i2, i1] = D[i1, i2] # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_t_12 = __pyx_v_i1; + __pyx_t_13 = __pyx_v_i2; + __pyx_t_14 = __pyx_v_i2; + __pyx_t_15 = __pyx_v_i1; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_D.data + __pyx_t_14 * __pyx_v_D.strides[0]) )) + __pyx_t_15)) )) = (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_D.data + __pyx_t_12 * __pyx_v_D.strides[0]) )) + __pyx_t_13)) ))); + } + } + + /* "sklearn/neighbors/dist_metrics.pyx":312 + * D[i1, i2] = self.dist(&X[i1, 0], &X[i2, 0], X.shape[1]) + * D[i2, i1] = D[i1, i2] + * return 0 # <<<<<<<<<<<<<< + * + * cdef int cdist(self, DTYPE_t[:, ::1] X, DTYPE_t[:, ::1] Y, + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.pdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":314 + * return 0 + * + * cdef int cdist(self, DTYPE_t[:, ::1] X, DTYPE_t[:, ::1] Y, # <<<<<<<<<<<<<< + * DTYPE_t[:, ::1] D) except -1: + * """compute the cross-pairwise distances between arrays X and Y""" + */ + +static int __pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_cdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_D) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("cdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":318 + * """compute the cross-pairwise distances between arrays X and Y""" + * cdef ITYPE_t i1, i2 + * if X.shape[1] != Y.shape[1]: # <<<<<<<<<<<<<< + * raise ValueError('X and Y must have the same second dimension') + * for i1 in range(X.shape[0]): + */ + __pyx_t_1 = (((__pyx_v_X.shape[1]) != (__pyx_v_Y.shape[1])) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/dist_metrics.pyx":319 + * cdef ITYPE_t i1, i2 + * if X.shape[1] != Y.shape[1]: + * raise ValueError('X and Y must have the same second dimension') # <<<<<<<<<<<<<< + * for i1 in range(X.shape[0]): + * for i2 in range(Y.shape[0]): + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/neighbors/dist_metrics.pyx":320 + * if X.shape[1] != Y.shape[1]: + * raise ValueError('X and Y must have the same second dimension') + * for i1 in range(X.shape[0]): # <<<<<<<<<<<<<< + * for i2 in range(Y.shape[0]): + * D[i1, i2] = self.dist(&X[i1, 0], &Y[i2, 0], X.shape[1]) + */ + __pyx_t_3 = (__pyx_v_X.shape[0]); + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i1 = __pyx_t_4; + + /* "sklearn/neighbors/dist_metrics.pyx":321 + * raise ValueError('X and Y must have the same second dimension') + * for i1 in range(X.shape[0]): + * for i2 in range(Y.shape[0]): # <<<<<<<<<<<<<< + * D[i1, i2] = self.dist(&X[i1, 0], &Y[i2, 0], X.shape[1]) + * return 0 + */ + __pyx_t_5 = (__pyx_v_Y.shape[0]); + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i2 = __pyx_t_6; + + /* "sklearn/neighbors/dist_metrics.pyx":322 + * for i1 in range(X.shape[0]): + * for i2 in range(Y.shape[0]): + * D[i1, i2] = self.dist(&X[i1, 0], &Y[i2, 0], X.shape[1]) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_t_7 = __pyx_v_i1; + __pyx_t_8 = 0; + __pyx_t_9 = __pyx_v_i2; + __pyx_t_10 = 0; + __pyx_t_11 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->__pyx_vtab)->dist(__pyx_v_self, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_X.data + __pyx_t_7 * __pyx_v_X.strides[0]) )) + __pyx_t_8)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_9 * __pyx_v_Y.strides[0]) )) + __pyx_t_10)) )))), (__pyx_v_X.shape[1])); if (unlikely(__pyx_t_11 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = __pyx_v_i1; + __pyx_t_13 = __pyx_v_i2; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_D.data + __pyx_t_12 * __pyx_v_D.strides[0]) )) + __pyx_t_13)) )) = __pyx_t_11; + } + } + + /* "sklearn/neighbors/dist_metrics.pyx":323 + * for i2 in range(Y.shape[0]): + * D[i1, i2] = self.dist(&X[i1, 0], &Y[i2, 0], X.shape[1]) + * return 0 # <<<<<<<<<<<<<< + * + * cdef DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.cdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":325 + * return 0 + * + * cdef DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: # <<<<<<<<<<<<<< + * """Convert the reduced distance to the distance""" + * return rdist + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric__rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rdist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":327 + * cdef DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + * """Convert the reduced distance to the distance""" + * return rdist # <<<<<<<<<<<<<< + * + * cdef DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + */ + __pyx_r = __pyx_v_rdist; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":329 + * return rdist + * + * cdef DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * """Convert the distance to the reduced distance""" + * return dist + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric__dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":331 + * cdef DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + * """Convert the distance to the reduced distance""" + * return dist # <<<<<<<<<<<<<< + * + * def rdist_to_dist(self, rdist): + */ + __pyx_r = __pyx_v_dist; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_13rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_12rdist_to_dist[] = "Convert the Reduced distance to the true distance.\n\n The reduced distance, defined for some metrics, is a computationally\n more efficent measure which preserves the rank of the true distance.\n For example, in the Euclidean distance metric, the reduced distance\n is the squared-euclidean distance.\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_13rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("rdist_to_dist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_12rdist_to_dist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self), ((PyObject *)__pyx_v_rdist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":333 + * return dist + * + * def rdist_to_dist(self, rdist): # <<<<<<<<<<<<<< + * """Convert the Reduced distance to the true distance. + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_12rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":341 + * is the squared-euclidean distance. + * """ + * return rdist # <<<<<<<<<<<<<< + * + * def dist_to_rdist(self, dist): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_rdist); + __pyx_r = __pyx_v_rdist; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_15dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_14dist_to_rdist[] = "Convert the true distance to the reduced distance.\n\n The reduced distance, defined for some metrics, is a computationally\n more efficent measure which preserves the rank of the true distance.\n For example, in the Euclidean distance metric, the reduced distance\n is the squared-euclidean distance.\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_15dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dist_to_rdist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_14dist_to_rdist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self), ((PyObject *)__pyx_v_dist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":343 + * return rdist + * + * def dist_to_rdist(self, dist): # <<<<<<<<<<<<<< + * """Convert the true distance to the reduced distance. + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_14dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":351 + * is the squared-euclidean distance. + * """ + * return dist # <<<<<<<<<<<<<< + * + * def pairwise(self, X, Y=None): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_dist); + __pyx_r = __pyx_v_dist; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_17pairwise(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_16pairwise[] = "Compute the pairwise distances between X and Y\n\n This is a convenience routine for the sake of testing. For many\n metrics, the utilities in scipy.spatial.distance.cdist and\n scipy.spatial.distance.pdist will be faster.\n\n Parameters\n ----------\n X : array_like\n Array of shape (Nx, D), representing Nx points in D dimensions.\n Y : array_like (optional)\n Array of shape (Ny, D), representing Ny points in D dimensions.\n If not specified, then Y=X.\n Returns\n -------\n dist : ndarray\n The shape (Nx, Ny) array of pairwise distances between points in\n X and Y.\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_17pairwise(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_X = 0; + PyObject *__pyx_v_Y = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("pairwise (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__Y,0}; + PyObject* values[2] = {0,0}; + + /* "sklearn/neighbors/dist_metrics.pyx":353 + * return dist + * + * def pairwise(self, X, Y=None): # <<<<<<<<<<<<<< + * """Compute the pairwise distances between X and Y + * + */ + values[1] = ((PyObject *)Py_None); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__Y); + if (value) { values[1] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "pairwise") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 353; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_X = values[0]; + __pyx_v_Y = values[1]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("pairwise", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 353; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.pairwise", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_16pairwise(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self), __pyx_v_X, __pyx_v_Y); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_16pairwise(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_Y) { + PyArrayObject *__pyx_v_Xarr = 0; + PyArrayObject *__pyx_v_Yarr = 0; + PyArrayObject *__pyx_v_Darr = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_Darr; + __Pyx_Buffer __pyx_pybuffer_Darr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_Xarr; + __Pyx_Buffer __pyx_pybuffer_Xarr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_Yarr; + __Pyx_Buffer __pyx_pybuffer_Yarr; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyArrayObject *__pyx_t_5 = NULL; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + int __pyx_t_10; + int __pyx_t_11; + PyArrayObject *__pyx_t_12 = NULL; + __Pyx_memviewslice __pyx_t_13 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_14 = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyArrayObject *__pyx_t_15 = NULL; + __Pyx_memviewslice __pyx_t_16 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pairwise", 0); + __pyx_pybuffer_Xarr.pybuffer.buf = NULL; + __pyx_pybuffer_Xarr.refcount = 0; + __pyx_pybuffernd_Xarr.data = NULL; + __pyx_pybuffernd_Xarr.rcbuffer = &__pyx_pybuffer_Xarr; + __pyx_pybuffer_Yarr.pybuffer.buf = NULL; + __pyx_pybuffer_Yarr.refcount = 0; + __pyx_pybuffernd_Yarr.data = NULL; + __pyx_pybuffernd_Yarr.rcbuffer = &__pyx_pybuffer_Yarr; + __pyx_pybuffer_Darr.pybuffer.buf = NULL; + __pyx_pybuffer_Darr.refcount = 0; + __pyx_pybuffernd_Darr.data = NULL; + __pyx_pybuffernd_Darr.rcbuffer = &__pyx_pybuffer_Darr; + + /* "sklearn/neighbors/dist_metrics.pyx":377 + * cdef np.ndarray[DTYPE_t, ndim=2, mode='c'] Darr + * + * Xarr = np.asarray(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * if Y is None: + * Darr = np.zeros((Xarr.shape[0], Xarr.shape[0]), + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Xarr.rcbuffer->pybuffer); + __pyx_t_6 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Xarr.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_6 < 0)) { + PyErr_Fetch(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Xarr.rcbuffer->pybuffer, (PyObject*)__pyx_v_Xarr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_7); Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_7, __pyx_t_8, __pyx_t_9); + } + } + __pyx_pybuffernd_Xarr.diminfo[0].strides = __pyx_pybuffernd_Xarr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_Xarr.diminfo[0].shape = __pyx_pybuffernd_Xarr.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_Xarr.diminfo[1].strides = __pyx_pybuffernd_Xarr.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_Xarr.diminfo[1].shape = __pyx_pybuffernd_Xarr.rcbuffer->pybuffer.shape[1]; + if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_5 = 0; + __pyx_v_Xarr = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":378 + * + * Xarr = np.asarray(X, dtype=DTYPE, order='C') + * if Y is None: # <<<<<<<<<<<<<< + * Darr = np.zeros((Xarr.shape[0], Xarr.shape[0]), + * dtype=DTYPE, order='C') + */ + __pyx_t_10 = (__pyx_v_Y == Py_None); + __pyx_t_11 = (__pyx_t_10 != 0); + if (__pyx_t_11) { + + /* "sklearn/neighbors/dist_metrics.pyx":379 + * Xarr = np.asarray(X, dtype=DTYPE, order='C') + * if Y is None: + * Darr = np.zeros((Xarr.shape[0], Xarr.shape[0]), # <<<<<<<<<<<<<< + * dtype=DTYPE, order='C') + * self.pdist(get_memview_DTYPE_2D(Xarr), + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_Xarr->dimensions[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_Xarr->dimensions[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_4 = 0; + __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_2)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + + /* "sklearn/neighbors/dist_metrics.pyx":380 + * if Y is None: + * Darr = np.zeros((Xarr.shape[0], Xarr.shape[0]), + * dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.pdist(get_memview_DTYPE_2D(Xarr), + * get_memview_DTYPE_2D(Darr)) + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Darr.rcbuffer->pybuffer); + __pyx_t_6 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Darr.rcbuffer->pybuffer, (PyObject*)__pyx_t_12, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_6 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_8, &__pyx_t_7); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Darr.rcbuffer->pybuffer, (PyObject*)__pyx_v_Darr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_7); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_8, __pyx_t_7); + } + } + __pyx_pybuffernd_Darr.diminfo[0].strides = __pyx_pybuffernd_Darr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_Darr.diminfo[0].shape = __pyx_pybuffernd_Darr.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_Darr.diminfo[1].strides = __pyx_pybuffernd_Darr.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_Darr.diminfo[1].shape = __pyx_pybuffernd_Darr.rcbuffer->pybuffer.shape[1]; + if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_12 = 0; + __pyx_v_Darr = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":381 + * Darr = np.zeros((Xarr.shape[0], Xarr.shape[0]), + * dtype=DTYPE, order='C') + * self.pdist(get_memview_DTYPE_2D(Xarr), # <<<<<<<<<<<<<< + * get_memview_DTYPE_2D(Darr)) + * else: + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_v_Xarr)); if (unlikely(!__pyx_t_13.memview)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":382 + * dtype=DTYPE, order='C') + * self.pdist(get_memview_DTYPE_2D(Xarr), + * get_memview_DTYPE_2D(Darr)) # <<<<<<<<<<<<<< + * else: + * Yarr = np.asarray(Y, dtype=DTYPE, order='C') + */ + __pyx_t_14 = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_v_Darr)); if (unlikely(!__pyx_t_14.memview)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->__pyx_vtab)->pdist(__pyx_v_self, __pyx_t_13, __pyx_t_14); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_XDEC_MEMVIEW(&__pyx_t_13, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_14, 1); + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/neighbors/dist_metrics.pyx":384 + * get_memview_DTYPE_2D(Darr)) + * else: + * Yarr = np.asarray(Y, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * Darr = np.zeros((Xarr.shape[0], Yarr.shape[0]), + * dtype=DTYPE, order='C') + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_Y); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_Y); + __Pyx_GIVEREF(__pyx_v_Y); + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_15 = ((PyArrayObject *)__pyx_t_3); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Yarr.rcbuffer->pybuffer); + __pyx_t_6 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Yarr.rcbuffer->pybuffer, (PyObject*)__pyx_t_15, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_6 < 0)) { + PyErr_Fetch(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Yarr.rcbuffer->pybuffer, (PyObject*)__pyx_v_Yarr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_7); Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_7, __pyx_t_8, __pyx_t_9); + } + } + __pyx_pybuffernd_Yarr.diminfo[0].strides = __pyx_pybuffernd_Yarr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_Yarr.diminfo[0].shape = __pyx_pybuffernd_Yarr.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_Yarr.diminfo[1].strides = __pyx_pybuffernd_Yarr.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_Yarr.diminfo[1].shape = __pyx_pybuffernd_Yarr.rcbuffer->pybuffer.shape[1]; + if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_15 = 0; + __pyx_v_Yarr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":385 + * else: + * Yarr = np.asarray(Y, dtype=DTYPE, order='C') + * Darr = np.zeros((Xarr.shape[0], Yarr.shape[0]), # <<<<<<<<<<<<<< + * dtype=DTYPE, order='C') + * self.cdist(get_memview_DTYPE_2D(Xarr), + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_Xarr->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_Yarr->dimensions[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_2)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + + /* "sklearn/neighbors/dist_metrics.pyx":386 + * Yarr = np.asarray(Y, dtype=DTYPE, order='C') + * Darr = np.zeros((Xarr.shape[0], Yarr.shape[0]), + * dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.cdist(get_memview_DTYPE_2D(Xarr), + * get_memview_DTYPE_2D(Yarr), + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = ((PyArrayObject *)__pyx_t_3); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Darr.rcbuffer->pybuffer); + __pyx_t_6 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Darr.rcbuffer->pybuffer, (PyObject*)__pyx_t_12, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_6 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_8, &__pyx_t_7); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Darr.rcbuffer->pybuffer, (PyObject*)__pyx_v_Darr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_7); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_8, __pyx_t_7); + } + } + __pyx_pybuffernd_Darr.diminfo[0].strides = __pyx_pybuffernd_Darr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_Darr.diminfo[0].shape = __pyx_pybuffernd_Darr.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_Darr.diminfo[1].strides = __pyx_pybuffernd_Darr.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_Darr.diminfo[1].shape = __pyx_pybuffernd_Darr.rcbuffer->pybuffer.shape[1]; + if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_12 = 0; + __pyx_v_Darr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":387 + * Darr = np.zeros((Xarr.shape[0], Yarr.shape[0]), + * dtype=DTYPE, order='C') + * self.cdist(get_memview_DTYPE_2D(Xarr), # <<<<<<<<<<<<<< + * get_memview_DTYPE_2D(Yarr), + * get_memview_DTYPE_2D(Darr)) + */ + __pyx_t_14 = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_v_Xarr)); if (unlikely(!__pyx_t_14.memview)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 387; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":388 + * dtype=DTYPE, order='C') + * self.cdist(get_memview_DTYPE_2D(Xarr), + * get_memview_DTYPE_2D(Yarr), # <<<<<<<<<<<<<< + * get_memview_DTYPE_2D(Darr)) + * return Darr + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_v_Yarr)); if (unlikely(!__pyx_t_13.memview)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 388; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":389 + * self.cdist(get_memview_DTYPE_2D(Xarr), + * get_memview_DTYPE_2D(Yarr), + * get_memview_DTYPE_2D(Darr)) # <<<<<<<<<<<<<< + * return Darr + * + */ + __pyx_t_16 = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_v_Darr)); if (unlikely(!__pyx_t_16.memview)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 389; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->__pyx_vtab)->cdist(__pyx_v_self, __pyx_t_14, __pyx_t_13, __pyx_t_16); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 387; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_XDEC_MEMVIEW(&__pyx_t_14, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_13, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_16, 1); + } + __pyx_L3:; + + /* "sklearn/neighbors/dist_metrics.pyx":390 + * get_memview_DTYPE_2D(Yarr), + * get_memview_DTYPE_2D(Darr)) + * return Darr # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_Darr)); + __pyx_r = ((PyObject *)__pyx_v_Darr); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_13, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_14, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_16, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Darr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Xarr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Yarr.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.DistanceMetric.pairwise", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Darr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Xarr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Yarr.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_Xarr); + __Pyx_XDECREF((PyObject *)__pyx_v_Yarr); + __Pyx_XDECREF((PyObject *)__pyx_v_Darr); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} + if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__init__", 0))) return -1; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance___init__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":402 + * D(x, y) = \sqrt{ \sum_i (x_i - y_i) ^ 2 } + * """ + * def __init__(self): # <<<<<<<<<<<<<< + * self.p = 2 + * + */ + +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":403 + * """ + * def __init__(self): + * self.p = 2 # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_v_self->__pyx_base.p = 2.0; + + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":405 + * self.p = 2 + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * return euclidean_dist(x1, x2, size) + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":407 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * return euclidean_dist(x1, x2, size) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_t_1 = __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist(__pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_1 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.EuclideanDistance.dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":409 + * return euclidean_dist(x1, x2, size) + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * return euclidean_rdist(x1, x2, size) + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":411 + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * return euclidean_rdist(x1, x2, size) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + */ + __pyx_t_1 = __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist(__pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_1 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.EuclideanDistance.rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":413 + * return euclidean_rdist(x1, x2, size) + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: # <<<<<<<<<<<<<< + * return sqrt(rdist) + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance__rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rdist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":414 + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + * return sqrt(rdist) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + */ + __pyx_r = sqrt(__pyx_v_rdist); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":416 + * return sqrt(rdist) + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return dist * dist + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance__dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":417 + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + * return dist * dist # <<<<<<<<<<<<<< + * + * def rdist_to_dist(self, rdist): + */ + __pyx_r = (__pyx_v_dist * __pyx_v_dist); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_3rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_3rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("rdist_to_dist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_2rdist_to_dist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *)__pyx_v_self), ((PyObject *)__pyx_v_rdist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":419 + * return dist * dist + * + * def rdist_to_dist(self, rdist): # <<<<<<<<<<<<<< + * return np.sqrt(rdist) + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_2rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":420 + * + * def rdist_to_dist(self, rdist): + * return np.sqrt(rdist) # <<<<<<<<<<<<<< + * + * def dist_to_rdist(self, dist): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__sqrt); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_rdist); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_rdist); + __Pyx_GIVEREF(__pyx_v_rdist); + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.EuclideanDistance.rdist_to_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_5dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_5dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dist_to_rdist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_4dist_to_rdist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *)__pyx_v_self), ((PyObject *)__pyx_v_dist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":422 + * return np.sqrt(rdist) + * + * def dist_to_rdist(self, dist): # <<<<<<<<<<<<<< + * return dist ** 2 + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_4dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":423 + * + * def dist_to_rdist(self, dist): + * return dist ** 2 # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyNumber_Power(__pyx_v_dist, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.EuclideanDistance.dist_to_rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_V = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__V,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__V)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 435; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_V = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 435; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.SEuclideanDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance___init__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *)__pyx_v_self), __pyx_v_V); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":435 + * D(x, y) = \sqrt{ \sum_i \frac{ (x_i - y_i) ^ 2}{V_i} } + * """ + * def __init__(self, V): # <<<<<<<<<<<<<< + * self.vec = np.asarray(V, dtype=DTYPE) + * self.vec_ptr = get_vec_ptr(self.vec) + */ + +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *__pyx_v_self, PyObject *__pyx_v_V) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":436 + * """ + * def __init__(self, V): + * self.vec = np.asarray(V, dtype=DTYPE) # <<<<<<<<<<<<<< + * self.vec_ptr = get_vec_ptr(self.vec) + * self.size = self.vec.shape[0] + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_V); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_V); + __Pyx_GIVEREF(__pyx_v_V); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.vec); + __Pyx_DECREF(((PyObject *)__pyx_v_self->__pyx_base.vec)); + __pyx_v_self->__pyx_base.vec = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":437 + * def __init__(self, V): + * self.vec = np.asarray(V, dtype=DTYPE) + * self.vec_ptr = get_vec_ptr(self.vec) # <<<<<<<<<<<<<< + * self.size = self.vec.shape[0] + * self.p = 2 + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->__pyx_base.vec); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_self->__pyx_base.vec_ptr = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_vec_ptr(((PyArrayObject *)__pyx_t_4)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":438 + * self.vec = np.asarray(V, dtype=DTYPE) + * self.vec_ptr = get_vec_ptr(self.vec) + * self.size = self.vec.shape[0] # <<<<<<<<<<<<<< + * self.p = 2 + * + */ + __pyx_v_self->__pyx_base.size = (__pyx_v_self->__pyx_base.vec->dimensions[0]); + + /* "sklearn/neighbors/dist_metrics.pyx":439 + * self.vec_ptr = get_vec_ptr(self.vec) + * self.size = self.vec.shape[0] + * self.p = 2 # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_v_self->__pyx_base.p = 2.0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.SEuclideanDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":441 + * self.p = 2 + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * if size != self.size: + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_rdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_tmp; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + __pyx_t_5numpy_intp_t __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":443 + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * if size != self.size: # <<<<<<<<<<<<<< + * raise ValueError('SEuclidean dist: size of V does not match') + * cdef DTYPE_t tmp, d=0 + */ + __pyx_t_1 = ((__pyx_v_size != __pyx_v_self->__pyx_base.size) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/dist_metrics.pyx":444 + * ITYPE_t size) except -1: + * if size != self.size: + * raise ValueError('SEuclidean dist: size of V does not match') # <<<<<<<<<<<<<< + * cdef DTYPE_t tmp, d=0 + * cdef np.intp_t j + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/neighbors/dist_metrics.pyx":445 + * if size != self.size: + * raise ValueError('SEuclidean dist: size of V does not match') + * cdef DTYPE_t tmp, d=0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "sklearn/neighbors/dist_metrics.pyx":447 + * cdef DTYPE_t tmp, d=0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tmp = x1[j] - x2[j] + * d += tmp * tmp / self.vec_ptr[j] + */ + __pyx_t_3 = __pyx_v_size; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_j = __pyx_t_4; + + /* "sklearn/neighbors/dist_metrics.pyx":448 + * cdef np.intp_t j + * for j in range(size): + * tmp = x1[j] - x2[j] # <<<<<<<<<<<<<< + * d += tmp * tmp / self.vec_ptr[j] + * return d + */ + __pyx_v_tmp = ((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j])); + + /* "sklearn/neighbors/dist_metrics.pyx":449 + * for j in range(size): + * tmp = x1[j] - x2[j] + * d += tmp * tmp / self.vec_ptr[j] # <<<<<<<<<<<<<< + * return d + * + */ + __pyx_v_d = (__pyx_v_d + ((__pyx_v_tmp * __pyx_v_tmp) / (__pyx_v_self->__pyx_base.vec_ptr[__pyx_v_j]))); + } + + /* "sklearn/neighbors/dist_metrics.pyx":450 + * tmp = x1[j] - x2[j] + * d += tmp * tmp / self.vec_ptr[j] + * return d # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_r = __pyx_v_d; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.SEuclideanDistance.rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":452 + * return d + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * return sqrt(self.rdist(x1, x2, size)) + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_dist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":454 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * return sqrt(self.rdist(x1, x2, size)) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + */ + __pyx_t_1 = __pyx_f_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_rdist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self), __pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_1 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = sqrt(__pyx_t_1); + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.SEuclideanDistance.dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":456 + * return sqrt(self.rdist(x1, x2, size)) + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: # <<<<<<<<<<<<<< + * return sqrt(rdist) + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance__rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rdist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":457 + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + * return sqrt(rdist) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + */ + __pyx_r = sqrt(__pyx_v_rdist); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":459 + * return sqrt(rdist) + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return dist * dist + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance__dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":460 + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + * return dist * dist # <<<<<<<<<<<<<< + * + * def rdist_to_dist(self, rdist): + */ + __pyx_r = (__pyx_v_dist * __pyx_v_dist); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_3rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_3rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("rdist_to_dist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_2rdist_to_dist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *)__pyx_v_self), ((PyObject *)__pyx_v_rdist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":462 + * return dist * dist + * + * def rdist_to_dist(self, rdist): # <<<<<<<<<<<<<< + * return np.sqrt(rdist) + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_2rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":463 + * + * def rdist_to_dist(self, rdist): + * return np.sqrt(rdist) # <<<<<<<<<<<<<< + * + * def dist_to_rdist(self, dist): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__sqrt); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_rdist); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_rdist); + __Pyx_GIVEREF(__pyx_v_rdist); + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.SEuclideanDistance.rdist_to_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_5dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_5dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dist_to_rdist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_4dist_to_rdist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *)__pyx_v_self), ((PyObject *)__pyx_v_dist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":465 + * return np.sqrt(rdist) + * + * def dist_to_rdist(self, dist): # <<<<<<<<<<<<<< + * return dist ** 2 + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_4dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":466 + * + * def dist_to_rdist(self, dist): + * return dist ** 2 # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyNumber_Power(__pyx_v_dist, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 466; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.SEuclideanDistance.dist_to_rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_17ManhattanDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_17ManhattanDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} + if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__init__", 0))) return -1; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_17ManhattanDistance___init__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ManhattanDistance *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":478 + * D(x, y) = \sum_i |x_i - y_i| + * """ + * def __init__(self): # <<<<<<<<<<<<<< + * self.p = 1 + * + */ + +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_17ManhattanDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ManhattanDistance *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":479 + * """ + * def __init__(self): + * self.p = 1 # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_v_self->__pyx_base.p = 1.0; + + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":481 + * self.p = 1 + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t d = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17ManhattanDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ManhattanDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":483 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef DTYPE_t d = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "sklearn/neighbors/dist_metrics.pyx":485 + * cdef DTYPE_t d = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * d += fabs(x1[j] - x2[j]) + * return d + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":486 + * cdef np.intp_t j + * for j in range(size): + * d += fabs(x1[j] - x2[j]) # <<<<<<<<<<<<<< + * return d + * + */ + __pyx_v_d = (__pyx_v_d + fabs(((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j])))); + } + + /* "sklearn/neighbors/dist_metrics.pyx":487 + * for j in range(size): + * d += fabs(x1[j] - x2[j]) + * return d # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_d; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_17ChebyshevDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_17ChebyshevDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} + if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__init__", 0))) return -1; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_17ChebyshevDistance___init__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":499 + * D(x, y) = max_i (|x_i - y_i|) + * """ + * def __init__(self): # <<<<<<<<<<<<<< + * self.p = INF + * + */ + +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_17ChebyshevDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":500 + * """ + * def __init__(self): + * self.p = INF # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_v_self->__pyx_base.p = __pyx_v_7sklearn_9neighbors_12dist_metrics_INF; + + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":502 + * self.p = INF + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t d = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17ChebyshevDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":504 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef DTYPE_t d = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "sklearn/neighbors/dist_metrics.pyx":506 + * cdef DTYPE_t d = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * d = fmax(d, fabs(x1[j] - x2[j])) + * return d + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":507 + * cdef np.intp_t j + * for j in range(size): + * d = fmax(d, fabs(x1[j] - x2[j])) # <<<<<<<<<<<<<< + * return d + * + */ + __pyx_v_d = __pyx_f_7sklearn_9neighbors_12dist_metrics_fmax(__pyx_v_d, fabs(((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j])))); + } + + /* "sklearn/neighbors/dist_metrics.pyx":508 + * for j in range(size): + * d = fmax(d, fabs(x1[j] - x2[j])) + * return d # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_d; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_p = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_p = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.MinkowskiDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance___init__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *)__pyx_v_self), __pyx_v_p); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":525 + * p=2, EuclideanDistance is more efficient. + * """ + * def __init__(self, p): # <<<<<<<<<<<<<< + * if p < 1: + * raise ValueError("p must be greater than 1") + */ + +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_p) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":526 + * """ + * def __init__(self, p): + * if p < 1: # <<<<<<<<<<<<<< + * raise ValueError("p must be greater than 1") + * elif np.isinf(p): + */ + __pyx_t_1 = PyObject_RichCompare(__pyx_v_p, __pyx_int_1, Py_LT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_2) { + + /* "sklearn/neighbors/dist_metrics.pyx":527 + * def __init__(self, p): + * if p < 1: + * raise ValueError("p must be greater than 1") # <<<<<<<<<<<<<< + * elif np.isinf(p): + * raise ValueError("MinkowskiDistance requires finite p. " + */ + __pyx_t_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_13), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + + /* "sklearn/neighbors/dist_metrics.pyx":528 + * if p < 1: + * raise ValueError("p must be greater than 1") + * elif np.isinf(p): # <<<<<<<<<<<<<< + * raise ValueError("MinkowskiDistance requires finite p. " + * "For p=inf, use ChebyshevDistance.") + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__isinf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_p); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_p); + __Pyx_GIVEREF(__pyx_v_p); + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_2) { + + /* "sklearn/neighbors/dist_metrics.pyx":529 + * raise ValueError("p must be greater than 1") + * elif np.isinf(p): + * raise ValueError("MinkowskiDistance requires finite p. " # <<<<<<<<<<<<<< + * "For p=inf, use ChebyshevDistance.") + * self.p = p + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/neighbors/dist_metrics.pyx":531 + * raise ValueError("MinkowskiDistance requires finite p. " + * "For p=inf, use ChebyshevDistance.") + * self.p = p # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_v_p); if (unlikely((__pyx_t_5 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->__pyx_base.p = __pyx_t_5; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.MinkowskiDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":533 + * self.p = p + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t d=0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_rdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":535 + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef DTYPE_t d=0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "sklearn/neighbors/dist_metrics.pyx":537 + * cdef DTYPE_t d=0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * d += pow(fabs(x1[j] - x2[j]), self.p) + * return d + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":538 + * cdef np.intp_t j + * for j in range(size): + * d += pow(fabs(x1[j] - x2[j]), self.p) # <<<<<<<<<<<<<< + * return d + * + */ + __pyx_v_d = (__pyx_v_d + pow(fabs(((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j]))), __pyx_v_self->__pyx_base.p)); + } + + /* "sklearn/neighbors/dist_metrics.pyx":539 + * for j in range(size): + * d += pow(fabs(x1[j] - x2[j]), self.p) + * return d # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_r = __pyx_v_d; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":541 + * return d + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * return pow(self.rdist(x1, x2, size), 1. / self.p) + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_dist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":543 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * return pow(self.rdist(x1, x2, size), 1. / self.p) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + */ + __pyx_t_1 = __pyx_f_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_rdist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self), __pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_1 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = pow(__pyx_t_1, (1. / __pyx_v_self->__pyx_base.p)); + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.MinkowskiDistance.dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":545 + * return pow(self.rdist(x1, x2, size), 1. / self.p) + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: # <<<<<<<<<<<<<< + * return pow(rdist, 1. / self.p) + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance__rdist_to_dist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rdist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":546 + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + * return pow(rdist, 1. / self.p) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + */ + __pyx_r = pow(__pyx_v_rdist, (1. / __pyx_v_self->__pyx_base.p)); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":548 + * return pow(rdist, 1. / self.p) + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return pow(dist, self.p) + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance__dist_to_rdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":549 + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + * return pow(dist, self.p) # <<<<<<<<<<<<<< + * + * def rdist_to_dist(self, rdist): + */ + __pyx_r = pow(__pyx_v_dist, __pyx_v_self->__pyx_base.p); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_3rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_3rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("rdist_to_dist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_2rdist_to_dist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *)__pyx_v_self), ((PyObject *)__pyx_v_rdist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":551 + * return pow(dist, self.p) + * + * def rdist_to_dist(self, rdist): # <<<<<<<<<<<<<< + * return rdist ** (1. / self.p) + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_2rdist_to_dist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":552 + * + * def rdist_to_dist(self, rdist): + * return rdist ** (1. / self.p) # <<<<<<<<<<<<<< + * + * def dist_to_rdist(self, dist): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyFloat_FromDouble((1. / __pyx_v_self->__pyx_base.p)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 552; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyNumber_Power(__pyx_v_rdist, __pyx_t_1, Py_None); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 552; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.MinkowskiDistance.rdist_to_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_5dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_5dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dist_to_rdist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_4dist_to_rdist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *)__pyx_v_self), ((PyObject *)__pyx_v_dist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":554 + * return rdist ** (1. / self.p) + * + * def dist_to_rdist(self, dist): # <<<<<<<<<<<<<< + * return dist ** self.p + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_4dist_to_rdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":555 + * + * def dist_to_rdist(self, dist): + * return dist ** self.p # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->__pyx_base.p); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 555; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyNumber_Power(__pyx_v_dist, __pyx_t_1, Py_None); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 555; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.MinkowskiDistance.dist_to_rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_p = 0; + PyObject *__pyx_v_w = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__w,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__w)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, 1); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 577; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 577; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_p = values[0]; + __pyx_v_w = values[1]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 577; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.WMinkowskiDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance___init__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *)__pyx_v_self), __pyx_v_p, __pyx_v_w); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":577 + * + * """ + * def __init__(self, p, w): # <<<<<<<<<<<<<< + * if p < 1: + * raise ValueError("p must be greater than 1") + */ + +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_p, PyObject *__pyx_v_w) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":578 + * """ + * def __init__(self, p, w): + * if p < 1: # <<<<<<<<<<<<<< + * raise ValueError("p must be greater than 1") + * elif np.isinf(p): + */ + __pyx_t_1 = PyObject_RichCompare(__pyx_v_p, __pyx_int_1, Py_LT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 578; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 578; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_2) { + + /* "sklearn/neighbors/dist_metrics.pyx":579 + * def __init__(self, p, w): + * if p < 1: + * raise ValueError("p must be greater than 1") # <<<<<<<<<<<<<< + * elif np.isinf(p): + * raise ValueError("WMinkowskiDistance requires finite p. " + */ + __pyx_t_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + + /* "sklearn/neighbors/dist_metrics.pyx":580 + * if p < 1: + * raise ValueError("p must be greater than 1") + * elif np.isinf(p): # <<<<<<<<<<<<<< + * raise ValueError("WMinkowskiDistance requires finite p. " + * "For p=inf, use ChebyshevDistance.") + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__isinf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_p); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_p); + __Pyx_GIVEREF(__pyx_v_p); + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_2) { + + /* "sklearn/neighbors/dist_metrics.pyx":581 + * raise ValueError("p must be greater than 1") + * elif np.isinf(p): + * raise ValueError("WMinkowskiDistance requires finite p. " # <<<<<<<<<<<<<< + * "For p=inf, use ChebyshevDistance.") + * self.p = p + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_18), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 581; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 581; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/neighbors/dist_metrics.pyx":583 + * raise ValueError("WMinkowskiDistance requires finite p. " + * "For p=inf, use ChebyshevDistance.") + * self.p = p # <<<<<<<<<<<<<< + * self.vec = np.asarray(w, dtype=DTYPE) + * self.vec_ptr = get_vec_ptr(self.vec) + */ + __pyx_t_5 = __pyx_PyFloat_AsDouble(__pyx_v_p); if (unlikely((__pyx_t_5 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->__pyx_base.p = __pyx_t_5; + + /* "sklearn/neighbors/dist_metrics.pyx":584 + * "For p=inf, use ChebyshevDistance.") + * self.p = p + * self.vec = np.asarray(w, dtype=DTYPE) # <<<<<<<<<<<<<< + * self.vec_ptr = get_vec_ptr(self.vec) + * self.size = self.vec.shape[0] + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_w); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_w); + __Pyx_GIVEREF(__pyx_v_w); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s__DTYPE); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.vec); + __Pyx_DECREF(((PyObject *)__pyx_v_self->__pyx_base.vec)); + __pyx_v_self->__pyx_base.vec = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":585 + * self.p = p + * self.vec = np.asarray(w, dtype=DTYPE) + * self.vec_ptr = get_vec_ptr(self.vec) # <<<<<<<<<<<<<< + * self.size = self.vec.shape[0] + * + */ + __pyx_t_6 = ((PyObject *)__pyx_v_self->__pyx_base.vec); + __Pyx_INCREF(__pyx_t_6); + __pyx_v_self->__pyx_base.vec_ptr = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_vec_ptr(((PyArrayObject *)__pyx_t_6)); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":586 + * self.vec = np.asarray(w, dtype=DTYPE) + * self.vec_ptr = get_vec_ptr(self.vec) + * self.size = self.vec.shape[0] # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_v_self->__pyx_base.size = (__pyx_v_self->__pyx_base.vec->dimensions[0]); + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.WMinkowskiDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":588 + * self.size = self.vec.shape[0] + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * if size != self.size: + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_rdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + __pyx_t_5numpy_intp_t __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":590 + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * if size != self.size: # <<<<<<<<<<<<<< + * raise ValueError('WMinkowskiDistance dist: ' + * 'size of w does not match') + */ + __pyx_t_1 = ((__pyx_v_size != __pyx_v_self->__pyx_base.size) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/dist_metrics.pyx":591 + * ITYPE_t size) except -1: + * if size != self.size: + * raise ValueError('WMinkowskiDistance dist: ' # <<<<<<<<<<<<<< + * 'size of w does not match') + * cdef DTYPE_t d=0 + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_20), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/neighbors/dist_metrics.pyx":593 + * raise ValueError('WMinkowskiDistance dist: ' + * 'size of w does not match') + * cdef DTYPE_t d=0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "sklearn/neighbors/dist_metrics.pyx":595 + * cdef DTYPE_t d=0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * d += pow(self.vec_ptr[j] * fabs(x1[j] - x2[j]), self.p) + * return d + */ + __pyx_t_3 = __pyx_v_size; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_j = __pyx_t_4; + + /* "sklearn/neighbors/dist_metrics.pyx":596 + * cdef np.intp_t j + * for j in range(size): + * d += pow(self.vec_ptr[j] * fabs(x1[j] - x2[j]), self.p) # <<<<<<<<<<<<<< + * return d + * + */ + __pyx_v_d = (__pyx_v_d + pow(((__pyx_v_self->__pyx_base.vec_ptr[__pyx_v_j]) * fabs(((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j])))), __pyx_v_self->__pyx_base.p)); + } + + /* "sklearn/neighbors/dist_metrics.pyx":597 + * for j in range(size): + * d += pow(self.vec_ptr[j] * fabs(x1[j] - x2[j]), self.p) + * return d # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_r = __pyx_v_d; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.WMinkowskiDistance.rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":599 + * return d + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * return pow(self.rdist(x1, x2, size), 1. / self.p) + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_dist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":601 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * return pow(self.rdist(x1, x2, size), 1. / self.p) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + */ + __pyx_t_1 = __pyx_f_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_rdist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self), __pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_1 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 601; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = pow(__pyx_t_1, (1. / __pyx_v_self->__pyx_base.p)); + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.WMinkowskiDistance.dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":603 + * return pow(self.rdist(x1, x2, size), 1. / self.p) + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: # <<<<<<<<<<<<<< + * return pow(rdist, 1. / self.p) + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance__rdist_to_dist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rdist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":604 + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + * return pow(rdist, 1. / self.p) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + */ + __pyx_r = pow(__pyx_v_rdist, (1. / __pyx_v_self->__pyx_base.p)); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":606 + * return pow(rdist, 1. / self.p) + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return pow(dist, self.p) + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance__dist_to_rdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":607 + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + * return pow(dist, self.p) # <<<<<<<<<<<<<< + * + * def rdist_to_dist(self, rdist): + */ + __pyx_r = pow(__pyx_v_dist, __pyx_v_self->__pyx_base.p); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_3rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_3rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("rdist_to_dist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_2rdist_to_dist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *)__pyx_v_self), ((PyObject *)__pyx_v_rdist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":609 + * return pow(dist, self.p) + * + * def rdist_to_dist(self, rdist): # <<<<<<<<<<<<<< + * return rdist ** (1. / self.p) + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_2rdist_to_dist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":610 + * + * def rdist_to_dist(self, rdist): + * return rdist ** (1. / self.p) # <<<<<<<<<<<<<< + * + * def dist_to_rdist(self, dist): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyFloat_FromDouble((1. / __pyx_v_self->__pyx_base.p)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 610; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyNumber_Power(__pyx_v_rdist, __pyx_t_1, Py_None); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 610; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.WMinkowskiDistance.rdist_to_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_5dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_5dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dist_to_rdist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_4dist_to_rdist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *)__pyx_v_self), ((PyObject *)__pyx_v_dist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":612 + * return rdist ** (1. / self.p) + * + * def dist_to_rdist(self, dist): # <<<<<<<<<<<<<< + * return dist ** self.p + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_4dist_to_rdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":613 + * + * def dist_to_rdist(self, dist): + * return dist ** self.p # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->__pyx_base.p); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 613; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyNumber_Power(__pyx_v_dist, __pyx_t_1, Py_None); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 613; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.WMinkowskiDistance.dist_to_rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_V = 0; + PyObject *__pyx_v_VI = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__V,&__pyx_n_s__VI,0}; + PyObject* values[2] = {0,0}; + + /* "sklearn/neighbors/dist_metrics.pyx":634 + * then V is not referenced. + * """ + * def __init__(self, V=None, VI=None): # <<<<<<<<<<<<<< + * if VI is None: + * VI = np.linalg.inv(V) + */ + values[0] = ((PyObject *)Py_None); + values[1] = ((PyObject *)Py_None); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__V); + if (value) { values[0] = value; kw_args--; } + } + case 1: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__VI); + if (value) { values[1] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_V = values[0]; + __pyx_v_VI = values[1]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 0, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.MahalanobisDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance___init__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *)__pyx_v_self), __pyx_v_V, __pyx_v_VI); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *__pyx_v_self, PyObject *__pyx_v_V, PyObject *__pyx_v_VI) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_INCREF(__pyx_v_VI); + + /* "sklearn/neighbors/dist_metrics.pyx":635 + * """ + * def __init__(self, V=None, VI=None): + * if VI is None: # <<<<<<<<<<<<<< + * VI = np.linalg.inv(V) + * if VI.ndim != 2 or VI.shape[0] != VI.shape[1]: + */ + __pyx_t_1 = (__pyx_v_VI == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "sklearn/neighbors/dist_metrics.pyx":636 + * def __init__(self, V=None, VI=None): + * if VI is None: + * VI = np.linalg.inv(V) # <<<<<<<<<<<<<< + * if VI.ndim != 2 or VI.shape[0] != VI.shape[1]: + * raise ValueError("V/VI must be square") + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 636; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__linalg); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 636; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__inv); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 636; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 636; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_V); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_V); + __Pyx_GIVEREF(__pyx_v_V); + __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 636; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_v_VI); + __pyx_v_VI = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/neighbors/dist_metrics.pyx":637 + * if VI is None: + * VI = np.linalg.inv(V) + * if VI.ndim != 2 or VI.shape[0] != VI.shape[1]: # <<<<<<<<<<<<<< + * raise ValueError("V/VI must be square") + * + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_VI, __pyx_n_s__ndim); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_5, __pyx_int_2, Py_NE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_2) { + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_VI, __pyx_n_s__shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_4, 0, sizeof(long), PyInt_FromLong, 0, 0, 0); if (!__pyx_t_5) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_VI, __pyx_n_s__shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_4, 1, sizeof(long), PyInt_FromLong, 0, 0, 0); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_RichCompare(__pyx_t_5, __pyx_t_3, Py_NE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __pyx_t_1; + } else { + __pyx_t_6 = __pyx_t_2; + } + if (__pyx_t_6) { + + /* "sklearn/neighbors/dist_metrics.pyx":638 + * VI = np.linalg.inv(V) + * if VI.ndim != 2 or VI.shape[0] != VI.shape[1]: + * raise ValueError("V/VI must be square") # <<<<<<<<<<<<<< + * + * self.mat = np.asarray(VI, dtype=float, order='C') + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_22), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "sklearn/neighbors/dist_metrics.pyx":640 + * raise ValueError("V/VI must be square") + * + * self.mat = np.asarray(VI, dtype=float, order='C') # <<<<<<<<<<<<<< + * self.mat_ptr = get_mat_ptr(self.mat) + * + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__asarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_VI); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_VI); + __Pyx_GIVEREF(__pyx_v_VI); + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), ((PyObject *)((PyObject*)(&PyFloat_Type)))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.mat); + __Pyx_DECREF(((PyObject *)__pyx_v_self->__pyx_base.mat)); + __pyx_v_self->__pyx_base.mat = ((PyArrayObject *)__pyx_t_7); + __pyx_t_7 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":641 + * + * self.mat = np.asarray(VI, dtype=float, order='C') + * self.mat_ptr = get_mat_ptr(self.mat) # <<<<<<<<<<<<<< + * + * self.size = self.mat.shape[0] + */ + __pyx_t_7 = ((PyObject *)__pyx_v_self->__pyx_base.mat); + __Pyx_INCREF(__pyx_t_7); + __pyx_v_self->__pyx_base.mat_ptr = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_mat_ptr(((PyArrayObject *)__pyx_t_7)); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":643 + * self.mat_ptr = get_mat_ptr(self.mat) + * + * self.size = self.mat.shape[0] # <<<<<<<<<<<<<< + * + * # we need vec as a work buffer + */ + __pyx_v_self->__pyx_base.size = (__pyx_v_self->__pyx_base.mat->dimensions[0]); + + /* "sklearn/neighbors/dist_metrics.pyx":646 + * + * # we need vec as a work buffer + * self.vec = np.zeros(self.size, dtype=DTYPE) # <<<<<<<<<<<<<< + * self.vec_ptr = get_vec_ptr(self.vec) + * + */ + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s__zeros); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_self->__pyx_base.size); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_7)); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.vec); + __Pyx_DECREF(((PyObject *)__pyx_v_self->__pyx_base.vec)); + __pyx_v_self->__pyx_base.vec = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":647 + * # we need vec as a work buffer + * self.vec = np.zeros(self.size, dtype=DTYPE) + * self.vec_ptr = get_vec_ptr(self.vec) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_t_3 = ((PyObject *)__pyx_v_self->__pyx_base.vec); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_self->__pyx_base.vec_ptr = __pyx_f_7sklearn_9neighbors_12dist_metrics_get_vec_ptr(((PyArrayObject *)__pyx_t_3)); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.MahalanobisDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_VI); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":649 + * self.vec_ptr = get_vec_ptr(self.vec) + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * if size != self.size: + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_rdist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_tmp; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_i; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + __pyx_t_5numpy_intp_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + __pyx_t_5numpy_intp_t __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":651 + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * if size != self.size: # <<<<<<<<<<<<<< + * raise ValueError('Mahalanobis dist: size of V does not match') + * + */ + __pyx_t_1 = ((__pyx_v_size != __pyx_v_self->__pyx_base.size) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/dist_metrics.pyx":652 + * ITYPE_t size) except -1: + * if size != self.size: + * raise ValueError('Mahalanobis dist: size of V does not match') # <<<<<<<<<<<<<< + * + * cdef DTYPE_t tmp, d = 0 + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_24), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/neighbors/dist_metrics.pyx":654 + * raise ValueError('Mahalanobis dist: size of V does not match') + * + * cdef DTYPE_t tmp, d = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t i, j + * + */ + __pyx_v_d = 0.0; + + /* "sklearn/neighbors/dist_metrics.pyx":658 + * + * # compute (x1 - x2).T * VI * (x1 - x2) + * for i in range(size): # <<<<<<<<<<<<<< + * self.vec_ptr[i] = x1[i] - x2[i] + * + */ + __pyx_t_3 = __pyx_v_size; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + + /* "sklearn/neighbors/dist_metrics.pyx":659 + * # compute (x1 - x2).T * VI * (x1 - x2) + * for i in range(size): + * self.vec_ptr[i] = x1[i] - x2[i] # <<<<<<<<<<<<<< + * + * for i in range(size): + */ + (__pyx_v_self->__pyx_base.vec_ptr[__pyx_v_i]) = ((__pyx_v_x1[__pyx_v_i]) - (__pyx_v_x2[__pyx_v_i])); + } + + /* "sklearn/neighbors/dist_metrics.pyx":661 + * self.vec_ptr[i] = x1[i] - x2[i] + * + * for i in range(size): # <<<<<<<<<<<<<< + * tmp = 0 + * for j in range(size): + */ + __pyx_t_3 = __pyx_v_size; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + + /* "sklearn/neighbors/dist_metrics.pyx":662 + * + * for i in range(size): + * tmp = 0 # <<<<<<<<<<<<<< + * for j in range(size): + * tmp += self.mat_ptr[i * size + j] * self.vec_ptr[j] + */ + __pyx_v_tmp = 0.0; + + /* "sklearn/neighbors/dist_metrics.pyx":663 + * for i in range(size): + * tmp = 0 + * for j in range(size): # <<<<<<<<<<<<<< + * tmp += self.mat_ptr[i * size + j] * self.vec_ptr[j] + * d += tmp * self.vec_ptr[i] + */ + __pyx_t_5 = __pyx_v_size; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_j = __pyx_t_6; + + /* "sklearn/neighbors/dist_metrics.pyx":664 + * tmp = 0 + * for j in range(size): + * tmp += self.mat_ptr[i * size + j] * self.vec_ptr[j] # <<<<<<<<<<<<<< + * d += tmp * self.vec_ptr[i] + * return d + */ + __pyx_v_tmp = (__pyx_v_tmp + ((__pyx_v_self->__pyx_base.mat_ptr[((__pyx_v_i * __pyx_v_size) + __pyx_v_j)]) * (__pyx_v_self->__pyx_base.vec_ptr[__pyx_v_j]))); + } + + /* "sklearn/neighbors/dist_metrics.pyx":665 + * for j in range(size): + * tmp += self.mat_ptr[i * size + j] * self.vec_ptr[j] + * d += tmp * self.vec_ptr[i] # <<<<<<<<<<<<<< + * return d + * + */ + __pyx_v_d = (__pyx_v_d + (__pyx_v_tmp * (__pyx_v_self->__pyx_base.vec_ptr[__pyx_v_i]))); + } + + /* "sklearn/neighbors/dist_metrics.pyx":666 + * tmp += self.mat_ptr[i * size + j] * self.vec_ptr[j] + * d += tmp * self.vec_ptr[i] + * return d # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_r = __pyx_v_d; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.MahalanobisDistance.rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":668 + * return d + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * return sqrt(self.rdist(x1, x2, size)) + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_dist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":670 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * return sqrt(self.rdist(x1, x2, size)) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + */ + __pyx_t_1 = __pyx_f_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_rdist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self), __pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_1 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 670; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = sqrt(__pyx_t_1); + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.MahalanobisDistance.dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":672 + * return sqrt(self.rdist(x1, x2, size)) + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: # <<<<<<<<<<<<<< + * return sqrt(rdist) + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance__rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rdist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":673 + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + * return sqrt(rdist) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + */ + __pyx_r = sqrt(__pyx_v_rdist); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":675 + * return sqrt(rdist) + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return dist * dist + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance__dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":676 + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + * return dist * dist # <<<<<<<<<<<<<< + * + * def rdist_to_dist(self, rdist): + */ + __pyx_r = (__pyx_v_dist * __pyx_v_dist); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_3rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_3rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("rdist_to_dist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_2rdist_to_dist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *)__pyx_v_self), ((PyObject *)__pyx_v_rdist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":678 + * return dist * dist + * + * def rdist_to_dist(self, rdist): # <<<<<<<<<<<<<< + * return np.sqrt(rdist) + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_2rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":679 + * + * def rdist_to_dist(self, rdist): + * return np.sqrt(rdist) # <<<<<<<<<<<<<< + * + * def dist_to_rdist(self, dist): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__sqrt); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_rdist); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_rdist); + __Pyx_GIVEREF(__pyx_v_rdist); + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.MahalanobisDistance.rdist_to_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_5dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_5dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dist_to_rdist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_4dist_to_rdist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *)__pyx_v_self), ((PyObject *)__pyx_v_dist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":681 + * return np.sqrt(rdist) + * + * def dist_to_rdist(self, dist): # <<<<<<<<<<<<<< + * return dist ** 2 + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_4dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":682 + * + * def dist_to_rdist(self, dist): + * return dist ** 2 # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyNumber_Power(__pyx_v_dist, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 682; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.MahalanobisDistance.dist_to_rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":697 + * D(x, y) = \frac{1}{N} \sum_i \delta_{x_i, y_i} + * """ + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef int n_unequal = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_15HammingDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HammingDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + int __pyx_v_n_unequal; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":699 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef int n_unequal = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_n_unequal = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":701 + * cdef int n_unequal = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * if x1[j] != x2[j]: + * n_unequal += 1 + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":702 + * cdef np.intp_t j + * for j in range(size): + * if x1[j] != x2[j]: # <<<<<<<<<<<<<< + * n_unequal += 1 + * return float(n_unequal) / size + */ + __pyx_t_3 = (((__pyx_v_x1[__pyx_v_j]) != (__pyx_v_x2[__pyx_v_j])) != 0); + if (__pyx_t_3) { + + /* "sklearn/neighbors/dist_metrics.pyx":703 + * for j in range(size): + * if x1[j] != x2[j]: + * n_unequal += 1 # <<<<<<<<<<<<<< + * return float(n_unequal) / size + * + */ + __pyx_v_n_unequal = (__pyx_v_n_unequal + 1); + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "sklearn/neighbors/dist_metrics.pyx":704 + * if x1[j] != x2[j]: + * n_unequal += 1 + * return float(n_unequal) / size # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (((double)__pyx_v_n_unequal) / __pyx_v_size); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":719 + * D(x, y) = \sum_i \frac{|x_i - y_i|}{|x_i| + |y_i|} + * """ + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t denom, d = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_16CanberraDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_CanberraDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_denom; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":721 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef DTYPE_t denom, d = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "sklearn/neighbors/dist_metrics.pyx":723 + * cdef DTYPE_t denom, d = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * denom = abs(x1[j]) + abs(x2[j]) + * if denom > 0: + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":724 + * cdef np.intp_t j + * for j in range(size): + * denom = abs(x1[j]) + abs(x2[j]) # <<<<<<<<<<<<<< + * if denom > 0: + * d += abs(x1[j] - x2[j]) / denom + */ + __pyx_v_denom = (fabs((__pyx_v_x1[__pyx_v_j])) + fabs((__pyx_v_x2[__pyx_v_j]))); + + /* "sklearn/neighbors/dist_metrics.pyx":725 + * for j in range(size): + * denom = abs(x1[j]) + abs(x2[j]) + * if denom > 0: # <<<<<<<<<<<<<< + * d += abs(x1[j] - x2[j]) / denom + * return d + */ + __pyx_t_3 = ((__pyx_v_denom > 0.0) != 0); + if (__pyx_t_3) { + + /* "sklearn/neighbors/dist_metrics.pyx":726 + * denom = abs(x1[j]) + abs(x2[j]) + * if denom > 0: + * d += abs(x1[j] - x2[j]) / denom # <<<<<<<<<<<<<< + * return d + * + */ + __pyx_v_d = (__pyx_v_d + (fabs(((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j]))) / __pyx_v_denom)); + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "sklearn/neighbors/dist_metrics.pyx":727 + * if denom > 0: + * d += abs(x1[j] - x2[j]) / denom + * return d # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_d; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":742 + * D(x, y) = \frac{\sum_i |x_i - y_i|}{\sum_i(|x_i| + |y_i|)} + * """ + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t num = 0, denom = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_18BrayCurtisDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_num; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_denom; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":744 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef DTYPE_t num = 0, denom = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_num = 0.0; + __pyx_v_denom = 0.0; + + /* "sklearn/neighbors/dist_metrics.pyx":746 + * cdef DTYPE_t num = 0, denom = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * num += abs(x1[j] - x2[j]) + * denom += abs(x1[j]) + abs(x2[j]) + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":747 + * cdef np.intp_t j + * for j in range(size): + * num += abs(x1[j] - x2[j]) # <<<<<<<<<<<<<< + * denom += abs(x1[j]) + abs(x2[j]) + * if denom > 0: + */ + __pyx_v_num = (__pyx_v_num + fabs(((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j])))); + + /* "sklearn/neighbors/dist_metrics.pyx":748 + * for j in range(size): + * num += abs(x1[j] - x2[j]) + * denom += abs(x1[j]) + abs(x2[j]) # <<<<<<<<<<<<<< + * if denom > 0: + * return num / denom + */ + __pyx_v_denom = (__pyx_v_denom + (fabs((__pyx_v_x1[__pyx_v_j])) + fabs((__pyx_v_x2[__pyx_v_j])))); + } + + /* "sklearn/neighbors/dist_metrics.pyx":749 + * num += abs(x1[j] - x2[j]) + * denom += abs(x1[j]) + abs(x2[j]) + * if denom > 0: # <<<<<<<<<<<<<< + * return num / denom + * else: + */ + __pyx_t_3 = ((__pyx_v_denom > 0.0) != 0); + if (__pyx_t_3) { + + /* "sklearn/neighbors/dist_metrics.pyx":750 + * denom += abs(x1[j]) + abs(x2[j]) + * if denom > 0: + * return num / denom # <<<<<<<<<<<<<< + * else: + * return 0.0 + */ + __pyx_r = (__pyx_v_num / __pyx_v_denom); + goto __pyx_L0; + goto __pyx_L5; + } + /*else*/ { + + /* "sklearn/neighbors/dist_metrics.pyx":752 + * return num / denom + * else: + * return 0.0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0.0; + goto __pyx_L0; + } + __pyx_L5:; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":768 + * D(x, y) = \frac{N_{TF} + N_{FT}}{N_{TT} + N_{TF} + N_{FT}} + * """ + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef int tf1, tf2, n_eq = 0, nnz = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_15JaccardDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_JaccardDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + int __pyx_v_tf1; + int __pyx_v_tf2; + int __pyx_v_n_eq; + int __pyx_v_nnz; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":770 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef int tf1, tf2, n_eq = 0, nnz = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_n_eq = 0; + __pyx_v_nnz = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":772 + * cdef int tf1, tf2, n_eq = 0, nnz = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":773 + * cdef np.intp_t j + * for j in range(size): + * tf1 = x1[j] != 0 # <<<<<<<<<<<<<< + * tf2 = x2[j] != 0 + * nnz += (tf1 or tf2) + */ + __pyx_v_tf1 = ((__pyx_v_x1[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":774 + * for j in range(size): + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 # <<<<<<<<<<<<<< + * nnz += (tf1 or tf2) + * n_eq += (tf1 and tf2) + */ + __pyx_v_tf2 = ((__pyx_v_x2[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":775 + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + * nnz += (tf1 or tf2) # <<<<<<<<<<<<<< + * n_eq += (tf1 and tf2) + * return (nnz - n_eq) * 1.0 / nnz + */ + if (!__pyx_v_tf1) { + __pyx_t_3 = __pyx_v_tf2; + } else { + __pyx_t_3 = __pyx_v_tf1; + } + __pyx_v_nnz = (__pyx_v_nnz + __pyx_t_3); + + /* "sklearn/neighbors/dist_metrics.pyx":776 + * tf2 = x2[j] != 0 + * nnz += (tf1 or tf2) + * n_eq += (tf1 and tf2) # <<<<<<<<<<<<<< + * return (nnz - n_eq) * 1.0 / nnz + * + */ + if (__pyx_v_tf1) { + __pyx_t_3 = __pyx_v_tf2; + } else { + __pyx_t_3 = __pyx_v_tf1; + } + __pyx_v_n_eq = (__pyx_v_n_eq + __pyx_t_3); + } + + /* "sklearn/neighbors/dist_metrics.pyx":777 + * nnz += (tf1 or tf2) + * n_eq += (tf1 and tf2) + * return (nnz - n_eq) * 1.0 / nnz # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (((__pyx_v_nnz - __pyx_v_n_eq) * 1.0) / __pyx_v_nnz); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":793 + * D(x, y) = \frac{N_{TF} + N_{FT}}{N} + * """ + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef int tf1, tf2, n_neq = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_16MatchingDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MatchingDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + int __pyx_v_tf1; + int __pyx_v_tf2; + int __pyx_v_n_neq; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":795 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef int tf1, tf2, n_neq = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_n_neq = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":797 + * cdef int tf1, tf2, n_neq = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":798 + * cdef np.intp_t j + * for j in range(size): + * tf1 = x1[j] != 0 # <<<<<<<<<<<<<< + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) + */ + __pyx_v_tf1 = ((__pyx_v_x1[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":799 + * for j in range(size): + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 # <<<<<<<<<<<<<< + * n_neq += (tf1 != tf2) + * return n_neq * 1. / size + */ + __pyx_v_tf2 = ((__pyx_v_x2[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":800 + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) # <<<<<<<<<<<<<< + * return n_neq * 1. / size + * + */ + __pyx_v_n_neq = (__pyx_v_n_neq + (__pyx_v_tf1 != __pyx_v_tf2)); + } + + /* "sklearn/neighbors/dist_metrics.pyx":801 + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) + * return n_neq * 1. / size # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((__pyx_v_n_neq * 1.) / __pyx_v_size); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":817 + * D(x, y) = \frac{N_{TF} + N_{FT}}{2 * N_{TT} + N_{TF} + N_{FT}} + * """ + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef int tf1, tf2, n_neq = 0, ntt = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_12DiceDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DiceDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + int __pyx_v_tf1; + int __pyx_v_tf2; + int __pyx_v_n_neq; + int __pyx_v_ntt; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":819 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef int tf1, tf2, n_neq = 0, ntt = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_n_neq = 0; + __pyx_v_ntt = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":821 + * cdef int tf1, tf2, n_neq = 0, ntt = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":822 + * cdef np.intp_t j + * for j in range(size): + * tf1 = x1[j] != 0 # <<<<<<<<<<<<<< + * tf2 = x2[j] != 0 + * ntt += (tf1 and tf2) + */ + __pyx_v_tf1 = ((__pyx_v_x1[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":823 + * for j in range(size): + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 # <<<<<<<<<<<<<< + * ntt += (tf1 and tf2) + * n_neq += (tf1 != tf2) + */ + __pyx_v_tf2 = ((__pyx_v_x2[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":824 + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + * ntt += (tf1 and tf2) # <<<<<<<<<<<<<< + * n_neq += (tf1 != tf2) + * return n_neq / (2.0 * ntt + n_neq) + */ + if (__pyx_v_tf1) { + __pyx_t_3 = __pyx_v_tf2; + } else { + __pyx_t_3 = __pyx_v_tf1; + } + __pyx_v_ntt = (__pyx_v_ntt + __pyx_t_3); + + /* "sklearn/neighbors/dist_metrics.pyx":825 + * tf2 = x2[j] != 0 + * ntt += (tf1 and tf2) + * n_neq += (tf1 != tf2) # <<<<<<<<<<<<<< + * return n_neq / (2.0 * ntt + n_neq) + * + */ + __pyx_v_n_neq = (__pyx_v_n_neq + (__pyx_v_tf1 != __pyx_v_tf2)); + } + + /* "sklearn/neighbors/dist_metrics.pyx":826 + * ntt += (tf1 and tf2) + * n_neq += (tf1 != tf2) + * return n_neq / (2.0 * ntt + n_neq) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (__pyx_v_n_neq / ((2.0 * __pyx_v_ntt) + __pyx_v_n_neq)); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":842 + * D(x, y) = 1 - \frac{N_{TT}}{N + N_{TF} + N_{FT}} + * """ + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef int tf1, tf2, ntt = 0, n_neq = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17KulsinskiDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + int __pyx_v_tf1; + int __pyx_v_tf2; + int __pyx_v_ntt; + int __pyx_v_n_neq; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":844 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef int tf1, tf2, ntt = 0, n_neq = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_ntt = 0; + __pyx_v_n_neq = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":846 + * cdef int tf1, tf2, ntt = 0, n_neq = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":847 + * cdef np.intp_t j + * for j in range(size): + * tf1 = x1[j] != 0 # <<<<<<<<<<<<<< + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) + */ + __pyx_v_tf1 = ((__pyx_v_x1[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":848 + * for j in range(size): + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 # <<<<<<<<<<<<<< + * n_neq += (tf1 != tf2) + * ntt += (tf1 and tf2) + */ + __pyx_v_tf2 = ((__pyx_v_x2[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":849 + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) # <<<<<<<<<<<<<< + * ntt += (tf1 and tf2) + * return (n_neq - ntt + size) * 1.0 / (n_neq + size) + */ + __pyx_v_n_neq = (__pyx_v_n_neq + (__pyx_v_tf1 != __pyx_v_tf2)); + + /* "sklearn/neighbors/dist_metrics.pyx":850 + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) + * ntt += (tf1 and tf2) # <<<<<<<<<<<<<< + * return (n_neq - ntt + size) * 1.0 / (n_neq + size) + * + */ + if (__pyx_v_tf1) { + __pyx_t_3 = __pyx_v_tf2; + } else { + __pyx_t_3 = __pyx_v_tf1; + } + __pyx_v_ntt = (__pyx_v_ntt + __pyx_t_3); + } + + /* "sklearn/neighbors/dist_metrics.pyx":851 + * n_neq += (tf1 != tf2) + * ntt += (tf1 and tf2) + * return (n_neq - ntt + size) * 1.0 / (n_neq + size) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((((__pyx_v_n_neq - __pyx_v_ntt) + __pyx_v_size) * 1.0) / (__pyx_v_n_neq + __pyx_v_size)); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":867 + * D(x, y) = \frac{2 (N_{TF} + N_{FT})}{N + N_{TF} + N_{FT}} + * """ + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef int tf1, tf2, n_neq = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_22RogersTanimotoDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + int __pyx_v_tf1; + int __pyx_v_tf2; + int __pyx_v_n_neq; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":869 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef int tf1, tf2, n_neq = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_n_neq = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":871 + * cdef int tf1, tf2, n_neq = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":872 + * cdef np.intp_t j + * for j in range(size): + * tf1 = x1[j] != 0 # <<<<<<<<<<<<<< + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) + */ + __pyx_v_tf1 = ((__pyx_v_x1[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":873 + * for j in range(size): + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 # <<<<<<<<<<<<<< + * n_neq += (tf1 != tf2) + * return (2.0 * n_neq) / (size + n_neq) + */ + __pyx_v_tf2 = ((__pyx_v_x2[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":874 + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) # <<<<<<<<<<<<<< + * return (2.0 * n_neq) / (size + n_neq) + * + */ + __pyx_v_n_neq = (__pyx_v_n_neq + (__pyx_v_tf1 != __pyx_v_tf2)); + } + + /* "sklearn/neighbors/dist_metrics.pyx":875 + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) + * return (2.0 * n_neq) / (size + n_neq) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((2.0 * __pyx_v_n_neq) / (__pyx_v_size + __pyx_v_n_neq)); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":891 + * D(x, y) = \frac{N - N_{TT}}{N} + * """ + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef int tf1, tf2, ntt = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_18RussellRaoDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + int __pyx_v_tf1; + int __pyx_v_tf2; + int __pyx_v_ntt; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":893 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef int tf1, tf2, ntt = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_ntt = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":895 + * cdef int tf1, tf2, ntt = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":896 + * cdef np.intp_t j + * for j in range(size): + * tf1 = x1[j] != 0 # <<<<<<<<<<<<<< + * tf2 = x2[j] != 0 + * ntt += (tf1 and tf2) + */ + __pyx_v_tf1 = ((__pyx_v_x1[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":897 + * for j in range(size): + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 # <<<<<<<<<<<<<< + * ntt += (tf1 and tf2) + * return (size - ntt) * 1. / size + */ + __pyx_v_tf2 = ((__pyx_v_x2[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":898 + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + * ntt += (tf1 and tf2) # <<<<<<<<<<<<<< + * return (size - ntt) * 1. / size + * + */ + if (__pyx_v_tf1) { + __pyx_t_3 = __pyx_v_tf2; + } else { + __pyx_t_3 = __pyx_v_tf1; + } + __pyx_v_ntt = (__pyx_v_ntt + __pyx_t_3); + } + + /* "sklearn/neighbors/dist_metrics.pyx":899 + * tf2 = x2[j] != 0 + * ntt += (tf1 and tf2) + * return (size - ntt) * 1. / size # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (((__pyx_v_size - __pyx_v_ntt) * 1.) / __pyx_v_size); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":915 + * D(x, y) = \frac{2 (N_{TF} + N_{FT})}{N + N_{TF} + N_{FT}} + * """ + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef int tf1, tf2, n_neq = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_21SokalMichenerDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + int __pyx_v_tf1; + int __pyx_v_tf2; + int __pyx_v_n_neq; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":917 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef int tf1, tf2, n_neq = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_n_neq = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":919 + * cdef int tf1, tf2, n_neq = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":920 + * cdef np.intp_t j + * for j in range(size): + * tf1 = x1[j] != 0 # <<<<<<<<<<<<<< + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) + */ + __pyx_v_tf1 = ((__pyx_v_x1[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":921 + * for j in range(size): + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 # <<<<<<<<<<<<<< + * n_neq += (tf1 != tf2) + * return (2.0 * n_neq) / (size + n_neq) + */ + __pyx_v_tf2 = ((__pyx_v_x2[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":922 + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) # <<<<<<<<<<<<<< + * return (2.0 * n_neq) / (size + n_neq) + * + */ + __pyx_v_n_neq = (__pyx_v_n_neq + (__pyx_v_tf1 != __pyx_v_tf2)); + } + + /* "sklearn/neighbors/dist_metrics.pyx":923 + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) + * return (2.0 * n_neq) / (size + n_neq) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((2.0 * __pyx_v_n_neq) / (__pyx_v_size + __pyx_v_n_neq)); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":939 + * D(x, y) = \frac{N_{TF} + N_{FT}}{N_{TT} / 2 + N_{TF} + N_{FT}} + * """ + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef int tf1, tf2, ntt = 0, n_neq = 0 + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_19SokalSneathDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + int __pyx_v_tf1; + int __pyx_v_tf2; + int __pyx_v_ntt; + int __pyx_v_n_neq; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":941 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef int tf1, tf2, ntt = 0, n_neq = 0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_ntt = 0; + __pyx_v_n_neq = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":943 + * cdef int tf1, tf2, ntt = 0, n_neq = 0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pyx":944 + * cdef np.intp_t j + * for j in range(size): + * tf1 = x1[j] != 0 # <<<<<<<<<<<<<< + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) + */ + __pyx_v_tf1 = ((__pyx_v_x1[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":945 + * for j in range(size): + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 # <<<<<<<<<<<<<< + * n_neq += (tf1 != tf2) + * ntt += (tf1 and tf2) + */ + __pyx_v_tf2 = ((__pyx_v_x2[__pyx_v_j]) != 0.0); + + /* "sklearn/neighbors/dist_metrics.pyx":946 + * tf1 = x1[j] != 0 + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) # <<<<<<<<<<<<<< + * ntt += (tf1 and tf2) + * return n_neq / (0.5 * ntt + n_neq) + */ + __pyx_v_n_neq = (__pyx_v_n_neq + (__pyx_v_tf1 != __pyx_v_tf2)); + + /* "sklearn/neighbors/dist_metrics.pyx":947 + * tf2 = x2[j] != 0 + * n_neq += (tf1 != tf2) + * ntt += (tf1 and tf2) # <<<<<<<<<<<<<< + * return n_neq / (0.5 * ntt + n_neq) + * + */ + if (__pyx_v_tf1) { + __pyx_t_3 = __pyx_v_tf2; + } else { + __pyx_t_3 = __pyx_v_tf1; + } + __pyx_v_ntt = (__pyx_v_ntt + __pyx_t_3); + } + + /* "sklearn/neighbors/dist_metrics.pyx":948 + * n_neq += (tf1 != tf2) + * ntt += (tf1 and tf2) + * return n_neq / (0.5 * ntt + n_neq) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (__pyx_v_n_neq / ((0.5 * __pyx_v_ntt) + __pyx_v_n_neq)); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":967 + * + cos(x1)cos(y1)sin^2((x2 - y2) / 2)}] + * """ + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * if size != 2: + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_sin_0; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_sin_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":969 + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * if size != 2: # <<<<<<<<<<<<<< + * raise ValueError("Haversine distance only valid in 2 dimensions") + * cdef DTYPE_t sin_0 = sin(0.5 * (x1[0] - x2[0])) + */ + __pyx_t_1 = ((__pyx_v_size != 2) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/dist_metrics.pyx":970 + * ITYPE_t size) except -1: + * if size != 2: + * raise ValueError("Haversine distance only valid in 2 dimensions") # <<<<<<<<<<<<<< + * cdef DTYPE_t sin_0 = sin(0.5 * (x1[0] - x2[0])) + * cdef DTYPE_t sin_1 = sin(0.5 * (x1[1] - x2[1])) + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_26), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 970; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 970; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/neighbors/dist_metrics.pyx":971 + * if size != 2: + * raise ValueError("Haversine distance only valid in 2 dimensions") + * 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) + */ + __pyx_v_sin_0 = sin((0.5 * ((__pyx_v_x1[0]) - (__pyx_v_x2[0])))); + + /* "sklearn/neighbors/dist_metrics.pyx":972 + * raise ValueError("Haversine distance only valid in 2 dimensions") + * 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) + * + */ + __pyx_v_sin_1 = sin((0.5 * ((__pyx_v_x1[1]) - (__pyx_v_x2[1])))); + + /* "sklearn/neighbors/dist_metrics.pyx":973 + * 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) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_r = ((__pyx_v_sin_0 * __pyx_v_sin_0) + (((cos((__pyx_v_x1[0])) * cos((__pyx_v_x2[0]))) * __pyx_v_sin_1) * __pyx_v_sin_1)); + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.HaversineDistance.rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":975 + * return (sin_0 * sin_0 + cos(x1[0]) * cos(x2[0]) * sin_1 * sin_1) + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * if size != 2: + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_sin_0; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_sin_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":977 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * if size != 2: # <<<<<<<<<<<<<< + * raise ValueError("Haversine distance only valid in 2 dimensions") + * cdef DTYPE_t sin_0 = sin(0.5 * (x1[0] - x2[0])) + */ + __pyx_t_1 = ((__pyx_v_size != 2) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/dist_metrics.pyx":978 + * ITYPE_t size) except -1: + * if size != 2: + * raise ValueError("Haversine distance only valid in 2 dimensions") # <<<<<<<<<<<<<< + * cdef DTYPE_t sin_0 = sin(0.5 * (x1[0] - x2[0])) + * cdef DTYPE_t sin_1 = sin(0.5 * (x1[1] - x2[1])) + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_27), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 978; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 978; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/neighbors/dist_metrics.pyx":979 + * if size != 2: + * raise ValueError("Haversine distance only valid in 2 dimensions") + * 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 2 * asin(sqrt(sin_0 * sin_0 + */ + __pyx_v_sin_0 = sin((0.5 * ((__pyx_v_x1[0]) - (__pyx_v_x2[0])))); + + /* "sklearn/neighbors/dist_metrics.pyx":980 + * raise ValueError("Haversine distance only valid in 2 dimensions") + * 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 2 * asin(sqrt(sin_0 * sin_0 + * + cos(x1[0]) * cos(x2[0]) * sin_1 * sin_1)) + */ + __pyx_v_sin_1 = sin((0.5 * ((__pyx_v_x1[1]) - (__pyx_v_x2[1])))); + + /* "sklearn/neighbors/dist_metrics.pyx":982 + * cdef DTYPE_t sin_1 = sin(0.5 * (x1[1] - x2[1])) + * return 2 * asin(sqrt(sin_0 * sin_0 + * + cos(x1[0]) * cos(x2[0]) * sin_1 * sin_1)) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist): + */ + __pyx_r = (2.0 * asin(sqrt(((__pyx_v_sin_0 * __pyx_v_sin_0) + (((cos((__pyx_v_x1[0])) * cos((__pyx_v_x2[0]))) * __pyx_v_sin_1) * __pyx_v_sin_1))))); + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.HaversineDistance.dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":984 + * + cos(x1[0]) * cos(x2[0]) * sin_1 * sin_1)) + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist): # <<<<<<<<<<<<<< + * return 2 * asin(sqrt(rdist)) + * + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17HaversineDistance__rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rdist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":985 + * + * cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist): + * return 2 * asin(sqrt(rdist)) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist): + */ + __pyx_r = (2.0 * asin(sqrt(__pyx_v_rdist))); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":987 + * return 2 * asin(sqrt(rdist)) + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist): # <<<<<<<<<<<<<< + * cdef DTYPE_t tmp = sin(0.5 * dist) + * return tmp * tmp + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_17HaversineDistance__dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_tmp; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":988 + * + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist): + * cdef DTYPE_t tmp = sin(0.5 * dist) # <<<<<<<<<<<<<< + * return tmp * tmp + * + */ + __pyx_v_tmp = sin((0.5 * __pyx_v_dist)); + + /* "sklearn/neighbors/dist_metrics.pyx":989 + * cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist): + * cdef DTYPE_t tmp = sin(0.5 * dist) + * return tmp * tmp # <<<<<<<<<<<<<< + * + * def rdist_to_dist(self, rdist): + */ + __pyx_r = (__pyx_v_tmp * __pyx_v_tmp); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_1rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_1rdist_to_dist(PyObject *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("rdist_to_dist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_rdist_to_dist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *)__pyx_v_self), ((PyObject *)__pyx_v_rdist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":991 + * return tmp * tmp + * + * def rdist_to_dist(self, rdist): # <<<<<<<<<<<<<< + * return 2 * np.arcsin(np.sqrt(rdist)) + * + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_rdist_to_dist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *__pyx_v_self, PyObject *__pyx_v_rdist) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":992 + * + * def rdist_to_dist(self, rdist): + * return 2 * np.arcsin(np.sqrt(rdist)) # <<<<<<<<<<<<<< + * + * def dist_to_rdist(self, dist): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__arcsin); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__sqrt); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_rdist); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_rdist); + __Pyx_GIVEREF(__pyx_v_rdist); + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Multiply(__pyx_int_2, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.HaversineDistance.rdist_to_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_3dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_3dist_to_rdist(PyObject *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dist_to_rdist (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_2dist_to_rdist(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *)__pyx_v_self), ((PyObject *)__pyx_v_dist)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":994 + * return 2 * np.arcsin(np.sqrt(rdist)) + * + * def dist_to_rdist(self, dist): # <<<<<<<<<<<<<< + * tmp = np.sin(0.5 * dist) + * return tmp * tmp + */ + +static PyObject *__pyx_pf_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_2dist_to_rdist(CYTHON_UNUSED struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *__pyx_v_self, PyObject *__pyx_v_dist) { + PyObject *__pyx_v_tmp = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":995 + * + * def dist_to_rdist(self, dist): + * tmp = np.sin(0.5 * dist) # <<<<<<<<<<<<<< + * return tmp * tmp + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 995; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__sin); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 995; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyFloat_FromDouble(0.5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 995; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_v_dist); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 995; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 995; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 995; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_v_tmp = __pyx_t_3; + __pyx_t_3 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":996 + * def dist_to_rdist(self, dist): + * tmp = np.sin(0.5 * dist) + * return tmp * tmp # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = PyNumber_Multiply(__pyx_v_tmp, __pyx_v_tmp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 996; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.HaversineDistance.dist_to_rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_tmp); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_14PyFuncDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_12dist_metrics_14PyFuncDistance_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_func = 0; + PyObject *__pyx_v_kwargs = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + __pyx_v_kwargs = PyDict_New(); if (unlikely(!__pyx_v_kwargs)) return -1; + __Pyx_GOTREF(__pyx_v_kwargs); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__func,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__func)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, __pyx_v_kwargs, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1074; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_func = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1074; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_DECREF(__pyx_v_kwargs); __pyx_v_kwargs = 0; + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.PyFuncDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_12dist_metrics_14PyFuncDistance___init__(((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_PyFuncDistance *)__pyx_v_self), __pyx_v_func, __pyx_v_kwargs); + __Pyx_XDECREF(__pyx_v_kwargs); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":1074 + * func should take two numpy arrays as input, and return a distance. + * """ + * def __init__(self, func, **kwargs): # <<<<<<<<<<<<<< + * self.func = func + * x = np.random.random(10) + */ + +static int __pyx_pf_7sklearn_9neighbors_12dist_metrics_14PyFuncDistance___init__(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_PyFuncDistance *__pyx_v_self, PyObject *__pyx_v_func, PyObject *__pyx_v_kwargs) { + PyObject *__pyx_v_x = NULL; + PyObject *__pyx_v_d = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + double __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":1075 + * """ + * def __init__(self, func, **kwargs): + * self.func = func # <<<<<<<<<<<<<< + * x = np.random.random(10) + * try: + */ + __Pyx_INCREF(__pyx_v_func); + __Pyx_GIVEREF(__pyx_v_func); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.func); + __Pyx_DECREF(__pyx_v_self->__pyx_base.func); + __pyx_v_self->__pyx_base.func = __pyx_v_func; + + /* "sklearn/neighbors/dist_metrics.pyx":1076 + * def __init__(self, func, **kwargs): + * self.func = func + * x = np.random.random(10) # <<<<<<<<<<<<<< + * try: + * d = self.func(x, x, **kwargs) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__random); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__random); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_28), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_x = __pyx_t_2; + __pyx_t_2 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":1077 + * self.func = func + * x = np.random.random(10) + * try: # <<<<<<<<<<<<<< + * d = self.func(x, x, **kwargs) + * except TypeError: + */ + { + __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + /*try:*/ { + + /* "sklearn/neighbors/dist_metrics.pyx":1078 + * x = np.random.random(10) + * try: + * d = self.func(x, x, **kwargs) # <<<<<<<<<<<<<< + * except TypeError: + * raise ValueError("func must be a callable taking two arrays") + */ + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1078; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_x); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_x); + __Pyx_GIVEREF(__pyx_v_x); + __Pyx_INCREF(__pyx_v_x); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_x); + __Pyx_GIVEREF(__pyx_v_x); + __pyx_t_1 = ((PyObject *)__pyx_v_kwargs); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_6 = PyObject_Call(__pyx_v_self->__pyx_base.func, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1078; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_v_d = __pyx_t_6; + __pyx_t_6 = 0; + } + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L10_try_end; + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":1079 + * try: + * d = self.func(x, x, **kwargs) + * except TypeError: # <<<<<<<<<<<<<< + * raise ValueError("func must be a callable taking two arrays") + * + */ + __pyx_t_7 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_7) { + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.PyFuncDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_6, &__pyx_t_1, &__pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1079; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_t_2); + + /* "sklearn/neighbors/dist_metrics.pyx":1080 + * d = self.func(x, x, **kwargs) + * except TypeError: + * raise ValueError("func must be a callable taking two arrays") # <<<<<<<<<<<<<< + * + * try: + */ + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_30), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1080; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1080; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L4_exception_handled; + } + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L1_error; + __pyx_L4_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + __pyx_L10_try_end:; + } + + /* "sklearn/neighbors/dist_metrics.pyx":1082 + * raise ValueError("func must be a callable taking two arrays") + * + * try: # <<<<<<<<<<<<<< + * d = float(d) + * except TypeError: + */ + { + __Pyx_ExceptionSave(&__pyx_t_5, &__pyx_t_4, &__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_3); + /*try:*/ { + + /* "sklearn/neighbors/dist_metrics.pyx":1083 + * + * try: + * d = float(d) # <<<<<<<<<<<<<< + * except TypeError: + * raise ValueError("func must return a float") + */ + __pyx_t_9 = __Pyx_PyObject_AsDouble(__pyx_v_d); if (unlikely(__pyx_t_9 == ((double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1083; __pyx_clineno = __LINE__; goto __pyx_L13_error;} + __pyx_t_2 = PyFloat_FromDouble(__pyx_t_9); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1083; __pyx_clineno = __LINE__; goto __pyx_L13_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_v_d); + __pyx_v_d = __pyx_t_2; + __pyx_t_2 = 0; + } + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L20_try_end; + __pyx_L13_error:; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":1084 + * try: + * d = float(d) + * except TypeError: # <<<<<<<<<<<<<< + * raise ValueError("func must return a float") + * + */ + __pyx_t_7 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_7) { + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.PyFuncDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_2, &__pyx_t_1, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L15_except_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_t_6); + + /* "sklearn/neighbors/dist_metrics.pyx":1085 + * d = float(d) + * except TypeError: + * raise ValueError("func must return a float") # <<<<<<<<<<<<<< + * + * self.kwargs = kwargs + */ + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_32), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L15_except_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L15_except_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L14_exception_handled; + } + __pyx_L15_except_error:; + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_ExceptionReset(__pyx_t_5, __pyx_t_4, __pyx_t_3); + goto __pyx_L1_error; + __pyx_L14_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_ExceptionReset(__pyx_t_5, __pyx_t_4, __pyx_t_3); + __pyx_L20_try_end:; + } + + /* "sklearn/neighbors/dist_metrics.pyx":1087 + * raise ValueError("func must return a float") + * + * self.kwargs = kwargs # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __Pyx_INCREF(((PyObject *)__pyx_v_kwargs)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_kwargs)); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.kwargs); + __Pyx_DECREF(__pyx_v_self->__pyx_base.kwargs); + __pyx_v_self->__pyx_base.kwargs = ((PyObject *)__pyx_v_kwargs); + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.PyFuncDistance.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_x); + __Pyx_XDECREF(__pyx_v_d); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":1089 + * self.kwargs = kwargs + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef np.ndarray x1arr = _buffer_to_ndarray(x1, size) + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_14PyFuncDistance_dist(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_PyFuncDistance *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + PyArrayObject *__pyx_v_x1arr = 0; + PyArrayObject *__pyx_v_x2arr = 0; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":1091 + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef np.ndarray x1arr = _buffer_to_ndarray(x1, size) # <<<<<<<<<<<<<< + * cdef np.ndarray x2arr = _buffer_to_ndarray(x2, size) + * return self.func(x1arr, x2arr, **self.kwargs) + */ + __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_9neighbors_12dist_metrics__buffer_to_ndarray(__pyx_v_x1, __pyx_v_size)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1091; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_x1arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":1092 + * ITYPE_t size) except -1: + * cdef np.ndarray x1arr = _buffer_to_ndarray(x1, size) + * cdef np.ndarray x2arr = _buffer_to_ndarray(x2, size) # <<<<<<<<<<<<<< + * return self.func(x1arr, x2arr, **self.kwargs) + * + */ + __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_9neighbors_12dist_metrics__buffer_to_ndarray(__pyx_v_x2, __pyx_v_size)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1092; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_x2arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":1093 + * cdef np.ndarray x1arr = _buffer_to_ndarray(x1, size) + * cdef np.ndarray x2arr = _buffer_to_ndarray(x2, size) + * return self.func(x1arr, x2arr, **self.kwargs) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1093; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_x1arr)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_x1arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_x1arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_x2arr)); + PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_x2arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_x2arr)); + if (unlikely(__pyx_v_self->__pyx_base.kwargs == Py_None)) { + PyErr_SetString(PyExc_TypeError, "argument after ** must be a mapping, not NoneType"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1093; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (likely(PyDict_Check(__pyx_v_self->__pyx_base.kwargs))) { + __pyx_t_2 = __pyx_v_self->__pyx_base.kwargs; + __Pyx_INCREF(__pyx_t_2); + } else { + __pyx_t_2 = PyObject_CallFunctionObjArgs((PyObject*)&PyDict_Type, __pyx_v_self->__pyx_base.kwargs, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1093; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + } + __pyx_t_3 = PyObject_Call(__pyx_v_self->__pyx_base.func, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1093; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1093; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.dist_metrics.PyFuncDistance.dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_x1arr); + __Pyx_XDECREF((PyObject *)__pyx_v_x2arr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pyx":1096 + * + * + * cdef inline double fmax(double a, double b): # <<<<<<<<<<<<<< + * return max(a, b) + */ + +static CYTHON_INLINE double __pyx_f_7sklearn_9neighbors_12dist_metrics_fmax(double __pyx_v_a, double __pyx_v_b) { + double __pyx_r; + __Pyx_RefNannyDeclarations + double __pyx_t_1; + double __pyx_t_2; + double __pyx_t_3; + __Pyx_RefNannySetupContext("fmax", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":1097 + * + * cdef inline double fmax(double a, double b): + * return max(a, b) # <<<<<<<<<<<<<< + */ + __pyx_t_1 = __pyx_v_b; + __pyx_t_2 = __pyx_v_a; + if (((__pyx_t_1 > __pyx_t_2) != 0)) { + __pyx_t_3 = __pyx_t_1; + } else { + __pyx_t_3 = __pyx_t_2; + } + __pyx_r = __pyx_t_3; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pxd":18 + * # We use these for the default (euclidean) case so that they can be + * # inlined. This leads to faster computation for the most common case + * cdef inline DTYPE_t euclidean_dist(DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_tmp; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("euclidean_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pxd":20 + * cdef inline DTYPE_t euclidean_dist(DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "sklearn/neighbors/dist_metrics.pxd":22 + * cdef DTYPE_t tmp, d=0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tmp = x1[j] - x2[j] + * d += tmp * tmp + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pxd":23 + * cdef np.intp_t j + * for j in range(size): + * tmp = x1[j] - x2[j] # <<<<<<<<<<<<<< + * d += tmp * tmp + * return sqrt(d) + */ + __pyx_v_tmp = ((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j])); + + /* "sklearn/neighbors/dist_metrics.pxd":24 + * for j in range(size): + * tmp = x1[j] - x2[j] + * d += tmp * tmp # <<<<<<<<<<<<<< + * return sqrt(d) + * + */ + __pyx_v_d = (__pyx_v_d + (__pyx_v_tmp * __pyx_v_tmp)); + } + + /* "sklearn/neighbors/dist_metrics.pxd":25 + * tmp = x1[j] - x2[j] + * d += tmp * tmp + * return sqrt(d) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = sqrt(__pyx_v_d); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pxd":28 + * + * + * cdef inline DTYPE_t euclidean_rdist(DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_tmp; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("euclidean_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pxd":30 + * cdef inline DTYPE_t euclidean_rdist(DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "sklearn/neighbors/dist_metrics.pxd":32 + * cdef DTYPE_t tmp, d=0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tmp = x1[j] - x2[j] + * d += tmp * tmp + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "sklearn/neighbors/dist_metrics.pxd":33 + * cdef np.intp_t j + * for j in range(size): + * tmp = x1[j] - x2[j] # <<<<<<<<<<<<<< + * d += tmp * tmp + * return d + */ + __pyx_v_tmp = ((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j])); + + /* "sklearn/neighbors/dist_metrics.pxd":34 + * for j in range(size): + * tmp = x1[j] - x2[j] + * d += tmp * tmp # <<<<<<<<<<<<<< + * return d + * + */ + __pyx_v_d = (__pyx_v_d + (__pyx_v_tmp * __pyx_v_tmp)); + } + + /* "sklearn/neighbors/dist_metrics.pxd":35 + * tmp = x1[j] - x2[j] + * d += tmp * tmp + * return d # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_d; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pxd":38 + * + * + * cdef inline DTYPE_t euclidean_dist_to_rdist(DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return dist * dist + * + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist_to_rdist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("euclidean_dist_to_rdist", 0); + + /* "sklearn/neighbors/dist_metrics.pxd":39 + * + * cdef inline DTYPE_t euclidean_dist_to_rdist(DTYPE_t dist) except -1: + * return dist * dist # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (__pyx_v_dist * __pyx_v_dist); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/dist_metrics.pxd":42 + * + * + * cdef inline DTYPE_t euclidean_rdist_to_dist(DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return sqrt(dist) + * + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist_to_dist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("euclidean_rdist_to_dist", 0); + + /* "sklearn/neighbors/dist_metrics.pxd":43 + * + * cdef inline DTYPE_t euclidean_rdist_to_dist(DTYPE_t dist) except -1: + * return sqrt(dist) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = sqrt(__pyx_v_dist); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "numpy.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "numpy.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "numpy.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "numpy.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "numpy.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_34), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "numpy.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_3) { + + /* "numpy.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "numpy.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_36), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "numpy.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "numpy.pxd":222 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "numpy.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { + + /* "numpy.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "numpy.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "numpy.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "numpy.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "numpy.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "numpy.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "numpy.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "numpy.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "numpy.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "numpy.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "numpy.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "numpy.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "numpy.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "numpy.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "numpy.pxd":251 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "numpy.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; + + /* "numpy.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); + if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "numpy.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_1) { + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_38), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "numpy.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k__b; + break; + + /* "numpy.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k__B; + break; + + /* "numpy.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k__h; + break; + + /* "numpy.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k__H; + break; + + /* "numpy.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k__i; + break; + + /* "numpy.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k__I; + break; + + /* "numpy.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k__l; + break; + + /* "numpy.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k__L; + break; + + /* "numpy.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k__q; + break; + + /* "numpy.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k__Q; + break; + + /* "numpy.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k__f; + break; + + /* "numpy.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k__d; + break; + + /* "numpy.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k__g; + break; + + /* "numpy.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k__Zf; + break; + + /* "numpy.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k__Zd; + break; + + /* "numpy.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k__Zg; + break; + + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k__O; + break; + default: + + /* "numpy.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_39), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "numpy.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "numpy.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "numpy.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "numpy.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "numpy.pxd":285 + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + * &offset) # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "numpy.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + __pyx_L11:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "numpy.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "numpy.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "numpy.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "numpy.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "numpy.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "numpy.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + long __pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "numpy.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF(__pyx_v_childname); + __pyx_v_childname = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); + __pyx_v_fields = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "numpy.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { + PyObject* sequence = ((PyObject *)__pyx_v_fields); + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_child)); + __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_v_new_offset); + __pyx_v_new_offset = __pyx_t_4; + __pyx_t_4 = 0; + + /* "numpy.pxd":798 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + + /* "numpy.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_41), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + + /* "numpy.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_7) { + __pyx_t_8 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_8 = __pyx_t_7; + } + if (!__pyx_t_8) { + + /* "numpy.pxd":802 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + __pyx_t_9 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_10 = __pyx_t_9; + } else { + __pyx_t_10 = __pyx_t_7; + } + __pyx_t_7 = __pyx_t_10; + } else { + __pyx_t_7 = __pyx_t_8; + } + if (__pyx_t_7) { + + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_42), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + + /* "numpy.pxd":813 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_7) break; + + /* "numpy.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "numpy.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "numpy.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); + } + + /* "numpy.pxd":818 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); + + /* "numpy.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_7 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_7) { + + /* "numpy.pxd":821 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_v_t); + __pyx_v_t = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_7 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_7) { + + /* "numpy.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_44), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 98; + goto __pyx_L13; + } + + /* "numpy.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 66; + goto __pyx_L13; + } + + /* "numpy.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 104; + goto __pyx_L13; + } + + /* "numpy.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 72; + goto __pyx_L13; + } + + /* "numpy.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 105; + goto __pyx_L13; + } + + /* "numpy.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 73; + goto __pyx_L13; + } + + /* "numpy.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 108; + goto __pyx_L13; + } + + /* "numpy.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 76; + goto __pyx_L13; + } + + /* "numpy.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 113; + goto __pyx_L13; + } + + /* "numpy.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 81; + goto __pyx_L13; + } + + /* "numpy.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 102; + goto __pyx_L13; + } + + /* "numpy.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 100; + goto __pyx_L13; + } + + /* "numpy.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 103; + goto __pyx_L13; + } + + /* "numpy.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 79; + goto __pyx_L13; + } + /*else*/ { + + /* "numpy.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_39), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L13:; + + /* "numpy.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_12; + } + __pyx_L11:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "numpy.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":965 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "numpy.pxd":967 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "numpy.pxd":968 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":970 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "numpy.pxd":971 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "numpy.pxd":972 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "numpy.pxd":973 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":975 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "numpy.pxd":976 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":977 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":979 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_shape = 0; + Py_ssize_t __pyx_v_itemsize; + PyObject *__pyx_v_format = 0; + PyObject *__pyx_v_mode = 0; + int __pyx_v_allocate_buffer; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__shape,&__pyx_n_s__itemsize,&__pyx_n_s__format,&__pyx_n_s__mode,&__pyx_n_s__allocate_buffer,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[3] = ((PyObject *)__pyx_n_u__c); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shape)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__itemsize)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__format)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__mode); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__allocate_buffer); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_shape = ((PyObject*)values[0]); + __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_format = values[2]; + __pyx_v_mode = values[3]; + if (values[4]) { + __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "View.MemoryView":114 + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, + * mode=u"c", bint allocate_buffer=True): # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_v_allocate_buffer = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { + PyErr_Format(PyExc_TypeError, "Argument 'format' must not be None"); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_r = __pyx_array_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":113 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode=u"c", bint allocate_buffer=True): + * + */ + +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { + int __pyx_v_idx; + Py_ssize_t __pyx_v_i; + PyObject **__pyx_v_p; + PyObject *__pyx_v_encode = NULL; + PyObject *__pyx_v_dim = NULL; + char __pyx_v_order; + PyObject *__pyx_v_decode = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_INCREF(__pyx_v_format); + __Pyx_INCREF(__pyx_v_mode); + + /* "View.MemoryView":120 + * cdef PyObject **p + * + * self.ndim = len(shape) # <<<<<<<<<<<<<< + * self.itemsize = itemsize + * + */ + if (unlikely(((PyObject *)__pyx_v_shape) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = PyTuple_GET_SIZE(((PyObject *)__pyx_v_shape)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->ndim = __pyx_t_1; + + /* "View.MemoryView":121 + * + * self.ndim = len(shape) + * self.itemsize = itemsize # <<<<<<<<<<<<<< + * + * if not self.ndim: + */ + __pyx_v_self->itemsize = __pyx_v_itemsize; + + /* "View.MemoryView":123 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ + __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":124 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if self.itemsize <= 0: + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_46), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":126 + * raise ValueError("Empty shape tuple for cython.array") + * + * if self.itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ + __pyx_t_2 = ((__pyx_v_self->itemsize <= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":127 + * + * if self.itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * encode = getattr(format, 'encode', None) + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_48), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":129 + * raise ValueError("itemsize <= 0 for cython.array") + * + * encode = getattr(format, 'encode', None) # <<<<<<<<<<<<<< + * if encode: + * format = encode('ASCII') + */ + __pyx_t_3 = __Pyx_GetAttr3(__pyx_v_format, ((PyObject *)__pyx_n_s__encode), Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_encode = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":130 + * + * encode = getattr(format, 'encode', None) + * if encode: # <<<<<<<<<<<<<< + * format = encode('ASCII') + * self._format = format + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_encode); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":131 + * encode = getattr(format, 'encode', None) + * if encode: + * format = encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format + * self.format = self._format + */ + __pyx_t_3 = PyObject_Call(__pyx_v_encode, ((PyObject *)__pyx_k_tuple_49), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_format); + __pyx_v_format = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":132 + * if encode: + * format = encode('ASCII') + * self._format = format # <<<<<<<<<<<<<< + * self.format = self._format + * + */ + if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_format); + __Pyx_GIVEREF(__pyx_v_format); + __Pyx_GOTREF(__pyx_v_self->_format); + __Pyx_DECREF(((PyObject *)__pyx_v_self->_format)); + __pyx_v_self->_format = ((PyObject*)__pyx_v_format); + + /* "View.MemoryView":133 + * format = encode('ASCII') + * self._format = format + * self.format = self._format # <<<<<<<<<<<<<< + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) + */ + __pyx_t_4 = __Pyx_PyObject_AsString(((PyObject *)__pyx_v_self->_format)); if (unlikely((!__pyx_t_4) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->format = __pyx_t_4; + + /* "View.MemoryView":135 + * self.format = self._format + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<< + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) + * + */ + __pyx_v_self->_shape = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim))); + + /* "View.MemoryView":136 + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<< + * + * if not self._shape or not self._strides: + */ + __pyx_v_self->_strides = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim))); + + /* "View.MemoryView":138 + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) + * + * if not self._shape or not self._strides: # <<<<<<<<<<<<<< + * free(self._shape) + * free(self._strides) + */ + __pyx_t_2 = ((!(__pyx_v_self->_shape != 0)) != 0); + if (!__pyx_t_2) { + __pyx_t_5 = ((!(__pyx_v_self->_strides != 0)) != 0); + __pyx_t_6 = __pyx_t_5; + } else { + __pyx_t_6 = __pyx_t_2; + } + if (__pyx_t_6) { + + /* "View.MemoryView":139 + * + * if not self._shape or not self._strides: + * free(self._shape) # <<<<<<<<<<<<<< + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") + */ + free(__pyx_v_self->_shape); + + /* "View.MemoryView":140 + * if not self._shape or not self._strides: + * free(self._shape) + * free(self._strides) # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape or strides.") + * + */ + free(__pyx_v_self->_strides); + + /* "View.MemoryView":141 + * free(self._shape) + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_51), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":144 + * + * + * idx = 0 # <<<<<<<<<<<<<< + * for idx, dim in enumerate(shape): + * if dim <= 0: + */ + __pyx_v_idx = 0; + + /* "View.MemoryView":145 + * + * idx = 0 + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + __pyx_t_7 = 0; + __pyx_t_3 = ((PyObject *)__pyx_v_shape); __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; + for (;;) { + if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_8 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_8); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_8 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF(__pyx_v_dim); + __pyx_v_dim = __pyx_t_8; + __pyx_t_8 = 0; + __pyx_v_idx = __pyx_t_7; + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":146 + * idx = 0 + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * + */ + __pyx_t_8 = PyObject_RichCompare(__pyx_v_dim, __pyx_int_0, Py_LE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (__pyx_t_6) { + + /* "View.MemoryView":147 + * for idx, dim in enumerate(shape): + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< + * + * self._shape[idx] = dim + */ + __pyx_t_8 = PyInt_FromLong(__pyx_v_idx); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_dim); + PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_dim); + __Pyx_GIVEREF(__pyx_v_dim); + __pyx_t_8 = 0; + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_52), ((PyObject *)__pyx_t_9)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":149 + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * + * self._shape[idx] = dim # <<<<<<<<<<<<<< + * idx += 1 + * + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_dim); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_t_10; + + /* "View.MemoryView":150 + * + * self._shape[idx] = dim + * idx += 1 # <<<<<<<<<<<<<< + * + * if mode not in ("fortran", "c"): + */ + __pyx_v_idx = (__pyx_v_idx + 1); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":152 + * idx += 1 + * + * if mode not in ("fortran", "c"): # <<<<<<<<<<<<<< + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + * + */ + __Pyx_INCREF(__pyx_v_mode); + __pyx_t_3 = __pyx_v_mode; + __pyx_t_8 = PyObject_RichCompare(__pyx_t_3, ((PyObject *)__pyx_n_s__fortran), Py_NE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (((int)__pyx_t_6)) { + __pyx_t_8 = PyObject_RichCompare(__pyx_t_3, ((PyObject *)__pyx_n_s__c), Py_NE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_5 = ((int)__pyx_t_2); + } else { + __pyx_t_5 = ((int)__pyx_t_6); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = (__pyx_t_5 != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":153 + * + * if mode not in ("fortran", "c"): + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< + * + * cdef char order + */ + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_53), __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":156 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = 'F' + * else: + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_mode, ((PyObject *)__pyx_n_s__fortran), Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + + /* "View.MemoryView":157 + * cdef char order + * if mode == 'fortran': + * order = 'F' # <<<<<<<<<<<<<< + * else: + * order = 'C' + */ + __pyx_v_order = 'F'; + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":159 + * order = 'F' + * else: + * order = 'C' # <<<<<<<<<<<<<< + * + * self.len = fill_contig_strides_array(self._shape, self._strides, + */ + __pyx_v_order = 'C'; + } + __pyx_L11:; + + /* "View.MemoryView":161 + * order = 'C' + * + * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< + * itemsize, self.ndim, order) + * + */ + __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); + + /* "View.MemoryView":164 + * itemsize, self.ndim, order) + * + * decode = getattr(mode, 'decode', None) # <<<<<<<<<<<<<< + * if decode: + * mode = decode('ASCII') + */ + __pyx_t_3 = __Pyx_GetAttr3(__pyx_v_mode, ((PyObject *)__pyx_n_s__decode), Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_decode = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":165 + * + * decode = getattr(mode, 'decode', None) + * if decode: # <<<<<<<<<<<<<< + * mode = decode('ASCII') + * self.mode = mode + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_decode); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":166 + * decode = getattr(mode, 'decode', None) + * if decode: + * mode = decode('ASCII') # <<<<<<<<<<<<<< + * self.mode = mode + * + */ + __pyx_t_3 = PyObject_Call(__pyx_v_decode, ((PyObject *)__pyx_k_tuple_54), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_mode); + __pyx_v_mode = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":167 + * if decode: + * mode = decode('ASCII') + * self.mode = mode # <<<<<<<<<<<<<< + * + * self.free_data = allocate_buffer + */ + if (!(likely(PyUnicode_CheckExact(__pyx_v_mode))||((__pyx_v_mode) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected unicode, got %.200s", Py_TYPE(__pyx_v_mode)->tp_name), 0))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_mode); + __Pyx_GIVEREF(__pyx_v_mode); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(((PyObject *)__pyx_v_self->mode)); + __pyx_v_self->mode = ((PyObject*)__pyx_v_mode); + + /* "View.MemoryView":169 + * self.mode = mode + * + * self.free_data = allocate_buffer # <<<<<<<<<<<<<< + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + */ + __pyx_v_self->free_data = __pyx_v_allocate_buffer; + + /* "View.MemoryView":170 + * + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< + * if allocate_buffer: + * self.data = malloc(self.len) + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_format, ((PyObject *)__pyx_n_b__O), Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_6; + + /* "View.MemoryView":171 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * self.data = malloc(self.len) + * if not self.data: + */ + __pyx_t_6 = (__pyx_v_allocate_buffer != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":172 + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + * self.data = malloc(self.len) # <<<<<<<<<<<<<< + * if not self.data: + * raise MemoryError("unable to allocate array data.") + */ + __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); + + /* "View.MemoryView":173 + * if allocate_buffer: + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ + __pyx_t_6 = ((!(__pyx_v_self->data != 0)) != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":174 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_56), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":176 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ + __pyx_t_6 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":177 + * + * if self.dtype_is_object: + * p = self.data # <<<<<<<<<<<<<< + * for i in range(self.len / itemsize): + * p[i] = Py_None + */ + __pyx_v_p = ((PyObject **)__pyx_v_self->data); + + /* "View.MemoryView":178 + * if self.dtype_is_object: + * p = self.data + * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< + * p[i] = Py_None + * Py_INCREF(Py_None) + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = (__pyx_v_self->len / __pyx_v_itemsize); + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_1; __pyx_t_10+=1) { + __pyx_v_i = __pyx_t_10; + + /* "View.MemoryView":179 + * p = self.data + * for i in range(self.len / itemsize): + * p[i] = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + (__pyx_v_p[__pyx_v_i]) = Py_None; + + /* "View.MemoryView":180 + * for i in range(self.len / itemsize): + * p[i] = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + Py_INCREF(Py_None); + } + goto __pyx_L15; + } + __pyx_L15:; + goto __pyx_L13; + } + __pyx_L13:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_encode); + __Pyx_XDECREF(__pyx_v_dim); + __Pyx_XDECREF(__pyx_v_decode); + __Pyx_XDECREF(__pyx_v_format); + __Pyx_XDECREF(__pyx_v_mode); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":183 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == b"c": + */ + +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_bufmode; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + Py_ssize_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":184 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 # <<<<<<<<<<<<<< + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = -1; + + /* "View.MemoryView":185 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == b"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": + */ + __pyx_t_1 = (__Pyx_PyUnicode_Equals(((PyObject *)__pyx_v_self->mode), ((PyObject *)__pyx_n_b__c), Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":186 + * cdef int bufmode = -1 + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + + /* "View.MemoryView":187 + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ + __pyx_t_2 = (__Pyx_PyUnicode_Equals(((PyObject *)__pyx_v_self->mode), ((PyObject *)__pyx_n_b__fortran), Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":188 + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + */ + __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":189 + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ + __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":190 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_58), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":191 + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data # <<<<<<<<<<<<<< + * info.len = self.len + * info.ndim = self.ndim + */ + __pyx_t_4 = __pyx_v_self->data; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":192 + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + * info.len = self.len # <<<<<<<<<<<<<< + * info.ndim = self.ndim + * info.shape = self._shape + */ + __pyx_t_5 = __pyx_v_self->len; + __pyx_v_info->len = __pyx_t_5; + + /* "View.MemoryView":193 + * info.buf = self.data + * info.len = self.len + * info.ndim = self.ndim # <<<<<<<<<<<<<< + * info.shape = self._shape + * info.strides = self._strides + */ + __pyx_t_6 = __pyx_v_self->ndim; + __pyx_v_info->ndim = __pyx_t_6; + + /* "View.MemoryView":194 + * info.len = self.len + * info.ndim = self.ndim + * info.shape = self._shape # <<<<<<<<<<<<<< + * info.strides = self._strides + * info.suboffsets = NULL + */ + __pyx_t_7 = __pyx_v_self->_shape; + __pyx_v_info->shape = __pyx_t_7; + + /* "View.MemoryView":195 + * info.ndim = self.ndim + * info.shape = self._shape + * info.strides = self._strides # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = self.itemsize + */ + __pyx_t_7 = __pyx_v_self->_strides; + __pyx_v_info->strides = __pyx_t_7; + + /* "View.MemoryView":196 + * info.shape = self._shape + * info.strides = self._strides + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = self.itemsize + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; + + /* "View.MemoryView":197 + * info.strides = self._strides + * info.suboffsets = NULL + * info.itemsize = self.itemsize # <<<<<<<<<<<<<< + * info.readonly = 0 + * + */ + __pyx_t_5 = __pyx_v_self->itemsize; + __pyx_v_info->itemsize = __pyx_t_5; + + /* "View.MemoryView":198 + * info.suboffsets = NULL + * info.itemsize = self.itemsize + * info.readonly = 0 # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":200 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":201 + * + * if flags & PyBUF_FORMAT: + * info.format = self.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_4 = __pyx_v_self->format; + __pyx_v_info->format = __pyx_t_4; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":203 + * info.format = self.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.obj = self + */ + __pyx_v_info->format = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":205 + * info.format = NULL + * + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_array_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":209 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":210 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ + __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":211 + * def __dealloc__(array self): + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) # <<<<<<<<<<<<<< + * elif self.free_data: + * if self.dtype_is_object: + */ + __pyx_v_self->callback_free_data(__pyx_v_self->data); + goto __pyx_L3; + } + + /* "View.MemoryView":212 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ + __pyx_t_1 = (__pyx_v_self->free_data != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":213 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":215 + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) # <<<<<<<<<<<<<< + * free(self.data) + * + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":216 + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + * free(self.data) # <<<<<<<<<<<<<< + * + * free(self._strides) + */ + free(__pyx_v_self->data); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":218 + * free(self.data) + * + * free(self._strides) # <<<<<<<<<<<<<< + * free(self._shape) + * + */ + free(__pyx_v_self->_strides); + + /* "View.MemoryView":219 + * + * free(self._strides) + * free(self._shape) # <<<<<<<<<<<<<< + * + * property memview: + */ + free(__pyx_v_self->_shape); + + __Pyx_RefNannyFinishContext(); +} + +/* Python wrapper */ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = get_memview_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":223 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":225 + * def __get__(self): + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< + * return memoryview(self, flags, self.dtype_is_object) + * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":226 + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromLong(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":229 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":230 + * + * def __getattr__(self, attr): + * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * + * def __getitem__(self, item): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":232 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":233 + * + * def __getitem__(self, item): + * return self.memview[item] # <<<<<<<<<<<<<< + * + * def __setitem__(self, item, value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (!__pyx_t_2) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":235 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "View.MemoryView":236 + * + * def __setitem__(self, item, value): + * self.memview[item] = value # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":240 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + +static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { + struct __pyx_array_obj *__pyx_v_result = 0; + struct __pyx_array_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("array_cwrapper", 0); + + /* "View.MemoryView":244 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":245 + * + * if buf == NULL: + * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_shape)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 2, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + PyTuple_SET_ITEM(__pyx_t_5, 3, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":247 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_shape)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + PyTuple_SET_ITEM(__pyx_t_2, 3, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + + /* "View.MemoryView":248 + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) # <<<<<<<<<<<<<< + * result.data = buf + * + */ + __pyx_t_5 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 248; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__allocate_buffer), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":249 + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) + * result.data = buf # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->data = __pyx_v_buf; + } + __pyx_L3:; + + /* "View.MemoryView":251 + * result.data = buf + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + __pyx_r = ((struct __pyx_array_obj *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_name = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__name,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__name)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_name = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":277 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "View.MemoryView":278 + * cdef object name + * def __init__(self, name): + * self.name = name # <<<<<<<<<<<<<< + * def __repr__(self): + * return self.name + */ + __Pyx_INCREF(__pyx_v_name); + __Pyx_GIVEREF(__pyx_v_name); + __Pyx_GOTREF(__pyx_v_self->name); + __Pyx_DECREF(__pyx_v_self->name); + __pyx_v_self->name = __pyx_v_name; + + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":279 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":280 + * self.name = name + * def __repr__(self): + * return self.name # <<<<<<<<<<<<<< + * + * cdef generic = Enum("") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->name); + __pyx_r = __pyx_v_self->name; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":294 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + +static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { + Py_intptr_t __pyx_v_aligned_p; + size_t __pyx_v_offset; + void *__pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":296 + * cdef void *align_pointer(void *memory, size_t alignment) nogil: + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< + * cdef size_t offset + * + */ + __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + + /* "View.MemoryView":300 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":302 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + __pyx_t_1 = ((__pyx_v_offset > 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":303 + * + * if offset > 0: + * aligned_p += alignment - offset # <<<<<<<<<<<<<< + * + * return aligned_p + */ + __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":305 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview') + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_obj = 0; + int __pyx_v_flags; + int __pyx_v_dtype_is_object; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__obj,&__pyx_n_s__flags,&__pyx_n_s__dtype_is_object,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__obj)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__flags)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dtype_is_object); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_obj = values[0]; + __pyx_v_flags = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[2]) { + __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "View.MemoryView":323 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + __pyx_v_dtype_is_object = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_memoryview_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "View.MemoryView":324 + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj # <<<<<<<<<<<<<< + * self.flags = flags + * if type(self) is memoryview or obj is not None: + */ + __Pyx_INCREF(__pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __Pyx_GOTREF(__pyx_v_self->obj); + __Pyx_DECREF(__pyx_v_self->obj); + __pyx_v_self->obj = __pyx_v_obj; + + /* "View.MemoryView":325 + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj + * self.flags = flags # <<<<<<<<<<<<<< + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + */ + __pyx_v_self->flags = __pyx_v_flags; + + /* "View.MemoryView":326 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ + __pyx_t_1 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type))); + if (!(__pyx_t_1 != 0)) { + __pyx_t_2 = (__pyx_v_obj != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + } else { + __pyx_t_3 = (__pyx_t_1 != 0); + } + if (__pyx_t_3) { + + /* "View.MemoryView":327 + * self.flags = flags + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + */ + __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":328 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_t_3 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":329 + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; + + /* "View.MemoryView":330 + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * self.lock = PyThread_allocate_lock() + */ + Py_INCREF(Py_None); + goto __pyx_L4; + } + __pyx_L4:; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":332 + * Py_INCREF(Py_None) + * + * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< + * if self.lock == NULL: + * raise MemoryError + */ + __pyx_v_self->lock = PyThread_allocate_lock(); + + /* "View.MemoryView":333 + * + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + __pyx_t_3 = ((__pyx_v_self->lock == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":334 + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":336 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = self.view.format == b'O' + * else: + */ + __pyx_t_3 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":337 + * + * if flags & PyBUF_FORMAT: + * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< + * else: + * self.dtype_is_object = dtype_is_object + */ + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_6 = PyObject_RichCompare(((PyObject *)__pyx_t_5), ((PyObject *)__pyx_n_b__O), Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":339 + * self.dtype_is_object = self.view.format == b'O' + * else: + * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + */ + __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; + } + __pyx_L6:; + + /* "View.MemoryView":341 + * self.dtype_is_object = dtype_is_object + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL + */ + __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); + + /* "View.MemoryView":343 + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(memoryview self): + */ + __pyx_v_self->typeinfo = NULL; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":345 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":346 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< + * __Pyx_ReleaseBuffer(&self.view) + * + */ + __pyx_t_1 = (__pyx_v_self->obj != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":347 + * def __dealloc__(memoryview self): + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< + * + * if self.lock != NULL: + */ + __Pyx_ReleaseBuffer((&__pyx_v_self->view)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":349 + * __Pyx_ReleaseBuffer(&self.view) + * + * if self.lock != NULL: # <<<<<<<<<<<<<< + * PyThread_free_lock(self.lock) + * + */ + __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":350 + * + * if self.lock != NULL: + * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + */ + PyThread_free_lock(__pyx_v_self->lock); + goto __pyx_L4; + } + __pyx_L4:; + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":352 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + Py_ssize_t __pyx_v_dim; + char *__pyx_v_itemp; + PyObject *__pyx_v_idx = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_item_pointer", 0); + + /* "View.MemoryView":354 + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< + * + * for dim, idx in enumerate(index): + */ + __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); + + /* "View.MemoryView":356 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + __pyx_t_1 = 0; + if (PyList_CheckExact(__pyx_v_index) || PyTuple_CheckExact(__pyx_v_index)) { + __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; + } + for (;;) { + if (!__pyx_t_4 && PyList_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_4 && PyTuple_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF(__pyx_v_idx); + __pyx_v_idx = __pyx_t_5; + __pyx_t_5 = 0; + __pyx_v_dim = __pyx_t_1; + __pyx_t_1 = (__pyx_t_1 + 1); + + /* "View.MemoryView":357 + * + * for dim, idx in enumerate(index): + * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< + * + * return itemp + */ + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_7; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":359 + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + * return itemp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_itemp; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":362 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_indices = NULL; + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *(*__pyx_t_7)(PyObject *); + char *__pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":363 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":364 + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: + * return self # <<<<<<<<<<<<<< + * + * have_slices, indices = _unellipsify(index, self.view.ndim) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __pyx_r = ((PyObject *)__pyx_v_self); + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":366 + * return self + * + * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * cdef char *itemp + */ + __pyx_t_3 = ((PyObject *)_unellipsify(__pyx_v_index, __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (likely(PyTuple_CheckExact(__pyx_t_3))) { + PyObject* sequence = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_6 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = Py_TYPE(__pyx_t_6)->tp_iternext; + index = 0; __pyx_t_4 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_4)) goto __pyx_L4_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + index = 1; __pyx_t_5 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_5)) goto __pyx_L4_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_6), 2) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = NULL; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L5_unpacking_done; + __pyx_L4_unpacking_failed:; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_7 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L5_unpacking_done:; + } + __pyx_v_have_slices = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; + + /* "View.MemoryView":369 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":370 + * cdef char *itemp + * if have_slices: + * return memview_slice(self, indices) # <<<<<<<<<<<<<< + * else: + * itemp = self.get_item_pointer(indices) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":372 + * return memview_slice(self, indices) + * else: + * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< + * return self.convert_item_to_object(itemp) + * + */ + __pyx_t_8 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_8 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_8; + + /* "View.MemoryView":373 + * else: + * itemp = self.get_item_pointer(indices) + * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< + * + * def __setitem__(memoryview self, object index, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + __pyx_L6:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":375 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_obj = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *(*__pyx_t_5)(PyObject *); + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_INCREF(__pyx_v_index); + + /* "View.MemoryView":376 + * + * def __setitem__(memoryview self, object index, object value): + * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * if have_slices: + */ + __pyx_t_1 = ((PyObject *)_unellipsify(__pyx_v_index, __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (likely(PyTuple_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_3 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = NULL; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L4_unpacking_done:; + } + __pyx_v_have_slices = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_v_index); + __pyx_v_index = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":378 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":379 + * + * if have_slices: + * obj = self.is_slice(value) # <<<<<<<<<<<<<< + * if obj: + * self.setitem_slice_assignment(self[index], obj) + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_obj = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":380 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":381 + * obj = self.is_slice(value) + * if obj: + * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< + * else: + * self.setitem_slice_assign_scalar(self[index], value) + */ + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (!__pyx_t_1) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":383 + * self.setitem_slice_assignment(self[index], obj) + * else: + * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< + * else: + * self.setitem_indexed(index, value) + */ + __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (!__pyx_t_3) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":385 + * self.setitem_slice_assign_scalar(self[index], value) + * else: + * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< + * + * cdef is_slice(self, obj): + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L5:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":387 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_slice", 0); + __Pyx_INCREF(__pyx_v_obj); + + /* "View.MemoryView":388 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type)); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":389 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + { + __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + /*try:*/ { + + /* "View.MemoryView":390 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_6 = PyInt_FromLong((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":391 + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * except TypeError: + * return None + */ + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_7 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_v_obj); + __pyx_v_obj = __pyx_t_7; + __pyx_t_7 = 0; + } + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L11_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":392 + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + * except TypeError: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":393 + * self.dtype_is_object) + * except TypeError: + * return None # <<<<<<<<<<<<<< + * + * return obj + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L7_except_return; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L5_exception_handled; + } + __pyx_L6_except_error:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L1_error; + __pyx_L7_except_return:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L0; + __pyx_L5_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + __pyx_L11_try_end:; + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":395 + * return None + * + * return obj # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assignment(self, dst, src): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_obj); + __pyx_r = __pyx_v_obj; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":397 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { + __Pyx_memviewslice __pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_src_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); + + /* "View.MemoryView":401 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":402 + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< + * src.ndim, dst.ndim, self.dtype_is_object) + * + */ + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":403 + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s__ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s__ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":405 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { + int __pyx_v_array[128]; + void *__pyx_v_tmp; + void *__pyx_v_item; + __Pyx_memviewslice __pyx_v_tmp_slice; + __Pyx_memviewslice *__pyx_v_dst_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); + + /* "View.MemoryView":407 + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + * cdef int array[128] + * cdef void *tmp = NULL # <<<<<<<<<<<<<< + * cdef void *item + * + */ + __pyx_v_tmp = NULL; + + /* "View.MemoryView":411 + * + * cdef __Pyx_memviewslice tmp_slice, *dst_slice + * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< + * + * if self.view.itemsize > sizeof(array): + */ + __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); + + /* "View.MemoryView":413 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: + */ + __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":414 + * + * if self.view.itemsize > sizeof(array): + * tmp = malloc(self.view.itemsize) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError + */ + __pyx_v_tmp = malloc(__pyx_v_self->view.itemsize); + + /* "View.MemoryView":415 + * if self.view.itemsize > sizeof(array): + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":416 + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * item = tmp + * else: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":417 + * if tmp == NULL: + * raise MemoryError + * item = tmp # <<<<<<<<<<<<<< + * else: + * item = array + */ + __pyx_v_item = __pyx_v_tmp; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":419 + * item = tmp + * else: + * item = array # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_v_item = ((void *)__pyx_v_array); + } + __pyx_L3:; + + /* "View.MemoryView":421 + * item = array + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":422 + * + * if self.dtype_is_object: + * ( item)[0] = value # <<<<<<<<<<<<<< + * else: + * try: + */ + (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":424 + * ( item)[0] = value + * else: + * try: # <<<<<<<<<<<<<< + * self.assign_item_from_object( item, value) + * except: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":425 + * else: + * try: + * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< + * except: + * free(tmp) + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L13_try_end; + __pyx_L6_error:; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":426 + * try: + * self.assign_item_from_object( item, value) + * except: # <<<<<<<<<<<<<< + * free(tmp) + * raise + */ + /*except:*/ { + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 426; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":427 + * self.assign_item_from_object( item, value) + * except: + * free(tmp) # <<<<<<<<<<<<<< + * raise + * + */ + free(__pyx_v_tmp); + + /* "View.MemoryView":428 + * except: + * free(tmp) + * raise # <<<<<<<<<<<<<< + * + * + */ + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_7); + __Pyx_ErrRestore(__pyx_t_5, __pyx_t_6, __pyx_t_7); + __pyx_t_5 = 0; __pyx_t_6 = 0; __pyx_t_7 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 428; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L7_exception_handled; + } + __pyx_L8_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L7_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L13_try_end:; + } + } + __pyx_L5:; + + /* "View.MemoryView":432 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":433 + * + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + */ + __pyx_t_7 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":435 + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) # <<<<<<<<<<<<<< + * free(tmp) + * + */ + __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); + + /* "View.MemoryView":436 + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + * free(tmp) # <<<<<<<<<<<<<< + * + * cdef setitem_indexed(self, index, value): + */ + free(__pyx_v_tmp); + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":438 + * free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_indexed", 0); + + /* "View.MemoryView":439 + * + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< + * self.assign_item_from_object(itemp, value) + * + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_1; + + /* "View.MemoryView":440 + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":442 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_v_struct = NULL; + PyObject *__pyx_v_bytesitem = 0; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":445 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef bytes bytesitem + * + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__struct), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":448 + * cdef bytes bytesitem + * + * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< + * try: + * result = struct.unpack(self.view.format, bytesitem) + */ + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":449 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":450 + * bytesitem = itemp[:self.view.itemsize] + * try: + * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< + * except struct.error: + * raise ValueError("Unable to convert item to object") + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__unpack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __Pyx_INCREF(((PyObject *)__pyx_v_bytesitem)); + PyTuple_SET_ITEM(__pyx_t_6, 1, ((PyObject *)__pyx_v_bytesitem)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_bytesitem)); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + } + /*else:*/ { + + /* "View.MemoryView":454 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + __pyx_t_7 = strlen(__pyx_v_self->view.format); + __pyx_t_8 = ((__pyx_t_7 == 1) != 0); + if (__pyx_t_8) { + + /* "View.MemoryView":455 + * else: + * if len(self.view.format) == 1: + * return result[0] # <<<<<<<<<<<<<< + * return result + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_result, 0, sizeof(long), PyInt_FromLong, 0, 0, 0); if (!__pyx_t_5) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L6_except_return; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":456 + * if len(self.view.format) == 1: + * return result[0] + * return result # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L6_except_return; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L10_try_end; + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":451 + * try: + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: # <<<<<<<<<<<<<< + * raise ValueError("Unable to convert item to object") + * else: + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__error); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_1) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_1); + + /* "View.MemoryView":452 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_t_10 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_60), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L4_exception_handled; + } + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L6_except_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + __pyx_L4_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L10_try_end:; + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesitem); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":458 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_v_struct = NULL; + char __pyx_v_c; + PyObject *__pyx_v_bytesvalue = 0; + Py_ssize_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + char *__pyx_t_10; + char *__pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":461 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef char c + * cdef bytes bytesvalue + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__struct), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":466 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + __pyx_t_2 = PyTuple_Check(__pyx_v_value); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":467 + * + * if isinstance(value, tuple): + * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< + * else: + * bytesvalue = struct.pack(self.view.format, value) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = 0; + __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_6 = PyNumber_Add(((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":469 + * bytesvalue = struct.pack(self.view.format, *value) + * else: + * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< + * + * for i, c in enumerate(bytesvalue): + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__pack); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_6)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_6)); + __Pyx_INCREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + __pyx_t_6 = 0; + __pyx_t_6 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_6)->tp_name), 0))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":471 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = 0; + if (unlikely(((PyObject *)__pyx_v_bytesvalue) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_INCREF(((PyObject *)__pyx_v_bytesvalue)); + __pyx_t_8 = __pyx_v_bytesvalue; + __pyx_t_10 = PyBytes_AS_STRING(__pyx_t_8); + __pyx_t_11 = (__pyx_t_10 + PyBytes_GET_SIZE(__pyx_t_8)); + for (__pyx_t_12 = __pyx_t_10; __pyx_t_12 < __pyx_t_11; __pyx_t_12++) { + __pyx_t_9 = __pyx_t_12; + __pyx_v_c = (__pyx_t_9[0]); + + /* "View.MemoryView":472 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + __pyx_v_i = __pyx_t_7; + + /* "View.MemoryView":471 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":472 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; + } + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(((PyObject *)__pyx_t_8)); + __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":475 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + char *__pyx_t_3; + void *__pyx_t_4; + int __pyx_t_5; + Py_ssize_t __pyx_t_6; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":476 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":477 + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape # <<<<<<<<<<<<<< + * else: + * info.shape = NULL + */ + __pyx_t_2 = __pyx_v_self->view.shape; + __pyx_v_info->shape = __pyx_t_2; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":479 + * info.shape = self.view.shape + * else: + * info.shape = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_STRIDES: + */ + __pyx_v_info->shape = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":481 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":482 + * + * if flags & PyBUF_STRIDES: + * info.strides = self.view.strides # <<<<<<<<<<<<<< + * else: + * info.strides = NULL + */ + __pyx_t_2 = __pyx_v_self->view.strides; + __pyx_v_info->strides = __pyx_t_2; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":484 + * info.strides = self.view.strides + * else: + * info.strides = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_INDIRECT: + */ + __pyx_v_info->strides = NULL; + } + __pyx_L4:; + + /* "View.MemoryView":486 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":487 + * + * if flags & PyBUF_INDIRECT: + * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< + * else: + * info.suboffsets = NULL + */ + __pyx_t_2 = __pyx_v_self->view.suboffsets; + __pyx_v_info->suboffsets = __pyx_t_2; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":489 + * info.suboffsets = self.view.suboffsets + * else: + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->suboffsets = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":491 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":492 + * + * if flags & PyBUF_FORMAT: + * info.format = self.view.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_3 = __pyx_v_self->view.format; + __pyx_v_info->format = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":494 + * info.format = self.view.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.buf = self.view.buf + */ + __pyx_v_info->format = NULL; + } + __pyx_L6:; + + /* "View.MemoryView":496 + * info.format = NULL + * + * info.buf = self.view.buf # <<<<<<<<<<<<<< + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + */ + __pyx_t_4 = __pyx_v_self->view.buf; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":497 + * + * info.buf = self.view.buf + * info.ndim = self.view.ndim # <<<<<<<<<<<<<< + * info.itemsize = self.view.itemsize + * info.len = self.view.len + */ + __pyx_t_5 = __pyx_v_self->view.ndim; + __pyx_v_info->ndim = __pyx_t_5; + + /* "View.MemoryView":498 + * info.buf = self.view.buf + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< + * info.len = self.view.len + * info.readonly = 0 + */ + __pyx_t_6 = __pyx_v_self->view.itemsize; + __pyx_v_info->itemsize = __pyx_t_6; + + /* "View.MemoryView":499 + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + * info.len = self.view.len # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.obj = self + */ + __pyx_t_6 = __pyx_v_self->view.len; + __pyx_v_info->len = __pyx_t_6; + + /* "View.MemoryView":500 + * info.itemsize = self.view.itemsize + * info.len = self.view.len + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.obj = self + * + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":501 + * info.len = self.view.len + * info.readonly = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + __pyx_r = 0; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":508 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":509 + * @cname('__pyx_memoryview_transpose') + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< + * transpose_memslice(&result.from_slice) + * return result + */ + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":510 + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":511 + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + * return result # <<<<<<<<<<<<<< + * + * property base: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":515 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":516 + * @cname('__pyx_memoryview__get__base') + * def __get__(self): + * return self.obj # <<<<<<<<<<<<<< + * + * property shape: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->obj); + __pyx_r = __pyx_v_self->obj; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":520 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":521 + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property strides: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_v_self->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->view.shape[__pyx_v_i])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __pyx_t_4 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_1))); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_r = ((PyObject *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":525 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":526 + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":528 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_62), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":530 + * raise ValueError("Buffer view does not expose strides") + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property suboffsets: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.strides[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_2))); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_5); + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":534 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":535 + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return [-1] * self.view.ndim + * + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":536 + * def __get__(self): + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(1 * ((__pyx_v_self->view.ndim<0) ? 0:__pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_self->view.ndim; __pyx_temp++) { + __Pyx_INCREF(__pyx_int_neg_1); + PyList_SET_ITEM(__pyx_t_2, __pyx_temp, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + } + } + __pyx_r = ((PyObject *)__pyx_t_2); + __pyx_t_2 = 0; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":538 + * return [-1] * self.view.ndim + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property ndim: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.suboffsets[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_2))); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_5); + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":542 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":543 + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): + * return self.view.ndim # <<<<<<<<<<<<<< + * + * property itemsize: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromLong(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":547 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":548 + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): + * return self.view.itemsize # <<<<<<<<<<<<<< + * + * property nbytes: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":552 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":553 + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): + * return self.size * self.view.itemsize # <<<<<<<<<<<<<< + * + * property size: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":557 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":558 + * @cname('__pyx_memoryview_get_size') + * def __get__(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + __pyx_t_1 = (__pyx_v_self->_size == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":559 + * def __get__(self): + * if self._size is None: + * result = 1 # <<<<<<<<<<<<<< + * + * for length in self.shape: + */ + __Pyx_INCREF(__pyx_int_1); + __pyx_v_result = __pyx_int_1; + + /* "View.MemoryView":561 + * result = 1 + * + * for length in self.shape: # <<<<<<<<<<<<<< + * result *= length + * + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyList_CheckExact(__pyx_t_3) || PyTuple_CheckExact(__pyx_t_3)) { + __pyx_t_4 = __pyx_t_3; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_3 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_3)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF(__pyx_v_length); + __pyx_v_length = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":562 + * + * for length in self.shape: + * result *= length # <<<<<<<<<<<<<< + * + * self._size = result + */ + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_result); + __pyx_v_result = __pyx_t_3; + __pyx_t_3 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "View.MemoryView":564 + * result *= length + * + * self._size = result # <<<<<<<<<<<<<< + * + * return self._size + */ + __Pyx_INCREF(__pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __Pyx_GOTREF(__pyx_v_self->_size); + __Pyx_DECREF(__pyx_v_self->_size); + __pyx_v_self->_size = __pyx_v_result; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":566 + * self._size = result + * + * return self._size # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->_size); + __pyx_r = __pyx_v_self->_size; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":568 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__len__", 0); + + /* "View.MemoryView":569 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":570 + * def __len__(self): + * if self.view.ndim >= 1: + * return self.view.shape[0] # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_r = (__pyx_v_self->view.shape[0]); + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":572 + * return self.view.shape[0] + * + * return 0 # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":574 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":575 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s____class__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s____name__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":576 + * def __repr__(self): + * return "" % (self.base.__class__.__name__, + * id(self)) # <<<<<<<<<<<<<< + * + * def __str__(self): + */ + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __pyx_t_3 = PyObject_Call(__pyx_builtin_id, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_63), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":578 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__str__", 0); + + /* "View.MemoryView":579 + * + * def __str__(self): + * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s____class__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s____name__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_64), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":582 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_c_contig", 0); + + /* "View.MemoryView":584 + * def is_c_contig(self): + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":585 + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< + * + * def is_f_contig(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":587 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_f_contig", 0); + + /* "View.MemoryView":589 + * def is_f_contig(self): + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":590 + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< + * + * def copy(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":592 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_mslice; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "View.MemoryView":594 + * def copy(self): + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &mslice) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); + + /* "View.MemoryView":596 + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + * + * slice_copy(self, &mslice) # <<<<<<<<<<<<<< + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); + + /* "View.MemoryView":600 + * self.view.itemsize, + * flags|PyBUF_C_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * + * return memoryview_copy_from_slice(self, &mslice) + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k__c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":602 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< + * + * def copy_fortran(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":604 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy_fortran", 0); + + /* "View.MemoryView":606 + * def copy_fortran(self): + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &src) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); + + /* "View.MemoryView":608 + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + * + * slice_copy(self, &src) # <<<<<<<<<<<<<< + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); + + /* "View.MemoryView":612 + * self.view.itemsize, + * flags|PyBUF_F_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * + * return memoryview_copy_from_slice(self, &dst) + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k__fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dst = __pyx_t_1; + + /* "View.MemoryView":614 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":618 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + +static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { + struct __pyx_memoryview_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); + + /* "View.MemoryView":619 + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< + * result.typeinfo = typeinfo + * return result + */ + __pyx_t_1 = PyInt_FromLong(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); + __Pyx_GIVEREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":620 + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_v_result->typeinfo = __pyx_v_typeinfo; + + /* "View.MemoryView":621 + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_check') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":624 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("memoryview_check", 0); + + /* "View.MemoryView":625 + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): + * return isinstance(o, memoryview) # <<<<<<<<<<<<<< + * + * cdef tuple _unellipsify(object index, int ndim): + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type)); + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":627 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + +static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { + PyObject *__pyx_v_tup = NULL; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_have_slices = NULL; + int __pyx_v_seen_ellipsis; + CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_item = NULL; + PyObject *__pyx_v_nslices = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + Py_ssize_t __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_unellipsify", 0); + + /* "View.MemoryView":632 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + __pyx_t_1 = PyTuple_Check(__pyx_v_index); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":633 + * """ + * if not isinstance(index, tuple): + * tup = (index,) # <<<<<<<<<<<<<< + * else: + * tup = index + */ + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 633; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_index); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); + __Pyx_GIVEREF(__pyx_v_index); + __pyx_v_tup = ((PyObject *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":635 + * tup = (index,) + * else: + * tup = index # <<<<<<<<<<<<<< + * + * result = [] + */ + __Pyx_INCREF(__pyx_v_index); + __pyx_v_tup = __pyx_v_index; + } + __pyx_L3:; + + /* "View.MemoryView":637 + * tup = index + * + * result = [] # <<<<<<<<<<<<<< + * have_slices = False + * seen_ellipsis = False + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_result = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":638 + * + * result = [] + * have_slices = False # <<<<<<<<<<<<<< + * seen_ellipsis = False + * for idx, item in enumerate(tup): + */ + __pyx_t_3 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_have_slices = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":639 + * result = [] + * have_slices = False + * seen_ellipsis = False # <<<<<<<<<<<<<< + * for idx, item in enumerate(tup): + * if item is Ellipsis: + */ + __pyx_v_seen_ellipsis = 0; + + /* "View.MemoryView":640 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_3 = __pyx_int_0; + if (PyList_CheckExact(__pyx_v_tup) || PyTuple_CheckExact(__pyx_v_tup)) { + __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_7 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_7)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_XDECREF(__pyx_v_item); + __pyx_v_item = __pyx_t_7; + __pyx_t_7 = 0; + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_v_idx); + __pyx_v_idx = __pyx_t_3; + __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_t_7; + __pyx_t_7 = 0; + + /* "View.MemoryView":641 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ + __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":642 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ + __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":643 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_result), __pyx_n_s__extend); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_65), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_9) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_9) + 1))); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_9) + 1); __pyx_temp++) { + __Pyx_INCREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_10, __pyx_temp, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + } + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_10)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_10)); + __pyx_t_10 = 0; + __pyx_t_10 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + + /* "View.MemoryView":644 + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True # <<<<<<<<<<<<<< + * else: + * result.append(slice(None)) + */ + __pyx_v_seen_ellipsis = 1; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":646 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_t_10 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_66), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_result, __pyx_t_10); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + } + __pyx_L7:; + + /* "View.MemoryView":647 + * else: + * result.append(slice(None)) + * have_slices = True # <<<<<<<<<<<<<< + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + */ + __pyx_t_10 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_v_have_slices); + __pyx_v_have_slices = __pyx_t_10; + __pyx_t_10 = 0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":649 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ + __pyx_t_1 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_1 = ((!(__Pyx_PyIndex_Check(__pyx_v_item) != 0)) != 0); + __pyx_t_12 = __pyx_t_1; + } else { + __pyx_t_12 = __pyx_t_2; + } + if (__pyx_t_12) { + + /* "View.MemoryView":650 + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< + * + * have_slices = have_slices or isinstance(item, slice) + */ + __pyx_t_10 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_67), ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_10)); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_10)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_10)); + __pyx_t_10 = 0; + __pyx_t_10 = PyObject_Call(__pyx_builtin_TypeError, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":652 + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< + * result.append(item) + * + */ + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_12) { + __pyx_t_12 = PySlice_Check(__pyx_v_item); + __pyx_t_10 = __Pyx_PyBool_FromLong(__pyx_t_12); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_8 = __pyx_t_10; + __pyx_t_10 = 0; + } else { + __Pyx_INCREF(__pyx_v_have_slices); + __pyx_t_8 = __pyx_v_have_slices; + } + __Pyx_DECREF(__pyx_v_have_slices); + __pyx_v_have_slices = __pyx_t_8; + __pyx_t_8 = 0; + + /* "View.MemoryView":653 + * + * have_slices = have_slices or isinstance(item, slice) + * result.append(item) # <<<<<<<<<<<<<< + * + * nslices = ndim - len(result) + */ + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":655 + * result.append(item) + * + * nslices = ndim - len(result) # <<<<<<<<<<<<<< + * if nslices: + * result.extend([slice(None)] * nslices) + */ + __pyx_t_5 = PyList_GET_SIZE(((PyObject *)__pyx_v_result)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_ndim - __pyx_t_5)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_nslices = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":656 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_nslices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_12) { + + /* "View.MemoryView":657 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_result), __pyx_n_s__extend); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_68), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyList_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_8, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + { PyObject* __pyx_temp = PyNumber_InPlaceMultiply(__pyx_t_8, __pyx_v_nslices); if (unlikely(!__pyx_temp)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_temp); + __Pyx_DECREF(__pyx_t_8); + __pyx_t_8 = __pyx_temp; + } + __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":659 + * result.extend([slice(None)] * nslices) + * + * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_12) { + __Pyx_INCREF(__pyx_v_nslices); + __pyx_t_8 = __pyx_v_nslices; + } else { + __Pyx_INCREF(__pyx_v_have_slices); + __pyx_t_8 = __pyx_v_have_slices; + } + __pyx_t_4 = ((PyObject *)PyList_AsTuple(__pyx_v_result)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_8 = 0; + __pyx_t_4 = 0; + __pyx_r = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = ((PyObject*)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_tup); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_item); + __Pyx_XDECREF(__pyx_v_nslices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":661 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + +static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); + + /* "View.MemoryView":663 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * cdef int i + * for i in range(ndim): # <<<<<<<<<<<<<< + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":664 + * cdef int i + * for i in range(ndim): + * if suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ + __pyx_t_3 = (((__pyx_v_suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":665 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_70), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":672 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { + int __pyx_v_new_ndim; + int __pyx_v_suboffset_dim; + int __pyx_v_dim; + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + __Pyx_memviewslice *__pyx_v_p_src; + struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; + __Pyx_memviewslice *__pyx_v_p_dst; + int *__pyx_v_p_suboffset_dim; + Py_ssize_t __pyx_v_start; + Py_ssize_t __pyx_v_stop; + Py_ssize_t __pyx_v_step; + int __pyx_v_have_start; + int __pyx_v_have_stop; + int __pyx_v_have_step; + PyObject *__pyx_v_index = NULL; + struct __pyx_memoryview_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + struct __pyx_memoryview_obj *__pyx_t_3; + char *__pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + PyObject *__pyx_t_12 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memview_slice", 0); + + /* "View.MemoryView":673 + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): + * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< + * cdef bint negative_step + * cdef __Pyx_memviewslice src, dst + */ + __pyx_v_new_ndim = 0; + __pyx_v_suboffset_dim = -1; + + /* "View.MemoryView":680 + * + * + * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< + * + * cdef _memoryviewslice memviewsliceobj + */ + memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); + + /* "View.MemoryView":684 + * cdef _memoryviewslice memviewsliceobj + * + * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 684; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #endif + + /* "View.MemoryView":686 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":687 + * + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview # <<<<<<<<<<<<<< + * p_src = &memviewsliceobj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(((PyObject *)__pyx_v_memview)); + __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview); + + /* "View.MemoryView":688 + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, &src) + */ + __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":690 + * p_src = &memviewsliceobj.from_slice + * else: + * slice_copy(memview, &src) # <<<<<<<<<<<<<< + * p_src = &src + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); + + /* "View.MemoryView":691 + * else: + * slice_copy(memview, &src) + * p_src = &src # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_src = (&__pyx_v_src); + } + __pyx_L3:; + + /* "View.MemoryView":697 + * + * + * dst.memview = p_src.memview # <<<<<<<<<<<<<< + * dst.data = p_src.data + * + */ + __pyx_t_3 = __pyx_v_p_src->memview; + __pyx_v_dst.memview = __pyx_t_3; + + /* "View.MemoryView":698 + * + * dst.memview = p_src.memview + * dst.data = p_src.data # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = __pyx_v_p_src->data; + __pyx_v_dst.data = __pyx_t_4; + + /* "View.MemoryView":703 + * + * + * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< + * cdef int *p_suboffset_dim = &suboffset_dim + * cdef Py_ssize_t start, stop, step + */ + __pyx_v_p_dst = (&__pyx_v_dst); + + /* "View.MemoryView":704 + * + * cdef __Pyx_memviewslice *p_dst = &dst + * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< + * cdef Py_ssize_t start, stop, step + * cdef bint have_start, have_stop, have_step + */ + __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); + + /* "View.MemoryView":708 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + __pyx_t_5 = 0; + if (PyList_CheckExact(__pyx_v_indices) || PyTuple_CheckExact(__pyx_v_indices)) { + __pyx_t_6 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_6); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = Py_TYPE(__pyx_t_6)->tp_iternext; + } + for (;;) { + if (!__pyx_t_8 && PyList_CheckExact(__pyx_t_6)) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_6)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_6, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_6, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_8 && PyTuple_CheckExact(__pyx_t_6)) { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_6)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_6, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_9 = __pyx_t_8(__pyx_t_6); + if (unlikely(!__pyx_t_9)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_9); + } + __Pyx_XDECREF(__pyx_v_index); + __pyx_v_index = __pyx_t_9; + __pyx_t_9 = 0; + __pyx_v_dim = __pyx_t_5; + __pyx_t_5 = (__pyx_t_5 + 1); + + /* "View.MemoryView":709 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ + __pyx_t_2 = (__Pyx_PyIndex_Check(__pyx_v_index) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":713 + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< + * 0, 0, 0, # have_{start,stop,step} + * False) + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":715 + * index, 0, 0, # start, stop, step + * 0, 0, 0, # have_{start,stop,step} + * False) # <<<<<<<<<<<<<< + * elif index is None: + * p_dst.shape[new_ndim] = 1 + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 710; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + + /* "View.MemoryView":716 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ + __pyx_t_2 = (__pyx_v_index == Py_None); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":717 + * False) + * elif index is None: + * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + */ + (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; + + /* "View.MemoryView":718 + * elif index is None: + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 + */ + (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; + + /* "View.MemoryView":719 + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< + * new_ndim += 1 + * else: + */ + (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1; + + /* "View.MemoryView":720 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 # <<<<<<<<<<<<<< + * else: + * start = index.start or 0 + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":722 + * new_ndim += 1 + * else: + * start = index.start or 0 # <<<<<<<<<<<<<< + * stop = index.stop or 0 + * step = index.step or 0 + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_start = __pyx_t_10; + + /* "View.MemoryView":723 + * else: + * start = index.start or 0 + * stop = index.stop or 0 # <<<<<<<<<<<<<< + * step = index.step or 0 + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_12); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_9 = __pyx_int_0; + } else { + __pyx_t_9 = __pyx_t_12; + __pyx_t_12 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_stop = __pyx_t_10; + + /* "View.MemoryView":724 + * start = index.start or 0 + * stop = index.stop or 0 + * step = index.step or 0 # <<<<<<<<<<<<<< + * + * have_start = index.start is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_step = __pyx_t_10; + + /* "View.MemoryView":726 + * step = index.step or 0 + * + * have_start = index.start is not None # <<<<<<<<<<<<<< + * have_stop = index.stop is not None + * have_step = index.step is not None + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__start); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 726; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_start = __pyx_t_1; + + /* "View.MemoryView":727 + * + * have_start = index.start is not None + * have_stop = index.stop is not None # <<<<<<<<<<<<<< + * have_step = index.step is not None + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 727; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_stop = __pyx_t_1; + + /* "View.MemoryView":728 + * have_start = index.start is not None + * have_stop = index.stop is not None + * have_step = index.step is not None # <<<<<<<<<<<<<< + * + * slice_memviewslice( + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__step); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_step = __pyx_t_1; + + /* "View.MemoryView":735 + * start, stop, step, + * have_start, have_stop, have_step, + * True) # <<<<<<<<<<<<<< + * new_ndim += 1 + * + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 730; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":736 + * have_start, have_stop, have_step, + * True) + * new_ndim += 1 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "View.MemoryView":738 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":739 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":740 + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 740; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":742 + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + */ + __pyx_t_6 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_6); + __pyx_t_6 = 0; + goto __pyx_L0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":744 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":745 + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_6 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 744; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 744; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_6); + __pyx_t_6 = 0; + goto __pyx_L0; + } + __pyx_L7:; + + __pyx_r = ((struct __pyx_memoryview_obj *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":769 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { + Py_ssize_t __pyx_v_new_shape; + int __pyx_v_negative_step; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":789 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":791 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + __pyx_t_1 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":792 + * + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":793 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + __pyx_t_1 = (0 <= __pyx_v_start); + if (__pyx_t_1) { + __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); + } + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":794 + * start += shape + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< + * else: + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_71, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":797 + * else: + * + * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< + * + * if have_step and step == 0: + */ + __pyx_t_2 = (__pyx_v_have_step != 0); + if (__pyx_t_2) { + __pyx_t_1 = (__pyx_v_step < 0); + __pyx_t_4 = __pyx_t_1; + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_v_negative_step = __pyx_t_4; + + /* "View.MemoryView":799 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + if ((__pyx_v_have_step != 0)) { + __pyx_t_4 = (__pyx_v_step == 0); + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = (__pyx_v_have_step != 0); + } + if (__pyx_t_2) { + + /* "View.MemoryView":800 + * + * if have_step and step == 0: + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_72, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":803 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + __pyx_t_2 = (__pyx_v_have_start != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":804 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":805 + * if have_start: + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if start < 0: + * start = 0 + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":806 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":807 + * start += shape + * if start < 0: + * start = 0 # <<<<<<<<<<<<<< + * elif start >= shape: + * if negative_step: + */ + __pyx_v_start = 0; + goto __pyx_L9; + } + __pyx_L9:; + goto __pyx_L8; + } + + /* "View.MemoryView":808 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":809 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":810 + * elif start >= shape: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = shape + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L10; + } + /*else*/ { + + /* "View.MemoryView":812 + * start = shape - 1 + * else: + * start = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_start = __pyx_v_shape; + } + __pyx_L10:; + goto __pyx_L8; + } + __pyx_L8:; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":814 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":815 + * else: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = 0 + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":817 + * start = shape - 1 + * else: + * start = 0 # <<<<<<<<<<<<<< + * + * if have_stop: + */ + __pyx_v_start = 0; + } + __pyx_L11:; + } + __pyx_L7:; + + /* "View.MemoryView":819 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + __pyx_t_2 = (__pyx_v_have_stop != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":820 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":821 + * if have_stop: + * if stop < 0: + * stop += shape # <<<<<<<<<<<<<< + * if stop < 0: + * stop = 0 + */ + __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); + + /* "View.MemoryView":822 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":823 + * stop += shape + * if stop < 0: + * stop = 0 # <<<<<<<<<<<<<< + * elif stop > shape: + * stop = shape + */ + __pyx_v_stop = 0; + goto __pyx_L14; + } + __pyx_L14:; + goto __pyx_L13; + } + + /* "View.MemoryView":824 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":825 + * stop = 0 + * elif stop > shape: + * stop = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_stop = __pyx_v_shape; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L12; + } + /*else*/ { + + /* "View.MemoryView":827 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":828 + * else: + * if negative_step: + * stop = -1 # <<<<<<<<<<<<<< + * else: + * stop = shape + */ + __pyx_v_stop = -1; + goto __pyx_L15; + } + /*else*/ { + + /* "View.MemoryView":830 + * stop = -1 + * else: + * stop = shape # <<<<<<<<<<<<<< + * + * if not have_step: + */ + __pyx_v_stop = __pyx_v_shape; + } + __pyx_L15:; + } + __pyx_L12:; + + /* "View.MemoryView":832 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":833 + * + * if not have_step: + * step = 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_step = 1; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":837 + * + * with cython.cdivision(True): + * new_shape = (stop - start) // step # <<<<<<<<<<<<<< + * + * if (stop - start) - step * new_shape: + */ + __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); + + /* "View.MemoryView":839 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":840 + * + * if (stop - start) - step * new_shape: + * new_shape += 1 # <<<<<<<<<<<<<< + * + * if new_shape < 0: + */ + __pyx_v_new_shape = (__pyx_v_new_shape + 1); + goto __pyx_L17; + } + __pyx_L17:; + + /* "View.MemoryView":842 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":843 + * + * if new_shape < 0: + * new_shape = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_new_shape = 0; + goto __pyx_L18; + } + __pyx_L18:; + + /* "View.MemoryView":846 + * + * + * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset + */ + (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); + + /* "View.MemoryView":847 + * + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< + * dst.suboffsets[new_ndim] = suboffset + * + */ + (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; + + /* "View.MemoryView":848 + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; + } + __pyx_L3:; + + /* "View.MemoryView":851 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":852 + * + * if suboffset_dim[0] < 0: + * dst.data += start * stride # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride + */ + __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); + goto __pyx_L19; + } + /*else*/ { + + /* "View.MemoryView":854 + * dst.data += start * stride + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< + * + * if suboffset >= 0: + */ + __pyx_t_3 = (__pyx_v_suboffset_dim[0]); + (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); + } + __pyx_L19:; + + /* "View.MemoryView":856 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":857 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":858 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":859 + * if not is_slice: + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + */ + __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); + goto __pyx_L22; + } + /*else*/ { + + /* "View.MemoryView":862 + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< + * else: + * suboffset_dim[0] = new_ndim + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_73, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L22:; + goto __pyx_L21; + } + /*else*/ { + + /* "View.MemoryView":864 + * "must be indexed and not sliced", dim) + * else: + * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< + * + * return 0 + */ + (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; + } + __pyx_L21:; + goto __pyx_L20; + } + __pyx_L20:; + + /* "View.MemoryView":866 + * suboffset_dim[0] = new_ndim + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":872 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + +static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, int __pyx_v_dim) { + Py_ssize_t __pyx_v_shape; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_suboffset; + Py_ssize_t __pyx_v_itemsize; + char *__pyx_v_resultp; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pybuffer_index", 0); + + /* "View.MemoryView":874 + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< + * cdef Py_ssize_t itemsize = view.itemsize + * cdef char *resultp + */ + __pyx_v_suboffset = -1; + + /* "View.MemoryView":875 + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< + * cdef char *resultp + * + */ + __pyx_t_1 = __pyx_v_view->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":878 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":879 + * + * if view.ndim == 0: + * shape = view.len / itemsize # <<<<<<<<<<<<<< + * stride = itemsize + * else: + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 879; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 879; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_shape = (__pyx_v_view->len / __pyx_v_itemsize); + + /* "View.MemoryView":880 + * if view.ndim == 0: + * shape = view.len / itemsize + * stride = itemsize # <<<<<<<<<<<<<< + * else: + * shape = view.shape[dim] + */ + __pyx_v_stride = __pyx_v_itemsize; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":882 + * stride = itemsize + * else: + * shape = view.shape[dim] # <<<<<<<<<<<<<< + * stride = view.strides[dim] + * if view.suboffsets != NULL: + */ + __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); + + /* "View.MemoryView":883 + * else: + * shape = view.shape[dim] + * stride = view.strides[dim] # <<<<<<<<<<<<<< + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] + */ + __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); + + /* "View.MemoryView":884 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":885 + * stride = view.strides[dim] + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< + * + * if index < 0: + */ + __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); + goto __pyx_L4; + } + __pyx_L4:; + } + __pyx_L3:; + + /* "View.MemoryView":887 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":888 + * + * if index < 0: + * index += view.shape[dim] # <<<<<<<<<<<<<< + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + */ + __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); + + /* "View.MemoryView":889 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":890 + * index += view.shape[dim] + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * if index >= shape: + */ + __pyx_t_3 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_74), __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_builtin_IndexError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":892 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":893 + * + * if index >= shape: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * resultp = bufp + index * stride + */ + __pyx_t_4 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_74), __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_IndexError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + + /* "View.MemoryView":895 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * resultp = bufp + index * stride # <<<<<<<<<<<<<< + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset + */ + __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); + + /* "View.MemoryView":896 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":897 + * resultp = bufp + index * stride + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< + * + * return resultp + */ + __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":899 + * resultp = ( resultp)[0] + suboffset + * + * return resultp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_resultp; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":905 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + +static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { + int __pyx_v_ndim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + int __pyx_v_i; + int __pyx_v_j; + int __pyx_r; + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + long __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":906 + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: + * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< + * + * cdef Py_ssize_t *shape = memslice.shape + */ + __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; + __pyx_v_ndim = __pyx_t_1; + + /* "View.MemoryView":908 + * cdef int ndim = memslice.memview.view.ndim + * + * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< + * cdef Py_ssize_t *strides = memslice.strides + * + */ + __pyx_t_2 = __pyx_v_memslice->shape; + __pyx_v_shape = __pyx_t_2; + + /* "View.MemoryView":909 + * + * cdef Py_ssize_t *shape = memslice.shape + * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_v_memslice->strides; + __pyx_v_strides = __pyx_t_2; + + /* "View.MemoryView":913 + * + * cdef int i, j + * for i in range(ndim / 2): # <<<<<<<<<<<<<< + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + */ + __pyx_t_3 = (__pyx_v_ndim / 2); + for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":914 + * cdef int i, j + * for i in range(ndim / 2): + * j = ndim - 1 - i # <<<<<<<<<<<<<< + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] + */ + __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); + + /* "View.MemoryView":915 + * for i in range(ndim / 2): + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< + * shape[i], shape[j] = shape[j], shape[i] + * + */ + __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); + __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); + (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; + (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; + + /* "View.MemoryView":916 + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + */ + __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); + __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); + (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; + (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; + + /* "View.MemoryView":918 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + __pyx_t_6 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); + if (!__pyx_t_6) { + __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); + __pyx_t_8 = __pyx_t_7; + } else { + __pyx_t_8 = __pyx_t_6; + } + if (__pyx_t_8) { + + /* "View.MemoryView":919 + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< + * + * return 1 + */ + __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_75); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 919; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "View.MemoryView":921 + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + * return 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 1; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":938 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":939 + * + * def __dealloc__(self): + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":941 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":942 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":943 + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) # <<<<<<<<<<<<<< + * else: + * return memoryview.convert_item_to_object(self, itemp) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":945 + * return self.to_object_func(itemp) + * else: + * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_vtabptr_memoryview->convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 945; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":947 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":948 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":949 + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< + * else: + * memoryview.assign_item_from_object(self, itemp, value) + */ + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":951 + * self.to_dtype_func(itemp, value) + * else: + * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< + * + * property base: + */ + __pyx_t_3 = __pyx_vtabptr_memoryview->assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 951; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":955 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":956 + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): + * return self.from_object # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->from_object); + __pyx_r = __pyx_v_self->from_object; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":962 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_TypeInfo *__pyx_t_4; + Py_buffer __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_fromslice", 0); + + /* "View.MemoryView":971 + * cdef int i + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":972 + * + * if memviewslice.memview == Py_None: + * return None # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":977 + * + * + * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< + * + * result.from_slice = memviewslice + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":979 + * result = _memoryviewslice(None, 0, dtype_is_object) + * + * result.from_slice = memviewslice # <<<<<<<<<<<<<< + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + */ + __pyx_v_result->from_slice = __pyx_v_memviewslice; + + /* "View.MemoryView":980 + * + * result.from_slice = memviewslice + * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< + * + * result.from_object = ( memviewslice.memview).base + */ + __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); + + /* "View.MemoryView":982 + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< + * result.typeinfo = memviewslice.memview.typeinfo + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s__base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 982; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_result->from_object); + __Pyx_DECREF(__pyx_v_result->from_object); + __pyx_v_result->from_object = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":983 + * + * result.from_object = ( memviewslice.memview).base + * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< + * + * result.view = memviewslice.memview.view + */ + __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; + __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; + + /* "View.MemoryView":985 + * result.typeinfo = memviewslice.memview.typeinfo + * + * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + */ + __pyx_t_5 = __pyx_v_memviewslice.memview->view; + __pyx_v_result->__pyx_base.view = __pyx_t_5; + + /* "View.MemoryView":986 + * + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + */ + __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); + + /* "View.MemoryView":987 + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data + * result.view.ndim = ndim # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; + + /* "View.MemoryView":988 + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; + + /* "View.MemoryView":989 + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * result.flags = PyBUF_RECORDS + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":991 + * Py_INCREF(Py_None) + * + * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< + * + * result.view.shape = result.from_slice.shape + */ + __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; + + /* "View.MemoryView":993 + * result.flags = PyBUF_RECORDS + * + * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets + */ + __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); + + /* "View.MemoryView":994 + * + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * + */ + __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); + + /* "View.MemoryView":995 + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + * + * result.view.len = result.view.itemsize + */ + __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + + /* "View.MemoryView":997 + * result.view.suboffsets = result.from_slice.suboffsets + * + * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< + * for i in range(ndim): + * result.view.len *= result.view.shape[i] + */ + __pyx_t_6 = __pyx_v_result->__pyx_base.view.itemsize; + __pyx_v_result->__pyx_base.view.len = __pyx_t_6; + + /* "View.MemoryView":998 + * + * result.view.len = result.view.itemsize + * for i in range(ndim): # <<<<<<<<<<<<<< + * result.view.len *= result.view.shape[i] + * + */ + __pyx_t_7 = __pyx_v_ndim; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "View.MemoryView":999 + * result.view.len = result.view.itemsize + * for i in range(ndim): + * result.view.len *= result.view.shape[i] # <<<<<<<<<<<<<< + * + * result.to_object_func = to_object_func + */ + __pyx_v_result->__pyx_base.view.len = (__pyx_v_result->__pyx_base.view.len * (__pyx_v_result->__pyx_base.view.shape[__pyx_v_i])); + } + + /* "View.MemoryView":1001 + * result.view.len *= result.view.shape[i] + * + * result.to_object_func = to_object_func # <<<<<<<<<<<<<< + * result.to_dtype_func = to_dtype_func + * + */ + __pyx_v_result->to_object_func = __pyx_v_to_object_func; + + /* "View.MemoryView":1002 + * + * result.to_object_func = to_object_func + * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; + + /* "View.MemoryView":1004 + * result.to_dtype_func = to_dtype_func + * + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1007 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { + struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; + __Pyx_memviewslice *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_slice_from_memview", 0); + + /* "View.MemoryView":1010 + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1011 + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): + * obj = memview # <<<<<<<<<<<<<< + * return &obj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1011; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(((PyObject *)__pyx_v_memview)); + __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview); + + /* "View.MemoryView":1012 + * if isinstance(memview, _memoryviewslice): + * obj = memview + * return &obj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, mslice) + */ + __pyx_r = (&__pyx_v_obj->from_slice); + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1014 + * return &obj.from_slice + * else: + * slice_copy(memview, mslice) # <<<<<<<<<<<<<< + * return mslice + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); + + /* "View.MemoryView":1015 + * else: + * slice_copy(memview, mslice) + * return mslice # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_copy') + */ + __pyx_r = __pyx_v_mslice; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_obj); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1018 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef Py_ssize_t *shape, *strides, *suboffsets + */ + +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { + int __pyx_v_dim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + Py_ssize_t *__pyx_v_suboffsets; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + __Pyx_RefNannySetupContext("slice_copy", 0); + + /* "View.MemoryView":1022 + * cdef Py_ssize_t *shape, *strides, *suboffsets + * + * shape = memview.view.shape # <<<<<<<<<<<<<< + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets + */ + __pyx_t_1 = __pyx_v_memview->view.shape; + __pyx_v_shape = __pyx_t_1; + + /* "View.MemoryView":1023 + * + * shape = memview.view.shape + * strides = memview.view.strides # <<<<<<<<<<<<<< + * suboffsets = memview.view.suboffsets + * + */ + __pyx_t_1 = __pyx_v_memview->view.strides; + __pyx_v_strides = __pyx_t_1; + + /* "View.MemoryView":1024 + * shape = memview.view.shape + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< + * + * dst.memview = <__pyx_memoryview *> memview + */ + __pyx_t_1 = __pyx_v_memview->view.suboffsets; + __pyx_v_suboffsets = __pyx_t_1; + + /* "View.MemoryView":1026 + * suboffsets = memview.view.suboffsets + * + * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< + * dst.data = memview.view.buf + * + */ + __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); + + /* "View.MemoryView":1027 + * + * dst.memview = <__pyx_memoryview *> memview + * dst.data = memview.view.buf # <<<<<<<<<<<<<< + * + * for dim in range(memview.view.ndim): + */ + __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); + + /* "View.MemoryView":1029 + * dst.data = memview.view.buf + * + * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + */ + __pyx_t_2 = __pyx_v_memview->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_dim = __pyx_t_3; + + /* "View.MemoryView":1030 + * + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + */ + (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); + + /* "View.MemoryView":1031 + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 + */ + (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); + + /* "View.MemoryView":1032 + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: # <<<<<<<<<<<<<< + * dst.suboffsets[dim] = -1 + * else: + */ + __pyx_t_4 = ((__pyx_v_suboffsets == NULL) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":1033 + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[dim] = suboffsets[dim] + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = -1; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1035 + * dst.suboffsets[dim] = -1 + * else: + * dst.suboffsets[dim] = suboffsets[dim] # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object') + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = (__pyx_v_suboffsets[__pyx_v_dim]); + } + __pyx_L5:; + } + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1038 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { + __Pyx_memviewslice __pyx_v_memviewslice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy", 0); + + /* "View.MemoryView":1041 + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< + * return memoryview_copy_from_slice(memview, &memviewslice) + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); + + /* "View.MemoryView":1042 + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) + * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object_from_slice') + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1042; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1045 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { + PyObject *(*__pyx_v_to_object_func)(char *); + int (*__pyx_v_to_dtype_func)(char *, PyObject *); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *(*__pyx_t_3)(char *); + int (*__pyx_t_4)(char *, PyObject *); + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); + + /* "View.MemoryView":1052 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1053 + * + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + */ + __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; + __pyx_v_to_object_func = __pyx_t_3; + + /* "View.MemoryView":1054 + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< + * else: + * to_object_func = NULL + */ + __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; + __pyx_v_to_dtype_func = __pyx_t_4; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1056 + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + * to_object_func = NULL # <<<<<<<<<<<<<< + * to_dtype_func = NULL + * + */ + __pyx_v_to_object_func = NULL; + + /* "View.MemoryView":1057 + * else: + * to_object_func = NULL + * to_dtype_func = NULL # <<<<<<<<<<<<<< + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + */ + __pyx_v_to_dtype_func = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":1059 + * to_dtype_func = NULL + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< + * to_object_func, to_dtype_func, + * memview.dtype_is_object) + */ + __Pyx_XDECREF(__pyx_r); + + /* "View.MemoryView":1061 + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + * to_object_func, to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1067 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + +static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { + Py_ssize_t __pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":1068 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + __pyx_t_1 = ((__pyx_v_arg < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1069 + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: + * return -arg # <<<<<<<<<<<<<< + * else: + * return arg + */ + __pyx_r = (-__pyx_v_arg); + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1071 + * return -arg + * else: + * return arg # <<<<<<<<<<<<<< + * + * @cname('__pyx_get_best_slice_order') + */ + __pyx_r = __pyx_v_arg; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1074 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + +static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_c_stride; + Py_ssize_t __pyx_v_f_stride; + char __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1079 + * """ + * cdef int i + * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t f_stride = 0 + * + */ + __pyx_v_c_stride = 0; + + /* "View.MemoryView":1080 + * cdef int i + * cdef Py_ssize_t c_stride = 0 + * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_f_stride = 0; + + /* "View.MemoryView":1082 + * cdef Py_ssize_t f_stride = 0 + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1083 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1084 + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1085 + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + goto __pyx_L4_break; + goto __pyx_L5; + } + __pyx_L5:; + } + __pyx_L4_break:; + + /* "View.MemoryView":1087 + * break + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1088 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1089 + * for i in range(ndim): + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1090 + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + */ + goto __pyx_L7_break; + goto __pyx_L8; + } + __pyx_L8:; + } + __pyx_L7_break:; + + /* "View.MemoryView":1092 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1093 + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + * return 'C' # <<<<<<<<<<<<<< + * else: + * return 'F' + */ + __pyx_r = 'C'; + goto __pyx_L0; + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1095 + * return 'C' + * else: + * return 'F' # <<<<<<<<<<<<<< + * + * @cython.cdivision(True) + */ + __pyx_r = 'F'; + goto __pyx_L0; + } + __pyx_L9:; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1098 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + +static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; + Py_ssize_t __pyx_v_dst_extent; + Py_ssize_t __pyx_v_src_stride; + Py_ssize_t __pyx_v_dst_stride; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + + /* "View.MemoryView":1105 + * + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + */ + __pyx_v_src_extent = (__pyx_v_src_shape[0]); + + /* "View.MemoryView":1106 + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] + */ + __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); + + /* "View.MemoryView":1107 + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + */ + __pyx_v_src_stride = (__pyx_v_src_strides[0]); + + /* "View.MemoryView":1108 + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); + + /* "View.MemoryView":1110 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1111 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + __pyx_t_1 = ((__pyx_v_src_stride > 0) != 0); + if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1112 + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + */ + __pyx_t_3 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); + if (__pyx_t_3) { + __pyx_t_3 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); + } + __pyx_t_4 = (__pyx_t_3 != 0); + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = __pyx_t_1; + } + if (__pyx_t_2) { + + /* "View.MemoryView":1113 + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":1115 + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1116 + * else: + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); + + /* "View.MemoryView":1117 + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * else: + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1118 + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1120 + * dst_data += dst_stride + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * _copy_strided_to_strided(src_data, src_strides + 1, + * dst_data, dst_strides + 1, + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1124 + * dst_data, dst_strides + 1, + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); + + /* "View.MemoryView":1125 + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1126 + * ndim - 1, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L3:; + +} + +/* "View.MemoryView":1128 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + +static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + + /* "View.MemoryView":1132 + * int ndim, size_t itemsize) nogil: + * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, + * src.shape, dst.shape, ndim, itemsize) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_get_size') + */ + _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); + +} + +/* "View.MemoryView":1135 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_size; + Py_ssize_t __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1138 + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_size = __pyx_t_1; + + /* "View.MemoryView":1140 + * cdef Py_ssize_t size = src.memview.view.itemsize + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * size *= src.shape[i] + * + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1141 + * + * for i in range(ndim): + * size *= src.shape[i] # <<<<<<<<<<<<<< + * + * return size + */ + __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); + } + + /* "View.MemoryView":1143 + * size *= src.shape[i] + * + * return size # <<<<<<<<<<<<<< + * + * @cname('__pyx_fill_contig_strides_array') + */ + __pyx_r = __pyx_v_size; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1146 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { + int __pyx_v_idx; + Py_ssize_t __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1155 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + __pyx_t_1 = ((__pyx_v_order == 'F') != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1156 + * + * if order == 'F': + * for idx in range(ndim): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_idx = __pyx_t_3; + + /* "View.MemoryView":1157 + * if order == 'F': + * for idx in range(ndim): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * else: + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1158 + * for idx in range(ndim): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * else: + * for idx in range(ndim - 1, -1, -1): + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1160 + * stride = stride * shape[idx] + * else: + * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { + __pyx_v_idx = __pyx_t_2; + + /* "View.MemoryView":1161 + * else: + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1162 + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * + * return stride + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + } + __pyx_L3:; + + /* "View.MemoryView":1164 + * stride = stride * shape[idx] + * + * return stride # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_data_to_temp') + */ + __pyx_r = __pyx_v_stride; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1167 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { + int __pyx_v_i; + void *__pyx_v_result; + size_t __pyx_v_itemsize; + size_t __pyx_v_size; + void *__pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + struct __pyx_memoryview_obj *__pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1178 + * cdef void *result + * + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef size_t size = slice_get_size(src, ndim) + * + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1179 + * + * cdef size_t itemsize = src.memview.view.itemsize + * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< + * + * result = malloc(size) + */ + __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); + + /* "View.MemoryView":1181 + * cdef size_t size = slice_get_size(src, ndim) + * + * result = malloc(size) # <<<<<<<<<<<<<< + * if not result: + * _err(MemoryError, NULL) + */ + __pyx_v_result = malloc(__pyx_v_size); + + /* "View.MemoryView":1182 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1183 + * result = malloc(size) + * if not result: + * _err(MemoryError, NULL) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1186 + * + * + * tmpslice.data = result # <<<<<<<<<<<<<< + * tmpslice.memview = src.memview + * for i in range(ndim): + */ + __pyx_v_tmpslice->data = ((char *)__pyx_v_result); + + /* "View.MemoryView":1187 + * + * tmpslice.data = result + * tmpslice.memview = src.memview # <<<<<<<<<<<<<< + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + */ + __pyx_t_4 = __pyx_v_src->memview; + __pyx_v_tmpslice->memview = __pyx_t_4; + + /* "View.MemoryView":1188 + * tmpslice.data = result + * tmpslice.memview = src.memview + * for i in range(ndim): # <<<<<<<<<<<<<< + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1189 + * tmpslice.memview = src.memview + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< + * tmpslice.suboffsets[i] = -1 + * + */ + (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); + + /* "View.MemoryView":1190 + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + */ + (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1193 + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + * ndim, order) # <<<<<<<<<<<<<< + * + * + */ + __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); + + /* "View.MemoryView":1196 + * + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1197 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1198 + * for i in range(ndim): + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< + * + * if slice_is_contig(src, order, ndim): + */ + (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1200 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1201 + * + * if slice_is_contig(src, order, ndim): + * memcpy(result, src.data, size) # <<<<<<<<<<<<<< + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + */ + memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1203 + * memcpy(result, src.data, size) + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< + * + * return result + */ + copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); + } + __pyx_L9:; + + /* "View.MemoryView":1205 + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = NULL; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1210 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + +static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_extents", 0); + + /* "View.MemoryView":1213 + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + * (i, extent1, extent2)) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err_dim') + */ + __pyx_t_1 = PyInt_FromLong(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_76), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1216 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + +static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_dim", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1217 + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: + * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err') + */ + __pyx_t_1 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_2 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_t_1), __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_v_error, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1220 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + +static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1221 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ + __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1222 + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: + * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< + * else: + * raise error + */ + __pyx_t_2 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_2)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_v_error, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1224 + * raise error(msg.decode('ascii')) + * else: + * raise error # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_contents') + */ + __Pyx_Raise(__pyx_v_error, 0, 0, 0); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1227 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { + void *__pyx_v_tmpdata; + size_t __pyx_v_itemsize; + int __pyx_v_i; + char __pyx_v_order; + int __pyx_v_broadcasting; + int __pyx_v_direct_copy; + __Pyx_memviewslice __pyx_v_tmp; + int __pyx_v_ndim; + int __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + void *__pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1235 + * Check for overlapping memory and verify the shapes. + * """ + * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + */ + __pyx_v_tmpdata = NULL; + + /* "View.MemoryView":1236 + * """ + * cdef void *tmpdata = NULL + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + */ + __pyx_t_1 = __pyx_v_src.memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1238 + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< + * cdef bint broadcasting = False + * cdef bint direct_copy = False + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); + + /* "View.MemoryView":1239 + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False # <<<<<<<<<<<<<< + * cdef bint direct_copy = False + * cdef __Pyx_memviewslice tmp + */ + __pyx_v_broadcasting = 0; + + /* "View.MemoryView":1240 + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False + * cdef bint direct_copy = False # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice tmp + * + */ + __pyx_v_direct_copy = 0; + + /* "View.MemoryView":1243 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ + __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1244 + * + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); + goto __pyx_L3; + } + + /* "View.MemoryView":1245 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ + __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1246 + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< + * + * cdef int ndim = max(src_ndim, dst_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1248 + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_3 = __pyx_v_dst_ndim; + __pyx_t_4 = __pyx_v_src_ndim; + if (((__pyx_t_3 > __pyx_t_4) != 0)) { + __pyx_t_5 = __pyx_t_3; + } else { + __pyx_t_5 = __pyx_t_4; + } + __pyx_v_ndim = __pyx_t_5; + + /* "View.MemoryView":1250 + * cdef int ndim = max(src_ndim, dst_ndim) + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1251 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1252 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1253 + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + * broadcasting = True # <<<<<<<<<<<<<< + * src.strides[i] = 0 + * else: + */ + __pyx_v_broadcasting = 1; + + /* "View.MemoryView":1254 + * if src.shape[i] == 1: + * broadcasting = True + * src.strides[i] = 0 # <<<<<<<<<<<<<< + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) + */ + (__pyx_v_src.strides[__pyx_v_i]) = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":1256 + * src.strides[i] = 0 + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< + * + * if src.suboffsets[i] >= 0: + */ + __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":1258 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ + __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1259 + * + * if src.suboffsets[i] >= 0: + * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< + * + * if slices_overlap(&src, &dst, ndim, itemsize): + */ + __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_77, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1259; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1261 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(&src, order, ndim): + */ + __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1263 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1264 + * + * if not slice_is_contig(&src, order, ndim): + * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":1266 + * order = get_best_order(&dst, ndim) + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< + * src = tmp + * + */ + __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_tmpdata = __pyx_t_6; + + /* "View.MemoryView":1267 + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + * src = tmp # <<<<<<<<<<<<<< + * + * if not broadcasting: + */ + __pyx_v_src = __pyx_v_tmp; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":1269 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1272 + * + * + * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1273 + * + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); + goto __pyx_L12; + } + + /* "View.MemoryView":1274 + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1275 + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< + * + * if direct_copy: + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":1277 + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_2 = (__pyx_v_direct_copy != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1279 + * if direct_copy: + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1280 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * return 0 + */ + memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); + + /* "View.MemoryView":1281 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1282 + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + * return 0 # <<<<<<<<<<<<<< + * + * if order == 'F' == get_best_order(&dst, ndim): + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":1284 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = (__pyx_v_order == 'F'); + if (__pyx_t_2) { + __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); + } + __pyx_t_7 = (__pyx_t_2 != 0); + if (__pyx_t_7) { + + /* "View.MemoryView":1287 + * + * + * transpose_memslice(&src) # <<<<<<<<<<<<<< + * transpose_memslice(&dst) + * + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1288 + * + * transpose_memslice(&src) + * transpose_memslice(&dst) # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":1290 + * transpose_memslice(&dst) + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1291 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + */ + copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1292 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * free(tmpdata) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1294 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1295 + * + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_broadcast_leading') + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1298 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice, int __pyx_v_ndim, int __pyx_v_ndim_other) { + int __pyx_v_i; + int __pyx_v_offset; + int __pyx_t_1; + int __pyx_t_2; + + /* "View.MemoryView":1302 + * int ndim_other) nogil: + * cdef int i + * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); + + /* "View.MemoryView":1304 + * cdef int offset = ndim_other - ndim + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1305 + * + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] # <<<<<<<<<<<<<< + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] + */ + (__pyx_v_slice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->shape[__pyx_v_i]); + + /* "View.MemoryView":1306 + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] # <<<<<<<<<<<<<< + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + */ + (__pyx_v_slice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->strides[__pyx_v_i]); + + /* "View.MemoryView":1307 + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] # <<<<<<<<<<<<<< + * + * for i in range(offset): + */ + (__pyx_v_slice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->suboffsets[__pyx_v_i]); + } + + /* "View.MemoryView":1309 + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + * for i in range(offset): # <<<<<<<<<<<<<< + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + */ + __pyx_t_1 = __pyx_v_offset; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1310 + * + * for i in range(offset): + * slice.shape[i] = 1 # <<<<<<<<<<<<<< + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 + */ + (__pyx_v_slice->shape[__pyx_v_i]) = 1; + + /* "View.MemoryView":1311 + * for i in range(offset): + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] # <<<<<<<<<<<<<< + * slice.suboffsets[i] = -1 + * + */ + (__pyx_v_slice->strides[__pyx_v_i]) = (__pyx_v_slice->strides[0]); + + /* "View.MemoryView":1312 + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_slice->suboffsets[__pyx_v_i]) = -1; + } + +} + +/* "View.MemoryView":1320 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { + int __pyx_t_1; + + /* "View.MemoryView":1324 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + __pyx_t_1 = (__pyx_v_dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1326 + * if dtype_is_object: + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + */ + __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); + goto __pyx_L3; + } + __pyx_L3:; + +} + +/* "View.MemoryView":1329 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + __Pyx_RefNannyDeclarations + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); + + /* "View.MemoryView":1332 + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); + + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif +} + +/* "View.MemoryView":1335 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + +static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); + + /* "View.MemoryView":1339 + * cdef Py_ssize_t i + * + * for i in range(shape[0]): # <<<<<<<<<<<<<< + * if ndim == 1: + * if inc: + */ + __pyx_t_1 = (__pyx_v_shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1340 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1341 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + __pyx_t_3 = (__pyx_v_inc != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1342 + * if ndim == 1: + * if inc: + * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * Py_DECREF(( data)[0]) + */ + Py_INCREF((((PyObject **)__pyx_v_data)[0])); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":1344 + * Py_INCREF(( data)[0]) + * else: + * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + */ + Py_DECREF((((PyObject **)__pyx_v_data)[0])); + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1347 + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + * ndim - 1, inc) # <<<<<<<<<<<<<< + * + * data += strides[0] + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); + } + __pyx_L5:; + + /* "View.MemoryView":1349 + * ndim - 1, inc) + * + * data += strides[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); + } + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1355 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { + + /* "View.MemoryView":1358 + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1360 + * refcount_copying(dst, dtype_is_object, ndim, False) + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) # <<<<<<<<<<<<<< + * refcount_copying(dst, dtype_is_object, ndim, True) + * + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1361 + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + +} + +/* "View.MemoryView":1365 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + +static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_extent; + int __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + + /* "View.MemoryView":1369 + * size_t itemsize, void *item) nogil: + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t extent = shape[0] + * + */ + __pyx_v_stride = (__pyx_v_strides[0]); + + /* "View.MemoryView":1370 + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] + * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_extent = (__pyx_v_shape[0]); + + /* "View.MemoryView":1372 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1373 + * + * if ndim == 1: + * for i in range(extent): # <<<<<<<<<<<<<< + * memcpy(data, item, itemsize) + * data += stride + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1374 + * if ndim == 1: + * for i in range(extent): + * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< + * data += stride + * else: + */ + memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); + + /* "View.MemoryView":1375 + * for i in range(extent): + * memcpy(data, item, itemsize) + * data += stride # <<<<<<<<<<<<<< + * else: + * for i in range(extent): + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1377 + * data += stride + * else: + * for i in range(extent): # <<<<<<<<<<<<<< + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1379 + * for i in range(extent): + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) # <<<<<<<<<<<<<< + * data += stride + * + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1380 + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + * data += stride # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + } + __pyx_L3:; + +} + +/* "BufferFormatFromTypeInfo":1421 + * + * @cname('__pyx_format_from_typeinfo') + * cdef bytes format_from_typeinfo(__Pyx_TypeInfo *type): # <<<<<<<<<<<<<< + * cdef __Pyx_StructField *field + * cdef __pyx_typeinfo_string fmt + */ + +static PyObject *__pyx_format_from_typeinfo(__Pyx_TypeInfo *__pyx_v_type) { + __Pyx_StructField *__pyx_v_field; + struct __pyx_typeinfo_string __pyx_v_fmt; + PyObject *__pyx_v_part = 0; + PyObject *__pyx_v_result = 0; + PyObject *__pyx_v_alignment = NULL; + PyObject *__pyx_v_parts = NULL; + PyObject *__pyx_v_extents = NULL; + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + __Pyx_StructField *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("format_from_typeinfo", 0); + + /* "BufferFormatFromTypeInfo":1426 + * cdef bytes part, result + * + * if type.typegroup == 'S': # <<<<<<<<<<<<<< + * assert type.fields != NULL and type.fields.type != NULL + * + */ + __pyx_t_1 = ((__pyx_v_type->typegroup == 'S') != 0); + if (__pyx_t_1) { + + /* "BufferFormatFromTypeInfo":1427 + * + * if type.typegroup == 'S': + * assert type.fields != NULL and type.fields.type != NULL # <<<<<<<<<<<<<< + * + * if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT: + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + __pyx_t_1 = ((__pyx_v_type->fields != NULL) != 0); + if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_type->fields->type != NULL) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (unlikely(!__pyx_t_3)) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1427; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #endif + + /* "BufferFormatFromTypeInfo":1429 + * assert type.fields != NULL and type.fields.type != NULL + * + * if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT: # <<<<<<<<<<<<<< + * alignment = b'^' + * else: + */ + __pyx_t_3 = ((__pyx_v_type->flags & __PYX_BUF_FLAGS_PACKED_STRUCT) != 0); + if (__pyx_t_3) { + + /* "BufferFormatFromTypeInfo":1430 + * + * if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT: + * alignment = b'^' # <<<<<<<<<<<<<< + * else: + * alignment = b'' + */ + __Pyx_INCREF(((PyObject *)__pyx_kp_b_78)); + __pyx_v_alignment = __pyx_kp_b_78; + goto __pyx_L4; + } + /*else*/ { + + /* "BufferFormatFromTypeInfo":1432 + * alignment = b'^' + * else: + * alignment = b'' # <<<<<<<<<<<<<< + * + * parts = [b"T{"] + */ + __Pyx_INCREF(((PyObject *)__pyx_kp_b_79)); + __pyx_v_alignment = __pyx_kp_b_79; + } + __pyx_L4:; + + /* "BufferFormatFromTypeInfo":1434 + * alignment = b'' + * + * parts = [b"T{"] # <<<<<<<<<<<<<< + * field = type.fields + * + */ + __pyx_t_4 = PyList_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_kp_b_80)); + PyList_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_kp_b_80)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_b_80)); + __pyx_v_parts = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "BufferFormatFromTypeInfo":1435 + * + * parts = [b"T{"] + * field = type.fields # <<<<<<<<<<<<<< + * + * while field.type: + */ + __pyx_t_5 = __pyx_v_type->fields; + __pyx_v_field = __pyx_t_5; + + /* "BufferFormatFromTypeInfo":1437 + * field = type.fields + * + * while field.type: # <<<<<<<<<<<<<< + * part = format_from_typeinfo(field.type) + * parts.append(part + b':' + field.name + b':') + */ + while (1) { + __pyx_t_3 = (__pyx_v_field->type != 0); + if (!__pyx_t_3) break; + + /* "BufferFormatFromTypeInfo":1438 + * + * while field.type: + * part = format_from_typeinfo(field.type) # <<<<<<<<<<<<<< + * parts.append(part + b':' + field.name + b':') + * field += 1 + */ + __pyx_t_4 = ((PyObject *)__pyx_format_from_typeinfo(__pyx_v_field->type)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF(((PyObject *)__pyx_v_part)); + __pyx_v_part = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "BufferFormatFromTypeInfo":1439 + * while field.type: + * part = format_from_typeinfo(field.type) + * parts.append(part + b':' + field.name + b':') # <<<<<<<<<<<<<< + * field += 1 + * + */ + __pyx_t_4 = PyNumber_Add(((PyObject *)__pyx_v_part), ((PyObject *)__pyx_kp_b_81)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_field->name); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __pyx_t_7 = PyNumber_Add(((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_7)); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + __pyx_t_6 = PyNumber_Add(((PyObject *)__pyx_t_7), ((PyObject *)__pyx_kp_b_81)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __pyx_t_8 = __Pyx_PyList_Append(__pyx_v_parts, ((PyObject *)__pyx_t_6)); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + + /* "BufferFormatFromTypeInfo":1440 + * part = format_from_typeinfo(field.type) + * parts.append(part + b':' + field.name + b':') + * field += 1 # <<<<<<<<<<<<<< + * + * result = alignment.join(parts) + b'}' + */ + __pyx_v_field = (__pyx_v_field + 1); + } + + /* "BufferFormatFromTypeInfo":1442 + * field += 1 + * + * result = alignment.join(parts) + b'}' # <<<<<<<<<<<<<< + * else: + * fmt = __Pyx_TypeInfoToFormat(type) + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_alignment), __pyx_n_s__join); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_INCREF(((PyObject *)__pyx_v_parts)); + PyTuple_SET_ITEM(__pyx_t_7, 0, ((PyObject *)__pyx_v_parts)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_parts)); + __pyx_t_4 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __pyx_t_7 = PyNumber_Add(__pyx_t_4, ((PyObject *)__pyx_kp_b_82)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_7))||((__pyx_t_7) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_7)->tp_name), 0))) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "BufferFormatFromTypeInfo":1444 + * result = alignment.join(parts) + b'}' + * else: + * fmt = __Pyx_TypeInfoToFormat(type) # <<<<<<<<<<<<<< + * if type.arraysize[0]: + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] + */ + __pyx_v_fmt = __Pyx_TypeInfoToFormat(__pyx_v_type); + + /* "BufferFormatFromTypeInfo":1445 + * else: + * fmt = __Pyx_TypeInfoToFormat(type) + * if type.arraysize[0]: # <<<<<<<<<<<<<< + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string + */ + __pyx_t_3 = ((__pyx_v_type->arraysize[0]) != 0); + if (__pyx_t_3) { + + /* "BufferFormatFromTypeInfo":1446 + * fmt = __Pyx_TypeInfoToFormat(type) + * if type.arraysize[0]: + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] # <<<<<<<<<<<<<< + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string + * else: + */ + __pyx_t_7 = PyList_New(0); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = __pyx_v_type->ndim; + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { + __pyx_v_i = __pyx_t_10; + __pyx_t_4 = __Pyx_PyInt_FromSize_t((__pyx_v_type->arraysize[__pyx_v_i])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(((PyObject *)((PyObject*)(&PyUnicode_Type))), ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + if (unlikely(__Pyx_ListComp_Append(__pyx_t_7, (PyObject*)__pyx_t_4))) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __pyx_v_extents = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + + /* "BufferFormatFromTypeInfo":1447 + * if type.arraysize[0]: + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string # <<<<<<<<<<<<<< + * else: + * result = fmt.string + */ + __pyx_t_7 = ((PyObject *)PyUnicode_Join(__pyx_kp_u_84, ((PyObject *)__pyx_v_extents))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_83), __pyx_t_7); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = ((PyObject *)PyUnicode_AsASCIIString(((PyObject*)__pyx_t_4))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_7)); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_fmt.string); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_6 = PyNumber_Add(((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_6))||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_6)->tp_name), 0))) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "BufferFormatFromTypeInfo":1449 + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string + * else: + * result = fmt.string # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_fmt.string); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __pyx_v_result = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + } + __pyx_L7:; + } + __pyx_L3:; + + /* "BufferFormatFromTypeInfo":1451 + * result = fmt.string + * + * return result # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + __pyx_r = ((PyObject*)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("BufferFormatFromTypeInfo.format_from_typeinfo", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_part); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_alignment); + __Pyx_XDECREF(__pyx_v_parts); + __Pyx_XDECREF(__pyx_v_extents); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_MemviewEnum_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_MemviewEnum_obj *)o); + p->name = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + PyObject_GC_UnTrack(o); + Py_CLEAR(p->name); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + if (p->name) { + e = (*v)(p->name, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->name); + p->name = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_Enum[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_MemviewEnum = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.Enum"), /*tp_name*/ + sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_Enum, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_MemviewEnum___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_Enum, /*tp_traverse*/ + __pyx_tp_clear_Enum, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_Enum, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_MemviewEnum___init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_Enum, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric __pyx_vtable_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + p->vec = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->mat = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->func = Py_None; Py_INCREF(Py_None); + p->kwargs = Py_None; Py_INCREF(Py_None); + if (unlikely(__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_1__cinit__(o, __pyx_empty_tuple, NULL) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric(PyObject *o) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *p = (struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)o; + PyObject_GC_UnTrack(o); + Py_CLEAR(p->vec); + Py_CLEAR(p->mat); + Py_CLEAR(p->func); + Py_CLEAR(p->kwargs); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *p = (struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)o; + if (p->vec) { + e = (*v)(((PyObject*)p->vec), a); if (e) return e; + } + if (p->mat) { + e = (*v)(((PyObject*)p->mat), a); if (e) return e; + } + if (p->func) { + e = (*v)(p->func, a); if (e) return e; + } + if (p->kwargs) { + e = (*v)(p->kwargs, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric(PyObject *o) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *p = (struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)o; + PyObject* tmp; + tmp = ((PyObject*)p->vec); + p->vec = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->mat); + p->mat = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->func); + p->func = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->kwargs); + p->kwargs = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_DistanceMetric[] = { + {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_3__reduce__, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_2__reduce__)}, + {__Pyx_NAMESTR("__getstate__"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_5__getstate__, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_4__getstate__)}, + {__Pyx_NAMESTR("__setstate__"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_7__setstate__, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_6__setstate__)}, + {__Pyx_NAMESTR("get_metric"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_9get_metric, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_8get_metric)}, + {__Pyx_NAMESTR("rdist_to_dist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_13rdist_to_dist, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_12rdist_to_dist)}, + {__Pyx_NAMESTR("dist_to_rdist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_15dist_to_rdist, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_14dist_to_rdist)}, + {__Pyx_NAMESTR("pairwise"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_17pairwise, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_16pairwise)}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_DistanceMetric = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.DistanceMetric"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("DistanceMetric class\n\n This class provides a uniform interface to fast distance metric\n functions. The various metrics can be accessed via the `get_metric`\n class method and the metric string identifier (see below).\n For example, to use the Euclidean distance:\n\n >>> dist = DistanceMetric.get_metric('euclidean')\n >>> X = [[0, 1, 2],\n [3, 4, 5]])\n >>> dist.pairwise(X)\n array([[ 0. , 5.19615242],\n [ 5.19615242, 0. ]])\n\n Available Metrics\n The following lists the string metric identifiers and the associated\n distance metric classes:\n\n **Metrics intended for real-valued vector spaces:**\n\n ============== ==================== ======== ===============================\n identifier class name args distance function\n -------------- -------------------- -------- -------------------------------\n \"euclidean\" EuclideanDistance - ``sqrt(sum((x - y)^2))``\n \"manhattan\" ManhattanDistance - ``sum(|x - y|)``\n \"chebyshev\" ChebyshevDistance - ``sum(max(|x - y|))``\n \"minkowski\" MinkowskiDistance p ``sum(|x - y|^p)^(1/p)``\n \"wminkowski\" WMinkowskiDistance p, w ``sum(w * |x - y|^p)^(1/p)``\n \"seuclidean\" SEuclideanDistance V ``sqrt(sum((x - y)^2 / V))``\n \"mahalanobis\" MahalanobisDistance V or VI ``sqrt((x - y)' V^-1 (x - y))``\n ============== ==================== ======== ===============================\n\n **Metrics intended for two-dimensional vector spaces:**\n\n ============ ================== ========================================\n identifier class name distance function\n ------------ ------------------ ----------------------------------------\n \"haversine\" HaversineDistance 2 arcsin(sqrt(sin^2(0.5*dx)\n + cos(x1)cos(x2)sin^2(0.5*dy)))\n ============ ================== ========================================\n\n\n **Metrics intended for integer-valued vector spaces:** Though intended\n for integer-valued vectors, these are also valid metrics in the case of\n real-valued vectors.\n\n ============= ==================== ========================================\n identifier class name distance function\n ------------- -------------------- ----------------------------------------\n \"hamming\" HammingDistance ``N_unequal(x, y) / N_tot``\n \"canberra\" CanberraDistance ``sum(|x - y| / (|x| + |y|))``\n \"braycurtis\" BrayCurtisDistance ``sum(|x - y|) / (sum(|x|) + sum(|y|))``\n ============= ==================== ========================================\n\n **Metrics intended for boolean-valued vector spaces:** Any nonzero entry\n is evaluated to \"True\". In the listings below, the following\n abbreviations are used:\n\n - N : number of dimensions\n - NTT : number of dims in which both values are True\n - NTF : number of dims in which the first value is True, second is False\n - NFT : number of dims in which the first value is False, second is True\n - NFF : number of dims in which both values are False\n - NNEQ : number of non-equal dimensions, NNEQ = NTF + NFT\n - NNZ : number of nonzero dimensions, NNZ = NTF + NFT + NTT\n\n ================= ======================= ===============================\n identifier class name distance function\n ----------------- ----------------------- -------------------------------\n \"jaccard\" JaccardDistance NNEQ / NNZ\n \"maching\" MatchingDistance NNEQ / N\n \"dice\" DiceDistance NNEQ / (NTT + NNZ)\n \"kulsinski\" KulsinskiDistance (NNEQ + N - NTT) / (NNEQ + N)\n \"rogerstanimoto\" RogersTanimotoDistance 2 * NNEQ / (N + NNEQ)\n \"russellrao\" RussellRaoDistance NNZ / N\n \"sokalmichener\" SokalMichenerDistance 2 * NNEQ / (N + NNEQ)\n \"sokalsneath\" SokalSneathDistance NNEQ / (NNEQ + 0.5 * NTT)\n ================= ======================= ===============================\n\n **User-defined distance:**\n\n =========== =============== =======\n identifier class name args\n ----------- --------------- -------\n \"pyfunc\" PyFuncDistance func\n =========== =============== =======\n\n Here ``func`` is a function which takes two one-dimensional numpy\n arrays, and returns a distance. Note that in order to be used within\n the BallTree, the distance must be a true metric:\n i.e. it must satisfy the following properties\n\n 1) Non-negativity: d(x, y) >= 0\n 2) Identity: d(x, y) = 0 if and only if x == y\n 3) Symmetry: d(x, y) = d(y, x)\n 4) Triangle Inequality: d(x, y) + d(y, z) >= d(x, z)\n\n Because of the Python object overhead involved in calling the python\n function, this will be fairly slow, but it will have the same\n scaling as other distances.\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; + +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryview_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryview_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_memoryview; + p->obj = Py_None; Py_INCREF(Py_None); + p->_size = Py_None; Py_INCREF(Py_None); + p->_array_interface = Py_None; Py_INCREF(Py_None); + p->view.obj = NULL; + if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryview___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->obj); + Py_CLEAR(p->_size); + Py_CLEAR(p->_array_interface); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + if (p->obj) { + e = (*v)(p->obj, a); if (e) return e; + } + if (p->_size) { + e = (*v)(p->_size, a); if (e) return e; + } + if (p->_array_interface) { + e = (*v)(p->_array_interface, a); if (e) return e; + } + if (p->view.obj) { + e = (*v)(p->view.obj, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->obj); + p->obj = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_size); + p->_size = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_array_interface); + p->_array_interface = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + Py_CLEAR(p->view.obj); + return 0; +} +static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_memoryview___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_transpose(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview__get__base(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_shape(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_strides(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_suboffsets(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_ndim(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_itemsize(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_nbytes(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_size(o); +} + +static PyMethodDef __pyx_methods_memoryview[] = { + {__Pyx_NAMESTR("is_c_contig"), (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("is_f_contig"), (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy"), (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy_fortran"), (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_memoryview[] = { + {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, + {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, + {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, + {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, + {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, + {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, + {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, + {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_memoryview = { + __pyx_memoryview___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_memoryview, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_memoryview = { + __pyx_memoryview___len__, /*mp_length*/ + __pyx_memoryview___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_memoryview = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_memoryview_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_memoryview = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.memoryview"), /*tp_name*/ + sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_memoryview___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_memoryview___str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_memoryview, /*tp_traverse*/ + __pyx_tp_clear_memoryview, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_memoryview, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_memoryview, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_memoryview, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.KulsinskiDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Kulsinski Distance\n\n Kulsinski Distance is a dissimilarity measure for boolean-valued\n vectors. All nonzero entries will be treated as True, zero entries will\n be treated as False.\n\n .. math::\n D(x, y) = 1 - \014rac{N_{TT}}{N + N_{TF} + N_{FT}}\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.SokalSneathDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Sokal-Sneath Distance\n\n Sokal-Sneath Distance is a dissimilarity measure for boolean-valued\n vectors. All nonzero entries will be treated as True, zero entries will\n be treated as False.\n\n .. math::\n D(x, y) = \014rac{N_{TF} + N_{FT}}{N_{TT} / 2 + N_{TF} + N_{FT}}\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance[] = { + {__Pyx_NAMESTR("rdist_to_dist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_3rdist_to_dist, METH_O, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("dist_to_rdist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_5dist_to_rdist, METH_O, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.SEuclideanDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Standardized Euclidean Distance metric\n\n .. math::\n D(x, y) = \\sqrt{ \\sum_i \014rac{ (x_i - y_i) ^ 2}{V_i} }\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_JaccardDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_JaccardDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_JaccardDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_JaccardDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_JaccardDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_JaccardDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_JaccardDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_JaccardDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.JaccardDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_JaccardDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Jaccard Distance\n\n Jaccard Distance is a dissimilarity measure for boolean-valued\n vectors. All nonzero entries will be treated as True, zero entries will\n be treated as False.\n\n .. math::\n D(x, y) = \014rac{N_{TF} + N_{FT}}{N_{TT} + N_{TF} + N_{FT}}\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_JaccardDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_JaccardDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_HammingDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_HammingDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_HammingDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HammingDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HammingDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_HammingDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_HammingDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_HammingDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.HammingDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HammingDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Hamming Distance\n\n Hamming distance is meant for discrete-valued vectors, though it is\n a valid metric for real-valued vectors.\n\n .. math::\n D(x, y) = \014rac{1}{N} \\sum_i \\delta_{x_i, y_i}\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_HammingDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_HammingDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.BrayCurtisDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Bray-Curtis Distance\n\n Bray-Curtis distance is meant for discrete-valued vectors, though it is\n a valid metric for real-valued vectors.\n\n .. math::\n D(x, y) = \014rac{\\sum_i |x_i - y_i|}{\\sum_i(|x_i| + |y_i|)}\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_CanberraDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_CanberraDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_CanberraDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_CanberraDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_CanberraDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_CanberraDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_CanberraDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_CanberraDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.CanberraDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_CanberraDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Canberra Distance\n\n Canberra distance is meant for discrete-valued vectors, though it is\n a valid metric for real-valued vectors.\n\n .. math::\n D(x, y) = \\sum_i \014rac{|x_i - y_i|}{|x_i| + |y_i|}\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_CanberraDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_CanberraDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.RussellRaoDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Russell-Rao Distance\n\n Russell-Rao Distance is a dissimilarity measure for boolean-valued\n vectors. All nonzero entries will be treated as True, zero entries will\n be treated as False.\n\n .. math::\n D(x, y) = \014rac{N - N_{TT}}{N}\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_EuclideanDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_EuclideanDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_EuclideanDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_EuclideanDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_EuclideanDistance[] = { + {__Pyx_NAMESTR("rdist_to_dist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_3rdist_to_dist, METH_O, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("dist_to_rdist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_5dist_to_rdist, METH_O, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_EuclideanDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.EuclideanDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_EuclideanDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Euclidean Distance metric\n\n .. math::\n D(x, y) = \\sqrt{ \\sum_i (x_i - y_i) ^ 2 }\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_EuclideanDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_EuclideanDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance[] = { + {__Pyx_NAMESTR("rdist_to_dist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_3rdist_to_dist, METH_O, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("dist_to_rdist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_5dist_to_rdist, METH_O, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.WMinkowskiDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Weighted Minkowski Distance\n\n .. math::\n D(x, y) = [\\sum_i w_i (x_i - y_i)^p] ^ (1/p)\n\n Weighted Minkowski Distance requires p >= 1 and finite.\n\n Parameters\n ----------\n p : int\n The order of the norm of the difference :math:`{||u-v||}_p`.\n w : (N,) array_like\n The weight vector.\n\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance[] = { + {__Pyx_NAMESTR("rdist_to_dist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_3rdist_to_dist, METH_O, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("dist_to_rdist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_5dist_to_rdist, METH_O, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.MinkowskiDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Minkowski Distance\n\n .. math::\n D(x, y) = [\\sum_i (x_i - y_i)^p] ^ (1/p)\n\n Minkowski Distance requires p >= 1 and finite. For p = infinity,\n use ChebyshevDistance.\n Note that for p=1, ManhattanDistance is more efficient, and for\n p=2, EuclideanDistance is more efficient.\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance[] = { + {__Pyx_NAMESTR("rdist_to_dist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_3rdist_to_dist, METH_O, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("dist_to_rdist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_5dist_to_rdist, METH_O, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.MahalanobisDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Mahalanobis Distance\n\n .. math::\n D(x, y) = \\sqrt{ (x - y)^T V^{-1} (x - y) }\n\n Parameters\n ----------\n V : array_like\n Symmetric positive-definite covariance matrix.\n The inverse of this matrix will be explicitly computed.\n VI : array_like\n optionally specify the inverse directly. If VI is passed,\n then V is not referenced.\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_ManhattanDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_ManhattanDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_ManhattanDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ManhattanDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ManhattanDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_ManhattanDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_ManhattanDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_ManhattanDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.ManhattanDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ManhattanDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Manhattan/City-block Distance metric\n\n .. math::\n D(x, y) = \\sum_i |x_i - y_i|\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_ManhattanDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_12dist_metrics_17ManhattanDistance_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_ManhattanDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.SokalMichenerDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Sokal-Michener Distance\n\n Sokal-Michener Distance is a dissimilarity measure for boolean-valued\n vectors. All nonzero entries will be treated as True, zero entries will\n be treated as False.\n\n .. math::\n D(x, y) = \014rac{2 (N_{TF} + N_{FT})}{N + N_{TF} + N_{FT}}\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_array_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_array_obj *)o); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_array___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->mode); + Py_CLEAR(p->_format); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_array(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + if (p->mode) { + e = (*v)(p->mode, a); if (e) return e; + } + if (p->_format) { + e = (*v)(p->_format, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->mode); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_format); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} +static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_array___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { + PyObject *v = PyObject_GenericGetAttr(o, n); + if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + v = __pyx_array___getattr__(o, n); + } + return v; +} + +static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { + return get_memview(o); +} + +static PyMethodDef __pyx_methods_array[] = { + {__Pyx_NAMESTR("__getattr__"), (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_array[] = { + {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_array = { + 0, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_array, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_array = { + 0, /*mp_length*/ + __pyx_array___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_array = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_array_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_array = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.array"), /*tp_name*/ + sizeof(struct __pyx_array_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_array, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + __pyx_tp_getattro_array, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_array, /*tp_traverse*/ + __pyx_tp_clear_array, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_array, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_array, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_array, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; + +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryviewslice_obj *p; + PyObject *o = __pyx_tp_new_memoryview(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryviewslice_obj *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; + p->from_object = Py_None; Py_INCREF(Py_None); + p->from_slice.memview = NULL; + return o; +} + +static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryviewslice___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->from_object); + PyObject_GC_Track(o); + __pyx_tp_dealloc_memoryview(o); +} + +static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; + if (p->from_object) { + e = (*v)(p->from_object, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + PyObject* tmp; + __pyx_tp_clear_memoryview(o); + tmp = ((PyObject*)p->from_object); + p->from_object = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + __PYX_XDEC_MEMVIEW(&p->from_slice, 1); + return 0; +} + +static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryviewslice__get__base(o); +} + +static PyMethodDef __pyx_methods__memoryviewslice[] = { + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { + {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_memoryviewslice = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics._memoryviewslice"), /*tp_name*/ + sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___repr__, /*tp_repr*/ + #else + 0, /*tp_repr*/ + #endif + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___str__, /*tp_str*/ + #else + 0, /*tp_str*/ + #endif + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Internal class for passing memoryview slices to Python"), /*tp_doc*/ + __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ + __pyx_tp_clear__memoryviewslice, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods__memoryviewslice, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets__memoryviewslice, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new__memoryviewslice, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.RogersTanimotoDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Rogers-Tanimoto Distance\n\n Rogers-Tanimoto Distance is a dissimilarity measure for boolean-valued\n vectors. All nonzero entries will be treated as True, zero entries will\n be treated as False.\n\n .. math::\n D(x, y) = \014rac{2 (N_{TF} + N_{FT})}{N + N_{TF} + N_{FT}}\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_PyFuncDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_PyFuncDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_PyFuncDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_PyFuncDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_PyFuncDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_PyFuncDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_PyFuncDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_PyFuncDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.PyFuncDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_PyFuncDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("PyFunc Distance\n\n A user-defined distance\n\n Parameters\n ----------\n func : function\n func should take two numpy arrays as input, and return a distance.\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_PyFuncDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14PyFuncDistance_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_PyFuncDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_MatchingDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MatchingDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_MatchingDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MatchingDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MatchingDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MatchingDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_MatchingDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_MatchingDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.MatchingDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_MatchingDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Matching Distance\n\n Matching Distance is a dissimilarity measure for boolean-valued\n vectors. All nonzero entries will be treated as True, zero entries will\n be treated as False.\n\n .. math::\n D(x, y) = \014rac{N_{TF} + N_{FT}}{N}\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_MatchingDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_MatchingDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.ChebyshevDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Chebyshev/Infinity Distance\n\n .. math::\n D(x, y) = max_i (|x_i - y_i|)\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_12dist_metrics_17ChebyshevDistance_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_HaversineDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_HaversineDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_HaversineDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_HaversineDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_HaversineDistance[] = { + {__Pyx_NAMESTR("rdist_to_dist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_1rdist_to_dist, METH_O, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("dist_to_rdist"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_3dist_to_rdist, METH_O, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_HaversineDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.HaversineDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_HaversineDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Haversine (Spherical) Distance\n\n The Haversine distance is the angular distance between two points on\n the surface of a sphere. The first distance of each point is assumed\n to be the latitude, the second is the longitude, given in radians.\n The dimension of the points must be 2:\n\n .. math::\n D(x, y) = 2\007rcsin[\\sqrt{\\sin^2((x1 - y1) / 2)\n + cos(x1)cos(y1)sin^2((x2 - y2) / 2)}]\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_HaversineDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_HaversineDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DiceDistance __pyx_vtable_7sklearn_9neighbors_12dist_metrics_DiceDistance; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DiceDistance(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DiceDistance *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DistanceMetric(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DiceDistance *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DiceDistance; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_12dist_metrics_DiceDistance[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_12dist_metrics_DiceDistance = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.dist_metrics.DiceDistance"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DiceDistance), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Dice Distance\n\n Dice Distance is a dissimilarity measure for boolean-valued\n vectors. All nonzero entries will be treated as True, zero entries will\n be treated as False.\n\n .. math::\n D(x, y) = \014rac{N_{TF} + N_{FT}}{2 * N_{TT} + N_{TF} + N_{FT}}\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_12dist_metrics_DistanceMetric, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_12dist_metrics_DiceDistance, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_11__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_12dist_metrics_DiceDistance, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + __Pyx_NAMESTR("dist_metrics"), + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_s_10, __pyx_k_10, sizeof(__pyx_k_10), 0, 0, 1, 0}, + {&__pyx_kp_s_101, __pyx_k_101, sizeof(__pyx_k_101), 0, 0, 1, 0}, + {&__pyx_kp_s_103, __pyx_k_103, sizeof(__pyx_k_103), 0, 0, 1, 0}, + {&__pyx_kp_s_12, __pyx_k_12, sizeof(__pyx_k_12), 0, 0, 1, 0}, + {&__pyx_kp_s_14, __pyx_k_14, sizeof(__pyx_k_14), 0, 0, 1, 0}, + {&__pyx_kp_s_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 0, 1, 0}, + {&__pyx_kp_s_19, __pyx_k_19, sizeof(__pyx_k_19), 0, 0, 1, 0}, + {&__pyx_kp_s_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 1, 0}, + {&__pyx_kp_s_23, __pyx_k_23, sizeof(__pyx_k_23), 0, 0, 1, 0}, + {&__pyx_kp_s_25, __pyx_k_25, sizeof(__pyx_k_25), 0, 0, 1, 0}, + {&__pyx_kp_s_29, __pyx_k_29, sizeof(__pyx_k_29), 0, 0, 1, 0}, + {&__pyx_kp_s_31, __pyx_k_31, sizeof(__pyx_k_31), 0, 0, 1, 0}, + {&__pyx_kp_u_33, __pyx_k_33, sizeof(__pyx_k_33), 0, 1, 0, 0}, + {&__pyx_kp_u_35, __pyx_k_35, sizeof(__pyx_k_35), 0, 1, 0, 0}, + {&__pyx_kp_u_37, __pyx_k_37, sizeof(__pyx_k_37), 0, 1, 0, 0}, + {&__pyx_kp_u_39, __pyx_k_39, sizeof(__pyx_k_39), 0, 1, 0, 0}, + {&__pyx_kp_s_4, __pyx_k_4, sizeof(__pyx_k_4), 0, 0, 1, 0}, + {&__pyx_kp_u_40, __pyx_k_40, sizeof(__pyx_k_40), 0, 1, 0, 0}, + {&__pyx_kp_u_43, __pyx_k_43, sizeof(__pyx_k_43), 0, 1, 0, 0}, + {&__pyx_kp_s_45, __pyx_k_45, sizeof(__pyx_k_45), 0, 0, 1, 0}, + {&__pyx_kp_s_47, __pyx_k_47, sizeof(__pyx_k_47), 0, 0, 1, 0}, + {&__pyx_kp_s_50, __pyx_k_50, sizeof(__pyx_k_50), 0, 0, 1, 0}, + {&__pyx_kp_s_52, __pyx_k_52, sizeof(__pyx_k_52), 0, 0, 1, 0}, + {&__pyx_kp_s_53, __pyx_k_53, sizeof(__pyx_k_53), 0, 0, 1, 0}, + {&__pyx_kp_s_55, __pyx_k_55, sizeof(__pyx_k_55), 0, 0, 1, 0}, + {&__pyx_kp_s_57, __pyx_k_57, sizeof(__pyx_k_57), 0, 0, 1, 0}, + {&__pyx_kp_s_59, __pyx_k_59, sizeof(__pyx_k_59), 0, 0, 1, 0}, + {&__pyx_kp_s_6, __pyx_k_6, sizeof(__pyx_k_6), 0, 0, 1, 0}, + {&__pyx_kp_s_61, __pyx_k_61, sizeof(__pyx_k_61), 0, 0, 1, 0}, + {&__pyx_kp_s_63, __pyx_k_63, sizeof(__pyx_k_63), 0, 0, 1, 0}, + {&__pyx_kp_s_64, __pyx_k_64, sizeof(__pyx_k_64), 0, 0, 1, 0}, + {&__pyx_kp_s_67, __pyx_k_67, sizeof(__pyx_k_67), 0, 0, 1, 0}, + {&__pyx_kp_s_69, __pyx_k_69, sizeof(__pyx_k_69), 0, 0, 1, 0}, + {&__pyx_kp_s_74, __pyx_k_74, sizeof(__pyx_k_74), 0, 0, 1, 0}, + {&__pyx_kp_s_76, __pyx_k_76, sizeof(__pyx_k_76), 0, 0, 1, 0}, + {&__pyx_kp_b_78, __pyx_k_78, sizeof(__pyx_k_78), 0, 0, 0, 0}, + {&__pyx_kp_b_79, __pyx_k_79, sizeof(__pyx_k_79), 0, 0, 0, 0}, + {&__pyx_kp_s_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 0, 1, 0}, + {&__pyx_kp_b_80, __pyx_k_80, sizeof(__pyx_k_80), 0, 0, 0, 0}, + {&__pyx_kp_b_81, __pyx_k_81, sizeof(__pyx_k_81), 0, 0, 0, 0}, + {&__pyx_kp_b_82, __pyx_k_82, sizeof(__pyx_k_82), 0, 0, 0, 0}, + {&__pyx_kp_u_83, __pyx_k_83, sizeof(__pyx_k_83), 0, 1, 0, 0}, + {&__pyx_kp_u_84, __pyx_k_84, sizeof(__pyx_k_84), 0, 1, 0, 0}, + {&__pyx_kp_s_87, __pyx_k_87, sizeof(__pyx_k_87), 0, 0, 1, 0}, + {&__pyx_n_s_88, __pyx_k_88, sizeof(__pyx_k_88), 0, 0, 1, 1}, + {&__pyx_n_s_91, __pyx_k_91, sizeof(__pyx_k_91), 0, 0, 1, 1}, + {&__pyx_kp_u_92, __pyx_k_92, sizeof(__pyx_k_92), 0, 1, 0, 0}, + {&__pyx_kp_u_93, __pyx_k_93, sizeof(__pyx_k_93), 0, 1, 0, 0}, + {&__pyx_kp_s_95, __pyx_k_95, sizeof(__pyx_k_95), 0, 0, 1, 0}, + {&__pyx_kp_s_97, __pyx_k_97, sizeof(__pyx_k_97), 0, 0, 1, 0}, + {&__pyx_kp_s_99, __pyx_k_99, sizeof(__pyx_k_99), 0, 0, 1, 0}, + {&__pyx_n_s__ASCII, __pyx_k__ASCII, sizeof(__pyx_k__ASCII), 0, 0, 1, 1}, + {&__pyx_n_s__C, __pyx_k__C, sizeof(__pyx_k__C), 0, 0, 1, 1}, + {&__pyx_n_s__DTYPE, __pyx_k__DTYPE, sizeof(__pyx_k__DTYPE), 0, 0, 1, 1}, + {&__pyx_n_s__Ellipsis, __pyx_k__Ellipsis, sizeof(__pyx_k__Ellipsis), 0, 0, 1, 1}, + {&__pyx_n_s__ITYPE, __pyx_k__ITYPE, sizeof(__pyx_k__ITYPE), 0, 0, 1, 1}, + {&__pyx_n_s__IndexError, __pyx_k__IndexError, sizeof(__pyx_k__IndexError), 0, 0, 1, 1}, + {&__pyx_n_s__L, __pyx_k__L, sizeof(__pyx_k__L), 0, 0, 1, 1}, + {&__pyx_n_s__METRIC_MAPPING, __pyx_k__METRIC_MAPPING, sizeof(__pyx_k__METRIC_MAPPING), 0, 0, 1, 1}, + {&__pyx_n_s__MemoryError, __pyx_k__MemoryError, sizeof(__pyx_k__MemoryError), 0, 0, 1, 1}, + {&__pyx_n_s__NotImplementedError, __pyx_k__NotImplementedError, sizeof(__pyx_k__NotImplementedError), 0, 0, 1, 1}, + {&__pyx_n_b__O, __pyx_k__O, sizeof(__pyx_k__O), 0, 0, 0, 1}, + {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s__TypeError, __pyx_k__TypeError, sizeof(__pyx_k__TypeError), 0, 0, 1, 1}, + {&__pyx_n_s__V, __pyx_k__V, sizeof(__pyx_k__V), 0, 0, 1, 1}, + {&__pyx_n_s__VI, __pyx_k__VI, sizeof(__pyx_k__VI), 0, 0, 1, 1}, + {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, + {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, + {&__pyx_n_s__Y, __pyx_k__Y, sizeof(__pyx_k__Y), 0, 0, 1, 1}, + {&__pyx_n_s____class__, __pyx_k____class__, sizeof(__pyx_k____class__), 0, 0, 1, 1}, + {&__pyx_n_s____getstate__, __pyx_k____getstate__, sizeof(__pyx_k____getstate__), 0, 0, 1, 1}, + {&__pyx_n_s____import__, __pyx_k____import__, sizeof(__pyx_k____import__), 0, 0, 1, 1}, + {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, + {&__pyx_n_s____name__, __pyx_k____name__, sizeof(__pyx_k____name__), 0, 0, 1, 1}, + {&__pyx_n_s____new__, __pyx_k____new__, sizeof(__pyx_k____new__), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_getbuffer, __pyx_k____pyx_getbuffer, sizeof(__pyx_k____pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_releasebuffer, __pyx_k____pyx_releasebuffer, sizeof(__pyx_k____pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_vtable__, __pyx_k____pyx_vtable__, sizeof(__pyx_k____pyx_vtable__), 0, 0, 1, 1}, + {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, + {&__pyx_n_s__allocate_buffer, __pyx_k__allocate_buffer, sizeof(__pyx_k__allocate_buffer), 0, 0, 1, 1}, + {&__pyx_n_s__arcsin, __pyx_k__arcsin, sizeof(__pyx_k__arcsin), 0, 0, 1, 1}, + {&__pyx_n_s__asarray, __pyx_k__asarray, sizeof(__pyx_k__asarray), 0, 0, 1, 1}, + {&__pyx_n_s__base, __pyx_k__base, sizeof(__pyx_k__base), 0, 0, 1, 1}, + {&__pyx_n_s__braycurtis, __pyx_k__braycurtis, sizeof(__pyx_k__braycurtis), 0, 0, 1, 1}, + {&__pyx_n_b__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 0, 0, 1}, + {&__pyx_n_s__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 0, 1, 1}, + {&__pyx_n_u__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 1, 0, 1}, + {&__pyx_n_s__canberra, __pyx_k__canberra, sizeof(__pyx_k__canberra), 0, 0, 1, 1}, + {&__pyx_n_s__chebyshev, __pyx_k__chebyshev, sizeof(__pyx_k__chebyshev), 0, 0, 1, 1}, + {&__pyx_n_s__cityblock, __pyx_k__cityblock, sizeof(__pyx_k__cityblock), 0, 0, 1, 1}, + {&__pyx_n_s__decode, __pyx_k__decode, sizeof(__pyx_k__decode), 0, 0, 1, 1}, + {&__pyx_n_s__dice, __pyx_k__dice, sizeof(__pyx_k__dice), 0, 0, 1, 1}, + {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, + {&__pyx_n_s__dtype_is_object, __pyx_k__dtype_is_object, sizeof(__pyx_k__dtype_is_object), 0, 0, 1, 1}, + {&__pyx_n_s__encode, __pyx_k__encode, sizeof(__pyx_k__encode), 0, 0, 1, 1}, + {&__pyx_n_s__enumerate, __pyx_k__enumerate, sizeof(__pyx_k__enumerate), 0, 0, 1, 1}, + {&__pyx_n_s__error, __pyx_k__error, sizeof(__pyx_k__error), 0, 0, 1, 1}, + {&__pyx_n_s__euclidean, __pyx_k__euclidean, sizeof(__pyx_k__euclidean), 0, 0, 1, 1}, + {&__pyx_n_s__extend, __pyx_k__extend, sizeof(__pyx_k__extend), 0, 0, 1, 1}, + {&__pyx_n_s__flags, __pyx_k__flags, sizeof(__pyx_k__flags), 0, 0, 1, 1}, + {&__pyx_n_s__format, __pyx_k__format, sizeof(__pyx_k__format), 0, 0, 1, 1}, + {&__pyx_n_b__fortran, __pyx_k__fortran, sizeof(__pyx_k__fortran), 0, 0, 0, 1}, + {&__pyx_n_s__fortran, __pyx_k__fortran, sizeof(__pyx_k__fortran), 0, 0, 1, 1}, + {&__pyx_n_s__func, __pyx_k__func, sizeof(__pyx_k__func), 0, 0, 1, 1}, + {&__pyx_n_s__get_metric, __pyx_k__get_metric, sizeof(__pyx_k__get_metric), 0, 0, 1, 1}, + {&__pyx_n_s__hamming, __pyx_k__hamming, sizeof(__pyx_k__hamming), 0, 0, 1, 1}, + {&__pyx_n_s__haversine, __pyx_k__haversine, sizeof(__pyx_k__haversine), 0, 0, 1, 1}, + {&__pyx_n_s__id, __pyx_k__id, sizeof(__pyx_k__id), 0, 0, 1, 1}, + {&__pyx_n_s__inf, __pyx_k__inf, sizeof(__pyx_k__inf), 0, 0, 1, 1}, + {&__pyx_n_s__infinity, __pyx_k__infinity, sizeof(__pyx_k__infinity), 0, 0, 1, 1}, + {&__pyx_n_s__inv, __pyx_k__inv, sizeof(__pyx_k__inv), 0, 0, 1, 1}, + {&__pyx_n_s__isinf, __pyx_k__isinf, sizeof(__pyx_k__isinf), 0, 0, 1, 1}, + {&__pyx_n_s__items, __pyx_k__items, sizeof(__pyx_k__items), 0, 0, 1, 1}, + {&__pyx_n_s__itemsize, __pyx_k__itemsize, sizeof(__pyx_k__itemsize), 0, 0, 1, 1}, + {&__pyx_n_s__jaccard, __pyx_k__jaccard, sizeof(__pyx_k__jaccard), 0, 0, 1, 1}, + {&__pyx_n_s__join, __pyx_k__join, sizeof(__pyx_k__join), 0, 0, 1, 1}, + {&__pyx_n_s__key, __pyx_k__key, sizeof(__pyx_k__key), 0, 0, 1, 1}, + {&__pyx_n_s__kulsinski, __pyx_k__kulsinski, sizeof(__pyx_k__kulsinski), 0, 0, 1, 1}, + {&__pyx_n_s__l1, __pyx_k__l1, sizeof(__pyx_k__l1), 0, 0, 1, 1}, + {&__pyx_n_s__l2, __pyx_k__l2, sizeof(__pyx_k__l2), 0, 0, 1, 1}, + {&__pyx_n_s__linalg, __pyx_k__linalg, sizeof(__pyx_k__linalg), 0, 0, 1, 1}, + {&__pyx_n_s__mahalanobis, __pyx_k__mahalanobis, sizeof(__pyx_k__mahalanobis), 0, 0, 1, 1}, + {&__pyx_n_s__manhattan, __pyx_k__manhattan, sizeof(__pyx_k__manhattan), 0, 0, 1, 1}, + {&__pyx_n_s__matching, __pyx_k__matching, sizeof(__pyx_k__matching), 0, 0, 1, 1}, + {&__pyx_n_s__memview, __pyx_k__memview, sizeof(__pyx_k__memview), 0, 0, 1, 1}, + {&__pyx_n_s__metric, __pyx_k__metric, sizeof(__pyx_k__metric), 0, 0, 1, 1}, + {&__pyx_n_s__minkowski, __pyx_k__minkowski, sizeof(__pyx_k__minkowski), 0, 0, 1, 1}, + {&__pyx_n_s__mode, __pyx_k__mode, sizeof(__pyx_k__mode), 0, 0, 1, 1}, + {&__pyx_n_s__name, __pyx_k__name, sizeof(__pyx_k__name), 0, 0, 1, 1}, + {&__pyx_n_s__ndim, __pyx_k__ndim, sizeof(__pyx_k__ndim), 0, 0, 1, 1}, + {&__pyx_n_s__newObj, __pyx_k__newObj, sizeof(__pyx_k__newObj), 0, 0, 1, 1}, + {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, + {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, + {&__pyx_n_s__obj, __pyx_k__obj, sizeof(__pyx_k__obj), 0, 0, 1, 1}, + {&__pyx_n_s__order, __pyx_k__order, sizeof(__pyx_k__order), 0, 0, 1, 1}, + {&__pyx_n_s__p, __pyx_k__p, sizeof(__pyx_k__p), 0, 0, 1, 1}, + {&__pyx_n_s__pack, __pyx_k__pack, sizeof(__pyx_k__pack), 0, 0, 1, 1}, + {&__pyx_n_s__pop, __pyx_k__pop, sizeof(__pyx_k__pop), 0, 0, 1, 1}, + {&__pyx_n_s__pyfunc, __pyx_k__pyfunc, sizeof(__pyx_k__pyfunc), 0, 0, 1, 1}, + {&__pyx_n_s__random, __pyx_k__random, sizeof(__pyx_k__random), 0, 0, 1, 1}, + {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, + {&__pyx_n_s__rogerstanimoto, __pyx_k__rogerstanimoto, sizeof(__pyx_k__rogerstanimoto), 0, 0, 1, 1}, + {&__pyx_n_s__russellrao, __pyx_k__russellrao, sizeof(__pyx_k__russellrao), 0, 0, 1, 1}, + {&__pyx_n_s__seuclidean, __pyx_k__seuclidean, sizeof(__pyx_k__seuclidean), 0, 0, 1, 1}, + {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, + {&__pyx_n_s__sin, __pyx_k__sin, sizeof(__pyx_k__sin), 0, 0, 1, 1}, + {&__pyx_n_s__size, __pyx_k__size, sizeof(__pyx_k__size), 0, 0, 1, 1}, + {&__pyx_n_s__sokalmichener, __pyx_k__sokalmichener, sizeof(__pyx_k__sokalmichener), 0, 0, 1, 1}, + {&__pyx_n_s__sokalsneath, __pyx_k__sokalsneath, sizeof(__pyx_k__sokalsneath), 0, 0, 1, 1}, + {&__pyx_n_s__sqrt, __pyx_k__sqrt, sizeof(__pyx_k__sqrt), 0, 0, 1, 1}, + {&__pyx_n_s__start, __pyx_k__start, sizeof(__pyx_k__start), 0, 0, 1, 1}, + {&__pyx_n_s__step, __pyx_k__step, sizeof(__pyx_k__step), 0, 0, 1, 1}, + {&__pyx_n_s__stop, __pyx_k__stop, sizeof(__pyx_k__stop), 0, 0, 1, 1}, + {&__pyx_n_s__struct, __pyx_k__struct, sizeof(__pyx_k__struct), 0, 0, 1, 1}, + {&__pyx_n_s__typedefs, __pyx_k__typedefs, sizeof(__pyx_k__typedefs), 0, 0, 1, 1}, + {&__pyx_n_s__unpack, __pyx_k__unpack, sizeof(__pyx_k__unpack), 0, 0, 1, 1}, + {&__pyx_n_s__val, __pyx_k__val, sizeof(__pyx_k__val), 0, 0, 1, 1}, + {&__pyx_n_s__w, __pyx_k__w, sizeof(__pyx_k__w), 0, 0, 1, 1}, + {&__pyx_n_s__wminkowski, __pyx_k__wminkowski, sizeof(__pyx_k__wminkowski), 0, 0, 1, 1}, + {&__pyx_n_s__xrange, __pyx_k__xrange, sizeof(__pyx_k__xrange), 0, 0, 1, 1}, + {&__pyx_n_s__zeros, __pyx_k__zeros, sizeof(__pyx_k__zeros), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_NotImplementedError = __Pyx_GetBuiltinName(__pyx_n_s__NotImplementedError); if (!__pyx_builtin_NotImplementedError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s__TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1079; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s__MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s__enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s__Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s__id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s__IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "sklearn/neighbors/dist_metrics.pyx":211 + * def __cinit__(self): + * self.p = 2 + * self.vec = np.zeros(1, dtype=DTYPE, order='c') # <<<<<<<<<<<<<< + * self.mat = np.zeros((1, 1), dtype=DTYPE, order='c') + * self.vec_ptr = get_vec_ptr(self.vec) + */ + __pyx_k_tuple_1 = PyTuple_Pack(1, __pyx_int_1); if (unlikely(!__pyx_k_tuple_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_1); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_1)); + + /* "sklearn/neighbors/dist_metrics.pyx":212 + * self.p = 2 + * self.vec = np.zeros(1, dtype=DTYPE, order='c') + * self.mat = np.zeros((1, 1), dtype=DTYPE, order='c') # <<<<<<<<<<<<<< + * self.vec_ptr = get_vec_ptr(self.vec) + * self.mat_ptr = get_mat_ptr(self.mat) + */ + __pyx_k_tuple_2 = PyTuple_Pack(2, __pyx_int_1, __pyx_int_1); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_2); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); + __pyx_k_tuple_3 = PyTuple_Pack(1, ((PyObject *)__pyx_k_tuple_2)); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_3); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_3)); + + /* "sklearn/neighbors/dist_metrics.pyx":270 + * # In Minkowski special cases, return more efficient methods + * if metric is MinkowskiDistance: + * p = kwargs.pop('p', 2) # <<<<<<<<<<<<<< + * if p == 1: + * return ManhattanDistance(**kwargs) + */ + __pyx_k_tuple_5 = PyTuple_Pack(2, ((PyObject *)__pyx_n_s__p), __pyx_int_2); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_5); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); + + /* "sklearn/neighbors/dist_metrics.pyx":284 + * def __init__(self): + * if self.__class__ is DistanceMetric: + * raise NotImplementedError("DistanceMetric is an abstract class") # <<<<<<<<<<<<<< + * + * cdef DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size) except -1: + */ + __pyx_k_tuple_7 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_6)); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_7); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); + + /* "sklearn/neighbors/dist_metrics.pyx":319 + * cdef ITYPE_t i1, i2 + * if X.shape[1] != Y.shape[1]: + * raise ValueError('X and Y must have the same second dimension') # <<<<<<<<<<<<<< + * for i1 in range(X.shape[0]): + * for i2 in range(Y.shape[0]): + */ + __pyx_k_tuple_9 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_8)); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_9); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); + + /* "sklearn/neighbors/dist_metrics.pyx":444 + * ITYPE_t size) except -1: + * if size != self.size: + * raise ValueError('SEuclidean dist: size of V does not match') # <<<<<<<<<<<<<< + * cdef DTYPE_t tmp, d=0 + * cdef np.intp_t j + */ + __pyx_k_tuple_11 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_10)); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_11); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); + + /* "sklearn/neighbors/dist_metrics.pyx":527 + * def __init__(self, p): + * if p < 1: + * raise ValueError("p must be greater than 1") # <<<<<<<<<<<<<< + * elif np.isinf(p): + * raise ValueError("MinkowskiDistance requires finite p. " + */ + __pyx_k_tuple_13 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_12)); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_13); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); + + /* "sklearn/neighbors/dist_metrics.pyx":529 + * raise ValueError("p must be greater than 1") + * elif np.isinf(p): + * raise ValueError("MinkowskiDistance requires finite p. " # <<<<<<<<<<<<<< + * "For p=inf, use ChebyshevDistance.") + * self.p = p + */ + __pyx_k_tuple_15 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_14)); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_15); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); + + /* "sklearn/neighbors/dist_metrics.pyx":579 + * def __init__(self, p, w): + * if p < 1: + * raise ValueError("p must be greater than 1") # <<<<<<<<<<<<<< + * elif np.isinf(p): + * raise ValueError("WMinkowskiDistance requires finite p. " + */ + __pyx_k_tuple_16 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_12)); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_16); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); + + /* "sklearn/neighbors/dist_metrics.pyx":581 + * raise ValueError("p must be greater than 1") + * elif np.isinf(p): + * raise ValueError("WMinkowskiDistance requires finite p. " # <<<<<<<<<<<<<< + * "For p=inf, use ChebyshevDistance.") + * self.p = p + */ + __pyx_k_tuple_18 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_17)); if (unlikely(!__pyx_k_tuple_18)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 581; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_18); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_18)); + + /* "sklearn/neighbors/dist_metrics.pyx":591 + * ITYPE_t size) except -1: + * if size != self.size: + * raise ValueError('WMinkowskiDistance dist: ' # <<<<<<<<<<<<<< + * 'size of w does not match') + * cdef DTYPE_t d=0 + */ + __pyx_k_tuple_20 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_19)); if (unlikely(!__pyx_k_tuple_20)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_20); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_20)); + + /* "sklearn/neighbors/dist_metrics.pyx":638 + * VI = np.linalg.inv(V) + * if VI.ndim != 2 or VI.shape[0] != VI.shape[1]: + * raise ValueError("V/VI must be square") # <<<<<<<<<<<<<< + * + * self.mat = np.asarray(VI, dtype=float, order='C') + */ + __pyx_k_tuple_22 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_21)); if (unlikely(!__pyx_k_tuple_22)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_22); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_22)); + + /* "sklearn/neighbors/dist_metrics.pyx":652 + * ITYPE_t size) except -1: + * if size != self.size: + * raise ValueError('Mahalanobis dist: size of V does not match') # <<<<<<<<<<<<<< + * + * cdef DTYPE_t tmp, d = 0 + */ + __pyx_k_tuple_24 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_23)); if (unlikely(!__pyx_k_tuple_24)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_24); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_24)); + + /* "sklearn/neighbors/dist_metrics.pyx":970 + * ITYPE_t size) except -1: + * if size != 2: + * raise ValueError("Haversine distance only valid in 2 dimensions") # <<<<<<<<<<<<<< + * cdef DTYPE_t sin_0 = sin(0.5 * (x1[0] - x2[0])) + * cdef DTYPE_t sin_1 = sin(0.5 * (x1[1] - x2[1])) + */ + __pyx_k_tuple_26 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_25)); if (unlikely(!__pyx_k_tuple_26)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 970; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_26); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_26)); + + /* "sklearn/neighbors/dist_metrics.pyx":978 + * ITYPE_t size) except -1: + * if size != 2: + * raise ValueError("Haversine distance only valid in 2 dimensions") # <<<<<<<<<<<<<< + * cdef DTYPE_t sin_0 = sin(0.5 * (x1[0] - x2[0])) + * cdef DTYPE_t sin_1 = sin(0.5 * (x1[1] - x2[1])) + */ + __pyx_k_tuple_27 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_25)); if (unlikely(!__pyx_k_tuple_27)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 978; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_27); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_27)); + + /* "sklearn/neighbors/dist_metrics.pyx":1076 + * def __init__(self, func, **kwargs): + * self.func = func + * x = np.random.random(10) # <<<<<<<<<<<<<< + * try: + * d = self.func(x, x, **kwargs) + */ + __pyx_k_tuple_28 = PyTuple_Pack(1, __pyx_int_10); if (unlikely(!__pyx_k_tuple_28)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_28); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_28)); + + /* "sklearn/neighbors/dist_metrics.pyx":1080 + * d = self.func(x, x, **kwargs) + * except TypeError: + * raise ValueError("func must be a callable taking two arrays") # <<<<<<<<<<<<<< + * + * try: + */ + __pyx_k_tuple_30 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_29)); if (unlikely(!__pyx_k_tuple_30)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1080; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_30); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_30)); + + /* "sklearn/neighbors/dist_metrics.pyx":1085 + * d = float(d) + * except TypeError: + * raise ValueError("func must return a float") # <<<<<<<<<<<<<< + * + * self.kwargs = kwargs + */ + __pyx_k_tuple_32 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_31)); if (unlikely(!__pyx_k_tuple_32)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_32); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_32)); + + /* "numpy.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_k_tuple_34 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_33)); if (unlikely(!__pyx_k_tuple_34)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_34); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_34)); + + /* "numpy.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_k_tuple_36 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_35)); if (unlikely(!__pyx_k_tuple_36)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_36); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_36)); + + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_k_tuple_38 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_37)); if (unlikely(!__pyx_k_tuple_38)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_38); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_38)); + + /* "numpy.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_k_tuple_41 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_40)); if (unlikely(!__pyx_k_tuple_41)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_41); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_41)); + + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_k_tuple_42 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_37)); if (unlikely(!__pyx_k_tuple_42)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_42); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_42)); + + /* "numpy.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_k_tuple_44 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_43)); if (unlikely(!__pyx_k_tuple_44)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_44); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_44)); + + /* "View.MemoryView":124 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if self.itemsize <= 0: + */ + __pyx_k_tuple_46 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_45)); if (unlikely(!__pyx_k_tuple_46)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_46); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_46)); + + /* "View.MemoryView":127 + * + * if self.itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * encode = getattr(format, 'encode', None) + */ + __pyx_k_tuple_48 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_47)); if (unlikely(!__pyx_k_tuple_48)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_48); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_48)); + + /* "View.MemoryView":131 + * encode = getattr(format, 'encode', None) + * if encode: + * format = encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format + * self.format = self._format + */ + __pyx_k_tuple_49 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__ASCII)); if (unlikely(!__pyx_k_tuple_49)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_49); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_49)); + + /* "View.MemoryView":141 + * free(self._shape) + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_51 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_50)); if (unlikely(!__pyx_k_tuple_51)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_51); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_51)); + + /* "View.MemoryView":166 + * decode = getattr(mode, 'decode', None) + * if decode: + * mode = decode('ASCII') # <<<<<<<<<<<<<< + * self.mode = mode + * + */ + __pyx_k_tuple_54 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__ASCII)); if (unlikely(!__pyx_k_tuple_54)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_54); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_54)); + + /* "View.MemoryView":174 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_k_tuple_56 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_55)); if (unlikely(!__pyx_k_tuple_56)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_56); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_56)); + + /* "View.MemoryView":190 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_k_tuple_58 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_57)); if (unlikely(!__pyx_k_tuple_58)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_58); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_58)); + + /* "View.MemoryView":452 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_k_tuple_60 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_59)); if (unlikely(!__pyx_k_tuple_60)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_60); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_60)); + + /* "View.MemoryView":528 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_k_tuple_62 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_61)); if (unlikely(!__pyx_k_tuple_62)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_62); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_62)); + + /* "View.MemoryView":643 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_k_tuple_65 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_65)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_65); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_65)); + + /* "View.MemoryView":646 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_k_tuple_66 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_66)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_66); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_66)); + + /* "View.MemoryView":657 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_k_tuple_68 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_68)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_68); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_68)); + + /* "View.MemoryView":665 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_70 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_69)); if (unlikely(!__pyx_k_tuple_70)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_70); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_70)); + + /* "sklearn/neighbors/dist_metrics.pyx":58 + * # newObj function + * # this is a helper function for pickling + * def newObj(obj): # <<<<<<<<<<<<<< + * return obj.__new__(obj) + * + */ + __pyx_k_tuple_85 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__obj)); if (unlikely(!__pyx_k_tuple_85)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_85); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_85)); + __pyx_k_codeobj_86 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_85, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_87, __pyx_n_s__newObj, 58, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_86)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":92 + * + * + * def get_valid_metric_ids(L): # <<<<<<<<<<<<<< + * """Given an iterable of metric class names or class identifiers, + * return a list of metric IDs which map to those classes. + */ + __pyx_k_tuple_89 = PyTuple_Pack(3, ((PyObject *)__pyx_n_s__L), ((PyObject *)__pyx_n_s__key), ((PyObject *)__pyx_n_s__val)); if (unlikely(!__pyx_k_tuple_89)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_89); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_89)); + __pyx_k_codeobj_90 = (PyObject*)__Pyx_PyCode_New(1, 0, 3, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_89, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_87, __pyx_n_s_91, 92, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_90)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":282 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_k_tuple_96 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_95)); if (unlikely(!__pyx_k_tuple_96)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_96); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_96)); + + /* "View.MemoryView":283 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_k_tuple_98 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_97)); if (unlikely(!__pyx_k_tuple_98)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_98); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_98)); + + /* "View.MemoryView":284 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_100 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_99)); if (unlikely(!__pyx_k_tuple_100)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_100); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_100)); + + /* "View.MemoryView":287 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_k_tuple_102 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_101)); if (unlikely(!__pyx_k_tuple_102)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_102); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_102)); + + /* "View.MemoryView":288 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_104 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_103)); if (unlikely(!__pyx_k_tuple_104)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_104); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_104)); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_10 = PyInt_FromLong(10); if (unlikely(!__pyx_int_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC initdist_metrics(void); /*proto*/ +PyMODINIT_FUNC initdist_metrics(void) +#else +PyMODINIT_FUNC PyInit_dist_metrics(void); /*proto*/ +PyMODINIT_FUNC PyInit_dist_metrics(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_dist_metrics(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("dist_metrics"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.neighbors.dist_metrics")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.neighbors.dist_metrics", __pyx_m) < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__neighbors__dist_metrics) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + generic = Py_None; Py_INCREF(Py_None); + strided = Py_None; Py_INCREF(Py_None); + indirect = Py_None; Py_INCREF(Py_None); + contiguous = Py_None; Py_INCREF(Py_None); + indirect_contiguous = Py_None; Py_INCREF(Py_None); + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_DistanceMetric.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_DistanceMetric.rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_rdist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_DistanceMetric.pdist = (int (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __Pyx_memviewslice, __Pyx_memviewslice))__pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_pdist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_DistanceMetric.cdist = (int (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice))__pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric_cdist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_DistanceMetric._rdist_to_dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric__rdist_to_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_DistanceMetric._dist_to_rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_14DistanceMetric__dist_to_rdist; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_DistanceMetric) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_DistanceMetric.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "DistanceMetric", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_DistanceMetric) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric = &__pyx_type_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; + __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; + __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; + __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; + __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; + __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; + __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; + __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; + if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryview_type = &__pyx_type___pyx_memoryview; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17KulsinskiDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "KulsinskiDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_19SokalSneathDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 929; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 929; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "SokalSneathDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 929; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance.__pyx_base.rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance_rdist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance.__pyx_base._rdist_to_dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance__rdist_to_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance.__pyx_base._dist_to_rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_18SEuclideanDistance__dist_to_rdist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "SEuclideanDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_JaccardDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_JaccardDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_JaccardDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_JaccardDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_15JaccardDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_JaccardDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_JaccardDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 758; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_JaccardDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_JaccardDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 758; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "JaccardDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_JaccardDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 758; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_JaccardDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_JaccardDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_HammingDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_HammingDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_HammingDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_HammingDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_15HammingDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_HammingDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_HammingDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 688; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_HammingDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_HammingDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 688; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "HammingDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_HammingDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 688; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_HammingDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_HammingDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_18BrayCurtisDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 733; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 733; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "BrayCurtisDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 733; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_CanberraDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_CanberraDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_CanberraDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_CanberraDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_16CanberraDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_CanberraDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_CanberraDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 710; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_CanberraDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_CanberraDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 710; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "CanberraDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_CanberraDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 710; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_CanberraDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_CanberraDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_18RussellRaoDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 881; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 881; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "RussellRaoDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 881; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_EuclideanDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_EuclideanDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_EuclideanDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_EuclideanDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_EuclideanDistance.__pyx_base.rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance_rdist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_EuclideanDistance.__pyx_base._rdist_to_dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance__rdist_to_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_EuclideanDistance.__pyx_base._dist_to_rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17EuclideanDistance__dist_to_rdist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_EuclideanDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_EuclideanDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_EuclideanDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_EuclideanDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "EuclideanDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_EuclideanDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_EuclideanDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_EuclideanDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance.__pyx_base.rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance_rdist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance.__pyx_base._rdist_to_dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance__rdist_to_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance.__pyx_base._dist_to_rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_18WMinkowskiDistance__dist_to_rdist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "WMinkowskiDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance.__pyx_base.rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance_rdist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance.__pyx_base._rdist_to_dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance__rdist_to_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance.__pyx_base._dist_to_rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17MinkowskiDistance__dist_to_rdist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "MinkowskiDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance.__pyx_base.rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance_rdist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance.__pyx_base._rdist_to_dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance__rdist_to_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance.__pyx_base._dist_to_rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_19MahalanobisDistance__dist_to_rdist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "MahalanobisDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_ManhattanDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_ManhattanDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_ManhattanDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_ManhattanDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17ManhattanDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_ManhattanDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_ManhattanDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 472; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_ManhattanDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_ManhattanDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 472; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "ManhattanDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_ManhattanDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 472; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_ManhattanDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_ManhattanDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_21SokalMichenerDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 905; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 905; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "SokalMichenerDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 905; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance; + if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_array_type = &__pyx_type___pyx_array; + __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; + __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; + __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; + __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; + __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 927; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 927; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_22RogersTanimotoDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "RogersTanimotoDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_PyFuncDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_PyFuncDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_PyFuncDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_PyFuncDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_14PyFuncDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_PyFuncDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_PyFuncDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1064; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_PyFuncDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_PyFuncDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1064; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "PyFuncDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_PyFuncDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1064; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_PyFuncDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_PyFuncDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MatchingDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_MatchingDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MatchingDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_MatchingDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_16MatchingDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_MatchingDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_MatchingDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 783; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_MatchingDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_MatchingDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 783; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "MatchingDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_MatchingDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 783; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_MatchingDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_MatchingDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17ChebyshevDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "ChebyshevDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_HaversineDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_HaversineDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_HaversineDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_HaversineDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_HaversineDistance.__pyx_base.rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17HaversineDistance_rdist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_HaversineDistance.__pyx_base._rdist_to_dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17HaversineDistance__rdist_to_dist; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_HaversineDistance.__pyx_base._dist_to_rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_17HaversineDistance__dist_to_rdist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_HaversineDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_HaversineDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 955; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_HaversineDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_HaversineDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 955; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "HaversineDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_HaversineDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 955; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_HaversineDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_HaversineDistance; + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DiceDistance = &__pyx_vtable_7sklearn_9neighbors_12dist_metrics_DiceDistance; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_DiceDistance.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + __pyx_vtable_7sklearn_9neighbors_12dist_metrics_DiceDistance.__pyx_base.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_12dist_metrics_12DiceDistance_dist; + __pyx_type_7sklearn_9neighbors_12dist_metrics_DiceDistance.tp_base = __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_12dist_metrics_DiceDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_12dist_metrics_DiceDistance.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DiceDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "DiceDistance", (PyObject *)&__pyx_type_7sklearn_9neighbors_12dist_metrics_DiceDistance) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DiceDistance = &__pyx_type_7sklearn_9neighbors_12dist_metrics_DiceDistance; + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[5]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/neighbors/dist_metrics.pyx":10 + * # License: BSD + * + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * np.import_array() # required in order to use C-API + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":12 + * import numpy as np + * cimport numpy as np + * np.import_array() # required in order to use C-API # <<<<<<<<<<<<<< + * + * + */ + import_array(); + + /* "sklearn/neighbors/dist_metrics.pyx":49 + * # some handy constants + * from libc.math cimport fabs, sqrt, exp, pow, cos, sin, asin + * cdef DTYPE_t INF = np.inf # <<<<<<<<<<<<<< + * + * from typedefs cimport DTYPE_t, ITYPE_t, DITYPE_t, DTYPECODE + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_3 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_7sklearn_9neighbors_12dist_metrics_INF = __pyx_t_3; + + /* "sklearn/neighbors/dist_metrics.pyx":52 + * + * from typedefs cimport DTYPE_t, ITYPE_t, DITYPE_t, DTYPECODE + * from typedefs import DTYPE, ITYPE # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = PyList_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_n_s__DTYPE)); + PyList_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_n_s__DTYPE)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__DTYPE)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__ITYPE)); + PyList_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_n_s__ITYPE)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__ITYPE)); + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__typedefs), ((PyObject *)__pyx_t_2), -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__DTYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__ITYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":58 + * # newObj function + * # this is a helper function for pickling + * def newObj(obj): # <<<<<<<<<<<<<< + * return obj.__new__(obj) + * + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_12dist_metrics_1newObj, NULL, __pyx_n_s_88); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__newObj, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":65 + * # metric mappings + * # These map from metric id strings to class names + * METRIC_MAPPING = {'euclidean': EuclideanDistance, # <<<<<<<<<<<<<< + * 'l2': EuclideanDistance, + * 'minkowski': MinkowskiDistance, + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__euclidean), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_EuclideanDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":66 + * # These map from metric id strings to class names + * METRIC_MAPPING = {'euclidean': EuclideanDistance, + * 'l2': EuclideanDistance, # <<<<<<<<<<<<<< + * 'minkowski': MinkowskiDistance, + * 'p': MinkowskiDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__l2), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_EuclideanDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":67 + * METRIC_MAPPING = {'euclidean': EuclideanDistance, + * 'l2': EuclideanDistance, + * 'minkowski': MinkowskiDistance, # <<<<<<<<<<<<<< + * 'p': MinkowskiDistance, + * 'manhattan': ManhattanDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__minkowski), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":68 + * 'l2': EuclideanDistance, + * 'minkowski': MinkowskiDistance, + * 'p': MinkowskiDistance, # <<<<<<<<<<<<<< + * 'manhattan': ManhattanDistance, + * 'cityblock': ManhattanDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__p), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_MinkowskiDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":69 + * 'minkowski': MinkowskiDistance, + * 'p': MinkowskiDistance, + * 'manhattan': ManhattanDistance, # <<<<<<<<<<<<<< + * 'cityblock': ManhattanDistance, + * 'l1': ManhattanDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__manhattan), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_ManhattanDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":70 + * 'p': MinkowskiDistance, + * 'manhattan': ManhattanDistance, + * 'cityblock': ManhattanDistance, # <<<<<<<<<<<<<< + * 'l1': ManhattanDistance, + * 'chebyshev': ChebyshevDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__cityblock), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_ManhattanDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":71 + * 'manhattan': ManhattanDistance, + * 'cityblock': ManhattanDistance, + * 'l1': ManhattanDistance, # <<<<<<<<<<<<<< + * 'chebyshev': ChebyshevDistance, + * 'infinity': ChebyshevDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__l1), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_ManhattanDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":72 + * 'cityblock': ManhattanDistance, + * 'l1': ManhattanDistance, + * 'chebyshev': ChebyshevDistance, # <<<<<<<<<<<<<< + * 'infinity': ChebyshevDistance, + * 'seuclidean': SEuclideanDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__chebyshev), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":73 + * 'l1': ManhattanDistance, + * 'chebyshev': ChebyshevDistance, + * 'infinity': ChebyshevDistance, # <<<<<<<<<<<<<< + * 'seuclidean': SEuclideanDistance, + * 'mahalanobis': MahalanobisDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__infinity), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_ChebyshevDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":74 + * 'chebyshev': ChebyshevDistance, + * 'infinity': ChebyshevDistance, + * 'seuclidean': SEuclideanDistance, # <<<<<<<<<<<<<< + * 'mahalanobis': MahalanobisDistance, + * 'wminkowski': WMinkowskiDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__seuclidean), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_SEuclideanDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":75 + * 'infinity': ChebyshevDistance, + * 'seuclidean': SEuclideanDistance, + * 'mahalanobis': MahalanobisDistance, # <<<<<<<<<<<<<< + * 'wminkowski': WMinkowskiDistance, + * 'hamming': HammingDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__mahalanobis), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_MahalanobisDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":76 + * 'seuclidean': SEuclideanDistance, + * 'mahalanobis': MahalanobisDistance, + * 'wminkowski': WMinkowskiDistance, # <<<<<<<<<<<<<< + * 'hamming': HammingDistance, + * 'canberra': CanberraDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__wminkowski), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_WMinkowskiDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":77 + * 'mahalanobis': MahalanobisDistance, + * 'wminkowski': WMinkowskiDistance, + * 'hamming': HammingDistance, # <<<<<<<<<<<<<< + * 'canberra': CanberraDistance, + * 'braycurtis': BrayCurtisDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__hamming), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_HammingDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":78 + * 'wminkowski': WMinkowskiDistance, + * 'hamming': HammingDistance, + * 'canberra': CanberraDistance, # <<<<<<<<<<<<<< + * 'braycurtis': BrayCurtisDistance, + * 'matching': MatchingDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__canberra), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_CanberraDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":79 + * 'hamming': HammingDistance, + * 'canberra': CanberraDistance, + * 'braycurtis': BrayCurtisDistance, # <<<<<<<<<<<<<< + * 'matching': MatchingDistance, + * 'jaccard': JaccardDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__braycurtis), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_BrayCurtisDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":80 + * 'canberra': CanberraDistance, + * 'braycurtis': BrayCurtisDistance, + * 'matching': MatchingDistance, # <<<<<<<<<<<<<< + * 'jaccard': JaccardDistance, + * 'dice': DiceDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__matching), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_MatchingDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":81 + * 'braycurtis': BrayCurtisDistance, + * 'matching': MatchingDistance, + * 'jaccard': JaccardDistance, # <<<<<<<<<<<<<< + * 'dice': DiceDistance, + * 'kulsinski': KulsinskiDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__jaccard), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_JaccardDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":82 + * 'matching': MatchingDistance, + * 'jaccard': JaccardDistance, + * 'dice': DiceDistance, # <<<<<<<<<<<<<< + * 'kulsinski': KulsinskiDistance, + * 'rogerstanimoto': RogersTanimotoDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dice), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DiceDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":83 + * 'jaccard': JaccardDistance, + * 'dice': DiceDistance, + * 'kulsinski': KulsinskiDistance, # <<<<<<<<<<<<<< + * 'rogerstanimoto': RogersTanimotoDistance, + * 'russellrao': RussellRaoDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__kulsinski), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_KulsinskiDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":84 + * 'dice': DiceDistance, + * 'kulsinski': KulsinskiDistance, + * 'rogerstanimoto': RogersTanimotoDistance, # <<<<<<<<<<<<<< + * 'russellrao': RussellRaoDistance, + * 'sokalmichener': SokalMichenerDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__rogerstanimoto), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_RogersTanimotoDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":85 + * 'kulsinski': KulsinskiDistance, + * 'rogerstanimoto': RogersTanimotoDistance, + * 'russellrao': RussellRaoDistance, # <<<<<<<<<<<<<< + * 'sokalmichener': SokalMichenerDistance, + * 'sokalsneath': SokalSneathDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__russellrao), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_RussellRaoDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":86 + * 'rogerstanimoto': RogersTanimotoDistance, + * 'russellrao': RussellRaoDistance, + * 'sokalmichener': SokalMichenerDistance, # <<<<<<<<<<<<<< + * 'sokalsneath': SokalSneathDistance, + * 'haversine': HaversineDistance, + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__sokalmichener), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_SokalMichenerDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":87 + * 'russellrao': RussellRaoDistance, + * 'sokalmichener': SokalMichenerDistance, + * 'sokalsneath': SokalSneathDistance, # <<<<<<<<<<<<<< + * 'haversine': HaversineDistance, + * 'pyfunc': PyFuncDistance} + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__sokalsneath), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_SokalSneathDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":88 + * 'sokalmichener': SokalMichenerDistance, + * 'sokalsneath': SokalSneathDistance, + * 'haversine': HaversineDistance, # <<<<<<<<<<<<<< + * 'pyfunc': PyFuncDistance} + * + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__haversine), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_HaversineDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/neighbors/dist_metrics.pyx":89 + * 'sokalsneath': SokalSneathDistance, + * 'haversine': HaversineDistance, + * 'pyfunc': PyFuncDistance} # <<<<<<<<<<<<<< + * + * + */ + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__pyfunc), ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_PyFuncDistance))) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s__METRIC_MAPPING, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":92 + * + * + * def get_valid_metric_ids(L): # <<<<<<<<<<<<<< + * """Given an iterable of metric class names or class identifiers, + * return a list of metric IDs which map to those classes. + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_12dist_metrics_3get_valid_metric_ids, NULL, __pyx_n_s_88); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_91, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/neighbors/dist_metrics.pyx":241 + * + * @classmethod + * def get_metric(cls, metric, **kwargs): # <<<<<<<<<<<<<< + * """Get the given distance metric from the string identifier. + * + */ + __pyx_t_1 = __Pyx_GetNameInClass((PyObject *)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric, __pyx_n_s__get_metric); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_Method_ClassMethod(__pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem((PyObject *)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric->tp_dict, __pyx_n_s__get_metric, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric); + + /* "sklearn/neighbors/dist_metrics.pyx":1 + * #!python # <<<<<<<<<<<<<< + * #cython: boundscheck=False + * #cython: wraparound=False + */ + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_kp_u_92), ((PyObject *)__pyx_kp_u_93)) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + + /* "View.MemoryView":207 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * def __dealloc__(array self): + */ + __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_94); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_array_type); + + /* "View.MemoryView":282 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_96), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(generic); + __Pyx_DECREF(generic); + __Pyx_GIVEREF(__pyx_t_2); + generic = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":283 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_98), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(strided); + __Pyx_DECREF(strided); + __Pyx_GIVEREF(__pyx_t_2); + strided = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":284 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_100), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(indirect); + __Pyx_DECREF(indirect); + __Pyx_GIVEREF(__pyx_t_2); + indirect = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":287 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_102), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(contiguous); + __Pyx_DECREF(contiguous); + __Pyx_GIVEREF(__pyx_t_2); + contiguous = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":288 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_104), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(indirect_contiguous); + __Pyx_DECREF(indirect_contiguous); + __Pyx_GIVEREF(__pyx_t_2); + indirect_contiguous = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":503 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_94); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_memoryview_type); + + /* "View.MemoryView":958 + * return self.from_object + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_94); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 958; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 958; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_memoryviewslice_type); + + /* "BufferFormatFromTypeInfo":1421 + * + * @cname('__pyx_format_from_typeinfo') + * cdef bytes format_from_typeinfo(__Pyx_TypeInfo *type): # <<<<<<<<<<<<<< + * cdef __Pyx_StructField *field + * cdef __pyx_typeinfo_string fmt + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.neighbors.dist_metrics", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.neighbors.dist_metrics"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; /* Consume from buffer string */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + if (isspace(*ts)) + continue; + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case 10: + case 13: + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } /* fall through */ + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 's': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + } else { + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + } + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (!buf) { + PyErr_SetString(PyExc_ValueError, + "buf is NULL."); + goto fail; + } else if (memviewslice->memview || memviewslice->data) { + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); + } + retval = 0; + goto no_fail; +fail: + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} +static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { + va_list vargs; + char msg[200]; + va_start(vargs, fmt); +#ifdef HAVE_STDARG_PROTOTYPES + va_start(vargs, fmt); +#else + va_start(vargs); +#endif + vsnprintf(msg, 200, fmt, vargs); + Py_FatalError(msg); + va_end(vargs); +} +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) +{ + int first_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview || (PyObject *) memview == Py_None) + return; /* allow uninitialized memoryview assignment */ + if (__pyx_get_slice_count(memview) < 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + first_time = __pyx_add_acquisition_count(memview) == 0; + if (first_time) { + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); + } + } +} +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, + int have_gil, int lineno) { + int last_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview ) { + return; + } else if ((PyObject *) memview == Py_None) { + memslice->memview = NULL; + return; + } + if (__pyx_get_slice_count(memview) <= 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; + if (last_time) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } + } else { + memslice->memview = NULL; + } +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static CYTHON_INLINE int __Pyx_CheckKeywordStrings( + PyObject *kwdict, + const char* function_name, + int kw_allowed) +{ + PyObject* key = 0; + Py_ssize_t pos = 0; +#if CPYTHON_COMPILING_IN_PYPY + if (!kw_allowed && PyDict_Next(kwdict, &pos, &key, 0)) + goto invalid_keyword; + return 1; +#else + while (PyDict_Next(kwdict, &pos, &key, 0)) { + #if PY_MAJOR_VERSION < 3 + if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) + #endif + if (unlikely(!PyUnicode_Check(key))) + goto invalid_keyword_type; + } + if ((!kw_allowed) && unlikely(key)) + goto invalid_keyword; + return 1; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + return 0; +#endif +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif + return 0; +} + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + #endif + Py_INCREF(local_type); + Py_INCREF(local_value); + Py_INCREF(local_tb); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + /* Make sure tstate is in a consistent state when we XDECREF + these objects (DECREF may run arbitrary code). */ + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { + #endif +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static void __Pyx_RaiseBufferFallbackError(void) { + PyErr_Format(PyExc_ValueError, + "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +} + +static double __Pyx__PyObject_AsDouble(PyObject* obj) { + PyObject* float_value; +#if CYTHON_COMPILING_IN_PYPY + float_value = PyNumber_Float(obj); +#else + PyNumberMethods *nb = Py_TYPE(obj)->tp_as_number; + if (likely(nb) && likely(nb->nb_float)) { + float_value = nb->nb_float(obj); + if (likely(float_value) && unlikely(!PyFloat_Check(float_value))) { + PyErr_Format(PyExc_TypeError, + "__float__ returned non-float (type %.200s)", + Py_TYPE(float_value)->tp_name); + Py_DECREF(float_value); + goto bad; + } + } else if (PyUnicode_CheckExact(obj) || PyBytes_CheckExact(obj)) { +#if PY_MAJOR_VERSION >= 3 + float_value = PyFloat_FromString(obj); +#else + float_value = PyFloat_FromString(obj, 0); +#endif + } else { + PyObject* args = PyTuple_New(1); + if (unlikely(!args)) goto bad; + PyTuple_SET_ITEM(args, 0, obj); + float_value = PyObject_Call((PyObject*)&PyFloat_Type, args, 0); + PyTuple_SET_ITEM(args, 0, 0); + Py_DECREF(args); + } +#endif + if (likely(float_value)) { + double value = PyFloat_AS_DOUBLE(float_value); + Py_DECREF(float_value); + return value; + } +bad: + return (double)-1; +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (!type) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (Py_TYPE(obj) == type) return 1; + } + else { + if (PyObject_TypeCheck(obj, type)) return 1; + } + PyErr_Format(PyExc_TypeError, + "Argument '%s' has incorrect type (expected %s, got %s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); + return 0; +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +#if CYTHON_COMPILING_IN_CPYTHON +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) +#else + if (likely(PyString_Check(n))) +#endif + return __Pyx_PyObject_GetAttrStr(o, n); +#endif + return PyObject_GetAttr(o, n); +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r = __Pyx_GetAttr(o, n); + if (!r) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + goto bad; + PyErr_Clear(); + r = d; + Py_INCREF(d); + } + return r; +bad: + return NULL; +} + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyUnicode_CheckExact(s1) & PyUnicode_CheckExact(s2)) { + #if CYTHON_PEP393_ENABLED + if ((PyUnicode_READY(s1) < 0) || (PyUnicode_READY(s2) < 0)) + return -1; + if (PyUnicode_GET_LENGTH(s1) != PyUnicode_GET_LENGTH(s2)) { + return (equals == Py_NE); + } else if (PyUnicode_GET_LENGTH(s1) == 1) { + Py_UCS4 ch1 = PyUnicode_READ_CHAR(s1, 0); + Py_UCS4 ch2 = PyUnicode_READ_CHAR(s2, 0); + return (equals == Py_EQ) ? (ch1 == ch2) : (ch1 != ch2); + #else + if (PyUnicode_GET_SIZE(s1) != PyUnicode_GET_SIZE(s2)) { + return (equals == Py_NE); + } else if (PyUnicode_GET_SIZE(s1) == 1) { + Py_UNICODE ch1 = PyUnicode_AS_UNICODE(s1)[0]; + Py_UNICODE ch2 = PyUnicode_AS_UNICODE(s2)[0]; + return (equals == Py_EQ) ? (ch1 == ch2) : (ch1 != ch2); + #endif + } else { + int result = PyUnicode_Compare(s1, s2); + if ((result == -1) && unlikely(PyErr_Occurred())) + return -1; + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyUnicode_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyUnicode_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + length = strlen(cstring); + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s____pyx_vtable__, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif + } + return value; +} + +static PyObject *__Pyx_GetNameInClass(PyObject *nmspace, PyObject *name) { + PyObject *result; + result = __Pyx_PyObject_GetAttrStr(nmspace, name); + if (!result) + result = __Pyx_GetModuleGlobalName(name); + return result; +} + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s____import__); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t val) { + const Py_intptr_t neg_one = (Py_intptr_t)-1, const_zero = (Py_intptr_t)0; + const int is_unsigned = const_zero < neg_one; + if ((sizeof(Py_intptr_t) == sizeof(char)) || + (sizeof(Py_intptr_t) == sizeof(short))) { + return PyInt_FromLong((long)val); + } else if ((sizeof(Py_intptr_t) == sizeof(int)) || + (sizeof(Py_intptr_t) == sizeof(long))) { + if (is_unsigned) + return PyLong_FromUnsignedLong((unsigned long)val); + else + return PyInt_FromLong((long)val); + } else if (sizeof(Py_intptr_t) == sizeof(PY_LONG_LONG)) { + if (is_unsigned) + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); + else + return PyLong_FromLongLong((PY_LONG_LONG)val); + } else { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); + } +} + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_from_py_Py_intptr_t(PyObject* x) { + const Py_intptr_t neg_one = (Py_intptr_t)-1, const_zero = (Py_intptr_t)0; + const int is_unsigned = const_zero < neg_one; + if (sizeof(Py_intptr_t) == sizeof(char)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedChar(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedChar(x); + } else if (sizeof(Py_intptr_t) == sizeof(short)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedShort(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedShort(x); + } else if (sizeof(Py_intptr_t) == sizeof(int)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedInt(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedInt(x); + } else if (sizeof(Py_intptr_t) == sizeof(long)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedLong(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedLong(x); + } else if (sizeof(Py_intptr_t) == sizeof(PY_LONG_LONG)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedLongLong(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedLongLong(x); + } else { + #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); + #else + Py_intptr_t val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } + #endif + return (Py_intptr_t)-1; + } +} + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +#else + PyErr_GetExcInfo(type, value, tb); +#endif +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(type, value, tb); +#endif +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } + } + #endif + PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: + Py_DECREF(obj); + view->obj = NULL; +} +#endif /* PY_MAJOR_VERSION < 3 */ + + + static PyObject* __Pyx_Method_ClassMethod(PyObject *method) { +#if CYTHON_COMPILING_IN_PYPY + if (PyObject_TypeCheck(method, &PyWrapperDescr_Type)) { /* cdef classes */ + return PyClassMethod_New(method); + } +#else + static PyTypeObject *methoddescr_type = NULL; + if (methoddescr_type == NULL) { + PyObject *meth = __Pyx_GetAttrString((PyObject*)&PyList_Type, "append"); + if (!meth) return NULL; + methoddescr_type = Py_TYPE(meth); + Py_DECREF(meth); + } + if (PyObject_TypeCheck(method, methoddescr_type)) { /* cdef classes */ + PyMethodDescrObject *descr = (PyMethodDescrObject *)method; + #if PY_VERSION_HEX < 0x03020000 + PyTypeObject *d_type = descr->d_type; + #else + PyTypeObject *d_type = descr->d_common.d_type; + #endif + return PyDescr_NewClassMethod(d_type, descr->d_method); + } +#endif + else if (PyMethod_Check(method)) { /* python classes */ + return PyClassMethod_New(PyMethod_GET_FUNCTION(method)); + } + else if (PyCFunction_Check(method)) { + return PyClassMethod_New(method); + } +#ifdef __Pyx_CyFunction_USED + else if (PyObject_TypeCheck(method, __pyx_CyFunctionType)) { + return PyClassMethod_New(method); + } +#endif + PyErr_Format(PyExc_TypeError, + "Class-level classmethod() can only be called on " + "a method_descriptor or instance method."); + return NULL; +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +static int +__pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim) +{ + int i, index, step, start; + Py_ssize_t itemsize = mvs->memview->view.itemsize; + if (order == 'F') { + step = 1; + start = 0; + } else { + step = -1; + start = ndim - 1; + } + for (i = 0; i < ndim; i++) { + index = start + step * i; + if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) + return 0; + itemsize *= mvs->shape[index]; + } + return 1; +} + +static void +__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + start = end = slice->data; + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + if (extent == 0) { + *out_start = *out_end = start; + return; + } else { + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); + } + } + *out_start = start; + *out_end = end + itemsize; +} +static int +__pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize) +{ + void *start1, *end1, *start2, *end2; + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + return (start1 < end2) && (start2 < end1); +} + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + for (i = 0; i < ndim; i++) { + if (from_mvs->suboffsets[i] >= 0) { + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; + } + } + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; + } + __Pyx_GOTREF(shape_tuple); + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromLong(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; + } else { + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; + } + } + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + goto no_fail; +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; +} + +static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) +{ + PyObject *cobj; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); +#endif + return cobj; +} + +static struct __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *type) { + struct __pyx_typeinfo_string result = { {0} }; + char *buf = (char *) result.string; + size_t size = type->size; + switch (type->typegroup) { + case 'H': + *buf = 'c'; + break; + case 'I': + case 'U': + if (size == 1) + *buf = 'b'; + else if (size == 2) + *buf = 'h'; + else if (size == 4) + *buf = 'i'; + else if (size == 8) + *buf = 'q'; + if (type->is_unsigned) + *buf = toupper(*buf); + break; + case 'P': + *buf = 'P'; + break; + case 'C': + { + __Pyx_TypeInfo complex_type = *type; + complex_type.typegroup = 'R'; + complex_type.size /= 2; + *buf++ = 'Z'; + *buf = __Pyx_TypeInfoToFormat(&complex_type).string[0]; + break; + } + case 'R': + if (size == 4) + *buf = 'f'; + else if (size == 8) + *buf = 'd'; + else + *buf = 'g'; + break; + } + return result; +} + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { + const unsigned char neg_one = (unsigned char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned char" : + "value too large to convert to unsigned char"); + } + return (unsigned char)-1; + } + return (unsigned char)val; + } + return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { + const unsigned short neg_one = (unsigned short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned short" : + "value too large to convert to unsigned short"); + } + return (unsigned short)-1; + } + return (unsigned short)val; + } + return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { + const unsigned int neg_one = (unsigned int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned int" : + "value too large to convert to unsigned int"); + } + return (unsigned int)-1; + } + return (unsigned int)val; + } + return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { + const char neg_one = (char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to char" : + "value too large to convert to char"); + } + return (char)-1; + } + return (char)val; + } + return (char)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { + const short neg_one = (short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to short" : + "value too large to convert to short"); + } + return (short)-1; + } + return (short)val; + } + return (short)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { + const signed char neg_one = (signed char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed char" : + "value too large to convert to signed char"); + } + return (signed char)-1; + } + return (signed char)val; + } + return (signed char)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { + const signed short neg_one = (signed short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed short" : + "value too large to convert to signed short"); + } + return (signed short)-1; + } + return (signed short)val; + } + return (signed short)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { + const signed int neg_one = (signed int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed int" : + "value too large to convert to signed int"); + } + return (signed int)-1; + } + return (signed int)val; + } + return (signed int)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { + const unsigned long neg_one = (unsigned long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (unsigned long)PyLong_AsLong(x); + } + } else { + unsigned long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned long)-1; + val = __Pyx_PyInt_AsUnsignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { + const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + unsigned PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsUnsignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { + const long neg_one = (long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (long)PyLong_AsLong(x); + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long)-1; + val = __Pyx_PyInt_AsLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { + const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { + const signed long neg_one = (signed long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (signed long)PyLong_AsLong(x); + } + } else { + signed long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed long)-1; + val = __Pyx_PyInt_AsSignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { + const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + signed PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsSignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static int +__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) +{ + int i; + if (!a || !b) + return 0; + if (a == b) + return 1; + if (a->size != b->size || a->typegroup != b->typegroup || + a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { + if (a->typegroup == 'H' || b->typegroup == 'H') { + return a->size == b->size; + } else { + return 0; + } + } + if (a->ndim) { + for (i = 0; i < a->ndim; i++) + if (a->arraysize[i] != b->arraysize[i]) + return 0; + } + if (a->typegroup == 'S') { + if (a->flags != b->flags) + return 0; + if (a->fields || b->fields) { + if (!(a->fields && b->fields)) + return 0; + for (i = 0; a->fields[i].type && b->fields[i].type; i++) { + __Pyx_StructField *field_a = a->fields + i; + __Pyx_StructField *field_b = b->fields + i; + if (field_a->offset != field_b->offset || + !__pyx_typeinfo_cmp(field_a->type, field_b->type)) + return 0; + } + return !a->fields[i].type && !b->fields[i].type; + } + } + return 1; +} + +static int +__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) +{ + if (buf->shape[dim] <= 1) + return 1; + if (buf->strides) { + if (spec & __Pyx_MEMVIEW_CONTIG) { + if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { + if (buf->strides[dim] != sizeof(void *)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly contiguous " + "in dimension %d.", dim); + goto fail; + } + } else if (buf->strides[dim] != buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_FOLLOW) { + Py_ssize_t stride = buf->strides[dim]; + if (stride < 0) + stride = -stride; + if (stride < buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + } else { + if (spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not contiguous in " + "dimension %d", dim); + goto fail; + } else if (spec & (__Pyx_MEMVIEW_PTR)) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not indirect in " + "dimension %d", dim); + goto fail; + } else if (buf->suboffsets) { + PyErr_SetString(PyExc_ValueError, + "Buffer exposes suboffsets but no strides"); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) +{ + if (spec & __Pyx_MEMVIEW_DIRECT) { + if (buf->suboffsets && buf->suboffsets[dim] >= 0) { + PyErr_Format(PyExc_ValueError, + "Buffer not compatible with direct access " + "in dimension %d.", dim); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_PTR) { + if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly accessisble " + "in dimension %d.", dim); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) +{ + int i; + if (c_or_f_flag & __Pyx_IS_F_CONTIG) { + Py_ssize_t stride = 1; + for (i = 0; i < ndim; i++) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) + { + PyErr_SetString(PyExc_ValueError, + "Buffer not fortran contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { + Py_ssize_t stride = 1; + for (i = ndim - 1; i >- 1; i--) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) { + PyErr_SetString(PyExc_ValueError, + "Buffer not C contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } + return 1; +fail: + return 0; +} +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj) +{ + struct __pyx_memoryview_obj *memview, *new_memview; + __Pyx_RefNannyDeclarations + Py_buffer *buf; + int i, spec = 0, retval = -1; + __Pyx_BufFmt_Context ctx; + int from_memoryview = __pyx_memoryview_check(original_obj); + __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); + if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) + original_obj)->typeinfo)) { + memview = (struct __pyx_memoryview_obj *) original_obj; + new_memview = NULL; + } else { + memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + original_obj, buf_flags, 0, dtype); + new_memview = memview; + if (unlikely(!memview)) + goto fail; + } + buf = &memview->view; + if (buf->ndim != ndim) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + ndim, buf->ndim); + goto fail; + } + if (new_memview) { + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned) buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " + "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", + buf->itemsize, + (buf->itemsize > 1) ? "s" : "", + dtype->name, + dtype->size, + (dtype->size > 1) ? "s" : ""); + goto fail; + } + for (i = 0; i < ndim; i++) { + spec = axes_specs[i]; + if (!__pyx_check_strides(buf, i, ndim, spec)) + goto fail; + if (!__pyx_check_suboffsets(buf, i, ndim, spec)) + goto fail; + } + if (buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, + new_memview != NULL) == -1)) { + goto fail; + } + retval = 0; + goto no_fail; +fail: + Py_XDECREF(new_memview); + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%s.%s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + #if PY_VERSION_HEX < 0x02050000 + if (PyErr_Warn(NULL, warning) < 0) goto bad; + #else + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + #endif + } + else if ((size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%s.%s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (r < 0) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_MAJOR_VERSION < 3 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%s__ returned non-%s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject* x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { + unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); + if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); + return (size_t)-1; + } + return (size_t)val; +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/neighbors/dist_metrics.pxd b/sklearn/neighbors/dist_metrics.pxd new file mode 100644 index 0000000000000..0f05ccb41ef9b --- /dev/null +++ b/sklearn/neighbors/dist_metrics.pxd @@ -0,0 +1,75 @@ +#!python +#cython: boundscheck=False +#cython: wraparound=False +#cython: cdivision=True + +cimport cython +cimport numpy as np +from libc.math cimport fabs, sqrt, exp, cos, pow + +from typedefs cimport DTYPE_t, ITYPE_t, DITYPE_t +from typedefs import DTYPE, ITYPE + +###################################################################### +# Inline distance functions +# +# We use these for the default (euclidean) case so that they can be +# inlined. This leads to faster computation for the most common case +cdef inline DTYPE_t euclidean_dist(DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef DTYPE_t tmp, d=0 + cdef np.intp_t j + for j in range(size): + tmp = x1[j] - x2[j] + d += tmp * tmp + return sqrt(d) + + +cdef inline DTYPE_t euclidean_rdist(DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef DTYPE_t tmp, d=0 + cdef np.intp_t j + for j in range(size): + tmp = x1[j] - x2[j] + d += tmp * tmp + return d + + +cdef inline DTYPE_t euclidean_dist_to_rdist(DTYPE_t dist) except -1: + return dist * dist + + +cdef inline DTYPE_t euclidean_rdist_to_dist(DTYPE_t dist) except -1: + return sqrt(dist) + + +###################################################################### +# DistanceMetric base class +cdef class DistanceMetric: + # The following attributes are required for a few of the subclasses. + # we must define them here so that cython's limited polymorphism will work. + # Because we don't expect to instantiate a lot of these objects, the + # extra memory overhead of this setup should not be an issue. + cdef DTYPE_t p + #cdef DTYPE_t[::1] vec + #cdef DTYPE_t[:, ::1] mat + cdef np.ndarray vec + cdef np.ndarray mat + cdef DTYPE_t* vec_ptr + cdef DTYPE_t* mat_ptr + cdef ITYPE_t size + cdef object func + cdef object kwargs + + cdef DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size) except -1 + + cdef DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size) except -1 + + cdef int pdist(self, DTYPE_t[:, ::1] X, DTYPE_t[:, ::1] D) except -1 + + cdef int cdist(self, DTYPE_t[:, ::1] X, DTYPE_t[:, ::1] Y, + DTYPE_t[:, ::1] D) except -1 + + cdef DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1 + + cdef DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1 diff --git a/sklearn/neighbors/dist_metrics.pyx b/sklearn/neighbors/dist_metrics.pyx new file mode 100644 index 0000000000000..9d68da9083884 --- /dev/null +++ b/sklearn/neighbors/dist_metrics.pyx @@ -0,0 +1,1097 @@ +#!python +#cython: boundscheck=False +#cython: wraparound=False +#cython: cdivision=True + +# By Jake Vanderplas (2013) +# written for the scikit-learn project +# License: BSD + +import numpy as np +cimport numpy as np +np.import_array() # required in order to use C-API + + +###################################################################### +# Numpy 1.3-1.4 compatibility utilities +cdef DTYPE_t[:, ::1] get_memview_DTYPE_2D( + np.ndarray[DTYPE_t, ndim=2, mode='c'] X): + return ( X.data) + + +cdef DTYPE_t* get_vec_ptr(np.ndarray[DTYPE_t, ndim=1, mode='c'] vec): + return &vec[0] + + +cdef DTYPE_t* get_mat_ptr(np.ndarray[DTYPE_t, ndim=2, mode='c'] mat): + return &mat[0, 0] +###################################################################### + + +# First, define a function to get an ndarray from a memory bufffer +cdef extern from "arrayobject.h": + object PyArray_SimpleNewFromData(int nd, np.npy_intp* dims, + int typenum, void* data) + + +cdef inline np.ndarray _buffer_to_ndarray(DTYPE_t* x, np.npy_intp n): + # Wrap a memory buffer with an ndarray. Warning: this is not robust. + # In particular, if x is deallocated before the returned array goes + # out of scope, this could cause memory errors. Since there is not + # a possibility of this for our use-case, this should be safe. + + # Note: this Segfaults unless np.import_array() is called above + return PyArray_SimpleNewFromData(1, &n, DTYPECODE, x) + + +# some handy constants +from libc.math cimport fabs, sqrt, exp, pow, cos, sin, asin +cdef DTYPE_t INF = np.inf + +from typedefs cimport DTYPE_t, ITYPE_t, DITYPE_t, DTYPECODE +from typedefs import DTYPE, ITYPE + + +###################################################################### +# newObj function +# this is a helper function for pickling +def newObj(obj): + return obj.__new__(obj) + + +###################################################################### +# metric mappings +# These map from metric id strings to class names +METRIC_MAPPING = {'euclidean': EuclideanDistance, + 'l2': EuclideanDistance, + 'minkowski': MinkowskiDistance, + 'p': MinkowskiDistance, + 'manhattan': ManhattanDistance, + 'cityblock': ManhattanDistance, + 'l1': ManhattanDistance, + 'chebyshev': ChebyshevDistance, + 'infinity': ChebyshevDistance, + 'seuclidean': SEuclideanDistance, + 'mahalanobis': MahalanobisDistance, + 'wminkowski': WMinkowskiDistance, + 'hamming': HammingDistance, + 'canberra': CanberraDistance, + 'braycurtis': BrayCurtisDistance, + 'matching': MatchingDistance, + 'jaccard': JaccardDistance, + 'dice': DiceDistance, + 'kulsinski': KulsinskiDistance, + 'rogerstanimoto': RogersTanimotoDistance, + 'russellrao': RussellRaoDistance, + 'sokalmichener': SokalMichenerDistance, + 'sokalsneath': SokalSneathDistance, + 'haversine': HaversineDistance, + 'pyfunc': PyFuncDistance} + + +def get_valid_metric_ids(L): + """Given an iterable of metric class names or class identifiers, + return a list of metric IDs which map to those classes. + + Example: + >>> L = get_valid_metric_ids([EuclideanDistance, 'ManhattanDistance']) + >>> sorted(L) + ['cityblock', 'euclidean', 'l1', 'l2', 'manhattan'] + """ + return [key for (key, val) in METRIC_MAPPING.items() + if (val.__name__ in L) or (val in L)] + + +###################################################################### +# Distance Metric Classes +cdef class DistanceMetric: + """DistanceMetric class + + This class provides a uniform interface to fast distance metric + functions. The various metrics can be accessed via the `get_metric` + class method and the metric string identifier (see below). + For example, to use the Euclidean distance: + + >>> dist = DistanceMetric.get_metric('euclidean') + >>> X = [[0, 1, 2], + [3, 4, 5]]) + >>> dist.pairwise(X) + array([[ 0. , 5.19615242], + [ 5.19615242, 0. ]]) + + Available Metrics + The following lists the string metric identifiers and the associated + distance metric classes: + + **Metrics intended for real-valued vector spaces:** + + ============== ==================== ======== =============================== + identifier class name args distance function + -------------- -------------------- -------- ------------------------------- + "euclidean" EuclideanDistance - ``sqrt(sum((x - y)^2))`` + "manhattan" ManhattanDistance - ``sum(|x - y|)`` + "chebyshev" ChebyshevDistance - ``sum(max(|x - y|))`` + "minkowski" MinkowskiDistance p ``sum(|x - y|^p)^(1/p)`` + "wminkowski" WMinkowskiDistance p, w ``sum(w * |x - y|^p)^(1/p)`` + "seuclidean" SEuclideanDistance V ``sqrt(sum((x - y)^2 / V))`` + "mahalanobis" MahalanobisDistance V or VI ``sqrt((x - y)' V^-1 (x - y))`` + ============== ==================== ======== =============================== + + **Metrics intended for two-dimensional vector spaces:** + + ============ ================== ======================================== + identifier class name distance function + ------------ ------------------ ---------------------------------------- + "haversine" HaversineDistance 2 arcsin(sqrt(sin^2(0.5*dx) + + cos(x1)cos(x2)sin^2(0.5*dy))) + ============ ================== ======================================== + + + **Metrics intended for integer-valued vector spaces:** Though intended + for integer-valued vectors, these are also valid metrics in the case of + real-valued vectors. + + ============= ==================== ======================================== + identifier class name distance function + ------------- -------------------- ---------------------------------------- + "hamming" HammingDistance ``N_unequal(x, y) / N_tot`` + "canberra" CanberraDistance ``sum(|x - y| / (|x| + |y|))`` + "braycurtis" BrayCurtisDistance ``sum(|x - y|) / (sum(|x|) + sum(|y|))`` + ============= ==================== ======================================== + + **Metrics intended for boolean-valued vector spaces:** Any nonzero entry + is evaluated to "True". In the listings below, the following + abbreviations are used: + + - N : number of dimensions + - NTT : number of dims in which both values are True + - NTF : number of dims in which the first value is True, second is False + - NFT : number of dims in which the first value is False, second is True + - NFF : number of dims in which both values are False + - NNEQ : number of non-equal dimensions, NNEQ = NTF + NFT + - NNZ : number of nonzero dimensions, NNZ = NTF + NFT + NTT + + ================= ======================= =============================== + identifier class name distance function + ----------------- ----------------------- ------------------------------- + "jaccard" JaccardDistance NNEQ / NNZ + "maching" MatchingDistance NNEQ / N + "dice" DiceDistance NNEQ / (NTT + NNZ) + "kulsinski" KulsinskiDistance (NNEQ + N - NTT) / (NNEQ + N) + "rogerstanimoto" RogersTanimotoDistance 2 * NNEQ / (N + NNEQ) + "russellrao" RussellRaoDistance NNZ / N + "sokalmichener" SokalMichenerDistance 2 * NNEQ / (N + NNEQ) + "sokalsneath" SokalSneathDistance NNEQ / (NNEQ + 0.5 * NTT) + ================= ======================= =============================== + + **User-defined distance:** + + =========== =============== ======= + identifier class name args + ----------- --------------- ------- + "pyfunc" PyFuncDistance func + =========== =============== ======= + + Here ``func`` is a function which takes two one-dimensional numpy + arrays, and returns a distance. Note that in order to be used within + the BallTree, the distance must be a true metric: + i.e. it must satisfy the following properties + + 1) Non-negativity: d(x, y) >= 0 + 2) Identity: d(x, y) = 0 if and only if x == y + 3) Symmetry: d(x, y) = d(y, x) + 4) Triangle Inequality: d(x, y) + d(y, z) >= d(x, z) + + Because of the Python object overhead involved in calling the python + function, this will be fairly slow, but it will have the same + scaling as other distances. + """ + def __cinit__(self): + self.p = 2 + self.vec = np.zeros(1, dtype=DTYPE, order='c') + self.mat = np.zeros((1, 1), dtype=DTYPE, order='c') + self.vec_ptr = get_vec_ptr(self.vec) + self.mat_ptr = get_mat_ptr(self.mat) + self.size = 1 + + def __reduce__(self): + """ + reduce method used for pickling + """ + return (newObj, (self.__class__,), self.__getstate__()) + + def __getstate__(self): + """ + get state for pickling + """ + return (float(self.p), self.vec, self.mat) + + def __setstate__(self, state): + """ + set state for pickling + """ + self.p = state[0] + self.vec = state[1] + self.mat = state[2] + self.vec_ptr = get_vec_ptr(self.vec) + self.mat_ptr = get_mat_ptr(self.mat) + self.size = 1 + + @classmethod + def get_metric(cls, metric, **kwargs): + """Get the given distance metric from the string identifier. + + See the docstring of DistanceMetric for a list of available metrics. + + Parameters + ---------- + metric : string or class name + The distance metric to use + **kwargs + additional arguments will be passed to the requested metric + """ + if isinstance(metric, DistanceMetric): + return metric + + if callable(metric): + return PyFuncDistance(metric, **kwargs) + + # Map the metric string ID to the metric class + if isinstance(metric, type) and issubclass(metric, DistanceMetric): + pass + else: + try: + metric = METRIC_MAPPING[metric] + except: + raise ValueError("Unrecognized metric '%s'" % metric) + + # In Minkowski special cases, return more efficient methods + if metric is MinkowskiDistance: + p = kwargs.pop('p', 2) + if p == 1: + return ManhattanDistance(**kwargs) + elif p == 2: + return EuclideanDistance(**kwargs) + elif np.isinf(p): + return ChebyshevDistance(**kwargs) + else: + return MinkowskiDistance(p, **kwargs) + else: + return metric(**kwargs) + + def __init__(self): + if self.__class__ is DistanceMetric: + raise NotImplementedError("DistanceMetric is an abstract class") + + cdef DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size) except -1: + """Compute the distance between vectors x1 and x2 + + This should be overridden in a base class. + """ + return -999 + + cdef DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size) except -1: + """Compute the reduced distance between vectors x1 and x2. + + This can optionally be overridden in a base class. + + The reduced distance is any measure that yields the same rank as the + distance, but is more efficient to compute. For example, for the + Euclidean metric, the reduced distance is the squared-euclidean + distance. + """ + return self.dist(x1, x2, size) + + cdef int pdist(self, DTYPE_t[:, ::1] X, DTYPE_t[:, ::1] D) except -1: + """compute the pairwise distances between points in X""" + cdef ITYPE_t i1, i2 + for i1 in range(X.shape[0]): + for i2 in range(i1, X.shape[0]): + D[i1, i2] = self.dist(&X[i1, 0], &X[i2, 0], X.shape[1]) + D[i2, i1] = D[i1, i2] + return 0 + + cdef int cdist(self, DTYPE_t[:, ::1] X, DTYPE_t[:, ::1] Y, + DTYPE_t[:, ::1] D) except -1: + """compute the cross-pairwise distances between arrays X and Y""" + cdef ITYPE_t i1, i2 + if X.shape[1] != Y.shape[1]: + raise ValueError('X and Y must have the same second dimension') + for i1 in range(X.shape[0]): + for i2 in range(Y.shape[0]): + D[i1, i2] = self.dist(&X[i1, 0], &Y[i2, 0], X.shape[1]) + return 0 + + cdef DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + """Convert the reduced distance to the distance""" + return rdist + + cdef DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + """Convert the distance to the reduced distance""" + return dist + + def rdist_to_dist(self, rdist): + """Convert the Reduced distance to the true distance. + + The reduced distance, defined for some metrics, is a computationally + more efficent measure which preserves the rank of the true distance. + For example, in the Euclidean distance metric, the reduced distance + is the squared-euclidean distance. + """ + return rdist + + def dist_to_rdist(self, dist): + """Convert the true distance to the reduced distance. + + The reduced distance, defined for some metrics, is a computationally + more efficent measure which preserves the rank of the true distance. + For example, in the Euclidean distance metric, the reduced distance + is the squared-euclidean distance. + """ + return dist + + def pairwise(self, X, Y=None): + """Compute the pairwise distances between X and Y + + This is a convenience routine for the sake of testing. For many + metrics, the utilities in scipy.spatial.distance.cdist and + scipy.spatial.distance.pdist will be faster. + + Parameters + ---------- + X : array_like + Array of shape (Nx, D), representing Nx points in D dimensions. + Y : array_like (optional) + Array of shape (Ny, D), representing Ny points in D dimensions. + If not specified, then Y=X. + Returns + ------- + dist : ndarray + The shape (Nx, Ny) array of pairwise distances between points in + X and Y. + """ + cdef np.ndarray[DTYPE_t, ndim=2, mode='c'] Xarr + cdef np.ndarray[DTYPE_t, ndim=2, mode='c'] Yarr + cdef np.ndarray[DTYPE_t, ndim=2, mode='c'] Darr + + Xarr = np.asarray(X, dtype=DTYPE, order='C') + if Y is None: + Darr = np.zeros((Xarr.shape[0], Xarr.shape[0]), + dtype=DTYPE, order='C') + self.pdist(get_memview_DTYPE_2D(Xarr), + get_memview_DTYPE_2D(Darr)) + else: + Yarr = np.asarray(Y, dtype=DTYPE, order='C') + Darr = np.zeros((Xarr.shape[0], Yarr.shape[0]), + dtype=DTYPE, order='C') + self.cdist(get_memview_DTYPE_2D(Xarr), + get_memview_DTYPE_2D(Yarr), + get_memview_DTYPE_2D(Darr)) + return Darr + + +#------------------------------------------------------------ +# Euclidean Distance +# d = sqrt(sum(x_i^2 - y_i^2)) +cdef class EuclideanDistance(DistanceMetric): + """Euclidean Distance metric + + .. math:: + D(x, y) = \sqrt{ \sum_i (x_i - y_i) ^ 2 } + """ + def __init__(self): + self.p = 2 + + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + return euclidean_dist(x1, x2, size) + + cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + return euclidean_rdist(x1, x2, size) + + cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + return sqrt(rdist) + + cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + return dist * dist + + def rdist_to_dist(self, rdist): + return np.sqrt(rdist) + + def dist_to_rdist(self, dist): + return dist ** 2 + + +#------------------------------------------------------------ +# SEuclidean Distance +# d = sqrt(sum((x_i - y_i2)^2 / v_i)) +cdef class SEuclideanDistance(DistanceMetric): + """Standardized Euclidean Distance metric + + .. math:: + D(x, y) = \sqrt{ \sum_i \frac{ (x_i - y_i) ^ 2}{V_i} } + """ + def __init__(self, V): + self.vec = np.asarray(V, dtype=DTYPE) + self.vec_ptr = get_vec_ptr(self.vec) + self.size = self.vec.shape[0] + self.p = 2 + + cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + if size != self.size: + raise ValueError('SEuclidean dist: size of V does not match') + cdef DTYPE_t tmp, d=0 + cdef np.intp_t j + for j in range(size): + tmp = x1[j] - x2[j] + d += tmp * tmp / self.vec_ptr[j] + return d + + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + return sqrt(self.rdist(x1, x2, size)) + + cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + return sqrt(rdist) + + cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + return dist * dist + + def rdist_to_dist(self, rdist): + return np.sqrt(rdist) + + def dist_to_rdist(self, dist): + return dist ** 2 + + +#------------------------------------------------------------ +# Manhattan Distance +# d = sum(abs(x_i - y_i)) +cdef class ManhattanDistance(DistanceMetric): + """Manhattan/City-block Distance metric + + .. math:: + D(x, y) = \sum_i |x_i - y_i| + """ + def __init__(self): + self.p = 1 + + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef DTYPE_t d = 0 + cdef np.intp_t j + for j in range(size): + d += fabs(x1[j] - x2[j]) + return d + + +#------------------------------------------------------------ +# Chebyshev Distance +# d = max_i(abs(x_i), abs(y_i)) +cdef class ChebyshevDistance(DistanceMetric): + """Chebyshev/Infinity Distance + + .. math:: + D(x, y) = max_i (|x_i - y_i|) + """ + def __init__(self): + self.p = INF + + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef DTYPE_t d = 0 + cdef np.intp_t j + for j in range(size): + d = fmax(d, fabs(x1[j] - x2[j])) + return d + + +#------------------------------------------------------------ +# Minkowski Distance +# d = sum(x_i^p - y_i^p) ^ (1/p) +cdef class MinkowskiDistance(DistanceMetric): + """Minkowski Distance + + .. math:: + D(x, y) = [\sum_i (x_i - y_i)^p] ^ (1/p) + + Minkowski Distance requires p >= 1 and finite. For p = infinity, + use ChebyshevDistance. + Note that for p=1, ManhattanDistance is more efficient, and for + p=2, EuclideanDistance is more efficient. + """ + def __init__(self, p): + if p < 1: + raise ValueError("p must be greater than 1") + elif np.isinf(p): + raise ValueError("MinkowskiDistance requires finite p. " + "For p=inf, use ChebyshevDistance.") + self.p = p + + cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef DTYPE_t d=0 + cdef np.intp_t j + for j in range(size): + d += pow(fabs(x1[j] - x2[j]), self.p) + return d + + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + return pow(self.rdist(x1, x2, size), 1. / self.p) + + cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + return pow(rdist, 1. / self.p) + + cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + return pow(dist, self.p) + + def rdist_to_dist(self, rdist): + return rdist ** (1. / self.p) + + def dist_to_rdist(self, dist): + return dist ** self.p + + +#------------------------------------------------------------ +# W-Minkowski Distance +# d = sum(w_i * (x_i^p - y_i^p)) ^ (1/p) +cdef class WMinkowskiDistance(DistanceMetric): + """Weighted Minkowski Distance + + .. math:: + D(x, y) = [\sum_i w_i (x_i - y_i)^p] ^ (1/p) + + Weighted Minkowski Distance requires p >= 1 and finite. + + Parameters + ---------- + p : int + The order of the norm of the difference :math:`{||u-v||}_p`. + w : (N,) array_like + The weight vector. + + """ + def __init__(self, p, w): + if p < 1: + raise ValueError("p must be greater than 1") + elif np.isinf(p): + raise ValueError("WMinkowskiDistance requires finite p. " + "For p=inf, use ChebyshevDistance.") + self.p = p + self.vec = np.asarray(w, dtype=DTYPE) + self.vec_ptr = get_vec_ptr(self.vec) + self.size = self.vec.shape[0] + + cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + if size != self.size: + raise ValueError('WMinkowskiDistance dist: ' + 'size of w does not match') + cdef DTYPE_t d=0 + cdef np.intp_t j + for j in range(size): + d += pow(self.vec_ptr[j] * fabs(x1[j] - x2[j]), self.p) + return d + + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + return pow(self.rdist(x1, x2, size), 1. / self.p) + + cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + return pow(rdist, 1. / self.p) + + cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + return pow(dist, self.p) + + def rdist_to_dist(self, rdist): + return rdist ** (1. / self.p) + + def dist_to_rdist(self, dist): + return dist ** self.p + + +#------------------------------------------------------------ +# Mahalanobis Distance +# d = sqrt( (x - y)^T V^-1 (x - y) ) +cdef class MahalanobisDistance(DistanceMetric): + """Mahalanobis Distance + + .. math:: + D(x, y) = \sqrt{ (x - y)^T V^{-1} (x - y) } + + Parameters + ---------- + V : array_like + Symmetric positive-definite covariance matrix. + The inverse of this matrix will be explicitly computed. + VI : array_like + optionally specify the inverse directly. If VI is passed, + then V is not referenced. + """ + def __init__(self, V=None, VI=None): + if VI is None: + VI = np.linalg.inv(V) + if VI.ndim != 2 or VI.shape[0] != VI.shape[1]: + raise ValueError("V/VI must be square") + + self.mat = np.asarray(VI, dtype=float, order='C') + self.mat_ptr = get_mat_ptr(self.mat) + + self.size = self.mat.shape[0] + + # we need vec as a work buffer + self.vec = np.zeros(self.size, dtype=DTYPE) + self.vec_ptr = get_vec_ptr(self.vec) + + cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + if size != self.size: + raise ValueError('Mahalanobis dist: size of V does not match') + + cdef DTYPE_t tmp, d = 0 + cdef np.intp_t i, j + + # compute (x1 - x2).T * VI * (x1 - x2) + for i in range(size): + self.vec_ptr[i] = x1[i] - x2[i] + + for i in range(size): + tmp = 0 + for j in range(size): + tmp += self.mat_ptr[i * size + j] * self.vec_ptr[j] + d += tmp * self.vec_ptr[i] + return d + + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + return sqrt(self.rdist(x1, x2, size)) + + cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) except -1: + return sqrt(rdist) + + cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist) except -1: + return dist * dist + + def rdist_to_dist(self, rdist): + return np.sqrt(rdist) + + def dist_to_rdist(self, dist): + return dist ** 2 + + +#------------------------------------------------------------ +# Hamming Distance +# d = N_unequal(x, y) / N_tot +cdef class HammingDistance(DistanceMetric): + """Hamming Distance + + Hamming distance is meant for discrete-valued vectors, though it is + a valid metric for real-valued vectors. + + .. math:: + D(x, y) = \frac{1}{N} \sum_i \delta_{x_i, y_i} + """ + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef int n_unequal = 0 + cdef np.intp_t j + for j in range(size): + if x1[j] != x2[j]: + n_unequal += 1 + return float(n_unequal) / size + + +#------------------------------------------------------------ +# Canberra Distance +# D(x, y) = sum[ abs(x_i - y_i) / (abs(x_i) + abs(y_i)) ] +cdef class CanberraDistance(DistanceMetric): + """Canberra Distance + + Canberra distance is meant for discrete-valued vectors, though it is + a valid metric for real-valued vectors. + + .. math:: + D(x, y) = \sum_i \frac{|x_i - y_i|}{|x_i| + |y_i|} + """ + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef DTYPE_t denom, d = 0 + cdef np.intp_t j + for j in range(size): + denom = abs(x1[j]) + abs(x2[j]) + if denom > 0: + d += abs(x1[j] - x2[j]) / denom + return d + + +#------------------------------------------------------------ +# Bray-Curtis Distance +# D(x, y) = sum[abs(x_i - y_i)] / sum[abs(x_i) + abs(y_i)] +cdef class BrayCurtisDistance(DistanceMetric): + """Bray-Curtis Distance + + Bray-Curtis distance is meant for discrete-valued vectors, though it is + a valid metric for real-valued vectors. + + .. math:: + D(x, y) = \frac{\sum_i |x_i - y_i|}{\sum_i(|x_i| + |y_i|)} + """ + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef DTYPE_t num = 0, denom = 0 + cdef np.intp_t j + for j in range(size): + num += abs(x1[j] - x2[j]) + denom += abs(x1[j]) + abs(x2[j]) + if denom > 0: + return num / denom + else: + return 0.0 + + +#------------------------------------------------------------ +# Jaccard Distance (boolean) +# D(x, y) = N_unequal(x, y) / N_nonzero(x, y) +cdef class JaccardDistance(DistanceMetric): + """Jaccard Distance + + Jaccard Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + .. math:: + D(x, y) = \frac{N_{TF} + N_{FT}}{N_{TT} + N_{TF} + N_{FT}} + """ + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef int tf1, tf2, n_eq = 0, nnz = 0 + cdef np.intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + nnz += (tf1 or tf2) + n_eq += (tf1 and tf2) + return (nnz - n_eq) * 1.0 / nnz + + +#------------------------------------------------------------ +# Matching Distance (boolean) +# D(x, y) = n_neq / n +cdef class MatchingDistance(DistanceMetric): + """Matching Distance + + Matching Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + .. math:: + D(x, y) = \frac{N_{TF} + N_{FT}}{N} + """ + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef int tf1, tf2, n_neq = 0 + cdef np.intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_neq += (tf1 != tf2) + return n_neq * 1. / size + + +#------------------------------------------------------------ +# Dice Distance (boolean) +# D(x, y) = n_neq / (2 * ntt + n_neq) +cdef class DiceDistance(DistanceMetric): + """Dice Distance + + Dice Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + .. math:: + D(x, y) = \frac{N_{TF} + N_{FT}}{2 * N_{TT} + N_{TF} + N_{FT}} + """ + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef int tf1, tf2, n_neq = 0, ntt = 0 + cdef np.intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + ntt += (tf1 and tf2) + n_neq += (tf1 != tf2) + return n_neq / (2.0 * ntt + n_neq) + + +#------------------------------------------------------------ +# Kulsinski Distance (boolean) +# D(x, y) = (ntf + nft - ntt + n) / (n_neq + n) +cdef class KulsinskiDistance(DistanceMetric): + """Kulsinski Distance + + Kulsinski Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + .. math:: + D(x, y) = 1 - \frac{N_{TT}}{N + N_{TF} + N_{FT}} + """ + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef int tf1, tf2, ntt = 0, n_neq = 0 + cdef np.intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_neq += (tf1 != tf2) + ntt += (tf1 and tf2) + return (n_neq - ntt + size) * 1.0 / (n_neq + size) + + +#------------------------------------------------------------ +# Rogers-Tanimoto Distance (boolean) +# D(x, y) = 2 * n_neq / (n + n_neq) +cdef class RogersTanimotoDistance(DistanceMetric): + """Rogers-Tanimoto Distance + + Rogers-Tanimoto Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + .. math:: + D(x, y) = \frac{2 (N_{TF} + N_{FT})}{N + N_{TF} + N_{FT}} + """ + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef int tf1, tf2, n_neq = 0 + cdef np.intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_neq += (tf1 != tf2) + return (2.0 * n_neq) / (size + n_neq) + + +#------------------------------------------------------------ +# Russell-Rao Distance (boolean) +# D(x, y) = (n - ntt) / n +cdef class RussellRaoDistance(DistanceMetric): + """Russell-Rao Distance + + Russell-Rao Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + .. math:: + D(x, y) = \frac{N - N_{TT}}{N} + """ + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef int tf1, tf2, ntt = 0 + cdef np.intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + ntt += (tf1 and tf2) + return (size - ntt) * 1. / size + + +#------------------------------------------------------------ +# Sokal-Michener Distance (boolean) +# D(x, y) = 2 * n_neq / (n + n_neq) +cdef class SokalMichenerDistance(DistanceMetric): + """Sokal-Michener Distance + + Sokal-Michener Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + .. math:: + D(x, y) = \frac{2 (N_{TF} + N_{FT})}{N + N_{TF} + N_{FT}} + """ + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef int tf1, tf2, n_neq = 0 + cdef np.intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_neq += (tf1 != tf2) + return (2.0 * n_neq) / (size + n_neq) + + +#------------------------------------------------------------ +# Sokal-Sneath Distance (boolean) +# D(x, y) = n_neq / (0.5 * n_tt + n_neq) +cdef class SokalSneathDistance(DistanceMetric): + """Sokal-Sneath Distance + + Sokal-Sneath Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + .. math:: + D(x, y) = \frac{N_{TF} + N_{FT}}{N_{TT} / 2 + N_{TF} + N_{FT}} + """ + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef int tf1, tf2, ntt = 0, n_neq = 0 + cdef np.intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_neq += (tf1 != tf2) + ntt += (tf1 and tf2) + return n_neq / (0.5 * ntt + n_neq) + + +#------------------------------------------------------------ +# Haversine Distance (2 dimensional) +# D(x, y) = 2 arcsin{sqrt[sin^2 ((x1 - y1) / 2) +# + cos(x1) cos(y1) sin^2 ((x2 - y2) / 2)]} +cdef class HaversineDistance(DistanceMetric): + """Haversine (Spherical) Distance + + The Haversine distance is the angular distance between two points on + the surface of a sphere. The first distance of each point is assumed + to be the latitude, the second is the longitude, given in radians. + The dimension of the points must be 2: + + .. math:: + D(x, y) = 2\arcsin[\sqrt{\sin^2((x1 - y1) / 2) + + cos(x1)cos(y1)sin^2((x2 - y2) / 2)}] + """ + cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + if size != 2: + raise ValueError("Haversine distance only valid in 2 dimensions") + 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) + + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + if size != 2: + raise ValueError("Haversine distance only valid in 2 dimensions") + 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 2 * asin(sqrt(sin_0 * sin_0 + + cos(x1[0]) * cos(x2[0]) * sin_1 * sin_1)) + + cdef inline DTYPE_t _rdist_to_dist(self, DTYPE_t rdist): + return 2 * asin(sqrt(rdist)) + + cdef inline DTYPE_t _dist_to_rdist(self, DTYPE_t dist): + cdef DTYPE_t tmp = sin(0.5 * dist) + return tmp * tmp + + def rdist_to_dist(self, rdist): + return 2 * np.arcsin(np.sqrt(rdist)) + + def dist_to_rdist(self, dist): + tmp = np.sin(0.5 * dist) + return tmp * tmp + + +#------------------------------------------------------------ +# Yule Distance (boolean) +# D(x, y) = 2 * ntf * nft / (ntt * nff + ntf * nft) +# [This is not a true metric, so we will leave it out.] +# +#cdef class YuleDistance(DistanceMetric): +# cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size): +# cdef int tf1, tf2, ntf = 0, nft = 0, ntt = 0, nff = 0 +# cdef np.intp_t j +# for j in range(size): +# tf1 = x1[j] != 0 +# tf2 = x2[j] != 0 +# ntt += tf1 and tf2 +# ntf += tf1 and (tf2 == 0) +# nft += (tf1 == 0) and tf2 +# nff = size - ntt - ntf - nft +# return (2.0 * ntf * nft) / (ntt * nff + ntf * nft) + + +#------------------------------------------------------------ +# Cosine Distance +# D(x, y) = dot(x, y) / (|x| * |y|) +# [This is not a true metric, so we will leave it out.] +# +#cdef class CosineDistance(DistanceMetric): +# cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size): +# cdef DTYPE_t d = 0, norm1 = 0, norm2 = 0 +# cdef np.intp_t j +# for j in range(size): +# d += x1[j] * x2[j] +# norm1 += x1[j] * x1[j] +# norm2 += x2[j] * x2[j] +# return 1.0 - d / sqrt(norm1 * norm2) + + +#------------------------------------------------------------ +# Correlation Distance +# D(x, y) = dot((x - mx), (y - my)) / (|x - mx| * |y - my|) +# [This is not a true metric, so we will leave it out.] +# +#cdef class CorrelationDistance(DistanceMetric): +# cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, ITYPE_t size): +# cdef DTYPE_t mu1 = 0, mu2 = 0, x1nrm = 0, x2nrm = 0, x1Tx2 = 0 +# cdef DTYPE_t tmp1, tmp2 +# +# cdef np.intp_t i +# for i in range(size): +# mu1 += x1[i] +# mu2 += x2[i] +# mu1 /= size +# mu2 /= size +# +# for i in range(size): +# tmp1 = x1[i] - mu1 +# tmp2 = x2[i] - mu2 +# x1nrm += tmp1 * tmp1 +# x2nrm += tmp2 * tmp2 +# x1Tx2 += tmp1 * tmp2 +# +# return (1. - x1Tx2) / sqrt(x1nrm * x2nrm) + + +#------------------------------------------------------------ +# User-defined distance +# +cdef class PyFuncDistance(DistanceMetric): + """PyFunc Distance + + A user-defined distance + + Parameters + ---------- + func : function + func should take two numpy arrays as input, and return a distance. + """ + def __init__(self, func, **kwargs): + self.func = func + x = np.random.random(10) + try: + d = self.func(x, x, **kwargs) + except TypeError: + raise ValueError("func must be a callable taking two arrays") + + try: + d = float(d) + except TypeError: + raise ValueError("func must return a float") + + self.kwargs = kwargs + + cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + ITYPE_t size) except -1: + cdef np.ndarray x1arr = _buffer_to_ndarray(x1, size) + cdef np.ndarray x2arr = _buffer_to_ndarray(x2, size) + return self.func(x1arr, x2arr, **self.kwargs) + + +cdef inline double fmax(double a, double b): + return max(a, b) diff --git a/sklearn/neighbors/graph.py b/sklearn/neighbors/graph.py index cdfc3bcb9dcaf..3798871a43c5a 100644 --- a/sklearn/neighbors/graph.py +++ b/sklearn/neighbors/graph.py @@ -2,13 +2,52 @@ # Author: Jake Vanderplas # -# License: BSD, (C) INRIA, University of Amsterdam +# License: BSD 3 clause (C) INRIA, University of Amsterdam + +import warnings from .base import KNeighborsMixin, RadiusNeighborsMixin from .unsupervised import NearestNeighbors - -def kneighbors_graph(X, n_neighbors, mode='connectivity'): +def _check_params(X, metric, p, metric_params): + """Check the validity of the input parameters""" + params = zip(['metric', 'p', 'metric_params'], + [metric, p, metric_params]) + est_params = X.get_params() + for param_name, func_param in params: + if func_param != est_params[param_name]: + raise ValueError( + "Got %s for %s, while the estimator has %s for " + "the same parameter." % ( + func_param, param_name, est_params[param_name])) + + +def _query_include_self(X, include_self, mode): + """Return the query based on include_self param""" + # Done to preserve backward compatibility. + if include_self is None: + if mode == "connectivity": + warnings.warn( + "The behavior of 'kneighbors_graph' when mode='connectivity' " + "will change in version 0.18. Presently, the nearest neighbor " + "of each sample is the sample itself. Beginning in version " + "0.18, the default behavior will be to exclude each sample " + "from being its own nearest neighbor. To maintain the current " + "behavior, set include_self=True.", DeprecationWarning) + include_self = True + else: + include_self = False + + if include_self: + query = X._fit_X + else: + query = None + + return query + + +def kneighbors_graph(X, n_neighbors, mode='connectivity', metric='minkowski', + p=2, metric_params=None, include_self=None): """Computes the (weighted) graph of k-Neighbors for points in X Parameters @@ -25,6 +64,27 @@ def kneighbors_graph(X, n_neighbors, mode='connectivity'): connectivity matrix with ones and zeros, in 'distance' the edges are Euclidean distance between points. + metric : string, default 'minkowski' + The distance metric used to calculate the k-Neighbors for each sample + point. The DistanceMetric class gives a list of available metrics. + The default distance is 'euclidean' ('minkowski' metric with the p + param equal to 2.) + + include_self: bool, default backward-compatible. + Whether or not to mark each sample as the first nearest neighbor to + itself. If `None`, then True is used for mode='connectivity' and False + for mode='distance' as this will preserve backwards compatibilty. From + version 0.18, the default value will be False, irrespective of the + value of `mode`. + + p : int, default 2 + Power parameter for the Minkowski metric. When p = 1, this is + equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + + metric_params: dict, optional + additional keyword arguments for the metric function. + Returns ------- A : sparse matrix in CSR format, shape = [n_samples, n_samples] @@ -35,21 +95,28 @@ def kneighbors_graph(X, n_neighbors, mode='connectivity'): >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import kneighbors_graph >>> A = kneighbors_graph(X, 2) - >>> A.todense() - matrix([[ 1., 0., 1.], - [ 0., 1., 1.], - [ 1., 0., 1.]]) + >>> A.toarray() + array([[ 1., 0., 1.], + [ 0., 1., 1.], + [ 1., 0., 1.]]) See also -------- radius_neighbors_graph """ if not isinstance(X, KNeighborsMixin): - X = NearestNeighbors(n_neighbors).fit(X) - return X.kneighbors_graph(X._fit_X, n_neighbors, mode=mode) + X = NearestNeighbors( + n_neighbors, metric=metric, p=p, metric_params=metric_params + ).fit(X) + else: + _check_params(X, metric, p, metric_params) + query = _query_include_self(X, include_self, mode) + return X.kneighbors_graph(X=query, n_neighbors=n_neighbors, mode=mode) -def radius_neighbors_graph(X, radius, mode='connectivity'): + +def radius_neighbors_graph(X, radius, mode='connectivity', metric='minkowski', + p=2, metric_params=None, include_self=None): """Computes the (weighted) graph of Neighbors for points in X Neighborhoods are restricted the points at a distance lower than @@ -69,6 +136,27 @@ def radius_neighbors_graph(X, radius, mode='connectivity'): connectivity matrix with ones and zeros, in 'distance' the edges are Euclidean distance between points. + metric : string, default 'minkowski' + The distance metric used to calculate the neighbors within a + given radius for each sample point. The DistanceMetric class + gives a list of available metrics. The default distance is + 'euclidean' ('minkowski' metric with the param equal to 2.) + + include_self: bool, default None + Whether or not to mark each sample as the first nearest neighbor to + itself. If `None`, then True is used for mode='connectivity' and False + for mode='distance' as this will preserve backwards compatibilty. From + version 0.18, the default value will be False, irrespective of the + value of `mode`. + + p : int, default 2 + Power parameter for the Minkowski metric. When p = 1, this is + equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + + metric_params: dict, optional + additional keyword arguments for the metric function. + Returns ------- A : sparse matrix in CSR format, shape = [n_samples, n_samples] @@ -79,15 +167,22 @@ def radius_neighbors_graph(X, radius, mode='connectivity'): >>> X = [[0], [3], [1]] >>> from sklearn.neighbors import radius_neighbors_graph >>> A = radius_neighbors_graph(X, 1.5) - >>> A.todense() - matrix([[ 1., 0., 1.], - [ 0., 1., 0.], - [ 1., 0., 1.]]) + >>> A.toarray() + array([[ 1., 0., 1.], + [ 0., 1., 0.], + [ 1., 0., 1.]]) See also -------- kneighbors_graph """ if not isinstance(X, RadiusNeighborsMixin): - X = NearestNeighbors(radius=radius).fit(X) - return X.radius_neighbors_graph(X._fit_X, radius, mode) + X = NearestNeighbors( + radius=radius, metric=metric, p=p, + metric_params=metric_params + ).fit(X) + else: + _check_params(X, metric, p, metric_params) + + query = _query_include_self(X, include_self, mode) + return X.radius_neighbors_graph(query, radius, mode) diff --git a/sklearn/neighbors/kd_tree.c b/sklearn/neighbors/kd_tree.c new file mode 100644 index 0000000000000..2497690d25ae7 --- /dev/null +++ b/sklearn/neighbors/kd_tree.c @@ -0,0 +1,41111 @@ +/* Generated by Cython 0.20.1post0 (Debian 0.20.1+git90-g0e6e38e-1ubuntu2) on Thu Nov 27 09:12:01 2014 */ + +#define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#define CYTHON_ABI "0_20_1post0" +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if CYTHON_COMPILING_IN_PYPY +#define Py_OptimizeFlag 0 +#endif +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT) + #define Py_TPFLAGS_IS_ABSTRACT 0 +#endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_VERSION_HEX < 0x030200A4 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#ifdef __cplusplus +template +void __Pyx_call_destructor(T* x) { + x->~T(); +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__neighbors__kd_tree +#define __PYX_HAVE_API__sklearn__neighbors__kd_tree +#include "string.h" +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#include "math.h" +#include "pythread.h" +#include "pystate.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "binary_tree.pxi", + "kd_tree.pyx", + "__init__.pxd", + "stringsource", + "stringsource", + "type.pxd", + "dist_metrics.pxd", +}; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + +struct __pyx_memoryview_obj; +typedef struct { + struct __pyx_memoryview_obj *memview; + char *data; + Py_ssize_t shape[8]; + Py_ssize_t strides[8]; + Py_ssize_t suboffsets[8]; +} __Pyx_memviewslice; + +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __pyx_atomic_int_type int +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ + !defined(__i386__) + #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && MSC_VER + #include + #define __pyx_atomic_int_type LONG + #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using MSVC atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 + #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using Intel atomics" + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif +typedef volatile __pyx_atomic_int_type __pyx_atomic_int; +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview) \ + __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) +#else + #define __pyx_add_acquisition_count(memview) \ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif + + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":723 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":724 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":725 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":726 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":730 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":731 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":732 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":733 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":737 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":738 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":747 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":748 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":749 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":751 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":752 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":753 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":755 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":756 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":758 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":759 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":760 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; + +/* "typedefs.pxd":5 + * + * # Floating point/data type + * ctypedef np.float64_t DTYPE_t # WARNING: should match DTYPE in typedefs.pyx # <<<<<<<<<<<<<< + * + * cdef enum: + */ +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t; + +/* "typedefs.pxd":13 + * # Index/integer type. + * # WARNING: ITYPE_t must be a signed integer type or you will have a bad time! + * ctypedef np.intp_t ITYPE_t # WARNING: should match ITYPE in typedefs.pyx # <<<<<<<<<<<<<< + * + * # Fused type for certain operations + */ +typedef __pyx_t_5numpy_intp_t __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric; +struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap; +struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap; +struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree; +struct __pyx_obj_7sklearn_9neighbors_7kd_tree_KDTree; +struct __pyx_array_obj; +struct __pyx_MemviewEnum_obj; +struct __pyx_memoryview_obj; +struct __pyx_memoryviewslice_obj; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":762 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":763 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":764 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":766 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; + +/* "typedefs.pxd":7 + * ctypedef np.float64_t DTYPE_t # WARNING: should match DTYPE in typedefs.pyx + * + * cdef enum: # <<<<<<<<<<<<<< + * DTYPECODE = np.NPY_FLOAT64 + * ITYPECODE = np.NPY_INTP + */ +enum { + + /* "typedefs.pxd":9 + * cdef enum: + * DTYPECODE = np.NPY_FLOAT64 + * ITYPECODE = np.NPY_INTP # <<<<<<<<<<<<<< + * + * # Index/integer type. + */ + __pyx_e_7sklearn_9neighbors_8typedefs_DTYPECODE = NPY_FLOAT64, + __pyx_e_7sklearn_9neighbors_8typedefs_ITYPECODE = NPY_INTP +}; +struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t; +struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t; + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":385 + * # for all valid d and h. Note that for precision, the log of both + * # the kernel and kernel norm is returned. + * cdef enum KernelType: # <<<<<<<<<<<<<< + * GAUSSIAN_KERNEL = 1 + * TOPHAT_KERNEL = 2 + */ +enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType { + __pyx_e_7sklearn_9neighbors_7kd_tree_GAUSSIAN_KERNEL = 1, + __pyx_e_7sklearn_9neighbors_7kd_tree_TOPHAT_KERNEL = 2, + __pyx_e_7sklearn_9neighbors_7kd_tree_EPANECHNIKOV_KERNEL = 3, + __pyx_e_7sklearn_9neighbors_7kd_tree_EXPONENTIAL_KERNEL = 4, + __pyx_e_7sklearn_9neighbors_7kd_tree_LINEAR_KERNEL = 5, + __pyx_e_7sklearn_9neighbors_7kd_tree_COSINE_KERNEL = 6 +}; + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":169 + * + * # Some compound datatypes used below: + * cdef struct NodeHeapData_t: # <<<<<<<<<<<<<< + * DTYPE_t val + * ITYPE_t i1 + */ +struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t val; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t i2; +}; + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":188 + * 'itemsize': sizeof(NodeHeapData_t)}) + * + * cdef struct NodeData_t: # <<<<<<<<<<<<<< + * ITYPE_t idx_start + * ITYPE_t idx_end + */ +struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t idx_start; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t idx_end; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t is_leaf; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t radius; +}; + +/* "dist_metrics.pxd":48 + * ###################################################################### + * # DistanceMetric base class + * cdef class DistanceMetric: # <<<<<<<<<<<<<< + * # The following attributes are required for a few of the subclasses. + * # we must define them here so that cython's limited polymorphism will work. + */ +struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_vtab; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t p; + PyArrayObject *vec; + PyArrayObject *mat; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *vec_ptr; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *mat_ptr; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t size; + PyObject *func; + PyObject *kwargs; +}; + + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":560 + * + * + * cdef class NeighborsHeap: # <<<<<<<<<<<<<< + * """A max-heap structure to keep track of distances/indices of neighbors + * + */ +struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_vtab; + PyArrayObject *distances_arr; + PyArrayObject *indices_arr; + __Pyx_memviewslice distances; + __Pyx_memviewslice indices; +}; + + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":860 + * + * + * cdef class NodeHeap: # <<<<<<<<<<<<<< + * """NodeHeap + * + */ +struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_vtab; + PyArrayObject *data_arr; + __Pyx_memviewslice data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t n; +}; + + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":997 + * ###################################################################### + * # Binary Tree class + * cdef class BinaryTree: # <<<<<<<<<<<<<< + * + * cdef np.ndarray data_arr + */ +struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_vtab; + PyArrayObject *data_arr; + PyArrayObject *idx_array_arr; + PyArrayObject *node_data_arr; + PyArrayObject *node_bounds_arr; + __Pyx_memviewslice data; + __Pyx_memviewslice idx_array; + __Pyx_memviewslice node_data; + __Pyx_memviewslice node_bounds; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t leaf_size; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t n_levels; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t n_nodes; + struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *dist_metric; + int euclidean; + int n_trims; + int n_leaves; + int n_splits; + int n_calls; +}; + + +/* "sklearn/neighbors/kd_tree.pyx":21 + * include "binary_tree.pxi" + * + * cdef class KDTree(BinaryTree): # <<<<<<<<<<<<<< + * __doc__ = CLASS_DOC.format(**DOC_DICT) + * pass + */ +struct __pyx_obj_7sklearn_9neighbors_7kd_tree_KDTree { + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree __pyx_base; +}; + + +/* "View.MemoryView":99 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ +struct __pyx_array_obj { + PyObject_HEAD + char *data; + Py_ssize_t len; + char *format; + int ndim; + Py_ssize_t *_shape; + Py_ssize_t *_strides; + Py_ssize_t itemsize; + PyObject *mode; + PyObject *_format; + void (*callback_free_data)(void *); + int free_data; + int dtype_is_object; +}; + + +/* "View.MemoryView":269 + * + * @cname('__pyx_MemviewEnum') + * cdef class Enum(object): # <<<<<<<<<<<<<< + * cdef object name + * def __init__(self, name): + */ +struct __pyx_MemviewEnum_obj { + PyObject_HEAD + PyObject *name; +}; + + +/* "View.MemoryView":302 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ +struct __pyx_memoryview_obj { + PyObject_HEAD + struct __pyx_vtabstruct_memoryview *__pyx_vtab; + PyObject *obj; + PyObject *_size; + PyObject *_array_interface; + PyThread_type_lock lock; + __pyx_atomic_int acquisition_count[2]; + __pyx_atomic_int *acquisition_count_aligned_p; + Py_buffer view; + int flags; + int dtype_is_object; + __Pyx_TypeInfo *typeinfo; +}; + + +/* "View.MemoryView":922 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ +struct __pyx_memoryviewslice_obj { + struct __pyx_memoryview_obj __pyx_base; + __Pyx_memviewslice from_slice; + PyObject *from_object; + PyObject *(*to_object_func)(char *); + int (*to_dtype_func)(char *, PyObject *); +}; + + + +/* "dist_metrics.pxd":48 + * ###################################################################### + * # DistanceMetric base class + * cdef class DistanceMetric: # <<<<<<<<<<<<<< + * # The following attributes are required for a few of the subclasses. + * # we must define them here so that cython's limited polymorphism will work. + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*dist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*rdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*pdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __Pyx_memviewslice, __Pyx_memviewslice); + int (*cdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*_rdist_to_dist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*_dist_to_rdist)(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric; + + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":560 + * + * + * cdef class NeighborsHeap: # <<<<<<<<<<<<<< + * """A max-heap structure to keep track of distances/indices of neighbors + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NeighborsHeap { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*largest)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*push)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, int __pyx_skip_dispatch); + int (*_sort)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *); +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_vtabptr_7sklearn_9neighbors_7kd_tree_NeighborsHeap; +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":860 + * + * + * cdef class NodeHeap: # <<<<<<<<<<<<<< + * """NodeHeap + * + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap { + int (*resize)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*push)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *, struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t); + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t (*peek)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *); + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t (*pop)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *); + void (*clear)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *); +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_vtabptr_7sklearn_9neighbors_7kd_tree_NodeHeap; + + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":997 + * ###################################################################### + * # Binary Tree class + * cdef class BinaryTree: # <<<<<<<<<<<<<< + * + * cdef np.ndarray data_arr + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*dist)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*rdist)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*_recursive_build)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*_query_single_depthfirst)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + int (*_query_single_breadthfirst)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *); + int (*_query_dual_depthfirst)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __Pyx_memviewslice, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + int (*_query_dual_breadthfirst)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *); + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t (*_query_radius_single)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, int, int); + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*_kde_single_breadthfirst)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); + int (*_kde_single_depthfirst)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); + int (*_two_point_single)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + int (*_two_point_dual)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_vtabptr_7sklearn_9neighbors_7kd_tree_BinaryTree; +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_dist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_rdist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + + +/* "sklearn/neighbors/kd_tree.pyx":21 + * include "binary_tree.pxi" + * + * cdef class KDTree(BinaryTree): # <<<<<<<<<<<<<< + * __doc__ = CLASS_DOC.format(**DOC_DICT) + * pass + */ + +struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_KDTree { + struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_KDTree *__pyx_vtabptr_7sklearn_9neighbors_7kd_tree_KDTree; + + +/* "View.MemoryView":302 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ + +struct __pyx_vtabstruct_memoryview { + char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); + PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); +}; +static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; + + +/* "View.MemoryView":922 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ + +struct __pyx_vtabstruct__memoryviewslice { + struct __pyx_vtabstruct_memoryview __pyx_base; +}; +static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d +#define __Pyx_MEMVIEW_DIRECT 1 +#define __Pyx_MEMVIEW_PTR 2 +#define __Pyx_MEMVIEW_FULL 4 +#define __Pyx_MEMVIEW_CONTIG 8 +#define __Pyx_MEMVIEW_STRIDED 16 +#define __Pyx_MEMVIEW_FOLLOW 32 +#define __Pyx_IS_C_CONTIG 1 +#define __Pyx_IS_F_CONTIG 2 +static int __Pyx_init_memviewslice( + struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference); +static CYTHON_INLINE int __pyx_add_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) +#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) +#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) +#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) +static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +#include + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals +#else +#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals +#endif + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +static CYTHON_INLINE int __Pyx_CheckKeywordStrings(PyObject *kwdict, const char* function_name, int kw_allowed); /*proto*/ + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename, + int full_traceback); /*proto*/ + +static CYTHON_INLINE int __Pyx_PySequence_Contains(PyObject* item, PyObject* seq, int eq) { + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); + +#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) : \ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck); + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); /*proto*/ + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) + +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /*proto*/ + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject* none = _PyList_Extend((PyListObject*)L, v); + if (unlikely(!none)) + return -1; + Py_DECREF(none); + return 0; +#else + return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); +#endif +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +#if PY_MAJOR_VERSION < 3 +#define __Pyx_PyString_Join __Pyx_PyBytes_Join +#define __Pyx_PyBaseString_Join(s, v) (PyUnicode_CheckExact(s) ? PyUnicode_Join(s, v) : __Pyx_PyBytes_Join(s, v)) +#else +#define __Pyx_PyString_Join PyUnicode_Join +#define __Pyx_PyBaseString_Join PyUnicode_Join +#endif +#if CYTHON_COMPILING_IN_CPYTHON + #if PY_MAJOR_VERSION < 3 + #define __Pyx_PyBytes_Join _PyString_Join + #else + #define __Pyx_PyBytes_Join _PyBytes_Join + #endif +#else +static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values); /*proto*/ +#endif + +static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ + +static void* __Pyx_GetVtable(PyObject *dict); /*proto*/ + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /*proto*/ + +static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); + +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *); + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); + +static PyObject *__pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(const char *itemp); /* proto */ +static int __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(const char *itemp, PyObject *obj); /* proto */ + +static CYTHON_INLINE long __Pyx_pow_long(long, long); /* proto */ + +static PyObject *__pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(const char *itemp); /* proto */ +static int __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(const char *itemp, PyObject *obj); /* proto */ + +struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t; +static PyObject* __pyx_convert__to_py___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t s); +struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t; +static struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_convert__from_py___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(PyObject *); + +static PyObject *__pyx_memview_get_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(const char *itemp); /* proto */ +static int __pyx_memview_set_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(const char *itemp, PyObject *obj); /* proto */ + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim); + +static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize); + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object); + +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); + +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); + +struct __pyx_typeinfo_string { + char string[3]; +}; +static struct __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *type); + +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t(PyObject *); + +static int __Pyx_check_binary_version(void); + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'cython.view' */ +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ + +/* Module declarations from 'cython' */ + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'libc.math' */ + +/* Module declarations from 'sklearn.utils.lgamma' */ +static double (*__pyx_f_7sklearn_5utils_6lgamma_lgamma)(double); /*proto*/ + +/* Module declarations from 'sklearn.neighbors.typedefs' */ + +/* Module declarations from 'sklearn.neighbors.dist_metrics' */ +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric = 0; +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist_to_rdist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist_to_dist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ + +/* Module declarations from 'sklearn.neighbors.kd_tree' */ +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_7kd_tree_NeighborsHeap = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_7kd_tree_NodeHeap = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree = 0; +static PyTypeObject *__pyx_ptype_7sklearn_9neighbors_7kd_tree_KDTree = 0; +static PyTypeObject *__pyx_array_type = 0; +static PyTypeObject *__pyx_MemviewEnum_type = 0; +static PyTypeObject *__pyx_memoryview_type = 0; +static PyTypeObject *__pyx_memoryviewslice_type = 0; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_7kd_tree_INF; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_7kd_tree_NEG_INF; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_7kd_tree_PI; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_7kd_tree_ROOT_2PI; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_7kd_tree_LOG_PI; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_7kd_tree_LOG_2PI; +static struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_v_7sklearn_9neighbors_7kd_tree_nhd_tmp; +static struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_7sklearn_9neighbors_7kd_tree_nd_tmp; +static PyObject *generic = 0; +static PyObject *strided = 0; +static PyObject *indirect = 0; +static PyObject *contiguous = 0; +static PyObject *indirect_contiguous = 0; +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_1D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_2D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_3D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_1D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_2D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_NodeHeapData_1D(PyArrayObject *); /*proto*/ +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_NodeData_1D(PyArrayObject *); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_gaussian_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_tophat_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_epanechnikov_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_exponential_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_linear_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_cosine_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_logVn(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_logSn(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree__log_kernel_norm(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType); /*proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_7kd_tree_dual_swap(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static int __pyx_f_7sklearn_9neighbors_7kd_tree__simultaneous_sort(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_find_node_split_dim(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static int __pyx_f_7sklearn_9neighbors_7kd_tree_partition_node_indices(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_7kd_tree_swap_nodes(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE double __pyx_f_7sklearn_9neighbors_7kd_tree_fmin(double, double); /*proto*/ +static CYTHON_INLINE double __pyx_f_7sklearn_9neighbors_7kd_tree_fmax(double, double); /*proto*/ +static int __pyx_f_7sklearn_9neighbors_7kd_tree_allocate_data(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static int __pyx_f_7sklearn_9neighbors_7kd_tree_init_node(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_min_dist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_max_rdist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); /*proto*/ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_max_dist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); /*proto*/ +static CYTHON_INLINE int __pyx_f_7sklearn_9neighbors_7kd_tree_min_max_dist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist_dual(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_min_dist_dual(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_max_rdist_dual(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_max_dist_dual(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); /*proto*/ +static CYTHON_INLINE void __pyx_fuse_0__pyx_f_7sklearn_9neighbors_7kd_tree_swap(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, int, int); /*proto*/ +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ +static void *__pyx_align_pointer(void *, size_t); /*proto*/ +static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ +static PyObject *_unellipsify(PyObject *, int); /*proto*/ +static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ +static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ +static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ +static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ +static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ +static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ +static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ +static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ +static PyObject *__pyx_format_from_typeinfo(__Pyx_TypeInfo *); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t = { "ITYPE_t", NULL, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t), 0 }; +static __Pyx_StructField __Pyx_StructFields_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t[] = { + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, "val", offsetof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t, val)}, + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, "i1", offsetof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t, i1)}, + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, "i2", offsetof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t, i2)}, + {NULL, NULL, 0} +}; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t = { "NodeHeapData_t", __Pyx_StructFields_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t, sizeof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t), { 0 }, 0, 'S', 0, 0 }; +static __Pyx_StructField __Pyx_StructFields_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t[] = { + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, "idx_start", offsetof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t, idx_start)}, + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, "idx_end", offsetof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t, idx_end)}, + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, "is_leaf", offsetof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t, is_leaf)}, + {&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, "radius", offsetof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t, radius)}, + {NULL, NULL, 0} +}; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t = { "NodeData_t", __Pyx_StructFields_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t, sizeof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t), { 0 }, 0, 'S', 0, 0 }; +#define __Pyx_MODULE_NAME "sklearn.neighbors.kd_tree" +int __pyx_module_is_main_sklearn__neighbors__kd_tree = 0; + +/* Implementation of 'sklearn.neighbors.kd_tree' */ +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_Ellipsis; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_xrange; +static PyObject *__pyx_builtin_id; +static PyObject *__pyx_builtin_IndexError; +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_kernel_norm(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_h, PyObject *__pyx_v_d, PyObject *__pyx_v_kernel, PyObject *__pyx_v_return_log); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap___cinit__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_2__init__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_self, PyObject *__pyx_v_n_pts, PyObject *__pyx_v_n_nbrs); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_4get_arrays(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_self, PyObject *__pyx_v_sort); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_6push(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_val, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_val); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_8NodeHeap___cinit__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_8NodeHeap_2__init__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_self, PyObject *__pyx_v_size_guess); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_2newObj(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_obj); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree___cinit__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_2__init__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_data, PyObject *__pyx_v_leaf_size, PyObject *__pyx_v_metric, PyObject *__pyx_v_kwargs); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_4__reduce__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_6__getstate__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_8__setstate__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_state); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_10get_tree_stats(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_12reset_n_calls(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_14get_n_calls(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_16get_arrays(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_18query(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_k, PyObject *__pyx_v_return_distance, PyObject *__pyx_v_dualtree, PyObject *__pyx_v_breadth_first, PyObject *__pyx_v_sort_results); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_20query_radius(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_r, PyObject *__pyx_v_return_distance, int __pyx_v_count_only, int __pyx_v_sort_results); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_22kernel_density(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_h, PyObject *__pyx_v_kernel, PyObject *__pyx_v_atol, PyObject *__pyx_v_rtol, PyObject *__pyx_v_breadth_first, PyObject *__pyx_v_return_log); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_24two_point_correlation(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_r, PyObject *__pyx_v_dualtree); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_4data___get__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array___get__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array_2__set__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data___get__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data_2__set__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds___get__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds_2__set__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_4load_heap(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_k); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_6simultaneous_sort(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_distances, __Pyx_memviewslice __pyx_v_indices); /* proto */ +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_8nodeheap_sort(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_vals); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_7kd_tree_NeighborsHeap(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_7kd_tree_NodeHeap(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_7kd_tree_BinaryTree(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_9neighbors_7kd_tree_KDTree(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_B[] = "B"; +static char __pyx_k_C[] = "C"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_T[] = "T{"; + static char __pyx_k_X[] = "X"; + static char __pyx_k_b[] = "b"; + static char __pyx_k_c[] = "c"; + static char __pyx_k_d[] = "d"; + static char __pyx_k_f[] = "f"; + static char __pyx_k_g[] = "g"; + static char __pyx_k_h[] = "h"; + static char __pyx_k_i[] = "i"; + static char __pyx_k_j[] = "j"; + static char __pyx_k_k[] = "k"; + static char __pyx_k_l[] = "l"; + static char __pyx_k_q[] = "q"; + static char __pyx_k_r[] = "r"; + static char __pyx_k_s[] = "(%s)"; + static char __pyx_k_Zd[] = "Zd"; + static char __pyx_k_Zf[] = "Zf"; + static char __pyx_k_Zg[] = "Zg"; + static char __pyx_k_i1[] = "i1"; + static char __pyx_k_i2[] = "i2"; + static char __pyx_k_id[] = "id"; + static char __pyx_k_np[] = "np"; + static char __pyx_k_pi[] = "pi"; + static char __pyx_k__50[] = "^"; + static char __pyx_k__51[] = ""; + static char __pyx_k__52[] = ":"; +static char __pyx_k__53[] = "}"; +static char __pyx_k__54[] = ","; +static char __pyx_k_all[] = "__all__"; +static char __pyx_k_doc[] = "__doc__"; +static char __pyx_k_exp[] = "exp"; +static char __pyx_k_inf[] = "inf"; +static char __pyx_k_new[] = "__new__"; +static char __pyx_k_obj[] = "obj"; +static char __pyx_k_row[] = "row"; +static char __pyx_k_val[] = "val"; +static char __pyx_k_atol[] = "atol"; +static char __pyx_k_base[] = "base"; +static char __pyx_k_copy[] = "copy"; +static char __pyx_k_data[] = "data"; +static char __pyx_k_heap[] = "heap"; +static char __pyx_k_join[] = "join"; +static char __pyx_k_log2[] = "log2"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_mode[] = "mode"; +static char __pyx_k_name[] = "__name__"; +static char __pyx_k_ndim[] = "ndim"; +static char __pyx_k_pack[] = "pack"; +static char __pyx_k_push[] = "push"; +static char __pyx_k_rtol[] = "rtol"; +static char __pyx_k_size[] = "size"; +static char __pyx_k_sort[] = "sort"; +static char __pyx_k_step[] = "step"; +static char __pyx_k_stop[] = "stop"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_vals[] = "vals"; +static char __pyx_k_warn[] = "warn"; +static char __pyx_k_DTYPE[] = "DTYPE"; +static char __pyx_k_ITYPE[] = "ITYPE"; +static char __pyx_k_class[] = "__class__"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_empty[] = "empty"; +static char __pyx_k_error[] = "error"; +static char __pyx_k_flags[] = "flags"; +static char __pyx_k_i_val[] = "i_val"; +static char __pyx_k_n_pts[] = "n_pts"; +static char __pyx_k_names[] = "names"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_order[] = "order"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_shape[] = "shape"; +static char __pyx_k_start[] = "start"; +static char __pyx_k_utils[] = "utils"; +static char __pyx_k_zeros[] = "zeros"; +static char __pyx_k_KDTree[] = "KDTree"; +static char __pyx_k_arange[] = "arange"; +static char __pyx_k_cosine[] = "cosine"; +static char __pyx_k_format[] = "format"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_kernel[] = "kernel"; +static char __pyx_k_linear[] = "linear"; +static char __pyx_k_metric[] = "metric"; +static char __pyx_k_n_nbrs[] = "n_nbrs"; +static char __pyx_k_name_2[] = "name"; +static char __pyx_k_newObj[] = "newObj"; +static char __pyx_k_object[] = "object"; +static char __pyx_k_radius[] = "radius"; +static char __pyx_k_result[] = "result"; +static char __pyx_k_struct[] = "struct"; +static char __pyx_k_tophat[] = "tophat"; +static char __pyx_k_unpack[] = "unpack"; +static char __pyx_k_xrange[] = "xrange"; +static char __pyx_k_argsort[] = "argsort"; +static char __pyx_k_asarray[] = "asarray"; +static char __pyx_k_formats[] = "formats"; +static char __pyx_k_fortran[] = "fortran"; +static char __pyx_k_idx_end[] = "idx_end"; +static char __pyx_k_indices[] = "indices"; +static char __pyx_k_is_leaf[] = "is_leaf"; +static char __pyx_k_kd_tree[] = "kd_tree"; +static char __pyx_k_memview[] = "memview"; +static char __pyx_k_offsets[] = "offsets"; +static char __pyx_k_reshape[] = "reshape"; +static char __pyx_k_DOC_DICT[] = "DOC_DICT"; +static char __pyx_k_Ellipsis[] = "Ellipsis"; +static char __pyx_k_NodeData[] = "NodeData"; +static char __pyx_k_dualtree[] = "dualtree"; +static char __pyx_k_gaussian[] = "gaussian"; +static char __pyx_k_getstate[] = "__getstate__"; +static char __pyx_k_itemsize[] = "itemsize"; +static char __pyx_k_typedefs[] = "typedefs"; +static char __pyx_k_warnings[] = "warnings"; +static char __pyx_k_CLASS_DOC[] = "CLASS_DOC"; +static char __pyx_k_TypeError[] = "TypeError"; +static char __pyx_k_distances[] = "distances"; +static char __pyx_k_enumerate[] = "enumerate"; +static char __pyx_k_idx_start[] = "idx_start"; +static char __pyx_k_leaf_size[] = "leaf_size"; +static char __pyx_k_load_heap[] = "load_heap"; +static char __pyx_k_minkowski[] = "minkowski"; +static char __pyx_k_node_data[] = "node_data"; +static char __pyx_k_BinaryTree[] = "BinaryTree"; +static char __pyx_k_IndexError[] = "IndexError"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_atleast_1d[] = "atleast_1d"; +static char __pyx_k_count_only[] = "count_only"; +static char __pyx_k_get_arrays[] = "get_arrays"; +static char __pyx_k_get_metric[] = "get_metric"; +static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static char __pyx_k_return_log[] = "return_log"; +static char __pyx_k_size_guess[] = "size_guess"; +static char __pyx_k_zeros_like[] = "zeros_like"; +static char __pyx_k_MemoryError[] = "MemoryError"; +static char __pyx_k_binary_tree[] = "binary_tree"; +static char __pyx_k_check_array[] = "check_array"; +static char __pyx_k_exponential[] = "exponential"; +static char __pyx_k_kernel_norm[] = "kernel_norm"; +static char __pyx_k_vals_sorted[] = "vals_sorted"; +static char __pyx_k_NodeHeapData[] = "NodeHeapData"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_dist_metrics[] = "dist_metrics"; +static char __pyx_k_epanechnikov[] = "epanechnikov"; +static char __pyx_k_sort_results[] = "sort_results"; +static char __pyx_k_VALID_METRICS[] = "VALID_METRICS"; +static char __pyx_k_breadth_first[] = "breadth_first"; +static char __pyx_k_nodeheap_sort[] = "nodeheap_sort"; +static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k_rdist_to_dist[] = "rdist_to_dist"; +static char __pyx_k_valid_metrics[] = "valid_metrics"; +static char __pyx_k_allocate_buffer[] = "allocate_buffer"; +static char __pyx_k_dtype_is_object[] = "dtype_is_object"; +static char __pyx_k_return_distance[] = "return_distance"; +static char __pyx_k_VALID_METRIC_IDS[] = "VALID_METRIC_IDS"; +static char __pyx_k_ChebyshevDistance[] = "ChebyshevDistance"; +static char __pyx_k_EuclideanDistance[] = "EuclideanDistance"; +static char __pyx_k_ManhattanDistance[] = "ManhattanDistance"; +static char __pyx_k_MinkowskiDistance[] = "MinkowskiDistance"; +static char __pyx_k_pyx_releasebuffer[] = "__pyx_releasebuffer"; +static char __pyx_k_simultaneous_sort[] = "simultaneous_sort"; +static char __pyx_k_strided_and_direct[] = ""; +static char __pyx_k_X_is_an_empty_array[] = "X is an empty array"; +static char __pyx_k_get_valid_metric_ids[] = "get_valid_metric_ids"; +static char __pyx_k_strided_and_indirect[] = ""; +static char __pyx_k_contiguous_and_direct[] = ""; +static char __pyx_k_kernel_not_recognized[] = "kernel not recognized"; +static char __pyx_k_MemoryView_of_r_object[] = ""; +static char __pyx_k_MemoryView_of_r_at_0x_x[] = ""; +static char __pyx_k_contiguous_and_indirect[] = ""; +static char __pyx_k_kernel_s_not_recognized[] = "kernel = '%s' not recognized"; +static char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; +static char __pyx_k_cannot_pop_on_empty_heap[] = "cannot pop on empty heap"; +static char __pyx_k_getbuffer_obj_view_flags[] = "getbuffer(obj, view, flags)"; +static char __pyx_k_Dimension_d_is_not_direct[] = "Dimension %d is not direct"; +static char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; +static char __pyx_k_sklearn_neighbors_kd_tree[] = "sklearn.neighbors.kd_tree"; +static char __pyx_k_BinaryTree_query_line_1228[] = "BinaryTree.query (line 1228)"; +static char __pyx_k_Index_out_of_bounds_axis_d[] = "Index out of bounds (axis %d)"; +static char __pyx_k_Kernel_code_not_recognized[] = "Kernel code not recognized"; +static char __pyx_k_Step_may_not_be_zero_axis_d[] = "Step may not be zero (axis %d)"; +static char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; +static char __pyx_k_kernel_density_self_X_h_kernel[] = "\n kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1E-8,\n breadth_first=True, return_log=False)\n\n Compute the kernel density estimate at points X with the given kernel,\n using the distance metric specified at tree creation.\n\n Parameters\n ----------\n X : array_like\n An array of points to query. Last dimension should match dimension\n of training data.\n h : float\n the bandwidth of the kernel\n kernel : string\n specify the kernel to use. Options are\n - 'gaussian'\n - 'tophat'\n - 'epanechnikov'\n - 'exponential'\n - 'linear'\n - 'cosine'\n Default is kernel = 'gaussian'\n atol, rtol : float (default = 0)\n Specify the desired relative and absolute tolerance of the result.\n If the true result is K_true, then the returned result K_ret\n satisfies ``abs(K_true - K_ret) < atol + rtol * K_ret``\n The default is zero (i.e. machine precision) for both.\n breadth_first : boolean (default = False)\n if True, use a breadth-first search. If False (default) use a\n depth-first search. Breadth-first is generally faster for\n compact kernels and/or high tolerances.\n return_log : boolean (default = False)\n return the logarithm of the result. This can be more accurate\n than returning the result itself for narrow kernels.\n\n Returns\n -------\n density : ndarray\n The array of (log)-density evaluations, shape = X.shape[:-1]\n\n Examples\n --------\n Compute a gaussian kernel density estimate:\n\n >>> import numpy as np\n >>> np.random.seed(1)\n >>> X = np.random.random((100, 3))\n >>> tree = BinaryTree(X) # doctest: +SKIP\n >>> tree.kernel_den""sity(X[:3], h=0.1, kernel='gaussian')\n array([ 6.94114649, 7.83281226, 7.2071716 ])\n "; +static char __pyx_k_strided_and_direct_or_indirect[] = ""; +static char __pyx_k_BinaryTree_for_fast_generalized[] = "{BinaryTree} for fast generalized N-point problems\n\n{BinaryTree}(X, leaf_size=40, metric='minkowski', **kwargs)\n\nParameters\n----------\nX : array-like, shape = [n_samples, n_features]\n n_samples is the number of points in the data set, and\n n_features is the dimension of the parameter space.\n Note: if X is a C-contiguous array of doubles then data will\n not be copied. Otherwise, an internal copy will be made.\n\nleaf_size : positive integer (default = 20)\n Number of points at which to switch to brute-force. Changing\n leaf_size will not affect the results of a query, but can\n significantly impact the speed of a query and the memory required\n to store the constructed tree. The amount of memory needed to\n store the tree scales as approximately n_samples / leaf_size.\n For a specified ``leaf_size``, a leaf node is guaranteed to\n satisfy ``leaf_size <= n_points <= 2 * leaf_size``, except in\n the case that ``n_samples < leaf_size``.\n\nmetric : string or DistanceMetric object\n the distance metric to use for the tree. Default='minkowski'\n with p=2 (that is, a euclidean metric). See the documentation\n of the DistanceMetric class for a list of available metrics.\n {binary_tree}.valid_metrics gives a list of the metrics which\n are valid for {BinaryTree}.\n\nAdditional keywords are passed to the distance metric class.\n\nAttributes\n----------\ndata : np.ndarray\n The training data\n\nExamples\n--------\nQuery for k-nearest neighbors\n\n >>> import numpy as np\n\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions\n >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP\n >>> dist, ind = tree.query(X[0], k=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors\n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n\nPickle and Unpickle a tree. Not""e that the state of the tree is saved in the\npickle operation: the tree needs not be rebuilt upon unpickling.\n\n >>> import numpy as np\n >>> import pickle\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions\n >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP\n >>> s = pickle.dumps(tree) # doctest: +SKIP\n >>> tree_copy = pickle.loads(s) # doctest: +SKIP\n >>> dist, ind = tree_copy.query(X[0], k=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors\n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n\nQuery for neighbors within a given radius\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions\n >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP\n >>> print tree.query_radius(X[0], r=0.3, count_only=True)\n 3\n >>> ind = tree.query_radius(X[0], r=0.3) # doctest: +SKIP\n >>> print ind # indices of neighbors within distance 0.3\n [3 0 1]\n\n\nCompute a gaussian kernel density estimate:\n\n >>> import numpy as np\n >>> np.random.seed(1)\n >>> X = np.random.random((100, 3))\n >>> tree = {BinaryTree}(X) # doctest: +SKIP\n >>> tree.kernel_density(X[:3], h=0.1, kernel='gaussian')\n array([ 6.94114649, 7.83281226, 7.2071716 ])\n\nCompute a two-point auto-correlation function\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((30, 3))\n >>> r = np.linspace(0, 1, 5)\n >>> tree = {BinaryTree}(X) # doctest: +SKIP\n >>> tree.two_point_correlation(X, r)\n array([ 30, 62, 278, 580, 820])\n\n"; +static char __pyx_k_Fatal_count_too_big_this_should[] = "Fatal: count too big: this should never happen"; +static char __pyx_k_home_manoj_scikit_learn_sklearn[] = "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi"; +static char __pyx_k_k_must_be_less_than_or_equal_to[] = "k must be less than or equal to the number of training points"; +static char __pyx_k_query_X_k_1_return_distance_Tru[] = "\n query(X, k=1, return_distance=True,\n dualtree=False, breadth_first=False)\n\n query the tree for the k nearest neighbors\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n k : integer (default = 1)\n The number of nearest neighbors to return\n return_distance : boolean (default = True)\n if True, return a tuple (d, i) of distances and indices\n if False, return array i\n dualtree : boolean (default = False)\n if True, use the dual tree formalism for the query: a tree is\n built for the query points, and the pair of trees is used to\n efficiently search this space. This can lead to better\n performance as the number of points grows large.\n breadth_first : boolean (default = False)\n if True, then query the nodes in a breadth-first manner.\n Otherwise, query the nodes in a depth-first manner.\n sort_results : boolean (default = True)\n if True, then distances and indices of each point are sorted\n on return, so that the first column contains the closest points.\n Otherwise, neighbors are returned in an arbitrary order.\n\n Returns\n -------\n i : if return_distance == False\n (d,i) : if return_distance == True\n\n d : array of doubles - shape: x.shape[:-1] + (k,)\n each entry gives the list of distances to the\n neighbors of the corresponding point\n\n i : array of integers - shape: x.shape[:-1] + (k,)\n each entry gives the list of indices of\n neighbors of the corresponding point\n\n Examples\n --------\n Query for k-nearest neighbors\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimension""s\n >>> tree = BinaryTree(X, leaf_size=2) # doctest: +SKIP\n >>> dist, ind = tree.query(X[0], k=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors\n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n "; +static char __pyx_k_query_data_dimension_must_match[] = "query data dimension must match training data dimension"; +static char __pyx_k_query_radius_self_X_r_count_onl[] = "\n query_radius(self, X, r, count_only = False):\n\n query the tree for neighbors within a radius r\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n r : distance within which neighbors are returned\n r can be a single value, or an array of values of shape\n x.shape[:-1] if different radii are desired for each point.\n return_distance : boolean (default = False)\n if True, return distances to neighbors of each point\n if False, return only neighbors\n Note that unlike the query() method, setting return_distance=True\n here adds to the computation time. Not all distances need to be\n calculated explicitly for return_distance=False. Results are\n not sorted by default: see ``sort_results`` keyword.\n count_only : boolean (default = False)\n if True, return only the count of points within distance r\n if False, return the indices of all points within distance r\n If return_distance==True, setting count_only=True will\n result in an error.\n sort_results : boolean (default = False)\n if True, the distances and indices will be sorted before being\n returned. If False, the results will not be sorted. If\n return_distance == False, setting sort_results = True will\n result in an error.\n\n Returns\n -------\n count : if count_only == True\n ind : if count_only == False and return_distance == False\n (ind, dist) : if count_only == False and return_distance == True\n\n count : array of integers, shape = X.shape[:-1]\n each entry gives the number of neighbors within\n a distance r of the corresponding point.\n\n ind : array of objects, shape = X.shape[:-1]\n each element is a num""py integer array listing the indices of\n neighbors of the corresponding point. Note that unlike\n the results of a k-neighbors query, the returned neighbors\n are not sorted by distance by default.\n\n dist : array of objects, shape = X.shape[:-1]\n each element is a numpy double array\n listing the distances corresponding to indices in i.\n\n Examples\n --------\n Query for neighbors in a given radius\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions\n >>> tree = BinaryTree(X, leaf_size=2) # doctest: +SKIP\n >>> print tree.query_radius(X[0], r=0.3, count_only=True)\n 3\n >>> ind = tree.query_radius(X[0], r=0.3) # doctest: +SKIP\n >>> print ind # indices of neighbors within distance 0.3\n [3 0 1]\n "; +static char __pyx_k_r_must_be_a_1_dimensional_array[] = "r must be a 1-dimensional array"; +static char __pyx_k_return_distance_must_be_True_if[] = "return_distance must be True if sort_results is True"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_All_dimensions_preceding_dimensi[] = "All dimensions preceding dimension %d must be indexed and not sliced"; +static char __pyx_k_BinaryTree_kernel_density_line_1[] = "BinaryTree.kernel_density (line 1499)"; +static char __pyx_k_BinaryTree_query_radius_line_135[] = "BinaryTree.query_radius (line 1353)"; +static char __pyx_k_BinaryTree_two_point_correlation[] = "BinaryTree.two_point_correlation (line 1650)"; +static char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; +static char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; +static char __pyx_k_Cannot_transpose_memoryview_with[] = "Cannot transpose memoryview with indirect dimensions"; +static char __pyx_k_Compute_the_two_point_correlatio[] = "Compute the two-point correlation function\n\n Parameters\n ----------\n X : array_like\n An array of points to query. Last dimension should match dimension\n of training data.\n r : array_like\n A one-dimensional array of distances\n dualtree : boolean (default = False)\n If true, use a dualtree algorithm. Otherwise, use a single-tree\n algorithm. Dual tree algorithms can have better scaling for\n large N.\n\n Returns\n -------\n counts : ndarray\n counts[i] contains the number of pairs of points with distance\n less than or equal to r[i]\n\n Examples\n --------\n Compute the two-point autocorrelation function of X:\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((30, 3))\n >>> r = np.linspace(0, 1, 5)\n >>> tree = BinaryTree(X) # doctest: +SKIP\n >>> tree.two_point_correlation(X, r)\n array([ 30, 62, 278, 580, 820])\n "; +static char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; +static char __pyx_k_Fatal_count_out_of_range_This_sh[] = "Fatal: count out of range. This should never happen."; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; +static char __pyx_k_Internal_memory_layout_is_flawed[] = "Internal: memory layout is flawed: not enough nodes allocated"; +static char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; +static char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; +static char __pyx_k_count_only_and_return_distance_c[] = "count_only and return_distance cannot both be true"; +static char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; +static char __pyx_k_leaf_size_must_be_greater_than_o[] = "leaf_size must be greater than or equal to 1"; +static char __pyx_k_metric_metric_is_not_valid_for_B[] = "metric {metric} is not valid for {BinaryTree}"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_r_must_be_broadcastable_to_X_sha[] = "r must be broadcastable to X.shape"; +static char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static char __pyx_k_Internal_memory_layout_is_flawed_2[] = "Internal: memory layout is flawed: too many nodes allocated"; +static PyObject *__pyx_n_s_BinaryTree; +static PyObject *__pyx_kp_s_BinaryTree_for_fast_generalized; +static PyObject *__pyx_kp_u_BinaryTree_kernel_density_line_1; +static PyObject *__pyx_kp_u_BinaryTree_query_line_1228; +static PyObject *__pyx_kp_u_BinaryTree_query_radius_line_135; +static PyObject *__pyx_kp_u_BinaryTree_two_point_correlation; +static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; +static PyObject *__pyx_n_s_C; +static PyObject *__pyx_n_s_CLASS_DOC; +static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; +static PyObject *__pyx_kp_s_Cannot_index_with_type_s; +static PyObject *__pyx_n_s_ChebyshevDistance; +static PyObject *__pyx_kp_u_Compute_the_two_point_correlatio; +static PyObject *__pyx_n_s_DOC_DICT; +static PyObject *__pyx_n_s_DTYPE; +static PyObject *__pyx_n_s_Ellipsis; +static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; +static PyObject *__pyx_n_s_EuclideanDistance; +static PyObject *__pyx_kp_s_Fatal_count_out_of_range_This_sh; +static PyObject *__pyx_kp_s_Fatal_count_too_big_this_should; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_n_s_ITYPE; +static PyObject *__pyx_n_s_IndexError; +static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; +static PyObject *__pyx_kp_s_Internal_memory_layout_is_flawed; +static PyObject *__pyx_kp_s_Internal_memory_layout_is_flawed_2; +static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; +static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; +static PyObject *__pyx_n_s_KDTree; +static PyObject *__pyx_kp_s_Kernel_code_not_recognized; +static PyObject *__pyx_n_s_ManhattanDistance; +static PyObject *__pyx_n_s_MemoryError; +static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; +static PyObject *__pyx_kp_s_MemoryView_of_r_object; +static PyObject *__pyx_n_s_MinkowskiDistance; +static PyObject *__pyx_n_s_NodeData; +static PyObject *__pyx_n_s_NodeHeapData; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_b_O; +static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_kp_b_T; +static PyObject *__pyx_n_s_TypeError; +static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; +static PyObject *__pyx_n_s_VALID_METRICS; +static PyObject *__pyx_n_s_VALID_METRIC_IDS; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_kp_s_X_is_an_empty_array; +static PyObject *__pyx_kp_b__50; +static PyObject *__pyx_kp_b__51; +static PyObject *__pyx_kp_b__52; +static PyObject *__pyx_kp_b__53; +static PyObject *__pyx_kp_u__54; +static PyObject *__pyx_n_s_all; +static PyObject *__pyx_n_s_allocate_buffer; +static PyObject *__pyx_n_s_arange; +static PyObject *__pyx_n_s_argsort; +static PyObject *__pyx_n_s_asarray; +static PyObject *__pyx_n_s_atleast_1d; +static PyObject *__pyx_n_s_atol; +static PyObject *__pyx_n_s_base; +static PyObject *__pyx_n_s_binary_tree; +static PyObject *__pyx_n_s_breadth_first; +static PyObject *__pyx_n_s_c; +static PyObject *__pyx_n_u_c; +static PyObject *__pyx_kp_s_cannot_pop_on_empty_heap; +static PyObject *__pyx_n_s_check_array; +static PyObject *__pyx_n_s_class; +static PyObject *__pyx_kp_s_contiguous_and_direct; +static PyObject *__pyx_kp_s_contiguous_and_indirect; +static PyObject *__pyx_n_s_copy; +static PyObject *__pyx_n_s_cosine; +static PyObject *__pyx_n_s_count_only; +static PyObject *__pyx_kp_s_count_only_and_return_distance_c; +static PyObject *__pyx_n_s_d; +static PyObject *__pyx_n_s_data; +static PyObject *__pyx_n_s_dist_metrics; +static PyObject *__pyx_n_s_distances; +static PyObject *__pyx_n_s_doc; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_dtype_is_object; +static PyObject *__pyx_n_s_dualtree; +static PyObject *__pyx_n_s_empty; +static PyObject *__pyx_n_s_enumerate; +static PyObject *__pyx_n_s_epanechnikov; +static PyObject *__pyx_n_s_error; +static PyObject *__pyx_n_s_exp; +static PyObject *__pyx_n_s_exponential; +static PyObject *__pyx_n_s_flags; +static PyObject *__pyx_n_s_format; +static PyObject *__pyx_n_s_formats; +static PyObject *__pyx_n_s_fortran; +static PyObject *__pyx_n_u_fortran; +static PyObject *__pyx_n_s_gaussian; +static PyObject *__pyx_n_s_get_arrays; +static PyObject *__pyx_n_s_get_metric; +static PyObject *__pyx_n_s_get_valid_metric_ids; +static PyObject *__pyx_n_s_getstate; +static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; +static PyObject *__pyx_n_s_h; +static PyObject *__pyx_n_s_heap; +static PyObject *__pyx_kp_s_home_manoj_scikit_learn_sklearn; +static PyObject *__pyx_n_s_i; +static PyObject *__pyx_n_s_i1; +static PyObject *__pyx_n_s_i2; +static PyObject *__pyx_n_s_i_val; +static PyObject *__pyx_n_s_id; +static PyObject *__pyx_n_s_idx_end; +static PyObject *__pyx_n_s_idx_start; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_indices; +static PyObject *__pyx_n_s_inf; +static PyObject *__pyx_n_s_is_leaf; +static PyObject *__pyx_n_s_itemsize; +static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; +static PyObject *__pyx_n_s_j; +static PyObject *__pyx_n_s_join; +static PyObject *__pyx_n_s_k; +static PyObject *__pyx_kp_s_k_must_be_less_than_or_equal_to; +static PyObject *__pyx_n_s_kd_tree; +static PyObject *__pyx_n_s_kernel; +static PyObject *__pyx_kp_u_kernel_density_self_X_h_kernel; +static PyObject *__pyx_n_s_kernel_norm; +static PyObject *__pyx_kp_s_kernel_not_recognized; +static PyObject *__pyx_kp_s_kernel_s_not_recognized; +static PyObject *__pyx_n_s_leaf_size; +static PyObject *__pyx_kp_s_leaf_size_must_be_greater_than_o; +static PyObject *__pyx_n_s_linear; +static PyObject *__pyx_n_s_load_heap; +static PyObject *__pyx_n_s_log2; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_memview; +static PyObject *__pyx_n_s_metric; +static PyObject *__pyx_kp_s_metric_metric_is_not_valid_for_B; +static PyObject *__pyx_n_s_minkowski; +static PyObject *__pyx_n_s_mode; +static PyObject *__pyx_n_s_n_nbrs; +static PyObject *__pyx_n_s_n_pts; +static PyObject *__pyx_n_s_name; +static PyObject *__pyx_n_s_name_2; +static PyObject *__pyx_n_s_names; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_ndim; +static PyObject *__pyx_n_s_new; +static PyObject *__pyx_n_s_newObj; +static PyObject *__pyx_n_s_node_data; +static PyObject *__pyx_n_s_nodeheap_sort; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_obj; +static PyObject *__pyx_n_s_object; +static PyObject *__pyx_n_s_offsets; +static PyObject *__pyx_n_s_order; +static PyObject *__pyx_n_s_pack; +static PyObject *__pyx_n_s_pi; +static PyObject *__pyx_n_s_push; +static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_releasebuffer; +static PyObject *__pyx_n_s_pyx_vtable; +static PyObject *__pyx_kp_u_query_X_k_1_return_distance_Tru; +static PyObject *__pyx_kp_s_query_data_dimension_must_match; +static PyObject *__pyx_kp_u_query_radius_self_X_r_count_onl; +static PyObject *__pyx_n_s_r; +static PyObject *__pyx_kp_s_r_must_be_a_1_dimensional_array; +static PyObject *__pyx_kp_s_r_must_be_broadcastable_to_X_sha; +static PyObject *__pyx_n_s_radius; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_rdist_to_dist; +static PyObject *__pyx_n_s_reshape; +static PyObject *__pyx_n_s_result; +static PyObject *__pyx_n_s_return_distance; +static PyObject *__pyx_kp_s_return_distance_must_be_True_if; +static PyObject *__pyx_n_s_return_log; +static PyObject *__pyx_n_s_row; +static PyObject *__pyx_n_s_rtol; +static PyObject *__pyx_kp_u_s; +static PyObject *__pyx_n_s_shape; +static PyObject *__pyx_n_s_simultaneous_sort; +static PyObject *__pyx_n_s_size; +static PyObject *__pyx_n_s_size_guess; +static PyObject *__pyx_n_s_sklearn_neighbors_kd_tree; +static PyObject *__pyx_n_s_sort; +static PyObject *__pyx_n_s_sort_results; +static PyObject *__pyx_n_s_start; +static PyObject *__pyx_n_s_step; +static PyObject *__pyx_n_s_stop; +static PyObject *__pyx_kp_s_strided_and_direct; +static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; +static PyObject *__pyx_kp_s_strided_and_indirect; +static PyObject *__pyx_n_s_struct; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_n_s_tophat; +static PyObject *__pyx_n_s_typedefs; +static PyObject *__pyx_kp_s_unable_to_allocate_array_data; +static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_unpack; +static PyObject *__pyx_n_s_utils; +static PyObject *__pyx_n_s_val; +static PyObject *__pyx_n_s_valid_metrics; +static PyObject *__pyx_n_s_vals; +static PyObject *__pyx_n_s_vals_sorted; +static PyObject *__pyx_n_s_warn; +static PyObject *__pyx_n_s_warnings; +static PyObject *__pyx_n_s_xrange; +static PyObject *__pyx_n_s_zeros; +static PyObject *__pyx_n_s_zeros_like; +static PyObject *__pyx_float_1Eneg_8; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_1; +static PyObject *__pyx_int_2; +static PyObject *__pyx_int_40; +static PyObject *__pyx_int_100; +static PyObject *__pyx_int_neg_1; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__8; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_tuple__10; +static PyObject *__pyx_tuple__11; +static PyObject *__pyx_tuple__12; +static PyObject *__pyx_tuple__13; +static PyObject *__pyx_tuple__14; +static PyObject *__pyx_tuple__15; +static PyObject *__pyx_tuple__16; +static PyObject *__pyx_tuple__17; +static PyObject *__pyx_tuple__18; +static PyObject *__pyx_tuple__19; +static PyObject *__pyx_tuple__20; +static PyObject *__pyx_tuple__21; +static PyObject *__pyx_tuple__22; +static PyObject *__pyx_tuple__23; +static PyObject *__pyx_tuple__24; +static PyObject *__pyx_tuple__25; +static PyObject *__pyx_tuple__26; +static PyObject *__pyx_tuple__27; +static PyObject *__pyx_tuple__28; +static PyObject *__pyx_tuple__29; +static PyObject *__pyx_tuple__30; +static PyObject *__pyx_tuple__31; +static PyObject *__pyx_tuple__32; +static PyObject *__pyx_tuple__33; +static PyObject *__pyx_tuple__34; +static PyObject *__pyx_tuple__35; +static PyObject *__pyx_tuple__36; +static PyObject *__pyx_tuple__37; +static PyObject *__pyx_tuple__38; +static PyObject *__pyx_tuple__39; +static PyObject *__pyx_tuple__40; +static PyObject *__pyx_tuple__41; +static PyObject *__pyx_tuple__42; +static PyObject *__pyx_tuple__43; +static PyObject *__pyx_tuple__44; +static PyObject *__pyx_tuple__45; +static PyObject *__pyx_tuple__46; +static PyObject *__pyx_tuple__47; +static PyObject *__pyx_tuple__48; +static PyObject *__pyx_tuple__49; +static PyObject *__pyx_tuple__55; +static PyObject *__pyx_tuple__57; +static PyObject *__pyx_tuple__59; +static PyObject *__pyx_tuple__61; +static PyObject *__pyx_tuple__63; +static PyObject *__pyx_tuple__65; +static PyObject *__pyx_tuple__66; +static PyObject *__pyx_tuple__67; +static PyObject *__pyx_tuple__68; +static PyObject *__pyx_tuple__69; +static PyObject *__pyx_codeobj__56; +static PyObject *__pyx_codeobj__58; +static PyObject *__pyx_codeobj__60; +static PyObject *__pyx_codeobj__62; +static PyObject *__pyx_codeobj__64; + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":212 + * ###################################################################### + * # Numpy 1.3-1.4 compatibility utilities + * cdef DTYPE_t[::1] get_memview_DTYPE_1D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=1, mode='c'] X): + * return ( X.data) + */ + +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_1D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_DTYPE_1D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":214 + * cdef DTYPE_t[::1] get_memview_DTYPE_1D( + * np.ndarray[DTYPE_t, ndim=1, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = ((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "fortran", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":212 + * ###################################################################### + * # Numpy 1.3-1.4 compatibility utilities + * cdef DTYPE_t[::1] get_memview_DTYPE_1D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=1, mode='c'] X): + * return ( X.data) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.get_memview_DTYPE_1D", __pyx_clineno, __pyx_lineno, __pyx_filename); + + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":217 + * + * + * cdef DTYPE_t[:, ::1] get_memview_DTYPE_2D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X): + * return ( X.data) + */ + +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_2D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_DTYPE_2D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":219 + * cdef DTYPE_t[:, ::1] get_memview_DTYPE_2D( + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = ((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0])), ((Py_ssize_t)(__pyx_v_X->dimensions[1]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "c", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":217 + * + * + * cdef DTYPE_t[:, ::1] get_memview_DTYPE_2D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2, mode='c'] X): + * return ( X.data) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.get_memview_DTYPE_2D", __pyx_clineno, __pyx_lineno, __pyx_filename); + + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":222 + * + * + * cdef DTYPE_t[:, :, ::1] get_memview_DTYPE_3D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=3, mode='c'] X): + * return \ + */ + +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_3D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_DTYPE_3D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 3, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_X.diminfo[2].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_X.diminfo[2].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[2]; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":225 + * np.ndarray[DTYPE_t, ndim=3, mode='c'] X): + * return \ + * ( X.data) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = ((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *)__pyx_v_X->data); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":224 + * cdef DTYPE_t[:, :, ::1] get_memview_DTYPE_3D( + * np.ndarray[DTYPE_t, ndim=3, mode='c'] X): + * return \ # <<<<<<<<<<<<<< + * ( X.data) + * + */ + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T __PYX_BUILD_PY_SSIZE_T __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0])), ((Py_ssize_t)(__pyx_v_X->dimensions[1])), ((Py_ssize_t)(__pyx_v_X->dimensions[2]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "c", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":222 + * + * + * cdef DTYPE_t[:, :, ::1] get_memview_DTYPE_3D( # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=3, mode='c'] X): + * return \ + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.get_memview_DTYPE_3D", __pyx_clineno, __pyx_lineno, __pyx_filename); + + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":228 + * + * + * cdef ITYPE_t[::1] get_memview_ITYPE_1D( # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1, mode='c'] X): + * return ( X.data) + */ + +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_1D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_ITYPE_1D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":230 + * cdef ITYPE_t[::1] get_memview_ITYPE_1D( + * np.ndarray[ITYPE_t, ndim=1, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = ((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "fortran", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":228 + * + * + * cdef ITYPE_t[::1] get_memview_ITYPE_1D( # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1, mode='c'] X): + * return ( X.data) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.get_memview_ITYPE_1D", __pyx_clineno, __pyx_lineno, __pyx_filename); + + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":233 + * + * + * cdef ITYPE_t[:, ::1] get_memview_ITYPE_2D( # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=2, mode='c'] X): + * return ( X.data) + */ + +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_2D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_ITYPE_2D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":235 + * cdef ITYPE_t[:, ::1] get_memview_ITYPE_2D( + * np.ndarray[ITYPE_t, ndim=2, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = ((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0])), ((Py_ssize_t)(__pyx_v_X->dimensions[1]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "c", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":233 + * + * + * cdef ITYPE_t[:, ::1] get_memview_ITYPE_2D( # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=2, mode='c'] X): + * return ( X.data) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.get_memview_ITYPE_2D", __pyx_clineno, __pyx_lineno, __pyx_filename); + + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":238 + * + * + * cdef NodeHeapData_t[::1] get_memview_NodeHeapData_1D( # <<<<<<<<<<<<<< + * np.ndarray[NodeHeapData_t, ndim=1, mode='c'] X): + * return ( X.data) + */ + +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_NodeHeapData_1D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_RefNannyDeclarations + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_NodeHeapData_1D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[2]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":240 + * cdef NodeHeapData_t[::1] get_memview_NodeHeapData_1D( + * np.ndarray[NodeHeapData_t, ndim=1, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = ((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "fortran", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":238 + * + * + * cdef NodeHeapData_t[::1] get_memview_NodeHeapData_1D( # <<<<<<<<<<<<<< + * np.ndarray[NodeHeapData_t, ndim=1, mode='c'] X): + * return ( X.data) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.get_memview_NodeHeapData_1D", __pyx_clineno, __pyx_lineno, __pyx_filename); + + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":243 + * + * + * cdef NodeData_t[::1] get_memview_NodeData_1D( # <<<<<<<<<<<<<< + * np.ndarray[NodeData_t, ndim=1, mode='c'] X): + * return ( X.data) + */ + +static __Pyx_memviewslice __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_NodeData_1D(PyArrayObject *__pyx_v_X) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_memviewslice __pyx_r = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_RefNannyDeclarations + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *__pyx_t_1; + struct __pyx_array_obj *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview_NodeData_1D", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + { + __Pyx_BufFmt_StackElem __pyx_stack[2]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":245 + * cdef NodeData_t[::1] get_memview_NodeData_1D( + * np.ndarray[NodeData_t, ndim=1, mode='c'] X): + * return ( X.data) # <<<<<<<<<<<<<< + * + * ###################################################################### + */ + __pyx_t_1 = ((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *)__pyx_v_X->data); + if (!__pyx_t_1) { + PyErr_SetString(PyExc_ValueError,"Cannot create cython.array from NULL pointer"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_4 = __pyx_format_from_typeinfo(&__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t); + __pyx_t_3 = Py_BuildValue((char*) "(" __PYX_BUILD_PY_SSIZE_T ")", ((Py_ssize_t)(__pyx_v_X->dimensions[0]))); + if (unlikely(!__pyx_t_4 || !__pyx_t_3 || !PyBytes_AsString(__pyx_t_4))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_array_new(__pyx_t_3, sizeof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t), PyBytes_AS_STRING(__pyx_t_4), (char *) "fortran", (char *) __pyx_t_1); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(((PyObject *)__pyx_t_2)); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":243 + * + * + * cdef NodeData_t[::1] get_memview_NodeData_1D( # <<<<<<<<<<<<<< + * np.ndarray[NodeData_t, ndim=1, mode='c'] X): + * return ( X.data) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(((PyObject *)__pyx_t_2)); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __pyx_r.data = NULL; + __pyx_r.memview = NULL; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.get_memview_NodeData_1D", __pyx_clineno, __pyx_lineno, __pyx_filename); + + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + if (unlikely(!__pyx_r.memview)) { + PyErr_SetString(PyExc_TypeError,"Memoryview return value is not initialized"); + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":359 + * ###################################################################### + * # Utility functions + * cdef DTYPE_t logaddexp(DTYPE_t x1, DTYPE_t x2): # <<<<<<<<<<<<<< + * """logaddexp(x1, x2) -> log(exp(x1) + exp(x2))""" + * cdef DTYPE_t a = fmax(x1, x2) + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_x2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_a; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("logaddexp", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":361 + * cdef DTYPE_t logaddexp(DTYPE_t x1, DTYPE_t x2): + * """logaddexp(x1, x2) -> log(exp(x1) + exp(x2))""" + * cdef DTYPE_t a = fmax(x1, x2) # <<<<<<<<<<<<<< + * if a == NEG_INF: + * return NEG_INF + */ + __pyx_v_a = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax(__pyx_v_x1, __pyx_v_x2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":362 + * """logaddexp(x1, x2) -> log(exp(x1) + exp(x2))""" + * cdef DTYPE_t a = fmax(x1, x2) + * if a == NEG_INF: # <<<<<<<<<<<<<< + * return NEG_INF + * else: + */ + __pyx_t_1 = ((__pyx_v_a == __pyx_v_7sklearn_9neighbors_7kd_tree_NEG_INF) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":363 + * cdef DTYPE_t a = fmax(x1, x2) + * if a == NEG_INF: + * return NEG_INF # <<<<<<<<<<<<<< + * else: + * return a + log(exp(x1 - a) + exp(x2 - a)) + */ + __pyx_r = __pyx_v_7sklearn_9neighbors_7kd_tree_NEG_INF; + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":365 + * return NEG_INF + * else: + * return a + log(exp(x1 - a) + exp(x2 - a)) # <<<<<<<<<<<<<< + * + * cdef DTYPE_t logsubexp(DTYPE_t x1, DTYPE_t x2): + */ + __pyx_r = (__pyx_v_a + log((exp((__pyx_v_x1 - __pyx_v_a)) + exp((__pyx_v_x2 - __pyx_v_a))))); + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":359 + * ###################################################################### + * # Utility functions + * cdef DTYPE_t logaddexp(DTYPE_t x1, DTYPE_t x2): # <<<<<<<<<<<<<< + * """logaddexp(x1, x2) -> log(exp(x1) + exp(x2))""" + * cdef DTYPE_t a = fmax(x1, x2) + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":367 + * return a + log(exp(x1 - a) + exp(x2 - a)) + * + * cdef DTYPE_t logsubexp(DTYPE_t x1, DTYPE_t x2): # <<<<<<<<<<<<<< + * """logsubexp(x1, x2) -> log(exp(x1) - exp(x2))""" + * if x1 <= x2: + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_x2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("logsubexp", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":369 + * cdef DTYPE_t logsubexp(DTYPE_t x1, DTYPE_t x2): + * """logsubexp(x1, x2) -> log(exp(x1) - exp(x2))""" + * if x1 <= x2: # <<<<<<<<<<<<<< + * return NEG_INF + * else: + */ + __pyx_t_1 = ((__pyx_v_x1 <= __pyx_v_x2) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":370 + * """logsubexp(x1, x2) -> log(exp(x1) - exp(x2))""" + * if x1 <= x2: + * return NEG_INF # <<<<<<<<<<<<<< + * else: + * return x1 + log(1 - exp(x2 - x1)) + */ + __pyx_r = __pyx_v_7sklearn_9neighbors_7kd_tree_NEG_INF; + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":372 + * return NEG_INF + * else: + * return x1 + log(1 - exp(x2 - x1)) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (__pyx_v_x1 + log((1.0 - exp((__pyx_v_x2 - __pyx_v_x1))))); + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":367 + * return a + log(exp(x1 - a) + exp(x2 - a)) + * + * cdef DTYPE_t logsubexp(DTYPE_t x1, DTYPE_t x2): # <<<<<<<<<<<<<< + * """logsubexp(x1, x2) -> log(exp(x1) - exp(x2))""" + * if x1 <= x2: + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":394 + * + * + * cdef inline DTYPE_t log_gaussian_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the gaussian kernel for bandwidth h (unnormalized)""" + * return -0.5 * (dist * dist) / (h * h) + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_gaussian_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("log_gaussian_kernel", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":396 + * cdef inline DTYPE_t log_gaussian_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the gaussian kernel for bandwidth h (unnormalized)""" + * return -0.5 * (dist * dist) / (h * h) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((-0.5 * (__pyx_v_dist * __pyx_v_dist)) / (__pyx_v_h * __pyx_v_h)); + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":394 + * + * + * cdef inline DTYPE_t log_gaussian_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the gaussian kernel for bandwidth h (unnormalized)""" + * return -0.5 * (dist * dist) / (h * h) + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":399 + * + * + * cdef inline DTYPE_t log_tophat_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the tophat kernel for bandwidth h (unnormalized)""" + * if dist < h: + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_tophat_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("log_tophat_kernel", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":401 + * cdef inline DTYPE_t log_tophat_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the tophat kernel for bandwidth h (unnormalized)""" + * if dist < h: # <<<<<<<<<<<<<< + * return 0.0 + * else: + */ + __pyx_t_1 = ((__pyx_v_dist < __pyx_v_h) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":402 + * """log of the tophat kernel for bandwidth h (unnormalized)""" + * if dist < h: + * return 0.0 # <<<<<<<<<<<<<< + * else: + * return NEG_INF + */ + __pyx_r = 0.0; + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":404 + * return 0.0 + * else: + * return NEG_INF # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_7sklearn_9neighbors_7kd_tree_NEG_INF; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":399 + * + * + * cdef inline DTYPE_t log_tophat_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the tophat kernel for bandwidth h (unnormalized)""" + * if dist < h: + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":407 + * + * + * cdef inline DTYPE_t log_epanechnikov_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the epanechnikov kernel for bandwidth h (unnormalized)""" + * if dist < h: + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_epanechnikov_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("log_epanechnikov_kernel", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":409 + * cdef inline DTYPE_t log_epanechnikov_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the epanechnikov kernel for bandwidth h (unnormalized)""" + * if dist < h: # <<<<<<<<<<<<<< + * return log(1.0 - (dist * dist) / (h * h)) + * else: + */ + __pyx_t_1 = ((__pyx_v_dist < __pyx_v_h) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":410 + * """log of the epanechnikov kernel for bandwidth h (unnormalized)""" + * if dist < h: + * return log(1.0 - (dist * dist) / (h * h)) # <<<<<<<<<<<<<< + * else: + * return NEG_INF + */ + __pyx_r = log((1.0 - ((__pyx_v_dist * __pyx_v_dist) / (__pyx_v_h * __pyx_v_h)))); + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":412 + * return log(1.0 - (dist * dist) / (h * h)) + * else: + * return NEG_INF # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_7sklearn_9neighbors_7kd_tree_NEG_INF; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":407 + * + * + * cdef inline DTYPE_t log_epanechnikov_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the epanechnikov kernel for bandwidth h (unnormalized)""" + * if dist < h: + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":415 + * + * + * cdef inline DTYPE_t log_exponential_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the exponential kernel for bandwidth h (unnormalized)""" + * return -dist / h + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_exponential_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("log_exponential_kernel", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":417 + * cdef inline DTYPE_t log_exponential_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the exponential kernel for bandwidth h (unnormalized)""" + * return -dist / h # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((-__pyx_v_dist) / __pyx_v_h); + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":415 + * + * + * cdef inline DTYPE_t log_exponential_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the exponential kernel for bandwidth h (unnormalized)""" + * return -dist / h + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":420 + * + * + * cdef inline DTYPE_t log_linear_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the linear kernel for bandwidth h (unnormalized)""" + * if dist < h: + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_linear_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("log_linear_kernel", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":422 + * cdef inline DTYPE_t log_linear_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the linear kernel for bandwidth h (unnormalized)""" + * if dist < h: # <<<<<<<<<<<<<< + * return log(1 - dist / h) + * else: + */ + __pyx_t_1 = ((__pyx_v_dist < __pyx_v_h) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":423 + * """log of the linear kernel for bandwidth h (unnormalized)""" + * if dist < h: + * return log(1 - dist / h) # <<<<<<<<<<<<<< + * else: + * return NEG_INF + */ + __pyx_r = log((1.0 - (__pyx_v_dist / __pyx_v_h))); + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":425 + * return log(1 - dist / h) + * else: + * return NEG_INF # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_7sklearn_9neighbors_7kd_tree_NEG_INF; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":420 + * + * + * cdef inline DTYPE_t log_linear_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the linear kernel for bandwidth h (unnormalized)""" + * if dist < h: + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":428 + * + * + * cdef inline DTYPE_t log_cosine_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the cosine kernel for bandwidth h (unnormalized)""" + * if dist < h: + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_log_cosine_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("log_cosine_kernel", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":430 + * cdef inline DTYPE_t log_cosine_kernel(DTYPE_t dist, DTYPE_t h): + * """log of the cosine kernel for bandwidth h (unnormalized)""" + * if dist < h: # <<<<<<<<<<<<<< + * return log(cos(0.5 * PI * dist / h)) + * else: + */ + __pyx_t_1 = ((__pyx_v_dist < __pyx_v_h) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":431 + * """log of the cosine kernel for bandwidth h (unnormalized)""" + * if dist < h: + * return log(cos(0.5 * PI * dist / h)) # <<<<<<<<<<<<<< + * else: + * return NEG_INF + */ + __pyx_r = log(cos((((0.5 * __pyx_v_7sklearn_9neighbors_7kd_tree_PI) * __pyx_v_dist) / __pyx_v_h))); + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":433 + * return log(cos(0.5 * PI * dist / h)) + * else: + * return NEG_INF # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_7sklearn_9neighbors_7kd_tree_NEG_INF; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":428 + * + * + * cdef inline DTYPE_t log_cosine_kernel(DTYPE_t dist, DTYPE_t h): # <<<<<<<<<<<<<< + * """log of the cosine kernel for bandwidth h (unnormalized)""" + * if dist < h: + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":436 + * + * + * cdef inline DTYPE_t compute_log_kernel(DTYPE_t dist, DTYPE_t h, # <<<<<<<<<<<<<< + * KernelType kernel): + * """Given a KernelType enumeration, compute the appropriate log-kernel""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h, enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType __pyx_v_kernel) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("compute_log_kernel", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":449 + * elif kernel == LINEAR_KERNEL: + * return log_linear_kernel(dist, h) + * elif kernel == COSINE_KERNEL: # <<<<<<<<<<<<<< + * return log_cosine_kernel(dist, h) + * + */ + switch (__pyx_v_kernel) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":439 + * KernelType kernel): + * """Given a KernelType enumeration, compute the appropriate log-kernel""" + * if kernel == GAUSSIAN_KERNEL: # <<<<<<<<<<<<<< + * return log_gaussian_kernel(dist, h) + * elif kernel == TOPHAT_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_GAUSSIAN_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":440 + * """Given a KernelType enumeration, compute the appropriate log-kernel""" + * if kernel == GAUSSIAN_KERNEL: + * return log_gaussian_kernel(dist, h) # <<<<<<<<<<<<<< + * elif kernel == TOPHAT_KERNEL: + * return log_tophat_kernel(dist, h) + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_7kd_tree_log_gaussian_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":441 + * if kernel == GAUSSIAN_KERNEL: + * return log_gaussian_kernel(dist, h) + * elif kernel == TOPHAT_KERNEL: # <<<<<<<<<<<<<< + * return log_tophat_kernel(dist, h) + * elif kernel == EPANECHNIKOV_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_TOPHAT_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":442 + * return log_gaussian_kernel(dist, h) + * elif kernel == TOPHAT_KERNEL: + * return log_tophat_kernel(dist, h) # <<<<<<<<<<<<<< + * elif kernel == EPANECHNIKOV_KERNEL: + * return log_epanechnikov_kernel(dist, h) + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_7kd_tree_log_tophat_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":443 + * elif kernel == TOPHAT_KERNEL: + * return log_tophat_kernel(dist, h) + * elif kernel == EPANECHNIKOV_KERNEL: # <<<<<<<<<<<<<< + * return log_epanechnikov_kernel(dist, h) + * elif kernel == EXPONENTIAL_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_EPANECHNIKOV_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":444 + * return log_tophat_kernel(dist, h) + * elif kernel == EPANECHNIKOV_KERNEL: + * return log_epanechnikov_kernel(dist, h) # <<<<<<<<<<<<<< + * elif kernel == EXPONENTIAL_KERNEL: + * return log_exponential_kernel(dist, h) + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_7kd_tree_log_epanechnikov_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":445 + * elif kernel == EPANECHNIKOV_KERNEL: + * return log_epanechnikov_kernel(dist, h) + * elif kernel == EXPONENTIAL_KERNEL: # <<<<<<<<<<<<<< + * return log_exponential_kernel(dist, h) + * elif kernel == LINEAR_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_EXPONENTIAL_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":446 + * return log_epanechnikov_kernel(dist, h) + * elif kernel == EXPONENTIAL_KERNEL: + * return log_exponential_kernel(dist, h) # <<<<<<<<<<<<<< + * elif kernel == LINEAR_KERNEL: + * return log_linear_kernel(dist, h) + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_7kd_tree_log_exponential_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":447 + * elif kernel == EXPONENTIAL_KERNEL: + * return log_exponential_kernel(dist, h) + * elif kernel == LINEAR_KERNEL: # <<<<<<<<<<<<<< + * return log_linear_kernel(dist, h) + * elif kernel == COSINE_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_LINEAR_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":448 + * return log_exponential_kernel(dist, h) + * elif kernel == LINEAR_KERNEL: + * return log_linear_kernel(dist, h) # <<<<<<<<<<<<<< + * elif kernel == COSINE_KERNEL: + * return log_cosine_kernel(dist, h) + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_7kd_tree_log_linear_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":449 + * elif kernel == LINEAR_KERNEL: + * return log_linear_kernel(dist, h) + * elif kernel == COSINE_KERNEL: # <<<<<<<<<<<<<< + * return log_cosine_kernel(dist, h) + * + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_COSINE_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":450 + * return log_linear_kernel(dist, h) + * elif kernel == COSINE_KERNEL: + * return log_cosine_kernel(dist, h) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_7kd_tree_log_cosine_kernel(__pyx_v_dist, __pyx_v_h); + goto __pyx_L0; + break; + default: break; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":436 + * + * + * cdef inline DTYPE_t compute_log_kernel(DTYPE_t dist, DTYPE_t h, # <<<<<<<<<<<<<< + * KernelType kernel): + * """Given a KernelType enumeration, compute the appropriate log-kernel""" + */ + + /* function exit code */ + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":456 + * # Kernel norms are defined via the volume element V_n + * # and surface element S_(n-1) of an n-sphere. + * cdef DTYPE_t logVn(ITYPE_t n): # <<<<<<<<<<<<<< + * """V_n = pi^(n/2) / gamma(n/2 - 1)""" + * return 0.5 * n * LOG_PI - lgamma(0.5 * n + 1) + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_logVn(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("logVn", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":458 + * cdef DTYPE_t logVn(ITYPE_t n): + * """V_n = pi^(n/2) / gamma(n/2 - 1)""" + * return 0.5 * n * LOG_PI - lgamma(0.5 * n + 1) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (((0.5 * __pyx_v_n) * __pyx_v_7sklearn_9neighbors_7kd_tree_LOG_PI) - __pyx_f_7sklearn_5utils_6lgamma_lgamma(((0.5 * __pyx_v_n) + 1.0))); + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":456 + * # Kernel norms are defined via the volume element V_n + * # and surface element S_(n-1) of an n-sphere. + * cdef DTYPE_t logVn(ITYPE_t n): # <<<<<<<<<<<<<< + * """V_n = pi^(n/2) / gamma(n/2 - 1)""" + * return 0.5 * n * LOG_PI - lgamma(0.5 * n + 1) + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":461 + * + * + * cdef DTYPE_t logSn(ITYPE_t n): # <<<<<<<<<<<<<< + * """V_(n+1) = int_0^1 S_n r^n dr""" + * return LOG_2PI + logVn(n - 1) + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_logSn(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("logSn", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":463 + * cdef DTYPE_t logSn(ITYPE_t n): + * """V_(n+1) = int_0^1 S_n r^n dr""" + * return LOG_2PI + logVn(n - 1) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (__pyx_v_7sklearn_9neighbors_7kd_tree_LOG_2PI + __pyx_f_7sklearn_9neighbors_7kd_tree_logVn((__pyx_v_n - 1))); + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":461 + * + * + * cdef DTYPE_t logSn(ITYPE_t n): # <<<<<<<<<<<<<< + * """V_(n+1) = int_0^1 S_n r^n dr""" + * return LOG_2PI + logVn(n - 1) + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":466 + * + * + * cdef DTYPE_t _log_kernel_norm(DTYPE_t h, ITYPE_t d, # <<<<<<<<<<<<<< + * KernelType kernel) except -1: + * """Given a KernelType enumeration, compute the kernel normalization. + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree__log_kernel_norm(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_d, enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType __pyx_v_kernel) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_tmp; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_factor; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_k; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + long __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_log_kernel_norm", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":472 + * h is the bandwidth, d is the dimension. + * """ + * cdef DTYPE_t tmp, factor = 0 # <<<<<<<<<<<<<< + * cdef ITYPE_t k + * if kernel == GAUSSIAN_KERNEL: + */ + __pyx_v_factor = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":484 + * elif kernel == LINEAR_KERNEL: + * factor = logVn(d) - log(d + 1.) + * elif kernel == COSINE_KERNEL: # <<<<<<<<<<<<<< + * # this is derived from a chain rule integration + * factor = 0 + */ + switch (__pyx_v_kernel) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":474 + * cdef DTYPE_t tmp, factor = 0 + * cdef ITYPE_t k + * if kernel == GAUSSIAN_KERNEL: # <<<<<<<<<<<<<< + * factor = 0.5 * d * LOG_2PI + * elif kernel == TOPHAT_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_GAUSSIAN_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":475 + * cdef ITYPE_t k + * if kernel == GAUSSIAN_KERNEL: + * factor = 0.5 * d * LOG_2PI # <<<<<<<<<<<<<< + * elif kernel == TOPHAT_KERNEL: + * factor = logVn(d) + */ + __pyx_v_factor = ((0.5 * __pyx_v_d) * __pyx_v_7sklearn_9neighbors_7kd_tree_LOG_2PI); + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":476 + * if kernel == GAUSSIAN_KERNEL: + * factor = 0.5 * d * LOG_2PI + * elif kernel == TOPHAT_KERNEL: # <<<<<<<<<<<<<< + * factor = logVn(d) + * elif kernel == EPANECHNIKOV_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_TOPHAT_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":477 + * factor = 0.5 * d * LOG_2PI + * elif kernel == TOPHAT_KERNEL: + * factor = logVn(d) # <<<<<<<<<<<<<< + * elif kernel == EPANECHNIKOV_KERNEL: + * factor = logVn(d) + log(2. / (d + 2.)) + */ + __pyx_v_factor = __pyx_f_7sklearn_9neighbors_7kd_tree_logVn(__pyx_v_d); + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":478 + * elif kernel == TOPHAT_KERNEL: + * factor = logVn(d) + * elif kernel == EPANECHNIKOV_KERNEL: # <<<<<<<<<<<<<< + * factor = logVn(d) + log(2. / (d + 2.)) + * elif kernel == EXPONENTIAL_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_EPANECHNIKOV_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":479 + * factor = logVn(d) + * elif kernel == EPANECHNIKOV_KERNEL: + * factor = logVn(d) + log(2. / (d + 2.)) # <<<<<<<<<<<<<< + * elif kernel == EXPONENTIAL_KERNEL: + * factor = logSn(d - 1) + lgamma(d) + */ + __pyx_v_factor = (__pyx_f_7sklearn_9neighbors_7kd_tree_logVn(__pyx_v_d) + log((2. / (__pyx_v_d + 2.)))); + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":480 + * elif kernel == EPANECHNIKOV_KERNEL: + * factor = logVn(d) + log(2. / (d + 2.)) + * elif kernel == EXPONENTIAL_KERNEL: # <<<<<<<<<<<<<< + * factor = logSn(d - 1) + lgamma(d) + * elif kernel == LINEAR_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_EXPONENTIAL_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":481 + * factor = logVn(d) + log(2. / (d + 2.)) + * elif kernel == EXPONENTIAL_KERNEL: + * factor = logSn(d - 1) + lgamma(d) # <<<<<<<<<<<<<< + * elif kernel == LINEAR_KERNEL: + * factor = logVn(d) - log(d + 1.) + */ + __pyx_v_factor = (__pyx_f_7sklearn_9neighbors_7kd_tree_logSn((__pyx_v_d - 1)) + __pyx_f_7sklearn_5utils_6lgamma_lgamma(__pyx_v_d)); + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":482 + * elif kernel == EXPONENTIAL_KERNEL: + * factor = logSn(d - 1) + lgamma(d) + * elif kernel == LINEAR_KERNEL: # <<<<<<<<<<<<<< + * factor = logVn(d) - log(d + 1.) + * elif kernel == COSINE_KERNEL: + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_LINEAR_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":483 + * factor = logSn(d - 1) + lgamma(d) + * elif kernel == LINEAR_KERNEL: + * factor = logVn(d) - log(d + 1.) # <<<<<<<<<<<<<< + * elif kernel == COSINE_KERNEL: + * # this is derived from a chain rule integration + */ + __pyx_v_factor = (__pyx_f_7sklearn_9neighbors_7kd_tree_logVn(__pyx_v_d) - log((__pyx_v_d + 1.))); + break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":484 + * elif kernel == LINEAR_KERNEL: + * factor = logVn(d) - log(d + 1.) + * elif kernel == COSINE_KERNEL: # <<<<<<<<<<<<<< + * # this is derived from a chain rule integration + * factor = 0 + */ + case __pyx_e_7sklearn_9neighbors_7kd_tree_COSINE_KERNEL: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":486 + * elif kernel == COSINE_KERNEL: + * # this is derived from a chain rule integration + * factor = 0 # <<<<<<<<<<<<<< + * tmp = 2. / PI + * for k in range(1, d + 1, 2): + */ + __pyx_v_factor = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":487 + * # this is derived from a chain rule integration + * factor = 0 + * tmp = 2. / PI # <<<<<<<<<<<<<< + * for k in range(1, d + 1, 2): + * factor += tmp + */ + __pyx_v_tmp = (2. / __pyx_v_7sklearn_9neighbors_7kd_tree_PI); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":488 + * factor = 0 + * tmp = 2. / PI + * for k in range(1, d + 1, 2): # <<<<<<<<<<<<<< + * factor += tmp + * tmp *= -(d - k) * (d - k - 1) * (2. / PI) ** 2 + */ + __pyx_t_1 = (__pyx_v_d + 1); + for (__pyx_t_2 = 1; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=2) { + __pyx_v_k = __pyx_t_2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":489 + * tmp = 2. / PI + * for k in range(1, d + 1, 2): + * factor += tmp # <<<<<<<<<<<<<< + * tmp *= -(d - k) * (d - k - 1) * (2. / PI) ** 2 + * factor = log(factor) + logSn(d - 1) + */ + __pyx_v_factor = (__pyx_v_factor + __pyx_v_tmp); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":490 + * for k in range(1, d + 1, 2): + * factor += tmp + * tmp *= -(d - k) * (d - k - 1) * (2. / PI) ** 2 # <<<<<<<<<<<<<< + * factor = log(factor) + logSn(d - 1) + * else: + */ + __pyx_v_tmp = (__pyx_v_tmp * (((-(__pyx_v_d - __pyx_v_k)) * ((__pyx_v_d - __pyx_v_k) - 1)) * pow((2. / __pyx_v_7sklearn_9neighbors_7kd_tree_PI), 2.0))); + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":491 + * factor += tmp + * tmp *= -(d - k) * (d - k - 1) * (2. / PI) ** 2 + * factor = log(factor) + logSn(d - 1) # <<<<<<<<<<<<<< + * else: + * raise ValueError("Kernel code not recognized") + */ + __pyx_v_factor = (log(__pyx_v_factor) + __pyx_f_7sklearn_9neighbors_7kd_tree_logSn((__pyx_v_d - 1))); + break; + default: + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":493 + * factor = log(factor) + logSn(d - 1) + * else: + * raise ValueError("Kernel code not recognized") # <<<<<<<<<<<<<< + * return -factor - d * log(h) + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":494 + * else: + * raise ValueError("Kernel code not recognized") + * return -factor - d * log(h) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((-__pyx_v_factor) - (__pyx_v_d * log(__pyx_v_h))); + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":466 + * + * + * cdef DTYPE_t _log_kernel_norm(DTYPE_t h, ITYPE_t d, # <<<<<<<<<<<<<< + * KernelType kernel) except -1: + * """Given a KernelType enumeration, compute the kernel normalization. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree._log_kernel_norm", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":497 + * + * + * def kernel_norm(h, d, kernel, return_log=False): # <<<<<<<<<<<<<< + * """Given a string specification of a kernel, compute the normalization. + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_1kernel_norm(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_kernel_norm[] = "Given a string specification of a kernel, compute the normalization.\n\n Parameters\n ----------\n h : float\n the bandwidth of the kernel\n d : int\n the dimension of the space in which the kernel norm is computed\n kernel : string\n The kernel identifier. Must be one of\n ['gaussian'|'tophat'|'epanechnikov'|\n 'exponential'|'linear'|'cosine']\n return_log : boolean\n if True, return the log of the kernel norm. Otherwise, return the\n kernel norm.\n Returns\n -------\n knorm or log_knorm : float\n the kernel norm or logarithm of the kernel norm.\n "; +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_7kd_tree_1kernel_norm = {__Pyx_NAMESTR("kernel_norm"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_1kernel_norm, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_kernel_norm)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_1kernel_norm(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_h = 0; + PyObject *__pyx_v_d = 0; + PyObject *__pyx_v_kernel = 0; + PyObject *__pyx_v_return_log = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("kernel_norm (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_h,&__pyx_n_s_d,&__pyx_n_s_kernel,&__pyx_n_s_return_log,0}; + PyObject* values[4] = {0,0,0,0}; + values[3] = ((PyObject *)Py_False); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_h)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_d)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("kernel_norm", 0, 3, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kernel)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("kernel_norm", 0, 3, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_return_log); + if (value) { values[3] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "kernel_norm") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_h = values[0]; + __pyx_v_d = values[1]; + __pyx_v_kernel = values[2]; + __pyx_v_return_log = values[3]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("kernel_norm", 0, 3, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.kernel_norm", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_kernel_norm(__pyx_self, __pyx_v_h, __pyx_v_d, __pyx_v_kernel, __pyx_v_return_log); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_kernel_norm(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_h, PyObject *__pyx_v_d, PyObject *__pyx_v_kernel, PyObject *__pyx_v_return_log) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("kernel_norm", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":518 + * the kernel norm or logarithm of the kernel norm. + * """ + * if kernel == 'gaussian': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, GAUSSIAN_KERNEL) + * elif kernel == 'tophat': + */ + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_gaussian, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 518; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":519 + * """ + * if kernel == 'gaussian': + * result = _log_kernel_norm(h, d, GAUSSIAN_KERNEL) # <<<<<<<<<<<<<< + * elif kernel == 'tophat': + * result = _log_kernel_norm(h, d, TOPHAT_KERNEL) + */ + __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_2 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree__log_kernel_norm(__pyx_t_2, __pyx_t_3, __pyx_e_7sklearn_9neighbors_7kd_tree_GAUSSIAN_KERNEL); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":520 + * if kernel == 'gaussian': + * result = _log_kernel_norm(h, d, GAUSSIAN_KERNEL) + * elif kernel == 'tophat': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, TOPHAT_KERNEL) + * elif kernel == 'epanechnikov': + */ + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_tophat, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":521 + * result = _log_kernel_norm(h, d, GAUSSIAN_KERNEL) + * elif kernel == 'tophat': + * result = _log_kernel_norm(h, d, TOPHAT_KERNEL) # <<<<<<<<<<<<<< + * elif kernel == 'epanechnikov': + * result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) + */ + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_7kd_tree__log_kernel_norm(__pyx_t_4, __pyx_t_3, __pyx_e_7sklearn_9neighbors_7kd_tree_TOPHAT_KERNEL); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":522 + * elif kernel == 'tophat': + * result = _log_kernel_norm(h, d, TOPHAT_KERNEL) + * elif kernel == 'epanechnikov': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) + * elif kernel == 'exponential': + */ + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_epanechnikov, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":523 + * result = _log_kernel_norm(h, d, TOPHAT_KERNEL) + * elif kernel == 'epanechnikov': + * result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) # <<<<<<<<<<<<<< + * elif kernel == 'exponential': + * result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) + */ + __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_2 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree__log_kernel_norm(__pyx_t_2, __pyx_t_3, __pyx_e_7sklearn_9neighbors_7kd_tree_EPANECHNIKOV_KERNEL); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":524 + * elif kernel == 'epanechnikov': + * result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) + * elif kernel == 'exponential': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) + * elif kernel == 'linear': + */ + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_exponential, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":525 + * result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) + * elif kernel == 'exponential': + * result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) # <<<<<<<<<<<<<< + * elif kernel == 'linear': + * result = _log_kernel_norm(h, d, LINEAR_KERNEL) + */ + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_7kd_tree__log_kernel_norm(__pyx_t_4, __pyx_t_3, __pyx_e_7sklearn_9neighbors_7kd_tree_EXPONENTIAL_KERNEL); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":526 + * elif kernel == 'exponential': + * result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) + * elif kernel == 'linear': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, LINEAR_KERNEL) + * elif kernel == 'cosine': + */ + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_linear, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":527 + * result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) + * elif kernel == 'linear': + * result = _log_kernel_norm(h, d, LINEAR_KERNEL) # <<<<<<<<<<<<<< + * elif kernel == 'cosine': + * result = _log_kernel_norm(h, d, COSINE_KERNEL) + */ + __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_2 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree__log_kernel_norm(__pyx_t_2, __pyx_t_3, __pyx_e_7sklearn_9neighbors_7kd_tree_LINEAR_KERNEL); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":528 + * elif kernel == 'linear': + * result = _log_kernel_norm(h, d, LINEAR_KERNEL) + * elif kernel == 'cosine': # <<<<<<<<<<<<<< + * result = _log_kernel_norm(h, d, COSINE_KERNEL) + * else: + */ + __pyx_t_1 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_cosine, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":529 + * result = _log_kernel_norm(h, d, LINEAR_KERNEL) + * elif kernel == 'cosine': + * result = _log_kernel_norm(h, d, COSINE_KERNEL) # <<<<<<<<<<<<<< + * else: + * raise ValueError('kernel not recognized') + */ + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_d); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_7kd_tree__log_kernel_norm(__pyx_t_4, __pyx_t_3, __pyx_e_7sklearn_9neighbors_7kd_tree_COSINE_KERNEL); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":531 + * result = _log_kernel_norm(h, d, COSINE_KERNEL) + * else: + * raise ValueError('kernel not recognized') # <<<<<<<<<<<<<< + * + * if return_log: + */ + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":533 + * raise ValueError('kernel not recognized') + * + * if return_log: # <<<<<<<<<<<<<< + * return result + * else: + */ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_return_log); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":534 + * + * if return_log: + * return result # <<<<<<<<<<<<<< + * else: + * return np.exp(result) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":536 + * return result + * else: + * return np.exp(result) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_exp); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_result); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_5, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_r = __pyx_t_7; + __pyx_t_7 = 0; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":497 + * + * + * def kernel_norm(h, d, kernel, return_log=False): # <<<<<<<<<<<<<< + * """Given a string specification of a kernel, compute the normalization. + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.kernel_norm", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":541 + * ###################################################################### + * # Tree Utility Routines + * cdef inline void swap(DITYPE_t* arr, ITYPE_t i1, ITYPE_t i2): # <<<<<<<<<<<<<< + * """swap the values at index i1 and i2 of arr""" + * cdef DITYPE_t tmp = arr[i1] + */ + +static CYTHON_INLINE void __pyx_fuse_0__pyx_f_7sklearn_9neighbors_7kd_tree_swap(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_arr, int __pyx_v_i1, int __pyx_v_i2) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_tmp; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_fuse_0swap", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":543 + * cdef inline void swap(DITYPE_t* arr, ITYPE_t i1, ITYPE_t i2): + * """swap the values at index i1 and i2 of arr""" + * cdef DITYPE_t tmp = arr[i1] # <<<<<<<<<<<<<< + * arr[i1] = arr[i2] + * arr[i2] = tmp + */ + __pyx_v_tmp = (__pyx_v_arr[__pyx_v_i1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":544 + * """swap the values at index i1 and i2 of arr""" + * cdef DITYPE_t tmp = arr[i1] + * arr[i1] = arr[i2] # <<<<<<<<<<<<<< + * arr[i2] = tmp + * + */ + (__pyx_v_arr[__pyx_v_i1]) = (__pyx_v_arr[__pyx_v_i2]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":545 + * cdef DITYPE_t tmp = arr[i1] + * arr[i1] = arr[i2] + * arr[i2] = tmp # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_arr[__pyx_v_i2]) = __pyx_v_tmp; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":541 + * ###################################################################### + * # Tree Utility Routines + * cdef inline void swap(DITYPE_t* arr, ITYPE_t i1, ITYPE_t i2): # <<<<<<<<<<<<<< + * """swap the values at index i1 and i2 of arr""" + * cdef DITYPE_t tmp = arr[i1] + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":548 + * + * + * cdef inline void dual_swap(DTYPE_t* darr, ITYPE_t* iarr, # <<<<<<<<<<<<<< + * ITYPE_t i1, ITYPE_t i2): + * """swap the values at inex i1 and i2 of both darr and iarr""" + */ + +static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_7kd_tree_dual_swap(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_darr, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_iarr, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dtmp; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_itmp; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("dual_swap", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":551 + * ITYPE_t i1, ITYPE_t i2): + * """swap the values at inex i1 and i2 of both darr and iarr""" + * cdef DTYPE_t dtmp = darr[i1] # <<<<<<<<<<<<<< + * darr[i1] = darr[i2] + * darr[i2] = dtmp + */ + __pyx_v_dtmp = (__pyx_v_darr[__pyx_v_i1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":552 + * """swap the values at inex i1 and i2 of both darr and iarr""" + * cdef DTYPE_t dtmp = darr[i1] + * darr[i1] = darr[i2] # <<<<<<<<<<<<<< + * darr[i2] = dtmp + * + */ + (__pyx_v_darr[__pyx_v_i1]) = (__pyx_v_darr[__pyx_v_i2]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":553 + * cdef DTYPE_t dtmp = darr[i1] + * darr[i1] = darr[i2] + * darr[i2] = dtmp # <<<<<<<<<<<<<< + * + * cdef ITYPE_t itmp = iarr[i1] + */ + (__pyx_v_darr[__pyx_v_i2]) = __pyx_v_dtmp; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":555 + * darr[i2] = dtmp + * + * cdef ITYPE_t itmp = iarr[i1] # <<<<<<<<<<<<<< + * iarr[i1] = iarr[i2] + * iarr[i2] = itmp + */ + __pyx_v_itmp = (__pyx_v_iarr[__pyx_v_i1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":556 + * + * cdef ITYPE_t itmp = iarr[i1] + * iarr[i1] = iarr[i2] # <<<<<<<<<<<<<< + * iarr[i2] = itmp + * + */ + (__pyx_v_iarr[__pyx_v_i1]) = (__pyx_v_iarr[__pyx_v_i2]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":557 + * cdef ITYPE_t itmp = iarr[i1] + * iarr[i1] = iarr[i2] + * iarr[i2] = itmp # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_iarr[__pyx_v_i2]) = __pyx_v_itmp; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":548 + * + * + * cdef inline void dual_swap(DTYPE_t* darr, ITYPE_t* iarr, # <<<<<<<<<<<<<< + * ITYPE_t i1, ITYPE_t i2): + * """swap the values at inex i1 and i2 of both darr and iarr""" + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":581 + * cdef ITYPE_t[:, ::1] indices + * + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} + if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap___cinit__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap___cinit__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":582 + * + * def __cinit__(self): + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__4, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->distances_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->distances_arr)); + __pyx_v_self->distances_arr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":583 + * def __cinit__(self): + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_tuple__6, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_self->indices_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->indices_arr)); + __pyx_v_self->indices_arr = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":584 + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) # <<<<<<<<<<<<<< + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + * + */ + __pyx_t_2 = ((PyObject *)__pyx_v_self->distances_arr); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_2)); if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->distances, 0); + __pyx_v_self->distances = __pyx_t_4; + __pyx_t_4.memview = NULL; + __pyx_t_4.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":585 + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + * self.indices = get_memview_ITYPE_2D(self.indices_arr) # <<<<<<<<<<<<<< + * + * def __init__(self, n_pts, n_nbrs): + */ + __pyx_t_2 = ((PyObject *)__pyx_v_self->indices_arr); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_2D(((PyArrayObject *)__pyx_t_2)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->indices, 0); + __pyx_v_self->indices = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":581 + * cdef ITYPE_t[:, ::1] indices + * + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __PYX_XDEC_MEMVIEW(&__pyx_t_4, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NeighborsHeap.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":587 + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + * + * def __init__(self, n_pts, n_nbrs): # <<<<<<<<<<<<<< + * self.distances_arr = np.inf + np.zeros((n_pts, n_nbrs), dtype=DTYPE, + * order='C') + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_n_pts = 0; + PyObject *__pyx_v_n_nbrs = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_n_pts,&__pyx_n_s_n_nbrs,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_pts)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_nbrs)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 587; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 587; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_n_pts = values[0]; + __pyx_v_n_nbrs = values[1]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 587; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NeighborsHeap.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_2__init__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_v_self), __pyx_v_n_pts, __pyx_v_n_nbrs); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_2__init__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_self, PyObject *__pyx_v_n_pts, PyObject *__pyx_v_n_nbrs) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":588 + * + * def __init__(self, n_pts, n_nbrs): + * self.distances_arr = np.inf + np.zeros((n_pts, n_nbrs), dtype=DTYPE, # <<<<<<<<<<<<<< + * order='C') + * self.indices_arr = np.zeros((n_pts, n_nbrs), dtype=ITYPE, order='C') + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_n_pts); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_n_pts); + __Pyx_GIVEREF(__pyx_v_n_pts); + __Pyx_INCREF(__pyx_v_n_nbrs); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_n_nbrs); + __Pyx_GIVEREF(__pyx_v_n_nbrs); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_t_5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->distances_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->distances_arr)); + __pyx_v_self->distances_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":590 + * self.distances_arr = np.inf + np.zeros((n_pts, n_nbrs), dtype=DTYPE, + * order='C') + * self.indices_arr = np.zeros((n_pts, n_nbrs), dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_n_pts); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_n_pts); + __Pyx_GIVEREF(__pyx_v_n_pts); + __Pyx_INCREF(__pyx_v_n_nbrs); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_n_nbrs); + __Pyx_GIVEREF(__pyx_v_n_nbrs); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->indices_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->indices_arr)); + __pyx_v_self->indices_arr = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":591 + * order='C') + * self.indices_arr = np.zeros((n_pts, n_nbrs), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) # <<<<<<<<<<<<<< + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + * + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->distances_arr); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_4)); if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->distances, 0); + __pyx_v_self->distances = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":592 + * self.indices_arr = np.zeros((n_pts, n_nbrs), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + * self.indices = get_memview_ITYPE_2D(self.indices_arr) # <<<<<<<<<<<<<< + * + * def get_arrays(self, sort=True): + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->indices_arr); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_2D(((PyArrayObject *)__pyx_t_4)); if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->indices, 0); + __pyx_v_self->indices = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":587 + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + * + * def __init__(self, n_pts, n_nbrs): # <<<<<<<<<<<<<< + * self.distances_arr = np.inf + np.zeros((n_pts, n_nbrs), dtype=DTYPE, + * order='C') + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NeighborsHeap.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":594 + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + * + * def get_arrays(self, sort=True): # <<<<<<<<<<<<<< + * """Get the arrays of distances and indices within the heap. + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_5get_arrays(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_4get_arrays[] = "Get the arrays of distances and indices within the heap.\n\n If sort=True, then simultaneously sort the indices and distances,\n so the closer points are listed first.\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_5get_arrays(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_sort = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_arrays (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_sort,0}; + PyObject* values[1] = {0}; + values[0] = ((PyObject *)Py_True); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sort); + if (value) { values[0] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "get_arrays") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 594; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_sort = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_arrays", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 594; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NeighborsHeap.get_arrays", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_4get_arrays(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_v_self), __pyx_v_sort); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_4get_arrays(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_self, PyObject *__pyx_v_sort) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_arrays", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":600 + * so the closer points are listed first. + * """ + * if sort: # <<<<<<<<<<<<<< + * self._sort() + * return self.distances_arr, self.indices_arr + */ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_sort); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":601 + * """ + * if sort: + * self._sort() # <<<<<<<<<<<<<< + * return self.distances_arr, self.indices_arr + * + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_v_self->__pyx_vtab)->_sort(__pyx_v_self); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 601; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":602 + * if sort: + * self._sort() + * return self.distances_arr, self.indices_arr # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t largest(self, ITYPE_t row) except -1: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self->distances_arr)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self->distances_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->distances_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->indices_arr)); + PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_v_self->indices_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->indices_arr)); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":594 + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + * + * def get_arrays(self, sort=True): # <<<<<<<<<<<<<< + * """Get the arrays of distances and indices within the heap. + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NeighborsHeap.get_arrays", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":604 + * return self.distances_arr, self.indices_arr + * + * cdef inline DTYPE_t largest(self, ITYPE_t row) except -1: # <<<<<<<<<<<<<< + * """Return the largest distance in the given row""" + * return self.distances[row, 0] + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("largest", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":606 + * cdef inline DTYPE_t largest(self, ITYPE_t row) except -1: + * """Return the largest distance in the given row""" + * return self.distances[row, 0] # <<<<<<<<<<<<<< + * + * cpdef int push(self, ITYPE_t row, DTYPE_t val, ITYPE_t i_val) except -1: + */ + if (unlikely(!__pyx_v_self->distances.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 606; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_v_row; + __pyx_t_2 = 0; + __pyx_r = (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->distances.data + __pyx_t_1 * __pyx_v_self->distances.strides[0]) )) + __pyx_t_2)) ))); + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":604 + * return self.distances_arr, self.indices_arr + * + * cdef inline DTYPE_t largest(self, ITYPE_t row) except -1: # <<<<<<<<<<<<<< + * """Return the largest distance in the given row""" + * return self.distances[row, 0] + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NeighborsHeap.largest", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":608 + * return self.distances[row, 0] + * + * cpdef int push(self, ITYPE_t row, DTYPE_t val, ITYPE_t i_val) except -1: # <<<<<<<<<<<<<< + * """push (val, i_val) into the given row""" + * cdef ITYPE_t i, ic1, ic2, i_swap + */ + +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_7push(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_push(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_val, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_val, int __pyx_skip_dispatch) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_ic1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_ic2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_swap; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_dist_arr; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_ind_arr; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("push", 0); + /* Check if called by wrapper */ + if (unlikely(__pyx_skip_dispatch)) ; + /* Check if overridden in Python */ + else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_push); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_7push)) { + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_row); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_val); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_i_val); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyInt_As_int(__pyx_t_4); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_r = __pyx_t_6; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":611 + * """push (val, i_val) into the given row""" + * cdef ITYPE_t i, ic1, ic2, i_swap + * cdef ITYPE_t size = self.distances.shape[1] # <<<<<<<<<<<<<< + * cdef DTYPE_t* dist_arr = &self.distances[row, 0] + * cdef ITYPE_t* ind_arr = &self.indices[row, 0] + */ + if (unlikely(!__pyx_v_self->distances.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 611; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_size = (__pyx_v_self->distances.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":612 + * cdef ITYPE_t i, ic1, ic2, i_swap + * cdef ITYPE_t size = self.distances.shape[1] + * cdef DTYPE_t* dist_arr = &self.distances[row, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* ind_arr = &self.indices[row, 0] + * + */ + if (unlikely(!__pyx_v_self->distances.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = __pyx_v_row; + __pyx_t_8 = 0; + __pyx_v_dist_arr = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->distances.data + __pyx_t_7 * __pyx_v_self->distances.strides[0]) )) + __pyx_t_8)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":613 + * cdef ITYPE_t size = self.distances.shape[1] + * cdef DTYPE_t* dist_arr = &self.distances[row, 0] + * cdef ITYPE_t* ind_arr = &self.indices[row, 0] # <<<<<<<<<<<<<< + * + * # check if val should be in heap + */ + if (unlikely(!__pyx_v_self->indices.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 613; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = __pyx_v_row; + __pyx_t_10 = 0; + __pyx_v_ind_arr = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ (__pyx_v_self->indices.data + __pyx_t_9 * __pyx_v_self->indices.strides[0]) )) + __pyx_t_10)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":616 + * + * # check if val should be in heap + * if val > dist_arr[0]: # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_t_11 = ((__pyx_v_val > (__pyx_v_dist_arr[0])) != 0); + if (__pyx_t_11) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":617 + * # check if val should be in heap + * if val > dist_arr[0]: + * return 0 # <<<<<<<<<<<<<< + * + * # insert val at position zero + */ + __pyx_r = 0; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":620 + * + * # insert val at position zero + * dist_arr[0] = val # <<<<<<<<<<<<<< + * ind_arr[0] = i_val + * + */ + (__pyx_v_dist_arr[0]) = __pyx_v_val; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":621 + * # insert val at position zero + * dist_arr[0] = val + * ind_arr[0] = i_val # <<<<<<<<<<<<<< + * + * #descend the heap, swapping values until the max heap criterion is met + */ + (__pyx_v_ind_arr[0]) = __pyx_v_i_val; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":624 + * + * #descend the heap, swapping values until the max heap criterion is met + * i = 0 # <<<<<<<<<<<<<< + * while True: + * ic1 = 2 * i + 1 + */ + __pyx_v_i = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":625 + * #descend the heap, swapping values until the max heap criterion is met + * i = 0 + * while True: # <<<<<<<<<<<<<< + * ic1 = 2 * i + 1 + * ic2 = ic1 + 1 + */ + while (1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":626 + * i = 0 + * while True: + * ic1 = 2 * i + 1 # <<<<<<<<<<<<<< + * ic2 = ic1 + 1 + * + */ + __pyx_v_ic1 = ((2 * __pyx_v_i) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":627 + * while True: + * ic1 = 2 * i + 1 + * ic2 = ic1 + 1 # <<<<<<<<<<<<<< + * + * if ic1 >= size: + */ + __pyx_v_ic2 = (__pyx_v_ic1 + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":629 + * ic2 = ic1 + 1 + * + * if ic1 >= size: # <<<<<<<<<<<<<< + * break + * elif ic2 >= size: + */ + __pyx_t_11 = ((__pyx_v_ic1 >= __pyx_v_size) != 0); + if (__pyx_t_11) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":630 + * + * if ic1 >= size: + * break # <<<<<<<<<<<<<< + * elif ic2 >= size: + * if dist_arr[ic1] > val: + */ + goto __pyx_L5_break; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":631 + * if ic1 >= size: + * break + * elif ic2 >= size: # <<<<<<<<<<<<<< + * if dist_arr[ic1] > val: + * i_swap = ic1 + */ + __pyx_t_11 = ((__pyx_v_ic2 >= __pyx_v_size) != 0); + if (__pyx_t_11) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":632 + * break + * elif ic2 >= size: + * if dist_arr[ic1] > val: # <<<<<<<<<<<<<< + * i_swap = ic1 + * else: + */ + __pyx_t_11 = (((__pyx_v_dist_arr[__pyx_v_ic1]) > __pyx_v_val) != 0); + if (__pyx_t_11) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":633 + * elif ic2 >= size: + * if dist_arr[ic1] > val: + * i_swap = ic1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_swap = __pyx_v_ic1; + goto __pyx_L7; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":635 + * i_swap = ic1 + * else: + * break # <<<<<<<<<<<<<< + * elif dist_arr[ic1] >= dist_arr[ic2]: + * if val < dist_arr[ic1]: + */ + goto __pyx_L5_break; + } + __pyx_L7:; + goto __pyx_L6; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":636 + * else: + * break + * elif dist_arr[ic1] >= dist_arr[ic2]: # <<<<<<<<<<<<<< + * if val < dist_arr[ic1]: + * i_swap = ic1 + */ + __pyx_t_11 = (((__pyx_v_dist_arr[__pyx_v_ic1]) >= (__pyx_v_dist_arr[__pyx_v_ic2])) != 0); + if (__pyx_t_11) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":637 + * break + * elif dist_arr[ic1] >= dist_arr[ic2]: + * if val < dist_arr[ic1]: # <<<<<<<<<<<<<< + * i_swap = ic1 + * else: + */ + __pyx_t_11 = ((__pyx_v_val < (__pyx_v_dist_arr[__pyx_v_ic1])) != 0); + if (__pyx_t_11) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":638 + * elif dist_arr[ic1] >= dist_arr[ic2]: + * if val < dist_arr[ic1]: + * i_swap = ic1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_swap = __pyx_v_ic1; + goto __pyx_L8; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":640 + * i_swap = ic1 + * else: + * break # <<<<<<<<<<<<<< + * else: + * if val < dist_arr[ic2]: + */ + goto __pyx_L5_break; + } + __pyx_L8:; + goto __pyx_L6; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":642 + * break + * else: + * if val < dist_arr[ic2]: # <<<<<<<<<<<<<< + * i_swap = ic2 + * else: + */ + __pyx_t_11 = ((__pyx_v_val < (__pyx_v_dist_arr[__pyx_v_ic2])) != 0); + if (__pyx_t_11) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":643 + * else: + * if val < dist_arr[ic2]: + * i_swap = ic2 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_swap = __pyx_v_ic2; + goto __pyx_L9; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":645 + * i_swap = ic2 + * else: + * break # <<<<<<<<<<<<<< + * + * dist_arr[i] = dist_arr[i_swap] + */ + goto __pyx_L5_break; + } + __pyx_L9:; + } + __pyx_L6:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":647 + * break + * + * dist_arr[i] = dist_arr[i_swap] # <<<<<<<<<<<<<< + * ind_arr[i] = ind_arr[i_swap] + * + */ + (__pyx_v_dist_arr[__pyx_v_i]) = (__pyx_v_dist_arr[__pyx_v_i_swap]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":648 + * + * dist_arr[i] = dist_arr[i_swap] + * ind_arr[i] = ind_arr[i_swap] # <<<<<<<<<<<<<< + * + * i = i_swap + */ + (__pyx_v_ind_arr[__pyx_v_i]) = (__pyx_v_ind_arr[__pyx_v_i_swap]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":650 + * ind_arr[i] = ind_arr[i_swap] + * + * i = i_swap # <<<<<<<<<<<<<< + * + * dist_arr[i] = val + */ + __pyx_v_i = __pyx_v_i_swap; + } + __pyx_L5_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":652 + * i = i_swap + * + * dist_arr[i] = val # <<<<<<<<<<<<<< + * ind_arr[i] = i_val + * + */ + (__pyx_v_dist_arr[__pyx_v_i]) = __pyx_v_val; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":653 + * + * dist_arr[i] = val + * ind_arr[i] = i_val # <<<<<<<<<<<<<< + * + * return 0 + */ + (__pyx_v_ind_arr[__pyx_v_i]) = __pyx_v_i_val; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":655 + * ind_arr[i] = i_val + * + * return 0 # <<<<<<<<<<<<<< + * + * cdef int _sort(self) except -1: + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":608 + * return self.distances[row, 0] + * + * cpdef int push(self, ITYPE_t row, DTYPE_t val, ITYPE_t i_val) except -1: # <<<<<<<<<<<<<< + * """push (val, i_val) into the given row""" + * cdef ITYPE_t i, ic1, ic2, i_swap + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NeighborsHeap.push", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_7push(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_6push[] = "push (val, i_val) into the given row"; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_7push(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_val; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_val; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("push (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_row,&__pyx_n_s_val,&__pyx_n_s_i_val,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_row)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_val)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("push", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_i_val)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("push", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "push") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v_row = __Pyx_PyInt_As_Py_intptr_t(values[0]); if (unlikely((__pyx_v_row == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_val = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_val == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_i_val = __Pyx_PyInt_As_Py_intptr_t(values[2]); if (unlikely((__pyx_v_i_val == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("push", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NeighborsHeap.push", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_6push(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_v_self), __pyx_v_row, __pyx_v_val, __pyx_v_i_val); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_6push(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_val, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_val) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("push", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_v_self->__pyx_vtab)->push(__pyx_v_self, __pyx_v_row, __pyx_v_val, __pyx_v_i_val, 1); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NeighborsHeap.push", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":657 + * return 0 + * + * cdef int _sort(self) except -1: # <<<<<<<<<<<<<< + * """simultaneously sort the distances and indices""" + * cdef DTYPE_t[:, ::1] distances = self.distances + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap__sort(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_distances = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_indices = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_2 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_sort", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":659 + * cdef int _sort(self) except -1: + * """simultaneously sort the distances and indices""" + * cdef DTYPE_t[:, ::1] distances = self.distances # <<<<<<<<<<<<<< + * cdef ITYPE_t[:, ::1] indices = self.indices + * cdef ITYPE_t row + */ + if (unlikely(!__pyx_v_self->distances.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_v_self->distances; + __PYX_INC_MEMVIEW(&__pyx_t_1, 1); + __pyx_v_distances = __pyx_t_1; + __pyx_t_1.memview = NULL; + __pyx_t_1.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":660 + * """simultaneously sort the distances and indices""" + * cdef DTYPE_t[:, ::1] distances = self.distances + * cdef ITYPE_t[:, ::1] indices = self.indices # <<<<<<<<<<<<<< + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + */ + if (unlikely(!__pyx_v_self->indices.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = __pyx_v_self->indices; + __PYX_INC_MEMVIEW(&__pyx_t_2, 1); + __pyx_v_indices = __pyx_t_2; + __pyx_t_2.memview = NULL; + __pyx_t_2.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":662 + * cdef ITYPE_t[:, ::1] indices = self.indices + * cdef ITYPE_t row + * for row in range(distances.shape[0]): # <<<<<<<<<<<<<< + * _simultaneous_sort(&distances[row, 0], + * &indices[row, 0], + */ + __pyx_t_3 = (__pyx_v_distances.shape[0]); + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_row = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":663 + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], # <<<<<<<<<<<<<< + * &indices[row, 0], + * distances.shape[1]) + */ + __pyx_t_5 = __pyx_v_row; + __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":664 + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], + * &indices[row, 0], # <<<<<<<<<<<<<< + * distances.shape[1]) + * return 0 + */ + __pyx_t_7 = __pyx_v_row; + __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":663 + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], # <<<<<<<<<<<<<< + * &indices[row, 0], + * distances.shape[1]) + */ + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_7kd_tree__simultaneous_sort((&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_distances.data + __pyx_t_5 * __pyx_v_distances.strides[0]) )) + __pyx_t_6)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ (__pyx_v_indices.data + __pyx_t_7 * __pyx_v_indices.strides[0]) )) + __pyx_t_8)) )))), (__pyx_v_distances.shape[1])); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 663; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":666 + * &indices[row, 0], + * distances.shape[1]) + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":657 + * return 0 + * + * cdef int _sort(self) except -1: # <<<<<<<<<<<<<< + * """simultaneously sort the distances and indices""" + * cdef DTYPE_t[:, ::1] distances = self.distances + */ + + /* function exit code */ + __pyx_L1_error:; + __PYX_XDEC_MEMVIEW(&__pyx_t_1, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_2, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NeighborsHeap._sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_distances, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_indices, 1); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":669 + * + * + * cdef int _simultaneous_sort(DTYPE_t* dist, ITYPE_t* idx, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """ + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree__simultaneous_sort(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_dist, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_pivot_idx; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_store_idx; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_pivot_val; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + long __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_simultaneous_sort", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":684 + * + * # in the small-array case, do things efficiently + * if size <= 1: # <<<<<<<<<<<<<< + * pass + * elif size == 2: + */ + __pyx_t_1 = ((__pyx_v_size <= 1) != 0); + if (__pyx_t_1) { + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":686 + * if size <= 1: + * pass + * elif size == 2: # <<<<<<<<<<<<<< + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) + */ + __pyx_t_1 = ((__pyx_v_size == 2) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":687 + * pass + * elif size == 2: + * if dist[0] > dist[1]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 0, 1) + * elif size == 3: + */ + __pyx_t_1 = (((__pyx_v_dist[0]) > (__pyx_v_dist[1])) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":688 + * elif size == 2: + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) # <<<<<<<<<<<<<< + * elif size == 3: + * if dist[0] > dist[1]: + */ + __pyx_f_7sklearn_9neighbors_7kd_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 0, 1); + goto __pyx_L4; + } + __pyx_L4:; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":689 + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) + * elif size == 3: # <<<<<<<<<<<<<< + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) + */ + __pyx_t_1 = ((__pyx_v_size == 3) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":690 + * dual_swap(dist, idx, 0, 1) + * elif size == 3: + * if dist[0] > dist[1]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 0, 1) + * if dist[1] > dist[2]: + */ + __pyx_t_1 = (((__pyx_v_dist[0]) > (__pyx_v_dist[1])) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":691 + * elif size == 3: + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) # <<<<<<<<<<<<<< + * if dist[1] > dist[2]: + * dual_swap(dist, idx, 1, 2) + */ + __pyx_f_7sklearn_9neighbors_7kd_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 0, 1); + goto __pyx_L5; + } + __pyx_L5:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":692 + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) + * if dist[1] > dist[2]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 1, 2) + * if dist[0] > dist[1]: + */ + __pyx_t_1 = (((__pyx_v_dist[1]) > (__pyx_v_dist[2])) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":693 + * dual_swap(dist, idx, 0, 1) + * if dist[1] > dist[2]: + * dual_swap(dist, idx, 1, 2) # <<<<<<<<<<<<<< + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) + */ + __pyx_f_7sklearn_9neighbors_7kd_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 1, 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":694 + * if dist[1] > dist[2]: + * dual_swap(dist, idx, 1, 2) + * if dist[0] > dist[1]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 0, 1) + * else: + */ + __pyx_t_1 = (((__pyx_v_dist[0]) > (__pyx_v_dist[1])) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":695 + * dual_swap(dist, idx, 1, 2) + * if dist[0] > dist[1]: + * dual_swap(dist, idx, 0, 1) # <<<<<<<<<<<<<< + * else: + * # Determine the pivot using the median-of-three rule. + */ + __pyx_f_7sklearn_9neighbors_7kd_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 0, 1); + goto __pyx_L7; + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":701 + * # the middle (the pivot value) is moved to the end, and the largest + * # is moved to the pivot index. + * pivot_idx = size / 2 # <<<<<<<<<<<<<< + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) + */ + __pyx_v_pivot_idx = (__pyx_v_size / 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":702 + * # is moved to the pivot index. + * pivot_idx = size / 2 + * if dist[0] > dist[size - 1]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 0, size - 1) + * if dist[size - 1] > dist[pivot_idx]: + */ + __pyx_t_1 = (((__pyx_v_dist[0]) > (__pyx_v_dist[(__pyx_v_size - 1)])) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":703 + * pivot_idx = size / 2 + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) # <<<<<<<<<<<<<< + * if dist[size - 1] > dist[pivot_idx]: + * dual_swap(dist, idx, size - 1, pivot_idx) + */ + __pyx_f_7sklearn_9neighbors_7kd_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 0, (__pyx_v_size - 1)); + goto __pyx_L8; + } + __pyx_L8:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":704 + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) + * if dist[size - 1] > dist[pivot_idx]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, size - 1, pivot_idx) + * if dist[0] > dist[size - 1]: + */ + __pyx_t_1 = (((__pyx_v_dist[(__pyx_v_size - 1)]) > (__pyx_v_dist[__pyx_v_pivot_idx])) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":705 + * dual_swap(dist, idx, 0, size - 1) + * if dist[size - 1] > dist[pivot_idx]: + * dual_swap(dist, idx, size - 1, pivot_idx) # <<<<<<<<<<<<<< + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) + */ + __pyx_f_7sklearn_9neighbors_7kd_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, (__pyx_v_size - 1), __pyx_v_pivot_idx); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":706 + * if dist[size - 1] > dist[pivot_idx]: + * dual_swap(dist, idx, size - 1, pivot_idx) + * if dist[0] > dist[size - 1]: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, 0, size - 1) + * pivot_val = dist[size - 1] + */ + __pyx_t_1 = (((__pyx_v_dist[0]) > (__pyx_v_dist[(__pyx_v_size - 1)])) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":707 + * dual_swap(dist, idx, size - 1, pivot_idx) + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) # <<<<<<<<<<<<<< + * pivot_val = dist[size - 1] + * + */ + __pyx_f_7sklearn_9neighbors_7kd_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, 0, (__pyx_v_size - 1)); + goto __pyx_L10; + } + __pyx_L10:; + goto __pyx_L9; + } + __pyx_L9:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":708 + * if dist[0] > dist[size - 1]: + * dual_swap(dist, idx, 0, size - 1) + * pivot_val = dist[size - 1] # <<<<<<<<<<<<<< + * + * # partition indices about pivot. At the end of this operation, + */ + __pyx_v_pivot_val = (__pyx_v_dist[(__pyx_v_size - 1)]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":713 + * # pivot_idx will contain the pivot value, everything to the left + * # will be smaller, and everything to the right will be larger. + * store_idx = 0 # <<<<<<<<<<<<<< + * for i in range(size - 1): + * if dist[i] < pivot_val: + */ + __pyx_v_store_idx = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":714 + * # will be smaller, and everything to the right will be larger. + * store_idx = 0 + * for i in range(size - 1): # <<<<<<<<<<<<<< + * if dist[i] < pivot_val: + * dual_swap(dist, idx, i, store_idx) + */ + __pyx_t_2 = (__pyx_v_size - 1); + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":715 + * store_idx = 0 + * for i in range(size - 1): + * if dist[i] < pivot_val: # <<<<<<<<<<<<<< + * dual_swap(dist, idx, i, store_idx) + * store_idx += 1 + */ + __pyx_t_1 = (((__pyx_v_dist[__pyx_v_i]) < __pyx_v_pivot_val) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":716 + * for i in range(size - 1): + * if dist[i] < pivot_val: + * dual_swap(dist, idx, i, store_idx) # <<<<<<<<<<<<<< + * store_idx += 1 + * dual_swap(dist, idx, store_idx, size - 1) + */ + __pyx_f_7sklearn_9neighbors_7kd_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, __pyx_v_i, __pyx_v_store_idx); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":717 + * if dist[i] < pivot_val: + * dual_swap(dist, idx, i, store_idx) + * store_idx += 1 # <<<<<<<<<<<<<< + * dual_swap(dist, idx, store_idx, size - 1) + * pivot_idx = store_idx + */ + __pyx_v_store_idx = (__pyx_v_store_idx + 1); + goto __pyx_L13; + } + __pyx_L13:; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":718 + * dual_swap(dist, idx, i, store_idx) + * store_idx += 1 + * dual_swap(dist, idx, store_idx, size - 1) # <<<<<<<<<<<<<< + * pivot_idx = store_idx + * + */ + __pyx_f_7sklearn_9neighbors_7kd_tree_dual_swap(__pyx_v_dist, __pyx_v_idx, __pyx_v_store_idx, (__pyx_v_size - 1)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":719 + * store_idx += 1 + * dual_swap(dist, idx, store_idx, size - 1) + * pivot_idx = store_idx # <<<<<<<<<<<<<< + * + * # recursively sort each side of the pivot + */ + __pyx_v_pivot_idx = __pyx_v_store_idx; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":722 + * + * # recursively sort each side of the pivot + * if pivot_idx > 1: # <<<<<<<<<<<<<< + * _simultaneous_sort(dist, idx, pivot_idx) + * if pivot_idx + 2 < size: + */ + __pyx_t_1 = ((__pyx_v_pivot_idx > 1) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":723 + * # recursively sort each side of the pivot + * if pivot_idx > 1: + * _simultaneous_sort(dist, idx, pivot_idx) # <<<<<<<<<<<<<< + * if pivot_idx + 2 < size: + * _simultaneous_sort(dist + pivot_idx + 1, + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree__simultaneous_sort(__pyx_v_dist, __pyx_v_idx, __pyx_v_pivot_idx); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":724 + * if pivot_idx > 1: + * _simultaneous_sort(dist, idx, pivot_idx) + * if pivot_idx + 2 < size: # <<<<<<<<<<<<<< + * _simultaneous_sort(dist + pivot_idx + 1, + * idx + pivot_idx + 1, + */ + __pyx_t_1 = (((__pyx_v_pivot_idx + 2) < __pyx_v_size) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":725 + * _simultaneous_sort(dist, idx, pivot_idx) + * if pivot_idx + 2 < size: + * _simultaneous_sort(dist + pivot_idx + 1, # <<<<<<<<<<<<<< + * idx + pivot_idx + 1, + * size - pivot_idx - 1) + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree__simultaneous_sort(((__pyx_v_dist + __pyx_v_pivot_idx) + 1), ((__pyx_v_idx + __pyx_v_pivot_idx) + 1), ((__pyx_v_size - __pyx_v_pivot_idx) - 1)); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L15; + } + __pyx_L15:; + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":728 + * idx + pivot_idx + 1, + * size - pivot_idx - 1) + * return 0 # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":669 + * + * + * cdef int _simultaneous_sort(DTYPE_t* dist, ITYPE_t* idx, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """ + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree._simultaneous_sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":734 + * # this computes the equivalent of + * # j_max = np.argmax(np.max(data, 0) - np.min(data, 0)) + * cdef ITYPE_t find_node_split_dim(DTYPE_t* data, # <<<<<<<<<<<<<< + * ITYPE_t* node_indices, + * ITYPE_t n_features, + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_find_node_split_dim(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_node_indices, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_points) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_min_val; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_max_val; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_val; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_max_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j_max; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + int __pyx_t_5; + __Pyx_RefNannySetupContext("find_node_split_dim", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":767 + * cdef ITYPE_t i, j, j_max + * + * j_max = 0 # <<<<<<<<<<<<<< + * max_spread = 0 + * + */ + __pyx_v_j_max = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":768 + * + * j_max = 0 + * max_spread = 0 # <<<<<<<<<<<<<< + * + * for j in range(n_features): + */ + __pyx_v_max_spread = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":770 + * max_spread = 0 + * + * for j in range(n_features): # <<<<<<<<<<<<<< + * max_val = data[node_indices[0] * n_features + j] + * min_val = max_val + */ + __pyx_t_1 = __pyx_v_n_features; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":771 + * + * for j in range(n_features): + * max_val = data[node_indices[0] * n_features + j] # <<<<<<<<<<<<<< + * min_val = max_val + * for i in range(1, n_points): + */ + __pyx_v_max_val = (__pyx_v_data[(((__pyx_v_node_indices[0]) * __pyx_v_n_features) + __pyx_v_j)]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":772 + * for j in range(n_features): + * max_val = data[node_indices[0] * n_features + j] + * min_val = max_val # <<<<<<<<<<<<<< + * for i in range(1, n_points): + * val = data[node_indices[i] * n_features + j] + */ + __pyx_v_min_val = __pyx_v_max_val; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":773 + * max_val = data[node_indices[0] * n_features + j] + * min_val = max_val + * for i in range(1, n_points): # <<<<<<<<<<<<<< + * val = data[node_indices[i] * n_features + j] + * max_val = fmax(max_val, val) + */ + __pyx_t_3 = __pyx_v_n_points; + for (__pyx_t_4 = 1; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":774 + * min_val = max_val + * for i in range(1, n_points): + * val = data[node_indices[i] * n_features + j] # <<<<<<<<<<<<<< + * max_val = fmax(max_val, val) + * min_val = fmin(min_val, val) + */ + __pyx_v_val = (__pyx_v_data[(((__pyx_v_node_indices[__pyx_v_i]) * __pyx_v_n_features) + __pyx_v_j)]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":775 + * for i in range(1, n_points): + * val = data[node_indices[i] * n_features + j] + * max_val = fmax(max_val, val) # <<<<<<<<<<<<<< + * min_val = fmin(min_val, val) + * spread = max_val - min_val + */ + __pyx_v_max_val = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax(__pyx_v_max_val, __pyx_v_val); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":776 + * val = data[node_indices[i] * n_features + j] + * max_val = fmax(max_val, val) + * min_val = fmin(min_val, val) # <<<<<<<<<<<<<< + * spread = max_val - min_val + * if spread > max_spread: + */ + __pyx_v_min_val = __pyx_f_7sklearn_9neighbors_7kd_tree_fmin(__pyx_v_min_val, __pyx_v_val); + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":777 + * max_val = fmax(max_val, val) + * min_val = fmin(min_val, val) + * spread = max_val - min_val # <<<<<<<<<<<<<< + * if spread > max_spread: + * max_spread = spread + */ + __pyx_v_spread = (__pyx_v_max_val - __pyx_v_min_val); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":778 + * min_val = fmin(min_val, val) + * spread = max_val - min_val + * if spread > max_spread: # <<<<<<<<<<<<<< + * max_spread = spread + * j_max = j + */ + __pyx_t_5 = ((__pyx_v_spread > __pyx_v_max_spread) != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":779 + * spread = max_val - min_val + * if spread > max_spread: + * max_spread = spread # <<<<<<<<<<<<<< + * j_max = j + * return j_max + */ + __pyx_v_max_spread = __pyx_v_spread; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":780 + * if spread > max_spread: + * max_spread = spread + * j_max = j # <<<<<<<<<<<<<< + * return j_max + * + */ + __pyx_v_j_max = __pyx_v_j; + goto __pyx_L7; + } + __pyx_L7:; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":781 + * max_spread = spread + * j_max = j + * return j_max # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_j_max; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":734 + * # this computes the equivalent of + * # j_max = np.argmax(np.max(data, 0) - np.min(data, 0)) + * cdef ITYPE_t find_node_split_dim(DTYPE_t* data, # <<<<<<<<<<<<<< + * ITYPE_t* node_indices, + * ITYPE_t n_features, + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":784 + * + * + * cdef int partition_node_indices(DTYPE_t* data, # <<<<<<<<<<<<<< + * ITYPE_t* node_indices, + * ITYPE_t split_dim, + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_partition_node_indices(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_node_indices, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_split_dim, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_split_index, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_points) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_left; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_right; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_midindex; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d2; + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("partition_node_indices", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":829 + * cdef ITYPE_t left, right, midindex, i + * cdef DTYPE_t d1, d2 + * left = 0 # <<<<<<<<<<<<<< + * right = n_points - 1 + * + */ + __pyx_v_left = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":830 + * cdef DTYPE_t d1, d2 + * left = 0 + * right = n_points - 1 # <<<<<<<<<<<<<< + * + * while True: + */ + __pyx_v_right = (__pyx_v_n_points - 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":832 + * right = n_points - 1 + * + * while True: # <<<<<<<<<<<<<< + * midindex = left + * for i in range(left, right): + */ + while (1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":833 + * + * while True: + * midindex = left # <<<<<<<<<<<<<< + * for i in range(left, right): + * d1 = data[node_indices[i] * n_features + split_dim] + */ + __pyx_v_midindex = __pyx_v_left; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":834 + * while True: + * midindex = left + * for i in range(left, right): # <<<<<<<<<<<<<< + * d1 = data[node_indices[i] * n_features + split_dim] + * d2 = data[node_indices[right] * n_features + split_dim] + */ + __pyx_t_1 = __pyx_v_right; + for (__pyx_t_2 = __pyx_v_left; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":835 + * midindex = left + * for i in range(left, right): + * d1 = data[node_indices[i] * n_features + split_dim] # <<<<<<<<<<<<<< + * d2 = data[node_indices[right] * n_features + split_dim] + * if d1 < d2: + */ + __pyx_v_d1 = (__pyx_v_data[(((__pyx_v_node_indices[__pyx_v_i]) * __pyx_v_n_features) + __pyx_v_split_dim)]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":836 + * for i in range(left, right): + * d1 = data[node_indices[i] * n_features + split_dim] + * d2 = data[node_indices[right] * n_features + split_dim] # <<<<<<<<<<<<<< + * if d1 < d2: + * swap(node_indices, i, midindex) + */ + __pyx_v_d2 = (__pyx_v_data[(((__pyx_v_node_indices[__pyx_v_right]) * __pyx_v_n_features) + __pyx_v_split_dim)]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":837 + * d1 = data[node_indices[i] * n_features + split_dim] + * d2 = data[node_indices[right] * n_features + split_dim] + * if d1 < d2: # <<<<<<<<<<<<<< + * swap(node_indices, i, midindex) + * midindex += 1 + */ + __pyx_t_3 = ((__pyx_v_d1 < __pyx_v_d2) != 0); + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":838 + * d2 = data[node_indices[right] * n_features + split_dim] + * if d1 < d2: + * swap(node_indices, i, midindex) # <<<<<<<<<<<<<< + * midindex += 1 + * swap(node_indices, midindex, right) + */ + __pyx_fuse_0__pyx_f_7sklearn_9neighbors_7kd_tree_swap(__pyx_v_node_indices, __pyx_v_i, __pyx_v_midindex); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":839 + * if d1 < d2: + * swap(node_indices, i, midindex) + * midindex += 1 # <<<<<<<<<<<<<< + * swap(node_indices, midindex, right) + * if midindex == split_index: + */ + __pyx_v_midindex = (__pyx_v_midindex + 1); + goto __pyx_L7; + } + __pyx_L7:; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":840 + * swap(node_indices, i, midindex) + * midindex += 1 + * swap(node_indices, midindex, right) # <<<<<<<<<<<<<< + * if midindex == split_index: + * break + */ + __pyx_fuse_0__pyx_f_7sklearn_9neighbors_7kd_tree_swap(__pyx_v_node_indices, __pyx_v_midindex, __pyx_v_right); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":841 + * midindex += 1 + * swap(node_indices, midindex, right) + * if midindex == split_index: # <<<<<<<<<<<<<< + * break + * elif midindex < split_index: + */ + __pyx_t_3 = ((__pyx_v_midindex == __pyx_v_split_index) != 0); + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":842 + * swap(node_indices, midindex, right) + * if midindex == split_index: + * break # <<<<<<<<<<<<<< + * elif midindex < split_index: + * left = midindex + 1 + */ + goto __pyx_L4_break; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":843 + * if midindex == split_index: + * break + * elif midindex < split_index: # <<<<<<<<<<<<<< + * left = midindex + 1 + * else: + */ + __pyx_t_3 = ((__pyx_v_midindex < __pyx_v_split_index) != 0); + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":844 + * break + * elif midindex < split_index: + * left = midindex + 1 # <<<<<<<<<<<<<< + * else: + * right = midindex - 1 + */ + __pyx_v_left = (__pyx_v_midindex + 1); + goto __pyx_L8; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":846 + * left = midindex + 1 + * else: + * right = midindex - 1 # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_v_right = (__pyx_v_midindex - 1); + } + __pyx_L8:; + } + __pyx_L4_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":848 + * right = midindex - 1 + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":784 + * + * + * cdef int partition_node_indices(DTYPE_t* data, # <<<<<<<<<<<<<< + * ITYPE_t* node_indices, + * ITYPE_t split_dim, + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":854 + * # NodeHeap : min-heap used to keep track of nodes during + * # breadth-first query + * cdef inline void swap_nodes(NodeHeapData_t* arr, ITYPE_t i1, ITYPE_t i2): # <<<<<<<<<<<<<< + * cdef NodeHeapData_t tmp = arr[i1] + * arr[i1] = arr[i2] + */ + +static CYTHON_INLINE void __pyx_f_7sklearn_9neighbors_7kd_tree_swap_nodes(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *__pyx_v_arr, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2) { + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_v_tmp; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("swap_nodes", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":855 + * # breadth-first query + * cdef inline void swap_nodes(NodeHeapData_t* arr, ITYPE_t i1, ITYPE_t i2): + * cdef NodeHeapData_t tmp = arr[i1] # <<<<<<<<<<<<<< + * arr[i1] = arr[i2] + * arr[i2] = tmp + */ + __pyx_v_tmp = (__pyx_v_arr[__pyx_v_i1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":856 + * cdef inline void swap_nodes(NodeHeapData_t* arr, ITYPE_t i1, ITYPE_t i2): + * cdef NodeHeapData_t tmp = arr[i1] + * arr[i1] = arr[i2] # <<<<<<<<<<<<<< + * arr[i2] = tmp + * + */ + (__pyx_v_arr[__pyx_v_i1]) = (__pyx_v_arr[__pyx_v_i2]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":857 + * cdef NodeHeapData_t tmp = arr[i1] + * arr[i1] = arr[i2] + * arr[i2] = tmp # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_arr[__pyx_v_i2]) = __pyx_v_tmp; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":854 + * # NodeHeap : min-heap used to keep track of nodes during + * # breadth-first query + * cdef inline void swap_nodes(NodeHeapData_t* arr, ITYPE_t i1, ITYPE_t i2): # <<<<<<<<<<<<<< + * cdef NodeHeapData_t tmp = arr[i1] + * arr[i1] = arr[i2] + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":877 + * cdef ITYPE_t n + * + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.data_arr = np.zeros(1, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_8NodeHeap_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_8NodeHeap_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} + if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_8NodeHeap___cinit__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_8NodeHeap___cinit__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":878 + * + * def __cinit__(self): + * self.data_arr = np.zeros(1, dtype=NodeHeapData, order='C') # <<<<<<<<<<<<<< + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_NodeHeapData); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__7, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":879 + * def __cinit__(self): + * self.data_arr = np.zeros(1, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) # <<<<<<<<<<<<<< + * + * def __init__(self, size_guess=100): + */ + __pyx_t_3 = ((PyObject *)__pyx_v_self->data_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_NodeHeapData_1D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 879; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __pyx_v_self->data = __pyx_t_4; + __pyx_t_4.memview = NULL; + __pyx_t_4.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":877 + * cdef ITYPE_t n + * + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.data_arr = np.zeros(1, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __PYX_XDEC_MEMVIEW(&__pyx_t_4, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NodeHeap.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":881 + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + * + * def __init__(self, size_guess=100): # <<<<<<<<<<<<<< + * size_guess = max(size_guess, 1) # need space for at least one item + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_8NodeHeap_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_8NodeHeap_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_size_guess = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_size_guess,0}; + PyObject* values[1] = {0}; + values[0] = ((PyObject *)__pyx_int_100); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_size_guess); + if (value) { values[0] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 881; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_size_guess = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 881; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NodeHeap.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_8NodeHeap_2__init__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_self), __pyx_v_size_guess); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_8NodeHeap_2__init__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_self, PyObject *__pyx_v_size_guess) { + int __pyx_r; + __Pyx_RefNannyDeclarations + long __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_INCREF(__pyx_v_size_guess); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":882 + * + * def __init__(self, size_guess=100): + * size_guess = max(size_guess, 1) # need space for at least one item # <<<<<<<<<<<<<< + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + */ + __pyx_t_1 = 1; + __Pyx_INCREF(__pyx_v_size_guess); + __pyx_t_2 = __pyx_v_size_guess; + __pyx_t_4 = __Pyx_PyInt_From_long(__pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyObject_RichCompare(__pyx_t_4, __pyx_t_2, Py_GT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + __pyx_t_5 = __Pyx_PyInt_From_long(__pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __pyx_t_5; + __pyx_t_5 = 0; + } else { + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = __pyx_t_2; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_size_guess, __pyx_t_2); + __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":883 + * def __init__(self, size_guess=100): + * size_guess = max(size_guess, 1) # need space for at least one item + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') # <<<<<<<<<<<<<< + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + * self.n = size_guess + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_size_guess); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size_guess); + __Pyx_GIVEREF(__pyx_v_size_guess); + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_NodeHeapData); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_2, __pyx_t_5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 883; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":884 + * size_guess = max(size_guess, 1) # need space for at least one item + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) # <<<<<<<<<<<<<< + * self.n = size_guess + * self.clear() + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->data_arr); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_NodeHeapData_1D(((PyArrayObject *)__pyx_t_4)); if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __pyx_v_self->data = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":885 + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + * self.n = size_guess # <<<<<<<<<<<<<< + * self.clear() + * + */ + __pyx_t_8 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_size_guess); if (unlikely((__pyx_t_8 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->n = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":886 + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + * self.n = size_guess + * self.clear() # <<<<<<<<<<<<<< + * + * cdef int resize(self, ITYPE_t new_size) except -1: + */ + ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_self->__pyx_vtab)->clear(__pyx_v_self); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":881 + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + * + * def __init__(self, size_guess=100): # <<<<<<<<<<<<<< + * size_guess = max(size_guess, 1) # need space for at least one item + * self.data_arr = np.zeros(size_guess, dtype=NodeHeapData, order='C') + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NodeHeap.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_size_guess); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":888 + * self.clear() + * + * cdef int resize(self, ITYPE_t new_size) except -1: # <<<<<<<<<<<<<< + * """Resize the heap to be either larger or smaller""" + * cdef NodeHeapData_t *data_ptr, *new_data_ptr + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_8NodeHeap_resize(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_new_size) { + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *__pyx_v_data_ptr; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *__pyx_v_new_data_ptr; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size; + PyArrayObject *__pyx_v_new_data_arr = 0; + __Pyx_memviewslice __pyx_v_new_data = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("resize", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":892 + * cdef NodeHeapData_t *data_ptr, *new_data_ptr + * cdef ITYPE_t i + * cdef ITYPE_t size = self.data.shape[0] # <<<<<<<<<<<<<< + * cdef np.ndarray new_data_arr = np.zeros(new_size, + * dtype=NodeHeapData) + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 892; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_size = (__pyx_v_self->data.shape[0]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":893 + * cdef ITYPE_t i + * cdef ITYPE_t size = self.data.shape[0] + * cdef np.ndarray new_data_arr = np.zeros(new_size, # <<<<<<<<<<<<<< + * dtype=NodeHeapData) + * cdef NodeHeapData_t[::1] new_data =\ + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_new_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":894 + * cdef ITYPE_t size = self.data.shape[0] + * cdef np.ndarray new_data_arr = np.zeros(new_size, + * dtype=NodeHeapData) # <<<<<<<<<<<<<< + * cdef NodeHeapData_t[::1] new_data =\ + * get_memview_NodeHeapData_1D(new_data_arr) + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_NodeHeapData); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 894; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":893 + * cdef ITYPE_t i + * cdef ITYPE_t size = self.data.shape[0] + * cdef np.ndarray new_data_arr = np.zeros(new_size, # <<<<<<<<<<<<<< + * dtype=NodeHeapData) + * cdef NodeHeapData_t[::1] new_data =\ + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_new_data_arr = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":896 + * dtype=NodeHeapData) + * cdef NodeHeapData_t[::1] new_data =\ + * get_memview_NodeHeapData_1D(new_data_arr) # <<<<<<<<<<<<<< + * + * if size > 0 and new_size > 0: + */ + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_NodeHeapData_1D(((PyArrayObject *)__pyx_v_new_data_arr)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_new_data = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":898 + * get_memview_NodeHeapData_1D(new_data_arr) + * + * if size > 0 and new_size > 0: # <<<<<<<<<<<<<< + * data_ptr = &self.data[0] + * new_data_ptr = &new_data[0] + */ + __pyx_t_6 = ((__pyx_v_size > 0) != 0); + if (__pyx_t_6) { + __pyx_t_7 = ((__pyx_v_new_size > 0) != 0); + __pyx_t_8 = __pyx_t_7; + } else { + __pyx_t_8 = __pyx_t_6; + } + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":899 + * + * if size > 0 and new_size > 0: + * data_ptr = &self.data[0] # <<<<<<<<<<<<<< + * new_data_ptr = &new_data[0] + * for i in range(min(size, new_size)): + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 899; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = 0; + __pyx_v_data_ptr = (&(*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *) __pyx_v_self->data.data) + __pyx_t_9)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":900 + * if size > 0 and new_size > 0: + * data_ptr = &self.data[0] + * new_data_ptr = &new_data[0] # <<<<<<<<<<<<<< + * for i in range(min(size, new_size)): + * new_data_ptr[i] = data_ptr[i] + */ + __pyx_t_10 = 0; + __pyx_v_new_data_ptr = (&(*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *) __pyx_v_new_data.data) + __pyx_t_10)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":901 + * data_ptr = &self.data[0] + * new_data_ptr = &new_data[0] + * for i in range(min(size, new_size)): # <<<<<<<<<<<<<< + * new_data_ptr[i] = data_ptr[i] + * + */ + __pyx_t_11 = __pyx_v_new_size; + __pyx_t_12 = __pyx_v_size; + if (((__pyx_t_11 < __pyx_t_12) != 0)) { + __pyx_t_13 = __pyx_t_11; + } else { + __pyx_t_13 = __pyx_t_12; + } + __pyx_t_11 = __pyx_t_13; + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_11; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":902 + * new_data_ptr = &new_data[0] + * for i in range(min(size, new_size)): + * new_data_ptr[i] = data_ptr[i] # <<<<<<<<<<<<<< + * + * if new_size < size: + */ + (__pyx_v_new_data_ptr[__pyx_v_i]) = (__pyx_v_data_ptr[__pyx_v_i]); + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":904 + * new_data_ptr[i] = data_ptr[i] + * + * if new_size < size: # <<<<<<<<<<<<<< + * self.n = new_size + * + */ + __pyx_t_8 = ((__pyx_v_new_size < __pyx_v_size) != 0); + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":905 + * + * if new_size < size: + * self.n = new_size # <<<<<<<<<<<<<< + * + * self.data = new_data + */ + __pyx_v_self->n = __pyx_v_new_size; + goto __pyx_L6; + } + __pyx_L6:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":907 + * self.n = new_size + * + * self.data = new_data # <<<<<<<<<<<<<< + * self.data_arr = new_data_arr + * return 0 + */ + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __PYX_INC_MEMVIEW(&__pyx_v_new_data, 0); + __pyx_v_self->data = __pyx_v_new_data; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":908 + * + * self.data = new_data + * self.data_arr = new_data_arr # <<<<<<<<<<<<<< + * return 0 + * + */ + __Pyx_INCREF(((PyObject *)__pyx_v_new_data_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_new_data_arr)); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = __pyx_v_new_data_arr; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":909 + * self.data = new_data + * self.data_arr = new_data_arr + * return 0 # <<<<<<<<<<<<<< + * + * cdef int push(self, NodeHeapData_t data) except -1: + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":888 + * self.clear() + * + * cdef int resize(self, ITYPE_t new_size) except -1: # <<<<<<<<<<<<<< + * """Resize the heap to be either larger or smaller""" + * cdef NodeHeapData_t *data_ptr, *new_data_ptr + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NodeHeap.resize", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_new_data_arr); + __PYX_XDEC_MEMVIEW(&__pyx_v_new_data, 1); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":911 + * return 0 + * + * cdef int push(self, NodeHeapData_t data) except -1: # <<<<<<<<<<<<<< + * """Push a new item onto the heap""" + * cdef ITYPE_t i, i_parent + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_8NodeHeap_push(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_self, struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_v_data) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_parent; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *__pyx_v_data_arr; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + Py_ssize_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("push", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":915 + * cdef ITYPE_t i, i_parent + * cdef NodeHeapData_t* data_arr + * self.n += 1 # <<<<<<<<<<<<<< + * if self.n > self.data.shape[0]: + * self.resize(2 * self.n) + */ + __pyx_v_self->n = (__pyx_v_self->n + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":916 + * cdef NodeHeapData_t* data_arr + * self.n += 1 + * if self.n > self.data.shape[0]: # <<<<<<<<<<<<<< + * self.resize(2 * self.n) + * + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 916; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = ((__pyx_v_self->n > (__pyx_v_self->data.shape[0])) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":917 + * self.n += 1 + * if self.n > self.data.shape[0]: + * self.resize(2 * self.n) # <<<<<<<<<<<<<< + * + * # put the new element at the end, + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_self->__pyx_vtab)->resize(__pyx_v_self, (2 * __pyx_v_self->n)); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 917; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":921 + * # put the new element at the end, + * # and then perform swaps until the heap is in order + * data_arr = &self.data[0] # <<<<<<<<<<<<<< + * i = self.n - 1 + * data_arr[i] = data + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 921; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_data_arr = (&(*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *) __pyx_v_self->data.data) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":922 + * # and then perform swaps until the heap is in order + * data_arr = &self.data[0] + * i = self.n - 1 # <<<<<<<<<<<<<< + * data_arr[i] = data + * + */ + __pyx_v_i = (__pyx_v_self->n - 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":923 + * data_arr = &self.data[0] + * i = self.n - 1 + * data_arr[i] = data # <<<<<<<<<<<<<< + * + * while i > 0: + */ + (__pyx_v_data_arr[__pyx_v_i]) = __pyx_v_data; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":925 + * data_arr[i] = data + * + * while i > 0: # <<<<<<<<<<<<<< + * i_parent = (i - 1) // 2 + * if data_arr[i_parent].val <= data_arr[i].val: + */ + while (1) { + __pyx_t_1 = ((__pyx_v_i > 0) != 0); + if (!__pyx_t_1) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":926 + * + * while i > 0: + * i_parent = (i - 1) // 2 # <<<<<<<<<<<<<< + * if data_arr[i_parent].val <= data_arr[i].val: + * break + */ + __pyx_v_i_parent = ((__pyx_v_i - 1) / 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":927 + * while i > 0: + * i_parent = (i - 1) // 2 + * if data_arr[i_parent].val <= data_arr[i].val: # <<<<<<<<<<<<<< + * break + * else: + */ + __pyx_t_1 = (((__pyx_v_data_arr[__pyx_v_i_parent]).val <= (__pyx_v_data_arr[__pyx_v_i]).val) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":928 + * i_parent = (i - 1) // 2 + * if data_arr[i_parent].val <= data_arr[i].val: + * break # <<<<<<<<<<<<<< + * else: + * swap_nodes(data_arr, i, i_parent) + */ + goto __pyx_L5_break; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":930 + * break + * else: + * swap_nodes(data_arr, i, i_parent) # <<<<<<<<<<<<<< + * i = i_parent + * return 0 + */ + __pyx_f_7sklearn_9neighbors_7kd_tree_swap_nodes(__pyx_v_data_arr, __pyx_v_i, __pyx_v_i_parent); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":931 + * else: + * swap_nodes(data_arr, i, i_parent) + * i = i_parent # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_v_i = __pyx_v_i_parent; + } + } + __pyx_L5_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":932 + * swap_nodes(data_arr, i, i_parent) + * i = i_parent + * return 0 # <<<<<<<<<<<<<< + * + * cdef NodeHeapData_t peek(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":911 + * return 0 + * + * cdef int push(self, NodeHeapData_t data) except -1: # <<<<<<<<<<<<<< + * """Push a new item onto the heap""" + * cdef ITYPE_t i, i_parent + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.NodeHeap.push", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":934 + * return 0 + * + * cdef NodeHeapData_t peek(self): # <<<<<<<<<<<<<< + * """Peek at the root of the heap, without removing it""" + * return self.data[0] + */ + +static struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_f_7sklearn_9neighbors_7kd_tree_8NodeHeap_peek(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_self) { + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("peek", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":936 + * cdef NodeHeapData_t peek(self): + * """Peek at the root of the heap, without removing it""" + * return self.data[0] # <<<<<<<<<<<<<< + * + * cdef NodeHeapData_t pop(self): + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 936; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_r = (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *) __pyx_v_self->data.data) + __pyx_t_1)) ))); + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":934 + * return 0 + * + * cdef NodeHeapData_t peek(self): # <<<<<<<<<<<<<< + * """Peek at the root of the heap, without removing it""" + * return self.data[0] + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_WriteUnraisable("sklearn.neighbors.kd_tree.NodeHeap.peek", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":938 + * return self.data[0] + * + * cdef NodeHeapData_t pop(self): # <<<<<<<<<<<<<< + * """Remove the root of the heap, and update the remaining nodes""" + * if self.n == 0: + */ + +static struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_f_7sklearn_9neighbors_7kd_tree_8NodeHeap_pop(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_self) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_child1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_child2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_swap; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *__pyx_v_data_arr; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_v_popped_element; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pop", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":940 + * cdef NodeHeapData_t pop(self): + * """Remove the root of the heap, and update the remaining nodes""" + * if self.n == 0: # <<<<<<<<<<<<<< + * raise ValueError('cannot pop on empty heap') + * + */ + __pyx_t_1 = ((__pyx_v_self->n == 0) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":941 + * """Remove the root of the heap, and update the remaining nodes""" + * if self.n == 0: + * raise ValueError('cannot pop on empty heap') # <<<<<<<<<<<<<< + * + * cdef ITYPE_t i, i_child1, i_child2, i_swap + */ + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 941; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 941; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":944 + * + * cdef ITYPE_t i, i_child1, i_child2, i_swap + * cdef NodeHeapData_t* data_arr = &self.data[0] # <<<<<<<<<<<<<< + * cdef NodeHeapData_t popped_element = data_arr[0] + * + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 944; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_data_arr = (&(*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t *) __pyx_v_self->data.data) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":945 + * cdef ITYPE_t i, i_child1, i_child2, i_swap + * cdef NodeHeapData_t* data_arr = &self.data[0] + * cdef NodeHeapData_t popped_element = data_arr[0] # <<<<<<<<<<<<<< + * + * # pop off the first element, move the last element to the front, + */ + __pyx_v_popped_element = (__pyx_v_data_arr[0]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":949 + * # pop off the first element, move the last element to the front, + * # and then perform swaps until the heap is back in order + * data_arr[0] = data_arr[self.n - 1] # <<<<<<<<<<<<<< + * self.n -= 1 + * + */ + (__pyx_v_data_arr[0]) = (__pyx_v_data_arr[(__pyx_v_self->n - 1)]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":950 + * # and then perform swaps until the heap is back in order + * data_arr[0] = data_arr[self.n - 1] + * self.n -= 1 # <<<<<<<<<<<<<< + * + * i = 0 + */ + __pyx_v_self->n = (__pyx_v_self->n - 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":952 + * self.n -= 1 + * + * i = 0 # <<<<<<<<<<<<<< + * + * while (i < self.n): + */ + __pyx_v_i = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":954 + * i = 0 + * + * while (i < self.n): # <<<<<<<<<<<<<< + * i_child1 = 2 * i + 1 + * i_child2 = 2 * i + 2 + */ + while (1) { + __pyx_t_1 = ((__pyx_v_i < __pyx_v_self->n) != 0); + if (!__pyx_t_1) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":955 + * + * while (i < self.n): + * i_child1 = 2 * i + 1 # <<<<<<<<<<<<<< + * i_child2 = 2 * i + 2 + * i_swap = 0 + */ + __pyx_v_i_child1 = ((2 * __pyx_v_i) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":956 + * while (i < self.n): + * i_child1 = 2 * i + 1 + * i_child2 = 2 * i + 2 # <<<<<<<<<<<<<< + * i_swap = 0 + * + */ + __pyx_v_i_child2 = ((2 * __pyx_v_i) + 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":957 + * i_child1 = 2 * i + 1 + * i_child2 = 2 * i + 2 + * i_swap = 0 # <<<<<<<<<<<<<< + * + * if i_child2 < self.n: + */ + __pyx_v_i_swap = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":959 + * i_swap = 0 + * + * if i_child2 < self.n: # <<<<<<<<<<<<<< + * if data_arr[i_child1].val <= data_arr[i_child2].val: + * i_swap = i_child1 + */ + __pyx_t_1 = ((__pyx_v_i_child2 < __pyx_v_self->n) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":960 + * + * if i_child2 < self.n: + * if data_arr[i_child1].val <= data_arr[i_child2].val: # <<<<<<<<<<<<<< + * i_swap = i_child1 + * else: + */ + __pyx_t_1 = (((__pyx_v_data_arr[__pyx_v_i_child1]).val <= (__pyx_v_data_arr[__pyx_v_i_child2]).val) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":961 + * if i_child2 < self.n: + * if data_arr[i_child1].val <= data_arr[i_child2].val: + * i_swap = i_child1 # <<<<<<<<<<<<<< + * else: + * i_swap = i_child2 + */ + __pyx_v_i_swap = __pyx_v_i_child1; + goto __pyx_L7; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":963 + * i_swap = i_child1 + * else: + * i_swap = i_child2 # <<<<<<<<<<<<<< + * elif i_child1 < self.n: + * i_swap = i_child1 + */ + __pyx_v_i_swap = __pyx_v_i_child2; + } + __pyx_L7:; + goto __pyx_L6; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":964 + * else: + * i_swap = i_child2 + * elif i_child1 < self.n: # <<<<<<<<<<<<<< + * i_swap = i_child1 + * else: + */ + __pyx_t_1 = ((__pyx_v_i_child1 < __pyx_v_self->n) != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":965 + * i_swap = i_child2 + * elif i_child1 < self.n: + * i_swap = i_child1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_swap = __pyx_v_i_child1; + goto __pyx_L6; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":967 + * i_swap = i_child1 + * else: + * break # <<<<<<<<<<<<<< + * + * if (i_swap > 0) and (data_arr[i_swap].val <= data_arr[i].val): + */ + goto __pyx_L5_break; + } + __pyx_L6:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":969 + * break + * + * if (i_swap > 0) and (data_arr[i_swap].val <= data_arr[i].val): # <<<<<<<<<<<<<< + * swap_nodes(data_arr, i, i_swap) + * i = i_swap + */ + __pyx_t_1 = ((__pyx_v_i_swap > 0) != 0); + if (__pyx_t_1) { + __pyx_t_4 = (((__pyx_v_data_arr[__pyx_v_i_swap]).val <= (__pyx_v_data_arr[__pyx_v_i]).val) != 0); + __pyx_t_5 = __pyx_t_4; + } else { + __pyx_t_5 = __pyx_t_1; + } + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":970 + * + * if (i_swap > 0) and (data_arr[i_swap].val <= data_arr[i].val): + * swap_nodes(data_arr, i, i_swap) # <<<<<<<<<<<<<< + * i = i_swap + * else: + */ + __pyx_f_7sklearn_9neighbors_7kd_tree_swap_nodes(__pyx_v_data_arr, __pyx_v_i, __pyx_v_i_swap); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":971 + * if (i_swap > 0) and (data_arr[i_swap].val <= data_arr[i].val): + * swap_nodes(data_arr, i, i_swap) + * i = i_swap # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i = __pyx_v_i_swap; + goto __pyx_L8; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":973 + * i = i_swap + * else: + * break # <<<<<<<<<<<<<< + * + * return popped_element + */ + goto __pyx_L5_break; + } + __pyx_L8:; + } + __pyx_L5_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":975 + * break + * + * return popped_element # <<<<<<<<<<<<<< + * + * cdef void clear(self): + */ + __pyx_r = __pyx_v_popped_element; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":938 + * return self.data[0] + * + * cdef NodeHeapData_t pop(self): # <<<<<<<<<<<<<< + * """Remove the root of the heap, and update the remaining nodes""" + * if self.n == 0: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_WriteUnraisable("sklearn.neighbors.kd_tree.NodeHeap.pop", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":977 + * return popped_element + * + * cdef void clear(self): # <<<<<<<<<<<<<< + * """Clear the heap""" + * self.n = 0 + */ + +static void __pyx_f_7sklearn_9neighbors_7kd_tree_8NodeHeap_clear(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("clear", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":979 + * cdef void clear(self): + * """Clear the heap""" + * self.n = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_self->n = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":977 + * return popped_element + * + * cdef void clear(self): # <<<<<<<<<<<<<< + * """Clear the heap""" + * self.n = 0 + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":985 + * # newObj function + * # this is a helper function for pickling + * def newObj(obj): # <<<<<<<<<<<<<< + * return obj.__new__(obj) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_3newObj(PyObject *__pyx_self, PyObject *__pyx_v_obj); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_7kd_tree_3newObj = {__Pyx_NAMESTR("newObj"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_3newObj, METH_O, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_3newObj(PyObject *__pyx_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("newObj (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_2newObj(__pyx_self, ((PyObject *)__pyx_v_obj)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_2newObj(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("newObj", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":986 + * # this is a helper function for pickling + * def newObj(obj): + * return obj.__new__(obj) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_obj, __pyx_n_s_new); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 986; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 986; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 986; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":985 + * # newObj function + * # this is a helper function for pickling + * def newObj(obj): # <<<<<<<<<<<<<< + * return obj.__new__(obj) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.newObj", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1026 + * # Use cinit to initialize all arrays to empty: this will prevent memory + * # errors and seg-faults in rare cases where __init__ is not called + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} + if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree___cinit__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree___cinit__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1027 + * # errors and seg-faults in rare cases where __init__ is not called + * def __cinit__(self): + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__10, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1028 + * def __cinit__(self): + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_tuple__11, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_self->idx_array_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->idx_array_arr)); + __pyx_v_self->idx_array_arr = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1029 + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') # <<<<<<<<<<<<<< + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) + * + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_NodeData); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_tuple__12, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->node_data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->node_data_arr)); + __pyx_v_self->node_data_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1030 + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) # <<<<<<<<<<<<<< + * + * self.data = get_memview_DTYPE_2D(self.data_arr) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__14, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->node_bounds_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + __pyx_v_self->node_bounds_arr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1032 + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) + * + * self.data = get_memview_DTYPE_2D(self.data_arr) # <<<<<<<<<<<<<< + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) + */ + __pyx_t_3 = ((PyObject *)__pyx_v_self->data_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1032; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __pyx_v_self->data = __pyx_t_4; + __pyx_t_4.memview = NULL; + __pyx_t_4.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1033 + * + * self.data = get_memview_DTYPE_2D(self.data_arr) + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) # <<<<<<<<<<<<<< + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) + */ + __pyx_t_3 = ((PyObject *)__pyx_v_self->idx_array_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1033; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->idx_array, 0); + __pyx_v_self->idx_array = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1034 + * self.data = get_memview_DTYPE_2D(self.data_arr) + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) # <<<<<<<<<<<<<< + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) + * + */ + __pyx_t_3 = ((PyObject *)__pyx_v_self->node_data_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_NodeData_1D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1034; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_data, 0); + __pyx_v_self->node_data = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1035 + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) # <<<<<<<<<<<<<< + * + * self.leaf_size = 0 + */ + __pyx_t_3 = ((PyObject *)__pyx_v_self->node_bounds_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_3D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1035; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_bounds, 0); + __pyx_v_self->node_bounds = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1037 + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) + * + * self.leaf_size = 0 # <<<<<<<<<<<<<< + * self.n_levels = 0 + * self.n_nodes = 0 + */ + __pyx_v_self->leaf_size = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1038 + * + * self.leaf_size = 0 + * self.n_levels = 0 # <<<<<<<<<<<<<< + * self.n_nodes = 0 + * + */ + __pyx_v_self->n_levels = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1039 + * self.leaf_size = 0 + * self.n_levels = 0 + * self.n_nodes = 0 # <<<<<<<<<<<<<< + * + * self.euclidean = False + */ + __pyx_v_self->n_nodes = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1041 + * self.n_nodes = 0 + * + * self.euclidean = False # <<<<<<<<<<<<<< + * + * self.n_trims = 0 + */ + __pyx_v_self->euclidean = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1043 + * self.euclidean = False + * + * self.n_trims = 0 # <<<<<<<<<<<<<< + * self.n_leaves = 0 + * self.n_splits = 0 + */ + __pyx_v_self->n_trims = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1044 + * + * self.n_trims = 0 + * self.n_leaves = 0 # <<<<<<<<<<<<<< + * self.n_splits = 0 + * self.n_calls = 0 + */ + __pyx_v_self->n_leaves = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1045 + * self.n_trims = 0 + * self.n_leaves = 0 + * self.n_splits = 0 # <<<<<<<<<<<<<< + * self.n_calls = 0 + * + */ + __pyx_v_self->n_splits = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1046 + * self.n_leaves = 0 + * self.n_splits = 0 + * self.n_calls = 0 # <<<<<<<<<<<<<< + * + * def __init__(self, data, + */ + __pyx_v_self->n_calls = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1026 + * # Use cinit to initialize all arrays to empty: this will prevent memory + * # errors and seg-faults in rare cases where __init__ is not called + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __PYX_XDEC_MEMVIEW(&__pyx_t_4, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1048 + * self.n_calls = 0 + * + * def __init__(self, data, # <<<<<<<<<<<<<< + * leaf_size=40, metric='minkowski', **kwargs): + * self.data_arr = np.asarray(data, dtype=DTYPE, order='C') + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_data = 0; + PyObject *__pyx_v_leaf_size = 0; + PyObject *__pyx_v_metric = 0; + PyObject *__pyx_v_kwargs = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + __pyx_v_kwargs = PyDict_New(); if (unlikely(!__pyx_v_kwargs)) return -1; + __Pyx_GOTREF(__pyx_v_kwargs); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_data,&__pyx_n_s_leaf_size,&__pyx_n_s_metric,0}; + PyObject* values[3] = {0,0,0}; + values[1] = ((PyObject *)__pyx_int_40); + values[2] = ((PyObject *)__pyx_n_s_minkowski); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_data)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_leaf_size); + if (value) { values[1] = value; kw_args--; } + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_metric); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, __pyx_v_kwargs, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1048; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_data = values[0]; + __pyx_v_leaf_size = values[1]; + __pyx_v_metric = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1048; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_DECREF(__pyx_v_kwargs); __pyx_v_kwargs = 0; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_2__init__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self), __pyx_v_data, __pyx_v_leaf_size, __pyx_v_metric, __pyx_v_kwargs); + + /* function exit code */ + __Pyx_XDECREF(__pyx_v_kwargs); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_2__init__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_data, PyObject *__pyx_v_leaf_size, PyObject *__pyx_v_metric, PyObject *__pyx_v_kwargs) { + PyObject *__pyx_v_n_samples = NULL; + Py_ssize_t __pyx_v_n_features; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + double __pyx_t_10; + __Pyx_memviewslice __pyx_t_11 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_12 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_INCREF(__pyx_v_metric); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1050 + * def __init__(self, data, + * leaf_size=40, metric='minkowski', **kwargs): + * self.data_arr = np.asarray(data, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.data = get_memview_DTYPE_2D(self.data_arr) + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_data); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_data); + __Pyx_GIVEREF(__pyx_v_data); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1051 + * leaf_size=40, metric='minkowski', **kwargs): + * self.data_arr = np.asarray(data, dtype=DTYPE, order='C') + * self.data = get_memview_DTYPE_2D(self.data_arr) # <<<<<<<<<<<<<< + * + * self.leaf_size = leaf_size + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->data_arr); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_4)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __pyx_v_self->data = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1053 + * self.data = get_memview_DTYPE_2D(self.data_arr) + * + * self.leaf_size = leaf_size # <<<<<<<<<<<<<< + * self.dist_metric = DistanceMetric.get_metric(metric, **kwargs) + * self.euclidean = (self.dist_metric.__class__.__name__ + */ + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_leaf_size); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1053; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->leaf_size = __pyx_t_6; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1054 + * + * self.leaf_size = leaf_size + * self.dist_metric = DistanceMetric.get_metric(metric, **kwargs) # <<<<<<<<<<<<<< + * self.euclidean = (self.dist_metric.__class__.__name__ + * == 'EuclideanDistance') + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric)), __pyx_n_s_get_metric); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_metric); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_metric); + __Pyx_GIVEREF(__pyx_v_metric); + __pyx_t_1 = __pyx_v_kwargs; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_self->dist_metric); + __Pyx_DECREF(((PyObject *)__pyx_v_self->dist_metric)); + __pyx_v_self->dist_metric = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1055 + * self.leaf_size = leaf_size + * self.dist_metric = DistanceMetric.get_metric(metric, **kwargs) + * self.euclidean = (self.dist_metric.__class__.__name__ # <<<<<<<<<<<<<< + * == 'EuclideanDistance') + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->dist_metric), __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1055; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1055; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_RichCompare(__pyx_t_1, __pyx_n_s_EuclideanDistance, Py_EQ); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1056; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1056 + * self.dist_metric = DistanceMetric.get_metric(metric, **kwargs) + * self.euclidean = (self.dist_metric.__class__.__name__ + * == 'EuclideanDistance') # <<<<<<<<<<<<<< + * + * metric = self.dist_metric.__class__.__name__ + */ + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_2); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1056; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1055 + * self.leaf_size = leaf_size + * self.dist_metric = DistanceMetric.get_metric(metric, **kwargs) + * self.euclidean = (self.dist_metric.__class__.__name__ # <<<<<<<<<<<<<< + * == 'EuclideanDistance') + * + */ + __pyx_v_self->euclidean = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1058 + * == 'EuclideanDistance') + * + * metric = self.dist_metric.__class__.__name__ # <<<<<<<<<<<<<< + * if metric not in VALID_METRICS: + * raise ValueError('metric {metric} is not valid for ' + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->dist_metric), __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1058; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1058; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_metric, __pyx_t_1); + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1059 + * + * metric = self.dist_metric.__class__.__name__ + * if metric not in VALID_METRICS: # <<<<<<<<<<<<<< + * raise ValueError('metric {metric} is not valid for ' + * '{BinaryTree}'.format(metric=metric, + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_VALID_METRICS); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_8 = (__Pyx_PySequence_Contains(__pyx_v_metric, __pyx_t_1, Py_NE)); if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_9 = (__pyx_t_8 != 0); + if (__pyx_t_9) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1061 + * if metric not in VALID_METRICS: + * raise ValueError('metric {metric} is not valid for ' + * '{BinaryTree}'.format(metric=metric, # <<<<<<<<<<<<<< + * **DOC_DICT)) + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_metric_metric_is_not_valid_for_B, __pyx_n_s_format); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1062 + * raise ValueError('metric {metric} is not valid for ' + * '{BinaryTree}'.format(metric=metric, + * **DOC_DICT)) # <<<<<<<<<<<<<< + * + * # validate data + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DOC_DICT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (unlikely(__pyx_t_3 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "argument after ** must be a mapping, not NoneType"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (likely(PyDict_Check(__pyx_t_3))) { + __pyx_t_2 = PyDict_Copy(__pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + } else { + __pyx_t_2 = PyObject_CallFunctionObjArgs((PyObject*)&PyDict_Type, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1061 + * if metric not in VALID_METRICS: + * raise ValueError('metric {metric} is not valid for ' + * '{BinaryTree}'.format(metric=metric, # <<<<<<<<<<<<<< + * **DOC_DICT)) + * + */ + if (unlikely(PyDict_GetItem(__pyx_t_2, __pyx_n_s_metric))) { + __Pyx_RaiseDoubleKeywordsError("function", __pyx_n_s_metric); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_metric, __pyx_v_metric) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_empty_tuple, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1060 + * metric = self.dist_metric.__class__.__name__ + * if metric not in VALID_METRICS: + * raise ValueError('metric {metric} is not valid for ' # <<<<<<<<<<<<<< + * '{BinaryTree}'.format(metric=metric, + * **DOC_DICT)) + */ + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1065 + * + * # validate data + * if self.data.size == 0: # <<<<<<<<<<<<<< + * raise ValueError("X is an empty array") + * + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_self->data, 2, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_size); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_RichCompare(__pyx_t_2, __pyx_int_0, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_9) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1066 + * # validate data + * if self.data.size == 0: + * raise ValueError("X is an empty array") # <<<<<<<<<<<<<< + * + * if leaf_size < 1: + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1066; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1066; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1068 + * raise ValueError("X is an empty array") + * + * if leaf_size < 1: # <<<<<<<<<<<<<< + * raise ValueError("leaf_size must be greater than or equal to 1") + * + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_leaf_size, __pyx_int_1, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1068; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1068; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_9) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1069 + * + * if leaf_size < 1: + * raise ValueError("leaf_size must be greater than or equal to 1") # <<<<<<<<<<<<<< + * + * n_samples = self.data.shape[0] + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1071 + * raise ValueError("leaf_size must be greater than or equal to 1") + * + * n_samples = self.data.shape[0] # <<<<<<<<<<<<<< + * n_features = self.data.shape[1] + * + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1071; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_self->data.shape[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1071; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_n_samples = __pyx_t_3; + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1072 + * + * n_samples = self.data.shape[0] + * n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * + * # determine number of levels in the tree, and from this + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1072; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1077 + * # the number of nodes in the tree. This results in leaf nodes + * # with numbers of points betweeen leaf_size and 2 * leaf_size + * self.n_levels = np.log2(fmax(1, (n_samples - 1) / self.leaf_size)) + 1 # <<<<<<<<<<<<<< + * self.n_nodes = (2 ** self.n_levels) - 1 + * + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_log2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_v_n_samples, __pyx_int_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->leaf_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyNumber_Divide(__pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_10 = __pyx_PyFloat_AsDouble(__pyx_t_4); if (unlikely((__pyx_t_10 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyFloat_FromDouble(__pyx_f_7sklearn_9neighbors_7kd_tree_fmax(1.0, __pyx_t_10)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_1, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Add(__pyx_t_4, __pyx_int_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_levels = __pyx_t_6; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1078 + * # with numbers of points betweeen leaf_size and 2 * leaf_size + * self.n_levels = np.log2(fmax(1, (n_samples - 1) / self.leaf_size)) + 1 + * self.n_nodes = (2 ** self.n_levels) - 1 # <<<<<<<<<<<<<< + * + * # allocate arrays for storage + */ + __pyx_v_self->n_nodes = (__Pyx_pow_long(2, ((long)__pyx_v_self->n_levels)) - 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1081 + * + * # allocate arrays for storage + * self.idx_array_arr = np.arange(n_samples, dtype=ITYPE) # <<<<<<<<<<<<<< + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_arange); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_n_samples); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_n_samples); + __Pyx_GIVEREF(__pyx_v_n_samples); + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->idx_array_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->idx_array_arr)); + __pyx_v_self->idx_array_arr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1082 + * # allocate arrays for storage + * self.idx_array_arr = np.arange(n_samples, dtype=ITYPE) + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) # <<<<<<<<<<<<<< + * + * self.node_data_arr = np.zeros(self.n_nodes, dtype=NodeData) + */ + __pyx_t_3 = ((PyObject *)__pyx_v_self->idx_array_arr); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_11 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_t_3)); if (unlikely(!__pyx_t_11.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1082; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->idx_array, 0); + __pyx_v_self->idx_array = __pyx_t_11; + __pyx_t_11.memview = NULL; + __pyx_t_11.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1084 + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * + * self.node_data_arr = np.zeros(self.n_nodes, dtype=NodeData) # <<<<<<<<<<<<<< + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) + * + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_nodes); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_NodeData); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->node_data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->node_data_arr)); + __pyx_v_self->node_data_arr = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1085 + * + * self.node_data_arr = np.zeros(self.n_nodes, dtype=NodeData) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) # <<<<<<<<<<<<<< + * + * # Allocate tree-specific data + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->node_data_arr); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_NodeData_1D(((PyArrayObject *)__pyx_t_4)); if (unlikely(!__pyx_t_12.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_data, 0); + __pyx_v_self->node_data = __pyx_t_12; + __pyx_t_12.memview = NULL; + __pyx_t_12.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1088 + * + * # Allocate tree-specific data + * allocate_data(self, self.n_nodes, n_features) # <<<<<<<<<<<<<< + * self._recursive_build(0, 0, n_samples) + * + */ + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_7kd_tree_allocate_data(__pyx_v_self, __pyx_v_self->n_nodes, __pyx_v_n_features); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1088; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1089 + * # Allocate tree-specific data + * allocate_data(self, self.n_nodes, n_features) + * self._recursive_build(0, 0, n_samples) # <<<<<<<<<<<<<< + * + * def __reduce__(self): + */ + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_n_samples); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1089; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_recursive_build(__pyx_v_self, 0, 0, __pyx_t_6); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1089; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1048 + * self.n_calls = 0 + * + * def __init__(self, data, # <<<<<<<<<<<<<< + * leaf_size=40, metric='minkowski', **kwargs): + * self.data_arr = np.asarray(data, dtype=DTYPE, order='C') + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_11, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_n_samples); + __Pyx_XDECREF(__pyx_v_metric); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1091 + * self._recursive_build(0, 0, n_samples) + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * """ + * reduce method used for pickling + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_4__reduce__[] = "\n reduce method used for pickling\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_4__reduce__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_4__reduce__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce__", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1095 + * reduce method used for pickling + * """ + * return (newObj, (BinaryTree,), self.__getstate__()) # <<<<<<<<<<<<<< + * + * def __getstate__(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_newObj); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1095; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1095; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree))); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree))); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_getstate); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1095; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1095; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1095; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_4 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1091 + * self._recursive_build(0, 0, n_samples) + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * """ + * reduce method used for pickling + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1097 + * return (newObj, (BinaryTree,), self.__getstate__()) + * + * def __getstate__(self): # <<<<<<<<<<<<<< + * """ + * get state for pickling + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_6__getstate__[] = "\n get state for pickling\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_6__getstate__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_6__getstate__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getstate__", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1101 + * get state for pickling + * """ + * return (self.data_arr, # <<<<<<<<<<<<<< + * self.idx_array_arr, + * self.node_data_arr, + */ + __Pyx_XDECREF(__pyx_r); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1105 + * self.node_data_arr, + * self.node_bounds_arr, + * int(self.leaf_size), # <<<<<<<<<<<<<< + * int(self.n_levels), + * int(self.n_nodes), + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->leaf_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1106 + * self.node_bounds_arr, + * int(self.leaf_size), + * int(self.n_levels), # <<<<<<<<<<<<<< + * int(self.n_nodes), + * int(self.n_trims), + */ + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_levels); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1107 + * int(self.leaf_size), + * int(self.n_levels), + * int(self.n_nodes), # <<<<<<<<<<<<<< + * int(self.n_trims), + * int(self.n_leaves), + */ + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_nodes); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1108 + * int(self.n_levels), + * int(self.n_nodes), + * int(self.n_trims), # <<<<<<<<<<<<<< + * int(self.n_leaves), + * int(self.n_splits), + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_self->n_trims); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1109 + * int(self.n_nodes), + * int(self.n_trims), + * int(self.n_leaves), # <<<<<<<<<<<<<< + * int(self.n_splits), + * int(self.n_calls), + */ + __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_self->n_leaves); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1110 + * int(self.n_trims), + * int(self.n_leaves), + * int(self.n_splits), # <<<<<<<<<<<<<< + * int(self.n_calls), + * self.dist_metric) + */ + __pyx_t_6 = __Pyx_PyInt_From_int(__pyx_v_self->n_splits); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1111 + * int(self.n_leaves), + * int(self.n_splits), + * int(self.n_calls), # <<<<<<<<<<<<<< + * self.dist_metric) + * + */ + __pyx_t_7 = __Pyx_PyInt_From_int(__pyx_v_self->n_calls); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1101 + * get state for pickling + * """ + * return (self.data_arr, # <<<<<<<<<<<<<< + * self.idx_array_arr, + * self.node_data_arr, + */ + __pyx_t_8 = PyTuple_New(12); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(((PyObject *)__pyx_v_self->data_arr)); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_v_self->data_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->data_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->idx_array_arr)); + PyTuple_SET_ITEM(__pyx_t_8, 1, ((PyObject *)__pyx_v_self->idx_array_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->idx_array_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->node_data_arr)); + PyTuple_SET_ITEM(__pyx_t_8, 2, ((PyObject *)__pyx_v_self->node_data_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->node_data_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + PyTuple_SET_ITEM(__pyx_t_8, 3, ((PyObject *)__pyx_v_self->node_bounds_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + PyTuple_SET_ITEM(__pyx_t_8, 4, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_8, 5, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_8, 6, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_8, 7, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_8, 8, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_8, 9, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 10, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __Pyx_INCREF(((PyObject *)__pyx_v_self->dist_metric)); + PyTuple_SET_ITEM(__pyx_t_8, 11, ((PyObject *)__pyx_v_self->dist_metric)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->dist_metric)); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_r = __pyx_t_8; + __pyx_t_8 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1097 + * return (newObj, (BinaryTree,), self.__getstate__()) + * + * def __getstate__(self): # <<<<<<<<<<<<<< + * """ + * get state for pickling + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1114 + * self.dist_metric) + * + * def __setstate__(self, state): # <<<<<<<<<<<<<< + * """ + * set state for pickling + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_state); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_8__setstate__[] = "\n set state for pickling\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_state) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_8__setstate__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self), ((PyObject *)__pyx_v_state)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_8__setstate__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __Pyx_memviewslice __pyx_t_2 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_3 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate__", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1118 + * set state for pickling + * """ + * self.data_arr = state[0] # <<<<<<<<<<<<<< + * self.idx_array_arr = state[1] + * self.node_data_arr = state[2] + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1118; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->data_arr)); + __pyx_v_self->data_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1119 + * """ + * self.data_arr = state[0] + * self.idx_array_arr = state[1] # <<<<<<<<<<<<<< + * self.node_data_arr = state[2] + * self.node_bounds_arr = state[3] + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1119; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->idx_array_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->idx_array_arr)); + __pyx_v_self->idx_array_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1120 + * self.data_arr = state[0] + * self.idx_array_arr = state[1] + * self.node_data_arr = state[2] # <<<<<<<<<<<<<< + * self.node_bounds_arr = state[3] + * + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 2, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1120; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->node_data_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->node_data_arr)); + __pyx_v_self->node_data_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1121 + * self.idx_array_arr = state[1] + * self.node_data_arr = state[2] + * self.node_bounds_arr = state[3] # <<<<<<<<<<<<<< + * + * self.data = get_memview_DTYPE_2D(self.data_arr) + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 3, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1121; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->node_bounds_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + __pyx_v_self->node_bounds_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1123 + * self.node_bounds_arr = state[3] + * + * self.data = get_memview_DTYPE_2D(self.data_arr) # <<<<<<<<<<<<<< + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) + */ + __pyx_t_1 = ((PyObject *)__pyx_v_self->data_arr); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_1)); if (unlikely(!__pyx_t_2.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->data, 0); + __pyx_v_self->data = __pyx_t_2; + __pyx_t_2.memview = NULL; + __pyx_t_2.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1124 + * + * self.data = get_memview_DTYPE_2D(self.data_arr) + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) # <<<<<<<<<<<<<< + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) + */ + __pyx_t_1 = ((PyObject *)__pyx_v_self->idx_array_arr); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_3 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_t_1)); if (unlikely(!__pyx_t_3.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->idx_array, 0); + __pyx_v_self->idx_array = __pyx_t_3; + __pyx_t_3.memview = NULL; + __pyx_t_3.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1125 + * self.data = get_memview_DTYPE_2D(self.data_arr) + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) # <<<<<<<<<<<<<< + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) + * + */ + __pyx_t_1 = ((PyObject *)__pyx_v_self->node_data_arr); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_NodeData_1D(((PyArrayObject *)__pyx_t_1)); if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_data, 0); + __pyx_v_self->node_data = __pyx_t_4; + __pyx_t_4.memview = NULL; + __pyx_t_4.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1126 + * self.idx_array = get_memview_ITYPE_1D(self.idx_array_arr) + * self.node_data = get_memview_NodeData_1D(self.node_data_arr) + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) # <<<<<<<<<<<<<< + * + * self.leaf_size = state[4] + */ + __pyx_t_1 = ((PyObject *)__pyx_v_self->node_bounds_arr); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_3D(((PyArrayObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_bounds, 0); + __pyx_v_self->node_bounds = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1128 + * self.node_bounds = get_memview_DTYPE_3D(self.node_bounds_arr) + * + * self.leaf_size = state[4] # <<<<<<<<<<<<<< + * self.n_levels = state[5] + * self.n_nodes = state[6] + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 4, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1128; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->leaf_size = __pyx_t_6; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1129 + * + * self.leaf_size = state[4] + * self.n_levels = state[5] # <<<<<<<<<<<<<< + * self.n_nodes = state[6] + * self.n_trims = state[7] + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 5, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1129; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_levels = __pyx_t_6; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1130 + * self.leaf_size = state[4] + * self.n_levels = state[5] + * self.n_nodes = state[6] # <<<<<<<<<<<<<< + * self.n_trims = state[7] + * self.n_leaves = state[8] + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 6, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1130; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_nodes = __pyx_t_6; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1131 + * self.n_levels = state[5] + * self.n_nodes = state[6] + * self.n_trims = state[7] # <<<<<<<<<<<<<< + * self.n_leaves = state[8] + * self.n_splits = state[9] + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 7, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1131; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_trims = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1132 + * self.n_nodes = state[6] + * self.n_trims = state[7] + * self.n_leaves = state[8] # <<<<<<<<<<<<<< + * self.n_splits = state[9] + * self.n_calls = state[10] + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 8, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1132; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_leaves = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1133 + * self.n_trims = state[7] + * self.n_leaves = state[8] + * self.n_splits = state[9] # <<<<<<<<<<<<<< + * self.n_calls = state[10] + * self.dist_metric = state[11] + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 9, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1133; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_splits = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1134 + * self.n_leaves = state[8] + * self.n_splits = state[9] + * self.n_calls = state[10] # <<<<<<<<<<<<<< + * self.dist_metric = state[11] + * self.euclidean = (self.dist_metric.__class__.__name__ + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 10, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1134; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->n_calls = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1135 + * self.n_splits = state[9] + * self.n_calls = state[10] + * self.dist_metric = state[11] # <<<<<<<<<<<<<< + * self.euclidean = (self.dist_metric.__class__.__name__ + * == 'EuclideanDistance') + */ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 11, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1135; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->dist_metric); + __Pyx_DECREF(((PyObject *)__pyx_v_self->dist_metric)); + __pyx_v_self->dist_metric = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1136 + * self.n_calls = state[10] + * self.dist_metric = state[11] + * self.euclidean = (self.dist_metric.__class__.__name__ # <<<<<<<<<<<<<< + * == 'EuclideanDistance') + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->dist_metric), __pyx_n_s_class); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_name); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_RichCompare(__pyx_t_8, __pyx_n_s_EuclideanDistance, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1137; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1137 + * self.dist_metric = state[11] + * self.euclidean = (self.dist_metric.__class__.__name__ + * == 'EuclideanDistance') # <<<<<<<<<<<<<< + * + * def get_tree_stats(self): + */ + __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1137; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1136 + * self.n_calls = state[10] + * self.dist_metric = state[11] + * self.euclidean = (self.dist_metric.__class__.__name__ # <<<<<<<<<<<<<< + * == 'EuclideanDistance') + * + */ + __pyx_v_self->euclidean = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1114 + * self.dist_metric) + * + * def __setstate__(self, state): # <<<<<<<<<<<<<< + * """ + * set state for pickling + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __PYX_XDEC_MEMVIEW(&__pyx_t_2, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_3, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_4, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.__setstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1139 + * == 'EuclideanDistance') + * + * def get_tree_stats(self): # <<<<<<<<<<<<<< + * return (self.n_trims, self.n_leaves, self.n_splits) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_11get_tree_stats(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_11get_tree_stats(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_tree_stats (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_10get_tree_stats(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_10get_tree_stats(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_tree_stats", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1140 + * + * def get_tree_stats(self): + * return (self.n_trims, self.n_leaves, self.n_splits) # <<<<<<<<<<<<<< + * + * def reset_n_calls(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->n_trims); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->n_leaves); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_self->n_splits); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1139 + * == 'EuclideanDistance') + * + * def get_tree_stats(self): # <<<<<<<<<<<<<< + * return (self.n_trims, self.n_leaves, self.n_splits) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.get_tree_stats", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1142 + * return (self.n_trims, self.n_leaves, self.n_splits) + * + * def reset_n_calls(self): # <<<<<<<<<<<<<< + * self.n_calls = 0 + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_13reset_n_calls(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_13reset_n_calls(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("reset_n_calls (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_12reset_n_calls(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_12reset_n_calls(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("reset_n_calls", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1143 + * + * def reset_n_calls(self): + * self.n_calls = 0 # <<<<<<<<<<<<<< + * + * def get_n_calls(self): + */ + __pyx_v_self->n_calls = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1142 + * return (self.n_trims, self.n_leaves, self.n_splits) + * + * def reset_n_calls(self): # <<<<<<<<<<<<<< + * self.n_calls = 0 + * + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1145 + * self.n_calls = 0 + * + * def get_n_calls(self): # <<<<<<<<<<<<<< + * return self.n_calls + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_15get_n_calls(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_15get_n_calls(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_n_calls (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_14get_n_calls(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_14get_n_calls(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_n_calls", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1146 + * + * def get_n_calls(self): + * return self.n_calls # <<<<<<<<<<<<<< + * + * def get_arrays(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->n_calls); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1145 + * self.n_calls = 0 + * + * def get_n_calls(self): # <<<<<<<<<<<<<< + * return self.n_calls + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.get_n_calls", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1148 + * return self.n_calls + * + * def get_arrays(self): # <<<<<<<<<<<<<< + * return (self.data_arr, self.idx_array_arr, + * self.node_data_arr, self.node_bounds_arr) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_17get_arrays(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_17get_arrays(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_arrays (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_16get_arrays(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_16get_arrays(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_arrays", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1149 + * + * def get_arrays(self): + * return (self.data_arr, self.idx_array_arr, # <<<<<<<<<<<<<< + * self.node_data_arr, self.node_bounds_arr) + * + */ + __Pyx_XDECREF(__pyx_r); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1150 + * def get_arrays(self): + * return (self.data_arr, self.idx_array_arr, + * self.node_data_arr, self.node_bounds_arr) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_t_1 = PyTuple_New(4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_self->data_arr)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_self->data_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->data_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->idx_array_arr)); + PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_self->idx_array_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->idx_array_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->node_data_arr)); + PyTuple_SET_ITEM(__pyx_t_1, 2, ((PyObject *)__pyx_v_self->node_data_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->node_data_arr)); + __Pyx_INCREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + PyTuple_SET_ITEM(__pyx_t_1, 3, ((PyObject *)__pyx_v_self->node_bounds_arr)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->node_bounds_arr)); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1148 + * return self.n_calls + * + * def get_arrays(self): # <<<<<<<<<<<<<< + * return (self.data_arr, self.idx_array_arr, + * self.node_data_arr, self.node_bounds_arr) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.get_arrays", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1152 + * self.node_data_arr, self.node_bounds_arr) + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """Compute the distance between arrays x1 and x2""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_dist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("dist", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1155 + * ITYPE_t size) except -1: + * """Compute the distance between arrays x1 and x2""" + * self.n_calls += 1 # <<<<<<<<<<<<<< + * if self.euclidean: + * return euclidean_dist(x1, x2, size) + */ + __pyx_v_self->n_calls = (__pyx_v_self->n_calls + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1156 + * """Compute the distance between arrays x1 and x2""" + * self.n_calls += 1 + * if self.euclidean: # <<<<<<<<<<<<<< + * return euclidean_dist(x1, x2, size) + * else: + */ + __pyx_t_1 = (__pyx_v_self->euclidean != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1157 + * self.n_calls += 1 + * if self.euclidean: + * return euclidean_dist(x1, x2, size) # <<<<<<<<<<<<<< + * else: + * return self.dist_metric.dist(x1, x2, size) + */ + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist(__pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1159 + * return euclidean_dist(x1, x2, size) + * else: + * return self.dist_metric.dist(x1, x2, size) # <<<<<<<<<<<<<< + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->dist_metric->__pyx_vtab)->dist(__pyx_v_self->dist_metric, __pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1152 + * self.node_data_arr, self.node_bounds_arr) + * + * cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """Compute the distance between arrays x1 and x2""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1161 + * return self.dist_metric.dist(x1, x2, size) + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """Compute the reduced distance between arrays x1 and x2. + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_rdist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("rdist", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1170 + * distance for the Euclidean metric is the squared-euclidean distance. + * """ + * self.n_calls += 1 # <<<<<<<<<<<<<< + * if self.euclidean: + * return euclidean_rdist(x1, x2, size) + */ + __pyx_v_self->n_calls = (__pyx_v_self->n_calls + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1171 + * """ + * self.n_calls += 1 + * if self.euclidean: # <<<<<<<<<<<<<< + * return euclidean_rdist(x1, x2, size) + * else: + */ + __pyx_t_1 = (__pyx_v_self->euclidean != 0); + if (__pyx_t_1) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1172 + * self.n_calls += 1 + * if self.euclidean: + * return euclidean_rdist(x1, x2, size) # <<<<<<<<<<<<<< + * else: + * return self.dist_metric.rdist(x1, x2, size) + */ + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist(__pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1174 + * return euclidean_rdist(x1, x2, size) + * else: + * return self.dist_metric.rdist(x1, x2, size) # <<<<<<<<<<<<<< + * + * cdef int _recursive_build(self, ITYPE_t i_node, ITYPE_t idx_start, + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->dist_metric->__pyx_vtab)->rdist(__pyx_v_self->dist_metric, __pyx_v_x1, __pyx_v_x2, __pyx_v_size); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1161 + * return self.dist_metric.dist(x1, x2, size) + * + * cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * """Compute the reduced distance between arrays x1 and x2. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1176 + * return self.dist_metric.rdist(x1, x2, size) + * + * cdef int _recursive_build(self, ITYPE_t i_node, ITYPE_t idx_start, # <<<<<<<<<<<<<< + * ITYPE_t idx_end) except -1: + * """Recursively build the tree. + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__recursive_build(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_idx_start, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_idx_end) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_points; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_mid; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + PyObject *__pyx_v_warnings = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_max; + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_recursive_build", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1189 + * """ + * cdef ITYPE_t imax + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_points = idx_end - idx_start + * cdef ITYPE_t n_mid = n_points / 2 + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1189; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1190 + * cdef ITYPE_t imax + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef ITYPE_t n_points = idx_end - idx_start # <<<<<<<<<<<<<< + * cdef ITYPE_t n_mid = n_points / 2 + * cdef ITYPE_t* idx_array = &self.idx_array[idx_start] + */ + __pyx_v_n_points = (__pyx_v_idx_end - __pyx_v_idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1191 + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef ITYPE_t n_points = idx_end - idx_start + * cdef ITYPE_t n_mid = n_points / 2 # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array = &self.idx_array[idx_start] + * cdef DTYPE_t* data = &self.data[0, 0] + */ + __pyx_v_n_mid = (__pyx_v_n_points / 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1192 + * cdef ITYPE_t n_points = idx_end - idx_start + * cdef ITYPE_t n_mid = n_points / 2 + * cdef ITYPE_t* idx_array = &self.idx_array[idx_start] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data = &self.data[0, 0] + * + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1192; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_v_idx_start; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_1)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1193 + * cdef ITYPE_t n_mid = n_points / 2 + * cdef ITYPE_t* idx_array = &self.idx_array[idx_start] + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * + * # initialize node data + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1193; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_2 * __pyx_v_self->data.strides[0]) )) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1196 + * + * # initialize node data + * init_node(self, i_node, idx_start, idx_end) # <<<<<<<<<<<<<< + * + * if 2 * i_node + 1 >= self.n_nodes: + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_init_node(__pyx_v_self, __pyx_v_i_node, __pyx_v_idx_start, __pyx_v_idx_end); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1196; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1198 + * init_node(self, i_node, idx_start, idx_end) + * + * if 2 * i_node + 1 >= self.n_nodes: # <<<<<<<<<<<<<< + * self.node_data[i_node].is_leaf = True + * if idx_end - idx_start > 2 * self.leaf_size: + */ + __pyx_t_5 = ((((2 * __pyx_v_i_node) + 1) >= __pyx_v_self->n_nodes) != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1199 + * + * if 2 * i_node + 1 >= self.n_nodes: + * self.node_data[i_node].is_leaf = True # <<<<<<<<<<<<<< + * if idx_end - idx_start > 2 * self.leaf_size: + * # this shouldn't happen if our memory allocation is correct + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1199; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_6 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_6)) ))).is_leaf = 1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1200 + * if 2 * i_node + 1 >= self.n_nodes: + * self.node_data[i_node].is_leaf = True + * if idx_end - idx_start > 2 * self.leaf_size: # <<<<<<<<<<<<<< + * # this shouldn't happen if our memory allocation is correct + * # we'll proactively prevent memory errors, but raise a + */ + __pyx_t_5 = (((__pyx_v_idx_end - __pyx_v_idx_start) > (2 * __pyx_v_self->leaf_size)) != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1204 + * # we'll proactively prevent memory errors, but raise a + * # warning saying we're doing so. + * import warnings # <<<<<<<<<<<<<< + * warnings.warn("Internal: memory layout is flawed: " + * "not enough nodes allocated") + */ + __pyx_t_7 = __Pyx_Import(__pyx_n_s_warnings, 0, -1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_v_warnings = __pyx_t_7; + __pyx_t_7 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1205 + * # warning saying we're doing so. + * import warnings + * warnings.warn("Internal: memory layout is flawed: " # <<<<<<<<<<<<<< + * "not enough nodes allocated") + * + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_warnings, __pyx_n_s_warn); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L4; + } + __pyx_L4:; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1208 + * "not enough nodes allocated") + * + * elif idx_end - idx_start < 2: # <<<<<<<<<<<<<< + * # again, this shouldn't happen if our memory allocation + * # is correct. Raise a warning. + */ + __pyx_t_5 = (((__pyx_v_idx_end - __pyx_v_idx_start) < 2) != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1211 + * # again, this shouldn't happen if our memory allocation + * # is correct. Raise a warning. + * import warnings # <<<<<<<<<<<<<< + * warnings.warn("Internal: memory layout is flawed: " + * "too many nodes allocated") + */ + __pyx_t_8 = __Pyx_Import(__pyx_n_s_warnings, 0, -1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_v_warnings = __pyx_t_8; + __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1212 + * # is correct. Raise a warning. + * import warnings + * warnings.warn("Internal: memory layout is flawed: " # <<<<<<<<<<<<<< + * "too many nodes allocated") + * self.node_data[i_node].is_leaf = True + */ + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_warnings, __pyx_n_s_warn); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1214 + * warnings.warn("Internal: memory layout is flawed: " + * "too many nodes allocated") + * self.node_data[i_node].is_leaf = True # <<<<<<<<<<<<<< + * + * else: + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1214; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_9)) ))).is_leaf = 1; + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1218 + * else: + * # split node and recursively construct child nodes. + * self.node_data[i_node].is_leaf = False # <<<<<<<<<<<<<< + * i_max = find_node_split_dim(data, idx_array, + * n_features, n_points) + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_10)) ))).is_leaf = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1219 + * # split node and recursively construct child nodes. + * self.node_data[i_node].is_leaf = False + * i_max = find_node_split_dim(data, idx_array, # <<<<<<<<<<<<<< + * n_features, n_points) + * partition_node_indices(data, idx_array, i_max, n_mid, + */ + __pyx_t_11 = __pyx_f_7sklearn_9neighbors_7kd_tree_find_node_split_dim(__pyx_v_data, __pyx_v_idx_array, __pyx_v_n_features, __pyx_v_n_points); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_i_max = __pyx_t_11; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1221 + * i_max = find_node_split_dim(data, idx_array, + * n_features, n_points) + * partition_node_indices(data, idx_array, i_max, n_mid, # <<<<<<<<<<<<<< + * n_features, n_points) + * self._recursive_build(2 * i_node + 1, + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_partition_node_indices(__pyx_v_data, __pyx_v_idx_array, __pyx_v_i_max, __pyx_v_n_mid, __pyx_v_n_features, __pyx_v_n_points); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1223 + * partition_node_indices(data, idx_array, i_max, n_mid, + * n_features, n_points) + * self._recursive_build(2 * i_node + 1, # <<<<<<<<<<<<<< + * idx_start, idx_start + n_mid) + * self._recursive_build(2 * i_node + 2, + */ + __pyx_t_4 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_recursive_build(__pyx_v_self, ((2 * __pyx_v_i_node) + 1), __pyx_v_idx_start, (__pyx_v_idx_start + __pyx_v_n_mid)); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1225 + * self._recursive_build(2 * i_node + 1, + * idx_start, idx_start + n_mid) + * self._recursive_build(2 * i_node + 2, # <<<<<<<<<<<<<< + * idx_start + n_mid, idx_end) + * + */ + __pyx_t_4 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_recursive_build(__pyx_v_self, ((2 * __pyx_v_i_node) + 2), (__pyx_v_idx_start + __pyx_v_n_mid), __pyx_v_idx_end); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1176 + * return self.dist_metric.rdist(x1, x2, size) + * + * cdef int _recursive_build(self, ITYPE_t i_node, ITYPE_t idx_start, # <<<<<<<<<<<<<< + * ITYPE_t idx_end) except -1: + * """Recursively build the tree. + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree._recursive_build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_warnings); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1228 + * idx_start + n_mid, idx_end) + * + * def query(self, X, k=1, return_distance=True, # <<<<<<<<<<<<<< + * dualtree=False, breadth_first=False, + * sort_results=True): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_19query(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_18query[] = "\n query(X, k=1, return_distance=True,\n dualtree=False, breadth_first=False)\n\n query the tree for the k nearest neighbors\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n k : integer (default = 1)\n The number of nearest neighbors to return\n return_distance : boolean (default = True)\n if True, return a tuple (d, i) of distances and indices\n if False, return array i\n dualtree : boolean (default = False)\n if True, use the dual tree formalism for the query: a tree is\n built for the query points, and the pair of trees is used to\n efficiently search this space. This can lead to better\n performance as the number of points grows large.\n breadth_first : boolean (default = False)\n if True, then query the nodes in a breadth-first manner.\n Otherwise, query the nodes in a depth-first manner.\n sort_results : boolean (default = True)\n if True, then distances and indices of each point are sorted\n on return, so that the first column contains the closest points.\n Otherwise, neighbors are returned in an arbitrary order.\n\n Returns\n -------\n i : if return_distance == False\n (d,i) : if return_distance == True\n\n d : array of doubles - shape: x.shape[:-1] + (k,)\n each entry gives the list of distances to the\n neighbors of the corresponding point\n\n i : array of integers - shape: x.shape[:-1] + (k,)\n each entry gives the list of indices of\n neighbors of the corresponding point\n\n Examples\n --------\n Query for k-nearest neighbors\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimension""s\n >>> tree = BinaryTree(X, leaf_size=2) # doctest: +SKIP\n >>> dist, ind = tree.query(X[0], k=3) # doctest: +SKIP\n >>> print ind # indices of 3 closest neighbors\n [0 3 1]\n >>> print dist # distances to 3 closest neighbors\n [ 0. 0.19662693 0.29473397]\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_19query(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_X = 0; + PyObject *__pyx_v_k = 0; + PyObject *__pyx_v_return_distance = 0; + PyObject *__pyx_v_dualtree = 0; + PyObject *__pyx_v_breadth_first = 0; + PyObject *__pyx_v_sort_results = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("query (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_k,&__pyx_n_s_return_distance,&__pyx_n_s_dualtree,&__pyx_n_s_breadth_first,&__pyx_n_s_sort_results,0}; + PyObject* values[6] = {0,0,0,0,0,0}; + values[1] = ((PyObject *)__pyx_int_1); + values[2] = ((PyObject *)Py_True); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1229 + * + * def query(self, X, k=1, return_distance=True, + * dualtree=False, breadth_first=False, # <<<<<<<<<<<<<< + * sort_results=True): + * """ + */ + values[3] = ((PyObject *)Py_False); + values[4] = ((PyObject *)Py_False); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1230 + * def query(self, X, k=1, return_distance=True, + * dualtree=False, breadth_first=False, + * sort_results=True): # <<<<<<<<<<<<<< + * """ + * query(X, k=1, return_distance=True, + */ + values[5] = ((PyObject *)Py_True); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_k); + if (value) { values[1] = value; kw_args--; } + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_return_distance); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dualtree); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_breadth_first); + if (value) { values[4] = value; kw_args--; } + } + case 5: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sort_results); + if (value) { values[5] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "query") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1228; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_X = values[0]; + __pyx_v_k = values[1]; + __pyx_v_return_distance = values[2]; + __pyx_v_dualtree = values[3]; + __pyx_v_breadth_first = values[4]; + __pyx_v_sort_results = values[5]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("query", 0, 1, 6, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1228; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.query", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_18query(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self), __pyx_v_X, __pyx_v_k, __pyx_v_return_distance, __pyx_v_dualtree, __pyx_v_breadth_first, __pyx_v_sort_results); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1228 + * idx_start + n_mid, idx_end) + * + * def query(self, X, k=1, return_distance=True, # <<<<<<<<<<<<<< + * dualtree=False, breadth_first=False, + * sort_results=True): + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_18query(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_k, PyObject *__pyx_v_return_distance, PyObject *__pyx_v_dualtree, PyObject *__pyx_v_breadth_first, PyObject *__pyx_v_sort_results) { + PyObject *__pyx_v_np_Xarr = NULL; + __Pyx_memviewslice __pyx_v_Xarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt; + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_heap = 0; + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_nodeheap = 0; + __Pyx_memviewslice __pyx_v_bounds = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_other = NULL; + PyObject *__pyx_v_distances = NULL; + PyObject *__pyx_v_indices = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_8; + __Pyx_memviewslice __pyx_t_9 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + PyObject *(*__pyx_t_14)(PyObject *); + PyObject *__pyx_t_15 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("query", 0); + __Pyx_INCREF(__pyx_v_X); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1287 + * """ + * # XXX: we should allow X to be a pre-built tree. + * X = check_array(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_check_array); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1289 + * X = check_array(X, dtype=DTYPE, order='C') + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: # <<<<<<<<<<<<<< + * raise ValueError("query data dimension must " + * "match training data dimension") + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyNumber_Subtract(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_GetItem(__pyx_t_4, __pyx_t_2); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_t_2, Py_NE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1290 + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1293 + * "match training data dimension") + * + * if self.data.shape[0] < k: # <<<<<<<<<<<<<< + * raise ValueError("k must be less than or equal " + * "to the number of training points") + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1293; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->data.shape[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1293; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = PyObject_RichCompare(__pyx_t_4, __pyx_v_k, Py_LT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1293; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1293; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1294 + * + * if self.data.shape[0] < k: + * raise ValueError("k must be less than or equal " # <<<<<<<<<<<<<< + * "to the number of training points") + * + */ + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1298 + * + * # flatten X, and save original shape information + * np_Xarr = X.reshape((-1, self.data.shape[1])) # <<<<<<<<<<<<<< + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(np_Xarr) + * cdef DTYPE_t reduced_dist_LB + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_reshape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_np_Xarr = __pyx_t_3; + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1299 + * # flatten X, and save original shape information + * np_Xarr = X.reshape((-1, self.data.shape[1])) + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(np_Xarr) # <<<<<<<<<<<<<< + * cdef DTYPE_t reduced_dist_LB + * cdef ITYPE_t i + */ + if (!(likely(((__pyx_v_np_Xarr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_np_Xarr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_v_np_Xarr)); if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_Xarr = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1305 + * + * # initialize heap for neighbors + * cdef NeighborsHeap heap = NeighborsHeap(Xarr.shape[0], k) # <<<<<<<<<<<<<< + * + * # node heap for breadth-first queries + */ + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_Xarr.shape[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_k); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_v_k); + __Pyx_GIVEREF(__pyx_v_k); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_7kd_tree_NeighborsHeap)), __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_heap = ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1309 + * # node heap for breadth-first queries + * cdef NodeHeap nodeheap + * if breadth_first: # <<<<<<<<<<<<<< + * nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) + * + */ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_breadth_first); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1309; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1310 + * cdef NodeHeap nodeheap + * if breadth_first: + * nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) # <<<<<<<<<<<<<< + * + * # bounds is needed for the dual tree algorithm + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1310; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = PyInt_FromSsize_t(((__pyx_v_self->data.shape[0]) / __pyx_v_self->leaf_size)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_7kd_tree_NodeHeap)), __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_nodeheap = ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L5; + } + __pyx_L5:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1315 + * cdef DTYPE_t[::1] bounds + * + * self.n_trims = 0 # <<<<<<<<<<<<<< + * self.n_leaves = 0 + * self.n_splits = 0 + */ + __pyx_v_self->n_trims = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1316 + * + * self.n_trims = 0 + * self.n_leaves = 0 # <<<<<<<<<<<<<< + * self.n_splits = 0 + * + */ + __pyx_v_self->n_leaves = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1317 + * self.n_trims = 0 + * self.n_leaves = 0 + * self.n_splits = 0 # <<<<<<<<<<<<<< + * + * if dualtree: + */ + __pyx_v_self->n_splits = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1319 + * self.n_splits = 0 + * + * if dualtree: # <<<<<<<<<<<<<< + * other = self.__class__(np_Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) + */ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_dualtree); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1320 + * + * if dualtree: + * other = self.__class__(np_Xarr, metric=self.dist_metric, # <<<<<<<<<<<<<< + * leaf_size=self.leaf_size) + * if breadth_first: + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_class); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_np_Xarr); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_np_Xarr); + __Pyx_GIVEREF(__pyx_v_np_Xarr); + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_metric, ((PyObject *)__pyx_v_self->dist_metric)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1321 + * if dualtree: + * other = self.__class__(np_Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) # <<<<<<<<<<<<<< + * if breadth_first: + * self._query_dual_breadthfirst(other, heap, nodeheap) + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->leaf_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_leaf_size, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1320 + * + * if dualtree: + * other = self.__class__(np_Xarr, metric=self.dist_metric, # <<<<<<<<<<<<<< + * leaf_size=self.leaf_size) + * if breadth_first: + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_other = __pyx_t_1; + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1322 + * other = self.__class__(np_Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) + * if breadth_first: # <<<<<<<<<<<<<< + * self._query_dual_breadthfirst(other, heap, nodeheap) + * else: + */ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_breadth_first); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1322; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1323 + * leaf_size=self.leaf_size) + * if breadth_first: + * self._query_dual_breadthfirst(other, heap, nodeheap) # <<<<<<<<<<<<<< + * else: + * reduced_dist_LB = min_rdist_dual(self, 0, other, 0) + */ + if (!(likely(((__pyx_v_other) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_other, __pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__pyx_v_nodeheap)) { __Pyx_RaiseUnboundLocalError("nodeheap"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_breadthfirst(__pyx_v_self, ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_other), __pyx_v_heap, __pyx_v_nodeheap); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1325 + * self._query_dual_breadthfirst(other, heap, nodeheap) + * else: + * reduced_dist_LB = min_rdist_dual(self, 0, other, 0) # <<<<<<<<<<<<<< + * bounds = np.inf + np.zeros(other.node_data.shape[0]) + * self._query_dual_depthfirst(0, other, 0, bounds, + */ + if (!(likely(((__pyx_v_other) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_other, __pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist_dual(__pyx_v_self, 0, ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_other), 0); if (unlikely(__pyx_t_8 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1326 + * else: + * reduced_dist_LB = min_rdist_dual(self, 0, other, 0) + * bounds = np.inf + np.zeros(other.node_data.shape[0]) # <<<<<<<<<<<<<< + * self._query_dual_depthfirst(0, other, 0, bounds, + * heap, reduced_dist_LB) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_other, __pyx_n_s_node_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_3, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Add(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_9 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(__pyx_t_3); + if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_bounds = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1327 + * reduced_dist_LB = min_rdist_dual(self, 0, other, 0) + * bounds = np.inf + np.zeros(other.node_data.shape[0]) + * self._query_dual_depthfirst(0, other, 0, bounds, # <<<<<<<<<<<<<< + * heap, reduced_dist_LB) + * + */ + if (!(likely(((__pyx_v_other) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_other, __pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1328 + * bounds = np.inf + np.zeros(other.node_data.shape[0]) + * self._query_dual_depthfirst(0, other, 0, bounds, + * heap, reduced_dist_LB) # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, 0, ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_other), 0, __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + goto __pyx_L6; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1331 + * + * else: + * pt = &Xarr[0, 0] # <<<<<<<<<<<<<< + * if breadth_first: + * for i in range(Xarr.shape[0]): + */ + __pyx_t_10 = 0; + __pyx_t_11 = 0; + __pyx_v_pt = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_Xarr.data + __pyx_t_10 * __pyx_v_Xarr.strides[0]) )) + __pyx_t_11)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1332 + * else: + * pt = &Xarr[0, 0] + * if breadth_first: # <<<<<<<<<<<<<< + * for i in range(Xarr.shape[0]): + * self._query_single_breadthfirst(pt, i, heap, nodeheap) + */ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_breadth_first); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1332; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1333 + * pt = &Xarr[0, 0] + * if breadth_first: + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * self._query_single_breadthfirst(pt, i, heap, nodeheap) + * pt += Xarr.shape[1] + */ + __pyx_t_12 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1334 + * if breadth_first: + * for i in range(Xarr.shape[0]): + * self._query_single_breadthfirst(pt, i, heap, nodeheap) # <<<<<<<<<<<<<< + * pt += Xarr.shape[1] + * else: + */ + if (unlikely(!__pyx_v_nodeheap)) { __Pyx_RaiseUnboundLocalError("nodeheap"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_breadthfirst(__pyx_v_self, __pyx_v_pt, __pyx_v_i, __pyx_v_heap, __pyx_v_nodeheap); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1335 + * for i in range(Xarr.shape[0]): + * self._query_single_breadthfirst(pt, i, heap, nodeheap) + * pt += Xarr.shape[1] # <<<<<<<<<<<<<< + * else: + * for i in range(Xarr.shape[0]): + */ + __pyx_v_pt = (__pyx_v_pt + (__pyx_v_Xarr.shape[1])); + } + goto __pyx_L8; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1337 + * pt += Xarr.shape[1] + * else: + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * reduced_dist_LB = min_rdist(self, 0, pt) + * self._query_single_depthfirst(0, pt, i, heap, + */ + __pyx_t_12 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1338 + * else: + * for i in range(Xarr.shape[0]): + * reduced_dist_LB = min_rdist(self, 0, pt) # <<<<<<<<<<<<<< + * self._query_single_depthfirst(0, pt, i, heap, + * reduced_dist_LB) + */ + __pyx_t_8 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist(__pyx_v_self, 0, __pyx_v_pt); if (unlikely(__pyx_t_8 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1338; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1339 + * for i in range(Xarr.shape[0]): + * reduced_dist_LB = min_rdist(self, 0, pt) + * self._query_single_depthfirst(0, pt, i, heap, # <<<<<<<<<<<<<< + * reduced_dist_LB) + * pt += Xarr.shape[1] + */ + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_depthfirst(__pyx_v_self, 0, __pyx_v_pt, __pyx_v_i, __pyx_v_heap, __pyx_v_reduced_dist_LB); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1339; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1341 + * self._query_single_depthfirst(0, pt, i, heap, + * reduced_dist_LB) + * pt += Xarr.shape[1] # <<<<<<<<<<<<<< + * + * distances, indices = heap.get_arrays(sort=sort_results) + */ + __pyx_v_pt = (__pyx_v_pt + (__pyx_v_Xarr.shape[1])); + } + } + __pyx_L8:; + } + __pyx_L6:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1343 + * pt += Xarr.shape[1] + * + * distances, indices = heap.get_arrays(sort=sort_results) # <<<<<<<<<<<<<< + * distances = self.dist_metric.rdist_to_dist(distances) + * + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_heap), __pyx_n_s_get_arrays); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_sort, __pyx_v_sort_results) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_empty_tuple, __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_1 = PyList_GET_ITEM(sequence, 0); + __pyx_t_3 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_14 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_1 = __pyx_t_14(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L13_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + index = 1; __pyx_t_3 = __pyx_t_14(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L13_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_14(__pyx_t_4), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = NULL; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L14_unpacking_done; + __pyx_L13_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_14 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L14_unpacking_done:; + } + __pyx_v_distances = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_v_indices = __pyx_t_3; + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1344 + * + * distances, indices = heap.get_arrays(sort=sort_results) + * distances = self.dist_metric.rdist_to_dist(distances) # <<<<<<<<<<<<<< + * + * # deflatten results + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->dist_metric), __pyx_n_s_rdist_to_dist); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1344; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1344; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_distances); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_distances); + __Pyx_GIVEREF(__pyx_v_distances); + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1344; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_distances, __pyx_t_1); + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1347 + * + * # deflatten results + * if return_distance: # <<<<<<<<<<<<<< + * return (distances.reshape(X.shape[:X.ndim - 1] + (k,)), + * indices.reshape(X.shape[:X.ndim - 1] + (k,))) + */ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1348 + * # deflatten results + * if return_distance: + * return (distances.reshape(X.shape[:X.ndim - 1] + (k,)), # <<<<<<<<<<<<<< + * indices.reshape(X.shape[:X.ndim - 1] + (k,))) + * else: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_distances, __pyx_n_s_reshape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyNumber_Subtract(__pyx_t_2, __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_t_3, 0, 0, NULL, &__pyx_t_4, NULL, 0, 0, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_k); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_k); + __Pyx_GIVEREF(__pyx_v_k); + __pyx_t_3 = PyNumber_Add(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1349 + * if return_distance: + * return (distances.reshape(X.shape[:X.ndim - 1] + (k,)), + * indices.reshape(X.shape[:X.ndim - 1] + (k,))) # <<<<<<<<<<<<<< + * else: + * return indices.reshape(X.shape[:X.ndim - 1] + (k,)) + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_indices, __pyx_n_s_reshape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_15 = PyNumber_Subtract(__pyx_t_2, __pyx_int_1); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_t_1, 0, 0, NULL, &__pyx_t_15, NULL, 0, 0, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_15 = PyTuple_New(1); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + __Pyx_INCREF(__pyx_v_k); + PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_v_k); + __Pyx_GIVEREF(__pyx_v_k); + __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_t_15); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_15 = PyTuple_New(1); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_15, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1348 + * # deflatten results + * if return_distance: + * return (distances.reshape(X.shape[:X.ndim - 1] + (k,)), # <<<<<<<<<<<<<< + * indices.reshape(X.shape[:X.ndim - 1] + (k,))) + * else: + */ + __pyx_t_15 = PyTuple_New(2); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_15, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_3 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_15; + __pyx_t_15 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1351 + * indices.reshape(X.shape[:X.ndim - 1] + (k,))) + * else: + * return indices.reshape(X.shape[:X.ndim - 1] + (k,)) # <<<<<<<<<<<<<< + * + * def query_radius(self, X, r, return_distance=False, + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_15 = __Pyx_PyObject_GetAttrStr(__pyx_v_indices, __pyx_n_s_reshape); if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyNumber_Subtract(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_t_1, 0, 0, NULL, &__pyx_t_4, NULL, 0, 0, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_k); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_k); + __Pyx_GIVEREF(__pyx_v_k); + __pyx_t_1 = PyNumber_Add(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_15, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1228 + * idx_start + n_mid, idx_end) + * + * def query(self, X, k=1, return_distance=True, # <<<<<<<<<<<<<< + * dualtree=False, breadth_first=False, + * sort_results=True): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_9, 1); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.query", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_np_Xarr); + __PYX_XDEC_MEMVIEW(&__pyx_v_Xarr, 1); + __Pyx_XDECREF((PyObject *)__pyx_v_heap); + __Pyx_XDECREF((PyObject *)__pyx_v_nodeheap); + __PYX_XDEC_MEMVIEW(&__pyx_v_bounds, 1); + __Pyx_XDECREF(__pyx_v_other); + __Pyx_XDECREF(__pyx_v_distances); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XDECREF(__pyx_v_X); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1353 + * return indices.reshape(X.shape[:X.ndim - 1] + (k,)) + * + * def query_radius(self, X, r, return_distance=False, # <<<<<<<<<<<<<< + * int count_only=False, int sort_results=False): + * """ + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_21query_radius(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_20query_radius[] = "\n query_radius(self, X, r, count_only = False):\n\n query the tree for neighbors within a radius r\n\n Parameters\n ----------\n X : array-like, last dimension self.dim\n An array of points to query\n r : distance within which neighbors are returned\n r can be a single value, or an array of values of shape\n x.shape[:-1] if different radii are desired for each point.\n return_distance : boolean (default = False)\n if True, return distances to neighbors of each point\n if False, return only neighbors\n Note that unlike the query() method, setting return_distance=True\n here adds to the computation time. Not all distances need to be\n calculated explicitly for return_distance=False. Results are\n not sorted by default: see ``sort_results`` keyword.\n count_only : boolean (default = False)\n if True, return only the count of points within distance r\n if False, return the indices of all points within distance r\n If return_distance==True, setting count_only=True will\n result in an error.\n sort_results : boolean (default = False)\n if True, the distances and indices will be sorted before being\n returned. If False, the results will not be sorted. If\n return_distance == False, setting sort_results = True will\n result in an error.\n\n Returns\n -------\n count : if count_only == True\n ind : if count_only == False and return_distance == False\n (ind, dist) : if count_only == False and return_distance == True\n\n count : array of integers, shape = X.shape[:-1]\n each entry gives the number of neighbors within\n a distance r of the corresponding point.\n\n ind : array of objects, shape = X.shape[:-1]\n each element is a num""py integer array listing the indices of\n neighbors of the corresponding point. Note that unlike\n the results of a k-neighbors query, the returned neighbors\n are not sorted by distance by default.\n\n dist : array of objects, shape = X.shape[:-1]\n each element is a numpy double array\n listing the distances corresponding to indices in i.\n\n Examples\n --------\n Query for neighbors in a given radius\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((10, 3)) # 10 points in 3 dimensions\n >>> tree = BinaryTree(X, leaf_size=2) # doctest: +SKIP\n >>> print tree.query_radius(X[0], r=0.3, count_only=True)\n 3\n >>> ind = tree.query_radius(X[0], r=0.3) # doctest: +SKIP\n >>> print ind # indices of neighbors within distance 0.3\n [3 0 1]\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_21query_radius(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_X = 0; + PyObject *__pyx_v_r = 0; + PyObject *__pyx_v_return_distance = 0; + int __pyx_v_count_only; + int __pyx_v_sort_results; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("query_radius (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_r,&__pyx_n_s_return_distance,&__pyx_n_s_count_only,&__pyx_n_s_sort_results,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[2] = ((PyObject *)Py_False); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_r)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("query_radius", 0, 2, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1353; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_return_distance); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_count_only); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sort_results); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "query_radius") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1353; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_X = values[0]; + __pyx_v_r = values[1]; + __pyx_v_return_distance = values[2]; + if (values[3]) { + __pyx_v_count_only = __Pyx_PyInt_As_int(values[3]); if (unlikely((__pyx_v_count_only == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1354; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1354 + * + * def query_radius(self, X, r, return_distance=False, + * int count_only=False, int sort_results=False): # <<<<<<<<<<<<<< + * """ + * query_radius(self, X, r, count_only = False): + */ + __pyx_v_count_only = ((int)0); + } + if (values[4]) { + __pyx_v_sort_results = __Pyx_PyInt_As_int(values[4]); if (unlikely((__pyx_v_sort_results == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1354; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_sort_results = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("query_radius", 0, 2, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1353; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.query_radius", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_20query_radius(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self), __pyx_v_X, __pyx_v_r, __pyx_v_return_distance, __pyx_v_count_only, __pyx_v_sort_results); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1353 + * return indices.reshape(X.shape[:X.ndim - 1] + (k,)) + * + * def query_radius(self, X, r, return_distance=False, # <<<<<<<<<<<<<< + * int count_only=False, int sort_results=False): + * """ + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_20query_radius(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_r, PyObject *__pyx_v_return_distance, int __pyx_v_count_only, int __pyx_v_sort_results) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_count_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __Pyx_memviewslice __pyx_v_dist_arr_i = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_idx_arr_i = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_counts = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt; + __Pyx_memviewslice __pyx_v_Xarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_rarr_np = NULL; + __Pyx_memviewslice __pyx_v_rarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_indices = NULL; + PyObject *__pyx_v_distances = NULL; + PyObject *__pyx_v_np_idx_arr = NULL; + PyObject *__pyx_v_np_dist_arr = NULL; + PyObject *__pyx_v_counts_arr = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_t_8 = NULL; + __Pyx_memviewslice __pyx_t_9 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_10 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + Py_ssize_t __pyx_t_16; + Py_ssize_t __pyx_t_17; + int __pyx_t_18; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_19; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_20; + Py_ssize_t __pyx_t_21; + Py_ssize_t __pyx_t_22; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_23; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_24; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("query_radius", 0); + __Pyx_INCREF(__pyx_v_X); + __Pyx_INCREF(__pyx_v_r); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1419 + * [3 0 1] + * """ + * if count_only and return_distance: # <<<<<<<<<<<<<< + * raise ValueError("count_only and return_distance " + * "cannot both be true") + */ + if ((__pyx_v_count_only != 0)) { + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1419; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = (__pyx_v_count_only != 0); + } + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1420 + * """ + * if count_only and return_distance: + * raise ValueError("count_only and return_distance " # <<<<<<<<<<<<<< + * "cannot both be true") + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1423 + * "cannot both be true") + * + * if sort_results and not return_distance: # <<<<<<<<<<<<<< + * raise ValueError("return_distance must be True " + * "if sort_results is True") + */ + if ((__pyx_v_sort_results != 0)) { + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (!__pyx_t_2); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = (__pyx_v_sort_results != 0); + } + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1424 + * + * if sort_results and not return_distance: + * raise ValueError("return_distance must be True " # <<<<<<<<<<<<<< + * "if sort_results is True") + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__22, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1427 + * "if sort_results is True") + * + * cdef ITYPE_t i, count_i = 0 # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef DTYPE_t[::1] dist_arr_i + */ + __pyx_v_count_i = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1428 + * + * cdef ITYPE_t i, count_i = 0 + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] dist_arr_i + * cdef ITYPE_t[::1] idx_arr_i, counts + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1428; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1434 + * + * # validate X and prepare for query + * X = check_array(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_check_array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_6); + __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1436 + * X = check_array(X, dtype=DTYPE, order='C') + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: # <<<<<<<<<<<<<< + * raise ValueError("query data dimension must " + * "match training data dimension") + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyNumber_Subtract(__pyx_t_5, __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_GetItem(__pyx_t_6, __pyx_t_4); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_5, __pyx_t_4, Py_NE); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1437 + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * + */ + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__23, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1441 + * + * cdef DTYPE_t[:, ::1] Xarr =\ + * get_memview_DTYPE_2D(X.reshape((-1, self.data.shape[1]))) # <<<<<<<<<<<<<< + * + * # prepare r for query + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_reshape); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_4, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_t_5)); if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_Xarr = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1444 + * + * # prepare r for query + * r = np.asarray(r, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * r = np.atleast_1d(r) + * if r.shape == (1,): + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_asarray); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_r); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_r); + __Pyx_GIVEREF(__pyx_v_r); + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, __pyx_t_6); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF_SET(__pyx_v_r, __pyx_t_3); + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1445 + * # prepare r for query + * r = np.asarray(r, dtype=DTYPE, order='C') + * r = np.atleast_1d(r) # <<<<<<<<<<<<<< + * if r.shape == (1,): + * r = r[0] + np.zeros(X.shape[:X.ndim - 1], dtype=DTYPE) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_atleast_1d); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_r); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_r); + __Pyx_GIVEREF(__pyx_v_r); + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_3, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_r, __pyx_t_5); + __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1446 + * r = np.asarray(r, dtype=DTYPE, order='C') + * r = np.atleast_1d(r) + * if r.shape == (1,): # <<<<<<<<<<<<<< + * r = r[0] + np.zeros(X.shape[:X.ndim - 1], dtype=DTYPE) + * else: + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_r, __pyx_n_s_shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_tuple__24, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1447 + * r = np.atleast_1d(r) + * if r.shape == (1,): + * r = r[0] + np.zeros(X.shape[:X.ndim - 1], dtype=DTYPE) # <<<<<<<<<<<<<< + * else: + * if r.shape != X.shape[:X.ndim - 1]: + */ + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_r, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyNumber_Subtract(__pyx_t_4, __pyx_int_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetSlice(__pyx_t_5, 0, 0, NULL, &__pyx_t_8, NULL, 0, 0, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, __pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_Add(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF_SET(__pyx_v_r, __pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L6; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1449 + * r = r[0] + np.zeros(X.shape[:X.ndim - 1], dtype=DTYPE) + * else: + * if r.shape != X.shape[:X.ndim - 1]: # <<<<<<<<<<<<<< + * raise ValueError("r must be broadcastable to X.shape") + * + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_r, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = PyNumber_Subtract(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_t_5, 0, 0, NULL, &__pyx_t_8, NULL, 0, 0, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyObject_RichCompare(__pyx_t_4, __pyx_t_3, Py_NE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1450 + * else: + * if r.shape != X.shape[:X.ndim - 1]: + * raise ValueError("r must be broadcastable to X.shape") # <<<<<<<<<<<<<< + * + * rarr_np = r.reshape(-1) # store explicitly to keep in scope + */ + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__25, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + __pyx_L6:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1452 + * raise ValueError("r must be broadcastable to X.shape") + * + * rarr_np = r.reshape(-1) # store explicitly to keep in scope # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) + * + */ + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_r, __pyx_n_s_reshape); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__26, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_rarr_np = __pyx_t_3; + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1453 + * + * rarr_np = r.reshape(-1) # store explicitly to keep in scope + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) # <<<<<<<<<<<<<< + * + * # prepare variables for iteration + */ + if (!(likely(((__pyx_v_rarr_np) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_rarr_np, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_rarr_np)); if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_rarr = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1456 + * + * # prepare variables for iteration + * if not count_only: # <<<<<<<<<<<<<< + * indices = np.zeros(Xarr.shape[0], dtype='object') + * if return_distance: + */ + __pyx_t_2 = ((!(__pyx_v_count_only != 0)) != 0); + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1457 + * # prepare variables for iteration + * if not count_only: + * indices = np.zeros(Xarr.shape[0], dtype='object') # <<<<<<<<<<<<<< + * if return_distance: + * distances = np.zeros(Xarr.shape[0], dtype='object') + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_Xarr.shape[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_n_s_object) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1458 + * if not count_only: + * indices = np.zeros(Xarr.shape[0], dtype='object') + * if return_distance: # <<<<<<<<<<<<<< + * distances = np.zeros(Xarr.shape[0], dtype='object') + * + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1458; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1459 + * indices = np.zeros(Xarr.shape[0], dtype='object') + * if return_distance: + * distances = np.zeros(Xarr.shape[0], dtype='object') # <<<<<<<<<<<<<< + * + * np_idx_arr = np.zeros(self.data.shape[0], dtype=ITYPE) + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_Xarr.shape[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_n_s_object) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_distances = __pyx_t_8; + __pyx_t_8 = 0; + goto __pyx_L9; + } + __pyx_L9:; + goto __pyx_L8; + } + __pyx_L8:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1461 + * distances = np.zeros(Xarr.shape[0], dtype='object') + * + * np_idx_arr = np.zeros(self.data.shape[0], dtype=ITYPE) # <<<<<<<<<<<<<< + * idx_arr_i = get_memview_ITYPE_1D(np_idx_arr) + * + */ + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_zeros); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_8 = PyInt_FromSsize_t((__pyx_v_self->data.shape[0])); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = PyDict_New(); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_8, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_8); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_np_idx_arr = __pyx_t_3; + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1462 + * + * np_idx_arr = np.zeros(self.data.shape[0], dtype=ITYPE) + * idx_arr_i = get_memview_ITYPE_1D(np_idx_arr) # <<<<<<<<<<<<<< + * + * np_dist_arr = np.zeros(self.data.shape[0], dtype=DTYPE) + */ + if (!(likely(((__pyx_v_np_idx_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_np_idx_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_v_np_idx_arr)); if (unlikely(!__pyx_t_10.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_idx_arr_i = __pyx_t_10; + __pyx_t_10.memview = NULL; + __pyx_t_10.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1464 + * idx_arr_i = get_memview_ITYPE_1D(np_idx_arr) + * + * np_dist_arr = np.zeros(self.data.shape[0], dtype=DTYPE) # <<<<<<<<<<<<<< + * dist_arr_i = get_memview_DTYPE_1D(np_dist_arr) + * + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_self->data.shape[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_np_dist_arr = __pyx_t_5; + __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1465 + * + * np_dist_arr = np.zeros(self.data.shape[0], dtype=DTYPE) + * dist_arr_i = get_memview_DTYPE_1D(np_dist_arr) # <<<<<<<<<<<<<< + * + * counts_arr = np.zeros(Xarr.shape[0], dtype=ITYPE) + */ + if (!(likely(((__pyx_v_np_dist_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_np_dist_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1465; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_np_dist_arr)); if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1465; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_arr_i = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1467 + * dist_arr_i = get_memview_DTYPE_1D(np_dist_arr) + * + * counts_arr = np.zeros(Xarr.shape[0], dtype=ITYPE) # <<<<<<<<<<<<<< + * counts = get_memview_ITYPE_1D(counts_arr) + * + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_Xarr.shape[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_counts_arr = __pyx_t_8; + __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1468 + * + * counts_arr = np.zeros(Xarr.shape[0], dtype=ITYPE) + * counts = get_memview_ITYPE_1D(counts_arr) # <<<<<<<<<<<<<< + * + * pt = &Xarr[0, 0] + */ + if (!(likely(((__pyx_v_counts_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_counts_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_v_counts_arr)); if (unlikely(!__pyx_t_10.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_counts = __pyx_t_10; + __pyx_t_10.memview = NULL; + __pyx_t_10.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1470 + * counts = get_memview_ITYPE_1D(counts_arr) + * + * pt = &Xarr[0, 0] # <<<<<<<<<<<<<< + * for i in range(Xarr.shape[0]): + * counts[i] = self._query_radius_single(0, pt, rarr[i], + */ + __pyx_t_11 = 0; + __pyx_t_12 = 0; + __pyx_v_pt = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_Xarr.data + __pyx_t_11 * __pyx_v_Xarr.strides[0]) )) + __pyx_t_12)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1471 + * + * pt = &Xarr[0, 0] + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * counts[i] = self._query_radius_single(0, pt, rarr[i], + * &idx_arr_i[0], + */ + __pyx_t_13 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_14 = 0; __pyx_t_14 < __pyx_t_13; __pyx_t_14+=1) { + __pyx_v_i = __pyx_t_14; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1472 + * pt = &Xarr[0, 0] + * for i in range(Xarr.shape[0]): + * counts[i] = self._query_radius_single(0, pt, rarr[i], # <<<<<<<<<<<<<< + * &idx_arr_i[0], + * &dist_arr_i[0], + */ + __pyx_t_15 = __pyx_v_i; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1473 + * for i in range(Xarr.shape[0]): + * counts[i] = self._query_radius_single(0, pt, rarr[i], + * &idx_arr_i[0], # <<<<<<<<<<<<<< + * &dist_arr_i[0], + * 0, count_only, + */ + __pyx_t_16 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1474 + * counts[i] = self._query_radius_single(0, pt, rarr[i], + * &idx_arr_i[0], + * &dist_arr_i[0], # <<<<<<<<<<<<<< + * 0, count_only, + * return_distance) + */ + __pyx_t_17 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1476 + * &dist_arr_i[0], + * 0, count_only, + * return_distance) # <<<<<<<<<<<<<< + * pt += n_features + * + */ + __pyx_t_18 = __Pyx_PyInt_As_int(__pyx_v_return_distance); if (unlikely((__pyx_t_18 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1472 + * pt = &Xarr[0, 0] + * for i in range(Xarr.shape[0]): + * counts[i] = self._query_radius_single(0, pt, rarr[i], # <<<<<<<<<<<<<< + * &idx_arr_i[0], + * &dist_arr_i[0], + */ + __pyx_t_19 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_radius_single(__pyx_v_self, 0, __pyx_v_pt, (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_rarr.data) + __pyx_t_15)) ))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_idx_arr_i.data) + __pyx_t_16)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_dist_arr_i.data) + __pyx_t_17)) )))), 0, __pyx_v_count_only, __pyx_t_18); if (unlikely(__pyx_t_19 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1472; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_20 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_counts.data) + __pyx_t_20)) )) = __pyx_t_19; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1477 + * 0, count_only, + * return_distance) + * pt += n_features # <<<<<<<<<<<<<< + * + * if count_only: + */ + __pyx_v_pt = (__pyx_v_pt + __pyx_v_n_features); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1479 + * pt += n_features + * + * if count_only: # <<<<<<<<<<<<<< + * pass + * else: + */ + __pyx_t_2 = (__pyx_v_count_only != 0); + if (__pyx_t_2) { + goto __pyx_L12; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1482 + * pass + * else: + * if sort_results: # <<<<<<<<<<<<<< + * _simultaneous_sort(&dist_arr_i[0], &idx_arr_i[0], + * counts[i]) + */ + __pyx_t_2 = (__pyx_v_sort_results != 0); + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1483 + * else: + * if sort_results: + * _simultaneous_sort(&dist_arr_i[0], &idx_arr_i[0], # <<<<<<<<<<<<<< + * counts[i]) + * + */ + __pyx_t_21 = 0; + __pyx_t_22 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1484 + * if sort_results: + * _simultaneous_sort(&dist_arr_i[0], &idx_arr_i[0], + * counts[i]) # <<<<<<<<<<<<<< + * + * indices[i] = np_idx_arr[:counts[i]].copy() + */ + __pyx_t_19 = __pyx_v_i; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1483 + * else: + * if sort_results: + * _simultaneous_sort(&dist_arr_i[0], &idx_arr_i[0], # <<<<<<<<<<<<<< + * counts[i]) + * + */ + __pyx_t_18 = __pyx_f_7sklearn_9neighbors_7kd_tree__simultaneous_sort((&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_dist_arr_i.data) + __pyx_t_21)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_idx_arr_i.data) + __pyx_t_22)) )))), (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_counts.data) + __pyx_t_19)) )))); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L13; + } + __pyx_L13:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1486 + * counts[i]) + * + * indices[i] = np_idx_arr[:counts[i]].copy() # <<<<<<<<<<<<<< + * if return_distance: + * distances[i] = np_dist_arr[:counts[i]].copy() + */ + __pyx_t_23 = __pyx_v_i; + __pyx_t_8 = __Pyx_PyObject_GetSlice(__pyx_v_np_idx_arr, 0, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_counts.data) + __pyx_t_23)) ))), NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_copy); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_v_indices)) { __Pyx_RaiseUnboundLocalError("indices"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + if (unlikely(__Pyx_SetItemInt(__pyx_v_indices, __pyx_v_i, __pyx_t_8, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, 1, __Pyx_PyInt_From_Py_intptr_t, 0, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1487 + * + * indices[i] = np_idx_arr[:counts[i]].copy() + * if return_distance: # <<<<<<<<<<<<<< + * distances[i] = np_dist_arr[:counts[i]].copy() + * + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1488 + * indices[i] = np_idx_arr[:counts[i]].copy() + * if return_distance: + * distances[i] = np_dist_arr[:counts[i]].copy() # <<<<<<<<<<<<<< + * + * # deflatten results + */ + __pyx_t_24 = __pyx_v_i; + __pyx_t_8 = __Pyx_PyObject_GetSlice(__pyx_v_np_dist_arr, 0, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_counts.data) + __pyx_t_24)) ))), NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_copy); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_v_distances)) { __Pyx_RaiseUnboundLocalError("distances"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + if (unlikely(__Pyx_SetItemInt(__pyx_v_distances, __pyx_v_i, __pyx_t_8, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, 1, __Pyx_PyInt_From_Py_intptr_t, 0, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L14; + } + __pyx_L14:; + } + __pyx_L12:; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1491 + * + * # deflatten results + * if count_only: # <<<<<<<<<<<<<< + * return counts_arr.reshape(X.shape[:X.ndim - 1]) + * elif return_distance: + */ + __pyx_t_2 = (__pyx_v_count_only != 0); + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1492 + * # deflatten results + * if count_only: + * return counts_arr.reshape(X.shape[:X.ndim - 1]) # <<<<<<<<<<<<<< + * elif return_distance: + * return (indices.reshape(X.shape[:X.ndim - 1]), + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_counts_arr, __pyx_n_s_reshape); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_int_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetSlice(__pyx_t_5, 0, 0, NULL, &__pyx_t_3, NULL, 0, 0, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1493 + * if count_only: + * return counts_arr.reshape(X.shape[:X.ndim - 1]) + * elif return_distance: # <<<<<<<<<<<<<< + * return (indices.reshape(X.shape[:X.ndim - 1]), + * distances.reshape(X.shape[:X.ndim - 1])) + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_return_distance); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1494 + * return counts_arr.reshape(X.shape[:X.ndim - 1]) + * elif return_distance: + * return (indices.reshape(X.shape[:X.ndim - 1]), # <<<<<<<<<<<<<< + * distances.reshape(X.shape[:X.ndim - 1])) + * else: + */ + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_indices)) { __Pyx_RaiseUnboundLocalError("indices"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_indices, __pyx_n_s_reshape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = PyNumber_Subtract(__pyx_t_8, __pyx_int_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_GetSlice(__pyx_t_3, 0, 0, NULL, &__pyx_t_5, NULL, 0, 0, 0); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1495 + * elif return_distance: + * return (indices.reshape(X.shape[:X.ndim - 1]), + * distances.reshape(X.shape[:X.ndim - 1])) # <<<<<<<<<<<<<< + * else: + * return indices.reshape(X.shape[:X.ndim - 1]) + */ + if (unlikely(!__pyx_v_distances)) { __Pyx_RaiseUnboundLocalError("distances"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_distances, __pyx_n_s_reshape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = PyNumber_Subtract(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_t_4, 0, 0, NULL, &__pyx_t_6, NULL, 0, 0, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1494 + * return counts_arr.reshape(X.shape[:X.ndim - 1]) + * elif return_distance: + * return (indices.reshape(X.shape[:X.ndim - 1]), # <<<<<<<<<<<<<< + * distances.reshape(X.shape[:X.ndim - 1])) + * else: + */ + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_8 = 0; + __pyx_t_3 = 0; + __pyx_r = __pyx_t_6; + __pyx_t_6 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1497 + * distances.reshape(X.shape[:X.ndim - 1])) + * else: + * return indices.reshape(X.shape[:X.ndim - 1]) # <<<<<<<<<<<<<< + * + * def kernel_density(self, X, h, kernel='gaussian', + */ + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_indices)) { __Pyx_RaiseUnboundLocalError("indices"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_indices, __pyx_n_s_reshape); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = PyNumber_Subtract(__pyx_t_8, __pyx_int_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_GetSlice(__pyx_t_3, 0, 0, NULL, &__pyx_t_5, NULL, 0, 0, 0); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_5, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_r = __pyx_t_8; + __pyx_t_8 = 0; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1353 + * return indices.reshape(X.shape[:X.ndim - 1] + (k,)) + * + * def query_radius(self, X, r, return_distance=False, # <<<<<<<<<<<<<< + * int count_only=False, int sort_results=False): + * """ + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __Pyx_XDECREF(__pyx_t_8); + __PYX_XDEC_MEMVIEW(&__pyx_t_9, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_10, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.query_radius", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_dist_arr_i, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_idx_arr_i, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_counts, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Xarr, 1); + __Pyx_XDECREF(__pyx_v_rarr_np); + __PYX_XDEC_MEMVIEW(&__pyx_v_rarr, 1); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XDECREF(__pyx_v_distances); + __Pyx_XDECREF(__pyx_v_np_idx_arr); + __Pyx_XDECREF(__pyx_v_np_dist_arr); + __Pyx_XDECREF(__pyx_v_counts_arr); + __Pyx_XDECREF(__pyx_v_X); + __Pyx_XDECREF(__pyx_v_r); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1499 + * return indices.reshape(X.shape[:X.ndim - 1]) + * + * def kernel_density(self, X, h, kernel='gaussian', # <<<<<<<<<<<<<< + * atol=0, rtol=1E-8, + * breadth_first=True, return_log=False): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_23kernel_density(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_22kernel_density[] = "\n kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1E-8,\n breadth_first=True, return_log=False)\n\n Compute the kernel density estimate at points X with the given kernel,\n using the distance metric specified at tree creation.\n\n Parameters\n ----------\n X : array_like\n An array of points to query. Last dimension should match dimension\n of training data.\n h : float\n the bandwidth of the kernel\n kernel : string\n specify the kernel to use. Options are\n - 'gaussian'\n - 'tophat'\n - 'epanechnikov'\n - 'exponential'\n - 'linear'\n - 'cosine'\n Default is kernel = 'gaussian'\n atol, rtol : float (default = 0)\n Specify the desired relative and absolute tolerance of the result.\n If the true result is K_true, then the returned result K_ret\n satisfies ``abs(K_true - K_ret) < atol + rtol * K_ret``\n The default is zero (i.e. machine precision) for both.\n breadth_first : boolean (default = False)\n if True, use a breadth-first search. If False (default) use a\n depth-first search. Breadth-first is generally faster for\n compact kernels and/or high tolerances.\n return_log : boolean (default = False)\n return the logarithm of the result. This can be more accurate\n than returning the result itself for narrow kernels.\n\n Returns\n -------\n density : ndarray\n The array of (log)-density evaluations, shape = X.shape[:-1]\n\n Examples\n --------\n Compute a gaussian kernel density estimate:\n\n >>> import numpy as np\n >>> np.random.seed(1)\n >>> X = np.random.random((100, 3))\n >>> tree = BinaryTree(X) # doctest: +SKIP\n >>> tree.kernel_den""sity(X[:3], h=0.1, kernel='gaussian')\n array([ 6.94114649, 7.83281226, 7.2071716 ])\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_23kernel_density(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_X = 0; + PyObject *__pyx_v_h = 0; + PyObject *__pyx_v_kernel = 0; + PyObject *__pyx_v_atol = 0; + PyObject *__pyx_v_rtol = 0; + PyObject *__pyx_v_breadth_first = 0; + PyObject *__pyx_v_return_log = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("kernel_density (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_h,&__pyx_n_s_kernel,&__pyx_n_s_atol,&__pyx_n_s_rtol,&__pyx_n_s_breadth_first,&__pyx_n_s_return_log,0}; + PyObject* values[7] = {0,0,0,0,0,0,0}; + values[2] = ((PyObject *)__pyx_n_s_gaussian); + values[3] = ((PyObject *)__pyx_int_0); + values[4] = ((PyObject *)__pyx_float_1Eneg_8); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1501 + * def kernel_density(self, X, h, kernel='gaussian', + * atol=0, rtol=1E-8, + * breadth_first=True, return_log=False): # <<<<<<<<<<<<<< + * """ + * kernel_density(self, X, h, kernel='gaussian', atol=0, rtol=1E-8, + */ + values[5] = ((PyObject *)Py_True); + values[6] = ((PyObject *)Py_False); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_h)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("kernel_density", 0, 2, 7, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1499; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kernel); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_atol); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_rtol); + if (value) { values[4] = value; kw_args--; } + } + case 5: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_breadth_first); + if (value) { values[5] = value; kw_args--; } + } + case 6: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_return_log); + if (value) { values[6] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "kernel_density") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1499; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_X = values[0]; + __pyx_v_h = values[1]; + __pyx_v_kernel = values[2]; + __pyx_v_atol = values[3]; + __pyx_v_rtol = values[4]; + __pyx_v_breadth_first = values[5]; + __pyx_v_return_log = values[6]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("kernel_density", 0, 2, 7, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1499; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.kernel_density", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_22kernel_density(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self), __pyx_v_X, __pyx_v_h, __pyx_v_kernel, __pyx_v_atol, __pyx_v_rtol, __pyx_v_breadth_first, __pyx_v_return_log); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1499 + * return indices.reshape(X.shape[:X.ndim - 1]) + * + * def kernel_density(self, X, h, kernel='gaussian', # <<<<<<<<<<<<<< + * atol=0, rtol=1E-8, + * breadth_first=True, return_log=False): + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_22kernel_density(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_h, PyObject *__pyx_v_kernel, PyObject *__pyx_v_atol, PyObject *__pyx_v_rtol, PyObject *__pyx_v_breadth_first, PyObject *__pyx_v_return_log) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h_c; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_atol; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_rtol; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_min_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_max_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_bound_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_samples; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType __pyx_v_kernel_c; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_knorm; + PyObject *__pyx_v_Xarr_np = NULL; + __Pyx_memviewslice __pyx_v_Xarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_log_density_arr = NULL; + __Pyx_memviewslice __pyx_v_log_density = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt; + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_nodeheap = 0; + __Pyx_memviewslice __pyx_v_node_log_min_bounds = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_node_bound_widths = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_node_log_min_bounds_arr = NULL; + PyObject *__pyx_v_node_bound_widths_arr = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_1; + double __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + __Pyx_memviewslice __pyx_t_8 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_9 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + Py_ssize_t __pyx_t_14; + Py_ssize_t __pyx_t_15; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_16; + int __pyx_t_17; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_18; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_19; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("kernel_density", 0); + __Pyx_INCREF(__pyx_v_X); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1554 + * array([ 6.94114649, 7.83281226, 7.2071716 ]) + * """ + * cdef DTYPE_t h_c = h # <<<<<<<<<<<<<< + * cdef DTYPE_t log_atol = log(atol) + * cdef DTYPE_t log_rtol = log(rtol) + */ + __pyx_t_1 = __pyx_PyFloat_AsDouble(__pyx_v_h); if (unlikely((__pyx_t_1 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_h_c = __pyx_t_1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1555 + * """ + * cdef DTYPE_t h_c = h + * cdef DTYPE_t log_atol = log(atol) # <<<<<<<<<<<<<< + * cdef DTYPE_t log_rtol = log(rtol) + * cdef DTYPE_t log_min_bound, log_max_bound, log_bound_spread + */ + __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_v_atol); if (unlikely((__pyx_t_2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1555; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_log_atol = log(__pyx_t_2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1556 + * cdef DTYPE_t h_c = h + * cdef DTYPE_t log_atol = log(atol) + * cdef DTYPE_t log_rtol = log(rtol) # <<<<<<<<<<<<<< + * cdef DTYPE_t log_min_bound, log_max_bound, log_bound_spread + * cdef DTYPE_t dist_LB = 0, dist_UB = 0 + */ + __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_v_rtol); if (unlikely((__pyx_t_2 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1556; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_log_rtol = log(__pyx_t_2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1558 + * cdef DTYPE_t log_rtol = log(rtol) + * cdef DTYPE_t log_min_bound, log_max_bound, log_bound_spread + * cdef DTYPE_t dist_LB = 0, dist_UB = 0 # <<<<<<<<<<<<<< + * + * cdef ITYPE_t n_samples = self.data.shape[0] + */ + __pyx_v_dist_LB = 0.0; + __pyx_v_dist_UB = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1560 + * cdef DTYPE_t dist_LB = 0, dist_UB = 0 + * + * cdef ITYPE_t n_samples = self.data.shape[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef ITYPE_t i + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1560; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_samples = (__pyx_v_self->data.shape[0]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1561 + * + * cdef ITYPE_t n_samples = self.data.shape[0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef ITYPE_t i + * cdef KernelType kernel_c + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1561; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1566 + * + * # validate kernel + * if kernel == 'gaussian': # <<<<<<<<<<<<<< + * kernel_c = GAUSSIAN_KERNEL + * elif kernel == 'tophat': + */ + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_gaussian, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1567 + * # validate kernel + * if kernel == 'gaussian': + * kernel_c = GAUSSIAN_KERNEL # <<<<<<<<<<<<<< + * elif kernel == 'tophat': + * kernel_c = TOPHAT_KERNEL + */ + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_7kd_tree_GAUSSIAN_KERNEL; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1568 + * if kernel == 'gaussian': + * kernel_c = GAUSSIAN_KERNEL + * elif kernel == 'tophat': # <<<<<<<<<<<<<< + * kernel_c = TOPHAT_KERNEL + * elif kernel == 'epanechnikov': + */ + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_tophat, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1569 + * kernel_c = GAUSSIAN_KERNEL + * elif kernel == 'tophat': + * kernel_c = TOPHAT_KERNEL # <<<<<<<<<<<<<< + * elif kernel == 'epanechnikov': + * kernel_c = EPANECHNIKOV_KERNEL + */ + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_7kd_tree_TOPHAT_KERNEL; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1570 + * elif kernel == 'tophat': + * kernel_c = TOPHAT_KERNEL + * elif kernel == 'epanechnikov': # <<<<<<<<<<<<<< + * kernel_c = EPANECHNIKOV_KERNEL + * elif kernel == 'exponential': + */ + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_epanechnikov, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1571 + * kernel_c = TOPHAT_KERNEL + * elif kernel == 'epanechnikov': + * kernel_c = EPANECHNIKOV_KERNEL # <<<<<<<<<<<<<< + * elif kernel == 'exponential': + * kernel_c = EXPONENTIAL_KERNEL + */ + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_7kd_tree_EPANECHNIKOV_KERNEL; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1572 + * elif kernel == 'epanechnikov': + * kernel_c = EPANECHNIKOV_KERNEL + * elif kernel == 'exponential': # <<<<<<<<<<<<<< + * kernel_c = EXPONENTIAL_KERNEL + * elif kernel == 'linear': + */ + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_exponential, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1573 + * kernel_c = EPANECHNIKOV_KERNEL + * elif kernel == 'exponential': + * kernel_c = EXPONENTIAL_KERNEL # <<<<<<<<<<<<<< + * elif kernel == 'linear': + * kernel_c = LINEAR_KERNEL + */ + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_7kd_tree_EXPONENTIAL_KERNEL; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1574 + * elif kernel == 'exponential': + * kernel_c = EXPONENTIAL_KERNEL + * elif kernel == 'linear': # <<<<<<<<<<<<<< + * kernel_c = LINEAR_KERNEL + * elif kernel == 'cosine': + */ + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_linear, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1575 + * kernel_c = EXPONENTIAL_KERNEL + * elif kernel == 'linear': + * kernel_c = LINEAR_KERNEL # <<<<<<<<<<<<<< + * elif kernel == 'cosine': + * kernel_c = COSINE_KERNEL + */ + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_7kd_tree_LINEAR_KERNEL; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1576 + * elif kernel == 'linear': + * kernel_c = LINEAR_KERNEL + * elif kernel == 'cosine': # <<<<<<<<<<<<<< + * kernel_c = COSINE_KERNEL + * else: + */ + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_v_kernel, __pyx_n_s_cosine, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1577 + * kernel_c = LINEAR_KERNEL + * elif kernel == 'cosine': + * kernel_c = COSINE_KERNEL # <<<<<<<<<<<<<< + * else: + * raise ValueError("kernel = '%s' not recognized" % kernel) + */ + __pyx_v_kernel_c = __pyx_e_7sklearn_9neighbors_7kd_tree_COSINE_KERNEL; + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1579 + * kernel_c = COSINE_KERNEL + * else: + * raise ValueError("kernel = '%s' not recognized" % kernel) # <<<<<<<<<<<<<< + * + * cdef DTYPE_t log_knorm = _log_kernel_norm(h_c, n_features, kernel_c) + */ + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_kernel_s_not_recognized, __pyx_v_kernel); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1581 + * raise ValueError("kernel = '%s' not recognized" % kernel) + * + * cdef DTYPE_t log_knorm = _log_kernel_norm(h_c, n_features, kernel_c) # <<<<<<<<<<<<<< + * + * # validate X and prepare for query + */ + __pyx_t_1 = __pyx_f_7sklearn_9neighbors_7kd_tree__log_kernel_norm(__pyx_v_h_c, __pyx_v_n_features, __pyx_v_kernel_c); if (unlikely(__pyx_t_1 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1581; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_log_knorm = __pyx_t_1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1584 + * + * # validate X and prepare for query + * X = check_array(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * + * if X.shape[X.ndim - 1] != n_features: + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_check_array); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, __pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_7); + __pyx_t_7 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1586 + * X = check_array(X, dtype=DTYPE, order='C') + * + * if X.shape[X.ndim - 1] != n_features: # <<<<<<<<<<<<<< + * raise ValueError("query data dimension must " + * "match training data dimension") + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = PyNumber_Subtract(__pyx_t_6, __pyx_int_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyObject_GetItem(__pyx_t_7, __pyx_t_5); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_features); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = PyObject_RichCompare(__pyx_t_6, __pyx_t_5, Py_NE); __Pyx_XGOTREF(__pyx_t_7); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1587 + * + * if X.shape[X.ndim - 1] != n_features: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * Xarr_np = X.reshape((-1, n_features)) + */ + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__27, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1587; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_Raise(__pyx_t_7, 0, 0, 0); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1587; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1589 + * raise ValueError("query data dimension must " + * "match training data dimension") + * Xarr_np = X.reshape((-1, n_features)) # <<<<<<<<<<<<<< + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(Xarr_np) + * + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_reshape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_features); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_INCREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_5, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_Xarr_np = __pyx_t_6; + __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1590 + * "match training data dimension") + * Xarr_np = X.reshape((-1, n_features)) + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(Xarr_np) # <<<<<<<<<<<<<< + * + * log_density_arr = np.zeros(Xarr.shape[0], dtype=DTYPE) + */ + if (!(likely(((__pyx_v_Xarr_np) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_Xarr_np, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_v_Xarr_np)); if (unlikely(!__pyx_t_8.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_Xarr = __pyx_t_8; + __pyx_t_8.memview = NULL; + __pyx_t_8.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1592 + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(Xarr_np) + * + * log_density_arr = np.zeros(Xarr.shape[0], dtype=DTYPE) # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] log_density = get_memview_DTYPE_1D(log_density_arr) + * + */ + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_zeros); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyInt_FromSsize_t((__pyx_v_Xarr.shape[0])); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_7, __pyx_t_6); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_log_density_arr = __pyx_t_4; + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1593 + * + * log_density_arr = np.zeros(Xarr.shape[0], dtype=DTYPE) + * cdef DTYPE_t[::1] log_density = get_memview_DTYPE_1D(log_density_arr) # <<<<<<<<<<<<<< + * + * cdef DTYPE_t* pt = &Xarr[0, 0] + */ + if (!(likely(((__pyx_v_log_density_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_log_density_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_log_density_arr)); if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_log_density = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1595 + * cdef DTYPE_t[::1] log_density = get_memview_DTYPE_1D(log_density_arr) + * + * cdef DTYPE_t* pt = &Xarr[0, 0] # <<<<<<<<<<<<<< + * + * cdef NodeHeap nodeheap + */ + __pyx_t_10 = 0; + __pyx_t_11 = 0; + __pyx_v_pt = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_Xarr.data + __pyx_t_10 * __pyx_v_Xarr.strides[0]) )) + __pyx_t_11)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1598 + * + * cdef NodeHeap nodeheap + * if breadth_first: # <<<<<<<<<<<<<< + * nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) + * cdef DTYPE_t[::1] node_log_min_bounds + */ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_breadth_first); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1599 + * cdef NodeHeap nodeheap + * if breadth_first: + * nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] node_log_min_bounds + * cdef DTYPE_t[::1] node_bound_widths + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = PyInt_FromSsize_t(((__pyx_v_self->data.shape[0]) / __pyx_v_self->leaf_size)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_7kd_tree_NodeHeap)), __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_nodeheap = ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L5; + } + __pyx_L5:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1605 + * # this is difficult because of the need to cache values + * # computed between node pairs. + * if breadth_first: # <<<<<<<<<<<<<< + * node_log_min_bounds_arr = -np.inf + np.zeros(self.n_nodes) + * node_log_min_bounds = get_memview_DTYPE_1D(node_log_min_bounds_arr) + */ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_breadth_first); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1605; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1606 + * # computed between node pairs. + * if breadth_first: + * node_log_min_bounds_arr = -np.inf + np.zeros(self.n_nodes) # <<<<<<<<<<<<<< + * node_log_min_bounds = get_memview_DTYPE_1D(node_log_min_bounds_arr) + * node_bound_widths_arr = np.zeros(self.n_nodes) + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_inf); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_Negative(__pyx_t_6); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_zeros); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_nodes); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_5, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyNumber_Add(__pyx_t_4, __pyx_t_6); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_node_log_min_bounds_arr = __pyx_t_5; + __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1607 + * if breadth_first: + * node_log_min_bounds_arr = -np.inf + np.zeros(self.n_nodes) + * node_log_min_bounds = get_memview_DTYPE_1D(node_log_min_bounds_arr) # <<<<<<<<<<<<<< + * node_bound_widths_arr = np.zeros(self.n_nodes) + * node_bound_widths = get_memview_DTYPE_1D(node_bound_widths_arr) + */ + if (!(likely(((__pyx_v_node_log_min_bounds_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_node_log_min_bounds_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1607; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_node_log_min_bounds_arr)); if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1607; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_node_log_min_bounds = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1608 + * node_log_min_bounds_arr = -np.inf + np.zeros(self.n_nodes) + * node_log_min_bounds = get_memview_DTYPE_1D(node_log_min_bounds_arr) + * node_bound_widths_arr = np.zeros(self.n_nodes) # <<<<<<<<<<<<<< + * node_bound_widths = get_memview_DTYPE_1D(node_bound_widths_arr) + * for i in range(Xarr.shape[0]): + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_nodes); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_4, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_node_bound_widths_arr = __pyx_t_5; + __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1609 + * node_log_min_bounds = get_memview_DTYPE_1D(node_log_min_bounds_arr) + * node_bound_widths_arr = np.zeros(self.n_nodes) + * node_bound_widths = get_memview_DTYPE_1D(node_bound_widths_arr) # <<<<<<<<<<<<<< + * for i in range(Xarr.shape[0]): + * log_density[i] = self._kde_single_breadthfirst( + */ + if (!(likely(((__pyx_v_node_bound_widths_arr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_node_bound_widths_arr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_node_bound_widths_arr)); if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_node_bound_widths = __pyx_t_9; + __pyx_t_9.memview = NULL; + __pyx_t_9.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1610 + * node_bound_widths_arr = np.zeros(self.n_nodes) + * node_bound_widths = get_memview_DTYPE_1D(node_bound_widths_arr) + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * log_density[i] = self._kde_single_breadthfirst( + * pt, kernel_c, h_c, + */ + __pyx_t_12 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1614 + * pt, kernel_c, h_c, + * log_knorm, log_atol, log_rtol, + * nodeheap, # <<<<<<<<<<<<<< + * &node_log_min_bounds[0], + * &node_bound_widths[0]) + */ + if (unlikely(!__pyx_v_nodeheap)) { __Pyx_RaiseUnboundLocalError("nodeheap"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1615 + * log_knorm, log_atol, log_rtol, + * nodeheap, + * &node_log_min_bounds[0], # <<<<<<<<<<<<<< + * &node_bound_widths[0]) + * pt += n_features + */ + __pyx_t_14 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1616 + * nodeheap, + * &node_log_min_bounds[0], + * &node_bound_widths[0]) # <<<<<<<<<<<<<< + * pt += n_features + * else: + */ + __pyx_t_15 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1611 + * node_bound_widths = get_memview_DTYPE_1D(node_bound_widths_arr) + * for i in range(Xarr.shape[0]): + * log_density[i] = self._kde_single_breadthfirst( # <<<<<<<<<<<<<< + * pt, kernel_c, h_c, + * log_knorm, log_atol, log_rtol, + */ + __pyx_t_16 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_log_density.data) + __pyx_t_16)) )) = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_kde_single_breadthfirst(__pyx_v_self, __pyx_v_pt, __pyx_v_kernel_c, __pyx_v_h_c, __pyx_v_log_knorm, __pyx_v_log_atol, __pyx_v_log_rtol, __pyx_v_nodeheap, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_node_log_min_bounds.data) + __pyx_t_14)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_node_bound_widths.data) + __pyx_t_15)) ))))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1617 + * &node_log_min_bounds[0], + * &node_bound_widths[0]) + * pt += n_features # <<<<<<<<<<<<<< + * else: + * for i in range(Xarr.shape[0]): + */ + __pyx_v_pt = (__pyx_v_pt + __pyx_v_n_features); + } + goto __pyx_L6; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1619 + * pt += n_features + * else: + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * min_max_dist(self, 0, pt, &dist_LB, &dist_UB) + * # compute max & min bounds on density within top node + */ + __pyx_t_12 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1620 + * else: + * for i in range(Xarr.shape[0]): + * min_max_dist(self, 0, pt, &dist_LB, &dist_UB) # <<<<<<<<<<<<<< + * # compute max & min bounds on density within top node + * log_min_bound = (log(n_samples) + + */ + __pyx_t_17 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_max_dist(__pyx_v_self, 0, __pyx_v_pt, (&__pyx_v_dist_LB), (&__pyx_v_dist_UB)); if (unlikely(__pyx_t_17 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1620; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1622 + * min_max_dist(self, 0, pt, &dist_LB, &dist_UB) + * # compute max & min bounds on density within top node + * log_min_bound = (log(n_samples) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_UB, + * h_c, kernel_c)) + */ + __pyx_v_log_min_bound = (log(__pyx_v_n_samples) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_UB, __pyx_v_h_c, __pyx_v_kernel_c)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1625 + * compute_log_kernel(dist_UB, + * h_c, kernel_c)) + * log_max_bound = (log(n_samples) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_LB, + * h_c, kernel_c)) + */ + __pyx_v_log_max_bound = (log(__pyx_v_n_samples) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_LB, __pyx_v_h_c, __pyx_v_kernel_c)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1628 + * compute_log_kernel(dist_LB, + * h_c, kernel_c)) + * log_bound_spread = logsubexp(log_max_bound, log_min_bound) # <<<<<<<<<<<<<< + * self._kde_single_depthfirst(0, pt, kernel_c, h_c, + * log_knorm, log_atol, log_rtol, + */ + __pyx_v_log_bound_spread = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp(__pyx_v_log_max_bound, __pyx_v_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1629 + * h_c, kernel_c)) + * log_bound_spread = logsubexp(log_max_bound, log_min_bound) + * self._kde_single_depthfirst(0, pt, kernel_c, h_c, # <<<<<<<<<<<<<< + * log_knorm, log_atol, log_rtol, + * log_min_bound, + */ + __pyx_t_17 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_kde_single_depthfirst(__pyx_v_self, 0, __pyx_v_pt, __pyx_v_kernel_c, __pyx_v_h_c, __pyx_v_log_knorm, __pyx_v_log_atol, __pyx_v_log_rtol, __pyx_v_log_min_bound, __pyx_v_log_bound_spread, (&__pyx_v_log_min_bound), (&__pyx_v_log_bound_spread)); if (unlikely(__pyx_t_17 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1629; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1635 + * &log_min_bound, + * &log_bound_spread) + * log_density[i] = logaddexp(log_min_bound, # <<<<<<<<<<<<<< + * log_bound_spread - log(2)) + * pt += n_features + */ + __pyx_t_18 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_log_density.data) + __pyx_t_18)) )) = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_v_log_min_bound, (__pyx_v_log_bound_spread - log(2.0))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1637 + * log_density[i] = logaddexp(log_min_bound, + * log_bound_spread - log(2)) + * pt += n_features # <<<<<<<<<<<<<< + * + * # normalize the results + */ + __pyx_v_pt = (__pyx_v_pt + __pyx_v_n_features); + } + } + __pyx_L6:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1640 + * + * # normalize the results + * for i in range(log_density.shape[0]): # <<<<<<<<<<<<<< + * log_density[i] += log_knorm + * + */ + __pyx_t_12 = (__pyx_v_log_density.shape[0]); + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1641 + * # normalize the results + * for i in range(log_density.shape[0]): + * log_density[i] += log_knorm # <<<<<<<<<<<<<< + * + * log_density_arr = log_density_arr.reshape(X.shape[:X.ndim - 1]) + */ + __pyx_t_19 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_log_density.data) + __pyx_t_19)) )) += __pyx_v_log_knorm; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1643 + * log_density[i] += log_knorm + * + * log_density_arr = log_density_arr.reshape(X.shape[:X.ndim - 1]) # <<<<<<<<<<<<<< + * + * if return_log: + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_log_density_arr, __pyx_n_s_reshape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyNumber_Subtract(__pyx_t_6, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_GetSlice(__pyx_t_4, 0, 0, NULL, &__pyx_t_7, NULL, 0, 0, 0); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF_SET(__pyx_v_log_density_arr, __pyx_t_6); + __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1645 + * log_density_arr = log_density_arr.reshape(X.shape[:X.ndim - 1]) + * + * if return_log: # <<<<<<<<<<<<<< + * return log_density_arr + * else: + */ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_return_log); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1646 + * + * if return_log: + * return log_density_arr # <<<<<<<<<<<<<< + * else: + * return np.exp(log_density_arr) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_log_density_arr); + __pyx_r = __pyx_v_log_density_arr; + goto __pyx_L0; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1648 + * return log_density_arr + * else: + * return np.exp(log_density_arr) # <<<<<<<<<<<<<< + * + * def two_point_correlation(self, X, r, dualtree=False): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_exp); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_INCREF(__pyx_v_log_density_arr); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_v_log_density_arr); + __Pyx_GIVEREF(__pyx_v_log_density_arr); + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1499 + * return indices.reshape(X.shape[:X.ndim - 1]) + * + * def kernel_density(self, X, h, kernel='gaussian', # <<<<<<<<<<<<<< + * atol=0, rtol=1E-8, + * breadth_first=True, return_log=False): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __PYX_XDEC_MEMVIEW(&__pyx_t_8, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_9, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.kernel_density", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_Xarr_np); + __PYX_XDEC_MEMVIEW(&__pyx_v_Xarr, 1); + __Pyx_XDECREF(__pyx_v_log_density_arr); + __PYX_XDEC_MEMVIEW(&__pyx_v_log_density, 1); + __Pyx_XDECREF((PyObject *)__pyx_v_nodeheap); + __PYX_XDEC_MEMVIEW(&__pyx_v_node_log_min_bounds, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_node_bound_widths, 1); + __Pyx_XDECREF(__pyx_v_node_log_min_bounds_arr); + __Pyx_XDECREF(__pyx_v_node_bound_widths_arr); + __Pyx_XDECREF(__pyx_v_X); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1650 + * return np.exp(log_density_arr) + * + * def two_point_correlation(self, X, r, dualtree=False): # <<<<<<<<<<<<<< + * """Compute the two-point correlation function + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_25two_point_correlation(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_24two_point_correlation[] = "Compute the two-point correlation function\n\n Parameters\n ----------\n X : array_like\n An array of points to query. Last dimension should match dimension\n of training data.\n r : array_like\n A one-dimensional array of distances\n dualtree : boolean (default = False)\n If true, use a dualtree algorithm. Otherwise, use a single-tree\n algorithm. Dual tree algorithms can have better scaling for\n large N.\n\n Returns\n -------\n counts : ndarray\n counts[i] contains the number of pairs of points with distance\n less than or equal to r[i]\n\n Examples\n --------\n Compute the two-point autocorrelation function of X:\n\n >>> import numpy as np\n >>> np.random.seed(0)\n >>> X = np.random.random((30, 3))\n >>> r = np.linspace(0, 1, 5)\n >>> tree = BinaryTree(X) # doctest: +SKIP\n >>> tree.two_point_correlation(X, r)\n array([ 30, 62, 278, 580, 820])\n "; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_25two_point_correlation(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_X = 0; + PyObject *__pyx_v_r = 0; + PyObject *__pyx_v_dualtree = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("two_point_correlation (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_r,&__pyx_n_s_dualtree,0}; + PyObject* values[3] = {0,0,0}; + values[2] = ((PyObject *)Py_False); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_r)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("two_point_correlation", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1650; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dualtree); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "two_point_correlation") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1650; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_X = values[0]; + __pyx_v_r = values[1]; + __pyx_v_dualtree = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("two_point_correlation", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1650; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.two_point_correlation", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_24two_point_correlation(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self), __pyx_v_X, __pyx_v_r, __pyx_v_dualtree); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_24two_point_correlation(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_X, PyObject *__pyx_v_r, PyObject *__pyx_v_dualtree) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + PyObject *__pyx_v_np_Xarr = NULL; + __Pyx_memviewslice __pyx_v_Xarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_i_rsort = NULL; + PyObject *__pyx_v_rarr_np = NULL; + __Pyx_memviewslice __pyx_v_rarr = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_v_count = NULL; + __Pyx_memviewslice __pyx_v_carr = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt; + PyObject *__pyx_v_other = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_8 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + int __pyx_t_13; + Py_ssize_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + Py_ssize_t __pyx_t_16; + Py_ssize_t __pyx_t_17; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("two_point_correlation", 0); + __Pyx_INCREF(__pyx_v_X); + __Pyx_INCREF(__pyx_v_r); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1683 + * array([ 30, 62, 278, 580, 820]) + * """ + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef ITYPE_t i + * + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1683; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1687 + * + * # validate X and prepare for query + * X = check_array(X, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_check_array); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1689 + * X = check_array(X, dtype=DTYPE, order='C') + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: # <<<<<<<<<<<<<< + * raise ValueError("query data dimension must " + * "match training data dimension") + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyNumber_Subtract(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_GetItem(__pyx_t_4, __pyx_t_2); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_t_2, Py_NE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1690 + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__28, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1690; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1690; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1693 + * "match training data dimension") + * + * np_Xarr = X.reshape((-1, self.data.shape[1])) # <<<<<<<<<<<<<< + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(np_Xarr) + * + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_reshape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = PyInt_FromSsize_t((__pyx_v_self->data.shape[1])); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_np_Xarr = __pyx_t_3; + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1694 + * + * np_Xarr = X.reshape((-1, self.data.shape[1])) + * cdef DTYPE_t[:, ::1] Xarr = get_memview_DTYPE_2D(np_Xarr) # <<<<<<<<<<<<<< + * + * # prepare r for query + */ + if (!(likely(((__pyx_v_np_Xarr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_np_Xarr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1694; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_2D(((PyArrayObject *)__pyx_v_np_Xarr)); if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1694; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_Xarr = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1697 + * + * # prepare r for query + * r = np.asarray(r, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * r = np.atleast_1d(r) + * if r.ndim != 1: + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_r); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_r); + __Pyx_GIVEREF(__pyx_v_r); + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1697; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF_SET(__pyx_v_r, __pyx_t_1); + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1698 + * # prepare r for query + * r = np.asarray(r, dtype=DTYPE, order='C') + * r = np.atleast_1d(r) # <<<<<<<<<<<<<< + * if r.ndim != 1: + * raise ValueError("r must be a 1-dimensional array") + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_atleast_1d); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_r); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_r); + __Pyx_GIVEREF(__pyx_v_r); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_1, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF_SET(__pyx_v_r, __pyx_t_3); + __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1699 + * r = np.asarray(r, dtype=DTYPE, order='C') + * r = np.atleast_1d(r) + * if r.ndim != 1: # <<<<<<<<<<<<<< + * raise ValueError("r must be a 1-dimensional array") + * i_rsort = np.argsort(r) + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_r, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyObject_RichCompare(__pyx_t_3, __pyx_int_1, Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1700 + * r = np.atleast_1d(r) + * if r.ndim != 1: + * raise ValueError("r must be a 1-dimensional array") # <<<<<<<<<<<<<< + * i_rsort = np.argsort(r) + * rarr_np = r[i_rsort] # needed to keep memory in scope + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__29, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1701 + * if r.ndim != 1: + * raise ValueError("r must be a 1-dimensional array") + * i_rsort = np.argsort(r) # <<<<<<<<<<<<<< + * rarr_np = r[i_rsort] # needed to keep memory in scope + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1701; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_argsort); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1701; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1701; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_r); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_r); + __Pyx_GIVEREF(__pyx_v_r); + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_1, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1701; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_i_rsort = __pyx_t_4; + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1702 + * raise ValueError("r must be a 1-dimensional array") + * i_rsort = np.argsort(r) + * rarr_np = r[i_rsort] # needed to keep memory in scope # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) + * + */ + __pyx_t_4 = PyObject_GetItem(__pyx_v_r, __pyx_v_i_rsort); if (unlikely(__pyx_t_4 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1702; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_rarr_np = __pyx_t_4; + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1703 + * i_rsort = np.argsort(r) + * rarr_np = r[i_rsort] # needed to keep memory in scope + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) # <<<<<<<<<<<<<< + * + * # create array to hold counts + */ + if (!(likely(((__pyx_v_rarr_np) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_rarr_np, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_1D(((PyArrayObject *)__pyx_v_rarr_np)); if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_rarr = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1706 + * + * # create array to hold counts + * count = np.zeros(r.shape[0], dtype=ITYPE) # <<<<<<<<<<<<<< + * cdef ITYPE_t[::1] carr = get_memview_ITYPE_1D(count) + * + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_r, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_4, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_count = __pyx_t_2; + __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1707 + * # create array to hold counts + * count = np.zeros(r.shape[0], dtype=ITYPE) + * cdef ITYPE_t[::1] carr = get_memview_ITYPE_1D(count) # <<<<<<<<<<<<<< + * + * cdef DTYPE_t* pt = &Xarr[0, 0] + */ + if (!(likely(((__pyx_v_count) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_count, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1707; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_ITYPE_1D(((PyArrayObject *)__pyx_v_count)); if (unlikely(!__pyx_t_8.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1707; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_carr = __pyx_t_8; + __pyx_t_8.memview = NULL; + __pyx_t_8.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1709 + * cdef ITYPE_t[::1] carr = get_memview_ITYPE_1D(count) + * + * cdef DTYPE_t* pt = &Xarr[0, 0] # <<<<<<<<<<<<<< + * + * if dualtree: + */ + __pyx_t_9 = 0; + __pyx_t_10 = 0; + __pyx_v_pt = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_Xarr.data + __pyx_t_9 * __pyx_v_Xarr.strides[0]) )) + __pyx_t_10)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1711 + * cdef DTYPE_t* pt = &Xarr[0, 0] + * + * if dualtree: # <<<<<<<<<<<<<< + * other = self.__class__(Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) + */ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_dualtree); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1711; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1712 + * + * if dualtree: + * other = self.__class__(Xarr, metric=self.dist_metric, # <<<<<<<<<<<<<< + * leaf_size=self.leaf_size) + * self._two_point_dual(0, other, 0, &rarr[0], &carr[0], + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_Xarr, 2, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_metric, ((PyObject *)__pyx_v_self->dist_metric)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1713 + * if dualtree: + * other = self.__class__(Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) # <<<<<<<<<<<<<< + * self._two_point_dual(0, other, 0, &rarr[0], &carr[0], + * 0, rarr.shape[0]) + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->leaf_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_leaf_size, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1712 + * + * if dualtree: + * other = self.__class__(Xarr, metric=self.dist_metric, # <<<<<<<<<<<<<< + * leaf_size=self.leaf_size) + * self._two_point_dual(0, other, 0, &rarr[0], &carr[0], + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_other = __pyx_t_1; + __pyx_t_1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1714 + * other = self.__class__(Xarr, metric=self.dist_metric, + * leaf_size=self.leaf_size) + * self._two_point_dual(0, other, 0, &rarr[0], &carr[0], # <<<<<<<<<<<<<< + * 0, rarr.shape[0]) + * else: + */ + if (!(likely(((__pyx_v_other) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_other, __pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1714; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = 0; + __pyx_t_12 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1715 + * leaf_size=self.leaf_size) + * self._two_point_dual(0, other, 0, &rarr[0], &carr[0], + * 0, rarr.shape[0]) # <<<<<<<<<<<<<< + * else: + * for i in range(Xarr.shape[0]): + */ + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_dual(__pyx_v_self, 0, ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_other), 0, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_rarr.data) + __pyx_t_11)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_carr.data) + __pyx_t_12)) )))), 0, (__pyx_v_rarr.shape[0])); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1714; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1717 + * 0, rarr.shape[0]) + * else: + * for i in range(Xarr.shape[0]): # <<<<<<<<<<<<<< + * self._two_point_single(0, pt, &rarr[0], &carr[0], + * 0, rarr.shape[0]) + */ + __pyx_t_14 = (__pyx_v_Xarr.shape[0]); + for (__pyx_t_15 = 0; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { + __pyx_v_i = __pyx_t_15; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1718 + * else: + * for i in range(Xarr.shape[0]): + * self._two_point_single(0, pt, &rarr[0], &carr[0], # <<<<<<<<<<<<<< + * 0, rarr.shape[0]) + * pt += n_features + */ + __pyx_t_16 = 0; + __pyx_t_17 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1719 + * for i in range(Xarr.shape[0]): + * self._two_point_single(0, pt, &rarr[0], &carr[0], + * 0, rarr.shape[0]) # <<<<<<<<<<<<<< + * pt += n_features + * + */ + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_single(__pyx_v_self, 0, __pyx_v_pt, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_rarr.data) + __pyx_t_16)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_carr.data) + __pyx_t_17)) )))), 0, (__pyx_v_rarr.shape[0])); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1720 + * self._two_point_single(0, pt, &rarr[0], &carr[0], + * 0, rarr.shape[0]) + * pt += n_features # <<<<<<<<<<<<<< + * + * return count + */ + __pyx_v_pt = (__pyx_v_pt + __pyx_v_n_features); + } + } + __pyx_L5:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1722 + * pt += n_features + * + * return count # <<<<<<<<<<<<<< + * + * cdef int _query_single_depthfirst(self, ITYPE_t i_node, + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_count); + __pyx_r = __pyx_v_count; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1650 + * return np.exp(log_density_arr) + * + * def two_point_correlation(self, X, r, dualtree=False): # <<<<<<<<<<<<<< + * """Compute the two-point correlation function + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_8, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.two_point_correlation", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_np_Xarr); + __PYX_XDEC_MEMVIEW(&__pyx_v_Xarr, 1); + __Pyx_XDECREF(__pyx_v_i_rsort); + __Pyx_XDECREF(__pyx_v_rarr_np); + __PYX_XDEC_MEMVIEW(&__pyx_v_rarr, 1); + __Pyx_XDECREF(__pyx_v_count); + __PYX_XDEC_MEMVIEW(&__pyx_v_carr, 1); + __Pyx_XDECREF(__pyx_v_other); + __Pyx_XDECREF(__pyx_v_X); + __Pyx_XDECREF(__pyx_v_r); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1724 + * return count + * + * cdef int _query_single_depthfirst(self, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt, ITYPE_t i_pt, + * NeighborsHeap heap, + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__query_single_depthfirst(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_pt, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_heap, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB) { + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + int __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_query_single_depthfirst", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1729 + * DTYPE_t reduced_dist_LB) except -1: + * """Recursive Single-tree k-neighbors query, depth-first approach""" + * cdef NodeData_t node_info = self.node_data[i_node] # <<<<<<<<<<<<<< + * + * cdef DTYPE_t dist_pt, reduced_dist_LB_1, reduced_dist_LB_2 + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1729; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_v_i_node; + __pyx_v_node_info = (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_1)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1734 + * cdef ITYPE_t i, i1, i2 + * + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1734; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_2 * __pyx_v_self->data.strides[0]) )) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1739 + * # Case 1: query point is outside node radius: + * # trim it from the query + * if reduced_dist_LB > heap.largest(i_pt): # <<<<<<<<<<<<<< + * self.n_trims += 1 + * + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = ((__pyx_v_reduced_dist_LB > __pyx_t_4) != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1740 + * # trim it from the query + * if reduced_dist_LB > heap.largest(i_pt): + * self.n_trims += 1 # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_v_self->n_trims = (__pyx_v_self->n_trims + 1); + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1744 + * #------------------------------------------------------------ + * # Case 2: this is a leaf node. Update set of nearby points + * elif node_info.is_leaf: # <<<<<<<<<<<<<< + * self.n_leaves += 1 + * for i in range(node_info.idx_start, node_info.idx_end): + */ + __pyx_t_5 = (__pyx_v_node_info.is_leaf != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1745 + * # Case 2: this is a leaf node. Update set of nearby points + * elif node_info.is_leaf: + * self.n_leaves += 1 # <<<<<<<<<<<<<< + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.rdist(pt, + */ + __pyx_v_self->n_leaves = (__pyx_v_self->n_leaves + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1746 + * elif node_info.is_leaf: + * self.n_leaves += 1 + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], + */ + __pyx_t_6 = __pyx_v_node_info.idx_end; + for (__pyx_t_7 = __pyx_v_node_info.idx_start; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1748 + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], # <<<<<<<<<<<<<< + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1748; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1748; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_8 = __pyx_v_i; + __pyx_t_9 = (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_8)) ))); + __pyx_t_10 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1749 + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) # <<<<<<<<<<<<<< + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i]) + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1749; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1747 + * self.n_leaves += 1 + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.rdist(pt, # <<<<<<<<<<<<<< + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_rdist(__pyx_v_self, __pyx_v_pt, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_9 * __pyx_v_self->data.strides[0]) )) + __pyx_t_10)) )))), (__pyx_v_self->data.shape[1])); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1747; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1750 + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): # <<<<<<<<<<<<<< + * heap.push(i_pt, dist_pt, self.idx_array[i]) + * + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1750; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = ((__pyx_v_dist_pt < __pyx_t_4) != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1751 + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i]) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1751; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_11 = __pyx_v_i; + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_i_pt, __pyx_v_dist_pt, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_11)) ))), 0); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + } + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1757 + * # starting with the closest + * else: + * self.n_splits += 1 # <<<<<<<<<<<<<< + * i1 = 2 * i_node + 1 + * i2 = i1 + 1 + */ + __pyx_v_self->n_splits = (__pyx_v_self->n_splits + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1758 + * else: + * self.n_splits += 1 + * i1 = 2 * i_node + 1 # <<<<<<<<<<<<<< + * i2 = i1 + 1 + * reduced_dist_LB_1 = min_rdist(self, i1, pt) + */ + __pyx_v_i1 = ((2 * __pyx_v_i_node) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1759 + * self.n_splits += 1 + * i1 = 2 * i_node + 1 + * i2 = i1 + 1 # <<<<<<<<<<<<<< + * reduced_dist_LB_1 = min_rdist(self, i1, pt) + * reduced_dist_LB_2 = min_rdist(self, i2, pt) + */ + __pyx_v_i2 = (__pyx_v_i1 + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1760 + * i1 = 2 * i_node + 1 + * i2 = i1 + 1 + * reduced_dist_LB_1 = min_rdist(self, i1, pt) # <<<<<<<<<<<<<< + * reduced_dist_LB_2 = min_rdist(self, i2, pt) + * + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist(__pyx_v_self, __pyx_v_i1, __pyx_v_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB_1 = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1761 + * i2 = i1 + 1 + * reduced_dist_LB_1 = min_rdist(self, i1, pt) + * reduced_dist_LB_2 = min_rdist(self, i2, pt) # <<<<<<<<<<<<<< + * + * # recursively query subnodes + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist(__pyx_v_self, __pyx_v_i2, __pyx_v_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1761; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB_2 = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1764 + * + * # recursively query subnodes + * if reduced_dist_LB_1 <= reduced_dist_LB_2: # <<<<<<<<<<<<<< + * self._query_single_depthfirst(i1, pt, i_pt, heap, + * reduced_dist_LB_1) + */ + __pyx_t_5 = ((__pyx_v_reduced_dist_LB_1 <= __pyx_v_reduced_dist_LB_2) != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1765 + * # recursively query subnodes + * if reduced_dist_LB_1 <= reduced_dist_LB_2: + * self._query_single_depthfirst(i1, pt, i_pt, heap, # <<<<<<<<<<<<<< + * reduced_dist_LB_1) + * self._query_single_depthfirst(i2, pt, i_pt, heap, + */ + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_depthfirst(__pyx_v_self, __pyx_v_i1, __pyx_v_pt, __pyx_v_i_pt, __pyx_v_heap, __pyx_v_reduced_dist_LB_1); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1767 + * self._query_single_depthfirst(i1, pt, i_pt, heap, + * reduced_dist_LB_1) + * self._query_single_depthfirst(i2, pt, i_pt, heap, # <<<<<<<<<<<<<< + * reduced_dist_LB_2) + * else: + */ + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_depthfirst(__pyx_v_self, __pyx_v_i2, __pyx_v_pt, __pyx_v_i_pt, __pyx_v_heap, __pyx_v_reduced_dist_LB_2); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1770 + * reduced_dist_LB_2) + * else: + * self._query_single_depthfirst(i2, pt, i_pt, heap, # <<<<<<<<<<<<<< + * reduced_dist_LB_2) + * self._query_single_depthfirst(i1, pt, i_pt, heap, + */ + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_depthfirst(__pyx_v_self, __pyx_v_i2, __pyx_v_pt, __pyx_v_i_pt, __pyx_v_heap, __pyx_v_reduced_dist_LB_2); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1770; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1772 + * self._query_single_depthfirst(i2, pt, i_pt, heap, + * reduced_dist_LB_2) + * self._query_single_depthfirst(i1, pt, i_pt, heap, # <<<<<<<<<<<<<< + * reduced_dist_LB_1) + * return 0 + */ + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_single_depthfirst(__pyx_v_self, __pyx_v_i1, __pyx_v_pt, __pyx_v_i_pt, __pyx_v_heap, __pyx_v_reduced_dist_LB_1); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1774 + * self._query_single_depthfirst(i1, pt, i_pt, heap, + * reduced_dist_LB_1) + * return 0 # <<<<<<<<<<<<<< + * + * cdef int _query_single_breadthfirst(self, DTYPE_t* pt, + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1724 + * return count + * + * cdef int _query_single_depthfirst(self, ITYPE_t i_node, # <<<<<<<<<<<<<< + * DTYPE_t* pt, ITYPE_t i_pt, + * NeighborsHeap heap, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree._query_single_depthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1776 + * return 0 + * + * cdef int _query_single_breadthfirst(self, DTYPE_t* pt, # <<<<<<<<<<<<<< + * ITYPE_t i_pt, + * NeighborsHeap heap, + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__query_single_breadthfirst(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_pt, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_heap, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_nodeheap) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *__pyx_v_node_data; + CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_v_nodeheap_item; + CYTHON_UNUSED struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + long __pyx_t_13; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_query_single_breadthfirst", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1783 + * cdef ITYPE_t i, i_node + * cdef DTYPE_t dist_pt, reduced_dist_LB + * cdef NodeData_t* node_data = &self.node_data[0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data = &self.data[0, 0] + * + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1783; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_v_node_data = (&(*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_1)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1784 + * cdef DTYPE_t dist_pt, reduced_dist_LB + * cdef NodeData_t* node_data = &self.node_data[0] + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * + * # Set up the node heap and push the head node onto it + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1784; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_2 * __pyx_v_self->data.strides[0]) )) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1788 + * # Set up the node heap and push the head node onto it + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_rdist(self, 0, pt) # <<<<<<<<<<<<<< + * nodeheap_item.i1 = 0 + * nodeheap.push(nodeheap_item) + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist(__pyx_v_self, 0, __pyx_v_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1788; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1789 + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_rdist(self, 0, pt) + * nodeheap_item.i1 = 0 # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) + * + */ + __pyx_v_nodeheap_item.i1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1790 + * nodeheap_item.val = min_rdist(self, 0, pt) + * nodeheap_item.i1 = 0 + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * + * while nodeheap.n > 0: + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1792 + * nodeheap.push(nodeheap_item) + * + * while nodeheap.n > 0: # <<<<<<<<<<<<<< + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val + */ + while (1) { + __pyx_t_6 = ((__pyx_v_nodeheap->n > 0) != 0); + if (!__pyx_t_6) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1793 + * + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() # <<<<<<<<<<<<<< + * reduced_dist_LB = nodeheap_item.val + * i_node = nodeheap_item.i1 + */ + __pyx_v_nodeheap_item = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->pop(__pyx_v_nodeheap); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1794 + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val # <<<<<<<<<<<<<< + * i_node = nodeheap_item.i1 + * node_info = node_data[i_node] + */ + __pyx_t_4 = __pyx_v_nodeheap_item.val; + __pyx_v_reduced_dist_LB = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1795 + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val + * i_node = nodeheap_item.i1 # <<<<<<<<<<<<<< + * node_info = node_data[i_node] + * + */ + __pyx_t_7 = __pyx_v_nodeheap_item.i1; + __pyx_v_i_node = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1796 + * reduced_dist_LB = nodeheap_item.val + * i_node = nodeheap_item.i1 + * node_info = node_data[i_node] # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_v_node_info = (__pyx_v_node_data[__pyx_v_i_node]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1801 + * # Case 1: query point is outside node radius: + * # trim it from the query + * if reduced_dist_LB > heap.largest(i_pt): # <<<<<<<<<<<<<< + * self.n_trims += 1 + * + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((__pyx_v_reduced_dist_LB > __pyx_t_4) != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1802 + * # trim it from the query + * if reduced_dist_LB > heap.largest(i_pt): + * self.n_trims += 1 # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_v_self->n_trims = (__pyx_v_self->n_trims + 1); + goto __pyx_L5; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1806 + * #------------------------------------------------------------ + * # Case 2: this is a leaf node. Update set of nearby points + * elif node_data[i_node].is_leaf: # <<<<<<<<<<<<<< + * self.n_leaves += 1 + * for i in range(node_data[i_node].idx_start, + */ + __pyx_t_6 = ((__pyx_v_node_data[__pyx_v_i_node]).is_leaf != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1807 + * # Case 2: this is a leaf node. Update set of nearby points + * elif node_data[i_node].is_leaf: + * self.n_leaves += 1 # <<<<<<<<<<<<<< + * for i in range(node_data[i_node].idx_start, + * node_data[i_node].idx_end): + */ + __pyx_v_self->n_leaves = (__pyx_v_self->n_leaves + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1809 + * self.n_leaves += 1 + * for i in range(node_data[i_node].idx_start, + * node_data[i_node].idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], + */ + __pyx_t_7 = (__pyx_v_node_data[__pyx_v_i_node]).idx_end; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1808 + * elif node_data[i_node].is_leaf: + * self.n_leaves += 1 + * for i in range(node_data[i_node].idx_start, # <<<<<<<<<<<<<< + * node_data[i_node].idx_end): + * dist_pt = self.rdist(pt, + */ + for (__pyx_t_8 = (__pyx_v_node_data[__pyx_v_i_node]).idx_start; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1811 + * node_data[i_node].idx_end): + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], # <<<<<<<<<<<<<< + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1811; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1811; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = __pyx_v_i; + __pyx_t_10 = (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_9)) ))); + __pyx_t_11 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1812 + * dist_pt = self.rdist(pt, + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) # <<<<<<<<<<<<<< + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i]) + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1812; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1810 + * for i in range(node_data[i_node].idx_start, + * node_data[i_node].idx_end): + * dist_pt = self.rdist(pt, # <<<<<<<<<<<<<< + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_rdist(__pyx_v_self, __pyx_v_pt, (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_10 * __pyx_v_self->data.strides[0]) )) + __pyx_t_11)) )))), (__pyx_v_self->data.shape[1])); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1810; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1813 + * &self.data[self.idx_array[i], 0], + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): # <<<<<<<<<<<<<< + * heap.push(i_pt, dist_pt, self.idx_array[i]) + * + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((__pyx_v_dist_pt < __pyx_t_4) != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1814 + * self.data.shape[1]) + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i]) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1814; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_12 = __pyx_v_i; + __pyx_t_5 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_i_pt, __pyx_v_dist_pt, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_12)) ))), 0); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1814; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + } + goto __pyx_L5; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1819 + * # Case 3: Node is not a leaf. Add subnodes to the node heap + * else: + * self.n_splits += 1 # <<<<<<<<<<<<<< + * for i in range(2 * i_node + 1, 2 * i_node + 3): + * nodeheap_item.i1 = i + */ + __pyx_v_self->n_splits = (__pyx_v_self->n_splits + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1820 + * else: + * self.n_splits += 1 + * for i in range(2 * i_node + 1, 2 * i_node + 3): # <<<<<<<<<<<<<< + * nodeheap_item.i1 = i + * nodeheap_item.val = min_rdist(self, i, pt) + */ + __pyx_t_13 = ((2 * __pyx_v_i_node) + 3); + for (__pyx_t_7 = ((2 * __pyx_v_i_node) + 1); __pyx_t_7 < __pyx_t_13; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1821 + * self.n_splits += 1 + * for i in range(2 * i_node + 1, 2 * i_node + 3): + * nodeheap_item.i1 = i # <<<<<<<<<<<<<< + * nodeheap_item.val = min_rdist(self, i, pt) + * nodeheap.push(nodeheap_item) + */ + __pyx_v_nodeheap_item.i1 = __pyx_v_i; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1822 + * for i in range(2 * i_node + 1, 2 * i_node + 3): + * nodeheap_item.i1 = i + * nodeheap_item.val = min_rdist(self, i, pt) # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) + * return 0 + */ + __pyx_t_4 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist(__pyx_v_self, __pyx_v_i, __pyx_v_pt); if (unlikely(__pyx_t_4 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1823 + * nodeheap_item.i1 = i + * nodeheap_item.val = min_rdist(self, i, pt) + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + __pyx_L5:; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1824 + * nodeheap_item.val = min_rdist(self, i, pt) + * nodeheap.push(nodeheap_item) + * return 0 # <<<<<<<<<<<<<< + * + * cdef int _query_dual_depthfirst(self, ITYPE_t i_node1, + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1776 + * return 0 + * + * cdef int _query_single_breadthfirst(self, DTYPE_t* pt, # <<<<<<<<<<<<<< + * ITYPE_t i_pt, + * NeighborsHeap heap, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree._query_single_breadthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1826 + * return 0 + * + * cdef int _query_dual_depthfirst(self, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree other, ITYPE_t i_node2, + * DTYPE_t[::1] bounds, + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__query_dual_depthfirst(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_other, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2, __Pyx_memviewslice __pyx_v_bounds, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_heap, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB) { + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info1; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_bound_max; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_parent; + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + int __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_16; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_17; + int __pyx_t_18; + long __pyx_t_19; + long __pyx_t_20; + int __pyx_t_21; + int __pyx_t_22; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_query_dual_depthfirst", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1835 + * # bounds[i] is the largest distance among any of the + * # current neighbors in node i of the other tree. + * cdef NodeData_t node_info1 = self.node_data[i_node1] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info2 = other.node_data[i_node2] + * + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1835; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_v_i_node1; + __pyx_v_node_info1 = (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_1)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1836 + * # current neighbors in node i of the other tree. + * cdef NodeData_t node_info1 = self.node_data[i_node1] + * cdef NodeData_t node_info2 = other.node_data[i_node2] # <<<<<<<<<<<<<< + * + * cdef DTYPE_t* data1 = &self.data[0, 0] + */ + if (unlikely(!__pyx_v_other->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1836; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_2 = __pyx_v_i_node2; + __pyx_v_node_info2 = (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_other->node_data.data) + __pyx_t_2)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1838 + * cdef NodeData_t node_info2 = other.node_data[i_node2] + * + * cdef DTYPE_t* data1 = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1838; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_v_data1 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_3 * __pyx_v_self->data.strides[0]) )) + __pyx_t_4)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1839 + * + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * + */ + if (unlikely(!__pyx_v_other->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1839; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_v_data2 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_other->data.data + __pyx_t_5 * __pyx_v_other->data.strides[0]) )) + __pyx_t_6)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1840 + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * + * cdef DTYPE_t bound_max, dist_pt, reduced_dist_LB1, reduced_dist_LB2 + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1840; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1848 + * # Case 1: nodes are further apart than the current bound: + * # trim both from the query + * if reduced_dist_LB > bounds[i_node2]: # <<<<<<<<<<<<<< + * pass + * + */ + __pyx_t_7 = __pyx_v_i_node2; + __pyx_t_8 = ((__pyx_v_reduced_dist_LB > (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_7)) )))) != 0); + if (__pyx_t_8) { + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1854 + * # Case 2: both nodes are leaves: + * # do a brute-force search comparing all pairs + * elif node_info1.is_leaf and node_info2.is_leaf: # <<<<<<<<<<<<<< + * bounds[i_node2] = 0 + * + */ + if ((__pyx_v_node_info1.is_leaf != 0)) { + __pyx_t_8 = (__pyx_v_node_info2.is_leaf != 0); + } else { + __pyx_t_8 = (__pyx_v_node_info1.is_leaf != 0); + } + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1855 + * # do a brute-force search comparing all pairs + * elif node_info1.is_leaf and node_info2.is_leaf: + * bounds[i_node2] = 0 # <<<<<<<<<<<<<< + * + * for i2 in range(node_info2.idx_start, node_info2.idx_end): + */ + __pyx_t_9 = __pyx_v_i_node2; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_9)) )) = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1857 + * bounds[i_node2] = 0 + * + * for i2 in range(node_info2.idx_start, node_info2.idx_end): # <<<<<<<<<<<<<< + * i_pt = other.idx_array[i2] + * + */ + __pyx_t_10 = __pyx_v_node_info2.idx_end; + for (__pyx_t_11 = __pyx_v_node_info2.idx_start; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) { + __pyx_v_i2 = __pyx_t_11; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1858 + * + * for i2 in range(node_info2.idx_start, node_info2.idx_end): + * i_pt = other.idx_array[i2] # <<<<<<<<<<<<<< + * + * if heap.largest(i_pt) <= reduced_dist_LB: + */ + if (unlikely(!__pyx_v_other->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1858; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_12 = __pyx_v_i2; + __pyx_v_i_pt = (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_other->idx_array.data) + __pyx_t_12)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1860 + * i_pt = other.idx_array[i2] + * + * if heap.largest(i_pt) <= reduced_dist_LB: # <<<<<<<<<<<<<< + * continue + * + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((__pyx_t_13 <= __pyx_v_reduced_dist_LB) != 0); + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1861 + * + * if heap.largest(i_pt) <= reduced_dist_LB: + * continue # <<<<<<<<<<<<<< + * + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + */ + goto __pyx_L4_continue; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1863 + * continue + * + * for i1 in range(node_info1.idx_start, node_info1.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.rdist( + * data1 + n_features * self.idx_array[i1], + */ + __pyx_t_14 = __pyx_v_node_info1.idx_end; + for (__pyx_t_15 = __pyx_v_node_info1.idx_start; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { + __pyx_v_i1 = __pyx_t_15; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1865 + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * dist_pt = self.rdist( + * data1 + n_features * self.idx_array[i1], # <<<<<<<<<<<<<< + * data2 + n_features * i_pt, + * n_features) + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1865; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_16 = __pyx_v_i1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1864 + * + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * dist_pt = self.rdist( # <<<<<<<<<<<<<< + * data1 + n_features * self.idx_array[i1], + * data2 + n_features * i_pt, + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_rdist(__pyx_v_self, (__pyx_v_data1 + (__pyx_v_n_features * (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_16)) ))))), (__pyx_v_data2 + (__pyx_v_n_features * __pyx_v_i_pt)), __pyx_v_n_features); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1864; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1868 + * data2 + n_features * i_pt, + * n_features) + * if dist_pt < heap.largest(i_pt): # <<<<<<<<<<<<<< + * heap.push(i_pt, dist_pt, self.idx_array[i1]) + * + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1868; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((__pyx_v_dist_pt < __pyx_t_13) != 0); + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1869 + * n_features) + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i1]) # <<<<<<<<<<<<<< + * + * # keep track of node bound + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1869; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_17 = __pyx_v_i1; + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_i_pt, __pyx_v_dist_pt, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_17)) ))), 0); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1869; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L9; + } + __pyx_L9:; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1872 + * + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], # <<<<<<<<<<<<<< + * heap.largest(i_pt)) + * + */ + __pyx_t_14 = __pyx_v_i_node2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1873 + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], + * heap.largest(i_pt)) # <<<<<<<<<<<<<< + * + * # update bounds up the tree + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1873; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1872 + * + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], # <<<<<<<<<<<<<< + * heap.largest(i_pt)) + * + */ + __pyx_t_15 = __pyx_v_i_node2; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_15)) )) = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_14)) ))), __pyx_t_13); + __pyx_L4_continue:; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1876 + * + * # update bounds up the tree + * while i_node2 > 0: # <<<<<<<<<<<<<< + * i_parent = (i_node2 - 1) // 2 + * bound_max = fmax(bounds[2 * i_parent + 1], + */ + while (1) { + __pyx_t_8 = ((__pyx_v_i_node2 > 0) != 0); + if (!__pyx_t_8) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1877 + * # update bounds up the tree + * while i_node2 > 0: + * i_parent = (i_node2 - 1) // 2 # <<<<<<<<<<<<<< + * bound_max = fmax(bounds[2 * i_parent + 1], + * bounds[2 * i_parent + 2]) + */ + __pyx_v_i_parent = ((__pyx_v_i_node2 - 1) / 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1878 + * while i_node2 > 0: + * i_parent = (i_node2 - 1) // 2 + * bound_max = fmax(bounds[2 * i_parent + 1], # <<<<<<<<<<<<<< + * bounds[2 * i_parent + 2]) + * if bound_max < bounds[i_parent]: + */ + __pyx_t_19 = ((2 * __pyx_v_i_parent) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1879 + * i_parent = (i_node2 - 1) // 2 + * bound_max = fmax(bounds[2 * i_parent + 1], + * bounds[2 * i_parent + 2]) # <<<<<<<<<<<<<< + * if bound_max < bounds[i_parent]: + * bounds[i_parent] = bound_max + */ + __pyx_t_20 = ((2 * __pyx_v_i_parent) + 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1878 + * while i_node2 > 0: + * i_parent = (i_node2 - 1) // 2 + * bound_max = fmax(bounds[2 * i_parent + 1], # <<<<<<<<<<<<<< + * bounds[2 * i_parent + 2]) + * if bound_max < bounds[i_parent]: + */ + __pyx_v_bound_max = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_19)) ))), (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_20)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1880 + * bound_max = fmax(bounds[2 * i_parent + 1], + * bounds[2 * i_parent + 2]) + * if bound_max < bounds[i_parent]: # <<<<<<<<<<<<<< + * bounds[i_parent] = bound_max + * i_node2 = i_parent + */ + __pyx_t_10 = __pyx_v_i_parent; + __pyx_t_8 = ((__pyx_v_bound_max < (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_10)) )))) != 0); + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1881 + * bounds[2 * i_parent + 2]) + * if bound_max < bounds[i_parent]: + * bounds[i_parent] = bound_max # <<<<<<<<<<<<<< + * i_node2 = i_parent + * else: + */ + __pyx_t_11 = __pyx_v_i_parent; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_11)) )) = __pyx_v_bound_max; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1882 + * if bound_max < bounds[i_parent]: + * bounds[i_parent] = bound_max + * i_node2 = i_parent # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_node2 = __pyx_v_i_parent; + goto __pyx_L12; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1884 + * i_node2 = i_parent + * else: + * break # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + goto __pyx_L11_break; + } + __pyx_L12:; + } + __pyx_L11_break:; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1889 + * # Case 3a: node 1 is a leaf or is smaller: split node 2 and + * # recursively query, starting with the nearest subnode + * elif node_info1.is_leaf or (not node_info2.is_leaf # <<<<<<<<<<<<<< + * and node_info2.radius > node_info1.radius): + * reduced_dist_LB1 = min_rdist_dual(self, i_node1, + */ + if (!(__pyx_v_node_info1.is_leaf != 0)) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1890 + * # recursively query, starting with the nearest subnode + * elif node_info1.is_leaf or (not node_info2.is_leaf + * and node_info2.radius > node_info1.radius): # <<<<<<<<<<<<<< + * reduced_dist_LB1 = min_rdist_dual(self, i_node1, + * other, 2 * i_node2 + 1) + */ + __pyx_t_8 = (!(__pyx_v_node_info2.is_leaf != 0)); + if (__pyx_t_8) { + __pyx_t_21 = (__pyx_v_node_info2.radius > __pyx_v_node_info1.radius); + __pyx_t_22 = __pyx_t_21; + } else { + __pyx_t_22 = __pyx_t_8; + } + __pyx_t_8 = __pyx_t_22; + } else { + __pyx_t_8 = (__pyx_v_node_info1.is_leaf != 0); + } + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1891 + * elif node_info1.is_leaf or (not node_info2.is_leaf + * and node_info2.radius > node_info1.radius): + * reduced_dist_LB1 = min_rdist_dual(self, i_node1, # <<<<<<<<<<<<<< + * other, 2 * i_node2 + 1) + * reduced_dist_LB2 = min_rdist_dual(self, i_node1, + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 1)); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1891; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB1 = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1893 + * reduced_dist_LB1 = min_rdist_dual(self, i_node1, + * other, 2 * i_node2 + 1) + * reduced_dist_LB2 = min_rdist_dual(self, i_node1, # <<<<<<<<<<<<<< + * other, 2 * i_node2 + 2) + * + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 2)); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB2 = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1896 + * other, 2 * i_node2 + 2) + * + * if reduced_dist_LB1 < reduced_dist_LB2: # <<<<<<<<<<<<<< + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, + * bounds, heap, reduced_dist_LB1) + */ + __pyx_t_8 = ((__pyx_v_reduced_dist_LB1 < __pyx_v_reduced_dist_LB2) != 0); + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1897 + * + * if reduced_dist_LB1 < reduced_dist_LB2: + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB1) + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 1), __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB1); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1897; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1899 + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, + * bounds, heap, reduced_dist_LB1) + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB2) + * else: + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 2), __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB2); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1899; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L13; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1902 + * bounds, heap, reduced_dist_LB2) + * else: + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB2) + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 2), __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB2); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1904 + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, + * bounds, heap, reduced_dist_LB2) + * self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB1) + * + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, ((2 * __pyx_v_i_node2) + 1), __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB1); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1904; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L13:; + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1911 + * # recursively query, starting with the nearest subnode + * else: + * reduced_dist_LB1 = min_rdist_dual(self, 2 * i_node1 + 1, # <<<<<<<<<<<<<< + * other, i_node2) + * reduced_dist_LB2 = min_rdist_dual(self, 2 * i_node1 + 2, + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist_dual(__pyx_v_self, ((2 * __pyx_v_i_node1) + 1), __pyx_v_other, __pyx_v_i_node2); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1911; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB1 = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1913 + * reduced_dist_LB1 = min_rdist_dual(self, 2 * i_node1 + 1, + * other, i_node2) + * reduced_dist_LB2 = min_rdist_dual(self, 2 * i_node1 + 2, # <<<<<<<<<<<<<< + * other, i_node2) + * + */ + __pyx_t_13 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist_dual(__pyx_v_self, ((2 * __pyx_v_i_node1) + 2), __pyx_v_other, __pyx_v_i_node2); if (unlikely(__pyx_t_13 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1913; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_dist_LB2 = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1916 + * other, i_node2) + * + * if reduced_dist_LB1 < reduced_dist_LB2: # <<<<<<<<<<<<<< + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, + * bounds, heap, reduced_dist_LB1) + */ + __pyx_t_8 = ((__pyx_v_reduced_dist_LB1 < __pyx_v_reduced_dist_LB2) != 0); + if (__pyx_t_8) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1917 + * + * if reduced_dist_LB1 < reduced_dist_LB2: + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB1) + * self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, ((2 * __pyx_v_i_node1) + 1), __pyx_v_other, __pyx_v_i_node2, __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB1); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1917; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1919 + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, + * bounds, heap, reduced_dist_LB1) + * self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB2) + * else: + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, ((2 * __pyx_v_i_node1) + 2), __pyx_v_other, __pyx_v_i_node2, __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB2); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1919; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1922 + * bounds, heap, reduced_dist_LB2) + * else: + * self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB2) + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, ((2 * __pyx_v_i_node1) + 2), __pyx_v_other, __pyx_v_i_node2, __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB2); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1924 + * self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, + * bounds, heap, reduced_dist_LB2) + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, # <<<<<<<<<<<<<< + * bounds, heap, reduced_dist_LB1) + * return 0 + */ + __pyx_t_18 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_dual_depthfirst(__pyx_v_self, ((2 * __pyx_v_i_node1) + 1), __pyx_v_other, __pyx_v_i_node2, __pyx_v_bounds, __pyx_v_heap, __pyx_v_reduced_dist_LB1); if (unlikely(__pyx_t_18 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1924; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L14:; + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1926 + * self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, + * bounds, heap, reduced_dist_LB1) + * return 0 # <<<<<<<<<<<<<< + * + * cdef int _query_dual_breadthfirst(self, BinaryTree other, + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1826 + * return 0 + * + * cdef int _query_dual_depthfirst(self, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree other, ITYPE_t i_node2, + * DTYPE_t[::1] bounds, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree._query_dual_depthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1928 + * return 0 + * + * cdef int _query_dual_breadthfirst(self, BinaryTree other, # <<<<<<<<<<<<<< + * NeighborsHeap heap, + * NodeHeap nodeheap) except -1: + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__query_dual_breadthfirst(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_other, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_heap, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_nodeheap) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_dist_LB; + __Pyx_memviewslice __pyx_v_bounds = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *__pyx_v_node_data1; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *__pyx_v_node_data2; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info1; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_v_nodeheap_item; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_6; + Py_ssize_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_16; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_17; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_18; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_19; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_20; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_21; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_22; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_23; + int __pyx_t_24; + int __pyx_t_25; + long __pyx_t_26; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_query_dual_breadthfirst", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1934 + * cdef ITYPE_t i, i1, i2, i_node1, i_node2, i_pt + * cdef DTYPE_t dist_pt, reduced_dist_LB + * cdef DTYPE_t[::1] bounds = np.inf + np.zeros(other.node_data.shape[0]) # <<<<<<<<<<<<<< + * cdef NodeData_t* node_data1 = &self.node_data[0] + * cdef NodeData_t* node_data2 = &other.node_data[0] + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_v_other->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = PyInt_FromSsize_t((__pyx_v_other->node_data.shape[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_Add(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(__pyx_t_4); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1934; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_bounds = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1935 + * cdef DTYPE_t dist_pt, reduced_dist_LB + * cdef DTYPE_t[::1] bounds = np.inf + np.zeros(other.node_data.shape[0]) + * cdef NodeData_t* node_data1 = &self.node_data[0] # <<<<<<<<<<<<<< + * cdef NodeData_t* node_data2 = &other.node_data[0] + * cdef NodeData_t node_info1, node_info2 + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1935; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_6 = 0; + __pyx_v_node_data1 = (&(*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_6)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1936 + * cdef DTYPE_t[::1] bounds = np.inf + np.zeros(other.node_data.shape[0]) + * cdef NodeData_t* node_data1 = &self.node_data[0] + * cdef NodeData_t* node_data2 = &other.node_data[0] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info1, node_info2 + * cdef DTYPE_t* data1 = &self.data[0, 0] + */ + if (unlikely(!__pyx_v_other->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1936; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = 0; + __pyx_v_node_data2 = (&(*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_other->node_data.data) + __pyx_t_7)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1938 + * cdef NodeData_t* node_data2 = &other.node_data[0] + * cdef NodeData_t node_info1, node_info2 + * cdef DTYPE_t* data1 = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1938; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_8 = 0; + __pyx_t_9 = 0; + __pyx_v_data1 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_8 * __pyx_v_self->data.strides[0]) )) + __pyx_t_9)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1939 + * cdef NodeData_t node_info1, node_info2 + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * + */ + if (unlikely(!__pyx_v_other->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1939; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = 0; + __pyx_t_11 = 0; + __pyx_v_data2 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_other->data.data + __pyx_t_10 * __pyx_v_other->data.strides[0]) )) + __pyx_t_11)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1940 + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * + * # Set up the node heap and push the head nodes onto it + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1940; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1944 + * # Set up the node heap and push the head nodes onto it + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_rdist_dual(self, 0, other, 0) # <<<<<<<<<<<<<< + * nodeheap_item.i1 = 0 + * nodeheap_item.i2 = 0 + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist_dual(__pyx_v_self, 0, __pyx_v_other, 0); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1945 + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_rdist_dual(self, 0, other, 0) + * nodeheap_item.i1 = 0 # <<<<<<<<<<<<<< + * nodeheap_item.i2 = 0 + * nodeheap.push(nodeheap_item) + */ + __pyx_v_nodeheap_item.i1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1946 + * nodeheap_item.val = min_rdist_dual(self, 0, other, 0) + * nodeheap_item.i1 = 0 + * nodeheap_item.i2 = 0 # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) + * + */ + __pyx_v_nodeheap_item.i2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1947 + * nodeheap_item.i1 = 0 + * nodeheap_item.i2 = 0 + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * + * while nodeheap.n > 0: + */ + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1947; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1949 + * nodeheap.push(nodeheap_item) + * + * while nodeheap.n > 0: # <<<<<<<<<<<<<< + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val + */ + while (1) { + __pyx_t_14 = ((__pyx_v_nodeheap->n > 0) != 0); + if (!__pyx_t_14) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1950 + * + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() # <<<<<<<<<<<<<< + * reduced_dist_LB = nodeheap_item.val + * i_node1 = nodeheap_item.i1 + */ + __pyx_v_nodeheap_item = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->pop(__pyx_v_nodeheap); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1951 + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val # <<<<<<<<<<<<<< + * i_node1 = nodeheap_item.i1 + * i_node2 = nodeheap_item.i2 + */ + __pyx_t_12 = __pyx_v_nodeheap_item.val; + __pyx_v_reduced_dist_LB = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1952 + * nodeheap_item = nodeheap.pop() + * reduced_dist_LB = nodeheap_item.val + * i_node1 = nodeheap_item.i1 # <<<<<<<<<<<<<< + * i_node2 = nodeheap_item.i2 + * + */ + __pyx_t_15 = __pyx_v_nodeheap_item.i1; + __pyx_v_i_node1 = __pyx_t_15; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1953 + * reduced_dist_LB = nodeheap_item.val + * i_node1 = nodeheap_item.i1 + * i_node2 = nodeheap_item.i2 # <<<<<<<<<<<<<< + * + * node_info1 = node_data1[i_node1] + */ + __pyx_t_15 = __pyx_v_nodeheap_item.i2; + __pyx_v_i_node2 = __pyx_t_15; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1955 + * i_node2 = nodeheap_item.i2 + * + * node_info1 = node_data1[i_node1] # <<<<<<<<<<<<<< + * node_info2 = node_data2[i_node2] + * + */ + __pyx_v_node_info1 = (__pyx_v_node_data1[__pyx_v_i_node1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1956 + * + * node_info1 = node_data1[i_node1] + * node_info2 = node_data2[i_node2] # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_v_node_info2 = (__pyx_v_node_data2[__pyx_v_i_node2]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1961 + * # Case 1: nodes are further apart than the current bound: + * # trim both from the query + * if reduced_dist_LB > bounds[i_node2]: # <<<<<<<<<<<<<< + * pass + * + */ + __pyx_t_15 = __pyx_v_i_node2; + __pyx_t_14 = ((__pyx_v_reduced_dist_LB > (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_15)) )))) != 0); + if (__pyx_t_14) { + goto __pyx_L5; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1967 + * # Case 2: both nodes are leaves: + * # do a brute-force search comparing all pairs + * elif node_info1.is_leaf and node_info2.is_leaf: # <<<<<<<<<<<<<< + * bounds[i_node2] = -1 + * + */ + if ((__pyx_v_node_info1.is_leaf != 0)) { + __pyx_t_14 = (__pyx_v_node_info2.is_leaf != 0); + } else { + __pyx_t_14 = (__pyx_v_node_info1.is_leaf != 0); + } + if (__pyx_t_14) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1968 + * # do a brute-force search comparing all pairs + * elif node_info1.is_leaf and node_info2.is_leaf: + * bounds[i_node2] = -1 # <<<<<<<<<<<<<< + * + * for i2 in range(node_info2.idx_start, node_info2.idx_end): + */ + __pyx_t_16 = __pyx_v_i_node2; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_16)) )) = -1.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1970 + * bounds[i_node2] = -1 + * + * for i2 in range(node_info2.idx_start, node_info2.idx_end): # <<<<<<<<<<<<<< + * i_pt = other.idx_array[i2] + * + */ + __pyx_t_17 = __pyx_v_node_info2.idx_end; + for (__pyx_t_18 = __pyx_v_node_info2.idx_start; __pyx_t_18 < __pyx_t_17; __pyx_t_18+=1) { + __pyx_v_i2 = __pyx_t_18; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1971 + * + * for i2 in range(node_info2.idx_start, node_info2.idx_end): + * i_pt = other.idx_array[i2] # <<<<<<<<<<<<<< + * + * if heap.largest(i_pt) <= reduced_dist_LB: + */ + if (unlikely(!__pyx_v_other->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1971; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_19 = __pyx_v_i2; + __pyx_v_i_pt = (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_other->idx_array.data) + __pyx_t_19)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1973 + * i_pt = other.idx_array[i2] + * + * if heap.largest(i_pt) <= reduced_dist_LB: # <<<<<<<<<<<<<< + * continue + * + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1973; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = ((__pyx_t_12 <= __pyx_v_reduced_dist_LB) != 0); + if (__pyx_t_14) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1974 + * + * if heap.largest(i_pt) <= reduced_dist_LB: + * continue # <<<<<<<<<<<<<< + * + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + */ + goto __pyx_L6_continue; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1976 + * continue + * + * for i1 in range(node_info1.idx_start, node_info1.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.rdist( + * data1 + n_features * self.idx_array[i1], + */ + __pyx_t_20 = __pyx_v_node_info1.idx_end; + for (__pyx_t_21 = __pyx_v_node_info1.idx_start; __pyx_t_21 < __pyx_t_20; __pyx_t_21+=1) { + __pyx_v_i1 = __pyx_t_21; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1978 + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * dist_pt = self.rdist( + * data1 + n_features * self.idx_array[i1], # <<<<<<<<<<<<<< + * data2 + n_features * i_pt, + * n_features) + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1978; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_22 = __pyx_v_i1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1977 + * + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * dist_pt = self.rdist( # <<<<<<<<<<<<<< + * data1 + n_features * self.idx_array[i1], + * data2 + n_features * i_pt, + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_rdist(__pyx_v_self, (__pyx_v_data1 + (__pyx_v_n_features * (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_22)) ))))), (__pyx_v_data2 + (__pyx_v_n_features * __pyx_v_i_pt)), __pyx_v_n_features); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1981 + * data2 + n_features * i_pt, + * n_features) + * if dist_pt < heap.largest(i_pt): # <<<<<<<<<<<<<< + * heap.push(i_pt, dist_pt, self.idx_array[i1]) + * + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1981; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = ((__pyx_v_dist_pt < __pyx_t_12) != 0); + if (__pyx_t_14) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1982 + * n_features) + * if dist_pt < heap.largest(i_pt): + * heap.push(i_pt, dist_pt, self.idx_array[i1]) # <<<<<<<<<<<<<< + * + * # keep track of node bound + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1982; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_23 = __pyx_v_i1; + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_i_pt, __pyx_v_dist_pt, (*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_23)) ))), 0); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1982; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L11; + } + __pyx_L11:; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1985 + * + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], # <<<<<<<<<<<<<< + * heap.largest(i_pt)) + * + */ + __pyx_t_20 = __pyx_v_i_node2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1986 + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], + * heap.largest(i_pt)) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest(__pyx_v_heap, __pyx_v_i_pt); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1986; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1985 + * + * # keep track of node bound + * bounds[i_node2] = fmax(bounds[i_node2], # <<<<<<<<<<<<<< + * heap.largest(i_pt)) + * + */ + __pyx_t_21 = __pyx_v_i_node2; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_21)) )) = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_bounds.data) + __pyx_t_20)) ))), __pyx_t_12); + __pyx_L6_continue:; + } + goto __pyx_L5; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1991 + * # Case 3a: node 1 is a leaf or is smaller: split node 2 and + * # recursively query, starting with the nearest subnode + * elif node_info1.is_leaf or (not node_info2.is_leaf # <<<<<<<<<<<<<< + * and (node_info2.radius + * > node_info1.radius)): + */ + if (!(__pyx_v_node_info1.is_leaf != 0)) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1992 + * # recursively query, starting with the nearest subnode + * elif node_info1.is_leaf or (not node_info2.is_leaf + * and (node_info2.radius # <<<<<<<<<<<<<< + * > node_info1.radius)): + * nodeheap_item.i1 = i_node1 + */ + __pyx_t_14 = (!(__pyx_v_node_info2.is_leaf != 0)); + if (__pyx_t_14) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1993 + * elif node_info1.is_leaf or (not node_info2.is_leaf + * and (node_info2.radius + * > node_info1.radius)): # <<<<<<<<<<<<<< + * nodeheap_item.i1 = i_node1 + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + */ + __pyx_t_24 = (__pyx_v_node_info2.radius > __pyx_v_node_info1.radius); + __pyx_t_25 = __pyx_t_24; + } else { + __pyx_t_25 = __pyx_t_14; + } + __pyx_t_14 = __pyx_t_25; + } else { + __pyx_t_14 = (__pyx_v_node_info1.is_leaf != 0); + } + if (__pyx_t_14) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1994 + * and (node_info2.radius + * > node_info1.radius)): + * nodeheap_item.i1 = i_node1 # <<<<<<<<<<<<<< + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * nodeheap_item.i2 = i2 + */ + __pyx_v_nodeheap_item.i1 = __pyx_v_i_node1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1995 + * > node_info1.radius)): + * nodeheap_item.i1 = i_node1 + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): # <<<<<<<<<<<<<< + * nodeheap_item.i2 = i2 + * nodeheap_item.val = min_rdist_dual(self, i_node1, + */ + __pyx_t_26 = ((2 * __pyx_v_i_node2) + 3); + for (__pyx_t_17 = ((2 * __pyx_v_i_node2) + 1); __pyx_t_17 < __pyx_t_26; __pyx_t_17+=1) { + __pyx_v_i2 = __pyx_t_17; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1996 + * nodeheap_item.i1 = i_node1 + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * nodeheap_item.i2 = i2 # <<<<<<<<<<<<<< + * nodeheap_item.val = min_rdist_dual(self, i_node1, + * other, i2) + */ + __pyx_v_nodeheap_item.i2 = __pyx_v_i2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1997 + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * nodeheap_item.i2 = i2 + * nodeheap_item.val = min_rdist_dual(self, i_node1, # <<<<<<<<<<<<<< + * other, i2) + * nodeheap.push(nodeheap_item) + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, __pyx_v_i2); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1999 + * nodeheap_item.val = min_rdist_dual(self, i_node1, + * other, i2) + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1999; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L5; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2005 + * # recursively query, starting with the nearest subnode + * else: + * nodeheap_item.i2 = i_node2 # <<<<<<<<<<<<<< + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * nodeheap_item.i1 = i1 + */ + __pyx_v_nodeheap_item.i2 = __pyx_v_i_node2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2006 + * else: + * nodeheap_item.i2 = i_node2 + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): # <<<<<<<<<<<<<< + * nodeheap_item.i1 = i1 + * nodeheap_item.val = min_rdist_dual(self, i1, + */ + __pyx_t_26 = ((2 * __pyx_v_i_node1) + 3); + for (__pyx_t_17 = ((2 * __pyx_v_i_node1) + 1); __pyx_t_17 < __pyx_t_26; __pyx_t_17+=1) { + __pyx_v_i1 = __pyx_t_17; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2007 + * nodeheap_item.i2 = i_node2 + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * nodeheap_item.i1 = i1 # <<<<<<<<<<<<<< + * nodeheap_item.val = min_rdist_dual(self, i1, + * other, i_node2) + */ + __pyx_v_nodeheap_item.i1 = __pyx_v_i1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2008 + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * nodeheap_item.i1 = i1 + * nodeheap_item.val = min_rdist_dual(self, i1, # <<<<<<<<<<<<<< + * other, i_node2) + * nodeheap.push(nodeheap_item) + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist_dual(__pyx_v_self, __pyx_v_i1, __pyx_v_other, __pyx_v_i_node2); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2008; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2010 + * nodeheap_item.val = min_rdist_dual(self, i1, + * other, i_node2) + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2010; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + __pyx_L5:; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2011 + * other, i_node2) + * nodeheap.push(nodeheap_item) + * return 0 # <<<<<<<<<<<<<< + * + * cdef ITYPE_t _query_radius_single(self, + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1928 + * return 0 + * + * cdef int _query_dual_breadthfirst(self, BinaryTree other, # <<<<<<<<<<<<<< + * NeighborsHeap heap, + * NodeHeap nodeheap) except -1: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree._query_dual_breadthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_bounds, 1); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2013 + * return 0 + * + * cdef ITYPE_t _query_radius_single(self, # <<<<<<<<<<<<<< + * ITYPE_t i_node, + * DTYPE_t* pt, DTYPE_t r, + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__query_radius_single(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_r, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_indices, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_distances, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_count, int __pyx_v_count_only, int __pyx_v_return_distance) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_reduced_r; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + PyObject *__pyx_t_11 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_query_radius_single", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2022 + * int return_distance) except -1: + * """recursive single-tree radius query, depth-first""" + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2022; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_1 * __pyx_v_self->data.strides[0]) )) + __pyx_t_2)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2023 + * """recursive single-tree radius query, depth-first""" + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef NodeData_t node_info = self.node_data[i_node] + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2023; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2024 + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info = self.node_data[i_node] + * + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2024; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2025 + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef NodeData_t node_info = self.node_data[i_node] # <<<<<<<<<<<<<< + * + * cdef ITYPE_t i + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2025; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = __pyx_v_i_node; + __pyx_v_node_info = (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_4)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2030 + * cdef DTYPE_t reduced_r + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 # <<<<<<<<<<<<<< + * min_max_dist(self, i_node, pt, &dist_LB, &dist_UB) + * + */ + __pyx_v_dist_LB = 0.0; + __pyx_v_dist_UB = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2031 + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 + * min_max_dist(self, i_node, pt, &dist_LB, &dist_UB) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_max_dist(__pyx_v_self, __pyx_v_i_node, __pyx_v_pt, (&__pyx_v_dist_LB), (&__pyx_v_dist_UB)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2031; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2036 + * # Case 1: all node points are outside distance r. + * # prune this branch. + * if dist_LB > r: # <<<<<<<<<<<<<< + * pass + * + */ + __pyx_t_6 = ((__pyx_v_dist_LB > __pyx_v_r) != 0); + if (__pyx_t_6) { + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2042 + * # Case 2: all node points are within distance r + * # add all points to neighbors + * elif dist_UB <= r: # <<<<<<<<<<<<<< + * if count_only: + * count += (node_info.idx_end - node_info.idx_start) + */ + __pyx_t_6 = ((__pyx_v_dist_UB <= __pyx_v_r) != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2043 + * # add all points to neighbors + * elif dist_UB <= r: + * if count_only: # <<<<<<<<<<<<<< + * count += (node_info.idx_end - node_info.idx_start) + * else: + */ + __pyx_t_6 = (__pyx_v_count_only != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2044 + * elif dist_UB <= r: + * if count_only: + * count += (node_info.idx_end - node_info.idx_start) # <<<<<<<<<<<<<< + * else: + * for i in range(node_info.idx_start, node_info.idx_end): + */ + __pyx_v_count = (__pyx_v_count + (__pyx_v_node_info.idx_end - __pyx_v_node_info.idx_start)); + goto __pyx_L4; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2046 + * count += (node_info.idx_end - node_info.idx_start) + * else: + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count too big: " + */ + __pyx_t_7 = __pyx_v_node_info.idx_end; + for (__pyx_t_8 = __pyx_v_node_info.idx_start; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2047 + * else: + * for i in range(node_info.idx_start, node_info.idx_end): + * if (count < 0) or (count >= self.data.shape[0]): # <<<<<<<<<<<<<< + * raise ValueError("Fatal: count too big: " + * "this should never happen") + */ + __pyx_t_6 = ((__pyx_v_count < 0) != 0); + if (!__pyx_t_6) { + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2047; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = ((__pyx_v_count >= (__pyx_v_self->data.shape[0])) != 0); + __pyx_t_10 = __pyx_t_9; + } else { + __pyx_t_10 = __pyx_t_6; + } + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2048 + * for i in range(node_info.idx_start, node_info.idx_end): + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count too big: " # <<<<<<<<<<<<<< + * "this should never happen") + * indices[count] = idx_array[i] + */ + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__30, NULL); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2048; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + __Pyx_Raise(__pyx_t_11, 0, 0, 0); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2048; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2050 + * raise ValueError("Fatal: count too big: " + * "this should never happen") + * indices[count] = idx_array[i] # <<<<<<<<<<<<<< + * if return_distance: + * distances[count] = self.dist(pt, (data + n_features + */ + (__pyx_v_indices[__pyx_v_count]) = (__pyx_v_idx_array[__pyx_v_i]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2051 + * "this should never happen") + * indices[count] = idx_array[i] + * if return_distance: # <<<<<<<<<<<<<< + * distances[count] = self.dist(pt, (data + n_features + * * idx_array[i]), + */ + __pyx_t_10 = (__pyx_v_return_distance != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2052 + * indices[count] = idx_array[i] + * if return_distance: + * distances[count] = self.dist(pt, (data + n_features # <<<<<<<<<<<<<< + * * idx_array[i]), + * n_features) + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_dist(__pyx_v_self, __pyx_v_pt, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2052; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + (__pyx_v_distances[__pyx_v_count]) = __pyx_t_12; + goto __pyx_L8; + } + __pyx_L8:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2055 + * * idx_array[i]), + * n_features) + * count += 1 # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_v_count = (__pyx_v_count + 1); + } + } + __pyx_L4:; + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2060 + * # Case 3: this is a leaf node. Go through all points to + * # determine if they fall within radius + * elif node_info.is_leaf: # <<<<<<<<<<<<<< + * reduced_r = self.dist_metric._dist_to_rdist(r) + * + */ + __pyx_t_10 = (__pyx_v_node_info.is_leaf != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2061 + * # determine if they fall within radius + * elif node_info.is_leaf: + * reduced_r = self.dist_metric._dist_to_rdist(r) # <<<<<<<<<<<<<< + * + * for i in range(node_info.idx_start, node_info.idx_end): + */ + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->dist_metric->__pyx_vtab)->_dist_to_rdist(__pyx_v_self->dist_metric, __pyx_v_r); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_reduced_r = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2063 + * reduced_r = self.dist_metric._dist_to_rdist(r) + * + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.rdist(pt, (data + n_features * idx_array[i]), + * n_features) + */ + __pyx_t_7 = __pyx_v_node_info.idx_end; + for (__pyx_t_8 = __pyx_v_node_info.idx_start; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2064 + * + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.rdist(pt, (data + n_features * idx_array[i]), # <<<<<<<<<<<<<< + * n_features) + * if dist_pt <= reduced_r: + */ + __pyx_t_12 = __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_rdist(__pyx_v_self, __pyx_v_pt, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2064; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2066 + * dist_pt = self.rdist(pt, (data + n_features * idx_array[i]), + * n_features) + * if dist_pt <= reduced_r: # <<<<<<<<<<<<<< + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count out of range. " + */ + __pyx_t_10 = ((__pyx_v_dist_pt <= __pyx_v_reduced_r) != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2067 + * n_features) + * if dist_pt <= reduced_r: + * if (count < 0) or (count >= self.data.shape[0]): # <<<<<<<<<<<<<< + * raise ValueError("Fatal: count out of range. " + * "This should never happen.") + */ + __pyx_t_10 = ((__pyx_v_count < 0) != 0); + if (!__pyx_t_10) { + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2067; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_6 = ((__pyx_v_count >= (__pyx_v_self->data.shape[0])) != 0); + __pyx_t_9 = __pyx_t_6; + } else { + __pyx_t_9 = __pyx_t_10; + } + if (__pyx_t_9) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2068 + * if dist_pt <= reduced_r: + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count out of range. " # <<<<<<<<<<<<<< + * "This should never happen.") + * if count_only: + */ + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__31, NULL); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2068; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + __Pyx_Raise(__pyx_t_11, 0, 0, 0); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2068; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2070 + * raise ValueError("Fatal: count out of range. " + * "This should never happen.") + * if count_only: # <<<<<<<<<<<<<< + * pass + * else: + */ + __pyx_t_9 = (__pyx_v_count_only != 0); + if (__pyx_t_9) { + goto __pyx_L13; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2073 + * pass + * else: + * indices[count] = idx_array[i] # <<<<<<<<<<<<<< + * if return_distance: + * distances[count] =\ + */ + (__pyx_v_indices[__pyx_v_count]) = (__pyx_v_idx_array[__pyx_v_i]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2074 + * else: + * indices[count] = idx_array[i] + * if return_distance: # <<<<<<<<<<<<<< + * distances[count] =\ + * self.dist_metric._rdist_to_dist(dist_pt) + */ + __pyx_t_9 = (__pyx_v_return_distance != 0); + if (__pyx_t_9) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2076 + * if return_distance: + * distances[count] =\ + * self.dist_metric._rdist_to_dist(dist_pt) # <<<<<<<<<<<<<< + * count += 1 + * + */ + __pyx_t_12 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_self->dist_metric->__pyx_vtab)->_rdist_to_dist(__pyx_v_self->dist_metric, __pyx_v_dist_pt); if (unlikely(__pyx_t_12 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2075 + * indices[count] = idx_array[i] + * if return_distance: + * distances[count] =\ # <<<<<<<<<<<<<< + * self.dist_metric._rdist_to_dist(dist_pt) + * count += 1 + */ + (__pyx_v_distances[__pyx_v_count]) = __pyx_t_12; + goto __pyx_L14; + } + __pyx_L14:; + } + __pyx_L13:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2077 + * distances[count] =\ + * self.dist_metric._rdist_to_dist(dist_pt) + * count += 1 # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_v_count = (__pyx_v_count + 1); + goto __pyx_L11; + } + __pyx_L11:; + } + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2082 + * # Case 4: Node is not a leaf. Recursively query subnodes + * else: + * count = self._query_radius_single(2 * i_node + 1, pt, r, # <<<<<<<<<<<<<< + * indices, distances, count, + * count_only, return_distance) + */ + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_radius_single(__pyx_v_self, ((2 * __pyx_v_i_node) + 1), __pyx_v_pt, __pyx_v_r, __pyx_v_indices, __pyx_v_distances, __pyx_v_count, __pyx_v_count_only, __pyx_v_return_distance); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2082; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_count = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2085 + * indices, distances, count, + * count_only, return_distance) + * count = self._query_radius_single(2 * i_node + 2, pt, r, # <<<<<<<<<<<<<< + * indices, distances, count, + * count_only, return_distance) + */ + __pyx_t_7 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_query_radius_single(__pyx_v_self, ((2 * __pyx_v_i_node) + 2), __pyx_v_pt, __pyx_v_r, __pyx_v_indices, __pyx_v_distances, __pyx_v_count, __pyx_v_count_only, __pyx_v_return_distance); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_count = __pyx_t_7; + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2089 + * count_only, return_distance) + * + * return count # <<<<<<<<<<<<<< + * + * cdef DTYPE_t _kde_single_breadthfirst(self, DTYPE_t* pt, + */ + __pyx_r = __pyx_v_count; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2013 + * return 0 + * + * cdef ITYPE_t _query_radius_single(self, # <<<<<<<<<<<<<< + * ITYPE_t i_node, + * DTYPE_t* pt, DTYPE_t r, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_11); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree._query_radius_single", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2091 + * return count + * + * cdef DTYPE_t _kde_single_breadthfirst(self, DTYPE_t* pt, # <<<<<<<<<<<<<< + * KernelType kernel, DTYPE_t h, + * DTYPE_t log_knorm, + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__kde_single_breadthfirst(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType __pyx_v_kernel, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_knorm, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_atol, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_rtol, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_nodeheap, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_node_log_min_bounds, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_node_log_bound_spreads) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_N1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_N2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_global_log_min_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_global_log_bound_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_global_log_max_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *__pyx_v_node_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_N; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_density; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB_2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB_2; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_v_nodeheap_item; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_kde_single_breadthfirst", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2110 + * cdef DTYPE_t global_log_max_bound + * + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef NodeData_t* node_data = &self.node_data[0] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2110; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_1 * __pyx_v_self->data.strides[0]) )) + __pyx_t_2)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2111 + * + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] # <<<<<<<<<<<<<< + * cdef NodeData_t* node_data = &self.node_data[0] + * cdef ITYPE_t N = self.data.shape[0] + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2111; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2112 + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef NodeData_t* node_data = &self.node_data[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t N = self.data.shape[0] + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2112; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = 0; + __pyx_v_node_data = (&(*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_4)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2113 + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef NodeData_t* node_data = &self.node_data[0] + * cdef ITYPE_t N = self.data.shape[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2113; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_N = (__pyx_v_self->data.shape[0]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2114 + * cdef NodeData_t* node_data = &self.node_data[0] + * cdef ITYPE_t N = self.data.shape[0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * + * cdef NodeData_t node_info + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2114; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2118 + * cdef NodeData_t node_info + * cdef DTYPE_t dist_pt, log_density + * cdef DTYPE_t dist_LB_1 = 0, dist_LB_2 = 0 # <<<<<<<<<<<<<< + * cdef DTYPE_t dist_UB_1 = 0, dist_UB_2 = 0 + * + */ + __pyx_v_dist_LB_1 = 0.0; + __pyx_v_dist_LB_2 = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2119 + * cdef DTYPE_t dist_pt, log_density + * cdef DTYPE_t dist_LB_1 = 0, dist_LB_2 = 0 + * cdef DTYPE_t dist_UB_1 = 0, dist_UB_2 = 0 # <<<<<<<<<<<<<< + * + * cdef DTYPE_t dist_UB, dist_LB + */ + __pyx_v_dist_UB_1 = 0.0; + __pyx_v_dist_UB_2 = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2125 + * # push the top node to the heap + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_dist(self, 0, pt) # <<<<<<<<<<<<<< + * nodeheap_item.i1 = 0 + * nodeheap.push(nodeheap_item) + */ + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_dist(__pyx_v_self, 0, __pyx_v_pt); if (unlikely(__pyx_t_5 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nodeheap_item.val = __pyx_t_5; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2126 + * cdef NodeHeapData_t nodeheap_item + * nodeheap_item.val = min_dist(self, 0, pt) + * nodeheap_item.i1 = 0 # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) + * + */ + __pyx_v_nodeheap_item.i1 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2127 + * nodeheap_item.val = min_dist(self, 0, pt) + * nodeheap_item.i1 = 0 + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * + * global_log_min_bound = log(N) + compute_log_kernel(max_dist(self, + */ + __pyx_t_6 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2129 + * nodeheap.push(nodeheap_item) + * + * global_log_min_bound = log(N) + compute_log_kernel(max_dist(self, # <<<<<<<<<<<<<< + * 0, pt), + * h, kernel) + */ + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_7kd_tree_max_dist(__pyx_v_self, 0, __pyx_v_pt); if (unlikely(__pyx_t_5 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2131 + * global_log_min_bound = log(N) + compute_log_kernel(max_dist(self, + * 0, pt), + * h, kernel) # <<<<<<<<<<<<<< + * global_log_max_bound = log(N) + compute_log_kernel(nodeheap_item.val, + * h, kernel) + */ + __pyx_v_global_log_min_bound = (log(__pyx_v_N) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_t_5, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2132 + * 0, pt), + * h, kernel) + * global_log_max_bound = log(N) + compute_log_kernel(nodeheap_item.val, # <<<<<<<<<<<<<< + * h, kernel) + * global_log_bound_spread = logsubexp(global_log_max_bound, + */ + __pyx_v_global_log_max_bound = (log(__pyx_v_N) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_nodeheap_item.val, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2134 + * global_log_max_bound = log(N) + compute_log_kernel(nodeheap_item.val, + * h, kernel) + * global_log_bound_spread = logsubexp(global_log_max_bound, # <<<<<<<<<<<<<< + * global_log_min_bound) + * + */ + __pyx_v_global_log_bound_spread = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp(__pyx_v_global_log_max_bound, __pyx_v_global_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2137 + * global_log_min_bound) + * + * node_log_min_bounds[0] = global_log_min_bound # <<<<<<<<<<<<<< + * node_log_bound_spreads[0] = global_log_bound_spread + * + */ + (__pyx_v_node_log_min_bounds[0]) = __pyx_v_global_log_min_bound; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2138 + * + * node_log_min_bounds[0] = global_log_min_bound + * node_log_bound_spreads[0] = global_log_bound_spread # <<<<<<<<<<<<<< + * + * while nodeheap.n > 0: + */ + (__pyx_v_node_log_bound_spreads[0]) = __pyx_v_global_log_bound_spread; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2140 + * node_log_bound_spreads[0] = global_log_bound_spread + * + * while nodeheap.n > 0: # <<<<<<<<<<<<<< + * nodeheap_item = nodeheap.pop() + * i_node = nodeheap_item.i1 + */ + while (1) { + __pyx_t_7 = ((__pyx_v_nodeheap->n > 0) != 0); + if (!__pyx_t_7) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2141 + * + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() # <<<<<<<<<<<<<< + * i_node = nodeheap_item.i1 + * + */ + __pyx_v_nodeheap_item = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->pop(__pyx_v_nodeheap); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2142 + * while nodeheap.n > 0: + * nodeheap_item = nodeheap.pop() + * i_node = nodeheap_item.i1 # <<<<<<<<<<<<<< + * + * node_info = node_data[i_node] + */ + __pyx_t_8 = __pyx_v_nodeheap_item.i1; + __pyx_v_i_node = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2144 + * i_node = nodeheap_item.i1 + * + * node_info = node_data[i_node] # <<<<<<<<<<<<<< + * N1 = node_info.idx_end - node_info.idx_start + * + */ + __pyx_v_node_info = (__pyx_v_node_data[__pyx_v_i_node]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2145 + * + * node_info = node_data[i_node] + * N1 = node_info.idx_end - node_info.idx_start # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_v_N1 = (__pyx_v_node_info.idx_end - __pyx_v_node_info.idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2150 + * # Case 1: local bounds are equal to within per-point tolerance. + * if (log_knorm + node_log_bound_spreads[i_node] - log(N1) + log(N) + * <= logaddexp(log_atol, (log_rtol + log_knorm # <<<<<<<<<<<<<< + * + node_log_min_bounds[i_node]))): + * pass + */ + __pyx_t_7 = (((((__pyx_v_log_knorm + (__pyx_v_node_log_bound_spreads[__pyx_v_i_node])) - log(__pyx_v_N1)) + log(__pyx_v_N)) <= __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_v_log_atol, ((__pyx_v_log_rtol + __pyx_v_log_knorm) + (__pyx_v_node_log_min_bounds[__pyx_v_i_node])))) != 0); + if (__pyx_t_7) { + goto __pyx_L5; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2157 + * # Case 2: global bounds are within rtol & atol. + * elif (log_knorm + global_log_bound_spread + * <= logaddexp(log_atol, # <<<<<<<<<<<<<< + * log_rtol + log_knorm + global_log_min_bound)): + * break + */ + __pyx_t_7 = (((__pyx_v_log_knorm + __pyx_v_global_log_bound_spread) <= __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_v_log_atol, ((__pyx_v_log_rtol + __pyx_v_log_knorm) + __pyx_v_global_log_min_bound))) != 0); + if (__pyx_t_7) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2159 + * <= logaddexp(log_atol, + * log_rtol + log_knorm + global_log_min_bound)): + * break # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + goto __pyx_L4_break; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2163 + * #------------------------------------------------------------ + * # Case 3: node is a leaf. Count contributions from all points + * elif node_info.is_leaf: # <<<<<<<<<<<<<< + * global_log_min_bound =\ + * logsubexp(global_log_min_bound, + */ + __pyx_t_7 = (__pyx_v_node_info.is_leaf != 0); + if (__pyx_t_7) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2165 + * elif node_info.is_leaf: + * global_log_min_bound =\ + * logsubexp(global_log_min_bound, # <<<<<<<<<<<<<< + * node_log_min_bounds[i_node]) + * global_log_bound_spread =\ + */ + __pyx_v_global_log_min_bound = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp(__pyx_v_global_log_min_bound, (__pyx_v_node_log_min_bounds[__pyx_v_i_node])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2168 + * node_log_min_bounds[i_node]) + * global_log_bound_spread =\ + * logsubexp(global_log_bound_spread, # <<<<<<<<<<<<<< + * node_log_bound_spreads[i_node]) + * for i in range(node_info.idx_start, node_info.idx_end): + */ + __pyx_v_global_log_bound_spread = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp(__pyx_v_global_log_bound_spread, (__pyx_v_node_log_bound_spreads[__pyx_v_i_node])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2170 + * logsubexp(global_log_bound_spread, + * node_log_bound_spreads[i_node]) + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.dist(pt, data + n_features * idx_array[i], + * n_features) + */ + __pyx_t_8 = __pyx_v_node_info.idx_end; + for (__pyx_t_9 = __pyx_v_node_info.idx_start; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { + __pyx_v_i = __pyx_t_9; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2171 + * node_log_bound_spreads[i_node]) + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.dist(pt, data + n_features * idx_array[i], # <<<<<<<<<<<<<< + * n_features) + * log_density = compute_log_kernel(dist_pt, h, kernel) + */ + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_dist(__pyx_v_self, __pyx_v_pt, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features); if (unlikely(__pyx_t_5 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_5; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2173 + * dist_pt = self.dist(pt, data + n_features * idx_array[i], + * n_features) + * log_density = compute_log_kernel(dist_pt, h, kernel) # <<<<<<<<<<<<<< + * global_log_min_bound = logaddexp(global_log_min_bound, + * log_density) + */ + __pyx_v_log_density = __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_pt, __pyx_v_h, __pyx_v_kernel); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2174 + * n_features) + * log_density = compute_log_kernel(dist_pt, h, kernel) + * global_log_min_bound = logaddexp(global_log_min_bound, # <<<<<<<<<<<<<< + * log_density) + * + */ + __pyx_v_global_log_min_bound = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_v_global_log_min_bound, __pyx_v_log_density); + } + goto __pyx_L5; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2180 + * # Case 4: split node and query subnodes + * else: + * i1 = 2 * i_node + 1 # <<<<<<<<<<<<<< + * i2 = 2 * i_node + 2 + * + */ + __pyx_v_i1 = ((2 * __pyx_v_i_node) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2181 + * else: + * i1 = 2 * i_node + 1 + * i2 = 2 * i_node + 2 # <<<<<<<<<<<<<< + * + * N1 = node_data[i1].idx_end - node_data[i1].idx_start + */ + __pyx_v_i2 = ((2 * __pyx_v_i_node) + 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2183 + * i2 = 2 * i_node + 2 + * + * N1 = node_data[i1].idx_end - node_data[i1].idx_start # <<<<<<<<<<<<<< + * N2 = node_data[i2].idx_end - node_data[i2].idx_start + * + */ + __pyx_v_N1 = ((__pyx_v_node_data[__pyx_v_i1]).idx_end - (__pyx_v_node_data[__pyx_v_i1]).idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2184 + * + * N1 = node_data[i1].idx_end - node_data[i1].idx_start + * N2 = node_data[i2].idx_end - node_data[i2].idx_start # <<<<<<<<<<<<<< + * + * min_max_dist(self, i1, pt, &dist_LB_1, &dist_UB_1) + */ + __pyx_v_N2 = ((__pyx_v_node_data[__pyx_v_i2]).idx_end - (__pyx_v_node_data[__pyx_v_i2]).idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2186 + * N2 = node_data[i2].idx_end - node_data[i2].idx_start + * + * min_max_dist(self, i1, pt, &dist_LB_1, &dist_UB_1) # <<<<<<<<<<<<<< + * min_max_dist(self, i2, pt, &dist_LB_2, &dist_UB_2) + * + */ + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_max_dist(__pyx_v_self, __pyx_v_i1, __pyx_v_pt, (&__pyx_v_dist_LB_1), (&__pyx_v_dist_UB_1)); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2187 + * + * min_max_dist(self, i1, pt, &dist_LB_1, &dist_UB_1) + * min_max_dist(self, i2, pt, &dist_LB_2, &dist_UB_2) # <<<<<<<<<<<<<< + * + * node_log_min_bounds[i1] = (log(N1) + + */ + __pyx_t_6 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_max_dist(__pyx_v_self, __pyx_v_i2, __pyx_v_pt, (&__pyx_v_dist_LB_2), (&__pyx_v_dist_UB_2)); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2189 + * min_max_dist(self, i2, pt, &dist_LB_2, &dist_UB_2) + * + * node_log_min_bounds[i1] = (log(N1) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_UB_1, + * h, kernel)) + */ + (__pyx_v_node_log_min_bounds[__pyx_v_i1]) = (log(__pyx_v_N1) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_UB_1, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2192 + * compute_log_kernel(dist_UB_1, + * h, kernel)) + * node_log_bound_spreads[i1] = (log(N1) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_LB_1, + * h, kernel)) + */ + (__pyx_v_node_log_bound_spreads[__pyx_v_i1]) = (log(__pyx_v_N1) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_LB_1, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2196 + * h, kernel)) + * + * node_log_min_bounds[i2] = (log(N2) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_UB_2, + * h, kernel)) + */ + (__pyx_v_node_log_min_bounds[__pyx_v_i2]) = (log(__pyx_v_N2) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_UB_2, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2199 + * compute_log_kernel(dist_UB_2, + * h, kernel)) + * node_log_bound_spreads[i2] = (log(N2) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_LB_2, + * h, kernel)) + */ + (__pyx_v_node_log_bound_spreads[__pyx_v_i2]) = (log(__pyx_v_N2) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_LB_2, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2203 + * h, kernel)) + * + * global_log_min_bound = logsubexp(global_log_min_bound, # <<<<<<<<<<<<<< + * node_log_min_bounds[i_node]) + * global_log_min_bound = logaddexp(global_log_min_bound, + */ + __pyx_v_global_log_min_bound = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp(__pyx_v_global_log_min_bound, (__pyx_v_node_log_min_bounds[__pyx_v_i_node])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2205 + * global_log_min_bound = logsubexp(global_log_min_bound, + * node_log_min_bounds[i_node]) + * global_log_min_bound = logaddexp(global_log_min_bound, # <<<<<<<<<<<<<< + * node_log_min_bounds[i1]) + * global_log_min_bound = logaddexp(global_log_min_bound, + */ + __pyx_v_global_log_min_bound = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_v_global_log_min_bound, (__pyx_v_node_log_min_bounds[__pyx_v_i1])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2207 + * global_log_min_bound = logaddexp(global_log_min_bound, + * node_log_min_bounds[i1]) + * global_log_min_bound = logaddexp(global_log_min_bound, # <<<<<<<<<<<<<< + * node_log_min_bounds[i2]) + * + */ + __pyx_v_global_log_min_bound = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_v_global_log_min_bound, (__pyx_v_node_log_min_bounds[__pyx_v_i2])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2211 + * + * global_log_bound_spread =\ + * logsubexp(global_log_bound_spread, # <<<<<<<<<<<<<< + * node_log_bound_spreads[i_node]) + * global_log_bound_spread = logaddexp(global_log_bound_spread, + */ + __pyx_v_global_log_bound_spread = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp(__pyx_v_global_log_bound_spread, (__pyx_v_node_log_bound_spreads[__pyx_v_i_node])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2213 + * logsubexp(global_log_bound_spread, + * node_log_bound_spreads[i_node]) + * global_log_bound_spread = logaddexp(global_log_bound_spread, # <<<<<<<<<<<<<< + * node_log_bound_spreads[i1]) + * global_log_bound_spread = logaddexp(global_log_bound_spread, + */ + __pyx_v_global_log_bound_spread = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_v_global_log_bound_spread, (__pyx_v_node_log_bound_spreads[__pyx_v_i1])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2215 + * global_log_bound_spread = logaddexp(global_log_bound_spread, + * node_log_bound_spreads[i1]) + * global_log_bound_spread = logaddexp(global_log_bound_spread, # <<<<<<<<<<<<<< + * node_log_bound_spreads[i2]) + * + */ + __pyx_v_global_log_bound_spread = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_v_global_log_bound_spread, (__pyx_v_node_log_bound_spreads[__pyx_v_i2])); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2219 + * + * # TODO: rank by the spread rather than the distance? + * nodeheap_item.val = dist_LB_1 # <<<<<<<<<<<<<< + * nodeheap_item.i1 = i1 + * nodeheap.push(nodeheap_item) + */ + __pyx_v_nodeheap_item.val = __pyx_v_dist_LB_1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2220 + * # TODO: rank by the spread rather than the distance? + * nodeheap_item.val = dist_LB_1 + * nodeheap_item.i1 = i1 # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) + * + */ + __pyx_v_nodeheap_item.i1 = __pyx_v_i1; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2221 + * nodeheap_item.val = dist_LB_1 + * nodeheap_item.i1 = i1 + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * + * nodeheap_item.val = dist_LB_2 + */ + __pyx_t_6 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2223 + * nodeheap.push(nodeheap_item) + * + * nodeheap_item.val = dist_LB_2 # <<<<<<<<<<<<<< + * nodeheap_item.i1 = i2 + * nodeheap.push(nodeheap_item) + */ + __pyx_v_nodeheap_item.val = __pyx_v_dist_LB_2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2224 + * + * nodeheap_item.val = dist_LB_2 + * nodeheap_item.i1 = i2 # <<<<<<<<<<<<<< + * nodeheap.push(nodeheap_item) + * + */ + __pyx_v_nodeheap_item.i1 = __pyx_v_i2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2225 + * nodeheap_item.val = dist_LB_2 + * nodeheap_item.i1 = i2 + * nodeheap.push(nodeheap_item) # <<<<<<<<<<<<<< + * + * nodeheap.clear() + */ + __pyx_t_6 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->push(__pyx_v_nodeheap, __pyx_v_nodeheap_item); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L5:; + } + __pyx_L4_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2227 + * nodeheap.push(nodeheap_item) + * + * nodeheap.clear() # <<<<<<<<<<<<<< + * return logaddexp(global_log_min_bound, + * global_log_bound_spread - log(2)) + */ + ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_nodeheap->__pyx_vtab)->clear(__pyx_v_nodeheap); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2228 + * + * nodeheap.clear() + * return logaddexp(global_log_min_bound, # <<<<<<<<<<<<<< + * global_log_bound_spread - log(2)) + * + */ + __pyx_r = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_v_global_log_min_bound, (__pyx_v_global_log_bound_spread - log(2.0))); + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2091 + * return count + * + * cdef DTYPE_t _kde_single_breadthfirst(self, DTYPE_t* pt, # <<<<<<<<<<<<<< + * KernelType kernel, DTYPE_t h, + * DTYPE_t log_knorm, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_WriteUnraisable("sklearn.neighbors.kd_tree.BinaryTree._kde_single_breadthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2231 + * global_log_bound_spread - log(2)) + * + * cdef int _kde_single_depthfirst( # <<<<<<<<<<<<<< + * self, ITYPE_t i_node, DTYPE_t* pt, + * KernelType kernel, DTYPE_t h, + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__kde_single_depthfirst(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType __pyx_v_kernel, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_h, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_knorm, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_atol, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_rtol, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_local_log_min_bound, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_local_log_bound_spread, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_global_log_min_bound, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_global_log_bound_spread) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_N1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_N2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_log_dens_contribution; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_child1_log_min_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_child2_log_min_bound; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_child1_log_bound_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_child2_log_bound_spread; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + int __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_10; + int __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_kde_single_depthfirst", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2248 + * cdef ITYPE_t i, i1, i2, N1, N2 + * + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2248; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_1 * __pyx_v_self->data.strides[0]) )) + __pyx_t_2)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2249 + * + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2249; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2250 + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * + * cdef NodeData_t node_info = self.node_data[i_node] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2250; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2252 + * cdef ITYPE_t n_features = self.data.shape[1] + * + * cdef NodeData_t node_info = self.node_data[i_node] # <<<<<<<<<<<<<< + * cdef DTYPE_t dist_pt, log_dens_contribution + * + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2252; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = __pyx_v_i_node; + __pyx_v_node_info = (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_4)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2257 + * cdef DTYPE_t child1_log_min_bound, child2_log_min_bound + * cdef DTYPE_t child1_log_bound_spread, child2_log_bound_spread + * cdef DTYPE_t dist_UB = 0, dist_LB = 0 # <<<<<<<<<<<<<< + * + * N1 = node_info.idx_end - node_info.idx_start + */ + __pyx_v_dist_UB = 0.0; + __pyx_v_dist_LB = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2259 + * cdef DTYPE_t dist_UB = 0, dist_LB = 0 + * + * N1 = node_info.idx_end - node_info.idx_start # <<<<<<<<<<<<<< + * N2 = self.data.shape[0] + * + */ + __pyx_v_N1 = (__pyx_v_node_info.idx_end - __pyx_v_node_info.idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2260 + * + * N1 = node_info.idx_end - node_info.idx_start + * N2 = self.data.shape[0] # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2260; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_N2 = (__pyx_v_self->data.shape[0]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2265 + * # Case 1: local bounds are equal to within errors. Return + * if (log_knorm + local_log_bound_spread - log(N1) + log(N2) + * <= logaddexp(log_atol, (log_rtol + log_knorm # <<<<<<<<<<<<<< + * + local_log_min_bound))): + * pass + */ + __pyx_t_5 = (((((__pyx_v_log_knorm + __pyx_v_local_log_bound_spread) - log(__pyx_v_N1)) + log(__pyx_v_N2)) <= __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_v_log_atol, ((__pyx_v_log_rtol + __pyx_v_log_knorm) + __pyx_v_local_log_min_bound))) != 0); + if (__pyx_t_5) { + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2272 + * # Case 2: global bounds are within rtol & atol. Return + * elif (log_knorm + global_log_bound_spread[0] + * <= logaddexp(log_atol, (log_rtol + log_knorm # <<<<<<<<<<<<<< + * + global_log_min_bound[0]))): + * pass + */ + __pyx_t_5 = (((__pyx_v_log_knorm + (__pyx_v_global_log_bound_spread[0])) <= __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp(__pyx_v_log_atol, ((__pyx_v_log_rtol + __pyx_v_log_knorm) + (__pyx_v_global_log_min_bound[0])))) != 0); + if (__pyx_t_5) { + goto __pyx_L3; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2278 + * #------------------------------------------------------------ + * # Case 3: node is a leaf. Count contributions from all points + * elif node_info.is_leaf: # <<<<<<<<<<<<<< + * global_log_min_bound[0] = logsubexp(global_log_min_bound[0], + * local_log_min_bound) + */ + __pyx_t_5 = (__pyx_v_node_info.is_leaf != 0); + if (__pyx_t_5) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2279 + * # Case 3: node is a leaf. Count contributions from all points + * elif node_info.is_leaf: + * global_log_min_bound[0] = logsubexp(global_log_min_bound[0], # <<<<<<<<<<<<<< + * local_log_min_bound) + * global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], + */ + (__pyx_v_global_log_min_bound[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp((__pyx_v_global_log_min_bound[0]), __pyx_v_local_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2281 + * global_log_min_bound[0] = logsubexp(global_log_min_bound[0], + * local_log_min_bound) + * global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], # <<<<<<<<<<<<<< + * local_log_bound_spread) + * for i in range(node_info.idx_start, node_info.idx_end): + */ + (__pyx_v_global_log_bound_spread[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp((__pyx_v_global_log_bound_spread[0]), __pyx_v_local_log_bound_spread); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2283 + * global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], + * local_log_bound_spread) + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + * n_features) + */ + __pyx_t_6 = __pyx_v_node_info.idx_end; + for (__pyx_t_7 = __pyx_v_node_info.idx_start; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2284 + * local_log_bound_spread) + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), # <<<<<<<<<<<<<< + * n_features) + * log_dens_contribution = compute_log_kernel(dist_pt, h, kernel) + */ + __pyx_t_8 = __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_dist(__pyx_v_self, __pyx_v_pt, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features); if (unlikely(__pyx_t_8 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2286 + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + * n_features) + * log_dens_contribution = compute_log_kernel(dist_pt, h, kernel) # <<<<<<<<<<<<<< + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + * log_dens_contribution) + */ + __pyx_v_log_dens_contribution = __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_pt, __pyx_v_h, __pyx_v_kernel); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2287 + * n_features) + * log_dens_contribution = compute_log_kernel(dist_pt, h, kernel) + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], # <<<<<<<<<<<<<< + * log_dens_contribution) + * + */ + (__pyx_v_global_log_min_bound[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp((__pyx_v_global_log_min_bound[0]), __pyx_v_log_dens_contribution); + } + goto __pyx_L3; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2293 + * # Case 4: split node and query subnodes + * else: + * i1 = 2 * i_node + 1 # <<<<<<<<<<<<<< + * i2 = 2 * i_node + 2 + * + */ + __pyx_v_i1 = ((2 * __pyx_v_i_node) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2294 + * else: + * i1 = 2 * i_node + 1 + * i2 = 2 * i_node + 2 # <<<<<<<<<<<<<< + * + * N1 = self.node_data[i1].idx_end - self.node_data[i1].idx_start + */ + __pyx_v_i2 = ((2 * __pyx_v_i_node) + 2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2296 + * i2 = 2 * i_node + 2 + * + * N1 = self.node_data[i1].idx_end - self.node_data[i1].idx_start # <<<<<<<<<<<<<< + * N2 = self.node_data[i2].idx_end - self.node_data[i2].idx_start + * + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2296; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_6 = __pyx_v_i1; + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2296; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = __pyx_v_i1; + __pyx_v_N1 = ((*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_6)) ))).idx_end - (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_7)) ))).idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2297 + * + * N1 = self.node_data[i1].idx_end - self.node_data[i1].idx_start + * N2 = self.node_data[i2].idx_end - self.node_data[i2].idx_start # <<<<<<<<<<<<<< + * + * min_max_dist(self, i1, pt, &dist_LB, &dist_UB) + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2297; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = __pyx_v_i2; + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2297; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = __pyx_v_i2; + __pyx_v_N2 = ((*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_9)) ))).idx_end - (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_10)) ))).idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2299 + * N2 = self.node_data[i2].idx_end - self.node_data[i2].idx_start + * + * min_max_dist(self, i1, pt, &dist_LB, &dist_UB) # <<<<<<<<<<<<<< + * child1_log_min_bound = log(N1) + compute_log_kernel(dist_UB, h, + * kernel) + */ + __pyx_t_11 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_max_dist(__pyx_v_self, __pyx_v_i1, __pyx_v_pt, (&__pyx_v_dist_LB), (&__pyx_v_dist_UB)); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2300 + * + * min_max_dist(self, i1, pt, &dist_LB, &dist_UB) + * child1_log_min_bound = log(N1) + compute_log_kernel(dist_UB, h, # <<<<<<<<<<<<<< + * kernel) + * child1_log_bound_spread = logsubexp(log(N1) + + */ + __pyx_v_child1_log_min_bound = (log(__pyx_v_N1) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_UB, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2302 + * child1_log_min_bound = log(N1) + compute_log_kernel(dist_UB, h, + * kernel) + * child1_log_bound_spread = logsubexp(log(N1) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_LB, h, + * kernel), + */ + __pyx_v_child1_log_bound_spread = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp((log(__pyx_v_N1) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_LB, __pyx_v_h, __pyx_v_kernel)), __pyx_v_child1_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2307 + * child1_log_min_bound) + * + * min_max_dist(self, i2, pt, &dist_LB, &dist_UB) # <<<<<<<<<<<<<< + * child2_log_min_bound = log(N2) + compute_log_kernel(dist_UB, h, + * kernel) + */ + __pyx_t_11 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_max_dist(__pyx_v_self, __pyx_v_i2, __pyx_v_pt, (&__pyx_v_dist_LB), (&__pyx_v_dist_UB)); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2307; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2308 + * + * min_max_dist(self, i2, pt, &dist_LB, &dist_UB) + * child2_log_min_bound = log(N2) + compute_log_kernel(dist_UB, h, # <<<<<<<<<<<<<< + * kernel) + * child2_log_bound_spread = logsubexp(log(N2) + + */ + __pyx_v_child2_log_min_bound = (log(__pyx_v_N2) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_UB, __pyx_v_h, __pyx_v_kernel)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2310 + * child2_log_min_bound = log(N2) + compute_log_kernel(dist_UB, h, + * kernel) + * child2_log_bound_spread = logsubexp(log(N2) + # <<<<<<<<<<<<<< + * compute_log_kernel(dist_LB, h, + * kernel), + */ + __pyx_v_child2_log_bound_spread = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp((log(__pyx_v_N2) + __pyx_f_7sklearn_9neighbors_7kd_tree_compute_log_kernel(__pyx_v_dist_LB, __pyx_v_h, __pyx_v_kernel)), __pyx_v_child2_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2315 + * child2_log_min_bound) + * + * global_log_min_bound[0] = logsubexp(global_log_min_bound[0], # <<<<<<<<<<<<<< + * local_log_min_bound) + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + */ + (__pyx_v_global_log_min_bound[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp((__pyx_v_global_log_min_bound[0]), __pyx_v_local_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2317 + * global_log_min_bound[0] = logsubexp(global_log_min_bound[0], + * local_log_min_bound) + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], # <<<<<<<<<<<<<< + * child1_log_min_bound) + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + */ + (__pyx_v_global_log_min_bound[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp((__pyx_v_global_log_min_bound[0]), __pyx_v_child1_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2319 + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + * child1_log_min_bound) + * global_log_min_bound[0] = logaddexp(global_log_min_bound[0], # <<<<<<<<<<<<<< + * child2_log_min_bound) + * + */ + (__pyx_v_global_log_min_bound[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp((__pyx_v_global_log_min_bound[0]), __pyx_v_child2_log_min_bound); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2322 + * child2_log_min_bound) + * + * global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], # <<<<<<<<<<<<<< + * local_log_bound_spread) + * global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], + */ + (__pyx_v_global_log_bound_spread[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_logsubexp((__pyx_v_global_log_bound_spread[0]), __pyx_v_local_log_bound_spread); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2324 + * global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], + * local_log_bound_spread) + * global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], # <<<<<<<<<<<<<< + * child1_log_bound_spread) + * global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], + */ + (__pyx_v_global_log_bound_spread[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp((__pyx_v_global_log_bound_spread[0]), __pyx_v_child1_log_bound_spread); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2326 + * global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], + * child1_log_bound_spread) + * global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], # <<<<<<<<<<<<<< + * child2_log_bound_spread) + * + */ + (__pyx_v_global_log_bound_spread[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_logaddexp((__pyx_v_global_log_bound_spread[0]), __pyx_v_child2_log_bound_spread); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2329 + * child2_log_bound_spread) + * + * self._kde_single_depthfirst(i1, pt, kernel, h, log_knorm, # <<<<<<<<<<<<<< + * log_atol, log_rtol, + * child1_log_min_bound, + */ + __pyx_t_11 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_kde_single_depthfirst(__pyx_v_self, __pyx_v_i1, __pyx_v_pt, __pyx_v_kernel, __pyx_v_h, __pyx_v_log_knorm, __pyx_v_log_atol, __pyx_v_log_rtol, __pyx_v_child1_log_min_bound, __pyx_v_child1_log_bound_spread, __pyx_v_global_log_min_bound, __pyx_v_global_log_bound_spread); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2335 + * global_log_min_bound, + * global_log_bound_spread) + * self._kde_single_depthfirst(i2, pt, kernel, h, log_knorm, # <<<<<<<<<<<<<< + * log_atol, log_rtol, + * child2_log_min_bound, + */ + __pyx_t_11 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_kde_single_depthfirst(__pyx_v_self, __pyx_v_i2, __pyx_v_pt, __pyx_v_kernel, __pyx_v_h, __pyx_v_log_knorm, __pyx_v_log_atol, __pyx_v_log_rtol, __pyx_v_child2_log_min_bound, __pyx_v_child2_log_bound_spread, __pyx_v_global_log_min_bound, __pyx_v_global_log_bound_spread); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2341 + * global_log_min_bound, + * global_log_bound_spread) + * return 0 # <<<<<<<<<<<<<< + * + * cdef int _two_point_single(self, ITYPE_t i_node, DTYPE_t* pt, DTYPE_t* r, + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2231 + * global_log_bound_spread - log(2)) + * + * cdef int _kde_single_depthfirst( # <<<<<<<<<<<<<< + * self, ITYPE_t i_node, DTYPE_t* pt, + * KernelType kernel, DTYPE_t h, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree._kde_single_depthfirst", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2343 + * return 0 + * + * cdef int _two_point_single(self, ITYPE_t i_node, DTYPE_t* pt, DTYPE_t* r, # <<<<<<<<<<<<<< + * ITYPE_t* count, ITYPE_t i_min, + * ITYPE_t i_max) except -1: + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__two_point_single(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_r, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_count, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_min, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_max) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_Npts; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + long __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_two_point_single", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2347 + * ITYPE_t i_max) except -1: + * """recursive single-tree two-point correlation function query""" + * cdef DTYPE_t* data = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2347; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_1 * __pyx_v_self->data.strides[0]) )) + __pyx_t_2)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2348 + * """recursive single-tree two-point correlation function query""" + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef NodeData_t node_info = self.node_data[i_node] + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2348; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_3)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2349 + * cdef DTYPE_t* data = &self.data[0, 0] + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info = self.node_data[i_node] + * + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2349; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2350 + * cdef ITYPE_t* idx_array = &self.idx_array[0] + * cdef ITYPE_t n_features = self.data.shape[1] + * cdef NodeData_t node_info = self.node_data[i_node] # <<<<<<<<<<<<<< + * + * cdef ITYPE_t i, j, Npts + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2350; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = __pyx_v_i_node; + __pyx_v_node_info = (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_4)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2355 + * cdef DTYPE_t reduced_r + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 # <<<<<<<<<<<<<< + * min_max_dist(self, i_node, pt, &dist_LB, &dist_UB) + * + */ + __pyx_v_dist_LB = 0.0; + __pyx_v_dist_UB = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2356 + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 + * min_max_dist(self, i_node, pt, &dist_LB, &dist_UB) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_max_dist(__pyx_v_self, __pyx_v_i_node, __pyx_v_pt, (&__pyx_v_dist_LB), (&__pyx_v_dist_UB)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2360 + * #------------------------------------------------------------ + * # Go through bounds and check for cuts + * while i_min < i_max: # <<<<<<<<<<<<<< + * if dist_LB > r[i_min]: + * i_min += 1 + */ + while (1) { + __pyx_t_6 = ((__pyx_v_i_min < __pyx_v_i_max) != 0); + if (!__pyx_t_6) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2361 + * # Go through bounds and check for cuts + * while i_min < i_max: + * if dist_LB > r[i_min]: # <<<<<<<<<<<<<< + * i_min += 1 + * else: + */ + __pyx_t_6 = ((__pyx_v_dist_LB > (__pyx_v_r[__pyx_v_i_min])) != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2362 + * while i_min < i_max: + * if dist_LB > r[i_min]: + * i_min += 1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_min = (__pyx_v_i_min + 1); + goto __pyx_L5; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2364 + * i_min += 1 + * else: + * break # <<<<<<<<<<<<<< + * + * while i_max > i_min: + */ + goto __pyx_L4_break; + } + __pyx_L5:; + } + __pyx_L4_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2366 + * break + * + * while i_max > i_min: # <<<<<<<<<<<<<< + * Npts = (node_info.idx_end - node_info.idx_start) + * if dist_UB <= r[i_max - 1]: + */ + while (1) { + __pyx_t_6 = ((__pyx_v_i_max > __pyx_v_i_min) != 0); + if (!__pyx_t_6) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2367 + * + * while i_max > i_min: + * Npts = (node_info.idx_end - node_info.idx_start) # <<<<<<<<<<<<<< + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts + */ + __pyx_v_Npts = (__pyx_v_node_info.idx_end - __pyx_v_node_info.idx_start); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2368 + * while i_max > i_min: + * Npts = (node_info.idx_end - node_info.idx_start) + * if dist_UB <= r[i_max - 1]: # <<<<<<<<<<<<<< + * count[i_max - 1] += Npts + * i_max -= 1 + */ + __pyx_t_6 = ((__pyx_v_dist_UB <= (__pyx_v_r[(__pyx_v_i_max - 1)])) != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2369 + * Npts = (node_info.idx_end - node_info.idx_start) + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts # <<<<<<<<<<<<<< + * i_max -= 1 + * else: + */ + __pyx_t_7 = (__pyx_v_i_max - 1); + (__pyx_v_count[__pyx_t_7]) = ((__pyx_v_count[__pyx_t_7]) + __pyx_v_Npts); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2370 + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts + * i_max -= 1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_max = (__pyx_v_i_max - 1); + goto __pyx_L8; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2372 + * i_max -= 1 + * else: + * break # <<<<<<<<<<<<<< + * + * if i_min < i_max: + */ + goto __pyx_L7_break; + } + __pyx_L8:; + } + __pyx_L7_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2374 + * break + * + * if i_min < i_max: # <<<<<<<<<<<<<< + * # If node is a leaf, go through all points + * if node_info.is_leaf: + */ + __pyx_t_6 = ((__pyx_v_i_min < __pyx_v_i_max) != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2376 + * if i_min < i_max: + * # If node is a leaf, go through all points + * if node_info.is_leaf: # <<<<<<<<<<<<<< + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + */ + __pyx_t_6 = (__pyx_v_node_info.is_leaf != 0); + if (__pyx_t_6) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2377 + * # If node is a leaf, go through all points + * if node_info.is_leaf: + * for i in range(node_info.idx_start, node_info.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + * n_features) + */ + __pyx_t_8 = __pyx_v_node_info.idx_end; + for (__pyx_t_9 = __pyx_v_node_info.idx_start; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { + __pyx_v_i = __pyx_t_9; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2378 + * if node_info.is_leaf: + * for i in range(node_info.idx_start, node_info.idx_end): + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), # <<<<<<<<<<<<<< + * n_features) + * j = i_max - 1 + */ + __pyx_t_10 = __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_dist(__pyx_v_self, __pyx_v_pt, (__pyx_v_data + (__pyx_v_n_features * (__pyx_v_idx_array[__pyx_v_i]))), __pyx_v_n_features); if (unlikely(__pyx_t_10 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_10; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2380 + * dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + * n_features) + * j = i_max - 1 # <<<<<<<<<<<<<< + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 + */ + __pyx_v_j = (__pyx_v_i_max - 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2381 + * n_features) + * j = i_max - 1 + * while (j >= i_min) and (dist_pt <= r[j]): # <<<<<<<<<<<<<< + * count[j] += 1 + * j -= 1 + */ + while (1) { + __pyx_t_6 = ((__pyx_v_j >= __pyx_v_i_min) != 0); + if (__pyx_t_6) { + __pyx_t_11 = ((__pyx_v_dist_pt <= (__pyx_v_r[__pyx_v_j])) != 0); + __pyx_t_12 = __pyx_t_11; + } else { + __pyx_t_12 = __pyx_t_6; + } + if (!__pyx_t_12) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2382 + * j = i_max - 1 + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 # <<<<<<<<<<<<<< + * j -= 1 + * + */ + __pyx_t_13 = __pyx_v_j; + (__pyx_v_count[__pyx_t_13]) = ((__pyx_v_count[__pyx_t_13]) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2383 + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 + * j -= 1 # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_v_j = (__pyx_v_j - 1); + } + } + goto __pyx_L10; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2386 + * + * else: + * self._two_point_single(2 * i_node + 1, pt, r, # <<<<<<<<<<<<<< + * count, i_min, i_max) + * self._two_point_single(2 * i_node + 2, pt, r, + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_single(__pyx_v_self, ((2 * __pyx_v_i_node) + 1), __pyx_v_pt, __pyx_v_r, __pyx_v_count, __pyx_v_i_min, __pyx_v_i_max); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2388 + * self._two_point_single(2 * i_node + 1, pt, r, + * count, i_min, i_max) + * self._two_point_single(2 * i_node + 2, pt, r, # <<<<<<<<<<<<<< + * count, i_min, i_max) + * return 0 + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_single(__pyx_v_self, ((2 * __pyx_v_i_node) + 2), __pyx_v_pt, __pyx_v_r, __pyx_v_count, __pyx_v_i_min, __pyx_v_i_max); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2388; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L10:; + goto __pyx_L9; + } + __pyx_L9:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2390 + * self._two_point_single(2 * i_node + 2, pt, r, + * count, i_min, i_max) + * return 0 # <<<<<<<<<<<<<< + * + * cdef int _two_point_dual(self, ITYPE_t i_node1, + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2343 + * return 0 + * + * cdef int _two_point_single(self, ITYPE_t i_node, DTYPE_t* pt, DTYPE_t* r, # <<<<<<<<<<<<<< + * ITYPE_t* count, ITYPE_t i_min, + * ITYPE_t i_max) except -1: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree._two_point_single", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2392 + * return 0 + * + * cdef int _two_point_dual(self, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree other, ITYPE_t i_node2, + * DTYPE_t* r, ITYPE_t* count, + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__two_point_dual(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_other, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_r, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_count, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_min, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_max) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array2; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info1; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_v_node_info2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_Npts; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_pt; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_LB; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist_UB; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_9; + int __pyx_t_10; + long __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + int __pyx_t_16; + int __pyx_t_17; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_18; + int __pyx_t_19; + long __pyx_t_20; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_two_point_dual", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2397 + * ITYPE_t i_min, ITYPE_t i_max) except -1: + * """recursive dual-tree two-point correlation function query""" + * cdef DTYPE_t* data1 = &self.data[0, 0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t* idx_array1 = &self.idx_array[0] + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2397; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_v_data1 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_self->data.data + __pyx_t_1 * __pyx_v_self->data.strides[0]) )) + __pyx_t_2)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2398 + * """recursive dual-tree two-point correlation function query""" + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array1 = &self.idx_array[0] + * cdef ITYPE_t* idx_array2 = &other.idx_array[0] + */ + if (unlikely(!__pyx_v_other->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2398; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_v_data2 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_other->data.data + __pyx_t_3 * __pyx_v_other->data.strides[0]) )) + __pyx_t_4)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2399 + * cdef DTYPE_t* data1 = &self.data[0, 0] + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t* idx_array1 = &self.idx_array[0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array2 = &other.idx_array[0] + * cdef NodeData_t node_info1 = self.node_data[i_node1] + */ + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2399; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_5 = 0; + __pyx_v_idx_array1 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_self->idx_array.data) + __pyx_t_5)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2400 + * cdef DTYPE_t* data2 = &other.data[0, 0] + * cdef ITYPE_t* idx_array1 = &self.idx_array[0] + * cdef ITYPE_t* idx_array2 = &other.idx_array[0] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info1 = self.node_data[i_node1] + * cdef NodeData_t node_info2 = other.node_data[i_node2] + */ + if (unlikely(!__pyx_v_other->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2400; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_6 = 0; + __pyx_v_idx_array2 = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_other->idx_array.data) + __pyx_t_6)) )))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2401 + * cdef ITYPE_t* idx_array1 = &self.idx_array[0] + * cdef ITYPE_t* idx_array2 = &other.idx_array[0] + * cdef NodeData_t node_info1 = self.node_data[i_node1] # <<<<<<<<<<<<<< + * cdef NodeData_t node_info2 = other.node_data[i_node2] + * + */ + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2401; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = __pyx_v_i_node1; + __pyx_v_node_info1 = (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_self->node_data.data) + __pyx_t_7)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2402 + * cdef ITYPE_t* idx_array2 = &other.idx_array[0] + * cdef NodeData_t node_info1 = self.node_data[i_node1] + * cdef NodeData_t node_info2 = other.node_data[i_node2] # <<<<<<<<<<<<<< + * + * cdef ITYPE_t n_features = self.data.shape[1] + */ + if (unlikely(!__pyx_v_other->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2402; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_8 = __pyx_v_i_node2; + __pyx_v_node_info2 = (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_other->node_data.data) + __pyx_t_8)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2404 + * cdef NodeData_t node_info2 = other.node_data[i_node2] + * + * cdef ITYPE_t n_features = self.data.shape[1] # <<<<<<<<<<<<<< + * + * cdef ITYPE_t i1, i2, j, Npts + */ + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 2404; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_self->data.shape[1]); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2409 + * cdef DTYPE_t reduced_r + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 # <<<<<<<<<<<<<< + * dist_LB = min_dist_dual(self, i_node1, other, i_node2) + * dist_UB = max_dist_dual(self, i_node1, other, i_node2) + */ + __pyx_v_dist_LB = 0.0; + __pyx_v_dist_UB = 0.0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2410 + * + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 + * dist_LB = min_dist_dual(self, i_node1, other, i_node2) # <<<<<<<<<<<<<< + * dist_UB = max_dist_dual(self, i_node1, other, i_node2) + * + */ + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_dist_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, __pyx_v_i_node2); if (unlikely(__pyx_t_9 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_LB = __pyx_t_9; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2411 + * cdef DTYPE_t dist_pt, dist_LB = 0, dist_UB = 0 + * dist_LB = min_dist_dual(self, i_node1, other, i_node2) + * dist_UB = max_dist_dual(self, i_node1, other, i_node2) # <<<<<<<<<<<<<< + * + * #------------------------------------------------------------ + */ + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_7kd_tree_max_dist_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, __pyx_v_i_node2); if (unlikely(__pyx_t_9 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_UB = __pyx_t_9; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2415 + * #------------------------------------------------------------ + * # Go through bounds and check for cuts + * while i_min < i_max: # <<<<<<<<<<<<<< + * if dist_LB > r[i_min]: + * i_min += 1 + */ + while (1) { + __pyx_t_10 = ((__pyx_v_i_min < __pyx_v_i_max) != 0); + if (!__pyx_t_10) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2416 + * # Go through bounds and check for cuts + * while i_min < i_max: + * if dist_LB > r[i_min]: # <<<<<<<<<<<<<< + * i_min += 1 + * else: + */ + __pyx_t_10 = ((__pyx_v_dist_LB > (__pyx_v_r[__pyx_v_i_min])) != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2417 + * while i_min < i_max: + * if dist_LB > r[i_min]: + * i_min += 1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_min = (__pyx_v_i_min + 1); + goto __pyx_L5; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2419 + * i_min += 1 + * else: + * break # <<<<<<<<<<<<<< + * + * while i_max > i_min: + */ + goto __pyx_L4_break; + } + __pyx_L5:; + } + __pyx_L4_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2421 + * break + * + * while i_max > i_min: # <<<<<<<<<<<<<< + * Npts = ((node_info1.idx_end - node_info1.idx_start) + * * (node_info2.idx_end - node_info2.idx_start)) + */ + while (1) { + __pyx_t_10 = ((__pyx_v_i_max > __pyx_v_i_min) != 0); + if (!__pyx_t_10) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2423 + * while i_max > i_min: + * Npts = ((node_info1.idx_end - node_info1.idx_start) + * * (node_info2.idx_end - node_info2.idx_start)) # <<<<<<<<<<<<<< + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts + */ + __pyx_v_Npts = ((__pyx_v_node_info1.idx_end - __pyx_v_node_info1.idx_start) * (__pyx_v_node_info2.idx_end - __pyx_v_node_info2.idx_start)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2424 + * Npts = ((node_info1.idx_end - node_info1.idx_start) + * * (node_info2.idx_end - node_info2.idx_start)) + * if dist_UB <= r[i_max - 1]: # <<<<<<<<<<<<<< + * count[i_max - 1] += Npts + * i_max -= 1 + */ + __pyx_t_10 = ((__pyx_v_dist_UB <= (__pyx_v_r[(__pyx_v_i_max - 1)])) != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2425 + * * (node_info2.idx_end - node_info2.idx_start)) + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts # <<<<<<<<<<<<<< + * i_max -= 1 + * else: + */ + __pyx_t_11 = (__pyx_v_i_max - 1); + (__pyx_v_count[__pyx_t_11]) = ((__pyx_v_count[__pyx_t_11]) + __pyx_v_Npts); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2426 + * if dist_UB <= r[i_max - 1]: + * count[i_max - 1] += Npts + * i_max -= 1 # <<<<<<<<<<<<<< + * else: + * break + */ + __pyx_v_i_max = (__pyx_v_i_max - 1); + goto __pyx_L8; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2428 + * i_max -= 1 + * else: + * break # <<<<<<<<<<<<<< + * + * if i_min < i_max: + */ + goto __pyx_L7_break; + } + __pyx_L8:; + } + __pyx_L7_break:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2430 + * break + * + * if i_min < i_max: # <<<<<<<<<<<<<< + * if node_info1.is_leaf and node_info2.is_leaf: + * # If both nodes are leaves, go through all points + */ + __pyx_t_10 = ((__pyx_v_i_min < __pyx_v_i_max) != 0); + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2431 + * + * if i_min < i_max: + * if node_info1.is_leaf and node_info2.is_leaf: # <<<<<<<<<<<<<< + * # If both nodes are leaves, go through all points + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + */ + if ((__pyx_v_node_info1.is_leaf != 0)) { + __pyx_t_10 = (__pyx_v_node_info2.is_leaf != 0); + } else { + __pyx_t_10 = (__pyx_v_node_info1.is_leaf != 0); + } + if (__pyx_t_10) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2433 + * if node_info1.is_leaf and node_info2.is_leaf: + * # If both nodes are leaves, go through all points + * for i1 in range(node_info1.idx_start, node_info1.idx_end): # <<<<<<<<<<<<<< + * for i2 in range(node_info2.idx_start, node_info2.idx_end): + * dist_pt = self.dist((data1 + n_features + */ + __pyx_t_12 = __pyx_v_node_info1.idx_end; + for (__pyx_t_13 = __pyx_v_node_info1.idx_start; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_i1 = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2434 + * # If both nodes are leaves, go through all points + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * for i2 in range(node_info2.idx_start, node_info2.idx_end): # <<<<<<<<<<<<<< + * dist_pt = self.dist((data1 + n_features + * * idx_array1[i1]), + */ + __pyx_t_14 = __pyx_v_node_info2.idx_end; + for (__pyx_t_15 = __pyx_v_node_info2.idx_start; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { + __pyx_v_i2 = __pyx_t_15; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2435 + * for i1 in range(node_info1.idx_start, node_info1.idx_end): + * for i2 in range(node_info2.idx_start, node_info2.idx_end): + * dist_pt = self.dist((data1 + n_features # <<<<<<<<<<<<<< + * * idx_array1[i1]), + * (data2 + n_features + */ + __pyx_t_9 = __pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_dist(__pyx_v_self, (__pyx_v_data1 + (__pyx_v_n_features * (__pyx_v_idx_array1[__pyx_v_i1]))), (__pyx_v_data2 + (__pyx_v_n_features * (__pyx_v_idx_array2[__pyx_v_i2]))), __pyx_v_n_features); if (unlikely(__pyx_t_9 == -1.0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dist_pt = __pyx_t_9; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2440 + * * idx_array2[i2]), + * n_features) + * j = i_max - 1 # <<<<<<<<<<<<<< + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 + */ + __pyx_v_j = (__pyx_v_i_max - 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2441 + * n_features) + * j = i_max - 1 + * while (j >= i_min) and (dist_pt <= r[j]): # <<<<<<<<<<<<<< + * count[j] += 1 + * j -= 1 + */ + while (1) { + __pyx_t_10 = ((__pyx_v_j >= __pyx_v_i_min) != 0); + if (__pyx_t_10) { + __pyx_t_16 = ((__pyx_v_dist_pt <= (__pyx_v_r[__pyx_v_j])) != 0); + __pyx_t_17 = __pyx_t_16; + } else { + __pyx_t_17 = __pyx_t_10; + } + if (!__pyx_t_17) break; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2442 + * j = i_max - 1 + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 # <<<<<<<<<<<<<< + * j -= 1 + * + */ + __pyx_t_18 = __pyx_v_j; + (__pyx_v_count[__pyx_t_18]) = ((__pyx_v_count[__pyx_t_18]) + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2443 + * while (j >= i_min) and (dist_pt <= r[j]): + * count[j] += 1 + * j -= 1 # <<<<<<<<<<<<<< + * + * elif node_info1.is_leaf: + */ + __pyx_v_j = (__pyx_v_j - 1); + } + } + } + goto __pyx_L10; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2445 + * j -= 1 + * + * elif node_info1.is_leaf: # <<<<<<<<<<<<<< + * # If only one is a leaf, split the other + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + */ + __pyx_t_17 = (__pyx_v_node_info1.is_leaf != 0); + if (__pyx_t_17) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2447 + * elif node_info1.is_leaf: + * # If only one is a leaf, split the other + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): # <<<<<<<<<<<<<< + * self._two_point_dual(i_node1, other, i2, + * r, count, i_min, i_max) + */ + __pyx_t_11 = ((2 * __pyx_v_i_node2) + 3); + for (__pyx_t_12 = ((2 * __pyx_v_i_node2) + 1); __pyx_t_12 < __pyx_t_11; __pyx_t_12+=1) { + __pyx_v_i2 = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2448 + * # If only one is a leaf, split the other + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * self._two_point_dual(i_node1, other, i2, # <<<<<<<<<<<<<< + * r, count, i_min, i_max) + * + */ + __pyx_t_19 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_dual(__pyx_v_self, __pyx_v_i_node1, __pyx_v_other, __pyx_v_i2, __pyx_v_r, __pyx_v_count, __pyx_v_i_min, __pyx_v_i_max); if (unlikely(__pyx_t_19 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2448; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L10; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2451 + * r, count, i_min, i_max) + * + * elif node_info2.is_leaf: # <<<<<<<<<<<<<< + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * self._two_point_dual(i1, other, i_node2, + */ + __pyx_t_17 = (__pyx_v_node_info2.is_leaf != 0); + if (__pyx_t_17) { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2452 + * + * elif node_info2.is_leaf: + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): # <<<<<<<<<<<<<< + * self._two_point_dual(i1, other, i_node2, + * r, count, i_min, i_max) + */ + __pyx_t_11 = ((2 * __pyx_v_i_node1) + 3); + for (__pyx_t_12 = ((2 * __pyx_v_i_node1) + 1); __pyx_t_12 < __pyx_t_11; __pyx_t_12+=1) { + __pyx_v_i1 = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2453 + * elif node_info2.is_leaf: + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * self._two_point_dual(i1, other, i_node2, # <<<<<<<<<<<<<< + * r, count, i_min, i_max) + * + */ + __pyx_t_19 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_dual(__pyx_v_self, __pyx_v_i1, __pyx_v_other, __pyx_v_i_node2, __pyx_v_r, __pyx_v_count, __pyx_v_i_min, __pyx_v_i_max); if (unlikely(__pyx_t_19 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L10; + } + /*else*/ { + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2458 + * else: + * # neither is a leaf: split & query both + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): # <<<<<<<<<<<<<< + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * self._two_point_dual(i1, other, i2, + */ + __pyx_t_11 = ((2 * __pyx_v_i_node1) + 3); + for (__pyx_t_12 = ((2 * __pyx_v_i_node1) + 1); __pyx_t_12 < __pyx_t_11; __pyx_t_12+=1) { + __pyx_v_i1 = __pyx_t_12; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2459 + * # neither is a leaf: split & query both + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): # <<<<<<<<<<<<<< + * self._two_point_dual(i1, other, i2, + * r, count, i_min, i_max) + */ + __pyx_t_20 = ((2 * __pyx_v_i_node2) + 3); + for (__pyx_t_13 = ((2 * __pyx_v_i_node2) + 1); __pyx_t_13 < __pyx_t_20; __pyx_t_13+=1) { + __pyx_v_i2 = __pyx_t_13; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2460 + * for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + * for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + * self._two_point_dual(i1, other, i2, # <<<<<<<<<<<<<< + * r, count, i_min, i_max) + * return 0 + */ + __pyx_t_19 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self->__pyx_vtab)->_two_point_dual(__pyx_v_self, __pyx_v_i1, __pyx_v_other, __pyx_v_i2, __pyx_v_r, __pyx_v_count, __pyx_v_i_min, __pyx_v_i_max); if (unlikely(__pyx_t_19 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + } + __pyx_L10:; + goto __pyx_L9; + } + __pyx_L9:; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2462 + * self._two_point_dual(i1, other, i2, + * r, count, i_min, i_max) + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2392 + * return 0 + * + * cdef int _two_point_dual(self, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree other, ITYPE_t i_node2, + * DTYPE_t* r, ITYPE_t* count, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree._two_point_dual", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1004 + * cdef np.ndarray node_bounds_arr + * + * cdef readonly DTYPE_t[:, ::1] data # <<<<<<<<<<<<<< + * cdef public ITYPE_t[::1] idx_array + * cdef public NodeData_t[::1] node_data + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_4data_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_4data_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_4data___get__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_4data___get__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_self->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1004; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_self->data, 2, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1004; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.data.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1005 + * + * cdef readonly DTYPE_t[:, ::1] data + * cdef public ITYPE_t[::1] idx_array # <<<<<<<<<<<<<< + * cdef public NodeData_t[::1] node_data + * cdef public DTYPE_t[:, :, ::1] node_bounds + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array___get__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array___get__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_self->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1005; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_self->idx_array, 1, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, 0);; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1005; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.idx_array.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array_2__set__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array_2__set__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(__pyx_v_value); + if (unlikely(!__pyx_t_1.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1005; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_XDEC_MEMVIEW(&__pyx_v_self->idx_array, 0); + __pyx_v_self->idx_array = __pyx_t_1; + __pyx_t_1.memview = NULL; + __pyx_t_1.data = NULL; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __PYX_XDEC_MEMVIEW(&__pyx_t_1, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.idx_array.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1006 + * cdef readonly DTYPE_t[:, ::1] data + * cdef public ITYPE_t[::1] idx_array + * cdef public NodeData_t[::1] node_data # <<<<<<<<<<<<<< + * cdef public DTYPE_t[:, :, ::1] node_bounds + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data___get__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data___get__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_self->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_self->node_data, 1, (PyObject *(*)(char *)) __pyx_memview_get_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t, 0);; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.node_data.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data_2__set__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data_2__set__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(__pyx_v_value); + if (unlikely(!__pyx_t_1.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_data, 0); + __pyx_v_self->node_data = __pyx_t_1; + __pyx_t_1.memview = NULL; + __pyx_t_1.data = NULL; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __PYX_XDEC_MEMVIEW(&__pyx_t_1, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.node_data.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1007 + * cdef public ITYPE_t[::1] idx_array + * cdef public NodeData_t[::1] node_data + * cdef public DTYPE_t[:, :, ::1] node_bounds # <<<<<<<<<<<<<< + * + * cdef ITYPE_t leaf_size + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds___get__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds___get__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_self->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[0]; __pyx_lineno = 1007; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_self->node_bounds, 3, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1007; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.node_bounds.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds_2__set__(((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds_2__set__(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(__pyx_v_value); + if (unlikely(!__pyx_t_1.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1007; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_XDEC_MEMVIEW(&__pyx_v_self->node_bounds, 0); + __pyx_v_self->node_bounds = __pyx_t_1; + __pyx_t_1.memview = NULL; + __pyx_t_1.data = NULL; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __PYX_XDEC_MEMVIEW(&__pyx_t_1, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.BinaryTree.node_bounds.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2468 + * # Python functions for benchmarking and testing C implementations + * + * def load_heap(DTYPE_t[:, ::1] X, ITYPE_t k): # <<<<<<<<<<<<<< + * """test fully loading the heap""" + * assert k <= X.shape[1] + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_5load_heap(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_4load_heap[] = "test fully loading the heap"; +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_7kd_tree_5load_heap = {__Pyx_NAMESTR("load_heap"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_5load_heap, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_4load_heap)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_5load_heap(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_k; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("load_heap (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_k,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_k)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("load_heap", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "load_heap") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_k = __Pyx_PyInt_As_Py_intptr_t(values[1]); if (unlikely((__pyx_v_k == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("load_heap", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.load_heap", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_4load_heap(__pyx_self, __pyx_v_X, __pyx_v_k); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_4load_heap(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_k) { + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *__pyx_v_heap = 0; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + int __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("load_heap", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2470 + * def load_heap(DTYPE_t[:, ::1] X, ITYPE_t k): + * """test fully loading the heap""" + * assert k <= X.shape[1] # <<<<<<<<<<<<<< + * cdef NeighborsHeap heap = NeighborsHeap(X.shape[0], k) + * cdef ITYPE_t i, j + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!((__pyx_v_k <= (__pyx_v_X.shape[1])) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2471 + * """test fully loading the heap""" + * assert k <= X.shape[1] + * cdef NeighborsHeap heap = NeighborsHeap(X.shape[0], k) # <<<<<<<<<<<<<< + * cdef ITYPE_t i, j + * for i in range(X.shape[0]): + */ + __pyx_t_1 = PyInt_FromSsize_t((__pyx_v_X.shape[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_k); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_7kd_tree_NeighborsHeap)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_heap = ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2473 + * cdef NeighborsHeap heap = NeighborsHeap(X.shape[0], k) + * cdef ITYPE_t i, j + * for i in range(X.shape[0]): # <<<<<<<<<<<<<< + * for j in range(X.shape[1]): + * heap.push(i, X[i, j], j) + */ + __pyx_t_4 = (__pyx_v_X.shape[0]); + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2474 + * cdef ITYPE_t i, j + * for i in range(X.shape[0]): + * for j in range(X.shape[1]): # <<<<<<<<<<<<<< + * heap.push(i, X[i, j], j) + * return heap.get_arrays() + */ + __pyx_t_6 = (__pyx_v_X.shape[1]); + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_j = __pyx_t_7; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2475 + * for i in range(X.shape[0]): + * for j in range(X.shape[1]): + * heap.push(i, X[i, j], j) # <<<<<<<<<<<<<< + * return heap.get_arrays() + * + */ + __pyx_t_8 = __pyx_v_i; + __pyx_t_9 = __pyx_v_j; + __pyx_t_10 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_i, (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_X.data + __pyx_t_8 * __pyx_v_X.strides[0]) )) + __pyx_t_9)) ))), __pyx_v_j, 0); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2476 + * for j in range(X.shape[1]): + * heap.push(i, X[i, j], j) + * return heap.get_arrays() # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_heap), __pyx_n_s_get_arrays); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2468 + * # Python functions for benchmarking and testing C implementations + * + * def load_heap(DTYPE_t[:, ::1] X, ITYPE_t k): # <<<<<<<<<<<<<< + * """test fully loading the heap""" + * assert k <= X.shape[1] + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.load_heap", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_heap); + __PYX_XDEC_MEMVIEW(&__pyx_v_X, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2479 + * + * + * def simultaneous_sort(DTYPE_t[:, ::1] distances, ITYPE_t[:, ::1] indices): # <<<<<<<<<<<<<< + * """In-place simultaneous sort the given row of the arrays + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_7simultaneous_sort(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_6simultaneous_sort[] = "In-place simultaneous sort the given row of the arrays\n\n This python wrapper exists primarily to enable unit testing\n of the _simultaneous_sort C routine.\n "; +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_7kd_tree_7simultaneous_sort = {__Pyx_NAMESTR("simultaneous_sort"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_7simultaneous_sort, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_6simultaneous_sort)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_7simultaneous_sort(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __Pyx_memviewslice __pyx_v_distances = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_indices = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("simultaneous_sort (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_distances,&__pyx_n_s_indices,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_distances)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_indices)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("simultaneous_sort", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "simultaneous_sort") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_distances = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(values[0]); if (unlikely(!__pyx_v_distances.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_indices = __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(values[1]); if (unlikely(!__pyx_v_indices.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("simultaneous_sort", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.simultaneous_sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_6simultaneous_sort(__pyx_self, __pyx_v_distances, __pyx_v_indices); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_6simultaneous_sort(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_distances, __Pyx_memviewslice __pyx_v_indices) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_row; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("simultaneous_sort", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2485 + * of the _simultaneous_sort C routine. + * """ + * assert distances.shape[0] == indices.shape[0] # <<<<<<<<<<<<<< + * assert distances.shape[1] == indices.shape[1] + * cdef ITYPE_t row + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_distances.shape[0]) == (__pyx_v_indices.shape[0])) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2486 + * """ + * assert distances.shape[0] == indices.shape[0] + * assert distances.shape[1] == indices.shape[1] # <<<<<<<<<<<<<< + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_distances.shape[1]) == (__pyx_v_indices.shape[1])) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2488 + * assert distances.shape[1] == indices.shape[1] + * cdef ITYPE_t row + * for row in range(distances.shape[0]): # <<<<<<<<<<<<<< + * _simultaneous_sort(&distances[row, 0], + * &indices[row, 0], + */ + __pyx_t_1 = (__pyx_v_distances.shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_row = __pyx_t_2; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2489 + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], # <<<<<<<<<<<<<< + * &indices[row, 0], + * distances.shape[1]) + */ + __pyx_t_3 = __pyx_v_row; + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2490 + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], + * &indices[row, 0], # <<<<<<<<<<<<<< + * distances.shape[1]) + * + */ + __pyx_t_5 = __pyx_v_row; + __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2489 + * cdef ITYPE_t row + * for row in range(distances.shape[0]): + * _simultaneous_sort(&distances[row, 0], # <<<<<<<<<<<<<< + * &indices[row, 0], + * distances.shape[1]) + */ + __pyx_t_7 = __pyx_f_7sklearn_9neighbors_7kd_tree__simultaneous_sort((&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_distances.data + __pyx_t_3 * __pyx_v_distances.strides[0]) )) + __pyx_t_4)) )))), (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ (__pyx_v_indices.data + __pyx_t_5 * __pyx_v_indices.strides[0]) )) + __pyx_t_6)) )))), (__pyx_v_distances.shape[1])); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2489; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2479 + * + * + * def simultaneous_sort(DTYPE_t[:, ::1] distances, ITYPE_t[:, ::1] indices): # <<<<<<<<<<<<<< + * """In-place simultaneous sort the given row of the arrays + * + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.simultaneous_sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_distances, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_indices, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2494 + * + * + * def nodeheap_sort(DTYPE_t[::1] vals): # <<<<<<<<<<<<<< + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_9nodeheap_sort(PyObject *__pyx_self, PyObject *__pyx_arg_vals); /*proto*/ +static char __pyx_doc_7sklearn_9neighbors_7kd_tree_8nodeheap_sort[] = "In-place reverse sort of vals using NodeHeap"; +static PyMethodDef __pyx_mdef_7sklearn_9neighbors_7kd_tree_9nodeheap_sort = {__Pyx_NAMESTR("nodeheap_sort"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_9nodeheap_sort, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_8nodeheap_sort)}; +static PyObject *__pyx_pw_7sklearn_9neighbors_7kd_tree_9nodeheap_sort(PyObject *__pyx_self, PyObject *__pyx_arg_vals) { + __Pyx_memviewslice __pyx_v_vals = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("nodeheap_sort (wrapper)", 0); + assert(__pyx_arg_vals); { + __pyx_v_vals = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(__pyx_arg_vals); if (unlikely(!__pyx_v_vals.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2494; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.nodeheap_sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_9neighbors_7kd_tree_8nodeheap_sort(__pyx_self, __pyx_v_vals); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_9neighbors_7kd_tree_8nodeheap_sort(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_vals) { + __Pyx_memviewslice __pyx_v_indices = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_vals_sorted = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *__pyx_v_heap = 0; + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t __pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + Py_ssize_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + int __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("nodeheap_sort", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2496 + * def nodeheap_sort(DTYPE_t[::1] vals): + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] vals_sorted = np.zeros_like(vals) + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyInt_FromSsize_t((__pyx_v_vals.shape[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(__pyx_t_4); + if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2497 + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) + * cdef DTYPE_t[::1] vals_sorted = np.zeros_like(vals) # <<<<<<<<<<<<<< + * + * # use initial size 0 to check corner case + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros_like); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_vals, 1, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(__pyx_t_4); + if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_vals_sorted = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2500 + * + * # use initial size 0 to check corner case + * cdef NodeHeap heap = NodeHeap(0) # <<<<<<<<<<<<<< + * cdef NodeHeapData_t data + * cdef ITYPE_t i + */ + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_9neighbors_7kd_tree_NodeHeap)), __pyx_tuple__32, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2500; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_heap = ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2503 + * cdef NodeHeapData_t data + * cdef ITYPE_t i + * for i in range(vals.shape[0]): # <<<<<<<<<<<<<< + * data.val = vals[i] + * data.i1 = i + */ + __pyx_t_7 = (__pyx_v_vals.shape[0]); + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2504 + * cdef ITYPE_t i + * for i in range(vals.shape[0]): + * data.val = vals[i] # <<<<<<<<<<<<<< + * data.i1 = i + * data.i2 = i + 1 + */ + __pyx_t_9 = __pyx_v_i; + __pyx_v_data.val = (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_vals.data) + __pyx_t_9)) ))); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2505 + * for i in range(vals.shape[0]): + * data.val = vals[i] + * data.i1 = i # <<<<<<<<<<<<<< + * data.i2 = i + 1 + * heap.push(data) + */ + __pyx_v_data.i1 = __pyx_v_i; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2506 + * data.val = vals[i] + * data.i1 = i + * data.i2 = i + 1 # <<<<<<<<<<<<<< + * heap.push(data) + * + */ + __pyx_v_data.i2 = (__pyx_v_i + 1); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2507 + * data.i1 = i + * data.i2 = i + 1 + * heap.push(data) # <<<<<<<<<<<<<< + * + * for i in range(vals.shape[0]): + */ + __pyx_t_10 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_heap->__pyx_vtab)->push(__pyx_v_heap, __pyx_v_data); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2509 + * heap.push(data) + * + * for i in range(vals.shape[0]): # <<<<<<<<<<<<<< + * data = heap.pop() + * vals_sorted[i] = data.val + */ + __pyx_t_7 = (__pyx_v_vals.shape[0]); + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2510 + * + * for i in range(vals.shape[0]): + * data = heap.pop() # <<<<<<<<<<<<<< + * vals_sorted[i] = data.val + * indices[i] = data.i1 + */ + __pyx_v_data = ((struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap *)__pyx_v_heap->__pyx_vtab)->pop(__pyx_v_heap); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2511 + * for i in range(vals.shape[0]): + * data = heap.pop() + * vals_sorted[i] = data.val # <<<<<<<<<<<<<< + * indices[i] = data.i1 + * + */ + __pyx_t_11 = __pyx_v_data.val; + __pyx_t_12 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) __pyx_v_vals_sorted.data) + __pyx_t_12)) )) = __pyx_t_11; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2512 + * data = heap.pop() + * vals_sorted[i] = data.val + * indices[i] = data.i1 # <<<<<<<<<<<<<< + * + * return np.asarray(vals_sorted), np.asarray(indices) + */ + __pyx_t_13 = __pyx_v_data.i1; + __pyx_t_14 = __pyx_v_i; + *((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_indices.data) + __pyx_t_14)) )) = __pyx_t_13; + } + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2514 + * indices[i] = data.i1 + * + * return np.asarray(vals_sorted), np.asarray(indices) # <<<<<<<<<<<<<< + * + * # Reimplementation for MSVC support + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_asarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_vals_sorted, 1, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, 0);; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_1, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_asarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_indices, 1, (PyObject *(*)(char *)) __pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, (int (*)(char *, PyObject *)) __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, 0);; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_4 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2494 + * + * + * def nodeheap_sort(DTYPE_t[::1] vals): # <<<<<<<<<<<<<< + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.nodeheap_sort", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_vals, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_indices, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_vals_sorted, 1); + __Pyx_XDECREF((PyObject *)__pyx_v_heap); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2517 + * + * # Reimplementation for MSVC support + * cdef inline double fmin(double a, double b): # <<<<<<<<<<<<<< + * return min(a, b) + * + */ + +static CYTHON_INLINE double __pyx_f_7sklearn_9neighbors_7kd_tree_fmin(double __pyx_v_a, double __pyx_v_b) { + double __pyx_r; + __Pyx_RefNannyDeclarations + double __pyx_t_1; + double __pyx_t_2; + double __pyx_t_3; + __Pyx_RefNannySetupContext("fmin", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2518 + * # Reimplementation for MSVC support + * cdef inline double fmin(double a, double b): + * return min(a, b) # <<<<<<<<<<<<<< + * + * cdef inline double fmax(double a, double b): + */ + __pyx_t_1 = __pyx_v_b; + __pyx_t_2 = __pyx_v_a; + if (((__pyx_t_1 < __pyx_t_2) != 0)) { + __pyx_t_3 = __pyx_t_1; + } else { + __pyx_t_3 = __pyx_t_2; + } + __pyx_r = __pyx_t_3; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2517 + * + * # Reimplementation for MSVC support + * cdef inline double fmin(double a, double b): # <<<<<<<<<<<<<< + * return min(a, b) + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2520 + * return min(a, b) + * + * cdef inline double fmax(double a, double b): # <<<<<<<<<<<<<< + * return max(a, b) + */ + +static CYTHON_INLINE double __pyx_f_7sklearn_9neighbors_7kd_tree_fmax(double __pyx_v_a, double __pyx_v_b) { + double __pyx_r; + __Pyx_RefNannyDeclarations + double __pyx_t_1; + double __pyx_t_2; + double __pyx_t_3; + __Pyx_RefNannySetupContext("fmax", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2521 + * + * cdef inline double fmax(double a, double b): + * return max(a, b) # <<<<<<<<<<<<<< + */ + __pyx_t_1 = __pyx_v_b; + __pyx_t_2 = __pyx_v_a; + if (((__pyx_t_1 > __pyx_t_2) != 0)) { + __pyx_t_3 = __pyx_t_1; + } else { + __pyx_t_3 = __pyx_t_2; + } + __pyx_r = __pyx_t_3; + goto __pyx_L0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2520 + * return min(a, b) + * + * cdef inline double fmax(double a, double b): # <<<<<<<<<<<<<< + * return max(a, b) + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/kd_tree.pyx":36 + * + * + * cdef int allocate_data(BinaryTree tree, ITYPE_t n_nodes, # <<<<<<<<<<<<<< + * ITYPE_t n_features) except -1: + * """Allocate arrays needed for the KD Tree""" + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_allocate_data(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_nodes, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("allocate_data", 0); + + /* "sklearn/neighbors/kd_tree.pyx":39 + * ITYPE_t n_features) except -1: + * """Allocate arrays needed for the KD Tree""" + * tree.node_bounds_arr = np.zeros((2, n_nodes, n_features), dtype=DTYPE) # <<<<<<<<<<<<<< + * tree.node_bounds = get_memview_DTYPE_3D(tree.node_bounds_arr) + * return 0 + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_nodes); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_features); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_int_2); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_int_2); + __Pyx_GIVEREF(__pyx_int_2); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_tree->node_bounds_arr); + __Pyx_DECREF(((PyObject *)__pyx_v_tree->node_bounds_arr)); + __pyx_v_tree->node_bounds_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/neighbors/kd_tree.pyx":40 + * """Allocate arrays needed for the KD Tree""" + * tree.node_bounds_arr = np.zeros((2, n_nodes, n_features), dtype=DTYPE) + * tree.node_bounds = get_memview_DTYPE_3D(tree.node_bounds_arr) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_t_1 = ((PyObject *)__pyx_v_tree->node_bounds_arr); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_5 = __pyx_f_7sklearn_9neighbors_7kd_tree_get_memview_DTYPE_3D(((PyArrayObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5.memview)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_XDEC_MEMVIEW(&__pyx_v_tree->node_bounds, 0); + __pyx_v_tree->node_bounds = __pyx_t_5; + __pyx_t_5.memview = NULL; + __pyx_t_5.data = NULL; + + /* "sklearn/neighbors/kd_tree.pyx":41 + * tree.node_bounds_arr = np.zeros((2, n_nodes, n_features), dtype=DTYPE) + * tree.node_bounds = get_memview_DTYPE_3D(tree.node_bounds_arr) + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/neighbors/kd_tree.pyx":36 + * + * + * cdef int allocate_data(BinaryTree tree, ITYPE_t n_nodes, # <<<<<<<<<<<<<< + * ITYPE_t n_features) except -1: + * """Allocate arrays needed for the KD Tree""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.allocate_data", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/kd_tree.pyx":44 + * + * + * cdef int init_node(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * ITYPE_t idx_start, ITYPE_t idx_end) except -1: + * """Initialize the node for the dataset stored in tree.data""" + */ + +static int __pyx_f_7sklearn_9neighbors_7kd_tree_init_node(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_idx_start, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_idx_end) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rad; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_lower_bounds; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_upper_bounds; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *__pyx_v_idx_array; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_data_row; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + Py_ssize_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_13; + int __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("init_node", 0); + + /* "sklearn/neighbors/kd_tree.pyx":47 + * ITYPE_t idx_start, ITYPE_t idx_end) except -1: + * """Initialize the node for the dataset stored in tree.data""" + * cdef ITYPE_t n_features = tree.data.shape[1] # <<<<<<<<<<<<<< + * cdef ITYPE_t i, j + * cdef DTYPE_t rad = 0 + */ + if (unlikely(!__pyx_v_tree->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_tree->data.shape[1]); + + /* "sklearn/neighbors/kd_tree.pyx":49 + * cdef ITYPE_t n_features = tree.data.shape[1] + * cdef ITYPE_t i, j + * cdef DTYPE_t rad = 0 # <<<<<<<<<<<<<< + * + * cdef DTYPE_t* lower_bounds = &tree.node_bounds[0, i_node, 0] + */ + __pyx_v_rad = 0.0; + + /* "sklearn/neighbors/kd_tree.pyx":51 + * cdef DTYPE_t rad = 0 + * + * cdef DTYPE_t* lower_bounds = &tree.node_bounds[0, i_node, 0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* upper_bounds = &tree.node_bounds[1, i_node, 0] + * cdef DTYPE_t* data = &tree.data[0, 0] + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_1 = 0; + __pyx_t_2 = __pyx_v_i_node; + __pyx_t_3 = 0; + __pyx_v_lower_bounds = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_1 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_2 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_3)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":52 + * + * cdef DTYPE_t* lower_bounds = &tree.node_bounds[0, i_node, 0] + * cdef DTYPE_t* upper_bounds = &tree.node_bounds[1, i_node, 0] # <<<<<<<<<<<<<< + * cdef DTYPE_t* data = &tree.data[0, 0] + * cdef ITYPE_t* idx_array = &tree.idx_array[0] + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = 1; + __pyx_t_5 = __pyx_v_i_node; + __pyx_t_6 = 0; + __pyx_v_upper_bounds = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_4 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_5 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_6)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":53 + * cdef DTYPE_t* lower_bounds = &tree.node_bounds[0, i_node, 0] + * cdef DTYPE_t* upper_bounds = &tree.node_bounds[1, i_node, 0] + * cdef DTYPE_t* data = &tree.data[0, 0] # <<<<<<<<<<<<<< + * cdef ITYPE_t* idx_array = &tree.idx_array[0] + * + */ + if (unlikely(!__pyx_v_tree->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = 0; + __pyx_t_8 = 0; + __pyx_v_data = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=0 */ (__pyx_v_tree->data.data + __pyx_t_7 * __pyx_v_tree->data.strides[0]) )) + __pyx_t_8)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":54 + * cdef DTYPE_t* upper_bounds = &tree.node_bounds[1, i_node, 0] + * cdef DTYPE_t* data = &tree.data[0, 0] + * cdef ITYPE_t* idx_array = &tree.idx_array[0] # <<<<<<<<<<<<<< + * + * cdef DTYPE_t* data_row + */ + if (unlikely(!__pyx_v_tree->idx_array.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_9 = 0; + __pyx_v_idx_array = (&(*((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) ( /* dim=0 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) __pyx_v_tree->idx_array.data) + __pyx_t_9)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":59 + * + * # determine Node bounds + * for j in range(n_features): # <<<<<<<<<<<<<< + * lower_bounds[j] = INF + * upper_bounds[j] = -INF + */ + __pyx_t_10 = __pyx_v_n_features; + for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) { + __pyx_v_j = __pyx_t_11; + + /* "sklearn/neighbors/kd_tree.pyx":60 + * # determine Node bounds + * for j in range(n_features): + * lower_bounds[j] = INF # <<<<<<<<<<<<<< + * upper_bounds[j] = -INF + * + */ + (__pyx_v_lower_bounds[__pyx_v_j]) = __pyx_v_7sklearn_9neighbors_7kd_tree_INF; + + /* "sklearn/neighbors/kd_tree.pyx":61 + * for j in range(n_features): + * lower_bounds[j] = INF + * upper_bounds[j] = -INF # <<<<<<<<<<<<<< + * + * # Compute the actual data range. At build time, this is slightly + */ + (__pyx_v_upper_bounds[__pyx_v_j]) = (-__pyx_v_7sklearn_9neighbors_7kd_tree_INF); + } + + /* "sklearn/neighbors/kd_tree.pyx":66 + * # slower than using the previously-computed bounds of the parent node, + * # but leads to more compact trees and thus faster queries. + * for i in range(idx_start, idx_end): # <<<<<<<<<<<<<< + * data_row = data + idx_array[i] * n_features + * for j in range(n_features): + */ + __pyx_t_10 = __pyx_v_idx_end; + for (__pyx_t_11 = __pyx_v_idx_start; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) { + __pyx_v_i = __pyx_t_11; + + /* "sklearn/neighbors/kd_tree.pyx":67 + * # but leads to more compact trees and thus faster queries. + * for i in range(idx_start, idx_end): + * data_row = data + idx_array[i] * n_features # <<<<<<<<<<<<<< + * for j in range(n_features): + * lower_bounds[j] = fmin(lower_bounds[j], data_row[j]) + */ + __pyx_v_data_row = (__pyx_v_data + ((__pyx_v_idx_array[__pyx_v_i]) * __pyx_v_n_features)); + + /* "sklearn/neighbors/kd_tree.pyx":68 + * for i in range(idx_start, idx_end): + * data_row = data + idx_array[i] * n_features + * for j in range(n_features): # <<<<<<<<<<<<<< + * lower_bounds[j] = fmin(lower_bounds[j], data_row[j]) + * upper_bounds[j] = fmax(upper_bounds[j], data_row[j]) + */ + __pyx_t_12 = __pyx_v_n_features; + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { + __pyx_v_j = __pyx_t_13; + + /* "sklearn/neighbors/kd_tree.pyx":69 + * data_row = data + idx_array[i] * n_features + * for j in range(n_features): + * lower_bounds[j] = fmin(lower_bounds[j], data_row[j]) # <<<<<<<<<<<<<< + * upper_bounds[j] = fmax(upper_bounds[j], data_row[j]) + * if tree.dist_metric.p == INF: + */ + (__pyx_v_lower_bounds[__pyx_v_j]) = __pyx_f_7sklearn_9neighbors_7kd_tree_fmin((__pyx_v_lower_bounds[__pyx_v_j]), (__pyx_v_data_row[__pyx_v_j])); + + /* "sklearn/neighbors/kd_tree.pyx":70 + * for j in range(n_features): + * lower_bounds[j] = fmin(lower_bounds[j], data_row[j]) + * upper_bounds[j] = fmax(upper_bounds[j], data_row[j]) # <<<<<<<<<<<<<< + * if tree.dist_metric.p == INF: + * rad = fmax(rad, 0.5 * (upper_bounds[j] - lower_bounds[j])) + */ + (__pyx_v_upper_bounds[__pyx_v_j]) = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax((__pyx_v_upper_bounds[__pyx_v_j]), (__pyx_v_data_row[__pyx_v_j])); + } + + /* "sklearn/neighbors/kd_tree.pyx":71 + * lower_bounds[j] = fmin(lower_bounds[j], data_row[j]) + * upper_bounds[j] = fmax(upper_bounds[j], data_row[j]) + * if tree.dist_metric.p == INF: # <<<<<<<<<<<<<< + * rad = fmax(rad, 0.5 * (upper_bounds[j] - lower_bounds[j])) + * else: + */ + __pyx_t_14 = ((__pyx_v_tree->dist_metric->p == __pyx_v_7sklearn_9neighbors_7kd_tree_INF) != 0); + if (__pyx_t_14) { + + /* "sklearn/neighbors/kd_tree.pyx":72 + * upper_bounds[j] = fmax(upper_bounds[j], data_row[j]) + * if tree.dist_metric.p == INF: + * rad = fmax(rad, 0.5 * (upper_bounds[j] - lower_bounds[j])) # <<<<<<<<<<<<<< + * else: + * rad += pow(0.5 * abs(upper_bounds[j] - lower_bounds[j]), + */ + __pyx_v_rad = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax(__pyx_v_rad, (0.5 * ((__pyx_v_upper_bounds[__pyx_v_j]) - (__pyx_v_lower_bounds[__pyx_v_j])))); + goto __pyx_L9; + } + /*else*/ { + + /* "sklearn/neighbors/kd_tree.pyx":74 + * rad = fmax(rad, 0.5 * (upper_bounds[j] - lower_bounds[j])) + * else: + * rad += pow(0.5 * abs(upper_bounds[j] - lower_bounds[j]), # <<<<<<<<<<<<<< + * tree.dist_metric.p) + * + */ + __pyx_v_rad = (__pyx_v_rad + pow((0.5 * fabs(((__pyx_v_upper_bounds[__pyx_v_j]) - (__pyx_v_lower_bounds[__pyx_v_j])))), __pyx_v_tree->dist_metric->p)); + } + __pyx_L9:; + } + + /* "sklearn/neighbors/kd_tree.pyx":77 + * tree.dist_metric.p) + * + * tree.node_data[i_node].idx_start = idx_start # <<<<<<<<<<<<<< + * tree.node_data[i_node].idx_end = idx_end + * + */ + if (unlikely(!__pyx_v_tree->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_tree->node_data.data) + __pyx_t_10)) ))).idx_start = __pyx_v_idx_start; + + /* "sklearn/neighbors/kd_tree.pyx":78 + * + * tree.node_data[i_node].idx_start = idx_start + * tree.node_data[i_node].idx_end = idx_end # <<<<<<<<<<<<<< + * + * # The radius will hold the size of the circumscribed hypersphere measured + */ + if (unlikely(!__pyx_v_tree->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_11 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_tree->node_data.data) + __pyx_t_11)) ))).idx_end = __pyx_v_idx_end; + + /* "sklearn/neighbors/kd_tree.pyx":83 + * # with the specified metric: in querying, this is used as a measure of the + * # size of each node when deciding which nodes to split. + * tree.node_data[i_node].radius = pow(rad, 1. / tree.dist_metric.p) # <<<<<<<<<<<<<< + * return 0 + * + */ + if (unlikely(!__pyx_v_tree->node_data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_12 = __pyx_v_i_node; + (*((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) ( /* dim=0 */ ((char *) (((struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) __pyx_v_tree->node_data.data) + __pyx_t_12)) ))).radius = pow(__pyx_v_rad, (1. / __pyx_v_tree->dist_metric->p)); + + /* "sklearn/neighbors/kd_tree.pyx":84 + * # size of each node when deciding which nodes to split. + * tree.node_data[i_node].radius = pow(rad, 1. / tree.dist_metric.p) + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/neighbors/kd_tree.pyx":44 + * + * + * cdef int init_node(BinaryTree tree, ITYPE_t i_node, # <<<<<<<<<<<<<< + * ITYPE_t idx_start, ITYPE_t idx_end) except -1: + * """Initialize the node for the dataset stored in tree.data""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.init_node", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/kd_tree.pyx":87 + * + * + * cdef DTYPE_t min_rdist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: # <<<<<<<<<<<<<< + * """Compute the minimum reduced-distance between a point and a node""" + * cdef ITYPE_t n_features = tree.data.shape[1] + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d_lo; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d_hi; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rdist; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + Py_ssize_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("min_rdist", 0); + + /* "sklearn/neighbors/kd_tree.pyx":89 + * cdef DTYPE_t min_rdist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: + * """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 + * cdef ITYPE_t j + */ + if (unlikely(!__pyx_v_tree->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_tree->data.shape[1]); + + /* "sklearn/neighbors/kd_tree.pyx":90 + * """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 # <<<<<<<<<<<<<< + * cdef ITYPE_t j + * + */ + __pyx_v_rdist = 0.0; + + /* "sklearn/neighbors/kd_tree.pyx":93 + * cdef ITYPE_t j + * + * if tree.dist_metric.p == INF: # <<<<<<<<<<<<<< + * for j in range(n_features): + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + */ + __pyx_t_1 = ((__pyx_v_tree->dist_metric->p == __pyx_v_7sklearn_9neighbors_7kd_tree_INF) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/kd_tree.pyx":94 + * + * if tree.dist_metric.p == INF: + * for j in range(n_features): # <<<<<<<<<<<<<< + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + */ + __pyx_t_2 = __pyx_v_n_features; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_j = __pyx_t_3; + + /* "sklearn/neighbors/kd_tree.pyx":95 + * if tree.dist_metric.p == INF: + * for j in range(n_features): + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] # <<<<<<<<<<<<<< + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = 0; + __pyx_t_5 = __pyx_v_i_node; + __pyx_t_6 = __pyx_v_j; + __pyx_v_d_lo = ((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_4 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_5 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_6)) ))) - (__pyx_v_pt[__pyx_v_j])); + + /* "sklearn/neighbors/kd_tree.pyx":96 + * for j in range(n_features): + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] # <<<<<<<<<<<<<< + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + * rdist = fmax(rdist, 0.5 * d) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = 1; + __pyx_t_8 = __pyx_v_i_node; + __pyx_t_9 = __pyx_v_j; + __pyx_v_d_hi = ((__pyx_v_pt[__pyx_v_j]) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_7 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_8 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_9)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":97 + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) # <<<<<<<<<<<<<< + * rdist = fmax(rdist, 0.5 * d) + * else: + */ + __pyx_v_d = ((__pyx_v_d_lo + fabs(__pyx_v_d_lo)) + (__pyx_v_d_hi + fabs(__pyx_v_d_hi))); + + /* "sklearn/neighbors/kd_tree.pyx":98 + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + * rdist = fmax(rdist, 0.5 * d) # <<<<<<<<<<<<<< + * else: + * # here we'll use the fact that x + abs(x) = 2 * max(x, 0) + */ + __pyx_v_rdist = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax(__pyx_v_rdist, (0.5 * __pyx_v_d)); + } + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/neighbors/kd_tree.pyx":101 + * else: + * # here we'll use the fact that x + abs(x) = 2 * max(x, 0) + * for j in range(n_features): # <<<<<<<<<<<<<< + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + */ + __pyx_t_2 = __pyx_v_n_features; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_j = __pyx_t_3; + + /* "sklearn/neighbors/kd_tree.pyx":102 + * # here we'll use the fact that x + abs(x) = 2 * max(x, 0) + * for j in range(n_features): + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] # <<<<<<<<<<<<<< + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = 0; + __pyx_t_11 = __pyx_v_i_node; + __pyx_t_12 = __pyx_v_j; + __pyx_v_d_lo = ((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_10 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_11 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_12)) ))) - (__pyx_v_pt[__pyx_v_j])); + + /* "sklearn/neighbors/kd_tree.pyx":103 + * for j in range(n_features): + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] # <<<<<<<<<<<<<< + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + * rdist += pow(0.5 * d, tree.dist_metric.p) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_13 = 1; + __pyx_t_14 = __pyx_v_i_node; + __pyx_t_15 = __pyx_v_j; + __pyx_v_d_hi = ((__pyx_v_pt[__pyx_v_j]) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_13 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_14 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_15)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":104 + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) # <<<<<<<<<<<<<< + * rdist += pow(0.5 * d, tree.dist_metric.p) + * + */ + __pyx_v_d = ((__pyx_v_d_lo + fabs(__pyx_v_d_lo)) + (__pyx_v_d_hi + fabs(__pyx_v_d_hi))); + + /* "sklearn/neighbors/kd_tree.pyx":105 + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + * rdist += pow(0.5 * d, tree.dist_metric.p) # <<<<<<<<<<<<<< + * + * return rdist + */ + __pyx_v_rdist = (__pyx_v_rdist + pow((0.5 * __pyx_v_d), __pyx_v_tree->dist_metric->p)); + } + } + __pyx_L3:; + + /* "sklearn/neighbors/kd_tree.pyx":107 + * rdist += pow(0.5 * d, tree.dist_metric.p) + * + * return rdist # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_rdist; + goto __pyx_L0; + + /* "sklearn/neighbors/kd_tree.pyx":87 + * + * + * cdef DTYPE_t min_rdist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: # <<<<<<<<<<<<<< + * """Compute the minimum reduced-distance between a point and a node""" + * cdef ITYPE_t n_features = tree.data.shape[1] + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.min_rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/kd_tree.pyx":110 + * + * + * cdef DTYPE_t min_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: # <<<<<<<<<<<<<< + * """Compute the minimum distance between a point and a node""" + * if tree.dist_metric.p == INF: + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_min_dist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("min_dist", 0); + + /* "sklearn/neighbors/kd_tree.pyx":112 + * cdef DTYPE_t min_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: + * """Compute the minimum distance between a point and a node""" + * if tree.dist_metric.p == INF: # <<<<<<<<<<<<<< + * return min_rdist(tree, i_node, pt) + * else: + */ + __pyx_t_1 = ((__pyx_v_tree->dist_metric->p == __pyx_v_7sklearn_9neighbors_7kd_tree_INF) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/kd_tree.pyx":113 + * """Compute the minimum distance between a point and a node""" + * if tree.dist_metric.p == INF: + * return min_rdist(tree, i_node, pt) # <<<<<<<<<<<<<< + * else: + * return pow(min_rdist(tree, i_node, pt), 1. / tree.dist_metric.p) + */ + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist(__pyx_v_tree, __pyx_v_i_node, __pyx_v_pt); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + /*else*/ { + + /* "sklearn/neighbors/kd_tree.pyx":115 + * return min_rdist(tree, i_node, pt) + * else: + * return pow(min_rdist(tree, i_node, pt), 1. / tree.dist_metric.p) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist(__pyx_v_tree, __pyx_v_i_node, __pyx_v_pt); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = pow(__pyx_t_2, (1. / __pyx_v_tree->dist_metric->p)); + goto __pyx_L0; + } + + /* "sklearn/neighbors/kd_tree.pyx":110 + * + * + * cdef DTYPE_t min_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: # <<<<<<<<<<<<<< + * """Compute the minimum distance between a point and a node""" + * if tree.dist_metric.p == INF: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.min_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/kd_tree.pyx":118 + * + * + * cdef DTYPE_t max_rdist(BinaryTree tree, # <<<<<<<<<<<<<< + * ITYPE_t i_node, DTYPE_t* pt) except -1: + * """Compute the maximum reduced-distance between a point and a node""" + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_max_rdist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d_lo; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d_hi; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rdist; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + Py_ssize_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("max_rdist", 0); + + /* "sklearn/neighbors/kd_tree.pyx":121 + * ITYPE_t i_node, DTYPE_t* pt) except -1: + * """Compute the maximum 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 + */ + if (unlikely(!__pyx_v_tree->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_tree->data.shape[1]); + + /* "sklearn/neighbors/kd_tree.pyx":123 + * cdef ITYPE_t n_features = tree.data.shape[1] + * + * cdef DTYPE_t d, d_lo, d_hi, rdist=0.0 # <<<<<<<<<<<<<< + * cdef ITYPE_t j + * + */ + __pyx_v_rdist = 0.0; + + /* "sklearn/neighbors/kd_tree.pyx":126 + * cdef ITYPE_t j + * + * if tree.dist_metric.p == INF: # <<<<<<<<<<<<<< + * for j in range(n_features): + * rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[0, i_node, j])) + */ + __pyx_t_1 = ((__pyx_v_tree->dist_metric->p == __pyx_v_7sklearn_9neighbors_7kd_tree_INF) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/kd_tree.pyx":127 + * + * if tree.dist_metric.p == INF: + * for j in range(n_features): # <<<<<<<<<<<<<< + * rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[0, i_node, j])) + * rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[1, i_node, j])) + */ + __pyx_t_2 = __pyx_v_n_features; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_j = __pyx_t_3; + + /* "sklearn/neighbors/kd_tree.pyx":128 + * if tree.dist_metric.p == INF: + * for j in range(n_features): + * rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[0, i_node, j])) # <<<<<<<<<<<<<< + * rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[1, i_node, j])) + * else: + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = 0; + __pyx_t_5 = __pyx_v_i_node; + __pyx_t_6 = __pyx_v_j; + __pyx_v_rdist = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax(__pyx_v_rdist, fabs(((__pyx_v_pt[__pyx_v_j]) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_4 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_5 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_6)) )))))); + + /* "sklearn/neighbors/kd_tree.pyx":129 + * for j in range(n_features): + * rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[0, i_node, j])) + * rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[1, i_node, j])) # <<<<<<<<<<<<<< + * else: + * for j in range(n_features): + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = 1; + __pyx_t_8 = __pyx_v_i_node; + __pyx_t_9 = __pyx_v_j; + __pyx_v_rdist = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax(__pyx_v_rdist, fabs(((__pyx_v_pt[__pyx_v_j]) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_7 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_8 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_9)) )))))); + } + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/neighbors/kd_tree.pyx":131 + * rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[1, i_node, j])) + * else: + * for j in range(n_features): # <<<<<<<<<<<<<< + * d_lo = fabs(pt[j] - tree.node_bounds[0, i_node, j]) + * d_hi = fabs(pt[j] - tree.node_bounds[1, i_node, j]) + */ + __pyx_t_2 = __pyx_v_n_features; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_j = __pyx_t_3; + + /* "sklearn/neighbors/kd_tree.pyx":132 + * else: + * for j in range(n_features): + * d_lo = fabs(pt[j] - tree.node_bounds[0, i_node, j]) # <<<<<<<<<<<<<< + * d_hi = fabs(pt[j] - tree.node_bounds[1, i_node, j]) + * rdist += pow(fmax(d_lo, d_hi), tree.dist_metric.p) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = 0; + __pyx_t_11 = __pyx_v_i_node; + __pyx_t_12 = __pyx_v_j; + __pyx_v_d_lo = fabs(((__pyx_v_pt[__pyx_v_j]) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_10 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_11 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_12)) ))))); + + /* "sklearn/neighbors/kd_tree.pyx":133 + * for j in range(n_features): + * d_lo = fabs(pt[j] - tree.node_bounds[0, i_node, j]) + * d_hi = fabs(pt[j] - tree.node_bounds[1, i_node, j]) # <<<<<<<<<<<<<< + * rdist += pow(fmax(d_lo, d_hi), tree.dist_metric.p) + * + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_13 = 1; + __pyx_t_14 = __pyx_v_i_node; + __pyx_t_15 = __pyx_v_j; + __pyx_v_d_hi = fabs(((__pyx_v_pt[__pyx_v_j]) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_13 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_14 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_15)) ))))); + + /* "sklearn/neighbors/kd_tree.pyx":134 + * d_lo = fabs(pt[j] - tree.node_bounds[0, i_node, j]) + * d_hi = fabs(pt[j] - tree.node_bounds[1, i_node, j]) + * rdist += pow(fmax(d_lo, d_hi), tree.dist_metric.p) # <<<<<<<<<<<<<< + * + * return rdist + */ + __pyx_v_rdist = (__pyx_v_rdist + pow(__pyx_f_7sklearn_9neighbors_7kd_tree_fmax(__pyx_v_d_lo, __pyx_v_d_hi), __pyx_v_tree->dist_metric->p)); + } + } + __pyx_L3:; + + /* "sklearn/neighbors/kd_tree.pyx":136 + * rdist += pow(fmax(d_lo, d_hi), tree.dist_metric.p) + * + * return rdist # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_rdist; + goto __pyx_L0; + + /* "sklearn/neighbors/kd_tree.pyx":118 + * + * + * cdef DTYPE_t max_rdist(BinaryTree tree, # <<<<<<<<<<<<<< + * ITYPE_t i_node, DTYPE_t* pt) except -1: + * """Compute the maximum reduced-distance between a point and a node""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.max_rdist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/kd_tree.pyx":139 + * + * + * cdef DTYPE_t max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: # <<<<<<<<<<<<<< + * """Compute the maximum distance between a point and a node""" + * if tree.dist_metric.p == INF: + */ + +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_max_dist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("max_dist", 0); + + /* "sklearn/neighbors/kd_tree.pyx":141 + * cdef DTYPE_t max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: + * """Compute the maximum distance between a point and a node""" + * if tree.dist_metric.p == INF: # <<<<<<<<<<<<<< + * return max_rdist(tree, i_node, pt) + * else: + */ + __pyx_t_1 = ((__pyx_v_tree->dist_metric->p == __pyx_v_7sklearn_9neighbors_7kd_tree_INF) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/kd_tree.pyx":142 + * """Compute the maximum distance between a point and a node""" + * if tree.dist_metric.p == INF: + * return max_rdist(tree, i_node, pt) # <<<<<<<<<<<<<< + * else: + * return pow(max_rdist(tree, i_node, pt), 1. / tree.dist_metric.p) + */ + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_7kd_tree_max_rdist(__pyx_v_tree, __pyx_v_i_node, __pyx_v_pt); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + } + /*else*/ { + + /* "sklearn/neighbors/kd_tree.pyx":144 + * return max_rdist(tree, i_node, pt) + * else: + * return pow(max_rdist(tree, i_node, pt), 1. / tree.dist_metric.p) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_f_7sklearn_9neighbors_7kd_tree_max_rdist(__pyx_v_tree, __pyx_v_i_node, __pyx_v_pt); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = pow(__pyx_t_2, (1. / __pyx_v_tree->dist_metric->p)); + goto __pyx_L0; + } + + /* "sklearn/neighbors/kd_tree.pyx":139 + * + * + * cdef DTYPE_t max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: # <<<<<<<<<<<<<< + * """Compute the maximum distance between a point and a node""" + * if tree.dist_metric.p == INF: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.max_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/kd_tree.pyx":147 + * + * + * cdef inline int min_max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt, # <<<<<<<<<<<<<< + * DTYPE_t* min_dist, DTYPE_t* max_dist) except -1: + * """Compute the minimum and maximum distance between a point and a node""" + */ + +static CYTHON_INLINE int __pyx_f_7sklearn_9neighbors_7kd_tree_min_max_dist(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_pt, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_min_dist, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_max_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d_lo; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d_hi; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + Py_ssize_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + Py_ssize_t __pyx_t_16; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_17; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_18; + Py_ssize_t __pyx_t_19; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_20; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_21; + long __pyx_t_22; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("min_max_dist", 0); + + /* "sklearn/neighbors/kd_tree.pyx":150 + * DTYPE_t* min_dist, DTYPE_t* max_dist) except -1: + * """Compute the minimum and maximum distance between a point and a node""" + * cdef ITYPE_t n_features = tree.data.shape[1] # <<<<<<<<<<<<<< + * + * cdef DTYPE_t d, d_lo, d_hi + */ + if (unlikely(!__pyx_v_tree->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_tree->data.shape[1]); + + /* "sklearn/neighbors/kd_tree.pyx":155 + * cdef ITYPE_t j + * + * min_dist[0] = 0.0 # <<<<<<<<<<<<<< + * max_dist[0] = 0.0 + * + */ + (__pyx_v_min_dist[0]) = 0.0; + + /* "sklearn/neighbors/kd_tree.pyx":156 + * + * min_dist[0] = 0.0 + * max_dist[0] = 0.0 # <<<<<<<<<<<<<< + * + * if tree.dist_metric.p == INF: + */ + (__pyx_v_max_dist[0]) = 0.0; + + /* "sklearn/neighbors/kd_tree.pyx":158 + * max_dist[0] = 0.0 + * + * if tree.dist_metric.p == INF: # <<<<<<<<<<<<<< + * for j in range(n_features): + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + */ + __pyx_t_1 = ((__pyx_v_tree->dist_metric->p == __pyx_v_7sklearn_9neighbors_7kd_tree_INF) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/kd_tree.pyx":159 + * + * if tree.dist_metric.p == INF: + * for j in range(n_features): # <<<<<<<<<<<<<< + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + */ + __pyx_t_2 = __pyx_v_n_features; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_j = __pyx_t_3; + + /* "sklearn/neighbors/kd_tree.pyx":160 + * if tree.dist_metric.p == INF: + * for j in range(n_features): + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] # <<<<<<<<<<<<<< + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = 0; + __pyx_t_5 = __pyx_v_i_node; + __pyx_t_6 = __pyx_v_j; + __pyx_v_d_lo = ((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_4 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_5 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_6)) ))) - (__pyx_v_pt[__pyx_v_j])); + + /* "sklearn/neighbors/kd_tree.pyx":161 + * for j in range(n_features): + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] # <<<<<<<<<<<<<< + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + * min_dist[0] = fmax(min_dist[0], 0.5 * d) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = 1; + __pyx_t_8 = __pyx_v_i_node; + __pyx_t_9 = __pyx_v_j; + __pyx_v_d_hi = ((__pyx_v_pt[__pyx_v_j]) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_7 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_8 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_9)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":162 + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) # <<<<<<<<<<<<<< + * min_dist[0] = fmax(min_dist[0], 0.5 * d) + * max_dist[0] = fmax(max_dist[0], + */ + __pyx_v_d = ((__pyx_v_d_lo + fabs(__pyx_v_d_lo)) + (__pyx_v_d_hi + fabs(__pyx_v_d_hi))); + + /* "sklearn/neighbors/kd_tree.pyx":163 + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + * min_dist[0] = fmax(min_dist[0], 0.5 * d) # <<<<<<<<<<<<<< + * max_dist[0] = fmax(max_dist[0], + * fabs(pt[j] - tree.node_bounds[0, i_node, j])) + */ + (__pyx_v_min_dist[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax((__pyx_v_min_dist[0]), (0.5 * __pyx_v_d)); + + /* "sklearn/neighbors/kd_tree.pyx":165 + * min_dist[0] = fmax(min_dist[0], 0.5 * d) + * max_dist[0] = fmax(max_dist[0], + * fabs(pt[j] - tree.node_bounds[0, i_node, j])) # <<<<<<<<<<<<<< + * max_dist[0] = fmax(max_dist[0], + * fabs(pt[j] - tree.node_bounds[1, i_node, j])) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = 0; + __pyx_t_11 = __pyx_v_i_node; + __pyx_t_12 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":164 + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + * min_dist[0] = fmax(min_dist[0], 0.5 * d) + * max_dist[0] = fmax(max_dist[0], # <<<<<<<<<<<<<< + * fabs(pt[j] - tree.node_bounds[0, i_node, j])) + * max_dist[0] = fmax(max_dist[0], + */ + (__pyx_v_max_dist[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax((__pyx_v_max_dist[0]), fabs(((__pyx_v_pt[__pyx_v_j]) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_10 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_11 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_12)) )))))); + + /* "sklearn/neighbors/kd_tree.pyx":167 + * fabs(pt[j] - tree.node_bounds[0, i_node, j])) + * max_dist[0] = fmax(max_dist[0], + * fabs(pt[j] - tree.node_bounds[1, i_node, j])) # <<<<<<<<<<<<<< + * else: + * # as above, use the fact that x + abs(x) = 2 * max(x, 0) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_13 = 1; + __pyx_t_14 = __pyx_v_i_node; + __pyx_t_15 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":166 + * max_dist[0] = fmax(max_dist[0], + * fabs(pt[j] - tree.node_bounds[0, i_node, j])) + * max_dist[0] = fmax(max_dist[0], # <<<<<<<<<<<<<< + * fabs(pt[j] - tree.node_bounds[1, i_node, j])) + * else: + */ + (__pyx_v_max_dist[0]) = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax((__pyx_v_max_dist[0]), fabs(((__pyx_v_pt[__pyx_v_j]) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_13 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_14 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_15)) )))))); + } + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/neighbors/kd_tree.pyx":170 + * else: + * # as above, use the fact that x + abs(x) = 2 * max(x, 0) + * for j in range(n_features): # <<<<<<<<<<<<<< + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + */ + __pyx_t_2 = __pyx_v_n_features; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_j = __pyx_t_3; + + /* "sklearn/neighbors/kd_tree.pyx":171 + * # as above, use the fact that x + abs(x) = 2 * max(x, 0) + * for j in range(n_features): + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] # <<<<<<<<<<<<<< + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 171; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_16 = 0; + __pyx_t_17 = __pyx_v_i_node; + __pyx_t_18 = __pyx_v_j; + __pyx_v_d_lo = ((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_16 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_17 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_18)) ))) - (__pyx_v_pt[__pyx_v_j])); + + /* "sklearn/neighbors/kd_tree.pyx":172 + * for j in range(n_features): + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] # <<<<<<<<<<<<<< + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + * min_dist[0] += pow(0.5 * d, tree.dist_metric.p) + */ + if (unlikely(!__pyx_v_tree->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_19 = 1; + __pyx_t_20 = __pyx_v_i_node; + __pyx_t_21 = __pyx_v_j; + __pyx_v_d_hi = ((__pyx_v_pt[__pyx_v_j]) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree->node_bounds.data + __pyx_t_19 * __pyx_v_tree->node_bounds.strides[0]) ) + __pyx_t_20 * __pyx_v_tree->node_bounds.strides[1]) )) + __pyx_t_21)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":173 + * d_lo = tree.node_bounds[0, i_node, j] - pt[j] + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) # <<<<<<<<<<<<<< + * min_dist[0] += pow(0.5 * d, tree.dist_metric.p) + * max_dist[0] += pow(fmax(fabs(d_lo), fabs(d_hi)), + */ + __pyx_v_d = ((__pyx_v_d_lo + fabs(__pyx_v_d_lo)) + (__pyx_v_d_hi + fabs(__pyx_v_d_hi))); + + /* "sklearn/neighbors/kd_tree.pyx":174 + * d_hi = pt[j] - tree.node_bounds[1, i_node, j] + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + * min_dist[0] += pow(0.5 * d, tree.dist_metric.p) # <<<<<<<<<<<<<< + * max_dist[0] += pow(fmax(fabs(d_lo), fabs(d_hi)), + * tree.dist_metric.p) + */ + __pyx_t_22 = 0; + (__pyx_v_min_dist[__pyx_t_22]) = ((__pyx_v_min_dist[__pyx_t_22]) + pow((0.5 * __pyx_v_d), __pyx_v_tree->dist_metric->p)); + + /* "sklearn/neighbors/kd_tree.pyx":175 + * d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + * min_dist[0] += pow(0.5 * d, tree.dist_metric.p) + * max_dist[0] += pow(fmax(fabs(d_lo), fabs(d_hi)), # <<<<<<<<<<<<<< + * tree.dist_metric.p) + * + */ + __pyx_t_22 = 0; + + /* "sklearn/neighbors/kd_tree.pyx":176 + * min_dist[0] += pow(0.5 * d, tree.dist_metric.p) + * max_dist[0] += pow(fmax(fabs(d_lo), fabs(d_hi)), + * tree.dist_metric.p) # <<<<<<<<<<<<<< + * + * min_dist[0] = pow(min_dist[0], 1. / tree.dist_metric.p) + */ + (__pyx_v_max_dist[__pyx_t_22]) = ((__pyx_v_max_dist[__pyx_t_22]) + pow(__pyx_f_7sklearn_9neighbors_7kd_tree_fmax(fabs(__pyx_v_d_lo), fabs(__pyx_v_d_hi)), __pyx_v_tree->dist_metric->p)); + } + + /* "sklearn/neighbors/kd_tree.pyx":178 + * tree.dist_metric.p) + * + * min_dist[0] = pow(min_dist[0], 1. / tree.dist_metric.p) # <<<<<<<<<<<<<< + * max_dist[0] = pow(max_dist[0], 1. / tree.dist_metric.p) + * + */ + (__pyx_v_min_dist[0]) = pow((__pyx_v_min_dist[0]), (1. / __pyx_v_tree->dist_metric->p)); + + /* "sklearn/neighbors/kd_tree.pyx":179 + * + * min_dist[0] = pow(min_dist[0], 1. / tree.dist_metric.p) + * max_dist[0] = pow(max_dist[0], 1. / tree.dist_metric.p) # <<<<<<<<<<<<<< + * + * return 0 + */ + (__pyx_v_max_dist[0]) = pow((__pyx_v_max_dist[0]), (1. / __pyx_v_tree->dist_metric->p)); + } + __pyx_L3:; + + /* "sklearn/neighbors/kd_tree.pyx":181 + * max_dist[0] = pow(max_dist[0], 1. / tree.dist_metric.p) + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/neighbors/kd_tree.pyx":147 + * + * + * cdef inline int min_max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt, # <<<<<<<<<<<<<< + * DTYPE_t* min_dist, DTYPE_t* max_dist) except -1: + * """Compute the minimum and maximum distance between a point and a node""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.min_max_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/kd_tree.pyx":184 + * + * + * cdef inline DTYPE_t min_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the minimum reduced distance between two nodes""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist_dual(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rdist; + CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_zero; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + Py_ssize_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + Py_ssize_t __pyx_t_16; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_17; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_18; + Py_ssize_t __pyx_t_19; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_20; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_21; + Py_ssize_t __pyx_t_22; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_23; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_24; + Py_ssize_t __pyx_t_25; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_26; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_27; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("min_rdist_dual", 0); + + /* "sklearn/neighbors/kd_tree.pyx":187 + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the minimum reduced distance between two nodes""" + * cdef ITYPE_t n_features = tree1.data.shape[1] # <<<<<<<<<<<<<< + * + * cdef DTYPE_t d, d1, d2, rdist=0.0 + */ + if (unlikely(!__pyx_v_tree1->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_tree1->data.shape[1]); + + /* "sklearn/neighbors/kd_tree.pyx":189 + * cdef ITYPE_t n_features = tree1.data.shape[1] + * + * cdef DTYPE_t d, d1, d2, rdist=0.0 # <<<<<<<<<<<<<< + * cdef DTYPE_t zero = 0.0 + * cdef ITYPE_t j + */ + __pyx_v_rdist = 0.0; + + /* "sklearn/neighbors/kd_tree.pyx":190 + * + * cdef DTYPE_t d, d1, d2, rdist=0.0 + * cdef DTYPE_t zero = 0.0 # <<<<<<<<<<<<<< + * cdef ITYPE_t j + * + */ + __pyx_v_zero = 0.0; + + /* "sklearn/neighbors/kd_tree.pyx":193 + * cdef ITYPE_t j + * + * if tree1.dist_metric.p == INF: # <<<<<<<<<<<<<< + * for j in range(n_features): + * d1 = (tree1.node_bounds[0, i_node1, j] + */ + __pyx_t_1 = ((__pyx_v_tree1->dist_metric->p == __pyx_v_7sklearn_9neighbors_7kd_tree_INF) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/kd_tree.pyx":194 + * + * if tree1.dist_metric.p == INF: + * for j in range(n_features): # <<<<<<<<<<<<<< + * d1 = (tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j]) + */ + __pyx_t_2 = __pyx_v_n_features; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_j = __pyx_t_3; + + /* "sklearn/neighbors/kd_tree.pyx":195 + * if tree1.dist_metric.p == INF: + * for j in range(n_features): + * d1 = (tree1.node_bounds[0, i_node1, j] # <<<<<<<<<<<<<< + * - tree2.node_bounds[1, i_node2, j]) + * d2 = (tree2.node_bounds[0, i_node2, j] + */ + if (unlikely(!__pyx_v_tree1->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = 0; + __pyx_t_5 = __pyx_v_i_node1; + __pyx_t_6 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":196 + * for j in range(n_features): + * d1 = (tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j]) # <<<<<<<<<<<<<< + * d2 = (tree2.node_bounds[0, i_node2, j] + * - tree1.node_bounds[1, i_node1, j]) + */ + if (unlikely(!__pyx_v_tree2->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = 1; + __pyx_t_8 = __pyx_v_i_node2; + __pyx_t_9 = __pyx_v_j; + __pyx_v_d1 = ((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree1->node_bounds.data + __pyx_t_4 * __pyx_v_tree1->node_bounds.strides[0]) ) + __pyx_t_5 * __pyx_v_tree1->node_bounds.strides[1]) )) + __pyx_t_6)) ))) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree2->node_bounds.data + __pyx_t_7 * __pyx_v_tree2->node_bounds.strides[0]) ) + __pyx_t_8 * __pyx_v_tree2->node_bounds.strides[1]) )) + __pyx_t_9)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":197 + * d1 = (tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j]) + * d2 = (tree2.node_bounds[0, i_node2, j] # <<<<<<<<<<<<<< + * - tree1.node_bounds[1, i_node1, j]) + * d = (d1 + fabs(d1)) + (d2 + fabs(d2)) + */ + if (unlikely(!__pyx_v_tree2->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = 0; + __pyx_t_11 = __pyx_v_i_node2; + __pyx_t_12 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":198 + * - tree2.node_bounds[1, i_node2, j]) + * d2 = (tree2.node_bounds[0, i_node2, j] + * - tree1.node_bounds[1, i_node1, j]) # <<<<<<<<<<<<<< + * d = (d1 + fabs(d1)) + (d2 + fabs(d2)) + * + */ + if (unlikely(!__pyx_v_tree1->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_13 = 1; + __pyx_t_14 = __pyx_v_i_node1; + __pyx_t_15 = __pyx_v_j; + __pyx_v_d2 = ((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree2->node_bounds.data + __pyx_t_10 * __pyx_v_tree2->node_bounds.strides[0]) ) + __pyx_t_11 * __pyx_v_tree2->node_bounds.strides[1]) )) + __pyx_t_12)) ))) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree1->node_bounds.data + __pyx_t_13 * __pyx_v_tree1->node_bounds.strides[0]) ) + __pyx_t_14 * __pyx_v_tree1->node_bounds.strides[1]) )) + __pyx_t_15)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":199 + * d2 = (tree2.node_bounds[0, i_node2, j] + * - tree1.node_bounds[1, i_node1, j]) + * d = (d1 + fabs(d1)) + (d2 + fabs(d2)) # <<<<<<<<<<<<<< + * + * rdist = fmax(rdist, 0.5 * d) + */ + __pyx_v_d = ((__pyx_v_d1 + fabs(__pyx_v_d1)) + (__pyx_v_d2 + fabs(__pyx_v_d2))); + + /* "sklearn/neighbors/kd_tree.pyx":201 + * d = (d1 + fabs(d1)) + (d2 + fabs(d2)) + * + * rdist = fmax(rdist, 0.5 * d) # <<<<<<<<<<<<<< + * else: + * # here we'll use the fact that x + abs(x) = 2 * max(x, 0) + */ + __pyx_v_rdist = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax(__pyx_v_rdist, (0.5 * __pyx_v_d)); + } + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/neighbors/kd_tree.pyx":204 + * else: + * # here we'll use the fact that x + abs(x) = 2 * max(x, 0) + * for j in range(n_features): # <<<<<<<<<<<<<< + * d1 = (tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j]) + */ + __pyx_t_2 = __pyx_v_n_features; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_j = __pyx_t_3; + + /* "sklearn/neighbors/kd_tree.pyx":205 + * # here we'll use the fact that x + abs(x) = 2 * max(x, 0) + * for j in range(n_features): + * d1 = (tree1.node_bounds[0, i_node1, j] # <<<<<<<<<<<<<< + * - tree2.node_bounds[1, i_node2, j]) + * d2 = (tree2.node_bounds[0, i_node2, j] + */ + if (unlikely(!__pyx_v_tree1->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_16 = 0; + __pyx_t_17 = __pyx_v_i_node1; + __pyx_t_18 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":206 + * for j in range(n_features): + * d1 = (tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j]) # <<<<<<<<<<<<<< + * d2 = (tree2.node_bounds[0, i_node2, j] + * - tree1.node_bounds[1, i_node1, j]) + */ + if (unlikely(!__pyx_v_tree2->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_19 = 1; + __pyx_t_20 = __pyx_v_i_node2; + __pyx_t_21 = __pyx_v_j; + __pyx_v_d1 = ((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree1->node_bounds.data + __pyx_t_16 * __pyx_v_tree1->node_bounds.strides[0]) ) + __pyx_t_17 * __pyx_v_tree1->node_bounds.strides[1]) )) + __pyx_t_18)) ))) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree2->node_bounds.data + __pyx_t_19 * __pyx_v_tree2->node_bounds.strides[0]) ) + __pyx_t_20 * __pyx_v_tree2->node_bounds.strides[1]) )) + __pyx_t_21)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":207 + * d1 = (tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j]) + * d2 = (tree2.node_bounds[0, i_node2, j] # <<<<<<<<<<<<<< + * - tree1.node_bounds[1, i_node1, j]) + * d = (d1 + fabs(d1)) + (d2 + fabs(d2)) + */ + if (unlikely(!__pyx_v_tree2->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_22 = 0; + __pyx_t_23 = __pyx_v_i_node2; + __pyx_t_24 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":208 + * - tree2.node_bounds[1, i_node2, j]) + * d2 = (tree2.node_bounds[0, i_node2, j] + * - tree1.node_bounds[1, i_node1, j]) # <<<<<<<<<<<<<< + * d = (d1 + fabs(d1)) + (d2 + fabs(d2)) + * + */ + if (unlikely(!__pyx_v_tree1->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_25 = 1; + __pyx_t_26 = __pyx_v_i_node1; + __pyx_t_27 = __pyx_v_j; + __pyx_v_d2 = ((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree2->node_bounds.data + __pyx_t_22 * __pyx_v_tree2->node_bounds.strides[0]) ) + __pyx_t_23 * __pyx_v_tree2->node_bounds.strides[1]) )) + __pyx_t_24)) ))) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree1->node_bounds.data + __pyx_t_25 * __pyx_v_tree1->node_bounds.strides[0]) ) + __pyx_t_26 * __pyx_v_tree1->node_bounds.strides[1]) )) + __pyx_t_27)) )))); + + /* "sklearn/neighbors/kd_tree.pyx":209 + * d2 = (tree2.node_bounds[0, i_node2, j] + * - tree1.node_bounds[1, i_node1, j]) + * d = (d1 + fabs(d1)) + (d2 + fabs(d2)) # <<<<<<<<<<<<<< + * + * rdist += pow(0.5 * d, tree1.dist_metric.p) + */ + __pyx_v_d = ((__pyx_v_d1 + fabs(__pyx_v_d1)) + (__pyx_v_d2 + fabs(__pyx_v_d2))); + + /* "sklearn/neighbors/kd_tree.pyx":211 + * d = (d1 + fabs(d1)) + (d2 + fabs(d2)) + * + * rdist += pow(0.5 * d, tree1.dist_metric.p) # <<<<<<<<<<<<<< + * + * return rdist + */ + __pyx_v_rdist = (__pyx_v_rdist + pow((0.5 * __pyx_v_d), __pyx_v_tree1->dist_metric->p)); + } + } + __pyx_L3:; + + /* "sklearn/neighbors/kd_tree.pyx":213 + * rdist += pow(0.5 * d, tree1.dist_metric.p) + * + * return rdist # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_rdist; + goto __pyx_L0; + + /* "sklearn/neighbors/kd_tree.pyx":184 + * + * + * cdef inline DTYPE_t min_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the minimum reduced distance between two nodes""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.min_rdist_dual", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/kd_tree.pyx":216 + * + * + * cdef inline DTYPE_t min_dist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the minimum distance between two nodes""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_min_dist_dual(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("min_dist_dual", 0); + + /* "sklearn/neighbors/kd_tree.pyx":219 + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the minimum distance between two nodes""" + * return tree1.dist_metric._rdist_to_dist(min_rdist_dual(tree1, i_node1, # <<<<<<<<<<<<<< + * tree2, i_node2)) + * + */ + __pyx_t_1 = __pyx_f_7sklearn_9neighbors_7kd_tree_min_rdist_dual(__pyx_v_tree1, __pyx_v_i_node1, __pyx_v_tree2, __pyx_v_i_node2); if (unlikely(__pyx_t_1 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_tree1->dist_metric->__pyx_vtab)->_rdist_to_dist(__pyx_v_tree1->dist_metric, __pyx_t_1); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + + /* "sklearn/neighbors/kd_tree.pyx":216 + * + * + * cdef inline DTYPE_t min_dist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the minimum distance between two nodes""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.min_dist_dual", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/kd_tree.pyx":223 + * + * + * cdef inline DTYPE_t max_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the maximum reduced distance between two nodes""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_max_rdist_dual(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_n_features; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d2; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_rdist; + CYTHON_UNUSED __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_zero; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_2; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_5; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_6; + Py_ssize_t __pyx_t_7; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_8; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_11; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_14; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_15; + Py_ssize_t __pyx_t_16; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_17; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_18; + Py_ssize_t __pyx_t_19; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_20; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_21; + Py_ssize_t __pyx_t_22; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_23; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_24; + Py_ssize_t __pyx_t_25; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_26; + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_27; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("max_rdist_dual", 0); + + /* "sklearn/neighbors/kd_tree.pyx":226 + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the maximum reduced distance between two nodes""" + * cdef ITYPE_t n_features = tree1.data.shape[1] # <<<<<<<<<<<<<< + * + * cdef DTYPE_t d, d1, d2, rdist=0.0 + */ + if (unlikely(!__pyx_v_tree1->data.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_v_n_features = (__pyx_v_tree1->data.shape[1]); + + /* "sklearn/neighbors/kd_tree.pyx":228 + * cdef ITYPE_t n_features = tree1.data.shape[1] + * + * cdef DTYPE_t d, d1, d2, rdist=0.0 # <<<<<<<<<<<<<< + * cdef DTYPE_t zero = 0.0 + * cdef ITYPE_t j + */ + __pyx_v_rdist = 0.0; + + /* "sklearn/neighbors/kd_tree.pyx":229 + * + * cdef DTYPE_t d, d1, d2, rdist=0.0 + * cdef DTYPE_t zero = 0.0 # <<<<<<<<<<<<<< + * cdef ITYPE_t j + * + */ + __pyx_v_zero = 0.0; + + /* "sklearn/neighbors/kd_tree.pyx":232 + * cdef ITYPE_t j + * + * if tree1.dist_metric.p == INF: # <<<<<<<<<<<<<< + * for j in range(n_features): + * rdist = fmax(rdist, fabs(tree1.node_bounds[0, i_node1, j] + */ + __pyx_t_1 = ((__pyx_v_tree1->dist_metric->p == __pyx_v_7sklearn_9neighbors_7kd_tree_INF) != 0); + if (__pyx_t_1) { + + /* "sklearn/neighbors/kd_tree.pyx":233 + * + * if tree1.dist_metric.p == INF: + * for j in range(n_features): # <<<<<<<<<<<<<< + * rdist = fmax(rdist, fabs(tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j])) + */ + __pyx_t_2 = __pyx_v_n_features; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_j = __pyx_t_3; + + /* "sklearn/neighbors/kd_tree.pyx":234 + * if tree1.dist_metric.p == INF: + * for j in range(n_features): + * rdist = fmax(rdist, fabs(tree1.node_bounds[0, i_node1, j] # <<<<<<<<<<<<<< + * - tree2.node_bounds[1, i_node2, j])) + * rdist = fmax(rdist, fabs(tree1.node_bounds[1, i_node1, j] + */ + if (unlikely(!__pyx_v_tree1->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_4 = 0; + __pyx_t_5 = __pyx_v_i_node1; + __pyx_t_6 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":235 + * for j in range(n_features): + * rdist = fmax(rdist, fabs(tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j])) # <<<<<<<<<<<<<< + * rdist = fmax(rdist, fabs(tree1.node_bounds[1, i_node1, j] + * - tree2.node_bounds[0, i_node2, j])) + */ + if (unlikely(!__pyx_v_tree2->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_7 = 1; + __pyx_t_8 = __pyx_v_i_node2; + __pyx_t_9 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":234 + * if tree1.dist_metric.p == INF: + * for j in range(n_features): + * rdist = fmax(rdist, fabs(tree1.node_bounds[0, i_node1, j] # <<<<<<<<<<<<<< + * - tree2.node_bounds[1, i_node2, j])) + * rdist = fmax(rdist, fabs(tree1.node_bounds[1, i_node1, j] + */ + __pyx_v_rdist = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax(__pyx_v_rdist, fabs(((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree1->node_bounds.data + __pyx_t_4 * __pyx_v_tree1->node_bounds.strides[0]) ) + __pyx_t_5 * __pyx_v_tree1->node_bounds.strides[1]) )) + __pyx_t_6)) ))) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree2->node_bounds.data + __pyx_t_7 * __pyx_v_tree2->node_bounds.strides[0]) ) + __pyx_t_8 * __pyx_v_tree2->node_bounds.strides[1]) )) + __pyx_t_9)) )))))); + + /* "sklearn/neighbors/kd_tree.pyx":236 + * rdist = fmax(rdist, fabs(tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j])) + * rdist = fmax(rdist, fabs(tree1.node_bounds[1, i_node1, j] # <<<<<<<<<<<<<< + * - tree2.node_bounds[0, i_node2, j])) + * else: + */ + if (unlikely(!__pyx_v_tree1->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_10 = 1; + __pyx_t_11 = __pyx_v_i_node1; + __pyx_t_12 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":237 + * - tree2.node_bounds[1, i_node2, j])) + * rdist = fmax(rdist, fabs(tree1.node_bounds[1, i_node1, j] + * - tree2.node_bounds[0, i_node2, j])) # <<<<<<<<<<<<<< + * else: + * for j in range(n_features): + */ + if (unlikely(!__pyx_v_tree2->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 237; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_13 = 0; + __pyx_t_14 = __pyx_v_i_node2; + __pyx_t_15 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":236 + * rdist = fmax(rdist, fabs(tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j])) + * rdist = fmax(rdist, fabs(tree1.node_bounds[1, i_node1, j] # <<<<<<<<<<<<<< + * - tree2.node_bounds[0, i_node2, j])) + * else: + */ + __pyx_v_rdist = __pyx_f_7sklearn_9neighbors_7kd_tree_fmax(__pyx_v_rdist, fabs(((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree1->node_bounds.data + __pyx_t_10 * __pyx_v_tree1->node_bounds.strides[0]) ) + __pyx_t_11 * __pyx_v_tree1->node_bounds.strides[1]) )) + __pyx_t_12)) ))) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree2->node_bounds.data + __pyx_t_13 * __pyx_v_tree2->node_bounds.strides[0]) ) + __pyx_t_14 * __pyx_v_tree2->node_bounds.strides[1]) )) + __pyx_t_15)) )))))); + } + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/neighbors/kd_tree.pyx":239 + * - tree2.node_bounds[0, i_node2, j])) + * else: + * for j in range(n_features): # <<<<<<<<<<<<<< + * d1 = fabs(tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j]) + */ + __pyx_t_2 = __pyx_v_n_features; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_j = __pyx_t_3; + + /* "sklearn/neighbors/kd_tree.pyx":240 + * else: + * for j in range(n_features): + * d1 = fabs(tree1.node_bounds[0, i_node1, j] # <<<<<<<<<<<<<< + * - tree2.node_bounds[1, i_node2, j]) + * d2 = fabs(tree1.node_bounds[1, i_node1, j] + */ + if (unlikely(!__pyx_v_tree1->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_16 = 0; + __pyx_t_17 = __pyx_v_i_node1; + __pyx_t_18 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":241 + * for j in range(n_features): + * d1 = fabs(tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j]) # <<<<<<<<<<<<<< + * d2 = fabs(tree1.node_bounds[1, i_node1, j] + * - tree2.node_bounds[0, i_node2, j]) + */ + if (unlikely(!__pyx_v_tree2->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_19 = 1; + __pyx_t_20 = __pyx_v_i_node2; + __pyx_t_21 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":240 + * else: + * for j in range(n_features): + * d1 = fabs(tree1.node_bounds[0, i_node1, j] # <<<<<<<<<<<<<< + * - tree2.node_bounds[1, i_node2, j]) + * d2 = fabs(tree1.node_bounds[1, i_node1, j] + */ + __pyx_v_d1 = fabs(((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree1->node_bounds.data + __pyx_t_16 * __pyx_v_tree1->node_bounds.strides[0]) ) + __pyx_t_17 * __pyx_v_tree1->node_bounds.strides[1]) )) + __pyx_t_18)) ))) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree2->node_bounds.data + __pyx_t_19 * __pyx_v_tree2->node_bounds.strides[0]) ) + __pyx_t_20 * __pyx_v_tree2->node_bounds.strides[1]) )) + __pyx_t_21)) ))))); + + /* "sklearn/neighbors/kd_tree.pyx":242 + * d1 = fabs(tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j]) + * d2 = fabs(tree1.node_bounds[1, i_node1, j] # <<<<<<<<<<<<<< + * - tree2.node_bounds[0, i_node2, j]) + * rdist += pow(fmax(d1, d2), tree1.dist_metric.p) + */ + if (unlikely(!__pyx_v_tree1->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_22 = 1; + __pyx_t_23 = __pyx_v_i_node1; + __pyx_t_24 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":243 + * - tree2.node_bounds[1, i_node2, j]) + * d2 = fabs(tree1.node_bounds[1, i_node1, j] + * - tree2.node_bounds[0, i_node2, j]) # <<<<<<<<<<<<<< + * rdist += pow(fmax(d1, d2), tree1.dist_metric.p) + * + */ + if (unlikely(!__pyx_v_tree2->node_bounds.memview)) {PyErr_SetString(PyExc_AttributeError,"Memoryview is not initialized");{__pyx_filename = __pyx_f[1]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;}} + __pyx_t_25 = 0; + __pyx_t_26 = __pyx_v_i_node2; + __pyx_t_27 = __pyx_v_j; + + /* "sklearn/neighbors/kd_tree.pyx":242 + * d1 = fabs(tree1.node_bounds[0, i_node1, j] + * - tree2.node_bounds[1, i_node2, j]) + * d2 = fabs(tree1.node_bounds[1, i_node1, j] # <<<<<<<<<<<<<< + * - tree2.node_bounds[0, i_node2, j]) + * rdist += pow(fmax(d1, d2), tree1.dist_metric.p) + */ + __pyx_v_d2 = fabs(((*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree1->node_bounds.data + __pyx_t_22 * __pyx_v_tree1->node_bounds.strides[0]) ) + __pyx_t_23 * __pyx_v_tree1->node_bounds.strides[1]) )) + __pyx_t_24)) ))) - (*((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=2 */ ((char *) (((__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_tree2->node_bounds.data + __pyx_t_25 * __pyx_v_tree2->node_bounds.strides[0]) ) + __pyx_t_26 * __pyx_v_tree2->node_bounds.strides[1]) )) + __pyx_t_27)) ))))); + + /* "sklearn/neighbors/kd_tree.pyx":244 + * d2 = fabs(tree1.node_bounds[1, i_node1, j] + * - tree2.node_bounds[0, i_node2, j]) + * rdist += pow(fmax(d1, d2), tree1.dist_metric.p) # <<<<<<<<<<<<<< + * + * return rdist + */ + __pyx_v_rdist = (__pyx_v_rdist + pow(__pyx_f_7sklearn_9neighbors_7kd_tree_fmax(__pyx_v_d1, __pyx_v_d2), __pyx_v_tree1->dist_metric->p)); + } + } + __pyx_L3:; + + /* "sklearn/neighbors/kd_tree.pyx":246 + * rdist += pow(fmax(d1, d2), tree1.dist_metric.p) + * + * return rdist # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_rdist; + goto __pyx_L0; + + /* "sklearn/neighbors/kd_tree.pyx":223 + * + * + * cdef inline DTYPE_t max_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the maximum reduced distance between two nodes""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.max_rdist_dual", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/neighbors/kd_tree.pyx":249 + * + * + * cdef inline DTYPE_t max_dist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the maximum distance between two nodes""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_7kd_tree_max_dist_dual(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree1, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node1, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *__pyx_v_tree2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_i_node2) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_1; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("max_dist_dual", 0); + + /* "sklearn/neighbors/kd_tree.pyx":252 + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the maximum distance between two nodes""" + * return tree1.dist_metric._rdist_to_dist(max_rdist_dual(tree1, i_node1, # <<<<<<<<<<<<<< + * tree2, i_node2)) + */ + __pyx_t_1 = __pyx_f_7sklearn_9neighbors_7kd_tree_max_rdist_dual(__pyx_v_tree1, __pyx_v_i_node1, __pyx_v_tree2, __pyx_v_i_node2); if (unlikely(__pyx_t_1 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)__pyx_v_tree1->dist_metric->__pyx_vtab)->_rdist_to_dist(__pyx_v_tree1->dist_metric, __pyx_t_1); if (unlikely(__pyx_t_2 == -1.0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_t_2; + goto __pyx_L0; + + /* "sklearn/neighbors/kd_tree.pyx":249 + * + * + * cdef inline DTYPE_t max_dist_dual(BinaryTree tree1, ITYPE_t i_node1, # <<<<<<<<<<<<<< + * BinaryTree tree2, ITYPE_t i_node2) except -1: + * """Compute the maximum distance between two nodes""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.neighbors.kd_tree.max_dist_dual", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1.0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "dist_metrics.pxd":18 + * # We use these for the default (euclidean) case so that they can be + * # inlined. This leads to faster computation for the most common case + * cdef inline DTYPE_t euclidean_dist(DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_tmp; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("euclidean_dist", 0); + + /* "dist_metrics.pxd":20 + * cdef inline DTYPE_t euclidean_dist(DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "dist_metrics.pxd":22 + * cdef DTYPE_t tmp, d=0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tmp = x1[j] - x2[j] + * d += tmp * tmp + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "dist_metrics.pxd":23 + * cdef np.intp_t j + * for j in range(size): + * tmp = x1[j] - x2[j] # <<<<<<<<<<<<<< + * d += tmp * tmp + * return sqrt(d) + */ + __pyx_v_tmp = ((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j])); + + /* "dist_metrics.pxd":24 + * for j in range(size): + * tmp = x1[j] - x2[j] + * d += tmp * tmp # <<<<<<<<<<<<<< + * return sqrt(d) + * + */ + __pyx_v_d = (__pyx_v_d + (__pyx_v_tmp * __pyx_v_tmp)); + } + + /* "dist_metrics.pxd":25 + * tmp = x1[j] - x2[j] + * d += tmp * tmp + * return sqrt(d) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = sqrt(__pyx_v_d); + goto __pyx_L0; + + /* "dist_metrics.pxd":18 + * # We use these for the default (euclidean) case so that they can be + * # inlined. This leads to faster computation for the most common case + * cdef inline DTYPE_t euclidean_dist(DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "dist_metrics.pxd":28 + * + * + * cdef inline DTYPE_t euclidean_rdist(DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x1, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *__pyx_v_x2, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_v_size) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_tmp; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_d; + __pyx_t_5numpy_intp_t __pyx_v_j; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t __pyx_t_1; + __pyx_t_5numpy_intp_t __pyx_t_2; + __Pyx_RefNannySetupContext("euclidean_rdist", 0); + + /* "dist_metrics.pxd":30 + * cdef inline DTYPE_t euclidean_rdist(DTYPE_t* x1, DTYPE_t* x2, + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 # <<<<<<<<<<<<<< + * cdef np.intp_t j + * for j in range(size): + */ + __pyx_v_d = 0.0; + + /* "dist_metrics.pxd":32 + * cdef DTYPE_t tmp, d=0 + * cdef np.intp_t j + * for j in range(size): # <<<<<<<<<<<<<< + * tmp = x1[j] - x2[j] + * d += tmp * tmp + */ + __pyx_t_1 = __pyx_v_size; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_j = __pyx_t_2; + + /* "dist_metrics.pxd":33 + * cdef np.intp_t j + * for j in range(size): + * tmp = x1[j] - x2[j] # <<<<<<<<<<<<<< + * d += tmp * tmp + * return d + */ + __pyx_v_tmp = ((__pyx_v_x1[__pyx_v_j]) - (__pyx_v_x2[__pyx_v_j])); + + /* "dist_metrics.pxd":34 + * for j in range(size): + * tmp = x1[j] - x2[j] + * d += tmp * tmp # <<<<<<<<<<<<<< + * return d + * + */ + __pyx_v_d = (__pyx_v_d + (__pyx_v_tmp * __pyx_v_tmp)); + } + + /* "dist_metrics.pxd":35 + * tmp = x1[j] - x2[j] + * d += tmp * tmp + * return d # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_d; + goto __pyx_L0; + + /* "dist_metrics.pxd":28 + * + * + * cdef inline DTYPE_t euclidean_rdist(DTYPE_t* x1, DTYPE_t* x2, # <<<<<<<<<<<<<< + * ITYPE_t size) except -1: + * cdef DTYPE_t tmp, d=0 + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "dist_metrics.pxd":38 + * + * + * cdef inline DTYPE_t euclidean_dist_to_rdist(DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return dist * dist + * + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_dist_to_rdist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("euclidean_dist_to_rdist", 0); + + /* "dist_metrics.pxd":39 + * + * cdef inline DTYPE_t euclidean_dist_to_rdist(DTYPE_t dist) except -1: + * return dist * dist # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (__pyx_v_dist * __pyx_v_dist); + goto __pyx_L0; + + /* "dist_metrics.pxd":38 + * + * + * cdef inline DTYPE_t euclidean_dist_to_rdist(DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return dist * dist + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "dist_metrics.pxd":42 + * + * + * cdef inline DTYPE_t euclidean_rdist_to_dist(DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return sqrt(dist) + * + */ + +static CYTHON_INLINE __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_f_7sklearn_9neighbors_12dist_metrics_euclidean_rdist_to_dist(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_dist) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("euclidean_rdist_to_dist", 0); + + /* "dist_metrics.pxd":43 + * + * cdef inline DTYPE_t euclidean_rdist_to_dist(DTYPE_t dist) except -1: + * return sqrt(dist) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = sqrt(__pyx_v_dist); + goto __pyx_L0; + + /* "dist_metrics.pxd":42 + * + * + * cdef inline DTYPE_t euclidean_rdist_to_dist(DTYPE_t dist) except -1: # <<<<<<<<<<<<<< + * return sqrt(dist) + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__33, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_3) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__34, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":222 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":251 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); + if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_1) { + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__35, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< + * info.format + _buffer_format_string_len, + * &offset) + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + long __pyx_t_10; + char *__pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); + __pyx_t_3 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":798 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__36, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_6 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_6) { + __pyx_t_7 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_7 = __pyx_t_6; + } + if (!__pyx_t_7) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_6 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_6) { + __pyx_t_8 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_9 = __pyx_t_8; + } else { + __pyx_t_9 = __pyx_t_6; + } + __pyx_t_6 = __pyx_t_9; + } else { + __pyx_t_6 = __pyx_t_7; + } + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__37, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":813 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_6) break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":818 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":821 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__38, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L11; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L11:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L9; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_11; + } + __pyx_L9:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":968 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":969 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":971 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":972 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":973 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":974 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":977 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":978 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":980 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + +/* Python wrapper */ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_shape = 0; + Py_ssize_t __pyx_v_itemsize; + PyObject *__pyx_v_format = 0; + PyObject *__pyx_v_mode = 0; + int __pyx_v_allocate_buffer; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[3] = ((PyObject *)__pyx_n_s_c); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mode); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_allocate_buffer); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_shape = ((PyObject*)values[0]); + __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_format = values[2]; + __pyx_v_mode = values[3]; + if (values[4]) { + __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "View.MemoryView":117 + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, + * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_v_allocate_buffer = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { + PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_r = __pyx_array_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); + + /* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { + int __pyx_v_idx; + Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_dim; + PyObject **__pyx_v_p; + char __pyx_v_order; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + char *__pyx_t_5; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_INCREF(__pyx_v_format); + + /* "View.MemoryView":123 + * cdef PyObject **p + * + * self.ndim = len(shape) # <<<<<<<<<<<<<< + * self.itemsize = itemsize + * + */ + if (unlikely(__pyx_v_shape == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->ndim = ((int)__pyx_t_1); + + /* "View.MemoryView":124 + * + * self.ndim = len(shape) + * self.itemsize = itemsize # <<<<<<<<<<<<<< + * + * if not self.ndim: + */ + __pyx_v_self->itemsize = __pyx_v_itemsize; + + /* "View.MemoryView":126 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ + __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":127 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if itemsize <= 0: + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__39, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":129 + * raise ValueError("Empty shape tuple for cython.array") + * + * if itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ + __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":130 + * + * if itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * if isinstance(format, unicode): + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__40, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":132 + * raise ValueError("itemsize <= 0 for cython.array") + * + * if isinstance(format, unicode): # <<<<<<<<<<<<<< + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string + */ + __pyx_t_2 = PyUnicode_Check(__pyx_v_format); + __pyx_t_4 = (__pyx_t_2 != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":133 + * + * if isinstance(format, unicode): + * format = (format).encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format # keep a reference to the byte string + * self.format = self._format + */ + if (unlikely(__pyx_v_format == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", "encode"); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = PyUnicode_AsASCIIString(((PyObject*)__pyx_v_format)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":134 + * if isinstance(format, unicode): + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< + * self.format = self._format + * + */ + if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_v_format; + __Pyx_INCREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->_format); + __Pyx_DECREF(__pyx_v_self->_format); + __pyx_v_self->_format = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":135 + * format = (format).encode('ASCII') + * self._format = format # keep a reference to the byte string + * self.format = self._format # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __Pyx_PyObject_AsString(__pyx_v_self->_format); if (unlikely((!__pyx_t_5) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->format = __pyx_t_5; + + /* "View.MemoryView":138 + * + * + * self._shape = PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< + * self._strides = self._shape + self.ndim + * + */ + __pyx_v_self->_shape = ((Py_ssize_t *)PyMem_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); + + /* "View.MemoryView":139 + * + * self._shape = PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) + * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< + * + * if not self._shape: + */ + __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); + + /* "View.MemoryView":141 + * self._strides = self._shape + self.ndim + * + * if not self._shape: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape and strides.") + * + */ + __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":142 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__41, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":145 + * + * + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + __pyx_t_6 = 0; + __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; + for (;;) { + if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_7); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_t_8 = __Pyx_PyIndex_AsSsize_t(__pyx_t_7); if (unlikely((__pyx_t_8 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_dim = __pyx_t_8; + __pyx_v_idx = __pyx_t_6; + __pyx_t_6 = (__pyx_t_6 + 1); + + /* "View.MemoryView":146 + * + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim + */ + __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":147 + * for idx, dim in enumerate(shape): + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< + * self._shape[idx] = dim + * + */ + __pyx_t_7 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_7 = 0; + __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_10, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":148 + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim # <<<<<<<<<<<<<< + * + * cdef char order + */ + (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":151 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = b'F' + * self.mode = u'fortran' + */ + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":152 + * cdef char order + * if mode == 'fortran': + * order = b'F' # <<<<<<<<<<<<<< + * self.mode = u'fortran' + * elif mode == 'c': + */ + __pyx_v_order = 'F'; + + /* "View.MemoryView":153 + * if mode == 'fortran': + * order = b'F' + * self.mode = u'fortran' # <<<<<<<<<<<<<< + * elif mode == 'c': + * order = b'C' + */ + __Pyx_INCREF(__pyx_n_u_fortran); + __Pyx_GIVEREF(__pyx_n_u_fortran); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(__pyx_v_self->mode); + __pyx_v_self->mode = __pyx_n_u_fortran; + goto __pyx_L10; + } + + /* "View.MemoryView":154 + * order = b'F' + * self.mode = u'fortran' + * elif mode == 'c': # <<<<<<<<<<<<<< + * order = b'C' + * self.mode = u'c' + */ + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":155 + * self.mode = u'fortran' + * elif mode == 'c': + * order = b'C' # <<<<<<<<<<<<<< + * self.mode = u'c' + * else: + */ + __pyx_v_order = 'C'; + + /* "View.MemoryView":156 + * elif mode == 'c': + * order = b'C' + * self.mode = u'c' # <<<<<<<<<<<<<< + * else: + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + */ + __Pyx_INCREF(__pyx_n_u_c); + __Pyx_GIVEREF(__pyx_n_u_c); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(__pyx_v_self->mode); + __pyx_v_self->mode = __pyx_n_u_c; + goto __pyx_L10; + } + /*else*/ { + + /* "View.MemoryView":158 + * self.mode = u'c' + * else: + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< + * + * self.len = fill_contig_strides_array(self._shape, self._strides, + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L10:; + + /* "View.MemoryView":160 + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + * + * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< + * itemsize, self.ndim, order) + * + */ + __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); + + /* "View.MemoryView":163 + * itemsize, self.ndim, order) + * + * self.free_data = allocate_buffer # <<<<<<<<<<<<<< + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + */ + __pyx_v_self->free_data = __pyx_v_allocate_buffer; + + /* "View.MemoryView":164 + * + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< + * if allocate_buffer: + * + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_4; + + /* "View.MemoryView":165 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = (__pyx_v_allocate_buffer != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":168 + * + * + * self.data = malloc(self.len) # <<<<<<<<<<<<<< + * if not self.data: + * raise MemoryError("unable to allocate array data.") + */ + __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); + + /* "View.MemoryView":169 + * + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ + __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":170 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__42, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":172 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ + __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":173 + * + * if self.dtype_is_object: + * p = self.data # <<<<<<<<<<<<<< + * for i in range(self.len / itemsize): + * p[i] = Py_None + */ + __pyx_v_p = ((PyObject **)__pyx_v_self->data); + + /* "View.MemoryView":174 + * if self.dtype_is_object: + * p = self.data + * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< + * p[i] = Py_None + * Py_INCREF(Py_None) + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = (__pyx_v_self->len / __pyx_v_itemsize); + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_1; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "View.MemoryView":175 + * p = self.data + * for i in range(self.len / itemsize): + * p[i] = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + (__pyx_v_p[__pyx_v_i]) = Py_None; + + /* "View.MemoryView":176 + * for i in range(self.len / itemsize): + * p[i] = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + Py_INCREF(Py_None); + } + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":116 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_format); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":179 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == u"c": + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_bufmode; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + Py_ssize_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":180 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 # <<<<<<<<<<<<<< + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = -1; + + /* "View.MemoryView":181 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == u"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + */ + __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":182 + * cdef int bufmode = -1 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + + /* "View.MemoryView":183 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ + __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":184 + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + */ + __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":185 + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ + __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":186 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__43, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":187 + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data # <<<<<<<<<<<<<< + * info.len = self.len + * info.ndim = self.ndim + */ + __pyx_t_4 = __pyx_v_self->data; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":188 + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + * info.len = self.len # <<<<<<<<<<<<<< + * info.ndim = self.ndim + * info.shape = self._shape + */ + __pyx_t_5 = __pyx_v_self->len; + __pyx_v_info->len = __pyx_t_5; + + /* "View.MemoryView":189 + * info.buf = self.data + * info.len = self.len + * info.ndim = self.ndim # <<<<<<<<<<<<<< + * info.shape = self._shape + * info.strides = self._strides + */ + __pyx_t_6 = __pyx_v_self->ndim; + __pyx_v_info->ndim = __pyx_t_6; + + /* "View.MemoryView":190 + * info.len = self.len + * info.ndim = self.ndim + * info.shape = self._shape # <<<<<<<<<<<<<< + * info.strides = self._strides + * info.suboffsets = NULL + */ + __pyx_t_7 = __pyx_v_self->_shape; + __pyx_v_info->shape = __pyx_t_7; + + /* "View.MemoryView":191 + * info.ndim = self.ndim + * info.shape = self._shape + * info.strides = self._strides # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = self.itemsize + */ + __pyx_t_7 = __pyx_v_self->_strides; + __pyx_v_info->strides = __pyx_t_7; + + /* "View.MemoryView":192 + * info.shape = self._shape + * info.strides = self._strides + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = self.itemsize + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; + + /* "View.MemoryView":193 + * info.strides = self._strides + * info.suboffsets = NULL + * info.itemsize = self.itemsize # <<<<<<<<<<<<<< + * info.readonly = 0 + * + */ + __pyx_t_5 = __pyx_v_self->itemsize; + __pyx_v_info->itemsize = __pyx_t_5; + + /* "View.MemoryView":194 + * info.suboffsets = NULL + * info.itemsize = self.itemsize + * info.readonly = 0 # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":196 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":197 + * + * if flags & PyBUF_FORMAT: + * info.format = self.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_4 = __pyx_v_self->format; + __pyx_v_info->format = __pyx_t_4; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":199 + * info.format = self.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.obj = self + */ + __pyx_v_info->format = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":201 + * info.format = NULL + * + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "View.MemoryView":179 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == u"c": + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":205 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + +/* Python wrapper */ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_array_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":206 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ + __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":207 + * def __dealloc__(array self): + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) # <<<<<<<<<<<<<< + * elif self.free_data: + * if self.dtype_is_object: + */ + __pyx_v_self->callback_free_data(__pyx_v_self->data); + goto __pyx_L3; + } + + /* "View.MemoryView":208 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ + __pyx_t_1 = (__pyx_v_self->free_data != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":209 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":210 + * elif self.free_data: + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< + * self._strides, self.ndim, False) + * free(self.data) + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":212 + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + * free(self.data) # <<<<<<<<<<<<<< + * PyMem_Free(self._shape) + * + */ + free(__pyx_v_self->data); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":213 + * self._strides, self.ndim, False) + * free(self.data) + * PyMem_Free(self._shape) # <<<<<<<<<<<<<< + * + * property memview: + */ + PyMem_Free(__pyx_v_self->_shape); + + /* "View.MemoryView":205 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":217 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + +/* Python wrapper */ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = get_memview_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":219 + * def __get__(self): + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< + * return memoryview(self, flags, self.dtype_is_object) + * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":220 + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":217 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":223 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":224 + * + * def __getattr__(self, attr): + * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * + * def __getitem__(self, item): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":223 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":226 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":227 + * + * def __getitem__(self, item): + * return self.memview[item] # <<<<<<<<<<<<<< + * + * def __setitem__(self, item, value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":226 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":229 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + +/* Python wrapper */ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "View.MemoryView":230 + * + * def __setitem__(self, item, value): + * self.memview[item] = value # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":229 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":234 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + +static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { + struct __pyx_array_obj *__pyx_v_result = 0; + struct __pyx_array_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("array_cwrapper", 0); + + /* "View.MemoryView":238 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":239 + * + * if buf == NULL: + * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":241 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":242 + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) # <<<<<<<<<<<<<< + * result.data = buf + * + */ + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":241 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":243 + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) + * result.data = buf # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->data = __pyx_v_buf; + } + __pyx_L3:; + + /* "View.MemoryView":245 + * result.data = buf + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":234 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":271 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + +/* Python wrapper */ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_name = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name_2,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_name_2)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_name = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "View.MemoryView":272 + * cdef object name + * def __init__(self, name): + * self.name = name # <<<<<<<<<<<<<< + * def __repr__(self): + * return self.name + */ + __Pyx_INCREF(__pyx_v_name); + __Pyx_GIVEREF(__pyx_v_name); + __Pyx_GOTREF(__pyx_v_self->name); + __Pyx_DECREF(__pyx_v_self->name); + __pyx_v_self->name = __pyx_v_name; + + /* "View.MemoryView":271 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":273 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + +/* Python wrapper */ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":274 + * self.name = name + * def __repr__(self): + * return self.name # <<<<<<<<<<<<<< + * + * cdef generic = Enum("") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->name); + __pyx_r = __pyx_v_self->name; + goto __pyx_L0; + + /* "View.MemoryView":273 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":288 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + +static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { + Py_intptr_t __pyx_v_aligned_p; + size_t __pyx_v_offset; + void *__pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":290 + * cdef void *align_pointer(void *memory, size_t alignment) nogil: + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< + * cdef size_t offset + * + */ + __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + + /* "View.MemoryView":294 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":296 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + __pyx_t_1 = ((__pyx_v_offset > 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":297 + * + * if offset > 0: + * aligned_p += alignment - offset # <<<<<<<<<<<<<< + * + * return aligned_p + */ + __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":299 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview') + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + /* "View.MemoryView":288 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":317 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + +/* Python wrapper */ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_obj = 0; + int __pyx_v_flags; + int __pyx_v_dtype_is_object; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dtype_is_object); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_obj = values[0]; + __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[2]) { + __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_dtype_is_object = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_memoryview_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "View.MemoryView":318 + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj # <<<<<<<<<<<<<< + * self.flags = flags + * if type(self) is memoryview or obj is not None: + */ + __Pyx_INCREF(__pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __Pyx_GOTREF(__pyx_v_self->obj); + __Pyx_DECREF(__pyx_v_self->obj); + __pyx_v_self->obj = __pyx_v_obj; + + /* "View.MemoryView":319 + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj + * self.flags = flags # <<<<<<<<<<<<<< + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + */ + __pyx_v_self->flags = __pyx_v_flags; + + /* "View.MemoryView":320 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ + __pyx_t_1 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type))); + if (!(__pyx_t_1 != 0)) { + __pyx_t_2 = (__pyx_v_obj != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + } else { + __pyx_t_3 = (__pyx_t_1 != 0); + } + if (__pyx_t_3) { + + /* "View.MemoryView":321 + * self.flags = flags + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + */ + __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":322 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_t_3 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":323 + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; + + /* "View.MemoryView":324 + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * self.lock = PyThread_allocate_lock() + */ + Py_INCREF(Py_None); + goto __pyx_L4; + } + __pyx_L4:; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":326 + * Py_INCREF(Py_None) + * + * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< + * if self.lock == NULL: + * raise MemoryError + */ + __pyx_v_self->lock = PyThread_allocate_lock(); + + /* "View.MemoryView":327 + * + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + __pyx_t_3 = ((__pyx_v_self->lock == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":328 + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":330 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = self.view.format == b'O' + * else: + */ + __pyx_t_3 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":331 + * + * if flags & PyBUF_FORMAT: + * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< + * else: + * self.dtype_is_object = dtype_is_object + */ + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_5, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":333 + * self.dtype_is_object = self.view.format == b'O' + * else: + * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + */ + __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; + } + __pyx_L6:; + + /* "View.MemoryView":335 + * self.dtype_is_object = dtype_is_object + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL + */ + __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); + + /* "View.MemoryView":337 + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(memoryview self): + */ + __pyx_v_self->typeinfo = NULL; + + /* "View.MemoryView":317 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":339 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + +/* Python wrapper */ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":340 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< + * __Pyx_ReleaseBuffer(&self.view) + * + */ + __pyx_t_1 = (__pyx_v_self->obj != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":341 + * def __dealloc__(memoryview self): + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< + * + * if self.lock != NULL: + */ + __Pyx_ReleaseBuffer((&__pyx_v_self->view)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":343 + * __Pyx_ReleaseBuffer(&self.view) + * + * if self.lock != NULL: # <<<<<<<<<<<<<< + * PyThread_free_lock(self.lock) + * + */ + __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":344 + * + * if self.lock != NULL: + * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + */ + PyThread_free_lock(__pyx_v_self->lock); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":339 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":346 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + Py_ssize_t __pyx_v_dim; + char *__pyx_v_itemp; + PyObject *__pyx_v_idx = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_item_pointer", 0); + + /* "View.MemoryView":348 + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< + * + * for dim, idx in enumerate(index): + */ + __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); + + /* "View.MemoryView":350 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + __pyx_t_1 = 0; + if (PyList_CheckExact(__pyx_v_index) || PyTuple_CheckExact(__pyx_v_index)) { + __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; + } + for (;;) { + if (!__pyx_t_4 && PyList_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_4 && PyTuple_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); + __pyx_t_5 = 0; + __pyx_v_dim = __pyx_t_1; + __pyx_t_1 = (__pyx_t_1 + 1); + + /* "View.MemoryView":351 + * + * for dim, idx in enumerate(index): + * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< + * + * return itemp + */ + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_7; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":353 + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + * return itemp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_itemp; + goto __pyx_L0; + + /* "View.MemoryView":346 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":356 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_indices = NULL; + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + char *__pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":357 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":358 + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: + * return self # <<<<<<<<<<<<<< + * + * have_slices, indices = _unellipsify(index, self.view.ndim) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __pyx_r = ((PyObject *)__pyx_v_self); + goto __pyx_L0; + } + + /* "View.MemoryView":360 + * return self + * + * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * cdef char *itemp + */ + __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (likely(__pyx_t_3 != Py_None)) { + PyObject* sequence = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_have_slices = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; + + /* "View.MemoryView":363 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":364 + * cdef char *itemp + * if have_slices: + * return memview_slice(self, indices) # <<<<<<<<<<<<<< + * else: + * itemp = self.get_item_pointer(indices) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 364; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":366 + * return memview_slice(self, indices) + * else: + * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< + * return self.convert_item_to_object(itemp) + * + */ + __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_6; + + /* "View.MemoryView":367 + * else: + * itemp = self.get_item_pointer(indices) + * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< + * + * def __setitem__(memoryview self, object index, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 367; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":356 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":369 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + +/* Python wrapper */ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_obj = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_INCREF(__pyx_v_index); + + /* "View.MemoryView":370 + * + * def __setitem__(memoryview self, object index, object value): + * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * if have_slices: + */ + __pyx_t_1 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (likely(__pyx_t_1 != Py_None)) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_have_slices = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":372 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":373 + * + * if have_slices: + * obj = self.is_slice(value) # <<<<<<<<<<<<<< + * if obj: + * self.setitem_slice_assignment(self[index], obj) + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_obj = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":374 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_4) { + + /* "View.MemoryView":375 + * obj = self.is_slice(value) + * if obj: + * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< + * else: + * self.setitem_slice_assign_scalar(self[index], value) + */ + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":377 + * self.setitem_slice_assignment(self[index], obj) + * else: + * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< + * else: + * self.setitem_indexed(index, value) + */ + __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":379 + * self.setitem_slice_assign_scalar(self[index], value) + * else: + * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< + * + * cdef is_slice(self, obj): + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":369 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":381 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_slice", 0); + __Pyx_INCREF(__pyx_v_obj); + + /* "View.MemoryView":382 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type)); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":383 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + { + __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + /*try:*/ { + + /* "View.MemoryView":384 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_6 = __Pyx_PyInt_From_int((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":385 + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * except TypeError: + * return None + */ + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":384 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); + __pyx_t_7 = 0; + } + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L11_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":386 + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + * except TypeError: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":387 + * self.dtype_is_object) + * except TypeError: + * return None # <<<<<<<<<<<<<< + * + * return obj + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L7_except_return; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L5_exception_handled; + } + goto __pyx_L6_except_error; + __pyx_L6_except_error:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L1_error; + __pyx_L7_except_return:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L0; + __pyx_L5_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + __pyx_L11_try_end:; + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":389 + * return None + * + * return obj # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assignment(self, dst, src): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_obj); + __pyx_r = __pyx_v_obj; + goto __pyx_L0; + + /* "View.MemoryView":381 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":391 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { + __Pyx_memviewslice __pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_src_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); + + /* "View.MemoryView":395 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":396 + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< + * src.ndim, dst.ndim, self.dtype_is_object) + * + */ + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":397 + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":395 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":391 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":399 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { + int __pyx_v_array[128]; + void *__pyx_v_tmp; + void *__pyx_v_item; + __Pyx_memviewslice *__pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_tmp_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + char const *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); + + /* "View.MemoryView":401 + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + * cdef int array[128] + * cdef void *tmp = NULL # <<<<<<<<<<<<<< + * cdef void *item + * + */ + __pyx_v_tmp = NULL; + + /* "View.MemoryView":406 + * cdef __Pyx_memviewslice *dst_slice + * cdef __Pyx_memviewslice tmp_slice + * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< + * + * if self.view.itemsize > sizeof(array): + */ + __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); + + /* "View.MemoryView":408 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + */ + __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":409 + * + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError + */ + __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); + + /* "View.MemoryView":410 + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":411 + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * item = tmp + * else: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":412 + * if tmp == NULL: + * raise MemoryError + * item = tmp # <<<<<<<<<<<<<< + * else: + * item = array + */ + __pyx_v_item = __pyx_v_tmp; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":414 + * item = tmp + * else: + * item = array # <<<<<<<<<<<<<< + * + * try: + */ + __pyx_v_item = ((void *)__pyx_v_array); + } + __pyx_L3:; + + /* "View.MemoryView":416 + * item = array + * + * try: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * ( item)[0] = value + */ + /*try:*/ { + + /* "View.MemoryView":417 + * + * try: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":418 + * try: + * if self.dtype_is_object: + * ( item)[0] = value # <<<<<<<<<<<<<< + * else: + * self.assign_item_from_object( item, value) + */ + (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); + goto __pyx_L8; + } + /*else*/ { + + /* "View.MemoryView":420 + * ( item)[0] = value + * else: + * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_L8:; + + /* "View.MemoryView":424 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":425 + * + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + */ + __pyx_t_2 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":426 + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< + * item, self.dtype_is_object) + * finally: + */ + __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); + } + + /* "View.MemoryView":429 + * item, self.dtype_is_object) + * finally: + * PyMem_Free(tmp) # <<<<<<<<<<<<<< + * + * cdef setitem_indexed(self, index, value): + */ + /*finally:*/ { + /*normal exit:*/{ + PyMem_Free(__pyx_v_tmp); + goto __pyx_L7; + } + /*exception exit:*/{ + __pyx_L6_error:; + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8) < 0)) __Pyx_ErrFetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_11); + __pyx_t_3 = __pyx_lineno; __pyx_t_4 = __pyx_clineno; __pyx_t_5 = __pyx_filename; + { + PyMem_Free(__pyx_v_tmp); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } + __Pyx_XGIVEREF(__pyx_t_6); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_ErrRestore(__pyx_t_6, __pyx_t_7, __pyx_t_8); + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __pyx_lineno = __pyx_t_3; __pyx_clineno = __pyx_t_4; __pyx_filename = __pyx_t_5; + goto __pyx_L1_error; + } + __pyx_L7:; + } + + /* "View.MemoryView":399 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":431 + * PyMem_Free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_indexed", 0); + + /* "View.MemoryView":432 + * + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< + * self.assign_item_from_object(itemp, value) + * + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_1; + + /* "View.MemoryView":433 + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":431 + * PyMem_Free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":435 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_v_struct = NULL; + PyObject *__pyx_v_bytesitem = 0; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":438 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef bytes bytesitem + * + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":441 + * cdef bytes bytesitem + * + * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< + * try: + * result = struct.unpack(self.view.format, bytesitem) + */ + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":442 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":443 + * bytesitem = itemp[:self.view.itemsize] + * try: + * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< + * except struct.error: + * raise ValueError("Unable to convert item to object") + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_bytesitem); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_v_bytesitem); + __Pyx_GIVEREF(__pyx_v_bytesitem); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + } + /*else:*/ { + + /* "View.MemoryView":447 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + __pyx_t_7 = strlen(__pyx_v_self->view.format); + __pyx_t_8 = ((__pyx_t_7 == 1) != 0); + if (__pyx_t_8) { + + /* "View.MemoryView":448 + * else: + * if len(self.view.format) == 1: + * return result[0] # <<<<<<<<<<<<<< + * return result + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}; + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L6_except_return; + } + + /* "View.MemoryView":449 + * if len(self.view.format) == 1: + * return result[0] + * return result # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L6_except_return; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L10_try_end; + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":444 + * try: + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: # <<<<<<<<<<<<<< + * raise ValueError("Unable to convert item to object") + * else: + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_1) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_1); + + /* "View.MemoryView":445 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_t_10 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__44, NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L4_exception_handled; + } + goto __pyx_L5_except_error; + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L6_except_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + __pyx_L4_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L10_try_end:; + } + + /* "View.MemoryView":435 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesitem); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":451 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_v_struct = NULL; + char __pyx_v_c; + PyObject *__pyx_v_bytesvalue = 0; + Py_ssize_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + char *__pyx_t_10; + char *__pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":454 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef char c + * cdef bytes bytesvalue + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":459 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + __pyx_t_2 = PyTuple_Check(__pyx_v_value); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":460 + * + * if isinstance(value, tuple): + * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< + * else: + * bytesvalue = struct.pack(self.view.format, value) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":462 + * bytesvalue = struct.pack(self.view.format, *value) + * else: + * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< + * + * for i, c in enumerate(bytesvalue): + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_INCREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_1, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_6)->tp_name), 0))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":464 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = 0; + if (unlikely(__pyx_v_bytesvalue == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_INCREF(__pyx_v_bytesvalue); + __pyx_t_8 = __pyx_v_bytesvalue; + __pyx_t_10 = PyBytes_AS_STRING(__pyx_t_8); + __pyx_t_11 = (__pyx_t_10 + PyBytes_GET_SIZE(__pyx_t_8)); + for (__pyx_t_12 = __pyx_t_10; __pyx_t_12 < __pyx_t_11; __pyx_t_12++) { + __pyx_t_9 = __pyx_t_12; + __pyx_v_c = (__pyx_t_9[0]); + + /* "View.MemoryView":465 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + __pyx_v_i = __pyx_t_7; + + /* "View.MemoryView":464 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":465 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "View.MemoryView":451 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":468 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + char *__pyx_t_3; + void *__pyx_t_4; + int __pyx_t_5; + Py_ssize_t __pyx_t_6; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":469 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":470 + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape # <<<<<<<<<<<<<< + * else: + * info.shape = NULL + */ + __pyx_t_2 = __pyx_v_self->view.shape; + __pyx_v_info->shape = __pyx_t_2; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":472 + * info.shape = self.view.shape + * else: + * info.shape = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_STRIDES: + */ + __pyx_v_info->shape = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":474 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":475 + * + * if flags & PyBUF_STRIDES: + * info.strides = self.view.strides # <<<<<<<<<<<<<< + * else: + * info.strides = NULL + */ + __pyx_t_2 = __pyx_v_self->view.strides; + __pyx_v_info->strides = __pyx_t_2; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":477 + * info.strides = self.view.strides + * else: + * info.strides = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_INDIRECT: + */ + __pyx_v_info->strides = NULL; + } + __pyx_L4:; + + /* "View.MemoryView":479 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":480 + * + * if flags & PyBUF_INDIRECT: + * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< + * else: + * info.suboffsets = NULL + */ + __pyx_t_2 = __pyx_v_self->view.suboffsets; + __pyx_v_info->suboffsets = __pyx_t_2; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":482 + * info.suboffsets = self.view.suboffsets + * else: + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->suboffsets = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":484 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":485 + * + * if flags & PyBUF_FORMAT: + * info.format = self.view.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_3 = __pyx_v_self->view.format; + __pyx_v_info->format = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":487 + * info.format = self.view.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.buf = self.view.buf + */ + __pyx_v_info->format = NULL; + } + __pyx_L6:; + + /* "View.MemoryView":489 + * info.format = NULL + * + * info.buf = self.view.buf # <<<<<<<<<<<<<< + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + */ + __pyx_t_4 = __pyx_v_self->view.buf; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":490 + * + * info.buf = self.view.buf + * info.ndim = self.view.ndim # <<<<<<<<<<<<<< + * info.itemsize = self.view.itemsize + * info.len = self.view.len + */ + __pyx_t_5 = __pyx_v_self->view.ndim; + __pyx_v_info->ndim = __pyx_t_5; + + /* "View.MemoryView":491 + * info.buf = self.view.buf + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< + * info.len = self.view.len + * info.readonly = 0 + */ + __pyx_t_6 = __pyx_v_self->view.itemsize; + __pyx_v_info->itemsize = __pyx_t_6; + + /* "View.MemoryView":492 + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + * info.len = self.view.len # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.obj = self + */ + __pyx_t_6 = __pyx_v_self->view.len; + __pyx_v_info->len = __pyx_t_6; + + /* "View.MemoryView":493 + * info.itemsize = self.view.itemsize + * info.len = self.view.len + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.obj = self + * + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":494 + * info.len = self.view.len + * info.readonly = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "View.MemoryView":468 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + + /* function exit code */ + __pyx_r = 0; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":501 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":502 + * @cname('__pyx_memoryview_transpose') + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< + * transpose_memslice(&result.from_slice) + * return result + */ + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":503 + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":504 + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + * return result # <<<<<<<<<<<<<< + * + * property base: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":501 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":508 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":509 + * @cname('__pyx_memoryview__get__base') + * def __get__(self): + * return self.obj # <<<<<<<<<<<<<< + * + * property shape: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->obj); + __pyx_r = __pyx_v_self->obj; + goto __pyx_L0; + + /* "View.MemoryView":508 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":513 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":514 + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property strides: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_v_self->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->view.shape[__pyx_v_i])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __pyx_t_4 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + + /* "View.MemoryView":513 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":518 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":519 + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":521 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__45, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":523 + * raise ValueError("Buffer view does not expose strides") + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property suboffsets: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.strides[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":518 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":527 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":528 + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return [-1] * self.view.ndim + * + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":529 + * def __get__(self): + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(1 * ((__pyx_v_self->view.ndim<0) ? 0:__pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_self->view.ndim; __pyx_temp++) { + __Pyx_INCREF(__pyx_int_neg_1); + PyList_SET_ITEM(__pyx_t_2, __pyx_temp, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + } + } + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":531 + * return [-1] * self.view.ndim + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property ndim: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.suboffsets[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":527 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":535 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":536 + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): + * return self.view.ndim # <<<<<<<<<<<<<< + * + * property itemsize: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":535 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":540 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":541 + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): + * return self.view.itemsize # <<<<<<<<<<<<<< + * + * property nbytes: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 541; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":540 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":545 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":546 + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): + * return self.size * self.view.itemsize # <<<<<<<<<<<<<< + * + * property size: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":545 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":550 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":551 + * @cname('__pyx_memoryview_get_size') + * def __get__(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + __pyx_t_1 = (__pyx_v_self->_size == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":552 + * def __get__(self): + * if self._size is None: + * result = 1 # <<<<<<<<<<<<<< + * + * for length in self.shape: + */ + __Pyx_INCREF(__pyx_int_1); + __pyx_v_result = __pyx_int_1; + + /* "View.MemoryView":554 + * result = 1 + * + * for length in self.shape: # <<<<<<<<<<<<<< + * result *= length + * + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyList_CheckExact(__pyx_t_3) || PyTuple_CheckExact(__pyx_t_3)) { + __pyx_t_4 = __pyx_t_3; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_3 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_3)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":555 + * + * for length in self.shape: + * result *= length # <<<<<<<<<<<<<< + * + * self._size = result + */ + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 555; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_3); + __pyx_t_3 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "View.MemoryView":557 + * result *= length + * + * self._size = result # <<<<<<<<<<<<<< + * + * return self._size + */ + __Pyx_INCREF(__pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __Pyx_GOTREF(__pyx_v_self->_size); + __Pyx_DECREF(__pyx_v_self->_size); + __pyx_v_self->_size = __pyx_v_result; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":559 + * self._size = result + * + * return self._size # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->_size); + __pyx_r = __pyx_v_self->_size; + goto __pyx_L0; + + /* "View.MemoryView":550 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":561 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + +/* Python wrapper */ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__len__", 0); + + /* "View.MemoryView":562 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":563 + * def __len__(self): + * if self.view.ndim >= 1: + * return self.view.shape[0] # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_r = (__pyx_v_self->view.shape[0]); + goto __pyx_L0; + } + + /* "View.MemoryView":565 + * return self.view.shape[0] + * + * return 0 # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":561 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":567 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":568 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":569 + * def __repr__(self): + * return "" % (self.base.__class__.__name__, + * id(self)) # <<<<<<<<<<<<<< + * + * def __str__(self): + */ + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_id, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":568 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":567 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":571 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__str__", 0); + + /* "View.MemoryView":572 + * + * def __str__(self): + * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":571 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":575 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_c_contig", 0); + + /* "View.MemoryView":578 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":579 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< + * + * def is_f_contig(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":575 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":581 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_f_contig", 0); + + /* "View.MemoryView":584 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":585 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< + * + * def copy(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":581 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":587 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_mslice; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "View.MemoryView":589 + * def copy(self): + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &mslice) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); + + /* "View.MemoryView":591 + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + * + * slice_copy(self, &mslice) # <<<<<<<<<<<<<< + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); + + /* "View.MemoryView":592 + * + * slice_copy(self, &mslice) + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_C_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k_c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":597 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< + * + * def copy_fortran(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":587 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":599 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy_fortran", 0); + + /* "View.MemoryView":601 + * def copy_fortran(self): + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &src) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); + + /* "View.MemoryView":603 + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + * + * slice_copy(self, &src) # <<<<<<<<<<<<<< + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); + + /* "View.MemoryView":604 + * + * slice_copy(self, &src) + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_F_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k_fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dst = __pyx_t_1; + + /* "View.MemoryView":609 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":599 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":613 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + +static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { + struct __pyx_memoryview_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); + + /* "View.MemoryView":614 + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< + * result.typeinfo = typeinfo + * return result + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); + __Pyx_GIVEREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":615 + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_v_result->typeinfo = __pyx_v_typeinfo; + + /* "View.MemoryView":616 + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_check') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":613 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":619 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("memoryview_check", 0); + + /* "View.MemoryView":620 + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): + * return isinstance(o, memoryview) # <<<<<<<<<<<<<< + * + * cdef tuple _unellipsify(object index, int ndim): + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type)); + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + /* "View.MemoryView":619 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":622 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + +static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { + PyObject *__pyx_v_tup = NULL; + PyObject *__pyx_v_result = NULL; + int __pyx_v_have_slices; + int __pyx_v_seen_ellipsis; + CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_item = NULL; + Py_ssize_t __pyx_v_nslices; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + int __pyx_t_10; + int __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_unellipsify", 0); + + /* "View.MemoryView":627 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + __pyx_t_1 = PyTuple_Check(__pyx_v_index); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":628 + * """ + * if not isinstance(index, tuple): + * tup = (index,) # <<<<<<<<<<<<<< + * else: + * tup = index + */ + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_index); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); + __Pyx_GIVEREF(__pyx_v_index); + __pyx_v_tup = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":630 + * tup = (index,) + * else: + * tup = index # <<<<<<<<<<<<<< + * + * result = [] + */ + __Pyx_INCREF(__pyx_v_index); + __pyx_v_tup = __pyx_v_index; + } + __pyx_L3:; + + /* "View.MemoryView":632 + * tup = index + * + * result = [] # <<<<<<<<<<<<<< + * have_slices = False + * seen_ellipsis = False + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_result = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":633 + * + * result = [] + * have_slices = False # <<<<<<<<<<<<<< + * seen_ellipsis = False + * for idx, item in enumerate(tup): + */ + __pyx_v_have_slices = 0; + + /* "View.MemoryView":634 + * result = [] + * have_slices = False + * seen_ellipsis = False # <<<<<<<<<<<<<< + * for idx, item in enumerate(tup): + * if item is Ellipsis: + */ + __pyx_v_seen_ellipsis = 0; + + /* "View.MemoryView":635 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_3 = __pyx_int_0; + if (PyList_CheckExact(__pyx_v_tup) || PyTuple_CheckExact(__pyx_v_tup)) { + __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_7 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_7)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); + __pyx_t_7 = 0; + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); + __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_t_7; + __pyx_t_7 = 0; + + /* "View.MemoryView":636 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ + __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":637 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ + __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":638 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__46, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { + __Pyx_INCREF(__pyx_t_7); + PyList_SET_ITEM(__pyx_t_9, __pyx_temp, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + } + } + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_10 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_9); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "View.MemoryView":639 + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True # <<<<<<<<<<<<<< + * else: + * result.append(slice(None)) + */ + __pyx_v_seen_ellipsis = 1; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":641 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_t_9 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__47, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = __Pyx_PyList_Append(__pyx_v_result, __pyx_t_9); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + __pyx_L7:; + + /* "View.MemoryView":642 + * else: + * result.append(slice(None)) + * have_slices = True # <<<<<<<<<<<<<< + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + */ + __pyx_v_have_slices = 1; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":644 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ + __pyx_t_1 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_1 = ((!(__Pyx_PyIndex_Check(__pyx_v_item) != 0)) != 0); + __pyx_t_11 = __pyx_t_1; + } else { + __pyx_t_11 = __pyx_t_2; + } + if (__pyx_t_11) { + + /* "View.MemoryView":645 + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< + * + * have_slices = have_slices or isinstance(item, slice) + */ + __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_7, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":647 + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< + * result.append(item) + * + */ + if (!__pyx_v_have_slices) { + __pyx_t_11 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = __pyx_t_11; + } else { + __pyx_t_2 = __pyx_v_have_slices; + } + __pyx_v_have_slices = __pyx_t_2; + + /* "View.MemoryView":648 + * + * have_slices = have_slices or isinstance(item, slice) + * result.append(item) # <<<<<<<<<<<<<< + * + * nslices = ndim - len(result) + */ + __pyx_t_10 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":650 + * result.append(item) + * + * nslices = ndim - len(result) # <<<<<<<<<<<<<< + * if nslices: + * result.extend([slice(None)] * nslices) + */ + __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); + + /* "View.MemoryView":651 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + __pyx_t_2 = (__pyx_v_nslices != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":652 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__48, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { + __Pyx_INCREF(__pyx_t_3); + PyList_SET_ITEM(__pyx_t_4, __pyx_temp, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + } + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_10 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_4); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":654 + * result.extend([slice(None)] * nslices) + * + * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_2) { + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_9 = __pyx_t_3; + __pyx_t_3 = 0; + } else { + __pyx_t_9 = __pyx_t_4; + __pyx_t_4 = 0; + } + __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_9 = 0; + __pyx_t_4 = 0; + __pyx_r = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":622 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_tup); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_item); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":656 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + +static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); + + /* "View.MemoryView":658 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * cdef int i + * for i in range(ndim): # <<<<<<<<<<<<<< + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":659 + * cdef int i + * for i in range(ndim): + * if suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ + __pyx_t_3 = (((__pyx_v_suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":660 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__49, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + + /* "View.MemoryView":656 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":667 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { + int __pyx_v_new_ndim; + int __pyx_v_suboffset_dim; + int __pyx_v_dim; + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + __Pyx_memviewslice *__pyx_v_p_src; + struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; + __Pyx_memviewslice *__pyx_v_p_dst; + int *__pyx_v_p_suboffset_dim; + Py_ssize_t __pyx_v_start; + Py_ssize_t __pyx_v_stop; + Py_ssize_t __pyx_v_step; + int __pyx_v_have_start; + int __pyx_v_have_stop; + int __pyx_v_have_step; + PyObject *__pyx_v_index = NULL; + struct __pyx_memoryview_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + struct __pyx_memoryview_obj *__pyx_t_4; + char *__pyx_t_5; + int __pyx_t_6; + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + PyObject *__pyx_t_12 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memview_slice", 0); + + /* "View.MemoryView":668 + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): + * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< + * cdef bint negative_step + * cdef __Pyx_memviewslice src, dst + */ + __pyx_v_new_ndim = 0; + __pyx_v_suboffset_dim = -1; + + /* "View.MemoryView":675 + * + * + * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< + * + * cdef _memoryviewslice memviewsliceobj + */ + memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); + + /* "View.MemoryView":679 + * cdef _memoryviewslice memviewsliceobj + * + * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "View.MemoryView":681 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":682 + * + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview # <<<<<<<<<<<<<< + * p_src = &memviewsliceobj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 682; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":683 + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, &src) + */ + __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":685 + * p_src = &memviewsliceobj.from_slice + * else: + * slice_copy(memview, &src) # <<<<<<<<<<<<<< + * p_src = &src + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); + + /* "View.MemoryView":686 + * else: + * slice_copy(memview, &src) + * p_src = &src # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_src = (&__pyx_v_src); + } + __pyx_L3:; + + /* "View.MemoryView":692 + * + * + * dst.memview = p_src.memview # <<<<<<<<<<<<<< + * dst.data = p_src.data + * + */ + __pyx_t_4 = __pyx_v_p_src->memview; + __pyx_v_dst.memview = __pyx_t_4; + + /* "View.MemoryView":693 + * + * dst.memview = p_src.memview + * dst.data = p_src.data # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_v_p_src->data; + __pyx_v_dst.data = __pyx_t_5; + + /* "View.MemoryView":698 + * + * + * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< + * cdef int *p_suboffset_dim = &suboffset_dim + * cdef Py_ssize_t start, stop, step + */ + __pyx_v_p_dst = (&__pyx_v_dst); + + /* "View.MemoryView":699 + * + * cdef __Pyx_memviewslice *p_dst = &dst + * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< + * cdef Py_ssize_t start, stop, step + * cdef bint have_start, have_stop, have_step + */ + __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); + + /* "View.MemoryView":703 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + __pyx_t_6 = 0; + if (PyList_CheckExact(__pyx_v_indices) || PyTuple_CheckExact(__pyx_v_indices)) { + __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; + } + for (;;) { + if (!__pyx_t_8 && PyList_CheckExact(__pyx_t_3)) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_8 && PyTuple_CheckExact(__pyx_t_3)) { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_9 = __pyx_t_8(__pyx_t_3); + if (unlikely(!__pyx_t_9)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[3]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_9); + } + __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); + __pyx_t_9 = 0; + __pyx_v_dim = __pyx_t_6; + __pyx_t_6 = (__pyx_t_6 + 1); + + /* "View.MemoryView":704 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ + __pyx_t_2 = (__Pyx_PyIndex_Check(__pyx_v_index) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":708 + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< + * 0, 0, 0, # have_{start,stop,step} + * False) + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":705 + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 705; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + + /* "View.MemoryView":711 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ + __pyx_t_2 = (__pyx_v_index == Py_None); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":712 + * False) + * elif index is None: + * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + */ + (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; + + /* "View.MemoryView":713 + * elif index is None: + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 + */ + (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; + + /* "View.MemoryView":714 + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< + * new_ndim += 1 + * else: + */ + (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1; + + /* "View.MemoryView":715 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 # <<<<<<<<<<<<<< + * else: + * start = index.start or 0 + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":717 + * new_ndim += 1 + * else: + * start = index.start or 0 # <<<<<<<<<<<<<< + * stop = index.stop or 0 + * step = index.step or 0 + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_start = __pyx_t_10; + + /* "View.MemoryView":718 + * else: + * start = index.start or 0 + * stop = index.stop or 0 # <<<<<<<<<<<<<< + * step = index.step or 0 + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_12); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_9 = __pyx_int_0; + } else { + __pyx_t_9 = __pyx_t_12; + __pyx_t_12 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_stop = __pyx_t_10; + + /* "View.MemoryView":719 + * start = index.start or 0 + * stop = index.stop or 0 + * step = index.step or 0 # <<<<<<<<<<<<<< + * + * have_start = index.start is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_step = __pyx_t_10; + + /* "View.MemoryView":721 + * step = index.step or 0 + * + * have_start = index.start is not None # <<<<<<<<<<<<<< + * have_stop = index.stop is not None + * have_step = index.step is not None + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 721; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_start = __pyx_t_1; + + /* "View.MemoryView":722 + * + * have_start = index.start is not None + * have_stop = index.stop is not None # <<<<<<<<<<<<<< + * have_step = index.step is not None + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_stop = __pyx_t_1; + + /* "View.MemoryView":723 + * have_start = index.start is not None + * have_stop = index.stop is not None + * have_step = index.step is not None # <<<<<<<<<<<<<< + * + * slice_memviewslice( + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_step = __pyx_t_1; + + /* "View.MemoryView":725 + * have_step = index.step is not None + * + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":731 + * have_start, have_stop, have_step, + * True) + * new_ndim += 1 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":733 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":734 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":735 + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 735; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":736 + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * else: + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[3]; __pyx_lineno = 736; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":734 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 734; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 734; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":739 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":740 + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":739 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":667 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":764 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { + Py_ssize_t __pyx_v_new_shape; + int __pyx_v_negative_step; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":784 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":786 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + __pyx_t_1 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":787 + * + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":788 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + __pyx_t_1 = (0 <= __pyx_v_start); + if (__pyx_t_1) { + __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); + } + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":789 + * start += shape + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< + * else: + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_Index_out_of_bounds_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 789; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":792 + * else: + * + * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< + * + * if have_step and step == 0: + */ + __pyx_t_2 = (__pyx_v_have_step != 0); + if (__pyx_t_2) { + __pyx_t_1 = (__pyx_v_step < 0); + __pyx_t_4 = __pyx_t_1; + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_v_negative_step = __pyx_t_4; + + /* "View.MemoryView":794 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + if ((__pyx_v_have_step != 0)) { + __pyx_t_4 = (__pyx_v_step == 0); + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = (__pyx_v_have_step != 0); + } + if (__pyx_t_2) { + + /* "View.MemoryView":795 + * + * if have_step and step == 0: + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Step_may_not_be_zero_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":798 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + __pyx_t_2 = (__pyx_v_have_start != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":799 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":800 + * if have_start: + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if start < 0: + * start = 0 + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":801 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":802 + * start += shape + * if start < 0: + * start = 0 # <<<<<<<<<<<<<< + * elif start >= shape: + * if negative_step: + */ + __pyx_v_start = 0; + goto __pyx_L9; + } + __pyx_L9:; + goto __pyx_L8; + } + + /* "View.MemoryView":803 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":804 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":805 + * elif start >= shape: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = shape + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L10; + } + /*else*/ { + + /* "View.MemoryView":807 + * start = shape - 1 + * else: + * start = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_start = __pyx_v_shape; + } + __pyx_L10:; + goto __pyx_L8; + } + __pyx_L8:; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":809 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":810 + * else: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = 0 + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":812 + * start = shape - 1 + * else: + * start = 0 # <<<<<<<<<<<<<< + * + * if have_stop: + */ + __pyx_v_start = 0; + } + __pyx_L11:; + } + __pyx_L7:; + + /* "View.MemoryView":814 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + __pyx_t_2 = (__pyx_v_have_stop != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":815 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":816 + * if have_stop: + * if stop < 0: + * stop += shape # <<<<<<<<<<<<<< + * if stop < 0: + * stop = 0 + */ + __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); + + /* "View.MemoryView":817 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":818 + * stop += shape + * if stop < 0: + * stop = 0 # <<<<<<<<<<<<<< + * elif stop > shape: + * stop = shape + */ + __pyx_v_stop = 0; + goto __pyx_L14; + } + __pyx_L14:; + goto __pyx_L13; + } + + /* "View.MemoryView":819 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":820 + * stop = 0 + * elif stop > shape: + * stop = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_stop = __pyx_v_shape; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L12; + } + /*else*/ { + + /* "View.MemoryView":822 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":823 + * else: + * if negative_step: + * stop = -1 # <<<<<<<<<<<<<< + * else: + * stop = shape + */ + __pyx_v_stop = -1; + goto __pyx_L15; + } + /*else*/ { + + /* "View.MemoryView":825 + * stop = -1 + * else: + * stop = shape # <<<<<<<<<<<<<< + * + * if not have_step: + */ + __pyx_v_stop = __pyx_v_shape; + } + __pyx_L15:; + } + __pyx_L12:; + + /* "View.MemoryView":827 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":828 + * + * if not have_step: + * step = 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_step = 1; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":832 + * + * with cython.cdivision(True): + * new_shape = (stop - start) // step # <<<<<<<<<<<<<< + * + * if (stop - start) - step * new_shape: + */ + __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); + + /* "View.MemoryView":834 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":835 + * + * if (stop - start) - step * new_shape: + * new_shape += 1 # <<<<<<<<<<<<<< + * + * if new_shape < 0: + */ + __pyx_v_new_shape = (__pyx_v_new_shape + 1); + goto __pyx_L17; + } + __pyx_L17:; + + /* "View.MemoryView":837 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":838 + * + * if new_shape < 0: + * new_shape = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_new_shape = 0; + goto __pyx_L18; + } + __pyx_L18:; + + /* "View.MemoryView":841 + * + * + * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset + */ + (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); + + /* "View.MemoryView":842 + * + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< + * dst.suboffsets[new_ndim] = suboffset + * + */ + (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; + + /* "View.MemoryView":843 + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; + } + __pyx_L3:; + + /* "View.MemoryView":846 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":847 + * + * if suboffset_dim[0] < 0: + * dst.data += start * stride # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride + */ + __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); + goto __pyx_L19; + } + /*else*/ { + + /* "View.MemoryView":849 + * dst.data += start * stride + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< + * + * if suboffset >= 0: + */ + __pyx_t_3 = (__pyx_v_suboffset_dim[0]); + (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); + } + __pyx_L19:; + + /* "View.MemoryView":851 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":852 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":853 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":854 + * if not is_slice: + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + */ + __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); + goto __pyx_L22; + } + /*else*/ { + + /* "View.MemoryView":856 + * dst.data = ( dst.data)[0] + suboffset + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< + * "must be indexed and not sliced", dim) + * else: + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_All_dimensions_preceding_dimensi, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 856; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L22:; + goto __pyx_L21; + } + /*else*/ { + + /* "View.MemoryView":859 + * "must be indexed and not sliced", dim) + * else: + * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< + * + * return 0 + */ + (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; + } + __pyx_L21:; + goto __pyx_L20; + } + __pyx_L20:; + + /* "View.MemoryView":861 + * suboffset_dim[0] = new_ndim + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":764 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":867 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + +static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { + Py_ssize_t __pyx_v_shape; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_suboffset; + Py_ssize_t __pyx_v_itemsize; + char *__pyx_v_resultp; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pybuffer_index", 0); + + /* "View.MemoryView":869 + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< + * cdef Py_ssize_t itemsize = view.itemsize + * cdef char *resultp + */ + __pyx_v_suboffset = -1; + + /* "View.MemoryView":870 + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< + * cdef char *resultp + * + */ + __pyx_t_1 = __pyx_v_view->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":873 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":874 + * + * if view.ndim == 0: + * shape = view.len / itemsize # <<<<<<<<<<<<<< + * stride = itemsize + * else: + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 874; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 874; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_shape = (__pyx_v_view->len / __pyx_v_itemsize); + + /* "View.MemoryView":875 + * if view.ndim == 0: + * shape = view.len / itemsize + * stride = itemsize # <<<<<<<<<<<<<< + * else: + * shape = view.shape[dim] + */ + __pyx_v_stride = __pyx_v_itemsize; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":877 + * stride = itemsize + * else: + * shape = view.shape[dim] # <<<<<<<<<<<<<< + * stride = view.strides[dim] + * if view.suboffsets != NULL: + */ + __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); + + /* "View.MemoryView":878 + * else: + * shape = view.shape[dim] + * stride = view.strides[dim] # <<<<<<<<<<<<<< + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] + */ + __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); + + /* "View.MemoryView":879 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":880 + * stride = view.strides[dim] + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< + * + * if index < 0: + */ + __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); + goto __pyx_L4; + } + __pyx_L4:; + } + __pyx_L3:; + + /* "View.MemoryView":882 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":883 + * + * if index < 0: + * index += view.shape[dim] # <<<<<<<<<<<<<< + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + */ + __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); + + /* "View.MemoryView":884 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":885 + * index += view.shape[dim] + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * if index >= shape: + */ + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":887 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":888 + * + * if index >= shape: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * resultp = bufp + index * stride + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":890 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * resultp = bufp + index * stride # <<<<<<<<<<<<<< + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset + */ + __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); + + /* "View.MemoryView":891 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":892 + * resultp = bufp + index * stride + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< + * + * return resultp + */ + __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":894 + * resultp = ( resultp)[0] + suboffset + * + * return resultp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_resultp; + goto __pyx_L0; + + /* "View.MemoryView":867 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":900 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + +static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { + int __pyx_v_ndim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + int __pyx_v_i; + int __pyx_v_j; + int __pyx_r; + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + long __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":901 + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: + * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< + * + * cdef Py_ssize_t *shape = memslice.shape + */ + __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; + __pyx_v_ndim = __pyx_t_1; + + /* "View.MemoryView":903 + * cdef int ndim = memslice.memview.view.ndim + * + * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< + * cdef Py_ssize_t *strides = memslice.strides + * + */ + __pyx_t_2 = __pyx_v_memslice->shape; + __pyx_v_shape = __pyx_t_2; + + /* "View.MemoryView":904 + * + * cdef Py_ssize_t *shape = memslice.shape + * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_v_memslice->strides; + __pyx_v_strides = __pyx_t_2; + + /* "View.MemoryView":908 + * + * cdef int i, j + * for i in range(ndim / 2): # <<<<<<<<<<<<<< + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + */ + __pyx_t_3 = (__pyx_v_ndim / 2); + for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":909 + * cdef int i, j + * for i in range(ndim / 2): + * j = ndim - 1 - i # <<<<<<<<<<<<<< + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] + */ + __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); + + /* "View.MemoryView":910 + * for i in range(ndim / 2): + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< + * shape[i], shape[j] = shape[j], shape[i] + * + */ + __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); + __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); + (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; + (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; + + /* "View.MemoryView":911 + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + */ + __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); + __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); + (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; + (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; + + /* "View.MemoryView":913 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + __pyx_t_6 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); + if (!__pyx_t_6) { + __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); + __pyx_t_8 = __pyx_t_7; + } else { + __pyx_t_8 = __pyx_t_6; + } + if (__pyx_t_8) { + + /* "View.MemoryView":914 + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< + * + * return 1 + */ + __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_Cannot_transpose_memoryview_with); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 914; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "View.MemoryView":916 + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + * return 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 1; + goto __pyx_L0; + + /* "View.MemoryView":900 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":933 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + +/* Python wrapper */ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":934 + * + * def __dealloc__(self): + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); + + /* "View.MemoryView":933 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":936 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":937 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":938 + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) # <<<<<<<<<<<<<< + * else: + * return memoryview.convert_item_to_object(self, itemp) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 938; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":940 + * return self.to_object_func(itemp) + * else: + * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_vtabptr_memoryview->convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 940; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":936 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":942 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":943 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":944 + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< + * else: + * memoryview.assign_item_from_object(self, itemp, value) + */ + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":946 + * self.to_dtype_func(itemp, value) + * else: + * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< + * + * property base: + */ + __pyx_t_3 = __pyx_vtabptr_memoryview->assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":942 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":950 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":951 + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): + * return self.from_object # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->from_object); + __pyx_r = __pyx_v_self->from_object; + goto __pyx_L0; + + /* "View.MemoryView":950 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":957 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_TypeInfo *__pyx_t_4; + Py_buffer __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_fromslice", 0); + + /* "View.MemoryView":966 + * cdef int i + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":967 + * + * if memviewslice.memview == Py_None: + * return None # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + + /* "View.MemoryView":972 + * + * + * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< + * + * result.from_slice = memviewslice + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":974 + * result = _memoryviewslice(None, 0, dtype_is_object) + * + * result.from_slice = memviewslice # <<<<<<<<<<<<<< + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + */ + __pyx_v_result->from_slice = __pyx_v_memviewslice; + + /* "View.MemoryView":975 + * + * result.from_slice = memviewslice + * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< + * + * result.from_object = ( memviewslice.memview).base + */ + __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); + + /* "View.MemoryView":977 + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< + * result.typeinfo = memviewslice.memview.typeinfo + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_result->from_object); + __Pyx_DECREF(__pyx_v_result->from_object); + __pyx_v_result->from_object = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":978 + * + * result.from_object = ( memviewslice.memview).base + * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< + * + * result.view = memviewslice.memview.view + */ + __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; + __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; + + /* "View.MemoryView":980 + * result.typeinfo = memviewslice.memview.typeinfo + * + * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + */ + __pyx_t_5 = __pyx_v_memviewslice.memview->view; + __pyx_v_result->__pyx_base.view = __pyx_t_5; + + /* "View.MemoryView":981 + * + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + */ + __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); + + /* "View.MemoryView":982 + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data + * result.view.ndim = ndim # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; + + /* "View.MemoryView":983 + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; + + /* "View.MemoryView":984 + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * result.flags = PyBUF_RECORDS + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":986 + * Py_INCREF(Py_None) + * + * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< + * + * result.view.shape = result.from_slice.shape + */ + __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; + + /* "View.MemoryView":988 + * result.flags = PyBUF_RECORDS + * + * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets + */ + __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); + + /* "View.MemoryView":989 + * + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * + */ + __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); + + /* "View.MemoryView":990 + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + * + * result.view.len = result.view.itemsize + */ + __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + + /* "View.MemoryView":992 + * result.view.suboffsets = result.from_slice.suboffsets + * + * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< + * for i in range(ndim): + * result.view.len *= result.view.shape[i] + */ + __pyx_t_6 = __pyx_v_result->__pyx_base.view.itemsize; + __pyx_v_result->__pyx_base.view.len = __pyx_t_6; + + /* "View.MemoryView":993 + * + * result.view.len = result.view.itemsize + * for i in range(ndim): # <<<<<<<<<<<<<< + * result.view.len *= result.view.shape[i] + * + */ + __pyx_t_7 = __pyx_v_ndim; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "View.MemoryView":994 + * result.view.len = result.view.itemsize + * for i in range(ndim): + * result.view.len *= result.view.shape[i] # <<<<<<<<<<<<<< + * + * result.to_object_func = to_object_func + */ + __pyx_v_result->__pyx_base.view.len = (__pyx_v_result->__pyx_base.view.len * (__pyx_v_result->__pyx_base.view.shape[__pyx_v_i])); + } + + /* "View.MemoryView":996 + * result.view.len *= result.view.shape[i] + * + * result.to_object_func = to_object_func # <<<<<<<<<<<<<< + * result.to_dtype_func = to_dtype_func + * + */ + __pyx_v_result->to_object_func = __pyx_v_to_object_func; + + /* "View.MemoryView":997 + * + * result.to_object_func = to_object_func + * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; + + /* "View.MemoryView":999 + * result.to_dtype_func = to_dtype_func + * + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":957 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1002 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { + struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; + __Pyx_memviewslice *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_slice_from_memview", 0); + + /* "View.MemoryView":1005 + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1006 + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): + * obj = memview # <<<<<<<<<<<<<< + * return &obj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":1007 + * if isinstance(memview, _memoryviewslice): + * obj = memview + * return &obj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, mslice) + */ + __pyx_r = (&__pyx_v_obj->from_slice); + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1009 + * return &obj.from_slice + * else: + * slice_copy(memview, mslice) # <<<<<<<<<<<<<< + * return mslice + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); + + /* "View.MemoryView":1010 + * else: + * slice_copy(memview, mslice) + * return mslice # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_copy') + */ + __pyx_r = __pyx_v_mslice; + goto __pyx_L0; + } + + /* "View.MemoryView":1002 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_obj); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1013 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { + int __pyx_v_dim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + Py_ssize_t *__pyx_v_suboffsets; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + __Pyx_RefNannySetupContext("slice_copy", 0); + + /* "View.MemoryView":1017 + * cdef (Py_ssize_t*) shape, strides, suboffsets + * + * shape = memview.view.shape # <<<<<<<<<<<<<< + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets + */ + __pyx_t_1 = __pyx_v_memview->view.shape; + __pyx_v_shape = __pyx_t_1; + + /* "View.MemoryView":1018 + * + * shape = memview.view.shape + * strides = memview.view.strides # <<<<<<<<<<<<<< + * suboffsets = memview.view.suboffsets + * + */ + __pyx_t_1 = __pyx_v_memview->view.strides; + __pyx_v_strides = __pyx_t_1; + + /* "View.MemoryView":1019 + * shape = memview.view.shape + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< + * + * dst.memview = <__pyx_memoryview *> memview + */ + __pyx_t_1 = __pyx_v_memview->view.suboffsets; + __pyx_v_suboffsets = __pyx_t_1; + + /* "View.MemoryView":1021 + * suboffsets = memview.view.suboffsets + * + * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< + * dst.data = memview.view.buf + * + */ + __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); + + /* "View.MemoryView":1022 + * + * dst.memview = <__pyx_memoryview *> memview + * dst.data = memview.view.buf # <<<<<<<<<<<<<< + * + * for dim in range(memview.view.ndim): + */ + __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); + + /* "View.MemoryView":1024 + * dst.data = memview.view.buf + * + * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + */ + __pyx_t_2 = __pyx_v_memview->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_dim = __pyx_t_3; + + /* "View.MemoryView":1025 + * + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + */ + (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); + + /* "View.MemoryView":1026 + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 + */ + (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); + + /* "View.MemoryView":1027 + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: # <<<<<<<<<<<<<< + * dst.suboffsets[dim] = -1 + * else: + */ + __pyx_t_4 = ((__pyx_v_suboffsets == NULL) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":1028 + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[dim] = suboffsets[dim] + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = -1; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1030 + * dst.suboffsets[dim] = -1 + * else: + * dst.suboffsets[dim] = suboffsets[dim] # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object') + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = (__pyx_v_suboffsets[__pyx_v_dim]); + } + __pyx_L5:; + } + + /* "View.MemoryView":1013 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1033 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { + __Pyx_memviewslice __pyx_v_memviewslice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy", 0); + + /* "View.MemoryView":1036 + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< + * return memoryview_copy_from_slice(memview, &memviewslice) + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); + + /* "View.MemoryView":1037 + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) + * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object_from_slice') + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1033 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1040 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { + PyObject *(*__pyx_v_to_object_func)(char *); + int (*__pyx_v_to_dtype_func)(char *, PyObject *); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *(*__pyx_t_3)(char *); + int (*__pyx_t_4)(char *, PyObject *); + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); + + /* "View.MemoryView":1047 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1048 + * + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + */ + __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; + __pyx_v_to_object_func = __pyx_t_3; + + /* "View.MemoryView":1049 + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< + * else: + * to_object_func = NULL + */ + __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; + __pyx_v_to_dtype_func = __pyx_t_4; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1051 + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + * to_object_func = NULL # <<<<<<<<<<<<<< + * to_dtype_func = NULL + * + */ + __pyx_v_to_object_func = NULL; + + /* "View.MemoryView":1052 + * else: + * to_object_func = NULL + * to_dtype_func = NULL # <<<<<<<<<<<<<< + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + */ + __pyx_v_to_dtype_func = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":1054 + * to_dtype_func = NULL + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< + * to_object_func, to_dtype_func, + * memview.dtype_is_object) + */ + __Pyx_XDECREF(__pyx_r); + + /* "View.MemoryView":1056 + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + * to_object_func, to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1040 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1062 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + +static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { + Py_ssize_t __pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":1063 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + __pyx_t_1 = ((__pyx_v_arg < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1064 + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: + * return -arg # <<<<<<<<<<<<<< + * else: + * return arg + */ + __pyx_r = (-__pyx_v_arg); + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1066 + * return -arg + * else: + * return arg # <<<<<<<<<<<<<< + * + * @cname('__pyx_get_best_slice_order') + */ + __pyx_r = __pyx_v_arg; + goto __pyx_L0; + } + + /* "View.MemoryView":1062 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1069 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + +static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_c_stride; + Py_ssize_t __pyx_v_f_stride; + char __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1074 + * """ + * cdef int i + * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t f_stride = 0 + * + */ + __pyx_v_c_stride = 0; + + /* "View.MemoryView":1075 + * cdef int i + * cdef Py_ssize_t c_stride = 0 + * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_f_stride = 0; + + /* "View.MemoryView":1077 + * cdef Py_ssize_t f_stride = 0 + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1078 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1079 + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1080 + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + goto __pyx_L4_break; + } + } + __pyx_L4_break:; + + /* "View.MemoryView":1082 + * break + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1083 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1084 + * for i in range(ndim): + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1085 + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + */ + goto __pyx_L7_break; + } + } + __pyx_L7_break:; + + /* "View.MemoryView":1087 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1088 + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + * return 'C' # <<<<<<<<<<<<<< + * else: + * return 'F' + */ + __pyx_r = 'C'; + goto __pyx_L0; + } + /*else*/ { + + /* "View.MemoryView":1090 + * return 'C' + * else: + * return 'F' # <<<<<<<<<<<<<< + * + * @cython.cdivision(True) + */ + __pyx_r = 'F'; + goto __pyx_L0; + } + + /* "View.MemoryView":1069 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1093 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + +static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; + Py_ssize_t __pyx_v_dst_extent; + Py_ssize_t __pyx_v_src_stride; + Py_ssize_t __pyx_v_dst_stride; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + + /* "View.MemoryView":1100 + * + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + */ + __pyx_v_src_extent = (__pyx_v_src_shape[0]); + + /* "View.MemoryView":1101 + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] + */ + __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); + + /* "View.MemoryView":1102 + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + */ + __pyx_v_src_stride = (__pyx_v_src_strides[0]); + + /* "View.MemoryView":1103 + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); + + /* "View.MemoryView":1105 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1106 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + __pyx_t_1 = ((__pyx_v_src_stride > 0) != 0); + if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1107 + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + */ + __pyx_t_3 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); + if (__pyx_t_3) { + __pyx_t_3 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); + } + __pyx_t_4 = (__pyx_t_3 != 0); + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = __pyx_t_1; + } + if (__pyx_t_2) { + + /* "View.MemoryView":1108 + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":1110 + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1111 + * else: + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); + + /* "View.MemoryView":1112 + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * else: + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1113 + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1115 + * dst_data += dst_stride + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * _copy_strided_to_strided(src_data, src_strides + 1, + * dst_data, dst_strides + 1, + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1116 + * else: + * for i in range(dst_extent): + * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< + * dst_data, dst_strides + 1, + * src_shape + 1, dst_shape + 1, + */ + _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); + + /* "View.MemoryView":1120 + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1121 + * ndim - 1, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1093 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + + /* function exit code */ +} + +/* "View.MemoryView":1123 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + +static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + + /* "View.MemoryView":1126 + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< + * src.shape, dst.shape, ndim, itemsize) + * + */ + _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1123 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1130 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_size; + Py_ssize_t __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1133 + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_size = __pyx_t_1; + + /* "View.MemoryView":1135 + * cdef Py_ssize_t size = src.memview.view.itemsize + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * size *= src.shape[i] + * + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1136 + * + * for i in range(ndim): + * size *= src.shape[i] # <<<<<<<<<<<<<< + * + * return size + */ + __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); + } + + /* "View.MemoryView":1138 + * size *= src.shape[i] + * + * return size # <<<<<<<<<<<<<< + * + * @cname('__pyx_fill_contig_strides_array') + */ + __pyx_r = __pyx_v_size; + goto __pyx_L0; + + /* "View.MemoryView":1130 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1141 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { + int __pyx_v_idx; + Py_ssize_t __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1150 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + __pyx_t_1 = ((__pyx_v_order == 'F') != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1151 + * + * if order == 'F': + * for idx in range(ndim): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_idx = __pyx_t_3; + + /* "View.MemoryView":1152 + * if order == 'F': + * for idx in range(ndim): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * else: + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1153 + * for idx in range(ndim): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * else: + * for idx in range(ndim - 1, -1, -1): + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1155 + * stride = stride * shape[idx] + * else: + * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { + __pyx_v_idx = __pyx_t_2; + + /* "View.MemoryView":1156 + * else: + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1157 + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * + * return stride + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + } + __pyx_L3:; + + /* "View.MemoryView":1159 + * stride = stride * shape[idx] + * + * return stride # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_data_to_temp') + */ + __pyx_r = __pyx_v_stride; + goto __pyx_L0; + + /* "View.MemoryView":1141 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1162 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { + int __pyx_v_i; + void *__pyx_v_result; + size_t __pyx_v_itemsize; + size_t __pyx_v_size; + void *__pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + struct __pyx_memoryview_obj *__pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1173 + * cdef void *result + * + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef size_t size = slice_get_size(src, ndim) + * + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1174 + * + * cdef size_t itemsize = src.memview.view.itemsize + * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< + * + * result = malloc(size) + */ + __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); + + /* "View.MemoryView":1176 + * cdef size_t size = slice_get_size(src, ndim) + * + * result = malloc(size) # <<<<<<<<<<<<<< + * if not result: + * _err(MemoryError, NULL) + */ + __pyx_v_result = malloc(__pyx_v_size); + + /* "View.MemoryView":1177 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1178 + * result = malloc(size) + * if not result: + * _err(MemoryError, NULL) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1181 + * + * + * tmpslice.data = result # <<<<<<<<<<<<<< + * tmpslice.memview = src.memview + * for i in range(ndim): + */ + __pyx_v_tmpslice->data = ((char *)__pyx_v_result); + + /* "View.MemoryView":1182 + * + * tmpslice.data = result + * tmpslice.memview = src.memview # <<<<<<<<<<<<<< + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + */ + __pyx_t_4 = __pyx_v_src->memview; + __pyx_v_tmpslice->memview = __pyx_t_4; + + /* "View.MemoryView":1183 + * tmpslice.data = result + * tmpslice.memview = src.memview + * for i in range(ndim): # <<<<<<<<<<<<<< + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1184 + * tmpslice.memview = src.memview + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< + * tmpslice.suboffsets[i] = -1 + * + */ + (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); + + /* "View.MemoryView":1185 + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + */ + (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1187 + * tmpslice.suboffsets[i] = -1 + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< + * ndim, order) + * + */ + __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); + + /* "View.MemoryView":1191 + * + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1192 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1193 + * for i in range(ndim): + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< + * + * if slice_is_contig(src, order, ndim): + */ + (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1195 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1196 + * + * if slice_is_contig(src, order, ndim): + * memcpy(result, src.data, size) # <<<<<<<<<<<<<< + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + */ + memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1198 + * memcpy(result, src.data, size) + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< + * + * return result + */ + copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); + } + __pyx_L9:; + + /* "View.MemoryView":1200 + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":1162 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = NULL; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1205 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + +static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_extents", 0); + + /* "View.MemoryView":1208 + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + * (i, extent1, extent2)) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err_dim') + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + + /* "View.MemoryView":1207 + * cdef int _err_extents(int i, Py_ssize_t extent1, + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< + * (i, extent1, extent2)) + * + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1205 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1211 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + +static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_dim", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1212 + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: + * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err') + */ + __pyx_t_1 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyUnicode_Format(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_v_error, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1211 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1215 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + +static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1216 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ + __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1217 + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: + * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< + * else: + * raise error + */ + __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_v_error, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + /*else*/ { + + /* "View.MemoryView":1219 + * raise error(msg.decode('ascii')) + * else: + * raise error # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_contents') + */ + __Pyx_Raise(__pyx_v_error, 0, 0, 0); + {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "View.MemoryView":1215 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1222 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { + void *__pyx_v_tmpdata; + size_t __pyx_v_itemsize; + int __pyx_v_i; + char __pyx_v_order; + int __pyx_v_broadcasting; + int __pyx_v_direct_copy; + __Pyx_memviewslice __pyx_v_tmp; + int __pyx_v_ndim; + int __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + void *__pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1230 + * Check for overlapping memory and verify the shapes. + * """ + * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + */ + __pyx_v_tmpdata = NULL; + + /* "View.MemoryView":1231 + * """ + * cdef void *tmpdata = NULL + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + */ + __pyx_t_1 = __pyx_v_src.memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1233 + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< + * cdef bint broadcasting = False + * cdef bint direct_copy = False + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); + + /* "View.MemoryView":1234 + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False # <<<<<<<<<<<<<< + * cdef bint direct_copy = False + * cdef __Pyx_memviewslice tmp + */ + __pyx_v_broadcasting = 0; + + /* "View.MemoryView":1235 + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False + * cdef bint direct_copy = False # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice tmp + * + */ + __pyx_v_direct_copy = 0; + + /* "View.MemoryView":1238 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ + __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1239 + * + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); + goto __pyx_L3; + } + + /* "View.MemoryView":1240 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ + __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1241 + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< + * + * cdef int ndim = max(src_ndim, dst_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1243 + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_3 = __pyx_v_dst_ndim; + __pyx_t_4 = __pyx_v_src_ndim; + if (((__pyx_t_3 > __pyx_t_4) != 0)) { + __pyx_t_5 = __pyx_t_3; + } else { + __pyx_t_5 = __pyx_t_4; + } + __pyx_v_ndim = __pyx_t_5; + + /* "View.MemoryView":1245 + * cdef int ndim = max(src_ndim, dst_ndim) + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1246 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1247 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1248 + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + * broadcasting = True # <<<<<<<<<<<<<< + * src.strides[i] = 0 + * else: + */ + __pyx_v_broadcasting = 1; + + /* "View.MemoryView":1249 + * if src.shape[i] == 1: + * broadcasting = True + * src.strides[i] = 0 # <<<<<<<<<<<<<< + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) + */ + (__pyx_v_src.strides[__pyx_v_i]) = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":1251 + * src.strides[i] = 0 + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< + * + * if src.suboffsets[i] >= 0: + */ + __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":1253 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ + __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1254 + * + * if src.suboffsets[i] >= 0: + * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< + * + * if slices_overlap(&src, &dst, ndim, itemsize): + */ + __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Dimension_d_is_not_direct, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1256 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(&src, order, ndim): + */ + __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1258 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1259 + * + * if not slice_is_contig(&src, order, ndim): + * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":1261 + * order = get_best_order(&dst, ndim) + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< + * src = tmp + * + */ + __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_tmpdata = __pyx_t_6; + + /* "View.MemoryView":1262 + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + * src = tmp # <<<<<<<<<<<<<< + * + * if not broadcasting: + */ + __pyx_v_src = __pyx_v_tmp; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":1264 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1267 + * + * + * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1268 + * + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); + goto __pyx_L12; + } + + /* "View.MemoryView":1269 + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1270 + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< + * + * if direct_copy: + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":1272 + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_2 = (__pyx_v_direct_copy != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1274 + * if direct_copy: + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1275 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) + */ + memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); + + /* "View.MemoryView":1276 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * free(tmpdata) + * return 0 + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1277 + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1278 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * if order == 'F' == get_best_order(&dst, ndim): + */ + __pyx_r = 0; + goto __pyx_L0; + } + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":1280 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = (__pyx_v_order == 'F'); + if (__pyx_t_2) { + __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); + } + __pyx_t_7 = (__pyx_t_2 != 0); + if (__pyx_t_7) { + + /* "View.MemoryView":1283 + * + * + * transpose_memslice(&src) # <<<<<<<<<<<<<< + * transpose_memslice(&dst) + * + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1284 + * + * transpose_memslice(&src) + * transpose_memslice(&dst) # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":1286 + * transpose_memslice(&dst) + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1287 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + */ + copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1288 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * free(tmpdata) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1290 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1291 + * + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_broadcast_leading') + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":1222 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1294 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice, int __pyx_v_ndim, int __pyx_v_ndim_other) { + int __pyx_v_i; + int __pyx_v_offset; + int __pyx_t_1; + int __pyx_t_2; + + /* "View.MemoryView":1298 + * int ndim_other) nogil: + * cdef int i + * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); + + /* "View.MemoryView":1300 + * cdef int offset = ndim_other - ndim + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1301 + * + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] # <<<<<<<<<<<<<< + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] + */ + (__pyx_v_slice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->shape[__pyx_v_i]); + + /* "View.MemoryView":1302 + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] # <<<<<<<<<<<<<< + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + */ + (__pyx_v_slice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->strides[__pyx_v_i]); + + /* "View.MemoryView":1303 + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] # <<<<<<<<<<<<<< + * + * for i in range(offset): + */ + (__pyx_v_slice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->suboffsets[__pyx_v_i]); + } + + /* "View.MemoryView":1305 + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + * for i in range(offset): # <<<<<<<<<<<<<< + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + */ + __pyx_t_1 = __pyx_v_offset; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1306 + * + * for i in range(offset): + * slice.shape[i] = 1 # <<<<<<<<<<<<<< + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 + */ + (__pyx_v_slice->shape[__pyx_v_i]) = 1; + + /* "View.MemoryView":1307 + * for i in range(offset): + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] # <<<<<<<<<<<<<< + * slice.suboffsets[i] = -1 + * + */ + (__pyx_v_slice->strides[__pyx_v_i]) = (__pyx_v_slice->strides[0]); + + /* "View.MemoryView":1308 + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_slice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1294 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1316 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { + int __pyx_t_1; + + /* "View.MemoryView":1320 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + __pyx_t_1 = (__pyx_v_dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1321 + * + * if dtype_is_object: + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< + * dst.strides, ndim, inc) + * + */ + __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1316 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + + /* function exit code */ +} + +/* "View.MemoryView":1325 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + __Pyx_RefNannyDeclarations + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); + + /* "View.MemoryView":1328 + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); + + /* "View.MemoryView":1325 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif +} + +/* "View.MemoryView":1331 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + +static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); + + /* "View.MemoryView":1335 + * cdef Py_ssize_t i + * + * for i in range(shape[0]): # <<<<<<<<<<<<<< + * if ndim == 1: + * if inc: + */ + __pyx_t_1 = (__pyx_v_shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1336 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1337 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + __pyx_t_3 = (__pyx_v_inc != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1338 + * if ndim == 1: + * if inc: + * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * Py_DECREF(( data)[0]) + */ + Py_INCREF((((PyObject **)__pyx_v_data)[0])); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":1340 + * Py_INCREF(( data)[0]) + * else: + * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + */ + Py_DECREF((((PyObject **)__pyx_v_data)[0])); + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1342 + * Py_DECREF(( data)[0]) + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, inc) + * + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); + } + __pyx_L5:; + + /* "View.MemoryView":1345 + * ndim - 1, inc) + * + * data += strides[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); + } + + /* "View.MemoryView":1331 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1351 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { + + /* "View.MemoryView":1354 + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1355 + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1357 + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1351 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1361 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + +static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_extent; + int __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + + /* "View.MemoryView":1365 + * size_t itemsize, void *item) nogil: + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t extent = shape[0] + * + */ + __pyx_v_stride = (__pyx_v_strides[0]); + + /* "View.MemoryView":1366 + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] + * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_extent = (__pyx_v_shape[0]); + + /* "View.MemoryView":1368 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1369 + * + * if ndim == 1: + * for i in range(extent): # <<<<<<<<<<<<<< + * memcpy(data, item, itemsize) + * data += stride + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1370 + * if ndim == 1: + * for i in range(extent): + * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< + * data += stride + * else: + */ + memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); + + /* "View.MemoryView":1371 + * for i in range(extent): + * memcpy(data, item, itemsize) + * data += stride # <<<<<<<<<<<<<< + * else: + * for i in range(extent): + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1373 + * data += stride + * else: + * for i in range(extent): # <<<<<<<<<<<<<< + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1374 + * else: + * for i in range(extent): + * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, itemsize, item) + * data += stride + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1376 + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + * data += stride # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1361 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + + /* function exit code */ +} + +/* "BufferFormatFromTypeInfo":1417 + * + * @cname('__pyx_format_from_typeinfo') + * cdef bytes format_from_typeinfo(__Pyx_TypeInfo *type): # <<<<<<<<<<<<<< + * cdef __Pyx_StructField *field + * cdef __pyx_typeinfo_string fmt + */ + +static PyObject *__pyx_format_from_typeinfo(__Pyx_TypeInfo *__pyx_v_type) { + __Pyx_StructField *__pyx_v_field; + struct __pyx_typeinfo_string __pyx_v_fmt; + PyObject *__pyx_v_part = 0; + PyObject *__pyx_v_result = 0; + PyObject *__pyx_v_alignment = NULL; + PyObject *__pyx_v_parts = NULL; + PyObject *__pyx_v_extents = NULL; + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + __Pyx_StructField *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("format_from_typeinfo", 0); + + /* "BufferFormatFromTypeInfo":1422 + * cdef bytes part, result + * + * if type.typegroup == 'S': # <<<<<<<<<<<<<< + * assert type.fields != NULL and type.fields.type != NULL + * + */ + __pyx_t_1 = ((__pyx_v_type->typegroup == 'S') != 0); + if (__pyx_t_1) { + + /* "BufferFormatFromTypeInfo":1423 + * + * if type.typegroup == 'S': + * assert type.fields != NULL and type.fields.type != NULL # <<<<<<<<<<<<<< + * + * if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT: + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + __pyx_t_1 = ((__pyx_v_type->fields != NULL) != 0); + if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_type->fields->type != NULL) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (unlikely(!__pyx_t_3)) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + + /* "BufferFormatFromTypeInfo":1425 + * assert type.fields != NULL and type.fields.type != NULL + * + * if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT: # <<<<<<<<<<<<<< + * alignment = b'^' + * else: + */ + __pyx_t_3 = ((__pyx_v_type->flags & __PYX_BUF_FLAGS_PACKED_STRUCT) != 0); + if (__pyx_t_3) { + + /* "BufferFormatFromTypeInfo":1426 + * + * if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT: + * alignment = b'^' # <<<<<<<<<<<<<< + * else: + * alignment = b'' + */ + __Pyx_INCREF(__pyx_kp_b__50); + __pyx_v_alignment = __pyx_kp_b__50; + goto __pyx_L4; + } + /*else*/ { + + /* "BufferFormatFromTypeInfo":1428 + * alignment = b'^' + * else: + * alignment = b'' # <<<<<<<<<<<<<< + * + * parts = [b"T{"] + */ + __Pyx_INCREF(__pyx_kp_b__51); + __pyx_v_alignment = __pyx_kp_b__51; + } + __pyx_L4:; + + /* "BufferFormatFromTypeInfo":1430 + * alignment = b'' + * + * parts = [b"T{"] # <<<<<<<<<<<<<< + * field = type.fields + * + */ + __pyx_t_4 = PyList_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_kp_b_T); + PyList_SET_ITEM(__pyx_t_4, 0, __pyx_kp_b_T); + __Pyx_GIVEREF(__pyx_kp_b_T); + __pyx_v_parts = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "BufferFormatFromTypeInfo":1431 + * + * parts = [b"T{"] + * field = type.fields # <<<<<<<<<<<<<< + * + * while field.type: + */ + __pyx_t_5 = __pyx_v_type->fields; + __pyx_v_field = __pyx_t_5; + + /* "BufferFormatFromTypeInfo":1433 + * field = type.fields + * + * while field.type: # <<<<<<<<<<<<<< + * part = format_from_typeinfo(field.type) + * parts.append(part + b':' + field.name + b':') + */ + while (1) { + __pyx_t_3 = (__pyx_v_field->type != 0); + if (!__pyx_t_3) break; + + /* "BufferFormatFromTypeInfo":1434 + * + * while field.type: + * part = format_from_typeinfo(field.type) # <<<<<<<<<<<<<< + * parts.append(part + b':' + field.name + b':') + * field += 1 + */ + __pyx_t_4 = __pyx_format_from_typeinfo(__pyx_v_field->type); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_part, ((PyObject*)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "BufferFormatFromTypeInfo":1435 + * while field.type: + * part = format_from_typeinfo(field.type) + * parts.append(part + b':' + field.name + b':') # <<<<<<<<<<<<<< + * field += 1 + * + */ + __pyx_t_4 = PyNumber_Add(__pyx_v_part, __pyx_kp_b__52); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_field->name); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyNumber_Add(__pyx_t_4, __pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyNumber_Add(__pyx_t_7, __pyx_kp_b__52); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = __Pyx_PyList_Append(__pyx_v_parts, __pyx_t_6); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "BufferFormatFromTypeInfo":1436 + * part = format_from_typeinfo(field.type) + * parts.append(part + b':' + field.name + b':') + * field += 1 # <<<<<<<<<<<<<< + * + * result = alignment.join(parts) + b'}' + */ + __pyx_v_field = (__pyx_v_field + 1); + } + + /* "BufferFormatFromTypeInfo":1438 + * field += 1 + * + * result = alignment.join(parts) + b'}' # <<<<<<<<<<<<<< + * else: + * fmt = __Pyx_TypeInfoToFormat(type) + */ + __pyx_t_6 = __Pyx_PyBytes_Join(__pyx_v_alignment, __pyx_v_parts); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyNumber_Add(__pyx_t_6, __pyx_kp_b__53); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_7))||((__pyx_t_7) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_7)->tp_name), 0))) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "BufferFormatFromTypeInfo":1440 + * result = alignment.join(parts) + b'}' + * else: + * fmt = __Pyx_TypeInfoToFormat(type) # <<<<<<<<<<<<<< + * if type.arraysize[0]: + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] + */ + __pyx_v_fmt = __Pyx_TypeInfoToFormat(__pyx_v_type); + + /* "BufferFormatFromTypeInfo":1441 + * else: + * fmt = __Pyx_TypeInfoToFormat(type) + * if type.arraysize[0]: # <<<<<<<<<<<<<< + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string + */ + __pyx_t_3 = ((__pyx_v_type->arraysize[0]) != 0); + if (__pyx_t_3) { + + /* "BufferFormatFromTypeInfo":1442 + * fmt = __Pyx_TypeInfoToFormat(type) + * if type.arraysize[0]: + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] # <<<<<<<<<<<<<< + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string + * else: + */ + __pyx_t_7 = PyList_New(0); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = __pyx_v_type->ndim; + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { + __pyx_v_i = __pyx_t_10; + __pyx_t_6 = __Pyx_PyInt_FromSize_t((__pyx_v_type->arraysize[__pyx_v_i])); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PyUnicode_Type))), __pyx_t_4, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(__Pyx_ListComp_Append(__pyx_t_7, (PyObject*)__pyx_t_6))) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __pyx_v_extents = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + + /* "BufferFormatFromTypeInfo":1443 + * if type.arraysize[0]: + * extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string # <<<<<<<<<<<<<< + * else: + * result = fmt.string + */ + __pyx_t_7 = PyUnicode_Join(__pyx_kp_u__54, __pyx_v_extents); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_s, __pyx_t_7); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyUnicode_AsASCIIString(((PyObject*)__pyx_t_6)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_fmt.string); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = PyNumber_Add(__pyx_t_7, __pyx_t_6); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "BufferFormatFromTypeInfo":1445 + * result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string + * else: + * result = fmt.string # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_fmt.string); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 1445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_result = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + } + __pyx_L7:; + } + __pyx_L3:; + + /* "BufferFormatFromTypeInfo":1447 + * result = fmt.string + * + * return result # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "BufferFormatFromTypeInfo":1417 + * + * @cname('__pyx_format_from_typeinfo') + * cdef bytes format_from_typeinfo(__Pyx_TypeInfo *type): # <<<<<<<<<<<<<< + * cdef __Pyx_StructField *field + * cdef __pyx_typeinfo_string fmt + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("BufferFormatFromTypeInfo.format_from_typeinfo", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_part); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_alignment); + __Pyx_XDECREF(__pyx_v_parts); + __Pyx_XDECREF(__pyx_v_extents); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NeighborsHeap __pyx_vtable_7sklearn_9neighbors_7kd_tree_NeighborsHeap; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_7kd_tree_NeighborsHeap(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_9neighbors_7kd_tree_NeighborsHeap; + p->distances_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->indices_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->distances.data = NULL; + p->distances.memview = NULL; + p->indices.data = NULL; + p->indices.memview = NULL; + if (unlikely(__pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_1__cinit__(o, __pyx_empty_tuple, NULL) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_9neighbors_7kd_tree_NeighborsHeap(PyObject *o) { + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *p = (struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->distances_arr); + Py_CLEAR(p->indices_arr); + __PYX_XDEC_MEMVIEW(&p->distances, 1); + __PYX_XDEC_MEMVIEW(&p->indices, 1); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_7sklearn_9neighbors_7kd_tree_NeighborsHeap(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *p = (struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)o; + if (p->distances_arr) { + e = (*v)(((PyObject*)p->distances_arr), a); if (e) return e; + } + if (p->indices_arr) { + e = (*v)(((PyObject*)p->indices_arr), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_7sklearn_9neighbors_7kd_tree_NeighborsHeap(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *p = (struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *)o; + tmp = ((PyObject*)p->distances_arr); + p->distances_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->indices_arr); + p->indices_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_7kd_tree_NeighborsHeap[] = { + {__Pyx_NAMESTR("get_arrays"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_5get_arrays, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_4get_arrays)}, + {__Pyx_NAMESTR("push"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_7push, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_6push)}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_7kd_tree_NeighborsHeap = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.kd_tree.NeighborsHeap"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_7kd_tree_NeighborsHeap, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("A max-heap structure to keep track of distances/indices of neighbors\n\n This implements an efficient pre-allocated set of fixed-size heaps\n for chasing neighbors, holding both an index and a distance.\n When any row of the heap is full, adding an additional point will push\n the furthest point off the heap.\n\n Parameters\n ----------\n n_pts : int\n the number of heaps to use\n n_nbrs : int\n the size of each heap.\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_7kd_tree_NeighborsHeap, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_7kd_tree_NeighborsHeap, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_7kd_tree_NeighborsHeap, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_3__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_7kd_tree_NeighborsHeap, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_NodeHeap __pyx_vtable_7sklearn_9neighbors_7kd_tree_NodeHeap; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_7kd_tree_NodeHeap(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_9neighbors_7kd_tree_NodeHeap; + p->data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->data.data = NULL; + p->data.memview = NULL; + if (unlikely(__pyx_pw_7sklearn_9neighbors_7kd_tree_8NodeHeap_1__cinit__(o, __pyx_empty_tuple, NULL) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_9neighbors_7kd_tree_NodeHeap(PyObject *o) { + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *p = (struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->data_arr); + __PYX_XDEC_MEMVIEW(&p->data, 1); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_7sklearn_9neighbors_7kd_tree_NodeHeap(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *p = (struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *)o; + if (p->data_arr) { + e = (*v)(((PyObject*)p->data_arr), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_7sklearn_9neighbors_7kd_tree_NodeHeap(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *p = (struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *)o; + tmp = ((PyObject*)p->data_arr); + p->data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_7kd_tree_NodeHeap[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_7kd_tree_NodeHeap = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.kd_tree.NodeHeap"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_7kd_tree_NodeHeap, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("NodeHeap\n\n This is a min-heap implementation for keeping track of nodes\n during a breadth-first search. Unlike the NeighborsHeap above,\n the NodeHeap does not have a fixed size and must be able to grow\n as elements are added.\n\n Internally, the data is stored in a simple binary heap which meets\n the min heap condition:\n\n heap[i].val < min(heap[2 * i + 1].val, heap[2 * i + 2].val)\n "), /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_7kd_tree_NodeHeap, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_7kd_tree_NodeHeap, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_7kd_tree_NodeHeap, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_7kd_tree_8NodeHeap_3__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_7kd_tree_NodeHeap, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_7kd_tree_BinaryTree(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_9neighbors_7kd_tree_BinaryTree; + p->data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->idx_array_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->node_data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->node_bounds_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + p->dist_metric = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)Py_None); Py_INCREF(Py_None); + p->data.data = NULL; + p->data.memview = NULL; + p->idx_array.data = NULL; + p->idx_array.memview = NULL; + p->node_data.data = NULL; + p->node_data.memview = NULL; + p->node_bounds.data = NULL; + p->node_bounds.memview = NULL; + if (unlikely(__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_1__cinit__(o, __pyx_empty_tuple, NULL) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_9neighbors_7kd_tree_BinaryTree(PyObject *o) { + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *p = (struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->data_arr); + Py_CLEAR(p->idx_array_arr); + Py_CLEAR(p->node_data_arr); + Py_CLEAR(p->node_bounds_arr); + Py_CLEAR(p->dist_metric); + __PYX_XDEC_MEMVIEW(&p->data, 1); + __PYX_XDEC_MEMVIEW(&p->idx_array, 1); + __PYX_XDEC_MEMVIEW(&p->node_data, 1); + __PYX_XDEC_MEMVIEW(&p->node_bounds, 1); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_7sklearn_9neighbors_7kd_tree_BinaryTree(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *p = (struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)o; + if (p->data_arr) { + e = (*v)(((PyObject*)p->data_arr), a); if (e) return e; + } + if (p->idx_array_arr) { + e = (*v)(((PyObject*)p->idx_array_arr), a); if (e) return e; + } + if (p->node_data_arr) { + e = (*v)(((PyObject*)p->node_data_arr), a); if (e) return e; + } + if (p->node_bounds_arr) { + e = (*v)(((PyObject*)p->node_bounds_arr), a); if (e) return e; + } + if (p->dist_metric) { + e = (*v)(((PyObject*)p->dist_metric), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_7sklearn_9neighbors_7kd_tree_BinaryTree(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *p = (struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *)o; + tmp = ((PyObject*)p->data_arr); + p->data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->idx_array_arr); + p->idx_array_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->node_data_arr); + p->node_data_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->node_bounds_arr); + p->node_bounds_arr = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->dist_metric); + p->dist_metric = ((struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyObject *__pyx_getprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_data(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_4data_1__get__(o); +} + +static PyObject *__pyx_getprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_idx_array(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array_1__get__(o); +} + +static int __pyx_setprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_idx_array(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9idx_array_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_node_data(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data_1__get__(o); +} + +static int __pyx_setprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_node_data(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9node_data_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_node_bounds(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds_1__get__(o); +} + +static int __pyx_setprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_node_bounds(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_11node_bounds_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyMethodDef __pyx_methods_7sklearn_9neighbors_7kd_tree_BinaryTree[] = { + {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_5__reduce__, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_4__reduce__)}, + {__Pyx_NAMESTR("__getstate__"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_7__getstate__, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_6__getstate__)}, + {__Pyx_NAMESTR("__setstate__"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_9__setstate__, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_8__setstate__)}, + {__Pyx_NAMESTR("get_tree_stats"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_11get_tree_stats, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("reset_n_calls"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_13reset_n_calls, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("get_n_calls"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_15get_n_calls, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("get_arrays"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_17get_arrays, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("query"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_19query, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_18query)}, + {__Pyx_NAMESTR("query_radius"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_21query_radius, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_20query_radius)}, + {__Pyx_NAMESTR("kernel_density"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_23kernel_density, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_22kernel_density)}, + {__Pyx_NAMESTR("two_point_correlation"), (PyCFunction)__pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_25two_point_correlation, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_9neighbors_7kd_tree_10BinaryTree_24two_point_correlation)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_7sklearn_9neighbors_7kd_tree_BinaryTree[] = { + {(char *)"data", __pyx_getprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_data, 0, 0, 0}, + {(char *)"idx_array", __pyx_getprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_idx_array, __pyx_setprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_idx_array, 0, 0}, + {(char *)"node_data", __pyx_getprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_node_data, __pyx_setprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_node_data, 0, 0}, + {(char *)"node_bounds", __pyx_getprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_node_bounds, __pyx_setprop_7sklearn_9neighbors_7kd_tree_10BinaryTree_node_bounds, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_9neighbors_7kd_tree_BinaryTree = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.kd_tree.BinaryTree"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_7kd_tree_BinaryTree, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_7kd_tree_BinaryTree, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_7kd_tree_BinaryTree, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_9neighbors_7kd_tree_BinaryTree, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_7sklearn_9neighbors_7kd_tree_BinaryTree, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_3__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_7kd_tree_BinaryTree, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_KDTree __pyx_vtable_7sklearn_9neighbors_7kd_tree_KDTree; + +static PyObject *__pyx_tp_new_7sklearn_9neighbors_7kd_tree_KDTree(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_9neighbors_7kd_tree_KDTree *p; + PyObject *o = __pyx_tp_new_7sklearn_9neighbors_7kd_tree_BinaryTree(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_9neighbors_7kd_tree_KDTree *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_9neighbors_7kd_tree_BinaryTree*)__pyx_vtabptr_7sklearn_9neighbors_7kd_tree_KDTree; + return o; +} + +static PyTypeObject __pyx_type_7sklearn_9neighbors_7kd_tree_KDTree = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.kd_tree.KDTree"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_KDTree), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_9neighbors_7kd_tree_BinaryTree, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_7sklearn_9neighbors_7kd_tree_BinaryTree, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_9neighbors_7kd_tree_BinaryTree, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_pw_7sklearn_9neighbors_7kd_tree_10BinaryTree_3__init__, /*tp_init*/ + #else + 0, /*tp_init*/ + #endif + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_9neighbors_7kd_tree_KDTree, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_array_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_array_obj *)o); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_array___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->mode); + Py_CLEAR(p->_format); + (*Py_TYPE(o)->tp_free)(o); +} +static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_array___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { + PyObject *v = PyObject_GenericGetAttr(o, n); + if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + v = __pyx_array___getattr__(o, n); + } + return v; +} + +static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { + return get_memview(o); +} + +static PyMethodDef __pyx_methods_array[] = { + {__Pyx_NAMESTR("__getattr__"), (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_array[] = { + {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_array = { + 0, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_array, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_array = { + 0, /*mp_length*/ + __pyx_array___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_array = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_array_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_array = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.kd_tree.array"), /*tp_name*/ + sizeof(struct __pyx_array_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_array, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + __pyx_tp_getattro_array, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_array, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_array, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_array, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_MemviewEnum_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_MemviewEnum_obj *)o); + p->name = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->name); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + if (p->name) { + e = (*v)(p->name, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_Enum(PyObject *o) { + PyObject* tmp; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + tmp = ((PyObject*)p->name); + p->name = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_Enum[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_MemviewEnum = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.kd_tree.Enum"), /*tp_name*/ + sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_Enum, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_MemviewEnum___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_Enum, /*tp_traverse*/ + __pyx_tp_clear_Enum, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_Enum, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_MemviewEnum___init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_Enum, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; + +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryview_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryview_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_memoryview; + p->obj = Py_None; Py_INCREF(Py_None); + p->_size = Py_None; Py_INCREF(Py_None); + p->_array_interface = Py_None; Py_INCREF(Py_None); + p->view.obj = NULL; + if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryview___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->obj); + Py_CLEAR(p->_size); + Py_CLEAR(p->_array_interface); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + if (p->obj) { + e = (*v)(p->obj, a); if (e) return e; + } + if (p->_size) { + e = (*v)(p->_size, a); if (e) return e; + } + if (p->_array_interface) { + e = (*v)(p->_array_interface, a); if (e) return e; + } + if (p->view.obj) { + e = (*v)(p->view.obj, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_memoryview(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + tmp = ((PyObject*)p->obj); + p->obj = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_size); + p->_size = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_array_interface); + p->_array_interface = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + Py_CLEAR(p->view.obj); + return 0; +} +static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_memoryview___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_transpose(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview__get__base(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_shape(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_strides(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_suboffsets(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_ndim(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_itemsize(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_nbytes(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_size(o); +} + +static PyMethodDef __pyx_methods_memoryview[] = { + {__Pyx_NAMESTR("is_c_contig"), (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("is_f_contig"), (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy"), (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy_fortran"), (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_memoryview[] = { + {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, + {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, + {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, + {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, + {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, + {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, + {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, + {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_memoryview = { + __pyx_memoryview___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_memoryview, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_memoryview = { + __pyx_memoryview___len__, /*mp_length*/ + __pyx_memoryview___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_memoryview = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_memoryview_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_memoryview = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.kd_tree.memoryview"), /*tp_name*/ + sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_memoryview___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_memoryview___str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_memoryview, /*tp_traverse*/ + __pyx_tp_clear_memoryview, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_memoryview, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_memoryview, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_memoryview, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; + +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryviewslice_obj *p; + PyObject *o = __pyx_tp_new_memoryview(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryviewslice_obj *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; + p->from_object = Py_None; Py_INCREF(Py_None); + p->from_slice.memview = NULL; + return o; +} + +static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryviewslice___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->from_object); + PyObject_GC_Track(o); + __pyx_tp_dealloc_memoryview(o); +} + +static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; + if (p->from_object) { + e = (*v)(p->from_object, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear__memoryviewslice(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + __pyx_tp_clear_memoryview(o); + tmp = ((PyObject*)p->from_object); + p->from_object = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + __PYX_XDEC_MEMVIEW(&p->from_slice, 1); + return 0; +} + +static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryviewslice__get__base(o); +} + +static PyMethodDef __pyx_methods__memoryviewslice[] = { + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { + {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_memoryviewslice = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.neighbors.kd_tree._memoryviewslice"), /*tp_name*/ + sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___repr__, /*tp_repr*/ + #else + 0, /*tp_repr*/ + #endif + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___str__, /*tp_str*/ + #else + 0, /*tp_str*/ + #endif + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Internal class for passing memoryview slices to Python"), /*tp_doc*/ + __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ + __pyx_tp_clear__memoryviewslice, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods__memoryviewslice, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets__memoryviewslice, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new__memoryviewslice, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + __Pyx_NAMESTR("kd_tree"), + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_n_s_BinaryTree, __pyx_k_BinaryTree, sizeof(__pyx_k_BinaryTree), 0, 0, 1, 1}, + {&__pyx_kp_s_BinaryTree_for_fast_generalized, __pyx_k_BinaryTree_for_fast_generalized, sizeof(__pyx_k_BinaryTree_for_fast_generalized), 0, 0, 1, 0}, + {&__pyx_kp_u_BinaryTree_kernel_density_line_1, __pyx_k_BinaryTree_kernel_density_line_1, sizeof(__pyx_k_BinaryTree_kernel_density_line_1), 0, 1, 0, 0}, + {&__pyx_kp_u_BinaryTree_query_line_1228, __pyx_k_BinaryTree_query_line_1228, sizeof(__pyx_k_BinaryTree_query_line_1228), 0, 1, 0, 0}, + {&__pyx_kp_u_BinaryTree_query_radius_line_135, __pyx_k_BinaryTree_query_radius_line_135, sizeof(__pyx_k_BinaryTree_query_radius_line_135), 0, 1, 0, 0}, + {&__pyx_kp_u_BinaryTree_two_point_correlation, __pyx_k_BinaryTree_two_point_correlation, sizeof(__pyx_k_BinaryTree_two_point_correlation), 0, 1, 0, 0}, + {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, + {&__pyx_n_s_C, __pyx_k_C, sizeof(__pyx_k_C), 0, 0, 1, 1}, + {&__pyx_n_s_CLASS_DOC, __pyx_k_CLASS_DOC, sizeof(__pyx_k_CLASS_DOC), 0, 0, 1, 1}, + {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, + {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, + {&__pyx_n_s_ChebyshevDistance, __pyx_k_ChebyshevDistance, sizeof(__pyx_k_ChebyshevDistance), 0, 0, 1, 1}, + {&__pyx_kp_u_Compute_the_two_point_correlatio, __pyx_k_Compute_the_two_point_correlatio, sizeof(__pyx_k_Compute_the_two_point_correlatio), 0, 1, 0, 0}, + {&__pyx_n_s_DOC_DICT, __pyx_k_DOC_DICT, sizeof(__pyx_k_DOC_DICT), 0, 0, 1, 1}, + {&__pyx_n_s_DTYPE, __pyx_k_DTYPE, sizeof(__pyx_k_DTYPE), 0, 0, 1, 1}, + {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, + {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, + {&__pyx_n_s_EuclideanDistance, __pyx_k_EuclideanDistance, sizeof(__pyx_k_EuclideanDistance), 0, 0, 1, 1}, + {&__pyx_kp_s_Fatal_count_out_of_range_This_sh, __pyx_k_Fatal_count_out_of_range_This_sh, sizeof(__pyx_k_Fatal_count_out_of_range_This_sh), 0, 0, 1, 0}, + {&__pyx_kp_s_Fatal_count_too_big_this_should, __pyx_k_Fatal_count_too_big_this_should, sizeof(__pyx_k_Fatal_count_too_big_this_should), 0, 0, 1, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_n_s_ITYPE, __pyx_k_ITYPE, sizeof(__pyx_k_ITYPE), 0, 0, 1, 1}, + {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, + {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, + {&__pyx_kp_s_Internal_memory_layout_is_flawed, __pyx_k_Internal_memory_layout_is_flawed, sizeof(__pyx_k_Internal_memory_layout_is_flawed), 0, 0, 1, 0}, + {&__pyx_kp_s_Internal_memory_layout_is_flawed_2, __pyx_k_Internal_memory_layout_is_flawed_2, sizeof(__pyx_k_Internal_memory_layout_is_flawed_2), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, + {&__pyx_n_s_KDTree, __pyx_k_KDTree, sizeof(__pyx_k_KDTree), 0, 0, 1, 1}, + {&__pyx_kp_s_Kernel_code_not_recognized, __pyx_k_Kernel_code_not_recognized, sizeof(__pyx_k_Kernel_code_not_recognized), 0, 0, 1, 0}, + {&__pyx_n_s_ManhattanDistance, __pyx_k_ManhattanDistance, sizeof(__pyx_k_ManhattanDistance), 0, 0, 1, 1}, + {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, + {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, + {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, + {&__pyx_n_s_MinkowskiDistance, __pyx_k_MinkowskiDistance, sizeof(__pyx_k_MinkowskiDistance), 0, 0, 1, 1}, + {&__pyx_n_s_NodeData, __pyx_k_NodeData, sizeof(__pyx_k_NodeData), 0, 0, 1, 1}, + {&__pyx_n_s_NodeHeapData, __pyx_k_NodeHeapData, sizeof(__pyx_k_NodeHeapData), 0, 0, 1, 1}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, + {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_kp_b_T, __pyx_k_T, sizeof(__pyx_k_T), 0, 0, 0, 0}, + {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, + {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, + {&__pyx_n_s_VALID_METRICS, __pyx_k_VALID_METRICS, sizeof(__pyx_k_VALID_METRICS), 0, 0, 1, 1}, + {&__pyx_n_s_VALID_METRIC_IDS, __pyx_k_VALID_METRIC_IDS, sizeof(__pyx_k_VALID_METRIC_IDS), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_kp_s_X_is_an_empty_array, __pyx_k_X_is_an_empty_array, sizeof(__pyx_k_X_is_an_empty_array), 0, 0, 1, 0}, + {&__pyx_kp_b__50, __pyx_k__50, sizeof(__pyx_k__50), 0, 0, 0, 0}, + {&__pyx_kp_b__51, __pyx_k__51, sizeof(__pyx_k__51), 0, 0, 0, 0}, + {&__pyx_kp_b__52, __pyx_k__52, sizeof(__pyx_k__52), 0, 0, 0, 0}, + {&__pyx_kp_b__53, __pyx_k__53, sizeof(__pyx_k__53), 0, 0, 0, 0}, + {&__pyx_kp_u__54, __pyx_k__54, sizeof(__pyx_k__54), 0, 1, 0, 0}, + {&__pyx_n_s_all, __pyx_k_all, sizeof(__pyx_k_all), 0, 0, 1, 1}, + {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, + {&__pyx_n_s_arange, __pyx_k_arange, sizeof(__pyx_k_arange), 0, 0, 1, 1}, + {&__pyx_n_s_argsort, __pyx_k_argsort, sizeof(__pyx_k_argsort), 0, 0, 1, 1}, + {&__pyx_n_s_asarray, __pyx_k_asarray, sizeof(__pyx_k_asarray), 0, 0, 1, 1}, + {&__pyx_n_s_atleast_1d, __pyx_k_atleast_1d, sizeof(__pyx_k_atleast_1d), 0, 0, 1, 1}, + {&__pyx_n_s_atol, __pyx_k_atol, sizeof(__pyx_k_atol), 0, 0, 1, 1}, + {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, + {&__pyx_n_s_binary_tree, __pyx_k_binary_tree, sizeof(__pyx_k_binary_tree), 0, 0, 1, 1}, + {&__pyx_n_s_breadth_first, __pyx_k_breadth_first, sizeof(__pyx_k_breadth_first), 0, 0, 1, 1}, + {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, + {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, + {&__pyx_kp_s_cannot_pop_on_empty_heap, __pyx_k_cannot_pop_on_empty_heap, sizeof(__pyx_k_cannot_pop_on_empty_heap), 0, 0, 1, 0}, + {&__pyx_n_s_check_array, __pyx_k_check_array, sizeof(__pyx_k_check_array), 0, 0, 1, 1}, + {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, + {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_copy, __pyx_k_copy, sizeof(__pyx_k_copy), 0, 0, 1, 1}, + {&__pyx_n_s_cosine, __pyx_k_cosine, sizeof(__pyx_k_cosine), 0, 0, 1, 1}, + {&__pyx_n_s_count_only, __pyx_k_count_only, sizeof(__pyx_k_count_only), 0, 0, 1, 1}, + {&__pyx_kp_s_count_only_and_return_distance_c, __pyx_k_count_only_and_return_distance_c, sizeof(__pyx_k_count_only_and_return_distance_c), 0, 0, 1, 0}, + {&__pyx_n_s_d, __pyx_k_d, sizeof(__pyx_k_d), 0, 0, 1, 1}, + {&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1}, + {&__pyx_n_s_dist_metrics, __pyx_k_dist_metrics, sizeof(__pyx_k_dist_metrics), 0, 0, 1, 1}, + {&__pyx_n_s_distances, __pyx_k_distances, sizeof(__pyx_k_distances), 0, 0, 1, 1}, + {&__pyx_n_s_doc, __pyx_k_doc, sizeof(__pyx_k_doc), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, + {&__pyx_n_s_dualtree, __pyx_k_dualtree, sizeof(__pyx_k_dualtree), 0, 0, 1, 1}, + {&__pyx_n_s_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 0, 0, 1, 1}, + {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, + {&__pyx_n_s_epanechnikov, __pyx_k_epanechnikov, sizeof(__pyx_k_epanechnikov), 0, 0, 1, 1}, + {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, + {&__pyx_n_s_exp, __pyx_k_exp, sizeof(__pyx_k_exp), 0, 0, 1, 1}, + {&__pyx_n_s_exponential, __pyx_k_exponential, sizeof(__pyx_k_exponential), 0, 0, 1, 1}, + {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, + {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, + {&__pyx_n_s_formats, __pyx_k_formats, sizeof(__pyx_k_formats), 0, 0, 1, 1}, + {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, + {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, + {&__pyx_n_s_gaussian, __pyx_k_gaussian, sizeof(__pyx_k_gaussian), 0, 0, 1, 1}, + {&__pyx_n_s_get_arrays, __pyx_k_get_arrays, sizeof(__pyx_k_get_arrays), 0, 0, 1, 1}, + {&__pyx_n_s_get_metric, __pyx_k_get_metric, sizeof(__pyx_k_get_metric), 0, 0, 1, 1}, + {&__pyx_n_s_get_valid_metric_ids, __pyx_k_get_valid_metric_ids, sizeof(__pyx_k_get_valid_metric_ids), 0, 0, 1, 1}, + {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, + {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, + {&__pyx_n_s_h, __pyx_k_h, sizeof(__pyx_k_h), 0, 0, 1, 1}, + {&__pyx_n_s_heap, __pyx_k_heap, sizeof(__pyx_k_heap), 0, 0, 1, 1}, + {&__pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_k_home_manoj_scikit_learn_sklearn, sizeof(__pyx_k_home_manoj_scikit_learn_sklearn), 0, 0, 1, 0}, + {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, + {&__pyx_n_s_i1, __pyx_k_i1, sizeof(__pyx_k_i1), 0, 0, 1, 1}, + {&__pyx_n_s_i2, __pyx_k_i2, sizeof(__pyx_k_i2), 0, 0, 1, 1}, + {&__pyx_n_s_i_val, __pyx_k_i_val, sizeof(__pyx_k_i_val), 0, 0, 1, 1}, + {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, + {&__pyx_n_s_idx_end, __pyx_k_idx_end, sizeof(__pyx_k_idx_end), 0, 0, 1, 1}, + {&__pyx_n_s_idx_start, __pyx_k_idx_start, sizeof(__pyx_k_idx_start), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_indices, __pyx_k_indices, sizeof(__pyx_k_indices), 0, 0, 1, 1}, + {&__pyx_n_s_inf, __pyx_k_inf, sizeof(__pyx_k_inf), 0, 0, 1, 1}, + {&__pyx_n_s_is_leaf, __pyx_k_is_leaf, sizeof(__pyx_k_is_leaf), 0, 0, 1, 1}, + {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, + {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, + {&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, + {&__pyx_n_s_join, __pyx_k_join, sizeof(__pyx_k_join), 0, 0, 1, 1}, + {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1}, + {&__pyx_kp_s_k_must_be_less_than_or_equal_to, __pyx_k_k_must_be_less_than_or_equal_to, sizeof(__pyx_k_k_must_be_less_than_or_equal_to), 0, 0, 1, 0}, + {&__pyx_n_s_kd_tree, __pyx_k_kd_tree, sizeof(__pyx_k_kd_tree), 0, 0, 1, 1}, + {&__pyx_n_s_kernel, __pyx_k_kernel, sizeof(__pyx_k_kernel), 0, 0, 1, 1}, + {&__pyx_kp_u_kernel_density_self_X_h_kernel, __pyx_k_kernel_density_self_X_h_kernel, sizeof(__pyx_k_kernel_density_self_X_h_kernel), 0, 1, 0, 0}, + {&__pyx_n_s_kernel_norm, __pyx_k_kernel_norm, sizeof(__pyx_k_kernel_norm), 0, 0, 1, 1}, + {&__pyx_kp_s_kernel_not_recognized, __pyx_k_kernel_not_recognized, sizeof(__pyx_k_kernel_not_recognized), 0, 0, 1, 0}, + {&__pyx_kp_s_kernel_s_not_recognized, __pyx_k_kernel_s_not_recognized, sizeof(__pyx_k_kernel_s_not_recognized), 0, 0, 1, 0}, + {&__pyx_n_s_leaf_size, __pyx_k_leaf_size, sizeof(__pyx_k_leaf_size), 0, 0, 1, 1}, + {&__pyx_kp_s_leaf_size_must_be_greater_than_o, __pyx_k_leaf_size_must_be_greater_than_o, sizeof(__pyx_k_leaf_size_must_be_greater_than_o), 0, 0, 1, 0}, + {&__pyx_n_s_linear, __pyx_k_linear, sizeof(__pyx_k_linear), 0, 0, 1, 1}, + {&__pyx_n_s_load_heap, __pyx_k_load_heap, sizeof(__pyx_k_load_heap), 0, 0, 1, 1}, + {&__pyx_n_s_log2, __pyx_k_log2, sizeof(__pyx_k_log2), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, + {&__pyx_n_s_metric, __pyx_k_metric, sizeof(__pyx_k_metric), 0, 0, 1, 1}, + {&__pyx_kp_s_metric_metric_is_not_valid_for_B, __pyx_k_metric_metric_is_not_valid_for_B, sizeof(__pyx_k_metric_metric_is_not_valid_for_B), 0, 0, 1, 0}, + {&__pyx_n_s_minkowski, __pyx_k_minkowski, sizeof(__pyx_k_minkowski), 0, 0, 1, 1}, + {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, + {&__pyx_n_s_n_nbrs, __pyx_k_n_nbrs, sizeof(__pyx_k_n_nbrs), 0, 0, 1, 1}, + {&__pyx_n_s_n_pts, __pyx_k_n_pts, sizeof(__pyx_k_n_pts), 0, 0, 1, 1}, + {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, + {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, + {&__pyx_n_s_names, __pyx_k_names, sizeof(__pyx_k_names), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, + {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, + {&__pyx_n_s_newObj, __pyx_k_newObj, sizeof(__pyx_k_newObj), 0, 0, 1, 1}, + {&__pyx_n_s_node_data, __pyx_k_node_data, sizeof(__pyx_k_node_data), 0, 0, 1, 1}, + {&__pyx_n_s_nodeheap_sort, __pyx_k_nodeheap_sort, sizeof(__pyx_k_nodeheap_sort), 0, 0, 1, 1}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, + {&__pyx_n_s_object, __pyx_k_object, sizeof(__pyx_k_object), 0, 0, 1, 1}, + {&__pyx_n_s_offsets, __pyx_k_offsets, sizeof(__pyx_k_offsets), 0, 0, 1, 1}, + {&__pyx_n_s_order, __pyx_k_order, sizeof(__pyx_k_order), 0, 0, 1, 1}, + {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, + {&__pyx_n_s_pi, __pyx_k_pi, sizeof(__pyx_k_pi), 0, 0, 1, 1}, + {&__pyx_n_s_push, __pyx_k_push, sizeof(__pyx_k_push), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_releasebuffer, __pyx_k_pyx_releasebuffer, sizeof(__pyx_k_pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_kp_u_query_X_k_1_return_distance_Tru, __pyx_k_query_X_k_1_return_distance_Tru, sizeof(__pyx_k_query_X_k_1_return_distance_Tru), 0, 1, 0, 0}, + {&__pyx_kp_s_query_data_dimension_must_match, __pyx_k_query_data_dimension_must_match, sizeof(__pyx_k_query_data_dimension_must_match), 0, 0, 1, 0}, + {&__pyx_kp_u_query_radius_self_X_r_count_onl, __pyx_k_query_radius_self_X_r_count_onl, sizeof(__pyx_k_query_radius_self_X_r_count_onl), 0, 1, 0, 0}, + {&__pyx_n_s_r, __pyx_k_r, sizeof(__pyx_k_r), 0, 0, 1, 1}, + {&__pyx_kp_s_r_must_be_a_1_dimensional_array, __pyx_k_r_must_be_a_1_dimensional_array, sizeof(__pyx_k_r_must_be_a_1_dimensional_array), 0, 0, 1, 0}, + {&__pyx_kp_s_r_must_be_broadcastable_to_X_sha, __pyx_k_r_must_be_broadcastable_to_X_sha, sizeof(__pyx_k_r_must_be_broadcastable_to_X_sha), 0, 0, 1, 0}, + {&__pyx_n_s_radius, __pyx_k_radius, sizeof(__pyx_k_radius), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_rdist_to_dist, __pyx_k_rdist_to_dist, sizeof(__pyx_k_rdist_to_dist), 0, 0, 1, 1}, + {&__pyx_n_s_reshape, __pyx_k_reshape, sizeof(__pyx_k_reshape), 0, 0, 1, 1}, + {&__pyx_n_s_result, __pyx_k_result, sizeof(__pyx_k_result), 0, 0, 1, 1}, + {&__pyx_n_s_return_distance, __pyx_k_return_distance, sizeof(__pyx_k_return_distance), 0, 0, 1, 1}, + {&__pyx_kp_s_return_distance_must_be_True_if, __pyx_k_return_distance_must_be_True_if, sizeof(__pyx_k_return_distance_must_be_True_if), 0, 0, 1, 0}, + {&__pyx_n_s_return_log, __pyx_k_return_log, sizeof(__pyx_k_return_log), 0, 0, 1, 1}, + {&__pyx_n_s_row, __pyx_k_row, sizeof(__pyx_k_row), 0, 0, 1, 1}, + {&__pyx_n_s_rtol, __pyx_k_rtol, sizeof(__pyx_k_rtol), 0, 0, 1, 1}, + {&__pyx_kp_u_s, __pyx_k_s, sizeof(__pyx_k_s), 0, 1, 0, 0}, + {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, + {&__pyx_n_s_simultaneous_sort, __pyx_k_simultaneous_sort, sizeof(__pyx_k_simultaneous_sort), 0, 0, 1, 1}, + {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, + {&__pyx_n_s_size_guess, __pyx_k_size_guess, sizeof(__pyx_k_size_guess), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_neighbors_kd_tree, __pyx_k_sklearn_neighbors_kd_tree, sizeof(__pyx_k_sklearn_neighbors_kd_tree), 0, 0, 1, 1}, + {&__pyx_n_s_sort, __pyx_k_sort, sizeof(__pyx_k_sort), 0, 0, 1, 1}, + {&__pyx_n_s_sort_results, __pyx_k_sort_results, sizeof(__pyx_k_sort_results), 0, 0, 1, 1}, + {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, + {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, + {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, + {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_tophat, __pyx_k_tophat, sizeof(__pyx_k_tophat), 0, 0, 1, 1}, + {&__pyx_n_s_typedefs, __pyx_k_typedefs, sizeof(__pyx_k_typedefs), 0, 0, 1, 1}, + {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, + {&__pyx_kp_s_unable_to_allocate_shape_and_str, __pyx_k_unable_to_allocate_shape_and_str, sizeof(__pyx_k_unable_to_allocate_shape_and_str), 0, 0, 1, 0}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, + {&__pyx_n_s_utils, __pyx_k_utils, sizeof(__pyx_k_utils), 0, 0, 1, 1}, + {&__pyx_n_s_val, __pyx_k_val, sizeof(__pyx_k_val), 0, 0, 1, 1}, + {&__pyx_n_s_valid_metrics, __pyx_k_valid_metrics, sizeof(__pyx_k_valid_metrics), 0, 0, 1, 1}, + {&__pyx_n_s_vals, __pyx_k_vals, sizeof(__pyx_k_vals), 0, 0, 1, 1}, + {&__pyx_n_s_vals_sorted, __pyx_k_vals_sorted, sizeof(__pyx_k_vals_sorted), 0, 0, 1, 1}, + {&__pyx_n_s_warn, __pyx_k_warn, sizeof(__pyx_k_warn), 0, 0, 1, 1}, + {&__pyx_n_s_warnings, __pyx_k_warnings, sizeof(__pyx_k_warnings), 0, 0, 1, 1}, + {&__pyx_n_s_xrange, __pyx_k_xrange, sizeof(__pyx_k_xrange), 0, 0, 1, 1}, + {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, + {&__pyx_n_s_zeros_like, __pyx_k_zeros_like, sizeof(__pyx_k_zeros_like), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 789; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":493 + * factor = log(factor) + logSn(d - 1) + * else: + * raise ValueError("Kernel code not recognized") # <<<<<<<<<<<<<< + * return -factor - d * log(h) + * + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_s_Kernel_code_not_recognized); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":531 + * result = _log_kernel_norm(h, d, COSINE_KERNEL) + * else: + * raise ValueError('kernel not recognized') # <<<<<<<<<<<<<< + * + * if return_log: + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_kernel_not_recognized); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":582 + * + * def __cinit__(self): + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + */ + __pyx_tuple__3 = PyTuple_Pack(2, __pyx_int_1, __pyx_int_1); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_tuple__3); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":583 + * def __cinit__(self): + * self.distances_arr = np.zeros((1, 1), dtype=DTYPE, order='C') + * self.indices_arr = np.zeros((1, 1), dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * self.distances = get_memview_DTYPE_2D(self.distances_arr) + * self.indices = get_memview_ITYPE_2D(self.indices_arr) + */ + __pyx_tuple__5 = PyTuple_Pack(2, __pyx_int_1, __pyx_int_1); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_tuple__5); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":878 + * + * def __cinit__(self): + * self.data_arr = np.zeros(1, dtype=NodeHeapData, order='C') # <<<<<<<<<<<<<< + * self.data = get_memview_NodeHeapData_1D(self.data_arr) + * + */ + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_int_1); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":941 + * """Remove the root of the heap, and update the remaining nodes""" + * if self.n == 0: + * raise ValueError('cannot pop on empty heap') # <<<<<<<<<<<<<< + * + * cdef ITYPE_t i, i_child1, i_child2, i_swap + */ + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_cannot_pop_on_empty_heap); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 941; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1027 + * # errors and seg-faults in rare cases where __init__ is not called + * def __cinit__(self): + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + */ + __pyx_tuple__9 = PyTuple_Pack(2, __pyx_int_1, __pyx_int_1); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + __pyx_tuple__10 = PyTuple_Pack(1, __pyx_tuple__9); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1028 + * def __cinit__(self): + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) + */ + __pyx_tuple__11 = PyTuple_Pack(1, __pyx_int_1); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__11); + __Pyx_GIVEREF(__pyx_tuple__11); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1029 + * self.data_arr = np.empty((1, 1), dtype=DTYPE, order='C') + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') # <<<<<<<<<<<<<< + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) + * + */ + __pyx_tuple__12 = PyTuple_Pack(1, __pyx_int_1); if (unlikely(!__pyx_tuple__12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1030 + * self.idx_array_arr = np.empty(1, dtype=ITYPE, order='C') + * self.node_data_arr = np.empty(1, dtype=NodeData, order='C') + * self.node_bounds_arr = np.empty((1, 1, 1), dtype=DTYPE) # <<<<<<<<<<<<<< + * + * self.data = get_memview_DTYPE_2D(self.data_arr) + */ + __pyx_tuple__13 = PyTuple_Pack(3, __pyx_int_1, __pyx_int_1, __pyx_int_1); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__13); + __Pyx_GIVEREF(__pyx_tuple__13); + __pyx_tuple__14 = PyTuple_Pack(1, __pyx_tuple__13); if (unlikely(!__pyx_tuple__14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_GIVEREF(__pyx_tuple__14); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1066 + * # validate data + * if self.data.size == 0: + * raise ValueError("X is an empty array") # <<<<<<<<<<<<<< + * + * if leaf_size < 1: + */ + __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_X_is_an_empty_array); if (unlikely(!__pyx_tuple__15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1066; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__15); + __Pyx_GIVEREF(__pyx_tuple__15); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1069 + * + * if leaf_size < 1: + * raise ValueError("leaf_size must be greater than or equal to 1") # <<<<<<<<<<<<<< + * + * n_samples = self.data.shape[0] + */ + __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_leaf_size_must_be_greater_than_o); if (unlikely(!__pyx_tuple__16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__16); + __Pyx_GIVEREF(__pyx_tuple__16); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1205 + * # warning saying we're doing so. + * import warnings + * warnings.warn("Internal: memory layout is flawed: " # <<<<<<<<<<<<<< + * "not enough nodes allocated") + * + */ + __pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_s_Internal_memory_layout_is_flawed); if (unlikely(!__pyx_tuple__17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__17); + __Pyx_GIVEREF(__pyx_tuple__17); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1212 + * # is correct. Raise a warning. + * import warnings + * warnings.warn("Internal: memory layout is flawed: " # <<<<<<<<<<<<<< + * "too many nodes allocated") + * self.node_data[i_node].is_leaf = True + */ + __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_Internal_memory_layout_is_flawed_2); if (unlikely(!__pyx_tuple__18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__18); + __Pyx_GIVEREF(__pyx_tuple__18); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1290 + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * + */ + __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_query_data_dimension_must_match); if (unlikely(!__pyx_tuple__19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__19); + __Pyx_GIVEREF(__pyx_tuple__19); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1294 + * + * if self.data.shape[0] < k: + * raise ValueError("k must be less than or equal " # <<<<<<<<<<<<<< + * "to the number of training points") + * + */ + __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_k_must_be_less_than_or_equal_to); if (unlikely(!__pyx_tuple__20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__20); + __Pyx_GIVEREF(__pyx_tuple__20); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1420 + * """ + * if count_only and return_distance: + * raise ValueError("count_only and return_distance " # <<<<<<<<<<<<<< + * "cannot both be true") + * + */ + __pyx_tuple__21 = PyTuple_Pack(1, __pyx_kp_s_count_only_and_return_distance_c); if (unlikely(!__pyx_tuple__21)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1420; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__21); + __Pyx_GIVEREF(__pyx_tuple__21); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1424 + * + * if sort_results and not return_distance: + * raise ValueError("return_distance must be True " # <<<<<<<<<<<<<< + * "if sort_results is True") + * + */ + __pyx_tuple__22 = PyTuple_Pack(1, __pyx_kp_s_return_distance_must_be_True_if); if (unlikely(!__pyx_tuple__22)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__22); + __Pyx_GIVEREF(__pyx_tuple__22); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1437 + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * + */ + __pyx_tuple__23 = PyTuple_Pack(1, __pyx_kp_s_query_data_dimension_must_match); if (unlikely(!__pyx_tuple__23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__23); + __Pyx_GIVEREF(__pyx_tuple__23); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1446 + * r = np.asarray(r, dtype=DTYPE, order='C') + * r = np.atleast_1d(r) + * if r.shape == (1,): # <<<<<<<<<<<<<< + * r = r[0] + np.zeros(X.shape[:X.ndim - 1], dtype=DTYPE) + * else: + */ + __pyx_tuple__24 = PyTuple_Pack(1, __pyx_int_1); if (unlikely(!__pyx_tuple__24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__24); + __Pyx_GIVEREF(__pyx_tuple__24); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1450 + * else: + * if r.shape != X.shape[:X.ndim - 1]: + * raise ValueError("r must be broadcastable to X.shape") # <<<<<<<<<<<<<< + * + * rarr_np = r.reshape(-1) # store explicitly to keep in scope + */ + __pyx_tuple__25 = PyTuple_Pack(1, __pyx_kp_s_r_must_be_broadcastable_to_X_sha); if (unlikely(!__pyx_tuple__25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__25); + __Pyx_GIVEREF(__pyx_tuple__25); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1452 + * raise ValueError("r must be broadcastable to X.shape") + * + * rarr_np = r.reshape(-1) # store explicitly to keep in scope # <<<<<<<<<<<<<< + * cdef DTYPE_t[::1] rarr = get_memview_DTYPE_1D(rarr_np) + * + */ + __pyx_tuple__26 = PyTuple_Pack(1, __pyx_int_neg_1); if (unlikely(!__pyx_tuple__26)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__26); + __Pyx_GIVEREF(__pyx_tuple__26); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1587 + * + * if X.shape[X.ndim - 1] != n_features: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * Xarr_np = X.reshape((-1, n_features)) + */ + __pyx_tuple__27 = PyTuple_Pack(1, __pyx_kp_s_query_data_dimension_must_match); if (unlikely(!__pyx_tuple__27)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1587; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__27); + __Pyx_GIVEREF(__pyx_tuple__27); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1690 + * + * if X.shape[X.ndim - 1] != self.data.shape[1]: + * raise ValueError("query data dimension must " # <<<<<<<<<<<<<< + * "match training data dimension") + * + */ + __pyx_tuple__28 = PyTuple_Pack(1, __pyx_kp_s_query_data_dimension_must_match); if (unlikely(!__pyx_tuple__28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1690; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__28); + __Pyx_GIVEREF(__pyx_tuple__28); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1700 + * r = np.atleast_1d(r) + * if r.ndim != 1: + * raise ValueError("r must be a 1-dimensional array") # <<<<<<<<<<<<<< + * i_rsort = np.argsort(r) + * rarr_np = r[i_rsort] # needed to keep memory in scope + */ + __pyx_tuple__29 = PyTuple_Pack(1, __pyx_kp_s_r_must_be_a_1_dimensional_array); if (unlikely(!__pyx_tuple__29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__29); + __Pyx_GIVEREF(__pyx_tuple__29); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2048 + * for i in range(node_info.idx_start, node_info.idx_end): + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count too big: " # <<<<<<<<<<<<<< + * "this should never happen") + * indices[count] = idx_array[i] + */ + __pyx_tuple__30 = PyTuple_Pack(1, __pyx_kp_s_Fatal_count_too_big_this_should); if (unlikely(!__pyx_tuple__30)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2048; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__30); + __Pyx_GIVEREF(__pyx_tuple__30); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2068 + * if dist_pt <= reduced_r: + * if (count < 0) or (count >= self.data.shape[0]): + * raise ValueError("Fatal: count out of range. " # <<<<<<<<<<<<<< + * "This should never happen.") + * if count_only: + */ + __pyx_tuple__31 = PyTuple_Pack(1, __pyx_kp_s_Fatal_count_out_of_range_This_sh); if (unlikely(!__pyx_tuple__31)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2068; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__31); + __Pyx_GIVEREF(__pyx_tuple__31); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2500 + * + * # use initial size 0 to check corner case + * cdef NodeHeap heap = NodeHeap(0) # <<<<<<<<<<<<<< + * cdef NodeHeapData_t data + * cdef ITYPE_t i + */ + __pyx_tuple__32 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__32)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2500; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__32); + __Pyx_GIVEREF(__pyx_tuple__32); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_tuple__33 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__33)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__33); + __Pyx_GIVEREF(__pyx_tuple__33); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_tuple__34 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__34)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__34); + __Pyx_GIVEREF(__pyx_tuple__34); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_tuple__35 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__35)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__35); + __Pyx_GIVEREF(__pyx_tuple__35); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_tuple__36 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__36)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__36); + __Pyx_GIVEREF(__pyx_tuple__36); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_tuple__37 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__37)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__37); + __Pyx_GIVEREF(__pyx_tuple__37); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_tuple__38 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__38)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__38); + __Pyx_GIVEREF(__pyx_tuple__38); + + /* "View.MemoryView":127 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if itemsize <= 0: + */ + __pyx_tuple__39 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__39)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__39); + __Pyx_GIVEREF(__pyx_tuple__39); + + /* "View.MemoryView":130 + * + * if itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * if isinstance(format, unicode): + */ + __pyx_tuple__40 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__40)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__40); + __Pyx_GIVEREF(__pyx_tuple__40); + + /* "View.MemoryView":142 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__41 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__41)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__41); + __Pyx_GIVEREF(__pyx_tuple__41); + + /* "View.MemoryView":170 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_tuple__42 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__42)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__42); + __Pyx_GIVEREF(__pyx_tuple__42); + + /* "View.MemoryView":186 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_tuple__43 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__43)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__43); + __Pyx_GIVEREF(__pyx_tuple__43); + + /* "View.MemoryView":445 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_tuple__44 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__44)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__44); + __Pyx_GIVEREF(__pyx_tuple__44); + + /* "View.MemoryView":521 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_tuple__45 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__45)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__45); + __Pyx_GIVEREF(__pyx_tuple__45); + + /* "View.MemoryView":638 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_tuple__46 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__46)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__46); + __Pyx_GIVEREF(__pyx_tuple__46); + + /* "View.MemoryView":641 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_tuple__47 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__47)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__47); + __Pyx_GIVEREF(__pyx_tuple__47); + + /* "View.MemoryView":652 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_tuple__48 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__48)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__48); + __Pyx_GIVEREF(__pyx_tuple__48); + + /* "View.MemoryView":660 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__49 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__49)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__49); + __Pyx_GIVEREF(__pyx_tuple__49); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":497 + * + * + * def kernel_norm(h, d, kernel, return_log=False): # <<<<<<<<<<<<<< + * """Given a string specification of a kernel, compute the normalization. + * + */ + __pyx_tuple__55 = PyTuple_Pack(5, __pyx_n_s_h, __pyx_n_s_d, __pyx_n_s_kernel, __pyx_n_s_return_log, __pyx_n_s_result); if (unlikely(!__pyx_tuple__55)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__55); + __Pyx_GIVEREF(__pyx_tuple__55); + __pyx_codeobj__56 = (PyObject*)__Pyx_PyCode_New(4, 0, 5, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__55, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_n_s_kernel_norm, 497, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__56)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":985 + * # newObj function + * # this is a helper function for pickling + * def newObj(obj): # <<<<<<<<<<<<<< + * return obj.__new__(obj) + * + */ + __pyx_tuple__57 = PyTuple_Pack(1, __pyx_n_s_obj); if (unlikely(!__pyx_tuple__57)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__57); + __Pyx_GIVEREF(__pyx_tuple__57); + __pyx_codeobj__58 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__57, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_n_s_newObj, 985, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__58)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2468 + * # Python functions for benchmarking and testing C implementations + * + * def load_heap(DTYPE_t[:, ::1] X, ITYPE_t k): # <<<<<<<<<<<<<< + * """test fully loading the heap""" + * assert k <= X.shape[1] + */ + __pyx_tuple__59 = PyTuple_Pack(5, __pyx_n_s_X, __pyx_n_s_k, __pyx_n_s_heap, __pyx_n_s_i, __pyx_n_s_j); if (unlikely(!__pyx_tuple__59)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__59); + __Pyx_GIVEREF(__pyx_tuple__59); + __pyx_codeobj__60 = (PyObject*)__Pyx_PyCode_New(2, 0, 5, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__59, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_n_s_load_heap, 2468, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__60)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2479 + * + * + * def simultaneous_sort(DTYPE_t[:, ::1] distances, ITYPE_t[:, ::1] indices): # <<<<<<<<<<<<<< + * """In-place simultaneous sort the given row of the arrays + * + */ + __pyx_tuple__61 = PyTuple_Pack(3, __pyx_n_s_distances, __pyx_n_s_indices, __pyx_n_s_row); if (unlikely(!__pyx_tuple__61)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__61); + __Pyx_GIVEREF(__pyx_tuple__61); + __pyx_codeobj__62 = (PyObject*)__Pyx_PyCode_New(2, 0, 3, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__61, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_n_s_simultaneous_sort, 2479, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__62)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2494 + * + * + * def nodeheap_sort(DTYPE_t[::1] vals): # <<<<<<<<<<<<<< + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) + */ + __pyx_tuple__63 = PyTuple_Pack(7, __pyx_n_s_vals, __pyx_n_s_vals, __pyx_n_s_indices, __pyx_n_s_vals_sorted, __pyx_n_s_heap, __pyx_n_s_data, __pyx_n_s_i); if (unlikely(!__pyx_tuple__63)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__63); + __Pyx_GIVEREF(__pyx_tuple__63); + __pyx_codeobj__64 = (PyObject*)__Pyx_PyCode_New(1, 0, 7, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__63, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_manoj_scikit_learn_sklearn, __pyx_n_s_nodeheap_sort, 2494, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__64)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":276 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_tuple__65 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__65)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__65); + __Pyx_GIVEREF(__pyx_tuple__65); + + /* "View.MemoryView":277 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_tuple__66 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__66)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__66); + __Pyx_GIVEREF(__pyx_tuple__66); + + /* "View.MemoryView":278 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__67 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__67)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__67); + __Pyx_GIVEREF(__pyx_tuple__67); + + /* "View.MemoryView":281 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_tuple__68 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__68)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__68); + __Pyx_GIVEREF(__pyx_tuple__68); + + /* "View.MemoryView":282 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__69 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__69)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__69); + __Pyx_GIVEREF(__pyx_tuple__69); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_float_1Eneg_8 = PyFloat_FromDouble(1E-8); if (unlikely(!__pyx_float_1Eneg_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_40 = PyInt_FromLong(40); if (unlikely(!__pyx_int_40)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_100 = PyInt_FromLong(100); if (unlikely(!__pyx_int_100)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC initkd_tree(void); /*proto*/ +PyMODINIT_FUNC initkd_tree(void) +#else +PyMODINIT_FUNC PyInit_kd_tree(void); /*proto*/ +PyMODINIT_FUNC PyInit_kd_tree(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_kd_tree(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("kd_tree"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__neighbors__kd_tree) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.neighbors.kd_tree")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.neighbors.kd_tree", __pyx_m) < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + generic = Py_None; Py_INCREF(Py_None); + strided = Py_None; Py_INCREF(Py_None); + indirect = Py_None; Py_INCREF(Py_None); + contiguous = Py_None; Py_INCREF(Py_None); + indirect_contiguous = Py_None; Py_INCREF(Py_None); + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + __pyx_vtabptr_7sklearn_9neighbors_7kd_tree_NeighborsHeap = &__pyx_vtable_7sklearn_9neighbors_7kd_tree_NeighborsHeap; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_NeighborsHeap.largest = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_largest; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_NeighborsHeap.push = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, int __pyx_skip_dispatch))__pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap_push; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_NeighborsHeap._sort = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *))__pyx_f_7sklearn_9neighbors_7kd_tree_13NeighborsHeap__sort; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_7kd_tree_NeighborsHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_9neighbors_7kd_tree_NeighborsHeap.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_7kd_tree_NeighborsHeap.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_7kd_tree_NeighborsHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "NeighborsHeap", (PyObject *)&__pyx_type_7sklearn_9neighbors_7kd_tree_NeighborsHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_7kd_tree_NeighborsHeap = &__pyx_type_7sklearn_9neighbors_7kd_tree_NeighborsHeap; + __pyx_vtabptr_7sklearn_9neighbors_7kd_tree_NodeHeap = &__pyx_vtable_7sklearn_9neighbors_7kd_tree_NodeHeap; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_NodeHeap.resize = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_7kd_tree_8NodeHeap_resize; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_NodeHeap.push = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *, struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t))__pyx_f_7sklearn_9neighbors_7kd_tree_8NodeHeap_push; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_NodeHeap.peek = (struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *))__pyx_f_7sklearn_9neighbors_7kd_tree_8NodeHeap_peek; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_NodeHeap.pop = (struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *))__pyx_f_7sklearn_9neighbors_7kd_tree_8NodeHeap_pop; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_NodeHeap.clear = (void (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *))__pyx_f_7sklearn_9neighbors_7kd_tree_8NodeHeap_clear; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_7kd_tree_NodeHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_9neighbors_7kd_tree_NodeHeap.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_7kd_tree_NodeHeap.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_7kd_tree_NodeHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "NodeHeap", (PyObject *)&__pyx_type_7sklearn_9neighbors_7kd_tree_NodeHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_7kd_tree_NodeHeap = &__pyx_type_7sklearn_9neighbors_7kd_tree_NodeHeap; + __pyx_vtabptr_7sklearn_9neighbors_7kd_tree_BinaryTree = &__pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree.dist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_dist; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree.rdist = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree_rdist; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree._recursive_build = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__recursive_build; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree._query_single_depthfirst = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__query_single_depthfirst; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree._query_single_breadthfirst = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__query_single_breadthfirst; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree._query_dual_depthfirst = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __Pyx_memviewslice, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__query_dual_depthfirst; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree._query_dual_breadthfirst = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NeighborsHeap *, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__query_dual_breadthfirst; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree._query_radius_single = (__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, int, int))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__query_radius_single; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree._kde_single_breadthfirst = (__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_NodeHeap *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__kde_single_breadthfirst; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree._kde_single_depthfirst = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, enum __pyx_t_7sklearn_9neighbors_7kd_tree_KernelType, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__kde_single_depthfirst; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree._two_point_single = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__two_point_single; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_BinaryTree._two_point_dual = (int (*)(struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, struct __pyx_obj_7sklearn_9neighbors_7kd_tree_BinaryTree *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t))__pyx_f_7sklearn_9neighbors_7kd_tree_10BinaryTree__two_point_dual; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_7kd_tree_BinaryTree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_9neighbors_7kd_tree_BinaryTree.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_7kd_tree_BinaryTree.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_7kd_tree_BinaryTree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "BinaryTree", (PyObject *)&__pyx_type_7sklearn_9neighbors_7kd_tree_BinaryTree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree = &__pyx_type_7sklearn_9neighbors_7kd_tree_BinaryTree; + __pyx_vtabptr_7sklearn_9neighbors_7kd_tree_KDTree = &__pyx_vtable_7sklearn_9neighbors_7kd_tree_KDTree; + __pyx_vtable_7sklearn_9neighbors_7kd_tree_KDTree.__pyx_base = *__pyx_vtabptr_7sklearn_9neighbors_7kd_tree_BinaryTree; + __pyx_type_7sklearn_9neighbors_7kd_tree_KDTree.tp_base = __pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree; + if (PyType_Ready(&__pyx_type_7sklearn_9neighbors_7kd_tree_KDTree) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_9neighbors_7kd_tree_KDTree.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_9neighbors_7kd_tree_KDTree.tp_dict, __pyx_vtabptr_7sklearn_9neighbors_7kd_tree_KDTree) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "KDTree", (PyObject *)&__pyx_type_7sklearn_9neighbors_7kd_tree_KDTree) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_7kd_tree_KDTree = &__pyx_type_7sklearn_9neighbors_7kd_tree_KDTree; + if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_array.tp_print = 0; + __pyx_array_type = &__pyx_type___pyx_array; + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_MemviewEnum.tp_print = 0; + __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; + __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; + __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; + __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; + __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; + __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; + __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; + __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; + __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; + if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_memoryview.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryview_type = &__pyx_type___pyx_memoryview; + __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; + __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; + __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; + __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; + __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type___pyx_memoryviewslice.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[5]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric = __Pyx_ImportType("sklearn.neighbors.dist_metrics", "DistanceMetric", sizeof(struct __pyx_obj_7sklearn_9neighbors_12dist_metrics_DistanceMetric), 1); if (unlikely(!__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric)) {__pyx_filename = __pyx_f[6]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric = (struct __pyx_vtabstruct_7sklearn_9neighbors_12dist_metrics_DistanceMetric*)__Pyx_GetVtable(__pyx_ptype_7sklearn_9neighbors_12dist_metrics_DistanceMetric->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_9neighbors_12dist_metrics_DistanceMetric)) {__pyx_filename = __pyx_f[6]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + __pyx_t_1 = __Pyx_ImportModule("sklearn.utils.lgamma"); if (!__pyx_t_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_ImportFunction(__pyx_t_1, "lgamma", (void (**)(void))&__pyx_f_7sklearn_5utils_6lgamma_lgamma, "double (double)") < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /*--- Execution code ---*/ + + /* "sklearn/neighbors/kd_tree.pyx":10 + * # License: BSD + * + * __all__ = ['KDTree'] # <<<<<<<<<<<<<< + * + * DOC_DICT = {'BinaryTree': 'KDTree', 'binary_tree': 'kd_tree'} + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_KDTree); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_KDTree); + __Pyx_GIVEREF(__pyx_n_s_KDTree); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_all, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/neighbors/kd_tree.pyx":12 + * __all__ = ['KDTree'] + * + * DOC_DICT = {'BinaryTree': 'KDTree', 'binary_tree': 'kd_tree'} # <<<<<<<<<<<<<< + * + * VALID_METRICS = ['EuclideanDistance', 'ManhattanDistance', + */ + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_BinaryTree, __pyx_n_s_KDTree) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_binary_tree, __pyx_n_s_kd_tree) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_DOC_DICT, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/neighbors/kd_tree.pyx":14 + * DOC_DICT = {'BinaryTree': 'KDTree', 'binary_tree': 'kd_tree'} + * + * VALID_METRICS = ['EuclideanDistance', 'ManhattanDistance', # <<<<<<<<<<<<<< + * 'ChebyshevDistance', 'MinkowskiDistance'] + * + */ + __pyx_t_2 = PyList_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_EuclideanDistance); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_EuclideanDistance); + __Pyx_GIVEREF(__pyx_n_s_EuclideanDistance); + __Pyx_INCREF(__pyx_n_s_ManhattanDistance); + PyList_SET_ITEM(__pyx_t_2, 1, __pyx_n_s_ManhattanDistance); + __Pyx_GIVEREF(__pyx_n_s_ManhattanDistance); + __Pyx_INCREF(__pyx_n_s_ChebyshevDistance); + PyList_SET_ITEM(__pyx_t_2, 2, __pyx_n_s_ChebyshevDistance); + __Pyx_GIVEREF(__pyx_n_s_ChebyshevDistance); + __Pyx_INCREF(__pyx_n_s_MinkowskiDistance); + PyList_SET_ITEM(__pyx_t_2, 3, __pyx_n_s_MinkowskiDistance); + __Pyx_GIVEREF(__pyx_n_s_MinkowskiDistance); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_VALID_METRICS, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":149 + * from sklearn.utils.lgamma cimport lgamma + * + * import numpy as np # <<<<<<<<<<<<<< + * import warnings + * from ..utils import check_array + */ + __pyx_t_2 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":150 + * + * import numpy as np + * import warnings # <<<<<<<<<<<<<< + * from ..utils import check_array + * + */ + __pyx_t_2 = __Pyx_Import(__pyx_n_s_warnings, 0, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_warnings, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":151 + * import numpy as np + * import warnings + * from ..utils import check_array # <<<<<<<<<<<<<< + * + * from typedefs cimport DTYPE_t, ITYPE_t, DITYPE_t + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_check_array); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_check_array); + __Pyx_GIVEREF(__pyx_n_s_check_array); + __pyx_t_3 = __Pyx_Import(__pyx_n_s_utils, __pyx_t_2, 2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_check_array); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_check_array, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":154 + * + * from typedefs cimport DTYPE_t, ITYPE_t, DITYPE_t + * from typedefs import DTYPE, ITYPE # <<<<<<<<<<<<<< + * + * from dist_metrics cimport (DistanceMetric, euclidean_dist, euclidean_rdist, + */ + __pyx_t_3 = PyList_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_n_s_DTYPE); + PyList_SET_ITEM(__pyx_t_3, 0, __pyx_n_s_DTYPE); + __Pyx_GIVEREF(__pyx_n_s_DTYPE); + __Pyx_INCREF(__pyx_n_s_ITYPE); + PyList_SET_ITEM(__pyx_t_3, 1, __pyx_n_s_ITYPE); + __Pyx_GIVEREF(__pyx_n_s_ITYPE); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_typedefs, __pyx_t_3, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_ITYPE, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":160 + * + * # some handy constants + * cdef DTYPE_t INF = np.inf # <<<<<<<<<<<<<< + * cdef DTYPE_t NEG_INF = -np.inf + * cdef DTYPE_t PI = np.pi + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_inf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_7sklearn_9neighbors_7kd_tree_INF = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":161 + * # some handy constants + * cdef DTYPE_t INF = np.inf + * cdef DTYPE_t NEG_INF = -np.inf # <<<<<<<<<<<<<< + * cdef DTYPE_t PI = np.pi + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Negative(__pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_7sklearn_9neighbors_7kd_tree_NEG_INF = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":162 + * cdef DTYPE_t INF = np.inf + * cdef DTYPE_t NEG_INF = -np.inf + * cdef DTYPE_t PI = np.pi # <<<<<<<<<<<<<< + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) + * cdef DTYPE_t LOG_PI = log(PI) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_pi); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_4 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_7sklearn_9neighbors_7kd_tree_PI = __pyx_t_4; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":163 + * cdef DTYPE_t NEG_INF = -np.inf + * cdef DTYPE_t PI = np.pi + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) # <<<<<<<<<<<<<< + * cdef DTYPE_t LOG_PI = log(PI) + * cdef DTYPE_t LOG_2PI = log(2 * PI) + */ + __pyx_v_7sklearn_9neighbors_7kd_tree_ROOT_2PI = sqrt((2.0 * __pyx_v_7sklearn_9neighbors_7kd_tree_PI)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":164 + * cdef DTYPE_t PI = np.pi + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) + * cdef DTYPE_t LOG_PI = log(PI) # <<<<<<<<<<<<<< + * cdef DTYPE_t LOG_2PI = log(2 * PI) + * + */ + __pyx_v_7sklearn_9neighbors_7kd_tree_LOG_PI = log(__pyx_v_7sklearn_9neighbors_7kd_tree_PI); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":165 + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) + * cdef DTYPE_t LOG_PI = log(PI) + * cdef DTYPE_t LOG_2PI = log(2 * PI) # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_7sklearn_9neighbors_7kd_tree_LOG_2PI = log((2.0 * __pyx_v_7sklearn_9neighbors_7kd_tree_PI)); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":180 + * # NodeHeapData = np.asarray((&nhd_tmp)).dtype + * cdef NodeHeapData_t nhd_tmp + * offsets = [&(nhd_tmp.val) - &nhd_tmp, # <<<<<<<<<<<<<< + * &(nhd_tmp.i1) - &nhd_tmp, + * &(nhd_tmp.i2) - &nhd_tmp] + */ + __pyx_t_2 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nhd_tmp.val)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nhd_tmp)))); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":181 + * cdef NodeHeapData_t nhd_tmp + * offsets = [&(nhd_tmp.val) - &nhd_tmp, + * &(nhd_tmp.i1) - &nhd_tmp, # <<<<<<<<<<<<<< + * &(nhd_tmp.i2) - &nhd_tmp] + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], + */ + __pyx_t_3 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nhd_tmp.i1)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nhd_tmp)))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":182 + * offsets = [&(nhd_tmp.val) - &nhd_tmp, + * &(nhd_tmp.i1) - &nhd_tmp, + * &(nhd_tmp.i2) - &nhd_tmp] # <<<<<<<<<<<<<< + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], + * 'formats': [DTYPE, ITYPE, ITYPE], + */ + __pyx_t_5 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nhd_tmp.i2)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nhd_tmp)))); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":180 + * # NodeHeapData = np.asarray((&nhd_tmp)).dtype + * cdef NodeHeapData_t nhd_tmp + * offsets = [&(nhd_tmp.val) - &nhd_tmp, # <<<<<<<<<<<<<< + * &(nhd_tmp.i1) - &nhd_tmp, + * &(nhd_tmp.i2) - &nhd_tmp] + */ + __pyx_t_6 = PyList_New(3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyList_SET_ITEM(__pyx_t_6, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyList_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyList_SET_ITEM(__pyx_t_6, 2, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_offsets, __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":183 + * &(nhd_tmp.i1) - &nhd_tmp, + * &(nhd_tmp.i2) - &nhd_tmp] + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], # <<<<<<<<<<<<<< + * 'formats': [DTYPE, ITYPE, ITYPE], + * 'offsets': offsets, + */ + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = PyList_New(3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_n_s_val); + PyList_SET_ITEM(__pyx_t_5, 0, __pyx_n_s_val); + __Pyx_GIVEREF(__pyx_n_s_val); + __Pyx_INCREF(__pyx_n_s_i1); + PyList_SET_ITEM(__pyx_t_5, 1, __pyx_n_s_i1); + __Pyx_GIVEREF(__pyx_n_s_i1); + __Pyx_INCREF(__pyx_n_s_i2); + PyList_SET_ITEM(__pyx_t_5, 2, __pyx_n_s_i2); + __Pyx_GIVEREF(__pyx_n_s_i2); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_names, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":184 + * &(nhd_tmp.i2) - &nhd_tmp] + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], + * 'formats': [DTYPE, ITYPE, ITYPE], # <<<<<<<<<<<<<< + * 'offsets': offsets, + * 'itemsize': sizeof(NodeHeapData_t)}) + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = PyList_New(3); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyList_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyList_SET_ITEM(__pyx_t_7, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyList_SET_ITEM(__pyx_t_7, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_formats, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":185 + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], + * 'formats': [DTYPE, ITYPE, ITYPE], + * 'offsets': offsets, # <<<<<<<<<<<<<< + * 'itemsize': sizeof(NodeHeapData_t)}) + * + */ + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_offsets); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_offsets, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":186 + * 'formats': [DTYPE, ITYPE, ITYPE], + * 'offsets': offsets, + * 'itemsize': sizeof(NodeHeapData_t)}) # <<<<<<<<<<<<<< + * + * cdef struct NodeData_t: + */ + __pyx_t_7 = __Pyx_PyInt_FromSize_t((sizeof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_itemsize, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":183 + * &(nhd_tmp.i1) - &nhd_tmp, + * &(nhd_tmp.i2) - &nhd_tmp] + * NodeHeapData = np.dtype({'names': ['val', 'i1', 'i2'], # <<<<<<<<<<<<<< + * 'formats': [DTYPE, ITYPE, ITYPE], + * 'offsets': offsets, + */ + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_5numpy_dtype)), __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_NodeHeapData, __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":200 + * # NodeData = np.asarray((&nd_tmp)).dtype + * cdef NodeData_t nd_tmp + * offsets = [&(nd_tmp.idx_start) - &nd_tmp, # <<<<<<<<<<<<<< + * &(nd_tmp.idx_end) - &nd_tmp, + * &(nd_tmp.is_leaf) - &nd_tmp, + */ + __pyx_t_6 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nd_tmp.idx_start)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nd_tmp)))); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":201 + * cdef NodeData_t nd_tmp + * offsets = [&(nd_tmp.idx_start) - &nd_tmp, + * &(nd_tmp.idx_end) - &nd_tmp, # <<<<<<<<<<<<<< + * &(nd_tmp.is_leaf) - &nd_tmp, + * &(nd_tmp.radius) - &nd_tmp] + */ + __pyx_t_7 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nd_tmp.idx_end)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nd_tmp)))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":202 + * offsets = [&(nd_tmp.idx_start) - &nd_tmp, + * &(nd_tmp.idx_end) - &nd_tmp, + * &(nd_tmp.is_leaf) - &nd_tmp, # <<<<<<<<<<<<<< + * &(nd_tmp.radius) - &nd_tmp] + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], + */ + __pyx_t_2 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nd_tmp.is_leaf)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nd_tmp)))); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":203 + * &(nd_tmp.idx_end) - &nd_tmp, + * &(nd_tmp.is_leaf) - &nd_tmp, + * &(nd_tmp.radius) - &nd_tmp] # <<<<<<<<<<<<<< + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], + */ + __pyx_t_3 = __Pyx_PyInt_From_int((((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nd_tmp.radius)) - ((__pyx_t_5numpy_intp_t)(&__pyx_v_7sklearn_9neighbors_7kd_tree_nd_tmp)))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":200 + * # NodeData = np.asarray((&nd_tmp)).dtype + * cdef NodeData_t nd_tmp + * offsets = [&(nd_tmp.idx_start) - &nd_tmp, # <<<<<<<<<<<<<< + * &(nd_tmp.idx_end) - &nd_tmp, + * &(nd_tmp.is_leaf) - &nd_tmp, + */ + __pyx_t_5 = PyList_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyList_SET_ITEM(__pyx_t_5, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyList_SET_ITEM(__pyx_t_5, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_offsets, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":204 + * &(nd_tmp.is_leaf) - &nd_tmp, + * &(nd_tmp.radius) - &nd_tmp] + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], # <<<<<<<<<<<<<< + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], + * 'offsets': offsets, + */ + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyList_New(4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_n_s_idx_start); + PyList_SET_ITEM(__pyx_t_3, 0, __pyx_n_s_idx_start); + __Pyx_GIVEREF(__pyx_n_s_idx_start); + __Pyx_INCREF(__pyx_n_s_idx_end); + PyList_SET_ITEM(__pyx_t_3, 1, __pyx_n_s_idx_end); + __Pyx_GIVEREF(__pyx_n_s_idx_end); + __Pyx_INCREF(__pyx_n_s_is_leaf); + PyList_SET_ITEM(__pyx_t_3, 2, __pyx_n_s_is_leaf); + __Pyx_GIVEREF(__pyx_n_s_is_leaf); + __Pyx_INCREF(__pyx_n_s_radius); + PyList_SET_ITEM(__pyx_t_3, 3, __pyx_n_s_radius); + __Pyx_GIVEREF(__pyx_n_s_radius); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_names, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":205 + * &(nd_tmp.radius) - &nd_tmp] + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], # <<<<<<<<<<<<<< + * 'offsets': offsets, + * 'itemsize': sizeof(NodeData_t)}) + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_ITYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = PyList_New(4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_8, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyList_SET_ITEM(__pyx_t_8, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyList_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyList_SET_ITEM(__pyx_t_8, 3, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_3 = 0; + __pyx_t_2 = 0; + __pyx_t_7 = 0; + __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_formats, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":206 + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], + * 'offsets': offsets, # <<<<<<<<<<<<<< + * 'itemsize': sizeof(NodeData_t)}) + * + */ + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_offsets); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_offsets, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":207 + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], + * 'offsets': offsets, + * 'itemsize': sizeof(NodeData_t)}) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __Pyx_PyInt_FromSize_t((sizeof(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t))); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_itemsize, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":204 + * &(nd_tmp.is_leaf) - &nd_tmp, + * &(nd_tmp.radius) - &nd_tmp] + * NodeData = np.dtype({'names': ['idx_start', 'idx_end', 'is_leaf', 'radius'], # <<<<<<<<<<<<<< + * 'formats': [ITYPE, ITYPE, ITYPE, DTYPE], + * 'offsets': offsets, + */ + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_5numpy_dtype)), __pyx_t_8, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_NodeData, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":255 + * # the DOC_DICT variable defined in the pyx files. + * CLASS_DOC = \ + * """{BinaryTree} for fast generalized N-point problems # <<<<<<<<<<<<<< + * + * {BinaryTree}(X, leaf_size=40, metric='minkowski', **kwargs) + */ + if (PyDict_SetItem(__pyx_d, __pyx_n_s_CLASS_DOC, __pyx_kp_s_BinaryTree_for_fast_generalized) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":497 + * + * + * def kernel_norm(h, d, kernel, return_log=False): # <<<<<<<<<<<<<< + * """Given a string specification of a kernel, compute the normalization. + * + */ + __pyx_t_5 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_7kd_tree_1kernel_norm, NULL, __pyx_n_s_sklearn_neighbors_kd_tree); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_kernel_norm, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":985 + * # newObj function + * # this is a helper function for pickling + * def newObj(obj): # <<<<<<<<<<<<<< + * return obj.__new__(obj) + * + */ + __pyx_t_5 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_7kd_tree_3newObj, NULL, __pyx_n_s_sklearn_neighbors_kd_tree); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_newObj, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":991 + * ###################################################################### + * # define the reverse mapping of VALID_METRICS + * from dist_metrics import get_valid_metric_ids # <<<<<<<<<<<<<< + * VALID_METRIC_IDS = get_valid_metric_ids(VALID_METRICS) + * + */ + __pyx_t_5 = PyList_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 991; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_n_s_get_valid_metric_ids); + PyList_SET_ITEM(__pyx_t_5, 0, __pyx_n_s_get_valid_metric_ids); + __Pyx_GIVEREF(__pyx_n_s_get_valid_metric_ids); + __pyx_t_8 = __Pyx_Import(__pyx_n_s_dist_metrics, __pyx_t_5, -1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 991; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_ImportFrom(__pyx_t_8, __pyx_n_s_get_valid_metric_ids); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 991; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_get_valid_metric_ids, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 991; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":992 + * # define the reverse mapping of VALID_METRICS + * from dist_metrics import get_valid_metric_ids + * VALID_METRIC_IDS = get_valid_metric_ids(VALID_METRICS) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_get_valid_metric_ids); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_VALID_METRICS); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_VALID_METRIC_IDS, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":1022 + * cdef int n_calls + * + * valid_metrics = VALID_METRIC_IDS # <<<<<<<<<<<<<< + * + * # Use cinit to initialize all arrays to empty: this will prevent memory + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_VALID_METRIC_IDS); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem((PyObject *)__pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree->tp_dict, __pyx_n_s_valid_metrics, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + PyType_Modified(__pyx_ptype_7sklearn_9neighbors_7kd_tree_BinaryTree); + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2468 + * # Python functions for benchmarking and testing C implementations + * + * def load_heap(DTYPE_t[:, ::1] X, ITYPE_t k): # <<<<<<<<<<<<<< + * """test fully loading the heap""" + * assert k <= X.shape[1] + */ + __pyx_t_5 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_7kd_tree_5load_heap, NULL, __pyx_n_s_sklearn_neighbors_kd_tree); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_load_heap, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2479 + * + * + * def simultaneous_sort(DTYPE_t[:, ::1] distances, ITYPE_t[:, ::1] indices): # <<<<<<<<<<<<<< + * """In-place simultaneous sort the given row of the arrays + * + */ + __pyx_t_5 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_7kd_tree_7simultaneous_sort, NULL, __pyx_n_s_sklearn_neighbors_kd_tree); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_simultaneous_sort, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "/home/manoj/scikit-learn/sklearn/neighbors/binary_tree.pxi":2494 + * + * + * def nodeheap_sort(DTYPE_t[::1] vals): # <<<<<<<<<<<<<< + * """In-place reverse sort of vals using NodeHeap""" + * cdef ITYPE_t[::1] indices = np.zeros(vals.shape[0], dtype=ITYPE) + */ + __pyx_t_5 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_9neighbors_7kd_tree_9nodeheap_sort, NULL, __pyx_n_s_sklearn_neighbors_kd_tree); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_nodeheap_sort, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "sklearn/neighbors/kd_tree.pyx":22 + * + * cdef class KDTree(BinaryTree): + * __doc__ = CLASS_DOC.format(**DOC_DICT) # <<<<<<<<<<<<<< + * pass + * + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_CLASS_DOC); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_DOC_DICT); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (unlikely(__pyx_t_8 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "argument after ** must be a mapping, not NoneType"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (likely(PyDict_Check(__pyx_t_8))) { + __pyx_t_5 = __pyx_t_8; + __Pyx_INCREF(__pyx_t_5); + } else { + __pyx_t_5 = PyObject_CallFunctionObjArgs((PyObject*)&PyDict_Type, __pyx_t_8, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_empty_tuple, __pyx_t_5); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem((PyObject *)__pyx_ptype_7sklearn_9neighbors_7kd_tree_KDTree->tp_dict, __pyx_n_s_doc, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + PyType_Modified(__pyx_ptype_7sklearn_9neighbors_7kd_tree_KDTree); + + /* "sklearn/neighbors/kd_tree.pyx":1 + * #!python # <<<<<<<<<<<<<< + * #cython: boundscheck=False + * #cython: wraparound=False + */ + __pyx_t_8 = PyDict_New(); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_t_8, __pyx_kp_u_BinaryTree_query_line_1228, __pyx_kp_u_query_X_k_1_return_distance_Tru) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_8, __pyx_kp_u_BinaryTree_query_radius_line_135, __pyx_kp_u_query_radius_self_X_r_count_onl) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_8, __pyx_kp_u_BinaryTree_kernel_density_line_1, __pyx_kp_u_kernel_density_self_X_h_kernel) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_8, __pyx_kp_u_BinaryTree_two_point_correlation, __pyx_kp_u_Compute_the_two_point_correlatio) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "View.MemoryView":203 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * def __dealloc__(array self): + */ + __pyx_t_8 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + PyType_Modified(__pyx_array_type); + + /* "View.MemoryView":276 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_t_8 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__65, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XGOTREF(generic); + __Pyx_DECREF_SET(generic, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + + /* "View.MemoryView":277 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_t_8 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__66, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XGOTREF(strided); + __Pyx_DECREF_SET(strided, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + + /* "View.MemoryView":278 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__67, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XGOTREF(indirect); + __Pyx_DECREF_SET(indirect, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + + /* "View.MemoryView":281 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_t_8 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__68, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XGOTREF(contiguous); + __Pyx_DECREF_SET(contiguous, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + + /* "View.MemoryView":282 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__69, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XGOTREF(indirect_contiguous); + __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + + /* "View.MemoryView":496 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + PyType_Modified(__pyx_memoryview_type); + + /* "View.MemoryView":953 + * return self.from_object + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_8 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + PyType_Modified(__pyx_memoryviewslice_type); + + /* "BufferFormatFromTypeInfo":1417 + * + * @cname('__pyx_format_from_typeinfo') + * cdef bytes format_from_typeinfo(__Pyx_TypeInfo *type): # <<<<<<<<<<<<<< + * cdef __Pyx_StructField *field + * cdef __pyx_typeinfo_string fmt + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.neighbors.kd_tree", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.neighbors.kd_tree"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; /* Consume from buffer string */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; /* not a 'break' in the loop */ + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case '\r': + case '\n': + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; + } + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (!buf) { + PyErr_SetString(PyExc_ValueError, + "buf is NULL."); + goto fail; + } else if (memviewslice->memview || memviewslice->data) { + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); + } + retval = 0; + goto no_fail; +fail: + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} +static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { + va_list vargs; + char msg[200]; + va_start(vargs, fmt); +#ifdef HAVE_STDARG_PROTOTYPES + va_start(vargs, fmt); +#else + va_start(vargs); +#endif + vsnprintf(msg, 200, fmt, vargs); + Py_FatalError(msg); + va_end(vargs); +} +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) +{ + int first_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview || (PyObject *) memview == Py_None) + return; /* allow uninitialized memoryview assignment */ + if (__pyx_get_slice_count(memview) < 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + first_time = __pyx_add_acquisition_count(memview) == 0; + if (first_time) { + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); + } + } +} +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, + int have_gil, int lineno) { + int last_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview ) { + return; + } else if ((PyObject *) memview == Py_None) { + memslice->memview = NULL; + return; + } + if (__pyx_get_slice_count(memview) <= 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; + if (last_time) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } + } else { + memslice->memview = NULL; + } +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; +#endif + result = (*call)(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + Py_LeaveRecursiveCall(); +#endif + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { + #endif +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); + } +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + #if CYTHON_PEP393_ENABLED + if (unlikely(PyUnicode_READY(s1) < 0) || unlikely(PyUnicode_READY(s2) < 0)) + return -1; + #endif + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, length * kind); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static CYTHON_INLINE int __Pyx_CheckKeywordStrings( + PyObject *kwdict, + const char* function_name, + int kw_allowed) +{ + PyObject* key = 0; + Py_ssize_t pos = 0; +#if CPYTHON_COMPILING_IN_PYPY + if (!kw_allowed && PyDict_Next(kwdict, &pos, &key, 0)) + goto invalid_keyword; + return 1; +#else + while (PyDict_Next(kwdict, &pos, &key, 0)) { + #if PY_MAJOR_VERSION < 3 + if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) + #endif + if (unlikely(!PyUnicode_Check(key))) + goto invalid_keyword_type; + } + if ((!kw_allowed) && unlikely(key)) + goto invalid_keyword; + return 1; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + return 0; +#endif +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif + return 0; +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, + int full_traceback) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + if (full_traceback) { + Py_XINCREF(old_exc); + Py_XINCREF(old_val); + Py_XINCREF(old_tb); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + PyErr_PrintEx(1); + } + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { +#if CYTHON_COMPILING_IN_CPYTHON + PyMappingMethods* mp; +#if PY_MAJOR_VERSION < 3 + PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; + if (likely(ms && ms->sq_slice)) { + if (!has_cstart) { + if (_py_start && (*_py_start != Py_None)) { + cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); + if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstart = 0; + } + if (!has_cstop) { + if (_py_stop && (*_py_stop != Py_None)) { + cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); + if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstop = PY_SSIZE_T_MAX; + } + if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { + Py_ssize_t l = ms->sq_length(obj); + if (likely(l >= 0)) { + if (cstop < 0) { + cstop += l; + if (cstop < 0) cstop = 0; + } + if (cstart < 0) { + cstart += l; + if (cstart < 0) cstart = 0; + } + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + goto bad; + } + } + return ms->sq_slice(obj, cstart, cstop); + } +#endif + mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_subscript)) +#endif + { + PyObject* result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyInt_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyInt_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_COMPILING_IN_CPYTHON + result = mp->mp_subscript(obj, py_slice); +#else + result = PyObject_GetItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } + PyErr_Format(PyExc_TypeError, + "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); +bad: + return NULL; +} + +static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { + int r; + if (!j) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { + PyObject* old = PyList_GET_ITEM(o, n); + Py_INCREF(v); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 1; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return -1; + } + } + return m->sq_ass_item(o, i, v); + } + } +#else +#if CYTHON_COMPILING_IN_PYPY + if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) { +#else + if (is_list || PySequence_Check(o)) { +#endif + return PySequence_SetItem(o, i, v); + } +#endif + return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(PyObject_TypeCheck(obj, type))) return 1; + } + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); + return 0; +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +#if CYTHON_COMPILING_IN_CPYTHON +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) +#else + if (likely(PyString_Check(n))) +#endif + return __Pyx_PyObject_GetAttrStr(o, n); +#endif + return PyObject_GetAttr(o, n); +} + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + length = strlen(cstring); + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +#else + PyErr_GetExcInfo(type, value, tb); +#endif +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(type, value, tb); +#endif +} + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } + #endif + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; +#else + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); +#endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} + +#if !CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values) { + return PyObject_CallMethodObjArgs(sep, __pyx_n_s_join, values, NULL); +} +#endif + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +static void* __Pyx_GetVtable(PyObject *dict) { + void* ptr; + PyObject *ob = PyObject_GetItem(dict, __pyx_n_s_pyx_vtable); + if (!ob) + goto bad; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + ptr = PyCapsule_GetPointer(ob, 0); +#else + ptr = PyCObject_AsVoidPtr(ob); +#endif + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif + } + return value; +} + +static int +__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) +{ + int i; + if (!a || !b) + return 0; + if (a == b) + return 1; + if (a->size != b->size || a->typegroup != b->typegroup || + a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { + if (a->typegroup == 'H' || b->typegroup == 'H') { + return a->size == b->size; + } else { + return 0; + } + } + if (a->ndim) { + for (i = 0; i < a->ndim; i++) + if (a->arraysize[i] != b->arraysize[i]) + return 0; + } + if (a->typegroup == 'S') { + if (a->flags != b->flags) + return 0; + if (a->fields || b->fields) { + if (!(a->fields && b->fields)) + return 0; + for (i = 0; a->fields[i].type && b->fields[i].type; i++) { + __Pyx_StructField *field_a = a->fields + i; + __Pyx_StructField *field_b = b->fields + i; + if (field_a->offset != field_b->offset || + !__pyx_typeinfo_cmp(field_a->type, field_b->type)) + return 0; + } + return !a->fields[i].type && !b->fields[i].type; + } + } + return 1; +} + +static int +__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) +{ + if (buf->shape[dim] <= 1) + return 1; + if (buf->strides) { + if (spec & __Pyx_MEMVIEW_CONTIG) { + if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { + if (buf->strides[dim] != sizeof(void *)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly contiguous " + "in dimension %d.", dim); + goto fail; + } + } else if (buf->strides[dim] != buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_FOLLOW) { + Py_ssize_t stride = buf->strides[dim]; + if (stride < 0) + stride = -stride; + if (stride < buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + } else { + if (spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not contiguous in " + "dimension %d", dim); + goto fail; + } else if (spec & (__Pyx_MEMVIEW_PTR)) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not indirect in " + "dimension %d", dim); + goto fail; + } else if (buf->suboffsets) { + PyErr_SetString(PyExc_ValueError, + "Buffer exposes suboffsets but no strides"); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) +{ + if (spec & __Pyx_MEMVIEW_DIRECT) { + if (buf->suboffsets && buf->suboffsets[dim] >= 0) { + PyErr_Format(PyExc_ValueError, + "Buffer not compatible with direct access " + "in dimension %d.", dim); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_PTR) { + if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly accessible " + "in dimension %d.", dim); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) +{ + int i; + if (c_or_f_flag & __Pyx_IS_F_CONTIG) { + Py_ssize_t stride = 1; + for (i = 0; i < ndim; i++) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) + { + PyErr_SetString(PyExc_ValueError, + "Buffer not fortran contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { + Py_ssize_t stride = 1; + for (i = ndim - 1; i >- 1; i--) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) { + PyErr_SetString(PyExc_ValueError, + "Buffer not C contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } + return 1; +fail: + return 0; +} +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj) +{ + struct __pyx_memoryview_obj *memview, *new_memview; + __Pyx_RefNannyDeclarations + Py_buffer *buf; + int i, spec = 0, retval = -1; + __Pyx_BufFmt_Context ctx; + int from_memoryview = __pyx_memoryview_check(original_obj); + __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); + if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) + original_obj)->typeinfo)) { + memview = (struct __pyx_memoryview_obj *) original_obj; + new_memview = NULL; + } else { + memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + original_obj, buf_flags, 0, dtype); + new_memview = memview; + if (unlikely(!memview)) + goto fail; + } + buf = &memview->view; + if (buf->ndim != ndim) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + ndim, buf->ndim); + goto fail; + } + if (new_memview) { + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned) buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " + "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", + buf->itemsize, + (buf->itemsize > 1) ? "s" : "", + dtype->name, + dtype->size, + (dtype->size > 1) ? "s" : ""); + goto fail; + } + for (i = 0; i < ndim; i++) { + spec = axes_specs[i]; + if (!__pyx_check_strides(buf, i, ndim, spec)) + goto fail; + if (!__pyx_check_suboffsets(buf, i, ndim, spec)) + goto fail; + } + if (buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, + new_memview != NULL) == -1)) { + goto fail; + } + retval = 0; + goto no_fail; +fail: + Py_XDECREF(new_memview); + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[2]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 3, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } + } + #endif + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: + Py_DECREF(obj); + view->obj = NULL; +} +#endif /* PY_MAJOR_VERSION < 3 */ + + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } +} + +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \ + { \ + func_type value = func(x); \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + PyErr_SetString(PyExc_OverflowError, \ + (is_unsigned && unlikely(value < zero)) ? \ + "can't convert negative value to " #target_type : \ + "value too large to convert to " #target_type); \ + return (target_type) -1; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *x) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; + } + return (Py_intptr_t) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(Py_intptr_t)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; + } + if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(Py_intptr_t)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(Py_intptr_t) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyLong_AsLong) + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + Py_intptr_t val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (Py_intptr_t) -1; + } + } else { + Py_intptr_t val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (Py_intptr_t) -1; + val = __Pyx_PyInt_As_Py_intptr_t(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(int) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(Py_intptr_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); + } +} + +static PyObject *__pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(const char *itemp) { + return (PyObject *) PyFloat_FromDouble(*(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) itemp); +} +static int __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t(const char *itemp, PyObject *obj) { + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t value = __pyx_PyFloat_AsDouble(obj); + if ((value == (npy_float64)-1) && PyErr_Occurred()) + return 0; + *(__pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t *) itemp = value; + return 1; +} + +static CYTHON_INLINE long __Pyx_pow_long(long b, long e) { + long t = b; + switch (e) { + case 3: + t *= b; + case 2: + t *= b; + case 1: + return t; + case 0: + return 1; + } + #if 1 + if (unlikely(e<0)) return 0; + #endif + t = 1; + while (likely(e)) { + t *= (b * (e&1)) | ((~e)&1); /* 1 or b */ + b *= b; + e >>= 1; + } + return t; +} + +static PyObject *__pyx_memview_get_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(const char *itemp) { + return (PyObject *) __Pyx_PyInt_From_Py_intptr_t(*(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) itemp); +} +static int __pyx_memview_set_nn___pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t(const char *itemp, PyObject *obj) { + __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t value = __Pyx_PyInt_As_Py_intptr_t(obj); + if ((value == (npy_intp)-1) && PyErr_Occurred()) + return 0; + *(__pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t *) itemp = value; + return 1; +} + +static PyObject* __pyx_convert__to_py___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t s) { + PyObject* res; + PyObject* member; + res = PyDict_New(); if (res == NULL) return NULL; + member = __Pyx_PyInt_From_Py_intptr_t(s.idx_start); if (member == NULL) goto bad; + if (PyDict_SetItem(res, __pyx_n_s_idx_start, member) < 0) goto bad; + Py_DECREF(member); + member = __Pyx_PyInt_From_Py_intptr_t(s.idx_end); if (member == NULL) goto bad; + if (PyDict_SetItem(res, __pyx_n_s_idx_end, member) < 0) goto bad; + Py_DECREF(member); + member = __Pyx_PyInt_From_Py_intptr_t(s.is_leaf); if (member == NULL) goto bad; + if (PyDict_SetItem(res, __pyx_n_s_is_leaf, member) < 0) goto bad; + Py_DECREF(member); + member = PyFloat_FromDouble(s.radius); if (member == NULL) goto bad; + if (PyDict_SetItem(res, __pyx_n_s_radius, member) < 0) goto bad; + Py_DECREF(member); + return res; + bad: + Py_XDECREF(member); + Py_DECREF(res); + return NULL; + } + static struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t __pyx_convert__from_py___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(PyObject * o) { + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t result; + PyObject *value = NULL; + if (!PyMapping_Check(o)) { + PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "a mapping", Py_TYPE(o)->tp_name); + goto bad; + } + value = PyObject_GetItem(o, __pyx_n_s_idx_start); + if (!value) { + PyErr_Format(PyExc_ValueError, \ + "No value specified for struct attribute '%.200s'", "idx_start"); + goto bad; + } + result.idx_start = __Pyx_PyInt_As_Py_intptr_t(value); + if ((result.idx_start == (npy_intp)-1) && PyErr_Occurred()) + goto bad; + Py_DECREF(value); + value = PyObject_GetItem(o, __pyx_n_s_idx_end); + if (!value) { + PyErr_Format(PyExc_ValueError, \ + "No value specified for struct attribute '%.200s'", "idx_end"); + goto bad; + } + result.idx_end = __Pyx_PyInt_As_Py_intptr_t(value); + if ((result.idx_end == (npy_intp)-1) && PyErr_Occurred()) + goto bad; + Py_DECREF(value); + value = PyObject_GetItem(o, __pyx_n_s_is_leaf); + if (!value) { + PyErr_Format(PyExc_ValueError, \ + "No value specified for struct attribute '%.200s'", "is_leaf"); + goto bad; + } + result.is_leaf = __Pyx_PyInt_As_Py_intptr_t(value); + if ((result.is_leaf == (npy_intp)-1) && PyErr_Occurred()) + goto bad; + Py_DECREF(value); + value = PyObject_GetItem(o, __pyx_n_s_radius); + if (!value) { + PyErr_Format(PyExc_ValueError, \ + "No value specified for struct attribute '%.200s'", "radius"); + goto bad; + } + result.radius = __pyx_PyFloat_AsDouble(value); + if ((result.radius == (npy_float64)-1) && PyErr_Occurred()) + goto bad; + Py_DECREF(value); + return result; +bad: + Py_XDECREF(value); + return result; +} + +static PyObject *__pyx_memview_get_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(const char *itemp) { + return (PyObject *) __pyx_convert__to_py___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(*(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) itemp); +} +static int __pyx_memview_set_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(const char *itemp, PyObject *obj) { + struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t value = __pyx_convert__from_py___pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t(obj); + if (PyErr_Occurred()) + return 0; + *(struct __pyx_t_7sklearn_9neighbors_7kd_tree_NodeData_t *) itemp = value; + return 1; +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +static int +__pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim) +{ + int i, index, step, start; + Py_ssize_t itemsize = mvs->memview->view.itemsize; + if (order == 'F') { + step = 1; + start = 0; + } else { + step = -1; + start = ndim - 1; + } + for (i = 0; i < ndim; i++) { + index = start + step * i; + if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) + return 0; + itemsize *= mvs->shape[index]; + } + return 1; +} + +static void +__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + start = end = slice->data; + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + if (extent == 0) { + *out_start = *out_end = start; + return; + } else { + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); + } + } + *out_start = start; + *out_end = end + itemsize; +} +static int +__pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize) +{ + void *start1, *end1, *start2, *end2; + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + return (start1 < end2) && (start2 < end1); +} + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + for (i = 0; i < ndim; i++) { + if (from_mvs->suboffsets[i] >= 0) { + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; + } + } + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; + } + __Pyx_GOTREF(shape_tuple); + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; + } else { + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; + } + } + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + goto no_fail; +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; +} + +static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) +{ + PyObject *cobj; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); +#endif + return cobj; +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { + const char neg_one = (char) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(char) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to char"); + return (char) -1; + } + return (char) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(char)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (char) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to char"); + return (char) -1; + } + if (sizeof(char) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(char) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(char)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(char) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(char) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(char) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyLong_AsLong) + } else if (sizeof(char) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(char, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + char val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (char) -1; + } + } else { + char val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (char) -1; + val = __Pyx_PyInt_As_char(tmp); + Py_DECREF(tmp); + return val; + } +} + +static struct __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *type) { + struct __pyx_typeinfo_string result = { {0} }; + char *buf = (char *) result.string; + size_t size = type->size; + switch (type->typegroup) { + case 'H': + *buf = 'c'; + break; + case 'I': + case 'U': + if (size == 1) + *buf = 'b'; + else if (size == 2) + *buf = 'h'; + else if (size == 4) + *buf = 'i'; + else if (size == 8) + *buf = 'q'; + if (type->is_unsigned) + *buf = toupper(*buf); + break; + case 'P': + *buf = 'P'; + break; + case 'C': + { + __Pyx_TypeInfo complex_type = *type; + complex_type.typegroup = 'R'; + complex_type.size /= 2; + *buf++ = 'Z'; + *buf = __Pyx_TypeInfoToFormat(&complex_type).string[0]; + break; + } + case 'R': + if (size == 4) + *buf = 'f'; + else if (size == 8) + *buf = 'd'; + else + *buf = 'g'; + break; + } + return result; +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; + } + return (long) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[2]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, + (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, + &__Pyx_TypeInfo_nn_struct___pyx_t_7sklearn_9neighbors_7kd_tree_NodeHeapData_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + #if PY_VERSION_HEX < 0x02050000 + if (PyErr_Warn(NULL, warning) < 0) goto bad; + #else + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + #endif + } + else if ((size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportFunction +#define __PYX_HAVE_RT_ImportFunction +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); + if (!d) + goto bad; + cobj = PyDict_GetItemString(d, funcname); + if (!cobj) { + PyErr_Format(PyExc_ImportError, + "%.200s does not export expected C function %.200s", + PyModule_GetName(module), funcname); + goto bad; + } +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3 && PY_MINOR_VERSION==0) + if (!PyCapsule_IsValid(cobj, sig)) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); + goto bad; + } + tmp.p = PyCapsule_GetPointer(cobj, sig); +#else + {const char *desc, *s1, *s2; + desc = (const char *)PyCObject_GetDesc(cobj); + if (!desc) + goto bad; + s1 = desc; s2 = sig; + while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } + if (*s1 != *s2) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, desc); + goto bad; + } + tmp.p = PyCObject_AsVoidPtr(cobj);} +#endif + *f = tmp.fp; + if (!(*f)) + goto bad; + Py_DECREF(d); + return 0; +bad: + Py_XDECREF(d); + return -1; +} +#endif + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ +#if !CYTHON_COMPILING_IN_PYPY +#if PY_VERSION_HEX >= 0x02060000 + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_MAJOR_VERSION < 3 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%.4s__ returned non-%.4s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + #if PY_VERSION_HEX < 0x02060000 + return PyInt_AsSsize_t(b); + #else + return PyLong_AsSsize_t(b); + #endif + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/neighbors/kd_tree.pyx b/sklearn/neighbors/kd_tree.pyx new file mode 100644 index 0000000000000..be374167dcd40 --- /dev/null +++ b/sklearn/neighbors/kd_tree.pyx @@ -0,0 +1,253 @@ +#!python +#cython: boundscheck=False +#cython: wraparound=False +#cython: cdivision=True + +# By Jake Vanderplas (2013) +# written for the scikit-learn project +# License: BSD + +__all__ = ['KDTree'] + +DOC_DICT = {'BinaryTree': 'KDTree', 'binary_tree': 'kd_tree'} + +VALID_METRICS = ['EuclideanDistance', 'ManhattanDistance', + 'ChebyshevDistance', 'MinkowskiDistance'] + + +# Inherit KDTree from BinaryTree +include "binary_tree.pxi" + +cdef class KDTree(BinaryTree): + __doc__ = CLASS_DOC.format(**DOC_DICT) + pass + +#---------------------------------------------------------------------- +# The functions below specialized the Binary Tree as a KD Tree +# +# Note that these functions use the concept of "reduced distance". +# The reduced distance, defined for some metrics, is a quantity which +# is more efficient to compute than the distance, but preserves the +# relative rankings of the true distance. For example, the reduced +# distance for the Euclidean metric is the squared-euclidean distance. +# For some metrics, the reduced distance is simply the distance. + + +cdef int allocate_data(BinaryTree tree, ITYPE_t n_nodes, + ITYPE_t n_features) except -1: + """Allocate arrays needed for the KD Tree""" + tree.node_bounds_arr = np.zeros((2, n_nodes, n_features), dtype=DTYPE) + tree.node_bounds = get_memview_DTYPE_3D(tree.node_bounds_arr) + return 0 + + +cdef int init_node(BinaryTree tree, ITYPE_t i_node, + ITYPE_t idx_start, ITYPE_t idx_end) except -1: + """Initialize the node for the dataset stored in tree.data""" + cdef ITYPE_t n_features = tree.data.shape[1] + cdef ITYPE_t i, j + cdef DTYPE_t rad = 0 + + cdef DTYPE_t* lower_bounds = &tree.node_bounds[0, i_node, 0] + cdef DTYPE_t* upper_bounds = &tree.node_bounds[1, i_node, 0] + cdef DTYPE_t* data = &tree.data[0, 0] + cdef ITYPE_t* idx_array = &tree.idx_array[0] + + cdef DTYPE_t* data_row + + # determine Node bounds + for j in range(n_features): + lower_bounds[j] = INF + upper_bounds[j] = -INF + + # Compute the actual data range. At build time, this is slightly + # slower than using the previously-computed bounds of the parent node, + # but leads to more compact trees and thus faster queries. + for i in range(idx_start, idx_end): + data_row = data + idx_array[i] * n_features + for j in range(n_features): + lower_bounds[j] = fmin(lower_bounds[j], data_row[j]) + upper_bounds[j] = fmax(upper_bounds[j], data_row[j]) + if tree.dist_metric.p == INF: + rad = fmax(rad, 0.5 * (upper_bounds[j] - lower_bounds[j])) + else: + rad += pow(0.5 * abs(upper_bounds[j] - lower_bounds[j]), + tree.dist_metric.p) + + tree.node_data[i_node].idx_start = idx_start + tree.node_data[i_node].idx_end = idx_end + + # The radius will hold the size of the circumscribed hypersphere measured + # with the specified metric: in querying, this is used as a measure of the + # size of each node when deciding which nodes to split. + tree.node_data[i_node].radius = pow(rad, 1. / tree.dist_metric.p) + return 0 + + +cdef DTYPE_t min_rdist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: + """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 + cdef ITYPE_t j + + if tree.dist_metric.p == INF: + for j in range(n_features): + d_lo = tree.node_bounds[0, i_node, j] - pt[j] + d_hi = pt[j] - tree.node_bounds[1, i_node, j] + d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + rdist = fmax(rdist, 0.5 * d) + else: + # here we'll use the fact that x + abs(x) = 2 * max(x, 0) + for j in range(n_features): + d_lo = tree.node_bounds[0, i_node, j] - pt[j] + d_hi = pt[j] - tree.node_bounds[1, i_node, j] + d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + rdist += pow(0.5 * d, tree.dist_metric.p) + + return rdist + + +cdef DTYPE_t min_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: + """Compute the minimum distance between a point and a node""" + if tree.dist_metric.p == INF: + return min_rdist(tree, i_node, pt) + else: + return pow(min_rdist(tree, i_node, pt), 1. / tree.dist_metric.p) + + +cdef DTYPE_t max_rdist(BinaryTree tree, + ITYPE_t i_node, DTYPE_t* pt) except -1: + """Compute the maximum 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 + cdef ITYPE_t j + + if tree.dist_metric.p == INF: + for j in range(n_features): + rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[0, i_node, j])) + rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[1, i_node, j])) + else: + for j in range(n_features): + d_lo = fabs(pt[j] - tree.node_bounds[0, i_node, j]) + d_hi = fabs(pt[j] - tree.node_bounds[1, i_node, j]) + rdist += pow(fmax(d_lo, d_hi), tree.dist_metric.p) + + return rdist + + +cdef DTYPE_t max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: + """Compute the maximum distance between a point and a node""" + if tree.dist_metric.p == INF: + return max_rdist(tree, i_node, pt) + else: + return pow(max_rdist(tree, i_node, pt), 1. / tree.dist_metric.p) + + +cdef inline int min_max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt, + DTYPE_t* min_dist, DTYPE_t* max_dist) except -1: + """Compute the minimum and maximum distance between a point and a node""" + cdef ITYPE_t n_features = tree.data.shape[1] + + cdef DTYPE_t d, d_lo, d_hi + cdef ITYPE_t j + + min_dist[0] = 0.0 + max_dist[0] = 0.0 + + if tree.dist_metric.p == INF: + for j in range(n_features): + d_lo = tree.node_bounds[0, i_node, j] - pt[j] + d_hi = pt[j] - tree.node_bounds[1, i_node, j] + d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + min_dist[0] = fmax(min_dist[0], 0.5 * d) + max_dist[0] = fmax(max_dist[0], + fabs(pt[j] - tree.node_bounds[0, i_node, j])) + max_dist[0] = fmax(max_dist[0], + fabs(pt[j] - tree.node_bounds[1, i_node, j])) + else: + # as above, use the fact that x + abs(x) = 2 * max(x, 0) + for j in range(n_features): + d_lo = tree.node_bounds[0, i_node, j] - pt[j] + d_hi = pt[j] - tree.node_bounds[1, i_node, j] + d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + min_dist[0] += pow(0.5 * d, tree.dist_metric.p) + max_dist[0] += pow(fmax(fabs(d_lo), fabs(d_hi)), + tree.dist_metric.p) + + min_dist[0] = pow(min_dist[0], 1. / tree.dist_metric.p) + max_dist[0] = pow(max_dist[0], 1. / tree.dist_metric.p) + + return 0 + + +cdef inline DTYPE_t min_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, + BinaryTree tree2, ITYPE_t i_node2) except -1: + """Compute the minimum reduced distance between two nodes""" + cdef ITYPE_t n_features = tree1.data.shape[1] + + cdef DTYPE_t d, d1, d2, rdist=0.0 + cdef DTYPE_t zero = 0.0 + cdef ITYPE_t j + + if tree1.dist_metric.p == INF: + for j in range(n_features): + d1 = (tree1.node_bounds[0, i_node1, j] + - tree2.node_bounds[1, i_node2, j]) + d2 = (tree2.node_bounds[0, i_node2, j] + - tree1.node_bounds[1, i_node1, j]) + d = (d1 + fabs(d1)) + (d2 + fabs(d2)) + + rdist = fmax(rdist, 0.5 * d) + else: + # here we'll use the fact that x + abs(x) = 2 * max(x, 0) + for j in range(n_features): + d1 = (tree1.node_bounds[0, i_node1, j] + - tree2.node_bounds[1, i_node2, j]) + d2 = (tree2.node_bounds[0, i_node2, j] + - tree1.node_bounds[1, i_node1, j]) + d = (d1 + fabs(d1)) + (d2 + fabs(d2)) + + rdist += pow(0.5 * d, tree1.dist_metric.p) + + return rdist + + +cdef inline DTYPE_t min_dist_dual(BinaryTree tree1, ITYPE_t i_node1, + BinaryTree tree2, ITYPE_t i_node2) except -1: + """Compute the minimum distance between two nodes""" + return tree1.dist_metric._rdist_to_dist(min_rdist_dual(tree1, i_node1, + tree2, i_node2)) + + +cdef inline DTYPE_t max_rdist_dual(BinaryTree tree1, ITYPE_t i_node1, + BinaryTree tree2, ITYPE_t i_node2) except -1: + """Compute the maximum reduced distance between two nodes""" + cdef ITYPE_t n_features = tree1.data.shape[1] + + cdef DTYPE_t d, d1, d2, rdist=0.0 + cdef DTYPE_t zero = 0.0 + cdef ITYPE_t j + + if tree1.dist_metric.p == INF: + for j in range(n_features): + rdist = fmax(rdist, fabs(tree1.node_bounds[0, i_node1, j] + - tree2.node_bounds[1, i_node2, j])) + rdist = fmax(rdist, fabs(tree1.node_bounds[1, i_node1, j] + - tree2.node_bounds[0, i_node2, j])) + else: + for j in range(n_features): + d1 = fabs(tree1.node_bounds[0, i_node1, j] + - tree2.node_bounds[1, i_node2, j]) + d2 = fabs(tree1.node_bounds[1, i_node1, j] + - tree2.node_bounds[0, i_node2, j]) + rdist += pow(fmax(d1, d2), tree1.dist_metric.p) + + return rdist + + +cdef inline DTYPE_t max_dist_dual(BinaryTree tree1, ITYPE_t i_node1, + BinaryTree tree2, ITYPE_t i_node2) except -1: + """Compute the maximum distance between two nodes""" + return tree1.dist_metric._rdist_to_dist(max_rdist_dual(tree1, i_node1, + tree2, i_node2)) diff --git a/sklearn/neighbors/kde.py b/sklearn/neighbors/kde.py new file mode 100644 index 0000000000000..8d940264f4374 --- /dev/null +++ b/sklearn/neighbors/kde.py @@ -0,0 +1,214 @@ +""" +Kernel Density Estimation +------------------------- +""" +# Author: Jake Vanderplas + +import numpy as np +from scipy.special import gammainc +from ..base import BaseEstimator +from ..utils import check_array, check_random_state +from ..utils.extmath import row_norms +from .ball_tree import BallTree, DTYPE +from .kd_tree import KDTree + + +VALID_KERNELS = ['gaussian', 'tophat', 'epanechnikov', 'exponential', 'linear', + 'cosine'] +TREE_DICT = {'ball_tree': BallTree, 'kd_tree': KDTree} + + +# TODO: implement a brute force version for testing purposes +# TODO: bandwidth estimation +# TODO: create a density estimation base class? +class KernelDensity(BaseEstimator): + """Kernel Density Estimation + + Parameters + ---------- + bandwidth : float + The bandwidth of the kernel. + + algorithm : string + The tree algorithm to use. Valid options are + ['kd_tree'|'ball_tree'|'auto']. Default is 'auto'. + + kernel : string + The kernel to use. Valid kernels are + ['gaussian'|'tophat'|'epanechnikov'|'exponential'|'linear'|'cosine'] + Default is 'gaussian'. + + metric : string + The distance metric to use. Note that not all metrics are + valid with all algorithms. Refer to the documentation of + :class:`BallTree` and :class:`KDTree` for a description of + available algorithms. Note that the normalization of the density + output is correct only for the Euclidean distance metric. Default + is 'euclidean'. + + atol : float + The desired absolute tolerance of the result. A larger tolerance will + generally lead to faster execution. Default is 0. + + rtol : float + The desired relative tolerance of the result. A larger tolerance will + generally lead to faster execution. Default is 1E-8. + + breadth_first : boolean + If true (default), use a breadth-first approach to the problem. + Otherwise use a depth-first approach. + + leaf_size : int + Specify the leaf size of the underlying tree. See :class:`BallTree` + or :class:`KDTree` for details. Default is 40. + + metric_params : dict + Additional parameters to be passed to the tree for use with the + metric. For more information, see the documentation of + :class:`BallTree` or :class:`KDTree`. + """ + def __init__(self, bandwidth=1.0, algorithm='auto', + kernel='gaussian', metric="euclidean", atol=0, rtol=0, + breadth_first=True, leaf_size=40, metric_params=None): + self.algorithm = algorithm + self.bandwidth = bandwidth + self.kernel = kernel + self.metric = metric + self.atol = atol + self.rtol = rtol + self.breadth_first = breadth_first + self.leaf_size = leaf_size + self.metric_params = metric_params + + # run the choose algorithm code so that exceptions will happen here + # we're using clone() in the GenerativeBayes classifier, + # so we can't do this kind of logic in __init__ + self._choose_algorithm(self.algorithm, self.metric) + + if bandwidth <= 0: + raise ValueError("bandwidth must be positive") + if kernel not in VALID_KERNELS: + raise ValueError("invalid kernel: '{0}'".format(kernel)) + + def _choose_algorithm(self, algorithm, metric): + # given the algorithm string + metric string, choose the optimal + # algorithm to compute the result. + if algorithm == 'auto': + # use KD Tree if possible + if metric in KDTree.valid_metrics: + return 'kd_tree' + elif metric in BallTree.valid_metrics: + return 'ball_tree' + else: + raise ValueError("invalid metric: '{0}'".format(metric)) + elif algorithm in TREE_DICT: + if metric not in TREE_DICT[algorithm].valid_metrics: + raise ValueError("invalid metric for {0}: " + "'{1}'".format(TREE_DICT[algorithm], + metric)) + return algorithm + else: + raise ValueError("invalid algorithm: '{0}'".format(algorithm)) + + def fit(self, X, y=None): + """Fit the Kernel Density model on the data. + + Parameters + ---------- + X : array_like, shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single data point. + """ + algorithm = self._choose_algorithm(self.algorithm, self.metric) + X = check_array(X, order='C', dtype=DTYPE) + + kwargs = self.metric_params + if kwargs is None: + kwargs = {} + self.tree_ = TREE_DICT[algorithm](X, metric=self.metric, + leaf_size=self.leaf_size, + **kwargs) + return self + + def score_samples(self, X): + """Evaluate the density model on the data. + + Parameters + ---------- + X : array_like, shape (n_samples, n_features) + An array of points to query. Last dimension should match dimension + of training data (n_features). + + Returns + ------- + density : ndarray, shape (n_samples,) + The array of log(density) evaluations. + """ + # The returned density is normalized to the number of points. + # For it to be a probability, we must scale it. For this reason + # we'll also scale atol. + X = check_array(X, order='C', dtype=DTYPE) + N = self.tree_.data.shape[0] + atol_N = self.atol * N + log_density = self.tree_.kernel_density( + X, h=self.bandwidth, kernel=self.kernel, atol=atol_N, + rtol=self.rtol, breadth_first=self.breadth_first, return_log=True) + log_density -= np.log(N) + return log_density + + def score(self, X, y=None): + """Compute the total log probability under the model. + + Parameters + ---------- + X : array_like, shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single data point. + + Returns + ------- + logprob : float + Total log-likelihood of the data in X. + """ + return np.sum(self.score_samples(X)) + + def sample(self, n_samples=1, random_state=None): + """Generate random samples from the model. + + Currently, this is implemented only for gaussian and tophat kernels. + + Parameters + ---------- + n_samples : int, optional + Number of samples to generate. Defaults to 1. + + random_state : RandomState or an int seed (0 by default) + A random number generator instance. + + Returns + ------- + X : array_like, shape (n_samples, n_features) + List of samples. + """ + # TODO: implement sampling for other valid kernel shapes + if self.kernel not in ['gaussian', 'tophat']: + raise NotImplementedError() + + data = np.asarray(self.tree_.data) + + rng = check_random_state(random_state) + i = rng.randint(data.shape[0], size=n_samples) + + if self.kernel == 'gaussian': + return np.atleast_2d(rng.normal(data[i], self.bandwidth)) + + elif self.kernel == 'tophat': + # we first draw points from a d-dimensional normal distribution, + # then use an incomplete gamma function to map them to a uniform + # d-dimensional tophat distribution. + dim = data.shape[1] + X = rng.normal(size=(n_samples, dim)) + s_sq = row_norms(X, squared=True) + correction = (gammainc(0.5 * dim, 0.5 * s_sq) ** (1. / dim) + * self.bandwidth / np.sqrt(s_sq)) + return data[i] + X * correction[:, np.newaxis] diff --git a/sklearn/neighbors/nearest_centroid.py b/sklearn/neighbors/nearest_centroid.py index 5a9d0c1a6ca89..b10c05e6fcd84 100644 --- a/sklearn/neighbors/nearest_centroid.py +++ b/sklearn/neighbors/nearest_centroid.py @@ -6,14 +6,18 @@ # Author: Robert Layton # Olivier Grisel # -# License: BSD Style. +# License: BSD 3 clause +import warnings import numpy as np from scipy import sparse as sp from ..base import BaseEstimator, ClassifierMixin -from ..utils.validation import check_arrays, atleast2d_or_csr +from ..externals.six.moves import xrange from ..metrics.pairwise import pairwise_distances +from ..preprocessing import LabelEncoder +from ..utils.validation import check_array, check_X_y, check_is_fitted +from ..utils.sparsefuncs import csc_median_axis_0 class NearestCentroid(BaseEstimator, ClassifierMixin): @@ -29,12 +33,18 @@ class NearestCentroid(BaseEstimator, ClassifierMixin): feature array. If metric is a string or callable, it must be one of the options allowed by metrics.pairwise.pairwise_distances for its metric parameter. + The centroids for the samples corresponding to each class is the point + from which the sum of the distances (according to the metric) of all + samples that belong to that particular class are minimized. + If the "manhattan" metric is provided, this centroid is the median and + for all other metrics, the centroid is now set to be the mean. + shrink_threshold : float, optional (default = None) Threshold for shrinking centroids to remove features. Attributes ---------- - `centroids_` : array-like, shape = [n_classes, n_features] + centroids_ : array-like, shape = [n_classes, n_features] Centroid of each class Examples @@ -46,7 +56,7 @@ class NearestCentroid(BaseEstimator, ClassifierMixin): >>> clf = NearestCentroid() >>> clf.fit(X, y) NearestCentroid(metric='euclidean', shrink_threshold=None) - >>> print clf.predict([[-0.8, -1]]) + >>> print(clf.predict([[-0.8, -1]])) [1] See also @@ -55,7 +65,7 @@ class NearestCentroid(BaseEstimator, ClassifierMixin): Notes ----- - When used for text classification with tf–idf vectors, this classifier is + When used for text classification with tf-idf vectors, this classifier is also known as the Rocchio classifier. References @@ -84,35 +94,58 @@ def fit(self, X, y): y : array, shape = [n_samples] Target values (integers) """ - X, y = check_arrays(X, y, sparse_format="csr") - if sp.issparse(X) and self.shrink_threshold: + # If X is sparse and the metric is "manhattan", store it in a csc + # format is easier to calculate the median. + if self.metric == 'manhattan': + X, y = check_X_y(X, y, ['csc']) + else: + X, y = check_X_y(X, y, ['csr', 'csc']) + is_X_sparse = sp.issparse(X) + if is_X_sparse and self.shrink_threshold: raise ValueError("threshold shrinking not supported" " for sparse input") n_samples, n_features = X.shape - classes = np.unique(y) - self.classes_ = classes + le = LabelEncoder() + y_ind = le.fit_transform(y) + self.classes_ = classes = le.classes_ n_classes = classes.size if n_classes < 2: raise ValueError('y has less than 2 classes') # Mask mapping each class to it's members. self.centroids_ = np.empty((n_classes, n_features), dtype=np.float64) - for i, cur_class in enumerate(classes): - center_mask = y == cur_class - if sp.issparse(X): + # Number of clusters in each class. + nk = np.zeros(n_classes) + + for cur_class in range(n_classes): + center_mask = y_ind == cur_class + nk[cur_class] = np.sum(center_mask) + if is_X_sparse: center_mask = np.where(center_mask)[0] - self.centroids_[i] = X[center_mask].mean(axis=0) + + # XXX: Update other averaging methods according to the metrics. + if self.metric == "manhattan": + # NumPy does not calculate median of sparse matrices. + if not is_X_sparse: + self.centroids_[cur_class] = np.median(X[center_mask], axis=0) + else: + self.centroids_[cur_class] = csc_median_axis_0(X[center_mask]) + else: + if self.metric != 'euclidean': + warnings.warn("Averaging for metrics other than " + "euclidean and manhattan not supported. " + "The average is set to be the mean." + ) + self.centroids_[cur_class] = X[center_mask].mean(axis=0) if self.shrink_threshold: - dataset_centroid_ = np.array(X.mean(axis=0))[0] - # Number of clusters in each class. - nk = np.array([np.sum(classes == cur_class) - for cur_class in classes]) + dataset_centroid_ = np.mean(X, axis=0) + # m parameter for determining deviation m = np.sqrt((1. / nk) + (1. / n_samples)) # Calculate deviation using the standard deviation of centroids. - variance = np.array(np.power(X - self.centroids_[y], 2)) + variance = (X - self.centroids_[y_ind]) ** 2 variance = variance.sum(axis=0) s = np.sqrt(variance / (n_samples - n_classes)) s += np.median(s) # To deter outliers from affecting the results. @@ -124,11 +157,10 @@ def fit(self, X, y): signs = np.sign(deviation) deviation = (np.abs(deviation) - self.shrink_threshold) deviation[deviation < 0] = 0 - deviation = np.multiply(deviation, signs) + deviation *= signs # Now adjust the centroids using the deviation - msd = np.multiply(ms, deviation) - self.centroids_ = np.array([dataset_centroid_ + msd[i] - for i in xrange(n_classes)]) + msd = ms * deviation + self.centroids_ = dataset_centroid_[np.newaxis, :] + msd return self def predict(self, X): @@ -150,8 +182,8 @@ def predict(self, X): be the distance matrix between the data to be predicted and ``self.centroids_``. """ - X = atleast2d_or_csr(X) - if not hasattr(self, "centroids_"): - raise AttributeError("Model has not been trained yet.") + check_is_fitted(self, 'centroids_') + + X = check_array(X, accept_sparse='csr') return self.classes_[pairwise_distances( X, self.centroids_, metric=self.metric).argmin(axis=1)] diff --git a/sklearn/neighbors/regression.py b/sklearn/neighbors/regression.py index e554205a01bd9..a6285c77d9fef 100644 --- a/sklearn/neighbors/regression.py +++ b/sklearn/neighbors/regression.py @@ -4,17 +4,16 @@ # Fabian Pedregosa # Alexandre Gramfort # Sparseness support by Lars Buitinck +# Multi-output support by Arnaud Joly # -# License: BSD, (C) INRIA, University of Amsterdam +# License: BSD 3 clause (C) INRIA, University of Amsterdam import numpy as np -from .base import \ - _get_weights, _check_weights, \ - NeighborsBase, KNeighborsMixin, \ - RadiusNeighborsMixin, SupervisedFloatMixin +from .base import _get_weights, _check_weights, NeighborsBase, KNeighborsMixin +from .base import RadiusNeighborsMixin, SupervisedFloatMixin from ..base import RegressorMixin -from ..utils import atleast2d_or_csr +from ..utils import check_array class KNeighborsRegressor(NeighborsBase, KNeighborsMixin, @@ -48,7 +47,7 @@ class KNeighborsRegressor(NeighborsBase, KNeighborsMixin, Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - - 'kd_tree' will use :class:`scipy.spatial.cKDtree` + - 'kd_tree' will use :class:`KDtree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. @@ -57,25 +56,25 @@ class KNeighborsRegressor(NeighborsBase, KNeighborsMixin, this parameter, using brute force. leaf_size : int, optional (default = 30) - Leaf size passed to BallTree or cKDTree. This can affect the + Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. - warn_on_equidistant : boolean, optional. Defaults to True. - Generate a warning if equidistant neighbors are discarded. - For classification or regression based on k-neighbors, if - neighbor k and neighbor k+1 have identical distances but - different labels, then the result will be dependent on the - ordering of the training data. - If the fit method is ``'kd_tree'``, no warnings will be generated. - - p: integer, optional (default = 2) - Parameter for the Minkowski metric from - sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is + metric : string or DistanceMetric object (default='minkowski') + the distance metric to use for the tree. The default metric is + minkowski, and with p=2 is equivalent to the standard Euclidean + metric. See the documentation of the DistanceMetric class for a + list of available metrics. + + p : integer, optional (default = 2) + Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + metric_params: dict, optional (default = None) + additional keyword arguments for the metric function. + Examples -------- >>> X = [[0], [1], [2], [3]] @@ -99,17 +98,23 @@ class KNeighborsRegressor(NeighborsBase, KNeighborsMixin, See :ref:`Nearest Neighbors ` in the online documentation for a discussion of the choice of ``algorithm`` and ``leaf_size``. + .. warning:: + + Regarding the Nearest Neighbors algorithms, if it is found that two + neighbors, neighbor `k+1` and `k`, have identical distances but + but different labels, the results will depend on the ordering of the + training data. + http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm """ def __init__(self, n_neighbors=5, weights='uniform', - algorithm='auto', leaf_size=30, warn_on_equidistant=True, - p=2): + algorithm='auto', leaf_size=30, + p=2, metric='minkowski', metric_params=None, **kwargs): self._init_params(n_neighbors=n_neighbors, algorithm=algorithm, - leaf_size=leaf_size, - warn_on_equidistant=warn_on_equidistant, - p=p) + leaf_size=leaf_size, metric=metric, p=p, + metric_params=metric_params, **kwargs) self.weights = _check_weights(weights) def predict(self, X): @@ -117,26 +122,38 @@ def predict(self, X): Parameters ---------- - X : array - A 2-D array representing the test data. + X : array or matrix, shape = [n_samples, n_features] + Returns ------- - y: array - List of target values (one for each data sample). + y : array of int, shape = [n_samples] or [n_samples, n_outputs] + Target values """ - X = atleast2d_or_csr(X) + X = check_array(X, accept_sparse='csr') neigh_dist, neigh_ind = self.kneighbors(X) weights = _get_weights(neigh_dist, self.weights) + _y = self._y + if _y.ndim == 1: + _y = _y.reshape((-1, 1)) + if weights is None: - return np.mean(self._y[neigh_ind], axis=1) + y_pred = np.mean(_y[neigh_ind], axis=1) else: - num = np.sum(self._y[neigh_ind] * weights, axis=1) + y_pred = np.empty((X.shape[0], _y.shape[1]), dtype=np.float) denom = np.sum(weights, axis=1) - return num / denom + + for j in range(_y.shape[1]): + num = np.sum(_y[neigh_ind, j] * weights, axis=1) + y_pred[:, j] = num / denom + + if self._y.ndim == 1: + y_pred = y_pred.ravel() + + return y_pred class RadiusNeighborsRegressor(NeighborsBase, RadiusNeighborsMixin, @@ -171,7 +188,7 @@ class RadiusNeighborsRegressor(NeighborsBase, RadiusNeighborsMixin, Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - - 'kd_tree' will use :class:`scipy.spatial.cKDtree` + - 'kd_tree' will use :class:`KDtree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. @@ -180,17 +197,24 @@ class RadiusNeighborsRegressor(NeighborsBase, RadiusNeighborsMixin, this parameter, using brute force. leaf_size : int, optional (default = 30) - Leaf size passed to BallTree or cKDTree. This can affect the + Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. - p: integer, optional (default = 2) - Parameter for the Minkowski metric from - sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is + metric : string or DistanceMetric object (default='minkowski') + the distance metric to use for the tree. The default metric is + minkowski, and with p=2 is equivalent to the standard Euclidean + metric. See the documentation of the DistanceMetric class for a + list of available metrics. + + p : integer, optional (default = 2) + Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + metric_params: dict, optional (default = None) + additional keyword arguments for the metric function. Examples -------- @@ -219,11 +243,13 @@ class RadiusNeighborsRegressor(NeighborsBase, RadiusNeighborsMixin, """ def __init__(self, radius=1.0, weights='uniform', - algorithm='auto', leaf_size=30, p=2): + algorithm='auto', leaf_size=30, + p=2, metric='minkowski', metric_params=None, **kwargs): self._init_params(radius=radius, algorithm=algorithm, leaf_size=leaf_size, - p=p) + p=p, metric=metric, metric_params=metric_params, + **kwargs) self.weights = _check_weights(weights) def predict(self, X): @@ -231,24 +257,32 @@ def predict(self, X): Parameters ---------- - X : array - A 2-D array representing the test data. + X : array or matrix, shape = [n_samples, n_features] Returns ------- - y: array - List of target values (one for each data sample). + y : array of int, shape = [n_samples] or [n_samples, n_outputs] + Target values """ - X = atleast2d_or_csr(X) + X = check_array(X, accept_sparse='csr') neigh_dist, neigh_ind = self.radius_neighbors(X) weights = _get_weights(neigh_dist, self.weights) + _y = self._y + if _y.ndim == 1: + _y = _y.reshape((-1, 1)) + if weights is None: - return np.array([np.mean(self._y[ind]) - for ind in neigh_ind]) + y_pred = np.array([np.mean(_y[ind, :], axis=0) + for ind in neigh_ind]) else: - return np.array([(np.sum(self._y[ind] * weights[i]) - / np.sum(weights[i])) - for (i, ind) in enumerate(neigh_ind)]) + y_pred = np.array([(np.average(_y[ind, :], axis=0, + weights=weights[i])) + for (i, ind) in enumerate(neigh_ind)]) + + if self._y.ndim == 1: + y_pred = y_pred.ravel() + + return y_pred diff --git a/sklearn/neighbors/setup.py b/sklearn/neighbors/setup.py index 9ea4b6e741755..2ddfb8cf34551 100644 --- a/sklearn/neighbors/setup.py +++ b/sklearn/neighbors/setup.py @@ -15,4 +15,21 @@ def configuration(parent_package='', top_path=None): include_dirs=[numpy.get_include()], libraries=libraries) + config.add_extension('kd_tree', + sources=['kd_tree.c'], + include_dirs=[numpy.get_include()], + libraries=libraries) + + config.add_extension('dist_metrics', + sources=['dist_metrics.c'], + include_dirs=[numpy.get_include(), + os.path.join(numpy.get_include(), + 'numpy')], + libraries=libraries) + + config.add_extension('typedefs', + sources=['typedefs.c'], + include_dirs=[numpy.get_include()], + libraries=libraries) + return config diff --git a/sklearn/neighbors/tests/test_approximate.py b/sklearn/neighbors/tests/test_approximate.py new file mode 100644 index 0000000000000..4192934a49a2f --- /dev/null +++ b/sklearn/neighbors/tests/test_approximate.py @@ -0,0 +1,485 @@ +""" +Testing for the approximate neighbor search using +Locality Sensitive Hashing Forest module +(sklearn.neighbors.LSHForest). +""" + +# Author: Maheshakya Wijewardena, Joel Nothman + +import numpy as np +import scipy.sparse as sp + +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_array_less +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_not_equal +from sklearn.utils.testing import assert_warns_message +from sklearn.utils.testing import ignore_warnings + +from sklearn.metrics.pairwise import pairwise_distances +from sklearn.neighbors import LSHForest +from sklearn.neighbors import NearestNeighbors + + +def test_neighbors_accuracy_with_n_candidates(): + """Checks whether accuracy increases as `n_candidates` increases.""" + n_candidates_values = np.array([.1, 50, 500]) + n_samples = 100 + n_features = 10 + n_iter = 10 + n_points = 5 + rng = np.random.RandomState(42) + accuracies = np.zeros(n_candidates_values.shape[0], dtype=float) + X = rng.rand(n_samples, n_features) + + for i, n_candidates in enumerate(n_candidates_values): + lshf = LSHForest(n_candidates=n_candidates) + lshf.fit(X) + for j in range(n_iter): + query = X[rng.randint(0, n_samples)] + neighbors = lshf.kneighbors(query, n_neighbors=n_points, + return_distance=False) + distances = pairwise_distances(query, X, metric='cosine') + ranks = np.argsort(distances)[0, :n_points] + + intersection = np.intersect1d(ranks, neighbors).shape[0] + ratio = intersection / float(n_points) + accuracies[i] = accuracies[i] + ratio + + accuracies[i] = accuracies[i] / float(n_iter) + # Sorted accuracies should be equal to original accuracies + assert_true(np.all(np.diff(accuracies) >= 0), + msg="Accuracies are not non-decreasing.") + # Highest accuracy should be strictly greater than the lowest + assert_true(np.ptp(accuracies) > 0, + msg="Highest accuracy is not strictly greater than lowest.") + + +def test_neighbors_accuracy_with_n_estimators(): + """Checks whether accuracy increases as `n_estimators` increases.""" + n_estimators = np.array([1, 10, 100]) + n_samples = 100 + n_features = 10 + n_iter = 10 + n_points = 5 + rng = np.random.RandomState(42) + accuracies = np.zeros(n_estimators.shape[0], dtype=float) + X = rng.rand(n_samples, n_features) + + for i, t in enumerate(n_estimators): + lshf = LSHForest(n_candidates=500, n_estimators=t) + lshf.fit(X) + for j in range(n_iter): + query = X[rng.randint(0, n_samples)] + neighbors = lshf.kneighbors(query, n_neighbors=n_points, + return_distance=False) + distances = pairwise_distances(query, X, metric='cosine') + ranks = np.argsort(distances)[0, :n_points] + + intersection = np.intersect1d(ranks, neighbors).shape[0] + ratio = intersection / float(n_points) + accuracies[i] = accuracies[i] + ratio + + accuracies[i] = accuracies[i] / float(n_iter) + # Sorted accuracies should be equal to original accuracies + assert_true(np.all(np.diff(accuracies) >= 0), + msg="Accuracies are not non-decreasing.") + # Highest accuracy should be strictly greater than the lowest + assert_true(np.ptp(accuracies) > 0, + msg="Highest accuracy is not strictly greater than lowest.") + + +@ignore_warnings +def test_kneighbors(): + """Checks whether desired number of neighbors are returned. + + It is guaranteed to return the requested number of neighbors + if `min_hash_match` is set to 0. Returned distances should be + in ascending order. + """ + n_samples = 12 + n_features = 2 + n_iter = 10 + rng = np.random.RandomState(42) + X = rng.rand(n_samples, n_features) + + lshf = LSHForest(min_hash_match=0) + # Test unfitted estimator + assert_raises(ValueError, lshf.kneighbors, X[0]) + + lshf.fit(X) + + for i in range(n_iter): + n_neighbors = rng.randint(0, n_samples) + query = X[rng.randint(0, n_samples)] + neighbors = lshf.kneighbors(query, n_neighbors=n_neighbors, + return_distance=False) + # Desired number of neighbors should be returned. + assert_equal(neighbors.shape[1], n_neighbors) + + # Multiple points + n_queries = 5 + queries = X[rng.randint(0, n_samples, n_queries)] + distances, neighbors = lshf.kneighbors(queries, + n_neighbors=1, + return_distance=True) + assert_equal(neighbors.shape[0], n_queries) + assert_equal(distances.shape[0], n_queries) + # Test only neighbors + neighbors = lshf.kneighbors(queries, n_neighbors=1, + return_distance=False) + assert_equal(neighbors.shape[0], n_queries) + # Test random point(not in the data set) + query = rng.randn(n_features) + lshf.kneighbors(query, n_neighbors=1, + return_distance=False) + # Test n_neighbors at initialization + neighbors = lshf.kneighbors(query, return_distance=False) + assert_equal(neighbors.shape[1], 5) + # Test `neighbors` has an integer dtype + assert_true(neighbors.dtype.kind == 'i', + msg="neighbors are not in integer dtype.") + + +def test_radius_neighbors(): + """Checks whether Returned distances are less than `radius` + + At least one point should be returned when the `radius` is set + to mean distance from the considering point to other points in + the database. + Moreover, this test compares the radius neighbors of LSHForest + with the `sklearn.neighbors.NearestNeighbors`. + """ + n_samples = 12 + n_features = 2 + n_iter = 10 + rng = np.random.RandomState(42) + X = rng.rand(n_samples, n_features) + + lshf = LSHForest() + # Test unfitted estimator + assert_raises(ValueError, lshf.radius_neighbors, X[0]) + + lshf.fit(X) + + for i in range(n_iter): + # Select a random point in the dataset as the query + query = X[rng.randint(0, n_samples)] + + # At least one neighbor should be returned when the radius is the + # mean distance from the query to the points of the dataset. + mean_dist = np.mean(pairwise_distances(query, X, metric='cosine')) + neighbors = lshf.radius_neighbors(query, radius=mean_dist, + return_distance=False) + + assert_equal(neighbors.shape, (1,)) + assert_equal(neighbors.dtype, object) + assert_greater(neighbors[0].shape[0], 0) + # All distances to points in the results of the radius query should + # be less than mean_dist + distances, neighbors = lshf.radius_neighbors(query, + radius=mean_dist, + return_distance=True) + assert_array_less(distances[0], mean_dist) + + # Multiple points + n_queries = 5 + queries = X[rng.randint(0, n_samples, n_queries)] + distances, neighbors = lshf.radius_neighbors(queries, + return_distance=True) + + # dists and inds should not be 1D arrays or arrays of variable lengths + # hence the use of the object dtype. + assert_equal(distances.shape, (n_queries,)) + assert_equal(distances.dtype, object) + assert_equal(neighbors.shape, (n_queries,)) + assert_equal(neighbors.dtype, object) + + # Compare with exact neighbor search + query = X[rng.randint(0, n_samples)] + mean_dist = np.mean(pairwise_distances(query, X, metric='cosine')) + nbrs = NearestNeighbors(algorithm='brute', metric='cosine').fit(X) + + distances_exact, _ = nbrs.radius_neighbors(query, radius=mean_dist) + distances_approx, _ = lshf.radius_neighbors(query, radius=mean_dist) + + # Radius-based queries do not sort the result points and the order + # depends on the method, the random_state and the dataset order. Therefore + # we need to sort the results ourselves before performing any comparison. + sorted_dists_exact = np.sort(distances_exact[0]) + sorted_dists_approx = np.sort(distances_approx[0]) + + # Distances to exact neighbors are less than or equal to approximate + # counterparts as the approximate radius query might have missed some + # closer neighbors. + assert_true(np.all(np.less_equal(sorted_dists_exact, + sorted_dists_approx))) + + +def test_radius_neighbors_boundary_handling(): + X = [[0.999, 0.001], [0.5, 0.5], [0, 1.], [-1., 0.001]] + n_points = len(X) + + # Build an exact nearest neighbors model as reference model to ensure + # consistency between exact and approximate methods + nnbrs = NearestNeighbors(algorithm='brute', metric='cosine').fit(X) + + # Build a LSHForest model with hyperparameter values that always guarantee + # exact results on this toy dataset. + lsfh = LSHForest(min_hash_match=0, n_candidates=n_points).fit(X) + + # define a query aligned with the first axis + query = [1., 0.] + + # Compute the exact cosine distances of the query to the four points of + # the dataset + dists = pairwise_distances(query, X, metric='cosine').ravel() + + # The first point is almost aligned with the query (very small angle), + # the cosine distance should therefore be almost null: + assert_almost_equal(dists[0], 0, decimal=5) + + # The second point form an angle of 45 degrees to the query vector + assert_almost_equal(dists[1], 1 - np.cos(np.pi / 4)) + + # The third point is orthogonal from the query vector hence at a distance + # exactly one: + assert_almost_equal(dists[2], 1) + + # The last point is almost colinear but with opposite sign to the query + # therefore it has a cosine 'distance' very close to the maximum possible + # value of 2. + assert_almost_equal(dists[3], 2, decimal=5) + + # If we query with a radius of one, all the samples except the last sample + # should be included in the results. This means that the third sample + # is lying on the boundary of the radius query: + exact_dists, exact_idx = nnbrs.radius_neighbors(query, radius=1) + approx_dists, approx_idx = lsfh.radius_neighbors(query, radius=1) + + assert_array_equal(np.sort(exact_idx[0]), [0, 1, 2]) + assert_array_equal(np.sort(approx_idx[0]), [0, 1, 2]) + assert_array_almost_equal(np.sort(exact_dists[0]), dists[:-1]) + assert_array_almost_equal(np.sort(approx_dists[0]), dists[:-1]) + + # If we perform the same query with a slighltly lower radius, the third + # point of the dataset that lay on the boundary of the previous query + # is now rejected: + eps = np.finfo(np.float64).eps + exact_dists, exact_idx = nnbrs.radius_neighbors(query, radius=1 - eps) + approx_dists, approx_idx = lsfh.radius_neighbors(query, radius=1 - eps) + + assert_array_equal(np.sort(exact_idx[0]), [0, 1]) + assert_array_equal(np.sort(approx_idx[0]), [0, 1]) + assert_array_almost_equal(np.sort(exact_dists[0]), dists[:-2]) + assert_array_almost_equal(np.sort(approx_dists[0]), dists[:-2]) + + +def test_distances(): + """Checks whether returned neighbors are from closest to farthest.""" + n_samples = 12 + n_features = 2 + n_iter = 10 + rng = np.random.RandomState(42) + X = rng.rand(n_samples, n_features) + + lshf = LSHForest() + lshf.fit(X) + + for i in range(n_iter): + n_neighbors = rng.randint(0, n_samples) + query = X[rng.randint(0, n_samples)] + distances, neighbors = lshf.kneighbors(query, + n_neighbors=n_neighbors, + return_distance=True) + + # Returned neighbors should be from closest to farthest, that is + # increasing distance values. + assert_true(np.all(np.diff(distances[0]) >= 0)) + + # Note: the radius_neighbors method does not guarantee the order of + # the results. + + +def test_fit(): + """Checks whether `fit` method sets all attribute values correctly.""" + n_samples = 12 + n_features = 2 + n_estimators = 5 + rng = np.random.RandomState(42) + X = rng.rand(n_samples, n_features) + + lshf = LSHForest(n_estimators=n_estimators) + lshf.fit(X) + + # _input_array = X + assert_array_equal(X, lshf._fit_X) + # A hash function g(p) for each tree + assert_equal(n_estimators, len(lshf.hash_functions_)) + # Hash length = 32 + assert_equal(32, lshf.hash_functions_[0].components_.shape[0]) + # Number of trees_ in the forest + assert_equal(n_estimators, len(lshf.trees_)) + # Each tree has entries for every data point + assert_equal(n_samples, len(lshf.trees_[0])) + # Original indices after sorting the hashes + assert_equal(n_estimators, len(lshf.original_indices_)) + # Each set of original indices in a tree has entries for every data point + assert_equal(n_samples, len(lshf.original_indices_[0])) + + +def test_partial_fit(): + """Checks whether inserting array is consitent with fitted data. + + `partial_fit` method should set all attribute values correctly. + """ + n_samples = 12 + n_samples_partial_fit = 3 + n_features = 2 + rng = np.random.RandomState(42) + X = rng.rand(n_samples, n_features) + X_partial_fit = rng.rand(n_samples_partial_fit, n_features) + + lshf = LSHForest() + + # Test unfitted estimator + lshf.partial_fit(X) + assert_array_equal(X, lshf._fit_X) + + lshf.fit(X) + + # Insert wrong dimension + assert_raises(ValueError, lshf.partial_fit, + np.random.randn(n_samples_partial_fit, n_features - 1)) + + lshf.partial_fit(X_partial_fit) + + # size of _input_array = samples + 1 after insertion + assert_equal(lshf._fit_X.shape[0], + n_samples + n_samples_partial_fit) + # size of original_indices_[1] = samples + 1 + assert_equal(len(lshf.original_indices_[0]), + n_samples + n_samples_partial_fit) + # size of trees_[1] = samples + 1 + assert_equal(len(lshf.trees_[1]), + n_samples + n_samples_partial_fit) + + +def test_hash_functions(): + """Checks randomness of hash functions. + + Variance and mean of each hash function (projection vector) + should be different from flattened array of hash functions. + If hash functions are not randomly built (seeded with + same value), variances and means of all functions are equal. + """ + n_samples = 12 + n_features = 2 + n_estimators = 5 + rng = np.random.RandomState(42) + X = rng.rand(n_samples, n_features) + + lshf = LSHForest(n_estimators=n_estimators, + random_state=rng.randint(0, np.iinfo(np.int32).max)) + lshf.fit(X) + + hash_functions = [] + for i in range(n_estimators): + hash_functions.append(lshf.hash_functions_[i].components_) + + for i in range(n_estimators): + assert_not_equal(np.var(hash_functions), + np.var(lshf.hash_functions_[i].components_)) + + for i in range(n_estimators): + assert_not_equal(np.mean(hash_functions), + np.mean(lshf.hash_functions_[i].components_)) + + +def test_candidates(): + """Checks whether candidates are sufficient. + + This should handle the cases when number of candidates is 0. + User should be warned when number of candidates is less than + requested number of neighbors. + """ + X_train = np.array([[5, 5, 2], [21, 5, 5], [1, 1, 1], [8, 9, 1], + [6, 10, 2]], dtype=np.float32) + X_test = np.array([7, 10, 3], dtype=np.float32) + + # For zero candidates + lshf = LSHForest(min_hash_match=32) + lshf.fit(X_train) + + message = ("Number of candidates is not sufficient to retrieve" + " %i neighbors with" + " min_hash_match = %i. Candidates are filled up" + " uniformly from unselected" + " indices." % (3, 32)) + assert_warns_message(UserWarning, message, lshf.kneighbors, + X_test, n_neighbors=3) + distances, neighbors = lshf.kneighbors(X_test, n_neighbors=3) + assert_equal(distances.shape[1], 3) + + # For candidates less than n_neighbors + lshf = LSHForest(min_hash_match=31) + lshf.fit(X_train) + + message = ("Number of candidates is not sufficient to retrieve" + " %i neighbors with" + " min_hash_match = %i. Candidates are filled up" + " uniformly from unselected" + " indices." % (5, 31)) + assert_warns_message(UserWarning, message, lshf.kneighbors, + X_test, n_neighbors=5) + distances, neighbors = lshf.kneighbors(X_test, n_neighbors=5) + assert_equal(distances.shape[1], 5) + + +def test_graphs(): + """Smoke tests for graph methods.""" + n_samples_sizes = [5, 10, 20] + n_features = 3 + rng = np.random.RandomState(42) + + for n_samples in n_samples_sizes: + X = rng.rand(n_samples, n_features) + lshf = LSHForest(min_hash_match=0) + lshf.fit(X) + + kneighbors_graph = lshf.kneighbors_graph(X) + radius_neighbors_graph = lshf.radius_neighbors_graph(X) + + assert_equal(kneighbors_graph.shape[0], n_samples) + assert_equal(kneighbors_graph.shape[1], n_samples) + assert_equal(radius_neighbors_graph.shape[0], n_samples) + assert_equal(radius_neighbors_graph.shape[1], n_samples) + + +def test_sparse_input(): + # note: Fixed random state in sp.rand is not supported in older scipy. + # The test should succeed regardless. + X1 = sp.rand(50, 100) + X2 = sp.rand(10, 100) + forest_sparse = LSHForest(radius=1, random_state=0).fit(X1) + forest_dense = LSHForest(radius=1, random_state=0).fit(X1.A) + + d_sparse, i_sparse = forest_sparse.kneighbors(X2, return_distance=True) + d_dense, i_dense = forest_dense.kneighbors(X2.A, return_distance=True) + assert_array_equal(d_sparse, d_dense) + assert_array_equal(i_sparse, i_dense) + + d_sparse, i_sparse = forest_sparse.radius_neighbors(X2, + return_distance=True) + d_dense, i_dense = forest_dense.radius_neighbors(X2.A, + return_distance=True) + assert_equal(d_sparse.shape, d_dense.shape) + for a, b in zip(d_sparse, d_dense): + assert_array_equal(a, b) + for a, b in zip(i_sparse, i_dense): + assert_array_equal(a, b) diff --git a/sklearn/neighbors/tests/test_ball_tree.py b/sklearn/neighbors/tests/test_ball_tree.py index 891f80960d636..0c248fdadb7ce 100644 --- a/sklearn/neighbors/tests/test_ball_tree.py +++ b/sklearn/neighbors/tests/test_ball_tree.py @@ -1,50 +1,104 @@ import numpy as np from numpy.testing import assert_array_almost_equal +from sklearn.neighbors.ball_tree import (BallTree, NeighborsHeap, + simultaneous_sort, kernel_norm, + nodeheap_sort, DTYPE, ITYPE) +from sklearn.neighbors.dist_metrics import DistanceMetric +from sklearn.utils.testing import SkipTest, assert_allclose + +rng = np.random.RandomState(10) +V = rng.rand(3, 3) +V = np.dot(V, V.T) + +DIMENSION = 3 + +METRICS = {'euclidean': {}, + 'manhattan': {}, + 'minkowski': dict(p=3), + 'chebyshev': {}, + 'seuclidean': dict(V=np.random.random(DIMENSION)), + 'wminkowski': dict(p=3, w=np.random.random(DIMENSION)), + 'mahalanobis': dict(V=V)} + +DISCRETE_METRICS = ['hamming', + 'canberra', + 'braycurtis'] + +BOOLEAN_METRICS = ['matching', 'jaccard', 'dice', 'kulsinski', + 'rogerstanimoto', 'russellrao', 'sokalmichener', + 'sokalsneath'] + + +def brute_force_neighbors(X, Y, k, metric, **kwargs): + D = DistanceMetric.get_metric(metric, **kwargs).pairwise(Y, X) + ind = np.argsort(D, axis=1)[:, :k] + dist = D[np.arange(Y.shape[0])[:, None], ind] + return dist, ind + + +def test_ball_tree_query(): + np.random.seed(0) + X = np.random.random((40, DIMENSION)) + Y = np.random.random((10, DIMENSION)) + + def check_neighbors(dualtree, breadth_first, k, metric, kwargs): + bt = BallTree(X, leaf_size=1, metric=metric, **kwargs) + dist1, ind1 = bt.query(Y, k, dualtree=dualtree, + breadth_first=breadth_first) + dist2, ind2 = brute_force_neighbors(X, Y, k, metric, **kwargs) + + # don't check indices here: if there are any duplicate distances, + # the indices may not match. Distances should not have this problem. + assert_array_almost_equal(dist1, dist2) -from scipy.spatial import cKDTree - -from sklearn import neighbors - -# Note: simple tests of BallTree.query() and BallTree.query_radius() -# are contained within the tests of test_neighbors.py - -rng = np.random.RandomState(0) - - -def test_warning_flag(n_samples=100, n_features=3, k=3): - """test that discarding identical distances triggers warning flag""" - X = rng.random_sample(size=(n_samples, n_features)) - q = rng.random_sample(size=n_features) - bt = neighbors.BallTree(X[:-1], leaf_size=5) - dist, ind = bt.query(q, k=k) - - # make the last point identical to the furthest neighbor - # querying this should set warning_flag to True - X[-1:] = X[ind[0, k - 1]] + for (metric, kwargs) in METRICS.items(): + for k in (1, 3, 5): + for dualtree in (True, False): + for breadth_first in (True, False): + yield (check_neighbors, + dualtree, breadth_first, + k, metric, kwargs) + + +def test_ball_tree_query_boolean_metrics(): + np.random.seed(0) + X = np.random.random((40, 10)).round(0) + Y = np.random.random((10, 10)).round(0) + k = 5 + + def check_neighbors(metric): + bt = BallTree(X, leaf_size=1, metric=metric) + dist1, ind1 = bt.query(Y, k) + dist2, ind2 = brute_force_neighbors(X, Y, k, metric) + assert_array_almost_equal(dist1, dist2) - bt = neighbors.BallTree(X, leaf_size=5) - dist, ind = bt.query(q, k=k) + for metric in BOOLEAN_METRICS: + yield check_neighbors, metric - assert bt.warning_flag - # make the last point identical to the closest neighbor - # though the distance is identical, there is no ambiguity, so there - # should be no warning. If k==1, this should not be done - if k > 1: - X[-1:] = X[ind[0, 0]] +def test_ball_tree_query_discrete_metrics(): + np.random.seed(0) + X = (4 * np.random.random((40, 10))).round(0) + Y = (4 * np.random.random((10, 10))).round(0) + k = 5 - bt = neighbors.BallTree(X, leaf_size=5) - dist, ind = bt.query(q, k=k) + def check_neighbors(metric): + bt = BallTree(X, leaf_size=1, metric=metric) + dist1, ind1 = bt.query(Y, k) + dist2, ind2 = brute_force_neighbors(X, Y, k, metric) + assert_array_almost_equal(dist1, dist2) - assert not bt.warning_flag + for metric in DISCRETE_METRICS: + yield check_neighbors, metric def test_ball_tree_query_radius(n_samples=100, n_features=10): - X = 2 * rng.random_sample(size=(n_samples, n_features)) - 1 + np.random.seed(0) + X = 2 * np.random.random(size=(n_samples, n_features)) - 1 query_pt = np.zeros(n_features, dtype=float) eps = 1E-15 # roundoff error can cause test to fail - bt = neighbors.BallTree(X, leaf_size=5) + bt = BallTree(X, leaf_size=5) rad = np.sqrt(((X - query_pt) ** 2).sum(1)) for r in np.linspace(rad[0], rad[-1], 100): @@ -54,15 +108,16 @@ def test_ball_tree_query_radius(n_samples=100, n_features=10): ind.sort() i.sort() - assert np.all(i == ind) + assert_array_almost_equal(i, ind) def test_ball_tree_query_radius_distance(n_samples=100, n_features=10): - X = 2 * rng.random_sample(size=(n_samples, n_features)) - 1 + np.random.seed(0) + X = 2 * np.random.random(size=(n_samples, n_features)) - 1 query_pt = np.zeros(n_features, dtype=float) eps = 1E-15 # roundoff error can cause test to fail - bt = neighbors.BallTree(X, leaf_size=5) + bt = BallTree(X, leaf_size=5) rad = np.sqrt(((X - query_pt) ** 2).sum(1)) for r in np.linspace(rad[0], rad[-1], 100): @@ -76,30 +131,166 @@ def test_ball_tree_query_radius_distance(n_samples=100, n_features=10): assert_array_almost_equal(d, dist) +def compute_kernel_slow(Y, X, kernel, h): + d = np.sqrt(((Y[:, None, :] - X) ** 2).sum(-1)) + norm = kernel_norm(h, X.shape[1], kernel) + + if kernel == 'gaussian': + return norm * np.exp(-0.5 * (d * d) / (h * h)).sum(-1) + elif kernel == 'tophat': + return norm * (d < h).sum(-1) + elif kernel == 'epanechnikov': + return norm * ((1.0 - (d * d) / (h * h)) * (d < h)).sum(-1) + elif kernel == 'exponential': + return norm * (np.exp(-d / h)).sum(-1) + elif kernel == 'linear': + return norm * ((1 - d / h) * (d < h)).sum(-1) + elif kernel == 'cosine': + return norm * (np.cos(0.5 * np.pi * d / h) * (d < h)).sum(-1) + else: + raise ValueError('kernel not recognized') + + +def test_ball_tree_kde(n_samples=100, n_features=3): + np.random.seed(0) + X = np.random.random((n_samples, n_features)) + Y = np.random.random((n_samples, n_features)) + bt = BallTree(X, leaf_size=10) + + for kernel in ['gaussian', 'tophat', 'epanechnikov', + 'exponential', 'linear', 'cosine']: + for h in [0.01, 0.1, 1]: + dens_true = compute_kernel_slow(Y, X, kernel, h) + + def check_results(kernel, h, atol, rtol, breadth_first): + dens = bt.kernel_density(Y, h, atol=atol, rtol=rtol, + kernel=kernel, + breadth_first=breadth_first) + assert_allclose(dens, dens_true, + atol=atol, rtol=max(rtol, 1e-7)) + + for rtol in [0, 1E-5]: + for atol in [1E-6, 1E-2]: + for breadth_first in (True, False): + yield (check_results, kernel, h, atol, rtol, + breadth_first) + + +def test_gaussian_kde(n_samples=1000): + """Compare gaussian KDE results to scipy.stats.gaussian_kde""" + from scipy.stats import gaussian_kde + np.random.seed(0) + x_in = np.random.normal(0, 1, n_samples) + x_out = np.linspace(-5, 5, 30) + + for h in [0.01, 0.1, 1]: + bt = BallTree(x_in[:, None]) + try: + gkde = gaussian_kde(x_in, bw_method=h / np.std(x_in)) + except TypeError: + raise SkipTest("Old version of scipy, doesn't accept " + "explicit bandwidth.") + + dens_bt = bt.kernel_density(x_out[:, None], h) / n_samples + dens_gkde = gkde.evaluate(x_out) + + assert_array_almost_equal(dens_bt, dens_gkde, decimal=3) + + +def test_ball_tree_two_point(n_samples=100, n_features=3): + np.random.seed(0) + X = np.random.random((n_samples, n_features)) + Y = np.random.random((n_samples, n_features)) + r = np.linspace(0, 1, 10) + bt = BallTree(X, leaf_size=10) + + D = DistanceMetric.get_metric("euclidean").pairwise(Y, X) + counts_true = [(D <= ri).sum() for ri in r] + + def check_two_point(r, dualtree): + counts = bt.two_point_correlation(Y, r=r, dualtree=dualtree) + assert_array_almost_equal(counts, counts_true) + + for dualtree in (True, False): + yield check_two_point, r, dualtree + + def test_ball_tree_pickle(): import pickle - X = rng.random_sample(size=(10, 3)) - bt1 = neighbors.BallTree(X, leaf_size=1) + np.random.seed(0) + X = np.random.random((10, 3)) + bt1 = BallTree(X, leaf_size=1) ind1, dist1 = bt1.query(X) - for protocol in (0, 1, 2): + + def check_pickle_protocol(protocol): s = pickle.dumps(bt1, protocol=protocol) bt2 = pickle.loads(s) ind2, dist2 = bt2.query(X) - assert np.all(ind1 == ind2) + assert_array_almost_equal(ind1, ind2) assert_array_almost_equal(dist1, dist2) + for protocol in (0, 1, 2): + yield check_pickle_protocol, protocol + + +def test_neighbors_heap(n_pts=5, n_nbrs=10): + heap = NeighborsHeap(n_pts, n_nbrs) + + for row in range(n_pts): + d_in = np.random.random(2 * n_nbrs).astype(DTYPE) + i_in = np.arange(2 * n_nbrs, dtype=ITYPE) + for d, i in zip(d_in, i_in): + heap.push(row, d, i) + + ind = np.argsort(d_in) + d_in = d_in[ind] + i_in = i_in[ind] + + d_heap, i_heap = heap.get_arrays(sort=True) + + assert_array_almost_equal(d_in[:n_nbrs], d_heap[row]) + assert_array_almost_equal(i_in[:n_nbrs], i_heap[row]) + + +def test_node_heap(n_nodes=50): + vals = np.random.random(n_nodes).astype(DTYPE) + + i1 = np.argsort(vals) + vals2, i2 = nodeheap_sort(vals) + + assert_array_almost_equal(i1, i2) + assert_array_almost_equal(vals[i1], vals2) + + +def test_simultaneous_sort(n_rows=10, n_pts=201): + dist = np.random.random((n_rows, n_pts)).astype(DTYPE) + ind = (np.arange(n_pts) + np.zeros((n_rows, 1))).astype(ITYPE) + + dist2 = dist.copy() + ind2 = ind.copy() + + # simultaneous sort rows using function + simultaneous_sort(dist, ind) + + # simultaneous sort rows using numpy + i = np.argsort(dist2, axis=1) + row_ind = np.arange(n_rows)[:, None] + dist2 = dist2[row_ind, i] + ind2 = ind2[row_ind, i] -def test_ball_tree_p_distance(): - X = rng.random_sample(size=(100, 5)) + assert_array_almost_equal(dist, dist2) + assert_array_almost_equal(ind, ind2) - for p in (1, 2, 3, 4, np.inf): - bt = neighbors.BallTree(X, leaf_size=10, p=p) - kdt = cKDTree(X, leafsize=10) - dist_bt, ind_bt = bt.query(X, k=5) - dist_kd, ind_kd = kdt.query(X, k=5, p=p) +def test_query_haversine(): + np.random.seed(0) + X = 2 * np.pi * np.random.random((40, 2)) + bt = BallTree(X, leaf_size=1, metric='haversine') + dist1, ind1 = bt.query(X, k=5) + dist2, ind2 = brute_force_neighbors(X, X, k=5, metric='haversine') - assert_array_almost_equal(dist_bt, dist_kd) + assert_array_almost_equal(dist1, dist2) + assert_array_almost_equal(ind1, ind2) if __name__ == '__main__': diff --git a/sklearn/neighbors/tests/test_dist_metrics.py b/sklearn/neighbors/tests/test_dist_metrics.py new file mode 100644 index 0000000000000..d49e8ca31461a --- /dev/null +++ b/sklearn/neighbors/tests/test_dist_metrics.py @@ -0,0 +1,141 @@ +import itertools + +import numpy as np +from numpy.testing import assert_array_almost_equal + +import scipy +from scipy.spatial.distance import cdist +from sklearn.neighbors.dist_metrics import DistanceMetric +from nose import SkipTest + + +def cmp_version(version1, version2): + version1 = tuple(map(int, version1.split('.')[:2])) + version2 = tuple(map(int, version2.split('.')[:2])) + + if version1 < version2: + return -1 + elif version1 > version2: + return 1 + else: + return 0 + + +class TestMetrics: + def __init__(self, n1=20, n2=25, d=4, zero_frac=0.5, + rseed=0, dtype=np.float64): + np.random.seed(rseed) + self.X1 = np.random.random((n1, d)).astype(dtype) + self.X2 = np.random.random((n2, d)).astype(dtype) + + # make boolean arrays: ones and zeros + self.X1_bool = self.X1.round(0) + self.X2_bool = self.X2.round(0) + + V = np.random.random((d, d)) + VI = np.dot(V, V.T) + + self.metrics = {'euclidean': {}, + 'cityblock': {}, + 'minkowski': dict(p=(1, 1.5, 2, 3)), + 'chebyshev': {}, + 'seuclidean': dict(V=(np.random.random(d),)), + 'wminkowski': dict(p=(1, 1.5, 3), + w=(np.random.random(d),)), + 'mahalanobis': dict(VI=(VI,)), + 'hamming': {}, + 'canberra': {}, + 'braycurtis': {}} + + self.bool_metrics = ['matching', 'jaccard', 'dice', + 'kulsinski', 'rogerstanimoto', 'russellrao', + 'sokalmichener', 'sokalsneath'] + + def test_cdist(self): + for metric, argdict in self.metrics.items(): + keys = argdict.keys() + for vals in itertools.product(*argdict.values()): + kwargs = dict(zip(keys, vals)) + D_true = cdist(self.X1, self.X2, metric, **kwargs) + yield self.check_cdist, metric, kwargs, D_true + + for metric in self.bool_metrics: + D_true = cdist(self.X1_bool, self.X2_bool, metric) + yield self.check_cdist_bool, metric, D_true + + def check_cdist(self, metric, kwargs, D_true): + if metric == 'canberra' and cmp_version(scipy.__version__, '0.9') <= 0: + raise SkipTest("Canberra distance incorrect in scipy < 0.9") + dm = DistanceMetric.get_metric(metric, **kwargs) + D12 = dm.pairwise(self.X1, self.X2) + assert_array_almost_equal(D12, D_true) + + def check_cdist_bool(self, metric, D_true): + dm = DistanceMetric.get_metric(metric) + D12 = dm.pairwise(self.X1_bool, self.X2_bool) + assert_array_almost_equal(D12, D_true) + + def test_pdist(self): + for metric, argdict in self.metrics.items(): + keys = argdict.keys() + for vals in itertools.product(*argdict.values()): + kwargs = dict(zip(keys, vals)) + D_true = cdist(self.X1, self.X1, metric, **kwargs) + yield self.check_pdist, metric, kwargs, D_true + + for metric in self.bool_metrics: + D_true = cdist(self.X1_bool, self.X1_bool, metric) + yield self.check_pdist_bool, metric, D_true + + def check_pdist(self, metric, kwargs, D_true): + if metric == 'canberra' and cmp_version(scipy.__version__, '0.9') <= 0: + raise SkipTest("Canberra distance incorrect in scipy < 0.9") + dm = DistanceMetric.get_metric(metric, **kwargs) + D12 = dm.pairwise(self.X1) + assert_array_almost_equal(D12, D_true) + + def check_pdist_bool(self, metric, D_true): + dm = DistanceMetric.get_metric(metric) + D12 = dm.pairwise(self.X1_bool) + assert_array_almost_equal(D12, D_true) + + +def test_haversine_metric(): + def haversine_slow(x1, x2): + return 2 * np.arcsin(np.sqrt(np.sin(0.5 * (x1[0] - x2[0])) ** 2 + + np.cos(x1[0]) * np.cos(x2[0]) * + np.sin(0.5 * (x1[1] - x2[1])) ** 2)) + + X = np.random.random((10, 2)) + + haversine = DistanceMetric.get_metric("haversine") + + D1 = haversine.pairwise(X) + D2 = np.zeros_like(D1) + for i, x1 in enumerate(X): + for j, x2 in enumerate(X): + D2[i, j] = haversine_slow(x1, x2) + + assert_array_almost_equal(D1, D2) + assert_array_almost_equal(haversine.dist_to_rdist(D1), + np.sin(0.5 * D2) ** 2) + + +def test_pyfunc_metric(): + def dist_func(x1, x2, p): + return np.sum((x1 - x2) ** p) ** (1. / p) + + X = np.random.random((10, 3)) + + euclidean = DistanceMetric.get_metric("euclidean") + pyfunc = DistanceMetric.get_metric("pyfunc", func=dist_func, p=2) + + D1 = euclidean.pairwise(X) + D2 = pyfunc.pairwise(X) + + assert_array_almost_equal(D1, D2) + + +if __name__ == '__main__': + import nose + nose.runmodule() diff --git a/sklearn/neighbors/tests/test_kd_tree.py b/sklearn/neighbors/tests/test_kd_tree.py new file mode 100644 index 0000000000000..c949f1035216a --- /dev/null +++ b/sklearn/neighbors/tests/test_kd_tree.py @@ -0,0 +1,242 @@ +import numpy as np +from numpy.testing import assert_array_almost_equal +from sklearn.neighbors.kd_tree import (KDTree, NeighborsHeap, + simultaneous_sort, kernel_norm, + nodeheap_sort, DTYPE, ITYPE) +from sklearn.neighbors.dist_metrics import DistanceMetric +from sklearn.utils.testing import SkipTest, assert_allclose + +V = np.random.random((3, 3)) +V = np.dot(V, V.T) + +DIMENSION = 3 + +METRICS = {'euclidean': {}, + 'manhattan': {}, + 'chebyshev': {}, + 'minkowski': dict(p=3)} + + +def brute_force_neighbors(X, Y, k, metric, **kwargs): + D = DistanceMetric.get_metric(metric, **kwargs).pairwise(Y, X) + ind = np.argsort(D, axis=1)[:, :k] + dist = D[np.arange(Y.shape[0])[:, None], ind] + return dist, ind + + +def test_kd_tree_query(): + np.random.seed(0) + X = np.random.random((40, DIMENSION)) + Y = np.random.random((10, DIMENSION)) + + def check_neighbors(dualtree, breadth_first, k, metric, kwargs): + kdt = KDTree(X, leaf_size=1, metric=metric, **kwargs) + dist1, ind1 = kdt.query(Y, k, dualtree=dualtree, + breadth_first=breadth_first) + dist2, ind2 = brute_force_neighbors(X, Y, k, metric, **kwargs) + + # don't check indices here: if there are any duplicate distances, + # the indices may not match. Distances should not have this problem. + assert_array_almost_equal(dist1, dist2) + + for (metric, kwargs) in METRICS.items(): + for k in (1, 3, 5): + for dualtree in (True, False): + for breadth_first in (True, False): + yield (check_neighbors, + dualtree, breadth_first, + k, metric, kwargs) + + +def test_kd_tree_query_radius(n_samples=100, n_features=10): + np.random.seed(0) + X = 2 * np.random.random(size=(n_samples, n_features)) - 1 + query_pt = np.zeros(n_features, dtype=float) + + eps = 1E-15 # roundoff error can cause test to fail + kdt = KDTree(X, leaf_size=5) + rad = np.sqrt(((X - query_pt) ** 2).sum(1)) + + for r in np.linspace(rad[0], rad[-1], 100): + ind = kdt.query_radius(query_pt, r + eps)[0] + i = np.where(rad <= r + eps)[0] + + ind.sort() + i.sort() + + assert_array_almost_equal(i, ind) + + +def test_kd_tree_query_radius_distance(n_samples=100, n_features=10): + np.random.seed(0) + X = 2 * np.random.random(size=(n_samples, n_features)) - 1 + query_pt = np.zeros(n_features, dtype=float) + + eps = 1E-15 # roundoff error can cause test to fail + kdt = KDTree(X, leaf_size=5) + rad = np.sqrt(((X - query_pt) ** 2).sum(1)) + + for r in np.linspace(rad[0], rad[-1], 100): + ind, dist = kdt.query_radius(query_pt, r + eps, return_distance=True) + + ind = ind[0] + dist = dist[0] + + d = np.sqrt(((query_pt - X[ind]) ** 2).sum(1)) + + assert_array_almost_equal(d, dist) + + +def compute_kernel_slow(Y, X, kernel, h): + d = np.sqrt(((Y[:, None, :] - X) ** 2).sum(-1)) + norm = kernel_norm(h, X.shape[1], kernel) + + if kernel == 'gaussian': + return norm * np.exp(-0.5 * (d * d) / (h * h)).sum(-1) + elif kernel == 'tophat': + return norm * (d < h).sum(-1) + elif kernel == 'epanechnikov': + return norm * ((1.0 - (d * d) / (h * h)) * (d < h)).sum(-1) + elif kernel == 'exponential': + return norm * (np.exp(-d / h)).sum(-1) + elif kernel == 'linear': + return norm * ((1 - d / h) * (d < h)).sum(-1) + elif kernel == 'cosine': + return norm * (np.cos(0.5 * np.pi * d / h) * (d < h)).sum(-1) + else: + raise ValueError('kernel not recognized') + + +def test_kd_tree_kde(n_samples=100, n_features=3): + np.random.seed(0) + X = np.random.random((n_samples, n_features)) + Y = np.random.random((n_samples, n_features)) + kdt = KDTree(X, leaf_size=10) + + for kernel in ['gaussian', 'tophat', 'epanechnikov', + 'exponential', 'linear', 'cosine']: + for h in [0.01, 0.1, 1]: + dens_true = compute_kernel_slow(Y, X, kernel, h) + + def check_results(kernel, h, atol, rtol, breadth_first): + dens = kdt.kernel_density(Y, h, atol=atol, rtol=rtol, + kernel=kernel, + breadth_first=breadth_first) + assert_allclose(dens, dens_true, atol=atol, + rtol=max(rtol, 1e-7)) + + for rtol in [0, 1E-5]: + for atol in [1E-6, 1E-2]: + for breadth_first in (True, False): + yield (check_results, kernel, h, atol, rtol, + breadth_first) + + +def test_gaussian_kde(n_samples=1000): + """Compare gaussian KDE results to scipy.stats.gaussian_kde""" + from scipy.stats import gaussian_kde + np.random.seed(0) + x_in = np.random.normal(0, 1, n_samples) + x_out = np.linspace(-5, 5, 30) + + for h in [0.01, 0.1, 1]: + kdt = KDTree(x_in[:, None]) + try: + gkde = gaussian_kde(x_in, bw_method=h / np.std(x_in)) + except TypeError: + raise SkipTest("Old scipy, does not accept explicit bandwidth.") + + dens_kdt = kdt.kernel_density(x_out[:, None], h) / n_samples + dens_gkde = gkde.evaluate(x_out) + + assert_array_almost_equal(dens_kdt, dens_gkde, decimal=3) + + +def test_kd_tree_two_point(n_samples=100, n_features=3): + np.random.seed(0) + X = np.random.random((n_samples, n_features)) + Y = np.random.random((n_samples, n_features)) + r = np.linspace(0, 1, 10) + kdt = KDTree(X, leaf_size=10) + + D = DistanceMetric.get_metric("euclidean").pairwise(Y, X) + counts_true = [(D <= ri).sum() for ri in r] + + def check_two_point(r, dualtree): + counts = kdt.two_point_correlation(Y, r=r, dualtree=dualtree) + assert_array_almost_equal(counts, counts_true) + + for dualtree in (True, False): + yield check_two_point, r, dualtree + + +def test_kd_tree_pickle(): + import pickle + np.random.seed(0) + X = np.random.random((10, 3)) + kdt1 = KDTree(X, leaf_size=1) + ind1, dist1 = kdt1.query(X) + + def check_pickle_protocol(protocol): + s = pickle.dumps(kdt1, protocol=protocol) + kdt2 = pickle.loads(s) + ind2, dist2 = kdt2.query(X) + assert_array_almost_equal(ind1, ind2) + assert_array_almost_equal(dist1, dist2) + + for protocol in (0, 1, 2): + yield check_pickle_protocol, protocol + + +def test_neighbors_heap(n_pts=5, n_nbrs=10): + heap = NeighborsHeap(n_pts, n_nbrs) + + for row in range(n_pts): + d_in = np.random.random(2 * n_nbrs).astype(DTYPE) + i_in = np.arange(2 * n_nbrs, dtype=ITYPE) + for d, i in zip(d_in, i_in): + heap.push(row, d, i) + + ind = np.argsort(d_in) + d_in = d_in[ind] + i_in = i_in[ind] + + d_heap, i_heap = heap.get_arrays(sort=True) + + assert_array_almost_equal(d_in[:n_nbrs], d_heap[row]) + assert_array_almost_equal(i_in[:n_nbrs], i_heap[row]) + + +def test_node_heap(n_nodes=50): + vals = np.random.random(n_nodes).astype(DTYPE) + + i1 = np.argsort(vals) + vals2, i2 = nodeheap_sort(vals) + + assert_array_almost_equal(i1, i2) + assert_array_almost_equal(vals[i1], vals2) + + +def test_simultaneous_sort(n_rows=10, n_pts=201): + dist = np.random.random((n_rows, n_pts)).astype(DTYPE) + ind = (np.arange(n_pts) + np.zeros((n_rows, 1))).astype(ITYPE) + + dist2 = dist.copy() + ind2 = ind.copy() + + # simultaneous sort rows using function + simultaneous_sort(dist, ind) + + # simultaneous sort rows using numpy + i = np.argsort(dist2, axis=1) + row_ind = np.arange(n_rows)[:, None] + dist2 = dist2[row_ind, i] + ind2 = ind2[row_ind, i] + + assert_array_almost_equal(dist, dist2) + assert_array_almost_equal(ind, ind2) + + +if __name__ == '__main__': + import nose + nose.runmodule() diff --git a/sklearn/neighbors/tests/test_kde.py b/sklearn/neighbors/tests/test_kde.py new file mode 100644 index 0000000000000..132ae3171d06c --- /dev/null +++ b/sklearn/neighbors/tests/test_kde.py @@ -0,0 +1,146 @@ +import numpy as np +from sklearn.utils.testing import (assert_allclose, assert_raises, + assert_equal) +from sklearn.neighbors import KernelDensity, KDTree, NearestNeighbors +from sklearn.neighbors.ball_tree import kernel_norm +from sklearn.pipeline import make_pipeline +from sklearn.datasets import make_blobs +from sklearn.grid_search import GridSearchCV +from sklearn.preprocessing import StandardScaler + + +def compute_kernel_slow(Y, X, kernel, h): + d = np.sqrt(((Y[:, None, :] - X) ** 2).sum(-1)) + norm = kernel_norm(h, X.shape[1], kernel) / X.shape[0] + + if kernel == 'gaussian': + return norm * np.exp(-0.5 * (d * d) / (h * h)).sum(-1) + elif kernel == 'tophat': + return norm * (d < h).sum(-1) + elif kernel == 'epanechnikov': + return norm * ((1.0 - (d * d) / (h * h)) * (d < h)).sum(-1) + elif kernel == 'exponential': + return norm * (np.exp(-d / h)).sum(-1) + elif kernel == 'linear': + return norm * ((1 - d / h) * (d < h)).sum(-1) + elif kernel == 'cosine': + return norm * (np.cos(0.5 * np.pi * d / h) * (d < h)).sum(-1) + else: + raise ValueError('kernel not recognized') + + +def test_kernel_density(n_samples=100, n_features=3): + rng = np.random.RandomState(0) + X = rng.randn(n_samples, n_features) + Y = rng.randn(n_samples, n_features) + + for kernel in ['gaussian', 'tophat', 'epanechnikov', + 'exponential', 'linear', 'cosine']: + for bandwidth in [0.01, 0.1, 1]: + dens_true = compute_kernel_slow(Y, X, kernel, bandwidth) + + def check_results(kernel, bandwidth, atol, rtol): + kde = KernelDensity(kernel=kernel, bandwidth=bandwidth, + atol=atol, rtol=rtol) + log_dens = kde.fit(X).score_samples(Y) + assert_allclose(np.exp(log_dens), dens_true, + atol=atol, rtol=max(1E-7, rtol)) + assert_allclose(np.exp(kde.score(Y)), + np.prod(dens_true), + atol=atol, rtol=max(1E-7, rtol)) + + for rtol in [0, 1E-5]: + for atol in [1E-6, 1E-2]: + for breadth_first in (True, False): + yield (check_results, kernel, bandwidth, atol, rtol) + + +def test_kernel_density_sampling(n_samples=100, n_features=3): + rng = np.random.RandomState(0) + X = rng.randn(n_samples, n_features) + + bandwidth = 0.2 + + for kernel in ['gaussian', 'tophat']: + # draw a tophat sample + kde = KernelDensity(bandwidth, kernel=kernel).fit(X) + samp = kde.sample(100) + assert_equal(X.shape, samp.shape) + + # check that samples are in the right range + nbrs = NearestNeighbors(n_neighbors=1).fit(X) + dist, ind = nbrs.kneighbors(X, return_distance=True) + + if kernel == 'tophat': + assert np.all(dist < bandwidth) + elif kernel == 'gaussian': + # 5 standard deviations is safe for 100 samples, but there's a + # very small chance this test could fail. + assert np.all(dist < 5 * bandwidth) + + # check unsupported kernels + for kernel in ['epanechnikov', 'exponential', 'linear', 'cosine']: + kde = KernelDensity(bandwidth, kernel=kernel).fit(X) + assert_raises(NotImplementedError, kde.sample, 100) + + # non-regression test: used to return a scalar + X = rng.randn(4, 1) + kde = KernelDensity(kernel="gaussian").fit(X) + assert_equal(kde.sample().shape, (1, 1)) + + +def test_kde_algorithm_metric_choice(): + """Smoke test for various metrics and algorithms""" + rng = np.random.RandomState(0) + X = rng.randn(10, 2) # 2 features required for haversine dist. + Y = rng.randn(10, 2) + + for algorithm in ['auto', 'ball_tree', 'kd_tree']: + for metric in ['euclidean', 'minkowski', 'manhattan', + 'chebyshev', 'haversine']: + if algorithm == 'kd_tree' and metric not in KDTree.valid_metrics: + assert_raises(ValueError, KernelDensity, + algorithm=algorithm, metric=metric) + else: + kde = KernelDensity(algorithm=algorithm, metric=metric) + kde.fit(X) + y_dens = kde.score_samples(Y) + assert_equal(y_dens.shape, Y.shape[:1]) + + +def test_kde_score(n_samples=100, n_features=3): + pass + #FIXME + #np.random.seed(0) + #X = np.random.random((n_samples, n_features)) + #Y = np.random.random((n_samples, n_features)) + + +def test_kde_badargs(): + assert_raises(ValueError, KernelDensity, + algorithm='blah') + assert_raises(ValueError, KernelDensity, + bandwidth=0) + assert_raises(ValueError, KernelDensity, + kernel='blah') + assert_raises(ValueError, KernelDensity, + metric='blah') + assert_raises(ValueError, KernelDensity, + algorithm='kd_tree', metric='blah') + + +def test_kde_pipeline_gridsearch(): + # test that kde plays nice in pipelines and grid-searches + X, _ = make_blobs(cluster_std=.1, random_state=1, + centers=[[0, 1], [1, 0], [0, 0]]) + pipe1 = make_pipeline(StandardScaler(with_mean=False, with_std=False), + KernelDensity(kernel="gaussian")) + params = dict(kerneldensity__bandwidth=[0.001, 0.01, 0.1, 1, 10]) + search = GridSearchCV(pipe1, param_grid=params, cv=5) + search.fit(X) + assert_equal(search.best_params_['kerneldensity__bandwidth'], .1) + + +if __name__ == '__main__': + import nose + nose.runmodule() diff --git a/sklearn/neighbors/tests/test_nearest_centroid.py b/sklearn/neighbors/tests/test_nearest_centroid.py index d3c61c545d244..9922434c3b869 100644 --- a/sklearn/neighbors/tests/test_nearest_centroid.py +++ b/sklearn/neighbors/tests/test_nearest_centroid.py @@ -98,6 +98,44 @@ def test_pickle(): " after pickling (classification).") +def test_shrinkage_threshold_decoded_y(): + clf = NearestCentroid(shrink_threshold=0.01) + y_ind = np.asarray(y) + y_ind[y_ind == -1] = 0 + clf.fit(X, y_ind) + centroid_encoded = clf.centroids_ + clf.fit(X, y) + assert_array_equal(centroid_encoded, clf.centroids_) + + +def test_predict_translated_data(): + """Test that NearestCentroid gives same results on translated data""" + + rng = np.random.RandomState(0) + X = rng.rand(50, 50) + y = rng.randint(0, 3, 50) + noise = rng.rand(50) + clf = NearestCentroid(shrink_threshold=0.1) + clf.fit(X, y) + y_init = clf.predict(X) + clf = NearestCentroid(shrink_threshold=0.1) + X_noise = X + noise + clf.fit(X_noise, y) + y_translate = clf.predict(X_noise) + assert_array_equal(y_init, y_translate) + + +def test_manhattan_metric(): + """Test the manhattan metric.""" + + clf = NearestCentroid(metric='manhattan') + clf.fit(X, y) + dense_centroid = clf.centroids_ + clf.fit(X_csr, y) + assert_array_equal(clf.centroids_, dense_centroid) + assert_array_equal(dense_centroid, [[-1, -1], [1, 1]]) + + if __name__ == "__main__": import nose nose.runmodule() diff --git a/sklearn/neighbors/tests/test_neighbors.py b/sklearn/neighbors/tests/test_neighbors.py index b469325e33d3b..270b470a6d3fa 100644 --- a/sklearn/neighbors/tests/test_neighbors.py +++ b/sklearn/neighbors/tests/test_neighbors.py @@ -1,14 +1,19 @@ -import warnings - -from nose.tools import assert_equal, assert_true +from itertools import product import numpy as np -from numpy.testing import assert_array_almost_equal, assert_array_equal -from numpy.testing import assert_raises from scipy.sparse import (bsr_matrix, coo_matrix, csc_matrix, csr_matrix, dok_matrix, lil_matrix) -from scipy.spatial import cKDTree +from sklearn.cross_validation import train_test_split +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import ignore_warnings +from sklearn.utils.validation import check_random_state +from sklearn.metrics.pairwise import pairwise_distances from sklearn import neighbors, datasets rng = np.random.RandomState(0) @@ -31,6 +36,11 @@ ALGORITHMS = ('ball_tree', 'brute', 'kd_tree', 'auto') P = (1, 2, 3, 4, np.inf) +# Filter deprecation warnings. +neighbors.kneighbors_graph = ignore_warnings(neighbors.kneighbors_graph) +neighbors.radius_neighbors_graph = ignore_warnings( + neighbors.radius_neighbors_graph) + def _weight_func(dist): """ Weight function to replace lambda d: d ** -2. @@ -44,43 +54,8 @@ def _weight_func(dist): return retval ** 2 -def test_warn_on_equidistant(n_samples=100, n_features=3, k=3): - """test the production of a warning if equidistant points are discarded""" - X = rng.random_sample(size=(n_samples, n_features)) - q = rng.random_sample(size=n_features) - - neigh = neighbors.NearestNeighbors(n_neighbors=k) - neigh.fit(X[:-1]) - ind = neigh.kneighbors(q, return_distance=False) - - # make the last point identical to the furthest neighbor - # querying this should set warning_flag to True - X[-1] = X[ind[0, k - 1]] - - y = np.zeros(X.shape[0]) - - expected_message = ("kneighbors: neighbor k+1 and neighbor k " - "have the same distance: results will be " - "dependent on data order.") - - algorithms = ('ball_tree', 'brute') - estimators = (neighbors.KNeighborsClassifier, - neighbors.KNeighborsRegressor) - - for algorithm in algorithms: - for estimator in estimators: - with warnings.catch_warnings(record=True) as warn_queue: - neigh = estimator(n_neighbors=k, algorithm=algorithm) - neigh.fit(X, y) - neigh.predict(q) - - assert_equal(len(warn_queue), 1) - assert_equal(str(warn_queue[0].message), expected_message) - - def test_unsupervised_kneighbors(n_samples=20, n_features=5, - n_query_pts=2, n_neighbors=5, - random_state=0): + n_query_pts=2, n_neighbors=5): """Test unsupervised neighbors methods""" X = rng.rand(n_samples, n_features) @@ -97,7 +72,7 @@ def test_unsupervised_kneighbors(n_samples=20, n_features=5, neigh.fit(X) results_nodist.append(neigh.kneighbors(test, - return_distance=False)) + return_distance=False)) results.append(neigh.kneighbors(test, return_distance=True)) for i in range(len(results) - 1): @@ -117,7 +92,7 @@ def test_unsupervised_inputs(): nbrs = neighbors.NearestNeighbors(n_neighbors=1) - for input in (nbrs_fid, neighbors.BallTree(X), cKDTree(X)): + for input in (nbrs_fid, neighbors.BallTree(X), neighbors.KDTree(X)): nbrs.fit(input) dist2, ind2 = nbrs.kneighbors(X) @@ -175,6 +150,7 @@ def test_kneighbors_classifier(n_samples=40, rng = np.random.RandomState(random_state) X = 2 * rng.rand(n_samples, n_features) - 1 y = ((X ** 2).sum(axis=1) < .5).astype(np.int) + y_str = y.astype(str) weight_func = _weight_func @@ -187,6 +163,25 @@ def test_kneighbors_classifier(n_samples=40, epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1) y_pred = knn.predict(X[:n_test_pts] + epsilon) assert_array_equal(y_pred, y[:n_test_pts]) + # Test prediction with y_str + knn.fit(X, y_str) + y_pred = knn.predict(X[:n_test_pts] + epsilon) + assert_array_equal(y_pred, y_str[:n_test_pts]) + + +def test_kneighbors_classifier_float_labels(n_samples=40, n_features=5, + n_test_pts=10, n_neighbors=5, + random_state=0): + """Test k-neighbors classification""" + rng = np.random.RandomState(random_state) + X = 2 * rng.rand(n_samples, n_features) - 1 + y = ((X ** 2).sum(axis=1) < .5).astype(np.int) + + knn = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors) + knn.fit(X, y.astype(np.float)) + epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1) + y_pred = knn.predict(X[:n_test_pts] + epsilon) + assert_array_equal(y_pred, y[:n_test_pts]) def test_kneighbors_classifier_predict_proba(): @@ -208,6 +203,17 @@ def test_kneighbors_classifier_predict_proba(): [2. / 3, 1. / 3, 0], [2. / 3, 1. / 3, 0]]) assert_array_equal(real_prob, y_prob) + # Check that it also works with non integer labels + cls.fit(X, y.astype(str)) + y_prob = cls.predict_proba(X) + assert_array_equal(real_prob, y_prob) + # Check that it works with weights='distance' + cls = neighbors.KNeighborsClassifier( + n_neighbors=2, p=1, weights='distance') + cls.fit(X, y) + y_prob = cls.predict_proba(np.array([[0, 2, 0], [2, 2, 2]])) + real_prob = np.array([[0, 1, 0], [0, 0.4, 0.6]]) + assert_array_almost_equal(real_prob, y_prob) def test_radius_neighbors_classifier(n_samples=40, @@ -219,6 +225,7 @@ def test_radius_neighbors_classifier(n_samples=40, rng = np.random.RandomState(random_state) X = 2 * rng.rand(n_samples, n_features) - 1 y = ((X ** 2).sum(axis=1) < .5).astype(np.int) + y_str = y.astype(str) weight_func = _weight_func @@ -231,6 +238,9 @@ def test_radius_neighbors_classifier(n_samples=40, epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1) y_pred = neigh.predict(X[:n_test_pts] + epsilon) assert_array_equal(y_pred, y[:n_test_pts]) + neigh.fit(X, y_str) + y_pred = neigh.predict(X[:n_test_pts] + epsilon) + assert_array_equal(y_pred, y_str[:n_test_pts]) def test_radius_neighbors_classifier_when_no_neighbors(): @@ -246,14 +256,20 @@ def test_radius_neighbors_classifier_when_no_neighbors(): weight_func = _weight_func - for algorithm in ALGORITHMS: - for weights in ['uniform', 'distance', weight_func]: - clf = neighbors.RadiusNeighborsClassifier(radius=radius, - weights=weights, - algorithm=algorithm) - clf.fit(X, y) - clf.predict(z1) - assert_raises(ValueError, clf.predict, z2) + for outlier_label in [0, -1, None]: + for algorithm in ALGORITHMS: + for weights in ['uniform', 'distance', weight_func]: + rnc = neighbors.RadiusNeighborsClassifier + clf = rnc(radius=radius, weights=weights, algorithm=algorithm, + outlier_label=outlier_label) + clf.fit(X, y) + assert_array_equal(np.array([1, 2]), + clf.predict(z1)) + if outlier_label is None: + assert_raises(ValueError, clf.predict, z2) + elif False: + assert_array_equal(np.array([1, outlier_label]), + clf.predict(z2)) def test_radius_neighbors_classifier_outlier_labeling(): @@ -303,6 +319,93 @@ def test_radius_neighbors_classifier_zero_distance(): assert_array_equal(correct_labels1, clf.predict(z1)) +def test_neighbors_regressors_zero_distance(): + """ Test radius-based regressor, when distance to a sample is zero. """ + + X = np.array([[1.0, 1.0], [1.0, 1.0], [2.0, 2.0], [2.5, 2.5]]) + y = np.array([1.0, 1.5, 2.0, 0.0]) + radius = 0.2 + z = np.array([[1.1, 1.1], [2.0, 2.0]]) + + rnn_correct_labels = np.array([1.25, 2.0]) + + knn_correct_unif = np.array([1.25, 1.0]) + knn_correct_dist = np.array([1.25, 2.0]) + + for algorithm in ALGORITHMS: + # we don't test for weights=_weight_func since user will be expected + # to handle zero distances themselves in the function. + for weights in ['uniform', 'distance']: + rnn = neighbors.RadiusNeighborsRegressor(radius=radius, + weights=weights, + algorithm=algorithm) + rnn.fit(X, y) + assert_array_almost_equal(rnn_correct_labels, rnn.predict(z)) + + for weights, corr_labels in zip(['uniform', 'distance'], + [knn_correct_unif, knn_correct_dist]): + knn = neighbors.KNeighborsRegressor(n_neighbors=2, + weights=weights, + algorithm=algorithm) + knn.fit(X, y) + assert_array_almost_equal(corr_labels, knn.predict(z)) + + +def test_radius_neighbors_boundary_handling(): + """Test whether points lying on boundary are handled consistently + + Also ensures that even with only one query point, an object array + is returned rather than a 2d array. + """ + + X = np.array([[1.5], [3.0], [3.01]]) + radius = 3.0 + + for algorithm in ALGORITHMS: + nbrs = neighbors.NearestNeighbors(radius=radius, + algorithm=algorithm).fit(X) + results = nbrs.radius_neighbors([0.0], return_distance=False) + assert_equal(results.shape, (1,)) + assert_equal(results.dtype, object) + assert_array_equal(results[0], [0, 1]) + + +def test_RadiusNeighborsClassifier_multioutput(): + """Test k-NN classifier on multioutput data""" + rng = check_random_state(0) + n_features = 2 + n_samples = 40 + n_output = 3 + + X = rng.rand(n_samples, n_features) + y = rng.randint(0, 3, (n_samples, n_output)) + + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + + weights = [None, 'uniform', 'distance', _weight_func] + + for algorithm, weights in product(ALGORITHMS, weights): + # Stack single output prediction + y_pred_so = [] + for o in range(n_output): + rnn = neighbors.RadiusNeighborsClassifier(weights=weights, + algorithm=algorithm) + rnn.fit(X_train, y_train[:, o]) + y_pred_so.append(rnn.predict(X_test)) + + y_pred_so = np.vstack(y_pred_so).T + assert_equal(y_pred_so.shape, y_test.shape) + + # Multioutput prediction + rnn_mo = neighbors.RadiusNeighborsClassifier(weights=weights, + algorithm=algorithm) + rnn_mo.fit(X_train, y_train) + y_pred_mo = rnn_mo.predict(X_test) + + assert_equal(y_pred_mo.shape, y_test.shape) + assert_array_almost_equal(y_pred_mo, y_pred_so) + + def test_kneighbors_classifier_sparse(n_samples=40, n_features=5, n_test_pts=10, @@ -312,10 +415,9 @@ def test_kneighbors_classifier_sparse(n_samples=40, # Like the above, but with various types of sparse matrices rng = np.random.RandomState(random_state) X = 2 * rng.rand(n_samples, n_features) - 1 + X *= X > .2 y = ((X ** 2).sum(axis=1) < .5).astype(np.int) - SPARSE_TYPES = (bsr_matrix, coo_matrix, csc_matrix, csr_matrix, - dok_matrix, lil_matrix) for sparsemat in SPARSE_TYPES: knn = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm='auto') @@ -327,6 +429,52 @@ def test_kneighbors_classifier_sparse(n_samples=40, assert_array_equal(y_pred, y[:n_test_pts]) +def test_KNeighborsClassifier_multioutput(): + """Test k-NN classifier on multioutput data""" + rng = check_random_state(0) + n_features = 5 + n_samples = 50 + n_output = 3 + + X = rng.rand(n_samples, n_features) + y = rng.randint(0, 3, (n_samples, n_output)) + + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + + weights = [None, 'uniform', 'distance', _weight_func] + + for algorithm, weights in product(ALGORITHMS, weights): + # Stack single output prediction + y_pred_so = [] + y_pred_proba_so = [] + for o in range(n_output): + knn = neighbors.KNeighborsClassifier(weights=weights, + algorithm=algorithm) + knn.fit(X_train, y_train[:, o]) + y_pred_so.append(knn.predict(X_test)) + y_pred_proba_so.append(knn.predict_proba(X_test)) + + y_pred_so = np.vstack(y_pred_so).T + assert_equal(y_pred_so.shape, y_test.shape) + assert_equal(len(y_pred_proba_so), n_output) + + # Multioutput prediction + knn_mo = neighbors.KNeighborsClassifier(weights=weights, + algorithm=algorithm) + knn_mo.fit(X_train, y_train) + y_pred_mo = knn_mo.predict(X_test) + + assert_equal(y_pred_mo.shape, y_test.shape) + assert_array_almost_equal(y_pred_mo, y_pred_so) + + # Check proba + y_pred_proba_mo = knn_mo.predict_proba(X_test) + assert_equal(len(y_pred_proba_mo), n_output) + + for proba_mo, proba_so in zip(y_pred_proba_mo, y_pred_proba_so): + assert_array_almost_equal(proba_mo, proba_so) + + def test_kneighbors_regressor(n_samples=40, n_features=5, n_test_pts=10, @@ -353,6 +501,60 @@ def test_kneighbors_regressor(n_samples=40, assert_true(np.all(abs(y_pred - y_target) < 0.3)) +def test_KNeighborsRegressor_multioutput_uniform_weight(): + """Test k-neighbors in multi-output regression with uniform weight""" + rng = check_random_state(0) + n_features = 5 + n_samples = 40 + n_output = 4 + + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples, n_output) + + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + for algorithm, weights in product(ALGORITHMS, [None, 'uniform']): + knn = neighbors.KNeighborsRegressor(weights=weights, + algorithm=algorithm) + knn.fit(X_train, y_train) + + neigh_idx = knn.kneighbors(X_test, return_distance=False) + y_pred_idx = np.array([np.mean(y_train[idx], axis=0) + for idx in neigh_idx]) + + y_pred = knn.predict(X_test) + + assert_equal(y_pred.shape, y_test.shape) + assert_equal(y_pred_idx.shape, y_test.shape) + assert_array_almost_equal(y_pred, y_pred_idx) + + +def test_kneighbors_regressor_multioutput(n_samples=40, + n_features=5, + n_test_pts=10, + n_neighbors=3, + random_state=0): + """Test k-neighbors in multi-output regression""" + rng = np.random.RandomState(random_state) + X = 2 * rng.rand(n_samples, n_features) - 1 + y = np.sqrt((X ** 2).sum(1)) + y /= y.max() + y = np.vstack([y, y]).T + + y_target = y[:n_test_pts] + + weights = ['uniform', 'distance', _weight_func] + for algorithm, weights in product(ALGORITHMS, weights): + knn = neighbors.KNeighborsRegressor(n_neighbors=n_neighbors, + weights=weights, + algorithm=algorithm) + knn.fit(X, y) + epsilon = 1E-5 * (2 * rng.rand(1, n_features) - 1) + y_pred = knn.predict(X[:n_test_pts] + epsilon) + assert_equal(y_pred.shape, y_target.shape) + + assert_true(np.all(np.abs(y_pred - y_target) < 0.3)) + + def test_radius_neighbors_regressor(n_samples=40, n_features=3, n_test_pts=10, @@ -379,6 +581,63 @@ def test_radius_neighbors_regressor(n_samples=40, assert_true(np.all(abs(y_pred - y_target) < radius / 2)) +def test_RadiusNeighborsRegressor_multioutput_with_uniform_weight(): + """Test radius neighbors in multi-output regression (uniform weight)""" + + rng = check_random_state(0) + n_features = 5 + n_samples = 40 + n_output = 4 + + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples, n_output) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + + for algorithm, weights in product(ALGORITHMS, [None, 'uniform']): + + rnn = neighbors. RadiusNeighborsRegressor(weights=weights, + algorithm=algorithm) + rnn.fit(X_train, y_train) + + neigh_idx = rnn.radius_neighbors(X_test, return_distance=False) + y_pred_idx = np.array([np.mean(y_train[idx], axis=0) + for idx in neigh_idx]) + + y_pred_idx = np.array(y_pred_idx) + y_pred = rnn.predict(X_test) + + assert_equal(y_pred_idx.shape, y_test.shape) + assert_equal(y_pred.shape, y_test.shape) + assert_array_almost_equal(y_pred, y_pred_idx) + + +def test_RadiusNeighborsRegressor_multioutput(n_samples=40, + n_features=5, + n_test_pts=10, + n_neighbors=3, + random_state=0): + """Test k-neighbors in multi-output regression with various weight""" + rng = np.random.RandomState(random_state) + X = 2 * rng.rand(n_samples, n_features) - 1 + y = np.sqrt((X ** 2).sum(1)) + y /= y.max() + y = np.vstack([y, y]).T + + y_target = y[:n_test_pts] + weights = ['uniform', 'distance', _weight_func] + + for algorithm, weights in product(ALGORITHMS, weights): + rnn = neighbors.RadiusNeighborsRegressor(n_neighbors=n_neighbors, + weights=weights, + algorithm=algorithm) + rnn.fit(X, y) + epsilon = 1E-5 * (2 * rng.rand(1, n_features) - 1) + y_pred = rnn.predict(X[:n_test_pts] + epsilon) + + assert_equal(y_pred.shape, y_target.shape) + assert_true(np.all(np.abs(y_pred - y_target) < 0.3)) + + def test_kneighbors_regressor_sparse(n_samples=40, n_features=5, n_test_pts=10, @@ -390,8 +649,6 @@ def test_kneighbors_regressor_sparse(n_samples=40, X = 2 * rng.rand(n_samples, n_features) - 1 y = ((X ** 2).sum(axis=1) < .25).astype(np.int) - SPARSE_TYPES = (bsr_matrix, coo_matrix, csc_matrix, csr_matrix, - dok_matrix, lil_matrix) for sparsemat in SPARSE_TYPES: knn = neighbors.KNeighborsRegressor(n_neighbors=n_neighbors, algorithm='auto') @@ -410,7 +667,7 @@ def test_neighbors_iris(): for algorithm in ALGORITHMS: clf = neighbors.KNeighborsClassifier(n_neighbors=1, - algorithm=algorithm, warn_on_equidistant=False) + algorithm=algorithm) clf.fit(iris.data, iris.target) assert_array_equal(clf.predict(iris.data), iris.target) @@ -418,8 +675,7 @@ def test_neighbors_iris(): clf.fit(iris.data, iris.target) assert_true(np.mean(clf.predict(iris.data) == iris.target) > 0.95) - rgs = neighbors.KNeighborsRegressor(n_neighbors=5, algorithm=algorithm, - warn_on_equidistant=False) + rgs = neighbors.KNeighborsRegressor(n_neighbors=5, algorithm=algorithm) rgs.fit(iris.data, iris.target) assert_true(np.mean(rgs.predict(iris.data).round() == iris.target) > 0.95) @@ -440,8 +696,7 @@ def test_neighbors_digits(): test = np.arange(train_test_boundary, n_samples) (X_train, Y_train, X_test, Y_test) = X[train], Y[train], X[test], Y[test] - clf = neighbors.KNeighborsClassifier(n_neighbors=1, algorithm='brute', - warn_on_equidistant=False) + clf = neighbors.KNeighborsClassifier(n_neighbors=1, algorithm='brute') score_uint8 = clf.fit(X_train, Y_train).score(X_test, Y_test) score_float = clf.fit(X_train.astype(float), Y_train).score( X_test.astype(float), Y_test) @@ -454,54 +709,90 @@ def test_kneighbors_graph(): # n_neighbors = 1 A = neighbors.kneighbors_graph(X, 1, mode='connectivity') - assert_array_equal(A.todense(), np.eye(A.shape[0])) + assert_array_equal(A.toarray(), np.eye(A.shape[0])) A = neighbors.kneighbors_graph(X, 1, mode='distance') assert_array_almost_equal( - A.todense(), - [[0.00, 1.01, 0.], - [1.01, 0., 0.], - [0.00, 1.40716026, 0.]]) + A.toarray(), + [[0.00, 1.01, 0.], + [1.01, 0., 0.], + [0.00, 1.40716026, 0.]]) # n_neighbors = 2 A = neighbors.kneighbors_graph(X, 2, mode='connectivity') assert_array_equal( - A.todense(), - [[1., 1., 0.], - [1., 1., 0.], - [0., 1., 1.]]) + A.toarray(), + [[1., 1., 0.], + [1., 1., 0.], + [0., 1., 1.]]) A = neighbors.kneighbors_graph(X, 2, mode='distance') assert_array_almost_equal( - A.todense(), - [[0., 1.01, 2.23606798], - [1.01, 0., 1.40716026], - [2.23606798, 1.40716026, 0.]]) + A.toarray(), + [[0., 1.01, 2.23606798], + [1.01, 0., 1.40716026], + [2.23606798, 1.40716026, 0.]]) # n_neighbors = 3 A = neighbors.kneighbors_graph(X, 3, mode='connectivity') assert_array_almost_equal( - A.todense(), + A.toarray(), [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) +def test_kneighbors_graph_sparse(seed=36): + """Test kneighbors_graph to build the k-Nearest Neighbor graph + for sparse input.""" + rng = np.random.RandomState(seed) + X = rng.randn(10, 10) + Xcsr = csr_matrix(X) + + for n_neighbors in [1, 2, 3]: + for mode in ["connectivity", "distance"]: + assert_array_almost_equal( + neighbors.kneighbors_graph(X, + n_neighbors, + mode=mode).toarray(), + neighbors.kneighbors_graph(Xcsr, + n_neighbors, + mode=mode).toarray()) + + def test_radius_neighbors_graph(): """Test radius_neighbors_graph to build the Nearest Neighbor graph.""" X = np.array([[0, 1], [1.01, 1.], [2, 0]]) A = neighbors.radius_neighbors_graph(X, 1.5, mode='connectivity') assert_array_equal( - A.todense(), - [[1., 1., 0.], - [1., 1., 1.], - [0., 1., 1.]]) + A.toarray(), + [[1., 1., 0.], + [1., 1., 1.], + [0., 1., 1.]]) A = neighbors.radius_neighbors_graph(X, 1.5, mode='distance') assert_array_almost_equal( - A.todense(), - [[0., 1.01, 0.], - [1.01, 0., 1.40716026], - [0., 1.40716026, 0.]]) + A.toarray(), + [[0., 1.01, 0.], + [1.01, 0., 1.40716026], + [0., 1.40716026, 0.]]) + + +def test_radius_neighbors_graph_sparse(seed=36): + """Test radius_neighbors_graph to build the Nearest Neighbor graph + for sparse input.""" + rng = np.random.RandomState(seed) + X = rng.randn(10, 10) + Xcsr = csr_matrix(X) + + for n_neighbors in [1, 2, 3]: + for mode in ["connectivity", "distance"]: + assert_array_almost_equal( + neighbors.radius_neighbors_graph(X, + n_neighbors, + mode=mode).toarray(), + neighbors.radius_neighbors_graph(Xcsr, + n_neighbors, + mode=mode).toarray()) def test_neighbors_badargs(): @@ -511,6 +802,8 @@ def test_neighbors_badargs(): algorithm='blah') X = rng.random_sample((10, 2)) + Xsparse = csr_matrix(X) + y = np.ones(10) for cls in (neighbors.KNeighborsClassifier, neighbors.RadiusNeighborsClassifier, @@ -519,10 +812,28 @@ def test_neighbors_badargs(): assert_raises(ValueError, cls, weights='blah') - nbrs = cls() + assert_raises(ValueError, + cls, p=-1) + assert_raises(ValueError, + cls, algorithm='blah') + nbrs = cls(algorithm='ball_tree', metric='haversine') assert_raises(ValueError, nbrs.predict, X) + assert_raises(ValueError, + ignore_warnings(nbrs.fit), + Xsparse, y) + nbrs = cls() + assert_raises(ValueError, + nbrs.fit, + np.ones((0, 2)), np.ones(0)) + assert_raises(ValueError, + nbrs.fit, + X[:, :, None], y) + nbrs.fit(X, y) + assert_raises(ValueError, + nbrs.predict, + []) nbrs = neighbors.NearestNeighbors().fit(X) @@ -534,6 +845,249 @@ def test_neighbors_badargs(): X, mode='blah') +def test_neighbors_metrics(n_samples=20, n_features=3, + n_query_pts=2, n_neighbors=5): + """Test computing the neighbors for various metrics""" + # create a symmetric matrix + V = rng.rand(n_features, n_features) + VI = np.dot(V, V.T) + + metrics = [('euclidean', {}), + ('manhattan', {}), + ('minkowski', dict(p=1)), + ('minkowski', dict(p=2)), + ('minkowski', dict(p=3)), + ('minkowski', dict(p=np.inf)), + ('chebyshev', {}), + ('seuclidean', dict(V=rng.rand(n_features))), + ('wminkowski', dict(p=3, w=rng.rand(n_features))), + ('mahalanobis', dict(VI=VI))] + algorithms = ['brute', 'ball_tree', 'kd_tree'] + X = rng.rand(n_samples, n_features) + + test = rng.rand(n_query_pts, n_features) + + for metric, metric_params in metrics: + results = [] + p = metric_params.pop('p', 2) + for algorithm in algorithms: + # KD tree doesn't support all metrics + if (algorithm == 'kd_tree' and + metric not in neighbors.KDTree.valid_metrics): + assert_raises(ValueError, + neighbors.NearestNeighbors, + algorithm=algorithm, + metric=metric, metric_params=metric_params) + continue + + neigh = neighbors.NearestNeighbors(n_neighbors=n_neighbors, + algorithm=algorithm, + metric=metric, p=p, + metric_params=metric_params) + neigh.fit(X) + results.append(neigh.kneighbors(test, return_distance=True)) + + assert_array_almost_equal(results[0][0], results[1][0]) + assert_array_almost_equal(results[0][1], results[1][1]) + + +def test_callable_metric(): + metric = lambda x1, x2: np.sqrt(np.sum(x1 ** 2 + x2 ** 2)) + + X = np.random.RandomState(42).rand(20, 2) + nbrs1 = neighbors.NearestNeighbors(3, algorithm='auto', metric=metric) + nbrs2 = neighbors.NearestNeighbors(3, algorithm='brute', metric=metric) + + nbrs1.fit(X) + nbrs2.fit(X) + + dist1, ind1 = nbrs1.kneighbors(X) + dist2, ind2 = nbrs2.kneighbors(X) + + assert_array_almost_equal(dist1, dist2) + + +def test_metric_params_interface(): + assert_warns(DeprecationWarning, neighbors.KNeighborsClassifier, + metric='wminkowski', w=np.ones(10)) + assert_warns(SyntaxWarning, neighbors.KNeighborsClassifier, + metric_params={'p': 3}) + + +def test_predict_sparse_ball_kd_tree(): + rng = np.random.RandomState(0) + X = rng.rand(5, 5) + y = rng.randint(0, 2, 5) + nbrs1 = neighbors.KNeighborsClassifier(1, algorithm='kd_tree') + nbrs2 = neighbors.KNeighborsRegressor(1, algorithm='ball_tree') + for model in [nbrs1, nbrs2]: + model.fit(X, y) + assert_raises(ValueError, model.predict, csr_matrix(X)) + + +def test_non_euclidean_kneighbors(): + rng = np.random.RandomState(0) + X = rng.rand(5, 5) + + # Find a reasonable radius. + dist_array = pairwise_distances(X).flatten() + np.sort(dist_array) + radius = dist_array[15] + + # Test kneighbors_graph + for metric in ['manhattan', 'chebyshev']: + nbrs_graph = neighbors.kneighbors_graph( + X, 3, metric=metric).toarray() + nbrs1 = neighbors.NearestNeighbors(3, metric=metric).fit(X) + assert_array_equal(nbrs_graph, nbrs1.kneighbors_graph(X).toarray()) + + # Test radiusneighbors_graph + for metric in ['manhattan', 'chebyshev']: + nbrs_graph = neighbors.radius_neighbors_graph( + X, radius, metric=metric).toarray() + nbrs1 = neighbors.NearestNeighbors(metric=metric, radius=radius).fit(X) + assert_array_equal(nbrs_graph, + nbrs1.radius_neighbors_graph(X).toarray()) + + # Raise error when wrong parameters are supplied, + X_nbrs = neighbors.NearestNeighbors(3, metric='manhattan') + X_nbrs.fit(X) + assert_raises(ValueError, neighbors.kneighbors_graph, X_nbrs, 3, + metric='euclidean') + X_nbrs = neighbors.NearestNeighbors(radius=radius, metric='manhattan') + X_nbrs.fit(X) + assert_raises(ValueError, neighbors.radius_neighbors_graph, X_nbrs, + radius, metric='euclidean') + + +def check_object_arrays(nparray, list_check): + for ind, ele in enumerate(nparray): + assert_array_equal(ele, list_check[ind]) + + +def test_k_and_radius_neighbors_train_is_not_query(): + """Test kneighbors et.al when query is not training data""" + + for algorithm in ALGORITHMS: + + nn = neighbors.NearestNeighbors(n_neighbors=1, algorithm=algorithm) + + X = [[0], [1]] + nn.fit(X) + test_data = [[2], [1]] + + # Test neighbors. + dist, ind = nn.kneighbors(test_data) + assert_array_equal(dist, [[1], [0]]) + assert_array_equal(ind, [[1], [1]]) + dist, ind = nn.radius_neighbors([[2], [1]], radius=1.5) + check_object_arrays(dist, [[1], [1, 0]]) + check_object_arrays(ind, [[1], [0, 1]]) + + # Test the graph variants. + assert_array_equal( + nn.kneighbors_graph(test_data).A, [[0., 1.], [0., 1.]]) + assert_array_equal( + nn.kneighbors_graph([[2], [1]], mode='distance').A, + np.array([[0., 1.], [0., 0.]])) + rng = nn.radius_neighbors_graph([[2], [1]], radius=1.5) + assert_array_equal(rng.A, [[0, 1], [1, 1]]) + + +def test_k_and_radius_neighbors_X_None(): + """Test kneighbors et.al when query is None""" + for algorithm in ALGORITHMS: + + nn = neighbors.NearestNeighbors(n_neighbors=1, algorithm=algorithm) + + X = [[0], [1]] + nn.fit(X) + + dist, ind = nn.kneighbors() + assert_array_equal(dist, [[1], [1]]) + assert_array_equal(ind, [[1], [0]]) + dist, ind = nn.radius_neighbors(None, radius=1.5) + check_object_arrays(dist, [[1], [1]]) + check_object_arrays(ind, [[1], [0]]) + + # Test the graph variants. + rng = nn.radius_neighbors_graph(None, radius=1.5) + kng = nn.kneighbors_graph(None) + for graph in [rng, kng]: + assert_array_equal(rng.A, [[0, 1], [1, 0]]) + assert_array_equal(rng.data, [1, 1]) + assert_array_equal(rng.indices, [1, 0]) + + X = [[0, 1], [0, 1], [1, 1]] + nn = neighbors.NearestNeighbors(n_neighbors=2, algorithm=algorithm) + nn.fit(X) + assert_array_equal( + nn.kneighbors_graph().A, + np.array([[0., 1., 1.], [1., 0., 1.], [1., 1., 0]])) + + +def test_k_and_radius_neighbors_duplicates(): + """Test behavior of kneighbors when duplicates are present in query""" + + for algorithm in ALGORITHMS: + nn = neighbors.NearestNeighbors(n_neighbors=1, algorithm=algorithm) + nn.fit([[0], [1]]) + + # Do not do anything special to duplicates. + kng = nn.kneighbors_graph([[0], [1]], mode='distance') + assert_array_equal( + kng.A, + np.array([[0., 0.], [0., 0.]])) + assert_array_equal(kng.data, [0., 0.]) + assert_array_equal(kng.indices, [0, 1]) + + dist, ind = nn.radius_neighbors([[0], [1]], radius=1.5) + check_object_arrays(dist, [[0, 1], [1, 0]]) + check_object_arrays(ind, [[0, 1], [0, 1]]) + + rng = nn.radius_neighbors_graph([[0], [1]], radius=1.5) + assert_array_equal(rng.A, np.ones((2, 2))) + + rng = nn.radius_neighbors_graph([[0], [1]], radius=1.5, + mode='distance') + assert_array_equal(rng.A, [[0, 1], [1, 0]]) + assert_array_equal(rng.indices, [0, 1, 0, 1]) + assert_array_equal(rng.data, [0, 1, 1, 0]) + + # Mask the first duplicates when n_duplicates > n_neighbors. + X = np.ones((3, 1)) + nn = neighbors.NearestNeighbors(n_neighbors=1) + nn.fit(X) + dist, ind = nn.kneighbors() + assert_array_equal(dist, np.zeros((3, 1))) + assert_array_equal(ind, [[1], [0], [1]]) + + # Test that zeros are explicitly marked in kneighbors_graph. + kng = nn.kneighbors_graph(mode='distance') + assert_array_equal( + kng.A, np.zeros((3, 3))) + assert_array_equal(kng.data, np.zeros(3)) + assert_array_equal(kng.indices, [1., 0., 1.]) + assert_array_equal( + nn.kneighbors_graph().A, + np.array([[0., 1., 0.], [1., 0., 0.], [0., 1., 0.]])) + + +def test_include_self_neighbors_graph(): + """Test include_self parameter in neighbors_graph""" + X = [[2, 3], [4, 5]] + kng = neighbors.kneighbors_graph(X, 1, include_self=True).A + kng_not_self = neighbors.kneighbors_graph(X, 1, include_self=False).A + assert_array_equal(kng, [[1., 0.], [0., 1.]]) + assert_array_equal(kng_not_self, [[0., 1.], [1., 0.]]) + + rng = neighbors.radius_neighbors_graph(X, 5.0, include_self=True).A + rng_not_self = neighbors.radius_neighbors_graph( + X, 5.0, include_self=False).A + assert_array_equal(rng, [[1., 1.], [1., 1.]]) + assert_array_equal(rng_not_self, [[0., 1.], [1., 0.]]) + + if __name__ == '__main__': import nose nose.runmodule() diff --git a/sklearn/utils/arraybuilder.c b/sklearn/neighbors/typedefs.c similarity index 67% rename from sklearn/utils/arraybuilder.c rename to sklearn/neighbors/typedefs.c index f656490130e61..315734863baa3 100644 --- a/sklearn/utils/arraybuilder.c +++ b/sklearn/neighbors/typedefs.c @@ -1,18 +1,28 @@ -/* Generated by Cython 0.15.1+ on Thu Nov 17 19:41:19 2011 */ +/* Generated by Cython 0.19.1 on Fri Jul 26 13:30:00 2013 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02040000 #error Cython requires Python 2.4+. #else - #include /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -24,30 +34,47 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -55,7 +82,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -69,7 +95,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -79,40 +104,47 @@ #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" - #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #endif - +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - -/* new Py3.3 unicode representation (PEP 393) */ -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_GET_LENGTH) - #define CYTHON_PEP393_ENABLED - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #else - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #endif - #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -120,7 +152,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -139,7 +170,14 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) +#endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -147,9 +185,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -166,11 +202,9 @@ #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - #if PY_VERSION_HEX < 0x03020000 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong @@ -179,16 +213,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -207,11 +231,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -221,7 +243,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -229,6 +250,49 @@ #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus @@ -242,12 +306,14 @@ #define _USE_MATH_DEFINES #endif #include -#define __PYX_HAVE__sklearn__utils__arraybuilder -#define __PYX_HAVE_API__sklearn__utils__arraybuilder +#define __PYX_HAVE__sklearn__neighbors__typedefs +#define __PYX_HAVE_API__sklearn__neighbors__typedefs +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" +#include "math.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -256,21 +322,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -284,25 +335,129 @@ # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif #ifdef __GNUC__ @@ -318,8 +473,9 @@ static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -328,7 +484,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -338,7 +493,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -346,18 +500,19 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { - "arraybuilder.pyx", "numpy.pxd", + "typedefs.pyx", + "type.pxd", }; -/* "numpy.pxd":719 +/* "numpy.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -366,7 +521,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "numpy.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -375,7 +530,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "numpy.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -384,7 +539,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "numpy.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -393,7 +548,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "numpy.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -402,7 +557,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "numpy.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -411,7 +566,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "numpy.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -420,7 +575,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "numpy.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -429,7 +584,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "numpy.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -438,7 +593,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "numpy.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -447,7 +602,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "numpy.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -456,7 +611,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "numpy.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -465,7 +620,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "numpy.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -474,7 +629,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "numpy.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -483,7 +638,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "numpy.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -492,7 +647,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "numpy.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -501,7 +656,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "numpy.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -510,7 +665,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "numpy.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -519,7 +674,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "numpy.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -528,7 +683,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "numpy.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -537,7 +692,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "numpy.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -546,6 +701,23 @@ typedef npy_double __pyx_t_5numpy_double_t; */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; +/* "sklearn/neighbors/typedefs.pxd":5 + * + * # Floating point/data type + * ctypedef np.float64_t DTYPE_t # WARNING: should match DTYPE in typedefs.pyx # <<<<<<<<<<<<<< + * + * cdef enum: + */ +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t; + +/* "sklearn/neighbors/typedefs.pxd":13 + * # Index/integer type. + * # WARNING: ITYPE_t must be a signed integer type or you will have a bad time! + * ctypedef np.intp_t ITYPE_t # WARNING: should match ITYPE in typedefs.pyx # <<<<<<<<<<<<<< + * + * # Fused type for certain operations + */ +typedef __pyx_t_5numpy_intp_t __pyx_t_7sklearn_9neighbors_8typedefs_ITYPE_t; #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -566,10 +738,10 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ -struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder; -/* "numpy.pxd":758 +/* "numpy.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -578,7 +750,7 @@ struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "numpy.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -587,7 +759,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "numpy.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -596,7 +768,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "numpy.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -605,31 +777,28 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; */ typedef npy_cdouble __pyx_t_5numpy_complex_t; -/* "sklearn/utils/arraybuilder.pyx":6 +/* "sklearn/neighbors/typedefs.pxd":7 + * ctypedef np.float64_t DTYPE_t # WARNING: should match DTYPE in typedefs.pyx * - * - * cdef class ArrayBuilder(object): # <<<<<<<<<<<<<< - * """Helper class to incrementally build a 1-d numpy.ndarray""" - * # Or: let's reinvent the wheel! - */ -struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder { - PyObject_HEAD - struct __pyx_vtabstruct_7sklearn_5utils_12arraybuilder_ArrayBuilder *__pyx_vtab; - Py_ssize_t _nelems; - PyObject *_arr; -}; - - + * cdef enum: # <<<<<<<<<<<<<< + * DTYPECODE = np.NPY_FLOAT64 + * ITYPECODE = np.NPY_INT32 + */ +enum { -struct __pyx_vtabstruct_7sklearn_5utils_12arraybuilder_ArrayBuilder { - PyObject *(*_grow)(struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *); + /* "sklearn/neighbors/typedefs.pxd":9 + * cdef enum: + * DTYPECODE = np.NPY_FLOAT64 + * ITYPECODE = np.NPY_INT32 # <<<<<<<<<<<<<< + * + * # Index/integer type. + */ + __pyx_e_7sklearn_9neighbors_8typedefs_DTYPECODE = NPY_FLOAT64, + __pyx_e_7sklearn_9neighbors_8typedefs_ITYPECODE = NPY_INT32 }; -static struct __pyx_vtabstruct_7sklearn_5utils_12arraybuilder_ArrayBuilder *__pyx_vtabptr_7sklearn_5utils_12arraybuilder_ArrayBuilder; - #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -642,8 +811,21 @@ static struct __pyx_vtabstruct_7sklearn_5utils_12arraybuilder_ArrayBuilder *__py static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -654,7 +836,7 @@ static struct __pyx_vtabstruct_7sklearn_5utils_12arraybuilder_ArrayBuilder *__py #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -665,68 +847,46 @@ static struct __pyx_vtabstruct_7sklearn_5utils_12arraybuilder_ArrayBuilder *__py #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ - #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ - -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ - -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ - -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ - -#define __Pyx_SetItemInt(o, i, v, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_SetItemInt_Fast(o, i, v) : \ - __Pyx_SetItemInt_Generic(o, to_py_func(i), v)) - -static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { - int r; - if (!j) return -1; - r = PyObject_SetItem(o, j, v); - Py_DECREF(j); - return r; +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); } +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v) { - if (PyList_CheckExact(o)) { - Py_ssize_t n = (likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if (likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { - PyObject* old = PyList_GET_ITEM(o, n); - Py_INCREF(v); - PyList_SET_ITEM(o, n, v); - Py_DECREF(old); - return 1; - } - } - else if (likely(i >= 0)) { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_ass_item)) { - return m->sq_ass_item(o, i, v); - } - } - return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); -} +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -740,7 +900,6 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - #if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) @@ -861,27 +1020,53 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject * static int __Pyx_check_binary_version(void); -static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ -/* Module declarations from 'cython' */ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -892,24 +1077,23 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ -/* Module declarations from 'sklearn.utils.arraybuilder' */ -static PyTypeObject *__pyx_ptype_7sklearn_5utils_12arraybuilder_ArrayBuilder = 0; -#define __Pyx_MODULE_NAME "sklearn.utils.arraybuilder" -int __pyx_module_is_main_sklearn__utils__arraybuilder = 0; +/* Module declarations from 'libc.math' */ + +/* Module declarations from 'sklearn.neighbors.typedefs' */ +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_8typedefs_INF; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_8typedefs_PI; +static __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_v_7sklearn_9neighbors_8typedefs_ROOT_2PI; +#define __Pyx_MODULE_NAME "sklearn.neighbors.typedefs" +int __pyx_module_is_main_sklearn__neighbors__typedefs = 0; -/* Implementation of 'sklearn.utils.arraybuilder' */ +/* Implementation of 'sklearn.neighbors.typedefs' */ static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_RuntimeError; +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static char __pyx_k_1[] = "ndarray is not C contiguous"; static char __pyx_k_3[] = "ndarray is not Fortran contiguous"; static char __pyx_k_5[] = "Non-native byte order not supported"; @@ -934,41 +1118,40 @@ static char __pyx_k__Zd[] = "Zd"; static char __pyx_k__Zf[] = "Zf"; static char __pyx_k__Zg[] = "Zg"; static char __pyx_k__np[] = "np"; -static char __pyx_k__size[] = "size"; -static char __pyx_k__dtype[] = "dtype"; -static char __pyx_k__empty[] = "empty"; +static char __pyx_k__pi[] = "pi"; +static char __pyx_k__inf[] = "inf"; +static char __pyx_k__intp[] = "intp"; +static char __pyx_k__DTYPE[] = "DTYPE"; +static char __pyx_k__ITYPE[] = "ITYPE"; static char __pyx_k__numpy[] = "numpy"; static char __pyx_k__range[] = "range"; -static char __pyx_k__resize[] = "resize"; +static char __pyx_k__float64[] = "float64"; static char __pyx_k____main__[] = "__main__"; static char __pyx_k____test__[] = "__test__"; static char __pyx_k__ValueError[] = "ValueError"; +static char __pyx_k____import__[] = "__import__"; static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k__GROWTH_FACTOR[] = "GROWTH_FACTOR"; -static char __pyx_k__initial_capacity[] = "initial_capacity"; static PyObject *__pyx_kp_u_1; static PyObject *__pyx_kp_u_11; static PyObject *__pyx_kp_u_3; static PyObject *__pyx_kp_u_5; static PyObject *__pyx_kp_u_7; static PyObject *__pyx_kp_u_8; -static PyObject *__pyx_n_s__GROWTH_FACTOR; +static PyObject *__pyx_n_s__DTYPE; +static PyObject *__pyx_n_s__ITYPE; static PyObject *__pyx_n_s__RuntimeError; static PyObject *__pyx_n_s__ValueError; +static PyObject *__pyx_n_s____import__; static PyObject *__pyx_n_s____main__; static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__dtype; -static PyObject *__pyx_n_s__empty; -static PyObject *__pyx_n_s__initial_capacity; +static PyObject *__pyx_n_s__float64; +static PyObject *__pyx_n_s__inf; +static PyObject *__pyx_n_s__intp; static PyObject *__pyx_n_s__np; static PyObject *__pyx_n_s__numpy; +static PyObject *__pyx_n_s__pi; static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__resize; -static PyObject *__pyx_n_s__size; -static PyObject *__pyx_int_1; -static PyObject *__pyx_int_2; static PyObject *__pyx_int_15; -static PyObject *__pyx_int_256; static PyObject *__pyx_k_tuple_2; static PyObject *__pyx_k_tuple_4; static PyObject *__pyx_k_tuple_6; @@ -976,419 +1159,18 @@ static PyObject *__pyx_k_tuple_9; static PyObject *__pyx_k_tuple_10; static PyObject *__pyx_k_tuple_12; -/* "sklearn/utils/arraybuilder.pyx":15 - * cdef object _arr # object because we don't know the dtype statically - * - * def __init__(self, dtype, initial_capacity=256): # <<<<<<<<<<<<<< - * assert self.GROWTH_FACTOR > 1 - * assert initial_capacity >= 2 - */ - -static int __pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_dtype = 0; - PyObject *__pyx_v_initial_capacity = 0; +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__dtype,&__pyx_n_s__initial_capacity,0}; - __Pyx_RefNannySetupContext("__init__"); - { - PyObject* values[2] = {0,0}; - values[1] = ((PyObject *)__pyx_int_256); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dtype); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__initial_capacity); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - __pyx_v_dtype = values[0]; - __pyx_v_initial_capacity = values[1]; - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_dtype = values[0]; - __pyx_v_initial_capacity = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.utils.arraybuilder.ArrayBuilder.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - - /* "sklearn/utils/arraybuilder.pyx":16 - * - * def __init__(self, dtype, initial_capacity=256): - * assert self.GROWTH_FACTOR > 1 # <<<<<<<<<<<<<< - * assert initial_capacity >= 2 - * self._arr = np.empty(initial_capacity, dtype=dtype) - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - __pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_s__GROWTH_FACTOR); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_RichCompare(__pyx_t_1, __pyx_int_1, Py_GT); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_3)) { - PyErr_SetNone(PyExc_AssertionError); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - #endif - - /* "sklearn/utils/arraybuilder.pyx":17 - * def __init__(self, dtype, initial_capacity=256): - * assert self.GROWTH_FACTOR > 1 - * assert initial_capacity >= 2 # <<<<<<<<<<<<<< - * self._arr = np.empty(initial_capacity, dtype=dtype) - * self._nelems = 0 - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - __pyx_t_2 = PyObject_RichCompare(__pyx_v_initial_capacity, __pyx_int_2, Py_GE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_3)) { - PyErr_SetNone(PyExc_AssertionError); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - #endif - - /* "sklearn/utils/arraybuilder.pyx":18 - * assert self.GROWTH_FACTOR > 1 - * assert initial_capacity >= 2 - * self._arr = np.empty(initial_capacity, dtype=dtype) # <<<<<<<<<<<<<< - * self._nelems = 0 - * - */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_initial_capacity); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_initial_capacity); - __Pyx_GIVEREF(__pyx_v_initial_capacity); - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_v_dtype) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_GIVEREF(__pyx_t_5); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_arr); - __Pyx_DECREF(((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_arr); - ((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_arr = __pyx_t_5; - __pyx_t_5 = 0; - - /* "sklearn/utils/arraybuilder.pyx":19 - * assert initial_capacity >= 2 - * self._arr = np.empty(initial_capacity, dtype=dtype) - * self._nelems = 0 # <<<<<<<<<<<<<< - * - * def __len__(self): - */ - ((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_nelems = 0; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("sklearn.utils.arraybuilder.ArrayBuilder.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/utils/arraybuilder.pyx":21 - * self._nelems = 0 - * - * def __len__(self): # <<<<<<<<<<<<<< - * return self._nelems - * - */ - -static Py_ssize_t __pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder_1__len__(PyObject *__pyx_v_self); /*proto*/ -static Py_ssize_t __pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder_1__len__(PyObject *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__"); - - /* "sklearn/utils/arraybuilder.pyx":22 - * - * def __len__(self): - * return self._nelems # <<<<<<<<<<<<<< - * - * @cython.boundscheck(False) - */ - __pyx_r = ((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_nelems; - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/utils/arraybuilder.pyx":25 - * - * @cython.boundscheck(False) - * def append(self, x): # <<<<<<<<<<<<<< - * """Append a single value. - * - */ - -static PyObject *__pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder_2append(PyObject *__pyx_v_self, PyObject *__pyx_v_x); /*proto*/ -static char __pyx_doc_7sklearn_5utils_12arraybuilder_12ArrayBuilder_2append[] = "Append a single value.\n\n Complexity: amortized O(1).\n "; -static PyObject *__pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder_2append(PyObject *__pyx_v_self, PyObject *__pyx_v_x) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("append"); - - /* "sklearn/utils/arraybuilder.pyx":30 - * Complexity: amortized O(1). - * """ - * if self._nelems == self._arr.size: # <<<<<<<<<<<<<< - * self._grow() - * self._arr[self._nelems] = x - */ - __pyx_t_1 = PyInt_FromSsize_t(((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_nelems); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_arr, __pyx_n_s__size); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_1, __pyx_t_2, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_4) { - - /* "sklearn/utils/arraybuilder.pyx":31 - * """ - * if self._nelems == self._arr.size: - * self._grow() # <<<<<<<<<<<<<< - * self._arr[self._nelems] = x - * self._nelems += 1 - */ - __pyx_t_3 = ((struct __pyx_vtabstruct_7sklearn_5utils_12arraybuilder_ArrayBuilder *)((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->__pyx_vtab)->_grow(((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L5; - } - __pyx_L5:; - - /* "sklearn/utils/arraybuilder.pyx":32 - * if self._nelems == self._arr.size: - * self._grow() - * self._arr[self._nelems] = x # <<<<<<<<<<<<<< - * self._nelems += 1 - * - */ - if (__Pyx_SetItemInt(((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_arr, ((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_nelems, __pyx_v_x, sizeof(Py_ssize_t), PyInt_FromSsize_t) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/utils/arraybuilder.pyx":33 - * self._grow() - * self._arr[self._nelems] = x - * self._nelems += 1 # <<<<<<<<<<<<<< - * - * def get(self): - */ - ((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_nelems = (((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_nelems + 1); - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("sklearn.utils.arraybuilder.ArrayBuilder.append", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/utils/arraybuilder.pyx":35 - * self._nelems += 1 - * - * def get(self): # <<<<<<<<<<<<<< - * """Return the constructed array. - * - */ - -static PyObject *__pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder_3get(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7sklearn_5utils_12arraybuilder_12ArrayBuilder_3get[] = "Return the constructed array.\n\n Don't use an ArrayBuilder after calling this method.\n "; -static PyObject *__pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder_3get(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get"); - - /* "sklearn/utils/arraybuilder.pyx":40 - * Don't use an ArrayBuilder after calling this method. - * """ - * self._arr.resize(self._nelems) # <<<<<<<<<<<<<< - * return self._arr - * - */ - __pyx_t_1 = PyObject_GetAttr(((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_arr, __pyx_n_s__resize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromSsize_t(((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_nelems); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "sklearn/utils/arraybuilder.pyx":41 - * """ - * self._arr.resize(self._nelems) - * return self._arr # <<<<<<<<<<<<<< - * - * cdef _grow(self): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_arr); - __pyx_r = ((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)__pyx_v_self)->_arr; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("sklearn.utils.arraybuilder.ArrayBuilder.get", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/utils/arraybuilder.pyx":43 - * return self._arr - * - * cdef _grow(self): # <<<<<<<<<<<<<< - * self._arr.resize(self._arr.size * self.GROWTH_FACTOR) - */ - -static PyObject *__pyx_f_7sklearn_5utils_12arraybuilder_12ArrayBuilder__grow(struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_grow"); - - /* "sklearn/utils/arraybuilder.pyx":44 - * - * cdef _grow(self): - * self._arr.resize(self._arr.size * self.GROWTH_FACTOR) # <<<<<<<<<<<<<< - */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_self->_arr, __pyx_n_s__resize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_v_self->_arr, __pyx_n_s__size); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__GROWTH_FACTOR); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyNumber_Multiply(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("sklearn.utils.arraybuilder.ArrayBuilder._grow", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "numpy.pxd":190 +/* "numpy.pxd":194 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< @@ -1396,8 +1178,7 @@ static PyObject *__pyx_f_7sklearn_5utils_12arraybuilder_12ArrayBuilder__grow(str * # requirements, and does not yet fullfill the PEP. */ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; @@ -1422,28 +1203,28 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__"); + __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":196 + /* "numpy.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ - __pyx_t_1 = (__pyx_v_info == NULL); + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":199 + /* "numpy.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -1452,7 +1233,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":200 + /* "numpy.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -1461,26 +1242,26 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":202 + /* "numpy.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":204 + /* "numpy.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":205 + /* "numpy.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -1488,11 +1269,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ * copy_shape = 0 */ __pyx_v_copy_shape = 1; - goto __pyx_L6; + goto __pyx_L4; } /*else*/ { - /* "numpy.pxd":207 + /* "numpy.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -1501,98 +1282,98 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_copy_shape = 0; } - __pyx_L6:; + __pyx_L4:; - /* "numpy.pxd":209 + /* "numpy.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_1) { - /* "numpy.pxd":210 + /* "numpy.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { - /* "numpy.pxd":211 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; } - __pyx_L7:; + __pyx_L5:; - /* "numpy.pxd":213 + /* "numpy.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_3) { - /* "numpy.pxd":214 + /* "numpy.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { - /* "numpy.pxd":215 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; } - __pyx_L8:; + __pyx_L6:; - /* "numpy.pxd":217 + /* "numpy.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":218 + /* "numpy.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -1601,16 +1382,17 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":219 + /* "numpy.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ - if (__pyx_v_copy_shape) { + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { - /* "numpy.pxd":222 + /* "numpy.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -1619,7 +1401,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":223 + /* "numpy.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -1628,7 +1410,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":224 + /* "numpy.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< @@ -1639,49 +1421,49 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "numpy.pxd":225 + /* "numpy.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":226 + /* "numpy.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } - goto __pyx_L9; + goto __pyx_L7; } /*else*/ { - /* "numpy.pxd":228 + /* "numpy.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":229 + /* "numpy.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } - __pyx_L9:; + __pyx_L7:; - /* "numpy.pxd":230 + /* "numpy.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -1690,25 +1472,25 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":231 + /* "numpy.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":232 + /* "numpy.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - /* "numpy.pxd":235 + /* "numpy.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -1717,17 +1499,19 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_f = NULL; - /* "numpy.pxd":236 + /* "numpy.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":240 + /* "numpy.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -1736,23 +1520,23 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":242 + /* "numpy.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; } if (__pyx_t_1) { - /* "numpy.pxd":244 + /* "numpy.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -1764,69 +1548,70 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; - goto __pyx_L12; + goto __pyx_L10; } /*else*/ { - /* "numpy.pxd":247 + /* "numpy.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } - __pyx_L12:; + __pyx_L10:; - /* "numpy.pxd":249 + /* "numpy.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { - /* "numpy.pxd":250 + /* "numpy.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; - /* "numpy.pxd":251 + /* "numpy.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; + __pyx_t_2 = (__pyx_v_little_endian != 0); } else { __pyx_t_2 = __pyx_t_1; } if (!__pyx_t_2) { - /* "numpy.pxd":252 + /* "numpy.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_7 = __pyx_t_3; } else { __pyx_t_7 = __pyx_t_1; @@ -1837,271 +1622,246 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (__pyx_t_1) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; } - __pyx_L14:; + __pyx_L12:; - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "numpy.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { + case NPY_BYTE: __pyx_v_f = __pyx_k__b; - goto __pyx_L15; - } + break; - /* "numpy.pxd":255 + /* "numpy.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { + case NPY_UBYTE: __pyx_v_f = __pyx_k__B; - goto __pyx_L15; - } + break; - /* "numpy.pxd":256 + /* "numpy.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { + case NPY_SHORT: __pyx_v_f = __pyx_k__h; - goto __pyx_L15; - } + break; - /* "numpy.pxd":257 + /* "numpy.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { + case NPY_USHORT: __pyx_v_f = __pyx_k__H; - goto __pyx_L15; - } + break; - /* "numpy.pxd":258 + /* "numpy.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { + case NPY_INT: __pyx_v_f = __pyx_k__i; - goto __pyx_L15; - } + break; - /* "numpy.pxd":259 + /* "numpy.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { + case NPY_UINT: __pyx_v_f = __pyx_k__I; - goto __pyx_L15; - } + break; - /* "numpy.pxd":260 + /* "numpy.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { + case NPY_LONG: __pyx_v_f = __pyx_k__l; - goto __pyx_L15; - } + break; - /* "numpy.pxd":261 + /* "numpy.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { + case NPY_ULONG: __pyx_v_f = __pyx_k__L; - goto __pyx_L15; - } + break; - /* "numpy.pxd":262 + /* "numpy.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { + case NPY_LONGLONG: __pyx_v_f = __pyx_k__q; - goto __pyx_L15; - } + break; - /* "numpy.pxd":263 + /* "numpy.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { + case NPY_ULONGLONG: __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; - } + break; - /* "numpy.pxd":264 + /* "numpy.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { + case NPY_FLOAT: __pyx_v_f = __pyx_k__f; - goto __pyx_L15; - } + break; - /* "numpy.pxd":265 + /* "numpy.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { + case NPY_DOUBLE: __pyx_v_f = __pyx_k__d; - goto __pyx_L15; - } + break; - /* "numpy.pxd":266 + /* "numpy.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { + case NPY_LONGDOUBLE: __pyx_v_f = __pyx_k__g; - goto __pyx_L15; - } + break; - /* "numpy.pxd":267 + /* "numpy.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { + case NPY_CFLOAT: __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; - } + break; - /* "numpy.pxd":268 + /* "numpy.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { + case NPY_CDOUBLE: __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; - } + break; - /* "numpy.pxd":269 + /* "numpy.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { + case NPY_CLONGDOUBLE: __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; - } + break; - /* "numpy.pxd":270 + /* "numpy.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L15; - } - /*else*/ { + case NPY_OBJECT: + __pyx_v_f = __pyx_k__O; + break; + default: - /* "numpy.pxd":272 + /* "numpy.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_8)); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L15:; - /* "numpy.pxd":273 + /* "numpy.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -2110,7 +1870,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":274 + /* "numpy.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -2119,57 +1879,57 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L13; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":276 + /* "numpy.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":277 + /* "numpy.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":278 + /* "numpy.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":281 + /* "numpy.pxd":285 * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string + * f[0] = c'\0' # Terminate format string * */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; - /* "numpy.pxd":282 + /* "numpy.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L13:; + __pyx_L11:; __pyx_r = 0; goto __pyx_L0; @@ -2194,31 +1954,39 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ return __pyx_r; } -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":288 + * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__"); + __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":285 + /* "numpy.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { - /* "numpy.pxd":286 + /* "numpy.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -2226,21 +1994,21 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * stdlib.free(info.strides) */ free(__pyx_v_info->format); - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":287 + /* "numpy.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":288 + /* "numpy.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -2248,14 +2016,14 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * */ free(__pyx_v_info->strides); - goto __pyx_L6; + goto __pyx_L4; } - __pyx_L6:; + __pyx_L4:; __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":764 +/* "numpy.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -2270,9 +2038,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":765 + /* "numpy.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -2280,7 +2048,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -2298,7 +2066,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":767 +/* "numpy.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -2313,9 +2081,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":768 + /* "numpy.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -2323,7 +2091,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -2341,7 +2109,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "numpy.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -2356,9 +2124,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":771 + /* "numpy.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -2366,7 +2134,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -2384,7 +2152,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "numpy.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -2399,9 +2167,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":774 + /* "numpy.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -2409,7 +2177,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -2427,7 +2195,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "numpy.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -2442,9 +2210,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":777 + /* "numpy.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -2452,7 +2220,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -2470,7 +2238,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "numpy.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -2493,18 +2261,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; + PyObject *(*__pyx_t_6)(PyObject *); int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; + int __pyx_t_10; + long __pyx_t_11; + char *__pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring"); + __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":786 + /* "numpy.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -2513,7 +2282,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":787 + /* "numpy.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -2522,7 +2291,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":790 + /* "numpy.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< @@ -2530,31 +2299,36 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * child, new_offset = fields */ if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif __Pyx_XDECREF(__pyx_v_childname); __pyx_v_childname = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":791 + /* "numpy.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); __pyx_v_fields = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":792 + /* "numpy.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< @@ -2563,20 +2337,51 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); - } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_child)); __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; @@ -2584,99 +2389,98 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_v_new_offset = __pyx_t_4; __pyx_t_4 = 0; - /* "numpy.pxd":794 + /* "numpy.pxd":798 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":795 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; } - __pyx_L5:; + __pyx_L7:; - /* "numpy.pxd":797 + /* "numpy.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_7) { + __pyx_t_8 = (__pyx_v_little_endian != 0); } else { - __pyx_t_7 = __pyx_t_6; + __pyx_t_8 = __pyx_t_7; } - if (!__pyx_t_7) { + if (!__pyx_t_8) { - /* "numpy.pxd":798 + /* "numpy.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + __pyx_t_9 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_10 = __pyx_t_9; } else { - __pyx_t_9 = __pyx_t_6; + __pyx_t_10 = __pyx_t_7; } - __pyx_t_6 = __pyx_t_9; + __pyx_t_7 = __pyx_t_10; } else { - __pyx_t_6 = __pyx_t_7; + __pyx_t_7 = __pyx_t_8; } - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; } - __pyx_L6:; + __pyx_L8:; - /* "numpy.pxd":809 + /* "numpy.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -2684,16 +2488,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!__pyx_t_6) break; + if (!__pyx_t_7) break; - /* "numpy.pxd":810 + /* "numpy.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -2702,7 +2505,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":811 + /* "numpy.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -2711,430 +2514,413 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":812 + /* "numpy.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); } - /* "numpy.pxd":814 + /* "numpy.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); - /* "numpy.pxd":816 + /* "numpy.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); - if (__pyx_t_6) { + __pyx_t_7 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_7) { - /* "numpy.pxd":817 + /* "numpy.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XDECREF(__pyx_v_t); __pyx_v_t = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":818 + /* "numpy.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); - if (__pyx_t_6) { + __pyx_t_7 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_7) { - /* "numpy.pxd":819 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; } - __pyx_L10:; + __pyx_L12:; - /* "numpy.pxd":822 + /* "numpy.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 98; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":823 + /* "numpy.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 66; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":824 + /* "numpy.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 104; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":825 + /* "numpy.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 72; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":826 + /* "numpy.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 105; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":827 + /* "numpy.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 73; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":828 + /* "numpy.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 108; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":829 + /* "numpy.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 76; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":830 + /* "numpy.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 113; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":831 + /* "numpy.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 81; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":832 + /* "numpy.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 102; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":833 + /* "numpy.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 100; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":834 + /* "numpy.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 103; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":835 + /* "numpy.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":836 + /* "numpy.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":837 + /* "numpy.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":838 + /* "numpy.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 79; - goto __pyx_L11; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":840 + /* "numpy.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L11:; + __pyx_L13:; - /* "numpy.pxd":841 + /* "numpy.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -3142,25 +2928,25 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":845 + /* "numpy.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_12; } - __pyx_L9:; + __pyx_L11:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":846 + /* "numpy.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -3189,7 +2975,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":961 +/* "numpy.pxd":965 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -3201,9 +2987,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base"); + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":963 + /* "numpy.pxd":967 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -3211,9 +2998,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "numpy.pxd":964 + /* "numpy.pxd":968 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -3225,7 +3013,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":966 + /* "numpy.pxd":970 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -3234,7 +3022,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":967 + /* "numpy.pxd":971 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -3245,7 +3033,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":968 + /* "numpy.pxd":972 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -3254,7 +3042,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":969 + /* "numpy.pxd":973 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -3266,7 +3054,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":971 +/* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -3278,19 +3066,19 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base"); + __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":972 + /* "numpy.pxd":976 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { - /* "numpy.pxd":973 + /* "numpy.pxd":977 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -3305,7 +3093,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py } /*else*/ { - /* "numpy.pxd":975 + /* "numpy.pxd":979 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -3323,201 +3111,6 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __Pyx_RefNannyFinishContext(); return __pyx_r; } -static struct __pyx_vtabstruct_7sklearn_5utils_12arraybuilder_ArrayBuilder __pyx_vtable_7sklearn_5utils_12arraybuilder_ArrayBuilder; - -static PyObject *__pyx_tp_new_7sklearn_5utils_12arraybuilder_ArrayBuilder(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *p; - PyObject *o = (*t->tp_alloc)(t, 0); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)o); - p->__pyx_vtab = __pyx_vtabptr_7sklearn_5utils_12arraybuilder_ArrayBuilder; - p->_arr = Py_None; Py_INCREF(Py_None); - return o; -} - -static void __pyx_tp_dealloc_7sklearn_5utils_12arraybuilder_ArrayBuilder(PyObject *o) { - struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *p = (struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)o; - Py_XDECREF(p->_arr); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_7sklearn_5utils_12arraybuilder_ArrayBuilder(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *p = (struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)o; - if (p->_arr) { - e = (*v)(p->_arr, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7sklearn_5utils_12arraybuilder_ArrayBuilder(PyObject *o) { - struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *p = (struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *)o; - PyObject* tmp; - tmp = ((PyObject*)p->_arr); - p->_arr = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyMethodDef __pyx_methods_7sklearn_5utils_12arraybuilder_ArrayBuilder[] = { - {__Pyx_NAMESTR("append"), (PyCFunction)__pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder_2append, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_12arraybuilder_12ArrayBuilder_2append)}, - {__Pyx_NAMESTR("get"), (PyCFunction)__pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder_3get, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_12arraybuilder_12ArrayBuilder_3get)}, - {0, 0, 0, 0} -}; - -static PyNumberMethods __pyx_tp_as_number_ArrayBuilder = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; - -static PySequenceMethods __pyx_tp_as_sequence_ArrayBuilder = { - __pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder_1__len__, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_ArrayBuilder = { - __pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder_1__len__, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_ArrayBuilder = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; - -static PyTypeObject __pyx_type_7sklearn_5utils_12arraybuilder_ArrayBuilder = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.utils.arraybuilder.ArrayBuilder"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_5utils_12arraybuilder_ArrayBuilder, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_ArrayBuilder, /*tp_as_number*/ - &__pyx_tp_as_sequence_ArrayBuilder, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_ArrayBuilder, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_ArrayBuilder, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - __Pyx_DOCSTR("Helper class to incrementally build a 1-d numpy.ndarray"), /*tp_doc*/ - __pyx_tp_traverse_7sklearn_5utils_12arraybuilder_ArrayBuilder, /*tp_traverse*/ - __pyx_tp_clear_7sklearn_5utils_12arraybuilder_ArrayBuilder, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_5utils_12arraybuilder_ArrayBuilder, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pf_7sklearn_5utils_12arraybuilder_12ArrayBuilder___init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_5utils_12arraybuilder_ArrayBuilder, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} @@ -3525,8 +3118,12 @@ static PyMethodDef __pyx_methods[] = { #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else PyModuleDef_HEAD_INIT, - __Pyx_NAMESTR("arraybuilder"), + #endif + __Pyx_NAMESTR("typedefs"), 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, @@ -3544,25 +3141,26 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, - {&__pyx_n_s__GROWTH_FACTOR, __pyx_k__GROWTH_FACTOR, sizeof(__pyx_k__GROWTH_FACTOR), 0, 0, 1, 1}, + {&__pyx_n_s__DTYPE, __pyx_k__DTYPE, sizeof(__pyx_k__DTYPE), 0, 0, 1, 1}, + {&__pyx_n_s__ITYPE, __pyx_k__ITYPE, sizeof(__pyx_k__ITYPE), 0, 0, 1, 1}, {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, + {&__pyx_n_s____import__, __pyx_k____import__, sizeof(__pyx_k____import__), 0, 0, 1, 1}, {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, - {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, - {&__pyx_n_s__initial_capacity, __pyx_k__initial_capacity, sizeof(__pyx_k__initial_capacity), 0, 0, 1, 1}, + {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, + {&__pyx_n_s__inf, __pyx_k__inf, sizeof(__pyx_k__inf), 0, 0, 1, 1}, + {&__pyx_n_s__intp, __pyx_k__intp, sizeof(__pyx_k__intp), 0, 0, 1, 1}, {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, + {&__pyx_n_s__pi, __pyx_k__pi, sizeof(__pyx_k__pi), 0, 0, 1, 1}, {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__resize, __pyx_k__resize, sizeof(__pyx_k__resize), 0, 0, 1, 1}, - {&__pyx_n_s__size, __pyx_k__size, sizeof(__pyx_k__size), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -3570,90 +3168,72 @@ static int __Pyx_InitCachedBuiltins(void) { static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "numpy.pxd":211 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_2 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_2 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_1)); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_2); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_1)); - PyTuple_SET_ITEM(__pyx_k_tuple_2, 0, ((PyObject *)__pyx_kp_u_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_1)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); - /* "numpy.pxd":215 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_4 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_3)); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_4); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_3)); - PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_u_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_3)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_6 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_5)); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_6); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); - /* "numpy.pxd":795 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_9 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_8)); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_9); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_10 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_5)); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_10); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); - /* "numpy.pxd":819 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_12 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_11)); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_12); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); - PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); __Pyx_RefNannyFinishContext(); return 0; @@ -3663,25 +3243,27 @@ static int __Pyx_InitCachedConstants(void) { } static int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_256 = PyInt_FromLong(256); if (unlikely(!__pyx_int_256)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 -PyMODINIT_FUNC initarraybuilder(void); /*proto*/ -PyMODINIT_FUNC initarraybuilder(void) +PyMODINIT_FUNC inittypedefs(void); /*proto*/ +PyMODINIT_FUNC inittypedefs(void) #else -PyMODINIT_FUNC PyInit_arraybuilder(void); /*proto*/ -PyMODINIT_FUNC PyInit_arraybuilder(void) +PyMODINIT_FUNC PyInit_typedefs(void); /*proto*/ +PyMODINIT_FUNC PyInit_typedefs(void) #endif { PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + __pyx_t_7sklearn_9neighbors_8typedefs_DTYPE_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -3692,12 +3274,18 @@ PyMODINIT_FUNC PyInit_arraybuilder(void) Py_FatalError("failed to import 'refnanny' module"); } #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_arraybuilder(void)"); - if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_typedefs(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #ifdef __Pyx_CyFunction_USED - if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -3708,82 +3296,150 @@ PyMODINIT_FUNC PyInit_arraybuilder(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("arraybuilder"), __pyx_methods, 0, 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("typedefs"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.neighbors.typedefs")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.neighbors.typedefs", __pyx_m) < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ - if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_module_is_main_sklearn__utils__arraybuilder) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__neighbors__typedefs) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } /*--- Builtin init code ---*/ - if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ - if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ - __pyx_vtabptr_7sklearn_5utils_12arraybuilder_ArrayBuilder = &__pyx_vtable_7sklearn_5utils_12arraybuilder_ArrayBuilder; - __pyx_vtable_7sklearn_5utils_12arraybuilder_ArrayBuilder._grow = (PyObject *(*)(struct __pyx_obj_7sklearn_5utils_12arraybuilder_ArrayBuilder *))__pyx_f_7sklearn_5utils_12arraybuilder_12ArrayBuilder__grow; - if (PyType_Ready(&__pyx_type_7sklearn_5utils_12arraybuilder_ArrayBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_5utils_12arraybuilder_ArrayBuilder.tp_dict, __pyx_vtabptr_7sklearn_5utils_12arraybuilder_ArrayBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "ArrayBuilder", (PyObject *)&__pyx_type_7sklearn_5utils_12arraybuilder_ArrayBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_5utils_12arraybuilder_ArrayBuilder = &__pyx_type_7sklearn_5utils_12arraybuilder_ArrayBuilder; /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ - /* "sklearn/utils/arraybuilder.pyx":3 - * cimport cython - * cimport numpy as np - * import numpy as np # <<<<<<<<<<<<<< + /* "sklearn/neighbors/typedefs.pyx":3 + * #!python * + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * from libc.math cimport sqrt + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/neighbors/typedefs.pyx":13 + * #cdef ITYPE_t[:] idummy_view = &idummy + * #ITYPE = np.asarray(idummy_view).dtype + * ITYPE = np.intp # WARNING: this should match ITYPE_t in typedefs.pxd # <<<<<<<<<<<<<< * + * #cdef DTYPE_t ddummy */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__intp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s__ITYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/utils/arraybuilder.pyx":10 - * # Or: let's reinvent the wheel! + /* "sklearn/neighbors/typedefs.pyx":18 + * #cdef DTYPE_t[:] ddummy_view = &ddummy + * #DTYPE = np.asarray(ddummy_view).dtype + * DTYPE = np.float64 # WARNING: this should match DTYPE_t in typedefs.pxd # <<<<<<<<<<<<<< * - * GROWTH_FACTOR = 1.5 # <<<<<<<<<<<<<< + * # some handy constants + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s__DTYPE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/neighbors/typedefs.pyx":21 * - * cdef Py_ssize_t _nelems + * # some handy constants + * cdef DTYPE_t INF = np.inf # <<<<<<<<<<<<<< + * cdef DTYPE_t PI = np.pi + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) */ - __pyx_t_1 = PyFloat_FromDouble(1.5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_ptype_7sklearn_5utils_12arraybuilder_ArrayBuilder->tp_dict, __pyx_n_s__GROWTH_FACTOR, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - PyType_Modified(__pyx_ptype_7sklearn_5utils_12arraybuilder_ArrayBuilder); + __pyx_t_3 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_3 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_7sklearn_9neighbors_8typedefs_INF = __pyx_t_3; - /* "sklearn/utils/arraybuilder.pyx":1 - * cimport cython # <<<<<<<<<<<<<< - * cimport numpy as np + /* "sklearn/neighbors/typedefs.pyx":22 + * # some handy constants + * cdef DTYPE_t INF = np.inf + * cdef DTYPE_t PI = np.pi # <<<<<<<<<<<<<< + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__pi); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_3 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_7sklearn_9neighbors_8typedefs_PI = __pyx_t_3; + + /* "sklearn/neighbors/typedefs.pyx":23 + * cdef DTYPE_t INF = np.inf + * cdef DTYPE_t PI = np.pi + * cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) # <<<<<<<<<<<<<< + */ + __pyx_v_7sklearn_9neighbors_8typedefs_ROOT_2PI = sqrt((2.0 * __pyx_v_7sklearn_9neighbors_8typedefs_PI)); + + /* "sklearn/neighbors/typedefs.pyx":1 + * #!python # <<<<<<<<<<<<<< + * * import numpy as np */ - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - /* "numpy.pxd":971 + /* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -3793,11 +3449,12 @@ PyMODINIT_FUNC PyInit_arraybuilder(void) goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { - __Pyx_AddTraceback("init sklearn.utils.arraybuilder", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("init sklearn.neighbors.typedefs", __pyx_clineno, __pyx_lineno, __pyx_filename); Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init sklearn.utils.arraybuilder"); + PyErr_SetString(PyExc_ImportError, "init sklearn.neighbors.typedefs"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); @@ -3809,7 +3466,6 @@ PyMODINIT_FUNC PyInit_arraybuilder(void) } /* Runtime support code */ - #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; @@ -3826,144 +3482,23 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { } #endif /* CYTHON_REFNANNY */ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); - #endif -} - -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { - values[name-argnames] = value; - } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - } - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%s' is not defined", PyString_AS_STRING(name)); +#endif } return result; } - static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; @@ -3973,78 +3508,81 @@ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyOb Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif } - static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif } - #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) + if (PyClass_Check(type)) { #else - if (!PyType_Check(type)) + if (PyType_Check(type)) { #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - /* Normalize to raise , */ - Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } #endif } - __Pyx_ErrRestore(type, value, tb); return; raise_error: @@ -4053,10 +3591,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tb); return; } - #else /* Python 3+ */ - static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -4066,7 +3603,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } if (value == Py_None) value = 0; - if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, @@ -4075,37 +3611,58 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } - +#if PY_VERSION_HEX >= 0x03030000 if (cause) { +#else + if (cause && cause != Py_None) { +#endif PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; - } - else if (PyExceptionInstance_Check(cause)) { + } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; @@ -4115,35 +3672,70 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tmp_tb); } } - bad: + Py_XDECREF(owned_instance); return; } #endif -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", + index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; } else { - __Pyx_RaiseTooManyValuesError(index); + return __Pyx_IterFinish(); } + return 0; } static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { @@ -4158,16 +3750,35 @@ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { return 0; } -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s____import__); if (!py_import) goto bad; + #endif if (from_list) list = from_list; else { @@ -4184,12 +3795,42 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { goto bad; #if PY_VERSION_HEX >= 0x02050000 { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } } #else if (level>0) { @@ -4200,8 +3841,10 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { name, global_dict, empty_dict, list, NULL); #endif bad: - Py_XDECREF(empty_list); + #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } @@ -4636,10 +4279,15 @@ static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { return (int)__Pyx_PyInt_AsLong(x); } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { const unsigned long neg_one = (unsigned long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -4652,6 +4300,16 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); @@ -4659,6 +4317,17 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { } return (unsigned long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (unsigned long)PyLong_AsLong(x); } } else { @@ -4671,10 +4340,15 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -4687,6 +4361,16 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned PY_LONG_LONG"); @@ -4694,6 +4378,17 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje } return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -4706,10 +4401,15 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { const long neg_one = (long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -4722,6 +4422,16 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); @@ -4729,6 +4439,17 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { } return (long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (long)PyLong_AsLong(x); } } else { @@ -4741,10 +4462,15 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -4757,6 +4483,16 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to PY_LONG_LONG"); @@ -4764,6 +4500,17 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { } return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -4776,10 +4523,15 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { const signed long neg_one = (signed long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -4792,6 +4544,16 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed long"); @@ -4799,6 +4561,17 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { } return (signed long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (signed long)PyLong_AsLong(x); } } else { @@ -4811,10 +4584,15 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -4827,6 +4605,16 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed PY_LONG_LONG"); @@ -4834,6 +4622,17 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* } return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (signed PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -4865,22 +4664,22 @@ static int __Pyx_check_binary_version(void) { return 0; } -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItemString(dict, "__pyx_vtable__", ob) < 0) +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) goto bad; - Py_DECREF(ob); - return 0; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; bad: - Py_XDECREF(ob); - return -1; + Py_XDECREF(py_name); + return 0; } +#endif #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType @@ -4891,7 +4690,10 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; @@ -4911,7 +4713,19 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -4921,7 +4735,7 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%s.%s has the wrong size, try recompiling", module_name, class_name); @@ -4935,47 +4749,105 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - py_name = __Pyx_PyIdentifier_FromString(name); - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); } -#endif #include "compile.h" #include "frameobject.h" #include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); + py_srcfile = PyString_FromString(filename); #else - py_srcfile = PyUnicode_FromString(__pyx_filename); + py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; - if (__pyx_clineno) { + if (c_line) { #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { @@ -4986,8 +4858,6 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, #endif } if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; py_code = __Pyx_PyCode_New( 0, /*int argcount,*/ 0, /*int kwonlyargcount,*/ @@ -4995,17 +4865,38 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ + py_line, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); - if (!py_code) goto bad; + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ @@ -5013,11 +4904,9 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; + py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); } @@ -5052,26 +4941,82 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (r < 0) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -5087,7 +5032,7 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { @@ -5105,7 +5050,6 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject* x = PyNumber_Index(b); @@ -5114,7 +5058,6 @@ static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) @@ -5128,14 +5071,12 @@ static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); #endif } - static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); + if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); return (size_t)-1; } return (size_t)val; diff --git a/sklearn/neighbors/typedefs.pxd b/sklearn/neighbors/typedefs.pxd new file mode 100644 index 0000000000000..b121953d15e4e --- /dev/null +++ b/sklearn/neighbors/typedefs.pxd @@ -0,0 +1,18 @@ +#!python +cimport numpy as np + +# Floating point/data type +ctypedef np.float64_t DTYPE_t # WARNING: should match DTYPE in typedefs.pyx + +cdef enum: + DTYPECODE = np.NPY_FLOAT64 + ITYPECODE = np.NPY_INTP + +# Index/integer type. +# WARNING: ITYPE_t must be a signed integer type or you will have a bad time! +ctypedef np.intp_t ITYPE_t # WARNING: should match ITYPE in typedefs.pyx + +# Fused type for certain operations +ctypedef fused DITYPE_t: + ITYPE_t + DTYPE_t diff --git a/sklearn/neighbors/typedefs.pyx b/sklearn/neighbors/typedefs.pyx new file mode 100644 index 0000000000000..bbdfd00505b43 --- /dev/null +++ b/sklearn/neighbors/typedefs.pyx @@ -0,0 +1,23 @@ +#!python + +import numpy as np +cimport numpy as np +from libc.math cimport sqrt + +# use a hack to determine the associated numpy data types +# NOTE: the following requires the buffer interface, only available in +# numpy 1.5+. We'll choose the DTYPE by hand instead. +#cdef ITYPE_t idummy +#cdef ITYPE_t[:] idummy_view = &idummy +#ITYPE = np.asarray(idummy_view).dtype +ITYPE = np.intp # WARNING: this should match ITYPE_t in typedefs.pxd + +#cdef DTYPE_t ddummy +#cdef DTYPE_t[:] ddummy_view = &ddummy +#DTYPE = np.asarray(ddummy_view).dtype +DTYPE = np.float64 # WARNING: this should match DTYPE_t in typedefs.pxd + +# some handy constants +cdef DTYPE_t INF = np.inf +cdef DTYPE_t PI = np.pi +cdef DTYPE_t ROOT_2PI = sqrt(2 * PI) diff --git a/sklearn/neighbors/unsupervised.py b/sklearn/neighbors/unsupervised.py index b53c896091739..a599ce2f3532c 100644 --- a/sklearn/neighbors/unsupervised.py +++ b/sklearn/neighbors/unsupervised.py @@ -23,7 +23,7 @@ class NearestNeighbors(NeighborsBase, KNeighborsMixin, Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - - 'kd_tree' will use :class:`scipy.spatial.cKDtree` + - 'kd_tree' will use :class:`KDtree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. @@ -32,27 +32,49 @@ class NearestNeighbors(NeighborsBase, KNeighborsMixin, this parameter, using brute force. leaf_size : int, optional (default = 30) - Leaf size passed to BallTree or cKDTree. This can affect the + Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. - warn_on_equidistant : boolean, optional. Defaults to True. - Generate a warning if equidistant neighbors are discarded. - For classification or regression based on k-neighbors, if - neighbor k and neighbor k+1 have identical distances but - different labels, then the result will be dependent on the - ordering of the training data. - If the fit method is ``'kd_tree'``, no warnings will be generated. - p: integer, optional (default = 2) Parameter for the Minkowski metric from sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + + metric : string or callable, default 'minkowski' + metric to use for distance computation. Any metric from scikit-learn + or scipy.spatial.distance can be used. + + If metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays as input and return one value indicating the + distance between them. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + Distance matrices are not supported. + + Valid values for metric are: + + - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan'] + + - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', + 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', + 'sqeuclidean', 'yule'] + + See the documentation for scipy.spatial.distance for details on these + metrics. + + metric_params: dict, optional (default = None) + additional keyword arguments for the metric function. Examples -------- + >>> import numpy as np >>> from sklearn.neighbors import NearestNeighbors >>> samples = [[0, 0, 2], [1, 0, 0], [0, 0, 1]] @@ -64,8 +86,9 @@ class NearestNeighbors(NeighborsBase, KNeighborsMixin, ... #doctest: +ELLIPSIS array([[2, 0]]...) - >>> neigh.radius_neighbors([0, 0, 1.3], 0.4, return_distance=False) - array([[2]]) + >>> rng = neigh.radius_neighbors([0, 0, 1.3], 0.4, return_distance=False) + >>> np.asarray(rng[0][0]) + array(2) See also -------- @@ -84,11 +107,10 @@ class NearestNeighbors(NeighborsBase, KNeighborsMixin, """ def __init__(self, n_neighbors=5, radius=1.0, - algorithm='auto', leaf_size=30, - warn_on_equidistant=True, p=2): + algorithm='auto', leaf_size=30, metric='minkowski', + p=2, metric_params=None, **kwargs): self._init_params(n_neighbors=n_neighbors, radius=radius, algorithm=algorithm, - leaf_size=leaf_size, - warn_on_equidistant=warn_on_equidistant, - p=p) + leaf_size=leaf_size, metric=metric, p=p, + metric_params=metric_params, **kwargs) diff --git a/sklearn/neural_network/__init__.py b/sklearn/neural_network/__init__.py new file mode 100644 index 0000000000000..43bac35c8c597 --- /dev/null +++ b/sklearn/neural_network/__init__.py @@ -0,0 +1,8 @@ +""" +The :mod:`sklearn.neural_network` module includes models based on neural +networks. +""" + +from .rbm import BernoulliRBM + +__all__ = ['BernoulliRBM'] diff --git a/sklearn/neural_network/rbm.py b/sklearn/neural_network/rbm.py new file mode 100644 index 0000000000000..b646dae0d9d91 --- /dev/null +++ b/sklearn/neural_network/rbm.py @@ -0,0 +1,363 @@ +"""Restricted Boltzmann Machine +""" + +# Authors: Yann N. Dauphin +# Vlad Niculae +# Gabriel Synnaeve +# Lars Buitinck +# License: BSD 3 clause + +import time + +import numpy as np +import scipy.sparse as sp + +from ..base import BaseEstimator +from ..base import TransformerMixin +from ..externals.six.moves import xrange +from ..utils import check_array +from ..utils import check_random_state +from ..utils import gen_even_slices +from ..utils import issparse +from ..utils.extmath import safe_sparse_dot +from ..utils.extmath import log_logistic +from ..utils.fixes import expit # logistic function +from ..utils.validation import check_is_fitted + + +class BernoulliRBM(BaseEstimator, TransformerMixin): + """Bernoulli Restricted Boltzmann Machine (RBM). + + A Restricted Boltzmann Machine with binary visible units and + binary hiddens. Parameters are estimated using Stochastic Maximum + Likelihood (SML), also known as Persistent Contrastive Divergence (PCD) + [2]. + + The time complexity of this implementation is ``O(d ** 2)`` assuming + d ~ n_features ~ n_components. + + Parameters + ---------- + n_components : int, optional + Number of binary hidden units. + + learning_rate : float, optional + The learning rate for weight updates. It is *highly* recommended + to tune this hyper-parameter. Reasonable values are in the + 10**[0., -3.] range. + + batch_size : int, optional + Number of examples per minibatch. + + n_iter : int, optional + Number of iterations/sweeps over the training dataset to perform + during training. + + verbose : int, optional + The verbosity level. The default, zero, means silent mode. + + random_state : integer or numpy.RandomState, optional + A random number generator instance to define the state of the + random permutations generator. If an integer is given, it fixes the + seed. Defaults to the global numpy random number generator. + + Attributes + ---------- + intercept_hidden_ : array-like, shape (n_components,) + Biases of the hidden units. + + intercept_visible_ : array-like, shape (n_features,) + Biases of the visible units. + + components_ : array-like, shape (n_components, n_features) + Weight matrix, where n_features in the number of + visible units and n_components is the number of hidden units. + + Examples + -------- + + >>> import numpy as np + >>> from sklearn.neural_network import BernoulliRBM + >>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) + >>> model = BernoulliRBM(n_components=2) + >>> model.fit(X) + BernoulliRBM(batch_size=10, learning_rate=0.1, n_components=2, n_iter=10, + random_state=None, verbose=0) + + References + ---------- + + [1] Hinton, G. E., Osindero, S. and Teh, Y. A fast learning algorithm for + deep belief nets. Neural Computation 18, pp 1527-1554. + http://www.cs.toronto.edu/~hinton/absps/fastnc.pdf + + [2] Tieleman, T. Training Restricted Boltzmann Machines using + Approximations to the Likelihood Gradient. International Conference + on Machine Learning (ICML) 2008 + """ + def __init__(self, n_components=256, learning_rate=0.1, batch_size=10, + n_iter=10, verbose=0, random_state=None): + self.n_components = n_components + self.learning_rate = learning_rate + self.batch_size = batch_size + self.n_iter = n_iter + self.verbose = verbose + self.random_state = random_state + + def transform(self, X): + """Compute the hidden layer activation probabilities, P(h=1|v=X). + + Parameters + ---------- + X : {array-like, sparse matrix} shape (n_samples, n_features) + The data to be transformed. + + Returns + ------- + h : array, shape (n_samples, n_components) + Latent representations of the data. + """ + check_is_fitted(self, "components_") + + X = check_array(X, accept_sparse='csr', dtype=np.float) + return self._mean_hiddens(X) + + def _mean_hiddens(self, v): + """Computes the probabilities P(h=1|v). + + Parameters + ---------- + v : array-like, shape (n_samples, n_features) + Values of the visible layer. + + Returns + ------- + h : array-like, shape (n_samples, n_components) + Corresponding mean field values for the hidden layer. + """ + p = safe_sparse_dot(v, self.components_.T) + p += self.intercept_hidden_ + return expit(p, out=p) + + def _sample_hiddens(self, v, rng): + """Sample from the distribution P(h|v). + + Parameters + ---------- + v : array-like, shape (n_samples, n_features) + Values of the visible layer to sample from. + + rng : RandomState + Random number generator to use. + + Returns + ------- + h : array-like, shape (n_samples, n_components) + Values of the hidden layer. + """ + p = self._mean_hiddens(v) + return (rng.random_sample(size=p.shape) < p) + + def _sample_visibles(self, h, rng): + """Sample from the distribution P(v|h). + + Parameters + ---------- + h : array-like, shape (n_samples, n_components) + Values of the hidden layer to sample from. + + rng : RandomState + Random number generator to use. + + Returns + ------- + v : array-like, shape (n_samples, n_features) + Values of the visible layer. + """ + p = np.dot(h, self.components_) + p += self.intercept_visible_ + expit(p, out=p) + return (rng.random_sample(size=p.shape) < p) + + def _free_energy(self, v): + """Computes the free energy F(v) = - log sum_h exp(-E(v,h)). + + Parameters + ---------- + v : array-like, shape (n_samples, n_features) + Values of the visible layer. + + Returns + ------- + free_energy : array-like, shape (n_samples,) + The value of the free energy. + """ + return (- safe_sparse_dot(v, self.intercept_visible_) + - np.logaddexp(0, safe_sparse_dot(v, self.components_.T) + + self.intercept_hidden_).sum(axis=1)) + + def gibbs(self, v): + """Perform one Gibbs sampling step. + + Parameters + ---------- + v : array-like, shape (n_samples, n_features) + Values of the visible layer to start from. + + Returns + ------- + v_new : array-like, shape (n_samples, n_features) + Values of the visible layer after one Gibbs step. + """ + check_is_fitted(self, "components_") + if not hasattr(self, "random_state_"): + self.random_state_ = check_random_state(self.random_state) + h_ = self._sample_hiddens(v, self.random_state_) + v_ = self._sample_visibles(h_, self.random_state_) + + return v_ + + def partial_fit(self, X, y=None): + """Fit the model to the data X which should contain a partial + segment of the data. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data. + + Returns + ------- + self : BernoulliRBM + The fitted model. + """ + X = check_array(X, accept_sparse='csr', dtype=np.float) + if not hasattr(self, 'random_state_'): + self.random_state_ = check_random_state(self.random_state) + if not hasattr(self, 'components_'): + self.components_ = np.asarray( + self.random_state_.normal( + 0, + 0.01, + (self.n_components, X.shape[1]) + ), + order='fortran') + if not hasattr(self, 'intercept_hidden_'): + self.intercept_hidden_ = np.zeros(self.n_components, ) + if not hasattr(self, 'intercept_visible_'): + self.intercept_visible_ = np.zeros(X.shape[1], ) + if not hasattr(self, 'h_samples_'): + self.h_samples_ = np.zeros((self.batch_size, self.n_components)) + + self._fit(X, self.random_state_) + + def _fit(self, v_pos, rng): + """Inner fit for one mini-batch. + + Adjust the parameters to maximize the likelihood of v using + Stochastic Maximum Likelihood (SML). + + Parameters + ---------- + v_pos : array-like, shape (n_samples, n_features) + The data to use for training. + + rng : RandomState + Random number generator to use for sampling. + """ + h_pos = self._mean_hiddens(v_pos) + v_neg = self._sample_visibles(self.h_samples_, rng) + h_neg = self._mean_hiddens(v_neg) + + lr = float(self.learning_rate) / v_pos.shape[0] + update = safe_sparse_dot(v_pos.T, h_pos, dense_output=True).T + update -= np.dot(h_neg.T, v_neg) + self.components_ += lr * update + self.intercept_hidden_ += lr * (h_pos.sum(axis=0) - h_neg.sum(axis=0)) + self.intercept_visible_ += lr * (np.asarray( + v_pos.sum(axis=0)).squeeze() - + v_neg.sum(axis=0)) + + h_neg[rng.uniform(size=h_neg.shape) < h_neg] = 1.0 # sample binomial + self.h_samples_ = np.floor(h_neg, h_neg) + + def score_samples(self, X): + """Compute the pseudo-likelihood of X. + + Parameters + ---------- + X : {array-like, sparse matrix} shape (n_samples, n_features) + Values of the visible layer. Must be all-boolean (not checked). + + Returns + ------- + pseudo_likelihood : array-like, shape (n_samples,) + Value of the pseudo-likelihood (proxy for likelihood). + + Notes + ----- + This method is not deterministic: it computes a quantity called the + free energy on X, then on a randomly corrupted version of X, and + returns the log of the logistic function of the difference. + """ + check_is_fitted(self, "components_") + + v = check_array(X, accept_sparse='csr') + rng = check_random_state(self.random_state) + + # Randomly corrupt one feature in each sample in v. + ind = (np.arange(v.shape[0]), + rng.randint(0, v.shape[1], v.shape[0])) + if issparse(v): + data = -2 * v[ind] + 1 + v_ = v + sp.csr_matrix((data.A.ravel(), ind), shape=v.shape) + else: + v_ = v.copy() + v_[ind] = 1 - v_[ind] + + fe = self._free_energy(v) + fe_ = self._free_energy(v_) + return v.shape[1] * log_logistic(fe_ - fe) + + def fit(self, X, y=None): + """Fit the model to the data X. + + Parameters + ---------- + X : {array-like, sparse matrix} shape (n_samples, n_features) + Training data. + + Returns + ------- + self : BernoulliRBM + The fitted model. + """ + X = check_array(X, accept_sparse='csr', dtype=np.float) + n_samples = X.shape[0] + rng = check_random_state(self.random_state) + + self.components_ = np.asarray( + rng.normal(0, 0.01, (self.n_components, X.shape[1])), + order='fortran') + self.intercept_hidden_ = np.zeros(self.n_components, ) + self.intercept_visible_ = np.zeros(X.shape[1], ) + self.h_samples_ = np.zeros((self.batch_size, self.n_components)) + + n_batches = int(np.ceil(float(n_samples) / self.batch_size)) + batch_slices = list(gen_even_slices(n_batches * self.batch_size, + n_batches, n_samples)) + verbose = self.verbose + begin = time.time() + for iteration in xrange(1, self.n_iter + 1): + for batch_slice in batch_slices: + self._fit(X[batch_slice], rng) + + if verbose: + end = time.time() + print("[%s] Iteration %d, pseudo-likelihood = %.2f," + " time = %.2fs" + % (type(self).__name__, iteration, + self.score_samples(X).mean(), end - begin)) + begin = end + + return self diff --git a/sklearn/neural_network/tests/test_rbm.py b/sklearn/neural_network/tests/test_rbm.py new file mode 100644 index 0000000000000..6041e246f1dcd --- /dev/null +++ b/sklearn/neural_network/tests/test_rbm.py @@ -0,0 +1,200 @@ +import sys +import re + +import numpy as np +from scipy.sparse import csc_matrix, csr_matrix, lil_matrix +from sklearn.utils.testing import (assert_almost_equal, assert_array_equal, + assert_true) + +from sklearn.datasets import load_digits +from sklearn.externals.six.moves import cStringIO as StringIO +from sklearn.neural_network import BernoulliRBM +from sklearn.utils.validation import assert_all_finite +np.seterr(all='warn') + +Xdigits = load_digits().data +Xdigits -= Xdigits.min() +Xdigits /= Xdigits.max() + + +def test_fit(): + X = Xdigits.copy() + + rbm = BernoulliRBM(n_components=64, learning_rate=0.1, + batch_size=10, n_iter=7, random_state=9) + rbm.fit(X) + + assert_almost_equal(rbm.score_samples(X).mean(), -21., decimal=0) + + # in-place tricks shouldn't have modified X + assert_array_equal(X, Xdigits) + + +def test_partial_fit(): + X = Xdigits.copy() + rbm = BernoulliRBM(n_components=64, learning_rate=0.1, + batch_size=20, random_state=9) + n_samples = X.shape[0] + n_batches = int(np.ceil(float(n_samples) / rbm.batch_size)) + batch_slices = np.array_split(X, n_batches) + + for i in range(7): + for batch in batch_slices: + rbm.partial_fit(batch) + + assert_almost_equal(rbm.score_samples(X).mean(), -21., decimal=0) + assert_array_equal(X, Xdigits) + + +def test_transform(): + X = Xdigits[:100] + rbm1 = BernoulliRBM(n_components=16, batch_size=5, + n_iter=5, random_state=42) + rbm1.fit(X) + + Xt1 = rbm1.transform(X) + Xt2 = rbm1._mean_hiddens(X) + + assert_array_equal(Xt1, Xt2) + + +def test_small_sparse(): + """BernoulliRBM should work on small sparse matrices.""" + X = csr_matrix(Xdigits[:4]) + BernoulliRBM().fit(X) # no exception + + +def test_small_sparse_partial_fit(): + for sparse in [csc_matrix, csr_matrix]: + X_sparse = sparse(Xdigits[:100]) + X = Xdigits[:100].copy() + + rbm1 = BernoulliRBM(n_components=64, learning_rate=0.1, + batch_size=10, random_state=9) + rbm2 = BernoulliRBM(n_components=64, learning_rate=0.1, + batch_size=10, random_state=9) + + rbm1.partial_fit(X_sparse) + rbm2.partial_fit(X) + + assert_almost_equal(rbm1.score_samples(X).mean(), + rbm2.score_samples(X).mean(), + decimal=0) + + +def test_sample_hiddens(): + rng = np.random.RandomState(0) + X = Xdigits[:100] + rbm1 = BernoulliRBM(n_components=2, batch_size=5, + n_iter=5, random_state=42) + rbm1.fit(X) + + h = rbm1._mean_hiddens(X[0]) + hs = np.mean([rbm1._sample_hiddens(X[0], rng) for i in range(100)], 0) + + assert_almost_equal(h, hs, decimal=1) + + +def test_fit_gibbs(): + """ + Gibbs on the RBM hidden layer should be able to recreate [[0], [1]] + from the same input + """ + rng = np.random.RandomState(42) + X = np.array([[0.], [1.]]) + rbm1 = BernoulliRBM(n_components=2, batch_size=2, + n_iter=42, random_state=rng) + # you need that much iters + rbm1.fit(X) + assert_almost_equal(rbm1.components_, + np.array([[0.02649814], [0.02009084]]), decimal=4) + assert_almost_equal(rbm1.gibbs(X), X) + return rbm1 + + +def test_fit_gibbs_sparse(): + """ + Gibbs on the RBM hidden layer should be able to recreate [[0], [1]] from + the same input even when the input is sparse, and test against non-sparse + """ + rbm1 = test_fit_gibbs() + rng = np.random.RandomState(42) + from scipy.sparse import csc_matrix + X = csc_matrix([[0.], [1.]]) + rbm2 = BernoulliRBM(n_components=2, batch_size=2, + n_iter=42, random_state=rng) + rbm2.fit(X) + assert_almost_equal(rbm2.components_, + np.array([[0.02649814], [0.02009084]]), decimal=4) + assert_almost_equal(rbm2.gibbs(X), X.toarray()) + assert_almost_equal(rbm1.components_, rbm2.components_) + + +def test_gibbs_smoke(): + """Check if we don't get NaNs sampling the full digits dataset. + Also check that sampling again will yield different results.""" + X = Xdigits + rbm1 = BernoulliRBM(n_components=42, batch_size=40, + n_iter=20, random_state=42) + rbm1.fit(X) + X_sampled = rbm1.gibbs(X) + assert_all_finite(X_sampled) + X_sampled2 = rbm1.gibbs(X) + assert_true(np.all((X_sampled != X_sampled2).max(axis=1))) + + +def test_score_samples(): + """Test score_samples (pseudo-likelihood) method.""" + # Assert that pseudo-likelihood is computed without clipping. + # See Fabian's blog, http://bit.ly/1iYefRk + rng = np.random.RandomState(42) + X = np.vstack([np.zeros(1000), np.ones(1000)]) + rbm1 = BernoulliRBM(n_components=10, batch_size=2, + n_iter=10, random_state=rng) + rbm1.fit(X) + assert_true((rbm1.score_samples(X) < -300).all()) + + # Sparse vs. dense should not affect the output. Also test sparse input + # validation. + rbm1.random_state = 42 + d_score = rbm1.score_samples(X) + rbm1.random_state = 42 + s_score = rbm1.score_samples(lil_matrix(X)) + assert_almost_equal(d_score, s_score) + + # Test numerical stability (#2785): would previously generate infinities + # and crash with an exception. + with np.errstate(under='ignore'): + rbm1.score_samples(np.arange(1000) * 100) + + +def test_rbm_verbose(): + rbm = BernoulliRBM(n_iter=2, verbose=10) + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + rbm.fit(Xdigits) + finally: + sys.stdout = old_stdout + + +def test_sparse_and_verbose(): + """ + Make sure RBM works with sparse input when verbose=True + """ + old_stdout = sys.stdout + sys.stdout = StringIO() + from scipy.sparse import csc_matrix + X = csc_matrix([[0.], [1.]]) + rbm = BernoulliRBM(n_components=2, batch_size=2, n_iter=1, + random_state=42, verbose=True) + try: + rbm.fit(X) + s = sys.stdout.getvalue() + # make sure output is sound + assert_true(re.match(r"\[BernoulliRBM\] Iteration 1," + r" pseudo-likelihood = -?(\d)+(\.\d+)?," + r" time = (\d|\.)+s", + s)) + finally: + sys.stdout = old_stdout diff --git a/sklearn/pipeline.py b/sklearn/pipeline.py index 7ee4a5cd132d8..86d0e624cb54b 100644 --- a/sklearn/pipeline.py +++ b/sklearn/pipeline.py @@ -1,28 +1,36 @@ """ -The :mod:`sklearn.pipeline` module implements utilites to build a composite +The :mod:`sklearn.pipeline` module implements utilities to build a composite estimator, as a chain of transforms and estimators. """ # Author: Edouard Duchesnay # Gael Varoquaux # Virgile Fritsch # Alexandre Gramfort +# Lars Buitinck # Licence: BSD -from .base import BaseEstimator +from collections import defaultdict -__all__ = ['Pipeline'] +import numpy as np +from scipy import sparse +from .base import BaseEstimator, TransformerMixin +from .externals.joblib import Parallel, delayed +from .externals import six +from .utils import tosequence +from .utils.metaestimators import if_delegate_has_method +from .externals.six import iteritems + +__all__ = ['Pipeline', 'FeatureUnion'] -# One round of beers on me if someone finds out why the backslash -# is needed in the Attributes section so as not to upset sphinx. class Pipeline(BaseEstimator): """Pipeline of transforms with a final estimator. Sequentially apply a list of transforms and a final estimator. Intermediate steps of the pipeline must be 'transforms', that is, they - must implements fit and transform methods. - The final estimator needs only implements fit. + must implement fit and transform methods. + The final estimator only needs to implement fit. The purpose of the pipeline is to assemble several steps that can be cross-validated together while setting different parameters. @@ -36,12 +44,6 @@ class Pipeline(BaseEstimator): chained, in the order in which they are chained, with the last object an estimator. - Attributes - ---------- - `steps` : list of (name, object) - List of the named object that compose the pipeline, in the \ - order that they are applied on the data. - Examples -------- >>> from sklearn import svm @@ -49,26 +51,22 @@ class Pipeline(BaseEstimator): >>> from sklearn.feature_selection import SelectKBest >>> from sklearn.feature_selection import f_regression >>> from sklearn.pipeline import Pipeline - >>> # generate some data to play with >>> X, y = samples_generator.make_classification( ... n_informative=5, n_redundant=0, random_state=42) - >>> # ANOVA SVM-C >>> anova_filter = SelectKBest(f_regression, k=5) >>> clf = svm.SVC(kernel='linear') >>> anova_svm = Pipeline([('anova', anova_filter), ('svc', clf)]) - >>> # You can set the parameters using the names issued >>> # For instance, fit using a k of 10 in the SelectKBest - >>> # and a parameter 'C' of the svn + >>> # and a parameter 'C' of the svm >>> anova_svm.set_params(anova__k=10, svc__C=.1).fit(X, y) ... # doctest: +ELLIPSIS Pipeline(steps=[...]) - >>> prediction = anova_svm.predict(X) - >>> anova_svm.score(X, y) - 0.75 + >>> anova_svm.score(X, y) # doctest: +ELLIPSIS + 0.77... """ # BaseEstimator interface @@ -77,38 +75,44 @@ def __init__(self, steps): self.named_steps = dict(steps) names, estimators = zip(*steps) if len(self.named_steps) != len(steps): - raise ValueError("Names provided are not unique: %s" % names) + raise ValueError("Names provided are not unique: %s" % (names,)) - self.steps = zip(names, estimators) # shallow copy of steps + # shallow copy of steps + self.steps = tosequence(zip(names, estimators)) transforms = estimators[:-1] estimator = estimators[-1] for t in transforms: - if not (hasattr(t, "fit") or hasattr(t, "fit_transform")) \ - or not hasattr(t, "transform"): - raise TypeError("All intermediate steps a the chain should " - "be transforms and implement fit and transform" - "'%s' (type %s) doesn't)" % (t, type(t))) + if (not (hasattr(t, "fit") or hasattr(t, "fit_transform")) or not + hasattr(t, "transform")): + raise TypeError("All intermediate steps of the chain should " + "be transforms and implement fit and transform" + " '%s' (type %s) doesn't)" % (t, type(t))) if not hasattr(estimator, "fit"): raise TypeError("Last step of chain should implement fit " - "'%s' (type %s) doesn't)" % (estimator, type(estimator))) + "'%s' (type %s) doesn't)" + % (estimator, type(estimator))) def get_params(self, deep=True): if not deep: return super(Pipeline, self).get_params(deep=False) else: out = self.named_steps.copy() - for name, step in self.named_steps.iteritems(): - for key, value in step.get_params(deep=True).iteritems(): + for name, step in six.iteritems(self.named_steps): + for key, value in six.iteritems(step.get_params(deep=True)): out['%s__%s' % (name, key)] = value return out + @property + def _final_estimator(self): + return self.steps[-1][1] + # Estimator interface def _pre_transform(self, X, y=None, **fit_params): fit_params_steps = dict((step, {}) for step, _ in self.steps) - for pname, pval in fit_params.iteritems(): + for pname, pval in six.iteritems(fit_params): step, param = pname.split('__', 1) fit_params_steps[step][param] = pval Xt = X @@ -123,6 +127,15 @@ def _pre_transform(self, X, y=None, **fit_params): def fit(self, X, y=None, **fit_params): """Fit all the transforms one after the other and transform the data, then fit the transformed data using the final estimator. + + Parameters + ---------- + X : iterable + Training data. Must fulfill input requirements of first step of the + pipeline. + y : iterable, default=None + Training targets. Must fulfill label requirements for all steps of + the pipeline. """ Xt, fit_params = self._pre_transform(X, y, **fit_params) self.steps[-1][-1].fit(Xt, y, **fit_params) @@ -131,71 +144,382 @@ def fit(self, X, y=None, **fit_params): def fit_transform(self, X, y=None, **fit_params): """Fit all the transforms one after the other and transform the data, then use fit_transform on transformed data using the final - estimator. Valid only if the final estimator implements - fit_transform.""" + estimator. + + Parameters + ---------- + X : iterable + Training data. Must fulfill input requirements of first step of the + pipeline. + + y : iterable, default=None + Training targets. Must fulfill label requirements for all steps of + the pipeline. + """ Xt, fit_params = self._pre_transform(X, y, **fit_params) - return self.steps[-1][-1].fit_transform(Xt, y, **fit_params) + if hasattr(self.steps[-1][-1], 'fit_transform'): + return self.steps[-1][-1].fit_transform(Xt, y, **fit_params) + else: + return self.steps[-1][-1].fit(Xt, y, **fit_params).transform(Xt) + @if_delegate_has_method(delegate='_final_estimator') def predict(self, X): """Applies transforms to the data, and the predict method of the final estimator. Valid only if the final estimator implements - predict.""" + predict. + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements of first step of + the pipeline. + """ Xt = X for name, transform in self.steps[:-1]: Xt = transform.transform(Xt) return self.steps[-1][-1].predict(Xt) + @if_delegate_has_method(delegate='_final_estimator') def predict_proba(self, X): """Applies transforms to the data, and the predict_proba method of the final estimator. Valid only if the final estimator implements - predict_proba.""" + predict_proba. + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements of first step of + the pipeline. + """ Xt = X for name, transform in self.steps[:-1]: Xt = transform.transform(Xt) return self.steps[-1][-1].predict_proba(Xt) + @if_delegate_has_method(delegate='_final_estimator') def decision_function(self, X): """Applies transforms to the data, and the decision_function method of the final estimator. Valid only if the final estimator implements - decision_function.""" + decision_function. + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements of first step of + the pipeline. + """ Xt = X for name, transform in self.steps[:-1]: Xt = transform.transform(Xt) return self.steps[-1][-1].decision_function(Xt) + @if_delegate_has_method(delegate='_final_estimator') def predict_log_proba(self, X): + """Applies transforms to the data, and the predict_log_proba method of + the final estimator. Valid only if the final estimator implements + predict_log_proba. + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements of first step of + the pipeline. + """ Xt = X for name, transform in self.steps[:-1]: Xt = transform.transform(Xt) return self.steps[-1][-1].predict_log_proba(Xt) + @if_delegate_has_method(delegate='_final_estimator') def transform(self, X): """Applies transforms to the data, and the transform method of the final estimator. Valid only if the final estimator implements - transform.""" + transform. + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements of first step of + the pipeline. + """ Xt = X - for name, transform in self.steps[:-1]: + for name, transform in self.steps: Xt = transform.transform(Xt) - return self.steps[-1][-1].transform(Xt) + return Xt + @if_delegate_has_method(delegate='_final_estimator') def inverse_transform(self, X): + """Applies inverse transform to the data. + Starts with the last step of the pipeline and applies ``inverse_transform`` in + inverse order of the pipeline steps. + Valid only if all steps of the pipeline implement inverse_transform. + + Parameters + ---------- + X : iterable + Data to inverse transform. Must fulfill output requirements of the + last step of the pipeline. + """ if X.ndim == 1: X = X[None, :] Xt = X - for name, step in self.steps[:-1][::-1]: + for name, step in self.steps[::-1]: Xt = step.inverse_transform(Xt) return Xt + @if_delegate_has_method(delegate='_final_estimator') def score(self, X, y=None): """Applies transforms to the data, and the score method of the final estimator. Valid only if the final estimator implements - score.""" + score. + + Parameters + ---------- + X : iterable + Data to score. Must fulfill input requirements of first step of the + pipeline. + + y : iterable, default=None + Targets used for scoring. Must fulfill label requirements for all steps of + the pipeline. + """ Xt = X for name, transform in self.steps[:-1]: Xt = transform.transform(Xt) return self.steps[-1][-1].score(Xt, y) + @property + def classes_(self): + return self.steps[-1][-1].classes_ + @property def _pairwise(self): # check if first estimator expects pairwise input return getattr(self.steps[0][1], '_pairwise', False) + + +def _name_estimators(estimators): + """Generate names for estimators.""" + + names = [type(estimator).__name__.lower() for estimator in estimators] + namecount = defaultdict(int) + for est, name in zip(estimators, names): + namecount[name] += 1 + + for k, v in list(six.iteritems(namecount)): + if v == 1: + del namecount[k] + + for i in reversed(range(len(estimators))): + name = names[i] + if name in namecount: + names[i] += "-%d" % namecount[name] + namecount[name] -= 1 + + return list(zip(names, estimators)) + + +def make_pipeline(*steps): + """Construct a Pipeline from the given estimators. + + This is a shorthand for the Pipeline constructor; it does not require, and + does not permit, naming the estimators. Instead, they will be given names + automatically based on their types. + + Examples + -------- + >>> from sklearn.naive_bayes import GaussianNB + >>> from sklearn.preprocessing import StandardScaler + >>> make_pipeline(StandardScaler(), GaussianNB()) # doctest: +NORMALIZE_WHITESPACE + Pipeline(steps=[('standardscaler', + StandardScaler(copy=True, with_mean=True, with_std=True)), + ('gaussiannb', GaussianNB())]) + + Returns + ------- + p : Pipeline + """ + return Pipeline(_name_estimators(steps)) + + +def _fit_one_transformer(transformer, X, y): + return transformer.fit(X, y) + + +def _transform_one(transformer, name, X, transformer_weights): + if transformer_weights is not None and name in transformer_weights: + # if we have a weight for this transformer, muliply output + return transformer.transform(X) * transformer_weights[name] + return transformer.transform(X) + + +def _fit_transform_one(transformer, name, X, y, transformer_weights, + **fit_params): + if transformer_weights is not None and name in transformer_weights: + # if we have a weight for this transformer, muliply output + if hasattr(transformer, 'fit_transform'): + X_transformed = transformer.fit_transform(X, y, **fit_params) + return X_transformed * transformer_weights[name], transformer + else: + X_transformed = transformer.fit(X, y, **fit_params).transform(X) + return X_transformed * transformer_weights[name], transformer + if hasattr(transformer, 'fit_transform'): + X_transformed = transformer.fit_transform(X, y, **fit_params) + return X_transformed, transformer + else: + X_transformed = transformer.fit(X, y, **fit_params).transform(X) + return X_transformed, transformer + + +class FeatureUnion(BaseEstimator, TransformerMixin): + """Concatenates results of multiple transformer objects. + + This estimator applies a list of transformer objects in parallel to the + input data, then concatenates the results. This is useful to combine + several feature extraction mechanisms into a single transformer. + + Parameters + ---------- + transformer_list: list of (string, transformer) tuples + List of transformer objects to be applied to the data. The first + half of each tuple is the name of the transformer. + + n_jobs: int, optional + Number of jobs to run in parallel (default 1). + + transformer_weights: dict, optional + Multiplicative weights for features per transformer. + Keys are transformer names, values the weights. + + """ + def __init__(self, transformer_list, n_jobs=1, transformer_weights=None): + self.transformer_list = transformer_list + self.n_jobs = n_jobs + self.transformer_weights = transformer_weights + + def get_feature_names(self): + """Get feature names from all transformers. + + Returns + ------- + feature_names : list of strings + Names of the features produced by transform. + """ + feature_names = [] + for name, trans in self.transformer_list: + if not hasattr(trans, 'get_feature_names'): + raise AttributeError("Transformer %s does not provide" + " get_feature_names." % str(name)) + feature_names.extend([name + "__" + f for f in + trans.get_feature_names()]) + return feature_names + + def fit(self, X, y=None): + """Fit all transformers using X. + + Parameters + ---------- + X : array-like or sparse matrix, shape (n_samples, n_features) + Input data, used to fit transformers. + """ + transformers = Parallel(n_jobs=self.n_jobs)( + delayed(_fit_one_transformer)(trans, X, y) + for name, trans in self.transformer_list) + self._update_transformer_list(transformers) + return self + + def fit_transform(self, X, y=None, **fit_params): + """Fit all transformers using X, transform the data and concatenate + results. + + Parameters + ---------- + X : array-like or sparse matrix, shape (n_samples, n_features) + Input data to be transformed. + + Returns + ------- + X_t : array-like or sparse matrix, shape (n_samples, sum_n_components) + hstack of results of transformers. sum_n_components is the + sum of n_components (output dimension) over transformers. + """ + result = Parallel(n_jobs=self.n_jobs)( + delayed(_fit_transform_one)(trans, name, X, y, + self.transformer_weights, **fit_params) + for name, trans in self.transformer_list) + + Xs, transformers = zip(*result) + self._update_transformer_list(transformers) + if any(sparse.issparse(f) for f in Xs): + Xs = sparse.hstack(Xs).tocsr() + else: + Xs = np.hstack(Xs) + return Xs + + def transform(self, X): + """Transform X separately by each transformer, concatenate results. + + Parameters + ---------- + X : array-like or sparse matrix, shape (n_samples, n_features) + Input data to be transformed. + + Returns + ------- + X_t : array-like or sparse matrix, shape (n_samples, sum_n_components) + hstack of results of transformers. sum_n_components is the + sum of n_components (output dimension) over transformers. + """ + Xs = Parallel(n_jobs=self.n_jobs)( + delayed(_transform_one)(trans, name, X, self.transformer_weights) + for name, trans in self.transformer_list) + if any(sparse.issparse(f) for f in Xs): + Xs = sparse.hstack(Xs).tocsr() + else: + Xs = np.hstack(Xs) + return Xs + + def get_params(self, deep=True): + if not deep: + return super(FeatureUnion, self).get_params(deep=False) + else: + out = dict(self.transformer_list) + for name, trans in self.transformer_list: + for key, value in iteritems(trans.get_params(deep=True)): + out['%s__%s' % (name, key)] = value + return out + + def _update_transformer_list(self, transformers): + self.transformer_list[:] = [ + (name, new) + for ((name, old), new) in zip(self.transformer_list, transformers) + ] + + +# XXX it would be nice to have a keyword-only n_jobs argument to this function, +# but that's not allowed in Python 2.x. +def make_union(*transformers): + """Construct a FeatureUnion from the given transformers. + + This is a shorthand for the FeatureUnion constructor; it does not require, + and does not permit, naming the transformers. Instead, they will be given + names automatically based on their types. It also does not allow weighting. + + Examples + -------- + >>> from sklearn.decomposition import PCA, TruncatedSVD + >>> make_union(PCA(), TruncatedSVD()) # doctest: +NORMALIZE_WHITESPACE + FeatureUnion(n_jobs=1, + transformer_list=[('pca', PCA(copy=True, n_components=None, + whiten=False)), + ('truncatedsvd', + TruncatedSVD(algorithm='randomized', + n_components=2, n_iter=5, + random_state=None, tol=0.0))], + transformer_weights=None) + + Returns + ------- + f : FeatureUnion + """ + return FeatureUnion(_name_estimators(transformers)) diff --git a/sklearn/preprocessing.py b/sklearn/preprocessing.py deleted file mode 100644 index 087c25f75b264..0000000000000 --- a/sklearn/preprocessing.py +++ /dev/null @@ -1,974 +0,0 @@ -# Authors: Alexandre Gramfort -# Mathieu Blondel -# Olivier Grisel -# License: BSD -from collections import Sequence -import warnings - -import numpy as np -import scipy.sparse as sp - -from .utils import check_arrays, array2d -from .utils import warn_if_not_float -from .utils.fixes import unique -from .base import BaseEstimator, TransformerMixin - -from .utils.sparsefuncs import inplace_csr_row_normalize_l1 -from .utils.sparsefuncs import inplace_csr_row_normalize_l2 -from .utils.sparsefuncs import inplace_csr_column_scale -from .utils.sparsefuncs import mean_variance_axis0 - -__all__ = ['Binarizer', - 'KernelCenterer', - 'LabelBinarizer', - 'LabelEncoder', - 'Normalizer', - 'StandardScaler', - 'binarize', - 'normalize', - 'scale'] - - -def _mean_and_std(X, axis=0, with_mean=True, with_std=True): - """Compute mean and std dev for centering, scaling - - Zero valued std components are reset to 1.0 to avoid NaNs when scaling. - """ - X = np.asarray(X) - Xr = np.rollaxis(X, axis) - - if with_mean: - mean_ = Xr.mean(axis=0) - else: - mean_ = None - - if with_std: - std_ = Xr.std(axis=0) - if isinstance(std_, np.ndarray): - std_[std_ == 0.0] = 1.0 - elif std_ == 0.: - std_ = 1. - else: - std_ = None - - return mean_, std_ - - -def scale(X, axis=0, with_mean=True, with_std=True, copy=True): - """Standardize a dataset along any axis - - Center to the mean and component wise scale to unit variance. - - Parameters - ---------- - X : array-like or CSR matrix. - The data to center and scale. - - axis : int (0 by default) - axis used to compute the means and standard deviations along. If 0, - independently standardize each feature, otherwise (if 1) standardize - each sample. - - with_mean : boolean, True by default - If True, center the data before scaling. - - with_std : boolean, True by default - If True, scale the data to unit variance (or equivalently, - unit standard deviation). - - copy : boolean, optional, default is True - set to False to perform inplace row normalization and avoid a - copy (if the input is already a numpy array or a scipy.sparse - CSR matrix and if axis is 1). - - Notes - ----- - This implementation will refuse to center scipy.sparse matrices - since it would make them non-sparse and would potentially crash the - program with memory exhaustion problems. - - Instead the caller is expected to either set explicitly - `with_mean=False` (in that case, only variance scaling will be - performed on the features of the CSR matrix) or to call `X.toarray()` - if he/she expects the materialized dense array to fit in memory. - - To avoid memory copy the caller should pass a CSR matrix. - - See also - -------- - :class:`sklearn.preprocessing.StandardScaler` to perform centering and - scaling using the ``Transformer`` API (e.g. as part of a preprocessing - :class:`sklearn.pipeline.Pipeline`) - """ - if sp.issparse(X): - if with_mean: - raise ValueError( - "Cannot center sparse matrices: pass `with_mean=False` instead" - " See docstring for motivation and alternatives.") - if axis != 0: - raise ValueError("Can only scale sparse matrix on axis=0, " - " got axis=%d" % axis) - warn_if_not_float(X, estimator='The scale function') - if not sp.isspmatrix_csr(X): - X = X.tocsr() - copy = False - if copy: - X = X.copy() - _, var = mean_variance_axis0(X) - var[var == 0.0] = 1.0 - inplace_csr_column_scale(X, 1 / np.sqrt(var)) - else: - X = np.asarray(X) - warn_if_not_float(X, estimator='The scale function') - mean_, std_ = _mean_and_std( - X, axis, with_mean=with_mean, with_std=with_std) - if copy: - X = X.copy() - # Xr is a view on the original array that enables easy use of - # broadcasting on the axis in which we are interested in - Xr = np.rollaxis(X, axis) - if with_mean: - Xr -= mean_ - if with_std: - Xr /= std_ - return X - - -class MinMaxScaler(BaseEstimator, TransformerMixin): - """Standardizes features by scaling each feature to a given range. - - This estimator scales and translates each feature individually such - that it is in the given range on the training set, i.e. between - zero and one. - - The standardization is given by:: - X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) - X_scaled = X_std / (max - min) + min - where min, max = feature_range. - - This standardization is often used as an alternative to zero mean, - unit variance scaling. - - Parameters - ---------- - feature_range: tuple (min, max), default=(0, 1) - Desired range of transformed data. - - copy : boolean, optional, default is True - Set to False to perform inplace row normalization and avoid a - copy (if the input is already a numpy array). - - Attributes - ---------- - min_ : ndarray, shape (n_features,) - Per feature adjustment for minimum. - - scale_ : ndarray, shape (n_features,) - Per feature relative scaling of the data. - """ - - def __init__(self, feature_range=(0, 1), copy=True): - self.feature_range = feature_range - self.copy = copy - - def fit(self, X, y=None): - """Compute the minimum and maximum to be used for later scaling. - - Parameters - ---------- - X : array-like, shape [n_samples, n_features] - The data used to compute the per-feature minimum and maximum - used for later scaling along the features axis. - """ - X = check_arrays(X, sparse_format="dense", copy=self.copy)[0] - feature_range = self.feature_range - if feature_range[0] >= feature_range[1]: - raise ValueError("Minimum of desired feature range must be smaller" - " than maximum. Got %s." % str(feature_range)) - min_ = np.min(X, axis=0) - scale_ = np.max(X, axis=0) - min_ - self.scale_ = (feature_range[1] - feature_range[0]) / scale_ - self.min_ = feature_range[0] - min_ / scale_ - return self - - def transform(self, X): - """Scaling features of X according to feature_range. - - Parameters - ---------- - X : array-like with shape [n_samples, n_features] - Input data that will be transformed. - """ - X = check_arrays(X, sparse_format="dense", copy=self.copy)[0] - X *= self.scale_ - X += self.min_ - return X - - -class StandardScaler(BaseEstimator, TransformerMixin): - """Standardize features by removing the mean and scaling to unit variance - - Centering and scaling happen indepently on each feature by computing - the relevant statistics on the samples in the training set. Mean and - standard deviation are then stored to be used on later data using the - `transform` method. - - Standardization of a dataset is a common requirement for many - machine learning estimators: they might behave badly if the - individual feature do not more or less look like standard normally - distributed data (e.g. Gaussian with 0 mean and unit variance). - - For instance many elements used in the objective function of - a learning algorithm (such as the RBF kernel of Support Vector - Machines or the L1 and L2 regularizers of linear models) assume that - all features are centered around 0 and have variance in the same - order. If a feature has a variance that is orders of magnitude larger - that others, it might dominate the objective function and make the - estimator unable to learn from other features correctly as expected. - - Parameters - ---------- - with_mean : boolean, True by default - If True, center the data before scaling. - - with_std : boolean, True by default - If True, scale the data to unit variance (or equivalently, - unit standard deviation). - - copy : boolean, optional, default is True - Set to False to perform inplace row normalization and avoid a - copy (if the input is already a numpy array or a scipy.sparse - CSR matrix and if axis is 1). - - Attributes - ---------- - `mean_` : array of floats with shape [n_features] - The mean value for each feature in the training set. - - `std_` : array of floats with shape [n_features] - The standard deviation for each feature in the training set. - - See also - -------- - :func:`sklearn.preprocessing.scale` to perform centering and - scaling without using the ``Transformer`` object oriented API - - :class:`sklearn.decomposition.RandomizedPCA` with `whiten=True` - to further remove the linear correlation across features. - """ - - def __init__(self, copy=True, with_mean=True, with_std=True): - self.with_mean = with_mean - self.with_std = with_std - self.copy = copy - - def fit(self, X, y=None): - """Compute the mean and std to be used for later scaling. - - Parameters - ---------- - X : array-like or CSR matrix with shape [n_samples, n_features] - The data used to compute the mean and standard deviation - used for later scaling along the features axis. - """ - if sp.issparse(X): - if self.with_mean: - raise ValueError( - "Cannot center sparse matrices: pass `with_mean=False` " - "instead See docstring for motivation and alternatives.") - warn_if_not_float(X, estimator=self) - copy = self.copy - if not sp.isspmatrix_csr(X): - X = X.tocsr() - copy = False - if copy: - X = X.copy() - self.mean_ = None - _, var = mean_variance_axis0(X) - self.std_ = np.sqrt(var) - self.std_[var == 0.0] = 1.0 - return self - else: - X = np.asarray(X) - warn_if_not_float(X, estimator=self) - self.mean_, self.std_ = _mean_and_std( - X, axis=0, with_mean=self.with_mean, with_std=self.with_std) - return self - - def transform(self, X, y=None, copy=None): - """Perform standardization by centering and scaling - - Parameters - ---------- - X : array-like with shape [n_samples, n_features] - The data used to scale along the features axis. - """ - copy = copy if copy is not None else self.copy - if sp.issparse(X): - if self.with_mean: - raise ValueError( - "Cannot center sparse matrices: pass `with_mean=False` " - "instead See docstring for motivation and alternatives.") - warn_if_not_float(X, estimator=self) - if not sp.isspmatrix_csr(X): - X = X.tocsr() - copy = False - if copy: - X = X.copy() - inplace_csr_column_scale(X, 1 / self.std_) - else: - X = np.asarray(X) - warn_if_not_float(X, estimator=self) - if copy: - X = X.copy() - if self.with_mean: - X -= self.mean_ - if self.with_std: - X /= self.std_ - return X - - def inverse_transform(self, X, copy=None): - """Scale back the data to the original representation - - Parameters - ---------- - X : array-like with shape [n_samples, n_features] - The data used to scale along the features axis. - """ - copy = copy if copy is not None else self.copy - if sp.issparse(X): - if self.with_mean: - raise ValueError( - "Cannot uncenter sparse matrices: pass `with_mean=False` " - "instead See docstring for motivation and alternatives.") - if not sp.isspmatrix_csr(X): - X = X.tocsr() - copy = False - if copy: - X = X.copy() - inplace_csr_column_scale(X, self.std_) - else: - X = np.asarray(X) - if copy: - X = X.copy() - if self.with_std: - X *= self.std_ - if self.with_mean: - X += self.mean_ - return X - - -class Scaler(StandardScaler): - def __init__(self, copy=True, with_mean=True, with_std=True): - warnings.warn("Scaler was renamed to StandardScaler. The old name " - " will be removed in 0.15.", DeprecationWarning) - super(Scaler, self).__init__(copy, with_mean, with_std) - - -def normalize(X, norm='l2', axis=1, copy=True): - """Normalize a dataset along any axis - - Parameters - ---------- - X : array or scipy.sparse matrix with shape [n_samples, n_features] - The data to normalize, element by element. - scipy.sparse matrices should be in CSR format to avoid an - un-necessary copy. - - norm : 'l1' or 'l2', optional ('l2' by default) - The norm to use to normalize each non zero sample (or each non-zero - feature if axis is 0). - - axis : 0 or 1, optional (1 by default) - axis used to normalize the data along. If 1, independently normalize - each sample, otherwise (if 0) normalize each feature. - - copy : boolean, optional, default is True - set to False to perform inplace row normalization and avoid a - copy (if the input is already a numpy array or a scipy.sparse - CSR matrix and if axis is 1). - - See also - -------- - :class:`sklearn.preprocessing.Normalizer` to perform normalization - using the ``Transformer`` API (e.g. as part of a preprocessing - :class:`sklearn.pipeline.Pipeline`) - """ - if norm not in ('l1', 'l2'): - raise ValueError("'%s' is not a supported norm" % norm) - - if axis == 0: - sparse_format = 'csc' - elif axis == 1: - sparse_format = 'csr' - else: - raise ValueError("'%d' is not a supported axis" % axis) - - X = check_arrays(X, sparse_format=sparse_format, copy=copy)[0] - warn_if_not_float(X, 'The normalize function') - if axis == 0: - X = X.T - - if sp.issparse(X): - if norm == 'l1': - inplace_csr_row_normalize_l1(X) - elif norm == 'l2': - inplace_csr_row_normalize_l2(X) - else: - if norm == 'l1': - norms = np.abs(X).sum(axis=1)[:, np.newaxis] - norms[norms == 0.0] = 1.0 - elif norm == 'l2': - norms = np.sqrt(np.sum(X ** 2, axis=1))[:, np.newaxis] - norms[norms == 0.0] = 1.0 - X /= norms - - if axis == 0: - X = X.T - - return X - - -class Normalizer(BaseEstimator, TransformerMixin): - """Normalize samples individually to unit norm - - Each sample (i.e. each row of the data matrix) with at least one - non zero component is rescaled independently of other samples so - that its norm (l1 or l2) equals one. - - This transformer is able to work both with dense numpy arrays and - scipy.sparse matrix (use CSR format if you want to avoid the burden of - a copy / conversion). - - Scaling inputs to unit norms is a common operation for text - classification or clustering for instance. For instance the dot - product of two l2-normalized TF-IDF vectors is the cosine similarity - of the vectors and is the base similarity metric for the Vector - Space Model commonly used by the Information Retrieval community. - - Parameters - ---------- - norm : 'l1' or 'l2', optional ('l2' by default) - The norm to use to normalize each non zero sample. - - copy : boolean, optional, default is True - set to False to perform inplace row normalization and avoid a - copy (if the input is already a numpy array or a scipy.sparse - CSR matrix). - - Notes - ----- - This estimator is stateless (besides constructor parameters), the - fit method does nothing but is useful when used in a pipeline. - - See also - -------- - :func:`sklearn.preprocessing.normalize` equivalent function - without the object oriented API - """ - - def __init__(self, norm='l2', copy=True): - self.norm = norm - self.copy = copy - - def fit(self, X, y=None): - """Do nothing and return the estimator unchanged - - This method is just there to implement the usual API and hence - work in pipelines. - """ - return self - - def transform(self, X, y=None, copy=None): - """Scale each non zero row of X to unit norm - - Parameters - ---------- - X : array or scipy.sparse matrix with shape [n_samples, n_features] - The data to normalize, row by row. scipy.sparse matrices should be - in CSR format to avoid an un-necessary copy. - """ - copy = copy if copy is not None else self.copy - return normalize(X, norm=self.norm, axis=1, copy=copy) - - -def binarize(X, threshold=0.0, copy=True): - """Boolean thresholding of array-like or scipy.sparse matrix - - Parameters - ---------- - X : array or scipy.sparse matrix with shape [n_samples, n_features] - The data to binarize, element by element. - scipy.sparse matrices should be in CSR format to avoid an - un-necessary copy. - - threshold : float, optional (0.0 by default) - The lower bound that triggers feature values to be replaced by 1.0. - - copy : boolean, optional, default is True - set to False to perform inplace binarization and avoid a copy - (if the input is already a numpy array or a scipy.sparse CSR - matrix and if axis is 1). - - See also - -------- - :class:`sklearn.preprocessing.Binarizer` to perform binarization - using the ``Transformer`` API (e.g. as part of a preprocessing - :class:`sklearn.pipeline.Pipeline`) - """ - X = check_arrays(X, sparse_format='csr', copy=copy)[0] - if sp.issparse(X): - cond = X.data > threshold - not_cond = np.logical_not(cond) - X.data[cond] = 1 - # FIXME: if enough values became 0, it may be worth changing - # the sparsity structure - X.data[not_cond] = 0 - else: - cond = X > threshold - not_cond = np.logical_not(cond) - X[cond] = 1 - X[not_cond] = 0 - return X - - -class Binarizer(BaseEstimator, TransformerMixin): - """Binarize data (set feature values to 0 or 1) according to a threshold - - The default threshold is 0.0 so that any non-zero values are set to 1.0 - and zeros are left untouched. - - Binarization is a common operation on text count data where the - analyst can decide to only consider the presence or absence of a - feature rather than a quantified number of occurences for instance. - - It can also be used as a pre-processing step for estimators that - consider boolean random variables (e.g. modeled using the Bernoulli - distribution in a Bayesian setting). - - Parameters - ---------- - threshold : float, optional (0.0 by default) - The lower bound that triggers feature values to be replaced by 1.0. - - copy : boolean, optional, default is True - set to False to perform inplace binarization and avoid a copy (if - the input is already a numpy array or a scipy.sparse CSR matrix). - - Notes - ----- - If the input is a sparse matrix, only the non-zero values are subject - to update by the Binarizer class. - - This estimator is stateless (besides constructor parameters), the - fit method does nothing but is useful when used in a pipeline. - """ - - def __init__(self, threshold=0.0, copy=True): - self.threshold = threshold - self.copy = copy - - def fit(self, X, y=None): - """Do nothing and return the estimator unchanged - - This method is just there to implement the usual API and hence - work in pipelines. - """ - return self - - def transform(self, X, y=None, copy=None): - """Binarize each element of X - - Parameters - ---------- - X : array or scipy.sparse matrix with shape [n_samples, n_features] - The data to binarize, element by element. - scipy.sparse matrices should be in CSR format to avoid an - un-necessary copy. - """ - copy = copy if copy is not None else self.copy - return binarize(X, threshold=self.threshold, copy=copy) - - -def _is_label_indicator_matrix(y): - return hasattr(y, "shape") and len(y.shape) == 2 - - -def _is_multilabel(y): - # the explicit check for ndarray is for forward compatibility; future - # versions of Numpy might want to register ndarray as a Sequence - return not isinstance(y[0], np.ndarray) and isinstance(y[0], Sequence) \ - and not isinstance(y[0], basestring) \ - or _is_label_indicator_matrix(y) - - -class LabelEncoder(BaseEstimator, TransformerMixin): - """Encode labels with value between 0 and n_classes-1. - - Attributes - ---------- - `classes_`: array of shape [n_class] - Holds the label for each class. - - Examples - -------- - `LabelEncoder` can be used to normalize labels. - - >>> from sklearn import preprocessing - >>> le = preprocessing.LabelEncoder() - >>> le.fit([1, 2, 2, 6]) - LabelEncoder() - >>> le.classes_ - array([1, 2, 6]) - >>> le.transform([1, 1, 2, 6]) - array([0, 0, 1, 2]) - >>> le.inverse_transform([0, 0, 1, 2]) - array([1, 1, 2, 6]) - - It can also be used to transform non-numerical labels (as long as they are - hashable and comparable) to numerical labels. - - >>> le = preprocessing.LabelEncoder() - >>> le.fit(["paris", "paris", "tokyo", "amsterdam"]) - LabelEncoder() - >>> list(le.classes_) - ['amsterdam', 'paris', 'tokyo'] - >>> le.transform(["tokyo", "tokyo", "paris"]) - array([2, 2, 1]) - >>> list(le.inverse_transform([2, 2, 1])) - ['tokyo', 'tokyo', 'paris'] - - """ - - def _check_fitted(self): - if not hasattr(self, "classes_"): - raise ValueError("LabelNormalizer was not fitted yet.") - - def fit(self, y): - """Fit label encoder - - Parameters - ---------- - y : array-like of shape [n_samples] - Target values. - - Returns - ------- - self : returns an instance of self. - """ - self.classes_ = np.unique(y) - return self - - def fit_transform(self, y): - """Fit label encoder and return encoded labels - - Parameters - ---------- - y : array-like of shape [n_samples] - Target values. - - Returns - ------- - y : array-like of shape [n_samples] - """ - self.classes_, y = unique(y, return_inverse=True) - return y - - def transform(self, y): - """Transform labels to normalized encoding. - - Parameters - ---------- - y : array-like of shape [n_samples] - Target values. - - Returns - ------- - y : array-like of shape [n_samples] - """ - self._check_fitted() - - classes = np.unique(y) - if len(np.intersect1d(classes, self.classes_)) < len(classes): - diff = np.setdiff1d(classes, self.classes_) - raise ValueError("y contains new labels: %s" % str(diff)) - - return np.searchsorted(self.classes_, y) - - def inverse_transform(self, y): - """Transform labels back to original encoding. - - Parameters - ---------- - y : numpy array of shape [n_samples] - Target values. - - Returns - ------- - y : numpy array of shape [n_samples] - """ - self._check_fitted() - - y = np.asarray(y) - return self.classes_[y] - - -class LabelBinarizer(BaseEstimator, TransformerMixin): - """Binarize labels in a one-vs-all fashion - - Several regression and binary classification algorithms are - available in the scikit. A simple way to extend these algorithms - to the multi-class classification case is to use the so-called - one-vs-all scheme. - - At learning time, this simply consists in learning one regressor - or binary classifier per class. In doing so, one needs to convert - multi-class labels to binary labels (belong or does not belong - to the class). LabelBinarizer makes this process easy with the - transform method. - - At prediction time, one assigns the class for which the corresponding - model gave the greatest confidence. LabelBinarizer makes this easy - with the inverse_transform method. - - Parameters - ---------- - - neg_label: int (default: 0) - Value with which negative labels must be encoded. - - pos_label: int (default: 1) - Value with which positive labels must be encoded. - - Attributes - ---------- - `classes_`: array of shape [n_class] - Holds the label for each class. - - Examples - -------- - >>> from sklearn import preprocessing - >>> lb = preprocessing.LabelBinarizer() - >>> lb.fit([1, 2, 6, 4, 2]) - LabelBinarizer(neg_label=0, pos_label=1) - >>> lb.classes_ - array([1, 2, 4, 6]) - >>> lb.transform([1, 6]) - array([[1, 0, 0, 0], - [0, 0, 0, 1]]) - - >>> lb.fit_transform([(1, 2), (3,)]) - array([[1, 1, 0], - [0, 0, 1]]) - >>> lb.classes_ - array([1, 2, 3]) - """ - - def __init__(self, neg_label=0, pos_label=1): - if neg_label >= pos_label: - raise ValueError("neg_label must be strictly less than pos_label.") - - self.neg_label = neg_label - self.pos_label = pos_label - - def _check_fitted(self): - if not hasattr(self, "classes_"): - raise ValueError("LabelBinarizer was not fitted yet.") - - def fit(self, y): - """Fit label binarizer - - Parameters - ---------- - y : numpy array of shape [n_samples] or sequence of sequences - Target values. In the multilabel case the nested sequences can - have variable lengths. - - Returns - ------- - self : returns an instance of self. - """ - self.multilabel = _is_multilabel(y) - if self.multilabel: - self.indicator_matrix_ = _is_label_indicator_matrix(y) - if self.indicator_matrix_: - self.classes_ = np.arange(y.shape[1]) - else: - self.classes_ = np.array(sorted(set.union(*map(set, y)))) - else: - self.classes_ = np.unique(y) - return self - - def transform(self, y): - """Transform multi-class labels to binary labels - - The output of transform is sometimes referred to by some authors as the - 1-of-K coding scheme. - - Parameters - ---------- - y : numpy array of shape [n_samples] or sequence of sequences - Target values. In the multilabel case the nested sequences can - have variable lengths. - - Returns - ------- - Y : numpy array of shape [n_samples, n_classes] - """ - self._check_fitted() - - if self.multilabel or len(self.classes_) > 2: - if _is_label_indicator_matrix(y): - # nothing to do as y is already a label indicator matrix - return y - - Y = np.zeros((len(y), len(self.classes_)), dtype=np.int) - else: - Y = np.zeros((len(y), 1), dtype=np.int) - - Y += self.neg_label - - y_is_multilabel = _is_multilabel(y) - - if y_is_multilabel and not self.multilabel: - raise ValueError("The object was not " + - "fitted with multilabel input!") - - elif self.multilabel: - if not _is_multilabel(y): - raise ValueError("y should be a list of label lists/tuples," - "got %r" % (y,)) - - # inverse map: label => column index - imap = dict((v, k) for k, v in enumerate(self.classes_)) - - for i, label_tuple in enumerate(y): - for label in label_tuple: - Y[i, imap[label]] = self.pos_label - - return Y - - else: - y = np.asarray(y) - - if len(self.classes_) == 2: - Y[y == self.classes_[1], 0] = self.pos_label - return Y - - elif len(self.classes_) >= 2: - for i, k in enumerate(self.classes_): - Y[y == k, i] = self.pos_label - return Y - - else: - # Only one class, returns a matrix with all negative labels. - return Y - - def inverse_transform(self, Y, threshold=None): - """Transform binary labels back to multi-class labels - - Parameters - ---------- - Y : numpy array of shape [n_samples, n_classes] - Target values. - - threshold : float or None - Threshold used in the binary and multi-label cases. - - Use 0 when: - - Y contains the output of decision_function (classifier) - Use 0.5 when: - - Y contains the output of predict_proba - - If None, the threshold is assumed to be half way between - neg_label and pos_label. - - Returns - ------- - y : numpy array of shape [n_samples] or sequence of sequences - Target values. In the multilabel case the nested sequences can - have variable lengths. - - Notes - ----- - In the case when the binary labels are fractional - (probabilistic), inverse_transform chooses the class with the - greatest value. Typically, this allows to use the output of a - linear model's decision_function method directly as the input - of inverse_transform. - """ - self._check_fitted() - - if threshold is None: - half = (self.pos_label - self.neg_label) / 2.0 - threshold = self.neg_label + half - - if self.multilabel: - Y = np.array(Y > threshold, dtype=int) - # Return the predictions in the same format as in fit - if self.indicator_matrix_: - # Label indicator matrix format - return Y - else: - # Lists of tuples format - return [tuple(self.classes_[np.flatnonzero(Y[i])]) - for i in range(Y.shape[0])] - - if len(Y.shape) == 1 or Y.shape[1] == 1: - y = np.array(Y.ravel() > threshold, dtype=int) - - else: - y = Y.argmax(axis=1) - - return self.classes_[y] - - -class KernelCenterer(BaseEstimator, TransformerMixin): - """Center a kernel matrix - - This is equivalent to centering phi(X) with - sklearn.preprocessing.StandardScaler(with_std=False). - """ - - def fit(self, K, y=None): - """Fit KernelCenterer - - Parameters - ---------- - K : numpy array of shape [n_samples, n_samples] - Kernel matrix. - - Returns - ------- - self : returns an instance of self. - """ - K = array2d(K) - n_samples = K.shape[0] - self.K_fit_rows_ = np.sum(K, axis=0) / n_samples - self.K_fit_all_ = self.K_fit_rows_.sum() / n_samples - return self - - def transform(self, K, y=None, copy=True): - """Center kernel - - Parameters - ---------- - K : numpy array of shape [n_samples1, n_samples2] - Kernel matrix. - - Returns - ------- - K_new : numpy array of shape [n_samples1, n_samples2] - """ - K = array2d(K) - if copy: - K = K.copy() - - K_pred_cols = (np.sum(K, axis=1) / - self.K_fit_rows_.shape[0])[:, np.newaxis] - - K -= self.K_fit_rows_ - K -= K_pred_cols - K += self.K_fit_all_ - - return K diff --git a/sklearn/preprocessing/__init__.py b/sklearn/preprocessing/__init__.py new file mode 100644 index 0000000000000..c8c71570dfee1 --- /dev/null +++ b/sklearn/preprocessing/__init__.py @@ -0,0 +1,43 @@ +""" +The :mod:`sklearn.preprocessing` module includes scaling, centering, +normalization, binarization and imputation methods. +""" + +from .data import Binarizer +from .data import KernelCenterer +from .data import MinMaxScaler +from .data import Normalizer +from .data import StandardScaler +from .data import add_dummy_feature +from .data import binarize +from .data import normalize +from .data import scale +from .data import OneHotEncoder + +from .data import PolynomialFeatures + +from .label import label_binarize +from .label import LabelBinarizer +from .label import LabelEncoder +from .label import MultiLabelBinarizer + +from .imputation import Imputer + +__all__ = [ + 'Binarizer', + 'Imputer', + 'KernelCenterer', + 'LabelBinarizer', + 'LabelEncoder', + 'MultiLabelBinarizer', + 'MinMaxScaler', + 'Normalizer', + 'OneHotEncoder', + 'StandardScaler', + 'add_dummy_feature', + 'PolynomialFeatures', + 'binarize', + 'normalize', + 'scale', + 'label_binarize', +] diff --git a/sklearn/preprocessing/_weights.py b/sklearn/preprocessing/_weights.py new file mode 100644 index 0000000000000..f8daccddd00a8 --- /dev/null +++ b/sklearn/preprocessing/_weights.py @@ -0,0 +1,25 @@ +import numpy as np +from ..utils.fixes import bincount + +def _balance_weights(y): + """Compute sample weights such that the class distribution of y becomes + balanced. + + Parameters + ---------- + y : array-like + Labels for the samples. + + Returns + ------- + weights : array-like + The sample weights. + """ + y = np.asarray(y) + y = np.searchsorted(np.unique(y), y) + bins = bincount(y) + + weights = 1. / bins.take(y) + weights *= bins.min() + + return weights diff --git a/sklearn/preprocessing/data.py b/sklearn/preprocessing/data.py new file mode 100644 index 0000000000000..e0dc810627d39 --- /dev/null +++ b/sklearn/preprocessing/data.py @@ -0,0 +1,1122 @@ +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Olivier Grisel +# Andreas Mueller +# License: BSD 3 clause + +from itertools import chain, combinations +import numbers + +import numpy as np +from scipy import sparse + +from ..base import BaseEstimator, TransformerMixin +from ..externals import six +from ..utils import check_array +from ..utils import warn_if_not_float +from ..utils.extmath import row_norms +from ..utils.fixes import (combinations_with_replacement as combinations_w_r, + bincount) +from ..utils.sparsefuncs_fast import (inplace_csr_row_normalize_l1, + inplace_csr_row_normalize_l2) +from ..utils.sparsefuncs import (inplace_column_scale, mean_variance_axis) +from ..utils.validation import check_is_fitted + +zip = six.moves.zip +map = six.moves.map +range = six.moves.range + +__all__ = [ + 'Binarizer', + 'KernelCenterer', + 'MinMaxScaler', + 'Normalizer', + 'OneHotEncoder', + 'StandardScaler', + 'add_dummy_feature', + 'binarize', + 'normalize', + 'scale', +] + + +def _mean_and_std(X, axis=0, with_mean=True, with_std=True): + """Compute mean and std deviation for centering, scaling. + + Zero valued std components are reset to 1.0 to avoid NaNs when scaling. + """ + X = np.asarray(X) + Xr = np.rollaxis(X, axis) + + if with_mean: + mean_ = Xr.mean(axis=0) + else: + mean_ = None + + if with_std: + std_ = Xr.std(axis=0) + if isinstance(std_, np.ndarray): + std_[std_ == 0.0] = 1.0 + elif std_ == 0.: + std_ = 1. + else: + std_ = None + + return mean_, std_ + + +def scale(X, axis=0, with_mean=True, with_std=True, copy=True): + """Standardize a dataset along any axis + + Center to the mean and component wise scale to unit variance. + + Parameters + ---------- + X : array-like or CSR matrix. + The data to center and scale. + + axis : int (0 by default) + axis used to compute the means and standard deviations along. If 0, + independently standardize each feature, otherwise (if 1) standardize + each sample. + + with_mean : boolean, True by default + If True, center the data before scaling. + + with_std : boolean, True by default + If True, scale the data to unit variance (or equivalently, + unit standard deviation). + + copy : boolean, optional, default True + set to False to perform inplace row normalization and avoid a + copy (if the input is already a numpy array or a scipy.sparse + CSR matrix and if axis is 1). + + Notes + ----- + This implementation will refuse to center scipy.sparse matrices + since it would make them non-sparse and would potentially crash the + program with memory exhaustion problems. + + Instead the caller is expected to either set explicitly + `with_mean=False` (in that case, only variance scaling will be + performed on the features of the CSR matrix) or to call `X.toarray()` + if he/she expects the materialized dense array to fit in memory. + + To avoid memory copy the caller should pass a CSR matrix. + + See also + -------- + :class:`sklearn.preprocessing.StandardScaler` to perform centering and + scaling using the ``Transformer`` API (e.g. as part of a preprocessing + :class:`sklearn.pipeline.Pipeline`) + """ + X = check_array(X, accept_sparse='csr', copy=copy, ensure_2d=False) + warn_if_not_float(X, estimator='The scale function') + if sparse.issparse(X): + if with_mean: + raise ValueError( + "Cannot center sparse matrices: pass `with_mean=False` instead" + " See docstring for motivation and alternatives.") + if axis != 0: + raise ValueError("Can only scale sparse matrix on axis=0, " + " got axis=%d" % axis) + if not sparse.isspmatrix_csr(X): + X = X.tocsr() + copy = False + if copy: + X = X.copy() + _, var = mean_variance_axis(X, axis=0) + var[var == 0.0] = 1.0 + inplace_column_scale(X, 1 / np.sqrt(var)) + else: + X = np.asarray(X) + mean_, std_ = _mean_and_std( + X, axis, with_mean=with_mean, with_std=with_std) + if copy: + X = X.copy() + # Xr is a view on the original array that enables easy use of + # broadcasting on the axis in which we are interested in + Xr = np.rollaxis(X, axis) + if with_mean: + Xr -= mean_ + if with_std: + Xr /= std_ + return X + + +class MinMaxScaler(BaseEstimator, TransformerMixin): + """Standardizes features by scaling each feature to a given range. + + This estimator scales and translates each feature individually such + that it is in the given range on the training set, i.e. between + zero and one. + + The standardization is given by:: + + X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) + X_scaled = X_std * (max - min) + min + + where min, max = feature_range. + + This standardization is often used as an alternative to zero mean, + unit variance scaling. + + Parameters + ---------- + feature_range: tuple (min, max), default=(0, 1) + Desired range of transformed data. + + copy : boolean, optional, default True + Set to False to perform inplace row normalization and avoid a + copy (if the input is already a numpy array). + + Attributes + ---------- + min_ : ndarray, shape (n_features,) + Per feature adjustment for minimum. + + scale_ : ndarray, shape (n_features,) + Per feature relative scaling of the data. + """ + + def __init__(self, feature_range=(0, 1), copy=True): + self.feature_range = feature_range + self.copy = copy + + def fit(self, X, y=None): + """Compute the minimum and maximum to be used for later scaling. + + Parameters + ---------- + X : array-like, shape [n_samples, n_features] + The data used to compute the per-feature minimum and maximum + used for later scaling along the features axis. + """ + X = check_array(X, copy=self.copy, ensure_2d=False) + warn_if_not_float(X, estimator=self) + feature_range = self.feature_range + if feature_range[0] >= feature_range[1]: + raise ValueError("Minimum of desired feature range must be smaller" + " than maximum. Got %s." % str(feature_range)) + data_min = np.min(X, axis=0) + data_range = np.max(X, axis=0) - data_min + # Do not scale constant features + if isinstance(data_range, np.ndarray): + data_range[data_range == 0.0] = 1.0 + elif data_range == 0.: + data_range = 1. + self.scale_ = (feature_range[1] - feature_range[0]) / data_range + self.min_ = feature_range[0] - data_min * self.scale_ + self.data_range = data_range + self.data_min = data_min + return self + + def transform(self, X): + """Scaling features of X according to feature_range. + + Parameters + ---------- + X : array-like with shape [n_samples, n_features] + Input data that will be transformed. + """ + check_is_fitted(self, 'scale_') + + X = check_array(X, copy=self.copy, ensure_2d=False) + X *= self.scale_ + X += self.min_ + return X + + def inverse_transform(self, X): + """Undo the scaling of X according to feature_range. + + Parameters + ---------- + X : array-like with shape [n_samples, n_features] + Input data that will be transformed. + """ + check_is_fitted(self, 'scale_') + + X = check_array(X, copy=self.copy, ensure_2d=False) + X -= self.min_ + X /= self.scale_ + return X + + +class StandardScaler(BaseEstimator, TransformerMixin): + """Standardize features by removing the mean and scaling to unit variance + + Centering and scaling happen independently on each feature by computing + the relevant statistics on the samples in the training set. Mean and + standard deviation are then stored to be used on later data using the + `transform` method. + + Standardization of a dataset is a common requirement for many + machine learning estimators: they might behave badly if the + individual feature do not more or less look like standard normally + distributed data (e.g. Gaussian with 0 mean and unit variance). + + For instance many elements used in the objective function of + a learning algorithm (such as the RBF kernel of Support Vector + Machines or the L1 and L2 regularizers of linear models) assume that + all features are centered around 0 and have variance in the same + order. If a feature has a variance that is orders of magnitude larger + that others, it might dominate the objective function and make the + estimator unable to learn from other features correctly as expected. + + Parameters + ---------- + with_mean : boolean, True by default + If True, center the data before scaling. + This does not work (and will raise an exception) when attempted on + sparse matrices, because centering them entails building a dense + matrix which in common use cases is likely to be too large to fit in + memory. + + with_std : boolean, True by default + If True, scale the data to unit variance (or equivalently, + unit standard deviation). + + copy : boolean, optional, default True + If False, try to avoid a copy and do inplace scaling instead. + This is not guaranteed to always work inplace; e.g. if the data is + not a NumPy array or scipy.sparse CSR matrix, a copy may still be + returned. + + Attributes + ---------- + mean_ : array of floats with shape [n_features] + The mean value for each feature in the training set. + + std_ : array of floats with shape [n_features] + The standard deviation for each feature in the training set. + + See also + -------- + :func:`sklearn.preprocessing.scale` to perform centering and + scaling without using the ``Transformer`` object oriented API + + :class:`sklearn.decomposition.RandomizedPCA` with `whiten=True` + to further remove the linear correlation across features. + """ + + def __init__(self, copy=True, with_mean=True, with_std=True): + self.with_mean = with_mean + self.with_std = with_std + self.copy = copy + + def fit(self, X, y=None): + """Compute the mean and std to be used for later scaling. + + Parameters + ---------- + X : array-like or CSR matrix with shape [n_samples, n_features] + The data used to compute the mean and standard deviation + used for later scaling along the features axis. + """ + X = check_array(X, accept_sparse='csr', copy=self.copy, + ensure_2d=False) + if warn_if_not_float(X, estimator=self): + X = X.astype(np.float) + if sparse.issparse(X): + if self.with_mean: + raise ValueError( + "Cannot center sparse matrices: pass `with_mean=False` " + "instead. See docstring for motivation and alternatives.") + self.mean_ = None + + if self.with_std: + var = mean_variance_axis(X, axis=0)[1] + self.std_ = np.sqrt(var) + self.std_[var == 0.0] = 1.0 + else: + self.std_ = None + return self + else: + self.mean_, self.std_ = _mean_and_std( + X, axis=0, with_mean=self.with_mean, with_std=self.with_std) + return self + + def transform(self, X, y=None, copy=None): + """Perform standardization by centering and scaling + + Parameters + ---------- + X : array-like with shape [n_samples, n_features] + The data used to scale along the features axis. + """ + check_is_fitted(self, 'std_') + + copy = copy if copy is not None else self.copy + X = check_array(X, accept_sparse='csr', copy=copy, ensure_2d=False) + if warn_if_not_float(X, estimator=self): + X = X.astype(np.float) + if sparse.issparse(X): + if self.with_mean: + raise ValueError( + "Cannot center sparse matrices: pass `with_mean=False` " + "instead. See docstring for motivation and alternatives.") + if self.std_ is not None: + inplace_column_scale(X, 1 / self.std_) + else: + if self.with_mean: + X -= self.mean_ + if self.with_std: + X /= self.std_ + return X + + def inverse_transform(self, X, copy=None): + """Scale back the data to the original representation + + Parameters + ---------- + X : array-like with shape [n_samples, n_features] + The data used to scale along the features axis. + """ + check_is_fitted(self, 'std_') + + copy = copy if copy is not None else self.copy + if sparse.issparse(X): + if self.with_mean: + raise ValueError( + "Cannot uncenter sparse matrices: pass `with_mean=False` " + "instead See docstring for motivation and alternatives.") + if not sparse.isspmatrix_csr(X): + X = X.tocsr() + copy = False + if copy: + X = X.copy() + if self.std_ is not None: + inplace_column_scale(X, self.std_) + else: + X = np.asarray(X) + if copy: + X = X.copy() + if self.with_std: + X *= self.std_ + if self.with_mean: + X += self.mean_ + return X + + +class PolynomialFeatures(BaseEstimator, TransformerMixin): + """Generate polynomial and interaction features. + + Generate a new feature matrix consisting of all polynomial combinations + of the features with degree less than or equal to the specified degree. + For example, if an input sample is two dimensional and of the form + [a, b], the degree-2 polynomial features are [1, a, b, a^2, ab, b^2]. + + Parameters + ---------- + degree : integer + The degree of the polynomial features. Default = 2. + + interaction_only : boolean, default = False + If true, only interaction features are produced: features that are + products of at most ``degree`` *distinct* input features (so not + ``x[1] ** 2``, ``x[0] * x[2] ** 3``, etc.). + + include_bias : boolean + If True (default), then include a bias column, the feature in which + all polynomial powers are zero (i.e. a column of ones - acts as an + intercept term in a linear model). + + Examples + -------- + >>> X = np.arange(6).reshape(3, 2) + >>> X + array([[0, 1], + [2, 3], + [4, 5]]) + >>> poly = PolynomialFeatures(2) + >>> poly.fit_transform(X) + array([[ 1, 0, 1, 0, 0, 1], + [ 1, 2, 3, 4, 6, 9], + [ 1, 4, 5, 16, 20, 25]]) + >>> poly = PolynomialFeatures(interaction_only=True) + >>> poly.fit_transform(X) + array([[ 1, 0, 1, 0], + [ 1, 2, 3, 6], + [ 1, 4, 5, 20]]) + + Attributes + ---------- + + powers_ : + powers_[i, j] is the exponent of the jth input in the ith output. + + Notes + ----- + Be aware that the number of features in the output array scales + polynomially in the number of features of the input array, and + exponentially in the degree. High degrees can cause overfitting. + + See :ref:`examples/linear_model/plot_polynomial_interpolation.py + ` + """ + def __init__(self, degree=2, interaction_only=False, include_bias=True): + self.degree = degree + self.interaction_only = interaction_only + self.include_bias = include_bias + + @staticmethod + def _power_matrix(n_features, degree, interaction_only, include_bias): + """Compute the matrix of polynomial powers""" + comb = (combinations if interaction_only else combinations_w_r) + start = int(not include_bias) + combn = chain.from_iterable(comb(range(n_features), i) + for i in range(start, degree + 1)) + powers = np.vstack(bincount(c, minlength=n_features) for c in combn) + return powers + + def fit(self, X, y=None): + """ + Compute the polynomial feature combinations + """ + n_samples, n_features = check_array(X).shape + self.powers_ = self._power_matrix(n_features, self.degree, + self.interaction_only, + self.include_bias) + return self + + def transform(self, X, y=None): + """Transform data to polynomial features + + Parameters + ---------- + X : array with shape [n_samples, n_features] + The data to transform, row by row. + + Returns + ------- + XP : np.ndarray shape [n_samples, NP] + The matrix of features, where NP is the number of polynomial + features generated from the combination of inputs. + """ + check_is_fitted(self, 'powers_') + + X = check_array(X) + n_samples, n_features = X.shape + + if n_features != self.powers_.shape[1]: + raise ValueError("X shape does not match training shape") + + return (X[:, None, :] ** self.powers_).prod(-1) + + +def normalize(X, norm='l2', axis=1, copy=True): + """Scale input vectors individually to unit norm (vector length). + + Parameters + ---------- + X : array or scipy.sparse matrix with shape [n_samples, n_features] + The data to normalize, element by element. + scipy.sparse matrices should be in CSR format to avoid an + un-necessary copy. + + norm : 'l1' or 'l2', optional ('l2' by default) + The norm to use to normalize each non zero sample (or each non-zero + feature if axis is 0). + + axis : 0 or 1, optional (1 by default) + axis used to normalize the data along. If 1, independently normalize + each sample, otherwise (if 0) normalize each feature. + + copy : boolean, optional, default True + set to False to perform inplace row normalization and avoid a + copy (if the input is already a numpy array or a scipy.sparse + CSR matrix and if axis is 1). + + See also + -------- + :class:`sklearn.preprocessing.Normalizer` to perform normalization + using the ``Transformer`` API (e.g. as part of a preprocessing + :class:`sklearn.pipeline.Pipeline`) + """ + if norm not in ('l1', 'l2'): + raise ValueError("'%s' is not a supported norm" % norm) + + if axis == 0: + sparse_format = 'csc' + elif axis == 1: + sparse_format = 'csr' + else: + raise ValueError("'%d' is not a supported axis" % axis) + + X = check_array(X, sparse_format, copy=copy) + warn_if_not_float(X, 'The normalize function') + if axis == 0: + X = X.T + + if sparse.issparse(X): + if norm == 'l1': + inplace_csr_row_normalize_l1(X) + elif norm == 'l2': + inplace_csr_row_normalize_l2(X) + else: + if norm == 'l1': + norms = np.abs(X).sum(axis=1) + norms[norms == 0.0] = 1.0 + elif norm == 'l2': + norms = row_norms(X) + norms[norms == 0.0] = 1.0 + X /= norms[:, np.newaxis] + + if axis == 0: + X = X.T + + return X + + +class Normalizer(BaseEstimator, TransformerMixin): + """Normalize samples individually to unit norm. + + Each sample (i.e. each row of the data matrix) with at least one + non zero component is rescaled independently of other samples so + that its norm (l1 or l2) equals one. + + This transformer is able to work both with dense numpy arrays and + scipy.sparse matrix (use CSR format if you want to avoid the burden of + a copy / conversion). + + Scaling inputs to unit norms is a common operation for text + classification or clustering for instance. For instance the dot + product of two l2-normalized TF-IDF vectors is the cosine similarity + of the vectors and is the base similarity metric for the Vector + Space Model commonly used by the Information Retrieval community. + + Parameters + ---------- + norm : 'l1' or 'l2', optional ('l2' by default) + The norm to use to normalize each non zero sample. + + copy : boolean, optional, default True + set to False to perform inplace row normalization and avoid a + copy (if the input is already a numpy array or a scipy.sparse + CSR matrix). + + Notes + ----- + This estimator is stateless (besides constructor parameters), the + fit method does nothing but is useful when used in a pipeline. + + See also + -------- + :func:`sklearn.preprocessing.normalize` equivalent function + without the object oriented API + """ + + def __init__(self, norm='l2', copy=True): + self.norm = norm + self.copy = copy + + def fit(self, X, y=None): + """Do nothing and return the estimator unchanged + + This method is just there to implement the usual API and hence + work in pipelines. + """ + X = check_array(X, accept_sparse='csr') + return self + + def transform(self, X, y=None, copy=None): + """Scale each non zero row of X to unit norm + + Parameters + ---------- + X : array or scipy.sparse matrix with shape [n_samples, n_features] + The data to normalize, row by row. scipy.sparse matrices should be + in CSR format to avoid an un-necessary copy. + """ + copy = copy if copy is not None else self.copy + X = check_array(X, accept_sparse='csr') + return normalize(X, norm=self.norm, axis=1, copy=copy) + + +def binarize(X, threshold=0.0, copy=True): + """Boolean thresholding of array-like or scipy.sparse matrix + + Parameters + ---------- + X : array or scipy.sparse matrix with shape [n_samples, n_features] + The data to binarize, element by element. + scipy.sparse matrices should be in CSR or CSC format to avoid an + un-necessary copy. + + threshold : float, optional (0.0 by default) + Feature values below or equal to this are replaced by 0, above it by 1. + Threshold may not be less than 0 for operations on sparse matrices. + + copy : boolean, optional, default True + set to False to perform inplace binarization and avoid a copy + (if the input is already a numpy array or a scipy.sparse CSR / CSC + matrix and if axis is 1). + + See also + -------- + :class:`sklearn.preprocessing.Binarizer` to perform binarization + using the ``Transformer`` API (e.g. as part of a preprocessing + :class:`sklearn.pipeline.Pipeline`) + """ + X = check_array(X, accept_sparse=['csr', 'csc'], copy=copy) + if sparse.issparse(X): + if threshold < 0: + raise ValueError('Cannot binarize a sparse matrix with threshold ' + '< 0') + cond = X.data > threshold + not_cond = np.logical_not(cond) + X.data[cond] = 1 + X.data[not_cond] = 0 + X.eliminate_zeros() + else: + cond = X > threshold + not_cond = np.logical_not(cond) + X[cond] = 1 + X[not_cond] = 0 + return X + + +class Binarizer(BaseEstimator, TransformerMixin): + """Binarize data (set feature values to 0 or 1) according to a threshold + + Values greater than the threshold map to 1, while values less than + or equal to the threshold map to 0. With the default threshold of 0, + only positive values map to 1. + + Binarization is a common operation on text count data where the + analyst can decide to only consider the presence or absence of a + feature rather than a quantified number of occurrences for instance. + + It can also be used as a pre-processing step for estimators that + consider boolean random variables (e.g. modelled using the Bernoulli + distribution in a Bayesian setting). + + Parameters + ---------- + threshold : float, optional (0.0 by default) + Feature values below or equal to this are replaced by 0, above it by 1. + Threshold may not be less than 0 for operations on sparse matrices. + + copy : boolean, optional, default True + set to False to perform inplace binarization and avoid a copy (if + the input is already a numpy array or a scipy.sparse CSR matrix). + + Notes + ----- + If the input is a sparse matrix, only the non-zero values are subject + to update by the Binarizer class. + + This estimator is stateless (besides constructor parameters), the + fit method does nothing but is useful when used in a pipeline. + """ + + def __init__(self, threshold=0.0, copy=True): + self.threshold = threshold + self.copy = copy + + def fit(self, X, y=None): + """Do nothing and return the estimator unchanged + + This method is just there to implement the usual API and hence + work in pipelines. + """ + check_array(X, accept_sparse='csr') + return self + + def transform(self, X, y=None, copy=None): + """Binarize each element of X + + Parameters + ---------- + X : array or scipy.sparse matrix with shape [n_samples, n_features] + The data to binarize, element by element. + scipy.sparse matrices should be in CSR format to avoid an + un-necessary copy. + """ + copy = copy if copy is not None else self.copy + return binarize(X, threshold=self.threshold, copy=copy) + + +class KernelCenterer(BaseEstimator, TransformerMixin): + """Center a kernel matrix + + Let K(x, z) be a kernel defined by phi(x)^T phi(z), where phi is a + function mapping x to a Hilbert space. KernelCenterer centers (i.e., + normalize to have zero mean) the data without explicitly computing phi(x). + It is equivalent to centering phi(x) with + sklearn.preprocessing.StandardScaler(with_std=False). + """ + + def fit(self, K, y=None): + """Fit KernelCenterer + + Parameters + ---------- + K : numpy array of shape [n_samples, n_samples] + Kernel matrix. + + Returns + ------- + self : returns an instance of self. + """ + K = check_array(K) + n_samples = K.shape[0] + self.K_fit_rows_ = np.sum(K, axis=0) / n_samples + self.K_fit_all_ = self.K_fit_rows_.sum() / n_samples + return self + + def transform(self, K, y=None, copy=True): + """Center kernel matrix. + + Parameters + ---------- + K : numpy array of shape [n_samples1, n_samples2] + Kernel matrix. + + copy : boolean, optional, default True + Set to False to perform inplace computation. + + Returns + ------- + K_new : numpy array of shape [n_samples1, n_samples2] + """ + check_is_fitted(self, 'K_fit_all_') + + K = check_array(K) + if copy: + K = K.copy() + + K_pred_cols = (np.sum(K, axis=1) / + self.K_fit_rows_.shape[0])[:, np.newaxis] + + K -= self.K_fit_rows_ + K -= K_pred_cols + K += self.K_fit_all_ + + return K + + +def add_dummy_feature(X, value=1.0): + """Augment dataset with an additional dummy feature. + + This is useful for fitting an intercept term with implementations which + cannot otherwise fit it directly. + + Parameters + ---------- + X : array or scipy.sparse matrix with shape [n_samples, n_features] + Data. + + value : float + Value to use for the dummy feature. + + Returns + ------- + + X : array or scipy.sparse matrix with shape [n_samples, n_features + 1] + Same data with dummy feature added as first column. + + Examples + -------- + + >>> from sklearn.preprocessing import add_dummy_feature + >>> add_dummy_feature([[0, 1], [1, 0]]) + array([[ 1., 0., 1.], + [ 1., 1., 0.]]) + """ + X = check_array(X, accept_sparse=['csc', 'csr', 'coo']) + n_samples, n_features = X.shape + shape = (n_samples, n_features + 1) + if sparse.issparse(X): + if sparse.isspmatrix_coo(X): + # Shift columns to the right. + col = X.col + 1 + # Column indices of dummy feature are 0 everywhere. + col = np.concatenate((np.zeros(n_samples), col)) + # Row indices of dummy feature are 0, ..., n_samples-1. + row = np.concatenate((np.arange(n_samples), X.row)) + # Prepend the dummy feature n_samples times. + data = np.concatenate((np.ones(n_samples) * value, X.data)) + return sparse.coo_matrix((data, (row, col)), shape) + elif sparse.isspmatrix_csc(X): + # Shift index pointers since we need to add n_samples elements. + indptr = X.indptr + n_samples + # indptr[0] must be 0. + indptr = np.concatenate((np.array([0]), indptr)) + # Row indices of dummy feature are 0, ..., n_samples-1. + indices = np.concatenate((np.arange(n_samples), X.indices)) + # Prepend the dummy feature n_samples times. + data = np.concatenate((np.ones(n_samples) * value, X.data)) + return sparse.csc_matrix((data, indices, indptr), shape) + else: + klass = X.__class__ + return klass(add_dummy_feature(X.tocoo(), value)) + else: + return np.hstack((np.ones((n_samples, 1)) * value, X)) + + +def _transform_selected(X, transform, selected="all", copy=True): + """Apply a transform function to portion of selected features + + Parameters + ---------- + X : array-like or sparse matrix, shape=(n_samples, n_features) + Dense array or sparse matrix. + + transform : callable + A callable transform(X) -> X_transformed + + copy : boolean, optional + Copy X even if it could be avoided. + + selected: "all" or array of indices or mask + Specify which features to apply the transform to. + + Returns + ------- + X : array or sparse matrix, shape=(n_samples, n_features_new) + """ + if selected == "all": + return transform(X) + + X = check_array(X, accept_sparse='csc', copy=copy) + + if len(selected) == 0: + return X + + n_features = X.shape[1] + ind = np.arange(n_features) + sel = np.zeros(n_features, dtype=bool) + sel[np.asarray(selected)] = True + not_sel = np.logical_not(sel) + n_selected = np.sum(sel) + + if n_selected == 0: + # No features selected. + return X + elif n_selected == n_features: + # All features selected. + return transform(X) + else: + X_sel = transform(X[:, ind[sel]]) + X_not_sel = X[:, ind[not_sel]] + + if sparse.issparse(X_sel) or sparse.issparse(X_not_sel): + return sparse.hstack((X_sel, X_not_sel)) + else: + return np.hstack((X_sel, X_not_sel)) + + +class OneHotEncoder(BaseEstimator, TransformerMixin): + """Encode categorical integer features using a one-hot aka one-of-K scheme. + + The input to this transformer should be a matrix of integers, denoting + the values taken on by categorical (discrete) features. The output will be + a sparse matrix where each column corresponds to one possible value of one + feature. It is assumed that input features take on values in the range + [0, n_values). + + This encoding is needed for feeding categorical data to many scikit-learn + estimators, notably linear models and SVMs with the standard kernels. + + Parameters + ---------- + n_values : 'auto', int or array of ints + Number of values per feature. + + - 'auto' : determine value range from training data. + - int : maximum value for all features. + - array : maximum value per feature. + + categorical_features: "all" or array of indices or mask + Specify what features are treated as categorical. + + - 'all' (default): All features are treated as categorical. + - array of indices: Array of categorical feature indices. + - mask: Array of length n_features and with dtype=bool. + + Non-categorical features are always stacked to the right of the matrix. + + dtype : number type, default=np.float + Desired dtype of output. + + sparse : boolean, default=True + Will return sparse matrix if set True else will return an array. + + handle_unknown : str, 'error' or 'ignore' + Whether to raise an error or ignore if a unknown categorical feature is + present during transform. + + Attributes + ---------- + active_features_ : array + Indices for active features, meaning values that actually occur + in the training set. Only available when n_values is ``'auto'``. + + feature_indices_ : array of shape (n_features,) + Indices to feature ranges. + Feature ``i`` in the original data is mapped to features + from ``feature_indices_[i]`` to ``feature_indices_[i+1]`` + (and then potentially masked by `active_features_` afterwards) + + n_values_ : array of shape (n_features,) + Maximum number of values per feature. + + Examples + -------- + Given a dataset with three features and two samples, we let the encoder + find the maximum value per feature and transform the data to a binary + one-hot encoding. + + >>> from sklearn.preprocessing import OneHotEncoder + >>> enc = OneHotEncoder() + >>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], \ +[1, 0, 2]]) # doctest: +ELLIPSIS + OneHotEncoder(categorical_features='all', dtype=<... 'float'>, + handle_unknown='error', n_values='auto', sparse=True) + >>> enc.n_values_ + array([2, 3, 4]) + >>> enc.feature_indices_ + array([0, 2, 5, 9]) + >>> enc.transform([[0, 1, 1]]).toarray() + array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.]]) + + See also + -------- + sklearn.feature_extraction.DictVectorizer : performs a one-hot encoding of + dictionary items (also handles string-valued features). + sklearn.feature_extraction.FeatureHasher : performs an approximate one-hot + encoding of dictionary items or strings. + """ + def __init__(self, n_values="auto", categorical_features="all", + dtype=np.float, sparse=True, handle_unknown='error'): + self.n_values = n_values + self.categorical_features = categorical_features + self.dtype = dtype + self.sparse = sparse + self.handle_unknown = handle_unknown + + def fit(self, X, y=None): + """Fit OneHotEncoder to X. + + Parameters + ---------- + X : array-like, shape=(n_samples, n_feature) + Input array of type int. + + Returns + ------- + self + """ + self.fit_transform(X) + return self + + def _fit_transform(self, X): + """Assumes X contains only categorical features.""" + X = check_array(X, dtype=np.int) + if np.any(X < 0): + raise ValueError("X needs to contain only non-negative integers.") + n_samples, n_features = X.shape + if self.n_values == 'auto': + n_values = np.max(X, axis=0) + 1 + elif isinstance(self.n_values, numbers.Integral): + if (np.max(X, axis=0) >= self.n_values).any(): + raise ValueError("Feature out of bounds for n_values=%d" + % self.n_values) + n_values = np.empty(n_features, dtype=np.int) + n_values.fill(self.n_values) + else: + try: + n_values = np.asarray(self.n_values, dtype=int) + except (ValueError, TypeError): + raise TypeError("Wrong type for parameter `n_values`. Expected" + " 'auto', int or array of ints, got %r" + % type(X)) + if n_values.ndim < 1 or n_values.shape[0] != X.shape[1]: + raise ValueError("Shape mismatch: if n_values is an array," + " it has to be of shape (n_features,).") + + self.n_values_ = n_values + n_values = np.hstack([[0], n_values]) + indices = np.cumsum(n_values) + self.feature_indices_ = indices + + column_indices = (X + indices[:-1]).ravel() + row_indices = np.repeat(np.arange(n_samples, dtype=np.int32), + n_features) + data = np.ones(n_samples * n_features) + out = sparse.coo_matrix((data, (row_indices, column_indices)), + shape=(n_samples, indices[-1]), + dtype=self.dtype).tocsr() + + if self.n_values == 'auto': + mask = np.array(out.sum(axis=0)).ravel() != 0 + active_features = np.where(mask)[0] + out = out[:, active_features] + self.active_features_ = active_features + + return out if self.sparse else out.toarray() + + def fit_transform(self, X, y=None): + """Fit OneHotEncoder to X, then transform X. + + Equivalent to self.fit(X).transform(X), but more convenient and more + efficient. See fit for the parameters, transform for the return value. + """ + return _transform_selected(X, self._fit_transform, + self.categorical_features, copy=True) + + def _transform(self, X): + """Assumes X contains only categorical features.""" + X = check_array(X, dtype=np.int) + if np.any(X < 0): + raise ValueError("X needs to contain only non-negative integers.") + n_samples, n_features = X.shape + + indices = self.feature_indices_ + if n_features != indices.shape[0] - 1: + raise ValueError("X has different shape than during fitting." + " Expected %d, got %d." + % (indices.shape[0] - 1, n_features)) + + # We use only those catgorical features of X that are known using fit. + # i.e lesser than n_values_ using mask. + # This means, if self.handle_unknown is "ignore", the row_indices and + # col_indices corresponding to the unknown categorical feature are ignored. + mask = (X < self.n_values_).ravel() + if np.any(~mask): + if self.handle_unknown not in ['error', 'ignore']: + raise ValueError("handle_unknown should be either error or " + "unknown got %s" % self.handle_unknown) + if self.handle_unknown == 'error': + raise ValueError("unknown categorical feature present %s " + "during transform." % X[~mask]) + + column_indices = (X + indices[:-1]).ravel()[mask] + row_indices = np.repeat(np.arange(n_samples, dtype=np.int32), + n_features)[mask] + data = np.ones(np.sum(mask)) + out = sparse.coo_matrix((data, (row_indices, column_indices)), + shape=(n_samples, indices[-1]), + dtype=self.dtype).tocsr() + if self.n_values == 'auto': + out = out[:, self.active_features_] + + return out if self.sparse else out.toarray() + + def transform(self, X): + """Transform X using one-hot encoding. + + Parameters + ---------- + X : array-like, shape=(n_samples, n_features) + Input array of type int. + + Returns + ------- + X_out : sparse matrix if sparse=True else a 2-d array, dtype=int + Transformed input. + """ + return _transform_selected(X, self._transform, + self.categorical_features, copy=True) diff --git a/sklearn/preprocessing/imputation.py b/sklearn/preprocessing/imputation.py new file mode 100644 index 0000000000000..3f7bd29da1fe4 --- /dev/null +++ b/sklearn/preprocessing/imputation.py @@ -0,0 +1,375 @@ +# Authors: Nicolas Tresegnie +# License: BSD 3 clause + +import warnings + +import numpy as np +import numpy.ma as ma +from scipy import sparse +from scipy import stats + +from ..base import BaseEstimator, TransformerMixin +from ..utils import check_array +from ..utils import as_float_array +from ..utils.fixes import astype +from ..utils.sparsefuncs import _get_median +from ..utils.validation import check_is_fitted + +from ..externals import six + +zip = six.moves.zip +map = six.moves.map + +__all__ = [ + 'Imputer', +] + + +def _get_mask(X, value_to_mask): + """Compute the boolean mask X == missing_values.""" + if value_to_mask == "NaN" or np.isnan(value_to_mask): + return np.isnan(X) + else: + return X == value_to_mask + + +def _most_frequent(array, extra_value, n_repeat): + """Compute the most frequent value in a 1d array extended with + [extra_value] * n_repeat, where extra_value is assumed to be not part + of the array.""" + # Compute the most frequent value in array only + if array.size > 0: + mode = stats.mode(array) + most_frequent_value = mode[0][0] + most_frequent_count = mode[1][0] + else: + most_frequent_value = 0 + most_frequent_count = 0 + + # Compare to array + [extra_value] * n_repeat + if most_frequent_count == 0 and n_repeat == 0: + return np.nan + elif most_frequent_count < n_repeat: + return extra_value + elif most_frequent_count > n_repeat: + return most_frequent_value + elif most_frequent_count == n_repeat: + # Ties the breaks. Copy the behaviour of scipy.stats.mode + if most_frequent_value < extra_value: + return most_frequent_value + else: + return extra_value + + +class Imputer(BaseEstimator, TransformerMixin): + """Imputation transformer for completing missing values. + + Parameters + ---------- + missing_values : integer or "NaN", optional (default="NaN") + The placeholder for the missing values. All occurrences of + `missing_values` will be imputed. For missing values encoded as np.nan, + use the string value "NaN". + + strategy : string, optional (default="mean") + The imputation strategy. + + - If "mean", then replace missing values using the mean along + the axis. + - If "median", then replace missing values using the median along + the axis. + - If "most_frequent", then replace missing using the most frequent + value along the axis. + + axis : integer, optional (default=0) + The axis along which to impute. + + - If `axis=0`, then impute along columns. + - If `axis=1`, then impute along rows. + + verbose : integer, optional (default=0) + Controls the verbosity of the imputer. + + copy : boolean, optional (default=True) + If True, a copy of X will be created. If False, imputation will + be done in-place whenever possible. Note that, in the following cases, + a new copy will always be made, even if `copy=False`: + + - If X is not an array of floating values; + - If X is sparse and `missing_values=0`; + - If `axis=0` and X is encoded as a CSR matrix; + - If `axis=1` and X is encoded as a CSC matrix. + + Attributes + ---------- + statistics_ : array of shape (n_features,) + The imputation fill value for each feature if axis == 0. + + Notes + ----- + - When ``axis=0``, columns which only contained missing values at `fit` + are discarded upon `transform`. + - When ``axis=1``, an exception is raised if there are rows for which it is + not possible to fill in the missing values (e.g., because they only + contain missing values). + """ + def __init__(self, missing_values="NaN", strategy="mean", + axis=0, verbose=0, copy=True): + self.missing_values = missing_values + self.strategy = strategy + self.axis = axis + self.verbose = verbose + self.copy = copy + + def fit(self, X, y=None): + """Fit the imputer on X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Input data, where ``n_samples`` is the number of samples and + ``n_features`` is the number of features. + + Returns + ------- + self : object + Returns self. + """ + # Check parameters + allowed_strategies = ["mean", "median", "most_frequent"] + if self.strategy not in allowed_strategies: + raise ValueError("Can only use these strategies: {0} " + " got strategy={1}".format(allowed_strategies, + self.strategy)) + + if self.axis not in [0, 1]: + raise ValueError("Can only impute missing values on axis 0 and 1, " + " got axis={0}".format(self.axis)) + + # Since two different arrays can be provided in fit(X) and + # transform(X), the imputation data will be computed in transform() + # when the imputation is done per sample (i.e., when axis=1). + if self.axis == 0: + X = check_array(X, accept_sparse='csc', dtype=np.float64, + force_all_finite=False) + + if sparse.issparse(X): + self.statistics_ = self._sparse_fit(X, + self.strategy, + self.missing_values, + self.axis) + else: + self.statistics_ = self._dense_fit(X, + self.strategy, + self.missing_values, + self.axis) + + return self + + def _sparse_fit(self, X, strategy, missing_values, axis): + """Fit the transformer on sparse data.""" + # Imputation is done "by column", so if we want to do it + # by row we only need to convert the matrix to csr format. + if axis == 1: + X = X.tocsr() + else: + X = X.tocsc() + + # Count the zeros + if missing_values == 0: + n_zeros_axis = np.zeros(X.shape[not axis], dtype=int) + else: + n_zeros_axis = X.shape[axis] - np.diff(X.indptr) + + # Mean + if strategy == "mean": + if missing_values != 0: + n_non_missing = n_zeros_axis + + # Mask the missing elements + mask_missing_values = _get_mask(X.data, missing_values) + mask_valids = np.logical_not(mask_missing_values) + + # Sum only the valid elements + new_data = X.data.copy() + new_data[mask_missing_values] = 0 + X = sparse.csc_matrix((new_data, X.indices, X.indptr), + copy=False) + sums = X.sum(axis=0) + + # Count the elements != 0 + mask_non_zeros = sparse.csc_matrix( + (mask_valids.astype(np.float64), + X.indices, + X.indptr), copy=False) + s = mask_non_zeros.sum(axis=0) + n_non_missing = np.add(n_non_missing, s) + + else: + sums = X.sum(axis=axis) + n_non_missing = np.diff(X.indptr) + + # Ignore the error, columns with a np.nan statistics_ + # are not an error at this point. These columns will + # be removed in transform + with np.errstate(all="ignore"): + return np.ravel(sums) / np.ravel(n_non_missing) + + # Median + Most frequent + else: + # Remove the missing values, for each column + columns_all = np.hsplit(X.data, X.indptr[1:-1]) + mask_missing_values = _get_mask(X.data, missing_values) + mask_valids = np.hsplit(np.logical_not(mask_missing_values), + X.indptr[1:-1]) + + # astype necessary for bug in numpy.hsplit before v1.9 + columns = [col[astype(mask, bool, copy=False)] + for col, mask in zip(columns_all, mask_valids)] + + # Median + if strategy == "median": + median = np.empty(len(columns)) + for i, column in enumerate(columns): + median[i] = _get_median(column, n_zeros_axis[i]) + + return median + + # Most frequent + elif strategy == "most_frequent": + most_frequent = np.empty(len(columns)) + + for i, column in enumerate(columns): + most_frequent[i] = _most_frequent(column, + 0, + n_zeros_axis[i]) + + return most_frequent + + def _dense_fit(self, X, strategy, missing_values, axis): + """Fit the transformer on dense data.""" + X = check_array(X, force_all_finite=False) + mask = _get_mask(X, missing_values) + masked_X = ma.masked_array(X, mask=mask) + + # Mean + if strategy == "mean": + mean_masked = np.ma.mean(masked_X, axis=axis) + # Avoid the warning "Warning: converting a masked element to nan." + mean = np.ma.getdata(mean_masked) + mean[np.ma.getmask(mean_masked)] = np.nan + + return mean + + # Median + elif strategy == "median": + if tuple(int(v) for v in np.__version__.split('.')[:2]) < (1, 5): + # In old versions of numpy, calling a median on an array + # containing nans returns nan. This is different is + # recent versions of numpy, which we want to mimic + masked_X.mask = np.logical_or(masked_X.mask, + np.isnan(X)) + median_masked = np.ma.median(masked_X, axis=axis) + # Avoid the warning "Warning: converting a masked element to nan." + median = np.ma.getdata(median_masked) + median[np.ma.getmaskarray(median_masked)] = np.nan + + return median + + # Most frequent + elif strategy == "most_frequent": + # scipy.stats.mstats.mode cannot be used because it will no work + # properly if the first element is masked and if it's frequency + # is equal to the frequency of the most frequent valid element + # See https://github.com/scipy/scipy/issues/2636 + + # To be able access the elements by columns + if axis == 0: + X = X.transpose() + mask = mask.transpose() + + most_frequent = np.empty(X.shape[0]) + + for i, (row, row_mask) in enumerate(zip(X[:], mask[:])): + row_mask = np.logical_not(row_mask).astype(np.bool) + row = row[row_mask] + most_frequent[i] = _most_frequent(row, np.nan, 0) + + return most_frequent + + def transform(self, X): + """Impute all missing values in X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + The input data to complete. + """ + if self.axis == 0: + check_is_fitted(self, 'statistics_') + + # Copy just once + X = as_float_array(X, copy=self.copy, force_all_finite=False) + + # Since two different arrays can be provided in fit(X) and + # transform(X), the imputation data need to be recomputed + # when the imputation is done per sample + if self.axis == 1: + X = check_array(X, accept_sparse='csr', force_all_finite=False, + copy=False) + + if sparse.issparse(X): + statistics = self._sparse_fit(X, + self.strategy, + self.missing_values, + self.axis) + + else: + statistics = self._dense_fit(X, + self.strategy, + self.missing_values, + self.axis) + else: + X = check_array(X, accept_sparse='csc', force_all_finite=False, + copy=False) + statistics = self.statistics_ + + # Delete the invalid rows/columns + invalid_mask = np.isnan(statistics) + valid_mask = np.logical_not(invalid_mask) + valid_statistics = statistics[valid_mask] + valid_statistics_indexes = np.where(valid_mask)[0] + missing = np.arange(X.shape[not self.axis])[invalid_mask] + + if self.axis == 0 and invalid_mask.any(): + if self.verbose: + warnings.warn("Deleting features without " + "observed values: %s" % missing) + X = X[:, valid_statistics_indexes] + elif self.axis == 1 and invalid_mask.any(): + raise ValueError("Some rows only contain " + "missing values: %s" % missing) + + # Do actual imputation + if sparse.issparse(X) and self.missing_values != 0: + mask = _get_mask(X.data, self.missing_values) + indexes = np.repeat(np.arange(len(X.indptr) - 1, dtype=np.int), + np.diff(X.indptr))[mask] + + X.data[mask] = valid_statistics[indexes].astype(X.dtype) + else: + if sparse.issparse(X): + X = X.toarray() + + mask = _get_mask(X, self.missing_values) + n_missing = np.sum(mask, axis=self.axis) + values = np.repeat(valid_statistics, n_missing) + + if self.axis == 0: + coordinates = np.where(mask.transpose())[::-1] + else: + coordinates = mask + + X[coordinates] = values + + return X diff --git a/sklearn/preprocessing/label.py b/sklearn/preprocessing/label.py new file mode 100644 index 0000000000000..4e1809b87b1df --- /dev/null +++ b/sklearn/preprocessing/label.py @@ -0,0 +1,855 @@ +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Olivier Grisel +# Andreas Mueller +# Joel Nothman +# Hamzeh Alsalhi +# License: BSD 3 clause + +from collections import defaultdict +import itertools +import array +import warnings + +import numpy as np +import scipy.sparse as sp + +from ..base import BaseEstimator, TransformerMixin + +from ..utils.fixes import np_version +from ..utils.fixes import sparse_min_max +from ..utils.fixes import astype +from ..utils.fixes import in1d +from ..utils import deprecated, column_or_1d +from ..utils.validation import check_array +from ..utils.validation import _num_samples +from ..utils.multiclass import unique_labels +from ..utils.multiclass import type_of_target + +from ..externals import six + +zip = six.moves.zip +map = six.moves.map + +__all__ = [ + 'label_binarize', + 'LabelBinarizer', + 'LabelEncoder', + 'MultiLabelBinarizer', +] + + +def _check_numpy_unicode_bug(labels): + """Check that user is not subject to an old numpy bug + + Fixed in master before 1.7.0: + + https://github.com/numpy/numpy/pull/243 + + """ + if np_version[:3] < (1, 7, 0) and labels.dtype.kind == 'U': + raise RuntimeError("NumPy < 1.7.0 does not implement searchsorted" + " on unicode data correctly. Please upgrade" + " NumPy to use LabelEncoder with unicode inputs.") + + +class LabelEncoder(BaseEstimator, TransformerMixin): + """Encode labels with value between 0 and n_classes-1. + + Attributes + ---------- + classes_ : array of shape (n_class,) + Holds the label for each class. + + Examples + -------- + `LabelEncoder` can be used to normalize labels. + + >>> from sklearn import preprocessing + >>> le = preprocessing.LabelEncoder() + >>> le.fit([1, 2, 2, 6]) + LabelEncoder() + >>> le.classes_ + array([1, 2, 6]) + >>> le.transform([1, 1, 2, 6]) #doctest: +ELLIPSIS + array([0, 0, 1, 2]...) + >>> le.inverse_transform([0, 0, 1, 2]) + array([1, 1, 2, 6]) + + It can also be used to transform non-numerical labels (as long as they are + hashable and comparable) to numerical labels. + + >>> le = preprocessing.LabelEncoder() + >>> le.fit(["paris", "paris", "tokyo", "amsterdam"]) + LabelEncoder() + >>> list(le.classes_) + ['amsterdam', 'paris', 'tokyo'] + >>> le.transform(["tokyo", "tokyo", "paris"]) #doctest: +ELLIPSIS + array([2, 2, 1]...) + >>> list(le.inverse_transform([2, 2, 1])) + ['tokyo', 'tokyo', 'paris'] + + """ + + def _check_fitted(self): + if not hasattr(self, "classes_"): + raise ValueError("LabelEncoder was not fitted yet.") + + def fit(self, y): + """Fit label encoder + + Parameters + ---------- + y : array-like of shape (n_samples,) + Target values. + + Returns + ------- + self : returns an instance of self. + """ + y = column_or_1d(y, warn=True) + _check_numpy_unicode_bug(y) + self.classes_ = np.unique(y) + return self + + def fit_transform(self, y): + """Fit label encoder and return encoded labels + + Parameters + ---------- + y : array-like of shape [n_samples] + Target values. + + Returns + ------- + y : array-like of shape [n_samples] + """ + y = column_or_1d(y, warn=True) + _check_numpy_unicode_bug(y) + self.classes_, y = np.unique(y, return_inverse=True) + return y + + def transform(self, y): + """Transform labels to normalized encoding. + + Parameters + ---------- + y : array-like of shape [n_samples] + Target values. + + Returns + ------- + y : array-like of shape [n_samples] + """ + self._check_fitted() + + classes = np.unique(y) + _check_numpy_unicode_bug(classes) + if len(np.intersect1d(classes, self.classes_)) < len(classes): + diff = np.setdiff1d(classes, self.classes_) + raise ValueError("y contains new labels: %s" % str(diff)) + return np.searchsorted(self.classes_, y) + + def inverse_transform(self, y): + """Transform labels back to original encoding. + + Parameters + ---------- + y : numpy array of shape [n_samples] + Target values. + + Returns + ------- + y : numpy array of shape [n_samples] + """ + self._check_fitted() + + y = np.asarray(y) + return self.classes_[y] + + +class LabelBinarizer(BaseEstimator, TransformerMixin): + """Binarize labels in a one-vs-all fashion + + Several regression and binary classification algorithms are + available in the scikit. A simple way to extend these algorithms + to the multi-class classification case is to use the so-called + one-vs-all scheme. + + At learning time, this simply consists in learning one regressor + or binary classifier per class. In doing so, one needs to convert + multi-class labels to binary labels (belong or does not belong + to the class). LabelBinarizer makes this process easy with the + transform method. + + At prediction time, one assigns the class for which the corresponding + model gave the greatest confidence. LabelBinarizer makes this easy + with the inverse_transform method. + + Parameters + ---------- + + neg_label : int (default: 0) + Value with which negative labels must be encoded. + + pos_label : int (default: 1) + Value with which positive labels must be encoded. + + sparse_output : boolean (default: False) + True if the returned array from transform is desired to be in sparse + CSR format. + + Attributes + ---------- + classes_ : array of shape [n_class] + Holds the label for each class. + + y_type_ : str, + Represents the type of the target data as evaluated by + utils.multiclass.type_of_target. Possible type are 'continuous', + 'continuous-multioutput', 'binary', 'multiclass', + 'mutliclass-multioutput', 'multilabel-sequences', + 'multilabel-indicator', and 'unknown'. + + multilabel_ : boolean + True if the transformer was fitted on a multilabel rather than a + multiclass set of labels. The ``multilabel_`` attribute is deprecated + and will be removed in 0.18 + + sparse_input_ : boolean, + True if the input data to transform is given as a sparse matrix, False + otherwise. + + indicator_matrix_ : str + 'sparse' when the input data to tansform is a multilable-indicator and + is sparse, None otherwise. The ``indicator_matrix_`` attribute is + deprecated as of version 0.16 and will be removed in 0.18 + + + Examples + -------- + >>> from sklearn import preprocessing + >>> lb = preprocessing.LabelBinarizer() + >>> lb.fit([1, 2, 6, 4, 2]) + LabelBinarizer(neg_label=0, pos_label=1, sparse_output=False) + >>> lb.classes_ + array([1, 2, 4, 6]) + >>> lb.transform([1, 6]) + array([[1, 0, 0, 0], + [0, 0, 0, 1]]) + + Binary targets transform to a column vector + + >>> lb = preprocessing.LabelBinarizer() + >>> lb.fit_transform(['yes', 'no', 'no', 'yes']) + array([[1], + [0], + [0], + [1]]) + + Passing a 2D matrix for multilabel classification + + >>> import numpy as np + >>> lb.fit(np.array([[0, 1, 1], [1, 0, 0]])) + LabelBinarizer(neg_label=0, pos_label=1, sparse_output=False) + >>> lb.classes_ + array([0, 1, 2]) + >>> lb.transform([0, 1, 2, 1]) + array([[1, 0, 0], + [0, 1, 0], + [0, 0, 1], + [0, 1, 0]]) + + See also + -------- + label_binarize : function to perform the transform operation of + LabelBinarizer with fixed classes. + """ + + def __init__(self, neg_label=0, pos_label=1, sparse_output=False): + if neg_label >= pos_label: + raise ValueError("neg_label={0} must be strictly less than " + "pos_label={1}.".format(neg_label, pos_label)) + + if sparse_output and (pos_label == 0 or neg_label != 0): + raise ValueError("Sparse binarization is only supported with non " + "zero pos_label and zero neg_label, got " + "pos_label={0} and neg_label={1}" + "".format(pos_label, neg_label)) + + self.neg_label = neg_label + self.pos_label = pos_label + self.sparse_output = sparse_output + + @property + @deprecated("Attribute indicator_matrix_ is deprecated and will be " + "removed in 0.17. Use 'y_type_ == 'multilabel-indicator'' " + "instead") + def indicator_matrix_(self): + return self.y_type_ == 'multilabel-indicator' + + @property + @deprecated("Attribute multilabel_ is deprecated and will be removed " + "in 0.17. Use 'y_type_.startswith('multilabel')' " + "instead") + def multilabel_(self): + return self.y_type_.startswith('multilabel') + + def _check_fitted(self): + if not hasattr(self, "classes_"): + raise ValueError("LabelBinarizer was not fitted yet.") + + def fit(self, y): + """Fit label binarizer + + Parameters + ---------- + y : numpy array of shape (n_samples,) or (n_samples, n_classes) + Target values. The 2-d matrix should only contain 0 and 1, + represents multilabel classification. + + Returns + ------- + self : returns an instance of self. + """ + self.y_type_ = type_of_target(y) + if 'multioutput' in self.y_type_: + raise ValueError("Multioutput target data is not supported with " + "label binarization") + if _num_samples(y) == 0: + raise ValueError('y has 0 samples: %r' % y) + + self.sparse_input_ = sp.issparse(y) + self.classes_ = unique_labels(y) + return self + + def transform(self, y): + """Transform multi-class labels to binary labels + + The output of transform is sometimes referred to by some authors as the + 1-of-K coding scheme. + + Parameters + ---------- + y : numpy array or sparse matrix of shape (n_samples,) or + (n_samples, n_classes) Target values. The 2-d matrix should only + contain 0 and 1, represents multilabel classification. Sparse + matrix can be CSR, CSC, COO, DOK, or LIL. + + Returns + ------- + Y : numpy array or CSR matrix of shape [n_samples, n_classes] + Shape will be [n_samples, 1] for binary problems. + """ + self._check_fitted() + + y_is_multilabel = type_of_target(y).startswith('multilabel') + if y_is_multilabel and not self.y_type_.startswith('multilabel'): + raise ValueError("The object was not fitted with multilabel" + " input.") + + return label_binarize(y, self.classes_, + pos_label=self.pos_label, + neg_label=self.neg_label, + sparse_output=self.sparse_output) + + def inverse_transform(self, Y, threshold=None): + """Transform binary labels back to multi-class labels + + Parameters + ---------- + Y : numpy array or sparse matrix with shape [n_samples, n_classes] + Target values. All sparse matrices are converted to CSR before + inverse transformation. + + threshold : float or None + Threshold used in the binary and multi-label cases. + + Use 0 when: + - Y contains the output of decision_function (classifier) + Use 0.5 when: + - Y contains the output of predict_proba + + If None, the threshold is assumed to be half way between + neg_label and pos_label. + + Returns + ------- + y : numpy array or CSR matrix of shape [n_samples] Target values. + + Notes + ----- + In the case when the binary labels are fractional + (probabilistic), inverse_transform chooses the class with the + greatest value. Typically, this allows to use the output of a + linear model's decision_function method directly as the input + of inverse_transform. + """ + self._check_fitted() + + if threshold is None: + threshold = (self.pos_label + self.neg_label) / 2. + + if self.y_type_ == "multiclass": + y_inv = _inverse_binarize_multiclass(Y, self.classes_) + else: + y_inv = _inverse_binarize_thresholding(Y, self.y_type_, + self.classes_, threshold) + + if self.sparse_input_: + y_inv = sp.csr_matrix(y_inv) + elif sp.issparse(y_inv): + y_inv = y_inv.toarray() + + return y_inv + + +def label_binarize(y, classes, neg_label=0, pos_label=1, + sparse_output=False, multilabel=None): + """Binarize labels in a one-vs-all fashion + + Several regression and binary classification algorithms are + available in the scikit. A simple way to extend these algorithms + to the multi-class classification case is to use the so-called + one-vs-all scheme. + + This function makes it possible to compute this transformation for a + fixed set of class labels known ahead of time. + + Parameters + ---------- + y : array-like + Sequence of integer labels or multilabel data to encode. + + classes : array-like of shape [n_classes] + Uniquely holds the label for each class. + + neg_label : int (default: 0) + Value with which negative labels must be encoded. + + pos_label : int (default: 1) + Value with which positive labels must be encoded. + + sparse_output : boolean (default: False), + Set to true if output binary array is desired in CSR sparse format + + Returns + ------- + Y : numpy array or CSR matrix of shape [n_samples, n_classes] + Shape will be [n_samples, 1] for binary problems. + + Examples + -------- + >>> from sklearn.preprocessing import label_binarize + >>> label_binarize([1, 6], classes=[1, 2, 4, 6]) + array([[1, 0, 0, 0], + [0, 0, 0, 1]]) + + The class ordering is preserved: + + >>> label_binarize([1, 6], classes=[1, 6, 4, 2]) + array([[1, 0, 0, 0], + [0, 1, 0, 0]]) + + Binary targets transform to a column vector + + >>> label_binarize(['yes', 'no', 'no', 'yes'], classes=['no', 'yes']) + array([[1], + [0], + [0], + [1]]) + + See also + -------- + LabelBinarizer : class used to wrap the functionality of label_binarize and + allow for fitting to classes independently of the transform operation + """ + if not isinstance(y, list): + # XXX Workaround that will be removed when list of list format is + # dropped + y = check_array(y, accept_sparse='csr', ensure_2d=False, dtype=None) + else: + if _num_samples(y) == 0: + raise ValueError('y has 0 samples: %r' % y) + if neg_label >= pos_label: + raise ValueError("neg_label={0} must be strictly less than " + "pos_label={1}.".format(neg_label, pos_label)) + + if (sparse_output and (pos_label == 0 or neg_label != 0)): + raise ValueError("Sparse binarization is only supported with non " + "zero pos_label and zero neg_label, got " + "pos_label={0} and neg_label={1}" + "".format(pos_label, neg_label)) + + if multilabel is not None: + warnings.warn("The multilabel parameter is deprecated as of version " + "0.15 and will be removed in 0.17. The parameter is no " + "longer necessary because the value is automatically " + "inferred.", DeprecationWarning) + + # To account for pos_label == 0 in the dense case + pos_switch = pos_label == 0 + if pos_switch: + pos_label = -neg_label + + y_type = type_of_target(y) + if 'multioutput' in y_type: + raise ValueError("Multioutput target data is not supported with label " + "binarization") + + n_samples = y.shape[0] if sp.issparse(y) else len(y) + n_classes = len(classes) + classes = np.asarray(classes) + + if y_type == "binary": + if len(classes) == 1: + Y = np.zeros((len(y), 1), dtype=np.int) + Y += neg_label + return Y + elif len(classes) >= 3: + y_type = "multiclass" + + sorted_class = np.sort(classes) + if (y_type == "multilabel-indicator" and classes.size != y.shape[1]): + raise ValueError("classes {0} missmatch with the labels {1}" + "found in the data".format(classes, unique_labels(y))) + + if y_type in ("binary", "multiclass"): + y = column_or_1d(y) + + # pick out the known labels from y + y_in_classes = in1d(y, classes) + y_seen = y[y_in_classes] + indices = np.searchsorted(sorted_class, y_seen) + indptr = np.hstack((0, np.cumsum(y_in_classes))) + + data = np.empty_like(indices) + data.fill(pos_label) + Y = sp.csr_matrix((data, indices, indptr), + shape=(n_samples, n_classes)) + + elif y_type == "multilabel-indicator": + Y = sp.csr_matrix(y) + if pos_label != 1: + data = np.empty_like(Y.data) + data.fill(pos_label) + Y.data = data + + elif y_type == "multilabel-sequences": + Y = MultiLabelBinarizer(classes=classes, + sparse_output=sparse_output).fit_transform(y) + + if sp.issparse(Y): + Y.data[:] = pos_label + else: + Y[Y == 1] = pos_label + return Y + + if not sparse_output: + Y = Y.toarray() + Y = astype(Y, int, copy=False) + + if neg_label != 0: + Y[Y == 0] = neg_label + + if pos_switch: + Y[Y == pos_label] = 0 + else: + Y.data = astype(Y.data, int, copy=False) + + # preserve label ordering + if np.any(classes != sorted_class): + indices = np.argsort(classes) + Y = Y[:, indices] + + if y_type == "binary": + if sparse_output: + Y = Y.getcol(-1) + else: + Y = Y[:, -1].reshape((-1, 1)) + + return Y + + +def _inverse_binarize_multiclass(y, classes): + """Inverse label binarization transformation for multiclass. + + Multiclass uses the maximal score instead of a threshold. + """ + classes = np.asarray(classes) + + if sp.issparse(y): + # Find the argmax for each row in y where y is a CSR matrix + + y = y.tocsr() + n_samples, n_outputs = y.shape + outputs = np.arange(n_outputs) + row_max = sparse_min_max(y, 1)[1] + row_nnz = np.diff(y.indptr) + + y_data_repeated_max = np.repeat(row_max, row_nnz) + # picks out all indices obtaining the maximum per row + y_i_all_argmax = np.flatnonzero(y_data_repeated_max == y.data) + + # For corner case where last row has a max of 0 + if row_max[-1] == 0: + y_i_all_argmax = np.append(y_i_all_argmax, [len(y.data)]) + + # Gets the index of the first argmax in each row from y_i_all_argmax + index_first_argmax = np.searchsorted(y_i_all_argmax, y.indptr[:-1]) + # first argmax of each row + y_ind_ext = np.append(y.indices, [0]) + y_i_argmax = y_ind_ext[y_i_all_argmax[index_first_argmax]] + # Handle rows of all 0 + y_i_argmax[np.where(row_nnz == 0)[0]] = 0 + + # Handles rows with max of 0 that contain negative numbers + samples = np.arange(n_samples)[(row_nnz > 0) & + (row_max.ravel() == 0)] + for i in samples: + ind = y.indices[y.indptr[i]:y.indptr[i + 1]] + y_i_argmax[i] = classes[np.setdiff1d(outputs, ind)][0] + + return classes[y_i_argmax] + else: + return classes.take(y.argmax(axis=1), mode="clip") + + +def _inverse_binarize_thresholding(y, output_type, classes, threshold): + """Inverse label binarization transformation using thresholding.""" + + if output_type == "binary" and y.ndim == 2 and y.shape[1] > 2: + raise ValueError("output_type='binary', but y.shape = {0}". + format(y.shape)) + + if output_type != "binary" and y.shape[1] != len(classes): + raise ValueError("The number of class is not equal to the number of " + "dimension of y.") + + classes = np.asarray(classes) + + # Perform thresholding + if sp.issparse(y): + if threshold > 0: + if y.format not in ('csr', 'csc'): + y = y.tocsr() + y.data = np.array(y.data > threshold, dtype=np.int) + y.eliminate_zeros() + else: + y = np.array(y.toarray() > threshold, dtype=np.int) + else: + y = np.array(y > threshold, dtype=np.int) + + # Inverse transform data + if output_type == "binary": + if sp.issparse(y): + y = y.toarray() + if y.ndim == 2 and y.shape[1] == 2: + return classes[y[:, 1]] + else: + if len(classes) == 1: + y = np.empty(len(y), dtype=classes.dtype) + y.fill(classes[0]) + return y + else: + return classes[y.ravel()] + + elif output_type == "multilabel-indicator": + return y + + elif output_type == "multilabel-sequences": + warnings.warn('Direct support for sequence of sequences multilabel ' + 'representation will be unavailable from version 0.17. ' + 'Use sklearn.preprocessing.MultiLabelBinarizer to ' + 'convert to a label indicator representation.', + DeprecationWarning) + mlb = MultiLabelBinarizer(classes=classes).fit([]) + return mlb.inverse_transform(y) + + else: + raise ValueError("{0} format is not supported".format(output_type)) + + +class MultiLabelBinarizer(BaseEstimator, TransformerMixin): + """Transform between iterable of iterables and a multilabel format + + Although a list of sets or tuples is a very intuitive format for multilabel + data, it is unwieldy to process. This transformer converts between this + intuitive format and the supported multilabel format: a (samples x classes) + binary matrix indicating the presence of a class label. + + Parameters + ---------- + classes : array-like of shape [n_classes] (optional) + Indicates an ordering for the class labels + + sparse_output : boolean (default: False), + Set to true if output binary array is desired in CSR sparse format + + Attributes + ---------- + classes_ : array of labels + A copy of the `classes` parameter where provided, + or otherwise, the sorted set of classes found when fitting. + + Examples + -------- + >>> mlb = MultiLabelBinarizer() + >>> mlb.fit_transform([(1, 2), (3,)]) + array([[1, 1, 0], + [0, 0, 1]]) + >>> mlb.classes_ + array([1, 2, 3]) + + >>> mlb.fit_transform([set(['sci-fi', 'thriller']), set(['comedy'])]) + array([[0, 1, 1], + [1, 0, 0]]) + >>> list(mlb.classes_) + ['comedy', 'sci-fi', 'thriller'] + + """ + def __init__(self, classes=None, sparse_output=False): + self.classes = classes + self.sparse_output = sparse_output + + def fit(self, y): + """Fit the label sets binarizer, storing `classes_` + + Parameters + ---------- + y : iterable of iterables + A set of labels (any orderable and hashable object) for each + sample. If the `classes` parameter is set, `y` will not be + iterated. + + Returns + ------- + self : returns this MultiLabelBinarizer instance + """ + if self.classes is None: + classes = sorted(set(itertools.chain.from_iterable(y))) + else: + classes = self.classes + dtype = np.int if all(isinstance(c, int) for c in classes) else object + self.classes_ = np.empty(len(classes), dtype=dtype) + self.classes_[:] = classes + return self + + def fit_transform(self, y): + """Fit the label sets binarizer and transform the given label sets + + Parameters + ---------- + y : iterable of iterables + A set of labels (any orderable and hashable object) for each + sample. If the `classes` parameter is set, `y` will not be + iterated. + + Returns + ------- + y_indicator : array or CSR matrix, shape (n_samples, n_classes) + A matrix such that `y_indicator[i, j] = 1` iff `classes_[j]` is in + `y[i]`, and 0 otherwise. + """ + if self.classes is not None: + return self.fit(y).transform(y) + + # Automatically increment on new class + class_mapping = defaultdict(int) + class_mapping.default_factory = class_mapping.__len__ + yt = self._transform(y, class_mapping) + + # sort classes and reorder columns + tmp = sorted(class_mapping, key=class_mapping.get) + + # (make safe for tuples) + dtype = np.int if all(isinstance(c, int) for c in tmp) else object + class_mapping = np.empty(len(tmp), dtype=dtype) + class_mapping[:] = tmp + self.classes_, inverse = np.unique(class_mapping, return_inverse=True) + yt.indices = np.take(inverse, yt.indices) + + if not self.sparse_output: + yt = yt.toarray() + + return yt + + def transform(self, y): + """Transform the given label sets + + Parameters + ---------- + y : iterable of iterables + A set of labels (any orderable and hashable object) for each + sample. If the `classes` parameter is set, `y` will not be + iterated. + + Returns + ------- + y_indicator : array or CSR matrix, shape (n_samples, n_classes) + A matrix such that `y_indicator[i, j] = 1` iff `classes_[j]` is in + `y[i]`, and 0 otherwise. + """ + class_to_index = dict(zip(self.classes_, range(len(self.classes_)))) + yt = self._transform(y, class_to_index) + + if not self.sparse_output: + yt = yt.toarray() + + return yt + + def _transform(self, y, class_mapping): + """Transforms the label sets with a given mapping + + Parameters + ---------- + y : iterable of iterables + class_mapping : Mapping + Maps from label to column index in label indicator matrix + + Returns + ------- + y_indicator : sparse CSR matrix, shape (n_samples, n_classes) + Label indicator matrix + """ + indices = array.array('i') + indptr = array.array('i', [0]) + for labels in y: + indices.extend(set(class_mapping[label] for label in labels)) + indptr.append(len(indices)) + data = np.ones(len(indices), dtype=int) + + return sp.csr_matrix((data, indices, indptr), + shape=(len(indptr) - 1, len(class_mapping))) + + def inverse_transform(self, yt): + """Transform the given indicator matrix into label sets + + Parameters + ---------- + yt : array or sparse matrix of shape (n_samples, n_classes) + A matrix containing only 1s ands 0s. + + Returns + ------- + y : list of tuples + The set of labels for each sample such that `y[i]` consists of + `classes_[j]` for each `yt[i, j] == 1`. + """ + if yt.shape[1] != len(self.classes_): + raise ValueError('Expected indicator for {0} classes, but got {1}' + .format(len(self.classes_), yt.shape[1])) + + if sp.issparse(yt): + yt = yt.tocsr() + if len(yt.data) != 0 and len(np.setdiff1d(yt.data, [0, 1])) > 0: + raise ValueError('Expected only 0s and 1s in label indicator.') + return [tuple(self.classes_.take(yt.indices[start:end])) + for start, end in zip(yt.indptr[:-1], yt.indptr[1:])] + else: + unexpected = np.setdiff1d(yt, [0, 1]) + if len(unexpected) > 0: + raise ValueError('Expected only 0s and 1s in label indicator. ' + 'Also got {0}'.format(unexpected)) + return [tuple(self.classes_.compress(indicators)) for indicators + in yt] diff --git a/sklearn/preprocessing/tests/__init__.py b/sklearn/preprocessing/tests/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sklearn/preprocessing/tests/test_data.py b/sklearn/preprocessing/tests/test_data.py new file mode 100644 index 0000000000000..bdd441057b46a --- /dev/null +++ b/sklearn/preprocessing/tests/test_data.py @@ -0,0 +1,839 @@ +import warnings +import numpy as np +import numpy.linalg as la +from scipy import sparse + +from sklearn.utils.testing import assert_almost_equal, clean_warning_registry +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_greater_equal +from sklearn.utils.testing import assert_less_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_raises_regex +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_warns_message + +from sklearn.utils.sparsefuncs import mean_variance_axis +from sklearn.preprocessing.data import _transform_selected +from sklearn.preprocessing.data import Binarizer +from sklearn.preprocessing.data import KernelCenterer +from sklearn.preprocessing.data import Normalizer +from sklearn.preprocessing.data import normalize +from sklearn.preprocessing.data import OneHotEncoder +from sklearn.preprocessing.data import StandardScaler +from sklearn.preprocessing.data import scale +from sklearn.preprocessing.data import MinMaxScaler +from sklearn.preprocessing.data import add_dummy_feature +from sklearn.preprocessing.data import PolynomialFeatures + +from sklearn import datasets + +iris = datasets.load_iris() + + +def toarray(a): + if hasattr(a, "toarray"): + a = a.toarray() + return a + + +def test_polynomial_features(): + """Test Polynomial Features""" + X1 = np.arange(6)[:, np.newaxis] + P1 = np.hstack([np.ones_like(X1), + X1, X1 ** 2, X1 ** 3]) + deg1 = 3 + + X2 = np.arange(6).reshape((3, 2)) + x1 = X2[:, :1] + x2 = X2[:, 1:] + P2 = np.hstack([x1 ** 0 * x2 ** 0, + x1 ** 1 * x2 ** 0, + x1 ** 0 * x2 ** 1, + x1 ** 2 * x2 ** 0, + x1 ** 1 * x2 ** 1, + x1 ** 0 * x2 ** 2]) + deg2 = 2 + + for (deg, X, P) in [(deg1, X1, P1), (deg2, X2, P2)]: + P_test = PolynomialFeatures(deg, include_bias=True).fit_transform(X) + assert_array_almost_equal(P_test, P) + + P_test = PolynomialFeatures(deg, include_bias=False).fit_transform(X) + assert_array_almost_equal(P_test, P[:, 1:]) + + interact = PolynomialFeatures(2, interaction_only=True, include_bias=True) + X_poly = interact.fit_transform(X) + assert_array_almost_equal(X_poly, P2[:, [0, 1, 2, 4]]) + + assert_raises(ValueError, interact.transform, X[:, 1:]) + + +def test_scaler_1d(): + """Test scaling of dataset along single axis""" + rng = np.random.RandomState(0) + X = rng.randn(5) + X_orig_copy = X.copy() + + scaler = StandardScaler() + X_scaled = scaler.fit(X).transform(X, copy=False) + assert_array_almost_equal(X_scaled.mean(axis=0), 0.0) + assert_array_almost_equal(X_scaled.std(axis=0), 1.0) + + # check inverse transform + X_scaled_back = scaler.inverse_transform(X_scaled) + assert_array_almost_equal(X_scaled_back, X_orig_copy) + + # Test with 1D list + X = [0., 1., 2, 0.4, 1.] + scaler = StandardScaler() + X_scaled = scaler.fit(X).transform(X, copy=False) + assert_array_almost_equal(X_scaled.mean(axis=0), 0.0) + assert_array_almost_equal(X_scaled.std(axis=0), 1.0) + + X_scaled = scale(X) + assert_array_almost_equal(X_scaled.mean(axis=0), 0.0) + assert_array_almost_equal(X_scaled.std(axis=0), 1.0) + + X = np.ones(5) + assert_array_equal(scale(X, with_mean=False), X) + + +def test_scaler_2d_arrays(): + """Test scaling of 2d array along first axis""" + rng = np.random.RandomState(0) + X = rng.randn(4, 5) + X[:, 0] = 0.0 # first feature is always of zero + + scaler = StandardScaler() + X_scaled = scaler.fit(X).transform(X, copy=True) + assert_false(np.any(np.isnan(X_scaled))) + + assert_array_almost_equal(X_scaled.mean(axis=0), 5 * [0.0]) + assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) + # Check that X has been copied + assert_true(X_scaled is not X) + + # check inverse transform + X_scaled_back = scaler.inverse_transform(X_scaled) + assert_true(X_scaled_back is not X) + assert_true(X_scaled_back is not X_scaled) + assert_array_almost_equal(X_scaled_back, X) + + X_scaled = scale(X, axis=1, with_std=False) + assert_false(np.any(np.isnan(X_scaled))) + assert_array_almost_equal(X_scaled.mean(axis=1), 4 * [0.0]) + X_scaled = scale(X, axis=1, with_std=True) + assert_false(np.any(np.isnan(X_scaled))) + assert_array_almost_equal(X_scaled.mean(axis=1), 4 * [0.0]) + assert_array_almost_equal(X_scaled.std(axis=1), 4 * [1.0]) + # Check that the data hasn't been modified + assert_true(X_scaled is not X) + + X_scaled = scaler.fit(X).transform(X, copy=False) + assert_false(np.any(np.isnan(X_scaled))) + assert_array_almost_equal(X_scaled.mean(axis=0), 5 * [0.0]) + assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) + # Check that X has not been copied + assert_true(X_scaled is X) + + X = rng.randn(4, 5) + X[:, 0] = 1.0 # first feature is a constant, non zero feature + scaler = StandardScaler() + X_scaled = scaler.fit(X).transform(X, copy=True) + assert_false(np.any(np.isnan(X_scaled))) + assert_array_almost_equal(X_scaled.mean(axis=0), 5 * [0.0]) + assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) + # Check that X has not been copied + assert_true(X_scaled is not X) + + +def test_min_max_scaler_iris(): + X = iris.data + scaler = MinMaxScaler() + # default params + X_trans = scaler.fit_transform(X) + assert_array_almost_equal(X_trans.min(axis=0), 0) + assert_array_almost_equal(X_trans.min(axis=0), 0) + assert_array_almost_equal(X_trans.max(axis=0), 1) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + + # not default params: min=1, max=2 + scaler = MinMaxScaler(feature_range=(1, 2)) + X_trans = scaler.fit_transform(X) + assert_array_almost_equal(X_trans.min(axis=0), 1) + assert_array_almost_equal(X_trans.max(axis=0), 2) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + + # min=-.5, max=.6 + scaler = MinMaxScaler(feature_range=(-.5, .6)) + X_trans = scaler.fit_transform(X) + assert_array_almost_equal(X_trans.min(axis=0), -.5) + assert_array_almost_equal(X_trans.max(axis=0), .6) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + + # raises on invalid range + scaler = MinMaxScaler(feature_range=(2, 1)) + assert_raises(ValueError, scaler.fit, X) + + +def test_min_max_scaler_zero_variance_features(): + """Check min max scaler on toy data with zero variance features""" + X = [[0., 1., +0.5], + [0., 1., -0.1], + [0., 1., +1.1]] + + X_new = [[+0., 2., 0.5], + [-1., 1., 0.0], + [+0., 1., 1.5]] + + # default params + scaler = MinMaxScaler() + X_trans = scaler.fit_transform(X) + X_expected_0_1 = [[0., 0., 0.5], + [0., 0., 0.0], + [0., 0., 1.0]] + assert_array_almost_equal(X_trans, X_expected_0_1) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + + X_trans_new = scaler.transform(X_new) + X_expected_0_1_new = [[+0., 1., 0.500], + [-1., 0., 0.083], + [+0., 0., 1.333]] + assert_array_almost_equal(X_trans_new, X_expected_0_1_new, decimal=2) + + # not default params + scaler = MinMaxScaler(feature_range=(1, 2)) + X_trans = scaler.fit_transform(X) + X_expected_1_2 = [[1., 1., 1.5], + [1., 1., 1.0], + [1., 1., 2.0]] + assert_array_almost_equal(X_trans, X_expected_1_2) + + +def test_min_max_scaler_1d(): + """Test scaling of dataset along single axis""" + rng = np.random.RandomState(0) + X = rng.randn(5) + X_orig_copy = X.copy() + + scaler = MinMaxScaler() + X_scaled = scaler.fit(X).transform(X) + assert_array_almost_equal(X_scaled.min(axis=0), 0.0) + assert_array_almost_equal(X_scaled.max(axis=0), 1.0) + + # check inverse transform + X_scaled_back = scaler.inverse_transform(X_scaled) + assert_array_almost_equal(X_scaled_back, X_orig_copy) + + # Test with 1D list + X = [0., 1., 2, 0.4, 1.] + scaler = MinMaxScaler() + X_scaled = scaler.fit(X).transform(X) + assert_array_almost_equal(X_scaled.min(axis=0), 0.0) + assert_array_almost_equal(X_scaled.max(axis=0), 1.0) + + # Constant feature. + X = np.zeros(5) + scaler = MinMaxScaler() + X_scaled = scaler.fit(X).transform(X) + assert_greater_equal(X_scaled.min(), 0.) + assert_less_equal(X_scaled.max(), 1.) + + +def test_scaler_without_centering(): + rng = np.random.RandomState(42) + X = rng.randn(4, 5) + X[:, 0] = 0.0 # first feature is always of zero + X_csr = sparse.csr_matrix(X) + X_csc = sparse.csc_matrix(X) + + assert_raises(ValueError, StandardScaler().fit, X_csr) + + null_transform = StandardScaler(with_mean=False, with_std=False, copy=True) + X_null = null_transform.fit_transform(X_csr) + assert_array_equal(X_null.data, X_csr.data) + X_orig = null_transform.inverse_transform(X_null) + assert_array_equal(X_orig.data, X_csr.data) + + scaler = StandardScaler(with_mean=False).fit(X) + X_scaled = scaler.transform(X, copy=True) + assert_false(np.any(np.isnan(X_scaled))) + + scaler_csr = StandardScaler(with_mean=False).fit(X_csr) + X_csr_scaled = scaler_csr.transform(X_csr, copy=True) + assert_false(np.any(np.isnan(X_csr_scaled.data))) + + scaler_csc = StandardScaler(with_mean=False).fit(X_csc) + X_csc_scaled = scaler_csr.transform(X_csc, copy=True) + assert_false(np.any(np.isnan(X_csc_scaled.data))) + + assert_equal(scaler.mean_, scaler_csr.mean_) + assert_array_almost_equal(scaler.std_, scaler_csr.std_) + + assert_equal(scaler.mean_, scaler_csc.mean_) + assert_array_almost_equal(scaler.std_, scaler_csc.std_) + + assert_array_almost_equal( + X_scaled.mean(axis=0), [0., -0.01, 2.24, -0.35, -0.78], 2) + assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) + + X_csr_scaled_mean, X_csr_scaled_std = mean_variance_axis(X_csr_scaled, 0) + assert_array_almost_equal(X_csr_scaled_mean, X_scaled.mean(axis=0)) + assert_array_almost_equal(X_csr_scaled_std, X_scaled.std(axis=0)) + + # Check that X has not been modified (copy) + assert_true(X_scaled is not X) + assert_true(X_csr_scaled is not X_csr) + + X_scaled_back = scaler.inverse_transform(X_scaled) + assert_true(X_scaled_back is not X) + assert_true(X_scaled_back is not X_scaled) + assert_array_almost_equal(X_scaled_back, X) + + X_csr_scaled_back = scaler_csr.inverse_transform(X_csr_scaled) + assert_true(X_csr_scaled_back is not X_csr) + assert_true(X_csr_scaled_back is not X_csr_scaled) + assert_array_almost_equal(X_csr_scaled_back.toarray(), X) + + X_csc_scaled_back = scaler_csr.inverse_transform(X_csc_scaled.tocsc()) + assert_true(X_csc_scaled_back is not X_csc) + assert_true(X_csc_scaled_back is not X_csc_scaled) + assert_array_almost_equal(X_csc_scaled_back.toarray(), X) + + +def test_scaler_int(): + # test that scaler converts integer input to floating + # for both sparse and dense matrices + rng = np.random.RandomState(42) + X = rng.randint(20, size=(4, 5)) + X[:, 0] = 0 # first feature is always of zero + X_csr = sparse.csr_matrix(X) + X_csc = sparse.csc_matrix(X) + + null_transform = StandardScaler(with_mean=False, with_std=False, copy=True) + clean_warning_registry() + with warnings.catch_warnings(record=True): + X_null = null_transform.fit_transform(X_csr) + assert_array_equal(X_null.data, X_csr.data) + X_orig = null_transform.inverse_transform(X_null) + assert_array_equal(X_orig.data, X_csr.data) + + clean_warning_registry() + with warnings.catch_warnings(record=True): + scaler = StandardScaler(with_mean=False).fit(X) + X_scaled = scaler.transform(X, copy=True) + assert_false(np.any(np.isnan(X_scaled))) + + clean_warning_registry() + with warnings.catch_warnings(record=True): + scaler_csr = StandardScaler(with_mean=False).fit(X_csr) + X_csr_scaled = scaler_csr.transform(X_csr, copy=True) + assert_false(np.any(np.isnan(X_csr_scaled.data))) + + clean_warning_registry() + with warnings.catch_warnings(record=True): + scaler_csc = StandardScaler(with_mean=False).fit(X_csc) + X_csc_scaled = scaler_csr.transform(X_csc, copy=True) + assert_false(np.any(np.isnan(X_csc_scaled.data))) + + assert_equal(scaler.mean_, scaler_csr.mean_) + assert_array_almost_equal(scaler.std_, scaler_csr.std_) + + assert_equal(scaler.mean_, scaler_csc.mean_) + assert_array_almost_equal(scaler.std_, scaler_csc.std_) + + assert_array_almost_equal( + X_scaled.mean(axis=0), + [0., 1.109, 1.856, 21., 1.559], 2) + assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) + + X_csr_scaled_mean, X_csr_scaled_std = mean_variance_axis( + X_csr_scaled.astype(np.float), 0) + assert_array_almost_equal(X_csr_scaled_mean, X_scaled.mean(axis=0)) + assert_array_almost_equal(X_csr_scaled_std, X_scaled.std(axis=0)) + + # Check that X has not been modified (copy) + assert_true(X_scaled is not X) + assert_true(X_csr_scaled is not X_csr) + + X_scaled_back = scaler.inverse_transform(X_scaled) + assert_true(X_scaled_back is not X) + assert_true(X_scaled_back is not X_scaled) + assert_array_almost_equal(X_scaled_back, X) + + X_csr_scaled_back = scaler_csr.inverse_transform(X_csr_scaled) + assert_true(X_csr_scaled_back is not X_csr) + assert_true(X_csr_scaled_back is not X_csr_scaled) + assert_array_almost_equal(X_csr_scaled_back.toarray(), X) + + X_csc_scaled_back = scaler_csr.inverse_transform(X_csc_scaled.tocsc()) + assert_true(X_csc_scaled_back is not X_csc) + assert_true(X_csc_scaled_back is not X_csc_scaled) + assert_array_almost_equal(X_csc_scaled_back.toarray(), X) + + +def test_scaler_without_copy(): + """Check that StandardScaler.fit does not change input""" + rng = np.random.RandomState(42) + X = rng.randn(4, 5) + X[:, 0] = 0.0 # first feature is always of zero + X_csr = sparse.csr_matrix(X) + + X_copy = X.copy() + StandardScaler(copy=False).fit(X) + assert_array_equal(X, X_copy) + + X_csr_copy = X_csr.copy() + StandardScaler(with_mean=False, copy=False).fit(X_csr) + assert_array_equal(X_csr.toarray(), X_csr_copy.toarray()) + + +def test_scale_sparse_with_mean_raise_exception(): + rng = np.random.RandomState(42) + X = rng.randn(4, 5) + X_csr = sparse.csr_matrix(X) + + # check scaling and fit with direct calls on sparse data + assert_raises(ValueError, scale, X_csr, with_mean=True) + assert_raises(ValueError, StandardScaler(with_mean=True).fit, X_csr) + + # check transform and inverse_transform after a fit on a dense array + scaler = StandardScaler(with_mean=True).fit(X) + assert_raises(ValueError, scaler.transform, X_csr) + + X_transformed_csr = sparse.csr_matrix(scaler.transform(X)) + assert_raises(ValueError, scaler.inverse_transform, X_transformed_csr) + + +def test_scale_input_finiteness_validation(): + """Check if non finite inputs raise ValueError""" + X = [np.nan, 5, 6, 7, 8] + assert_raises_regex(ValueError, + "Input contains NaN, infinity or a value too large", + scale, X) + + X = [np.inf, 5, 6, 7, 8] + assert_raises_regex(ValueError, + "Input contains NaN, infinity or a value too large", + scale, X) + + +def test_scale_function_without_centering(): + rng = np.random.RandomState(42) + X = rng.randn(4, 5) + X[:, 0] = 0.0 # first feature is always of zero + X_csr = sparse.csr_matrix(X) + + X_scaled = scale(X, with_mean=False) + assert_false(np.any(np.isnan(X_scaled))) + + X_csr_scaled = scale(X_csr, with_mean=False) + assert_false(np.any(np.isnan(X_csr_scaled.data))) + + # test csc has same outcome + X_csc_scaled = scale(X_csr.tocsc(), with_mean=False) + assert_array_almost_equal(X_scaled, X_csc_scaled.toarray()) + + # raises value error on axis != 0 + assert_raises(ValueError, scale, X_csr, with_mean=False, axis=1) + + assert_array_almost_equal(X_scaled.mean(axis=0), + [0., -0.01, 2.24, -0.35, -0.78], 2) + assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) + # Check that X has not been copied + assert_true(X_scaled is not X) + + X_csr_scaled_mean, X_csr_scaled_std = mean_variance_axis(X_csr_scaled, 0) + assert_array_almost_equal(X_csr_scaled_mean, X_scaled.mean(axis=0)) + assert_array_almost_equal(X_csr_scaled_std, X_scaled.std(axis=0)) + + +def test_warning_scaling_integers(): + """Check warning when scaling integer data""" + X = np.array([[1, 2, 0], + [0, 0, 0]], dtype=np.uint8) + + w = "assumes floating point values as input, got uint8" + + clean_warning_registry() + assert_warns_message(UserWarning, w, scale, X) + assert_warns_message(UserWarning, w, StandardScaler().fit, X) + assert_warns_message(UserWarning, w, MinMaxScaler().fit, X) + + +def test_normalizer_l1(): + rng = np.random.RandomState(0) + X_dense = rng.randn(4, 5) + X_sparse_unpruned = sparse.csr_matrix(X_dense) + + # set the row number 3 to zero + X_dense[3, :] = 0.0 + + # set the row number 3 to zero without pruning (can happen in real life) + indptr_3 = X_sparse_unpruned.indptr[3] + indptr_4 = X_sparse_unpruned.indptr[4] + X_sparse_unpruned.data[indptr_3:indptr_4] = 0.0 + + # build the pruned variant using the regular constructor + X_sparse_pruned = sparse.csr_matrix(X_dense) + + # check inputs that support the no-copy optim + for X in (X_dense, X_sparse_pruned, X_sparse_unpruned): + + normalizer = Normalizer(norm='l1', copy=True) + X_norm = normalizer.transform(X) + assert_true(X_norm is not X) + X_norm1 = toarray(X_norm) + + normalizer = Normalizer(norm='l1', copy=False) + X_norm = normalizer.transform(X) + assert_true(X_norm is X) + X_norm2 = toarray(X_norm) + + for X_norm in (X_norm1, X_norm2): + row_sums = np.abs(X_norm).sum(axis=1) + for i in range(3): + assert_almost_equal(row_sums[i], 1.0) + assert_almost_equal(row_sums[3], 0.0) + + # check input for which copy=False won't prevent a copy + for init in (sparse.coo_matrix, sparse.csc_matrix, sparse.lil_matrix): + X = init(X_dense) + X_norm = normalizer = Normalizer(norm='l2', copy=False).transform(X) + + assert_true(X_norm is not X) + assert_true(isinstance(X_norm, sparse.csr_matrix)) + + X_norm = toarray(X_norm) + for i in range(3): + assert_almost_equal(row_sums[i], 1.0) + assert_almost_equal(la.norm(X_norm[3]), 0.0) + + +def test_normalizer_l2(): + rng = np.random.RandomState(0) + X_dense = rng.randn(4, 5) + X_sparse_unpruned = sparse.csr_matrix(X_dense) + + # set the row number 3 to zero + X_dense[3, :] = 0.0 + + # set the row number 3 to zero without pruning (can happen in real life) + indptr_3 = X_sparse_unpruned.indptr[3] + indptr_4 = X_sparse_unpruned.indptr[4] + X_sparse_unpruned.data[indptr_3:indptr_4] = 0.0 + + # build the pruned variant using the regular constructor + X_sparse_pruned = sparse.csr_matrix(X_dense) + + # check inputs that support the no-copy optim + for X in (X_dense, X_sparse_pruned, X_sparse_unpruned): + + normalizer = Normalizer(norm='l2', copy=True) + X_norm1 = normalizer.transform(X) + assert_true(X_norm1 is not X) + X_norm1 = toarray(X_norm1) + + normalizer = Normalizer(norm='l2', copy=False) + X_norm2 = normalizer.transform(X) + assert_true(X_norm2 is X) + X_norm2 = toarray(X_norm2) + + for X_norm in (X_norm1, X_norm2): + for i in range(3): + assert_almost_equal(la.norm(X_norm[i]), 1.0) + assert_almost_equal(la.norm(X_norm[3]), 0.0) + + # check input for which copy=False won't prevent a copy + for init in (sparse.coo_matrix, sparse.csc_matrix, sparse.lil_matrix): + X = init(X_dense) + X_norm = normalizer = Normalizer(norm='l2', copy=False).transform(X) + + assert_true(X_norm is not X) + assert_true(isinstance(X_norm, sparse.csr_matrix)) + + X_norm = toarray(X_norm) + for i in range(3): + assert_almost_equal(la.norm(X_norm[i]), 1.0) + assert_almost_equal(la.norm(X_norm[3]), 0.0) + + +def test_normalize(): + """Test normalize function""" + # Only tests functionality not used by the tests for Normalizer. + X = np.random.RandomState(37).randn(3, 2) + assert_array_equal(normalize(X, copy=False), + normalize(X.T, axis=0, copy=False).T) + assert_raises(ValueError, normalize, [[0]], axis=2) + assert_raises(ValueError, normalize, [[0]], norm='l3') + + +def test_binarizer(): + X_ = np.array([[1, 0, 5], [2, 3, -1]]) + + for init in (np.array, list, sparse.csr_matrix, sparse.csc_matrix): + + X = init(X_.copy()) + + binarizer = Binarizer(threshold=2.0, copy=True) + X_bin = toarray(binarizer.transform(X)) + assert_equal(np.sum(X_bin == 0), 4) + assert_equal(np.sum(X_bin == 1), 2) + X_bin = binarizer.transform(X) + assert_equal(sparse.issparse(X), sparse.issparse(X_bin)) + + binarizer = Binarizer(copy=True).fit(X) + X_bin = toarray(binarizer.transform(X)) + assert_true(X_bin is not X) + assert_equal(np.sum(X_bin == 0), 2) + assert_equal(np.sum(X_bin == 1), 4) + + binarizer = Binarizer(copy=True) + X_bin = binarizer.transform(X) + assert_true(X_bin is not X) + X_bin = toarray(X_bin) + assert_equal(np.sum(X_bin == 0), 2) + assert_equal(np.sum(X_bin == 1), 4) + + binarizer = Binarizer(copy=False) + X_bin = binarizer.transform(X) + if init is not list: + assert_true(X_bin is X) + X_bin = toarray(X_bin) + assert_equal(np.sum(X_bin == 0), 2) + assert_equal(np.sum(X_bin == 1), 4) + + binarizer = Binarizer(threshold=-0.5, copy=True) + for init in (np.array, list): + X = init(X_.copy()) + + X_bin = toarray(binarizer.transform(X)) + assert_equal(np.sum(X_bin == 0), 1) + assert_equal(np.sum(X_bin == 1), 5) + X_bin = binarizer.transform(X) + + # Cannot use threshold < 0 for sparse + assert_raises(ValueError, binarizer.transform, sparse.csc_matrix(X)) + + +def test_center_kernel(): + """Test that KernelCenterer is equivalent to StandardScaler + in feature space""" + rng = np.random.RandomState(0) + X_fit = rng.random_sample((5, 4)) + scaler = StandardScaler(with_std=False) + scaler.fit(X_fit) + X_fit_centered = scaler.transform(X_fit) + K_fit = np.dot(X_fit, X_fit.T) + + # center fit time matrix + centerer = KernelCenterer() + K_fit_centered = np.dot(X_fit_centered, X_fit_centered.T) + K_fit_centered2 = centerer.fit_transform(K_fit) + assert_array_almost_equal(K_fit_centered, K_fit_centered2) + + # center predict time matrix + X_pred = rng.random_sample((2, 4)) + K_pred = np.dot(X_pred, X_fit.T) + X_pred_centered = scaler.transform(X_pred) + K_pred_centered = np.dot(X_pred_centered, X_fit_centered.T) + K_pred_centered2 = centerer.transform(K_pred) + assert_array_almost_equal(K_pred_centered, K_pred_centered2) + + +def test_fit_transform(): + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + for obj in ((StandardScaler(), Normalizer(), Binarizer())): + X_transformed = obj.fit(X).transform(X) + X_transformed2 = obj.fit_transform(X) + assert_array_equal(X_transformed, X_transformed2) + + +def test_add_dummy_feature(): + X = [[1, 0], [0, 1], [0, 1]] + X = add_dummy_feature(X) + assert_array_equal(X, [[1, 1, 0], [1, 0, 1], [1, 0, 1]]) + + +def test_add_dummy_feature_coo(): + X = sparse.coo_matrix([[1, 0], [0, 1], [0, 1]]) + X = add_dummy_feature(X) + assert_true(sparse.isspmatrix_coo(X), X) + assert_array_equal(X.toarray(), [[1, 1, 0], [1, 0, 1], [1, 0, 1]]) + + +def test_add_dummy_feature_csc(): + X = sparse.csc_matrix([[1, 0], [0, 1], [0, 1]]) + X = add_dummy_feature(X) + assert_true(sparse.isspmatrix_csc(X), X) + assert_array_equal(X.toarray(), [[1, 1, 0], [1, 0, 1], [1, 0, 1]]) + + +def test_add_dummy_feature_csr(): + X = sparse.csr_matrix([[1, 0], [0, 1], [0, 1]]) + X = add_dummy_feature(X) + assert_true(sparse.isspmatrix_csr(X), X) + assert_array_equal(X.toarray(), [[1, 1, 0], [1, 0, 1], [1, 0, 1]]) + + +def test_one_hot_encoder_sparse(): + """Test OneHotEncoder's fit and transform.""" + X = [[3, 2, 1], [0, 1, 1]] + enc = OneHotEncoder() + # discover max values automatically + X_trans = enc.fit_transform(X).toarray() + assert_equal(X_trans.shape, (2, 5)) + assert_array_equal(enc.active_features_, + np.where([1, 0, 0, 1, 0, 1, 1, 0, 1])[0]) + assert_array_equal(enc.feature_indices_, [0, 4, 7, 9]) + + # check outcome + assert_array_equal(X_trans, + [[0., 1., 0., 1., 1.], + [1., 0., 1., 0., 1.]]) + + # max value given as 3 + enc = OneHotEncoder(n_values=4) + X_trans = enc.fit_transform(X) + assert_equal(X_trans.shape, (2, 4 * 3)) + assert_array_equal(enc.feature_indices_, [0, 4, 8, 12]) + + # max value given per feature + enc = OneHotEncoder(n_values=[3, 2, 2]) + X = [[1, 0, 1], [0, 1, 1]] + X_trans = enc.fit_transform(X) + assert_equal(X_trans.shape, (2, 3 + 2 + 2)) + assert_array_equal(enc.n_values_, [3, 2, 2]) + # check that testing with larger feature works: + X = np.array([[2, 0, 1], [0, 1, 1]]) + enc.transform(X) + + # test that an error is raised when out of bounds: + X_too_large = [[0, 2, 1], [0, 1, 1]] + assert_raises(ValueError, enc.transform, X_too_large) + assert_raises(ValueError, OneHotEncoder(n_values=2).fit_transform, X) + + # test that error is raised when wrong number of features + assert_raises(ValueError, enc.transform, X[:, :-1]) + # test that error is raised when wrong number of features in fit + # with prespecified n_values + assert_raises(ValueError, enc.fit, X[:, :-1]) + # test exception on wrong init param + assert_raises(TypeError, OneHotEncoder(n_values=np.int).fit, X) + + enc = OneHotEncoder() + # test negative input to fit + assert_raises(ValueError, enc.fit, [[0], [-1]]) + + # test negative input to transform + enc.fit([[0], [1]]) + assert_raises(ValueError, enc.transform, [[0], [-1]]) + +def test_one_hot_encoder_dense(): + """check for sparse=False""" + X = [[3, 2, 1], [0, 1, 1]] + enc = OneHotEncoder(sparse=False) + # discover max values automatically + X_trans = enc.fit_transform(X) + assert_equal(X_trans.shape, (2, 5)) + assert_array_equal(enc.active_features_, + np.where([1, 0, 0, 1, 0, 1, 1, 0, 1])[0]) + assert_array_equal(enc.feature_indices_, [0, 4, 7, 9]) + + # check outcome + assert_array_equal(X_trans, + np.array([[0., 1., 0., 1., 1.], + [1., 0., 1., 0., 1.]])) + + +def _check_transform_selected(X, X_expected, sel): + for M in (X, sparse.csr_matrix(X)): + Xtr = _transform_selected(M, Binarizer().transform, sel) + assert_array_equal(toarray(Xtr), X_expected) + + +def test_transform_selected(): + X = [[3, 2, 1], [0, 1, 1]] + + X_expected = [[1, 2, 1], [0, 1, 1]] + _check_transform_selected(X, X_expected, [0]) + _check_transform_selected(X, X_expected, [True, False, False]) + + X_expected = [[1, 1, 1], [0, 1, 1]] + _check_transform_selected(X, X_expected, [0, 1, 2]) + _check_transform_selected(X, X_expected, [True, True, True]) + _check_transform_selected(X, X_expected, "all") + + _check_transform_selected(X, X, []) + _check_transform_selected(X, X, [False, False, False]) + + +def _run_one_hot(X, X2, cat): + enc = OneHotEncoder(categorical_features=cat) + Xtr = enc.fit_transform(X) + X2tr = enc.transform(X2) + return Xtr, X2tr + + +def _check_one_hot(X, X2, cat, n_features): + ind = np.where(cat)[0] + # With mask + A, B = _run_one_hot(X, X2, cat) + # With indices + C, D = _run_one_hot(X, X2, ind) + # Check shape + assert_equal(A.shape, (2, n_features)) + assert_equal(B.shape, (1, n_features)) + assert_equal(C.shape, (2, n_features)) + assert_equal(D.shape, (1, n_features)) + # Check that mask and indices give the same results + assert_array_equal(toarray(A), toarray(C)) + assert_array_equal(toarray(B), toarray(D)) + + +def test_one_hot_encoder_categorical_features(): + X = np.array([[3, 2, 1], [0, 1, 1]]) + X2 = np.array([[1, 1, 1]]) + + cat = [True, False, False] + _check_one_hot(X, X2, cat, 4) + + # Edge case: all non-categorical + cat = [False, False, False] + _check_one_hot(X, X2, cat, 3) + + # Edge case: all categorical + cat = [True, True, True] + _check_one_hot(X, X2, cat, 5) + + +def test_one_hot_encoder_unknown_transform(): + X = np.array([[0, 2, 1], [1, 0, 3], [1, 0, 2]]) + y = np.array([[4, 1, 1]]) + + # Test that one hot encoder raises error for unknown features + # present during transform. + oh = OneHotEncoder(handle_unknown='error') + oh.fit(X) + assert_raises(ValueError, oh.transform, y) + + # Test the ignore option, ignores unknown features. + oh = OneHotEncoder(handle_unknown='ignore') + oh.fit(X) + assert_array_equal( + oh.transform(y).toarray(), + np.array([[ 0., 0., 0., 0., 1., 0., 0.]]) + ) + + # Raise error if handle_unknown is neither ignore or error. + oh = OneHotEncoder(handle_unknown='42') + oh.fit(X) + assert_raises(ValueError, oh.transform, y) diff --git a/sklearn/preprocessing/tests/test_imputation.py b/sklearn/preprocessing/tests/test_imputation.py new file mode 100644 index 0000000000000..608fdacee6e12 --- /dev/null +++ b/sklearn/preprocessing/tests/test_imputation.py @@ -0,0 +1,348 @@ +import numpy as np +from scipy import sparse + +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_true + +from sklearn.preprocessing.imputation import Imputer +from sklearn.pipeline import Pipeline +from sklearn import grid_search +from sklearn import tree +from sklearn.random_projection import sparse_random_matrix + + +def _check_statistics(X, X_true, + strategy, statistics, missing_values): + """Utility function for testing imputation for a given strategy. + + Test: + - along the two axes + - with dense and sparse arrays + + Check that: + - the statistics (mean, median, mode) are correct + - the missing values are imputed correctly""" + + err_msg = "Parameters: strategy = %s, missing_values = %s, " \ + "axis = {0}, sparse = {1}" % (strategy, missing_values) + + # Normal matrix, axis = 0 + imputer = Imputer(missing_values, strategy=strategy, axis=0) + X_trans = imputer.fit(X).transform(X.copy()) + assert_array_equal(imputer.statistics_, statistics, + err_msg.format(0, False)) + assert_array_equal(X_trans, X_true, err_msg.format(0, False)) + + # Normal matrix, axis = 1 + imputer = Imputer(missing_values, strategy=strategy, axis=1) + imputer.fit(X.transpose()) + if np.isnan(statistics).any(): + assert_raises(ValueError, imputer.transform, X.copy().transpose()) + else: + X_trans = imputer.transform(X.copy().transpose()) + assert_array_equal(X_trans, X_true.transpose(), + err_msg.format(1, False)) + + # Sparse matrix, axis = 0 + imputer = Imputer(missing_values, strategy=strategy, axis=0) + imputer.fit(sparse.csc_matrix(X)) + X_trans = imputer.transform(sparse.csc_matrix(X.copy())) + + if sparse.issparse(X_trans): + X_trans = X_trans.toarray() + + assert_array_equal(imputer.statistics_, statistics, + err_msg.format(0, True)) + assert_array_equal(X_trans, X_true, err_msg.format(0, True)) + + # Sparse matrix, axis = 1 + imputer = Imputer(missing_values, strategy=strategy, axis=1) + imputer.fit(sparse.csc_matrix(X.transpose())) + if np.isnan(statistics).any(): + assert_raises(ValueError, imputer.transform, + sparse.csc_matrix(X.copy().transpose())) + else: + X_trans = imputer.transform(sparse.csc_matrix(X.copy().transpose())) + + if sparse.issparse(X_trans): + X_trans = X_trans.toarray() + + assert_array_equal(X_trans, X_true.transpose(), + err_msg.format(1, True)) + + +def test_imputation_shape(): + """Verify the shapes of the imputed matrix for different strategies.""" + X = np.random.randn(10, 2) + X[::2] = np.nan + + for strategy in ['mean', 'median', 'most_frequent']: + imputer = Imputer(strategy=strategy) + X_imputed = imputer.fit_transform(X) + assert_equal(X_imputed.shape, (10, 2)) + X_imputed = imputer.fit_transform(sparse.csr_matrix(X)) + assert_equal(X_imputed.shape, (10, 2)) + + +def test_imputation_mean_median_only_zero(): + """Test imputation using the mean and median strategies, when + missing_values == 0.""" + X = np.array([ + [np.nan, 0, 0, 0, 5], + [np.nan, 1, 0, np.nan, 3], + [np.nan, 2, 0, 0, 0], + [np.nan, 6, 0, 5, 13], + ]) + + X_imputed_mean = np.array([ + [3, 5], + [1, 3], + [2, 7], + [6, 13], + ]) + statistics_mean = [np.nan, 3, np.nan, np.nan, 7] + + # Behaviour of median with NaN is undefined, e.g. different results in + # np.median and np.ma.median + X_for_median = X[:, [0, 1, 2, 4]] + X_imputed_median = np.array([ + [2, 5], + [1, 3], + [2, 5], + [6, 13], + ]) + statistics_median = [np.nan, 2, np.nan, 5] + + _check_statistics(X, X_imputed_mean, "mean", statistics_mean, 0) + _check_statistics(X_for_median, X_imputed_median, "median", + statistics_median, 0) + + +def test_imputation_mean_median(): + """Test imputation using the mean and median strategies, when + missing_values != 0.""" + rng = np.random.RandomState(0) + + dim = 10 + dec = 10 + shape = (dim * dim, dim + dec) + + zeros = np.zeros(shape[0]) + values = np.arange(1, shape[0]+1) + values[4::2] = - values[4::2] + + tests = [("mean", "NaN", lambda z, v, p: np.mean(np.hstack((z, v)))), + ("mean", 0, lambda z, v, p: np.mean(v)), + ("median", "NaN", lambda z, v, p: np.median(np.hstack((z, v)))), + ("median", 0, lambda z, v, p: np.median(v))] + + for strategy, test_missing_values, true_value_fun in tests: + X = np.empty(shape) + X_true = np.empty(shape) + true_statistics = np.empty(shape[1]) + + # Create a matrix X with columns + # - with only zeros, + # - with only missing values + # - with zeros, missing values and values + # And a matrix X_true containing all true values + for j in range(shape[1]): + nb_zeros = (j - dec + 1 > 0) * (j - dec + 1) * (j - dec + 1) + nb_missing_values = max(shape[0] + dec * dec + - (j + dec) * (j + dec), 0) + nb_values = shape[0] - nb_zeros - nb_missing_values + + z = zeros[:nb_zeros] + p = np.repeat(test_missing_values, nb_missing_values) + v = values[rng.permutation(len(values))[:nb_values]] + + true_statistics[j] = true_value_fun(z, v, p) + + # Create the columns + X[:, j] = np.hstack((v, z, p)) + + if 0 == test_missing_values: + X_true[:, j] = np.hstack((v, + np.repeat( + true_statistics[j], + nb_missing_values + nb_zeros))) + else: + X_true[:, j] = np.hstack((v, + z, + np.repeat(true_statistics[j], + nb_missing_values))) + + # Shuffle them the same way + np.random.RandomState(j).shuffle(X[:, j]) + np.random.RandomState(j).shuffle(X_true[:, j]) + + # Mean doesn't support columns containing NaNs, median does + if strategy == "median": + cols_to_keep = ~np.isnan(X_true).any(axis=0) + else: + cols_to_keep = ~np.isnan(X_true).all(axis=0) + + X_true = X_true[:, cols_to_keep] + + _check_statistics(X, X_true, strategy, + true_statistics, test_missing_values) + + +def test_imputation_median_special_cases(): + """Test median imputation with sparse boundary cases + """ + X = np.array([ + [0, np.nan, np.nan], # odd: implicit zero + [5, np.nan, np.nan], # odd: explicit nonzero + [0, 0, np.nan], # even: average two zeros + [-5, 0, np.nan], # even: avg zero and neg + [0, 5, np.nan], # even: avg zero and pos + [4, 5, np.nan], # even: avg nonzeros + [-4, -5, np.nan], # even: avg negatives + [-1, 2, np.nan], # even: crossing neg and pos + ]).transpose() + + X_imputed_median = np.array([ + [0, 0, 0], + [5, 5, 5], + [0, 0, 0], + [-5, 0, -2.5], + [0, 5, 2.5], + [4, 5, 4.5], + [-4, -5, -4.5], + [-1, 2, .5], + ]).transpose() + statistics_median = [0, 5, 0, -2.5, 2.5, 4.5, -4.5, .5] + + _check_statistics(X, X_imputed_median, "median", + statistics_median, 'NaN') + + +def test_imputation_most_frequent(): + """Test imputation using the most-frequent strategy.""" + X = np.array([ + [-1, -1, 0, 5], + [-1, 2, -1, 3], + [-1, 1, 3, -1], + [-1, 2, 3, 7], + ]) + + X_true = np.array([ + [2, 0, 5], + [2, 3, 3], + [1, 3, 3], + [2, 3, 7], + ]) + + # scipy.stats.mode, used in Imputer, doesn't return the first most + # frequent as promised in the doc but the lowest most frequent. When this + # test will fail after an update of scipy, Imputer will need to be updated + # to be consistent with the new (correct) behaviour + _check_statistics(X, X_true, "most_frequent", [np.nan, 2, 3, 3], -1) + + +def test_imputation_pipeline_grid_search(): + """Test imputation within a pipeline + gridsearch.""" + pipeline = Pipeline([('imputer', Imputer(missing_values=0)), + ('tree', tree.DecisionTreeRegressor(random_state=0))]) + + parameters = { + 'imputer__strategy': ["mean", "median", "most_frequent"], + 'imputer__axis': [0, 1] + } + + l = 100 + X = sparse_random_matrix(l, l, density=0.10) + Y = sparse_random_matrix(l, 1, density=0.10).toarray() + gs = grid_search.GridSearchCV(pipeline, parameters) + gs.fit(X, Y) + + +def test_imputation_pickle(): + """Test for pickling imputers.""" + import pickle + + l = 100 + X = sparse_random_matrix(l, l, density=0.10) + + for strategy in ["mean", "median", "most_frequent"]: + imputer = Imputer(missing_values=0, strategy=strategy) + imputer.fit(X) + + imputer_pickled = pickle.loads(pickle.dumps(imputer)) + + assert_array_equal(imputer.transform(X.copy()), + imputer_pickled.transform(X.copy()), + "Fail to transform the data after pickling " + "(strategy = %s)" % (strategy)) + + +def test_imputation_copy(): + """Test imputation with copy""" + X_orig = sparse_random_matrix(5, 5, density=0.75, random_state=0) + + # copy=True, dense => copy + X = X_orig.copy().toarray() + imputer = Imputer(missing_values=0, strategy="mean", copy=True) + Xt = imputer.fit(X).transform(X) + Xt[0, 0] = -1 + assert_false(np.all(X == Xt)) + + # copy=True, sparse csr => copy + X = X_orig.copy() + imputer = Imputer(missing_values=X.data[0], strategy="mean", copy=True) + Xt = imputer.fit(X).transform(X) + Xt.data[0] = -1 + assert_false(np.all(X.data == Xt.data)) + + # copy=False, dense => no copy + X = X_orig.copy().toarray() + imputer = Imputer(missing_values=0, strategy="mean", copy=False) + Xt = imputer.fit(X).transform(X) + Xt[0, 0] = -1 + assert_true(np.all(X == Xt)) + + # copy=False, sparse csr, axis=1 => no copy + X = X_orig.copy() + imputer = Imputer(missing_values=X.data[0], strategy="mean", + copy=False, axis=1) + Xt = imputer.fit(X).transform(X) + Xt.data[0] = -1 + assert_true(np.all(X.data == Xt.data)) + + # copy=False, sparse csc, axis=0 => no copy + X = X_orig.copy().tocsc() + imputer = Imputer(missing_values=X.data[0], strategy="mean", + copy=False, axis=0) + Xt = imputer.fit(X).transform(X) + Xt.data[0] = -1 + assert_true(np.all(X.data == Xt.data)) + + # copy=False, sparse csr, axis=0 => copy + X = X_orig.copy() + imputer = Imputer(missing_values=X.data[0], strategy="mean", + copy=False, axis=0) + Xt = imputer.fit(X).transform(X) + Xt.data[0] = -1 + assert_false(np.all(X.data == Xt.data)) + + # copy=False, sparse csc, axis=1 => copy + X = X_orig.copy().tocsc() + imputer = Imputer(missing_values=X.data[0], strategy="mean", + copy=False, axis=1) + Xt = imputer.fit(X).transform(X) + Xt.data[0] = -1 + assert_false(np.all(X.data == Xt.data)) + + # copy=False, sparse csr, axis=1, missing_values=0 => copy + X = X_orig.copy() + imputer = Imputer(missing_values=0, strategy="mean", + copy=False, axis=1) + Xt = imputer.fit(X).transform(X) + assert_false(sparse.issparse(Xt)) + + # Note: If X is sparse and if missing_values=0, then a (dense) copy of X is + # made, even if copy=False. diff --git a/sklearn/preprocessing/tests/test_label.py b/sklearn/preprocessing/tests/test_label.py new file mode 100644 index 0000000000000..f523870ffd2fd --- /dev/null +++ b/sklearn/preprocessing/tests/test_label.py @@ -0,0 +1,572 @@ +import numpy as np + +from scipy.sparse import issparse +from scipy.sparse import coo_matrix +from scipy.sparse import csc_matrix +from scipy.sparse import csr_matrix +from scipy.sparse import dok_matrix +from scipy.sparse import lil_matrix + +from sklearn.utils.multiclass import type_of_target + +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import assert_warns_message +from sklearn.utils.testing import ignore_warnings + +from sklearn.preprocessing.label import LabelBinarizer +from sklearn.preprocessing.label import MultiLabelBinarizer +from sklearn.preprocessing.label import LabelEncoder +from sklearn.preprocessing.label import label_binarize + +from sklearn.preprocessing.label import _inverse_binarize_thresholding +from sklearn.preprocessing.label import _inverse_binarize_multiclass + +from sklearn import datasets + +iris = datasets.load_iris() + + +def toarray(a): + if hasattr(a, "toarray"): + a = a.toarray() + return a + + +def test_label_binarizer(): + lb = LabelBinarizer() + + # one-class case defaults to negative label + inp = ["pos", "pos", "pos", "pos"] + expected = np.array([[0, 0, 0, 0]]).T + got = lb.fit_transform(inp) + assert_false(assert_warns(DeprecationWarning, getattr, lb, "multilabel_")) + assert_array_equal(lb.classes_, ["pos"]) + assert_array_equal(expected, got) + assert_array_equal(lb.inverse_transform(got), inp) + + # two-class case + inp = ["neg", "pos", "pos", "neg"] + expected = np.array([[0, 1, 1, 0]]).T + got = lb.fit_transform(inp) + assert_false(assert_warns(DeprecationWarning, getattr, lb, "multilabel_")) + assert_array_equal(lb.classes_, ["neg", "pos"]) + assert_array_equal(expected, got) + + to_invert = np.array([[1, 0], + [0, 1], + [0, 1], + [1, 0]]) + assert_array_equal(lb.inverse_transform(to_invert), inp) + + # multi-class case + inp = ["spam", "ham", "eggs", "ham", "0"] + expected = np.array([[0, 0, 0, 1], + [0, 0, 1, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [1, 0, 0, 0]]) + got = lb.fit_transform(inp) + assert_array_equal(lb.classes_, ['0', 'eggs', 'ham', 'spam']) + assert_false(assert_warns(DeprecationWarning, getattr, lb, "multilabel_")) + assert_array_equal(expected, got) + assert_array_equal(lb.inverse_transform(got), inp) + + +def test_label_binarizer_unseen_labels(): + lb = LabelBinarizer() + + expected = np.array([[1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + got = lb.fit_transform(['b', 'd', 'e']) + assert_array_equal(expected, got) + + expected = np.array([[0, 0, 0], + [1, 0, 0], + [0, 0, 0], + [0, 1, 0], + [0, 0, 1], + [0, 0, 0]]) + got = lb.transform(['a', 'b', 'c', 'd', 'e', 'f']) + assert_array_equal(expected, got) + + +@ignore_warnings +def test_label_binarizer_column_y(): + # first for binary classification vs multi-label with 1 possible class + # lists are multi-label, array is multi-class :-/ + inp_list = [[1], [2], [1]] + inp_array = np.array(inp_list) + + multilabel_indicator = np.array([[1, 0], [0, 1], [1, 0]]) + binaryclass_array = np.array([[0], [1], [0]]) + + lb_1 = LabelBinarizer() + out_1 = lb_1.fit_transform(inp_list) + + lb_2 = LabelBinarizer() + out_2 = lb_2.fit_transform(inp_array) + + assert_array_equal(out_1, multilabel_indicator) + assert_true(assert_warns(DeprecationWarning, getattr, lb_1, "multilabel_")) + assert_false(assert_warns(DeprecationWarning, getattr, lb_1, + "indicator_matrix_")) + + assert_array_equal(out_2, binaryclass_array) + assert_false(assert_warns(DeprecationWarning, getattr, lb_2, + "multilabel_")) + + # second for multiclass classification vs multi-label with multiple + # classes + inp_list = [[1], [2], [1], [3]] + inp_array = np.array(inp_list) + + # the indicator matrix output is the same in this case + indicator = np.array([[1, 0, 0], [0, 1, 0], [1, 0, 0], [0, 0, 1]]) + + lb_1 = LabelBinarizer() + out_1 = lb_1.fit_transform(inp_list) + + lb_2 = LabelBinarizer() + out_2 = lb_2.fit_transform(inp_array) + + assert_array_equal(out_1, out_2) + assert_true(assert_warns(DeprecationWarning, getattr, lb_1, "multilabel_")) + + assert_array_equal(out_2, indicator) + assert_false(assert_warns(DeprecationWarning, getattr, lb_2, + "multilabel_")) + + +def test_label_binarizer_set_label_encoding(): + lb = LabelBinarizer(neg_label=-2, pos_label=0) + + # two-class case with pos_label=0 + inp = np.array([0, 1, 1, 0]) + expected = np.array([[-2, 0, 0, -2]]).T + got = lb.fit_transform(inp) + assert_false(assert_warns(DeprecationWarning, getattr, lb, "multilabel_")) + assert_array_equal(expected, got) + assert_array_equal(lb.inverse_transform(got), inp) + + lb = LabelBinarizer(neg_label=-2, pos_label=2) + + # multi-class case + inp = np.array([3, 2, 1, 2, 0]) + expected = np.array([[-2, -2, -2, +2], + [-2, -2, +2, -2], + [-2, +2, -2, -2], + [-2, -2, +2, -2], + [+2, -2, -2, -2]]) + got = lb.fit_transform(inp) + assert_false(assert_warns(DeprecationWarning, getattr, lb, "multilabel_")) + assert_array_equal(expected, got) + assert_array_equal(lb.inverse_transform(got), inp) + + +@ignore_warnings +def test_label_binarizer_errors(): + """Check that invalid arguments yield ValueError""" + one_class = np.array([0, 0, 0, 0]) + lb = LabelBinarizer().fit(one_class) + assert_false(assert_warns(DeprecationWarning, getattr, lb, "multilabel_")) + + multi_label = [(2, 3), (0,), (0, 2)] + assert_raises(ValueError, lb.transform, multi_label) + + lb = LabelBinarizer() + assert_raises(ValueError, lb.transform, []) + assert_raises(ValueError, lb.inverse_transform, []) + + y = np.array([[0, 1, 0], [1, 1, 1]]) + classes = np.arange(3) + assert_raises(ValueError, label_binarize, y, classes, multilabel=True, + neg_label=2, pos_label=1) + assert_raises(ValueError, label_binarize, y, classes, multilabel=True, + neg_label=2, pos_label=2) + + assert_raises(ValueError, LabelBinarizer, neg_label=2, pos_label=1) + assert_raises(ValueError, LabelBinarizer, neg_label=2, pos_label=2) + + assert_raises(ValueError, LabelBinarizer, neg_label=1, pos_label=2, + sparse_output=True) + + # Fail on y_type + assert_raises(ValueError, _inverse_binarize_thresholding, + y=csr_matrix([[1, 2], [2, 1]]), output_type="foo", + classes=[1, 2], threshold=0) + + # Fail on the number of classes + assert_raises(ValueError, _inverse_binarize_thresholding, + y=csr_matrix([[1, 2], [2, 1]]), output_type="foo", + classes=[1, 2, 3], threshold=0) + + # Fail on the dimension of 'binary' + assert_raises(ValueError, _inverse_binarize_thresholding, + y=np.array([[1, 2, 3], [2, 1, 3]]), output_type="binary", + classes=[1, 2, 3], threshold=0) + + # Fail on multioutput data + assert_raises(ValueError, LabelBinarizer().fit, np.array([[1, 3], [2, 1]])) + assert_raises(ValueError, label_binarize, np.array([[1, 3], [2, 1]]), + [1, 2, 3]) + + +def test_label_encoder(): + """Test LabelEncoder's transform and inverse_transform methods""" + le = LabelEncoder() + le.fit([1, 1, 4, 5, -1, 0]) + assert_array_equal(le.classes_, [-1, 0, 1, 4, 5]) + assert_array_equal(le.transform([0, 1, 4, 4, 5, -1, -1]), + [1, 2, 3, 3, 4, 0, 0]) + assert_array_equal(le.inverse_transform([1, 2, 3, 3, 4, 0, 0]), + [0, 1, 4, 4, 5, -1, -1]) + assert_raises(ValueError, le.transform, [0, 6]) + + +def test_label_encoder_fit_transform(): + """Test fit_transform""" + le = LabelEncoder() + ret = le.fit_transform([1, 1, 4, 5, -1, 0]) + assert_array_equal(ret, [2, 2, 3, 4, 0, 1]) + + le = LabelEncoder() + ret = le.fit_transform(["paris", "paris", "tokyo", "amsterdam"]) + assert_array_equal(ret, [1, 1, 2, 0]) + + +def test_label_encoder_errors(): + """Check that invalid arguments yield ValueError""" + le = LabelEncoder() + assert_raises(ValueError, le.transform, []) + assert_raises(ValueError, le.inverse_transform, []) + + +def test_sparse_output_multilabel_binarizer(): + # test input as iterable of iterables + inputs = [ + lambda: [(2, 3), (1,), (1, 2)], + lambda: (set([2, 3]), set([1]), set([1, 2])), + lambda: iter([iter((2, 3)), iter((1,)), set([1, 2])]), + ] + indicator_mat = np.array([[0, 1, 1], + [1, 0, 0], + [1, 1, 0]]) + + inverse = inputs[0]() + for sparse_output in [True, False]: + for inp in inputs: + # With fit_tranform + mlb = MultiLabelBinarizer(sparse_output=sparse_output) + got = mlb.fit_transform(inp()) + assert_equal(issparse(got), sparse_output) + if sparse_output: + got = got.toarray() + assert_array_equal(indicator_mat, got) + assert_array_equal([1, 2, 3], mlb.classes_) + assert_equal(mlb.inverse_transform(got), inverse) + + # With fit + mlb = MultiLabelBinarizer(sparse_output=sparse_output) + got = mlb.fit(inp()).transform(inp()) + assert_equal(issparse(got), sparse_output) + if sparse_output: + got = got.toarray() + assert_array_equal(indicator_mat, got) + assert_array_equal([1, 2, 3], mlb.classes_) + assert_equal(mlb.inverse_transform(got), inverse) + + assert_raises(ValueError, mlb.inverse_transform, + csr_matrix(np.array([[0, 1, 1], + [2, 0, 0], + [1, 1, 0]]))) + + +def test_multilabel_binarizer(): + # test input as iterable of iterables + inputs = [ + lambda: [(2, 3), (1,), (1, 2)], + lambda: (set([2, 3]), set([1]), set([1, 2])), + lambda: iter([iter((2, 3)), iter((1,)), set([1, 2])]), + ] + indicator_mat = np.array([[0, 1, 1], + [1, 0, 0], + [1, 1, 0]]) + inverse = inputs[0]() + for inp in inputs: + # With fit_tranform + mlb = MultiLabelBinarizer() + got = mlb.fit_transform(inp()) + assert_array_equal(indicator_mat, got) + assert_array_equal([1, 2, 3], mlb.classes_) + assert_equal(mlb.inverse_transform(got), inverse) + + # With fit + mlb = MultiLabelBinarizer() + got = mlb.fit(inp()).transform(inp()) + assert_array_equal(indicator_mat, got) + assert_array_equal([1, 2, 3], mlb.classes_) + assert_equal(mlb.inverse_transform(got), inverse) + + +def test_multilabel_binarizer_empty_sample(): + mlb = MultiLabelBinarizer() + y = [[1, 2], [1], []] + Y = np.array([[1, 1], + [1, 0], + [0, 0]]) + assert_array_equal(mlb.fit_transform(y), Y) + + +def test_multilabel_binarizer_unknown_class(): + mlb = MultiLabelBinarizer() + y = [[1, 2]] + assert_raises(KeyError, mlb.fit(y).transform, [[0]]) + + mlb = MultiLabelBinarizer(classes=[1, 2]) + assert_raises(KeyError, mlb.fit_transform, [[0]]) + + +def test_multilabel_binarizer_given_classes(): + inp = [(2, 3), (1,), (1, 2)] + indicator_mat = np.array([[0, 1, 1], + [1, 0, 0], + [1, 0, 1]]) + # fit_transform() + mlb = MultiLabelBinarizer(classes=[1, 3, 2]) + assert_array_equal(mlb.fit_transform(inp), indicator_mat) + assert_array_equal(mlb.classes_, [1, 3, 2]) + + # fit().transform() + mlb = MultiLabelBinarizer(classes=[1, 3, 2]) + assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) + assert_array_equal(mlb.classes_, [1, 3, 2]) + + # ensure works with extra class + mlb = MultiLabelBinarizer(classes=[4, 1, 3, 2]) + assert_array_equal(mlb.fit_transform(inp), + np.hstack(([[0], [0], [0]], indicator_mat))) + assert_array_equal(mlb.classes_, [4, 1, 3, 2]) + + # ensure fit is no-op as iterable is not consumed + inp = iter(inp) + mlb = MultiLabelBinarizer(classes=[1, 3, 2]) + assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) + + +def test_multilabel_binarizer_same_length_sequence(): + """Ensure sequences of the same length are not interpreted as a 2-d array + """ + inp = [[1], [0], [2]] + indicator_mat = np.array([[0, 1, 0], + [1, 0, 0], + [0, 0, 1]]) + # fit_transform() + mlb = MultiLabelBinarizer() + assert_array_equal(mlb.fit_transform(inp), indicator_mat) + assert_array_equal(mlb.inverse_transform(indicator_mat), inp) + + # fit().transform() + mlb = MultiLabelBinarizer() + assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) + assert_array_equal(mlb.inverse_transform(indicator_mat), inp) + + +def test_multilabel_binarizer_non_integer_labels(): + tuple_classes = np.empty(3, dtype=object) + tuple_classes[:] = [(1,), (2,), (3,)] + inputs = [ + ([('2', '3'), ('1',), ('1', '2')], ['1', '2', '3']), + ([('b', 'c'), ('a',), ('a', 'b')], ['a', 'b', 'c']), + ([((2,), (3,)), ((1,),), ((1,), (2,))], tuple_classes), + ] + indicator_mat = np.array([[0, 1, 1], + [1, 0, 0], + [1, 1, 0]]) + for inp, classes in inputs: + # fit_transform() + mlb = MultiLabelBinarizer() + assert_array_equal(mlb.fit_transform(inp), indicator_mat) + assert_array_equal(mlb.classes_, classes) + assert_array_equal(mlb.inverse_transform(indicator_mat), inp) + + # fit().transform() + mlb = MultiLabelBinarizer() + assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) + assert_array_equal(mlb.classes_, classes) + assert_array_equal(mlb.inverse_transform(indicator_mat), inp) + + mlb = MultiLabelBinarizer() + assert_raises(TypeError, mlb.fit_transform, [({}), ({}, {'a': 'b'})]) + + +def test_multilabel_binarizer_non_unique(): + inp = [(1, 1, 1, 0)] + indicator_mat = np.array([[1, 1]]) + mlb = MultiLabelBinarizer() + assert_array_equal(mlb.fit_transform(inp), indicator_mat) + + +def test_multilabel_binarizer_inverse_validation(): + inp = [(1, 1, 1, 0)] + mlb = MultiLabelBinarizer() + mlb.fit_transform(inp) + # Not binary + assert_raises(ValueError, mlb.inverse_transform, np.array([[1, 3]])) + # The following binary cases are fine, however + mlb.inverse_transform(np.array([[0, 0]])) + mlb.inverse_transform(np.array([[1, 1]])) + mlb.inverse_transform(np.array([[1, 0]])) + + # Wrong shape + assert_raises(ValueError, mlb.inverse_transform, np.array([[1]])) + assert_raises(ValueError, mlb.inverse_transform, np.array([[1, 1, 1]])) + + +def test_label_binarize_with_class_order(): + out = label_binarize([1, 6], classes=[1, 2, 4, 6]) + expected = np.array([[1, 0, 0, 0], [0, 0, 0, 1]]) + assert_array_equal(out, expected) + + # Modified class order + out = label_binarize([1, 6], classes=[1, 6, 4, 2]) + expected = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) + assert_array_equal(out, expected) + + +def check_binarized_results(y, classes, pos_label, neg_label, expected): + for sparse_output in [True, False]: + if ((pos_label == 0 or neg_label != 0) and sparse_output): + assert_raises(ValueError, label_binarize, y, classes, + neg_label=neg_label, pos_label=pos_label, + sparse_output=sparse_output) + continue + + # check label_binarize + binarized = label_binarize(y, classes, neg_label=neg_label, + pos_label=pos_label, + sparse_output=sparse_output) + assert_array_equal(toarray(binarized), expected) + assert_equal(issparse(binarized), sparse_output) + + # check inverse + y_type = type_of_target(y) + if y_type == "multiclass": + inversed = _inverse_binarize_multiclass(binarized, classes=classes) + + else: + inversed = _inverse_binarize_thresholding(binarized, + output_type=y_type, + classes=classes, + threshold=((neg_label + + pos_label) / + 2.)) + + assert_array_equal(toarray(inversed), toarray(y)) + + # Check label binarizer + lb = LabelBinarizer(neg_label=neg_label, pos_label=pos_label, + sparse_output=sparse_output) + binarized = lb.fit_transform(y) + assert_array_equal(toarray(binarized), expected) + assert_equal(issparse(binarized), sparse_output) + inverse_output = lb.inverse_transform(binarized) + assert_array_equal(toarray(inverse_output), toarray(y)) + assert_equal(issparse(inverse_output), issparse(y)) + + +def test_label_binarize_binary(): + y = [0, 1, 0] + classes = [0, 1] + pos_label = 2 + neg_label = -1 + expected = np.array([[2, -1], [-1, 2], [2, -1]])[:, 1].reshape((-1, 1)) + + yield check_binarized_results, y, classes, pos_label, neg_label, expected + + # Binary case where sparse_output = True will not result in a ValueError + y = [0, 1, 0] + classes = [0, 1] + pos_label = 3 + neg_label = 0 + expected = np.array([[3, 0], [0, 3], [3, 0]])[:, 1].reshape((-1, 1)) + + yield check_binarized_results, y, classes, pos_label, neg_label, expected + + +def test_label_binarize_multiclass(): + y = [0, 1, 2] + classes = [0, 1, 2] + pos_label = 2 + neg_label = 0 + expected = 2 * np.eye(3) + + yield check_binarized_results, y, classes, pos_label, neg_label, expected + + assert_raises(ValueError, label_binarize, y, classes, neg_label=-1, + pos_label=pos_label, sparse_output=True) + + +def test_label_binarize_multilabel(): + y_seq = [(1,), (0, 1, 2), tuple()] + y_ind = np.array([[0, 1, 0], [1, 1, 1], [0, 0, 0]]) + classes = [0, 1, 2] + pos_label = 2 + neg_label = 0 + expected = pos_label * y_ind + y_sparse = [sparse_matrix(y_ind) + for sparse_matrix in [coo_matrix, csc_matrix, csr_matrix, + dok_matrix, lil_matrix]] + + for y in [y_ind] + y_sparse: + yield (check_binarized_results, y, classes, pos_label, neg_label, + expected) + + deprecation_message = ("Direct support for sequence of sequences " + + "multilabel representation will be unavailable " + + "from version 0.17. Use sklearn.preprocessing." + + "MultiLabelBinarizer to convert to a label " + + "indicator representation.") + + assert_warns_message(DeprecationWarning, deprecation_message, + check_binarized_results, y_seq, classes, pos_label, + neg_label, expected) + + assert_raises(ValueError, label_binarize, y, classes, neg_label=-1, + pos_label=pos_label, sparse_output=True) + + +def test_deprecation_inverse_binarize_thresholding(): + deprecation_message = ("Direct support for sequence of sequences " + + "multilabel representation will be unavailable " + + "from version 0.17. Use sklearn.preprocessing." + + "MultiLabelBinarizer to convert to a label " + + "indicator representation.") + + assert_warns_message(DeprecationWarning, deprecation_message, + _inverse_binarize_thresholding, + y=csr_matrix([[1, 0], [0, 1]]), + output_type="multilabel-sequences", + classes=[1, 2], threshold=0) + + +def test_invalid_input_label_binarize(): + assert_raises(ValueError, label_binarize, [0, 2], classes=[0, 2], + pos_label=0, neg_label=1) + + +def test_inverse_binarize_multiclass(): + got = _inverse_binarize_multiclass(csr_matrix([[0, 1, 0], + [-1, 0, -1], + [0, 0, 0]]), + np.arange(3)) + assert_array_equal(got, np.array([1, 1, 0])) + +if __name__ == "__main__": + import nose + nose.runmodule() diff --git a/sklearn/preprocessing/tests/test_weights.py b/sklearn/preprocessing/tests/test_weights.py new file mode 100644 index 0000000000000..c86e94804506a --- /dev/null +++ b/sklearn/preprocessing/tests/test_weights.py @@ -0,0 +1,13 @@ +from sklearn.preprocessing._weights import _balance_weights +from sklearn.utils.testing import assert_array_equal + + +def test_balance_weights(): + weights = _balance_weights([0, 0, 1, 1]) + assert_array_equal(weights, [1., 1., 1., 1.]) + + weights = _balance_weights([0, 1, 1, 1, 1]) + assert_array_equal(weights, [1., 0.25, 0.25, 0.25, 0.25]) + + weights = _balance_weights([0, 0]) + assert_array_equal(weights, [1., 1.]) diff --git a/sklearn/qda.py b/sklearn/qda.py index 163011d26b3f7..6b05f0b0d14f8 100644 --- a/sklearn/qda.py +++ b/sklearn/qda.py @@ -4,15 +4,17 @@ # Author: Matthieu Perrot # -# License: BSD Style. +# License: BSD 3 clause import warnings import numpy as np from .base import BaseEstimator, ClassifierMixin -from .utils.fixes import unique -from .utils import check_arrays +from .externals.six.moves import xrange +from .utils import check_array, check_X_y +from .utils.validation import check_is_fitted +from .utils.fixes import bincount __all__ = ['QDA'] @@ -32,14 +34,31 @@ class QDA(BaseEstimator, ClassifierMixin): priors : array, optional, shape = [n_classes] Priors on classes + reg_param : float, optional + Regularizes the covariance estimate as + ``(1-reg_param)*Sigma + reg_param*np.eye(n_features)`` + Attributes ---------- - `means_` : array-like, shape = [n_classes, n_features] - Class means - `priors_` : array-like, shape = [n_classes] - Class priors (sum to 1) - `covariances_` : list of array-like, shape = [n_features, n_features] - Covariance matrices of each class + covariances_ : list of array-like, shape = [n_features, n_features] + Covariance matrices of each class. + + means_ : array-like, shape = [n_classes, n_features] + Class means. + + priors_ : array-like, shape = [n_classes] + Class priors (sum to 1). + + rotations_ : list of arrays + For each class k an array of shape [n_features, n_k], with + ``n_k = min(n_features, number of elements in class k)`` + It is the rotation of the Gaussian distribution, i.e. its + principal axis. + + scalings_ : list of arrays + For each class k an array of shape [n_k]. It contains the scaling + of the Gaussian distributions along its principal axes, i.e. the + variance in the rotated coordinate system. Examples -------- @@ -49,7 +68,7 @@ class QDA(BaseEstimator, ClassifierMixin): >>> y = np.array([1, 1, 1, 2, 2, 2]) >>> clf = QDA() >>> clf.fit(X, y) - QDA(priors=None) + QDA(priors=None, reg_param=0.0) >>> print(clf.predict([[-0.8, -1]])) [1] @@ -58,8 +77,9 @@ class QDA(BaseEstimator, ClassifierMixin): sklearn.lda.LDA: Linear discriminant analysis """ - def __init__(self, priors=None): + def __init__(self, priors=None, reg_param=0.): self.priors = np.asarray(priors) if priors is not None else None + self.reg_param = reg_param def fit(self, X, y, store_covariances=False, tol=1.0e-4): """ @@ -70,20 +90,25 @@ def fit(self, X, y, store_covariances=False, tol=1.0e-4): X : array-like, shape = [n_samples, n_features] Training vector, where n_samples in the number of samples and n_features is the number of features. + y : array, shape = [n_samples] Target values (integers) + store_covariances : boolean If True the covariance matrices are computed and stored in the `self.covariances_` attribute. + + tol : float, optional, default 1.0e-4 + Threshold used for rank estimation. """ - X, y = check_arrays(X, y) - self.classes_, y = unique(y, return_inverse=True) + X, y = check_X_y(X, y) + self.classes_, y = np.unique(y, return_inverse=True) n_samples, n_features = X.shape n_classes = len(self.classes_) if n_classes < 2: raise ValueError('y has less than 2 classes') if self.priors is None: - self.priors_ = np.bincount(y) / float(n_samples) + self.priors_ = bincount(y) / float(n_samples) else: self.priors_ = self.priors @@ -97,6 +122,9 @@ def fit(self, X, y, store_covariances=False, tol=1.0e-4): Xg = X[y == ind, :] meang = Xg.mean(0) means.append(meang) + if len(Xg) == 1: + raise ValueError('y has only 1 sample in class %s, covariance ' + 'is ill defined.' % str(self.classes_[ind])) Xgc = Xg - meang # Xgc = U * S * V.T U, S, Vt = np.linalg.svd(Xgc, full_matrices=False) @@ -104,6 +132,7 @@ def fit(self, X, y, store_covariances=False, tol=1.0e-4): if rank < n_features: warnings.warn("Variables are collinear") S2 = (S ** 2) / (len(Xg) - 1) + S2 = ((1 - self.reg_param) * S2) + self.reg_param if store_covariances: # cov = V * (S^2 / (n-1)) * V.T cov.append(np.dot(S2 * Vt.T, Vt)) @@ -112,29 +141,24 @@ def fit(self, X, y, store_covariances=False, tol=1.0e-4): if store_covariances: self.covariances_ = cov self.means_ = np.asarray(means) - self.scalings = np.asarray(scalings) - self.rotations = rotations + self.scalings_ = scalings + self.rotations_ = rotations return self - @property - def classes(self): - warnings.warn("QDA.classes is deprecated and will be removed in 0.14. " - "Use QDA.classes_ instead.", DeprecationWarning, - stacklevel=2) - return self.classes_ - def _decision_function(self, X): - X = np.asarray(X) + check_is_fitted(self, 'classes_') + + X = check_array(X) norm2 = [] for i in range(len(self.classes_)): - R = self.rotations[i] - S = self.scalings[i] + R = self.rotations_[i] + S = self.scalings_[i] Xm = X - self.means_[i] X2 = np.dot(Xm, R * (S ** (-0.5))) norm2.append(np.sum(X2 ** 2, 1)) norm2 = np.array(norm2).T # shape = [len(X), n_classes] - return (-0.5 * (norm2 + np.sum(np.log(self.scalings), 1)) - + np.log(self.priors_)) + u = np.asarray([np.sum(np.log(s)) for s in self.scalings_]) + return (-0.5 * (norm2 + u) + np.log(self.priors_)) def decision_function(self, X): """Apply decision function to an array of samples. @@ -190,7 +214,7 @@ def predict_proba(self, X): values = self._decision_function(X) # compute the likelihood of the underlying gaussian models # up to a multiplicative constant. - likelihood = np.exp(values - values.min(axis=1)[:, np.newaxis]) + likelihood = np.exp(values - values.max(axis=1)[:, np.newaxis]) # compute posterior probabilities return likelihood / likelihood.sum(axis=1)[:, np.newaxis] diff --git a/sklearn/random_projection.py b/sklearn/random_projection.py new file mode 100644 index 0000000000000..30cb5b78e3972 --- /dev/null +++ b/sklearn/random_projection.py @@ -0,0 +1,612 @@ +# -*- coding: utf8 +"""Random Projection transformers + +Random Projections are a simple and computationally efficient way to +reduce the dimensionality of the data by trading a controlled amount +of accuracy (as additional variance) for faster processing times and +smaller model sizes. + +The dimensions and distribution of Random Projections matrices are +controlled so as to preserve the pairwise distances between any two +samples of the dataset. + +The main theoretical result behind the efficiency of random projection is the +`Johnson-Lindenstrauss lemma (quoting Wikipedia) +`_: + + In mathematics, the Johnson-Lindenstrauss lemma is a result + concerning low-distortion embeddings of points from high-dimensional + into low-dimensional Euclidean space. The lemma states that a small set + of points in a high-dimensional space can be embedded into a space of + much lower dimension in such a way that distances between the points are + nearly preserved. The map used for the embedding is at least Lipschitz, + and can even be taken to be an orthogonal projection. + +""" +# Authors: Olivier Grisel , +# Arnaud Joly +# License: BSD 3 clause + +from __future__ import division +import warnings +from abc import ABCMeta, abstractmethod + +import numpy as np +from numpy.testing import assert_equal +import scipy.sparse as sp + +from .base import BaseEstimator, TransformerMixin +from .externals import six +from .externals.six.moves import xrange +from .utils import check_random_state +from .utils.extmath import safe_sparse_dot +from .utils.random import sample_without_replacement +from .utils.validation import check_array, NotFittedError +from .utils import DataDimensionalityWarning + + +__all__ = ["SparseRandomProjection", + "GaussianRandomProjection", + "johnson_lindenstrauss_min_dim"] + + +def johnson_lindenstrauss_min_dim(n_samples, eps=0.1): + """Find a 'safe' number of components to randomly project to + + The distortion introduced by a random projection `p` only changes the + distance between two points by a factor (1 +- eps) in an euclidean space + with good probability. The projection `p` is an eps-embedding as defined + by: + + (1 - eps) ||u - v||^2 < ||p(u) - p(v)||^2 < (1 + eps) ||u - v||^2 + + Where u and v are any rows taken from a dataset of shape [n_samples, + n_features], eps is in ]0, 1[ and p is a projection by a random Gaussian + N(0, 1) matrix with shape [n_components, n_features] (or a sparse + Achlioptas matrix). + + The minimum number of components to guarantee the eps-embedding is + given by: + + n_components >= 4 log(n_samples) / (eps^2 / 2 - eps^3 / 3) + + Note that the number of dimensions is independent of the original + number of features but instead depends on the size of the dataset: + the larger the dataset, the higher is the minimal dimensionality of + an eps-embedding. + + Parameters + ---------- + n_samples : int or numpy array of int greater than 0, + Number of samples. If an array is given, it will compute + a safe number of components array-wise. + + eps : float or numpy array of float in ]0,1[, optional (default=0.1) + Maximum distortion rate as defined by the Johnson-Lindenstrauss lemma. + If an array is given, it will compute a safe number of components + array-wise. + + Returns + ------- + n_components : int or numpy array of int, + The minimal number of components to guarantee with good probability + an eps-embedding with n_samples. + + Examples + -------- + + >>> johnson_lindenstrauss_min_dim(1e6, eps=0.5) + 663 + + >>> johnson_lindenstrauss_min_dim(1e6, eps=[0.5, 0.1, 0.01]) + array([ 663, 11841, 1112658]) + + >>> johnson_lindenstrauss_min_dim([1e4, 1e5, 1e6], eps=0.1) + array([ 7894, 9868, 11841]) + + References + ---------- + + .. [1] http://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma + + .. [2] Sanjoy Dasgupta and Anupam Gupta, 1999, + "An elementary proof of the Johnson-Lindenstrauss Lemma." + http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.45.3654 + + """ + eps = np.asarray(eps) + n_samples = np.asarray(n_samples) + + if np.any(eps <= 0.0) or np.any(eps >= 1): + raise ValueError( + "The JL bound is defined for eps in ]0, 1[, got %r" % eps) + + if np.any(n_samples) <= 0: + raise ValueError( + "The JL bound is defined for n_samples greater than zero, got %r" + % n_samples) + + denominator = (eps ** 2 / 2) - (eps ** 3 / 3) + return (4 * np.log(n_samples) / denominator).astype(np.int) + + +def _check_density(density, n_features): + """Factorize density check according to Li et al.""" + if density == 'auto': + density = 1 / np.sqrt(n_features) + + elif density <= 0 or density > 1: + raise ValueError("Expected density in range ]0, 1], got: %r" + % density) + return density + + +def _check_input_size(n_components, n_features): + """Factorize argument checking for random matrix generation""" + if n_components <= 0: + raise ValueError("n_components must be strictly positive, got %d" % + n_components) + if n_features <= 0: + raise ValueError("n_features must be strictly positive, got %d" % + n_components) + + +def gaussian_random_matrix(n_components, n_features, random_state=None): + """ Generate a dense Gaussian random matrix. + + The components of the random matrix are drawn from + + N(0, 1.0 / n_components). + + Parameters + ---------- + n_components : int, + Dimensionality of the target projection space. + + n_features : int, + Dimensionality of the original source space. + + random_state : int, RandomState instance or None (default=None) + Control the pseudo random number generator used to generate the + matrix at fit time. + + Returns + ------- + components : numpy array of shape [n_components, n_features] + The generated Gaussian random matrix. + + See Also + -------- + GaussianRandomProjection + sparse_random_matrix + """ + _check_input_size(n_components, n_features) + rng = check_random_state(random_state) + components = rng.normal(loc=0.0, + scale=1.0 / np.sqrt(n_components), + size=(n_components, n_features)) + return components + + +def sparse_random_matrix(n_components, n_features, density='auto', + random_state=None): + """Generalized Achlioptas random sparse matrix for random projection + + Setting density to 1 / 3 will yield the original matrix by Dimitris + Achlioptas while setting a lower value will yield the generalization + by Ping Li et al. + + If we note :math:`s = 1 / density`, the components of the random matrix are + drawn from: + + - -sqrt(s) / sqrt(n_components) with probability 1 / 2s + - 0 with probability 1 - 1 / s + - +sqrt(s) / sqrt(n_components) with probability 1 / 2s + + Parameters + ---------- + n_components : int, + Dimensionality of the target projection space. + + n_features : int, + Dimensionality of the original source space. + + density : float in range ]0, 1] or 'auto', optional (default='auto') + Ratio of non-zero component in the random projection matrix. + + If density = 'auto', the value is set to the minimum density + as recommended by Ping Li et al.: 1 / sqrt(n_features). + + Use density = 1 / 3.0 if you want to reproduce the results from + Achlioptas, 2001. + + random_state : integer, RandomState instance or None (default=None) + Control the pseudo random number generator used to generate the + matrix at fit time. + + Returns + ------- + components: numpy array or CSR matrix with shape [n_components, n_features] + The generated Gaussian random matrix. + + See Also + -------- + SparseRandomProjection + gaussian_random_matrix + + References + ---------- + + .. [1] Ping Li, T. Hastie and K. W. Church, 2006, + "Very Sparse Random Projections". + http://www.stanford.edu/~hastie/Papers/Ping/KDD06_rp.pdf + + .. [2] D. Achlioptas, 2001, "Database-friendly random projections", + http://www.cs.ucsc.edu/~optas/papers/jl.pdf + + """ + _check_input_size(n_components, n_features) + density = _check_density(density, n_features) + rng = check_random_state(random_state) + + if density == 1: + # skip index generation if totally dense + components = rng.binomial(1, 0.5, (n_components, n_features)) * 2 - 1 + return 1 / np.sqrt(n_components) * components + + else: + # Generate location of non zero elements + indices = [] + offset = 0 + indptr = [offset] + for i in xrange(n_components): + # find the indices of the non-zero components for row i + n_nonzero_i = rng.binomial(n_features, density) + indices_i = sample_without_replacement(n_features, n_nonzero_i, + random_state=rng) + indices.append(indices_i) + offset += n_nonzero_i + indptr.append(offset) + + indices = np.concatenate(indices) + + # Among non zero components the probability of the sign is 50%/50% + data = rng.binomial(1, 0.5, size=np.size(indices)) * 2 - 1 + + # build the CSR structure by concatenating the rows + components = sp.csr_matrix((data, indices, indptr), + shape=(n_components, n_features)) + + return np.sqrt(1 / density) / np.sqrt(n_components) * components + + +class BaseRandomProjection(six.with_metaclass(ABCMeta, BaseEstimator, + TransformerMixin)): + """Base class for random projections. + + Warning: This class should not be used directly. + Use derived classes instead. + """ + + @abstractmethod + def __init__(self, n_components='auto', eps=0.1, dense_output=False, + random_state=None): + self.n_components = n_components + self.eps = eps + self.dense_output = dense_output + self.random_state = random_state + + self.components_ = None + self.n_components_ = None + + @abstractmethod + def _make_random_matrix(n_components, n_features): + """ Generate the random projection matrix + + Parameters + ---------- + n_components : int, + Dimensionality of the target projection space. + + n_features : int, + Dimensionality of the original source space. + + Returns + ------- + components : numpy array or CSR matrix [n_components, n_features] + The generated random matrix. + + """ + + def fit(self, X, y=None): + """Generate a sparse random projection matrix + + Parameters + ---------- + X : numpy array or scipy.sparse of shape [n_samples, n_features] + Training set: only the shape is used to find optimal random + matrix dimensions based on the theory referenced in the + afore mentioned papers. + + y : is not used: placeholder to allow for usage in a Pipeline. + + Returns + ------- + self + + """ + X = check_array(X, accept_sparse=['csr', 'csc']) + + n_samples, n_features = X.shape + + if self.n_components == 'auto': + self.n_components_ = johnson_lindenstrauss_min_dim( + n_samples=n_samples, eps=self.eps) + + if self.n_components_ <= 0: + raise ValueError( + 'eps=%f and n_samples=%d lead to a target dimension of ' + '%d which is invalid' % ( + self.eps, n_samples, self.n_components_)) + + elif self.n_components_ > n_features: + raise ValueError( + 'eps=%f and n_samples=%d lead to a target dimension of ' + '%d which is larger than the original space with ' + 'n_features=%d' % (self.eps, n_samples, self.n_components_, + n_features)) + else: + if self.n_components <= 0: + raise ValueError("n_components must be greater than 0, got %s" + % self.n_components_) + + elif self.n_components > n_features: + warnings.warn( + "The number of components is higher than the number of" + " features: n_features < n_components (%s < %s)." + "The dimensionality of the problem will not be reduced." + % (n_features, self.n_components), + DataDimensionalityWarning) + + self.n_components_ = self.n_components + + # Generate a projection matrix of size [n_components, n_features] + self.components_ = self._make_random_matrix(self.n_components_, + n_features) + + # Check contract + assert_equal( + self.components_.shape, + (self.n_components_, n_features), + err_msg=('An error has occurred the self.components_ matrix has ' + ' not the proper shape.')) + + return self + + def transform(self, X, y=None): + """Project the data by using matrix product with the random matrix + + Parameters + ---------- + X : numpy array or scipy.sparse of shape [n_samples, n_features] + The input data to project into a smaller dimensional space. + + y : is not used: placeholder to allow for usage in a Pipeline. + + Returns + ------- + X_new : numpy array or scipy sparse of shape [n_samples, n_components] + Projected array. + + """ + X = check_array(X, accept_sparse=['csr', 'csc']) + + if self.components_ is None: + raise NotFittedError('No random projection matrix had been fit.') + + if X.shape[1] != self.components_.shape[1]: + raise ValueError( + 'Impossible to perform projection:' + 'X at fit stage had a different number of features. ' + '(%s != %s)' % (X.shape[1], self.components_.shape[1])) + + X_new = safe_sparse_dot(X, self.components_.T, + dense_output=self.dense_output) + return X_new + + +class GaussianRandomProjection(BaseRandomProjection): + """Reduce dimensionality through Gaussian random projection + + The components of the random matrix are drawn from N(0, 1 / n_components). + + Parameters + ---------- + n_components : int or 'auto', optional (default = 'auto') + Dimensionality of the target projection space. + + n_components can be automatically adjusted according to the + number of samples in the dataset and the bound given by the + Johnson-Lindenstrauss lemma. In that case the quality of the + embedding is controlled by the ``eps`` parameter. + + It should be noted that Johnson-Lindenstrauss lemma can yield + very conservative estimated of the required number of components + as it makes no assumption on the structure of the dataset. + + eps : strictly positive float, optional (default=0.1) + Parameter to control the quality of the embedding according to + the Johnson-Lindenstrauss lemma when n_components is set to + 'auto'. + + Smaller values lead to better embedding and higher number of + dimensions (n_components) in the target projection space. + + random_state : integer, RandomState instance or None (default=None) + Control the pseudo random number generator used to generate the + matrix at fit time. + + Attributes + ---------- + n_component_ : int + Concrete number of components computed when n_components="auto". + + components_ : numpy array of shape [n_components, n_features] + Random matrix used for the projection. + + See Also + -------- + SparseRandomProjection + + """ + def __init__(self, n_components='auto', eps=0.1, random_state=None): + super(GaussianRandomProjection, self).__init__( + n_components=n_components, + eps=eps, + dense_output=True, + random_state=random_state) + + def _make_random_matrix(self, n_components, n_features): + """ Generate the random projection matrix + + Parameters + ---------- + n_components : int, + Dimensionality of the target projection space. + + n_features : int, + Dimensionality of the original source space. + + Returns + ------- + components : numpy array or CSR matrix [n_components, n_features] + The generated random matrix. + + """ + random_state = check_random_state(self.random_state) + return gaussian_random_matrix(n_components, + n_features, + random_state=random_state) + + +class SparseRandomProjection(BaseRandomProjection): + """Reduce dimensionality through sparse random projection + + Sparse random matrix is an alternative to dense random + projection matrix that guarantees similar embedding quality while being + much more memory efficient and allowing faster computation of the + projected data. + + If we note `s = 1 / density` the components of the random matrix are + drawn from: + + - -sqrt(s) / sqrt(n_components) with probability 1 / 2s + - 0 with probability 1 - 1 / s + - +sqrt(s) / sqrt(n_components) with probability 1 / 2s + + Parameters + ---------- + n_components : int or 'auto', optional (default = 'auto') + Dimensionality of the target projection space. + + n_components can be automatically adjusted according to the + number of samples in the dataset and the bound given by the + Johnson-Lindenstrauss lemma. In that case the quality of the + embedding is controlled by the ``eps`` parameter. + + It should be noted that Johnson-Lindenstrauss lemma can yield + very conservative estimated of the required number of components + as it makes no assumption on the structure of the dataset. + + density : float in range ]0, 1], optional (default='auto') + Ratio of non-zero component in the random projection matrix. + + If density = 'auto', the value is set to the minimum density + as recommended by Ping Li et al.: 1 / sqrt(n_features). + + Use density = 1 / 3.0 if you want to reproduce the results from + Achlioptas, 2001. + + eps : strictly positive float, optional, (default=0.1) + Parameter to control the quality of the embedding according to + the Johnson-Lindenstrauss lemma when n_components is set to + 'auto'. + + Smaller values lead to better embedding and higher number of + dimensions (n_components) in the target projection space. + + dense_output : boolean, optional (default=False) + If True, ensure that the output of the random projection is a + dense numpy array even if the input and random projection matrix + are both sparse. In practice, if the number of components is + small the number of zero components in the projected data will + be very small and it will be more CPU and memory efficient to + use a dense representation. + + If False, the projected data uses a sparse representation if + the input is sparse. + + random_state : integer, RandomState instance or None (default=None) + Control the pseudo random number generator used to generate the + matrix at fit time. + + Attributes + ---------- + n_component_ : int + Concrete number of components computed when n_components="auto". + + components_ : CSR matrix with shape [n_components, n_features] + Random matrix used for the projection. + + density_ : float in range 0.0 - 1.0 + Concrete density computed from when density = "auto". + + See Also + -------- + GaussianRandomProjection + + References + ---------- + + .. [1] Ping Li, T. Hastie and K. W. Church, 2006, + "Very Sparse Random Projections". + http://www.stanford.edu/~hastie/Papers/Ping/KDD06_rp.pdf + + .. [2] D. Achlioptas, 2001, "Database-friendly random projections", + http://www.cs.ucsc.edu/~optas/papers/jl.pdf + + """ + def __init__(self, n_components='auto', density='auto', eps=0.1, + dense_output=False, random_state=None): + super(SparseRandomProjection, self).__init__( + n_components=n_components, + eps=eps, + dense_output=dense_output, + random_state=random_state) + + self.density = density + self.density_ = None + + def _make_random_matrix(self, n_components, n_features): + """ Generate the random projection matrix + + Parameters + ---------- + n_components : int, + Dimensionality of the target projection space. + + n_features : int, + Dimensionality of the original source space. + + Returns + ------- + components : numpy array or CSR matrix [n_components, n_features] + The generated random matrix. + + """ + random_state = check_random_state(self.random_state) + self.density_ = _check_density(self.density, n_features) + return sparse_random_matrix(n_components, + n_features, + density=self.density_, + random_state=random_state) diff --git a/sklearn/semi_supervised/label_propagation.py b/sklearn/semi_supervised/label_propagation.py index dc1a1cdc1e106..31429a2a7c2bf 100644 --- a/sklearn/semi_supervised/label_propagation.py +++ b/sklearn/semi_supervised/label_propagation.py @@ -27,8 +27,8 @@ size O(k*N) which will run much faster. See the documentation for SVMs for more info on kernels. -Example -------- +Examples +-------- >>> from sklearn import datasets >>> from sklearn.semi_supervised import LabelPropagation >>> label_prop_model = LabelPropagation() @@ -53,15 +53,16 @@ # Authors: Clay Woolam # Licence: BSD - -import numpy as np -from scipy import sparse from abc import ABCMeta, abstractmethod +from scipy import sparse +import numpy as np from ..base import BaseEstimator, ClassifierMixin from ..metrics.pairwise import rbf_kernel from ..utils.graph import graph_laplacian from ..utils.extmath import safe_sparse_dot +from ..utils.validation import check_X_y, check_is_fitted +from ..externals import six from ..neighbors.unsupervised import NearestNeighbors @@ -72,7 +73,8 @@ def _not_converged(y_truth, y_prediction, tol=1e-3): return np.abs(y_truth - y_prediction).sum() > tol -class BaseLabelPropagation(BaseEstimator, ClassifierMixin): +class BaseLabelPropagation(six.with_metaclass(ABCMeta, BaseEstimator, + ClassifierMixin)): """Base class for label propagation module. Parameters @@ -87,18 +89,22 @@ class BaseLabelPropagation(BaseEstimator, ClassifierMixin): alpha : float Clamping factor - max_iters : float + max_iter : float Change maximum number of iterations allowed tol : float Convergence tolerance: threshold to consider the system at steady state + + n_neighbors : integer > 0 + Parameter for knn kernel + """ - __metaclass__ = ABCMeta def __init__(self, kernel='rbf', gamma=20, n_neighbors=7, - alpha=1, max_iters=30, tol=1e-3): - self.max_iters = max_iters + alpha=1, max_iter=30, tol=1e-3): + + self.max_iter = max_iter self.tol = tol # kernel parameters @@ -120,7 +126,8 @@ def _get_kernel(self, X, y=None): self.nn_fit = NearestNeighbors(self.n_neighbors).fit(X) if y is None: return self.nn_fit.kneighbors_graph(self.nn_fit._fit_X, - self.n_neighbors, mode='connectivity') + self.n_neighbors, + mode='connectivity') else: return self.nn_fit.kneighbors(y, return_distance=False) else: @@ -164,6 +171,8 @@ def predict_proba(self, X): Normalized probability distributions across class labels """ + check_is_fitted(self, 'X_') + if sparse.isspmatrix(X): X_2d = X else: @@ -202,10 +211,8 @@ def fit(self, X, y): ------- self : returns an instance of self. """ - if sparse.isspmatrix(X): - self.X_ = X - else: - self.X_ = np.asarray(X) + X, y = check_X_y(X, y) + self.X_ = X # actual graph construction (implementations should override this) graph_matrix = self._build_graph() @@ -235,25 +242,26 @@ def fit(self, X, y): l_previous = np.zeros((self.X_.shape[0], n_classes)) - remaining_iter = self.max_iters + remaining_iter = self.max_iter if sparse.isspmatrix(graph_matrix): graph_matrix = graph_matrix.tocsr() while (_not_converged(self.label_distributions_, l_previous, self.tol) and remaining_iter > 1): l_previous = self.label_distributions_ - self.label_distributions_ = safe_sparse_dot(graph_matrix, - self.label_distributions_) + self.label_distributions_ = safe_sparse_dot( + graph_matrix, self.label_distributions_) # clamp - self.label_distributions_ = np.multiply(clamp_weights, - self.label_distributions_) + y_static + self.label_distributions_ = np.multiply( + clamp_weights, self.label_distributions_) + y_static remaining_iter -= 1 normalizer = np.sum(self.label_distributions_, axis=1)[:, np.newaxis] self.label_distributions_ /= normalizer # set the transduction item transduction = self.classes_[np.argmax(self.label_distributions_, - axis=1)] + axis=1)] self.transduction_ = transduction.ravel() + self.n_iter_ = self.max_iter - remaining_iter return self @@ -266,16 +274,33 @@ class LabelPropagation(BaseLabelPropagation): String identifier for kernel function to use. Only 'rbf' and 'knn' kernels are currently supported.. gamma : float - parameter for rbf kernel + Parameter for rbf kernel n_neighbors : integer > 0 - parameter for knn kernel + Parameter for knn kernel alpha : float - clamping factor - max_iters : float - change maximum number of iterations allowed + Clamping factor + max_iter : float + Change maximum number of iterations allowed tol : float - Convergence tolerance: threshold to consider the system at steady - state + Convergence tolerance: threshold to consider the system at steady + state + + Attributes + ---------- + X_ : array, shape = [n_samples, n_features] + Input array. + + classes_ : array, shape = [n_classes] + The distinct labels used in classifying instances. + + label_distributions_ : array, shape = [n_samples, n_classes] + Categorical distribution for each item. + + transduction_ : array, shape = [n_samples] + Label assigned to each item via the transduction. + + n_iter_ : int + Number of iterations run. Examples -------- @@ -299,7 +324,7 @@ class LabelPropagation(BaseLabelPropagation): See Also -------- - LabelSpreading : Alternate label proagation strategy more robust to noise + LabelSpreading : Alternate label propagation strategy more robust to noise """ def _build_graph(self): """Matrix representing a fully connected graph between each sample @@ -336,12 +361,29 @@ class LabelSpreading(BaseLabelPropagation): parameter for knn kernel alpha : float clamping factor - max_iters : float + max_iter : float maximum number of iterations allowed tol : float Convergence tolerance: threshold to consider the system at steady state + Attributes + ---------- + X_ : array, shape = [n_samples, n_features] + Input array. + + classes_ : array, shape = [n_classes] + The distinct labels used in classifying instances. + + label_distributions_ : array, shape = [n_samples, n_classes] + Categorical distribution for each item. + + transduction_ : array, shape = [n_samples] + Label assigned to each item via the transduction. + + n_iter_ : int + Number of iterations run. + Examples -------- >>> from sklearn import datasets @@ -359,7 +401,7 @@ class LabelSpreading(BaseLabelPropagation): References ---------- Dengyong Zhou, Olivier Bousquet, Thomas Navin Lal, Jason Weston, - Bernhard Schölkopf. Learning with local and global consistency (2004) + Bernhard Schoelkopf. Learning with local and global consistency (2004) http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.115.3219 See Also @@ -368,11 +410,13 @@ class LabelSpreading(BaseLabelPropagation): """ def __init__(self, kernel='rbf', gamma=20, n_neighbors=7, alpha=0.2, - max_iters=30, tol=1e-3): + max_iter=30, tol=1e-3): + # this one has different base parameters super(LabelSpreading, self).__init__(kernel=kernel, gamma=gamma, - n_neighbors=n_neighbors, alpha=alpha, - max_iters=max_iters, tol=tol) + n_neighbors=n_neighbors, + alpha=alpha, max_iter=max_iter, + tol=tol) def _build_graph(self): """Graph matrix for Label Spreading computes the graph laplacian""" diff --git a/sklearn/semi_supervised/tests/test_label_propagation.py b/sklearn/semi_supervised/tests/test_label_propagation.py index 05035b80b3709..2414ec33b0c68 100644 --- a/sklearn/semi_supervised/tests/test_label_propagation.py +++ b/sklearn/semi_supervised/tests/test_label_propagation.py @@ -30,11 +30,12 @@ def test_distribution(): for estimator, parameters in ESTIMATORS: clf = estimator(**parameters).fit(samples, labels) if parameters['kernel'] == 'knn': + continue # unstable test; changes in k-NN ordering break it assert_array_almost_equal(clf.predict_proba([[1., 0.0]]), - np.array([[1., 0.]]), 2) + np.array([[1., 0.]]), 2) else: assert_array_almost_equal(np.asarray(clf.label_distributions_[2]), - np.array([.5, .5]), 2) + np.array([.5, .5]), 2) def test_predict(): @@ -51,4 +52,4 @@ def test_predict_proba(): for estimator, parameters in ESTIMATORS: clf = estimator(**parameters).fit(samples, labels) assert_array_almost_equal(clf.predict_proba([[1., 1.]]), - np.array([[0.5, 0.5]])) + np.array([[0.5, 0.5]])) diff --git a/sklearn/setup.py b/sklearn/setup.py index 3b032d2539b5e..111d9680287e6 100644 --- a/sklearn/setup.py +++ b/sklearn/setup.py @@ -24,6 +24,7 @@ def configuration(parent_package='', top_path=None): config.add_subpackage('cluster/tests') config.add_subpackage('covariance') config.add_subpackage('covariance/tests') + config.add_subpackage('cross_decomposition') config.add_subpackage('decomposition') config.add_subpackage('decomposition/tests') config.add_subpackage("ensemble") @@ -38,6 +39,8 @@ def configuration(parent_package='', top_path=None): config.add_subpackage('gaussian_process') config.add_subpackage('gaussian_process/tests') config.add_subpackage('neighbors') + config.add_subpackage('neural_network') + config.add_subpackage('preprocessing') config.add_subpackage('manifold') config.add_subpackage('metrics') config.add_subpackage('semi_supervised') @@ -54,11 +57,17 @@ def configuration(parent_package='', top_path=None): include_dirs=[numpy.get_include()], libraries=libraries, ) + config.add_extension( + '_isotonic', + sources=['_isotonic.c'], + include_dirs=[numpy.get_include()], + libraries=libraries, + ) # some libs needs cblas, fortran-compiled BLAS will not be sufficient blas_info = get_info('blas_opt', 0) if (not blas_info) or ( - ('NO_ATLAS_INFO', 1) in blas_info.get('define_macros', [])): + ('NO_ATLAS_INFO', 1) in blas_info.get('define_macros', [])): config.add_library('cblas', sources=[join('src', 'cblas', '*.c')]) warnings.warn(BlasNotFoundError.__doc__) diff --git a/sklearn/src/cblas/ATL_dreftrsvLTN.c b/sklearn/src/cblas/ATL_drefasum.c similarity index 55% rename from sklearn/src/cblas/ATL_dreftrsvLTN.c rename to sklearn/src/cblas/ATL_drefasum.c index 766ace797467d..221c19363967e 100644 --- a/sklearn/src/cblas/ATL_dreftrsvLTN.c +++ b/sklearn/src/cblas/ATL_drefasum.c @@ -47,15 +47,12 @@ * Include files */ #include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" +#include "atlas_reflevel1.h" -void ATL_dreftrsvLTN +double ATL_drefasum ( const int N, - const double * A, - const int LDA, - double * X, + const double * X, const int INCX ) { @@ -63,34 +60,74 @@ void ATL_dreftrsvLTN * Purpose * ======= * - * ATL_dreftrsvLTN( ... ) + * ATL_drefasum returns the sum of absolute values of the entries of a + * vector x. * - * <=> + * Arguments + * ========= * - * ATL_dreftrsv( AtlasLower, AtlasTrans, AtlasNonUnit, ... ) + * N (input) const int + * On entry, N specifies the length of the vector x. N must be + * at least zero. Unchanged on exit. * - * See ATL_dreftrsv for details. + * X (input) const double * + * On entry, X points to the first entry to be accessed of an + * incremented array of size equal to or greater than + * ( 1 + ( n - 1 ) * abs( INCX ) ) * sizeof( double ), + * that contains the vector x. Unchanged on exit. + * + * INCX (input) const int + * On entry, INCX specifies the increment for the elements of X. + * INCX must not be zero. Unchanged on exit. * * --------------------------------------------------------------------- */ /* * .. Local Variables .. */ - register double t0; - int i, iaij, ix, j, jaj, jx, ldap1 = LDA + 1; + register double sum = ATL_dZERO, x0, x1, x2, x3, + x4, x5, x6, x7; + double * StX; + register int i; + int nu; + const int incX2 = 2 * INCX, incX3 = 3 * INCX, + incX4 = 4 * INCX, incX5 = 5 * INCX, + incX6 = 6 * INCX, incX7 = 7 * INCX, + incX8 = 8 * INCX; /* .. * .. Executable Statements .. * */ - for( j = N-1, jaj = (N-1)*(ldap1), jx = (N-1)*INCX; - j >= 0; j--, jaj -= ldap1, jx -= INCX ) + if( ( N > 0 ) && ( INCX >= 1 ) ) { - t0 = X[jx]; - for( i = j+1, iaij = 1+jaj, ix = jx + INCX; - i < N; i++, iaij += 1, ix += INCX ) { t0 -= A[iaij] * X[ix]; } - t0 /= A[jaj]; X[jx] = t0; + if( ( nu = ( N >> 3 ) << 3 ) != 0 ) + { + StX = (double *)X + nu * INCX; + + do + { + x0 = (*X); x4 = X[incX4]; x1 = X[INCX ]; x5 = X[incX5]; + x2 = X[incX2]; x6 = X[incX6]; x3 = X[incX3]; x7 = X[incX7]; + + sum += Mdabs( x0 ); sum += Mdabs( x4 ); + sum += Mdabs( x1 ); sum += Mdabs( x3 ); + sum += Mdabs( x2 ); sum += Mdabs( x6 ); + sum += Mdabs( x5 ); sum += Mdabs( x7 ); + + X += incX8; + + } while( X != StX ); + } + + for( i = N - nu; i != 0; i-- ) + { + x0 = (*X); + sum += Mdabs( x0 ); + X += INCX; + } } + return( sum ); /* - * End of ATL_dreftrsvLTN + * End of ATL_drefasum */ } diff --git a/sklearn/src/cblas/ATL_dreftrsv.c b/sklearn/src/cblas/ATL_dreftrsv.c deleted file mode 100644 index 853794976b9c0..0000000000000 --- a/sklearn/src/cblas/ATL_dreftrsv.c +++ /dev/null @@ -1,213 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_dreftrsv -( - const enum ATLAS_UPLO UPLO, - const enum ATLAS_TRANS TRANS, - const enum ATLAS_DIAG DIAG, - const int N, - const double * A, - const int LDA, - double * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_dreftrsv solves one of the systems of equations - * - * A * x = b, or A' * x = b, - * - * where b and x are n-element vectors and A is an n by n unit, or non- - * unit, upper or lower triangular matrix. - * - * No test for singularity or near-singularity is included in this - * routine. Such tests must be performed before calling this routine. - * - * Arguments - * ========= - * - * UPLO (input) const enum ATLAS_UPLO - * On entry, UPLO specifies whether the matrix is an upper or - * lower triangular matrix as follows: - * - * UPLO = AtlasUpper A is an upper triangular matrix. - * - * UPLO = AtlasLower A is a lower triangular matrix. - * - * Unchanged on exit. - * - * TRANS (input) const enum ATLAS_TRANS - * On entry, TRANS specifies the equations to be solved as fol- - * lows: - * - * TRANS = AtlasNoTrans A * x = b, - * - * TRANS = AtlasConj A * x = b, - * - * TRANS = AtlasTrans A' * x = b, - * - * TRANS = AtlasTrans A' * x = b. - * - * Unchanged on exit. - * - * DIAG (input) const enum ATLAS_DIAG - * On entry, DIAG specifies whether or not A is unit triangu- - * lar as follows: - * - * DIAG = AtlasUnit A is assumed to be unit triangular, - * - * DIAG = AtlasNonUnit A is not assumed to be unit trian- - * gular. - * - * Unchanged on exit. - * - * N (input) const int - * On entry, N specifies the order of the matrix A. N must be at - * least zero. Unchanged on exit. - * - * A (input) const double * - * On entry, A points to an array of size equal to or greater - * than LDA * n * sizeof( double ). Before entry with - * UPLO = AtlasUpper, the leading n by n upper triangular part - * of the array A must contain the upper triangular matrix and - * the strictly lower triangular part of A is not referenced. - * Before entry with UPLO = AtlasLower, the leading n by n lower - * triangular part of the array A must contain the lower trian- - * gular matrix and the strictly upper triangular part of A is - * not referenced. Unchanged on exit. - * - * Note that when DIAG = AtlasUnit, the diagonal elements of A - * are not referenced either, but are assumed to be unity. - * - * LDA (input) const int - * On entry, LDA specifies the leading dimension of A as decla- - * red in the calling (sub) program. LDA must be at least - * MAX( 1, n ). Unchanged on exit. - * - * X (input/output) double * - * On entry, X points to the first entry to be accessed of an - * incremented array of size equal to or greater than - * ( 1 + ( n - 1 ) * abs( INCX ) ) * sizeof( double ), - * that contains the vector x. Before entry, the incremented ar- - * ray X must contain the n element right-hand side vector b. On - * exit, X is overwritten with the solution vector x. - * - * INCX (input) const int - * On entry, INCX specifies the increment for the elements of X. - * INCX must not be zero. Unchanged on exit. - * - * --------------------------------------------------------------------- - */ -/* .. - * .. Executable Statements .. - * - */ - if( N == 0 ) return; - - if( UPLO == AtlasUpper ) - { - if( ( TRANS == AtlasNoTrans ) || ( TRANS == AtlasConj ) ) - { - if( DIAG == AtlasNonUnit ) - { - ATL_dreftrsvUNN( N, A, LDA, X, INCX ); - } - else - { - ATL_dreftrsvUNU( N, A, LDA, X, INCX ); - } - } - else - { - if( DIAG == AtlasNonUnit ) - { - ATL_dreftrsvUTN( N, A, LDA, X, INCX ); - } - else - { - ATL_dreftrsvUTU( N, A, LDA, X, INCX ); - } - } - } - else - { - if( ( TRANS == AtlasNoTrans ) || ( TRANS == AtlasConj ) ) - { - if( DIAG == AtlasNonUnit ) - { - ATL_dreftrsvLNN( N, A, LDA, X, INCX ); - } - else - { - ATL_dreftrsvLNU( N, A, LDA, X, INCX ); - } - } - else - { - if( DIAG == AtlasNonUnit ) - { - ATL_dreftrsvLTN( N, A, LDA, X, INCX ); - } - else - { - ATL_dreftrsvLTU( N, A, LDA, X, INCX ); - } - } - } -/* - * End of ATL_dreftrsv - */ -} diff --git a/sklearn/src/cblas/ATL_dreftrsvLNN.c b/sklearn/src/cblas/ATL_dreftrsvLNN.c deleted file mode 100644 index 6f56e794a6cb1..0000000000000 --- a/sklearn/src/cblas/ATL_dreftrsvLNN.c +++ /dev/null @@ -1,94 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_dreftrsvLNN -( - const int N, - const double * A, - const int LDA, - double * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_dreftrsvLNN( ... ) - * - * <=> - * - * ATL_dreftrsv( AtlasLower, AtlasNoTrans, AtlasNonUnit, ... ) - * - * See ATL_dreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register double t0; - int i, iaij, ix, j, jaj, jx, ldap1 = LDA + 1; -/* .. - * .. Executable Statements .. - * - */ - for( j = 0, jaj = 0, jx = 0; j < N; j++, jaj += ldap1, jx += INCX ) - { - X[jx] /= A[jaj]; t0 = X[jx]; - for( i = j+1, iaij = jaj+1, ix = jx + INCX; - i < N; i++, iaij += 1, ix += INCX ) { X[ix] -= t0 * A[iaij]; } - } -/* - * End of ATL_dreftrsvLNN - */ -} diff --git a/sklearn/src/cblas/ATL_dreftrsvLNU.c b/sklearn/src/cblas/ATL_dreftrsvLNU.c deleted file mode 100644 index 1ca3235961b12..0000000000000 --- a/sklearn/src/cblas/ATL_dreftrsvLNU.c +++ /dev/null @@ -1,94 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_dreftrsvLNU -( - const int N, - const double * A, - const int LDA, - double * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_dreftrsvLNU( ... ) - * - * <=> - * - * ATL_dreftrsv( AtlasLower, AtlasNoTrans, AtlasUnit, ... ) - * - * See ATL_dreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register double t0; - int i, iaij, ix, j, jaj, jx, ldap1 = LDA + 1; -/* .. - * .. Executable Statements .. - * - */ - for( j = 0, jaj = 0, jx = 0; j < N; j++, jaj += ldap1, jx += INCX ) - { - t0 = X[jx]; - for( i = j+1, iaij = jaj+1, ix = jx + INCX; - i < N; i++, iaij += 1, ix += INCX ) { X[ix] -= t0 * A[iaij]; } - } -/* - * End of ATL_dreftrsvLNU - */ -} diff --git a/sklearn/src/cblas/ATL_dreftrsvLTU.c b/sklearn/src/cblas/ATL_dreftrsvLTU.c deleted file mode 100644 index 8c3ba9c59029e..0000000000000 --- a/sklearn/src/cblas/ATL_dreftrsvLTU.c +++ /dev/null @@ -1,96 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_dreftrsvLTU -( - const int N, - const double * A, - const int LDA, - double * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_dreftrsvLTU( ... ) - * - * <=> - * - * ATL_dreftrsv( AtlasLower, AtlasTrans, AtlasUnit, ... ) - * - * See ATL_dreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register double t0; - int i, iaij, ix, j, jaj, jx, ldap1 = LDA + 1; -/* .. - * .. Executable Statements .. - * - */ - for( j = N-1, jaj = (N-1)*(ldap1), jx = (N-1)*INCX; - j >= 0; j--, jaj -= ldap1, jx -= INCX ) - { - t0 = X[jx]; - for( i = j+1, iaij = 1+jaj, ix = jx + INCX; - i < N; i++, iaij += 1, ix += INCX ) { t0 -= A[iaij] * X[ix]; } - X[jx] = t0; - } -/* - * End of ATL_dreftrsvLTU - */ -} diff --git a/sklearn/src/cblas/ATL_dreftrsvUNN.c b/sklearn/src/cblas/ATL_dreftrsvUNN.c deleted file mode 100644 index 57b3e09cb0470..0000000000000 --- a/sklearn/src/cblas/ATL_dreftrsvUNN.c +++ /dev/null @@ -1,95 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_dreftrsvUNN -( - const int N, - const double * A, - const int LDA, - double * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_dreftrsvUNN( ... ) - * - * <=> - * - * ATL_dreftrsv( AtlasUpper, AtlasNoTrans, AtlasNonUnit, ... ) - * - * See ATL_dreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register double t0; - int i, iaij, ix, j, jaj, jx; -/* .. - * .. Executable Statements .. - * - */ - for( j = N-1, jaj = (N-1)*LDA, jx = (N-1)*INCX; - j >= 0; j--, jaj -= LDA, jx -= INCX ) - { - X[jx] /= A[j+jaj]; t0 = X[jx]; - for( i = 0, iaij = jaj, ix = 0; i < j; i++, iaij += 1, ix += INCX ) - { X[ix] -= t0 * A[iaij]; } - } -/* - * End of ATL_dreftrsvUNN - */ -} diff --git a/sklearn/src/cblas/ATL_dreftrsvUNU.c b/sklearn/src/cblas/ATL_dreftrsvUNU.c deleted file mode 100644 index 08246d58eeb12..0000000000000 --- a/sklearn/src/cblas/ATL_dreftrsvUNU.c +++ /dev/null @@ -1,95 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_dreftrsvUNU -( - const int N, - const double * A, - const int LDA, - double * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_dreftrsvUNU( ... ) - * - * <=> - * - * ATL_dreftrsv( AtlasUpper, AtlasNoTrans, AtlasUnit, ... ) - * - * See ATL_dreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register double t0; - int i, iaij, ix, j, jaj, jx; -/* .. - * .. Executable Statements .. - * - */ - for( j = N-1, jaj = (N-1)*LDA, jx = (N-1)*INCX; - j >= 0; j--, jaj -= LDA, jx -= INCX ) - { - t0 = X[jx]; - for( i = 0, iaij = jaj, ix = 0; i < j; i++, iaij += 1, ix += INCX ) - { X[ix] -= t0 * A[iaij]; } - } -/* - * End of ATL_dreftrsvUNU - */ -} diff --git a/sklearn/src/cblas/ATL_dreftrsvUTN.c b/sklearn/src/cblas/ATL_dreftrsvUTN.c deleted file mode 100644 index d7899d5de9529..0000000000000 --- a/sklearn/src/cblas/ATL_dreftrsvUTN.c +++ /dev/null @@ -1,95 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_dreftrsvUTN -( - const int N, - const double * A, - const int LDA, - double * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_dreftrsvUTN( ... ) - * - * <=> - * - * ATL_dreftrsv( AtlasUpper, AtlasTrans, AtlasNonUnit, ... ) - * - * See ATL_dreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register double t0; - int i, iaij, ix, j, jaj, jx; -/* .. - * .. Executable Statements .. - * - */ - for( j = 0, jaj = 0,jx = 0; j < N; j++, jaj += LDA, jx += INCX ) - { - t0 = X[jx]; - for( i = 0, iaij = jaj, ix = 0; i < j; i++, iaij += 1, ix += INCX ) - { t0 -= A[iaij] * X[ix]; } - t0 /= A[iaij]; X[jx] = t0; - } -/* - * End of ATL_dreftrsvUTN - */ -} diff --git a/sklearn/src/cblas/ATL_dreftrsvUTU.c b/sklearn/src/cblas/ATL_dreftrsvUTU.c deleted file mode 100644 index 590bc0b7a5b42..0000000000000 --- a/sklearn/src/cblas/ATL_dreftrsvUTU.c +++ /dev/null @@ -1,95 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_dreftrsvUTU -( - const int N, - const double * A, - const int LDA, - double * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_dreftrsvUTU( ... ) - * - * <=> - * - * ATL_dreftrsv( AtlasUpper, AtlasTrans, AtlasUnit, ... ) - * - * See ATL_dreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register double t0; - int i, iaij, ix, j, jaj, jx; -/* .. - * .. Executable Statements .. - * - */ - for( j = 0, jaj = 0, jx = 0; j < N; j++, jaj += LDA, jx += INCX ) - { - t0 = X[jx]; - for( i = 0, iaij = jaj, ix = 0; i < j; i++, iaij += 1, ix += INCX ) - { t0 -= A[iaij] * X[ix]; } - X[jx] = t0; - } -/* - * End of ATL_dreftrsvUTU - */ -} diff --git a/sklearn/src/cblas/ATL_sreftrsv.c b/sklearn/src/cblas/ATL_sreftrsv.c deleted file mode 100644 index f77d179215a7c..0000000000000 --- a/sklearn/src/cblas/ATL_sreftrsv.c +++ /dev/null @@ -1,213 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_sreftrsv -( - const enum ATLAS_UPLO UPLO, - const enum ATLAS_TRANS TRANS, - const enum ATLAS_DIAG DIAG, - const int N, - const float * A, - const int LDA, - float * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_sreftrsv solves one of the systems of equations - * - * A * x = b, or A' * x = b, - * - * where b and x are n-element vectors and A is an n by n unit, or non- - * unit, upper or lower triangular matrix. - * - * No test for singularity or near-singularity is included in this - * routine. Such tests must be performed before calling this routine. - * - * Arguments - * ========= - * - * UPLO (input) const enum ATLAS_UPLO - * On entry, UPLO specifies whether the matrix is an upper or - * lower triangular matrix as follows: - * - * UPLO = AtlasUpper A is an upper triangular matrix. - * - * UPLO = AtlasLower A is a lower triangular matrix. - * - * Unchanged on exit. - * - * TRANS (input) const enum ATLAS_TRANS - * On entry, TRANS specifies the equations to be solved as fol- - * lows: - * - * TRANS = AtlasNoTrans A * x = b, - * - * TRANS = AtlasConj A * x = b, - * - * TRANS = AtlasTrans A' * x = b, - * - * TRANS = AtlasTrans A' * x = b. - * - * Unchanged on exit. - * - * DIAG (input) const enum ATLAS_DIAG - * On entry, DIAG specifies whether or not A is unit triangu- - * lar as follows: - * - * DIAG = AtlasUnit A is assumed to be unit triangular, - * - * DIAG = AtlasNonUnit A is not assumed to be unit trian- - * gular. - * - * Unchanged on exit. - * - * N (input) const int - * On entry, N specifies the order of the matrix A. N must be at - * least zero. Unchanged on exit. - * - * A (input) const float * - * On entry, A points to an array of size equal to or greater - * than LDA * n * sizeof( float ). Before entry with - * UPLO = AtlasUpper, the leading n by n upper triangular part - * of the array A must contain the upper triangular matrix and - * the strictly lower triangular part of A is not referenced. - * Before entry with UPLO = AtlasLower, the leading n by n lower - * triangular part of the array A must contain the lower trian- - * gular matrix and the strictly upper triangular part of A is - * not referenced. Unchanged on exit. - * - * Note that when DIAG = AtlasUnit, the diagonal elements of A - * are not referenced either, but are assumed to be unity. - * - * LDA (input) const int - * On entry, LDA specifies the leading dimension of A as decla- - * red in the calling (sub) program. LDA must be at least - * MAX( 1, n ). Unchanged on exit. - * - * X (input/output) float * - * On entry, X points to the first entry to be accessed of an - * incremented array of size equal to or greater than - * ( 1 + ( n - 1 ) * abs( INCX ) ) * sizeof( float ), - * that contains the vector x. Before entry, the incremented ar- - * ray X must contain the n element right-hand side vector b. On - * exit, X is overwritten with the solution vector x. - * - * INCX (input) const int - * On entry, INCX specifies the increment for the elements of X. - * INCX must not be zero. Unchanged on exit. - * - * --------------------------------------------------------------------- - */ -/* .. - * .. Executable Statements .. - * - */ - if( N == 0 ) return; - - if( UPLO == AtlasUpper ) - { - if( ( TRANS == AtlasNoTrans ) || ( TRANS == AtlasConj ) ) - { - if( DIAG == AtlasNonUnit ) - { - ATL_sreftrsvUNN( N, A, LDA, X, INCX ); - } - else - { - ATL_sreftrsvUNU( N, A, LDA, X, INCX ); - } - } - else - { - if( DIAG == AtlasNonUnit ) - { - ATL_sreftrsvUTN( N, A, LDA, X, INCX ); - } - else - { - ATL_sreftrsvUTU( N, A, LDA, X, INCX ); - } - } - } - else - { - if( ( TRANS == AtlasNoTrans ) || ( TRANS == AtlasConj ) ) - { - if( DIAG == AtlasNonUnit ) - { - ATL_sreftrsvLNN( N, A, LDA, X, INCX ); - } - else - { - ATL_sreftrsvLNU( N, A, LDA, X, INCX ); - } - } - else - { - if( DIAG == AtlasNonUnit ) - { - ATL_sreftrsvLTN( N, A, LDA, X, INCX ); - } - else - { - ATL_sreftrsvLTU( N, A, LDA, X, INCX ); - } - } - } -/* - * End of ATL_sreftrsv - */ -} diff --git a/sklearn/src/cblas/ATL_sreftrsvLNN.c b/sklearn/src/cblas/ATL_sreftrsvLNN.c deleted file mode 100644 index 109a68884845b..0000000000000 --- a/sklearn/src/cblas/ATL_sreftrsvLNN.c +++ /dev/null @@ -1,94 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_sreftrsvLNN -( - const int N, - const float * A, - const int LDA, - float * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_sreftrsvLNN( ... ) - * - * <=> - * - * ATL_sreftrsv( AtlasLower, AtlasNoTrans, AtlasNonUnit, ... ) - * - * See ATL_sreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register float t0; - int i, iaij, ix, j, jaj, jx, ldap1 = LDA + 1; -/* .. - * .. Executable Statements .. - * - */ - for( j = 0, jaj = 0, jx = 0; j < N; j++, jaj += ldap1, jx += INCX ) - { - X[jx] /= A[jaj]; t0 = X[jx]; - for( i = j+1, iaij = jaj+1, ix = jx + INCX; - i < N; i++, iaij += 1, ix += INCX ) { X[ix] -= t0 * A[iaij]; } - } -/* - * End of ATL_sreftrsvLNN - */ -} diff --git a/sklearn/src/cblas/ATL_sreftrsvLNU.c b/sklearn/src/cblas/ATL_sreftrsvLNU.c deleted file mode 100644 index f97e51be13966..0000000000000 --- a/sklearn/src/cblas/ATL_sreftrsvLNU.c +++ /dev/null @@ -1,94 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_sreftrsvLNU -( - const int N, - const float * A, - const int LDA, - float * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_sreftrsvLNU( ... ) - * - * <=> - * - * ATL_sreftrsv( AtlasLower, AtlasNoTrans, AtlasUnit, ... ) - * - * See ATL_sreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register float t0; - int i, iaij, ix, j, jaj, jx, ldap1 = LDA + 1; -/* .. - * .. Executable Statements .. - * - */ - for( j = 0, jaj = 0, jx = 0; j < N; j++, jaj += ldap1, jx += INCX ) - { - t0 = X[jx]; - for( i = j+1, iaij = jaj+1, ix = jx + INCX; - i < N; i++, iaij += 1, ix += INCX ) { X[ix] -= t0 * A[iaij]; } - } -/* - * End of ATL_sreftrsvLNU - */ -} diff --git a/sklearn/src/cblas/ATL_sreftrsvLTN.c b/sklearn/src/cblas/ATL_sreftrsvLTN.c deleted file mode 100644 index 923f84e709f2e..0000000000000 --- a/sklearn/src/cblas/ATL_sreftrsvLTN.c +++ /dev/null @@ -1,96 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_sreftrsvLTN -( - const int N, - const float * A, - const int LDA, - float * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_sreftrsvLTN( ... ) - * - * <=> - * - * ATL_sreftrsv( AtlasLower, AtlasTrans, AtlasNonUnit, ... ) - * - * See ATL_sreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register float t0; - int i, iaij, ix, j, jaj, jx, ldap1 = LDA + 1; -/* .. - * .. Executable Statements .. - * - */ - for( j = N-1, jaj = (N-1)*(ldap1), jx = (N-1)*INCX; - j >= 0; j--, jaj -= ldap1, jx -= INCX ) - { - t0 = X[jx]; - for( i = j+1, iaij = 1+jaj, ix = jx + INCX; - i < N; i++, iaij += 1, ix += INCX ) { t0 -= A[iaij] * X[ix]; } - t0 /= A[jaj]; X[jx] = t0; - } -/* - * End of ATL_sreftrsvLTN - */ -} diff --git a/sklearn/src/cblas/ATL_sreftrsvLTU.c b/sklearn/src/cblas/ATL_sreftrsvLTU.c deleted file mode 100644 index 40288f92aa8cf..0000000000000 --- a/sklearn/src/cblas/ATL_sreftrsvLTU.c +++ /dev/null @@ -1,96 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_sreftrsvLTU -( - const int N, - const float * A, - const int LDA, - float * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_sreftrsvLTU( ... ) - * - * <=> - * - * ATL_sreftrsv( AtlasLower, AtlasTrans, AtlasUnit, ... ) - * - * See ATL_sreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register float t0; - int i, iaij, ix, j, jaj, jx, ldap1 = LDA + 1; -/* .. - * .. Executable Statements .. - * - */ - for( j = N-1, jaj = (N-1)*(ldap1), jx = (N-1)*INCX; - j >= 0; j--, jaj -= ldap1, jx -= INCX ) - { - t0 = X[jx]; - for( i = j+1, iaij = 1+jaj, ix = jx + INCX; - i < N; i++, iaij += 1, ix += INCX ) { t0 -= A[iaij] * X[ix]; } - X[jx] = t0; - } -/* - * End of ATL_sreftrsvLTU - */ -} diff --git a/sklearn/src/cblas/ATL_sreftrsvUNN.c b/sklearn/src/cblas/ATL_sreftrsvUNN.c deleted file mode 100644 index 6e4b465d095a6..0000000000000 --- a/sklearn/src/cblas/ATL_sreftrsvUNN.c +++ /dev/null @@ -1,95 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_sreftrsvUNN -( - const int N, - const float * A, - const int LDA, - float * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_sreftrsvUNN( ... ) - * - * <=> - * - * ATL_sreftrsv( AtlasUpper, AtlasNoTrans, AtlasNonUnit, ... ) - * - * See ATL_sreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register float t0; - int i, iaij, ix, j, jaj, jx; -/* .. - * .. Executable Statements .. - * - */ - for( j = N-1, jaj = (N-1)*LDA, jx = (N-1)*INCX; - j >= 0; j--, jaj -= LDA, jx -= INCX ) - { - X[jx] /= A[j+jaj]; t0 = X[jx]; - for( i = 0, iaij = jaj, ix = 0; i < j; i++, iaij += 1, ix += INCX ) - { X[ix] -= t0 * A[iaij]; } - } -/* - * End of ATL_sreftrsvUNN - */ -} diff --git a/sklearn/src/cblas/ATL_sreftrsvUNU.c b/sklearn/src/cblas/ATL_sreftrsvUNU.c deleted file mode 100644 index a3c2acaf76461..0000000000000 --- a/sklearn/src/cblas/ATL_sreftrsvUNU.c +++ /dev/null @@ -1,95 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_sreftrsvUNU -( - const int N, - const float * A, - const int LDA, - float * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_sreftrsvUNU( ... ) - * - * <=> - * - * ATL_sreftrsv( AtlasUpper, AtlasNoTrans, AtlasUnit, ... ) - * - * See ATL_sreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register float t0; - int i, iaij, ix, j, jaj, jx; -/* .. - * .. Executable Statements .. - * - */ - for( j = N-1, jaj = (N-1)*LDA, jx = (N-1)*INCX; - j >= 0; j--, jaj -= LDA, jx -= INCX ) - { - t0 = X[jx]; - for( i = 0, iaij = jaj, ix = 0; i < j; i++, iaij += 1, ix += INCX ) - { X[ix] -= t0 * A[iaij]; } - } -/* - * End of ATL_sreftrsvUNU - */ -} diff --git a/sklearn/src/cblas/ATL_sreftrsvUTN.c b/sklearn/src/cblas/ATL_sreftrsvUTN.c deleted file mode 100644 index 6a689fa0ebcc2..0000000000000 --- a/sklearn/src/cblas/ATL_sreftrsvUTN.c +++ /dev/null @@ -1,95 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_sreftrsvUTN -( - const int N, - const float * A, - const int LDA, - float * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_sreftrsvUTN( ... ) - * - * <=> - * - * ATL_sreftrsv( AtlasUpper, AtlasTrans, AtlasNonUnit, ... ) - * - * See ATL_sreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register float t0; - int i, iaij, ix, j, jaj, jx; -/* .. - * .. Executable Statements .. - * - */ - for( j = 0, jaj = 0,jx = 0; j < N; j++, jaj += LDA, jx += INCX ) - { - t0 = X[jx]; - for( i = 0, iaij = jaj, ix = 0; i < j; i++, iaij += 1, ix += INCX ) - { t0 -= A[iaij] * X[ix]; } - t0 /= A[iaij]; X[jx] = t0; - } -/* - * End of ATL_sreftrsvUTN - */ -} diff --git a/sklearn/src/cblas/ATL_sreftrsvUTU.c b/sklearn/src/cblas/ATL_sreftrsvUTU.c deleted file mode 100644 index 244700aa6e9c4..0000000000000 --- a/sklearn/src/cblas/ATL_sreftrsvUTU.c +++ /dev/null @@ -1,95 +0,0 @@ -/* --------------------------------------------------------------------- - * - * -- Automatically Tuned Linear Algebra Software (ATLAS) - * (C) Copyright 2000 All Rights Reserved - * - * -- ATLAS routine -- Version 3.9.24 -- December 25, 2000 - * - * Author : Antoine P. Petitet - * Originally developed at the University of Tennessee, - * Innovative Computing Laboratory, Knoxville TN, 37996-1301, USA. - * - * --------------------------------------------------------------------- - * - * -- Copyright notice and Licensing terms: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in - * the documentation and/or other materials provided with the distri- - * bution. - * 3. The name of the University, the ATLAS group, or the names of its - * contributors may not be used to endorse or promote products deri- - * ved from this software without specific written permission. - * - * -- Disclaimer: - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO- - * RY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (IN- - * CLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --------------------------------------------------------------------- - */ -/* - * Include files - */ -#include "atlas_refmisc.h" -#include "atlas_reflvl2.h" -#include "atlas_reflevel2.h" - -void ATL_sreftrsvUTU -( - const int N, - const float * A, - const int LDA, - float * X, - const int INCX -) -{ -/* - * Purpose - * ======= - * - * ATL_sreftrsvUTU( ... ) - * - * <=> - * - * ATL_sreftrsv( AtlasUpper, AtlasTrans, AtlasUnit, ... ) - * - * See ATL_sreftrsv for details. - * - * --------------------------------------------------------------------- - */ -/* - * .. Local Variables .. - */ - register float t0; - int i, iaij, ix, j, jaj, jx; -/* .. - * .. Executable Statements .. - * - */ - for( j = 0, jaj = 0, jx = 0; j < N; j++, jaj += LDA, jx += INCX ) - { - t0 = X[jx]; - for( i = 0, iaij = jaj, ix = 0; i < j; i++, iaij += 1, ix += INCX ) - { t0 -= A[iaij] * X[ix]; } - X[jx] = t0; - } -/* - * End of ATL_sreftrsvUTU - */ -} diff --git a/sklearn/src/cblas/README.txt b/sklearn/src/cblas/README.txt index 2c877b9143a5d..98c3adbb1a194 100644 --- a/sklearn/src/cblas/README.txt +++ b/sklearn/src/cblas/README.txt @@ -1,13 +1,11 @@ +This is a stripped-down version of CBLAS (C-interface to the Basic Linear +Algebra Subroutines), containing only those parts used by scikit-learn's +C/C++/Cython extensions. It is used when no CBLAS implementation is available +at build time. -This is a stripped-down version of CBLAS. +Sources here are taken from the reference implementation in ATLAS. To add new +algorithms, the only thing that should be done is to copy the reference +implementation from ${ATLAS}/src/blas/reference/level* into this directory. -Sources are taken from ATLAS 3.9.25. To avoid ATLAS' build system, we -only ship the reference implementation for the algorithms we need, -which can be found at -$(prefix)/ATLAS/src/blas/reference/level*. Header files are taken from -$(prefix)/ATLAS/include, the only change being the inclusion of -"atlas_refalias*.h" into its respective "atlas_level*.h" file. - -To add new algorithms, the only thing that should be done is to copy -the reference implementation from -$(prefix)/ATLAS/src/blas/reference/level* into this directory. +Header files are taken from ${ATLAS}/include, the only change being the +inclusion of "atlas_refalias*.h" into its respective "atlas_level*.h" file. diff --git a/sklearn/src/cblas/cblas_dasum.c b/sklearn/src/cblas/cblas_dasum.c new file mode 100644 index 0000000000000..ee9591c475bb4 --- /dev/null +++ b/sklearn/src/cblas/cblas_dasum.c @@ -0,0 +1,44 @@ +/* + * Automatically Tuned Linear Algebra Software v3.10.1 + * (C) Copyright 1999 R. Clint Whaley + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions, and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the ATLAS group or the names of its contributers may + * not be used to endorse or promote products derived from this + * software without specific written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ATLAS GROUP OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#define DREAL +#include "atlas_misc.h" +#ifdef ATL_USEPTHREADS + #include "atlas_ptalias1.h" +#endif +#include "atlas_level1.h" +#include "cblas.h" + +double cblas_dasum(const int N, const double *X, const int incX) +{ + if (N > 0 && incX > 0) + return(ATL_dasum(N, X, incX)); + return(0.0); +} diff --git a/sklearn/src/cblas/cblas_dtrsv.c b/sklearn/src/cblas/cblas_dtrsv.c deleted file mode 100644 index cf98014167578..0000000000000 --- a/sklearn/src/cblas/cblas_dtrsv.c +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Automatically Tuned Linear Algebra Software v3.9.25 - * (C) Copyright 1999 R. Clint Whaley - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the ATLAS group or the names of its contributers may - * not be used to endorse or promote products derived from this - * software without specific written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ATLAS GROUP OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - */ - -#define DREAL -#include "atlas_misc.h" -#include "cblas.h" -#ifdef ATL_USEPTHREADS - #include "atlas_ptalias2.h" -#endif -#include "atlas_level2.h" - -void cblas_dtrsv(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, - const enum CBLAS_TRANSPOSE TA, const enum CBLAS_DIAG Diag, - const int N, const double *A, const int lda, - double *X, const int incX) -{ - int info = 2000; - enum CBLAS_UPLO uplo; - enum CBLAS_TRANSPOSE ta; - #define x X - -#ifndef NoCblasErrorChecks - if (Order != CblasColMajor && Order != CblasRowMajor) - info = cblas_errprn(1, info, "Order must be %d or %d, but is set to %d", - CblasRowMajor, CblasColMajor, Order); - if (Uplo != CblasUpper && Uplo != CblasLower) - info = cblas_errprn(2, info, "UPLO must be %d or %d, but is set to %d", - CblasUpper, CblasLower, Uplo); - if (TA != CblasNoTrans && TA != CblasTrans && TA != CblasConjTrans) - info = cblas_errprn(3, info, - "TransA must be %d, %d or %d, but is set to %d", - CblasNoTrans, CblasTrans, CblasConjTrans, TA); - if (Diag != CblasUnit && Diag != CblasNonUnit) - info = cblas_errprn(4, info, "DIAG must be %d or %d, but is set to %d", - CblasUnit, CblasNonUnit, Diag); - - if (N < 0) info = cblas_errprn(5, info, - "N cannot be less than zero; is set to %d.", N); - if (lda < N || lda < 1) - info = cblas_errprn(7, info, "lda must be >= MAX(N,1): lda=%d N=%d", - lda, N); - if (!incX) info = cblas_errprn(9, info, - "incX cannot be zero; is set to %d.", incX); - if (info != 2000) - { - cblas_xerbla(info, "cblas_dtrsv", ""); - return; - } -#endif - if (incX < 0) x += (1-N)*incX; - if (Order == CblasColMajor) - ATL_dtrsv(Uplo, TA, Diag, N, A, lda, x, incX); - else - { - uplo = ( (Uplo == CblasUpper) ? CblasLower : CblasUpper ); - if (TA == CblasNoTrans) ta = CblasTrans; - else ta = CblasNoTrans; - ATL_dtrsv(uplo, ta, Diag, N, A, lda, x, incX); - } -} diff --git a/sklearn/src/cblas/cblas_strsv.c b/sklearn/src/cblas/cblas_strsv.c deleted file mode 100644 index 367ffded02f14..0000000000000 --- a/sklearn/src/cblas/cblas_strsv.c +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Automatically Tuned Linear Algebra Software v3.9.25 - * (C) Copyright 1999 R. Clint Whaley - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the ATLAS group or the names of its contributers may - * not be used to endorse or promote products derived from this - * software without specific written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ATLAS GROUP OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - */ - -#define SREAL -#include "atlas_misc.h" -#include "cblas.h" -#ifdef ATL_USEPTHREADS - #include "atlas_ptalias2.h" -#endif -#include "atlas_level2.h" - -void cblas_strsv(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, - const enum CBLAS_TRANSPOSE TA, const enum CBLAS_DIAG Diag, - const int N, const float *A, const int lda, - float *X, const int incX) -{ - int info = 2000; - enum CBLAS_UPLO uplo; - enum CBLAS_TRANSPOSE ta; - #define x X - -#ifndef NoCblasErrorChecks - if (Order != CblasColMajor && Order != CblasRowMajor) - info = cblas_errprn(1, info, "Order must be %d or %d, but is set to %d", - CblasRowMajor, CblasColMajor, Order); - if (Uplo != CblasUpper && Uplo != CblasLower) - info = cblas_errprn(2, info, "UPLO must be %d or %d, but is set to %d", - CblasUpper, CblasLower, Uplo); - if (TA != CblasNoTrans && TA != CblasTrans && TA != CblasConjTrans) - info = cblas_errprn(3, info, - "TransA must be %d, %d or %d, but is set to %d", - CblasNoTrans, CblasTrans, CblasConjTrans, TA); - if (Diag != CblasUnit && Diag != CblasNonUnit) - info = cblas_errprn(4, info, "DIAG must be %d or %d, but is set to %d", - CblasUnit, CblasNonUnit, Diag); - - if (N < 0) info = cblas_errprn(5, info, - "N cannot be less than zero; is set to %d.", N); - if (lda < N || lda < 1) - info = cblas_errprn(7, info, "lda must be >= MAX(N,1): lda=%d N=%d", - lda, N); - if (!incX) info = cblas_errprn(9, info, - "incX cannot be zero; is set to %d.", incX); - if (info != 2000) - { - cblas_xerbla(info, "cblas_strsv", ""); - return; - } -#endif - if (incX < 0) x += (1-N)*incX; - if (Order == CblasColMajor) - ATL_strsv(Uplo, TA, Diag, N, A, lda, x, incX); - else - { - uplo = ( (Uplo == CblasUpper) ? CblasLower : CblasUpper ); - if (TA == CblasNoTrans) ta = CblasTrans; - else ta = CblasNoTrans; - ATL_strsv(uplo, ta, Diag, N, A, lda, x, incX); - } -} diff --git a/sklearn/svm/__init__.py b/sklearn/svm/__init__.py index 43db02eb94f11..d11002a1fde5d 100644 --- a/sklearn/svm/__init__.py +++ b/sklearn/svm/__init__.py @@ -8,13 +8,15 @@ # Author: Fabian Pedregosa with help from # the scikit-learn community. LibSVM and LibLinear are copyright # of their respective owners. -# License: New BSD, (C) INRIA 2010 +# License: BSD 3 clause (C) INRIA 2010 -from .classes import SVC, NuSVC, SVR, NuSVR, OneClassSVM, LinearSVC +from .classes import SVC, NuSVC, SVR, NuSVR, OneClassSVM, LinearSVC, \ + LinearSVR from .bounds import l1_min_c -from . import sparse, libsvm, liblinear, libsvm_sparse +from . import libsvm, liblinear, libsvm_sparse __all__ = ['LinearSVC', + 'LinearSVR', 'NuSVC', 'NuSVR', 'OneClassSVM', @@ -23,5 +25,4 @@ 'l1_min_c', 'liblinear', 'libsvm', - 'libsvm_sparse', - 'sparse'] + 'libsvm_sparse'] diff --git a/sklearn/svm/base.py b/sklearn/svm/base.py index bcd06a98151d8..f40e9063080f4 100644 --- a/sklearn/svm/base.py +++ b/sklearn/svm/base.py @@ -1,3 +1,5 @@ +from __future__ import print_function + import numpy as np import scipy.sparse as sp import warnings @@ -7,33 +9,15 @@ from . import libsvm_sparse from ..base import BaseEstimator, ClassifierMixin from ..preprocessing import LabelEncoder -from ..utils import atleast2d_or_csr, array2d +from ..utils import check_array, check_random_state, column_or_1d +from ..utils import ConvergenceWarning, compute_class_weight from ..utils.extmath import safe_sparse_dot - +from ..utils.validation import check_is_fitted +from ..externals import six LIBSVM_IMPL = ['c_svc', 'nu_svc', 'one_class', 'epsilon_svr', 'nu_svr'] -def _get_class_weight(class_weight, y): - """Estimate class weights for unbalanced datasets.""" - if class_weight == 'auto': - uy = np.unique(y) - weight_label = np.asarray(uy, dtype=np.int32, order='C') - weight = np.array([1.0 / np.sum(y == i) for i in uy], - dtype=np.float64, order='C') - weight *= uy.shape[0] / np.sum(weight) - else: - if class_weight is None: - keys = values = [] - else: - keys = class_weight.keys() - values = class_weight.values() - weight = np.asarray(values, dtype=np.float64, order='C') - weight_label = np.asarray(keys, dtype=np.int32, order='C') - - return weight, weight_label - - def _one_vs_one_coef(dual_coef, n_support, support_vectors): """Generate primal coefficients from dual coefficients for the one-vs-one multi class LibSVM in the case @@ -49,10 +33,10 @@ def _one_vs_one_coef(dual_coef, n_support, support_vectors): # would have to take care in the sparse case coef = [] sv_locs = np.cumsum(np.hstack([[0], n_support])) - for class1 in xrange(n_class): + for class1 in range(n_class): # SVs for class1: sv1 = support_vectors[sv_locs[class1]:sv_locs[class1 + 1], :] - for class2 in xrange(class1 + 1, n_class): + for class2 in range(class1 + 1, n_class): # SVs for class1: sv2 = support_vectors[sv_locs[class2]:sv_locs[class2 + 1], :] @@ -63,36 +47,33 @@ def _one_vs_one_coef(dual_coef, n_support, support_vectors): # build weight for class1 vs class2 coef.append(safe_sparse_dot(alpha1, sv1) - + safe_sparse_dot(alpha2, sv2)) + + safe_sparse_dot(alpha2, sv2)) return coef -class BaseLibSVM(BaseEstimator): +class BaseLibSVM(six.with_metaclass(ABCMeta, BaseEstimator)): """Base class for estimators that use libsvm as backing library This implements support vector machine classification and regression. + + Parameter documentation is in the derived `SVC` class. """ - __metaclass__ = ABCMeta + # The order of these must match the integer values in LibSVM. + # XXX These are actually the same in the dense case. Need to factor + # this out. _sparse_kernels = ["linear", "poly", "rbf", "sigmoid", "precomputed"] @abstractmethod def __init__(self, impl, kernel, degree, gamma, coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, - sparse, class_weight, verbose): + class_weight, verbose, max_iter, random_state): - if not impl in LIBSVM_IMPL: + if impl not in LIBSVM_IMPL: # pragma: no cover raise ValueError("impl should be one of %s, %s was given" % ( LIBSVM_IMPL, impl)) - if C is None: - warnings.warn("Using 'None' for C of BaseLibSVM is deprecated " - "since version 0.12, and backward compatibility " - "won't be maintained from version 0.14 onward. " - "Setting C=1.0.", DeprecationWarning, stacklevel=2) - C = 1.0 - - self.impl = impl + self._impl = impl self.kernel = kernel self.degree = degree self.gamma = gamma @@ -104,30 +85,33 @@ def __init__(self, impl, kernel, degree, gamma, coef0, self.shrinking = shrinking self.probability = probability self.cache_size = cache_size - self.sparse = sparse self.class_weight = class_weight self.verbose = verbose + self.max_iter = max_iter + self.random_state = random_state @property def _pairwise(self): + # Used by cross_val_score. kernel = self.kernel - return kernel == "precomputed" or hasattr(kernel, "__call__") + return kernel == "precomputed" or callable(kernel) def fit(self, X, y, sample_weight=None): """Fit the SVM model according to the given training data. Parameters ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] + X : {array-like, sparse matrix}, shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. - y : array-like, shape = [n_samples] - Target values (integers in classification, real numbers in + y : array-like, shape (n_samples,) + Target values (class labels in classification, real numbers in regression) - sample_weight : array-like, shape = [n_samples], optional - Weights applied to individual samples (1. for unweighted). + sample_weight : array-like, shape (n_samples,) + Per-sample weights. Rescale C per sample. Higher weights + force the classifier to put more emphasis on these points. Returns ------- @@ -143,28 +127,20 @@ def fit(self, X, y, sample_weight=None): matrices as input. """ - if self.sparse == "auto": - self._sparse = sp.isspmatrix(X) and not self._pairwise - else: - self._sparse = self.sparse - - if self._sparse and self._pairwise: - raise ValueError("Sparse precomputed kernels are not supported. " - "Using sparse data and dense kernels is possible by not " - "using the ``sparse`` parameter") + rnd = check_random_state(self.random_state) - X = atleast2d_or_csr(X, dtype=np.float64, order='C') - y = np.asarray(y, dtype=np.float64, order='C') + sparse = sp.isspmatrix(X) + if sparse and self.kernel == "precomputed": + raise TypeError("Sparse precomputed kernels are not supported.") + self._sparse = sparse and not callable(self.kernel) - if self.impl != "one_class" and len(np.unique(y)) < 2: - raise ValueError("The number of classes has to be greater than" - " one.") + X = check_array(X, accept_sparse='csr', dtype=np.float64, order='C') + y = self._validate_targets(y) - sample_weight = np.asarray([] if sample_weight is None - else sample_weight, dtype=np.float64) - solver_type = LIBSVM_IMPL.index(self.impl) - self.class_weight_, self.class_weight_label_ = \ - _get_class_weight(self.class_weight, y) + sample_weight = np.asarray([] + if sample_weight is None + else sample_weight, dtype=np.float64) + solver_type = LIBSVM_IMPL.index(self._impl) # input validation if solver_type != 2 and X.shape[0] != y.shape[0]: @@ -176,7 +152,7 @@ def fit(self, X, y, sample_weight=None): raise ValueError("X.shape[0] should be equal to X.shape[1]") if sample_weight.shape[0] > 0 and sample_weight.shape[0] != X.shape[0]: - raise ValueError("sample_weight and X have incompatible shapes:" + raise ValueError("sample_weight and X have incompatible shapes: " "%r vs %r\n" "Note: Sparse matrices cannot be indexed w/" "boolean masks (use `indices=True` in CV)." @@ -189,66 +165,102 @@ def fit(self, X, y, sample_weight=None): self._gamma = self.gamma kernel = self.kernel - if hasattr(kernel, '__call__'): + if callable(kernel): kernel = 'precomputed' fit = self._sparse_fit if self._sparse else self._dense_fit - if self.verbose: - print '[LibSVM]', - fit(X, y, sample_weight, solver_type, kernel) + if self.verbose: # pragma: no cover + print('[LibSVM]', end='') + + seed = rnd.randint(np.iinfo('i').max) + fit(X, y, sample_weight, solver_type, kernel, random_seed=seed) + # see comment on the other call to np.iinfo in this file self.shape_fit_ = X.shape # In binary case, we need to flip the sign of coef, intercept and - # decision function. Use self._intercept_ internally. + # decision function. Use self._intercept_ and self._dual_coef_ internally. self._intercept_ = self.intercept_.copy() - if len(self.label_) == 2 and self.impl != 'one_class': + self._dual_coef_ = self.dual_coef_ + if self._impl in ['c_svc', 'nu_svc'] and len(self.classes_) == 2: self.intercept_ *= -1 + self.dual_coef_ = -self.dual_coef_ + return self - def _dense_fit(self, X, y, sample_weight, solver_type, kernel): + def _validate_targets(self, y): + """Validation of y and class_weight. - if hasattr(self.kernel, '__call__'): + Default implementation for SVR and one-class; overridden in BaseSVC. + """ + # XXX this is ugly. + # Regression models should not have a class_weight_ attribute. + self.class_weight_ = np.empty(0) + return np.asarray(y, dtype=np.float64, order='C') + + def _warn_from_fit_status(self): + assert self.fit_status_ in (0, 1) + if self.fit_status_ == 1: + warnings.warn('Solver terminated early (max_iter=%i).' + ' Consider pre-processing your data with' + ' StandardScaler or MinMaxScaler.' + % self.max_iter, ConvergenceWarning) + + def _dense_fit(self, X, y, sample_weight, solver_type, kernel, + random_seed): + if callable(self.kernel): # you must store a reference to X to compute the kernel in predict # TODO: add keyword copy to copy on demand self.__Xfit = X X = self._compute_kernel(X) - if hasattr(self.kernel, '__call__') and X.shape[0] != X.shape[1]: - raise ValueError("X.shape[0] should be equal to X.shape[1]") + if X.shape[0] != X.shape[1]: + raise ValueError("X.shape[0] should be equal to X.shape[1]") libsvm.set_verbosity_wrap(self.verbose) # we don't pass **self.get_params() to allow subclasses to # add other parameters to __init__ self.support_, self.support_vectors_, self.n_support_, \ - self.dual_coef_, self.intercept_, self.label_, self.probA_, \ - self.probB_ = libsvm.fit(X, y, - svm_type=solver_type, sample_weight=sample_weight, - class_weight=self.class_weight_, - class_weight_label=self.class_weight_label_, - kernel=kernel, C=self.C, nu=self.nu, - probability=self.probability, degree=self.degree, - shrinking=self.shrinking, tol=self.tol, cache_size=self.cache_size, - coef0=self.coef0, gamma=self._gamma, epsilon=self.epsilon) - - def _sparse_fit(self, X, y, sample_weight, solver_type, kernel): + self.dual_coef_, self.intercept_, self.probA_, \ + self.probB_, self.fit_status_ = libsvm.fit( + X, y, + svm_type=solver_type, sample_weight=sample_weight, + class_weight=self.class_weight_, kernel=kernel, C=self.C, + nu=self.nu, probability=self.probability, degree=self.degree, + shrinking=self.shrinking, tol=self.tol, + cache_size=self.cache_size, coef0=self.coef0, + gamma=self._gamma, epsilon=self.epsilon, + max_iter=self.max_iter, random_seed=random_seed) + + self._warn_from_fit_status() + + def _sparse_fit(self, X, y, sample_weight, solver_type, kernel, + random_seed): X.data = np.asarray(X.data, dtype=np.float64, order='C') + X.sort_indices() kernel_type = self._sparse_kernels.index(kernel) libsvm_sparse.set_verbosity_wrap(self.verbose) - self.support_vectors_, dual_coef_data, self.intercept_, self.label_, \ - self.n_support_, self.probA_, self.probB_ = \ + self.support_, self.support_vectors_, dual_coef_data, \ + self.intercept_, self.n_support_, \ + self.probA_, self.probB_, self.fit_status_ = \ libsvm_sparse.libsvm_sparse_train( - X.shape[1], X.data, X.indices, X.indptr, y, solver_type, - kernel_type, self.degree, self._gamma, self.coef0, self.tol, - self.C, self.class_weight_label_, self.class_weight_, - sample_weight, self.nu, self.cache_size, self.epsilon, - int(self.shrinking), int(self.probability)) - - n_class = len(self.label_) - 1 + X.shape[1], X.data, X.indices, X.indptr, y, solver_type, + kernel_type, self.degree, self._gamma, self.coef0, self.tol, + self.C, self.class_weight_, + sample_weight, self.nu, self.cache_size, self.epsilon, + int(self.shrinking), int(self.probability), self.max_iter, + random_seed) + + self._warn_from_fit_status() + + if hasattr(self, "classes_"): + n_class = len(self.classes_) - 1 + else: # regression + n_class = 1 n_SV = self.support_vectors_.shape[0] dual_coef_indices = np.tile(np.arange(n_SV), n_class) @@ -259,21 +271,17 @@ def _sparse_fit(self, X, y, sample_weight, solver_type, kernel): (n_class, n_SV)) def predict(self, X): - """Perform classification or regression samples in X. - - For a classification model, the predicted class for each - sample in X is returned. For a regression model, the function - value of X calculated is returned. + """Perform regression on samples in X. For an one-class model, +1 or -1 is returned. Parameters ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] + X : {array-like, sparse matrix}, shape (n_samples, n_features) Returns ------- - y_pred : array, shape = [n_samples] + y_pred : array, shape (n_samples,) """ X = self._validate_for_predict(X) predict = self._sparse_predict if self._sparse else self._dense_predict @@ -283,35 +291,29 @@ def _dense_predict(self, X): n_samples, n_features = X.shape X = self._compute_kernel(X) if X.ndim == 1: - X = array2d(X, order='C') + X = check_array(X, order='C') kernel = self.kernel - if hasattr(self.kernel, "__call__"): + if callable(self.kernel): kernel = 'precomputed' if X.shape[1] != self.shape_fit_[0]: raise ValueError("X.shape[1] = %d should be equal to %d, " "the number of samples at training time" % (X.shape[1], self.shape_fit_[0])) - C = 0.0 # C is not useful here - - svm_type = LIBSVM_IMPL.index(self.impl) + svm_type = LIBSVM_IMPL.index(self._impl) return libsvm.predict( X, self.support_, self.support_vectors_, self.n_support_, - self.dual_coef_, self._intercept_, - self.label_, self.probA_, self.probB_, - svm_type=svm_type, - kernel=kernel, C=C, nu=self.nu, - probability=self.probability, degree=self.degree, - shrinking=self.shrinking, tol=self.tol, cache_size=self.cache_size, - coef0=self.coef0, gamma=self._gamma, epsilon=self.epsilon) + self._dual_coef_, self._intercept_, + self.probA_, self.probB_, svm_type=svm_type, kernel=kernel, + degree=self.degree, coef0=self.coef0, gamma=self._gamma, + cache_size=self.cache_size) def _sparse_predict(self, X): - X = sp.csr_matrix(X, dtype=np.float64) - + # Precondition: X is a csr_matrix of dtype np.float64. kernel = self.kernel - if hasattr(kernel, '__call__'): + if callable(kernel): kernel = 'precomputed' kernel_type = self._sparse_kernels.index(kernel) @@ -319,21 +321,21 @@ def _sparse_predict(self, X): C = 0.0 # C is not useful here return libsvm_sparse.libsvm_sparse_predict( - X.data, X.indices, X.indptr, - self.support_vectors_.data, - self.support_vectors_.indices, - self.support_vectors_.indptr, - self.dual_coef_.data, self._intercept_, - LIBSVM_IMPL.index(self.impl), kernel_type, - self.degree, self._gamma, self.coef0, self.tol, - C, self.class_weight_label_, self.class_weight_, - self.nu, self.epsilon, self.shrinking, - self.probability, self.n_support_, self.label_, - self.probA_, self.probB_) + X.data, X.indices, X.indptr, + self.support_vectors_.data, + self.support_vectors_.indices, + self.support_vectors_.indptr, + self._dual_coef_.data, self._intercept_, + LIBSVM_IMPL.index(self._impl), kernel_type, + self.degree, self._gamma, self.coef0, self.tol, + C, self.class_weight_, + self.nu, self.epsilon, self.shrinking, + self.probability, self.n_support_, + self.probA_, self.probB_) def _compute_kernel(self, X): """Return the data transformed by a callable kernel""" - if hasattr(self.kernel, '__call__'): + if callable(self.kernel): # in the case of precomputed kernel given as a function, we # have to compute explicitly the kernel matrix kernel = self.kernel(X, self.__Xfit) @@ -355,41 +357,43 @@ def decision_function(self, X): Returns the decision function of the sample for each class in the model. """ - if self._sparse: - raise NotImplementedError("decision_function not supported for" - " sparse SVM") - + # NOTE: _validate_for_predict contains check for is_fitted + # hence must be placed before any other attributes are used. X = self._validate_for_predict(X) - - C = 0.0 # C is not useful here + if self._sparse: + raise NotImplementedError("Decision_function not supported for" + " sparse SVM.") + X = self._compute_kernel(X) kernel = self.kernel - if hasattr(kernel, '__call__'): + if callable(kernel): kernel = 'precomputed' dec_func = libsvm.decision_function( X, self.support_, self.support_vectors_, self.n_support_, - self.dual_coef_, self._intercept_, self.label_, + self._dual_coef_, self._intercept_, self.probA_, self.probB_, - svm_type=LIBSVM_IMPL.index(self.impl), - kernel=kernel, C=C, nu=self.nu, - probability=self.probability, degree=self.degree, - shrinking=self.shrinking, tol=self.tol, cache_size=self.cache_size, - coef0=self.coef0, gamma=self._gamma, epsilon=self.epsilon) + svm_type=LIBSVM_IMPL.index(self._impl), + kernel=kernel, degree=self.degree, cache_size=self.cache_size, + coef0=self.coef0, gamma=self._gamma) # In binary case, we need to flip the sign of coef, intercept and # decision function. - if len(self.label_) == 2 and self.impl != 'one_class': - return -dec_func + if self._impl in ['c_svc', 'nu_svc'] and len(self.classes_) == 2: + return -dec_func.ravel() return dec_func def _validate_for_predict(self, X): - X = atleast2d_or_csr(X, dtype=np.float64, order="C") + check_is_fitted(self, 'support_') + + X = check_array(X, accept_sparse='csr', dtype=np.float64, order="C") if self._sparse and not sp.isspmatrix(X): X = sp.csr_matrix(X) - if (sp.issparse(X) and not self._sparse and - not hasattr(self.kernel, '__call__')): + if self._sparse: + X.sort_indices() + + if sp.issparse(X) and not self._sparse and not callable(self.kernel): raise ValueError( "cannot use sparse input in %r trained on dense data" % type(self).__name__) @@ -412,20 +416,10 @@ def coef_(self): raise ValueError('coef_ is only available when using a ' 'linear kernel') - if self.dual_coef_.shape[0] == 1: - # binary classifier - coef = -safe_sparse_dot(self.dual_coef_, self.support_vectors_) - else: - # 1vs1 classifier - coef = _one_vs_one_coef(self.dual_coef_, self.n_support_, - self.support_vectors_) - if sp.issparse(coef[0]): - coef = sp.vstack(coef).tocsr() - else: - coef = np.vstack(coef) + coef = self._get_coef() - # coef_ being a read-only property it's better to mark the value as - # immutable to avoid hiding potential bugs for the unsuspecting user + # coef_ being a read-only property, it's better to mark the value as + # immutable to avoid hiding potential bugs for the unsuspecting user. if sp.issparse(coef): # sparse matrix do not have global flags coef.data.flags.writeable = False @@ -434,11 +428,57 @@ def coef_(self): coef.flags.writeable = False return coef + def _get_coef(self): + return safe_sparse_dot(self._dual_coef_, self.support_vectors_) + class BaseSVC(BaseLibSVM, ClassifierMixin): """ABC for LibSVM-based classifiers.""" - def predict_proba(self, X): + def _validate_targets(self, y): + y_ = column_or_1d(y, warn=True) + cls, y = np.unique(y_, return_inverse=True) + self.class_weight_ = compute_class_weight(self.class_weight, cls, y_) + if len(cls) < 2: + raise ValueError( + "The number of classes has to be greater than one; got %d" + % len(cls)) + + self.classes_ = cls + + return np.asarray(y, dtype=np.float64, order='C') + + def predict(self, X): + """Perform classification on samples in X. + + For an one-class model, +1 or -1 is returned. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + + Returns + ------- + y_pred : array, shape = [n_samples] + Class labels for samples in X. + """ + y = super(BaseSVC, self).predict(X) + return self.classes_.take(np.asarray(y, dtype=np.intp)) + + # Hacky way of getting predict_proba to raise an AttributeError when + # probability=False using properties. Do not use this in new code; when + # probabilities are not available depending on a setting, introduce two + # estimators. + def _check_proba(self): + if not self.probability: + raise AttributeError("predict_proba is not available when" + " probability=%r" % self.probability) + if self._impl not in ('c_svc', 'nu_svc'): + raise AttributeError("predict_proba only implemented for SVC" + " and NuSVC") + + @property + def predict_proba(self): """Compute probabilities of possible outcomes for samples in X. The model need to have probability information computed at training @@ -450,10 +490,10 @@ def predict_proba(self, X): Returns ------- - X : array-like, shape = [n_samples, n_classes] + T : array-like, shape = [n_samples, n_classes] Returns the probability of the sample for each class in - the model, where classes are ordered by arithmetical - order. + the model. The columns correspond to the classes in sorted + order, as they appear in the attribute `classes_`. Notes ----- @@ -462,20 +502,17 @@ def predict_proba(self, X): predict. Also, it will produce meaningless results on very small datasets. """ - if not self.probability: - raise NotImplementedError( - "probability estimates must be enabled to use this method") - - if self.impl not in ('c_svc', 'nu_svc'): - raise NotImplementedError("predict_proba only implemented for SVC " - "and NuSVC") + self._check_proba() + return self._predict_proba + def _predict_proba(self, X): X = self._validate_for_predict(X) - pred_proba = self._sparse_predict_proba if self._sparse \ - else self._dense_predict_proba + pred_proba = (self._sparse_predict_proba + if self._sparse else self._dense_predict_proba) return pred_proba(X) - def predict_log_proba(self, X): + @property + def predict_log_proba(self): """Compute log probabilities of possible outcomes for samples in X. The model need to have probability information computed at training @@ -487,10 +524,10 @@ def predict_log_proba(self, X): Returns ------- - X : array-like, shape = [n_samples, n_classes] + T : array-like, shape = [n_samples, n_classes] Returns the log-probabilities of the sample for each class in - the model, where classes are ordered by arithmetical - order. + the model. The columns correspond to the classes in sorted + order, as they appear in the attribute `classes_`. Notes ----- @@ -499,26 +536,26 @@ def predict_log_proba(self, X): predict. Also, it will produce meaningless results on very small datasets. """ + self._check_proba() + return self._predict_log_proba + + def _predict_log_proba(self, X): return np.log(self.predict_proba(X)) def _dense_predict_proba(self, X): X = self._compute_kernel(X) - C = 0.0 # C is not useful here - kernel = self.kernel - if hasattr(kernel, '__call__'): + if callable(kernel): kernel = 'precomputed' - svm_type = LIBSVM_IMPL.index(self.impl) + svm_type = LIBSVM_IMPL.index(self._impl) pprob = libsvm.predict_proba( X, self.support_, self.support_vectors_, self.n_support_, - self.dual_coef_, self._intercept_, self.label_, + self._dual_coef_, self._intercept_, self.probA_, self.probB_, - svm_type=svm_type, kernel=kernel, C=C, nu=self.nu, - probability=self.probability, degree=self.degree, - shrinking=self.shrinking, tol=self.tol, cache_size=self.cache_size, - coef0=self.coef0, gamma=self._gamma, epsilon=self.epsilon) + svm_type=svm_type, kernel=kernel, degree=self.degree, + cache_size=self.cache_size, coef0=self.coef0, gamma=self._gamma) return pprob @@ -526,7 +563,7 @@ def _sparse_predict_proba(self, X): X.data = np.asarray(X.data, dtype=np.float64, order='C') kernel = self.kernel - if hasattr(kernel, '__call__'): + if callable(kernel): kernel = 'precomputed' kernel_type = self._sparse_kernels.index(kernel) @@ -536,164 +573,242 @@ def _sparse_predict_proba(self, X): self.support_vectors_.data, self.support_vectors_.indices, self.support_vectors_.indptr, - self.dual_coef_.data, self._intercept_, - LIBSVM_IMPL.index(self.impl), kernel_type, + self._dual_coef_.data, self._intercept_, + LIBSVM_IMPL.index(self._impl), kernel_type, self.degree, self._gamma, self.coef0, self.tol, - self.C, self.class_weight_label_, self.class_weight_, + self.C, self.class_weight_, self.nu, self.epsilon, self.shrinking, - self.probability, self.n_support_, self.label_, + self.probability, self.n_support_, self.probA_, self.probB_) + def _get_coef(self): + if self.dual_coef_.shape[0] == 1: + # binary classifier + coef = safe_sparse_dot(self.dual_coef_, self.support_vectors_) + else: + # 1vs1 classifier + coef = _one_vs_one_coef(self.dual_coef_, self.n_support_, + self.support_vectors_) + if sp.issparse(coef[0]): + coef = sp.vstack(coef).tocsr() + else: + coef = np.vstack(coef) -class BaseLibLinear(BaseEstimator): - """Base for classes binding liblinear (dense and sparse versions)""" + return coef - _solver_type_dict = { - 'PL2_LLR_D0': 0, # L2 penalty, logistic regression - 'PL2_LL2_D1': 1, # L2 penalty, L2 loss, dual form - 'PL2_LL2_D0': 2, # L2 penalty, L2 loss, primal form - 'PL2_LL1_D1': 3, # L2 penalty, L1 Loss, dual form - 'MC_SVC': 4, # Multi-class Support Vector Classification - 'PL1_LL2_D0': 5, # L1 penalty, L2 Loss, primal form - 'PL1_LLR_D0': 6, # L1 penalty, logistic regression - 'PL2_LLR_D1': 7, # L2 penalty, logistic regression, dual form - } - - def __init__(self, penalty='l2', loss='l2', dual=True, tol=1e-4, C=1.0, - multi_class='ovr', fit_intercept=True, intercept_scaling=1, - class_weight=None, verbose=0): - - if C is None: - warnings.warn("Using 'None' for C of BaseLibLinear is deprecated " - "since version 0.12, and backward compatibility " - "won't be maintained from version 0.14 onward. " - "Setting C=1.0.", DeprecationWarning, stacklevel=2) - C = 1.0 - - self.penalty = penalty - self.loss = loss - self.dual = dual - self.tol = tol - self.C = C - self.fit_intercept = fit_intercept - self.intercept_scaling = intercept_scaling - self.multi_class = multi_class - self.class_weight = class_weight - self.verbose = verbose - # Check that the arguments given are valid: - self._get_solver_type() +def _get_liblinear_solver_type(multi_class, penalty, loss, dual): + """Find the liblinear magic number for the solver. - def _get_solver_type(self): - """Find the liblinear magic number for the solver. + This number depends on the values of the following attributes: + - multi_class + - penalty + - loss + - dual - This number depends on the values of the following attributes: - - multi_class - - penalty - - loss - - dual - """ - if self.multi_class == 'crammer_singer': - solver_type = 'MC_SVC' + The same number is also internally used by LibLinear to determine + which solver to use. + """ + # nested dicts containing level 1: available loss functions, + # level2: available penalties for the given loss functin, + # level3: wether the dual solver is available for the specified + # combination of loss function and penalty + _solver_type_dict = { + 'logistic_regression': { + 'l1': {False: 6}, + 'l2': {False: 0, True: 7}}, + 'hinge': { + 'l2': {True: 3}}, + 'squared_hinge': { + 'l1': {False: 5}, + 'l2': {False: 2, True: 1}}, + 'epsilon_insensitive': { + 'l2': {True: 13}}, + 'squared_epsilon_insensitive': { + 'l2': {False: 11, True: 12}}, + 'crammer_singer': 4 + } + + if multi_class == 'crammer_singer': + return _solver_type_dict[multi_class] + elif multi_class != 'ovr': + raise ValueError("`multi_class` must be one of `ovr`, " + "`crammer_singer`, got %r" % multi_class) + + # FIXME loss.lower() --> loss in 0.18 + _solver_pen = _solver_type_dict.get(loss.lower(), None) + if _solver_pen is None: + error_string = ("loss='%s' is not supported" % loss) + else: + # FIME penalty.lower() --> penalty in 0.18 + _solver_dual = _solver_pen.get(penalty.lower(), None) + if _solver_dual is None: + error_string = ("The combination of penalty='%s'" + "and loss='%s' is not supported" + % (penalty, loss)) else: - if self.multi_class != 'ovr': - raise ValueError("`multi_class` must be one of `ovr`, " - "`crammer_singer`") - solver_type = "P%s_L%s_D%d" % ( - self.penalty.upper(), self.loss.upper(), int(self.dual)) - if not solver_type in self._solver_type_dict: - if self.penalty.upper() == 'L1' and self.loss.upper() == 'L1': - error_string = ("The combination of penalty='l1' " - "and loss='l1' is not supported.") - elif self.penalty.upper() == 'L2' and self.loss.upper() == 'L1': - # this has to be in primal - error_string = ("loss='l2' and penalty='l1' is " - "only supported when dual='true'.") + solver_num = _solver_dual.get(dual, None) + if solver_num is None: + error_string = ("loss='%s' and penalty='%s'" + "are not supported when dual=%s" + % (penalty, loss, dual)) else: - # only PL1 in dual remains - error_string = ("penalty='l1' is only supported " - "when dual='false'.") - raise ValueError('Not supported set of arguments: ' - + error_string) - return self._solver_type_dict[solver_type] + return solver_num + + raise ValueError(('Unsupported set of arguments: %s, ' + 'Parameters: penalty=%r, loss=%r, dual=%r') + % (error_string, penalty, loss, dual)) - def fit(self, X, y): - """Fit the model according to the given training data. - Parameters - ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] - Training vector, where n_samples in the number of samples and - n_features is the number of features. +def _fit_liblinear(X, y, C, fit_intercept, intercept_scaling, class_weight, + penalty, dual, verbose, max_iter, tol, + random_state=None, multi_class='ovr', + loss='logistic_regression', epsilon=0.1): + """Used by Logistic Regression (and CV) and LinearSVC. - y : array-like, shape = [n_samples] - Target vector relative to X + Preprocessing is done in this function before supplying it to liblinear. - class_weight : {dict, 'auto'}, optional - Weights associated with classes. If not given, all classes - are supposed to have weight one. + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Training vector, where n_samples in the number of samples and + n_features is the number of features. - Returns - ------- - self : object - Returns self. - """ - self._enc = LabelEncoder() - y = self._enc.fit_transform(y) - if len(self.classes_) < 2: - raise ValueError("The number of classes has to be greater than" - " one.") + y : array-like, shape = [n_samples] + Target vector relative to X - X = atleast2d_or_csr(X, dtype=np.float64, order="C") - y = np.asarray(y, dtype=np.float64).ravel() + C : float + Inverse of cross-validation parameter. Lower the C, the more + the penalization. - self.class_weight_, self.class_weight_label_ = \ - _get_class_weight(self.class_weight, y) + fit_intercept : bool + Whether or not to fit the intercept, that is to add a intercept + term to the decision function. - if X.shape[0] != y.shape[0]: - raise ValueError("X and y have incompatible shapes.\n" + - "X has %s samples, but y has %s." % \ - (X.shape[0], y.shape[0])) + intercept_scaling : float + LibLinear internally penalizes the intercept and this term is subject + to regularization just like the other terms of the feature vector. + In order to avoid this, one should increase the intercept_scaling. + such that the feature vector becomes [x, intercept_scaling]. - liblinear.set_verbosity_wrap(self.verbose) + class_weight : {dict, 'auto'}, optional + Weight assigned to each class. If class_weight provided is 'auto', + then the weights provided are inverses of the frequency in the + target vector. - if sp.isspmatrix(X): - train = liblinear.csr_train_wrap - else: - train = liblinear.train_wrap + penalty : str, {'l1', 'l2'} + The norm of the penalty used in regularization. - if self.verbose: - print '[LibLinear]', - self.raw_coef_ = train(X, y, self._get_solver_type(), self.tol, - self._get_bias(), self.C, - self.class_weight_label_, self.class_weight_) + dual : bool + Dual or primal formulation, - if self.fit_intercept: - self.coef_ = self.raw_coef_[:, :-1] - self.intercept_ = self.intercept_scaling * self.raw_coef_[:, -1] - else: - self.coef_ = self.raw_coef_ - self.intercept_ = 0. + verbose : int + Set verbose to any positive number for verbosity. - return self + max_iter : int + Number of iterations. - @property - def classes_(self): - return self._enc.classes_ - - def _check_n_features(self, X): - n_features = self.coef_.shape[1] - if X.shape[1] != n_features: - raise ValueError("X.shape[1] should be %d, not %d." % (n_features, - X.shape[1])) - - def _get_bias(self): - if self.fit_intercept: - return self.intercept_scaling - else: - return -1.0 + tol : float + Stopping condition. + + random_state : int seed, RandomState instance, or None (default) + The seed of the pseudo random number generator to use when + shuffling the data. + + multi_class : str, {'ovr', 'crammer_singer'} + `ovr` trains n_classes one-vs-rest classifiers, while `crammer_singer` + optimizes a joint objective over all classes. + While `crammer_singer` is interesting from an theoretical perspective + as it is consistent it is seldom used in practice and rarely leads to + better accuracy and is more expensive to compute. + If `crammer_singer` is chosen, the options loss, penalty and dual will + be ignored. + + loss : str, {'logistic_regression', 'hinge', 'squared_hinge', + 'epsilon_insensitive', 'squared_epsilon_insensitive} + The loss function used to fit the model. + epsilon : float, optional (default=0.1) + Epsilon parameter in the epsilon-insensitive loss function. Note + that the value of this parameter depends on the scale of the target + variable y. If unsure, set epsilon=0. + + + Returns + ------- + coef_ : ndarray, shape (n_features, n_features + 1) + The coefficent vector got by minimizing the objective function. + + intercept_ : float + The intercept term added to the vector. + + n_iter_ : int + Maximum number of iterations run across all classes. + """ + # FIXME Remove case insensitivity in 0.18 --------------------- + loss_l, penalty_l = loss.lower(), penalty.lower() + + msg = ("loss='%s' has been deprecated in favor of " + "loss='%s' as of 0.16. Backward compatibility" + " for the uppercase notation will be removed in %s") + if (not loss.islower()) and loss_l not in ('l1', 'l2'): + warnings.warn(msg % (loss, loss_l, "0.18"), + DeprecationWarning) + if not penalty.islower(): + warnings.warn(msg.replace("loss", "penalty") + % (penalty, penalty_l, "0.18"), + DeprecationWarning) + # ------------------------------------------------------------- + + # FIXME loss_l --> loss in 0.18 + if loss_l not in ['epsilon_insensitive', 'squared_epsilon_insensitive']: + enc = LabelEncoder() + y_ind = enc.fit_transform(y) + classes_ = enc.classes_ + if len(classes_) < 2: + raise ValueError("This solver needs samples of at least 2 classes" + " in the data, but the data contains only one" + " class: %r" % classes_[0]) + + class_weight_ = compute_class_weight(class_weight, classes_, y) + else: + class_weight_ = np.empty(0, dtype=np.float) + y_ind = y + liblinear.set_verbosity_wrap(verbose) + rnd = check_random_state(random_state) + if verbose: + print('[LibLinear]', end='') + + bias = -1.0 + if fit_intercept: + bias = intercept_scaling + + libsvm.set_verbosity_wrap(verbose) + libsvm_sparse.set_verbosity_wrap(verbose) + liblinear.set_verbosity_wrap(verbose) + + # LibLinear wants targets as doubles, even for classification + y_ind = np.asarray(y_ind, dtype=np.float64).ravel() + solver_type = _get_liblinear_solver_type(multi_class, penalty, loss, dual) + raw_coef_, n_iter_ = liblinear.train_wrap( + X, y_ind, sp.isspmatrix(X), solver_type, tol, bias, C, + class_weight_, max_iter, rnd.randint(np.iinfo('i').max), + epsilon + ) + # Regarding rnd.randint(..) in the above signature: + # seed for srand in range [0..INT_MAX); due to limitations in Numpy + # on 32-bit platforms, we can't get to the UINT_MAX limit that + # srand supports + n_iter_ = max(n_iter_) + if n_iter_ >= max_iter and verbose > 0: + warnings.warn("Liblinear failed to converge, increase " + "the number of iterations.", ConvergenceWarning) + + if fit_intercept: + coef_ = raw_coef_[:, :-1] + intercept_ = intercept_scaling * raw_coef_[:, -1] + else: + coef_ = raw_coef_ + intercept_ = 0. -libsvm.set_verbosity_wrap(0) -libsvm_sparse.set_verbosity_wrap(0) -liblinear.set_verbosity_wrap(0) + return coef_, intercept_, n_iter_ diff --git a/sklearn/svm/bounds.py b/sklearn/svm/bounds.py index 807aceb0fcae2..01f79d34d651e 100644 --- a/sklearn/svm/bounds.py +++ b/sklearn/svm/bounds.py @@ -1,8 +1,18 @@ -import operator +"""Determination of parameter bounds""" +# Author: Paolo Losi +# License: BSD 3 clause + +from warnings import warn + import numpy as np +from ..preprocessing import LabelBinarizer +from ..utils.validation import check_consistent_length, check_array +from ..utils.extmath import safe_sparse_dot + -def l1_min_c(X, y, loss='l2', fit_intercept=True, intercept_scaling=1.0): +def l1_min_c(X, y, loss='squared_hinge', fit_intercept=True, + intercept_scaling=1.0): """ Return the lowest bound for C such that for C in (l1_min_C, infinity) the model is guaranteed not to be empty. This applies to l1 penalized @@ -20,14 +30,16 @@ def l1_min_c(X, y, loss='l2', fit_intercept=True, intercept_scaling=1.0): y : array, shape = [n_samples] Target vector relative to X - loss : {'l2', 'log'}, default to 'l2' + loss : {'squared_hinge', 'log'}, default 'squared_hinge' Specifies the loss function. - With 'l2' it is the l2 loss (a.k.a. squared hinge loss). + With 'squared_hinge' it is the squared hinge loss (a.k.a. L2 loss). With 'log' it is the loss of logistic regression models. + 'l2' is accepted as an alias for 'squared_hinge', for backward + compatibility reasons, but should not be used in new code. fit_intercept : bool, default: True Specifies if the intercept should be fitted by the model. - It must match the fit() method paramenter. + It must match the fit() method parameter. intercept_scaling : float, default: 1 when fit_intercept is True, instance vector x becomes @@ -41,45 +53,29 @@ def l1_min_c(X, y, loss='l2', fit_intercept=True, intercept_scaling=1.0): l1_min_c: float minimum value for C """ - import scipy.sparse as sp - - if loss not in ('l2', 'log'): - raise ValueError('loss type not in ("l2", "log")') - y = np.asarray(y) + if loss == "l2": + warn("loss='l2' will be impossible from 0.18 onwards." + " Use loss='squared_hinge' instead.", + DeprecationWarning) + loss = "squared_hinge" + if loss not in ('squared_hinge', 'log'): + raise ValueError('loss type not in ("squared_hinge", "log", "l2")') - if sp.issparse(X): - X = sp.csc_matrix(X) - hstack = sp.hstack - dot = operator.mul - else: - X = np.asarray(X) - hstack = np.hstack - dot = np.dot + X = check_array(X, accept_sparse='csc') + check_consistent_length(X, y) + Y = LabelBinarizer(neg_label=-1).fit_transform(y).T + # maximum absolute value over classes and features + den = np.max(np.abs(safe_sparse_dot(Y, X))) if fit_intercept: bias = intercept_scaling * np.ones((np.size(y), 1)) - X = hstack((X, bias)) - - classes = np.unique(y) - n_classes = np.size(classes) - if n_classes <= 2: - c = classes[0] - y = y.reshape((1, -1)) - _y = np.empty(y.shape) - _y[y == c] = 1 - _y[y != c] = -1 - else: - _y = np.empty((n_classes, np.size(y))) - for i, c in enumerate(classes): - _y[i, y == c] = 1 - _y[i, y != c] = -1 - - den = np.max(np.abs(dot(_y, X))) + den = max(den, abs(np.dot(Y, bias)).max()) if den == 0.0: - raise ValueError('Ill-posed l1_min_c calculation') - if loss == 'l2': + raise ValueError('Ill-posed l1_min_c calculation: l1 will always ' + 'select zero coefficients for this data') + if loss == 'squared_hinge': return 0.5 / den else: # loss == 'log': return 2.0 / den diff --git a/sklearn/svm/classes.py b/sklearn/svm/classes.py index 4fd685bc6a980..c833de23b7f17 100644 --- a/sklearn/svm/classes.py +++ b/sklearn/svm/classes.py @@ -1,10 +1,16 @@ -from .base import BaseLibLinear, BaseSVC, BaseLibSVM -from ..base import RegressorMixin -from ..linear_model.base import LinearClassifierMixin -from ..feature_selection.selector_mixin import SelectorMixin +import warnings +import numpy as np +from .base import _fit_liblinear, BaseSVC, BaseLibSVM +from ..base import BaseEstimator, RegressorMixin +from ..linear_model.base import LinearClassifierMixin, SparseCoefMixin, \ + LinearModel +from ..feature_selection.from_model import _LearntSelectorMixin +from ..utils import check_X_y -class LinearSVC(BaseLibLinear, LinearClassifierMixin, SelectorMixin): + +class LinearSVC(BaseEstimator, LinearClassifierMixin, + _LearntSelectorMixin, SparseCoefMixin): """Linear Support Vector Classification. Similar to SVC with parameter kernel='linear', but implemented in terms of @@ -20,9 +26,10 @@ class LinearSVC(BaseLibLinear, LinearClassifierMixin, SelectorMixin): C : float, optional (default=1.0) Penalty parameter C of the error term. - loss : string, 'l1' or 'l2' (default='l2') - Specifies the loss function. 'l1' is the hinge loss (standard SVM) - while 'l2' is the squared hinge loss. + loss : string, 'hinge' or 'squared_hinge' (default='squared_hinge') + Specifies the loss function. 'hinge' is the standard SVM loss + (used e.g. by the SVC class) while 'squared_hinge' is the + square of the hinge loss. penalty : string, 'l1' or 'l2' (default='l2') Specifies the norm used in the penalization. The 'l2' @@ -33,8 +40,8 @@ class LinearSVC(BaseLibLinear, LinearClassifierMixin, SelectorMixin): Select the algorithm to either solve the dual or primal optimization problem. Prefer dual=False when n_samples > n_features. - tol: float, optional (default=1e-4) - Tolerance for stopping criteria + tol : float, optional (default=1e-4) + Tolerance for stopping criteria. multi_class: string, 'ovr' or 'crammer_singer' (default='ovr') Determines the multi-class strategy if `y` contains more than @@ -44,7 +51,7 @@ class LinearSVC(BaseLibLinear, LinearClassifierMixin, SelectorMixin): While `crammer_singer` is interesting from an theoretical perspective as it is consistent it is seldom used in practice and rarely leads to better accuracy and is more expensive to compute. - If `crammer_singer` is choosen, the options loss, penalty and dual will + If `crammer_singer` is chosen, the options loss, penalty and dual will be ignored. fit_intercept : boolean, optional (default=True) @@ -53,7 +60,7 @@ class LinearSVC(BaseLibLinear, LinearClassifierMixin, SelectorMixin): (e.g. data is expected to be already centered). intercept_scaling : float, optional (default=1) - when self.fit_intercept is True, instance vector x becomes + When self.fit_intercept is True, instance vector x becomes [x, self.intercept_scaling], i.e. a "synthetic" feature with constant value equals to intercept_scaling is appended to the instance vector. @@ -70,22 +77,29 @@ class LinearSVC(BaseLibLinear, LinearClassifierMixin, SelectorMixin): automatically adjust weights inversely proportional to class frequencies. - verbose : int, default: 0 + verbose : int, (default=0) Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in liblinear that, if enabled, may not work properly in a multithreaded context. + random_state : int seed, RandomState instance, or None (default=None) + The seed of the pseudo random number generator to use when + shuffling the data. + + max_iter : int, (default=1000) + The maximum number of iterations to be run. + Attributes ---------- - `coef_` : array, shape = [n_features] if n_classes == 2 \ + coef_ : array, shape = [n_features] if n_classes == 2 \ else [n_classes, n_features] - Weights asigned to the features (coefficients in the primal + Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. - `coef_` is readonly property derived from `raw_coef_` that \ + `coef_` is a readonly property derived from `raw_coef_` that \ follows the internal memory layout of liblinear. - `intercept_` : array, shape = [1] if n_classes == 2 else [n_classes] + intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] Constants in decision function. Notes @@ -98,6 +112,10 @@ class frequencies. The underlying implementation (liblinear) uses a sparse internal representation for the data that will incur a memory copy. + Predict output may not match that of standalone liblinear in certain + cases. See :ref:`differences from liblinear ` + in the narrative documentation. + **References:** `LIBLINEAR: A Library for Large Linear Classification `__ @@ -119,31 +137,256 @@ class frequencies. sklearn.linear_model.SGDClassifier SGDClassifier can optimize the same cost function as LinearSVC - by adjusting the penalty and loss parameters. Furthermore - SGDClassifier is scalable to large number of samples as it uses - a Stochastic Gradient Descent optimizer. + by adjusting the penalty and loss parameters. In addition it requires + less memory, allows incremental (online) learning, and implements + various loss functions and regularization regimes. + + """ + + def __init__(self, penalty='l2', loss='squared_hinge', dual=True, tol=1e-4, + C=1.0, multi_class='ovr', fit_intercept=True, + intercept_scaling=1, class_weight=None, verbose=0, + random_state=None, max_iter=1000): + self.dual = dual + self.tol = tol + self.C = C + self.multi_class = multi_class + self.fit_intercept = fit_intercept + self.intercept_scaling = intercept_scaling + self.class_weight = class_weight + self.verbose = verbose + self.random_state = random_state + self.max_iter = max_iter + self.penalty = penalty + self.loss = loss + + def fit(self, X, y): + """Fit the model according to the given training data. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Training vector, where n_samples in the number of samples and + n_features is the number of features. + + y : array-like, shape = [n_samples] + Target vector relative to X + + Returns + ------- + self : object + Returns self. + """ + # FIXME Remove l1/l2 support in 1.0 ----------------------------------- + loss_l = self.loss.lower() + + msg = ("loss='%s' has been deprecated in favor of " + "loss='%s' as of 0.16. Backward compatibility" + " for the loss='%s' will be removed in %s") + + # FIXME change loss_l --> self.loss after 0.18 + if loss_l in ('l1', 'l2'): + old_loss = self.loss + self.loss = {'l1': 'hinge', 'l2': 'squared_hinge'}.get(loss_l) + warnings.warn(msg % (old_loss, self.loss, old_loss, '1.0'), + DeprecationWarning) + # --------------------------------------------------------------------- + + if self.C < 0: + raise ValueError("Penalty term must be positive; got (C=%r)" + % self.C) + + X, y = check_X_y(X, y, accept_sparse='csr', + dtype=np.float64, order="C") + self.classes_ = np.unique(y) + + self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear( + X, y, self.C, self.fit_intercept, self.intercept_scaling, + self.class_weight, self.penalty, self.dual, self.verbose, + self.max_iter, self.tol, self.random_state, self.multi_class, + self.loss + ) + + if self.multi_class == "crammer_singer" and len(self.classes_) == 2: + self.coef_ = (self.coef_[1] - self.coef_[0]).reshape(1, -1) + if self.fit_intercept: + intercept = self.intercept_[1] - self.intercept_[0] + self.intercept_ = np.array([intercept]) + + return self + + +class LinearSVR(LinearModel, RegressorMixin): + """Linear Support Vector Regression. + + Similar to SVR with parameter kernel='linear', but implemented in terms of + liblinear rather than libsvm, so it has more flexibility in the choice of + penalties and loss functions and should scale better (to large numbers of + samples). + + This class supports both dense and sparse input. + + Parameters + ---------- + C : float, optional (default=1.0) + Penalty parameter C of the error term. The penalty is a squared + l2 penalty. The bigger this parameter, the less regularization is used. + + loss : string, 'epsilon_insensitive' or 'squared_epsilon_insensitive' + (default='epsilon_insensitive') + Specifies the loss function. 'l1' is the epsilon-insensitive loss + (standard SVR) while 'l2' is the squared epsilon-insensitive loss. + + epsilon : float, optional (default=0.1) + Epsilon parameter in the epsilon-insensitive loss function. Note + that the value of this parameter depends on the scale of the target + variable y. If unsure, set epsilon=0. + + dual : bool, (default=True) + Select the algorithm to either solve the dual or primal + optimization problem. Prefer dual=False when n_samples > n_features. + + tol : float, optional (default=1e-4) + Tolerance for stopping criteria. + + fit_intercept : boolean, optional (default=True) + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (e.g. data is expected to be already centered). + + intercept_scaling : float, optional (default=1) + When self.fit_intercept is True, instance vector x becomes + [x, self.intercept_scaling], + i.e. a "synthetic" feature with constant value equals to + intercept_scaling is appended to the instance vector. + The intercept becomes intercept_scaling * synthetic feature weight + Note! the synthetic feature weight is subject to l1/l2 regularization + as all other features. + To lessen the effect of regularization on synthetic feature weight + (and therefore on the intercept) intercept_scaling has to be increased. + + verbose : int, (default=0) + Enable verbose output. Note that this setting takes advantage of a + per-process runtime setting in liblinear that, if enabled, may not work + properly in a multithreaded context. + + random_state : int seed, RandomState instance, or None (default=None) + The seed of the pseudo random number generator to use when + shuffling the data. + + max_iter : int, (default=1000) + The maximum number of iterations to be run. + + Attributes + ---------- + coef_ : array, shape = [n_features] if n_classes == 2 \ + else [n_classes, n_features] + Weights assigned to the features (coefficients in the primal + problem). This is only available in the case of linear kernel. + + `coef_` is a readonly property derived from `raw_coef_` that \ + follows the internal memory layout of liblinear. + + intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] + Constants in decision function. - Finally SGDClassifier can fit both dense and sparse data without - memory copy if the input is C-contiguous or CSR. + See also + -------- + LinearSVC + Implementation of Support Vector Machine classifier using the + same library as this class (liblinear). + + SVR + Implementation of Support Vector Machine regression using libsvm: + the kernel can be non-linear but its SMO algorithm does not + scale to large number of samples as LinearSVC does. + + sklearn.linear_model.SGDRegressor + SGDRegressor can optimize the same cost function as LinearSVR + by adjusting the penalty and loss parameters. In addition it requires + less memory, allows incremental (online) learning, and implements + various loss functions and regularization regimes. """ - # all the implementation is provided by the mixins - pass + def __init__(self, epsilon=0.0, tol=1e-4, C=1.0, + loss='epsilon_insensitive', fit_intercept=True, + intercept_scaling=1., dual=True, verbose=0, + random_state=None, max_iter=1000): + self.tol = tol + self.C = C + self.epsilon = epsilon + self.fit_intercept = fit_intercept + self.intercept_scaling = intercept_scaling + self.verbose = verbose + self.random_state = random_state + self.max_iter = max_iter + self.dual = dual + self.loss = loss + + def fit(self, X, y): + """Fit the model according to the given training data. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape = [n_samples, n_features] + Training vector, where n_samples in the number of samples and + n_features is the number of features. + + y : array-like, shape = [n_samples] + Target vector relative to X + + Returns + ------- + self : object + Returns self. + """ + # FIXME Remove l1/l2 support in 1.0 ----------------------------------- + loss_l = self.loss.lower() + + msg = ("loss='%s' has been deprecated in favor of " + "loss='%s' as of 0.16. Backward compatibility" + " for the loss='%s' will be removed in %s") + + # FIXME change loss_l --> self.loss after 0.18 + if loss_l in ('l1', 'l2'): + old_loss = self.loss + self.loss = {'l1': 'epsilon_insensitive', + 'l2': 'squared_epsilon_insensitive' + }.get(loss_l) + warnings.warn(msg % (old_loss, self.loss, old_loss, '1.0'), + DeprecationWarning) + # --------------------------------------------------------------------- + + if self.C < 0: + raise ValueError("Penalty term must be positive; got (C=%r)" + % self.C) + + X, y = check_X_y(X, y, accept_sparse='csr', + dtype=np.float64, order="C") + penalty = 'l2' # SVR only accepts l2 penalty + self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear( + X, y, self.C, self.fit_intercept, self.intercept_scaling, + None, penalty, self.dual, self.verbose, + self.max_iter, self.tol, self.random_state, loss=self.loss, + epsilon=self.epsilon) + self.coef_ = self.coef_.ravel() + + return self class SVC(BaseSVC): """C-Support Vector Classification. - The implementations is a based on libsvm. The fit time complexity + The implementation is based on libsvm. The fit time complexity is more than quadratic with the number of samples which makes it hard to scale to dataset with more than a couple of 10000 samples. The multiclass support is handled according to a one-vs-one scheme. For details on the precise mathematical formulation of the provided - kernel functions and how `gamma`, `coef0` and `degree` affect each, - see the corresponding section in the narrative documentation: + kernel functions and how `gamma`, `coef0` and `degree` affect each + other, see the corresponding section in the narrative documentation: :ref:`svm_kernels`. .. The narrative documentation is available at http://scikit-learn.org/ @@ -155,15 +398,17 @@ class SVC(BaseSVC): kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. - It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed'. - If none is given, 'rbf' will be used. + It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or + a callable. + If none is given, 'rbf' will be used. If a callable is given it is + used to precompute the kernel matrix. degree : int, optional (default=3) - Degree of kernel function. - It is significant only in 'poly' and 'sigmoid'. + Degree of the polynomial kernel function ('poly'). + Ignored by all other kernels. gamma : float, optional (default=0.0) - Kernel coefficient for 'rbf' and 'poly'. + Kernel coefficient for 'rbf', 'poly' and 'sigmoid'. If gamma is 0.0 then 1/n_features will be used instead. coef0 : float, optional (default=0.0) @@ -172,16 +417,16 @@ class SVC(BaseSVC): probability: boolean, optional (default=False) Whether to enable probability estimates. This must be enabled prior - to calling predict_proba. + to calling `fit`, and will slow down that method. shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. - tol: float, optional (default=1e-3) + tol : float, optional (default=1e-3) Tolerance for stopping criterion. - cache_size: float, optional - Specify the size of the kernel cache (in MB) + cache_size : float, optional + Specify the size of the kernel cache (in MB). class_weight : {dict, 'auto'}, optional Set the parameter C of class i to class_weight[i]*C for @@ -195,32 +440,39 @@ class frequencies. per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. + max_iter : int, optional (default=-1) + Hard limit on iterations within solver, or -1 for no limit. + + random_state : int seed, RandomState instance, or None (default) + The seed of the pseudo random number generator to use when + shuffling the data for probability estimation. + Attributes ---------- - `support_` : array-like, shape = [n_SV] - Index of support vectors. + support_ : array-like, shape = [n_SV] + Indices of support vectors. - `support_vectors_` : array-like, shape = [n_SV, n_features] + support_vectors_ : array-like, shape = [n_SV, n_features] Support vectors. - `n_support_` : array-like, dtype=int32, shape = [n_class] - number of support vector for each class. + n_support_ : array-like, dtype=int32, shape = [n_class] + Number of support vectors for each class. - `dual_coef_` : array, shape = [n_class-1, n_SV] + dual_coef_ : array, shape = [n_class-1, n_SV] Coefficients of the support vector in the decision function. \ For multiclass, coefficient for all 1-vs-1 classifiers. \ The layout of the coefficients in the multiclass case is somewhat \ non-trivial. See the section about multi-class classification in the \ SVM section of the User Guide for details. - `coef_` : array, shape = [n_class-1, n_features] - Weights asigned to the features (coefficients in the primal + coef_ : array, shape = [n_class-1, n_features] + Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. - `coef_` is readonly property derived from `dual_coef_` and - `support_vectors_` + `coef_` is a readonly property derived from `dual_coef_` and + `support_vectors_`. - `intercept_` : array, shape = [n_class * (n_class-1) / 2] + intercept_ : array, shape = [n_class * (n_class-1) / 2] Constants in decision function. Examples @@ -232,10 +484,10 @@ class frequencies. >>> clf = SVC() >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, - gamma=0.0, kernel='rbf', probability=False, shrinking=True, - tol=0.001, verbose=False) + gamma=0.0, kernel='rbf', max_iter=-1, probability=False, + random_state=None, shrinking=True, tol=0.001, verbose=False) >>> print(clf.predict([[-0.8, -1]])) - [ 1.] + [1] See also -------- @@ -243,7 +495,7 @@ class frequencies. Support Vector Machine for Regression implemented using libsvm. LinearSVC - Scalable Linear Support Vector Machine for classififcation + Scalable Linear Support Vector Machine for classification implemented using liblinear. Check the See also section of LinearSVC for more comparison element. @@ -252,11 +504,12 @@ class frequencies. def __init__(self, C=1.0, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, probability=False, tol=1e-3, cache_size=200, class_weight=None, - verbose=False): + verbose=False, max_iter=-1, random_state=None): - super(SVC, self).__init__('c_svc', kernel, degree, gamma, coef0, tol, - C, 0., 0., shrinking, probability, cache_size, "auto", - class_weight, verbose) + super(SVC, self).__init__( + 'c_svc', kernel, degree, gamma, coef0, tol, C, 0., 0., shrinking, + probability, cache_size, class_weight, verbose, max_iter, + random_state) class NuSVC(BaseSVC): @@ -276,73 +529,74 @@ class NuSVC(BaseSVC): kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. - one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed'. - If none is given 'rbf' will be used. + It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or + a callable. + If none is given, 'rbf' will be used. If a callable is given it is + used to precompute the kernel matrix. degree : int, optional (default=3) - degree of kernel function - is significant only in poly, rbf, sigmoid + Degree of kernel function + is significant only in poly, rbf, sigmoid. gamma : float, optional (default=0.0) - kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features + Kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features will be taken. coef0 : float, optional (default=0.0) - independent term in kernel function. It is only significant + Independent term in kernel function. It is only significant in poly/sigmoid. probability: boolean, optional (default=False) Whether to enable probability estimates. This must be enabled prior - to calling predict_proba. + to calling `fit`, and will slow down that method. shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. - tol: float, optional (default=1e-3) + tol : float, optional (default=1e-3) Tolerance for stopping criterion. - cache_size: float, optional - Specify the size of the kernel cache (in MB) - - class_weight : {dict, 'auto'}, optional - Set the parameter C of class i to class_weight[i]*C for - SVC. If not given, all classes are supposed to have - weight one. The 'auto' mode uses the values of y to - automatically adjust weights inversely proportional to - class frequencies. + cache_size : float, optional + Specify the size of the kernel cache (in MB). verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. + max_iter : int, optional (default=-1) + Hard limit on iterations within solver, or -1 for no limit. + + random_state : int seed, RandomState instance, or None (default) + The seed of the pseudo random number generator to use when + shuffling the data for probability estimation. Attributes ---------- - `support_` : array-like, shape = [n_SV] - Index of support vectors. + support_ : array-like, shape = [n_SV] + Indices of support vectors. - `support_vectors_` : array-like, shape = [n_SV, n_features] + support_vectors_ : array-like, shape = [n_SV, n_features] Support vectors. - `n_support_` : array-like, dtype=int32, shape = [n_class] - number of support vector for each class. + n_support_ : array-like, dtype=int32, shape = [n_class] + Number of support vector for each class. - `dual_coef_` : array, shape = [n_class-1, n_SV] + dual_coef_ : array, shape = [n_class-1, n_SV] Coefficients of the support vector in the decision function. \ For multiclass, coefficient for all 1-vs-1 classifiers. \ The layout of the coefficients in the multiclass case is somewhat \ non-trivial. See the section about multi-class classification in \ the SVM section of the User Guide for details. - `coef_` : array, shape = [n_class-1, n_features] - Weights asigned to the features (coefficients in the primal + coef_ : array, shape = [n_class-1, n_features] + Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and - `support_vectors_` + `support_vectors_`. - `intercept_` : array, shape = [n_class * (n_class-1) / 2] + intercept_ : array, shape = [n_class * (n_class-1) / 2] Constants in decision function. Examples @@ -352,11 +606,12 @@ class frequencies. >>> y = np.array([1, 1, 2, 2]) >>> from sklearn.svm import NuSVC >>> clf = NuSVC() - >>> clf.fit(X, y) - NuSVC(cache_size=200, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', nu=0.5, - probability=False, shrinking=True, tol=0.001, verbose=False) + >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE + NuSVC(cache_size=200, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', + max_iter=-1, nu=0.5, probability=False, random_state=None, + shrinking=True, tol=0.001, verbose=False) >>> print(clf.predict([[-0.8, -1]])) - [ 1.] + [1] See also -------- @@ -370,85 +625,87 @@ class frequencies. def __init__(self, nu=0.5, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, probability=False, - tol=1e-3, cache_size=200, verbose=False): + tol=1e-3, cache_size=200, verbose=False, max_iter=-1, + random_state=None): - super(NuSVC, self).__init__('nu_svc', kernel, degree, gamma, coef0, - tol, 0., nu, 0., shrinking, probability, cache_size, - "auto", None, verbose) + super(NuSVC, self).__init__( + 'nu_svc', kernel, degree, gamma, coef0, tol, 0., nu, 0., shrinking, + probability, cache_size, None, verbose, max_iter, random_state) class SVR(BaseLibSVM, RegressorMixin): - """epsilon-Support Vector Regression. + """Epsilon-Support Vector Regression. The free parameters in the model are C and epsilon. - The implementations is a based on libsvm. + The implementation is based on libsvm. Parameters ---------- C : float, optional (default=1.0) - penalty parameter C of the error term. + Penalty parameter C of the error term. epsilon : float, optional (default=0.1) - epsilon in the epsilon-SVR model. It specifies the epsilon-tube + Epsilon in the epsilon-SVR model. It specifies the epsilon-tube within which no penalty is associated in the training loss function with points predicted within a distance epsilon from the actual value. kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. - one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed'. - If none is given 'rbf' will be used. + It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or + a callable. + If none is given, 'rbf' will be used. If a callable is given it is + used to precompute the kernel matrix. degree : int, optional (default=3) - degree of kernel function - is significant only in poly, rbf, sigmoid + Degree of kernel function + is significant only in poly, rbf, sigmoid. gamma : float, optional (default=0.0) - kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features + Kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features will be taken. coef0 : float, optional (default=0.0) independent term in kernel function. It is only significant in poly/sigmoid. - probability: boolean, optional (default=False) - Whether to enable probability estimates. This must be enabled prior - to calling predict_proba. - shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. - tol: float, optional (default=1e-3) + tol : float, optional (default=1e-3) Tolerance for stopping criterion. - cache_size: float, optional - Specify the size of the kernel cache (in MB) + cache_size : float, optional + Specify the size of the kernel cache (in MB). verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. + max_iter : int, optional (default=-1) + Hard limit on iterations within solver, or -1 for no limit. + Attributes ---------- - `support_` : array-like, shape = [n_SV] - Index of support vectors. + support_ : array-like, shape = [n_SV] + Indices of support vectors. - `support_vectors_` : array-like, shape = [nSV, n_features] + support_vectors_ : array-like, shape = [nSV, n_features] Support vectors. - `dual_coef_` : array, shape = [n_classes-1, n_SV] + dual_coef_ : array, shape = [1, n_SV] Coefficients of the support vector in the decision function. - `coef_` : array, shape = [n_classes-1, n_features] - Weights asigned to the features (coefficients in the primal + coef_ : array, shape = [1, n_features] + Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and - `support_vectors_` + `support_vectors_`. - `intercept_` : array, shape = [n_class * (n_class-1) / 2] + intercept_ : array, shape = [1] Constants in decision function. Examples @@ -460,10 +717,9 @@ class SVR(BaseLibSVM, RegressorMixin): >>> y = np.random.randn(n_samples) >>> X = np.random.randn(n_samples, n_features) >>> clf = SVR(C=1.0, epsilon=0.2) - >>> clf.fit(X, y) + >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE SVR(C=1.0, cache_size=200, coef0=0.0, degree=3, epsilon=0.2, gamma=0.0, - kernel='rbf', probability=False, shrinking=True, tol=0.001, - verbose=False) + kernel='rbf', max_iter=-1, shrinking=True, tol=0.001, verbose=False) See also -------- @@ -471,14 +727,19 @@ class SVR(BaseLibSVM, RegressorMixin): Support Vector Machine for regression implemented using libsvm using a parameter to control the number of support vectors. + LinearSVR + Scalable Linear Support Vector Machine for regression + implemented using liblinear. """ def __init__(self, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, tol=1e-3, - C=1.0, epsilon=0.1, shrinking=True, probability=False, - cache_size=200, verbose=False): + C=1.0, epsilon=0.1, shrinking=True, cache_size=200, + verbose=False, max_iter=-1): - super(SVR, self).__init__('epsilon_svr', kernel, degree, gamma, coef0, - tol, C, 0., epsilon, shrinking, probability, cache_size, - "auto", None, verbose) + super(SVR, self).__init__( + 'epsilon_svr', kernel=kernel, degree=degree, gamma=gamma, + coef0=coef0, tol=tol, C=C, nu=0., epsilon=epsilon, verbose=verbose, + shrinking=shrinking, probability=False, cache_size=cache_size, + class_weight=None, max_iter=max_iter, random_state=None) class NuSVR(BaseLibSVM, RegressorMixin): @@ -486,74 +747,75 @@ class NuSVR(BaseLibSVM, RegressorMixin): Similar to NuSVC, for regression, uses a parameter nu to control the number of support vectors. However, unlike NuSVC, where nu - replaces C, here nu replaces with the parameter epsilon of SVR. + replaces C, here nu replaces the parameter epsilon of epsilon-SVR. - The implementations is a based on libsvm. + The implementation is based on libsvm. Parameters ---------- C : float, optional (default=1.0) - penalty parameter C of the error term. + Penalty parameter C of the error term. nu : float, optional An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. Should be in the interval (0, 1]. By - default 0.5 will be taken. Only available if impl='nu_svc'. + default 0.5 will be taken. kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. - one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed'. - If none is given 'rbf' will be used. + It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or + a callable. + If none is given, 'rbf' will be used. If a callable is given it is + used to precompute the kernel matrix. degree : int, optional (default=3) - degree of kernel function - is significant only in poly, rbf, sigmoid + Degree of kernel function + is significant only in poly, rbf, sigmoid. gamma : float, optional (default=0.0) - kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features + Kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features will be taken. coef0 : float, optional (default=0.0) - independent term in kernel function. It is only significant + Independent term in kernel function. It is only significant in poly/sigmoid. - probability: boolean, optional (default=False) - Whether to enable probability estimates. This must be enabled prior - to calling predict_proba. - shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. - tol: float, optional (default=1e-3) + tol : float, optional (default=1e-3) Tolerance for stopping criterion. - cache_size: float, optional - Specify the size of the kernel cache (in MB) + cache_size : float, optional + Specify the size of the kernel cache (in MB). verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. + max_iter : int, optional (default=-1) + Hard limit on iterations within solver, or -1 for no limit. + Attributes ---------- - `support_` : array-like, shape = [n_SV] - Index of support vectors. + support_ : array-like, shape = [n_SV] + Indices of support vectors. - `support_vectors_` : array-like, shape = [nSV, n_features] + support_vectors_ : array-like, shape = [nSV, n_features] Support vectors. - `dual_coef_` : array, shape = [n_classes-1, n_SV] + dual_coef_ : array, shape = [1, n_SV] Coefficients of the support vector in the decision function. - `coef_` : array, shape = [n_classes-1, n_features] - Weights asigned to the features (coefficients in the primal + coef_ : array, shape = [1, n_features] + Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and - `support_vectors_` + `support_vectors_`. - `intercept_` : array, shape = [n_class * (n_class-1) / 2] + intercept_ : array, shape = [1] Constants in decision function. Examples @@ -565,9 +827,9 @@ class NuSVR(BaseLibSVM, RegressorMixin): >>> y = np.random.randn(n_samples) >>> X = np.random.randn(n_samples, n_features) >>> clf = NuSVR(C=1.0, nu=0.1) - >>> clf.fit(X, y) + >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE NuSVR(C=1.0, cache_size=200, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', - nu=0.1, probability=False, shrinking=True, tol=0.001, verbose=False) + max_iter=-1, nu=0.1, shrinking=True, tol=0.001, verbose=False) See also -------- @@ -580,17 +842,18 @@ class NuSVR(BaseLibSVM, RegressorMixin): """ def __init__(self, nu=0.5, C=1.0, kernel='rbf', degree=3, - gamma=0.0, coef0=0.0, shrinking=True, - probability=False, tol=1e-3, cache_size=200, - verbose=False): + gamma=0.0, coef0=0.0, shrinking=True, tol=1e-3, + cache_size=200, verbose=False, max_iter=-1): - super(NuSVR, self).__init__('nu_svr', kernel, degree, gamma, coef0, - tol, C, nu, 0., shrinking, probability, cache_size, - "auto", None, verbose) + super(NuSVR, self).__init__( + 'nu_svr', kernel=kernel, degree=degree, gamma=gamma, coef0=coef0, + tol=tol, C=C, nu=nu, epsilon=0., shrinking=shrinking, + probability=False, cache_size=cache_size, class_weight=None, + verbose=verbose, max_iter=max_iter, random_state=None) class OneClassSVM(BaseLibSVM): - """Unsupervised Outliers Detection. + """Unsupervised Outlier Detection. Estimate the support of a high-dimensional distribution. @@ -598,10 +861,12 @@ class OneClassSVM(BaseLibSVM): Parameters ---------- - kernel : string, optional - Specifies the kernel type to be used in - the algorithm. Can be one of 'linear', 'poly', 'rbf', 'sigmoid', - 'precomputed'. If none is given 'rbf' will be used. + kernel : string, optional (default='rbf') + Specifies the kernel type to be used in the algorithm. + It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or + a callable. + If none is given, 'rbf' will be used. If a callable is given it is + used to precompute the kernel matrix. nu : float, optional An upper bound on the fraction of training @@ -609,70 +874,84 @@ class OneClassSVM(BaseLibSVM): vectors. Should be in the interval (0, 1]. By default 0.5 will be taken. - degree : int, optional - Degree of kernel function. Significant only in poly, rbf, sigmoid. + degree : int, optional (default=3) + Degree of the polynomial kernel function ('poly'). + Ignored by all other kernels. gamma : float, optional (default=0.0) - kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features - will be taken. + Kernel coefficient for 'rbf', 'poly' and 'sigmoid'. + If gamma is 0.0 then 1/n_features will be used instead. - coef0 : float, optional - Independent term in kernel function. It is only significant in - poly/sigmoid. + coef0 : float, optional (default=0.0) + Independent term in kernel function. + It is only significant in 'poly' and 'sigmoid'. - tol: float, optional + tol : float, optional Tolerance for stopping criterion. shrinking: boolean, optional Whether to use the shrinking heuristic. - cache_size: float, optional - Specify the size of the kernel cache (in MB) + cache_size : float, optional + Specify the size of the kernel cache (in MB). verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. + max_iter : int, optional (default=-1) + Hard limit on iterations within solver, or -1 for no limit. + + random_state : int seed, RandomState instance, or None (default) + The seed of the pseudo random number generator to use when + shuffling the data for probability estimation. + Attributes ---------- - `support_` : array-like, shape = [n_SV] - Index of support vectors. + support_ : array-like, shape = [n_SV] + Indices of support vectors. - `support_vectors_` : array-like, shape = [nSV, n_features] + support_vectors_ : array-like, shape = [nSV, n_features] Support vectors. - `dual_coef_` : array, shape = [n_classes-1, n_SV] - Coefficient of the support vector in the decision function. + dual_coef_ : array, shape = [n_classes-1, n_SV] + Coefficients of the support vectors in the decision function. - `coef_` : array, shape = [n_classes-1, n_features] - Weights asigned to the features (coefficients in the primal + coef_ : array, shape = [n_classes-1, n_features] + Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and `support_vectors_` - `intercept_` : array, shape = [n_classes-1] + intercept_ : array, shape = [n_classes-1] Constants in decision function. """ def __init__(self, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, tol=1e-3, - nu=0.5, shrinking=True, cache_size=200, verbose=False): + nu=0.5, shrinking=True, cache_size=200, verbose=False, + max_iter=-1, random_state=None): - super(OneClassSVM, self).__init__('one_class', kernel, degree, gamma, - coef0, tol, 0., nu, 0., shrinking, False, cache_size, - "auto", None, verbose) + super(OneClassSVM, self).__init__( + 'one_class', kernel, degree, gamma, coef0, tol, 0., nu, 0., + shrinking, False, cache_size, None, verbose, max_iter, + random_state) - def fit(self, X, sample_weight=None, **params): + def fit(self, X, y=None, sample_weight=None, **params): """ Detects the soft boundary of the set of samples X. Parameters ---------- - X : {array-like, sparse matrix}, shape = [n_samples, n_features] + X : {array-like, sparse matrix}, shape (n_samples, n_features) Set of samples, where n_samples is the number of samples and n_features is the number of features. + sample_weight : array-like, shape (n_samples,) + Per-sample weights. Rescale C per sample. Higher weights + force the classifier to put more emphasis on these points. + Returns ------- self : object @@ -684,5 +963,5 @@ def fit(self, X, sample_weight=None, **params): """ super(OneClassSVM, self).fit(X, [], sample_weight=sample_weight, - **params) + **params) return self diff --git a/sklearn/svm/liblinear.c b/sklearn/svm/liblinear.c index 500c190cd50b2..02f0911bbca59 100644 --- a/sklearn/svm/liblinear.c +++ b/sklearn/svm/liblinear.c @@ -1,17 +1,29 @@ -/* Generated by Cython 0.16 on Thu Sep 13 00:14:59 2012 */ +/* Generated by Cython 0.21 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02040000 - #error Cython requires Python 2.4+. +#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) + #error Cython requires Python 2.6+ or Python 3.2+. #else -#include /* For offsetof */ +#define CYTHON_ABI "0_21" +#include #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -23,22 +35,18 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif - #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 @@ -46,100 +54,65 @@ #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif - -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyCFunction_Call PyObject_Call -#else - #define __Pyx_PyCFunction_Call PyCFunction_Call -#endif - -#if PY_VERSION_HEX < 0x02050000 - typedef int Py_ssize_t; - #define PY_SSIZE_T_MAX INT_MAX - #define PY_SSIZE_T_MIN INT_MIN - #define PY_FORMAT_SIZE_T "" - #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) - #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) - #define __PYX_BUILD_PY_SSIZE_T "i" -#else - #define __PYX_BUILD_PY_SSIZE_T "n" -#endif - -#if PY_VERSION_HEX < 0x02060000 - #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) - #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) - #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) - #define PyVarObject_HEAD_INIT(type, size) \ - PyObject_HEAD_INIT(type) size, - #define PyType_Modified(t) - - typedef struct { - void *buf; - PyObject *obj; - Py_ssize_t len; - Py_ssize_t itemsize; - int readonly; - int ndim; - char *format; - Py_ssize_t *shape; - Py_ssize_t *strides; - Py_ssize_t *suboffsets; - void *internal; - } Py_buffer; - - #define PyBUF_SIMPLE 0 - #define PyBUF_WRITABLE 0x0001 - #define PyBUF_FORMAT 0x0004 - #define PyBUF_ND 0x0008 - #define PyBUF_STRIDES (0x0010 | PyBUF_ND) - #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) - #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) - #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) - #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) - #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) - - typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); - typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 +#define Py_OptimizeFlag 0 #endif - +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ - PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type #endif - -#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 - #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") -#endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - -#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) +#if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - - -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_GET_LENGTH) +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #else #define CYTHON_PEP393_ENABLED 0 - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif - #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -147,36 +120,17 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - -#if PY_VERSION_HEX < 0x02060000 - #define PyBytesObject PyStringObject - #define PyBytes_Type PyString_Type - #define PyBytes_Check PyString_Check - #define PyBytes_CheckExact PyString_CheckExact - #define PyBytes_FromString PyString_FromString - #define PyBytes_FromStringAndSize PyString_FromStringAndSize - #define PyBytes_FromFormat PyString_FromFormat - #define PyBytes_DecodeEscape PyString_DecodeEscape - #define PyBytes_AsString PyString_AsString - #define PyBytes_AsStringAndSize PyString_AsStringAndSize - #define PyBytes_Size PyString_Size - #define PyBytes_AS_STRING PyString_AS_STRING - #define PyBytes_GET_SIZE PyString_GET_SIZE - #define PyBytes_Repr PyString_Repr - #define PyBytes_Concat PyString_Concat - #define PyBytes_ConcatAndDel PyString_ConcatAndDel -#endif - -#if PY_VERSION_HEX < 0x02060000 - #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) - #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -192,13 +146,12 @@ #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - -#if PY_VERSION_HEX < 0x03020000 +#if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong @@ -206,48 +159,51 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - -#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) - #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) - #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) -#else - #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) - #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) -#endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) -#else - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif #endif - -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_NAMESTR(n) ((char *)(n)) - #define __Pyx_DOCSTR(n) ((char *)(n)) +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) #else - #define __Pyx_NAMESTR(n) (n) - #define __Pyx_DOCSTR(n) (n) +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#ifdef __cplusplus +template +void __Pyx_call_destructor(T* x) { + x->~T(); +} #endif + #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) @@ -270,6 +226,7 @@ #include #define __PYX_HAVE__sklearn__svm__liblinear #define __PYX_HAVE_API__sklearn__svm__liblinear +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" @@ -284,21 +241,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -312,42 +254,157 @@ # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + -#ifdef __GNUC__ - /* Test for GCC > 2.95 */ - #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) - #else /* __GNUC__ > 2 ... */ - #define likely(x) (x) - #define unlikely(x) (x) - #endif /* __GNUC__ > 2 ... */ -#else /* __GNUC__ */ +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -379,19 +436,20 @@ static const char *__pyx_filename; static const char *__pyx_f[] = { - "liblinear.pyx", - "numpy.pxd", + "sklearn/svm/liblinear.pyx", + "__init__.pxd", + "type.pxd", }; #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { - const char* name; /* for error messages only */ + const char* name; struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - size_t arraysize[8]; /* length of array in each dimension */ + size_t size; + size_t arraysize[8]; int ndim; - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ + char typegroup; char is_unsigned; int flags; } __Pyx_TypeInfo; @@ -418,7 +476,7 @@ typedef struct { } __Pyx_BufFmt_Context; -/* "numpy.pxd":722 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -427,7 +485,7 @@ typedef struct { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":723 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -436,7 +494,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":724 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -445,7 +503,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":725 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -454,7 +512,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":729 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -463,7 +521,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":730 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -472,7 +530,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":731 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -481,7 +539,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":732 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -490,7 +548,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":736 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -499,7 +557,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":737 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -508,7 +566,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":746 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -517,7 +575,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":747 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -526,7 +584,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":748 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -535,7 +593,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":750 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -544,7 +602,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":751 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -553,7 +611,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":752 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -562,7 +620,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":754 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -571,7 +629,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":755 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -580,7 +638,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":757 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -589,7 +647,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":758 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -598,7 +656,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":759 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -629,7 +687,7 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; /*--- Type declarations ---*/ -/* "numpy.pxd":761 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -638,7 +696,7 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":762 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -647,7 +705,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":763 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -656,7 +714,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":765 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -677,7 +735,7 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil) \ @@ -714,116 +772,111 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) -#endif /* CYTHON_REFNANNY */ +#endif +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ - const char* function_name); /*proto*/ + const char* function_name); -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact); /*proto*/ +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); -static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -#define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_List_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} -#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Tuple_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} -#define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { - if (PyList_CheckExact(o)) { - Py_ssize_t n = (likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if (likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = (likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if (likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (likely(i >= 0)) { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - return m->sq_item(o, i); - } - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +static void __Pyx_RaiseBufferFallbackError(void); static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); typedef struct { Py_ssize_t shape, strides, suboffsets; @@ -846,12 +899,27 @@ typedef struct { #define __Pyx_ReleaseBuffer PyBuffer_Release #endif + static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static CYTHON_INLINE npy_int32 __Pyx_PyInt_As_npy_int32(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); -static CYTHON_INLINE npy_int32 __Pyx_PyInt_from_py_npy_int32(PyObject *); +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -865,7 +933,7 @@ static CYTHON_INLINE npy_int32 __Pyx_PyInt_from_py_npy_int32(PyObject *); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif -#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else @@ -951,37 +1019,7 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); static int __Pyx_check_binary_version(void); @@ -993,38 +1031,28 @@ static int __Pyx_check_binary_version(void); #endif #endif -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ - -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ - -typedef struct { - int code_line; - PyCodeObject* code_object; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); +static PyObject *__Pyx_ImportModule(const char *name); -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); /*proto*/ +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -1038,9 +1066,8 @@ static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ /* Module declarations from 'sklearn.svm.liblinear' */ -static PyObject *__pyx_f_7sklearn_3svm_9liblinear__csr_train_wrap(__pyx_t_5numpy_int32_t, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, int, double, double, double, PyArrayObject *, PyArrayObject *); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t = { "float64_t", NULL, sizeof(__pyx_t_5numpy_float64_t), { 0 }, 0, 'R', 0, 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t = { "int32_t", NULL, sizeof(__pyx_t_5numpy_int32_t), { 0 }, 0, 'I', IS_UNSIGNED(__pyx_t_5numpy_int32_t), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t = { "int32_t", NULL, sizeof(__pyx_t_5numpy_int32_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_int32_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_int32_t), 0 }; #define __Pyx_MODULE_NAME "sklearn.svm.liblinear" int __pyx_module_is_main_sklearn__svm__liblinear = 0; @@ -1048,152 +1075,183 @@ int __pyx_module_is_main_sklearn__svm__liblinear = 0; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_RuntimeError; -static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_solver_type, double __pyx_v_eps, double __pyx_v_bias, double __pyx_v_C, PyArrayObject *__pyx_v_weight_label, PyArrayObject *__pyx_v_weight); /* proto */ -static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_2csr_train_wrap(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, PyObject *__pyx_v_Y, PyObject *__pyx_v_solver_type, PyObject *__pyx_v_eps, PyObject *__pyx_v_bias, PyObject *__pyx_v_C, PyObject *__pyx_v_weight_label, PyObject *__pyx_v_weight); /* proto */ -static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_4set_verbosity_wrap(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_verbosity); /* proto */ +static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_is_sparse, int __pyx_v_solver_type, double __pyx_v_eps, double __pyx_v_bias, double __pyx_v_C, PyArrayObject *__pyx_v_class_weight, int __pyx_v_max_iter, unsigned int __pyx_v_random_seed, double __pyx_v_epsilon); /* proto */ +static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_2set_verbosity_wrap(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_verbosity); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ -static char __pyx_k_1[] = "ndarray is not C contiguous"; -static char __pyx_k_3[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_5[] = "Non-native byte order not supported"; -static char __pyx_k_7[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_8[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_11[] = "Format string allocated too short."; -static char __pyx_k_13[] = "\nWrapper for liblinear\n\nAuthor: fabian.pedregosa@inria.fr\n"; -static char __pyx_k_16[] = "/home/lars/src/scikit-learn/sklearn/svm/liblinear.pyx"; -static char __pyx_k_17[] = "sklearn.svm.liblinear"; -static char __pyx_k__B[] = "B"; -static char __pyx_k__C[] = "C"; -static char __pyx_k__F[] = "F"; -static char __pyx_k__H[] = "H"; -static char __pyx_k__I[] = "I"; -static char __pyx_k__L[] = "L"; -static char __pyx_k__O[] = "O"; -static char __pyx_k__Q[] = "Q"; -static char __pyx_k__X[] = "X"; -static char __pyx_k__Y[] = "Y"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__d[] = "d"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__g[] = "g"; -static char __pyx_k__h[] = "h"; -static char __pyx_k__i[] = "i"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__q[] = "q"; -static char __pyx_k__w[] = "w"; -static char __pyx_k__Zd[] = "Zd"; -static char __pyx_k__Zf[] = "Zf"; -static char __pyx_k__Zg[] = "Zg"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__eps[] = "eps"; -static char __pyx_k__bias[] = "bias"; -static char __pyx_k__data[] = "data"; -static char __pyx_k__empty[] = "empty"; -static char __pyx_k__len_w[] = "len_w"; -static char __pyx_k__model[] = "model"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__order[] = "order"; -static char __pyx_k__param[] = "param"; -static char __pyx_k__range[] = "range"; -static char __pyx_k__shape[] = "shape"; -static char __pyx_k__indptr[] = "indptr"; -static char __pyx_k__weight[] = "weight"; -static char __pyx_k__indices[] = "indices"; -static char __pyx_k__problem[] = "problem"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__nr_class[] = "nr_class"; -static char __pyx_k__error_msg[] = "error_msg"; -static char __pyx_k__verbosity[] = "verbosity"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__nr_feature[] = "nr_feature"; -static char __pyx_k__train_wrap[] = "train_wrap"; -static char __pyx_k__solver_type[] = "solver_type"; -static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k__weight_label[] = "weight_label"; -static char __pyx_k__csr_train_wrap[] = "csr_train_wrap"; -static char __pyx_k__set_verbosity_wrap[] = "set_verbosity_wrap"; -static PyObject *__pyx_kp_u_1; -static PyObject *__pyx_kp_u_11; -static PyObject *__pyx_kp_s_16; -static PyObject *__pyx_n_s_17; -static PyObject *__pyx_kp_u_3; -static PyObject *__pyx_kp_u_5; -static PyObject *__pyx_kp_u_7; -static PyObject *__pyx_kp_u_8; -static PyObject *__pyx_n_s__C; -static PyObject *__pyx_n_s__F; -static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s__X; -static PyObject *__pyx_n_s__Y; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__bias; -static PyObject *__pyx_n_s__csr_train_wrap; -static PyObject *__pyx_n_s__data; -static PyObject *__pyx_n_s__empty; -static PyObject *__pyx_n_s__eps; -static PyObject *__pyx_n_s__error_msg; -static PyObject *__pyx_n_s__indices; -static PyObject *__pyx_n_s__indptr; -static PyObject *__pyx_n_s__len_w; -static PyObject *__pyx_n_s__model; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__nr_class; -static PyObject *__pyx_n_s__nr_feature; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__order; -static PyObject *__pyx_n_s__param; -static PyObject *__pyx_n_s__problem; -static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__set_verbosity_wrap; -static PyObject *__pyx_n_s__shape; -static PyObject *__pyx_n_s__solver_type; -static PyObject *__pyx_n_s__train_wrap; -static PyObject *__pyx_n_s__verbosity; -static PyObject *__pyx_n_s__w; -static PyObject *__pyx_n_s__weight; -static PyObject *__pyx_n_s__weight_label; +static char __pyx_k_B[] = "B"; +static char __pyx_k_C[] = "C"; +static char __pyx_k_F[] = "F"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_X[] = "X"; +static char __pyx_k_Y[] = "Y"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_w[] = "w"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_eps[] = "eps"; +static char __pyx_k_bias[] = "bias"; +static char __pyx_k_data[] = "data"; +static char __pyx_k_intc[] = "intc"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_empty[] = "empty"; +static char __pyx_k_len_w[] = "len_w"; +static char __pyx_k_model[] = "model"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_order[] = "order"; +static char __pyx_k_param[] = "param"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_shape[] = "shape"; +static char __pyx_k_zeros[] = "zeros"; +static char __pyx_k_arange[] = "arange"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_indptr[] = "indptr"; +static char __pyx_k_labels[] = "labels_"; +static char __pyx_k_n_iter[] = "n_iter"; +static char __pyx_k_epsilon[] = "epsilon"; +static char __pyx_k_indices[] = "indices"; +static char __pyx_k_problem[] = "problem"; +static char __pyx_k_max_iter[] = "max_iter"; +static char __pyx_k_nr_class[] = "nr_class"; +static char __pyx_k_error_msg[] = "error_msg"; +static char __pyx_k_is_sparse[] = "is_sparse"; +static char __pyx_k_verbosity[] = "verbosity"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_nr_feature[] = "nr_feature"; +static char __pyx_k_train_wrap[] = "train_wrap"; +static char __pyx_k_random_seed[] = "random_seed"; +static char __pyx_k_solver_type[] = "solver_type"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_class_weight[] = "class_weight"; +static char __pyx_k_class_weight_label[] = "class_weight_label"; +static char __pyx_k_set_verbosity_wrap[] = "set_verbosity_wrap"; +static char __pyx_k_sklearn_svm_liblinear[] = "sklearn.svm.liblinear"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_home_fp985994_dev_scikit_learn[] = "/home/fp985994/dev/scikit-learn/sklearn/svm/liblinear.pyx"; +static char __pyx_k_Wrapper_for_liblinear_Author_fa[] = "\nWrapper for liblinear\n\nAuthor: fabian.pedregosa@inria.fr\n"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_n_s_C; +static PyObject *__pyx_n_s_F; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_n_s_Y; +static PyObject *__pyx_n_s_arange; +static PyObject *__pyx_n_s_bias; +static PyObject *__pyx_n_s_class_weight; +static PyObject *__pyx_n_s_class_weight_label; +static PyObject *__pyx_n_s_data; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_empty; +static PyObject *__pyx_n_s_eps; +static PyObject *__pyx_n_s_epsilon; +static PyObject *__pyx_n_s_error_msg; +static PyObject *__pyx_kp_s_home_fp985994_dev_scikit_learn; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_indices; +static PyObject *__pyx_n_s_indptr; +static PyObject *__pyx_n_s_intc; +static PyObject *__pyx_n_s_is_sparse; +static PyObject *__pyx_n_s_labels; +static PyObject *__pyx_n_s_len_w; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_max_iter; +static PyObject *__pyx_n_s_model; +static PyObject *__pyx_n_s_n_iter; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_nr_class; +static PyObject *__pyx_n_s_nr_feature; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_order; +static PyObject *__pyx_n_s_param; +static PyObject *__pyx_n_s_problem; +static PyObject *__pyx_n_s_random_seed; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_set_verbosity_wrap; +static PyObject *__pyx_n_s_shape; +static PyObject *__pyx_n_s_sklearn_svm_liblinear; +static PyObject *__pyx_n_s_solver_type; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_n_s_train_wrap; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_verbosity; +static PyObject *__pyx_n_s_w; +static PyObject *__pyx_n_s_zeros; static PyObject *__pyx_int_1; -static PyObject *__pyx_int_15; -static PyObject *__pyx_k_tuple_2; -static PyObject *__pyx_k_tuple_4; -static PyObject *__pyx_k_tuple_6; -static PyObject *__pyx_k_tuple_9; -static PyObject *__pyx_k_tuple_10; -static PyObject *__pyx_k_tuple_12; -static PyObject *__pyx_k_tuple_14; -static PyObject *__pyx_k_tuple_18; -static PyObject *__pyx_k_tuple_20; -static PyObject *__pyx_k_codeobj_15; -static PyObject *__pyx_k_codeobj_19; -static PyObject *__pyx_k_codeobj_21; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_codeobj__8; +static PyObject *__pyx_codeobj__10; + +/* "sklearn/svm/liblinear.pyx":14 + * + * + * def train_wrap(X, np.ndarray[np.float64_t, ndim=1, mode='c'] Y, # <<<<<<<<<<<<<< + * bint is_sparse, int solver_type, double eps, double bias, + * double C, np.ndarray[np.float64_t, ndim=1] class_weight, + */ /* Python wrapper */ static PyObject *__pyx_pw_7sklearn_3svm_9liblinear_1train_wrap(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_3svm_9liblinear_train_wrap[] = "\n Wrapper for train methd.\n "; -static PyMethodDef __pyx_mdef_7sklearn_3svm_9liblinear_1train_wrap = {__Pyx_NAMESTR("train_wrap"), (PyCFunction)__pyx_pw_7sklearn_3svm_9liblinear_1train_wrap, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_3svm_9liblinear_train_wrap)}; +static PyMethodDef __pyx_mdef_7sklearn_3svm_9liblinear_1train_wrap = {"train_wrap", (PyCFunction)__pyx_pw_7sklearn_3svm_9liblinear_1train_wrap, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_7sklearn_3svm_9liblinear_1train_wrap(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_X = 0; + PyObject *__pyx_v_X = 0; PyArrayObject *__pyx_v_Y = 0; + int __pyx_v_is_sparse; int __pyx_v_solver_type; double __pyx_v_eps; double __pyx_v_bias; double __pyx_v_C; - PyArrayObject *__pyx_v_weight_label = 0; - PyArrayObject *__pyx_v_weight = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__Y,&__pyx_n_s__solver_type,&__pyx_n_s__eps,&__pyx_n_s__bias,&__pyx_n_s__C,&__pyx_n_s__weight_label,&__pyx_n_s__weight,0}; + PyArrayObject *__pyx_v_class_weight = 0; + int __pyx_v_max_iter; + unsigned int __pyx_v_random_seed; + double __pyx_v_epsilon; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("train_wrap (wrapper)", 0); - __pyx_self = __pyx_self; { - PyObject* values[8] = {0,0,0,0,0,0,0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_Y,&__pyx_n_s_is_sparse,&__pyx_n_s_solver_type,&__pyx_n_s_eps,&__pyx_n_s_bias,&__pyx_n_s_C,&__pyx_n_s_class_weight,&__pyx_n_s_max_iter,&__pyx_n_s_random_seed,&__pyx_n_s_epsilon,0}; + PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { + case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); + case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); + case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); @@ -1208,56 +1266,63 @@ static PyObject *__pyx_pw_7sklearn_3svm_9liblinear_1train_wrap(PyObject *__pyx_s kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__Y); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 8, 8, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__solver_type); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_is_sparse)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 8, 8, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__eps); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_solver_type)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 8, 8, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__bias); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_eps)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 8, 8, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_bias)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 8, 8, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight_label); - if (likely(values[6])) kw_args--; + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_C)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 8, 8, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: - values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight); - if (likely(values[7])) kw_args--; + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 8: + if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_iter)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 9: + if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random_seed)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 8, 8, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 10: + if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_epsilon)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "train_wrap") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "train_wrap") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - } else if (PyTuple_GET_SIZE(__pyx_args) != 8) { + } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); @@ -1268,29 +1333,35 @@ static PyObject *__pyx_pw_7sklearn_3svm_9liblinear_1train_wrap(PyObject *__pyx_s values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + values[8] = PyTuple_GET_ITEM(__pyx_args, 8); + values[9] = PyTuple_GET_ITEM(__pyx_args, 9); + values[10] = PyTuple_GET_ITEM(__pyx_args, 10); } - __pyx_v_X = ((PyArrayObject *)values[0]); + __pyx_v_X = values[0]; __pyx_v_Y = ((PyArrayObject *)values[1]); - __pyx_v_solver_type = __Pyx_PyInt_AsInt(values[2]); if (unlikely((__pyx_v_solver_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_eps = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_eps == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_bias = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_bias == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_C = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_weight_label = ((PyArrayObject *)values[6]); - __pyx_v_weight = ((PyArrayObject *)values[7]); + __pyx_v_is_sparse = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_is_sparse == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_solver_type = __Pyx_PyInt_As_int(values[3]); if (unlikely((__pyx_v_solver_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_eps = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_eps == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_bias = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_bias == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_C = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_class_weight = ((PyArrayObject *)values[7]); + __pyx_v_max_iter = __Pyx_PyInt_As_int(values[8]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_random_seed = __Pyx_PyInt_As_unsigned_int(values[9]); if (unlikely((__pyx_v_random_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_epsilon = __pyx_PyFloat_AsDouble(values[10]); if (unlikely((__pyx_v_epsilon == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 8, 8, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("train_wrap", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.svm.liblinear.train_wrap", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weight_label), __pyx_ptype_5numpy_ndarray, 1, "weight_label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weight), __pyx_ptype_5numpy_ndarray, 1, "weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_3svm_9liblinear_train_wrap(__pyx_self, __pyx_v_X, __pyx_v_Y, __pyx_v_solver_type, __pyx_v_eps, __pyx_v_bias, __pyx_v_C, __pyx_v_weight_label, __pyx_v_weight); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_3svm_9liblinear_train_wrap(__pyx_self, __pyx_v_X, __pyx_v_Y, __pyx_v_is_sparse, __pyx_v_solver_type, __pyx_v_eps, __pyx_v_bias, __pyx_v_C, __pyx_v_class_weight, __pyx_v_max_iter, __pyx_v_random_seed, __pyx_v_epsilon); + + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -1299,33 +1370,28 @@ static PyObject *__pyx_pw_7sklearn_3svm_9liblinear_1train_wrap(PyObject *__pyx_s return __pyx_r; } -/* "sklearn/svm/liblinear.pyx":12 - * - * - * def train_wrap ( np.ndarray[np.float64_t, ndim=2, mode='c'] X, # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, - * int solver_type, double eps, double bias, double C, - */ - -static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_solver_type, double __pyx_v_eps, double __pyx_v_bias, double __pyx_v_C, PyArrayObject *__pyx_v_weight_label, PyArrayObject *__pyx_v_weight) { +static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_is_sparse, int __pyx_v_solver_type, double __pyx_v_eps, double __pyx_v_bias, double __pyx_v_C, PyArrayObject *__pyx_v_class_weight, int __pyx_v_max_iter, unsigned int __pyx_v_random_seed, double __pyx_v_epsilon) { struct parameter *__pyx_v_param; struct problem *__pyx_v_problem; struct model *__pyx_v_model; char const * __pyx_v_error_msg; int __pyx_v_len_w; + PyArrayObject *__pyx_v_class_weight_label = 0; PyArrayObject *__pyx_v_w = 0; int __pyx_v_nr_class; + int __pyx_v_labels_; + PyArrayObject *__pyx_v_n_iter = 0; int __pyx_v_nr_feature; - __Pyx_LocalBuf_ND __pyx_pybuffernd_X; - __Pyx_Buffer __pyx_pybuffer_X; __Pyx_LocalBuf_ND __pyx_pybuffernd_Y; __Pyx_Buffer __pyx_pybuffer_Y; + __Pyx_LocalBuf_ND __pyx_pybuffernd_class_weight; + __Pyx_Buffer __pyx_pybuffer_class_weight; + __Pyx_LocalBuf_ND __pyx_pybuffernd_class_weight_label; + __Pyx_Buffer __pyx_pybuffer_class_weight_label; + __Pyx_LocalBuf_ND __pyx_pybuffernd_n_iter; + __Pyx_Buffer __pyx_pybuffer_n_iter; __Pyx_LocalBuf_ND __pyx_pybuffernd_w; __Pyx_Buffer __pyx_pybuffer_w; - __Pyx_LocalBuf_ND __pyx_pybuffernd_weight; - __Pyx_Buffer __pyx_pybuffer_weight; - __Pyx_LocalBuf_ND __pyx_pybuffernd_weight_label; - __Pyx_Buffer __pyx_pybuffer_weight_label; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; @@ -1333,76 +1399,214 @@ static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyOb PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - int __pyx_t_7; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; + __pyx_t_5numpy_int32_t __pyx_t_9; + PyArrayObject *__pyx_t_10 = NULL; + PyArrayObject *__pyx_t_11 = NULL; + int __pyx_t_12; + PyArrayObject *__pyx_t_13 = NULL; + int __pyx_t_14; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + PyObject *__pyx_t_17 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("train_wrap", 0); + __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight_label.refcount = 0; + __pyx_pybuffernd_class_weight_label.data = NULL; + __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_w.pybuffer.buf = NULL; __pyx_pybuffer_w.refcount = 0; __pyx_pybuffernd_w.data = NULL; __pyx_pybuffernd_w.rcbuffer = &__pyx_pybuffer_w; - __pyx_pybuffer_X.pybuffer.buf = NULL; - __pyx_pybuffer_X.refcount = 0; - __pyx_pybuffernd_X.data = NULL; - __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + __pyx_pybuffer_n_iter.pybuffer.buf = NULL; + __pyx_pybuffer_n_iter.refcount = 0; + __pyx_pybuffernd_n_iter.data = NULL; + __pyx_pybuffernd_n_iter.rcbuffer = &__pyx_pybuffer_n_iter; __pyx_pybuffer_Y.pybuffer.buf = NULL; __pyx_pybuffer_Y.refcount = 0; __pyx_pybuffernd_Y.data = NULL; __pyx_pybuffernd_Y.rcbuffer = &__pyx_pybuffer_Y; - __pyx_pybuffer_weight_label.pybuffer.buf = NULL; - __pyx_pybuffer_weight_label.refcount = 0; - __pyx_pybuffernd_weight_label.data = NULL; - __pyx_pybuffernd_weight_label.rcbuffer = &__pyx_pybuffer_weight_label; - __pyx_pybuffer_weight.pybuffer.buf = NULL; - __pyx_pybuffer_weight.refcount = 0; - __pyx_pybuffernd_weight.data = NULL; - __pyx_pybuffernd_weight.rcbuffer = &__pyx_pybuffer_weight; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; + __pyx_pybuffer_class_weight.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight.refcount = 0; + __pyx_pybuffernd_class_weight.data = NULL; + __pyx_pybuffernd_class_weight.rcbuffer = &__pyx_pybuffer_class_weight; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Y.rcbuffer->pybuffer, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Y.rcbuffer->pybuffer, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_Y.diminfo[0].strides = __pyx_pybuffernd_Y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_Y.diminfo[0].shape = __pyx_pybuffernd_Y.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_weight_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_pybuffernd_weight_label.diminfo[0].strides = __pyx_pybuffernd_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weight_label.diminfo[0].shape = __pyx_pybuffernd_weight_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_weight.diminfo[0].strides = __pyx_pybuffernd_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weight.diminfo[0].shape = __pyx_pybuffernd_weight.rcbuffer->pybuffer.shape[0]; + __pyx_pybuffernd_class_weight.diminfo[0].strides = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight.diminfo[0].shape = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.shape[0]; - /* "sklearn/svm/liblinear.pyx":26 + /* "sklearn/svm/liblinear.pyx":24 * cdef int len_w * - * problem = set_problem(X.data, Y.data, X.shape, bias) # <<<<<<<<<<<<<< - * - * param = set_parameter(solver_type, eps, C, weight.shape[0], weight_label.data, weight.data) + * if is_sparse: # <<<<<<<<<<<<<< + * problem = csr_set_problem( + * (X.data).data, */ - __pyx_v_problem = set_problem(__pyx_v_X->data, __pyx_v_Y->data, __pyx_v_X->dimensions, __pyx_v_bias); + __pyx_t_1 = (__pyx_v_is_sparse != 0); + if (__pyx_t_1) { - /* "sklearn/svm/liblinear.pyx":28 - * problem = set_problem(X.data, Y.data, X.shape, bias) - * - * param = set_parameter(solver_type, eps, C, weight.shape[0], weight_label.data, weight.data) # <<<<<<<<<<<<<< + /* "sklearn/svm/liblinear.pyx":26 + * if is_sparse: + * problem = csr_set_problem( + * (X.data).data, # <<<<<<<<<<<<<< + * (X.indices).shape, + * (X.indices).data, + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + + /* "sklearn/svm/liblinear.pyx":27 + * problem = csr_set_problem( + * (X.data).data, + * (X.indices).shape, # <<<<<<<<<<<<<< + * (X.indices).data, + * (X.indptr).shape, + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "sklearn/svm/liblinear.pyx":28 + * (X.data).data, + * (X.indices).shape, + * (X.indices).data, # <<<<<<<<<<<<<< + * (X.indptr).shape, + * (X.indptr).data, + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + + /* "sklearn/svm/liblinear.pyx":29 + * (X.indices).shape, + * (X.indices).data, + * (X.indptr).shape, # <<<<<<<<<<<<<< + * (X.indptr).data, + * Y.data, (X.shape[1]), bias) + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + + /* "sklearn/svm/liblinear.pyx":30 + * (X.indices).data, + * (X.indptr).shape, + * (X.indptr).data, # <<<<<<<<<<<<<< + * Y.data, (X.shape[1]), bias) + * else: + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "sklearn/svm/liblinear.pyx":31 + * (X.indptr).shape, + * (X.indptr).data, + * Y.data, (X.shape[1]), bias) # <<<<<<<<<<<<<< + * else: + * problem = set_problem( + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_GetItemInt(__pyx_t_7, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_8 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_9 = __Pyx_PyInt_As_npy_int32(__pyx_t_8); if (unlikely((__pyx_t_9 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "sklearn/svm/liblinear.pyx":25 * - * error_msg = check_parameter(problem, param) + * if is_sparse: + * problem = csr_set_problem( # <<<<<<<<<<<<<< + * (X.data).data, + * (X.indices).shape, + */ + __pyx_v_problem = csr_set_problem(((PyArrayObject *)__pyx_t_2)->data, ((PyArrayObject *)__pyx_t_3)->dimensions, ((PyArrayObject *)__pyx_t_4)->data, ((PyArrayObject *)__pyx_t_5)->dimensions, ((PyArrayObject *)__pyx_t_6)->data, __pyx_v_Y->data, ((__pyx_t_5numpy_int32_t)__pyx_t_9), __pyx_v_bias); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/svm/liblinear.pyx":33 + * Y.data, (X.shape[1]), bias) + * else: + * problem = set_problem( # <<<<<<<<<<<<<< + * (X).data, + * Y.data, + */ + __pyx_v_problem = set_problem(((PyArrayObject *)__pyx_v_X)->data, __pyx_v_Y->data, ((PyArrayObject *)__pyx_v_X)->dimensions, __pyx_v_bias); + } + __pyx_L3:; + + /* "sklearn/svm/liblinear.pyx":40 + * + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.intc) # <<<<<<<<<<<<<< + * param = set_parameter(solver_type, eps, C, class_weight.shape[0], + * class_weight_label.data, class_weight.data, + */ + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_arange); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_class_weight->dimensions[0])); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_intc); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_6); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = ((PyArrayObject *)__pyx_t_2); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_class_weight_label = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_10 = 0; + __pyx_v_class_weight_label = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/svm/liblinear.pyx":41 + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.intc) + * param = set_parameter(solver_type, eps, C, class_weight.shape[0], # <<<<<<<<<<<<<< + * class_weight_label.data, class_weight.data, + * max_iter, random_seed, epsilon) */ - __pyx_v_param = set_parameter(__pyx_v_solver_type, __pyx_v_eps, __pyx_v_C, (__pyx_v_weight->dimensions[0]), __pyx_v_weight_label->data, __pyx_v_weight->data); + __pyx_v_param = set_parameter(__pyx_v_solver_type, __pyx_v_eps, __pyx_v_C, (__pyx_v_class_weight->dimensions[0]), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data, __pyx_v_max_iter, __pyx_v_random_seed, __pyx_v_epsilon); - /* "sklearn/svm/liblinear.pyx":30 - * param = set_parameter(solver_type, eps, C, weight.shape[0], weight_label.data, weight.data) + /* "sklearn/svm/liblinear.pyx":45 + * max_iter, random_seed, epsilon) * * error_msg = check_parameter(problem, param) # <<<<<<<<<<<<<< * if error_msg: @@ -1410,7 +1614,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyOb */ __pyx_v_error_msg = check_parameter(__pyx_v_problem, __pyx_v_param); - /* "sklearn/svm/liblinear.pyx":31 + /* "sklearn/svm/liblinear.pyx":46 * * error_msg = check_parameter(problem, param) * if error_msg: # <<<<<<<<<<<<<< @@ -1420,7 +1624,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyOb __pyx_t_1 = (__pyx_v_error_msg != 0); if (__pyx_t_1) { - /* "sklearn/svm/liblinear.pyx":32 + /* "sklearn/svm/liblinear.pyx":47 * error_msg = check_parameter(problem, param) * if error_msg: * free_problem(problem) # <<<<<<<<<<<<<< @@ -1429,7 +1633,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyOb */ free_problem(__pyx_v_problem); - /* "sklearn/svm/liblinear.pyx":33 + /* "sklearn/svm/liblinear.pyx":48 * if error_msg: * free_problem(problem) * free_parameter(param) # <<<<<<<<<<<<<< @@ -1438,151 +1642,279 @@ static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyOb */ free_parameter(__pyx_v_param); - /* "sklearn/svm/liblinear.pyx":34 + /* "sklearn/svm/liblinear.pyx":49 * free_problem(problem) * free_parameter(param) * raise ValueError(error_msg) # <<<<<<<<<<<<<< * * # early return */ - __pyx_t_2 = PyBytes_FromString(__pyx_v_error_msg); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = __Pyx_PyBytes_FromString(__pyx_v_error_msg); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L3:; - /* "sklearn/svm/liblinear.pyx":37 + /* "sklearn/svm/liblinear.pyx":52 * * # early return - * model = train(problem, param) # <<<<<<<<<<<<<< + * with nogil: # <<<<<<<<<<<<<< + * model = train(problem, param) + * + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/svm/liblinear.pyx":53 + * # early return + * with nogil: + * model = train(problem, param) # <<<<<<<<<<<<<< * * # coef matrix holder created as fortran since that's what's used in liblinear */ - __pyx_v_model = train(__pyx_v_problem, __pyx_v_param); + __pyx_v_model = train(__pyx_v_problem, __pyx_v_param); + } - /* "sklearn/svm/liblinear.pyx":41 + /* "sklearn/svm/liblinear.pyx":52 + * + * # early return + * with nogil: # <<<<<<<<<<<<<< + * model = train(problem, param) + * + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L7; + } + __pyx_L7:; + } + } + + /* "sklearn/svm/liblinear.pyx":57 * # coef matrix holder created as fortran since that's what's used in liblinear * cdef np.ndarray[np.float64_t, ndim=2, mode='fortran'] w * cdef int nr_class = get_nr_class(model) # <<<<<<<<<<<<<< - * cdef int nr_feature = get_nr_feature(model) - * if bias > 0: nr_feature = nr_feature + 1 + * + * cdef int labels_ = nr_class */ __pyx_v_nr_class = get_nr_class(__pyx_v_model); - /* "sklearn/svm/liblinear.pyx":42 - * cdef np.ndarray[np.float64_t, ndim=2, mode='fortran'] w + /* "sklearn/svm/liblinear.pyx":59 * cdef int nr_class = get_nr_class(model) + * + * cdef int labels_ = nr_class # <<<<<<<<<<<<<< + * if nr_class == 2: + * labels_ = 1 + */ + __pyx_v_labels_ = __pyx_v_nr_class; + + /* "sklearn/svm/liblinear.pyx":60 + * + * cdef int labels_ = nr_class + * if nr_class == 2: # <<<<<<<<<<<<<< + * labels_ = 1 + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] n_iter = np.zeros(labels_, dtype=np.intc) + */ + __pyx_t_1 = ((__pyx_v_nr_class == 2) != 0); + if (__pyx_t_1) { + + /* "sklearn/svm/liblinear.pyx":61 + * cdef int labels_ = nr_class + * if nr_class == 2: + * labels_ = 1 # <<<<<<<<<<<<<< + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] n_iter = np.zeros(labels_, dtype=np.intc) + * get_n_iter(model, n_iter.data) + */ + __pyx_v_labels_ = 1; + goto __pyx_L8; + } + __pyx_L8:; + + /* "sklearn/svm/liblinear.pyx":62 + * if nr_class == 2: + * labels_ = 1 + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] n_iter = np.zeros(labels_, dtype=np.intc) # <<<<<<<<<<<<<< + * get_n_iter(model, n_iter.data) + * + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_labels_); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_intc); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_4, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = ((PyArrayObject *)__pyx_t_3); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_n_iter.rcbuffer->pybuffer, (PyObject*)__pyx_t_11, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_n_iter = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_n_iter.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_n_iter.diminfo[0].strides = __pyx_pybuffernd_n_iter.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_n_iter.diminfo[0].shape = __pyx_pybuffernd_n_iter.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_11 = 0; + __pyx_v_n_iter = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "sklearn/svm/liblinear.pyx":63 + * labels_ = 1 + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] n_iter = np.zeros(labels_, dtype=np.intc) + * get_n_iter(model, n_iter.data) # <<<<<<<<<<<<<< + * + * cdef int nr_feature = get_nr_feature(model) + */ + get_n_iter(__pyx_v_model, ((int *)__pyx_v_n_iter->data)); + + /* "sklearn/svm/liblinear.pyx":65 + * get_n_iter(model, n_iter.data) + * * cdef int nr_feature = get_nr_feature(model) # <<<<<<<<<<<<<< * if bias > 0: nr_feature = nr_feature + 1 - * if nr_class == 2: + * if nr_class == 2 and solver_type != 4: # solver is not Crammer-Singer */ __pyx_v_nr_feature = get_nr_feature(__pyx_v_model); - /* "sklearn/svm/liblinear.pyx":43 - * cdef int nr_class = get_nr_class(model) + /* "sklearn/svm/liblinear.pyx":66 + * * cdef int nr_feature = get_nr_feature(model) * if bias > 0: nr_feature = nr_feature + 1 # <<<<<<<<<<<<<< - * if nr_class == 2: + * if nr_class == 2 and solver_type != 4: # solver is not Crammer-Singer * w = np.empty((1, nr_feature),order='F') */ - __pyx_t_1 = (__pyx_v_bias > 0.0); + __pyx_t_1 = ((__pyx_v_bias > 0.0) != 0); if (__pyx_t_1) { __pyx_v_nr_feature = (__pyx_v_nr_feature + 1); - goto __pyx_L4; + goto __pyx_L9; } - __pyx_L4:; + __pyx_L9:; - /* "sklearn/svm/liblinear.pyx":44 + /* "sklearn/svm/liblinear.pyx":67 * cdef int nr_feature = get_nr_feature(model) * if bias > 0: nr_feature = nr_feature + 1 - * if nr_class == 2: # <<<<<<<<<<<<<< + * if nr_class == 2 and solver_type != 4: # solver is not Crammer-Singer # <<<<<<<<<<<<<< * w = np.empty((1, nr_feature),order='F') * copy_w(w.data, model, nr_feature) */ - __pyx_t_1 = (__pyx_v_nr_class == 2); + __pyx_t_12 = ((__pyx_v_nr_class == 2) != 0); + if (__pyx_t_12) { + goto __pyx_L12_next_and; + } else { + __pyx_t_1 = __pyx_t_12; + goto __pyx_L11_bool_binop_done; + } + __pyx_L12_next_and:; + __pyx_t_12 = ((__pyx_v_solver_type != 4) != 0); + __pyx_t_1 = __pyx_t_12; + __pyx_L11_bool_binop_done:; if (__pyx_t_1) { - /* "sklearn/svm/liblinear.pyx":45 + /* "sklearn/svm/liblinear.pyx":68 * if bias > 0: nr_feature = nr_feature + 1 - * if nr_class == 2: + * if nr_class == 2 and solver_type != 4: # solver is not Crammer-Singer * w = np.empty((1, nr_feature),order='F') # <<<<<<<<<<<<<< * copy_w(w.data, model, nr_feature) * else: */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyInt_FromLong(__pyx_v_nr_feature); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_nr_feature); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_INCREF(__pyx_int_1); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_int_1); __Pyx_GIVEREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__F)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_order, __pyx_n_s_F) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = ((PyArrayObject *)__pyx_t_6); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); + __pyx_t_14 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_t_13, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_14 < 0)) { + PyErr_Fetch(&__pyx_t_15, &__pyx_t_16, &__pyx_t_17); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_v_w, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); + Py_XDECREF(__pyx_t_15); Py_XDECREF(__pyx_t_16); Py_XDECREF(__pyx_t_17); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); + PyErr_Restore(__pyx_t_15, __pyx_t_16, __pyx_t_17); } } __pyx_pybuffernd_w.diminfo[0].strides = __pyx_pybuffernd_w.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_w.diminfo[0].shape = __pyx_pybuffernd_w.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_w.diminfo[1].strides = __pyx_pybuffernd_w.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_w.diminfo[1].shape = __pyx_pybuffernd_w.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_14 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_13 = 0; + __pyx_v_w = ((PyArrayObject *)__pyx_t_6); __pyx_t_6 = 0; - __pyx_v_w = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; - /* "sklearn/svm/liblinear.pyx":46 - * if nr_class == 2: + /* "sklearn/svm/liblinear.pyx":69 + * if nr_class == 2 and solver_type != 4: # solver is not Crammer-Singer * w = np.empty((1, nr_feature),order='F') * copy_w(w.data, model, nr_feature) # <<<<<<<<<<<<<< * else: * len_w = (nr_class) * nr_feature */ copy_w(__pyx_v_w->data, __pyx_v_model, __pyx_v_nr_feature); - goto __pyx_L5; + goto __pyx_L10; } /*else*/ { - /* "sklearn/svm/liblinear.pyx":48 + /* "sklearn/svm/liblinear.pyx":71 * copy_w(w.data, model, nr_feature) * else: * len_w = (nr_class) * nr_feature # <<<<<<<<<<<<<< @@ -1591,66 +1923,66 @@ static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyOb */ __pyx_v_len_w = (__pyx_v_nr_class * __pyx_v_nr_feature); - /* "sklearn/svm/liblinear.pyx":49 + /* "sklearn/svm/liblinear.pyx":72 * else: * len_w = (nr_class) * nr_feature * w = np.empty((nr_class, nr_feature),order='F') # <<<<<<<<<<<<<< * copy_w(w.data, model, len_w) * */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyInt_FromLong(__pyx_v_nr_class); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = PyInt_FromLong(__pyx_v_nr_feature); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyInt_From_int(__pyx_v_nr_class); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_nr_feature); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_6 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_5 = 0; __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); - __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__F)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_order, __pyx_n_s_F) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = ((PyArrayObject *)__pyx_t_6); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); + __pyx_t_14 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_t_13, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_14 < 0)) { + PyErr_Fetch(&__pyx_t_17, &__pyx_t_16, &__pyx_t_15); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_v_w, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); + Py_XDECREF(__pyx_t_17); Py_XDECREF(__pyx_t_16); Py_XDECREF(__pyx_t_15); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); + PyErr_Restore(__pyx_t_17, __pyx_t_16, __pyx_t_15); } } __pyx_pybuffernd_w.diminfo[0].strides = __pyx_pybuffernd_w.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_w.diminfo[0].shape = __pyx_pybuffernd_w.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_w.diminfo[1].strides = __pyx_pybuffernd_w.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_w.diminfo[1].shape = __pyx_pybuffernd_w.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_14 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + __pyx_t_13 = 0; + __pyx_v_w = ((PyArrayObject *)__pyx_t_6); __pyx_t_6 = 0; - __pyx_v_w = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; - /* "sklearn/svm/liblinear.pyx":50 + /* "sklearn/svm/liblinear.pyx":73 * len_w = (nr_class) * nr_feature * w = np.empty((nr_class, nr_feature),order='F') * copy_w(w.data, model, len_w) # <<<<<<<<<<<<<< @@ -1659,9 +1991,9 @@ static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyOb */ copy_w(__pyx_v_w->data, __pyx_v_model, __pyx_v_len_w); } - __pyx_L5:; + __pyx_L10:; - /* "sklearn/svm/liblinear.pyx":53 + /* "sklearn/svm/liblinear.pyx":76 * * ### FREE * free_and_destroy_model(&model) # <<<<<<<<<<<<<< @@ -1670,1014 +2002,367 @@ static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_train_wrap(CYTHON_UNUSED PyOb */ free_and_destroy_model((&__pyx_v_model)); - /* "sklearn/svm/liblinear.pyx":54 + /* "sklearn/svm/liblinear.pyx":77 * ### FREE * free_and_destroy_model(&model) * free_problem(problem) # <<<<<<<<<<<<<< * free_parameter(param) - * # destroy_param(param) don't call this or it will destroy weight_label and weight + * # destroy_param(param) don't call this or it will destroy class_weight_label and class_weight */ free_problem(__pyx_v_problem); - /* "sklearn/svm/liblinear.pyx":55 + /* "sklearn/svm/liblinear.pyx":78 * free_and_destroy_model(&model) * free_problem(problem) * free_parameter(param) # <<<<<<<<<<<<<< - * # destroy_param(param) don't call this or it will destroy weight_label and weight + * # destroy_param(param) don't call this or it will destroy class_weight_label and class_weight * */ free_parameter(__pyx_v_param); - /* "sklearn/svm/liblinear.pyx":58 - * # destroy_param(param) don't call this or it will destroy weight_label and weight + /* "sklearn/svm/liblinear.pyx":81 + * # destroy_param(param) don't call this or it will destroy class_weight_label and class_weight * - * return w # <<<<<<<<<<<<<< + * return w, n_iter # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); __Pyx_INCREF(((PyObject *)__pyx_v_w)); - __pyx_r = ((PyObject *)__pyx_v_w); + PyTuple_SET_ITEM(__pyx_t_6, 0, ((PyObject *)__pyx_v_w)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); + __Pyx_INCREF(((PyObject *)__pyx_v_n_iter)); + PyTuple_SET_ITEM(__pyx_t_6, 1, ((PyObject *)__pyx_v_n_iter)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_n_iter)); + __pyx_r = __pyx_t_6; + __pyx_t_6 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/svm/liblinear.pyx":14 + * + * + * def train_wrap(X, np.ndarray[np.float64_t, ndim=1, mode='c'] Y, # <<<<<<<<<<<<<< + * bint is_sparse, int solver_type, double eps, double bias, + * double C, np.ndarray[np.float64_t, ndim=1] class_weight, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Y.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_n_iter.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.svm.liblinear.train_wrap", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Y.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_n_iter.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer); __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_class_weight_label); __Pyx_XDECREF((PyObject *)__pyx_v_w); + __Pyx_XDECREF((PyObject *)__pyx_v_n_iter); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/svm/liblinear.pyx":61 +/* "sklearn/svm/liblinear.pyx":84 * * - * cdef _csr_train_wrap(np.int32_t n_features, # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] X_values, - * np.ndarray[np.int32_t, ndim=1, mode='c'] X_indices, + * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< + * """ + * Control verbosity of libsvm library */ -static PyObject *__pyx_f_7sklearn_3svm_9liblinear__csr_train_wrap(__pyx_t_5numpy_int32_t __pyx_v_n_features, PyArrayObject *__pyx_v_X_values, PyArrayObject *__pyx_v_X_indices, PyArrayObject *__pyx_v_X_indptr, PyArrayObject *__pyx_v_Y, int __pyx_v_solver_type, double __pyx_v_eps, double __pyx_v_bias, double __pyx_v_C, PyArrayObject *__pyx_v_weight_label, PyArrayObject *__pyx_v_weight) { - struct parameter *__pyx_v_param; - struct problem *__pyx_v_problem; - struct model *__pyx_v_model; - char const * __pyx_v_error_msg; - int __pyx_v_len_w; - PyArrayObject *__pyx_v_w = 0; - int __pyx_v_nr_class; - int __pyx_v_nr_feature; - __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indices; - __Pyx_Buffer __pyx_pybuffer_X_indices; - __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indptr; - __Pyx_Buffer __pyx_pybuffer_X_indptr; - __Pyx_LocalBuf_ND __pyx_pybuffernd_X_values; - __Pyx_Buffer __pyx_pybuffer_X_values; - __Pyx_LocalBuf_ND __pyx_pybuffernd_Y; - __Pyx_Buffer __pyx_pybuffer_Y; - __Pyx_LocalBuf_ND __pyx_pybuffernd_w; - __Pyx_Buffer __pyx_pybuffer_w; - __Pyx_LocalBuf_ND __pyx_pybuffernd_weight; - __Pyx_Buffer __pyx_pybuffer_weight; - __Pyx_LocalBuf_ND __pyx_pybuffernd_weight_label; - __Pyx_Buffer __pyx_pybuffer_weight_label; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_3svm_9liblinear_3set_verbosity_wrap(PyObject *__pyx_self, PyObject *__pyx_arg_verbosity); /*proto*/ +static char __pyx_doc_7sklearn_3svm_9liblinear_2set_verbosity_wrap[] = "\n Control verbosity of libsvm library\n "; +static PyMethodDef __pyx_mdef_7sklearn_3svm_9liblinear_3set_verbosity_wrap = {"set_verbosity_wrap", (PyCFunction)__pyx_pw_7sklearn_3svm_9liblinear_3set_verbosity_wrap, METH_O, __pyx_doc_7sklearn_3svm_9liblinear_2set_verbosity_wrap}; +static PyObject *__pyx_pw_7sklearn_3svm_9liblinear_3set_verbosity_wrap(PyObject *__pyx_self, PyObject *__pyx_arg_verbosity) { + int __pyx_v_verbosity; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_csr_train_wrap", 0); - __pyx_pybuffer_w.pybuffer.buf = NULL; - __pyx_pybuffer_w.refcount = 0; - __pyx_pybuffernd_w.data = NULL; - __pyx_pybuffernd_w.rcbuffer = &__pyx_pybuffer_w; - __pyx_pybuffer_X_values.pybuffer.buf = NULL; - __pyx_pybuffer_X_values.refcount = 0; - __pyx_pybuffernd_X_values.data = NULL; - __pyx_pybuffernd_X_values.rcbuffer = &__pyx_pybuffer_X_values; - __pyx_pybuffer_X_indices.pybuffer.buf = NULL; - __pyx_pybuffer_X_indices.refcount = 0; - __pyx_pybuffernd_X_indices.data = NULL; - __pyx_pybuffernd_X_indices.rcbuffer = &__pyx_pybuffer_X_indices; - __pyx_pybuffer_X_indptr.pybuffer.buf = NULL; - __pyx_pybuffer_X_indptr.refcount = 0; - __pyx_pybuffernd_X_indptr.data = NULL; - __pyx_pybuffernd_X_indptr.rcbuffer = &__pyx_pybuffer_X_indptr; - __pyx_pybuffer_Y.pybuffer.buf = NULL; - __pyx_pybuffer_Y.refcount = 0; - __pyx_pybuffernd_Y.data = NULL; - __pyx_pybuffernd_Y.rcbuffer = &__pyx_pybuffer_Y; - __pyx_pybuffer_weight_label.pybuffer.buf = NULL; - __pyx_pybuffer_weight_label.refcount = 0; - __pyx_pybuffernd_weight_label.data = NULL; - __pyx_pybuffernd_weight_label.rcbuffer = &__pyx_pybuffer_weight_label; - __pyx_pybuffer_weight.pybuffer.buf = NULL; - __pyx_pybuffer_weight.refcount = 0; - __pyx_pybuffernd_weight.data = NULL; - __pyx_pybuffernd_weight.rcbuffer = &__pyx_pybuffer_weight; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_X_values, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_X_values.diminfo[0].strides = __pyx_pybuffernd_X_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_values.diminfo[0].shape = __pyx_pybuffernd_X_values.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_X_indices, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_X_indices.diminfo[0].strides = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indices.diminfo[0].shape = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_X_indptr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_X_indptr.diminfo[0].strides = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indptr.diminfo[0].shape = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Y.rcbuffer->pybuffer, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_Y.diminfo[0].strides = __pyx_pybuffernd_Y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_Y.diminfo[0].shape = __pyx_pybuffernd_Y.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_weight_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_weight_label.diminfo[0].strides = __pyx_pybuffernd_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weight_label.diminfo[0].shape = __pyx_pybuffernd_weight_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("set_verbosity_wrap (wrapper)", 0); + assert(__pyx_arg_verbosity); { + __pyx_v_verbosity = __Pyx_PyInt_As_int(__pyx_arg_verbosity); if (unlikely((__pyx_v_verbosity == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - __pyx_pybuffernd_weight.diminfo[0].strides = __pyx_pybuffernd_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weight.diminfo[0].shape = __pyx_pybuffernd_weight.rcbuffer->pybuffer.shape[0]; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.svm.liblinear.set_verbosity_wrap", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_3svm_9liblinear_2set_verbosity_wrap(__pyx_self, ((int)__pyx_v_verbosity)); - /* "sklearn/svm/liblinear.pyx":77 - * problem = csr_set_problem(X_values.data, X_indices.shape, - * X_indices.data, X_indptr.shape, - * X_indptr.data, Y.data, n_features, bias) # <<<<<<<<<<<<<< - * - * param = set_parameter(solver_type, eps, C, weight.shape[0], + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_2set_verbosity_wrap(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_verbosity) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("set_verbosity_wrap", 0); + + /* "sklearn/svm/liblinear.pyx":88 + * Control verbosity of libsvm library + * """ + * set_verbosity(verbosity) # <<<<<<<<<<<<<< */ - __pyx_v_problem = csr_set_problem(__pyx_v_X_values->data, __pyx_v_X_indices->dimensions, __pyx_v_X_indices->data, __pyx_v_X_indptr->dimensions, __pyx_v_X_indptr->data, __pyx_v_Y->data, __pyx_v_n_features, __pyx_v_bias); + set_verbosity(__pyx_v_verbosity); - /* "sklearn/svm/liblinear.pyx":80 + /* "sklearn/svm/liblinear.pyx":84 * - * param = set_parameter(solver_type, eps, C, weight.shape[0], - * weight_label.data, weight.data) # <<<<<<<<<<<<<< * - * error_msg = check_parameter(problem, param) + * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< + * """ + * Control verbosity of libsvm library */ - __pyx_v_param = set_parameter(__pyx_v_solver_type, __pyx_v_eps, __pyx_v_C, (__pyx_v_weight->dimensions[0]), __pyx_v_weight_label->data, __pyx_v_weight->data); - /* "sklearn/svm/liblinear.pyx":82 - * weight_label.data, weight.data) - * - * error_msg = check_parameter(problem, param) # <<<<<<<<<<<<<< - * if error_msg: - * free_problem(problem) - */ - __pyx_v_error_msg = check_parameter(__pyx_v_problem, __pyx_v_param); + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/svm/liblinear.pyx":83 - * - * error_msg = check_parameter(problem, param) - * if error_msg: # <<<<<<<<<<<<<< - * free_problem(problem) - * free_parameter(param) +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. */ - __pyx_t_1 = (__pyx_v_error_msg != 0); - if (__pyx_t_1) { - /* "sklearn/svm/liblinear.pyx":84 - * error_msg = check_parameter(problem, param) - * if error_msg: - * free_problem(problem) # <<<<<<<<<<<<<< - * free_parameter(param) - * raise ValueError(error_msg) - */ - free_problem(__pyx_v_problem); +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); - /* "sklearn/svm/liblinear.pyx":85 - * if error_msg: - * free_problem(problem) - * free_parameter(param) # <<<<<<<<<<<<<< - * raise ValueError(error_msg) - * - */ - free_parameter(__pyx_v_param); + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/svm/liblinear.pyx":86 - * free_problem(problem) - * free_parameter(param) - * raise ValueError(error_msg) # <<<<<<<<<<<<<< +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":200 + * # of flags * - * # early return + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim */ - __pyx_t_2 = PyBytes_FromString(__pyx_v_error_msg); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; } - __pyx_L3:; - /* "sklearn/svm/liblinear.pyx":89 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":203 * - * # early return - * model = train(problem, param) # <<<<<<<<<<<<<< + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) * - * # fortran order since that's what liblinear does */ - __pyx_v_model = train(__pyx_v_problem, __pyx_v_param); + __pyx_v_endian_detector = 1; - /* "sklearn/svm/liblinear.pyx":93 - * # fortran order since that's what liblinear does - * cdef np.ndarray[np.float64_t, ndim=2, mode='fortran'] w - * cdef int nr_class = get_nr_class(model) # <<<<<<<<<<<<<< - * cdef int nr_feature = n_features - * if bias > 0: nr_feature = nr_feature + 1 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) */ - __pyx_v_nr_class = get_nr_class(__pyx_v_model); + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "sklearn/svm/liblinear.pyx":94 - * cdef np.ndarray[np.float64_t, ndim=2, mode='fortran'] w - * cdef int nr_class = get_nr_class(model) - * cdef int nr_feature = n_features # <<<<<<<<<<<<<< - * if bias > 0: nr_feature = nr_feature + 1 - * if nr_class == 2: + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_nr_feature = __pyx_v_n_features; + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "sklearn/svm/liblinear.pyx":95 - * cdef int nr_class = get_nr_class(model) - * cdef int nr_feature = n_features - * if bias > 0: nr_feature = nr_feature + 1 # <<<<<<<<<<<<<< - * if nr_class == 2: - * w = np.empty((1, nr_feature),order='F') + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: */ - __pyx_t_1 = (__pyx_v_bias > 0.0); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - __pyx_v_nr_feature = (__pyx_v_nr_feature + 1); + + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; goto __pyx_L4; } + /*else*/ { + + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } __pyx_L4:; - /* "sklearn/svm/liblinear.pyx":96 - * cdef int nr_feature = n_features - * if bias > 0: nr_feature = nr_feature + 1 - * if nr_class == 2: # <<<<<<<<<<<<<< - * w = np.empty((1, nr_feature),order='F') - * copy_w(w.data, model, nr_feature) + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_2) { + goto __pyx_L7_next_and; + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L6_bool_binop_done; + } + __pyx_L7_next_and:; + + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * */ - __pyx_t_1 = (__pyx_v_nr_class == 2); + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L6_bool_binop_done:; if (__pyx_t_1) { - /* "sklearn/svm/liblinear.pyx":97 - * if bias > 0: nr_feature = nr_feature + 1 - * if nr_class == 2: - * w = np.empty((1, nr_feature),order='F') # <<<<<<<<<<<<<< - * copy_w(w.data, model, nr_feature) - * else: + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyInt_FromLong(__pyx_v_nr_feature); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_int_1); - __Pyx_GIVEREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); - __pyx_t_4 = 0; - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__F)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_v_w, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); - } - } - __pyx_pybuffernd_w.diminfo[0].strides = __pyx_pybuffernd_w.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_w.diminfo[0].shape = __pyx_pybuffernd_w.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_w.diminfo[1].strides = __pyx_pybuffernd_w.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_w.diminfo[1].shape = __pyx_pybuffernd_w.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_6 = 0; - __pyx_v_w = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "sklearn/svm/liblinear.pyx":98 - * if nr_class == 2: - * w = np.empty((1, nr_feature),order='F') - * copy_w(w.data, model, nr_feature) # <<<<<<<<<<<<<< - * else: - * len_w = (nr_class * nr_feature) + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") */ - copy_w(__pyx_v_w->data, __pyx_v_model, __pyx_v_nr_feature); - goto __pyx_L5; + __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_2) { + goto __pyx_L10_next_and; + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L9_bool_binop_done; } - /*else*/ { + __pyx_L10_next_and:; - /* "sklearn/svm/liblinear.pyx":100 - * copy_w(w.data, model, nr_feature) - * else: - * len_w = (nr_class * nr_feature) # <<<<<<<<<<<<<< - * w = np.empty((nr_class, nr_feature),order='F') - * copy_w(w.data, model, len_w) + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * */ - __pyx_v_len_w = (__pyx_v_nr_class * __pyx_v_nr_feature); + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L9_bool_binop_done:; + if (__pyx_t_1) { - /* "sklearn/svm/liblinear.pyx":101 - * else: - * len_w = (nr_class * nr_feature) - * w = np.empty((nr_class, nr_feature),order='F') # <<<<<<<<<<<<<< - * copy_w(w.data, model, len_w) + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * + * info.buf = PyArray_DATA(self) */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyInt_FromLong(__pyx_v_nr_class); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = PyInt_FromLong(__pyx_v_nr_feature); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_5 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); - __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__F)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_v_w, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); - } - } - __pyx_pybuffernd_w.diminfo[0].strides = __pyx_pybuffernd_w.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_w.diminfo[0].shape = __pyx_pybuffernd_w.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_w.diminfo[1].strides = __pyx_pybuffernd_w.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_w.diminfo[1].shape = __pyx_pybuffernd_w.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_6 = 0; - __pyx_v_w = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } - /* "sklearn/svm/liblinear.pyx":102 - * len_w = (nr_class * nr_feature) - * w = np.empty((nr_class, nr_feature),order='F') - * copy_w(w.data, model, len_w) # <<<<<<<<<<<<<< + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") * - * ### FREE + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: */ - copy_w(__pyx_v_w->data, __pyx_v_model, __pyx_v_len_w); - } - __pyx_L5:; + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "sklearn/svm/liblinear.pyx":105 - * - * ### FREE - * free_and_destroy_model(&model) # <<<<<<<<<<<<<< - * free_problem(problem) - * free_parameter(param) - */ - free_and_destroy_model((&__pyx_v_model)); - - /* "sklearn/svm/liblinear.pyx":106 - * ### FREE - * free_and_destroy_model(&model) - * free_problem(problem) # <<<<<<<<<<<<<< - * free_parameter(param) - * # destroy_param(param) don't call this or it will destroy weight_label and weight - */ - free_problem(__pyx_v_problem); - - /* "sklearn/svm/liblinear.pyx":107 - * free_and_destroy_model(&model) - * free_problem(problem) - * free_parameter(param) # <<<<<<<<<<<<<< - * # destroy_param(param) don't call this or it will destroy weight_label and weight - * - */ - free_parameter(__pyx_v_param); - - /* "sklearn/svm/liblinear.pyx":110 - * # destroy_param(param) don't call this or it will destroy weight_label and weight - * - * return w # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - __pyx_r = ((PyObject *)__pyx_v_w); - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_values.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Y.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.svm.liblinear._csr_train_wrap", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_values.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Y.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_w); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_3svm_9liblinear_3csr_train_wrap(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_3svm_9liblinear_2csr_train_wrap[] = "\n Wrapper for train.\n\n X matrix is given in CSR sparse format.\n "; -static PyMethodDef __pyx_mdef_7sklearn_3svm_9liblinear_3csr_train_wrap = {__Pyx_NAMESTR("csr_train_wrap"), (PyCFunction)__pyx_pw_7sklearn_3svm_9liblinear_3csr_train_wrap, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_3svm_9liblinear_2csr_train_wrap)}; -static PyObject *__pyx_pw_7sklearn_3svm_9liblinear_3csr_train_wrap(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_X = 0; - PyObject *__pyx_v_Y = 0; - PyObject *__pyx_v_solver_type = 0; - PyObject *__pyx_v_eps = 0; - PyObject *__pyx_v_bias = 0; - PyObject *__pyx_v_C = 0; - PyObject *__pyx_v_weight_label = 0; - PyObject *__pyx_v_weight = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__Y,&__pyx_n_s__solver_type,&__pyx_n_s__eps,&__pyx_n_s__bias,&__pyx_n_s__C,&__pyx_n_s__weight_label,&__pyx_n_s__weight,0}; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("csr_train_wrap (wrapper)", 0); - __pyx_self = __pyx_self; - { - PyObject* values[8] = {0,0,0,0,0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__Y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("csr_train_wrap", 1, 8, 8, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__solver_type); - if (likely(values[2])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("csr_train_wrap", 1, 8, 8, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__eps); - if (likely(values[3])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("csr_train_wrap", 1, 8, 8, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__bias); - if (likely(values[4])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("csr_train_wrap", 1, 8, 8, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C); - if (likely(values[5])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("csr_train_wrap", 1, 8, 8, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight_label); - if (likely(values[6])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("csr_train_wrap", 1, 8, 8, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 7: - values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight); - if (likely(values[7])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("csr_train_wrap", 1, 8, 8, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "csr_train_wrap") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 8) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - } - __pyx_v_X = values[0]; - __pyx_v_Y = values[1]; - __pyx_v_solver_type = values[2]; - __pyx_v_eps = values[3]; - __pyx_v_bias = values[4]; - __pyx_v_C = values[5]; - __pyx_v_weight_label = values[6]; - __pyx_v_weight = values[7]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("csr_train_wrap", 1, 8, 8, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.svm.liblinear.csr_train_wrap", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7sklearn_3svm_9liblinear_2csr_train_wrap(__pyx_self, __pyx_v_X, __pyx_v_Y, __pyx_v_solver_type, __pyx_v_eps, __pyx_v_bias, __pyx_v_C, __pyx_v_weight_label, __pyx_v_weight); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/svm/liblinear.pyx":113 - * - * - * def csr_train_wrap(X, Y, solver_type, eps, bias, C, weight_label, weight): # <<<<<<<<<<<<<< - * """ - * Wrapper for train. - */ - -static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_2csr_train_wrap(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, PyObject *__pyx_v_Y, PyObject *__pyx_v_solver_type, PyObject *__pyx_v_eps, PyObject *__pyx_v_bias, PyObject *__pyx_v_C, PyObject *__pyx_v_weight_label, PyObject *__pyx_v_weight) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - __pyx_t_5numpy_int32_t __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - double __pyx_t_7; - double __pyx_t_8; - double __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("csr_train_wrap", 0); - - /* "sklearn/svm/liblinear.pyx":119 - * X matrix is given in CSR sparse format. - * """ - * return _csr_train_wrap(X.shape[1], X.data, X.indices, X.indptr, Y, # <<<<<<<<<<<<<< - * solver_type, eps, bias, C, weight_label, weight) - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyInt_from_py_npy_int32(__pyx_t_2); if (unlikely((__pyx_t_3 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__data); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__indptr); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (!(likely(((__pyx_v_Y) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_Y, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = __pyx_v_Y; - __Pyx_INCREF(__pyx_t_5); - - /* "sklearn/svm/liblinear.pyx":120 - * """ - * return _csr_train_wrap(X.shape[1], X.data, X.indices, X.indptr, Y, - * solver_type, eps, bias, C, weight_label, weight) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_6 = __Pyx_PyInt_AsInt(__pyx_v_solver_type); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = __pyx_PyFloat_AsDouble(__pyx_v_eps); if (unlikely((__pyx_t_7 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_8 = __pyx_PyFloat_AsDouble(__pyx_v_bias); if (unlikely((__pyx_t_8 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_9 = __pyx_PyFloat_AsDouble(__pyx_v_C); if (unlikely((__pyx_t_9 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (!(likely(((__pyx_v_weight_label) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_weight_label, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = __pyx_v_weight_label; - __Pyx_INCREF(__pyx_t_10); - if (!(likely(((__pyx_v_weight) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_weight, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_11 = __pyx_v_weight; - __Pyx_INCREF(__pyx_t_11); - __pyx_t_12 = __pyx_f_7sklearn_3svm_9liblinear__csr_train_wrap(__pyx_t_3, ((PyArrayObject *)__pyx_t_2), ((PyArrayObject *)__pyx_t_1), ((PyArrayObject *)__pyx_t_4), ((PyArrayObject *)__pyx_t_5), __pyx_t_6, __pyx_t_7, __pyx_t_8, __pyx_t_9, ((PyArrayObject *)__pyx_t_10), ((PyArrayObject *)__pyx_t_11)); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_r = __pyx_t_12; - __pyx_t_12 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_AddTraceback("sklearn.svm.liblinear.csr_train_wrap", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_3svm_9liblinear_5set_verbosity_wrap(PyObject *__pyx_self, PyObject *__pyx_arg_verbosity); /*proto*/ -static char __pyx_doc_7sklearn_3svm_9liblinear_4set_verbosity_wrap[] = "\n Control verbosity of libsvm library\n "; -static PyMethodDef __pyx_mdef_7sklearn_3svm_9liblinear_5set_verbosity_wrap = {__Pyx_NAMESTR("set_verbosity_wrap"), (PyCFunction)__pyx_pw_7sklearn_3svm_9liblinear_5set_verbosity_wrap, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_3svm_9liblinear_4set_verbosity_wrap)}; -static PyObject *__pyx_pw_7sklearn_3svm_9liblinear_5set_verbosity_wrap(PyObject *__pyx_self, PyObject *__pyx_arg_verbosity) { - int __pyx_v_verbosity; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("set_verbosity_wrap (wrapper)", 0); - __pyx_self = __pyx_self; - assert(__pyx_arg_verbosity); { - __pyx_v_verbosity = __Pyx_PyInt_AsInt(__pyx_arg_verbosity); if (unlikely((__pyx_v_verbosity == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.svm.liblinear.set_verbosity_wrap", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7sklearn_3svm_9liblinear_4set_verbosity_wrap(__pyx_self, ((int)__pyx_v_verbosity)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/svm/liblinear.pyx":123 - * - * - * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< - * """ - * Control verbosity of libsvm library - */ - -static PyObject *__pyx_pf_7sklearn_3svm_9liblinear_4set_verbosity_wrap(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_verbosity) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("set_verbosity_wrap", 0); - - /* "sklearn/svm/liblinear.pyx":127 - * Control verbosity of libsvm library - * """ - * set_verbosity(verbosity) # <<<<<<<<<<<<<< - */ - set_verbosity(__pyx_v_verbosity); - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "numpy.pxd":193 - * # experimental exception made for __getbuffer__ and __releasebuffer__ - * # -- the details of this may change. - * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< - * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP. - */ - -static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_v_copy_shape; - int __pyx_v_i; - int __pyx_v_ndim; - int __pyx_v_endian_detector; - int __pyx_v_little_endian; - int __pyx_v_t; - char *__pyx_v_f; - PyArray_Descr *__pyx_v_descr = 0; - int __pyx_v_offset; - int __pyx_v_hasfields; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - char *__pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__", 0); - if (__pyx_v_info != NULL) { - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); - } - - /* "numpy.pxd":199 - * # of flags - * - * if info == NULL: return # <<<<<<<<<<<<<< - * - * cdef int copy_shape, i, ndim - */ - __pyx_t_1 = (__pyx_v_info == NULL); - if (__pyx_t_1) { - __pyx_r = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "numpy.pxd":202 - * - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * - */ - __pyx_v_endian_detector = 1; - - /* "numpy.pxd":203 - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< - * - * ndim = PyArray_NDIM(self) - */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - - /* "numpy.pxd":205 - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * - * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< - * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - */ - __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - - /* "numpy.pxd":207 - * ndim = PyArray_NDIM(self) - * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * copy_shape = 1 - * else: - */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); - if (__pyx_t_1) { - - /* "numpy.pxd":208 - * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * copy_shape = 1 # <<<<<<<<<<<<<< - * else: - * copy_shape = 0 - */ - __pyx_v_copy_shape = 1; - goto __pyx_L4; - } - /*else*/ { - - /* "numpy.pxd":210 - * copy_shape = 1 - * else: - * copy_shape = 0 # <<<<<<<<<<<<<< - * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - */ - __pyx_v_copy_shape = 0; - } - __pyx_L4:; - - /* "numpy.pxd":212 - * copy_shape = 0 - * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); - if (__pyx_t_1) { - - /* "numpy.pxd":213 - * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not C contiguous") - * - */ - __pyx_t_2 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS)); - __pyx_t_3 = __pyx_t_2; - } else { - __pyx_t_3 = __pyx_t_1; - } - if (__pyx_t_3) { - - /* "numpy.pxd":214 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< - * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "numpy.pxd":216 - * raise ValueError(u"ndarray is not C contiguous") - * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") - */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); - if (__pyx_t_3) { - - /* "numpy.pxd":217 - * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not Fortran contiguous") - * - */ - __pyx_t_1 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS)); - __pyx_t_2 = __pyx_t_1; - } else { - __pyx_t_2 = __pyx_t_3; - } - if (__pyx_t_2) { - - /* "numpy.pxd":218 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< - * - * info.buf = PyArray_DATA(self) - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "numpy.pxd":220 - * raise ValueError(u"ndarray is not Fortran contiguous") - * - * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< - * info.ndim = ndim - * if copy_shape: - */ - __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - - /* "numpy.pxd":221 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -2686,16 +2371,17 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":222 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ - if (__pyx_v_copy_shape) { + __pyx_t_1 = (__pyx_v_copy_shape != 0); + if (__pyx_t_1) { - /* "numpy.pxd":225 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -2704,7 +2390,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":226 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -2713,18 +2399,18 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":227 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] */ - __pyx_t_5 = __pyx_v_ndim; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; + __pyx_t_4 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; - /* "numpy.pxd":228 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< @@ -2733,7 +2419,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":229 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< @@ -2742,11 +2428,11 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } - goto __pyx_L7; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":231 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< @@ -2755,7 +2441,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":232 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< @@ -2764,9 +2450,9 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } - __pyx_L7:; + __pyx_L11:; - /* "numpy.pxd":233 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -2775,7 +2461,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":234 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< @@ -2784,16 +2470,16 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":235 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - /* "numpy.pxd":238 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -2802,17 +2488,19 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_f = NULL; - /* "numpy.pxd":239 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)__pyx_v_self->descr)); - __pyx_v_descr = __pyx_v_self->descr; + __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; - /* "numpy.pxd":243 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -2821,23 +2509,27 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":245 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); - __pyx_t_1 = __pyx_t_3; + goto __pyx_L16_next_and; } else { __pyx_t_1 = __pyx_t_2; + goto __pyx_L15_bool_binop_done; } + __pyx_L16_next_and:; + __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L15_bool_binop_done:; if (__pyx_t_1) { - /* "numpy.pxd":247 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -2849,11 +2541,11 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; - goto __pyx_L10; + goto __pyx_L14; } /*else*/ { - /* "numpy.pxd":250 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< @@ -2866,327 +2558,309 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } - __pyx_L10:; + __pyx_L14:; - /* "numpy.pxd":252 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { - /* "numpy.pxd":253 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_4 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_4; - /* "numpy.pxd":254 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); - if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; + __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); + if (!__pyx_t_2) { + goto __pyx_L20_next_or; } else { - __pyx_t_2 = __pyx_t_1; + goto __pyx_L21_next_and; } + __pyx_L21_next_and:; + __pyx_t_2 = (__pyx_v_little_endian != 0); if (!__pyx_t_2) { + goto __pyx_L20_next_or; + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_L20_next_or:; - /* "numpy.pxd":255 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); - if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); - __pyx_t_7 = __pyx_t_3; - } else { - __pyx_t_7 = __pyx_t_1; - } - __pyx_t_1 = __pyx_t_7; + __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_2) { + goto __pyx_L22_next_and; } else { __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; } + __pyx_L22_next_and:; + __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L19_bool_binop_done:; if (__pyx_t_1) { - /* "numpy.pxd":256 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L12; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L12:; - /* "numpy.pxd":257 - * (descr.byteorder == '<' and not little_endian)): + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__b; - goto __pyx_L13; - } + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; - /* "numpy.pxd":258 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__B; - goto __pyx_L13; - } + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; - /* "numpy.pxd":259 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__h; - goto __pyx_L13; - } + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; - /* "numpy.pxd":260 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__H; - goto __pyx_L13; - } + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; - /* "numpy.pxd":261 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__i; - goto __pyx_L13; - } + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; - /* "numpy.pxd":262 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__I; - goto __pyx_L13; - } + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; - /* "numpy.pxd":263 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__l; - goto __pyx_L13; - } + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; - /* "numpy.pxd":264 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__L; - goto __pyx_L13; - } + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; - /* "numpy.pxd":265 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__q; - goto __pyx_L13; - } + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; - /* "numpy.pxd":266 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Q; - goto __pyx_L13; - } + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; - /* "numpy.pxd":267 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__f; - goto __pyx_L13; - } + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; - /* "numpy.pxd":268 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__d; - goto __pyx_L13; - } + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; - /* "numpy.pxd":269 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__g; - goto __pyx_L13; - } + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; - /* "numpy.pxd":270 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zf; - goto __pyx_L13; - } + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; - /* "numpy.pxd":271 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zd; - goto __pyx_L13; - } + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; - /* "numpy.pxd":272 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zg; - goto __pyx_L13; - } + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; - /* "numpy.pxd":273 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L13; - } - /*else*/ { + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: - /* "numpy.pxd":275 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); - __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L13:; - /* "numpy.pxd":276 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -3195,7 +2869,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":277 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -3204,63 +2878,70 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":279 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":280 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":281 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":284 - * f = _util_dtypestring(descr, info.format + 1, + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, - * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string - * + * &offset) */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_9; + __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_7; - /* "numpy.pxd":285 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L11:; + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { @@ -3279,39 +2960,41 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P return __pyx_r; } +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + /* Python wrapper */ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":287 - * f[0] = 0 # Terminate format string - * - * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) - */ - static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":288 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { - /* "numpy.pxd":289 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -3323,17 +3006,17 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s } __pyx_L3:; - /* "numpy.pxd":290 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":291 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -3345,10 +3028,19 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s } __pyx_L4:; + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":767 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -3365,7 +3057,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":768 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -3373,14 +3065,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -3391,7 +3090,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -3408,7 +3107,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":771 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -3416,14 +3115,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -3434,7 +3140,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -3451,7 +3157,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":774 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -3459,14 +3165,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -3477,7 +3190,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -3494,7 +3207,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":777 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -3502,14 +3215,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -3520,7 +3240,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -3537,7 +3257,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":780 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -3545,14 +3265,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -3563,7 +3290,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":782 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -3585,19 +3312,17 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; + int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; + long __pyx_t_8; + char *__pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":789 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -3606,7 +3331,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":790 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -3615,161 +3340,169 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":793 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ - if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":794 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; - /* "numpy.pxd":795 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: */ - if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { - PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; - /* "numpy.pxd":797 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { - /* "numpy.pxd":798 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L5:; - /* "numpy.pxd":800 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (!__pyx_t_7) { + goto __pyx_L8_next_or; } else { - __pyx_t_7 = __pyx_t_6; + goto __pyx_L9_next_and; } + __pyx_L9_next_and:; + __pyx_t_7 = (__pyx_v_little_endian != 0); if (!__pyx_t_7) { + goto __pyx_L8_next_or; + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_L8_next_or:; - /* "numpy.pxd":801 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; - } else { - __pyx_t_9 = __pyx_t_6; - } - __pyx_t_6 = __pyx_t_9; + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + goto __pyx_L10_next_and; } else { __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; } + __pyx_L10_next_and:; + __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L7_bool_binop_done:; if (__pyx_t_6) { - /* "numpy.pxd":802 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; - /* "numpy.pxd":812 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -3777,16 +3510,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; - /* "numpy.pxd":813 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -3795,7 +3527,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":814 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -3804,430 +3536,410 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":815 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); } - /* "numpy.pxd":817 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); - /* "numpy.pxd":819 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { - /* "numpy.pxd":820 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 820; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":821 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { - /* "numpy.pxd":822 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L10:; - /* "numpy.pxd":825 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":826 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":827 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 104; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":828 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":829 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 105; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":830 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":831 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 108; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":832 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":833 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 113; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":834 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":835 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 102; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":836 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 100; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":837 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 103; - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":838 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":839 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":840 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L15; } - /* "numpy.pxd":841 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; - goto __pyx_L11; + goto __pyx_L15; } /*else*/ { - /* "numpy.pxd":843 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L11:; + __pyx_L15:; - /* "numpy.pxd":844 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -4235,25 +3947,33 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":848 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 848; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; } - __pyx_L9:; + __pyx_L13:; + + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":849 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -4263,13 +3983,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_r = __pyx_v_f; goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -4282,7 +4008,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":964 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -4294,9 +4020,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; + int __pyx_t_2; __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":966 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -4304,9 +4031,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "numpy.pxd":967 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -4318,7 +4046,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":969 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":971 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -4327,7 +4055,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":970 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":972 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -4338,7 +4066,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":971 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":973 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -4347,7 +4075,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":972 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":974 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -4356,10 +4084,19 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ __pyx_v_arr->base = __pyx_v_baseptr; + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":974 +/* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -4373,17 +4110,17 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":975 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { - /* "numpy.pxd":976 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":978 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -4394,11 +4131,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "numpy.pxd":978 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -4408,9 +4144,16 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } - __pyx_L3:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); @@ -4423,9 +4166,13 @@ static PyMethodDef __pyx_methods[] = { #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else PyModuleDef_HEAD_INIT, - __Pyx_NAMESTR("liblinear"), - __Pyx_DOCSTR(__pyx_k_13), /* m_doc */ + #endif + "liblinear", + __pyx_k_Wrapper_for_liblinear_Author_fa, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ @@ -4436,54 +4183,64 @@ static struct PyModuleDef __pyx_moduledef = { #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_u_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 1, 0, 0}, - {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, - {&__pyx_kp_s_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 1, 0}, - {&__pyx_n_s_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 0, 1, 1}, - {&__pyx_kp_u_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 1, 0, 0}, - {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, - {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, - {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, - {&__pyx_n_s__C, __pyx_k__C, sizeof(__pyx_k__C), 0, 0, 1, 1}, - {&__pyx_n_s__F, __pyx_k__F, sizeof(__pyx_k__F), 0, 0, 1, 1}, - {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, - {&__pyx_n_s__Y, __pyx_k__Y, sizeof(__pyx_k__Y), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__bias, __pyx_k__bias, sizeof(__pyx_k__bias), 0, 0, 1, 1}, - {&__pyx_n_s__csr_train_wrap, __pyx_k__csr_train_wrap, sizeof(__pyx_k__csr_train_wrap), 0, 0, 1, 1}, - {&__pyx_n_s__data, __pyx_k__data, sizeof(__pyx_k__data), 0, 0, 1, 1}, - {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, - {&__pyx_n_s__eps, __pyx_k__eps, sizeof(__pyx_k__eps), 0, 0, 1, 1}, - {&__pyx_n_s__error_msg, __pyx_k__error_msg, sizeof(__pyx_k__error_msg), 0, 0, 1, 1}, - {&__pyx_n_s__indices, __pyx_k__indices, sizeof(__pyx_k__indices), 0, 0, 1, 1}, - {&__pyx_n_s__indptr, __pyx_k__indptr, sizeof(__pyx_k__indptr), 0, 0, 1, 1}, - {&__pyx_n_s__len_w, __pyx_k__len_w, sizeof(__pyx_k__len_w), 0, 0, 1, 1}, - {&__pyx_n_s__model, __pyx_k__model, sizeof(__pyx_k__model), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__nr_class, __pyx_k__nr_class, sizeof(__pyx_k__nr_class), 0, 0, 1, 1}, - {&__pyx_n_s__nr_feature, __pyx_k__nr_feature, sizeof(__pyx_k__nr_feature), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__order, __pyx_k__order, sizeof(__pyx_k__order), 0, 0, 1, 1}, - {&__pyx_n_s__param, __pyx_k__param, sizeof(__pyx_k__param), 0, 0, 1, 1}, - {&__pyx_n_s__problem, __pyx_k__problem, sizeof(__pyx_k__problem), 0, 0, 1, 1}, - {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__set_verbosity_wrap, __pyx_k__set_verbosity_wrap, sizeof(__pyx_k__set_verbosity_wrap), 0, 0, 1, 1}, - {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, - {&__pyx_n_s__solver_type, __pyx_k__solver_type, sizeof(__pyx_k__solver_type), 0, 0, 1, 1}, - {&__pyx_n_s__train_wrap, __pyx_k__train_wrap, sizeof(__pyx_k__train_wrap), 0, 0, 1, 1}, - {&__pyx_n_s__verbosity, __pyx_k__verbosity, sizeof(__pyx_k__verbosity), 0, 0, 1, 1}, - {&__pyx_n_s__w, __pyx_k__w, sizeof(__pyx_k__w), 0, 0, 1, 1}, - {&__pyx_n_s__weight, __pyx_k__weight, sizeof(__pyx_k__weight), 0, 0, 1, 1}, - {&__pyx_n_s__weight_label, __pyx_k__weight_label, sizeof(__pyx_k__weight_label), 0, 0, 1, 1}, + {&__pyx_n_s_C, __pyx_k_C, sizeof(__pyx_k_C), 0, 0, 1, 1}, + {&__pyx_n_s_F, __pyx_k_F, sizeof(__pyx_k_F), 0, 0, 1, 1}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_n_s_Y, __pyx_k_Y, sizeof(__pyx_k_Y), 0, 0, 1, 1}, + {&__pyx_n_s_arange, __pyx_k_arange, sizeof(__pyx_k_arange), 0, 0, 1, 1}, + {&__pyx_n_s_bias, __pyx_k_bias, sizeof(__pyx_k_bias), 0, 0, 1, 1}, + {&__pyx_n_s_class_weight, __pyx_k_class_weight, sizeof(__pyx_k_class_weight), 0, 0, 1, 1}, + {&__pyx_n_s_class_weight_label, __pyx_k_class_weight_label, sizeof(__pyx_k_class_weight_label), 0, 0, 1, 1}, + {&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 0, 0, 1, 1}, + {&__pyx_n_s_eps, __pyx_k_eps, sizeof(__pyx_k_eps), 0, 0, 1, 1}, + {&__pyx_n_s_epsilon, __pyx_k_epsilon, sizeof(__pyx_k_epsilon), 0, 0, 1, 1}, + {&__pyx_n_s_error_msg, __pyx_k_error_msg, sizeof(__pyx_k_error_msg), 0, 0, 1, 1}, + {&__pyx_kp_s_home_fp985994_dev_scikit_learn, __pyx_k_home_fp985994_dev_scikit_learn, sizeof(__pyx_k_home_fp985994_dev_scikit_learn), 0, 0, 1, 0}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_indices, __pyx_k_indices, sizeof(__pyx_k_indices), 0, 0, 1, 1}, + {&__pyx_n_s_indptr, __pyx_k_indptr, sizeof(__pyx_k_indptr), 0, 0, 1, 1}, + {&__pyx_n_s_intc, __pyx_k_intc, sizeof(__pyx_k_intc), 0, 0, 1, 1}, + {&__pyx_n_s_is_sparse, __pyx_k_is_sparse, sizeof(__pyx_k_is_sparse), 0, 0, 1, 1}, + {&__pyx_n_s_labels, __pyx_k_labels, sizeof(__pyx_k_labels), 0, 0, 1, 1}, + {&__pyx_n_s_len_w, __pyx_k_len_w, sizeof(__pyx_k_len_w), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_max_iter, __pyx_k_max_iter, sizeof(__pyx_k_max_iter), 0, 0, 1, 1}, + {&__pyx_n_s_model, __pyx_k_model, sizeof(__pyx_k_model), 0, 0, 1, 1}, + {&__pyx_n_s_n_iter, __pyx_k_n_iter, sizeof(__pyx_k_n_iter), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_nr_class, __pyx_k_nr_class, sizeof(__pyx_k_nr_class), 0, 0, 1, 1}, + {&__pyx_n_s_nr_feature, __pyx_k_nr_feature, sizeof(__pyx_k_nr_feature), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_order, __pyx_k_order, sizeof(__pyx_k_order), 0, 0, 1, 1}, + {&__pyx_n_s_param, __pyx_k_param, sizeof(__pyx_k_param), 0, 0, 1, 1}, + {&__pyx_n_s_problem, __pyx_k_problem, sizeof(__pyx_k_problem), 0, 0, 1, 1}, + {&__pyx_n_s_random_seed, __pyx_k_random_seed, sizeof(__pyx_k_random_seed), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_set_verbosity_wrap, __pyx_k_set_verbosity_wrap, sizeof(__pyx_k_set_verbosity_wrap), 0, 0, 1, 1}, + {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_svm_liblinear, __pyx_k_sklearn_svm_liblinear, sizeof(__pyx_k_sklearn_svm_liblinear), 0, 0, 1, 1}, + {&__pyx_n_s_solver_type, __pyx_k_solver_type, sizeof(__pyx_k_solver_type), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_train_wrap, __pyx_k_train_wrap, sizeof(__pyx_k_train_wrap), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_verbosity, __pyx_k_verbosity, sizeof(__pyx_k_verbosity), 0, 0, 1, 1}, + {&__pyx_n_s_w, __pyx_k_w, sizeof(__pyx_k_w), 0, 0, 1, 1}, + {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -4493,203 +4250,95 @@ static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "numpy.pxd":214 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_2 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_2); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_1)); - PyTuple_SET_ITEM(__pyx_k_tuple_2, 0, ((PyObject *)__pyx_kp_u_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); - /* "numpy.pxd":218 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_4); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_3)); - PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_u_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); - /* "numpy.pxd":256 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_6); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); - /* "numpy.pxd":798 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_9); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); - /* "numpy.pxd":802 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_10); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); - /* "numpy.pxd":822 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_12); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); - PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); - - /* "sklearn/svm/liblinear.pyx":12 - * - * - * def train_wrap ( np.ndarray[np.float64_t, ndim=2, mode='c'] X, # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, - * int solver_type, double eps, double bias, double C, - */ - __pyx_k_tuple_14 = PyTuple_New(16); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_14); - __Pyx_INCREF(((PyObject *)__pyx_n_s__X)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, ((PyObject *)__pyx_n_s__X)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__X)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__Y)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 1, ((PyObject *)__pyx_n_s__Y)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__Y)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__solver_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 2, ((PyObject *)__pyx_n_s__solver_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__solver_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__eps)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 3, ((PyObject *)__pyx_n_s__eps)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__eps)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__bias)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 4, ((PyObject *)__pyx_n_s__bias)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__bias)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__C)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 5, ((PyObject *)__pyx_n_s__C)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__C)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__weight_label)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 6, ((PyObject *)__pyx_n_s__weight_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__weight_label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 7, ((PyObject *)__pyx_n_s__weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__param)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 8, ((PyObject *)__pyx_n_s__param)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__param)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__problem)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 9, ((PyObject *)__pyx_n_s__problem)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__problem)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__model)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 10, ((PyObject *)__pyx_n_s__model)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__model)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__error_msg)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 11, ((PyObject *)__pyx_n_s__error_msg)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__error_msg)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__len_w)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 12, ((PyObject *)__pyx_n_s__len_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__len_w)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__w)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 13, ((PyObject *)__pyx_n_s__w)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__w)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nr_class)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 14, ((PyObject *)__pyx_n_s__nr_class)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nr_class)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nr_feature)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 15, ((PyObject *)__pyx_n_s__nr_feature)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nr_feature)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); - __pyx_k_codeobj_15 = (PyObject*)__Pyx_PyCode_New(8, 0, 16, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_14, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_16, __pyx_n_s__train_wrap, 12, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/svm/liblinear.pyx":113 - * - * - * def csr_train_wrap(X, Y, solver_type, eps, bias, C, weight_label, weight): # <<<<<<<<<<<<<< - * """ - * Wrapper for train. - */ - __pyx_k_tuple_18 = PyTuple_New(8); if (unlikely(!__pyx_k_tuple_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_18); - __Pyx_INCREF(((PyObject *)__pyx_n_s__X)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 0, ((PyObject *)__pyx_n_s__X)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__X)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__Y)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 1, ((PyObject *)__pyx_n_s__Y)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__Y)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__solver_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 2, ((PyObject *)__pyx_n_s__solver_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__solver_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__eps)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 3, ((PyObject *)__pyx_n_s__eps)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__eps)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__bias)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 4, ((PyObject *)__pyx_n_s__bias)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__bias)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__C)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 5, ((PyObject *)__pyx_n_s__C)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__C)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__weight_label)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 6, ((PyObject *)__pyx_n_s__weight_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__weight_label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 7, ((PyObject *)__pyx_n_s__weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_18)); - __pyx_k_codeobj_19 = (PyObject*)__Pyx_PyCode_New(8, 0, 8, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_18, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_16, __pyx_n_s__csr_train_wrap, 113, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/svm/liblinear.pyx":123 + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + + /* "sklearn/svm/liblinear.pyx":14 + * + * + * def train_wrap(X, np.ndarray[np.float64_t, ndim=1, mode='c'] Y, # <<<<<<<<<<<<<< + * bint is_sparse, int solver_type, double eps, double bias, + * double C, np.ndarray[np.float64_t, ndim=1] class_weight, + */ + __pyx_tuple__7 = PyTuple_Pack(22, __pyx_n_s_X, __pyx_n_s_Y, __pyx_n_s_is_sparse, __pyx_n_s_solver_type, __pyx_n_s_eps, __pyx_n_s_bias, __pyx_n_s_C, __pyx_n_s_class_weight, __pyx_n_s_max_iter, __pyx_n_s_random_seed, __pyx_n_s_epsilon, __pyx_n_s_param, __pyx_n_s_problem, __pyx_n_s_model, __pyx_n_s_error_msg, __pyx_n_s_len_w, __pyx_n_s_class_weight_label, __pyx_n_s_w, __pyx_n_s_nr_class, __pyx_n_s_labels, __pyx_n_s_n_iter, __pyx_n_s_nr_feature); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + __pyx_codeobj__8 = (PyObject*)__Pyx_PyCode_New(11, 0, 22, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__7, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_fp985994_dev_scikit_learn, __pyx_n_s_train_wrap, 14, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/svm/liblinear.pyx":84 * * * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< * """ * Control verbosity of libsvm library */ - __pyx_k_tuple_20 = PyTuple_New(2); if (unlikely(!__pyx_k_tuple_20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_20); - __Pyx_INCREF(((PyObject *)__pyx_n_s__verbosity)); - PyTuple_SET_ITEM(__pyx_k_tuple_20, 0, ((PyObject *)__pyx_n_s__verbosity)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__verbosity)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__verbosity)); - PyTuple_SET_ITEM(__pyx_k_tuple_20, 1, ((PyObject *)__pyx_n_s__verbosity)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__verbosity)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_20)); - __pyx_k_codeobj_21 = (PyObject*)__Pyx_PyCode_New(1, 0, 2, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_20, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_16, __pyx_n_s__set_verbosity_wrap, 123, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_21)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_tuple__9 = PyTuple_Pack(2, __pyx_n_s_verbosity, __pyx_n_s_verbosity); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + __pyx_codeobj__10 = (PyObject*)__Pyx_PyCode_New(1, 0, 2, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__9, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_fp985994_dev_scikit_learn, __pyx_n_s_set_verbosity_wrap, 84, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -4699,8 +4348,7 @@ static int __Pyx_InitCachedConstants(void) { static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -4715,6 +4363,9 @@ PyMODINIT_FUNC PyInit_liblinear(void) #endif { PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -4747,22 +4398,34 @@ PyMODINIT_FUNC PyInit_liblinear(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("liblinear"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_13), 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4("liblinear", __pyx_methods, __pyx_k_Wrapper_for_liblinear_Author_fa, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif if (__pyx_module_is_main_sklearn__svm__liblinear) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.svm.liblinear")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.svm.liblinear", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } } + #endif /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ @@ -4772,11 +4435,18 @@ PyMODINIT_FUNC PyInit_liblinear(void) /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ @@ -4788,45 +4458,42 @@ PyMODINIT_FUNC PyInit_liblinear(void) * cimport numpy as np * cimport liblinear */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/liblinear.pyx":12 + /* "sklearn/svm/liblinear.pyx":11 + * cimport liblinear + * + * np.import_array() # <<<<<<<<<<<<<< * * - * def train_wrap ( np.ndarray[np.float64_t, ndim=2, mode='c'] X, # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, - * int solver_type, double eps, double bias, double C, */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_9liblinear_1train_wrap, NULL, __pyx_n_s_17); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__train_wrap, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + import_array(); - /* "sklearn/svm/liblinear.pyx":113 + /* "sklearn/svm/liblinear.pyx":14 * * - * def csr_train_wrap(X, Y, solver_type, eps, bias, C, weight_label, weight): # <<<<<<<<<<<<<< - * """ - * Wrapper for train. + * def train_wrap(X, np.ndarray[np.float64_t, ndim=1, mode='c'] Y, # <<<<<<<<<<<<<< + * bint is_sparse, int solver_type, double eps, double bias, + * double C, np.ndarray[np.float64_t, ndim=1] class_weight, */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_9liblinear_3csr_train_wrap, NULL, __pyx_n_s_17); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_9liblinear_1train_wrap, NULL, __pyx_n_s_sklearn_svm_liblinear); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__csr_train_wrap, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_train_wrap, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/liblinear.pyx":123 + /* "sklearn/svm/liblinear.pyx":84 * * * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< * """ * Control verbosity of libsvm library */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_9liblinear_5set_verbosity_wrap, NULL, __pyx_n_s_17); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_9liblinear_3set_verbosity_wrap, NULL, __pyx_n_s_sklearn_svm_liblinear); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__set_verbosity_wrap, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_set_verbosity_wrap, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "sklearn/svm/liblinear.pyx":1 @@ -4835,22 +4502,28 @@ PyMODINIT_FUNC PyInit_liblinear(void) * */ __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":974 + /* "../../miniconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ + + /*--- Wrapped vars code ---*/ + goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); if (__pyx_m) { - __Pyx_AddTraceback("init sklearn.svm.liblinear", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__pyx_d) { + __Pyx_AddTraceback("init sklearn.svm.liblinear", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_d); __pyx_d = 0; + } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init sklearn.svm.liblinear"); @@ -4879,19 +4552,17 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } -#endif /* CYTHON_REFNANNY */ +#endif -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif } return result; } @@ -4916,7 +4587,7 @@ static void __Pyx_RaiseArgtupleInvalid( more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } @@ -4930,7 +4601,7 @@ static void __Pyx_RaiseDoubleKeywordsError( "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); + PyString_AsString(kw_name)); #endif } @@ -4951,57 +4622,81 @@ static int __Pyx_ParseOptionalKeywords( while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { values[name-argnames] = value; - } else { - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; } } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; } } return 0; arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); + __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); + "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", + "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", @@ -5011,23 +4706,29 @@ static int __Pyx_ParseOptionalKeywords( return -1; } -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { - if (Py_TYPE(obj) == type) return 1; + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif } else { - if (PyObject_TypeCheck(obj, type)) return 1; + if (likely(PyObject_TypeCheck(obj, type))) return 1; } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } @@ -5079,7 +4780,7 @@ static int __Pyx_BufFmt_ParseNumber(const char** ts) { } static int __Pyx_BufFmt_ExpectNumber(const char **ts) { int number = __Pyx_BufFmt_ParseNumber(ts); - if (number == -1) /* First char was not a digit */ + if (number == -1) PyErr_Format(PyExc_ValueError,\ "Does not understand character buffer dtype format string ('%c')", **ts); return number; @@ -5090,7 +4791,8 @@ static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { - case 'b': return "'char'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; @@ -5158,7 +4860,7 @@ typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); @@ -5190,7 +4892,7 @@ typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif -static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); @@ -5210,7 +4912,9 @@ static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, int is_complex) { } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'h': case 'i': + case 'c': + return 'H'; + case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case 'B': case 'H': case 'I': case 'L': case 'Q': @@ -5305,20 +5009,23 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ctx->head->parent_offset = parent_offset; continue; } - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } ctx->fmt_offset += size; if (arraysize) ctx->fmt_offset += (arraysize - 1) * size; - --ctx->enc_count; /* Consume from buffer string */ + --ctx->enc_count; while (1) { if (field == &ctx->root) { ctx->head = NULL; @@ -5326,7 +5033,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } - break; /* breaks both loops as ctx->enc_count == 0 */ + break; } ctx->head->field = ++field; if (field->type == NULL) { @@ -5335,7 +5042,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { continue; } else if (field->type->typegroup == 'S') { size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; /* empty struct */ + if (field->type->fields->type == NULL) continue; field = field->type->fields; ++ctx->head; ctx->head->field = field; @@ -5365,8 +5072,10 @@ __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; while (*ts && *ts != ')') { - if (isspace(*ts)) - continue; + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; + } number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) @@ -5406,10 +5115,10 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } - return ts; + return ts; case ' ': - case 10: - case 13: + case '\r': + case '\n': ++ts; break; case '<': @@ -5434,7 +5143,7 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha case '^': ctx->new_packmode = *ts++; break; - case 'T': /* substruct */ + case 'T': { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; @@ -5446,7 +5155,7 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_type = 0; ctx->enc_count = 0; ctx->struct_alignment = 0; ++ts; @@ -5459,12 +5168,12 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; - case '}': /* end of substruct; either repeat or move on */ + case '}': { size_t alignment = ctx->struct_alignment; ++ts; if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_type = 0; if (alignment && ctx->fmt_offset % alignment) { ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); } @@ -5485,21 +5194,25 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha if (*ts != 'f' && *ts != 'd' && *ts != 'g') { __Pyx_BufFmt_RaiseUnexpectedChar('Z'); return NULL; - } /* fall through */ + } case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': - case 'O': case 's': case 'p': + case 'O': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { ctx->enc_count += ctx->new_count; - } else { - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; } + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; ++ts; ctx->new_count = 1; got_Z = 0; @@ -5551,7 +5264,7 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate( } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; @@ -5568,6 +5281,132 @@ static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { __Pyx_ReleaseBuffer(info); } +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (likely(result)) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { #if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; @@ -5603,54 +5442,42 @@ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyOb static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } - #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) - #else - if (!PyType_Check(type)) - #endif - { - if (value != Py_None) { + if (PyType_Check(type)) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - Py_DECREF(value); value = type; - #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - #endif + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } } __Pyx_ErrRestore(type, value, tb); return; @@ -5660,8 +5487,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, Py_XDECREF(tb); return; } -#else /* Python 3+ */ +#else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -5679,303 +5507,740 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } +#if PY_VERSION_HEX >= 0x03030000 if (cause) { +#else + if (cause && cause != Py_None) { +#endif PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; - } - else if (PyExceptionInstance_Check(cause)) { + } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static void __Pyx_RaiseBufferFallbackError(void) { + PyErr_SetString(PyExc_ValueError, + "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +} + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; bad: - return; -} -#endif - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; - } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -static void __Pyx_RaiseBufferFallbackError(void) { - PyErr_Format(PyExc_ValueError, - "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); -} - - - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); -} - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); -} - -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; } - -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); - } else { - __Pyx_RaiseTooManyValuesError(index); +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - PyObject *getbuffer_cobj; - - #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); - - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (getbuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_getbuffer"))) { - getbufferproc func; - - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (getbufferproc) PyCapsule_GetPointer(getbuffer_cobj, "getbuffer(obj, view, flags)"); - #else - func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); - #endif - Py_DECREF(getbuffer_cobj); - if (!func) - goto fail; - - return func(obj, view, flags); - } else { - PyErr_Clear(); - } - #endif - - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - -#if PY_VERSION_HEX < 0x02060000 -fail: -#endif - + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); return -1; } - static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; - PyObject *releasebuffer_cobj; - if (!obj) return; - - #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + Py_DECREF(obj); + view->obj = NULL; +} +#endif - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (releasebuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_releasebuffer"))) { - releasebufferproc func; - - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (releasebufferproc) PyCapsule_GetPointer(releasebuffer_cobj, "releasebuffer(obj, view)"); - #else - func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); - #endif - Py_DECREF(releasebuffer_cobj); + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} - if (!func) - goto fail; +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ + { \ + func_type value = func_value; \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + if (is_unsigned && unlikely(value < zero)) \ + goto raise_neg_overflow; \ + else \ + goto raise_overflow; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif - func(obj, view); - return; +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong(x)) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } } else { - PyErr_Clear(); + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; } - #endif - - goto nofail; +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} -#if PY_VERSION_HEX < 0x02060000 -fail: +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) { + const unsigned int neg_one = (unsigned int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(unsigned int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (unsigned int) val; + } + } else #endif - PyErr_WriteUnraisable(obj); - -nofail: - Py_DECREF(obj); - view->obj = NULL; + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(unsigned int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(unsigned int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(unsigned int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(unsigned int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyLong_AsLong(x)) + } else if (sizeof(unsigned int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + unsigned int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (unsigned int) -1; + } + } else { + unsigned int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned int) -1; + val = __Pyx_PyInt_As_unsigned_int(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to unsigned int"); + return (unsigned int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned int"); + return (unsigned int) -1; } -#endif /* PY_MAJOR_VERSION < 3 */ - - static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); - if (!py_import) - goto bad; - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - #if PY_VERSION_HEX >= 0x02050000 { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if (strchr(__Pyx_MODULE_NAME, '.')) { - /* try package relative import first */ - PyObject *py_level = PyInt_FromLong(1); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); + } +} + +static CYTHON_INLINE npy_int32 __Pyx_PyInt_As_npy_int32(PyObject *x) { + const npy_int32 neg_one = (npy_int32) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(npy_int32) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; } - level = 0; /* try absolute import on failure */ + return (npy_int32) val; } - #endif - if (!module) { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_int32, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(npy_int32) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(npy_int32) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_int32, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(npy_int32, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(npy_int32) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, long, PyLong_AsLong(x)) + } else if (sizeof(npy_int32) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + npy_int32 val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (npy_int32) -1; } + } else { + npy_int32 val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (npy_int32) -1; + val = __Pyx_PyInt_As_npy_int32(tmp); + Py_DECREF(tmp); + return val; } - #else - if (level>0) { - PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); - goto bad; +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to npy_int32"); + return (npy_int32) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to npy_int32"); + return (npy_int32) -1; +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(Py_intptr_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); } - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, NULL); - #endif -bad: - Py_XDECREF(empty_list); - Py_XDECREF(py_import); - Py_XDECREF(empty_dict); - return module; } -static CYTHON_INLINE npy_int32 __Pyx_PyInt_from_py_npy_int32(PyObject* x) { - const npy_int32 neg_one = (npy_int32)-1, const_zero = (npy_int32)0; - const int is_unsigned = const_zero < neg_one; - if (sizeof(npy_int32) == sizeof(char)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedChar(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedChar(x); - } else if (sizeof(npy_int32) == sizeof(short)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedShort(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedShort(x); - } else if (sizeof(npy_int32) == sizeof(int)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedInt(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedInt(x); - } else if (sizeof(npy_int32) == sizeof(long)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedLong(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedLong(x); - } else if (sizeof(npy_int32) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return (npy_int32)__Pyx_PyInt_AsUnsignedLongLong(x); - else - return (npy_int32)__Pyx_PyInt_AsSignedLongLong(x); - } else { - npy_int32 val; - PyObject *v = __Pyx_PyNumber_Int(x); - #if PY_VERSION_HEX < 0x03000000 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); } - return (npy_int32)-1; + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); } } @@ -6217,406 +6482,101 @@ static CYTHON_INLINE npy_int32 __Pyx_PyInt_from_py_npy_int32(PyObject* x) { return z; } #endif -#endif - -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; - } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; - } - return (unsigned short)val; - } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; - } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; - } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; - } - return (short)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; - } - return (signed char)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; - } - return (signed short)val; - } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; - } - return (signed int)val; - } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)PyLong_AsUnsignedLong(x); - } else { - return (unsigned long)PyLong_AsLong(x); - } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)PyLong_AsUnsignedLong(x); - } else { - return (long)PyLong_AsLong(x); - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)PyLong_AsUnsignedLong(x); - } else { - return (signed long)PyLong_AsLong(x); - } - } else { - signed long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} +#endif -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; } - return (signed PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + goto raise_neg_overflow; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong(x)) } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong(x)) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; } } else { - signed PY_LONG_LONG val; + long val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; } static int __Pyx_check_binary_version(void) { @@ -6629,15 +6589,28 @@ static int __Pyx_check_binary_version(void) { "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); - #if PY_VERSION_HEX < 0x02050000 - return PyErr_Warn(NULL, message); - #else return PyErr_WarnEx(NULL, message, 1); - #endif } return 0; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -6647,6 +6620,10 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; @@ -6662,23 +6639,31 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", + "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } - if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); - #if PY_VERSION_HEX < 0x02050000 - if (PyErr_Warn(NULL, warning) < 0) goto bad; - #else if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - #endif } - else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", + "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } @@ -6690,185 +6675,6 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - py_name = __Pyx_PyIdentifier_FromString(name); - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; -} -#endif - -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = (start + end) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, /*int argcount,*/ - 0, /*int kwonlyargcount,*/ - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ - 0, /*int flags,*/ - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, /*int firstlineno,*/ - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_globals = 0; - PyFrameObject *py_frame = 0; - py_code = __pyx_find_code_object(c_line ? c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? c_line : py_line, py_code); - } - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_frame = PyFrame_New( - PyThreadState_GET(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - py_globals, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = py_line; - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 @@ -6879,7 +6685,7 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } - #else /* Python 3+ has unicode identifiers */ + #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); @@ -6899,27 +6705,88 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } - -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else + if (__Pyx_PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif + } else +#endif +#if !CYTHON_COMPILING_IN_PYPY + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -6935,13 +6802,13 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", + "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; @@ -6953,40 +6820,33 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { -#if PY_VERSION_HEX < 0x02050000 - if (ival <= LONG_MAX) - return PyInt_FromLong((long)ival); - else { - unsigned char *bytes = (unsigned char *) &ival; - int one = 1; int little = (int)*(unsigned char*)&one; - return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); - } -#else - return PyInt_FromSize_t(ival); -#endif -} - -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; + return PyInt_FromSize_t(ival); } diff --git a/sklearn/svm/liblinear.pxd b/sklearn/svm/liblinear.pxd index d7c203f84634e..7391fd434c14f 100644 --- a/sklearn/svm/liblinear.pxd +++ b/sklearn/svm/liblinear.pxd @@ -10,21 +10,20 @@ cdef extern from "src/liblinear/linear.h": ctypedef parameter* parameter_const_ptr "parameter const *" ctypedef char* char_const_ptr "char const *" char_const_ptr check_parameter(problem_const_ptr prob, parameter_const_ptr param) - model *train(problem_const_ptr prob, parameter_const_ptr param) + model *train(problem_const_ptr prob, parameter_const_ptr param) nogil int get_nr_feature (model *model) int get_nr_class (model *model) + void get_n_iter (model *model, int *n_iter) void free_and_destroy_model (model **) void destroy_param (parameter *) cdef extern from "src/liblinear/liblinear_helper.c": void copy_w(void *, model *, int) - parameter *set_parameter (int, double, double, int, - char *, char *) + parameter *set_parameter(int, double, double, int, char *, char *, int, int, double) problem *set_problem (char *, char *, np.npy_intp *, double) problem *csr_set_problem (char *values, np.npy_intp *n_indices, char *indices, np.npy_intp *n_indptr, char *indptr, char *Y, np.npy_intp n_features, double bias) - parameter *set_parameter(int, double, double, int, char *, char *) model *set_model(parameter *, char *, np.npy_intp *, char *, double) diff --git a/sklearn/svm/liblinear.pyx b/sklearn/svm/liblinear.pyx index 5200c44fb332e..23b73783d2a27 100644 --- a/sklearn/svm/liblinear.pyx +++ b/sklearn/svm/liblinear.pyx @@ -8,76 +8,39 @@ import numpy as np cimport numpy as np cimport liblinear +np.import_array() -def train_wrap ( np.ndarray[np.float64_t, ndim=2, mode='c'] X, - np.ndarray[np.float64_t, ndim=1, mode='c'] Y, - int solver_type, double eps, double bias, double C, - np.ndarray[np.int32_t, ndim=1] weight_label, - np.ndarray[np.float64_t, ndim=1] weight): - """ - Wrapper for train methd. - """ - cdef parameter *param - cdef problem *problem - cdef model *model - cdef char_const_ptr error_msg - cdef int len_w - - problem = set_problem(X.data, Y.data, X.shape, bias) - - param = set_parameter(solver_type, eps, C, weight.shape[0], weight_label.data, weight.data) - - error_msg = check_parameter(problem, param) - if error_msg: - free_problem(problem) - free_parameter(param) - raise ValueError(error_msg) - - # early return - model = train(problem, param) - - # coef matrix holder created as fortran since that's what's used in liblinear - cdef np.ndarray[np.float64_t, ndim=2, mode='fortran'] w - cdef int nr_class = get_nr_class(model) - cdef int nr_feature = get_nr_feature(model) - if bias > 0: nr_feature = nr_feature + 1 - if nr_class == 2: - w = np.empty((1, nr_feature),order='F') - copy_w(w.data, model, nr_feature) - else: - len_w = (nr_class) * nr_feature - w = np.empty((nr_class, nr_feature),order='F') - copy_w(w.data, model, len_w) - - ### FREE - free_and_destroy_model(&model) - free_problem(problem) - free_parameter(param) - # destroy_param(param) don't call this or it will destroy weight_label and weight - - return w - -cdef _csr_train_wrap(np.int32_t n_features, - np.ndarray[np.float64_t, ndim=1, mode='c'] X_values, - np.ndarray[np.int32_t, ndim=1, mode='c'] X_indices, - np.ndarray[np.int32_t, ndim=1, mode='c'] X_indptr, - np.ndarray[np.float64_t, ndim=1, mode='c'] Y, - int solver_type, double eps, double bias, double C, - np.ndarray[np.int32_t, ndim=1] weight_label, - np.ndarray[np.float64_t, ndim=1] weight): +def train_wrap(X, np.ndarray[np.float64_t, ndim=1, mode='c'] Y, + bint is_sparse, int solver_type, double eps, double bias, + double C, np.ndarray[np.float64_t, ndim=1] class_weight, + int max_iter, unsigned random_seed, double epsilon): cdef parameter *param cdef problem *problem cdef model *model cdef char_const_ptr error_msg cdef int len_w - problem = csr_set_problem(X_values.data, X_indices.shape, - X_indices.data, X_indptr.shape, - X_indptr.data, Y.data, n_features, bias) - - param = set_parameter(solver_type, eps, C, weight.shape[0], - weight_label.data, weight.data) + if is_sparse: + problem = csr_set_problem( + (X.data).data, + (X.indices).shape, + (X.indices).data, + (X.indptr).shape, + (X.indptr).data, + Y.data, (X.shape[1]), bias) + else: + problem = set_problem( + (X).data, + Y.data, + (X).shape, + bias) + + cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + class_weight_label = np.arange(class_weight.shape[0], dtype=np.intc) + param = set_parameter(solver_type, eps, C, class_weight.shape[0], + class_weight_label.data, class_weight.data, + max_iter, random_seed, epsilon) error_msg = check_parameter(problem, param) if error_msg: @@ -86,18 +49,26 @@ cdef _csr_train_wrap(np.int32_t n_features, raise ValueError(error_msg) # early return - model = train(problem, param) + with nogil: + model = train(problem, param) - # fortran order since that's what liblinear does + # coef matrix holder created as fortran since that's what's used in liblinear cdef np.ndarray[np.float64_t, ndim=2, mode='fortran'] w cdef int nr_class = get_nr_class(model) - cdef int nr_feature = n_features - if bias > 0: nr_feature = nr_feature + 1 + + cdef int labels_ = nr_class if nr_class == 2: + labels_ = 1 + cdef np.ndarray[np.int32_t, ndim=1, mode='c'] n_iter = np.zeros(labels_, dtype=np.intc) + get_n_iter(model, n_iter.data) + + cdef int nr_feature = get_nr_feature(model) + if bias > 0: nr_feature = nr_feature + 1 + if nr_class == 2 and solver_type != 4: # solver is not Crammer-Singer w = np.empty((1, nr_feature),order='F') copy_w(w.data, model, nr_feature) else: - len_w = (nr_class * nr_feature) + len_w = (nr_class) * nr_feature w = np.empty((nr_class, nr_feature),order='F') copy_w(w.data, model, len_w) @@ -105,19 +76,9 @@ cdef _csr_train_wrap(np.int32_t n_features, free_and_destroy_model(&model) free_problem(problem) free_parameter(param) - # destroy_param(param) don't call this or it will destroy weight_label and weight - - return w - + # destroy_param(param) don't call this or it will destroy class_weight_label and class_weight -def csr_train_wrap(X, Y, solver_type, eps, bias, C, weight_label, weight): - """ - Wrapper for train. - - X matrix is given in CSR sparse format. - """ - return _csr_train_wrap(X.shape[1], X.data, X.indices, X.indptr, Y, - solver_type, eps, bias, C, weight_label, weight) + return w, n_iter def set_verbosity_wrap(int verbosity): diff --git a/sklearn/svm/libsvm.c b/sklearn/svm/libsvm.c index 76997ab0cef5f..ee1a29c4638e6 100644 --- a/sklearn/svm/libsvm.c +++ b/sklearn/svm/libsvm.c @@ -1,17 +1,29 @@ -/* Generated by Cython 0.16 on Mon Aug 27 14:17:56 2012 */ +/* Generated by Cython 0.20.1 on Thu Apr 3 16:22:28 2014 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02040000 #error Cython requires Python 2.4+. #else +#define CYTHON_ABI "0_20_1" #include /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -23,22 +35,18 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif - #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 @@ -46,28 +54,31 @@ #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif - #if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyCFunction_Call PyObject_Call -#else - #define __Pyx_PyCFunction_Call PyCFunction_Call +#define Py_OptimizeFlag 0 #endif - #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) #define __PYX_BUILD_PY_SSIZE_T "i" #else #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -75,7 +86,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -89,7 +99,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -101,45 +110,72 @@ #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) - typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ - PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type #endif - -#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 +#if PY_VERSION_HEX < 0x02060000 #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - - -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_GET_LENGTH) +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT) + #define Py_TPFLAGS_IS_ABSTRACT 0 +#endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #else #define CYTHON_PEP393_ENABLED 0 - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif - #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -147,7 +183,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -166,7 +201,14 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -174,9 +216,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -192,13 +232,12 @@ #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - -#if PY_VERSION_HEX < 0x03020000 +#if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong @@ -206,7 +245,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -225,11 +263,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -239,7 +275,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -247,6 +282,41 @@ #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) @@ -270,6 +340,7 @@ #include #define __PYX_HAVE__sklearn__svm__libsvm #define __PYX_HAVE_API__sklearn__svm__libsvm +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" @@ -284,21 +355,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -312,26 +368,143 @@ # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + #ifdef __GNUC__ /* Test for GCC > 2.95 */ @@ -346,8 +519,9 @@ static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -380,7 +554,8 @@ static const char *__pyx_filename; static const char *__pyx_f[] = { "libsvm.pyx", - "numpy.pxd", + "__init__.pxd", + "type.pxd", }; #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; @@ -391,7 +566,7 @@ typedef struct { size_t size; /* sizeof(type) */ size_t arraysize[8]; /* length of array in each dimension */ int ndim; - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ char is_unsigned; int flags; } __Pyx_TypeInfo; @@ -418,7 +593,7 @@ typedef struct { } __Pyx_BufFmt_Context; -/* "numpy.pxd":722 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -427,7 +602,7 @@ typedef struct { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":723 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -436,7 +611,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":724 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -445,7 +620,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":725 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -454,7 +629,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":729 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -463,7 +638,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":730 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -472,7 +647,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":731 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -481,7 +656,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":732 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -490,7 +665,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":736 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -499,7 +674,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":737 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -508,7 +683,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":746 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -517,7 +692,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":747 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -526,7 +701,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":748 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -535,7 +710,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":750 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -544,7 +719,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":751 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -553,7 +728,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":752 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -562,7 +737,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":754 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -571,7 +746,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":755 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -580,7 +755,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":757 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -589,7 +764,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":758 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -598,7 +773,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":759 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -629,7 +804,7 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; /*--- Type declarations ---*/ -/* "numpy.pxd":761 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -638,7 +813,7 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":762 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -647,7 +822,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":763 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -656,7 +831,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":765 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -715,10 +890,33 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ @@ -729,13 +927,21 @@ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ const char* function_name); /*proto*/ -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); /*proto*/ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ @@ -745,15 +951,27 @@ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyOb static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ -static CYTHON_INLINE long __Pyx_div_long(long, long); /* proto */ +#include -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ + +static CYTHON_INLINE long __Pyx_div_long(long, long); /* proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); typedef struct { Py_ssize_t shape, strides, suboffsets; @@ -776,12 +994,21 @@ typedef struct { #define __Pyx_ReleaseBuffer PyBuffer_Release #endif + static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -795,7 +1022,7 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif -#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else @@ -881,37 +1108,9 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); static int __Pyx_check_binary_version(void); @@ -923,10 +1122,10 @@ static int __Pyx_check_binary_version(void); #endif #endif -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ - static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + typedef struct { int code_line; PyCodeObject* code_object; @@ -951,10 +1150,17 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -968,8 +1174,9 @@ static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ /* Module declarations from 'sklearn.svm.libsvm' */ +static void __pyx_f_7sklearn_3svm_6libsvm_set_predict_params(struct svm_parameter *, int, PyObject *, int, double, double, double, int, int, char *, char *); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t = { "float64_t", NULL, sizeof(__pyx_t_5numpy_float64_t), { 0 }, 0, 'R', 0, 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t = { "int32_t", NULL, sizeof(__pyx_t_5numpy_int32_t), { 0 }, 0, 'I', IS_UNSIGNED(__pyx_t_5numpy_int32_t), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t = { "int32_t", NULL, sizeof(__pyx_t_5numpy_int32_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_int32_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_int32_t), 0 }; #define __Pyx_MODULE_NAME "sklearn.svm.libsvm" int __pyx_module_is_main_sklearn__svm__libsvm = 0; @@ -978,278 +1185,288 @@ static PyObject *__pyx_builtin_MemoryError; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_RuntimeError; -static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight_label, PyArrayObject *__pyx_v_class_weight, PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size); /* proto */ -static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_label, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight_label, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size); /* proto */ -static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_label, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight_label, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size); /* proto */ -static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_label, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight_label, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size); /* proto */ -static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_n_fold, PyObject *__pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, CYTHON_UNUSED double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight_label, PyArrayObject *__pyx_v_class_weight, PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size); /* proto */ +static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight, PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size, int __pyx_v_max_iter, int __pyx_v_random_seed); /* proto */ +static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, double __pyx_v_cache_size); /* proto */ +static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, double __pyx_v_cache_size); /* proto */ +static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, double __pyx_v_cache_size); /* proto */ +static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_n_fold, PyObject *__pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, CYTHON_UNUSED double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight, PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size, int __pyx_v_max_iter, int __pyx_v_random_seed); /* proto */ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_10set_verbosity_wrap(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_verbosity); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ -static char __pyx_k_4[] = "sample_weight and X have incompatible shapes: "; -static char __pyx_k_5[] = "sample_weight has %s samples while X has %s"; -static char __pyx_k_6[] = "Seems we've run out of of memory"; -static char __pyx_k_8[] = "p < 0"; -static char __pyx_k_9[] = "epsilon < 0"; -static char __pyx_k_22[] = "We've run out of of memory"; -static char __pyx_k_39[] = "Number of samples is less than number of folds"; -static char __pyx_k_42[] = "ndarray is not C contiguous"; -static char __pyx_k_44[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_46[] = "Non-native byte order not supported"; -static char __pyx_k_48[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_49[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_52[] = "Format string allocated too short."; -static char __pyx_k_54[] = "\nBinding for libsvm_skl\n----------------------\n\nThese are the bindings for libsvm_skl, which is a fork o libsvm[1]\nthat adds to libsvm some capabilities, like index of support vectors\nand efficient representation of dense matrices.\n\nThese are low-level routines, but can be used for flexibility or\nperformance reasons. See sklearn.svm for a higher-level API.\n\nLow-level memory management is done in libsvm_helper.c. If we happen\nto run out of memory a MemoryError will be raised. In practice this is\nnot very helpful since hight changes are malloc fails inside svm.cpp,\nwhere no sort of memory checks are done.\n\n[1] http://www.csie.ntu.edu.tw/~cjlin/libsvm/\n\nNotes\n-----\nMaybe we could speed it a bit further by decorating functions with\n@cython.boundscheck(False), but probably it is not worth since all\nwork is done in lisvm_helper.c\nAlso, the signature mode='c' is somewhat superficial, since we already\ncheck that arrays are C-contiguous in svm.py\n\nAuthors\n-------\n2010: Fabian Pedregosa \n Gael Varoquaux \n"; -static char __pyx_k_60[] = "/home/andy/checkout/scikit-learn/sklearn/svm/libsvm.pyx"; -static char __pyx_k_61[] = "sklearn.svm.libsvm"; -static char __pyx_k__B[] = "B"; -static char __pyx_k__C[] = "C"; -static char __pyx_k__H[] = "H"; -static char __pyx_k__I[] = "I"; -static char __pyx_k__L[] = "L"; -static char __pyx_k__O[] = "O"; -static char __pyx_k__Q[] = "Q"; -static char __pyx_k__X[] = "X"; -static char __pyx_k__Y[] = "Y"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__d[] = "d"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__g[] = "g"; -static char __pyx_k__h[] = "h"; -static char __pyx_k__i[] = "i"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__q[] = "q"; -static char __pyx_k__SV[] = "SV"; -static char __pyx_k__Zd[] = "Zd"; -static char __pyx_k__Zf[] = "Zf"; -static char __pyx_k__Zg[] = "Zg"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__nr[] = "nr"; -static char __pyx_k__nu[] = "nu"; -static char __pyx_k__fit[] = "fit"; -static char __pyx_k__nSV[] = "nSV"; -static char __pyx_k__rbf[] = "rbf"; -static char __pyx_k__tol[] = "tol"; -static char __pyx_k__ones[] = "ones"; -static char __pyx_k__poly[] = "poly"; -static char __pyx_k__coef0[] = "coef0"; -static char __pyx_k__dtype[] = "dtype"; -static char __pyx_k__empty[] = "empty"; -static char __pyx_k__gamma[] = "gamma"; -static char __pyx_k__index[] = "index"; -static char __pyx_k__int32[] = "int32"; -static char __pyx_k__label[] = "label"; -static char __pyx_k__model[] = "model"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__param[] = "param"; -static char __pyx_k__probA[] = "probA"; -static char __pyx_k__probB[] = "probB"; -static char __pyx_k__range[] = "range"; -static char __pyx_k__SV_len[] = "SV_len"; -static char __pyx_k__degree[] = "degree"; -static char __pyx_k__kernel[] = "kernel"; -static char __pyx_k__linear[] = "linear"; -static char __pyx_k__n_fold[] = "n_fold"; -static char __pyx_k__target[] = "target"; -static char __pyx_k__epsilon[] = "epsilon"; -static char __pyx_k__float64[] = "float64"; -static char __pyx_k__n_class[] = "n_class"; -static char __pyx_k__predict[] = "predict"; -static char __pyx_k__problem[] = "problem"; -static char __pyx_k__replace[] = "replace"; -static char __pyx_k__sigmoid[] = "sigmoid"; -static char __pyx_k__support[] = "support"; -static char __pyx_k__sv_coef[] = "sv_coef"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__svm_type[] = "svm_type"; -static char __pyx_k__error_msg[] = "error_msg"; -static char __pyx_k__intercept[] = "intercept"; -static char __pyx_k__shrinking[] = "shrinking"; -static char __pyx_k__verbosity[] = "verbosity"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__cache_size[] = "cache_size"; -static char __pyx_k__dec_values[] = "dec_values"; -static char __pyx_k__error_repl[] = "error_repl"; -static char __pyx_k__n_class_SV[] = "n_class_SV"; -static char __pyx_k__MemoryError[] = "MemoryError"; -static char __pyx_k__precomputed[] = "precomputed"; -static char __pyx_k__probability[] = "probability"; -static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k__class_weight[] = "class_weight"; -static char __pyx_k__kernel_index[] = "kernel_index"; -static char __pyx_k__predict_proba[] = "predict_proba"; -static char __pyx_k__sample_weight[] = "sample_weight"; -static char __pyx_k__support_vectors[] = "support_vectors"; -static char __pyx_k__cross_validation[] = "cross_validation"; -static char __pyx_k__decision_function[] = "decision_function"; -static char __pyx_k__class_weight_label[] = "class_weight_label"; -static char __pyx_k__set_verbosity_wrap[] = "set_verbosity_wrap"; -static char __pyx_k__LIBSVM_KERNEL_TYPES[] = "LIBSVM_KERNEL_TYPES"; -static PyObject *__pyx_kp_s_22; -static PyObject *__pyx_kp_s_39; -static PyObject *__pyx_kp_s_4; -static PyObject *__pyx_kp_u_42; -static PyObject *__pyx_kp_u_44; -static PyObject *__pyx_kp_u_46; -static PyObject *__pyx_kp_u_48; -static PyObject *__pyx_kp_u_49; -static PyObject *__pyx_kp_s_5; -static PyObject *__pyx_kp_u_52; -static PyObject *__pyx_kp_s_6; -static PyObject *__pyx_kp_s_60; -static PyObject *__pyx_n_s_61; -static PyObject *__pyx_kp_s_8; -static PyObject *__pyx_kp_s_9; -static PyObject *__pyx_n_s__C; -static PyObject *__pyx_n_s__LIBSVM_KERNEL_TYPES; -static PyObject *__pyx_n_s__MemoryError; -static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__SV; -static PyObject *__pyx_n_s__SV_len; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s__X; -static PyObject *__pyx_n_s__Y; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__cache_size; -static PyObject *__pyx_n_s__class_weight; -static PyObject *__pyx_n_s__class_weight_label; -static PyObject *__pyx_n_s__coef0; -static PyObject *__pyx_n_s__cross_validation; -static PyObject *__pyx_n_s__dec_values; -static PyObject *__pyx_n_s__decision_function; -static PyObject *__pyx_n_s__degree; -static PyObject *__pyx_n_s__dtype; -static PyObject *__pyx_n_s__empty; -static PyObject *__pyx_n_s__epsilon; -static PyObject *__pyx_n_s__error_msg; -static PyObject *__pyx_n_s__error_repl; -static PyObject *__pyx_n_s__fit; -static PyObject *__pyx_n_s__float64; -static PyObject *__pyx_n_s__gamma; -static PyObject *__pyx_n_s__index; -static PyObject *__pyx_n_s__int32; -static PyObject *__pyx_n_s__intercept; -static PyObject *__pyx_n_s__kernel; -static PyObject *__pyx_n_s__kernel_index; -static PyObject *__pyx_n_s__label; -static PyObject *__pyx_n_s__linear; -static PyObject *__pyx_n_s__model; -static PyObject *__pyx_n_s__nSV; -static PyObject *__pyx_n_s__n_class; -static PyObject *__pyx_n_s__n_class_SV; -static PyObject *__pyx_n_s__n_fold; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__nr; -static PyObject *__pyx_n_s__nu; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__ones; -static PyObject *__pyx_n_s__param; -static PyObject *__pyx_n_s__poly; -static PyObject *__pyx_n_s__precomputed; -static PyObject *__pyx_n_s__predict; -static PyObject *__pyx_n_s__predict_proba; -static PyObject *__pyx_n_s__probA; -static PyObject *__pyx_n_s__probB; -static PyObject *__pyx_n_s__probability; -static PyObject *__pyx_n_s__problem; -static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__rbf; -static PyObject *__pyx_n_s__replace; -static PyObject *__pyx_n_s__sample_weight; -static PyObject *__pyx_n_s__set_verbosity_wrap; -static PyObject *__pyx_n_s__shrinking; -static PyObject *__pyx_n_s__sigmoid; -static PyObject *__pyx_n_s__support; -static PyObject *__pyx_n_s__support_vectors; -static PyObject *__pyx_n_s__sv_coef; -static PyObject *__pyx_n_s__svm_type; -static PyObject *__pyx_n_s__target; -static PyObject *__pyx_n_s__tol; -static PyObject *__pyx_n_s__verbosity; +static char __pyx_k_B[] = "B"; +static char __pyx_k_C[] = "C"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_X[] = "X"; +static char __pyx_k_Y[] = "Y"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_SV[] = "SV"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_nr[] = "nr"; +static char __pyx_k_nu[] = "nu"; +static char __pyx_k_rv[] = "rv"; +static char __pyx_k_fit[] = "fit"; +static char __pyx_k_nSV[] = "nSV"; +static char __pyx_k_p_0[] = "p < 0"; +static char __pyx_k_rbf[] = "rbf"; +static char __pyx_k_tol[] = "tol"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_ones[] = "ones"; +static char __pyx_k_poly[] = "poly"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_coef0[] = "coef0"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_empty[] = "empty"; +static char __pyx_k_gamma[] = "gamma"; +static char __pyx_k_index[] = "index"; +static char __pyx_k_int32[] = "int32"; +static char __pyx_k_model[] = "model"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_param[] = "param"; +static char __pyx_k_probA[] = "probA"; +static char __pyx_k_probB[] = "probB"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_SV_len[] = "SV_len"; +static char __pyx_k_arange[] = "arange"; +static char __pyx_k_degree[] = "degree"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_kernel[] = "kernel"; +static char __pyx_k_linear[] = "linear"; +static char __pyx_k_n_fold[] = "n_fold"; +static char __pyx_k_target[] = "target"; +static char __pyx_k_epsilon[] = "epsilon"; +static char __pyx_k_float64[] = "float64"; +static char __pyx_k_n_class[] = "n_class"; +static char __pyx_k_predict[] = "predict"; +static char __pyx_k_problem[] = "problem"; +static char __pyx_k_sigmoid[] = "sigmoid"; +static char __pyx_k_support[] = "support"; +static char __pyx_k_sv_coef[] = "sv_coef"; +static char __pyx_k_max_iter[] = "max_iter"; +static char __pyx_k_svm_type[] = "svm_type"; +static char __pyx_k_warnings[] = "warnings"; +static char __pyx_k_epsilon_0[] = "epsilon < 0"; +static char __pyx_k_error_msg[] = "error_msg"; +static char __pyx_k_intercept[] = "intercept"; +static char __pyx_k_shrinking[] = "shrinking"; +static char __pyx_k_verbosity[] = "verbosity"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_cache_size[] = "cache_size"; +static char __pyx_k_dec_values[] = "dec_values"; +static char __pyx_k_error_repl[] = "error_repl"; +static char __pyx_k_fit_status[] = "fit_status"; +static char __pyx_k_n_class_SV[] = "n_class_SV"; +static char __pyx_k_MemoryError[] = "MemoryError"; +static char __pyx_k_precomputed[] = "precomputed"; +static char __pyx_k_probability[] = "probability"; +static char __pyx_k_random_seed[] = "random_seed"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_class_weight[] = "class_weight"; +static char __pyx_k_kernel_index[] = "kernel_index"; +static char __pyx_k_predict_proba[] = "predict_proba"; +static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k_sample_weight[] = "sample_weight"; +static char __pyx_k_support_vectors[] = "support_vectors"; +static char __pyx_k_cross_validation[] = "cross_validation"; +static char __pyx_k_decision_function[] = "decision_function"; +static char __pyx_k_pyx_releasebuffer[] = "__pyx_releasebuffer"; +static char __pyx_k_class_weight_label[] = "class_weight_label"; +static char __pyx_k_set_verbosity_wrap[] = "set_verbosity_wrap"; +static char __pyx_k_sklearn_svm_libsvm[] = "sklearn.svm.libsvm"; +static char __pyx_k_LIBSVM_KERNEL_TYPES[] = "LIBSVM_KERNEL_TYPES"; +static char __pyx_k_We_ve_run_out_of_memory[] = "We've run out of memory"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_Seems_we_ve_run_out_of_memory[] = "Seems we've run out of memory"; +static char __pyx_k_Binding_for_libsvm_skl_These_ar[] = "\nBinding for libsvm_skl\n----------------------\n\nThese are the bindings for libsvm_skl, which is a fork of libsvm[1]\nthat adds to libsvm some capabilities, like index of support vectors\nand efficient representation of dense matrices.\n\nThese are low-level routines, but can be used for flexibility or\nperformance reasons. See sklearn.svm for a higher-level API.\n\nLow-level memory management is done in libsvm_helper.c. If we happen\nto run out of memory a MemoryError will be raised. In practice this is\nnot very helpful since hight changes are malloc fails inside svm.cpp,\nwhere no sort of memory checks are done.\n\n[1] http://www.csie.ntu.edu.tw/~cjlin/libsvm/\n\nNotes\n-----\nMaybe we could speed it a bit further by decorating functions with\n@cython.boundscheck(False), but probably it is not worth since all\nwork is done in lisvm_helper.c\nAlso, the signature mode='c' is somewhat superficial, since we already\ncheck that arrays are C-contiguous in svm.py\n\nAuthors\n-------\n2010: Fabian Pedregosa \n Gael Varoquaux \n"; +static char __pyx_k_home_larsb_src_scikit_learn_skl[] = "/home/larsb/src/scikit-learn/sklearn/svm/libsvm.pyx"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_Number_of_samples_is_less_than_n[] = "Number of samples is less than number of folds"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_sample_weight_and_X_have_incompa[] = "sample_weight and X have incompatible shapes: "; +static char __pyx_k_sample_weight_has_s_samples_whil[] = "sample_weight has %s samples while X has %s"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_n_s_C; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_n_s_LIBSVM_KERNEL_TYPES; +static PyObject *__pyx_n_s_MemoryError; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_kp_s_Number_of_samples_is_less_than_n; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_SV; +static PyObject *__pyx_n_s_SV_len; +static PyObject *__pyx_kp_s_Seems_we_ve_run_out_of_memory; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_kp_s_We_ve_run_out_of_memory; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_n_s_Y; +static PyObject *__pyx_n_s_arange; +static PyObject *__pyx_n_s_cache_size; +static PyObject *__pyx_n_s_class_weight; +static PyObject *__pyx_n_s_class_weight_label; +static PyObject *__pyx_n_s_coef0; +static PyObject *__pyx_n_s_cross_validation; +static PyObject *__pyx_n_s_dec_values; +static PyObject *__pyx_n_s_decision_function; +static PyObject *__pyx_n_s_degree; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_empty; +static PyObject *__pyx_n_s_epsilon; +static PyObject *__pyx_kp_s_epsilon_0; +static PyObject *__pyx_n_s_error_msg; +static PyObject *__pyx_n_s_error_repl; +static PyObject *__pyx_n_s_fit; +static PyObject *__pyx_n_s_fit_status; +static PyObject *__pyx_n_s_float64; +static PyObject *__pyx_n_s_gamma; +static PyObject *__pyx_kp_s_home_larsb_src_scikit_learn_skl; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_index; +static PyObject *__pyx_n_s_int32; +static PyObject *__pyx_n_s_intercept; +static PyObject *__pyx_n_s_kernel; +static PyObject *__pyx_n_s_kernel_index; +static PyObject *__pyx_n_s_linear; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_max_iter; +static PyObject *__pyx_n_s_model; +static PyObject *__pyx_n_s_nSV; +static PyObject *__pyx_n_s_n_class; +static PyObject *__pyx_n_s_n_class_SV; +static PyObject *__pyx_n_s_n_fold; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_nr; +static PyObject *__pyx_n_s_nu; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_ones; +static PyObject *__pyx_kp_s_p_0; +static PyObject *__pyx_n_s_param; +static PyObject *__pyx_n_s_poly; +static PyObject *__pyx_n_s_precomputed; +static PyObject *__pyx_n_s_predict; +static PyObject *__pyx_n_s_predict_proba; +static PyObject *__pyx_n_s_probA; +static PyObject *__pyx_n_s_probB; +static PyObject *__pyx_n_s_probability; +static PyObject *__pyx_n_s_problem; +static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_releasebuffer; +static PyObject *__pyx_n_s_random_seed; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_rbf; +static PyObject *__pyx_n_s_rv; +static PyObject *__pyx_n_s_sample_weight; +static PyObject *__pyx_kp_s_sample_weight_and_X_have_incompa; +static PyObject *__pyx_kp_s_sample_weight_has_s_samples_whil; +static PyObject *__pyx_n_s_set_verbosity_wrap; +static PyObject *__pyx_n_s_shrinking; +static PyObject *__pyx_n_s_sigmoid; +static PyObject *__pyx_n_s_sklearn_svm_libsvm; +static PyObject *__pyx_n_s_support; +static PyObject *__pyx_n_s_support_vectors; +static PyObject *__pyx_n_s_sv_coef; +static PyObject *__pyx_n_s_svm_type; +static PyObject *__pyx_n_s_target; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_n_s_tol; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_verbosity; +static PyObject *__pyx_n_s_warnings; static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_2; static PyObject *__pyx_int_4; -static PyObject *__pyx_int_15; -static PyArrayObject *__pyx_k_1; -static PyArrayObject *__pyx_k_2; -static PyArrayObject *__pyx_k_3; -static PyArrayObject *__pyx_k_17; -static PyArrayObject *__pyx_k_18; -static PyArrayObject *__pyx_k_19; -static PyArrayObject *__pyx_k_20; -static PyArrayObject *__pyx_k_21; -static PyArrayObject *__pyx_k_24; -static PyArrayObject *__pyx_k_25; -static PyArrayObject *__pyx_k_26; -static PyArrayObject *__pyx_k_27; -static PyArrayObject *__pyx_k_28; -static PyArrayObject *__pyx_k_30; -static PyArrayObject *__pyx_k_31; -static PyArrayObject *__pyx_k_32; -static PyArrayObject *__pyx_k_33; -static PyArrayObject *__pyx_k_34; -static PyArrayObject *__pyx_k_36; -static PyArrayObject *__pyx_k_37; -static PyArrayObject *__pyx_k_38; -static PyObject *__pyx_k_tuple_7; -static PyObject *__pyx_k_tuple_10; -static PyObject *__pyx_k_tuple_11; -static PyObject *__pyx_k_tuple_12; -static PyObject *__pyx_k_tuple_13; -static PyObject *__pyx_k_tuple_14; -static PyObject *__pyx_k_tuple_15; -static PyObject *__pyx_k_tuple_16; -static PyObject *__pyx_k_tuple_23; -static PyObject *__pyx_k_tuple_29; -static PyObject *__pyx_k_tuple_35; -static PyObject *__pyx_k_tuple_40; -static PyObject *__pyx_k_tuple_41; -static PyObject *__pyx_k_tuple_43; -static PyObject *__pyx_k_tuple_45; -static PyObject *__pyx_k_tuple_47; -static PyObject *__pyx_k_tuple_50; -static PyObject *__pyx_k_tuple_51; -static PyObject *__pyx_k_tuple_53; -static PyObject *__pyx_k_tuple_55; -static PyObject *__pyx_k_tuple_56; -static PyObject *__pyx_k_tuple_57; -static PyObject *__pyx_k_tuple_58; -static PyObject *__pyx_k_tuple_62; -static PyObject *__pyx_k_tuple_63; -static PyObject *__pyx_k_tuple_64; -static PyObject *__pyx_k_tuple_65; -static PyObject *__pyx_k_tuple_66; -static PyObject *__pyx_k_tuple_67; -static PyObject *__pyx_k_tuple_69; -static PyObject *__pyx_k_tuple_70; -static PyObject *__pyx_k_tuple_71; -static PyObject *__pyx_k_tuple_72; -static PyObject *__pyx_k_tuple_73; -static PyObject *__pyx_k_tuple_74; -static PyObject *__pyx_k_tuple_76; -static PyObject *__pyx_k_tuple_77; -static PyObject *__pyx_k_tuple_78; -static PyObject *__pyx_k_tuple_79; -static PyObject *__pyx_k_tuple_80; -static PyObject *__pyx_k_tuple_81; -static PyObject *__pyx_k_tuple_83; -static PyObject *__pyx_k_tuple_84; -static PyObject *__pyx_k_tuple_85; -static PyObject *__pyx_k_tuple_86; -static PyObject *__pyx_k_tuple_88; -static PyObject *__pyx_k_codeobj_59; -static PyObject *__pyx_k_codeobj_68; -static PyObject *__pyx_k_codeobj_75; -static PyObject *__pyx_k_codeobj_82; -static PyObject *__pyx_k_codeobj_87; -static PyObject *__pyx_k_codeobj_89; +static PyArrayObject *__pyx_k_; +static PyArrayObject *__pyx_k__2; +static PyArrayObject *__pyx_k__10; +static PyArrayObject *__pyx_k__11; +static PyArrayObject *__pyx_k__12; +static PyArrayObject *__pyx_k__13; +static PyArrayObject *__pyx_k__15; +static PyArrayObject *__pyx_k__16; +static PyArrayObject *__pyx_k__17; +static PyArrayObject *__pyx_k__18; +static PyArrayObject *__pyx_k__20; +static PyArrayObject *__pyx_k__21; +static PyArrayObject *__pyx_k__22; +static PyArrayObject *__pyx_k__23; +static PyArrayObject *__pyx_k__25; +static PyArrayObject *__pyx_k__26; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__8; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_tuple__14; +static PyObject *__pyx_tuple__19; +static PyObject *__pyx_tuple__24; +static PyObject *__pyx_tuple__27; +static PyObject *__pyx_tuple__28; +static PyObject *__pyx_tuple__29; +static PyObject *__pyx_tuple__30; +static PyObject *__pyx_tuple__31; +static PyObject *__pyx_tuple__32; +static PyObject *__pyx_tuple__33; +static PyObject *__pyx_tuple__34; +static PyObject *__pyx_tuple__35; +static PyObject *__pyx_tuple__36; +static PyObject *__pyx_tuple__37; +static PyObject *__pyx_tuple__39; +static PyObject *__pyx_tuple__40; +static PyObject *__pyx_tuple__41; +static PyObject *__pyx_tuple__42; +static PyObject *__pyx_tuple__43; +static PyObject *__pyx_tuple__45; +static PyObject *__pyx_tuple__46; +static PyObject *__pyx_tuple__47; +static PyObject *__pyx_tuple__48; +static PyObject *__pyx_tuple__49; +static PyObject *__pyx_tuple__51; +static PyObject *__pyx_tuple__52; +static PyObject *__pyx_tuple__53; +static PyObject *__pyx_tuple__54; +static PyObject *__pyx_tuple__55; +static PyObject *__pyx_tuple__57; +static PyObject *__pyx_tuple__58; +static PyObject *__pyx_tuple__59; +static PyObject *__pyx_tuple__61; +static PyObject *__pyx_codeobj__38; +static PyObject *__pyx_codeobj__44; +static PyObject *__pyx_codeobj__50; +static PyObject *__pyx_codeobj__56; +static PyObject *__pyx_codeobj__60; +static PyObject *__pyx_codeobj__62; + +/* "sklearn/svm/libsvm.pyx":54 + * # Wrapper functions + * + * def fit( # <<<<<<<<<<<<<< + * np.ndarray[np.float64_t, ndim=2, mode='c'] X, + * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, + */ /* Python wrapper */ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_1fit(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_3svm_6libsvm_fit[] = "\n Train the model using libsvm (low-level method)\n\n Parameters\n ----------\n X: array-like, dtype=float64, size=[n_samples, n_features]\n\n Y: array, dtype=float64, size=[n_samples]\n target vector\n\n svm_type : {0, 1, 2, 3, 4}\n Type of SVM: C_SVC, NuSVC, OneClassSVM, EpsilonSVR or NuSVR\n respectevely.\n\n kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'}\n Kernel to use in the model: linear, polynomial, RBF, sigmoid\n or precomputed.\n\n degree : int32\n Degree of the polynomial kernel (only relevant if kernel is\n set to polynomial)\n\n gamma : float64\n Gamma parameter in RBF kernel (only relevant if kernel is set\n to RBF)\n\n coef0 : float64\n Independent parameter in poly/sigmoid kernel.\n\n tol : float64\n Stopping criteria.\n\n C : float64\n C parameter in C-Support Vector Classification\n\n nu : float64\n\n cache_size : float64\n\n Returns\n -------\n support : array, shape=[n_support]\n index of support vectors\n\n support_vectors : array, shape=[n_support, n_features]\n support vectors (equivalent to X[support]). Will return an\n empty array in the case of precomputed kernel.\n\n n_class_SV : array\n number of support vectors in each class.\n\n sv_coef : array\n coefficients of support vectors in decision function.\n\n intercept : array\n intercept in decision function\n\n label : labels for different classes (only relevant in classification).\n\n probA, probB : array\n probability estimates, empty array for probability=False\n "; +static char __pyx_doc_7sklearn_3svm_6libsvm_fit[] = "\n Train the model using libsvm (low-level method)\n\n Parameters\n ----------\n X : array-like, dtype=float64, size=[n_samples, n_features]\n\n Y : array, dtype=float64, size=[n_samples]\n target vector\n\n svm_type : {0, 1, 2, 3, 4}, optional\n Type of SVM: C_SVC, NuSVC, OneClassSVM, EpsilonSVR or NuSVR\n respectively. 0 by default.\n\n kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'}, optional\n Kernel to use in the model: linear, polynomial, RBF, sigmoid\n or precomputed. 'rbf' by default.\n\n degree : int32, optional\n Degree of the polynomial kernel (only relevant if kernel is\n set to polynomial), 3 by default.\n\n gamma : float64, optional\n Gamma parameter in RBF kernel (only relevant if kernel is set\n to RBF). 0.1 by default.\n\n coef0 : float64, optional\n Independent parameter in poly/sigmoid kernel. 0 by default.\n\n tol : float64, optional\n Numeric stopping criterion (WRITEME). 1e-3 by default.\n\n C : float64, optional\n C parameter in C-Support Vector Classification. 1 by default.\n\n nu : float64, optional\n 0.5 by default.\n\n epsilon : double, optional\n 0.1 by default.\n\n class_weight : array, dtype float64, shape (n_classes,), optional\n np.empty(0) by default.\n\n sample_weight : array, dtype float64, shape (n_samples,), optional\n np.empty(0) by default.\n\n shrinking : int, optional\n 1 by default.\n\n probability : int, optional\n 0 by default.\n\n cache_size : float64, optional\n Cache size for gram matrix columns (in megabytes). 100 by default.\n\n max_iter : int (-1 for no limit), optional.\n Stop solver after this many iterations regardless of accuracy\n (XXX Currently there is no API to know whether this kicked in.)\n -1 by default.\n\n random_seed : int, optional\n Seed for the random number generator"" used for probability estimates.\n 0 by default.\n\n Returns\n -------\n support : array, shape=[n_support]\n index of support vectors\n\n support_vectors : array, shape=[n_support, n_features]\n support vectors (equivalent to X[support]). Will return an\n empty array in the case of precomputed kernel.\n\n n_class_SV : array\n number of support vectors in each class.\n\n sv_coef : array\n coefficients of support vectors in decision function.\n\n intercept : array\n intercept in decision function\n\n probA, probB : array\n probability estimates, empty array for probability=False\n "; static PyMethodDef __pyx_mdef_7sklearn_3svm_6libsvm_1fit = {__Pyx_NAMESTR("fit"), (PyCFunction)__pyx_pw_7sklearn_3svm_6libsvm_1fit, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_3svm_6libsvm_fit)}; static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_1fit(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_X = 0; @@ -1263,27 +1480,30 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_1fit(PyObject *__pyx_self, PyObj double __pyx_v_C; double __pyx_v_nu; double __pyx_v_epsilon; - PyArrayObject *__pyx_v_class_weight_label = 0; PyArrayObject *__pyx_v_class_weight = 0; PyArrayObject *__pyx_v_sample_weight = 0; int __pyx_v_shrinking; int __pyx_v_probability; double __pyx_v_cache_size; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__Y,&__pyx_n_s__svm_type,&__pyx_n_s__kernel,&__pyx_n_s__degree,&__pyx_n_s__gamma,&__pyx_n_s__coef0,&__pyx_n_s__tol,&__pyx_n_s__C,&__pyx_n_s__nu,&__pyx_n_s__epsilon,&__pyx_n_s__class_weight_label,&__pyx_n_s__class_weight,&__pyx_n_s__sample_weight,&__pyx_n_s__shrinking,&__pyx_n_s__probability,&__pyx_n_s__cache_size,0}; + int __pyx_v_max_iter; + int __pyx_v_random_seed; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("fit (wrapper)", 0); - __pyx_self = __pyx_self; { - PyObject* values[17] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - values[3] = ((PyObject*)__pyx_n_s__rbf); - values[11] = (PyObject *)__pyx_k_1; - values[12] = (PyObject *)__pyx_k_2; - values[13] = (PyObject *)__pyx_k_3; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_Y,&__pyx_n_s_svm_type,&__pyx_n_s_kernel,&__pyx_n_s_degree,&__pyx_n_s_gamma,&__pyx_n_s_coef0,&__pyx_n_s_tol,&__pyx_n_s_C,&__pyx_n_s_nu,&__pyx_n_s_epsilon,&__pyx_n_s_class_weight,&__pyx_n_s_sample_weight,&__pyx_n_s_shrinking,&__pyx_n_s_probability,&__pyx_n_s_cache_size,&__pyx_n_s_max_iter,&__pyx_n_s_random_seed,0}; + PyObject* values[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + values[3] = ((PyObject*)__pyx_n_s_rbf); + values[11] = (PyObject *)__pyx_k_; + values[12] = (PyObject *)__pyx_k__2; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { + case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); case 15: values[14] = PyTuple_GET_ITEM(__pyx_args, 14); @@ -1307,164 +1527,100 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_1fit(PyObject *__pyx_self, PyObj kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__Y); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("fit", 0, 2, 17, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("fit", 0, 2, 18, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__svm_type); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_svm_type); if (value) { values[2] = value; kw_args--; } } case 3: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kernel); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kernel); if (value) { values[3] = value; kw_args--; } } case 4: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__degree); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_degree); if (value) { values[4] = value; kw_args--; } } case 5: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__gamma); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_gamma); if (value) { values[5] = value; kw_args--; } } case 6: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coef0); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_coef0); if (value) { values[6] = value; kw_args--; } } case 7: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__tol); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tol); if (value) { values[7] = value; kw_args--; } } case 8: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_C); if (value) { values[8] = value; kw_args--; } } case 9: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nu); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_nu); if (value) { values[9] = value; kw_args--; } } case 10: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__epsilon); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_epsilon); if (value) { values[10] = value; kw_args--; } } case 11: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight_label); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight); if (value) { values[11] = value; kw_args--; } } case 12: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sample_weight); if (value) { values[12] = value; kw_args--; } } case 13: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sample_weight); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shrinking); if (value) { values[13] = value; kw_args--; } } case 14: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shrinking); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_probability); if (value) { values[14] = value; kw_args--; } } case 15: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probability); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_cache_size); if (value) { values[15] = value; kw_args--; } } case 16: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__cache_size); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_iter); if (value) { values[16] = value; kw_args--; } } + case 17: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random_seed); + if (value) { values[17] = value; kw_args--; } + } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "fit") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - if (values[2]) { - } else { - __pyx_v_svm_type = ((int)0); - } - if (values[4]) { - } else { - __pyx_v_degree = ((int)3); - } - if (values[5]) { - } else { - - /* "sklearn/svm/libsvm.pyx":51 - * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, # <<<<<<<<<<<<<< - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - */ - __pyx_v_gamma = ((double)0.1); - } - if (values[6]) { - } else { - __pyx_v_coef0 = ((double)0.); - } - if (values[7]) { - } else { - __pyx_v_tol = ((double)1e-3); - } - if (values[8]) { - } else { - - /* "sklearn/svm/libsvm.pyx":52 - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - * double C=1., double nu=0.5, double epsilon=0.1, # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), - */ - __pyx_v_C = ((double)1.); - } - if (values[9]) { - } else { - __pyx_v_nu = ((double)0.5); - } - if (values[10]) { - } else { - __pyx_v_epsilon = ((double)0.1); - } - if (values[14]) { - } else { - __pyx_v_shrinking = ((int)1); - } - if (values[15]) { - } else { - __pyx_v_probability = ((int)0); - } - if (values[16]) { - } else { - - /* "sklearn/svm/libsvm.pyx":60 - * sample_weight=np.empty(0), - * int shrinking=1, int probability=0, - * double cache_size=100.): # <<<<<<<<<<<<<< - * """ - * Train the model using libsvm (low-level method) - */ - __pyx_v_cache_size = ((double)100.); + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "fit") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { + case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); case 15: values[14] = PyTuple_GET_ITEM(__pyx_args, 14); @@ -1489,104 +1645,90 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_1fit(PyObject *__pyx_self, PyObj __pyx_v_X = ((PyArrayObject *)values[0]); __pyx_v_Y = ((PyArrayObject *)values[1]); if (values[2]) { - __pyx_v_svm_type = __Pyx_PyInt_AsInt(values[2]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_svm_type = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_svm_type = ((int)0); } __pyx_v_kernel = ((PyObject*)values[3]); if (values[4]) { - __pyx_v_degree = __Pyx_PyInt_AsInt(values[4]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_degree = __Pyx_PyInt_As_int(values[4]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_degree = ((int)3); } if (values[5]) { - __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[5]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/svm/libsvm.pyx":51 - * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, # <<<<<<<<<<<<<< - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - */ __pyx_v_gamma = ((double)0.1); } if (values[6]) { - __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_coef0 = ((double)0.); } if (values[7]) { - __pyx_v_tol = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_tol = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_tol = ((double)1e-3); } if (values[8]) { - __pyx_v_C = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_C = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/svm/libsvm.pyx":52 - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - * double C=1., double nu=0.5, double epsilon=0.1, # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), - */ __pyx_v_C = ((double)1.); } if (values[9]) { - __pyx_v_nu = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_nu = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_nu = ((double)0.5); } if (values[10]) { - __pyx_v_epsilon = __pyx_PyFloat_AsDouble(values[10]); if (unlikely((__pyx_v_epsilon == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_epsilon = __pyx_PyFloat_AsDouble(values[10]); if (unlikely((__pyx_v_epsilon == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_epsilon = ((double)0.1); } - __pyx_v_class_weight_label = ((PyArrayObject *)values[11]); - __pyx_v_class_weight = ((PyArrayObject *)values[12]); - __pyx_v_sample_weight = ((PyArrayObject *)values[13]); - if (values[14]) { - __pyx_v_shrinking = __Pyx_PyInt_AsInt(values[14]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_class_weight = ((PyArrayObject *)values[11]); + __pyx_v_sample_weight = ((PyArrayObject *)values[12]); + if (values[13]) { + __pyx_v_shrinking = __Pyx_PyInt_As_int(values[13]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_shrinking = ((int)1); } - if (values[15]) { - __pyx_v_probability = __Pyx_PyInt_AsInt(values[15]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[14]) { + __pyx_v_probability = __Pyx_PyInt_As_int(values[14]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_probability = ((int)0); } - if (values[16]) { - __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[15]) { + __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/svm/libsvm.pyx":60 - * sample_weight=np.empty(0), - * int shrinking=1, int probability=0, - * double cache_size=100.): # <<<<<<<<<<<<<< - * """ - * Train the model using libsvm (low-level method) - */ __pyx_v_cache_size = ((double)100.); } + if (values[16]) { + __pyx_v_max_iter = __Pyx_PyInt_As_int(values[16]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_max_iter = ((int)-1); + } + if (values[17]) { + __pyx_v_random_seed = __Pyx_PyInt_As_int(values[17]); if (unlikely((__pyx_v_random_seed == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_random_seed = ((int)0); + } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("fit", 0, 2, 17, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("fit", 0, 2, 18, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.svm.libsvm.fit", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kernel), (&PyString_Type), 1, "kernel", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight_label), __pyx_ptype_5numpy_ndarray, 1, "class_weight_label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_3svm_6libsvm_fit(__pyx_self, __pyx_v_X, __pyx_v_Y, __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_tol, __pyx_v_C, __pyx_v_nu, __pyx_v_epsilon, __pyx_v_class_weight_label, __pyx_v_class_weight, __pyx_v_sample_weight, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_cache_size); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kernel), (&PyString_Type), 1, "kernel", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_3svm_6libsvm_fit(__pyx_self, __pyx_v_X, __pyx_v_Y, __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_tol, __pyx_v_C, __pyx_v_nu, __pyx_v_epsilon, __pyx_v_class_weight, __pyx_v_sample_weight, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_cache_size, __pyx_v_max_iter, __pyx_v_random_seed); + + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -1595,29 +1737,22 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_1fit(PyObject *__pyx_self, PyObj return __pyx_r; } -/* "sklearn/svm/libsvm.pyx":47 - * # Wrapper functions - * - * def fit( # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=2, mode='c'] X, - * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, - */ - -static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight_label, PyArrayObject *__pyx_v_class_weight, PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size) { +static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight, PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size, int __pyx_v_max_iter, int __pyx_v_random_seed) { struct svm_parameter __pyx_v_param; struct svm_problem __pyx_v_problem; struct svm_model *__pyx_v_model; - char *__pyx_v_error_msg; + char const *__pyx_v_error_msg; npy_intp __pyx_v_SV_len; PyObject *__pyx_v_kernel_index = NULL; + PyArrayObject *__pyx_v_class_weight_label = 0; PyObject *__pyx_v_error_repl = NULL; + int __pyx_v_fit_status; PyObject *__pyx_v_n_class = NULL; PyArrayObject *__pyx_v_sv_coef = 0; PyArrayObject *__pyx_v_intercept = 0; PyArrayObject *__pyx_v_support = 0; PyArrayObject *__pyx_v_support_vectors = 0; PyArrayObject *__pyx_v_n_class_SV = 0; - PyArrayObject *__pyx_v_label = 0; PyArrayObject *__pyx_v_probA = 0; PyArrayObject *__pyx_v_probB = 0; __Pyx_LocalBuf_ND __pyx_pybuffernd_X; @@ -1630,8 +1765,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py __Pyx_Buffer __pyx_pybuffer_class_weight_label; __Pyx_LocalBuf_ND __pyx_pybuffernd_intercept; __Pyx_Buffer __pyx_pybuffer_intercept; - __Pyx_LocalBuf_ND __pyx_pybuffernd_label; - __Pyx_Buffer __pyx_pybuffer_label; __Pyx_LocalBuf_ND __pyx_pybuffernd_n_class_SV; __Pyx_Buffer __pyx_pybuffer_n_class_SV; __Pyx_LocalBuf_ND __pyx_pybuffernd_probA; @@ -1673,6 +1806,10 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py int __pyx_clineno = 0; __Pyx_RefNannySetupContext("fit", 0); __Pyx_INCREF((PyObject *)__pyx_v_sample_weight); + __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight_label.refcount = 0; + __pyx_pybuffernd_class_weight_label.data = NULL; + __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_sv_coef.pybuffer.buf = NULL; __pyx_pybuffer_sv_coef.refcount = 0; __pyx_pybuffernd_sv_coef.data = NULL; @@ -1693,10 +1830,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py __pyx_pybuffer_n_class_SV.refcount = 0; __pyx_pybuffernd_n_class_SV.data = NULL; __pyx_pybuffernd_n_class_SV.rcbuffer = &__pyx_pybuffer_n_class_SV; - __pyx_pybuffer_label.pybuffer.buf = NULL; - __pyx_pybuffer_label.refcount = 0; - __pyx_pybuffernd_label.data = NULL; - __pyx_pybuffernd_label.rcbuffer = &__pyx_pybuffer_label; __pyx_pybuffer_probA.pybuffer.buf = NULL; __pyx_pybuffer_probA.refcount = 0; __pyx_pybuffernd_probA.data = NULL; @@ -1713,10 +1846,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py __pyx_pybuffer_Y.refcount = 0; __pyx_pybuffernd_Y.data = NULL; __pyx_pybuffernd_Y.rcbuffer = &__pyx_pybuffer_Y; - __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; - __pyx_pybuffer_class_weight_label.refcount = 0; - __pyx_pybuffernd_class_weight_label.data = NULL; - __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_class_weight.pybuffer.buf = NULL; __pyx_pybuffer_class_weight.refcount = 0; __pyx_pybuffernd_class_weight.data = NULL; @@ -1727,75 +1856,70 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py __pyx_pybuffernd_sample_weight.rcbuffer = &__pyx_pybuffer_sample_weight; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Y.rcbuffer->pybuffer, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Y.rcbuffer->pybuffer, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_Y.diminfo[0].strides = __pyx_pybuffernd_Y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_Y.diminfo[0].shape = __pyx_pybuffernd_Y.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_class_weight.diminfo[0].strides = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight.diminfo[0].shape = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_sample_weight.diminfo[0].strides = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weight.diminfo[0].shape = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.shape[0]; - /* "sklearn/svm/libsvm.pyx":132 + /* "sklearn/svm/libsvm.pyx":163 * * * if len(sample_weight) == 0: # <<<<<<<<<<<<<< * sample_weight = np.ones(X.shape[0], dtype=np.float64) * else: */ - __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_sample_weight)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = (__pyx_t_1 == 0); + __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_sample_weight)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((__pyx_t_1 == 0) != 0); if (__pyx_t_2) { - /* "sklearn/svm/libsvm.pyx":133 + /* "sklearn/svm/libsvm.pyx":164 * * if len(sample_weight) == 0: * sample_weight = np.ones(X.shape[0], dtype=np.float64) # <<<<<<<<<<<<<< * else: * assert sample_weight.shape[0] == X.shape[0], \ */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__ones); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_ones); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, __pyx_t_3); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_8 = ((PyArrayObject *)__pyx_t_7); { __Pyx_BufFmt_StackElem __pyx_stack[1]; @@ -1811,17 +1935,16 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py } } __pyx_pybuffernd_sample_weight.diminfo[0].strides = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weight.diminfo[0].shape = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_8 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_sample_weight)); - __pyx_v_sample_weight = ((PyArrayObject *)__pyx_t_7); + __Pyx_DECREF_SET(__pyx_v_sample_weight, ((PyArrayObject *)__pyx_t_7)); __pyx_t_7 = 0; goto __pyx_L3; } /*else*/ { - /* "sklearn/svm/libsvm.pyx":135 + /* "sklearn/svm/libsvm.pyx":166 * sample_weight = np.ones(X.shape[0], dtype=np.float64) * else: * assert sample_weight.shape[0] == X.shape[0], \ # <<<<<<<<<<<<<< @@ -1829,188 +1952,296 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py * "sample_weight has %s samples while X has %s" % \ */ #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!((__pyx_v_sample_weight->dimensions[0]) == (__pyx_v_X->dimensions[0])))) { + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_sample_weight->dimensions[0]) == (__pyx_v_X->dimensions[0])) != 0))) { - /* "sklearn/svm/libsvm.pyx":138 + /* "sklearn/svm/libsvm.pyx":169 * "sample_weight and X have incompatible shapes: " + \ * "sample_weight has %s samples while X has %s" % \ * (sample_weight.shape[0], X.shape[0]) # <<<<<<<<<<<<<< * - * # set problem + * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) */ - __pyx_t_7 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_sample_weight->dimensions[0])); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_7 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_5), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 137; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Add(((PyObject *)__pyx_kp_s_4), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - PyErr_SetObject(PyExc_AssertionError, ((PyObject *)__pyx_t_5)); - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_sample_weight->dimensions[0])); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_7 = 0; + __pyx_t_3 = 0; + + /* "sklearn/svm/libsvm.pyx":168 + * assert sample_weight.shape[0] == X.shape[0], \ + * "sample_weight and X have incompatible shapes: " + \ + * "sample_weight has %s samples while X has %s" % \ # <<<<<<<<<<<<<< + * (sample_weight.shape[0], X.shape[0]) + * + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_sample_weight_has_s_samples_whil, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "sklearn/svm/libsvm.pyx":167 + * else: + * assert sample_weight.shape[0] == X.shape[0], \ + * "sample_weight and X have incompatible shapes: " + \ # <<<<<<<<<<<<<< + * "sample_weight has %s samples while X has %s" % \ + * (sample_weight.shape[0], X.shape[0]) + */ + __pyx_t_5 = PyNumber_Add(__pyx_kp_s_sample_weight_and_X_have_incompa, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyErr_SetObject(PyExc_AssertionError, __pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } } #endif } __pyx_L3:; - /* "sklearn/svm/libsvm.pyx":141 + /* "sklearn/svm/libsvm.pyx":171 + * (sample_weight.shape[0], X.shape[0]) * - * # set problem * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) # <<<<<<<<<<<<<< * set_problem( * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__LIBSVM_KERNEL_TYPES); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_LIBSVM_KERNEL_TYPES); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__index); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_index); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_kernel)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_kernel)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_kernel)); - __pyx_t_7 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_kernel); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_kernel); + __Pyx_GIVEREF(__pyx_v_kernel); + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_kernel_index = __pyx_t_7; __pyx_t_7 = 0; - /* "sklearn/svm/libsvm.pyx":143 + /* "sklearn/svm/libsvm.pyx":173 * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) * set_problem( * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) # <<<<<<<<<<<<<< * if problem.x == NULL: - * raise MemoryError("Seems we've run out of of memory") + * raise MemoryError("Seems we've run out of memory") + */ + __pyx_t_9 = __Pyx_PyInt_As_int(__pyx_v_kernel_index); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/svm/libsvm.pyx":172 + * + * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) + * set_problem( # <<<<<<<<<<<<<< + * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) + * if problem.x == NULL: */ - __pyx_t_9 = __Pyx_PyInt_AsInt(__pyx_v_kernel_index); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} set_problem((&__pyx_v_problem), __pyx_v_X->data, __pyx_v_Y->data, __pyx_v_sample_weight->data, __pyx_v_X->dimensions, __pyx_t_9); - /* "sklearn/svm/libsvm.pyx":144 + /* "sklearn/svm/libsvm.pyx":174 * set_problem( * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) * if problem.x == NULL: # <<<<<<<<<<<<<< - * raise MemoryError("Seems we've run out of of memory") - * + * raise MemoryError("Seems we've run out of memory") + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ */ - __pyx_t_2 = (__pyx_v_problem.x == NULL); + __pyx_t_2 = ((__pyx_v_problem.x == NULL) != 0); if (__pyx_t_2) { - /* "sklearn/svm/libsvm.pyx":145 + /* "sklearn/svm/libsvm.pyx":175 * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) * if problem.x == NULL: - * raise MemoryError("Seems we've run out of of memory") # <<<<<<<<<<<<<< - * - * # set parameters + * raise MemoryError("Seems we've run out of memory") # <<<<<<<<<<<<<< + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) */ - __pyx_t_7 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_7), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_Raise(__pyx_t_7, 0, 0, 0); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L4:; - /* "sklearn/svm/libsvm.pyx":149 - * # set parameters + /* "sklearn/svm/libsvm.pyx":177 + * raise MemoryError("Seems we've run out of memory") + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) # <<<<<<<<<<<<<< + * set_parameter( + * ¶m, svm_type, kernel_index, degree, gamma, coef0, nu, cache_size, + */ + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_arange); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_class_weight->dimensions[0])); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_int32); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_dtype, __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_3, __pyx_t_7); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = ((PyArrayObject *)__pyx_t_6); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_t_13, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_class_weight_label = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_13 = 0; + __pyx_v_class_weight_label = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; + + /* "sklearn/svm/libsvm.pyx":179 + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) * set_parameter( * ¶m, svm_type, kernel_index, degree, gamma, coef0, nu, cache_size, # <<<<<<<<<<<<<< * C, tol, epsilon, shrinking, probability, class_weight.shape[0], - * class_weight_label.data, class_weight.data) + * class_weight_label.data, class_weight.data, max_iter, random_seed) */ - __pyx_t_9 = __Pyx_PyInt_AsInt(__pyx_v_kernel_index); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyInt_As_int(__pyx_v_kernel_index); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/svm/libsvm.pyx":151 + /* "sklearn/svm/libsvm.pyx":178 + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) + * set_parameter( # <<<<<<<<<<<<<< * ¶m, svm_type, kernel_index, degree, gamma, coef0, nu, cache_size, * C, tol, epsilon, shrinking, probability, class_weight.shape[0], - * class_weight_label.data, class_weight.data) # <<<<<<<<<<<<<< - * - * # check parameters */ - set_parameter((&__pyx_v_param), __pyx_v_svm_type, __pyx_t_9, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_C, __pyx_v_tol, __pyx_v_epsilon, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data); + set_parameter((&__pyx_v_param), __pyx_v_svm_type, __pyx_t_9, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_C, __pyx_v_tol, __pyx_v_epsilon, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data, __pyx_v_max_iter, __pyx_v_random_seed); - /* "sklearn/svm/libsvm.pyx":154 + /* "sklearn/svm/libsvm.pyx":183 + * class_weight_label.data, class_weight.data, max_iter, random_seed) * - * # check parameters * error_msg = svm_check_parameter(&problem, ¶m) # <<<<<<<<<<<<<< * if error_msg: * # for SVR: epsilon is called p in libsvm */ __pyx_v_error_msg = svm_check_parameter((&__pyx_v_problem), (&__pyx_v_param)); - /* "sklearn/svm/libsvm.pyx":155 - * # check parameters + /* "sklearn/svm/libsvm.pyx":184 + * * error_msg = svm_check_parameter(&problem, ¶m) * if error_msg: # <<<<<<<<<<<<<< * # for SVR: epsilon is called p in libsvm - * error_repl = error_msg.replace("p < 0", "epsilon < 0") + * error_repl = error_msg.decode('utf-8').replace("p < 0", "epsilon < 0") */ __pyx_t_2 = (__pyx_v_error_msg != 0); if (__pyx_t_2) { - /* "sklearn/svm/libsvm.pyx":157 + /* "sklearn/svm/libsvm.pyx":186 * if error_msg: * # for SVR: epsilon is called p in libsvm - * error_repl = error_msg.replace("p < 0", "epsilon < 0") # <<<<<<<<<<<<<< + * error_repl = error_msg.decode('utf-8').replace("p < 0", "epsilon < 0") # <<<<<<<<<<<<<< * raise ValueError(error_repl) * */ - __pyx_t_7 = PyBytes_FromString(__pyx_v_error_msg); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __pyx_t_5 = PyObject_GetAttr(((PyObject *)__pyx_t_7), __pyx_n_s__replace); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_decode_c_string(__pyx_v_error_msg, 0, strlen(__pyx_v_error_msg), NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyUnicode_Replace(((PyObject*)__pyx_t_6), __pyx_kp_s_p_0, __pyx_kp_s_epsilon_0, -1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_v_error_repl = __pyx_t_7; __pyx_t_7 = 0; - /* "sklearn/svm/libsvm.pyx":158 + /* "sklearn/svm/libsvm.pyx":187 * # for SVR: epsilon is called p in libsvm - * error_repl = error_msg.replace("p < 0", "epsilon < 0") + * error_repl = error_msg.decode('utf-8').replace("p < 0", "epsilon < 0") * raise ValueError(error_repl) # <<<<<<<<<<<<<< * * # this does the real work */ - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_INCREF(__pyx_v_error_repl); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_v_error_repl); __Pyx_GIVEREF(__pyx_v_error_repl); - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L5:; - /* "sklearn/svm/libsvm.pyx":161 + /* "sklearn/svm/libsvm.pyx":190 * * # this does the real work - * model = svm_train(&problem, ¶m) # <<<<<<<<<<<<<< + * cdef int fit_status = 0 # <<<<<<<<<<<<<< + * with nogil: + * model = svm_train(&problem, ¶m, &fit_status) + */ + __pyx_v_fit_status = 0; + + /* "sklearn/svm/libsvm.pyx":191 + * # this does the real work + * cdef int fit_status = 0 + * with nogil: # <<<<<<<<<<<<<< + * model = svm_train(&problem, ¶m, &fit_status) + * + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/svm/libsvm.pyx":192 + * cdef int fit_status = 0 + * with nogil: + * model = svm_train(&problem, ¶m, &fit_status) # <<<<<<<<<<<<<< * * # from here until the end, we just copy the data returned by */ - __pyx_v_model = svm_train((&__pyx_v_problem), (&__pyx_v_param)); + __pyx_v_model = svm_train((&__pyx_v_problem), (&__pyx_v_param), (&__pyx_v_fit_status)); + } + + /* "sklearn/svm/libsvm.pyx":191 + * # this does the real work + * cdef int fit_status = 0 + * with nogil: # <<<<<<<<<<<<<< + * model = svm_train(&problem, ¶m, &fit_status) + * + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L8; + } + __pyx_L8:; + } + } - /* "sklearn/svm/libsvm.pyx":165 + /* "sklearn/svm/libsvm.pyx":196 * # from here until the end, we just copy the data returned by * # svm_train * SV_len = get_l(model) # <<<<<<<<<<<<<< @@ -2019,67 +2250,67 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py */ __pyx_v_SV_len = get_l(__pyx_v_model); - /* "sklearn/svm/libsvm.pyx":166 + /* "sklearn/svm/libsvm.pyx":197 * # svm_train * SV_len = get_l(model) * n_class = get_nr(model) # <<<<<<<<<<<<<< * - * # copy model.sv_coef + * cdef np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef */ - __pyx_t_5 = __Pyx_PyInt_to_py_Py_intptr_t(get_nr(__pyx_v_model)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_v_n_class = __pyx_t_5; - __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t(get_nr(__pyx_v_model)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_v_n_class = __pyx_t_6; + __pyx_t_6 = 0; - /* "sklearn/svm/libsvm.pyx":170 - * # copy model.sv_coef + /* "sklearn/svm/libsvm.pyx":200 + * * cdef np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef * sv_coef = np.empty((n_class-1, SV_len), dtype=np.float64) # <<<<<<<<<<<<<< * copy_sv_coef (sv_coef.data, model) * */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Subtract(__pyx_v_n_class, __pyx_int_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_SV_len); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyNumber_Subtract(__pyx_v_n_class, __pyx_int_1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_SV_len); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_5 = 0; + __pyx_t_6 = 0; __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); - __pyx_t_4 = 0; - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_13 = ((PyArrayObject *)__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer); - __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_t_13, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); + __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_t_14, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_v_sv_coef, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { @@ -2090,66 +2321,69 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py } } __pyx_pybuffernd_sv_coef.diminfo[0].strides = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sv_coef.diminfo[0].shape = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_sv_coef.diminfo[1].strides = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_sv_coef.diminfo[1].shape = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_13 = 0; - __pyx_v_sv_coef = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; + __pyx_t_14 = 0; + __pyx_v_sv_coef = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; - /* "sklearn/svm/libsvm.pyx":171 + /* "sklearn/svm/libsvm.pyx":201 * cdef np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef * sv_coef = np.empty((n_class-1, SV_len), dtype=np.float64) * copy_sv_coef (sv_coef.data, model) # <<<<<<<<<<<<<< * - * # copy model.rho into the intercept + * # the intercept is just model.rho but with sign changed */ copy_sv_coef(__pyx_v_sv_coef->data, __pyx_v_model); - /* "sklearn/svm/libsvm.pyx":176 + /* "sklearn/svm/libsvm.pyx":205 * # the intercept is just model.rho but with sign changed * cdef np.ndarray[np.float64_t, ndim=1, mode='c'] intercept - * intercept = np.empty(n_class*(n_class-1)/2, dtype=np.float64) # <<<<<<<<<<<<<< + * intercept = np.empty(int((n_class*(n_class-1))/2), dtype=np.float64) # <<<<<<<<<<<<<< * copy_intercept (intercept.data, model, intercept.shape) * */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyNumber_Subtract(__pyx_v_n_class, __pyx_int_1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_3 = PyNumber_Multiply(__pyx_v_n_class, __pyx_t_6); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_Subtract(__pyx_v_n_class, __pyx_int_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Multiply(__pyx_v_n_class, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyNumber_Divide(__pyx_t_3, __pyx_int_2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyNumber_Divide(__pyx_t_3, __pyx_int_2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Int(__pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_6); - __pyx_t_6 = 0; - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_14 = ((PyArrayObject *)__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_15 = ((PyArrayObject *)__pyx_t_6); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_t_14, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); + __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_t_15, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_v_intercept, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { @@ -2160,60 +2394,60 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py } } __pyx_pybuffernd_intercept.diminfo[0].strides = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_intercept.diminfo[0].shape = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_14 = 0; - __pyx_v_intercept = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; + __pyx_t_15 = 0; + __pyx_v_intercept = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; - /* "sklearn/svm/libsvm.pyx":177 + /* "sklearn/svm/libsvm.pyx":206 * cdef np.ndarray[np.float64_t, ndim=1, mode='c'] intercept - * intercept = np.empty(n_class*(n_class-1)/2, dtype=np.float64) + * intercept = np.empty(int((n_class*(n_class-1))/2), dtype=np.float64) * copy_intercept (intercept.data, model, intercept.shape) # <<<<<<<<<<<<<< * * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] support */ copy_intercept(__pyx_v_intercept->data, __pyx_v_model, __pyx_v_intercept->dimensions); - /* "sklearn/svm/libsvm.pyx":180 + /* "sklearn/svm/libsvm.pyx":209 * * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] support * support = np.empty (SV_len, dtype=np.int32) # <<<<<<<<<<<<<< * copy_support (support.data, model) * */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_SV_len); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_SV_len); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_int32); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_15 = ((PyArrayObject *)__pyx_t_7); + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_16 = ((PyArrayObject *)__pyx_t_7); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_support.rcbuffer->pybuffer); - __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support.rcbuffer->pybuffer, (PyObject*)__pyx_t_15, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); + __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support.rcbuffer->pybuffer, (PyObject*)__pyx_t_16, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support.rcbuffer->pybuffer, (PyObject*)__pyx_v_support, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { @@ -2224,13 +2458,13 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py } } __pyx_pybuffernd_support.diminfo[0].strides = __pyx_pybuffernd_support.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_support.diminfo[0].shape = __pyx_pybuffernd_support.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_15 = 0; + __pyx_t_16 = 0; __pyx_v_support = ((PyArrayObject *)__pyx_t_7); __pyx_t_7 = 0; - /* "sklearn/svm/libsvm.pyx":181 + /* "sklearn/svm/libsvm.pyx":210 * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] support * support = np.empty (SV_len, dtype=np.int32) * copy_support (support.data, model) # <<<<<<<<<<<<<< @@ -2239,50 +2473,49 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py */ copy_support(__pyx_v_support->data, __pyx_v_model); - /* "sklearn/svm/libsvm.pyx":185 + /* "sklearn/svm/libsvm.pyx":214 * # copy model.SV * cdef np.ndarray[np.float64_t, ndim=2, mode='c'] support_vectors * if kernel_index == 4: # <<<<<<<<<<<<<< * # precomputed kernel * support_vectors = np.empty((0, 0), dtype=np.float64) */ - __pyx_t_7 = PyObject_RichCompare(__pyx_v_kernel_index, __pyx_int_4, Py_EQ); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyObject_RichCompare(__pyx_v_kernel_index, __pyx_int_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_7); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; if (__pyx_t_2) { - /* "sklearn/svm/libsvm.pyx":187 + /* "sklearn/svm/libsvm.pyx":216 * if kernel_index == 4: * # precomputed kernel * support_vectors = np.empty((0, 0), dtype=np.float64) # <<<<<<<<<<<<<< * else: * support_vectors = np.empty((SV_len, X.shape[1]), dtype=np.float64) */ - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_float64); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_tuple__5, __pyx_t_7); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_k_tuple_12), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_16 = ((PyArrayObject *)__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = ((PyArrayObject *)__pyx_t_3); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_support_vectors.rcbuffer->pybuffer); - __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support_vectors.rcbuffer->pybuffer, (PyObject*)__pyx_t_16, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); + __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support_vectors.rcbuffer->pybuffer, (PyObject*)__pyx_t_17, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support_vectors.rcbuffer->pybuffer, (PyObject*)__pyx_v_support_vectors, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { @@ -2293,64 +2526,64 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py } } __pyx_pybuffernd_support_vectors.diminfo[0].strides = __pyx_pybuffernd_support_vectors.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_support_vectors.diminfo[0].shape = __pyx_pybuffernd_support_vectors.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_support_vectors.diminfo[1].strides = __pyx_pybuffernd_support_vectors.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_support_vectors.diminfo[1].shape = __pyx_pybuffernd_support_vectors.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_16 = 0; - __pyx_v_support_vectors = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; - goto __pyx_L6; + __pyx_t_17 = 0; + __pyx_v_support_vectors = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L9; } /*else*/ { - /* "sklearn/svm/libsvm.pyx":189 + /* "sklearn/svm/libsvm.pyx":218 * support_vectors = np.empty((0, 0), dtype=np.float64) * else: * support_vectors = np.empty((SV_len, X.shape[1]), dtype=np.float64) # <<<<<<<<<<<<<< * copy_SV(support_vectors.data, model, support_vectors.shape) * */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_SV_len); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_5 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_X->dimensions[1])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_SV_len); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->dimensions[1])); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_6 = 0; - __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_t_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = 0; + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_6, __pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_16 = ((PyArrayObject *)__pyx_t_4); + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_17 = ((PyArrayObject *)__pyx_t_5); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_support_vectors.rcbuffer->pybuffer); - __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support_vectors.rcbuffer->pybuffer, (PyObject*)__pyx_t_16, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); + __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support_vectors.rcbuffer->pybuffer, (PyObject*)__pyx_t_17, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support_vectors.rcbuffer->pybuffer, (PyObject*)__pyx_v_support_vectors, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { @@ -2361,60 +2594,60 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py } } __pyx_pybuffernd_support_vectors.diminfo[0].strides = __pyx_pybuffernd_support_vectors.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_support_vectors.diminfo[0].shape = __pyx_pybuffernd_support_vectors.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_support_vectors.diminfo[1].strides = __pyx_pybuffernd_support_vectors.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_support_vectors.diminfo[1].shape = __pyx_pybuffernd_support_vectors.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_16 = 0; - __pyx_v_support_vectors = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; + __pyx_t_17 = 0; + __pyx_v_support_vectors = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; - /* "sklearn/svm/libsvm.pyx":190 + /* "sklearn/svm/libsvm.pyx":219 * else: * support_vectors = np.empty((SV_len, X.shape[1]), dtype=np.float64) * copy_SV(support_vectors.data, model, support_vectors.shape) # <<<<<<<<<<<<<< * - * # copy model.nSV + * # TODO: do only in classification */ copy_SV(__pyx_v_support_vectors->data, __pyx_v_model, __pyx_v_support_vectors->dimensions); } - __pyx_L6:; + __pyx_L9:; - /* "sklearn/svm/libsvm.pyx":195 + /* "sklearn/svm/libsvm.pyx":223 * # TODO: do only in classification * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] n_class_SV * n_class_SV = np.empty(n_class, dtype=np.int32) # <<<<<<<<<<<<<< * copy_nSV(n_class_SV.data, model) * */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(__pyx_v_n_class); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_n_class); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_n_class); __Pyx_GIVEREF(__pyx_v_n_class); - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__int32); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_int32); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_17 = ((PyArrayObject *)__pyx_t_6); - { + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, __pyx_t_6); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_18 = ((PyArrayObject *)__pyx_t_3); + { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_n_class_SV.rcbuffer->pybuffer); - __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_n_class_SV.rcbuffer->pybuffer, (PyObject*)__pyx_t_17, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); + __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_n_class_SV.rcbuffer->pybuffer, (PyObject*)__pyx_t_18, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_n_class_SV.rcbuffer->pybuffer, (PyObject*)__pyx_v_n_class_SV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { @@ -2425,334 +2658,278 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py } } __pyx_pybuffernd_n_class_SV.diminfo[0].strides = __pyx_pybuffernd_n_class_SV.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_n_class_SV.diminfo[0].shape = __pyx_pybuffernd_n_class_SV.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_17 = 0; - __pyx_v_n_class_SV = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; + __pyx_t_18 = 0; + __pyx_v_n_class_SV = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; - /* "sklearn/svm/libsvm.pyx":196 + /* "sklearn/svm/libsvm.pyx":224 * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] n_class_SV * n_class_SV = np.empty(n_class, dtype=np.int32) * copy_nSV(n_class_SV.data, model) # <<<<<<<<<<<<<< * - * # copy label + * cdef np.ndarray[np.float64_t, ndim=1, mode='c'] probA */ copy_nSV(__pyx_v_n_class_SV->data, __pyx_v_model); - /* "sklearn/svm/libsvm.pyx":200 - * # copy label - * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] label - * label = np.empty((n_class), dtype=np.int32) # <<<<<<<<<<<<<< - * copy_label(label.data, model) - * - */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_INCREF(__pyx_v_n_class); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_v_n_class); - __Pyx_GIVEREF(__pyx_v_n_class); - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__int32); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_6), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_18 = ((PyArrayObject *)__pyx_t_7); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); - __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_label.rcbuffer->pybuffer, (PyObject*)__pyx_t_18, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_9 < 0)) { - PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_12, __pyx_t_11, __pyx_t_10); - } - } - __pyx_pybuffernd_label.diminfo[0].strides = __pyx_pybuffernd_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_label.diminfo[0].shape = __pyx_pybuffernd_label.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_18 = 0; - __pyx_v_label = ((PyArrayObject *)__pyx_t_7); - __pyx_t_7 = 0; - - /* "sklearn/svm/libsvm.pyx":201 - * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] label - * label = np.empty((n_class), dtype=np.int32) - * copy_label(label.data, model) # <<<<<<<<<<<<<< - * - * # copy probabilities - */ - copy_label(__pyx_v_label->data, __pyx_v_model); - - /* "sklearn/svm/libsvm.pyx":206 + /* "sklearn/svm/libsvm.pyx":228 * cdef np.ndarray[np.float64_t, ndim=1, mode='c'] probA * cdef np.ndarray[np.float64_t, ndim=1, mode='c'] probB * if probability != 0: # <<<<<<<<<<<<<< * if svm_type < 2: # SVC and NuSVC - * probA = np.empty(n_class*(n_class-1)/2, dtype=np.float64) + * probA = np.empty(int(n_class*(n_class-1)/2), dtype=np.float64) */ - __pyx_t_2 = (__pyx_v_probability != 0); + __pyx_t_2 = ((__pyx_v_probability != 0) != 0); if (__pyx_t_2) { - /* "sklearn/svm/libsvm.pyx":207 + /* "sklearn/svm/libsvm.pyx":229 * cdef np.ndarray[np.float64_t, ndim=1, mode='c'] probB * if probability != 0: * if svm_type < 2: # SVC and NuSVC # <<<<<<<<<<<<<< - * probA = np.empty(n_class*(n_class-1)/2, dtype=np.float64) - * probB = np.empty(n_class*(n_class-1)/2, dtype=np.float64) + * probA = np.empty(int(n_class*(n_class-1)/2), dtype=np.float64) + * probB = np.empty(int(n_class*(n_class-1)/2), dtype=np.float64) */ - __pyx_t_2 = (__pyx_v_svm_type < 2); + __pyx_t_2 = ((__pyx_v_svm_type < 2) != 0); if (__pyx_t_2) { - /* "sklearn/svm/libsvm.pyx":208 + /* "sklearn/svm/libsvm.pyx":230 * if probability != 0: * if svm_type < 2: # SVC and NuSVC - * probA = np.empty(n_class*(n_class-1)/2, dtype=np.float64) # <<<<<<<<<<<<<< - * probB = np.empty(n_class*(n_class-1)/2, dtype=np.float64) + * probA = np.empty(int(n_class*(n_class-1)/2), dtype=np.float64) # <<<<<<<<<<<<<< + * probB = np.empty(int(n_class*(n_class-1)/2), dtype=np.float64) * copy_probB(probB.data, model, probB.shape) */ - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyNumber_Subtract(__pyx_v_n_class, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_6 = PyNumber_Multiply(__pyx_v_n_class, __pyx_t_7); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyNumber_Divide(__pyx_t_6, __pyx_int_2); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_v_n_class, __pyx_int_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyNumber_Multiply(__pyx_v_n_class, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__float64); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_5, __pyx_int_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Int(__pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_6), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_19 = ((PyArrayObject *)__pyx_t_3); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_19 = ((PyArrayObject *)__pyx_t_7); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_t_19, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { - PyErr_Fetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); + PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_12); + Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_10, __pyx_t_11, __pyx_t_12); + PyErr_Restore(__pyx_t_12, __pyx_t_11, __pyx_t_10); } } __pyx_pybuffernd_probA.diminfo[0].strides = __pyx_pybuffernd_probA.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probA.diminfo[0].shape = __pyx_pybuffernd_probA.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_19 = 0; - __pyx_v_probA = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; + __pyx_v_probA = ((PyArrayObject *)__pyx_t_7); + __pyx_t_7 = 0; - /* "sklearn/svm/libsvm.pyx":209 + /* "sklearn/svm/libsvm.pyx":231 * if svm_type < 2: # SVC and NuSVC - * probA = np.empty(n_class*(n_class-1)/2, dtype=np.float64) - * probB = np.empty(n_class*(n_class-1)/2, dtype=np.float64) # <<<<<<<<<<<<<< + * probA = np.empty(int(n_class*(n_class-1)/2), dtype=np.float64) + * probB = np.empty(int(n_class*(n_class-1)/2), dtype=np.float64) # <<<<<<<<<<<<<< * copy_probB(probB.data, model, probB.shape) * else: */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_v_n_class, __pyx_int_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyNumber_Subtract(__pyx_v_n_class, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = PyNumber_Multiply(__pyx_v_n_class, __pyx_t_7); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyNumber_Multiply(__pyx_v_n_class, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyNumber_Divide(__pyx_t_3, __pyx_int_2); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_6, __pyx_int_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Int(__pyx_t_7); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_3); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_7, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_6), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_20 = ((PyArrayObject *)__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_20 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_t_20, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { - PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); + PyErr_Fetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); + Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_12); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_12, __pyx_t_11, __pyx_t_10); + PyErr_Restore(__pyx_t_10, __pyx_t_11, __pyx_t_12); } } __pyx_pybuffernd_probB.diminfo[0].strides = __pyx_pybuffernd_probB.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probB.diminfo[0].shape = __pyx_pybuffernd_probB.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_20 = 0; - __pyx_v_probB = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; + __pyx_v_probB = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; - /* "sklearn/svm/libsvm.pyx":210 - * probA = np.empty(n_class*(n_class-1)/2, dtype=np.float64) - * probB = np.empty(n_class*(n_class-1)/2, dtype=np.float64) + /* "sklearn/svm/libsvm.pyx":232 + * probA = np.empty(int(n_class*(n_class-1)/2), dtype=np.float64) + * probB = np.empty(int(n_class*(n_class-1)/2), dtype=np.float64) * copy_probB(probB.data, model, probB.shape) # <<<<<<<<<<<<<< * else: * probA = np.empty(1, dtype=np.float64) */ copy_probB(__pyx_v_probB->data, __pyx_v_model, __pyx_v_probB->dimensions); - goto __pyx_L8; + goto __pyx_L11; } /*else*/ { - /* "sklearn/svm/libsvm.pyx":212 + /* "sklearn/svm/libsvm.pyx":234 * copy_probB(probB.data, model, probB.shape) * else: * probA = np.empty(1, dtype=np.float64) # <<<<<<<<<<<<<< * probB = np.empty(0, dtype=np.float64) * copy_probA(probA.data, model, probA.shape) */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_k_tuple_13), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_tuple__6, __pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_19 = ((PyArrayObject *)__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_19 = ((PyArrayObject *)__pyx_t_5); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_t_19, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { - PyErr_Fetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); + PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_12); + Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_10, __pyx_t_11, __pyx_t_12); + PyErr_Restore(__pyx_t_12, __pyx_t_11, __pyx_t_10); } } __pyx_pybuffernd_probA.diminfo[0].strides = __pyx_pybuffernd_probA.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probA.diminfo[0].shape = __pyx_pybuffernd_probA.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_19 = 0; - __pyx_v_probA = ((PyArrayObject *)__pyx_t_7); - __pyx_t_7 = 0; + __pyx_v_probA = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; - /* "sklearn/svm/libsvm.pyx":213 + /* "sklearn/svm/libsvm.pyx":235 * else: * probA = np.empty(1, dtype=np.float64) * probB = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * copy_probA(probA.data, model, probA.shape) * else: */ - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_k_tuple_14), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_tuple__7, __pyx_t_5); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_20 = ((PyArrayObject *)__pyx_t_6); + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_20 = ((PyArrayObject *)__pyx_t_7); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_t_20, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { - PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); + PyErr_Fetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); + Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_12); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_12, __pyx_t_11, __pyx_t_10); + PyErr_Restore(__pyx_t_10, __pyx_t_11, __pyx_t_12); } } __pyx_pybuffernd_probB.diminfo[0].strides = __pyx_pybuffernd_probB.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probB.diminfo[0].shape = __pyx_pybuffernd_probB.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_20 = 0; - __pyx_v_probB = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; + __pyx_v_probB = ((PyArrayObject *)__pyx_t_7); + __pyx_t_7 = 0; } - __pyx_L8:; + __pyx_L11:; - /* "sklearn/svm/libsvm.pyx":214 + /* "sklearn/svm/libsvm.pyx":236 * probA = np.empty(1, dtype=np.float64) * probB = np.empty(0, dtype=np.float64) * copy_probA(probA.data, model, probA.shape) # <<<<<<<<<<<<<< @@ -2760,172 +2937,189 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py * probA = np.empty(0, dtype=np.float64) */ copy_probA(__pyx_v_probA->data, __pyx_v_model, __pyx_v_probA->dimensions); - goto __pyx_L7; + goto __pyx_L10; } /*else*/ { - /* "sklearn/svm/libsvm.pyx":216 + /* "sklearn/svm/libsvm.pyx":238 * copy_probA(probA.data, model, probA.shape) * else: * probA = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * probB = np.empty(0, dtype=np.float64) * */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__float64); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_float64); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_k_tuple_15), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_tuple__8, __pyx_t_7); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_19 = ((PyArrayObject *)__pyx_t_3); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_t_19, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { - PyErr_Fetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); + PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_12); + Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_10, __pyx_t_11, __pyx_t_12); + PyErr_Restore(__pyx_t_12, __pyx_t_11, __pyx_t_10); } } __pyx_pybuffernd_probA.diminfo[0].strides = __pyx_pybuffernd_probA.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probA.diminfo[0].shape = __pyx_pybuffernd_probA.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_19 = 0; __pyx_v_probA = ((PyArrayObject *)__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/svm/libsvm.pyx":217 + /* "sklearn/svm/libsvm.pyx":239 * else: * probA = np.empty(0, dtype=np.float64) * probB = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * - * # memory deallocation + * svm_free_and_destroy_model(&model) */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_k_tuple_16), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_20 = ((PyArrayObject *)__pyx_t_5); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_tuple__9, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_20 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_t_20, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { - PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); + PyErr_Fetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); + Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_12); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_12, __pyx_t_11, __pyx_t_10); + PyErr_Restore(__pyx_t_10, __pyx_t_11, __pyx_t_12); } } __pyx_pybuffernd_probB.diminfo[0].strides = __pyx_pybuffernd_probB.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probB.diminfo[0].shape = __pyx_pybuffernd_probB.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_20 = 0; - __pyx_v_probB = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; + __pyx_v_probB = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; } - __pyx_L7:; + __pyx_L10:; - /* "sklearn/svm/libsvm.pyx":220 + /* "sklearn/svm/libsvm.pyx":241 + * probB = np.empty(0, dtype=np.float64) * - * # memory deallocation * svm_free_and_destroy_model(&model) # <<<<<<<<<<<<<< * free(problem.x) - * return support, support_vectors, n_class_SV, sv_coef, intercept, label, \ + * */ svm_free_and_destroy_model((&__pyx_v_model)); - /* "sklearn/svm/libsvm.pyx":221 - * # memory deallocation + /* "sklearn/svm/libsvm.pyx":242 + * * svm_free_and_destroy_model(&model) * free(problem.x) # <<<<<<<<<<<<<< - * return support, support_vectors, n_class_SV, sv_coef, intercept, label, \ - * probA, probB + * + * return (support, support_vectors, n_class_SV, sv_coef, intercept, */ free(__pyx_v_problem.x); - /* "sklearn/svm/libsvm.pyx":222 - * svm_free_and_destroy_model(&model) + /* "sklearn/svm/libsvm.pyx":244 * free(problem.x) - * return support, support_vectors, n_class_SV, sv_coef, intercept, label, \ # <<<<<<<<<<<<<< - * probA, probB + * + * return (support, support_vectors, n_class_SV, sv_coef, intercept, # <<<<<<<<<<<<<< + * probA, probB, fit_status) * */ __Pyx_XDECREF(__pyx_r); - /* "sklearn/svm/libsvm.pyx":223 + /* "sklearn/svm/libsvm.pyx":245 + * + * return (support, support_vectors, n_class_SV, sv_coef, intercept, + * probA, probB, fit_status) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_fit_status); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + + /* "sklearn/svm/libsvm.pyx":244 * free(problem.x) - * return support, support_vectors, n_class_SV, sv_coef, intercept, label, \ - * probA, probB # <<<<<<<<<<<<<< * + * return (support, support_vectors, n_class_SV, sv_coef, intercept, # <<<<<<<<<<<<<< + * probA, probB, fit_status) * */ - __pyx_t_5 = PyTuple_New(8); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyTuple_New(8); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(((PyObject *)__pyx_v_support)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_support)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_support)); __Pyx_GIVEREF(((PyObject *)__pyx_v_support)); __Pyx_INCREF(((PyObject *)__pyx_v_support_vectors)); - PyTuple_SET_ITEM(__pyx_t_5, 1, ((PyObject *)__pyx_v_support_vectors)); + PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_v_support_vectors)); __Pyx_GIVEREF(((PyObject *)__pyx_v_support_vectors)); __Pyx_INCREF(((PyObject *)__pyx_v_n_class_SV)); - PyTuple_SET_ITEM(__pyx_t_5, 2, ((PyObject *)__pyx_v_n_class_SV)); + PyTuple_SET_ITEM(__pyx_t_3, 2, ((PyObject *)__pyx_v_n_class_SV)); __Pyx_GIVEREF(((PyObject *)__pyx_v_n_class_SV)); __Pyx_INCREF(((PyObject *)__pyx_v_sv_coef)); - PyTuple_SET_ITEM(__pyx_t_5, 3, ((PyObject *)__pyx_v_sv_coef)); + PyTuple_SET_ITEM(__pyx_t_3, 3, ((PyObject *)__pyx_v_sv_coef)); __Pyx_GIVEREF(((PyObject *)__pyx_v_sv_coef)); __Pyx_INCREF(((PyObject *)__pyx_v_intercept)); - PyTuple_SET_ITEM(__pyx_t_5, 4, ((PyObject *)__pyx_v_intercept)); + PyTuple_SET_ITEM(__pyx_t_3, 4, ((PyObject *)__pyx_v_intercept)); __Pyx_GIVEREF(((PyObject *)__pyx_v_intercept)); - __Pyx_INCREF(((PyObject *)__pyx_v_label)); - PyTuple_SET_ITEM(__pyx_t_5, 5, ((PyObject *)__pyx_v_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_label)); __Pyx_INCREF(((PyObject *)__pyx_v_probA)); - PyTuple_SET_ITEM(__pyx_t_5, 6, ((PyObject *)__pyx_v_probA)); + PyTuple_SET_ITEM(__pyx_t_3, 5, ((PyObject *)__pyx_v_probA)); __Pyx_GIVEREF(((PyObject *)__pyx_v_probA)); __Pyx_INCREF(((PyObject *)__pyx_v_probB)); - PyTuple_SET_ITEM(__pyx_t_5, 7, ((PyObject *)__pyx_v_probB)); + PyTuple_SET_ITEM(__pyx_t_3, 6, ((PyObject *)__pyx_v_probB)); __Pyx_GIVEREF(((PyObject *)__pyx_v_probB)); - __pyx_r = ((PyObject *)__pyx_t_5); - __pyx_t_5 = 0; + PyTuple_SET_ITEM(__pyx_t_3, 7, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/svm/libsvm.pyx":54 + * # Wrapper functions + * + * def fit( # <<<<<<<<<<<<<< + * np.ndarray[np.float64_t, ndim=2, mode='c'] X, + * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); @@ -2939,7 +3133,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_n_class_SV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); @@ -2957,7 +3150,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_n_class_SV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); @@ -2967,6 +3159,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF(__pyx_v_kernel_index); + __Pyx_XDECREF((PyObject *)__pyx_v_class_weight_label); __Pyx_XDECREF(__pyx_v_error_repl); __Pyx_XDECREF(__pyx_v_n_class); __Pyx_XDECREF((PyObject *)__pyx_v_sv_coef); @@ -2974,7 +3167,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py __Pyx_XDECREF((PyObject *)__pyx_v_support); __Pyx_XDECREF((PyObject *)__pyx_v_support_vectors); __Pyx_XDECREF((PyObject *)__pyx_v_n_class_SV); - __Pyx_XDECREF((PyObject *)__pyx_v_label); __Pyx_XDECREF((PyObject *)__pyx_v_probA); __Pyx_XDECREF((PyObject *)__pyx_v_probB); __Pyx_XDECREF((PyObject *)__pyx_v_sample_weight); @@ -2983,60 +3175,205 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_fit(CYTHON_UNUSED PyObject *__py return __pyx_r; } -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_3predict(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_3svm_6libsvm_2predict[] = "\n Predict target values of X given a model (low-level method)\n\n Parameters\n ----------\n X: array-like, dtype=float, size=[n_samples, n_features]\n\n svm_type : {0, 1, 2, 3, 4}\n Type of SVM: C SVC, nu SVC, one class, epsilon SVR, nu SVR\n\n kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'}\n Kernel to use in the model: linear, polynomial, RBF, sigmoid\n or precomputed.\n\n degree : int\n Degree of the polynomial kernel (only relevant if kernel is\n set to polynomial)\n\n gamma : float\n Gamma parameter in RBF kernel (only relevant if kernel is set\n to RBF)\n\n coef0 : float\n Independent parameter in poly/sigmoid kernel.\n\n eps : float\n Stopping criteria.\n\n C : float\n C parameter in C-Support Vector Classification\n\n\n Returns\n -------\n dec_values : array\n predicted values.\n\n\n TODO: probably there's no point in setting some parameters, like\n cache_size or weights.\n "; -static PyMethodDef __pyx_mdef_7sklearn_3svm_6libsvm_3predict = {__Pyx_NAMESTR("predict"), (PyCFunction)__pyx_pw_7sklearn_3svm_6libsvm_3predict, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_3svm_6libsvm_2predict)}; -static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_3predict(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_X = 0; - PyArrayObject *__pyx_v_support = 0; - PyArrayObject *__pyx_v_SV = 0; - PyArrayObject *__pyx_v_nSV = 0; - PyArrayObject *__pyx_v_sv_coef = 0; - PyArrayObject *__pyx_v_intercept = 0; - PyArrayObject *__pyx_v_label = 0; - PyArrayObject *__pyx_v_probA = 0; - PyArrayObject *__pyx_v_probB = 0; - int __pyx_v_svm_type; - PyObject *__pyx_v_kernel = 0; - int __pyx_v_degree; - double __pyx_v_gamma; - double __pyx_v_coef0; - double __pyx_v_tol; +/* "sklearn/svm/libsvm.pyx":248 + * + * + * cdef void set_predict_params( # <<<<<<<<<<<<<< + * svm_parameter *param, int svm_type, kernel, int degree, double gamma, + * double coef0, double cache_size, int probability, int nr_weight, + */ + +static void __pyx_f_7sklearn_3svm_6libsvm_set_predict_params(struct svm_parameter *__pyx_v_param, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_cache_size, int __pyx_v_probability, int __pyx_v_nr_weight, char *__pyx_v_weight_label, char *__pyx_v_weight) { double __pyx_v_C; - double __pyx_v_nu; double __pyx_v_epsilon; - PyArrayObject *__pyx_v_class_weight_label = 0; - PyArrayObject *__pyx_v_class_weight = 0; - CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight = 0; + int __pyx_v_max_iter; + double __pyx_v_nu; int __pyx_v_shrinking; - int __pyx_v_probability; - double __pyx_v_cache_size; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__support,&__pyx_n_s__SV,&__pyx_n_s__nSV,&__pyx_n_s__sv_coef,&__pyx_n_s__intercept,&__pyx_n_s__label,&__pyx_n_s__probA,&__pyx_n_s__probB,&__pyx_n_s__svm_type,&__pyx_n_s__kernel,&__pyx_n_s__degree,&__pyx_n_s__gamma,&__pyx_n_s__coef0,&__pyx_n_s__tol,&__pyx_n_s__C,&__pyx_n_s__nu,&__pyx_n_s__epsilon,&__pyx_n_s__class_weight_label,&__pyx_n_s__class_weight,&__pyx_n_s__sample_weight,&__pyx_n_s__shrinking,&__pyx_n_s__probability,&__pyx_n_s__cache_size,0}; - PyObject *__pyx_r = 0; + double __pyx_v_tol; + int __pyx_v_random_seed; + PyObject *__pyx_v_kernel_index = NULL; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("predict (wrapper)", 0); - __pyx_self = __pyx_self; - { - PyObject* values[24] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - values[7] = (PyObject *)__pyx_k_17; - values[8] = (PyObject *)__pyx_k_18; - values[10] = ((PyObject*)__pyx_n_s__rbf); - values[18] = (PyObject *)__pyx_k_19; - values[19] = (PyObject *)__pyx_k_20; - values[20] = (PyObject *)__pyx_k_21; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 24: values[23] = PyTuple_GET_ITEM(__pyx_args, 23); - case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); - case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); - case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); - case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); - case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); - case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); - case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("set_predict_params", 0); + + /* "sklearn/svm/libsvm.pyx":255 + * + * # training-time only parameters + * cdef double C = .0 # <<<<<<<<<<<<<< + * cdef double epsilon = .1 + * cdef int max_iter = 0 + */ + __pyx_v_C = .0; + + /* "sklearn/svm/libsvm.pyx":256 + * # training-time only parameters + * cdef double C = .0 + * cdef double epsilon = .1 # <<<<<<<<<<<<<< + * cdef int max_iter = 0 + * cdef double nu = .5 + */ + __pyx_v_epsilon = .1; + + /* "sklearn/svm/libsvm.pyx":257 + * cdef double C = .0 + * cdef double epsilon = .1 + * cdef int max_iter = 0 # <<<<<<<<<<<<<< + * cdef double nu = .5 + * cdef int shrinking = 0 + */ + __pyx_v_max_iter = 0; + + /* "sklearn/svm/libsvm.pyx":258 + * cdef double epsilon = .1 + * cdef int max_iter = 0 + * cdef double nu = .5 # <<<<<<<<<<<<<< + * cdef int shrinking = 0 + * cdef double tol = .1 + */ + __pyx_v_nu = .5; + + /* "sklearn/svm/libsvm.pyx":259 + * cdef int max_iter = 0 + * cdef double nu = .5 + * cdef int shrinking = 0 # <<<<<<<<<<<<<< + * cdef double tol = .1 + * cdef int random_seed = -1 + */ + __pyx_v_shrinking = 0; + + /* "sklearn/svm/libsvm.pyx":260 + * cdef double nu = .5 + * cdef int shrinking = 0 + * cdef double tol = .1 # <<<<<<<<<<<<<< + * cdef int random_seed = -1 + * + */ + __pyx_v_tol = .1; + + /* "sklearn/svm/libsvm.pyx":261 + * cdef int shrinking = 0 + * cdef double tol = .1 + * cdef int random_seed = -1 # <<<<<<<<<<<<<< + * + * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) + */ + __pyx_v_random_seed = -1; + + /* "sklearn/svm/libsvm.pyx":263 + * cdef int random_seed = -1 + * + * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) # <<<<<<<<<<<<<< + * + * set_parameter(param, svm_type, kernel_index, degree, gamma, coef0, nu, + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_LIBSVM_KERNEL_TYPES); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_kernel); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_kernel); + __Pyx_GIVEREF(__pyx_v_kernel); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_1, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_kernel_index = __pyx_t_3; + __pyx_t_3 = 0; + + /* "sklearn/svm/libsvm.pyx":265 + * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) + * + * set_parameter(param, svm_type, kernel_index, degree, gamma, coef0, nu, # <<<<<<<<<<<<<< + * cache_size, C, tol, epsilon, shrinking, probability, + * nr_weight, weight_label, weight, max_iter, random_seed) + */ + __pyx_t_4 = __Pyx_PyInt_As_int(__pyx_v_kernel_index); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 265; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/svm/libsvm.pyx":267 + * set_parameter(param, svm_type, kernel_index, degree, gamma, coef0, nu, + * cache_size, C, tol, epsilon, shrinking, probability, + * nr_weight, weight_label, weight, max_iter, random_seed) # <<<<<<<<<<<<<< + * + * + */ + set_parameter(__pyx_v_param, __pyx_v_svm_type, __pyx_t_4, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_C, __pyx_v_tol, __pyx_v_epsilon, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_nr_weight, __pyx_v_weight_label, __pyx_v_weight, __pyx_v_max_iter, __pyx_v_random_seed); + + /* "sklearn/svm/libsvm.pyx":248 + * + * + * cdef void set_predict_params( # <<<<<<<<<<<<<< + * svm_parameter *param, int svm_type, kernel, int degree, double gamma, + * double coef0, double cache_size, int probability, int nr_weight, + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.svm.libsvm.set_predict_params", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_kernel_index); + __Pyx_RefNannyFinishContext(); +} + +/* "sklearn/svm/libsvm.pyx":270 + * + * + * def predict(np.ndarray[np.float64_t, ndim=2, mode='c'] X, # <<<<<<<<<<<<<< + * np.ndarray[np.int32_t, ndim=1, mode='c'] support, + * np.ndarray[np.float64_t, ndim=2, mode='c'] SV, + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_3predict(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_3svm_6libsvm_2predict[] = "\n Predict target values of X given a model (low-level method)\n\n Parameters\n ----------\n X: array-like, dtype=float, size=[n_samples, n_features]\n svm_type : {0, 1, 2, 3, 4}\n Type of SVM: C SVC, nu SVC, one class, epsilon SVR, nu SVR\n kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'}\n Type of kernel.\n degree : int\n Degree of the polynomial kernel.\n gamma : float\n Gamma parameter in RBF kernel.\n coef0 : float\n Independent parameter in poly/sigmoid kernel.\n\n Returns\n -------\n dec_values : array\n predicted values.\n "; +static PyMethodDef __pyx_mdef_7sklearn_3svm_6libsvm_3predict = {__Pyx_NAMESTR("predict"), (PyCFunction)__pyx_pw_7sklearn_3svm_6libsvm_3predict, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_3svm_6libsvm_2predict)}; +static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_3predict(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_X = 0; + PyArrayObject *__pyx_v_support = 0; + PyArrayObject *__pyx_v_SV = 0; + PyArrayObject *__pyx_v_nSV = 0; + PyArrayObject *__pyx_v_sv_coef = 0; + PyArrayObject *__pyx_v_intercept = 0; + PyArrayObject *__pyx_v_probA = 0; + PyArrayObject *__pyx_v_probB = 0; + int __pyx_v_svm_type; + PyObject *__pyx_v_kernel = 0; + int __pyx_v_degree; + double __pyx_v_gamma; + double __pyx_v_coef0; + PyArrayObject *__pyx_v_class_weight = 0; + CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight = 0; + double __pyx_v_cache_size; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("predict (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_support,&__pyx_n_s_SV,&__pyx_n_s_nSV,&__pyx_n_s_sv_coef,&__pyx_n_s_intercept,&__pyx_n_s_probA,&__pyx_n_s_probB,&__pyx_n_s_svm_type,&__pyx_n_s_kernel,&__pyx_n_s_degree,&__pyx_n_s_gamma,&__pyx_n_s_coef0,&__pyx_n_s_class_weight,&__pyx_n_s_sample_weight,&__pyx_n_s_cache_size,0}; + PyObject* values[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + values[6] = (PyObject *)__pyx_k__10; + values[7] = (PyObject *)__pyx_k__11; + values[9] = ((PyObject *)__pyx_n_s_rbf); + values[13] = (PyObject *)__pyx_k__12; + values[14] = (PyObject *)__pyx_k__13; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); case 15: values[14] = PyTuple_GET_ITEM(__pyx_args, 14); case 14: values[13] = PyTuple_GET_ITEM(__pyx_args, 13); @@ -3059,212 +3396,89 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_3predict(PyObject *__pyx_self, P kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__support); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_support)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict", 0, 7, 24, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict", 0, 6, 16, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_SV)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict", 0, 7, 24, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict", 0, 6, 16, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nSV); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_nSV)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict", 0, 7, 24, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict", 0, 6, 16, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sv_coef); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sv_coef)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict", 0, 7, 24, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict", 0, 6, 16, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__intercept); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_intercept)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict", 0, 7, 24, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict", 0, 6, 16, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__label); - if (likely(values[6])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("predict", 0, 7, 24, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_probA); + if (value) { values[6] = value; kw_args--; } } case 7: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probA); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_probB); if (value) { values[7] = value; kw_args--; } } case 8: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probB); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_svm_type); if (value) { values[8] = value; kw_args--; } } case 9: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__svm_type); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kernel); if (value) { values[9] = value; kw_args--; } } case 10: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kernel); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_degree); if (value) { values[10] = value; kw_args--; } } case 11: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__degree); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_gamma); if (value) { values[11] = value; kw_args--; } } case 12: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__gamma); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_coef0); if (value) { values[12] = value; kw_args--; } } case 13: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coef0); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight); if (value) { values[13] = value; kw_args--; } } case 14: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__tol); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sample_weight); if (value) { values[14] = value; kw_args--; } } case 15: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_cache_size); if (value) { values[15] = value; kw_args--; } } - case 16: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nu); - if (value) { values[16] = value; kw_args--; } - } - case 17: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__epsilon); - if (value) { values[17] = value; kw_args--; } - } - case 18: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight_label); - if (value) { values[18] = value; kw_args--; } - } - case 19: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight); - if (value) { values[19] = value; kw_args--; } - } - case 20: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sample_weight); - if (value) { values[20] = value; kw_args--; } - } - case 21: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shrinking); - if (value) { values[21] = value; kw_args--; } - } - case 22: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probability); - if (value) { values[22] = value; kw_args--; } - } - case 23: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__cache_size); - if (value) { values[23] = value; kw_args--; } - } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "predict") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - if (values[9]) { - } else { - __pyx_v_svm_type = ((int)0); - } - if (values[11]) { - } else { - __pyx_v_degree = ((int)3); - } - if (values[12]) { - } else { - - /* "sklearn/svm/libsvm.pyx":236 - * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, # <<<<<<<<<<<<<< - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - */ - __pyx_v_gamma = ((double)0.1); - } - if (values[13]) { - } else { - __pyx_v_coef0 = ((double)0.); - } - if (values[14]) { - } else { - __pyx_v_tol = ((double)1e-3); - } - if (values[15]) { - } else { - - /* "sklearn/svm/libsvm.pyx":237 - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - * double C=1., double nu=0.5, double epsilon=0.1, # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), - */ - __pyx_v_C = ((double)1.); - } - if (values[16]) { - } else { - __pyx_v_nu = ((double)0.5); - } - if (values[17]) { - } else { - __pyx_v_epsilon = ((double)0.1); - } - if (values[21]) { - } else { - __pyx_v_shrinking = ((int)0); - } - if (values[22]) { - } else { - __pyx_v_probability = ((int)0); - } - if (values[23]) { - } else { - - /* "sklearn/svm/libsvm.pyx":245 - * sample_weight=np.empty(0), - * int shrinking=0, int probability=0, - * double cache_size=100.): # <<<<<<<<<<<<<< - * """ - * Predict target values of X given a model (low-level method) - */ - __pyx_v_cache_size = ((double)100.); + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "predict") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { - case 24: values[23] = PyTuple_GET_ITEM(__pyx_args, 23); - case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); - case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); - case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); - case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); - case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); - case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); - case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); case 15: values[14] = PyTuple_GET_ITEM(__pyx_args, 14); case 14: values[13] = PyTuple_GET_ITEM(__pyx_args, 13); @@ -3275,7 +3489,7 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_3predict(PyObject *__pyx_self, P case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); @@ -3291,115 +3505,58 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_3predict(PyObject *__pyx_self, P __pyx_v_nSV = ((PyArrayObject *)values[3]); __pyx_v_sv_coef = ((PyArrayObject *)values[4]); __pyx_v_intercept = ((PyArrayObject *)values[5]); - __pyx_v_label = ((PyArrayObject *)values[6]); - __pyx_v_probA = ((PyArrayObject *)values[7]); - __pyx_v_probB = ((PyArrayObject *)values[8]); - if (values[9]) { - __pyx_v_svm_type = __Pyx_PyInt_AsInt(values[9]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_probA = ((PyArrayObject *)values[6]); + __pyx_v_probB = ((PyArrayObject *)values[7]); + if (values[8]) { + __pyx_v_svm_type = __Pyx_PyInt_As_int(values[8]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_svm_type = ((int)0); } - __pyx_v_kernel = ((PyObject*)values[10]); - if (values[11]) { - __pyx_v_degree = __Pyx_PyInt_AsInt(values[11]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_kernel = values[9]; + if (values[10]) { + __pyx_v_degree = __Pyx_PyInt_As_int(values[10]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_degree = ((int)3); } - if (values[12]) { - __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[11]) { + __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/svm/libsvm.pyx":236 - * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, # <<<<<<<<<<<<<< - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - */ __pyx_v_gamma = ((double)0.1); } - if (values[13]) { - __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[13]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[12]) { + __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_coef0 = ((double)0.); } - if (values[14]) { - __pyx_v_tol = __pyx_PyFloat_AsDouble(values[14]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_tol = ((double)1e-3); - } + __pyx_v_class_weight = ((PyArrayObject *)values[13]); + __pyx_v_sample_weight = ((PyArrayObject *)values[14]); if (values[15]) { - __pyx_v_C = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 237; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - - /* "sklearn/svm/libsvm.pyx":237 - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - * double C=1., double nu=0.5, double epsilon=0.1, # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), - */ - __pyx_v_C = ((double)1.); - } - if (values[16]) { - __pyx_v_nu = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 237; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_nu = ((double)0.5); - } - if (values[17]) { - __pyx_v_epsilon = __pyx_PyFloat_AsDouble(values[17]); if (unlikely((__pyx_v_epsilon == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 237; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - __pyx_v_epsilon = ((double)0.1); - } - __pyx_v_class_weight_label = ((PyArrayObject *)values[18]); - __pyx_v_class_weight = ((PyArrayObject *)values[19]); - __pyx_v_sample_weight = ((PyArrayObject *)values[20]); - if (values[21]) { - __pyx_v_shrinking = __Pyx_PyInt_AsInt(values[21]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_shrinking = ((int)0); - } - if (values[22]) { - __pyx_v_probability = __Pyx_PyInt_AsInt(values[22]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_probability = ((int)0); - } - if (values[23]) { - __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[23]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - - /* "sklearn/svm/libsvm.pyx":245 - * sample_weight=np.empty(0), - * int shrinking=0, int probability=0, - * double cache_size=100.): # <<<<<<<<<<<<<< - * """ - * Predict target values of X given a model (low-level method) - */ __pyx_v_cache_size = ((double)100.); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("predict", 0, 7, 24, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict", 0, 6, 16, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.svm.libsvm.predict", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_support), __pyx_ptype_5numpy_ndarray, 1, "support", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV), __pyx_ptype_5numpy_ndarray, 1, "SV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nSV), __pyx_ptype_5numpy_ndarray, 1, "nSV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 229; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sv_coef), __pyx_ptype_5numpy_ndarray, 1, "sv_coef", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_intercept), __pyx_ptype_5numpy_ndarray, 1, "intercept", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_label), __pyx_ptype_5numpy_ndarray, 1, "label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probA), __pyx_ptype_5numpy_ndarray, 1, "probA", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probB), __pyx_ptype_5numpy_ndarray, 1, "probB", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kernel), (&PyString_Type), 1, "kernel", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight_label), __pyx_ptype_5numpy_ndarray, 1, "class_weight_label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_3svm_6libsvm_2predict(__pyx_self, __pyx_v_X, __pyx_v_support, __pyx_v_SV, __pyx_v_nSV, __pyx_v_sv_coef, __pyx_v_intercept, __pyx_v_label, __pyx_v_probA, __pyx_v_probB, __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_tol, __pyx_v_C, __pyx_v_nu, __pyx_v_epsilon, __pyx_v_class_weight_label, __pyx_v_class_weight, __pyx_v_sample_weight, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_cache_size); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_support), __pyx_ptype_5numpy_ndarray, 1, "support", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV), __pyx_ptype_5numpy_ndarray, 1, "SV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nSV), __pyx_ptype_5numpy_ndarray, 1, "nSV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sv_coef), __pyx_ptype_5numpy_ndarray, 1, "sv_coef", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 274; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_intercept), __pyx_ptype_5numpy_ndarray, 1, "intercept", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probA), __pyx_ptype_5numpy_ndarray, 1, "probA", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probB), __pyx_ptype_5numpy_ndarray, 1, "probB", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_3svm_6libsvm_2predict(__pyx_self, __pyx_v_X, __pyx_v_support, __pyx_v_SV, __pyx_v_nSV, __pyx_v_sv_coef, __pyx_v_intercept, __pyx_v_probA, __pyx_v_probB, __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_class_weight, __pyx_v_sample_weight, __pyx_v_cache_size); + + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -3408,19 +3565,12 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_3predict(PyObject *__pyx_self, P return __pyx_r; } -/* "sklearn/svm/libsvm.pyx":226 - * - * - * def predict(np.ndarray[np.float64_t, ndim=2, mode='c'] X, # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t, ndim=1, mode='c'] support, - * np.ndarray[np.float64_t, ndim=2, mode='c'] SV, - */ - -static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_label, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight_label, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size) { +static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, double __pyx_v_cache_size) { PyArrayObject *__pyx_v_dec_values = 0; struct svm_parameter __pyx_v_param; struct svm_model *__pyx_v_model; - PyObject *__pyx_v_kernel_index = NULL; + int __pyx_v_rv; + PyArrayObject *__pyx_v_class_weight_label = 0; __Pyx_LocalBuf_ND __pyx_pybuffernd_SV; __Pyx_Buffer __pyx_pybuffer_SV; __Pyx_LocalBuf_ND __pyx_pybuffernd_X; @@ -3433,8 +3583,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject __Pyx_Buffer __pyx_pybuffer_dec_values; __Pyx_LocalBuf_ND __pyx_pybuffernd_intercept; __Pyx_Buffer __pyx_pybuffer_intercept; - __Pyx_LocalBuf_ND __pyx_pybuffernd_label; - __Pyx_Buffer __pyx_pybuffer_label; __Pyx_LocalBuf_ND __pyx_pybuffernd_nSV; __Pyx_Buffer __pyx_pybuffer_nSV; __Pyx_LocalBuf_ND __pyx_pybuffernd_probA; @@ -3452,12 +3600,20 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyArrayObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + PyArrayObject *__pyx_t_7 = NULL; + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_t_12; + int __pyx_t_13; + char const *__pyx_t_14; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + PyObject *__pyx_t_17 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; @@ -3466,6 +3622,10 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject __pyx_pybuffer_dec_values.refcount = 0; __pyx_pybuffernd_dec_values.data = NULL; __pyx_pybuffernd_dec_values.rcbuffer = &__pyx_pybuffer_dec_values; + __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight_label.refcount = 0; + __pyx_pybuffernd_class_weight_label.data = NULL; + __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_X.pybuffer.buf = NULL; __pyx_pybuffer_X.refcount = 0; __pyx_pybuffernd_X.data = NULL; @@ -3490,10 +3650,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject __pyx_pybuffer_intercept.refcount = 0; __pyx_pybuffernd_intercept.data = NULL; __pyx_pybuffernd_intercept.rcbuffer = &__pyx_pybuffer_intercept; - __pyx_pybuffer_label.pybuffer.buf = NULL; - __pyx_pybuffer_label.refcount = 0; - __pyx_pybuffernd_label.data = NULL; - __pyx_pybuffernd_label.rcbuffer = &__pyx_pybuffer_label; __pyx_pybuffer_probA.pybuffer.buf = NULL; __pyx_pybuffer_probA.refcount = 0; __pyx_pybuffernd_probA.data = NULL; @@ -3502,10 +3658,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject __pyx_pybuffer_probB.refcount = 0; __pyx_pybuffernd_probB.data = NULL; __pyx_pybuffernd_probB.rcbuffer = &__pyx_pybuffer_probB; - __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; - __pyx_pybuffer_class_weight_label.refcount = 0; - __pyx_pybuffernd_class_weight_label.data = NULL; - __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_class_weight.pybuffer.buf = NULL; __pyx_pybuffer_class_weight.refcount = 0; __pyx_pybuffernd_class_weight.data = NULL; @@ -3516,199 +3668,293 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject __pyx_pybuffernd_sample_weight.rcbuffer = &__pyx_pybuffer_sample_weight; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support.rcbuffer->pybuffer, (PyObject*)__pyx_v_support, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support.rcbuffer->pybuffer, (PyObject*)__pyx_v_support, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_support.diminfo[0].strides = __pyx_pybuffernd_support.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_support.diminfo[0].shape = __pyx_pybuffernd_support.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_SV.diminfo[0].strides = __pyx_pybuffernd_SV.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_SV.diminfo[0].shape = __pyx_pybuffernd_SV.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_SV.diminfo[1].strides = __pyx_pybuffernd_SV.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_SV.diminfo[1].shape = __pyx_pybuffernd_SV.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer, (PyObject*)__pyx_v_nSV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer, (PyObject*)__pyx_v_nSV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_nSV.diminfo[0].strides = __pyx_pybuffernd_nSV.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_nSV.diminfo[0].shape = __pyx_pybuffernd_nSV.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_v_sv_coef, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_v_sv_coef, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_sv_coef.diminfo[0].strides = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sv_coef.diminfo[0].shape = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_sv_coef.diminfo[1].strides = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_sv_coef.diminfo[1].shape = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_v_intercept, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_v_intercept, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_intercept.diminfo[0].strides = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_intercept.diminfo[0].shape = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_label.diminfo[0].strides = __pyx_pybuffernd_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_label.diminfo[0].shape = __pyx_pybuffernd_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_probA.diminfo[0].strides = __pyx_pybuffernd_probA.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probA.diminfo[0].shape = __pyx_pybuffernd_probA.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_probB.diminfo[0].strides = __pyx_pybuffernd_probB.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probB.diminfo[0].shape = __pyx_pybuffernd_probB.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_class_weight.diminfo[0].strides = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight.diminfo[0].shape = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_sample_weight.diminfo[0].strides = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weight.diminfo[0].shape = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.shape[0]; - /* "sklearn/svm/libsvm.pyx":291 - * cdef svm_model *model + /* "sklearn/svm/libsvm.pyx":313 * - * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) # <<<<<<<<<<<<<< - * set_parameter(¶m, svm_type, kernel_index, degree, gamma, coef0, - * nu, cache_size, C, tol, epsilon, shrinking, + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) # <<<<<<<<<<<<<< + * + * set_predict_params(¶m, svm_type, kernel, degree, gamma, coef0, */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__LIBSVM_KERNEL_TYPES); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_arange); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_class_weight->dimensions[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)__pyx_v_kernel)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_kernel)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_kernel)); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_int32); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_v_kernel_index = __pyx_t_3; - __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_class_weight_label = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __pyx_v_class_weight_label = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; - /* "sklearn/svm/libsvm.pyx":292 + /* "sklearn/svm/libsvm.pyx":315 + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) * - * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) - * set_parameter(¶m, svm_type, kernel_index, degree, gamma, coef0, # <<<<<<<<<<<<<< - * nu, cache_size, C, tol, epsilon, shrinking, - * probability, class_weight.shape[0], + * set_predict_params(¶m, svm_type, kernel, degree, gamma, coef0, # <<<<<<<<<<<<<< + * cache_size, 0, class_weight.shape[0], + * class_weight_label.data, class_weight.data) */ - __pyx_t_4 = __Pyx_PyInt_AsInt(__pyx_v_kernel_index); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 292; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_f_7sklearn_3svm_6libsvm_set_predict_params((&__pyx_v_param), __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_cache_size, 0, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 315; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/svm/libsvm.pyx":295 - * nu, cache_size, C, tol, epsilon, shrinking, - * probability, class_weight.shape[0], - * class_weight_label.data, class_weight.data) # <<<<<<<<<<<<<< - * - * model = set_model(¶m, nSV.shape[0], SV.data, SV.shape, + /* "sklearn/svm/libsvm.pyx":318 + * cache_size, 0, class_weight.shape[0], + * class_weight_label.data, class_weight.data) + * model = set_model(¶m, nSV.shape[0], SV.data, SV.shape, # <<<<<<<<<<<<<< + * support.data, support.shape, sv_coef.strides, + * sv_coef.data, intercept.data, nSV.data, probA.data, probB.data) */ - set_parameter((&__pyx_v_param), __pyx_v_svm_type, __pyx_t_4, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_C, __pyx_v_tol, __pyx_v_epsilon, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data); + __pyx_v_model = set_model((&__pyx_v_param), ((int)(__pyx_v_nSV->dimensions[0])), __pyx_v_SV->data, __pyx_v_SV->dimensions, __pyx_v_support->data, __pyx_v_support->dimensions, __pyx_v_sv_coef->strides, __pyx_v_sv_coef->data, __pyx_v_intercept->data, __pyx_v_nSV->data, __pyx_v_probA->data, __pyx_v_probB->data); - /* "sklearn/svm/libsvm.pyx":300 - * support.data, support.shape, sv_coef.strides, - * sv_coef.data, intercept.data, nSV.data, - * label.data, probA.data, probB.data) # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm.pyx":323 * * #TODO: use check_model + * try: # <<<<<<<<<<<<<< + * dec_values = np.empty(X.shape[0]) + * with nogil: */ - __pyx_v_model = set_model((&__pyx_v_param), ((int)(__pyx_v_nSV->dimensions[0])), __pyx_v_SV->data, __pyx_v_SV->dimensions, __pyx_v_support->data, __pyx_v_support->dimensions, __pyx_v_sv_coef->strides, __pyx_v_sv_coef->data, __pyx_v_intercept->data, __pyx_v_nSV->data, __pyx_v_label->data, __pyx_v_probA->data, __pyx_v_probB->data); + /*try:*/ { - /* "sklearn/svm/libsvm.pyx":303 - * + /* "sklearn/svm/libsvm.pyx":324 * #TODO: use check_model - * dec_values = np.empty(X.shape[0]) # <<<<<<<<<<<<<< - * if copy_predict(X.data, model, X.shape, dec_values.data) < 0: - * raise MemoryError("We've run out of of memory") + * try: + * dec_values = np.empty(X.shape[0]) # <<<<<<<<<<<<<< + * with nogil: + * rv = copy_predict(X.data, model, X.shape, dec_values.data) */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 303; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 303; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 303; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 303; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 303; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 303; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = ((PyArrayObject *)__pyx_t_3); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); - __pyx_t_4 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_4 < 0)) { - PyErr_Fetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_dec_values, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_6); Py_XDECREF(__pyx_t_7); Py_XDECREF(__pyx_t_8); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_6, __pyx_t_7, __pyx_t_8); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_5); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); + __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_8 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_dec_values, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } } + __pyx_pybuffernd_dec_values.diminfo[0].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_dec_values.diminfo[0].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L4_error;} } - __pyx_pybuffernd_dec_values.diminfo[0].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_dec_values.diminfo[0].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 303; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_5 = 0; - __pyx_v_dec_values = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; + __pyx_t_7 = 0; + __pyx_v_dec_values = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; - /* "sklearn/svm/libsvm.pyx":304 - * #TODO: use check_model - * dec_values = np.empty(X.shape[0]) - * if copy_predict(X.data, model, X.shape, dec_values.data) < 0: # <<<<<<<<<<<<<< - * raise MemoryError("We've run out of of memory") - * free_model(model) - */ - __pyx_t_9 = (copy_predict(__pyx_v_X->data, __pyx_v_model, __pyx_v_X->dimensions, __pyx_v_dec_values->data) < 0); - if (__pyx_t_9) { - - /* "sklearn/svm/libsvm.pyx":305 - * dec_values = np.empty(X.shape[0]) - * if copy_predict(X.data, model, X.shape, dec_values.data) < 0: - * raise MemoryError("We've run out of of memory") # <<<<<<<<<<<<<< - * free_model(model) - * return dec_values + /* "sklearn/svm/libsvm.pyx":325 + * try: + * dec_values = np.empty(X.shape[0]) + * with nogil: # <<<<<<<<<<<<<< + * rv = copy_predict(X.data, model, X.shape, dec_values.data) + * if rv < 0: */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_23), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/svm/libsvm.pyx":326 + * dec_values = np.empty(X.shape[0]) + * with nogil: + * rv = copy_predict(X.data, model, X.shape, dec_values.data) # <<<<<<<<<<<<<< + * if rv < 0: + * raise MemoryError("We've run out of memory") + */ + __pyx_v_rv = copy_predict(__pyx_v_X->data, __pyx_v_model, __pyx_v_X->dimensions, __pyx_v_dec_values->data); + } + + /* "sklearn/svm/libsvm.pyx":325 + * try: + * dec_values = np.empty(X.shape[0]) + * with nogil: # <<<<<<<<<<<<<< + * rv = copy_predict(X.data, model, X.shape, dec_values.data) + * if rv < 0: + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L8; + } + __pyx_L8:; + } + } + + /* "sklearn/svm/libsvm.pyx":327 + * with nogil: + * rv = copy_predict(X.data, model, X.shape, dec_values.data) + * if rv < 0: # <<<<<<<<<<<<<< + * raise MemoryError("We've run out of memory") + * finally: + */ + __pyx_t_12 = ((__pyx_v_rv < 0) != 0); + if (__pyx_t_12) { + + /* "sklearn/svm/libsvm.pyx":328 + * rv = copy_predict(X.data, model, X.shape, dec_values.data) + * if rv < 0: + * raise MemoryError("We've run out of memory") # <<<<<<<<<<<<<< + * finally: + * free_model(model) + */ + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__14, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + } } - __pyx_L3:; - /* "sklearn/svm/libsvm.pyx":306 - * if copy_predict(X.data, model, X.shape, dec_values.data) < 0: - * raise MemoryError("We've run out of of memory") - * free_model(model) # <<<<<<<<<<<<<< - * return dec_values + /* "sklearn/svm/libsvm.pyx":330 + * raise MemoryError("We've run out of memory") + * finally: + * free_model(model) # <<<<<<<<<<<<<< * + * return dec_values */ - free_model(__pyx_v_model); + /*finally:*/ { + /*normal exit:*/{ + free_model(__pyx_v_model); + goto __pyx_L5; + } + /*exception exit:*/{ + __pyx_L4_error:; + __pyx_t_11 = 0; __pyx_t_10 = 0; __pyx_t_9 = 0; __pyx_t_15 = 0; __pyx_t_16 = 0; __pyx_t_17 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_15, &__pyx_t_16, &__pyx_t_17); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9) < 0)) __Pyx_ErrFetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_11); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_15); + __Pyx_XGOTREF(__pyx_t_16); + __Pyx_XGOTREF(__pyx_t_17); + __pyx_t_8 = __pyx_lineno; __pyx_t_13 = __pyx_clineno; __pyx_t_14 = __pyx_filename; + { + free_model(__pyx_v_model); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_15); + __Pyx_XGIVEREF(__pyx_t_16); + __Pyx_XGIVEREF(__pyx_t_17); + __Pyx_ExceptionReset(__pyx_t_15, __pyx_t_16, __pyx_t_17); + } + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_ErrRestore(__pyx_t_11, __pyx_t_10, __pyx_t_9); + __pyx_t_11 = 0; __pyx_t_10 = 0; __pyx_t_9 = 0; __pyx_t_15 = 0; __pyx_t_16 = 0; __pyx_t_17 = 0; + __pyx_lineno = __pyx_t_8; __pyx_clineno = __pyx_t_13; __pyx_filename = __pyx_t_14; + goto __pyx_L1_error; + } + __pyx_L5:; + } - /* "sklearn/svm/libsvm.pyx":307 - * raise MemoryError("We've run out of of memory") - * free_model(model) + /* "sklearn/svm/libsvm.pyx":332 + * free_model(model) + * * return dec_values # <<<<<<<<<<<<<< * * @@ -3718,12 +3964,21 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject __pyx_r = ((PyObject *)__pyx_v_dec_values); goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/svm/libsvm.pyx":270 + * + * + * def predict(np.ndarray[np.float64_t, ndim=2, mode='c'] X, # <<<<<<<<<<<<<< + * np.ndarray[np.int32_t, ndim=1, mode='c'] support, + * np.ndarray[np.float64_t, ndim=2, mode='c'] SV, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_SV.rcbuffer->pybuffer); @@ -3732,7 +3987,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); @@ -3750,7 +4004,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); @@ -3759,15 +4012,23 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_2predict(CYTHON_UNUSED PyObject __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_dec_values); - __Pyx_XDECREF(__pyx_v_kernel_index); + __Pyx_XDECREF((PyObject *)__pyx_v_class_weight_label); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } +/* "sklearn/svm/libsvm.pyx":335 + * + * + * def predict_proba( # <<<<<<<<<<<<<< + * np.ndarray[np.float64_t, ndim=2, mode='c'] X, + * np.ndarray[np.int32_t, ndim=1, mode='c'] support, + */ + /* Python wrapper */ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_5predict_proba(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_3svm_6libsvm_4predict_proba[] = "\n Predict probabilities\n\n svm_model stores all parameters needed to predict a given value.\n\n For speed, all real work is done at the C level in function\n copy_predict (libsvm_helper.c).\n\n We have to reconstruct model and parameters to make sure we stay\n in sync with the python object.\n\n See sklearn.svm.predict for a complete list of parameters.\n\n Parameters\n ----------\n X: array-like, dtype=float\n Y: array\n target vector\n\n kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'}\n\n\n Returns\n -------\n dec_values : array\n predicted values.\n "; +static char __pyx_doc_7sklearn_3svm_6libsvm_4predict_proba[] = "\n Predict probabilities\n\n svm_model stores all parameters needed to predict a given value.\n\n For speed, all real work is done at the C level in function\n copy_predict (libsvm_helper.c).\n\n We have to reconstruct model and parameters to make sure we stay\n in sync with the python object.\n\n See sklearn.svm.predict for a complete list of parameters.\n\n Parameters\n ----------\n X: array-like, dtype=float\n kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'}\n\n Returns\n -------\n dec_values : array\n predicted values.\n "; static PyMethodDef __pyx_mdef_7sklearn_3svm_6libsvm_5predict_proba = {__Pyx_NAMESTR("predict_proba"), (PyCFunction)__pyx_pw_7sklearn_3svm_6libsvm_5predict_proba, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_3svm_6libsvm_4predict_proba)}; static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_5predict_proba(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_X = 0; @@ -3776,7 +4037,6 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_5predict_proba(PyObject *__pyx_s PyArrayObject *__pyx_v_nSV = 0; PyArrayObject *__pyx_v_sv_coef = 0; PyArrayObject *__pyx_v_intercept = 0; - PyArrayObject *__pyx_v_label = 0; PyArrayObject *__pyx_v_probA = 0; PyArrayObject *__pyx_v_probB = 0; int __pyx_v_svm_type; @@ -3784,41 +4044,27 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_5predict_proba(PyObject *__pyx_s int __pyx_v_degree; double __pyx_v_gamma; double __pyx_v_coef0; - double __pyx_v_tol; - double __pyx_v_C; - double __pyx_v_nu; - double __pyx_v_epsilon; - PyArrayObject *__pyx_v_class_weight_label = 0; PyArrayObject *__pyx_v_class_weight = 0; CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight = 0; - int __pyx_v_shrinking; - int __pyx_v_probability; double __pyx_v_cache_size; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__support,&__pyx_n_s__SV,&__pyx_n_s__nSV,&__pyx_n_s__sv_coef,&__pyx_n_s__intercept,&__pyx_n_s__label,&__pyx_n_s__probA,&__pyx_n_s__probB,&__pyx_n_s__svm_type,&__pyx_n_s__kernel,&__pyx_n_s__degree,&__pyx_n_s__gamma,&__pyx_n_s__coef0,&__pyx_n_s__tol,&__pyx_n_s__C,&__pyx_n_s__nu,&__pyx_n_s__epsilon,&__pyx_n_s__class_weight_label,&__pyx_n_s__class_weight,&__pyx_n_s__sample_weight,&__pyx_n_s__shrinking,&__pyx_n_s__probability,&__pyx_n_s__cache_size,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("predict_proba (wrapper)", 0); - __pyx_self = __pyx_self; { - PyObject* values[24] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - values[7] = (PyObject *)__pyx_k_24; - values[8] = (PyObject *)__pyx_k_25; - values[10] = ((PyObject*)__pyx_n_s__rbf); - values[18] = (PyObject *)__pyx_k_26; - values[19] = (PyObject *)__pyx_k_27; - values[20] = (PyObject *)__pyx_k_28; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_support,&__pyx_n_s_SV,&__pyx_n_s_nSV,&__pyx_n_s_sv_coef,&__pyx_n_s_intercept,&__pyx_n_s_probA,&__pyx_n_s_probB,&__pyx_n_s_svm_type,&__pyx_n_s_kernel,&__pyx_n_s_degree,&__pyx_n_s_gamma,&__pyx_n_s_coef0,&__pyx_n_s_class_weight,&__pyx_n_s_sample_weight,&__pyx_n_s_cache_size,0}; + PyObject* values[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + values[6] = (PyObject *)__pyx_k__15; + values[7] = (PyObject *)__pyx_k__16; + values[9] = ((PyObject*)__pyx_n_s_rbf); + values[13] = (PyObject *)__pyx_k__17; + values[14] = (PyObject *)__pyx_k__18; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { - case 24: values[23] = PyTuple_GET_ITEM(__pyx_args, 23); - case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); - case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); - case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); - case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); - case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); - case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); - case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); case 15: values[14] = PyTuple_GET_ITEM(__pyx_args, 14); case 14: values[13] = PyTuple_GET_ITEM(__pyx_args, 13); @@ -3841,212 +4087,89 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_5predict_proba(PyObject *__pyx_s kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__support); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_support)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 7, 24, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 6, 16, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_SV)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 7, 24, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 6, 16, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nSV); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_nSV)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 7, 24, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 6, 16, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sv_coef); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sv_coef)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 7, 24, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 6, 16, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__intercept); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_intercept)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 7, 24, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 6, 16, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__label); - if (likely(values[6])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 7, 24, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_probA); + if (value) { values[6] = value; kw_args--; } } case 7: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probA); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_probB); if (value) { values[7] = value; kw_args--; } } case 8: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probB); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_svm_type); if (value) { values[8] = value; kw_args--; } } - case 9: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__svm_type); - if (value) { values[9] = value; kw_args--; } - } - case 10: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kernel); - if (value) { values[10] = value; kw_args--; } - } - case 11: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__degree); - if (value) { values[11] = value; kw_args--; } - } - case 12: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__gamma); - if (value) { values[12] = value; kw_args--; } - } - case 13: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coef0); - if (value) { values[13] = value; kw_args--; } - } - case 14: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__tol); - if (value) { values[14] = value; kw_args--; } - } - case 15: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C); - if (value) { values[15] = value; kw_args--; } - } - case 16: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nu); - if (value) { values[16] = value; kw_args--; } - } - case 17: + case 9: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__epsilon); - if (value) { values[17] = value; kw_args--; } + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kernel); + if (value) { values[9] = value; kw_args--; } } - case 18: + case 10: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight_label); - if (value) { values[18] = value; kw_args--; } + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_degree); + if (value) { values[10] = value; kw_args--; } } - case 19: + case 11: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight); - if (value) { values[19] = value; kw_args--; } + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_gamma); + if (value) { values[11] = value; kw_args--; } } - case 20: + case 12: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sample_weight); - if (value) { values[20] = value; kw_args--; } + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_coef0); + if (value) { values[12] = value; kw_args--; } } - case 21: + case 13: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shrinking); - if (value) { values[21] = value; kw_args--; } + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight); + if (value) { values[13] = value; kw_args--; } } - case 22: + case 14: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probability); - if (value) { values[22] = value; kw_args--; } + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sample_weight); + if (value) { values[14] = value; kw_args--; } } - case 23: + case 15: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__cache_size); - if (value) { values[23] = value; kw_args--; } + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_cache_size); + if (value) { values[15] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "predict_proba") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - if (values[9]) { - } else { - __pyx_v_svm_type = ((int)0); - } - if (values[11]) { - } else { - __pyx_v_degree = ((int)3); - } - if (values[12]) { - } else { - - /* "sklearn/svm/libsvm.pyx":322 - * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, # <<<<<<<<<<<<<< - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - */ - __pyx_v_gamma = ((double)0.1); - } - if (values[13]) { - } else { - __pyx_v_coef0 = ((double)0.); - } - if (values[14]) { - } else { - __pyx_v_tol = ((double)1e-3); - } - if (values[15]) { - } else { - - /* "sklearn/svm/libsvm.pyx":323 - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - * double C=1., double nu=0.5, double epsilon=0.1, # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), - */ - __pyx_v_C = ((double)1.); - } - if (values[16]) { - } else { - __pyx_v_nu = ((double)0.5); - } - if (values[17]) { - } else { - __pyx_v_epsilon = ((double)0.1); - } - if (values[21]) { - } else { - __pyx_v_shrinking = ((int)0); - } - if (values[22]) { - } else { - __pyx_v_probability = ((int)0); - } - if (values[23]) { - } else { - - /* "sklearn/svm/libsvm.pyx":331 - * sample_weight=np.empty(0), - * int shrinking=0, int probability=0, - * double cache_size=100.): # <<<<<<<<<<<<<< - * """ - * Predict probabilities - */ - __pyx_v_cache_size = ((double)100.); + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "predict_proba") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { - case 24: values[23] = PyTuple_GET_ITEM(__pyx_args, 23); - case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); - case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); - case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); - case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); - case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); - case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); - case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); case 15: values[14] = PyTuple_GET_ITEM(__pyx_args, 14); case 14: values[13] = PyTuple_GET_ITEM(__pyx_args, 13); @@ -4057,7 +4180,7 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_5predict_proba(PyObject *__pyx_s case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); @@ -4073,115 +4196,59 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_5predict_proba(PyObject *__pyx_s __pyx_v_nSV = ((PyArrayObject *)values[3]); __pyx_v_sv_coef = ((PyArrayObject *)values[4]); __pyx_v_intercept = ((PyArrayObject *)values[5]); - __pyx_v_label = ((PyArrayObject *)values[6]); - __pyx_v_probA = ((PyArrayObject *)values[7]); - __pyx_v_probB = ((PyArrayObject *)values[8]); - if (values[9]) { - __pyx_v_svm_type = __Pyx_PyInt_AsInt(values[9]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_probA = ((PyArrayObject *)values[6]); + __pyx_v_probB = ((PyArrayObject *)values[7]); + if (values[8]) { + __pyx_v_svm_type = __Pyx_PyInt_As_int(values[8]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 344; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_svm_type = ((int)0); } - __pyx_v_kernel = ((PyObject*)values[10]); - if (values[11]) { - __pyx_v_degree = __Pyx_PyInt_AsInt(values[11]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_kernel = ((PyObject*)values[9]); + if (values[10]) { + __pyx_v_degree = __Pyx_PyInt_As_int(values[10]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 344; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_degree = ((int)3); } - if (values[12]) { - __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[11]) { + __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/svm/libsvm.pyx":322 - * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, # <<<<<<<<<<<<<< - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - */ __pyx_v_gamma = ((double)0.1); } - if (values[13]) { - __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[13]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[12]) { + __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_coef0 = ((double)0.); } - if (values[14]) { - __pyx_v_tol = __pyx_PyFloat_AsDouble(values[14]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_tol = ((double)1e-3); - } + __pyx_v_class_weight = ((PyArrayObject *)values[13]); + __pyx_v_sample_weight = ((PyArrayObject *)values[14]); if (values[15]) { - __pyx_v_C = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - - /* "sklearn/svm/libsvm.pyx":323 - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - * double C=1., double nu=0.5, double epsilon=0.1, # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), - */ - __pyx_v_C = ((double)1.); - } - if (values[16]) { - __pyx_v_nu = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_nu = ((double)0.5); - } - if (values[17]) { - __pyx_v_epsilon = __pyx_PyFloat_AsDouble(values[17]); if (unlikely((__pyx_v_epsilon == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_epsilon = ((double)0.1); - } - __pyx_v_class_weight_label = ((PyArrayObject *)values[18]); - __pyx_v_class_weight = ((PyArrayObject *)values[19]); - __pyx_v_sample_weight = ((PyArrayObject *)values[20]); - if (values[21]) { - __pyx_v_shrinking = __Pyx_PyInt_AsInt(values[21]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 330; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - __pyx_v_shrinking = ((int)0); - } - if (values[22]) { - __pyx_v_probability = __Pyx_PyInt_AsInt(values[22]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 330; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_probability = ((int)0); - } - if (values[23]) { - __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[23]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - - /* "sklearn/svm/libsvm.pyx":331 - * sample_weight=np.empty(0), - * int shrinking=0, int probability=0, - * double cache_size=100.): # <<<<<<<<<<<<<< - * """ - * Predict probabilities - */ __pyx_v_cache_size = ((double)100.); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 7, 24, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("predict_proba", 0, 6, 16, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.svm.libsvm.predict_proba", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_support), __pyx_ptype_5numpy_ndarray, 1, "support", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV), __pyx_ptype_5numpy_ndarray, 1, "SV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nSV), __pyx_ptype_5numpy_ndarray, 1, "nSV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 315; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sv_coef), __pyx_ptype_5numpy_ndarray, 1, "sv_coef", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 316; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_intercept), __pyx_ptype_5numpy_ndarray, 1, "intercept", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_label), __pyx_ptype_5numpy_ndarray, 1, "label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 318; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probA), __pyx_ptype_5numpy_ndarray, 1, "probA", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probB), __pyx_ptype_5numpy_ndarray, 1, "probB", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kernel), (&PyString_Type), 1, "kernel", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight_label), __pyx_ptype_5numpy_ndarray, 1, "class_weight_label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(__pyx_self, __pyx_v_X, __pyx_v_support, __pyx_v_SV, __pyx_v_nSV, __pyx_v_sv_coef, __pyx_v_intercept, __pyx_v_label, __pyx_v_probA, __pyx_v_probB, __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_tol, __pyx_v_C, __pyx_v_nu, __pyx_v_epsilon, __pyx_v_class_weight_label, __pyx_v_class_weight, __pyx_v_sample_weight, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_cache_size); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 336; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_support), __pyx_ptype_5numpy_ndarray, 1, "support", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV), __pyx_ptype_5numpy_ndarray, 1, "SV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 338; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nSV), __pyx_ptype_5numpy_ndarray, 1, "nSV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 339; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sv_coef), __pyx_ptype_5numpy_ndarray, 1, "sv_coef", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_intercept), __pyx_ptype_5numpy_ndarray, 1, "intercept", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probA), __pyx_ptype_5numpy_ndarray, 1, "probA", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 342; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probB), __pyx_ptype_5numpy_ndarray, 1, "probB", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kernel), (&PyString_Type), 1, "kernel", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 344; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 346; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(__pyx_self, __pyx_v_X, __pyx_v_support, __pyx_v_SV, __pyx_v_nSV, __pyx_v_sv_coef, __pyx_v_intercept, __pyx_v_probA, __pyx_v_probB, __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_class_weight, __pyx_v_sample_weight, __pyx_v_cache_size); + + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -4190,19 +4257,12 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_5predict_proba(PyObject *__pyx_s return __pyx_r; } -/* "sklearn/svm/libsvm.pyx":311 - * - * - * def predict_proba( # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=2, mode='c'] X, - * np.ndarray[np.int32_t, ndim=1, mode='c'] support, - */ - -static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_label, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight_label, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size) { +static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, double __pyx_v_cache_size) { PyArrayObject *__pyx_v_dec_values = 0; struct svm_parameter __pyx_v_param; struct svm_model *__pyx_v_model; - PyObject *__pyx_v_kernel_index = NULL; + PyArrayObject *__pyx_v_class_weight_label = 0; + int __pyx_v_rv; npy_intp __pyx_v_n_class; __Pyx_LocalBuf_ND __pyx_pybuffernd_SV; __Pyx_Buffer __pyx_pybuffer_SV; @@ -4216,8 +4276,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyO __Pyx_Buffer __pyx_pybuffer_dec_values; __Pyx_LocalBuf_ND __pyx_pybuffernd_intercept; __Pyx_Buffer __pyx_pybuffer_intercept; - __Pyx_LocalBuf_ND __pyx_pybuffernd_label; - __Pyx_Buffer __pyx_pybuffer_label; __Pyx_LocalBuf_ND __pyx_pybuffernd_nSV; __Pyx_Buffer __pyx_pybuffer_nSV; __Pyx_LocalBuf_ND __pyx_pybuffernd_probA; @@ -4235,14 +4293,20 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyO PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; + PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; + PyArrayObject *__pyx_t_6 = NULL; PyArrayObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; + int __pyx_t_8; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; - int __pyx_t_11; + PyObject *__pyx_t_11 = NULL; + int __pyx_t_12; + int __pyx_t_13; + char const *__pyx_t_14; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + PyObject *__pyx_t_17 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; @@ -4251,6 +4315,10 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyO __pyx_pybuffer_dec_values.refcount = 0; __pyx_pybuffernd_dec_values.data = NULL; __pyx_pybuffernd_dec_values.rcbuffer = &__pyx_pybuffer_dec_values; + __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight_label.refcount = 0; + __pyx_pybuffernd_class_weight_label.data = NULL; + __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_X.pybuffer.buf = NULL; __pyx_pybuffer_X.refcount = 0; __pyx_pybuffernd_X.data = NULL; @@ -4275,10 +4343,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyO __pyx_pybuffer_intercept.refcount = 0; __pyx_pybuffernd_intercept.data = NULL; __pyx_pybuffernd_intercept.rcbuffer = &__pyx_pybuffer_intercept; - __pyx_pybuffer_label.pybuffer.buf = NULL; - __pyx_pybuffer_label.refcount = 0; - __pyx_pybuffernd_label.data = NULL; - __pyx_pybuffernd_label.rcbuffer = &__pyx_pybuffer_label; __pyx_pybuffer_probA.pybuffer.buf = NULL; __pyx_pybuffer_probA.refcount = 0; __pyx_pybuffernd_probA.data = NULL; @@ -4287,10 +4351,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyO __pyx_pybuffer_probB.refcount = 0; __pyx_pybuffernd_probB.data = NULL; __pyx_pybuffernd_probB.rcbuffer = &__pyx_pybuffer_probB; - __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; - __pyx_pybuffer_class_weight_label.refcount = 0; - __pyx_pybuffernd_class_weight_label.data = NULL; - __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_class_weight.pybuffer.buf = NULL; __pyx_pybuffer_class_weight.refcount = 0; __pyx_pybuffernd_class_weight.data = NULL; @@ -4301,228 +4361,322 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyO __pyx_pybuffernd_sample_weight.rcbuffer = &__pyx_pybuffer_sample_weight; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support.rcbuffer->pybuffer, (PyObject*)__pyx_v_support, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support.rcbuffer->pybuffer, (PyObject*)__pyx_v_support, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_support.diminfo[0].strides = __pyx_pybuffernd_support.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_support.diminfo[0].shape = __pyx_pybuffernd_support.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_SV.diminfo[0].strides = __pyx_pybuffernd_SV.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_SV.diminfo[0].shape = __pyx_pybuffernd_SV.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_SV.diminfo[1].strides = __pyx_pybuffernd_SV.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_SV.diminfo[1].shape = __pyx_pybuffernd_SV.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer, (PyObject*)__pyx_v_nSV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer, (PyObject*)__pyx_v_nSV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_nSV.diminfo[0].strides = __pyx_pybuffernd_nSV.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_nSV.diminfo[0].shape = __pyx_pybuffernd_nSV.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_v_sv_coef, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_v_sv_coef, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_sv_coef.diminfo[0].strides = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sv_coef.diminfo[0].shape = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_sv_coef.diminfo[1].strides = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_sv_coef.diminfo[1].shape = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_v_intercept, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_v_intercept, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_intercept.diminfo[0].strides = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_intercept.diminfo[0].shape = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_label.diminfo[0].strides = __pyx_pybuffernd_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_label.diminfo[0].shape = __pyx_pybuffernd_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_probA.diminfo[0].strides = __pyx_pybuffernd_probA.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probA.diminfo[0].shape = __pyx_pybuffernd_probA.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_probB.diminfo[0].strides = __pyx_pybuffernd_probB.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probB.diminfo[0].shape = __pyx_pybuffernd_probB.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_class_weight.diminfo[0].strides = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight.diminfo[0].shape = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_sample_weight.diminfo[0].strides = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weight.diminfo[0].shape = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.shape[0]; - /* "sklearn/svm/libsvm.pyx":363 + /* "sklearn/svm/libsvm.pyx":378 * cdef svm_model *model + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) # <<<<<<<<<<<<<< + * cdef int rv * - * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) # <<<<<<<<<<<<<< - * set_parameter(¶m, svm_type, kernel_index, degree, gamma, - * coef0, nu, cache_size, C, tol, epsilon, shrinking, */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__LIBSVM_KERNEL_TYPES); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_arange); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_class_weight->dimensions[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)__pyx_v_kernel)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_kernel)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_kernel)); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_int32); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_v_kernel_index = __pyx_t_3; - __pyx_t_3 = 0; - - /* "sklearn/svm/libsvm.pyx":364 - * - * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) - * set_parameter(¶m, svm_type, kernel_index, degree, gamma, # <<<<<<<<<<<<<< - * coef0, nu, cache_size, C, tol, epsilon, shrinking, - * probability, class_weight.shape[0], class_weight_label.data, - */ - __pyx_t_4 = __Pyx_PyInt_AsInt(__pyx_v_kernel_index); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 364; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_class_weight_label = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __pyx_v_class_weight_label = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; - /* "sklearn/svm/libsvm.pyx":367 - * coef0, nu, cache_size, C, tol, epsilon, shrinking, - * probability, class_weight.shape[0], class_weight_label.data, - * class_weight.data) # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm.pyx":381 + * cdef int rv * - * model = set_model(¶m, nSV.shape[0], SV.data, SV.shape, + * set_predict_params(¶m, svm_type, kernel, degree, gamma, coef0, # <<<<<<<<<<<<<< + * cache_size, 1, class_weight.shape[0], + * class_weight_label.data, class_weight.data) */ - set_parameter((&__pyx_v_param), __pyx_v_svm_type, __pyx_t_4, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_C, __pyx_v_tol, __pyx_v_epsilon, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data); + __pyx_f_7sklearn_3svm_6libsvm_set_predict_params((&__pyx_v_param), __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_cache_size, 1, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/svm/libsvm.pyx":372 + /* "sklearn/svm/libsvm.pyx":384 + * cache_size, 1, class_weight.shape[0], + * class_weight_label.data, class_weight.data) + * model = set_model(¶m, nSV.shape[0], SV.data, SV.shape, # <<<<<<<<<<<<<< * support.data, support.shape, sv_coef.strides, * sv_coef.data, intercept.data, nSV.data, - * label.data, probA.data, probB.data) # <<<<<<<<<<<<<< - * - * cdef np.npy_intp n_class = get_nr(model) */ - __pyx_v_model = set_model((&__pyx_v_param), ((int)(__pyx_v_nSV->dimensions[0])), __pyx_v_SV->data, __pyx_v_SV->dimensions, __pyx_v_support->data, __pyx_v_support->dimensions, __pyx_v_sv_coef->strides, __pyx_v_sv_coef->data, __pyx_v_intercept->data, __pyx_v_nSV->data, __pyx_v_label->data, __pyx_v_probA->data, __pyx_v_probB->data); + __pyx_v_model = set_model((&__pyx_v_param), ((int)(__pyx_v_nSV->dimensions[0])), __pyx_v_SV->data, __pyx_v_SV->dimensions, __pyx_v_support->data, __pyx_v_support->dimensions, __pyx_v_sv_coef->strides, __pyx_v_sv_coef->data, __pyx_v_intercept->data, __pyx_v_nSV->data, __pyx_v_probA->data, __pyx_v_probB->data); - /* "sklearn/svm/libsvm.pyx":374 - * label.data, probA.data, probB.data) + /* "sklearn/svm/libsvm.pyx":389 + * probA.data, probB.data) * * cdef np.npy_intp n_class = get_nr(model) # <<<<<<<<<<<<<< - * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) - * if copy_predict_proba(X.data, model, X.shape, dec_values.data) < 0: + * try: + * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) */ __pyx_v_n_class = get_nr(__pyx_v_model); - /* "sklearn/svm/libsvm.pyx":375 + /* "sklearn/svm/libsvm.pyx":390 * * cdef np.npy_intp n_class = get_nr(model) - * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) # <<<<<<<<<<<<<< - * if copy_predict_proba(X.data, model, X.shape, dec_values.data) < 0: - * raise MemoryError("We've run out of of memory") + * try: # <<<<<<<<<<<<<< + * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) + * with nogil: */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_n_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_3 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = ((PyArrayObject *)__pyx_t_6); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); - __pyx_t_4 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_4 < 0)) { - PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_dec_values, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); + /*try:*/ { + + /* "sklearn/svm/libsvm.pyx":391 + * cdef np.npy_intp n_class = get_nr(model) + * try: + * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) # <<<<<<<<<<<<<< + * with nogil: + * rv = copy_predict_proba(X.data, model, X.shape, dec_values.data) + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_class); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); + __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_8 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_dec_values, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } } + __pyx_pybuffernd_dec_values.diminfo[0].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_dec_values.diminfo[0].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_dec_values.diminfo[1].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_dec_values.diminfo[1].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[1]; + if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} } - __pyx_pybuffernd_dec_values.diminfo[0].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_dec_values.diminfo[0].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_dec_values.diminfo[1].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_dec_values.diminfo[1].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_7 = 0; - __pyx_v_dec_values = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_v_dec_values = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; - /* "sklearn/svm/libsvm.pyx":376 - * cdef np.npy_intp n_class = get_nr(model) - * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) - * if copy_predict_proba(X.data, model, X.shape, dec_values.data) < 0: # <<<<<<<<<<<<<< - * raise MemoryError("We've run out of of memory") - * # free model and param - */ - __pyx_t_11 = (copy_predict_proba(__pyx_v_X->data, __pyx_v_model, __pyx_v_X->dimensions, __pyx_v_dec_values->data) < 0); - if (__pyx_t_11) { - - /* "sklearn/svm/libsvm.pyx":377 - * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) - * if copy_predict_proba(X.data, model, X.shape, dec_values.data) < 0: - * raise MemoryError("We've run out of of memory") # <<<<<<<<<<<<<< - * # free model and param - * free_model(model) - */ - __pyx_t_6 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_29), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_Raise(__pyx_t_6, 0, 0, 0); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; + /* "sklearn/svm/libsvm.pyx":392 + * try: + * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) + * with nogil: # <<<<<<<<<<<<<< + * rv = copy_predict_proba(X.data, model, X.shape, dec_values.data) + * if rv < 0: + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/svm/libsvm.pyx":393 + * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) + * with nogil: + * rv = copy_predict_proba(X.data, model, X.shape, dec_values.data) # <<<<<<<<<<<<<< + * if rv < 0: + * raise MemoryError("We've run out of memory") + */ + __pyx_v_rv = copy_predict_proba(__pyx_v_X->data, __pyx_v_model, __pyx_v_X->dimensions, __pyx_v_dec_values->data); + } + + /* "sklearn/svm/libsvm.pyx":392 + * try: + * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) + * with nogil: # <<<<<<<<<<<<<< + * rv = copy_predict_proba(X.data, model, X.shape, dec_values.data) + * if rv < 0: + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L8; + } + __pyx_L8:; + } + } + + /* "sklearn/svm/libsvm.pyx":394 + * with nogil: + * rv = copy_predict_proba(X.data, model, X.shape, dec_values.data) + * if rv < 0: # <<<<<<<<<<<<<< + * raise MemoryError("We've run out of memory") + * finally: + */ + __pyx_t_12 = ((__pyx_v_rv < 0) != 0); + if (__pyx_t_12) { + + /* "sklearn/svm/libsvm.pyx":395 + * rv = copy_predict_proba(X.data, model, X.shape, dec_values.data) + * if rv < 0: + * raise MemoryError("We've run out of memory") # <<<<<<<<<<<<<< + * finally: + * free_model(model) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + } } - __pyx_L3:; - /* "sklearn/svm/libsvm.pyx":379 - * raise MemoryError("We've run out of of memory") - * # free model and param - * free_model(model) # <<<<<<<<<<<<<< - * return dec_values + /* "sklearn/svm/libsvm.pyx":397 + * raise MemoryError("We've run out of memory") + * finally: + * free_model(model) # <<<<<<<<<<<<<< * + * return dec_values */ - free_model(__pyx_v_model); + /*finally:*/ { + /*normal exit:*/{ + free_model(__pyx_v_model); + goto __pyx_L5; + } + /*exception exit:*/{ + __pyx_L4_error:; + __pyx_t_11 = 0; __pyx_t_10 = 0; __pyx_t_9 = 0; __pyx_t_15 = 0; __pyx_t_16 = 0; __pyx_t_17 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_15, &__pyx_t_16, &__pyx_t_17); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9) < 0)) __Pyx_ErrFetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_11); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_15); + __Pyx_XGOTREF(__pyx_t_16); + __Pyx_XGOTREF(__pyx_t_17); + __pyx_t_8 = __pyx_lineno; __pyx_t_13 = __pyx_clineno; __pyx_t_14 = __pyx_filename; + { + free_model(__pyx_v_model); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_15); + __Pyx_XGIVEREF(__pyx_t_16); + __Pyx_XGIVEREF(__pyx_t_17); + __Pyx_ExceptionReset(__pyx_t_15, __pyx_t_16, __pyx_t_17); + } + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_ErrRestore(__pyx_t_11, __pyx_t_10, __pyx_t_9); + __pyx_t_11 = 0; __pyx_t_10 = 0; __pyx_t_9 = 0; __pyx_t_15 = 0; __pyx_t_16 = 0; __pyx_t_17 = 0; + __pyx_lineno = __pyx_t_8; __pyx_clineno = __pyx_t_13; __pyx_filename = __pyx_t_14; + goto __pyx_L1_error; + } + __pyx_L5:; + } - /* "sklearn/svm/libsvm.pyx":380 - * # free model and param - * free_model(model) + /* "sklearn/svm/libsvm.pyx":399 + * free_model(model) + * * return dec_values # <<<<<<<<<<<<<< * * @@ -4532,14 +4686,21 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyO __pyx_r = ((PyObject *)__pyx_v_dec_values); goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/svm/libsvm.pyx":335 + * + * + * def predict_proba( # <<<<<<<<<<<<<< + * np.ndarray[np.float64_t, ndim=2, mode='c'] X, + * np.ndarray[np.int32_t, ndim=1, mode='c'] support, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_SV.rcbuffer->pybuffer); @@ -4548,7 +4709,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyO __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); @@ -4566,7 +4726,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyO __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); @@ -4575,12 +4734,20 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_4predict_proba(CYTHON_UNUSED PyO __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_dec_values); - __Pyx_XDECREF(__pyx_v_kernel_index); + __Pyx_XDECREF((PyObject *)__pyx_v_class_weight_label); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } +/* "sklearn/svm/libsvm.pyx":402 + * + * + * def decision_function( # <<<<<<<<<<<<<< + * np.ndarray[np.float64_t, ndim=2, mode='c'] X, + * np.ndarray[np.int32_t, ndim=1, mode='c'] support, + */ + /* Python wrapper */ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_7decision_function(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_7sklearn_3svm_6libsvm_6decision_function[] = "\n Predict margin (libsvm name for this is predict_values)\n\n We have to reconstruct model and parameters to make sure we stay\n in sync with the python object.\n "; @@ -4592,7 +4759,6 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_7decision_function(PyObject *__p PyArrayObject *__pyx_v_nSV = 0; PyArrayObject *__pyx_v_sv_coef = 0; PyArrayObject *__pyx_v_intercept = 0; - PyArrayObject *__pyx_v_label = 0; PyArrayObject *__pyx_v_probA = 0; PyArrayObject *__pyx_v_probB = 0; int __pyx_v_svm_type; @@ -4600,41 +4766,27 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_7decision_function(PyObject *__p int __pyx_v_degree; double __pyx_v_gamma; double __pyx_v_coef0; - double __pyx_v_tol; - double __pyx_v_C; - double __pyx_v_nu; - double __pyx_v_epsilon; - PyArrayObject *__pyx_v_class_weight_label = 0; PyArrayObject *__pyx_v_class_weight = 0; CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight = 0; - int __pyx_v_shrinking; - int __pyx_v_probability; double __pyx_v_cache_size; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__support,&__pyx_n_s__SV,&__pyx_n_s__nSV,&__pyx_n_s__sv_coef,&__pyx_n_s__intercept,&__pyx_n_s__label,&__pyx_n_s__probA,&__pyx_n_s__probB,&__pyx_n_s__svm_type,&__pyx_n_s__kernel,&__pyx_n_s__degree,&__pyx_n_s__gamma,&__pyx_n_s__coef0,&__pyx_n_s__tol,&__pyx_n_s__C,&__pyx_n_s__nu,&__pyx_n_s__epsilon,&__pyx_n_s__class_weight_label,&__pyx_n_s__class_weight,&__pyx_n_s__sample_weight,&__pyx_n_s__shrinking,&__pyx_n_s__probability,&__pyx_n_s__cache_size,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("decision_function (wrapper)", 0); - __pyx_self = __pyx_self; { - PyObject* values[24] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - values[7] = (PyObject *)__pyx_k_30; - values[8] = (PyObject *)__pyx_k_31; - values[10] = ((PyObject*)__pyx_n_s__rbf); - values[18] = (PyObject *)__pyx_k_32; - values[19] = (PyObject *)__pyx_k_33; - values[20] = (PyObject *)__pyx_k_34; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_support,&__pyx_n_s_SV,&__pyx_n_s_nSV,&__pyx_n_s_sv_coef,&__pyx_n_s_intercept,&__pyx_n_s_probA,&__pyx_n_s_probB,&__pyx_n_s_svm_type,&__pyx_n_s_kernel,&__pyx_n_s_degree,&__pyx_n_s_gamma,&__pyx_n_s_coef0,&__pyx_n_s_class_weight,&__pyx_n_s_sample_weight,&__pyx_n_s_cache_size,0}; + PyObject* values[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + values[6] = (PyObject *)__pyx_k__20; + values[7] = (PyObject *)__pyx_k__21; + values[9] = ((PyObject *)__pyx_n_s_rbf); + values[13] = (PyObject *)__pyx_k__22; + values[14] = (PyObject *)__pyx_k__23; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { - case 24: values[23] = PyTuple_GET_ITEM(__pyx_args, 23); - case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); - case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); - case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); - case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); - case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); - case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); - case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); case 15: values[14] = PyTuple_GET_ITEM(__pyx_args, 14); case 14: values[13] = PyTuple_GET_ITEM(__pyx_args, 13); @@ -4657,212 +4809,89 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_7decision_function(PyObject *__p kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__support); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_support)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("decision_function", 0, 7, 24, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("decision_function", 0, 6, 16, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_SV)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("decision_function", 0, 7, 24, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("decision_function", 0, 6, 16, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nSV); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_nSV)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("decision_function", 0, 7, 24, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("decision_function", 0, 6, 16, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sv_coef); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sv_coef)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("decision_function", 0, 7, 24, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("decision_function", 0, 6, 16, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__intercept); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_intercept)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("decision_function", 0, 7, 24, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("decision_function", 0, 6, 16, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__label); - if (likely(values[6])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("decision_function", 0, 7, 24, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_probA); + if (value) { values[6] = value; kw_args--; } } case 7: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probA); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_probB); if (value) { values[7] = value; kw_args--; } } case 8: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probB); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_svm_type); if (value) { values[8] = value; kw_args--; } } case 9: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__svm_type); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kernel); if (value) { values[9] = value; kw_args--; } } case 10: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kernel); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_degree); if (value) { values[10] = value; kw_args--; } } case 11: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__degree); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_gamma); if (value) { values[11] = value; kw_args--; } } case 12: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__gamma); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_coef0); if (value) { values[12] = value; kw_args--; } } case 13: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coef0); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight); if (value) { values[13] = value; kw_args--; } } case 14: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__tol); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sample_weight); if (value) { values[14] = value; kw_args--; } } case 15: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_cache_size); if (value) { values[15] = value; kw_args--; } } - case 16: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nu); - if (value) { values[16] = value; kw_args--; } - } - case 17: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__epsilon); - if (value) { values[17] = value; kw_args--; } - } - case 18: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight_label); - if (value) { values[18] = value; kw_args--; } - } - case 19: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight); - if (value) { values[19] = value; kw_args--; } - } - case 20: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sample_weight); - if (value) { values[20] = value; kw_args--; } - } - case 21: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shrinking); - if (value) { values[21] = value; kw_args--; } - } - case 22: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probability); - if (value) { values[22] = value; kw_args--; } - } - case 23: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__cache_size); - if (value) { values[23] = value; kw_args--; } - } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "decision_function") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - if (values[9]) { - } else { - __pyx_v_svm_type = ((int)0); - } - if (values[11]) { - } else { - __pyx_v_degree = ((int)3); - } - if (values[12]) { - } else { - - /* "sklearn/svm/libsvm.pyx":394 - * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, # <<<<<<<<<<<<<< - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - */ - __pyx_v_gamma = ((double)0.1); - } - if (values[13]) { - } else { - __pyx_v_coef0 = ((double)0.); - } - if (values[14]) { - } else { - __pyx_v_tol = ((double)1e-3); - } - if (values[15]) { - } else { - - /* "sklearn/svm/libsvm.pyx":395 - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - * double C=1., double nu=0.5, double epsilon=0.1, # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), - */ - __pyx_v_C = ((double)1.); - } - if (values[16]) { - } else { - __pyx_v_nu = ((double)0.5); - } - if (values[17]) { - } else { - __pyx_v_epsilon = ((double)0.1); - } - if (values[21]) { - } else { - __pyx_v_shrinking = ((int)0); - } - if (values[22]) { - } else { - __pyx_v_probability = ((int)0); - } - if (values[23]) { - } else { - - /* "sklearn/svm/libsvm.pyx":403 - * sample_weight=np.empty(0), - * int shrinking=0, int probability=0, - * double cache_size=100.): # <<<<<<<<<<<<<< - * """ - * Predict margin (libsvm name for this is predict_values) - */ - __pyx_v_cache_size = ((double)100.); + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "decision_function") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { - case 24: values[23] = PyTuple_GET_ITEM(__pyx_args, 23); - case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); - case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); - case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); - case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); - case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); - case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); - case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); case 15: values[14] = PyTuple_GET_ITEM(__pyx_args, 14); case 14: values[13] = PyTuple_GET_ITEM(__pyx_args, 13); @@ -4873,7 +4902,7 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_7decision_function(PyObject *__p case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); @@ -4889,115 +4918,58 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_7decision_function(PyObject *__p __pyx_v_nSV = ((PyArrayObject *)values[3]); __pyx_v_sv_coef = ((PyArrayObject *)values[4]); __pyx_v_intercept = ((PyArrayObject *)values[5]); - __pyx_v_label = ((PyArrayObject *)values[6]); - __pyx_v_probA = ((PyArrayObject *)values[7]); - __pyx_v_probB = ((PyArrayObject *)values[8]); - if (values[9]) { - __pyx_v_svm_type = __Pyx_PyInt_AsInt(values[9]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_probA = ((PyArrayObject *)values[6]); + __pyx_v_probB = ((PyArrayObject *)values[7]); + if (values[8]) { + __pyx_v_svm_type = __Pyx_PyInt_As_int(values[8]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_svm_type = ((int)0); } - __pyx_v_kernel = ((PyObject*)values[10]); - if (values[11]) { - __pyx_v_degree = __Pyx_PyInt_AsInt(values[11]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_kernel = values[9]; + if (values[10]) { + __pyx_v_degree = __Pyx_PyInt_As_int(values[10]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_degree = ((int)3); } - if (values[12]) { - __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[11]) { + __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 412; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/svm/libsvm.pyx":394 - * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, # <<<<<<<<<<<<<< - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - */ __pyx_v_gamma = ((double)0.1); } - if (values[13]) { - __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[13]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[12]) { + __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 412; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_coef0 = ((double)0.); } - if (values[14]) { - __pyx_v_tol = __pyx_PyFloat_AsDouble(values[14]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_tol = ((double)1e-3); - } + __pyx_v_class_weight = ((PyArrayObject *)values[13]); + __pyx_v_sample_weight = ((PyArrayObject *)values[14]); if (values[15]) { - __pyx_v_C = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - - /* "sklearn/svm/libsvm.pyx":395 - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - * double C=1., double nu=0.5, double epsilon=0.1, # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), - */ - __pyx_v_C = ((double)1.); - } - if (values[16]) { - __pyx_v_nu = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_nu = ((double)0.5); - } - if (values[17]) { - __pyx_v_epsilon = __pyx_PyFloat_AsDouble(values[17]); if (unlikely((__pyx_v_epsilon == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 417; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - __pyx_v_epsilon = ((double)0.1); - } - __pyx_v_class_weight_label = ((PyArrayObject *)values[18]); - __pyx_v_class_weight = ((PyArrayObject *)values[19]); - __pyx_v_sample_weight = ((PyArrayObject *)values[20]); - if (values[21]) { - __pyx_v_shrinking = __Pyx_PyInt_AsInt(values[21]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_shrinking = ((int)0); - } - if (values[22]) { - __pyx_v_probability = __Pyx_PyInt_AsInt(values[22]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - __pyx_v_probability = ((int)0); - } - if (values[23]) { - __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[23]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else { - - /* "sklearn/svm/libsvm.pyx":403 - * sample_weight=np.empty(0), - * int shrinking=0, int probability=0, - * double cache_size=100.): # <<<<<<<<<<<<<< - * """ - * Predict margin (libsvm name for this is predict_values) - */ __pyx_v_cache_size = ((double)100.); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("decision_function", 0, 7, 24, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("decision_function", 0, 6, 16, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.svm.libsvm.decision_function", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_support), __pyx_ptype_5numpy_ndarray, 1, "support", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV), __pyx_ptype_5numpy_ndarray, 1, "SV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nSV), __pyx_ptype_5numpy_ndarray, 1, "nSV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 387; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sv_coef), __pyx_ptype_5numpy_ndarray, 1, "sv_coef", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 388; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_intercept), __pyx_ptype_5numpy_ndarray, 1, "intercept", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 389; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_label), __pyx_ptype_5numpy_ndarray, 1, "label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probA), __pyx_ptype_5numpy_ndarray, 1, "probA", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probB), __pyx_ptype_5numpy_ndarray, 1, "probB", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kernel), (&PyString_Type), 1, "kernel", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight_label), __pyx_ptype_5numpy_ndarray, 1, "class_weight_label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_3svm_6libsvm_6decision_function(__pyx_self, __pyx_v_X, __pyx_v_support, __pyx_v_SV, __pyx_v_nSV, __pyx_v_sv_coef, __pyx_v_intercept, __pyx_v_label, __pyx_v_probA, __pyx_v_probB, __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_tol, __pyx_v_C, __pyx_v_nu, __pyx_v_epsilon, __pyx_v_class_weight_label, __pyx_v_class_weight, __pyx_v_sample_weight, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_cache_size); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_support), __pyx_ptype_5numpy_ndarray, 1, "support", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 404; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV), __pyx_ptype_5numpy_ndarray, 1, "SV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 405; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nSV), __pyx_ptype_5numpy_ndarray, 1, "nSV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 406; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sv_coef), __pyx_ptype_5numpy_ndarray, 1, "sv_coef", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_intercept), __pyx_ptype_5numpy_ndarray, 1, "intercept", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probA), __pyx_ptype_5numpy_ndarray, 1, "probA", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 409; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probB), __pyx_ptype_5numpy_ndarray, 1, "probB", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_3svm_6libsvm_6decision_function(__pyx_self, __pyx_v_X, __pyx_v_support, __pyx_v_SV, __pyx_v_nSV, __pyx_v_sv_coef, __pyx_v_intercept, __pyx_v_probA, __pyx_v_probB, __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_class_weight, __pyx_v_sample_weight, __pyx_v_cache_size); + + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -5006,20 +4978,13 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_7decision_function(PyObject *__p return __pyx_r; } -/* "sklearn/svm/libsvm.pyx":383 - * - * - * def decision_function( # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=2, mode='c'] X, - * np.ndarray[np.int32_t, ndim=1, mode='c'] support, - */ - -static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_label, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight_label, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size) { +static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_support, PyArrayObject *__pyx_v_SV, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB, int __pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, PyArrayObject *__pyx_v_class_weight, CYTHON_UNUSED PyArrayObject *__pyx_v_sample_weight, double __pyx_v_cache_size) { PyArrayObject *__pyx_v_dec_values = 0; struct svm_parameter __pyx_v_param; struct svm_model *__pyx_v_model; npy_intp __pyx_v_n_class; - PyObject *__pyx_v_kernel_index = NULL; + PyArrayObject *__pyx_v_class_weight_label = 0; + int __pyx_v_rv; __Pyx_LocalBuf_ND __pyx_pybuffernd_SV; __Pyx_Buffer __pyx_pybuffer_SV; __Pyx_LocalBuf_ND __pyx_pybuffernd_X; @@ -5032,8 +4997,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED __Pyx_Buffer __pyx_pybuffer_dec_values; __Pyx_LocalBuf_ND __pyx_pybuffernd_intercept; __Pyx_Buffer __pyx_pybuffer_intercept; - __Pyx_LocalBuf_ND __pyx_pybuffernd_label; - __Pyx_Buffer __pyx_pybuffer_label; __Pyx_LocalBuf_ND __pyx_pybuffernd_nSV; __Pyx_Buffer __pyx_pybuffer_nSV; __Pyx_LocalBuf_ND __pyx_pybuffernd_probA; @@ -5051,14 +5014,20 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + int __pyx_t_7; PyArrayObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; + int __pyx_t_9; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + int __pyx_t_13; + char const *__pyx_t_14; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + PyObject *__pyx_t_17 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; @@ -5067,6 +5036,10 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED __pyx_pybuffer_dec_values.refcount = 0; __pyx_pybuffernd_dec_values.data = NULL; __pyx_pybuffernd_dec_values.rcbuffer = &__pyx_pybuffer_dec_values; + __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight_label.refcount = 0; + __pyx_pybuffernd_class_weight_label.data = NULL; + __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_X.pybuffer.buf = NULL; __pyx_pybuffer_X.refcount = 0; __pyx_pybuffernd_X.data = NULL; @@ -5091,10 +5064,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED __pyx_pybuffer_intercept.refcount = 0; __pyx_pybuffernd_intercept.data = NULL; __pyx_pybuffernd_intercept.rcbuffer = &__pyx_pybuffer_intercept; - __pyx_pybuffer_label.pybuffer.buf = NULL; - __pyx_pybuffer_label.refcount = 0; - __pyx_pybuffernd_label.data = NULL; - __pyx_pybuffernd_label.rcbuffer = &__pyx_pybuffer_label; __pyx_pybuffer_probA.pybuffer.buf = NULL; __pyx_pybuffer_probA.refcount = 0; __pyx_pybuffernd_probA.data = NULL; @@ -5103,10 +5072,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED __pyx_pybuffer_probB.refcount = 0; __pyx_pybuffernd_probB.data = NULL; __pyx_pybuffernd_probB.rcbuffer = &__pyx_pybuffer_probB; - __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; - __pyx_pybuffer_class_weight_label.refcount = 0; - __pyx_pybuffernd_class_weight_label.data = NULL; - __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_class_weight.pybuffer.buf = NULL; __pyx_pybuffer_class_weight.refcount = 0; __pyx_pybuffernd_class_weight.data = NULL; @@ -5117,127 +5082,131 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED __pyx_pybuffernd_sample_weight.rcbuffer = &__pyx_pybuffer_sample_weight; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support.rcbuffer->pybuffer, (PyObject*)__pyx_v_support, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support.rcbuffer->pybuffer, (PyObject*)__pyx_v_support, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_support.diminfo[0].strides = __pyx_pybuffernd_support.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_support.diminfo[0].shape = __pyx_pybuffernd_support.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_SV.diminfo[0].strides = __pyx_pybuffernd_SV.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_SV.diminfo[0].shape = __pyx_pybuffernd_SV.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_SV.diminfo[1].strides = __pyx_pybuffernd_SV.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_SV.diminfo[1].shape = __pyx_pybuffernd_SV.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer, (PyObject*)__pyx_v_nSV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer, (PyObject*)__pyx_v_nSV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_nSV.diminfo[0].strides = __pyx_pybuffernd_nSV.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_nSV.diminfo[0].shape = __pyx_pybuffernd_nSV.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_v_sv_coef, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_v_sv_coef, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_sv_coef.diminfo[0].strides = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sv_coef.diminfo[0].shape = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_sv_coef.diminfo[1].strides = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_sv_coef.diminfo[1].shape = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_v_intercept, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_v_intercept, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_intercept.diminfo[0].strides = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_intercept.diminfo[0].shape = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_label.diminfo[0].strides = __pyx_pybuffernd_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_label.diminfo[0].shape = __pyx_pybuffernd_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_probA.diminfo[0].strides = __pyx_pybuffernd_probA.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probA.diminfo[0].shape = __pyx_pybuffernd_probA.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_probB.diminfo[0].strides = __pyx_pybuffernd_probB.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probB.diminfo[0].shape = __pyx_pybuffernd_probB.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_class_weight.diminfo[0].strides = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight.diminfo[0].shape = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_sample_weight.diminfo[0].strides = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weight.diminfo[0].shape = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.shape[0]; - /* "sklearn/svm/libsvm.pyx":415 - * cdef np.npy_intp n_class + /* "sklearn/svm/libsvm.pyx":430 * - * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) # <<<<<<<<<<<<<< - * set_parameter(¶m, svm_type, kernel_index, degree, gamma, - * coef0, nu, cache_size, C, tol, epsilon, shrinking, + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) # <<<<<<<<<<<<<< + * + * cdef int rv */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__LIBSVM_KERNEL_TYPES); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_arange); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_class_weight->dimensions[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)__pyx_v_kernel)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_kernel)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_kernel)); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 415; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_int32); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_v_kernel_index = __pyx_t_3; - __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 430; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_class_weight_label = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __pyx_v_class_weight_label = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; - /* "sklearn/svm/libsvm.pyx":416 + /* "sklearn/svm/libsvm.pyx":434 + * cdef int rv * - * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) - * set_parameter(¶m, svm_type, kernel_index, degree, gamma, # <<<<<<<<<<<<<< - * coef0, nu, cache_size, C, tol, epsilon, shrinking, - * probability, class_weight.shape[0], class_weight_label.data, + * set_predict_params(¶m, svm_type, kernel, degree, gamma, coef0, # <<<<<<<<<<<<<< + * cache_size, 0, class_weight.shape[0], + * class_weight_label.data, class_weight.data) */ - __pyx_t_4 = __Pyx_PyInt_AsInt(__pyx_v_kernel_index); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_f_7sklearn_3svm_6libsvm_set_predict_params((&__pyx_v_param), __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_cache_size, 0, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/svm/libsvm.pyx":419 - * coef0, nu, cache_size, C, tol, epsilon, shrinking, - * probability, class_weight.shape[0], class_weight_label.data, - * class_weight.data) # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm.pyx":438 + * class_weight_label.data, class_weight.data) * - * model = set_model(¶m, nSV.shape[0], SV.data, SV.shape, - */ - set_parameter((&__pyx_v_param), __pyx_v_svm_type, __pyx_t_4, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_C, __pyx_v_tol, __pyx_v_epsilon, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data); - - /* "sklearn/svm/libsvm.pyx":424 + * model = set_model(¶m, nSV.shape[0], SV.data, SV.shape, # <<<<<<<<<<<<<< * support.data, support.shape, sv_coef.strides, * sv_coef.data, intercept.data, nSV.data, - * label.data, probA.data, probB.data) # <<<<<<<<<<<<<< - * - * if svm_type > 1: */ - __pyx_v_model = set_model((&__pyx_v_param), ((int)(__pyx_v_nSV->dimensions[0])), __pyx_v_SV->data, __pyx_v_SV->dimensions, __pyx_v_support->data, __pyx_v_support->dimensions, __pyx_v_sv_coef->strides, __pyx_v_sv_coef->data, __pyx_v_intercept->data, __pyx_v_nSV->data, __pyx_v_label->data, __pyx_v_probA->data, __pyx_v_probB->data); + __pyx_v_model = set_model((&__pyx_v_param), ((int)(__pyx_v_nSV->dimensions[0])), __pyx_v_SV->data, __pyx_v_SV->dimensions, __pyx_v_support->data, __pyx_v_support->dimensions, __pyx_v_sv_coef->strides, __pyx_v_sv_coef->data, __pyx_v_intercept->data, __pyx_v_nSV->data, __pyx_v_probA->data, __pyx_v_probB->data); - /* "sklearn/svm/libsvm.pyx":426 - * label.data, probA.data, probB.data) + /* "sklearn/svm/libsvm.pyx":443 + * probA.data, probB.data) * * if svm_type > 1: # <<<<<<<<<<<<<< * n_class = 1 * else: */ - __pyx_t_5 = (__pyx_v_svm_type > 1); - if (__pyx_t_5) { + __pyx_t_7 = ((__pyx_v_svm_type > 1) != 0); + if (__pyx_t_7) { - /* "sklearn/svm/libsvm.pyx":427 + /* "sklearn/svm/libsvm.pyx":444 * * if svm_type > 1: * n_class = 1 # <<<<<<<<<<<<<< @@ -5249,7 +5218,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED } /*else*/ { - /* "sklearn/svm/libsvm.pyx":429 + /* "sklearn/svm/libsvm.pyx":446 * n_class = 1 * else: * n_class = get_nr(model) # <<<<<<<<<<<<<< @@ -5258,120 +5227,210 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED */ __pyx_v_n_class = get_nr(__pyx_v_model); - /* "sklearn/svm/libsvm.pyx":430 + /* "sklearn/svm/libsvm.pyx":447 * else: * n_class = get_nr(model) * n_class = n_class * (n_class - 1) / 2 # <<<<<<<<<<<<<< * - * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) + * try: */ __pyx_v_n_class = __Pyx_div_long((__pyx_v_n_class * (__pyx_v_n_class - 1)), 2); } __pyx_L3:; - /* "sklearn/svm/libsvm.pyx":432 + /* "sklearn/svm/libsvm.pyx":449 * n_class = n_class * (n_class - 1) / 2 * - * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) # <<<<<<<<<<<<<< - * if copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) < 0: - * raise MemoryError("We've run out of of memory") + * try: # <<<<<<<<<<<<<< + * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) + * with nogil: */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_n_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_3 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_6)); - __pyx_t_6 = 0; - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_8 = ((PyArrayObject *)__pyx_t_7); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); - __pyx_t_4 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_4 < 0)) { - PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_dec_values, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + /*try:*/ { + + /* "sklearn/svm/libsvm.pyx":450 + * + * try: + * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) # <<<<<<<<<<<<<< + * with nogil: + * rv = copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_class); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __pyx_t_8 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); + __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_9 < 0)) { + PyErr_Fetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_dec_values, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_12); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_10, __pyx_t_11, __pyx_t_12); + } } + __pyx_pybuffernd_dec_values.diminfo[0].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_dec_values.diminfo[0].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_dec_values.diminfo[1].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_dec_values.diminfo[1].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[1]; + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_error;} } - __pyx_pybuffernd_dec_values.diminfo[0].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_dec_values.diminfo[0].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_dec_values.diminfo[1].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_dec_values.diminfo[1].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_8 = 0; - __pyx_v_dec_values = ((PyArrayObject *)__pyx_t_7); - __pyx_t_7 = 0; + __pyx_t_8 = 0; + __pyx_v_dec_values = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; - /* "sklearn/svm/libsvm.pyx":433 - * - * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) - * if copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) < 0: # <<<<<<<<<<<<<< - * raise MemoryError("We've run out of of memory") - * # free model and param + /* "sklearn/svm/libsvm.pyx":451 + * try: + * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) + * with nogil: # <<<<<<<<<<<<<< + * rv = copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) + * if rv < 0: */ - __pyx_t_5 = (copy_predict_values(__pyx_v_X->data, __pyx_v_model, __pyx_v_X->dimensions, __pyx_v_dec_values->data, __pyx_v_n_class) < 0); - if (__pyx_t_5) { + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { - /* "sklearn/svm/libsvm.pyx":434 - * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) - * if copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) < 0: - * raise MemoryError("We've run out of of memory") # <<<<<<<<<<<<<< - * # free model and param - * free_model(model) + /* "sklearn/svm/libsvm.pyx":452 + * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) + * with nogil: + * rv = copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) # <<<<<<<<<<<<<< + * if rv < 0: + * raise MemoryError("We've run out of memory") */ - __pyx_t_7 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_35), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_Raise(__pyx_t_7, 0, 0, 0); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; + __pyx_v_rv = copy_predict_values(__pyx_v_X->data, __pyx_v_model, __pyx_v_X->dimensions, __pyx_v_dec_values->data, __pyx_v_n_class); + } + + /* "sklearn/svm/libsvm.pyx":451 + * try: + * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) + * with nogil: # <<<<<<<<<<<<<< + * rv = copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) + * if rv < 0: + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L9; + } + __pyx_L9:; + } + } + + /* "sklearn/svm/libsvm.pyx":453 + * with nogil: + * rv = copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) + * if rv < 0: # <<<<<<<<<<<<<< + * raise MemoryError("We've run out of memory") + * finally: + */ + __pyx_t_7 = ((__pyx_v_rv < 0) != 0); + if (__pyx_t_7) { + + /* "sklearn/svm/libsvm.pyx":454 + * rv = copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) + * if rv < 0: + * raise MemoryError("We've run out of memory") # <<<<<<<<<<<<<< + * finally: + * free_model(model) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__24, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L5_error;} + } } - __pyx_L4:; - /* "sklearn/svm/libsvm.pyx":436 - * raise MemoryError("We've run out of of memory") - * # free model and param - * free_model(model) # <<<<<<<<<<<<<< - * return dec_values + /* "sklearn/svm/libsvm.pyx":456 + * raise MemoryError("We've run out of memory") + * finally: + * free_model(model) # <<<<<<<<<<<<<< * + * return dec_values */ - free_model(__pyx_v_model); + /*finally:*/ { + /*normal exit:*/{ + free_model(__pyx_v_model); + goto __pyx_L6; + } + /*exception exit:*/{ + __pyx_L5_error:; + __pyx_t_12 = 0; __pyx_t_11 = 0; __pyx_t_10 = 0; __pyx_t_15 = 0; __pyx_t_16 = 0; __pyx_t_17 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_15, &__pyx_t_16, &__pyx_t_17); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10) < 0)) __Pyx_ErrFetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_12); + __Pyx_XGOTREF(__pyx_t_11); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_15); + __Pyx_XGOTREF(__pyx_t_16); + __Pyx_XGOTREF(__pyx_t_17); + __pyx_t_9 = __pyx_lineno; __pyx_t_13 = __pyx_clineno; __pyx_t_14 = __pyx_filename; + { + free_model(__pyx_v_model); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_15); + __Pyx_XGIVEREF(__pyx_t_16); + __Pyx_XGIVEREF(__pyx_t_17); + __Pyx_ExceptionReset(__pyx_t_15, __pyx_t_16, __pyx_t_17); + } + __Pyx_XGIVEREF(__pyx_t_12); + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_ErrRestore(__pyx_t_12, __pyx_t_11, __pyx_t_10); + __pyx_t_12 = 0; __pyx_t_11 = 0; __pyx_t_10 = 0; __pyx_t_15 = 0; __pyx_t_16 = 0; __pyx_t_17 = 0; + __pyx_lineno = __pyx_t_9; __pyx_clineno = __pyx_t_13; __pyx_filename = __pyx_t_14; + goto __pyx_L1_error; + } + __pyx_L6:; + } - /* "sklearn/svm/libsvm.pyx":437 - * # free model and param - * free_model(model) + /* "sklearn/svm/libsvm.pyx":458 + * free_model(model) + * * return dec_values # <<<<<<<<<<<<<< * * @@ -5381,14 +5440,21 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED __pyx_r = ((PyObject *)__pyx_v_dec_values); goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/svm/libsvm.pyx":402 + * + * + * def decision_function( # <<<<<<<<<<<<<< + * np.ndarray[np.float64_t, ndim=2, mode='c'] X, + * np.ndarray[np.int32_t, ndim=1, mode='c'] support, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_SV.rcbuffer->pybuffer); @@ -5397,7 +5463,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); @@ -5415,7 +5480,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); @@ -5424,15 +5488,23 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_6decision_function(CYTHON_UNUSED __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_dec_values); - __Pyx_XDECREF(__pyx_v_kernel_index); + __Pyx_XDECREF((PyObject *)__pyx_v_class_weight_label); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } +/* "sklearn/svm/libsvm.pyx":461 + * + * + * def cross_validation( # <<<<<<<<<<<<<< + * np.ndarray[np.float64_t, ndim=2, mode='c'] X, + * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, + */ + /* Python wrapper */ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_9cross_validation(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_3svm_6libsvm_8cross_validation[] = "\n Binding of the cross-validation routine (low-level routine)\n\n Parameters\n ----------\n\n X: array-like, dtype=float, size=[n_samples, n_features]\n\n Y: array, dtype=float, size=[n_samples]\n target vector\n\n svm_type : {0, 1, 2, 3, 4}\n Type of SVM: C SVC, nu SVC, one class, epsilon SVR, nu SVR\n\n kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'}\n Kernel to use in the model: linear, polynomial, RBF, sigmoid\n or precomputed.\n\n degree : int\n Degree of the polynomial kernel (only relevant if kernel is\n set to polynomial)\n\n gamma : float\n Gamma parameter in RBF kernel (only relevant if kernel is set\n to RBF)\n\n coef0 : float\n Independent parameter in poly/sigmoid kernel.\n\n tol : float\n Stopping criteria.\n\n C : float\n C parameter in C-Support Vector Classification\n\n nu : float\n\n cache_size : float\n\n Returns\n -------\n target : array, float\n\n "; +static char __pyx_doc_7sklearn_3svm_6libsvm_8cross_validation[] = "\n Binding of the cross-validation routine (low-level routine)\n\n Parameters\n ----------\n\n X: array-like, dtype=float, size=[n_samples, n_features]\n\n Y: array, dtype=float, size=[n_samples]\n target vector\n\n svm_type : {0, 1, 2, 3, 4}\n Type of SVM: C SVC, nu SVC, one class, epsilon SVR, nu SVR\n\n kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'}\n Kernel to use in the model: linear, polynomial, RBF, sigmoid\n or precomputed.\n\n degree : int\n Degree of the polynomial kernel (only relevant if kernel is\n set to polynomial)\n\n gamma : float\n Gamma parameter in RBF kernel (only relevant if kernel is set\n to RBF)\n\n coef0 : float\n Independent parameter in poly/sigmoid kernel.\n\n tol : float\n Stopping criteria.\n\n C : float\n C parameter in C-Support Vector Classification\n\n nu : float\n\n cache_size : float\n\n random_seed : int, optional\n Seed for the random number generator used for probability estimates.\n 0 by default.\n\n Returns\n -------\n target : array, float\n\n "; static PyMethodDef __pyx_mdef_7sklearn_3svm_6libsvm_9cross_validation = {__Pyx_NAMESTR("cross_validation"), (PyCFunction)__pyx_pw_7sklearn_3svm_6libsvm_9cross_validation, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_3svm_6libsvm_8cross_validation)}; static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_9cross_validation(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_X = 0; @@ -5447,28 +5519,31 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_9cross_validation(PyObject *__py double __pyx_v_C; double __pyx_v_nu; CYTHON_UNUSED double __pyx_v_epsilon; - PyArrayObject *__pyx_v_class_weight_label = 0; PyArrayObject *__pyx_v_class_weight = 0; PyArrayObject *__pyx_v_sample_weight = 0; int __pyx_v_shrinking; int __pyx_v_probability; double __pyx_v_cache_size; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__Y,&__pyx_n_s__n_fold,&__pyx_n_s__svm_type,&__pyx_n_s__kernel,&__pyx_n_s__degree,&__pyx_n_s__gamma,&__pyx_n_s__coef0,&__pyx_n_s__tol,&__pyx_n_s__C,&__pyx_n_s__nu,&__pyx_n_s__epsilon,&__pyx_n_s__class_weight_label,&__pyx_n_s__class_weight,&__pyx_n_s__sample_weight,&__pyx_n_s__shrinking,&__pyx_n_s__probability,&__pyx_n_s__cache_size,0}; + int __pyx_v_max_iter; + int __pyx_v_random_seed; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("cross_validation (wrapper)", 0); - __pyx_self = __pyx_self; { - PyObject* values[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_Y,&__pyx_n_s_n_fold,&__pyx_n_s_svm_type,&__pyx_n_s_kernel,&__pyx_n_s_degree,&__pyx_n_s_gamma,&__pyx_n_s_coef0,&__pyx_n_s_tol,&__pyx_n_s_C,&__pyx_n_s_nu,&__pyx_n_s_epsilon,&__pyx_n_s_class_weight,&__pyx_n_s_sample_weight,&__pyx_n_s_shrinking,&__pyx_n_s_probability,&__pyx_n_s_cache_size,&__pyx_n_s_max_iter,&__pyx_n_s_random_seed,0}; + PyObject* values[19] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; values[3] = ((PyObject *)__pyx_int_0); - values[4] = ((PyObject*)__pyx_n_s__rbf); - values[12] = (PyObject *)__pyx_k_36; - values[13] = (PyObject *)__pyx_k_37; - values[14] = (PyObject *)__pyx_k_38; + values[4] = ((PyObject*)__pyx_n_s_rbf); + values[12] = (PyObject *)__pyx_k__25; + values[13] = (PyObject *)__pyx_k__26; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { + case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); @@ -5493,166 +5568,105 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_9cross_validation(PyObject *__py kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__Y); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("cross_validation", 0, 3, 18, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("cross_validation", 0, 3, 19, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_fold); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_fold)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("cross_validation", 0, 3, 18, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("cross_validation", 0, 3, 19, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__svm_type); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_svm_type); if (value) { values[3] = value; kw_args--; } } case 4: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kernel); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kernel); if (value) { values[4] = value; kw_args--; } } case 5: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__degree); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_degree); if (value) { values[5] = value; kw_args--; } } case 6: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__gamma); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_gamma); if (value) { values[6] = value; kw_args--; } } case 7: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coef0); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_coef0); if (value) { values[7] = value; kw_args--; } } case 8: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__tol); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tol); if (value) { values[8] = value; kw_args--; } } case 9: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_C); if (value) { values[9] = value; kw_args--; } } case 10: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nu); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_nu); if (value) { values[10] = value; kw_args--; } } case 11: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__epsilon); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_epsilon); if (value) { values[11] = value; kw_args--; } } case 12: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight_label); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight); if (value) { values[12] = value; kw_args--; } } case 13: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sample_weight); if (value) { values[13] = value; kw_args--; } } case 14: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sample_weight); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shrinking); if (value) { values[14] = value; kw_args--; } } case 15: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shrinking); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_probability); if (value) { values[15] = value; kw_args--; } } case 16: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probability); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_cache_size); if (value) { values[16] = value; kw_args--; } } case 17: if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__cache_size); + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_iter); if (value) { values[17] = value; kw_args--; } } + case 18: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random_seed); + if (value) { values[18] = value; kw_args--; } + } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "cross_validation") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - if (values[5]) { - } else { - __pyx_v_degree = ((int)3); - } - if (values[6]) { - } else { - - /* "sklearn/svm/libsvm.pyx":444 - * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, - * int n_fold, svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, # <<<<<<<<<<<<<< - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - */ - __pyx_v_gamma = ((double)0.1); - } - if (values[7]) { - } else { - __pyx_v_coef0 = ((double)0.); - } - if (values[8]) { - } else { - __pyx_v_tol = ((double)1e-3); - } - if (values[9]) { - } else { - - /* "sklearn/svm/libsvm.pyx":445 - * int n_fold, svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - * double C=1., double nu=0.5, double epsilon=0.1, # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), - */ - __pyx_v_C = ((double)1.); - } - if (values[10]) { - } else { - __pyx_v_nu = ((double)0.5); - } - if (values[11]) { - } else { - __pyx_v_epsilon = ((double)0.1); - } - if (values[15]) { - } else { - __pyx_v_shrinking = ((int)0); - } - if (values[16]) { - } else { - __pyx_v_probability = ((int)0); - } - if (values[17]) { - } else { - - /* "sklearn/svm/libsvm.pyx":452 - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * sample_weight=np.empty(0), - * int shrinking=0, int probability=0, double cache_size=100.): # <<<<<<<<<<<<<< - * """ - * Binding of the cross-validation routine (low-level routine) - */ - __pyx_v_cache_size = ((double)100.); + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "cross_validation") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { + case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); case 17: values[16] = PyTuple_GET_ITEM(__pyx_args, 16); case 16: values[15] = PyTuple_GET_ITEM(__pyx_args, 15); @@ -5677,102 +5691,88 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_9cross_validation(PyObject *__py } __pyx_v_X = ((PyArrayObject *)values[0]); __pyx_v_Y = ((PyArrayObject *)values[1]); - __pyx_v_n_fold = __Pyx_PyInt_AsInt(values[2]); if (unlikely((__pyx_v_n_fold == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_fold = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_n_fold == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_svm_type = values[3]; __pyx_v_kernel = ((PyObject*)values[4]); if (values[5]) { - __pyx_v_degree = __Pyx_PyInt_AsInt(values[5]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_degree = __Pyx_PyInt_As_int(values[5]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_degree = ((int)3); } if (values[6]) { - __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[6]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 465; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/svm/libsvm.pyx":444 - * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, - * int n_fold, svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, # <<<<<<<<<<<<<< - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - */ __pyx_v_gamma = ((double)0.1); } if (values[7]) { - __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 465; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_coef0 = ((double)0.); } if (values[8]) { - __pyx_v_tol = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_tol = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_tol == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 465; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_tol = ((double)1e-3); } if (values[9]) { - __pyx_v_C = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_C = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 466; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/svm/libsvm.pyx":445 - * int n_fold, svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - * double C=1., double nu=0.5, double epsilon=0.1, # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), - */ __pyx_v_C = ((double)1.); } if (values[10]) { - __pyx_v_nu = __pyx_PyFloat_AsDouble(values[10]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_nu = __pyx_PyFloat_AsDouble(values[10]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 466; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_nu = ((double)0.5); } if (values[11]) { - __pyx_v_epsilon = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_epsilon == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_epsilon = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_epsilon == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 466; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_epsilon = ((double)0.1); } - __pyx_v_class_weight_label = ((PyArrayObject *)values[12]); - __pyx_v_class_weight = ((PyArrayObject *)values[13]); - __pyx_v_sample_weight = ((PyArrayObject *)values[14]); - if (values[15]) { - __pyx_v_shrinking = __Pyx_PyInt_AsInt(values[15]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_class_weight = ((PyArrayObject *)values[12]); + __pyx_v_sample_weight = ((PyArrayObject *)values[13]); + if (values[14]) { + __pyx_v_shrinking = __Pyx_PyInt_As_int(values[14]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_shrinking = ((int)0); } - if (values[16]) { - __pyx_v_probability = __Pyx_PyInt_AsInt(values[16]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[15]) { + __pyx_v_probability = __Pyx_PyInt_As_int(values[15]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_probability = ((int)0); } - if (values[17]) { - __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[17]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[16]) { + __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { - - /* "sklearn/svm/libsvm.pyx":452 - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * sample_weight=np.empty(0), - * int shrinking=0, int probability=0, double cache_size=100.): # <<<<<<<<<<<<<< - * """ - * Binding of the cross-validation routine (low-level routine) - */ __pyx_v_cache_size = ((double)100.); } + if (values[17]) { + __pyx_v_max_iter = __Pyx_PyInt_As_int(values[17]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 472; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_max_iter = ((int)-1); + } + if (values[18]) { + __pyx_v_random_seed = __Pyx_PyInt_As_int(values[18]); if (unlikely((__pyx_v_random_seed == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 473; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + __pyx_v_random_seed = ((int)0); + } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("cross_validation", 0, 3, 18, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("cross_validation", 0, 3, 19, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.svm.libsvm.cross_validation", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kernel), (&PyString_Type), 1, "kernel", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight_label), __pyx_ptype_5numpy_ndarray, 1, "class_weight_label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(__pyx_self, __pyx_v_X, __pyx_v_Y, __pyx_v_n_fold, __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_tol, __pyx_v_C, __pyx_v_nu, __pyx_v_epsilon, __pyx_v_class_weight_label, __pyx_v_class_weight, __pyx_v_sample_weight, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_cache_size); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kernel), (&PyString_Type), 1, "kernel", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(__pyx_self, __pyx_v_X, __pyx_v_Y, __pyx_v_n_fold, __pyx_v_svm_type, __pyx_v_kernel, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_tol, __pyx_v_C, __pyx_v_nu, __pyx_v_epsilon, __pyx_v_class_weight, __pyx_v_sample_weight, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_cache_size, __pyx_v_max_iter, __pyx_v_random_seed); + + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -5781,19 +5781,12 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_9cross_validation(PyObject *__py return __pyx_r; } -/* "sklearn/svm/libsvm.pyx":440 - * - * - * def cross_validation( # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=2, mode='c'] X, - * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, - */ - -static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_n_fold, PyObject *__pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, CYTHON_UNUSED double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight_label, PyArrayObject *__pyx_v_class_weight, PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size) { +static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, int __pyx_v_n_fold, PyObject *__pyx_v_svm_type, PyObject *__pyx_v_kernel, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_tol, double __pyx_v_C, double __pyx_v_nu, CYTHON_UNUSED double __pyx_v_epsilon, PyArrayObject *__pyx_v_class_weight, PyArrayObject *__pyx_v_sample_weight, int __pyx_v_shrinking, int __pyx_v_probability, double __pyx_v_cache_size, int __pyx_v_max_iter, int __pyx_v_random_seed) { struct svm_parameter __pyx_v_param; struct svm_problem __pyx_v_problem; - char *__pyx_v_error_msg; + char const *__pyx_v_error_msg; PyObject *__pyx_v_kernel_index = NULL; + PyArrayObject *__pyx_v_class_weight_label = 0; PyArrayObject *__pyx_v_target = 0; __Pyx_LocalBuf_ND __pyx_pybuffernd_X; __Pyx_Buffer __pyx_pybuffer_X; @@ -5821,13 +5814,22 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; PyObject *__pyx_t_12 = NULL; - int __pyx_t_13; - PyArrayObject *__pyx_t_14 = NULL; + PyArrayObject *__pyx_t_13 = NULL; + int __pyx_t_14; + PyArrayObject *__pyx_t_15 = NULL; + char const *__pyx_t_16; + PyObject *__pyx_t_17 = NULL; + PyObject *__pyx_t_18 = NULL; + PyObject *__pyx_t_19 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("cross_validation", 0); __Pyx_INCREF((PyObject *)__pyx_v_sample_weight); + __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight_label.refcount = 0; + __pyx_pybuffernd_class_weight_label.data = NULL; + __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_target.pybuffer.buf = NULL; __pyx_pybuffer_target.refcount = 0; __pyx_pybuffernd_target.data = NULL; @@ -5840,10 +5842,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED __pyx_pybuffer_Y.refcount = 0; __pyx_pybuffernd_Y.data = NULL; __pyx_pybuffernd_Y.rcbuffer = &__pyx_pybuffer_Y; - __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; - __pyx_pybuffer_class_weight_label.refcount = 0; - __pyx_pybuffernd_class_weight_label.data = NULL; - __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_class_weight.pybuffer.buf = NULL; __pyx_pybuffer_class_weight.refcount = 0; __pyx_pybuffernd_class_weight.data = NULL; @@ -5854,75 +5852,70 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED __pyx_pybuffernd_sample_weight.rcbuffer = &__pyx_pybuffer_sample_weight; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Y.rcbuffer->pybuffer, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Y.rcbuffer->pybuffer, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_Y.diminfo[0].strides = __pyx_pybuffernd_Y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_Y.diminfo[0].shape = __pyx_pybuffernd_Y.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_class_weight.diminfo[0].strides = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight.diminfo[0].shape = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_sample_weight.diminfo[0].strides = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weight.diminfo[0].shape = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.shape[0]; - /* "sklearn/svm/libsvm.pyx":505 + /* "sklearn/svm/libsvm.pyx":530 * cdef np.npy_intp nr * * if len(sample_weight) == 0: # <<<<<<<<<<<<<< * sample_weight = np.ones(X.shape[0], dtype=np.float64) * else: */ - __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_sample_weight)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 505; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = (__pyx_t_1 == 0); + __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_sample_weight)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((__pyx_t_1 == 0) != 0); if (__pyx_t_2) { - /* "sklearn/svm/libsvm.pyx":506 + /* "sklearn/svm/libsvm.pyx":531 * * if len(sample_weight) == 0: * sample_weight = np.ones(X.shape[0], dtype=np.float64) # <<<<<<<<<<<<<< * else: * assert sample_weight.shape[0] == X.shape[0], \ */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__ones); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_ones); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, __pyx_t_3); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_8 = ((PyArrayObject *)__pyx_t_7); { __Pyx_BufFmt_StackElem __pyx_stack[1]; @@ -5938,17 +5931,16 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED } } __pyx_pybuffernd_sample_weight.diminfo[0].strides = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weight.diminfo[0].shape = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_8 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_sample_weight)); - __pyx_v_sample_weight = ((PyArrayObject *)__pyx_t_7); + __Pyx_DECREF_SET(__pyx_v_sample_weight, ((PyArrayObject *)__pyx_t_7)); __pyx_t_7 = 0; goto __pyx_L3; } /*else*/ { - /* "sklearn/svm/libsvm.pyx":508 + /* "sklearn/svm/libsvm.pyx":533 * sample_weight = np.ones(X.shape[0], dtype=np.float64) * else: * assert sample_weight.shape[0] == X.shape[0], \ # <<<<<<<<<<<<<< @@ -5956,148 +5948,217 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED * "sample_weight has %s samples while X has %s" % \ */ #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!((__pyx_v_sample_weight->dimensions[0]) == (__pyx_v_X->dimensions[0])))) { + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_sample_weight->dimensions[0]) == (__pyx_v_X->dimensions[0])) != 0))) { - /* "sklearn/svm/libsvm.pyx":511 + /* "sklearn/svm/libsvm.pyx":536 * "sample_weight and X have incompatible shapes: " + \ * "sample_weight has %s samples while X has %s" % \ * (sample_weight.shape[0], X.shape[0]) # <<<<<<<<<<<<<< * * if X.shape[0] < n_fold: */ - __pyx_t_7 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_sample_weight->dimensions[0])); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_7 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_5), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Add(((PyObject *)__pyx_kp_s_4), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - PyErr_SetObject(PyExc_AssertionError, ((PyObject *)__pyx_t_5)); - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_sample_weight->dimensions[0])); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_7 = 0; + __pyx_t_3 = 0; + + /* "sklearn/svm/libsvm.pyx":535 + * assert sample_weight.shape[0] == X.shape[0], \ + * "sample_weight and X have incompatible shapes: " + \ + * "sample_weight has %s samples while X has %s" % \ # <<<<<<<<<<<<<< + * (sample_weight.shape[0], X.shape[0]) + * + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_sample_weight_has_s_samples_whil, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "sklearn/svm/libsvm.pyx":534 + * else: + * assert sample_weight.shape[0] == X.shape[0], \ + * "sample_weight and X have incompatible shapes: " + \ # <<<<<<<<<<<<<< + * "sample_weight has %s samples while X has %s" % \ + * (sample_weight.shape[0], X.shape[0]) + */ + __pyx_t_5 = PyNumber_Add(__pyx_kp_s_sample_weight_and_X_have_incompa, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 534; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyErr_SetObject(PyExc_AssertionError, __pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } } #endif } __pyx_L3:; - /* "sklearn/svm/libsvm.pyx":513 + /* "sklearn/svm/libsvm.pyx":538 * (sample_weight.shape[0], X.shape[0]) * * if X.shape[0] < n_fold: # <<<<<<<<<<<<<< * raise ValueError("Number of samples is less than number of folds") * */ - __pyx_t_2 = ((__pyx_v_X->dimensions[0]) < __pyx_v_n_fold); + __pyx_t_2 = (((__pyx_v_X->dimensions[0]) < __pyx_v_n_fold) != 0); if (__pyx_t_2) { - /* "sklearn/svm/libsvm.pyx":514 + /* "sklearn/svm/libsvm.pyx":539 * * if X.shape[0] < n_fold: * raise ValueError("Number of samples is less than number of folds") # <<<<<<<<<<<<<< * * # set problem */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_40), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__27, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L4:; - /* "sklearn/svm/libsvm.pyx":517 + /* "sklearn/svm/libsvm.pyx":542 * * # set problem * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) # <<<<<<<<<<<<<< * set_problem( * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__LIBSVM_KERNEL_TYPES); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 517; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_LIBSVM_KERNEL_TYPES); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__index); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 517; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_index); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 517; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_kernel)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_kernel)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_kernel)); - __pyx_t_7 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 517; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_kernel); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_kernel); + __Pyx_GIVEREF(__pyx_v_kernel); + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_kernel_index = __pyx_t_7; __pyx_t_7 = 0; - /* "sklearn/svm/libsvm.pyx":519 + /* "sklearn/svm/libsvm.pyx":544 * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) * set_problem( * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) # <<<<<<<<<<<<<< * if problem.x == NULL: - * raise MemoryError("Seems we've run out of of memory") + * raise MemoryError("Seems we've run out of memory") + */ + __pyx_t_9 = __Pyx_PyInt_As_int(__pyx_v_kernel_index); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 544; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/svm/libsvm.pyx":543 + * # set problem + * kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) + * set_problem( # <<<<<<<<<<<<<< + * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) + * if problem.x == NULL: */ - __pyx_t_9 = __Pyx_PyInt_AsInt(__pyx_v_kernel_index); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} set_problem((&__pyx_v_problem), __pyx_v_X->data, __pyx_v_Y->data, __pyx_v_sample_weight->data, __pyx_v_X->dimensions, __pyx_t_9); - /* "sklearn/svm/libsvm.pyx":520 + /* "sklearn/svm/libsvm.pyx":545 * set_problem( * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) * if problem.x == NULL: # <<<<<<<<<<<<<< - * raise MemoryError("Seems we've run out of of memory") - * + * raise MemoryError("Seems we've run out of memory") + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ */ - __pyx_t_2 = (__pyx_v_problem.x == NULL); + __pyx_t_2 = ((__pyx_v_problem.x == NULL) != 0); if (__pyx_t_2) { - /* "sklearn/svm/libsvm.pyx":521 + /* "sklearn/svm/libsvm.pyx":546 * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) * if problem.x == NULL: - * raise MemoryError("Seems we've run out of of memory") # <<<<<<<<<<<<<< - * - * # set parameters + * raise MemoryError("Seems we've run out of memory") # <<<<<<<<<<<<<< + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) */ - __pyx_t_7 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_41), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__28, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_Raise(__pyx_t_7, 0, 0, 0); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/svm/libsvm.pyx":548 + * raise MemoryError("Seems we've run out of memory") + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) # <<<<<<<<<<<<<< + * + * # set parameters + */ + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_arange); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_class_weight->dimensions[0])); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_int32); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_dtype, __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_3, __pyx_t_7); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = ((PyArrayObject *)__pyx_t_6); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_t_13, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_class_weight_label = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 547; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; + } } - __pyx_L5:; + __pyx_t_13 = 0; + __pyx_v_class_weight_label = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; - /* "sklearn/svm/libsvm.pyx":525 + /* "sklearn/svm/libsvm.pyx":552 * # set parameters * set_parameter( * ¶m, svm_type, kernel_index, degree, gamma, coef0, nu, cache_size, # <<<<<<<<<<<<<< * C, tol, tol, shrinking, probability, * class_weight.shape[0], class_weight_label.data, */ - __pyx_t_9 = __Pyx_PyInt_AsInt(__pyx_v_svm_type); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_13 = __Pyx_PyInt_AsInt(__pyx_v_kernel_index); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyInt_As_int(__pyx_v_svm_type); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 552; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = __Pyx_PyInt_As_int(__pyx_v_kernel_index); if (unlikely((__pyx_t_14 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 552; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/svm/libsvm.pyx":528 - * C, tol, tol, shrinking, probability, - * class_weight.shape[0], class_weight_label.data, - * class_weight.data) # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm.pyx":551 * - * error_msg = svm_check_parameter(&problem, ¶m); + * # set parameters + * set_parameter( # <<<<<<<<<<<<<< + * ¶m, svm_type, kernel_index, degree, gamma, coef0, nu, cache_size, + * C, tol, tol, shrinking, probability, */ - set_parameter((&__pyx_v_param), __pyx_t_9, __pyx_t_13, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_C, __pyx_v_tol, __pyx_v_tol, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data); + set_parameter((&__pyx_v_param), __pyx_t_9, __pyx_t_14, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_C, __pyx_v_tol, __pyx_v_tol, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data, __pyx_v_max_iter, __pyx_v_random_seed); - /* "sklearn/svm/libsvm.pyx":530 - * class_weight.data) + /* "sklearn/svm/libsvm.pyx":557 + * class_weight.data, max_iter, random_seed) * * error_msg = svm_check_parameter(&problem, ¶m); # <<<<<<<<<<<<<< * if error_msg: @@ -6105,7 +6166,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED */ __pyx_v_error_msg = svm_check_parameter((&__pyx_v_problem), (&__pyx_v_param)); - /* "sklearn/svm/libsvm.pyx":531 + /* "sklearn/svm/libsvm.pyx":558 * * error_msg = svm_check_parameter(&problem, ¶m); * if error_msg: # <<<<<<<<<<<<<< @@ -6115,106 +6176,187 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED __pyx_t_2 = (__pyx_v_error_msg != 0); if (__pyx_t_2) { - /* "sklearn/svm/libsvm.pyx":532 + /* "sklearn/svm/libsvm.pyx":559 * error_msg = svm_check_parameter(&problem, ¶m); * if error_msg: * raise ValueError(error_msg) # <<<<<<<<<<<<<< * * cdef np.ndarray[np.float64_t, ndim=1, mode='c'] target */ - __pyx_t_7 = PyBytes_FromString(__pyx_v_error_msg); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_t_7)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_7)); - __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_Raise(__pyx_t_7, 0, 0, 0); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_error_msg); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/svm/libsvm.pyx":562 + * + * cdef np.ndarray[np.float64_t, ndim=1, mode='c'] target + * try: # <<<<<<<<<<<<<< + * target = np.empty((X.shape[0]), dtype=np.float64) + * with nogil: + */ + /*try:*/ { + + /* "sklearn/svm/libsvm.pyx":563 + * cdef np.ndarray[np.float64_t, ndim=1, mode='c'] target + * try: + * target = np.empty((X.shape[0]), dtype=np.float64) # <<<<<<<<<<<<<< + * with nogil: + * svm_cross_validation(&problem, ¶m, n_fold, target.data) + */ + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L8_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L8_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L8_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L8_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L8_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L8_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L8_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L8_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_3, __pyx_t_6); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L8_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L8_error;} + __pyx_t_15 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_target.rcbuffer->pybuffer); + __pyx_t_14 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_target.rcbuffer->pybuffer, (PyObject*)__pyx_t_15, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_14 < 0)) { + PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_target.rcbuffer->pybuffer, (PyObject*)__pyx_v_target, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_12, __pyx_t_11, __pyx_t_10); + } + } + __pyx_pybuffernd_target.diminfo[0].strides = __pyx_pybuffernd_target.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_target.diminfo[0].shape = __pyx_pybuffernd_target.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_14 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L8_error;} + } + __pyx_t_15 = 0; + __pyx_v_target = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/svm/libsvm.pyx":564 + * try: + * target = np.empty((X.shape[0]), dtype=np.float64) + * with nogil: # <<<<<<<<<<<<<< + * svm_cross_validation(&problem, ¶m, n_fold, target.data) + * finally: + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/svm/libsvm.pyx":565 + * target = np.empty((X.shape[0]), dtype=np.float64) + * with nogil: + * svm_cross_validation(&problem, ¶m, n_fold, target.data) # <<<<<<<<<<<<<< + * finally: + * free(problem.x) + */ + svm_cross_validation((&__pyx_v_problem), (&__pyx_v_param), __pyx_v_n_fold, ((double *)__pyx_v_target->data)); + } - /* "sklearn/svm/libsvm.pyx":535 - * - * cdef np.ndarray[np.float64_t, ndim=1, mode='c'] target - * target = np.empty((X.shape[0]), dtype=np.float64) # <<<<<<<<<<<<<< - * svm_cross_validation(&problem, ¶m, n_fold, target.data) - * + /* "sklearn/svm/libsvm.pyx":564 + * try: + * target = np.empty((X.shape[0]), dtype=np.float64) + * with nogil: # <<<<<<<<<<<<<< + * svm_cross_validation(&problem, ¶m, n_fold, target.data) + * finally: */ - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_14 = ((PyArrayObject *)__pyx_t_6); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_target.rcbuffer->pybuffer); - __pyx_t_13 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_target.rcbuffer->pybuffer, (PyObject*)__pyx_t_14, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_13 < 0)) { - PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_target.rcbuffer->pybuffer, (PyObject*)__pyx_v_target, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_12, __pyx_t_11, __pyx_t_10); - } + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L12; + } + __pyx_L12:; + } } - __pyx_pybuffernd_target.diminfo[0].strides = __pyx_pybuffernd_target.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_target.diminfo[0].shape = __pyx_pybuffernd_target.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_13 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_14 = 0; - __pyx_v_target = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; - - /* "sklearn/svm/libsvm.pyx":536 - * cdef np.ndarray[np.float64_t, ndim=1, mode='c'] target - * target = np.empty((X.shape[0]), dtype=np.float64) - * svm_cross_validation(&problem, ¶m, n_fold, target.data) # <<<<<<<<<<<<<< - * - * free(problem.x) - */ - svm_cross_validation((&__pyx_v_problem), (&__pyx_v_param), __pyx_v_n_fold, ((double *)__pyx_v_target->data)); - /* "sklearn/svm/libsvm.pyx":538 - * svm_cross_validation(&problem, ¶m, n_fold, target.data) + /* "sklearn/svm/libsvm.pyx":567 + * svm_cross_validation(&problem, ¶m, n_fold, target.data) + * finally: + * free(problem.x) # <<<<<<<<<<<<<< * - * free(problem.x) # <<<<<<<<<<<<<< * return target - * */ - free(__pyx_v_problem.x); + /*finally:*/ { + /*normal exit:*/{ + free(__pyx_v_problem.x); + goto __pyx_L9; + } + /*exception exit:*/{ + __pyx_L8_error:; + __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_17 = 0; __pyx_t_18 = 0; __pyx_t_19 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_17, &__pyx_t_18, &__pyx_t_19); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12) < 0)) __Pyx_ErrFetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_11); + __Pyx_XGOTREF(__pyx_t_12); + __Pyx_XGOTREF(__pyx_t_17); + __Pyx_XGOTREF(__pyx_t_18); + __Pyx_XGOTREF(__pyx_t_19); + __pyx_t_14 = __pyx_lineno; __pyx_t_9 = __pyx_clineno; __pyx_t_16 = __pyx_filename; + { + free(__pyx_v_problem.x); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_17); + __Pyx_XGIVEREF(__pyx_t_18); + __Pyx_XGIVEREF(__pyx_t_19); + __Pyx_ExceptionReset(__pyx_t_17, __pyx_t_18, __pyx_t_19); + } + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_XGIVEREF(__pyx_t_12); + __Pyx_ErrRestore(__pyx_t_10, __pyx_t_11, __pyx_t_12); + __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_17 = 0; __pyx_t_18 = 0; __pyx_t_19 = 0; + __pyx_lineno = __pyx_t_14; __pyx_clineno = __pyx_t_9; __pyx_filename = __pyx_t_16; + goto __pyx_L1_error; + } + __pyx_L9:; + } - /* "sklearn/svm/libsvm.pyx":539 + /* "sklearn/svm/libsvm.pyx":569 + * free(problem.x) * - * free(problem.x) * return target # <<<<<<<<<<<<<< * * @@ -6224,8 +6366,15 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED __pyx_r = ((PyObject *)__pyx_v_target); goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/svm/libsvm.pyx":461 + * + * + * def cross_validation( # <<<<<<<<<<<<<< + * np.ndarray[np.float64_t, ndim=2, mode='c'] X, + * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); @@ -6253,6 +6402,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_target.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF(__pyx_v_kernel_index); + __Pyx_XDECREF((PyObject *)__pyx_v_class_weight_label); __Pyx_XDECREF((PyObject *)__pyx_v_target); __Pyx_XDECREF((PyObject *)__pyx_v_sample_weight); __Pyx_XGIVEREF(__pyx_r); @@ -6260,18 +6410,28 @@ static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_8cross_validation(CYTHON_UNUSED return __pyx_r; } +/* "sklearn/svm/libsvm.pyx":572 + * + * + * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< + * """ + * Control verbosity of libsvm library + */ + /* Python wrapper */ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_11set_verbosity_wrap(PyObject *__pyx_self, PyObject *__pyx_arg_verbosity); /*proto*/ static char __pyx_doc_7sklearn_3svm_6libsvm_10set_verbosity_wrap[] = "\n Control verbosity of libsvm library\n "; static PyMethodDef __pyx_mdef_7sklearn_3svm_6libsvm_11set_verbosity_wrap = {__Pyx_NAMESTR("set_verbosity_wrap"), (PyCFunction)__pyx_pw_7sklearn_3svm_6libsvm_11set_verbosity_wrap, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_3svm_6libsvm_10set_verbosity_wrap)}; static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_11set_verbosity_wrap(PyObject *__pyx_self, PyObject *__pyx_arg_verbosity) { int __pyx_v_verbosity; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("set_verbosity_wrap (wrapper)", 0); - __pyx_self = __pyx_self; assert(__pyx_arg_verbosity); { - __pyx_v_verbosity = __Pyx_PyInt_AsInt(__pyx_arg_verbosity); if (unlikely((__pyx_v_verbosity == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_verbosity = __Pyx_PyInt_As_int(__pyx_arg_verbosity); if (unlikely((__pyx_v_verbosity == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; @@ -6280,55 +6440,60 @@ static PyObject *__pyx_pw_7sklearn_3svm_6libsvm_11set_verbosity_wrap(PyObject *_ return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_7sklearn_3svm_6libsvm_10set_verbosity_wrap(__pyx_self, ((int)__pyx_v_verbosity)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/svm/libsvm.pyx":542 - * - * - * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< - * """ - * Control verbosity of libsvm library - */ - static PyObject *__pyx_pf_7sklearn_3svm_6libsvm_10set_verbosity_wrap(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_verbosity) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("set_verbosity_wrap", 0); - /* "sklearn/svm/libsvm.pyx":546 + /* "sklearn/svm/libsvm.pyx":576 * Control verbosity of libsvm library * """ * set_verbosity(verbosity) # <<<<<<<<<<<<<< */ set_verbosity(__pyx_v_verbosity); + /* "sklearn/svm/libsvm.pyx":572 + * + * + * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< + * """ + * Control verbosity of libsvm library + */ + + /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + /* Python wrapper */ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":193 - * # experimental exception made for __getbuffer__ and __releasebuffer__ - * # -- the details of this may change. - * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< - * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP. - */ - static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; @@ -6360,22 +6525,20 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":199 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ - __pyx_t_1 = (__pyx_v_info == NULL); + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; - goto __pyx_L3; } - __pyx_L3:; - /* "numpy.pxd":202 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -6384,7 +6547,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":203 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -6393,7 +6556,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":205 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< @@ -6402,17 +6565,17 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":207 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":208 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -6424,7 +6587,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /*else*/ { - /* "numpy.pxd":210 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -6435,87 +6598,83 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } __pyx_L4:; - /* "numpy.pxd":212 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_1) { - /* "numpy.pxd":213 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS)); + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { - /* "numpy.pxd":214 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_43), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__29, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L5:; - /* "numpy.pxd":216 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_3) { - /* "numpy.pxd":217 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS)); + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { - /* "numpy.pxd":218 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_45), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__30, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; - /* "numpy.pxd":220 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< @@ -6524,7 +6683,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":221 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -6533,16 +6692,17 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":222 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ - if (__pyx_v_copy_shape) { + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { - /* "numpy.pxd":225 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -6551,7 +6711,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":226 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -6560,7 +6720,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":227 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< @@ -6571,7 +6731,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "numpy.pxd":228 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< @@ -6580,7 +6740,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":229 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< @@ -6593,7 +6753,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /*else*/ { - /* "numpy.pxd":231 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< @@ -6602,7 +6762,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":232 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< @@ -6613,7 +6773,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } __pyx_L7:; - /* "numpy.pxd":233 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -6622,7 +6782,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":234 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< @@ -6631,16 +6791,16 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":235 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - /* "numpy.pxd":238 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -6649,17 +6809,19 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_f = NULL; - /* "numpy.pxd":239 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)__pyx_v_self->descr)); - __pyx_v_descr = __pyx_v_self->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":243 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -6668,23 +6830,23 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":245 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; } if (__pyx_t_1) { - /* "numpy.pxd":247 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -6700,7 +6862,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /*else*/ { - /* "numpy.pxd":250 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< @@ -6715,50 +6877,51 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } __pyx_L10:; - /* "numpy.pxd":252 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { - /* "numpy.pxd":253 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; - /* "numpy.pxd":254 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; + __pyx_t_2 = (__pyx_v_little_endian != 0); } else { __pyx_t_2 = __pyx_t_1; } if (!__pyx_t_2) { - /* "numpy.pxd":255 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_7 = __pyx_t_3; } else { __pyx_t_7 = __pyx_t_1; @@ -6769,271 +6932,244 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } if (__pyx_t_1) { - /* "numpy.pxd":256 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_47), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__31, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L12; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L12:; - /* "numpy.pxd":257 - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__b; - goto __pyx_L13; - } + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; - /* "numpy.pxd":258 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__B; - goto __pyx_L13; - } + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; - /* "numpy.pxd":259 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__h; - goto __pyx_L13; - } + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; - /* "numpy.pxd":260 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__H; - goto __pyx_L13; - } + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; - /* "numpy.pxd":261 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__i; - goto __pyx_L13; - } + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; - /* "numpy.pxd":262 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__I; - goto __pyx_L13; - } + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; - /* "numpy.pxd":263 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__l; - goto __pyx_L13; - } + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; - /* "numpy.pxd":264 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__L; - goto __pyx_L13; - } + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; - /* "numpy.pxd":265 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__q; - goto __pyx_L13; - } + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; - /* "numpy.pxd":266 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Q; - goto __pyx_L13; - } + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; - /* "numpy.pxd":267 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__f; - goto __pyx_L13; - } + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; - /* "numpy.pxd":268 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__d; - goto __pyx_L13; - } + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; - /* "numpy.pxd":269 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__g; - goto __pyx_L13; - } + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; - /* "numpy.pxd":270 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zf; - goto __pyx_L13; - } + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; - /* "numpy.pxd":271 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zd; - goto __pyx_L13; - } + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; - /* "numpy.pxd":272 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zg; - goto __pyx_L13; - } + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; - /* "numpy.pxd":273 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L13; - } - /*else*/ { + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: - /* "numpy.pxd":275 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_48), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L13:; - /* "numpy.pxd":276 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -7042,7 +7178,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":277 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -7051,58 +7187,65 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":279 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":280 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":281 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":284 - * f = _util_dtypestring(descr, info.format + 1, + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, - * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string - * + * &offset) */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; - /* "numpy.pxd":285 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L11:; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; @@ -7126,39 +7269,41 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P return __pyx_r; } +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + /* Python wrapper */ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":287 - * f[0] = 0 # Terminate format string - * - * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) - */ - static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":288 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { - /* "numpy.pxd":289 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -7170,17 +7315,17 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s } __pyx_L3:; - /* "numpy.pxd":290 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":291 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -7192,10 +7337,19 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s } __pyx_L4:; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":767 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -7212,7 +7366,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":768 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -7220,14 +7374,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -7238,7 +7399,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -7255,7 +7416,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":771 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -7263,14 +7424,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -7281,7 +7449,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -7298,7 +7466,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":774 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -7306,14 +7474,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -7324,7 +7499,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -7341,7 +7516,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":777 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -7349,14 +7524,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -7367,7 +7549,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -7384,7 +7566,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":780 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -7392,14 +7574,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -7410,7 +7599,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":782 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -7432,7 +7621,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; + int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; int __pyx_t_8; @@ -7444,7 +7633,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":789 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -7453,7 +7642,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":790 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -7462,134 +7651,136 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":793 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ - if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":794 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; - /* "numpy.pxd":795 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: */ - if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { - PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; - /* "numpy.pxd":797 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { - /* "numpy.pxd":798 - * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if ((child.byteorder == '>' and little_endian) or - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_50), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__32, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L5:; - /* "numpy.pxd":800 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); + __pyx_t_6 = ((__pyx_v_child->byteorder == '>') != 0); if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = (__pyx_v_little_endian != 0); } else { __pyx_t_7 = __pyx_t_6; } if (!__pyx_t_7) { - /* "numpy.pxd":801 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); + __pyx_t_6 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); + __pyx_t_8 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_9 = __pyx_t_8; } else { __pyx_t_9 = __pyx_t_6; @@ -7600,23 +7791,21 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } if (__pyx_t_6) { - /* "numpy.pxd":802 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_51), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__33, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; - /* "numpy.pxd":812 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -7624,16 +7813,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; - /* "numpy.pxd":813 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -7642,7 +7830,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":814 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -7651,7 +7839,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":815 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< @@ -7662,7 +7850,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); } - /* "numpy.pxd":817 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< @@ -7672,316 +7860,299 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_t_10 = 0; (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); - /* "numpy.pxd":819 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { - /* "numpy.pxd":820 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 820; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":821 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { - /* "numpy.pxd":822 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_53), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__34, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L10:; - /* "numpy.pxd":825 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L11; } - /* "numpy.pxd":826 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L11; } - /* "numpy.pxd":827 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 104; goto __pyx_L11; } - /* "numpy.pxd":828 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L11; } - /* "numpy.pxd":829 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 105; goto __pyx_L11; } - /* "numpy.pxd":830 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L11; } - /* "numpy.pxd":831 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 108; goto __pyx_L11; } - /* "numpy.pxd":832 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L11; } - /* "numpy.pxd":833 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 113; goto __pyx_L11; } - /* "numpy.pxd":834 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L11; } - /* "numpy.pxd":835 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 102; goto __pyx_L11; } - /* "numpy.pxd":836 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 100; goto __pyx_L11; } - /* "numpy.pxd":837 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 103; goto __pyx_L11; } - /* "numpy.pxd":838 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; @@ -7989,20 +8160,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":839 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; @@ -8010,20 +8180,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":840 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; @@ -8031,50 +8200,49 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":841 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":843 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_48), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L11:; - /* "numpy.pxd":844 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -8086,21 +8254,21 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } /*else*/ { - /* "numpy.pxd":848 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 848; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_11; } __pyx_L9:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":849 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -8110,13 +8278,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_r = __pyx_v_f; goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -8129,7 +8303,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":964 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -8141,9 +8315,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; + int __pyx_t_2; __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":966 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -8151,9 +8326,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "numpy.pxd":967 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":969 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -8165,7 +8341,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":969 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":971 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -8174,7 +8350,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":970 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":972 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -8185,7 +8361,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":971 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":973 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -8194,7 +8370,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":972 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":974 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -8203,10 +8379,19 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ __pyx_v_arr->base = __pyx_v_baseptr; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":974 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -8220,17 +8405,17 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":975 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { - /* "numpy.pxd":976 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":978 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -8241,11 +8426,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "numpy.pxd":978 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -8255,9 +8439,16 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } - __pyx_L3:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); @@ -8270,9 +8461,13 @@ static PyMethodDef __pyx_methods[] = { #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else PyModuleDef_HEAD_INIT, + #endif __Pyx_NAMESTR("libsvm"), - __Pyx_DOCSTR(__pyx_k_54), /* m_doc */ + __Pyx_DOCSTR(__pyx_k_Binding_for_libsvm_skl_These_ar), /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ @@ -8283,95 +8478,102 @@ static struct PyModuleDef __pyx_moduledef = { #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_s_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 1, 0}, - {&__pyx_kp_s_39, __pyx_k_39, sizeof(__pyx_k_39), 0, 0, 1, 0}, - {&__pyx_kp_s_4, __pyx_k_4, sizeof(__pyx_k_4), 0, 0, 1, 0}, - {&__pyx_kp_u_42, __pyx_k_42, sizeof(__pyx_k_42), 0, 1, 0, 0}, - {&__pyx_kp_u_44, __pyx_k_44, sizeof(__pyx_k_44), 0, 1, 0, 0}, - {&__pyx_kp_u_46, __pyx_k_46, sizeof(__pyx_k_46), 0, 1, 0, 0}, - {&__pyx_kp_u_48, __pyx_k_48, sizeof(__pyx_k_48), 0, 1, 0, 0}, - {&__pyx_kp_u_49, __pyx_k_49, sizeof(__pyx_k_49), 0, 1, 0, 0}, - {&__pyx_kp_s_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 0, 1, 0}, - {&__pyx_kp_u_52, __pyx_k_52, sizeof(__pyx_k_52), 0, 1, 0, 0}, - {&__pyx_kp_s_6, __pyx_k_6, sizeof(__pyx_k_6), 0, 0, 1, 0}, - {&__pyx_kp_s_60, __pyx_k_60, sizeof(__pyx_k_60), 0, 0, 1, 0}, - {&__pyx_n_s_61, __pyx_k_61, sizeof(__pyx_k_61), 0, 0, 1, 1}, - {&__pyx_kp_s_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 0, 1, 0}, - {&__pyx_kp_s_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 0, 1, 0}, - {&__pyx_n_s__C, __pyx_k__C, sizeof(__pyx_k__C), 0, 0, 1, 1}, - {&__pyx_n_s__LIBSVM_KERNEL_TYPES, __pyx_k__LIBSVM_KERNEL_TYPES, sizeof(__pyx_k__LIBSVM_KERNEL_TYPES), 0, 0, 1, 1}, - {&__pyx_n_s__MemoryError, __pyx_k__MemoryError, sizeof(__pyx_k__MemoryError), 0, 0, 1, 1}, - {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__SV, __pyx_k__SV, sizeof(__pyx_k__SV), 0, 0, 1, 1}, - {&__pyx_n_s__SV_len, __pyx_k__SV_len, sizeof(__pyx_k__SV_len), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, - {&__pyx_n_s__Y, __pyx_k__Y, sizeof(__pyx_k__Y), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__cache_size, __pyx_k__cache_size, sizeof(__pyx_k__cache_size), 0, 0, 1, 1}, - {&__pyx_n_s__class_weight, __pyx_k__class_weight, sizeof(__pyx_k__class_weight), 0, 0, 1, 1}, - {&__pyx_n_s__class_weight_label, __pyx_k__class_weight_label, sizeof(__pyx_k__class_weight_label), 0, 0, 1, 1}, - {&__pyx_n_s__coef0, __pyx_k__coef0, sizeof(__pyx_k__coef0), 0, 0, 1, 1}, - {&__pyx_n_s__cross_validation, __pyx_k__cross_validation, sizeof(__pyx_k__cross_validation), 0, 0, 1, 1}, - {&__pyx_n_s__dec_values, __pyx_k__dec_values, sizeof(__pyx_k__dec_values), 0, 0, 1, 1}, - {&__pyx_n_s__decision_function, __pyx_k__decision_function, sizeof(__pyx_k__decision_function), 0, 0, 1, 1}, - {&__pyx_n_s__degree, __pyx_k__degree, sizeof(__pyx_k__degree), 0, 0, 1, 1}, - {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, - {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, - {&__pyx_n_s__epsilon, __pyx_k__epsilon, sizeof(__pyx_k__epsilon), 0, 0, 1, 1}, - {&__pyx_n_s__error_msg, __pyx_k__error_msg, sizeof(__pyx_k__error_msg), 0, 0, 1, 1}, - {&__pyx_n_s__error_repl, __pyx_k__error_repl, sizeof(__pyx_k__error_repl), 0, 0, 1, 1}, - {&__pyx_n_s__fit, __pyx_k__fit, sizeof(__pyx_k__fit), 0, 0, 1, 1}, - {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, - {&__pyx_n_s__gamma, __pyx_k__gamma, sizeof(__pyx_k__gamma), 0, 0, 1, 1}, - {&__pyx_n_s__index, __pyx_k__index, sizeof(__pyx_k__index), 0, 0, 1, 1}, - {&__pyx_n_s__int32, __pyx_k__int32, sizeof(__pyx_k__int32), 0, 0, 1, 1}, - {&__pyx_n_s__intercept, __pyx_k__intercept, sizeof(__pyx_k__intercept), 0, 0, 1, 1}, - {&__pyx_n_s__kernel, __pyx_k__kernel, sizeof(__pyx_k__kernel), 0, 0, 1, 1}, - {&__pyx_n_s__kernel_index, __pyx_k__kernel_index, sizeof(__pyx_k__kernel_index), 0, 0, 1, 1}, - {&__pyx_n_s__label, __pyx_k__label, sizeof(__pyx_k__label), 0, 0, 1, 1}, - {&__pyx_n_s__linear, __pyx_k__linear, sizeof(__pyx_k__linear), 0, 0, 1, 1}, - {&__pyx_n_s__model, __pyx_k__model, sizeof(__pyx_k__model), 0, 0, 1, 1}, - {&__pyx_n_s__nSV, __pyx_k__nSV, sizeof(__pyx_k__nSV), 0, 0, 1, 1}, - {&__pyx_n_s__n_class, __pyx_k__n_class, sizeof(__pyx_k__n_class), 0, 0, 1, 1}, - {&__pyx_n_s__n_class_SV, __pyx_k__n_class_SV, sizeof(__pyx_k__n_class_SV), 0, 0, 1, 1}, - {&__pyx_n_s__n_fold, __pyx_k__n_fold, sizeof(__pyx_k__n_fold), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__nr, __pyx_k__nr, sizeof(__pyx_k__nr), 0, 0, 1, 1}, - {&__pyx_n_s__nu, __pyx_k__nu, sizeof(__pyx_k__nu), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__ones, __pyx_k__ones, sizeof(__pyx_k__ones), 0, 0, 1, 1}, - {&__pyx_n_s__param, __pyx_k__param, sizeof(__pyx_k__param), 0, 0, 1, 1}, - {&__pyx_n_s__poly, __pyx_k__poly, sizeof(__pyx_k__poly), 0, 0, 1, 1}, - {&__pyx_n_s__precomputed, __pyx_k__precomputed, sizeof(__pyx_k__precomputed), 0, 0, 1, 1}, - {&__pyx_n_s__predict, __pyx_k__predict, sizeof(__pyx_k__predict), 0, 0, 1, 1}, - {&__pyx_n_s__predict_proba, __pyx_k__predict_proba, sizeof(__pyx_k__predict_proba), 0, 0, 1, 1}, - {&__pyx_n_s__probA, __pyx_k__probA, sizeof(__pyx_k__probA), 0, 0, 1, 1}, - {&__pyx_n_s__probB, __pyx_k__probB, sizeof(__pyx_k__probB), 0, 0, 1, 1}, - {&__pyx_n_s__probability, __pyx_k__probability, sizeof(__pyx_k__probability), 0, 0, 1, 1}, - {&__pyx_n_s__problem, __pyx_k__problem, sizeof(__pyx_k__problem), 0, 0, 1, 1}, - {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__rbf, __pyx_k__rbf, sizeof(__pyx_k__rbf), 0, 0, 1, 1}, - {&__pyx_n_s__replace, __pyx_k__replace, sizeof(__pyx_k__replace), 0, 0, 1, 1}, - {&__pyx_n_s__sample_weight, __pyx_k__sample_weight, sizeof(__pyx_k__sample_weight), 0, 0, 1, 1}, - {&__pyx_n_s__set_verbosity_wrap, __pyx_k__set_verbosity_wrap, sizeof(__pyx_k__set_verbosity_wrap), 0, 0, 1, 1}, - {&__pyx_n_s__shrinking, __pyx_k__shrinking, sizeof(__pyx_k__shrinking), 0, 0, 1, 1}, - {&__pyx_n_s__sigmoid, __pyx_k__sigmoid, sizeof(__pyx_k__sigmoid), 0, 0, 1, 1}, - {&__pyx_n_s__support, __pyx_k__support, sizeof(__pyx_k__support), 0, 0, 1, 1}, - {&__pyx_n_s__support_vectors, __pyx_k__support_vectors, sizeof(__pyx_k__support_vectors), 0, 0, 1, 1}, - {&__pyx_n_s__sv_coef, __pyx_k__sv_coef, sizeof(__pyx_k__sv_coef), 0, 0, 1, 1}, - {&__pyx_n_s__svm_type, __pyx_k__svm_type, sizeof(__pyx_k__svm_type), 0, 0, 1, 1}, - {&__pyx_n_s__target, __pyx_k__target, sizeof(__pyx_k__target), 0, 0, 1, 1}, - {&__pyx_n_s__tol, __pyx_k__tol, sizeof(__pyx_k__tol), 0, 0, 1, 1}, - {&__pyx_n_s__verbosity, __pyx_k__verbosity, sizeof(__pyx_k__verbosity), 0, 0, 1, 1}, + {&__pyx_n_s_C, __pyx_k_C, sizeof(__pyx_k_C), 0, 0, 1, 1}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_n_s_LIBSVM_KERNEL_TYPES, __pyx_k_LIBSVM_KERNEL_TYPES, sizeof(__pyx_k_LIBSVM_KERNEL_TYPES), 0, 0, 1, 1}, + {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_kp_s_Number_of_samples_is_less_than_n, __pyx_k_Number_of_samples_is_less_than_n, sizeof(__pyx_k_Number_of_samples_is_less_than_n), 0, 0, 1, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_SV, __pyx_k_SV, sizeof(__pyx_k_SV), 0, 0, 1, 1}, + {&__pyx_n_s_SV_len, __pyx_k_SV_len, sizeof(__pyx_k_SV_len), 0, 0, 1, 1}, + {&__pyx_kp_s_Seems_we_ve_run_out_of_memory, __pyx_k_Seems_we_ve_run_out_of_memory, sizeof(__pyx_k_Seems_we_ve_run_out_of_memory), 0, 0, 1, 0}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_kp_s_We_ve_run_out_of_memory, __pyx_k_We_ve_run_out_of_memory, sizeof(__pyx_k_We_ve_run_out_of_memory), 0, 0, 1, 0}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_n_s_Y, __pyx_k_Y, sizeof(__pyx_k_Y), 0, 0, 1, 1}, + {&__pyx_n_s_arange, __pyx_k_arange, sizeof(__pyx_k_arange), 0, 0, 1, 1}, + {&__pyx_n_s_cache_size, __pyx_k_cache_size, sizeof(__pyx_k_cache_size), 0, 0, 1, 1}, + {&__pyx_n_s_class_weight, __pyx_k_class_weight, sizeof(__pyx_k_class_weight), 0, 0, 1, 1}, + {&__pyx_n_s_class_weight_label, __pyx_k_class_weight_label, sizeof(__pyx_k_class_weight_label), 0, 0, 1, 1}, + {&__pyx_n_s_coef0, __pyx_k_coef0, sizeof(__pyx_k_coef0), 0, 0, 1, 1}, + {&__pyx_n_s_cross_validation, __pyx_k_cross_validation, sizeof(__pyx_k_cross_validation), 0, 0, 1, 1}, + {&__pyx_n_s_dec_values, __pyx_k_dec_values, sizeof(__pyx_k_dec_values), 0, 0, 1, 1}, + {&__pyx_n_s_decision_function, __pyx_k_decision_function, sizeof(__pyx_k_decision_function), 0, 0, 1, 1}, + {&__pyx_n_s_degree, __pyx_k_degree, sizeof(__pyx_k_degree), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 0, 0, 1, 1}, + {&__pyx_n_s_epsilon, __pyx_k_epsilon, sizeof(__pyx_k_epsilon), 0, 0, 1, 1}, + {&__pyx_kp_s_epsilon_0, __pyx_k_epsilon_0, sizeof(__pyx_k_epsilon_0), 0, 0, 1, 0}, + {&__pyx_n_s_error_msg, __pyx_k_error_msg, sizeof(__pyx_k_error_msg), 0, 0, 1, 1}, + {&__pyx_n_s_error_repl, __pyx_k_error_repl, sizeof(__pyx_k_error_repl), 0, 0, 1, 1}, + {&__pyx_n_s_fit, __pyx_k_fit, sizeof(__pyx_k_fit), 0, 0, 1, 1}, + {&__pyx_n_s_fit_status, __pyx_k_fit_status, sizeof(__pyx_k_fit_status), 0, 0, 1, 1}, + {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 0, 0, 1, 1}, + {&__pyx_n_s_gamma, __pyx_k_gamma, sizeof(__pyx_k_gamma), 0, 0, 1, 1}, + {&__pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_k_home_larsb_src_scikit_learn_skl, sizeof(__pyx_k_home_larsb_src_scikit_learn_skl), 0, 0, 1, 0}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_index, __pyx_k_index, sizeof(__pyx_k_index), 0, 0, 1, 1}, + {&__pyx_n_s_int32, __pyx_k_int32, sizeof(__pyx_k_int32), 0, 0, 1, 1}, + {&__pyx_n_s_intercept, __pyx_k_intercept, sizeof(__pyx_k_intercept), 0, 0, 1, 1}, + {&__pyx_n_s_kernel, __pyx_k_kernel, sizeof(__pyx_k_kernel), 0, 0, 1, 1}, + {&__pyx_n_s_kernel_index, __pyx_k_kernel_index, sizeof(__pyx_k_kernel_index), 0, 0, 1, 1}, + {&__pyx_n_s_linear, __pyx_k_linear, sizeof(__pyx_k_linear), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_max_iter, __pyx_k_max_iter, sizeof(__pyx_k_max_iter), 0, 0, 1, 1}, + {&__pyx_n_s_model, __pyx_k_model, sizeof(__pyx_k_model), 0, 0, 1, 1}, + {&__pyx_n_s_nSV, __pyx_k_nSV, sizeof(__pyx_k_nSV), 0, 0, 1, 1}, + {&__pyx_n_s_n_class, __pyx_k_n_class, sizeof(__pyx_k_n_class), 0, 0, 1, 1}, + {&__pyx_n_s_n_class_SV, __pyx_k_n_class_SV, sizeof(__pyx_k_n_class_SV), 0, 0, 1, 1}, + {&__pyx_n_s_n_fold, __pyx_k_n_fold, sizeof(__pyx_k_n_fold), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_nr, __pyx_k_nr, sizeof(__pyx_k_nr), 0, 0, 1, 1}, + {&__pyx_n_s_nu, __pyx_k_nu, sizeof(__pyx_k_nu), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_ones, __pyx_k_ones, sizeof(__pyx_k_ones), 0, 0, 1, 1}, + {&__pyx_kp_s_p_0, __pyx_k_p_0, sizeof(__pyx_k_p_0), 0, 0, 1, 0}, + {&__pyx_n_s_param, __pyx_k_param, sizeof(__pyx_k_param), 0, 0, 1, 1}, + {&__pyx_n_s_poly, __pyx_k_poly, sizeof(__pyx_k_poly), 0, 0, 1, 1}, + {&__pyx_n_s_precomputed, __pyx_k_precomputed, sizeof(__pyx_k_precomputed), 0, 0, 1, 1}, + {&__pyx_n_s_predict, __pyx_k_predict, sizeof(__pyx_k_predict), 0, 0, 1, 1}, + {&__pyx_n_s_predict_proba, __pyx_k_predict_proba, sizeof(__pyx_k_predict_proba), 0, 0, 1, 1}, + {&__pyx_n_s_probA, __pyx_k_probA, sizeof(__pyx_k_probA), 0, 0, 1, 1}, + {&__pyx_n_s_probB, __pyx_k_probB, sizeof(__pyx_k_probB), 0, 0, 1, 1}, + {&__pyx_n_s_probability, __pyx_k_probability, sizeof(__pyx_k_probability), 0, 0, 1, 1}, + {&__pyx_n_s_problem, __pyx_k_problem, sizeof(__pyx_k_problem), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_releasebuffer, __pyx_k_pyx_releasebuffer, sizeof(__pyx_k_pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s_random_seed, __pyx_k_random_seed, sizeof(__pyx_k_random_seed), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_rbf, __pyx_k_rbf, sizeof(__pyx_k_rbf), 0, 0, 1, 1}, + {&__pyx_n_s_rv, __pyx_k_rv, sizeof(__pyx_k_rv), 0, 0, 1, 1}, + {&__pyx_n_s_sample_weight, __pyx_k_sample_weight, sizeof(__pyx_k_sample_weight), 0, 0, 1, 1}, + {&__pyx_kp_s_sample_weight_and_X_have_incompa, __pyx_k_sample_weight_and_X_have_incompa, sizeof(__pyx_k_sample_weight_and_X_have_incompa), 0, 0, 1, 0}, + {&__pyx_kp_s_sample_weight_has_s_samples_whil, __pyx_k_sample_weight_has_s_samples_whil, sizeof(__pyx_k_sample_weight_has_s_samples_whil), 0, 0, 1, 0}, + {&__pyx_n_s_set_verbosity_wrap, __pyx_k_set_verbosity_wrap, sizeof(__pyx_k_set_verbosity_wrap), 0, 0, 1, 1}, + {&__pyx_n_s_shrinking, __pyx_k_shrinking, sizeof(__pyx_k_shrinking), 0, 0, 1, 1}, + {&__pyx_n_s_sigmoid, __pyx_k_sigmoid, sizeof(__pyx_k_sigmoid), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_svm_libsvm, __pyx_k_sklearn_svm_libsvm, sizeof(__pyx_k_sklearn_svm_libsvm), 0, 0, 1, 1}, + {&__pyx_n_s_support, __pyx_k_support, sizeof(__pyx_k_support), 0, 0, 1, 1}, + {&__pyx_n_s_support_vectors, __pyx_k_support_vectors, sizeof(__pyx_k_support_vectors), 0, 0, 1, 1}, + {&__pyx_n_s_sv_coef, __pyx_k_sv_coef, sizeof(__pyx_k_sv_coef), 0, 0, 1, 1}, + {&__pyx_n_s_svm_type, __pyx_k_svm_type, sizeof(__pyx_k_svm_type), 0, 0, 1, 1}, + {&__pyx_n_s_target, __pyx_k_target, sizeof(__pyx_k_target), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_tol, __pyx_k_tol, sizeof(__pyx_k_tol), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_verbosity, __pyx_k_verbosity, sizeof(__pyx_k_verbosity), 0, 0, 1, 1}, + {&__pyx_n_s_warnings, __pyx_k_warnings, sizeof(__pyx_k_warnings), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_MemoryError = __Pyx_GetName(__pyx_b, __pyx_n_s__MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -8381,1079 +8583,443 @@ static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "sklearn/svm/libsvm.pyx":145 + /* "sklearn/svm/libsvm.pyx":175 * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) * if problem.x == NULL: - * raise MemoryError("Seems we've run out of of memory") # <<<<<<<<<<<<<< - * - * # set parameters - */ - __pyx_k_tuple_7 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_7); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_6)); - PyTuple_SET_ITEM(__pyx_k_tuple_7, 0, ((PyObject *)__pyx_kp_s_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); - - /* "sklearn/svm/libsvm.pyx":157 - * if error_msg: - * # for SVR: epsilon is called p in libsvm - * error_repl = error_msg.replace("p < 0", "epsilon < 0") # <<<<<<<<<<<<<< - * raise ValueError(error_repl) - * + * raise MemoryError("Seems we've run out of memory") # <<<<<<<<<<<<<< + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) */ - __pyx_k_tuple_10 = PyTuple_New(2); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_10); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_s_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_8)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_9)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 1, ((PyObject *)__pyx_kp_s_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_Seems_we_ve_run_out_of_memory); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); - /* "sklearn/svm/libsvm.pyx":187 + /* "sklearn/svm/libsvm.pyx":216 * if kernel_index == 4: * # precomputed kernel * support_vectors = np.empty((0, 0), dtype=np.float64) # <<<<<<<<<<<<<< * else: * support_vectors = np.empty((SV_len, X.shape[1]), dtype=np.float64) */ - __pyx_k_tuple_11 = PyTuple_New(2); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_11); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_11, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_11, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_12); - __Pyx_INCREF(((PyObject *)__pyx_k_tuple_11)); - PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_k_tuple_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); - - /* "sklearn/svm/libsvm.pyx":212 + __pyx_tuple__4 = PyTuple_Pack(2, __pyx_int_0, __pyx_int_0); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_tuple__4); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + + /* "sklearn/svm/libsvm.pyx":234 * copy_probB(probB.data, model, probB.shape) * else: * probA = np.empty(1, dtype=np.float64) # <<<<<<<<<<<<<< * probB = np.empty(0, dtype=np.float64) * copy_probA(probA.data, model, probA.shape) */ - __pyx_k_tuple_13 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_13); - __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 0, __pyx_int_1); - __Pyx_GIVEREF(__pyx_int_1); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_int_1); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); - /* "sklearn/svm/libsvm.pyx":213 + /* "sklearn/svm/libsvm.pyx":235 * else: * probA = np.empty(1, dtype=np.float64) * probB = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * copy_probA(probA.data, model, probA.shape) * else: */ - __pyx_k_tuple_14 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_14); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); - /* "sklearn/svm/libsvm.pyx":216 + /* "sklearn/svm/libsvm.pyx":238 * copy_probA(probA.data, model, probA.shape) * else: * probA = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * probB = np.empty(0, dtype=np.float64) * */ - __pyx_k_tuple_15 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_15); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_15, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); - /* "sklearn/svm/libsvm.pyx":217 + /* "sklearn/svm/libsvm.pyx":239 * else: * probA = np.empty(0, dtype=np.float64) * probB = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * - * # memory deallocation - */ - __pyx_k_tuple_16 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_16); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_16, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); - - /* "sklearn/svm/libsvm.pyx":305 - * dec_values = np.empty(X.shape[0]) - * if copy_predict(X.data, model, X.shape, dec_values.data) < 0: - * raise MemoryError("We've run out of of memory") # <<<<<<<<<<<<<< - * free_model(model) - * return dec_values - */ - __pyx_k_tuple_23 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_23); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_22)); - PyTuple_SET_ITEM(__pyx_k_tuple_23, 0, ((PyObject *)__pyx_kp_s_22)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_22)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_23)); - - /* "sklearn/svm/libsvm.pyx":377 - * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) - * if copy_predict_proba(X.data, model, X.shape, dec_values.data) < 0: - * raise MemoryError("We've run out of of memory") # <<<<<<<<<<<<<< - * # free model and param - * free_model(model) - */ - __pyx_k_tuple_29 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_29); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_22)); - PyTuple_SET_ITEM(__pyx_k_tuple_29, 0, ((PyObject *)__pyx_kp_s_22)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_22)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_29)); - - /* "sklearn/svm/libsvm.pyx":434 - * dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) - * if copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) < 0: - * raise MemoryError("We've run out of of memory") # <<<<<<<<<<<<<< - * # free model and param - * free_model(model) + * svm_free_and_destroy_model(&model) */ - __pyx_k_tuple_35 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_35)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_35); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_22)); - PyTuple_SET_ITEM(__pyx_k_tuple_35, 0, ((PyObject *)__pyx_kp_s_22)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_22)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_35)); + __pyx_tuple__9 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + + /* "sklearn/svm/libsvm.pyx":328 + * rv = copy_predict(X.data, model, X.shape, dec_values.data) + * if rv < 0: + * raise MemoryError("We've run out of memory") # <<<<<<<<<<<<<< + * finally: + * free_model(model) + */ + __pyx_tuple__14 = PyTuple_Pack(1, __pyx_kp_s_We_ve_run_out_of_memory); if (unlikely(!__pyx_tuple__14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_GIVEREF(__pyx_tuple__14); + + /* "sklearn/svm/libsvm.pyx":395 + * rv = copy_predict_proba(X.data, model, X.shape, dec_values.data) + * if rv < 0: + * raise MemoryError("We've run out of memory") # <<<<<<<<<<<<<< + * finally: + * free_model(model) + */ + __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_We_ve_run_out_of_memory); if (unlikely(!__pyx_tuple__19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__19); + __Pyx_GIVEREF(__pyx_tuple__19); + + /* "sklearn/svm/libsvm.pyx":454 + * rv = copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) + * if rv < 0: + * raise MemoryError("We've run out of memory") # <<<<<<<<<<<<<< + * finally: + * free_model(model) + */ + __pyx_tuple__24 = PyTuple_Pack(1, __pyx_kp_s_We_ve_run_out_of_memory); if (unlikely(!__pyx_tuple__24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__24); + __Pyx_GIVEREF(__pyx_tuple__24); - /* "sklearn/svm/libsvm.pyx":514 + /* "sklearn/svm/libsvm.pyx":539 * * if X.shape[0] < n_fold: * raise ValueError("Number of samples is less than number of folds") # <<<<<<<<<<<<<< * * # set problem */ - __pyx_k_tuple_40 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_40)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_40); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_39)); - PyTuple_SET_ITEM(__pyx_k_tuple_40, 0, ((PyObject *)__pyx_kp_s_39)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_39)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_40)); + __pyx_tuple__27 = PyTuple_Pack(1, __pyx_kp_s_Number_of_samples_is_less_than_n); if (unlikely(!__pyx_tuple__27)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__27); + __Pyx_GIVEREF(__pyx_tuple__27); - /* "sklearn/svm/libsvm.pyx":521 + /* "sklearn/svm/libsvm.pyx":546 * &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) * if problem.x == NULL: - * raise MemoryError("Seems we've run out of of memory") # <<<<<<<<<<<<<< - * - * # set parameters + * raise MemoryError("Seems we've run out of memory") # <<<<<<<<<<<<<< + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) */ - __pyx_k_tuple_41 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_41)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_41); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_6)); - PyTuple_SET_ITEM(__pyx_k_tuple_41, 0, ((PyObject *)__pyx_kp_s_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_41)); + __pyx_tuple__28 = PyTuple_Pack(1, __pyx_kp_s_Seems_we_ve_run_out_of_memory); if (unlikely(!__pyx_tuple__28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__28); + __Pyx_GIVEREF(__pyx_tuple__28); - /* "numpy.pxd":214 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_43 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_43)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_43); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_42)); - PyTuple_SET_ITEM(__pyx_k_tuple_43, 0, ((PyObject *)__pyx_kp_u_42)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_42)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_43)); + __pyx_tuple__29 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__29)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__29); + __Pyx_GIVEREF(__pyx_tuple__29); - /* "numpy.pxd":218 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_45 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_45)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_45); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_44)); - PyTuple_SET_ITEM(__pyx_k_tuple_45, 0, ((PyObject *)__pyx_kp_u_44)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_44)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_45)); + __pyx_tuple__30 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__30)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__30); + __Pyx_GIVEREF(__pyx_tuple__30); - /* "numpy.pxd":256 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_47 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_47)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_47); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_46)); - PyTuple_SET_ITEM(__pyx_k_tuple_47, 0, ((PyObject *)__pyx_kp_u_46)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_46)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_47)); + __pyx_tuple__31 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__31)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__31); + __Pyx_GIVEREF(__pyx_tuple__31); - /* "numpy.pxd":798 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_50 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_50)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_50); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_49)); - PyTuple_SET_ITEM(__pyx_k_tuple_50, 0, ((PyObject *)__pyx_kp_u_49)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_49)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_50)); + __pyx_tuple__32 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__32)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__32); + __Pyx_GIVEREF(__pyx_tuple__32); - /* "numpy.pxd":802 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_51 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_51)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_51); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_46)); - PyTuple_SET_ITEM(__pyx_k_tuple_51, 0, ((PyObject *)__pyx_kp_u_46)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_46)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_51)); + __pyx_tuple__33 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__33)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__33); + __Pyx_GIVEREF(__pyx_tuple__33); - /* "numpy.pxd":822 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_53 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_53)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_53); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_52)); - PyTuple_SET_ITEM(__pyx_k_tuple_53, 0, ((PyObject *)__pyx_kp_u_52)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_52)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_53)); + __pyx_tuple__34 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__34)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__34); + __Pyx_GIVEREF(__pyx_tuple__34); - /* "sklearn/svm/libsvm.pyx":54 + /* "sklearn/svm/libsvm.pyx":61 * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * class_weight=np.empty(0), - */ - __pyx_k_tuple_55 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_55)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_55); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_55, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_55)); - - /* "sklearn/svm/libsvm.pyx":56 - * class_weight_label=np.empty(0, dtype=np.int32), * np.ndarray[np.float64_t, ndim=1, mode='c'] * class_weight=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), */ - __pyx_k_tuple_56 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_56)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_56); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_56, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_56)); + __pyx_tuple__35 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__35)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__35); + __Pyx_GIVEREF(__pyx_tuple__35); - /* "sklearn/svm/libsvm.pyx":58 + /* "sklearn/svm/libsvm.pyx":63 * class_weight=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), # <<<<<<<<<<<<<< * int shrinking=1, int probability=0, - * double cache_size=100.): + * double cache_size=100., */ - __pyx_k_tuple_57 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_57)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_57); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_57, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_57)); + __pyx_tuple__36 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__36)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__36); + __Pyx_GIVEREF(__pyx_tuple__36); - /* "sklearn/svm/libsvm.pyx":47 + /* "sklearn/svm/libsvm.pyx":54 * # Wrapper functions * * def fit( # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=2, mode='c'] X, * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, */ - __pyx_k_tuple_58 = PyTuple_New(34); if (unlikely(!__pyx_k_tuple_58)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_58); - __Pyx_INCREF(((PyObject *)__pyx_n_s__X)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 0, ((PyObject *)__pyx_n_s__X)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__X)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__Y)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 1, ((PyObject *)__pyx_n_s__Y)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__Y)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__svm_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 2, ((PyObject *)__pyx_n_s__svm_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__svm_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 3, ((PyObject *)__pyx_n_s__kernel)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__degree)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 4, ((PyObject *)__pyx_n_s__degree)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__degree)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__gamma)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 5, ((PyObject *)__pyx_n_s__gamma)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gamma)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__coef0)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 6, ((PyObject *)__pyx_n_s__coef0)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__coef0)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__tol)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 7, ((PyObject *)__pyx_n_s__tol)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__tol)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__C)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 8, ((PyObject *)__pyx_n_s__C)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__C)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nu)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 9, ((PyObject *)__pyx_n_s__nu)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nu)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__epsilon)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 10, ((PyObject *)__pyx_n_s__epsilon)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__epsilon)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__class_weight_label)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 11, ((PyObject *)__pyx_n_s__class_weight_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__class_weight_label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__class_weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 12, ((PyObject *)__pyx_n_s__class_weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__class_weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sample_weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 13, ((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__shrinking)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 14, ((PyObject *)__pyx_n_s__shrinking)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__shrinking)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probability)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 15, ((PyObject *)__pyx_n_s__probability)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probability)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__cache_size)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 16, ((PyObject *)__pyx_n_s__cache_size)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__cache_size)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__param)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 17, ((PyObject *)__pyx_n_s__param)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__param)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__problem)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 18, ((PyObject *)__pyx_n_s__problem)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__problem)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__model)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 19, ((PyObject *)__pyx_n_s__model)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__model)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__error_msg)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 20, ((PyObject *)__pyx_n_s__error_msg)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__error_msg)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_len)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 21, ((PyObject *)__pyx_n_s__SV_len)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_len)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nr)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 22, ((PyObject *)__pyx_n_s__nr)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nr)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel_index)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 23, ((PyObject *)__pyx_n_s__kernel_index)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel_index)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__error_repl)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 24, ((PyObject *)__pyx_n_s__error_repl)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__error_repl)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_class)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 25, ((PyObject *)__pyx_n_s__n_class)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_class)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sv_coef)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 26, ((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__intercept)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 27, ((PyObject *)__pyx_n_s__intercept)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__intercept)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__support)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 28, ((PyObject *)__pyx_n_s__support)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__support)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__support_vectors)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 29, ((PyObject *)__pyx_n_s__support_vectors)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__support_vectors)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_class_SV)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 30, ((PyObject *)__pyx_n_s__n_class_SV)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_class_SV)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__label)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 31, ((PyObject *)__pyx_n_s__label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probA)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 32, ((PyObject *)__pyx_n_s__probA)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probA)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probB)); - PyTuple_SET_ITEM(__pyx_k_tuple_58, 33, ((PyObject *)__pyx_n_s__probB)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probB)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_58)); - __pyx_k_codeobj_59 = (PyObject*)__Pyx_PyCode_New(17, 0, 34, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_58, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_60, __pyx_n_s__fit, 47, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_59)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/svm/libsvm.pyx":233 + __pyx_tuple__37 = PyTuple_Pack(36, __pyx_n_s_X, __pyx_n_s_Y, __pyx_n_s_svm_type, __pyx_n_s_kernel, __pyx_n_s_degree, __pyx_n_s_gamma, __pyx_n_s_coef0, __pyx_n_s_tol, __pyx_n_s_C, __pyx_n_s_nu, __pyx_n_s_epsilon, __pyx_n_s_class_weight, __pyx_n_s_sample_weight, __pyx_n_s_shrinking, __pyx_n_s_probability, __pyx_n_s_cache_size, __pyx_n_s_max_iter, __pyx_n_s_random_seed, __pyx_n_s_param, __pyx_n_s_problem, __pyx_n_s_model, __pyx_n_s_error_msg, __pyx_n_s_SV_len, __pyx_n_s_nr, __pyx_n_s_kernel_index, __pyx_n_s_class_weight_label, __pyx_n_s_error_repl, __pyx_n_s_fit_status, __pyx_n_s_n_class, __pyx_n_s_sv_coef, __pyx_n_s_intercept, __pyx_n_s_support, __pyx_n_s_support_vectors, __pyx_n_s_n_class_SV, __pyx_n_s_probA, __pyx_n_s_probB); if (unlikely(!__pyx_tuple__37)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__37); + __Pyx_GIVEREF(__pyx_tuple__37); + __pyx_codeobj__38 = (PyObject*)__Pyx_PyCode_New(18, 0, 36, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__37, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_fit, 54, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__38)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/svm/libsvm.pyx":276 + * np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef, * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - * int svm_type=0, str kernel='rbf', int degree=3, + * int svm_type=0, kernel='rbf', int degree=3, */ - __pyx_k_tuple_62 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_62)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_62); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_62, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_62)); + __pyx_tuple__39 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__39)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__39); + __Pyx_GIVEREF(__pyx_tuple__39); - /* "sklearn/svm/libsvm.pyx":234 - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, + /* "sklearn/svm/libsvm.pyx":277 + * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), # <<<<<<<<<<<<<< - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - */ - __pyx_k_tuple_63 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_63)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_63); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_63, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_63)); - - /* "sklearn/svm/libsvm.pyx":239 - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * class_weight=np.empty(0), + * int svm_type=0, kernel='rbf', int degree=3, + * double gamma=0.1, double coef0=0., */ - __pyx_k_tuple_64 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_64)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_64); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_64, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_64)); + __pyx_tuple__40 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__40)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__40); + __Pyx_GIVEREF(__pyx_tuple__40); - /* "sklearn/svm/libsvm.pyx":241 - * class_weight_label=np.empty(0, dtype=np.int32), + /* "sklearn/svm/libsvm.pyx":281 + * double gamma=0.1, double coef0=0., * np.ndarray[np.float64_t, ndim=1, mode='c'] * class_weight=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), */ - __pyx_k_tuple_65 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_65)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_65); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_65, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_65)); + __pyx_tuple__41 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__41)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__41); + __Pyx_GIVEREF(__pyx_tuple__41); - /* "sklearn/svm/libsvm.pyx":243 + /* "sklearn/svm/libsvm.pyx":283 * class_weight=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), # <<<<<<<<<<<<<< - * int shrinking=0, int probability=0, * double cache_size=100.): + * """ */ - __pyx_k_tuple_66 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_66)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_66); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_66, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_66)); + __pyx_tuple__42 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__42)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__42); + __Pyx_GIVEREF(__pyx_tuple__42); - /* "sklearn/svm/libsvm.pyx":226 + /* "sklearn/svm/libsvm.pyx":270 * * * def predict(np.ndarray[np.float64_t, ndim=2, mode='c'] X, # <<<<<<<<<<<<<< * np.ndarray[np.int32_t, ndim=1, mode='c'] support, * np.ndarray[np.float64_t, ndim=2, mode='c'] SV, */ - __pyx_k_tuple_67 = PyTuple_New(28); if (unlikely(!__pyx_k_tuple_67)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_67); - __Pyx_INCREF(((PyObject *)__pyx_n_s__X)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 0, ((PyObject *)__pyx_n_s__X)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__X)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__support)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 1, ((PyObject *)__pyx_n_s__support)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__support)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 2, ((PyObject *)__pyx_n_s__SV)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nSV)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 3, ((PyObject *)__pyx_n_s__nSV)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nSV)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sv_coef)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 4, ((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__intercept)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 5, ((PyObject *)__pyx_n_s__intercept)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__intercept)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__label)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 6, ((PyObject *)__pyx_n_s__label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probA)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 7, ((PyObject *)__pyx_n_s__probA)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probA)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probB)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 8, ((PyObject *)__pyx_n_s__probB)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probB)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__svm_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 9, ((PyObject *)__pyx_n_s__svm_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__svm_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 10, ((PyObject *)__pyx_n_s__kernel)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__degree)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 11, ((PyObject *)__pyx_n_s__degree)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__degree)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__gamma)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 12, ((PyObject *)__pyx_n_s__gamma)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gamma)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__coef0)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 13, ((PyObject *)__pyx_n_s__coef0)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__coef0)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__tol)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 14, ((PyObject *)__pyx_n_s__tol)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__tol)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__C)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 15, ((PyObject *)__pyx_n_s__C)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__C)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nu)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 16, ((PyObject *)__pyx_n_s__nu)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nu)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__epsilon)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 17, ((PyObject *)__pyx_n_s__epsilon)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__epsilon)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__class_weight_label)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 18, ((PyObject *)__pyx_n_s__class_weight_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__class_weight_label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__class_weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 19, ((PyObject *)__pyx_n_s__class_weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__class_weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sample_weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 20, ((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__shrinking)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 21, ((PyObject *)__pyx_n_s__shrinking)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__shrinking)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probability)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 22, ((PyObject *)__pyx_n_s__probability)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probability)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__cache_size)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 23, ((PyObject *)__pyx_n_s__cache_size)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__cache_size)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__dec_values)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 24, ((PyObject *)__pyx_n_s__dec_values)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__dec_values)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__param)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 25, ((PyObject *)__pyx_n_s__param)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__param)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__model)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 26, ((PyObject *)__pyx_n_s__model)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__model)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel_index)); - PyTuple_SET_ITEM(__pyx_k_tuple_67, 27, ((PyObject *)__pyx_n_s__kernel_index)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel_index)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_67)); - __pyx_k_codeobj_68 = (PyObject*)__Pyx_PyCode_New(24, 0, 28, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_67, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_60, __pyx_n_s__predict, 226, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_68)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/svm/libsvm.pyx":319 + __pyx_tuple__43 = PyTuple_Pack(21, __pyx_n_s_X, __pyx_n_s_support, __pyx_n_s_SV, __pyx_n_s_nSV, __pyx_n_s_sv_coef, __pyx_n_s_intercept, __pyx_n_s_probA, __pyx_n_s_probB, __pyx_n_s_svm_type, __pyx_n_s_kernel, __pyx_n_s_degree, __pyx_n_s_gamma, __pyx_n_s_coef0, __pyx_n_s_class_weight, __pyx_n_s_sample_weight, __pyx_n_s_cache_size, __pyx_n_s_dec_values, __pyx_n_s_param, __pyx_n_s_model, __pyx_n_s_rv, __pyx_n_s_class_weight_label); if (unlikely(!__pyx_tuple__43)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__43); + __Pyx_GIVEREF(__pyx_tuple__43); + __pyx_codeobj__44 = (PyObject*)__Pyx_PyCode_New(16, 0, 21, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__43, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_predict, 270, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__44)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/svm/libsvm.pyx":342 + * np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef, * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), * int svm_type=0, str kernel='rbf', int degree=3, */ - __pyx_k_tuple_69 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_69)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_69); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_69, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_69)); + __pyx_tuple__45 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__45)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 342; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__45); + __Pyx_GIVEREF(__pyx_tuple__45); - /* "sklearn/svm/libsvm.pyx":320 - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, + /* "sklearn/svm/libsvm.pyx":343 + * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), # <<<<<<<<<<<<<< * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - */ - __pyx_k_tuple_70 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_70)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_70); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_70, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_70)); - - /* "sklearn/svm/libsvm.pyx":325 - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * class_weight=np.empty(0), + * double gamma=0.1, double coef0=0., */ - __pyx_k_tuple_71 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_71)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_71); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_71, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_71)); + __pyx_tuple__46 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__46)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__46); + __Pyx_GIVEREF(__pyx_tuple__46); - /* "sklearn/svm/libsvm.pyx":327 - * class_weight_label=np.empty(0, dtype=np.int32), + /* "sklearn/svm/libsvm.pyx":347 + * double gamma=0.1, double coef0=0., * np.ndarray[np.float64_t, ndim=1, mode='c'] * class_weight=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), */ - __pyx_k_tuple_72 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_72)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_72); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_72, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_72)); + __pyx_tuple__47 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__47)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__47); + __Pyx_GIVEREF(__pyx_tuple__47); - /* "sklearn/svm/libsvm.pyx":329 + /* "sklearn/svm/libsvm.pyx":349 * class_weight=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), # <<<<<<<<<<<<<< - * int shrinking=0, int probability=0, * double cache_size=100.): + * """ */ - __pyx_k_tuple_73 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_73)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_73); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_73, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_73)); + __pyx_tuple__48 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__48)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__48); + __Pyx_GIVEREF(__pyx_tuple__48); - /* "sklearn/svm/libsvm.pyx":311 + /* "sklearn/svm/libsvm.pyx":335 * * * def predict_proba( # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=2, mode='c'] X, * np.ndarray[np.int32_t, ndim=1, mode='c'] support, */ - __pyx_k_tuple_74 = PyTuple_New(29); if (unlikely(!__pyx_k_tuple_74)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_74); - __Pyx_INCREF(((PyObject *)__pyx_n_s__X)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 0, ((PyObject *)__pyx_n_s__X)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__X)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__support)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 1, ((PyObject *)__pyx_n_s__support)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__support)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 2, ((PyObject *)__pyx_n_s__SV)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nSV)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 3, ((PyObject *)__pyx_n_s__nSV)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nSV)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sv_coef)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 4, ((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__intercept)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 5, ((PyObject *)__pyx_n_s__intercept)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__intercept)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__label)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 6, ((PyObject *)__pyx_n_s__label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probA)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 7, ((PyObject *)__pyx_n_s__probA)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probA)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probB)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 8, ((PyObject *)__pyx_n_s__probB)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probB)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__svm_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 9, ((PyObject *)__pyx_n_s__svm_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__svm_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 10, ((PyObject *)__pyx_n_s__kernel)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__degree)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 11, ((PyObject *)__pyx_n_s__degree)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__degree)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__gamma)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 12, ((PyObject *)__pyx_n_s__gamma)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gamma)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__coef0)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 13, ((PyObject *)__pyx_n_s__coef0)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__coef0)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__tol)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 14, ((PyObject *)__pyx_n_s__tol)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__tol)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__C)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 15, ((PyObject *)__pyx_n_s__C)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__C)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nu)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 16, ((PyObject *)__pyx_n_s__nu)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nu)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__epsilon)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 17, ((PyObject *)__pyx_n_s__epsilon)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__epsilon)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__class_weight_label)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 18, ((PyObject *)__pyx_n_s__class_weight_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__class_weight_label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__class_weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 19, ((PyObject *)__pyx_n_s__class_weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__class_weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sample_weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 20, ((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__shrinking)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 21, ((PyObject *)__pyx_n_s__shrinking)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__shrinking)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probability)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 22, ((PyObject *)__pyx_n_s__probability)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probability)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__cache_size)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 23, ((PyObject *)__pyx_n_s__cache_size)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__cache_size)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__dec_values)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 24, ((PyObject *)__pyx_n_s__dec_values)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__dec_values)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__param)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 25, ((PyObject *)__pyx_n_s__param)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__param)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__model)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 26, ((PyObject *)__pyx_n_s__model)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__model)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel_index)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 27, ((PyObject *)__pyx_n_s__kernel_index)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel_index)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_class)); - PyTuple_SET_ITEM(__pyx_k_tuple_74, 28, ((PyObject *)__pyx_n_s__n_class)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_class)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_74)); - __pyx_k_codeobj_75 = (PyObject*)__Pyx_PyCode_New(24, 0, 29, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_74, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_60, __pyx_n_s__predict_proba, 311, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_75)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/svm/libsvm.pyx":391 + __pyx_tuple__49 = PyTuple_Pack(22, __pyx_n_s_X, __pyx_n_s_support, __pyx_n_s_SV, __pyx_n_s_nSV, __pyx_n_s_sv_coef, __pyx_n_s_intercept, __pyx_n_s_probA, __pyx_n_s_probB, __pyx_n_s_svm_type, __pyx_n_s_kernel, __pyx_n_s_degree, __pyx_n_s_gamma, __pyx_n_s_coef0, __pyx_n_s_class_weight, __pyx_n_s_sample_weight, __pyx_n_s_cache_size, __pyx_n_s_dec_values, __pyx_n_s_param, __pyx_n_s_model, __pyx_n_s_class_weight_label, __pyx_n_s_rv, __pyx_n_s_n_class); if (unlikely(!__pyx_tuple__49)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__49); + __Pyx_GIVEREF(__pyx_tuple__49); + __pyx_codeobj__50 = (PyObject*)__Pyx_PyCode_New(16, 0, 22, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__49, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_predict_proba, 335, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__50)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/svm/libsvm.pyx":409 + * np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef, * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - * int svm_type=0, str kernel='rbf', int degree=3, + * int svm_type=0, kernel='rbf', int degree=3, */ - __pyx_k_tuple_76 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_76)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_76); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_76, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_76)); + __pyx_tuple__51 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__51)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 409; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__51); + __Pyx_GIVEREF(__pyx_tuple__51); - /* "sklearn/svm/libsvm.pyx":392 - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, + /* "sklearn/svm/libsvm.pyx":410 + * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), # <<<<<<<<<<<<<< - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - */ - __pyx_k_tuple_77 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_77)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_77); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_77, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_77)); - - /* "sklearn/svm/libsvm.pyx":397 - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * class_weight=np.empty(0), + * int svm_type=0, kernel='rbf', int degree=3, + * double gamma=0.1, double coef0=0., */ - __pyx_k_tuple_78 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_78)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_78); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_78, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_78)); + __pyx_tuple__52 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__52)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__52); + __Pyx_GIVEREF(__pyx_tuple__52); - /* "sklearn/svm/libsvm.pyx":399 - * class_weight_label=np.empty(0, dtype=np.int32), + /* "sklearn/svm/libsvm.pyx":414 + * double gamma=0.1, double coef0=0., * np.ndarray[np.float64_t, ndim=1, mode='c'] * class_weight=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), */ - __pyx_k_tuple_79 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_79)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_79); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_79, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_79)); + __pyx_tuple__53 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__53)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__53); + __Pyx_GIVEREF(__pyx_tuple__53); - /* "sklearn/svm/libsvm.pyx":401 + /* "sklearn/svm/libsvm.pyx":416 * class_weight=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), # <<<<<<<<<<<<<< - * int shrinking=0, int probability=0, * double cache_size=100.): + * """ */ - __pyx_k_tuple_80 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_80)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_80); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_80, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_80)); + __pyx_tuple__54 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__54)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__54); + __Pyx_GIVEREF(__pyx_tuple__54); - /* "sklearn/svm/libsvm.pyx":383 + /* "sklearn/svm/libsvm.pyx":402 * * * def decision_function( # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=2, mode='c'] X, * np.ndarray[np.int32_t, ndim=1, mode='c'] support, */ - __pyx_k_tuple_81 = PyTuple_New(29); if (unlikely(!__pyx_k_tuple_81)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_81); - __Pyx_INCREF(((PyObject *)__pyx_n_s__X)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 0, ((PyObject *)__pyx_n_s__X)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__X)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__support)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 1, ((PyObject *)__pyx_n_s__support)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__support)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 2, ((PyObject *)__pyx_n_s__SV)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nSV)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 3, ((PyObject *)__pyx_n_s__nSV)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nSV)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sv_coef)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 4, ((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__intercept)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 5, ((PyObject *)__pyx_n_s__intercept)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__intercept)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__label)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 6, ((PyObject *)__pyx_n_s__label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probA)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 7, ((PyObject *)__pyx_n_s__probA)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probA)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probB)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 8, ((PyObject *)__pyx_n_s__probB)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probB)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__svm_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 9, ((PyObject *)__pyx_n_s__svm_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__svm_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 10, ((PyObject *)__pyx_n_s__kernel)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__degree)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 11, ((PyObject *)__pyx_n_s__degree)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__degree)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__gamma)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 12, ((PyObject *)__pyx_n_s__gamma)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gamma)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__coef0)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 13, ((PyObject *)__pyx_n_s__coef0)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__coef0)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__tol)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 14, ((PyObject *)__pyx_n_s__tol)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__tol)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__C)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 15, ((PyObject *)__pyx_n_s__C)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__C)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nu)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 16, ((PyObject *)__pyx_n_s__nu)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nu)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__epsilon)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 17, ((PyObject *)__pyx_n_s__epsilon)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__epsilon)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__class_weight_label)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 18, ((PyObject *)__pyx_n_s__class_weight_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__class_weight_label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__class_weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 19, ((PyObject *)__pyx_n_s__class_weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__class_weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sample_weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 20, ((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__shrinking)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 21, ((PyObject *)__pyx_n_s__shrinking)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__shrinking)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probability)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 22, ((PyObject *)__pyx_n_s__probability)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probability)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__cache_size)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 23, ((PyObject *)__pyx_n_s__cache_size)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__cache_size)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__dec_values)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 24, ((PyObject *)__pyx_n_s__dec_values)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__dec_values)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__param)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 25, ((PyObject *)__pyx_n_s__param)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__param)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__model)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 26, ((PyObject *)__pyx_n_s__model)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__model)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_class)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 27, ((PyObject *)__pyx_n_s__n_class)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_class)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel_index)); - PyTuple_SET_ITEM(__pyx_k_tuple_81, 28, ((PyObject *)__pyx_n_s__kernel_index)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel_index)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_81)); - __pyx_k_codeobj_82 = (PyObject*)__Pyx_PyCode_New(24, 0, 29, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_81, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_60, __pyx_n_s__decision_function, 383, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_82)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/svm/libsvm.pyx":447 - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * class_weight=np.empty(0), - */ - __pyx_k_tuple_83 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_83)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_83); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_83, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_83)); + __pyx_tuple__55 = PyTuple_Pack(22, __pyx_n_s_X, __pyx_n_s_support, __pyx_n_s_SV, __pyx_n_s_nSV, __pyx_n_s_sv_coef, __pyx_n_s_intercept, __pyx_n_s_probA, __pyx_n_s_probB, __pyx_n_s_svm_type, __pyx_n_s_kernel, __pyx_n_s_degree, __pyx_n_s_gamma, __pyx_n_s_coef0, __pyx_n_s_class_weight, __pyx_n_s_sample_weight, __pyx_n_s_cache_size, __pyx_n_s_dec_values, __pyx_n_s_param, __pyx_n_s_model, __pyx_n_s_n_class, __pyx_n_s_class_weight_label, __pyx_n_s_rv); if (unlikely(!__pyx_tuple__55)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__55); + __Pyx_GIVEREF(__pyx_tuple__55); + __pyx_codeobj__56 = (PyObject*)__Pyx_PyCode_New(16, 0, 22, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__55, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_decision_function, 402, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__56)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/svm/libsvm.pyx":449 - * class_weight_label=np.empty(0, dtype=np.int32), + /* "sklearn/svm/libsvm.pyx":468 + * double C=1., double nu=0.5, double epsilon=0.1, * np.ndarray[np.float64_t, ndim=1, mode='c'] * class_weight=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), */ - __pyx_k_tuple_84 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_84)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_84); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_84, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_84)); + __pyx_tuple__57 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__57)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__57); + __Pyx_GIVEREF(__pyx_tuple__57); - /* "sklearn/svm/libsvm.pyx":451 + /* "sklearn/svm/libsvm.pyx":470 * class_weight=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), # <<<<<<<<<<<<<< - * int shrinking=0, int probability=0, double cache_size=100.): - * """ + * int shrinking=0, int probability=0, double cache_size=100., + * int max_iter=-1, */ - __pyx_k_tuple_85 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_85)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_85); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_85, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_85)); + __pyx_tuple__58 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_tuple__58)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__58); + __Pyx_GIVEREF(__pyx_tuple__58); - /* "sklearn/svm/libsvm.pyx":440 + /* "sklearn/svm/libsvm.pyx":461 * * * def cross_validation( # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=2, mode='c'] X, * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, */ - __pyx_k_tuple_86 = PyTuple_New(26); if (unlikely(!__pyx_k_tuple_86)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_86); - __Pyx_INCREF(((PyObject *)__pyx_n_s__X)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 0, ((PyObject *)__pyx_n_s__X)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__X)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__Y)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 1, ((PyObject *)__pyx_n_s__Y)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__Y)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_fold)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 2, ((PyObject *)__pyx_n_s__n_fold)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_fold)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__svm_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 3, ((PyObject *)__pyx_n_s__svm_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__svm_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 4, ((PyObject *)__pyx_n_s__kernel)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__degree)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 5, ((PyObject *)__pyx_n_s__degree)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__degree)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__gamma)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 6, ((PyObject *)__pyx_n_s__gamma)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gamma)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__coef0)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 7, ((PyObject *)__pyx_n_s__coef0)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__coef0)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__tol)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 8, ((PyObject *)__pyx_n_s__tol)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__tol)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__C)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 9, ((PyObject *)__pyx_n_s__C)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__C)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nu)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 10, ((PyObject *)__pyx_n_s__nu)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nu)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__epsilon)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 11, ((PyObject *)__pyx_n_s__epsilon)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__epsilon)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__class_weight_label)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 12, ((PyObject *)__pyx_n_s__class_weight_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__class_weight_label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__class_weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 13, ((PyObject *)__pyx_n_s__class_weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__class_weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sample_weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 14, ((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__shrinking)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 15, ((PyObject *)__pyx_n_s__shrinking)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__shrinking)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probability)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 16, ((PyObject *)__pyx_n_s__probability)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probability)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__cache_size)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 17, ((PyObject *)__pyx_n_s__cache_size)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__cache_size)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__param)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 18, ((PyObject *)__pyx_n_s__param)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__param)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__problem)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 19, ((PyObject *)__pyx_n_s__problem)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__problem)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__model)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 20, ((PyObject *)__pyx_n_s__model)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__model)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__error_msg)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 21, ((PyObject *)__pyx_n_s__error_msg)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__error_msg)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_len)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 22, ((PyObject *)__pyx_n_s__SV_len)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_len)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nr)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 23, ((PyObject *)__pyx_n_s__nr)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nr)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel_index)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 24, ((PyObject *)__pyx_n_s__kernel_index)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel_index)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__target)); - PyTuple_SET_ITEM(__pyx_k_tuple_86, 25, ((PyObject *)__pyx_n_s__target)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__target)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_86)); - __pyx_k_codeobj_87 = (PyObject*)__Pyx_PyCode_New(18, 0, 26, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_86, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_60, __pyx_n_s__cross_validation, 440, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_87)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_tuple__59 = PyTuple_Pack(28, __pyx_n_s_X, __pyx_n_s_Y, __pyx_n_s_n_fold, __pyx_n_s_svm_type, __pyx_n_s_kernel, __pyx_n_s_degree, __pyx_n_s_gamma, __pyx_n_s_coef0, __pyx_n_s_tol, __pyx_n_s_C, __pyx_n_s_nu, __pyx_n_s_epsilon, __pyx_n_s_class_weight, __pyx_n_s_sample_weight, __pyx_n_s_shrinking, __pyx_n_s_probability, __pyx_n_s_cache_size, __pyx_n_s_max_iter, __pyx_n_s_random_seed, __pyx_n_s_param, __pyx_n_s_problem, __pyx_n_s_model, __pyx_n_s_error_msg, __pyx_n_s_SV_len, __pyx_n_s_nr, __pyx_n_s_kernel_index, __pyx_n_s_class_weight_label, __pyx_n_s_target); if (unlikely(!__pyx_tuple__59)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__59); + __Pyx_GIVEREF(__pyx_tuple__59); + __pyx_codeobj__60 = (PyObject*)__Pyx_PyCode_New(19, 0, 28, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__59, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_cross_validation, 461, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__60)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/svm/libsvm.pyx":542 + /* "sklearn/svm/libsvm.pyx":572 * * * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< * """ * Control verbosity of libsvm library */ - __pyx_k_tuple_88 = PyTuple_New(2); if (unlikely(!__pyx_k_tuple_88)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_88); - __Pyx_INCREF(((PyObject *)__pyx_n_s__verbosity)); - PyTuple_SET_ITEM(__pyx_k_tuple_88, 0, ((PyObject *)__pyx_n_s__verbosity)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__verbosity)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__verbosity)); - PyTuple_SET_ITEM(__pyx_k_tuple_88, 1, ((PyObject *)__pyx_n_s__verbosity)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__verbosity)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_88)); - __pyx_k_codeobj_89 = (PyObject*)__Pyx_PyCode_New(1, 0, 2, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_88, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_60, __pyx_n_s__set_verbosity_wrap, 542, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_89)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_tuple__61 = PyTuple_Pack(2, __pyx_n_s_verbosity, __pyx_n_s_verbosity); if (unlikely(!__pyx_tuple__61)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__61); + __Pyx_GIVEREF(__pyx_tuple__61); + __pyx_codeobj__62 = (PyObject*)__Pyx_PyCode_New(1, 0, 2, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__61, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_set_verbosity_wrap, 572, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__62)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -9463,11 +9029,10 @@ static int __Pyx_InitCachedConstants(void) { static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_4 = PyInt_FromLong(4); if (unlikely(!__pyx_int_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_4 = PyInt_FromLong(4); if (unlikely(!__pyx_int_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -9483,8 +9048,9 @@ PyMODINIT_FUNC PyInit_libsvm(void) { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -9517,22 +9083,34 @@ PyMODINIT_FUNC PyInit_libsvm(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("libsvm"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_54), 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("libsvm"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_Binding_for_libsvm_skl_These_ar), 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif if (__pyx_module_is_main_sklearn__svm__libsvm) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.svm.libsvm")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.svm.libsvm", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } } + #endif /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ @@ -9542,11 +9120,18 @@ PyMODINIT_FUNC PyInit_libsvm(void) /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ @@ -9554,595 +9139,466 @@ PyMODINIT_FUNC PyInit_libsvm(void) /* "sklearn/svm/libsvm.pyx":33 * """ * + * import warnings # <<<<<<<<<<<<<< + * import numpy as np + * cimport numpy as np + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_warnings, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_warnings, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/svm/libsvm.pyx":34 + * + * import warnings * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np * cimport libsvm */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":41 + /* "sklearn/svm/libsvm.pyx":43 + * pass + * + * np.import_array() # <<<<<<<<<<<<<< + * + * + */ + import_array(); + + /* "sklearn/svm/libsvm.pyx":48 * ################################################################################ * # Internal variables * LIBSVM_KERNEL_TYPES = ['linear', 'poly', 'rbf', 'sigmoid', 'precomputed'] # <<<<<<<<<<<<<< * * */ - __pyx_t_1 = PyList_New(5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)__pyx_n_s__linear)); - PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s__linear)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__linear)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__poly)); - PyList_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_n_s__poly)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__poly)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__rbf)); - PyList_SET_ITEM(__pyx_t_1, 2, ((PyObject *)__pyx_n_s__rbf)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__rbf)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sigmoid)); - PyList_SET_ITEM(__pyx_t_1, 3, ((PyObject *)__pyx_n_s__sigmoid)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sigmoid)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__precomputed)); - PyList_SET_ITEM(__pyx_t_1, 4, ((PyObject *)__pyx_n_s__precomputed)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__precomputed)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__LIBSVM_KERNEL_TYPES, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - - /* "sklearn/svm/libsvm.pyx":54 - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * class_weight=np.empty(0), - */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__int32); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_k_tuple_55), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_1 = ((PyArrayObject *)__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; + __pyx_t_1 = PyList_New(5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s_linear); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_linear); + __Pyx_GIVEREF(__pyx_n_s_linear); + __Pyx_INCREF(__pyx_n_s_poly); + PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_poly); + __Pyx_GIVEREF(__pyx_n_s_poly); + __Pyx_INCREF(__pyx_n_s_rbf); + PyList_SET_ITEM(__pyx_t_1, 2, __pyx_n_s_rbf); + __Pyx_GIVEREF(__pyx_n_s_rbf); + __Pyx_INCREF(__pyx_n_s_sigmoid); + PyList_SET_ITEM(__pyx_t_1, 3, __pyx_n_s_sigmoid); + __Pyx_GIVEREF(__pyx_n_s_sigmoid); + __Pyx_INCREF(__pyx_n_s_precomputed); + PyList_SET_ITEM(__pyx_t_1, 4, __pyx_n_s_precomputed); + __Pyx_GIVEREF(__pyx_n_s_precomputed); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_LIBSVM_KERNEL_TYPES, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":56 - * class_weight_label=np.empty(0, dtype=np.int32), + /* "sklearn/svm/libsvm.pyx":61 + * double C=1., double nu=0.5, double epsilon=0.1, * np.ndarray[np.float64_t, ndim=1, mode='c'] * class_weight=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_56), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_2 = ((PyArrayObject *)__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__35, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_ = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":58 + /* "sklearn/svm/libsvm.pyx":63 * class_weight=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), # <<<<<<<<<<<<<< * int shrinking=1, int probability=0, - * double cache_size=100.): + * double cache_size=100., */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_57), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_3 = ((PyArrayObject *)__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__36, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__2 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":47 + /* "sklearn/svm/libsvm.pyx":54 * # Wrapper functions * * def fit( # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=2, mode='c'] X, * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, */ - __pyx_t_4 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_1fit, NULL, __pyx_n_s_61); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__fit, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_1fit, NULL, __pyx_n_s_sklearn_svm_libsvm); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_fit, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":233 + /* "sklearn/svm/libsvm.pyx":276 + * np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef, * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - * int svm_type=0, str kernel='rbf', int degree=3, + * int svm_type=0, kernel='rbf', int degree=3, */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_62), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_17 = ((PyArrayObject *)__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__39, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__10 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":234 - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, + /* "sklearn/svm/libsvm.pyx":277 + * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), # <<<<<<<<<<<<<< - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, + * int svm_type=0, kernel='rbf', int degree=3, + * double gamma=0.1, double coef0=0., */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_63), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 234; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_18 = ((PyArrayObject *)__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "sklearn/svm/libsvm.pyx":239 - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * class_weight=np.empty(0), - */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__40, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__int32); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_64), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_19 = ((PyArrayObject *)__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__11 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":241 - * class_weight_label=np.empty(0, dtype=np.int32), + /* "sklearn/svm/libsvm.pyx":281 + * double gamma=0.1, double coef0=0., * np.ndarray[np.float64_t, ndim=1, mode='c'] * class_weight=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_k_tuple_65), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_20 = ((PyArrayObject *)__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__41, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__12 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":243 + /* "sklearn/svm/libsvm.pyx":283 * class_weight=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), # <<<<<<<<<<<<<< - * int shrinking=0, int probability=0, * double cache_size=100.): + * """ */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_k_tuple_66), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_21 = ((PyArrayObject *)__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__42, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__13 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":226 + /* "sklearn/svm/libsvm.pyx":270 * * * def predict(np.ndarray[np.float64_t, ndim=2, mode='c'] X, # <<<<<<<<<<<<<< * np.ndarray[np.int32_t, ndim=1, mode='c'] support, * np.ndarray[np.float64_t, ndim=2, mode='c'] SV, */ - __pyx_t_3 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_3predict, NULL, __pyx_n_s_61); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__predict, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_3predict, NULL, __pyx_n_s_sklearn_svm_libsvm); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_predict, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":319 + /* "sklearn/svm/libsvm.pyx":342 + * np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef, * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), * int svm_type=0, str kernel='rbf', int degree=3, */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_k_tuple_69), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_24 = ((PyArrayObject *)__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 342; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 342; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__45, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 342; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 342; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__15 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":320 - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, + /* "sklearn/svm/libsvm.pyx":343 + * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), # <<<<<<<<<<<<<< * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, + * double gamma=0.1, double coef0=0., */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_k_tuple_70), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_25 = ((PyArrayObject *)__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - - /* "sklearn/svm/libsvm.pyx":325 - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * class_weight=np.empty(0), - */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__int32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__46, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_k_tuple_71), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_26 = ((PyArrayObject *)__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - - /* "sklearn/svm/libsvm.pyx":327 - * class_weight_label=np.empty(0, dtype=np.int32), + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__16 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/svm/libsvm.pyx":347 + * double gamma=0.1, double coef0=0., * np.ndarray[np.float64_t, ndim=1, mode='c'] * class_weight=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__47, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_k_tuple_72), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_27 = ((PyArrayObject *)__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__17 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":329 + /* "sklearn/svm/libsvm.pyx":349 * class_weight=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), # <<<<<<<<<<<<<< - * int shrinking=0, int probability=0, * double cache_size=100.): + * """ */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__48, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_k_tuple_73), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_28 = ((PyArrayObject *)__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__18 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":311 + /* "sklearn/svm/libsvm.pyx":335 * * * def predict_proba( # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=2, mode='c'] X, * np.ndarray[np.int32_t, ndim=1, mode='c'] support, */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_5predict_proba, NULL, __pyx_n_s_61); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__predict_proba, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_5predict_proba, NULL, __pyx_n_s_sklearn_svm_libsvm); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_predict_proba, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 335; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":391 + /* "sklearn/svm/libsvm.pyx":409 + * np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef, * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - * int svm_type=0, str kernel='rbf', int degree=3, + * int svm_type=0, kernel='rbf', int degree=3, */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 409; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 409; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__51, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 409; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_k_tuple_76), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_30 = ((PyArrayObject *)__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 409; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__20 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":392 - * np.ndarray[np.int32_t, ndim=1, mode='c'] label, + /* "sklearn/svm/libsvm.pyx":410 + * np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, * np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), # <<<<<<<<<<<<<< - * int svm_type=0, str kernel='rbf', int degree=3, - * double gamma=0.1, double coef0=0., double tol=1e-3, - */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_k_tuple_77), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_31 = ((PyArrayObject *)__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - - /* "sklearn/svm/libsvm.pyx":397 - * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * class_weight=np.empty(0), + * int svm_type=0, kernel='rbf', int degree=3, + * double gamma=0.1, double coef0=0., */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_k_tuple_78), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__52, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_32 = ((PyArrayObject *)__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__21 = ((PyArrayObject *)__pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":399 - * class_weight_label=np.empty(0, dtype=np.int32), + /* "sklearn/svm/libsvm.pyx":414 + * double gamma=0.1, double coef0=0., * np.ndarray[np.float64_t, ndim=1, mode='c'] * class_weight=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_k_tuple_79), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__53, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_33 = ((PyArrayObject *)__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__22 = ((PyArrayObject *)__pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":401 + /* "sklearn/svm/libsvm.pyx":416 * class_weight=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), # <<<<<<<<<<<<<< - * int shrinking=0, int probability=0, * double cache_size=100.): + * """ */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_k_tuple_80), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__54, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_34 = ((PyArrayObject *)__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__23 = ((PyArrayObject *)__pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":383 + /* "sklearn/svm/libsvm.pyx":402 * * * def decision_function( # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=2, mode='c'] X, * np.ndarray[np.int32_t, ndim=1, mode='c'] support, */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_7decision_function, NULL, __pyx_n_s_61); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_7decision_function, NULL, __pyx_n_s_sklearn_svm_libsvm); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__decision_function, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_decision_function, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":447 + /* "sklearn/svm/libsvm.pyx":468 * double C=1., double nu=0.5, double epsilon=0.1, - * np.ndarray[np.int32_t, ndim=1, mode='c'] - * class_weight_label=np.empty(0, dtype=np.int32), # <<<<<<<<<<<<<< - * np.ndarray[np.float64_t, ndim=1, mode='c'] - * class_weight=np.empty(0), - */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__int32); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_k_tuple_83), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_36 = ((PyArrayObject *)__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "sklearn/svm/libsvm.pyx":449 - * class_weight_label=np.empty(0, dtype=np.int32), * np.ndarray[np.float64_t, ndim=1, mode='c'] * class_weight=np.empty(0), # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_84), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_37 = ((PyArrayObject *)__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__57, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__25 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":451 + /* "sklearn/svm/libsvm.pyx":470 * class_weight=np.empty(0), * np.ndarray[np.float64_t, ndim=1, mode='c'] * sample_weight=np.empty(0), # <<<<<<<<<<<<<< - * int shrinking=0, int probability=0, double cache_size=100.): - * """ + * int shrinking=0, int probability=0, double cache_size=100., + * int max_iter=-1, */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_85), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_k_38 = ((PyArrayObject *)__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_tuple__58, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k__26 = ((PyArrayObject *)__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":440 + /* "sklearn/svm/libsvm.pyx":461 * * * def cross_validation( # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=2, mode='c'] X, * np.ndarray[np.float64_t, ndim=1, mode='c'] Y, */ - __pyx_t_4 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_9cross_validation, NULL, __pyx_n_s_61); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__cross_validation, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_9cross_validation, NULL, __pyx_n_s_sklearn_svm_libsvm); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_cross_validation, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm.pyx":542 + /* "sklearn/svm/libsvm.pyx":572 * * * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< * """ * Control verbosity of libsvm library */ - __pyx_t_4 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_11set_verbosity_wrap, NULL, __pyx_n_s_61); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__set_verbosity_wrap, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_6libsvm_11set_verbosity_wrap, NULL, __pyx_n_s_sklearn_svm_libsvm); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_set_verbosity_wrap, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "sklearn/svm/libsvm.pyx":1 * """ # <<<<<<<<<<<<<< * Binding for libsvm_skl * ---------------------- */ - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_4)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":974 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -10153,8 +9609,6 @@ PyMODINIT_FUNC PyInit_libsvm(void) __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); if (__pyx_m) { __Pyx_AddTraceback("init sklearn.svm.libsvm", __pyx_clineno, __pyx_lineno, __pyx_filename); Py_DECREF(__pyx_m); __pyx_m = 0; @@ -10187,17 +9641,15 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { } #endif /* CYTHON_REFNANNY */ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif } return result; } @@ -10222,7 +9674,7 @@ static void __Pyx_RaiseArgtupleInvalid( more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } @@ -10236,7 +9688,7 @@ static void __Pyx_RaiseDoubleKeywordsError( "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); + PyString_AsString(kw_name)); #endif } @@ -10257,57 +9709,81 @@ static int __Pyx_ParseOptionalKeywords( while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; } - if (*name) { + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { values[name-argnames] = value; - } else { - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } + break; } + name++; } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; } } return 0; arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); + __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); + "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", + "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", @@ -10317,23 +9793,29 @@ static int __Pyx_ParseOptionalKeywords( return -1; } -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { - if (Py_TYPE(obj) == type) return 1; + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif } else { - if (PyObject_TypeCheck(obj, type)) return 1; + if (likely(PyObject_TypeCheck(obj, type))) return 1; } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } @@ -10396,7 +9878,8 @@ static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { - case 'b': return "'char'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; @@ -10464,7 +9947,7 @@ typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); @@ -10496,7 +9979,7 @@ typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif -static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); @@ -10516,7 +9999,9 @@ static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, int is_complex) { } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'h': case 'i': + case 'c': + return 'H'; + case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case 'B': case 'H': case 'I': case 'L': case 'Q': @@ -10611,13 +10096,16 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ctx->head->parent_offset = parent_offset; continue; } - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } @@ -10671,8 +10159,10 @@ __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; while (*ts && *ts != ')') { - if (isspace(*ts)) - continue; + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; /* not a 'break' in the loop */ + } number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) @@ -10857,7 +10347,7 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate( } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; @@ -10874,9 +10364,49 @@ static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { __Pyx_ReleaseBuffer(info); } +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; +#endif + result = (*call)(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + Py_LeaveRecursiveCall(); +#endif + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); + PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) @@ -10887,7 +10417,7 @@ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { } static void __Pyx_RaiseBufferFallbackError(void) { - PyErr_Format(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); } @@ -10926,53 +10456,57 @@ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyOb static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) + if (PyClass_Check(type)) { #else - if (!PyType_Check(type)) + if (PyType_Check(type)) { #endif - { - if (value != Py_None) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } #endif } __Pyx_ErrRestore(type, value, tb); @@ -10985,6 +10519,7 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, } #else /* Python 3+ */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -11002,31 +10537,68 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } +#if PY_VERSION_HEX >= 0x03030000 if (cause) { +#else + if (cause && cause != Py_None) { +#endif PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; - } - else if (PyExceptionInstance_Check(cause)) { + } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); @@ -11040,10 +10612,144 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } } bad: + Py_XDECREF(owned_instance); return; } #endif +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + length = strlen(cstring); + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } + #endif + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; +#else + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); +#endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +#else + PyErr_GetExcInfo(type, value, tb); +#endif +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(type, value, tb); +#endif +} + static CYTHON_INLINE long __Pyx_div_long(long a, long b) { long q = a / b; long r = a - q*b; @@ -11051,134 +10757,98 @@ static CYTHON_INLINE long __Pyx_div_long(long a, long b) { return q; } -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); - } else { - __Pyx_RaiseTooManyValuesError(index); - } -} - #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - PyObject *getbuffer_cobj; - #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (getbuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_getbuffer"))) { - getbufferproc func; - - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (getbufferproc) PyCapsule_GetPointer(getbuffer_cobj, "getbuffer(obj, view, flags)"); - #else - func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); - #endif - Py_DECREF(getbuffer_cobj); - if (!func) - goto fail; - - return func(obj, view, flags); - } else { - PyErr_Clear(); + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } } #endif - - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); #if PY_VERSION_HEX < 0x02060000 fail: #endif - return -1; } - static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; - PyObject *releasebuffer_cobj; - if (!obj) return; - #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (releasebuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_releasebuffer"))) { - releasebufferproc func; - - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (releasebufferproc) PyCapsule_GetPointer(releasebuffer_cobj, "releasebuffer(obj, view)"); - #else - func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); - #endif - - Py_DECREF(releasebuffer_cobj); - - if (!func) - goto fail; - - func(obj, view); - return; - } else { - PyErr_Clear(); + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } } #endif - goto nofail; - #if PY_VERSION_HEX < 0x02060000 fail: #endif PyErr_WriteUnraisable(obj); - nofail: Py_DECREF(obj); view->obj = NULL; } - #endif /* PY_MAJOR_VERSION < 3 */ - static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; + #endif if (from_list) list = from_list; else { @@ -11198,13 +10868,17 @@ static void __Pyx_ReleaseBuffer(Py_buffer *view) { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { - /* try package relative import first */ + #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(1); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; @@ -11215,12 +10889,17 @@ static void __Pyx_ReleaseBuffer(Py_buffer *view) { } #endif if (!module) { + #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif } } #else @@ -11232,33 +10911,178 @@ static void __Pyx_ReleaseBuffer(Py_buffer *view) { name, global_dict, empty_dict, list, NULL); #endif bad: - Py_XDECREF(empty_list); + #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t val) { - const Py_intptr_t neg_one = (Py_intptr_t)-1, const_zero = (Py_intptr_t)0; - const int is_unsigned = const_zero < neg_one; - if ((sizeof(Py_intptr_t) == sizeof(char)) || - (sizeof(Py_intptr_t) == sizeof(short))) { - return PyInt_FromLong((long)val); - } else if ((sizeof(Py_intptr_t) == sizeof(int)) || - (sizeof(Py_intptr_t) == sizeof(long))) { - if (is_unsigned) - return PyLong_FromUnsignedLong((unsigned long)val); - else - return PyInt_FromLong((long)val); - } else if (sizeof(Py_intptr_t) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); - else - return PyLong_FromLongLong((PY_LONG_LONG)val); +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \ + { \ + func_type value = func(x); \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + PyErr_SetString(PyExc_OverflowError, \ + (is_unsigned && unlikely(value < zero)) ? \ + "can't convert negative value to " #target_type : \ + "value too large to convert to " #target_type); \ + return (target_type) -1; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(int) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(Py_intptr_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } @@ -11503,401 +11327,127 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t val) { #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; - } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; - } - return (unsigned short)val; - } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; - } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; - } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; - } - return (short)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; - } - return (signed char)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); } - return (signed short)val; - } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); } - return (signed int)val; } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); } - return (int)__Pyx_PyInt_AsLong(x); } -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; + "can't convert negative value to long"); + return (long) -1; } - return (unsigned long)PyLong_AsUnsignedLong(x); - } else { - return (unsigned long)PyLong_AsLong(x); - } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; + return (long) val; } - return (unsigned PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)val; - } else + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); - return (long)-1; + return (long) -1; } - return (long)PyLong_AsUnsignedLong(x); - } else { - return (long)PyLong_AsLong(x); - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong) } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { - return (PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)val; - } else +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong) } - return (signed long)PyLong_AsUnsignedLong(x); - } else { - return (signed long)PyLong_AsLong(x); - } - } else { - signed long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; } - return (signed PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; } } else { - signed PY_LONG_LONG val; + long val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } @@ -11922,6 +11472,23 @@ static int __Pyx_check_binary_version(void) { return 0; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -11931,6 +11498,10 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; @@ -11946,11 +11517,23 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", + "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } - if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -11960,9 +11543,9 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", + "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } @@ -11974,23 +11557,6 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - py_name = __Pyx_PyIdentifier_FromString(name); - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; -} -#endif - static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { @@ -12183,27 +11749,90 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } - -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ +#if !CYTHON_COMPILING_IN_PYPY +#if PY_VERSION_HEX >= 0x02060000 + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -12219,13 +11848,13 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", + "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; @@ -12237,16 +11866,40 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + #if PY_VERSION_HEX < 0x02060000 + return PyInt_AsSsize_t(b); + #else + return PyLong_AsSsize_t(b); + #endif + } + x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) @@ -12261,17 +11914,5 @@ static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #endif } -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; -} - #endif /* Py_PYTHON_H */ diff --git a/sklearn/svm/libsvm.pxd b/sklearn/svm/libsvm.pxd index adea7b26cb561..2664a335a372f 100644 --- a/sklearn/svm/libsvm.pxd +++ b/sklearn/svm/libsvm.pxd @@ -24,6 +24,8 @@ cdef extern from "svm.h": double p # for EPSILON_SVR int shrinking # use the shrinking heuristics int probability # do probability estimates + int max_iter # ceiling on Solver runtime + int random_seed # seed for random generator in probability estimation cdef struct svm_problem: int l @@ -32,9 +34,9 @@ cdef extern from "svm.h": double *W # instance weights char *svm_check_parameter(svm_problem *, svm_parameter *) - svm_model *svm_train(svm_problem *, svm_parameter *) + svm_model *svm_train(svm_problem *, svm_parameter *, int *) nogil void svm_free_and_destroy_model(svm_model** model_ptr_ptr) - void svm_cross_validation(svm_problem *, svm_parameter *, int nr_fold, double *target) + void svm_cross_validation(svm_problem *, svm_parameter *, int nr_fold, double *target) nogil cdef extern from "libsvm_helper.c": @@ -42,22 +44,22 @@ cdef extern from "libsvm_helper.c": svm_node **dense_to_sparse (char *, np.npy_intp *) void set_parameter (svm_parameter *, int , int , int , double, double , double , double , double , double, - double, int, int, int, char *, char *) + double, int, int, int, char *, char *, int, + int) void set_problem (svm_problem *, char *, char *, char *, np.npy_intp *, int) svm_model *set_model (svm_parameter *, int, char *, np.npy_intp *, char *, np.npy_intp *, np.npy_intp *, char *, - char *, char *, char *, char *, char *) + char *, char *, char *, char *) void copy_sv_coef (char *, svm_model *) void copy_intercept (char *, svm_model *, np.npy_intp *) void copy_SV (char *, svm_model *, np.npy_intp *) int copy_support (char *data, svm_model *model) - int copy_predict (char *, svm_model *, np.npy_intp *, char *) - int copy_predict_proba (char *, svm_model *, np.npy_intp *, char *) - int copy_predict_values(char *, svm_model *, np.npy_intp *, char *, int) + int copy_predict (char *, svm_model *, np.npy_intp *, char *) nogil + int copy_predict_proba (char *, svm_model *, np.npy_intp *, char *) nogil + int copy_predict_values(char *, svm_model *, np.npy_intp *, char *, int) nogil void copy_nSV (char *, svm_model *) - void copy_label (char *, svm_model *) void copy_probA (char *, svm_model *, np.npy_intp *) void copy_probB (char *, svm_model *, np.npy_intp *) np.npy_intp get_l (svm_model *) diff --git a/sklearn/svm/libsvm.pyx b/sklearn/svm/libsvm.pyx index 685d83e818857..589cf1e8ac150 100644 --- a/sklearn/svm/libsvm.pyx +++ b/sklearn/svm/libsvm.pyx @@ -2,7 +2,7 @@ Binding for libsvm_skl ---------------------- -These are the bindings for libsvm_skl, which is a fork o libsvm[1] +These are the bindings for libsvm_skl, which is a fork of libsvm[1] that adds to libsvm some capabilities, like index of support vectors and efficient representation of dense matrices. @@ -30,11 +30,18 @@ Authors Gael Varoquaux """ +import warnings import numpy as np cimport numpy as np cimport libsvm from libc.stdlib cimport free +cdef extern from *: + ctypedef struct svm_parameter: + pass + +np.import_array() + ################################################################################ # Internal variables @@ -50,52 +57,78 @@ def fit( int svm_type=0, str kernel='rbf', int degree=3, double gamma=0.1, double coef0=0., double tol=1e-3, double C=1., double nu=0.5, double epsilon=0.1, - np.ndarray[np.int32_t, ndim=1, mode='c'] - class_weight_label=np.empty(0, dtype=np.int32), np.ndarray[np.float64_t, ndim=1, mode='c'] class_weight=np.empty(0), np.ndarray[np.float64_t, ndim=1, mode='c'] sample_weight=np.empty(0), int shrinking=1, int probability=0, - double cache_size=100.): + double cache_size=100., + int max_iter=-1, + int random_seed=0): """ Train the model using libsvm (low-level method) Parameters ---------- - X: array-like, dtype=float64, size=[n_samples, n_features] + X : array-like, dtype=float64, size=[n_samples, n_features] - Y: array, dtype=float64, size=[n_samples] + Y : array, dtype=float64, size=[n_samples] target vector - svm_type : {0, 1, 2, 3, 4} + svm_type : {0, 1, 2, 3, 4}, optional Type of SVM: C_SVC, NuSVC, OneClassSVM, EpsilonSVR or NuSVR - respectevely. + respectively. 0 by default. - kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'} + kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'}, optional Kernel to use in the model: linear, polynomial, RBF, sigmoid - or precomputed. + or precomputed. 'rbf' by default. - degree : int32 + degree : int32, optional Degree of the polynomial kernel (only relevant if kernel is - set to polynomial) + set to polynomial), 3 by default. - gamma : float64 + gamma : float64, optional Gamma parameter in RBF kernel (only relevant if kernel is set - to RBF) + to RBF). 0.1 by default. - coef0 : float64 - Independent parameter in poly/sigmoid kernel. + coef0 : float64, optional + Independent parameter in poly/sigmoid kernel. 0 by default. - tol : float64 - Stopping criteria. + tol : float64, optional + Numeric stopping criterion (WRITEME). 1e-3 by default. - C : float64 - C parameter in C-Support Vector Classification + C : float64, optional + C parameter in C-Support Vector Classification. 1 by default. + + nu : float64, optional + 0.5 by default. + + epsilon : double, optional + 0.1 by default. + + class_weight : array, dtype float64, shape (n_classes,), optional + np.empty(0) by default. + + sample_weight : array, dtype float64, shape (n_samples,), optional + np.empty(0) by default. + + shrinking : int, optional + 1 by default. + + probability : int, optional + 0 by default. + + cache_size : float64, optional + Cache size for gram matrix columns (in megabytes). 100 by default. - nu : float64 + max_iter : int (-1 for no limit), optional. + Stop solver after this many iterations regardless of accuracy + (XXX Currently there is no API to know whether this kicked in.) + -1 by default. - cache_size : float64 + random_seed : int, optional + Seed for the random number generator used for probability estimates. + 0 by default. Returns ------- @@ -115,8 +148,6 @@ def fit( intercept : array intercept in decision function - label : labels for different classes (only relevant in classification). - probA, probB : array probability estimates, empty array for probability=False """ @@ -124,7 +155,7 @@ def fit( cdef svm_parameter param cdef svm_problem problem cdef svm_model *model - cdef char *error_msg + cdef const char *error_msg cdef np.npy_intp SV_len cdef np.npy_intp nr @@ -137,43 +168,41 @@ def fit( "sample_weight has %s samples while X has %s" % \ (sample_weight.shape[0], X.shape[0]) - # set problem kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) set_problem( &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) if problem.x == NULL: - raise MemoryError("Seems we've run out of of memory") - - # set parameters + raise MemoryError("Seems we've run out of memory") + cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) set_parameter( ¶m, svm_type, kernel_index, degree, gamma, coef0, nu, cache_size, C, tol, epsilon, shrinking, probability, class_weight.shape[0], - class_weight_label.data, class_weight.data) + class_weight_label.data, class_weight.data, max_iter, random_seed) - # check parameters error_msg = svm_check_parameter(&problem, ¶m) if error_msg: # for SVR: epsilon is called p in libsvm - error_repl = error_msg.replace("p < 0", "epsilon < 0") + error_repl = error_msg.decode('utf-8').replace("p < 0", "epsilon < 0") raise ValueError(error_repl) # this does the real work - model = svm_train(&problem, ¶m) + cdef int fit_status = 0 + with nogil: + model = svm_train(&problem, ¶m, &fit_status) # from here until the end, we just copy the data returned by # svm_train SV_len = get_l(model) n_class = get_nr(model) - # copy model.sv_coef cdef np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef sv_coef = np.empty((n_class-1, SV_len), dtype=np.float64) copy_sv_coef (sv_coef.data, model) - # copy model.rho into the intercept # the intercept is just model.rho but with sign changed cdef np.ndarray[np.float64_t, ndim=1, mode='c'] intercept - intercept = np.empty(n_class*(n_class-1)/2, dtype=np.float64) + intercept = np.empty(int((n_class*(n_class-1))/2), dtype=np.float64) copy_intercept (intercept.data, model, intercept.shape) cdef np.ndarray[np.int32_t, ndim=1, mode='c'] support @@ -189,24 +218,17 @@ def fit( support_vectors = np.empty((SV_len, X.shape[1]), dtype=np.float64) copy_SV(support_vectors.data, model, support_vectors.shape) - # copy model.nSV # TODO: do only in classification cdef np.ndarray[np.int32_t, ndim=1, mode='c'] n_class_SV n_class_SV = np.empty(n_class, dtype=np.int32) copy_nSV(n_class_SV.data, model) - # copy label - cdef np.ndarray[np.int32_t, ndim=1, mode='c'] label - label = np.empty((n_class), dtype=np.int32) - copy_label(label.data, model) - - # copy probabilities cdef np.ndarray[np.float64_t, ndim=1, mode='c'] probA cdef np.ndarray[np.float64_t, ndim=1, mode='c'] probB if probability != 0: if svm_type < 2: # SVC and NuSVC - probA = np.empty(n_class*(n_class-1)/2, dtype=np.float64) - probB = np.empty(n_class*(n_class-1)/2, dtype=np.float64) + probA = np.empty(int(n_class*(n_class-1)/2), dtype=np.float64) + probB = np.empty(int(n_class*(n_class-1)/2), dtype=np.float64) copy_probB(probB.data, model, probB.shape) else: probA = np.empty(1, dtype=np.float64) @@ -216,11 +238,33 @@ def fit( probA = np.empty(0, dtype=np.float64) probB = np.empty(0, dtype=np.float64) - # memory deallocation svm_free_and_destroy_model(&model) free(problem.x) - return support, support_vectors, n_class_SV, sv_coef, intercept, label, \ - probA, probB + + return (support, support_vectors, n_class_SV, sv_coef, intercept, + probA, probB, fit_status) + + +cdef void set_predict_params( + svm_parameter *param, int svm_type, kernel, int degree, double gamma, + double coef0, double cache_size, int probability, int nr_weight, + char *weight_label, char *weight) except *: + """Fill param with prediction time-only parameters.""" + + # training-time only parameters + cdef double C = .0 + cdef double epsilon = .1 + cdef int max_iter = 0 + cdef double nu = .5 + cdef int shrinking = 0 + cdef double tol = .1 + cdef int random_seed = -1 + + kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) + + set_parameter(param, svm_type, kernel_index, degree, gamma, coef0, nu, + cache_size, C, tol, epsilon, shrinking, probability, + nr_weight, weight_label, weight, max_iter, random_seed) def predict(np.ndarray[np.float64_t, ndim=2, mode='c'] X, @@ -229,19 +273,14 @@ def predict(np.ndarray[np.float64_t, ndim=2, mode='c'] X, np.ndarray[np.int32_t, ndim=1, mode='c'] nSV, np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef, np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, - np.ndarray[np.int32_t, ndim=1, mode='c'] label, np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - int svm_type=0, str kernel='rbf', int degree=3, - double gamma=0.1, double coef0=0., double tol=1e-3, - double C=1., double nu=0.5, double epsilon=0.1, - np.ndarray[np.int32_t, ndim=1, mode='c'] - class_weight_label=np.empty(0, dtype=np.int32), + int svm_type=0, kernel='rbf', int degree=3, + double gamma=0.1, double coef0=0., np.ndarray[np.float64_t, ndim=1, mode='c'] class_weight=np.empty(0), np.ndarray[np.float64_t, ndim=1, mode='c'] sample_weight=np.empty(0), - int shrinking=0, int probability=0, double cache_size=100.): """ Predict target values of X given a model (low-level method) @@ -249,63 +288,48 @@ def predict(np.ndarray[np.float64_t, ndim=2, mode='c'] X, Parameters ---------- X: array-like, dtype=float, size=[n_samples, n_features] - svm_type : {0, 1, 2, 3, 4} Type of SVM: C SVC, nu SVC, one class, epsilon SVR, nu SVR - kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'} - Kernel to use in the model: linear, polynomial, RBF, sigmoid - or precomputed. - + Type of kernel. degree : int - Degree of the polynomial kernel (only relevant if kernel is - set to polynomial) - + Degree of the polynomial kernel. gamma : float - Gamma parameter in RBF kernel (only relevant if kernel is set - to RBF) - + Gamma parameter in RBF kernel. coef0 : float Independent parameter in poly/sigmoid kernel. - eps : float - Stopping criteria. - - C : float - C parameter in C-Support Vector Classification - - Returns ------- dec_values : array predicted values. - - - TODO: probably there's no point in setting some parameters, like - cache_size or weights. """ cdef np.ndarray[np.float64_t, ndim=1, mode='c'] dec_values cdef svm_parameter param cdef svm_model *model + cdef int rv - kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) - set_parameter(¶m, svm_type, kernel_index, degree, gamma, coef0, - nu, cache_size, C, tol, epsilon, shrinking, - probability, class_weight.shape[0], - class_weight_label.data, class_weight.data) + cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) + set_predict_params(¶m, svm_type, kernel, degree, gamma, coef0, + cache_size, 0, class_weight.shape[0], + class_weight_label.data, class_weight.data) model = set_model(¶m, nSV.shape[0], SV.data, SV.shape, support.data, support.shape, sv_coef.strides, - sv_coef.data, intercept.data, nSV.data, - label.data, probA.data, probB.data) + sv_coef.data, intercept.data, nSV.data, probA.data, probB.data) #TODO: use check_model - dec_values = np.empty(X.shape[0]) - if copy_predict(X.data, model, X.shape, dec_values.data) < 0: - raise MemoryError("We've run out of of memory") - free_model(model) - return dec_values + try: + dec_values = np.empty(X.shape[0]) + with nogil: + rv = copy_predict(X.data, model, X.shape, dec_values.data) + if rv < 0: + raise MemoryError("We've run out of memory") + finally: + free_model(model) + return dec_values def predict_proba( @@ -315,19 +339,14 @@ def predict_proba( np.ndarray[np.int32_t, ndim=1, mode='c'] nSV, np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef, np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, - np.ndarray[np.int32_t, ndim=1, mode='c'] label, np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), int svm_type=0, str kernel='rbf', int degree=3, - double gamma=0.1, double coef0=0., double tol=1e-3, - double C=1., double nu=0.5, double epsilon=0.1, - np.ndarray[np.int32_t, ndim=1, mode='c'] - class_weight_label=np.empty(0, dtype=np.int32), + double gamma=0.1, double coef0=0., np.ndarray[np.float64_t, ndim=1, mode='c'] class_weight=np.empty(0), np.ndarray[np.float64_t, ndim=1, mode='c'] sample_weight=np.empty(0), - int shrinking=0, int probability=0, double cache_size=100.): """ Predict probabilities @@ -345,12 +364,8 @@ def predict_proba( Parameters ---------- X: array-like, dtype=float - Y: array - target vector - kernel : {'linear', 'rbf', 'poly', 'sigmoid', 'precomputed'} - Returns ------- dec_values : array @@ -359,24 +374,28 @@ def predict_proba( cdef np.ndarray[np.float64_t, ndim=2, mode='c'] dec_values cdef svm_parameter param cdef svm_model *model + cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) + cdef int rv - kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) - set_parameter(¶m, svm_type, kernel_index, degree, gamma, - coef0, nu, cache_size, C, tol, epsilon, shrinking, - probability, class_weight.shape[0], class_weight_label.data, - class_weight.data) - + set_predict_params(¶m, svm_type, kernel, degree, gamma, coef0, + cache_size, 1, class_weight.shape[0], + class_weight_label.data, class_weight.data) model = set_model(¶m, nSV.shape[0], SV.data, SV.shape, support.data, support.shape, sv_coef.strides, sv_coef.data, intercept.data, nSV.data, - label.data, probA.data, probB.data) + probA.data, probB.data) cdef np.npy_intp n_class = get_nr(model) - dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) - if copy_predict_proba(X.data, model, X.shape, dec_values.data) < 0: - raise MemoryError("We've run out of of memory") - # free model and param - free_model(model) + try: + dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) + with nogil: + rv = copy_predict_proba(X.data, model, X.shape, dec_values.data) + if rv < 0: + raise MemoryError("We've run out of memory") + finally: + free_model(model) + return dec_values @@ -387,19 +406,14 @@ def decision_function( np.ndarray[np.int32_t, ndim=1, mode='c'] nSV, np.ndarray[np.float64_t, ndim=2, mode='c'] sv_coef, np.ndarray[np.float64_t, ndim=1, mode='c'] intercept, - np.ndarray[np.int32_t, ndim=1, mode='c'] label, np.ndarray[np.float64_t, ndim=1, mode='c'] probA=np.empty(0), np.ndarray[np.float64_t, ndim=1, mode='c'] probB=np.empty(0), - int svm_type=0, str kernel='rbf', int degree=3, - double gamma=0.1, double coef0=0., double tol=1e-3, - double C=1., double nu=0.5, double epsilon=0.1, - np.ndarray[np.int32_t, ndim=1, mode='c'] - class_weight_label=np.empty(0, dtype=np.int32), + int svm_type=0, kernel='rbf', int degree=3, + double gamma=0.1, double coef0=0., np.ndarray[np.float64_t, ndim=1, mode='c'] class_weight=np.empty(0), np.ndarray[np.float64_t, ndim=1, mode='c'] sample_weight=np.empty(0), - int shrinking=0, int probability=0, double cache_size=100.): """ Predict margin (libsvm name for this is predict_values) @@ -412,16 +426,19 @@ def decision_function( cdef svm_model *model cdef np.npy_intp n_class - kernel_index = LIBSVM_KERNEL_TYPES.index(kernel) - set_parameter(¶m, svm_type, kernel_index, degree, gamma, - coef0, nu, cache_size, C, tol, epsilon, shrinking, - probability, class_weight.shape[0], class_weight_label.data, - class_weight.data) + cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) + + cdef int rv + + set_predict_params(¶m, svm_type, kernel, degree, gamma, coef0, + cache_size, 0, class_weight.shape[0], + class_weight_label.data, class_weight.data) model = set_model(¶m, nSV.shape[0], SV.data, SV.shape, support.data, support.shape, sv_coef.strides, sv_coef.data, intercept.data, nSV.data, - label.data, probA.data, probB.data) + probA.data, probB.data) if svm_type > 1: n_class = 1 @@ -429,11 +446,15 @@ def decision_function( n_class = get_nr(model) n_class = n_class * (n_class - 1) / 2 - dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) - if copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) < 0: - raise MemoryError("We've run out of of memory") - # free model and param - free_model(model) + try: + dec_values = np.empty((X.shape[0], n_class), dtype=np.float64) + with nogil: + rv = copy_predict_values(X.data, model, X.shape, dec_values.data, n_class) + if rv < 0: + raise MemoryError("We've run out of memory") + finally: + free_model(model) + return dec_values @@ -443,13 +464,13 @@ def cross_validation( int n_fold, svm_type=0, str kernel='rbf', int degree=3, double gamma=0.1, double coef0=0., double tol=1e-3, double C=1., double nu=0.5, double epsilon=0.1, - np.ndarray[np.int32_t, ndim=1, mode='c'] - class_weight_label=np.empty(0, dtype=np.int32), np.ndarray[np.float64_t, ndim=1, mode='c'] class_weight=np.empty(0), np.ndarray[np.float64_t, ndim=1, mode='c'] sample_weight=np.empty(0), - int shrinking=0, int probability=0, double cache_size=100.): + int shrinking=0, int probability=0, double cache_size=100., + int max_iter=-1, + int random_seed=0): """ Binding of the cross-validation routine (low-level routine) @@ -489,6 +510,10 @@ def cross_validation( cache_size : float + random_seed : int, optional + Seed for the random number generator used for probability estimates. + 0 by default. + Returns ------- target : array, float @@ -498,7 +523,7 @@ def cross_validation( cdef svm_parameter param cdef svm_problem problem cdef svm_model *model - cdef char *error_msg + cdef const char *error_msg cdef np.npy_intp SV_len cdef np.npy_intp nr @@ -518,24 +543,29 @@ def cross_validation( set_problem( &problem, X.data, Y.data, sample_weight.data, X.shape, kernel_index) if problem.x == NULL: - raise MemoryError("Seems we've run out of of memory") + raise MemoryError("Seems we've run out of memory") + cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) # set parameters set_parameter( ¶m, svm_type, kernel_index, degree, gamma, coef0, nu, cache_size, C, tol, tol, shrinking, probability, class_weight.shape[0], class_weight_label.data, - class_weight.data) + class_weight.data, max_iter, random_seed) error_msg = svm_check_parameter(&problem, ¶m); if error_msg: raise ValueError(error_msg) cdef np.ndarray[np.float64_t, ndim=1, mode='c'] target - target = np.empty((X.shape[0]), dtype=np.float64) - svm_cross_validation(&problem, ¶m, n_fold, target.data) + try: + target = np.empty((X.shape[0]), dtype=np.float64) + with nogil: + svm_cross_validation(&problem, ¶m, n_fold, target.data) + finally: + free(problem.x) - free(problem.x) return target diff --git a/sklearn/svm/libsvm_sparse.c b/sklearn/svm/libsvm_sparse.c index e11a292a8f589..6faa83f219704 100644 --- a/sklearn/svm/libsvm_sparse.c +++ b/sklearn/svm/libsvm_sparse.c @@ -1,6 +1,18 @@ -/* Generated by Cython 0.16 on Thu Aug 30 17:40:54 2012 */ +/* Generated by Cython 0.19.1 on Mon Jan 6 15:23:21 2014 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. @@ -11,7 +23,6 @@ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -23,22 +34,18 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif - #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 @@ -46,28 +53,28 @@ #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif - -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyCFunction_Call PyObject_Call -#else - #define __Pyx_PyCFunction_Call PyCFunction_Call -#endif - #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) #define __PYX_BUILD_PY_SSIZE_T "i" #else #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -75,7 +82,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -89,7 +95,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -101,11 +106,9 @@ #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) - typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ @@ -115,31 +118,33 @@ #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #endif - #if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - - -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_GET_LENGTH) +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #else #define CYTHON_PEP393_ENABLED 0 - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #endif - #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -147,7 +152,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -166,7 +170,14 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) +#endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -174,9 +185,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -193,11 +202,9 @@ #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - #if PY_VERSION_HEX < 0x03020000 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong @@ -206,7 +213,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -225,11 +231,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -239,7 +243,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -247,6 +250,41 @@ #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) @@ -270,6 +308,7 @@ #include #define __PYX_HAVE__sklearn__svm__libsvm_sparse #define __PYX_HAVE_API__sklearn__svm__libsvm_sparse +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" @@ -284,21 +323,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -312,26 +336,130 @@ # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + #ifdef __GNUC__ /* Test for GCC > 2.95 */ @@ -346,8 +474,9 @@ static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -381,6 +510,7 @@ static const char *__pyx_filename; static const char *__pyx_f[] = { "libsvm_sparse.pyx", "numpy.pxd", + "type.pxd", }; #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; @@ -391,7 +521,7 @@ typedef struct { size_t size; /* sizeof(type) */ size_t arraysize[8]; /* length of array in each dimension */ int ndim; - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ char is_unsigned; int flags; } __Pyx_TypeInfo; @@ -418,7 +548,7 @@ typedef struct { } __Pyx_BufFmt_Context; -/* "numpy.pxd":722 +/* "numpy.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -427,7 +557,7 @@ typedef struct { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":723 +/* "numpy.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -436,7 +566,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":724 +/* "numpy.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -445,7 +575,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":725 +/* "numpy.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -454,7 +584,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":729 +/* "numpy.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -463,7 +593,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":730 +/* "numpy.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -472,7 +602,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":731 +/* "numpy.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -481,7 +611,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":732 +/* "numpy.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -490,7 +620,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":736 +/* "numpy.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -499,7 +629,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":737 +/* "numpy.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -508,7 +638,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":746 +/* "numpy.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -517,7 +647,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":747 +/* "numpy.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -526,7 +656,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":748 +/* "numpy.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -535,7 +665,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":750 +/* "numpy.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -544,7 +674,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":751 +/* "numpy.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -553,7 +683,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":752 +/* "numpy.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -562,7 +692,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":754 +/* "numpy.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -571,7 +701,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":755 +/* "numpy.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -580,7 +710,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":757 +/* "numpy.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -589,7 +719,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":758 +/* "numpy.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -598,7 +728,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":759 +/* "numpy.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -629,7 +759,7 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; /*--- Type declarations ---*/ -/* "numpy.pxd":761 +/* "numpy.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -638,7 +768,7 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":762 +/* "numpy.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -647,7 +777,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":763 +/* "numpy.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -656,7 +786,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":765 +/* "numpy.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -718,7 +848,22 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ @@ -736,6 +881,8 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* o __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ @@ -747,13 +894,17 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject static CYTHON_INLINE long __Pyx_div_long(long, long); /* proto */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /*proto*/ typedef struct { Py_ssize_t shape, strides, suboffsets; @@ -776,15 +927,18 @@ typedef struct { #define __Pyx_ReleaseBuffer PyBuffer_Release #endif + static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ - -static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name); +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t); +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + #if CYTHON_CCOMPLEX #ifdef __cplusplus #define __Pyx_CREAL(z) ((z).real()) @@ -925,10 +1079,10 @@ static int __Pyx_check_binary_version(void); #endif #endif -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ - static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + typedef struct { int code_line; PyCodeObject* code_object; @@ -953,10 +1107,17 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -971,7 +1132,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, cha /* Module declarations from 'sklearn.svm.libsvm_sparse' */ static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t = { "float64_t", NULL, sizeof(__pyx_t_5numpy_float64_t), { 0 }, 0, 'R', 0, 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t = { "int32_t", NULL, sizeof(__pyx_t_5numpy_int32_t), { 0 }, 0, 'I', IS_UNSIGNED(__pyx_t_5numpy_int32_t), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t = { "int32_t", NULL, sizeof(__pyx_t_5numpy_int32_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_int32_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_int32_t), 0 }; #define __Pyx_MODULE_NAME "sklearn.svm.libsvm_sparse" int __pyx_module_is_main_sklearn__svm__libsvm_sparse = 0; @@ -980,16 +1141,16 @@ static PyObject *__pyx_builtin_MemoryError; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_RuntimeError; -static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_features, PyArrayObject *__pyx_v_values, PyArrayObject *__pyx_v_indices, PyArrayObject *__pyx_v_indptr, PyArrayObject *__pyx_v_Y, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_weight_label, PyArrayObject *__pyx_v_weight, PyArrayObject *__pyx_v_sample_weight, double __pyx_v_nu, double __pyx_v_cache_size, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability); /* proto */ -static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T_data, PyArrayObject *__pyx_v_T_indices, PyArrayObject *__pyx_v_T_indptr, PyArrayObject *__pyx_v_SV_data, PyArrayObject *__pyx_v_SV_indices, PyArrayObject *__pyx_v_SV_indptr, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_weight_label, PyArrayObject *__pyx_v_weight, double __pyx_v_nu, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_label, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB); /* proto */ -static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_proba(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T_data, PyArrayObject *__pyx_v_T_indices, PyArrayObject *__pyx_v_T_indptr, PyArrayObject *__pyx_v_SV_data, PyArrayObject *__pyx_v_SV_indices, PyArrayObject *__pyx_v_SV_indptr, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_weight_label, PyArrayObject *__pyx_v_weight, double __pyx_v_nu, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_label, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB); /* proto */ +static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_features, PyArrayObject *__pyx_v_values, PyArrayObject *__pyx_v_indices, PyArrayObject *__pyx_v_indptr, PyArrayObject *__pyx_v_Y, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_class_weight, PyArrayObject *__pyx_v_sample_weight, double __pyx_v_nu, double __pyx_v_cache_size, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability, int __pyx_v_max_iter, int __pyx_v_random_seed); /* proto */ +static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T_data, PyArrayObject *__pyx_v_T_indices, PyArrayObject *__pyx_v_T_indptr, PyArrayObject *__pyx_v_SV_data, PyArrayObject *__pyx_v_SV_indices, PyArrayObject *__pyx_v_SV_indptr, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_class_weight, double __pyx_v_nu, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB); /* proto */ +static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_proba(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T_data, PyArrayObject *__pyx_v_T_indices, PyArrayObject *__pyx_v_T_indptr, PyArrayObject *__pyx_v_SV_data, PyArrayObject *__pyx_v_SV_indices, PyArrayObject *__pyx_v_SV_indptr, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_class_weight, double __pyx_v_nu, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB); /* proto */ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_6set_verbosity_wrap(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_verbosity); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static char __pyx_k_1[] = "sample_weight and X have incompatible shapes: "; static char __pyx_k_2[] = "sample_weight has %s samples while X has %s"; -static char __pyx_k_3[] = "Seems we've run out of of memory"; -static char __pyx_k_9[] = "We've run out of of memory"; +static char __pyx_k_3[] = "Seems we've run out of memory"; +static char __pyx_k_9[] = "We've run out of memory"; static char __pyx_k_12[] = "ndarray is not C contiguous"; static char __pyx_k_14[] = "ndarray is not Fortran contiguous"; static char __pyx_k_16[] = "Non-native byte order not supported"; @@ -1022,6 +1183,7 @@ static char __pyx_k__Zf[] = "Zf"; static char __pyx_k__Zg[] = "Zg"; static char __pyx_k__np[] = "np"; static char __pyx_k__nu[] = "nu"; +static char __pyx_k__rv[] = "rv"; static char __pyx_k__eps[] = "eps"; static char __pyx_k__nSV[] = "nSV"; static char __pyx_k__ones[] = "ones"; @@ -1030,7 +1192,6 @@ static char __pyx_k__dtype[] = "dtype"; static char __pyx_k__empty[] = "empty"; static char __pyx_k__gamma[] = "gamma"; static char __pyx_k__int32[] = "int32"; -static char __pyx_k__label[] = "label"; static char __pyx_k__model[] = "model"; static char __pyx_k__numpy[] = "numpy"; static char __pyx_k__param[] = "param"; @@ -1038,23 +1199,27 @@ static char __pyx_k__probA[] = "probA"; static char __pyx_k__probB[] = "probB"; static char __pyx_k__range[] = "range"; static char __pyx_k__scipy[] = "scipy"; +static char __pyx_k__utils[] = "utils"; static char __pyx_k__SV_len[] = "SV_len"; static char __pyx_k__T_data[] = "T_data"; +static char __pyx_k__arange[] = "arange"; static char __pyx_k__degree[] = "degree"; static char __pyx_k__indptr[] = "indptr"; static char __pyx_k__sparse[] = "sparse"; static char __pyx_k__values[] = "values"; -static char __pyx_k__weight[] = "weight"; static char __pyx_k__SV_data[] = "SV_data"; static char __pyx_k__float64[] = "float64"; static char __pyx_k__indices[] = "indices"; static char __pyx_k__n_class[] = "n_class"; static char __pyx_k__problem[] = "problem"; +static char __pyx_k__support[] = "support"; static char __pyx_k__sv_coef[] = "sv_coef"; static char __pyx_k__T_indptr[] = "T_indptr"; static char __pyx_k____main__[] = "__main__"; static char __pyx_k____test__[] = "__test__"; +static char __pyx_k__max_iter[] = "max_iter"; static char __pyx_k__svm_type[] = "svm_type"; +static char __pyx_k__warnings[] = "warnings"; static char __pyx_k__SV_indptr[] = "SV_indptr"; static char __pyx_k__T_indices[] = "T_indices"; static char __pyx_k__error_msg[] = "error_msg"; @@ -1063,21 +1228,28 @@ static char __pyx_k__shrinking[] = "shrinking"; static char __pyx_k__verbosity[] = "verbosity"; static char __pyx_k__SV_indices[] = "SV_indices"; static char __pyx_k__ValueError[] = "ValueError"; +static char __pyx_k____import__[] = "__import__"; static char __pyx_k__cache_size[] = "cache_size"; static char __pyx_k__csr_matrix[] = "csr_matrix"; static char __pyx_k__dec_values[] = "dec_values"; +static char __pyx_k__fit_status[] = "fit_status"; static char __pyx_k__n_class_SV[] = "n_class_SV"; static char __pyx_k__n_features[] = "n_features"; static char __pyx_k__nonzero_SV[] = "nonzero_SV"; static char __pyx_k__MemoryError[] = "MemoryError"; static char __pyx_k__kernel_type[] = "kernel_type"; static char __pyx_k__probability[] = "probability"; +static char __pyx_k__random_seed[] = "random_seed"; static char __pyx_k__RuntimeError[] = "RuntimeError"; +static char __pyx_k__class_weight[] = "class_weight"; static char __pyx_k__sv_coef_data[] = "sv_coef_data"; -static char __pyx_k__weight_label[] = "weight_label"; static char __pyx_k__sample_weight[] = "sample_weight"; +static char __pyx_k____pyx_getbuffer[] = "__pyx_getbuffer"; static char __pyx_k__support_vectors_[] = "support_vectors_"; +static char __pyx_k__ConvergenceWarning[] = "ConvergenceWarning"; +static char __pyx_k__class_weight_label[] = "class_weight_label"; static char __pyx_k__set_verbosity_wrap[] = "set_verbosity_wrap"; +static char __pyx_k____pyx_releasebuffer[] = "__pyx_releasebuffer"; static char __pyx_k__libsvm_sparse_train[] = "libsvm_sparse_train"; static PyObject *__pyx_kp_s_1; static PyObject *__pyx_kp_u_12; @@ -1094,6 +1266,7 @@ static PyObject *__pyx_n_s_30; static PyObject *__pyx_n_s_33; static PyObject *__pyx_kp_s_9; static PyObject *__pyx_n_s__C; +static PyObject *__pyx_n_s__ConvergenceWarning; static PyObject *__pyx_n_s__MemoryError; static PyObject *__pyx_n_s__RuntimeError; static PyObject *__pyx_n_s__SV_data; @@ -1105,9 +1278,15 @@ static PyObject *__pyx_n_s__T_indices; static PyObject *__pyx_n_s__T_indptr; static PyObject *__pyx_n_s__ValueError; static PyObject *__pyx_n_s__Y; +static PyObject *__pyx_n_s____import__; static PyObject *__pyx_n_s____main__; +static PyObject *__pyx_n_s____pyx_getbuffer; +static PyObject *__pyx_n_s____pyx_releasebuffer; static PyObject *__pyx_n_s____test__; +static PyObject *__pyx_n_s__arange; static PyObject *__pyx_n_s__cache_size; +static PyObject *__pyx_n_s__class_weight; +static PyObject *__pyx_n_s__class_weight_label; static PyObject *__pyx_n_s__coef0; static PyObject *__pyx_n_s__csr_matrix; static PyObject *__pyx_n_s__dec_values; @@ -1116,6 +1295,7 @@ static PyObject *__pyx_n_s__dtype; static PyObject *__pyx_n_s__empty; static PyObject *__pyx_n_s__eps; static PyObject *__pyx_n_s__error_msg; +static PyObject *__pyx_n_s__fit_status; static PyObject *__pyx_n_s__float64; static PyObject *__pyx_n_s__gamma; static PyObject *__pyx_n_s__indices; @@ -1123,8 +1303,8 @@ static PyObject *__pyx_n_s__indptr; static PyObject *__pyx_n_s__int32; static PyObject *__pyx_n_s__intercept; static PyObject *__pyx_n_s__kernel_type; -static PyObject *__pyx_n_s__label; static PyObject *__pyx_n_s__libsvm_sparse_train; +static PyObject *__pyx_n_s__max_iter; static PyObject *__pyx_n_s__model; static PyObject *__pyx_n_s__nSV; static PyObject *__pyx_n_s__n_class; @@ -1141,20 +1321,23 @@ static PyObject *__pyx_n_s__probA; static PyObject *__pyx_n_s__probB; static PyObject *__pyx_n_s__probability; static PyObject *__pyx_n_s__problem; +static PyObject *__pyx_n_s__random_seed; static PyObject *__pyx_n_s__range; +static PyObject *__pyx_n_s__rv; static PyObject *__pyx_n_s__sample_weight; static PyObject *__pyx_n_s__scipy; static PyObject *__pyx_n_s__set_verbosity_wrap; static PyObject *__pyx_n_s__shrinking; static PyObject *__pyx_n_s__sparse; +static PyObject *__pyx_n_s__support; static PyObject *__pyx_n_s__support_vectors_; static PyObject *__pyx_n_s__sv_coef; static PyObject *__pyx_n_s__sv_coef_data; static PyObject *__pyx_n_s__svm_type; +static PyObject *__pyx_n_s__utils; static PyObject *__pyx_n_s__values; static PyObject *__pyx_n_s__verbosity; -static PyObject *__pyx_n_s__weight; -static PyObject *__pyx_n_s__weight_label; +static PyObject *__pyx_n_s__warnings; static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_15; @@ -1197,25 +1380,29 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_1libsvm_sparse_train(PyO double __pyx_v_coef0; double __pyx_v_eps; double __pyx_v_C; - PyArrayObject *__pyx_v_weight_label = 0; - PyArrayObject *__pyx_v_weight = 0; + PyArrayObject *__pyx_v_class_weight = 0; PyArrayObject *__pyx_v_sample_weight = 0; double __pyx_v_nu; double __pyx_v_cache_size; double __pyx_v_p; int __pyx_v_shrinking; int __pyx_v_probability; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_features,&__pyx_n_s__values,&__pyx_n_s__indices,&__pyx_n_s__indptr,&__pyx_n_s__Y,&__pyx_n_s__svm_type,&__pyx_n_s__kernel_type,&__pyx_n_s__degree,&__pyx_n_s__gamma,&__pyx_n_s__coef0,&__pyx_n_s__eps,&__pyx_n_s__C,&__pyx_n_s__weight_label,&__pyx_n_s__weight,&__pyx_n_s__sample_weight,&__pyx_n_s__nu,&__pyx_n_s__cache_size,&__pyx_n_s__p,&__pyx_n_s__shrinking,&__pyx_n_s__probability,0}; + int __pyx_v_max_iter; + int __pyx_v_random_seed; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("libsvm_sparse_train (wrapper)", 0); - __pyx_self = __pyx_self; { - PyObject* values[20] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_features,&__pyx_n_s__values,&__pyx_n_s__indices,&__pyx_n_s__indptr,&__pyx_n_s__Y,&__pyx_n_s__svm_type,&__pyx_n_s__kernel_type,&__pyx_n_s__degree,&__pyx_n_s__gamma,&__pyx_n_s__coef0,&__pyx_n_s__eps,&__pyx_n_s__C,&__pyx_n_s__class_weight,&__pyx_n_s__sample_weight,&__pyx_n_s__nu,&__pyx_n_s__cache_size,&__pyx_n_s__p,&__pyx_n_s__shrinking,&__pyx_n_s__probability,&__pyx_n_s__max_iter,&__pyx_n_s__random_seed,0}; + PyObject* values[21] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { + case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); case 20: values[19] = PyTuple_GET_ITEM(__pyx_args, 19); case 19: values[18] = PyTuple_GET_ITEM(__pyx_args, 18); case 18: values[17] = PyTuple_GET_ITEM(__pyx_args, 17); @@ -1242,128 +1429,113 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_1libsvm_sparse_train(PyO kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_features); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_features)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__values); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__values)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__indices); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__indices)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__indptr); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__indptr)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__Y); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__svm_type); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__svm_type)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kernel_type); - if (likely(values[6])) kw_args--; + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kernel_type)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: - values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__degree); - if (likely(values[7])) kw_args--; + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__degree)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: - values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__gamma); - if (likely(values[8])) kw_args--; + if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__gamma)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: - values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coef0); - if (likely(values[9])) kw_args--; + if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coef0)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: - values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__eps); - if (likely(values[10])) kw_args--; + if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__eps)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 11: - values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C); - if (likely(values[11])) kw_args--; + if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 12: - values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight_label); - if (likely(values[12])) kw_args--; + if (likely((values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 13: - values[13] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight); - if (likely(values[13])) kw_args--; + if (likely((values[13] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sample_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 13); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 13); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 14: - values[14] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sample_weight); - if (likely(values[14])) kw_args--; + if (likely((values[14] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nu)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 14); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 14); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 15: - values[15] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nu); - if (likely(values[15])) kw_args--; + if (likely((values[15] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__cache_size)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 15); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 15); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 16: - values[16] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__cache_size); - if (likely(values[16])) kw_args--; + if (likely((values[16] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 16); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 16); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 17: - values[17] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[17])) kw_args--; + if (likely((values[17] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shrinking)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 17); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 17); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 18: - values[18] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shrinking); - if (likely(values[18])) kw_args--; + if (likely((values[18] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probability)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 18); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 18); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 19: - values[19] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probability); - if (likely(values[19])) kw_args--; + if (likely((values[19] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__max_iter)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 19); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 20: + if (likely((values[20] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__random_seed)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, 19); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, 20); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "libsvm_sparse_train") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "libsvm_sparse_train") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - } else if (PyTuple_GET_SIZE(__pyx_args) != 20) { + } else if (PyTuple_GET_SIZE(__pyx_args) != 21) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); @@ -1386,44 +1558,45 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_1libsvm_sparse_train(PyO values[17] = PyTuple_GET_ITEM(__pyx_args, 17); values[18] = PyTuple_GET_ITEM(__pyx_args, 18); values[19] = PyTuple_GET_ITEM(__pyx_args, 19); + values[20] = PyTuple_GET_ITEM(__pyx_args, 20); } - __pyx_v_n_features = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_features == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_features = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_features == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_values = ((PyArrayObject *)values[1]); __pyx_v_indices = ((PyArrayObject *)values[2]); __pyx_v_indptr = ((PyArrayObject *)values[3]); __pyx_v_Y = ((PyArrayObject *)values[4]); - __pyx_v_svm_type = __Pyx_PyInt_AsInt(values[5]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_kernel_type = __Pyx_PyInt_AsInt(values[6]); if (unlikely((__pyx_v_kernel_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_degree = __Pyx_PyInt_AsInt(values[7]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_eps = __pyx_PyFloat_AsDouble(values[10]); if (unlikely((__pyx_v_eps == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_C = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_weight_label = ((PyArrayObject *)values[12]); - __pyx_v_weight = ((PyArrayObject *)values[13]); - __pyx_v_sample_weight = ((PyArrayObject *)values[14]); - __pyx_v_nu = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_p = __pyx_PyFloat_AsDouble(values[17]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_shrinking = __Pyx_PyInt_AsInt(values[18]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_probability = __Pyx_PyInt_AsInt(values[19]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_svm_type = __Pyx_PyInt_AsInt(values[5]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_kernel_type = __Pyx_PyInt_AsInt(values[6]); if (unlikely((__pyx_v_kernel_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_degree = __Pyx_PyInt_AsInt(values[7]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[8]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[9]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_eps = __pyx_PyFloat_AsDouble(values[10]); if (unlikely((__pyx_v_eps == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_C = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_class_weight = ((PyArrayObject *)values[12]); + __pyx_v_sample_weight = ((PyArrayObject *)values[13]); + __pyx_v_nu = __pyx_PyFloat_AsDouble(values[14]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_cache_size = __pyx_PyFloat_AsDouble(values[15]); if (unlikely((__pyx_v_cache_size == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_p = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_shrinking = __Pyx_PyInt_AsInt(values[17]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_probability = __Pyx_PyInt_AsInt(values[18]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_max_iter = __Pyx_PyInt_AsInt(values[19]); if (unlikely((__pyx_v_max_iter == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_random_seed = __Pyx_PyInt_AsInt(values[20]); if (unlikely((__pyx_v_random_seed == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 20, 20, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_train", 1, 21, 21, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.svm.libsvm_sparse.libsvm_sparse_train", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_values), __pyx_ptype_5numpy_ndarray, 1, "values", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_indices), __pyx_ptype_5numpy_ndarray, 1, "indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_indptr), __pyx_ptype_5numpy_ndarray, 1, "indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weight_label), __pyx_ptype_5numpy_ndarray, 1, "weight_label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weight), __pyx_ptype_5numpy_ndarray, 1, "weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(__pyx_self, __pyx_v_n_features, __pyx_v_values, __pyx_v_indices, __pyx_v_indptr, __pyx_v_Y, __pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_eps, __pyx_v_C, __pyx_v_weight_label, __pyx_v_weight, __pyx_v_sample_weight, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_values), __pyx_ptype_5numpy_ndarray, 1, "values", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_indices), __pyx_ptype_5numpy_ndarray, 1, "indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_indptr), __pyx_ptype_5numpy_ndarray, 1, "indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(__pyx_self, __pyx_v_n_features, __pyx_v_values, __pyx_v_indices, __pyx_v_indptr, __pyx_v_Y, __pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_eps, __pyx_v_C, __pyx_v_class_weight, __pyx_v_sample_weight, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_max_iter, __pyx_v_random_seed); goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -1432,7 +1605,7 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_1libsvm_sparse_train(PyO return __pyx_r; } -/* "sklearn/svm/libsvm_sparse.pyx":59 +/* "sklearn/svm/libsvm_sparse.pyx":67 * * * def libsvm_sparse_train ( int n_features, # <<<<<<<<<<<<<< @@ -1440,14 +1613,17 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_1libsvm_sparse_train(PyO * np.ndarray[np.int32_t, ndim=1, mode='c'] indices, */ -static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_features, PyArrayObject *__pyx_v_values, PyArrayObject *__pyx_v_indices, PyArrayObject *__pyx_v_indptr, PyArrayObject *__pyx_v_Y, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_weight_label, PyArrayObject *__pyx_v_weight, PyArrayObject *__pyx_v_sample_weight, double __pyx_v_nu, double __pyx_v_cache_size, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability) { +static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_features, PyArrayObject *__pyx_v_values, PyArrayObject *__pyx_v_indices, PyArrayObject *__pyx_v_indptr, PyArrayObject *__pyx_v_Y, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_class_weight, PyArrayObject *__pyx_v_sample_weight, double __pyx_v_nu, double __pyx_v_cache_size, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability, int __pyx_v_max_iter, int __pyx_v_random_seed) { struct svm_parameter *__pyx_v_param; struct svm_csr_problem *__pyx_v_problem; struct svm_csr_model *__pyx_v_model; - char *__pyx_v_error_msg; + const char* __pyx_v_error_msg; + PyArrayObject *__pyx_v_class_weight_label = 0; + int __pyx_v_fit_status; npy_intp __pyx_v_SV_len; npy_intp __pyx_v_n_class; PyArrayObject *__pyx_v_sv_coef_data = 0; + PyArrayObject *__pyx_v_support = 0; PyArrayObject *__pyx_v_intercept = 0; npy_intp __pyx_v_nonzero_SV; PyArrayObject *__pyx_v_SV_data = 0; @@ -1455,23 +1631,24 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH PyArrayObject *__pyx_v_SV_indptr = 0; PyObject *__pyx_v_support_vectors_ = NULL; PyArrayObject *__pyx_v_n_class_SV = 0; - PyArrayObject *__pyx_v_label = 0; PyArrayObject *__pyx_v_probA = 0; PyArrayObject *__pyx_v_probB = 0; __Pyx_LocalBuf_ND __pyx_pybuffernd_Y; __Pyx_Buffer __pyx_pybuffer_Y; + __Pyx_LocalBuf_ND __pyx_pybuffernd_class_weight; + __Pyx_Buffer __pyx_pybuffer_class_weight; + __Pyx_LocalBuf_ND __pyx_pybuffernd_class_weight_label; + __Pyx_Buffer __pyx_pybuffer_class_weight_label; __Pyx_LocalBuf_ND __pyx_pybuffernd_indices; __Pyx_Buffer __pyx_pybuffer_indices; __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr; __Pyx_Buffer __pyx_pybuffer_indptr; __Pyx_LocalBuf_ND __pyx_pybuffernd_sample_weight; __Pyx_Buffer __pyx_pybuffer_sample_weight; + __Pyx_LocalBuf_ND __pyx_pybuffernd_support; + __Pyx_Buffer __pyx_pybuffer_support; __Pyx_LocalBuf_ND __pyx_pybuffernd_values; __Pyx_Buffer __pyx_pybuffer_values; - __Pyx_LocalBuf_ND __pyx_pybuffernd_weight; - __Pyx_Buffer __pyx_pybuffer_weight; - __Pyx_LocalBuf_ND __pyx_pybuffernd_weight_label; - __Pyx_Buffer __pyx_pybuffer_weight_label; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; @@ -1486,13 +1663,23 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; PyObject *__pyx_t_12 = NULL; - int __pyx_t_13; + PyArrayObject *__pyx_t_13 = NULL; int __pyx_t_14; + int __pyx_t_15; + PyArrayObject *__pyx_t_16 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("libsvm_sparse_train", 0); __Pyx_INCREF((PyObject *)__pyx_v_sample_weight); + __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight_label.refcount = 0; + __pyx_pybuffernd_class_weight_label.data = NULL; + __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; + __pyx_pybuffer_support.pybuffer.buf = NULL; + __pyx_pybuffer_support.refcount = 0; + __pyx_pybuffernd_support.data = NULL; + __pyx_pybuffernd_support.rcbuffer = &__pyx_pybuffer_support; __pyx_pybuffer_values.pybuffer.buf = NULL; __pyx_pybuffer_values.refcount = 0; __pyx_pybuffernd_values.data = NULL; @@ -1509,99 +1696,90 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH __pyx_pybuffer_Y.refcount = 0; __pyx_pybuffernd_Y.data = NULL; __pyx_pybuffernd_Y.rcbuffer = &__pyx_pybuffer_Y; - __pyx_pybuffer_weight_label.pybuffer.buf = NULL; - __pyx_pybuffer_weight_label.refcount = 0; - __pyx_pybuffernd_weight_label.data = NULL; - __pyx_pybuffernd_weight_label.rcbuffer = &__pyx_pybuffer_weight_label; - __pyx_pybuffer_weight.pybuffer.buf = NULL; - __pyx_pybuffer_weight.refcount = 0; - __pyx_pybuffernd_weight.data = NULL; - __pyx_pybuffernd_weight.rcbuffer = &__pyx_pybuffer_weight; + __pyx_pybuffer_class_weight.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight.refcount = 0; + __pyx_pybuffernd_class_weight.data = NULL; + __pyx_pybuffernd_class_weight.rcbuffer = &__pyx_pybuffer_class_weight; __pyx_pybuffer_sample_weight.pybuffer.buf = NULL; __pyx_pybuffer_sample_weight.refcount = 0; __pyx_pybuffernd_sample_weight.data = NULL; __pyx_pybuffernd_sample_weight.rcbuffer = &__pyx_pybuffer_sample_weight; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_values, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_values, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_values.diminfo[0].strides = __pyx_pybuffernd_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_values.diminfo[0].shape = __pyx_pybuffernd_values.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_indices.diminfo[0].strides = __pyx_pybuffernd_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices.diminfo[0].shape = __pyx_pybuffernd_indices.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_indptr.diminfo[0].strides = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr.diminfo[0].shape = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Y.rcbuffer->pybuffer, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Y.rcbuffer->pybuffer, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_Y.diminfo[0].strides = __pyx_pybuffernd_Y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_Y.diminfo[0].shape = __pyx_pybuffernd_Y.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_weight_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_weight_label.diminfo[0].strides = __pyx_pybuffernd_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weight_label.diminfo[0].shape = __pyx_pybuffernd_weight_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_pybuffernd_weight.diminfo[0].strides = __pyx_pybuffernd_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weight.diminfo[0].shape = __pyx_pybuffernd_weight.rcbuffer->pybuffer.shape[0]; + __pyx_pybuffernd_class_weight.diminfo[0].strides = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight.diminfo[0].shape = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_sample_weight.diminfo[0].strides = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weight.diminfo[0].shape = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.shape[0]; - /* "sklearn/svm/libsvm_sparse.pyx":99 - * cdef char *error_msg + /* "sklearn/svm/libsvm_sparse.pyx":107 + * cdef const_char_p error_msg * * if len(sample_weight) == 0: # <<<<<<<<<<<<<< * sample_weight = np.ones(Y.shape[0], dtype=np.float64) * else: */ - __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_sample_weight)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = (__pyx_t_1 == 0); + __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_sample_weight)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((__pyx_t_1 == 0) != 0); if (__pyx_t_2) { - /* "sklearn/svm/libsvm_sparse.pyx":100 + /* "sklearn/svm/libsvm_sparse.pyx":108 * * if len(sample_weight) == 0: * sample_weight = np.ones(Y.shape[0], dtype=np.float64) # <<<<<<<<<<<<<< * else: * assert sample_weight.shape[0] == indptr.shape[0] - 1, \ */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__ones); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__ones); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_Y->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_Y->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s__float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_8 = ((PyArrayObject *)__pyx_t_7); { __Pyx_BufFmt_StackElem __pyx_stack[1]; @@ -1617,7 +1795,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH } } __pyx_pybuffernd_sample_weight.diminfo[0].strides = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weight.diminfo[0].shape = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_8 = 0; __Pyx_DECREF(((PyObject *)__pyx_v_sample_weight)); @@ -1627,7 +1805,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH } /*else*/ { - /* "sklearn/svm/libsvm_sparse.pyx":102 + /* "sklearn/svm/libsvm_sparse.pyx":110 * sample_weight = np.ones(Y.shape[0], dtype=np.float64) * else: * assert sample_weight.shape[0] == indptr.shape[0] - 1, \ # <<<<<<<<<<<<<< @@ -1635,20 +1813,20 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH * "sample_weight has %s samples while X has %s" % \ */ #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!((__pyx_v_sample_weight->dimensions[0]) == ((__pyx_v_indptr->dimensions[0]) - 1)))) { + if (unlikely(!(((__pyx_v_sample_weight->dimensions[0]) == ((__pyx_v_indptr->dimensions[0]) - 1)) != 0))) { - /* "sklearn/svm/libsvm_sparse.pyx":105 + /* "sklearn/svm/libsvm_sparse.pyx":113 * "sample_weight and X have incompatible shapes: " + \ * "sample_weight has %s samples while X has %s" % \ * (sample_weight.shape[0], indptr.shape[0] - 1) # <<<<<<<<<<<<<< * * # we should never end up here with a precomputed kernel matrix, */ - __pyx_t_7 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_sample_weight->dimensions[0])); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_sample_weight->dimensions[0])); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = PyInt_FromLong(((__pyx_v_indptr->dimensions[0]) - 1)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(((__pyx_v_indptr->dimensions[0]) - 1)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); @@ -1656,21 +1834,21 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH __Pyx_GIVEREF(__pyx_t_3); __pyx_t_7 = 0; __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_2), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_2), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_3)); __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyNumber_Add(((PyObject *)__pyx_kp_s_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Add(((PyObject *)__pyx_kp_s_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_5)); __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; PyErr_SetObject(PyExc_AssertionError, ((PyObject *)__pyx_t_5)); __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #endif } __pyx_L3:; - /* "sklearn/svm/libsvm_sparse.pyx":109 + /* "sklearn/svm/libsvm_sparse.pyx":117 * # we should never end up here with a precomputed kernel matrix, * # as this is always dense. * assert(kernel_type != 4) # <<<<<<<<<<<<<< @@ -1678,82 +1856,129 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH * # set libsvm problem */ #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!(__pyx_v_kernel_type != 4))) { + if (unlikely(!((__pyx_v_kernel_type != 4) != 0))) { PyErr_SetNone(PyExc_AssertionError); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #endif - /* "sklearn/svm/libsvm_sparse.pyx":114 + /* "sklearn/svm/libsvm_sparse.pyx":122 * problem = csr_set_problem(values.data, indices.shape, indices.data, * indptr.shape, indptr.data, Y.data, * sample_weight.data, kernel_type) # <<<<<<<<<<<<<< * - * # set parameters + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ */ __pyx_v_problem = csr_set_problem(__pyx_v_values->data, __pyx_v_indices->dimensions, __pyx_v_indices->data, __pyx_v_indptr->dimensions, __pyx_v_indptr->data, __pyx_v_Y->data, __pyx_v_sample_weight->data, __pyx_v_kernel_type); - /* "sklearn/svm/libsvm_sparse.pyx":120 - * nu, cache_size, C, eps, p, shrinking, - * probability, weight.shape[0], - * weight_label.data, weight.data) # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm_sparse.pyx":125 + * + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) # <<<<<<<<<<<<<< + * + * # set parameters + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__arange); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_class_weight->dimensions[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = ((PyArrayObject *)__pyx_t_6); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_t_13, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_class_weight_label = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_13 = 0; + __pyx_v_class_weight_label = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; + + /* "sklearn/svm/libsvm_sparse.pyx":132 + * probability, class_weight.shape[0], + * class_weight_label.data, class_weight.data, max_iter, + * random_seed) # <<<<<<<<<<<<<< * * # check parameters */ - __pyx_v_param = set_parameter(__pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_C, __pyx_v_eps, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_weight->dimensions[0])), __pyx_v_weight_label->data, __pyx_v_weight->data); + __pyx_v_param = set_parameter(__pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, __pyx_v_cache_size, __pyx_v_C, __pyx_v_eps, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data, __pyx_v_max_iter, __pyx_v_random_seed); - /* "sklearn/svm/libsvm_sparse.pyx":123 + /* "sklearn/svm/libsvm_sparse.pyx":135 * * # check parameters * if (param == NULL or problem == NULL): # <<<<<<<<<<<<<< - * raise MemoryError("Seems we've run out of of memory") + * raise MemoryError("Seems we've run out of memory") * error_msg = svm_csr_check_parameter(problem, param); */ - __pyx_t_2 = (__pyx_v_param == NULL); + __pyx_t_2 = ((__pyx_v_param == NULL) != 0); if (!__pyx_t_2) { - __pyx_t_13 = (__pyx_v_problem == NULL); - __pyx_t_14 = __pyx_t_13; + __pyx_t_14 = ((__pyx_v_problem == NULL) != 0); + __pyx_t_15 = __pyx_t_14; } else { - __pyx_t_14 = __pyx_t_2; + __pyx_t_15 = __pyx_t_2; } - if (__pyx_t_14) { + if (__pyx_t_15) { - /* "sklearn/svm/libsvm_sparse.pyx":124 + /* "sklearn/svm/libsvm_sparse.pyx":136 * # check parameters * if (param == NULL or problem == NULL): - * raise MemoryError("Seems we've run out of of memory") # <<<<<<<<<<<<<< + * raise MemoryError("Seems we've run out of memory") # <<<<<<<<<<<<<< * error_msg = svm_csr_check_parameter(problem, param); * if error_msg: */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; - /* "sklearn/svm/libsvm_sparse.pyx":125 + /* "sklearn/svm/libsvm_sparse.pyx":137 * if (param == NULL or problem == NULL): - * raise MemoryError("Seems we've run out of of memory") + * raise MemoryError("Seems we've run out of memory") * error_msg = svm_csr_check_parameter(problem, param); # <<<<<<<<<<<<<< * if error_msg: * free_problem(problem) */ __pyx_v_error_msg = svm_csr_check_parameter(__pyx_v_problem, __pyx_v_param); - /* "sklearn/svm/libsvm_sparse.pyx":126 - * raise MemoryError("Seems we've run out of of memory") + /* "sklearn/svm/libsvm_sparse.pyx":138 + * raise MemoryError("Seems we've run out of memory") * error_msg = svm_csr_check_parameter(problem, param); * if error_msg: # <<<<<<<<<<<<<< * free_problem(problem) * free_param(param) */ - __pyx_t_14 = (__pyx_v_error_msg != 0); - if (__pyx_t_14) { + __pyx_t_15 = (__pyx_v_error_msg != 0); + if (__pyx_t_15) { - /* "sklearn/svm/libsvm_sparse.pyx":127 + /* "sklearn/svm/libsvm_sparse.pyx":139 * error_msg = svm_csr_check_parameter(problem, param); * if error_msg: * free_problem(problem) # <<<<<<<<<<<<<< @@ -1762,7 +1987,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH */ free_problem(__pyx_v_problem); - /* "sklearn/svm/libsvm_sparse.pyx":128 + /* "sklearn/svm/libsvm_sparse.pyx":140 * if error_msg: * free_problem(problem) * free_param(param) # <<<<<<<<<<<<<< @@ -1771,41 +1996,79 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH */ free_param(__pyx_v_param); - /* "sklearn/svm/libsvm_sparse.pyx":129 + /* "sklearn/svm/libsvm_sparse.pyx":141 * free_problem(problem) * free_param(param) * raise ValueError(error_msg) # <<<<<<<<<<<<<< * * # call svm_train, this does the real work */ - __pyx_t_5 = PyBytes_FromString(__pyx_v_error_msg); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_error_msg); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_t_6)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_6)); + __pyx_t_6 = 0; + __pyx_t_6 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; - /* "sklearn/svm/libsvm_sparse.pyx":132 + /* "sklearn/svm/libsvm_sparse.pyx":144 * * # call svm_train, this does the real work - * model = svm_csr_train(problem, param) # <<<<<<<<<<<<<< + * cdef int fit_status = 0 # <<<<<<<<<<<<<< + * with nogil: + * model = svm_csr_train(problem, param, &fit_status) + */ + __pyx_v_fit_status = 0; + + /* "sklearn/svm/libsvm_sparse.pyx":145 + * # call svm_train, this does the real work + * cdef int fit_status = 0 + * with nogil: # <<<<<<<<<<<<<< + * model = svm_csr_train(problem, param, &fit_status) + * + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/svm/libsvm_sparse.pyx":146 + * cdef int fit_status = 0 + * with nogil: + * model = svm_csr_train(problem, param, &fit_status) # <<<<<<<<<<<<<< * * cdef np.npy_intp SV_len = get_l(model) */ - __pyx_v_model = svm_csr_train(__pyx_v_problem, __pyx_v_param); + __pyx_v_model = svm_csr_train(__pyx_v_problem, __pyx_v_param, (&__pyx_v_fit_status)); + } + + /* "sklearn/svm/libsvm_sparse.pyx":145 + * # call svm_train, this does the real work + * cdef int fit_status = 0 + * with nogil: # <<<<<<<<<<<<<< + * model = svm_csr_train(problem, param, &fit_status) + * + */ + /*finally:*/ { + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + } + } - /* "sklearn/svm/libsvm_sparse.pyx":134 - * model = svm_csr_train(problem, param) + /* "sklearn/svm/libsvm_sparse.pyx":148 + * model = svm_csr_train(problem, param, &fit_status) * * cdef np.npy_intp SV_len = get_l(model) # <<<<<<<<<<<<<< * cdef np.npy_intp n_class = get_nr(model) @@ -1813,7 +2076,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH */ __pyx_v_SV_len = get_l(__pyx_v_model); - /* "sklearn/svm/libsvm_sparse.pyx":135 + /* "sklearn/svm/libsvm_sparse.pyx":149 * * cdef np.npy_intp SV_len = get_l(model) * cdef np.npy_intp n_class = get_nr(model) # <<<<<<<<<<<<<< @@ -1822,219 +2085,283 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH */ __pyx_v_n_class = get_nr(__pyx_v_model); - /* "sklearn/svm/libsvm_sparse.pyx":141 + /* "sklearn/svm/libsvm_sparse.pyx":155 * # it would not erase previous information * cdef np.ndarray sv_coef_data * sv_coef_data = np.empty((n_class-1)*SV_len, dtype=np.float64) # <<<<<<<<<<<<<< * copy_sv_coef (sv_coef_data.data, model) * */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyInt_FromLong(((__pyx_v_n_class - 1) * __pyx_v_SV_len)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s__empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyInt_FromLong(((__pyx_v_n_class - 1) * __pyx_v_SV_len)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_sv_coef_data = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; - - /* "sklearn/svm/libsvm_sparse.pyx":142 - * cdef np.ndarray sv_coef_data - * sv_coef_data = np.empty((n_class-1)*SV_len, dtype=np.float64) - * copy_sv_coef (sv_coef_data.data, model) # <<<<<<<<<<<<<< - * - * # copy model.rho into the intercept - */ - copy_sv_coef(__pyx_v_sv_coef_data->data, __pyx_v_model); - - /* "sklearn/svm/libsvm_sparse.pyx":147 - * # the intercept is just model.rho but with sign changed - * cdef np.ndarray intercept - * intercept = np.empty(n_class*(n_class-1)/2, dtype=np.float64) # <<<<<<<<<<<<<< - * copy_intercept (intercept.data, model, intercept.shape) - * - */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyInt_FromLong(__Pyx_div_long((__pyx_v_n_class * (__pyx_v_n_class - 1)), 2)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_intercept = ((PyArrayObject *)__pyx_t_4); + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_sv_coef_data = ((PyArrayObject *)__pyx_t_4); __pyx_t_4 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":148 - * cdef np.ndarray intercept - * intercept = np.empty(n_class*(n_class-1)/2, dtype=np.float64) - * copy_intercept (intercept.data, model, intercept.shape) # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm_sparse.pyx":156 + * cdef np.ndarray sv_coef_data + * sv_coef_data = np.empty((n_class-1)*SV_len, dtype=np.float64) + * copy_sv_coef (sv_coef_data.data, model) # <<<<<<<<<<<<<< * - * # copy model.SV + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] support */ - copy_intercept(__pyx_v_intercept->data, __pyx_v_model, __pyx_v_intercept->dimensions); + copy_sv_coef(__pyx_v_sv_coef_data->data, __pyx_v_model); - /* "sklearn/svm/libsvm_sparse.pyx":154 - * # TODO: custom kernel - * cdef np.npy_intp nonzero_SV - * nonzero_SV = get_nonzero_SV (model) # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm_sparse.pyx":159 * - * cdef np.ndarray SV_data, SV_indices, SV_indptr - */ - __pyx_v_nonzero_SV = get_nonzero_SV(__pyx_v_model); - - /* "sklearn/svm/libsvm_sparse.pyx":157 + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] support + * support = np.empty(SV_len, dtype=np.int32) # <<<<<<<<<<<<<< + * copy_support(support.data, model) * - * cdef np.ndarray SV_data, SV_indices, SV_indptr - * SV_data = np.empty(nonzero_SV, dtype=np.float64) # <<<<<<<<<<<<<< - * SV_indices = np.empty(nonzero_SV, dtype=np.int32) - * SV_indptr = np.empty(SV_len + 1, dtype=np.int32) */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_nonzero_SV); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_SV_len); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__float64); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__int32); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_SV_data = ((PyArrayObject *)__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_16 = ((PyArrayObject *)__pyx_t_3); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_support.rcbuffer->pybuffer); + __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support.rcbuffer->pybuffer, (PyObject*)__pyx_t_16, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_9 < 0)) { + PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_support.rcbuffer->pybuffer, (PyObject*)__pyx_v_support, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_12, __pyx_t_11, __pyx_t_10); + } + } + __pyx_pybuffernd_support.diminfo[0].strides = __pyx_pybuffernd_support.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_support.diminfo[0].shape = __pyx_pybuffernd_support.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_9 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_16 = 0; + __pyx_v_support = ((PyArrayObject *)__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":158 - * cdef np.ndarray SV_data, SV_indices, SV_indptr - * SV_data = np.empty(nonzero_SV, dtype=np.float64) - * SV_indices = np.empty(nonzero_SV, dtype=np.int32) # <<<<<<<<<<<<<< - * SV_indptr = np.empty(SV_len + 1, dtype=np.int32) - * csr_copy_SV(SV_data.data, SV_indices.shape, SV_indices.data, + /* "sklearn/svm/libsvm_sparse.pyx":160 + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] support + * support = np.empty(SV_len, dtype=np.int32) + * copy_support(support.data, model) # <<<<<<<<<<<<<< + * + * # copy model.rho into the intercept + */ + copy_support(__pyx_v_support->data, __pyx_v_model); + + /* "sklearn/svm/libsvm_sparse.pyx":165 + * # the intercept is just model.rho but with sign changed + * cdef np.ndarray intercept + * intercept = np.empty(n_class*(n_class-1)/2, dtype=np.float64) # <<<<<<<<<<<<<< + * copy_intercept (intercept.data, model, intercept.shape) + * */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_nonzero_SV); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(__Pyx_div_long((__pyx_v_n_class * (__pyx_v_n_class - 1)), 2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__int32); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s__float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_SV_indices = ((PyArrayObject *)__pyx_t_5); + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_intercept = ((PyArrayObject *)__pyx_t_5); __pyx_t_5 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":159 - * SV_data = np.empty(nonzero_SV, dtype=np.float64) + /* "sklearn/svm/libsvm_sparse.pyx":166 + * cdef np.ndarray intercept + * intercept = np.empty(n_class*(n_class-1)/2, dtype=np.float64) + * copy_intercept (intercept.data, model, intercept.shape) # <<<<<<<<<<<<<< + * + * # copy model.SV + */ + copy_intercept(__pyx_v_intercept->data, __pyx_v_model, __pyx_v_intercept->dimensions); + + /* "sklearn/svm/libsvm_sparse.pyx":172 + * # TODO: custom kernel + * cdef np.npy_intp nonzero_SV + * nonzero_SV = get_nonzero_SV (model) # <<<<<<<<<<<<<< + * + * cdef np.ndarray SV_data, SV_indices, SV_indptr + */ + __pyx_v_nonzero_SV = get_nonzero_SV(__pyx_v_model); + + /* "sklearn/svm/libsvm_sparse.pyx":175 + * + * cdef np.ndarray SV_data, SV_indices, SV_indptr + * SV_data = np.empty(nonzero_SV, dtype=np.float64) # <<<<<<<<<<<<<< * SV_indices = np.empty(nonzero_SV, dtype=np.int32) - * SV_indptr = np.empty(SV_len + 1, dtype=np.int32) # <<<<<<<<<<<<<< - * csr_copy_SV(SV_data.data, SV_indices.shape, SV_indices.data, - * SV_indptr.shape, SV_indptr.data, model, n_features) + * SV_indptr = np.empty(SV_len + 1, dtype=np.int32) */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyInt_FromLong((((npy_intp)__pyx_v_SV_len) + 1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_nonzero_SV); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_SV_indptr = ((PyArrayObject *)__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_SV_data = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; + + /* "sklearn/svm/libsvm_sparse.pyx":176 + * cdef np.ndarray SV_data, SV_indices, SV_indptr + * SV_data = np.empty(nonzero_SV, dtype=np.float64) + * SV_indices = np.empty(nonzero_SV, dtype=np.int32) # <<<<<<<<<<<<<< + * SV_indptr = np.empty(SV_len + 1, dtype=np.int32) + * csr_copy_SV(SV_data.data, SV_indices.shape, SV_indices.data, + */ + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s__empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_nonzero_SV); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__int32); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_SV_indices = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/svm/libsvm_sparse.pyx":177 + * SV_data = np.empty(nonzero_SV, dtype=np.float64) + * SV_indices = np.empty(nonzero_SV, dtype=np.int32) + * SV_indptr = np.empty(SV_len + 1, dtype=np.int32) # <<<<<<<<<<<<<< + * csr_copy_SV(SV_data.data, SV_indices.shape, SV_indices.data, + * SV_indptr.shape, SV_indptr.data, model, n_features) + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyInt_FromLong((((npy_intp)__pyx_v_SV_len) + 1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__int32); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_SV_indptr = ((PyArrayObject *)__pyx_t_3); + __pyx_t_3 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":161 + /* "sklearn/svm/libsvm_sparse.pyx":179 * SV_indptr = np.empty(SV_len + 1, dtype=np.int32) * csr_copy_SV(SV_data.data, SV_indices.shape, SV_indices.data, * SV_indptr.shape, SV_indptr.data, model, n_features) # <<<<<<<<<<<<<< @@ -2043,251 +2370,205 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH */ csr_copy_SV(__pyx_v_SV_data->data, __pyx_v_SV_indices->dimensions, __pyx_v_SV_indices->data, __pyx_v_SV_indptr->dimensions, __pyx_v_SV_indptr->data, __pyx_v_model, __pyx_v_n_features); - /* "sklearn/svm/libsvm_sparse.pyx":162 + /* "sklearn/svm/libsvm_sparse.pyx":180 * csr_copy_SV(SV_data.data, SV_indices.shape, SV_indices.data, * SV_indptr.shape, SV_indptr.data, model, n_features) * support_vectors_ = sparse.csr_matrix( # <<<<<<<<<<<<<< * (SV_data, SV_indices, SV_indptr), (SV_len, n_features)) * */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__sparse); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__csr_matrix); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__sparse); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__csr_matrix); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":163 + /* "sklearn/svm/libsvm_sparse.pyx":181 * SV_indptr.shape, SV_indptr.data, model, n_features) * support_vectors_ = sparse.csr_matrix( * (SV_data, SV_indices, SV_indptr), (SV_len, n_features)) # <<<<<<<<<<<<<< * * # copy model.nSV */ - __pyx_t_6 = PyTuple_New(3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(((PyObject *)__pyx_v_SV_data)); - PyTuple_SET_ITEM(__pyx_t_6, 0, ((PyObject *)__pyx_v_SV_data)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_SV_data)); __Pyx_GIVEREF(((PyObject *)__pyx_v_SV_data)); __Pyx_INCREF(((PyObject *)__pyx_v_SV_indices)); - PyTuple_SET_ITEM(__pyx_t_6, 1, ((PyObject *)__pyx_v_SV_indices)); + PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_v_SV_indices)); __Pyx_GIVEREF(((PyObject *)__pyx_v_SV_indices)); __Pyx_INCREF(((PyObject *)__pyx_v_SV_indptr)); - PyTuple_SET_ITEM(__pyx_t_6, 2, ((PyObject *)__pyx_v_SV_indptr)); + PyTuple_SET_ITEM(__pyx_t_3, 2, ((PyObject *)__pyx_v_SV_indptr)); __Pyx_GIVEREF(((PyObject *)__pyx_v_SV_indptr)); - __pyx_t_7 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_SV_len); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_SV_len); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = PyInt_FromLong(__pyx_v_n_features); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_7); + __pyx_t_6 = PyInt_FromLong(__pyx_v_n_features); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); __pyx_t_7 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_6)); - PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_t_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); __pyx_t_6 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_v_support_vectors_ = __pyx_t_4; - __pyx_t_4 = 0; + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + PyTuple_SET_ITEM(__pyx_t_6, 1, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = 0; + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + __pyx_v_support_vectors_ = __pyx_t_5; + __pyx_t_5 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":168 + /* "sklearn/svm/libsvm_sparse.pyx":186 * # TODO: do only in classification * cdef np.ndarray n_class_SV * n_class_SV = np.empty(n_class, dtype=np.int32) # <<<<<<<<<<<<<< * copy_nSV(n_class_SV.data, model) * */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_n_class); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__int32); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_n_class); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__int32); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_n_class_SV = ((PyArrayObject *)__pyx_t_7); __pyx_t_7 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":169 + /* "sklearn/svm/libsvm_sparse.pyx":187 * cdef np.ndarray n_class_SV * n_class_SV = np.empty(n_class, dtype=np.int32) * copy_nSV(n_class_SV.data, model) # <<<<<<<<<<<<<< * - * # # copy label - */ - copy_nSV(__pyx_v_n_class_SV->data, __pyx_v_model); - - /* "sklearn/svm/libsvm_sparse.pyx":173 - * # # copy label - * cdef np.ndarray label - * label = np.empty((n_class), dtype=np.int32) # <<<<<<<<<<<<<< - * copy_label(label.data, model) - * - */ - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_n_class); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__int32); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_label = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; - - /* "sklearn/svm/libsvm_sparse.pyx":174 - * cdef np.ndarray label - * label = np.empty((n_class), dtype=np.int32) - * copy_label(label.data, model) # <<<<<<<<<<<<<< - * * # # copy probabilities */ - copy_label(__pyx_v_label->data, __pyx_v_model); + copy_nSV(__pyx_v_n_class_SV->data, __pyx_v_model); - /* "sklearn/svm/libsvm_sparse.pyx":178 + /* "sklearn/svm/libsvm_sparse.pyx":191 * # # copy probabilities * cdef np.ndarray probA, probB * if probability != 0: # <<<<<<<<<<<<<< * if svm_type < 2: # SVC and NuSVC * probA = np.empty(n_class*(n_class-1)/2, dtype=np.float64) */ - __pyx_t_14 = (__pyx_v_probability != 0); - if (__pyx_t_14) { + __pyx_t_15 = ((__pyx_v_probability != 0) != 0); + if (__pyx_t_15) { - /* "sklearn/svm/libsvm_sparse.pyx":179 + /* "sklearn/svm/libsvm_sparse.pyx":192 * cdef np.ndarray probA, probB * if probability != 0: * if svm_type < 2: # SVC and NuSVC # <<<<<<<<<<<<<< * probA = np.empty(n_class*(n_class-1)/2, dtype=np.float64) * probB = np.empty(n_class*(n_class-1)/2, dtype=np.float64) */ - __pyx_t_14 = (__pyx_v_svm_type < 2); - if (__pyx_t_14) { + __pyx_t_15 = ((__pyx_v_svm_type < 2) != 0); + if (__pyx_t_15) { - /* "sklearn/svm/libsvm_sparse.pyx":180 + /* "sklearn/svm/libsvm_sparse.pyx":193 * if probability != 0: * if svm_type < 2: # SVC and NuSVC * probA = np.empty(n_class*(n_class-1)/2, dtype=np.float64) # <<<<<<<<<<<<<< * probB = np.empty(n_class*(n_class-1)/2, dtype=np.float64) * copy_probB(probB.data, model, probB.shape) */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyInt_FromLong(__Pyx_div_long((__pyx_v_n_class * (__pyx_v_n_class - 1)), 2)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s__empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_6); - __pyx_t_6 = 0; - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyInt_FromLong(__Pyx_div_long((__pyx_v_n_class * (__pyx_v_n_class - 1)), 2)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__float64); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_7)); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s__float64); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_probA = ((PyArrayObject *)__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":181 + /* "sklearn/svm/libsvm_sparse.pyx":194 * if svm_type < 2: # SVC and NuSVC * probA = np.empty(n_class*(n_class-1)/2, dtype=np.float64) * probB = np.empty(n_class*(n_class-1)/2, dtype=np.float64) # <<<<<<<<<<<<<< * copy_probB(probB.data, model, probB.shape) * else: */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyInt_FromLong(__Pyx_div_long((__pyx_v_n_class * (__pyx_v_n_class - 1)), 2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(__Pyx_div_long((__pyx_v_n_class * (__pyx_v_n_class - 1)), 2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_6 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_probB = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_probB = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":182 + /* "sklearn/svm/libsvm_sparse.pyx":195 * probA = np.empty(n_class*(n_class-1)/2, dtype=np.float64) * probB = np.empty(n_class*(n_class-1)/2, dtype=np.float64) * copy_probB(probB.data, model, probB.shape) # <<<<<<<<<<<<<< @@ -2295,71 +2576,71 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH * probA = np.empty(1, dtype=np.float64) */ copy_probB(__pyx_v_probB->data, __pyx_v_model, __pyx_v_probB->dimensions); - goto __pyx_L7; + goto __pyx_L10; } /*else*/ { - /* "sklearn/svm/libsvm_sparse.pyx":184 + /* "sklearn/svm/libsvm_sparse.pyx":197 * copy_probB(probB.data, model, probB.shape) * else: * probA = np.empty(1, dtype=np.float64) # <<<<<<<<<<<<<< * probB = np.empty(0, dtype=np.float64) * copy_probA(probA.data, model, probA.shape) */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_k_tuple_5), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_k_tuple_5), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_probA = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_probA = ((PyArrayObject *)__pyx_t_7); + __pyx_t_7 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":185 + /* "sklearn/svm/libsvm_sparse.pyx":198 * else: * probA = np.empty(1, dtype=np.float64) * probB = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * copy_probA(probA.data, model, probA.shape) * else: */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s__empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_7)); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_k_tuple_6), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_probB = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_k_tuple_6), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_probB = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; } - __pyx_L7:; + __pyx_L10:; - /* "sklearn/svm/libsvm_sparse.pyx":186 + /* "sklearn/svm/libsvm_sparse.pyx":199 * probA = np.empty(1, dtype=np.float64) * probB = np.empty(0, dtype=np.float64) * copy_probA(probA.data, model, probA.shape) # <<<<<<<<<<<<<< @@ -2367,71 +2648,71 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH * probA = np.empty(0, dtype=np.float64) */ copy_probA(__pyx_v_probA->data, __pyx_v_model, __pyx_v_probA->dimensions); - goto __pyx_L6; + goto __pyx_L9; } /*else*/ { - /* "sklearn/svm/libsvm_sparse.pyx":188 + /* "sklearn/svm/libsvm_sparse.pyx":201 * copy_probA(probA.data, model, probA.shape) * else: * probA = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * probB = np.empty(0, dtype=np.float64) * */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 188; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 188; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 188; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 188; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__float64); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 188; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 188; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_k_tuple_7), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 188; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s__float64); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 188; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_k_tuple_7), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_probA = ((PyArrayObject *)__pyx_t_3); __pyx_t_3 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":189 + /* "sklearn/svm/libsvm_sparse.pyx":202 * else: * probA = np.empty(0, dtype=np.float64) * probB = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * * svm_csr_free_and_destroy_model (&model) */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s__float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_k_tuple_8), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_k_tuple_8), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_probB = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_probB = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; } - __pyx_L6:; + __pyx_L9:; - /* "sklearn/svm/libsvm_sparse.pyx":191 + /* "sklearn/svm/libsvm_sparse.pyx":204 * probB = np.empty(0, dtype=np.float64) * * svm_csr_free_and_destroy_model (&model) # <<<<<<<<<<<<<< @@ -2440,7 +2721,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH */ svm_csr_free_and_destroy_model((&__pyx_v_model)); - /* "sklearn/svm/libsvm_sparse.pyx":192 + /* "sklearn/svm/libsvm_sparse.pyx":205 * * svm_csr_free_and_destroy_model (&model) * free_problem(problem) # <<<<<<<<<<<<<< @@ -2449,48 +2730,61 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH */ free_problem(__pyx_v_problem); - /* "sklearn/svm/libsvm_sparse.pyx":193 + /* "sklearn/svm/libsvm_sparse.pyx":206 * svm_csr_free_and_destroy_model (&model) * free_problem(problem) * free_param(param) # <<<<<<<<<<<<<< * - * return support_vectors_, sv_coef_data, intercept, label, n_class_SV, probA, probB + * return (support, support_vectors_, sv_coef_data, intercept, n_class_SV, */ free_param(__pyx_v_param); - /* "sklearn/svm/libsvm_sparse.pyx":195 + /* "sklearn/svm/libsvm_sparse.pyx":208 * free_param(param) * - * return support_vectors_, sv_coef_data, intercept, label, n_class_SV, probA, probB # <<<<<<<<<<<<<< - * + * return (support, support_vectors_, sv_coef_data, intercept, n_class_SV, # <<<<<<<<<<<<<< + * probA, probB, fit_status) * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = PyTuple_New(7); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + + /* "sklearn/svm/libsvm_sparse.pyx":209 + * + * return (support, support_vectors_, sv_coef_data, intercept, n_class_SV, + * probA, probB, fit_status) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_6 = PyInt_FromLong(__pyx_v_fit_status); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = PyTuple_New(8); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_support)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_support)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_support)); __Pyx_INCREF(__pyx_v_support_vectors_); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_support_vectors_); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_support_vectors_); __Pyx_GIVEREF(__pyx_v_support_vectors_); __Pyx_INCREF(((PyObject *)__pyx_v_sv_coef_data)); - PyTuple_SET_ITEM(__pyx_t_4, 1, ((PyObject *)__pyx_v_sv_coef_data)); + PyTuple_SET_ITEM(__pyx_t_3, 2, ((PyObject *)__pyx_v_sv_coef_data)); __Pyx_GIVEREF(((PyObject *)__pyx_v_sv_coef_data)); __Pyx_INCREF(((PyObject *)__pyx_v_intercept)); - PyTuple_SET_ITEM(__pyx_t_4, 2, ((PyObject *)__pyx_v_intercept)); + PyTuple_SET_ITEM(__pyx_t_3, 3, ((PyObject *)__pyx_v_intercept)); __Pyx_GIVEREF(((PyObject *)__pyx_v_intercept)); - __Pyx_INCREF(((PyObject *)__pyx_v_label)); - PyTuple_SET_ITEM(__pyx_t_4, 3, ((PyObject *)__pyx_v_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_label)); __Pyx_INCREF(((PyObject *)__pyx_v_n_class_SV)); - PyTuple_SET_ITEM(__pyx_t_4, 4, ((PyObject *)__pyx_v_n_class_SV)); + PyTuple_SET_ITEM(__pyx_t_3, 4, ((PyObject *)__pyx_v_n_class_SV)); __Pyx_GIVEREF(((PyObject *)__pyx_v_n_class_SV)); __Pyx_INCREF(((PyObject *)__pyx_v_probA)); - PyTuple_SET_ITEM(__pyx_t_4, 5, ((PyObject *)__pyx_v_probA)); + PyTuple_SET_ITEM(__pyx_t_3, 5, ((PyObject *)__pyx_v_probA)); __Pyx_GIVEREF(((PyObject *)__pyx_v_probA)); __Pyx_INCREF(((PyObject *)__pyx_v_probB)); - PyTuple_SET_ITEM(__pyx_t_4, 6, ((PyObject *)__pyx_v_probB)); + PyTuple_SET_ITEM(__pyx_t_3, 6, ((PyObject *)__pyx_v_probB)); __Pyx_GIVEREF(((PyObject *)__pyx_v_probB)); - __pyx_r = ((PyObject *)__pyx_t_4); - __pyx_t_4 = 0; + PyTuple_SET_ITEM(__pyx_t_3, 7, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_r = ((PyObject *)__pyx_t_3); + __pyx_t_3 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); @@ -2504,33 +2798,36 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_libsvm_sparse_train(CYTH { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Y.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_support.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_values.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.svm.libsvm_sparse.libsvm_sparse_train", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Y.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_support.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_values.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer); __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_class_weight_label); __Pyx_XDECREF((PyObject *)__pyx_v_sv_coef_data); + __Pyx_XDECREF((PyObject *)__pyx_v_support); __Pyx_XDECREF((PyObject *)__pyx_v_intercept); __Pyx_XDECREF((PyObject *)__pyx_v_SV_data); __Pyx_XDECREF((PyObject *)__pyx_v_SV_indices); __Pyx_XDECREF((PyObject *)__pyx_v_SV_indptr); __Pyx_XDECREF(__pyx_v_support_vectors_); __Pyx_XDECREF((PyObject *)__pyx_v_n_class_SV); - __Pyx_XDECREF((PyObject *)__pyx_v_label); __Pyx_XDECREF((PyObject *)__pyx_v_probA); __Pyx_XDECREF((PyObject *)__pyx_v_probB); __Pyx_XDECREF((PyObject *)__pyx_v_sample_weight); @@ -2559,29 +2856,27 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_3libsvm_sparse_predict(P double __pyx_v_coef0; double __pyx_v_eps; double __pyx_v_C; - PyArrayObject *__pyx_v_weight_label = 0; - PyArrayObject *__pyx_v_weight = 0; + PyArrayObject *__pyx_v_class_weight = 0; double __pyx_v_nu; double __pyx_v_p; int __pyx_v_shrinking; int __pyx_v_probability; PyArrayObject *__pyx_v_nSV = 0; - PyArrayObject *__pyx_v_label = 0; PyArrayObject *__pyx_v_probA = 0; PyArrayObject *__pyx_v_probB = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__T_data,&__pyx_n_s__T_indices,&__pyx_n_s__T_indptr,&__pyx_n_s__SV_data,&__pyx_n_s__SV_indices,&__pyx_n_s__SV_indptr,&__pyx_n_s__sv_coef,&__pyx_n_s__intercept,&__pyx_n_s__svm_type,&__pyx_n_s__kernel_type,&__pyx_n_s__degree,&__pyx_n_s__gamma,&__pyx_n_s__coef0,&__pyx_n_s__eps,&__pyx_n_s__C,&__pyx_n_s__weight_label,&__pyx_n_s__weight,&__pyx_n_s__nu,&__pyx_n_s__p,&__pyx_n_s__shrinking,&__pyx_n_s__probability,&__pyx_n_s__nSV,&__pyx_n_s__label,&__pyx_n_s__probA,&__pyx_n_s__probB,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("libsvm_sparse_predict (wrapper)", 0); - __pyx_self = __pyx_self; { - PyObject* values[25] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__T_data,&__pyx_n_s__T_indices,&__pyx_n_s__T_indptr,&__pyx_n_s__SV_data,&__pyx_n_s__SV_indices,&__pyx_n_s__SV_indptr,&__pyx_n_s__sv_coef,&__pyx_n_s__intercept,&__pyx_n_s__svm_type,&__pyx_n_s__kernel_type,&__pyx_n_s__degree,&__pyx_n_s__gamma,&__pyx_n_s__coef0,&__pyx_n_s__eps,&__pyx_n_s__C,&__pyx_n_s__class_weight,&__pyx_n_s__nu,&__pyx_n_s__p,&__pyx_n_s__shrinking,&__pyx_n_s__probability,&__pyx_n_s__nSV,&__pyx_n_s__probA,&__pyx_n_s__probB,0}; + PyObject* values[23] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { - case 25: values[24] = PyTuple_GET_ITEM(__pyx_args, 24); - case 24: values[23] = PyTuple_GET_ITEM(__pyx_args, 23); case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); @@ -2611,158 +2906,123 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_3libsvm_sparse_predict(P kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_data); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_data)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_indices); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_indices)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_indptr); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_indptr)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_data); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_data)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_indices); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_indices)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_indptr); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_indptr)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sv_coef); - if (likely(values[6])) kw_args--; + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sv_coef)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: - values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__intercept); - if (likely(values[7])) kw_args--; + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__intercept)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: - values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__svm_type); - if (likely(values[8])) kw_args--; + if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__svm_type)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: - values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kernel_type); - if (likely(values[9])) kw_args--; + if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kernel_type)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: - values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__degree); - if (likely(values[10])) kw_args--; + if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__degree)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 11: - values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__gamma); - if (likely(values[11])) kw_args--; + if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__gamma)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 12: - values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coef0); - if (likely(values[12])) kw_args--; + if (likely((values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coef0)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 13: - values[13] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__eps); - if (likely(values[13])) kw_args--; + if (likely((values[13] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__eps)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 13); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 13); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 14: - values[14] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C); - if (likely(values[14])) kw_args--; + if (likely((values[14] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 14); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 14); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 15: - values[15] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight_label); - if (likely(values[15])) kw_args--; + if (likely((values[15] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 15); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 15); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 16: - values[16] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight); - if (likely(values[16])) kw_args--; + if (likely((values[16] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nu)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 16); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 16); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 17: - values[17] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nu); - if (likely(values[17])) kw_args--; + if (likely((values[17] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 17); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 17); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 18: - values[18] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[18])) kw_args--; + if (likely((values[18] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shrinking)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 18); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 18); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 19: - values[19] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shrinking); - if (likely(values[19])) kw_args--; + if (likely((values[19] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probability)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 19); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 19); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 20: - values[20] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probability); - if (likely(values[20])) kw_args--; + if (likely((values[20] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nSV)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 20); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 20); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 21: - values[21] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nSV); - if (likely(values[21])) kw_args--; + if (likely((values[21] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probA)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 21); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 21); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 22: - values[22] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__label); - if (likely(values[22])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 22); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 23: - values[23] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probA); - if (likely(values[23])) kw_args--; + if (likely((values[22] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probB)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 23); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 24: - values[24] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probB); - if (likely(values[24])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, 24); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, 22); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "libsvm_sparse_predict") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "libsvm_sparse_predict") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - } else if (PyTuple_GET_SIZE(__pyx_args) != 25) { + } else if (PyTuple_GET_SIZE(__pyx_args) != 23) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); @@ -2788,8 +3048,6 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_3libsvm_sparse_predict(P values[20] = PyTuple_GET_ITEM(__pyx_args, 20); values[21] = PyTuple_GET_ITEM(__pyx_args, 21); values[22] = PyTuple_GET_ITEM(__pyx_args, 22); - values[23] = PyTuple_GET_ITEM(__pyx_args, 23); - values[24] = PyTuple_GET_ITEM(__pyx_args, 24); } __pyx_v_T_data = ((PyArrayObject *)values[0]); __pyx_v_T_indices = ((PyArrayObject *)values[1]); @@ -2799,47 +3057,43 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_3libsvm_sparse_predict(P __pyx_v_SV_indptr = ((PyArrayObject *)values[5]); __pyx_v_sv_coef = ((PyArrayObject *)values[6]); __pyx_v_intercept = ((PyArrayObject *)values[7]); - __pyx_v_svm_type = __Pyx_PyInt_AsInt(values[8]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_kernel_type = __Pyx_PyInt_AsInt(values[9]); if (unlikely((__pyx_v_kernel_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_degree = __Pyx_PyInt_AsInt(values[10]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_eps = __pyx_PyFloat_AsDouble(values[13]); if (unlikely((__pyx_v_eps == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_C = __pyx_PyFloat_AsDouble(values[14]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_weight_label = ((PyArrayObject *)values[15]); - __pyx_v_weight = ((PyArrayObject *)values[16]); - __pyx_v_nu = __pyx_PyFloat_AsDouble(values[17]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_p = __pyx_PyFloat_AsDouble(values[18]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_shrinking = __Pyx_PyInt_AsInt(values[19]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_probability = __Pyx_PyInt_AsInt(values[20]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_nSV = ((PyArrayObject *)values[21]); - __pyx_v_label = ((PyArrayObject *)values[22]); - __pyx_v_probA = ((PyArrayObject *)values[23]); - __pyx_v_probB = ((PyArrayObject *)values[24]); + __pyx_v_svm_type = __Pyx_PyInt_AsInt(values[8]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_kernel_type = __Pyx_PyInt_AsInt(values[9]); if (unlikely((__pyx_v_kernel_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_degree = __Pyx_PyInt_AsInt(values[10]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_eps = __pyx_PyFloat_AsDouble(values[13]); if (unlikely((__pyx_v_eps == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_C = __pyx_PyFloat_AsDouble(values[14]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_class_weight = ((PyArrayObject *)values[15]); + __pyx_v_nu = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_p = __pyx_PyFloat_AsDouble(values[17]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_shrinking = __Pyx_PyInt_AsInt(values[18]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_probability = __Pyx_PyInt_AsInt(values[19]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_nSV = ((PyArrayObject *)values[20]); + __pyx_v_probA = ((PyArrayObject *)values[21]); + __pyx_v_probB = ((PyArrayObject *)values[22]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 25, 25, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict", 1, 23, 23, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.svm.libsvm_sparse.libsvm_sparse_predict", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_data), __pyx_ptype_5numpy_ndarray, 1, "T_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_indices), __pyx_ptype_5numpy_ndarray, 1, "T_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_indptr), __pyx_ptype_5numpy_ndarray, 1, "T_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_data), __pyx_ptype_5numpy_ndarray, 1, "SV_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_indices), __pyx_ptype_5numpy_ndarray, 1, "SV_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_indptr), __pyx_ptype_5numpy_ndarray, 1, "SV_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sv_coef), __pyx_ptype_5numpy_ndarray, 1, "sv_coef", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_intercept), __pyx_ptype_5numpy_ndarray, 1, "intercept", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weight_label), __pyx_ptype_5numpy_ndarray, 1, "weight_label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weight), __pyx_ptype_5numpy_ndarray, 1, "weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nSV), __pyx_ptype_5numpy_ndarray, 1, "nSV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_label), __pyx_ptype_5numpy_ndarray, 1, "label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probA), __pyx_ptype_5numpy_ndarray, 1, "probA", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probB), __pyx_ptype_5numpy_ndarray, 1, "probB", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(__pyx_self, __pyx_v_T_data, __pyx_v_T_indices, __pyx_v_T_indptr, __pyx_v_SV_data, __pyx_v_SV_indices, __pyx_v_SV_indptr, __pyx_v_sv_coef, __pyx_v_intercept, __pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_eps, __pyx_v_C, __pyx_v_weight_label, __pyx_v_weight, __pyx_v_nu, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_nSV, __pyx_v_label, __pyx_v_probA, __pyx_v_probB); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_data), __pyx_ptype_5numpy_ndarray, 1, "T_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_indices), __pyx_ptype_5numpy_ndarray, 1, "T_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_indptr), __pyx_ptype_5numpy_ndarray, 1, "T_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_data), __pyx_ptype_5numpy_ndarray, 1, "SV_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_indices), __pyx_ptype_5numpy_ndarray, 1, "SV_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_indptr), __pyx_ptype_5numpy_ndarray, 1, "SV_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sv_coef), __pyx_ptype_5numpy_ndarray, 1, "sv_coef", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_intercept), __pyx_ptype_5numpy_ndarray, 1, "intercept", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nSV), __pyx_ptype_5numpy_ndarray, 1, "nSV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probA), __pyx_ptype_5numpy_ndarray, 1, "probA", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probB), __pyx_ptype_5numpy_ndarray, 1, "probB", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(__pyx_self, __pyx_v_T_data, __pyx_v_T_indices, __pyx_v_T_indptr, __pyx_v_SV_data, __pyx_v_SV_indices, __pyx_v_SV_indptr, __pyx_v_sv_coef, __pyx_v_intercept, __pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_eps, __pyx_v_C, __pyx_v_class_weight, __pyx_v_nu, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_nSV, __pyx_v_probA, __pyx_v_probB); goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -2848,7 +3102,7 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_3libsvm_sparse_predict(P return __pyx_r; } -/* "sklearn/svm/libsvm_sparse.pyx":199 +/* "sklearn/svm/libsvm_sparse.pyx":212 * * * def libsvm_sparse_predict (np.ndarray[np.float64_t, ndim=1, mode='c'] T_data, # <<<<<<<<<<<<<< @@ -2856,10 +3110,12 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_3libsvm_sparse_predict(P * np.ndarray[np.int32_t, ndim=1, mode='c'] T_indptr, */ -static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T_data, PyArrayObject *__pyx_v_T_indices, PyArrayObject *__pyx_v_T_indptr, PyArrayObject *__pyx_v_SV_data, PyArrayObject *__pyx_v_SV_indices, PyArrayObject *__pyx_v_SV_indptr, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_weight_label, PyArrayObject *__pyx_v_weight, double __pyx_v_nu, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_label, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB) { +static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T_data, PyArrayObject *__pyx_v_T_indices, PyArrayObject *__pyx_v_T_indptr, PyArrayObject *__pyx_v_SV_data, PyArrayObject *__pyx_v_SV_indices, PyArrayObject *__pyx_v_SV_indptr, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_class_weight, double __pyx_v_nu, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB) { PyArrayObject *__pyx_v_dec_values = 0; struct svm_parameter *__pyx_v_param; struct svm_csr_model *__pyx_v_model; + PyArrayObject *__pyx_v_class_weight_label = 0; + int __pyx_v_rv; __Pyx_LocalBuf_ND __pyx_pybuffernd_SV_data; __Pyx_Buffer __pyx_pybuffer_SV_data; __Pyx_LocalBuf_ND __pyx_pybuffernd_SV_indices; @@ -2872,12 +3128,14 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(C __Pyx_Buffer __pyx_pybuffer_T_indices; __Pyx_LocalBuf_ND __pyx_pybuffernd_T_indptr; __Pyx_Buffer __pyx_pybuffer_T_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_class_weight; + __Pyx_Buffer __pyx_pybuffer_class_weight; + __Pyx_LocalBuf_ND __pyx_pybuffernd_class_weight_label; + __Pyx_Buffer __pyx_pybuffer_class_weight_label; __Pyx_LocalBuf_ND __pyx_pybuffernd_dec_values; __Pyx_Buffer __pyx_pybuffer_dec_values; __Pyx_LocalBuf_ND __pyx_pybuffernd_intercept; __Pyx_Buffer __pyx_pybuffer_intercept; - __Pyx_LocalBuf_ND __pyx_pybuffernd_label; - __Pyx_Buffer __pyx_pybuffer_label; __Pyx_LocalBuf_ND __pyx_pybuffernd_nSV; __Pyx_Buffer __pyx_pybuffer_nSV; __Pyx_LocalBuf_ND __pyx_pybuffernd_probA; @@ -2886,21 +3144,20 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(C __Pyx_Buffer __pyx_pybuffer_probB; __Pyx_LocalBuf_ND __pyx_pybuffernd_sv_coef; __Pyx_Buffer __pyx_pybuffer_sv_coef; - __Pyx_LocalBuf_ND __pyx_pybuffernd_weight; - __Pyx_Buffer __pyx_pybuffer_weight; - __Pyx_LocalBuf_ND __pyx_pybuffernd_weight_label; - __Pyx_Buffer __pyx_pybuffer_weight_label; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; - PyArrayObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + PyArrayObject *__pyx_t_7 = NULL; + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; @@ -2909,6 +3166,10 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(C __pyx_pybuffer_dec_values.refcount = 0; __pyx_pybuffernd_dec_values.data = NULL; __pyx_pybuffernd_dec_values.rcbuffer = &__pyx_pybuffer_dec_values; + __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight_label.refcount = 0; + __pyx_pybuffernd_class_weight_label.data = NULL; + __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_T_data.pybuffer.buf = NULL; __pyx_pybuffer_T_data.refcount = 0; __pyx_pybuffernd_T_data.data = NULL; @@ -2941,22 +3202,14 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(C __pyx_pybuffer_intercept.refcount = 0; __pyx_pybuffernd_intercept.data = NULL; __pyx_pybuffernd_intercept.rcbuffer = &__pyx_pybuffer_intercept; - __pyx_pybuffer_weight_label.pybuffer.buf = NULL; - __pyx_pybuffer_weight_label.refcount = 0; - __pyx_pybuffernd_weight_label.data = NULL; - __pyx_pybuffernd_weight_label.rcbuffer = &__pyx_pybuffer_weight_label; - __pyx_pybuffer_weight.pybuffer.buf = NULL; - __pyx_pybuffer_weight.refcount = 0; - __pyx_pybuffernd_weight.data = NULL; - __pyx_pybuffernd_weight.rcbuffer = &__pyx_pybuffer_weight; + __pyx_pybuffer_class_weight.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight.refcount = 0; + __pyx_pybuffernd_class_weight.data = NULL; + __pyx_pybuffernd_class_weight.rcbuffer = &__pyx_pybuffer_class_weight; __pyx_pybuffer_nSV.pybuffer.buf = NULL; __pyx_pybuffer_nSV.refcount = 0; __pyx_pybuffernd_nSV.data = NULL; __pyx_pybuffernd_nSV.rcbuffer = &__pyx_pybuffer_nSV; - __pyx_pybuffer_label.pybuffer.buf = NULL; - __pyx_pybuffer_label.refcount = 0; - __pyx_pybuffernd_label.data = NULL; - __pyx_pybuffernd_label.rcbuffer = &__pyx_pybuffer_label; __pyx_pybuffer_probA.pybuffer.buf = NULL; __pyx_pybuffer_probA.refcount = 0; __pyx_pybuffernd_probA.data = NULL; @@ -2967,166 +3220,241 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(C __pyx_pybuffernd_probB.rcbuffer = &__pyx_pybuffer_probB; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_data, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_data, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_T_data.diminfo[0].strides = __pyx_pybuffernd_T_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_T_data.diminfo[0].shape = __pyx_pybuffernd_T_data.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_indices, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_indices, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_T_indices.diminfo[0].strides = __pyx_pybuffernd_T_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_T_indices.diminfo[0].shape = __pyx_pybuffernd_T_indices.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_indptr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_indptr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_T_indptr.diminfo[0].strides = __pyx_pybuffernd_T_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_T_indptr.diminfo[0].shape = __pyx_pybuffernd_T_indptr.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_data, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_data, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_SV_data.diminfo[0].strides = __pyx_pybuffernd_SV_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_SV_data.diminfo[0].shape = __pyx_pybuffernd_SV_data.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_indices, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_indices, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_SV_indices.diminfo[0].strides = __pyx_pybuffernd_SV_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_SV_indices.diminfo[0].shape = __pyx_pybuffernd_SV_indices.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_indptr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_indptr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_SV_indptr.diminfo[0].strides = __pyx_pybuffernd_SV_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_SV_indptr.diminfo[0].shape = __pyx_pybuffernd_SV_indptr.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_v_sv_coef, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_v_sv_coef, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_sv_coef.diminfo[0].strides = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sv_coef.diminfo[0].shape = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_v_intercept, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_v_intercept, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_intercept.diminfo[0].strides = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_intercept.diminfo[0].shape = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_weight_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_weight_label.diminfo[0].strides = __pyx_pybuffernd_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weight_label.diminfo[0].shape = __pyx_pybuffernd_weight_label.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_pybuffernd_weight.diminfo[0].strides = __pyx_pybuffernd_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weight.diminfo[0].shape = __pyx_pybuffernd_weight.rcbuffer->pybuffer.shape[0]; + __pyx_pybuffernd_class_weight.diminfo[0].strides = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight.diminfo[0].shape = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer, (PyObject*)__pyx_v_nSV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer, (PyObject*)__pyx_v_nSV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_nSV.diminfo[0].strides = __pyx_pybuffernd_nSV.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_nSV.diminfo[0].shape = __pyx_pybuffernd_nSV.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_pybuffernd_label.diminfo[0].strides = __pyx_pybuffernd_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_label.diminfo[0].shape = __pyx_pybuffernd_label.rcbuffer->pybuffer.shape[0]; + __pyx_pybuffernd_probA.diminfo[0].strides = __pyx_pybuffernd_probA.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probA.diminfo[0].shape = __pyx_pybuffernd_probA.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_pybuffernd_probA.diminfo[0].strides = __pyx_pybuffernd_probA.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probA.diminfo[0].shape = __pyx_pybuffernd_probA.rcbuffer->pybuffer.shape[0]; + __pyx_pybuffernd_probB.diminfo[0].strides = __pyx_pybuffernd_probB.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probB.diminfo[0].shape = __pyx_pybuffernd_probB.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/svm/libsvm_sparse.pyx":255 + * cdef svm_csr_model *model + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) # <<<<<<<<<<<<<< + * cdef int rv + * param = set_parameter(svm_type, kernel_type, degree, gamma, + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__arange); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_class_weight->dimensions[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_class_weight_label = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; + } } - __pyx_pybuffernd_probB.diminfo[0].strides = __pyx_pybuffernd_probB.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probB.diminfo[0].shape = __pyx_pybuffernd_probB.rcbuffer->pybuffer.shape[0]; + __pyx_t_6 = 0; + __pyx_v_class_weight_label = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":248 - * C, eps, p, shrinking, - * probability, weight.shape[0], weight_label.data, - * weight.data) # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm_sparse.pyx":262 + * C, eps, p, shrinking, + * probability, class_weight.shape[0], class_weight_label.data, + * class_weight.data, -1, # <<<<<<<<<<<<<< + * -1) # random seed has no effect on predict either * - * model = csr_set_model(param, nSV.shape[0], SV_data.data, */ - __pyx_v_param = set_parameter(__pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, 100., __pyx_v_C, __pyx_v_eps, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_weight->dimensions[0])), __pyx_v_weight_label->data, __pyx_v_weight->data); + __pyx_v_param = set_parameter(__pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, 100., __pyx_v_C, __pyx_v_eps, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data, -1, -1); - /* "sklearn/svm/libsvm_sparse.pyx":254 + /* "sklearn/svm/libsvm_sparse.pyx":269 * SV_indptr.shape, SV_indptr.data, * sv_coef.data, intercept.data, - * nSV.data, label.data, probA.data, probB.data) # <<<<<<<<<<<<<< + * nSV.data, probA.data, probB.data) # <<<<<<<<<<<<<< * #TODO: use check_model * dec_values = np.empty(T_indptr.shape[0]-1) */ - __pyx_v_model = csr_set_model(__pyx_v_param, ((int)(__pyx_v_nSV->dimensions[0])), __pyx_v_SV_data->data, __pyx_v_SV_indices->dimensions, __pyx_v_SV_indices->data, __pyx_v_SV_indptr->dimensions, __pyx_v_SV_indptr->data, __pyx_v_sv_coef->data, __pyx_v_intercept->data, __pyx_v_nSV->data, __pyx_v_label->data, __pyx_v_probA->data, __pyx_v_probB->data); + __pyx_v_model = csr_set_model(__pyx_v_param, ((int)(__pyx_v_nSV->dimensions[0])), __pyx_v_SV_data->data, __pyx_v_SV_indices->dimensions, __pyx_v_SV_indices->data, __pyx_v_SV_indptr->dimensions, __pyx_v_SV_indptr->data, __pyx_v_sv_coef->data, __pyx_v_intercept->data, __pyx_v_nSV->data, __pyx_v_probA->data, __pyx_v_probB->data); - /* "sklearn/svm/libsvm_sparse.pyx":256 - * nSV.data, label.data, probA.data, probB.data) + /* "sklearn/svm/libsvm_sparse.pyx":271 + * nSV.data, probA.data, probB.data) * #TODO: use check_model * dec_values = np.empty(T_indptr.shape[0]-1) # <<<<<<<<<<<<<< - * if csr_copy_predict(T_data.shape, T_data.data, - * T_indices.shape, T_indices.data, + * with nogil: + * rv = csr_copy_predict(T_data.shape, T_data.data, */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromLong(((__pyx_v_T_indptr->dimensions[0]) - 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyInt_FromLong(((__pyx_v_T_indptr->dimensions[0]) - 1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_5); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); - __pyx_t_5 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_5 < 0)) { - PyErr_Fetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); + __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_8 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_dec_values, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_6); Py_XDECREF(__pyx_t_7); Py_XDECREF(__pyx_t_8); + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_6, __pyx_t_7, __pyx_t_8); + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); } } __pyx_pybuffernd_dec_values.diminfo[0].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_dec_values.diminfo[0].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_7 = 0; + __pyx_v_dec_values = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "sklearn/svm/libsvm_sparse.pyx":272 + * #TODO: use check_model + * dec_values = np.empty(T_indptr.shape[0]-1) + * with nogil: # <<<<<<<<<<<<<< + * rv = csr_copy_predict(T_data.shape, T_data.data, + * T_indices.shape, T_indices.data, + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/svm/libsvm_sparse.pyx":276 + * T_indices.shape, T_indices.data, + * T_indptr.shape, T_indptr.data, + * model, dec_values.data) # <<<<<<<<<<<<<< + * if rv < 0: + * raise MemoryError("We've run out of memory") + */ + __pyx_v_rv = csr_copy_predict(__pyx_v_T_data->dimensions, __pyx_v_T_data->data, __pyx_v_T_indices->dimensions, __pyx_v_T_indices->data, __pyx_v_T_indptr->dimensions, __pyx_v_T_indptr->data, __pyx_v_model, __pyx_v_dec_values->data); + } + + /* "sklearn/svm/libsvm_sparse.pyx":272 + * #TODO: use check_model + * dec_values = np.empty(T_indptr.shape[0]-1) + * with nogil: # <<<<<<<<<<<<<< + * rv = csr_copy_predict(T_data.shape, T_data.data, + * T_indices.shape, T_indices.data, + */ + /*finally:*/ { + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + } } - __pyx_t_4 = 0; - __pyx_v_dec_values = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":260 - * T_indices.shape, T_indices.data, - * T_indptr.shape, T_indptr.data, - * model, dec_values.data) < 0: # <<<<<<<<<<<<<< - * raise MemoryError("We've run out of of memory") + /* "sklearn/svm/libsvm_sparse.pyx":277 + * T_indptr.shape, T_indptr.data, + * model, dec_values.data) + * if rv < 0: # <<<<<<<<<<<<<< + * raise MemoryError("We've run out of memory") * # free model and param */ - __pyx_t_9 = (csr_copy_predict(__pyx_v_T_data->dimensions, __pyx_v_T_data->data, __pyx_v_T_indices->dimensions, __pyx_v_T_indices->data, __pyx_v_T_indptr->dimensions, __pyx_v_T_indptr->data, __pyx_v_model, __pyx_v_dec_values->data) < 0); - if (__pyx_t_9) { + __pyx_t_12 = ((__pyx_v_rv < 0) != 0); + if (__pyx_t_12) { - /* "sklearn/svm/libsvm_sparse.pyx":261 - * T_indptr.shape, T_indptr.data, - * model, dec_values.data) < 0: - * raise MemoryError("We've run out of of memory") # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm_sparse.pyx":278 + * model, dec_values.data) + * if rv < 0: + * raise MemoryError("We've run out of memory") # <<<<<<<<<<<<<< * # free model and param * free_model_SV(model) */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; + __pyx_t_5 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; } - __pyx_L3:; + __pyx_L6:; - /* "sklearn/svm/libsvm_sparse.pyx":263 - * raise MemoryError("We've run out of of memory") + /* "sklearn/svm/libsvm_sparse.pyx":280 + * raise MemoryError("We've run out of memory") * # free model and param * free_model_SV(model) # <<<<<<<<<<<<<< * free_model(model) @@ -3134,7 +3462,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(C */ free_model_SV(__pyx_v_model); - /* "sklearn/svm/libsvm_sparse.pyx":264 + /* "sklearn/svm/libsvm_sparse.pyx":281 * # free model and param * free_model_SV(model) * free_model(model) # <<<<<<<<<<<<<< @@ -3143,7 +3471,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(C */ free_model(__pyx_v_model); - /* "sklearn/svm/libsvm_sparse.pyx":265 + /* "sklearn/svm/libsvm_sparse.pyx":282 * free_model_SV(model) * free_model(model) * free_param(param) # <<<<<<<<<<<<<< @@ -3152,7 +3480,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(C */ free_param(__pyx_v_param); - /* "sklearn/svm/libsvm_sparse.pyx":266 + /* "sklearn/svm/libsvm_sparse.pyx":283 * free_model(model) * free_param(param) * return dec_values # <<<<<<<<<<<<<< @@ -3170,6 +3498,8 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(C __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_SV_data.rcbuffer->pybuffer); @@ -3178,15 +3508,14 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(C __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_data.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_indices.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.svm.libsvm_sparse.libsvm_sparse_predict", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; @@ -3198,17 +3527,17 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_2libsvm_sparse_predict(C __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_data.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_indices.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_dec_values); + __Pyx_XDECREF((PyObject *)__pyx_v_class_weight_label); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; @@ -3234,29 +3563,27 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_5libsvm_sparse_predict_p double __pyx_v_coef0; double __pyx_v_eps; double __pyx_v_C; - PyArrayObject *__pyx_v_weight_label = 0; - PyArrayObject *__pyx_v_weight = 0; + PyArrayObject *__pyx_v_class_weight = 0; double __pyx_v_nu; double __pyx_v_p; int __pyx_v_shrinking; int __pyx_v_probability; PyArrayObject *__pyx_v_nSV = 0; - PyArrayObject *__pyx_v_label = 0; PyArrayObject *__pyx_v_probA = 0; PyArrayObject *__pyx_v_probB = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__T_data,&__pyx_n_s__T_indices,&__pyx_n_s__T_indptr,&__pyx_n_s__SV_data,&__pyx_n_s__SV_indices,&__pyx_n_s__SV_indptr,&__pyx_n_s__sv_coef,&__pyx_n_s__intercept,&__pyx_n_s__svm_type,&__pyx_n_s__kernel_type,&__pyx_n_s__degree,&__pyx_n_s__gamma,&__pyx_n_s__coef0,&__pyx_n_s__eps,&__pyx_n_s__C,&__pyx_n_s__weight_label,&__pyx_n_s__weight,&__pyx_n_s__nu,&__pyx_n_s__p,&__pyx_n_s__shrinking,&__pyx_n_s__probability,&__pyx_n_s__nSV,&__pyx_n_s__label,&__pyx_n_s__probA,&__pyx_n_s__probB,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("libsvm_sparse_predict_proba (wrapper)", 0); - __pyx_self = __pyx_self; { - PyObject* values[25] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__T_data,&__pyx_n_s__T_indices,&__pyx_n_s__T_indptr,&__pyx_n_s__SV_data,&__pyx_n_s__SV_indices,&__pyx_n_s__SV_indptr,&__pyx_n_s__sv_coef,&__pyx_n_s__intercept,&__pyx_n_s__svm_type,&__pyx_n_s__kernel_type,&__pyx_n_s__degree,&__pyx_n_s__gamma,&__pyx_n_s__coef0,&__pyx_n_s__eps,&__pyx_n_s__C,&__pyx_n_s__class_weight,&__pyx_n_s__nu,&__pyx_n_s__p,&__pyx_n_s__shrinking,&__pyx_n_s__probability,&__pyx_n_s__nSV,&__pyx_n_s__probA,&__pyx_n_s__probB,0}; + PyObject* values[23] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { - case 25: values[24] = PyTuple_GET_ITEM(__pyx_args, 24); - case 24: values[23] = PyTuple_GET_ITEM(__pyx_args, 23); case 23: values[22] = PyTuple_GET_ITEM(__pyx_args, 22); case 22: values[21] = PyTuple_GET_ITEM(__pyx_args, 21); case 21: values[20] = PyTuple_GET_ITEM(__pyx_args, 20); @@ -3286,158 +3613,123 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_5libsvm_sparse_predict_p kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_data); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_data)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_indices); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_indices)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_indptr); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__T_indptr)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_data); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_data)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_indices); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_indices)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: - values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_indptr); - if (likely(values[5])) kw_args--; + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__SV_indptr)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: - values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sv_coef); - if (likely(values[6])) kw_args--; + if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sv_coef)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: - values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__intercept); - if (likely(values[7])) kw_args--; + if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__intercept)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: - values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__svm_type); - if (likely(values[8])) kw_args--; + if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__svm_type)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: - values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kernel_type); - if (likely(values[9])) kw_args--; + if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kernel_type)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: - values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__degree); - if (likely(values[10])) kw_args--; + if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__degree)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 11: - values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__gamma); - if (likely(values[11])) kw_args--; + if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__gamma)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 12: - values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coef0); - if (likely(values[12])) kw_args--; + if (likely((values[12] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coef0)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 12); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 13: - values[13] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__eps); - if (likely(values[13])) kw_args--; + if (likely((values[13] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__eps)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 13); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 13); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 14: - values[14] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C); - if (likely(values[14])) kw_args--; + if (likely((values[14] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__C)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 14); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 14); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 15: - values[15] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight_label); - if (likely(values[15])) kw_args--; + if (likely((values[15] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__class_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 15); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 15); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 16: - values[16] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__weight); - if (likely(values[16])) kw_args--; + if (likely((values[16] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nu)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 16); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 16); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 17: - values[17] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nu); - if (likely(values[17])) kw_args--; + if (likely((values[17] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 17); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 17); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 18: - values[18] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (likely(values[18])) kw_args--; + if (likely((values[18] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shrinking)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 18); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 18); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 19: - values[19] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shrinking); - if (likely(values[19])) kw_args--; + if (likely((values[19] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probability)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 19); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 19); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 20: - values[20] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probability); - if (likely(values[20])) kw_args--; + if (likely((values[20] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nSV)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 20); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 20); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 21: - values[21] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nSV); - if (likely(values[21])) kw_args--; + if (likely((values[21] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probA)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 21); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 21); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 22: - values[22] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__label); - if (likely(values[22])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 22); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 23: - values[23] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probA); - if (likely(values[23])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 23); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 24: - values[24] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probB); - if (likely(values[24])) kw_args--; + if (likely((values[22] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__probB)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, 24); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, 22); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "libsvm_sparse_predict_proba") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "libsvm_sparse_predict_proba") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - } else if (PyTuple_GET_SIZE(__pyx_args) != 25) { + } else if (PyTuple_GET_SIZE(__pyx_args) != 23) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); @@ -3463,8 +3755,6 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_5libsvm_sparse_predict_p values[20] = PyTuple_GET_ITEM(__pyx_args, 20); values[21] = PyTuple_GET_ITEM(__pyx_args, 21); values[22] = PyTuple_GET_ITEM(__pyx_args, 22); - values[23] = PyTuple_GET_ITEM(__pyx_args, 23); - values[24] = PyTuple_GET_ITEM(__pyx_args, 24); } __pyx_v_T_data = ((PyArrayObject *)values[0]); __pyx_v_T_indices = ((PyArrayObject *)values[1]); @@ -3474,47 +3764,43 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_5libsvm_sparse_predict_p __pyx_v_SV_indptr = ((PyArrayObject *)values[5]); __pyx_v_sv_coef = ((PyArrayObject *)values[6]); __pyx_v_intercept = ((PyArrayObject *)values[7]); - __pyx_v_svm_type = __Pyx_PyInt_AsInt(values[8]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_kernel_type = __Pyx_PyInt_AsInt(values[9]); if (unlikely((__pyx_v_kernel_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_degree = __Pyx_PyInt_AsInt(values[10]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_eps = __pyx_PyFloat_AsDouble(values[13]); if (unlikely((__pyx_v_eps == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_C = __pyx_PyFloat_AsDouble(values[14]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_weight_label = ((PyArrayObject *)values[15]); - __pyx_v_weight = ((PyArrayObject *)values[16]); - __pyx_v_nu = __pyx_PyFloat_AsDouble(values[17]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_p = __pyx_PyFloat_AsDouble(values[18]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_shrinking = __Pyx_PyInt_AsInt(values[19]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_probability = __Pyx_PyInt_AsInt(values[20]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_nSV = ((PyArrayObject *)values[21]); - __pyx_v_label = ((PyArrayObject *)values[22]); - __pyx_v_probA = ((PyArrayObject *)values[23]); - __pyx_v_probB = ((PyArrayObject *)values[24]); + __pyx_v_svm_type = __Pyx_PyInt_AsInt(values[8]); if (unlikely((__pyx_v_svm_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_kernel_type = __Pyx_PyInt_AsInt(values[9]); if (unlikely((__pyx_v_kernel_type == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_degree = __Pyx_PyInt_AsInt(values[10]); if (unlikely((__pyx_v_degree == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_gamma = __pyx_PyFloat_AsDouble(values[11]); if (unlikely((__pyx_v_gamma == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_coef0 = __pyx_PyFloat_AsDouble(values[12]); if (unlikely((__pyx_v_coef0 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_eps = __pyx_PyFloat_AsDouble(values[13]); if (unlikely((__pyx_v_eps == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_C = __pyx_PyFloat_AsDouble(values[14]); if (unlikely((__pyx_v_C == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_class_weight = ((PyArrayObject *)values[15]); + __pyx_v_nu = __pyx_PyFloat_AsDouble(values[16]); if (unlikely((__pyx_v_nu == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_p = __pyx_PyFloat_AsDouble(values[17]); if (unlikely((__pyx_v_p == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_shrinking = __Pyx_PyInt_AsInt(values[18]); if (unlikely((__pyx_v_shrinking == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_probability = __Pyx_PyInt_AsInt(values[19]); if (unlikely((__pyx_v_probability == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_nSV = ((PyArrayObject *)values[20]); + __pyx_v_probA = ((PyArrayObject *)values[21]); + __pyx_v_probB = ((PyArrayObject *)values[22]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 25, 25, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("libsvm_sparse_predict_proba", 1, 23, 23, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.svm.libsvm_sparse.libsvm_sparse_predict_proba", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_data), __pyx_ptype_5numpy_ndarray, 1, "T_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_indices), __pyx_ptype_5numpy_ndarray, 1, "T_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_indptr), __pyx_ptype_5numpy_ndarray, 1, "T_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 274; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_data), __pyx_ptype_5numpy_ndarray, 1, "SV_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_indices), __pyx_ptype_5numpy_ndarray, 1, "SV_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_indptr), __pyx_ptype_5numpy_ndarray, 1, "SV_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sv_coef), __pyx_ptype_5numpy_ndarray, 1, "sv_coef", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_intercept), __pyx_ptype_5numpy_ndarray, 1, "intercept", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weight_label), __pyx_ptype_5numpy_ndarray, 1, "weight_label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_weight), __pyx_ptype_5numpy_ndarray, 1, "weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nSV), __pyx_ptype_5numpy_ndarray, 1, "nSV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_label), __pyx_ptype_5numpy_ndarray, 1, "label", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probA), __pyx_ptype_5numpy_ndarray, 1, "probA", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probB), __pyx_ptype_5numpy_ndarray, 1, "probB", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_proba(__pyx_self, __pyx_v_T_data, __pyx_v_T_indices, __pyx_v_T_indptr, __pyx_v_SV_data, __pyx_v_SV_indices, __pyx_v_SV_indptr, __pyx_v_sv_coef, __pyx_v_intercept, __pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_eps, __pyx_v_C, __pyx_v_weight_label, __pyx_v_weight, __pyx_v_nu, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_nSV, __pyx_v_label, __pyx_v_probA, __pyx_v_probB); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_data), __pyx_ptype_5numpy_ndarray, 1, "T_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_indices), __pyx_ptype_5numpy_ndarray, 1, "T_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T_indptr), __pyx_ptype_5numpy_ndarray, 1, "T_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_data), __pyx_ptype_5numpy_ndarray, 1, "SV_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 292; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_indices), __pyx_ptype_5numpy_ndarray, 1, "SV_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 293; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_SV_indptr), __pyx_ptype_5numpy_ndarray, 1, "SV_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sv_coef), __pyx_ptype_5numpy_ndarray, 1, "sv_coef", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 295; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_intercept), __pyx_ptype_5numpy_ndarray, 1, "intercept", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_class_weight), __pyx_ptype_5numpy_ndarray, 1, "class_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_nSV), __pyx_ptype_5numpy_ndarray, 1, "nSV", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probA), __pyx_ptype_5numpy_ndarray, 1, "probA", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 303; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_probB), __pyx_ptype_5numpy_ndarray, 1, "probB", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 304; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_proba(__pyx_self, __pyx_v_T_data, __pyx_v_T_indices, __pyx_v_T_indptr, __pyx_v_SV_data, __pyx_v_SV_indices, __pyx_v_SV_indptr, __pyx_v_sv_coef, __pyx_v_intercept, __pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_eps, __pyx_v_C, __pyx_v_class_weight, __pyx_v_nu, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability, __pyx_v_nSV, __pyx_v_probA, __pyx_v_probB); goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -3523,7 +3809,7 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_5libsvm_sparse_predict_p return __pyx_r; } -/* "sklearn/svm/libsvm_sparse.pyx":271 +/* "sklearn/svm/libsvm_sparse.pyx":288 * * * def libsvm_sparse_predict_proba( # <<<<<<<<<<<<<< @@ -3531,11 +3817,13 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_5libsvm_sparse_predict_p * np.ndarray[np.int32_t, ndim=1, mode='c'] T_indices, */ -static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_proba(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T_data, PyArrayObject *__pyx_v_T_indices, PyArrayObject *__pyx_v_T_indptr, PyArrayObject *__pyx_v_SV_data, PyArrayObject *__pyx_v_SV_indices, PyArrayObject *__pyx_v_SV_indptr, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_weight_label, PyArrayObject *__pyx_v_weight, double __pyx_v_nu, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_label, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB) { +static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_proba(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T_data, PyArrayObject *__pyx_v_T_indices, PyArrayObject *__pyx_v_T_indptr, PyArrayObject *__pyx_v_SV_data, PyArrayObject *__pyx_v_SV_indices, PyArrayObject *__pyx_v_SV_indptr, PyArrayObject *__pyx_v_sv_coef, PyArrayObject *__pyx_v_intercept, int __pyx_v_svm_type, int __pyx_v_kernel_type, int __pyx_v_degree, double __pyx_v_gamma, double __pyx_v_coef0, double __pyx_v_eps, double __pyx_v_C, PyArrayObject *__pyx_v_class_weight, double __pyx_v_nu, double __pyx_v_p, int __pyx_v_shrinking, int __pyx_v_probability, PyArrayObject *__pyx_v_nSV, PyArrayObject *__pyx_v_probA, PyArrayObject *__pyx_v_probB) { PyArrayObject *__pyx_v_dec_values = 0; struct svm_parameter *__pyx_v_param; struct svm_csr_model *__pyx_v_model; + PyArrayObject *__pyx_v_class_weight_label = 0; npy_intp __pyx_v_n_class; + int __pyx_v_rv; __Pyx_LocalBuf_ND __pyx_pybuffernd_SV_data; __Pyx_Buffer __pyx_pybuffer_SV_data; __Pyx_LocalBuf_ND __pyx_pybuffernd_SV_indices; @@ -3548,12 +3836,14 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_p __Pyx_Buffer __pyx_pybuffer_T_indices; __Pyx_LocalBuf_ND __pyx_pybuffernd_T_indptr; __Pyx_Buffer __pyx_pybuffer_T_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_class_weight; + __Pyx_Buffer __pyx_pybuffer_class_weight; + __Pyx_LocalBuf_ND __pyx_pybuffernd_class_weight_label; + __Pyx_Buffer __pyx_pybuffer_class_weight_label; __Pyx_LocalBuf_ND __pyx_pybuffernd_dec_values; __Pyx_Buffer __pyx_pybuffer_dec_values; __Pyx_LocalBuf_ND __pyx_pybuffernd_intercept; __Pyx_Buffer __pyx_pybuffer_intercept; - __Pyx_LocalBuf_ND __pyx_pybuffernd_label; - __Pyx_Buffer __pyx_pybuffer_label; __Pyx_LocalBuf_ND __pyx_pybuffernd_nSV; __Pyx_Buffer __pyx_pybuffer_nSV; __Pyx_LocalBuf_ND __pyx_pybuffernd_probA; @@ -3562,10 +3852,6 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_p __Pyx_Buffer __pyx_pybuffer_probB; __Pyx_LocalBuf_ND __pyx_pybuffernd_sv_coef; __Pyx_Buffer __pyx_pybuffer_sv_coef; - __Pyx_LocalBuf_ND __pyx_pybuffernd_weight; - __Pyx_Buffer __pyx_pybuffer_weight; - __Pyx_LocalBuf_ND __pyx_pybuffernd_weight_label; - __Pyx_Buffer __pyx_pybuffer_weight_label; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -3574,11 +3860,12 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_p PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; + PyArrayObject *__pyx_t_7 = NULL; + int __pyx_t_8; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; - int __pyx_t_11; + PyObject *__pyx_t_11 = NULL; + int __pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; @@ -3587,6 +3874,10 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_p __pyx_pybuffer_dec_values.refcount = 0; __pyx_pybuffernd_dec_values.data = NULL; __pyx_pybuffernd_dec_values.rcbuffer = &__pyx_pybuffer_dec_values; + __pyx_pybuffer_class_weight_label.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight_label.refcount = 0; + __pyx_pybuffernd_class_weight_label.data = NULL; + __pyx_pybuffernd_class_weight_label.rcbuffer = &__pyx_pybuffer_class_weight_label; __pyx_pybuffer_T_data.pybuffer.buf = NULL; __pyx_pybuffer_T_data.refcount = 0; __pyx_pybuffernd_T_data.data = NULL; @@ -3619,22 +3910,14 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_p __pyx_pybuffer_intercept.refcount = 0; __pyx_pybuffernd_intercept.data = NULL; __pyx_pybuffernd_intercept.rcbuffer = &__pyx_pybuffer_intercept; - __pyx_pybuffer_weight_label.pybuffer.buf = NULL; - __pyx_pybuffer_weight_label.refcount = 0; - __pyx_pybuffernd_weight_label.data = NULL; - __pyx_pybuffernd_weight_label.rcbuffer = &__pyx_pybuffer_weight_label; - __pyx_pybuffer_weight.pybuffer.buf = NULL; - __pyx_pybuffer_weight.refcount = 0; - __pyx_pybuffernd_weight.data = NULL; - __pyx_pybuffernd_weight.rcbuffer = &__pyx_pybuffer_weight; + __pyx_pybuffer_class_weight.pybuffer.buf = NULL; + __pyx_pybuffer_class_weight.refcount = 0; + __pyx_pybuffernd_class_weight.data = NULL; + __pyx_pybuffernd_class_weight.rcbuffer = &__pyx_pybuffer_class_weight; __pyx_pybuffer_nSV.pybuffer.buf = NULL; __pyx_pybuffer_nSV.refcount = 0; __pyx_pybuffernd_nSV.data = NULL; __pyx_pybuffernd_nSV.rcbuffer = &__pyx_pybuffer_nSV; - __pyx_pybuffer_label.pybuffer.buf = NULL; - __pyx_pybuffer_label.refcount = 0; - __pyx_pybuffernd_label.data = NULL; - __pyx_pybuffernd_label.rcbuffer = &__pyx_pybuffer_label; __pyx_pybuffer_probA.pybuffer.buf = NULL; __pyx_pybuffer_probA.refcount = 0; __pyx_pybuffernd_probA.data = NULL; @@ -3645,195 +3928,270 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_p __pyx_pybuffernd_probB.rcbuffer = &__pyx_pybuffer_probB; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_data, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_data, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_T_data.diminfo[0].strides = __pyx_pybuffernd_T_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_T_data.diminfo[0].shape = __pyx_pybuffernd_T_data.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_indices, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_indices, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_T_indices.diminfo[0].strides = __pyx_pybuffernd_T_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_T_indices.diminfo[0].shape = __pyx_pybuffernd_T_indices.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_indptr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_T_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_T_indptr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_T_indptr.diminfo[0].strides = __pyx_pybuffernd_T_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_T_indptr.diminfo[0].shape = __pyx_pybuffernd_T_indptr.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_data, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_data, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_SV_data.diminfo[0].strides = __pyx_pybuffernd_SV_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_SV_data.diminfo[0].shape = __pyx_pybuffernd_SV_data.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_indices, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_indices, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_SV_indices.diminfo[0].strides = __pyx_pybuffernd_SV_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_SV_indices.diminfo[0].shape = __pyx_pybuffernd_SV_indices.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_indptr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SV_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_SV_indptr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_SV_indptr.diminfo[0].strides = __pyx_pybuffernd_SV_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_SV_indptr.diminfo[0].shape = __pyx_pybuffernd_SV_indptr.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_v_sv_coef, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer, (PyObject*)__pyx_v_sv_coef, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_sv_coef.diminfo[0].strides = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sv_coef.diminfo[0].shape = __pyx_pybuffernd_sv_coef.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_v_intercept, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer, (PyObject*)__pyx_v_intercept, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_intercept.diminfo[0].strides = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_intercept.diminfo[0].shape = __pyx_pybuffernd_intercept.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_weight_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_class_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_pybuffernd_weight_label.diminfo[0].strides = __pyx_pybuffernd_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weight_label.diminfo[0].shape = __pyx_pybuffernd_weight_label.rcbuffer->pybuffer.shape[0]; + __pyx_pybuffernd_class_weight.diminfo[0].strides = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight.diminfo[0].shape = __pyx_pybuffernd_class_weight.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_weight, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_weight.diminfo[0].strides = __pyx_pybuffernd_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_weight.diminfo[0].shape = __pyx_pybuffernd_weight.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer, (PyObject*)__pyx_v_nSV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer, (PyObject*)__pyx_v_nSV, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_nSV.diminfo[0].strides = __pyx_pybuffernd_nSV.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_nSV.diminfo[0].shape = __pyx_pybuffernd_nSV.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_label.rcbuffer->pybuffer, (PyObject*)__pyx_v_label, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_pybuffernd_label.diminfo[0].strides = __pyx_pybuffernd_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_label.diminfo[0].shape = __pyx_pybuffernd_label.rcbuffer->pybuffer.shape[0]; + __pyx_pybuffernd_probA.diminfo[0].strides = __pyx_pybuffernd_probA.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probA.diminfo[0].shape = __pyx_pybuffernd_probA.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probA.rcbuffer->pybuffer, (PyObject*)__pyx_v_probA, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_pybuffernd_probA.diminfo[0].strides = __pyx_pybuffernd_probA.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probA.diminfo[0].shape = __pyx_pybuffernd_probA.rcbuffer->pybuffer.shape[0]; + __pyx_pybuffernd_probB.diminfo[0].strides = __pyx_pybuffernd_probB.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probB.diminfo[0].shape = __pyx_pybuffernd_probB.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/svm/libsvm_sparse.pyx":312 + * cdef svm_csr_model *model + * cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + * class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) # <<<<<<<<<<<<<< + * param = set_parameter(svm_type, kernel_type, degree, gamma, + * coef0, nu, + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__arange); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_class_weight->dimensions[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_probB.rcbuffer->pybuffer, (PyObject*)__pyx_v_probB, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_class_weight_label = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_class_weight_label.diminfo[0].strides = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_class_weight_label.diminfo[0].shape = __pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer.shape[0]; + } } - __pyx_pybuffernd_probB.diminfo[0].strides = __pyx_pybuffernd_probB.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_probB.diminfo[0].shape = __pyx_pybuffernd_probB.rcbuffer->pybuffer.shape[0]; + __pyx_t_6 = 0; + __pyx_v_class_weight_label = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":301 - * C, eps, p, shrinking, - * probability, weight.shape[0], weight_label.data, - * weight.data) # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm_sparse.pyx":318 + * C, eps, p, shrinking, + * probability, class_weight.shape[0], class_weight_label.data, + * class_weight.data, -1, # <<<<<<<<<<<<<< + * -1) # random seed has no effect on predict either * - * model = csr_set_model(param, nSV.shape[0], SV_data.data, */ - __pyx_v_param = set_parameter(__pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, 100., __pyx_v_C, __pyx_v_eps, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_weight->dimensions[0])), __pyx_v_weight_label->data, __pyx_v_weight->data); + __pyx_v_param = set_parameter(__pyx_v_svm_type, __pyx_v_kernel_type, __pyx_v_degree, __pyx_v_gamma, __pyx_v_coef0, __pyx_v_nu, 100., __pyx_v_C, __pyx_v_eps, __pyx_v_p, __pyx_v_shrinking, __pyx_v_probability, ((int)(__pyx_v_class_weight->dimensions[0])), __pyx_v_class_weight_label->data, __pyx_v_class_weight->data, -1, -1); - /* "sklearn/svm/libsvm_sparse.pyx":307 + /* "sklearn/svm/libsvm_sparse.pyx":325 * SV_indptr.shape, SV_indptr.data, * sv_coef.data, intercept.data, - * nSV.data, label.data, probA.data, probB.data) # <<<<<<<<<<<<<< + * nSV.data, probA.data, probB.data) # <<<<<<<<<<<<<< * #TODO: use check_model * cdef np.npy_intp n_class = get_nr(model) */ - __pyx_v_model = csr_set_model(__pyx_v_param, ((int)(__pyx_v_nSV->dimensions[0])), __pyx_v_SV_data->data, __pyx_v_SV_indices->dimensions, __pyx_v_SV_indices->data, __pyx_v_SV_indptr->dimensions, __pyx_v_SV_indptr->data, __pyx_v_sv_coef->data, __pyx_v_intercept->data, __pyx_v_nSV->data, __pyx_v_label->data, __pyx_v_probA->data, __pyx_v_probB->data); + __pyx_v_model = csr_set_model(__pyx_v_param, ((int)(__pyx_v_nSV->dimensions[0])), __pyx_v_SV_data->data, __pyx_v_SV_indices->dimensions, __pyx_v_SV_indices->data, __pyx_v_SV_indptr->dimensions, __pyx_v_SV_indptr->data, __pyx_v_sv_coef->data, __pyx_v_intercept->data, __pyx_v_nSV->data, __pyx_v_probA->data, __pyx_v_probB->data); - /* "sklearn/svm/libsvm_sparse.pyx":309 - * nSV.data, label.data, probA.data, probB.data) + /* "sklearn/svm/libsvm_sparse.pyx":327 + * nSV.data, probA.data, probB.data) * #TODO: use check_model * cdef np.npy_intp n_class = get_nr(model) # <<<<<<<<<<<<<< + * cdef int rv * dec_values = np.empty((T_indptr.shape[0]-1, n_class), dtype=np.float64) - * if csr_copy_predict_proba(T_data.shape, T_data.data, */ __pyx_v_n_class = get_nr(__pyx_v_model); - /* "sklearn/svm/libsvm_sparse.pyx":310 - * #TODO: use check_model + /* "sklearn/svm/libsvm_sparse.pyx":329 * cdef np.npy_intp n_class = get_nr(model) + * cdef int rv * dec_values = np.empty((T_indptr.shape[0]-1, n_class), dtype=np.float64) # <<<<<<<<<<<<<< - * if csr_copy_predict_proba(T_data.shape, T_data.data, - * T_indices.shape, T_indices.data, + * with nogil: + * rv = csr_copy_predict_proba(T_data.shape, T_data.data, */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromLong(((__pyx_v_T_indptr->dimensions[0]) - 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_n_class); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyInt_FromLong(((__pyx_v_T_indptr->dimensions[0]) - 1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_n_class); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_1 = 0; + __pyx_t_5 = 0; __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); - __pyx_t_4 = 0; - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_2)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); + __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); + if (unlikely(__pyx_t_8 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_dec_values, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); } } __pyx_pybuffernd_dec_values.diminfo[0].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_dec_values.diminfo[0].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_dec_values.diminfo[1].strides = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_dec_values.diminfo[1].shape = __pyx_pybuffernd_dec_values.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_7 = 0; + __pyx_v_dec_values = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/svm/libsvm_sparse.pyx":330 + * cdef int rv + * dec_values = np.empty((T_indptr.shape[0]-1, n_class), dtype=np.float64) + * with nogil: # <<<<<<<<<<<<<< + * rv = csr_copy_predict_proba(T_data.shape, T_data.data, + * T_indices.shape, T_indices.data, + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/svm/libsvm_sparse.pyx":334 + * T_indices.shape, T_indices.data, + * T_indptr.shape, T_indptr.data, + * model, dec_values.data) # <<<<<<<<<<<<<< + * if rv < 0: + * raise MemoryError("We've run out of memory") + */ + __pyx_v_rv = csr_copy_predict_proba(__pyx_v_T_data->dimensions, __pyx_v_T_data->data, __pyx_v_T_indices->dimensions, __pyx_v_T_indices->data, __pyx_v_T_indptr->dimensions, __pyx_v_T_indptr->data, __pyx_v_model, __pyx_v_dec_values->data); + } + + /* "sklearn/svm/libsvm_sparse.pyx":330 + * cdef int rv + * dec_values = np.empty((T_indptr.shape[0]-1, n_class), dtype=np.float64) + * with nogil: # <<<<<<<<<<<<<< + * rv = csr_copy_predict_proba(T_data.shape, T_data.data, + * T_indices.shape, T_indices.data, + */ + /*finally:*/ { + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + } } - __pyx_t_6 = 0; - __pyx_v_dec_values = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":314 - * T_indices.shape, T_indices.data, - * T_indptr.shape, T_indptr.data, - * model, dec_values.data) < 0: # <<<<<<<<<<<<<< - * raise MemoryError("We've run out of of memory") + /* "sklearn/svm/libsvm_sparse.pyx":335 + * T_indptr.shape, T_indptr.data, + * model, dec_values.data) + * if rv < 0: # <<<<<<<<<<<<<< + * raise MemoryError("We've run out of memory") * # free model and param */ - __pyx_t_11 = (csr_copy_predict_proba(__pyx_v_T_data->dimensions, __pyx_v_T_data->data, __pyx_v_T_indices->dimensions, __pyx_v_T_indices->data, __pyx_v_T_indptr->dimensions, __pyx_v_T_indptr->data, __pyx_v_model, __pyx_v_dec_values->data) < 0); - if (__pyx_t_11) { + __pyx_t_12 = ((__pyx_v_rv < 0) != 0); + if (__pyx_t_12) { - /* "sklearn/svm/libsvm_sparse.pyx":315 - * T_indptr.shape, T_indptr.data, - * model, dec_values.data) < 0: - * raise MemoryError("We've run out of of memory") # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm_sparse.pyx":336 + * model, dec_values.data) + * if rv < 0: + * raise MemoryError("We've run out of memory") # <<<<<<<<<<<<<< * # free model and param * free_model_SV(model) */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 315; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 315; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; + __pyx_t_4 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 336; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 336; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; } - __pyx_L3:; + __pyx_L6:; - /* "sklearn/svm/libsvm_sparse.pyx":317 - * raise MemoryError("We've run out of of memory") + /* "sklearn/svm/libsvm_sparse.pyx":338 + * raise MemoryError("We've run out of memory") * # free model and param * free_model_SV(model) # <<<<<<<<<<<<<< * free_model(model) @@ -3841,7 +4199,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_p */ free_model_SV(__pyx_v_model); - /* "sklearn/svm/libsvm_sparse.pyx":318 + /* "sklearn/svm/libsvm_sparse.pyx":339 * # free model and param * free_model_SV(model) * free_model(model) # <<<<<<<<<<<<<< @@ -3850,7 +4208,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_p */ free_model(__pyx_v_model); - /* "sklearn/svm/libsvm_sparse.pyx":319 + /* "sklearn/svm/libsvm_sparse.pyx":340 * free_model_SV(model) * free_model(model) * free_param(param) # <<<<<<<<<<<<<< @@ -3859,7 +4217,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_p */ free_param(__pyx_v_param); - /* "sklearn/svm/libsvm_sparse.pyx":320 + /* "sklearn/svm/libsvm_sparse.pyx":341 * free_model(model) * free_param(param) * return dec_values # <<<<<<<<<<<<<< @@ -3887,15 +4245,14 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_p __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_data.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_indices.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.svm.libsvm_sparse.libsvm_sparse_predict_proba", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; @@ -3907,17 +4264,17 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_4libsvm_sparse_predict_p __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_data.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_indices.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_T_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_class_weight_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dec_values.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intercept.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_label.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_nSV.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probA.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_probB.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sv_coef.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_weight_label.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_dec_values); + __Pyx_XDECREF((PyObject *)__pyx_v_class_weight_label); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; @@ -3929,12 +4286,14 @@ static char __pyx_doc_7sklearn_3svm_13libsvm_sparse_6set_verbosity_wrap[] = "\n static PyMethodDef __pyx_mdef_7sklearn_3svm_13libsvm_sparse_7set_verbosity_wrap = {__Pyx_NAMESTR("set_verbosity_wrap"), (PyCFunction)__pyx_pw_7sklearn_3svm_13libsvm_sparse_7set_verbosity_wrap, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_3svm_13libsvm_sparse_6set_verbosity_wrap)}; static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_7set_verbosity_wrap(PyObject *__pyx_self, PyObject *__pyx_arg_verbosity) { int __pyx_v_verbosity; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("set_verbosity_wrap (wrapper)", 0); - __pyx_self = __pyx_self; assert(__pyx_arg_verbosity); { - __pyx_v_verbosity = __Pyx_PyInt_AsInt(__pyx_arg_verbosity); if (unlikely((__pyx_v_verbosity == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_verbosity = __Pyx_PyInt_AsInt(__pyx_arg_verbosity); if (unlikely((__pyx_v_verbosity == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; @@ -3947,7 +4306,7 @@ static PyObject *__pyx_pw_7sklearn_3svm_13libsvm_sparse_7set_verbosity_wrap(PyOb return __pyx_r; } -/* "sklearn/svm/libsvm_sparse.pyx":324 +/* "sklearn/svm/libsvm_sparse.pyx":345 * * * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< @@ -3960,7 +4319,7 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_6set_verbosity_wrap(CYTH __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("set_verbosity_wrap", 0); - /* "sklearn/svm/libsvm_sparse.pyx":328 + /* "sklearn/svm/libsvm_sparse.pyx":349 * Control verbosity of libsvm library * """ * set_verbosity(verbosity) # <<<<<<<<<<<<<< @@ -3974,8 +4333,8 @@ static PyObject *__pyx_pf_7sklearn_3svm_13libsvm_sparse_6set_verbosity_wrap(CYTH } /* Python wrapper */ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); @@ -3984,7 +4343,7 @@ static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_bu return __pyx_r; } -/* "numpy.pxd":193 +/* "numpy.pxd":194 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< @@ -4023,14 +4382,14 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":199 + /* "numpy.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ - __pyx_t_1 = (__pyx_v_info == NULL); + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; @@ -4038,7 +4397,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } __pyx_L3:; - /* "numpy.pxd":202 + /* "numpy.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -4047,7 +4406,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":203 + /* "numpy.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -4056,7 +4415,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":205 + /* "numpy.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< @@ -4065,17 +4424,17 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":207 + /* "numpy.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":208 + /* "numpy.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -4087,7 +4446,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /*else*/ { - /* "numpy.pxd":210 + /* "numpy.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -4098,87 +4457,87 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } __pyx_L4:; - /* "numpy.pxd":212 + /* "numpy.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_1) { - /* "numpy.pxd":213 + /* "numpy.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS)); + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { - /* "numpy.pxd":214 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_13), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_13), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; - /* "numpy.pxd":216 + /* "numpy.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_3) { - /* "numpy.pxd":217 + /* "numpy.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS)); + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { - /* "numpy.pxd":218 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; - /* "numpy.pxd":220 + /* "numpy.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< @@ -4187,7 +4546,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":221 + /* "numpy.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -4196,16 +4555,17 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":222 + /* "numpy.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ - if (__pyx_v_copy_shape) { + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { - /* "numpy.pxd":225 + /* "numpy.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -4214,7 +4574,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":226 + /* "numpy.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -4223,7 +4583,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":227 + /* "numpy.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< @@ -4234,7 +4594,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "numpy.pxd":228 + /* "numpy.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< @@ -4243,7 +4603,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":229 + /* "numpy.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< @@ -4256,7 +4616,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /*else*/ { - /* "numpy.pxd":231 + /* "numpy.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< @@ -4265,7 +4625,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":232 + /* "numpy.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< @@ -4276,7 +4636,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } __pyx_L7:; - /* "numpy.pxd":233 + /* "numpy.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -4285,7 +4645,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":234 + /* "numpy.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< @@ -4294,16 +4654,16 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":235 + /* "numpy.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - /* "numpy.pxd":238 + /* "numpy.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -4312,17 +4672,19 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_f = NULL; - /* "numpy.pxd":239 + /* "numpy.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)__pyx_v_self->descr)); - __pyx_v_descr = __pyx_v_self->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":243 + /* "numpy.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -4331,23 +4693,23 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":245 + /* "numpy.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; } if (__pyx_t_1) { - /* "numpy.pxd":247 + /* "numpy.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -4363,7 +4725,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /*else*/ { - /* "numpy.pxd":250 + /* "numpy.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< @@ -4378,50 +4740,51 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } __pyx_L10:; - /* "numpy.pxd":252 + /* "numpy.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { - /* "numpy.pxd":253 + /* "numpy.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; - /* "numpy.pxd":254 + /* "numpy.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; + __pyx_t_2 = (__pyx_v_little_endian != 0); } else { __pyx_t_2 = __pyx_t_1; } if (!__pyx_t_2) { - /* "numpy.pxd":255 + /* "numpy.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_7 = __pyx_t_3; } else { __pyx_t_7 = __pyx_t_1; @@ -4432,271 +4795,246 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } if (__pyx_t_1) { - /* "numpy.pxd":256 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_17), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_17), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L12; } __pyx_L12:; - /* "numpy.pxd":257 - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "numpy.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { + case NPY_BYTE: __pyx_v_f = __pyx_k__b; - goto __pyx_L13; - } + break; - /* "numpy.pxd":258 + /* "numpy.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { + case NPY_UBYTE: __pyx_v_f = __pyx_k__B; - goto __pyx_L13; - } + break; - /* "numpy.pxd":259 + /* "numpy.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { + case NPY_SHORT: __pyx_v_f = __pyx_k__h; - goto __pyx_L13; - } + break; - /* "numpy.pxd":260 + /* "numpy.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { + case NPY_USHORT: __pyx_v_f = __pyx_k__H; - goto __pyx_L13; - } + break; - /* "numpy.pxd":261 + /* "numpy.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { + case NPY_INT: __pyx_v_f = __pyx_k__i; - goto __pyx_L13; - } + break; - /* "numpy.pxd":262 + /* "numpy.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { + case NPY_UINT: __pyx_v_f = __pyx_k__I; - goto __pyx_L13; - } + break; - /* "numpy.pxd":263 + /* "numpy.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { + case NPY_LONG: __pyx_v_f = __pyx_k__l; - goto __pyx_L13; - } + break; - /* "numpy.pxd":264 + /* "numpy.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { + case NPY_ULONG: __pyx_v_f = __pyx_k__L; - goto __pyx_L13; - } + break; - /* "numpy.pxd":265 + /* "numpy.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { + case NPY_LONGLONG: __pyx_v_f = __pyx_k__q; - goto __pyx_L13; - } + break; - /* "numpy.pxd":266 + /* "numpy.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { + case NPY_ULONGLONG: __pyx_v_f = __pyx_k__Q; - goto __pyx_L13; - } + break; - /* "numpy.pxd":267 + /* "numpy.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { + case NPY_FLOAT: __pyx_v_f = __pyx_k__f; - goto __pyx_L13; - } + break; - /* "numpy.pxd":268 + /* "numpy.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { + case NPY_DOUBLE: __pyx_v_f = __pyx_k__d; - goto __pyx_L13; - } + break; - /* "numpy.pxd":269 + /* "numpy.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { + case NPY_LONGDOUBLE: __pyx_v_f = __pyx_k__g; - goto __pyx_L13; - } + break; - /* "numpy.pxd":270 + /* "numpy.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { + case NPY_CFLOAT: __pyx_v_f = __pyx_k__Zf; - goto __pyx_L13; - } + break; - /* "numpy.pxd":271 + /* "numpy.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { + case NPY_CDOUBLE: __pyx_v_f = __pyx_k__Zd; - goto __pyx_L13; - } + break; - /* "numpy.pxd":272 + /* "numpy.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { + case NPY_CLONGDOUBLE: __pyx_v_f = __pyx_k__Zg; - goto __pyx_L13; - } + break; - /* "numpy.pxd":273 + /* "numpy.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { + case NPY_OBJECT: __pyx_v_f = __pyx_k__O; - goto __pyx_L13; - } - /*else*/ { + break; + default: - /* "numpy.pxd":275 + /* "numpy.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_18), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_18), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_8)); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L13:; - /* "numpy.pxd":276 + /* "numpy.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -4705,7 +5043,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":277 + /* "numpy.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -4718,51 +5056,51 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /*else*/ { - /* "numpy.pxd":279 + /* "numpy.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":280 + /* "numpy.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":281 + /* "numpy.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":284 + /* "numpy.pxd":285 * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string + * f[0] = c'\0' # Terminate format string * */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; - /* "numpy.pxd":285 + /* "numpy.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } __pyx_L11:; @@ -4790,16 +5128,16 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /* Python wrapper */ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":287 - * f[0] = 0 # Terminate format string +/* "numpy.pxd":288 + * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): @@ -4811,17 +5149,17 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s int __pyx_t_1; __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":288 + /* "numpy.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { - /* "numpy.pxd":289 + /* "numpy.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -4833,17 +5171,17 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s } __pyx_L3:; - /* "numpy.pxd":290 + /* "numpy.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":291 + /* "numpy.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -4858,7 +5196,7 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":767 +/* "numpy.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -4875,7 +5213,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":768 + /* "numpy.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -4883,7 +5221,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -4901,7 +5239,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "numpy.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -4918,7 +5256,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":771 + /* "numpy.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -4926,7 +5264,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -4944,7 +5282,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "numpy.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -4961,7 +5299,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":774 + /* "numpy.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -4969,7 +5307,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -4987,7 +5325,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "numpy.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -5004,7 +5342,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":777 + /* "numpy.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -5012,7 +5350,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -5030,7 +5368,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "numpy.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -5047,7 +5385,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":780 + /* "numpy.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -5055,7 +5393,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -5073,7 +5411,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":782 +/* "numpy.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -5096,18 +5434,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; + PyObject *(*__pyx_t_6)(PyObject *); int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; + int __pyx_t_10; + long __pyx_t_11; + char *__pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":789 + /* "numpy.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -5116,7 +5455,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":790 + /* "numpy.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -5125,7 +5464,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":793 + /* "numpy.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< @@ -5133,31 +5472,36 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * child, new_offset = fields */ if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif __Pyx_XDECREF(__pyx_v_childname); __pyx_v_childname = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":794 + /* "numpy.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); __pyx_v_fields = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":795 + /* "numpy.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< @@ -5166,20 +5510,51 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); - } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_child)); __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; @@ -5187,99 +5562,98 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_v_new_offset = __pyx_t_4; __pyx_t_4 = 0; - /* "numpy.pxd":797 + /* "numpy.pxd":798 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":798 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_20), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_20), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; } - __pyx_L5:; + __pyx_L7:; - /* "numpy.pxd":800 + /* "numpy.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_7) { + __pyx_t_8 = (__pyx_v_little_endian != 0); } else { - __pyx_t_7 = __pyx_t_6; + __pyx_t_8 = __pyx_t_7; } - if (!__pyx_t_7) { + if (!__pyx_t_8) { - /* "numpy.pxd":801 + /* "numpy.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + __pyx_t_9 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_10 = __pyx_t_9; } else { - __pyx_t_9 = __pyx_t_6; + __pyx_t_10 = __pyx_t_7; } - __pyx_t_6 = __pyx_t_9; + __pyx_t_7 = __pyx_t_10; } else { - __pyx_t_6 = __pyx_t_7; + __pyx_t_7 = __pyx_t_8; } - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":802 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_21), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_21), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; } - __pyx_L6:; + __pyx_L8:; - /* "numpy.pxd":812 + /* "numpy.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -5287,16 +5661,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!__pyx_t_6) break; + if (!__pyx_t_7) break; - /* "numpy.pxd":813 + /* "numpy.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -5305,7 +5678,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":814 + /* "numpy.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -5314,430 +5687,413 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":815 + /* "numpy.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); } - /* "numpy.pxd":817 + /* "numpy.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); - /* "numpy.pxd":819 + /* "numpy.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); - if (__pyx_t_6) { + __pyx_t_7 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_7) { - /* "numpy.pxd":820 + /* "numpy.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 820; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XDECREF(__pyx_v_t); __pyx_v_t = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":821 + /* "numpy.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); - if (__pyx_t_6) { + __pyx_t_7 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_7) { - /* "numpy.pxd":822 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_23), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_23), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; } - __pyx_L10:; + __pyx_L12:; - /* "numpy.pxd":825 + /* "numpy.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 98; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":826 + /* "numpy.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 66; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":827 + /* "numpy.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 104; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":828 + /* "numpy.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 72; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":829 + /* "numpy.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 105; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":830 + /* "numpy.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 73; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":831 + /* "numpy.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 108; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":832 + /* "numpy.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 76; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":833 + /* "numpy.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 113; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":834 + /* "numpy.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 81; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":835 + /* "numpy.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 102; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":836 + /* "numpy.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 100; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":837 + /* "numpy.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 103; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":838 + /* "numpy.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":839 + /* "numpy.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":840 + /* "numpy.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":841 + /* "numpy.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 79; - goto __pyx_L11; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":843 + /* "numpy.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_18), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_18), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L11:; + __pyx_L13:; - /* "numpy.pxd":844 + /* "numpy.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -5745,25 +6101,25 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":848 + /* "numpy.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 848; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_12; } - __pyx_L9:; + __pyx_L11:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":849 + /* "numpy.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -5792,7 +6148,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":964 +/* "numpy.pxd":965 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -5804,9 +6160,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; + int __pyx_t_2; __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":966 + /* "numpy.pxd":967 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -5814,9 +6171,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "numpy.pxd":967 + /* "numpy.pxd":968 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -5828,7 +6186,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":969 + /* "numpy.pxd":970 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -5837,7 +6195,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":970 + /* "numpy.pxd":971 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -5848,7 +6206,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":971 + /* "numpy.pxd":972 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -5857,7 +6215,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":972 + /* "numpy.pxd":973 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -5869,7 +6227,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":974 +/* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -5883,17 +6241,17 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":975 + /* "numpy.pxd":976 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { - /* "numpy.pxd":976 + /* "numpy.pxd":977 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -5908,7 +6266,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py } /*else*/ { - /* "numpy.pxd":978 + /* "numpy.pxd":979 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -5933,7 +6291,11 @@ static PyMethodDef __pyx_methods[] = { #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else PyModuleDef_HEAD_INIT, + #endif __Pyx_NAMESTR("libsvm_sparse"), 0, /* m_doc */ -1, /* m_size */ @@ -5961,6 +6323,7 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_33, __pyx_k_33, sizeof(__pyx_k_33), 0, 0, 1, 1}, {&__pyx_kp_s_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 0, 1, 0}, {&__pyx_n_s__C, __pyx_k__C, sizeof(__pyx_k__C), 0, 0, 1, 1}, + {&__pyx_n_s__ConvergenceWarning, __pyx_k__ConvergenceWarning, sizeof(__pyx_k__ConvergenceWarning), 0, 0, 1, 1}, {&__pyx_n_s__MemoryError, __pyx_k__MemoryError, sizeof(__pyx_k__MemoryError), 0, 0, 1, 1}, {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s__SV_data, __pyx_k__SV_data, sizeof(__pyx_k__SV_data), 0, 0, 1, 1}, @@ -5972,9 +6335,15 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s__T_indptr, __pyx_k__T_indptr, sizeof(__pyx_k__T_indptr), 0, 0, 1, 1}, {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, {&__pyx_n_s__Y, __pyx_k__Y, sizeof(__pyx_k__Y), 0, 0, 1, 1}, + {&__pyx_n_s____import__, __pyx_k____import__, sizeof(__pyx_k____import__), 0, 0, 1, 1}, {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_getbuffer, __pyx_k____pyx_getbuffer, sizeof(__pyx_k____pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_releasebuffer, __pyx_k____pyx_releasebuffer, sizeof(__pyx_k____pyx_releasebuffer), 0, 0, 1, 1}, {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, + {&__pyx_n_s__arange, __pyx_k__arange, sizeof(__pyx_k__arange), 0, 0, 1, 1}, {&__pyx_n_s__cache_size, __pyx_k__cache_size, sizeof(__pyx_k__cache_size), 0, 0, 1, 1}, + {&__pyx_n_s__class_weight, __pyx_k__class_weight, sizeof(__pyx_k__class_weight), 0, 0, 1, 1}, + {&__pyx_n_s__class_weight_label, __pyx_k__class_weight_label, sizeof(__pyx_k__class_weight_label), 0, 0, 1, 1}, {&__pyx_n_s__coef0, __pyx_k__coef0, sizeof(__pyx_k__coef0), 0, 0, 1, 1}, {&__pyx_n_s__csr_matrix, __pyx_k__csr_matrix, sizeof(__pyx_k__csr_matrix), 0, 0, 1, 1}, {&__pyx_n_s__dec_values, __pyx_k__dec_values, sizeof(__pyx_k__dec_values), 0, 0, 1, 1}, @@ -5983,6 +6352,7 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, {&__pyx_n_s__eps, __pyx_k__eps, sizeof(__pyx_k__eps), 0, 0, 1, 1}, {&__pyx_n_s__error_msg, __pyx_k__error_msg, sizeof(__pyx_k__error_msg), 0, 0, 1, 1}, + {&__pyx_n_s__fit_status, __pyx_k__fit_status, sizeof(__pyx_k__fit_status), 0, 0, 1, 1}, {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, {&__pyx_n_s__gamma, __pyx_k__gamma, sizeof(__pyx_k__gamma), 0, 0, 1, 1}, {&__pyx_n_s__indices, __pyx_k__indices, sizeof(__pyx_k__indices), 0, 0, 1, 1}, @@ -5990,8 +6360,8 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s__int32, __pyx_k__int32, sizeof(__pyx_k__int32), 0, 0, 1, 1}, {&__pyx_n_s__intercept, __pyx_k__intercept, sizeof(__pyx_k__intercept), 0, 0, 1, 1}, {&__pyx_n_s__kernel_type, __pyx_k__kernel_type, sizeof(__pyx_k__kernel_type), 0, 0, 1, 1}, - {&__pyx_n_s__label, __pyx_k__label, sizeof(__pyx_k__label), 0, 0, 1, 1}, {&__pyx_n_s__libsvm_sparse_train, __pyx_k__libsvm_sparse_train, sizeof(__pyx_k__libsvm_sparse_train), 0, 0, 1, 1}, + {&__pyx_n_s__max_iter, __pyx_k__max_iter, sizeof(__pyx_k__max_iter), 0, 0, 1, 1}, {&__pyx_n_s__model, __pyx_k__model, sizeof(__pyx_k__model), 0, 0, 1, 1}, {&__pyx_n_s__nSV, __pyx_k__nSV, sizeof(__pyx_k__nSV), 0, 0, 1, 1}, {&__pyx_n_s__n_class, __pyx_k__n_class, sizeof(__pyx_k__n_class), 0, 0, 1, 1}, @@ -6008,27 +6378,30 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s__probB, __pyx_k__probB, sizeof(__pyx_k__probB), 0, 0, 1, 1}, {&__pyx_n_s__probability, __pyx_k__probability, sizeof(__pyx_k__probability), 0, 0, 1, 1}, {&__pyx_n_s__problem, __pyx_k__problem, sizeof(__pyx_k__problem), 0, 0, 1, 1}, + {&__pyx_n_s__random_seed, __pyx_k__random_seed, sizeof(__pyx_k__random_seed), 0, 0, 1, 1}, {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, + {&__pyx_n_s__rv, __pyx_k__rv, sizeof(__pyx_k__rv), 0, 0, 1, 1}, {&__pyx_n_s__sample_weight, __pyx_k__sample_weight, sizeof(__pyx_k__sample_weight), 0, 0, 1, 1}, {&__pyx_n_s__scipy, __pyx_k__scipy, sizeof(__pyx_k__scipy), 0, 0, 1, 1}, {&__pyx_n_s__set_verbosity_wrap, __pyx_k__set_verbosity_wrap, sizeof(__pyx_k__set_verbosity_wrap), 0, 0, 1, 1}, {&__pyx_n_s__shrinking, __pyx_k__shrinking, sizeof(__pyx_k__shrinking), 0, 0, 1, 1}, {&__pyx_n_s__sparse, __pyx_k__sparse, sizeof(__pyx_k__sparse), 0, 0, 1, 1}, + {&__pyx_n_s__support, __pyx_k__support, sizeof(__pyx_k__support), 0, 0, 1, 1}, {&__pyx_n_s__support_vectors_, __pyx_k__support_vectors_, sizeof(__pyx_k__support_vectors_), 0, 0, 1, 1}, {&__pyx_n_s__sv_coef, __pyx_k__sv_coef, sizeof(__pyx_k__sv_coef), 0, 0, 1, 1}, {&__pyx_n_s__sv_coef_data, __pyx_k__sv_coef_data, sizeof(__pyx_k__sv_coef_data), 0, 0, 1, 1}, {&__pyx_n_s__svm_type, __pyx_k__svm_type, sizeof(__pyx_k__svm_type), 0, 0, 1, 1}, + {&__pyx_n_s__utils, __pyx_k__utils, sizeof(__pyx_k__utils), 0, 0, 1, 1}, {&__pyx_n_s__values, __pyx_k__values, sizeof(__pyx_k__values), 0, 0, 1, 1}, {&__pyx_n_s__verbosity, __pyx_k__verbosity, sizeof(__pyx_k__verbosity), 0, 0, 1, 1}, - {&__pyx_n_s__weight, __pyx_k__weight, sizeof(__pyx_k__weight), 0, 0, 1, 1}, - {&__pyx_n_s__weight_label, __pyx_k__weight_label, sizeof(__pyx_k__weight_label), 0, 0, 1, 1}, + {&__pyx_n_s__warnings, __pyx_k__warnings, sizeof(__pyx_k__warnings), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_MemoryError = __Pyx_GetName(__pyx_b, __pyx_n_s__MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s__MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -6038,523 +6411,196 @@ static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "sklearn/svm/libsvm_sparse.pyx":124 + /* "sklearn/svm/libsvm_sparse.pyx":136 * # check parameters * if (param == NULL or problem == NULL): - * raise MemoryError("Seems we've run out of of memory") # <<<<<<<<<<<<<< + * raise MemoryError("Seems we've run out of memory") # <<<<<<<<<<<<<< * error_msg = svm_csr_check_parameter(problem, param); * if error_msg: */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_4 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_3)); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_4); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_3)); - PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_s_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_3)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); - /* "sklearn/svm/libsvm_sparse.pyx":184 + /* "sklearn/svm/libsvm_sparse.pyx":197 * copy_probB(probB.data, model, probB.shape) * else: * probA = np.empty(1, dtype=np.float64) # <<<<<<<<<<<<<< * probB = np.empty(0, dtype=np.float64) * copy_probA(probA.data, model, probA.shape) */ - __pyx_k_tuple_5 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_5 = PyTuple_Pack(1, __pyx_int_1); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_5); - __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_k_tuple_5, 0, __pyx_int_1); - __Pyx_GIVEREF(__pyx_int_1); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); - /* "sklearn/svm/libsvm_sparse.pyx":185 + /* "sklearn/svm/libsvm_sparse.pyx":198 * else: * probA = np.empty(1, dtype=np.float64) * probB = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * copy_probA(probA.data, model, probA.shape) * else: */ - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_6 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_6); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); - /* "sklearn/svm/libsvm_sparse.pyx":188 + /* "sklearn/svm/libsvm_sparse.pyx":201 * copy_probA(probA.data, model, probA.shape) * else: * probA = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * probB = np.empty(0, dtype=np.float64) * */ - __pyx_k_tuple_7 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 188; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_7 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_7); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_7, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); - /* "sklearn/svm/libsvm_sparse.pyx":189 + /* "sklearn/svm/libsvm_sparse.pyx":202 * else: * probA = np.empty(0, dtype=np.float64) * probB = np.empty(0, dtype=np.float64) # <<<<<<<<<<<<<< * * svm_csr_free_and_destroy_model (&model) */ - __pyx_k_tuple_8 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_8 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_8); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_k_tuple_8, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); - /* "sklearn/svm/libsvm_sparse.pyx":261 - * T_indptr.shape, T_indptr.data, - * model, dec_values.data) < 0: - * raise MemoryError("We've run out of of memory") # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm_sparse.pyx":278 + * model, dec_values.data) + * if rv < 0: + * raise MemoryError("We've run out of memory") # <<<<<<<<<<<<<< * # free model and param * free_model_SV(model) */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_10 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_9)); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_10); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_9)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_s_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_9)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); - /* "sklearn/svm/libsvm_sparse.pyx":315 - * T_indptr.shape, T_indptr.data, - * model, dec_values.data) < 0: - * raise MemoryError("We've run out of of memory") # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm_sparse.pyx":336 + * model, dec_values.data) + * if rv < 0: + * raise MemoryError("We've run out of memory") # <<<<<<<<<<<<<< * # free model and param * free_model_SV(model) */ - __pyx_k_tuple_11 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 315; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_11 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_9)); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 336; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_11); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_9)); - PyTuple_SET_ITEM(__pyx_k_tuple_11, 0, ((PyObject *)__pyx_kp_s_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_9)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); - /* "numpy.pxd":214 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_13 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_13 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_12)); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_13); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_12)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 0, ((PyObject *)__pyx_kp_u_12)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_12)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); - /* "numpy.pxd":218 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_15 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_15 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_14)); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_15); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_14)); - PyTuple_SET_ITEM(__pyx_k_tuple_15, 0, ((PyObject *)__pyx_kp_u_14)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_14)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); - /* "numpy.pxd":256 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_17 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_17)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_17 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_16)); if (unlikely(!__pyx_k_tuple_17)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_17); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_16)); - PyTuple_SET_ITEM(__pyx_k_tuple_17, 0, ((PyObject *)__pyx_kp_u_16)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_16)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_17)); - /* "numpy.pxd":798 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_20 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_20)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_20 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_19)); if (unlikely(!__pyx_k_tuple_20)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_20); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_19)); - PyTuple_SET_ITEM(__pyx_k_tuple_20, 0, ((PyObject *)__pyx_kp_u_19)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_19)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_20)); - /* "numpy.pxd":802 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_21 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_21)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_21 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_16)); if (unlikely(!__pyx_k_tuple_21)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_21); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_16)); - PyTuple_SET_ITEM(__pyx_k_tuple_21, 0, ((PyObject *)__pyx_kp_u_16)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_16)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_21)); - /* "numpy.pxd":822 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_23 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_23)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_23 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_22)); if (unlikely(!__pyx_k_tuple_23)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_23); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_22)); - PyTuple_SET_ITEM(__pyx_k_tuple_23, 0, ((PyObject *)__pyx_kp_u_22)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_22)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_23)); - /* "sklearn/svm/libsvm_sparse.pyx":59 + /* "sklearn/svm/libsvm_sparse.pyx":67 * * * def libsvm_sparse_train ( int n_features, # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] values, * np.ndarray[np.int32_t, ndim=1, mode='c'] indices, */ - __pyx_k_tuple_24 = PyTuple_New(37); if (unlikely(!__pyx_k_tuple_24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_24 = PyTuple_Pack(40, ((PyObject *)__pyx_n_s__n_features), ((PyObject *)__pyx_n_s__values), ((PyObject *)__pyx_n_s__indices), ((PyObject *)__pyx_n_s__indptr), ((PyObject *)__pyx_n_s__Y), ((PyObject *)__pyx_n_s__svm_type), ((PyObject *)__pyx_n_s__kernel_type), ((PyObject *)__pyx_n_s__degree), ((PyObject *)__pyx_n_s__gamma), ((PyObject *)__pyx_n_s__coef0), ((PyObject *)__pyx_n_s__eps), ((PyObject *)__pyx_n_s__C), ((PyObject *)__pyx_n_s__class_weight), ((PyObject *)__pyx_n_s__sample_weight), ((PyObject *)__pyx_n_s__nu), ((PyObject *)__pyx_n_s__cache_size), ((PyObject *)__pyx_n_s__p), ((PyObject *)__pyx_n_s__shrinking), ((PyObject *)__pyx_n_s__probability), ((PyObject *)__pyx_n_s__max_iter), ((PyObject *)__pyx_n_s__random_seed), ((PyObject *)__pyx_n_s__param), ((PyObject *)__pyx_n_s__problem), ((PyObject *)__pyx_n_s__model), ((PyObject *)__pyx_n_s__error_msg), ((PyObject *)__pyx_n_s__class_weight_label), ((PyObject *)__pyx_n_s__fit_status), ((PyObject *)__pyx_n_s__SV_len), ((PyObject *)__pyx_n_s__n_class), ((PyObject *)__pyx_n_s__sv_coef_data), ((PyObject *)__pyx_n_s__support), ((PyObject *)__pyx_n_s__intercept), ((PyObject *)__pyx_n_s__nonzero_SV), ((PyObject *)__pyx_n_s__SV_data), ((PyObject *)__pyx_n_s__SV_indices), ((PyObject *)__pyx_n_s__SV_indptr), ((PyObject *)__pyx_n_s__support_vectors_), ((PyObject *)__pyx_n_s__n_class_SV), ((PyObject *)__pyx_n_s__probA), ((PyObject *)__pyx_n_s__probB)); if (unlikely(!__pyx_k_tuple_24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_24); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_features)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 0, ((PyObject *)__pyx_n_s__n_features)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_features)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__values)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 1, ((PyObject *)__pyx_n_s__values)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__values)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__indices)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 2, ((PyObject *)__pyx_n_s__indices)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__indices)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__indptr)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 3, ((PyObject *)__pyx_n_s__indptr)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__indptr)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__Y)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 4, ((PyObject *)__pyx_n_s__Y)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__Y)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__svm_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 5, ((PyObject *)__pyx_n_s__svm_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__svm_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 6, ((PyObject *)__pyx_n_s__kernel_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__degree)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 7, ((PyObject *)__pyx_n_s__degree)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__degree)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__gamma)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 8, ((PyObject *)__pyx_n_s__gamma)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gamma)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__coef0)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 9, ((PyObject *)__pyx_n_s__coef0)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__coef0)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__eps)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 10, ((PyObject *)__pyx_n_s__eps)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__eps)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__C)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 11, ((PyObject *)__pyx_n_s__C)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__C)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__weight_label)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 12, ((PyObject *)__pyx_n_s__weight_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__weight_label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 13, ((PyObject *)__pyx_n_s__weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sample_weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 14, ((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sample_weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nu)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 15, ((PyObject *)__pyx_n_s__nu)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nu)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__cache_size)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 16, ((PyObject *)__pyx_n_s__cache_size)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__cache_size)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__p)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 17, ((PyObject *)__pyx_n_s__p)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__p)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__shrinking)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 18, ((PyObject *)__pyx_n_s__shrinking)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__shrinking)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probability)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 19, ((PyObject *)__pyx_n_s__probability)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probability)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__param)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 20, ((PyObject *)__pyx_n_s__param)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__param)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__problem)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 21, ((PyObject *)__pyx_n_s__problem)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__problem)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__model)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 22, ((PyObject *)__pyx_n_s__model)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__model)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__error_msg)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 23, ((PyObject *)__pyx_n_s__error_msg)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__error_msg)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_len)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 24, ((PyObject *)__pyx_n_s__SV_len)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_len)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_class)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 25, ((PyObject *)__pyx_n_s__n_class)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_class)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sv_coef_data)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 26, ((PyObject *)__pyx_n_s__sv_coef_data)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sv_coef_data)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__intercept)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 27, ((PyObject *)__pyx_n_s__intercept)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__intercept)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nonzero_SV)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 28, ((PyObject *)__pyx_n_s__nonzero_SV)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nonzero_SV)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_data)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 29, ((PyObject *)__pyx_n_s__SV_data)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_data)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_indices)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 30, ((PyObject *)__pyx_n_s__SV_indices)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_indices)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_indptr)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 31, ((PyObject *)__pyx_n_s__SV_indptr)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_indptr)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__support_vectors_)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 32, ((PyObject *)__pyx_n_s__support_vectors_)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__support_vectors_)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_class_SV)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 33, ((PyObject *)__pyx_n_s__n_class_SV)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_class_SV)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__label)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 34, ((PyObject *)__pyx_n_s__label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probA)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 35, ((PyObject *)__pyx_n_s__probA)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probA)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probB)); - PyTuple_SET_ITEM(__pyx_k_tuple_24, 36, ((PyObject *)__pyx_n_s__probB)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probB)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_24)); - __pyx_k_codeobj_25 = (PyObject*)__Pyx_PyCode_New(20, 0, 37, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_24, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_26, __pyx_n_s__libsvm_sparse_train, 59, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_codeobj_25 = (PyObject*)__Pyx_PyCode_New(21, 0, 40, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_24, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_26, __pyx_n_s__libsvm_sparse_train, 67, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/svm/libsvm_sparse.pyx":199 + /* "sklearn/svm/libsvm_sparse.pyx":212 * * * def libsvm_sparse_predict (np.ndarray[np.float64_t, ndim=1, mode='c'] T_data, # <<<<<<<<<<<<<< * np.ndarray[np.int32_t, ndim=1, mode='c'] T_indices, * np.ndarray[np.int32_t, ndim=1, mode='c'] T_indptr, */ - __pyx_k_tuple_28 = PyTuple_New(28); if (unlikely(!__pyx_k_tuple_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_28 = PyTuple_Pack(28, ((PyObject *)__pyx_n_s__T_data), ((PyObject *)__pyx_n_s__T_indices), ((PyObject *)__pyx_n_s__T_indptr), ((PyObject *)__pyx_n_s__SV_data), ((PyObject *)__pyx_n_s__SV_indices), ((PyObject *)__pyx_n_s__SV_indptr), ((PyObject *)__pyx_n_s__sv_coef), ((PyObject *)__pyx_n_s__intercept), ((PyObject *)__pyx_n_s__svm_type), ((PyObject *)__pyx_n_s__kernel_type), ((PyObject *)__pyx_n_s__degree), ((PyObject *)__pyx_n_s__gamma), ((PyObject *)__pyx_n_s__coef0), ((PyObject *)__pyx_n_s__eps), ((PyObject *)__pyx_n_s__C), ((PyObject *)__pyx_n_s__class_weight), ((PyObject *)__pyx_n_s__nu), ((PyObject *)__pyx_n_s__p), ((PyObject *)__pyx_n_s__shrinking), ((PyObject *)__pyx_n_s__probability), ((PyObject *)__pyx_n_s__nSV), ((PyObject *)__pyx_n_s__probA), ((PyObject *)__pyx_n_s__probB), ((PyObject *)__pyx_n_s__dec_values), ((PyObject *)__pyx_n_s__param), ((PyObject *)__pyx_n_s__model), ((PyObject *)__pyx_n_s__class_weight_label), ((PyObject *)__pyx_n_s__rv)); if (unlikely(!__pyx_k_tuple_28)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_28); - __Pyx_INCREF(((PyObject *)__pyx_n_s__T_data)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 0, ((PyObject *)__pyx_n_s__T_data)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__T_data)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__T_indices)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 1, ((PyObject *)__pyx_n_s__T_indices)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__T_indices)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__T_indptr)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 2, ((PyObject *)__pyx_n_s__T_indptr)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__T_indptr)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_data)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 3, ((PyObject *)__pyx_n_s__SV_data)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_data)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_indices)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 4, ((PyObject *)__pyx_n_s__SV_indices)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_indices)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_indptr)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 5, ((PyObject *)__pyx_n_s__SV_indptr)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_indptr)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sv_coef)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 6, ((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__intercept)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 7, ((PyObject *)__pyx_n_s__intercept)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__intercept)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__svm_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 8, ((PyObject *)__pyx_n_s__svm_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__svm_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 9, ((PyObject *)__pyx_n_s__kernel_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__degree)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 10, ((PyObject *)__pyx_n_s__degree)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__degree)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__gamma)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 11, ((PyObject *)__pyx_n_s__gamma)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gamma)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__coef0)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 12, ((PyObject *)__pyx_n_s__coef0)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__coef0)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__eps)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 13, ((PyObject *)__pyx_n_s__eps)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__eps)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__C)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 14, ((PyObject *)__pyx_n_s__C)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__C)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__weight_label)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 15, ((PyObject *)__pyx_n_s__weight_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__weight_label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 16, ((PyObject *)__pyx_n_s__weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nu)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 17, ((PyObject *)__pyx_n_s__nu)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nu)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__p)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 18, ((PyObject *)__pyx_n_s__p)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__p)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__shrinking)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 19, ((PyObject *)__pyx_n_s__shrinking)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__shrinking)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probability)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 20, ((PyObject *)__pyx_n_s__probability)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probability)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nSV)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 21, ((PyObject *)__pyx_n_s__nSV)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nSV)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__label)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 22, ((PyObject *)__pyx_n_s__label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probA)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 23, ((PyObject *)__pyx_n_s__probA)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probA)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probB)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 24, ((PyObject *)__pyx_n_s__probB)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probB)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__dec_values)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 25, ((PyObject *)__pyx_n_s__dec_values)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__dec_values)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__param)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 26, ((PyObject *)__pyx_n_s__param)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__param)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__model)); - PyTuple_SET_ITEM(__pyx_k_tuple_28, 27, ((PyObject *)__pyx_n_s__model)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__model)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_28)); - __pyx_k_codeobj_29 = (PyObject*)__Pyx_PyCode_New(25, 0, 28, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_28, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_26, __pyx_n_s_30, 199, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_codeobj_29 = (PyObject*)__Pyx_PyCode_New(23, 0, 28, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_28, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_26, __pyx_n_s_30, 212, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/svm/libsvm_sparse.pyx":271 + /* "sklearn/svm/libsvm_sparse.pyx":288 * * * def libsvm_sparse_predict_proba( # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] T_data, * np.ndarray[np.int32_t, ndim=1, mode='c'] T_indices, */ - __pyx_k_tuple_31 = PyTuple_New(29); if (unlikely(!__pyx_k_tuple_31)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_31 = PyTuple_Pack(29, ((PyObject *)__pyx_n_s__T_data), ((PyObject *)__pyx_n_s__T_indices), ((PyObject *)__pyx_n_s__T_indptr), ((PyObject *)__pyx_n_s__SV_data), ((PyObject *)__pyx_n_s__SV_indices), ((PyObject *)__pyx_n_s__SV_indptr), ((PyObject *)__pyx_n_s__sv_coef), ((PyObject *)__pyx_n_s__intercept), ((PyObject *)__pyx_n_s__svm_type), ((PyObject *)__pyx_n_s__kernel_type), ((PyObject *)__pyx_n_s__degree), ((PyObject *)__pyx_n_s__gamma), ((PyObject *)__pyx_n_s__coef0), ((PyObject *)__pyx_n_s__eps), ((PyObject *)__pyx_n_s__C), ((PyObject *)__pyx_n_s__class_weight), ((PyObject *)__pyx_n_s__nu), ((PyObject *)__pyx_n_s__p), ((PyObject *)__pyx_n_s__shrinking), ((PyObject *)__pyx_n_s__probability), ((PyObject *)__pyx_n_s__nSV), ((PyObject *)__pyx_n_s__probA), ((PyObject *)__pyx_n_s__probB), ((PyObject *)__pyx_n_s__dec_values), ((PyObject *)__pyx_n_s__param), ((PyObject *)__pyx_n_s__model), ((PyObject *)__pyx_n_s__class_weight_label), ((PyObject *)__pyx_n_s__n_class), ((PyObject *)__pyx_n_s__rv)); if (unlikely(!__pyx_k_tuple_31)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_31); - __Pyx_INCREF(((PyObject *)__pyx_n_s__T_data)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 0, ((PyObject *)__pyx_n_s__T_data)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__T_data)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__T_indices)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 1, ((PyObject *)__pyx_n_s__T_indices)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__T_indices)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__T_indptr)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 2, ((PyObject *)__pyx_n_s__T_indptr)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__T_indptr)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_data)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 3, ((PyObject *)__pyx_n_s__SV_data)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_data)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_indices)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 4, ((PyObject *)__pyx_n_s__SV_indices)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_indices)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__SV_indptr)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 5, ((PyObject *)__pyx_n_s__SV_indptr)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__SV_indptr)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sv_coef)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 6, ((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sv_coef)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__intercept)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 7, ((PyObject *)__pyx_n_s__intercept)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__intercept)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__svm_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 8, ((PyObject *)__pyx_n_s__svm_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__svm_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__kernel_type)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 9, ((PyObject *)__pyx_n_s__kernel_type)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__kernel_type)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__degree)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 10, ((PyObject *)__pyx_n_s__degree)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__degree)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__gamma)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 11, ((PyObject *)__pyx_n_s__gamma)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__gamma)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__coef0)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 12, ((PyObject *)__pyx_n_s__coef0)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__coef0)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__eps)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 13, ((PyObject *)__pyx_n_s__eps)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__eps)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__C)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 14, ((PyObject *)__pyx_n_s__C)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__C)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__weight_label)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 15, ((PyObject *)__pyx_n_s__weight_label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__weight_label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__weight)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 16, ((PyObject *)__pyx_n_s__weight)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__weight)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nu)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 17, ((PyObject *)__pyx_n_s__nu)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nu)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__p)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 18, ((PyObject *)__pyx_n_s__p)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__p)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__shrinking)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 19, ((PyObject *)__pyx_n_s__shrinking)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__shrinking)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probability)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 20, ((PyObject *)__pyx_n_s__probability)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probability)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nSV)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 21, ((PyObject *)__pyx_n_s__nSV)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nSV)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__label)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 22, ((PyObject *)__pyx_n_s__label)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__label)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probA)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 23, ((PyObject *)__pyx_n_s__probA)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probA)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__probB)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 24, ((PyObject *)__pyx_n_s__probB)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__probB)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__dec_values)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 25, ((PyObject *)__pyx_n_s__dec_values)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__dec_values)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__param)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 26, ((PyObject *)__pyx_n_s__param)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__param)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__model)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 27, ((PyObject *)__pyx_n_s__model)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__model)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_class)); - PyTuple_SET_ITEM(__pyx_k_tuple_31, 28, ((PyObject *)__pyx_n_s__n_class)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_class)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_31)); - __pyx_k_codeobj_32 = (PyObject*)__Pyx_PyCode_New(25, 0, 29, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_31, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_26, __pyx_n_s_33, 271, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_32)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_codeobj_32 = (PyObject*)__Pyx_PyCode_New(23, 0, 29, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_31, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_26, __pyx_n_s_33, 288, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_32)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/svm/libsvm_sparse.pyx":324 + /* "sklearn/svm/libsvm_sparse.pyx":345 * * * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< * """ * Control verbosity of libsvm library */ - __pyx_k_tuple_34 = PyTuple_New(2); if (unlikely(!__pyx_k_tuple_34)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_34 = PyTuple_Pack(2, ((PyObject *)__pyx_n_s__verbosity), ((PyObject *)__pyx_n_s__verbosity)); if (unlikely(!__pyx_k_tuple_34)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_34); - __Pyx_INCREF(((PyObject *)__pyx_n_s__verbosity)); - PyTuple_SET_ITEM(__pyx_k_tuple_34, 0, ((PyObject *)__pyx_n_s__verbosity)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__verbosity)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__verbosity)); - PyTuple_SET_ITEM(__pyx_k_tuple_34, 1, ((PyObject *)__pyx_n_s__verbosity)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__verbosity)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_34)); - __pyx_k_codeobj_35 = (PyObject*)__Pyx_PyCode_New(1, 0, 2, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_34, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_26, __pyx_n_s__set_verbosity_wrap, 324, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_35)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_codeobj_35 = (PyObject*)__Pyx_PyCode_New(1, 0, 2, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_34, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_26, __pyx_n_s__set_verbosity_wrap, 345, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_35)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -6563,10 +6609,10 @@ static int __Pyx_InitCachedConstants(void) { } static int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; return 0; __pyx_L1_error:; return -1; @@ -6582,6 +6628,9 @@ PyMODINIT_FUNC PyInit_libsvm_sparse(void) { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -6593,17 +6642,17 @@ PyMODINIT_FUNC PyInit_libsvm_sparse(void) } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_libsvm_sparse(void)", 0); - if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #ifdef __Pyx_CyFunction_USED - if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -6614,57 +6663,86 @@ PyMODINIT_FUNC PyInit_libsvm_sparse(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("libsvm_sparse"), __pyx_methods, 0, 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("libsvm_sparse"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.svm.libsvm_sparse")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.svm.libsvm_sparse", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ - if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif if (__pyx_module_is_main_sklearn__svm__libsvm_sparse) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } /*--- Builtin init code ---*/ - if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ - if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ + /* "sklearn/svm/libsvm_sparse.pyx":1 + * import warnings # <<<<<<<<<<<<<< + * import numpy as np + * cimport numpy as np + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__warnings), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__warnings, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /* "sklearn/svm/libsvm_sparse.pyx":2 - * + * import warnings * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np * from scipy import sparse */ __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "sklearn/svm/libsvm_sparse.pyx":4 * import numpy as np * cimport numpy as np * from scipy import sparse # <<<<<<<<<<<<<< + * from ..utils import ConvergenceWarning * - * ################################################################################ */ __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); @@ -6674,76 +6752,101 @@ PyMODINIT_FUNC PyInit_libsvm_sparse(void) __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s__scipy), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__sparse); - if (__pyx_t_1 == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__sparse); - if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s__sparse); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__sparse, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s__sparse, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":59 + /* "sklearn/svm/libsvm_sparse.pyx":5 + * cimport numpy as np + * from scipy import sparse + * from ..utils import ConvergenceWarning # <<<<<<<<<<<<<< + * + * cdef extern from *: + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_n_s__ConvergenceWarning)); + PyList_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_n_s__ConvergenceWarning)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__ConvergenceWarning)); + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__utils), ((PyObject *)__pyx_t_2), 2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s__ConvergenceWarning); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__ConvergenceWarning, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/svm/libsvm_sparse.pyx":64 + * + * + * np.import_array() # <<<<<<<<<<<<<< + * + * + */ + import_array(); + + /* "sklearn/svm/libsvm_sparse.pyx":67 * * * def libsvm_sparse_train ( int n_features, # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] values, * np.ndarray[np.int32_t, ndim=1, mode='c'] indices, */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_13libsvm_sparse_1libsvm_sparse_train, NULL, __pyx_n_s_27); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__libsvm_sparse_train, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_13libsvm_sparse_1libsvm_sparse_train, NULL, __pyx_n_s_27); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__libsvm_sparse_train, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":199 + /* "sklearn/svm/libsvm_sparse.pyx":212 * * * def libsvm_sparse_predict (np.ndarray[np.float64_t, ndim=1, mode='c'] T_data, # <<<<<<<<<<<<<< * np.ndarray[np.int32_t, ndim=1, mode='c'] T_indices, * np.ndarray[np.int32_t, ndim=1, mode='c'] T_indptr, */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_13libsvm_sparse_3libsvm_sparse_predict, NULL, __pyx_n_s_27); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_30, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_13libsvm_sparse_3libsvm_sparse_predict, NULL, __pyx_n_s_27); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_30, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":271 + /* "sklearn/svm/libsvm_sparse.pyx":288 * * * def libsvm_sparse_predict_proba( # <<<<<<<<<<<<<< * np.ndarray[np.float64_t, ndim=1, mode='c'] T_data, * np.ndarray[np.int32_t, ndim=1, mode='c'] T_indices, */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_13libsvm_sparse_5libsvm_sparse_predict_proba, NULL, __pyx_n_s_27); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_33, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_13libsvm_sparse_5libsvm_sparse_predict_proba, NULL, __pyx_n_s_27); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_33, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":324 + /* "sklearn/svm/libsvm_sparse.pyx":345 * * * def set_verbosity_wrap(int verbosity): # <<<<<<<<<<<<<< * """ * Control verbosity of libsvm library */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_13libsvm_sparse_7set_verbosity_wrap, NULL, __pyx_n_s_27); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__set_verbosity_wrap, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_3svm_13libsvm_sparse_7set_verbosity_wrap, NULL, __pyx_n_s_27); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__set_verbosity_wrap, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/svm/libsvm_sparse.pyx":2 - * - * import numpy as np # <<<<<<<<<<<<<< + /* "sklearn/svm/libsvm_sparse.pyx":1 + * import warnings # <<<<<<<<<<<<<< + * import numpy as np * cimport numpy as np - * from scipy import sparse */ - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - /* "numpy.pxd":974 + /* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -6786,17 +6889,15 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { } #endif /* CYTHON_REFNANNY */ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%s' is not defined", PyString_AS_STRING(name)); +#endif } return result; } @@ -6821,7 +6922,7 @@ static void __Pyx_RaiseArgtupleInvalid( more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", + "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } @@ -6835,7 +6936,7 @@ static void __Pyx_RaiseDoubleKeywordsError( "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); + PyString_AsString(kw_name)); #endif } @@ -6856,48 +6957,72 @@ static int __Pyx_ParseOptionalKeywords( while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { values[name-argnames] = value; - } else { - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; } } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; } } return 0; arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); + __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, @@ -6995,7 +7120,8 @@ static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { - case 'b': return "'char'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; @@ -7063,7 +7189,7 @@ typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); @@ -7095,7 +7221,7 @@ typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif -static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); @@ -7115,7 +7241,9 @@ static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, int is_complex) { } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'h': case 'i': + case 'c': + return 'H'; + case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case 'B': case 'H': case 'I': case 'L': case 'Q': @@ -7210,13 +7338,16 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ctx->head->parent_offset = parent_offset; continue; } - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } @@ -7456,7 +7587,7 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate( } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; @@ -7473,6 +7604,23 @@ static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { __Pyx_ReleaseBuffer(info); } +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_Format(PyExc_SystemError, "Missing type object"); @@ -7525,53 +7673,57 @@ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyOb static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) + if (PyClass_Check(type)) { #else - if (!PyType_Check(type)) + if (PyType_Check(type)) { #endif - { - if (value != Py_None) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } #endif } __Pyx_ErrRestore(type, value, tb); @@ -7584,6 +7736,7 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, } #else /* Python 3+ */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -7601,31 +7754,55 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } +#if PY_VERSION_HEX >= 0x03030000 if (cause) { +#else + if (cause && cause != Py_None) { +#endif PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; - } - else if (PyExceptionInstance_Check(cause)) { + } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); @@ -7639,6 +7816,7 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } } bad: + Py_XDECREF(owned_instance); return; } #endif @@ -7650,134 +7828,156 @@ static CYTHON_INLINE long __Pyx_div_long(long a, long b) { return q; } -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", + index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; } else { - __Pyx_RaiseTooManyValuesError(index); + return __Pyx_IterFinish(); + } + return 0; +} + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif } + return value; } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - PyObject *getbuffer_cobj; - #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (getbuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_getbuffer"))) { - getbufferproc func; - - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (getbufferproc) PyCapsule_GetPointer(getbuffer_cobj, "getbuffer(obj, view, flags)"); - #else - func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); - #endif - Py_DECREF(getbuffer_cobj); - if (!func) - goto fail; - - return func(obj, view, flags); - } else { - PyErr_Clear(); + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } } #endif - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - #if PY_VERSION_HEX < 0x02060000 fail: #endif - return -1; } - static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; - PyObject *releasebuffer_cobj; - if (!obj) return; - #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (releasebuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_releasebuffer"))) { - releasebufferproc func; - - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (releasebufferproc) PyCapsule_GetPointer(releasebuffer_cobj, "releasebuffer(obj, view)"); - #else - func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); - #endif - - Py_DECREF(releasebuffer_cobj); - - if (!func) - goto fail; - - func(obj, view); - return; - } else { - PyErr_Clear(); + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } } #endif - goto nofail; - #if PY_VERSION_HEX < 0x02060000 fail: #endif PyErr_WriteUnraisable(obj); - nofail: Py_DECREF(obj); view->obj = NULL; } - #endif /* PY_MAJOR_VERSION < 3 */ - static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s____import__); if (!py_import) goto bad; + #endif if (from_list) list = from_list; else { @@ -7797,13 +7997,17 @@ static void __Pyx_ReleaseBuffer(Py_buffer *view) { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { - /* try package relative import first */ + #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(1); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; @@ -7814,12 +8018,17 @@ static void __Pyx_ReleaseBuffer(Py_buffer *view) { } #endif if (!module) { + #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif } } #else @@ -7831,21 +8040,14 @@ static void __Pyx_ReleaseBuffer(Py_buffer *view) { name, global_dict, empty_dict, list, NULL); #endif bad: - Py_XDECREF(empty_list); + #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } -static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name) { -#if PY_MAJOR_VERSION < 3 - PyErr_Format(PyExc_ImportError, "cannot import name %.230s", - PyString_AsString(name)); -#else - PyErr_Format(PyExc_ImportError, "cannot import name %S", name); -#endif -} - static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t val) { const Py_intptr_t neg_one = (Py_intptr_t)-1, const_zero = (Py_intptr_t)0; const int is_unsigned = const_zero < neg_one; @@ -8301,10 +8503,15 @@ static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { return (int)__Pyx_PyInt_AsLong(x); } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { const unsigned long neg_one = (unsigned long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -8317,6 +8524,16 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); @@ -8324,6 +8541,17 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { } return (unsigned long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (unsigned long)PyLong_AsLong(x); } } else { @@ -8336,10 +8564,15 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -8352,6 +8585,16 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned PY_LONG_LONG"); @@ -8359,6 +8602,17 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje } return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -8371,10 +8625,15 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { const long neg_one = (long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -8387,6 +8646,16 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); @@ -8394,6 +8663,17 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { } return (long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (long)PyLong_AsLong(x); } } else { @@ -8406,10 +8686,15 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -8422,6 +8707,16 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to PY_LONG_LONG"); @@ -8429,6 +8724,17 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { } return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -8441,10 +8747,15 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { const signed long neg_one = (signed long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -8457,6 +8768,16 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed long"); @@ -8464,6 +8785,17 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { } return (signed long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (signed long)PyLong_AsLong(x); } } else { @@ -8476,10 +8808,15 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -8492,6 +8829,16 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed PY_LONG_LONG"); @@ -8499,6 +8846,17 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* } return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (signed PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -8530,6 +8888,23 @@ static int __Pyx_check_binary_version(void) { return 0; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -8539,6 +8914,10 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; @@ -8558,7 +8937,19 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class module_name, class_name); goto bad; } - if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -8568,7 +8959,7 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%s.%s has the wrong size, try recompiling", module_name, class_name); @@ -8582,23 +8973,6 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - py_name = __Pyx_PyIdentifier_FromString(name); - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; -} -#endif - static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { @@ -8791,27 +9165,82 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } - -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (r < 0) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -8827,7 +9256,7 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { @@ -8845,7 +9274,6 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject* x = PyNumber_Index(b); @@ -8854,7 +9282,6 @@ static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) @@ -8868,14 +9295,12 @@ static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); #endif } - static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); + if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); return (size_t)-1; } return (size_t)val; diff --git a/sklearn/svm/libsvm_sparse.pyx b/sklearn/svm/libsvm_sparse.pyx index 173dab0262150..590dbb03808e0 100644 --- a/sklearn/svm/libsvm_sparse.pyx +++ b/sklearn/svm/libsvm_sparse.pyx @@ -1,7 +1,11 @@ - +import warnings import numpy as np cimport numpy as np from scipy import sparse +from ..utils import ConvergenceWarning + +cdef extern from *: + ctypedef char* const_char_p "const char*" ################################################################################ # Includes @@ -12,7 +16,7 @@ cdef extern from "svm.h": cdef struct svm_parameter cdef struct svm_csr_problem char *svm_csr_check_parameter(svm_csr_problem *, svm_parameter *) - svm_csr_model *svm_csr_train(svm_csr_problem *, svm_parameter *) + svm_csr_model *svm_csr_train(svm_csr_problem *, svm_parameter *, int *) nogil void svm_csr_free_and_destroy_model(svm_csr_model** model_ptr_ptr) cdef extern from "libsvm_sparse_helper.c": @@ -23,20 +27,22 @@ cdef extern from "libsvm_sparse_helper.c": char *SV_data, np.npy_intp *SV_indices_dims, char *SV_indices, np.npy_intp *SV_intptr_dims, char *SV_intptr, - char *sv_coef, char *rho, char *nSV, char *label, + char *sv_coef, char *rho, char *nSV, char *probA, char *probB) svm_parameter *set_parameter (int , int , int , double, double , double , double , double , double, - double, int, int, int, char *, char *) + double, int, int, int, char *, char *, int, + int) void copy_sv_coef (char *, svm_csr_model *) + void copy_support (char *, svm_csr_model *) void copy_intercept (char *, svm_csr_model *, np.npy_intp *) int copy_predict (char *, svm_csr_model *, np.npy_intp *, char *) int csr_copy_predict (np.npy_intp *data_size, char *data, np.npy_intp *index_size, char *index, np.npy_intp *intptr_size, char *size, - svm_csr_model *model, char *dec_values) + svm_csr_model *model, char *dec_values) nogil int csr_copy_predict_proba (np.npy_intp *data_size, char *data, np.npy_intp *index_size, char *index, np.npy_intp *intptr_size, char *size, - svm_csr_model *model, char *dec_values) + svm_csr_model *model, char *dec_values) nogil int copy_predict_values(char *, svm_csr_model *, np.npy_intp *, char *, int) int csr_copy_SV (char *values, np.npy_intp *n_indices, @@ -44,7 +50,6 @@ cdef extern from "libsvm_sparse_helper.c": svm_csr_model *model, int n_features) np.npy_intp get_nonzero_SV ( svm_csr_model *) void copy_nSV (char *, svm_csr_model *) - void copy_label (char *, svm_csr_model *) void copy_probA (char *, svm_csr_model *, np.npy_intp *) void copy_probB (char *, svm_csr_model *, np.npy_intp *) np.npy_intp get_l (svm_csr_model *) @@ -56,6 +61,9 @@ cdef extern from "libsvm_sparse_helper.c": void set_verbosity(int) +np.import_array() + + def libsvm_sparse_train ( int n_features, np.ndarray[np.float64_t, ndim=1, mode='c'] values, np.ndarray[np.int32_t, ndim=1, mode='c'] indices, @@ -63,11 +71,11 @@ def libsvm_sparse_train ( int n_features, np.ndarray[np.float64_t, ndim=1, mode='c'] Y, int svm_type, int kernel_type, int degree, double gamma, double coef0, double eps, double C, - np.ndarray[np.int32_t, ndim=1, mode='c'] weight_label, - np.ndarray[np.float64_t, ndim=1, mode='c'] weight, + np.ndarray[np.float64_t, ndim=1, mode='c'] class_weight, np.ndarray[np.float64_t, ndim=1, mode='c'] sample_weight, double nu, double cache_size, double p, int - shrinking, int probability): + shrinking, int probability, int max_iter, + int random_seed): """ Wrap svm_train from libsvm using a scipy.sparse.csr matrix @@ -94,7 +102,7 @@ def libsvm_sparse_train ( int n_features, cdef svm_parameter *param cdef svm_csr_problem *problem cdef svm_csr_model *model - cdef char *error_msg + cdef const_char_p error_msg if len(sample_weight) == 0: sample_weight = np.ones(Y.shape[0], dtype=np.float64) @@ -113,15 +121,19 @@ def libsvm_sparse_train ( int n_features, indptr.shape, indptr.data, Y.data, sample_weight.data, kernel_type) + cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) + # set parameters param = set_parameter(svm_type, kernel_type, degree, gamma, coef0, nu, cache_size, C, eps, p, shrinking, - probability, weight.shape[0], - weight_label.data, weight.data) + probability, class_weight.shape[0], + class_weight_label.data, class_weight.data, max_iter, + random_seed) # check parameters if (param == NULL or problem == NULL): - raise MemoryError("Seems we've run out of of memory") + raise MemoryError("Seems we've run out of memory") error_msg = svm_csr_check_parameter(problem, param); if error_msg: free_problem(problem) @@ -129,7 +141,9 @@ def libsvm_sparse_train ( int n_features, raise ValueError(error_msg) # call svm_train, this does the real work - model = svm_csr_train(problem, param) + cdef int fit_status = 0 + with nogil: + model = svm_csr_train(problem, param, &fit_status) cdef np.npy_intp SV_len = get_l(model) cdef np.npy_intp n_class = get_nr(model) @@ -141,6 +155,10 @@ def libsvm_sparse_train ( int n_features, sv_coef_data = np.empty((n_class-1)*SV_len, dtype=np.float64) copy_sv_coef (sv_coef_data.data, model) + cdef np.ndarray[np.int32_t, ndim=1, mode='c'] support + support = np.empty(SV_len, dtype=np.int32) + copy_support(support.data, model) + # copy model.rho into the intercept # the intercept is just model.rho but with sign changed cdef np.ndarray intercept @@ -168,11 +186,6 @@ def libsvm_sparse_train ( int n_features, n_class_SV = np.empty(n_class, dtype=np.int32) copy_nSV(n_class_SV.data, model) - # # copy label - cdef np.ndarray label - label = np.empty((n_class), dtype=np.int32) - copy_label(label.data, model) - # # copy probabilities cdef np.ndarray probA, probB if probability != 0: @@ -192,8 +205,8 @@ def libsvm_sparse_train ( int n_features, free_problem(problem) free_param(param) - return support_vectors_, sv_coef_data, intercept, label, n_class_SV, probA, probB - + return (support, support_vectors_, sv_coef_data, intercept, n_class_SV, + probA, probB, fit_status) def libsvm_sparse_predict (np.ndarray[np.float64_t, ndim=1, mode='c'] T_data, @@ -207,12 +220,10 @@ def libsvm_sparse_predict (np.ndarray[np.float64_t, ndim=1, mode='c'] T_data, intercept, int svm_type, int kernel_type, int degree, double gamma, double coef0, double eps, double C, - np.ndarray[np.int32_t, ndim=1] weight_label, - np.ndarray[np.float64_t, ndim=1] weight, + np.ndarray[np.float64_t, ndim=1] class_weight, double nu, double p, int shrinking, int probability, np.ndarray[np.int32_t, ndim=1, mode='c'] nSV, - np.ndarray[np.int32_t, ndim=1, mode='c'] label, np.ndarray[np.float64_t, ndim=1, mode='c'] probA, np.ndarray[np.float64_t, ndim=1, mode='c'] probB): """ @@ -240,25 +251,31 @@ def libsvm_sparse_predict (np.ndarray[np.float64_t, ndim=1, mode='c'] T_data, cdef np.ndarray[np.float64_t, ndim=1, mode='c'] dec_values cdef svm_parameter *param cdef svm_csr_model *model + cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) + cdef int rv param = set_parameter(svm_type, kernel_type, degree, gamma, coef0, nu, - 100., # cache size has no effect on predict - C, eps, p, shrinking, - probability, weight.shape[0], weight_label.data, - weight.data) + 100., # cache size has no effect on predict + C, eps, p, shrinking, + probability, class_weight.shape[0], class_weight_label.data, + class_weight.data, -1, + -1) # random seed has no effect on predict either model = csr_set_model(param, nSV.shape[0], SV_data.data, SV_indices.shape, SV_indices.data, SV_indptr.shape, SV_indptr.data, sv_coef.data, intercept.data, - nSV.data, label.data, probA.data, probB.data) + nSV.data, probA.data, probB.data) #TODO: use check_model dec_values = np.empty(T_indptr.shape[0]-1) - if csr_copy_predict(T_data.shape, T_data.data, - T_indices.shape, T_indices.data, - T_indptr.shape, T_indptr.data, - model, dec_values.data) < 0: - raise MemoryError("We've run out of of memory") + with nogil: + rv = csr_copy_predict(T_data.shape, T_data.data, + T_indices.shape, T_indices.data, + T_indptr.shape, T_indptr.data, + model, dec_values.data) + if rv < 0: + raise MemoryError("We've run out of memory") # free model and param free_model_SV(model) free_model(model) @@ -280,11 +297,9 @@ def libsvm_sparse_predict_proba( intercept, int svm_type, int kernel_type, int degree, double gamma, double coef0, double eps, double C, - np.ndarray[np.int32_t, ndim=1] weight_label, - np.ndarray[np.float64_t, ndim=1] weight, + np.ndarray[np.float64_t, ndim=1] class_weight, double nu, double p, int shrinking, int probability, np.ndarray[np.int32_t, ndim=1, mode='c'] nSV, - np.ndarray[np.int32_t, ndim=1, mode='c'] label, np.ndarray[np.float64_t, ndim=1, mode='c'] probA, np.ndarray[np.float64_t, ndim=1, mode='c'] probB): """ @@ -293,26 +308,32 @@ def libsvm_sparse_predict_proba( cdef np.ndarray[np.float64_t, ndim=2, mode='c'] dec_values cdef svm_parameter *param cdef svm_csr_model *model + cdef np.ndarray[np.int32_t, ndim=1, mode='c'] \ + class_weight_label = np.arange(class_weight.shape[0], dtype=np.int32) param = set_parameter(svm_type, kernel_type, degree, gamma, coef0, nu, - 100., # cache size has no effect on predict - C, eps, p, shrinking, - probability, weight.shape[0], weight_label.data, - weight.data) + 100., # cache size has no effect on predict + C, eps, p, shrinking, + probability, class_weight.shape[0], class_weight_label.data, + class_weight.data, -1, + -1) # random seed has no effect on predict either model = csr_set_model(param, nSV.shape[0], SV_data.data, SV_indices.shape, SV_indices.data, SV_indptr.shape, SV_indptr.data, sv_coef.data, intercept.data, - nSV.data, label.data, probA.data, probB.data) + nSV.data, probA.data, probB.data) #TODO: use check_model cdef np.npy_intp n_class = get_nr(model) + cdef int rv dec_values = np.empty((T_indptr.shape[0]-1, n_class), dtype=np.float64) - if csr_copy_predict_proba(T_data.shape, T_data.data, - T_indices.shape, T_indices.data, - T_indptr.shape, T_indptr.data, - model, dec_values.data) < 0: - raise MemoryError("We've run out of of memory") + with nogil: + rv = csr_copy_predict_proba(T_data.shape, T_data.data, + T_indices.shape, T_indices.data, + T_indptr.shape, T_indptr.data, + model, dec_values.data) + if rv < 0: + raise MemoryError("We've run out of memory") # free model and param free_model_SV(model) free_model(model) diff --git a/sklearn/svm/setup.py b/sklearn/svm/setup.py index 14cb74911a0ad..711e868b11eb4 100644 --- a/sklearn/svm/setup.py +++ b/sklearn/svm/setup.py @@ -1,12 +1,12 @@ +import os from os.path import join import numpy -import warnings +from sklearn._build_utils import get_blas_info def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration - from numpy.distutils.system_info import get_info, BlasNotFoundError config = Configuration('svm', parent_package, top_path) @@ -14,11 +14,14 @@ def configuration(parent_package='', top_path=None): # Section LibSVM - # we compile both libsvm and lisvm_sparse + # we compile both libsvm and libsvm_sparse config.add_library('libsvm-skl', sources=[join('src', 'libsvm', 'libsvm_template.cpp')], depends=[join('src', 'libsvm', 'svm.cpp'), join('src', 'libsvm', 'svm.h')], + # Force C++ linking in case gcc is picked up instead + # of g++ under windows with some versions of MinGW + extra_link_args=['-lstdc++'], ) libsvm_sources = ['libsvm.c'] @@ -36,10 +39,9 @@ def configuration(parent_package='', top_path=None): ) ### liblinear module - blas_sources = [join('src', 'blas', 'daxpy.c'), - join('src', 'blas', 'ddot.c'), - join('src', 'blas', 'dnrm2.c'), - join('src', 'blas', 'dscal.c')] + cblas_libs, blas_info = get_blas_info() + if os.name == 'posix': + cblas_libs.append('m') liblinear_sources = ['liblinear.c', join('src', 'liblinear', '*.cpp')] @@ -47,19 +49,14 @@ def configuration(parent_package='', top_path=None): liblinear_depends = [join('src', 'liblinear', '*.h'), join('src', 'liblinear', 'liblinear_helper.c')] - # we try to link agains system-wide blas - blas_info = get_info('blas_opt', 0) - - if not blas_info: - config.add_library('blas', blas_sources) - warnings.warn(BlasNotFoundError.__doc__) - config.add_extension('liblinear', sources=liblinear_sources, - libraries=blas_info.pop('libraries', ['blas']), - include_dirs=['src', + libraries=cblas_libs, + include_dirs=[join('..', 'src', 'cblas'), numpy.get_include(), blas_info.pop('include_dirs', [])], + extra_compile_args=blas_info.pop('extra_compile_args', + []), depends=liblinear_depends, # extra_compile_args=['-O0 -fno-inline'], ** blas_info) @@ -76,8 +73,6 @@ def configuration(parent_package='', top_path=None): join("src", "libsvm", "libsvm_sparse_helper.c")]) - config.add_subpackage('sparse') - return config diff --git a/sklearn/svm/sparse/__init__.py b/sklearn/svm/sparse/__init__.py deleted file mode 100644 index b2450b3a7216e..0000000000000 --- a/sklearn/svm/sparse/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -""" -The :mod:`sklearn.svm.sparse` module includes Support Vector Machine algorithms -for sparse matrices. - -This module should have the same API as :mod:`sklearn.svm`, except -that matrices are expected to be in some sparse format supported by -scipy.sparse. - -.. note:: - - Some fields, like `dual_coef_` are not sparse matrices strictly speaking. - However, they are converted to a sparse matrix for consistency and - efficiency when multiplying to other sparse matrices. -""" - -# see http://scikit-learn.sourceforge.net/modules/svm.html -# Author: Fabian Pedregosa with help from -# the scikit-learn community. -# License: New BSD, (C) INRIA 2010 - -from .classes import SVC, NuSVC, SVR, NuSVR, OneClassSVM, LinearSVC -from .. import libsvm_sparse as libsvm diff --git a/sklearn/svm/sparse/base.py b/sklearn/svm/sparse/base.py deleted file mode 100644 index b8ca8e367cea1..0000000000000 --- a/sklearn/svm/sparse/base.py +++ /dev/null @@ -1,23 +0,0 @@ -import numpy as np -import scipy.sparse -from abc import ABCMeta, abstractmethod - -from ..base import BaseLibSVM - - -class SparseBaseLibSVM(BaseLibSVM): - __metaclass__ = ABCMeta - - @abstractmethod - def __init__(self, impl, kernel, degree, gamma, coef0, - tol, C, nu, epsilon, shrinking, probability, cache_size, - class_weight, verbose): - - super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma, - coef0, tol, C, nu, epsilon, shrinking, probability, cache_size, - True, class_weight, verbose) - - def fit(self, X, y, sample_weight=None): - X = scipy.sparse.csr_matrix(X, dtype=np.float64) - return super(SparseBaseLibSVM, self).fit(X, y, - sample_weight=sample_weight) diff --git a/sklearn/svm/sparse/classes.py b/sklearn/svm/sparse/classes.py deleted file mode 100644 index bd144eb988ad1..0000000000000 --- a/sklearn/svm/sparse/classes.py +++ /dev/null @@ -1,188 +0,0 @@ -from .. import LinearSVC -from ..base import BaseSVC -from ...base import RegressorMixin -from .base import SparseBaseLibSVM -from ...utils import deprecated - - -@deprecated("""to be removed in v0.14; -use sklearn.svm.SVC instead""") -class SVC(SparseBaseLibSVM, BaseSVC): - """SVC for sparse matrices (csr). - - See :class:`sklearn.svm.SVC` for a complete list of parameters - - Notes - ----- - For best results, this accepts a matrix in csr format - (scipy.sparse.csr), but should be able to convert from any array-like - object (including other sparse representations). - - Examples - -------- - >>> import numpy as np - >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) - >>> y = np.array([1, 1, 2, 2]) - >>> from sklearn.svm.sparse import SVC - >>> clf = SVC() - >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE - SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, - gamma=0.0, kernel='rbf', probability=False, shrinking=True, - tol=0.001, verbose=False) - >>> print(clf.predict([[-0.8, -1]])) - [ 1.] - """ - - def __init__(self, C=1.0, kernel='rbf', degree=3, gamma=0.0, - coef0=0.0, shrinking=True, probability=False, - tol=1e-3, cache_size=200, class_weight=None, - verbose=False): - - super(SVC, self).__init__('c_svc', kernel, degree, gamma, coef0, tol, - C, 0., 0., shrinking, probability, - cache_size, class_weight, verbose) - - -@deprecated("""to be removed in v0.14; -use sklearn.svm.NuSVC instead""") -class NuSVC(SparseBaseLibSVM, BaseSVC): - """NuSVC for sparse matrices (csr). - - See :class:`sklearn.svm.NuSVC` for a complete list of parameters - - Notes - ----- - For best results, this accepts a matrix in csr format - (scipy.sparse.csr), but should be able to convert from any array-like - object (including other sparse representations). - - Examples - -------- - >>> import numpy as np - >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) - >>> y = np.array([1, 1, 2, 2]) - >>> from sklearn.svm.sparse import NuSVC - >>> clf = NuSVC() - >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE - NuSVC(cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, - kernel='rbf', nu=0.5, probability=False, shrinking=True, tol=0.001, - verbose=False) - >>> print(clf.predict([[-0.8, -1]])) - [ 1.] - """ - - def __init__(self, nu=0.5, kernel='rbf', degree=3, gamma=0.0, - coef0=0.0, shrinking=True, probability=False, - tol=1e-3, cache_size=200, class_weight=None, - verbose=False): - - super(NuSVC, self).__init__('nu_svc', kernel, degree, gamma, coef0, - tol, 0., nu, 0., shrinking, probability, - cache_size, class_weight, verbose) - - -@deprecated("""to be removed in v0.14; -use sklearn.svm.SVR instead""") -class SVR(SparseBaseLibSVM, RegressorMixin): - """SVR for sparse matrices (csr) - - See :class:`sklearn.svm.SVR` for a complete list of parameters - - Notes - ----- - For best results, this accepts a matrix in csr format - (scipy.sparse.csr), but should be able to convert from any array-like - object (including other sparse representations). - - Examples - -------- - >>> from sklearn.svm.sparse import SVR - >>> import numpy as np - >>> n_samples, n_features = 10, 5 - >>> np.random.seed(0) - >>> y = np.random.randn(n_samples) - >>> X = np.random.randn(n_samples, n_features) - >>> clf = SVR(C=1.0, epsilon=0.2) - >>> clf.fit(X, y) - SVR(C=1.0, cache_size=200, coef0=0.0, degree=3, epsilon=0.2, gamma=0.0, - kernel='rbf', probability=False, shrinking=True, tol=0.001, - verbose=False) - """ - - def __init__(self, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, tol=1e-3, - C=1.0, epsilon=0.1, shrinking=True, probability=False, - cache_size=200, verbose=False): - - super(SVR, self).__init__('epsilon_svr', kernel, degree, gamma, coef0, - tol, C, 0., epsilon, shrinking, probability, - cache_size, None, verbose) - - -@deprecated("""to be removed in v0.14; -use sklearn.svm.NuSVR instead""") -class NuSVR(SparseBaseLibSVM, RegressorMixin): - """NuSVR for sparse matrices (csr) - - See :class:`sklearn.svm.NuSVC` for a complete list of parameters - - Notes - ----- - For best results, this accepts a matrix in csr format - (scipy.sparse.csr), but should be able to convert from any array-like - object (including other sparse representations). - - Examples - -------- - >>> from sklearn.svm.sparse import NuSVR - >>> import numpy as np - >>> n_samples, n_features = 10, 5 - >>> np.random.seed(0) - >>> y = np.random.randn(n_samples) - >>> X = np.random.randn(n_samples, n_features) - >>> clf = NuSVR(nu=0.1, C=1.0) - >>> clf.fit(X, y) - NuSVR(C=1.0, cache_size=200, coef0=0.0, degree=3, epsilon=0.1, gamma=0.0, - kernel='rbf', nu=0.1, probability=False, shrinking=True, tol=0.001, - verbose=False) - """ - - def __init__(self, nu=0.5, C=1.0, kernel='rbf', degree=3, gamma=0.0, - coef0=0.0, shrinking=True, epsilon=0.1, probability=False, - tol=1e-3, cache_size=200, verbose=False): - - super(NuSVR, self).__init__('nu_svr', kernel, degree, gamma, coef0, - tol, C, nu, epsilon, shrinking, probability, cache_size, - None, verbose) - - -@deprecated("""to be removed in v0.14; -use sklearn.svm.OneClassSVM instead""") -class OneClassSVM(SparseBaseLibSVM): - """OneClassSVM for sparse matrices (csr) - - See :class:`sklearn.svm.OneClassSVM` for a complete list of parameters - - Notes - ----- - For best results, this accepts a matrix in csr format - (scipy.sparse.csr), but should be able to convert from any array-like - object (including other sparse representations). - """ - - def __init__(self, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, tol=1e-3, - nu=0.5, shrinking=True, probability=False, cache_size=200, - verbose=False): - - super(OneClassSVM, self).__init__('one_class', kernel, degree, gamma, - coef0, tol, 0.0, nu, 0.0, shrinking, probability, cache_size, - None, verbose) - - def fit(self, X, sample_weight=None): - super(OneClassSVM, self).fit( - X, [], sample_weight=sample_weight) - - -@deprecated("""to be removed in v0.14; -use sklearn.svm.LinearSVC instead""") -class LinearSVC(LinearSVC): - pass diff --git a/sklearn/svm/src/blas/Makefile b/sklearn/svm/src/blas/Makefile deleted file mode 100644 index 2be0186ef7f17..0000000000000 --- a/sklearn/svm/src/blas/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -AR = ar rcv -RANLIB = ranlib - -HEADERS = blas.h blas.h blasp.h -FILES = dnrm2.o daxpy.o ddot.o dscal.o - -CFLAGS = $(OPTFLAGS) -FFLAGS = $(OPTFLAGS) - -blas: $(FILES) $(HEADERS) - $(AR) blas.a $(FILES) - $(RANLIB) blas.a - -clean: - - rm -f *.o - - rm -f *.a - - rm -f *~ - -.c.o: - $(CC) $(CFLAGS) -c $*.c - - diff --git a/sklearn/svm/src/blas/blas.h b/sklearn/svm/src/blas/blas.h deleted file mode 100644 index 558893a043550..0000000000000 --- a/sklearn/svm/src/blas/blas.h +++ /dev/null @@ -1,25 +0,0 @@ -/* blas.h -- C header file for BLAS Ver 1.0 */ -/* Jesse Bennett March 23, 2000 */ - -/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - - - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ - -#ifndef BLAS_INCLUDE -#define BLAS_INCLUDE - -/* Data types specific to BLAS implementation */ -typedef struct { float r, i; } fcomplex; -typedef struct { double r, i; } dcomplex; -typedef int blasbool; - -#include "blasp.h" /* Prototypes for all BLAS functions */ - -#define FALSE 0 -#define TRUE 1 - -/* Macro functions */ -#define MIN(a,b) ((a) <= (b) ? (a) : (b)) -#define MAX(a,b) ((a) >= (b) ? (a) : (b)) - -#endif diff --git a/sklearn/svm/src/blas/blasp.h b/sklearn/svm/src/blas/blasp.h deleted file mode 100644 index 745836db87780..0000000000000 --- a/sklearn/svm/src/blas/blasp.h +++ /dev/null @@ -1,430 +0,0 @@ -/* blasp.h -- C prototypes for BLAS Ver 1.0 */ -/* Jesse Bennett March 23, 2000 */ - -/* Functions listed in alphabetical order */ - -#ifdef F2C_COMPAT - -void cdotc_(fcomplex *dotval, int *n, fcomplex *cx, int *incx, - fcomplex *cy, int *incy); - -void cdotu_(fcomplex *dotval, int *n, fcomplex *cx, int *incx, - fcomplex *cy, int *incy); - -double sasum_(int *n, float *sx, int *incx); - -double scasum_(int *n, fcomplex *cx, int *incx); - -double scnrm2_(int *n, fcomplex *x, int *incx); - -double sdot_(int *n, float *sx, int *incx, float *sy, int *incy); - -double snrm2_(int *n, float *x, int *incx); - -void zdotc_(dcomplex *dotval, int *n, dcomplex *cx, int *incx, - dcomplex *cy, int *incy); - -void zdotu_(dcomplex *dotval, int *n, dcomplex *cx, int *incx, - dcomplex *cy, int *incy); - -#else - -fcomplex cdotc_(int *n, fcomplex *cx, int *incx, fcomplex *cy, int *incy); - -fcomplex cdotu_(int *n, fcomplex *cx, int *incx, fcomplex *cy, int *incy); - -float sasum_(int *n, float *sx, int *incx); - -float scasum_(int *n, fcomplex *cx, int *incx); - -float scnrm2_(int *n, fcomplex *x, int *incx); - -float sdot_(int *n, float *sx, int *incx, float *sy, int *incy); - -float snrm2_(int *n, float *x, int *incx); - -dcomplex zdotc_(int *n, dcomplex *cx, int *incx, dcomplex *cy, int *incy); - -dcomplex zdotu_(int *n, dcomplex *cx, int *incx, dcomplex *cy, int *incy); - -#endif - -/* Remaining functions listed in alphabetical order */ - -int caxpy_(int *n, fcomplex *ca, fcomplex *cx, int *incx, fcomplex *cy, - int *incy); - -int ccopy_(int *n, fcomplex *cx, int *incx, fcomplex *cy, int *incy); - -int cgbmv_(char *trans, int *m, int *n, int *kl, int *ku, - fcomplex *alpha, fcomplex *a, int *lda, fcomplex *x, int *incx, - fcomplex *beta, fcomplex *y, int *incy); - -int cgemm_(char *transa, char *transb, int *m, int *n, int *k, - fcomplex *alpha, fcomplex *a, int *lda, fcomplex *b, int *ldb, - fcomplex *beta, fcomplex *c, int *ldc); - -int cgemv_(char *trans, int *m, int *n, fcomplex *alpha, fcomplex *a, - int *lda, fcomplex *x, int *incx, fcomplex *beta, fcomplex *y, - int *incy); - -int cgerc_(int *m, int *n, fcomplex *alpha, fcomplex *x, int *incx, - fcomplex *y, int *incy, fcomplex *a, int *lda); - -int cgeru_(int *m, int *n, fcomplex *alpha, fcomplex *x, int *incx, - fcomplex *y, int *incy, fcomplex *a, int *lda); - -int chbmv_(char *uplo, int *n, int *k, fcomplex *alpha, fcomplex *a, - int *lda, fcomplex *x, int *incx, fcomplex *beta, fcomplex *y, - int *incy); - -int chemm_(char *side, char *uplo, int *m, int *n, fcomplex *alpha, - fcomplex *a, int *lda, fcomplex *b, int *ldb, fcomplex *beta, - fcomplex *c, int *ldc); - -int chemv_(char *uplo, int *n, fcomplex *alpha, fcomplex *a, int *lda, - fcomplex *x, int *incx, fcomplex *beta, fcomplex *y, int *incy); - -int cher_(char *uplo, int *n, float *alpha, fcomplex *x, int *incx, - fcomplex *a, int *lda); - -int cher2_(char *uplo, int *n, fcomplex *alpha, fcomplex *x, int *incx, - fcomplex *y, int *incy, fcomplex *a, int *lda); - -int cher2k_(char *uplo, char *trans, int *n, int *k, fcomplex *alpha, - fcomplex *a, int *lda, fcomplex *b, int *ldb, float *beta, - fcomplex *c, int *ldc); - -int cherk_(char *uplo, char *trans, int *n, int *k, float *alpha, - fcomplex *a, int *lda, float *beta, fcomplex *c, int *ldc); - -int chpmv_(char *uplo, int *n, fcomplex *alpha, fcomplex *ap, fcomplex *x, - int *incx, fcomplex *beta, fcomplex *y, int *incy); - -int chpr_(char *uplo, int *n, float *alpha, fcomplex *x, int *incx, - fcomplex *ap); - -int chpr2_(char *uplo, int *n, fcomplex *alpha, fcomplex *x, int *incx, - fcomplex *y, int *incy, fcomplex *ap); - -int crotg_(fcomplex *ca, fcomplex *cb, float *c, fcomplex *s); - -int cscal_(int *n, fcomplex *ca, fcomplex *cx, int *incx); - -int csscal_(int *n, float *sa, fcomplex *cx, int *incx); - -int cswap_(int *n, fcomplex *cx, int *incx, fcomplex *cy, int *incy); - -int csymm_(char *side, char *uplo, int *m, int *n, fcomplex *alpha, - fcomplex *a, int *lda, fcomplex *b, int *ldb, fcomplex *beta, - fcomplex *c, int *ldc); - -int csyr2k_(char *uplo, char *trans, int *n, int *k, fcomplex *alpha, - fcomplex *a, int *lda, fcomplex *b, int *ldb, fcomplex *beta, - fcomplex *c, int *ldc); - -int csyrk_(char *uplo, char *trans, int *n, int *k, fcomplex *alpha, - fcomplex *a, int *lda, fcomplex *beta, fcomplex *c, int *ldc); - -int ctbmv_(char *uplo, char *trans, char *diag, int *n, int *k, - fcomplex *a, int *lda, fcomplex *x, int *incx); - -int ctbsv_(char *uplo, char *trans, char *diag, int *n, int *k, - fcomplex *a, int *lda, fcomplex *x, int *incx); - -int ctpmv_(char *uplo, char *trans, char *diag, int *n, fcomplex *ap, - fcomplex *x, int *incx); - -int ctpsv_(char *uplo, char *trans, char *diag, int *n, fcomplex *ap, - fcomplex *x, int *incx); - -int ctrmm_(char *side, char *uplo, char *transa, char *diag, int *m, - int *n, fcomplex *alpha, fcomplex *a, int *lda, fcomplex *b, - int *ldb); - -int ctrmv_(char *uplo, char *trans, char *diag, int *n, fcomplex *a, - int *lda, fcomplex *x, int *incx); - -int ctrsm_(char *side, char *uplo, char *transa, char *diag, int *m, - int *n, fcomplex *alpha, fcomplex *a, int *lda, fcomplex *b, - int *ldb); - -int ctrsv_(char *uplo, char *trans, char *diag, int *n, fcomplex *a, - int *lda, fcomplex *x, int *incx); - -int daxpy_(int *n, double *sa, double *sx, int *incx, double *sy, - int *incy); - -int dcopy_(int *n, double *sx, int *incx, double *sy, int *incy); - -int dgbmv_(char *trans, int *m, int *n, int *kl, int *ku, - double *alpha, double *a, int *lda, double *x, int *incx, - double *beta, double *y, int *incy); - -int dgemm_(char *transa, char *transb, int *m, int *n, int *k, - double *alpha, double *a, int *lda, double *b, int *ldb, - double *beta, double *c, int *ldc); - -int dgemv_(char *trans, int *m, int *n, double *alpha, double *a, - int *lda, double *x, int *incx, double *beta, double *y, - int *incy); - -int dger_(int *m, int *n, double *alpha, double *x, int *incx, - double *y, int *incy, double *a, int *lda); - -int drot_(int *n, double *sx, int *incx, double *sy, int *incy, - double *c, double *s); - -int drotg_(double *sa, double *sb, double *c, double *s); - -int dsbmv_(char *uplo, int *n, int *k, double *alpha, double *a, - int *lda, double *x, int *incx, double *beta, double *y, - int *incy); - -int dscal_(int *n, double *sa, double *sx, int *incx); - -int dspmv_(char *uplo, int *n, double *alpha, double *ap, double *x, - int *incx, double *beta, double *y, int *incy); - -int dspr_(char *uplo, int *n, double *alpha, double *x, int *incx, - double *ap); - -int dspr2_(char *uplo, int *n, double *alpha, double *x, int *incx, - double *y, int *incy, double *ap); - -int dswap_(int *n, double *sx, int *incx, double *sy, int *incy); - -int dsymm_(char *side, char *uplo, int *m, int *n, double *alpha, - double *a, int *lda, double *b, int *ldb, double *beta, - double *c, int *ldc); - -int dsymv_(char *uplo, int *n, double *alpha, double *a, int *lda, - double *x, int *incx, double *beta, double *y, int *incy); - -int dsyr_(char *uplo, int *n, double *alpha, double *x, int *incx, - double *a, int *lda); - -int dsyr2_(char *uplo, int *n, double *alpha, double *x, int *incx, - double *y, int *incy, double *a, int *lda); - -int dsyr2k_(char *uplo, char *trans, int *n, int *k, double *alpha, - double *a, int *lda, double *b, int *ldb, double *beta, - double *c, int *ldc); - -int dsyrk_(char *uplo, char *trans, int *n, int *k, double *alpha, - double *a, int *lda, double *beta, double *c, int *ldc); - -int dtbmv_(char *uplo, char *trans, char *diag, int *n, int *k, - double *a, int *lda, double *x, int *incx); - -int dtbsv_(char *uplo, char *trans, char *diag, int *n, int *k, - double *a, int *lda, double *x, int *incx); - -int dtpmv_(char *uplo, char *trans, char *diag, int *n, double *ap, - double *x, int *incx); - -int dtpsv_(char *uplo, char *trans, char *diag, int *n, double *ap, - double *x, int *incx); - -int dtrmm_(char *side, char *uplo, char *transa, char *diag, int *m, - int *n, double *alpha, double *a, int *lda, double *b, - int *ldb); - -int dtrmv_(char *uplo, char *trans, char *diag, int *n, double *a, - int *lda, double *x, int *incx); - -int dtrsm_(char *side, char *uplo, char *transa, char *diag, int *m, - int *n, double *alpha, double *a, int *lda, double *b, - int *ldb); - -int dtrsv_(char *uplo, char *trans, char *diag, int *n, double *a, - int *lda, double *x, int *incx); - - -int saxpy_(int *n, float *sa, float *sx, int *incx, float *sy, int *incy); - -int scopy_(int *n, float *sx, int *incx, float *sy, int *incy); - -int sgbmv_(char *trans, int *m, int *n, int *kl, int *ku, - float *alpha, float *a, int *lda, float *x, int *incx, - float *beta, float *y, int *incy); - -int sgemm_(char *transa, char *transb, int *m, int *n, int *k, - float *alpha, float *a, int *lda, float *b, int *ldb, - float *beta, float *c, int *ldc); - -int sgemv_(char *trans, int *m, int *n, float *alpha, float *a, - int *lda, float *x, int *incx, float *beta, float *y, - int *incy); - -int sger_(int *m, int *n, float *alpha, float *x, int *incx, - float *y, int *incy, float *a, int *lda); - -int srot_(int *n, float *sx, int *incx, float *sy, int *incy, - float *c, float *s); - -int srotg_(float *sa, float *sb, float *c, float *s); - -int ssbmv_(char *uplo, int *n, int *k, float *alpha, float *a, - int *lda, float *x, int *incx, float *beta, float *y, - int *incy); - -int sscal_(int *n, float *sa, float *sx, int *incx); - -int sspmv_(char *uplo, int *n, float *alpha, float *ap, float *x, - int *incx, float *beta, float *y, int *incy); - -int sspr_(char *uplo, int *n, float *alpha, float *x, int *incx, - float *ap); - -int sspr2_(char *uplo, int *n, float *alpha, float *x, int *incx, - float *y, int *incy, float *ap); - -int sswap_(int *n, float *sx, int *incx, float *sy, int *incy); - -int ssymm_(char *side, char *uplo, int *m, int *n, float *alpha, - float *a, int *lda, float *b, int *ldb, float *beta, - float *c, int *ldc); - -int ssymv_(char *uplo, int *n, float *alpha, float *a, int *lda, - float *x, int *incx, float *beta, float *y, int *incy); - -int ssyr_(char *uplo, int *n, float *alpha, float *x, int *incx, - float *a, int *lda); - -int ssyr2_(char *uplo, int *n, float *alpha, float *x, int *incx, - float *y, int *incy, float *a, int *lda); - -int ssyr2k_(char *uplo, char *trans, int *n, int *k, float *alpha, - float *a, int *lda, float *b, int *ldb, float *beta, - float *c, int *ldc); - -int ssyrk_(char *uplo, char *trans, int *n, int *k, float *alpha, - float *a, int *lda, float *beta, float *c, int *ldc); - -int stbmv_(char *uplo, char *trans, char *diag, int *n, int *k, - float *a, int *lda, float *x, int *incx); - -int stbsv_(char *uplo, char *trans, char *diag, int *n, int *k, - float *a, int *lda, float *x, int *incx); - -int stpmv_(char *uplo, char *trans, char *diag, int *n, float *ap, - float *x, int *incx); - -int stpsv_(char *uplo, char *trans, char *diag, int *n, float *ap, - float *x, int *incx); - -int strmm_(char *side, char *uplo, char *transa, char *diag, int *m, - int *n, float *alpha, float *a, int *lda, float *b, - int *ldb); - -int strmv_(char *uplo, char *trans, char *diag, int *n, float *a, - int *lda, float *x, int *incx); - -int strsm_(char *side, char *uplo, char *transa, char *diag, int *m, - int *n, float *alpha, float *a, int *lda, float *b, - int *ldb); - -int strsv_(char *uplo, char *trans, char *diag, int *n, float *a, - int *lda, float *x, int *incx); - -int zaxpy_(int *n, dcomplex *ca, dcomplex *cx, int *incx, dcomplex *cy, - int *incy); - -int zcopy_(int *n, dcomplex *cx, int *incx, dcomplex *cy, int *incy); - -int zdscal_(int *n, double *sa, dcomplex *cx, int *incx); - -int zgbmv_(char *trans, int *m, int *n, int *kl, int *ku, - dcomplex *alpha, dcomplex *a, int *lda, dcomplex *x, int *incx, - dcomplex *beta, dcomplex *y, int *incy); - -int zgemm_(char *transa, char *transb, int *m, int *n, int *k, - dcomplex *alpha, dcomplex *a, int *lda, dcomplex *b, int *ldb, - dcomplex *beta, dcomplex *c, int *ldc); - -int zgemv_(char *trans, int *m, int *n, dcomplex *alpha, dcomplex *a, - int *lda, dcomplex *x, int *incx, dcomplex *beta, dcomplex *y, - int *incy); - -int zgerc_(int *m, int *n, dcomplex *alpha, dcomplex *x, int *incx, - dcomplex *y, int *incy, dcomplex *a, int *lda); - -int zgeru_(int *m, int *n, dcomplex *alpha, dcomplex *x, int *incx, - dcomplex *y, int *incy, dcomplex *a, int *lda); - -int zhbmv_(char *uplo, int *n, int *k, dcomplex *alpha, dcomplex *a, - int *lda, dcomplex *x, int *incx, dcomplex *beta, dcomplex *y, - int *incy); - -int zhemm_(char *side, char *uplo, int *m, int *n, dcomplex *alpha, - dcomplex *a, int *lda, dcomplex *b, int *ldb, dcomplex *beta, - dcomplex *c, int *ldc); - -int zhemv_(char *uplo, int *n, dcomplex *alpha, dcomplex *a, int *lda, - dcomplex *x, int *incx, dcomplex *beta, dcomplex *y, int *incy); - -int zher_(char *uplo, int *n, double *alpha, dcomplex *x, int *incx, - dcomplex *a, int *lda); - -int zher2_(char *uplo, int *n, dcomplex *alpha, dcomplex *x, int *incx, - dcomplex *y, int *incy, dcomplex *a, int *lda); - -int zher2k_(char *uplo, char *trans, int *n, int *k, dcomplex *alpha, - dcomplex *a, int *lda, dcomplex *b, int *ldb, double *beta, - dcomplex *c, int *ldc); - -int zherk_(char *uplo, char *trans, int *n, int *k, double *alpha, - dcomplex *a, int *lda, double *beta, dcomplex *c, int *ldc); - -int zhpmv_(char *uplo, int *n, dcomplex *alpha, dcomplex *ap, dcomplex *x, - int *incx, dcomplex *beta, dcomplex *y, int *incy); - -int zhpr_(char *uplo, int *n, double *alpha, dcomplex *x, int *incx, - dcomplex *ap); - -int zhpr2_(char *uplo, int *n, dcomplex *alpha, dcomplex *x, int *incx, - dcomplex *y, int *incy, dcomplex *ap); - -int zrotg_(dcomplex *ca, dcomplex *cb, double *c, dcomplex *s); - -int zscal_(int *n, dcomplex *ca, dcomplex *cx, int *incx); - -int zswap_(int *n, dcomplex *cx, int *incx, dcomplex *cy, int *incy); - -int zsymm_(char *side, char *uplo, int *m, int *n, dcomplex *alpha, - dcomplex *a, int *lda, dcomplex *b, int *ldb, dcomplex *beta, - dcomplex *c, int *ldc); - -int zsyr2k_(char *uplo, char *trans, int *n, int *k, dcomplex *alpha, - dcomplex *a, int *lda, dcomplex *b, int *ldb, dcomplex *beta, - dcomplex *c, int *ldc); - -int zsyrk_(char *uplo, char *trans, int *n, int *k, dcomplex *alpha, - dcomplex *a, int *lda, dcomplex *beta, dcomplex *c, int *ldc); - -int ztbmv_(char *uplo, char *trans, char *diag, int *n, int *k, - dcomplex *a, int *lda, dcomplex *x, int *incx); - -int ztbsv_(char *uplo, char *trans, char *diag, int *n, int *k, - dcomplex *a, int *lda, dcomplex *x, int *incx); - -int ztpmv_(char *uplo, char *trans, char *diag, int *n, dcomplex *ap, - dcomplex *x, int *incx); - -int ztpsv_(char *uplo, char *trans, char *diag, int *n, dcomplex *ap, - dcomplex *x, int *incx); - -int ztrmm_(char *side, char *uplo, char *transa, char *diag, int *m, - int *n, dcomplex *alpha, dcomplex *a, int *lda, dcomplex *b, - int *ldb); - -int ztrmv_(char *uplo, char *trans, char *diag, int *n, dcomplex *a, - int *lda, dcomplex *x, int *incx); - -int ztrsm_(char *side, char *uplo, char *transa, char *diag, int *m, - int *n, dcomplex *alpha, dcomplex *a, int *lda, dcomplex *b, - int *ldb); - -int ztrsv_(char *uplo, char *trans, char *diag, int *n, dcomplex *a, - int *lda, dcomplex *x, int *incx); diff --git a/sklearn/svm/src/blas/daxpy.c b/sklearn/svm/src/blas/daxpy.c deleted file mode 100644 index 58f345a53ae80..0000000000000 --- a/sklearn/svm/src/blas/daxpy.c +++ /dev/null @@ -1,49 +0,0 @@ -#include "blas.h" - -int daxpy_(int *n, double *sa, double *sx, int *incx, double *sy, - int *incy) -{ - long int i, m, ix, iy, nn, iincx, iincy; - register double ssa; - - /* constant times a vector plus a vector. - uses unrolled loop for increments equal to one. - jack dongarra, linpack, 3/11/78. - modified 12/3/93, array(1) declarations changed to array(*) */ - - /* Dereference inputs */ - nn = *n; - ssa = *sa; - iincx = *incx; - iincy = *incy; - - if( nn > 0 && ssa != 0.0 ) - { - if (iincx == 1 && iincy == 1) /* code for both increments equal to 1 */ - { - m = nn-3; - for (i = 0; i < m; i += 4) - { - sy[i] += ssa * sx[i]; - sy[i+1] += ssa * sx[i+1]; - sy[i+2] += ssa * sx[i+2]; - sy[i+3] += ssa * sx[i+3]; - } - for ( ; i < nn; ++i) /* clean-up loop */ - sy[i] += ssa * sx[i]; - } - else /* code for unequal increments or equal increments not equal to 1 */ - { - ix = iincx >= 0 ? 0 : (1 - nn) * iincx; - iy = iincy >= 0 ? 0 : (1 - nn) * iincy; - for (i = 0; i < nn; i++) - { - sy[iy] += ssa * sx[ix]; - ix += iincx; - iy += iincy; - } - } - } - - return 0; -} /* daxpy_ */ diff --git a/sklearn/svm/src/blas/ddot.c b/sklearn/svm/src/blas/ddot.c deleted file mode 100644 index a64a2808f04f0..0000000000000 --- a/sklearn/svm/src/blas/ddot.c +++ /dev/null @@ -1,50 +0,0 @@ -#include "blas.h" - -double ddot_(int *n, double *sx, int *incx, double *sy, int *incy) -{ - long int i, m, nn, iincx, iincy; - double stemp; - long int ix, iy; - - /* forms the dot product of two vectors. - uses unrolled loops for increments equal to one. - jack dongarra, linpack, 3/11/78. - modified 12/3/93, array(1) declarations changed to array(*) */ - - /* Dereference inputs */ - nn = *n; - iincx = *incx; - iincy = *incy; - - stemp = 0.0; - if (nn > 0) - { - if (iincx == 1 && iincy == 1) /* code for both increments equal to 1 */ - { - m = nn-4; - for (i = 0; i < m; i += 5) - stemp += sx[i] * sy[i] + sx[i+1] * sy[i+1] + sx[i+2] * sy[i+2] + - sx[i+3] * sy[i+3] + sx[i+4] * sy[i+4]; - - for ( ; i < nn; i++) /* clean-up loop */ - stemp += sx[i] * sy[i]; - } - else /* code for unequal increments or equal increments not equal to 1 */ - { - ix = 0; - iy = 0; - if (iincx < 0) - ix = (1 - nn) * iincx; - if (iincy < 0) - iy = (1 - nn) * iincy; - for (i = 0; i < nn; i++) - { - stemp += sx[ix] * sy[iy]; - ix += iincx; - iy += iincy; - } - } - } - - return stemp; -} /* ddot_ */ diff --git a/sklearn/svm/src/blas/dnrm2.c b/sklearn/svm/src/blas/dnrm2.c deleted file mode 100644 index e50cdf777de34..0000000000000 --- a/sklearn/svm/src/blas/dnrm2.c +++ /dev/null @@ -1,62 +0,0 @@ -#include /* Needed for fabs() and sqrt() */ -#include "blas.h" - -double dnrm2_(int *n, double *x, int *incx) -{ - long int ix, nn, iincx; - double norm, scale, absxi, ssq, temp; - -/* DNRM2 returns the euclidean norm of a vector via the function - name, so that - - DNRM2 := sqrt( x'*x ) - - -- This version written on 25-October-1982. - Modified on 14-October-1993 to inline the call to SLASSQ. - Sven Hammarling, Nag Ltd. */ - - /* Dereference inputs */ - nn = *n; - iincx = *incx; - - if( nn > 0 && iincx > 0 ) - { - if (nn == 1) - { - norm = fabs(x[0]); - } - else - { - scale = 0.0; - ssq = 1.0; - - /* The following loop is equivalent to this call to the LAPACK - auxiliary routine: CALL SLASSQ( N, X, INCX, SCALE, SSQ ) */ - - for (ix=(nn-1)*iincx; ix>=0; ix-=iincx) - { - if (x[ix] != 0.0) - { - absxi = fabs(x[ix]); - if (scale < absxi) - { - temp = scale / absxi; - ssq = ssq * (temp * temp) + 1.0; - scale = absxi; - } - else - { - temp = absxi / scale; - ssq += temp * temp; - } - } - } - norm = scale * sqrt(ssq); - } - } - else - norm = 0.0; - - return norm; - -} /* dnrm2_ */ diff --git a/sklearn/svm/src/blas/dscal.c b/sklearn/svm/src/blas/dscal.c deleted file mode 100644 index a0eca0c399b86..0000000000000 --- a/sklearn/svm/src/blas/dscal.c +++ /dev/null @@ -1,44 +0,0 @@ -#include "blas.h" - -int dscal_(int *n, double *sa, double *sx, int *incx) -{ - long int i, m, nincx, nn, iincx; - double ssa; - - /* scales a vector by a constant. - uses unrolled loops for increment equal to 1. - jack dongarra, linpack, 3/11/78. - modified 3/93 to return if incx .le. 0. - modified 12/3/93, array(1) declarations changed to array(*) */ - - /* Dereference inputs */ - nn = *n; - iincx = *incx; - ssa = *sa; - - if (nn > 0 && iincx > 0) - { - if (iincx == 1) /* code for increment equal to 1 */ - { - m = nn-4; - for (i = 0; i < m; i += 5) - { - sx[i] = ssa * sx[i]; - sx[i+1] = ssa * sx[i+1]; - sx[i+2] = ssa * sx[i+2]; - sx[i+3] = ssa * sx[i+3]; - sx[i+4] = ssa * sx[i+4]; - } - for ( ; i < nn; ++i) /* clean-up loop */ - sx[i] = ssa * sx[i]; - } - else /* code for increment not equal to 1 */ - { - nincx = nn * iincx; - for (i = 0; i < nincx; i += iincx) - sx[i] = ssa * sx[i]; - } - } - - return 0; -} /* dscal_ */ diff --git a/sklearn/svm/src/liblinear/COPYRIGHT b/sklearn/svm/src/liblinear/COPYRIGHT index eefd055afe2a9..94371bb4cfd3a 100644 --- a/sklearn/svm/src/liblinear/COPYRIGHT +++ b/sklearn/svm/src/liblinear/COPYRIGHT @@ -1,5 +1,5 @@ -Copyright (c) 2007-2012 The LIBLINEAR Project. +Copyright (c) 2007-2014 The LIBLINEAR Project. All rights reserved. Redistribution and use in source and binary forms, with or without diff --git a/sklearn/svm/src/liblinear/LIBLINEAR_CHANGES b/sklearn/svm/src/liblinear/LIBLINEAR_CHANGES deleted file mode 100644 index 2deea1610b0cf..0000000000000 --- a/sklearn/svm/src/liblinear/LIBLINEAR_CHANGES +++ /dev/null @@ -1,15 +0,0 @@ -To compute probabilities in L1 logistic regression: - -diff --git a/scikits/learn/src/linear.cpp b/scikits/learn/src/linear.cpp -index 55f578d..2746585 100644 ---- a/scikits/learn/src/linear.cpp -+++ b/scikits/learn/src/linear.cpp -@@ -1961,7 +1961,7 @@ int predict(const model *model_, const feature_node *x) - - int predict_probability(const struct model *model_, const struct feature_node *x, double* prob_estimates) - { -- if(model_->param.solver_type==L2R_LR) -+ if(model_->param.solver_type==L2R_LR || model_->param.solver_type == L1R_LR) - { - int i; - int nr_class=model_->nr_class; diff --git a/sklearn/svm/src/liblinear/liblinear_helper.c b/sklearn/svm/src/liblinear/liblinear_helper.c index 857d8d5f928bb..06902ae3c2a6d 100644 --- a/sklearn/svm/src/liblinear/liblinear_helper.c +++ b/sklearn/svm/src/liblinear/liblinear_helper.c @@ -61,7 +61,7 @@ static struct feature_node **dense_to_sparse(double *x, npy_intp *dims, if (sparse[i] == NULL) { int k; for (k=0; ksolver_type = solver_type; param->eps = eps; param->C = C; - param->p = .1; // epsilon for epsilon-SVR; TODO pass as a parameter + param->p = epsilon; // epsilon for epsilon-SVR param->nr_weight = (int) nr_weight; param->weight_label = (int *) weight_label; param->weight = (double *) weight; + param->max_iter = max_iter; return param; } void copy_w(void *data, struct model *model, int len) { memcpy(data, model->w, len * sizeof(double)); - } double get_bias(struct model *model) diff --git a/sklearn/svm/src/liblinear/linear.cpp b/sklearn/svm/src/liblinear/linear.cpp index ed7429e8678f7..5ba05c775efec 100644 --- a/sklearn/svm/src/liblinear/linear.cpp +++ b/sklearn/svm/src/liblinear/linear.cpp @@ -7,6 +7,17 @@ - Changes roles of +1 and -1 to match scikit API, Andreas Mueller See issue 546: https://github.com/scikit-learn/scikit-learn/pull/546 + - Also changed roles for pairwise class weights, Andreas Mueller + See issue 1491: https://github.com/scikit-learn/scikit-learn/pull/1491 + + Modified 2014: + + - Remove the hard-coded value of max_iter (1000), that allows max_iter + to be passed as a parameter from the classes LogisticRegression and + LinearSVC, Manoj Kumar + - Added function get_n_iter that exposes the number of iterations. + See issue 3499: https://github.com/scikit-learn/scikit-learn/issues/3499 + See pull 3501: https://github.com/scikit-learn/scikit-learn/pull/3501 */ @@ -27,7 +38,7 @@ template static inline T min(T x,T y) { return (x static inline T max(T x,T y) { return (x>y)?x:y; } #endif template static inline void clone(T*& dst, S* src, int n) -{ +{ dst = new T[n]; memcpy((void *)dst,(void *)src,sizeof(T)*n); } @@ -390,12 +401,12 @@ double l2r_l2_svr_fun::fun(double *w) int l=prob->l; int w_size=get_nr_variable(); double d; - + Xv(w, z); for(i=0;ivalue; QD[i] += val*val; - + // Uncomment the for loop if initial alpha isn't zero // for(m=0; mindex-1)*nr_class+m] += alpha[i*nr_class+m]*val; @@ -593,7 +604,7 @@ void Solver_MCSVM_CS::Solve(double *w) index[i] = i; } - while(iter < max_iter) + while(iter < max_iter) { double stopping = -INF; for(i=0;im) { - if(!be_shrunk(i, active_size_i[i], y_index[i], + if(!be_shrunk(i, active_size_i[i], y_index[i], alpha_i[alpha_index_i[active_size_i[i]]], minG)) { swap(alpha_index_i[m], alpha_index_i[active_size_i[i]]); swap(G[m], G[active_size_i[i]]); if(y_index[i] == active_size_i[i]) y_index[i] = m; - else if(y_index[i] == m) + else if(y_index[i] == m) y_index[i] = active_size_i[i]; break; } @@ -664,7 +675,7 @@ void Solver_MCSVM_CS::Solve(double *w) { active_size--; swap(index[s], index[active_size]); - s--; + s--; continue; } @@ -755,6 +766,7 @@ void Solver_MCSVM_CS::Solve(double *w) delete [] alpha_index; delete [] y_index; delete [] active_size_i; + return iter; } // A coordinate descent algorithm for @@ -787,16 +799,15 @@ void Solver_MCSVM_CS::Solve(double *w) #define GETI(i) (y[i]+1) // To support weights for instances, use GETI(i) (i) -static void solve_l2r_l1l2_svc( - const problem *prob, double *w, double eps, - double Cp, double Cn, int solver_type) +static int solve_l2r_l1l2_svc( + const problem *prob, double *w, double eps, + double Cp, double Cn, int solver_type, int max_iter) { int l = prob->l; int w_size = prob->n; int i, s, iter = 0; double C, d, G; double *QD = new double[l]; - int max_iter = 1000; int *index = new int[l]; double *alpha = new double[l]; schar *y = new schar[l]; @@ -823,7 +834,7 @@ static void solve_l2r_l1l2_svc( { if(prob->y[i] > 0) { - y[i] = +1; + y[i] = +1; } else { @@ -835,7 +846,7 @@ static void solve_l2r_l1l2_svc( // 0 <= alpha[i] <= upper_bound[GETI(i)] for(i=0; il; double C = param->C; @@ -1015,14 +1027,13 @@ static void solve_l2r_l1l2_svr( int w_size = prob->n; double eps = param->eps; int i, s, iter = 0; - int max_iter = 1000; int active_size = l; int *index = new int[l]; double d, G, H; double Gmax_old = INF; double Gmax_new, Gnorm1_new; - double Gnorm1_init; + double Gnorm1_init = -1.0; // Gnorm1_init is initialized at the first iteration double *beta = new double[l]; double *QD = new double[l]; double *y = prob->y; @@ -1207,6 +1218,7 @@ static void solve_l2r_l1l2_svr( delete [] beta; delete [] QD; delete [] index; + return iter; } @@ -1232,18 +1244,18 @@ static void solve_l2r_l1l2_svr( #define GETI(i) (y[i]+1) // To support weights for instances, use GETI(i) (i) -void solve_l2r_lr_dual(const problem *prob, double *w, double eps, double Cp, double Cn) +int solve_l2r_lr_dual(const problem *prob, double *w, double eps, double Cp, double Cn, + int max_iter) { int l = prob->l; int w_size = prob->n; int i, s, iter = 0; double *xTx = new double[l]; - int max_iter = 1000; - int *index = new int[l]; + int *index = new int[l]; double *alpha = new double[2*l]; // store alpha and C - alpha - schar *y = new schar[l]; + schar *y = new schar[l]; int max_inner_iter = 100; // for inner Newton - double innereps = 1e-2; + double innereps = 1e-2; double innereps_min = min(1e-8, eps); double upper_bound[3] = {Cn, 0, Cp}; @@ -1251,14 +1263,14 @@ void solve_l2r_lr_dual(const problem *prob, double *w, double eps, double Cp, do { if(prob->y[i] > 0) { - y[i] = +1; + y[i] = +1; } else { y[i] = -1; } } - + // Initial alpha can be set here. Note that // 0 < alpha[i] < upper_bound[GETI(i)] // alpha[2*i] + alpha[2*i+1] = upper_bound[GETI(i)] @@ -1310,7 +1322,7 @@ void solve_l2r_lr_dual(const problem *prob, double *w, double eps, double Cp, do // Decide to minimize g_1(z) or g_2(z) int ind1 = 2*i, ind2 = 2*i+1, sign = 1; - if(0.5*a*(alpha[ind2]-alpha[ind1])+b < 0) + if(0.5*a*(alpha[ind2]-alpha[ind1])+b < 0) { ind1 = 2*i+1; ind2 = 2*i; @@ -1320,7 +1332,7 @@ void solve_l2r_lr_dual(const problem *prob, double *w, double eps, double Cp, do // g_t(z) = z*log(z) + (C-z)*log(C-z) + 0.5a(z-alpha_old)^2 + sign*b(z-alpha_old) double alpha_old = alpha[ind1]; double z = alpha_old; - if(C - z < 0.5 * C) + if(C - z < 0.5 * C) z = 0.1*z; double gp = a*(z-alpha_old)+sign*b+log(z/(C-z)); Gmax = max(Gmax, fabs(gp)); @@ -1328,13 +1340,13 @@ void solve_l2r_lr_dual(const problem *prob, double *w, double eps, double Cp, do // Newton method on the sub-problem const double eta = 0.1; // xi in the paper int inner_iter = 0; - while (inner_iter <= max_inner_iter) + while (inner_iter <= max_inner_iter) { if(fabs(gp) < innereps) break; double gpp = a + C/(C-z)/z; double tmpz = z - gp/gpp; - if(tmpz <= 0) + if(tmpz <= 0) z *= eta; else // tmpz in (0, C) z = tmpz; @@ -1352,7 +1364,7 @@ void solve_l2r_lr_dual(const problem *prob, double *w, double eps, double Cp, do { w[xi->index-1] += sign*(z-alpha_old)*yi*xi->value; xi++; - } + } } } @@ -1360,10 +1372,10 @@ void solve_l2r_lr_dual(const problem *prob, double *w, double eps, double Cp, do if(iter % 10 == 0) info("."); - if(Gmax < eps) + if(Gmax < eps) break; - if(newton_iter <= l/10) + if(newton_iter <= l/10) innereps = max(innereps_min, 0.1*innereps); } @@ -1373,13 +1385,13 @@ void solve_l2r_lr_dual(const problem *prob, double *w, double eps, double Cp, do info("\nWARNING: reaching max number of iterations\nUsing -s 0 may be faster (also see FAQ)\n\n"); // calculate objective value - + double v = 0; for(i=0; il; int w_size = prob_col->n; int j, s, iter = 0; - int max_iter = 1000; int active_size = w_size; int max_num_linesearch = 20; @@ -1421,7 +1433,7 @@ static void solve_l1r_l2_svc( double d, G_loss, G, H; double Gmax_old = INF; double Gmax_new, Gnorm1_new; - double Gnorm1_init; + double Gnorm1_init = -1.0; // Gnorm1_init is initialized at the first iteration double d_old, d_diff; double loss_old, loss_new; double appxcond, cond; @@ -1674,14 +1686,15 @@ static void solve_l1r_l2_svc( delete [] y; delete [] b; delete [] xj_sq; + return iter; } -// A coordinate descent algorithm for +// A coordinate descent algorithm for // L1-regularized logistic regression problems // // min_w \sum |wj| + C \sum log(1+exp(-yi w^T xi)), // -// Given: +// Given: // x, y, Cp, Cn // eps is the stopping tolerance // @@ -1693,14 +1706,13 @@ static void solve_l1r_l2_svc( #define GETI(i) (y[i]+1) // To support weights for instances, use GETI(i) (i) -static void solve_l1r_lr( - const problem *prob_col, double *w, double eps, - double Cp, double Cn) +static int solve_l1r_lr( + const problem *prob_col, double *w, double eps, + double Cp, double Cn, int max_newton_iter) { int l = prob_col->l; int w_size = prob_col->n; int j, s, newton_iter=0, iter=0; - int max_newton_iter = 100; int max_iter = 1000; int max_num_linesearch = 20; int active_size; @@ -1711,7 +1723,7 @@ static void solve_l1r_lr( double sigma = 0.01; double w_norm, w_norm_new; double z, G, H; - double Gnorm1_init; + double Gnorm1_init = -1.0; // Gnorm1_init is initialized at the first iteration double Gmax_old = INF; double Gmax_new, Gnorm1_new; double QP_Gmax_old = INF; @@ -2026,7 +2038,7 @@ static void solve_l1r_lr( info("WARNING: reaching max number of iterations\n"); // calculate objective value - + double v = 0; int nnz = 0; for(j=0; jl; int n = prob->n; - int nnz = 0; - int *col_ptr = new int[n+1]; + size_t nnz = 0; + size_t *col_ptr = new size_t [n+1]; feature_node *x_space; prob_col->l = l; prob_col->n = n; @@ -2153,7 +2166,7 @@ static void group_classes(const problem *prob, int *nr_class_ret, int **label_re } /* START MOD: Sort labels and apply to array count --dyamins */ - + int j; for (j=1; jeps; + int max_iter=param->max_iter; int pos = 0; int neg = 0; + int n_iter = -1; for(int i=0;il;i++) if(prob->y[i] > 0) pos++; neg = prob->l - pos; - + double primal_solver_tol = eps*max(min(pos,neg), 1)/prob->l; function *fun_obj=NULL; @@ -2231,11 +2265,11 @@ static void train_one(const problem *prob, const parameter *param, double *w, do C[i] = Cn; } fun_obj=new l2r_lr_fun(prob, C); - TRON tron_obj(fun_obj, primal_solver_tol); + TRON tron_obj(fun_obj, primal_solver_tol, max_iter); tron_obj.set_print_string(liblinear_print_string); - tron_obj.tron(w); + n_iter=tron_obj.tron(w); delete fun_obj; - delete C; + delete[] C; break; } case L2R_L2LOSS_SVC: @@ -2249,25 +2283,25 @@ static void train_one(const problem *prob, const parameter *param, double *w, do C[i] = Cn; } fun_obj=new l2r_l2_svc_fun(prob, C); - TRON tron_obj(fun_obj, primal_solver_tol); + TRON tron_obj(fun_obj, primal_solver_tol, max_iter); tron_obj.set_print_string(liblinear_print_string); - tron_obj.tron(w); + n_iter=tron_obj.tron(w); delete fun_obj; - delete C; + delete[] C; break; } case L2R_L2LOSS_SVC_DUAL: - solve_l2r_l1l2_svc(prob, w, eps, Cp, Cn, L2R_L2LOSS_SVC_DUAL); + n_iter=solve_l2r_l1l2_svc(prob, w, eps, Cp, Cn, L2R_L2LOSS_SVC_DUAL, max_iter); break; case L2R_L1LOSS_SVC_DUAL: - solve_l2r_l1l2_svc(prob, w, eps, Cp, Cn, L2R_L1LOSS_SVC_DUAL); + n_iter=solve_l2r_l1l2_svc(prob, w, eps, Cp, Cn, L2R_L1LOSS_SVC_DUAL, max_iter); break; case L1R_L2LOSS_SVC: { problem prob_col; feature_node *x_space = NULL; transpose(prob, &x_space ,&prob_col); - solve_l1r_l2_svc(&prob_col, w, primal_solver_tol, Cp, Cn); + n_iter=solve_l1r_l2_svc(&prob_col, w, primal_solver_tol, Cp, Cn, max_iter); delete [] prob_col.y; delete [] prob_col.x; delete [] x_space; @@ -2278,40 +2312,41 @@ static void train_one(const problem *prob, const parameter *param, double *w, do problem prob_col; feature_node *x_space = NULL; transpose(prob, &x_space ,&prob_col); - solve_l1r_lr(&prob_col, w, primal_solver_tol, Cp, Cn); + n_iter=solve_l1r_lr(&prob_col, w, primal_solver_tol, Cp, Cn, max_iter); delete [] prob_col.y; delete [] prob_col.x; delete [] x_space; break; } case L2R_LR_DUAL: - solve_l2r_lr_dual(prob, w, eps, Cp, Cn); + n_iter=solve_l2r_lr_dual(prob, w, eps, Cp, Cn, max_iter); break; case L2R_L2LOSS_SVR: { double *C = new double[prob->l]; for(int i = 0; i < prob->l; i++) C[i] = param->C; - + fun_obj=new l2r_l2_svr_fun(prob, C, param->p); - TRON tron_obj(fun_obj, param->eps); + TRON tron_obj(fun_obj, param->eps, max_iter); tron_obj.set_print_string(liblinear_print_string); - tron_obj.tron(w); + n_iter=tron_obj.tron(w); delete fun_obj; - delete C; + delete[] C; break; } case L2R_L1LOSS_SVR_DUAL: - solve_l2r_l1l2_svr(prob, w, param, L2R_L1LOSS_SVR_DUAL); + n_iter=solve_l2r_l1l2_svr(prob, w, param, L2R_L1LOSS_SVR_DUAL, max_iter); break; case L2R_L2LOSS_SVR_DUAL: - solve_l2r_l1l2_svr(prob, w, param, L2R_L2LOSS_SVR_DUAL); + n_iter=solve_l2r_l1l2_svr(prob, w, param, L2R_L2LOSS_SVR_DUAL, max_iter); break; default: fprintf(stderr, "ERROR: unknown solver_type\n"); break; } + return n_iter; } // @@ -2323,6 +2358,7 @@ model* train(const problem *prob, const parameter *param) int l = prob->l; int n = prob->n; int w_size = prob->n; + int n_iter; model *model_ = Malloc(model,1); if(prob->bias>=0) @@ -2332,14 +2368,13 @@ model* train(const problem *prob, const parameter *param) model_->param = *param; model_->bias = prob->bias; - if(param->solver_type == L2R_L2LOSS_SVR || - param->solver_type == L2R_L1LOSS_SVR_DUAL || - param->solver_type == L2R_L2LOSS_SVR_DUAL) + if(check_regression_model(model_)) { model_->w = Malloc(double, w_size); + model_->n_iter = Malloc(int, 1); model_->nr_class = 2; model_->label = NULL; - train_one(prob, param, &model_->w[0], 0, 0); + model_->n_iter[0] =train_one(prob, param, &model_->w[0], 0, 0); } else { @@ -2391,18 +2426,19 @@ model* train(const problem *prob, const parameter *param) if(param->solver_type == MCSVM_CS) { model_->w=Malloc(double, n*nr_class); + model_->n_iter=Malloc(int, 1); for(i=0;ieps); - Solver.Solve(model_->w); + model_->n_iter[0]=Solver.Solve(model_->w); } else { if(nr_class == 2) { model_->w=Malloc(double, w_size); - + model_->n_iter=Malloc(int, 1); int e0 = start[0]+count[0]; k=0; for(; kw[0], weighted_C[0], weighted_C[1]); + model_->n_iter[0]=train_one(&sub_prob, param, &model_->w[0], weighted_C[1], weighted_C[0]); } else { model_->w=Malloc(double, w_size*nr_class); double *w=Malloc(double, w_size); + model_->n_iter=Malloc(int, nr_class); for(i=0;iC); + model_->n_iter[i]=train_one(&sub_prob, param, w, weighted_C[i], param->C); for(int j=0;jw[j*nr_class+i] = w[j]; @@ -2455,10 +2492,15 @@ model* train(const problem *prob, const parameter *param) void cross_validation(const problem *prob, const parameter *param, int nr_fold, double *target) { int i; - int *fold_start = Malloc(int,nr_fold+1); + int *fold_start; int l = prob->l; int *perm = Malloc(int,l); - + if (nr_fold > l) + { + nr_fold = l; + fprintf(stderr,"WARNING: # folds > # data. Will use # folds = # data instead (i.e., leave-one-out cross validation)\n"); + } + fold_start = Malloc(int,nr_fold+1); for(i=0;iparam.solver_type == L2R_L2LOSS_SVR || - model_->param.solver_type == L2R_L1LOSS_SVR_DUAL || - model_->param.solver_type == L2R_L2LOSS_SVR_DUAL) + if(check_regression_model(model_)) return dec_values[0]; else return (dec_values[0]>0)?model_->label[0]:model_->label[1]; @@ -2590,7 +2630,7 @@ double predict_probability(const struct model *model_, const struct feature_node prob_estimates[i]=prob_estimates[i]/sum; } - return label; + return label; } else return 0; @@ -2630,7 +2670,7 @@ int save_model(const char *model_file_name, const struct model *model_) fprintf(fp, "solver_type %s\n", solver_type_table[param.solver_type]); fprintf(fp, "nr_class %d\n", model_->nr_class); - + if(model_->label) { fprintf(fp, "label"); @@ -2673,7 +2713,7 @@ struct model *load_model(const char *model_file_name) parameter& param = model_->param; model_->label = NULL; - + char *old_locale = strdup(setlocale(LC_ALL, NULL)); setlocale(LC_ALL, "C"); @@ -2696,7 +2736,7 @@ struct model *load_model(const char *model_file_name) if(solver_type_table[i] == NULL) { fprintf(stderr,"unknown solver type.\n"); - + setlocale(LC_ALL, old_locale); free(model_->label); free(model_); @@ -2761,10 +2801,10 @@ struct model *load_model(const char *model_file_name) fscanf(fp, "%lf ", &model_->w[i*nr_w+j]); fscanf(fp, "\n"); } - + setlocale(LC_ALL, old_locale); free(old_locale); - + if (ferror(fp) != 0 || fclose(fp) != 0) return NULL; return model_; @@ -2788,6 +2828,67 @@ void get_labels(const model *model_, int* label) label[i] = model_->label[i]; } +void get_n_iter(const model *model_, int* n_iter) +{ + int labels; + labels = model_->nr_class; + if (labels == 2) + labels = 1; + + if (model_->n_iter != NULL) + for(int i=0;in_iter[i]; +} + +#if 0 +// use inline here for better performance (around 20% faster than the non-inline one) +static inline double get_w_value(const struct model *model_, int idx, int label_idx) +{ + int nr_class = model_->nr_class; + int solver_type = model_->param.solver_type; + const double *w = model_->w; + + if(idx < 0 || idx > model_->nr_feature) + return 0; + if(check_regression_model(model_)) + return w[idx]; + else + { + if(label_idx < 0 || label_idx >= nr_class) + return 0; + if(nr_class == 2 && solver_type != MCSVM_CS) + { + if(label_idx == 0) + return w[idx]; + else + return -w[idx]; + } + else + return w[idx*nr_class+label_idx]; + } +} + +// feat_idx: starting from 1 to nr_feature +// label_idx: starting from 0 to nr_class-1 for classification models; +// for regression models, label_idx is ignored. +double get_decfun_coef(const struct model *model_, int feat_idx, int label_idx) +{ + if(feat_idx > model_->nr_feature) + return 0; + return get_w_value(model_, feat_idx-1, label_idx); +} + +double get_decfun_bias(const struct model *model_, int label_idx) +{ + int bias_idx = model_->nr_feature; + double bias = model_->bias; + if(bias <= 0) + return 0; + else + return bias*get_w_value(model_, bias_idx, label_idx); +} +#endif + void free_model_content(struct model *model_ptr) { if(model_ptr->w != NULL) @@ -2821,7 +2922,7 @@ const char *check_parameter(const problem *prob, const parameter *param) if(param->C <= 0) return "C <= 0"; - + if(param->p < 0) return "p < 0"; @@ -2850,9 +2951,16 @@ int check_probability_model(const struct model *model_) } #endif +int check_regression_model(const struct model *model_) +{ + return (model_->param.solver_type==L2R_L2LOSS_SVR || + model_->param.solver_type==L2R_L1LOSS_SVR_DUAL || + model_->param.solver_type==L2R_L2LOSS_SVR_DUAL); +} + void set_print_string_function(void (*print_func)(const char*)) { - if (print_func == NULL) + if (print_func == NULL) liblinear_print_string = &print_string_stdout; else liblinear_print_string = print_func; diff --git a/sklearn/svm/src/liblinear/linear.h b/sklearn/svm/src/liblinear/linear.h index 22a356743a790..d3ef54686797f 100644 --- a/sklearn/svm/src/liblinear/linear.h +++ b/sklearn/svm/src/liblinear/linear.h @@ -31,6 +31,7 @@ struct parameter int nr_weight; int *weight_label; double* weight; + int max_iter; double p; }; @@ -42,6 +43,7 @@ struct model double *w; int *label; /* label of each class */ double bias; + int *n_iter; /* no. of iterations of each class */ }; struct model* train(const struct problem *prob, const struct parameter *param); @@ -57,6 +59,11 @@ struct model *load_model(const char *model_file_name); int get_nr_feature(const struct model *model_); int get_nr_class(const struct model *model_); void get_labels(const struct model *model_, int* label); +void get_n_iter(const struct model *model_, int* n_iter); +#if 0 +double get_decfun_coef(const struct model *model_, int feat_idx, int label_idx); +double get_decfun_bias(const struct model *model_, int label_idx); +#endif void free_model_content(struct model *model_ptr); void free_and_destroy_model(struct model **model_ptr_ptr); @@ -64,6 +71,7 @@ void destroy_param(struct parameter *param); const char *check_parameter(const struct problem *prob, const struct parameter *param); int check_probability_model(const struct model *model); +int check_regression_model(const struct model *model); void set_print_string_function(void (*print_func) (const char*)); #ifdef __cplusplus diff --git a/sklearn/svm/src/liblinear/tron.cpp b/sklearn/svm/src/liblinear/tron.cpp index b54bedf18cd95..1bf3204415468 100644 --- a/sklearn/svm/src/liblinear/tron.cpp +++ b/sklearn/svm/src/liblinear/tron.cpp @@ -12,18 +12,9 @@ template static inline T min(T x,T y) { return (x static inline T max(T x,T y) { return (x>y)?x:y; } #endif -#ifdef __cplusplus extern "C" { -#endif - -extern double dnrm2_(int *, double *, int *); -extern double ddot_(int *, double *, int *, double *, int *); -extern int daxpy_(int *, double *, double *, int *, double *, int *); -extern int dscal_(int *, double *, double *, int *); - -#ifdef __cplusplus +#include } -#endif static void default_print(const char *buf) { @@ -53,7 +44,7 @@ TRON::~TRON() { } -void TRON::tron(double *w) +int TRON::tron(double *w) { // Parameters for updating the iterates. double eta0 = 1e-4, eta1 = 0.25, eta2 = 0.75; @@ -63,7 +54,7 @@ void TRON::tron(double *w) int n = fun_obj->get_nr_variable(); int i, cg_iter; - double delta, snorm, one=1.0; + double delta, snorm; double alpha, f, fnew, prered, actred, gs; int search = 1, iter = 1, inc = 1; double *s = new double[n]; @@ -74,9 +65,9 @@ void TRON::tron(double *w) for (i=0; ifun(w); + f = fun_obj->fun(w); fun_obj->grad(w, g); - delta = dnrm2_(&n, g, &inc); + delta = cblas_dnrm2(n, g, inc); double gnorm1 = delta; double gnorm = gnorm1; @@ -90,17 +81,17 @@ void TRON::tron(double *w) cg_iter = trcg(delta, g, s, r); memcpy(w_new, w, sizeof(double)*n); - daxpy_(&n, &one, s, &inc, w_new, &inc); + cblas_daxpy(n, 1.0, s, inc, w_new, inc); - gs = ddot_(&n, g, &inc, s, &inc); - prered = -0.5*(gs-ddot_(&n, s, &inc, r, &inc)); - fnew = fun_obj->fun(w_new); + gs = cblas_ddot(n, g, inc, s, inc); + prered = -0.5*(gs - cblas_ddot(n, s, inc, r, inc)); + fnew = fun_obj->fun(w_new); // Compute the actual reduction. - actred = f - fnew; + actred = f - fnew; // On the first iteration, adjust the initial step bound. - snorm = dnrm2_(&n, s, &inc); + snorm = cblas_dnrm2(n, s, inc); if (iter == 1) delta = min(delta, snorm); @@ -127,9 +118,9 @@ void TRON::tron(double *w) iter++; memcpy(w, w_new, sizeof(double)*n); f = fnew; - fun_obj->grad(w, g); + fun_obj->grad(w, g); - gnorm = dnrm2_(&n, g, &inc); + gnorm = cblas_dnrm2(n, g, inc); if (gnorm <= eps*gnorm1) break; } @@ -155,13 +146,13 @@ void TRON::tron(double *w) delete[] r; delete[] w_new; delete[] s; + return --iter; } int TRON::trcg(double delta, double *g, double *s, double *r) { int i, inc = 1; int n = fun_obj->get_nr_variable(); - double one = 1; double *d = new double[n]; double *Hd = new double[n]; double rTr, rnewTrnew, alpha, beta, cgtol; @@ -172,45 +163,45 @@ int TRON::trcg(double delta, double *g, double *s, double *r) r[i] = -g[i]; d[i] = r[i]; } - cgtol = 0.1*dnrm2_(&n, g, &inc); + cgtol = 0.1 * cblas_dnrm2(n, g, inc); int cg_iter = 0; - rTr = ddot_(&n, r, &inc, r, &inc); + rTr = cblas_ddot(n, r, inc, r, inc); while (1) { - if (dnrm2_(&n, r, &inc) <= cgtol) + if (cblas_dnrm2(n, r, inc) <= cgtol) break; cg_iter++; fun_obj->Hv(d, Hd); - alpha = rTr/ddot_(&n, d, &inc, Hd, &inc); - daxpy_(&n, &alpha, d, &inc, s, &inc); - if (dnrm2_(&n, s, &inc) > delta) + alpha = rTr / cblas_ddot(n, d, inc, Hd, inc); + cblas_daxpy(n, alpha, d, inc, s, inc); + if (cblas_dnrm2(n, s, inc) > delta) { info("cg reaches trust region boundary\n"); alpha = -alpha; - daxpy_(&n, &alpha, d, &inc, s, &inc); + cblas_daxpy(n, alpha, d, inc, s, inc); - double std = ddot_(&n, s, &inc, d, &inc); - double sts = ddot_(&n, s, &inc, s, &inc); - double dtd = ddot_(&n, d, &inc, d, &inc); + double std = cblas_ddot(n, s, inc, d, inc); + double sts = cblas_ddot(n, s, inc, s, inc); + double dtd = cblas_ddot(n, d, inc, d, inc); double dsq = delta*delta; double rad = sqrt(std*std + dtd*(dsq-sts)); if (std >= 0) alpha = (dsq - sts)/(std + rad); else alpha = (rad - std)/dtd; - daxpy_(&n, &alpha, d, &inc, s, &inc); + cblas_daxpy(n, alpha, d, inc, s, inc); alpha = -alpha; - daxpy_(&n, &alpha, Hd, &inc, r, &inc); + cblas_daxpy(n, alpha, Hd, inc, r, inc); break; } alpha = -alpha; - daxpy_(&n, &alpha, Hd, &inc, r, &inc); - rnewTrnew = ddot_(&n, r, &inc, r, &inc); + cblas_daxpy(n, alpha, Hd, inc, r, inc); + rnewTrnew = cblas_ddot(n, r, inc, r, inc); beta = rnewTrnew/rTr; - dscal_(&n, &beta, d, &inc); - daxpy_(&n, &one, r, &inc, d, &inc); + cblas_dscal(n, beta, d, inc); + cblas_daxpy(n, 1.0, r, inc, d, inc); rTr = rnewTrnew; } diff --git a/sklearn/svm/src/liblinear/tron.h b/sklearn/svm/src/liblinear/tron.h index 3045c2e83a133..3349b83f6418a 100644 --- a/sklearn/svm/src/liblinear/tron.h +++ b/sklearn/svm/src/liblinear/tron.h @@ -18,7 +18,7 @@ class TRON TRON(const function *fun_obj, double eps = 0.1, int max_iter = 1000); ~TRON(); - void tron(double *w); + int tron(double *w); void set_print_string(void (*i_print) (const char *buf)); private: diff --git a/sklearn/svm/src/libsvm/LIBSVM_CHANGES b/sklearn/svm/src/libsvm/LIBSVM_CHANGES index 97936b4b49f47..7a30471387c53 100644 --- a/sklearn/svm/src/libsvm/LIBSVM_CHANGES +++ b/sklearn/svm/src/libsvm/LIBSVM_CHANGES @@ -3,3 +3,6 @@ Changes to Libsvm This is here mainly as checklist for incorporation of new versions of libsvm. * Add copyright to files svm.cpp and svm.h + * Add random_seed support and call to srand in fit function + +The changes made with respect to upstream are detailed in the heading of svm.cpp diff --git a/sklearn/svm/src/libsvm/libsvm_helper.c b/sklearn/svm/src/libsvm/libsvm_helper.c index da11c068567ec..b61cfd2c51b58 100644 --- a/sklearn/svm/src/libsvm/libsvm_helper.c +++ b/sklearn/svm/src/libsvm/libsvm_helper.c @@ -9,7 +9,7 @@ * but libsvm does not expose this structure, so we define it here * along some utilities to convert from numpy arrays. * - * License: New BSD. + * License: BSD 3 clause * * Author: 2010 Fabian Pedregosa */ @@ -53,13 +53,12 @@ struct svm_node *dense_to_libsvm (double *x, npy_intp *dims) /* - * Create a svm_parameter struct and return it. It is up to the user to - * free the resulting object. + * Fill an svm_parameter struct. */ void set_parameter(struct svm_parameter *param, int svm_type, int kernel_type, int degree, double gamma, double coef0, double nu, double cache_size, double C, double eps, double p, int shrinking, int probability, int nr_weight, - char *weight_label, char *weight) + char *weight_label, char *weight, int max_iter, int random_seed) { param->svm_type = svm_type; param->kernel_type = kernel_type; @@ -76,11 +75,12 @@ void set_parameter(struct svm_parameter *param, int svm_type, int kernel_type, i param->weight_label = (int *) weight_label; param->weight = (double *) weight; param->gamma = gamma; + param->max_iter = max_iter; + param->random_seed = random_seed; } /* - * Create and return a svm_problem struct. It is up to the user to free resulting - * structure. + * Fill an svm_problem struct. problem->x will be malloc'd. */ void set_problem(struct svm_problem *problem, char *X, char *Y, char *sample_weight, npy_intp *dims, int kernel_type) { @@ -108,7 +108,7 @@ struct svm_model *set_model(struct svm_parameter *param, int nr_class, char *SV, npy_intp *SV_dims, char *support, npy_intp *support_dims, npy_intp *sv_coef_strides, - char *sv_coef, char *rho, char *nSV, char *label, + char *sv_coef, char *rho, char *nSV, char *probA, char *probB) { struct svm_model *model; @@ -148,7 +148,8 @@ struct svm_model *set_model(struct svm_parameter *param, int nr_class, */ if (param->svm_type < 2) { memcpy(model->nSV, nSV, model->nr_class * sizeof(int)); - memcpy(model->label, label, model->nr_class * sizeof(int)); + for(i=0; i < model->nr_class; i++) + model->label[i] = i; } for (i=0; i < model->nr_class-1; i++) { @@ -276,16 +277,6 @@ void copy_nSV(char *data, struct svm_model *model) memcpy(data, model->nSV, model->nr_class * sizeof(int)); } -/* - * same as above with model->label - * TODO: maybe merge into the previous? - */ -void copy_label(char *data, struct svm_model *model) -{ - if (model->label == NULL) return; - memcpy(data, model->label, model->nr_class * sizeof(int)); -} - void copy_probA(char *data, struct svm_model *model, npy_intp * dims) { memcpy(data, model->probA, dims[0] * sizeof(double)); @@ -392,11 +383,6 @@ int free_param(struct svm_parameter *param) } -/* rely on built-in facility to control verbose output - * in the versions of libsvm >= 2.89 - */ -#if LIBSVM_VERSION && LIBSVM_VERSION >= 289 - /* borrowed from original libsvm code */ static void print_null(const char *s) {} @@ -409,14 +395,7 @@ static void print_string_stdout(const char *s) /* provide convenience wrapper */ void set_verbosity(int verbosity_flag){ if (verbosity_flag) -# if LIBSVM_VERSION < 291 - svm_print_string = &print_string_stdout; - else - svm_print_string = &print_null; -# else svm_set_print_string_function(&print_string_stdout); else svm_set_print_string_function(&print_null); -# endif } -#endif diff --git a/sklearn/svm/src/libsvm/libsvm_sparse_helper.c b/sklearn/svm/src/libsvm/libsvm_sparse_helper.c index 8ff39572703f6..cd769f2584762 100644 --- a/sklearn/svm/src/libsvm/libsvm_sparse_helper.c +++ b/sklearn/svm/src/libsvm/libsvm_sparse_helper.c @@ -44,7 +44,7 @@ struct svm_csr_node **csr_to_libsvm (double *values, int* indices, int* indptr, struct svm_parameter * set_parameter(int svm_type, int kernel_type, int degree, double gamma, double coef0, double nu, double cache_size, double C, double eps, double p, int shrinking, int probability, int nr_weight, - char *weight_label, char *weight) + char *weight_label, char *weight, int max_iter, int random_seed) { struct svm_parameter *param; param = malloc(sizeof(struct svm_parameter)); @@ -64,6 +64,8 @@ struct svm_parameter * set_parameter(int svm_type, int kernel_type, int degree, param->weight_label = (int *) weight_label; param->weight = (double *) weight; param->gamma = gamma; + param->max_iter = max_iter; + param->random_seed = random_seed; return param; } @@ -100,7 +102,7 @@ struct svm_csr_model *csr_set_model(struct svm_parameter *param, int nr_class, char *SV_data, npy_intp *SV_indices_dims, char *SV_indices, npy_intp *SV_indptr_dims, char *SV_intptr, - char *sv_coef, char *rho, char *nSV, char *label, + char *sv_coef, char *rho, char *nSV, char *probA, char *probB) { struct svm_csr_model *model; @@ -134,7 +136,8 @@ struct svm_csr_model *csr_set_model(struct svm_parameter *param, int nr_class, */ if (param->svm_type < 2) { memcpy(model->nSV, nSV, model->nr_class * sizeof(int)); - memcpy(model->label, label, model->nr_class * sizeof(int)); + for(i=0; i < model->nr_class; i++) + model->label[i] = i; } for (i=0; i < model->nr_class-1; i++) { @@ -304,6 +307,10 @@ void copy_intercept(char *data, struct svm_csr_model *model, npy_intp *dims) } } +void copy_support (char *data, struct svm_model *model) +{ + memcpy (data, model->sv_ind, (model->l) * sizeof(int)); +} /* * Some helpers to convert from libsvm sparse data structures @@ -406,11 +413,6 @@ int free_model_SV(struct svm_csr_model *model) } -/* rely on built-in facility to control verbose output - * in the versions of libsvm >= 2.89 - */ -#if LIBSVM_VERSION && LIBSVM_VERSION >= 289 - /* borrowed from original libsvm code */ static void print_null(const char *s) {} @@ -423,14 +425,7 @@ static void print_string_stdout(const char *s) /* provide convenience wrapper */ void set_verbosity(int verbosity_flag){ if (verbosity_flag) -# if LIBSVM_VERSION < 291 - svm_print_string = &print_string_stdout; - else - svm_print_string = &print_null; -# else svm_set_print_string_function(&print_string_stdout); else svm_set_print_string_function(&print_null); -# endif } -#endif diff --git a/sklearn/svm/src/libsvm/svm.cpp b/sklearn/svm/src/libsvm/svm.cpp index 8bb22c731ffc6..f6d6882e63643 100644 --- a/sklearn/svm/src/libsvm/svm.cpp +++ b/sklearn/svm/src/libsvm/svm.cpp @@ -36,7 +36,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - Support for dense data by Ming-Fang Weng - - Return indicies for support vectors, Fabian Pedregosa + - Return indices for support vectors, Fabian Pedregosa - Fixes to avoid name collision, Fabian Pedregosa @@ -60,7 +60,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "svm.h" #ifndef _LIBSVM_CPP -int libsvm_version = LIBSVM_VERSION; typedef float Qfloat; typedef signed char schar; #ifndef min @@ -96,7 +95,7 @@ static void print_string_stdout(const char *s) fflush(stdout); } static void (*svm_print_string) (const char *) = &print_string_stdout; -#if 1 + static void info(const char *fmt,...) { char buf[BUFSIZ]; @@ -106,9 +105,6 @@ static void info(const char *fmt,...) va_end(ap); (*svm_print_string)(buf); } -#else -static void info(const char *fmt,...) {} -#endif #endif #define _LIBSVM_CPP @@ -531,6 +527,7 @@ double Kernel::k_function(const PREFIX(node) *x, const PREFIX(node) *y, // // solution will be put in \alpha, objective value will be put in obj // + class Solver { public: Solver() {}; @@ -541,11 +538,12 @@ class Solver { double rho; double *upper_bound; double r; // for Solver_NU + bool solve_timed_out; }; void Solve(int l, const QMatrix& Q, const double *p_, const schar *y_, double *alpha_, const double *C_, double eps, - SolutionInfo* si, int shrinking); + SolutionInfo* si, int shrinking, int max_iter); protected: int active_size; schar *y; @@ -645,7 +643,7 @@ void Solver::reconstruct_gradient() void Solver::Solve(int l, const QMatrix& Q, const double *p_, const schar *y_, double *alpha_, const double *C_, double eps, - SolutionInfo* si, int shrinking) + SolutionInfo* si, int shrinking, int max_iter) { this->l = l; this->Q = &Q; @@ -656,6 +654,7 @@ void Solver::Solve(int l, const QMatrix& Q, const double *p_, const schar *y_, clone(C, C_, l); this->eps = eps; unshrink = false; + si->solve_timed_out = false; // initialize alpha_status { @@ -703,6 +702,13 @@ void Solver::Solve(int l, const QMatrix& Q, const double *p_, const schar *y_, while(1) { + // set max_iter to -1 to disable the mechanism + if ((max_iter != -1) && (iter >= max_iter)) { + info("WARN: libsvm Solver reached max_iter"); + si->solve_timed_out = true; + break; + } + // show progress and do shrinking if(--counter == 0) @@ -1141,10 +1147,10 @@ class Solver_NU : public Solver Solver_NU() {} void Solve(int l, const QMatrix& Q, const double *p, const schar *y, double *alpha, const double *C_, double eps, - SolutionInfo* si, int shrinking) + SolutionInfo* si, int shrinking, int max_iter) { this->si = si; - Solver::Solve(l,Q,p,y,alpha,C_,eps,si,shrinking); + Solver::Solve(l,Q,p,y,alpha,C_,eps,si,shrinking,max_iter); } private: SolutionInfo *si; @@ -1595,7 +1601,8 @@ static void solve_c_svc( Solver s; s.Solve(l, SVC_Q(*prob,*param,y), minus_ones, y, - alpha, C, param->eps, si, param->shrinking); + alpha, C, param->eps, si, param->shrinking, + param->max_iter); /* double sum_alpha=0; @@ -1659,7 +1666,7 @@ static void solve_nu_svc( Solver_NU s; s.Solve(l, SVC_Q(*prob,*param,y), zeros, y, - alpha, C, param->eps, si, param->shrinking); + alpha, C, param->eps, si, param->shrinking, param->max_iter); double r = si->r; info("C = %f\n",1/r); @@ -1714,7 +1721,7 @@ static void solve_one_class( Solver s; s.Solve(l, ONE_CLASS_Q(*prob,*param), zeros, ones, - alpha, C, param->eps, si, param->shrinking); + alpha, C, param->eps, si, param->shrinking, param->max_iter); delete[] C; delete[] zeros; @@ -1747,7 +1754,7 @@ static void solve_epsilon_svr( Solver s; s.Solve(2*l, SVR_Q(*prob,*param), linear_term, y, - alpha2, C, param->eps, si, param->shrinking); + alpha2, C, param->eps, si, param->shrinking, param->max_iter); double sum_alpha = 0; for(i=0;ieps, si, param->shrinking); + alpha2, C, param->eps, si, param->shrinking, param->max_iter); info("epsilon = %f\n",-si->r); @@ -1820,7 +1827,7 @@ struct decision_function static decision_function svm_train_one( const PREFIX(problem) *prob, const svm_parameter *param, - double Cp, double Cn) + double Cp, double Cn, int *status) { double *alpha = Malloc(double,prob->l); Solver::SolutionInfo si; @@ -1848,6 +1855,8 @@ static decision_function svm_train_one( break; } + *status |= si.solve_timed_out; + info("obj = %f, rho = %f\n",si.obj,si.rho); // output SVs @@ -1882,7 +1891,7 @@ static decision_function svm_train_one( return f; } -// Platt's binary SVM Probablistic Output: an improvement from Lin et al. +// Platt's binary SVM Probabilistic Output: an improvement from Lin et al. static void sigmoid_train( int l, const double *dec_values, const double *labels, double& A, double& B) @@ -1999,6 +2008,7 @@ static void sigmoid_train( static double sigmoid_predict(double decision_value, double A, double B) { double fApB = decision_value*A+B; + // 1-p used later; avoid catastrophic cancellation if (fApB >= 0) return exp(-fApB)/(1.0+exp(-fApB)); else @@ -2072,7 +2082,7 @@ static void multiclass_probability(int k, double **r, double *p) // Cross-validation decision values for probability estimates static void svm_binary_svc_probability( const PREFIX(problem) *prob, const svm_parameter *param, - double Cp, double Cn, double& probA, double& probB) + double Cp, double Cn, double& probA, double& probB, int * status) { int i; int nr_fold = 5; @@ -2145,7 +2155,7 @@ static void svm_binary_svc_probability( subparam.weight_label[1]=-1; subparam.weight[0]=Cp; subparam.weight[1]=Cn; - struct PREFIX(model) *submodel = PREFIX(train)(&subprob,&subparam); + struct PREFIX(model) *submodel = PREFIX(train)(&subprob,&subparam, status); for(j=begin;jl;i++) { @@ -2323,7 +2335,8 @@ static void remove_zero_weight(PREFIX(problem) *newprob, const PREFIX(problem) * // // Interface functions // -PREFIX(model) *PREFIX(train)(const PREFIX(problem) *prob, const svm_parameter *param) +PREFIX(model) *PREFIX(train)(const PREFIX(problem) *prob, const svm_parameter *param, + int *status) { PREFIX(problem) newprob; remove_zero_weight(&newprob, prob); @@ -2333,6 +2346,11 @@ PREFIX(model) *PREFIX(train)(const PREFIX(problem) *prob, const svm_parameter *p model->param = *param; model->free_sv = 0; // XXX + if(param->random_seed >= 0) + { + srand(param->random_seed); + } + if(param->svm_type == ONE_CLASS || param->svm_type == EPSILON_SVR || param->svm_type == NU_SVR) @@ -2352,7 +2370,7 @@ PREFIX(model) *PREFIX(train)(const PREFIX(problem) *prob, const svm_parameter *p model->probA[0] = NAMESPACE::svm_svr_probability(prob,param); } - NAMESPACE::decision_function f = NAMESPACE::svm_train_one(prob,param,0,0); + NAMESPACE::decision_function f = NAMESPACE::svm_train_one(prob,param,0,0, status); model->rho = Malloc(double,1); model->rho[0] = f.rho; @@ -2467,9 +2485,9 @@ PREFIX(model) *PREFIX(train)(const PREFIX(problem) *prob, const svm_parameter *p } if(param->probability) - NAMESPACE::svm_binary_svc_probability(&sub_prob,param,weighted_C[i],weighted_C[j],probA[p],probB[p]); + NAMESPACE::svm_binary_svc_probability(&sub_prob,param,weighted_C[i],weighted_C[j],probA[p],probB[p], status); - f[p] = NAMESPACE::svm_train_one(&sub_prob,param,weighted_C[i],weighted_C[j]); + f[p] = NAMESPACE::svm_train_one(&sub_prob,param,weighted_C[i],weighted_C[j], status); for(k=0;k 0) nonzero[si+k] = true; @@ -2608,6 +2626,10 @@ void PREFIX(cross_validation)(const PREFIX(problem) *prob, const svm_parameter * int l = prob->l; int *perm = Malloc(int,l); int nr_class; + if(param->random_seed >= 0) + { + srand(param->random_seed); + } // stratified cv may not give leave-one-out rate // Each class to l folds -> some folds may have zero elements @@ -2703,7 +2725,8 @@ void PREFIX(cross_validation)(const PREFIX(problem) *prob, const svm_parameter * subprob.W[k] = prob->W[perm[j]]; ++k; } - struct PREFIX(model) *submodel = PREFIX(train)(&subprob,param); + int dummy_status = 0; // IGNORES TIMEOUT ERRORS + struct PREFIX(model) *submodel = PREFIX(train)(&subprob,param, &dummy_status); if(param->probability && (param->svm_type == C_SVC || param->svm_type == NU_SVC)) { @@ -2764,14 +2787,13 @@ double PREFIX(get_svr_probability)(const PREFIX(model) *model) double PREFIX(predict_values)(const PREFIX(model) *model, const PREFIX(node) *x, double* dec_values) { - int i; + int i; if(model->param.svm_type == ONE_CLASS || model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) { double *sv_coef = model->sv_coef[0]; double sum = 0; - for(i=0;il;i++) #ifdef _DENSE_REP @@ -2789,7 +2811,6 @@ double PREFIX(predict_values)(const PREFIX(model) *model, const PREFIX(node) *x, } else { - int i; int nr_class = model->nr_class; int l = model->l; @@ -2906,41 +2927,55 @@ double PREFIX(predict_probability)( void PREFIX(free_model_content)(PREFIX(model)* model_ptr) { - if(model_ptr->free_sv && model_ptr->l > 0) + if(model_ptr->free_sv && model_ptr->l > 0 && model_ptr->SV != NULL) #ifdef _DENSE_REP - for (int i = 0; i < model_ptr->l; i++) - free (model_ptr->SV[i].values); + for (int i = 0; i < model_ptr->l; i++) + free(model_ptr->SV[i].values); #else free((void *)(model_ptr->SV[0])); #endif - for(int i=0;inr_class-1;i++) - free(model_ptr->sv_coef[i]); + + if(model_ptr->sv_coef) + { + for(int i=0;inr_class-1;i++) + free(model_ptr->sv_coef[i]); + } + free(model_ptr->SV); + model_ptr->SV = NULL; + free(model_ptr->sv_coef); + model_ptr->sv_coef = NULL; + free(model_ptr->sv_ind); + model_ptr->sv_ind = NULL; + free(model_ptr->rho); + model_ptr->rho = NULL; + free(model_ptr->label); + model_ptr->label= NULL; + free(model_ptr->probA); + model_ptr->probA = NULL; + free(model_ptr->probB); + model_ptr->probB= NULL; + free(model_ptr->nSV); + model_ptr->nSV = NULL; } void PREFIX(free_and_destroy_model)(PREFIX(model)** model_ptr_ptr) { - PREFIX(model)* model_ptr = *model_ptr_ptr; - if(model_ptr != NULL) + if(model_ptr_ptr != NULL && *model_ptr_ptr != NULL) { - PREFIX(free_model_content)(model_ptr); - free(model_ptr); + PREFIX(free_model_content)(*model_ptr_ptr); + free(*model_ptr_ptr); + *model_ptr_ptr = NULL; } } -void PREFIX(destroy_model)(PREFIX(model)* model_ptr) -{ - fprintf(stderr,"warning: svm_destroy_model is deprecated and should not be used. Please use svm_free_and_destroy_model(PREFIX(model) **model_ptr_ptr)\n"); - PREFIX(free_and_destroy_model)(&model_ptr); -} - void PREFIX(destroy_param)(svm_parameter* param) { free(param->weight_label); @@ -3069,14 +3104,6 @@ const char *PREFIX(check_parameter)(const PREFIX(problem) *prob, const svm_param return NULL; } -int PREFIX(check_probability_model)(const PREFIX(model) *model) -{ - return ((model->param.svm_type == C_SVC || model->param.svm_type == NU_SVC) && - model->probA!=NULL && model->probB!=NULL) || - ((model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) && - model->probA!=NULL); -} - void PREFIX(set_print_string_function)(void (*print_func)(const char *)) { if(print_func == NULL) diff --git a/sklearn/svm/src/libsvm/svm.h b/sklearn/svm/src/libsvm/svm.h index 298665302644c..93a041377a464 100644 --- a/sklearn/svm/src/libsvm/svm.h +++ b/sklearn/svm/src/libsvm/svm.h @@ -1,14 +1,12 @@ #ifndef _LIBSVM_H #define _LIBSVM_H -#define LIBSVM_VERSION 300 +#define LIBSVM_VERSION 310 #ifdef __cplusplus extern "C" { #endif -extern int libsvm_version; - struct svm_node { int dim; @@ -63,6 +61,8 @@ struct svm_parameter double p; /* for EPSILON_SVR */ int shrinking; /* use the shrinking heuristics */ int probability; /* do probability estimates */ + int max_iter; /* ceiling on Solver runtime */ + int random_seed; /* seed for random number generator */ }; // @@ -118,7 +118,7 @@ struct svm_csr_model }; -struct svm_model *svm_train(const struct svm_problem *prob, const struct svm_parameter *param); +struct svm_model *svm_train(const struct svm_problem *prob, const struct svm_parameter *param, int *status); void svm_cross_validation(const struct svm_problem *prob, const struct svm_parameter *param, int nr_fold, double *target); int svm_save_model(const char *model_file_name, const struct svm_model *model); @@ -138,18 +138,13 @@ void svm_free_and_destroy_model(struct svm_model **model_ptr_ptr); void svm_destroy_param(struct svm_parameter *param); const char *svm_check_parameter(const struct svm_problem *prob, const struct svm_parameter *param); -int svm_check_probability_model(const struct svm_model *model); void svm_set_print_string_function(void (*print_func)(const char *)); -// deprecated -// this function will be removed in future release -void svm_destroy_model(struct svm_model *model_ptr); - /* sparse version */ -struct svm_csr_model *svm_csr_train(const struct svm_csr_problem *prob, const struct svm_parameter *param); +struct svm_csr_model *svm_csr_train(const struct svm_csr_problem *prob, const struct svm_parameter *param, int *status); void svm_csr_cross_validation(const struct svm_csr_problem *prob, const struct svm_parameter *param, int nr_fold, double *target); int svm_csr_get_svm_type(const struct svm_csr_model *model); @@ -166,7 +161,6 @@ void svm_csr_free_and_destroy_model(struct svm_csr_model **model_ptr_ptr); void svm_csr_destroy_param(struct svm_parameter *param); const char *svm_csr_check_parameter(const struct svm_csr_problem *prob, const struct svm_parameter *param); -int svm_csr_check_probability_model(const struct svm_csr_model *model); /* end sparse version */ diff --git a/sklearn/svm/tests/test_bounds.py b/sklearn/svm/tests/test_bounds.py index 7a246990920c7..1856a396436b5 100644 --- a/sklearn/svm/tests/test_bounds.py +++ b/sklearn/svm/tests/test_bounds.py @@ -1,5 +1,7 @@ import nose -from nose.tools import assert_true +from nose.tools import assert_equal, assert_true +from sklearn.utils.testing import clean_warning_registry +import warnings import numpy as np from scipy import sparse as sp @@ -17,10 +19,10 @@ def test_l1_min_c(): - losses = ['l2', 'log'] + losses = ['squared_hinge', 'log'] Xs = {'sparse': sparse_X, 'dense': dense_X} Ys = {'two-classes': Y1, 'multi-class': Y2} - intercepts = {'no-intercept': {'fit_intercept': False}, + intercepts = {'no-intercept': {'fit_intercept': False}, 'fit-intercept': {'fit_intercept': True, 'intercept_scaling': 10}} @@ -30,17 +32,27 @@ def test_l1_min_c(): for intercept_label, intercept_params in intercepts.items(): check = lambda: check_l1_min_c(X, Y, loss, **intercept_params) - check.description = 'Test l1_min_c loss=%r %s %s %s' % \ - (loss, X_label, Y_label, intercept_label) + check.description = ('Test l1_min_c loss=%r %s %s %s' % + (loss, X_label, Y_label, + intercept_label)) yield check +def test_l2_deprecation(): + clean_warning_registry() + with warnings.catch_warnings(record=True) as w: + assert_equal(l1_min_c(dense_X, Y1, "l2"), + l1_min_c(dense_X, Y1, "squared_hinge")) + assert_equal(w[0].category, DeprecationWarning) + + def check_l1_min_c(X, y, loss, fit_intercept=True, intercept_scaling=None): min_c = l1_min_c(X, y, loss, fit_intercept, intercept_scaling) clf = { - 'log': LogisticRegression(penalty='l1'), - 'l2': LinearSVC(loss='l2', penalty='l1', dual=False), + 'log': LogisticRegression(penalty='l1'), + 'squared_hinge': LinearSVC(loss='squared_hinge', + penalty='l1', dual=False), }[loss] clf.fit_intercept = fit_intercept @@ -53,7 +65,7 @@ def check_l1_min_c(X, y, loss, fit_intercept=True, intercept_scaling=None): clf.C = min_c * 1.01 clf.fit(X, y) - assert_true((np.asarray(clf.coef_) != 0).any() or \ + assert_true((np.asarray(clf.coef_) != 0).any() or (np.asarray(clf.intercept_) != 0).any()) diff --git a/sklearn/svm/tests/test_sparse.py b/sklearn/svm/tests/test_sparse.py index 6d031a6ac3cb8..d1b93d5299da2 100644 --- a/sklearn/svm/tests/test_sparse.py +++ b/sklearn/svm/tests/test_sparse.py @@ -1,12 +1,16 @@ +from nose.tools import assert_raises, assert_true, assert_false + import numpy as np from scipy import sparse -from sklearn import datasets, svm, linear_model, base -from numpy.testing import assert_array_almost_equal, \ - assert_array_equal, assert_equal +from numpy.testing import (assert_array_almost_equal, assert_array_equal, + assert_equal) -from nose.tools import assert_raises, assert_true -from sklearn.datasets.samples_generator import make_classification +from sklearn import datasets, svm, linear_model, base +from sklearn.datasets import make_classification, load_digits from sklearn.svm.tests import test_svm +from sklearn.utils import ConvergenceWarning +from sklearn.utils.extmath import safe_sparse_dot +from sklearn.utils.testing import assert_warns # test sample 1 X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]) @@ -37,45 +41,91 @@ def test_svc(): """Check that sparse SVC gives the same result as SVC""" - clf = svm.SVC(kernel='linear').fit(X, Y) - sp_clf = svm.SVC(kernel='linear').fit(X_sp, Y) + clf = svm.SVC(kernel='linear', probability=True, random_state=0) + clf.fit(X, Y) + sp_clf = svm.SVC(kernel='linear', probability=True, random_state=0) + sp_clf.fit(X_sp, Y) assert_array_equal(sp_clf.predict(T), true_result) assert_true(sparse.issparse(sp_clf.support_vectors_)) assert_array_almost_equal(clf.support_vectors_, - sp_clf.support_vectors_.todense()) + sp_clf.support_vectors_.toarray()) assert_true(sparse.issparse(sp_clf.dual_coef_)) - assert_array_almost_equal(clf.dual_coef_, sp_clf.dual_coef_.todense()) + assert_array_almost_equal(clf.dual_coef_, sp_clf.dual_coef_.toarray()) assert_true(sparse.issparse(sp_clf.coef_)) - assert_array_almost_equal(clf.coef_, sp_clf.coef_.todense()) + assert_array_almost_equal(clf.coef_, sp_clf.coef_.toarray()) + assert_array_almost_equal(clf.support_, sp_clf.support_) assert_array_almost_equal(clf.predict(T), sp_clf.predict(T)) # refit with a different dataset clf.fit(X2, Y2) sp_clf.fit(X2_sp, Y2) assert_array_almost_equal(clf.support_vectors_, - sp_clf.support_vectors_.todense()) - assert_array_almost_equal(clf.dual_coef_, sp_clf.dual_coef_.todense()) - assert_array_almost_equal(clf.coef_, sp_clf.coef_.todense()) + sp_clf.support_vectors_.toarray()) + assert_array_almost_equal(clf.dual_coef_, sp_clf.dual_coef_.toarray()) + assert_array_almost_equal(clf.coef_, sp_clf.coef_.toarray()) + assert_array_almost_equal(clf.support_, sp_clf.support_) assert_array_almost_equal(clf.predict(T2), sp_clf.predict(T2)) + assert_array_almost_equal(clf.predict_proba(T2), + sp_clf.predict_proba(T2), 4) + + +def test_unsorted_indices(): + # test that the result with sorted and unsorted indices in csr is the same + # we use a subset of digits as iris, blobs or make_classification didn't + # show the problem + digits = load_digits() + X, y = digits.data[:50], digits.target[:50] + X_test = sparse.csr_matrix(digits.data[50:100]) + + X_sparse = sparse.csr_matrix(X) + coef_dense = svm.SVC(kernel='linear', probability=True, + random_state=0).fit(X, y).coef_ + sparse_svc = svm.SVC(kernel='linear', probability=True, + random_state=0).fit(X_sparse, y) + coef_sorted = sparse_svc.coef_ + # make sure dense and sparse SVM give the same result + assert_array_almost_equal(coef_dense, coef_sorted.toarray()) + + X_sparse_unsorted = X_sparse[np.arange(X.shape[0])] + X_test_unsorted = X_test[np.arange(X_test.shape[0])] + + # make sure we scramble the indices + assert_false(X_sparse_unsorted.has_sorted_indices) + assert_false(X_test_unsorted.has_sorted_indices) + + unsorted_svc = svm.SVC(kernel='linear', probability=True, + random_state=0).fit(X_sparse_unsorted, y) + coef_unsorted = unsorted_svc.coef_ + # make sure unsorted indices give same result + assert_array_almost_equal(coef_unsorted.toarray(), coef_sorted.toarray()) + assert_array_almost_equal(sparse_svc.predict_proba(X_test_unsorted), + sparse_svc.predict_proba(X_test)) + + +def test_svc_with_custom_kernel(): + kfunc = lambda x, y: safe_sparse_dot(x, y.T) + clf_lin = svm.SVC(kernel='linear').fit(X_sp, Y) + clf_mylin = svm.SVC(kernel=kfunc).fit(X_sp, Y) + assert_array_equal(clf_lin.predict(X_sp), clf_mylin.predict(X_sp)) def test_svc_iris(): """Test the sparse SVC with the iris dataset""" for k in ('linear', 'poly', 'rbf'): sp_clf = svm.SVC(kernel=k).fit(iris.data, iris.target) - clf = svm.SVC(kernel=k).fit(iris.data.todense(), iris.target) + clf = svm.SVC(kernel=k).fit(iris.data.toarray(), iris.target) assert_array_almost_equal(clf.support_vectors_, - sp_clf.support_vectors_.todense()) - assert_array_almost_equal(clf.dual_coef_, sp_clf.dual_coef_.todense()) + sp_clf.support_vectors_.toarray()) + assert_array_almost_equal(clf.dual_coef_, sp_clf.dual_coef_.toarray()) assert_array_almost_equal( - clf.predict(iris.data.todense()), sp_clf.predict(iris.data)) + clf.predict(iris.data.toarray()), sp_clf.predict(iris.data)) if k == 'linear': - assert_array_almost_equal(clf.coef_, sp_clf.coef_.todense()) + assert_array_almost_equal(clf.coef_, sp_clf.coef_.toarray()) def test_error(): @@ -101,36 +151,46 @@ def test_linearsvc(): """ Similar to test_SVC """ - clf = svm.LinearSVC().fit(X, Y) - sp_clf = svm.LinearSVC().fit(X_sp, Y) + clf = svm.LinearSVC(random_state=0).fit(X, Y) + sp_clf = svm.LinearSVC(random_state=0).fit(X_sp, Y) assert_true(sp_clf.fit_intercept) - assert_array_almost_equal(clf.raw_coef_, sp_clf.raw_coef_, decimal=4) + assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=4) + assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=4) assert_array_almost_equal(clf.predict(X), sp_clf.predict(X_sp)) clf.fit(X2, Y2) sp_clf.fit(X2_sp, Y2) - assert_array_almost_equal(clf.raw_coef_, sp_clf.raw_coef_, decimal=4) + assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=4) + assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=4) def test_linearsvc_iris(): """Test the sparse LinearSVC with the iris dataset""" - sp_clf = svm.LinearSVC().fit(iris.data, iris.target) - clf = svm.LinearSVC().fit(iris.data.todense(), iris.target) + sp_clf = svm.LinearSVC(random_state=0).fit(iris.data, iris.target) + clf = svm.LinearSVC(random_state=0).fit(iris.data.toarray(), iris.target) assert_equal(clf.fit_intercept, sp_clf.fit_intercept) - assert_array_almost_equal(clf.raw_coef_, sp_clf.raw_coef_, decimal=1) + assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=1) + assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=1) assert_array_almost_equal( - clf.predict(iris.data.todense()), sp_clf.predict(iris.data)) + clf.predict(iris.data.toarray()), sp_clf.predict(iris.data)) # check decision_function pred = np.argmax(sp_clf.decision_function(iris.data), 1) - assert_array_almost_equal(pred, clf.predict(iris.data.todense())) + assert_array_almost_equal(pred, clf.predict(iris.data.toarray())) + + # sparsify the coefficients on both models and check that they still + # produce the same results + clf.sparsify() + assert_array_equal(pred, clf.predict(iris.data)) + sp_clf.sparsify() + assert_array_equal(pred, sp_clf.predict(iris.data)) def test_weight(): @@ -142,7 +202,7 @@ def test_weight(): X_ = sparse.csr_matrix(X_) for clf in (linear_model.LogisticRegression(), - svm.LinearSVC(), + svm.LinearSVC(random_state=0), svm.SVC()): clf.set_params(class_weight={0: 5}) clf.fit(X_[:180], y_[:180]) @@ -188,29 +248,25 @@ def test_sparse_realdata(): X = sparse.csr_matrix((data, indices, indptr)) y = np.array( [1., 0., 2., 2., 1., 1., 1., 2., 2., 0., 1., 2., 2., - 0., 2., 0., 3., 0., 3., 0., 1., 1., 3., 2., 3., 2., - 0., 3., 1., 0., 2., 1., 2., 0., 1., 0., 2., 3., 1., - 3., 0., 1., 0., 0., 2., 0., 1., 2., 2., 2., 3., 2., - 0., 3., 2., 1., 2., 3., 2., 2., 0., 1., 0., 1., 2., - 3., 0., 0., 2., 2., 1., 3., 1., 1., 0., 1., 2., 1., - 1., 3.]) - - clf = svm.SVC(kernel='linear').fit(X.todense(), y) + 0., 2., 0., 3., 0., 3., 0., 1., 1., 3., 2., 3., 2., + 0., 3., 1., 0., 2., 1., 2., 0., 1., 0., 2., 3., 1., + 3., 0., 1., 0., 0., 2., 0., 1., 2., 2., 2., 3., 2., + 0., 3., 2., 1., 2., 3., 2., 2., 0., 1., 0., 1., 2., + 3., 0., 0., 2., 2., 1., 3., 1., 1., 0., 1., 2., 1., + 1., 3.]) + + clf = svm.SVC(kernel='linear').fit(X.toarray(), y) sp_clf = svm.SVC(kernel='linear').fit(sparse.coo_matrix(X), y) - assert_array_equal(clf.support_vectors_, sp_clf.support_vectors_.todense()) - assert_array_equal(clf.dual_coef_, sp_clf.dual_coef_.todense()) + assert_array_equal(clf.support_vectors_, sp_clf.support_vectors_.toarray()) + assert_array_equal(clf.dual_coef_, sp_clf.dual_coef_.toarray()) def test_sparse_svc_clone_with_callable_kernel(): - # first, test that we raise a value error for "sparse kernels" - # this test is only relevant for the deprecated sparse.SVC class. - sp = svm.sparse.SVC(C=1, kernel=lambda x, y: x * y.T, probability=True) - assert_raises(ValueError, sp.fit, X_sp, Y) - # Test that the "dense_fit" is called even though we use sparse input # meaning that everything works fine. - a = svm.SVC(C=1, kernel=lambda x, y: x * y.T, probability=True) + a = svm.SVC(C=1, kernel=lambda x, y: x * y.T, probability=True, + random_state=0) b = base.clone(a) b.fit(X_sp, Y) @@ -218,12 +274,22 @@ def test_sparse_svc_clone_with_callable_kernel(): b.predict_proba(X_sp) dense_svm = svm.SVC(C=1, kernel=lambda x, y: np.dot(x, y.T), - probability=True) + probability=True, random_state=0) pred_dense = dense_svm.fit(X, Y).predict(X) assert_array_equal(pred_dense, pred) # b.decision_function(X_sp) # XXX : should be supported -if __name__ == '__main__': - import nose - nose.runmodule() +def test_timeout(): + sp = svm.SVC(C=1, kernel=lambda x, y: x * y.T, probability=True, + random_state=0, max_iter=1) + + assert_warns(ConvergenceWarning, sp.fit, X_sp, Y) + + +def test_consistent_proba(): + a = svm.SVC(probability=True, max_iter=1, random_state=0) + proba_1 = a.fit(X, Y).predict_proba(X) + a = svm.SVC(probability=True, max_iter=1, random_state=0) + proba_2 = a.fit(X, Y).predict_proba(X) + assert_array_almost_equal(proba_1, proba_2) diff --git a/sklearn/svm/tests/test_svm.py b/sklearn/svm/tests/test_svm.py index 3790796feddd9..96b893a4dc765 100644 --- a/sklearn/svm/tests/test_svm.py +++ b/sklearn/svm/tests/test_svm.py @@ -5,14 +5,22 @@ """ import numpy as np -from numpy.testing import assert_array_equal, assert_array_almost_equal, \ - assert_almost_equal -from nose.tools import assert_raises, assert_true, assert_equal +import itertools + +from numpy.testing import assert_array_equal, assert_array_almost_equal +from numpy.testing import assert_almost_equal +from scipy import sparse +from nose.tools import assert_raises, assert_true, assert_equal, assert_false from sklearn import svm, linear_model, datasets, metrics, base from sklearn.datasets.samples_generator import make_classification +from sklearn.metrics import f1_score +from sklearn.metrics.pairwise import rbf_kernel from sklearn.utils import check_random_state -from sklearn.utils.testing import assert_greater, assert_less +from sklearn.utils import ConvergenceWarning +from sklearn.utils.testing import assert_greater, assert_in, assert_less +from sklearn.utils.testing import assert_raises_regexp, assert_warns +from sklearn.utils.testing import assert_warns_message # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] @@ -33,7 +41,7 @@ def test_libsvm_parameters(): Test parameters on classes that make use of libsvm. """ clf = svm.SVC(kernel='linear').fit(X, Y) - assert_array_equal(clf.dual_coef_, [[0.25, -.25]]) + assert_array_equal(clf.dual_coef_, [[-0.25, .25]]) assert_array_equal(clf.support_, [1, 3]) assert_array_equal(clf.support_vectors_, (X[1], X[3])) assert_array_equal(clf.intercept_, [0.]) @@ -41,31 +49,40 @@ def test_libsvm_parameters(): def test_libsvm_iris(): - """ - Check consistency on dataset iris. - """ + """Check consistency on dataset iris.""" # shuffle the dataset so that labels are not ordered for k in ('linear', 'rbf'): clf = svm.SVC(kernel=k).fit(iris.data, iris.target) assert_greater(np.mean(clf.predict(iris.data) == iris.target), 0.9) - assert_array_equal(clf.label_, np.sort(clf.label_)) + assert_array_equal(clf.classes_, np.sort(clf.classes_)) # check also the low-level API model = svm.libsvm.fit(iris.data, iris.target.astype(np.float64)) pred = svm.libsvm.predict(iris.data, *model) assert_greater(np.mean(pred == iris.target), .95) - model = svm.libsvm.fit(iris.data, - iris.target.astype(np.float64), kernel='linear') + model = svm.libsvm.fit(iris.data, iris.target.astype(np.float64), + kernel='linear') pred = svm.libsvm.predict(iris.data, *model, kernel='linear') assert_greater(np.mean(pred == iris.target), .95) pred = svm.libsvm.cross_validation(iris.data, - iris.target.astype(np.float64), 5, kernel='linear') + iris.target.astype(np.float64), 5, + kernel='linear', + random_seed=0) assert_greater(np.mean(pred == iris.target), .95) + # If random_seed >= 0, the libsvm rng is seeded (by calling `srand`), hence + # we should get deteriministic results (assuming that there is no other + # thread calling this wrapper calling `srand` concurrently). + pred2 = svm.libsvm.cross_validation(iris.data, + iris.target.astype(np.float64), 5, + kernel='linear', + random_seed=0) + assert_array_equal(pred, pred2) + def test_single_sample_1d(): """ @@ -75,7 +92,7 @@ def test_single_sample_1d(): clf = svm.SVC().fit(X, Y) clf.predict(X[0]) - clf = svm.LinearSVC().fit(X, Y) + clf = svm.LinearSVC(random_state=0).fit(X, Y) clf.predict(X[0]) @@ -95,7 +112,7 @@ def test_precomputed(): pred = clf.predict(KT) assert_raises(ValueError, clf.predict, KT.T) - assert_array_equal(clf.dual_coef_, [[0.25, -.25]]) + assert_array_equal(clf.dual_coef_, [[-0.25, .25]]) assert_array_equal(clf.support_, [1, 3]) assert_array_equal(clf.intercept_, [0]) assert_array_almost_equal(clf.support_, [1, 3]) @@ -119,7 +136,7 @@ def test_precomputed(): clf.fit(X, Y) pred = clf.predict(T) - assert_array_equal(clf.dual_coef_, [[0.25, -.25]]) + assert_array_equal(clf.dual_coef_, [[-0.25, .25]]) assert_array_equal(clf.intercept_, [0]) assert_array_almost_equal(clf.support_, [1, 3]) assert_array_equal(pred, true_result) @@ -160,10 +177,42 @@ def test_svr(): diabetes = datasets.load_diabetes() for clf in (svm.NuSVR(kernel='linear', nu=.4, C=1.0), svm.NuSVR(kernel='linear', nu=.4, C=10.), - svm.SVR(kernel='linear', C=10.)): + svm.SVR(kernel='linear', C=10.), + svm.LinearSVR(C=10.), + svm.LinearSVR(C=10.), + ): clf.fit(diabetes.data, diabetes.target) assert_greater(clf.score(diabetes.data, diabetes.target), 0.02) + # non-regression test; previously, BaseLibSVM would check that + # len(np.unique(y)) < 2, which must only be done for SVC + svm.SVR().fit(diabetes.data, np.ones(len(diabetes.data))) + svm.LinearSVR().fit(diabetes.data, np.ones(len(diabetes.data))) + + +def test_linearsvr(): + # check that SVR(kernel='linear') and LinearSVC() give + # comparable results + diabetes = datasets.load_diabetes() + lsvr = svm.LinearSVR(C=1e3).fit(diabetes.data, diabetes.target) + score1 = lsvr.score(diabetes.data, diabetes.target) + + svr = svm.SVR(kernel='linear', C=1e3).fit(diabetes.data, diabetes.target) + score2 = svr.score(diabetes.data, diabetes.target) + + assert np.linalg.norm(lsvr.coef_ - svr.coef_) / np.linalg.norm(svr.coef_) < .1 + assert np.abs(score1 - score2) < 0.1 + + +def test_svr_errors(): + X = [[0.0], [1.0]] + y = [0.0, 0.5] + + # Bad kernel + clf = svm.SVR(kernel=lambda x, y: np.array([[1.0]])) + clf.fit(X, y) + assert_raises(ValueError, clf.predict, X) + def test_oneclass(): """ @@ -210,7 +259,7 @@ def test_oneclass_decision_function(): dec_func_test = clf.decision_function(X_test) assert_array_equal((dec_func_test > 0).ravel(), y_pred_test == 1) dec_func_outliers = clf.decision_function(X_outliers) - assert_array_equal((dec_func_outliers > 0).ravel(), y_pred_outliers == 1) + assert_array_equal((dec_func_outliers > 0).ravel(), y_pred_outliers == 1) def test_tweak_params(): @@ -226,9 +275,9 @@ def test_tweak_params(): """ clf = svm.SVC(kernel='linear', C=1.0) clf.fit(X, Y) - assert_array_equal(clf.dual_coef_, [[.25, -.25]]) + assert_array_equal(clf.dual_coef_, [[-.25, .25]]) assert_array_equal(clf.predict([[-.1, -.1]]), [1]) - clf.dual_coef_ = np.array([[.0, 1.]]) + clf._dual_coef_ = np.array([[.0, 1.]]) assert_array_equal(clf.predict([[-.1, -.1]]), [2]) @@ -239,9 +288,8 @@ def test_probability(): This uses cross validation, so we use a slightly bigger testing set. """ - for clf in ( - svm.SVC(probability=True, C=1.0), - svm.NuSVC(probability=True)): + for clf in (svm.SVC(probability=True, random_state=0, C=1.0), + svm.NuSVC(probability=True, random_state=0)): clf.fit(iris.data, iris.target) @@ -249,7 +297,7 @@ def test_probability(): assert_array_almost_equal( np.sum(prob_predict, 1), np.ones(iris.data.shape[0])) assert_true(np.mean(np.argmax(prob_predict, 1) - == clf.predict(iris.data)) > 0.9) + == clf.predict(iris.data)) > 0.9) assert_almost_equal(clf.predict_proba(iris.data), np.exp(clf.predict_log_proba(iris.data)), 8) @@ -274,12 +322,21 @@ def test_decision_function(): clf.fit(X, Y) dec = np.dot(X, clf.coef_.T) + clf.intercept_ prediction = clf.predict(X) - assert_array_almost_equal(dec, clf.decision_function(X)) - assert_array_almost_equal(prediction, clf.label_[(clf.decision_function(X) - > 0).astype(np.int).ravel()]) - expected = np.array([[-1.], [-0.66], [-1.], [0.66], [1.], [1.]]) + assert_array_almost_equal(dec.ravel(), clf.decision_function(X)) + assert_array_almost_equal( + prediction, + clf.classes_[(clf.decision_function(X) > 0).astype(np.int)]) + expected = np.array([-1., -0.66, -1., 0.66, 1., 1.]) assert_array_almost_equal(clf.decision_function(X), expected, 2) + # kernel binary: + clf = svm.SVC(kernel='rbf', gamma=1) + clf.fit(X, Y) + + rbfs = rbf_kernel(X, clf.support_vectors_, gamma=clf.gamma) + dec = np.dot(rbfs, clf.dual_coef_.T) + clf.intercept_ + assert_array_almost_equal(dec.ravel(), clf.decision_function(X)) + def test_weight(): """ @@ -291,15 +348,15 @@ def test_weight(): # so all predicted values belong to class 2 assert_array_almost_equal(clf.predict(X), [2] * 6) - X_, y_ = make_classification(n_samples=200, n_features=100, - weights=[0.833, 0.167], random_state=0) + X_, y_ = make_classification(n_samples=200, n_features=10, + weights=[0.833, 0.167], random_state=2) for clf in (linear_model.LogisticRegression(), - svm.LinearSVC(), svm.SVC()): - clf.set_params(class_weight={0: 5}) - clf.fit(X_[: 180], y_[: 180]) - y_pred = clf.predict(X_[180:]) - assert_true(np.sum(y_pred == y_[180:]) >= 11) + svm.LinearSVC(random_state=0), svm.SVC()): + clf.set_params(class_weight={0: .1, 1: 10}) + clf.fit(X_[:100], y_[:100]) + y_pred = clf.predict(X_[100:]) + assert_true(f1_score(y_[100:], y_pred) > .3) def test_sample_weights(): @@ -315,27 +372,40 @@ def test_sample_weights(): clf.fit(X, Y, sample_weight=sample_weight) assert_array_equal(clf.predict(X[2]), [2.]) + # test that rescaling all samples is the same as changing C + clf = svm.SVC() + clf.fit(X, Y) + dual_coef_no_weight = clf.dual_coef_ + clf.set_params(C=100) + clf.fit(X, Y, sample_weight=np.repeat(0.01, len(X))) + assert_array_almost_equal(dual_coef_no_weight, clf.dual_coef_) + def test_auto_weight(): """Test class weights for imbalanced data""" from sklearn.linear_model import LogisticRegression - # we take as dataset a the two-dimensional projection of iris so + # We take as dataset the two-dimensional projection of iris so # that it is not separable and remove half of predictors from - # class 1 - from sklearn.svm.base import _get_class_weight - X, y = iris.data[:, :2], iris.target - unbalanced = np.delete(np.arange(y.size), np.where(y > 1)[0][::2]) - - assert_true(np.argmax(_get_class_weight('auto', y[unbalanced])[0]) == 2) - - for clf in (svm.SVC(kernel='linear'), - svm.LinearSVC(), LogisticRegression()): + # class 1. + # We add one to the targets as a non-regression test: class_weight="auto" + # used to work only when the labels where a range [0..K). + from sklearn.utils import compute_class_weight + X, y = iris.data[:, :2], iris.target + 1 + unbalanced = np.delete(np.arange(y.size), np.where(y > 2)[0][::2]) + + classes = np.unique(y[unbalanced]) + class_weights = compute_class_weight('auto', classes, y[unbalanced]) + assert_true(np.argmax(class_weights) == 2) + + for clf in (svm.SVC(kernel='linear'), svm.LinearSVC(random_state=0), + LogisticRegression()): # check that score is better when class='auto' is set. y_pred = clf.fit(X[unbalanced], y[unbalanced]).predict(X) clf.set_params(class_weight='auto') y_pred_balanced = clf.fit(X[unbalanced], y[unbalanced],).predict(X) - assert_true(metrics.f1_score(y, y_pred) <= - metrics.f1_score(y, y_pred_balanced)) + assert_true(metrics.f1_score(y, y_pred, average='weighted') + <= metrics.f1_score(y, y_pred_balanced, + average='weighted')) def test_bad_input(): @@ -353,13 +423,13 @@ def test_bad_input(): assert_raises(ValueError, clf.fit, X, Y2) # Test with arrays that are non-contiguous. - for clf in (svm.SVC(), svm.LinearSVC()): + for clf in (svm.SVC(), svm.LinearSVC(random_state=0)): Xf = np.asfortranarray(X) - assert_true(Xf.flags['C_CONTIGUOUS'] == False) + assert_false(Xf.flags['C_CONTIGUOUS']) yf = np.ascontiguousarray(np.tile(Y, (2, 1)).T) yf = yf[:, -1] - assert_true(yf.flags['F_CONTIGUOUS'] == False) - assert_true(yf.flags['C_CONTIGUOUS'] == False) + assert_false(yf.flags['F_CONTIGUOUS']) + assert_false(yf.flags['C_CONTIGUOUS']) clf.fit(Xf, yf) assert_array_equal(clf.predict(T), true_result) @@ -367,6 +437,14 @@ def test_bad_input(): clf = svm.SVC(kernel='precomputed') assert_raises(ValueError, clf.fit, X, Y) + # sample_weight bad dimensions + clf = svm.SVC() + assert_raises(ValueError, clf.fit, X, Y, sample_weight=range(len(X) - 1)) + + # predict with sparse input when trained with dense + clf = svm.SVC().fit(X, Y) + assert_raises(ValueError, clf.predict, sparse.lil_matrix(X)) + Xt = np.array(X).T clf.fit(np.dot(X, Xt), Y) assert_raises(ValueError, clf.predict, X) @@ -376,33 +454,112 @@ def test_bad_input(): assert_raises(ValueError, clf.predict, Xt) +def test_sparse_precomputed(): + clf = svm.SVC(kernel='precomputed') + sparse_gram = sparse.csr_matrix([[1, 0], [0, 1]]) + try: + clf.fit(sparse_gram, [0, 1]) + assert not "reached" + except TypeError as e: + assert_in("Sparse precomputed", str(e)) + + def test_linearsvc_parameters(): """ Test possible parameter combinations in LinearSVC """ - # generate list of possible parameter combinations - params = [(dual, loss, penalty) for dual in [True, False] - for loss in ['l1', 'l2', 'lr'] for penalty in ['l1', 'l2']] - - for dual, loss, penalty in params: - if loss == 'l1' and penalty == 'l1': - assert_raises(ValueError, svm.LinearSVC, penalty=penalty, - loss=loss, dual=dual) - elif loss == 'l1' and penalty == 'l2' and dual == False: - assert_raises(ValueError, svm.LinearSVC, penalty=penalty, - loss=loss, dual=dual) - elif penalty == 'l1' and dual == True: - assert_raises(ValueError, svm.LinearSVC, penalty=penalty, - loss=loss, dual=dual) - else: - svm.LinearSVC(penalty=penalty, loss=loss, dual=dual) + # Generate list of possible parameter combinations + losses = ['hinge', 'squared_hinge', 'logistic_regression', 'foo'] + penalties, duals = ['l1', 'l2', 'bar'], [True, False] + + X, y = make_classification(n_samples=5, n_features=5) + + for loss, penalty, dual in itertools.product(losses, penalties, duals): + clf = svm.LinearSVC(penalty=penalty, loss=loss, dual=dual) + if ((loss, penalty) == ('hinge', 'l1') or + (loss, penalty, dual) == ('hinge', 'l2', False) or + (penalty, dual) == ('l1', True) or + loss == 'foo' or penalty == 'bar'): + + assert_raises_regexp(ValueError, + "Unsupported set of arguments.*penalty='%s.*" + "loss='%s.*dual=%s" + % (penalty, loss, dual), + clf.fit, X, y) + else: + clf.fit(X, y) + + # Incorrect loss value - test if explicit error message is raised + assert_raises_regexp(ValueError, ".*loss='l3' is not supported.*", + svm.LinearSVC(loss="l3").fit, X, y) + + +# FIXME remove in 1.0 +def test_linearsvx_loss_penalty_deprecations(): + X, y = [[0.0], [1.0]], [0, 1] + + msg = ("loss='%s' has been deprecated in favor of " + "loss='%s' as of 0.16. Backward compatibility" + " for the %s will be removed in %s") + + # LinearSVC + # loss l1/L1 --> hinge + assert_warns_message(DeprecationWarning, + msg % ("l1", "hinge", "loss='l1'", "1.0"), + svm.LinearSVC(loss="l1").fit, X, y) + + # loss l2/L2 --> squared_hinge + assert_warns_message(DeprecationWarning, + msg % ("L2", "squared_hinge", "loss='L2'", "1.0"), + svm.LinearSVC(loss="L2").fit, X, y) + + # LinearSVR + # loss l1/L1 --> epsilon_insensitive + assert_warns_message(DeprecationWarning, + msg % ("L1", "epsilon_insensitive", "loss='L1'", + "1.0"), + svm.LinearSVR(loss="L1").fit, X, y) + + # loss l2/L2 --> squared_epsilon_insensitive + assert_warns_message(DeprecationWarning, + msg % ("l2", "squared_epsilon_insensitive", + "loss='l2'", "1.0"), + svm.LinearSVR(loss="l2").fit, X, y) + + +# FIXME remove in 0.18 +def test_linear_svx_uppercase_loss_penalty(): + # Check if Upper case notation is supported by _fit_liblinear + # which is called by fit + X, y = [[0.0], [1.0]], [0, 1] + + msg = ("loss='%s' has been deprecated in favor of " + "loss='%s' as of 0.16. Backward compatibility" + " for the uppercase notation will be removed in %s") + + # loss SQUARED_hinge --> squared_hinge + assert_warns_message(DeprecationWarning, + msg % ("SQUARED_hinge", "squared_hinge", "0.18"), + svm.LinearSVC(loss="SQUARED_hinge").fit, X, y) + + # penalty L2 --> l2 + assert_warns_message(DeprecationWarning, + msg.replace("loss", "penalty") + % ("L2", "l2", "0.18"), + svm.LinearSVC(penalty="L2").fit, X, y) + + # loss EPSILON_INSENSITIVE --> epsilon_insensitive + assert_warns_message(DeprecationWarning, + msg % ("EPSILON_INSENSITIVE", "epsilon_insensitive", + "0.18"), + svm.LinearSVR(loss="EPSILON_INSENSITIVE").fit, X, y) def test_linearsvc(): """ Test basic routines using LinearSVC """ - clf = svm.LinearSVC().fit(X, Y) + clf = svm.LinearSVC(random_state=0).fit(X, Y) # by default should have intercept assert_true(clf.fit_intercept) @@ -411,15 +568,16 @@ def test_linearsvc(): assert_array_almost_equal(clf.intercept_, [0], decimal=3) # the same with l1 penalty - clf = svm.LinearSVC(penalty='l1', dual=False).fit(X, Y) + clf = svm.LinearSVC(penalty='l1', loss='squared_hinge', dual=False, random_state=0).fit(X, Y) assert_array_equal(clf.predict(T), true_result) # l2 penalty with dual formulation - clf = svm.LinearSVC(penalty='l2', dual=True).fit(X, Y) + clf = svm.LinearSVC(penalty='l2', dual=True, random_state=0).fit(X, Y) assert_array_equal(clf.predict(T), true_result) # l2 penalty, l1 loss - clf = svm.LinearSVC(penalty='l2', loss='l1', dual=True).fit(X, Y) + clf = svm.LinearSVC(penalty='l2', loss='hinge', dual=True, random_state=0) + clf.fit(X, Y) assert_array_equal(clf.predict(T), true_result) # test also decision function @@ -430,32 +588,44 @@ def test_linearsvc(): def test_linearsvc_crammer_singer(): """Test LinearSVC with crammer_singer multi-class svm""" - ovr_clf = svm.LinearSVC().fit(iris.data, iris.target) - cs_clf = svm.LinearSVC(multi_class='crammer_singer') + ovr_clf = svm.LinearSVC(random_state=0).fit(iris.data, iris.target) + cs_clf = svm.LinearSVC(multi_class='crammer_singer', random_state=0) cs_clf.fit(iris.data, iris.target) # similar prediction for ovr and crammer-singer: assert_true((ovr_clf.predict(iris.data) == - cs_clf.predict(iris.data)).mean() > .9) + cs_clf.predict(iris.data)).mean() > .9) # classifiers shouldn't be the same assert_true((ovr_clf.coef_ != cs_clf.coef_).all()) # test decision function assert_array_equal(cs_clf.predict(iris.data), - np.argmax(cs_clf.decision_function(iris.data), axis=1)) + np.argmax(cs_clf.decision_function(iris.data), axis=1)) dec_func = np.dot(iris.data, cs_clf.coef_.T) + cs_clf.intercept_ assert_array_almost_equal(dec_func, cs_clf.decision_function(iris.data)) +def test_crammer_singer_binary(): + """Test Crammer-Singer formulation in the binary case""" + X, y = make_classification(n_classes=2, random_state=0) + + for fit_intercept in (True, False): + acc = svm.LinearSVC(fit_intercept=fit_intercept, + multi_class="crammer_singer", + random_state=0).fit(X, y).score(X, y) + assert_greater(acc, 0.9) + + def test_linearsvc_iris(): + """ Test that LinearSVC gives plausible predictions on the iris dataset Also, test symbolic class names (classes_). """ target = iris.target_names[iris.target] - clf = svm.LinearSVC().fit(iris.data, target) + clf = svm.LinearSVC(random_state=0).fit(iris.data, target) assert_equal(set(clf.classes_), set(iris.target_names)) assert_greater(np.mean(clf.predict(iris.data) == target), 0.8) @@ -473,8 +643,8 @@ def test_dense_liblinear_intercept_handling(classifier=svm.LinearSVC): [1, 3], [2, 3]] y = [0, 0, 1, 1] - clf = classifier(fit_intercept=True, penalty='l1', loss='l2', - dual=False, C=4, tol=1e-7) + clf = classifier(fit_intercept=True, penalty='l1', loss='squared_hinge', + dual=False, C=4, tol=1e-7, random_state=0) assert_true(clf.intercept_scaling == 1, clf.intercept_scaling) assert_true(clf.fit_intercept) @@ -506,7 +676,7 @@ def test_liblinear_set_coef(): clf.coef_ = clf.coef_.copy() clf.intercept_ = clf.intercept_.copy() values2 = clf.decision_function(iris.data) - assert_array_equal(values, values2) + assert_array_almost_equal(values, values2) # binary-class case X = [[2, 1], @@ -566,13 +736,81 @@ def test_linearsvc_verbose(): def test_svc_clone_with_callable_kernel(): - a = svm.SVC(kernel=lambda x, y: np.dot(x, y.T), probability=True) - b = base.clone(a) + # create SVM with callable linear kernel, check that results are the same + # as with built-in linear kernel + svm_callable = svm.SVC(kernel=lambda x, y: np.dot(x, y.T), + probability=True, random_state=0) + # clone for checking clonability with lambda functions.. + svm_cloned = base.clone(svm_callable) + svm_cloned.fit(iris.data, iris.target) + + svm_builtin = svm.SVC(kernel='linear', probability=True, random_state=0) + svm_builtin.fit(iris.data, iris.target) + + assert_array_almost_equal(svm_cloned.dual_coef_, + svm_builtin.dual_coef_) + assert_array_almost_equal(svm_cloned.intercept_, + svm_builtin.intercept_) + assert_array_equal(svm_cloned.predict(iris.data), + svm_builtin.predict(iris.data)) + + assert_array_almost_equal(svm_cloned.predict_proba(iris.data), + svm_builtin.predict_proba(iris.data), + decimal=4) + assert_array_almost_equal(svm_cloned.decision_function(iris.data), + svm_builtin.decision_function(iris.data)) + + +def test_svc_bad_kernel(): + svc = svm.SVC(kernel=lambda x, y: x) + assert_raises(ValueError, svc.fit, X, Y) + + +def test_timeout(): + a = svm.SVC(kernel=lambda x, y: np.dot(x, y.T), probability=True, + random_state=0, max_iter=1) + assert_warns(ConvergenceWarning, a.fit, X, Y) + + +def test_unfitted(): + X = "foo!" # input validation not required when SVM not fitted + + clf = svm.SVC() + assert_raises_regexp(Exception, r".*\bSVC\b.*\bnot\b.*\bfitted\b", + clf.predict, X) + + clf = svm.NuSVR() + assert_raises_regexp(Exception, r".*\bNuSVR\b.*\bnot\b.*\bfitted\b", + clf.predict, X) + + +def test_consistent_proba(): + a = svm.SVC(probability=True, max_iter=1, random_state=0) + proba_1 = a.fit(X, Y).predict_proba(X) + a = svm.SVC(probability=True, max_iter=1, random_state=0) + proba_2 = a.fit(X, Y).predict_proba(X) + assert_array_almost_equal(proba_1, proba_2) + + +def test_linear_svc_convergence_warnings(): + """Test that warnings are raised if model does not converge""" + + lsvc = svm.LinearSVC(max_iter=2, verbose=1) + assert_warns(ConvergenceWarning, lsvc.fit, X, Y) + assert_equal(lsvc.n_iter_, 2) + + +def test_svr_coef_sign(): + """Test that SVR(kernel="linear") has coef_ with the right sign.""" + # Non-regression test for #2933. + X = np.random.RandomState(21).randn(10, 3) + y = np.random.RandomState(12).randn(10) - b.fit(X, Y) - b.predict(X) - b.predict_proba(X) - b.decision_function(X) + for svr in [svm.SVR(kernel='linear'), svm.NuSVR(kernel='linear'), + svm.LinearSVR()]: + svr.fit(X, y) + assert_array_almost_equal(svr.predict(X), + np.dot(X, svr.coef_.ravel()) + svr.intercept_) if __name__ == '__main__': diff --git a/sklearn/test_setup.py b/sklearn/test_setup.py deleted file mode 100644 index 693da84e84fec..0000000000000 --- a/sklearn/test_setup.py +++ /dev/null @@ -1,12 +0,0 @@ -""" -Fixtures for the tests. - -This module gets loaded by test discovery scanners (such as nose) in -their collection scan. -""" - -import platform -import os -if platform.system() == 'Windows': - # During the tests, under Windows, we don't want any multiprocessing - os.environ['JOBLIB_MULTIPROCESSING'] = '0' diff --git a/sklearn/tests/test_base.py b/sklearn/tests/test_base.py index 19afe7bc225d0..d0cd0050fd8f8 100644 --- a/sklearn/tests/test_base.py +++ b/sklearn/tests/test_base.py @@ -1,19 +1,22 @@ # Author: Gael Varoquaux -# License: BSD +# License: BSD 3 clause import numpy as np import scipy.sparse as sp -from numpy.testing import assert_array_equal -from nose.tools import assert_true -from nose.tools import assert_false -from nose.tools import assert_equal -from nose.tools import assert_raises +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_not_equal +from sklearn.utils.testing import assert_raises + from sklearn.base import BaseEstimator, clone, is_classifier from sklearn.svm import SVC from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV +from sklearn.utils import deprecated ############################################################################# @@ -37,6 +40,19 @@ def __init__(self, a=None, b=None): self.b = b +class DeprecatedAttributeEstimator(BaseEstimator): + def __init__(self, a=None, b=None): + self.a = a + if b is not None: + DeprecationWarning("b is deprecated and renamed 'a'") + self.a = b + + @property + @deprecated("Parameter 'b' is deprecated and renamed to 'a'") + def b(self): + return self._b + + class Buggy(BaseEstimator): " A buggy estimator that does not set its parameters right. " @@ -44,6 +60,23 @@ def __init__(self, a=None): self.a = 1 +class NoEstimator(object): + def __init__(self): + pass + + def fit(self, X=None, y=None): + return self + + def predict(self, X=None): + return None + + +class VargEstimator(BaseEstimator): + """Sklearn estimators shouldn't have vargs.""" + def __init__(self, *vargs): + pass + + ############################################################################# # The tests @@ -51,7 +84,7 @@ def test_clone(): """Tests that clone creates a correct deep copy. We create an estimator, make a copy of its original state - (which, in this case, is the current state of the setimator), + (which, in this case, is the current state of the estimator), and check that the obtained copy is a correct deep copy. """ @@ -88,6 +121,12 @@ def test_clone_buggy(): buggy.a = 2 assert_raises(RuntimeError, clone, buggy) + no_estimator = NoEstimator() + assert_raises(TypeError, clone, no_estimator) + + varg_est = VargEstimator() + assert_raises(RuntimeError, clone, varg_est) + def test_clone_empty_array(): """Regression test for cloning estimators with empty arrays""" @@ -110,6 +149,9 @@ def test_repr(): "T(a=K(c=None, d=None), b=K(c=None, d=None))" ) + some_est = T(a=["long_params"] * 1000) + assert_equal(len(repr(some_est)), 415) + def test_str(): """Smoke test the str of the base estimator""" @@ -128,6 +170,19 @@ def test_get_params(): assert_raises(ValueError, test.set_params, a__a=2) +def test_get_params_deprecated(): + # deprecated attribute should not show up as params + est = DeprecatedAttributeEstimator(a=1) + + assert_true('a' in est.get_params()) + assert_true('a' in est.get_params(deep=True)) + assert_true('a' in est.get_params(deep=False)) + + assert_true('b' not in est.get_params()) + assert_true('b' not in est.get_params(deep=True)) + assert_true('b' not in est.get_params(deep=False)) + + def test_is_classifier(): svc = SVC() assert_true(is_classifier(svc)) @@ -135,3 +190,41 @@ def test_is_classifier(): assert_true(is_classifier(Pipeline([('svc', svc)]))) assert_true(is_classifier(Pipeline([('svc_cv', GridSearchCV(svc, {'C': [0.1, 1]}))]))) + + +def test_set_params(): + # test nested estimator parameter setting + clf = Pipeline([("svc", SVC())]) + # non-existing parameter in svc + assert_raises(ValueError, clf.set_params, svc__stupid_param=True) + # non-existing parameter of pipeline + assert_raises(ValueError, clf.set_params, svm__stupid_param=True) + # we don't currently catch if the things in pipeline are estimators + #bad_pipeline = Pipeline([("bad", NoEstimator())]) + #assert_raises(AttributeError, bad_pipeline.set_params, + # bad__stupid_param=True) + + +def test_score_sample_weight(): + from sklearn.tree import DecisionTreeClassifier + from sklearn.tree import DecisionTreeRegressor + from sklearn import datasets + + rng = np.random.RandomState(0) + + # test both ClassifierMixin and RegressorMixin + estimators = [DecisionTreeClassifier(max_depth=2), + DecisionTreeRegressor(max_depth=2)] + sets = [datasets.load_iris(), + datasets.load_boston()] + + for est, ds in zip(estimators, sets): + est.fit(ds.data, ds.target) + # generate random sample weights + sample_weight = rng.randint(1, 10, size=len(ds.target)) + # check that the score with and without sample weights are different + assert_not_equal(est.score(ds.data, ds.target), + est.score(ds.data, ds.target, + sample_weight=sample_weight), + msg="Unweighted and weighted scores " + "are unexpectedly equal") diff --git a/sklearn/tests/test_calibration.py b/sklearn/tests/test_calibration.py new file mode 100644 index 0000000000000..09093011ea154 --- /dev/null +++ b/sklearn/tests/test_calibration.py @@ -0,0 +1,265 @@ +# Authors: Alexandre Gramfort +# License: BSD 3 clause + +import numpy as np +from scipy import sparse + +from sklearn.utils.testing import (assert_array_almost_equal, assert_equal, + assert_greater, assert_almost_equal, + assert_greater_equal, + assert_array_equal, + assert_raises, + assert_warns_message) +from sklearn.datasets import make_classification, make_blobs +from sklearn.naive_bayes import MultinomialNB +from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor +from sklearn.svm import LinearSVC +from sklearn.linear_model import Ridge +from sklearn.metrics import brier_score_loss, log_loss +from sklearn.calibration import CalibratedClassifierCV +from sklearn.calibration import _sigmoid_calibration, _SigmoidCalibration +from sklearn.calibration import calibration_curve + + +def test_calibration(): + """Test calibration objects with isotonic and sigmoid""" + n_samples = 100 + X, y = make_classification(n_samples=2 * n_samples, n_features=6, + random_state=42) + sample_weight = np.random.RandomState(seed=42).uniform(size=y.size) + + X -= X.min() # MultinomialNB only allows positive X + + # split train and test + X_train, y_train, sw_train = \ + X[:n_samples], y[:n_samples], sample_weight[:n_samples] + X_test, y_test = X[n_samples:], y[n_samples:] + + # Naive-Bayes + clf = MultinomialNB().fit(X_train, y_train, sample_weight=sw_train) + prob_pos_clf = clf.predict_proba(X_test)[:, 1] + + pc_clf = CalibratedClassifierCV(clf, cv=y.size + 1) + assert_raises(ValueError, pc_clf.fit, X, y) + + # Naive Bayes with calibration + for this_X_train, this_X_test in [(X_train, X_test), + (sparse.csr_matrix(X_train), + sparse.csr_matrix(X_test))]: + for method in ['isotonic', 'sigmoid']: + pc_clf = CalibratedClassifierCV(clf, method=method, cv=2) + # Note that this fit overwrites the fit on the entire training + # set + pc_clf.fit(this_X_train, y_train, sample_weight=sw_train) + prob_pos_pc_clf = pc_clf.predict_proba(this_X_test)[:, 1] + + # Check that brier score has improved after calibration + assert_greater(brier_score_loss(y_test, prob_pos_clf), + brier_score_loss(y_test, prob_pos_pc_clf)) + + # Check invariance against relabeling [0, 1] -> [1, 2] + pc_clf.fit(this_X_train, y_train + 1, sample_weight=sw_train) + prob_pos_pc_clf_relabeled = pc_clf.predict_proba(this_X_test)[:, 1] + assert_array_almost_equal(prob_pos_pc_clf, + prob_pos_pc_clf_relabeled) + + # Check invariance against relabeling [0, 1] -> [-1, 1] + pc_clf.fit(this_X_train, 2 * y_train - 1, sample_weight=sw_train) + prob_pos_pc_clf_relabeled = pc_clf.predict_proba(this_X_test)[:, 1] + assert_array_almost_equal(prob_pos_pc_clf, + prob_pos_pc_clf_relabeled) + + # Check invariance against relabeling [0, 1] -> [1, 0] + pc_clf.fit(this_X_train, (y_train + 1) % 2, + sample_weight=sw_train) + prob_pos_pc_clf_relabeled = \ + pc_clf.predict_proba(this_X_test)[:, 1] + if method == "sigmoid": + assert_array_almost_equal(prob_pos_pc_clf, + 1 - prob_pos_pc_clf_relabeled) + else: + # Isotonic calibration is not invariant against relabeling + # but should improve in both cases + assert_greater(brier_score_loss(y_test, prob_pos_clf), + brier_score_loss((y_test + 1) % 2, + prob_pos_pc_clf_relabeled)) + + # check that calibration can also deal with regressors that have + # a decision_function + clf_base_regressor = CalibratedClassifierCV(Ridge()) + clf_base_regressor.fit(X_train, y_train) + clf_base_regressor.predict(X_test) + + # Check failure cases: + # only "isotonic" and "sigmoid" should be accepted as methods + clf_invalid_method = CalibratedClassifierCV(clf, method="foo") + assert_raises(ValueError, clf_invalid_method.fit, X_train, y_train) + + # base-estimators should provide either decision_function or + # predict_proba (most regressors, for instance, should fail) + clf_base_regressor = \ + CalibratedClassifierCV(RandomForestRegressor(), method="sigmoid") + assert_raises(RuntimeError, clf_base_regressor.fit, X_train, y_train) + + +def test_sample_weight_warning(): + n_samples = 100 + X, y = make_classification(n_samples=2 * n_samples, n_features=6, + random_state=42) + + sample_weight = np.random.RandomState(seed=42).uniform(size=len(y)) + X_train, y_train, sw_train = \ + X[:n_samples], y[:n_samples], sample_weight[:n_samples] + X_test = X[n_samples:] + + for method in ['sigmoid', 'isotonic']: + base_estimator = LinearSVC(random_state=42) + calibrated_clf = CalibratedClassifierCV(base_estimator, method=method) + # LinearSVC does not currently support sample weights but they + # can still be used for the calibration step (with a warning) + msg = "LinearSVC does not support sample_weight." + assert_warns_message( + UserWarning, msg, + calibrated_clf.fit, X_train, y_train, sample_weight=sw_train) + probs_with_sw = calibrated_clf.predict_proba(X_test) + + # As the weights are used for the calibration, they should still yield + # a different predictions + calibrated_clf.fit(X_train, y_train) + probs_without_sw = calibrated_clf.predict_proba(X_test) + + diff = np.linalg.norm(probs_with_sw - probs_without_sw) + assert_greater(diff, 0.1) + + +def test_calibration_multiclass(): + """Test calibration for multiclass """ + # test multi-class setting with classifier that implements + # only decision function + clf = LinearSVC() + X, y_idx = make_blobs(n_samples=100, n_features=2, random_state=42, + centers=3, cluster_std=3.0) + + # Use categorical labels to check that CalibratedClassifierCV supports + # them correctly + target_names = np.array(['a', 'b', 'c']) + y = target_names[y_idx] + + X_train, y_train = X[::2], y[::2] + X_test, y_test = X[1::2], y[1::2] + + clf.fit(X_train, y_train) + for method in ['isotonic', 'sigmoid']: + cal_clf = CalibratedClassifierCV(clf, method=method, cv=2) + cal_clf.fit(X_train, y_train) + probas = cal_clf.predict_proba(X_test) + assert_array_almost_equal(np.sum(probas, axis=1), np.ones(len(X_test))) + + # Check that log-loss of calibrated classifier is smaller than + # log-loss of naively turned OvR decision function to probabilities + # via softmax + def softmax(y_pred): + e = np.exp(-y_pred) + return e / e.sum(axis=1).reshape(-1, 1) + uncalibrated_log_loss = \ + log_loss(y_test, softmax(clf.decision_function(X_test))) + calibrated_log_loss = log_loss(y_test, probas) + assert_greater_equal(uncalibrated_log_loss, calibrated_log_loss) + + # Test that calibration of a multiclass classifier decreases log-loss + # for RandomForestClassifier + X, y = make_blobs(n_samples=100, n_features=2, random_state=42, + cluster_std=3.0) + X_train, y_train = X[::2], y[::2] + X_test, y_test = X[1::2], y[1::2] + + clf = RandomForestClassifier(n_estimators=10, random_state=42) + clf.fit(X_train, y_train) + clf_probs = clf.predict_proba(X_test) + loss = log_loss(y_test, clf_probs) + + for method in ['isotonic', 'sigmoid']: + cal_clf = CalibratedClassifierCV(clf, method=method, cv=3) + cal_clf.fit(X_train, y_train) + cal_clf_probs = cal_clf.predict_proba(X_test) + cal_loss = log_loss(y_test, cal_clf_probs) + assert_greater(loss, cal_loss) + + +def test_calibration_prefit(): + """Test calibration for prefitted classifiers""" + n_samples = 50 + X, y = make_classification(n_samples=3 * n_samples, n_features=6, + random_state=42) + sample_weight = np.random.RandomState(seed=42).uniform(size=y.size) + + X -= X.min() # MultinomialNB only allows positive X + + # split train and test + X_train, y_train, sw_train = \ + X[:n_samples], y[:n_samples], sample_weight[:n_samples] + X_calib, y_calib, sw_calib = \ + X[n_samples:2 * n_samples], y[n_samples:2 * n_samples], \ + sample_weight[n_samples:2 * n_samples] + X_test, y_test = X[2 * n_samples:], y[2 * n_samples:] + + # Naive-Bayes + clf = MultinomialNB() + clf.fit(X_train, y_train, sw_train) + prob_pos_clf = clf.predict_proba(X_test)[:, 1] + + # Naive Bayes with calibration + for this_X_calib, this_X_test in [(X_calib, X_test), + (sparse.csr_matrix(X_calib), + sparse.csr_matrix(X_test))]: + for method in ['isotonic', 'sigmoid']: + pc_clf = CalibratedClassifierCV(clf, method=method, cv="prefit") + + for sw in [sw_calib, None]: + pc_clf.fit(this_X_calib, y_calib, sample_weight=sw) + y_prob = pc_clf.predict_proba(this_X_test) + y_pred = pc_clf.predict(this_X_test) + prob_pos_pc_clf = y_prob[:, 1] + assert_array_equal(y_pred, + np.array([0, 1])[np.argmax(y_prob, axis=1)]) + + assert_greater(brier_score_loss(y_test, prob_pos_clf), + brier_score_loss(y_test, prob_pos_pc_clf)) + + +def test_sigmoid_calibration(): + """Test calibration values with Platt sigmoid model""" + exF = np.array([5, -4, 1.0]) + exY = np.array([1, -1, -1]) + # computed from my python port of the C++ code in LibSVM + AB_lin_libsvm = np.array([-0.20261354391187855, 0.65236314980010512]) + assert_array_almost_equal(AB_lin_libsvm, + _sigmoid_calibration(exF, exY), 3) + lin_prob = 1. / (1. + np.exp(AB_lin_libsvm[0] * exF + AB_lin_libsvm[1])) + sk_prob = _SigmoidCalibration().fit(exF, exY).predict(exF) + assert_array_almost_equal(lin_prob, sk_prob, 6) + + # check that _SigmoidCalibration().fit only accepts 1d array or 2d column + # arrays + assert_raises(ValueError, _SigmoidCalibration().fit, + np.vstack((exF, exF)), exY) + + +def test_calibration_curve(): + """Check calibration_curve function""" + y_true = np.array([0, 0, 0, 1, 1, 1]) + y_pred = np.array([0., 0.1, 0.2, 0.8, 0.9, 1.]) + prob_true, prob_pred = calibration_curve(y_true, y_pred, n_bins=2) + prob_true_unnormalized, prob_pred_unnormalized = \ + calibration_curve(y_true, y_pred * 2, n_bins=2, normalize=True) + assert_equal(len(prob_true), len(prob_pred)) + assert_equal(len(prob_true), 2) + assert_almost_equal(prob_true, [0, 1]) + assert_almost_equal(prob_pred, [0.1, 0.9]) + assert_almost_equal(prob_true, prob_true_unnormalized) + assert_almost_equal(prob_pred, prob_pred_unnormalized) + + # probabilities outside [0, 1] should not be accepted when normalize + # is set to False + assert_raises(ValueError, calibration_curve, [1.1], [-0.1], + normalize=False) diff --git a/sklearn/tests/test_check_build.py b/sklearn/tests/test_check_build.py index 114b2064148fa..4f38629a745a1 100644 --- a/sklearn/tests/test_check_build.py +++ b/sklearn/tests/test_check_build.py @@ -1,14 +1,13 @@ """ Smoke Test the check_build module """ -# This # Author: G Varoquaux -# License: BSD style +# Licence: BSD 3 clause from sklearn.__check_build import raise_build_error -from nose.tools import assert_raises +from sklearn.utils.testing import assert_raises def test_raise_build_error(): diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index 80a87b8e46a55..043206323ff7d 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -1,487 +1,203 @@ """ General tests for all estimators in sklearn. """ + +# Authors: Andreas Mueller +# Gael Varoquaux gael.varoquaux@normalesup.org +# License: BSD 3 clause +from __future__ import print_function + import os import warnings import sys -import traceback - -import numpy as np -from scipy import sparse -from nose.tools import assert_raises, assert_equal, assert_true -from numpy.testing import assert_array_equal, \ - assert_array_almost_equal +import pkgutil -import sklearn +from sklearn.externals.six import PY3 +from sklearn.externals.six.moves import zip +from sklearn.utils.testing import assert_false, clean_warning_registry from sklearn.utils.testing import all_estimators from sklearn.utils.testing import assert_greater -from sklearn.base import clone, ClassifierMixin, RegressorMixin, \ - TransformerMixin, ClusterMixin -from sklearn.utils import shuffle -from sklearn.preprocessing import StandardScaler, Scaler -#from sklearn.cross_validation import train_test_split -from sklearn.datasets import load_iris, load_boston, make_blobs -from sklearn.metrics import zero_one_score, adjusted_rand_score -from sklearn.lda import LDA -from sklearn.svm.base import BaseLibSVM - -# import "special" estimators -from sklearn.grid_search import GridSearchCV -from sklearn.decomposition import SparseCoder -from sklearn.pipeline import Pipeline -from sklearn.pls import _PLS, PLSCanonical, PLSRegression, CCA, PLSSVD -from sklearn.ensemble import BaseEnsemble -from sklearn.multiclass import OneVsOneClassifier, OneVsRestClassifier,\ - OutputCodeClassifier -from sklearn.feature_selection import RFE, RFECV, SelectKBest -from sklearn.naive_bayes import MultinomialNB, BernoulliNB -from sklearn.covariance import EllipticEnvelope, EllipticEnvelop -from sklearn.feature_extraction import DictVectorizer -from sklearn.feature_extraction.text import TfidfTransformer -from sklearn.kernel_approximation import AdditiveChi2Sampler -from sklearn.preprocessing import LabelBinarizer, LabelEncoder, Binarizer, \ - Normalizer -from sklearn.cluster import WardAgglomeration, AffinityPropagation, \ - SpectralClustering -from sklearn.linear_model import IsotonicRegression - -dont_test = [Pipeline, GridSearchCV, SparseCoder, EllipticEnvelope, - EllipticEnvelop, DictVectorizer, LabelBinarizer, LabelEncoder, - TfidfTransformer, IsotonicRegression] -meta_estimators = [BaseEnsemble, OneVsOneClassifier, OutputCodeClassifier, - OneVsRestClassifier, RFE, RFECV] +from sklearn.utils.testing import assert_in +from sklearn.utils.testing import SkipTest +from sklearn.utils.testing import ignore_warnings + +import sklearn +from sklearn.preprocessing import StandardScaler +from sklearn.datasets import make_classification +from sklearn.cluster.bicluster import BiclusterMixin + +from sklearn.cross_validation import train_test_split +from sklearn.linear_model.base import LinearClassifierMixin +from sklearn.utils.estimator_checks import ( + check_dtype_object, + check_parameters_default_constructible, + check_estimator_sparse_data, + check_estimators_dtypes, + check_transformer, + check_clustering, + check_clusterer_compute_labels_predict, + check_regressors_int, + check_regressors_train, + check_regressors_pickle, + check_transformer_pickle, + check_transformers_unfitted, + check_estimators_empty_data_messages, + check_estimators_nan_inf, + check_estimators_unfitted, + check_classifiers_one_label, + check_classifiers_train, + check_classifiers_classes, + check_classifiers_input_shapes, + check_classifiers_pickle, + check_class_weight_classifiers, + check_class_weight_auto_classifiers, + check_class_weight_auto_linear_classifier, + check_estimators_overwrite_params, + check_estimators_partial_fit_n_features, + check_sparsify_coefficients, + check_classifier_data_not_an_array, + check_regressor_data_not_an_array, + check_transformer_data_not_an_array, + check_transformer_n_iter, + check_fit_score_takes_y, + check_non_transformer_estimators_n_iter, + check_pipeline_consistency, + CROSS_DECOMPOSITION) + + +def test_all_estimator_no_base_class(): + # test that all_estimators doesn't find abstract classes. + for name, Estimator in all_estimators(): + msg = ("Base estimators such as {0} should not be included" + " in all_estimators").format(name) + assert_false(name.lower().startswith('base'), msg=msg) def test_all_estimators(): # Test that estimators are default-constructible, clonable # and have working repr. - estimators = all_estimators() - clf = LDA() + estimators = all_estimators(include_meta_estimators=True) - for name, E in estimators: + # Meta sanity-check to make sure that the estimator introspection runs + # properly + assert_greater(len(estimators), 0) + + for name, Estimator in estimators: # some can just not be sensibly default constructed - if E in dont_test: - continue - # test default-constructibility - # get rid of deprecation warnings - with warnings.catch_warnings(record=True): - if E in meta_estimators: - e = E(clf) - else: - e = E() - #test cloning - clone(e) - # test __repr__ - repr(e) - - -def test_estimators_sparse_data(): - # All estimators should either deal with sparse data, or raise an - # intelligible error message - rng = np.random.RandomState(0) - X = rng.rand(40, 10) - X[X < .8] = 0 - X = sparse.csr_matrix(X) - y = (4 * rng.rand(40)).astype(np.int) + yield check_parameters_default_constructible, name, Estimator + + +def test_non_meta_estimators(): + # input validation etc for non-meta estimators estimators = all_estimators() - estimators = [(name, E) for name, E in estimators - if issubclass(E, (ClassifierMixin, RegressorMixin))] - for name, Clf in estimators: - if Clf in dont_test or Clf in meta_estimators: + for name, Estimator in estimators: + if issubclass(Estimator, BiclusterMixin): + continue + if name.endswith("HMM") or name.startswith("_"): continue - # catch deprecation warnings - with warnings.catch_warnings(record=True): - clf = Clf() - # fit - try: - clf.fit(X, y) - except TypeError, e: - if not 'sparse' in repr(e): - print ("Estimator %s doesn't seem to fail gracefully on " - "sparse data" % name) - traceback.print_exc(file=sys.stdout) - raise e - except Exception, exc: - print ("Estimator %s doesn't seem to fail gracefully on " - "sparse data" % name) - traceback.print_exc(file=sys.stdout) - raise exc + if name not in CROSS_DECOMPOSITION: + yield check_estimators_dtypes, name, Estimator + yield check_fit_score_takes_y, name, Estimator + yield check_dtype_object, name, Estimator + + # Check that all estimator yield informative messages when + # trained on empty datasets + yield check_estimators_empty_data_messages, name, Estimator + + if name not in CROSS_DECOMPOSITION + ['SpectralEmbedding']: + # SpectralEmbedding is non-deterministic, + # see issue #4236 + yield check_pipeline_consistency, name, Estimator + + if name not in CROSS_DECOMPOSITION + ['Imputer']: + # Test that all estimators check their input for NaN's and infs + yield check_estimators_nan_inf, name, Estimator + + if name not in CROSS_DECOMPOSITION + ['GaussianProcess']: + # FIXME! + # in particular GaussianProcess! + yield check_estimators_overwrite_params, name, Estimator + if hasattr(Estimator, 'sparsify'): + yield check_sparsify_coefficients, name, Estimator + + yield check_estimator_sparse_data, name, Estimator def test_transformers(): # test if transformers do something sensible on training set # also test all shapes / shape errors - estimators = all_estimators() - transformers = [(name, E) for name, E in estimators if issubclass(E, - TransformerMixin)] - X, y = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], - random_state=0, n_features=2, cluster_std=0.1) - n_samples, n_features = X.shape - X = StandardScaler().fit_transform(X) - X -= X.min() - - succeeded = True - - for name, Trans in transformers: - if Trans in dont_test or Trans in meta_estimators: - continue - # these don't actually fit the data: - if Trans in [AdditiveChi2Sampler, Binarizer, Normalizer]: - continue - # catch deprecation warnings - with warnings.catch_warnings(record=True): - trans = Trans() - - if hasattr(trans, 'compute_importances'): - trans.compute_importances = True - - if Trans is SelectKBest: - # SelectKBest has a default of k=10 - # which is more feature than we have. - trans.k = 1 - - # fit - - if Trans in (_PLS, PLSCanonical, PLSRegression, CCA, PLSSVD): - y_ = np.vstack([y, 2 * y + np.random.randint(2, size=len(y))]) - y_ = y_.T - else: - y_ = y - - try: - trans.fit(X, y_) - X_pred = trans.fit_transform(X, y=y_) - if isinstance(X_pred, tuple): - for x_pred in X_pred: - assert_equal(x_pred.shape[0], n_samples) - else: - assert_equal(X_pred.shape[0], n_samples) - except Exception as e: - print trans - print e - print - succeeded = False - - if hasattr(trans, 'transform'): - if Trans in (_PLS, PLSCanonical, PLSRegression, CCA, PLSSVD): - X_pred2 = trans.transform(X, y_) - else: - X_pred2 = trans.transform(X) - if isinstance(X_pred, tuple) and isinstance(X_pred2, tuple): - for x_pred, x_pred2 in zip(X_pred, X_pred2): - assert_array_almost_equal(x_pred, x_pred2, 2, - "fit_transform not correct in %s" % Trans) - else: - assert_array_almost_equal(X_pred, X_pred2, 2, - "fit_transform not correct in %s" % Trans) - - # raises error on malformed input for transform - assert_raises(ValueError, trans.transform, X.T) - assert_true(succeeded) - - -def test_transformers_sparse_data(): - # All estimators should either deal with sparse data, or raise an - # intelligible error message - rng = np.random.RandomState(0) - X = rng.rand(40, 10) - X[X < .8] = 0 - X = sparse.csr_matrix(X) - y = (4 * rng.rand(40)).astype(np.int) - estimators = all_estimators() - estimators = [(name, E) for name, E in estimators - if issubclass(E, TransformerMixin)] - for name, Trans in estimators: - if Trans in dont_test or Trans in meta_estimators: - continue - # catch deprecation warnings - with warnings.catch_warnings(record=True): - if Trans in [Scaler, StandardScaler]: - trans = Trans(with_mean=False) - else: - trans = Trans() - # fit - try: - trans.fit(X, y) - except TypeError, e: - if not 'sparse' in repr(e): - print ("Estimator %s doesn't seem to fail gracefully on " - "sparse data" % name) - traceback.print_exc(file=sys.stdout) - raise e - except Exception, exc: - print ("Estimator %s doesn't seem to fail gracefully on " - "sparse data" % name) - traceback.print_exc(file=sys.stdout) - raise exc - - -def test_classifiers_one_label(): - # test classifiers trained on a single label always return this label - # or raise an sensible error message - rnd = np.random.RandomState(0) - X_train = rnd.uniform(size=(10, 3)) - X_test = rnd.uniform(size=(10, 3)) - y = np.ones(10) - estimators = all_estimators() - classifiers = [(name, E) for name, E in estimators if issubclass(E, - ClassifierMixin)] - error_string_fit = "Classifier can't train when only one class is present." - error_string_predict = ("Classifier can't predict when only one class is " - "present.") - for name, Clf in classifiers: - if Clf in dont_test or Clf in meta_estimators: - continue - # catch deprecation warnings - with warnings.catch_warnings(record=True): - clf = Clf() - # try to fit - try: - clf.fit(X_train, y) - except ValueError, e: - if not 'class' in repr(e): - print(error_string_fit, Clf, e) - traceback.print_exc(file=sys.stdout) - raise e - else: - continue - except Exception, exc: - print(error_string_fit, Clf, exc) - traceback.print_exc(file=sys.stdout) - raise exc - # predict - try: - assert_array_equal(clf.predict(X_test), y) - except Exception, exc: - print(error_string_predict, Clf, exc) - traceback.print_exc(file=sys.stdout) + transformers = all_estimators(type_filter='transformer') + for name, Transformer in transformers: + # All transformers should either deal with sparse data or raise an + # exception with type TypeError and an intelligible error message + yield check_transformer_pickle, name, Transformer + if name not in ['AdditiveChi2Sampler', 'Binarizer', 'Normalizer', + 'PLSCanonical', 'PLSRegression', 'CCA', 'PLSSVD']: + yield check_transformer_data_not_an_array, name, Transformer + # these don't actually fit the data, so don't raise errors + if name not in ['AdditiveChi2Sampler', 'Binarizer', 'Normalizer']: + # basic tests + yield check_transformer, name, Transformer + yield check_transformers_unfitted, name, Transformer def test_clustering(): # test if clustering algorithms do something sensible # also test all shapes / shape errors - estimators = all_estimators() - clustering = [(name, E) for name, E in estimators if issubclass(E, - ClusterMixin)] - iris = load_iris() - X, y = iris.data, iris.target - X, y = shuffle(X, y, random_state=7) - n_samples, n_features = X.shape - X = StandardScaler().fit_transform(X) + clustering = all_estimators(type_filter='cluster') for name, Alg in clustering: - if Alg is WardAgglomeration: + # test whether any classifier overwrites his init parameters during fit + yield check_clusterer_compute_labels_predict, name, Alg + if name not in ('WardAgglomeration', "FeatureAgglomeration"): # this is clustering on the features # let's not test that here. - continue - # catch deprecation and neighbors warnings - with warnings.catch_warnings(record=True): - alg = Alg() - if hasattr(alg, "n_clusters"): - alg.set_params(n_clusters=3) - if hasattr(alg, "random_state"): - alg.set_params(random_state=1) - if Alg is AffinityPropagation: - alg.set_params(preference=-100) - # fit - alg.fit(X) - - assert_equal(alg.labels_.shape, (n_samples,)) - pred = alg.labels_ - assert_greater(adjusted_rand_score(pred, y), 0.4) - # fit another time with ``fit_predict`` and compare results - if Alg is SpectralClustering: - # there is no way to make Spectral clustering deterministic :( - continue - if hasattr(alg, "random_state"): - alg.set_params(random_state=1) - with warnings.catch_warnings(record=True): - pred2 = alg.fit_predict(X) - assert_array_equal(pred, pred2) + yield check_clustering, name, Alg + yield check_estimators_partial_fit_n_features, name, Alg -def test_classifiers_train(): - # test if classifiers do something sensible on training set - # also test all shapes / shape errors - estimators = all_estimators() - classifiers = [(name, E) for name, E in estimators if issubclass(E, - ClassifierMixin)] - iris = load_iris() - X_m, y_m = iris.data, iris.target - X_m, y_m = shuffle(X_m, y_m, random_state=7) - X_m = StandardScaler().fit_transform(X_m) - # generate binary problem from multi-class one - y_b = y_m[y_m != 2] - X_b = X_m[y_m != 2] - for (X, y) in [(X_m, y_m), (X_b, y_b)]: - # do it once with binary, once with multiclass - n_labels = len(np.unique(y)) - n_samples, n_features = X.shape - for name, Clf in classifiers: - if Clf in dont_test or Clf in meta_estimators: - continue - if Clf in [MultinomialNB, BernoulliNB]: - # TODO also test these! - continue - # catch deprecation warnings - with warnings.catch_warnings(record=True): - clf = Clf() - # raises error on malformed input for fit - assert_raises(ValueError, clf.fit, X, y[:-1]) - - # fit - clf.fit(X, y) - y_pred = clf.predict(X) - assert_equal(y_pred.shape, (n_samples,)) - # training set performance - assert_greater(zero_one_score(y, y_pred), 0.78) - - # raises error on malformed input for predict - assert_raises(ValueError, clf.predict, X.T) - if hasattr(clf, "decision_function"): - try: - # decision_function agrees with predict: - decision = clf.decision_function(X) - if n_labels is 2: - assert_equal(decision.ravel().shape, (n_samples,)) - dec_pred = (decision.ravel() > 0).astype(np.int) - assert_array_equal(dec_pred, y_pred) - if n_labels is 3 and not isinstance(clf, BaseLibSVM): - # 1on1 of LibSVM works differently - assert_equal(decision.shape, (n_samples, n_labels)) - assert_array_equal(np.argmax(decision, axis=1), y_pred) - - # raises error on malformed input - assert_raises(ValueError, clf.decision_function, X.T) - # raises error on malformed input for decision_function - assert_raises(ValueError, clf.decision_function, X.T) - except NotImplementedError: - pass - if hasattr(clf, "predict_proba"): - try: - # predict_proba agrees with predict: - y_prob = clf.predict_proba(X) - assert_equal(y_prob.shape, (n_samples, n_labels)) - # raises error on malformed input - assert_raises(ValueError, clf.predict_proba, X.T) - assert_array_equal(np.argmax(y_prob, axis=1), y_pred) - # raises error on malformed input for predict_proba - assert_raises(ValueError, clf.predict_proba, X.T) - except NotImplementedError: - pass - - -def test_classifiers_classes(): +def test_classifiers(): # test if classifiers can cope with non-consecutive classes - estimators = all_estimators() - classifiers = [(name, E) for name, E in estimators if issubclass(E, - ClassifierMixin)] - iris = load_iris() - X, y = iris.data, iris.target - X, y = shuffle(X, y, random_state=7) - X = StandardScaler().fit_transform(X) - y = 2 * y + 1 - # TODO: make work with next line :) - #y = y.astype(np.str) - for name, Clf in classifiers: - if Clf in dont_test or Clf in meta_estimators: - continue - if Clf in [MultinomialNB, BernoulliNB]: - # TODO also test these! - continue - - # catch deprecation warnings - with warnings.catch_warnings(record=True): - clf = Clf() - # fit - clf.fit(X, y) - y_pred = clf.predict(X) - # training set performance - assert_array_equal(np.unique(y), np.unique(y_pred)) - assert_greater(zero_one_score(y, y_pred), 0.78) - - -def test_regressors_int(): - # test if regressors can cope with integer labels (by converting them to - # float) - estimators = all_estimators() - regressors = [(name, E) for name, E in estimators if issubclass(E, - RegressorMixin)] - boston = load_boston() - X, y = boston.data, boston.target - X, y = shuffle(X, y, random_state=0) - X = StandardScaler().fit_transform(X) - y = np.random.randint(2, size=X.shape[0]) - for name, Reg in regressors: - if Reg in dont_test or Reg in meta_estimators or Reg in (CCA,): - continue - # catch deprecation warnings - with warnings.catch_warnings(record=True): - # separate estimators to control random seeds - reg1 = Reg() - reg2 = Reg() - if hasattr(reg1, 'alpha'): - reg1.set_params(alpha=0.01) - reg2.set_params(alpha=0.01) - if hasattr(reg1, 'random_state'): - reg1.set_params(random_state=0) - reg2.set_params(random_state=0) - - if Reg in (_PLS, PLSCanonical, PLSRegression): - y_ = np.vstack([y, 2 * y + np.random.randint(2, size=len(y))]) - y_ = y_.T - else: - y_ = y - - # fit - reg1.fit(X, y_) - pred1 = reg1.predict(X) - reg2.fit(X, y_.astype(np.float)) - pred2 = reg2.predict(X) - assert_array_almost_equal(pred1, pred2, 2, name) - - -def test_regressors_train(): - estimators = all_estimators() - regressors = [(name, E) for name, E in estimators if issubclass(E, - RegressorMixin)] - boston = load_boston() - X, y = boston.data, boston.target - X, y = shuffle(X, y, random_state=0) + classifiers = all_estimators(type_filter='classifier') + for name, Classifier in classifiers: + # test classfiers can handle non-array data + yield check_classifier_data_not_an_array, name, Classifier + # test classifiers trained on a single label always return this label + yield check_classifiers_one_label, name, Classifier + yield check_classifiers_classes, name, Classifier + yield check_classifiers_pickle, name, Classifier + yield check_estimators_partial_fit_n_features, name, Classifier + # basic consistency testing + yield check_classifiers_train, name, Classifier + if (name not in ["MultinomialNB", "LabelPropagation", "LabelSpreading"] + # TODO some complication with -1 label + and name not in ["DecisionTreeClassifier", + "ExtraTreeClassifier"]): + # We don't raise a warning in these classifiers, as + # the column y interface is used by the forests. + + # test if classifiers can cope with y.shape = (n_samples, 1) + yield check_classifiers_input_shapes, name, Classifier + # test if NotFittedError is raised + yield check_estimators_unfitted, name, Classifier + + +def test_regressors(): + regressors = all_estimators(type_filter='regressor') # TODO: test with intercept # TODO: test with multiple responses - X = StandardScaler().fit_transform(X) - y = StandardScaler().fit_transform(y) - succeeded = True - for name, Reg in regressors: - if Reg in dont_test or Reg in meta_estimators: - continue - # catch deprecation warnings - with warnings.catch_warnings(record=True): - reg = Reg() - if hasattr(reg, 'alpha'): - reg.set_params(alpha=0.01) - - # raises error on malformed input for fit - assert_raises(ValueError, reg.fit, X, y[:-1]) - # fit - try: - if Reg in (_PLS, PLSCanonical, PLSRegression, CCA): - y_ = np.vstack([y, 2 * y + np.random.randint(2, size=len(y))]) - y_ = y_.T - else: - y_ = y - reg.fit(X, y_) - reg.predict(X) - - if Reg not in (PLSCanonical, CCA): # TODO: find out why - assert_greater(reg.score(X, y_), 0.5) - except Exception as e: - print(reg) - print e - print - succeeded = False - - assert_true(succeeded) + for name, Regressor in regressors: + # basic testing + yield check_regressors_train, name, Regressor + yield check_regressor_data_not_an_array, name, Regressor + yield check_estimators_partial_fit_n_features, name, Regressor + # Test that estimators can be pickled, and once pickled + # give the same answer as before. + yield check_regressors_pickle, name, Regressor + if name != 'CCA': + # check that the regressor handles int input + yield check_regressors_int, name, Regressor + # Test if NotFittedError is raised + yield check_estimators_unfitted, name, Regressor def test_configure(): @@ -496,11 +212,168 @@ def test_configure(): os.chdir(setup_path) old_argv = sys.argv sys.argv = ['setup.py', 'config'] + clean_warning_registry() with warnings.catch_warnings(): # The configuration spits out warnings when not finding # Blas/Atlas development headers - warnings.simplefilter('ignore', UserWarning) - execfile('setup.py', dict(__name__='__main__')) + warnings.simplefilter('ignore', UserWarning) + if PY3: + with open('setup.py') as f: + exec(f.read(), dict(__name__='__main__')) + else: + execfile('setup.py', dict(__name__='__main__')) finally: sys.argv = old_argv os.chdir(cwd) + + +def test_class_weight_classifiers(): + # test that class_weight works and that the semantics are consistent + classifiers = all_estimators(type_filter='classifier') + + clean_warning_registry() + with warnings.catch_warnings(record=True): + classifiers = [c for c in classifiers + if 'class_weight' in c[1]().get_params().keys()] + + for name, Classifier in classifiers: + if name == "NuSVC": + # the sparse version has a parameter that doesn't do anything + continue + if name.endswith("NB"): + # NaiveBayes classifiers have a somewhat different interface. + # FIXME SOON! + continue + yield check_class_weight_classifiers, name, Classifier + + +def test_class_weight_auto_classifiers(): + """Test that class_weight="auto" improves f1-score""" + + # This test is broken; its success depends on: + # * a rare fortuitous RNG seed for make_classification; and + # * the use of binary F1 over a seemingly arbitrary positive class for two + # datasets, and weighted average F1 for the third. + # Its expectations need to be clarified and reimplemented. + raise SkipTest('This test requires redefinition') + + classifiers = all_estimators(type_filter='classifier') + + clean_warning_registry() + with warnings.catch_warnings(record=True): + classifiers = [c for c in classifiers + if 'class_weight' in c[1]().get_params().keys()] + + for n_classes, weights in zip([2, 3], [[.8, .2], [.8, .1, .1]]): + # create unbalanced dataset + X, y = make_classification(n_classes=n_classes, n_samples=200, + n_features=10, weights=weights, + random_state=0, n_informative=n_classes) + X = StandardScaler().fit_transform(X) + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, + random_state=0) + for name, Classifier in classifiers: + if (name != "NuSVC" + # the sparse version has a parameter that doesn't do anything + and not name.startswith("RidgeClassifier") + # RidgeClassifier behaves unexpected + # FIXME! + and not name.endswith("NB")): + # NaiveBayes classifiers have a somewhat different interface. + # FIXME SOON! + yield (check_class_weight_auto_classifiers, name, Classifier, + X_train, y_train, X_test, y_test, weights) + + +def test_class_weight_auto_linear_classifiers(): + classifiers = all_estimators(type_filter='classifier') + + clean_warning_registry() + with warnings.catch_warnings(record=True): + linear_classifiers = [ + (name, clazz) + for name, clazz in classifiers + if 'class_weight' in clazz().get_params().keys() + and issubclass(clazz, LinearClassifierMixin)] + + for name, Classifier in linear_classifiers: + if name == "LogisticRegressionCV": + # Contrary to RidgeClassifierCV, LogisticRegressionCV use actual + # CV folds and fit a model for each CV iteration before averaging + # the coef. Therefore it is expected to not behave exactly as the + # other linear model. + continue + yield check_class_weight_auto_linear_classifier, name, Classifier + + +@ignore_warnings +def test_import_all_consistency(): + # Smoke test to check that any name in a __all__ list is actually defined + # in the namespace of the module or package. + pkgs = pkgutil.walk_packages(path=sklearn.__path__, prefix='sklearn.', + onerror=lambda _: None) + submods = [modname for _, modname, _ in pkgs] + for modname in submods + ['sklearn']: + if ".tests." in modname: + continue + package = __import__(modname, fromlist="dummy") + for name in getattr(package, '__all__', ()): + if getattr(package, name, None) is None: + raise AttributeError( + "Module '{0}' has no attribute '{1}'".format( + modname, name)) + + +def test_root_import_all_completeness(): + EXCEPTIONS = ('utils', 'tests', 'base', 'setup') + for _, modname, _ in pkgutil.walk_packages(path=sklearn.__path__, + onerror=lambda _: None): + if '.' in modname or modname.startswith('_') or modname in EXCEPTIONS: + continue + assert_in(modname, sklearn.__all__) + + +def test_non_transformer_estimators_n_iter(): + # Test that all estimators of type which are non-transformer + # and which have an attribute of max_iter, return the attribute + # of n_iter atleast 1. + for est_type in ['regressor', 'classifier', 'cluster']: + regressors = all_estimators(type_filter=est_type) + for name, Estimator in regressors: + # LassoLars stops early for the default alpha=1.0 for + # the iris dataset. + if name == 'LassoLars': + estimator = Estimator(alpha=0.) + else: + estimator = Estimator() + if hasattr(estimator, "max_iter"): + # These models are dependent on external solvers like + # libsvm and accessing the iter parameter is non-trivial. + if name in (['Ridge', 'SVR', 'NuSVR', 'NuSVC', + 'RidgeClassifier', 'SVC', 'RandomizedLasso', + 'LogisticRegressionCV']): + continue + + # Tested in test_transformer_n_iter below + elif (name in CROSS_DECOMPOSITION or + name in ['LinearSVC', 'LogisticRegression']): + continue + + else: + # Multitask models related to ENet cannot handle + # if y is mono-output. + yield (check_non_transformer_estimators_n_iter, + name, estimator, 'Multi' in name) + + +def test_transformer_n_iter(): + transformers = all_estimators(type_filter='transformer') + for name, Estimator in transformers: + estimator = Estimator() + # Dependent on external solvers and hence accessing the iter + # param is non-trivial. + external_solver = ['Isomap', 'KernelPCA', 'LocallyLinearEmbedding', + 'RandomizedLasso', 'LogisticRegressionCV'] + + if hasattr(estimator, "max_iter") and name not in external_solver: + yield check_transformer_n_iter, name, estimator diff --git a/sklearn/tests/test_cross_validation.py b/sklearn/tests/test_cross_validation.py index 228b328468965..5dae0ebd0bc87 100644 --- a/sklearn/tests/test_cross_validation.py +++ b/sklearn/tests/test_cross_validation.py @@ -1,111 +1,368 @@ """Test the cross_validation module""" +from __future__ import division +import warnings import numpy as np from scipy.sparse import coo_matrix - -from nose.tools import assert_true, assert_equal -from nose.tools import assert_raises -from sklearn.utils.testing import assert_greater, assert_less -from sklearn.utils.fixes import unique +from scipy import stats + +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_not_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import assert_warns_message +from sklearn.utils.testing import ignore_warnings +from sklearn.utils.mocking import CheckingClassifier, MockDataFrame from sklearn import cross_validation as cval -from sklearn.base import BaseEstimator from sklearn.datasets import make_regression +from sklearn.datasets import load_boston +from sklearn.datasets import load_digits from sklearn.datasets import load_iris -from sklearn.metrics import zero_one_score -from sklearn.metrics import f1_score -from sklearn.metrics import mean_squared_error -from sklearn.metrics import r2_score from sklearn.metrics import explained_variance_score -from sklearn.svm import SVC +from sklearn.metrics import make_scorer +from sklearn.metrics import precision_score + +from sklearn.externals import six +from sklearn.externals.six.moves import zip + from sklearn.linear_model import Ridge -from sklearn.svm.sparse import SVC as SparseSVC +from sklearn.neighbors import KNeighborsClassifier +from sklearn.svm import SVC +from sklearn.cluster import KMeans -from numpy.testing import assert_array_almost_equal -from numpy.testing import assert_array_equal +from sklearn.preprocessing import Imputer, LabelBinarizer +from sklearn.pipeline import Pipeline -class MockClassifier(BaseEstimator): +class MockClassifier(object): """Dummy classifier to test the cross-validation""" - def __init__(self, a=0): + def __init__(self, a=0, allow_nd=False): self.a = a - - def fit(self, X, Y, sample_weight=None, class_prior=None): + self.allow_nd = allow_nd + + def fit(self, X, Y=None, sample_weight=None, class_prior=None, + sparse_sample_weight=None, sparse_param=None, dummy_int=None, + dummy_str=None, dummy_obj=None, callback=None): + """The dummy arguments are to test that this fit function can + accept non-array arguments through cross-validation, such as: + - int + - str (this is actually array-like) + - object + - function + """ + self.dummy_int = dummy_int + self.dummy_str = dummy_str + self.dummy_obj = dummy_obj + if callback is not None: + callback(self) + + if self.allow_nd: + X = X.reshape(len(X), -1) + if X.ndim >= 3 and not self.allow_nd: + raise ValueError('X cannot be d') if sample_weight is not None: assert_true(sample_weight.shape[0] == X.shape[0], - 'MockClassifier extra fit_param sample_weight.shape[0] is {0}, ' - 'should be {1}'.format(sample_weight.shape[0], X.shape[0])) + 'MockClassifier extra fit_param sample_weight.shape[0]' + ' is {0}, should be {1}'.format(sample_weight.shape[0], + X.shape[0])) if class_prior is not None: assert_true(class_prior.shape[0] == len(np.unique(y)), - 'MockClassifier extra fit_param class_prior.shape[0] is {0}, ' - 'should be {1}'.format(class_prior.shape[0], len(np.unique(y)))) + 'MockClassifier extra fit_param class_prior.shape[0]' + ' is {0}, should be {1}'.format(class_prior.shape[0], + len(np.unique(y)))) + if sparse_sample_weight is not None: + fmt = ('MockClassifier extra fit_param sparse_sample_weight' + '.shape[0] is {0}, should be {1}') + assert_true(sparse_sample_weight.shape[0] == X.shape[0], + fmt.format(sparse_sample_weight.shape[0], X.shape[0])) + if sparse_param is not None: + fmt = ('MockClassifier extra fit_param sparse_param.shape ' + 'is ({0}, {1}), should be ({2}, {3})') + assert_true(sparse_param.shape == P_sparse.shape, + fmt.format(sparse_param.shape[0], + sparse_param.shape[1], + P_sparse.shape[0], P_sparse.shape[1])) return self def predict(self, T): + if self.allow_nd: + T = T.reshape(len(T), -1) return T.shape[0] def score(self, X=None, Y=None): return 1. / (1 + np.abs(self.a)) + def get_params(self, deep=False): + return {'a': self.a, 'allow_nd': self.allow_nd} X = np.ones((10, 2)) X_sparse = coo_matrix(X) -y = np.arange(10) / 2 +W_sparse = coo_matrix((np.array([1]), (np.array([1]), np.array([0]))), + shape=(10, 1)) +P_sparse = coo_matrix(np.eye(5)) +y = np.arange(10) // 2 ############################################################################## # Tests -def test_kfold(): +def check_valid_split(train, test, n_samples=None): + # Use python sets to get more informative assertion failure messages + train, test = set(train), set(test) + + # Train and test split should not overlap + assert_equal(train.intersection(test), set()) + + if n_samples is not None: + # Check that the union of train an test split cover all the indices + assert_equal(train.union(test), set(range(n_samples))) + + +def check_cv_coverage(cv, expected_n_iter=None, n_samples=None): + # Check that a all the samples appear at least once in a test fold + if expected_n_iter is not None: + assert_equal(len(cv), expected_n_iter) + else: + expected_n_iter = len(cv) + + collected_test_samples = set() + iterations = 0 + for train, test in cv: + check_valid_split(train, test, n_samples=n_samples) + iterations += 1 + collected_test_samples.update(test) + + # Check that the accumulated test samples cover the whole dataset + assert_equal(iterations, expected_n_iter) + if n_samples is not None: + assert_equal(collected_test_samples, set(range(n_samples))) + + +def test_kfold_valueerrors(): # Check that errors are raised if there is not enough samples assert_raises(ValueError, cval.KFold, 3, 4) - y = [0, 0, 1, 1, 2] - assert_raises(ValueError, cval.StratifiedKFold, y, 3) + # Check that a warning is raised if the least populated class has too few + # members. + y = [3, 3, -1, -1, 2] + + cv = assert_warns_message(Warning, "The least populated class", + cval.StratifiedKFold, y, 3) + + # Check that despite the warning the folds are still computed even + # though all the classes are not necessarily represented at on each + # side of the split at each split + check_cv_coverage(cv, expected_n_iter=3, n_samples=len(y)) + + # Error when number of folds is <= 1 + assert_raises(ValueError, cval.KFold, 2, 0) + assert_raises(ValueError, cval.KFold, 2, 1) + assert_raises(ValueError, cval.StratifiedKFold, y, 0) + assert_raises(ValueError, cval.StratifiedKFold, y, 1) + + # When n is not integer: + assert_raises(ValueError, cval.KFold, 2.5, 2) + + # When n_folds is not integer: + assert_raises(ValueError, cval.KFold, 5, 1.5) + assert_raises(ValueError, cval.StratifiedKFold, y, 1.5) + + +def test_kfold_indices(): # Check all indices are returned in the test folds kf = cval.KFold(300, 3) - all_folds = None - for train, test in kf: - if all_folds is None: - all_folds = test.copy() - else: - all_folds = np.concatenate((all_folds, test)) - - all_folds.sort() - assert_array_equal(all_folds, np.arange(300)) + check_cv_coverage(kf, expected_n_iter=3, n_samples=300) + + # Check all indices are returned in the test folds even when equal-sized + # folds are not possible + kf = cval.KFold(17, 3) + check_cv_coverage(kf, expected_n_iter=3, n_samples=17) + + +def test_kfold_no_shuffle(): + # Manually check that KFold preserves the data ordering on toy datasets + splits = iter(cval.KFold(4, 2)) + train, test = next(splits) + assert_array_equal(test, [0, 1]) + assert_array_equal(train, [2, 3]) + + train, test = next(splits) + assert_array_equal(test, [2, 3]) + assert_array_equal(train, [0, 1]) + + splits = iter(cval.KFold(5, 2)) + train, test = next(splits) + assert_array_equal(test, [0, 1, 2]) + assert_array_equal(train, [3, 4]) + + train, test = next(splits) + assert_array_equal(test, [3, 4]) + assert_array_equal(train, [0, 1, 2]) + + +def test_stratified_kfold_no_shuffle(): + # Manually check that StratifiedKFold preserves the data ordering as much + # as possible on toy datasets in order to avoid hiding sample dependencies + # when possible + splits = iter(cval.StratifiedKFold([1, 1, 0, 0], 2)) + train, test = next(splits) + assert_array_equal(test, [0, 2]) + assert_array_equal(train, [1, 3]) + + train, test = next(splits) + assert_array_equal(test, [1, 3]) + assert_array_equal(train, [0, 2]) + + splits = iter(cval.StratifiedKFold([1, 1, 1, 0, 0, 0, 0], 2)) + train, test = next(splits) + assert_array_equal(test, [0, 1, 3, 4]) + assert_array_equal(train, [2, 5, 6]) + + train, test = next(splits) + assert_array_equal(test, [2, 5, 6]) + assert_array_equal(train, [0, 1, 3, 4]) + + +def test_stratified_kfold_ratios(): + # Check that stratified kfold preserves label ratios in individual splits + # Repeat with shuffling turned off and on + n_samples = 1000 + labels = np.array([4] * int(0.10 * n_samples) + + [0] * int(0.89 * n_samples) + + [1] * int(0.01 * n_samples)) + for shuffle in [False, True]: + for train, test in cval.StratifiedKFold(labels, 5, shuffle=shuffle): + assert_almost_equal(np.sum(labels[train] == 4) / len(train), 0.10, + 2) + assert_almost_equal(np.sum(labels[train] == 0) / len(train), 0.89, + 2) + assert_almost_equal(np.sum(labels[train] == 1) / len(train), 0.01, + 2) + assert_almost_equal(np.sum(labels[test] == 4) / len(test), 0.10, 2) + assert_almost_equal(np.sum(labels[test] == 0) / len(test), 0.89, 2) + assert_almost_equal(np.sum(labels[test] == 1) / len(test), 0.01, 2) + + +def test_kfold_balance(): + # Check that KFold returns folds with balanced sizes + for kf in [cval.KFold(i, 5) for i in range(11, 17)]: + sizes = [] + for _, test in kf: + sizes.append(len(test)) + + assert_true((np.max(sizes) - np.min(sizes)) <= 1) + assert_equal(np.sum(sizes), kf.n) + + +def test_stratifiedkfold_balance(): + # Check that KFold returns folds with balanced sizes (only when + # stratification is possible) + # Repeat with shuffling turned off and on + labels = [0] * 3 + [1] * 14 + for shuffle in [False, True]: + for skf in [cval.StratifiedKFold(labels[:i], 3, shuffle=shuffle) + for i in range(11, 17)]: + sizes = [] + for _, test in skf: + sizes.append(len(test)) + + assert_true((np.max(sizes) - np.min(sizes)) <= 1) + assert_equal(np.sum(sizes), skf.n) def test_shuffle_kfold(): # Check the indices are shuffled properly, and that all indices are # returned in the different test folds - kf1 = cval.KFold(300, 3, shuffle=True, random_state=0, indices=True) - kf2 = cval.KFold(300, 3, shuffle=True, random_state=0, indices=False) + kf = cval.KFold(300, 3, shuffle=True, random_state=0) ind = np.arange(300) - for kf in (kf1, kf2): - all_folds = None - for train, test in kf: - sorted_array = np.arange(100) - assert_true(np.any(sorted_array != ind[train])) - sorted_array = np.arange(101, 200) - assert_true(np.any(sorted_array != ind[train])) - sorted_array = np.arange(201, 300) - assert_true(np.any(sorted_array != ind[train])) - if all_folds is None: - all_folds = ind[test].copy() - else: - all_folds = np.concatenate((all_folds, ind[test])) + all_folds = None + for train, test in kf: + sorted_array = np.arange(100) + assert_true(np.any(sorted_array != ind[train])) + sorted_array = np.arange(101, 200) + assert_true(np.any(sorted_array != ind[train])) + sorted_array = np.arange(201, 300) + assert_true(np.any(sorted_array != ind[train])) + if all_folds is None: + all_folds = ind[test].copy() + else: + all_folds = np.concatenate((all_folds, ind[test])) - all_folds.sort() - assert_array_equal(all_folds, ind) + all_folds.sort() + assert_array_equal(all_folds, ind) + + +def test_shuffle_stratifiedkfold(): + # Check that shuffling is happening when requested, and for proper + # sample coverage + labels = [0] * 20 + [1] * 20 + kf0 = list(cval.StratifiedKFold(labels, 5, shuffle=True, random_state=0)) + kf1 = list(cval.StratifiedKFold(labels, 5, shuffle=True, random_state=1)) + for (_, test0), (_, test1) in zip(kf0, kf1): + assert_true(set(test0) != set(test1)) + check_cv_coverage(kf0, expected_n_iter=5, n_samples=40) + + +def test_kfold_can_detect_dependent_samples_on_digits(): # see #2372 + # The digits samples are dependent: they are apparently grouped by authors + # although we don't have any information on the groups segment locations + # for this data. We can highlight this fact be computing k-fold cross- + # validation with and without shuffling: we observe that the shuffling case + # wrongly makes the IID assumption and is therefore too optimistic: it + # estimates a much higher accuracy (around 0.96) than than the non + # shuffling variant (around 0.86). + + digits = load_digits() + X, y = digits.data[:800], digits.target[:800] + model = SVC(C=10, gamma=0.005) + n = len(y) + + cv = cval.KFold(n, 5, shuffle=False) + mean_score = cval.cross_val_score(model, X, y, cv=cv).mean() + assert_greater(0.88, mean_score) + assert_greater(mean_score, 0.85) + + # Shuffling the data artificially breaks the dependency and hides the + # overfitting of the model with regards to the writing style of the authors + # by yielding a seriously overestimated score: + + cv = cval.KFold(n, 5, shuffle=True, random_state=0) + mean_score = cval.cross_val_score(model, X, y, cv=cv).mean() + assert_greater(mean_score, 0.95) + + cv = cval.KFold(n, 5, shuffle=True, random_state=1) + mean_score = cval.cross_val_score(model, X, y, cv=cv).mean() + assert_greater(mean_score, 0.95) + + # Similarly, StratifiedKFold should try to shuffle the data as little + # as possible (while respecting the balanced class constraints) + # and thus be able to detect the dependency by not overestimating + # the CV score either. As the digits dataset is approximately balanced + # the estimated mean score is close to the score measured with + # non-shuffled KFold + + cv = cval.StratifiedKFold(y, 5) + mean_score = cval.cross_val_score(model, X, y, cv=cv).mean() + assert_greater(0.88, mean_score) + assert_greater(mean_score, 0.85) def test_shuffle_split(): ss1 = cval.ShuffleSplit(10, test_size=0.2, random_state=0) ss2 = cval.ShuffleSplit(10, test_size=2, random_state=0) ss3 = cval.ShuffleSplit(10, test_size=np.int32(2), random_state=0) - ss4 = cval.ShuffleSplit(10, test_size=long(2), random_state=0) + for typ in six.integer_types: + ss4 = cval.ShuffleSplit(10, test_size=typ(2), random_state=0) for t1, t2, t3, t4 in zip(ss1, ss2, ss3, ss4): assert_array_equal(t1[0], t2[0]) assert_array_equal(t2[0], t3[0]) @@ -115,7 +372,7 @@ def test_shuffle_split(): assert_array_equal(t3[1], t4[1]) -def test_stratified_shuffle_split(): +def test_stratified_shuffle_split_init(): y = np.asarray([0, 1, 1, 1, 2, 2, 2]) # Check that error is raised if there is a class with only one sample assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 0.2) @@ -132,31 +389,130 @@ def test_stratified_shuffle_split(): assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 8, 0.6) assert_raises(ValueError, cval.StratifiedShuffleSplit, y, 3, 0.6, 8) - ys = [ - np.array([1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3]), - np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]), - np.array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]), - np.array([1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4]), - np.array([-1] * 800 + [1] * 50) - ] + # Train size or test size too small + assert_raises(ValueError, cval.StratifiedShuffleSplit, y, train_size=2) + assert_raises(ValueError, cval.StratifiedShuffleSplit, y, test_size=2) + + +def test_stratified_shuffle_split_iter(): + ys = [np.array([1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3]), + np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]), + np.array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]), + np.array([1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4]), + np.array([-1] * 800 + [1] * 50) + ] for y in ys: sss = cval.StratifiedShuffleSplit(y, 6, test_size=0.33, - random_state=0, indices=True) + random_state=0) for train, test in sss: - assert_array_equal(unique(y[train]), unique(y[test])) + assert_array_equal(np.unique(y[train]), np.unique(y[test])) # Checks if folds keep classes proportions - p_train = np.bincount( - unique(y[train], return_inverse=True)[1] - ) / float(len(y[train])) - p_test = np.bincount( - unique(y[test], return_inverse=True)[1] - ) / float(len(y[test])) + p_train = (np.bincount(np.unique(y[train], return_inverse=True)[1]) + / float(len(y[train]))) + p_test = (np.bincount(np.unique(y[test], return_inverse=True)[1]) + / float(len(y[test]))) assert_array_almost_equal(p_train, p_test, 1) assert_equal(y[train].size + y[test].size, y.size) assert_array_equal(np.lib.arraysetops.intersect1d(train, test), []) +@ignore_warnings +def test_stratified_shuffle_split_iter_no_indices(): + y = np.asarray([0, 1, 2] * 10) + + sss1 = cval.StratifiedShuffleSplit(y, indices=False, random_state=0) + train_mask, test_mask = next(iter(sss1)) + + sss2 = cval.StratifiedShuffleSplit(y, indices=True, random_state=0) + train_indices, test_indices = next(iter(sss2)) + + assert_array_equal(sorted(test_indices), np.where(test_mask)[0]) + + +def test_stratified_shuffle_split_even(): + # Test the StratifiedShuffleSplit, indices are drawn with a + # equal chance + n_folds = 5 + n_iter = 1000 + + def assert_counts_are_ok(idx_counts, p): + # Here we test that the distribution of the counts + # per index is close enough to a binomial + threshold = 0.05 / n_splits + bf = stats.binom(n_splits, p) + for count in idx_counts: + p = bf.pmf(count) + assert_true(p > threshold, + "An index is not drawn with chance corresponding " + "to even draws") + + for n_samples in (6, 22): + labels = np.array((n_samples // 2) * [0, 1]) + splits = cval.StratifiedShuffleSplit(labels, n_iter=n_iter, + test_size=1. / n_folds, + random_state=0) + + train_counts = [0] * n_samples + test_counts = [0] * n_samples + n_splits = 0 + for train, test in splits: + n_splits += 1 + for counter, ids in [(train_counts, train), (test_counts, test)]: + for id in ids: + counter[id] += 1 + assert_equal(n_splits, n_iter) + + assert_equal(len(train), splits.n_train) + assert_equal(len(test), splits.n_test) + assert_equal(len(set(train).intersection(test)), 0) + + label_counts = np.unique(labels) + assert_equal(splits.test_size, 1.0 / n_folds) + assert_equal(splits.n_train + splits.n_test, len(labels)) + assert_equal(len(label_counts), 2) + ex_test_p = float(splits.n_test) / n_samples + ex_train_p = float(splits.n_train) / n_samples + + assert_counts_are_ok(train_counts, ex_train_p) + assert_counts_are_ok(test_counts, ex_test_p) + + +def test_predefinedsplit_with_kfold_split(): + '''Check that PredefinedSplit can reproduce a split generated by Kfold.''' + folds = -1 * np.ones(10) + kf_train = [] + kf_test = [] + for i, (train_ind, test_ind) in enumerate(cval.KFold(10, 5, shuffle=True)): + kf_train.append(train_ind) + kf_test.append(test_ind) + folds[test_ind] = i + ps_train = [] + ps_test = [] + ps = cval.PredefinedSplit(folds) + for train_ind, test_ind in ps: + ps_train.append(train_ind) + ps_test.append(test_ind) + assert_array_equal(ps_train, kf_train) + assert_array_equal(ps_test, kf_test) + + +def test_leave_label_out_changing_labels(): + """Check that LeaveOneLabelOut and LeavePLabelOut work normally if + the labels variable is changed before calling __iter__""" + labels = np.array([0, 1, 2, 1, 1, 2, 0, 0]) + labels_changing = np.array(labels, copy=True) + lolo = cval.LeaveOneLabelOut(labels) + lolo_changing = cval.LeaveOneLabelOut(labels_changing) + lplo = cval.LeavePLabelOut(labels, p=2) + lplo_changing = cval.LeavePLabelOut(labels_changing, p=2) + labels_changing[:] = 0 + for llo, llo_changing in [(lolo, lolo_changing), (lplo, lplo_changing)]: + for (train, test), (train_chan, test_chan) in zip(llo, llo_changing): + assert_array_equal(train, train_chan) + assert_array_equal(test, test_chan) + + def test_cross_val_score(): clf = MockClassifier() for a in range(-10, 10): @@ -165,47 +521,217 @@ def test_cross_val_score(): scores = cval.cross_val_score(clf, X, y) assert_array_equal(scores, clf.score(X, y)) + # test with multioutput y + scores = cval.cross_val_score(clf, X_sparse, X) + assert_array_equal(scores, clf.score(X_sparse, X)) + scores = cval.cross_val_score(clf, X_sparse, y) assert_array_equal(scores, clf.score(X_sparse, y)) + # test with multioutput y + scores = cval.cross_val_score(clf, X_sparse, X) + assert_array_equal(scores, clf.score(X_sparse, X)) + + # test with X and y as list + list_check = lambda x: isinstance(x, list) + clf = CheckingClassifier(check_X=list_check) + scores = cval.cross_val_score(clf, X.tolist(), y.tolist()) + + clf = CheckingClassifier(check_y=list_check) + scores = cval.cross_val_score(clf, X, y.tolist()) + + assert_raises(ValueError, cval.cross_val_score, clf, X, y, + scoring="sklearn") + + # test with 3d X and + X_3d = X[:, :, np.newaxis] + clf = MockClassifier(allow_nd=True) + scores = cval.cross_val_score(clf, X_3d, y) + + clf = MockClassifier(allow_nd=False) + assert_raises(ValueError, cval.cross_val_score, clf, X_3d, y) + + +def test_cross_val_score_pandas(): + # check cross_val_score doesn't destroy pandas dataframe + types = [(MockDataFrame, MockDataFrame)] + try: + from pandas import Series, DataFrame + types.append((Series, DataFrame)) + except ImportError: + pass + for TargetType, InputFeatureType in types: + # X dataframe, y series + X_df, y_ser = InputFeatureType(X), TargetType(y) + check_df = lambda x: isinstance(x, InputFeatureType) + check_series = lambda x: isinstance(x, TargetType) + clf = CheckingClassifier(check_X=check_df, check_y=check_series) + cval.cross_val_score(clf, X_df, y_ser) + + +def test_cross_val_score_mask(): + # test that cross_val_score works with boolean masks + svm = SVC(kernel="linear") + iris = load_iris() + X, y = iris.data, iris.target + with warnings.catch_warnings(record=True): + cv_indices = cval.KFold(len(y), 5, indices=True) + scores_indices = cval.cross_val_score(svm, X, y, cv=cv_indices) + with warnings.catch_warnings(record=True): + cv_masks = cval.KFold(len(y), 5, indices=False) + scores_masks = cval.cross_val_score(svm, X, y, cv=cv_masks) + assert_array_equal(scores_indices, scores_masks) + + +def test_cross_val_score_precomputed(): + # test for svm with precomputed kernel + svm = SVC(kernel="precomputed") + iris = load_iris() + X, y = iris.data, iris.target + linear_kernel = np.dot(X, X.T) + score_precomputed = cval.cross_val_score(svm, linear_kernel, y) + svm = SVC(kernel="linear") + score_linear = cval.cross_val_score(svm, X, y) + assert_array_equal(score_precomputed, score_linear) + + # Error raised for non-square X + svm = SVC(kernel="precomputed") + assert_raises(ValueError, cval.cross_val_score, svm, X, y) + + # test error is raised when the precomputed kernel is not array-like + # or sparse + assert_raises(ValueError, cval.cross_val_score, svm, + linear_kernel.tolist(), y) + def test_cross_val_score_fit_params(): clf = MockClassifier() n_samples = X.shape[0] n_classes = len(np.unique(y)) + + DUMMY_INT = 42 + DUMMY_STR = '42' + DUMMY_OBJ = object() + + def assert_fit_params(clf): + """Function to test that the values are passed correctly to the + classifier arguments for non-array type + """ + assert_equal(clf.dummy_int, DUMMY_INT) + assert_equal(clf.dummy_str, DUMMY_STR) + assert_equal(clf.dummy_obj, DUMMY_OBJ) + fit_params = {'sample_weight': np.ones(n_samples), - 'class_prior': np.ones(n_classes) / n_classes} + 'class_prior': np.ones(n_classes) / n_classes, + 'sparse_sample_weight': W_sparse, + 'sparse_param': P_sparse, + 'dummy_int': DUMMY_INT, + 'dummy_str': DUMMY_STR, + 'dummy_obj': DUMMY_OBJ, + 'callback': assert_fit_params} cval.cross_val_score(clf, X, y, fit_params=fit_params) +def test_cross_val_score_score_func(): + clf = MockClassifier() + _score_func_args = [] + + def score_func(y_test, y_predict): + _score_func_args.append((y_test, y_predict)) + return 1.0 + + with warnings.catch_warnings(record=True): + scoring = make_scorer(score_func) + score = cval.cross_val_score(clf, X, y, scoring=scoring) + assert_array_equal(score, [1.0, 1.0, 1.0]) + assert len(_score_func_args) == 3 + + +def test_cross_val_score_errors(): + class BrokenEstimator: + pass + + assert_raises(TypeError, cval.cross_val_score, BrokenEstimator(), X) + + def test_train_test_split_errors(): assert_raises(ValueError, cval.train_test_split) + assert_raises(ValueError, cval.train_test_split, range(3), train_size=1.1) + assert_raises(ValueError, cval.train_test_split, range(3), test_size=0.6, + train_size=0.6) assert_raises(ValueError, cval.train_test_split, range(3), - train_size=1.1) - assert_raises(ValueError, cval.train_test_split, range(3), - test_size=0.6, train_size=0.6) + test_size=np.float32(0.6), train_size=np.float32(0.6)) assert_raises(ValueError, cval.train_test_split, range(3), - test_size=np.float32(0.6), train_size=np.float32(0.6)) - assert_raises(ValueError, cval.train_test_split, range(3), - test_size="wrong_type") - assert_raises(ValueError, cval.train_test_split, range(3), - test_size=2, train_size=4) + test_size="wrong_type") + assert_raises(ValueError, cval.train_test_split, range(3), test_size=2, + train_size=4) assert_raises(TypeError, cval.train_test_split, range(3), - some_argument=1.1) + some_argument=1.1) assert_raises(ValueError, cval.train_test_split, range(3), range(42)) def test_train_test_split(): X = np.arange(100).reshape((10, 10)) X_s = coo_matrix(X) - y = range(10) - X_train, X_test, X_s_train, X_s_test, y_train, y_test = \ - cval.train_test_split(X, X_s, y) - assert_array_equal(X_train, X_s_train.toarray()) - assert_array_equal(X_test, X_s_test.toarray()) + y = np.arange(10) + + # simple test + split = cval.train_test_split(X, y, test_size=None, train_size=.5) + X_train, X_test, y_train, y_test = split + assert_equal(len(y_test), len(y_train)) + # test correspondence of X and y assert_array_equal(X_train[:, 0], y_train * 10) assert_array_equal(X_test[:, 0], y_test * 10) + # conversion of lists to arrays (deprecated?) + with warnings.catch_warnings(record=True): + split = cval.train_test_split(X, X_s, y.tolist(), allow_lists=False) + X_train, X_test, X_s_train, X_s_test, y_train, y_test = split + assert_array_equal(X_train, X_s_train.toarray()) + assert_array_equal(X_test, X_s_test.toarray()) + + # don't convert lists to anything else by default + split = cval.train_test_split(X, X_s, y.tolist()) + X_train, X_test, X_s_train, X_s_test, y_train, y_test = split + assert_true(isinstance(y_train, list)) + assert_true(isinstance(y_test, list)) + + # allow nd-arrays + X_4d = np.arange(10 * 5 * 3 * 2).reshape(10, 5, 3, 2) + y_3d = np.arange(10 * 7 * 11).reshape(10, 7, 11) + split = cval.train_test_split(X_4d, y_3d) + assert_equal(split[0].shape, (7, 5, 3, 2)) + assert_equal(split[1].shape, (3, 5, 3, 2)) + assert_equal(split[2].shape, (7, 7, 11)) + assert_equal(split[3].shape, (3, 7, 11)) + + +def train_test_split_pandas(): + # check cross_val_score doesn't destroy pandas dataframe + types = [MockDataFrame] + try: + from pandas import DataFrame + types.append(DataFrame) + except ImportError: + pass + for InputFeatureType in types: + # X dataframe + X_df = InputFeatureType(X) + X_train, X_test = cval.train_test_split(X_df) + assert_true(isinstance(X_train, InputFeatureType)) + assert_true(isinstance(X_test, InputFeatureType)) + + +def train_test_split_mock_pandas(): + # X mock dataframe + X_df = MockDataFrame(X) + X_train, X_test = cval.train_test_split(X_df) + assert_true(isinstance(X_train, MockDataFrame)) + assert_true(isinstance(X_test, MockDataFrame)) + X_train_arr, X_test_arr = cval.train_test_split(X_df, allow_lists=False) + assert_true(isinstance(X_train_arr, np.ndarray)) + assert_true(isinstance(X_test_arr, np.ndarray)) + def test_cross_val_score_with_score_func_classification(): iris = load_iris() @@ -213,19 +739,19 @@ def test_cross_val_score_with_score_func_classification(): # Default score (should be the accuracy score) scores = cval.cross_val_score(clf, iris.data, iris.target, cv=5) - assert_array_almost_equal(scores, [1., 0.97, 0.90, 0.97, 1.], 2) + assert_array_almost_equal(scores, [0.97, 1., 0.97, 0.97, 1.], 2) # Correct classification score (aka. zero / one score) - should be the # same as the default estimator score zo_scores = cval.cross_val_score(clf, iris.data, iris.target, - score_func=zero_one_score, cv=5) - assert_array_almost_equal(zo_scores, [1., 0.97, 0.90, 0.97, 1.], 2) + scoring="accuracy", cv=5) + assert_array_almost_equal(zo_scores, [0.97, 1., 0.97, 0.97, 1.], 2) # F1 score (class are balanced so f1_score should be equal to zero/one # score f1_scores = cval.cross_val_score(clf, iris.data, iris.target, - score_func=f1_score, cv=5) - assert_array_almost_equal(f1_scores, [1., 0.97, 0.90, 0.97, 1.], 2) + scoring="f1_weighted", cv=5) + assert_array_almost_equal(f1_scores, [0.97, 1., 0.97, 0.97, 1.], 2) def test_cross_val_score_with_score_func_regression(): @@ -239,18 +765,18 @@ def test_cross_val_score_with_score_func_regression(): # R2 score (aka. determination coefficient) - should be the # same as the default estimator score - r2_scores = cval.cross_val_score(reg, X, y, score_func=r2_score, cv=5) + r2_scores = cval.cross_val_score(reg, X, y, scoring="r2", cv=5) assert_array_almost_equal(r2_scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2) - # Mean squared error + # Mean squared error; this is a loss function, so "scores" are negative mse_scores = cval.cross_val_score(reg, X, y, cv=5, - score_func=mean_squared_error) - expected_mse = np.array([763.07, 553.16, 274.38, 273.26, 1681.99]) + scoring="mean_squared_error") + expected_mse = np.array([-763.07, -553.16, -274.38, -273.26, -1681.99]) assert_array_almost_equal(mse_scores, expected_mse, 2) # Explained variance - ev_scores = cval.cross_val_score(reg, X, y, cv=5, - score_func=explained_variance_score) + scoring = make_scorer(explained_variance_score) + ev_scores = cval.cross_val_score(reg, X, y, cv=5, scoring=scoring) assert_array_almost_equal(ev_scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2) @@ -263,88 +789,190 @@ def test_permutation_score(): cv = cval.StratifiedKFold(y, 2) score, scores, pvalue = cval.permutation_test_score( - svm, X, y, zero_one_score, cv) - + svm, X, y, n_permutations=30, cv=cv, scoring="accuracy") assert_greater(score, 0.9) - np.testing.assert_almost_equal(pvalue, 0.0, 1) + assert_almost_equal(pvalue, 0.0, 1) score_label, _, pvalue_label = cval.permutation_test_score( - svm, X, y, zero_one_score, cv, labels=np.ones(y.size), random_state=0) - + svm, X, y, n_permutations=30, cv=cv, scoring="accuracy", + labels=np.ones(y.size), random_state=0) assert_true(score_label == score) assert_true(pvalue_label == pvalue) # check that we obtain the same results with a sparse representation - svm_sparse = SparseSVC(kernel='linear') - cv_sparse = cval.StratifiedKFold(y, 2, indices=True) + svm_sparse = SVC(kernel='linear') + cv_sparse = cval.StratifiedKFold(y, 2) score_label, _, pvalue_label = cval.permutation_test_score( - svm_sparse, X_sparse, y, zero_one_score, cv_sparse, - labels=np.ones(y.size), random_state=0) + svm_sparse, X_sparse, y, n_permutations=30, cv=cv_sparse, + scoring="accuracy", labels=np.ones(y.size), random_state=0) assert_true(score_label == score) assert_true(pvalue_label == pvalue) + # test with custom scoring object + def custom_score(y_true, y_pred): + return (((y_true == y_pred).sum() - (y_true != y_pred).sum()) + / y_true.shape[0]) + + scorer = make_scorer(custom_score) + score, _, pvalue = cval.permutation_test_score( + svm, X, y, n_permutations=100, scoring=scorer, cv=cv, random_state=0) + assert_almost_equal(score, .93, 2) + assert_almost_equal(pvalue, 0.01, 3) + # set random y y = np.mod(np.arange(len(y)), 3) - score, scores, pvalue = cval.permutation_test_score(svm, X, y, - zero_one_score, cv) + score, scores, pvalue = cval.permutation_test_score( + svm, X, y, n_permutations=30, cv=cv, scoring="accuracy") assert_less(score, 0.5) - assert_greater(pvalue, 0.4) + assert_greater(pvalue, 0.2) def test_cross_val_generator_with_mask(): X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) y = np.array([1, 1, 2, 2]) labels = np.array([1, 2, 3, 4]) - loo = cval.LeaveOneOut(4, indices=False) - lpo = cval.LeavePOut(4, 2, indices=False) - kf = cval.KFold(4, 2, indices=False) - skf = cval.StratifiedKFold(y, 2, indices=False) - lolo = cval.LeaveOneLabelOut(labels, indices=False) - lopo = cval.LeavePLabelOut(labels, 2, indices=False) - ss = cval.ShuffleSplit(4, indices=False) - for cv in [loo, lpo, kf, skf, lolo, lopo, ss]: + loo = assert_warns(DeprecationWarning, cval.LeaveOneOut, + 4, indices=False) + lpo = assert_warns(DeprecationWarning, cval.LeavePOut, + 4, 2, indices=False) + kf = assert_warns(DeprecationWarning, cval.KFold, + 4, 2, indices=False) + skf = assert_warns(DeprecationWarning, cval.StratifiedKFold, + y, 2, indices=False) + lolo = assert_warns(DeprecationWarning, cval.LeaveOneLabelOut, + labels, indices=False) + lopo = assert_warns(DeprecationWarning, cval.LeavePLabelOut, + labels, 2, indices=False) + ss = assert_warns(DeprecationWarning, cval.ShuffleSplit, + 4, indices=False) + ps = assert_warns(DeprecationWarning, cval.PredefinedSplit, [1, 1, 2, 2], + indices=False) + for cv in [loo, lpo, kf, skf, lolo, lopo, ss, ps]: for train, test in cv: - X_train, X_test = X[train], X[test] - y_train, y_test = y[train], y[test] + assert_equal(np.asarray(train).dtype.kind, 'b') + assert_equal(np.asarray(train).dtype.kind, 'b') + X[train], X[test] + y[train], y[test] def test_cross_val_generator_with_indices(): X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) y = np.array([1, 1, 2, 2]) labels = np.array([1, 2, 3, 4]) - loo = cval.LeaveOneOut(4, indices=True) - lpo = cval.LeavePOut(4, 2, indices=True) - kf = cval.KFold(4, 2, indices=True) - skf = cval.StratifiedKFold(y, 2, indices=True) - lolo = cval.LeaveOneLabelOut(labels, indices=True) - lopo = cval.LeavePLabelOut(labels, 2, indices=True) - b = cval.Bootstrap(2) # only in index mode - ss = cval.ShuffleSplit(2, indices=True) - for cv in [loo, lpo, kf, skf, lolo, lopo, b, ss]: + # explicitly passing indices value is deprecated + loo = assert_warns(DeprecationWarning, cval.LeaveOneOut, + 4, indices=True) + lpo = assert_warns(DeprecationWarning, cval.LeavePOut, + 4, 2, indices=True) + kf = assert_warns(DeprecationWarning, cval.KFold, + 4, 2, indices=True) + skf = assert_warns(DeprecationWarning, cval.StratifiedKFold, + y, 2, indices=True) + lolo = assert_warns(DeprecationWarning, cval.LeaveOneLabelOut, + labels, indices=True) + lopo = assert_warns(DeprecationWarning, cval.LeavePLabelOut, + labels, 2, indices=True) + ps = assert_warns(DeprecationWarning, cval.PredefinedSplit, + [1, 1, 2, 2], indices=True) + # Bootstrap as a cross-validation is deprecated + b = assert_warns(DeprecationWarning, cval.Bootstrap, 2) + ss = assert_warns(DeprecationWarning, cval.ShuffleSplit, + 2, indices=True) + for cv in [loo, lpo, kf, skf, lolo, lopo, b, ss, ps]: for train, test in cv: - X_train, X_test = X[train], X[test] - y_train, y_test = y[train], y[test] + assert_not_equal(np.asarray(train).dtype.kind, 'b') + assert_not_equal(np.asarray(train).dtype.kind, 'b') + X[train], X[test] + y[train], y[test] +@ignore_warnings +def test_cross_val_generator_with_default_indices(): + X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) + y = np.array([1, 1, 2, 2]) + labels = np.array([1, 2, 3, 4]) + loo = cval.LeaveOneOut(4) + lpo = cval.LeavePOut(4, 2) + kf = cval.KFold(4, 2) + skf = cval.StratifiedKFold(y, 2) + lolo = cval.LeaveOneLabelOut(labels) + lopo = cval.LeavePLabelOut(labels, 2) + b = cval.Bootstrap(2) # only in index mode + ss = cval.ShuffleSplit(2) + ps = cval.PredefinedSplit([1, 1, 2, 2]) + for cv in [loo, lpo, kf, skf, lolo, lopo, b, ss, ps]: + for train, test in cv: + assert_not_equal(np.asarray(train).dtype.kind, 'b') + assert_not_equal(np.asarray(train).dtype.kind, 'b') + X[train], X[test] + y[train], y[test] + + +@ignore_warnings +def test_cross_val_generator_mask_indices_same(): + # Test that the cross validation generators return the same results when + # indices=True and when indices=False + y = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]) + labels = np.array([1, 1, 2, 3, 3, 3, 4]) + + loo_mask = cval.LeaveOneOut(5, indices=False) + loo_ind = cval.LeaveOneOut(5, indices=True) + lpo_mask = cval.LeavePOut(10, 2, indices=False) + lpo_ind = cval.LeavePOut(10, 2, indices=True) + kf_mask = cval.KFold(10, 5, indices=False, shuffle=True, random_state=1) + kf_ind = cval.KFold(10, 5, indices=True, shuffle=True, random_state=1) + skf_mask = cval.StratifiedKFold(y, 3, indices=False) + skf_ind = cval.StratifiedKFold(y, 3, indices=True) + lolo_mask = cval.LeaveOneLabelOut(labels, indices=False) + lolo_ind = cval.LeaveOneLabelOut(labels, indices=True) + lopo_mask = cval.LeavePLabelOut(labels, 2, indices=False) + lopo_ind = cval.LeavePLabelOut(labels, 2, indices=True) + ps_mask = cval.PredefinedSplit([1, 1, 2, 2], indices=False) + ps_ind = cval.PredefinedSplit([1, 1, 2, 2], indices=True) + + for cv_mask, cv_ind in [(loo_mask, loo_ind), (lpo_mask, lpo_ind), + (kf_mask, kf_ind), (skf_mask, skf_ind), + (lolo_mask, lolo_ind), (lopo_mask, lopo_ind), + (ps_mask, ps_ind)]: + for (train_mask, test_mask), (train_ind, test_ind) in \ + zip(cv_mask, cv_ind): + assert_array_equal(np.where(train_mask)[0], train_ind) + assert_array_equal(np.where(test_mask)[0], test_ind) + + +@ignore_warnings def test_bootstrap_errors(): assert_raises(ValueError, cval.Bootstrap, 10, train_size=100) assert_raises(ValueError, cval.Bootstrap, 10, test_size=100) assert_raises(ValueError, cval.Bootstrap, 10, train_size=1.1) assert_raises(ValueError, cval.Bootstrap, 10, test_size=1.1) + assert_raises(ValueError, cval.Bootstrap, 10, train_size=0.6, + test_size=0.5) + + +@ignore_warnings +def test_bootstrap_test_sizes(): + assert_equal(cval.Bootstrap(10, test_size=0.2).test_size, 2) + assert_equal(cval.Bootstrap(10, test_size=1).test_size, 1) + assert_equal(cval.Bootstrap(10, train_size=1.).train_size, 10) + assert_equal(cval.Bootstrap(10, test_size=2).test_size, 2) + assert_equal(cval.Bootstrap(10, test_size=None).test_size, 5) def test_shufflesplit_errors(): assert_raises(ValueError, cval.ShuffleSplit, 10, test_size=2.0) assert_raises(ValueError, cval.ShuffleSplit, 10, test_size=1.0) assert_raises(ValueError, cval.ShuffleSplit, 10, test_size=0.1, - train_size=0.95) + train_size=0.95) assert_raises(ValueError, cval.ShuffleSplit, 10, test_size=11) assert_raises(ValueError, cval.ShuffleSplit, 10, test_size=10) - assert_raises(ValueError, cval.ShuffleSplit, 10, test_size=8, - train_size=3) + assert_raises(ValueError, cval.ShuffleSplit, 10, test_size=8, train_size=3) + assert_raises(ValueError, cval.ShuffleSplit, 10, train_size=1j) + assert_raises(ValueError, cval.ShuffleSplit, 10, test_size=None, + train_size=None) def test_shufflesplit_reproducible(): @@ -354,6 +982,7 @@ def test_shufflesplit_reproducible(): assert_array_equal(list(a for a, b in ss), list(a for a, b in ss)) +@ignore_warnings def test_cross_indices_exception(): X = coo_matrix(np.array([[1, 2], [3, 4], [5, 6], [7, 8]])) y = np.array([1, 1, 2, 2]) @@ -371,3 +1000,160 @@ def test_cross_indices_exception(): assert_raises(ValueError, cval.check_cv, skf, X, y) assert_raises(ValueError, cval.check_cv, lolo, X, y) assert_raises(ValueError, cval.check_cv, lopo, X, y) + + +def test_safe_split_with_precomputed_kernel(): + clf = SVC() + clfp = SVC(kernel="precomputed") + + iris = load_iris() + X, y = iris.data, iris.target + K = np.dot(X, X.T) + + cv = cval.ShuffleSplit(X.shape[0], test_size=0.25, random_state=0) + tr, te = list(cv)[0] + + X_tr, y_tr = cval._safe_split(clf, X, y, tr) + K_tr, y_tr2 = cval._safe_split(clfp, K, y, tr) + assert_array_almost_equal(K_tr, np.dot(X_tr, X_tr.T)) + + X_te, y_te = cval._safe_split(clf, X, y, te, tr) + K_te, y_te2 = cval._safe_split(clfp, K, y, te, tr) + assert_array_almost_equal(K_te, np.dot(X_te, X_tr.T)) + + +def test_cross_val_score_allow_nans(): + # Check that cross_val_score allows input data with NaNs + X = np.arange(200, dtype=np.float64).reshape(10, -1) + X[2, :] = np.nan + y = np.repeat([0, 1], X.shape[0] / 2) + p = Pipeline([ + ('imputer', Imputer(strategy='mean', missing_values='NaN')), + ('classifier', MockClassifier()), + ]) + cval.cross_val_score(p, X, y, cv=5) + + +def test_train_test_split_allow_nans(): + # Check that train_test_split allows input data with NaNs + X = np.arange(200, dtype=np.float64).reshape(10, -1) + X[2, :] = np.nan + y = np.repeat([0, 1], X.shape[0] / 2) + cval.train_test_split(X, y, test_size=0.2, random_state=42) + + +def test_permutation_test_score_allow_nans(): + # Check that permutation_test_score allows input data with NaNs + X = np.arange(200, dtype=np.float64).reshape(10, -1) + X[2, :] = np.nan + y = np.repeat([0, 1], X.shape[0] / 2) + p = Pipeline([ + ('imputer', Imputer(strategy='mean', missing_values='NaN')), + ('classifier', MockClassifier()), + ]) + cval.permutation_test_score(p, X, y, cv=5) + + +def test_check_cv_return_types(): + X = np.ones((9, 2)) + cv = cval._check_cv(3, X, classifier=False) + assert_true(isinstance(cv, cval.KFold)) + + y_binary = np.array([0, 1, 0, 1, 0, 0, 1, 1, 1]) + cv = cval._check_cv(3, X, y_binary, classifier=True) + assert_true(isinstance(cv, cval.StratifiedKFold)) + + y_multiclass = np.array([0, 1, 0, 1, 2, 1, 2, 0, 2]) + cv = cval._check_cv(3, X, y_multiclass, classifier=True) + assert_true(isinstance(cv, cval.StratifiedKFold)) + + X = np.ones((5, 2)) + y_seq_of_seqs = [[], [1, 2], [3], [0, 1, 3], [2]] + + with warnings.catch_warnings(record=True): + # deprecated sequence of sequence format + cv = cval._check_cv(3, X, y_seq_of_seqs, classifier=True) + assert_true(isinstance(cv, cval.KFold)) + + y_indicator_matrix = LabelBinarizer().fit_transform(y_seq_of_seqs) + cv = cval._check_cv(3, X, y_indicator_matrix, classifier=True) + assert_true(isinstance(cv, cval.KFold)) + + y_multioutput = np.array([[1, 2], [0, 3], [0, 0], [3, 1], [2, 0]]) + cv = cval._check_cv(3, X, y_multioutput, classifier=True) + assert_true(isinstance(cv, cval.KFold)) + + +def test_cross_val_score_multilabel(): + X = np.array([[-3, 4], [2, 4], [3, 3], [0, 2], [-3, 1], + [-2, 1], [0, 0], [-2, -1], [-1, -2], [1, -2]]) + y = np.array([[1, 1], [0, 1], [0, 1], [0, 1], [1, 1], + [0, 1], [1, 0], [1, 1], [1, 0], [0, 0]]) + clf = KNeighborsClassifier(n_neighbors=1) + scoring_micro = make_scorer(precision_score, average='micro') + scoring_macro = make_scorer(precision_score, average='macro') + scoring_samples = make_scorer(precision_score, average='samples') + score_micro = cval.cross_val_score(clf, X, y, scoring=scoring_micro, cv=5) + score_macro = cval.cross_val_score(clf, X, y, scoring=scoring_macro, cv=5) + score_samples = cval.cross_val_score(clf, X, y, + scoring=scoring_samples, cv=5) + assert_almost_equal(score_micro, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 3]) + assert_almost_equal(score_macro, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 4]) + assert_almost_equal(score_samples, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 4]) + + +def test_cross_val_predict(): + boston = load_boston() + X, y = boston.data, boston.target + cv = cval.KFold(len(boston.target)) + + est = Ridge() + + # Naive loop (should be same as cross_val_predict): + preds2 = np.zeros_like(y) + for train, test in cv: + est.fit(X[train], y[train]) + preds2[test] = est.predict(X[test]) + + preds = cval.cross_val_predict(est, X, y, cv=cv) + assert_array_almost_equal(preds, preds2) + + preds = cval.cross_val_predict(est, X, y) + assert_equal(len(preds), len(y)) + + cv = cval.LeaveOneOut(len(y)) + preds = cval.cross_val_predict(est, X, y, cv=cv) + assert_equal(len(preds), len(y)) + + Xsp = X.copy() + Xsp *= (Xsp > np.median(Xsp)) + Xsp = coo_matrix(Xsp) + preds = cval.cross_val_predict(est, Xsp, y) + assert_array_almost_equal(len(preds), len(y)) + + preds = cval.cross_val_predict(KMeans(), X) + assert_equal(len(preds), len(y)) + + def bad_cv(): + for i in range(4): + yield np.array([0, 1, 2, 3]), np.array([4, 5, 6, 7, 8]) + + assert_raises(ValueError, cval.cross_val_predict, est, X, y, cv=bad_cv()) + + +def test_sparse_fit_params(): + iris = load_iris() + X, y = iris.data, iris.target + clf = MockClassifier() + fit_params = {'sparse_sample_weight': coo_matrix(np.eye(X.shape[0]))} + a = cval.cross_val_score(clf, X, y, fit_params=fit_params) + assert_array_equal(a, np.ones(3)) + + +def test_check_is_partition(): + p = np.arange(100) + assert_true(cval._check_is_partition(p, 100)) + assert_false(cval._check_is_partition(np.delete(p, 23), 100)) + + p[0] = 23 + assert_false(cval._check_is_partition(p, 100)) diff --git a/sklearn/tests/test_dummy.py b/sklearn/tests/test_dummy.py new file mode 100644 index 0000000000000..edc9498743633 --- /dev/null +++ b/sklearn/tests/test_dummy.py @@ -0,0 +1,596 @@ +from __future__ import division +import warnings +import numpy as np +import scipy.sparse as sp + +from sklearn.base import clone +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_warns_message +from sklearn.utils.stats import _weighted_percentile + +from sklearn.dummy import DummyClassifier, DummyRegressor + + +def _check_predict_proba(clf, X, y): + proba = clf.predict_proba(X) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + # We know that we can have division by zero + log_proba = clf.predict_log_proba(X) + + y = np.atleast_1d(y) + if y.ndim == 1: + y = np.reshape(y, (-1, 1)) + + n_outputs = y.shape[1] + n_samples = len(X) + + if n_outputs == 1: + proba = [proba] + log_proba = [log_proba] + + for k in range(n_outputs): + assert_equal(proba[k].shape[0], n_samples) + assert_equal(proba[k].shape[1], len(np.unique(y[:, k]))) + assert_array_equal(proba[k].sum(axis=1), np.ones(len(X))) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + # We know that we can have division by zero + assert_array_equal(np.log(proba[k]), log_proba[k]) + + +def _check_behavior_2d(clf): + # 1d case + X = np.array([[0], [0], [0], [0]]) # ignored + y = np.array([1, 2, 1, 1]) + est = clone(clf) + est.fit(X, y) + y_pred = est.predict(X) + assert_equal(y.shape, y_pred.shape) + + # 2d case + y = np.array([[1, 0], + [2, 0], + [1, 0], + [1, 3]]) + est = clone(clf) + est.fit(X, y) + y_pred = est.predict(X) + assert_equal(y.shape, y_pred.shape) + + +def _check_behavior_2d_for_constant(clf): + # 2d case only + X = np.array([[0], [0], [0], [0]]) # ignored + y = np.array([[1, 0, 5, 4, 3], + [2, 0, 1, 2, 5], + [1, 0, 4, 5, 2], + [1, 3, 3, 2, 0]]) + est = clone(clf) + est.fit(X, y) + y_pred = est.predict(X) + assert_equal(y.shape, y_pred.shape) + + +def _check_equality_regressor(statistic, y_learn, y_pred_learn, + y_test, y_pred_test): + assert_array_equal(np.tile(statistic, (y_learn.shape[0], 1)), + y_pred_learn) + assert_array_equal(np.tile(statistic, (y_test.shape[0], 1)), + y_pred_test) + + +def test_most_frequent_strategy(): + X = [[0], [0], [0], [0]] # ignored + y = [1, 2, 1, 1] + + clf = DummyClassifier(strategy="most_frequent", random_state=0) + clf.fit(X, y) + assert_array_equal(clf.predict(X), np.ones(len(X))) + _check_predict_proba(clf, X, y) + + +def test_most_frequent_strategy_multioutput(): + X = [[0], [0], [0], [0]] # ignored + y = np.array([[1, 0], + [2, 0], + [1, 0], + [1, 3]]) + + n_samples = len(X) + + clf = DummyClassifier(strategy="most_frequent", random_state=0) + clf.fit(X, y) + assert_array_equal(clf.predict(X), + np.hstack([np.ones((n_samples, 1)), + np.zeros((n_samples, 1))])) + _check_predict_proba(clf, X, y) + _check_behavior_2d(clf) + + +def test_stratified_strategy(): + X = [[0]] * 5 # ignored + y = [1, 2, 1, 1, 2] + clf = DummyClassifier(strategy="stratified", random_state=0) + clf.fit(X, y) + + X = [[0]] * 500 + y_pred = clf.predict(X) + p = np.bincount(y_pred) / float(len(X)) + assert_almost_equal(p[1], 3. / 5, decimal=1) + assert_almost_equal(p[2], 2. / 5, decimal=1) + _check_predict_proba(clf, X, y) + + +def test_stratified_strategy_multioutput(): + X = [[0]] * 5 # ignored + y = np.array([[2, 1], + [2, 2], + [1, 1], + [1, 2], + [1, 1]]) + + clf = DummyClassifier(strategy="stratified", random_state=0) + clf.fit(X, y) + + X = [[0]] * 500 + y_pred = clf.predict(X) + + for k in range(y.shape[1]): + p = np.bincount(y_pred[:, k]) / float(len(X)) + assert_almost_equal(p[1], 3. / 5, decimal=1) + assert_almost_equal(p[2], 2. / 5, decimal=1) + _check_predict_proba(clf, X, y) + + _check_behavior_2d(clf) + + +def test_uniform_strategy(): + X = [[0]] * 4 # ignored + y = [1, 2, 1, 1] + clf = DummyClassifier(strategy="uniform", random_state=0) + clf.fit(X, y) + + X = [[0]] * 500 + y_pred = clf.predict(X) + p = np.bincount(y_pred) / float(len(X)) + assert_almost_equal(p[1], 0.5, decimal=1) + assert_almost_equal(p[2], 0.5, decimal=1) + _check_predict_proba(clf, X, y) + + +def test_uniform_strategy_multioutput(): + X = [[0]] * 4 # ignored + y = np.array([[2, 1], + [2, 2], + [1, 2], + [1, 1]]) + clf = DummyClassifier(strategy="uniform", random_state=0) + clf.fit(X, y) + + X = [[0]] * 500 + y_pred = clf.predict(X) + + for k in range(y.shape[1]): + p = np.bincount(y_pred[:, k]) / float(len(X)) + assert_almost_equal(p[1], 0.5, decimal=1) + assert_almost_equal(p[2], 0.5, decimal=1) + _check_predict_proba(clf, X, y) + + _check_behavior_2d(clf) + + +def test_string_labels(): + X = [[0]] * 5 + y = ["paris", "paris", "tokyo", "amsterdam", "berlin"] + clf = DummyClassifier(strategy="most_frequent") + clf.fit(X, y) + assert_array_equal(clf.predict(X), ["paris"] * 5) + + +def test_classifier_exceptions(): + clf = DummyClassifier(strategy="unknown") + assert_raises(ValueError, clf.fit, [], []) + + assert_raises(ValueError, clf.predict, []) + assert_raises(ValueError, clf.predict_proba, []) + + +def test_mean_strategy_regressor(): + + random_state = np.random.RandomState(seed=1) + + X = [[0]] * 4 # ignored + y = random_state.randn(4) + + reg = DummyRegressor() + reg.fit(X, y) + assert_array_equal(reg.predict(X), [np.mean(y)] * len(X)) + + +def test_mean_strategy_multioutput_regressor(): + + random_state = np.random.RandomState(seed=1) + + X_learn = random_state.randn(10, 10) + y_learn = random_state.randn(10, 5) + + mean = np.mean(y_learn, axis=0).reshape((1, -1)) + + X_test = random_state.randn(20, 10) + y_test = random_state.randn(20, 5) + + # Correctness oracle + est = DummyRegressor() + est.fit(X_learn, y_learn) + y_pred_learn = est.predict(X_learn) + y_pred_test = est.predict(X_test) + + _check_equality_regressor(mean, y_learn, y_pred_learn, y_test, y_pred_test) + _check_behavior_2d(est) + + +def test_regressor_exceptions(): + reg = DummyRegressor() + assert_raises(ValueError, reg.predict, []) + + +def test_median_strategy_regressor(): + + random_state = np.random.RandomState(seed=1) + + X = [[0]] * 5 # ignored + y = random_state.randn(5) + + reg = DummyRegressor(strategy="median") + reg.fit(X, y) + assert_array_equal(reg.predict(X), [np.median(y)] * len(X)) + + +def test_median_strategy_multioutput_regressor(): + + random_state = np.random.RandomState(seed=1) + + X_learn = random_state.randn(10, 10) + y_learn = random_state.randn(10, 5) + + median = np.median(y_learn, axis=0).reshape((1, -1)) + + X_test = random_state.randn(20, 10) + y_test = random_state.randn(20, 5) + + # Correctness oracle + est = DummyRegressor(strategy="median") + est.fit(X_learn, y_learn) + y_pred_learn = est.predict(X_learn) + y_pred_test = est.predict(X_test) + + _check_equality_regressor( + median, y_learn, y_pred_learn, y_test, y_pred_test) + _check_behavior_2d(est) + + +def test_quantile_strategy_regressor(): + + random_state = np.random.RandomState(seed=1) + + X = [[0]] * 5 # ignored + y = random_state.randn(5) + + reg = DummyRegressor(strategy="quantile", quantile=0.5) + reg.fit(X, y) + assert_array_equal(reg.predict(X), [np.median(y)] * len(X)) + + reg = DummyRegressor(strategy="quantile", quantile=0) + reg.fit(X, y) + assert_array_equal(reg.predict(X), [np.min(y)] * len(X)) + + reg = DummyRegressor(strategy="quantile", quantile=1) + reg.fit(X, y) + assert_array_equal(reg.predict(X), [np.max(y)] * len(X)) + + reg = DummyRegressor(strategy="quantile", quantile=0.3) + reg.fit(X, y) + assert_array_equal(reg.predict(X), [np.percentile(y, q=30)] * len(X)) + + +def test_quantile_strategy_multioutput_regressor(): + + random_state = np.random.RandomState(seed=1) + + X_learn = random_state.randn(10, 10) + y_learn = random_state.randn(10, 5) + + median = np.median(y_learn, axis=0).reshape((1, -1)) + quantile_values = np.percentile(y_learn, axis=0, q=80).reshape((1, -1)) + + X_test = random_state.randn(20, 10) + y_test = random_state.randn(20, 5) + + # Correctness oracle + est = DummyRegressor(strategy="quantile", quantile=0.5) + est.fit(X_learn, y_learn) + y_pred_learn = est.predict(X_learn) + y_pred_test = est.predict(X_test) + + _check_equality_regressor( + median, y_learn, y_pred_learn, y_test, y_pred_test) + _check_behavior_2d(est) + + # Correctness oracle + est = DummyRegressor(strategy="quantile", quantile=0.8) + est.fit(X_learn, y_learn) + y_pred_learn = est.predict(X_learn) + y_pred_test = est.predict(X_test) + + _check_equality_regressor( + quantile_values, y_learn, y_pred_learn, y_test, y_pred_test) + _check_behavior_2d(est) + + +def test_quantile_invalid(): + + X = [[0]] * 5 # ignored + y = [0] * 5 # ignored + + est = DummyRegressor(strategy="quantile") + assert_raises(ValueError, est.fit, X, y) + + est = DummyRegressor(strategy="quantile", quantile=None) + assert_raises(ValueError, est.fit, X, y) + + est = DummyRegressor(strategy="quantile", quantile=[0]) + assert_raises(ValueError, est.fit, X, y) + + est = DummyRegressor(strategy="quantile", quantile=-0.1) + assert_raises(ValueError, est.fit, X, y) + + est = DummyRegressor(strategy="quantile", quantile=1.1) + assert_raises(ValueError, est.fit, X, y) + + est = DummyRegressor(strategy="quantile", quantile='abc') + assert_raises(TypeError, est.fit, X, y) + + +def test_quantile_strategy_empty_train(): + est = DummyRegressor(strategy="quantile", quantile=0.4) + assert_raises(ValueError, est.fit, [], []) + + +def test_constant_strategy_regressor(): + + random_state = np.random.RandomState(seed=1) + + X = [[0]] * 5 # ignored + y = random_state.randn(5) + + reg = DummyRegressor(strategy="constant", constant=[43]) + reg.fit(X, y) + assert_array_equal(reg.predict(X), [43] * len(X)) + + reg = DummyRegressor(strategy="constant", constant=43) + reg.fit(X, y) + assert_array_equal(reg.predict(X), [43] * len(X)) + + +def test_constant_strategy_multioutput_regressor(): + + random_state = np.random.RandomState(seed=1) + + X_learn = random_state.randn(10, 10) + y_learn = random_state.randn(10, 5) + + # test with 2d array + constants = random_state.randn(5) + + X_test = random_state.randn(20, 10) + y_test = random_state.randn(20, 5) + + # Correctness oracle + est = DummyRegressor(strategy="constant", constant=constants) + est.fit(X_learn, y_learn) + y_pred_learn = est.predict(X_learn) + y_pred_test = est.predict(X_test) + + _check_equality_regressor( + constants, y_learn, y_pred_learn, y_test, y_pred_test) + _check_behavior_2d_for_constant(est) + + +def test_y_mean_attribute_regressor(): + X = [[0]] * 5 + y = [1, 2, 4, 6, 8] + # when strategy = 'mean' + est = DummyRegressor(strategy='mean') + est.fit(X, y) + + assert_equal(est.constant_, np.mean(y)) + + +def test_unknown_strategey_regressor(): + X = [[0]] * 5 + y = [1, 2, 4, 6, 8] + + est = DummyRegressor(strategy='gona') + assert_raises(ValueError, est.fit, X, y) + + +def test_constants_not_specified_regressor(): + X = [[0]] * 5 + y = [1, 2, 4, 6, 8] + + est = DummyRegressor(strategy='constant') + assert_raises(TypeError, est.fit, X, y) + + +def test_constant_size_multioutput_regressor(): + random_state = np.random.RandomState(seed=1) + X = random_state.randn(10, 10) + y = random_state.randn(10, 5) + + est = DummyRegressor(strategy='constant', constant=[1, 2, 3, 4]) + assert_raises(ValueError, est.fit, X, y) + + +def test_constant_strategy(): + X = [[0], [0], [0], [0]] # ignored + y = [2, 1, 2, 2] + + clf = DummyClassifier(strategy="constant", random_state=0, constant=1) + clf.fit(X, y) + assert_array_equal(clf.predict(X), np.ones(len(X))) + _check_predict_proba(clf, X, y) + + X = [[0], [0], [0], [0]] # ignored + y = ['two', 'one', 'two', 'two'] + clf = DummyClassifier(strategy="constant", random_state=0, constant='one') + clf.fit(X, y) + assert_array_equal(clf.predict(X), np.array(['one'] * 4)) + _check_predict_proba(clf, X, y) + + +def test_constant_strategy_multioutput(): + X = [[0], [0], [0], [0]] # ignored + y = np.array([[2, 3], + [1, 3], + [2, 3], + [2, 0]]) + + n_samples = len(X) + + clf = DummyClassifier(strategy="constant", random_state=0, + constant=[1, 0]) + clf.fit(X, y) + assert_array_equal(clf.predict(X), + np.hstack([np.ones((n_samples, 1)), + np.zeros((n_samples, 1))])) + _check_predict_proba(clf, X, y) + + +def test_constant_strategy_exceptions(): + X = [[0], [0], [0], [0]] # ignored + y = [2, 1, 2, 2] + clf = DummyClassifier(strategy="constant", random_state=0) + assert_raises(ValueError, clf.fit, X, y) + clf = DummyClassifier(strategy="constant", random_state=0, + constant=[2, 0]) + assert_raises(ValueError, clf.fit, X, y) + + +def test_classification_sample_weight(): + X = [[0], [0], [1]] + y = [0, 1, 0] + sample_weight = [0.1, 1., 0.1] + + clf = DummyClassifier().fit(X, y, sample_weight) + assert_array_almost_equal(clf.class_prior_, [0.2 / 1.2, 1. / 1.2]) + + +def test_constant_strategy_sparse_target(): + X = [[0]] * 5 # ignored + y = sp.csc_matrix(np.array([[0, 1], + [4, 0], + [1, 1], + [1, 4], + [1, 1]])) + + n_samples = len(X) + + clf = DummyClassifier(strategy="constant", random_state=0, constant=[1, 0]) + clf.fit(X, y) + y_pred = clf.predict(X) + assert_true(sp.issparse(y_pred)) + assert_array_equal(y_pred.toarray(), np.hstack([np.ones((n_samples, 1)), + np.zeros((n_samples, 1))])) + + +def test_uniform_strategy_sparse_target_warning(): + X = [[0]] * 5 # ignored + y = sp.csc_matrix(np.array([[2, 1], + [2, 2], + [1, 4], + [4, 2], + [1, 1]])) + + clf = DummyClassifier(strategy="uniform", random_state=0) + assert_warns_message(UserWarning, + "the uniform strategy would not save memory", + clf.fit, X, y) + + X = [[0]] * 500 + y_pred = clf.predict(X) + + for k in range(y.shape[1]): + p = np.bincount(y_pred[:, k]) / float(len(X)) + assert_almost_equal(p[1], 1/3, decimal=1) + assert_almost_equal(p[2], 1/3, decimal=1) + assert_almost_equal(p[4], 1/3, decimal=1) + + +def test_stratified_strategy_sparse_target(): + X = [[0]] * 5 # ignored + y = sp.csc_matrix(np.array([[4, 1], + [0, 0], + [1, 1], + [1, 4], + [1, 1]])) + + clf = DummyClassifier(strategy="stratified", random_state=0) + clf.fit(X, y) + + X = [[0]] * 500 + y_pred = clf.predict(X) + assert_true(sp.issparse(y_pred)) + y_pred = y_pred.toarray() + + for k in range(y.shape[1]): + p = np.bincount(y_pred[:, k]) / float(len(X)) + assert_almost_equal(p[1], 3. / 5, decimal=1) + assert_almost_equal(p[0], 1. / 5, decimal=1) + assert_almost_equal(p[4], 1. / 5, decimal=1) + + +def test_most_frequent_strategy_sparse_target(): + X = [[0]] * 5 # ignored + y = sp.csc_matrix(np.array([[1, 0], + [1, 3], + [4, 0], + [0, 1], + [1, 0]])) + + n_samples = len(X) + clf = DummyClassifier(strategy="most_frequent", random_state=0) + clf.fit(X, y) + + y_pred = clf.predict(X) + assert_true(sp.issparse(y_pred)) + assert_array_equal(y_pred.toarray(), np.hstack([np.ones((n_samples, 1)), + np.zeros((n_samples, 1))])) + + +def test_dummy_regressor_sample_weight(n_samples=10): + random_state = np.random.RandomState(seed=1) + + X = [[0]] * n_samples + y = random_state.rand(n_samples) + sample_weight = random_state.rand(n_samples) + + est = DummyRegressor(strategy="mean").fit(X, y, sample_weight) + assert_equal(est.constant_, np.average(y, weights=sample_weight)) + + est = DummyRegressor(strategy="median").fit(X, y, sample_weight) + assert_equal(est.constant_, _weighted_percentile(y, sample_weight, 50.)) + + est = DummyRegressor(strategy="quantile", quantile=.95).fit(X, y, + sample_weight) + assert_equal(est.constant_, _weighted_percentile(y, sample_weight, 95.)) + + +if __name__ == '__main__': + import nose + nose.runmodule() diff --git a/sklearn/tests/test_grid_search.py b/sklearn/tests/test_grid_search.py index 1ee8829cf046d..8fe2bdc6279c6 100644 --- a/sklearn/tests/test_grid_search.py +++ b/sklearn/tests/test_grid_search.py @@ -2,21 +2,56 @@ Testing for grid search module (sklearn.grid_search) """ -from nose.tools import assert_equal, assert_raises, assert_true -from numpy.testing import assert_array_equal + +from collections import Iterable, Sized +from sklearn.externals.six.moves import cStringIO as StringIO +from sklearn.externals.six.moves import xrange +from itertools import chain, product +import pickle +import sys import numpy as np import scipy.sparse as sp +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_not_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import assert_raise_message +from sklearn.utils.testing import assert_false, assert_true +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_no_warnings +from sklearn.utils.testing import ignore_warnings +from sklearn.utils.mocking import CheckingClassifier, MockDataFrame + +from scipy.stats import bernoulli, expon, uniform + +from sklearn.externals.six.moves import zip from sklearn.base import BaseEstimator -from sklearn.grid_search import GridSearchCV -from sklearn.datasets.samples_generator import make_classification +from sklearn.datasets import make_classification +from sklearn.datasets import make_blobs +from sklearn.datasets import make_multilabel_classification +from sklearn.grid_search import (GridSearchCV, RandomizedSearchCV, + ParameterGrid, ParameterSampler, + ChangedBehaviorWarning) from sklearn.svm import LinearSVC, SVC -from sklearn.metrics import f1_score, precision_score -from sklearn.cross_validation import KFold - - -class MockClassifier(BaseEstimator): +from sklearn.tree import DecisionTreeRegressor +from sklearn.tree import DecisionTreeClassifier +from sklearn.cluster import KMeans +from sklearn.neighbors import KernelDensity +from sklearn.metrics import f1_score +from sklearn.metrics import make_scorer +from sklearn.metrics import roc_auc_score +from sklearn.cross_validation import KFold, StratifiedKFold, FitFailedWarning +from sklearn.preprocessing import Imputer +from sklearn.pipeline import Pipeline + + +# Neither of the following two estimators inherit from BaseEstimator, +# to test hyperparameter search on user-defined classifiers. +class MockClassifier(object): """Dummy classifier to test the cross-validation""" def __init__(self, foo_param=0): self.foo_param = foo_param @@ -28,6 +63,10 @@ def fit(self, X, Y): def predict(self, T): return T.shape[0] + predict_proba = predict + decision_function = predict + transform = predict + def score(self, X=None, Y=None): if self.foo_param > 1: score = 1. @@ -35,23 +74,149 @@ def score(self, X=None, Y=None): score = 0. return score + def get_params(self, deep=False): + return {'foo_param': self.foo_param} + + def set_params(self, **params): + self.foo_param = params['foo_param'] + return self + + +class LinearSVCNoScore(LinearSVC): + """An LinearSVC classifier that has no score method.""" + @property + def score(self): + raise AttributeError X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) y = np.array([1, 1, 2, 2]) +def test_parameter_grid(): + """Test basic properties of ParameterGrid.""" + params1 = {"foo": [1, 2, 3]} + grid1 = ParameterGrid(params1) + assert_true(isinstance(grid1, Iterable)) + assert_true(isinstance(grid1, Sized)) + assert_equal(len(grid1), 3) + + params2 = {"foo": [4, 2], + "bar": ["ham", "spam", "eggs"]} + grid2 = ParameterGrid(params2) + assert_equal(len(grid2), 6) + + # loop to assert we can iterate over the grid multiple times + for i in xrange(2): + # tuple + chain transforms {"a": 1, "b": 2} to ("a", 1, "b", 2) + points = set(tuple(chain(*(sorted(p.items())))) for p in grid2) + assert_equal(points, + set(("bar", x, "foo", y) + for x, y in product(params2["bar"], params2["foo"]))) + + # Special case: empty grid (useful to get default estimator settings) + empty = ParameterGrid({}) + assert_equal(len(empty), 1) + assert_equal(list(empty), [{}]) + + has_empty = ParameterGrid([{'C': [1, 10]}, {}]) + assert_equal(len(has_empty), 3) + assert_equal(list(has_empty), [{'C': 1}, {'C': 10}, {}]) + + def test_grid_search(): """Test that the best estimator contains the right value for foo_param""" clf = MockClassifier() - grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}) + grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}, verbose=3) # make sure it selects the smallest parameter in case of ties + old_stdout = sys.stdout + sys.stdout = StringIO() grid_search.fit(X, y) + sys.stdout = old_stdout assert_equal(grid_search.best_estimator_.foo_param, 2) for i, foo_i in enumerate([1, 2, 3]): - assert_true(grid_search.grid_scores_[i][0] == {'foo_param': foo_i}) - # Smoke test the score: + assert_true(grid_search.grid_scores_[i][0] + == {'foo_param': foo_i}) + # Smoke test the score etc: grid_search.score(X, y) + grid_search.predict_proba(X) + grid_search.decision_function(X) + grid_search.transform(X) + + # Test exception handling on scoring + grid_search.scoring = 'sklearn' + assert_raises(ValueError, grid_search.fit, X, y) + + +@ignore_warnings +def test_grid_search_no_score(): + # Test grid-search on classifier that has no score function. + clf = LinearSVC(random_state=0) + X, y = make_blobs(random_state=0, centers=2) + Cs = [.1, 1, 10] + clf_no_score = LinearSVCNoScore(random_state=0) + grid_search = GridSearchCV(clf, {'C': Cs}, scoring='accuracy') + grid_search.fit(X, y) + + grid_search_no_score = GridSearchCV(clf_no_score, {'C': Cs}, + scoring='accuracy') + # smoketest grid search + grid_search_no_score.fit(X, y) + + # check that best params are equal + assert_equal(grid_search_no_score.best_params_, grid_search.best_params_) + # check that we can call score and that it gives the correct result + assert_equal(grid_search.score(X, y), grid_search_no_score.score(X, y)) + + # giving no scoring function raises an error + grid_search_no_score = GridSearchCV(clf_no_score, {'C': Cs}) + assert_raise_message(TypeError, "no scoring", grid_search_no_score.fit, + [[1]]) + + +def test_grid_search_score_method(): + X, y = make_classification(n_samples=100, n_classes=2, flip_y=.2, + random_state=0) + clf = LinearSVC(random_state=0) + grid = {'C': [.1]} + + search_no_scoring = GridSearchCV(clf, grid, scoring=None).fit(X, y) + search_accuracy = GridSearchCV(clf, grid, scoring='accuracy').fit(X, y) + search_no_score_method_auc = GridSearchCV(LinearSVCNoScore(), grid, + scoring='roc_auc').fit(X, y) + search_auc = GridSearchCV(clf, grid, scoring='roc_auc').fit(X, y) + + # Check warning only occurs in situation where behavior changed: + # estimator requires score method to compete with scoring parameter + score_no_scoring = assert_no_warnings(search_no_scoring.score, X, y) + score_accuracy = assert_warns(ChangedBehaviorWarning, + search_accuracy.score, X, y) + score_no_score_auc = assert_no_warnings(search_no_score_method_auc.score, + X, y) + score_auc = assert_warns(ChangedBehaviorWarning, + search_auc.score, X, y) + # ensure the test is sane + assert_true(score_auc < 1.0) + assert_true(score_accuracy < 1.0) + assert_not_equal(score_auc, score_accuracy) + + assert_almost_equal(score_accuracy, score_no_scoring) + assert_almost_equal(score_auc, score_no_score_auc) + + +def test_trivial_grid_scores(): + """Test search over a "grid" with only one point. + + Non-regression test: grid_scores_ wouldn't be set by GridSearchCV. + """ + clf = MockClassifier() + grid_search = GridSearchCV(clf, {'foo_param': [1]}) + grid_search.fit(X, y) + assert_true(hasattr(grid_search, "grid_scores_")) + + random_search = RandomizedSearchCV(clf, {'foo_param': [0]}, n_iter=1) + random_search.fit(X, y) + assert_true(hasattr(random_search, "grid_scores_")) def test_no_refit(): @@ -72,6 +237,45 @@ def test_grid_search_error(): assert_raises(ValueError, cv.fit, X_[:180], y_) +def test_grid_search_iid(): + # test the iid parameter + # noise-free simple 2d-data + X, y = make_blobs(centers=[[0, 0], [1, 0], [0, 1], [1, 1]], random_state=0, + cluster_std=0.1, shuffle=False, n_samples=80) + # split dataset into two folds that are not iid + # first one contains data of all 4 blobs, second only from two. + mask = np.ones(X.shape[0], dtype=np.bool) + mask[np.where(y == 1)[0][::2]] = 0 + mask[np.where(y == 2)[0][::2]] = 0 + # this leads to perfect classification on one fold and a score of 1/3 on + # the other + svm = SVC(kernel='linear') + # create "cv" for splits + cv = [[mask, ~mask], [~mask, mask]] + # once with iid=True (default) + grid_search = GridSearchCV(svm, param_grid={'C': [1, 10]}, cv=cv) + grid_search.fit(X, y) + first = grid_search.grid_scores_[0] + assert_equal(first.parameters['C'], 1) + assert_array_almost_equal(first.cv_validation_scores, [1, 1. / 3.]) + # for first split, 1/4 of dataset is in test, for second 3/4. + # take weighted average + assert_almost_equal(first.mean_validation_score, + 1 * 1. / 4. + 1. / 3. * 3. / 4.) + + # once with iid=False + grid_search = GridSearchCV(svm, param_grid={'C': [1, 10]}, cv=cv, + iid=False) + grid_search.fit(X, y) + first = grid_search.grid_scores_[0] + assert_equal(first.parameters['C'], 1) + # scores are the same as above + assert_array_almost_equal(first.cv_validation_scores, [1, 1. / 3.]) + # averaged score is just mean of scores + assert_almost_equal(first.mean_validation_score, + np.mean(first.cv_validation_scores)) + + def test_grid_search_one_grid_point(): X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0) param_dict = {"C": [1.0], "kernel": ["rbf"], "gamma": [0.1]} @@ -121,18 +325,18 @@ def test_grid_search_sparse(): assert_equal(C, C2) -def test_grid_search_sparse_score_func(): +def test_grid_search_sparse_scoring(): X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0) clf = LinearSVC() - cv = GridSearchCV(clf, {'C': [0.1, 1.0]}, score_func=f1_score) + cv = GridSearchCV(clf, {'C': [0.1, 1.0]}, scoring="f1") cv.fit(X_[:180], y_[:180]) y_pred = cv.predict(X_[180:]) C = cv.best_estimator_.C X_ = sp.csr_matrix(X_) clf = LinearSVC() - cv = GridSearchCV(clf, {'C': [0.1, 1.0]}, score_func=f1_score) + cv = GridSearchCV(clf, {'C': [0.1, 1.0]}, scoring="f1") cv.fit(X_[:180], y_[:180]) y_pred2 = cv.predict(X_[180:]) C2 = cv.best_estimator_.C @@ -143,6 +347,18 @@ def test_grid_search_sparse_score_func(): #np.testing.assert_allclose(f1_score(cv.predict(X_[:180]), y[:180]), # cv.score(X_[:180], y[:180])) + # test loss where greater is worse + def f1_loss(y_true_, y_pred_): + return -f1_score(y_true_, y_pred_) + F1Loss = make_scorer(f1_loss, greater_is_better=False) + cv = GridSearchCV(clf, {'C': [0.1, 1.0]}, scoring=F1Loss) + cv.fit(X_[:180], y_[:180]) + y_pred3 = cv.predict(X_[180:]) + C3 = cv.best_estimator_.C + + assert_equal(C, C3) + assert_array_equal(y_pred, y_pred3) + def test_grid_search_precomputed_kernel(): """Test that grid search works when the input features are given in the @@ -167,6 +383,10 @@ def test_grid_search_precomputed_kernel(): assert_true(np.mean(y_pred == y_test) >= 0) + # test error is raised when the precomputed kernel is not array-like + # or sparse + assert_raises(ValueError, cv.fit, K_train.tolist(), y_train) + def test_grid_search_precomputed_kernel_error_nonsquare(): """Test that grid search returns an error with a non-square precomputed @@ -211,17 +431,344 @@ def test_refit(): y = np.array([0] * 5 + [1] * 5) clf = GridSearchCV(BrokenClassifier(), [{'parameter': [0, 1]}], - score_func=precision_score, refit=True) + scoring="precision", refit=True) clf.fit(X, y) +def test_gridsearch_nd(): + """Pass X as list in GridSearchCV""" + X_4d = np.arange(10 * 5 * 3 * 2).reshape(10, 5, 3, 2) + y_3d = np.arange(10 * 7 * 11).reshape(10, 7, 11) + check_X = lambda x: x.shape[1:] == (5, 3, 2) + check_y = lambda x: x.shape[1:] == (7, 11) + clf = CheckingClassifier(check_X=check_X, check_y=check_y) + grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}) + grid_search.fit(X_4d, y_3d).score(X, y) + assert_true(hasattr(grid_search, "grid_scores_")) + + def test_X_as_list(): - """Pass X as list in GridSearchCV - """ + """Pass X as list in GridSearchCV""" X = np.arange(100).reshape(10, 10) y = np.array([0] * 5 + [1] * 5) - clf = MockClassifier() - cv = KFold(n=len(X), k=3) + clf = CheckingClassifier(check_X=lambda x: isinstance(x, list)) + cv = KFold(n=len(X), n_folds=3) grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}, cv=cv) grid_search.fit(X.tolist(), y).score(X, y) + assert_true(hasattr(grid_search, "grid_scores_")) + + +def test_y_as_list(): + """Pass y as list in GridSearchCV""" + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + + clf = CheckingClassifier(check_y=lambda x: isinstance(x, list)) + cv = KFold(n=len(X), n_folds=3) + grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}, cv=cv) + grid_search.fit(X, y.tolist()).score(X, y) + assert_true(hasattr(grid_search, "grid_scores_")) + + +def test_pandas_input(): + # check cross_val_score doesn't destroy pandas dataframe + types = [(MockDataFrame, MockDataFrame)] + try: + from pandas import Series, DataFrame + types.append((DataFrame, Series)) + except ImportError: + pass + + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + + for InputFeatureType, TargetType in types: + # X dataframe, y series + X_df, y_ser = InputFeatureType(X), TargetType(y) + check_df = lambda x: isinstance(x, InputFeatureType) + check_series = lambda x: isinstance(x, TargetType) + clf = CheckingClassifier(check_X=check_df, check_y=check_series) + + grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}) + grid_search.fit(X_df, y_ser).score(X_df, y_ser) + grid_search.predict(X_df) + assert_true(hasattr(grid_search, "grid_scores_")) + + +def test_unsupervised_grid_search(): + # test grid-search with unsupervised estimator + X, y = make_blobs(random_state=0) + km = KMeans(random_state=0) + grid_search = GridSearchCV(km, param_grid=dict(n_clusters=[2, 3, 4]), + scoring='adjusted_rand_score') + grid_search.fit(X, y) + # ARI can find the right number :) + assert_equal(grid_search.best_params_["n_clusters"], 3) + + # Now without a score, and without y + grid_search = GridSearchCV(km, param_grid=dict(n_clusters=[2, 3, 4])) + grid_search.fit(X) + assert_equal(grid_search.best_params_["n_clusters"], 4) + + +def test_gridsearch_no_predict(): + # test grid-search with an estimator without predict. + # slight duplication of a test from KDE + def custom_scoring(estimator, X): + return 42 if estimator.bandwidth == .1 else 0 + X, _ = make_blobs(cluster_std=.1, random_state=1, + centers=[[0, 1], [1, 0], [0, 0]]) + search = GridSearchCV(KernelDensity(), + param_grid=dict(bandwidth=[.01, .1, 1]), + scoring=custom_scoring) + search.fit(X) + assert_equal(search.best_params_['bandwidth'], .1) + assert_equal(search.best_score_, 42) + + +def test_param_sampler(): + # test basic properties of param sampler + param_distributions = {"kernel": ["rbf", "linear"], + "C": uniform(0, 1)} + sampler = ParameterSampler(param_distributions=param_distributions, + n_iter=10, random_state=0) + samples = [x for x in sampler] + assert_equal(len(samples), 10) + for sample in samples: + assert_true(sample["kernel"] in ["rbf", "linear"]) + assert_true(0 <= sample["C"] <= 1) + + +def test_randomized_search_grid_scores(): + # Make a dataset with a lot of noise to get various kind of prediction + # errors across CV folds and parameter settings + X, y = make_classification(n_samples=200, n_features=100, n_informative=3, + random_state=0) + + # XXX: as of today (scipy 0.12) it's not possible to set the random seed + # of scipy.stats distributions: the assertions in this test should thus + # not depend on the randomization + params = dict(C=expon(scale=10), + gamma=expon(scale=0.1)) + n_cv_iter = 3 + n_search_iter = 30 + search = RandomizedSearchCV(SVC(), n_iter=n_search_iter, cv=n_cv_iter, + param_distributions=params, iid=False) + search.fit(X, y) + assert_equal(len(search.grid_scores_), n_search_iter) + + # Check consistency of the structure of each cv_score item + for cv_score in search.grid_scores_: + assert_equal(len(cv_score.cv_validation_scores), n_cv_iter) + # Because we set iid to False, the mean_validation score is the + # mean of the fold mean scores instead of the aggregate sample-wise + # mean score + assert_almost_equal(np.mean(cv_score.cv_validation_scores), + cv_score.mean_validation_score) + assert_equal(list(sorted(cv_score.parameters.keys())), + list(sorted(params.keys()))) + + # Check the consistency with the best_score_ and best_params_ attributes + sorted_grid_scores = list(sorted(search.grid_scores_, + key=lambda x: x.mean_validation_score)) + best_score = sorted_grid_scores[-1].mean_validation_score + assert_equal(search.best_score_, best_score) + + tied_best_params = [s.parameters for s in sorted_grid_scores + if s.mean_validation_score == best_score] + assert_true(search.best_params_ in tied_best_params, + "best_params_={0} is not part of the" + " tied best models: {1}".format( + search.best_params_, tied_best_params)) + + +def test_grid_search_score_consistency(): + # test that correct scores are used + clf = LinearSVC(random_state=0) + X, y = make_blobs(random_state=0, centers=2) + Cs = [.1, 1, 10] + for score in ['f1', 'roc_auc']: + grid_search = GridSearchCV(clf, {'C': Cs}, scoring=score) + grid_search.fit(X, y) + cv = StratifiedKFold(n_folds=3, y=y) + for C, scores in zip(Cs, grid_search.grid_scores_): + clf.set_params(C=C) + scores = scores[2] # get the separate runs from grid scores + i = 0 + for train, test in cv: + clf.fit(X[train], y[train]) + if score == "f1": + correct_score = f1_score(y[test], clf.predict(X[test])) + elif score == "roc_auc": + dec = clf.decision_function(X[test]) + correct_score = roc_auc_score(y[test], dec) + assert_almost_equal(correct_score, scores[i]) + i += 1 + + +def test_pickle(): + """Test that a fit search can be pickled""" + clf = MockClassifier() + grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]}, refit=True) + grid_search.fit(X, y) + pickle.dumps(grid_search) # smoke test + + random_search = RandomizedSearchCV(clf, {'foo_param': [1, 2, 3]}, + refit=True, n_iter=3) + random_search.fit(X, y) + pickle.dumps(random_search) # smoke test + + +def test_grid_search_with_multioutput_data(): + """ Test search with multi-output estimator""" + + X, y = make_multilabel_classification(return_indicator=True, + random_state=0) + + est_parameters = {"max_depth": [1, 2, 3, 4]} + cv = KFold(y.shape[0], random_state=0) + + estimators = [DecisionTreeRegressor(random_state=0), + DecisionTreeClassifier(random_state=0)] + + # Test with grid search cv + for est in estimators: + grid_search = GridSearchCV(est, est_parameters, cv=cv) + grid_search.fit(X, y) + for parameters, _, cv_validation_scores in grid_search.grid_scores_: + est.set_params(**parameters) + + for i, (train, test) in enumerate(cv): + est.fit(X[train], y[train]) + correct_score = est.score(X[test], y[test]) + assert_almost_equal(correct_score, + cv_validation_scores[i]) + + # Test with a randomized search + for est in estimators: + random_search = RandomizedSearchCV(est, est_parameters, cv=cv, n_iter=3) + random_search.fit(X, y) + for parameters, _, cv_validation_scores in random_search.grid_scores_: + est.set_params(**parameters) + + for i, (train, test) in enumerate(cv): + est.fit(X[train], y[train]) + correct_score = est.score(X[test], y[test]) + assert_almost_equal(correct_score, + cv_validation_scores[i]) + + +def test_predict_proba_disabled(): + """Test predict_proba when disabled on estimator.""" + X = np.arange(20).reshape(5, -1) + y = [0, 0, 1, 1, 1] + clf = SVC(probability=False) + gs = GridSearchCV(clf, {}, cv=2).fit(X, y) + assert_false(hasattr(gs, "predict_proba")) + + +def test_grid_search_allows_nans(): + """ Test GridSearchCV with Imputer """ + X = np.arange(20, dtype=np.float64).reshape(5, -1) + X[2, :] = np.nan + y = [0, 0, 1, 1, 1] + p = Pipeline([ + ('imputer', Imputer(strategy='mean', missing_values='NaN')), + ('classifier', MockClassifier()), + ]) + GridSearchCV(p, {'classifier__foo_param': [1, 2, 3]}, cv=2).fit(X, y) + + +class FailingClassifier(BaseEstimator): + """Classifier that raises a ValueError on fit()""" + + FAILING_PARAMETER = 2 + + def __init__(self, parameter=None): + self.parameter = parameter + + def fit(self, X, y=None): + if self.parameter == FailingClassifier.FAILING_PARAMETER: + raise ValueError("Failing classifier failed as required") + + def predict(self, X): + return np.zeros(X.shape[0]) + + +def test_grid_search_failing_classifier(): + """GridSearchCV with on_error != 'raise' + + Ensures that a warning is raised and score reset where appropriate. + """ + + X, y = make_classification(n_samples=20, n_features=10, random_state=0) + + clf = FailingClassifier() + + # refit=False because we only want to check that errors caused by fits + # to individual folds will be caught and warnings raised instead. If + # refit was done, then an exception would be raised on refit and not + # caught by grid_search (expected behavior), and this would cause an + # error in this test. + gs = GridSearchCV(clf, [{'parameter': [0, 1, 2]}], scoring='accuracy', + refit=False, error_score=0.0) + + assert_warns(FitFailedWarning, gs.fit, X, y) + + # Ensure that grid scores were set to zero as required for those fits + # that are expected to fail. + assert all(np.all(this_point.cv_validation_scores == 0.0) + for this_point in gs.grid_scores_ + if this_point.parameters['parameter'] == + FailingClassifier.FAILING_PARAMETER) + + gs = GridSearchCV(clf, [{'parameter': [0, 1, 2]}], scoring='accuracy', + refit=False, error_score=float('nan')) + assert_warns(FitFailedWarning, gs.fit, X, y) + assert all(np.all(np.isnan(this_point.cv_validation_scores)) + for this_point in gs.grid_scores_ + if this_point.parameters['parameter'] == + FailingClassifier.FAILING_PARAMETER) + + +def test_grid_search_failing_classifier_raise(): + """GridSearchCV with on_error == 'raise' raises the error""" + + X, y = make_classification(n_samples=20, n_features=10, random_state=0) + + clf = FailingClassifier() + + # refit=False because we want to test the behaviour of the grid search part + gs = GridSearchCV(clf, [{'parameter': [0, 1, 2]}], scoring='accuracy', + refit=False, error_score='raise') + + # FailingClassifier issues a ValueError so this is what we look for. + assert_raises(ValueError, gs.fit, X, y) + + +def test_parameters_sampler_replacement(): + # raise error if n_iter too large + params = {'first': [0, 1], 'second': ['a', 'b', 'c']} + sampler = ParameterSampler(params, n_iter=7) + assert_raises(ValueError, list, sampler) + # degenerates to GridSearchCV if n_iter the same as grid_size + sampler = ParameterSampler(params, n_iter=6) + samples = list(sampler) + assert_equal(len(samples), 6) + for values in ParameterGrid(params): + assert_true(values in samples) + + # test sampling without replacement in a large grid + params = {'a': range(10), 'b': range(10), 'c': range(10)} + sampler = ParameterSampler(params, n_iter=99, random_state=42) + samples = list(sampler) + assert_equal(len(samples), 99) + hashable_samples = ["a%db%dc%d" % (p['a'], p['b'], p['c']) for p in samples] + assert_equal(len(set(hashable_samples)), 99) + + # doesn't go into infinite loops + params_distribution = {'first': bernoulli(.5), 'second': ['a', 'b', 'c']} + sampler = ParameterSampler(params_distribution, n_iter=7) + samples = list(sampler) + assert_equal(len(samples), 7) diff --git a/sklearn/tests/test_hmm.py b/sklearn/tests/test_hmm.py index d2e2b503bc3fc..0a0d8de295520 100644 --- a/sklearn/tests/test_hmm.py +++ b/sklearn/tests/test_hmm.py @@ -1,3 +1,4 @@ +from __future__ import print_function import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal @@ -54,6 +55,18 @@ def test_init(self): for p in params: assert_array_almost_equal(getattr(h, p), getattr(h2, p)) + def test_set_startprob(self): + h, framelogprob = self.setup_example_hmm() + startprob = np.array([0.0, 1.0]) + h.startprob_ = startprob + assert np.allclose(startprob, h.startprob_) + + def test_set_transmat(self): + h, framelogprob = self.setup_example_hmm() + transmat = np.array([[0.8, 0.2], [0.0, 1.0]]) + h.transmat_ = transmat + assert np.allclose(transmat, h.transmat_) + def test_do_forward_pass(self): h, framelogprob = self.setup_example_hmm() @@ -92,11 +105,11 @@ def test_do_viterbi_pass(self): reflogprob = -4.4590 self.assertAlmostEqual(logprob, reflogprob, places=4) - def test_eval(self): + def test_score_samples(self): h, framelogprob = self.setup_example_hmm() nobs = len(framelogprob) - logprob, posteriors = h.eval([]) + logprob, posteriors = h.score_samples([]) assert_array_almost_equal(posteriors.sum(axis=1), np.ones(nobs)) @@ -110,7 +123,7 @@ def test_eval(self): [0.8673, 0.1327]]) assert_array_almost_equal(posteriors, refposteriors, decimal=4) - def test_hmm_eval_consistent_with_gmm(self): + def test_hmm_score_samples_consistent_with_gmm(self): n_components = 8 nobs = 10 h = self.StubHMM(n_components) @@ -123,7 +136,7 @@ def test_hmm_eval_consistent_with_gmm(self): # default), the transitions are uninformative - the model # reduces to a GMM with uniform mixing weights (in terms of # posteriors, not likelihoods). - logprob, hmmposteriors = h.eval([]) + logprob, hmmposteriors = h.score_samples([]) assert_array_almost_equal(hmmposteriors.sum(axis=1), np.ones(nobs)) @@ -161,7 +174,7 @@ def test_base_hmm_attributes(self): h = self.StubHMM(n_components) - self.assertEquals(h.n_components, n_components) + self.assertEqual(h.n_components, n_components) h.startprob_ = startprob assert_array_almost_equal(h.startprob_, startprob) @@ -185,7 +198,7 @@ def train_hmm_and_keep_track_of_log_likelihood(hmm, obs, n_iter=1, **kwargs): hmm.n_iter = 1 hmm.fit(obs) loglikelihoods = [] - for n in xrange(n_iter): + for n in range(n_iter): hmm.n_iter = 1 hmm.init_params = '' hmm.fit(obs) @@ -203,7 +216,7 @@ def setUp(self): self.startprob = self.startprob / self.startprob.sum() self.transmat = prng.rand(n_components, n_components) self.transmat /= np.tile(self.transmat.sum(axis=1)[:, np.newaxis], - (1, n_components)) + (1, n_components)) self.means = prng.randint(-20, 20, (n_components, n_features)) self.covars = { 'spherical': (1.0 + 2 * np.dot(prng.rand(n_components, 1), @@ -226,45 +239,9 @@ def setUp(self): def test_bad_covariance_type(self): hmm.GaussianHMM(20, self.covariance_type) self.assertRaises(ValueError, hmm.GaussianHMM, 20, - 'badcovariance_type') - - def _test_attributes(self): - # XXX: This test is bugged and creates weird errors -- skipped - h = hmm.GaussianHMM(self.n_components, self.covariance_type) - - self.assertEquals(h.n_components, self.n_components) - self.assertEquals(h.covariance_type, self.covariance_type) - - h.startprob_ = self.startprob - assert_array_almost_equal(h.startprob_, self.startprob) - self.assertRaises(ValueError, h.__setattr__, 'startprob_', - 2 * self.startprob) - self.assertRaises(ValueError, h.__setattr__, 'startprob_', []) - self.assertRaises(ValueError, h.__setattr__, 'startprob_', - np.zeros((self.n_components - 2, self.n_features))) - - h.transmat_ = self.transmat - assert_array_almost_equal(h.transmat_, self.transmat) - self.assertRaises(ValueError, h.__setattr__, 'transmat_', - 2 * self.transmat) - self.assertRaises(ValueError, h.__setattr__, 'transmat_', []) - self.assertRaises(ValueError, h.__setattr__, 'transmat_', - np.zeros((self.n_components - 2, self.n_components))) - - h.means_ = self.means - self.assertEquals(h.n_features, self.n_features) - self.assertRaises(ValueError, h.__setattr__, 'means_', []) - self.assertRaises(ValueError, h.__setattr__, 'means_', - np.zeros((self.n_components - 2, self.n_features))) + 'badcovariance_type') - h.covars_ = self.covars[self.covariance_type] - assert_array_almost_equal(h.covars_, - self.expanded_covars[self.covariance_type]) - #self.assertRaises(ValueError, h.__setattr__, 'covars', []) - #self.assertRaises(ValueError, h.__setattr__, 'covars', - # np.zeros((self.n_components - 2, self.n_features))) - - def test_eval_and_decode(self): + def test_score_samples_and_decode(self): h = hmm.GaussianHMM(self.n_components, self.covariance_type) h.means_ = self.means h.covars_ = self.covars[self.covariance_type] @@ -273,11 +250,11 @@ def test_eval_and_decode(self): # picks the actual component used to generate the observations. h.means_ = 20 * h.means_ - gaussidx = np.repeat(range(self.n_components), 5) + gaussidx = np.repeat(np.arange(self.n_components), 5) nobs = len(gaussidx) obs = self.prng.randn(nobs, self.n_features) + h.means_[gaussidx] - ll, posteriors = h.eval(obs) + ll, posteriors = h.score_samples(obs) self.assertEqual(posteriors.shape, (nobs, self.n_components)) assert_array_almost_equal(posteriors.sum(axis=1), np.ones(nobs)) @@ -294,18 +271,18 @@ def test_sample(self, n=1000): h.startprob_ = self.startprob samples = h.sample(n)[0] - self.assertEquals(samples.shape, (n, self.n_features)) + self.assertEqual(samples.shape, (n, self.n_features)) def test_fit(self, params='stmc', n_iter=5, verbose=False, **kwargs): h = hmm.GaussianHMM(self.n_components, self.covariance_type) h.startprob_ = self.startprob - h.transmat_ = hmm.normalize(self.transmat - + np.diag(self.prng.rand(self.n_components)), 1) + h.transmat_ = hmm.normalize( + self.transmat + np.diag(self.prng.rand(self.n_components)), 1) h.means_ = 20 * self.means h.covars_ = self.covars[self.covariance_type] # Create training data by sampling from the HMM. - train_obs = [h.sample(n=10)[0] for x in xrange(10)] + train_obs = [h.sample(n=10)[0] for x in range(10)] # Mess up the parameters and see if we can re-learn them. h.n_iter = 0 @@ -316,10 +293,8 @@ def test_fit(self, params='stmc', n_iter=5, verbose=False, **kwargs): # Check that the loglik is always increasing during training if not np.all(np.diff(trainll) > 0) and verbose: - print - print ('Test train: %s (%s)\n %s\n %s' - % (self.covariance_type, params, trainll, np.diff(trainll))) - + print('Test train: %s (%s)\n %s\n %s' + % (self.covariance_type, params, trainll, np.diff(trainll))) delta_min = np.diff(trainll).min() self.assertTrue( delta_min > -0.8, @@ -337,6 +312,15 @@ def test_fit_works_on_sequences_of_different_length(self): # ValueError: setting an array element with a sequence. h.fit(obs) + def test_fit_with_length_one_signal(self): + obs = [self.prng.rand(10, self.n_features), + self.prng.rand(8, self.n_features), + self.prng.rand(1, self.n_features)] + h = hmm.GaussianHMM(self.n_components, self.covariance_type) + # This shouldn't raise + # ValueError: zero-size array to reduction operation maximum which has no identity + h.fit(obs) + def test_fit_with_priors(self, params='stmc', n_iter=5, verbose=False): startprob_prior = 10 * self.startprob + 2.0 transmat_prior = 10 * self.transmat + 2.0 @@ -350,8 +334,8 @@ def test_fit_with_priors(self, params='stmc', n_iter=5, verbose=False): h = hmm.GaussianHMM(self.n_components, self.covariance_type) h.startprob_ = self.startprob h.startprob_prior = startprob_prior - h.transmat_ = hmm.normalize(self.transmat - + np.diag(self.prng.rand(self.n_components)), 1) + h.transmat_ = hmm.normalize( + self.transmat + np.diag(self.prng.rand(self.n_components)), 1) h.transmat_prior = transmat_prior h.means_ = 20 * self.means h.means_prior = means_prior @@ -361,7 +345,7 @@ def test_fit_with_priors(self, params='stmc', n_iter=5, verbose=False): h.covars_weight = covars_weight # Create training data by sampling from the HMM. - train_obs = [h.sample(n=10)[0] for x in xrange(10)] + train_obs = [h.sample(n=10)[0] for x in range(10)] # Mess up the parameters and see if we can re-learn them. h.n_iter = 0 @@ -372,12 +356,30 @@ def test_fit_with_priors(self, params='stmc', n_iter=5, verbose=False): # Check that the loglik is always increasing during training if not np.all(np.diff(trainll) > 0) and verbose: - print - print ('Test MAP train: %s (%s)\n %s\n %s' - % (self.covariance_type, params, trainll, np.diff(trainll))) + print('Test MAP train: %s (%s)\n %s\n %s' + % (self.covariance_type, params, trainll, np.diff(trainll))) # XXX: Why such a large tolerance? self.assertTrue(np.all(np.diff(trainll) > -0.5)) + def test_fit_non_ergodic_transmat(self): + startprob = np.array([1, 0, 0, 0, 0]) + transmat = np.array([[0.9, 0.1, 0, 0, 0], + [0, 0.9, 0.1, 0, 0], + [0, 0, 0.9, 0.1, 0], + [0, 0, 0, 0.9, 0.1], + [0, 0, 0, 0, 1.0]]) + + h = hmm.GaussianHMM(n_components=5, + covariance_type='full', startprob=startprob, + transmat=transmat, n_iter=100, init_params='st') + + h.means_ = np.zeros((5, 10)) + h.covars_ = np.tile(np.identity(10), (5, 1, 1)) + + obs = [h.sample(10)[0] for _ in range(10)] + + h.fit(obs=obs) + class TestGaussianHMMWithSphericalCovars(GaussianHMMBaseTester, TestCase): covariance_type = 'spherical' @@ -414,10 +416,16 @@ def setUp(self): self.transmat = [[0.7, 0.3], [0.4, 0.6]] self.h = hmm.MultinomialHMM(self.n_components, - startprob=self.startprob, - transmat=self.transmat) + startprob=self.startprob, + transmat=self.transmat) self.h.emissionprob_ = self.emissionprob + def test_set_emissionprob(self): + h = hmm.MultinomialHMM(self.n_components) + emissionprob = np.array([[0.8, 0.2, 0.0], [0.7, 0.2, 1.0]]) + h.emissionprob = emissionprob + assert np.allclose(emissionprob, h.emissionprob) + def test_wikipedia_viterbi_example(self): # From http://en.wikipedia.org/wiki/Viterbi_algorithm: # "This reveals that the observations ['walk', 'shop', 'clean'] @@ -428,10 +436,29 @@ def test_wikipedia_viterbi_example(self): self.assertAlmostEqual(np.exp(logprob), 0.01344) assert_array_equal(state_sequence, [1, 0, 0]) + def test_decode_map_algorithm(self): + observations = [0, 1, 2] + h = hmm.MultinomialHMM(self.n_components, startprob=self.startprob, + transmat=self.transmat, algorithm="map",) + h.emissionprob_ = self.emissionprob + logprob, state_sequence = h.decode(observations) + assert_array_equal(state_sequence, [1, 0, 0]) + + def test_predict(self): + observations = [0, 1, 2] + state_sequence = self.h.predict(observations) + posteriors = self.h.predict_proba(observations) + assert_array_equal(state_sequence, [1, 0, 0]) + assert_array_almost_equal(posteriors, [ + [0.23170303, 0.76829697], + [0.62406281, 0.37593719], + [0.86397706, 0.13602294], + ]) + def test_attributes(self): h = hmm.MultinomialHMM(self.n_components) - self.assertEquals(h.n_components, self.n_components) + self.assertEqual(h.n_components, self.n_components) h.startprob_ = self.startprob assert_array_almost_equal(h.startprob_, self.startprob) @@ -454,33 +481,33 @@ def test_attributes(self): self.assertRaises(ValueError, h.__setattr__, 'emissionprob_', []) self.assertRaises(ValueError, h.__setattr__, 'emissionprob_', np.zeros((self.n_components - 2, self.n_symbols))) - self.assertEquals(h.n_symbols, self.n_symbols) + self.assertEqual(h.n_symbols, self.n_symbols) - def test_eval(self): - idx = np.repeat(range(self.n_components), 10) + def test_score_samples(self): + idx = np.repeat(np.arange(self.n_components), 10) nobs = len(idx) obs = [int(x) for x in np.floor(self.prng.rand(nobs) * self.n_symbols)] - ll, posteriors = self.h.eval(obs) + ll, posteriors = self.h.score_samples(obs) self.assertEqual(posteriors.shape, (nobs, self.n_components)) assert_array_almost_equal(posteriors.sum(axis=1), np.ones(nobs)) def test_sample(self, n=1000): samples = self.h.sample(n)[0] - self.assertEquals(len(samples), n) - self.assertEquals(len(np.unique(samples)), self.n_symbols) + self.assertEqual(len(samples), n) + self.assertEqual(len(np.unique(samples)), self.n_symbols) def test_fit(self, params='ste', n_iter=5, verbose=False, **kwargs): h = self.h # Create training data by sampling from the HMM. - train_obs = [h.sample(n=10)[0] for x in xrange(10)] + train_obs = [h.sample(n=10)[0] for x in range(10)] # Mess up the parameters and see if we can re-learn them. h.startprob_ = hmm.normalize(self.prng.rand(self.n_components)) h.transmat_ = hmm.normalize(self.prng.rand(self.n_components, - self.n_components), axis=1) + self.n_components), axis=1) h.emissionprob_ = hmm.normalize( self.prng.rand(self.n_components, self.n_symbols), axis=1) @@ -489,14 +516,34 @@ def test_fit(self, params='ste', n_iter=5, verbose=False, **kwargs): # Check that the loglik is always increasing during training if not np.all(np.diff(trainll) > 0) and verbose: - print - print 'Test train: (%s)\n %s\n %s' % (params, trainll, - np.diff(trainll)) - self.assertTrue(np.all(np.diff(trainll) > - 1.e-3)) + print('Test train: (%s)\n %s\n %s' % (params, trainll, + np.diff(trainll))) + self.assertTrue(np.all(np.diff(trainll) > -1.e-3)) def test_fit_emissionprob(self): self.test_fit('e') + def test_fit_with_init(self, params='ste', n_iter=5, verbose=False, + **kwargs): + h = self.h + learner = hmm.MultinomialHMM(self.n_components) + + # Create training data by sampling from the HMM. + train_obs = [h.sample(n=10)[0] for x in range(10)] + + # use init_function to initialize paramerters + learner._init(train_obs, params) + + trainll = train_hmm_and_keep_track_of_log_likelihood( + learner, train_obs, n_iter=n_iter, params=params, **kwargs)[1:] + + # Check that the loglik is always increasing during training + if not np.all(np.diff(trainll) > 0) and verbose: + print() + print('Test train: (%s)\n %s\n %s' % (params, trainll, + np.diff(trainll))) + self.assertTrue(np.all(np.diff(trainll) > -1.e-3)) + def create_random_gmm(n_mix, n_features, covariance_type, prng=0): prng = check_random_state(prng) @@ -511,7 +558,7 @@ def create_random_gmm(n_mix, n_features, covariance_type, prng=0): 'diag': (mincv + mincv * prng.rand(n_mix, n_features)) ** 2, 'full': np.array( [make_spd_matrix(n_features, random_state=prng) - + mincv * np.eye(n_features) for x in xrange(n_mix)]) + + mincv * np.eye(n_features) for x in range(n_mix)]) }[covariance_type] g.weights_ = hmm.normalize(prng.rand(n_mix)) return g @@ -531,16 +578,16 @@ def setUp(self): self.transmat /= np.tile(self.transmat.sum(axis=1)[:, np.newaxis], (1, self.n_components)) - self.gmms = [] - for state in xrange(self.n_components): - self.gmms.append(create_random_gmm( + self.gmms_ = [] + for state in range(self.n_components): + self.gmms_.append(create_random_gmm( self.n_mix, self.n_features, self.covariance_type, prng=self.prng)) def test_attributes(self): h = hmm.GMMHMM(self.n_components, covariance_type=self.covariance_type) - self.assertEquals(h.n_components, self.n_components) + self.assertEqual(h.n_components, self.n_components) h.startprob_ = self.startprob assert_array_almost_equal(h.startprob_, self.startprob) @@ -558,18 +605,18 @@ def test_attributes(self): self.assertRaises(ValueError, h.__setattr__, 'transmat_', np.zeros((self.n_components - 2, self.n_components))) - def test_eval_and_decode(self): - h = hmm.GMMHMM(self.n_components, gmms=self.gmms) + def test_score_samples_and_decode(self): + h = hmm.GMMHMM(self.n_components, gmms=self.gmms_) # Make sure the means are far apart so posteriors.argmax() # picks the actual component used to generate the observations. - for g in h.gmms: + for g in h.gmms_: g.means_ *= 20 - refstateseq = np.repeat(range(self.n_components), 5) + refstateseq = np.repeat(np.arange(self.n_components), 5) nobs = len(refstateseq) - obs = [h.gmms[x].sample(1).flatten() for x in refstateseq] + obs = [h.gmms_[x].sample(1).flatten() for x in refstateseq] - ll, posteriors = h.eval(obs) + ll, posteriors = h.score_samples(obs) self.assertEqual(posteriors.shape, (nobs, self.n_components)) assert_array_almost_equal(posteriors.sum(axis=1), np.ones(nobs)) @@ -580,20 +627,20 @@ def test_eval_and_decode(self): def test_sample(self, n=1000): h = hmm.GMMHMM(self.n_components, self.covariance_type, startprob=self.startprob, transmat=self.transmat, - gmms=self.gmms) + gmms=self.gmms_) samples = h.sample(n)[0] - self.assertEquals(samples.shape, (n, self.n_features)) + self.assertEqual(samples.shape, (n, self.n_features)) def test_fit(self, params='stmwc', n_iter=5, verbose=False, **kwargs): h = hmm.GMMHMM(self.n_components, covars_prior=1.0) h.startprob_ = self.startprob h.transmat_ = hmm.normalize( self.transmat + np.diag(self.prng.rand(self.n_components)), 1) - h.gmms = self.gmms + h.gmms_ = self.gmms_ # Create training data by sampling from the HMM. - train_obs = [h.sample(n=10, - random_state=self.prng)[0] for x in xrange(10)] + train_obs = [h.sample(n=10, random_state=self.prng)[0] + for x in range(10)] # Mess up the parameters and see if we can re-learn them. h.n_iter = 0 @@ -606,9 +653,8 @@ def test_fit(self, params='stmwc', n_iter=5, verbose=False, **kwargs): h, train_obs, n_iter=n_iter, params=params)[1:] if not np.all(np.diff(trainll) > 0) and verbose: - print - print 'Test train: (%s)\n %s\n %s' % (params, trainll, - np.diff(trainll)) + print('Test train: (%s)\n %s\n %s' % (params, trainll, + np.diff(trainll))) # XXX: this test appears to check that training log likelihood should # never be decreasing (up to a tolerance of 0.5, why?) but this is not diff --git a/sklearn/tests/test_init.py b/sklearn/tests/test_init.py index 1cbcc0a49ff49..a7df69ee77b30 100644 --- a/sklearn/tests/test_init.py +++ b/sklearn/tests/test_init.py @@ -4,7 +4,7 @@ __license__ = 'BSD' -from nose.tools import assert_equal +from sklearn.utils.testing import assert_equal try: from sklearn import * diff --git a/sklearn/tests/test_isotonic.py b/sklearn/tests/test_isotonic.py new file mode 100644 index 0000000000000..f6b48020e0e50 --- /dev/null +++ b/sklearn/tests/test_isotonic.py @@ -0,0 +1,353 @@ +import numpy as np +import pickle + +from sklearn.isotonic import (check_increasing, isotonic_regression, + IsotonicRegression) + +from sklearn.utils.testing import (assert_raises, assert_array_equal, + assert_true, assert_false, assert_equal, + assert_array_almost_equal, + assert_warns_message, assert_no_warnings) +from sklearn.utils import shuffle + + +def test_permutation_invariance(): + # check that fit is permuation invariant. + # regression test of missing sorting of sample-weights + ir = IsotonicRegression() + x = [1, 2, 3, 4, 5, 6, 7] + y = [1, 41, 51, 1, 2, 5, 24] + sample_weight = [1, 2, 3, 4, 5, 6, 7] + x_s, y_s, sample_weight_s = shuffle(x, y, sample_weight, random_state=0) + y_transformed = ir.fit_transform(x, y, sample_weight=sample_weight) + y_transformed_s = ir.fit(x_s, y_s, sample_weight=sample_weight_s).transform(x) + + assert_array_equal(y_transformed, y_transformed_s) + + +def test_check_increasing_up(): + x = [0, 1, 2, 3, 4, 5] + y = [0, 1.5, 2.77, 8.99, 8.99, 50] + + # Check that we got increasing=True and no warnings + is_increasing = assert_no_warnings(check_increasing, x, y) + assert_true(is_increasing) + + +def test_check_increasing_up_extreme(): + x = [0, 1, 2, 3, 4, 5] + y = [0, 1, 2, 3, 4, 5] + + # Check that we got increasing=True and no warnings + is_increasing = assert_no_warnings(check_increasing, x, y) + assert_true(is_increasing) + + +def test_check_increasing_down(): + x = [0, 1, 2, 3, 4, 5] + y = [0, -1.5, -2.77, -8.99, -8.99, -50] + + # Check that we got increasing=False and no warnings + is_increasing = assert_no_warnings(check_increasing, x, y) + assert_false(is_increasing) + + +def test_check_increasing_down_extreme(): + x = [0, 1, 2, 3, 4, 5] + y = [0, -1, -2, -3, -4, -5] + + # Check that we got increasing=False and no warnings + is_increasing = assert_no_warnings(check_increasing, x, y) + assert_false(is_increasing) + + +def test_check_ci_warn(): + x = [0, 1, 2, 3, 4, 5] + y = [0, -1, 2, -3, 4, -5] + + # Check that we got increasing=False and CI interval warning + is_increasing = assert_warns_message(UserWarning, "interval", + check_increasing, + x, y) + + assert_false(is_increasing) + + +def test_isotonic_regression(): + y = np.array([3, 7, 5, 9, 8, 7, 10]) + y_ = np.array([3, 6, 6, 8, 8, 8, 10]) + assert_array_equal(y_, isotonic_regression(y)) + + x = np.arange(len(y)) + ir = IsotonicRegression(y_min=0., y_max=1.) + ir.fit(x, y) + assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) + assert_array_equal(ir.transform(x), ir.predict(x)) + + # check that it is immune to permutation + perm = np.random.permutation(len(y)) + ir = IsotonicRegression(y_min=0., y_max=1.) + assert_array_equal(ir.fit_transform(x[perm], y[perm]), + ir.fit_transform(x, y)[perm]) + assert_array_equal(ir.transform(x[perm]), ir.transform(x)[perm]) + + # check we don't crash when all x are equal: + ir = IsotonicRegression() + assert_array_equal(ir.fit_transform(np.ones(len(x)), y), np.mean(y)) + + +def test_isotonic_regression_ties_min(): + # Setup examples with ties on minimum + x = [0, 1, 1, 2, 3, 4, 5] + y = [0, 1, 2, 3, 4, 5, 6] + y_true = [0, 1.5, 1.5, 3, 4, 5, 6] + + # Check that we get identical results for fit/transform and fit_transform + ir = IsotonicRegression() + ir.fit(x, y) + assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) + assert_array_equal(y_true, ir.fit_transform(x, y)) + + +def test_isotonic_regression_ties_max(): + # Setup examples with ties on maximum + x = [1, 2, 3, 4, 5, 5] + y = [1, 2, 3, 4, 5, 6] + y_true = [1, 2, 3, 4, 5.5, 5.5] + + # Check that we get identical results for fit/transform and fit_transform + ir = IsotonicRegression() + ir.fit(x, y) + assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) + assert_array_equal(y_true, ir.fit_transform(x, y)) + + +def test_isotonic_regression_ties_secondary_(): + """ + Test isotonic regression fit, transform and fit_transform + against the "secondary" ties method and "pituitary" data from R + "isotone" package, as detailed in: J. d. Leeuw, K. Hornik, P. Mair, + Isotone Optimization in R: Pool-Adjacent-Violators Algorithm + (PAVA) and Active Set Methods + + Set values based on pituitary example and + the following R command detailed in the paper above: + > library("isotone") + > data("pituitary") + > res1 <- gpava(pituitary$age, pituitary$size, ties="secondary") + > res1$x + + `isotone` version: 1.0-2, 2014-09-07 + R version: R version 3.1.1 (2014-07-10) + """ + x = [8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14] + y = [21, 23.5, 23, 24, 21, 25, 21.5, 22, 19, 23.5, 25] + y_true = [22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 22.22222, + 22.22222, 22.22222, 22.22222, 24.25, 24.25] + + # Check fit, transform and fit_transform + ir = IsotonicRegression() + ir.fit(x, y) + assert_array_almost_equal(ir.transform(x), y_true, 4) + assert_array_almost_equal(ir.fit_transform(x, y), y_true, 4) + + +def test_isotonic_regression_reversed(): + y = np.array([10, 9, 10, 7, 6, 6.1, 5]) + y_ = IsotonicRegression(increasing=False).fit_transform( + np.arange(len(y)), y) + assert_array_equal(np.ones(y_[:-1].shape), ((y_[:-1] - y_[1:]) >= 0)) + + +def test_isotonic_regression_auto_decreasing(): + # Set y and x for decreasing + y = np.array([10, 9, 10, 7, 6, 6.1, 5]) + x = np.arange(len(y)) + + # Create model and fit_transform + ir = IsotonicRegression(increasing='auto') + y_ = assert_no_warnings(ir.fit_transform, x, y) + + # Check that relationship decreases + is_increasing = y_[0] < y_[-1] + assert_false(is_increasing) + + +def test_isotonic_regression_auto_increasing(): + # Set y and x for decreasing + y = np.array([5, 6.1, 6, 7, 10, 9, 10]) + x = np.arange(len(y)) + + # Create model and fit_transform + ir = IsotonicRegression(increasing='auto') + y_ = assert_no_warnings(ir.fit_transform, x, y) + + # Check that relationship increases + is_increasing = y_[0] < y_[-1] + assert_true(is_increasing) + + +def test_assert_raises_exceptions(): + ir = IsotonicRegression() + rng = np.random.RandomState(42) + assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) + assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) + assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2]) + assert_raises(ValueError, ir.transform, rng.randn(3, 10)) + + +def test_isotonic_sample_weight_parameter_default_value(): + # check if default value of sample_weight parameter is one + ir = IsotonicRegression() + # random test data + rng = np.random.RandomState(42) + n = 100 + x = np.arange(n) + y = rng.randint(-50, 50, size=(n,)) + 50. * np.log(1 + np.arange(n)) + # check if value is correctly used + weights = np.ones(n) + y_set_value = ir.fit_transform(x, y, sample_weight=weights) + y_default_value = ir.fit_transform(x, y) + + assert_array_equal(y_set_value, y_default_value) + + +def test_isotonic_min_max_boundaries(): + # check if min value is used correctly + ir = IsotonicRegression(y_min=2, y_max=4) + n = 6 + x = np.arange(n) + y = np.arange(n) + y_test = [2, 2, 2, 3, 4, 4] + y_result = np.round(ir.fit_transform(x, y)) + assert_array_equal(y_result, y_test) + + +def test_isotonic_sample_weight(): + ir = IsotonicRegression() + x = [1, 2, 3, 4, 5, 6, 7] + y = [1, 41, 51, 1, 2, 5, 24] + sample_weight = [1, 2, 3, 4, 5, 6, 7] + expected_y = [1, 13.95, 13.95, 13.95, 13.95, 13.95, 24] + received_y = ir.fit_transform(x, y, sample_weight=sample_weight) + + assert_array_equal(expected_y, received_y) + + +def test_isotonic_regression_oob_raise(): + # Set y and x + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="raise") + ir.fit(x, y) + + # Check that an exception is thrown + assert_raises(ValueError, ir.predict, [min(x) - 10, max(x) + 10]) + + +def test_isotonic_regression_oob_clip(): + # Set y and x + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="clip") + ir.fit(x, y) + + # Predict from training and test x and check that min/max match. + y1 = ir.predict([min(x) - 10, max(x) + 10]) + y2 = ir.predict(x) + assert_equal(max(y1), max(y2)) + assert_equal(min(y1), min(y2)) + + +def test_isotonic_regression_oob_nan(): + # Set y and x + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="nan") + ir.fit(x, y) + + # Predict from training and test x and check that we have two NaNs. + y1 = ir.predict([min(x) - 10, max(x) + 10]) + assert_equal(sum(np.isnan(y1)), 2) + + +def test_isotonic_regression_oob_bad(): + # Set y and x + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="xyz") + + # Make sure that we throw an error for bad out_of_bounds value + assert_raises(ValueError, ir.fit, x, y) + + +def test_isotonic_regression_oob_bad_after(): + # Set y and x + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="raise") + + # Make sure that we throw an error for bad out_of_bounds value in transform + ir.fit(x, y) + ir.out_of_bounds = "xyz" + assert_raises(ValueError, ir.transform, x) + + +def test_isotonic_regression_pickle(): + y = np.array([3, 7, 5, 9, 8, 7, 10]) + x = np.arange(len(y)) + + # Create model and fit + ir = IsotonicRegression(increasing='auto', out_of_bounds="clip") + ir.fit(x, y) + + ir_ser = pickle.dumps(ir, pickle.HIGHEST_PROTOCOL) + ir2 = pickle.loads(ir_ser) + np.testing.assert_array_equal(ir.predict(x), ir2.predict(x)) + + +def test_isotonic_duplicate_min_entry(): + x = [0, 0, 1] + y = [0, 0, 1] + + ir = IsotonicRegression(increasing=True, out_of_bounds="clip") + ir.fit(x, y) + all_predictions_finite = np.all(np.isfinite(ir.predict(x))) + assert_true(all_predictions_finite) + + +def test_isotonic_zero_weight_loop(): + # Test from @ogrisel's issue: + # https://github.com/scikit-learn/scikit-learn/issues/4297 + + # Get deterministic RNG with seed + rng = np.random.RandomState(42) + + # Create regression and samples + regression = IsotonicRegression() + n_samples = 50 + x = np.linspace(-3, 3, n_samples) + y = x + rng.uniform(size=n_samples) + + # Get some random weights and zero out + w = rng.uniform(size=n_samples) + w[5:8] = 0 + regression.fit(x, y, sample_weight=w) + + # This will hang in failure case. + regression.fit(x, y, sample_weight=w) + + +if __name__ == "__main__": + import nose + nose.run(argv=['', __file__]) diff --git a/sklearn/tests/test_kernel_approximation.py b/sklearn/tests/test_kernel_approximation.py index b1d6b4772be5a..e24eda736e5e8 100644 --- a/sklearn/tests/test_kernel_approximation.py +++ b/sklearn/tests/test_kernel_approximation.py @@ -1,10 +1,17 @@ import numpy as np from scipy.sparse import csr_matrix +from sklearn.utils.testing import assert_array_equal, assert_equal, assert_true +from sklearn.utils.testing import assert_not_equal +from sklearn.utils.testing import assert_array_almost_equal, assert_raises +from sklearn.utils.testing import assert_less_equal + +from sklearn.metrics.pairwise import kernel_metrics from sklearn.kernel_approximation import RBFSampler from sklearn.kernel_approximation import AdditiveChi2Sampler from sklearn.kernel_approximation import SkewedChi2Sampler -from sklearn.metrics.pairwise import rbf_kernel +from sklearn.kernel_approximation import Nystroem +from sklearn.metrics.pairwise import polynomial_kernel, rbf_kernel # generate data rng = np.random.RandomState(0) @@ -27,19 +34,49 @@ def test_additive_chi2_sampler(): # reduce to n_samples_x x n_samples_y by summing over features kernel = (large_kernel.sum(axis=2)) - # appoximate kernel mapping + # approximate kernel mapping transform = AdditiveChi2Sampler(sample_steps=3) X_trans = transform.fit_transform(X) Y_trans = transform.transform(Y) + kernel_approx = np.dot(X_trans, Y_trans.T) - np.testing.assert_array_almost_equal(kernel, kernel_approx, 1) + assert_array_almost_equal(kernel, kernel_approx, 1) X_sp_trans = transform.fit_transform(csr_matrix(X)) Y_sp_trans = transform.transform(csr_matrix(Y)) - np.testing.assert_array_equal(X_trans, X_sp_trans.A) - np.testing.assert_array_equal(Y_trans, Y_sp_trans.A) + assert_array_equal(X_trans, X_sp_trans.A) + assert_array_equal(Y_trans, Y_sp_trans.A) + + # test error is raised on negative input + Y_neg = Y.copy() + Y_neg[0, 0] = -1 + assert_raises(ValueError, transform.transform, Y_neg) + + # test error on invalid sample_steps + transform = AdditiveChi2Sampler(sample_steps=4) + assert_raises(ValueError, transform.fit, X) + + # test that the sample interval is set correctly + sample_steps_available = [1, 2, 3] + for sample_steps in sample_steps_available: + + # test that the sample_interval is initialized correctly + transform = AdditiveChi2Sampler(sample_steps=sample_steps) + assert_equal(transform.sample_interval, None) + + # test that the sample_interval is changed in the fit method + transform.fit(X) + assert_not_equal(transform.sample_interval_, None) + + # test that the sample_interval is set correctly + sample_interval = 0.3 + transform = AdditiveChi2Sampler(sample_steps=4, + sample_interval=sample_interval) + assert_equal(transform.sample_interval, sample_interval) + transform.fit(X) + assert_equal(transform.sample_interval_, sample_interval) def test_skewed_chi2_sampler(): @@ -53,18 +90,24 @@ def test_skewed_chi2_sampler(): # we do it in log-space in the hope that it's more stable # this array is n_samples_x x n_samples_y big x n_features - log_kernel = ((np.log(X_c) / 2.) + (np.log(Y_c) / 2.) + - np.log(2.) - np.log(X_c + Y_c)) + log_kernel = ((np.log(X_c) / 2.) + (np.log(Y_c) / 2.) + np.log(2.) - + np.log(X_c + Y_c)) # reduce to n_samples_x x n_samples_y by summing over features in log-space kernel = np.exp(log_kernel.sum(axis=2)) - # appoximate kernel mapping + # approximate kernel mapping transform = SkewedChi2Sampler(skewedness=c, n_components=1000, random_state=42) X_trans = transform.fit_transform(X) Y_trans = transform.transform(Y) + kernel_approx = np.dot(X_trans, Y_trans.T) - np.testing.assert_array_almost_equal(kernel, kernel_approx, 1) + assert_array_almost_equal(kernel, kernel_approx, 1) + + # test error is raised on negative input + Y_neg = Y.copy() + Y_neg[0, 0] = -1 + assert_raises(ValueError, transform.transform, Y_neg) def test_rbf_sampler(): @@ -73,13 +116,17 @@ def test_rbf_sampler(): gamma = 10. kernel = rbf_kernel(X, Y, gamma=gamma) - # appoximate kernel mapping + # approximate kernel mapping rbf_transform = RBFSampler(gamma=gamma, n_components=1000, random_state=42) X_trans = rbf_transform.fit_transform(X) Y_trans = rbf_transform.transform(Y) kernel_approx = np.dot(X_trans, Y_trans.T) - np.testing.assert_array_almost_equal(kernel, kernel_approx, 1) + error = kernel - kernel_approx + assert_less_equal(np.abs(np.mean(error)), 0.01) # close to unbiased + np.abs(error, out=error) + assert_less_equal(np.max(error), 0.1) # nothing too far off + assert_less_equal(np.mean(error), 0.05) # mean is fairly close def test_input_validation(): @@ -96,8 +143,76 @@ def test_input_validation(): RBFSampler().fit(X).transform(X) -if __name__ == "__main__": - test_additive_chi2_sampler() - test_input_validation() - test_skewed_chi2_sampler() - test_rbf_sampler() +def test_nystroem_approximation(): + # some basic tests + rnd = np.random.RandomState(0) + X = rnd.uniform(size=(10, 4)) + + # With n_components = n_samples this is exact + X_transformed = Nystroem(n_components=X.shape[0]).fit_transform(X) + K = rbf_kernel(X) + assert_array_almost_equal(np.dot(X_transformed, X_transformed.T), K) + + trans = Nystroem(n_components=2, random_state=rnd) + X_transformed = trans.fit(X).transform(X) + assert_equal(X_transformed.shape, (X.shape[0], 2)) + + # test callable kernel + linear_kernel = lambda X, Y: np.dot(X, Y.T) + trans = Nystroem(n_components=2, kernel=linear_kernel, random_state=rnd) + X_transformed = trans.fit(X).transform(X) + assert_equal(X_transformed.shape, (X.shape[0], 2)) + + # test that available kernels fit and transform + kernels_available = kernel_metrics() + for kern in kernels_available: + trans = Nystroem(n_components=2, kernel=kern, random_state=rnd) + X_transformed = trans.fit(X).transform(X) + assert_equal(X_transformed.shape, (X.shape[0], 2)) + + +def test_nystroem_singular_kernel(): + # test that nystroem works with singular kernel matrix + rng = np.random.RandomState(0) + X = rng.rand(10, 20) + X = np.vstack([X] * 2) # duplicate samples + + gamma = 100 + N = Nystroem(gamma=gamma, n_components=X.shape[0]).fit(X) + X_transformed = N.transform(X) + + K = rbf_kernel(X, gamma=gamma) + + assert_array_almost_equal(K, np.dot(X_transformed, X_transformed.T)) + assert_true(np.all(np.isfinite(Y))) + + +def test_nystroem_poly_kernel_params(): + """Non-regression: Nystroem should pass other parameters beside gamma.""" + rnd = np.random.RandomState(37) + X = rnd.uniform(size=(10, 4)) + + K = polynomial_kernel(X, degree=3.1, coef0=.1) + nystroem = Nystroem(kernel="polynomial", n_components=X.shape[0], + degree=3.1, coef0=.1) + X_transformed = nystroem.fit_transform(X) + assert_array_almost_equal(np.dot(X_transformed, X_transformed.T), K) + + +def test_nystroem_callable(): + """Test Nystroem on a callable.""" + rnd = np.random.RandomState(42) + n_samples = 10 + X = rnd.uniform(size=(n_samples, 4)) + + def logging_histogram_kernel(x, y, log): + """Histogram kernel that writes to a log.""" + log.append(1) + return np.minimum(x, y).sum() + + kernel_log = [] + X = list(X) # test input validation + Nystroem(kernel=logging_histogram_kernel, + n_components=(n_samples - 1), + kernel_params={'log': kernel_log}).fit(X) + assert_equal(len(kernel_log), n_samples * (n_samples - 1) / 2) diff --git a/sklearn/tests/test_kernel_ridge.py b/sklearn/tests/test_kernel_ridge.py new file mode 100644 index 0000000000000..4750a096ac66f --- /dev/null +++ b/sklearn/tests/test_kernel_ridge.py @@ -0,0 +1,85 @@ +import numpy as np +import scipy.sparse as sp + +from sklearn.datasets import make_regression +from sklearn.linear_model import Ridge +from sklearn.kernel_ridge import KernelRidge +from sklearn.metrics.pairwise import pairwise_kernels +from sklearn.utils.testing import ignore_warnings + +from sklearn.utils.testing import assert_array_almost_equal + + +X, y = make_regression(n_features=10) +Xcsr = sp.csr_matrix(X) +Xcsc = sp.csc_matrix(X) +Y = np.array([y, y]).T + + +def test_kernel_ridge(): + pred = Ridge(alpha=1, fit_intercept=False).fit(X, y).predict(X) + pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X) + assert_array_almost_equal(pred, pred2) + + +def test_kernel_ridge_csr(): + pred = Ridge(alpha=1, fit_intercept=False, + solver="cholesky").fit(Xcsr, y).predict(Xcsr) + pred2 = KernelRidge(kernel="linear", alpha=1).fit(Xcsr, y).predict(Xcsr) + assert_array_almost_equal(pred, pred2) + + +def test_kernel_ridge_csc(): + pred = Ridge(alpha=1, fit_intercept=False, + solver="cholesky").fit(Xcsc, y).predict(Xcsc) + pred2 = KernelRidge(kernel="linear", alpha=1).fit(Xcsc, y).predict(Xcsc) + assert_array_almost_equal(pred, pred2) + + +def test_kernel_ridge_singular_kernel(): + # alpha=0 causes a LinAlgError in computing the dual coefficients, + # which causes a fallback to a lstsq solver. This is tested here. + pred = Ridge(alpha=0, fit_intercept=False).fit(X, y).predict(X) + kr = KernelRidge(kernel="linear", alpha=0) + ignore_warnings(kr.fit)(X, y) + pred2 = kr.predict(X) + assert_array_almost_equal(pred, pred2) + + +def test_kernel_ridge_precomputed(): + for kernel in ["linear", "rbf", "poly", "cosine"]: + K = pairwise_kernels(X, X, metric=kernel) + pred = KernelRidge(kernel=kernel).fit(X, y).predict(X) + pred2 = KernelRidge(kernel="precomputed").fit(K, y).predict(K) + assert_array_almost_equal(pred, pred2) + + +def test_kernel_ridge_precomputed_kernel_unchanged(): + K = np.dot(X, X.T) + K2 = K.copy() + KernelRidge(kernel="precomputed").fit(K, y) + assert_array_almost_equal(K, K2) + + +def test_kernel_ridge_sample_weights(): + K = np.dot(X, X.T) # precomputed kernel + sw = np.random.RandomState(0).rand(X.shape[0]) + + pred = Ridge(alpha=1, + fit_intercept=False).fit(X, y, sample_weight=sw).predict(X) + pred2 = KernelRidge(kernel="linear", + alpha=1).fit(X, y, sample_weight=sw).predict(X) + pred3 = KernelRidge(kernel="precomputed", + alpha=1).fit(K, y, sample_weight=sw).predict(K) + assert_array_almost_equal(pred, pred2) + assert_array_almost_equal(pred, pred3) + + +def test_kernel_ridge_multi_output(): + pred = Ridge(alpha=1, fit_intercept=False).fit(X, Y).predict(X) + pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, Y).predict(X) + assert_array_almost_equal(pred, pred2) + + pred3 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X) + pred3 = np.array([pred3, pred3]).T + assert_array_almost_equal(pred2, pred3) diff --git a/sklearn/tests/test_lda.py b/sklearn/tests/test_lda.py index af1ef5f7889e7..336ceb043dcb8 100644 --- a/sklearn/tests/test_lda.py +++ b/sklearn/tests/test_lda.py @@ -1,48 +1,150 @@ import numpy as np -from numpy.testing import assert_array_equal, assert_array_almost_equal -from nose.tools import assert_equal, assert_true -from .. import lda +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_raises + +from sklearn.datasets import make_blobs +from sklearn import lda + # Data is just 6 separable points in the plane -X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]) +X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]], dtype='f') y = np.array([1, 1, 1, 2, 2, 2]) y3 = np.array([1, 1, 2, 2, 3, 3]) -# Degenerate data with 1 feature (still should be separable) -X1 = np.array([[-2, ], [-1, ], [-1, ], [1, ], [1, ], [2, ]]) +# Degenerate data with only one feature (still should be separable) +X1 = np.array([[-2, ], [-1, ], [-1, ], [1, ], [1, ], [2, ]], dtype='f') + +solver_shrinkage = [('svd', None), ('lsqr', None), ('eigen', None), + ('lsqr', 'auto'), ('lsqr', 0), ('lsqr', 0.43), + ('eigen', 'auto'), ('eigen', 0), ('eigen', 0.43)] def test_lda_predict(): - """ - LDA classification. + """Test LDA classification. - This checks that LDA implements fit and predict and returns - correct values for a simple toy dataset. + This checks that LDA implements fit and predict and returns correct values + for simple toy data. """ + for test_case in solver_shrinkage: + solver, shrinkage = test_case + clf = lda.LDA(solver=solver, shrinkage=shrinkage) + y_pred = clf.fit(X, y).predict(X) + assert_array_equal(y_pred, y, 'solver %s' % solver) - clf = lda.LDA() - y_pred = clf.fit(X, y).predict(X) + # Assert that it works with 1D data + y_pred1 = clf.fit(X1, y).predict(X1) + assert_array_equal(y_pred1, y, 'solver %s' % solver) - assert_array_equal(y_pred, y) + # Test probability estimates + y_proba_pred1 = clf.predict_proba(X1) + assert_array_equal((y_proba_pred1[:, 1] > 0.5) + 1, y, + 'solver %s' % solver) + y_log_proba_pred1 = clf.predict_log_proba(X1) + assert_array_almost_equal(np.exp(y_log_proba_pred1), y_proba_pred1, + 8, 'solver %s' % solver) - # Assure that it works with 1D data - y_pred1 = clf.fit(X1, y).predict(X1) - assert_array_equal(y_pred1, y) + # Primarily test for commit 2f34950 -- "reuse" of priors + y_pred3 = clf.fit(X, y3).predict(X) + # LDA shouldn't be able to separate those + assert_true(np.any(y_pred3 != y3), 'solver %s' % solver) - # Test probas estimates - y_proba_pred1 = clf.predict_proba(X1) - assert_array_equal((y_proba_pred1[:, 1] > 0.5) + 1, y) - y_log_proba_pred1 = clf.predict_log_proba(X1) - assert_array_almost_equal(np.exp(y_log_proba_pred1), y_proba_pred1, 8) + # Test invalid shrinkages + clf = lda.LDA(solver="lsqr", shrinkage=-0.2231) + assert_raises(ValueError, clf.fit, X, y) + clf = lda.LDA(solver="eigen", shrinkage="dummy") + assert_raises(ValueError, clf.fit, X, y) + clf = lda.LDA(solver="svd", shrinkage="auto") + assert_raises(NotImplementedError, clf.fit, X, y) + # Test unknown solver + clf = lda.LDA(solver="dummy") + assert_raises(ValueError, clf.fit, X, y) + + +def test_lda_coefs(): + """Test if the coefficients of the solvers are approximately the same. + """ + n_features = 2 + n_classes = 2 + n_samples = 1000 + X, y = make_blobs(n_samples=n_samples, n_features=n_features, + centers=n_classes, random_state=11) - # Primarily test for commit 2f34950 -- "reuse" of priors - y_pred3 = clf.fit(X, y3).predict(X) - # LDA shouldn't be able to separate those - assert_true(np.any(y_pred3 != y3)) + clf_lda_svd = lda.LDA(solver="svd") + clf_lda_lsqr = lda.LDA(solver="lsqr") + clf_lda_eigen = lda.LDA(solver="eigen") + + clf_lda_svd.fit(X, y) + clf_lda_lsqr.fit(X, y) + clf_lda_eigen.fit(X, y) + + assert_array_almost_equal(clf_lda_svd.coef_, clf_lda_lsqr.coef_, 1) + assert_array_almost_equal(clf_lda_svd.coef_, clf_lda_eigen.coef_, 1) + assert_array_almost_equal(clf_lda_eigen.coef_, clf_lda_lsqr.coef_, 1) def test_lda_transform(): - clf = lda.LDA() + """Test LDA transform. + """ + clf = lda.LDA(solver="svd", n_components=1) X_transformed = clf.fit(X, y).transform(X) assert_equal(X_transformed.shape[1], 1) + clf = lda.LDA(solver="eigen", n_components=1) + X_transformed = clf.fit(X, y).transform(X) + assert_equal(X_transformed.shape[1], 1) + + +def test_lda_orthogonality(): + # arrange four classes with their means in a kite-shaped pattern + # the longer distance should be transformed to the first component, and + # the shorter distance to the second component. + means = np.array([[0, 0, -1], [0, 2, 0], [0, -2, 0], [0, 0, 5]]) + + # We construct perfectly symmetric distributions, so the LDA can estimate + # precise means. + scatter = np.array([[0.1, 0, 0], [-0.1, 0, 0], [0, 0.1, 0], [0, -0.1, 0], + [0, 0, 0.1], [0, 0, -0.1]]) + + X = (means[:, np.newaxis, :] + scatter[np.newaxis, :, :]).reshape((-1, 3)) + y = np.repeat(np.arange(means.shape[0]), scatter.shape[0]) + + # Fit LDA and transform the means + clf = lda.LDA(solver="svd").fit(X, y) + means_transformed = clf.transform(means) + + d1 = means_transformed[3] - means_transformed[0] + d2 = means_transformed[2] - means_transformed[1] + d1 /= np.sqrt(np.sum(d1**2)) + d2 /= np.sqrt(np.sum(d2**2)) + + # the transformed within-class covariance should be the identity matrix + assert_almost_equal(np.cov(clf.transform(scatter).T), np.eye(2)) + + # the means of classes 0 and 3 should lie on the first component + assert_almost_equal(np.abs(np.dot(d1[:2], [1, 0])), 1.0) + + # the means of classes 1 and 2 should lie on the second component + assert_almost_equal(np.abs(np.dot(d2[:2], [0, 1])), 1.0) + + +def test_lda_scaling(): + """Test if classification works correctly with differently scaled features. + """ + n = 100 + rng = np.random.RandomState(1234) + # use uniform distribution of features to make sure there is absolutely no + # overlap between classes. + x1 = rng.uniform(-1, 1, (n, 3)) + [-10, 0, 0] + x2 = rng.uniform(-1, 1, (n, 3)) + [10, 0, 0] + x = np.vstack((x1, x2)) * [1, 100, 10000] + y = [-1] * n + [1] * n + + for solver in ('svd', 'lsqr', 'eigen'): + clf = lda.LDA(solver=solver) + # should be able to separate the data perfectly + assert_equal(clf.fit(x, y).score(x, y), 1.0, + 'using covariance: %s' % solver) diff --git a/sklearn/tests/test_learning_curve.py b/sklearn/tests/test_learning_curve.py new file mode 100644 index 0000000000000..c062abfab7189 --- /dev/null +++ b/sklearn/tests/test_learning_curve.py @@ -0,0 +1,255 @@ +# Author: Alexander Fabisch +# +# License: BSD 3 clause + +import sys +from sklearn.externals.six.moves import cStringIO as StringIO +import numpy as np +import warnings +from sklearn.base import BaseEstimator +from sklearn.learning_curve import learning_curve, validation_curve +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.datasets import make_classification +from sklearn.cross_validation import KFold +from sklearn.linear_model import PassiveAggressiveClassifier + + +class MockImprovingEstimator(BaseEstimator): + """Dummy classifier to test the learning curve""" + def __init__(self, n_max_train_sizes): + self.n_max_train_sizes = n_max_train_sizes + self.train_sizes = 0 + self.X_subset = None + + def fit(self, X_subset, y_subset=None): + self.X_subset = X_subset + self.train_sizes = X_subset.shape[0] + return self + + def predict(self, X): + raise NotImplementedError + + def score(self, X=None, Y=None): + # training score becomes worse (2 -> 1), test error better (0 -> 1) + if self._is_training_data(X): + return 2. - float(self.train_sizes) / self.n_max_train_sizes + else: + return float(self.train_sizes) / self.n_max_train_sizes + + def _is_training_data(self, X): + return X is self.X_subset + + +class MockIncrementalImprovingEstimator(MockImprovingEstimator): + """Dummy classifier that provides partial_fit""" + def __init__(self, n_max_train_sizes): + super(MockIncrementalImprovingEstimator, + self).__init__(n_max_train_sizes) + self.x = None + + def _is_training_data(self, X): + return self.x in X + + def partial_fit(self, X, y=None, **params): + self.train_sizes += X.shape[0] + self.x = X[0] + + +class MockEstimatorWithParameter(BaseEstimator): + """Dummy classifier to test the validation curve""" + def __init__(self, param=0.5): + self.X_subset = None + self.param = param + + def fit(self, X_subset, y_subset): + self.X_subset = X_subset + self.train_sizes = X_subset.shape[0] + return self + + def predict(self, X): + raise NotImplementedError + + def score(self, X=None, y=None): + return self.param if self._is_training_data(X) else 1 - self.param + + def _is_training_data(self, X): + return X is self.X_subset + + +def test_learning_curve(): + X, y = make_classification(n_samples=30, n_features=1, n_informative=1, + n_redundant=0, n_classes=2, + n_clusters_per_class=1, random_state=0) + estimator = MockImprovingEstimator(20) + with warnings.catch_warnings(record=True) as w: + train_sizes, train_scores, test_scores = learning_curve( + estimator, X, y, cv=3, train_sizes=np.linspace(0.1, 1.0, 10)) + if len(w) > 0: + raise RuntimeError("Unexpected warning: %r" % w[0].message) + assert_equal(train_scores.shape, (10, 3)) + assert_equal(test_scores.shape, (10, 3)) + assert_array_equal(train_sizes, np.linspace(2, 20, 10)) + assert_array_almost_equal(train_scores.mean(axis=1), + np.linspace(1.9, 1.0, 10)) + assert_array_almost_equal(test_scores.mean(axis=1), + np.linspace(0.1, 1.0, 10)) + + +def test_learning_curve_unsupervised(): + X, _ = make_classification(n_samples=30, n_features=1, n_informative=1, + n_redundant=0, n_classes=2, + n_clusters_per_class=1, random_state=0) + estimator = MockImprovingEstimator(20) + train_sizes, train_scores, test_scores = learning_curve( + estimator, X, y=None, cv=3, train_sizes=np.linspace(0.1, 1.0, 10)) + assert_array_equal(train_sizes, np.linspace(2, 20, 10)) + assert_array_almost_equal(train_scores.mean(axis=1), + np.linspace(1.9, 1.0, 10)) + assert_array_almost_equal(test_scores.mean(axis=1), + np.linspace(0.1, 1.0, 10)) + + +def test_learning_curve_verbose(): + X, y = make_classification(n_samples=30, n_features=1, n_informative=1, + n_redundant=0, n_classes=2, + n_clusters_per_class=1, random_state=0) + estimator = MockImprovingEstimator(20) + + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + train_sizes, train_scores, test_scores = \ + learning_curve(estimator, X, y, cv=3, verbose=1) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + + assert("[learning_curve]" in out) + + +def test_learning_curve_incremental_learning_not_possible(): + X, y = make_classification(n_samples=2, n_features=1, n_informative=1, + n_redundant=0, n_classes=2, + n_clusters_per_class=1, random_state=0) + # The mockup does not have partial_fit() + estimator = MockImprovingEstimator(1) + assert_raises(ValueError, learning_curve, estimator, X, y, + exploit_incremental_learning=True) + + +def test_learning_curve_incremental_learning(): + X, y = make_classification(n_samples=30, n_features=1, n_informative=1, + n_redundant=0, n_classes=2, + n_clusters_per_class=1, random_state=0) + estimator = MockIncrementalImprovingEstimator(20) + train_sizes, train_scores, test_scores = learning_curve( + estimator, X, y, cv=3, exploit_incremental_learning=True, + train_sizes=np.linspace(0.1, 1.0, 10)) + assert_array_equal(train_sizes, np.linspace(2, 20, 10)) + assert_array_almost_equal(train_scores.mean(axis=1), + np.linspace(1.9, 1.0, 10)) + assert_array_almost_equal(test_scores.mean(axis=1), + np.linspace(0.1, 1.0, 10)) + + +def test_learning_curve_incremental_learning_unsupervised(): + X, _ = make_classification(n_samples=30, n_features=1, n_informative=1, + n_redundant=0, n_classes=2, + n_clusters_per_class=1, random_state=0) + estimator = MockIncrementalImprovingEstimator(20) + train_sizes, train_scores, test_scores = learning_curve( + estimator, X, y=None, cv=3, exploit_incremental_learning=True, + train_sizes=np.linspace(0.1, 1.0, 10)) + assert_array_equal(train_sizes, np.linspace(2, 20, 10)) + assert_array_almost_equal(train_scores.mean(axis=1), + np.linspace(1.9, 1.0, 10)) + assert_array_almost_equal(test_scores.mean(axis=1), + np.linspace(0.1, 1.0, 10)) + + +def test_learning_curve_batch_and_incremental_learning_are_equal(): + X, y = make_classification(n_samples=30, n_features=1, n_informative=1, + n_redundant=0, n_classes=2, + n_clusters_per_class=1, random_state=0) + train_sizes = np.linspace(0.2, 1.0, 5) + estimator = PassiveAggressiveClassifier(n_iter=1, shuffle=False) + + train_sizes_inc, train_scores_inc, test_scores_inc = \ + learning_curve( + estimator, X, y, train_sizes=train_sizes, + cv=3, exploit_incremental_learning=True) + train_sizes_batch, train_scores_batch, test_scores_batch = \ + learning_curve( + estimator, X, y, cv=3, train_sizes=train_sizes, + exploit_incremental_learning=False) + + assert_array_equal(train_sizes_inc, train_sizes_batch) + assert_array_almost_equal(train_scores_inc.mean(axis=1), + train_scores_batch.mean(axis=1)) + assert_array_almost_equal(test_scores_inc.mean(axis=1), + test_scores_batch.mean(axis=1)) + + +def test_learning_curve_n_sample_range_out_of_bounds(): + X, y = make_classification(n_samples=30, n_features=1, n_informative=1, + n_redundant=0, n_classes=2, + n_clusters_per_class=1, random_state=0) + estimator = MockImprovingEstimator(20) + assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, + train_sizes=[0, 1]) + assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, + train_sizes=[0.0, 1.0]) + assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, + train_sizes=[0.1, 1.1]) + assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, + train_sizes=[0, 20]) + assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, + train_sizes=[1, 21]) + + +def test_learning_curve_remove_duplicate_sample_sizes(): + X, y = make_classification(n_samples=3, n_features=1, n_informative=1, + n_redundant=0, n_classes=2, + n_clusters_per_class=1, random_state=0) + estimator = MockImprovingEstimator(2) + train_sizes, _, _ = assert_warns( + RuntimeWarning, learning_curve, estimator, X, y, cv=3, + train_sizes=np.linspace(0.33, 1.0, 3)) + assert_array_equal(train_sizes, [1, 2]) + + +def test_learning_curve_with_boolean_indices(): + X, y = make_classification(n_samples=30, n_features=1, n_informative=1, + n_redundant=0, n_classes=2, + n_clusters_per_class=1, random_state=0) + estimator = MockImprovingEstimator(20) + cv = KFold(n=30, n_folds=3, indices=False) + train_sizes, train_scores, test_scores = learning_curve( + estimator, X, y, cv=cv, train_sizes=np.linspace(0.1, 1.0, 10)) + assert_array_equal(train_sizes, np.linspace(2, 20, 10)) + assert_array_almost_equal(train_scores.mean(axis=1), + np.linspace(1.9, 1.0, 10)) + assert_array_almost_equal(test_scores.mean(axis=1), + np.linspace(0.1, 1.0, 10)) + + +def test_validation_curve(): + X, y = make_classification(n_samples=2, n_features=1, n_informative=1, + n_redundant=0, n_classes=2, + n_clusters_per_class=1, random_state=0) + param_range = np.linspace(0, 1, 10) + with warnings.catch_warnings(record=True) as w: + train_scores, test_scores = validation_curve( + MockEstimatorWithParameter(), X, y, param_name="param", + param_range=param_range, cv=2 + ) + if len(w) > 0: + raise RuntimeError("Unexpected warning: %r" % w[0].message) + + assert_array_almost_equal(train_scores.mean(axis=1), param_range) + assert_array_almost_equal(test_scores.mean(axis=1), 1 - param_range) diff --git a/sklearn/tests/test_metaestimators.py b/sklearn/tests/test_metaestimators.py new file mode 100644 index 0000000000000..c0cee613a874c --- /dev/null +++ b/sklearn/tests/test_metaestimators.py @@ -0,0 +1,137 @@ +"""Common tests for metaestimators""" + +import functools + +import numpy as np + +from sklearn.base import BaseEstimator +from sklearn.externals.six import iterkeys +from sklearn.datasets import make_classification +from sklearn.utils.testing import assert_true, assert_false, assert_raises +from sklearn.pipeline import Pipeline +from sklearn.grid_search import GridSearchCV, RandomizedSearchCV +from sklearn.feature_selection import RFE, RFECV +from sklearn.ensemble import BaggingClassifier + + +class DelegatorData(object): + def __init__(self, name, construct, skip_methods=(), + fit_args=make_classification()): + self.name = name + self.construct = construct + self.fit_args = fit_args + self.skip_methods = skip_methods + + +DELEGATING_METAESTIMATORS = [ + DelegatorData('Pipeline', lambda est: Pipeline([('est', est)])), + DelegatorData('GridSearchCV', + lambda est: GridSearchCV( + est, param_grid={'param': [5]}, cv=2), + skip_methods=['score']), + DelegatorData('RandomizedSearchCV', + lambda est: RandomizedSearchCV( + est, param_distributions={'param': [5]}, cv=2, n_iter=1), + skip_methods=['score']), + DelegatorData('RFE', RFE, + skip_methods=['transform', 'inverse_transform', 'score']), + DelegatorData('RFECV', RFECV, + skip_methods=['transform', 'inverse_transform', 'score']), + DelegatorData('BaggingClassifier', BaggingClassifier, + skip_methods=['transform', 'inverse_transform', 'score', + 'predict_proba', 'predict_log_proba', 'predict']) +] + + +def test_metaestimator_delegation(): + """Ensures specified metaestimators have methods iff subestimator does""" + def hides(method): + @property + def wrapper(obj): + if obj.hidden_method == method.__name__: + raise AttributeError('%r is hidden' % obj.hidden_method) + return functools.partial(method, obj) + return wrapper + + class SubEstimator(BaseEstimator): + def __init__(self, param=1, hidden_method=None): + self.param = param + self.hidden_method = hidden_method + + def fit(self, X, y=None, *args, **kwargs): + self.coef_ = np.arange(X.shape[1]) + return True + + def _check_fit(self): + if not hasattr(self, 'coef_'): + raise RuntimeError('Estimator is not fit') + + @hides + def inverse_transform(self, X, *args, **kwargs): + self._check_fit() + return X + + @hides + def transform(self, X, *args, **kwargs): + self._check_fit() + return X + + @hides + def predict(self, X, *args, **kwargs): + self._check_fit() + return np.ones(X.shape[0]) + + @hides + def predict_proba(self, X, *args, **kwargs): + self._check_fit() + return np.ones(X.shape[0]) + + @hides + def predict_log_proba(self, X, *args, **kwargs): + self._check_fit() + return np.ones(X.shape[0]) + + @hides + def decision_function(self, X, *args, **kwargs): + self._check_fit() + return np.ones(X.shape[0]) + + @hides + def score(self, X, *args, **kwargs): + self._check_fit() + return 1.0 + + methods = [k for k in iterkeys(SubEstimator.__dict__) + if not k.startswith('_') and not k.startswith('fit')] + methods.sort() + + for delegator_data in DELEGATING_METAESTIMATORS: + delegate = SubEstimator() + delegator = delegator_data.construct(delegate) + for method in methods: + if method in delegator_data.skip_methods: + continue + assert_true(hasattr(delegate, method)) + assert_true(hasattr(delegator, method), + msg="%s does not have method %r when its delegate does" + % (delegator_data.name, method)) + # delegation before fit raises an exception + assert_raises(Exception, getattr(delegator, method), + delegator_data.fit_args[0]) + + delegator.fit(*delegator_data.fit_args) + for method in methods: + if method in delegator_data.skip_methods: + continue + # smoke test delegation + getattr(delegator, method)(delegator_data.fit_args[0]) + + for method in methods: + if method in delegator_data.skip_methods: + continue + delegate = SubEstimator(hidden_method=method) + delegator = delegator_data.construct(delegate) + assert_false(hasattr(delegate, method)) + assert_false(hasattr(delegator, method), + msg="%s has method %r when its delegate does not" + % (delegator_data.name, method)) diff --git a/sklearn/tests/test_multiclass.py b/sklearn/tests/test_multiclass.py index 1246728ba2d06..dad7363dde599 100644 --- a/sklearn/tests/test_multiclass.py +++ b/sklearn/tests/test_multiclass.py @@ -1,23 +1,42 @@ import numpy as np -import warnings - -from numpy.testing import assert_array_equal -from nose.tools import assert_equal -from nose.tools import assert_almost_equal -from nose.tools import assert_true -from nose.tools import assert_raises - +import scipy.sparse as sp + +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_greater from sklearn.multiclass import OneVsRestClassifier from sklearn.multiclass import OneVsOneClassifier from sklearn.multiclass import OutputCodeClassifier -from sklearn.svm import LinearSVC + +from sklearn.multiclass import fit_ovr +from sklearn.multiclass import fit_ovo +from sklearn.multiclass import fit_ecoc +from sklearn.multiclass import predict_ovr +from sklearn.multiclass import predict_ovo +from sklearn.multiclass import predict_ecoc +from sklearn.multiclass import predict_proba_ovr + +from sklearn.metrics import precision_score +from sklearn.metrics import recall_score + +from sklearn.preprocessing import LabelBinarizer + +from sklearn.svm import LinearSVC, SVC from sklearn.naive_bayes import MultinomialNB -from sklearn.linear_model import LinearRegression, Lasso, ElasticNet, Ridge +from sklearn.linear_model import (LinearRegression, Lasso, ElasticNet, Ridge, + Perceptron, LogisticRegression) from sklearn.tree import DecisionTreeClassifier from sklearn.grid_search import GridSearchCV +from sklearn.pipeline import Pipeline from sklearn import svm from sklearn import datasets +from sklearn.externals.six.moves import zip iris = datasets.load_iris() rng = np.random.RandomState(0) @@ -27,68 +46,180 @@ n_classes = 3 -# FIXME: - should use sets -# - should move to metrics module -def multilabel_precision(Y_true, Y_pred): - n_predictions = 0 - n_correct = 0 - for i in range(len(Y_true)): - n_predictions += len(Y_pred[i]) - for label in Y_pred[i]: - if label in Y_true[i]: - n_correct += 1 - return float(n_correct) / n_predictions - - -def multilabel_recall(Y_true, Y_pred): - n_labels = 0 - n_correct = 0 - for i in range(len(Y_true)): - n_labels += len(Y_true[i]) - for label in Y_pred[i]: - if label in Y_true[i]: - n_correct += 1 - return float(n_correct) / n_labels - - def test_ovr_exceptions(): - ovr = OneVsRestClassifier(LinearSVC()) + ovr = OneVsRestClassifier(LinearSVC(random_state=0)) assert_raises(ValueError, ovr.predict, []) + with ignore_warnings(): + assert_raises(ValueError, predict_ovr, [LinearSVC(), MultinomialNB()], + LabelBinarizer(), []) + + # Fail on multioutput data + assert_raises(ValueError, OneVsRestClassifier(MultinomialNB()).fit, + np.array([[1, 0], [0, 1]]), + np.array([[1, 2], [3, 1]])) + assert_raises(ValueError, OneVsRestClassifier(MultinomialNB()).fit, + np.array([[1, 0], [0, 1]]), + np.array([[1.5, 2.4], [3.1, 0.8]])) + def test_ovr_fit_predict(): # A classifier which implements decision_function. - ovr = OneVsRestClassifier(LinearSVC()) + ovr = OneVsRestClassifier(LinearSVC(random_state=0)) pred = ovr.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovr.estimators_), n_classes) - pred2 = LinearSVC().fit(iris.data, iris.target).predict(iris.data) + clf = LinearSVC(random_state=0) + pred2 = clf.fit(iris.data, iris.target).predict(iris.data) assert_equal(np.mean(iris.target == pred), np.mean(iris.target == pred2)) # A classifier which implements predict_proba. ovr = OneVsRestClassifier(MultinomialNB()) pred = ovr.fit(iris.data, iris.target).predict(iris.data) - assert_true(np.mean(iris.target == pred) >= 0.65) + assert_greater(np.mean(iris.target == pred), 0.65) + + +def test_ovr_fit_predict_sparse(): + for sparse in [sp.csr_matrix, sp.csc_matrix, sp.coo_matrix, sp.dok_matrix, + sp.lil_matrix]: + base_clf = MultinomialNB(alpha=1) + + X, Y = datasets.make_multilabel_classification(n_samples=100, + n_features=20, + n_classes=5, + n_labels=3, + length=50, + allow_unlabeled=True, + return_indicator=True, + random_state=0) + + X_train, Y_train = X[:80], Y[:80] + X_test = X[80:] + + clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) + Y_pred = clf.predict(X_test) + + clf_sprs = OneVsRestClassifier(base_clf).fit(X_train, sparse(Y_train)) + Y_pred_sprs = clf_sprs.predict(X_test) + + assert_true(clf.multilabel_) + assert_true(sp.issparse(Y_pred_sprs)) + assert_array_equal(Y_pred_sprs.toarray(), Y_pred) + + # Test predict_proba + Y_proba = clf_sprs.predict_proba(X_test) + + # predict assigns a label if the probability that the + # sample has the label is greater than 0.5. + pred = Y_proba > .5 + assert_array_equal(pred, Y_pred_sprs.toarray()) + + # Test decision_function + clf_sprs = OneVsRestClassifier(svm.SVC()).fit(X_train, sparse(Y_train)) + dec_pred = (clf_sprs.decision_function(X_test) > 0).astype(int) + assert_array_equal(dec_pred, clf_sprs.predict(X_test).toarray()) def test_ovr_always_present(): - # Test that ovr works with classes that are always present or absent + """Test that ovr works with classes that are always present or absent.""" + # Note: tests is the case where _ConstantPredictor is utilised X = np.ones((10, 2)) X[:5, :] = 0 - y = [[int(i >= 5), 2, 3] for i in xrange(10)] - with warnings.catch_warnings(record=True): - ovr = OneVsRestClassifier(DecisionTreeClassifier()) - ovr.fit(X, y) - y_pred = ovr.predict(X) - assert_array_equal(np.array(y_pred), np.array(y)) + # Build an indicator matrix where two features are always on. + # As list of lists, it would be: [[int(i >= 5), 2, 3] for i in range(10)] + y = np.zeros((10, 3)) + y[5:, 0] = 1 + y[:, 1] = 1 + y[:, 2] = 1 + + ovr = OneVsRestClassifier(LogisticRegression()) + assert_warns(UserWarning, ovr.fit, X, y) + y_pred = ovr.predict(X) + assert_array_equal(np.array(y_pred), np.array(y)) + y_pred = ovr.decision_function(X) + assert_equal(np.unique(y_pred[:, -2:]), 1) + y_pred = ovr.predict_proba(X) + assert_array_equal(y_pred[:, -1], np.ones(X.shape[0])) + + # y has a constantly absent label + y = np.zeros((10, 2)) + y[5:, 0] = 1 # variable label + ovr = OneVsRestClassifier(LogisticRegression()) + assert_warns(UserWarning, ovr.fit, X, y) + y_pred = ovr.predict_proba(X) + assert_array_equal(y_pred[:, -1], np.zeros(X.shape[0])) + + +def test_ovr_multiclass(): + # Toy dataset where features correspond directly to labels. + X = np.array([[0, 0, 5], [0, 5, 0], [3, 0, 0], [0, 0, 6], [6, 0, 0]]) + y = ["eggs", "spam", "ham", "eggs", "ham"] + Y = np.array([[0, 0, 1], + [0, 1, 0], + [1, 0, 0], + [0, 0, 1], + [1, 0, 0]]) + + classes = set("ham eggs spam".split()) + + for base_clf in (MultinomialNB(), LinearSVC(random_state=0), + LinearRegression(), Ridge(), + ElasticNet()): + + clf = OneVsRestClassifier(base_clf).fit(X, y) + assert_equal(set(clf.classes_), classes) + y_pred = clf.predict(np.array([[0, 0, 4]]))[0] + assert_equal(set(y_pred), set("eggs")) + + # test input as label indicator matrix + clf = OneVsRestClassifier(base_clf).fit(X, Y) + y_pred = clf.predict([[0, 0, 4]])[0] + assert_array_equal(y_pred, [0, 0, 1]) + + +def test_ovr_binary(): + # Toy dataset where features correspond directly to labels. + X = np.array([[0, 0, 5], [0, 5, 0], [3, 0, 0], [0, 0, 6], [6, 0, 0]]) + y = ["eggs", "spam", "spam", "eggs", "spam"] + Y = np.array([[0, 1, 1, 0, 1]]).T + + classes = set("eggs spam".split()) + + def conduct_test(base_clf, test_predict_proba=False): + clf = OneVsRestClassifier(base_clf).fit(X, y) + assert_equal(set(clf.classes_), classes) + y_pred = clf.predict(np.array([[0, 0, 4]]))[0] + assert_equal(set(y_pred), set("eggs")) + + if test_predict_proba: + X_test = np.array([[0, 0, 4]]) + probabilities = clf.predict_proba(X_test) + assert_equal(2, len(probabilities[0])) + assert_equal(clf.classes_[np.argmax(probabilities, axis=1)], + clf.predict(X_test)) + # test input as label indicator matrix + clf = OneVsRestClassifier(base_clf).fit(X, Y) + y_pred = clf.predict([[3, 0, 0]])[0] + assert_equal(y_pred, 1) + + for base_clf in (LinearSVC(random_state=0), LinearRegression(), + Ridge(), ElasticNet()): + conduct_test(base_clf) + + for base_clf in (MultinomialNB(), SVC(probability=True), + LogisticRegression()): + conduct_test(base_clf, test_predict_proba=True) + + +@ignore_warnings def test_ovr_multilabel(): # Toy dataset where features correspond directly to labels. X = np.array([[0, 4, 5], [0, 5, 0], [3, 3, 3], [4, 0, 6], [6, 0, 0]]) y = [["spam", "eggs"], ["spam"], ["ham", "eggs", "spam"], ["ham", "eggs"], ["ham"]] - #y = [[1, 2], [1], [0, 1, 2], [0, 2], [0]] + # y = [[1, 2], [1], [0, 1, 2], [0, 2], [0]] Y = np.array([[0, 1, 1], [0, 1, 0], [1, 1, 1], @@ -97,11 +228,13 @@ def test_ovr_multilabel(): classes = set("ham eggs spam".split()) - for base_clf in (MultinomialNB(), LinearSVC(), + for base_clf in (MultinomialNB(), LinearSVC(random_state=0), LinearRegression(), Ridge(), ElasticNet(), Lasso(alpha=0.5)): # test input as lists of tuples - clf = OneVsRestClassifier(base_clf).fit(X, y) + clf = assert_warns(DeprecationWarning, + OneVsRestClassifier(base_clf).fit, + X, y) assert_equal(set(clf.classes_), classes) y_pred = clf.predict([[0, 4, 4]])[0] assert_equal(set(y_pred), set(["spam", "eggs"])) @@ -123,27 +256,112 @@ def test_ovr_fit_predict_svc(): def test_ovr_multilabel_dataset(): base_clf = MultinomialNB(alpha=1) - for au, prec, recall in zip((True, False), (0.65, 0.74), (0.72, 0.84)): + for au, prec, recall in zip((True, False), (0.51, 0.66), (0.51, 0.80)): X, Y = datasets.make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, n_labels=2, length=50, allow_unlabeled=au, + return_indicator=True, random_state=0) X_train, Y_train = X[:80], Y[:80] X_test, Y_test = X[80:], Y[80:] clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) Y_pred = clf.predict(X_test) + assert_true(clf.multilabel_) - assert_almost_equal(multilabel_precision(Y_test, Y_pred), prec, - places=2) - assert_almost_equal(multilabel_recall(Y_test, Y_pred), recall, - places=2) + assert_almost_equal(precision_score(Y_test, Y_pred, average="micro"), + prec, + decimal=2) + assert_almost_equal(recall_score(Y_test, Y_pred, average="micro"), + recall, + decimal=2) + + +def test_ovr_multilabel_predict_proba(): + base_clf = MultinomialNB(alpha=1) + for au in (False, True): + X, Y = datasets.make_multilabel_classification(n_samples=100, + n_features=20, + n_classes=5, + n_labels=3, + length=50, + allow_unlabeled=au, + return_indicator=True, + random_state=0) + X_train, Y_train = X[:80], Y[:80] + X_test = X[80:] + clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) + + # decision function only estimator. Fails in current implementation. + decision_only = OneVsRestClassifier(svm.SVR()).fit(X_train, Y_train) + assert_raises(AttributeError, decision_only.predict_proba, X_test) + + # Estimator with predict_proba disabled, depending on parameters. + decision_only = OneVsRestClassifier(svm.SVC(probability=False)) + decision_only.fit(X_train, Y_train) + assert_raises(AttributeError, decision_only.predict_proba, X_test) + + Y_pred = clf.predict(X_test) + Y_proba = clf.predict_proba(X_test) + + # predict assigns a label if the probability that the + # sample has the label is greater than 0.5. + pred = Y_proba > .5 + assert_array_equal(pred, Y_pred) + + +def test_ovr_single_label_predict_proba(): + base_clf = MultinomialNB(alpha=1) + X, Y = iris.data, iris.target + X_train, Y_train = X[:80], Y[:80] + X_test = X[80:] + clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) + + # decision function only estimator. Fails in current implementation. + decision_only = OneVsRestClassifier(svm.SVR()).fit(X_train, Y_train) + assert_raises(AttributeError, decision_only.predict_proba, X_test) + + Y_pred = clf.predict(X_test) + Y_proba = clf.predict_proba(X_test) + + assert_almost_equal(Y_proba.sum(axis=1), 1.0) + # predict assigns a label if the probability that the + # sample has the label is greater than 0.5. + pred = np.array([l.argmax() for l in Y_proba]) + assert_false((pred - Y_pred).any()) + + +def test_ovr_multilabel_decision_function(): + X, Y = datasets.make_multilabel_classification(n_samples=100, + n_features=20, + n_classes=5, + n_labels=3, + length=50, + allow_unlabeled=True, + return_indicator=True, + random_state=0) + X_train, Y_train = X[:80], Y[:80] + X_test = X[80:] + clf = OneVsRestClassifier(svm.SVC()).fit(X_train, Y_train) + assert_array_equal((clf.decision_function(X_test) > 0).astype(int), + clf.predict(X_test)) + + +def test_ovr_single_label_decision_function(): + X, Y = datasets.make_classification(n_samples=100, + n_features=20, + random_state=0) + X_train, Y_train = X[:80], Y[:80] + X_test = X[80:] + clf = OneVsRestClassifier(svm.SVC()).fit(X_train, Y_train) + assert_array_equal(clf.decision_function(X_test).ravel() > 0, + clf.predict(X_test)) def test_ovr_gridsearch(): - ovr = OneVsRestClassifier(LinearSVC()) + ovr = OneVsRestClassifier(LinearSVC(random_state=0)) Cs = [0.1, 0.5, 0.8] cv = GridSearchCV(ovr, {'estimator__C': Cs}) cv.fit(iris.data, iris.target) @@ -151,8 +369,20 @@ def test_ovr_gridsearch(): assert_true(best_C in Cs) +def test_ovr_pipeline(): + # Test with pipeline of length one + # This test is needed because the multiclass estimators may fail to detect + # the presence of predict_proba or decision_function. + clf = Pipeline([("tree", DecisionTreeClassifier())]) + ovr_pipe = OneVsRestClassifier(clf) + ovr_pipe.fit(iris.data, iris.target) + ovr = OneVsRestClassifier(DecisionTreeClassifier()) + ovr.fit(iris.data, iris.target) + assert_array_equal(ovr.predict(iris.data), ovr_pipe.predict(iris.data)) + + def test_ovr_coef_(): - ovr = OneVsRestClassifier(LinearSVC()) + ovr = OneVsRestClassifier(LinearSVC(random_state=0)) ovr.fit(iris.data, iris.target) shape = ovr.coef_.shape assert_equal(shape[0], n_classes) @@ -161,7 +391,7 @@ def test_ovr_coef_(): def test_ovr_coef_exceptions(): # Not fitted exception! - ovr = OneVsRestClassifier(LinearSVC()) + ovr = OneVsRestClassifier(LinearSVC(random_state=0)) # lambda is needed because we don't want coef_ to be evaluated right away assert_raises(ValueError, lambda x: ovr.coef_, None) @@ -172,13 +402,23 @@ def test_ovr_coef_exceptions(): def test_ovo_exceptions(): - ovo = OneVsOneClassifier(LinearSVC()) + ovo = OneVsOneClassifier(LinearSVC(random_state=0)) assert_raises(ValueError, ovo.predict, []) +def test_ovo_fit_on_list(): + # Test that OneVsOne fitting works with a list of targets and yields the + # same output as predict from an array + ovo = OneVsOneClassifier(LinearSVC(random_state=0)) + prediction_from_array = ovo.fit(iris.data, iris.target).predict(iris.data) + prediction_from_list = ovo.fit(iris.data, + list(iris.target)).predict(iris.data) + assert_array_equal(prediction_from_array, prediction_from_list) + + def test_ovo_fit_predict(): # A classifier which implements decision_function. - ovo = OneVsOneClassifier(LinearSVC()) + ovo = OneVsOneClassifier(LinearSVC(random_state=0)) ovo.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovo.estimators_), n_classes * (n_classes - 1) / 2) @@ -188,8 +428,49 @@ def test_ovo_fit_predict(): assert_equal(len(ovo.estimators_), n_classes * (n_classes - 1) / 2) +def test_ovo_decision_function(): + n_samples = iris.data.shape[0] + + ovo_clf = OneVsOneClassifier(LinearSVC(random_state=0)) + ovo_clf.fit(iris.data, iris.target) + decisions = ovo_clf.decision_function(iris.data) + + assert_equal(decisions.shape, (n_samples, n_classes)) + assert_array_equal(decisions.argmax(axis=1), ovo_clf.predict(iris.data)) + + # Compute the votes + votes = np.zeros((n_samples, n_classes)) + + k = 0 + for i in range(n_classes): + for j in range(i + 1, n_classes): + pred = ovo_clf.estimators_[k].predict(iris.data) + votes[pred == 0, i] += 1 + votes[pred == 1, j] += 1 + k += 1 + + # Extract votes and verify + assert_array_equal(votes, np.round(decisions)) + + for class_idx in range(n_classes): + # For each sample and each class, there only 3 possible vote levels + # because they are only 3 distinct class pairs thus 3 distinct + # binary classifiers. + # Therefore, sorting predictions based on votes would yield + # mostly tied predictions: + assert_true(set(votes[:, class_idx]).issubset(set([0., 1., 2.]))) + + # The OVO decision function on the other hand is able to resolve + # most of the ties on this data as it combines both the vote counts + # and the aggregated confidence levels of the binary classifiers + # to compute the aggregate decision function. The iris dataset + # has 150 samples with a couple of duplicates. The OvO decisions + # can resolve most of the ties: + assert_greater(len(np.unique(decisions[:, class_idx])), 146) + + def test_ovo_gridsearch(): - ovo = OneVsOneClassifier(LinearSVC()) + ovo = OneVsOneClassifier(LinearSVC(random_state=0)) Cs = [0.1, 0.5, 0.8] cv = GridSearchCV(ovo, {'estimator__C': Cs}) cv.fit(iris.data, iris.target) @@ -197,14 +478,62 @@ def test_ovo_gridsearch(): assert_true(best_C in Cs) +def test_ovo_ties(): + # Test that ties are broken using the decision function, + # not defaulting to the smallest label + X = np.array([[1, 2], [2, 1], [-2, 1], [-2, -1]]) + y = np.array([2, 0, 1, 2]) + multi_clf = OneVsOneClassifier(Perceptron(shuffle=False)) + ovo_prediction = multi_clf.fit(X, y).predict(X) + ovo_decision = multi_clf.decision_function(X) + + # Classifiers are in order 0-1, 0-2, 1-2 + # Use decision_function to compute the votes and the normalized + # sum_of_confidences, which is used to disambiguate when there is a tie in + # votes. + votes = np.round(ovo_decision) + normalized_confidences = ovo_decision - votes + + # For the first point, there is one vote per class + assert_array_equal(votes[0, :], 1) + # For the rest, there is no tie and the prediction is the argmax + assert_array_equal(np.argmax(votes[1:], axis=1), ovo_prediction[1:]) + # For the tie, the prediction is the class with the highest score + assert_equal(ovo_prediction[0], normalized_confidences[0].argmax()) + + +def test_ovo_ties2(): + # test that ties can not only be won by the first two labels + X = np.array([[1, 2], [2, 1], [-2, 1], [-2, -1]]) + y_ref = np.array([2, 0, 1, 2]) + + # cycle through labels so that each label wins once + for i in range(3): + y = (y_ref + i) % 3 + multi_clf = OneVsOneClassifier(Perceptron(shuffle=False)) + ovo_prediction = multi_clf.fit(X, y).predict(X) + assert_equal(ovo_prediction[0], i % 3) + + +def test_ovo_string_y(): + # Test that the OvO doesn't mess up the encoding of string labels + X = np.eye(4) + y = np.array(['a', 'b', 'c', 'd']) + + ovo = OneVsOneClassifier(LinearSVC()) + ovo.fit(X, y) + assert_array_equal(y, ovo.predict(X)) + + def test_ecoc_exceptions(): - ecoc = OutputCodeClassifier(LinearSVC()) + ecoc = OutputCodeClassifier(LinearSVC(random_state=0)) assert_raises(ValueError, ecoc.predict, []) def test_ecoc_fit_predict(): # A classifier which implements decision_function. - ecoc = OutputCodeClassifier(LinearSVC(), code_size=2, random_state=0) + ecoc = OutputCodeClassifier(LinearSVC(random_state=0), + code_size=2, random_state=0) ecoc.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ecoc.estimators_), n_classes * 2) @@ -215,9 +544,56 @@ def test_ecoc_fit_predict(): def test_ecoc_gridsearch(): - ecoc = OutputCodeClassifier(LinearSVC(), random_state=0) + ecoc = OutputCodeClassifier(LinearSVC(random_state=0), + random_state=0) Cs = [0.1, 0.5, 0.8] cv = GridSearchCV(ecoc, {'estimator__C': Cs}) cv.fit(iris.data, iris.target) best_C = cv.best_estimator_.estimators_[0].C assert_true(best_C in Cs) + + +@ignore_warnings +def test_deprecated(): + base_estimator = DecisionTreeClassifier(random_state=0) + X, Y = iris.data, iris.target + X_train, Y_train = X[:80], Y[:80] + X_test = X[80:] + + all_metas = [ + (OneVsRestClassifier, fit_ovr, predict_ovr, predict_proba_ovr), + (OneVsOneClassifier, fit_ovo, predict_ovo, None), + (OutputCodeClassifier, fit_ecoc, predict_ecoc, None), + ] + + for MetaEst, fit_func, predict_func, proba_func in all_metas: + try: + meta_est = MetaEst(base_estimator, + random_state=0).fit(X_train, Y_train) + + fitted_return = fit_func(base_estimator, X_train, Y_train, + random_state=0) + except TypeError: + meta_est = MetaEst(base_estimator).fit(X_train, Y_train) + fitted_return = fit_func(base_estimator, X_train, Y_train) + + if len(fitted_return) == 2: + estimators_, classes_or_lb = fitted_return + assert_almost_equal(predict_func(estimators_, classes_or_lb, + X_test), + meta_est.predict(X_test)) + if proba_func is not None: + assert_almost_equal(proba_func(estimators_, X_test, + is_multilabel=False), + meta_est.predict_proba(X_test)) + + else: + estimators_, classes_or_lb, codebook = fitted_return + assert_almost_equal(predict_func(estimators_, classes_or_lb, + codebook, X_test), + meta_est.predict(X_test)) + + +if __name__ == "__main__": + import nose + nose.runmodule() diff --git a/sklearn/tests/test_naive_bayes.py b/sklearn/tests/test_naive_bayes.py index 4028595c46049..658130e3ec75f 100644 --- a/sklearn/tests/test_naive_bayes.py +++ b/sklearn/tests/test_naive_bayes.py @@ -3,12 +3,16 @@ import numpy as np import scipy.sparse -from cStringIO import StringIO -from numpy.testing import assert_almost_equal -from numpy.testing import assert_array_equal -from numpy.testing import assert_array_almost_equal -from numpy.testing import assert_equal -from nose.tools import assert_raises +from sklearn.datasets import load_digits, load_iris +from sklearn.cross_validation import cross_val_score, train_test_split + +from sklearn.externals.six.moves import zip +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_greater from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB @@ -43,6 +47,11 @@ def test_gnb(): y_pred_log_proba = clf.predict_log_proba(X) assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8) + # Test whether label mismatch between target y and classes raises + # an Error + # FIXME Remove this test once the more general partial_fit tests are merged + assert_raises(ValueError, GaussianNB().partial_fit, X, y, classes=[0, 1]) + def test_gnb_prior(): """Test whether class priors are properly set. """ @@ -54,6 +63,38 @@ def test_gnb_prior(): assert_array_almost_equal(clf.class_prior_.sum(), 1) +def test_gnb_sample_weight(): + """Test whether sample weights are properly used in GNB. """ + # Sample weights all being 1 should not change results + sw = np.ones(6) + clf = GaussianNB().fit(X, y) + clf_sw = GaussianNB().fit(X, y, sw) + + assert_array_almost_equal(clf.theta_, clf_sw.theta_) + assert_array_almost_equal(clf.sigma_, clf_sw.sigma_) + + # Fitting twice with half sample-weights should result + # in same result as fitting once with full weights + sw = rng.rand(y.shape[0]) + clf1 = GaussianNB().fit(X, y, sample_weight=sw) + clf2 = GaussianNB().partial_fit(X, y, classes=[1, 2], sample_weight=sw / 2) + clf2.partial_fit(X, y, sample_weight=sw / 2) + + assert_array_almost_equal(clf1.theta_, clf2.theta_) + assert_array_almost_equal(clf1.sigma_, clf2.sigma_) + + # Check that duplicate entries and correspondingly increased sample + # weights yield the same result + ind = rng.randint(0, X.shape[0], 20) + sample_weight = np.bincount(ind, minlength=X.shape[0]) + + clf_dupl = GaussianNB().fit(X[ind], y[ind]) + clf_sw = GaussianNB().fit(X, y, sample_weight) + + assert_array_almost_equal(clf_dupl.theta_, clf_sw.theta_) + assert_array_almost_equal(clf_dupl.sigma_, clf_sw.sigma_) + + def test_discrete_prior(): """Test whether class priors are properly set. """ for cls in [BernoulliNB, MultinomialNB]: @@ -63,8 +104,7 @@ def test_discrete_prior(): def test_mnnb(): - """ - Multinomial Naive Bayes classification. + """Test Multinomial Naive Bayes classification. This checks that MultinomialNB implements fit and predict and returns correct values for a simple toy dataset. @@ -84,6 +124,68 @@ def test_mnnb(): y_pred_log_proba = clf.predict_log_proba(X) assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8) + # Check that incremental fitting yields the same results + clf2 = MultinomialNB() + clf2.partial_fit(X[:2], y2[:2], classes=np.unique(y2)) + clf2.partial_fit(X[2:5], y2[2:5]) + clf2.partial_fit(X[5:], y2[5:]) + + y_pred2 = clf2.predict(X) + assert_array_equal(y_pred2, y2) + + y_pred_proba2 = clf2.predict_proba(X) + y_pred_log_proba2 = clf2.predict_log_proba(X) + assert_array_almost_equal(np.log(y_pred_proba2), y_pred_log_proba2, 8) + assert_array_almost_equal(y_pred_proba2, y_pred_proba) + assert_array_almost_equal(y_pred_log_proba2, y_pred_log_proba) + + # Partial fit on the whole data at once should be the same as fit too + clf3 = MultinomialNB() + clf3.partial_fit(X, y2, classes=np.unique(y2)) + + y_pred3 = clf3.predict(X) + assert_array_equal(y_pred3, y2) + y_pred_proba3 = clf3.predict_proba(X) + y_pred_log_proba3 = clf3.predict_log_proba(X) + assert_array_almost_equal(np.log(y_pred_proba3), y_pred_log_proba3, 8) + assert_array_almost_equal(y_pred_proba3, y_pred_proba) + assert_array_almost_equal(y_pred_log_proba3, y_pred_log_proba) + + +def check_partial_fit(cls): + clf1 = cls() + clf1.fit([[0, 1], [1, 0]], [0, 1]) + + clf2 = cls() + clf2.partial_fit([[0, 1], [1, 0]], [0, 1], classes=[0, 1]) + assert_array_equal(clf1.class_count_, clf2.class_count_) + assert_array_equal(clf1.feature_count_, clf2.feature_count_) + + clf3 = cls() + clf3.partial_fit([[0, 1]], [0], classes=[0, 1]) + clf3.partial_fit([[1, 0]], [1]) + assert_array_equal(clf1.class_count_, clf3.class_count_) + assert_array_equal(clf1.feature_count_, clf3.feature_count_) + + +def test_discretenb_partial_fit(): + for cls in [MultinomialNB, BernoulliNB]: + yield check_partial_fit, cls + + +def test_gnb_partial_fit(): + clf = GaussianNB().fit(X, y) + clf_pf = GaussianNB().partial_fit(X, y, np.unique(y)) + assert_array_almost_equal(clf.theta_, clf_pf.theta_) + assert_array_almost_equal(clf.sigma_, clf_pf.sigma_) + assert_array_almost_equal(clf.class_prior_, clf_pf.class_prior_) + + clf_pf2 = GaussianNB().partial_fit(X[0::2, :], y[0::2], np.unique(y)) + clf_pf2.partial_fit(X[1::2], y[1::2]) + assert_array_almost_equal(clf.theta_, clf_pf2.theta_) + assert_array_almost_equal(clf.sigma_, clf_pf2.sigma_) + assert_array_almost_equal(clf.class_prior_, clf_pf2.class_prior_) + def test_discretenb_pickle(): """Test picklability of discrete naive Bayes classifiers""" @@ -92,22 +194,55 @@ def test_discretenb_pickle(): clf = cls().fit(X2, y2) y_pred = clf.predict(X2) - store = StringIO() + store = BytesIO() pickle.dump(clf, store) - clf = pickle.load(StringIO(store.getvalue())) + clf = pickle.load(BytesIO(store.getvalue())) assert_array_equal(y_pred, clf.predict(X2)) - store = BytesIO() - pickle.dump(clf, store) - clf = pickle.load(BytesIO(store.getvalue())) + if cls is not GaussianNB: + # TODO re-enable me when partial_fit is implemented for GaussianNB + # Test pickling of estimator trained with partial_fit + clf2 = cls().partial_fit(X2[:3], y2[:3], classes=np.unique(y2)) + clf2.partial_fit(X2[3:], y2[3:]) + store = BytesIO() + pickle.dump(clf2, store) + clf2 = pickle.load(BytesIO(store.getvalue())) + assert_array_equal(y_pred, clf2.predict(X2)) -def test_input_check(): - """Test input checks""" + +def test_input_check_fit(): + """Test input checks for the fit method""" for cls in [BernoulliNB, MultinomialNB, GaussianNB]: + # check shape consistency for number of samples at fit time + assert_raises(ValueError, cls().fit, X2, y2[:-1]) + + # check shape consistency for number of input features at predict time + clf = cls().fit(X2, y2) + assert_raises(ValueError, clf.predict, X2[:, :-1]) + + +def test_input_check_partial_fit(): + for cls in [BernoulliNB, MultinomialNB]: + # check shape consistency + assert_raises(ValueError, cls().partial_fit, X2, y2[:-1], + classes=np.unique(y2)) + + # classes is required for first call to partial fit + assert_raises(ValueError, cls().partial_fit, X2, y2) + + # check consistency of consecutive classes values clf = cls() - assert_raises(ValueError, clf.fit, X2, y2[:-1]) + clf.partial_fit(X2, y2, classes=np.unique(y2)) + assert_raises(ValueError, clf.partial_fit, X2, y2, + classes=np.arange(42)) + + # check consistency of input shape for partial_fit + assert_raises(ValueError, clf.partial_fit, X2[:, :-1], y2) + + # check consistency of input shape for predict + assert_raises(ValueError, clf.predict, X2[:, :-1]) def test_discretenb_predict_proba(): @@ -157,18 +292,188 @@ def test_discretenb_provide_prior(): """Test whether discrete NB classes use provided prior""" for cls in [BernoulliNB, MultinomialNB]: - clf = cls() - clf.fit([[0], [0], [1]], [0, 0, 1], class_prior=[0.5, 0.5]) + clf = cls(class_prior=[0.5, 0.5]) + clf.fit([[0], [0], [1]], [0, 0, 1]) prior = np.exp(clf.class_log_prior_) assert_array_equal(prior, np.array([.5, .5])) + # Inconsistent number of classes with prior + assert_raises(ValueError, clf.fit, [[0], [1], [2]], [0, 1, 2]) + assert_raises(ValueError, clf.partial_fit, [[0], [1]], [0, 1], + classes=[0, 1, 1]) + -def test_sample_weight(): +def test_discretenb_provide_prior_with_partial_fit(): + """Test whether discrete NB classes use provided prior + when using partial_fit""" + + iris = load_iris() + iris_data1, iris_data2, iris_target1, iris_target2 = train_test_split( + iris.data, iris.target, test_size=0.4, random_state=415) + + for cls in [BernoulliNB, MultinomialNB]: + for prior in [None, [0.3, 0.3, 0.4]]: + clf_full = cls(class_prior=prior) + clf_full.fit(iris.data, iris.target) + clf_partial = cls(class_prior=prior) + clf_partial.partial_fit(iris_data1, iris_target1, + classes=[0, 1, 2]) + clf_partial.partial_fit(iris_data2, iris_target2) + assert_array_almost_equal(clf_full.class_log_prior_, + clf_partial.class_log_prior_) + + +def test_sample_weight_multiclass(): + for cls in [BernoulliNB, MultinomialNB]: + # check shape consistency for number of samples at fit time + yield check_sample_weight_multiclass, cls + + +def check_sample_weight_multiclass(cls): + X = [ + [0, 0, 1], + [0, 1, 1], + [0, 1, 1], + [1, 0, 0], + ] + y = [0, 0, 1, 2] + sample_weight = np.array([1, 1, 2, 2], dtype=np.float) + sample_weight /= sample_weight.sum() + clf = cls().fit(X, y, sample_weight=sample_weight) + assert_array_equal(clf.predict(X), [0, 1, 1, 2]) + + # Check sample weight using the partial_fit method + clf = cls() + clf.partial_fit(X[:2], y[:2], classes=[0, 1, 2], + sample_weight=sample_weight[:2]) + clf.partial_fit(X[2:3], y[2:3], sample_weight=sample_weight[2:3]) + clf.partial_fit(X[3:], y[3:], sample_weight=sample_weight[3:]) + assert_array_equal(clf.predict(X), [0, 1, 1, 2]) + + +def test_sample_weight_mnb(): clf = MultinomialNB() clf.fit([[1, 2], [1, 2], [1, 0]], [0, 0, 1], sample_weight=[1, 1, 4]) assert_array_equal(clf.predict([1, 0]), [1]) - positive_prior = np.exp(clf.intercept_) + positive_prior = np.exp(clf.intercept_[0]) assert_array_almost_equal([1 - positive_prior, positive_prior], [1 / 3., 2 / 3.]) + + +def test_coef_intercept_shape(): + """coef_ and intercept_ should have shapes as in other linear models. + + Non-regression test for issue #2127. + """ + X = [[1, 0, 0], [1, 1, 1]] + y = [1, 2] # binary classification + + for clf in [MultinomialNB(), BernoulliNB()]: + clf.fit(X, y) + assert_equal(clf.coef_.shape, (1, 3)) + assert_equal(clf.intercept_.shape, (1,)) + + +def test_check_accuracy_on_digits(): + # Non regression test to make sure that any further refactoring / optim + # of the NB models do not harm the performance on a slightly non-linearly + # separable dataset + digits = load_digits() + X, y = digits.data, digits.target + binary_3v8 = np.logical_or(digits.target == 3, digits.target == 8) + X_3v8, y_3v8 = X[binary_3v8], y[binary_3v8] + + # Multinomial NB + scores = cross_val_score(MultinomialNB(alpha=10), X, y, cv=10) + assert_greater(scores.mean(), 0.86) + + scores = cross_val_score(MultinomialNB(alpha=10), X_3v8, y_3v8, cv=10) + assert_greater(scores.mean(), 0.94) + + # Bernoulli NB + scores = cross_val_score(BernoulliNB(alpha=10), X > 4, y, cv=10) + assert_greater(scores.mean(), 0.83) + + scores = cross_val_score(BernoulliNB(alpha=10), X_3v8 > 4, y_3v8, cv=10) + assert_greater(scores.mean(), 0.92) + + # Gaussian NB + scores = cross_val_score(GaussianNB(), X, y, cv=10) + assert_greater(scores.mean(), 0.77) + + scores = cross_val_score(GaussianNB(), X_3v8, y_3v8, cv=10) + assert_greater(scores.mean(), 0.86) + + +def test_feature_log_prob_bnb(): + """Test for issue #4268. + + Tests that the feature log prob value computed by BernoulliNB when + alpha=1.0 is equal to the expression given in Manning, Raghavan, + and Schuetze's "Introduction to Information Retrieval" book: + http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html + """ + + X = np.array([[0, 0, 0], [1, 1, 0], [0, 1, 0], [1, 0, 1], [0, 1, 0]]) + Y = np.array([0, 0, 1, 2, 2]) + + # Fit Bernoulli NB w/ alpha = 1.0 + clf = BernoulliNB(alpha=1.0) + clf.fit(X, Y) + + # Manually form the (log) numerator and denominator that + # constitute P(feature presence | class) + num = np.log(clf.feature_count_ + 1.0) + denom = np.tile(np.log(clf.class_count_ + 2.0), (X.shape[1], 1)).T + + # Check manual estimate matches + assert_array_equal(clf.feature_log_prob_, (num - denom)) + + +def test_bnb(): + """ + Tests that BernoulliNB when alpha=1.0 gives the same values as + those given for the toy example in Manning, Raghavan, and + Schuetze's "Introduction to Information Retrieval" book: + http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html + """ + + # Training data points are: + # Chinese Beijing Chinese (class: China) + # Chinese Chinese Shanghai (class: China) + # Chinese Macao (class: China) + # Tokyo Japan Chinese (class: Japan) + + # Features are Beijing, Chinese, Japan, Macao, Shanghai, and Tokyo + X = np.array([[1, 1, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 0], + [0, 1, 0, 1, 0, 0], + [0, 1, 1, 0, 0, 1]]) + + # Classes are China (0), Japan (1) + Y = np.array([0, 0, 0, 1]) + + # Fit BernoulliBN w/ alpha = 1.0 + clf = BernoulliNB(alpha=1.0) + clf.fit(X, Y) + + # Check the class prior is correct + class_prior = np.array([0.75, 0.25]) + assert_array_almost_equal(np.exp(clf.class_log_prior_), class_prior) + + # Check the feature probabilities are correct + feature_prob = np.array([[0.4, 0.8, 0.2, 0.4, 0.4, 0.2], + [1/3.0, 2/3.0, 2/3.0, 1/3.0, 1/3.0, 2/3.0]]) + assert_array_almost_equal(np.exp(clf.feature_log_prob_), feature_prob) + + # Testing data point is: + # Chinese Chinese Chinese Tokyo Japan + X_test = np.array([0, 1, 1, 0, 0, 1]) + + # Check the predictive probabilities are correct + unnorm_predict_proba = np.array([[0.005183999999999999, + 0.02194787379972565]]) + predict_proba = unnorm_predict_proba / np.sum(unnorm_predict_proba) + assert_array_almost_equal(clf.predict_proba(X_test), predict_proba) diff --git a/sklearn/tests/test_pipeline.py b/sklearn/tests/test_pipeline.py index 258c4b0598ee6..c57ac01664a6a 100644 --- a/sklearn/tests/test_pipeline.py +++ b/sklearn/tests/test_pipeline.py @@ -2,20 +2,39 @@ Test the pipeline module. """ import numpy as np +from scipy import sparse -from nose.tools import assert_raises, assert_equal, assert_false, assert_true +from sklearn.externals.six.moves import zip +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal from sklearn.base import BaseEstimator, clone -from sklearn.pipeline import Pipeline +from sklearn.pipeline import Pipeline, FeatureUnion, make_pipeline, make_union from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression +from sklearn.linear_model import LinearRegression from sklearn.feature_selection import SelectKBest, f_classif -from sklearn.decomposition.pca import PCA, RandomizedPCA +from sklearn.decomposition import PCA, RandomizedPCA, TruncatedSVD from sklearn.datasets import load_iris from sklearn.preprocessing import StandardScaler +from sklearn.feature_extraction.text import CountVectorizer -class IncorrectT(BaseEstimator): +JUNK_FOOD_DOCS = ( + "the pizza pizza beer copyright", + "the pizza burger beer copyright", + "the the pizza beer beer copyright", + "the burger beer beer copyright", + "the coke burger coke copyright", + "the coke burger burger", +) + + +class IncorrectT(object): """Small class to test parameter dispatching. """ @@ -29,6 +48,12 @@ class T(IncorrectT): def fit(self, X, y): return self + def get_params(self, deep=False): + return {'a': self.a, 'b': self.b} + + def set_params(self, **params): + self.a = params['a'] + return self class TransfT(T): @@ -36,7 +61,7 @@ def transform(self, X, y=None): return X -class FitParamT(BaseEstimator): +class FitParamT(object): """Mock classifier """ @@ -57,8 +82,7 @@ def test_pipeline_init(): assert_raises(TypeError, Pipeline) # Check that we can't instantiate pipelines with objects without fit # method - pipe = assert_raises(TypeError, Pipeline, - [('svc', IncorrectT)]) + pipe = assert_raises(TypeError, Pipeline, [('svc', IncorrectT)]) # Smoke test with only an estimator clf = T() pipe = Pipeline([('svc', clf)]) @@ -68,6 +92,7 @@ def test_pipeline_init(): # Check that params are set pipe.set_params(svc__a=0.1) assert_equal(clf.a, 0.1) + assert_equal(clf.b, None) # Smoke test the repr: repr(pipe) @@ -76,6 +101,9 @@ def test_pipeline_init(): filter1 = SelectKBest(f_classif) pipe = Pipeline([('anova', filter1), ('svc', clf)]) + # Check that we can't use the same stage name twice + assert_raises(ValueError, Pipeline, [('svc', SVC()), ('svc', SVC())]) + # Check that params are set pipe.set_params(svc__C=0.1) assert_equal(clf.C, 0.1) @@ -89,7 +117,7 @@ def test_pipeline_init(): pipe2 = clone(pipe) assert_false(pipe.named_steps['svc'] is pipe2.named_steps['svc']) - # Check that appart from estimators, the parameters are the same + # Check that apart from estimators, the parameters are the same params = pipe.get_params() params2 = pipe2.get_params() # Remove estimators that where copied @@ -135,7 +163,7 @@ def test_pipeline_methods_pca_svm(): X = iris.data y = iris.target # Test with PCA + SVC - clf = SVC(probability=True) + clf = SVC(probability=True, random_state=0) pca = PCA(n_components='mle', whiten=True) pipe = Pipeline([('pca', pca), ('svc', clf)]) pipe.fit(X, y) @@ -154,10 +182,10 @@ def test_pipeline_methods_preprocessing_svm(): n_classes = len(np.unique(y)) scaler = StandardScaler() pca = RandomizedPCA(n_components=2, whiten=True) - clf = SVC(probability=True) + clf = SVC(probability=True, random_state=0) for preprocessing in [scaler, pca]: - pipe = Pipeline([('scaler', scaler), ('svc', clf)]) + pipe = Pipeline([('preprocess', preprocessing), ('svc', clf)]) pipe.fit(X, y) # check shapes of various prediction functions @@ -174,3 +202,202 @@ def test_pipeline_methods_preprocessing_svm(): assert_equal(decision_function.shape, (n_samples, n_classes)) pipe.score(X, y) + + +def test_feature_union(): + # basic sanity check for feature union + iris = load_iris() + X = iris.data + X -= X.mean(axis=0) + y = iris.target + svd = TruncatedSVD(n_components=2, random_state=0) + select = SelectKBest(k=1) + fs = FeatureUnion([("svd", svd), ("select", select)]) + fs.fit(X, y) + X_transformed = fs.transform(X) + assert_equal(X_transformed.shape, (X.shape[0], 3)) + + # check if it does the expected thing + assert_array_almost_equal(X_transformed[:, :-1], svd.fit_transform(X)) + assert_array_equal(X_transformed[:, -1], + select.fit_transform(X, y).ravel()) + + # test if it also works for sparse input + # We use a different svd object to control the random_state stream + fs = FeatureUnion([("svd", svd), ("select", select)]) + X_sp = sparse.csr_matrix(X) + X_sp_transformed = fs.fit_transform(X_sp, y) + assert_array_almost_equal(X_transformed, X_sp_transformed.toarray()) + + # test setting parameters + fs.set_params(select__k=2) + assert_equal(fs.fit_transform(X, y).shape, (X.shape[0], 4)) + + # test it works with transformers missing fit_transform + fs = FeatureUnion([("mock", TransfT()), ("svd", svd), ("select", select)]) + X_transformed = fs.fit_transform(X, y) + assert_equal(X_transformed.shape, (X.shape[0], 8)) + + +def test_make_union(): + pca = PCA() + mock = TransfT() + fu = make_union(pca, mock) + names, transformers = zip(*fu.transformer_list) + assert_equal(names, ("pca", "transft")) + assert_equal(transformers, (pca, mock)) + + +def test_pipeline_transform(): + # Test whether pipeline works with a transformer at the end. + # Also test pipeline.transform and pipeline.inverse_transform + iris = load_iris() + X = iris.data + pca = PCA(n_components=2) + pipeline = Pipeline([('pca', pca)]) + + # test transform and fit_transform: + X_trans = pipeline.fit(X).transform(X) + X_trans2 = pipeline.fit_transform(X) + X_trans3 = pca.fit_transform(X) + assert_array_almost_equal(X_trans, X_trans2) + assert_array_almost_equal(X_trans, X_trans3) + + X_back = pipeline.inverse_transform(X_trans) + X_back2 = pca.inverse_transform(X_trans) + assert_array_almost_equal(X_back, X_back2) + + +def test_pipeline_fit_transform(): + # Test whether pipeline works with a transformer missing fit_transform + iris = load_iris() + X = iris.data + y = iris.target + transft = TransfT() + pipeline = Pipeline([('mock', transft)]) + + # test fit_transform: + X_trans = pipeline.fit_transform(X, y) + X_trans2 = transft.fit(X, y).transform(X) + assert_array_almost_equal(X_trans, X_trans2) + + +def test_make_pipeline(): + t1 = TransfT() + t2 = TransfT() + + pipe = make_pipeline(t1, t2) + assert_true(isinstance(pipe, Pipeline)) + assert_equal(pipe.steps[0][0], "transft-1") + assert_equal(pipe.steps[1][0], "transft-2") + + pipe = make_pipeline(t1, t2, FitParamT()) + assert_true(isinstance(pipe, Pipeline)) + assert_equal(pipe.steps[0][0], "transft-1") + assert_equal(pipe.steps[1][0], "transft-2") + assert_equal(pipe.steps[2][0], "fitparamt") + + +def test_feature_union_weights(): + # test feature union with transformer weights + iris = load_iris() + X = iris.data + y = iris.target + pca = RandomizedPCA(n_components=2, random_state=0) + select = SelectKBest(k=1) + # test using fit followed by transform + fs = FeatureUnion([("pca", pca), ("select", select)], + transformer_weights={"pca": 10}) + fs.fit(X, y) + X_transformed = fs.transform(X) + # test using fit_transform + fs = FeatureUnion([("pca", pca), ("select", select)], + transformer_weights={"pca": 10}) + X_fit_transformed = fs.fit_transform(X, y) + # test it works with transformers missing fit_transform + fs = FeatureUnion([("mock", TransfT()), ("pca", pca), ("select", select)], + transformer_weights={"mock": 10}) + X_fit_transformed_wo_method = fs.fit_transform(X, y) + # check against expected result + + # We use a different pca object to control the random_state stream + assert_array_almost_equal(X_transformed[:, :-1], 10 * pca.fit_transform(X)) + assert_array_equal(X_transformed[:, -1], + select.fit_transform(X, y).ravel()) + assert_array_almost_equal(X_fit_transformed[:, :-1], + 10 * pca.fit_transform(X)) + assert_array_equal(X_fit_transformed[:, -1], + select.fit_transform(X, y).ravel()) + assert_equal(X_fit_transformed_wo_method.shape, (X.shape[0], 7)) + + +def test_feature_union_parallel(): + # test that n_jobs work for FeatureUnion + X = JUNK_FOOD_DOCS + + fs = FeatureUnion([ + ("words", CountVectorizer(analyzer='word')), + ("chars", CountVectorizer(analyzer='char')), + ]) + + fs_parallel = FeatureUnion([ + ("words", CountVectorizer(analyzer='word')), + ("chars", CountVectorizer(analyzer='char')), + ], n_jobs=2) + + fs_parallel2 = FeatureUnion([ + ("words", CountVectorizer(analyzer='word')), + ("chars", CountVectorizer(analyzer='char')), + ], n_jobs=2) + + fs.fit(X) + X_transformed = fs.transform(X) + assert_equal(X_transformed.shape[0], len(X)) + + fs_parallel.fit(X) + X_transformed_parallel = fs_parallel.transform(X) + assert_equal(X_transformed.shape, X_transformed_parallel.shape) + assert_array_equal( + X_transformed.toarray(), + X_transformed_parallel.toarray() + ) + + # fit_transform should behave the same + X_transformed_parallel2 = fs_parallel2.fit_transform(X) + assert_array_equal( + X_transformed.toarray(), + X_transformed_parallel2.toarray() + ) + + # transformers should stay fit after fit_transform + X_transformed_parallel2 = fs_parallel2.transform(X) + assert_array_equal( + X_transformed.toarray(), + X_transformed_parallel2.toarray() + ) + + +def test_feature_union_feature_names(): + word_vect = CountVectorizer(analyzer="word") + char_vect = CountVectorizer(analyzer="char_wb", ngram_range=(3, 3)) + ft = FeatureUnion([("chars", char_vect), ("words", word_vect)]) + ft.fit(JUNK_FOOD_DOCS) + feature_names = ft.get_feature_names() + for feat in feature_names: + assert_true("chars__" in feat or "words__" in feat) + assert_equal(len(feature_names), 35) + + +def test_classes_property(): + iris = load_iris() + X = iris.data + y = iris.target + + reg = make_pipeline(SelectKBest(k=1), LinearRegression()) + reg.fit(X, y) + assert_raises(AttributeError, getattr, reg, "classes_") + + clf = make_pipeline(SelectKBest(k=1), LogisticRegression(random_state=0)) + assert_raises(AttributeError, getattr, clf, "classes_") + clf.fit(X, y) + assert_array_equal(clf.classes_, np.unique(y)) diff --git a/sklearn/tests/test_preprocessing.py b/sklearn/tests/test_preprocessing.py deleted file mode 100644 index 456b06ee68688..0000000000000 --- a/sklearn/tests/test_preprocessing.py +++ /dev/null @@ -1,546 +0,0 @@ -import numpy as np -import numpy.linalg as la -import scipy.sparse as sp - -from numpy.testing import assert_almost_equal -from numpy.testing import assert_array_almost_equal -from numpy.testing import assert_array_equal -from numpy.testing import assert_equal - -from nose.tools import assert_raises, assert_true, assert_false - -from sklearn.utils.sparsefuncs import mean_variance_axis0 -from sklearn.preprocessing import Binarizer -from sklearn.preprocessing import KernelCenterer -from sklearn.preprocessing import LabelBinarizer -from sklearn.preprocessing import LabelEncoder -from sklearn.preprocessing import Normalizer -from sklearn.preprocessing import normalize -from sklearn.preprocessing import StandardScaler -from sklearn.preprocessing import scale -from sklearn.preprocessing import MinMaxScaler - -from sklearn import datasets -from sklearn.linear_model.stochastic_gradient import SGDClassifier - -iris = datasets.load_iris() - - -def toarray(a): - if hasattr(a, "toarray"): - a = a.toarray() - return a - - -def test_scaler_1d(): - """Test scaling of dataset along single axis""" - rng = np.random.RandomState(0) - X = rng.randn(5) - X_orig_copy = X.copy() - - scaler = StandardScaler() - X_scaled = scaler.fit(X).transform(X, copy=False) - assert_array_almost_equal(X_scaled.mean(axis=0), 0.0) - assert_array_almost_equal(X_scaled.std(axis=0), 1.0) - - # check inverse transform - X_scaled_back = scaler.inverse_transform(X_scaled) - assert_array_almost_equal(X_scaled_back, X_orig_copy) - - # Test with 1D list - X = [0., 1., 2, 0.4, 1.] - scaler = StandardScaler() - X_scaled = scaler.fit(X).transform(X, copy=False) - assert_array_almost_equal(X_scaled.mean(axis=0), 0.0) - assert_array_almost_equal(X_scaled.std(axis=0), 1.0) - - X_scaled = scale(X) - assert_array_almost_equal(X_scaled.mean(axis=0), 0.0) - assert_array_almost_equal(X_scaled.std(axis=0), 1.0) - - -def test_scaler_2d_arrays(): - """Test scaling of 2d array along first axis""" - rng = np.random.RandomState(0) - X = rng.randn(4, 5) - X[:, 0] = 0.0 # first feature is always of zero - - scaler = StandardScaler() - X_scaled = scaler.fit(X).transform(X, copy=True) - assert_false(np.any(np.isnan(X_scaled))) - - assert_array_almost_equal(X_scaled.mean(axis=0), 5 * [0.0]) - assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) - # Check that X has not been copied - assert_true(X_scaled is not X) - - # check inverse transform - X_scaled_back = scaler.inverse_transform(X_scaled) - assert_true(X_scaled_back is not X) - assert_true(X_scaled_back is not X_scaled) - assert_array_almost_equal(X_scaled_back, X) - - X_scaled = scale(X, axis=1, with_std=False) - assert_false(np.any(np.isnan(X_scaled))) - assert_array_almost_equal(X_scaled.mean(axis=1), 4 * [0.0]) - X_scaled = scale(X, axis=1, with_std=True) - assert_false(np.any(np.isnan(X_scaled))) - assert_array_almost_equal(X_scaled.mean(axis=1), 4 * [0.0]) - assert_array_almost_equal(X_scaled.std(axis=1), 4 * [1.0]) - # Check that the data hasn't been modified - assert_true(X_scaled is not X) - - X_scaled = scaler.fit(X).transform(X, copy=False) - assert_false(np.any(np.isnan(X_scaled))) - assert_array_almost_equal(X_scaled.mean(axis=0), 5 * [0.0]) - assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) - # Check that X has not been copied - assert_true(X_scaled is X) - - X = rng.randn(4, 5) - X[:, 0] = 1.0 # first feature is a constant, non zero feature - scaler = StandardScaler() - X_scaled = scaler.fit(X).transform(X, copy=True) - assert_false(np.any(np.isnan(X_scaled))) - assert_array_almost_equal(X_scaled.mean(axis=0), 5 * [0.0]) - assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) - # Check that X has not been copied - assert_true(X_scaled is not X) - - -def test_min_max_scaler(): - X = iris.data - scaler = MinMaxScaler() - # default params - X_trans = scaler.fit_transform(X) - assert_equal(X_trans.min(axis=0), 0) - assert_equal(X_trans.max(axis=0), 1) - - # not default params - scaler = MinMaxScaler(feature_range=(1, 2)) - X_trans = scaler.fit_transform(X) - assert_equal(X_trans.min(axis=0), 1) - assert_equal(X_trans.max(axis=0), 2) - - -def test_scaler_without_centering(): - rng = np.random.RandomState(42) - X = rng.randn(4, 5) - X[:, 0] = 0.0 # first feature is always of zero - X_csr = sp.csr_matrix(X) - - scaler = StandardScaler(with_mean=False).fit(X) - X_scaled = scaler.transform(X, copy=True) - assert_false(np.any(np.isnan(X_scaled))) - - scaler_csr = StandardScaler(with_mean=False).fit(X_csr) - X_csr_scaled = scaler_csr.transform(X_csr, copy=True) - assert_false(np.any(np.isnan(X_csr_scaled.data))) - - assert_equal(scaler.mean_, scaler_csr.mean_) - assert_array_almost_equal(scaler.std_, scaler_csr.std_) - - assert_array_almost_equal( - X_scaled.mean(axis=0), [0., -0.01, 2.24, -0.35, -0.78], 2) - assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) - - X_csr_scaled_mean, X_csr_scaled_std = mean_variance_axis0(X_csr_scaled) - assert_array_almost_equal(X_csr_scaled_mean, X_scaled.mean(axis=0)) - assert_array_almost_equal(X_csr_scaled_std, X_scaled.std(axis=0)) - - # Check that X has not been modified (copy) - assert_true(X_scaled is not X) - assert_true(X_csr_scaled is not X_csr) - - X_scaled_back = scaler.inverse_transform(X_scaled) - assert_true(X_scaled_back is not X) - assert_true(X_scaled_back is not X_scaled) - assert_array_almost_equal(X_scaled_back, X) - - X_csr_scaled_back = scaler_csr.inverse_transform(X_csr_scaled) - assert_true(X_csr_scaled_back is not X_csr) - assert_true(X_csr_scaled_back is not X_csr_scaled) - assert_array_almost_equal(X_scaled_back, X) - - -def test_scaler_without_copy(): - """Check that StandardScaler.fit does not change input""" - rng = np.random.RandomState(42) - X = rng.randn(4, 5) - X[:, 0] = 0.0 # first feature is always of zero - X_csr = sp.csr_matrix(X) - - X_copy = X.copy() - StandardScaler(copy=False).fit(X) - assert_array_equal(X, X_copy) - - X_csr_copy = X_csr.copy() - StandardScaler(with_mean=False, copy=False).fit(X_csr) - assert_array_equal(X_csr.toarray(), X_csr_copy.toarray()) - - -def test_scale_sparse_with_mean_raise_exception(): - rng = np.random.RandomState(42) - X = rng.randn(4, 5) - X_csr = sp.csr_matrix(X) - - # check scaling and fit with direct calls on sparse data - assert_raises(ValueError, scale, X_csr, with_mean=True) - assert_raises(ValueError, StandardScaler(with_mean=True).fit, X_csr) - - # check transform and inverse_transform after a fit on a dense array - scaler = StandardScaler(with_mean=True).fit(X) - assert_raises(ValueError, scaler.transform, X_csr) - - X_transformed_csr = sp.csr_matrix(scaler.transform(X)) - assert_raises(ValueError, scaler.inverse_transform, X_transformed_csr) - - -def test_scale_function_without_centering(): - rng = np.random.RandomState(42) - X = rng.randn(4, 5) - X[:, 0] = 0.0 # first feature is always of zero - X_csr = sp.csr_matrix(X) - - X_scaled = scale(X, with_mean=False) - assert_false(np.any(np.isnan(X_scaled))) - - X_csr_scaled = scale(X_csr, with_mean=False) - assert_false(np.any(np.isnan(X_csr_scaled.data))) - - assert_array_almost_equal( - X_scaled.mean(axis=0), [0., -0.01, 2.24, -0.35, -0.78], 2) - assert_array_almost_equal(X_scaled.std(axis=0), [0., 1., 1., 1., 1.]) - # Check that X has not been copied - assert_true(X_scaled is not X) - - X_csr_scaled_mean, X_csr_scaled_std = mean_variance_axis0(X_csr_scaled) - assert_array_almost_equal(X_csr_scaled_mean, X_scaled.mean(axis=0)) - assert_array_almost_equal(X_csr_scaled_std, X_scaled.std(axis=0)) - - -def test_normalizer_l1(): - rng = np.random.RandomState(0) - X_dense = rng.randn(4, 5) - X_sparse_unpruned = sp.csr_matrix(X_dense) - - # set the row number 3 to zero - X_dense[3, :] = 0.0 - - # set the row number 3 to zero without pruning (can happen in real life) - indptr_3 = X_sparse_unpruned.indptr[3] - indptr_4 = X_sparse_unpruned.indptr[4] - X_sparse_unpruned.data[indptr_3:indptr_4] = 0.0 - - # build the pruned variant using the regular constructor - X_sparse_pruned = sp.csr_matrix(X_dense) - - # check inputs that support the no-copy optim - for X in (X_dense, X_sparse_pruned, X_sparse_unpruned): - - normalizer = Normalizer(norm='l1', copy=True) - X_norm = normalizer.transform(X) - assert_true(X_norm is not X) - X_norm1 = toarray(X_norm) - - normalizer = Normalizer(norm='l1', copy=False) - X_norm = normalizer.transform(X) - assert_true(X_norm is X) - X_norm2 = toarray(X_norm) - - for X_norm in (X_norm1, X_norm2): - row_sums = np.abs(X_norm).sum(axis=1) - for i in range(3): - assert_almost_equal(row_sums[i], 1.0) - assert_almost_equal(row_sums[3], 0.0) - - # check input for which copy=False won't prevent a copy - for init in (sp.coo_matrix, sp.csc_matrix, sp.lil_matrix): - X = init(X_dense) - X_norm = normalizer = Normalizer(norm='l2', copy=False).transform(X) - - assert_true(X_norm is not X) - assert_true(isinstance(X_norm, sp.csr_matrix)) - - X_norm = toarray(X_norm) - for i in xrange(3): - assert_almost_equal(row_sums[i], 1.0) - assert_almost_equal(la.norm(X_norm[3]), 0.0) - - -def test_normalizer_l2(): - rng = np.random.RandomState(0) - X_dense = rng.randn(4, 5) - X_sparse_unpruned = sp.csr_matrix(X_dense) - - # set the row number 3 to zero - X_dense[3, :] = 0.0 - - # set the row number 3 to zero without pruning (can happen in real life) - indptr_3 = X_sparse_unpruned.indptr[3] - indptr_4 = X_sparse_unpruned.indptr[4] - X_sparse_unpruned.data[indptr_3:indptr_4] = 0.0 - - # build the pruned variant using the regular constructor - X_sparse_pruned = sp.csr_matrix(X_dense) - - # check inputs that support the no-copy optim - for X in (X_dense, X_sparse_pruned, X_sparse_unpruned): - - normalizer = Normalizer(norm='l2', copy=True) - X_norm1 = normalizer.transform(X) - assert_true(X_norm1 is not X) - X_norm1 = toarray(X_norm1) - - normalizer = Normalizer(norm='l2', copy=False) - X_norm2 = normalizer.transform(X) - assert_true(X_norm2 is X) - X_norm2 = toarray(X_norm2) - - for X_norm in (X_norm1, X_norm2): - for i in xrange(3): - assert_almost_equal(la.norm(X_norm[i]), 1.0) - assert_almost_equal(la.norm(X_norm[3]), 0.0) - - # check input for which copy=False won't prevent a copy - for init in (sp.coo_matrix, sp.csc_matrix, sp.lil_matrix): - X = init(X_dense) - X_norm = normalizer = Normalizer(norm='l2', copy=False).transform(X) - - assert_true(X_norm is not X) - assert_true(isinstance(X_norm, sp.csr_matrix)) - - X_norm = toarray(X_norm) - for i in xrange(3): - assert_almost_equal(la.norm(X_norm[i]), 1.0) - assert_almost_equal(la.norm(X_norm[3]), 0.0) - - -def test_normalize_errors(): - """Check that invalid arguments yield ValueError""" - assert_raises(ValueError, normalize, [[0]], axis=2) - assert_raises(ValueError, normalize, [[0]], norm='l3') - - -def test_binarizer(): - X_ = np.array([[1, 0, 5], [2, 3, 0]]) - - for init in (np.array, sp.csr_matrix): - - X = init(X_.copy()) - - binarizer = Binarizer(threshold=2.0, copy=True) - X_bin = toarray(binarizer.transform(X)) - assert_equal(np.sum(X_bin == 0), 4) - assert_equal(np.sum(X_bin == 1), 2) - - binarizer = Binarizer(copy=True).fit(X) - X_bin = toarray(binarizer.transform(X)) - assert_true(X_bin is not X) - assert_equal(np.sum(X_bin == 0), 2) - assert_equal(np.sum(X_bin == 1), 4) - - binarizer = Binarizer(copy=True) - X_bin = binarizer.transform(X) - assert_true(X_bin is not X) - X_bin = toarray(X_bin) - assert_equal(np.sum(X_bin == 0), 2) - assert_equal(np.sum(X_bin == 1), 4) - - binarizer = Binarizer(copy=False) - X_bin = binarizer.transform(X) - assert_true(X_bin is X) - X_bin = toarray(X_bin) - assert_equal(np.sum(X_bin == 0), 2) - assert_equal(np.sum(X_bin == 1), 4) - - -def test_label_binarizer(): - lb = LabelBinarizer() - - # two-class case - inp = ["neg", "pos", "pos", "neg"] - expected = np.array([[0, 1, 1, 0]]).T - got = lb.fit_transform(inp) - assert_array_equal(expected, got) - assert_array_equal(lb.inverse_transform(got), inp) - - # multi-class case - inp = ["spam", "ham", "eggs", "ham", "0"] - expected = np.array([[0, 0, 0, 1], - [0, 0, 1, 0], - [0, 1, 0, 0], - [0, 0, 1, 0], - [1, 0, 0, 0]]) - got = lb.fit_transform(inp) - assert_array_equal(expected, got) - assert_array_equal(lb.inverse_transform(got), inp) - - -def test_label_binarizer_set_label_encoding(): - lb = LabelBinarizer(neg_label=-2, pos_label=2) - - # two-class case - inp = np.array([0, 1, 1, 0]) - expected = np.array([[-2, 2, 2, -2]]).T - got = lb.fit_transform(inp) - assert_array_equal(expected, got) - assert_array_equal(lb.inverse_transform(got), inp) - - # multi-class case - inp = np.array([3, 2, 1, 2, 0]) - expected = np.array([[-2, -2, -2, +2], - [-2, -2, +2, -2], - [-2, +2, -2, -2], - [-2, -2, +2, -2], - [+2, -2, -2, -2]]) - got = lb.fit_transform(inp) - assert_array_equal(expected, got) - assert_array_equal(lb.inverse_transform(got), inp) - - -def test_label_binarizer_multilabel(): - lb = LabelBinarizer() - - # test input as lists of tuples - inp = [(2, 3), (1,), (1, 2)] - indicator_mat = np.array([[0, 1, 1], - [1, 0, 0], - [1, 1, 0]]) - got = lb.fit_transform(inp) - assert_array_equal(indicator_mat, got) - assert_equal(lb.inverse_transform(got), inp) - - # test input as label indicator matrix - lb.fit(indicator_mat) - assert_array_equal(indicator_mat, - lb.inverse_transform(indicator_mat)) - - # regression test for the two-class multilabel case - lb = LabelBinarizer() - - inp = [[1, 0], [0], [1], [0, 1]] - expected = np.array([[1, 1], - [1, 0], - [0, 1], - [1, 1]]) - got = lb.fit_transform(inp) - assert_array_equal(expected, got) - assert_equal([set(x) for x in lb.inverse_transform(got)], - [set(x) for x in inp]) - - -def test_label_binarizer_errors(): - """Check that invalid arguments yield ValueError""" - one_class = np.array([0, 0, 0, 0]) - lb = LabelBinarizer().fit(one_class) - - multi_label = [(2, 3), (0,), (0, 2)] - assert_raises(ValueError, lb.transform, multi_label) - - lb = LabelBinarizer() - assert_raises(ValueError, lb.transform, []) - assert_raises(ValueError, lb.inverse_transform, []) - - assert_raises(ValueError, LabelBinarizer, neg_label=2, pos_label=1) - assert_raises(ValueError, LabelBinarizer, neg_label=2, pos_label=2) - - -def test_label_encoder(): - """Test LabelEncoder's transform and inverse_transform methods""" - le = LabelEncoder() - le.fit([1, 1, 4, 5, -1, 0]) - assert_array_equal(le.classes_, [-1, 0, 1, 4, 5]) - assert_array_equal(le.transform([0, 1, 4, 4, 5, -1, -1]), - [1, 2, 3, 3, 4, 0, 0]) - assert_array_equal(le.inverse_transform([1, 2, 3, 3, 4, 0, 0]), - [0, 1, 4, 4, 5, -1, -1]) - assert_raises(ValueError, le.transform, [0, 6]) - - -def test_label_encoder_fit_transform(): - """Test fit_transform""" - le = LabelEncoder() - ret = le.fit_transform([1, 1, 4, 5, -1, 0]) - assert_array_equal(ret, [2, 2, 3, 4, 0, 1]) - - le = LabelEncoder() - ret = le.fit_transform(["paris", "paris", "tokyo", "amsterdam"]) - assert_array_equal(ret, [1, 1, 2, 0]) - - -def test_label_encoder_string_labels(): - """Test LabelEncoder's transform and inverse_transform methods with - non-numeric labels""" - le = LabelEncoder() - le.fit(["paris", "paris", "tokyo", "amsterdam"]) - assert_array_equal(le.classes_, ["amsterdam", "paris", "tokyo"]) - assert_array_equal(le.transform(["tokyo", "tokyo", "paris"]), - [2, 2, 1]) - assert_array_equal(le.inverse_transform([2, 2, 1]), - ["tokyo", "tokyo", "paris"]) - assert_raises(ValueError, le.transform, ["london"]) - - -def test_label_encoder_errors(): - """Check that invalid arguments yield ValueError""" - le = LabelEncoder() - assert_raises(ValueError, le.transform, []) - assert_raises(ValueError, le.inverse_transform, []) - - -def test_label_binarizer_iris(): - lb = LabelBinarizer() - Y = lb.fit_transform(iris.target) - clfs = [SGDClassifier().fit(iris.data, Y[:, k]) - for k in range(len(lb.classes_))] - Y_pred = np.array([clf.decision_function(iris.data) for clf in clfs]).T - y_pred = lb.inverse_transform(Y_pred) - accuracy = np.mean(iris.target == y_pred) - y_pred2 = SGDClassifier().fit(iris.data, iris.target).predict(iris.data) - accuracy2 = np.mean(iris.target == y_pred2) - assert_almost_equal(accuracy, accuracy2) - - -def test_label_binarizer_multilabel_unlabeled(): - """Check that LabelBinarizer can handle an unlabeled sample""" - lb = LabelBinarizer() - y = [[1, 2], [1], []] - Y = np.array([[1, 1], - [1, 0], - [0, 0]]) - assert_equal(lb.fit_transform(y), Y) - - -def test_center_kernel(): - """Test that KernelCenterer is equivalent to StandardScaler - in feature space""" - rng = np.random.RandomState(0) - X_fit = rng.random_sample((5, 4)) - scaler = StandardScaler(with_std=False) - scaler.fit(X_fit) - X_fit_centered = scaler.transform(X_fit) - K_fit = np.dot(X_fit, X_fit.T) - - # center fit time matrix - centerer = KernelCenterer() - K_fit_centered = np.dot(X_fit_centered, X_fit_centered.T) - K_fit_centered2 = centerer.fit_transform(K_fit) - assert_array_almost_equal(K_fit_centered, K_fit_centered2) - - # center predict time matrix - X_pred = rng.random_sample((2, 4)) - K_pred = np.dot(X_pred, X_fit.T) - X_pred_centered = scaler.transform(X_pred) - K_pred_centered = np.dot(X_pred_centered, X_fit_centered.T) - K_pred_centered2 = centerer.transform(K_pred) - assert_array_almost_equal(K_pred_centered, K_pred_centered2) - - -def test_fit_transform(): - rng = np.random.RandomState(0) - X = rng.random_sample((5, 4)) - for obj in ((StandardScaler(), Normalizer(), Binarizer())): - X_transformed = obj.fit(X).transform(X) - X_transformed2 = obj.fit_transform(X) - assert_array_equal(X_transformed, X_transformed2) diff --git a/sklearn/tests/test_qda.py b/sklearn/tests/test_qda.py index 7926e600b3d4a..fc59f05527154 100644 --- a/sklearn/tests/test_qda.py +++ b/sklearn/tests/test_qda.py @@ -1,8 +1,13 @@ import numpy as np -from numpy.testing import assert_array_equal, assert_array_almost_equal -from nose.tools import assert_true -from .. import qda +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import ignore_warnings + +from sklearn import qda # Data is just 6 separable points in the plane X = np.array([[0, 0], [-2, -2], [-2, -1], [-1, -1], [-1, -2], @@ -14,6 +19,17 @@ X1 = np.array([[-3, ], [-2, ], [-1, ], [-1, ], [0, ], [1, ], [1, ], [2, ], [3, ]]) +# Data that has zero variance in one dimension and needs regularization +X2 = np.array([[-3, 0], [-2, 0], [-1, 0], [-1, 0], [0, 0], [1, 0], [1, 0], + [2, 0], [3, 0]]) + +# One element class +y4 = np.array([1, 1, 1, 1, 1, 1, 1, 1, 2]) + +# Data with less samples in a class than n_features +X5 = np.c_[np.arange(8), np.zeros((8,3))] +y5 = np.array([0, 0, 0, 0, 0, 1, 1, 1]) + def test_qda(): """ @@ -39,3 +55,62 @@ def test_qda(): y_pred3 = clf.fit(X, y3).predict(X) # QDA shouldn't be able to separate those assert_true(np.any(y_pred3 != y3)) + + # Classes should have at least 2 elements + assert_raises(ValueError, clf.fit, X, y4) + + +def test_qda_priors(): + clf = qda.QDA() + y_pred = clf.fit(X, y).predict(X) + n_pos = np.sum(y_pred == 2) + + neg = 1e-10 + clf = qda.QDA(priors=np.array([neg, 1 - neg])) + y_pred = clf.fit(X, y).predict(X) + n_pos2 = np.sum(y_pred == 2) + + assert_greater(n_pos2, n_pos) + + +def test_qda_store_covariances(): + # The default is to not set the covariances_ attribute + clf = qda.QDA().fit(X, y) + assert_true(not hasattr(clf, 'covariances_')) + + # Test the actual attribute: + clf = qda.QDA().fit(X, y, store_covariances=True) + assert_true(hasattr(clf, 'covariances_')) + + assert_array_almost_equal( + clf.covariances_[0], + np.array([[0.7, 0.45], [0.45, 0.7]]) + ) + + assert_array_almost_equal( + clf.covariances_[1], + np.array([[0.33333333, -0.33333333], [-0.33333333, 0.66666667]]) + ) + + +def test_qda_regularization(): + # the default is reg_param=0. and will cause issues + # when there is a constant variable + clf = qda.QDA() + with ignore_warnings(): + y_pred = clf.fit(X2, y).predict(X2) + assert_true(np.any(y_pred != y)) + + # adding a little regularization fixes the problem + clf = qda.QDA(reg_param=0.01) + with ignore_warnings(): + clf.fit(X2, y) + y_pred = clf.predict(X2) + assert_array_equal(y_pred, y) + + # Case n_samples_in_a_class < n_features + clf = qda.QDA(reg_param=0.1) + with ignore_warnings(): + clf.fit(X5, y5) + y_pred5 = clf.predict(X5) + assert_array_equal(y_pred5, y5) diff --git a/sklearn/tests/test_random_projection.py b/sklearn/tests/test_random_projection.py new file mode 100644 index 0000000000000..7b2fb8157ac3a --- /dev/null +++ b/sklearn/tests/test_random_projection.py @@ -0,0 +1,354 @@ +from __future__ import division + +import numpy as np +import scipy.sparse as sp + +from sklearn.metrics import euclidean_distances + +from sklearn.random_projection import johnson_lindenstrauss_min_dim +from sklearn.random_projection import gaussian_random_matrix +from sklearn.random_projection import sparse_random_matrix +from sklearn.random_projection import SparseRandomProjection +from sklearn.random_projection import GaussianRandomProjection + +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_raise_message +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_in +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_warns +from sklearn.utils import DataDimensionalityWarning + +all_sparse_random_matrix = [sparse_random_matrix] +all_dense_random_matrix = [gaussian_random_matrix] +all_random_matrix = set(all_sparse_random_matrix + all_dense_random_matrix) + +all_SparseRandomProjection = [SparseRandomProjection] +all_DenseRandomProjection = [GaussianRandomProjection] +all_RandomProjection = set(all_SparseRandomProjection + + all_DenseRandomProjection) + + +# Make some random data with uniformly located non zero entries with +# Gaussian distributed values +def make_sparse_random_data(n_samples, n_features, n_nonzeros): + rng = np.random.RandomState(0) + data_coo = sp.coo_matrix( + (rng.randn(n_nonzeros), + (rng.randint(n_samples, size=n_nonzeros), + rng.randint(n_features, size=n_nonzeros))), + shape=(n_samples, n_features)) + return data_coo.toarray(), data_coo.tocsr() + + +def densify(matrix): + if not sp.issparse(matrix): + return matrix + else: + return matrix.toarray() + + +n_samples, n_features = (10, 1000) +n_nonzeros = int(n_samples * n_features / 100.) +data, data_csr = make_sparse_random_data(n_samples, n_features, n_nonzeros) + + +############################################################################### +# test on JL lemma +############################################################################### +def test_invalid_jl_domain(): + assert_raises(ValueError, johnson_lindenstrauss_min_dim, 100, 1.1) + assert_raises(ValueError, johnson_lindenstrauss_min_dim, 100, 0.0) + assert_raises(ValueError, johnson_lindenstrauss_min_dim, 100, -0.1) + assert_raises(ValueError, johnson_lindenstrauss_min_dim, 0, 0.5) + + +def test_input_size_jl_min_dim(): + assert_raises(ValueError, johnson_lindenstrauss_min_dim, + 3 * [100], 2 * [0.9]) + + assert_raises(ValueError, johnson_lindenstrauss_min_dim, 3 * [100], + 2 * [0.9]) + + johnson_lindenstrauss_min_dim(np.random.randint(1, 10, size=(10, 10)), + 0.5 * np.ones((10, 10))) + + +############################################################################### +# tests random matrix generation +############################################################################### +def check_input_size_random_matrix(random_matrix): + assert_raises(ValueError, random_matrix, 0, 0) + assert_raises(ValueError, random_matrix, -1, 1) + assert_raises(ValueError, random_matrix, 1, -1) + assert_raises(ValueError, random_matrix, 1, 0) + assert_raises(ValueError, random_matrix, -1, 0) + + +def check_size_generated(random_matrix): + assert_equal(random_matrix(1, 5).shape, (1, 5)) + assert_equal(random_matrix(5, 1).shape, (5, 1)) + assert_equal(random_matrix(5, 5).shape, (5, 5)) + assert_equal(random_matrix(1, 1).shape, (1, 1)) + + +def check_zero_mean_and_unit_norm(random_matrix): + # All random matrix should produce a transformation matrix + # with zero mean and unit norm for each columns + + A = densify(random_matrix(10000, 1, random_state=0)) + + assert_array_almost_equal(0, np.mean(A), 3) + assert_array_almost_equal(1.0, np.linalg.norm(A), 1) + + +def check_input_with_sparse_random_matrix(random_matrix): + n_components, n_features = 5, 10 + + for density in [-1., 0.0, 1.1]: + assert_raises(ValueError, + random_matrix, n_components, n_features, density=density) + + +def test_basic_property_of_random_matrix(): + """Check basic properties of random matrix generation""" + for random_matrix in all_random_matrix: + check_input_size_random_matrix(random_matrix) + check_size_generated(random_matrix) + check_zero_mean_and_unit_norm(random_matrix) + + for random_matrix in all_sparse_random_matrix: + check_input_with_sparse_random_matrix(random_matrix) + + random_matrix_dense = \ + lambda n_components, n_features, random_state: random_matrix( + n_components, n_features, random_state=random_state, + density=1.0) + check_zero_mean_and_unit_norm(random_matrix_dense) + + +def test_gaussian_random_matrix(): + """Check some statical properties of Gaussian random matrix""" + # Check that the random matrix follow the proper distribution. + # Let's say that each element of a_{ij} of A is taken from + # a_ij ~ N(0.0, 1 / n_components). + # + n_components = 100 + n_features = 1000 + A = gaussian_random_matrix(n_components, n_features, random_state=0) + + assert_array_almost_equal(0.0, np.mean(A), 2) + assert_array_almost_equal(np.var(A, ddof=1), 1 / n_components, 1) + + +def test_sparse_random_matrix(): + """Check some statical properties of sparse random matrix""" + n_components = 100 + n_features = 500 + + for density in [0.3, 1.]: + s = 1 / density + + A = sparse_random_matrix(n_components, + n_features, + density=density, + random_state=0) + A = densify(A) + + # Check possible values + values = np.unique(A) + assert_in(np.sqrt(s) / np.sqrt(n_components), values) + assert_in(- np.sqrt(s) / np.sqrt(n_components), values) + + if density == 1.0: + assert_equal(np.size(values), 2) + else: + assert_in(0., values) + assert_equal(np.size(values), 3) + + # Check that the random matrix follow the proper distribution. + # Let's say that each element of a_{ij} of A is taken from + # + # - -sqrt(s) / sqrt(n_components) with probability 1 / 2s + # - 0 with probability 1 - 1 / s + # - +sqrt(s) / sqrt(n_components) with probability 1 / 2s + # + assert_almost_equal(np.mean(A == 0.0), + 1 - 1 / s, decimal=2) + assert_almost_equal(np.mean(A == np.sqrt(s) / np.sqrt(n_components)), + 1 / (2 * s), decimal=2) + assert_almost_equal(np.mean(A == - np.sqrt(s) / np.sqrt(n_components)), + 1 / (2 * s), decimal=2) + + assert_almost_equal(np.var(A == 0.0, ddof=1), + (1 - 1 / s) * 1 / s, decimal=2) + assert_almost_equal(np.var(A == np.sqrt(s) / np.sqrt(n_components), + ddof=1), + (1 - 1 / (2 * s)) * 1 / (2 * s), decimal=2) + assert_almost_equal(np.var(A == - np.sqrt(s) / np.sqrt(n_components), + ddof=1), + (1 - 1 / (2 * s)) * 1 / (2 * s), decimal=2) + + +############################################################################### +# tests on random projection transformer +############################################################################### +def test_sparse_random_projection_transformer_invalid_density(): + for RandomProjection in all_SparseRandomProjection: + assert_raises(ValueError, + RandomProjection(density=1.1).fit, data) + + assert_raises(ValueError, + RandomProjection(density=0).fit, data) + + assert_raises(ValueError, + RandomProjection(density=-0.1).fit, data) + + +def test_random_projection_transformer_invalid_input(): + for RandomProjection in all_RandomProjection: + assert_raises(ValueError, + RandomProjection(n_components='auto').fit, [0, 1, 2]) + + assert_raises(ValueError, + RandomProjection(n_components=-10).fit, data) + + +def test_try_to_transform_before_fit(): + for RandomProjection in all_RandomProjection: + assert_raises(ValueError, + RandomProjection(n_components='auto').transform, data) + + +def test_too_many_samples_to_find_a_safe_embedding(): + data, _ = make_sparse_random_data(1000, 100, 1000) + + for RandomProjection in all_RandomProjection: + rp = RandomProjection(n_components='auto', eps=0.1) + expected_msg = ( + 'eps=0.100000 and n_samples=1000 lead to a target dimension' + ' of 5920 which is larger than the original space with' + ' n_features=100') + assert_raise_message(ValueError, expected_msg, rp.fit, data) + + +def test_random_projection_embedding_quality(): + data, _ = make_sparse_random_data(8, 5000, 15000) + eps = 0.2 + + original_distances = euclidean_distances(data, squared=True) + original_distances = original_distances.ravel() + non_identical = original_distances != 0.0 + + # remove 0 distances to avoid division by 0 + original_distances = original_distances[non_identical] + + for RandomProjection in all_RandomProjection: + rp = RandomProjection(n_components='auto', eps=eps, random_state=0) + projected = rp.fit_transform(data) + + projected_distances = euclidean_distances(projected, squared=True) + projected_distances = projected_distances.ravel() + + # remove 0 distances to avoid division by 0 + projected_distances = projected_distances[non_identical] + + distances_ratio = projected_distances / original_distances + + # check that the automatically tuned values for the density respect the + # contract for eps: pairwise distances are preserved according to the + # Johnson-Lindenstrauss lemma + assert_less(distances_ratio.max(), 1 + eps) + assert_less(1 - eps, distances_ratio.min()) + + +def test_SparseRandomProjection_output_representation(): + for SparseRandomProjection in all_SparseRandomProjection: + # when using sparse input, the projected data can be forced to be a + # dense numpy array + rp = SparseRandomProjection(n_components=10, dense_output=True, + random_state=0) + rp.fit(data) + assert isinstance(rp.transform(data), np.ndarray) + + sparse_data = sp.csr_matrix(data) + assert isinstance(rp.transform(sparse_data), np.ndarray) + + # the output can be left to a sparse matrix instead + rp = SparseRandomProjection(n_components=10, dense_output=False, + random_state=0) + rp = rp.fit(data) + # output for dense input will stay dense: + assert isinstance(rp.transform(data), np.ndarray) + + # output for sparse output will be sparse: + assert sp.issparse(rp.transform(sparse_data)) + + +def test_correct_RandomProjection_dimensions_embedding(): + for RandomProjection in all_RandomProjection: + rp = RandomProjection(n_components='auto', + random_state=0, + eps=0.5).fit(data) + + # the number of components is adjusted from the shape of the training + # set + assert_equal(rp.n_components, 'auto') + assert_equal(rp.n_components_, 110) + + if RandomProjection in all_SparseRandomProjection: + assert_equal(rp.density, 'auto') + assert_almost_equal(rp.density_, 0.03, 2) + + assert_equal(rp.components_.shape, (110, n_features)) + + projected_1 = rp.transform(data) + assert_equal(projected_1.shape, (n_samples, 110)) + + # once the RP is 'fitted' the projection is always the same + projected_2 = rp.transform(data) + assert_array_equal(projected_1, projected_2) + + # fit transform with same random seed will lead to the same results + rp2 = RandomProjection(random_state=0, eps=0.5) + projected_3 = rp2.fit_transform(data) + assert_array_equal(projected_1, projected_3) + + # Try to transform with an input X of size different from fitted. + assert_raises(ValueError, rp.transform, data[:, 1:5]) + + # it is also possible to fix the number of components and the density + # level + if RandomProjection in all_SparseRandomProjection: + rp = RandomProjection(n_components=100, density=0.001, + random_state=0) + projected = rp.fit_transform(data) + assert_equal(projected.shape, (n_samples, 100)) + assert_equal(rp.components_.shape, (100, n_features)) + assert_less(rp.components_.nnz, 115) # close to 1% density + assert_less(85, rp.components_.nnz) # close to 1% density + + +def test_warning_n_components_greater_than_n_features(): + n_features = 20 + data, _ = make_sparse_random_data(5, n_features, int(n_features / 4)) + + for RandomProjection in all_RandomProjection: + assert_warns(DataDimensionalityWarning, + RandomProjection(n_components=n_features + 1).fit, data) + + +def test_works_with_sparse_data(): + n_features = 20 + data, _ = make_sparse_random_data(5, n_features, int(n_features / 4)) + + for RandomProjection in all_RandomProjection: + rp_dense = RandomProjection(n_components=3, + random_state=1).fit(data) + rp_sparse = RandomProjection(n_components=3, + random_state=1).fit(sp.csr_matrix(data)) + assert_array_almost_equal(densify(rp_dense.components_), + densify(rp_sparse.components_)) diff --git a/sklearn/tree/__init__.py b/sklearn/tree/__init__.py index 4becdfd010cd7..1394bd914d27c 100644 --- a/sklearn/tree/__init__.py +++ b/sklearn/tree/__init__.py @@ -7,4 +7,7 @@ from .tree import DecisionTreeRegressor from .tree import ExtraTreeClassifier from .tree import ExtraTreeRegressor -from .tree import export_graphviz +from .export import export_graphviz + +__all__ = ["DecisionTreeClassifier", "DecisionTreeRegressor", + "ExtraTreeClassifier", "ExtraTreeRegressor", "export_graphviz"] diff --git a/sklearn/tree/_tree.c b/sklearn/tree/_tree.c index fee2ada8f0018..19bf1504737e0 100644 --- a/sklearn/tree/_tree.c +++ b/sklearn/tree/_tree.c @@ -1,13 +1,26 @@ -/* Generated by Cython 0.17 on Thu Sep 13 13:18:30 2012 */ +/* Generated by Cython 0.22 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02040000 - #error Cython requires Python 2.4+. +#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) + #error Cython requires Python 2.6+ or Python 3.2+. #else -#include /* For offsetof */ +#define CYTHON_ABI "0_22" +#include #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif @@ -41,91 +54,64 @@ #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif -#if PY_VERSION_HEX < 0x02050000 - typedef int Py_ssize_t; - #define PY_SSIZE_T_MAX INT_MAX - #define PY_SSIZE_T_MIN INT_MIN - #define PY_FORMAT_SIZE_T "" - #define CYTHON_FORMAT_SSIZE_T "" - #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ - (PyErr_Format(PyExc_TypeError, \ - "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ - (PyObject*)0)) - #define PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && !PyComplex_Check(o)) - #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) - #define __PYX_BUILD_PY_SSIZE_T "i" -#else - #define __PYX_BUILD_PY_SSIZE_T "n" - #define CYTHON_FORMAT_SSIZE_T "z" -#endif -#if PY_VERSION_HEX < 0x02060000 - #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) - #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) - #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) - #define PyVarObject_HEAD_INIT(type, size) \ - PyObject_HEAD_INIT(type) size, - #define PyType_Modified(t) - typedef struct { - void *buf; - PyObject *obj; - Py_ssize_t len; - Py_ssize_t itemsize; - int readonly; - int ndim; - char *format; - Py_ssize_t *shape; - Py_ssize_t *strides; - Py_ssize_t *suboffsets; - void *internal; - } Py_buffer; - #define PyBUF_SIMPLE 0 - #define PyBUF_WRITABLE 0x0001 - #define PyBUF_FORMAT 0x0004 - #define PyBUF_ND 0x0008 - #define PyBUF_STRIDES (0x0010 | PyBUF_ND) - #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) - #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) - #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) - #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) - #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) - typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); - typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) +#define Py_OptimizeFlag 0 #endif +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ - PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#endif -#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 - #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") + #define __Pyx_DefaultClassType PyType_Type #endif #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 -#endif -#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #else #define CYTHON_PEP393_ENABLED 0 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) + #define __Pyx_PyFrozenSet_Size(s) PyObject_Size(s) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) + #define __Pyx_PyFrozenSet_Size(s) PySet_Size(s) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type @@ -134,27 +120,12 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif -#if PY_VERSION_HEX < 0x02060000 - #define PyBytesObject PyStringObject - #define PyBytes_Type PyString_Type - #define PyBytes_Check PyString_Check - #define PyBytes_CheckExact PyString_CheckExact - #define PyBytes_FromString PyString_FromString - #define PyBytes_FromStringAndSize PyString_FromStringAndSize - #define PyBytes_FromFormat PyString_FromFormat - #define PyBytes_DecodeEscape PyString_DecodeEscape - #define PyBytes_AsString PyString_AsString - #define PyBytes_AsStringAndSize PyString_AsStringAndSize - #define PyBytes_Size PyString_Size - #define PyBytes_AS_STRING PyString_AS_STRING - #define PyBytes_GET_SIZE PyString_GET_SIZE - #define PyBytes_Repr PyString_Repr - #define PyBytes_Concat PyString_Concat - #define PyBytes_ConcatAndDel PyString_ConcatAndDel -#endif -#if PY_VERSION_HEX < 0x02060000 - #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) - #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) @@ -175,11 +146,17 @@ #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif -#if PY_VERSION_HEX < 0x03020000 +#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY + #ifndef PyUnicode_InternFromString + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) + #endif +#endif +#if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong @@ -187,42 +164,61 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif -#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) - #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) - #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else - #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) - #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif -#if PY_MAJOR_VERSION >= 3 - #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif #endif -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) -#else - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif #endif -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_NAMESTR(n) ((char *)(n)) - #define __Pyx_DOCSTR(n) ((char *)(n)) +#ifdef NAN +#define __PYX_NAN() ((float) NAN) #else - #define __Pyx_NAMESTR(n) (n) - #define __Pyx_DOCSTR(n) (n) +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#define __Pyx_void_to_None(void_result) (void_result, Py_INCREF(Py_None), Py_None) +#ifdef __cplusplus +template +void __Pyx_call_destructor(T* x) { + x->~T(); +} +template +class __Pyx_FakeReference { + public: + __Pyx_FakeReference() : ptr(NULL) { } + __Pyx_FakeReference(T& ref) : ptr(&ref) { } + T *operator->() { return ptr; } + operator T&() { return *ptr; } + private: + T *ptr; +}; #endif @@ -248,13 +244,13 @@ #include #define __PYX_HAVE__sklearn__tree___tree #define __PYX_HAVE_API__sklearn__tree___tree +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" -#include "string.h" #include "math.h" -#include "float.h" +#include "pythread.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -263,21 +259,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -291,46 +272,157 @@ # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - #if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + -#ifdef __GNUC__ - /* Test for GCC > 2.95 */ - #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) - #else /* __GNUC__ > 2 ... */ - #define likely(x) (x) - #define unlikely(x) (x) - #endif /* __GNUC__ > 2 ... */ -#else /* __GNUC__ */ +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -362,21 +454,24 @@ static const char *__pyx_filename; static const char *__pyx_f[] = { - "_tree.pyx", - "_tree.pxd", - "numpy.pxd", + "sklearn/tree/_tree.pyx", + "sklearn/tree/_tree.pxd", + "__init__.pxd", "type.pxd", + "bool.pxd", + "complex.pxd", + "sklearn/tree/_utils.pxd", }; #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { - const char* name; /* for error messages only */ + const char* name; struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - size_t arraysize[8]; /* length of array in each dimension */ + size_t size; + size_t arraysize[8]; int ndim; - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char typegroup; char is_unsigned; int flags; } __Pyx_TypeInfo; @@ -403,7 +498,7 @@ typedef struct { } __Pyx_BufFmt_Context; -/* "numpy.pxd":723 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":726 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -412,7 +507,7 @@ typedef struct { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":724 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":727 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -421,7 +516,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":725 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":728 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -430,7 +525,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":726 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":729 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -439,7 +534,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":730 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":733 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -448,7 +543,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":731 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":734 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -457,7 +552,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":732 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":735 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -466,7 +561,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":733 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":736 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -475,7 +570,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":737 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":740 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -484,7 +579,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":738 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":741 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -493,7 +588,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":747 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":750 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -502,7 +597,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":748 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":751 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -511,7 +606,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":749 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":752 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -520,7 +615,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":751 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":754 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -529,7 +624,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":752 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":755 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -538,7 +633,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":753 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":756 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -547,7 +642,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":755 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -556,7 +651,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":756 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -565,7 +660,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":758 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":761 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -574,7 +669,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":759 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":762 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -583,7 +678,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":760 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":763 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -592,32 +687,59 @@ typedef npy_double __pyx_t_5numpy_double_t; */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; -/* "sklearn/tree/_tree.pxd":8 +/* "sklearn/tree/_utils.pxd":12 + * cimport numpy as np + * + * ctypedef np.npy_intp SIZE_t # Type for indices and counters # <<<<<<<<<<<<<< + * + * + */ +typedef npy_intp __pyx_t_7sklearn_4tree_6_utils_SIZE_t; + +/* "sklearn/tree/_tree.pxd":14 * cimport numpy as np * - * ctypedef np.float32_t DTYPE_t # <<<<<<<<<<<<<< - * ctypedef np.float64_t DOUBLE_t - * ctypedef np.int8_t BOOL_t + * ctypedef np.npy_float32 DTYPE_t # Type of X # <<<<<<<<<<<<<< + * ctypedef np.npy_float64 DOUBLE_t # Type of y, sample_weight + * ctypedef np.npy_intp SIZE_t # Type for indices and counters */ -typedef __pyx_t_5numpy_float32_t __pyx_t_7sklearn_4tree_5_tree_DTYPE_t; +typedef npy_float32 __pyx_t_7sklearn_4tree_5_tree_DTYPE_t; -/* "sklearn/tree/_tree.pxd":9 +/* "sklearn/tree/_tree.pxd":15 * - * ctypedef np.float32_t DTYPE_t - * ctypedef np.float64_t DOUBLE_t # <<<<<<<<<<<<<< - * ctypedef np.int8_t BOOL_t + * ctypedef np.npy_float32 DTYPE_t # Type of X + * ctypedef np.npy_float64 DOUBLE_t # Type of y, sample_weight # <<<<<<<<<<<<<< + * ctypedef np.npy_intp SIZE_t # Type for indices and counters + * ctypedef np.npy_int32 INT32_t # Signed 32 bit integer + */ +typedef npy_float64 __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t; + +/* "sklearn/tree/_tree.pxd":16 + * ctypedef np.npy_float32 DTYPE_t # Type of X + * ctypedef np.npy_float64 DOUBLE_t # Type of y, sample_weight + * ctypedef np.npy_intp SIZE_t # Type for indices and counters # <<<<<<<<<<<<<< + * ctypedef np.npy_int32 INT32_t # Signed 32 bit integer + * ctypedef np.npy_uint32 UINT32_t # Unsigned 32 bit integer + */ +typedef npy_intp __pyx_t_7sklearn_4tree_5_tree_SIZE_t; + +/* "sklearn/tree/_tree.pxd":17 + * ctypedef np.npy_float64 DOUBLE_t # Type of y, sample_weight + * ctypedef np.npy_intp SIZE_t # Type for indices and counters + * ctypedef np.npy_int32 INT32_t # Signed 32 bit integer # <<<<<<<<<<<<<< + * ctypedef np.npy_uint32 UINT32_t # Unsigned 32 bit integer * */ -typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t; +typedef npy_int32 __pyx_t_7sklearn_4tree_5_tree_INT32_t; -/* "sklearn/tree/_tree.pxd":10 - * ctypedef np.float32_t DTYPE_t - * ctypedef np.float64_t DOUBLE_t - * ctypedef np.int8_t BOOL_t # <<<<<<<<<<<<<< +/* "sklearn/tree/_tree.pxd":18 + * ctypedef np.npy_intp SIZE_t # Type for indices and counters + * ctypedef np.npy_int32 INT32_t # Signed 32 bit integer + * ctypedef np.npy_uint32 UINT32_t # Unsigned 32 bit integer # <<<<<<<<<<<<<< * * */ -typedef __pyx_t_5numpy_int8_t __pyx_t_7sklearn_4tree_5_tree_BOOL_t; +typedef npy_uint32 __pyx_t_7sklearn_4tree_5_tree_UINT32_t; #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -640,15 +762,29 @@ typedef __pyx_t_5numpy_int8_t __pyx_t_7sklearn_4tree_5_tree_BOOL_t; /*--- Type declarations ---*/ -struct __pyx_obj_7sklearn_4tree_5_tree_Tree; +struct __pyx_obj_7sklearn_4tree_6_utils_Stack; +struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap; struct __pyx_obj_7sklearn_4tree_5_tree_Criterion; +struct __pyx_obj_7sklearn_4tree_5_tree_Splitter; +struct __pyx_obj_7sklearn_4tree_5_tree_Tree; +struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder; struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion; -struct __pyx_obj_7sklearn_4tree_5_tree_Gini; struct __pyx_obj_7sklearn_4tree_5_tree_Entropy; +struct __pyx_obj_7sklearn_4tree_5_tree_Gini; struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion; struct __pyx_obj_7sklearn_4tree_5_tree_MSE; - -/* "numpy.pxd":762 +struct __pyx_obj_7sklearn_4tree_5_tree_FriedmanMSE; +struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter; +struct __pyx_obj_7sklearn_4tree_5_tree_BestSplitter; +struct __pyx_obj_7sklearn_4tree_5_tree_RandomSplitter; +struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter; +struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter; +struct __pyx_obj_7sklearn_4tree_5_tree_BestSparseSplitter; +struct __pyx_obj_7sklearn_4tree_5_tree_RandomSparseSplitter; +struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder; +struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":765 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -657,7 +793,7 @@ struct __pyx_obj_7sklearn_4tree_5_tree_MSE; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":763 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":766 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -666,7 +802,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":764 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":767 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -675,7 +811,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":766 +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":769 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -683,142 +819,329 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; -struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_resize; -struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_build; +struct __pyx_t_7sklearn_4tree_6_utils_StackRecord; +struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord; + +/* "sklearn/tree/_utils.pxd":20 + * + * # A record on the stack for depth-first tree growing + * cdef struct StackRecord: # <<<<<<<<<<<<<< + * SIZE_t start + * SIZE_t end + */ +struct __pyx_t_7sklearn_4tree_6_utils_StackRecord { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t start; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t end; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t depth; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t parent; + int is_left; + double impurity; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t n_constant_features; +}; + +/* "sklearn/tree/_utils.pxd":46 + * + * # A record on the frontier for best-first tree growing + * cdef struct PriorityHeapRecord: # <<<<<<<<<<<<<< + * SIZE_t node_id + * SIZE_t start + */ +struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t node_id; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t start; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t end; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t pos; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t depth; + int is_leaf; + double impurity; + double impurity_left; + double impurity_right; + double improvement; +}; +struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord; +struct __pyx_t_7sklearn_4tree_5_tree_Node; +struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c; struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances; +struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build; +struct __pyx_opt_args_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_build; +struct __pyx_opt_args_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_build; + +/* "sklearn/tree/_tree.pxd":67 + * # ============================================================================= + * + * cdef struct SplitRecord: # <<<<<<<<<<<<<< + * # Data to track sample split + * SIZE_t feature # Which feature to split on. + */ +struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t feature; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t pos; + double threshold; + double improvement; + double impurity_left; + double impurity_right; +}; -/* "sklearn/tree/_tree.pxd":68 +/* "sklearn/tree/_tree.pxd":146 + * # ============================================================================= * - * # Methods - * cdef void resize(self, int capacity=*) # <<<<<<<<<<<<<< + * cdef struct Node: # <<<<<<<<<<<<<< + * # Base storage structure for the nodes in a Tree object * - * cpdef build(self, np.ndarray X, np.ndarray y, */ -struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_resize { +struct __pyx_t_7sklearn_4tree_5_tree_Node { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t left_child; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t right_child; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t feature; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t threshold; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t impurity; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_node_samples; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t weighted_n_node_samples; +}; + +/* "sklearn/tree/_tree.pxd":184 + * double weighted_n_samples) nogil + * cdef void _resize(self, SIZE_t capacity) except * + * cdef int _resize_c(self, SIZE_t capacity=*) nogil # <<<<<<<<<<<<<< + * + * cdef np.ndarray _get_value_ndarray(self) + */ +struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c { int __pyx_n; - int capacity; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t capacity; }; -/* "sklearn/tree/_tree.pxd":70 - * cdef void resize(self, int capacity=*) +/* "sklearn/tree/_tree.pxd":194 + * cdef np.ndarray _apply_sparse_csr(self, object X) + * + * cpdef compute_feature_importances(self, normalize=*) # <<<<<<<<<<<<<< * - * cpdef build(self, np.ndarray X, np.ndarray y, # <<<<<<<<<<<<<< - * np.ndarray sample_mask=*, np.ndarray X_argsorted=*) * */ -struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_build { +struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances { int __pyx_n; - PyArrayObject *sample_mask; - PyArrayObject *X_argsorted; + PyObject *normalize; }; -/* "sklearn/tree/_tree.pxd":119 - * cpdef apply(self, np.ndarray[DTYPE_t, ndim=2] X) +/* "sklearn/tree/_tree.pxd":216 + * cdef SIZE_t max_depth # Maximal tree depth * - * cpdef compute_feature_importances(self, method=*) # <<<<<<<<<<<<<< + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=*) + * cdef _check_input(self, object X, np.ndarray y, np.ndarray sample_weight) + */ +struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build { + int __pyx_n; + PyArrayObject *sample_weight; +}; + +/* "sklearn/tree/_tree.pyx":69 + * cdef int IS_NOT_LEFT = 0 * - * cdef inline double _compute_feature_importances_gini(self, int node) + * cdef enum: # <<<<<<<<<<<<<< + * # Max value for our rand_r replacement (near the bottom). + * # We don't use RAND_MAX because it's different across platforms and */ -struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances { +enum { + __pyx_e_7sklearn_4tree_5_tree_RAND_R_MAX = 0x7FFFFFFF +}; + +/* "sklearn/tree/_tree.pyx":2617 + * self.max_depth = max_depth + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ +struct __pyx_opt_args_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_build { + int __pyx_n; + PyArrayObject *sample_weight; +}; + +/* "sklearn/tree/_tree.pyx":2771 + * self.max_leaf_nodes = max_leaf_nodes + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ +struct __pyx_opt_args_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_build { int __pyx_n; - PyObject *method; + PyArrayObject *sample_weight; +}; + +/* "sklearn/tree/_utils.pxd":29 + * SIZE_t n_constant_features + * + * cdef class Stack: # <<<<<<<<<<<<<< + * cdef SIZE_t capacity + * cdef SIZE_t top + */ +struct __pyx_obj_7sklearn_4tree_6_utils_Stack { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack *__pyx_vtab; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t capacity; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t top; + struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *stack_; +}; + + +/* "sklearn/tree/_utils.pxd":58 + * double improvement + * + * cdef class PriorityHeap: # <<<<<<<<<<<<<< + * cdef SIZE_t capacity + * cdef SIZE_t heap_ptr + */ +struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_4tree_6_utils_PriorityHeap *__pyx_vtab; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t capacity; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t heap_ptr; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *heap_; +}; + + +/* "sklearn/tree/_tree.pxd":25 + * # ============================================================================= + * + * cdef class Criterion: # <<<<<<<<<<<<<< + * # The criterion computes the impurity of a node and the reduction of + * # impurity of a split on that node. It also computes the output statistics + */ +struct __pyx_obj_7sklearn_4tree_5_tree_Criterion { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *__pyx_vtab; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *y; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t y_stride; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *sample_weight; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t pos; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t end; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_node_samples; + double weighted_n_samples; + double weighted_n_node_samples; + double weighted_n_left; + double weighted_n_right; +}; + + +/* "sklearn/tree/_tree.pxd":79 + * + * + * cdef class Splitter: # <<<<<<<<<<<<<< + * # The splitter searches in the input space for a feature and a threshold + * # to split the samples samples[start:end]. + */ +struct __pyx_obj_7sklearn_4tree_5_tree_Splitter { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *__pyx_vtab; + struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *criterion; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t max_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t min_samples_leaf; + double min_weight_leaf; + PyObject *random_state; + __pyx_t_7sklearn_4tree_5_tree_UINT32_t rand_r_state; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_samples; + double weighted_n_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *constant_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_features; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *feature_values; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t end; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *y; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t y_stride; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *sample_weight; }; -/* "sklearn/tree/_tree.pxd":36 - * # ============================================================================== + +/* "sklearn/tree/_tree.pxd":158 + * * * cdef class Tree: # <<<<<<<<<<<<<< - * # Input/Output layout - * cdef public int n_features + * # The Tree object is a binary tree structure constructed by the + * # TreeBuilder. The tree structure is used for predictions and */ struct __pyx_obj_7sklearn_4tree_5_tree_Tree { PyObject_HEAD struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *__pyx_vtab; - int n_features; - int *n_classes; - int n_outputs; - int max_n_classes; - int value_stride; - struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *criterion; - double max_depth; - int min_samples_split; - int min_samples_leaf; - double min_density; - int max_features; - int find_split_algorithm; - PyObject *random_state; - int node_count; - int capacity; - int *children_left; - int *children_right; - int *feature; - double *threshold; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t max_n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t max_depth; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t node_count; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t capacity; + struct __pyx_t_7sklearn_4tree_5_tree_Node *nodes; double *value; - double *best_error; - double *init_error; - int *n_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t value_stride; }; -/* "sklearn/tree/_tree.pxd":17 - * # ============================================================================== +/* "sklearn/tree/_tree.pxd":201 + * # ============================================================================= * - * cdef class Criterion: # <<<<<<<<<<<<<< - * # Methods - * cdef void init(self, DOUBLE_t* y, int y_stride, BOOL_t* sample_mask, + * cdef class TreeBuilder: # <<<<<<<<<<<<<< + * # The TreeBuilder recursively builds a Tree object from training samples, + * # using a Splitter object for splitting internal nodes and assigning */ -struct __pyx_obj_7sklearn_4tree_5_tree_Criterion { +struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder { PyObject_HEAD - struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *__pyx_vtab; + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder *__pyx_vtab; + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *splitter; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t min_samples_split; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t min_samples_leaf; + double min_weight_leaf; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t max_depth; }; -/* "sklearn/tree/_tree.pyx":961 +/* "sklearn/tree/_tree.pyx":150 * * * cdef class ClassificationCriterion(Criterion): # <<<<<<<<<<<<<< - * """Abstract criterion for classification. - * + * """Abstract criterion for classification.""" + * cdef SIZE_t* n_classes */ struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion { struct __pyx_obj_7sklearn_4tree_5_tree_Criterion __pyx_base; - int n_outputs; - int *n_classes; - int n_samples; - int label_count_stride; - int *label_count_left; - int *label_count_right; - int *label_count_init; - int n_left; - int n_right; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t label_count_stride; + double *label_count_left; + double *label_count_right; + double *label_count_total; }; -/* "sklearn/tree/_tree.pyx":1173 +/* "sklearn/tree/_tree.pyx":368 * * - * cdef class Gini(ClassificationCriterion): # <<<<<<<<<<<<<< - * """Gini Index splitting criteria. + * cdef class Entropy(ClassificationCriterion): # <<<<<<<<<<<<<< + * """Cross Entropy impurity criteria. * */ -struct __pyx_obj_7sklearn_4tree_5_tree_Gini { +struct __pyx_obj_7sklearn_4tree_5_tree_Entropy { struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion __pyx_base; }; -/* "sklearn/tree/_tree.pyx":1233 +/* "sklearn/tree/_tree.pyx":459 * * - * cdef class Entropy(ClassificationCriterion): # <<<<<<<<<<<<<< - * """Cross Entropy splitting criteria. + * cdef class Gini(ClassificationCriterion): # <<<<<<<<<<<<<< + * """Gini Index impurity criteria. * */ -struct __pyx_obj_7sklearn_4tree_5_tree_Entropy { +struct __pyx_obj_7sklearn_4tree_5_tree_Gini { struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion __pyx_base; }; -/* "sklearn/tree/_tree.pyx":1284 +/* "sklearn/tree/_tree.pyx":553 * * * cdef class RegressionCriterion(Criterion): # <<<<<<<<<<<<<< @@ -827,22 +1150,21 @@ struct __pyx_obj_7sklearn_4tree_5_tree_Entropy { */ struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion { struct __pyx_obj_7sklearn_4tree_5_tree_Criterion __pyx_base; - int n_outputs; - int n_samples; double *mean_left; double *mean_right; - double *mean_init; + double *mean_total; double *sq_sum_left; double *sq_sum_right; - double *sq_sum_init; + double *sq_sum_total; double *var_left; double *var_right; - int n_right; - int n_left; + double *sum_left; + double *sum_right; + double *sum_total; }; -/* "sklearn/tree/_tree.pyx":1547 +/* "sklearn/tree/_tree.pyx":836 * * * cdef class MSE(RegressionCriterion): # <<<<<<<<<<<<<< @@ -854,125 +1176,474 @@ struct __pyx_obj_7sklearn_4tree_5_tree_MSE { }; - -/* "sklearn/tree/_tree.pyx":67 - * # ============================================================================== +/* "sklearn/tree/_tree.pyx":877 * - * cdef class Tree: # <<<<<<<<<<<<<< - * """Struct-of-arrays representation of a binary decision tree. + * + * cdef class FriedmanMSE(MSE): # <<<<<<<<<<<<<< + * """Mean squared error impurity criterion with improvement score by Friedman * */ - -struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree { - void (*resize)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_resize *__pyx_optional_args); - PyObject *(*build)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_build *__pyx_optional_args); - void (*recursive_partition)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, int, int, int, int, double *); - int (*add_split_node)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int, int, int, double, double *, double, double, int); - int (*add_leaf)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int, int, double *, double, int); - void (*find_split)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, int, int *, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int, int *, double *, double *, double *); - void (*find_best_split)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, int, int *, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int, int *, double *, double *, double *); - void (*find_random_split)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, int, int *, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int, int *, double *, double *, double *); - PyObject *(*predict)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, int __pyx_skip_dispatch); - PyObject *(*apply)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, int __pyx_skip_dispatch); - PyObject *(*compute_feature_importances)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances *__pyx_optional_args); - double (*_compute_feature_importances_gini)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int); - double (*_compute_feature_importances_squared)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int); +struct __pyx_obj_7sklearn_4tree_5_tree_FriedmanMSE { + struct __pyx_obj_7sklearn_4tree_5_tree_MSE __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *__pyx_vtabptr_7sklearn_4tree_5_tree_Tree; -static CYTHON_INLINE double __pyx_f_7sklearn_4tree_5_tree_4Tree__compute_feature_importances_gini(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int); -static CYTHON_INLINE double __pyx_f_7sklearn_4tree_5_tree_4Tree__compute_feature_importances_squared(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int); -/* "sklearn/tree/_tree.pyx":933 - * # ============================================================================== +/* "sklearn/tree/_tree.pyx":1031 * - * cdef class Criterion: # <<<<<<<<<<<<<< - * """Interface for splitting criteria (regression and classification).""" * + * cdef class BaseDenseSplitter(Splitter): # <<<<<<<<<<<<<< + * cdef DTYPE_t* X + * cdef SIZE_t X_sample_stride */ +struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter { + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter __pyx_base; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *X; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t X_sample_stride; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t X_fx_stride; +}; -struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion { - void (*init)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int); - void (*reset)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *); - int (*update)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, int, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, int *, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *); - double (*eval)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *); - void (*init_value)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *); + +/* "sklearn/tree/_tree.pyx":1062 + * + * + * cdef class BestSplitter(BaseDenseSplitter): # <<<<<<<<<<<<<< + * """Splitter for finding the best split.""" + * def __reduce__(self): + */ +struct __pyx_obj_7sklearn_4tree_5_tree_BestSplitter { + struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *__pyx_vtabptr_7sklearn_4tree_5_tree_Criterion; -/* "sklearn/tree/_tree.pyx":1284 +/* "sklearn/tree/_tree.pyx":1361 * * - * cdef class RegressionCriterion(Criterion): # <<<<<<<<<<<<<< - * """Abstract criterion for regression. + * cdef class RandomSplitter(BaseDenseSplitter): # <<<<<<<<<<<<<< + * """Splitter for finding the best random split.""" + * def __reduce__(self): + */ +struct __pyx_obj_7sklearn_4tree_5_tree_RandomSplitter { + struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter __pyx_base; +}; + + +/* "sklearn/tree/_tree.pyx":1563 + * * + * cdef class PresortBestSplitter(BaseDenseSplitter): # <<<<<<<<<<<<<< + * """Splitter for finding the best split, using presorting.""" + * cdef DTYPE_t* X_old */ +struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter { + struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter __pyx_base; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *X_old; + PyArrayObject *X_argsorted; + __pyx_t_7sklearn_4tree_5_tree_INT32_t *X_argsorted_ptr; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t X_argsorted_stride; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_total_samples; + unsigned char *sample_mask; +}; -struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RegressionCriterion { - struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion __pyx_base; + +/* "sklearn/tree/_tree.pyx":1811 + * + * + * cdef class BaseSparseSplitter(Splitter): # <<<<<<<<<<<<<< + * # The sparse splitter works only with csc sparse matrix format + * cdef DTYPE_t* X_data + */ +struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter { + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter __pyx_base; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *X_data; + __pyx_t_7sklearn_4tree_5_tree_INT32_t *X_indices; + __pyx_t_7sklearn_4tree_5_tree_INT32_t *X_indptr; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t n_total_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *index_to_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *sorted_samples; }; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_vtabptr_7sklearn_4tree_5_tree_RegressionCriterion; -/* "sklearn/tree/_tree.pyx":1547 +/* "sklearn/tree/_tree.pyx":2130 * * - * cdef class MSE(RegressionCriterion): # <<<<<<<<<<<<<< - * """Mean squared error impurity criterion. + * cdef class BestSparseSplitter(BaseSparseSplitter): # <<<<<<<<<<<<<< + * """Splitter for finding the best split, using the sparse data.""" * */ - -struct __pyx_vtabstruct_7sklearn_4tree_5_tree_MSE { - struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RegressionCriterion __pyx_base; +struct __pyx_obj_7sklearn_4tree_5_tree_BestSparseSplitter { + struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_MSE *__pyx_vtabptr_7sklearn_4tree_5_tree_MSE; -/* "sklearn/tree/_tree.pyx":961 +/* "sklearn/tree/_tree.pyx":2348 * * - * cdef class ClassificationCriterion(Criterion): # <<<<<<<<<<<<<< - * """Abstract criterion for classification. + * cdef class RandomSparseSplitter(BaseSparseSplitter): # <<<<<<<<<<<<<< + * """Splitter for finding a random split, using the sparse data.""" * */ +struct __pyx_obj_7sklearn_4tree_5_tree_RandomSparseSplitter { + struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter __pyx_base; +}; -struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion { - struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion __pyx_base; + +/* "sklearn/tree/_tree.pyx":2605 + * # Depth first builder --------------------------------------------------------- + * + * cdef class DepthFirstTreeBuilder(TreeBuilder): # <<<<<<<<<<<<<< + * """Build a decision tree in depth-first fashion.""" + * + */ +struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder { + struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion; -/* "sklearn/tree/_tree.pyx":1173 +/* "sklearn/tree/_tree.pyx":2751 * * - * cdef class Gini(ClassificationCriterion): # <<<<<<<<<<<<<< - * """Gini Index splitting criteria. + * cdef class BestFirstTreeBuilder(TreeBuilder): # <<<<<<<<<<<<<< + * """Build a decision tree in best-first fashion. + * + */ +struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder { + struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder __pyx_base; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t max_leaf_nodes; +}; + + + +/* "sklearn/tree/_utils.pxd":29 + * SIZE_t n_constant_features * + * cdef class Stack: # <<<<<<<<<<<<<< + * cdef SIZE_t capacity + * cdef SIZE_t top */ -struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Gini { - struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion __pyx_base; +struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack { + int (*is_empty)(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *); + int (*push)(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, int, double, __pyx_t_7sklearn_4tree_6_utils_SIZE_t); + int (*pop)(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *, struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *); }; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Gini *__pyx_vtabptr_7sklearn_4tree_5_tree_Gini; +static struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack *__pyx_vtabptr_7sklearn_4tree_6_utils_Stack; -/* "sklearn/tree/_tree.pyx":1233 +/* "sklearn/tree/_utils.pxd":58 + * double improvement * + * cdef class PriorityHeap: # <<<<<<<<<<<<<< + * cdef SIZE_t capacity + * cdef SIZE_t heap_ptr + */ + +struct __pyx_vtabstruct_7sklearn_4tree_6_utils_PriorityHeap { + int (*is_empty)(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *); + int (*push)(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, int, double, double, double, double); + int (*pop)(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *, struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *); +}; +static struct __pyx_vtabstruct_7sklearn_4tree_6_utils_PriorityHeap *__pyx_vtabptr_7sklearn_4tree_6_utils_PriorityHeap; + + +/* "sklearn/tree/_tree.pyx":97 + * # ============================================================================= * - * cdef class Entropy(ClassificationCriterion): # <<<<<<<<<<<<<< - * """Cross Entropy splitting criteria. + * cdef class Criterion: # <<<<<<<<<<<<<< + * """Interface for impurity criteria.""" * */ -struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Entropy { - struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion __pyx_base; +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion { + void (*init)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, double, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); + void (*reset)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *); + void (*update)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); + double (*node_impurity)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *); + void (*children_impurity)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *, double *); + void (*node_value)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *); + double (*impurity_improvement)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double); }; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Entropy *__pyx_vtabptr_7sklearn_4tree_5_tree_Entropy; -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *__pyx_vtabptr_7sklearn_4tree_5_tree_Criterion; + + +/* "sklearn/tree/_tree.pyx":922 + * + * + * cdef class Splitter: # <<<<<<<<<<<<<< + * def __cinit__(self, Criterion criterion, SIZE_t max_features, + * SIZE_t min_samples_leaf, double min_weight_leaf, + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter { + void (*init)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, PyObject *, PyArrayObject *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *); + void (*node_reset)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double *); + void (*node_split)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, double, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *); + void (*node_value)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, double *); + double (*node_impurity)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *); +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *__pyx_vtabptr_7sklearn_4tree_5_tree_Splitter; + + +/* "sklearn/tree/_tree.pyx":2955 + * # ============================================================================= + * + * cdef class Tree: # <<<<<<<<<<<<<< + * """Array-based representation of a binary decision tree. + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t (*_add_node)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, int, int, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double, double, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double); + void (*_resize)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); + int (*_resize_c)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c *__pyx_optional_args); + PyArrayObject *(*_get_value_ndarray)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *); + PyArrayObject *(*_get_node_ndarray)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *); + PyArrayObject *(*predict)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *, int __pyx_skip_dispatch); + PyArrayObject *(*apply)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *, int __pyx_skip_dispatch); + PyArrayObject *(*_apply_dense)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *); + PyArrayObject *(*_apply_sparse_csr)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *); + PyObject *(*compute_feature_importances)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances *__pyx_optional_args); +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *__pyx_vtabptr_7sklearn_4tree_5_tree_Tree; +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree__apply_dense(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *); +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree__apply_sparse_csr(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *); + + +/* "sklearn/tree/_tree.pyx":2566 + * # Tree builders + * # ============================================================================= + * cdef class TreeBuilder: # <<<<<<<<<<<<<< + * """Interface for different tree building strategies. """ + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder { + PyObject *(*build)(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *, PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build *__pyx_optional_args); + PyObject *(*_check_input)(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *, PyObject *, PyArrayObject *, PyArrayObject *); +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder *__pyx_vtabptr_7sklearn_4tree_5_tree_TreeBuilder; +static PyObject *__pyx_f_7sklearn_4tree_5_tree_11TreeBuilder__check_input(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *, PyObject *, PyArrayObject *, PyArrayObject *); + + +/* "sklearn/tree/_tree.pyx":150 + * + * + * cdef class ClassificationCriterion(Criterion): # <<<<<<<<<<<<<< + * """Abstract criterion for classification.""" + * cdef SIZE_t* n_classes + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion; + + +/* "sklearn/tree/_tree.pyx":368 + * + * + * cdef class Entropy(ClassificationCriterion): # <<<<<<<<<<<<<< + * """Cross Entropy impurity criteria. + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Entropy { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Entropy *__pyx_vtabptr_7sklearn_4tree_5_tree_Entropy; + + +/* "sklearn/tree/_tree.pyx":459 + * + * + * cdef class Gini(ClassificationCriterion): # <<<<<<<<<<<<<< + * """Gini Index impurity criteria. + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Gini { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Gini *__pyx_vtabptr_7sklearn_4tree_5_tree_Gini; + + +/* "sklearn/tree/_tree.pyx":553 + * + * + * cdef class RegressionCriterion(Criterion): # <<<<<<<<<<<<<< + * """Abstract criterion for regression. + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RegressionCriterion { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_vtabptr_7sklearn_4tree_5_tree_RegressionCriterion; + + +/* "sklearn/tree/_tree.pyx":836 + * + * + * cdef class MSE(RegressionCriterion): # <<<<<<<<<<<<<< + * """Mean squared error impurity criterion. + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_MSE { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RegressionCriterion __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_MSE *__pyx_vtabptr_7sklearn_4tree_5_tree_MSE; + + +/* "sklearn/tree/_tree.pyx":877 + * + * + * cdef class FriedmanMSE(MSE): # <<<<<<<<<<<<<< + * """Mean squared error impurity criterion with improvement score by Friedman + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_FriedmanMSE { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_MSE __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_FriedmanMSE *__pyx_vtabptr_7sklearn_4tree_5_tree_FriedmanMSE; + + +/* "sklearn/tree/_tree.pyx":1031 + * + * + * cdef class BaseDenseSplitter(Splitter): # <<<<<<<<<<<<<< + * cdef DTYPE_t* X + * cdef SIZE_t X_sample_stride + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BaseDenseSplitter { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BaseDenseSplitter *__pyx_vtabptr_7sklearn_4tree_5_tree_BaseDenseSplitter; + + +/* "sklearn/tree/_tree.pyx":1062 + * + * + * cdef class BestSplitter(BaseDenseSplitter): # <<<<<<<<<<<<<< + * """Splitter for finding the best split.""" + * def __reduce__(self): + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BestSplitter { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BaseDenseSplitter __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BestSplitter *__pyx_vtabptr_7sklearn_4tree_5_tree_BestSplitter; + + +/* "sklearn/tree/_tree.pyx":1361 + * + * + * cdef class RandomSplitter(BaseDenseSplitter): # <<<<<<<<<<<<<< + * """Splitter for finding the best random split.""" + * def __reduce__(self): + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RandomSplitter { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BaseDenseSplitter __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RandomSplitter *__pyx_vtabptr_7sklearn_4tree_5_tree_RandomSplitter; + + +/* "sklearn/tree/_tree.pyx":1563 + * + * + * cdef class PresortBestSplitter(BaseDenseSplitter): # <<<<<<<<<<<<<< + * """Splitter for finding the best split, using presorting.""" + * cdef DTYPE_t* X_old + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_PresortBestSplitter { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BaseDenseSplitter __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_PresortBestSplitter *__pyx_vtabptr_7sklearn_4tree_5_tree_PresortBestSplitter; + + +/* "sklearn/tree/_tree.pyx":1811 + * + * + * cdef class BaseSparseSplitter(Splitter): # <<<<<<<<<<<<<< + * # The sparse splitter works only with csc sparse matrix format + * cdef DTYPE_t* X_data + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BaseSparseSplitter { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter __pyx_base; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t (*_partition)(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *, double, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); + void (*extract_nnz)(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, int *); +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BaseSparseSplitter *__pyx_vtabptr_7sklearn_4tree_5_tree_BaseSparseSplitter; +static CYTHON_INLINE __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter__partition(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *, double, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter_extract_nnz(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, int *); + + +/* "sklearn/tree/_tree.pyx":2130 + * + * + * cdef class BestSparseSplitter(BaseSparseSplitter): # <<<<<<<<<<<<<< + * """Splitter for finding the best split, using the sparse data.""" + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BestSparseSplitter { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BaseSparseSplitter __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BestSparseSplitter *__pyx_vtabptr_7sklearn_4tree_5_tree_BestSparseSplitter; + + +/* "sklearn/tree/_tree.pyx":2348 + * + * + * cdef class RandomSparseSplitter(BaseSparseSplitter): # <<<<<<<<<<<<<< + * """Splitter for finding a random split, using the sparse data.""" + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RandomSparseSplitter { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BaseSparseSplitter __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RandomSparseSplitter *__pyx_vtabptr_7sklearn_4tree_5_tree_RandomSparseSplitter; + + +/* "sklearn/tree/_tree.pyx":2605 + * # Depth first builder --------------------------------------------------------- + * + * cdef class DepthFirstTreeBuilder(TreeBuilder): # <<<<<<<<<<<<<< + * """Build a decision tree in depth-first fashion.""" + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_DepthFirstTreeBuilder { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder __pyx_base; +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_DepthFirstTreeBuilder *__pyx_vtabptr_7sklearn_4tree_5_tree_DepthFirstTreeBuilder; + + +/* "sklearn/tree/_tree.pyx":2751 + * + * + * cdef class BestFirstTreeBuilder(TreeBuilder): # <<<<<<<<<<<<<< + * """Build a decision tree in best-first fashion. + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BestFirstTreeBuilder { + struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder __pyx_base; + int (*_add_split_node)(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *, struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double, int, int, struct __pyx_t_7sklearn_4tree_5_tree_Node *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *); +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BestFirstTreeBuilder *__pyx_vtabptr_7sklearn_4tree_5_tree_BestFirstTreeBuilder; +static CYTHON_INLINE int __pyx_f_7sklearn_4tree_5_tree_20BestFirstTreeBuilder__add_split_node(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *, struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double, int, int, struct __pyx_t_7sklearn_4tree_5_tree_Node *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *); + +/* --- Runtime support code (head) --- */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); @@ -982,7 +1653,7 @@ static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Entropy *__pyx_vtabptr_7skl void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil) \ @@ -1019,180 +1690,183 @@ static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Entropy *__pyx_vtabptr_7skl #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) -#endif /* CYTHON_REFNANNY */ +#endif +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ - const char* function_name); /*proto*/ + const char* function_name); -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact); /*proto*/ +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -#define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_List_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { #if CYTHON_COMPILING_IN_CPYTHON - if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else - return PySequence_GetItem(o, i); +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif -} -#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Tuple_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { + #if CYTHON_COMPILING_IN_CPYTHON - if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); #endif -} -#define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { + +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + #if CYTHON_COMPILING_IN_CPYTHON - if (PyList_CheckExact(o)) { - Py_ssize_t n = (likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if (likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = (likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if (likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { /* inlined PySequence_GetItem() */ - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (unlikely(l < 0)) return NULL; - i += l; - } - return m->sq_item(o, i); - } - } +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); #else - if (PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } +#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) #endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); + +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_PyObject_DelAttrStr(o,n) __Pyx_PyObject_SetAttrStr(o,n,NULL) +static CYTHON_INLINE int __Pyx_PyObject_SetAttrStr(PyObject* obj, PyObject* attr_name, PyObject* value) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_setattro)) + return tp->tp_setattro(obj, attr_name, value); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_setattr)) + return tp->tp_setattr(obj, PyString_AS_STRING(attr_name), value); +#endif + return PyObject_SetAttr(obj, attr_name, value); } +#else +#define __Pyx_PyObject_DelAttrStr(o,n) PyObject_DelAttr(o,n) +#define __Pyx_PyObject_SetAttrStr(o,n,v) PyObject_SetAttr(o,n,v) +#endif -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, - __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static CYTHON_INLINE int __Pyx_IterFinish(void); -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); -static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); -#define __Pyx_SetItemInt(o, i, v, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_SetItemInt_Fast(o, i, v) : \ - __Pyx_SetItemInt_Generic(o, to_py_func(i), v)) -static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { - int r; - if (!j) return -1; - r = PyObject_SetItem(o, j, v); - Py_DECREF(j); - return r; +static CYTHON_INLINE int __Pyx_PySequence_Contains(PyObject* item, PyObject* seq, int eq) { + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); } -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v) { -#if CYTHON_COMPILING_IN_CPYTHON - if (PyList_CheckExact(o)) { - Py_ssize_t n = (likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if (likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { - PyObject* old = PyList_GET_ITEM(o, n); - Py_INCREF(v); - PyList_SET_ITEM(o, n, v); - Py_DECREF(old); - return 1; - } - } else { /* inlined PySequence_SetItem() */ - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_ass_item)) { - if (unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (unlikely(l < 0)) return -1; - i += l; - } - return m->sq_ass_item(o, i, v); + +static void __Pyx_RaiseBufferFallbackError(void); + +#if PY_MAJOR_VERSION >= 3 +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { + PyObject *value; + value = PyDict_GetItemWithError(d, key); + if (unlikely(!value)) { + if (!PyErr_Occurred()) { + PyObject* args = PyTuple_Pack(1, key); + if (likely(args)) + PyErr_SetObject(PyExc_KeyError, args); + Py_XDECREF(args); } + return NULL; } + Py_INCREF(value); + return value; +} #else -#if CYTHON_COMPILING_IN_PYPY - if (PySequence_Check(o) && !PyDict_Check(o)) { -#else - if (PySequence_Check(o)) { -#endif - return PySequence_SetItem(o, i, v); - } + #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #endif - return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); -} -#define __Pyx_BufPtrCContig1d(type, buf, i0, s0) ((type)buf + i0) - #define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) - #define __Pyx_BufPtrStrided3d(type, buf, i0, s0, i1, s1, i2, s2) (type)((char*)buf + i0 * s0 + i1 * s1 + i2 * s2) - #define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) - static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +static int __Pyx_SetVtable(PyObject *dict, void *vtable); -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); +static void* __Pyx_GetVtable(PyObject *dict); + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); -static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); typedef struct { Py_ssize_t shape, strides, suboffsets; @@ -1216,12 +1890,30 @@ typedef struct { #endif - static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +static CYTHON_INLINE npy_uint32 __Pyx_PyInt_As_npy_uint32(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_int32(npy_int32 value); + +static CYTHON_INLINE npy_int32 __Pyx_PyInt_As_npy_int32(PyObject *); + +static CYTHON_INLINE long __Pyx_pow_long(long, long); /* proto */ + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -1235,7 +1927,7 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif -#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else @@ -1321,45 +2013,10 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); - -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename); /*proto*/ +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); static int __Pyx_check_binary_version(void); -static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ - #if !defined(__Pyx_PyIdentifier_FromString) #if PY_MAJOR_VERSION < 3 #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) @@ -1368,34 +2025,75 @@ static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ #endif #endif -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ - -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ - -typedef struct { - int code_line; - PyCodeObject* code_object; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); /*proto*/ - -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ - +static PyObject *__Pyx_ImportModule(const char *name); + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); + +static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_init(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_y_stride, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight, CYTHON_UNUSED double __pyx_v_weighted_n_samples, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_reset(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_update(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_new_pos); /* proto*/ +static double __pyx_f_7sklearn_4tree_5_tree_9Criterion_node_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_children_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, CYTHON_UNUSED double *__pyx_v_impurity_left, CYTHON_UNUSED double *__pyx_v_impurity_right); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_node_value(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, CYTHON_UNUSED double *__pyx_v_dest); /* proto*/ +static double __pyx_f_7sklearn_4tree_5_tree_9Criterion_impurity_improvement(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, double __pyx_v_impurity); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_init(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_y_stride, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight, double __pyx_v_weighted_n_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_reset(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_update(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_new_pos); /* proto*/ +static double __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_node_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_children_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, CYTHON_UNUSED double *__pyx_v_impurity_left, CYTHON_UNUSED double *__pyx_v_impurity_right); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_node_value(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, double *__pyx_v_dest); /* proto*/ +static double __pyx_f_7sklearn_4tree_5_tree_7Entropy_node_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_Entropy *__pyx_v_self); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_7Entropy_children_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_Entropy *__pyx_v_self, double *__pyx_v_impurity_left, double *__pyx_v_impurity_right); /* proto*/ +static double __pyx_f_7sklearn_4tree_5_tree_4Gini_node_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_Gini *__pyx_v_self); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_4Gini_children_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_Gini *__pyx_v_self, double *__pyx_v_impurity_left, double *__pyx_v_impurity_right); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_init(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_y_stride, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight, double __pyx_v_weighted_n_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_reset(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_update(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_new_pos); /* proto*/ +static double __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_node_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_children_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, CYTHON_UNUSED double *__pyx_v_impurity_left, CYTHON_UNUSED double *__pyx_v_impurity_right); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_node_value(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, double *__pyx_v_dest); /* proto*/ +static double __pyx_f_7sklearn_4tree_5_tree_3MSE_node_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_MSE *__pyx_v_self); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_3MSE_children_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_MSE *__pyx_v_self, double *__pyx_v_impurity_left, double *__pyx_v_impurity_right); /* proto*/ +static double __pyx_f_7sklearn_4tree_5_tree_11FriedmanMSE_impurity_improvement(struct __pyx_obj_7sklearn_4tree_5_tree_FriedmanMSE *__pyx_v_self, CYTHON_UNUSED double __pyx_v_impurity); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_8Splitter_init(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_8Splitter_node_reset(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end, double *__pyx_v_weighted_n_node_samples); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_8Splitter_node_split(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, CYTHON_UNUSED double __pyx_v_impurity, CYTHON_UNUSED struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_8Splitter_node_value(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, double *__pyx_v_dest); /* proto*/ +static double __pyx_f_7sklearn_4tree_5_tree_8Splitter_node_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_17BaseDenseSplitter_init(struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter *__pyx_v_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_12BestSplitter_node_split(struct __pyx_obj_7sklearn_4tree_5_tree_BestSplitter *__pyx_v_self, double __pyx_v_impurity, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_14RandomSplitter_node_split(struct __pyx_obj_7sklearn_4tree_5_tree_RandomSplitter *__pyx_v_self, double __pyx_v_impurity, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_19PresortBestSplitter_init(struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *__pyx_v_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_19PresortBestSplitter_node_split(struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *__pyx_v_self, double __pyx_v_impurity, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter_init(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *__pyx_v_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight); /* proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter__partition(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *__pyx_v_self, double __pyx_v_threshold, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end_negative, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start_positive, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_zero_pos); /* proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter_extract_nnz(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_feature, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_end_negative, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_start_positive, int *__pyx_v_is_samples_sorted); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_18BestSparseSplitter_node_split(struct __pyx_obj_7sklearn_4tree_5_tree_BestSparseSplitter *__pyx_v_self, double __pyx_v_impurity, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_20RandomSparseSplitter_node_split(struct __pyx_obj_7sklearn_4tree_5_tree_RandomSparseSplitter *__pyx_v_self, double __pyx_v_impurity, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features); /* proto*/ +static PyObject *__pyx_f_7sklearn_4tree_5_tree_11TreeBuilder_build(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *__pyx_v_self, CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, CYTHON_UNUSED PyObject *__pyx_v_X, CYTHON_UNUSED PyArrayObject *__pyx_v_y, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build *__pyx_optional_args); /* proto*/ +static PyObject *__pyx_f_7sklearn_4tree_5_tree_11TreeBuilder__check_input(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *__pyx_v_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_weight); /* proto*/ +static PyObject *__pyx_f_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_build(struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_build *__pyx_optional_args); /* proto*/ +static PyObject *__pyx_f_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_build(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_build *__pyx_optional_args); /* proto*/ +static CYTHON_INLINE int __pyx_f_7sklearn_4tree_5_tree_20BestFirstTreeBuilder__add_split_node(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_splitter, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end, double __pyx_v_impurity, int __pyx_v_is_first, int __pyx_v_is_left, struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_parent, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_depth, struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *__pyx_v_res); /* proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_4Tree__resize(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_capacity); /* proto*/ +static int __pyx_f_7sklearn_4tree_5_tree_4Tree__resize_c(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c *__pyx_optional_args); /* proto*/ +static __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_f_7sklearn_4tree_5_tree_4Tree__add_node(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_parent, int __pyx_v_is_left, int __pyx_v_is_leaf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_feature, double __pyx_v_threshold, double __pyx_v_impurity, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_node_samples, double __pyx_v_weighted_n_node_samples); /* proto*/ +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree_predict(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X, int __pyx_skip_dispatch); /* proto*/ +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree_apply(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X, int __pyx_skip_dispatch); /* proto*/ +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree__apply_dense(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X); /* proto*/ +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree__apply_sparse_csr(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X); /* proto*/ +static PyObject *__pyx_f_7sklearn_4tree_5_tree_4Tree_compute_feature_importances(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances *__pyx_optional_args); /* proto*/ +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree__get_value_ndarray(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto*/ +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree__get_node_ndarray(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto*/ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ @@ -1417,813 +2115,1266 @@ static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -/* Module declarations from 'cython' */ +/* Module declarations from 'libc.math' */ + +/* Module declarations from 'cpython.version' */ + +/* Module declarations from 'cpython.exc' */ + +/* Module declarations from 'cpython.module' */ + +/* Module declarations from 'cpython.mem' */ + +/* Module declarations from 'cpython.tuple' */ + +/* Module declarations from 'cpython.list' */ + +/* Module declarations from 'cpython.sequence' */ + +/* Module declarations from 'cpython.mapping' */ + +/* Module declarations from 'cpython.iterator' */ + +/* Module declarations from 'cpython.number' */ + +/* Module declarations from 'cpython.int' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.bool' */ +static PyTypeObject *__pyx_ptype_7cpython_4bool_bool = 0; + +/* Module declarations from 'cpython.long' */ + +/* Module declarations from 'cpython.float' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.complex' */ +static PyTypeObject *__pyx_ptype_7cpython_7complex_complex = 0; + +/* Module declarations from 'cpython.string' */ + +/* Module declarations from 'cpython.unicode' */ + +/* Module declarations from 'cpython.dict' */ + +/* Module declarations from 'cpython.instance' */ + +/* Module declarations from 'cpython.function' */ + +/* Module declarations from 'cpython.method' */ + +/* Module declarations from 'cpython.weakref' */ + +/* Module declarations from 'cpython.getargs' */ + +/* Module declarations from 'cpython.pythread' */ + +/* Module declarations from 'cpython.pystate' */ + +/* Module declarations from 'cpython.cobject' */ + +/* Module declarations from 'cpython.oldbuffer' */ + +/* Module declarations from 'cpython.set' */ + +/* Module declarations from 'cpython.bytes' */ + +/* Module declarations from 'cpython.pycapsule' */ + +/* Module declarations from 'cpython' */ + +/* Module declarations from 'sklearn.tree._utils' */ +static PyTypeObject *__pyx_ptype_7sklearn_4tree_6_utils_Stack = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_6_utils_PriorityHeap = 0; /* Module declarations from 'sklearn.tree._tree' */ static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_Criterion = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_Splitter = 0; static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_Tree = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_TreeBuilder = 0; static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion = 0; -static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_Gini = 0; static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_Entropy = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_Gini = 0; static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_RegressionCriterion = 0; static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_MSE = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_FriedmanMSE = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_BaseDenseSplitter = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_BestSplitter = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_RandomSplitter = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_PresortBestSplitter = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_BaseSparseSplitter = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_BestSparseSplitter = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_RandomSparseSplitter = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_DepthFirstTreeBuilder = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_5_tree_BestFirstTreeBuilder = 0; static double __pyx_v_7sklearn_4tree_5_tree_INFINITY; -static int __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF; -static int __pyx_v_7sklearn_4tree_5_tree__TREE_UNDEFINED; -static int __pyx_v_7sklearn_4tree_5_tree__TREE_SPLIT_BEST; -static int __pyx_v_7sklearn_4tree_5_tree__TREE_SPLIT_RANDOM; -static CYTHON_INLINE PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(int *, int); /*proto*/ -static CYTHON_INLINE PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_doublep_to_ndarray(double *, int); /*proto*/ -static CYTHON_INLINE int __pyx_f_7sklearn_4tree_5_tree__smallest_sample_larger_than(int, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, int *, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int); /*proto*/ -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t = { "int32_t", NULL, sizeof(__pyx_t_5numpy_int32_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_int32_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_int32_t), 0 }; +static __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF; +static __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_7sklearn_4tree_5_tree__TREE_UNDEFINED; +static __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_7sklearn_4tree_5_tree_INITIAL_STACK_SIZE; +static __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_7sklearn_4tree_5_tree_MIN_IMPURITY_SPLIT; +static __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_7sklearn_4tree_5_tree_FEATURE_THRESHOLD; +static __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_7sklearn_4tree_5_tree_EXTRACT_NNZ_SWITCH; +static int __pyx_v_7sklearn_4tree_5_tree_IS_FIRST; +static int __pyx_v_7sklearn_4tree_5_tree_IS_NOT_FIRST; +static int __pyx_v_7sklearn_4tree_5_tree_IS_LEFT; +static int __pyx_v_7sklearn_4tree_5_tree_IS_NOT_LEFT; +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree__init_split(struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); /*proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_sort(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); /*proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_swap(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_f_7sklearn_4tree_5_tree_median3(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); /*proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_introsort(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, int); /*proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_sift_down(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); /*proto*/ +static void __pyx_f_7sklearn_4tree_5_tree_heapsort(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); /*proto*/ +static int __pyx_f_7sklearn_4tree_5_tree_compare_SIZE_t(void const *, void const *); /*proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_binary_search(__pyx_t_7sklearn_4tree_5_tree_INT32_t *, __pyx_t_7sklearn_4tree_5_tree_INT32_t, __pyx_t_7sklearn_4tree_5_tree_INT32_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_INT32_t *); /*proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_extract_nnz_index_to_samples(__pyx_t_7sklearn_4tree_5_tree_INT32_t *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_t_7sklearn_4tree_5_tree_INT32_t, __pyx_t_7sklearn_4tree_5_tree_INT32_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *); /*proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_extract_nnz_binary_search(__pyx_t_7sklearn_4tree_5_tree_INT32_t *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_t_7sklearn_4tree_5_tree_INT32_t, __pyx_t_7sklearn_4tree_5_tree_INT32_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, int *); /*proto*/ +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_sparse_swap(__pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); /*proto*/ +static CYTHON_INLINE int __pyx_f_7sklearn_4tree_5_tree__add_to_frontier(struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *, struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_4tree_5_tree_UINT32_t __pyx_f_7sklearn_4tree_5_tree_our_rand_r(__pyx_t_7sklearn_4tree_5_tree_UINT32_t *); /*proto*/ +static CYTHON_INLINE PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_sizet_ptr_to_ndarray(__pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t); /*proto*/ +static CYTHON_INLINE __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_f_7sklearn_4tree_5_tree_rand_int(__pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_UINT32_t *); /*proto*/ +static CYTHON_INLINE double __pyx_f_7sklearn_4tree_5_tree_rand_uniform(double, double, __pyx_t_7sklearn_4tree_5_tree_UINT32_t *); /*proto*/ +static CYTHON_INLINE double __pyx_f_7sklearn_4tree_5_tree_log(double); /*proto*/ +static __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_fuse_0__pyx_f_7sklearn_4tree_5_tree_safe_realloc(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t **, size_t); /*proto*/ +static __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_fuse_1__pyx_f_7sklearn_4tree_5_tree_safe_realloc(__pyx_t_7sklearn_4tree_5_tree_SIZE_t **, size_t); /*proto*/ +static unsigned char *__pyx_fuse_2__pyx_f_7sklearn_4tree_5_tree_safe_realloc(unsigned char **, size_t); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_SIZE_t = { "SIZE_t", NULL, sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_4tree_5_tree_SIZE_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_4tree_5_tree_SIZE_t), 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DOUBLE_t = { "DOUBLE_t", NULL, sizeof(__pyx_t_7sklearn_4tree_5_tree_DOUBLE_t), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_INT32_t = { "INT32_t", NULL, sizeof(__pyx_t_7sklearn_4tree_5_tree_INT32_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_4tree_5_tree_INT32_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_4tree_5_tree_INT32_t), 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t = { "float64_t", NULL, sizeof(__pyx_t_5numpy_float64_t), { 0 }, 0, 'R', 0, 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_BOOL_t = { "BOOL_t", NULL, sizeof(__pyx_t_7sklearn_4tree_5_tree_BOOL_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_4tree_5_tree_BOOL_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_4tree_5_tree_BOOL_t), 0 }; #define __Pyx_MODULE_NAME "sklearn.tree._tree" int __pyx_module_is_main_sklearn__tree___tree = 0; /* Implementation of 'sklearn.tree._tree' */ +static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_MemoryError; static PyObject *__pyx_builtin_ValueError; -static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_RuntimeError; +static int __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs, PyArrayObject *__pyx_v_n_classes); /* proto */ +static void __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_6__getstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_8__setstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_d); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs); /* proto */ +static void __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_6__getstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_8__setstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_d); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, double __pyx_v_min_weight_leaf, PyObject *__pyx_v_random_state); /* proto */ +static void __pyx_pf_7sklearn_4tree_5_tree_8Splitter_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_4__getstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_6__setstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_d); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_9criterion___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter_9criterion_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter_9criterion_4__del__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_12max_features___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter_12max_features_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_17BaseDenseSplitter___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter *__pyx_v_self, CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, CYTHON_UNUSED double __pyx_v_min_weight_leaf, CYTHON_UNUSED PyObject *__pyx_v_random_state); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_12BestSplitter___reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_BestSplitter *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_14RandomSplitter___reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_RandomSplitter *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_19PresortBestSplitter___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *__pyx_v_self, CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, CYTHON_UNUSED double __pyx_v_min_weight_leaf, CYTHON_UNUSED PyObject *__pyx_v_random_state); /* proto */ +static void __pyx_pf_7sklearn_4tree_5_tree_19PresortBestSplitter_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19PresortBestSplitter_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_18BaseSparseSplitter___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *__pyx_v_self, CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, CYTHON_UNUSED double __pyx_v_min_weight_leaf, CYTHON_UNUSED PyObject *__pyx_v_random_state); /* proto */ +static void __pyx_pf_7sklearn_4tree_5_tree_18BaseSparseSplitter_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_18BestSparseSplitter___reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_BestSparseSplitter *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_20RandomSparseSplitter___reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_RandomSparseSplitter *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_11TreeBuilder_build(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_weight); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_splitter, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, double __pyx_v_min_weight_leaf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_depth); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_2build(struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_weight); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_20BestFirstTreeBuilder___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_splitter, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, PyObject *__pyx_v_min_weight_leaf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_depth, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_leaf_nodes); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_2build(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_weight); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_classes___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_13children_left___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_14children_right___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_7feature___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9threshold___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_8impurity___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_14n_node_samples___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_23weighted_n_node_samples___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_5value___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10best_error___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10init_error___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_samples___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, int __pyx_v_n_features, PyObject *__pyx_v_n_classes, int __pyx_v_n_outputs, struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion, double __pyx_v_max_depth, int __pyx_v_min_samples_split, int __pyx_v_min_samples_leaf, double __pyx_v_min_density, int __pyx_v_max_features, int __pyx_v_find_split_algorithm, PyObject *__pyx_v_random_state); /* proto */ +static int __pyx_pf_7sklearn_4tree_5_tree_4Tree___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, int __pyx_v_n_features, PyArrayObject *__pyx_v_n_classes, int __pyx_v_n_outputs); /* proto */ static void __pyx_pf_7sklearn_4tree_5_tree_4Tree_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_6__getstate__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_8__setstate__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_d); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10build(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_mask, PyArrayObject *__pyx_v_X_argsorted); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_12predict(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyArrayObject *__pyx_v_X); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_14apply(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyArrayObject *__pyx_v_X); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_16compute_feature_importances(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_method); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10predict(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_12apply(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_14compute_feature_importances(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_normalize); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_12value_stride___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_12value_stride_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9criterion___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_9criterion_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_9criterion_4__del__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9max_depth___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_9max_depth_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_17min_samples_split___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_17min_samples_split_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_11min_density___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_11min_density_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_12max_features___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_12max_features_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_12random_state___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_12random_state_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_12random_state_4__del__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10node_count___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_10node_count_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_8capacity___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self); /* proto */ static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_8capacity_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, int __pyx_v_n_outputs, PyObject *__pyx_v_n_classes); /* proto */ -static void __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_6__getstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_8__setstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_d); /* proto */ -static int __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, int __pyx_v_n_outputs); /* proto */ -static void __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_6__getstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_8__setstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_d); /* proto */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree__random_sample_mask(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_total_samples, int __pyx_v_n_total_in_bag, PyObject *__pyx_v_random_state); /* proto */ +static PyObject *__pyx_pf_7sklearn_4tree_5_tree__realloc_test(CYTHON_UNUSED PyObject *__pyx_self); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ -static char __pyx_k_1[] = "find_split_algorithm"; -static char __pyx_k_2[] = "Attempting to find a split with an empty sample_mask"; -static char __pyx_k_4[] = "compute_feature_importances"; -static char __pyx_k_5[] = "Invalid value for method. Allowed string values are \"gini\", or \"squared\"."; -static char __pyx_k_7[] = "ndarray is not C contiguous"; -static char __pyx_k_9[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_11[] = "Non-native byte order not supported"; -static char __pyx_k_13[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_14[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_17[] = "Format string allocated too short."; -static char __pyx_k_21[] = "/home/gilles/Sources/scikit-learn/sklearn/tree/_tree.pyx"; -static char __pyx_k_22[] = "sklearn.tree._tree"; -static char __pyx_k__B[] = "B"; -static char __pyx_k__C[] = "C"; -static char __pyx_k__F[] = "F"; -static char __pyx_k__H[] = "H"; -static char __pyx_k__I[] = "I"; -static char __pyx_k__L[] = "L"; -static char __pyx_k__O[] = "O"; -static char __pyx_k__Q[] = "Q"; -static char __pyx_k__T[] = "T"; -static char __pyx_k__X[] = "X"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__d[] = "d"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__g[] = "g"; -static char __pyx_k__h[] = "h"; -static char __pyx_k__i[] = "i"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__q[] = "q"; -static char __pyx_k__y[] = "y"; -static char __pyx_k__Zd[] = "Zd"; -static char __pyx_k__Zf[] = "Zf"; -static char __pyx_k__Zg[] = "Zg"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__inf[] = "inf"; -static char __pyx_k__max[] = "max"; -static char __pyx_k__sum[] = "sum"; -static char __pyx_k__axis[] = "axis"; -static char __pyx_k__bool[] = "bool"; -static char __pyx_k__gini[] = "gini"; -static char __pyx_k__int8[] = "int8"; -static char __pyx_k__ones[] = "ones"; -static char __pyx_k__rand[] = "rand"; -static char __pyx_k__DTYPE[] = "DTYPE"; -static char __pyx_k__apply[] = "apply"; -static char __pyx_k__build[] = "build"; -static char __pyx_k__dtype[] = "dtype"; -static char __pyx_k__flags[] = "flags"; -static char __pyx_k__int32[] = "int32"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__order[] = "order"; -static char __pyx_k__range[] = "range"; -static char __pyx_k__value[] = "value"; -static char __pyx_k__zeros[] = "zeros"; -static char __pyx_k__DOUBLE[] = "DOUBLE"; -static char __pyx_k__arange[] = "arange"; -static char __pyx_k__astype[] = "astype"; -static char __pyx_k__method[] = "method"; -static char __pyx_k__argsort[] = "argsort"; -static char __pyx_k__asarray[] = "asarray"; -static char __pyx_k__feature[] = "feature"; -static char __pyx_k__float32[] = "float32"; -static char __pyx_k__float64[] = "float64"; -static char __pyx_k__predict[] = "predict"; -static char __pyx_k__squared[] = "squared"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__capacity[] = "capacity"; -static char __pyx_k__n_bagged[] = "n_bagged"; -static char __pyx_k__TREE_LEAF[] = "TREE_LEAF"; -static char __pyx_k__criterion[] = "criterion"; -static char __pyx_k__isfortran[] = "isfortran"; -static char __pyx_k__max_depth[] = "max_depth"; -static char __pyx_k__n_classes[] = "n_classes"; -static char __pyx_k__n_outputs[] = "n_outputs"; -static char __pyx_k__n_samples[] = "n_samples"; -static char __pyx_k__threshold[] = "threshold"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__best_error[] = "best_error"; -static char __pyx_k__contiguous[] = "contiguous"; -static char __pyx_k__init_error[] = "init_error"; -static char __pyx_k__n_features[] = "n_features"; -static char __pyx_k__node_count[] = "node_count"; -static char __pyx_k__MemoryError[] = "MemoryError"; -static char __pyx_k__X_argsorted[] = "X_argsorted"; -static char __pyx_k__min_density[] = "min_density"; -static char __pyx_k__permutation[] = "permutation"; -static char __pyx_k__sample_mask[] = "sample_mask"; -static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k____getstate__[] = "__getstate__"; -static char __pyx_k__max_features[] = "max_features"; -static char __pyx_k__random_state[] = "random_state"; -static char __pyx_k__children_left[] = "children_left"; -static char __pyx_k__TREE_UNDEFINED[] = "TREE_UNDEFINED"; -static char __pyx_k__asfortranarray[] = "asfortranarray"; -static char __pyx_k__children_right[] = "children_right"; -static char __pyx_k__n_total_in_bag[] = "n_total_in_bag"; -static char __pyx_k__TREE_SPLIT_BEST[] = "TREE_SPLIT_BEST"; -static char __pyx_k__n_total_samples[] = "n_total_samples"; -static char __pyx_k__min_samples_leaf[] = "min_samples_leaf"; -static char __pyx_k__TREE_SPLIT_RANDOM[] = "TREE_SPLIT_RANDOM"; -static char __pyx_k__min_samples_split[] = "min_samples_split"; -static char __pyx_k___random_sample_mask[] = "_random_sample_mask"; -static PyObject *__pyx_n_s_1; -static PyObject *__pyx_kp_u_11; -static PyObject *__pyx_kp_u_13; -static PyObject *__pyx_kp_u_14; -static PyObject *__pyx_kp_u_17; -static PyObject *__pyx_kp_s_2; -static PyObject *__pyx_kp_s_21; -static PyObject *__pyx_n_s_22; -static PyObject *__pyx_n_s_4; -static PyObject *__pyx_kp_s_5; -static PyObject *__pyx_kp_u_7; -static PyObject *__pyx_kp_u_9; -static PyObject *__pyx_n_s__C; -static PyObject *__pyx_n_s__DOUBLE; -static PyObject *__pyx_n_s__DTYPE; -static PyObject *__pyx_n_s__F; -static PyObject *__pyx_n_s__MemoryError; -static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__T; -static PyObject *__pyx_n_s__TREE_LEAF; -static PyObject *__pyx_n_s__TREE_SPLIT_BEST; -static PyObject *__pyx_n_s__TREE_SPLIT_RANDOM; -static PyObject *__pyx_n_s__TREE_UNDEFINED; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s__X; -static PyObject *__pyx_n_s__X_argsorted; -static PyObject *__pyx_n_s____getstate__; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s___random_sample_mask; -static PyObject *__pyx_n_s__apply; -static PyObject *__pyx_n_s__arange; -static PyObject *__pyx_n_s__argsort; -static PyObject *__pyx_n_s__asarray; -static PyObject *__pyx_n_s__asfortranarray; -static PyObject *__pyx_n_s__astype; -static PyObject *__pyx_n_s__axis; -static PyObject *__pyx_n_s__best_error; -static PyObject *__pyx_n_s__bool; -static PyObject *__pyx_n_s__build; -static PyObject *__pyx_n_s__capacity; -static PyObject *__pyx_n_s__children_left; -static PyObject *__pyx_n_s__children_right; -static PyObject *__pyx_n_s__contiguous; -static PyObject *__pyx_n_s__criterion; -static PyObject *__pyx_n_s__dtype; -static PyObject *__pyx_n_s__feature; -static PyObject *__pyx_n_s__flags; -static PyObject *__pyx_n_s__float32; -static PyObject *__pyx_n_s__float64; -static PyObject *__pyx_n_s__gini; -static PyObject *__pyx_n_s__i; -static PyObject *__pyx_n_s__inf; -static PyObject *__pyx_n_s__init_error; -static PyObject *__pyx_n_s__int32; -static PyObject *__pyx_n_s__int8; -static PyObject *__pyx_n_s__isfortran; -static PyObject *__pyx_n_s__max; -static PyObject *__pyx_n_s__max_depth; -static PyObject *__pyx_n_s__max_features; -static PyObject *__pyx_n_s__method; -static PyObject *__pyx_n_s__min_density; -static PyObject *__pyx_n_s__min_samples_leaf; -static PyObject *__pyx_n_s__min_samples_split; -static PyObject *__pyx_n_s__n_bagged; -static PyObject *__pyx_n_s__n_classes; -static PyObject *__pyx_n_s__n_features; -static PyObject *__pyx_n_s__n_outputs; -static PyObject *__pyx_n_s__n_samples; -static PyObject *__pyx_n_s__n_total_in_bag; -static PyObject *__pyx_n_s__n_total_samples; -static PyObject *__pyx_n_s__node_count; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__ones; -static PyObject *__pyx_n_s__order; -static PyObject *__pyx_n_s__permutation; -static PyObject *__pyx_n_s__predict; -static PyObject *__pyx_n_s__rand; -static PyObject *__pyx_n_s__random_state; -static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__sample_mask; -static PyObject *__pyx_n_s__squared; -static PyObject *__pyx_n_s__sum; -static PyObject *__pyx_n_s__threshold; -static PyObject *__pyx_n_s__value; -static PyObject *__pyx_n_s__y; -static PyObject *__pyx_n_s__zeros; +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Criterion(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Splitter(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Tree(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_TreeBuilder(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_ClassificationCriterion(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Entropy(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Gini(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_RegressionCriterion(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_MSE(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_FriedmanMSE(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_BaseDenseSplitter(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_BestSplitter(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_RandomSplitter(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_PresortBestSplitter(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_BaseSparseSplitter(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_BestSparseSplitter(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_RandomSparseSplitter(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_DepthFirstTreeBuilder(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_BestFirstTreeBuilder(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_B[] = "B"; +static char __pyx_k_C[] = "C"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_X[] = "X"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_p[] = "p"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_y[] = "y"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_inf[] = "inf"; +static char __pyx_k_max[] = "max"; +static char __pyx_k_sum[] = "sum"; +static char __pyx_k_axis[] = "axis"; +static char __pyx_k_clip[] = "clip"; +static char __pyx_k_copy[] = "copy"; +static char __pyx_k_data[] = "data"; +static char __pyx_k_intp[] = "intp"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_mode[] = "mode"; +static char __pyx_k_ndim[] = "ndim"; +static char __pyx_k_take[] = "take"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_tree[] = "tree"; +static char __pyx_k_DTYPE[] = "DTYPE"; +static char __pyx_k_apply[] = "apply"; +static char __pyx_k_build[] = "build"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_flags[] = "flags"; +static char __pyx_k_int32[] = "int32"; +static char __pyx_k_names[] = "names"; +static char __pyx_k_nodes[] = "nodes"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_order[] = "order"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_shape[] = "shape"; +static char __pyx_k_tocsc[] = "tocsc"; +static char __pyx_k_zeros[] = "zeros"; +static char __pyx_k_DOUBLE[] = "DOUBLE"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_indptr[] = "indptr"; +static char __pyx_k_values[] = "values"; +static char __pyx_k_argsort[] = "argsort"; +static char __pyx_k_asarray[] = "asarray"; +static char __pyx_k_feature[] = "feature"; +static char __pyx_k_float32[] = "float32"; +static char __pyx_k_float64[] = "float64"; +static char __pyx_k_formats[] = "formats"; +static char __pyx_k_indices[] = "indices"; +static char __pyx_k_offsets[] = "offsets"; +static char __pyx_k_predict[] = "predict"; +static char __pyx_k_randint[] = "randint"; +static char __pyx_k_reshape[] = "reshape"; +static char __pyx_k_strides[] = "strides"; +static char __pyx_k_getstate[] = "__getstate__"; +static char __pyx_k_impurity[] = "impurity"; +static char __pyx_k_issparse[] = "issparse"; +static char __pyx_k_itemsize[] = "itemsize"; +static char __pyx_k_splitter[] = "splitter"; +static char __pyx_k_TREE_LEAF[] = "TREE_LEAF"; +static char __pyx_k_criterion[] = "criterion"; +static char __pyx_k_max_depth[] = "max_depth"; +static char __pyx_k_n_classes[] = "n_classes"; +static char __pyx_k_n_outputs[] = "n_outputs"; +static char __pyx_k_normalize[] = "normalize"; +static char __pyx_k_threshold[] = "threshold"; +static char __pyx_k_NODE_DTYPE[] = "NODE_DTYPE"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_contiguous[] = "contiguous"; +static char __pyx_k_csc_matrix[] = "csc_matrix"; +static char __pyx_k_csr_matrix[] = "csr_matrix"; +static char __pyx_k_left_child[] = "left_child"; +static char __pyx_k_n_features[] = "n_features"; +static char __pyx_k_node_count[] = "node_count"; +static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static char __pyx_k_MemoryError[] = "MemoryError"; +static char __pyx_k_right_child[] = "right_child"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_c_contiguous[] = "c_contiguous"; +static char __pyx_k_max_features[] = "max_features"; +static char __pyx_k_random_state[] = "random_state"; +static char __pyx_k_realloc_test[] = "_realloc_test"; +static char __pyx_k_scipy_sparse[] = "scipy.sparse"; +static char __pyx_k_sort_indices[] = "sort_indices"; +static char __pyx_k_sample_weight[] = "sample_weight"; +static char __pyx_k_TREE_UNDEFINED[] = "TREE_UNDEFINED"; +static char __pyx_k_asfortranarray[] = "asfortranarray"; +static char __pyx_k_max_leaf_nodes[] = "max_leaf_nodes"; +static char __pyx_k_n_node_samples[] = "n_node_samples"; +static char __pyx_k_min_weight_leaf[] = "min_weight_leaf"; +static char __pyx_k_min_samples_leaf[] = "min_samples_leaf"; +static char __pyx_k_ascontiguousarray[] = "ascontiguousarray"; +static char __pyx_k_min_samples_split[] = "min_samples_split"; +static char __pyx_k_resizing_tree_to_d[] = "resizing tree to %d"; +static char __pyx_k_sklearn_tree__tree[] = "sklearn.tree._tree"; +static char __pyx_k_weighted_n_node_samples[] = "weighted_n_node_samples"; +static char __pyx_k_X_should_be_in_csc_format[] = "X should be in csc format"; +static char __pyx_k_could_not_allocate_d_bytes[] = "could not allocate %d bytes"; +static char __pyx_k_compute_feature_importances[] = "compute_feature_importances"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_could_not_allocate_d_d_bytes[] = "could not allocate (%d * %d) bytes"; +static char __pyx_k_home_gilles_src_scikit_learn_sk[] = "/home/gilles/src/scikit-learn/sklearn/tree/_tree.pyx"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_Did_not_recognise_loaded_array_l[] = "Did not recognise loaded array layout"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_No_support_for_np_int64_index_ba[] = "No support for np.int64 index based sparse matrices"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_X_dtype_should_be_np_float32_got[] = "X.dtype should be np.float32, got %s"; +static char __pyx_k_X_should_be_in_csr_matrix_format[] = "X should be in csr_matrix format, got %s"; +static char __pyx_k_X_should_be_in_np_ndarray_format[] = "X should be in np.ndarray format, got %s"; +static char __pyx_k_You_have_loaded_Tree_version_whi[] = "You have loaded Tree version which cannot be imported"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_n_s_C; +static PyObject *__pyx_n_s_DOUBLE; +static PyObject *__pyx_n_s_DTYPE; +static PyObject *__pyx_kp_s_Did_not_recognise_loaded_array_l; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_n_s_MemoryError; +static PyObject *__pyx_n_s_NODE_DTYPE; +static PyObject *__pyx_kp_s_No_support_for_np_int64_index_ba; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_TREE_LEAF; +static PyObject *__pyx_n_s_TREE_UNDEFINED; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_kp_s_X_dtype_should_be_np_float32_got; +static PyObject *__pyx_kp_s_X_should_be_in_csc_format; +static PyObject *__pyx_kp_s_X_should_be_in_csr_matrix_format; +static PyObject *__pyx_kp_s_X_should_be_in_np_ndarray_format; +static PyObject *__pyx_kp_s_You_have_loaded_Tree_version_whi; +static PyObject *__pyx_n_s_apply; +static PyObject *__pyx_n_s_argsort; +static PyObject *__pyx_n_s_asarray; +static PyObject *__pyx_n_s_ascontiguousarray; +static PyObject *__pyx_n_s_asfortranarray; +static PyObject *__pyx_n_s_axis; +static PyObject *__pyx_n_s_build; +static PyObject *__pyx_n_s_c_contiguous; +static PyObject *__pyx_n_s_clip; +static PyObject *__pyx_n_s_compute_feature_importances; +static PyObject *__pyx_n_s_contiguous; +static PyObject *__pyx_n_s_copy; +static PyObject *__pyx_kp_s_could_not_allocate_d_bytes; +static PyObject *__pyx_kp_s_could_not_allocate_d_d_bytes; +static PyObject *__pyx_n_s_criterion; +static PyObject *__pyx_n_s_csc_matrix; +static PyObject *__pyx_n_s_csr_matrix; +static PyObject *__pyx_n_s_data; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_feature; +static PyObject *__pyx_n_s_flags; +static PyObject *__pyx_n_s_float32; +static PyObject *__pyx_n_s_float64; +static PyObject *__pyx_n_s_formats; +static PyObject *__pyx_n_s_getstate; +static PyObject *__pyx_kp_s_home_gilles_src_scikit_learn_sk; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_impurity; +static PyObject *__pyx_n_s_indices; +static PyObject *__pyx_n_s_indptr; +static PyObject *__pyx_n_s_inf; +static PyObject *__pyx_n_s_int32; +static PyObject *__pyx_n_s_intp; +static PyObject *__pyx_n_s_issparse; +static PyObject *__pyx_n_s_itemsize; +static PyObject *__pyx_n_s_left_child; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_max; +static PyObject *__pyx_n_s_max_depth; +static PyObject *__pyx_n_s_max_features; +static PyObject *__pyx_n_s_max_leaf_nodes; +static PyObject *__pyx_n_s_min_samples_leaf; +static PyObject *__pyx_n_s_min_samples_split; +static PyObject *__pyx_n_s_min_weight_leaf; +static PyObject *__pyx_n_s_mode; +static PyObject *__pyx_n_s_n_classes; +static PyObject *__pyx_n_s_n_features; +static PyObject *__pyx_n_s_n_node_samples; +static PyObject *__pyx_n_s_n_outputs; +static PyObject *__pyx_n_s_names; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_ndim; +static PyObject *__pyx_n_s_node_count; +static PyObject *__pyx_n_s_nodes; +static PyObject *__pyx_n_s_normalize; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_offsets; +static PyObject *__pyx_n_s_order; +static PyObject *__pyx_n_s_p; +static PyObject *__pyx_n_s_predict; +static PyObject *__pyx_n_s_pyx_vtable; +static PyObject *__pyx_n_s_randint; +static PyObject *__pyx_n_s_random_state; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_realloc_test; +static PyObject *__pyx_n_s_reshape; +static PyObject *__pyx_kp_s_resizing_tree_to_d; +static PyObject *__pyx_n_s_right_child; +static PyObject *__pyx_n_s_sample_weight; +static PyObject *__pyx_n_s_scipy_sparse; +static PyObject *__pyx_n_s_shape; +static PyObject *__pyx_n_s_sklearn_tree__tree; +static PyObject *__pyx_n_s_sort_indices; +static PyObject *__pyx_n_s_splitter; +static PyObject *__pyx_n_s_strides; +static PyObject *__pyx_n_s_sum; +static PyObject *__pyx_n_s_take; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_n_s_threshold; +static PyObject *__pyx_n_s_tocsc; +static PyObject *__pyx_n_s_tree; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_values; +static PyObject *__pyx_n_s_weighted_n_node_samples; +static PyObject *__pyx_n_s_y; +static PyObject *__pyx_n_s_zeros; +static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; -static PyObject *__pyx_int_2; static PyObject *__pyx_int_neg_1; static PyObject *__pyx_int_neg_2; -static PyObject *__pyx_int_15; -static PyObject *__pyx_k_tuple_3; -static PyObject *__pyx_k_tuple_6; -static PyObject *__pyx_k_tuple_8; -static PyObject *__pyx_k_tuple_10; -static PyObject *__pyx_k_tuple_12; -static PyObject *__pyx_k_tuple_15; -static PyObject *__pyx_k_tuple_16; -static PyObject *__pyx_k_tuple_18; -static PyObject *__pyx_k_tuple_19; -static PyObject *__pyx_k_codeobj_20; +static __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_k__5; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__8; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_tuple__10; +static PyObject *__pyx_tuple__11; +static PyObject *__pyx_tuple__12; +static PyObject *__pyx_codeobj__13; -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_classes_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_classes_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_classes___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; +/* "sklearn/tree/_tree.pyx":100 + * """Interface for impurity criteria.""" + * + * cdef void init(self, DOUBLE_t* y, SIZE_t y_stride, DOUBLE_t* sample_weight, # <<<<<<<<<<<<<< + * double weighted_n_samples, SIZE_t* samples, SIZE_t start, + * SIZE_t end) nogil: + */ + +static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_init(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_y_stride, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight, CYTHON_UNUSED double __pyx_v_weighted_n_samples, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end) { + + /* function exit code */ } -/* "sklearn/tree/_tree.pyx":165 - * # Wrap for outside world - * property n_classes: - * def __get__(self): # <<<<<<<<<<<<<< - * return intp_to_ndarray(self.n_classes, self.n_outputs) +/* "sklearn/tree/_tree.pyx":107 + * pass * + * cdef void reset(self) nogil: # <<<<<<<<<<<<<< + * """Reset the criterion at pos=start.""" + * pass */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_classes___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); +static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_reset(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self) { - /* "sklearn/tree/_tree.pyx":166 - * property n_classes: - * def __get__(self): - * return intp_to_ndarray(self.n_classes, self.n_outputs) # <<<<<<<<<<<<<< + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":111 + * pass * - * property children_left: + * cdef void update(self, SIZE_t new_pos) nogil: # <<<<<<<<<<<<<< + * """Update the collected statistics by moving samples[pos:new_pos] from + * the right child to the left child.""" */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(__pyx_v_self->n_classes, __pyx_v_self->n_outputs)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_classes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; +static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_update(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_new_pos) { + + /* function exit code */ } -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13children_left_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13children_left_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_13children_left___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); +/* "sklearn/tree/_tree.pyx":116 + * pass + * + * cdef double node_impurity(self) nogil: # <<<<<<<<<<<<<< + * """Evaluate the impurity of the current node, i.e. the impurity of + * samples[start:end].""" + */ + +static double __pyx_f_7sklearn_4tree_5_tree_9Criterion_node_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self) { + double __pyx_r; + + /* function exit code */ + __pyx_r = 0; return __pyx_r; } -/* "sklearn/tree/_tree.pyx":169 - * - * property children_left: - * def __get__(self): # <<<<<<<<<<<<<< - * return intp_to_ndarray(self.children_left, self.node_count) +/* "sklearn/tree/_tree.pyx":121 + * pass * + * cdef void children_impurity(self, double* impurity_left, # <<<<<<<<<<<<<< + * double* impurity_right) nogil: + * """Evaluate the impurity in children nodes, i.e. the impurity of */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_13children_left___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); +static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_children_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, CYTHON_UNUSED double *__pyx_v_impurity_left, CYTHON_UNUSED double *__pyx_v_impurity_right) { - /* "sklearn/tree/_tree.pyx":170 - * property children_left: - * def __get__(self): - * return intp_to_ndarray(self.children_left, self.node_count) # <<<<<<<<<<<<<< + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":127 + * pass * - * property children_right: + * cdef void node_value(self, double* dest) nogil: # <<<<<<<<<<<<<< + * """Compute the node value of samples[start:end] into dest.""" + * pass */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(__pyx_v_self->children_left, __pyx_v_self->node_count)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.children_left.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} +static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_node_value(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, CYTHON_UNUSED double *__pyx_v_dest) { -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_14children_right_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_14children_right_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_14children_right___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; + /* function exit code */ } -/* "sklearn/tree/_tree.pyx":173 +/* "sklearn/tree/_tree.pyx":131 + * pass * - * property children_right: - * def __get__(self): # <<<<<<<<<<<<<< - * return intp_to_ndarray(self.children_right, self.node_count) + * cdef double impurity_improvement(self, double impurity) nogil: # <<<<<<<<<<<<<< + * """Weighted impurity improvement, i.e. * */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_14children_right___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); +static double __pyx_f_7sklearn_4tree_5_tree_9Criterion_impurity_improvement(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, double __pyx_v_impurity) { + double __pyx_v_impurity_left; + double __pyx_v_impurity_right; + double __pyx_r; - /* "sklearn/tree/_tree.pyx":174 - * property children_right: - * def __get__(self): - * return intp_to_ndarray(self.children_right, self.node_count) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":143 + * cdef double impurity_right * - * property feature: + * self.children_impurity(&impurity_left, &impurity_right) # <<<<<<<<<<<<<< + * + * return ((self.weighted_n_node_samples / self.weighted_n_samples) * */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(__pyx_v_self->children_right, __pyx_v_self->node_count)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_vtab)->children_impurity(__pyx_v_self, (&__pyx_v_impurity_left), (&__pyx_v_impurity_right)); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "sklearn/tree/_tree.pyx":145 + * self.children_impurity(&impurity_left, &impurity_right) + * + * return ((self.weighted_n_node_samples / self.weighted_n_samples) * # <<<<<<<<<<<<<< + * (impurity - self.weighted_n_right / self.weighted_n_node_samples * impurity_right + * - self.weighted_n_left / self.weighted_n_node_samples * impurity_left)) + */ + __pyx_r = ((__pyx_v_self->weighted_n_node_samples / __pyx_v_self->weighted_n_samples) * ((__pyx_v_impurity - ((__pyx_v_self->weighted_n_right / __pyx_v_self->weighted_n_node_samples) * __pyx_v_impurity_right)) - ((__pyx_v_self->weighted_n_left / __pyx_v_self->weighted_n_node_samples) * __pyx_v_impurity_left))); goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.children_right.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_7feature_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_7feature_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_7feature___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); + /* "sklearn/tree/_tree.pyx":131 + * pass + * + * cdef double impurity_improvement(self, double impurity) nogil: # <<<<<<<<<<<<<< + * """Weighted impurity improvement, i.e. + * + */ + + /* function exit code */ + __pyx_L0:; return __pyx_r; } -/* "sklearn/tree/_tree.pyx":177 - * - * property feature: - * def __get__(self): # <<<<<<<<<<<<<< - * return intp_to_ndarray(self.feature, self.node_count) +/* "sklearn/tree/_tree.pyx":158 + * cdef double* label_count_total * + * def __cinit__(self, SIZE_t n_outputs, # <<<<<<<<<<<<<< + * np.ndarray[SIZE_t, ndim=1] n_classes): + * # Default values */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_7feature___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + PyArrayObject *__pyx_v_n_classes = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "sklearn/tree/_tree.pyx":178 - * property feature: - * def __get__(self): - * return intp_to_ndarray(self.feature, self.node_count) # <<<<<<<<<<<<<< - * - * property threshold: - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(__pyx_v_self->feature, __pyx_v_self->node_count)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_n_outputs,&__pyx_n_s_n_classes,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_outputs)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_classes)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_n_outputs = __Pyx_PyInt_As_Py_intptr_t(values[0]); if (unlikely((__pyx_v_n_outputs == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_classes = ((PyArrayObject *)values[1]); + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._tree.ClassificationCriterion.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_n_classes), __pyx_ptype_5numpy_ndarray, 1, "n_classes", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self), __pyx_v_n_outputs, __pyx_v_n_classes); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.feature.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __pyx_r = -1; __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9threshold_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9threshold_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9threshold___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/tree/_tree.pyx":181 - * - * property threshold: - * def __get__(self): # <<<<<<<<<<<<<< - * return doublep_to_ndarray(self.threshold, self.node_count) - * - */ - -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9threshold___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; +static int __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs, PyArrayObject *__pyx_v_n_classes) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_label_count_stride; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_elements; + __Pyx_LocalBuf_ND __pyx_pybuffernd_n_classes; + __Pyx_Buffer __pyx_pybuffer_n_classes; + int __pyx_r; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_4; + int __pyx_t_5; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_6; + int __pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_RefNannySetupContext("__cinit__", 0); + __pyx_pybuffer_n_classes.pybuffer.buf = NULL; + __pyx_pybuffer_n_classes.refcount = 0; + __pyx_pybuffernd_n_classes.data = NULL; + __pyx_pybuffernd_n_classes.rcbuffer = &__pyx_pybuffer_n_classes; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_n_classes.rcbuffer->pybuffer, (PyObject*)__pyx_v_n_classes, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_SIZE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_n_classes.diminfo[0].strides = __pyx_pybuffernd_n_classes.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_n_classes.diminfo[0].shape = __pyx_pybuffernd_n_classes.rcbuffer->pybuffer.shape[0]; - /* "sklearn/tree/_tree.pyx":182 - * property threshold: - * def __get__(self): - * return doublep_to_ndarray(self.threshold, self.node_count) # <<<<<<<<<<<<<< - * - * property value: + /* "sklearn/tree/_tree.pyx":161 + * np.ndarray[SIZE_t, ndim=1] n_classes): + * # Default values + * self.y = NULL # <<<<<<<<<<<<<< + * self.y_stride = 0 + * self.sample_weight = NULL */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_doublep_to_ndarray(__pyx_v_self->threshold, __pyx_v_self->node_count)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_v_self->__pyx_base.y = NULL; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.threshold.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":162 + * # Default values + * self.y = NULL + * self.y_stride = 0 # <<<<<<<<<<<<<< + * self.sample_weight = NULL + * + */ + __pyx_v_self->__pyx_base.y_stride = 0; -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_5value_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_5value_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_5value___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":163 + * self.y = NULL + * self.y_stride = 0 + * self.sample_weight = NULL # <<<<<<<<<<<<<< + * + * self.samples = NULL + */ + __pyx_v_self->__pyx_base.sample_weight = NULL; -/* "sklearn/tree/_tree.pyx":185 + /* "sklearn/tree/_tree.pyx":165 + * self.sample_weight = NULL * - * property value: - * def __get__(self): # <<<<<<<<<<<<<< - * cdef np.npy_intp shape[3] - * shape[0] = self.node_count + * self.samples = NULL # <<<<<<<<<<<<<< + * self.start = 0 + * self.pos = 0 */ + __pyx_v_self->__pyx_base.samples = NULL; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_5value___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - npy_intp __pyx_v_shape[3]; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); + /* "sklearn/tree/_tree.pyx":166 + * + * self.samples = NULL + * self.start = 0 # <<<<<<<<<<<<<< + * self.pos = 0 + * self.end = 0 + */ + __pyx_v_self->__pyx_base.start = 0; - /* "sklearn/tree/_tree.pyx":187 - * def __get__(self): - * cdef np.npy_intp shape[3] - * shape[0] = self.node_count # <<<<<<<<<<<<<< - * shape[1] = self.n_outputs - * shape[2] = self.max_n_classes + /* "sklearn/tree/_tree.pyx":167 + * self.samples = NULL + * self.start = 0 + * self.pos = 0 # <<<<<<<<<<<<<< + * self.end = 0 + * */ - (__pyx_v_shape[0]) = ((npy_intp)__pyx_v_self->node_count); + __pyx_v_self->__pyx_base.pos = 0; - /* "sklearn/tree/_tree.pyx":188 - * cdef np.npy_intp shape[3] - * shape[0] = self.node_count - * shape[1] = self.n_outputs # <<<<<<<<<<<<<< - * shape[2] = self.max_n_classes - * return np.PyArray_SimpleNewFromData(3, shape, np.NPY_DOUBLE, self.value) + /* "sklearn/tree/_tree.pyx":168 + * self.start = 0 + * self.pos = 0 + * self.end = 0 # <<<<<<<<<<<<<< + * + * self.n_outputs = n_outputs */ - (__pyx_v_shape[1]) = ((npy_intp)__pyx_v_self->n_outputs); + __pyx_v_self->__pyx_base.end = 0; - /* "sklearn/tree/_tree.pyx":189 - * shape[0] = self.node_count - * shape[1] = self.n_outputs - * shape[2] = self.max_n_classes # <<<<<<<<<<<<<< - * return np.PyArray_SimpleNewFromData(3, shape, np.NPY_DOUBLE, self.value) + /* "sklearn/tree/_tree.pyx":170 + * self.end = 0 * + * self.n_outputs = n_outputs # <<<<<<<<<<<<<< + * self.n_node_samples = 0 + * self.weighted_n_node_samples = 0.0 */ - (__pyx_v_shape[2]) = ((npy_intp)__pyx_v_self->max_n_classes); + __pyx_v_self->__pyx_base.n_outputs = __pyx_v_n_outputs; - /* "sklearn/tree/_tree.pyx":190 - * shape[1] = self.n_outputs - * shape[2] = self.max_n_classes - * return np.PyArray_SimpleNewFromData(3, shape, np.NPY_DOUBLE, self.value) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":171 * - * property best_error: + * self.n_outputs = n_outputs + * self.n_node_samples = 0 # <<<<<<<<<<<<<< + * self.weighted_n_node_samples = 0.0 + * self.weighted_n_left = 0.0 */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_SimpleNewFromData(3, __pyx_v_shape, NPY_DOUBLE, __pyx_v_self->value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_v_self->__pyx_base.n_node_samples = 0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.value.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":172 + * self.n_outputs = n_outputs + * self.n_node_samples = 0 + * self.weighted_n_node_samples = 0.0 # <<<<<<<<<<<<<< + * self.weighted_n_left = 0.0 + * self.weighted_n_right = 0.0 + */ + __pyx_v_self->__pyx_base.weighted_n_node_samples = 0.0; -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10best_error_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10best_error_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10best_error___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":173 + * self.n_node_samples = 0 + * self.weighted_n_node_samples = 0.0 + * self.weighted_n_left = 0.0 # <<<<<<<<<<<<<< + * self.weighted_n_right = 0.0 + * + */ + __pyx_v_self->__pyx_base.weighted_n_left = 0.0; -/* "sklearn/tree/_tree.pyx":193 + /* "sklearn/tree/_tree.pyx":174 + * self.weighted_n_node_samples = 0.0 + * self.weighted_n_left = 0.0 + * self.weighted_n_right = 0.0 # <<<<<<<<<<<<<< * - * property best_error: - * def __get__(self): # <<<<<<<<<<<<<< - * return doublep_to_ndarray(self.best_error, self.node_count) + * self.label_count_left = NULL + */ + __pyx_v_self->__pyx_base.weighted_n_right = 0.0; + + /* "sklearn/tree/_tree.pyx":176 + * self.weighted_n_right = 0.0 * + * self.label_count_left = NULL # <<<<<<<<<<<<<< + * self.label_count_right = NULL + * self.label_count_total = NULL */ + __pyx_v_self->label_count_left = NULL; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10best_error___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); + /* "sklearn/tree/_tree.pyx":177 + * + * self.label_count_left = NULL + * self.label_count_right = NULL # <<<<<<<<<<<<<< + * self.label_count_total = NULL + * + */ + __pyx_v_self->label_count_right = NULL; - /* "sklearn/tree/_tree.pyx":194 - * property best_error: - * def __get__(self): - * return doublep_to_ndarray(self.best_error, self.node_count) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":178 + * self.label_count_left = NULL + * self.label_count_right = NULL + * self.label_count_total = NULL # <<<<<<<<<<<<<< * - * property init_error: + * # Count labels for each output */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_doublep_to_ndarray(__pyx_v_self->best_error, __pyx_v_self->node_count)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_v_self->label_count_total = NULL; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.best_error.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":181 + * + * # Count labels for each output + * self.n_classes = NULL # <<<<<<<<<<<<<< + * safe_realloc(&self.n_classes, n_outputs) + * + */ + __pyx_v_self->n_classes = NULL; -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10init_error_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10init_error_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10init_error___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":182 + * # Count labels for each output + * self.n_classes = NULL + * safe_realloc(&self.n_classes, n_outputs) # <<<<<<<<<<<<<< + * + * cdef SIZE_t k = 0 + */ + __pyx_fuse_1__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_self->n_classes), __pyx_v_n_outputs); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} -/* "sklearn/tree/_tree.pyx":197 + /* "sklearn/tree/_tree.pyx":184 + * safe_realloc(&self.n_classes, n_outputs) * - * property init_error: - * def __get__(self): # <<<<<<<<<<<<<< - * return doublep_to_ndarray(self.init_error, self.node_count) + * cdef SIZE_t k = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t label_count_stride = 0 * */ + __pyx_v_k = 0; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10init_error___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); + /* "sklearn/tree/_tree.pyx":185 + * + * cdef SIZE_t k = 0 + * cdef SIZE_t label_count_stride = 0 # <<<<<<<<<<<<<< + * + * for k in range(n_outputs): + */ + __pyx_v_label_count_stride = 0; + + /* "sklearn/tree/_tree.pyx":187 + * cdef SIZE_t label_count_stride = 0 + * + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * self.n_classes[k] = n_classes[k] + * + */ + __pyx_t_1 = __pyx_v_n_outputs; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_k = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":188 + * + * for k in range(n_outputs): + * self.n_classes[k] = n_classes[k] # <<<<<<<<<<<<<< + * + * if n_classes[k] > label_count_stride: + */ + __pyx_t_3 = __pyx_v_k; + (__pyx_v_self->n_classes[__pyx_v_k]) = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_pybuffernd_n_classes.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_n_classes.diminfo[0].strides)); + + /* "sklearn/tree/_tree.pyx":190 + * self.n_classes[k] = n_classes[k] + * + * if n_classes[k] > label_count_stride: # <<<<<<<<<<<<<< + * label_count_stride = n_classes[k] + * + */ + __pyx_t_4 = __pyx_v_k; + __pyx_t_5 = (((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_pybuffernd_n_classes.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_n_classes.diminfo[0].strides)) > __pyx_v_label_count_stride) != 0); + if (__pyx_t_5) { + + /* "sklearn/tree/_tree.pyx":191 + * + * if n_classes[k] > label_count_stride: + * label_count_stride = n_classes[k] # <<<<<<<<<<<<<< + * + * self.label_count_stride = label_count_stride + */ + __pyx_t_6 = __pyx_v_k; + __pyx_v_label_count_stride = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_pybuffernd_n_classes.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_n_classes.diminfo[0].strides)); + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "sklearn/tree/_tree.pyx":193 + * label_count_stride = n_classes[k] + * + * self.label_count_stride = label_count_stride # <<<<<<<<<<<<<< + * + * # Allocate counters + */ + __pyx_v_self->label_count_stride = __pyx_v_label_count_stride; + + /* "sklearn/tree/_tree.pyx":196 + * + * # Allocate counters + * cdef SIZE_t n_elements = n_outputs * label_count_stride # <<<<<<<<<<<<<< + * self.label_count_left = calloc(n_elements, sizeof(double)) + * self.label_count_right = calloc(n_elements, sizeof(double)) + */ + __pyx_v_n_elements = (__pyx_v_n_outputs * __pyx_v_label_count_stride); + + /* "sklearn/tree/_tree.pyx":197 + * # Allocate counters + * cdef SIZE_t n_elements = n_outputs * label_count_stride + * self.label_count_left = calloc(n_elements, sizeof(double)) # <<<<<<<<<<<<<< + * self.label_count_right = calloc(n_elements, sizeof(double)) + * self.label_count_total = calloc(n_elements, sizeof(double)) + */ + __pyx_v_self->label_count_left = ((double *)calloc(__pyx_v_n_elements, (sizeof(double)))); /* "sklearn/tree/_tree.pyx":198 - * property init_error: - * def __get__(self): - * return doublep_to_ndarray(self.init_error, self.node_count) # <<<<<<<<<<<<<< + * cdef SIZE_t n_elements = n_outputs * label_count_stride + * self.label_count_left = calloc(n_elements, sizeof(double)) + * self.label_count_right = calloc(n_elements, sizeof(double)) # <<<<<<<<<<<<<< + * self.label_count_total = calloc(n_elements, sizeof(double)) * - * property n_samples: */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_doublep_to_ndarray(__pyx_v_self->init_error, __pyx_v_self->node_count)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_v_self->label_count_right = ((double *)calloc(__pyx_v_n_elements, (sizeof(double)))); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "sklearn/tree/_tree.pyx":199 + * self.label_count_left = calloc(n_elements, sizeof(double)) + * self.label_count_right = calloc(n_elements, sizeof(double)) + * self.label_count_total = calloc(n_elements, sizeof(double)) # <<<<<<<<<<<<<< + * + * # Check for allocation errors + */ + __pyx_v_self->label_count_total = ((double *)calloc(__pyx_v_n_elements, (sizeof(double)))); + + /* "sklearn/tree/_tree.pyx":202 + * + * # Check for allocation errors + * if (self.label_count_left == NULL or # <<<<<<<<<<<<<< + * self.label_count_right == NULL or + * self.label_count_total == NULL): + */ + __pyx_t_7 = ((__pyx_v_self->label_count_left == NULL) != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_5 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":203 + * # Check for allocation errors + * if (self.label_count_left == NULL or + * self.label_count_right == NULL or # <<<<<<<<<<<<<< + * self.label_count_total == NULL): + * raise MemoryError() + */ + __pyx_t_7 = ((__pyx_v_self->label_count_right == NULL) != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_5 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":204 + * if (self.label_count_left == NULL or + * self.label_count_right == NULL or + * self.label_count_total == NULL): # <<<<<<<<<<<<<< + * raise MemoryError() + * + */ + __pyx_t_7 = ((__pyx_v_self->label_count_total == NULL) != 0); + __pyx_t_5 = __pyx_t_7; + __pyx_L7_bool_binop_done:; + if (__pyx_t_5) { + + /* "sklearn/tree/_tree.pyx":205 + * self.label_count_right == NULL or + * self.label_count_total == NULL): + * raise MemoryError() # <<<<<<<<<<<<<< + * + * def __dealloc__(self): + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":158 + * cdef double* label_count_total + * + * def __cinit__(self, SIZE_t n_outputs, # <<<<<<<<<<<<<< + * np.ndarray[SIZE_t, ndim=1] n_classes): + * # Default values + */ + + /* function exit code */ + __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.init_error.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_n_classes.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.tree._tree.ClassificationCriterion.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + goto __pyx_L2; __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_n_classes.rcbuffer->pybuffer); + __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } +/* "sklearn/tree/_tree.pyx":207 + * raise MemoryError() + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Destructor.""" + * free(self.n_classes) + */ + /* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_samples_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_samples_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; +static void __pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_3__dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_samples___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_2__dealloc__(((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); - return __pyx_r; } -/* "sklearn/tree/_tree.pyx":201 +static void __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "sklearn/tree/_tree.pyx":209 + * def __dealloc__(self): + * """Destructor.""" + * free(self.n_classes) # <<<<<<<<<<<<<< + * free(self.label_count_left) + * free(self.label_count_right) + */ + free(__pyx_v_self->n_classes); + + /* "sklearn/tree/_tree.pyx":210 + * """Destructor.""" + * free(self.n_classes) + * free(self.label_count_left) # <<<<<<<<<<<<<< + * free(self.label_count_right) + * free(self.label_count_total) + */ + free(__pyx_v_self->label_count_left); + + /* "sklearn/tree/_tree.pyx":211 + * free(self.n_classes) + * free(self.label_count_left) + * free(self.label_count_right) # <<<<<<<<<<<<<< + * free(self.label_count_total) * - * property n_samples: - * def __get__(self): # <<<<<<<<<<<<<< - * return intp_to_ndarray(self.n_samples, self.node_count) + */ + free(__pyx_v_self->label_count_right); + + /* "sklearn/tree/_tree.pyx":212 + * free(self.label_count_left) + * free(self.label_count_right) + * free(self.label_count_total) # <<<<<<<<<<<<<< + * + * def __reduce__(self): + */ + free(__pyx_v_self->label_count_total); + + /* "sklearn/tree/_tree.pyx":207 + * raise MemoryError() + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Destructor.""" + * free(self.n_classes) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "sklearn/tree/_tree.pyx":214 + * free(self.label_count_total) * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (ClassificationCriterion, + * (self.n_outputs, */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_samples___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_4__reduce__(((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_RefNannySetupContext("__reduce__", 0); - /* "sklearn/tree/_tree.pyx":202 - * property n_samples: - * def __get__(self): - * return intp_to_ndarray(self.n_samples, self.node_count) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":215 * - * def __cinit__(self, int n_features, object n_classes, int n_outputs, + * def __reduce__(self): + * return (ClassificationCriterion, # <<<<<<<<<<<<<< + * (self.n_outputs, + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs)), */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(__pyx_v_self->n_samples, __pyx_v_self->node_count)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":216 + * def __reduce__(self): + * return (ClassificationCriterion, + * (self.n_outputs, # <<<<<<<<<<<<<< + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs)), + * self.__getstate__()) + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.n_outputs); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); + + /* "sklearn/tree/_tree.pyx":217 + * return (ClassificationCriterion, + * (self.n_outputs, + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs)), # <<<<<<<<<<<<<< + * self.__getstate__()) + * + */ + __pyx_t_2 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_sizet_ptr_to_ndarray(__pyx_v_self->n_classes, __pyx_v_self->__pyx_base.n_outputs)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + + /* "sklearn/tree/_tree.pyx":216 + * def __reduce__(self): + * return (ClassificationCriterion, + * (self.n_outputs, # <<<<<<<<<<<<<< + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs)), + * self.__getstate__()) + */ + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 216; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + + /* "sklearn/tree/_tree.pyx":218 + * (self.n_outputs, + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs)), + * self.__getstate__()) # <<<<<<<<<<<<<< + * + * def __getstate__(self): + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_getstate); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_1); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_1, function); + } + } + if (__pyx_t_4) { + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + __pyx_t_2 = __Pyx_PyObject_CallNoArg(__pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":215 + * + * def __reduce__(self): + * return (ClassificationCriterion, # <<<<<<<<<<<<<< + * (self.n_outputs, + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs)), + */ + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion))); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion))); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_3 = 0; + __pyx_t_2 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":214 + * free(self.label_count_total) + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (ClassificationCriterion, + * (self.n_outputs, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_samples.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.ClassificationCriterion.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); @@ -2231,2209 +3382,2157 @@ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_samples___get__(struct return __pyx_r; } -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - int __pyx_v_n_features; - PyObject *__pyx_v_n_classes = 0; - int __pyx_v_n_outputs; - struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion = 0; - double __pyx_v_max_depth; - int __pyx_v_min_samples_split; - int __pyx_v_min_samples_leaf; - double __pyx_v_min_density; - int __pyx_v_max_features; - int __pyx_v_find_split_algorithm; - PyObject *__pyx_v_random_state = 0; - int __pyx_r; +/* "sklearn/tree/_tree.pyx":220 + * self.__getstate__()) + * + * def __getstate__(self): # <<<<<<<<<<<<<< + * return {} + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_features,&__pyx_n_s__n_classes,&__pyx_n_s__n_outputs,&__pyx_n_s__criterion,&__pyx_n_s__max_depth,&__pyx_n_s__min_samples_split,&__pyx_n_s__min_samples_leaf,&__pyx_n_s__min_density,&__pyx_n_s__max_features,&__pyx_n_s_1,&__pyx_n_s__random_state,0}; - PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); - case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); - case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_features)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_classes)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 11, 11, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_outputs)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 11, 11, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 3: - if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__criterion)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 11, 11, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 4: - if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__max_depth)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 11, 11, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 5: - if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__min_samples_split)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 11, 11, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 6: - if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__min_samples_leaf)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 11, 11, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 7: - if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__min_density)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 11, 11, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 8: - if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__max_features)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 11, 11, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 9: - if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_1)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 11, 11, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 10: - if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__random_state)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 11, 11, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 11) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - values[9] = PyTuple_GET_ITEM(__pyx_args, 9); - values[10] = PyTuple_GET_ITEM(__pyx_args, 10); - } - __pyx_v_n_features = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_features == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_n_classes = values[1]; - __pyx_v_n_outputs = __Pyx_PyInt_AsInt(values[2]); if (unlikely((__pyx_v_n_outputs == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)values[3]); - __pyx_v_max_depth = __pyx_PyFloat_AsDouble(values[4]); if (unlikely((__pyx_v_max_depth == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_min_samples_split = __Pyx_PyInt_AsInt(values[5]); if (unlikely((__pyx_v_min_samples_split == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_min_samples_leaf = __Pyx_PyInt_AsInt(values[6]); if (unlikely((__pyx_v_min_samples_leaf == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_min_density = __pyx_PyFloat_AsDouble(values[7]); if (unlikely((__pyx_v_min_density == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_max_features = __Pyx_PyInt_AsInt(values[8]); if (unlikely((__pyx_v_max_features == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_find_split_algorithm = __Pyx_PyInt_AsInt(values[9]); if (unlikely((__pyx_v_find_split_algorithm == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_random_state = values[10]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 11, 11, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannySetupContext("__getstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_6__getstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_criterion), __pyx_ptype_7sklearn_4tree_5_tree_Criterion, 1, "criterion", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), __pyx_v_n_features, __pyx_v_n_classes, __pyx_v_n_outputs, __pyx_v_criterion, __pyx_v_max_depth, __pyx_v_min_samples_split, __pyx_v_min_samples_leaf, __pyx_v_min_density, __pyx_v_max_features, __pyx_v_find_split_algorithm, __pyx_v_random_state); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_6__getstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getstate__", 0); + + /* "sklearn/tree/_tree.pyx":221 + * + * def __getstate__(self): + * return {} # <<<<<<<<<<<<<< + * + * def __setstate__(self, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":220 + * self.__getstate__()) + * + * def __getstate__(self): # <<<<<<<<<<<<<< + * return {} + * + */ + + /* function exit code */ __pyx_L1_error:; - __pyx_r = -1; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.ClassificationCriterion.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pyx":204 - * return intp_to_ndarray(self.n_samples, self.node_count) +/* "sklearn/tree/_tree.pyx":223 + * return {} + * + * def __setstate__(self, d): # <<<<<<<<<<<<<< + * pass * - * def __cinit__(self, int n_features, object n_classes, int n_outputs, # <<<<<<<<<<<<<< - * Criterion criterion, double max_depth, int min_samples_split, - * int min_samples_leaf, double min_density, int max_features, */ -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, int __pyx_v_n_features, PyObject *__pyx_v_n_classes, int __pyx_v_n_outputs, struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion, double __pyx_v_max_depth, int __pyx_v_min_samples_split, int __pyx_v_min_samples_leaf, double __pyx_v_min_density, int __pyx_v_max_features, int __pyx_v_find_split_algorithm, PyObject *__pyx_v_random_state) { - int __pyx_v_k; - int __pyx_r; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d) { + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; + __Pyx_RefNannySetupContext("__setstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_8__setstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self), ((PyObject *)__pyx_v_d)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_8__setstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate__", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":226 + * pass + * + * cdef void init(self, DOUBLE_t* y, SIZE_t y_stride, # <<<<<<<<<<<<<< + * DOUBLE_t* sample_weight, double weighted_n_samples, + * SIZE_t* samples, SIZE_t start, SIZE_t end) nogil: + */ + +static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_init(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_y_stride, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight, double __pyx_v_weighted_n_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end) { + double __pyx_v_weighted_n_node_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_label_count_stride; + double *__pyx_v_label_count_total; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_c; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t __pyx_v_w; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_offset; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_2; + double *__pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_4; int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; + int __pyx_t_8; - /* "sklearn/tree/_tree.pyx":212 - * cdef int k + /* "sklearn/tree/_tree.pyx":232 + * children samples[start:start] and samples[start:end].""" + * # Initialize fields + * self.y = y # <<<<<<<<<<<<<< + * self.y_stride = y_stride + * self.sample_weight = sample_weight + */ + __pyx_v_self->__pyx_base.y = __pyx_v_y; + + /* "sklearn/tree/_tree.pyx":233 + * # Initialize fields + * self.y = y + * self.y_stride = y_stride # <<<<<<<<<<<<<< + * self.sample_weight = sample_weight + * self.samples = samples + */ + __pyx_v_self->__pyx_base.y_stride = __pyx_v_y_stride; + + /* "sklearn/tree/_tree.pyx":234 + * self.y = y + * self.y_stride = y_stride + * self.sample_weight = sample_weight # <<<<<<<<<<<<<< + * self.samples = samples + * self.start = start + */ + __pyx_v_self->__pyx_base.sample_weight = __pyx_v_sample_weight; + + /* "sklearn/tree/_tree.pyx":235 + * self.y_stride = y_stride + * self.sample_weight = sample_weight + * self.samples = samples # <<<<<<<<<<<<<< + * self.start = start + * self.end = end + */ + __pyx_v_self->__pyx_base.samples = __pyx_v_samples; + + /* "sklearn/tree/_tree.pyx":236 + * self.sample_weight = sample_weight + * self.samples = samples + * self.start = start # <<<<<<<<<<<<<< + * self.end = end + * self.n_node_samples = end - start + */ + __pyx_v_self->__pyx_base.start = __pyx_v_start; + + /* "sklearn/tree/_tree.pyx":237 + * self.samples = samples + * self.start = start + * self.end = end # <<<<<<<<<<<<<< + * self.n_node_samples = end - start + * self.weighted_n_samples = weighted_n_samples + */ + __pyx_v_self->__pyx_base.end = __pyx_v_end; + + /* "sklearn/tree/_tree.pyx":238 + * self.start = start + * self.end = end + * self.n_node_samples = end - start # <<<<<<<<<<<<<< + * self.weighted_n_samples = weighted_n_samples + * cdef double weighted_n_node_samples = 0.0 + */ + __pyx_v_self->__pyx_base.n_node_samples = (__pyx_v_end - __pyx_v_start); + + /* "sklearn/tree/_tree.pyx":239 + * self.end = end + * self.n_node_samples = end - start + * self.weighted_n_samples = weighted_n_samples # <<<<<<<<<<<<<< + * cdef double weighted_n_node_samples = 0.0 * - * self.n_features = n_features # <<<<<<<<<<<<<< - * self.n_outputs = n_outputs - * self.n_classes = malloc(n_outputs * sizeof(int)) */ - __pyx_v_self->n_features = __pyx_v_n_features; + __pyx_v_self->__pyx_base.weighted_n_samples = __pyx_v_weighted_n_samples; - /* "sklearn/tree/_tree.pyx":213 + /* "sklearn/tree/_tree.pyx":240 + * self.n_node_samples = end - start + * self.weighted_n_samples = weighted_n_samples + * cdef double weighted_n_node_samples = 0.0 # <<<<<<<<<<<<<< * - * self.n_features = n_features - * self.n_outputs = n_outputs # <<<<<<<<<<<<<< - * self.n_classes = malloc(n_outputs * sizeof(int)) + * # Initialize label_count_total and weighted_n_node_samples + */ + __pyx_v_weighted_n_node_samples = 0.0; + + /* "sklearn/tree/_tree.pyx":243 * + * # Initialize label_count_total and weighted_n_node_samples + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride */ - __pyx_v_self->n_outputs = __pyx_v_n_outputs; + __pyx_t_1 = __pyx_v_self->__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":214 - * self.n_features = n_features - * self.n_outputs = n_outputs - * self.n_classes = malloc(n_outputs * sizeof(int)) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":244 + * # Initialize label_count_total and weighted_n_node_samples + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes # <<<<<<<<<<<<<< + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total + */ + __pyx_t_2 = __pyx_v_self->n_classes; + __pyx_v_n_classes = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":245 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< + * cdef double* label_count_total = self.label_count_total * - * if self.n_classes == NULL: */ - __pyx_v_self->n_classes = ((int *)malloc((__pyx_v_n_outputs * (sizeof(int))))); + __pyx_t_1 = __pyx_v_self->label_count_stride; + __pyx_v_label_count_stride = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":216 - * self.n_classes = malloc(n_outputs * sizeof(int)) + /* "sklearn/tree/_tree.pyx":246 + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total # <<<<<<<<<<<<<< * - * if self.n_classes == NULL: # <<<<<<<<<<<<<< - * raise MemoryError() + * cdef SIZE_t i = 0 + */ + __pyx_t_3 = __pyx_v_self->label_count_total; + __pyx_v_label_count_total = __pyx_t_3; + + /* "sklearn/tree/_tree.pyx":248 + * cdef double* label_count_total = self.label_count_total * + * cdef SIZE_t i = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t p = 0 + * cdef SIZE_t k = 0 */ - __pyx_t_1 = (__pyx_v_self->n_classes == NULL); - if (__pyx_t_1) { + __pyx_v_i = 0; - /* "sklearn/tree/_tree.pyx":217 + /* "sklearn/tree/_tree.pyx":249 * - * if self.n_classes == NULL: - * raise MemoryError() # <<<<<<<<<<<<<< + * cdef SIZE_t i = 0 + * cdef SIZE_t p = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t k = 0 + * cdef SIZE_t c = 0 + */ + __pyx_v_p = 0; + + /* "sklearn/tree/_tree.pyx":250 + * cdef SIZE_t i = 0 + * cdef SIZE_t p = 0 + * cdef SIZE_t k = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t c = 0 + * cdef DOUBLE_t w = 1.0 + */ + __pyx_v_k = 0; + + /* "sklearn/tree/_tree.pyx":251 + * cdef SIZE_t p = 0 + * cdef SIZE_t k = 0 + * cdef SIZE_t c = 0 # <<<<<<<<<<<<<< + * cdef DOUBLE_t w = 1.0 + * cdef SIZE_t offset = 0 + */ + __pyx_v_c = 0; + + /* "sklearn/tree/_tree.pyx":252 + * cdef SIZE_t k = 0 + * cdef SIZE_t c = 0 + * cdef DOUBLE_t w = 1.0 # <<<<<<<<<<<<<< + * cdef SIZE_t offset = 0 * - * self.max_n_classes = np.max(n_classes) */ - PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; - } - __pyx_L3:; + __pyx_v_w = 1.0; - /* "sklearn/tree/_tree.pyx":219 - * raise MemoryError() + /* "sklearn/tree/_tree.pyx":253 + * cdef SIZE_t c = 0 + * cdef DOUBLE_t w = 1.0 + * cdef SIZE_t offset = 0 # <<<<<<<<<<<<<< * - * self.max_n_classes = np.max(n_classes) # <<<<<<<<<<<<<< - * self.value_stride = self.n_outputs * self.max_n_classes + * for k in range(n_outputs): + */ + __pyx_v_offset = 0; + + /* "sklearn/tree/_tree.pyx":255 + * cdef SIZE_t offset = 0 * + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * memset(label_count_total + offset, 0, + * n_classes[k] * sizeof(double)) */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__max); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_n_classes); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_n_classes); - __Pyx_GIVEREF(__pyx_v_n_classes); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_5 = __Pyx_PyInt_AsInt(__pyx_t_4); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_self->max_n_classes = __pyx_t_5; + __pyx_t_1 = __pyx_v_n_outputs; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_1; __pyx_t_4+=1) { + __pyx_v_k = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":220 + /* "sklearn/tree/_tree.pyx":256 * - * self.max_n_classes = np.max(n_classes) - * self.value_stride = self.n_outputs * self.max_n_classes # <<<<<<<<<<<<<< + * for k in range(n_outputs): + * memset(label_count_total + offset, 0, # <<<<<<<<<<<<<< + * n_classes[k] * sizeof(double)) + * offset += label_count_stride + */ + memset((__pyx_v_label_count_total + __pyx_v_offset), 0, ((__pyx_v_n_classes[__pyx_v_k]) * (sizeof(double)))); + + /* "sklearn/tree/_tree.pyx":258 + * memset(label_count_total + offset, 0, + * n_classes[k] * sizeof(double)) + * offset += label_count_stride # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: + * for p in range(start, end): */ - __pyx_v_self->value_stride = (__pyx_v_self->n_outputs * __pyx_v_self->max_n_classes); + __pyx_v_offset = (__pyx_v_offset + __pyx_v_label_count_stride); + } - /* "sklearn/tree/_tree.pyx":222 - * self.value_stride = self.n_outputs * self.max_n_classes + /* "sklearn/tree/_tree.pyx":260 + * offset += label_count_stride * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * self.n_classes[k] = n_classes[k] + * for p in range(start, end): # <<<<<<<<<<<<<< + * i = samples[p] * */ - __pyx_t_5 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_5; __pyx_v_k++) { + __pyx_t_1 = __pyx_v_end; + for (__pyx_t_4 = __pyx_v_start; __pyx_t_4 < __pyx_t_1; __pyx_t_4+=1) { + __pyx_v_p = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":223 + /* "sklearn/tree/_tree.pyx":261 * - * for k from 0 <= k < n_outputs: - * self.n_classes[k] = n_classes[k] # <<<<<<<<<<<<<< + * for p in range(start, end): + * i = samples[p] # <<<<<<<<<<<<<< * - * # Parameters + * if sample_weight != NULL: */ - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_n_classes, __pyx_v_k, sizeof(int), PyInt_FromLong); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = __Pyx_PyInt_AsInt(__pyx_t_4); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - (__pyx_v_self->n_classes[__pyx_v_k]) = __pyx_t_6; - } + __pyx_v_i = (__pyx_v_samples[__pyx_v_p]); - /* "sklearn/tree/_tree.pyx":226 + /* "sklearn/tree/_tree.pyx":263 + * i = samples[p] + * + * if sample_weight != NULL: # <<<<<<<<<<<<<< + * w = sample_weight[i] * - * # Parameters - * self.criterion = criterion # <<<<<<<<<<<<<< - * self.max_depth = max_depth - * self.min_samples_split = min_samples_split */ - __Pyx_INCREF(((PyObject *)__pyx_v_criterion)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_criterion)); - __Pyx_GOTREF(__pyx_v_self->criterion); - __Pyx_DECREF(((PyObject *)__pyx_v_self->criterion)); - __pyx_v_self->criterion = __pyx_v_criterion; + __pyx_t_5 = ((__pyx_v_sample_weight != NULL) != 0); + if (__pyx_t_5) { - /* "sklearn/tree/_tree.pyx":227 - * # Parameters - * self.criterion = criterion - * self.max_depth = max_depth # <<<<<<<<<<<<<< - * self.min_samples_split = min_samples_split - * self.min_samples_leaf = min_samples_leaf + /* "sklearn/tree/_tree.pyx":264 + * + * if sample_weight != NULL: + * w = sample_weight[i] # <<<<<<<<<<<<<< + * + * for k in range(n_outputs): */ - __pyx_v_self->max_depth = __pyx_v_max_depth; + __pyx_v_w = (__pyx_v_sample_weight[__pyx_v_i]); + goto __pyx_L7; + } + __pyx_L7:; - /* "sklearn/tree/_tree.pyx":228 - * self.criterion = criterion - * self.max_depth = max_depth - * self.min_samples_split = min_samples_split # <<<<<<<<<<<<<< - * self.min_samples_leaf = min_samples_leaf - * self.min_density = min_density + /* "sklearn/tree/_tree.pyx":266 + * w = sample_weight[i] + * + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * c = y[i * y_stride + k] + * label_count_total[k * label_count_stride + c] += w */ - __pyx_v_self->min_samples_split = __pyx_v_min_samples_split; + __pyx_t_6 = __pyx_v_n_outputs; + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_k = __pyx_t_7; - /* "sklearn/tree/_tree.pyx":229 - * self.max_depth = max_depth - * self.min_samples_split = min_samples_split - * self.min_samples_leaf = min_samples_leaf # <<<<<<<<<<<<<< - * self.min_density = min_density - * self.max_features = max_features + /* "sklearn/tree/_tree.pyx":267 + * + * for k in range(n_outputs): + * c = y[i * y_stride + k] # <<<<<<<<<<<<<< + * label_count_total[k * label_count_stride + c] += w + * */ - __pyx_v_self->min_samples_leaf = __pyx_v_min_samples_leaf; + __pyx_v_c = ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)(__pyx_v_y[((__pyx_v_i * __pyx_v_y_stride) + __pyx_v_k)])); - /* "sklearn/tree/_tree.pyx":230 - * self.min_samples_split = min_samples_split - * self.min_samples_leaf = min_samples_leaf - * self.min_density = min_density # <<<<<<<<<<<<<< - * self.max_features = max_features - * self.find_split_algorithm = find_split_algorithm + /* "sklearn/tree/_tree.pyx":268 + * for k in range(n_outputs): + * c = y[i * y_stride + k] + * label_count_total[k * label_count_stride + c] += w # <<<<<<<<<<<<<< + * + * weighted_n_node_samples += w */ - __pyx_v_self->min_density = __pyx_v_min_density; + __pyx_t_8 = ((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c); + (__pyx_v_label_count_total[__pyx_t_8]) = ((__pyx_v_label_count_total[__pyx_t_8]) + __pyx_v_w); + } - /* "sklearn/tree/_tree.pyx":231 - * self.min_samples_leaf = min_samples_leaf - * self.min_density = min_density - * self.max_features = max_features # <<<<<<<<<<<<<< - * self.find_split_algorithm = find_split_algorithm - * self.random_state = random_state + /* "sklearn/tree/_tree.pyx":270 + * label_count_total[k * label_count_stride + c] += w + * + * weighted_n_node_samples += w # <<<<<<<<<<<<<< + * + * self.weighted_n_node_samples = weighted_n_node_samples */ - __pyx_v_self->max_features = __pyx_v_max_features; + __pyx_v_weighted_n_node_samples = (__pyx_v_weighted_n_node_samples + __pyx_v_w); + } - /* "sklearn/tree/_tree.pyx":232 - * self.min_density = min_density - * self.max_features = max_features - * self.find_split_algorithm = find_split_algorithm # <<<<<<<<<<<<<< - * self.random_state = random_state + /* "sklearn/tree/_tree.pyx":272 + * weighted_n_node_samples += w * + * self.weighted_n_node_samples = weighted_n_node_samples # <<<<<<<<<<<<<< + * + * # Reset to pos=start */ - __pyx_v_self->find_split_algorithm = __pyx_v_find_split_algorithm; + __pyx_v_self->__pyx_base.weighted_n_node_samples = __pyx_v_weighted_n_node_samples; - /* "sklearn/tree/_tree.pyx":233 - * self.max_features = max_features - * self.find_split_algorithm = find_split_algorithm - * self.random_state = random_state # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":275 * - * # Inner structures + * # Reset to pos=start + * self.reset() # <<<<<<<<<<<<<< + * + * cdef void reset(self) nogil: */ - __Pyx_INCREF(__pyx_v_random_state); - __Pyx_GIVEREF(__pyx_v_random_state); - __Pyx_GOTREF(__pyx_v_self->random_state); - __Pyx_DECREF(__pyx_v_self->random_state); - __pyx_v_self->random_state = __pyx_v_random_state; + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.reset(((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self)); - /* "sklearn/tree/_tree.pyx":236 + /* "sklearn/tree/_tree.pyx":226 + * pass * - * # Inner structures - * self.node_count = 0 # <<<<<<<<<<<<<< - * self.capacity = 0 + * cdef void init(self, DOUBLE_t* y, SIZE_t y_stride, # <<<<<<<<<<<<<< + * DOUBLE_t* sample_weight, double weighted_n_samples, + * SIZE_t* samples, SIZE_t start, SIZE_t end) nogil: + */ + + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":277 + * self.reset() * + * cdef void reset(self) nogil: # <<<<<<<<<<<<<< + * """Reset the criterion at pos=start.""" + * self.pos = self.start */ - __pyx_v_self->node_count = 0; - /* "sklearn/tree/_tree.pyx":237 - * # Inner structures - * self.node_count = 0 - * self.capacity = 0 # <<<<<<<<<<<<<< +static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_reset(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_label_count_stride; + double *__pyx_v_label_count_total; + double *__pyx_v_label_count_left; + double *__pyx_v_label_count_right; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + double __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_3; + double *__pyx_t_4; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_5; + + /* "sklearn/tree/_tree.pyx":279 + * cdef void reset(self) nogil: + * """Reset the criterion at pos=start.""" + * self.pos = self.start # <<<<<<<<<<<<<< * - * self.children_left = NULL + * self.weighted_n_left = 0.0 */ - __pyx_v_self->capacity = 0; + __pyx_t_1 = __pyx_v_self->__pyx_base.start; + __pyx_v_self->__pyx_base.pos = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":239 - * self.capacity = 0 + /* "sklearn/tree/_tree.pyx":281 + * self.pos = self.start + * + * self.weighted_n_left = 0.0 # <<<<<<<<<<<<<< + * self.weighted_n_right = self.weighted_n_node_samples * - * self.children_left = NULL # <<<<<<<<<<<<<< - * self.children_right = NULL - * self.feature = NULL */ - __pyx_v_self->children_left = NULL; + __pyx_v_self->__pyx_base.weighted_n_left = 0.0; - /* "sklearn/tree/_tree.pyx":240 + /* "sklearn/tree/_tree.pyx":282 + * + * self.weighted_n_left = 0.0 + * self.weighted_n_right = self.weighted_n_node_samples # <<<<<<<<<<<<<< * - * self.children_left = NULL - * self.children_right = NULL # <<<<<<<<<<<<<< - * self.feature = NULL - * self.threshold = NULL + * cdef SIZE_t n_outputs = self.n_outputs */ - __pyx_v_self->children_right = NULL; + __pyx_t_2 = __pyx_v_self->__pyx_base.weighted_n_node_samples; + __pyx_v_self->__pyx_base.weighted_n_right = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":241 - * self.children_left = NULL - * self.children_right = NULL - * self.feature = NULL # <<<<<<<<<<<<<< - * self.threshold = NULL - * self.value = NULL + /* "sklearn/tree/_tree.pyx":284 + * self.weighted_n_right = self.weighted_n_node_samples + * + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride */ - __pyx_v_self->feature = NULL; + __pyx_t_1 = __pyx_v_self->__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":242 - * self.children_right = NULL - * self.feature = NULL - * self.threshold = NULL # <<<<<<<<<<<<<< - * self.value = NULL - * self.best_error = NULL + /* "sklearn/tree/_tree.pyx":285 + * + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes # <<<<<<<<<<<<<< + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total */ - __pyx_v_self->threshold = NULL; + __pyx_t_3 = __pyx_v_self->n_classes; + __pyx_v_n_classes = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":243 - * self.feature = NULL - * self.threshold = NULL - * self.value = NULL # <<<<<<<<<<<<<< - * self.best_error = NULL - * self.init_error = NULL + /* "sklearn/tree/_tree.pyx":286 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< + * cdef double* label_count_total = self.label_count_total + * cdef double* label_count_left = self.label_count_left */ - __pyx_v_self->value = NULL; + __pyx_t_1 = __pyx_v_self->label_count_stride; + __pyx_v_label_count_stride = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":244 - * self.threshold = NULL - * self.value = NULL - * self.best_error = NULL # <<<<<<<<<<<<<< - * self.init_error = NULL - * self.n_samples = NULL + /* "sklearn/tree/_tree.pyx":287 + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total # <<<<<<<<<<<<<< + * cdef double* label_count_left = self.label_count_left + * cdef double* label_count_right = self.label_count_right */ - __pyx_v_self->best_error = NULL; + __pyx_t_4 = __pyx_v_self->label_count_total; + __pyx_v_label_count_total = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":245 - * self.value = NULL - * self.best_error = NULL - * self.init_error = NULL # <<<<<<<<<<<<<< - * self.n_samples = NULL + /* "sklearn/tree/_tree.pyx":288 + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total + * cdef double* label_count_left = self.label_count_left # <<<<<<<<<<<<<< + * cdef double* label_count_right = self.label_count_right * */ - __pyx_v_self->init_error = NULL; + __pyx_t_4 = __pyx_v_self->label_count_left; + __pyx_v_label_count_left = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":246 - * self.best_error = NULL - * self.init_error = NULL - * self.n_samples = NULL # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":289 + * cdef double* label_count_total = self.label_count_total + * cdef double* label_count_left = self.label_count_left + * cdef double* label_count_right = self.label_count_right # <<<<<<<<<<<<<< * - * def __dealloc__(self): + * cdef SIZE_t k = 0 */ - __pyx_v_self->n_samples = NULL; + __pyx_t_4 = __pyx_v_self->label_count_right; + __pyx_v_label_count_right = __pyx_t_4; - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":291 + * cdef double* label_count_right = self.label_count_right + * + * cdef SIZE_t k = 0 # <<<<<<<<<<<<<< + * + * for k in range(n_outputs): + */ + __pyx_v_k = 0; -/* Python wrapper */ -static void __pyx_pw_7sklearn_4tree_5_tree_4Tree_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_pw_7sklearn_4tree_5_tree_4Tree_3__dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_pf_7sklearn_4tree_5_tree_4Tree_2__dealloc__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); -} + /* "sklearn/tree/_tree.pyx":293 + * cdef SIZE_t k = 0 + * + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * memset(label_count_left, 0, n_classes[k] * sizeof(double)) + * memcpy(label_count_right, label_count_total, + */ + __pyx_t_1 = __pyx_v_n_outputs; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_1; __pyx_t_5+=1) { + __pyx_v_k = __pyx_t_5; -/* "sklearn/tree/_tree.pyx":248 - * self.n_samples = NULL + /* "sklearn/tree/_tree.pyx":294 * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * """Destructor.""" - * # Free all inner structures + * for k in range(n_outputs): + * memset(label_count_left, 0, n_classes[k] * sizeof(double)) # <<<<<<<<<<<<<< + * memcpy(label_count_right, label_count_total, + * n_classes[k] * sizeof(double)) */ + memset(__pyx_v_label_count_left, 0, ((__pyx_v_n_classes[__pyx_v_k]) * (sizeof(double)))); -static void __pyx_pf_7sklearn_4tree_5_tree_4Tree_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__", 0); + /* "sklearn/tree/_tree.pyx":295 + * for k in range(n_outputs): + * memset(label_count_left, 0, n_classes[k] * sizeof(double)) + * memcpy(label_count_right, label_count_total, # <<<<<<<<<<<<<< + * n_classes[k] * sizeof(double)) + * + */ + memcpy(__pyx_v_label_count_right, __pyx_v_label_count_total, ((__pyx_v_n_classes[__pyx_v_k]) * (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":251 - * """Destructor.""" - * # Free all inner structures - * free(self.n_classes) # <<<<<<<<<<<<<< - * free(self.children_left) - * free(self.children_right) + /* "sklearn/tree/_tree.pyx":298 + * n_classes[k] * sizeof(double)) + * + * label_count_total += label_count_stride # <<<<<<<<<<<<<< + * label_count_left += label_count_stride + * label_count_right += label_count_stride */ - free(__pyx_v_self->n_classes); + __pyx_v_label_count_total = (__pyx_v_label_count_total + __pyx_v_label_count_stride); - /* "sklearn/tree/_tree.pyx":252 - * # Free all inner structures - * free(self.n_classes) - * free(self.children_left) # <<<<<<<<<<<<<< - * free(self.children_right) - * free(self.feature) + /* "sklearn/tree/_tree.pyx":299 + * + * label_count_total += label_count_stride + * label_count_left += label_count_stride # <<<<<<<<<<<<<< + * label_count_right += label_count_stride + * */ - free(__pyx_v_self->children_left); + __pyx_v_label_count_left = (__pyx_v_label_count_left + __pyx_v_label_count_stride); - /* "sklearn/tree/_tree.pyx":253 - * free(self.n_classes) - * free(self.children_left) - * free(self.children_right) # <<<<<<<<<<<<<< - * free(self.feature) - * free(self.threshold) - */ - free(__pyx_v_self->children_right); - - /* "sklearn/tree/_tree.pyx":254 - * free(self.children_left) - * free(self.children_right) - * free(self.feature) # <<<<<<<<<<<<<< - * free(self.threshold) - * free(self.value) + /* "sklearn/tree/_tree.pyx":300 + * label_count_total += label_count_stride + * label_count_left += label_count_stride + * label_count_right += label_count_stride # <<<<<<<<<<<<<< + * + * cdef void update(self, SIZE_t new_pos) nogil: */ - free(__pyx_v_self->feature); + __pyx_v_label_count_right = (__pyx_v_label_count_right + __pyx_v_label_count_stride); + } - /* "sklearn/tree/_tree.pyx":255 - * free(self.children_right) - * free(self.feature) - * free(self.threshold) # <<<<<<<<<<<<<< - * free(self.value) - * free(self.best_error) + /* "sklearn/tree/_tree.pyx":277 + * self.reset() + * + * cdef void reset(self) nogil: # <<<<<<<<<<<<<< + * """Reset the criterion at pos=start.""" + * self.pos = self.start + */ + + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":302 + * label_count_right += label_count_stride + * + * cdef void update(self, SIZE_t new_pos) nogil: # <<<<<<<<<<<<<< + * """Update the collected statistics by moving samples[pos:new_pos] from + * the right child to the left child.""" + */ + +static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_update(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_new_pos) { + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_y_stride; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_pos; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_label_count_stride; + CYTHON_UNUSED double *__pyx_v_label_count_total; + double *__pyx_v_label_count_left; + double *__pyx_v_label_count_right; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_label_index; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t __pyx_v_w; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t __pyx_v_diff_w; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_3; + double *__pyx_t_4; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_5; + int __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_8; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_9; + + /* "sklearn/tree/_tree.pyx":305 + * """Update the collected statistics by moving samples[pos:new_pos] from + * the right child to the left child.""" + * cdef DOUBLE_t* y = self.y # <<<<<<<<<<<<<< + * cdef SIZE_t y_stride = self.y_stride + * cdef DOUBLE_t* sample_weight = self.sample_weight */ - free(__pyx_v_self->threshold); + __pyx_t_1 = __pyx_v_self->__pyx_base.y; + __pyx_v_y = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":256 - * free(self.feature) - * free(self.threshold) - * free(self.value) # <<<<<<<<<<<<<< - * free(self.best_error) - * free(self.init_error) + /* "sklearn/tree/_tree.pyx":306 + * the right child to the left child.""" + * cdef DOUBLE_t* y = self.y + * cdef SIZE_t y_stride = self.y_stride # <<<<<<<<<<<<<< + * cdef DOUBLE_t* sample_weight = self.sample_weight + * */ - free(__pyx_v_self->value); + __pyx_t_2 = __pyx_v_self->__pyx_base.y_stride; + __pyx_v_y_stride = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":257 - * free(self.threshold) - * free(self.value) - * free(self.best_error) # <<<<<<<<<<<<<< - * free(self.init_error) - * free(self.n_samples) + /* "sklearn/tree/_tree.pyx":307 + * cdef DOUBLE_t* y = self.y + * cdef SIZE_t y_stride = self.y_stride + * cdef DOUBLE_t* sample_weight = self.sample_weight # <<<<<<<<<<<<<< + * + * cdef SIZE_t* samples = self.samples */ - free(__pyx_v_self->best_error); + __pyx_t_1 = __pyx_v_self->__pyx_base.sample_weight; + __pyx_v_sample_weight = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":258 - * free(self.value) - * free(self.best_error) - * free(self.init_error) # <<<<<<<<<<<<<< - * free(self.n_samples) + /* "sklearn/tree/_tree.pyx":309 + * cdef DOUBLE_t* sample_weight = self.sample_weight + * + * cdef SIZE_t* samples = self.samples # <<<<<<<<<<<<<< + * cdef SIZE_t pos = self.pos * */ - free(__pyx_v_self->init_error); + __pyx_t_3 = __pyx_v_self->__pyx_base.samples; + __pyx_v_samples = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":259 - * free(self.best_error) - * free(self.init_error) - * free(self.n_samples) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":310 * - * def __reduce__(self): + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t pos = self.pos # <<<<<<<<<<<<<< + * + * cdef SIZE_t n_outputs = self.n_outputs */ - free(__pyx_v_self->n_samples); + __pyx_t_2 = __pyx_v_self->__pyx_base.pos; + __pyx_v_pos = __pyx_t_2; - __Pyx_RefNannyFinishContext(); -} + /* "sklearn/tree/_tree.pyx":312 + * cdef SIZE_t pos = self.pos + * + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_2; -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_4__reduce__[] = "Reduce re-implementation, for pickling."; -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_4__reduce__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":313 + * + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes # <<<<<<<<<<<<<< + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total + */ + __pyx_t_3 = __pyx_v_self->n_classes; + __pyx_v_n_classes = __pyx_t_3; + + /* "sklearn/tree/_tree.pyx":314 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< + * cdef double* label_count_total = self.label_count_total + * cdef double* label_count_left = self.label_count_left + */ + __pyx_t_2 = __pyx_v_self->label_count_stride; + __pyx_v_label_count_stride = __pyx_t_2; -/* "sklearn/tree/_tree.pyx":261 - * free(self.n_samples) + /* "sklearn/tree/_tree.pyx":315 + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total # <<<<<<<<<<<<<< + * cdef double* label_count_left = self.label_count_left + * cdef double* label_count_right = self.label_count_right + */ + __pyx_t_4 = __pyx_v_self->label_count_total; + __pyx_v_label_count_total = __pyx_t_4; + + /* "sklearn/tree/_tree.pyx":316 + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total + * cdef double* label_count_left = self.label_count_left # <<<<<<<<<<<<<< + * cdef double* label_count_right = self.label_count_right * - * def __reduce__(self): # <<<<<<<<<<<<<< - * """Reduce re-implementation, for pickling.""" - * return (Tree, (self.n_features, */ + __pyx_t_4 = __pyx_v_self->label_count_left; + __pyx_v_label_count_left = __pyx_t_4; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce__", 0); + /* "sklearn/tree/_tree.pyx":317 + * cdef double* label_count_total = self.label_count_total + * cdef double* label_count_left = self.label_count_left + * cdef double* label_count_right = self.label_count_right # <<<<<<<<<<<<<< + * + * cdef SIZE_t i + */ + __pyx_t_4 = __pyx_v_self->label_count_right; + __pyx_v_label_count_right = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":263 - * def __reduce__(self): - * """Reduce re-implementation, for pickling.""" - * return (Tree, (self.n_features, # <<<<<<<<<<<<<< - * intp_to_ndarray(self.n_classes, self.n_outputs), - * self.n_outputs, + /* "sklearn/tree/_tree.pyx":323 + * cdef SIZE_t k + * cdef SIZE_t label_index + * cdef DOUBLE_t w = 1.0 # <<<<<<<<<<<<<< + * cdef DOUBLE_t diff_w = 0.0 + * */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __pyx_v_w = 1.0; - /* "sklearn/tree/_tree.pyx":264 - * """Reduce re-implementation, for pickling.""" - * return (Tree, (self.n_features, - * intp_to_ndarray(self.n_classes, self.n_outputs), # <<<<<<<<<<<<<< - * self.n_outputs, - * self.criterion, + /* "sklearn/tree/_tree.pyx":324 + * cdef SIZE_t label_index + * cdef DOUBLE_t w = 1.0 + * cdef DOUBLE_t diff_w = 0.0 # <<<<<<<<<<<<<< + * + * # Note: We assume start <= pos < new_pos <= end */ - __pyx_t_2 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(__pyx_v_self->n_classes, __pyx_v_self->n_outputs)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 264; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); + __pyx_v_diff_w = 0.0; - /* "sklearn/tree/_tree.pyx":265 - * return (Tree, (self.n_features, - * intp_to_ndarray(self.n_classes, self.n_outputs), - * self.n_outputs, # <<<<<<<<<<<<<< - * self.criterion, - * self.max_depth, + /* "sklearn/tree/_tree.pyx":328 + * # Note: We assume start <= pos < new_pos <= end + * + * for p in range(pos, new_pos): # <<<<<<<<<<<<<< + * i = samples[p] + * */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_self->n_outputs); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 265; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_v_new_pos; + for (__pyx_t_5 = __pyx_v_pos; __pyx_t_5 < __pyx_t_2; __pyx_t_5+=1) { + __pyx_v_p = __pyx_t_5; - /* "sklearn/tree/_tree.pyx":267 - * self.n_outputs, - * self.criterion, - * self.max_depth, # <<<<<<<<<<<<<< - * self.min_samples_split, - * self.min_samples_leaf, + /* "sklearn/tree/_tree.pyx":329 + * + * for p in range(pos, new_pos): + * i = samples[p] # <<<<<<<<<<<<<< + * + * if sample_weight != NULL: */ - __pyx_t_4 = PyFloat_FromDouble(__pyx_v_self->max_depth); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 267; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_v_i = (__pyx_v_samples[__pyx_v_p]); - /* "sklearn/tree/_tree.pyx":268 - * self.criterion, - * self.max_depth, - * self.min_samples_split, # <<<<<<<<<<<<<< - * self.min_samples_leaf, - * self.min_density, + /* "sklearn/tree/_tree.pyx":331 + * i = samples[p] + * + * if sample_weight != NULL: # <<<<<<<<<<<<<< + * w = sample_weight[i] + * */ - __pyx_t_5 = PyInt_FromLong(__pyx_v_self->min_samples_split); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 268; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = ((__pyx_v_sample_weight != NULL) != 0); + if (__pyx_t_6) { - /* "sklearn/tree/_tree.pyx":269 - * self.max_depth, - * self.min_samples_split, - * self.min_samples_leaf, # <<<<<<<<<<<<<< - * self.min_density, - * self.max_features, + /* "sklearn/tree/_tree.pyx":332 + * + * if sample_weight != NULL: + * w = sample_weight[i] # <<<<<<<<<<<<<< + * + * for k in range(n_outputs): */ - __pyx_t_6 = PyInt_FromLong(__pyx_v_self->min_samples_leaf); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); + __pyx_v_w = (__pyx_v_sample_weight[__pyx_v_i]); + goto __pyx_L5; + } + __pyx_L5:; - /* "sklearn/tree/_tree.pyx":270 - * self.min_samples_split, - * self.min_samples_leaf, - * self.min_density, # <<<<<<<<<<<<<< - * self.max_features, - * self.find_split_algorithm, + /* "sklearn/tree/_tree.pyx":334 + * w = sample_weight[i] + * + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * label_index = (k * label_count_stride + + * y[i * y_stride + k]) */ - __pyx_t_7 = PyFloat_FromDouble(__pyx_v_self->min_density); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); + __pyx_t_7 = __pyx_v_n_outputs; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_k = __pyx_t_8; - /* "sklearn/tree/_tree.pyx":271 - * self.min_samples_leaf, - * self.min_density, - * self.max_features, # <<<<<<<<<<<<<< - * self.find_split_algorithm, - * self.random_state), self.__getstate__()) + /* "sklearn/tree/_tree.pyx":335 + * + * for k in range(n_outputs): + * label_index = (k * label_count_stride + # <<<<<<<<<<<<<< + * y[i * y_stride + k]) + * label_count_left[label_index] += w */ - __pyx_t_8 = PyInt_FromLong(__pyx_v_self->max_features); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); + __pyx_v_label_index = ((__pyx_v_k * __pyx_v_label_count_stride) + ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)(__pyx_v_y[((__pyx_v_i * __pyx_v_y_stride) + __pyx_v_k)]))); - /* "sklearn/tree/_tree.pyx":272 - * self.min_density, - * self.max_features, - * self.find_split_algorithm, # <<<<<<<<<<<<<< - * self.random_state), self.__getstate__()) + /* "sklearn/tree/_tree.pyx":337 + * label_index = (k * label_count_stride + + * y[i * y_stride + k]) + * label_count_left[label_index] += w # <<<<<<<<<<<<<< + * label_count_right[label_index] -= w * */ - __pyx_t_9 = PyInt_FromLong(__pyx_v_self->find_split_algorithm); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); + __pyx_t_9 = __pyx_v_label_index; + (__pyx_v_label_count_left[__pyx_t_9]) = ((__pyx_v_label_count_left[__pyx_t_9]) + __pyx_v_w); - /* "sklearn/tree/_tree.pyx":273 - * self.max_features, - * self.find_split_algorithm, - * self.random_state), self.__getstate__()) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":338 + * y[i * y_stride + k]) + * label_count_left[label_index] += w + * label_count_right[label_index] -= w # <<<<<<<<<<<<<< * - * def __getstate__(self): + * diff_w += w */ - __pyx_t_10 = PyTuple_New(11); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_10, 2, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_self->criterion)); - PyTuple_SET_ITEM(__pyx_t_10, 3, ((PyObject *)__pyx_v_self->criterion)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self->criterion)); - PyTuple_SET_ITEM(__pyx_t_10, 4, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_10, 5, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_10, 6, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_10, 7, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_10, 8, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_8); - PyTuple_SET_ITEM(__pyx_t_10, 9, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_9); - __Pyx_INCREF(__pyx_v_self->random_state); - PyTuple_SET_ITEM(__pyx_t_10, 10, __pyx_v_self->random_state); - __Pyx_GIVEREF(__pyx_v_self->random_state); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_7 = 0; - __pyx_t_8 = 0; - __pyx_t_9 = 0; - __pyx_t_9 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s____getstate__); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_8 = PyObject_Call(__pyx_t_9, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = PyTuple_New(3); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_Tree))); - PyTuple_SET_ITEM(__pyx_t_9, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_Tree))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_Tree))); - PyTuple_SET_ITEM(__pyx_t_9, 1, ((PyObject *)__pyx_t_10)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_10)); - PyTuple_SET_ITEM(__pyx_t_9, 2, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_8); - __pyx_t_10 = 0; - __pyx_t_8 = 0; - __pyx_r = ((PyObject *)__pyx_t_9); - __pyx_t_9 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_6__getstate__[] = "Getstate re-implementation, for pickling."; -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getstate__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_6__getstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_t_9 = __pyx_v_label_index; + (__pyx_v_label_count_right[__pyx_t_9]) = ((__pyx_v_label_count_right[__pyx_t_9]) - __pyx_v_w); + } -/* "sklearn/tree/_tree.pyx":275 - * self.random_state), self.__getstate__()) + /* "sklearn/tree/_tree.pyx":340 + * label_count_right[label_index] -= w * - * def __getstate__(self): # <<<<<<<<<<<<<< - * """Getstate re-implementation, for pickling.""" - * d = {} + * diff_w += w # <<<<<<<<<<<<<< + * + * self.weighted_n_left += diff_w */ + __pyx_v_diff_w = (__pyx_v_diff_w + __pyx_v_w); + } -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_6__getstate__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_v_d = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getstate__", 0); - - /* "sklearn/tree/_tree.pyx":277 - * def __getstate__(self): - * """Getstate re-implementation, for pickling.""" - * d = {} # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":342 + * diff_w += w + * + * self.weighted_n_left += diff_w # <<<<<<<<<<<<<< + * self.weighted_n_right -= diff_w * - * d["node_count"] = self.node_count */ - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_v_d = __pyx_t_1; - __pyx_t_1 = 0; + __pyx_v_self->__pyx_base.weighted_n_left = (__pyx_v_self->__pyx_base.weighted_n_left + __pyx_v_diff_w); - /* "sklearn/tree/_tree.pyx":279 - * d = {} + /* "sklearn/tree/_tree.pyx":343 * - * d["node_count"] = self.node_count # <<<<<<<<<<<<<< - * d["capacity"] = self.capacity - * d["children_left"] = intp_to_ndarray(self.children_left, self.capacity) + * self.weighted_n_left += diff_w + * self.weighted_n_right -= diff_w # <<<<<<<<<<<<<< + * + * self.pos = new_pos */ - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->node_count); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(((PyObject *)__pyx_v_d), ((PyObject *)__pyx_n_s__node_count), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->__pyx_base.weighted_n_right = (__pyx_v_self->__pyx_base.weighted_n_right - __pyx_v_diff_w); - /* "sklearn/tree/_tree.pyx":280 + /* "sklearn/tree/_tree.pyx":345 + * self.weighted_n_right -= diff_w * - * d["node_count"] = self.node_count - * d["capacity"] = self.capacity # <<<<<<<<<<<<<< - * d["children_left"] = intp_to_ndarray(self.children_left, self.capacity) - * d["children_right"] = intp_to_ndarray(self.children_right, self.capacity) + * self.pos = new_pos # <<<<<<<<<<<<<< + * + * cdef double node_impurity(self) nogil: */ - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->capacity); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(((PyObject *)__pyx_v_d), ((PyObject *)__pyx_n_s__capacity), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->__pyx_base.pos = __pyx_v_new_pos; - /* "sklearn/tree/_tree.pyx":281 - * d["node_count"] = self.node_count - * d["capacity"] = self.capacity - * d["children_left"] = intp_to_ndarray(self.children_left, self.capacity) # <<<<<<<<<<<<<< - * d["children_right"] = intp_to_ndarray(self.children_right, self.capacity) - * d["feature"] = intp_to_ndarray(self.feature, self.capacity) + /* "sklearn/tree/_tree.pyx":302 + * label_count_right += label_count_stride + * + * cdef void update(self, SIZE_t new_pos) nogil: # <<<<<<<<<<<<<< + * """Update the collected statistics by moving samples[pos:new_pos] from + * the right child to the left child.""" */ - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(__pyx_v_self->children_left, __pyx_v_self->capacity)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(((PyObject *)__pyx_v_d), ((PyObject *)__pyx_n_s__children_left), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/tree/_tree.pyx":282 - * d["capacity"] = self.capacity - * d["children_left"] = intp_to_ndarray(self.children_left, self.capacity) - * d["children_right"] = intp_to_ndarray(self.children_right, self.capacity) # <<<<<<<<<<<<<< - * d["feature"] = intp_to_ndarray(self.feature, self.capacity) - * d["threshold"] = doublep_to_ndarray(self.threshold, self.capacity) - */ - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(__pyx_v_self->children_right, __pyx_v_self->capacity)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(((PyObject *)__pyx_v_d), ((PyObject *)__pyx_n_s__children_right), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /* function exit code */ +} - /* "sklearn/tree/_tree.pyx":283 - * d["children_left"] = intp_to_ndarray(self.children_left, self.capacity) - * d["children_right"] = intp_to_ndarray(self.children_right, self.capacity) - * d["feature"] = intp_to_ndarray(self.feature, self.capacity) # <<<<<<<<<<<<<< - * d["threshold"] = doublep_to_ndarray(self.threshold, self.capacity) - * d["value"] = doublep_to_ndarray(self.value, self.capacity * self.value_stride) +/* "sklearn/tree/_tree.pyx":347 + * self.pos = new_pos + * + * cdef double node_impurity(self) nogil: # <<<<<<<<<<<<<< + * pass + * */ - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(__pyx_v_self->feature, __pyx_v_self->capacity)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(((PyObject *)__pyx_v_d), ((PyObject *)__pyx_n_s__feature), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/tree/_tree.pyx":284 - * d["children_right"] = intp_to_ndarray(self.children_right, self.capacity) - * d["feature"] = intp_to_ndarray(self.feature, self.capacity) - * d["threshold"] = doublep_to_ndarray(self.threshold, self.capacity) # <<<<<<<<<<<<<< - * d["value"] = doublep_to_ndarray(self.value, self.capacity * self.value_stride) - * d["best_error"] = doublep_to_ndarray(self.best_error, self.capacity) - */ - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_doublep_to_ndarray(__pyx_v_self->threshold, __pyx_v_self->capacity)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(((PyObject *)__pyx_v_d), ((PyObject *)__pyx_n_s__threshold), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; +static double __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_node_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self) { + double __pyx_r; - /* "sklearn/tree/_tree.pyx":285 - * d["feature"] = intp_to_ndarray(self.feature, self.capacity) - * d["threshold"] = doublep_to_ndarray(self.threshold, self.capacity) - * d["value"] = doublep_to_ndarray(self.value, self.capacity * self.value_stride) # <<<<<<<<<<<<<< - * d["best_error"] = doublep_to_ndarray(self.best_error, self.capacity) - * d["init_error"] = doublep_to_ndarray(self.init_error, self.capacity) + /* function exit code */ + __pyx_r = 0; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":350 + * pass + * + * cdef void children_impurity(self, double* impurity_left, # <<<<<<<<<<<<<< + * double* impurity_right) nogil: + * pass */ - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_doublep_to_ndarray(__pyx_v_self->value, (__pyx_v_self->capacity * __pyx_v_self->value_stride))); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(((PyObject *)__pyx_v_d), ((PyObject *)__pyx_n_s__value), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/tree/_tree.pyx":286 - * d["threshold"] = doublep_to_ndarray(self.threshold, self.capacity) - * d["value"] = doublep_to_ndarray(self.value, self.capacity * self.value_stride) - * d["best_error"] = doublep_to_ndarray(self.best_error, self.capacity) # <<<<<<<<<<<<<< - * d["init_error"] = doublep_to_ndarray(self.init_error, self.capacity) - * d["n_samples"] = intp_to_ndarray(self.n_samples, self.capacity) +static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_children_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, CYTHON_UNUSED double *__pyx_v_impurity_left, CYTHON_UNUSED double *__pyx_v_impurity_right) { + + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":354 + * pass + * + * cdef void node_value(self, double* dest) nogil: # <<<<<<<<<<<<<< + * """Compute the node value of samples[start:end] into dest.""" + * cdef SIZE_t n_outputs = self.n_outputs + */ + +static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_node_value(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, double *__pyx_v_dest) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_label_count_stride; + double *__pyx_v_label_count_total; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_2; + double *__pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_4; + + /* "sklearn/tree/_tree.pyx":356 + * cdef void node_value(self, double* dest) nogil: + * """Compute the node value of samples[start:end] into dest.""" + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":357 + * """Compute the node value of samples[start:end] into dest.""" + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes # <<<<<<<<<<<<<< + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total + */ + __pyx_t_2 = __pyx_v_self->n_classes; + __pyx_v_n_classes = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":358 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< + * cdef double* label_count_total = self.label_count_total + * cdef SIZE_t k + */ + __pyx_t_1 = __pyx_v_self->label_count_stride; + __pyx_v_label_count_stride = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":359 + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total # <<<<<<<<<<<<<< + * cdef SIZE_t k + * + */ + __pyx_t_3 = __pyx_v_self->label_count_total; + __pyx_v_label_count_total = __pyx_t_3; + + /* "sklearn/tree/_tree.pyx":362 + * cdef SIZE_t k + * + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * memcpy(dest, label_count_total, n_classes[k] * sizeof(double)) + * dest += label_count_stride */ - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_doublep_to_ndarray(__pyx_v_self->best_error, __pyx_v_self->capacity)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(((PyObject *)__pyx_v_d), ((PyObject *)__pyx_n_s__best_error), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __pyx_v_n_outputs; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_1; __pyx_t_4+=1) { + __pyx_v_k = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":287 - * d["value"] = doublep_to_ndarray(self.value, self.capacity * self.value_stride) - * d["best_error"] = doublep_to_ndarray(self.best_error, self.capacity) - * d["init_error"] = doublep_to_ndarray(self.init_error, self.capacity) # <<<<<<<<<<<<<< - * d["n_samples"] = intp_to_ndarray(self.n_samples, self.capacity) + /* "sklearn/tree/_tree.pyx":363 * + * for k in range(n_outputs): + * memcpy(dest, label_count_total, n_classes[k] * sizeof(double)) # <<<<<<<<<<<<<< + * dest += label_count_stride + * label_count_total += label_count_stride */ - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_doublep_to_ndarray(__pyx_v_self->init_error, __pyx_v_self->capacity)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(((PyObject *)__pyx_v_d), ((PyObject *)__pyx_n_s__init_error), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + memcpy(__pyx_v_dest, __pyx_v_label_count_total, ((__pyx_v_n_classes[__pyx_v_k]) * (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":288 - * d["best_error"] = doublep_to_ndarray(self.best_error, self.capacity) - * d["init_error"] = doublep_to_ndarray(self.init_error, self.capacity) - * d["n_samples"] = intp_to_ndarray(self.n_samples, self.capacity) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":364 + * for k in range(n_outputs): + * memcpy(dest, label_count_total, n_classes[k] * sizeof(double)) + * dest += label_count_stride # <<<<<<<<<<<<<< + * label_count_total += label_count_stride * - * return d */ - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(__pyx_v_self->n_samples, __pyx_v_self->capacity)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(((PyObject *)__pyx_v_d), ((PyObject *)__pyx_n_s__n_samples), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_dest = (__pyx_v_dest + __pyx_v_label_count_stride); - /* "sklearn/tree/_tree.pyx":290 - * d["n_samples"] = intp_to_ndarray(self.n_samples, self.capacity) + /* "sklearn/tree/_tree.pyx":365 + * memcpy(dest, label_count_total, n_classes[k] * sizeof(double)) + * dest += label_count_stride + * label_count_total += label_count_stride # <<<<<<<<<<<<<< * - * return d # <<<<<<<<<<<<<< * - * def __setstate__(self, d): */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_d)); - __pyx_r = ((PyObject *)__pyx_v_d); - goto __pyx_L0; + __pyx_v_label_count_total = (__pyx_v_label_count_total + __pyx_v_label_count_stride); + } - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_d); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":354 + * pass + * + * cdef void node_value(self, double* dest) nogil: # <<<<<<<<<<<<<< + * """Compute the node value of samples[start:end] into dest.""" + * cdef SIZE_t n_outputs = self.n_outputs + */ -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d); /*proto*/ -static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_8__setstate__[] = "Setstate re-implementation, for unpickling."; -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_8__setstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_d)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; + /* function exit code */ } -/* "sklearn/tree/_tree.pyx":292 - * return d +/* "sklearn/tree/_tree.pyx":382 + * cross-entropy = - \sum_{k=0}^{K-1} pmk log(pmk) + * """ + * cdef double node_impurity(self) nogil: # <<<<<<<<<<<<<< + * """Evaluate the impurity of the current node, i.e. the impurity of + * samples[start:end].""" + */ + +static double __pyx_f_7sklearn_4tree_5_tree_7Entropy_node_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_Entropy *__pyx_v_self) { + double __pyx_v_weighted_n_node_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_label_count_stride; + double *__pyx_v_label_count_total; + double __pyx_v_entropy; + double __pyx_v_total; + double __pyx_v_tmp; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_c; + double __pyx_r; + double __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_3; + double *__pyx_t_4; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_5; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; + int __pyx_t_8; + + /* "sklearn/tree/_tree.pyx":385 + * """Evaluate the impurity of the current node, i.e. the impurity of + * samples[start:end].""" + * cdef double weighted_n_node_samples = self.weighted_n_node_samples # <<<<<<<<<<<<<< * - * def __setstate__(self, d): # <<<<<<<<<<<<<< - * """Setstate re-implementation, for unpickling.""" - * self.resize(d["capacity"]) + * cdef SIZE_t n_outputs = self.n_outputs */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.weighted_n_node_samples; + __pyx_v_weighted_n_node_samples = __pyx_t_1; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_8__setstate__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_d) { - int *__pyx_v_children_left; - int *__pyx_v_children_right; - int *__pyx_v_feature; - double *__pyx_v_threshold; - double *__pyx_v_value; - double *__pyx_v_best_error; - double *__pyx_v_init_error; - int *__pyx_v_n_samples; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_resize __pyx_t_3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate__", 0); + /* "sklearn/tree/_tree.pyx":387 + * cdef double weighted_n_node_samples = self.weighted_n_node_samples + * + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":294 - * def __setstate__(self, d): - * """Setstate re-implementation, for unpickling.""" - * self.resize(d["capacity"]) # <<<<<<<<<<<<<< - * self.node_count = d["node_count"] + /* "sklearn/tree/_tree.pyx":388 * + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes # <<<<<<<<<<<<<< + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total */ - __pyx_t_1 = PyObject_GetItem(__pyx_v_d, ((PyObject *)__pyx_n_s__capacity)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3.__pyx_n = 1; - __pyx_t_3.capacity = __pyx_t_2; - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->resize(__pyx_v_self, &__pyx_t_3); + __pyx_t_3 = __pyx_v_self->__pyx_base.n_classes; + __pyx_v_n_classes = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":295 - * """Setstate re-implementation, for unpickling.""" - * self.resize(d["capacity"]) - * self.node_count = d["node_count"] # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":389 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< + * cdef double* label_count_total = self.label_count_total * - * cdef int* children_left = ( d["children_left"]).data */ - __pyx_t_1 = PyObject_GetItem(__pyx_v_d, ((PyObject *)__pyx_n_s__node_count)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 295; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 295; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_self->node_count = __pyx_t_2; + __pyx_t_2 = __pyx_v_self->__pyx_base.label_count_stride; + __pyx_v_label_count_stride = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":297 - * self.node_count = d["node_count"] + /* "sklearn/tree/_tree.pyx":390 + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total # <<<<<<<<<<<<<< * - * cdef int* children_left = ( d["children_left"]).data # <<<<<<<<<<<<<< - * cdef int* children_right = ( d["children_right"]).data - * cdef int* feature = ( d["feature"]).data + * cdef double entropy = 0.0 */ - __pyx_t_1 = PyObject_GetItem(__pyx_v_d, ((PyObject *)__pyx_n_s__children_left)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_children_left = ((int *)((PyArrayObject *)__pyx_t_1)->data); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_4 = __pyx_v_self->__pyx_base.label_count_total; + __pyx_v_label_count_total = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":298 + /* "sklearn/tree/_tree.pyx":392 + * cdef double* label_count_total = self.label_count_total * - * cdef int* children_left = ( d["children_left"]).data - * cdef int* children_right = ( d["children_right"]).data # <<<<<<<<<<<<<< - * cdef int* feature = ( d["feature"]).data - * cdef double* threshold = ( d["threshold"]).data + * cdef double entropy = 0.0 # <<<<<<<<<<<<<< + * cdef double total = 0.0 + * cdef double tmp */ - __pyx_t_1 = PyObject_GetItem(__pyx_v_d, ((PyObject *)__pyx_n_s__children_right)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_children_right = ((int *)((PyArrayObject *)__pyx_t_1)->data); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_entropy = 0.0; - /* "sklearn/tree/_tree.pyx":299 - * cdef int* children_left = ( d["children_left"]).data - * cdef int* children_right = ( d["children_right"]).data - * cdef int* feature = ( d["feature"]).data # <<<<<<<<<<<<<< - * cdef double* threshold = ( d["threshold"]).data - * cdef double* value = ( d["value"]).data + /* "sklearn/tree/_tree.pyx":393 + * + * cdef double entropy = 0.0 + * cdef double total = 0.0 # <<<<<<<<<<<<<< + * cdef double tmp + * cdef SIZE_t k */ - __pyx_t_1 = PyObject_GetItem(__pyx_v_d, ((PyObject *)__pyx_n_s__feature)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_feature = ((int *)((PyArrayObject *)__pyx_t_1)->data); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_total = 0.0; - /* "sklearn/tree/_tree.pyx":300 - * cdef int* children_right = ( d["children_right"]).data - * cdef int* feature = ( d["feature"]).data - * cdef double* threshold = ( d["threshold"]).data # <<<<<<<<<<<<<< - * cdef double* value = ( d["value"]).data - * cdef double* best_error = ( d["best_error"]).data + /* "sklearn/tree/_tree.pyx":398 + * cdef SIZE_t c + * + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * entropy = 0.0 + * */ - __pyx_t_1 = PyObject_GetItem(__pyx_v_d, ((PyObject *)__pyx_n_s__threshold)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_threshold = ((double *)((PyArrayObject *)__pyx_t_1)->data); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_2 = __pyx_v_n_outputs; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_2; __pyx_t_5+=1) { + __pyx_v_k = __pyx_t_5; - /* "sklearn/tree/_tree.pyx":301 - * cdef int* feature = ( d["feature"]).data - * cdef double* threshold = ( d["threshold"]).data - * cdef double* value = ( d["value"]).data # <<<<<<<<<<<<<< - * cdef double* best_error = ( d["best_error"]).data - * cdef double* init_error = ( d["init_error"]).data + /* "sklearn/tree/_tree.pyx":399 + * + * for k in range(n_outputs): + * entropy = 0.0 # <<<<<<<<<<<<<< + * + * for c in range(n_classes[k]): */ - __pyx_t_1 = PyObject_GetItem(__pyx_v_d, ((PyObject *)__pyx_n_s__value)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_value = ((double *)((PyArrayObject *)__pyx_t_1)->data); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_entropy = 0.0; - /* "sklearn/tree/_tree.pyx":302 - * cdef double* threshold = ( d["threshold"]).data - * cdef double* value = ( d["value"]).data - * cdef double* best_error = ( d["best_error"]).data # <<<<<<<<<<<<<< - * cdef double* init_error = ( d["init_error"]).data - * cdef int* n_samples = ( d["n_samples"]).data + /* "sklearn/tree/_tree.pyx":401 + * entropy = 0.0 + * + * for c in range(n_classes[k]): # <<<<<<<<<<<<<< + * tmp = label_count_total[c] + * if tmp > 0.0: */ - __pyx_t_1 = PyObject_GetItem(__pyx_v_d, ((PyObject *)__pyx_n_s__best_error)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_best_error = ((double *)((PyArrayObject *)__pyx_t_1)->data); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_6 = (__pyx_v_n_classes[__pyx_v_k]); + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_c = __pyx_t_7; - /* "sklearn/tree/_tree.pyx":303 - * cdef double* value = ( d["value"]).data - * cdef double* best_error = ( d["best_error"]).data - * cdef double* init_error = ( d["init_error"]).data # <<<<<<<<<<<<<< - * cdef int* n_samples = ( d["n_samples"]).data + /* "sklearn/tree/_tree.pyx":402 * + * for c in range(n_classes[k]): + * tmp = label_count_total[c] # <<<<<<<<<<<<<< + * if tmp > 0.0: + * tmp /= weighted_n_node_samples */ - __pyx_t_1 = PyObject_GetItem(__pyx_v_d, ((PyObject *)__pyx_n_s__init_error)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 303; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_init_error = ((double *)((PyArrayObject *)__pyx_t_1)->data); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_tmp = (__pyx_v_label_count_total[__pyx_v_c]); + + /* "sklearn/tree/_tree.pyx":403 + * for c in range(n_classes[k]): + * tmp = label_count_total[c] + * if tmp > 0.0: # <<<<<<<<<<<<<< + * tmp /= weighted_n_node_samples + * entropy -= tmp * log(tmp) + */ + __pyx_t_8 = ((__pyx_v_tmp > 0.0) != 0); + if (__pyx_t_8) { - /* "sklearn/tree/_tree.pyx":304 - * cdef double* best_error = ( d["best_error"]).data - * cdef double* init_error = ( d["init_error"]).data - * cdef int* n_samples = ( d["n_samples"]).data # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":404 + * tmp = label_count_total[c] + * if tmp > 0.0: + * tmp /= weighted_n_node_samples # <<<<<<<<<<<<<< + * entropy -= tmp * log(tmp) * - * memcpy(self.children_left, children_left, self.capacity * sizeof(int)) */ - __pyx_t_1 = PyObject_GetItem(__pyx_v_d, ((PyObject *)__pyx_n_s__n_samples)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 304; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_n_samples = ((int *)((PyArrayObject *)__pyx_t_1)->data); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_tmp = (__pyx_v_tmp / __pyx_v_weighted_n_node_samples); - /* "sklearn/tree/_tree.pyx":306 - * cdef int* n_samples = ( d["n_samples"]).data + /* "sklearn/tree/_tree.pyx":405 + * if tmp > 0.0: + * tmp /= weighted_n_node_samples + * entropy -= tmp * log(tmp) # <<<<<<<<<<<<<< * - * memcpy(self.children_left, children_left, self.capacity * sizeof(int)) # <<<<<<<<<<<<<< - * memcpy(self.children_right, children_right, self.capacity * sizeof(int)) - * memcpy(self.feature, feature, self.capacity * sizeof(int)) + * total += entropy */ - memcpy(__pyx_v_self->children_left, __pyx_v_children_left, (__pyx_v_self->capacity * (sizeof(int)))); + __pyx_v_entropy = (__pyx_v_entropy - (__pyx_v_tmp * __pyx_f_7sklearn_4tree_5_tree_log(__pyx_v_tmp))); + goto __pyx_L7; + } + __pyx_L7:; + } - /* "sklearn/tree/_tree.pyx":307 + /* "sklearn/tree/_tree.pyx":407 + * entropy -= tmp * log(tmp) + * + * total += entropy # <<<<<<<<<<<<<< + * label_count_total += label_count_stride * - * memcpy(self.children_left, children_left, self.capacity * sizeof(int)) - * memcpy(self.children_right, children_right, self.capacity * sizeof(int)) # <<<<<<<<<<<<<< - * memcpy(self.feature, feature, self.capacity * sizeof(int)) - * memcpy(self.threshold, threshold, self.capacity * sizeof(double)) */ - memcpy(__pyx_v_self->children_right, __pyx_v_children_right, (__pyx_v_self->capacity * (sizeof(int)))); + __pyx_v_total = (__pyx_v_total + __pyx_v_entropy); - /* "sklearn/tree/_tree.pyx":308 - * memcpy(self.children_left, children_left, self.capacity * sizeof(int)) - * memcpy(self.children_right, children_right, self.capacity * sizeof(int)) - * memcpy(self.feature, feature, self.capacity * sizeof(int)) # <<<<<<<<<<<<<< - * memcpy(self.threshold, threshold, self.capacity * sizeof(double)) - * memcpy(self.value, value, self.capacity * self.value_stride * sizeof(double)) + /* "sklearn/tree/_tree.pyx":408 + * + * total += entropy + * label_count_total += label_count_stride # <<<<<<<<<<<<<< + * + * return total / n_outputs */ - memcpy(__pyx_v_self->feature, __pyx_v_feature, (__pyx_v_self->capacity * (sizeof(int)))); + __pyx_v_label_count_total = (__pyx_v_label_count_total + __pyx_v_label_count_stride); + } - /* "sklearn/tree/_tree.pyx":309 - * memcpy(self.children_right, children_right, self.capacity * sizeof(int)) - * memcpy(self.feature, feature, self.capacity * sizeof(int)) - * memcpy(self.threshold, threshold, self.capacity * sizeof(double)) # <<<<<<<<<<<<<< - * memcpy(self.value, value, self.capacity * self.value_stride * sizeof(double)) - * memcpy(self.best_error, best_error, self.capacity * sizeof(double)) + /* "sklearn/tree/_tree.pyx":410 + * label_count_total += label_count_stride + * + * return total / n_outputs # <<<<<<<<<<<<<< + * + * cdef void children_impurity(self, double* impurity_left, */ - memcpy(__pyx_v_self->threshold, __pyx_v_threshold, (__pyx_v_self->capacity * (sizeof(double)))); + __pyx_r = (__pyx_v_total / __pyx_v_n_outputs); + goto __pyx_L0; - /* "sklearn/tree/_tree.pyx":310 - * memcpy(self.feature, feature, self.capacity * sizeof(int)) - * memcpy(self.threshold, threshold, self.capacity * sizeof(double)) - * memcpy(self.value, value, self.capacity * self.value_stride * sizeof(double)) # <<<<<<<<<<<<<< - * memcpy(self.best_error, best_error, self.capacity * sizeof(double)) - * memcpy(self.init_error, init_error, self.capacity * sizeof(double)) + /* "sklearn/tree/_tree.pyx":382 + * cross-entropy = - \sum_{k=0}^{K-1} pmk log(pmk) + * """ + * cdef double node_impurity(self) nogil: # <<<<<<<<<<<<<< + * """Evaluate the impurity of the current node, i.e. the impurity of + * samples[start:end].""" */ - memcpy(__pyx_v_self->value, __pyx_v_value, ((__pyx_v_self->capacity * __pyx_v_self->value_stride) * (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":311 - * memcpy(self.threshold, threshold, self.capacity * sizeof(double)) - * memcpy(self.value, value, self.capacity * self.value_stride * sizeof(double)) - * memcpy(self.best_error, best_error, self.capacity * sizeof(double)) # <<<<<<<<<<<<<< - * memcpy(self.init_error, init_error, self.capacity * sizeof(double)) - * memcpy(self.n_samples, n_samples, self.capacity * sizeof(int)) + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":412 + * return total / n_outputs + * + * cdef void children_impurity(self, double* impurity_left, # <<<<<<<<<<<<<< + * double* impurity_right) nogil: + * """Evaluate the impurity in children nodes, i.e. the impurity of the + */ + +static void __pyx_f_7sklearn_4tree_5_tree_7Entropy_children_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_Entropy *__pyx_v_self, double *__pyx_v_impurity_left, double *__pyx_v_impurity_right) { + CYTHON_UNUSED double __pyx_v_weighted_n_node_samples; + double __pyx_v_weighted_n_left; + double __pyx_v_weighted_n_right; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_label_count_stride; + double *__pyx_v_label_count_left; + double *__pyx_v_label_count_right; + double __pyx_v_entropy_left; + double __pyx_v_entropy_right; + double __pyx_v_total_left; + double __pyx_v_total_right; + double __pyx_v_tmp; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_c; + double __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_3; + double *__pyx_t_4; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_5; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; + int __pyx_t_8; + + /* "sklearn/tree/_tree.pyx":417 + * left child (samples[start:pos]) and the impurity the right child + * (samples[pos:end]).""" + * cdef double weighted_n_node_samples = self.weighted_n_node_samples # <<<<<<<<<<<<<< + * cdef double weighted_n_left = self.weighted_n_left + * cdef double weighted_n_right = self.weighted_n_right */ - memcpy(__pyx_v_self->best_error, __pyx_v_best_error, (__pyx_v_self->capacity * (sizeof(double)))); + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.weighted_n_node_samples; + __pyx_v_weighted_n_node_samples = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":312 - * memcpy(self.value, value, self.capacity * self.value_stride * sizeof(double)) - * memcpy(self.best_error, best_error, self.capacity * sizeof(double)) - * memcpy(self.init_error, init_error, self.capacity * sizeof(double)) # <<<<<<<<<<<<<< - * memcpy(self.n_samples, n_samples, self.capacity * sizeof(int)) + /* "sklearn/tree/_tree.pyx":418 + * (samples[pos:end]).""" + * cdef double weighted_n_node_samples = self.weighted_n_node_samples + * cdef double weighted_n_left = self.weighted_n_left # <<<<<<<<<<<<<< + * cdef double weighted_n_right = self.weighted_n_right * */ - memcpy(__pyx_v_self->init_error, __pyx_v_init_error, (__pyx_v_self->capacity * (sizeof(double)))); + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.weighted_n_left; + __pyx_v_weighted_n_left = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":313 - * memcpy(self.best_error, best_error, self.capacity * sizeof(double)) - * memcpy(self.init_error, init_error, self.capacity * sizeof(double)) - * memcpy(self.n_samples, n_samples, self.capacity * sizeof(int)) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":419 + * cdef double weighted_n_node_samples = self.weighted_n_node_samples + * cdef double weighted_n_left = self.weighted_n_left + * cdef double weighted_n_right = self.weighted_n_right # <<<<<<<<<<<<<< * - * cdef void resize(self, int capacity=-1): + * cdef SIZE_t n_outputs = self.n_outputs */ - memcpy(__pyx_v_self->n_samples, __pyx_v_n_samples, (__pyx_v_self->capacity * (sizeof(int)))); + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.weighted_n_right; + __pyx_v_weighted_n_right = __pyx_t_1; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.__setstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":421 + * cdef double weighted_n_right = self.weighted_n_right + * + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_2; -/* "sklearn/tree/_tree.pyx":315 - * memcpy(self.n_samples, n_samples, self.capacity * sizeof(int)) + /* "sklearn/tree/_tree.pyx":422 * - * cdef void resize(self, int capacity=-1): # <<<<<<<<<<<<<< - * """Resize all inner arrays to `capacity`, if < 0 double capacity.""" - * if capacity == self.capacity: + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes # <<<<<<<<<<<<<< + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_left = self.label_count_left */ + __pyx_t_3 = __pyx_v_self->__pyx_base.n_classes; + __pyx_v_n_classes = __pyx_t_3; -static void __pyx_f_7sklearn_4tree_5_tree_4Tree_resize(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_resize *__pyx_optional_args) { - int __pyx_v_capacity = ((int)-1); - int *__pyx_v_tmp_children_left; - int *__pyx_v_tmp_children_right; - int *__pyx_v_tmp_feature; - double *__pyx_v_tmp_threshold; - double *__pyx_v_tmp_value; - double *__pyx_v_tmp_best_error; - double *__pyx_v_tmp_init_error; - int *__pyx_v_tmp_n_samples; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("resize", 0); - if (__pyx_optional_args) { - if (__pyx_optional_args->__pyx_n > 0) { - __pyx_v_capacity = __pyx_optional_args->capacity; - } - } + /* "sklearn/tree/_tree.pyx":423 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< + * cdef double* label_count_left = self.label_count_left + * cdef double* label_count_right = self.label_count_right + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.label_count_stride; + __pyx_v_label_count_stride = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":317 - * cdef void resize(self, int capacity=-1): - * """Resize all inner arrays to `capacity`, if < 0 double capacity.""" - * if capacity == self.capacity: # <<<<<<<<<<<<<< - * return + /* "sklearn/tree/_tree.pyx":424 + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_left = self.label_count_left # <<<<<<<<<<<<<< + * cdef double* label_count_right = self.label_count_right * */ - __pyx_t_1 = (__pyx_v_capacity == __pyx_v_self->capacity); - if (__pyx_t_1) { + __pyx_t_4 = __pyx_v_self->__pyx_base.label_count_left; + __pyx_v_label_count_left = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":318 - * """Resize all inner arrays to `capacity`, if < 0 double capacity.""" - * if capacity == self.capacity: - * return # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":425 + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_left = self.label_count_left + * cdef double* label_count_right = self.label_count_right # <<<<<<<<<<<<<< * - * if capacity < 0: + * cdef double entropy_left = 0.0 */ - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; + __pyx_t_4 = __pyx_v_self->__pyx_base.label_count_right; + __pyx_v_label_count_right = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":320 - * return + /* "sklearn/tree/_tree.pyx":427 + * cdef double* label_count_right = self.label_count_right * - * if capacity < 0: # <<<<<<<<<<<<<< - * if self.capacity <= 0: - * capacity = 3 + * cdef double entropy_left = 0.0 # <<<<<<<<<<<<<< + * cdef double entropy_right = 0.0 + * cdef double total_left = 0.0 */ - __pyx_t_1 = (__pyx_v_capacity < 0); - if (__pyx_t_1) { + __pyx_v_entropy_left = 0.0; - /* "sklearn/tree/_tree.pyx":321 + /* "sklearn/tree/_tree.pyx":428 * - * if capacity < 0: - * if self.capacity <= 0: # <<<<<<<<<<<<<< - * capacity = 3 - * else: + * cdef double entropy_left = 0.0 + * cdef double entropy_right = 0.0 # <<<<<<<<<<<<<< + * cdef double total_left = 0.0 + * cdef double total_right = 0.0 */ - __pyx_t_1 = (__pyx_v_self->capacity <= 0); - if (__pyx_t_1) { + __pyx_v_entropy_right = 0.0; - /* "sklearn/tree/_tree.pyx":322 - * if capacity < 0: - * if self.capacity <= 0: - * capacity = 3 # <<<<<<<<<<<<<< - * else: - * capacity = 2 * self.capacity + /* "sklearn/tree/_tree.pyx":429 + * cdef double entropy_left = 0.0 + * cdef double entropy_right = 0.0 + * cdef double total_left = 0.0 # <<<<<<<<<<<<<< + * cdef double total_right = 0.0 + * cdef double tmp */ - __pyx_v_capacity = 3; - goto __pyx_L5; - } - /*else*/ { + __pyx_v_total_left = 0.0; - /* "sklearn/tree/_tree.pyx":324 - * capacity = 3 - * else: - * capacity = 2 * self.capacity # <<<<<<<<<<<<<< - * - * self.capacity = capacity + /* "sklearn/tree/_tree.pyx":430 + * cdef double entropy_right = 0.0 + * cdef double total_left = 0.0 + * cdef double total_right = 0.0 # <<<<<<<<<<<<<< + * cdef double tmp + * cdef SIZE_t k */ - __pyx_v_capacity = (2 * __pyx_v_self->capacity); - } - __pyx_L5:; - goto __pyx_L4; - } - __pyx_L4:; + __pyx_v_total_right = 0.0; - /* "sklearn/tree/_tree.pyx":326 - * capacity = 2 * self.capacity - * - * self.capacity = capacity # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":435 + * cdef SIZE_t c * - * cdef int* tmp_children_left = realloc(self.children_left, capacity * sizeof(int)) + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * entropy_left = 0.0 + * entropy_right = 0.0 */ - __pyx_v_self->capacity = __pyx_v_capacity; + __pyx_t_2 = __pyx_v_n_outputs; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_2; __pyx_t_5+=1) { + __pyx_v_k = __pyx_t_5; - /* "sklearn/tree/_tree.pyx":328 - * self.capacity = capacity + /* "sklearn/tree/_tree.pyx":436 * - * cdef int* tmp_children_left = realloc(self.children_left, capacity * sizeof(int)) # <<<<<<<<<<<<<< - * if tmp_children_left != NULL: self.children_left = tmp_children_left + * for k in range(n_outputs): + * entropy_left = 0.0 # <<<<<<<<<<<<<< + * entropy_right = 0.0 * */ - __pyx_v_tmp_children_left = ((int *)realloc(__pyx_v_self->children_left, (__pyx_v_capacity * (sizeof(int))))); + __pyx_v_entropy_left = 0.0; - /* "sklearn/tree/_tree.pyx":329 - * - * cdef int* tmp_children_left = realloc(self.children_left, capacity * sizeof(int)) - * if tmp_children_left != NULL: self.children_left = tmp_children_left # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":437 + * for k in range(n_outputs): + * entropy_left = 0.0 + * entropy_right = 0.0 # <<<<<<<<<<<<<< * - * cdef int* tmp_children_right = realloc(self.children_right, capacity * sizeof(int)) + * for c in range(n_classes[k]): */ - __pyx_t_1 = (__pyx_v_tmp_children_left != NULL); - if (__pyx_t_1) { - __pyx_v_self->children_left = __pyx_v_tmp_children_left; - goto __pyx_L6; - } - __pyx_L6:; + __pyx_v_entropy_right = 0.0; - /* "sklearn/tree/_tree.pyx":331 - * if tmp_children_left != NULL: self.children_left = tmp_children_left + /* "sklearn/tree/_tree.pyx":439 + * entropy_right = 0.0 * - * cdef int* tmp_children_right = realloc(self.children_right, capacity * sizeof(int)) # <<<<<<<<<<<<<< - * if tmp_children_right != NULL: self.children_right = tmp_children_right + * for c in range(n_classes[k]): # <<<<<<<<<<<<<< + * tmp = label_count_left[c] + * if tmp > 0.0: + */ + __pyx_t_6 = (__pyx_v_n_classes[__pyx_v_k]); + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_c = __pyx_t_7; + + /* "sklearn/tree/_tree.pyx":440 * + * for c in range(n_classes[k]): + * tmp = label_count_left[c] # <<<<<<<<<<<<<< + * if tmp > 0.0: + * tmp /= weighted_n_left */ - __pyx_v_tmp_children_right = ((int *)realloc(__pyx_v_self->children_right, (__pyx_v_capacity * (sizeof(int))))); + __pyx_v_tmp = (__pyx_v_label_count_left[__pyx_v_c]); - /* "sklearn/tree/_tree.pyx":332 + /* "sklearn/tree/_tree.pyx":441 + * for c in range(n_classes[k]): + * tmp = label_count_left[c] + * if tmp > 0.0: # <<<<<<<<<<<<<< + * tmp /= weighted_n_left + * entropy_left -= tmp * log(tmp) + */ + __pyx_t_8 = ((__pyx_v_tmp > 0.0) != 0); + if (__pyx_t_8) { + + /* "sklearn/tree/_tree.pyx":442 + * tmp = label_count_left[c] + * if tmp > 0.0: + * tmp /= weighted_n_left # <<<<<<<<<<<<<< + * entropy_left -= tmp * log(tmp) * - * cdef int* tmp_children_right = realloc(self.children_right, capacity * sizeof(int)) - * if tmp_children_right != NULL: self.children_right = tmp_children_right # <<<<<<<<<<<<<< + */ + __pyx_v_tmp = (__pyx_v_tmp / __pyx_v_weighted_n_left); + + /* "sklearn/tree/_tree.pyx":443 + * if tmp > 0.0: + * tmp /= weighted_n_left + * entropy_left -= tmp * log(tmp) # <<<<<<<<<<<<<< * - * cdef int* tmp_feature = realloc(self.feature, capacity * sizeof(int)) + * tmp = label_count_right[c] */ - __pyx_t_1 = (__pyx_v_tmp_children_right != NULL); - if (__pyx_t_1) { - __pyx_v_self->children_right = __pyx_v_tmp_children_right; - goto __pyx_L7; - } - __pyx_L7:; + __pyx_v_entropy_left = (__pyx_v_entropy_left - (__pyx_v_tmp * __pyx_f_7sklearn_4tree_5_tree_log(__pyx_v_tmp))); + goto __pyx_L7; + } + __pyx_L7:; - /* "sklearn/tree/_tree.pyx":334 - * if tmp_children_right != NULL: self.children_right = tmp_children_right + /* "sklearn/tree/_tree.pyx":445 + * entropy_left -= tmp * log(tmp) * - * cdef int* tmp_feature = realloc(self.feature, capacity * sizeof(int)) # <<<<<<<<<<<<<< - * if tmp_feature != NULL: self.feature = tmp_feature + * tmp = label_count_right[c] # <<<<<<<<<<<<<< + * if tmp > 0.0: + * tmp /= weighted_n_right + */ + __pyx_v_tmp = (__pyx_v_label_count_right[__pyx_v_c]); + + /* "sklearn/tree/_tree.pyx":446 * + * tmp = label_count_right[c] + * if tmp > 0.0: # <<<<<<<<<<<<<< + * tmp /= weighted_n_right + * entropy_right -= tmp * log(tmp) */ - __pyx_v_tmp_feature = ((int *)realloc(__pyx_v_self->feature, (__pyx_v_capacity * (sizeof(int))))); + __pyx_t_8 = ((__pyx_v_tmp > 0.0) != 0); + if (__pyx_t_8) { - /* "sklearn/tree/_tree.pyx":335 + /* "sklearn/tree/_tree.pyx":447 + * tmp = label_count_right[c] + * if tmp > 0.0: + * tmp /= weighted_n_right # <<<<<<<<<<<<<< + * entropy_right -= tmp * log(tmp) * - * cdef int* tmp_feature = realloc(self.feature, capacity * sizeof(int)) - * if tmp_feature != NULL: self.feature = tmp_feature # <<<<<<<<<<<<<< + */ + __pyx_v_tmp = (__pyx_v_tmp / __pyx_v_weighted_n_right); + + /* "sklearn/tree/_tree.pyx":448 + * if tmp > 0.0: + * tmp /= weighted_n_right + * entropy_right -= tmp * log(tmp) # <<<<<<<<<<<<<< * - * cdef double* tmp_threshold = realloc(self.threshold, capacity * sizeof(double)) + * total_left += entropy_left */ - __pyx_t_1 = (__pyx_v_tmp_feature != NULL); - if (__pyx_t_1) { - __pyx_v_self->feature = __pyx_v_tmp_feature; - goto __pyx_L8; - } - __pyx_L8:; + __pyx_v_entropy_right = (__pyx_v_entropy_right - (__pyx_v_tmp * __pyx_f_7sklearn_4tree_5_tree_log(__pyx_v_tmp))); + goto __pyx_L8; + } + __pyx_L8:; + } - /* "sklearn/tree/_tree.pyx":337 - * if tmp_feature != NULL: self.feature = tmp_feature + /* "sklearn/tree/_tree.pyx":450 + * entropy_right -= tmp * log(tmp) * - * cdef double* tmp_threshold = realloc(self.threshold, capacity * sizeof(double)) # <<<<<<<<<<<<<< - * if tmp_threshold != NULL: self.threshold = tmp_threshold + * total_left += entropy_left # <<<<<<<<<<<<<< + * total_right += entropy_right + * label_count_left += label_count_stride + */ + __pyx_v_total_left = (__pyx_v_total_left + __pyx_v_entropy_left); + + /* "sklearn/tree/_tree.pyx":451 * + * total_left += entropy_left + * total_right += entropy_right # <<<<<<<<<<<<<< + * label_count_left += label_count_stride + * label_count_right += label_count_stride */ - __pyx_v_tmp_threshold = ((double *)realloc(__pyx_v_self->threshold, (__pyx_v_capacity * (sizeof(double))))); + __pyx_v_total_right = (__pyx_v_total_right + __pyx_v_entropy_right); - /* "sklearn/tree/_tree.pyx":338 + /* "sklearn/tree/_tree.pyx":452 + * total_left += entropy_left + * total_right += entropy_right + * label_count_left += label_count_stride # <<<<<<<<<<<<<< + * label_count_right += label_count_stride * - * cdef double* tmp_threshold = realloc(self.threshold, capacity * sizeof(double)) - * if tmp_threshold != NULL: self.threshold = tmp_threshold # <<<<<<<<<<<<<< + */ + __pyx_v_label_count_left = (__pyx_v_label_count_left + __pyx_v_label_count_stride); + + /* "sklearn/tree/_tree.pyx":453 + * total_right += entropy_right + * label_count_left += label_count_stride + * label_count_right += label_count_stride # <<<<<<<<<<<<<< * - * cdef double* tmp_value = realloc(self.value, capacity * self.value_stride * sizeof(double)) + * impurity_left[0] = total_left / n_outputs */ - __pyx_t_1 = (__pyx_v_tmp_threshold != NULL); - if (__pyx_t_1) { - __pyx_v_self->threshold = __pyx_v_tmp_threshold; - goto __pyx_L9; + __pyx_v_label_count_right = (__pyx_v_label_count_right + __pyx_v_label_count_stride); } - __pyx_L9:; - /* "sklearn/tree/_tree.pyx":340 - * if tmp_threshold != NULL: self.threshold = tmp_threshold + /* "sklearn/tree/_tree.pyx":455 + * label_count_right += label_count_stride * - * cdef double* tmp_value = realloc(self.value, capacity * self.value_stride * sizeof(double)) # <<<<<<<<<<<<<< - * if tmp_value != NULL: self.value = tmp_value + * impurity_left[0] = total_left / n_outputs # <<<<<<<<<<<<<< + * impurity_right[0] = total_right / n_outputs * */ - __pyx_v_tmp_value = ((double *)realloc(__pyx_v_self->value, ((__pyx_v_capacity * __pyx_v_self->value_stride) * (sizeof(double))))); + (__pyx_v_impurity_left[0]) = (__pyx_v_total_left / __pyx_v_n_outputs); - /* "sklearn/tree/_tree.pyx":341 + /* "sklearn/tree/_tree.pyx":456 + * + * impurity_left[0] = total_left / n_outputs + * impurity_right[0] = total_right / n_outputs # <<<<<<<<<<<<<< * - * cdef double* tmp_value = realloc(self.value, capacity * self.value_stride * sizeof(double)) - * if tmp_value != NULL: self.value = tmp_value # <<<<<<<<<<<<<< * - * cdef double* tmp_best_error = realloc(self.best_error, capacity * sizeof(double)) */ - __pyx_t_1 = (__pyx_v_tmp_value != NULL); - if (__pyx_t_1) { - __pyx_v_self->value = __pyx_v_tmp_value; - goto __pyx_L10; - } - __pyx_L10:; + (__pyx_v_impurity_right[0]) = (__pyx_v_total_right / __pyx_v_n_outputs); - /* "sklearn/tree/_tree.pyx":343 - * if tmp_value != NULL: self.value = tmp_value - * - * cdef double* tmp_best_error = realloc(self.best_error, capacity * sizeof(double)) # <<<<<<<<<<<<<< - * if tmp_best_error != NULL: self.best_error = tmp_best_error + /* "sklearn/tree/_tree.pyx":412 + * return total / n_outputs * + * cdef void children_impurity(self, double* impurity_left, # <<<<<<<<<<<<<< + * double* impurity_right) nogil: + * """Evaluate the impurity in children nodes, i.e. the impurity of the */ - __pyx_v_tmp_best_error = ((double *)realloc(__pyx_v_self->best_error, (__pyx_v_capacity * (sizeof(double))))); - /* "sklearn/tree/_tree.pyx":344 - * - * cdef double* tmp_best_error = realloc(self.best_error, capacity * sizeof(double)) - * if tmp_best_error != NULL: self.best_error = tmp_best_error # <<<<<<<<<<<<<< + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":474 + * = 1 - \sum_{k=0}^{K-1} pmk ** 2 + * """ + * cdef double node_impurity(self) nogil: # <<<<<<<<<<<<<< + * """Evaluate the impurity of the current node, i.e. the impurity of + * samples[start:end].""" + */ + +static double __pyx_f_7sklearn_4tree_5_tree_4Gini_node_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_Gini *__pyx_v_self) { + double __pyx_v_weighted_n_node_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_label_count_stride; + double *__pyx_v_label_count_total; + double __pyx_v_gini; + double __pyx_v_total; + double __pyx_v_tmp; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_c; + double __pyx_r; + double __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_3; + double *__pyx_t_4; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_5; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; + + /* "sklearn/tree/_tree.pyx":477 + * """Evaluate the impurity of the current node, i.e. the impurity of + * samples[start:end].""" + * cdef double weighted_n_node_samples = self.weighted_n_node_samples # <<<<<<<<<<<<<< * - * cdef double* tmp_init_error = realloc(self.init_error, capacity * sizeof(double)) + * cdef SIZE_t n_outputs = self.n_outputs */ - __pyx_t_1 = (__pyx_v_tmp_best_error != NULL); - if (__pyx_t_1) { - __pyx_v_self->best_error = __pyx_v_tmp_best_error; - goto __pyx_L11; - } - __pyx_L11:; + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.weighted_n_node_samples; + __pyx_v_weighted_n_node_samples = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":346 - * if tmp_best_error != NULL: self.best_error = tmp_best_error + /* "sklearn/tree/_tree.pyx":479 + * cdef double weighted_n_node_samples = self.weighted_n_node_samples * - * cdef double* tmp_init_error = realloc(self.init_error, capacity * sizeof(double)) # <<<<<<<<<<<<<< - * if tmp_init_error != NULL: self.init_error = tmp_init_error + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":480 * + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes # <<<<<<<<<<<<<< + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total */ - __pyx_v_tmp_init_error = ((double *)realloc(__pyx_v_self->init_error, (__pyx_v_capacity * (sizeof(double))))); + __pyx_t_3 = __pyx_v_self->__pyx_base.n_classes; + __pyx_v_n_classes = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":347 + /* "sklearn/tree/_tree.pyx":481 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< + * cdef double* label_count_total = self.label_count_total * - * cdef double* tmp_init_error = realloc(self.init_error, capacity * sizeof(double)) - * if tmp_init_error != NULL: self.init_error = tmp_init_error # <<<<<<<<<<<<<< + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.label_count_stride; + __pyx_v_label_count_stride = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":482 + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_total = self.label_count_total # <<<<<<<<<<<<<< * - * cdef int* tmp_n_samples = realloc(self.n_samples, capacity * sizeof(int)) + * cdef double gini = 0.0 */ - __pyx_t_1 = (__pyx_v_tmp_init_error != NULL); - if (__pyx_t_1) { - __pyx_v_self->init_error = __pyx_v_tmp_init_error; - goto __pyx_L12; - } - __pyx_L12:; + __pyx_t_4 = __pyx_v_self->__pyx_base.label_count_total; + __pyx_v_label_count_total = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":349 - * if tmp_init_error != NULL: self.init_error = tmp_init_error + /* "sklearn/tree/_tree.pyx":484 + * cdef double* label_count_total = self.label_count_total * - * cdef int* tmp_n_samples = realloc(self.n_samples, capacity * sizeof(int)) # <<<<<<<<<<<<<< - * if tmp_n_samples != NULL: self.n_samples = tmp_n_samples + * cdef double gini = 0.0 # <<<<<<<<<<<<<< + * cdef double total = 0.0 + * cdef double tmp + */ + __pyx_v_gini = 0.0; + + /* "sklearn/tree/_tree.pyx":485 * + * cdef double gini = 0.0 + * cdef double total = 0.0 # <<<<<<<<<<<<<< + * cdef double tmp + * cdef SIZE_t k */ - __pyx_v_tmp_n_samples = ((int *)realloc(__pyx_v_self->n_samples, (__pyx_v_capacity * (sizeof(int))))); + __pyx_v_total = 0.0; - /* "sklearn/tree/_tree.pyx":350 + /* "sklearn/tree/_tree.pyx":490 + * cdef SIZE_t c * - * cdef int* tmp_n_samples = realloc(self.n_samples, capacity * sizeof(int)) - * if tmp_n_samples != NULL: self.n_samples = tmp_n_samples # <<<<<<<<<<<<<< + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * gini = 0.0 * - * if tmp_children_left == NULL or \ */ - __pyx_t_1 = (__pyx_v_tmp_n_samples != NULL); - if (__pyx_t_1) { - __pyx_v_self->n_samples = __pyx_v_tmp_n_samples; - goto __pyx_L13; - } - __pyx_L13:; + __pyx_t_2 = __pyx_v_n_outputs; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_2; __pyx_t_5+=1) { + __pyx_v_k = __pyx_t_5; - /* "sklearn/tree/_tree.pyx":352 - * if tmp_n_samples != NULL: self.n_samples = tmp_n_samples + /* "sklearn/tree/_tree.pyx":491 + * + * for k in range(n_outputs): + * gini = 0.0 # <<<<<<<<<<<<<< * - * if tmp_children_left == NULL or \ # <<<<<<<<<<<<<< - * tmp_children_right == NULL or \ - * tmp_feature == NULL or \ + * for c in range(n_classes[k]): */ - __pyx_t_1 = (__pyx_v_tmp_children_left == NULL); - if (!__pyx_t_1) { + __pyx_v_gini = 0.0; - /* "sklearn/tree/_tree.pyx":353 + /* "sklearn/tree/_tree.pyx":493 + * gini = 0.0 * - * if tmp_children_left == NULL or \ - * tmp_children_right == NULL or \ # <<<<<<<<<<<<<< - * tmp_feature == NULL or \ - * tmp_threshold == NULL or \ + * for c in range(n_classes[k]): # <<<<<<<<<<<<<< + * tmp = label_count_total[c] + * gini += tmp * tmp */ - __pyx_t_2 = (__pyx_v_tmp_children_right == NULL); - if (!__pyx_t_2) { - - /* "sklearn/tree/_tree.pyx":354 - * if tmp_children_left == NULL or \ - * tmp_children_right == NULL or \ - * tmp_feature == NULL or \ # <<<<<<<<<<<<<< - * tmp_threshold == NULL or \ - * tmp_value == NULL or \ - */ - __pyx_t_3 = (__pyx_v_tmp_feature == NULL); - if (!__pyx_t_3) { - - /* "sklearn/tree/_tree.pyx":355 - * tmp_children_right == NULL or \ - * tmp_feature == NULL or \ - * tmp_threshold == NULL or \ # <<<<<<<<<<<<<< - * tmp_value == NULL or \ - * tmp_best_error == NULL or \ - */ - __pyx_t_4 = (__pyx_v_tmp_threshold == NULL); - if (!__pyx_t_4) { - - /* "sklearn/tree/_tree.pyx":356 - * tmp_feature == NULL or \ - * tmp_threshold == NULL or \ - * tmp_value == NULL or \ # <<<<<<<<<<<<<< - * tmp_best_error == NULL or \ - * tmp_init_error == NULL or \ - */ - __pyx_t_5 = (__pyx_v_tmp_value == NULL); - if (!__pyx_t_5) { - - /* "sklearn/tree/_tree.pyx":357 - * tmp_threshold == NULL or \ - * tmp_value == NULL or \ - * tmp_best_error == NULL or \ # <<<<<<<<<<<<<< - * tmp_init_error == NULL or \ - * tmp_n_samples == NULL: - */ - __pyx_t_6 = (__pyx_v_tmp_best_error == NULL); - if (!__pyx_t_6) { + __pyx_t_6 = (__pyx_v_n_classes[__pyx_v_k]); + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_c = __pyx_t_7; - /* "sklearn/tree/_tree.pyx":358 - * tmp_value == NULL or \ - * tmp_best_error == NULL or \ - * tmp_init_error == NULL or \ # <<<<<<<<<<<<<< - * tmp_n_samples == NULL: - * raise MemoryError() + /* "sklearn/tree/_tree.pyx":494 + * + * for c in range(n_classes[k]): + * tmp = label_count_total[c] # <<<<<<<<<<<<<< + * gini += tmp * tmp + * */ - __pyx_t_7 = (__pyx_v_tmp_init_error == NULL); - if (!__pyx_t_7) { + __pyx_v_tmp = (__pyx_v_label_count_total[__pyx_v_c]); - /* "sklearn/tree/_tree.pyx":359 - * tmp_best_error == NULL or \ - * tmp_init_error == NULL or \ - * tmp_n_samples == NULL: # <<<<<<<<<<<<<< - * raise MemoryError() + /* "sklearn/tree/_tree.pyx":495 + * for c in range(n_classes[k]): + * tmp = label_count_total[c] + * gini += tmp * tmp # <<<<<<<<<<<<<< * + * gini = 1.0 - gini / (weighted_n_node_samples * */ - __pyx_t_8 = (__pyx_v_tmp_n_samples == NULL); - __pyx_t_9 = __pyx_t_8; - } else { - __pyx_t_9 = __pyx_t_7; - } - __pyx_t_7 = __pyx_t_9; - } else { - __pyx_t_7 = __pyx_t_6; - } - __pyx_t_6 = __pyx_t_7; - } else { - __pyx_t_6 = __pyx_t_5; - } - __pyx_t_5 = __pyx_t_6; - } else { - __pyx_t_5 = __pyx_t_4; - } - __pyx_t_4 = __pyx_t_5; - } else { - __pyx_t_4 = __pyx_t_3; - } - __pyx_t_3 = __pyx_t_4; - } else { - __pyx_t_3 = __pyx_t_2; + __pyx_v_gini = (__pyx_v_gini + (__pyx_v_tmp * __pyx_v_tmp)); } - __pyx_t_2 = __pyx_t_3; - } else { - __pyx_t_2 = __pyx_t_1; - } - if (__pyx_t_2) { - /* "sklearn/tree/_tree.pyx":360 - * tmp_init_error == NULL or \ - * tmp_n_samples == NULL: - * raise MemoryError() # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":497 + * gini += tmp * tmp + * + * gini = 1.0 - gini / (weighted_n_node_samples * # <<<<<<<<<<<<<< + * weighted_n_node_samples) * - * # if capacity smaller than node_count, adjust the counter */ - PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; - } - __pyx_L14:; + __pyx_v_gini = (1.0 - (__pyx_v_gini / (__pyx_v_weighted_n_node_samples * __pyx_v_weighted_n_node_samples))); - /* "sklearn/tree/_tree.pyx":363 + /* "sklearn/tree/_tree.pyx":500 + * weighted_n_node_samples) * - * # if capacity smaller than node_count, adjust the counter - * if capacity < self.node_count: # <<<<<<<<<<<<<< - * self.node_count = capacity + * total += gini # <<<<<<<<<<<<<< + * label_count_total += label_count_stride * */ - __pyx_t_2 = (__pyx_v_capacity < __pyx_v_self->node_count); - if (__pyx_t_2) { + __pyx_v_total = (__pyx_v_total + __pyx_v_gini); - /* "sklearn/tree/_tree.pyx":364 - * # if capacity smaller than node_count, adjust the counter - * if capacity < self.node_count: - * self.node_count = capacity # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":501 + * + * total += gini + * label_count_total += label_count_stride # <<<<<<<<<<<<<< * - * cpdef build(self, np.ndarray X, np.ndarray y, + * return total / n_outputs */ - __pyx_v_self->node_count = __pyx_v_capacity; - goto __pyx_L15; + __pyx_v_label_count_total = (__pyx_v_label_count_total + __pyx_v_label_count_stride); } - __pyx_L15:; + /* "sklearn/tree/_tree.pyx":503 + * label_count_total += label_count_stride + * + * return total / n_outputs # <<<<<<<<<<<<<< + * + * cdef void children_impurity(self, double* impurity_left, + */ + __pyx_r = (__pyx_v_total / __pyx_v_n_outputs); goto __pyx_L0; - __pyx_L1_error:; - __Pyx_WriteUnraisable("sklearn.tree._tree.Tree.resize", __pyx_clineno, __pyx_lineno, __pyx_filename); + + /* "sklearn/tree/_tree.pyx":474 + * = 1 - \sum_{k=0}^{K-1} pmk ** 2 + * """ + * cdef double node_impurity(self) nogil: # <<<<<<<<<<<<<< + * """Evaluate the impurity of the current node, i.e. the impurity of + * samples[start:end].""" + */ + + /* function exit code */ __pyx_L0:; - __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "sklearn/tree/_tree.pyx":366 - * self.node_count = capacity +/* "sklearn/tree/_tree.pyx":505 + * return total / n_outputs * - * cpdef build(self, np.ndarray X, np.ndarray y, # <<<<<<<<<<<<<< - * np.ndarray sample_mask=None, np.ndarray X_argsorted=None): - * """Build a decision tree from the training set (X, y). + * cdef void children_impurity(self, double* impurity_left, # <<<<<<<<<<<<<< + * double* impurity_right) nogil: + * """Evaluate the impurity in children nodes, i.e. the impurity of the + */ + +static void __pyx_f_7sklearn_4tree_5_tree_4Gini_children_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_Gini *__pyx_v_self, double *__pyx_v_impurity_left, double *__pyx_v_impurity_right) { + CYTHON_UNUSED double __pyx_v_weighted_n_node_samples; + double __pyx_v_weighted_n_left; + double __pyx_v_weighted_n_right; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_classes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_label_count_stride; + double *__pyx_v_label_count_left; + double *__pyx_v_label_count_right; + double __pyx_v_gini_left; + double __pyx_v_gini_right; + CYTHON_UNUSED double __pyx_v_total; + double __pyx_v_total_left; + double __pyx_v_total_right; + double __pyx_v_tmp; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_c; + double __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_3; + double *__pyx_t_4; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_5; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; + + /* "sklearn/tree/_tree.pyx":510 + * left child (samples[start:pos]) and the impurity the right child + * (samples[pos:end]).""" + * cdef double weighted_n_node_samples = self.weighted_n_node_samples # <<<<<<<<<<<<<< + * cdef double weighted_n_left = self.weighted_n_left + * cdef double weighted_n_right = self.weighted_n_right */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.weighted_n_node_samples; + __pyx_v_weighted_n_node_samples = __pyx_t_1; -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_11build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_f_7sklearn_4tree_5_tree_4Tree_build(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_y, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_build *__pyx_optional_args) { + /* "sklearn/tree/_tree.pyx":511 + * (samples[pos:end]).""" + * cdef double weighted_n_node_samples = self.weighted_n_node_samples + * cdef double weighted_n_left = self.weighted_n_left # <<<<<<<<<<<<<< + * cdef double weighted_n_right = self.weighted_n_right + * + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.weighted_n_left; + __pyx_v_weighted_n_left = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":367 + /* "sklearn/tree/_tree.pyx":512 + * cdef double weighted_n_node_samples = self.weighted_n_node_samples + * cdef double weighted_n_left = self.weighted_n_left + * cdef double weighted_n_right = self.weighted_n_right # <<<<<<<<<<<<<< * - * cpdef build(self, np.ndarray X, np.ndarray y, - * np.ndarray sample_mask=None, np.ndarray X_argsorted=None): # <<<<<<<<<<<<<< - * """Build a decision tree from the training set (X, y). + * cdef SIZE_t n_outputs = self.n_outputs + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.weighted_n_right; + __pyx_v_weighted_n_right = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":514 + * cdef double weighted_n_right = self.weighted_n_right * + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride */ - PyArrayObject *__pyx_v_sample_mask = ((PyArrayObject *)Py_None); - PyArrayObject *__pyx_v_X_argsorted = ((PyArrayObject *)Py_None); - int __pyx_v_init_capacity; - double *__pyx_v_buffer_value; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; - struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_resize __pyx_t_10; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("build", 0); - if (__pyx_optional_args) { - if (__pyx_optional_args->__pyx_n > 0) { - __pyx_v_sample_mask = __pyx_optional_args->sample_mask; - if (__pyx_optional_args->__pyx_n > 1) { - __pyx_v_X_argsorted = __pyx_optional_args->X_argsorted; - } - } - } - __Pyx_INCREF((PyObject *)__pyx_v_X); - __Pyx_INCREF((PyObject *)__pyx_v_y); - __Pyx_INCREF((PyObject *)__pyx_v_sample_mask); - __Pyx_INCREF((PyObject *)__pyx_v_X_argsorted); + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":366 - * self.node_count = capacity + /* "sklearn/tree/_tree.pyx":515 * - * cpdef build(self, np.ndarray X, np.ndarray y, # <<<<<<<<<<<<<< - * np.ndarray sample_mask=None, np.ndarray X_argsorted=None): - * """Build a decision tree from the training set (X, y). + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes # <<<<<<<<<<<<<< + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_left = self.label_count_left */ - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__build); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_11build)) { - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_v_X)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_X)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_X)); - __Pyx_INCREF(((PyObject *)__pyx_v_y)); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_y)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); - __Pyx_INCREF(((PyObject *)__pyx_v_sample_mask)); - PyTuple_SET_ITEM(__pyx_t_2, 2, ((PyObject *)__pyx_v_sample_mask)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_sample_mask)); - __Pyx_INCREF(((PyObject *)__pyx_v_X_argsorted)); - PyTuple_SET_ITEM(__pyx_t_2, 3, ((PyObject *)__pyx_v_X_argsorted)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_X_argsorted)); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } + __pyx_t_3 = __pyx_v_self->__pyx_base.n_classes; + __pyx_v_n_classes = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":379 - * """ - * # Check input before recursive partitioning - * if X.dtype != DTYPE or not np.isfortran(X): # <<<<<<<<<<<<<< - * X = np.asarray(X, dtype=DTYPE, order="F") + /* "sklearn/tree/_tree.pyx":516 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< + * cdef double* label_count_left = self.label_count_left + * cdef double* label_count_right = self.label_count_right + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.label_count_stride; + __pyx_v_label_count_stride = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":517 + * cdef SIZE_t* n_classes = self.n_classes + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_left = self.label_count_left # <<<<<<<<<<<<<< + * cdef double* label_count_right = self.label_count_right * */ - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_X), __pyx_n_s__dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyObject_RichCompare(__pyx_t_1, __pyx_t_3, Py_NE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!__pyx_t_4) { - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isfortran); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_v_X)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_X)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_X)); - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = (!__pyx_t_5); - __pyx_t_5 = __pyx_t_6; - } else { - __pyx_t_5 = __pyx_t_4; - } - if (__pyx_t_5) { + __pyx_t_4 = __pyx_v_self->__pyx_base.label_count_left; + __pyx_v_label_count_left = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":380 - * # Check input before recursive partitioning - * if X.dtype != DTYPE or not np.isfortran(X): - * X = np.asarray(X, dtype=DTYPE, order="F") # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":518 + * cdef SIZE_t label_count_stride = self.label_count_stride + * cdef double* label_count_left = self.label_count_left + * cdef double* label_count_right = self.label_count_right # <<<<<<<<<<<<<< * - * if y.dtype != DOUBLE or not y.flags.contiguous: + * cdef double gini_left = 0.0 */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)__pyx_v_X)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_X)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_X)); - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__F)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_v_X)); - __pyx_v_X = ((PyArrayObject *)__pyx_t_7); - __pyx_t_7 = 0; - goto __pyx_L3; - } - __pyx_L3:; + __pyx_t_4 = __pyx_v_self->__pyx_base.label_count_right; + __pyx_v_label_count_right = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":382 - * X = np.asarray(X, dtype=DTYPE, order="F") - * - * if y.dtype != DOUBLE or not y.flags.contiguous: # <<<<<<<<<<<<<< - * y = np.asarray(y, dtype=DOUBLE, order="C") + /* "sklearn/tree/_tree.pyx":520 + * cdef double* label_count_right = self.label_count_right * + * cdef double gini_left = 0.0 # <<<<<<<<<<<<<< + * cdef double gini_right = 0.0 + * cdef double total = 0.0 */ - __pyx_t_7 = PyObject_GetAttr(((PyObject *)__pyx_v_y), __pyx_n_s__dtype); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_RichCompare(__pyx_t_7, __pyx_t_3, Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!__pyx_t_5) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_y), __pyx_n_s__flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__contiguous); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = (!__pyx_t_4); - __pyx_t_4 = __pyx_t_6; - } else { - __pyx_t_4 = __pyx_t_5; - } - if (__pyx_t_4) { + __pyx_v_gini_left = 0.0; - /* "sklearn/tree/_tree.pyx":383 - * - * if y.dtype != DOUBLE or not y.flags.contiguous: - * y = np.asarray(y, dtype=DOUBLE, order="C") # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":521 * - * if sample_mask is None: + * cdef double gini_left = 0.0 + * cdef double gini_right = 0.0 # <<<<<<<<<<<<<< + * cdef double total = 0.0 + * cdef double total_left = 0.0 */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_y)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_y)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__DOUBLE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_v_y)); - __pyx_v_y = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - goto __pyx_L4; - } - __pyx_L4:; + __pyx_v_gini_right = 0.0; - /* "sklearn/tree/_tree.pyx":385 - * y = np.asarray(y, dtype=DOUBLE, order="C") - * - * if sample_mask is None: # <<<<<<<<<<<<<< - * sample_mask = np.ones((X.shape[0],), dtype=np.bool) + /* "sklearn/tree/_tree.pyx":522 + * cdef double gini_left = 0.0 + * cdef double gini_right = 0.0 + * cdef double total = 0.0 # <<<<<<<<<<<<<< + * cdef double total_left = 0.0 + * cdef double total_right = 0.0 + */ + __pyx_v_total = 0.0; + + /* "sklearn/tree/_tree.pyx":523 + * cdef double gini_right = 0.0 + * cdef double total = 0.0 + * cdef double total_left = 0.0 # <<<<<<<<<<<<<< + * cdef double total_right = 0.0 + * cdef double tmp + */ + __pyx_v_total_left = 0.0; + + /* "sklearn/tree/_tree.pyx":524 + * cdef double total = 0.0 + * cdef double total_left = 0.0 + * cdef double total_right = 0.0 # <<<<<<<<<<<<<< + * cdef double tmp + * cdef SIZE_t k + */ + __pyx_v_total_right = 0.0; + + /* "sklearn/tree/_tree.pyx":529 + * cdef SIZE_t c * + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * gini_left = 0.0 + * gini_right = 0.0 */ - __pyx_t_4 = (((PyObject *)__pyx_v_sample_mask) == Py_None); - if (__pyx_t_4) { + __pyx_t_2 = __pyx_v_n_outputs; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_2; __pyx_t_5+=1) { + __pyx_v_k = __pyx_t_5; - /* "sklearn/tree/_tree.pyx":386 + /* "sklearn/tree/_tree.pyx":530 * - * if sample_mask is None: - * sample_mask = np.ones((X.shape[0],), dtype=np.bool) # <<<<<<<<<<<<<< + * for k in range(n_outputs): + * gini_left = 0.0 # <<<<<<<<<<<<<< + * gini_right = 0.0 * - * if X_argsorted is None: */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__ones); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyInt_to_py_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); - __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_8 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__bool); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_8) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_8, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_v_sample_mask)); - __pyx_v_sample_mask = ((PyArrayObject *)__pyx_t_8); - __pyx_t_8 = 0; - goto __pyx_L5; - } - __pyx_L5:; + __pyx_v_gini_left = 0.0; - /* "sklearn/tree/_tree.pyx":388 - * sample_mask = np.ones((X.shape[0],), dtype=np.bool) + /* "sklearn/tree/_tree.pyx":531 + * for k in range(n_outputs): + * gini_left = 0.0 + * gini_right = 0.0 # <<<<<<<<<<<<<< * - * if X_argsorted is None: # <<<<<<<<<<<<<< - * X_argsorted = np.asfortranarray( - * np.argsort(X.T, axis=1).astype(np.int32).T) + * for c in range(n_classes[k]): */ - __pyx_t_4 = (((PyObject *)__pyx_v_X_argsorted) == Py_None); - if (__pyx_t_4) { + __pyx_v_gini_right = 0.0; - /* "sklearn/tree/_tree.pyx":389 + /* "sklearn/tree/_tree.pyx":533 + * gini_right = 0.0 * - * if X_argsorted is None: - * X_argsorted = np.asfortranarray( # <<<<<<<<<<<<<< - * np.argsort(X.T, axis=1).astype(np.int32).T) + * for c in range(n_classes[k]): # <<<<<<<<<<<<<< + * tmp = label_count_left[c] + * gini_left += tmp * tmp + */ + __pyx_t_6 = (__pyx_v_n_classes[__pyx_v_k]); + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_c = __pyx_t_7; + + /* "sklearn/tree/_tree.pyx":534 * + * for c in range(n_classes[k]): + * tmp = label_count_left[c] # <<<<<<<<<<<<<< + * gini_left += tmp * tmp + * tmp = label_count_right[c] */ - __pyx_t_8 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 389; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_8, __pyx_n_s__asfortranarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 389; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_tmp = (__pyx_v_label_count_left[__pyx_v_c]); + + /* "sklearn/tree/_tree.pyx":535 + * for c in range(n_classes[k]): + * tmp = label_count_left[c] + * gini_left += tmp * tmp # <<<<<<<<<<<<<< + * tmp = label_count_right[c] + * gini_right += tmp * tmp + */ + __pyx_v_gini_left = (__pyx_v_gini_left + (__pyx_v_tmp * __pyx_v_tmp)); - /* "sklearn/tree/_tree.pyx":390 - * if X_argsorted is None: - * X_argsorted = np.asfortranarray( - * np.argsort(X.T, axis=1).astype(np.int32).T) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":536 + * tmp = label_count_left[c] + * gini_left += tmp * tmp + * tmp = label_count_right[c] # <<<<<<<<<<<<<< + * gini_right += tmp * tmp * - * # Pre-allocate some space */ - __pyx_t_8 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_8, __pyx_n_s__argsort); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_GetAttr(((PyObject *)__pyx_v_X), __pyx_n_s__T); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_8); - __pyx_t_8 = 0; - __pyx_t_8 = PyDict_New(); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); - if (PyDict_SetItem(__pyx_t_8, ((PyObject *)__pyx_n_s__axis), __pyx_int_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_8)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__astype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__int32); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_8, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__T); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 389; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 389; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 389; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_v_X_argsorted)); - __pyx_v_X_argsorted = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - goto __pyx_L6; - } - __pyx_L6:; + __pyx_v_tmp = (__pyx_v_label_count_right[__pyx_v_c]); - /* "sklearn/tree/_tree.pyx":395 - * cdef int init_capacity + /* "sklearn/tree/_tree.pyx":537 + * gini_left += tmp * tmp + * tmp = label_count_right[c] + * gini_right += tmp * tmp # <<<<<<<<<<<<<< * - * if self.max_depth <= 10: # <<<<<<<<<<<<<< - * init_capacity = (2 ** (int(self.max_depth) + 1)) - 1 - * else: + * gini_left = 1.0 - gini_left / (weighted_n_left * */ - __pyx_t_4 = (__pyx_v_self->max_depth <= 10.0); - if (__pyx_t_4) { + __pyx_v_gini_right = (__pyx_v_gini_right + (__pyx_v_tmp * __pyx_v_tmp)); + } - /* "sklearn/tree/_tree.pyx":396 + /* "sklearn/tree/_tree.pyx":539 + * gini_right += tmp * tmp * - * if self.max_depth <= 10: - * init_capacity = (2 ** (int(self.max_depth) + 1)) - 1 # <<<<<<<<<<<<<< - * else: - * init_capacity = 2047 + * gini_left = 1.0 - gini_left / (weighted_n_left * # <<<<<<<<<<<<<< + * weighted_n_left) + * gini_right = 1.0 - gini_right / (weighted_n_right * */ - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->max_depth); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __pyx_t_7 = PyNumber_Add(__pyx_t_1, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Power(__pyx_int_2, __pyx_t_7, Py_None); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyNumber_Subtract(__pyx_t_1, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_9 = __Pyx_PyInt_AsInt(__pyx_t_7); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_v_init_capacity = __pyx_t_9; - goto __pyx_L7; - } - /*else*/ { + __pyx_v_gini_left = (1.0 - (__pyx_v_gini_left / (__pyx_v_weighted_n_left * __pyx_v_weighted_n_left))); - /* "sklearn/tree/_tree.pyx":398 - * init_capacity = (2 ** (int(self.max_depth) + 1)) - 1 - * else: - * init_capacity = 2047 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":541 + * gini_left = 1.0 - gini_left / (weighted_n_left * + * weighted_n_left) + * gini_right = 1.0 - gini_right / (weighted_n_right * # <<<<<<<<<<<<<< + * weighted_n_right) * - * self.resize(init_capacity) */ - __pyx_v_init_capacity = 2047; - } - __pyx_L7:; + __pyx_v_gini_right = (1.0 - (__pyx_v_gini_right / (__pyx_v_weighted_n_right * __pyx_v_weighted_n_right))); - /* "sklearn/tree/_tree.pyx":400 - * init_capacity = 2047 + /* "sklearn/tree/_tree.pyx":544 + * weighted_n_right) * - * self.resize(init_capacity) # <<<<<<<<<<<<<< - * cdef double* buffer_value = malloc(self.value_stride * sizeof(double)) + * total_left += gini_left # <<<<<<<<<<<<<< + * total_right += gini_right + * label_count_left += label_count_stride + */ + __pyx_v_total_left = (__pyx_v_total_left + __pyx_v_gini_left); + + /* "sklearn/tree/_tree.pyx":545 * + * total_left += gini_left + * total_right += gini_right # <<<<<<<<<<<<<< + * label_count_left += label_count_stride + * label_count_right += label_count_stride */ - __pyx_t_10.__pyx_n = 1; - __pyx_t_10.capacity = __pyx_v_init_capacity; - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->resize(__pyx_v_self, &__pyx_t_10); + __pyx_v_total_right = (__pyx_v_total_right + __pyx_v_gini_right); - /* "sklearn/tree/_tree.pyx":401 + /* "sklearn/tree/_tree.pyx":546 + * total_left += gini_left + * total_right += gini_right + * label_count_left += label_count_stride # <<<<<<<<<<<<<< + * label_count_right += label_count_stride * - * self.resize(init_capacity) - * cdef double* buffer_value = malloc(self.value_stride * sizeof(double)) # <<<<<<<<<<<<<< + */ + __pyx_v_label_count_left = (__pyx_v_label_count_left + __pyx_v_label_count_stride); + + /* "sklearn/tree/_tree.pyx":547 + * total_right += gini_right + * label_count_left += label_count_stride + * label_count_right += label_count_stride # <<<<<<<<<<<<<< * - * # Build the tree by recursive partitioning + * impurity_left[0] = total_left / n_outputs */ - __pyx_v_buffer_value = ((double *)malloc((__pyx_v_self->value_stride * (sizeof(double))))); + __pyx_v_label_count_right = (__pyx_v_label_count_right + __pyx_v_label_count_stride); + } - /* "sklearn/tree/_tree.pyx":404 + /* "sklearn/tree/_tree.pyx":549 + * label_count_right += label_count_stride * - * # Build the tree by recursive partitioning - * self.recursive_partition(X, X_argsorted, y, sample_mask, np.sum(sample_mask), 0, -1, False, buffer_value) # <<<<<<<<<<<<<< + * impurity_left[0] = total_left / n_outputs # <<<<<<<<<<<<<< + * impurity_right[0] = total_right / n_outputs * - * # Compactify */ - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 404; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__sum); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 404; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 404; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_INCREF(((PyObject *)__pyx_v_sample_mask)); - PyTuple_SET_ITEM(__pyx_t_7, 0, ((PyObject *)__pyx_v_sample_mask)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_sample_mask)); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 404; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __pyx_t_9 = __Pyx_PyInt_AsInt(__pyx_t_3); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 404; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->recursive_partition(__pyx_v_self, ((PyArrayObject *)__pyx_v_X), ((PyArrayObject *)__pyx_v_X_argsorted), ((PyArrayObject *)__pyx_v_y), __pyx_v_sample_mask, __pyx_t_9, 0, -1, 0, __pyx_v_buffer_value); + (__pyx_v_impurity_left[0]) = (__pyx_v_total_left / __pyx_v_n_outputs); - /* "sklearn/tree/_tree.pyx":407 + /* "sklearn/tree/_tree.pyx":550 + * + * impurity_left[0] = total_left / n_outputs + * impurity_right[0] = total_right / n_outputs # <<<<<<<<<<<<<< * - * # Compactify - * self.resize(self.node_count) # <<<<<<<<<<<<<< - * free(buffer_value) * */ - __pyx_t_10.__pyx_n = 1; - __pyx_t_10.capacity = __pyx_v_self->node_count; - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->resize(__pyx_v_self, &__pyx_t_10); + (__pyx_v_impurity_right[0]) = (__pyx_v_total_right / __pyx_v_n_outputs); - /* "sklearn/tree/_tree.pyx":408 - * # Compactify - * self.resize(self.node_count) - * free(buffer_value) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":505 + * return total / n_outputs * - * cdef void recursive_partition(self, + * cdef void children_impurity(self, double* impurity_left, # <<<<<<<<<<<<<< + * double* impurity_right) nogil: + * """Evaluate the impurity in children nodes, i.e. the impurity of the */ - free(__pyx_v_buffer_value); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.build", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_X); - __Pyx_XDECREF((PyObject *)__pyx_v_y); - __Pyx_XDECREF((PyObject *)__pyx_v_sample_mask); - __Pyx_XDECREF((PyObject *)__pyx_v_X_argsorted); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; + /* function exit code */ } +/* "sklearn/tree/_tree.pyx":574 + * cdef double* sum_total + * + * def __cinit__(self, SIZE_t n_outputs): # <<<<<<<<<<<<<< + * # Default values + * self.y = NULL + */ + /* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_11build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_10build[] = "Build a decision tree from the training set (X, y).\n\n Parameters\n ----------\n X : ndarray of shape [n_samples, n_features]\n The training input samples.\n\n y : ndarray of shape [n_samples, n_outputs]\n The target values.\n "; -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_11build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_X = 0; - PyArrayObject *__pyx_v_y = 0; - PyArrayObject *__pyx_v_sample_mask = 0; - PyArrayObject *__pyx_v_X_argsorted = 0; - PyObject *__pyx_r = 0; +static int __pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("build (wrapper)", 0); + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__y,&__pyx_n_s__sample_mask,&__pyx_n_s__X_argsorted,0}; - PyObject* values[4] = {0,0,0,0}; - - /* "sklearn/tree/_tree.pyx":367 - * - * cpdef build(self, np.ndarray X, np.ndarray y, - * np.ndarray sample_mask=None, np.ndarray X_argsorted=None): # <<<<<<<<<<<<<< - * """Build a decision tree from the training set (X, y). - * - */ - values[2] = (PyObject *)((PyArrayObject *)Py_None); - values[3] = (PyObject *)((PyArrayObject *)Py_None); + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_n_outputs,0}; + PyObject* values[1] = {0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; @@ -4441,4134 +5540,3753 @@ static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_11build(PyObject *__pyx_v_ kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X)) != 0)) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_outputs)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build", 0, 2, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sample_mask); - if (value) { values[2] = value; kw_args--; } - } - case 3: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_argsorted); - if (value) { values[3] = value; kw_args--; } - } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "build") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); } - __pyx_v_X = ((PyArrayObject *)values[0]); - __pyx_v_y = ((PyArrayObject *)values[1]); - __pyx_v_sample_mask = ((PyArrayObject *)values[2]); - __pyx_v_X_argsorted = ((PyArrayObject *)values[3]); + __pyx_v_n_outputs = __Pyx_PyInt_As_Py_intptr_t(values[0]); if (unlikely((__pyx_v_n_outputs == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("build", 0, 2, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.tree._tree.RegressionCriterion.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); - return NULL; + return -1; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_mask), __pyx_ptype_5numpy_ndarray, 1, "sample_mask", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 367; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_argsorted), __pyx_ptype_5numpy_ndarray, 1, "X_argsorted", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 367; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10build(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), __pyx_v_X, __pyx_v_y, __pyx_v_sample_mask, __pyx_v_X_argsorted); - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self), __pyx_v_n_outputs); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pyx":366 - * self.node_count = capacity - * - * cpdef build(self, np.ndarray X, np.ndarray y, # <<<<<<<<<<<<<< - * np.ndarray sample_mask=None, np.ndarray X_argsorted=None): - * """Build a decision tree from the training set (X, y). - */ - -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10build(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_mask, PyArrayObject *__pyx_v_X_argsorted) { - PyObject *__pyx_r = NULL; +static int __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs) { + int __pyx_r; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_build __pyx_t_2; + int __pyx_t_1; + int __pyx_t_2; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("build", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_2.__pyx_n = 2; - __pyx_t_2.sample_mask = __pyx_v_sample_mask; - __pyx_t_2.X_argsorted = __pyx_v_X_argsorted; - __pyx_t_1 = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->build(__pyx_v_self, __pyx_v_X, __pyx_v_y, 1, &__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __Pyx_RefNannySetupContext("__cinit__", 0); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.build", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":576 + * def __cinit__(self, SIZE_t n_outputs): + * # Default values + * self.y = NULL # <<<<<<<<<<<<<< + * self.y_stride = 0 + * self.sample_weight = NULL + */ + __pyx_v_self->__pyx_base.y = NULL; -/* "sklearn/tree/_tree.pyx":410 - * free(buffer_value) + /* "sklearn/tree/_tree.pyx":577 + * # Default values + * self.y = NULL + * self.y_stride = 0 # <<<<<<<<<<<<<< + * self.sample_weight = NULL * - * cdef void recursive_partition(self, # <<<<<<<<<<<<<< - * np.ndarray[DTYPE_t, ndim=2, mode="fortran"] X, - * np.ndarray[np.int32_t, ndim=2, mode="fortran"] X_argsorted, */ + __pyx_v_self->__pyx_base.y_stride = 0; -static void __pyx_f_7sklearn_4tree_5_tree_4Tree_recursive_partition(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_X_argsorted, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_mask, int __pyx_v_n_node_samples, int __pyx_v_depth, int __pyx_v_parent, int __pyx_v_is_left_child, double *__pyx_v_buffer_value) { - struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion = 0; - __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_ptr; - int *__pyx_v_X_argsorted_ptr; - __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y_ptr; - __pyx_t_7sklearn_4tree_5_tree_BOOL_t *__pyx_v_sample_mask_ptr; - int __pyx_v_X_stride; - int __pyx_v_X_argsorted_stride; - int __pyx_v_y_stride; - int __pyx_v_n_total_samples; - int __pyx_v_feature; - double __pyx_v_threshold; - double __pyx_v_best_error; - double __pyx_v_init_error; - int __pyx_v_i; - PyArrayObject *__pyx_v_sample_mask_left = 0; - PyArrayObject *__pyx_v_sample_mask_right = 0; - int __pyx_v_n_node_samples_left; - int __pyx_v_n_node_samples_right; - int __pyx_v_node_id; - __Pyx_LocalBuf_ND __pyx_pybuffernd_X; - __Pyx_Buffer __pyx_pybuffer_X; - __Pyx_LocalBuf_ND __pyx_pybuffernd_X_argsorted; - __Pyx_Buffer __pyx_pybuffer_X_argsorted; - __Pyx_LocalBuf_ND __pyx_pybuffernd_y; - __Pyx_Buffer __pyx_pybuffer_y; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - PyArrayObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - PyObject *__pyx_t_13 = NULL; - PyObject *__pyx_t_14 = NULL; - PyArrayObject *__pyx_t_15 = NULL; - PyArrayObject *__pyx_t_16 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("recursive_partition", 0); - __Pyx_INCREF((PyObject *)__pyx_v_X); - __Pyx_INCREF((PyObject *)__pyx_v_X_argsorted); - __Pyx_INCREF((PyObject *)__pyx_v_y); - __Pyx_INCREF((PyObject *)__pyx_v_sample_mask); - __pyx_pybuffer_X.pybuffer.buf = NULL; - __pyx_pybuffer_X.refcount = 0; - __pyx_pybuffernd_X.data = NULL; - __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; - __pyx_pybuffer_X_argsorted.pybuffer.buf = NULL; - __pyx_pybuffer_X_argsorted.refcount = 0; - __pyx_pybuffernd_X_argsorted.data = NULL; - __pyx_pybuffernd_X_argsorted.rcbuffer = &__pyx_pybuffer_X_argsorted; - __pyx_pybuffer_y.pybuffer.buf = NULL; - __pyx_pybuffer_y.refcount = 0; - __pyx_pybuffernd_y.data = NULL; - __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DTYPE_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer, (PyObject*)__pyx_v_X_argsorted, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_X_argsorted.diminfo[0].strides = __pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_argsorted.diminfo[0].shape = __pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X_argsorted.diminfo[1].strides = __pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X_argsorted.diminfo[1].shape = __pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer.shape[1]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DOUBLE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_y.diminfo[1].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_y.diminfo[1].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[1]; - - /* "sklearn/tree/_tree.pyx":422 - * """Recursive partition algorithm for the tree construction.""" - * # Variables - * cdef Criterion criterion = self.criterion # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":578 + * self.y = NULL + * self.y_stride = 0 + * self.sample_weight = NULL # <<<<<<<<<<<<<< * - * cdef DTYPE_t* X_ptr = X.data + * self.samples = NULL */ - __Pyx_INCREF(((PyObject *)__pyx_v_self->criterion)); - __pyx_v_criterion = __pyx_v_self->criterion; + __pyx_v_self->__pyx_base.sample_weight = NULL; - /* "sklearn/tree/_tree.pyx":424 - * cdef Criterion criterion = self.criterion + /* "sklearn/tree/_tree.pyx":580 + * self.sample_weight = NULL * - * cdef DTYPE_t* X_ptr = X.data # <<<<<<<<<<<<<< - * cdef int* X_argsorted_ptr = X_argsorted.data - * cdef DOUBLE_t* y_ptr = y.data + * self.samples = NULL # <<<<<<<<<<<<<< + * self.start = 0 + * self.pos = 0 */ - __pyx_v_X_ptr = ((__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *)__pyx_v_X->data); + __pyx_v_self->__pyx_base.samples = NULL; - /* "sklearn/tree/_tree.pyx":425 + /* "sklearn/tree/_tree.pyx":581 * - * cdef DTYPE_t* X_ptr = X.data - * cdef int* X_argsorted_ptr = X_argsorted.data # <<<<<<<<<<<<<< - * cdef DOUBLE_t* y_ptr = y.data - * cdef BOOL_t* sample_mask_ptr = sample_mask.data + * self.samples = NULL + * self.start = 0 # <<<<<<<<<<<<<< + * self.pos = 0 + * self.end = 0 */ - __pyx_v_X_argsorted_ptr = ((int *)__pyx_v_X_argsorted->data); + __pyx_v_self->__pyx_base.start = 0; - /* "sklearn/tree/_tree.pyx":426 - * cdef DTYPE_t* X_ptr = X.data - * cdef int* X_argsorted_ptr = X_argsorted.data - * cdef DOUBLE_t* y_ptr = y.data # <<<<<<<<<<<<<< - * cdef BOOL_t* sample_mask_ptr = sample_mask.data + /* "sklearn/tree/_tree.pyx":582 + * self.samples = NULL + * self.start = 0 + * self.pos = 0 # <<<<<<<<<<<<<< + * self.end = 0 * */ - __pyx_v_y_ptr = ((__pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *)__pyx_v_y->data); + __pyx_v_self->__pyx_base.pos = 0; - /* "sklearn/tree/_tree.pyx":427 - * cdef int* X_argsorted_ptr = X_argsorted.data - * cdef DOUBLE_t* y_ptr = y.data - * cdef BOOL_t* sample_mask_ptr = sample_mask.data # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":583 + * self.start = 0 + * self.pos = 0 + * self.end = 0 # <<<<<<<<<<<<<< * - * cdef int X_stride = X.strides[1] / X.strides[0] + * self.n_outputs = n_outputs */ - __pyx_v_sample_mask_ptr = ((__pyx_t_7sklearn_4tree_5_tree_BOOL_t *)__pyx_v_sample_mask->data); + __pyx_v_self->__pyx_base.end = 0; - /* "sklearn/tree/_tree.pyx":429 - * cdef BOOL_t* sample_mask_ptr = sample_mask.data + /* "sklearn/tree/_tree.pyx":585 + * self.end = 0 * - * cdef int X_stride = X.strides[1] / X.strides[0] # <<<<<<<<<<<<<< - * cdef int X_argsorted_stride = X_argsorted.strides[1] / X_argsorted.strides[0] - * cdef int y_stride = y.strides[0] / y.strides[1] + * self.n_outputs = n_outputs # <<<<<<<<<<<<<< + * self.n_node_samples = 0 + * self.weighted_n_node_samples = 0.0 */ - __pyx_v_X_stride = (((int)(__pyx_v_X->strides[1])) / ((int)(__pyx_v_X->strides[0]))); + __pyx_v_self->__pyx_base.n_outputs = __pyx_v_n_outputs; - /* "sklearn/tree/_tree.pyx":430 - * - * cdef int X_stride = X.strides[1] / X.strides[0] - * cdef int X_argsorted_stride = X_argsorted.strides[1] / X_argsorted.strides[0] # <<<<<<<<<<<<<< - * cdef int y_stride = y.strides[0] / y.strides[1] + /* "sklearn/tree/_tree.pyx":586 * + * self.n_outputs = n_outputs + * self.n_node_samples = 0 # <<<<<<<<<<<<<< + * self.weighted_n_node_samples = 0.0 + * self.weighted_n_left = 0.0 */ - __pyx_v_X_argsorted_stride = (((int)(__pyx_v_X_argsorted->strides[1])) / ((int)(__pyx_v_X_argsorted->strides[0]))); + __pyx_v_self->__pyx_base.n_node_samples = 0; - /* "sklearn/tree/_tree.pyx":431 - * cdef int X_stride = X.strides[1] / X.strides[0] - * cdef int X_argsorted_stride = X_argsorted.strides[1] / X_argsorted.strides[0] - * cdef int y_stride = y.strides[0] / y.strides[1] # <<<<<<<<<<<<<< - * - * cdef int n_total_samples = y.shape[0] + /* "sklearn/tree/_tree.pyx":587 + * self.n_outputs = n_outputs + * self.n_node_samples = 0 + * self.weighted_n_node_samples = 0.0 # <<<<<<<<<<<<<< + * self.weighted_n_left = 0.0 + * self.weighted_n_right = 0.0 */ - __pyx_v_y_stride = (((int)(__pyx_v_y->strides[0])) / ((int)(__pyx_v_y->strides[1]))); + __pyx_v_self->__pyx_base.weighted_n_node_samples = 0.0; - /* "sklearn/tree/_tree.pyx":433 - * cdef int y_stride = y.strides[0] / y.strides[1] + /* "sklearn/tree/_tree.pyx":588 + * self.n_node_samples = 0 + * self.weighted_n_node_samples = 0.0 + * self.weighted_n_left = 0.0 # <<<<<<<<<<<<<< + * self.weighted_n_right = 0.0 * - * cdef int n_total_samples = y.shape[0] # <<<<<<<<<<<<<< - * cdef int feature - * cdef double threshold */ - __pyx_v_n_total_samples = (__pyx_v_y->dimensions[0]); + __pyx_v_self->__pyx_base.weighted_n_left = 0.0; - /* "sklearn/tree/_tree.pyx":446 + /* "sklearn/tree/_tree.pyx":589 + * self.weighted_n_node_samples = 0.0 + * self.weighted_n_left = 0.0 + * self.weighted_n_right = 0.0 # <<<<<<<<<<<<<< * - * # Count samples - * if n_node_samples == 0: # <<<<<<<<<<<<<< - * raise ValueError("Attempting to find a split " - * "with an empty sample_mask") + * # Allocate accumulators. Make sure they are NULL, not uninitialized, */ - __pyx_t_1 = (__pyx_v_n_node_samples == 0); - if (__pyx_t_1) { + __pyx_v_self->__pyx_base.weighted_n_right = 0.0; - /* "sklearn/tree/_tree.pyx":447 - * # Count samples - * if n_node_samples == 0: - * raise ValueError("Attempting to find a split " # <<<<<<<<<<<<<< - * "with an empty sample_mask") - * + /* "sklearn/tree/_tree.pyx":593 + * # Allocate accumulators. Make sure they are NULL, not uninitialized, + * # before an exception can be raised (which triggers __dealloc__). + * self.mean_left = NULL # <<<<<<<<<<<<<< + * self.mean_right = NULL + * self.mean_total = NULL */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; - } - __pyx_L3:; + __pyx_v_self->mean_left = NULL; - /* "sklearn/tree/_tree.pyx":451 - * - * # Split samples - * if depth < self.max_depth and \ # <<<<<<<<<<<<<< - * n_node_samples >= self.min_samples_split and \ - * n_node_samples >= 2 * self.min_samples_leaf: + /* "sklearn/tree/_tree.pyx":594 + * # before an exception can be raised (which triggers __dealloc__). + * self.mean_left = NULL + * self.mean_right = NULL # <<<<<<<<<<<<<< + * self.mean_total = NULL + * self.sq_sum_left = NULL */ - __pyx_t_1 = (__pyx_v_depth < __pyx_v_self->max_depth); - if (__pyx_t_1) { + __pyx_v_self->mean_right = NULL; - /* "sklearn/tree/_tree.pyx":452 - * # Split samples - * if depth < self.max_depth and \ - * n_node_samples >= self.min_samples_split and \ # <<<<<<<<<<<<<< - * n_node_samples >= 2 * self.min_samples_leaf: - * self.find_split(X_ptr, X_stride, + /* "sklearn/tree/_tree.pyx":595 + * self.mean_left = NULL + * self.mean_right = NULL + * self.mean_total = NULL # <<<<<<<<<<<<<< + * self.sq_sum_left = NULL + * self.sq_sum_right = NULL */ - __pyx_t_3 = (__pyx_v_n_node_samples >= __pyx_v_self->min_samples_split); - if (__pyx_t_3) { + __pyx_v_self->mean_total = NULL; - /* "sklearn/tree/_tree.pyx":453 - * if depth < self.max_depth and \ - * n_node_samples >= self.min_samples_split and \ - * n_node_samples >= 2 * self.min_samples_leaf: # <<<<<<<<<<<<<< - * self.find_split(X_ptr, X_stride, - * X_argsorted_ptr, X_argsorted_stride, + /* "sklearn/tree/_tree.pyx":596 + * self.mean_right = NULL + * self.mean_total = NULL + * self.sq_sum_left = NULL # <<<<<<<<<<<<<< + * self.sq_sum_right = NULL + * self.sq_sum_total = NULL */ - __pyx_t_4 = (__pyx_v_n_node_samples >= (2 * __pyx_v_self->min_samples_leaf)); - __pyx_t_5 = __pyx_t_4; - } else { - __pyx_t_5 = __pyx_t_3; - } - __pyx_t_3 = __pyx_t_5; - } else { - __pyx_t_3 = __pyx_t_1; - } - if (__pyx_t_3) { + __pyx_v_self->sq_sum_left = NULL; - /* "sklearn/tree/_tree.pyx":460 - * n_node_samples, - * n_total_samples, - * &feature, &threshold, &best_error, &init_error) # <<<<<<<<<<<<<< - * - * else: + /* "sklearn/tree/_tree.pyx":597 + * self.mean_total = NULL + * self.sq_sum_left = NULL + * self.sq_sum_right = NULL # <<<<<<<<<<<<<< + * self.sq_sum_total = NULL + * self.var_left = NULL */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->find_split(__pyx_v_self, __pyx_v_X_ptr, __pyx_v_X_stride, __pyx_v_X_argsorted_ptr, __pyx_v_X_argsorted_stride, __pyx_v_y_ptr, __pyx_v_y_stride, __pyx_v_sample_mask_ptr, __pyx_v_n_node_samples, __pyx_v_n_total_samples, (&__pyx_v_feature), (&__pyx_v_threshold), (&__pyx_v_best_error), (&__pyx_v_init_error)); - goto __pyx_L4; - } - /*else*/ { + __pyx_v_self->sq_sum_right = NULL; - /* "sklearn/tree/_tree.pyx":463 - * - * else: - * feature = -1 # <<<<<<<<<<<<<< - * criterion.init(y_ptr, y_stride, sample_mask_ptr, n_node_samples, n_total_samples) - * init_error = criterion.eval() + /* "sklearn/tree/_tree.pyx":598 + * self.sq_sum_left = NULL + * self.sq_sum_right = NULL + * self.sq_sum_total = NULL # <<<<<<<<<<<<<< + * self.var_left = NULL + * self.var_right = NULL */ - __pyx_v_feature = -1; + __pyx_v_self->sq_sum_total = NULL; - /* "sklearn/tree/_tree.pyx":464 - * else: - * feature = -1 - * criterion.init(y_ptr, y_stride, sample_mask_ptr, n_node_samples, n_total_samples) # <<<<<<<<<<<<<< - * init_error = criterion.eval() - * + /* "sklearn/tree/_tree.pyx":599 + * self.sq_sum_right = NULL + * self.sq_sum_total = NULL + * self.var_left = NULL # <<<<<<<<<<<<<< + * self.var_right = NULL + * self.sum_left = NULL */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->init(__pyx_v_criterion, __pyx_v_y_ptr, __pyx_v_y_stride, __pyx_v_sample_mask_ptr, __pyx_v_n_node_samples, __pyx_v_n_total_samples); + __pyx_v_self->var_left = NULL; - /* "sklearn/tree/_tree.pyx":465 - * feature = -1 - * criterion.init(y_ptr, y_stride, sample_mask_ptr, n_node_samples, n_total_samples) - * init_error = criterion.eval() # <<<<<<<<<<<<<< - * - * criterion.init_value(buffer_value) + /* "sklearn/tree/_tree.pyx":600 + * self.sq_sum_total = NULL + * self.var_left = NULL + * self.var_right = NULL # <<<<<<<<<<<<<< + * self.sum_left = NULL + * self.sum_right = NULL */ - __pyx_v_init_error = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->eval(__pyx_v_criterion); - } - __pyx_L4:; + __pyx_v_self->var_right = NULL; - /* "sklearn/tree/_tree.pyx":467 - * init_error = criterion.eval() - * - * criterion.init_value(buffer_value) # <<<<<<<<<<<<<< - * - * # Current node is leaf + /* "sklearn/tree/_tree.pyx":601 + * self.var_left = NULL + * self.var_right = NULL + * self.sum_left = NULL # <<<<<<<<<<<<<< + * self.sum_right = NULL + * self.sum_total = NULL */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->init_value(__pyx_v_criterion, __pyx_v_buffer_value); + __pyx_v_self->sum_left = NULL; - /* "sklearn/tree/_tree.pyx":470 + /* "sklearn/tree/_tree.pyx":602 + * self.var_right = NULL + * self.sum_left = NULL + * self.sum_right = NULL # <<<<<<<<<<<<<< + * self.sum_total = NULL * - * # Current node is leaf - * if feature == -1: # <<<<<<<<<<<<<< - * self.add_leaf(parent, is_left_child, buffer_value, init_error, n_node_samples) + */ + __pyx_v_self->sum_right = NULL; + + /* "sklearn/tree/_tree.pyx":603 + * self.sum_left = NULL + * self.sum_right = NULL + * self.sum_total = NULL # <<<<<<<<<<<<<< * + * self.mean_left = calloc(n_outputs, sizeof(double)) */ - __pyx_t_3 = (__pyx_v_feature == -1); - if (__pyx_t_3) { + __pyx_v_self->sum_total = NULL; - /* "sklearn/tree/_tree.pyx":471 - * # Current node is leaf - * if feature == -1: - * self.add_leaf(parent, is_left_child, buffer_value, init_error, n_node_samples) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":605 + * self.sum_total = NULL * - * # Current node is internal node (= split node) + * self.mean_left = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< + * self.mean_right = calloc(n_outputs, sizeof(double)) + * self.mean_total = calloc(n_outputs, sizeof(double)) */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->add_leaf(__pyx_v_self, __pyx_v_parent, __pyx_v_is_left_child, __pyx_v_buffer_value, __pyx_v_init_error, __pyx_v_n_node_samples); - goto __pyx_L5; - } - /*else*/ { + __pyx_v_self->mean_left = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":476 - * else: - * # Sample mask is too sparse? - * if 1. * n_node_samples / n_total_samples <= self.min_density: # <<<<<<<<<<<<<< - * X = X[sample_mask] - * X_argsorted = np.asfortranarray(np.argsort(X.T, axis=1).astype(np.int32).T) + /* "sklearn/tree/_tree.pyx":606 + * + * self.mean_left = calloc(n_outputs, sizeof(double)) + * self.mean_right = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< + * self.mean_total = calloc(n_outputs, sizeof(double)) + * self.sq_sum_left = calloc(n_outputs, sizeof(double)) */ - __pyx_t_3 = (((1. * __pyx_v_n_node_samples) / __pyx_v_n_total_samples) <= __pyx_v_self->min_density); - if (__pyx_t_3) { + __pyx_v_self->mean_right = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":477 - * # Sample mask is too sparse? - * if 1. * n_node_samples / n_total_samples <= self.min_density: - * X = X[sample_mask] # <<<<<<<<<<<<<< - * X_argsorted = np.asfortranarray(np.argsort(X.T, axis=1).astype(np.int32).T) - * y = y[sample_mask] + /* "sklearn/tree/_tree.pyx":607 + * self.mean_left = calloc(n_outputs, sizeof(double)) + * self.mean_right = calloc(n_outputs, sizeof(double)) + * self.mean_total = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< + * self.sq_sum_left = calloc(n_outputs, sizeof(double)) + * self.sq_sum_right = calloc(n_outputs, sizeof(double)) */ - __pyx_t_2 = PyObject_GetItem(((PyObject *)__pyx_v_X), ((PyObject *)__pyx_v_sample_mask)); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 477; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 477; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DTYPE_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DTYPE_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); - } - } - __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 477; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_X)); - __pyx_v_X = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; + __pyx_v_self->mean_total = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":478 - * if 1. * n_node_samples / n_total_samples <= self.min_density: - * X = X[sample_mask] - * X_argsorted = np.asfortranarray(np.argsort(X.T, axis=1).astype(np.int32).T) # <<<<<<<<<<<<<< - * y = y[sample_mask] - * sample_mask = np.ones((n_node_samples, ), dtype=np.bool) + /* "sklearn/tree/_tree.pyx":608 + * self.mean_right = calloc(n_outputs, sizeof(double)) + * self.mean_total = calloc(n_outputs, sizeof(double)) + * self.sq_sum_left = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< + * self.sq_sum_right = calloc(n_outputs, sizeof(double)) + * self.sq_sum_total = calloc(n_outputs, sizeof(double)) */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_11 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__asfortranarray); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_12 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__argsort); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_X), __pyx_n_s__T); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_13 = PyTuple_New(1); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_13); - PyTuple_SET_ITEM(__pyx_t_13, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__axis), __pyx_int_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_14 = PyObject_Call(__pyx_t_12, ((PyObject *)__pyx_t_13), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_14); - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_13)); __pyx_t_13 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetAttr(__pyx_t_14, __pyx_n_s__astype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; - __pyx_t_14 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_14); - __pyx_t_13 = PyObject_GetAttr(__pyx_t_14, __pyx_n_s__int32); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_13); - __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; - __pyx_t_14 = PyTuple_New(1); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_14); - PyTuple_SET_ITEM(__pyx_t_14, 0, __pyx_t_13); - __Pyx_GIVEREF(__pyx_t_13); - __pyx_t_13 = 0; - __pyx_t_13 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_14), NULL); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_13); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_14)); __pyx_t_14 = 0; - __pyx_t_14 = PyObject_GetAttr(__pyx_t_13, __pyx_n_s__T); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_14); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - __pyx_t_13 = PyTuple_New(1); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_13); - PyTuple_SET_ITEM(__pyx_t_13, 0, __pyx_t_14); - __Pyx_GIVEREF(__pyx_t_14); - __pyx_t_14 = 0; - __pyx_t_14 = PyObject_Call(__pyx_t_11, ((PyObject *)__pyx_t_13), NULL); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_14); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_13)); __pyx_t_13 = 0; - if (!(likely(((__pyx_t_14) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_14, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_15 = ((PyArrayObject *)__pyx_t_14); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer, (PyObject*)__pyx_t_15, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_10, &__pyx_t_9, &__pyx_t_8); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer, (PyObject*)__pyx_v_X_argsorted, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_F_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_8); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_10, __pyx_t_9, __pyx_t_8); - } - } - __pyx_pybuffernd_X_argsorted.diminfo[0].strides = __pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_argsorted.diminfo[0].shape = __pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X_argsorted.diminfo[1].strides = __pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X_argsorted.diminfo[1].shape = __pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_15 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_X_argsorted)); - __pyx_v_X_argsorted = ((PyArrayObject *)__pyx_t_14); - __pyx_t_14 = 0; - - /* "sklearn/tree/_tree.pyx":479 - * X = X[sample_mask] - * X_argsorted = np.asfortranarray(np.argsort(X.T, axis=1).astype(np.int32).T) - * y = y[sample_mask] # <<<<<<<<<<<<<< - * sample_mask = np.ones((n_node_samples, ), dtype=np.bool) - * - */ - __pyx_t_14 = PyObject_GetItem(((PyObject *)__pyx_v_y), ((PyObject *)__pyx_v_sample_mask)); if (!__pyx_t_14) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_14); - if (!(likely(((__pyx_t_14) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_14, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_16 = ((PyArrayObject *)__pyx_t_14); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_t_16, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DOUBLE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DOUBLE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); - } - } - __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_y.diminfo[1].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_y.diminfo[1].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[1]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_16 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_y)); - __pyx_v_y = ((PyArrayObject *)__pyx_t_14); - __pyx_t_14 = 0; - - /* "sklearn/tree/_tree.pyx":480 - * X_argsorted = np.asfortranarray(np.argsort(X.T, axis=1).astype(np.int32).T) - * y = y[sample_mask] - * sample_mask = np.ones((n_node_samples, ), dtype=np.bool) # <<<<<<<<<<<<<< - * - * n_total_samples = n_node_samples - */ - __pyx_t_14 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_14); - __pyx_t_13 = PyObject_GetAttr(__pyx_t_14, __pyx_n_s__ones); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_13); - __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; - __pyx_t_14 = PyInt_FromLong(__pyx_v_n_node_samples); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_14); - __pyx_t_11 = PyTuple_New(1); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_14); - __Pyx_GIVEREF(__pyx_t_14); - __pyx_t_14 = 0; - __pyx_t_14 = PyTuple_New(1); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_14); - PyTuple_SET_ITEM(__pyx_t_14, 0, ((PyObject *)__pyx_t_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_11)); - __pyx_t_11 = 0; - __pyx_t_11 = PyDict_New(); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_11)); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_12 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__bool); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_t_11, ((PyObject *)__pyx_n_s__dtype), __pyx_t_12) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - __pyx_t_12 = PyObject_Call(__pyx_t_13, ((PyObject *)__pyx_t_14), ((PyObject *)__pyx_t_11)); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_14)); __pyx_t_14 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_11)); __pyx_t_11 = 0; - if (!(likely(((__pyx_t_12) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_12, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_v_sample_mask)); - __pyx_v_sample_mask = ((PyArrayObject *)__pyx_t_12); - __pyx_t_12 = 0; + __pyx_v_self->sq_sum_left = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":482 - * sample_mask = np.ones((n_node_samples, ), dtype=np.bool) - * - * n_total_samples = n_node_samples # <<<<<<<<<<<<<< - * - * X_ptr = X.data + /* "sklearn/tree/_tree.pyx":609 + * self.mean_total = calloc(n_outputs, sizeof(double)) + * self.sq_sum_left = calloc(n_outputs, sizeof(double)) + * self.sq_sum_right = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< + * self.sq_sum_total = calloc(n_outputs, sizeof(double)) + * self.var_left = calloc(n_outputs, sizeof(double)) */ - __pyx_v_n_total_samples = __pyx_v_n_node_samples; + __pyx_v_self->sq_sum_right = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":484 - * n_total_samples = n_node_samples - * - * X_ptr = X.data # <<<<<<<<<<<<<< - * X_stride = X.strides[1] / X.strides[0] - * sample_mask_ptr = sample_mask.data + /* "sklearn/tree/_tree.pyx":610 + * self.sq_sum_left = calloc(n_outputs, sizeof(double)) + * self.sq_sum_right = calloc(n_outputs, sizeof(double)) + * self.sq_sum_total = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< + * self.var_left = calloc(n_outputs, sizeof(double)) + * self.var_right = calloc(n_outputs, sizeof(double)) */ - __pyx_v_X_ptr = ((__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *)__pyx_v_X->data); + __pyx_v_self->sq_sum_total = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":485 - * - * X_ptr = X.data - * X_stride = X.strides[1] / X.strides[0] # <<<<<<<<<<<<<< - * sample_mask_ptr = sample_mask.data - * + /* "sklearn/tree/_tree.pyx":611 + * self.sq_sum_right = calloc(n_outputs, sizeof(double)) + * self.sq_sum_total = calloc(n_outputs, sizeof(double)) + * self.var_left = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< + * self.var_right = calloc(n_outputs, sizeof(double)) + * self.sum_left = calloc(n_outputs, sizeof(double)) */ - __pyx_v_X_stride = (((int)(__pyx_v_X->strides[1])) / ((int)(__pyx_v_X->strides[0]))); + __pyx_v_self->var_left = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":486 - * X_ptr = X.data - * X_stride = X.strides[1] / X.strides[0] - * sample_mask_ptr = sample_mask.data # <<<<<<<<<<<<<< - * - * # !! No need to update the other variables + /* "sklearn/tree/_tree.pyx":612 + * self.sq_sum_total = calloc(n_outputs, sizeof(double)) + * self.var_left = calloc(n_outputs, sizeof(double)) + * self.var_right = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< + * self.sum_left = calloc(n_outputs, sizeof(double)) + * self.sum_right = calloc(n_outputs, sizeof(double)) */ - __pyx_v_sample_mask_ptr = ((__pyx_t_7sklearn_4tree_5_tree_BOOL_t *)__pyx_v_sample_mask->data); - goto __pyx_L6; - } - __pyx_L6:; + __pyx_v_self->var_right = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":495 - * - * # Split - * X_ptr = X_ptr + feature * X_stride # <<<<<<<<<<<<<< - * sample_mask_left = np.zeros((n_total_samples, ), dtype=np.bool) - * sample_mask_right = np.zeros((n_total_samples, ), dtype=np.bool) - */ - __pyx_v_X_ptr = (__pyx_v_X_ptr + (__pyx_v_feature * __pyx_v_X_stride)); - - /* "sklearn/tree/_tree.pyx":496 - * # Split - * X_ptr = X_ptr + feature * X_stride - * sample_mask_left = np.zeros((n_total_samples, ), dtype=np.bool) # <<<<<<<<<<<<<< - * sample_mask_right = np.zeros((n_total_samples, ), dtype=np.bool) - * n_node_samples_left = 0 - */ - __pyx_t_12 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_12); - __pyx_t_11 = PyObject_GetAttr(__pyx_t_12, __pyx_n_s__zeros); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - __pyx_t_12 = PyInt_FromLong(__pyx_v_n_total_samples); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_12); - __pyx_t_14 = PyTuple_New(1); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_14); - PyTuple_SET_ITEM(__pyx_t_14, 0, __pyx_t_12); - __Pyx_GIVEREF(__pyx_t_12); - __pyx_t_12 = 0; - __pyx_t_12 = PyTuple_New(1); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_12); - PyTuple_SET_ITEM(__pyx_t_12, 0, ((PyObject *)__pyx_t_14)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_14)); - __pyx_t_14 = 0; - __pyx_t_14 = PyDict_New(); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_14)); - __pyx_t_13 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_13); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_13, __pyx_n_s__bool); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - if (PyDict_SetItem(__pyx_t_14, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_11, ((PyObject *)__pyx_t_12), ((PyObject *)__pyx_t_14)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_12)); __pyx_t_12 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_14)); __pyx_t_14 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_sample_mask_left = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; + /* "sklearn/tree/_tree.pyx":613 + * self.var_left = calloc(n_outputs, sizeof(double)) + * self.var_right = calloc(n_outputs, sizeof(double)) + * self.sum_left = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< + * self.sum_right = calloc(n_outputs, sizeof(double)) + * self.sum_total = calloc(n_outputs, sizeof(double)) + */ + __pyx_v_self->sum_left = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":497 - * X_ptr = X_ptr + feature * X_stride - * sample_mask_left = np.zeros((n_total_samples, ), dtype=np.bool) - * sample_mask_right = np.zeros((n_total_samples, ), dtype=np.bool) # <<<<<<<<<<<<<< - * n_node_samples_left = 0 - * n_node_samples_right = 0 + /* "sklearn/tree/_tree.pyx":614 + * self.var_right = calloc(n_outputs, sizeof(double)) + * self.sum_left = calloc(n_outputs, sizeof(double)) + * self.sum_right = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< + * self.sum_total = calloc(n_outputs, sizeof(double)) + * */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_14 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__zeros); if (unlikely(!__pyx_t_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_14); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyInt_FromLong(__pyx_v_n_total_samples); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_12 = PyTuple_New(1); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_12); - PyTuple_SET_ITEM(__pyx_t_12, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_12)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_12)); - __pyx_t_12 = 0; - __pyx_t_12 = PyDict_New(); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_12)); - __pyx_t_11 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_13 = PyObject_GetAttr(__pyx_t_11, __pyx_n_s__bool); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_13); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - if (PyDict_SetItem(__pyx_t_12, ((PyObject *)__pyx_n_s__dtype), __pyx_t_13) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - __pyx_t_13 = PyObject_Call(__pyx_t_14, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_12)); if (unlikely(!__pyx_t_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_13); - __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_12)); __pyx_t_12 = 0; - if (!(likely(((__pyx_t_13) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_13, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_sample_mask_right = ((PyArrayObject *)__pyx_t_13); - __pyx_t_13 = 0; - - /* "sklearn/tree/_tree.pyx":498 - * sample_mask_left = np.zeros((n_total_samples, ), dtype=np.bool) - * sample_mask_right = np.zeros((n_total_samples, ), dtype=np.bool) - * n_node_samples_left = 0 # <<<<<<<<<<<<<< - * n_node_samples_right = 0 - * - */ - __pyx_v_n_node_samples_left = 0; - - /* "sklearn/tree/_tree.pyx":499 - * sample_mask_right = np.zeros((n_total_samples, ), dtype=np.bool) - * n_node_samples_left = 0 - * n_node_samples_right = 0 # <<<<<<<<<<<<<< - * - * for i from 0 <= i < n_total_samples: - */ - __pyx_v_n_node_samples_right = 0; + __pyx_v_self->sum_right = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":501 - * n_node_samples_right = 0 + /* "sklearn/tree/_tree.pyx":615 + * self.sum_left = calloc(n_outputs, sizeof(double)) + * self.sum_right = calloc(n_outputs, sizeof(double)) + * self.sum_total = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< * - * for i from 0 <= i < n_total_samples: # <<<<<<<<<<<<<< - * if sample_mask_ptr[i]: - * if X_ptr[i] <= threshold: + * if (self.mean_left == NULL or */ - __pyx_t_7 = __pyx_v_n_total_samples; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_7; __pyx_v_i++) { + __pyx_v_self->sum_total = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":502 + /* "sklearn/tree/_tree.pyx":617 + * self.sum_total = calloc(n_outputs, sizeof(double)) * - * for i from 0 <= i < n_total_samples: - * if sample_mask_ptr[i]: # <<<<<<<<<<<<<< - * if X_ptr[i] <= threshold: - * sample_mask_left[i] = 1 + * if (self.mean_left == NULL or # <<<<<<<<<<<<<< + * self.mean_right == NULL or + * self.mean_total == NULL or */ - if ((__pyx_v_sample_mask_ptr[__pyx_v_i])) { + __pyx_t_2 = ((__pyx_v_self->mean_left == NULL) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":503 - * for i from 0 <= i < n_total_samples: - * if sample_mask_ptr[i]: - * if X_ptr[i] <= threshold: # <<<<<<<<<<<<<< - * sample_mask_left[i] = 1 - * n_node_samples_left += 1 + /* "sklearn/tree/_tree.pyx":618 + * + * if (self.mean_left == NULL or + * self.mean_right == NULL or # <<<<<<<<<<<<<< + * self.mean_total == NULL or + * self.sq_sum_left == NULL or */ - __pyx_t_3 = ((__pyx_v_X_ptr[__pyx_v_i]) <= __pyx_v_threshold); - if (__pyx_t_3) { + __pyx_t_2 = ((__pyx_v_self->mean_right == NULL) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":504 - * if sample_mask_ptr[i]: - * if X_ptr[i] <= threshold: - * sample_mask_left[i] = 1 # <<<<<<<<<<<<<< - * n_node_samples_left += 1 - * else: + /* "sklearn/tree/_tree.pyx":619 + * if (self.mean_left == NULL or + * self.mean_right == NULL or + * self.mean_total == NULL or # <<<<<<<<<<<<<< + * self.sq_sum_left == NULL or + * self.sq_sum_right == NULL or */ - if (__Pyx_SetItemInt(((PyObject *)__pyx_v_sample_mask_left), __pyx_v_i, __pyx_int_1, sizeof(int), PyInt_FromLong) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 504; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((__pyx_v_self->mean_total == NULL) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":505 - * if X_ptr[i] <= threshold: - * sample_mask_left[i] = 1 - * n_node_samples_left += 1 # <<<<<<<<<<<<<< - * else: - * sample_mask_right[i] = 1 + /* "sklearn/tree/_tree.pyx":620 + * self.mean_right == NULL or + * self.mean_total == NULL or + * self.sq_sum_left == NULL or # <<<<<<<<<<<<<< + * self.sq_sum_right == NULL or + * self.sq_sum_total == NULL or */ - __pyx_v_n_node_samples_left = (__pyx_v_n_node_samples_left + 1); - goto __pyx_L10; - } - /*else*/ { + __pyx_t_2 = ((__pyx_v_self->sq_sum_left == NULL) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":507 - * n_node_samples_left += 1 - * else: - * sample_mask_right[i] = 1 # <<<<<<<<<<<<<< - * n_node_samples_right += 1 - * + /* "sklearn/tree/_tree.pyx":621 + * self.mean_total == NULL or + * self.sq_sum_left == NULL or + * self.sq_sum_right == NULL or # <<<<<<<<<<<<<< + * self.sq_sum_total == NULL or + * self.var_left == NULL or */ - if (__Pyx_SetItemInt(((PyObject *)__pyx_v_sample_mask_right), __pyx_v_i, __pyx_int_1, sizeof(int), PyInt_FromLong) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((__pyx_v_self->sq_sum_right == NULL) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":508 - * else: - * sample_mask_right[i] = 1 - * n_node_samples_right += 1 # <<<<<<<<<<<<<< - * - * node_id = self.add_split_node(parent, is_left_child, feature, + /* "sklearn/tree/_tree.pyx":622 + * self.sq_sum_left == NULL or + * self.sq_sum_right == NULL or + * self.sq_sum_total == NULL or # <<<<<<<<<<<<<< + * self.var_left == NULL or + * self.var_right == NULL or */ - __pyx_v_n_node_samples_right = (__pyx_v_n_node_samples_right + 1); - } - __pyx_L10:; - goto __pyx_L9; - } - __pyx_L9:; - } + __pyx_t_2 = ((__pyx_v_self->sq_sum_total == NULL) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":512 - * node_id = self.add_split_node(parent, is_left_child, feature, - * threshold, buffer_value, best_error, - * init_error, n_node_samples) # <<<<<<<<<<<<<< - * - * # Left child recursion + /* "sklearn/tree/_tree.pyx":623 + * self.sq_sum_right == NULL or + * self.sq_sum_total == NULL or + * self.var_left == NULL or # <<<<<<<<<<<<<< + * self.var_right == NULL or + * self.sum_left == NULL or */ - __pyx_v_node_id = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->add_split_node(__pyx_v_self, __pyx_v_parent, __pyx_v_is_left_child, __pyx_v_feature, __pyx_v_threshold, __pyx_v_buffer_value, __pyx_v_best_error, __pyx_v_init_error, __pyx_v_n_node_samples); + __pyx_t_2 = ((__pyx_v_self->var_left == NULL) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":517 - * self.recursive_partition(X, X_argsorted, y, sample_mask_left, - * n_node_samples_left, depth + 1, node_id, - * True, buffer_value) # <<<<<<<<<<<<<< - * - * # Right child recursion + /* "sklearn/tree/_tree.pyx":624 + * self.sq_sum_total == NULL or + * self.var_left == NULL or + * self.var_right == NULL or # <<<<<<<<<<<<<< + * self.sum_left == NULL or + * self.sum_right == NULL or */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->recursive_partition(__pyx_v_self, ((PyArrayObject *)__pyx_v_X), ((PyArrayObject *)__pyx_v_X_argsorted), ((PyArrayObject *)__pyx_v_y), __pyx_v_sample_mask_left, __pyx_v_n_node_samples_left, (__pyx_v_depth + 1), __pyx_v_node_id, 1, __pyx_v_buffer_value); + __pyx_t_2 = ((__pyx_v_self->var_right == NULL) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":522 - * self.recursive_partition(X, X_argsorted, y, sample_mask_right, - * n_node_samples_right, depth + 1, node_id, - * False, buffer_value) # <<<<<<<<<<<<<< - * - * cdef int add_split_node(self, int parent, int is_left_child, int feature, + /* "sklearn/tree/_tree.pyx":625 + * self.var_left == NULL or + * self.var_right == NULL or + * self.sum_left == NULL or # <<<<<<<<<<<<<< + * self.sum_right == NULL or + * self.sum_total == NULL): */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->recursive_partition(__pyx_v_self, ((PyArrayObject *)__pyx_v_X), ((PyArrayObject *)__pyx_v_X_argsorted), ((PyArrayObject *)__pyx_v_y), __pyx_v_sample_mask_right, __pyx_v_n_node_samples_right, (__pyx_v_depth + 1), __pyx_v_node_id, 0, __pyx_v_buffer_value); + __pyx_t_2 = ((__pyx_v_self->sum_left == NULL) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; } - __pyx_L5:; + /* "sklearn/tree/_tree.pyx":626 + * self.var_right == NULL or + * self.sum_left == NULL or + * self.sum_right == NULL or # <<<<<<<<<<<<<< + * self.sum_total == NULL): + * raise MemoryError() + */ + __pyx_t_2 = ((__pyx_v_self->sum_right == NULL) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":627 + * self.sum_left == NULL or + * self.sum_right == NULL or + * self.sum_total == NULL): # <<<<<<<<<<<<<< + * raise MemoryError() + * + */ + __pyx_t_2 = ((__pyx_v_self->sum_total == NULL) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L4_bool_binop_done:; + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":628 + * self.sum_right == NULL or + * self.sum_total == NULL): + * raise MemoryError() # <<<<<<<<<<<<<< + * + * def __dealloc__(self): + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":574 + * cdef double* sum_total + * + * def __cinit__(self, SIZE_t n_outputs): # <<<<<<<<<<<<<< + * # Default values + * self.y = NULL + */ + + /* function exit code */ + __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_XDECREF(__pyx_t_13); - __Pyx_XDECREF(__pyx_t_14); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_WriteUnraisable("sklearn.tree._tree.Tree.recursive_partition", __pyx_clineno, __pyx_lineno, __pyx_filename); - goto __pyx_L2; + __Pyx_AddTraceback("sklearn.tree._tree.RegressionCriterion.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_argsorted.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_criterion); - __Pyx_XDECREF((PyObject *)__pyx_v_sample_mask_left); - __Pyx_XDECREF((PyObject *)__pyx_v_sample_mask_right); - __Pyx_XDECREF((PyObject *)__pyx_v_X); - __Pyx_XDECREF((PyObject *)__pyx_v_X_argsorted); - __Pyx_XDECREF((PyObject *)__pyx_v_y); - __Pyx_XDECREF((PyObject *)__pyx_v_sample_mask); __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "sklearn/tree/_tree.pyx":524 - * False, buffer_value) +/* "sklearn/tree/_tree.pyx":630 + * raise MemoryError() * - * cdef int add_split_node(self, int parent, int is_left_child, int feature, # <<<<<<<<<<<<<< - * double threshold, double* value, - * double best_error, double init_error, + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Destructor.""" + * free(self.mean_left) */ -static int __pyx_f_7sklearn_4tree_5_tree_4Tree_add_split_node(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, int __pyx_v_parent, int __pyx_v_is_left_child, int __pyx_v_feature, double __pyx_v_threshold, double *__pyx_v_value, double __pyx_v_best_error, double __pyx_v_init_error, int __pyx_v_n_samples) { - int __pyx_v_node_id; - int __pyx_v_offset_node; - int __pyx_r; +/* Python wrapper */ +static void __pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_3__dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("add_split_node", 0); + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_2__dealloc__(((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self)); - /* "sklearn/tree/_tree.pyx":530 - * """Add a splitting node to the tree. The new node registers itself as - * the child of its parent. """ - * cdef int node_id = self.node_count # <<<<<<<<<<<<<< - * - * if node_id >= self.capacity: + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "sklearn/tree/_tree.pyx":632 + * def __dealloc__(self): + * """Destructor.""" + * free(self.mean_left) # <<<<<<<<<<<<<< + * free(self.mean_right) + * free(self.mean_total) */ - __pyx_v_node_id = __pyx_v_self->node_count; + free(__pyx_v_self->mean_left); - /* "sklearn/tree/_tree.pyx":532 - * cdef int node_id = self.node_count - * - * if node_id >= self.capacity: # <<<<<<<<<<<<<< - * self.resize() - * + /* "sklearn/tree/_tree.pyx":633 + * """Destructor.""" + * free(self.mean_left) + * free(self.mean_right) # <<<<<<<<<<<<<< + * free(self.mean_total) + * free(self.sq_sum_left) */ - __pyx_t_1 = (__pyx_v_node_id >= __pyx_v_self->capacity); - if (__pyx_t_1) { + free(__pyx_v_self->mean_right); - /* "sklearn/tree/_tree.pyx":533 - * - * if node_id >= self.capacity: - * self.resize() # <<<<<<<<<<<<<< - * - * self.feature[node_id] = feature + /* "sklearn/tree/_tree.pyx":634 + * free(self.mean_left) + * free(self.mean_right) + * free(self.mean_total) # <<<<<<<<<<<<<< + * free(self.sq_sum_left) + * free(self.sq_sum_right) */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->resize(__pyx_v_self, NULL); - goto __pyx_L3; - } - __pyx_L3:; + free(__pyx_v_self->mean_total); - /* "sklearn/tree/_tree.pyx":535 - * self.resize() - * - * self.feature[node_id] = feature # <<<<<<<<<<<<<< - * self.threshold[node_id] = threshold - * + /* "sklearn/tree/_tree.pyx":635 + * free(self.mean_right) + * free(self.mean_total) + * free(self.sq_sum_left) # <<<<<<<<<<<<<< + * free(self.sq_sum_right) + * free(self.sq_sum_total) */ - (__pyx_v_self->feature[__pyx_v_node_id]) = __pyx_v_feature; + free(__pyx_v_self->sq_sum_left); - /* "sklearn/tree/_tree.pyx":536 - * - * self.feature[node_id] = feature - * self.threshold[node_id] = threshold # <<<<<<<<<<<<<< - * - * cdef int offset_node = node_id * self.value_stride + /* "sklearn/tree/_tree.pyx":636 + * free(self.mean_total) + * free(self.sq_sum_left) + * free(self.sq_sum_right) # <<<<<<<<<<<<<< + * free(self.sq_sum_total) + * free(self.var_left) */ - (__pyx_v_self->threshold[__pyx_v_node_id]) = __pyx_v_threshold; + free(__pyx_v_self->sq_sum_right); - /* "sklearn/tree/_tree.pyx":538 - * self.threshold[node_id] = threshold - * - * cdef int offset_node = node_id * self.value_stride # <<<<<<<<<<<<<< - * memcpy(self.value + offset_node, value, self.value_stride * sizeof(double)) - * + /* "sklearn/tree/_tree.pyx":637 + * free(self.sq_sum_left) + * free(self.sq_sum_right) + * free(self.sq_sum_total) # <<<<<<<<<<<<<< + * free(self.var_left) + * free(self.var_right) */ - __pyx_v_offset_node = (__pyx_v_node_id * __pyx_v_self->value_stride); + free(__pyx_v_self->sq_sum_total); - /* "sklearn/tree/_tree.pyx":539 - * - * cdef int offset_node = node_id * self.value_stride - * memcpy(self.value + offset_node, value, self.value_stride * sizeof(double)) # <<<<<<<<<<<<<< - * - * self.init_error[node_id] = init_error + /* "sklearn/tree/_tree.pyx":638 + * free(self.sq_sum_right) + * free(self.sq_sum_total) + * free(self.var_left) # <<<<<<<<<<<<<< + * free(self.var_right) + * free(self.sum_left) */ - memcpy((__pyx_v_self->value + __pyx_v_offset_node), __pyx_v_value, (__pyx_v_self->value_stride * (sizeof(double)))); + free(__pyx_v_self->var_left); - /* "sklearn/tree/_tree.pyx":541 - * memcpy(self.value + offset_node, value, self.value_stride * sizeof(double)) - * - * self.init_error[node_id] = init_error # <<<<<<<<<<<<<< - * self.best_error[node_id] = best_error - * self.n_samples[node_id] = n_samples + /* "sklearn/tree/_tree.pyx":639 + * free(self.sq_sum_total) + * free(self.var_left) + * free(self.var_right) # <<<<<<<<<<<<<< + * free(self.sum_left) + * free(self.sum_right) */ - (__pyx_v_self->init_error[__pyx_v_node_id]) = __pyx_v_init_error; + free(__pyx_v_self->var_right); - /* "sklearn/tree/_tree.pyx":542 - * - * self.init_error[node_id] = init_error - * self.best_error[node_id] = best_error # <<<<<<<<<<<<<< - * self.n_samples[node_id] = n_samples - * + /* "sklearn/tree/_tree.pyx":640 + * free(self.var_left) + * free(self.var_right) + * free(self.sum_left) # <<<<<<<<<<<<<< + * free(self.sum_right) + * free(self.sum_total) */ - (__pyx_v_self->best_error[__pyx_v_node_id]) = __pyx_v_best_error; + free(__pyx_v_self->sum_left); - /* "sklearn/tree/_tree.pyx":543 - * self.init_error[node_id] = init_error - * self.best_error[node_id] = best_error - * self.n_samples[node_id] = n_samples # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":641 + * free(self.var_right) + * free(self.sum_left) + * free(self.sum_right) # <<<<<<<<<<<<<< + * free(self.sum_total) * - * # set as left or right child of parent */ - (__pyx_v_self->n_samples[__pyx_v_node_id]) = __pyx_v_n_samples; + free(__pyx_v_self->sum_right); - /* "sklearn/tree/_tree.pyx":546 + /* "sklearn/tree/_tree.pyx":642 + * free(self.sum_left) + * free(self.sum_right) + * free(self.sum_total) # <<<<<<<<<<<<<< * - * # set as left or right child of parent - * if parent > _TREE_LEAF: # <<<<<<<<<<<<<< - * if is_left_child: - * self.children_left[parent] = node_id + * def __reduce__(self): */ - __pyx_t_1 = (__pyx_v_parent > __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF); - if (__pyx_t_1) { + free(__pyx_v_self->sum_total); - /* "sklearn/tree/_tree.pyx":547 - * # set as left or right child of parent - * if parent > _TREE_LEAF: - * if is_left_child: # <<<<<<<<<<<<<< - * self.children_left[parent] = node_id - * else: + /* "sklearn/tree/_tree.pyx":630 + * raise MemoryError() + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Destructor.""" + * free(self.mean_left) */ - if (__pyx_v_is_left_child) { - /* "sklearn/tree/_tree.pyx":548 - * if parent > _TREE_LEAF: - * if is_left_child: - * self.children_left[parent] = node_id # <<<<<<<<<<<<<< - * else: - * self.children_right[parent] = node_id - */ - (__pyx_v_self->children_left[__pyx_v_parent]) = __pyx_v_node_id; - goto __pyx_L5; - } - /*else*/ { + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} - /* "sklearn/tree/_tree.pyx":550 - * self.children_left[parent] = node_id - * else: - * self.children_right[parent] = node_id # <<<<<<<<<<<<<< +/* "sklearn/tree/_tree.pyx":644 + * free(self.sum_total) + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (RegressionCriterion, (self.n_outputs,), self.__getstate__()) * - * self.node_count += 1 */ - (__pyx_v_self->children_right[__pyx_v_parent]) = __pyx_v_node_id; - } - __pyx_L5:; - goto __pyx_L4; - } - __pyx_L4:; - /* "sklearn/tree/_tree.pyx":552 - * self.children_right[parent] = node_id +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_4__reduce__(((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce__", 0); + + /* "sklearn/tree/_tree.pyx":645 * - * self.node_count += 1 # <<<<<<<<<<<<<< + * def __reduce__(self): + * return (RegressionCriterion, (self.n_outputs,), self.__getstate__()) # <<<<<<<<<<<<<< * - * return node_id + * def __getstate__(self): */ - __pyx_v_self->node_count = (__pyx_v_self->node_count + 1); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.n_outputs); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_getstate); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (__pyx_t_4) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RegressionCriterion))); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RegressionCriterion))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RegressionCriterion))); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_2 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; - /* "sklearn/tree/_tree.pyx":554 - * self.node_count += 1 + /* "sklearn/tree/_tree.pyx":644 + * free(self.sum_total) * - * return node_id # <<<<<<<<<<<<<< + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (RegressionCriterion, (self.n_outputs,), self.__getstate__()) * - * cdef int add_leaf(self, int parent, int is_left_child, double* value, */ - __pyx_r = __pyx_v_node_id; - goto __pyx_L0; - __pyx_r = 0; + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.RegressionCriterion.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pyx":556 - * return node_id +/* "sklearn/tree/_tree.pyx":647 + * return (RegressionCriterion, (self.n_outputs,), self.__getstate__()) + * + * def __getstate__(self): # <<<<<<<<<<<<<< + * return {} * - * cdef int add_leaf(self, int parent, int is_left_child, double* value, # <<<<<<<<<<<<<< - * double error, int n_samples): - * """Add a leaf to the tree. The new node registers itself as the */ -static int __pyx_f_7sklearn_4tree_5_tree_4Tree_add_leaf(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, int __pyx_v_parent, int __pyx_v_is_left_child, double *__pyx_v_value, double __pyx_v_error, int __pyx_v_n_samples) { - int __pyx_v_node_id; - int __pyx_v_offset_node; - int __pyx_r; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("add_leaf", 0); + __Pyx_RefNannySetupContext("__getstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_6__getstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self)); - /* "sklearn/tree/_tree.pyx":560 - * """Add a leaf to the tree. The new node registers itself as the - * child of its parent. """ - * cdef int node_id = self.node_count # <<<<<<<<<<<<<< - * - * if node_id >= self.capacity: - */ - __pyx_v_node_id = __pyx_v_self->node_count; + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_6__getstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getstate__", 0); - /* "sklearn/tree/_tree.pyx":562 - * cdef int node_id = self.node_count + /* "sklearn/tree/_tree.pyx":648 * - * if node_id >= self.capacity: # <<<<<<<<<<<<<< - * self.resize() + * def __getstate__(self): + * return {} # <<<<<<<<<<<<<< * + * def __setstate__(self, d): */ - __pyx_t_1 = (__pyx_v_node_id >= __pyx_v_self->capacity); - if (__pyx_t_1) { + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; - /* "sklearn/tree/_tree.pyx":563 + /* "sklearn/tree/_tree.pyx":647 + * return (RegressionCriterion, (self.n_outputs,), self.__getstate__()) * - * if node_id >= self.capacity: - * self.resize() # <<<<<<<<<<<<<< + * def __getstate__(self): # <<<<<<<<<<<<<< + * return {} * - * cdef int offset_node = node_id * self.n_outputs * self.max_n_classes */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->resize(__pyx_v_self, NULL); - goto __pyx_L3; - } - __pyx_L3:; - /* "sklearn/tree/_tree.pyx":565 - * self.resize() - * - * cdef int offset_node = node_id * self.n_outputs * self.max_n_classes # <<<<<<<<<<<<<< - * memcpy(self.value + offset_node, value, self.value_stride * sizeof(double)) - * - */ - __pyx_v_offset_node = ((__pyx_v_node_id * __pyx_v_self->n_outputs) * __pyx_v_self->max_n_classes); + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.RegressionCriterion.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/tree/_tree.pyx":566 +/* "sklearn/tree/_tree.pyx":650 + * return {} * - * cdef int offset_node = node_id * self.n_outputs * self.max_n_classes - * memcpy(self.value + offset_node, value, self.value_stride * sizeof(double)) # <<<<<<<<<<<<<< + * def __setstate__(self, d): # <<<<<<<<<<<<<< + * pass * - * self.init_error[node_id] = error */ - memcpy((__pyx_v_self->value + __pyx_v_offset_node), __pyx_v_value, (__pyx_v_self->value_stride * (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":568 - * memcpy(self.value + offset_node, value, self.value_stride * sizeof(double)) +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_8__setstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self), ((PyObject *)__pyx_v_d)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_8__setstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate__", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":653 + * pass * - * self.init_error[node_id] = error # <<<<<<<<<<<<<< - * self.best_error[node_id] = error - * self.n_samples[node_id] = n_samples + * cdef void init(self, DOUBLE_t* y, SIZE_t y_stride, DOUBLE_t* sample_weight, # <<<<<<<<<<<<<< + * double weighted_n_samples, SIZE_t* samples, SIZE_t start, + * SIZE_t end) nogil: */ - (__pyx_v_self->init_error[__pyx_v_node_id]) = __pyx_v_error; - /* "sklearn/tree/_tree.pyx":569 - * - * self.init_error[node_id] = error - * self.best_error[node_id] = error # <<<<<<<<<<<<<< - * self.n_samples[node_id] = n_samples - * +static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_init(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_y_stride, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight, double __pyx_v_weighted_n_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end) { + double __pyx_v_weighted_n_node_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + double *__pyx_v_mean_left; + double *__pyx_v_mean_right; + double *__pyx_v_mean_total; + double *__pyx_v_sq_sum_left; + double *__pyx_v_sq_sum_right; + double *__pyx_v_sq_sum_total; + double *__pyx_v_var_left; + double *__pyx_v_var_right; + double *__pyx_v_sum_left; + double *__pyx_v_sum_right; + double *__pyx_v_sum_total; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t __pyx_v_y_ik; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t __pyx_v_w_y_ik; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t __pyx_v_w; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_bytes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + double *__pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_3; + int __pyx_t_4; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_5; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; + + /* "sklearn/tree/_tree.pyx":659 + * children samples[start:start] and samples[start:end].""" + * # Initialize fields + * self.y = y # <<<<<<<<<<<<<< + * self.y_stride = y_stride + * self.sample_weight = sample_weight */ - (__pyx_v_self->best_error[__pyx_v_node_id]) = __pyx_v_error; + __pyx_v_self->__pyx_base.y = __pyx_v_y; - /* "sklearn/tree/_tree.pyx":570 - * self.init_error[node_id] = error - * self.best_error[node_id] = error - * self.n_samples[node_id] = n_samples # <<<<<<<<<<<<<< - * - * if parent >= 0: + /* "sklearn/tree/_tree.pyx":660 + * # Initialize fields + * self.y = y + * self.y_stride = y_stride # <<<<<<<<<<<<<< + * self.sample_weight = sample_weight + * self.samples = samples */ - (__pyx_v_self->n_samples[__pyx_v_node_id]) = __pyx_v_n_samples; + __pyx_v_self->__pyx_base.y_stride = __pyx_v_y_stride; - /* "sklearn/tree/_tree.pyx":572 - * self.n_samples[node_id] = n_samples - * - * if parent >= 0: # <<<<<<<<<<<<<< - * if is_left_child: - * self.children_left[parent] = node_id + /* "sklearn/tree/_tree.pyx":661 + * self.y = y + * self.y_stride = y_stride + * self.sample_weight = sample_weight # <<<<<<<<<<<<<< + * self.samples = samples + * self.start = start */ - __pyx_t_1 = (__pyx_v_parent >= 0); - if (__pyx_t_1) { + __pyx_v_self->__pyx_base.sample_weight = __pyx_v_sample_weight; - /* "sklearn/tree/_tree.pyx":573 - * - * if parent >= 0: - * if is_left_child: # <<<<<<<<<<<<<< - * self.children_left[parent] = node_id - * else: + /* "sklearn/tree/_tree.pyx":662 + * self.y_stride = y_stride + * self.sample_weight = sample_weight + * self.samples = samples # <<<<<<<<<<<<<< + * self.start = start + * self.end = end */ - if (__pyx_v_is_left_child) { + __pyx_v_self->__pyx_base.samples = __pyx_v_samples; - /* "sklearn/tree/_tree.pyx":574 - * if parent >= 0: - * if is_left_child: - * self.children_left[parent] = node_id # <<<<<<<<<<<<<< - * else: - * self.children_right[parent] = node_id + /* "sklearn/tree/_tree.pyx":663 + * self.sample_weight = sample_weight + * self.samples = samples + * self.start = start # <<<<<<<<<<<<<< + * self.end = end + * self.n_node_samples = end - start */ - (__pyx_v_self->children_left[__pyx_v_parent]) = __pyx_v_node_id; - goto __pyx_L5; - } - /*else*/ { + __pyx_v_self->__pyx_base.start = __pyx_v_start; - /* "sklearn/tree/_tree.pyx":576 - * self.children_left[parent] = node_id - * else: - * self.children_right[parent] = node_id # <<<<<<<<<<<<<< - * - * self.children_left[node_id] = _TREE_LEAF + /* "sklearn/tree/_tree.pyx":664 + * self.samples = samples + * self.start = start + * self.end = end # <<<<<<<<<<<<<< + * self.n_node_samples = end - start + * self.weighted_n_samples = weighted_n_samples */ - (__pyx_v_self->children_right[__pyx_v_parent]) = __pyx_v_node_id; - } - __pyx_L5:; - goto __pyx_L4; - } - __pyx_L4:; + __pyx_v_self->__pyx_base.end = __pyx_v_end; - /* "sklearn/tree/_tree.pyx":578 - * self.children_right[parent] = node_id - * - * self.children_left[node_id] = _TREE_LEAF # <<<<<<<<<<<<<< - * self.children_right[node_id] = _TREE_LEAF - * + /* "sklearn/tree/_tree.pyx":665 + * self.start = start + * self.end = end + * self.n_node_samples = end - start # <<<<<<<<<<<<<< + * self.weighted_n_samples = weighted_n_samples + * cdef double weighted_n_node_samples = 0. */ - (__pyx_v_self->children_left[__pyx_v_node_id]) = __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF; + __pyx_v_self->__pyx_base.n_node_samples = (__pyx_v_end - __pyx_v_start); - /* "sklearn/tree/_tree.pyx":579 - * - * self.children_left[node_id] = _TREE_LEAF - * self.children_right[node_id] = _TREE_LEAF # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":666 + * self.end = end + * self.n_node_samples = end - start + * self.weighted_n_samples = weighted_n_samples # <<<<<<<<<<<<<< + * cdef double weighted_n_node_samples = 0. * - * self.node_count += 1 */ - (__pyx_v_self->children_right[__pyx_v_node_id]) = __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF; + __pyx_v_self->__pyx_base.weighted_n_samples = __pyx_v_weighted_n_samples; - /* "sklearn/tree/_tree.pyx":581 - * self.children_right[node_id] = _TREE_LEAF - * - * self.node_count += 1 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":667 + * self.n_node_samples = end - start + * self.weighted_n_samples = weighted_n_samples + * cdef double weighted_n_node_samples = 0. # <<<<<<<<<<<<<< * - * return node_id + * # Initialize accumulators */ - __pyx_v_self->node_count = (__pyx_v_self->node_count + 1); + __pyx_v_weighted_n_node_samples = 0.; - /* "sklearn/tree/_tree.pyx":583 - * self.node_count += 1 + /* "sklearn/tree/_tree.pyx":670 * - * return node_id # <<<<<<<<<<<<<< - * - * cdef void find_split(self, DTYPE_t* X_ptr, int X_stride, + * # Initialize accumulators + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef double* mean_left = self.mean_left + * cdef double* mean_right = self.mean_right */ - __pyx_r = __pyx_v_node_id; - goto __pyx_L0; + __pyx_t_1 = __pyx_v_self->__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_1; - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":671 + * # Initialize accumulators + * cdef SIZE_t n_outputs = self.n_outputs + * cdef double* mean_left = self.mean_left # <<<<<<<<<<<<<< + * cdef double* mean_right = self.mean_right + * cdef double* mean_total = self.mean_total + */ + __pyx_t_2 = __pyx_v_self->mean_left; + __pyx_v_mean_left = __pyx_t_2; -/* "sklearn/tree/_tree.pyx":585 - * return node_id - * - * cdef void find_split(self, DTYPE_t* X_ptr, int X_stride, # <<<<<<<<<<<<<< - * int* X_argsorted_ptr, int X_argsorted_stride, - * DOUBLE_t* y_ptr, int y_stride, BOOL_t* sample_mask_ptr, + /* "sklearn/tree/_tree.pyx":672 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef double* mean_left = self.mean_left + * cdef double* mean_right = self.mean_right # <<<<<<<<<<<<<< + * cdef double* mean_total = self.mean_total + * cdef double* sq_sum_left = self.sq_sum_left */ + __pyx_t_2 = __pyx_v_self->mean_right; + __pyx_v_mean_right = __pyx_t_2; -static void __pyx_f_7sklearn_4tree_5_tree_4Tree_find_split(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_ptr, int __pyx_v_X_stride, int *__pyx_v_X_argsorted_ptr, int __pyx_v_X_argsorted_stride, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y_ptr, int __pyx_v_y_stride, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *__pyx_v_sample_mask_ptr, int __pyx_v_n_node_samples, int __pyx_v_n_total_samples, int *__pyx_v__best_i, double *__pyx_v__best_t, double *__pyx_v__best_error, double *__pyx_v__initial_error) { - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("find_split", 0); + /* "sklearn/tree/_tree.pyx":673 + * cdef double* mean_left = self.mean_left + * cdef double* mean_right = self.mean_right + * cdef double* mean_total = self.mean_total # <<<<<<<<<<<<<< + * cdef double* sq_sum_left = self.sq_sum_left + * cdef double* sq_sum_right = self.sq_sum_right + */ + __pyx_t_2 = __pyx_v_self->mean_total; + __pyx_v_mean_total = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":592 - * double* _initial_error): - * """Find the best dimension and threshold that minimises the error.""" - * if self.find_split_algorithm == _TREE_SPLIT_BEST: # <<<<<<<<<<<<<< - * self.find_best_split(X_ptr, X_stride, X_argsorted_ptr, - * X_argsorted_stride, y_ptr, y_stride, + /* "sklearn/tree/_tree.pyx":674 + * cdef double* mean_right = self.mean_right + * cdef double* mean_total = self.mean_total + * cdef double* sq_sum_left = self.sq_sum_left # <<<<<<<<<<<<<< + * cdef double* sq_sum_right = self.sq_sum_right + * cdef double* sq_sum_total = self.sq_sum_total */ - __pyx_t_1 = (__pyx_v_self->find_split_algorithm == __pyx_v_7sklearn_4tree_5_tree__TREE_SPLIT_BEST); - if (__pyx_t_1) { + __pyx_t_2 = __pyx_v_self->sq_sum_left; + __pyx_v_sq_sum_left = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":597 - * sample_mask_ptr, n_node_samples, - * n_total_samples, _best_i, _best_t, - * _best_error, _initial_error) # <<<<<<<<<<<<<< - * - * elif self.find_split_algorithm == _TREE_SPLIT_RANDOM: + /* "sklearn/tree/_tree.pyx":675 + * cdef double* mean_total = self.mean_total + * cdef double* sq_sum_left = self.sq_sum_left + * cdef double* sq_sum_right = self.sq_sum_right # <<<<<<<<<<<<<< + * cdef double* sq_sum_total = self.sq_sum_total + * cdef double* var_left = self.var_left */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->find_best_split(__pyx_v_self, __pyx_v_X_ptr, __pyx_v_X_stride, __pyx_v_X_argsorted_ptr, __pyx_v_X_argsorted_stride, __pyx_v_y_ptr, __pyx_v_y_stride, __pyx_v_sample_mask_ptr, __pyx_v_n_node_samples, __pyx_v_n_total_samples, __pyx_v__best_i, __pyx_v__best_t, __pyx_v__best_error, __pyx_v__initial_error); - goto __pyx_L3; - } + __pyx_t_2 = __pyx_v_self->sq_sum_right; + __pyx_v_sq_sum_right = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":599 - * _best_error, _initial_error) - * - * elif self.find_split_algorithm == _TREE_SPLIT_RANDOM: # <<<<<<<<<<<<<< - * self.find_random_split(X_ptr, X_stride, X_argsorted_ptr, - * X_argsorted_stride, y_ptr, y_stride, + /* "sklearn/tree/_tree.pyx":676 + * cdef double* sq_sum_left = self.sq_sum_left + * cdef double* sq_sum_right = self.sq_sum_right + * cdef double* sq_sum_total = self.sq_sum_total # <<<<<<<<<<<<<< + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right */ - __pyx_t_1 = (__pyx_v_self->find_split_algorithm == __pyx_v_7sklearn_4tree_5_tree__TREE_SPLIT_RANDOM); - if (__pyx_t_1) { + __pyx_t_2 = __pyx_v_self->sq_sum_total; + __pyx_v_sq_sum_total = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":604 - * sample_mask_ptr, n_node_samples, - * n_total_samples, _best_i, _best_t, - * _best_error, _initial_error) # <<<<<<<<<<<<<< - * - * cdef void find_best_split(self, DTYPE_t* X_ptr, int X_stride, + /* "sklearn/tree/_tree.pyx":677 + * cdef double* sq_sum_right = self.sq_sum_right + * cdef double* sq_sum_total = self.sq_sum_total + * cdef double* var_left = self.var_left # <<<<<<<<<<<<<< + * cdef double* var_right = self.var_right + * cdef double* sum_left = self.sum_left */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->find_random_split(__pyx_v_self, __pyx_v_X_ptr, __pyx_v_X_stride, __pyx_v_X_argsorted_ptr, __pyx_v_X_argsorted_stride, __pyx_v_y_ptr, __pyx_v_y_stride, __pyx_v_sample_mask_ptr, __pyx_v_n_node_samples, __pyx_v_n_total_samples, __pyx_v__best_i, __pyx_v__best_t, __pyx_v__best_error, __pyx_v__initial_error); - goto __pyx_L3; - } - __pyx_L3:; + __pyx_t_2 = __pyx_v_self->var_left; + __pyx_v_var_left = __pyx_t_2; - __Pyx_RefNannyFinishContext(); -} + /* "sklearn/tree/_tree.pyx":678 + * cdef double* sq_sum_total = self.sq_sum_total + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right # <<<<<<<<<<<<<< + * cdef double* sum_left = self.sum_left + * cdef double* sum_right = self.sum_right + */ + __pyx_t_2 = __pyx_v_self->var_right; + __pyx_v_var_right = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":679 + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right + * cdef double* sum_left = self.sum_left # <<<<<<<<<<<<<< + * cdef double* sum_right = self.sum_right + * cdef double* sum_total = self.sum_total + */ + __pyx_t_2 = __pyx_v_self->sum_left; + __pyx_v_sum_left = __pyx_t_2; -/* "sklearn/tree/_tree.pyx":606 - * _best_error, _initial_error) + /* "sklearn/tree/_tree.pyx":680 + * cdef double* var_right = self.var_right + * cdef double* sum_left = self.sum_left + * cdef double* sum_right = self.sum_right # <<<<<<<<<<<<<< + * cdef double* sum_total = self.sum_total * - * cdef void find_best_split(self, DTYPE_t* X_ptr, int X_stride, # <<<<<<<<<<<<<< - * int* X_argsorted_ptr, int X_argsorted_stride, - * DOUBLE_t* y_ptr, int y_stride, */ + __pyx_t_2 = __pyx_v_self->sum_right; + __pyx_v_sum_right = __pyx_t_2; -static void __pyx_f_7sklearn_4tree_5_tree_4Tree_find_best_split(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_ptr, int __pyx_v_X_stride, int *__pyx_v_X_argsorted_ptr, int __pyx_v_X_argsorted_stride, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y_ptr, int __pyx_v_y_stride, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *__pyx_v_sample_mask_ptr, int __pyx_v_n_node_samples, int __pyx_v_n_total_samples, int *__pyx_v__best_i, double *__pyx_v__best_t, double *__pyx_v__best_error, double *__pyx_v__initial_error) { - struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion = 0; - int __pyx_v_n_features; - int __pyx_v_max_features; - int __pyx_v_min_samples_leaf; - PyObject *__pyx_v_random_state = 0; - int __pyx_v_i; - int __pyx_v_a; - int __pyx_v_b; - int __pyx_v_best_i; - __pyx_t_5numpy_int32_t __pyx_v_feature_idx; - int __pyx_v_n_left; - double __pyx_v_t; - double __pyx_v_initial_error; - double __pyx_v_error; - double __pyx_v_best_error; - double __pyx_v_best_t; - __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_i; - int *__pyx_v_X_argsorted_i; - __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_X_a; - __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_X_b; - PyArrayObject *__pyx_v_features = 0; - __Pyx_LocalBuf_ND __pyx_pybuffernd_features; - __Pyx_Buffer __pyx_pybuffer_features; - __Pyx_RefNannyDeclarations - PyArrayObject *__pyx_t_1 = NULL; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - int __pyx_t_12; - int __pyx_t_13; - __pyx_t_5numpy_int32_t __pyx_t_14; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("find_best_split", 0); - __pyx_pybuffer_features.pybuffer.buf = NULL; - __pyx_pybuffer_features.refcount = 0; - __pyx_pybuffernd_features.data = NULL; - __pyx_pybuffernd_features.rcbuffer = &__pyx_pybuffer_features; + /* "sklearn/tree/_tree.pyx":681 + * cdef double* sum_left = self.sum_left + * cdef double* sum_right = self.sum_right + * cdef double* sum_total = self.sum_total # <<<<<<<<<<<<<< + * + * cdef SIZE_t i = 0 + */ + __pyx_t_2 = __pyx_v_self->sum_total; + __pyx_v_sum_total = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":615 - * """Implementation of `find_split` that looks for the best threshold.""" - * # Variables declarations - * cdef Criterion criterion = self.criterion # <<<<<<<<<<<<<< - * cdef int n_features = self.n_features - * cdef int max_features = self.max_features + /* "sklearn/tree/_tree.pyx":683 + * cdef double* sum_total = self.sum_total + * + * cdef SIZE_t i = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t p = 0 + * cdef SIZE_t k = 0 */ - __Pyx_INCREF(((PyObject *)__pyx_v_self->criterion)); - __pyx_v_criterion = __pyx_v_self->criterion; + __pyx_v_i = 0; - /* "sklearn/tree/_tree.pyx":616 - * # Variables declarations - * cdef Criterion criterion = self.criterion - * cdef int n_features = self.n_features # <<<<<<<<<<<<<< - * cdef int max_features = self.max_features - * cdef int min_samples_leaf = self.min_samples_leaf + /* "sklearn/tree/_tree.pyx":684 + * + * cdef SIZE_t i = 0 + * cdef SIZE_t p = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t k = 0 + * cdef DOUBLE_t y_ik = 0.0 */ - __pyx_v_n_features = __pyx_v_self->n_features; + __pyx_v_p = 0; - /* "sklearn/tree/_tree.pyx":617 - * cdef Criterion criterion = self.criterion - * cdef int n_features = self.n_features - * cdef int max_features = self.max_features # <<<<<<<<<<<<<< - * cdef int min_samples_leaf = self.min_samples_leaf - * cdef object random_state = self.random_state + /* "sklearn/tree/_tree.pyx":685 + * cdef SIZE_t i = 0 + * cdef SIZE_t p = 0 + * cdef SIZE_t k = 0 # <<<<<<<<<<<<<< + * cdef DOUBLE_t y_ik = 0.0 + * cdef DOUBLE_t w_y_ik = 0.0 */ - __pyx_v_max_features = __pyx_v_self->max_features; + __pyx_v_k = 0; - /* "sklearn/tree/_tree.pyx":618 - * cdef int n_features = self.n_features - * cdef int max_features = self.max_features - * cdef int min_samples_leaf = self.min_samples_leaf # <<<<<<<<<<<<<< - * cdef object random_state = self.random_state - * + /* "sklearn/tree/_tree.pyx":686 + * cdef SIZE_t p = 0 + * cdef SIZE_t k = 0 + * cdef DOUBLE_t y_ik = 0.0 # <<<<<<<<<<<<<< + * cdef DOUBLE_t w_y_ik = 0.0 + * cdef DOUBLE_t w = 1.0 */ - __pyx_v_min_samples_leaf = __pyx_v_self->min_samples_leaf; + __pyx_v_y_ik = 0.0; - /* "sklearn/tree/_tree.pyx":619 - * cdef int max_features = self.max_features - * cdef int min_samples_leaf = self.min_samples_leaf - * cdef object random_state = self.random_state # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":687 + * cdef SIZE_t k = 0 + * cdef DOUBLE_t y_ik = 0.0 + * cdef DOUBLE_t w_y_ik = 0.0 # <<<<<<<<<<<<<< + * cdef DOUBLE_t w = 1.0 * - * cdef int i, a, b, best_i = -1 */ - __Pyx_INCREF(__pyx_v_self->random_state); - __pyx_v_random_state = __pyx_v_self->random_state; + __pyx_v_w_y_ik = 0.0; - /* "sklearn/tree/_tree.pyx":621 - * cdef object random_state = self.random_state + /* "sklearn/tree/_tree.pyx":688 + * cdef DOUBLE_t y_ik = 0.0 + * cdef DOUBLE_t w_y_ik = 0.0 + * cdef DOUBLE_t w = 1.0 # <<<<<<<<<<<<<< * - * cdef int i, a, b, best_i = -1 # <<<<<<<<<<<<<< - * cdef np.int32_t feature_idx = -1 - * cdef int n_left = 0 + * cdef SIZE_t n_bytes = n_outputs * sizeof(double) */ - __pyx_v_best_i = -1; + __pyx_v_w = 1.0; - /* "sklearn/tree/_tree.pyx":622 - * - * cdef int i, a, b, best_i = -1 - * cdef np.int32_t feature_idx = -1 # <<<<<<<<<<<<<< - * cdef int n_left = 0 + /* "sklearn/tree/_tree.pyx":690 + * cdef DOUBLE_t w = 1.0 * + * cdef SIZE_t n_bytes = n_outputs * sizeof(double) # <<<<<<<<<<<<<< + * memset(mean_left, 0, n_bytes) + * memset(mean_right, 0, n_bytes) */ - __pyx_v_feature_idx = -1; + __pyx_v_n_bytes = (__pyx_v_n_outputs * (sizeof(double))); - /* "sklearn/tree/_tree.pyx":623 - * cdef int i, a, b, best_i = -1 - * cdef np.int32_t feature_idx = -1 - * cdef int n_left = 0 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":691 * - * cdef double t, initial_error, error + * cdef SIZE_t n_bytes = n_outputs * sizeof(double) + * memset(mean_left, 0, n_bytes) # <<<<<<<<<<<<<< + * memset(mean_right, 0, n_bytes) + * memset(mean_total, 0, n_bytes) */ - __pyx_v_n_left = 0; + memset(__pyx_v_mean_left, 0, __pyx_v_n_bytes); - /* "sklearn/tree/_tree.pyx":626 - * - * cdef double t, initial_error, error - * cdef double best_error = INFINITY, best_t = INFINITY # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":692 + * cdef SIZE_t n_bytes = n_outputs * sizeof(double) + * memset(mean_left, 0, n_bytes) + * memset(mean_right, 0, n_bytes) # <<<<<<<<<<<<<< + * memset(mean_total, 0, n_bytes) + * memset(sq_sum_left, 0, n_bytes) + */ + memset(__pyx_v_mean_right, 0, __pyx_v_n_bytes); + + /* "sklearn/tree/_tree.pyx":693 + * memset(mean_left, 0, n_bytes) + * memset(mean_right, 0, n_bytes) + * memset(mean_total, 0, n_bytes) # <<<<<<<<<<<<<< + * memset(sq_sum_left, 0, n_bytes) + * memset(sq_sum_right, 0, n_bytes) + */ + memset(__pyx_v_mean_total, 0, __pyx_v_n_bytes); + + /* "sklearn/tree/_tree.pyx":694 + * memset(mean_right, 0, n_bytes) + * memset(mean_total, 0, n_bytes) + * memset(sq_sum_left, 0, n_bytes) # <<<<<<<<<<<<<< + * memset(sq_sum_right, 0, n_bytes) + * memset(sq_sum_total, 0, n_bytes) + */ + memset(__pyx_v_sq_sum_left, 0, __pyx_v_n_bytes); + + /* "sklearn/tree/_tree.pyx":695 + * memset(mean_total, 0, n_bytes) + * memset(sq_sum_left, 0, n_bytes) + * memset(sq_sum_right, 0, n_bytes) # <<<<<<<<<<<<<< + * memset(sq_sum_total, 0, n_bytes) + * memset(var_left, 0, n_bytes) + */ + memset(__pyx_v_sq_sum_right, 0, __pyx_v_n_bytes); + + /* "sklearn/tree/_tree.pyx":696 + * memset(sq_sum_left, 0, n_bytes) + * memset(sq_sum_right, 0, n_bytes) + * memset(sq_sum_total, 0, n_bytes) # <<<<<<<<<<<<<< + * memset(var_left, 0, n_bytes) + * memset(var_right, 0, n_bytes) + */ + memset(__pyx_v_sq_sum_total, 0, __pyx_v_n_bytes); + + /* "sklearn/tree/_tree.pyx":697 + * memset(sq_sum_right, 0, n_bytes) + * memset(sq_sum_total, 0, n_bytes) + * memset(var_left, 0, n_bytes) # <<<<<<<<<<<<<< + * memset(var_right, 0, n_bytes) + * memset(sum_left, 0, n_bytes) + */ + memset(__pyx_v_var_left, 0, __pyx_v_n_bytes); + + /* "sklearn/tree/_tree.pyx":698 + * memset(sq_sum_total, 0, n_bytes) + * memset(var_left, 0, n_bytes) + * memset(var_right, 0, n_bytes) # <<<<<<<<<<<<<< + * memset(sum_left, 0, n_bytes) + * memset(sum_right, 0, n_bytes) + */ + memset(__pyx_v_var_right, 0, __pyx_v_n_bytes); + + /* "sklearn/tree/_tree.pyx":699 + * memset(var_left, 0, n_bytes) + * memset(var_right, 0, n_bytes) + * memset(sum_left, 0, n_bytes) # <<<<<<<<<<<<<< + * memset(sum_right, 0, n_bytes) + * memset(sum_total, 0, n_bytes) + */ + memset(__pyx_v_sum_left, 0, __pyx_v_n_bytes); + + /* "sklearn/tree/_tree.pyx":700 + * memset(var_right, 0, n_bytes) + * memset(sum_left, 0, n_bytes) + * memset(sum_right, 0, n_bytes) # <<<<<<<<<<<<<< + * memset(sum_total, 0, n_bytes) * - * cdef DTYPE_t* X_i = NULL */ - __pyx_v_best_error = __pyx_v_7sklearn_4tree_5_tree_INFINITY; - __pyx_v_best_t = __pyx_v_7sklearn_4tree_5_tree_INFINITY; + memset(__pyx_v_sum_right, 0, __pyx_v_n_bytes); - /* "sklearn/tree/_tree.pyx":628 - * cdef double best_error = INFINITY, best_t = INFINITY + /* "sklearn/tree/_tree.pyx":701 + * memset(sum_left, 0, n_bytes) + * memset(sum_right, 0, n_bytes) + * memset(sum_total, 0, n_bytes) # <<<<<<<<<<<<<< * - * cdef DTYPE_t* X_i = NULL # <<<<<<<<<<<<<< - * cdef int* X_argsorted_i = NULL - * cdef DTYPE_t X_a, X_b + * for p in range(start, end): */ - __pyx_v_X_i = NULL; + memset(__pyx_v_sum_total, 0, __pyx_v_n_bytes); - /* "sklearn/tree/_tree.pyx":629 + /* "sklearn/tree/_tree.pyx":703 + * memset(sum_total, 0, n_bytes) * - * cdef DTYPE_t* X_i = NULL - * cdef int* X_argsorted_i = NULL # <<<<<<<<<<<<<< - * cdef DTYPE_t X_a, X_b + * for p in range(start, end): # <<<<<<<<<<<<<< + * i = samples[p] * */ - __pyx_v_X_argsorted_i = NULL; + __pyx_t_1 = __pyx_v_end; + for (__pyx_t_3 = __pyx_v_start; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_p = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":632 - * cdef DTYPE_t X_a, X_b + /* "sklearn/tree/_tree.pyx":704 * - * cdef np.ndarray[np.int32_t, ndim=1, mode="c"] features = None # <<<<<<<<<<<<<< + * for p in range(start, end): + * i = samples[p] # <<<<<<<<<<<<<< * - * # Compute the initial criterion value in the node + * if sample_weight != NULL: */ - __pyx_t_1 = ((PyArrayObject *)Py_None); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_features.rcbuffer->pybuffer, (PyObject*)__pyx_t_1, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - __pyx_v_features = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_features.rcbuffer->pybuffer.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_pybuffernd_features.diminfo[0].strides = __pyx_pybuffernd_features.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_features.diminfo[0].shape = __pyx_pybuffernd_features.rcbuffer->pybuffer.shape[0]; - } - } - __pyx_t_1 = 0; - __Pyx_INCREF(Py_None); - __pyx_v_features = ((PyArrayObject *)Py_None); + __pyx_v_i = (__pyx_v_samples[__pyx_v_p]); - /* "sklearn/tree/_tree.pyx":635 + /* "sklearn/tree/_tree.pyx":706 + * i = samples[p] * - * # Compute the initial criterion value in the node - * criterion.init(y_ptr, y_stride, sample_mask_ptr, n_node_samples, n_total_samples) # <<<<<<<<<<<<<< - * initial_error = criterion.eval() + * if sample_weight != NULL: # <<<<<<<<<<<<<< + * w = sample_weight[i] * */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->init(__pyx_v_criterion, __pyx_v_y_ptr, __pyx_v_y_stride, __pyx_v_sample_mask_ptr, __pyx_v_n_node_samples, __pyx_v_n_total_samples); + __pyx_t_4 = ((__pyx_v_sample_weight != NULL) != 0); + if (__pyx_t_4) { - /* "sklearn/tree/_tree.pyx":636 - * # Compute the initial criterion value in the node - * criterion.init(y_ptr, y_stride, sample_mask_ptr, n_node_samples, n_total_samples) - * initial_error = criterion.eval() # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":707 + * + * if sample_weight != NULL: + * w = sample_weight[i] # <<<<<<<<<<<<<< * - * if initial_error == 0: # break early if the node is pure + * for k in range(n_outputs): */ - __pyx_v_initial_error = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->eval(__pyx_v_criterion); + __pyx_v_w = (__pyx_v_sample_weight[__pyx_v_i]); + goto __pyx_L5; + } + __pyx_L5:; - /* "sklearn/tree/_tree.pyx":638 - * initial_error = criterion.eval() + /* "sklearn/tree/_tree.pyx":709 + * w = sample_weight[i] * - * if initial_error == 0: # break early if the node is pure # <<<<<<<<<<<<<< - * _best_i[0] = best_i - * _best_t[0] = best_t + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * y_ik = y[i * y_stride + k] + * w_y_ik = w * y_ik */ - __pyx_t_2 = (__pyx_v_initial_error == 0.0); - if (__pyx_t_2) { + __pyx_t_5 = __pyx_v_n_outputs; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_k = __pyx_t_6; - /* "sklearn/tree/_tree.pyx":639 + /* "sklearn/tree/_tree.pyx":710 * - * if initial_error == 0: # break early if the node is pure - * _best_i[0] = best_i # <<<<<<<<<<<<<< - * _best_t[0] = best_t - * _best_error[0] = initial_error + * for k in range(n_outputs): + * y_ik = y[i * y_stride + k] # <<<<<<<<<<<<<< + * w_y_ik = w * y_ik + * sum_total[k] += w_y_ik */ - (__pyx_v__best_i[0]) = __pyx_v_best_i; + __pyx_v_y_ik = (__pyx_v_y[((__pyx_v_i * __pyx_v_y_stride) + __pyx_v_k)]); - /* "sklearn/tree/_tree.pyx":640 - * if initial_error == 0: # break early if the node is pure - * _best_i[0] = best_i - * _best_t[0] = best_t # <<<<<<<<<<<<<< - * _best_error[0] = initial_error - * _initial_error[0] = initial_error + /* "sklearn/tree/_tree.pyx":711 + * for k in range(n_outputs): + * y_ik = y[i * y_stride + k] + * w_y_ik = w * y_ik # <<<<<<<<<<<<<< + * sum_total[k] += w_y_ik + * sq_sum_total[k] += w_y_ik * y_ik */ - (__pyx_v__best_t[0]) = __pyx_v_best_t; + __pyx_v_w_y_ik = (__pyx_v_w * __pyx_v_y_ik); - /* "sklearn/tree/_tree.pyx":641 - * _best_i[0] = best_i - * _best_t[0] = best_t - * _best_error[0] = initial_error # <<<<<<<<<<<<<< - * _initial_error[0] = initial_error + /* "sklearn/tree/_tree.pyx":712 + * y_ik = y[i * y_stride + k] + * w_y_ik = w * y_ik + * sum_total[k] += w_y_ik # <<<<<<<<<<<<<< + * sq_sum_total[k] += w_y_ik * y_ik * */ - (__pyx_v__best_error[0]) = __pyx_v_initial_error; + __pyx_t_7 = __pyx_v_k; + (__pyx_v_sum_total[__pyx_t_7]) = ((__pyx_v_sum_total[__pyx_t_7]) + __pyx_v_w_y_ik); - /* "sklearn/tree/_tree.pyx":642 - * _best_t[0] = best_t - * _best_error[0] = initial_error - * _initial_error[0] = initial_error # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":713 + * w_y_ik = w * y_ik + * sum_total[k] += w_y_ik + * sq_sum_total[k] += w_y_ik * y_ik # <<<<<<<<<<<<<< * - * return + * weighted_n_node_samples += w */ - (__pyx_v__initial_error[0]) = __pyx_v_initial_error; + __pyx_t_7 = __pyx_v_k; + (__pyx_v_sq_sum_total[__pyx_t_7]) = ((__pyx_v_sq_sum_total[__pyx_t_7]) + (__pyx_v_w_y_ik * __pyx_v_y_ik)); + } - /* "sklearn/tree/_tree.pyx":644 - * _initial_error[0] = initial_error + /* "sklearn/tree/_tree.pyx":715 + * sq_sum_total[k] += w_y_ik * y_ik * - * return # <<<<<<<<<<<<<< + * weighted_n_node_samples += w # <<<<<<<<<<<<<< * - * best_error = initial_error + * self.weighted_n_node_samples = weighted_n_node_samples */ - goto __pyx_L0; - goto __pyx_L3; + __pyx_v_weighted_n_node_samples = (__pyx_v_weighted_n_node_samples + __pyx_v_w); } - __pyx_L3:; - /* "sklearn/tree/_tree.pyx":646 - * return + /* "sklearn/tree/_tree.pyx":717 + * weighted_n_node_samples += w * - * best_error = initial_error # <<<<<<<<<<<<<< + * self.weighted_n_node_samples = weighted_n_node_samples # <<<<<<<<<<<<<< * - * # Features to consider + * for k in range(n_outputs): */ - __pyx_v_best_error = __pyx_v_initial_error; + __pyx_v_self->__pyx_base.weighted_n_node_samples = __pyx_v_weighted_n_node_samples; - /* "sklearn/tree/_tree.pyx":649 + /* "sklearn/tree/_tree.pyx":719 + * self.weighted_n_node_samples = weighted_n_node_samples * - * # Features to consider - * features = np.arange(n_features, dtype=np.int32) # <<<<<<<<<<<<<< + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * mean_total[k] = sum_total[k] / weighted_n_node_samples * - * if max_features < 0 or max_features >= n_features: */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__arange); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyInt_FromLong(__pyx_v_n_features); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__int32); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = ((PyArrayObject *)__pyx_t_7); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_features.rcbuffer->pybuffer); - __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_features.rcbuffer->pybuffer, (PyObject*)__pyx_t_1, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_8 < 0)) { - PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_features.rcbuffer->pybuffer, (PyObject*)__pyx_v_features, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); - } - } - __pyx_pybuffernd_features.diminfo[0].strides = __pyx_pybuffernd_features.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_features.diminfo[0].shape = __pyx_pybuffernd_features.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_features)); - __pyx_v_features = ((PyArrayObject *)__pyx_t_7); - __pyx_t_7 = 0; + __pyx_t_1 = __pyx_v_n_outputs; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_k = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":651 - * features = np.arange(n_features, dtype=np.int32) + /* "sklearn/tree/_tree.pyx":720 * - * if max_features < 0 or max_features >= n_features: # <<<<<<<<<<<<<< - * max_features = n_features + * for k in range(n_outputs): + * mean_total[k] = sum_total[k] / weighted_n_node_samples # <<<<<<<<<<<<<< * + * # Reset to pos=start */ - __pyx_t_2 = (__pyx_v_max_features < 0); - if (!__pyx_t_2) { - __pyx_t_12 = (__pyx_v_max_features >= __pyx_v_n_features); - __pyx_t_13 = __pyx_t_12; - } else { - __pyx_t_13 = __pyx_t_2; + (__pyx_v_mean_total[__pyx_v_k]) = ((__pyx_v_sum_total[__pyx_v_k]) / __pyx_v_weighted_n_node_samples); } - if (__pyx_t_13) { - /* "sklearn/tree/_tree.pyx":652 + /* "sklearn/tree/_tree.pyx":723 * - * if max_features < 0 or max_features >= n_features: - * max_features = n_features # <<<<<<<<<<<<<< + * # Reset to pos=start + * self.reset() # <<<<<<<<<<<<<< * - * else: + * cdef void reset(self) nogil: */ - __pyx_v_max_features = __pyx_v_n_features; - goto __pyx_L4; - } - /*else*/ { + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.reset(((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self)); - /* "sklearn/tree/_tree.pyx":655 - * - * else: - * features = random_state.permutation(features)[:max_features] # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":653 + * pass * - * # Look for the best split + * cdef void init(self, DOUBLE_t* y, SIZE_t y_stride, DOUBLE_t* sample_weight, # <<<<<<<<<<<<<< + * double weighted_n_samples, SIZE_t* samples, SIZE_t start, + * SIZE_t end) nogil: */ - __pyx_t_7 = PyObject_GetAttr(__pyx_v_random_state, __pyx_n_s__permutation); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_features)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_features)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_features)); - __pyx_t_5 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_GetSlice(__pyx_t_5, 0, __pyx_v_max_features); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = ((PyArrayObject *)__pyx_t_3); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_features.rcbuffer->pybuffer); - __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_features.rcbuffer->pybuffer, (PyObject*)__pyx_t_1, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_8 < 0)) { - PyErr_Fetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_features.rcbuffer->pybuffer, (PyObject*)__pyx_v_features, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_11, __pyx_t_10, __pyx_t_9); - } - } - __pyx_pybuffernd_features.diminfo[0].strides = __pyx_pybuffernd_features.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_features.diminfo[0].shape = __pyx_pybuffernd_features.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_features)); - __pyx_v_features = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - } - __pyx_L4:; - /* "sklearn/tree/_tree.pyx":658 - * - * # Look for the best split - * for feature_idx from 0 <= feature_idx < max_features: # <<<<<<<<<<<<<< - * i = features[feature_idx] + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":725 + * self.reset() * + * cdef void reset(self) nogil: # <<<<<<<<<<<<<< + * """Reset the criterion at pos=start.""" + * self.pos = self.start */ - __pyx_t_8 = __pyx_v_max_features; - for (__pyx_v_feature_idx = 0; __pyx_v_feature_idx < __pyx_t_8; __pyx_v_feature_idx++) { - /* "sklearn/tree/_tree.pyx":659 - * # Look for the best split - * for feature_idx from 0 <= feature_idx < max_features: - * i = features[feature_idx] # <<<<<<<<<<<<<< +static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_reset(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + double *__pyx_v_mean_left; + double *__pyx_v_mean_right; + double *__pyx_v_mean_total; + double *__pyx_v_sq_sum_left; + double *__pyx_v_sq_sum_right; + double *__pyx_v_sq_sum_total; + double *__pyx_v_var_left; + double *__pyx_v_var_right; + double __pyx_v_weighted_n_node_samples; + double *__pyx_v_sum_left; + double *__pyx_v_sum_right; + double *__pyx_v_sum_total; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + double __pyx_t_2; + double *__pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_4; + + /* "sklearn/tree/_tree.pyx":727 + * cdef void reset(self) nogil: + * """Reset the criterion at pos=start.""" + * self.pos = self.start # <<<<<<<<<<<<<< + * + * self.weighted_n_left = 0.0 + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.start; + __pyx_v_self->__pyx_base.pos = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":729 + * self.pos = self.start + * + * self.weighted_n_left = 0.0 # <<<<<<<<<<<<<< + * self.weighted_n_right = self.weighted_n_node_samples * - * # Get i-th col of X and X_sorted */ - __pyx_t_14 = __pyx_v_feature_idx; - __pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_5numpy_int32_t *, __pyx_pybuffernd_features.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_features.diminfo[0].strides)); + __pyx_v_self->__pyx_base.weighted_n_left = 0.0; - /* "sklearn/tree/_tree.pyx":662 + /* "sklearn/tree/_tree.pyx":730 * - * # Get i-th col of X and X_sorted - * X_i = X_ptr + X_stride * i # <<<<<<<<<<<<<< - * X_argsorted_i = X_argsorted_ptr + X_argsorted_stride * i + * self.weighted_n_left = 0.0 + * self.weighted_n_right = self.weighted_n_node_samples # <<<<<<<<<<<<<< * + * cdef SIZE_t n_outputs = self.n_outputs */ - __pyx_v_X_i = (__pyx_v_X_ptr + (__pyx_v_X_stride * __pyx_v_i)); + __pyx_t_2 = __pyx_v_self->__pyx_base.weighted_n_node_samples; + __pyx_v_self->__pyx_base.weighted_n_right = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":663 - * # Get i-th col of X and X_sorted - * X_i = X_ptr + X_stride * i - * X_argsorted_i = X_argsorted_ptr + X_argsorted_stride * i # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":732 + * self.weighted_n_right = self.weighted_n_node_samples * - * # Reset the criterion for this feature + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef double* mean_left = self.mean_left + * cdef double* mean_right = self.mean_right */ - __pyx_v_X_argsorted_i = (__pyx_v_X_argsorted_ptr + (__pyx_v_X_argsorted_stride * __pyx_v_i)); + __pyx_t_1 = __pyx_v_self->__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":666 - * - * # Reset the criterion for this feature - * criterion.reset() # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":733 * - * # Index of smallest sample in X_argsorted_i that is in the sample mask + * cdef SIZE_t n_outputs = self.n_outputs + * cdef double* mean_left = self.mean_left # <<<<<<<<<<<<<< + * cdef double* mean_right = self.mean_right + * cdef double* mean_total = self.mean_total */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->reset(__pyx_v_criterion); + __pyx_t_3 = __pyx_v_self->mean_left; + __pyx_v_mean_left = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":669 - * - * # Index of smallest sample in X_argsorted_i that is in the sample mask - * a = 0 # <<<<<<<<<<<<<< - * - * while sample_mask_ptr[X_argsorted_i[a]] == 0: + /* "sklearn/tree/_tree.pyx":734 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef double* mean_left = self.mean_left + * cdef double* mean_right = self.mean_right # <<<<<<<<<<<<<< + * cdef double* mean_total = self.mean_total + * cdef double* sq_sum_left = self.sq_sum_left */ - __pyx_v_a = 0; + __pyx_t_3 = __pyx_v_self->mean_right; + __pyx_v_mean_right = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":671 - * a = 0 - * - * while sample_mask_ptr[X_argsorted_i[a]] == 0: # <<<<<<<<<<<<<< - * a = a + 1 - * + /* "sklearn/tree/_tree.pyx":735 + * cdef double* mean_left = self.mean_left + * cdef double* mean_right = self.mean_right + * cdef double* mean_total = self.mean_total # <<<<<<<<<<<<<< + * cdef double* sq_sum_left = self.sq_sum_left + * cdef double* sq_sum_right = self.sq_sum_right */ - while (1) { - __pyx_t_13 = ((__pyx_v_sample_mask_ptr[(__pyx_v_X_argsorted_i[__pyx_v_a])]) == 0); - if (!__pyx_t_13) break; + __pyx_t_3 = __pyx_v_self->mean_total; + __pyx_v_mean_total = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":672 - * - * while sample_mask_ptr[X_argsorted_i[a]] == 0: - * a = a + 1 # <<<<<<<<<<<<<< - * - * # Consider splits between two consecutive samples + /* "sklearn/tree/_tree.pyx":736 + * cdef double* mean_right = self.mean_right + * cdef double* mean_total = self.mean_total + * cdef double* sq_sum_left = self.sq_sum_left # <<<<<<<<<<<<<< + * cdef double* sq_sum_right = self.sq_sum_right + * cdef double* sq_sum_total = self.sq_sum_total */ - __pyx_v_a = (__pyx_v_a + 1); - } + __pyx_t_3 = __pyx_v_self->sq_sum_left; + __pyx_v_sq_sum_left = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":675 - * - * # Consider splits between two consecutive samples - * while True: # <<<<<<<<<<<<<< - * # Find the following larger sample - * b = _smallest_sample_larger_than(a, X_i, X_argsorted_i, + /* "sklearn/tree/_tree.pyx":737 + * cdef double* mean_total = self.mean_total + * cdef double* sq_sum_left = self.sq_sum_left + * cdef double* sq_sum_right = self.sq_sum_right # <<<<<<<<<<<<<< + * cdef double* sq_sum_total = self.sq_sum_total + * cdef double* var_left = self.var_left */ - while (1) { - if (!1) break; + __pyx_t_3 = __pyx_v_self->sq_sum_right; + __pyx_v_sq_sum_right = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":678 - * # Find the following larger sample - * b = _smallest_sample_larger_than(a, X_i, X_argsorted_i, - * sample_mask_ptr, n_total_samples) # <<<<<<<<<<<<<< - * if b == -1: - * break + /* "sklearn/tree/_tree.pyx":738 + * cdef double* sq_sum_left = self.sq_sum_left + * cdef double* sq_sum_right = self.sq_sum_right + * cdef double* sq_sum_total = self.sq_sum_total # <<<<<<<<<<<<<< + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right */ - __pyx_v_b = __pyx_f_7sklearn_4tree_5_tree__smallest_sample_larger_than(__pyx_v_a, __pyx_v_X_i, __pyx_v_X_argsorted_i, __pyx_v_sample_mask_ptr, __pyx_v_n_total_samples); + __pyx_t_3 = __pyx_v_self->sq_sum_total; + __pyx_v_sq_sum_total = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":679 - * b = _smallest_sample_larger_than(a, X_i, X_argsorted_i, - * sample_mask_ptr, n_total_samples) - * if b == -1: # <<<<<<<<<<<<<< - * break - * + /* "sklearn/tree/_tree.pyx":739 + * cdef double* sq_sum_right = self.sq_sum_right + * cdef double* sq_sum_total = self.sq_sum_total + * cdef double* var_left = self.var_left # <<<<<<<<<<<<<< + * cdef double* var_right = self.var_right + * cdef double weighted_n_node_samples = self.weighted_n_node_samples */ - __pyx_t_13 = (__pyx_v_b == -1); - if (__pyx_t_13) { + __pyx_t_3 = __pyx_v_self->var_left; + __pyx_v_var_left = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":680 - * sample_mask_ptr, n_total_samples) - * if b == -1: - * break # <<<<<<<<<<<<<< - * - * # Better split than the best so far? + /* "sklearn/tree/_tree.pyx":740 + * cdef double* sq_sum_total = self.sq_sum_total + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right # <<<<<<<<<<<<<< + * cdef double weighted_n_node_samples = self.weighted_n_node_samples + * cdef double* sum_left = self.sum_left */ - goto __pyx_L10_break; - goto __pyx_L11; - } - __pyx_L11:; + __pyx_t_3 = __pyx_v_self->var_right; + __pyx_v_var_right = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":683 - * - * # Better split than the best so far? - * n_left = criterion.update(a, b, y_ptr, y_stride, X_argsorted_i, sample_mask_ptr) # <<<<<<<<<<<<<< - * - * # Only consider splits that respect min_leaf + /* "sklearn/tree/_tree.pyx":741 + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right + * cdef double weighted_n_node_samples = self.weighted_n_node_samples # <<<<<<<<<<<<<< + * cdef double* sum_left = self.sum_left + * cdef double* sum_right = self.sum_right */ - __pyx_v_n_left = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->update(__pyx_v_criterion, __pyx_v_a, __pyx_v_b, __pyx_v_y_ptr, __pyx_v_y_stride, __pyx_v_X_argsorted_i, __pyx_v_sample_mask_ptr); + __pyx_t_2 = __pyx_v_self->__pyx_base.weighted_n_node_samples; + __pyx_v_weighted_n_node_samples = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":686 - * - * # Only consider splits that respect min_leaf - * if n_left < min_samples_leaf or (n_node_samples - n_left) < min_samples_leaf: # <<<<<<<<<<<<<< - * a = b - * continue + /* "sklearn/tree/_tree.pyx":742 + * cdef double* var_right = self.var_right + * cdef double weighted_n_node_samples = self.weighted_n_node_samples + * cdef double* sum_left = self.sum_left # <<<<<<<<<<<<<< + * cdef double* sum_right = self.sum_right + * cdef double* sum_total = self.sum_total */ - __pyx_t_13 = (__pyx_v_n_left < __pyx_v_min_samples_leaf); - if (!__pyx_t_13) { - __pyx_t_2 = ((__pyx_v_n_node_samples - __pyx_v_n_left) < __pyx_v_min_samples_leaf); - __pyx_t_12 = __pyx_t_2; - } else { - __pyx_t_12 = __pyx_t_13; - } - if (__pyx_t_12) { + __pyx_t_3 = __pyx_v_self->sum_left; + __pyx_v_sum_left = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":687 - * # Only consider splits that respect min_leaf - * if n_left < min_samples_leaf or (n_node_samples - n_left) < min_samples_leaf: - * a = b # <<<<<<<<<<<<<< - * continue + /* "sklearn/tree/_tree.pyx":743 + * cdef double weighted_n_node_samples = self.weighted_n_node_samples + * cdef double* sum_left = self.sum_left + * cdef double* sum_right = self.sum_right # <<<<<<<<<<<<<< + * cdef double* sum_total = self.sum_total * */ - __pyx_v_a = __pyx_v_b; + __pyx_t_3 = __pyx_v_self->sum_right; + __pyx_v_sum_right = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":688 - * if n_left < min_samples_leaf or (n_node_samples - n_left) < min_samples_leaf: - * a = b - * continue # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":744 + * cdef double* sum_left = self.sum_left + * cdef double* sum_right = self.sum_right + * cdef double* sum_total = self.sum_total # <<<<<<<<<<<<<< * - * error = criterion.eval() + * cdef SIZE_t k = 0 */ - goto __pyx_L9_continue; - goto __pyx_L12; - } - __pyx_L12:; + __pyx_t_3 = __pyx_v_self->sum_total; + __pyx_v_sum_total = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":690 - * continue + /* "sklearn/tree/_tree.pyx":746 + * cdef double* sum_total = self.sum_total * - * error = criterion.eval() # <<<<<<<<<<<<<< + * cdef SIZE_t k = 0 # <<<<<<<<<<<<<< * - * if error < best_error: + * for k in range(n_outputs): */ - __pyx_v_error = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->eval(__pyx_v_criterion); + __pyx_v_k = 0; - /* "sklearn/tree/_tree.pyx":692 - * error = criterion.eval() + /* "sklearn/tree/_tree.pyx":748 + * cdef SIZE_t k = 0 * - * if error < best_error: # <<<<<<<<<<<<<< - * X_a = X_i[X_argsorted_i[a]] - * X_b = X_i[X_argsorted_i[b]] + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * mean_right[k] = mean_total[k] + * mean_left[k] = 0.0 */ - __pyx_t_12 = (__pyx_v_error < __pyx_v_best_error); - if (__pyx_t_12) { + __pyx_t_1 = __pyx_v_n_outputs; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_1; __pyx_t_4+=1) { + __pyx_v_k = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":693 - * - * if error < best_error: - * X_a = X_i[X_argsorted_i[a]] # <<<<<<<<<<<<<< - * X_b = X_i[X_argsorted_i[b]] + /* "sklearn/tree/_tree.pyx":749 * + * for k in range(n_outputs): + * mean_right[k] = mean_total[k] # <<<<<<<<<<<<<< + * mean_left[k] = 0.0 + * sq_sum_right[k] = sq_sum_total[k] */ - __pyx_v_X_a = (__pyx_v_X_i[(__pyx_v_X_argsorted_i[__pyx_v_a])]); + (__pyx_v_mean_right[__pyx_v_k]) = (__pyx_v_mean_total[__pyx_v_k]); - /* "sklearn/tree/_tree.pyx":694 - * if error < best_error: - * X_a = X_i[X_argsorted_i[a]] - * X_b = X_i[X_argsorted_i[b]] # <<<<<<<<<<<<<< - * - * t = X_a + (X_b - X_a) / 2.0 + /* "sklearn/tree/_tree.pyx":750 + * for k in range(n_outputs): + * mean_right[k] = mean_total[k] + * mean_left[k] = 0.0 # <<<<<<<<<<<<<< + * sq_sum_right[k] = sq_sum_total[k] + * sq_sum_left[k] = 0.0 */ - __pyx_v_X_b = (__pyx_v_X_i[(__pyx_v_X_argsorted_i[__pyx_v_b])]); + (__pyx_v_mean_left[__pyx_v_k]) = 0.0; - /* "sklearn/tree/_tree.pyx":696 - * X_b = X_i[X_argsorted_i[b]] - * - * t = X_a + (X_b - X_a) / 2.0 # <<<<<<<<<<<<<< - * if t == X_b: - * t = X_a + /* "sklearn/tree/_tree.pyx":751 + * mean_right[k] = mean_total[k] + * mean_left[k] = 0.0 + * sq_sum_right[k] = sq_sum_total[k] # <<<<<<<<<<<<<< + * sq_sum_left[k] = 0.0 + * var_right[k] = (sq_sum_right[k] / weighted_n_node_samples - */ - __pyx_v_t = (__pyx_v_X_a + ((__pyx_v_X_b - __pyx_v_X_a) / 2.0)); + (__pyx_v_sq_sum_right[__pyx_v_k]) = (__pyx_v_sq_sum_total[__pyx_v_k]); - /* "sklearn/tree/_tree.pyx":697 - * - * t = X_a + (X_b - X_a) / 2.0 - * if t == X_b: # <<<<<<<<<<<<<< - * t = X_a - * + /* "sklearn/tree/_tree.pyx":752 + * mean_left[k] = 0.0 + * sq_sum_right[k] = sq_sum_total[k] + * sq_sum_left[k] = 0.0 # <<<<<<<<<<<<<< + * var_right[k] = (sq_sum_right[k] / weighted_n_node_samples - + * mean_right[k] * mean_right[k]) */ - __pyx_t_12 = (__pyx_v_t == __pyx_v_X_b); - if (__pyx_t_12) { + (__pyx_v_sq_sum_left[__pyx_v_k]) = 0.0; - /* "sklearn/tree/_tree.pyx":698 - * t = X_a + (X_b - X_a) / 2.0 - * if t == X_b: - * t = X_a # <<<<<<<<<<<<<< - * - * best_i = i + /* "sklearn/tree/_tree.pyx":753 + * sq_sum_right[k] = sq_sum_total[k] + * sq_sum_left[k] = 0.0 + * var_right[k] = (sq_sum_right[k] / weighted_n_node_samples - # <<<<<<<<<<<<<< + * mean_right[k] * mean_right[k]) + * var_left[k] = 0.0 */ - __pyx_v_t = __pyx_v_X_a; - goto __pyx_L14; - } - __pyx_L14:; + (__pyx_v_var_right[__pyx_v_k]) = (((__pyx_v_sq_sum_right[__pyx_v_k]) / __pyx_v_weighted_n_node_samples) - ((__pyx_v_mean_right[__pyx_v_k]) * (__pyx_v_mean_right[__pyx_v_k]))); + + /* "sklearn/tree/_tree.pyx":755 + * var_right[k] = (sq_sum_right[k] / weighted_n_node_samples - + * mean_right[k] * mean_right[k]) + * var_left[k] = 0.0 # <<<<<<<<<<<<<< + * sum_right[k] = sum_total[k] + * sum_left[k] = 0.0 + */ + (__pyx_v_var_left[__pyx_v_k]) = 0.0; - /* "sklearn/tree/_tree.pyx":700 - * t = X_a + /* "sklearn/tree/_tree.pyx":756 + * mean_right[k] * mean_right[k]) + * var_left[k] = 0.0 + * sum_right[k] = sum_total[k] # <<<<<<<<<<<<<< + * sum_left[k] = 0.0 * - * best_i = i # <<<<<<<<<<<<<< - * best_t = t - * best_error = error */ - __pyx_v_best_i = __pyx_v_i; + (__pyx_v_sum_right[__pyx_v_k]) = (__pyx_v_sum_total[__pyx_v_k]); - /* "sklearn/tree/_tree.pyx":701 + /* "sklearn/tree/_tree.pyx":757 + * var_left[k] = 0.0 + * sum_right[k] = sum_total[k] + * sum_left[k] = 0.0 # <<<<<<<<<<<<<< * - * best_i = i - * best_t = t # <<<<<<<<<<<<<< - * best_error = error + * cdef void update(self, SIZE_t new_pos) nogil: + */ + (__pyx_v_sum_left[__pyx_v_k]) = 0.0; + } + + /* "sklearn/tree/_tree.pyx":725 + * self.reset() * + * cdef void reset(self) nogil: # <<<<<<<<<<<<<< + * """Reset the criterion at pos=start.""" + * self.pos = self.start */ - __pyx_v_best_t = __pyx_v_t; - /* "sklearn/tree/_tree.pyx":702 - * best_i = i - * best_t = t - * best_error = error # <<<<<<<<<<<<<< + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":759 + * sum_left[k] = 0.0 * - * # Proceed to the next interval + * cdef void update(self, SIZE_t new_pos) nogil: # <<<<<<<<<<<<<< + * """Update the collected statistics by moving samples[pos:new_pos] from + * the right child to the left child.""" */ - __pyx_v_best_error = __pyx_v_error; - goto __pyx_L13; - } - __pyx_L13:; - /* "sklearn/tree/_tree.pyx":705 +static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_update(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_new_pos) { + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_y_stride; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_pos; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + double *__pyx_v_mean_left; + double *__pyx_v_mean_right; + double *__pyx_v_sq_sum_left; + double *__pyx_v_sq_sum_right; + double *__pyx_v_var_left; + double *__pyx_v_var_right; + double *__pyx_v_sum_left; + double *__pyx_v_sum_right; + double __pyx_v_weighted_n_left; + double __pyx_v_weighted_n_right; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t __pyx_v_w; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t __pyx_v_diff_w; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t __pyx_v_y_ik; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t __pyx_v_w_y_ik; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_3; + double *__pyx_t_4; + double __pyx_t_5; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_6; + int __pyx_t_7; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_8; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_9; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":762 + * """Update the collected statistics by moving samples[pos:new_pos] from + * the right child to the left child.""" + * cdef DOUBLE_t* y = self.y # <<<<<<<<<<<<<< + * cdef SIZE_t y_stride = self.y_stride + * cdef DOUBLE_t* sample_weight = self.sample_weight + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.y; + __pyx_v_y = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":763 + * the right child to the left child.""" + * cdef DOUBLE_t* y = self.y + * cdef SIZE_t y_stride = self.y_stride # <<<<<<<<<<<<<< + * cdef DOUBLE_t* sample_weight = self.sample_weight * - * # Proceed to the next interval - * a = b # <<<<<<<<<<<<<< + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.y_stride; + __pyx_v_y_stride = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":764 + * cdef DOUBLE_t* y = self.y + * cdef SIZE_t y_stride = self.y_stride + * cdef DOUBLE_t* sample_weight = self.sample_weight # <<<<<<<<<<<<<< * - * _best_i[0] = best_i + * cdef SIZE_t* samples = self.samples */ - __pyx_v_a = __pyx_v_b; - __pyx_L9_continue:; - } - __pyx_L10_break:; - } + __pyx_t_1 = __pyx_v_self->__pyx_base.sample_weight; + __pyx_v_sample_weight = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":707 - * a = b + /* "sklearn/tree/_tree.pyx":766 + * cdef DOUBLE_t* sample_weight = self.sample_weight + * + * cdef SIZE_t* samples = self.samples # <<<<<<<<<<<<<< + * cdef SIZE_t pos = self.pos * - * _best_i[0] = best_i # <<<<<<<<<<<<<< - * _best_t[0] = best_t - * _best_error[0] = best_error */ - (__pyx_v__best_i[0]) = __pyx_v_best_i; + __pyx_t_3 = __pyx_v_self->__pyx_base.samples; + __pyx_v_samples = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":708 + /* "sklearn/tree/_tree.pyx":767 + * + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t pos = self.pos # <<<<<<<<<<<<<< * - * _best_i[0] = best_i - * _best_t[0] = best_t # <<<<<<<<<<<<<< - * _best_error[0] = best_error - * _initial_error[0] = initial_error + * cdef SIZE_t n_outputs = self.n_outputs */ - (__pyx_v__best_t[0]) = __pyx_v_best_t; + __pyx_t_2 = __pyx_v_self->__pyx_base.pos; + __pyx_v_pos = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":709 - * _best_i[0] = best_i - * _best_t[0] = best_t - * _best_error[0] = best_error # <<<<<<<<<<<<<< - * _initial_error[0] = initial_error + /* "sklearn/tree/_tree.pyx":769 + * cdef SIZE_t pos = self.pos * + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef double* mean_left = self.mean_left + * cdef double* mean_right = self.mean_right */ - (__pyx_v__best_error[0]) = __pyx_v_best_error; + __pyx_t_2 = __pyx_v_self->__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":710 - * _best_t[0] = best_t - * _best_error[0] = best_error - * _initial_error[0] = initial_error # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":770 * - * cdef void find_random_split(self, DTYPE_t* X_ptr, int X_stride, + * cdef SIZE_t n_outputs = self.n_outputs + * cdef double* mean_left = self.mean_left # <<<<<<<<<<<<<< + * cdef double* mean_right = self.mean_right + * cdef double* sq_sum_left = self.sq_sum_left */ - (__pyx_v__initial_error[0]) = __pyx_v_initial_error; + __pyx_t_4 = __pyx_v_self->mean_left; + __pyx_v_mean_left = __pyx_t_4; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_features.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_WriteUnraisable("sklearn.tree._tree.Tree.find_best_split", __pyx_clineno, __pyx_lineno, __pyx_filename); - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_features.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_criterion); - __Pyx_XDECREF(__pyx_v_random_state); - __Pyx_XDECREF((PyObject *)__pyx_v_features); - __Pyx_RefNannyFinishContext(); -} + /* "sklearn/tree/_tree.pyx":771 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef double* mean_left = self.mean_left + * cdef double* mean_right = self.mean_right # <<<<<<<<<<<<<< + * cdef double* sq_sum_left = self.sq_sum_left + * cdef double* sq_sum_right = self.sq_sum_right + */ + __pyx_t_4 = __pyx_v_self->mean_right; + __pyx_v_mean_right = __pyx_t_4; -/* "sklearn/tree/_tree.pyx":712 - * _initial_error[0] = initial_error - * - * cdef void find_random_split(self, DTYPE_t* X_ptr, int X_stride, # <<<<<<<<<<<<<< - * int* X_argsorted_ptr, int X_argsorted_stride, - * DOUBLE_t* y_ptr, int y_stride, + /* "sklearn/tree/_tree.pyx":772 + * cdef double* mean_left = self.mean_left + * cdef double* mean_right = self.mean_right + * cdef double* sq_sum_left = self.sq_sum_left # <<<<<<<<<<<<<< + * cdef double* sq_sum_right = self.sq_sum_right + * cdef double* var_left = self.var_left */ + __pyx_t_4 = __pyx_v_self->sq_sum_left; + __pyx_v_sq_sum_left = __pyx_t_4; -static void __pyx_f_7sklearn_4tree_5_tree_4Tree_find_random_split(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_ptr, int __pyx_v_X_stride, int *__pyx_v_X_argsorted_ptr, int __pyx_v_X_argsorted_stride, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y_ptr, int __pyx_v_y_stride, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *__pyx_v_sample_mask_ptr, int __pyx_v_n_node_samples, int __pyx_v_n_total_samples, int *__pyx_v__best_i, double *__pyx_v__best_t, double *__pyx_v__best_error, double *__pyx_v__initial_error) { - struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion = 0; - int __pyx_v_n_features; - int __pyx_v_max_features; - int __pyx_v_min_samples_leaf; - PyObject *__pyx_v_random_state = 0; - int __pyx_v_i; - int __pyx_v_a; - int __pyx_v_b; - int __pyx_v_c; - int __pyx_v_best_i; - __pyx_t_5numpy_int32_t __pyx_v_feature_idx; - int __pyx_v_n_left; - double __pyx_v_random; - double __pyx_v_t; - double __pyx_v_initial_error; - double __pyx_v_error; - double __pyx_v_best_error; - double __pyx_v_best_t; - __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_i; - int *__pyx_v_X_argsorted_i; - __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_X_a; - __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_X_b; - PyArrayObject *__pyx_v_features = 0; - __Pyx_LocalBuf_ND __pyx_pybuffernd_features; - __Pyx_Buffer __pyx_pybuffer_features; - __Pyx_RefNannyDeclarations - PyArrayObject *__pyx_t_1 = NULL; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - int __pyx_t_12; - int __pyx_t_13; - __pyx_t_5numpy_int32_t __pyx_t_14; - double __pyx_t_15; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("find_random_split", 0); - __pyx_pybuffer_features.pybuffer.buf = NULL; - __pyx_pybuffer_features.refcount = 0; - __pyx_pybuffernd_features.data = NULL; - __pyx_pybuffernd_features.rcbuffer = &__pyx_pybuffer_features; - - /* "sklearn/tree/_tree.pyx":722 - * among randomly drawn thresholds at each feature.""" - * # Variables declarations - * cdef Criterion criterion = self.criterion # <<<<<<<<<<<<<< - * cdef int n_features = self.n_features - * cdef int max_features = self.max_features + /* "sklearn/tree/_tree.pyx":773 + * cdef double* mean_right = self.mean_right + * cdef double* sq_sum_left = self.sq_sum_left + * cdef double* sq_sum_right = self.sq_sum_right # <<<<<<<<<<<<<< + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right */ - __Pyx_INCREF(((PyObject *)__pyx_v_self->criterion)); - __pyx_v_criterion = __pyx_v_self->criterion; + __pyx_t_4 = __pyx_v_self->sq_sum_right; + __pyx_v_sq_sum_right = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":723 - * # Variables declarations - * cdef Criterion criterion = self.criterion - * cdef int n_features = self.n_features # <<<<<<<<<<<<<< - * cdef int max_features = self.max_features - * cdef int min_samples_leaf = self.min_samples_leaf + /* "sklearn/tree/_tree.pyx":774 + * cdef double* sq_sum_left = self.sq_sum_left + * cdef double* sq_sum_right = self.sq_sum_right + * cdef double* var_left = self.var_left # <<<<<<<<<<<<<< + * cdef double* var_right = self.var_right + * cdef double* sum_left = self.sum_left */ - __pyx_v_n_features = __pyx_v_self->n_features; + __pyx_t_4 = __pyx_v_self->var_left; + __pyx_v_var_left = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":724 - * cdef Criterion criterion = self.criterion - * cdef int n_features = self.n_features - * cdef int max_features = self.max_features # <<<<<<<<<<<<<< - * cdef int min_samples_leaf = self.min_samples_leaf - * cdef object random_state = self.random_state + /* "sklearn/tree/_tree.pyx":775 + * cdef double* sq_sum_right = self.sq_sum_right + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right # <<<<<<<<<<<<<< + * cdef double* sum_left = self.sum_left + * cdef double* sum_right = self.sum_right */ - __pyx_v_max_features = __pyx_v_self->max_features; + __pyx_t_4 = __pyx_v_self->var_right; + __pyx_v_var_right = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":725 - * cdef int n_features = self.n_features - * cdef int max_features = self.max_features - * cdef int min_samples_leaf = self.min_samples_leaf # <<<<<<<<<<<<<< - * cdef object random_state = self.random_state + /* "sklearn/tree/_tree.pyx":776 + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right + * cdef double* sum_left = self.sum_left # <<<<<<<<<<<<<< + * cdef double* sum_right = self.sum_right * */ - __pyx_v_min_samples_leaf = __pyx_v_self->min_samples_leaf; + __pyx_t_4 = __pyx_v_self->sum_left; + __pyx_v_sum_left = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":726 - * cdef int max_features = self.max_features - * cdef int min_samples_leaf = self.min_samples_leaf - * cdef object random_state = self.random_state # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":777 + * cdef double* var_right = self.var_right + * cdef double* sum_left = self.sum_left + * cdef double* sum_right = self.sum_right # <<<<<<<<<<<<<< * - * cdef int i, a, b, c, best_i = -1 + * cdef double weighted_n_left = self.weighted_n_left */ - __Pyx_INCREF(__pyx_v_self->random_state); - __pyx_v_random_state = __pyx_v_self->random_state; + __pyx_t_4 = __pyx_v_self->sum_right; + __pyx_v_sum_right = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":728 - * cdef object random_state = self.random_state + /* "sklearn/tree/_tree.pyx":779 + * cdef double* sum_right = self.sum_right + * + * cdef double weighted_n_left = self.weighted_n_left # <<<<<<<<<<<<<< + * cdef double weighted_n_right = self.weighted_n_right * - * cdef int i, a, b, c, best_i = -1 # <<<<<<<<<<<<<< - * cdef np.int32_t feature_idx = -1 - * cdef int n_left = 0 */ - __pyx_v_best_i = -1; + __pyx_t_5 = __pyx_v_self->__pyx_base.weighted_n_left; + __pyx_v_weighted_n_left = __pyx_t_5; - /* "sklearn/tree/_tree.pyx":729 + /* "sklearn/tree/_tree.pyx":780 + * + * cdef double weighted_n_left = self.weighted_n_left + * cdef double weighted_n_right = self.weighted_n_right # <<<<<<<<<<<<<< * - * cdef int i, a, b, c, best_i = -1 - * cdef np.int32_t feature_idx = -1 # <<<<<<<<<<<<<< - * cdef int n_left = 0 - * cdef double random + * cdef SIZE_t i */ - __pyx_v_feature_idx = -1; + __pyx_t_5 = __pyx_v_self->__pyx_base.weighted_n_right; + __pyx_v_weighted_n_right = __pyx_t_5; - /* "sklearn/tree/_tree.pyx":730 - * cdef int i, a, b, c, best_i = -1 - * cdef np.int32_t feature_idx = -1 - * cdef int n_left = 0 # <<<<<<<<<<<<<< - * cdef double random + /* "sklearn/tree/_tree.pyx":785 + * cdef SIZE_t p + * cdef SIZE_t k + * cdef DOUBLE_t w = 1.0 # <<<<<<<<<<<<<< + * cdef DOUBLE_t diff_w = 0.0 + * cdef DOUBLE_t y_ik, w_y_ik + */ + __pyx_v_w = 1.0; + + /* "sklearn/tree/_tree.pyx":786 + * cdef SIZE_t k + * cdef DOUBLE_t w = 1.0 + * cdef DOUBLE_t diff_w = 0.0 # <<<<<<<<<<<<<< + * cdef DOUBLE_t y_ik, w_y_ik * */ - __pyx_v_n_left = 0; + __pyx_v_diff_w = 0.0; - /* "sklearn/tree/_tree.pyx":734 + /* "sklearn/tree/_tree.pyx":790 * - * cdef double t, initial_error, error - * cdef double best_error = INFINITY, best_t = INFINITY # <<<<<<<<<<<<<< + * # Note: We assume start <= pos < new_pos <= end + * for p in range(pos, new_pos): # <<<<<<<<<<<<<< + * i = samples[p] * - * cdef DTYPE_t* X_i = NULL */ - __pyx_v_best_error = __pyx_v_7sklearn_4tree_5_tree_INFINITY; - __pyx_v_best_t = __pyx_v_7sklearn_4tree_5_tree_INFINITY; + __pyx_t_2 = __pyx_v_new_pos; + for (__pyx_t_6 = __pyx_v_pos; __pyx_t_6 < __pyx_t_2; __pyx_t_6+=1) { + __pyx_v_p = __pyx_t_6; - /* "sklearn/tree/_tree.pyx":736 - * cdef double best_error = INFINITY, best_t = INFINITY + /* "sklearn/tree/_tree.pyx":791 + * # Note: We assume start <= pos < new_pos <= end + * for p in range(pos, new_pos): + * i = samples[p] # <<<<<<<<<<<<<< * - * cdef DTYPE_t* X_i = NULL # <<<<<<<<<<<<<< - * cdef int* X_argsorted_i = NULL - * cdef DTYPE_t X_a, X_b + * if sample_weight != NULL: */ - __pyx_v_X_i = NULL; + __pyx_v_i = (__pyx_v_samples[__pyx_v_p]); - /* "sklearn/tree/_tree.pyx":737 + /* "sklearn/tree/_tree.pyx":793 + * i = samples[p] * - * cdef DTYPE_t* X_i = NULL - * cdef int* X_argsorted_i = NULL # <<<<<<<<<<<<<< - * cdef DTYPE_t X_a, X_b + * if sample_weight != NULL: # <<<<<<<<<<<<<< + * w = sample_weight[i] * */ - __pyx_v_X_argsorted_i = NULL; + __pyx_t_7 = ((__pyx_v_sample_weight != NULL) != 0); + if (__pyx_t_7) { - /* "sklearn/tree/_tree.pyx":740 - * cdef DTYPE_t X_a, X_b + /* "sklearn/tree/_tree.pyx":794 * - * cdef np.ndarray[np.int32_t, ndim=1, mode="c"] features = None # <<<<<<<<<<<<<< + * if sample_weight != NULL: + * w = sample_weight[i] # <<<<<<<<<<<<<< * - * # Compute the initial criterion value in the node + * for k in range(n_outputs): */ - __pyx_t_1 = ((PyArrayObject *)Py_None); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_features.rcbuffer->pybuffer, (PyObject*)__pyx_t_1, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - __pyx_v_features = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_features.rcbuffer->pybuffer.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 740; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_pybuffernd_features.diminfo[0].strides = __pyx_pybuffernd_features.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_features.diminfo[0].shape = __pyx_pybuffernd_features.rcbuffer->pybuffer.shape[0]; + __pyx_v_w = (__pyx_v_sample_weight[__pyx_v_i]); + goto __pyx_L5; } - } - __pyx_t_1 = 0; - __Pyx_INCREF(Py_None); - __pyx_v_features = ((PyArrayObject *)Py_None); + __pyx_L5:; - /* "sklearn/tree/_tree.pyx":743 - * - * # Compute the initial criterion value in the node - * criterion.init(y_ptr, y_stride, sample_mask_ptr, n_node_samples, n_total_samples) # <<<<<<<<<<<<<< - * initial_error = criterion.eval() + /* "sklearn/tree/_tree.pyx":796 + * w = sample_weight[i] * + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * y_ik = y[i * y_stride + k] + * w_y_ik = w * y_ik */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->init(__pyx_v_criterion, __pyx_v_y_ptr, __pyx_v_y_stride, __pyx_v_sample_mask_ptr, __pyx_v_n_node_samples, __pyx_v_n_total_samples); + __pyx_t_8 = __pyx_v_n_outputs; + for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { + __pyx_v_k = __pyx_t_9; - /* "sklearn/tree/_tree.pyx":744 - * # Compute the initial criterion value in the node - * criterion.init(y_ptr, y_stride, sample_mask_ptr, n_node_samples, n_total_samples) - * initial_error = criterion.eval() # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":797 + * + * for k in range(n_outputs): + * y_ik = y[i * y_stride + k] # <<<<<<<<<<<<<< + * w_y_ik = w * y_ik * - * if initial_error == 0: # break early if the node is pure */ - __pyx_v_initial_error = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->eval(__pyx_v_criterion); + __pyx_v_y_ik = (__pyx_v_y[((__pyx_v_i * __pyx_v_y_stride) + __pyx_v_k)]); - /* "sklearn/tree/_tree.pyx":746 - * initial_error = criterion.eval() + /* "sklearn/tree/_tree.pyx":798 + * for k in range(n_outputs): + * y_ik = y[i * y_stride + k] + * w_y_ik = w * y_ik # <<<<<<<<<<<<<< * - * if initial_error == 0: # break early if the node is pure # <<<<<<<<<<<<<< - * _best_i[0] = best_i - * _best_t[0] = best_t + * sum_left[k] += w_y_ik */ - __pyx_t_2 = (__pyx_v_initial_error == 0.0); - if (__pyx_t_2) { + __pyx_v_w_y_ik = (__pyx_v_w * __pyx_v_y_ik); - /* "sklearn/tree/_tree.pyx":747 + /* "sklearn/tree/_tree.pyx":800 + * w_y_ik = w * y_ik + * + * sum_left[k] += w_y_ik # <<<<<<<<<<<<<< + * sum_right[k] -= w_y_ik * - * if initial_error == 0: # break early if the node is pure - * _best_i[0] = best_i # <<<<<<<<<<<<<< - * _best_t[0] = best_t - * _best_error[0] = initial_error */ - (__pyx_v__best_i[0]) = __pyx_v_best_i; + __pyx_t_10 = __pyx_v_k; + (__pyx_v_sum_left[__pyx_t_10]) = ((__pyx_v_sum_left[__pyx_t_10]) + __pyx_v_w_y_ik); - /* "sklearn/tree/_tree.pyx":748 - * if initial_error == 0: # break early if the node is pure - * _best_i[0] = best_i - * _best_t[0] = best_t # <<<<<<<<<<<<<< - * _best_error[0] = initial_error - * _initial_error[0] = initial_error + /* "sklearn/tree/_tree.pyx":801 + * + * sum_left[k] += w_y_ik + * sum_right[k] -= w_y_ik # <<<<<<<<<<<<<< + * + * sq_sum_left[k] += w_y_ik * y_ik */ - (__pyx_v__best_t[0]) = __pyx_v_best_t; + __pyx_t_10 = __pyx_v_k; + (__pyx_v_sum_right[__pyx_t_10]) = ((__pyx_v_sum_right[__pyx_t_10]) - __pyx_v_w_y_ik); - /* "sklearn/tree/_tree.pyx":749 - * _best_i[0] = best_i - * _best_t[0] = best_t - * _best_error[0] = initial_error # <<<<<<<<<<<<<< - * _initial_error[0] = initial_error + /* "sklearn/tree/_tree.pyx":803 + * sum_right[k] -= w_y_ik + * + * sq_sum_left[k] += w_y_ik * y_ik # <<<<<<<<<<<<<< + * sq_sum_right[k] -= w_y_ik * y_ik * */ - (__pyx_v__best_error[0]) = __pyx_v_initial_error; + __pyx_t_10 = __pyx_v_k; + (__pyx_v_sq_sum_left[__pyx_t_10]) = ((__pyx_v_sq_sum_left[__pyx_t_10]) + (__pyx_v_w_y_ik * __pyx_v_y_ik)); - /* "sklearn/tree/_tree.pyx":750 - * _best_t[0] = best_t - * _best_error[0] = initial_error - * _initial_error[0] = initial_error # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":804 * - * return + * sq_sum_left[k] += w_y_ik * y_ik + * sq_sum_right[k] -= w_y_ik * y_ik # <<<<<<<<<<<<<< + * + * diff_w += w */ - (__pyx_v__initial_error[0]) = __pyx_v_initial_error; + __pyx_t_10 = __pyx_v_k; + (__pyx_v_sq_sum_right[__pyx_t_10]) = ((__pyx_v_sq_sum_right[__pyx_t_10]) - (__pyx_v_w_y_ik * __pyx_v_y_ik)); + } - /* "sklearn/tree/_tree.pyx":752 - * _initial_error[0] = initial_error + /* "sklearn/tree/_tree.pyx":806 + * sq_sum_right[k] -= w_y_ik * y_ik * - * return # <<<<<<<<<<<<<< + * diff_w += w # <<<<<<<<<<<<<< * - * best_error = initial_error + * weighted_n_left += diff_w */ - goto __pyx_L0; - goto __pyx_L3; + __pyx_v_diff_w = (__pyx_v_diff_w + __pyx_v_w); } - __pyx_L3:; - /* "sklearn/tree/_tree.pyx":754 - * return + /* "sklearn/tree/_tree.pyx":808 + * diff_w += w * - * best_error = initial_error # <<<<<<<<<<<<<< + * weighted_n_left += diff_w # <<<<<<<<<<<<<< + * weighted_n_right -= diff_w * - * # Features to consider */ - __pyx_v_best_error = __pyx_v_initial_error; + __pyx_v_weighted_n_left = (__pyx_v_weighted_n_left + __pyx_v_diff_w); - /* "sklearn/tree/_tree.pyx":757 + /* "sklearn/tree/_tree.pyx":809 * - * # Features to consider - * features = np.arange(n_features, dtype=np.int32) # <<<<<<<<<<<<<< + * weighted_n_left += diff_w + * weighted_n_right -= diff_w # <<<<<<<<<<<<<< * - * if max_features < 0 or max_features >= n_features: + * for k in range(n_outputs): */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__arange); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyInt_FromLong(__pyx_v_n_features); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__int32); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = ((PyArrayObject *)__pyx_t_7); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_features.rcbuffer->pybuffer); - __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_features.rcbuffer->pybuffer, (PyObject*)__pyx_t_1, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_8 < 0)) { - PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_features.rcbuffer->pybuffer, (PyObject*)__pyx_v_features, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); - } - } - __pyx_pybuffernd_features.diminfo[0].strides = __pyx_pybuffernd_features.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_features.diminfo[0].shape = __pyx_pybuffernd_features.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 757; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_features)); - __pyx_v_features = ((PyArrayObject *)__pyx_t_7); - __pyx_t_7 = 0; + __pyx_v_weighted_n_right = (__pyx_v_weighted_n_right - __pyx_v_diff_w); - /* "sklearn/tree/_tree.pyx":759 - * features = np.arange(n_features, dtype=np.int32) - * - * if max_features < 0 or max_features >= n_features: # <<<<<<<<<<<<<< - * max_features = n_features + /* "sklearn/tree/_tree.pyx":811 + * weighted_n_right -= diff_w * + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * mean_left[k] = sum_left[k] / weighted_n_left + * mean_right[k] = sum_right[k] / weighted_n_right */ - __pyx_t_2 = (__pyx_v_max_features < 0); - if (!__pyx_t_2) { - __pyx_t_12 = (__pyx_v_max_features >= __pyx_v_n_features); - __pyx_t_13 = __pyx_t_12; - } else { - __pyx_t_13 = __pyx_t_2; - } - if (__pyx_t_13) { + __pyx_t_2 = __pyx_v_n_outputs; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_2; __pyx_t_6+=1) { + __pyx_v_k = __pyx_t_6; - /* "sklearn/tree/_tree.pyx":760 - * - * if max_features < 0 or max_features >= n_features: - * max_features = n_features # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":812 * - * else: + * for k in range(n_outputs): + * mean_left[k] = sum_left[k] / weighted_n_left # <<<<<<<<<<<<<< + * mean_right[k] = sum_right[k] / weighted_n_right + * var_left[k] = (sq_sum_left[k] / weighted_n_left - */ - __pyx_v_max_features = __pyx_v_n_features; - goto __pyx_L4; - } - /*else*/ { + (__pyx_v_mean_left[__pyx_v_k]) = ((__pyx_v_sum_left[__pyx_v_k]) / __pyx_v_weighted_n_left); - /* "sklearn/tree/_tree.pyx":763 - * - * else: - * features = random_state.permutation(features)[:max_features] # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":813 + * for k in range(n_outputs): + * mean_left[k] = sum_left[k] / weighted_n_left + * mean_right[k] = sum_right[k] / weighted_n_right # <<<<<<<<<<<<<< + * var_left[k] = (sq_sum_left[k] / weighted_n_left - + * mean_left[k] * mean_left[k]) + */ + (__pyx_v_mean_right[__pyx_v_k]) = ((__pyx_v_sum_right[__pyx_v_k]) / __pyx_v_weighted_n_right); + + /* "sklearn/tree/_tree.pyx":814 + * mean_left[k] = sum_left[k] / weighted_n_left + * mean_right[k] = sum_right[k] / weighted_n_right + * var_left[k] = (sq_sum_left[k] / weighted_n_left - # <<<<<<<<<<<<<< + * mean_left[k] * mean_left[k]) + * var_right[k] = (sq_sum_right[k] / weighted_n_right - + */ + (__pyx_v_var_left[__pyx_v_k]) = (((__pyx_v_sq_sum_left[__pyx_v_k]) / __pyx_v_weighted_n_left) - ((__pyx_v_mean_left[__pyx_v_k]) * (__pyx_v_mean_left[__pyx_v_k]))); + + /* "sklearn/tree/_tree.pyx":816 + * var_left[k] = (sq_sum_left[k] / weighted_n_left - + * mean_left[k] * mean_left[k]) + * var_right[k] = (sq_sum_right[k] / weighted_n_right - # <<<<<<<<<<<<<< + * mean_right[k] * mean_right[k]) * - * # Look for the best split */ - __pyx_t_7 = PyObject_GetAttr(__pyx_v_random_state, __pyx_n_s__permutation); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 763; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 763; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_features)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_features)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_features)); - __pyx_t_5 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 763; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PySequence_GetSlice(__pyx_t_5, 0, __pyx_v_max_features); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 763; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 763; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = ((PyArrayObject *)__pyx_t_3); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_features.rcbuffer->pybuffer); - __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_features.rcbuffer->pybuffer, (PyObject*)__pyx_t_1, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_8 < 0)) { - PyErr_Fetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_features.rcbuffer->pybuffer, (PyObject*)__pyx_v_features, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_11, __pyx_t_10, __pyx_t_9); - } - } - __pyx_pybuffernd_features.diminfo[0].strides = __pyx_pybuffernd_features.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_features.diminfo[0].shape = __pyx_pybuffernd_features.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 763; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_features)); - __pyx_v_features = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; + (__pyx_v_var_right[__pyx_v_k]) = (((__pyx_v_sq_sum_right[__pyx_v_k]) / __pyx_v_weighted_n_right) - ((__pyx_v_mean_right[__pyx_v_k]) * (__pyx_v_mean_right[__pyx_v_k]))); } - __pyx_L4:; - /* "sklearn/tree/_tree.pyx":766 + /* "sklearn/tree/_tree.pyx":819 + * mean_right[k] * mean_right[k]) * - * # Look for the best split - * for feature_idx from 0 <= feature_idx < max_features: # <<<<<<<<<<<<<< - * i = features[feature_idx] + * self.weighted_n_left = weighted_n_left # <<<<<<<<<<<<<< + * self.weighted_n_right = weighted_n_right * */ - __pyx_t_8 = __pyx_v_max_features; - for (__pyx_v_feature_idx = 0; __pyx_v_feature_idx < __pyx_t_8; __pyx_v_feature_idx++) { + __pyx_v_self->__pyx_base.weighted_n_left = __pyx_v_weighted_n_left; - /* "sklearn/tree/_tree.pyx":767 - * # Look for the best split - * for feature_idx from 0 <= feature_idx < max_features: - * i = features[feature_idx] # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":820 * - * # Get i-th col of X and X_sorted + * self.weighted_n_left = weighted_n_left + * self.weighted_n_right = weighted_n_right # <<<<<<<<<<<<<< + * + * self.pos = new_pos */ - __pyx_t_14 = __pyx_v_feature_idx; - __pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_5numpy_int32_t *, __pyx_pybuffernd_features.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_features.diminfo[0].strides)); + __pyx_v_self->__pyx_base.weighted_n_right = __pyx_v_weighted_n_right; - /* "sklearn/tree/_tree.pyx":770 + /* "sklearn/tree/_tree.pyx":822 + * self.weighted_n_right = weighted_n_right * - * # Get i-th col of X and X_sorted - * X_i = X_ptr + X_stride * i # <<<<<<<<<<<<<< - * X_argsorted_i = X_argsorted_ptr + X_argsorted_stride * i + * self.pos = new_pos # <<<<<<<<<<<<<< * + * cdef double node_impurity(self) nogil: */ - __pyx_v_X_i = (__pyx_v_X_ptr + (__pyx_v_X_stride * __pyx_v_i)); + __pyx_v_self->__pyx_base.pos = __pyx_v_new_pos; - /* "sklearn/tree/_tree.pyx":771 - * # Get i-th col of X and X_sorted - * X_i = X_ptr + X_stride * i - * X_argsorted_i = X_argsorted_ptr + X_argsorted_stride * i # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":759 + * sum_left[k] = 0.0 * - * # Reset the criterion for this feature + * cdef void update(self, SIZE_t new_pos) nogil: # <<<<<<<<<<<<<< + * """Update the collected statistics by moving samples[pos:new_pos] from + * the right child to the left child.""" */ - __pyx_v_X_argsorted_i = (__pyx_v_X_argsorted_ptr + (__pyx_v_X_argsorted_stride * __pyx_v_i)); - /* "sklearn/tree/_tree.pyx":774 + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":824 + * self.pos = new_pos * - * # Reset the criterion for this feature - * criterion.reset() # <<<<<<<<<<<<<< + * cdef double node_impurity(self) nogil: # <<<<<<<<<<<<<< + * pass * - * # Find min and max */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->reset(__pyx_v_criterion); - /* "sklearn/tree/_tree.pyx":777 +static double __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_node_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self) { + double __pyx_r; + + /* function exit code */ + __pyx_r = 0; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":827 + * pass * - * # Find min and max - * a = 0 # <<<<<<<<<<<<<< - * while sample_mask_ptr[X_argsorted_i[a]] == 0: - * a = a + 1 + * cdef void children_impurity(self, double* impurity_left, # <<<<<<<<<<<<<< + * double* impurity_right) nogil: + * pass */ - __pyx_v_a = 0; - /* "sklearn/tree/_tree.pyx":778 - * # Find min and max - * a = 0 - * while sample_mask_ptr[X_argsorted_i[a]] == 0: # <<<<<<<<<<<<<< - * a = a + 1 - * X_a = X_i[X_argsorted_i[a]] - */ - while (1) { - __pyx_t_13 = ((__pyx_v_sample_mask_ptr[(__pyx_v_X_argsorted_i[__pyx_v_a])]) == 0); - if (!__pyx_t_13) break; +static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_children_impurity(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, CYTHON_UNUSED double *__pyx_v_impurity_left, CYTHON_UNUSED double *__pyx_v_impurity_right) { + + /* function exit code */ +} - /* "sklearn/tree/_tree.pyx":779 - * a = 0 - * while sample_mask_ptr[X_argsorted_i[a]] == 0: - * a = a + 1 # <<<<<<<<<<<<<< - * X_a = X_i[X_argsorted_i[a]] +/* "sklearn/tree/_tree.pyx":831 + * pass * + * cdef void node_value(self, double* dest) nogil: # <<<<<<<<<<<<<< + * """Compute the node value of samples[start:end] into dest.""" + * memcpy(dest, self.mean_total, self.n_outputs * sizeof(double)) */ - __pyx_v_a = (__pyx_v_a + 1); - } - /* "sklearn/tree/_tree.pyx":780 - * while sample_mask_ptr[X_argsorted_i[a]] == 0: - * a = a + 1 - * X_a = X_i[X_argsorted_i[a]] # <<<<<<<<<<<<<< +static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_node_value(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, double *__pyx_v_dest) { + + /* "sklearn/tree/_tree.pyx":833 + * cdef void node_value(self, double* dest) nogil: + * """Compute the node value of samples[start:end] into dest.""" + * memcpy(dest, self.mean_total, self.n_outputs * sizeof(double)) # <<<<<<<<<<<<<< + * * - * b = n_total_samples - 1 */ - __pyx_v_X_a = (__pyx_v_X_i[(__pyx_v_X_argsorted_i[__pyx_v_a])]); + memcpy(__pyx_v_dest, __pyx_v_self->mean_total, (__pyx_v_self->__pyx_base.n_outputs * (sizeof(double)))); - /* "sklearn/tree/_tree.pyx":782 - * X_a = X_i[X_argsorted_i[a]] + /* "sklearn/tree/_tree.pyx":831 + * pass * - * b = n_total_samples - 1 # <<<<<<<<<<<<<< - * while sample_mask_ptr[X_argsorted_i[b]] == 0: - * b = b - 1 + * cdef void node_value(self, double* dest) nogil: # <<<<<<<<<<<<<< + * """Compute the node value of samples[start:end] into dest.""" + * memcpy(dest, self.mean_total, self.n_outputs * sizeof(double)) */ - __pyx_v_b = (__pyx_v_n_total_samples - 1); - /* "sklearn/tree/_tree.pyx":783 - * - * b = n_total_samples - 1 - * while sample_mask_ptr[X_argsorted_i[b]] == 0: # <<<<<<<<<<<<<< - * b = b - 1 - * X_b = X_i[X_argsorted_i[b]] + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":841 + * MSE = var_left + var_right + * """ + * cdef double node_impurity(self) nogil: # <<<<<<<<<<<<<< + * """Evaluate the impurity of the current node, i.e. the impurity of + * samples[start:end].""" */ - while (1) { - __pyx_t_13 = ((__pyx_v_sample_mask_ptr[(__pyx_v_X_argsorted_i[__pyx_v_b])]) == 0); - if (!__pyx_t_13) break; - /* "sklearn/tree/_tree.pyx":784 - * b = n_total_samples - 1 - * while sample_mask_ptr[X_argsorted_i[b]] == 0: - * b = b - 1 # <<<<<<<<<<<<<< - * X_b = X_i[X_argsorted_i[b]] +static double __pyx_f_7sklearn_4tree_5_tree_3MSE_node_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_MSE *__pyx_v_self) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + double *__pyx_v_sq_sum_total; + double *__pyx_v_mean_total; + double __pyx_v_weighted_n_node_samples; + double __pyx_v_total; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + double __pyx_r; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + double *__pyx_t_2; + double __pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_4; + + /* "sklearn/tree/_tree.pyx":844 + * """Evaluate the impurity of the current node, i.e. the impurity of + * samples[start:end].""" + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef double* sq_sum_total = self.sq_sum_total + * cdef double* mean_total = self.mean_total + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":845 + * samples[start:end].""" + * cdef SIZE_t n_outputs = self.n_outputs + * cdef double* sq_sum_total = self.sq_sum_total # <<<<<<<<<<<<<< + * cdef double* mean_total = self.mean_total + * cdef double weighted_n_node_samples = self.weighted_n_node_samples + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.sq_sum_total; + __pyx_v_sq_sum_total = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":846 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef double* sq_sum_total = self.sq_sum_total + * cdef double* mean_total = self.mean_total # <<<<<<<<<<<<<< + * cdef double weighted_n_node_samples = self.weighted_n_node_samples + * cdef double total = 0.0 + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.mean_total; + __pyx_v_mean_total = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":847 + * cdef double* sq_sum_total = self.sq_sum_total + * cdef double* mean_total = self.mean_total + * cdef double weighted_n_node_samples = self.weighted_n_node_samples # <<<<<<<<<<<<<< + * cdef double total = 0.0 + * cdef SIZE_t k + */ + __pyx_t_3 = __pyx_v_self->__pyx_base.__pyx_base.weighted_n_node_samples; + __pyx_v_weighted_n_node_samples = __pyx_t_3; + + /* "sklearn/tree/_tree.pyx":848 + * cdef double* mean_total = self.mean_total + * cdef double weighted_n_node_samples = self.weighted_n_node_samples + * cdef double total = 0.0 # <<<<<<<<<<<<<< + * cdef SIZE_t k * */ - __pyx_v_b = (__pyx_v_b - 1); - } + __pyx_v_total = 0.0; - /* "sklearn/tree/_tree.pyx":785 - * while sample_mask_ptr[X_argsorted_i[b]] == 0: - * b = b - 1 - * X_b = X_i[X_argsorted_i[b]] # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":851 + * cdef SIZE_t k * - * if b <= a or X_a == X_b: + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * total += (sq_sum_total[k] / weighted_n_node_samples - + * mean_total[k] * mean_total[k]) */ - __pyx_v_X_b = (__pyx_v_X_i[(__pyx_v_X_argsorted_i[__pyx_v_b])]); + __pyx_t_1 = __pyx_v_n_outputs; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_1; __pyx_t_4+=1) { + __pyx_v_k = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":787 - * X_b = X_i[X_argsorted_i[b]] + /* "sklearn/tree/_tree.pyx":852 * - * if b <= a or X_a == X_b: # <<<<<<<<<<<<<< - * continue + * for k in range(n_outputs): + * total += (sq_sum_total[k] / weighted_n_node_samples - # <<<<<<<<<<<<<< + * mean_total[k] * mean_total[k]) * */ - __pyx_t_13 = (__pyx_v_b <= __pyx_v_a); - if (!__pyx_t_13) { - __pyx_t_2 = (__pyx_v_X_a == __pyx_v_X_b); - __pyx_t_12 = __pyx_t_2; - } else { - __pyx_t_12 = __pyx_t_13; - } - if (__pyx_t_12) { + __pyx_v_total = (__pyx_v_total + (((__pyx_v_sq_sum_total[__pyx_v_k]) / __pyx_v_weighted_n_node_samples) - ((__pyx_v_mean_total[__pyx_v_k]) * (__pyx_v_mean_total[__pyx_v_k])))); + } - /* "sklearn/tree/_tree.pyx":788 + /* "sklearn/tree/_tree.pyx":855 + * mean_total[k] * mean_total[k]) * - * if b <= a or X_a == X_b: - * continue # <<<<<<<<<<<<<< + * return total / n_outputs # <<<<<<<<<<<<<< * - * # Draw a random threshold in [a, b) + * cdef void children_impurity(self, double* impurity_left, */ - goto __pyx_L5_continue; - goto __pyx_L11; - } - __pyx_L11:; + __pyx_r = (__pyx_v_total / __pyx_v_n_outputs); + goto __pyx_L0; - /* "sklearn/tree/_tree.pyx":791 + /* "sklearn/tree/_tree.pyx":841 + * MSE = var_left + var_right + * """ + * cdef double node_impurity(self) nogil: # <<<<<<<<<<<<<< + * """Evaluate the impurity of the current node, i.e. the impurity of + * samples[start:end].""" + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":857 + * return total / n_outputs * - * # Draw a random threshold in [a, b) - * random = random_state.rand() # <<<<<<<<<<<<<< - * t = X_a + (random * (X_b - X_a)) - * if t == X_b: + * cdef void children_impurity(self, double* impurity_left, # <<<<<<<<<<<<<< + * double* impurity_right) nogil: + * """Evaluate the impurity in children nodes, i.e. the impurity of the */ - __pyx_t_3 = PyObject_GetAttr(__pyx_v_random_state, __pyx_n_s__rand); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_15 = __pyx_PyFloat_AsDouble(__pyx_t_5); if (unlikely((__pyx_t_15 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_random = __pyx_t_15; - /* "sklearn/tree/_tree.pyx":792 - * # Draw a random threshold in [a, b) - * random = random_state.rand() - * t = X_a + (random * (X_b - X_a)) # <<<<<<<<<<<<<< - * if t == X_b: - * t = X_a +static void __pyx_f_7sklearn_4tree_5_tree_3MSE_children_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_MSE *__pyx_v_self, double *__pyx_v_impurity_left, double *__pyx_v_impurity_right) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + double *__pyx_v_var_left; + double *__pyx_v_var_right; + double __pyx_v_total_left; + double __pyx_v_total_right; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + double *__pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_3; + + /* "sklearn/tree/_tree.pyx":862 + * left child (samples[start:pos]) and the impurity the right child + * (samples[pos:end]).""" + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right */ - __pyx_v_t = (__pyx_v_X_a + (__pyx_v_random * (__pyx_v_X_b - __pyx_v_X_a))); + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":793 - * random = random_state.rand() - * t = X_a + (random * (X_b - X_a)) - * if t == X_b: # <<<<<<<<<<<<<< - * t = X_a + /* "sklearn/tree/_tree.pyx":863 + * (samples[pos:end]).""" + * cdef SIZE_t n_outputs = self.n_outputs + * cdef double* var_left = self.var_left # <<<<<<<<<<<<<< + * cdef double* var_right = self.var_right + * cdef double total_left = 0.0 + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.var_left; + __pyx_v_var_left = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":864 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right # <<<<<<<<<<<<<< + * cdef double total_left = 0.0 + * cdef double total_right = 0.0 + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.var_right; + __pyx_v_var_right = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":865 + * cdef double* var_left = self.var_left + * cdef double* var_right = self.var_right + * cdef double total_left = 0.0 # <<<<<<<<<<<<<< + * cdef double total_right = 0.0 + * cdef SIZE_t k + */ + __pyx_v_total_left = 0.0; + + /* "sklearn/tree/_tree.pyx":866 + * cdef double* var_right = self.var_right + * cdef double total_left = 0.0 + * cdef double total_right = 0.0 # <<<<<<<<<<<<<< + * cdef SIZE_t k * */ - __pyx_t_12 = (__pyx_v_t == __pyx_v_X_b); - if (__pyx_t_12) { + __pyx_v_total_right = 0.0; - /* "sklearn/tree/_tree.pyx":794 - * t = X_a + (random * (X_b - X_a)) - * if t == X_b: - * t = X_a # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":869 + * cdef SIZE_t k * - * # Find the sample just greater than t + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * total_left += var_left[k] + * total_right += var_right[k] */ - __pyx_v_t = __pyx_v_X_a; - goto __pyx_L12; - } - __pyx_L12:; + __pyx_t_1 = __pyx_v_n_outputs; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_k = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":797 + /* "sklearn/tree/_tree.pyx":870 * - * # Find the sample just greater than t - * c = a + 1 # <<<<<<<<<<<<<< + * for k in range(n_outputs): + * total_left += var_left[k] # <<<<<<<<<<<<<< + * total_right += var_right[k] * - * while True: */ - __pyx_v_c = (__pyx_v_a + 1); + __pyx_v_total_left = (__pyx_v_total_left + (__pyx_v_var_left[__pyx_v_k])); - /* "sklearn/tree/_tree.pyx":799 - * c = a + 1 + /* "sklearn/tree/_tree.pyx":871 + * for k in range(n_outputs): + * total_left += var_left[k] + * total_right += var_right[k] # <<<<<<<<<<<<<< * - * while True: # <<<<<<<<<<<<<< - * if sample_mask_ptr[X_argsorted_i[c]] != 0: - * # FIXME why is t cast to DTYPE_t? + * impurity_left[0] = total_left / n_outputs */ - while (1) { - if (!1) break; + __pyx_v_total_right = (__pyx_v_total_right + (__pyx_v_var_right[__pyx_v_k])); + } - /* "sklearn/tree/_tree.pyx":800 + /* "sklearn/tree/_tree.pyx":873 + * total_right += var_right[k] + * + * impurity_left[0] = total_left / n_outputs # <<<<<<<<<<<<<< + * impurity_right[0] = total_right / n_outputs * - * while True: - * if sample_mask_ptr[X_argsorted_i[c]] != 0: # <<<<<<<<<<<<<< - * # FIXME why is t cast to DTYPE_t? - * if X_i[X_argsorted_i[c]] > ( t) or c == b: */ - __pyx_t_12 = ((__pyx_v_sample_mask_ptr[(__pyx_v_X_argsorted_i[__pyx_v_c])]) != 0); - if (__pyx_t_12) { + (__pyx_v_impurity_left[0]) = (__pyx_v_total_left / __pyx_v_n_outputs); - /* "sklearn/tree/_tree.pyx":802 - * if sample_mask_ptr[X_argsorted_i[c]] != 0: - * # FIXME why is t cast to DTYPE_t? - * if X_i[X_argsorted_i[c]] > ( t) or c == b: # <<<<<<<<<<<<<< - * break + /* "sklearn/tree/_tree.pyx":874 + * + * impurity_left[0] = total_left / n_outputs + * impurity_right[0] = total_right / n_outputs # <<<<<<<<<<<<<< + * * */ - __pyx_t_12 = ((__pyx_v_X_i[(__pyx_v_X_argsorted_i[__pyx_v_c])]) > ((__pyx_t_7sklearn_4tree_5_tree_DTYPE_t)__pyx_v_t)); - if (!__pyx_t_12) { - __pyx_t_13 = (__pyx_v_c == __pyx_v_b); - __pyx_t_2 = __pyx_t_13; - } else { - __pyx_t_2 = __pyx_t_12; - } - if (__pyx_t_2) { + (__pyx_v_impurity_right[0]) = (__pyx_v_total_right / __pyx_v_n_outputs); - /* "sklearn/tree/_tree.pyx":803 - * # FIXME why is t cast to DTYPE_t? - * if X_i[X_argsorted_i[c]] > ( t) or c == b: - * break # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":857 + * return total / n_outputs * - * c += 1 + * cdef void children_impurity(self, double* impurity_left, # <<<<<<<<<<<<<< + * double* impurity_right) nogil: + * """Evaluate the impurity in children nodes, i.e. the impurity of the */ - goto __pyx_L14_break; - goto __pyx_L16; - } - __pyx_L16:; - goto __pyx_L15; - } - __pyx_L15:; - /* "sklearn/tree/_tree.pyx":805 - * break + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":886 + * """ * - * c += 1 # <<<<<<<<<<<<<< + * cdef double impurity_improvement(self, double impurity) nogil: # <<<<<<<<<<<<<< + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t k + */ + +static double __pyx_f_7sklearn_4tree_5_tree_11FriedmanMSE_impurity_improvement(struct __pyx_obj_7sklearn_4tree_5_tree_FriedmanMSE *__pyx_v_self, CYTHON_UNUSED double __pyx_v_impurity) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_outputs; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + double *__pyx_v_sum_left; + double *__pyx_v_sum_right; + double __pyx_v_total_sum_left; + double __pyx_v_total_sum_right; + double __pyx_v_weighted_n_left; + double __pyx_v_weighted_n_right; + double __pyx_v_diff; + double __pyx_r; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + double *__pyx_t_2; + double __pyx_t_3; + + /* "sklearn/tree/_tree.pyx":887 * - * # Better than the best so far? + * cdef double impurity_improvement(self, double impurity) nogil: + * cdef SIZE_t n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * cdef SIZE_t k + * cdef double* sum_left = self.sum_left */ - __pyx_v_c = (__pyx_v_c + 1); - } - __pyx_L14_break:; + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.__pyx_base.n_outputs; + __pyx_v_n_outputs = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":889 + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t k + * cdef double* sum_left = self.sum_left # <<<<<<<<<<<<<< + * cdef double* sum_right = self.sum_right + * cdef double total_sum_left = 0.0 + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.sum_left; + __pyx_v_sum_left = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":890 + * cdef SIZE_t k + * cdef double* sum_left = self.sum_left + * cdef double* sum_right = self.sum_right # <<<<<<<<<<<<<< + * cdef double total_sum_left = 0.0 + * cdef double total_sum_right = 0.0 + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.sum_right; + __pyx_v_sum_right = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":891 + * cdef double* sum_left = self.sum_left + * cdef double* sum_right = self.sum_right + * cdef double total_sum_left = 0.0 # <<<<<<<<<<<<<< + * cdef double total_sum_right = 0.0 + * cdef double weighted_n_left = self.weighted_n_left + */ + __pyx_v_total_sum_left = 0.0; + + /* "sklearn/tree/_tree.pyx":892 + * cdef double* sum_right = self.sum_right + * cdef double total_sum_left = 0.0 + * cdef double total_sum_right = 0.0 # <<<<<<<<<<<<<< + * cdef double weighted_n_left = self.weighted_n_left + * cdef double weighted_n_right = self.weighted_n_right + */ + __pyx_v_total_sum_right = 0.0; + + /* "sklearn/tree/_tree.pyx":893 + * cdef double total_sum_left = 0.0 + * cdef double total_sum_right = 0.0 + * cdef double weighted_n_left = self.weighted_n_left # <<<<<<<<<<<<<< + * cdef double weighted_n_right = self.weighted_n_right + * cdef double diff = 0.0 + */ + __pyx_t_3 = __pyx_v_self->__pyx_base.__pyx_base.__pyx_base.weighted_n_left; + __pyx_v_weighted_n_left = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":808 + /* "sklearn/tree/_tree.pyx":894 + * cdef double total_sum_right = 0.0 + * cdef double weighted_n_left = self.weighted_n_left + * cdef double weighted_n_right = self.weighted_n_right # <<<<<<<<<<<<<< + * cdef double diff = 0.0 * - * # Better than the best so far? - * n_left = criterion.update(0, c, y_ptr, y_stride, X_argsorted_i, sample_mask_ptr) # <<<<<<<<<<<<<< - * error = criterion.eval() + */ + __pyx_t_3 = __pyx_v_self->__pyx_base.__pyx_base.__pyx_base.weighted_n_right; + __pyx_v_weighted_n_right = __pyx_t_3; + + /* "sklearn/tree/_tree.pyx":895 + * cdef double weighted_n_left = self.weighted_n_left + * cdef double weighted_n_right = self.weighted_n_right + * cdef double diff = 0.0 # <<<<<<<<<<<<<< * + * for k from 0 <= k < n_outputs: */ - __pyx_v_n_left = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->update(__pyx_v_criterion, 0, __pyx_v_c, __pyx_v_y_ptr, __pyx_v_y_stride, __pyx_v_X_argsorted_i, __pyx_v_sample_mask_ptr); + __pyx_v_diff = 0.0; - /* "sklearn/tree/_tree.pyx":809 - * # Better than the best so far? - * n_left = criterion.update(0, c, y_ptr, y_stride, X_argsorted_i, sample_mask_ptr) - * error = criterion.eval() # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":897 + * cdef double diff = 0.0 * - * if n_left < min_samples_leaf or (n_node_samples - n_left) < min_samples_leaf: + * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< + * total_sum_left += sum_left[k] + * total_sum_right += sum_right[k] */ - __pyx_v_error = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_criterion->__pyx_vtab)->eval(__pyx_v_criterion); + __pyx_t_1 = __pyx_v_n_outputs; + for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_1; __pyx_v_k++) { - /* "sklearn/tree/_tree.pyx":811 - * error = criterion.eval() + /* "sklearn/tree/_tree.pyx":898 * - * if n_left < min_samples_leaf or (n_node_samples - n_left) < min_samples_leaf: # <<<<<<<<<<<<<< - * continue + * for k from 0 <= k < n_outputs: + * total_sum_left += sum_left[k] # <<<<<<<<<<<<<< + * total_sum_right += sum_right[k] * */ - __pyx_t_2 = (__pyx_v_n_left < __pyx_v_min_samples_leaf); - if (!__pyx_t_2) { - __pyx_t_12 = ((__pyx_v_n_node_samples - __pyx_v_n_left) < __pyx_v_min_samples_leaf); - __pyx_t_13 = __pyx_t_12; - } else { - __pyx_t_13 = __pyx_t_2; - } - if (__pyx_t_13) { + __pyx_v_total_sum_left = (__pyx_v_total_sum_left + (__pyx_v_sum_left[__pyx_v_k])); - /* "sklearn/tree/_tree.pyx":812 + /* "sklearn/tree/_tree.pyx":899 + * for k from 0 <= k < n_outputs: + * total_sum_left += sum_left[k] + * total_sum_right += sum_right[k] # <<<<<<<<<<<<<< * - * if n_left < min_samples_leaf or (n_node_samples - n_left) < min_samples_leaf: - * continue # <<<<<<<<<<<<<< + * total_sum_left = total_sum_left / n_outputs + */ + __pyx_v_total_sum_right = (__pyx_v_total_sum_right + (__pyx_v_sum_right[__pyx_v_k])); + } + + /* "sklearn/tree/_tree.pyx":901 + * total_sum_right += sum_right[k] * - * if error < best_error: + * total_sum_left = total_sum_left / n_outputs # <<<<<<<<<<<<<< + * total_sum_right = total_sum_right / n_outputs + * diff = ((total_sum_left / weighted_n_left) - */ - goto __pyx_L5_continue; - goto __pyx_L17; - } - __pyx_L17:; + __pyx_v_total_sum_left = (__pyx_v_total_sum_left / __pyx_v_n_outputs); - /* "sklearn/tree/_tree.pyx":814 - * continue + /* "sklearn/tree/_tree.pyx":902 * - * if error < best_error: # <<<<<<<<<<<<<< - * best_i = i - * best_t = t + * total_sum_left = total_sum_left / n_outputs + * total_sum_right = total_sum_right / n_outputs # <<<<<<<<<<<<<< + * diff = ((total_sum_left / weighted_n_left) - + * (total_sum_right / weighted_n_right)) */ - __pyx_t_13 = (__pyx_v_error < __pyx_v_best_error); - if (__pyx_t_13) { + __pyx_v_total_sum_right = (__pyx_v_total_sum_right / __pyx_v_n_outputs); - /* "sklearn/tree/_tree.pyx":815 + /* "sklearn/tree/_tree.pyx":903 + * total_sum_left = total_sum_left / n_outputs + * total_sum_right = total_sum_right / n_outputs + * diff = ((total_sum_left / weighted_n_left) - # <<<<<<<<<<<<<< + * (total_sum_right / weighted_n_right)) * - * if error < best_error: - * best_i = i # <<<<<<<<<<<<<< - * best_t = t - * best_error = error */ - __pyx_v_best_i = __pyx_v_i; + __pyx_v_diff = ((__pyx_v_total_sum_left / __pyx_v_weighted_n_left) - (__pyx_v_total_sum_right / __pyx_v_weighted_n_right)); - /* "sklearn/tree/_tree.pyx":816 - * if error < best_error: - * best_i = i - * best_t = t # <<<<<<<<<<<<<< - * best_error = error + /* "sklearn/tree/_tree.pyx":906 + * (total_sum_right / weighted_n_right)) + * + * return (weighted_n_left * weighted_n_right * diff * diff / # <<<<<<<<<<<<<< + * (weighted_n_left + weighted_n_right)) * */ - __pyx_v_best_t = __pyx_v_t; + __pyx_r = ((((__pyx_v_weighted_n_left * __pyx_v_weighted_n_right) * __pyx_v_diff) * __pyx_v_diff) / (__pyx_v_weighted_n_left + __pyx_v_weighted_n_right)); + goto __pyx_L0; - /* "sklearn/tree/_tree.pyx":817 - * best_i = i - * best_t = t - * best_error = error # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":886 + * """ * - * _best_i[0] = best_i + * cdef double impurity_improvement(self, double impurity) nogil: # <<<<<<<<<<<<<< + * cdef SIZE_t n_outputs = self.n_outputs + * cdef SIZE_t k */ - __pyx_v_best_error = __pyx_v_error; - goto __pyx_L18; - } - __pyx_L18:; - __pyx_L5_continue:; - } - /* "sklearn/tree/_tree.pyx":819 - * best_error = error + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":913 + * # ============================================================================= * - * _best_i[0] = best_i # <<<<<<<<<<<<<< - * _best_t[0] = best_t - * _best_error[0] = best_error + * cdef inline void _init_split(SplitRecord* self, SIZE_t start_pos) nogil: # <<<<<<<<<<<<<< + * self.impurity_left = INFINITY + * self.impurity_right = INFINITY */ - (__pyx_v__best_i[0]) = __pyx_v_best_i; - /* "sklearn/tree/_tree.pyx":820 +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree__init_split(struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start_pos) { + + /* "sklearn/tree/_tree.pyx":914 + * + * cdef inline void _init_split(SplitRecord* self, SIZE_t start_pos) nogil: + * self.impurity_left = INFINITY # <<<<<<<<<<<<<< + * self.impurity_right = INFINITY + * self.pos = start_pos + */ + __pyx_v_self->impurity_left = __pyx_v_7sklearn_4tree_5_tree_INFINITY; + + /* "sklearn/tree/_tree.pyx":915 + * cdef inline void _init_split(SplitRecord* self, SIZE_t start_pos) nogil: + * self.impurity_left = INFINITY + * self.impurity_right = INFINITY # <<<<<<<<<<<<<< + * self.pos = start_pos + * self.feature = 0 + */ + __pyx_v_self->impurity_right = __pyx_v_7sklearn_4tree_5_tree_INFINITY; + + /* "sklearn/tree/_tree.pyx":916 + * self.impurity_left = INFINITY + * self.impurity_right = INFINITY + * self.pos = start_pos # <<<<<<<<<<<<<< + * self.feature = 0 + * self.threshold = 0. + */ + __pyx_v_self->pos = __pyx_v_start_pos; + + /* "sklearn/tree/_tree.pyx":917 + * self.impurity_right = INFINITY + * self.pos = start_pos + * self.feature = 0 # <<<<<<<<<<<<<< + * self.threshold = 0. + * self.improvement = -INFINITY + */ + __pyx_v_self->feature = 0; + + /* "sklearn/tree/_tree.pyx":918 + * self.pos = start_pos + * self.feature = 0 + * self.threshold = 0. # <<<<<<<<<<<<<< + * self.improvement = -INFINITY * - * _best_i[0] = best_i - * _best_t[0] = best_t # <<<<<<<<<<<<<< - * _best_error[0] = best_error - * _initial_error[0] = initial_error */ - (__pyx_v__best_t[0]) = __pyx_v_best_t; + __pyx_v_self->threshold = 0.; - /* "sklearn/tree/_tree.pyx":821 - * _best_i[0] = best_i - * _best_t[0] = best_t - * _best_error[0] = best_error # <<<<<<<<<<<<<< - * _initial_error[0] = initial_error + /* "sklearn/tree/_tree.pyx":919 + * self.feature = 0 + * self.threshold = 0. + * self.improvement = -INFINITY # <<<<<<<<<<<<<< + * * */ - (__pyx_v__best_error[0]) = __pyx_v_best_error; + __pyx_v_self->improvement = (-__pyx_v_7sklearn_4tree_5_tree_INFINITY); - /* "sklearn/tree/_tree.pyx":822 - * _best_t[0] = best_t - * _best_error[0] = best_error - * _initial_error[0] = initial_error # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":913 + * # ============================================================================= * - * cpdef predict(self, np.ndarray[DTYPE_t, ndim=2] X): + * cdef inline void _init_split(SplitRecord* self, SIZE_t start_pos) nogil: # <<<<<<<<<<<<<< + * self.impurity_left = INFINITY + * self.impurity_right = INFINITY */ - (__pyx_v__initial_error[0]) = __pyx_v_initial_error; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_features.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_WriteUnraisable("sklearn.tree._tree.Tree.find_random_split", __pyx_clineno, __pyx_lineno, __pyx_filename); - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_features.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_criterion); - __Pyx_XDECREF(__pyx_v_random_state); - __Pyx_XDECREF((PyObject *)__pyx_v_features); - __Pyx_RefNannyFinishContext(); + /* function exit code */ } -/* "sklearn/tree/_tree.pyx":824 - * _initial_error[0] = initial_error +/* "sklearn/tree/_tree.pyx":923 * - * cpdef predict(self, np.ndarray[DTYPE_t, ndim=2] X): # <<<<<<<<<<<<<< - * """Predict target for X.""" - * cdef int i, k, c + * cdef class Splitter: + * def __cinit__(self, Criterion criterion, SIZE_t max_features, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, double min_weight_leaf, + * object random_state): */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13predict(PyObject *__pyx_v_self, PyObject *__pyx_v_X); /*proto*/ -static PyObject *__pyx_f_7sklearn_4tree_5_tree_4Tree_predict(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyArrayObject *__pyx_v_X, int __pyx_skip_dispatch) { - int __pyx_v_i; - int __pyx_v_k; - int __pyx_v_c; - int __pyx_v_n_samples; - int __pyx_v_node_id; - int __pyx_v_offset_node; - int __pyx_v_offset_output; - PyArrayObject *__pyx_v_out = 0; - __Pyx_LocalBuf_ND __pyx_pybuffernd_X; - __Pyx_Buffer __pyx_pybuffer_X; - __Pyx_LocalBuf_ND __pyx_pybuffernd_out; - __Pyx_Buffer __pyx_pybuffer_out; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - int __pyx_t_11; - int __pyx_t_12; - int __pyx_t_13; - int __pyx_t_14; - int __pyx_t_15; - int __pyx_t_16; - int __pyx_t_17; - int __pyx_t_18; +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion = 0; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + double __pyx_v_min_weight_leaf; + PyObject *__pyx_v_random_state = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("predict", 0); - __pyx_pybuffer_out.pybuffer.buf = NULL; - __pyx_pybuffer_out.refcount = 0; - __pyx_pybuffernd_out.data = NULL; - __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; - __pyx_pybuffer_X.pybuffer.buf = NULL; - __pyx_pybuffer_X.refcount = 0; - __pyx_pybuffernd_X.data = NULL; - __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__predict); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_13predict)) { - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_v_X)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_X)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_X)); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_criterion,&__pyx_n_s_max_features,&__pyx_n_s_min_samples_leaf,&__pyx_n_s_min_weight_leaf,&__pyx_n_s_random_state,0}; + PyObject* values[5] = {0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_criterion)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_features)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 923; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_samples_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 923; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_weight_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 923; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random_state)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 923; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 923; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)values[0]); + __pyx_v_max_features = __Pyx_PyInt_As_Py_intptr_t(values[1]); if (unlikely((__pyx_v_max_features == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 923; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_samples_leaf = __Pyx_PyInt_As_Py_intptr_t(values[2]); if (unlikely((__pyx_v_min_samples_leaf == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 924; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_weight_leaf = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_min_weight_leaf == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 924; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_random_state = values[4]; } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 923; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._tree.Splitter.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_criterion), __pyx_ptype_7sklearn_4tree_5_tree_Criterion, 1, "criterion", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 923; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self), __pyx_v_criterion, __pyx_v_max_features, __pyx_v_min_samples_leaf, __pyx_v_min_weight_leaf, __pyx_v_random_state); - /* "sklearn/tree/_tree.pyx":827 - * """Predict target for X.""" - * cdef int i, k, c - * cdef int n_samples = X.shape[0] # <<<<<<<<<<<<<< - * cdef int node_id = 0 - * cdef int offset_node - */ - __pyx_v_n_samples = (__pyx_v_X->dimensions[0]); + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/tree/_tree.pyx":828 - * cdef int i, k, c - * cdef int n_samples = X.shape[0] - * cdef int node_id = 0 # <<<<<<<<<<<<<< - * cdef int offset_node - * cdef int offset_output - */ - __pyx_v_node_id = 0; +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, double __pyx_v_min_weight_leaf, PyObject *__pyx_v_random_state) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__", 0); - /* "sklearn/tree/_tree.pyx":833 - * - * cdef np.ndarray[np.float64_t, ndim=3] out - * out = np.zeros((n_samples, self.n_outputs, self.max_n_classes), dtype=np.float64) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":926 + * SIZE_t min_samples_leaf, double min_weight_leaf, + * object random_state): + * self.criterion = criterion # <<<<<<<<<<<<<< * - * for i from 0 <= i < n_samples: + * self.samples = NULL */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromLong(__pyx_v_n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromLong(__pyx_v_self->n_outputs); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyInt_FromLong(__pyx_v_self->max_n_classes); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 3, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_v_out, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 3, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); - } - } - __pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_out.diminfo[1].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_out.diminfo[1].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_out.diminfo[2].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_out.diminfo[2].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[2]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_6 = 0; - __pyx_v_out = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; + __Pyx_INCREF(((PyObject *)__pyx_v_criterion)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_criterion)); + __Pyx_GOTREF(__pyx_v_self->criterion); + __Pyx_DECREF(((PyObject *)__pyx_v_self->criterion)); + __pyx_v_self->criterion = __pyx_v_criterion; - /* "sklearn/tree/_tree.pyx":835 - * out = np.zeros((n_samples, self.n_outputs, self.max_n_classes), dtype=np.float64) - * - * for i from 0 <= i < n_samples: # <<<<<<<<<<<<<< - * node_id = 0 + /* "sklearn/tree/_tree.pyx":928 + * self.criterion = criterion * + * self.samples = NULL # <<<<<<<<<<<<<< + * self.n_samples = 0 + * self.features = NULL */ - __pyx_t_7 = __pyx_v_n_samples; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_7; __pyx_v_i++) { + __pyx_v_self->samples = NULL; - /* "sklearn/tree/_tree.pyx":836 + /* "sklearn/tree/_tree.pyx":929 * - * for i from 0 <= i < n_samples: - * node_id = 0 # <<<<<<<<<<<<<< - * - * # While node_id not a leaf + * self.samples = NULL + * self.n_samples = 0 # <<<<<<<<<<<<<< + * self.features = NULL + * self.n_features = 0 */ - __pyx_v_node_id = 0; + __pyx_v_self->n_samples = 0; - /* "sklearn/tree/_tree.pyx":839 - * - * # While node_id not a leaf - * while self.children_left[node_id] != _TREE_LEAF: # and self.children_right[node_id] != _TREE_LEAF: # <<<<<<<<<<<<<< - * if X[i, self.feature[node_id]] <= self.threshold[node_id]: - * node_id = self.children_left[node_id] - */ - while (1) { - __pyx_t_11 = ((__pyx_v_self->children_left[__pyx_v_node_id]) != __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF); - if (!__pyx_t_11) break; - - /* "sklearn/tree/_tree.pyx":840 - * # While node_id not a leaf - * while self.children_left[node_id] != _TREE_LEAF: # and self.children_right[node_id] != _TREE_LEAF: - * if X[i, self.feature[node_id]] <= self.threshold[node_id]: # <<<<<<<<<<<<<< - * node_id = self.children_left[node_id] - * else: + /* "sklearn/tree/_tree.pyx":930 + * self.samples = NULL + * self.n_samples = 0 + * self.features = NULL # <<<<<<<<<<<<<< + * self.n_features = 0 + * self.feature_values = NULL */ - __pyx_t_12 = __pyx_v_i; - __pyx_t_13 = (__pyx_v_self->feature[__pyx_v_node_id]); - __pyx_t_11 = ((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_pybuffernd_X.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_X.diminfo[0].strides, __pyx_t_13, __pyx_pybuffernd_X.diminfo[1].strides)) <= (__pyx_v_self->threshold[__pyx_v_node_id])); - if (__pyx_t_11) { + __pyx_v_self->features = NULL; - /* "sklearn/tree/_tree.pyx":841 - * while self.children_left[node_id] != _TREE_LEAF: # and self.children_right[node_id] != _TREE_LEAF: - * if X[i, self.feature[node_id]] <= self.threshold[node_id]: - * node_id = self.children_left[node_id] # <<<<<<<<<<<<<< - * else: - * node_id = self.children_right[node_id] + /* "sklearn/tree/_tree.pyx":931 + * self.n_samples = 0 + * self.features = NULL + * self.n_features = 0 # <<<<<<<<<<<<<< + * self.feature_values = NULL + * */ - __pyx_v_node_id = (__pyx_v_self->children_left[__pyx_v_node_id]); - goto __pyx_L7; - } - /*else*/ { + __pyx_v_self->n_features = 0; - /* "sklearn/tree/_tree.pyx":843 - * node_id = self.children_left[node_id] - * else: - * node_id = self.children_right[node_id] # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":932 + * self.features = NULL + * self.n_features = 0 + * self.feature_values = NULL # <<<<<<<<<<<<<< * - * offset_node = node_id * self.value_stride + * self.y = NULL */ - __pyx_v_node_id = (__pyx_v_self->children_right[__pyx_v_node_id]); - } - __pyx_L7:; - } + __pyx_v_self->feature_values = NULL; - /* "sklearn/tree/_tree.pyx":845 - * node_id = self.children_right[node_id] + /* "sklearn/tree/_tree.pyx":934 + * self.feature_values = NULL * - * offset_node = node_id * self.value_stride # <<<<<<<<<<<<<< - * - * for k from 0 <= k < self.n_outputs: + * self.y = NULL # <<<<<<<<<<<<<< + * self.y_stride = 0 + * self.sample_weight = NULL */ - __pyx_v_offset_node = (__pyx_v_node_id * __pyx_v_self->value_stride); + __pyx_v_self->y = NULL; - /* "sklearn/tree/_tree.pyx":847 - * offset_node = node_id * self.value_stride + /* "sklearn/tree/_tree.pyx":935 * - * for k from 0 <= k < self.n_outputs: # <<<<<<<<<<<<<< - * offset_output = k * self.max_n_classes + * self.y = NULL + * self.y_stride = 0 # <<<<<<<<<<<<<< + * self.sample_weight = NULL * */ - __pyx_t_14 = __pyx_v_self->n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_14; __pyx_v_k++) { + __pyx_v_self->y_stride = 0; - /* "sklearn/tree/_tree.pyx":848 - * - * for k from 0 <= k < self.n_outputs: - * offset_output = k * self.max_n_classes # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":936 + * self.y = NULL + * self.y_stride = 0 + * self.sample_weight = NULL # <<<<<<<<<<<<<< * - * for c from 0 <= c < self.n_classes[k]: + * self.max_features = max_features */ - __pyx_v_offset_output = (__pyx_v_k * __pyx_v_self->max_n_classes); + __pyx_v_self->sample_weight = NULL; - /* "sklearn/tree/_tree.pyx":850 - * offset_output = k * self.max_n_classes - * - * for c from 0 <= c < self.n_classes[k]: # <<<<<<<<<<<<<< - * out[i, k, c] = self.value[offset_node + offset_output + c] + /* "sklearn/tree/_tree.pyx":938 + * self.sample_weight = NULL * + * self.max_features = max_features # <<<<<<<<<<<<<< + * self.min_samples_leaf = min_samples_leaf + * self.min_weight_leaf = min_weight_leaf */ - __pyx_t_15 = (__pyx_v_self->n_classes[__pyx_v_k]); - for (__pyx_v_c = 0; __pyx_v_c < __pyx_t_15; __pyx_v_c++) { + __pyx_v_self->max_features = __pyx_v_max_features; - /* "sklearn/tree/_tree.pyx":851 + /* "sklearn/tree/_tree.pyx":939 * - * for c from 0 <= c < self.n_classes[k]: - * out[i, k, c] = self.value[offset_node + offset_output + c] # <<<<<<<<<<<<<< + * self.max_features = max_features + * self.min_samples_leaf = min_samples_leaf # <<<<<<<<<<<<<< + * self.min_weight_leaf = min_weight_leaf + * self.random_state = random_state + */ + __pyx_v_self->min_samples_leaf = __pyx_v_min_samples_leaf; + + /* "sklearn/tree/_tree.pyx":940 + * self.max_features = max_features + * self.min_samples_leaf = min_samples_leaf + * self.min_weight_leaf = min_weight_leaf # <<<<<<<<<<<<<< + * self.random_state = random_state * - * return out */ - __pyx_t_16 = __pyx_v_i; - __pyx_t_17 = __pyx_v_k; - __pyx_t_18 = __pyx_v_c; - *__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_out.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_out.diminfo[0].strides, __pyx_t_17, __pyx_pybuffernd_out.diminfo[1].strides, __pyx_t_18, __pyx_pybuffernd_out.diminfo[2].strides) = (__pyx_v_self->value[((__pyx_v_offset_node + __pyx_v_offset_output) + __pyx_v_c)]); - } - } - } + __pyx_v_self->min_weight_leaf = __pyx_v_min_weight_leaf; - /* "sklearn/tree/_tree.pyx":853 - * out[i, k, c] = self.value[offset_node + offset_output + c] + /* "sklearn/tree/_tree.pyx":941 + * self.min_samples_leaf = min_samples_leaf + * self.min_weight_leaf = min_weight_leaf + * self.random_state = random_state # <<<<<<<<<<<<<< * - * return out # <<<<<<<<<<<<<< + * def __dealloc__(self): + */ + __Pyx_INCREF(__pyx_v_random_state); + __Pyx_GIVEREF(__pyx_v_random_state); + __Pyx_GOTREF(__pyx_v_self->random_state); + __Pyx_DECREF(__pyx_v_self->random_state); + __pyx_v_self->random_state = __pyx_v_random_state; + + /* "sklearn/tree/_tree.pyx":923 * - * cpdef apply(self, np.ndarray[DTYPE_t, ndim=2] X): + * cdef class Splitter: + * def __cinit__(self, Criterion criterion, SIZE_t max_features, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, double min_weight_leaf, + * object random_state): */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_out)); - __pyx_r = ((PyObject *)__pyx_v_out); - goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.tree._tree.Tree.predict", __pyx_clineno, __pyx_lineno, __pyx_filename); + /* function exit code */ __pyx_r = 0; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_out); - __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } +/* "sklearn/tree/_tree.pyx":943 + * self.random_state = random_state + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Destructor.""" + * free(self.samples) + */ + /* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13predict(PyObject *__pyx_v_self, PyObject *__pyx_v_X); /*proto*/ -static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_12predict[] = "Predict target for X."; -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13predict(PyObject *__pyx_v_self, PyObject *__pyx_v_X) { - PyObject *__pyx_r = 0; +static void __pyx_pw_7sklearn_4tree_5_tree_8Splitter_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_7sklearn_4tree_5_tree_8Splitter_3__dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("predict (wrapper)", 0); - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_12predict(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyArrayObject *)__pyx_v_X)); - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_pf_7sklearn_4tree_5_tree_8Splitter_2__dealloc__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); - return __pyx_r; } -/* "sklearn/tree/_tree.pyx":824 - * _initial_error[0] = initial_error +static void __pyx_pf_7sklearn_4tree_5_tree_8Splitter_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "sklearn/tree/_tree.pyx":945 + * def __dealloc__(self): + * """Destructor.""" + * free(self.samples) # <<<<<<<<<<<<<< + * free(self.features) + * free(self.constant_features) + */ + free(__pyx_v_self->samples); + + /* "sklearn/tree/_tree.pyx":946 + * """Destructor.""" + * free(self.samples) + * free(self.features) # <<<<<<<<<<<<<< + * free(self.constant_features) + * free(self.feature_values) + */ + free(__pyx_v_self->features); + + /* "sklearn/tree/_tree.pyx":947 + * free(self.samples) + * free(self.features) + * free(self.constant_features) # <<<<<<<<<<<<<< + * free(self.feature_values) * - * cpdef predict(self, np.ndarray[DTYPE_t, ndim=2] X): # <<<<<<<<<<<<<< - * """Predict target for X.""" - * cdef int i, k, c */ + free(__pyx_v_self->constant_features); -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_12predict(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyArrayObject *__pyx_v_X) { - __Pyx_LocalBuf_ND __pyx_pybuffernd_X; - __Pyx_Buffer __pyx_pybuffer_X; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("predict", 0); - __pyx_pybuffer_X.pybuffer.buf = NULL; - __pyx_pybuffer_X.refcount = 0; - __pyx_pybuffernd_X.data = NULL; - __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->predict(__pyx_v_self, ((PyArrayObject *)__pyx_v_X), 1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":948 + * free(self.features) + * free(self.constant_features) + * free(self.feature_values) # <<<<<<<<<<<<<< + * + * def __getstate__(self): + */ + free(__pyx_v_self->feature_values); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":943 + * self.random_state = random_state + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Destructor.""" + * free(self.samples) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "sklearn/tree/_tree.pyx":950 + * free(self.feature_values) + * + * def __getstate__(self): # <<<<<<<<<<<<<< + * return {} + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_5__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_5__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter_4__getstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_4__getstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getstate__", 0); + + /* "sklearn/tree/_tree.pyx":951 + * + * def __getstate__(self): + * return {} # <<<<<<<<<<<<<< + * + * def __setstate__(self, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 951; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":950 + * free(self.feature_values) + * + * def __getstate__(self): # <<<<<<<<<<<<<< + * return {} + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.tree._tree.Tree.predict", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.tree._tree.Splitter.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; - goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); - __pyx_L2:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pyx":855 - * return out +/* "sklearn/tree/_tree.pyx":953 + * return {} + * + * def __setstate__(self, d): # <<<<<<<<<<<<<< + * pass * - * cpdef apply(self, np.ndarray[DTYPE_t, ndim=2] X): # <<<<<<<<<<<<<< - * """Finds the terminal region (=leaf node) for each sample in X.""" - * cdef int i = 0 */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_15apply(PyObject *__pyx_v_self, PyObject *__pyx_v_X); /*proto*/ -static PyObject *__pyx_f_7sklearn_4tree_5_tree_4Tree_apply(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyArrayObject *__pyx_v_X, int __pyx_skip_dispatch) { - int __pyx_v_i; - int __pyx_v_n_samples; - int __pyx_v_node_id; - PyArrayObject *__pyx_v_out = 0; - __Pyx_LocalBuf_ND __pyx_pybuffernd_X; - __Pyx_Buffer __pyx_pybuffer_X; - __Pyx_LocalBuf_ND __pyx_pybuffernd_out; - __Pyx_Buffer __pyx_pybuffer_out; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_7__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_7__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter_6__setstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self), ((PyObject *)__pyx_v_d)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_6__setstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate__", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":956 + * pass + * + * cdef void init(self, # <<<<<<<<<<<<<< + * object X, + * np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, + */ + +static void __pyx_f_7sklearn_4tree_5_tree_8Splitter_init(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_j; + double __pyx_v_weighted_n_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_features; + __Pyx_LocalBuf_ND __pyx_pybuffernd_y; + __Pyx_Buffer __pyx_pybuffer_y; + __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + __pyx_t_7sklearn_4tree_5_tree_UINT32_t __pyx_t_7; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_8; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_9; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_10; int __pyx_t_11; int __pyx_t_12; - int __pyx_t_13; - int __pyx_t_14; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("apply", 0); - __pyx_pybuffer_out.pybuffer.buf = NULL; - __pyx_pybuffer_out.refcount = 0; - __pyx_pybuffernd_out.data = NULL; - __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; - __pyx_pybuffer_X.pybuffer.buf = NULL; - __pyx_pybuffer_X.refcount = 0; - __pyx_pybuffernd_X.data = NULL; - __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + __Pyx_RefNannySetupContext("init", 0); + __pyx_pybuffer_y.pybuffer.buf = NULL; + __pyx_pybuffer_y.refcount = 0; + __pyx_pybuffernd_y.data = NULL; + __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 855; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DOUBLE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 956; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s__apply); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 855; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_15apply)) { - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 855; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_v_X)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_X)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_X)); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 855; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_y.diminfo[1].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_y.diminfo[1].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[1]; + + /* "sklearn/tree/_tree.pyx":962 + * """Initialize the splitter.""" + * # Reset random state + * self.rand_r_state = self.random_state.randint(0, RAND_R_MAX) # <<<<<<<<<<<<<< + * # Initialize samples and features structures + * cdef SIZE_t n_samples = X.shape[0] + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->random_state, __pyx_n_s_randint); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 962; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_e_7sklearn_4tree_5_tree_RAND_R_MAX); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 962; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = NULL; + __pyx_t_5 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_5 = 1; } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } + __pyx_t_6 = PyTuple_New(2+__pyx_t_5); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 962; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (__pyx_t_4) { + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + } + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_6, 0+__pyx_t_5, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_6, 1+__pyx_t_5, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_6, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 962; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_7 = __Pyx_PyInt_As_npy_uint32(__pyx_t_1); if (unlikely((__pyx_t_7 == (npy_uint32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 962; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->rand_r_state = __pyx_t_7; - /* "sklearn/tree/_tree.pyx":857 - * cpdef apply(self, np.ndarray[DTYPE_t, ndim=2] X): - * """Finds the terminal region (=leaf node) for each sample in X.""" - * cdef int i = 0 # <<<<<<<<<<<<<< - * cdef int n_samples = X.shape[0] - * cdef int node_id = 0 + /* "sklearn/tree/_tree.pyx":964 + * self.rand_r_state = self.random_state.randint(0, RAND_R_MAX) + * # Initialize samples and features structures + * cdef SIZE_t n_samples = X.shape[0] # <<<<<<<<<<<<<< + * cdef SIZE_t* samples = safe_realloc(&self.samples, n_samples) + * */ - __pyx_v_i = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 964; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 964; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_8 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_2); if (unlikely((__pyx_t_8 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 964; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_n_samples = __pyx_t_8; - /* "sklearn/tree/_tree.pyx":858 - * """Finds the terminal region (=leaf node) for each sample in X.""" - * cdef int i = 0 - * cdef int n_samples = X.shape[0] # <<<<<<<<<<<<<< - * cdef int node_id = 0 + /* "sklearn/tree/_tree.pyx":965 + * # Initialize samples and features structures + * cdef SIZE_t n_samples = X.shape[0] + * cdef SIZE_t* samples = safe_realloc(&self.samples, n_samples) # <<<<<<<<<<<<<< * + * cdef SIZE_t i, j */ - __pyx_v_n_samples = (__pyx_v_X->dimensions[0]); + __pyx_t_9 = __pyx_fuse_1__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_self->samples), __pyx_v_n_samples); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 965; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_samples = __pyx_t_9; - /* "sklearn/tree/_tree.pyx":859 - * cdef int i = 0 - * cdef int n_samples = X.shape[0] - * cdef int node_id = 0 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":968 + * + * cdef SIZE_t i, j + * cdef double weighted_n_samples = 0.0 # <<<<<<<<<<<<<< + * j = 0 * - * cdef np.ndarray[np.int32_t, ndim=1] out */ - __pyx_v_node_id = 0; + __pyx_v_weighted_n_samples = 0.0; - /* "sklearn/tree/_tree.pyx":862 + /* "sklearn/tree/_tree.pyx":969 + * cdef SIZE_t i, j + * cdef double weighted_n_samples = 0.0 + * j = 0 # <<<<<<<<<<<<<< * - * cdef np.ndarray[np.int32_t, ndim=1] out - * out = np.zeros((n_samples, ), dtype=np.int32) # <<<<<<<<<<<<<< + * for i in range(n_samples): + */ + __pyx_v_j = 0; + + /* "sklearn/tree/_tree.pyx":971 + * j = 0 * - * for i from 0 <= i < n_samples: + * for i in range(n_samples): # <<<<<<<<<<<<<< + * # Only work with positively weighted samples + * if sample_weight == NULL or sample_weight[i] != 0.0: */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromLong(__pyx_v_n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); - __pyx_t_2 = 0; - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); - __pyx_t_7 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_7 < 0)) { - PyErr_Fetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_v_out, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_8, __pyx_t_9, __pyx_t_10); - } + __pyx_t_8 = __pyx_v_n_samples; + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_8; __pyx_t_10+=1) { + __pyx_v_i = __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":973 + * for i in range(n_samples): + * # Only work with positively weighted samples + * if sample_weight == NULL or sample_weight[i] != 0.0: # <<<<<<<<<<<<<< + * samples[j] = i + * j += 1 + */ + __pyx_t_12 = ((__pyx_v_sample_weight == NULL) != 0); + if (!__pyx_t_12) { + } else { + __pyx_t_11 = __pyx_t_12; + goto __pyx_L6_bool_binop_done; } - __pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 862; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_6 = 0; - __pyx_v_out = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; + __pyx_t_12 = (((__pyx_v_sample_weight[__pyx_v_i]) != 0.0) != 0); + __pyx_t_11 = __pyx_t_12; + __pyx_L6_bool_binop_done:; + if (__pyx_t_11) { - /* "sklearn/tree/_tree.pyx":864 - * out = np.zeros((n_samples, ), dtype=np.int32) + /* "sklearn/tree/_tree.pyx":974 + * # Only work with positively weighted samples + * if sample_weight == NULL or sample_weight[i] != 0.0: + * samples[j] = i # <<<<<<<<<<<<<< + * j += 1 * - * for i from 0 <= i < n_samples: # <<<<<<<<<<<<<< - * node_id = 0 + */ + (__pyx_v_samples[__pyx_v_j]) = __pyx_v_i; + + /* "sklearn/tree/_tree.pyx":975 + * if sample_weight == NULL or sample_weight[i] != 0.0: + * samples[j] = i + * j += 1 # <<<<<<<<<<<<<< * + * if sample_weight != NULL: */ - __pyx_t_7 = __pyx_v_n_samples; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_7; __pyx_v_i++) { + __pyx_v_j = (__pyx_v_j + 1); + goto __pyx_L5; + } + __pyx_L5:; - /* "sklearn/tree/_tree.pyx":865 + /* "sklearn/tree/_tree.pyx":977 + * j += 1 * - * for i from 0 <= i < n_samples: - * node_id = 0 # <<<<<<<<<<<<<< + * if sample_weight != NULL: # <<<<<<<<<<<<<< + * weighted_n_samples += sample_weight[i] + * else: + */ + __pyx_t_11 = ((__pyx_v_sample_weight != NULL) != 0); + if (__pyx_t_11) { + + /* "sklearn/tree/_tree.pyx":978 * - * # While node_id not a leaf + * if sample_weight != NULL: + * weighted_n_samples += sample_weight[i] # <<<<<<<<<<<<<< + * else: + * weighted_n_samples += 1.0 */ - __pyx_v_node_id = 0; + __pyx_v_weighted_n_samples = (__pyx_v_weighted_n_samples + (__pyx_v_sample_weight[__pyx_v_i])); + goto __pyx_L8; + } + /*else*/ { - /* "sklearn/tree/_tree.pyx":868 + /* "sklearn/tree/_tree.pyx":980 + * weighted_n_samples += sample_weight[i] + * else: + * weighted_n_samples += 1.0 # <<<<<<<<<<<<<< * - * # While node_id not a leaf - * while self.children_left[node_id] != _TREE_LEAF: # and self.children_right[node_id] != _TREE_LEAF: # <<<<<<<<<<<<<< - * if X[i, self.feature[node_id]] <= self.threshold[node_id]: - * node_id = self.children_left[node_id] + * self.n_samples = j */ - while (1) { - __pyx_t_11 = ((__pyx_v_self->children_left[__pyx_v_node_id]) != __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF); - if (!__pyx_t_11) break; - - /* "sklearn/tree/_tree.pyx":869 - * # While node_id not a leaf - * while self.children_left[node_id] != _TREE_LEAF: # and self.children_right[node_id] != _TREE_LEAF: - * if X[i, self.feature[node_id]] <= self.threshold[node_id]: # <<<<<<<<<<<<<< - * node_id = self.children_left[node_id] - * else: + __pyx_v_weighted_n_samples = (__pyx_v_weighted_n_samples + 1.0); + } + __pyx_L8:; + } + + /* "sklearn/tree/_tree.pyx":982 + * weighted_n_samples += 1.0 + * + * self.n_samples = j # <<<<<<<<<<<<<< + * self.weighted_n_samples = weighted_n_samples + * */ - __pyx_t_12 = __pyx_v_i; - __pyx_t_13 = (__pyx_v_self->feature[__pyx_v_node_id]); - __pyx_t_11 = ((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, __pyx_pybuffernd_X.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_X.diminfo[0].strides, __pyx_t_13, __pyx_pybuffernd_X.diminfo[1].strides)) <= (__pyx_v_self->threshold[__pyx_v_node_id])); - if (__pyx_t_11) { + __pyx_v_self->n_samples = __pyx_v_j; - /* "sklearn/tree/_tree.pyx":870 - * while self.children_left[node_id] != _TREE_LEAF: # and self.children_right[node_id] != _TREE_LEAF: - * if X[i, self.feature[node_id]] <= self.threshold[node_id]: - * node_id = self.children_left[node_id] # <<<<<<<<<<<<<< - * else: - * node_id = self.children_right[node_id] + /* "sklearn/tree/_tree.pyx":983 + * + * self.n_samples = j + * self.weighted_n_samples = weighted_n_samples # <<<<<<<<<<<<<< + * + * cdef SIZE_t n_features = X.shape[1] */ - __pyx_v_node_id = (__pyx_v_self->children_left[__pyx_v_node_id]); - goto __pyx_L7; - } - /*else*/ { + __pyx_v_self->weighted_n_samples = __pyx_v_weighted_n_samples; - /* "sklearn/tree/_tree.pyx":872 - * node_id = self.children_left[node_id] - * else: - * node_id = self.children_right[node_id] # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":985 + * self.weighted_n_samples = weighted_n_samples + * + * cdef SIZE_t n_features = X.shape[1] # <<<<<<<<<<<<<< + * cdef SIZE_t* features = safe_realloc(&self.features, n_features) * - * out[i] = node_id */ - __pyx_v_node_id = (__pyx_v_self->children_right[__pyx_v_node_id]); - } - __pyx_L7:; - } + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_8 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_8 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_n_features = __pyx_t_8; - /* "sklearn/tree/_tree.pyx":874 - * node_id = self.children_right[node_id] + /* "sklearn/tree/_tree.pyx":986 * - * out[i] = node_id # <<<<<<<<<<<<<< + * cdef SIZE_t n_features = X.shape[1] + * cdef SIZE_t* features = safe_realloc(&self.features, n_features) # <<<<<<<<<<<<<< * - * return out + * for i in range(n_features): + */ + __pyx_t_9 = __pyx_fuse_1__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_self->features), __pyx_v_n_features); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 986; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_features = __pyx_t_9; + + /* "sklearn/tree/_tree.pyx":988 + * cdef SIZE_t* features = safe_realloc(&self.features, n_features) + * + * for i in range(n_features): # <<<<<<<<<<<<<< + * features[i] = i + * + */ + __pyx_t_8 = __pyx_v_n_features; + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_8; __pyx_t_10+=1) { + __pyx_v_i = __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":989 + * + * for i in range(n_features): + * features[i] = i # <<<<<<<<<<<<<< + * + * self.n_features = n_features */ - __pyx_t_14 = __pyx_v_i; - *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int32_t *, __pyx_pybuffernd_out.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_out.diminfo[0].strides) = __pyx_v_node_id; + (__pyx_v_features[__pyx_v_i]) = __pyx_v_i; } - /* "sklearn/tree/_tree.pyx":876 - * out[i] = node_id + /* "sklearn/tree/_tree.pyx":991 + * features[i] = i * - * return out # <<<<<<<<<<<<<< + * self.n_features = n_features # <<<<<<<<<<<<<< * - * cpdef compute_feature_importances(self, method="gini"): + * safe_realloc(&self.feature_values, n_samples) */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_out)); - __pyx_r = ((PyObject *)__pyx_v_out); - goto __pyx_L0; + __pyx_v_self->n_features = __pyx_v_n_features; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "sklearn/tree/_tree.pyx":993 + * self.n_features = n_features + * + * safe_realloc(&self.feature_values, n_samples) # <<<<<<<<<<<<<< + * safe_realloc(&self.constant_features, n_features) + * + */ + __pyx_fuse_0__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_self->feature_values), __pyx_v_n_samples); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 993; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":994 + * + * safe_realloc(&self.feature_values, n_samples) + * safe_realloc(&self.constant_features, n_features) # <<<<<<<<<<<<<< + * + * # Initialize y, sample_weight + */ + __pyx_fuse_1__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_self->constant_features), __pyx_v_n_features); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 994; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":997 + * + * # Initialize y, sample_weight + * self.y = y.data # <<<<<<<<<<<<<< + * self.y_stride = y.strides[0] / y.itemsize + * self.sample_weight = sample_weight + */ + __pyx_v_self->y = ((__pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *)__pyx_v_y->data); + + /* "sklearn/tree/_tree.pyx":998 + * # Initialize y, sample_weight + * self.y = y.data + * self.y_stride = y.strides[0] / y.itemsize # <<<<<<<<<<<<<< + * self.sample_weight = sample_weight + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_y), __pyx_n_s_itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_8 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_8 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->y_stride = (((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)(__pyx_v_y->strides[0])) / ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)__pyx_t_8)); + + /* "sklearn/tree/_tree.pyx":999 + * self.y = y.data + * self.y_stride = y.strides[0] / y.itemsize + * self.sample_weight = sample_weight # <<<<<<<<<<<<<< + * + * cdef void node_reset(self, SIZE_t start, SIZE_t end, + */ + __pyx_v_self->sample_weight = __pyx_v_sample_weight; + + /* "sklearn/tree/_tree.pyx":956 + * pass + * + * cdef void init(self, # <<<<<<<<<<<<<< + * object X, + * np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, + */ + + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.tree._tree.Tree.apply", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + __Pyx_AddTraceback("sklearn.tree._tree.Splitter.init", __pyx_clineno, __pyx_lineno, __pyx_filename); goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_out); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_15apply(PyObject *__pyx_v_self, PyObject *__pyx_v_X); /*proto*/ -static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_14apply[] = "Finds the terminal region (=leaf node) for each sample in X."; -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_15apply(PyObject *__pyx_v_self, PyObject *__pyx_v_X) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("apply (wrapper)", 0); - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 855; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_14apply(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyArrayObject *)__pyx_v_X)); - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; __Pyx_RefNannyFinishContext(); - return __pyx_r; } -/* "sklearn/tree/_tree.pyx":855 - * return out +/* "sklearn/tree/_tree.pyx":1001 + * self.sample_weight = sample_weight * - * cpdef apply(self, np.ndarray[DTYPE_t, ndim=2] X): # <<<<<<<<<<<<<< - * """Finds the terminal region (=leaf node) for each sample in X.""" - * cdef int i = 0 + * cdef void node_reset(self, SIZE_t start, SIZE_t end, # <<<<<<<<<<<<<< + * double* weighted_n_node_samples) nogil: + * """Reset splitter on node samples[start:end].""" */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_14apply(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyArrayObject *__pyx_v_X) { - __Pyx_LocalBuf_ND __pyx_pybuffernd_X; - __Pyx_Buffer __pyx_pybuffer_X; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("apply", 0); - __pyx_pybuffer_X.pybuffer.buf = NULL; - __pyx_pybuffer_X.refcount = 0; - __pyx_pybuffernd_X.data = NULL; - __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 855; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->apply(__pyx_v_self, ((PyArrayObject *)__pyx_v_X), 1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 855; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.tree._tree.Tree.apply", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} +static void __pyx_f_7sklearn_4tree_5_tree_8Splitter_node_reset(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end, double *__pyx_v_weighted_n_node_samples) { + double __pyx_t_1; -/* "sklearn/tree/_tree.pyx":878 - * return out - * - * cpdef compute_feature_importances(self, method="gini"): # <<<<<<<<<<<<<< - * """Computes the importance of each feature (aka variable). + /* "sklearn/tree/_tree.pyx":1004 + * double* weighted_n_node_samples) nogil: + * """Reset splitter on node samples[start:end].""" + * self.start = start # <<<<<<<<<<<<<< + * self.end = end * */ + __pyx_v_self->start = __pyx_v_start; -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_17compute_feature_importances(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_f_7sklearn_4tree_5_tree_4Tree_compute_feature_importances(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances *__pyx_optional_args) { - PyObject *__pyx_v_method = ((PyObject *)__pyx_n_s__gini); - int __pyx_v_node; - PyArrayObject *__pyx_v_importances = 0; - double __pyx_v_normalizer; - __Pyx_LocalBuf_ND __pyx_pybuffernd_importances; - __Pyx_Buffer __pyx_pybuffer_importances; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyArrayObject *__pyx_t_9 = NULL; - int __pyx_t_10; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - PyObject *__pyx_t_13 = NULL; - int __pyx_t_14; - int __pyx_t_15; - double __pyx_t_16; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("compute_feature_importances", 0); - if (__pyx_optional_args) { - if (__pyx_optional_args->__pyx_n > 0) { - __pyx_v_method = __pyx_optional_args->method; - } - } - __pyx_pybuffer_importances.pybuffer.buf = NULL; - __pyx_pybuffer_importances.refcount = 0; - __pyx_pybuffernd_importances.data = NULL; - __pyx_pybuffernd_importances.rcbuffer = &__pyx_pybuffer_importances; - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overriden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_17compute_feature_importances)) { - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_method); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_method); - __Pyx_GIVEREF(__pyx_v_method); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - - /* "sklearn/tree/_tree.pyx":893 - * or "squared". - * """ - * if method != "gini" and method != "squared": # <<<<<<<<<<<<<< - * raise ValueError( - * 'Invalid value for method. Allowed string ' + /* "sklearn/tree/_tree.pyx":1005 + * """Reset splitter on node samples[start:end].""" + * self.start = start + * self.end = end # <<<<<<<<<<<<<< + * + * self.criterion.init(self.y, */ - __pyx_t_1 = PyObject_RichCompare(__pyx_v_method, ((PyObject *)__pyx_n_s__gini), Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_4) { - __pyx_t_1 = PyObject_RichCompare(__pyx_v_method, ((PyObject *)__pyx_n_s__squared), Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = __pyx_t_5; - } else { - __pyx_t_6 = __pyx_t_4; - } - if (__pyx_t_6) { + __pyx_v_self->end = __pyx_v_end; - /* "sklearn/tree/_tree.pyx":894 - * """ - * if method != "gini" and method != "squared": - * raise ValueError( # <<<<<<<<<<<<<< - * 'Invalid value for method. Allowed string ' - * 'values are "gini", or "squared".') + /* "sklearn/tree/_tree.pyx":1007 + * self.end = end + * + * self.criterion.init(self.y, # <<<<<<<<<<<<<< + * self.y_stride, + * self.sample_weight, */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 894; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 894; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; - } - __pyx_L3:; + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->criterion->__pyx_vtab)->init(__pyx_v_self->criterion, __pyx_v_self->y, __pyx_v_self->y_stride, __pyx_v_self->sample_weight, __pyx_v_self->weighted_n_samples, __pyx_v_self->samples, __pyx_v_start, __pyx_v_end); - /* "sklearn/tree/_tree.pyx":900 - * cdef int node - * cdef np.ndarray[np.float64_t, ndim=1] importances - * importances = np.zeros((self.n_features,), dtype=np.float64) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1015 + * end) + * + * weighted_n_node_samples[0] = self.criterion.weighted_n_node_samples # <<<<<<<<<<<<<< * - * if method == "gini": + * cdef void node_split(self, double impurity, SplitRecord* split, */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); - __pyx_t_2 = 0; - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__float64); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_8) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_8, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_9 = ((PyArrayObject *)__pyx_t_8); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_importances.rcbuffer->pybuffer); - __pyx_t_10 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_importances.rcbuffer->pybuffer, (PyObject*)__pyx_t_9, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_10 < 0)) { - PyErr_Fetch(&__pyx_t_11, &__pyx_t_12, &__pyx_t_13); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_importances.rcbuffer->pybuffer, (PyObject*)__pyx_v_importances, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_13); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_11, __pyx_t_12, __pyx_t_13); - } - } - __pyx_pybuffernd_importances.diminfo[0].strides = __pyx_pybuffernd_importances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_importances.diminfo[0].shape = __pyx_pybuffernd_importances.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_10 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_9 = 0; - __pyx_v_importances = ((PyArrayObject *)__pyx_t_8); - __pyx_t_8 = 0; + __pyx_t_1 = __pyx_v_self->criterion->weighted_n_node_samples; + (__pyx_v_weighted_n_node_samples[0]) = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":902 - * importances = np.zeros((self.n_features,), dtype=np.float64) + /* "sklearn/tree/_tree.pyx":1001 + * self.sample_weight = sample_weight * - * if method == "gini": # <<<<<<<<<<<<<< - * for node from 0 <= node < self.node_count: - * if self.children_left[node] != _TREE_LEAF: # and self.children_right[node] != _TREE_LEAF: + * cdef void node_reset(self, SIZE_t start, SIZE_t end, # <<<<<<<<<<<<<< + * double* weighted_n_node_samples) nogil: + * """Reset splitter on node samples[start:end].""" */ - __pyx_t_8 = PyObject_RichCompare(__pyx_v_method, ((PyObject *)__pyx_n_s__gini), Py_EQ); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (__pyx_t_6) { - /* "sklearn/tree/_tree.pyx":903 + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":1017 + * weighted_n_node_samples[0] = self.criterion.weighted_n_node_samples * - * if method == "gini": - * for node from 0 <= node < self.node_count: # <<<<<<<<<<<<<< - * if self.children_left[node] != _TREE_LEAF: # and self.children_right[node] != _TREE_LEAF: - * importances[self.feature[node]] += \ + * cdef void node_split(self, double impurity, SplitRecord* split, # <<<<<<<<<<<<<< + * SIZE_t* n_constant_features) nogil: + * """Find a split on node samples[start:end].""" */ - __pyx_t_10 = __pyx_v_self->node_count; - for (__pyx_v_node = 0; __pyx_v_node < __pyx_t_10; __pyx_v_node++) { - /* "sklearn/tree/_tree.pyx":904 - * if method == "gini": - * for node from 0 <= node < self.node_count: - * if self.children_left[node] != _TREE_LEAF: # and self.children_right[node] != _TREE_LEAF: # <<<<<<<<<<<<<< - * importances[self.feature[node]] += \ - * self._compute_feature_importances_gini(node) - */ - __pyx_t_6 = ((__pyx_v_self->children_left[__pyx_v_node]) != __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF); - if (__pyx_t_6) { +static void __pyx_f_7sklearn_4tree_5_tree_8Splitter_node_split(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, CYTHON_UNUSED double __pyx_v_impurity, CYTHON_UNUSED struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features) { - /* "sklearn/tree/_tree.pyx":905 - * for node from 0 <= node < self.node_count: - * if self.children_left[node] != _TREE_LEAF: # and self.children_right[node] != _TREE_LEAF: - * importances[self.feature[node]] += \ # <<<<<<<<<<<<<< - * self._compute_feature_importances_gini(node) - * else: - */ - __pyx_t_14 = (__pyx_v_self->feature[__pyx_v_node]); - *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_importances.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_importances.diminfo[0].strides) += __pyx_f_7sklearn_4tree_5_tree_4Tree__compute_feature_importances_gini(__pyx_v_self, __pyx_v_node); - goto __pyx_L7; - } - __pyx_L7:; - } - goto __pyx_L4; - } - /*else*/ { + /* function exit code */ +} - /* "sklearn/tree/_tree.pyx":908 - * self._compute_feature_importances_gini(node) - * else: - * for node from 0 <= node < self.node_count: # <<<<<<<<<<<<<< - * if self.children_left[node] != _TREE_LEAF: # and self.children_right[node] != _TREE_LEAF: - * importances[self.feature[node]] += \ +/* "sklearn/tree/_tree.pyx":1022 + * pass + * + * cdef void node_value(self, double* dest) nogil: # <<<<<<<<<<<<<< + * """Copy the value of node samples[start:end] into dest.""" + * self.criterion.node_value(dest) */ - __pyx_t_10 = __pyx_v_self->node_count; - for (__pyx_v_node = 0; __pyx_v_node < __pyx_t_10; __pyx_v_node++) { - /* "sklearn/tree/_tree.pyx":909 - * else: - * for node from 0 <= node < self.node_count: - * if self.children_left[node] != _TREE_LEAF: # and self.children_right[node] != _TREE_LEAF: # <<<<<<<<<<<<<< - * importances[self.feature[node]] += \ - * self._compute_feature_importances_squared(node) - */ - __pyx_t_6 = ((__pyx_v_self->children_left[__pyx_v_node]) != __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF); - if (__pyx_t_6) { +static void __pyx_f_7sklearn_4tree_5_tree_8Splitter_node_value(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, double *__pyx_v_dest) { - /* "sklearn/tree/_tree.pyx":910 - * for node from 0 <= node < self.node_count: - * if self.children_left[node] != _TREE_LEAF: # and self.children_right[node] != _TREE_LEAF: - * importances[self.feature[node]] += \ # <<<<<<<<<<<<<< - * self._compute_feature_importances_squared(node) + /* "sklearn/tree/_tree.pyx":1024 + * cdef void node_value(self, double* dest) nogil: + * """Copy the value of node samples[start:end] into dest.""" + * self.criterion.node_value(dest) # <<<<<<<<<<<<<< * + * cdef double node_impurity(self) nogil: */ - __pyx_t_15 = (__pyx_v_self->feature[__pyx_v_node]); - *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_importances.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_importances.diminfo[0].strides) += __pyx_f_7sklearn_4tree_5_tree_4Tree__compute_feature_importances_squared(__pyx_v_self, __pyx_v_node); - goto __pyx_L10; - } - __pyx_L10:; - } - } - __pyx_L4:; + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->criterion->__pyx_vtab)->node_value(__pyx_v_self->criterion, __pyx_v_dest); - /* "sklearn/tree/_tree.pyx":913 - * self._compute_feature_importances_squared(node) - * - * cdef double normalizer = np.sum(importances) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1022 + * pass * - * if normalizer > 0.0: + * cdef void node_value(self, double* dest) nogil: # <<<<<<<<<<<<<< + * """Copy the value of node samples[start:end] into dest.""" + * self.criterion.node_value(dest) */ - __pyx_t_8 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 913; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_8, __pyx_n_s__sum); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 913; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 913; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_INCREF(((PyObject *)__pyx_v_importances)); - PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_v_importances)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_importances)); - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 913; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_16 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_16 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 913; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_normalizer = __pyx_t_16; - /* "sklearn/tree/_tree.pyx":915 - * cdef double normalizer = np.sum(importances) + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":1026 + * self.criterion.node_value(dest) * - * if normalizer > 0.0: # <<<<<<<<<<<<<< - * # Avoid dividing by zero (e.g., when root is pure) - * importances /= normalizer + * cdef double node_impurity(self) nogil: # <<<<<<<<<<<<<< + * """Copy the impurity of node samples[start:end.""" + * return self.criterion.node_impurity() */ - __pyx_t_6 = (__pyx_v_normalizer > 0.0); - if (__pyx_t_6) { - /* "sklearn/tree/_tree.pyx":917 - * if normalizer > 0.0: - * # Avoid dividing by zero (e.g., when root is pure) - * importances /= normalizer # <<<<<<<<<<<<<< +static double __pyx_f_7sklearn_4tree_5_tree_8Splitter_node_impurity(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self) { + double __pyx_r; + + /* "sklearn/tree/_tree.pyx":1028 + * cdef double node_impurity(self) nogil: + * """Copy the impurity of node samples[start:end.""" + * return self.criterion.node_impurity() # <<<<<<<<<<<<<< + * * - * return importances */ - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_normalizer); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 917; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_8 = __Pyx_PyNumber_InPlaceDivide(((PyObject *)__pyx_v_importances), __pyx_t_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 917; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_8) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_8, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 917; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_9 = ((PyArrayObject *)__pyx_t_8); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_importances.rcbuffer->pybuffer); - __pyx_t_10 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_importances.rcbuffer->pybuffer, (PyObject*)__pyx_t_9, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_10 < 0)) { - PyErr_Fetch(&__pyx_t_13, &__pyx_t_12, &__pyx_t_11); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_importances.rcbuffer->pybuffer, (PyObject*)__pyx_v_importances, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_13); Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_13, __pyx_t_12, __pyx_t_11); - } - } - __pyx_pybuffernd_importances.diminfo[0].strides = __pyx_pybuffernd_importances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_importances.diminfo[0].shape = __pyx_pybuffernd_importances.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_10 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 917; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_9 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_importances)); - __pyx_v_importances = ((PyArrayObject *)__pyx_t_8); - __pyx_t_8 = 0; - goto __pyx_L11; - } - __pyx_L11:; + __pyx_r = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->criterion->__pyx_vtab)->node_impurity(__pyx_v_self->criterion); + goto __pyx_L0; - /* "sklearn/tree/_tree.pyx":919 - * importances /= normalizer + /* "sklearn/tree/_tree.pyx":1026 + * self.criterion.node_value(dest) * - * return importances # <<<<<<<<<<<<<< + * cdef double node_impurity(self) nogil: # <<<<<<<<<<<<<< + * """Copy the impurity of node samples[start:end.""" + * return self.criterion.node_impurity() + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pxd":86 * - * cdef inline double _compute_feature_importances_gini(self, int node): + * # Internal structures + * cdef public Criterion criterion # Impurity criterion # <<<<<<<<<<<<<< + * cdef public SIZE_t max_features # Number of features to test + * cdef public SIZE_t min_samples_leaf # Min samples in a leaf */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_9criterion_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_9criterion_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter_9criterion___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_9criterion___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_importances)); - __pyx_r = ((PyObject *)__pyx_v_importances); + __Pyx_INCREF(((PyObject *)__pyx_v_self->criterion)); + __pyx_r = ((PyObject *)__pyx_v_self->criterion); goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_importances.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.tree._tree.Tree.compute_feature_importances", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - goto __pyx_L2; + /* function exit code */ __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_importances.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_importances); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_17compute_feature_importances(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_16compute_feature_importances[] = "Computes the importance of each feature (aka variable).\n\n The following `method`s are supported:\n\n * \"gini\" : The difference of the initial error and the error of the\n split times the number of samples that passed the node.\n * \"squared\" : The empirical improvement in squared error.\n\n Parameters\n ----------\n method : str, optional (default=\"gini\")\n The method to estimate the importance of a feature. Either \"gini\"\n or \"squared\".\n "; -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_17compute_feature_importances(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_method = 0; - PyObject *__pyx_r = 0; +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_9criterion_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_9criterion_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("compute_feature_importances (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__method,0}; - PyObject* values[1] = {0}; - values[0] = ((PyObject *)__pyx_n_s__gini); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__method); - if (value) { values[0] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "compute_feature_importances") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_method = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("compute_feature_importances", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.compute_feature_importances", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_16compute_feature_importances(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), __pyx_v_method); + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter_9criterion_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pyx":878 - * return out - * - * cpdef compute_feature_importances(self, method="gini"): # <<<<<<<<<<<<<< - * """Computes the importance of each feature (aka variable). - * - */ - -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_16compute_feature_importances(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_method) { - PyObject *__pyx_r = NULL; +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter_9criterion_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances __pyx_t_2; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("compute_feature_importances", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_2.__pyx_n = 1; - __pyx_t_2.method = __pyx_v_method; - __pyx_t_1 = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->compute_feature_importances(__pyx_v_self, 1, &__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 878; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; + __Pyx_RefNannySetupContext("__set__", 0); + if (!(likely(((__pyx_v_value) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_value, __pyx_ptype_7sklearn_4tree_5_tree_Criterion))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_v_value; + __Pyx_INCREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->criterion); + __Pyx_DECREF(((PyObject *)__pyx_v_self->criterion)); + __pyx_v_self->criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* function exit code */ + __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.compute_feature_importances", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __Pyx_AddTraceback("sklearn.tree._tree.Splitter.criterion.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pyx":921 - * return importances - * - * cdef inline double _compute_feature_importances_gini(self, int node): # <<<<<<<<<<<<<< - * return self.n_samples[node] * (self.init_error[node] - self.best_error[node]) - * - */ - -static CYTHON_INLINE double __pyx_f_7sklearn_4tree_5_tree_4Tree__compute_feature_importances_gini(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, int __pyx_v_node) { - double __pyx_r; +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_9criterion_5__del__(PyObject *__pyx_v_self); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_9criterion_5__del__(PyObject *__pyx_v_self) { + int __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_compute_feature_importances_gini", 0); - - /* "sklearn/tree/_tree.pyx":922 - * - * cdef inline double _compute_feature_importances_gini(self, int node): - * return self.n_samples[node] * (self.init_error[node] - self.best_error[node]) # <<<<<<<<<<<<<< - * - * cdef inline double _compute_feature_importances_squared(self, int node): - */ - __pyx_r = ((__pyx_v_self->n_samples[__pyx_v_node]) * ((__pyx_v_self->init_error[__pyx_v_node]) - (__pyx_v_self->best_error[__pyx_v_node]))); - goto __pyx_L0; + __Pyx_RefNannySetupContext("__del__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter_9criterion_4__del__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self)); - __pyx_r = 0; - __pyx_L0:; + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pyx":924 - * return self.n_samples[node] * (self.init_error[node] - self.best_error[node]) - * - * cdef inline double _compute_feature_importances_squared(self, int node): # <<<<<<<<<<<<<< - * cdef double error = self.init_error[node] - self.best_error[node] - * return error * error - */ - -static CYTHON_INLINE double __pyx_f_7sklearn_4tree_5_tree_4Tree__compute_feature_importances_squared(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, int __pyx_v_node) { - double __pyx_v_error; - double __pyx_r; +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter_9criterion_4__del__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self) { + int __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_compute_feature_importances_squared", 0); - - /* "sklearn/tree/_tree.pyx":925 - * - * cdef inline double _compute_feature_importances_squared(self, int node): - * cdef double error = self.init_error[node] - self.best_error[node] # <<<<<<<<<<<<<< - * return error * error - * - */ - __pyx_v_error = ((__pyx_v_self->init_error[__pyx_v_node]) - (__pyx_v_self->best_error[__pyx_v_node])); - - /* "sklearn/tree/_tree.pyx":926 - * cdef inline double _compute_feature_importances_squared(self, int node): - * cdef double error = self.init_error[node] - self.best_error[node] - * return error * error # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = (__pyx_v_error * __pyx_v_error); - goto __pyx_L0; + __Pyx_RefNannySetupContext("__del__", 0); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_self->criterion); + __Pyx_DECREF(((PyObject *)__pyx_v_self->criterion)); + __pyx_v_self->criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)Py_None); + /* function exit code */ __pyx_r = 0; - __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } +/* "sklearn/tree/_tree.pxd":87 + * # Internal structures + * cdef public Criterion criterion # Impurity criterion + * cdef public SIZE_t max_features # Number of features to test # <<<<<<<<<<<<<< + * cdef public SIZE_t min_samples_leaf # Min samples in a leaf + * cdef public double min_weight_leaf # Minimum weight in a leaf + */ + /* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_1__get__(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_12max_features_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_12max_features_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter_12max_features___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pxd":38 - * cdef class Tree: - * # Input/Output layout - * cdef public int n_features # <<<<<<<<<<<<<< - * cdef int* n_classes - * cdef public int n_outputs - */ - -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_12max_features___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -8577,17 +9295,16 @@ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features___get__(struc int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->max_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_features.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.tree._tree.Splitter.max_features.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); @@ -8596,57 +9313,62 @@ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features___get__(struc } /* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_12max_features_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_12max_features_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter_12max_features_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter_12max_features_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations - int __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_value); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->n_features = __pyx_t_1; + __pyx_t_1 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_value); if (unlikely((__pyx_t_1 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->max_features = __pyx_t_1; + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_features.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.tree._tree.Splitter.max_features.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } +/* "sklearn/tree/_tree.pxd":88 + * cdef public Criterion criterion # Impurity criterion + * cdef public SIZE_t max_features # Number of features to test + * cdef public SIZE_t min_samples_leaf # Min samples in a leaf # <<<<<<<<<<<<<< + * cdef public double min_weight_leaf # Minimum weight in a leaf + * + */ + /* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_1__get__(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pxd":40 - * cdef public int n_features - * cdef int* n_classes - * cdef public int n_outputs # <<<<<<<<<<<<<< - * - * cdef public int max_n_classes - */ - -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -8655,17 +9377,16 @@ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs___get__(struct int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->n_outputs); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->min_samples_leaf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_outputs.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.tree._tree.Splitter.min_samples_leaf.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); @@ -8674,57 +9395,62 @@ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs___get__(struct } /* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations - int __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_value); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->n_outputs = __pyx_t_1; + __pyx_t_1 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_value); if (unlikely((__pyx_t_1 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->min_samples_leaf = __pyx_t_1; + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_outputs.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.tree._tree.Splitter.min_samples_leaf.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } +/* "sklearn/tree/_tree.pxd":89 + * cdef public SIZE_t max_features # Number of features to test + * cdef public SIZE_t min_samples_leaf # Min samples in a leaf + * cdef public double min_weight_leaf # Minimum weight in a leaf # <<<<<<<<<<<<<< + * + * cdef object random_state # Random state + */ + /* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_1__get__(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pxd":42 - * cdef public int n_outputs - * - * cdef public int max_n_classes # <<<<<<<<<<<<<< - * cdef public int value_stride - * - */ - -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -8733,17 +9459,16 @@ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes___get__(st int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->max_n_classes); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->min_weight_leaf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.max_n_classes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.tree._tree.Splitter.min_weight_leaf.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); @@ -8752,250 +9477,477 @@ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes___get__(st } /* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { +static int __pyx_pf_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations - int __pyx_t_1; + double __pyx_t_1; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_value); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->max_n_classes = __pyx_t_1; + __pyx_t_1 = __pyx_PyFloat_AsDouble(__pyx_v_value); if (unlikely((__pyx_t_1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->min_weight_leaf = __pyx_t_1; + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.max_n_classes.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.tree._tree.Splitter.min_weight_leaf.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_12value_stride_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_12value_stride_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_12value_stride___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/tree/_tree.pxd":43 +/* "sklearn/tree/_tree.pyx":1036 + * cdef SIZE_t X_fx_stride * - * cdef public int max_n_classes - * cdef public int value_stride # <<<<<<<<<<<<<< - * - * # Parameters + * def __cinit__(self, Criterion criterion, SIZE_t max_features, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, double min_weight_leaf, + * object random_state): */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_12value_stride___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_17BaseDenseSplitter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_17BaseDenseSplitter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion = 0; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + CYTHON_UNUSED double __pyx_v_min_weight_leaf; + CYTHON_UNUSED PyObject *__pyx_v_random_state = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->value_stride); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_criterion,&__pyx_n_s_max_features,&__pyx_n_s_min_samples_leaf,&__pyx_n_s_min_weight_leaf,&__pyx_n_s_random_state,0}; + PyObject* values[5] = {0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_criterion)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_features)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1036; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_samples_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1036; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_weight_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1036; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random_state)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1036; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1036; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + } + __pyx_v_criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)values[0]); + __pyx_v_max_features = __Pyx_PyInt_As_Py_intptr_t(values[1]); if (unlikely((__pyx_v_max_features == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1036; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_samples_leaf = __Pyx_PyInt_As_Py_intptr_t(values[2]); if (unlikely((__pyx_v_min_samples_leaf == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1037; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_weight_leaf = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_min_weight_leaf == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1037; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_random_state = values[4]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1036; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._tree.BaseDenseSplitter.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_criterion), __pyx_ptype_7sklearn_4tree_5_tree_Criterion, 1, "criterion", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1036; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_17BaseDenseSplitter___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter *)__pyx_v_self), __pyx_v_criterion, __pyx_v_max_features, __pyx_v_min_samples_leaf, __pyx_v_min_weight_leaf, __pyx_v_random_state); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.value_stride.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __pyx_r = -1; __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_12value_stride_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_12value_stride_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { +static int __pyx_pf_7sklearn_4tree_5_tree_17BaseDenseSplitter___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter *__pyx_v_self, CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, CYTHON_UNUSED double __pyx_v_min_weight_leaf, CYTHON_UNUSED PyObject *__pyx_v_random_state) { int __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_12value_stride_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "sklearn/tree/_tree.pyx":1041 + * # Parent __cinit__ is automatically called + * + * self.X = NULL # <<<<<<<<<<<<<< + * self.X_sample_stride = 0 + * self.X_fx_stride = 0 + */ + __pyx_v_self->X = NULL; + + /* "sklearn/tree/_tree.pyx":1042 + * + * self.X = NULL + * self.X_sample_stride = 0 # <<<<<<<<<<<<<< + * self.X_fx_stride = 0 + * + */ + __pyx_v_self->X_sample_stride = 0; + + /* "sklearn/tree/_tree.pyx":1043 + * self.X = NULL + * self.X_sample_stride = 0 + * self.X_fx_stride = 0 # <<<<<<<<<<<<<< + * + * cdef void init(self, + */ + __pyx_v_self->X_fx_stride = 0; + + /* "sklearn/tree/_tree.pyx":1036 + * cdef SIZE_t X_fx_stride + * + * def __cinit__(self, Criterion criterion, SIZE_t max_features, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, double min_weight_leaf, + * object random_state): + */ + + /* function exit code */ + __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_12value_stride_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; +/* "sklearn/tree/_tree.pyx":1045 + * self.X_fx_stride = 0 + * + * cdef void init(self, # <<<<<<<<<<<<<< + * object X, + * np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, + */ + +static void __pyx_f_7sklearn_4tree_5_tree_17BaseDenseSplitter_init(struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter *__pyx_v_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight) { + PyArrayObject *__pyx_v_X_ndarray = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_y; + __Pyx_Buffer __pyx_pybuffer_y; __Pyx_RefNannyDeclarations - int __pyx_t_1; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_4; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_value); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->value_stride = __pyx_t_1; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.value_stride.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __Pyx_RefNannySetupContext("init", 0); + __pyx_pybuffer_y.pybuffer.buf = NULL; + __pyx_pybuffer_y.refcount = 0; + __pyx_pybuffernd_y.data = NULL; + __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DOUBLE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_y.diminfo[1].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_y.diminfo[1].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[1]; -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9criterion_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9criterion_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9criterion___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1052 + * + * # Call parent init + * Splitter.init(self, X, y, sample_weight) # <<<<<<<<<<<<<< + * + * # Initialize X + */ + __pyx_f_7sklearn_4tree_5_tree_8Splitter_init(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self), __pyx_v_X, ((PyArrayObject *)__pyx_v_y), __pyx_v_sample_weight); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1052; __pyx_clineno = __LINE__; goto __pyx_L1_error;} -/* "sklearn/tree/_tree.pxd":46 + /* "sklearn/tree/_tree.pyx":1055 * - * # Parameters - * cdef public Criterion criterion # <<<<<<<<<<<<<< - * cdef public double max_depth - * cdef public int min_samples_split + * # Initialize X + * cdef np.ndarray X_ndarray = X # <<<<<<<<<<<<<< + * + * self.X = X_ndarray.data */ + if (!(likely(((__pyx_v_X) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_X, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1055; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_v_X; + __Pyx_INCREF(__pyx_t_1); + __pyx_v_X_ndarray = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9criterion___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_self->criterion)); - __pyx_r = ((PyObject *)__pyx_v_self->criterion); - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":1057 + * cdef np.ndarray X_ndarray = X + * + * self.X = X_ndarray.data # <<<<<<<<<<<<<< + * self.X_sample_stride = X.strides[0] / X.itemsize + * self.X_fx_stride = X.strides[1] / X.itemsize + */ + __pyx_v_self->X = ((__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *)__pyx_v_X_ndarray->data); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1058 + * + * self.X = X_ndarray.data + * self.X_sample_stride = X.strides[0] / X.itemsize # <<<<<<<<<<<<<< + * self.X_fx_stride = X.strides[1] / X.itemsize + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_strides); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1058; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1058; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_2); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1058; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1058; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_2); if (unlikely((__pyx_t_4 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1058; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_self->X_sample_stride = (((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)__pyx_t_3) / ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)__pyx_t_4)); -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9criterion_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9criterion_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9criterion_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1059 + * self.X = X_ndarray.data + * self.X_sample_stride = X.strides[0] / X.itemsize + * self.X_fx_stride = X.strides[1] / X.itemsize # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_strides); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_4 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_3 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->X_fx_stride = (((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)__pyx_t_4) / ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)__pyx_t_3)); -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_9criterion_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__set__", 0); - if (!(likely(((__pyx_v_value) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_value, __pyx_ptype_7sklearn_4tree_5_tree_Criterion))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_INCREF(__pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - __Pyx_GOTREF(__pyx_v_self->criterion); - __Pyx_DECREF(((PyObject *)__pyx_v_self->criterion)); - __pyx_v_self->criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)__pyx_v_value); + /* "sklearn/tree/_tree.pyx":1045 + * self.X_fx_stride = 0 + * + * cdef void init(self, # <<<<<<<<<<<<<< + * object X, + * np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, + */ - __pyx_r = 0; + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.criterion.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.tree._tree.BaseDenseSplitter.init", __pyx_clineno, __pyx_lineno, __pyx_filename); + goto __pyx_L2; __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_X_ndarray); __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9criterion_5__del__(PyObject *__pyx_v_self); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9criterion_5__del__(PyObject *__pyx_v_self) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__del__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9criterion_4__del__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; } -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_9criterion_4__del__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__del__", 0); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->criterion); - __Pyx_DECREF(((PyObject *)__pyx_v_self->criterion)); - __pyx_v_self->criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)Py_None); - - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} +/* "sklearn/tree/_tree.pyx":1064 + * cdef class BestSplitter(BaseDenseSplitter): + * """Splitter for finding the best split.""" + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (BestSplitter, (self.criterion, + * self.max_features, + */ /* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_1__get__(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_12BestSplitter_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_12BestSplitter_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9max_depth___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_12BestSplitter___reduce__(((struct __pyx_obj_7sklearn_4tree_5_tree_BestSplitter *)__pyx_v_self)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pxd":47 - * # Parameters - * cdef public Criterion criterion - * cdef public double max_depth # <<<<<<<<<<<<<< - * cdef public int min_samples_split - * cdef public int min_samples_leaf - */ - -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9max_depth___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_12BestSplitter___reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_BestSplitter *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_RefNannySetupContext("__reduce__", 0); + + /* "sklearn/tree/_tree.pyx":1065 + * """Splitter for finding the best split.""" + * def __reduce__(self): + * return (BestSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, + */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->max_depth); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":1066 + * def __reduce__(self): + * return (BestSplitter, (self.criterion, + * self.max_features, # <<<<<<<<<<<<<< + * self.min_samples_leaf, + * self.min_weight_leaf, + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.__pyx_base.max_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1066; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":1067 + * return (BestSplitter, (self.criterion, + * self.max_features, + * self.min_samples_leaf, # <<<<<<<<<<<<<< + * self.min_weight_leaf, + * self.random_state), self.__getstate__()) + */ + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.__pyx_base.min_samples_leaf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1067; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + + /* "sklearn/tree/_tree.pyx":1068 + * self.max_features, + * self.min_samples_leaf, + * self.min_weight_leaf, # <<<<<<<<<<<<<< + * self.random_state), self.__getstate__()) + * + */ + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_self->__pyx_base.__pyx_base.min_weight_leaf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1068; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "sklearn/tree/_tree.pyx":1065 + * """Splitter for finding the best split.""" + * def __reduce__(self): + * return (BestSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, + */ + __pyx_t_4 = PyTuple_New(5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_self->__pyx_base.__pyx_base.random_state); + PyTuple_SET_ITEM(__pyx_t_4, 4, __pyx_v_self->__pyx_base.__pyx_base.random_state); + __Pyx_GIVEREF(__pyx_v_self->__pyx_base.__pyx_base.random_state); __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "sklearn/tree/_tree.pyx":1069 + * self.min_samples_leaf, + * self.min_weight_leaf, + * self.random_state), self.__getstate__()) # <<<<<<<<<<<<<< + * + * cdef void node_split(self, double impurity, SplitRecord* split, + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_getstate); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (__pyx_t_1) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/tree/_tree.pyx":1065 + * """Splitter for finding the best split.""" + * def __reduce__(self): + * return (BestSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, + */ + __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1065; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_BestSplitter))); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_BestSplitter))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_BestSplitter))); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":1064 + * cdef class BestSplitter(BaseDenseSplitter): + * """Splitter for finding the best split.""" + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (BestSplitter, (self.criterion, + * self.max_features, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.max_depth.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.BestSplitter.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); @@ -9003,2604 +9955,2868 @@ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9max_depth___get__(struct return __pyx_r; } -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9max_depth_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_9max_depth_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - double __pyx_t_1; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __pyx_PyFloat_AsDouble(__pyx_v_value); if (unlikely((__pyx_t_1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->max_depth = __pyx_t_1; +/* "sklearn/tree/_tree.pyx":1071 + * self.random_state), self.__getstate__()) + * + * cdef void node_split(self, double impurity, SplitRecord* split, # <<<<<<<<<<<<<< + * SIZE_t* n_constant_features) nogil: + * """Find the best split on node samples[start:end].""" + */ + +static void __pyx_f_7sklearn_4tree_5_tree_12BestSplitter_node_split(struct __pyx_obj_7sklearn_4tree_5_tree_BestSplitter *__pyx_v_self, double __pyx_v_impurity, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_constant_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_features; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_X_sample_stride; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_X_fx_stride; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + double __pyx_v_min_weight_leaf; + __pyx_t_7sklearn_4tree_5_tree_UINT32_t *__pyx_v_random_state; + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_best; + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_current; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_f_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_f_j; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_tmp; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_visited_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_found_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_drawn_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_known_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_total_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_partition_end; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_t_3; + double __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.max_depth.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1075 + * """Find the best split on node samples[start:end].""" + * # Find the best split + * cdef SIZE_t* samples = self.samples # <<<<<<<<<<<<<< + * cdef SIZE_t start = self.start + * cdef SIZE_t end = self.end + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.samples; + __pyx_v_samples = __pyx_t_1; -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_17min_samples_split_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_17min_samples_split_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_17min_samples_split___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1076 + * # Find the best split + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t start = self.start # <<<<<<<<<<<<<< + * cdef SIZE_t end = self.end + * + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.start; + __pyx_v_start = __pyx_t_2; -/* "sklearn/tree/_tree.pxd":48 - * cdef public Criterion criterion - * cdef public double max_depth - * cdef public int min_samples_split # <<<<<<<<<<<<<< - * cdef public int min_samples_leaf - * cdef public double min_density + /* "sklearn/tree/_tree.pyx":1077 + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t start = self.start + * cdef SIZE_t end = self.end # <<<<<<<<<<<<<< + * + * cdef SIZE_t* features = self.features */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.end; + __pyx_v_end = __pyx_t_2; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_17min_samples_split___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->min_samples_split); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":1079 + * cdef SIZE_t end = self.end + * + * cdef SIZE_t* features = self.features # <<<<<<<<<<<<<< + * cdef SIZE_t* constant_features = self.constant_features + * cdef SIZE_t n_features = self.n_features + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.features; + __pyx_v_features = __pyx_t_1; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.min_samples_split.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_17min_samples_split_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_17min_samples_split_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_17min_samples_split_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_17min_samples_split_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_value); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->min_samples_split = __pyx_t_1; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.min_samples_split.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1080 + * + * cdef SIZE_t* features = self.features + * cdef SIZE_t* constant_features = self.constant_features # <<<<<<<<<<<<<< + * cdef SIZE_t n_features = self.n_features + * + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.constant_features; + __pyx_v_constant_features = __pyx_t_1; -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1081 + * cdef SIZE_t* features = self.features + * cdef SIZE_t* constant_features = self.constant_features + * cdef SIZE_t n_features = self.n_features # <<<<<<<<<<<<<< + * + * cdef DTYPE_t* X = self.X + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.n_features; + __pyx_v_n_features = __pyx_t_2; -/* "sklearn/tree/_tree.pxd":49 - * cdef public double max_depth - * cdef public int min_samples_split - * cdef public int min_samples_leaf # <<<<<<<<<<<<<< - * cdef public double min_density - * cdef public int max_features + /* "sklearn/tree/_tree.pyx":1083 + * cdef SIZE_t n_features = self.n_features + * + * cdef DTYPE_t* X = self.X # <<<<<<<<<<<<<< + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t X_sample_stride = self.X_sample_stride */ + __pyx_t_3 = __pyx_v_self->__pyx_base.X; + __pyx_v_X = __pyx_t_3; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->min_samples_leaf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":1084 + * + * cdef DTYPE_t* X = self.X + * cdef DTYPE_t* Xf = self.feature_values # <<<<<<<<<<<<<< + * cdef SIZE_t X_sample_stride = self.X_sample_stride + * cdef SIZE_t X_fx_stride = self.X_fx_stride + */ + __pyx_t_3 = __pyx_v_self->__pyx_base.__pyx_base.feature_values; + __pyx_v_Xf = __pyx_t_3; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.min_samples_leaf.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1085 + * cdef DTYPE_t* X = self.X + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t X_sample_stride = self.X_sample_stride # <<<<<<<<<<<<<< + * cdef SIZE_t X_fx_stride = self.X_fx_stride + * cdef SIZE_t max_features = self.max_features + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.X_sample_stride; + __pyx_v_X_sample_stride = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":1086 + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t X_sample_stride = self.X_sample_stride + * cdef SIZE_t X_fx_stride = self.X_fx_stride # <<<<<<<<<<<<<< + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.X_fx_stride; + __pyx_v_X_fx_stride = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":1087 + * cdef SIZE_t X_sample_stride = self.X_sample_stride + * cdef SIZE_t X_fx_stride = self.X_fx_stride + * cdef SIZE_t max_features = self.max_features # <<<<<<<<<<<<<< + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.max_features; + __pyx_v_max_features = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":1088 + * cdef SIZE_t X_fx_stride = self.X_fx_stride + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf # <<<<<<<<<<<<<< + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef UINT32_t* random_state = &self.rand_r_state + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.min_samples_leaf; + __pyx_v_min_samples_leaf = __pyx_t_2; -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1089 + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf # <<<<<<<<<<<<<< + * cdef UINT32_t* random_state = &self.rand_r_state + * + */ + __pyx_t_4 = __pyx_v_self->__pyx_base.__pyx_base.min_weight_leaf; + __pyx_v_min_weight_leaf = __pyx_t_4; -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_value); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->min_samples_leaf = __pyx_t_1; + /* "sklearn/tree/_tree.pyx":1090 + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef UINT32_t* random_state = &self.rand_r_state # <<<<<<<<<<<<<< + * + * cdef SplitRecord best, current + */ + __pyx_v_random_state = (&__pyx_v_self->__pyx_base.__pyx_base.rand_r_state); - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.min_samples_leaf.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1094 + * cdef SplitRecord best, current + * + * cdef SIZE_t f_i = n_features # <<<<<<<<<<<<<< + * cdef SIZE_t f_j, p, tmp + * cdef SIZE_t n_visited_features = 0 + */ + __pyx_v_f_i = __pyx_v_n_features; -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_11min_density_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_11min_density_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_11min_density___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1096 + * cdef SIZE_t f_i = n_features + * cdef SIZE_t f_j, p, tmp + * cdef SIZE_t n_visited_features = 0 # <<<<<<<<<<<<<< + * # Number of features discovered to be constant during the split search + * cdef SIZE_t n_found_constants = 0 + */ + __pyx_v_n_visited_features = 0; -/* "sklearn/tree/_tree.pxd":50 - * cdef public int min_samples_split - * cdef public int min_samples_leaf - * cdef public double min_density # <<<<<<<<<<<<<< - * cdef public int max_features - * cdef public int find_split_algorithm + /* "sklearn/tree/_tree.pyx":1098 + * cdef SIZE_t n_visited_features = 0 + * # Number of features discovered to be constant during the split search + * cdef SIZE_t n_found_constants = 0 # <<<<<<<<<<<<<< + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 */ + __pyx_v_n_found_constants = 0; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_11min_density___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->min_density); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":1100 + * cdef SIZE_t n_found_constants = 0 + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t n_known_constants = n_constant_features[0] + * # n_total_constants = n_known_constants + n_found_constants + */ + __pyx_v_n_drawn_constants = 0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.min_density.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1101 + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 + * cdef SIZE_t n_known_constants = n_constant_features[0] # <<<<<<<<<<<<<< + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants + */ + __pyx_v_n_known_constants = (__pyx_v_n_constant_features[0]); -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_11min_density_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_11min_density_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_11min_density_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1103 + * cdef SIZE_t n_known_constants = n_constant_features[0] + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants # <<<<<<<<<<<<<< + * cdef DTYPE_t current_feature_value + * cdef SIZE_t partition_end + */ + __pyx_v_n_total_constants = __pyx_v_n_known_constants; -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_11min_density_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - double __pyx_t_1; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __pyx_PyFloat_AsDouble(__pyx_v_value); if (unlikely((__pyx_t_1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->min_density = __pyx_t_1; + /* "sklearn/tree/_tree.pyx":1107 + * cdef SIZE_t partition_end + * + * _init_split(&best, end) # <<<<<<<<<<<<<< + * + * # Sample up to max_features without replacement using a + */ + __pyx_f_7sklearn_4tree_5_tree__init_split((&__pyx_v_best), __pyx_v_end); - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.min_density.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1118 + * # newly discovered constant features to spare computation on descendant + * # nodes. + * while (f_i > n_total_constants and # Stop early if remaining features # <<<<<<<<<<<<<< + * # are constant + * (n_visited_features < max_features or + */ + while (1) { + __pyx_t_6 = ((__pyx_v_f_i > __pyx_v_n_total_constants) != 0); + if (__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L5_bool_binop_done; + } -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_12max_features_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_12max_features_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_12max_features___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1120 + * while (f_i > n_total_constants and # Stop early if remaining features + * # are constant + * (n_visited_features < max_features or # <<<<<<<<<<<<<< + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): + */ + __pyx_t_6 = ((__pyx_v_n_visited_features < __pyx_v_max_features) != 0); + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L5_bool_binop_done; + } -/* "sklearn/tree/_tree.pxd":51 - * cdef public int min_samples_leaf - * cdef public double min_density - * cdef public int max_features # <<<<<<<<<<<<<< - * cdef public int find_split_algorithm - * cdef public object random_state + /* "sklearn/tree/_tree.pyx":1122 + * (n_visited_features < max_features or + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): # <<<<<<<<<<<<<< + * + * n_visited_features += 1 */ + __pyx_t_6 = ((__pyx_v_n_visited_features <= (__pyx_v_n_found_constants + __pyx_v_n_drawn_constants)) != 0); + __pyx_t_5 = __pyx_t_6; + __pyx_L5_bool_binop_done:; + if (!__pyx_t_5) break; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_12max_features___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->max_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":1124 + * n_visited_features <= n_found_constants + n_drawn_constants)): + * + * n_visited_features += 1 # <<<<<<<<<<<<<< + * + * # Loop invariant: elements of features in + */ + __pyx_v_n_visited_features = (__pyx_v_n_visited_features + 1); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.max_features.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1138 + * + * # Draw a feature at random + * f_j = rand_int(n_drawn_constants, f_i - n_found_constants, # <<<<<<<<<<<<<< + * random_state) + * + */ + __pyx_v_f_j = __pyx_f_7sklearn_4tree_5_tree_rand_int(__pyx_v_n_drawn_constants, (__pyx_v_f_i - __pyx_v_n_found_constants), __pyx_v_random_state); -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_12max_features_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_12max_features_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_12max_features_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1141 + * random_state) + * + * if f_j < n_known_constants: # <<<<<<<<<<<<<< + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] + */ + __pyx_t_5 = ((__pyx_v_f_j < __pyx_v_n_known_constants) != 0); + if (__pyx_t_5) { -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_12max_features_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_value); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->max_features = __pyx_t_1; + /* "sklearn/tree/_tree.pyx":1143 + * if f_j < n_known_constants: + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] # <<<<<<<<<<<<<< + * features[f_j] = features[n_drawn_constants] + * features[n_drawn_constants] = tmp + */ + __pyx_v_tmp = (__pyx_v_features[__pyx_v_f_j]); - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.max_features.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1144 + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] + * features[f_j] = features[n_drawn_constants] # <<<<<<<<<<<<<< + * features[n_drawn_constants] = tmp + * + */ + (__pyx_v_features[__pyx_v_f_j]) = (__pyx_v_features[__pyx_v_n_drawn_constants]); -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1145 + * tmp = features[f_j] + * features[f_j] = features[n_drawn_constants] + * features[n_drawn_constants] = tmp # <<<<<<<<<<<<<< + * + * n_drawn_constants += 1 + */ + (__pyx_v_features[__pyx_v_n_drawn_constants]) = __pyx_v_tmp; -/* "sklearn/tree/_tree.pxd":52 - * cdef public double min_density - * cdef public int max_features - * cdef public int find_split_algorithm # <<<<<<<<<<<<<< - * cdef public object random_state + /* "sklearn/tree/_tree.pyx":1147 + * features[n_drawn_constants] = tmp + * + * n_drawn_constants += 1 # <<<<<<<<<<<<<< * + * else: */ + __pyx_v_n_drawn_constants = (__pyx_v_n_drawn_constants + 1); + goto __pyx_L8; + } + /*else*/ { -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->find_split_algorithm); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":1151 + * else: + * # f_j in the interval [n_known_constants, f_i - n_found_constants[ + * f_j += n_found_constants # <<<<<<<<<<<<<< + * # f_j in the interval [n_total_constants, f_i[ + * + */ + __pyx_v_f_j = (__pyx_v_f_j + __pyx_v_n_found_constants); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.find_split_algorithm.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1154 + * # f_j in the interval [n_total_constants, f_i[ + * + * current.feature = features[f_j] # <<<<<<<<<<<<<< + * + * # Sort samples along that feature; first copy the feature + */ + __pyx_v_current.feature = (__pyx_v_features[__pyx_v_f_j]); -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1160 + * # Xf[i] == X[samples[i], j], so the sort uses the cache more + * # effectively. + * for p in range(start, end): # <<<<<<<<<<<<<< + * Xf[p] = X[X_sample_stride * samples[p] + + * X_fx_stride * current.feature] + */ + __pyx_t_2 = __pyx_v_end; + for (__pyx_t_7 = __pyx_v_start; __pyx_t_7 < __pyx_t_2; __pyx_t_7+=1) { + __pyx_v_p = __pyx_t_7; -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_value); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->find_split_algorithm = __pyx_t_1; + /* "sklearn/tree/_tree.pyx":1161 + * # effectively. + * for p in range(start, end): + * Xf[p] = X[X_sample_stride * samples[p] + # <<<<<<<<<<<<<< + * X_fx_stride * current.feature] + * + */ + (__pyx_v_Xf[__pyx_v_p]) = (__pyx_v_X[((__pyx_v_X_sample_stride * (__pyx_v_samples[__pyx_v_p])) + (__pyx_v_X_fx_stride * __pyx_v_current.feature))]); + } - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.find_split_algorithm.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1164 + * X_fx_stride * current.feature] + * + * sort(Xf + start, samples + start, end - start) # <<<<<<<<<<<<<< + * + * if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: + */ + __pyx_f_7sklearn_4tree_5_tree_sort((__pyx_v_Xf + __pyx_v_start), (__pyx_v_samples + __pyx_v_start), (__pyx_v_end - __pyx_v_start)); -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_12random_state_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_12random_state_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_12random_state___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1166 + * sort(Xf + start, samples + start, end - start) + * + * if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: # <<<<<<<<<<<<<< + * features[f_j] = features[n_total_constants] + * features[n_total_constants] = current.feature + */ + __pyx_t_5 = (((__pyx_v_Xf[(__pyx_v_end - 1)]) <= ((__pyx_v_Xf[__pyx_v_start]) + __pyx_v_7sklearn_4tree_5_tree_FEATURE_THRESHOLD)) != 0); + if (__pyx_t_5) { -/* "sklearn/tree/_tree.pxd":53 - * cdef public int max_features - * cdef public int find_split_algorithm - * cdef public object random_state # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1167 + * + * if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: + * features[f_j] = features[n_total_constants] # <<<<<<<<<<<<<< + * features[n_total_constants] = current.feature * - * # Inner structures */ + (__pyx_v_features[__pyx_v_f_j]) = (__pyx_v_features[__pyx_v_n_total_constants]); -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_12random_state___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->random_state); - __pyx_r = __pyx_v_self->random_state; - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":1168 + * if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: + * features[f_j] = features[n_total_constants] + * features[n_total_constants] = current.feature # <<<<<<<<<<<<<< + * + * n_found_constants += 1 + */ + __pyx_t_2 = __pyx_v_current.feature; + (__pyx_v_features[__pyx_v_n_total_constants]) = __pyx_t_2; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1170 + * features[n_total_constants] = current.feature + * + * n_found_constants += 1 # <<<<<<<<<<<<<< + * n_total_constants += 1 + * + */ + __pyx_v_n_found_constants = (__pyx_v_n_found_constants + 1); -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_12random_state_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_12random_state_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_12random_state_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1171 + * + * n_found_constants += 1 + * n_total_constants += 1 # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_v_n_total_constants = (__pyx_v_n_total_constants + 1); + goto __pyx_L11; + } + /*else*/ { -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_12random_state_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__", 0); - __Pyx_INCREF(__pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - __Pyx_GOTREF(__pyx_v_self->random_state); - __Pyx_DECREF(__pyx_v_self->random_state); - __pyx_v_self->random_state = __pyx_v_value; + /* "sklearn/tree/_tree.pyx":1174 + * + * else: + * f_i -= 1 # <<<<<<<<<<<<<< + * features[f_i], features[f_j] = features[f_j], features[f_i] + * + */ + __pyx_v_f_i = (__pyx_v_f_i - 1); - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1175 + * else: + * f_i -= 1 + * features[f_i], features[f_j] = features[f_j], features[f_i] # <<<<<<<<<<<<<< + * + * # Evaluate all splits + */ + __pyx_t_2 = (__pyx_v_features[__pyx_v_f_j]); + __pyx_t_7 = (__pyx_v_features[__pyx_v_f_i]); + (__pyx_v_features[__pyx_v_f_i]) = __pyx_t_2; + (__pyx_v_features[__pyx_v_f_j]) = __pyx_t_7; -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_12random_state_5__del__(PyObject *__pyx_v_self); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_12random_state_5__del__(PyObject *__pyx_v_self) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__del__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_12random_state_4__del__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1178 + * + * # Evaluate all splits + * self.criterion.reset() # <<<<<<<<<<<<<< + * p = start + * + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->reset(__pyx_v_self->__pyx_base.__pyx_base.criterion); -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_12random_state_4__del__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__del__", 0); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->random_state); - __Pyx_DECREF(__pyx_v_self->random_state); - __pyx_v_self->random_state = Py_None; + /* "sklearn/tree/_tree.pyx":1179 + * # Evaluate all splits + * self.criterion.reset() + * p = start # <<<<<<<<<<<<<< + * + * while p < end: + */ + __pyx_v_p = __pyx_v_start; - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1181 + * p = start + * + * while p < end: # <<<<<<<<<<<<<< + * while (p + 1 < end and + * Xf[p + 1] <= Xf[p] + FEATURE_THRESHOLD): + */ + while (1) { + __pyx_t_5 = ((__pyx_v_p < __pyx_v_end) != 0); + if (!__pyx_t_5) break; -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10node_count___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1182 + * + * while p < end: + * while (p + 1 < end and # <<<<<<<<<<<<<< + * Xf[p + 1] <= Xf[p] + FEATURE_THRESHOLD): + * p += 1 + */ + while (1) { + __pyx_t_6 = (((__pyx_v_p + 1) < __pyx_v_end) != 0); + if (__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L16_bool_binop_done; + } -/* "sklearn/tree/_tree.pxd":56 + /* "sklearn/tree/_tree.pyx":1183 + * while p < end: + * while (p + 1 < end and + * Xf[p + 1] <= Xf[p] + FEATURE_THRESHOLD): # <<<<<<<<<<<<<< + * p += 1 * - * # Inner structures - * cdef public int node_count # <<<<<<<<<<<<<< - * cdef public int capacity - * cdef int* children_left */ + __pyx_t_6 = (((__pyx_v_Xf[(__pyx_v_p + 1)]) <= ((__pyx_v_Xf[__pyx_v_p]) + __pyx_v_7sklearn_4tree_5_tree_FEATURE_THRESHOLD)) != 0); + __pyx_t_5 = __pyx_t_6; + __pyx_L16_bool_binop_done:; + if (!__pyx_t_5) break; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10node_count___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->node_count); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":1184 + * while (p + 1 < end and + * Xf[p + 1] <= Xf[p] + FEATURE_THRESHOLD): + * p += 1 # <<<<<<<<<<<<<< + * + * # (p + 1 >= end) or (X[samples[p + 1], current.feature] > + */ + __pyx_v_p = (__pyx_v_p + 1); + } - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.node_count.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1188 + * # (p + 1 >= end) or (X[samples[p + 1], current.feature] > + * # X[samples[p], current.feature]) + * p += 1 # <<<<<<<<<<<<<< + * # (p >= end) or (X[samples[p], current.feature] > + * # X[samples[p - 1], current.feature]) + */ + __pyx_v_p = (__pyx_v_p + 1); -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10node_count_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1192 + * # X[samples[p - 1], current.feature]) + * + * if p < end: # <<<<<<<<<<<<<< + * current.pos = p + * + */ + __pyx_t_5 = ((__pyx_v_p < __pyx_v_end) != 0); + if (__pyx_t_5) { -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_10node_count_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_value); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->node_count = __pyx_t_1; + /* "sklearn/tree/_tree.pyx":1193 + * + * if p < end: + * current.pos = p # <<<<<<<<<<<<<< + * + * # Reject if min_samples_leaf is not guaranteed + */ + __pyx_v_current.pos = __pyx_v_p; - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.node_count.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1196 + * + * # Reject if min_samples_leaf is not guaranteed + * if (((current.pos - start) < min_samples_leaf) or # <<<<<<<<<<<<<< + * ((end - current.pos) < min_samples_leaf)): + * continue + */ + __pyx_t_6 = (((__pyx_v_current.pos - __pyx_v_start) < __pyx_v_min_samples_leaf) != 0); + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L20_bool_binop_done; + } -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_8capacity___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1197 + * # Reject if min_samples_leaf is not guaranteed + * if (((current.pos - start) < min_samples_leaf) or + * ((end - current.pos) < min_samples_leaf)): # <<<<<<<<<<<<<< + * continue + * + */ + __pyx_t_6 = (((__pyx_v_end - __pyx_v_current.pos) < __pyx_v_min_samples_leaf) != 0); + __pyx_t_5 = __pyx_t_6; + __pyx_L20_bool_binop_done:; + if (__pyx_t_5) { -/* "sklearn/tree/_tree.pxd":57 - * # Inner structures - * cdef public int node_count - * cdef public int capacity # <<<<<<<<<<<<<< - * cdef int* children_left - * cdef int* children_right + /* "sklearn/tree/_tree.pyx":1198 + * if (((current.pos - start) < min_samples_leaf) or + * ((end - current.pos) < min_samples_leaf)): + * continue # <<<<<<<<<<<<<< + * + * self.criterion.update(current.pos) */ + goto __pyx_L12_continue; + } -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_8capacity___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->capacity); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":1200 + * continue + * + * self.criterion.update(current.pos) # <<<<<<<<<<<<<< + * + * # Reject if min_weight_leaf is not satisfied + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->update(__pyx_v_self->__pyx_base.__pyx_base.criterion, __pyx_v_current.pos); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.Tree.capacity.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_8capacity_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_8capacity_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__set__", 0); - __pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_value); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->capacity = __pyx_t_1; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.Tree.capacity.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/tree/_tree.pyx":936 - * """Interface for splitting criteria (regression and classification).""" + /* "sklearn/tree/_tree.pyx":1203 * - * cdef void init(self, DOUBLE_t* y, int y_stride, BOOL_t* # <<<<<<<<<<<<<< - * sample_mask, int n_samples, int n_total_samples): - * """Initialise the criterion.""" + * # Reject if min_weight_leaf is not satisfied + * if ((self.criterion.weighted_n_left < min_weight_leaf) or # <<<<<<<<<<<<<< + * (self.criterion.weighted_n_right < min_weight_leaf)): + * continue */ + __pyx_t_6 = ((__pyx_v_self->__pyx_base.__pyx_base.criterion->weighted_n_left < __pyx_v_min_weight_leaf) != 0); + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L23_bool_binop_done; + } -static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_init(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, CYTHON_UNUSED int __pyx_v_y_stride, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_BOOL_t *__pyx_v_sample_mask, CYTHON_UNUSED int __pyx_v_n_samples, CYTHON_UNUSED int __pyx_v_n_total_samples) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("init", 0); - - __Pyx_RefNannyFinishContext(); -} - -/* "sklearn/tree/_tree.pyx":941 - * pass + /* "sklearn/tree/_tree.pyx":1204 + * # Reject if min_weight_leaf is not satisfied + * if ((self.criterion.weighted_n_left < min_weight_leaf) or + * (self.criterion.weighted_n_right < min_weight_leaf)): # <<<<<<<<<<<<<< + * continue * - * cdef void reset(self): # <<<<<<<<<<<<<< - * """Reset the criterion for a new feature index.""" - * pass */ + __pyx_t_6 = ((__pyx_v_self->__pyx_base.__pyx_base.criterion->weighted_n_right < __pyx_v_min_weight_leaf) != 0); + __pyx_t_5 = __pyx_t_6; + __pyx_L23_bool_binop_done:; + if (__pyx_t_5) { -static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_reset(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("reset", 0); - - __Pyx_RefNannyFinishContext(); -} - -/* "sklearn/tree/_tree.pyx":945 - * pass + /* "sklearn/tree/_tree.pyx":1205 + * if ((self.criterion.weighted_n_left < min_weight_leaf) or + * (self.criterion.weighted_n_right < min_weight_leaf)): + * continue # <<<<<<<<<<<<<< * - * cdef int update(self, int a, int b, DOUBLE_t* y, int y_stride, # <<<<<<<<<<<<<< - * int* X_argsorted_i, BOOL_t* sample_mask): - * """Update the criteria for each value in interval [a,b) (where a and b + * current.improvement = self.criterion.impurity_improvement(impurity) */ + goto __pyx_L12_continue; + } -static int __pyx_f_7sklearn_4tree_5_tree_9Criterion_update(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, CYTHON_UNUSED int __pyx_v_a, CYTHON_UNUSED int __pyx_v_b, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, CYTHON_UNUSED int __pyx_v_y_stride, CYTHON_UNUSED int *__pyx_v_X_argsorted_i, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_BOOL_t *__pyx_v_sample_mask) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("update", 0); - - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/tree/_tree.pyx":951 - * pass + /* "sklearn/tree/_tree.pyx":1207 + * continue * - * cdef double eval(self): # <<<<<<<<<<<<<< - * """Evaluate the criteria (aka the split error).""" - * pass + * current.improvement = self.criterion.impurity_improvement(impurity) # <<<<<<<<<<<<<< + * + * if current.improvement > best.improvement: */ + __pyx_v_current.improvement = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->impurity_improvement(__pyx_v_self->__pyx_base.__pyx_base.criterion, __pyx_v_impurity); -static double __pyx_f_7sklearn_4tree_5_tree_9Criterion_eval(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self) { - double __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("eval", 0); + /* "sklearn/tree/_tree.pyx":1209 + * current.improvement = self.criterion.impurity_improvement(impurity) + * + * if current.improvement > best.improvement: # <<<<<<<<<<<<<< + * self.criterion.children_impurity(¤t.impurity_left, + * ¤t.impurity_right) + */ + __pyx_t_5 = ((__pyx_v_current.improvement > __pyx_v_best.improvement) != 0); + if (__pyx_t_5) { - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1210 + * + * if current.improvement > best.improvement: + * self.criterion.children_impurity(¤t.impurity_left, # <<<<<<<<<<<<<< + * ¤t.impurity_right) + * current.threshold = (Xf[p - 1] + Xf[p]) / 2.0 + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->children_impurity(__pyx_v_self->__pyx_base.__pyx_base.criterion, (&__pyx_v_current.impurity_left), (&__pyx_v_current.impurity_right)); -/* "sklearn/tree/_tree.pyx":955 - * pass + /* "sklearn/tree/_tree.pyx":1212 + * self.criterion.children_impurity(¤t.impurity_left, + * ¤t.impurity_right) + * current.threshold = (Xf[p - 1] + Xf[p]) / 2.0 # <<<<<<<<<<<<<< * - * cdef void init_value(self, double* buffer_value): # <<<<<<<<<<<<<< - * """Get the initial value of the criterion (`init` must be called - * before).""" + * if current.threshold == Xf[p]: */ + __pyx_v_current.threshold = (((__pyx_v_Xf[(__pyx_v_p - 1)]) + (__pyx_v_Xf[__pyx_v_p])) / 2.0); -static void __pyx_f_7sklearn_4tree_5_tree_9Criterion_init_value(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_self, CYTHON_UNUSED double *__pyx_v_buffer_value) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("init_value", 0); + /* "sklearn/tree/_tree.pyx":1214 + * current.threshold = (Xf[p - 1] + Xf[p]) / 2.0 + * + * if current.threshold == Xf[p]: # <<<<<<<<<<<<<< + * current.threshold = Xf[p - 1] + * + */ + __pyx_t_5 = ((__pyx_v_current.threshold == (__pyx_v_Xf[__pyx_v_p])) != 0); + if (__pyx_t_5) { - __Pyx_RefNannyFinishContext(); -} + /* "sklearn/tree/_tree.pyx":1215 + * + * if current.threshold == Xf[p]: + * current.threshold = Xf[p - 1] # <<<<<<<<<<<<<< + * + * best = current # copy + */ + __pyx_v_current.threshold = (__pyx_v_Xf[(__pyx_v_p - 1)]); + goto __pyx_L26; + } + __pyx_L26:; -/* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - int __pyx_v_n_outputs; - PyObject *__pyx_v_n_classes = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_outputs,&__pyx_n_s__n_classes,0}; - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_outputs)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_classes)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1014; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + /* "sklearn/tree/_tree.pyx":1217 + * current.threshold = Xf[p - 1] + * + * best = current # copy # <<<<<<<<<<<<<< + * + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + */ + __pyx_v_best = __pyx_v_current; + goto __pyx_L25; + } + __pyx_L25:; + goto __pyx_L18; + } + __pyx_L18:; + __pyx_L12_continue:; } } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1014; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + __pyx_L11:; } - __pyx_v_n_outputs = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_outputs == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1014; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_n_classes = values[1]; + __pyx_L8:; } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1014; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.tree._tree.ClassificationCriterion.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self), __pyx_v_n_outputs, __pyx_v_n_classes); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -/* "sklearn/tree/_tree.pyx":1014 - * cdef int n_right + /* "sklearn/tree/_tree.pyx":1220 * - * def __cinit__(self, int n_outputs, object n_classes): # <<<<<<<<<<<<<< - * """Constructor.""" - * cdef int k = 0 + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + * if best.pos < end: # <<<<<<<<<<<<<< + * partition_end = end + * p = start */ + __pyx_t_5 = ((__pyx_v_best.pos < __pyx_v_end) != 0); + if (__pyx_t_5) { -static int __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, int __pyx_v_n_outputs, PyObject *__pyx_v_n_classes) { - int __pyx_v_k; - int __pyx_v_label_count_stride; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); + /* "sklearn/tree/_tree.pyx":1221 + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + * if best.pos < end: + * partition_end = end # <<<<<<<<<<<<<< + * p = start + * + */ + __pyx_v_partition_end = __pyx_v_end; - /* "sklearn/tree/_tree.pyx":1016 - * def __cinit__(self, int n_outputs, object n_classes): - * """Constructor.""" - * cdef int k = 0 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1222 + * if best.pos < end: + * partition_end = end + * p = start # <<<<<<<<<<<<<< * - * self.n_outputs = n_outputs + * while p < partition_end: */ - __pyx_v_k = 0; + __pyx_v_p = __pyx_v_start; - /* "sklearn/tree/_tree.pyx":1018 - * cdef int k = 0 + /* "sklearn/tree/_tree.pyx":1224 + * p = start * - * self.n_outputs = n_outputs # <<<<<<<<<<<<<< - * self.n_samples = 0 - * self.n_left = 0 + * while p < partition_end: # <<<<<<<<<<<<<< + * if X[X_sample_stride * samples[p] + + * X_fx_stride * best.feature] <= best.threshold: */ - __pyx_v_self->n_outputs = __pyx_v_n_outputs; + while (1) { + __pyx_t_5 = ((__pyx_v_p < __pyx_v_partition_end) != 0); + if (!__pyx_t_5) break; - /* "sklearn/tree/_tree.pyx":1019 + /* "sklearn/tree/_tree.pyx":1226 + * while p < partition_end: + * if X[X_sample_stride * samples[p] + + * X_fx_stride * best.feature] <= best.threshold: # <<<<<<<<<<<<<< + * p += 1 * - * self.n_outputs = n_outputs - * self.n_samples = 0 # <<<<<<<<<<<<<< - * self.n_left = 0 - * self.n_right = 0 */ - __pyx_v_self->n_samples = 0; + __pyx_t_5 = (((__pyx_v_X[((__pyx_v_X_sample_stride * (__pyx_v_samples[__pyx_v_p])) + (__pyx_v_X_fx_stride * __pyx_v_best.feature))]) <= __pyx_v_best.threshold) != 0); + if (__pyx_t_5) { - /* "sklearn/tree/_tree.pyx":1020 - * self.n_outputs = n_outputs - * self.n_samples = 0 - * self.n_left = 0 # <<<<<<<<<<<<<< - * self.n_right = 0 + /* "sklearn/tree/_tree.pyx":1227 + * if X[X_sample_stride * samples[p] + + * X_fx_stride * best.feature] <= best.threshold: + * p += 1 # <<<<<<<<<<<<<< * + * else: */ - __pyx_v_self->n_left = 0; + __pyx_v_p = (__pyx_v_p + 1); + goto __pyx_L30; + } + /*else*/ { - /* "sklearn/tree/_tree.pyx":1021 - * self.n_samples = 0 - * self.n_left = 0 - * self.n_right = 0 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1230 * - * self.n_classes = malloc(n_outputs * sizeof(int)) + * else: + * partition_end -= 1 # <<<<<<<<<<<<<< + * + * tmp = samples[partition_end] */ - __pyx_v_self->n_right = 0; + __pyx_v_partition_end = (__pyx_v_partition_end - 1); - /* "sklearn/tree/_tree.pyx":1023 - * self.n_right = 0 + /* "sklearn/tree/_tree.pyx":1232 + * partition_end -= 1 * - * self.n_classes = malloc(n_outputs * sizeof(int)) # <<<<<<<<<<<<<< - * if self.n_classes == NULL: - * raise MemoryError() + * tmp = samples[partition_end] # <<<<<<<<<<<<<< + * samples[partition_end] = samples[p] + * samples[p] = tmp */ - __pyx_v_self->n_classes = ((int *)malloc((__pyx_v_n_outputs * (sizeof(int))))); + __pyx_v_tmp = (__pyx_v_samples[__pyx_v_partition_end]); - /* "sklearn/tree/_tree.pyx":1024 + /* "sklearn/tree/_tree.pyx":1233 * - * self.n_classes = malloc(n_outputs * sizeof(int)) - * if self.n_classes == NULL: # <<<<<<<<<<<<<< - * raise MemoryError() + * tmp = samples[partition_end] + * samples[partition_end] = samples[p] # <<<<<<<<<<<<<< + * samples[p] = tmp * */ - __pyx_t_1 = (__pyx_v_self->n_classes == NULL); - if (__pyx_t_1) { + (__pyx_v_samples[__pyx_v_partition_end]) = (__pyx_v_samples[__pyx_v_p]); - /* "sklearn/tree/_tree.pyx":1025 - * self.n_classes = malloc(n_outputs * sizeof(int)) - * if self.n_classes == NULL: - * raise MemoryError() # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1234 + * tmp = samples[partition_end] + * samples[partition_end] = samples[p] + * samples[p] = tmp # <<<<<<<<<<<<<< * - * cdef int label_count_stride = -1 + * # Respect invariant for constant features: the original order of */ - PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1025; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; + (__pyx_v_samples[__pyx_v_p]) = __pyx_v_tmp; + } + __pyx_L30:; + } + goto __pyx_L27; } - __pyx_L3:; + __pyx_L27:; - /* "sklearn/tree/_tree.pyx":1027 - * raise MemoryError() + /* "sklearn/tree/_tree.pyx":1239 + * # element in features[:n_known_constants] must be preserved for sibling + * # and child nodes + * memcpy(features, constant_features, sizeof(SIZE_t) * n_known_constants) # <<<<<<<<<<<<<< * - * cdef int label_count_stride = -1 # <<<<<<<<<<<<<< + * # Copy newly found constant features + */ + memcpy(__pyx_v_features, __pyx_v_constant_features, ((sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)) * __pyx_v_n_known_constants)); + + /* "sklearn/tree/_tree.pyx":1242 * - * for k from 0 <= k < n_outputs: + * # Copy newly found constant features + * memcpy(constant_features + n_known_constants, # <<<<<<<<<<<<<< + * features + n_known_constants, + * sizeof(SIZE_t) * n_found_constants) */ - __pyx_v_label_count_stride = -1; + memcpy((__pyx_v_constant_features + __pyx_v_n_known_constants), (__pyx_v_features + __pyx_v_n_known_constants), ((sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)) * __pyx_v_n_found_constants)); - /* "sklearn/tree/_tree.pyx":1029 - * cdef int label_count_stride = -1 + /* "sklearn/tree/_tree.pyx":1247 * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * self.n_classes[k] = n_classes[k] + * # Return values + * split[0] = best # <<<<<<<<<<<<<< + * n_constant_features[0] = n_total_constants * */ - __pyx_t_2 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_2; __pyx_v_k++) { + (__pyx_v_split[0]) = __pyx_v_best; - /* "sklearn/tree/_tree.pyx":1030 + /* "sklearn/tree/_tree.pyx":1248 + * # Return values + * split[0] = best + * n_constant_features[0] = n_total_constants # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: - * self.n_classes[k] = n_classes[k] # <<<<<<<<<<<<<< * - * if n_classes[k] > label_count_stride: */ - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_n_classes, __pyx_v_k, sizeof(int), PyInt_FromLong); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyInt_AsInt(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1030; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - (__pyx_v_self->n_classes[__pyx_v_k]) = __pyx_t_4; + (__pyx_v_n_constant_features[0]) = __pyx_v_n_total_constants; - /* "sklearn/tree/_tree.pyx":1032 - * self.n_classes[k] = n_classes[k] + /* "sklearn/tree/_tree.pyx":1071 + * self.random_state), self.__getstate__()) * - * if n_classes[k] > label_count_stride: # <<<<<<<<<<<<<< - * label_count_stride = n_classes[k] + * cdef void node_split(self, double impurity, SplitRecord* split, # <<<<<<<<<<<<<< + * SIZE_t* n_constant_features) nogil: + * """Find the best split on node samples[start:end].""" + */ + + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":1253 + * # Sort n-element arrays pointed to by Xf and samples, simultaneously, + * # by the values in Xf. Algorithm: Introsort (Musser, SP&E, 1997). + * cdef inline void sort(DTYPE_t* Xf, SIZE_t* samples, SIZE_t n) nogil: # <<<<<<<<<<<<<< + * cdef int maxd = 2 * log(n) + * introsort(Xf, samples, n, maxd) + */ + +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_sort(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n) { + int __pyx_v_maxd; + + /* "sklearn/tree/_tree.pyx":1254 + * # by the values in Xf. Algorithm: Introsort (Musser, SP&E, 1997). + * cdef inline void sort(DTYPE_t* Xf, SIZE_t* samples, SIZE_t n) nogil: + * cdef int maxd = 2 * log(n) # <<<<<<<<<<<<<< + * introsort(Xf, samples, n, maxd) * */ - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_n_classes, __pyx_v_k, sizeof(int), PyInt_FromLong); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1032; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyInt_FromLong(__pyx_v_label_count_stride); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1032; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_RichCompare(__pyx_t_3, __pyx_t_5, Py_GT); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1032; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1032; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (__pyx_t_1) { + __pyx_v_maxd = (2 * ((int)__pyx_f_7sklearn_4tree_5_tree_log(__pyx_v_n))); - /* "sklearn/tree/_tree.pyx":1033 + /* "sklearn/tree/_tree.pyx":1255 + * cdef inline void sort(DTYPE_t* Xf, SIZE_t* samples, SIZE_t n) nogil: + * cdef int maxd = 2 * log(n) + * introsort(Xf, samples, n, maxd) # <<<<<<<<<<<<<< * - * if n_classes[k] > label_count_stride: - * label_count_stride = n_classes[k] # <<<<<<<<<<<<<< * - * self.label_count_stride = label_count_stride */ - __pyx_t_6 = __Pyx_GetItemInt(__pyx_v_n_classes, __pyx_v_k, sizeof(int), PyInt_FromLong); if (!__pyx_t_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1033; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_4 = __Pyx_PyInt_AsInt(__pyx_t_6); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1033; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_v_label_count_stride = __pyx_t_4; - goto __pyx_L6; - } - __pyx_L6:; - } + __pyx_f_7sklearn_4tree_5_tree_introsort(__pyx_v_Xf, __pyx_v_samples, __pyx_v_n, __pyx_v_maxd); - /* "sklearn/tree/_tree.pyx":1035 - * label_count_stride = n_classes[k] + /* "sklearn/tree/_tree.pyx":1253 + * # Sort n-element arrays pointed to by Xf and samples, simultaneously, + * # by the values in Xf. Algorithm: Introsort (Musser, SP&E, 1997). + * cdef inline void sort(DTYPE_t* Xf, SIZE_t* samples, SIZE_t n) nogil: # <<<<<<<<<<<<<< + * cdef int maxd = 2 * log(n) + * introsort(Xf, samples, n, maxd) + */ + + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":1258 * - * self.label_count_stride = label_count_stride # <<<<<<<<<<<<<< * - * # Allocate + * cdef inline void swap(DTYPE_t* Xf, SIZE_t* samples, SIZE_t i, SIZE_t j) nogil: # <<<<<<<<<<<<<< + * # Helper for sort + * Xf[i], Xf[j] = Xf[j], Xf[i] */ - __pyx_v_self->label_count_stride = __pyx_v_label_count_stride; - /* "sklearn/tree/_tree.pyx":1038 +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_swap(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_i, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_j) { + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_4; + + /* "sklearn/tree/_tree.pyx":1260 + * cdef inline void swap(DTYPE_t* Xf, SIZE_t* samples, SIZE_t i, SIZE_t j) nogil: + * # Helper for sort + * Xf[i], Xf[j] = Xf[j], Xf[i] # <<<<<<<<<<<<<< + * samples[i], samples[j] = samples[j], samples[i] * - * # Allocate - * self.label_count_left = calloc(n_outputs * label_count_stride, sizeof(int)) # <<<<<<<<<<<<<< - * self.label_count_right = calloc(n_outputs * label_count_stride, sizeof(int)) - * self.label_count_init = calloc(n_outputs * label_count_stride, sizeof(int)) */ - __pyx_v_self->label_count_left = ((int *)calloc((__pyx_v_n_outputs * __pyx_v_label_count_stride), (sizeof(int)))); + __pyx_t_1 = (__pyx_v_Xf[__pyx_v_j]); + __pyx_t_2 = (__pyx_v_Xf[__pyx_v_i]); + (__pyx_v_Xf[__pyx_v_i]) = __pyx_t_1; + (__pyx_v_Xf[__pyx_v_j]) = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1039 - * # Allocate - * self.label_count_left = calloc(n_outputs * label_count_stride, sizeof(int)) - * self.label_count_right = calloc(n_outputs * label_count_stride, sizeof(int)) # <<<<<<<<<<<<<< - * self.label_count_init = calloc(n_outputs * label_count_stride, sizeof(int)) + /* "sklearn/tree/_tree.pyx":1261 + * # Helper for sort + * Xf[i], Xf[j] = Xf[j], Xf[i] + * samples[i], samples[j] = samples[j], samples[i] # <<<<<<<<<<<<<< + * * */ - __pyx_v_self->label_count_right = ((int *)calloc((__pyx_v_n_outputs * __pyx_v_label_count_stride), (sizeof(int)))); + __pyx_t_3 = (__pyx_v_samples[__pyx_v_j]); + __pyx_t_4 = (__pyx_v_samples[__pyx_v_i]); + (__pyx_v_samples[__pyx_v_i]) = __pyx_t_3; + (__pyx_v_samples[__pyx_v_j]) = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":1040 - * self.label_count_left = calloc(n_outputs * label_count_stride, sizeof(int)) - * self.label_count_right = calloc(n_outputs * label_count_stride, sizeof(int)) - * self.label_count_init = calloc(n_outputs * label_count_stride, sizeof(int)) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1258 * - * # Check for allocation errors + * + * cdef inline void swap(DTYPE_t* Xf, SIZE_t* samples, SIZE_t i, SIZE_t j) nogil: # <<<<<<<<<<<<<< + * # Helper for sort + * Xf[i], Xf[j] = Xf[j], Xf[i] */ - __pyx_v_self->label_count_init = ((int *)calloc((__pyx_v_n_outputs * __pyx_v_label_count_stride), (sizeof(int)))); - /* "sklearn/tree/_tree.pyx":1043 + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":1264 * - * # Check for allocation errors - * if self.label_count_left == NULL or \ # <<<<<<<<<<<<<< - * self.label_count_right == NULL or \ - * self.label_count_init == NULL: + * + * cdef inline DTYPE_t median3(DTYPE_t* Xf, SIZE_t n) nogil: # <<<<<<<<<<<<<< + * # Median of three pivot selection, after Bentley and McIlroy (1993). + * # Engineering a sort function. SP&E. Requires 8/3 comparisons on average. */ - __pyx_t_1 = (__pyx_v_self->label_count_left == NULL); - if (!__pyx_t_1) { - /* "sklearn/tree/_tree.pyx":1044 - * # Check for allocation errors - * if self.label_count_left == NULL or \ - * self.label_count_right == NULL or \ # <<<<<<<<<<<<<< - * self.label_count_init == NULL: - * free(self.n_classes) +static CYTHON_INLINE __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_f_7sklearn_4tree_5_tree_median3(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n) { + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_a; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_b; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_c; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_r; + int __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":1267 + * # 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 = Xf[0], b = Xf[n / 2], c = Xf[n - 1] # <<<<<<<<<<<<<< + * if a < b: + * if b < c: + */ + __pyx_v_a = (__pyx_v_Xf[0]); + __pyx_v_b = (__pyx_v_Xf[(__pyx_v_n / 2)]); + __pyx_v_c = (__pyx_v_Xf[(__pyx_v_n - 1)]); + + /* "sklearn/tree/_tree.pyx":1268 + * # Engineering a sort function. SP&E. Requires 8/3 comparisons on average. + * cdef DTYPE_t a = Xf[0], b = Xf[n / 2], c = Xf[n - 1] + * if a < b: # <<<<<<<<<<<<<< + * if b < c: + * return b + */ + __pyx_t_1 = ((__pyx_v_a < __pyx_v_b) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":1269 + * cdef DTYPE_t a = Xf[0], b = Xf[n / 2], c = Xf[n - 1] + * if a < b: + * if b < c: # <<<<<<<<<<<<<< + * return b + * elif a < c: */ - __pyx_t_7 = (__pyx_v_self->label_count_right == NULL); - if (!__pyx_t_7) { + __pyx_t_1 = ((__pyx_v_b < __pyx_v_c) != 0); + if (__pyx_t_1) { - /* "sklearn/tree/_tree.pyx":1045 - * if self.label_count_left == NULL or \ - * self.label_count_right == NULL or \ - * self.label_count_init == NULL: # <<<<<<<<<<<<<< - * free(self.n_classes) - * free(self.label_count_left) + /* "sklearn/tree/_tree.pyx":1270 + * if a < b: + * if b < c: + * return b # <<<<<<<<<<<<<< + * elif a < c: + * return c */ - __pyx_t_8 = (__pyx_v_self->label_count_init == NULL); - __pyx_t_9 = __pyx_t_8; - } else { - __pyx_t_9 = __pyx_t_7; + __pyx_r = __pyx_v_b; + goto __pyx_L0; } - __pyx_t_7 = __pyx_t_9; - } else { - __pyx_t_7 = __pyx_t_1; - } - if (__pyx_t_7) { - /* "sklearn/tree/_tree.pyx":1046 - * self.label_count_right == NULL or \ - * self.label_count_init == NULL: - * free(self.n_classes) # <<<<<<<<<<<<<< - * free(self.label_count_left) - * free(self.label_count_right) - */ - free(__pyx_v_self->n_classes); - - /* "sklearn/tree/_tree.pyx":1047 - * self.label_count_init == NULL: - * free(self.n_classes) - * free(self.label_count_left) # <<<<<<<<<<<<<< - * free(self.label_count_right) - * free(self.label_count_init) - */ - free(__pyx_v_self->label_count_left); - - /* "sklearn/tree/_tree.pyx":1048 - * free(self.n_classes) - * free(self.label_count_left) - * free(self.label_count_right) # <<<<<<<<<<<<<< - * free(self.label_count_init) - * raise MemoryError() + /* "sklearn/tree/_tree.pyx":1271 + * if b < c: + * return b + * elif a < c: # <<<<<<<<<<<<<< + * return c + * else: */ - free(__pyx_v_self->label_count_right); + __pyx_t_1 = ((__pyx_v_a < __pyx_v_c) != 0); + if (__pyx_t_1) { - /* "sklearn/tree/_tree.pyx":1049 - * free(self.label_count_left) - * free(self.label_count_right) - * free(self.label_count_init) # <<<<<<<<<<<<<< - * raise MemoryError() - * + /* "sklearn/tree/_tree.pyx":1272 + * return b + * elif a < c: + * return c # <<<<<<<<<<<<<< + * else: + * return a */ - free(__pyx_v_self->label_count_init); + __pyx_r = __pyx_v_c; + goto __pyx_L0; + } + /*else*/ { - /* "sklearn/tree/_tree.pyx":1050 - * free(self.label_count_right) - * free(self.label_count_init) - * raise MemoryError() # <<<<<<<<<<<<<< - * - * def __dealloc__(self): + /* "sklearn/tree/_tree.pyx":1274 + * return c + * else: + * return a # <<<<<<<<<<<<<< + * elif b < c: + * if a < c: */ - PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + __pyx_r = __pyx_v_a; + goto __pyx_L0; + } } - __pyx_L7:; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("sklearn.tree._tree.ClassificationCriterion.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static void __pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_3__dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_2__dealloc__(((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); -} -/* "sklearn/tree/_tree.pyx":1052 - * raise MemoryError() - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * """Destructor.""" - * free(self.n_classes) + /* "sklearn/tree/_tree.pyx":1275 + * else: + * return a + * elif b < c: # <<<<<<<<<<<<<< + * if a < c: + * return a */ + __pyx_t_1 = ((__pyx_v_b < __pyx_v_c) != 0); + if (__pyx_t_1) { -static void __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__", 0); + /* "sklearn/tree/_tree.pyx":1276 + * return a + * elif b < c: + * if a < c: # <<<<<<<<<<<<<< + * return a + * else: + */ + __pyx_t_1 = ((__pyx_v_a < __pyx_v_c) != 0); + if (__pyx_t_1) { - /* "sklearn/tree/_tree.pyx":1054 - * def __dealloc__(self): - * """Destructor.""" - * free(self.n_classes) # <<<<<<<<<<<<<< - * free(self.label_count_left) - * free(self.label_count_right) + /* "sklearn/tree/_tree.pyx":1277 + * elif b < c: + * if a < c: + * return a # <<<<<<<<<<<<<< + * else: + * return c */ - free(__pyx_v_self->n_classes); + __pyx_r = __pyx_v_a; + goto __pyx_L0; + } + /*else*/ { - /* "sklearn/tree/_tree.pyx":1055 - * """Destructor.""" - * free(self.n_classes) - * free(self.label_count_left) # <<<<<<<<<<<<<< - * free(self.label_count_right) - * free(self.label_count_init) + /* "sklearn/tree/_tree.pyx":1279 + * return a + * else: + * return c # <<<<<<<<<<<<<< + * else: + * return b */ - free(__pyx_v_self->label_count_left); + __pyx_r = __pyx_v_c; + goto __pyx_L0; + } + } + /*else*/ { - /* "sklearn/tree/_tree.pyx":1056 - * free(self.n_classes) - * free(self.label_count_left) - * free(self.label_count_right) # <<<<<<<<<<<<<< - * free(self.label_count_init) + /* "sklearn/tree/_tree.pyx":1281 + * return c + * else: + * return b # <<<<<<<<<<<<<< + * * */ - free(__pyx_v_self->label_count_right); + __pyx_r = __pyx_v_b; + goto __pyx_L0; + } - /* "sklearn/tree/_tree.pyx":1057 - * free(self.label_count_left) - * free(self.label_count_right) - * free(self.label_count_init) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1264 * - * def __reduce__(self): + * + * cdef inline DTYPE_t median3(DTYPE_t* Xf, SIZE_t n) nogil: # <<<<<<<<<<<<<< + * # Median of three pivot selection, after Bentley and McIlroy (1993). + * # Engineering a sort function. SP&E. Requires 8/3 comparisons on average. */ - free(__pyx_v_self->label_count_init); - - __Pyx_RefNannyFinishContext(); -} -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_4__reduce__(((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); + /* function exit code */ + __pyx_L0:; return __pyx_r; } -/* "sklearn/tree/_tree.pyx":1059 - * free(self.label_count_init) - * - * def __reduce__(self): # <<<<<<<<<<<<<< - * return (ClassificationCriterion, - * (self.n_outputs, intp_to_ndarray(self.n_classes, +/* "sklearn/tree/_tree.pyx":1286 + * # 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* Xf, SIZE_t *samples, SIZE_t n, int maxd) nogil: # <<<<<<<<<<<<<< + * cdef DTYPE_t pivot + * cdef SIZE_t i, l, r */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce__", 0); +static void __pyx_f_7sklearn_4tree_5_tree_introsort(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n, int __pyx_v_maxd) { + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_pivot; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_l; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_r; + int __pyx_t_1; - /* "sklearn/tree/_tree.pyx":1060 + /* "sklearn/tree/_tree.pyx":1290 + * cdef SIZE_t i, l, r * - * def __reduce__(self): - * return (ClassificationCriterion, # <<<<<<<<<<<<<< - * (self.n_outputs, intp_to_ndarray(self.n_classes, - * self.n_outputs)), + * while n > 1: # <<<<<<<<<<<<<< + * if maxd <= 0: # max depth limit exceeded ("gone quadratic") + * heapsort(Xf, samples, n) */ - __Pyx_XDECREF(__pyx_r); + while (1) { + __pyx_t_1 = ((__pyx_v_n > 1) != 0); + if (!__pyx_t_1) break; - /* "sklearn/tree/_tree.pyx":1061 - * def __reduce__(self): - * return (ClassificationCriterion, - * (self.n_outputs, intp_to_ndarray(self.n_classes, # <<<<<<<<<<<<<< - * self.n_outputs)), - * self.__getstate__()) + /* "sklearn/tree/_tree.pyx":1291 + * + * while n > 1: + * if maxd <= 0: # max depth limit exceeded ("gone quadratic") # <<<<<<<<<<<<<< + * heapsort(Xf, samples, n) + * return */ - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->n_outputs); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __pyx_t_1 = ((__pyx_v_maxd <= 0) != 0); + if (__pyx_t_1) { - /* "sklearn/tree/_tree.pyx":1062 - * return (ClassificationCriterion, - * (self.n_outputs, intp_to_ndarray(self.n_classes, - * self.n_outputs)), # <<<<<<<<<<<<<< - * self.__getstate__()) - * + /* "sklearn/tree/_tree.pyx":1292 + * while n > 1: + * if maxd <= 0: # max depth limit exceeded ("gone quadratic") + * heapsort(Xf, samples, n) # <<<<<<<<<<<<<< + * return + * maxd -= 1 */ - __pyx_t_2 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(__pyx_v_self->n_classes, __pyx_v_self->n_outputs)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; + __pyx_f_7sklearn_4tree_5_tree_heapsort(__pyx_v_Xf, __pyx_v_samples, __pyx_v_n); - /* "sklearn/tree/_tree.pyx":1063 - * (self.n_outputs, intp_to_ndarray(self.n_classes, - * self.n_outputs)), - * self.__getstate__()) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1293 + * if maxd <= 0: # max depth limit exceeded ("gone quadratic") + * heapsort(Xf, samples, n) + * return # <<<<<<<<<<<<<< + * maxd -= 1 * - * def __getstate__(self): */ - __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s____getstate__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1063; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1063; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion))); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion))); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_t_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_3 = 0; - __pyx_t_1 = 0; - __pyx_r = ((PyObject *)__pyx_t_2); - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("sklearn.tree._tree.ClassificationCriterion.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getstate__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_6__getstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + goto __pyx_L0; + } -/* "sklearn/tree/_tree.pyx":1065 - * self.__getstate__()) - * - * def __getstate__(self): # <<<<<<<<<<<<<< - * return {} + /* "sklearn/tree/_tree.pyx":1294 + * heapsort(Xf, samples, n) + * return + * maxd -= 1 # <<<<<<<<<<<<<< * + * pivot = median3(Xf, n) */ + __pyx_v_maxd = (__pyx_v_maxd - 1); -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_6__getstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getstate__", 0); - - /* "sklearn/tree/_tree.pyx":1066 + /* "sklearn/tree/_tree.pyx":1296 + * maxd -= 1 * - * def __getstate__(self): - * return {} # <<<<<<<<<<<<<< + * pivot = median3(Xf, n) # <<<<<<<<<<<<<< * - * def __setstate__(self, d): + * # Three-way partition. */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1066; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_r = ((PyObject *)__pyx_t_1); - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.ClassificationCriterion.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_v_pivot = __pyx_f_7sklearn_4tree_5_tree_median3(__pyx_v_Xf, __pyx_v_n); -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_8__setstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self), ((PyObject *)__pyx_v_d)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/tree/_tree.pyx":1068 - * return {} - * - * def __setstate__(self, d): # <<<<<<<<<<<<<< - * pass + /* "sklearn/tree/_tree.pyx":1299 * + * # Three-way partition. + * i = l = 0 # <<<<<<<<<<<<<< + * r = n + * while i < r: */ + __pyx_v_i = 0; + __pyx_v_l = 0; -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_23ClassificationCriterion_8__setstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_d) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate__", 0); + /* "sklearn/tree/_tree.pyx":1300 + * # Three-way partition. + * i = l = 0 + * r = n # <<<<<<<<<<<<<< + * while i < r: + * if Xf[i] < pivot: + */ + __pyx_v_r = __pyx_v_n; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1301 + * i = l = 0 + * r = n + * while i < r: # <<<<<<<<<<<<<< + * if Xf[i] < pivot: + * swap(Xf, samples, i, l) + */ + while (1) { + __pyx_t_1 = ((__pyx_v_i < __pyx_v_r) != 0); + if (!__pyx_t_1) break; -/* "sklearn/tree/_tree.pyx":1071 - * pass - * - * cdef void init(self, DOUBLE_t* y, int y_stride, BOOL_t *sample_mask, # <<<<<<<<<<<<<< - * int n_samples, int n_total_samples): - * """Initialise the criterion.""" + /* "sklearn/tree/_tree.pyx":1302 + * r = n + * while i < r: + * if Xf[i] < pivot: # <<<<<<<<<<<<<< + * swap(Xf, samples, i, l) + * i += 1 */ + __pyx_t_1 = (((__pyx_v_Xf[__pyx_v_i]) < __pyx_v_pivot) != 0); + if (__pyx_t_1) { -static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_init(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, int __pyx_v_y_stride, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *__pyx_v_sample_mask, int __pyx_v_n_samples, int __pyx_v_n_total_samples) { - int __pyx_v_n_outputs; - int *__pyx_v_n_classes; - int __pyx_v_label_count_stride; - int *__pyx_v_label_count_init; - int __pyx_v_k; - int __pyx_v_c; - int __pyx_v_j; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - __Pyx_RefNannySetupContext("init", 0); + /* "sklearn/tree/_tree.pyx":1303 + * while i < r: + * if Xf[i] < pivot: + * swap(Xf, samples, i, l) # <<<<<<<<<<<<<< + * i += 1 + * l += 1 + */ + __pyx_f_7sklearn_4tree_5_tree_swap(__pyx_v_Xf, __pyx_v_samples, __pyx_v_i, __pyx_v_l); - /* "sklearn/tree/_tree.pyx":1074 - * int n_samples, int n_total_samples): - * """Initialise the criterion.""" - * cdef int n_outputs = self.n_outputs # <<<<<<<<<<<<<< - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride + /* "sklearn/tree/_tree.pyx":1304 + * if Xf[i] < pivot: + * swap(Xf, samples, i, l) + * i += 1 # <<<<<<<<<<<<<< + * l += 1 + * elif Xf[i] > pivot: */ - __pyx_v_n_outputs = __pyx_v_self->n_outputs; + __pyx_v_i = (__pyx_v_i + 1); - /* "sklearn/tree/_tree.pyx":1075 - * """Initialise the criterion.""" - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes # <<<<<<<<<<<<<< - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_init = self.label_count_init + /* "sklearn/tree/_tree.pyx":1305 + * swap(Xf, samples, i, l) + * i += 1 + * l += 1 # <<<<<<<<<<<<<< + * elif Xf[i] > pivot: + * r -= 1 */ - __pyx_v_n_classes = __pyx_v_self->n_classes; + __pyx_v_l = (__pyx_v_l + 1); + goto __pyx_L8; + } - /* "sklearn/tree/_tree.pyx":1076 - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< - * cdef int* label_count_init = self.label_count_init - * + /* "sklearn/tree/_tree.pyx":1306 + * i += 1 + * l += 1 + * elif Xf[i] > pivot: # <<<<<<<<<<<<<< + * r -= 1 + * swap(Xf, samples, i, r) */ - __pyx_v_label_count_stride = __pyx_v_self->label_count_stride; + __pyx_t_1 = (((__pyx_v_Xf[__pyx_v_i]) > __pyx_v_pivot) != 0); + if (__pyx_t_1) { - /* "sklearn/tree/_tree.pyx":1077 - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_init = self.label_count_init # <<<<<<<<<<<<<< - * - * cdef int k = 0 + /* "sklearn/tree/_tree.pyx":1307 + * l += 1 + * elif Xf[i] > pivot: + * r -= 1 # <<<<<<<<<<<<<< + * swap(Xf, samples, i, r) + * else: */ - __pyx_v_label_count_init = __pyx_v_self->label_count_init; + __pyx_v_r = (__pyx_v_r - 1); - /* "sklearn/tree/_tree.pyx":1079 - * cdef int* label_count_init = self.label_count_init + /* "sklearn/tree/_tree.pyx":1308 + * elif Xf[i] > pivot: + * r -= 1 + * swap(Xf, samples, i, r) # <<<<<<<<<<<<<< + * else: + * i += 1 + */ + __pyx_f_7sklearn_4tree_5_tree_swap(__pyx_v_Xf, __pyx_v_samples, __pyx_v_i, __pyx_v_r); + goto __pyx_L8; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":1310 + * swap(Xf, samples, i, r) + * else: + * i += 1 # <<<<<<<<<<<<<< * - * cdef int k = 0 # <<<<<<<<<<<<<< - * cdef int c = 0 - * cdef int j = 0 + * introsort(Xf, samples, l, maxd) */ - __pyx_v_k = 0; + __pyx_v_i = (__pyx_v_i + 1); + } + __pyx_L8:; + } - /* "sklearn/tree/_tree.pyx":1080 + /* "sklearn/tree/_tree.pyx":1312 + * i += 1 * - * cdef int k = 0 - * cdef int c = 0 # <<<<<<<<<<<<<< - * cdef int j = 0 + * introsort(Xf, samples, l, maxd) # <<<<<<<<<<<<<< + * Xf += r + * samples += r + */ + __pyx_f_7sklearn_4tree_5_tree_introsort(__pyx_v_Xf, __pyx_v_samples, __pyx_v_l, __pyx_v_maxd); + + /* "sklearn/tree/_tree.pyx":1313 * + * introsort(Xf, samples, l, maxd) + * Xf += r # <<<<<<<<<<<<<< + * samples += r + * n -= r */ - __pyx_v_c = 0; + __pyx_v_Xf = (__pyx_v_Xf + __pyx_v_r); - /* "sklearn/tree/_tree.pyx":1081 - * cdef int k = 0 - * cdef int c = 0 - * cdef int j = 0 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1314 + * introsort(Xf, samples, l, maxd) + * Xf += r + * samples += r # <<<<<<<<<<<<<< + * n -= r * - * self.n_samples = n_samples */ - __pyx_v_j = 0; + __pyx_v_samples = (__pyx_v_samples + __pyx_v_r); - /* "sklearn/tree/_tree.pyx":1083 - * cdef int j = 0 + /* "sklearn/tree/_tree.pyx":1315 + * Xf += r + * samples += r + * n -= r # <<<<<<<<<<<<<< * - * self.n_samples = n_samples # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: */ - __pyx_v_self->n_samples = __pyx_v_n_samples; + __pyx_v_n = (__pyx_v_n - __pyx_v_r); + } - /* "sklearn/tree/_tree.pyx":1085 - * self.n_samples = n_samples - * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * for c from 0 <= c < n_classes[k]: - * label_count_init[k * label_count_stride + c] = 0 + /* "sklearn/tree/_tree.pyx":1286 + * # 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* Xf, SIZE_t *samples, SIZE_t n, int maxd) nogil: # <<<<<<<<<<<<<< + * cdef DTYPE_t pivot + * cdef SIZE_t i, l, r */ - __pyx_t_1 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_1; __pyx_v_k++) { - /* "sklearn/tree/_tree.pyx":1086 + /* function exit code */ + __pyx_L0:; +} + +/* "sklearn/tree/_tree.pyx":1318 * - * for k from 0 <= k < n_outputs: - * for c from 0 <= c < n_classes[k]: # <<<<<<<<<<<<<< - * label_count_init[k * label_count_stride + c] = 0 * + * cdef inline void sift_down(DTYPE_t* Xf, SIZE_t* samples, # <<<<<<<<<<<<<< + * SIZE_t start, SIZE_t end) nogil: + * # Restore heap order in Xf[start:end] by moving the max element to start. */ - __pyx_t_2 = (__pyx_v_n_classes[__pyx_v_k]); - for (__pyx_v_c = 0; __pyx_v_c < __pyx_t_2; __pyx_v_c++) { - /* "sklearn/tree/_tree.pyx":1087 - * for k from 0 <= k < n_outputs: - * for c from 0 <= c < n_classes[k]: - * label_count_init[k * label_count_stride + c] = 0 # <<<<<<<<<<<<<< +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_sift_down(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_child; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_maxind; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_root; + int __pyx_t_1; + int __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":1323 + * cdef SIZE_t child, maxind, root * - * for j from 0 <= j < n_total_samples: + * root = start # <<<<<<<<<<<<<< + * while True: + * child = root * 2 + 1 */ - (__pyx_v_label_count_init[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]) = 0; - } - } + __pyx_v_root = __pyx_v_start; - /* "sklearn/tree/_tree.pyx":1089 - * label_count_init[k * label_count_stride + c] = 0 + /* "sklearn/tree/_tree.pyx":1324 + * + * root = start + * while True: # <<<<<<<<<<<<<< + * child = root * 2 + 1 * - * for j from 0 <= j < n_total_samples: # <<<<<<<<<<<<<< - * if sample_mask[j] == 0: - * continue */ - __pyx_t_1 = __pyx_v_n_total_samples; - for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_1; __pyx_v_j++) { + while (1) { - /* "sklearn/tree/_tree.pyx":1090 + /* "sklearn/tree/_tree.pyx":1325 + * root = start + * while True: + * child = root * 2 + 1 # <<<<<<<<<<<<<< * - * for j from 0 <= j < n_total_samples: - * if sample_mask[j] == 0: # <<<<<<<<<<<<<< - * continue + * # find max of root, left child, right child + */ + __pyx_v_child = ((__pyx_v_root * 2) + 1); + + /* "sklearn/tree/_tree.pyx":1328 * + * # find max of root, left child, right child + * maxind = root # <<<<<<<<<<<<<< + * if child < end and Xf[maxind] < Xf[child]: + * maxind = child */ - __pyx_t_3 = ((__pyx_v_sample_mask[__pyx_v_j]) == 0); - if (__pyx_t_3) { + __pyx_v_maxind = __pyx_v_root; + + /* "sklearn/tree/_tree.pyx":1329 + * # find max of root, left child, right child + * maxind = root + * if child < end and Xf[maxind] < Xf[child]: # <<<<<<<<<<<<<< + * maxind = child + * if child + 1 < end and Xf[maxind] < Xf[child + 1]: + */ + __pyx_t_2 = ((__pyx_v_child < __pyx_v_end) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_2 = (((__pyx_v_Xf[__pyx_v_maxind]) < (__pyx_v_Xf[__pyx_v_child])) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L6_bool_binop_done:; + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":1330 + * maxind = root + * if child < end and Xf[maxind] < Xf[child]: + * maxind = child # <<<<<<<<<<<<<< + * if child + 1 < end and Xf[maxind] < Xf[child + 1]: + * maxind = child + 1 + */ + __pyx_v_maxind = __pyx_v_child; + goto __pyx_L5; + } + __pyx_L5:; + + /* "sklearn/tree/_tree.pyx":1331 + * if child < end and Xf[maxind] < Xf[child]: + * maxind = child + * if child + 1 < end and Xf[maxind] < Xf[child + 1]: # <<<<<<<<<<<<<< + * maxind = child + 1 + * + */ + __pyx_t_2 = (((__pyx_v_child + 1) < __pyx_v_end) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L9_bool_binop_done; + } + __pyx_t_2 = (((__pyx_v_Xf[__pyx_v_maxind]) < (__pyx_v_Xf[(__pyx_v_child + 1)])) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L9_bool_binop_done:; + if (__pyx_t_1) { - /* "sklearn/tree/_tree.pyx":1091 - * for j from 0 <= j < n_total_samples: - * if sample_mask[j] == 0: - * continue # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1332 + * maxind = child + * if child + 1 < end and Xf[maxind] < Xf[child + 1]: + * maxind = child + 1 # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: + * if maxind == root: */ - goto __pyx_L7_continue; - goto __pyx_L9; + __pyx_v_maxind = (__pyx_v_child + 1); + goto __pyx_L8; } - __pyx_L9:; + __pyx_L8:; - /* "sklearn/tree/_tree.pyx":1093 - * continue + /* "sklearn/tree/_tree.pyx":1334 + * maxind = child + 1 * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * c = y[j * y_stride + k] - * label_count_init[k * label_count_stride + c] += 1 + * if maxind == root: # <<<<<<<<<<<<<< + * break + * else: */ - __pyx_t_2 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_2; __pyx_v_k++) { + __pyx_t_1 = ((__pyx_v_maxind == __pyx_v_root) != 0); + if (__pyx_t_1) { - /* "sklearn/tree/_tree.pyx":1094 + /* "sklearn/tree/_tree.pyx":1335 * - * for k from 0 <= k < n_outputs: - * c = y[j * y_stride + k] # <<<<<<<<<<<<<< - * label_count_init[k * label_count_stride + c] += 1 + * if maxind == root: + * break # <<<<<<<<<<<<<< + * else: + * swap(Xf, samples, root, maxind) + */ + goto __pyx_L4_break; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":1337 + * break + * else: + * swap(Xf, samples, root, maxind) # <<<<<<<<<<<<<< + * root = maxind * */ - __pyx_v_c = ((int)(__pyx_v_y[((__pyx_v_j * __pyx_v_y_stride) + __pyx_v_k)])); + __pyx_f_7sklearn_4tree_5_tree_swap(__pyx_v_Xf, __pyx_v_samples, __pyx_v_root, __pyx_v_maxind); - /* "sklearn/tree/_tree.pyx":1095 - * for k from 0 <= k < n_outputs: - * c = y[j * y_stride + k] - * label_count_init[k * label_count_stride + c] += 1 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1338 + * else: + * swap(Xf, samples, root, maxind) + * root = maxind # <<<<<<<<<<<<<< + * * - * self.reset() */ - __pyx_t_4 = ((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c); - (__pyx_v_label_count_init[__pyx_t_4]) = ((__pyx_v_label_count_init[__pyx_t_4]) + 1); + __pyx_v_root = __pyx_v_maxind; } - __pyx_L7_continue:; } + __pyx_L4_break:; - /* "sklearn/tree/_tree.pyx":1097 - * label_count_init[k * label_count_stride + c] += 1 + /* "sklearn/tree/_tree.pyx":1318 * - * self.reset() # <<<<<<<<<<<<<< * - * cdef void reset(self): + * cdef inline void sift_down(DTYPE_t* Xf, SIZE_t* samples, # <<<<<<<<<<<<<< + * SIZE_t start, SIZE_t end) nogil: + * # Restore heap order in Xf[start:end] by moving the max element to start. */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.reset(((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); + /* function exit code */ } -/* "sklearn/tree/_tree.pyx":1099 - * self.reset() +/* "sklearn/tree/_tree.pyx":1341 + * + * + * cdef void heapsort(DTYPE_t* Xf, SIZE_t* samples, SIZE_t n) nogil: # <<<<<<<<<<<<<< + * cdef SIZE_t start, end * - * cdef void reset(self): # <<<<<<<<<<<<<< - * """Reset the criterion for a new feature index.""" - * cdef int n_outputs = self.n_outputs */ -static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_reset(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self) { - int __pyx_v_n_outputs; - int *__pyx_v_n_classes; - int __pyx_v_label_count_stride; - int *__pyx_v_label_count_init; - int *__pyx_v_label_count_left; - int *__pyx_v_label_count_right; - int __pyx_v_k; - int __pyx_v_c; - __Pyx_RefNannyDeclarations +static void __pyx_f_7sklearn_4tree_5_tree_heapsort(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end; int __pyx_t_1; - int __pyx_t_2; - __Pyx_RefNannySetupContext("reset", 0); - /* "sklearn/tree/_tree.pyx":1101 - * cdef void reset(self): - * """Reset the criterion for a new feature index.""" - * cdef int n_outputs = self.n_outputs # <<<<<<<<<<<<<< - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride + /* "sklearn/tree/_tree.pyx":1345 + * + * # heapify + * start = (n - 2) / 2 # <<<<<<<<<<<<<< + * end = n + * while True: */ - __pyx_v_n_outputs = __pyx_v_self->n_outputs; + __pyx_v_start = ((__pyx_v_n - 2) / 2); - /* "sklearn/tree/_tree.pyx":1102 - * """Reset the criterion for a new feature index.""" - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes # <<<<<<<<<<<<<< - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_init = self.label_count_init + /* "sklearn/tree/_tree.pyx":1346 + * # heapify + * start = (n - 2) / 2 + * end = n # <<<<<<<<<<<<<< + * while True: + * sift_down(Xf, samples, start, end) */ - __pyx_v_n_classes = __pyx_v_self->n_classes; + __pyx_v_end = __pyx_v_n; - /* "sklearn/tree/_tree.pyx":1103 - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< - * cdef int* label_count_init = self.label_count_init - * cdef int* label_count_left = self.label_count_left + /* "sklearn/tree/_tree.pyx":1347 + * start = (n - 2) / 2 + * end = n + * while True: # <<<<<<<<<<<<<< + * sift_down(Xf, samples, start, end) + * if start == 0: */ - __pyx_v_label_count_stride = __pyx_v_self->label_count_stride; + while (1) { - /* "sklearn/tree/_tree.pyx":1104 - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_init = self.label_count_init # <<<<<<<<<<<<<< - * cdef int* label_count_left = self.label_count_left - * cdef int* label_count_right = self.label_count_right + /* "sklearn/tree/_tree.pyx":1348 + * end = n + * while True: + * sift_down(Xf, samples, start, end) # <<<<<<<<<<<<<< + * if start == 0: + * break */ - __pyx_v_label_count_init = __pyx_v_self->label_count_init; + __pyx_f_7sklearn_4tree_5_tree_sift_down(__pyx_v_Xf, __pyx_v_samples, __pyx_v_start, __pyx_v_end); - /* "sklearn/tree/_tree.pyx":1105 - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_init = self.label_count_init - * cdef int* label_count_left = self.label_count_left # <<<<<<<<<<<<<< - * cdef int* label_count_right = self.label_count_right - * + /* "sklearn/tree/_tree.pyx":1349 + * while True: + * sift_down(Xf, samples, start, end) + * if start == 0: # <<<<<<<<<<<<<< + * break + * start -= 1 */ - __pyx_v_label_count_left = __pyx_v_self->label_count_left; + __pyx_t_1 = ((__pyx_v_start == 0) != 0); + if (__pyx_t_1) { - /* "sklearn/tree/_tree.pyx":1106 - * cdef int* label_count_init = self.label_count_init - * cdef int* label_count_left = self.label_count_left - * cdef int* label_count_right = self.label_count_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1350 + * sift_down(Xf, samples, start, end) + * if start == 0: + * break # <<<<<<<<<<<<<< + * start -= 1 * - * cdef int k = 0 */ - __pyx_v_label_count_right = __pyx_v_self->label_count_right; + goto __pyx_L4_break; + } - /* "sklearn/tree/_tree.pyx":1108 - * cdef int* label_count_right = self.label_count_right + /* "sklearn/tree/_tree.pyx":1351 + * if start == 0: + * break + * start -= 1 # <<<<<<<<<<<<<< * - * cdef int k = 0 # <<<<<<<<<<<<<< - * cdef int c = 0 - * self.n_left = 0 + * # sort by shrinking the heap, putting the max element immediately after it */ - __pyx_v_k = 0; + __pyx_v_start = (__pyx_v_start - 1); + } + __pyx_L4_break:; - /* "sklearn/tree/_tree.pyx":1109 + /* "sklearn/tree/_tree.pyx":1354 * - * cdef int k = 0 - * cdef int c = 0 # <<<<<<<<<<<<<< - * self.n_left = 0 - * self.n_right = self.n_samples + * # sort by shrinking the heap, putting the max element immediately after it + * end = n - 1 # <<<<<<<<<<<<<< + * while end > 0: + * swap(Xf, samples, 0, end) */ - __pyx_v_c = 0; + __pyx_v_end = (__pyx_v_n - 1); - /* "sklearn/tree/_tree.pyx":1110 - * cdef int k = 0 - * cdef int c = 0 - * self.n_left = 0 # <<<<<<<<<<<<<< - * self.n_right = self.n_samples - * + /* "sklearn/tree/_tree.pyx":1355 + * # sort by shrinking the heap, putting the max element immediately after it + * end = n - 1 + * while end > 0: # <<<<<<<<<<<<<< + * swap(Xf, samples, 0, end) + * sift_down(Xf, samples, 0, end) */ - __pyx_v_self->n_left = 0; + while (1) { + __pyx_t_1 = ((__pyx_v_end > 0) != 0); + if (!__pyx_t_1) break; - /* "sklearn/tree/_tree.pyx":1111 - * cdef int c = 0 - * self.n_left = 0 - * self.n_right = self.n_samples # <<<<<<<<<<<<<< - * - * for k from 0 <= k < n_outputs: + /* "sklearn/tree/_tree.pyx":1356 + * end = n - 1 + * while end > 0: + * swap(Xf, samples, 0, end) # <<<<<<<<<<<<<< + * sift_down(Xf, samples, 0, end) + * end = end - 1 */ - __pyx_v_self->n_right = __pyx_v_self->n_samples; + __pyx_f_7sklearn_4tree_5_tree_swap(__pyx_v_Xf, __pyx_v_samples, 0, __pyx_v_end); - /* "sklearn/tree/_tree.pyx":1113 - * self.n_right = self.n_samples + /* "sklearn/tree/_tree.pyx":1357 + * while end > 0: + * swap(Xf, samples, 0, end) + * sift_down(Xf, samples, 0, end) # <<<<<<<<<<<<<< + * end = end - 1 * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * for c from 0 <= c < n_classes[k]: - * # Reset left label counts to 0 */ - __pyx_t_1 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_1; __pyx_v_k++) { + __pyx_f_7sklearn_4tree_5_tree_sift_down(__pyx_v_Xf, __pyx_v_samples, 0, __pyx_v_end); - /* "sklearn/tree/_tree.pyx":1114 + /* "sklearn/tree/_tree.pyx":1358 + * swap(Xf, samples, 0, end) + * sift_down(Xf, samples, 0, end) + * end = end - 1 # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: - * for c from 0 <= c < n_classes[k]: # <<<<<<<<<<<<<< - * # Reset left label counts to 0 - * label_count_left[k * label_count_stride + c] = 0 - */ - __pyx_t_2 = (__pyx_v_n_classes[__pyx_v_k]); - for (__pyx_v_c = 0; __pyx_v_c < __pyx_t_2; __pyx_v_c++) { - - /* "sklearn/tree/_tree.pyx":1116 - * for c from 0 <= c < n_classes[k]: - * # Reset left label counts to 0 - * label_count_left[k * label_count_stride + c] = 0 # <<<<<<<<<<<<<< * - * # Reset right label counts to the initial counts */ - (__pyx_v_label_count_left[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]) = 0; + __pyx_v_end = (__pyx_v_end - 1); + } - /* "sklearn/tree/_tree.pyx":1119 + /* "sklearn/tree/_tree.pyx":1341 * - * # Reset right label counts to the initial counts - * label_count_right[k * label_count_stride + c] = label_count_init[k * label_count_stride + c] # <<<<<<<<<<<<<< * - * cdef int update(self, int a, int b, DOUBLE_t* y, int y_stride, + * cdef void heapsort(DTYPE_t* Xf, SIZE_t* samples, SIZE_t n) nogil: # <<<<<<<<<<<<<< + * cdef SIZE_t start, end + * */ - (__pyx_v_label_count_right[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]) = (__pyx_v_label_count_init[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]); - } - } - __Pyx_RefNannyFinishContext(); + /* function exit code */ } -/* "sklearn/tree/_tree.pyx":1121 - * label_count_right[k * label_count_stride + c] = label_count_init[k * label_count_stride + c] - * - * cdef int update(self, int a, int b, DOUBLE_t* y, int y_stride, # <<<<<<<<<<<<<< - * int* X_argsorted_i, BOOL_t* sample_mask): - * """Update the criteria for each value in interval [a,b) (where a and b +/* "sklearn/tree/_tree.pyx":1363 + * cdef class RandomSplitter(BaseDenseSplitter): + * """Splitter for finding the best random split.""" + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (RandomSplitter, (self.criterion, + * self.max_features, */ -static int __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_update(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, int __pyx_v_a, int __pyx_v_b, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, int __pyx_v_y_stride, int *__pyx_v_X_argsorted_i, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *__pyx_v_sample_mask) { - int __pyx_v_n_outputs; - int __pyx_v_label_count_stride; - int *__pyx_v_label_count_left; - int *__pyx_v_label_count_right; - int __pyx_v_n_left; - int __pyx_v_n_right; - int __pyx_v_idx; - int __pyx_v_k; - int __pyx_v_c; - int __pyx_v_s; - int __pyx_r; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_14RandomSplitter_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_14RandomSplitter_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - __Pyx_RefNannySetupContext("update", 0); + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_14RandomSplitter___reduce__(((struct __pyx_obj_7sklearn_4tree_5_tree_RandomSplitter *)__pyx_v_self)); - /* "sklearn/tree/_tree.pyx":1125 - * """Update the criteria for each value in interval [a,b) (where a and b - * are indices in `X_argsorted_i`).""" - * cdef int n_outputs = self.n_outputs # <<<<<<<<<<<<<< - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_left = self.label_count_left - */ - __pyx_v_n_outputs = __pyx_v_self->n_outputs; + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/tree/_tree.pyx":1126 - * are indices in `X_argsorted_i`).""" - * cdef int n_outputs = self.n_outputs - * cdef int label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< - * cdef int* label_count_left = self.label_count_left - * cdef int* label_count_right = self.label_count_right - */ - __pyx_v_label_count_stride = __pyx_v_self->label_count_stride; +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_14RandomSplitter___reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_RandomSplitter *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce__", 0); - /* "sklearn/tree/_tree.pyx":1127 - * cdef int n_outputs = self.n_outputs - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_left = self.label_count_left # <<<<<<<<<<<<<< - * cdef int* label_count_right = self.label_count_right - * cdef int n_left = self.n_left + /* "sklearn/tree/_tree.pyx":1364 + * """Splitter for finding the best random split.""" + * def __reduce__(self): + * return (RandomSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, */ - __pyx_v_label_count_left = __pyx_v_self->label_count_left; + __Pyx_XDECREF(__pyx_r); - /* "sklearn/tree/_tree.pyx":1128 - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_left = self.label_count_left - * cdef int* label_count_right = self.label_count_right # <<<<<<<<<<<<<< - * cdef int n_left = self.n_left - * cdef int n_right = self.n_right + /* "sklearn/tree/_tree.pyx":1365 + * def __reduce__(self): + * return (RandomSplitter, (self.criterion, + * self.max_features, # <<<<<<<<<<<<<< + * self.min_samples_leaf, + * self.min_weight_leaf, */ - __pyx_v_label_count_right = __pyx_v_self->label_count_right; + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.__pyx_base.max_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1365; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); - /* "sklearn/tree/_tree.pyx":1129 - * cdef int* label_count_left = self.label_count_left - * cdef int* label_count_right = self.label_count_right - * cdef int n_left = self.n_left # <<<<<<<<<<<<<< - * cdef int n_right = self.n_right - * + /* "sklearn/tree/_tree.pyx":1366 + * return (RandomSplitter, (self.criterion, + * self.max_features, + * self.min_samples_leaf, # <<<<<<<<<<<<<< + * self.min_weight_leaf, + * self.random_state), self.__getstate__()) */ - __pyx_v_n_left = __pyx_v_self->n_left; + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.__pyx_base.min_samples_leaf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); - /* "sklearn/tree/_tree.pyx":1130 - * cdef int* label_count_right = self.label_count_right - * cdef int n_left = self.n_left - * cdef int n_right = self.n_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1367 + * self.max_features, + * self.min_samples_leaf, + * self.min_weight_leaf, # <<<<<<<<<<<<<< + * self.random_state), self.__getstate__()) * - * cdef int idx, k, c, s */ - __pyx_v_n_right = __pyx_v_self->n_right; + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_self->__pyx_base.__pyx_base.min_weight_leaf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1367; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); - /* "sklearn/tree/_tree.pyx":1135 - * - * # post condition: all samples from [0:b) are on the left side - * for idx from a <= idx < b: # <<<<<<<<<<<<<< - * s = X_argsorted_i[idx] - * + /* "sklearn/tree/_tree.pyx":1364 + * """Splitter for finding the best random split.""" + * def __reduce__(self): + * return (RandomSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, */ - __pyx_t_1 = __pyx_v_b; - for (__pyx_v_idx = __pyx_v_a; __pyx_v_idx < __pyx_t_1; __pyx_v_idx++) { + __pyx_t_4 = PyTuple_New(5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1364; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_self->__pyx_base.__pyx_base.random_state); + PyTuple_SET_ITEM(__pyx_t_4, 4, __pyx_v_self->__pyx_base.__pyx_base.random_state); + __Pyx_GIVEREF(__pyx_v_self->__pyx_base.__pyx_base.random_state); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; - /* "sklearn/tree/_tree.pyx":1136 - * # post condition: all samples from [0:b) are on the left side - * for idx from a <= idx < b: - * s = X_argsorted_i[idx] # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1368 + * self.min_samples_leaf, + * self.min_weight_leaf, + * self.random_state), self.__getstate__()) # <<<<<<<<<<<<<< * - * if sample_mask[s] == 0: + * cdef void node_split(self, double impurity, SplitRecord* split, */ - __pyx_v_s = (__pyx_v_X_argsorted_i[__pyx_v_idx]); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_getstate); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (__pyx_t_1) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/tree/_tree.pyx":1138 - * s = X_argsorted_i[idx] - * - * if sample_mask[s] == 0: # <<<<<<<<<<<<<< - * continue - * + /* "sklearn/tree/_tree.pyx":1364 + * """Splitter for finding the best random split.""" + * def __reduce__(self): + * return (RandomSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, */ - __pyx_t_2 = ((__pyx_v_sample_mask[__pyx_v_s]) == 0); - if (__pyx_t_2) { + __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1364; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RandomSplitter))); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RandomSplitter))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RandomSplitter))); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; - /* "sklearn/tree/_tree.pyx":1139 - * - * if sample_mask[s] == 0: - * continue # <<<<<<<<<<<<<< - * - * for k from 0 <= k < n_outputs: + /* "sklearn/tree/_tree.pyx":1363 + * cdef class RandomSplitter(BaseDenseSplitter): + * """Splitter for finding the best random split.""" + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (RandomSplitter, (self.criterion, + * self.max_features, */ - goto __pyx_L3_continue; - goto __pyx_L5; - } - __pyx_L5:; - /* "sklearn/tree/_tree.pyx":1141 - * continue - * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * c = y[s * y_stride + k] - * label_count_right[k * label_count_stride + c] -= 1 + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.RandomSplitter.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":1370 + * self.random_state), self.__getstate__()) + * + * cdef void node_split(self, double impurity, SplitRecord* split, # <<<<<<<<<<<<<< + * SIZE_t* n_constant_features) nogil: + * """Find the best random split on node samples[start:end].""" + */ + +static void __pyx_f_7sklearn_4tree_5_tree_14RandomSplitter_node_split(struct __pyx_obj_7sklearn_4tree_5_tree_RandomSplitter *__pyx_v_self, double __pyx_v_impurity, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_constant_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_features; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_X_sample_stride; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_X_fx_stride; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + double __pyx_v_min_weight_leaf; + __pyx_t_7sklearn_4tree_5_tree_UINT32_t *__pyx_v_random_state; + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_best; + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_current; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_f_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_f_j; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_tmp; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_found_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_drawn_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_known_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_total_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_visited_features; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_min_feature_value; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_max_feature_value; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_current_feature_value; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_partition_end; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_t_3; + double __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; + + /* "sklearn/tree/_tree.pyx":1374 + * """Find the best random split on node samples[start:end].""" + * # Draw random splits and pick the best + * cdef SIZE_t* samples = self.samples # <<<<<<<<<<<<<< + * cdef SIZE_t start = self.start + * cdef SIZE_t end = self.end */ - __pyx_t_3 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_3; __pyx_v_k++) { + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.samples; + __pyx_v_samples = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":1142 + /* "sklearn/tree/_tree.pyx":1375 + * # Draw random splits and pick the best + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t start = self.start # <<<<<<<<<<<<<< + * cdef SIZE_t end = self.end * - * for k from 0 <= k < n_outputs: - * c = y[s * y_stride + k] # <<<<<<<<<<<<<< - * label_count_right[k * label_count_stride + c] -= 1 - * label_count_left[k * label_count_stride + c] += 1 */ - __pyx_v_c = ((int)(__pyx_v_y[((__pyx_v_s * __pyx_v_y_stride) + __pyx_v_k)])); + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.start; + __pyx_v_start = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1143 - * for k from 0 <= k < n_outputs: - * c = y[s * y_stride + k] - * label_count_right[k * label_count_stride + c] -= 1 # <<<<<<<<<<<<<< - * label_count_left[k * label_count_stride + c] += 1 + /* "sklearn/tree/_tree.pyx":1376 + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t start = self.start + * cdef SIZE_t end = self.end # <<<<<<<<<<<<<< * + * cdef SIZE_t* features = self.features */ - __pyx_t_4 = ((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c); - (__pyx_v_label_count_right[__pyx_t_4]) = ((__pyx_v_label_count_right[__pyx_t_4]) - 1); + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.end; + __pyx_v_end = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1144 - * c = y[s * y_stride + k] - * label_count_right[k * label_count_stride + c] -= 1 - * label_count_left[k * label_count_stride + c] += 1 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1378 + * cdef SIZE_t end = self.end * - * n_left += 1 + * cdef SIZE_t* features = self.features # <<<<<<<<<<<<<< + * cdef SIZE_t* constant_features = self.constant_features + * cdef SIZE_t n_features = self.n_features */ - __pyx_t_4 = ((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c); - (__pyx_v_label_count_left[__pyx_t_4]) = ((__pyx_v_label_count_left[__pyx_t_4]) + 1); - } + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.features; + __pyx_v_features = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":1146 - * label_count_left[k * label_count_stride + c] += 1 + /* "sklearn/tree/_tree.pyx":1379 * - * n_left += 1 # <<<<<<<<<<<<<< - * n_right -=1 + * cdef SIZE_t* features = self.features + * cdef SIZE_t* constant_features = self.constant_features # <<<<<<<<<<<<<< + * cdef SIZE_t n_features = self.n_features * */ - __pyx_v_n_left = (__pyx_v_n_left + 1); + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.constant_features; + __pyx_v_constant_features = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":1147 - * - * n_left += 1 - * n_right -=1 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1380 + * cdef SIZE_t* features = self.features + * cdef SIZE_t* constant_features = self.constant_features + * cdef SIZE_t n_features = self.n_features # <<<<<<<<<<<<<< * - * self.n_left = n_left + * cdef DTYPE_t* X = self.X */ - __pyx_v_n_right = (__pyx_v_n_right - 1); - __pyx_L3_continue:; - } + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.n_features; + __pyx_v_n_features = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1149 - * n_right -=1 - * - * self.n_left = n_left # <<<<<<<<<<<<<< - * self.n_right = n_right + /* "sklearn/tree/_tree.pyx":1382 + * cdef SIZE_t n_features = self.n_features * + * cdef DTYPE_t* X = self.X # <<<<<<<<<<<<<< + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t X_sample_stride = self.X_sample_stride */ - __pyx_v_self->n_left = __pyx_v_n_left; + __pyx_t_3 = __pyx_v_self->__pyx_base.X; + __pyx_v_X = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":1150 - * - * self.n_left = n_left - * self.n_right = n_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1383 * - * return n_left + * cdef DTYPE_t* X = self.X + * cdef DTYPE_t* Xf = self.feature_values # <<<<<<<<<<<<<< + * cdef SIZE_t X_sample_stride = self.X_sample_stride + * cdef SIZE_t X_fx_stride = self.X_fx_stride */ - __pyx_v_self->n_right = __pyx_v_n_right; + __pyx_t_3 = __pyx_v_self->__pyx_base.__pyx_base.feature_values; + __pyx_v_Xf = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":1152 - * self.n_right = n_right - * - * return n_left # <<<<<<<<<<<<<< - * - * cdef double eval(self): + /* "sklearn/tree/_tree.pyx":1384 + * cdef DTYPE_t* X = self.X + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t X_sample_stride = self.X_sample_stride # <<<<<<<<<<<<<< + * cdef SIZE_t X_fx_stride = self.X_fx_stride + * cdef SIZE_t max_features = self.max_features */ - __pyx_r = __pyx_v_n_left; - goto __pyx_L0; + __pyx_t_2 = __pyx_v_self->__pyx_base.X_sample_stride; + __pyx_v_X_sample_stride = __pyx_t_2; - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1385 + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t X_sample_stride = self.X_sample_stride + * cdef SIZE_t X_fx_stride = self.X_fx_stride # <<<<<<<<<<<<<< + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.X_fx_stride; + __pyx_v_X_fx_stride = __pyx_t_2; -/* "sklearn/tree/_tree.pyx":1154 - * return n_left - * - * cdef double eval(self): # <<<<<<<<<<<<<< - * """Evaluate the criteria (aka the split error).""" - * pass + /* "sklearn/tree/_tree.pyx":1386 + * cdef SIZE_t X_sample_stride = self.X_sample_stride + * cdef SIZE_t X_fx_stride = self.X_fx_stride + * cdef SIZE_t max_features = self.max_features # <<<<<<<<<<<<<< + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.max_features; + __pyx_v_max_features = __pyx_t_2; -static double __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_eval(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self) { - double __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("eval", 0); + /* "sklearn/tree/_tree.pyx":1387 + * cdef SIZE_t X_fx_stride = self.X_fx_stride + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf # <<<<<<<<<<<<<< + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef UINT32_t* random_state = &self.rand_r_state + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.min_samples_leaf; + __pyx_v_min_samples_leaf = __pyx_t_2; - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1388 + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf # <<<<<<<<<<<<<< + * cdef UINT32_t* random_state = &self.rand_r_state + * + */ + __pyx_t_4 = __pyx_v_self->__pyx_base.__pyx_base.min_weight_leaf; + __pyx_v_min_weight_leaf = __pyx_t_4; -/* "sklearn/tree/_tree.pyx":1158 - * pass + /* "sklearn/tree/_tree.pyx":1389 + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef UINT32_t* random_state = &self.rand_r_state # <<<<<<<<<<<<<< * - * cdef void init_value(self, double* buffer_value): # <<<<<<<<<<<<<< - * """Get the initial value of the criterion (`init` must be called - * before).""" + * cdef SplitRecord best, current */ + __pyx_v_random_state = (&__pyx_v_self->__pyx_base.__pyx_base.rand_r_state); -static void __pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_init_value(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *__pyx_v_self, double *__pyx_v_buffer_value) { - int __pyx_v_n_outputs; - int *__pyx_v_n_classes; - int __pyx_v_label_count_stride; - int *__pyx_v_label_count_init; - int __pyx_v_k; - int __pyx_v_c; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - __Pyx_RefNannySetupContext("init_value", 0); + /* "sklearn/tree/_tree.pyx":1393 + * cdef SplitRecord best, current + * + * cdef SIZE_t f_i = n_features # <<<<<<<<<<<<<< + * cdef SIZE_t f_j, p, tmp + * # Number of features discovered to be constant during the split search + */ + __pyx_v_f_i = __pyx_v_n_features; - /* "sklearn/tree/_tree.pyx":1161 - * """Get the initial value of the criterion (`init` must be called - * before).""" - * cdef int n_outputs = self.n_outputs # <<<<<<<<<<<<<< - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride + /* "sklearn/tree/_tree.pyx":1396 + * cdef SIZE_t f_j, p, tmp + * # Number of features discovered to be constant during the split search + * cdef SIZE_t n_found_constants = 0 # <<<<<<<<<<<<<< + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 */ - __pyx_v_n_outputs = __pyx_v_self->n_outputs; + __pyx_v_n_found_constants = 0; - /* "sklearn/tree/_tree.pyx":1162 - * before).""" - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes # <<<<<<<<<<<<<< - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_init = self.label_count_init + /* "sklearn/tree/_tree.pyx":1398 + * cdef SIZE_t n_found_constants = 0 + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t n_known_constants = n_constant_features[0] + * # n_total_constants = n_known_constants + n_found_constants */ - __pyx_v_n_classes = __pyx_v_self->n_classes; + __pyx_v_n_drawn_constants = 0; - /* "sklearn/tree/_tree.pyx":1163 - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< - * cdef int* label_count_init = self.label_count_init - * + /* "sklearn/tree/_tree.pyx":1399 + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 + * cdef SIZE_t n_known_constants = n_constant_features[0] # <<<<<<<<<<<<<< + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants */ - __pyx_v_label_count_stride = __pyx_v_self->label_count_stride; + __pyx_v_n_known_constants = (__pyx_v_n_constant_features[0]); - /* "sklearn/tree/_tree.pyx":1164 - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_init = self.label_count_init # <<<<<<<<<<<<<< - * - * cdef int k, c + /* "sklearn/tree/_tree.pyx":1401 + * cdef SIZE_t n_known_constants = n_constant_features[0] + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants # <<<<<<<<<<<<<< + * cdef SIZE_t n_visited_features = 0 + * cdef DTYPE_t min_feature_value */ - __pyx_v_label_count_init = __pyx_v_self->label_count_init; + __pyx_v_n_total_constants = __pyx_v_n_known_constants; - /* "sklearn/tree/_tree.pyx":1168 - * cdef int k, c - * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * for c from 0 <= c < n_classes[k]: - * buffer_value[k * label_count_stride + c] = label_count_init[k * label_count_stride + c] + /* "sklearn/tree/_tree.pyx":1402 + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants + * cdef SIZE_t n_visited_features = 0 # <<<<<<<<<<<<<< + * cdef DTYPE_t min_feature_value + * cdef DTYPE_t max_feature_value */ - __pyx_t_1 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_1; __pyx_v_k++) { + __pyx_v_n_visited_features = 0; - /* "sklearn/tree/_tree.pyx":1169 + /* "sklearn/tree/_tree.pyx":1408 + * cdef SIZE_t partition_end * - * for k from 0 <= k < n_outputs: - * for c from 0 <= c < n_classes[k]: # <<<<<<<<<<<<<< - * buffer_value[k * label_count_stride + c] = label_count_init[k * label_count_stride + c] + * _init_split(&best, end) # <<<<<<<<<<<<<< * + * # Sample up to max_features without replacement using a */ - __pyx_t_2 = (__pyx_v_n_classes[__pyx_v_k]); - for (__pyx_v_c = 0; __pyx_v_c < __pyx_t_2; __pyx_v_c++) { + __pyx_f_7sklearn_4tree_5_tree__init_split((&__pyx_v_best), __pyx_v_end); - /* "sklearn/tree/_tree.pyx":1170 - * for k from 0 <= k < n_outputs: - * for c from 0 <= c < n_classes[k]: - * buffer_value[k * label_count_stride + c] = label_count_init[k * label_count_stride + c] # <<<<<<<<<<<<<< - * - * + /* "sklearn/tree/_tree.pyx":1419 + * # newly discovered constant features to spare computation on descendant + * # nodes. + * while (f_i > n_total_constants and # Stop early if remaining features # <<<<<<<<<<<<<< + * # are constant + * (n_visited_features < max_features or */ - (__pyx_v_buffer_value[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]) = (__pyx_v_label_count_init[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]); + while (1) { + __pyx_t_6 = ((__pyx_v_f_i > __pyx_v_n_total_constants) != 0); + if (__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L5_bool_binop_done; } - } - __Pyx_RefNannyFinishContext(); -} + /* "sklearn/tree/_tree.pyx":1421 + * while (f_i > n_total_constants and # Stop early if remaining features + * # are constant + * (n_visited_features < max_features or # <<<<<<<<<<<<<< + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): + */ + __pyx_t_6 = ((__pyx_v_n_visited_features < __pyx_v_max_features) != 0); + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L5_bool_binop_done; + } -/* "sklearn/tree/_tree.pyx":1189 - * """ + /* "sklearn/tree/_tree.pyx":1423 + * (n_visited_features < max_features or + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): # <<<<<<<<<<<<<< + * n_visited_features += 1 * - * cdef double eval(self): # <<<<<<<<<<<<<< - * """Returns Gini index of left branch + Gini index of right branch.""" - * cdef int n_samples = self.n_samples */ + __pyx_t_6 = ((__pyx_v_n_visited_features <= (__pyx_v_n_found_constants + __pyx_v_n_drawn_constants)) != 0); + __pyx_t_5 = __pyx_t_6; + __pyx_L5_bool_binop_done:; + if (!__pyx_t_5) break; -static double __pyx_f_7sklearn_4tree_5_tree_4Gini_eval(struct __pyx_obj_7sklearn_4tree_5_tree_Gini *__pyx_v_self) { - int __pyx_v_n_samples; - int __pyx_v_n_outputs; - int *__pyx_v_n_classes; - int __pyx_v_label_count_stride; - int *__pyx_v_label_count_left; - int *__pyx_v_label_count_right; - double __pyx_v_n_left; - double __pyx_v_n_right; - double __pyx_v_total; - double __pyx_v_H_left; - double __pyx_v_H_right; - int __pyx_v_k; - int __pyx_v_c; - int __pyx_v_count_left; - int __pyx_v_count_right; - double __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - __Pyx_RefNannySetupContext("eval", 0); + /* "sklearn/tree/_tree.pyx":1424 + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): + * n_visited_features += 1 # <<<<<<<<<<<<<< + * + * # Loop invariant: elements of features in + */ + __pyx_v_n_visited_features = (__pyx_v_n_visited_features + 1); + + /* "sklearn/tree/_tree.pyx":1438 + * + * # Draw a feature at random + * f_j = rand_int(n_drawn_constants, f_i - n_found_constants, # <<<<<<<<<<<<<< + * random_state) + * + */ + __pyx_v_f_j = __pyx_f_7sklearn_4tree_5_tree_rand_int(__pyx_v_n_drawn_constants, (__pyx_v_f_i - __pyx_v_n_found_constants), __pyx_v_random_state); - /* "sklearn/tree/_tree.pyx":1191 - * cdef double eval(self): - * """Returns Gini index of left branch + Gini index of right branch.""" - * cdef int n_samples = self.n_samples # <<<<<<<<<<<<<< - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes + /* "sklearn/tree/_tree.pyx":1441 + * random_state) + * + * if f_j < n_known_constants: # <<<<<<<<<<<<<< + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] */ - __pyx_v_n_samples = __pyx_v_self->__pyx_base.n_samples; + __pyx_t_5 = ((__pyx_v_f_j < __pyx_v_n_known_constants) != 0); + if (__pyx_t_5) { - /* "sklearn/tree/_tree.pyx":1192 - * """Returns Gini index of left branch + Gini index of right branch.""" - * cdef int n_samples = self.n_samples - * cdef int n_outputs = self.n_outputs # <<<<<<<<<<<<<< - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride + /* "sklearn/tree/_tree.pyx":1443 + * if f_j < n_known_constants: + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] # <<<<<<<<<<<<<< + * features[f_j] = features[n_drawn_constants] + * features[n_drawn_constants] = tmp */ - __pyx_v_n_outputs = __pyx_v_self->__pyx_base.n_outputs; + __pyx_v_tmp = (__pyx_v_features[__pyx_v_f_j]); - /* "sklearn/tree/_tree.pyx":1193 - * cdef int n_samples = self.n_samples - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes # <<<<<<<<<<<<<< - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_left = self.label_count_left + /* "sklearn/tree/_tree.pyx":1444 + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] + * features[f_j] = features[n_drawn_constants] # <<<<<<<<<<<<<< + * features[n_drawn_constants] = tmp + * */ - __pyx_v_n_classes = __pyx_v_self->__pyx_base.n_classes; + (__pyx_v_features[__pyx_v_f_j]) = (__pyx_v_features[__pyx_v_n_drawn_constants]); - /* "sklearn/tree/_tree.pyx":1194 - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< - * cdef int* label_count_left = self.label_count_left - * cdef int* label_count_right = self.label_count_right + /* "sklearn/tree/_tree.pyx":1445 + * tmp = features[f_j] + * features[f_j] = features[n_drawn_constants] + * features[n_drawn_constants] = tmp # <<<<<<<<<<<<<< + * + * n_drawn_constants += 1 */ - __pyx_v_label_count_stride = __pyx_v_self->__pyx_base.label_count_stride; + (__pyx_v_features[__pyx_v_n_drawn_constants]) = __pyx_v_tmp; - /* "sklearn/tree/_tree.pyx":1195 - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_left = self.label_count_left # <<<<<<<<<<<<<< - * cdef int* label_count_right = self.label_count_right - * cdef double n_left = self.n_left + /* "sklearn/tree/_tree.pyx":1447 + * features[n_drawn_constants] = tmp + * + * n_drawn_constants += 1 # <<<<<<<<<<<<<< + * + * else: */ - __pyx_v_label_count_left = __pyx_v_self->__pyx_base.label_count_left; + __pyx_v_n_drawn_constants = (__pyx_v_n_drawn_constants + 1); + goto __pyx_L8; + } + /*else*/ { - /* "sklearn/tree/_tree.pyx":1196 - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_left = self.label_count_left - * cdef int* label_count_right = self.label_count_right # <<<<<<<<<<<<<< - * cdef double n_left = self.n_left - * cdef double n_right = self.n_right + /* "sklearn/tree/_tree.pyx":1451 + * else: + * # f_j in the interval [n_known_constants, f_i - n_found_constants[ + * f_j += n_found_constants # <<<<<<<<<<<<<< + * # f_j in the interval [n_total_constants, f_i[ + * */ - __pyx_v_label_count_right = __pyx_v_self->__pyx_base.label_count_right; + __pyx_v_f_j = (__pyx_v_f_j + __pyx_v_n_found_constants); - /* "sklearn/tree/_tree.pyx":1197 - * cdef int* label_count_left = self.label_count_left - * cdef int* label_count_right = self.label_count_right - * cdef double n_left = self.n_left # <<<<<<<<<<<<<< - * cdef double n_right = self.n_right + /* "sklearn/tree/_tree.pyx":1454 + * # f_j in the interval [n_total_constants, f_i[ * + * current.feature = features[f_j] # <<<<<<<<<<<<<< + * + * # Find min, max */ - __pyx_v_n_left = ((double)__pyx_v_self->__pyx_base.n_left); + __pyx_v_current.feature = (__pyx_v_features[__pyx_v_f_j]); - /* "sklearn/tree/_tree.pyx":1198 - * cdef int* label_count_right = self.label_count_right - * cdef double n_left = self.n_left - * cdef double n_right = self.n_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1457 * - * cdef double total = 0.0 + * # Find min, max + * min_feature_value = X[X_sample_stride * samples[start] + # <<<<<<<<<<<<<< + * X_fx_stride * current.feature] + * max_feature_value = min_feature_value */ - __pyx_v_n_right = ((double)__pyx_v_self->__pyx_base.n_right); + __pyx_v_min_feature_value = (__pyx_v_X[((__pyx_v_X_sample_stride * (__pyx_v_samples[__pyx_v_start])) + (__pyx_v_X_fx_stride * __pyx_v_current.feature))]); - /* "sklearn/tree/_tree.pyx":1200 - * cdef double n_right = self.n_right + /* "sklearn/tree/_tree.pyx":1459 + * min_feature_value = X[X_sample_stride * samples[start] + + * X_fx_stride * current.feature] + * max_feature_value = min_feature_value # <<<<<<<<<<<<<< + * Xf[start] = min_feature_value * - * cdef double total = 0.0 # <<<<<<<<<<<<<< - * cdef double H_left - * cdef double H_right */ - __pyx_v_total = 0.0; + __pyx_v_max_feature_value = __pyx_v_min_feature_value; - /* "sklearn/tree/_tree.pyx":1205 - * cdef int k, c, count_left, count_right + /* "sklearn/tree/_tree.pyx":1460 + * X_fx_stride * current.feature] + * max_feature_value = min_feature_value + * Xf[start] = min_feature_value # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * H_left = n_left * n_left - * H_right = n_right * n_right + * for p in range(start + 1, end): */ - __pyx_t_1 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_1; __pyx_v_k++) { + (__pyx_v_Xf[__pyx_v_start]) = __pyx_v_min_feature_value; - /* "sklearn/tree/_tree.pyx":1206 + /* "sklearn/tree/_tree.pyx":1462 + * Xf[start] = min_feature_value * - * for k from 0 <= k < n_outputs: - * H_left = n_left * n_left # <<<<<<<<<<<<<< - * H_right = n_right * n_right + * for p in range(start + 1, end): # <<<<<<<<<<<<<< + * current_feature_value = X[X_sample_stride * samples[p] + + * X_fx_stride * current.feature] + */ + __pyx_t_2 = __pyx_v_end; + for (__pyx_t_7 = (__pyx_v_start + 1); __pyx_t_7 < __pyx_t_2; __pyx_t_7+=1) { + __pyx_v_p = __pyx_t_7; + + /* "sklearn/tree/_tree.pyx":1463 * + * for p in range(start + 1, end): + * current_feature_value = X[X_sample_stride * samples[p] + # <<<<<<<<<<<<<< + * X_fx_stride * current.feature] + * Xf[p] = current_feature_value */ - __pyx_v_H_left = (__pyx_v_n_left * __pyx_v_n_left); + __pyx_v_current_feature_value = (__pyx_v_X[((__pyx_v_X_sample_stride * (__pyx_v_samples[__pyx_v_p])) + (__pyx_v_X_fx_stride * __pyx_v_current.feature))]); - /* "sklearn/tree/_tree.pyx":1207 - * for k from 0 <= k < n_outputs: - * H_left = n_left * n_left - * H_right = n_right * n_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1465 + * current_feature_value = X[X_sample_stride * samples[p] + + * X_fx_stride * current.feature] + * Xf[p] = current_feature_value # <<<<<<<<<<<<<< * - * for c from 0 <= c < n_classes[k]: + * if current_feature_value < min_feature_value: */ - __pyx_v_H_right = (__pyx_v_n_right * __pyx_v_n_right); + (__pyx_v_Xf[__pyx_v_p]) = __pyx_v_current_feature_value; - /* "sklearn/tree/_tree.pyx":1209 - * H_right = n_right * n_right + /* "sklearn/tree/_tree.pyx":1467 + * Xf[p] = current_feature_value * - * for c from 0 <= c < n_classes[k]: # <<<<<<<<<<<<<< - * count_left = label_count_left[k * label_count_stride + c] - * if count_left > 0: + * if current_feature_value < min_feature_value: # <<<<<<<<<<<<<< + * min_feature_value = current_feature_value + * elif current_feature_value > max_feature_value: */ - __pyx_t_2 = (__pyx_v_n_classes[__pyx_v_k]); - for (__pyx_v_c = 0; __pyx_v_c < __pyx_t_2; __pyx_v_c++) { + __pyx_t_5 = ((__pyx_v_current_feature_value < __pyx_v_min_feature_value) != 0); + if (__pyx_t_5) { - /* "sklearn/tree/_tree.pyx":1210 + /* "sklearn/tree/_tree.pyx":1468 * - * for c from 0 <= c < n_classes[k]: - * count_left = label_count_left[k * label_count_stride + c] # <<<<<<<<<<<<<< - * if count_left > 0: - * H_left -= (count_left * count_left) + * if current_feature_value < min_feature_value: + * min_feature_value = current_feature_value # <<<<<<<<<<<<<< + * elif current_feature_value > max_feature_value: + * max_feature_value = current_feature_value */ - __pyx_v_count_left = (__pyx_v_label_count_left[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]); + __pyx_v_min_feature_value = __pyx_v_current_feature_value; + goto __pyx_L11; + } - /* "sklearn/tree/_tree.pyx":1211 - * for c from 0 <= c < n_classes[k]: - * count_left = label_count_left[k * label_count_stride + c] - * if count_left > 0: # <<<<<<<<<<<<<< - * H_left -= (count_left * count_left) + /* "sklearn/tree/_tree.pyx":1469 + * if current_feature_value < min_feature_value: + * min_feature_value = current_feature_value + * elif current_feature_value > max_feature_value: # <<<<<<<<<<<<<< + * max_feature_value = current_feature_value * */ - __pyx_t_3 = (__pyx_v_count_left > 0); - if (__pyx_t_3) { + __pyx_t_5 = ((__pyx_v_current_feature_value > __pyx_v_max_feature_value) != 0); + if (__pyx_t_5) { - /* "sklearn/tree/_tree.pyx":1212 - * count_left = label_count_left[k * label_count_stride + c] - * if count_left > 0: - * H_left -= (count_left * count_left) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1470 + * min_feature_value = current_feature_value + * elif current_feature_value > max_feature_value: + * max_feature_value = current_feature_value # <<<<<<<<<<<<<< * - * count_right = label_count_right[k * label_count_stride + c] + * if max_feature_value <= min_feature_value + FEATURE_THRESHOLD: */ - __pyx_v_H_left = (__pyx_v_H_left - (__pyx_v_count_left * __pyx_v_count_left)); - goto __pyx_L7; + __pyx_v_max_feature_value = __pyx_v_current_feature_value; + goto __pyx_L11; + } + __pyx_L11:; } - __pyx_L7:; - /* "sklearn/tree/_tree.pyx":1214 - * H_left -= (count_left * count_left) + /* "sklearn/tree/_tree.pyx":1472 + * max_feature_value = current_feature_value * - * count_right = label_count_right[k * label_count_stride + c] # <<<<<<<<<<<<<< - * if count_right > 0: - * H_right -= (count_right * count_right) + * if max_feature_value <= min_feature_value + FEATURE_THRESHOLD: # <<<<<<<<<<<<<< + * features[f_j] = features[n_total_constants] + * features[n_total_constants] = current.feature */ - __pyx_v_count_right = (__pyx_v_label_count_right[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]); + __pyx_t_5 = ((__pyx_v_max_feature_value <= (__pyx_v_min_feature_value + __pyx_v_7sklearn_4tree_5_tree_FEATURE_THRESHOLD)) != 0); + if (__pyx_t_5) { - /* "sklearn/tree/_tree.pyx":1215 + /* "sklearn/tree/_tree.pyx":1473 * - * count_right = label_count_right[k * label_count_stride + c] - * if count_right > 0: # <<<<<<<<<<<<<< - * H_right -= (count_right * count_right) + * if max_feature_value <= min_feature_value + FEATURE_THRESHOLD: + * features[f_j] = features[n_total_constants] # <<<<<<<<<<<<<< + * features[n_total_constants] = current.feature * */ - __pyx_t_3 = (__pyx_v_count_right > 0); - if (__pyx_t_3) { + (__pyx_v_features[__pyx_v_f_j]) = (__pyx_v_features[__pyx_v_n_total_constants]); - /* "sklearn/tree/_tree.pyx":1216 - * count_right = label_count_right[k * label_count_stride + c] - * if count_right > 0: - * H_right -= (count_right * count_right) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1474 + * if max_feature_value <= min_feature_value + FEATURE_THRESHOLD: + * features[f_j] = features[n_total_constants] + * features[n_total_constants] = current.feature # <<<<<<<<<<<<<< * - * if n_left == 0: + * n_found_constants += 1 */ - __pyx_v_H_right = (__pyx_v_H_right - (__pyx_v_count_right * __pyx_v_count_right)); - goto __pyx_L8; + __pyx_t_2 = __pyx_v_current.feature; + (__pyx_v_features[__pyx_v_n_total_constants]) = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":1476 + * features[n_total_constants] = current.feature + * + * n_found_constants += 1 # <<<<<<<<<<<<<< + * n_total_constants += 1 + * + */ + __pyx_v_n_found_constants = (__pyx_v_n_found_constants + 1); + + /* "sklearn/tree/_tree.pyx":1477 + * + * n_found_constants += 1 + * n_total_constants += 1 # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_v_n_total_constants = (__pyx_v_n_total_constants + 1); + goto __pyx_L12; } - __pyx_L8:; - } + /*else*/ { - /* "sklearn/tree/_tree.pyx":1218 - * H_right -= (count_right * count_right) + /* "sklearn/tree/_tree.pyx":1480 + * + * else: + * f_i -= 1 # <<<<<<<<<<<<<< + * features[f_i], features[f_j] = features[f_j], features[f_i] * - * if n_left == 0: # <<<<<<<<<<<<<< - * H_left = 0 - * else: */ - __pyx_t_3 = (__pyx_v_n_left == 0.0); - if (__pyx_t_3) { + __pyx_v_f_i = (__pyx_v_f_i - 1); - /* "sklearn/tree/_tree.pyx":1219 + /* "sklearn/tree/_tree.pyx":1481 + * else: + * f_i -= 1 + * features[f_i], features[f_j] = features[f_j], features[f_i] # <<<<<<<<<<<<<< * - * if n_left == 0: - * H_left = 0 # <<<<<<<<<<<<<< - * else: - * H_left /= n_left + * # Draw a random threshold */ - __pyx_v_H_left = 0.0; - goto __pyx_L9; - } - /*else*/ { + __pyx_t_2 = (__pyx_v_features[__pyx_v_f_j]); + __pyx_t_7 = (__pyx_v_features[__pyx_v_f_i]); + (__pyx_v_features[__pyx_v_f_i]) = __pyx_t_2; + (__pyx_v_features[__pyx_v_f_j]) = __pyx_t_7; - /* "sklearn/tree/_tree.pyx":1221 - * H_left = 0 - * else: - * H_left /= n_left # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1484 * - * if n_right == 0: + * # Draw a random threshold + * current.threshold = rand_uniform(min_feature_value, # <<<<<<<<<<<<<< + * max_feature_value, + * random_state) */ - __pyx_v_H_left = (__pyx_v_H_left / __pyx_v_n_left); - } - __pyx_L9:; + __pyx_v_current.threshold = __pyx_f_7sklearn_4tree_5_tree_rand_uniform(__pyx_v_min_feature_value, __pyx_v_max_feature_value, __pyx_v_random_state); - /* "sklearn/tree/_tree.pyx":1223 - * H_left /= n_left + /* "sklearn/tree/_tree.pyx":1488 + * random_state) + * + * if current.threshold == max_feature_value: # <<<<<<<<<<<<<< + * current.threshold = min_feature_value * - * if n_right == 0: # <<<<<<<<<<<<<< - * H_right = 0 - * else: */ - __pyx_t_3 = (__pyx_v_n_right == 0.0); - if (__pyx_t_3) { + __pyx_t_5 = ((__pyx_v_current.threshold == __pyx_v_max_feature_value) != 0); + if (__pyx_t_5) { - /* "sklearn/tree/_tree.pyx":1224 + /* "sklearn/tree/_tree.pyx":1489 * - * if n_right == 0: - * H_right = 0 # <<<<<<<<<<<<<< - * else: - * H_right /= n_right + * if current.threshold == max_feature_value: + * current.threshold = min_feature_value # <<<<<<<<<<<<<< + * + * # Partition */ - __pyx_v_H_right = 0.0; - goto __pyx_L10; - } - /*else*/ { + __pyx_v_current.threshold = __pyx_v_min_feature_value; + goto __pyx_L13; + } + __pyx_L13:; + + /* "sklearn/tree/_tree.pyx":1492 + * + * # Partition + * partition_end = end # <<<<<<<<<<<<<< + * p = start + * while p < partition_end: + */ + __pyx_v_partition_end = __pyx_v_end; + + /* "sklearn/tree/_tree.pyx":1493 + * # Partition + * partition_end = end + * p = start # <<<<<<<<<<<<<< + * while p < partition_end: + * current_feature_value = Xf[p] + */ + __pyx_v_p = __pyx_v_start; + + /* "sklearn/tree/_tree.pyx":1494 + * partition_end = end + * p = start + * while p < partition_end: # <<<<<<<<<<<<<< + * current_feature_value = Xf[p] + * if current_feature_value <= current.threshold: + */ + while (1) { + __pyx_t_5 = ((__pyx_v_p < __pyx_v_partition_end) != 0); + if (!__pyx_t_5) break; + + /* "sklearn/tree/_tree.pyx":1495 + * p = start + * while p < partition_end: + * current_feature_value = Xf[p] # <<<<<<<<<<<<<< + * if current_feature_value <= current.threshold: + * p += 1 + */ + __pyx_v_current_feature_value = (__pyx_v_Xf[__pyx_v_p]); + + /* "sklearn/tree/_tree.pyx":1496 + * while p < partition_end: + * current_feature_value = Xf[p] + * if current_feature_value <= current.threshold: # <<<<<<<<<<<<<< + * p += 1 + * else: + */ + __pyx_t_5 = ((__pyx_v_current_feature_value <= __pyx_v_current.threshold) != 0); + if (__pyx_t_5) { + + /* "sklearn/tree/_tree.pyx":1497 + * current_feature_value = Xf[p] + * if current_feature_value <= current.threshold: + * p += 1 # <<<<<<<<<<<<<< + * else: + * partition_end -= 1 + */ + __pyx_v_p = (__pyx_v_p + 1); + goto __pyx_L16; + } + /*else*/ { - /* "sklearn/tree/_tree.pyx":1226 - * H_right = 0 - * else: - * H_right /= n_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1499 + * p += 1 + * else: + * partition_end -= 1 # <<<<<<<<<<<<<< * - * total += (H_left + H_right) + * Xf[p] = Xf[partition_end] */ - __pyx_v_H_right = (__pyx_v_H_right / __pyx_v_n_right); - } - __pyx_L10:; + __pyx_v_partition_end = (__pyx_v_partition_end - 1); - /* "sklearn/tree/_tree.pyx":1228 - * H_right /= n_right + /* "sklearn/tree/_tree.pyx":1501 + * partition_end -= 1 * - * total += (H_left + H_right) # <<<<<<<<<<<<<< + * Xf[p] = Xf[partition_end] # <<<<<<<<<<<<<< + * Xf[partition_end] = current_feature_value * - * return total / (n_samples * n_outputs) */ - __pyx_v_total = (__pyx_v_total + (__pyx_v_H_left + __pyx_v_H_right)); - } + (__pyx_v_Xf[__pyx_v_p]) = (__pyx_v_Xf[__pyx_v_partition_end]); - /* "sklearn/tree/_tree.pyx":1230 - * total += (H_left + H_right) + /* "sklearn/tree/_tree.pyx":1502 * - * return total / (n_samples * n_outputs) # <<<<<<<<<<<<<< + * Xf[p] = Xf[partition_end] + * Xf[partition_end] = current_feature_value # <<<<<<<<<<<<<< * + * tmp = samples[partition_end] + */ + (__pyx_v_Xf[__pyx_v_partition_end]) = __pyx_v_current_feature_value; + + /* "sklearn/tree/_tree.pyx":1504 + * Xf[partition_end] = current_feature_value * + * tmp = samples[partition_end] # <<<<<<<<<<<<<< + * samples[partition_end] = samples[p] + * samples[p] = tmp */ - __pyx_r = (__pyx_v_total / (__pyx_v_n_samples * __pyx_v_n_outputs)); - goto __pyx_L0; + __pyx_v_tmp = (__pyx_v_samples[__pyx_v_partition_end]); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1505 + * + * tmp = samples[partition_end] + * samples[partition_end] = samples[p] # <<<<<<<<<<<<<< + * samples[p] = tmp + * + */ + (__pyx_v_samples[__pyx_v_partition_end]) = (__pyx_v_samples[__pyx_v_p]); -/* "sklearn/tree/_tree.pyx":1248 - * """ + /* "sklearn/tree/_tree.pyx":1506 + * tmp = samples[partition_end] + * samples[partition_end] = samples[p] + * samples[p] = tmp # <<<<<<<<<<<<<< * - * cdef double eval(self): # <<<<<<<<<<<<<< - * """Returns Entropy of left branch + Entropy index of right branch. """ - * cdef int n_samples = self.n_samples + * current.pos = partition_end */ + (__pyx_v_samples[__pyx_v_p]) = __pyx_v_tmp; + } + __pyx_L16:; + } -static double __pyx_f_7sklearn_4tree_5_tree_7Entropy_eval(struct __pyx_obj_7sklearn_4tree_5_tree_Entropy *__pyx_v_self) { - int __pyx_v_n_samples; - int __pyx_v_n_outputs; - int *__pyx_v_n_classes; - int __pyx_v_label_count_stride; - int *__pyx_v_label_count_left; - int *__pyx_v_label_count_right; - double __pyx_v_n_left; - double __pyx_v_n_right; - double __pyx_v_total; - double __pyx_v_H_left; - double __pyx_v_H_right; - int __pyx_v_k; - int __pyx_v_c; - double __pyx_v_e1; - double __pyx_v_e2; - double __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - __Pyx_RefNannySetupContext("eval", 0); + /* "sklearn/tree/_tree.pyx":1508 + * samples[p] = tmp + * + * current.pos = partition_end # <<<<<<<<<<<<<< + * + * # Reject if min_samples_leaf is not guaranteed + */ + __pyx_v_current.pos = __pyx_v_partition_end; - /* "sklearn/tree/_tree.pyx":1250 - * cdef double eval(self): - * """Returns Entropy of left branch + Entropy index of right branch. """ - * cdef int n_samples = self.n_samples # <<<<<<<<<<<<<< - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes + /* "sklearn/tree/_tree.pyx":1511 + * + * # Reject if min_samples_leaf is not guaranteed + * if (((current.pos - start) < min_samples_leaf) or # <<<<<<<<<<<<<< + * ((end - current.pos) < min_samples_leaf)): + * continue */ - __pyx_v_n_samples = __pyx_v_self->__pyx_base.n_samples; + __pyx_t_6 = (((__pyx_v_current.pos - __pyx_v_start) < __pyx_v_min_samples_leaf) != 0); + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L18_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":1251 - * """Returns Entropy of left branch + Entropy index of right branch. """ - * cdef int n_samples = self.n_samples - * cdef int n_outputs = self.n_outputs # <<<<<<<<<<<<<< - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride + /* "sklearn/tree/_tree.pyx":1512 + * # Reject if min_samples_leaf is not guaranteed + * if (((current.pos - start) < min_samples_leaf) or + * ((end - current.pos) < min_samples_leaf)): # <<<<<<<<<<<<<< + * continue + * */ - __pyx_v_n_outputs = __pyx_v_self->__pyx_base.n_outputs; + __pyx_t_6 = (((__pyx_v_end - __pyx_v_current.pos) < __pyx_v_min_samples_leaf) != 0); + __pyx_t_5 = __pyx_t_6; + __pyx_L18_bool_binop_done:; + if (__pyx_t_5) { - /* "sklearn/tree/_tree.pyx":1252 - * cdef int n_samples = self.n_samples - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes # <<<<<<<<<<<<<< - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_left = self.label_count_left + /* "sklearn/tree/_tree.pyx":1513 + * if (((current.pos - start) < min_samples_leaf) or + * ((end - current.pos) < min_samples_leaf)): + * continue # <<<<<<<<<<<<<< + * + * # Evaluate split */ - __pyx_v_n_classes = __pyx_v_self->__pyx_base.n_classes; + goto __pyx_L3_continue; + } - /* "sklearn/tree/_tree.pyx":1253 - * cdef int n_outputs = self.n_outputs - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride # <<<<<<<<<<<<<< - * cdef int* label_count_left = self.label_count_left - * cdef int* label_count_right = self.label_count_right + /* "sklearn/tree/_tree.pyx":1516 + * + * # Evaluate split + * self.criterion.reset() # <<<<<<<<<<<<<< + * self.criterion.update(current.pos) + * */ - __pyx_v_label_count_stride = __pyx_v_self->__pyx_base.label_count_stride; + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->reset(__pyx_v_self->__pyx_base.__pyx_base.criterion); - /* "sklearn/tree/_tree.pyx":1254 - * cdef int* n_classes = self.n_classes - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_left = self.label_count_left # <<<<<<<<<<<<<< - * cdef int* label_count_right = self.label_count_right - * cdef double n_left = self.n_left + /* "sklearn/tree/_tree.pyx":1517 + * # Evaluate split + * self.criterion.reset() + * self.criterion.update(current.pos) # <<<<<<<<<<<<<< + * + * # Reject if min_weight_leaf is not satisfied */ - __pyx_v_label_count_left = __pyx_v_self->__pyx_base.label_count_left; + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->update(__pyx_v_self->__pyx_base.__pyx_base.criterion, __pyx_v_current.pos); - /* "sklearn/tree/_tree.pyx":1255 - * cdef int label_count_stride = self.label_count_stride - * cdef int* label_count_left = self.label_count_left - * cdef int* label_count_right = self.label_count_right # <<<<<<<<<<<<<< - * cdef double n_left = self.n_left - * cdef double n_right = self.n_right + /* "sklearn/tree/_tree.pyx":1520 + * + * # Reject if min_weight_leaf is not satisfied + * if ((self.criterion.weighted_n_left < min_weight_leaf) or # <<<<<<<<<<<<<< + * (self.criterion.weighted_n_right < min_weight_leaf)): + * continue */ - __pyx_v_label_count_right = __pyx_v_self->__pyx_base.label_count_right; + __pyx_t_6 = ((__pyx_v_self->__pyx_base.__pyx_base.criterion->weighted_n_left < __pyx_v_min_weight_leaf) != 0); + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L21_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":1256 - * cdef int* label_count_left = self.label_count_left - * cdef int* label_count_right = self.label_count_right - * cdef double n_left = self.n_left # <<<<<<<<<<<<<< - * cdef double n_right = self.n_right + /* "sklearn/tree/_tree.pyx":1521 + * # Reject if min_weight_leaf is not satisfied + * if ((self.criterion.weighted_n_left < min_weight_leaf) or + * (self.criterion.weighted_n_right < min_weight_leaf)): # <<<<<<<<<<<<<< + * continue * */ - __pyx_v_n_left = ((double)__pyx_v_self->__pyx_base.n_left); + __pyx_t_6 = ((__pyx_v_self->__pyx_base.__pyx_base.criterion->weighted_n_right < __pyx_v_min_weight_leaf) != 0); + __pyx_t_5 = __pyx_t_6; + __pyx_L21_bool_binop_done:; + if (__pyx_t_5) { - /* "sklearn/tree/_tree.pyx":1257 - * cdef int* label_count_right = self.label_count_right - * cdef double n_left = self.n_left - * cdef double n_right = self.n_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1522 + * if ((self.criterion.weighted_n_left < min_weight_leaf) or + * (self.criterion.weighted_n_right < min_weight_leaf)): + * continue # <<<<<<<<<<<<<< * - * cdef double total = 0.0 + * current.improvement = self.criterion.impurity_improvement(impurity) */ - __pyx_v_n_right = ((double)__pyx_v_self->__pyx_base.n_right); + goto __pyx_L3_continue; + } - /* "sklearn/tree/_tree.pyx":1259 - * cdef double n_right = self.n_right + /* "sklearn/tree/_tree.pyx":1524 + * continue * - * cdef double total = 0.0 # <<<<<<<<<<<<<< - * cdef double H_left - * cdef double H_right + * current.improvement = self.criterion.impurity_improvement(impurity) # <<<<<<<<<<<<<< + * + * if current.improvement > best.improvement: */ - __pyx_v_total = 0.0; + __pyx_v_current.improvement = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->impurity_improvement(__pyx_v_self->__pyx_base.__pyx_base.criterion, __pyx_v_impurity); - /* "sklearn/tree/_tree.pyx":1265 - * cdef double e1, e2 + /* "sklearn/tree/_tree.pyx":1526 + * current.improvement = self.criterion.impurity_improvement(impurity) * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * H_left = 0.0 - * H_right = 0.0 + * if current.improvement > best.improvement: # <<<<<<<<<<<<<< + * self.criterion.children_impurity(¤t.impurity_left, + * ¤t.impurity_right) */ - __pyx_t_1 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_1; __pyx_v_k++) { + __pyx_t_5 = ((__pyx_v_current.improvement > __pyx_v_best.improvement) != 0); + if (__pyx_t_5) { - /* "sklearn/tree/_tree.pyx":1266 + /* "sklearn/tree/_tree.pyx":1527 * - * for k from 0 <= k < n_outputs: - * H_left = 0.0 # <<<<<<<<<<<<<< - * H_right = 0.0 + * if current.improvement > best.improvement: + * self.criterion.children_impurity(¤t.impurity_left, # <<<<<<<<<<<<<< + * ¤t.impurity_right) + * best = current # copy + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->children_impurity(__pyx_v_self->__pyx_base.__pyx_base.criterion, (&__pyx_v_current.impurity_left), (&__pyx_v_current.impurity_right)); + + /* "sklearn/tree/_tree.pyx":1529 + * self.criterion.children_impurity(¤t.impurity_left, + * ¤t.impurity_right) + * best = current # copy # <<<<<<<<<<<<<< * + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] */ - __pyx_v_H_left = 0.0; + __pyx_v_best = __pyx_v_current; + goto __pyx_L23; + } + __pyx_L23:; + } + __pyx_L12:; + } + __pyx_L8:; + __pyx_L3_continue:; + } - /* "sklearn/tree/_tree.pyx":1267 - * for k from 0 <= k < n_outputs: - * H_left = 0.0 - * H_right = 0.0 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1532 * - * for c from 0 <= c < n_classes[k]: + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + * if best.pos < end and current.feature != best.feature: # <<<<<<<<<<<<<< + * partition_end = end + * p = start */ - __pyx_v_H_right = 0.0; + __pyx_t_6 = ((__pyx_v_best.pos < __pyx_v_end) != 0); + if (__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L25_bool_binop_done; + } + __pyx_t_6 = ((__pyx_v_current.feature != __pyx_v_best.feature) != 0); + __pyx_t_5 = __pyx_t_6; + __pyx_L25_bool_binop_done:; + if (__pyx_t_5) { - /* "sklearn/tree/_tree.pyx":1269 - * H_right = 0.0 + /* "sklearn/tree/_tree.pyx":1533 + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + * if best.pos < end and current.feature != best.feature: + * partition_end = end # <<<<<<<<<<<<<< + * p = start * - * for c from 0 <= c < n_classes[k]: # <<<<<<<<<<<<<< - * if label_count_left[k * label_count_stride + c] > 0: - * H_left -= ((label_count_left[k * label_count_stride + c] / n_left) * log(label_count_left[k * label_count_stride + c] / n_left)) */ - __pyx_t_2 = (__pyx_v_n_classes[__pyx_v_k]); - for (__pyx_v_c = 0; __pyx_v_c < __pyx_t_2; __pyx_v_c++) { + __pyx_v_partition_end = __pyx_v_end; - /* "sklearn/tree/_tree.pyx":1270 + /* "sklearn/tree/_tree.pyx":1534 + * if best.pos < end and current.feature != best.feature: + * partition_end = end + * p = start # <<<<<<<<<<<<<< * - * for c from 0 <= c < n_classes[k]: - * if label_count_left[k * label_count_stride + c] > 0: # <<<<<<<<<<<<<< - * H_left -= ((label_count_left[k * label_count_stride + c] / n_left) * log(label_count_left[k * label_count_stride + c] / n_left)) + * while p < partition_end: + */ + __pyx_v_p = __pyx_v_start; + + /* "sklearn/tree/_tree.pyx":1536 + * p = start * + * while p < partition_end: # <<<<<<<<<<<<<< + * if X[X_sample_stride * samples[p] + + * X_fx_stride * best.feature] <= best.threshold: */ - __pyx_t_3 = ((__pyx_v_label_count_left[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]) > 0); - if (__pyx_t_3) { + while (1) { + __pyx_t_5 = ((__pyx_v_p < __pyx_v_partition_end) != 0); + if (!__pyx_t_5) break; - /* "sklearn/tree/_tree.pyx":1271 - * for c from 0 <= c < n_classes[k]: - * if label_count_left[k * label_count_stride + c] > 0: - * H_left -= ((label_count_left[k * label_count_stride + c] / n_left) * log(label_count_left[k * label_count_stride + c] / n_left)) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1538 + * while p < partition_end: + * if X[X_sample_stride * samples[p] + + * X_fx_stride * best.feature] <= best.threshold: # <<<<<<<<<<<<<< + * p += 1 * - * if self.label_count_right[k * label_count_stride + c] > 0: */ - __pyx_v_H_left = (__pyx_v_H_left - (((__pyx_v_label_count_left[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]) / __pyx_v_n_left) * log(((__pyx_v_label_count_left[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]) / __pyx_v_n_left)))); - goto __pyx_L7; + __pyx_t_5 = (((__pyx_v_X[((__pyx_v_X_sample_stride * (__pyx_v_samples[__pyx_v_p])) + (__pyx_v_X_fx_stride * __pyx_v_best.feature))]) <= __pyx_v_best.threshold) != 0); + if (__pyx_t_5) { + + /* "sklearn/tree/_tree.pyx":1539 + * if X[X_sample_stride * samples[p] + + * X_fx_stride * best.feature] <= best.threshold: + * p += 1 # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_v_p = (__pyx_v_p + 1); + goto __pyx_L29; } - __pyx_L7:; + /*else*/ { - /* "sklearn/tree/_tree.pyx":1273 - * H_left -= ((label_count_left[k * label_count_stride + c] / n_left) * log(label_count_left[k * label_count_stride + c] / n_left)) + /* "sklearn/tree/_tree.pyx":1542 + * + * else: + * partition_end -= 1 # <<<<<<<<<<<<<< * - * if self.label_count_right[k * label_count_stride + c] > 0: # <<<<<<<<<<<<<< - * H_right -= ((label_count_right[k * label_count_stride + c] / n_right) * log(label_count_right[k * label_count_stride + c] / n_right)) + * tmp = samples[partition_end] + */ + __pyx_v_partition_end = (__pyx_v_partition_end - 1); + + /* "sklearn/tree/_tree.pyx":1544 + * partition_end -= 1 * + * tmp = samples[partition_end] # <<<<<<<<<<<<<< + * samples[partition_end] = samples[p] + * samples[p] = tmp */ - __pyx_t_3 = ((__pyx_v_self->__pyx_base.label_count_right[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]) > 0); - if (__pyx_t_3) { + __pyx_v_tmp = (__pyx_v_samples[__pyx_v_partition_end]); - /* "sklearn/tree/_tree.pyx":1274 + /* "sklearn/tree/_tree.pyx":1545 * - * if self.label_count_right[k * label_count_stride + c] > 0: - * H_right -= ((label_count_right[k * label_count_stride + c] / n_right) * log(label_count_right[k * label_count_stride + c] / n_right)) # <<<<<<<<<<<<<< + * tmp = samples[partition_end] + * samples[partition_end] = samples[p] # <<<<<<<<<<<<<< + * samples[p] = tmp * - * e1 = (n_left / n_samples) * H_left */ - __pyx_v_H_right = (__pyx_v_H_right - (((__pyx_v_label_count_right[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]) / __pyx_v_n_right) * log(((__pyx_v_label_count_right[((__pyx_v_k * __pyx_v_label_count_stride) + __pyx_v_c)]) / __pyx_v_n_right)))); - goto __pyx_L8; + (__pyx_v_samples[__pyx_v_partition_end]) = (__pyx_v_samples[__pyx_v_p]); + + /* "sklearn/tree/_tree.pyx":1546 + * tmp = samples[partition_end] + * samples[partition_end] = samples[p] + * samples[p] = tmp # <<<<<<<<<<<<<< + * + * # Respect invariant for constant features: the original order of + */ + (__pyx_v_samples[__pyx_v_p]) = __pyx_v_tmp; } - __pyx_L8:; + __pyx_L29:; } + goto __pyx_L24; + } + __pyx_L24:; - /* "sklearn/tree/_tree.pyx":1276 - * H_right -= ((label_count_right[k * label_count_stride + c] / n_right) * log(label_count_right[k * label_count_stride + c] / n_right)) - * - * e1 = (n_left / n_samples) * H_left # <<<<<<<<<<<<<< - * e2 = (n_right / n_samples) * H_right + /* "sklearn/tree/_tree.pyx":1551 + * # element in features[:n_known_constants] must be preserved for sibling + * # and child nodes + * memcpy(features, constant_features, sizeof(SIZE_t) * n_known_constants) # <<<<<<<<<<<<<< * + * # Copy newly found constant features */ - __pyx_v_e1 = ((__pyx_v_n_left / __pyx_v_n_samples) * __pyx_v_H_left); + memcpy(__pyx_v_features, __pyx_v_constant_features, ((sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)) * __pyx_v_n_known_constants)); - /* "sklearn/tree/_tree.pyx":1277 - * - * e1 = (n_left / n_samples) * H_left - * e2 = (n_right / n_samples) * H_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1554 * - * total += e1 + e2 + * # Copy newly found constant features + * memcpy(constant_features + n_known_constants, # <<<<<<<<<<<<<< + * features + n_known_constants, + * sizeof(SIZE_t) * n_found_constants) */ - __pyx_v_e2 = ((__pyx_v_n_right / __pyx_v_n_samples) * __pyx_v_H_right); + memcpy((__pyx_v_constant_features + __pyx_v_n_known_constants), (__pyx_v_features + __pyx_v_n_known_constants), ((sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)) * __pyx_v_n_found_constants)); - /* "sklearn/tree/_tree.pyx":1279 - * e2 = (n_right / n_samples) * H_right + /* "sklearn/tree/_tree.pyx":1559 * - * total += e1 + e2 # <<<<<<<<<<<<<< + * # Return values + * split[0] = best # <<<<<<<<<<<<<< + * n_constant_features[0] = n_total_constants * - * return total / n_outputs */ - __pyx_v_total = (__pyx_v_total + (__pyx_v_e1 + __pyx_v_e2)); - } + (__pyx_v_split[0]) = __pyx_v_best; - /* "sklearn/tree/_tree.pyx":1281 - * total += e1 + e2 + /* "sklearn/tree/_tree.pyx":1560 + * # Return values + * split[0] = best + * n_constant_features[0] = n_total_constants # <<<<<<<<<<<<<< * - * return total / n_outputs # <<<<<<<<<<<<<< * + */ + (__pyx_v_n_constant_features[0]) = __pyx_v_n_total_constants; + + /* "sklearn/tree/_tree.pyx":1370 + * self.random_state), self.__getstate__()) * + * cdef void node_split(self, double impurity, SplitRecord* split, # <<<<<<<<<<<<<< + * SIZE_t* n_constant_features) nogil: + * """Find the best random split on node samples[start:end].""" */ - __pyx_r = (__pyx_v_total / __pyx_v_n_outputs); - goto __pyx_L0; - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; + /* function exit code */ } +/* "sklearn/tree/_tree.pyx":1573 + * cdef unsigned char* sample_mask + * + * def __cinit__(self, Criterion criterion, SIZE_t max_features, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, + * double min_weight_leaf, + */ + /* Python wrapper */ -static int __pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - int __pyx_v_n_outputs; +static int __pyx_pw_7sklearn_4tree_5_tree_19PresortBestSplitter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_19PresortBestSplitter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion = 0; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + CYTHON_UNUSED double __pyx_v_min_weight_leaf; + CYTHON_UNUSED PyObject *__pyx_v_random_state = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_outputs,0}; - PyObject* values[1] = {0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_criterion,&__pyx_n_s_max_features,&__pyx_n_s_min_samples_leaf,&__pyx_n_s_min_weight_leaf,&__pyx_n_s_random_state,0}; + PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; @@ -11608,561 +12824,328 @@ static int __pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_1__cinit__(PyObj kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_outputs)) != 0)) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_criterion)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_features)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1573; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_samples_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1573; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_weight_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1573; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random_state)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1573; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1347; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1573; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); } - __pyx_v_n_outputs = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_outputs == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1347; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)values[0]); + __pyx_v_max_features = __Pyx_PyInt_As_Py_intptr_t(values[1]); if (unlikely((__pyx_v_max_features == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1573; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_samples_leaf = __Pyx_PyInt_As_Py_intptr_t(values[2]); if (unlikely((__pyx_v_min_samples_leaf == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1574; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_weight_leaf = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_min_weight_leaf == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1575; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_random_state = values[4]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1347; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1573; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.tree._tree.RegressionCriterion.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.tree._tree.PresortBestSplitter.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self), __pyx_v_n_outputs); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_criterion), __pyx_ptype_7sklearn_4tree_5_tree_Criterion, 1, "criterion", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_19PresortBestSplitter___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *)__pyx_v_self), __pyx_v_criterion, __pyx_v_max_features, __pyx_v_min_samples_leaf, __pyx_v_min_weight_leaf, __pyx_v_random_state); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pyx":1347 - * cdef int n_left - * - * def __cinit__(self, int n_outputs): # <<<<<<<<<<<<<< - * """Constructor.""" - * cdef int k = 0 - */ - -static int __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, int __pyx_v_n_outputs) { - CYTHON_UNUSED int __pyx_v_k; +static int __pyx_pf_7sklearn_4tree_5_tree_19PresortBestSplitter___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *__pyx_v_self, CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, CYTHON_UNUSED double __pyx_v_min_weight_leaf, CYTHON_UNUSED PyObject *__pyx_v_random_state) { int __pyx_r; __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); - /* "sklearn/tree/_tree.pyx":1349 - * def __cinit__(self, int n_outputs): - * """Constructor.""" - * cdef int k = 0 # <<<<<<<<<<<<<< - * - * self.n_outputs = n_outputs + /* "sklearn/tree/_tree.pyx":1578 + * object random_state): + * # Initialize pointers + * self.X_old = NULL # <<<<<<<<<<<<<< + * self.X_argsorted_ptr = NULL + * self.X_argsorted_stride = 0 */ - __pyx_v_k = 0; + __pyx_v_self->X_old = NULL; - /* "sklearn/tree/_tree.pyx":1351 - * cdef int k = 0 - * - * self.n_outputs = n_outputs # <<<<<<<<<<<<<< - * - * self.n_samples = 0 - */ - __pyx_v_self->n_outputs = __pyx_v_n_outputs; - - /* "sklearn/tree/_tree.pyx":1353 - * self.n_outputs = n_outputs - * - * self.n_samples = 0 # <<<<<<<<<<<<<< - * self.n_left = 0 - * self.n_right = 0 - */ - __pyx_v_self->n_samples = 0; - - /* "sklearn/tree/_tree.pyx":1354 - * - * self.n_samples = 0 - * self.n_left = 0 # <<<<<<<<<<<<<< - * self.n_right = 0 - * - */ - __pyx_v_self->n_left = 0; - - /* "sklearn/tree/_tree.pyx":1355 - * self.n_samples = 0 - * self.n_left = 0 - * self.n_right = 0 # <<<<<<<<<<<<<< - * - * # Allocate - */ - __pyx_v_self->n_right = 0; - - /* "sklearn/tree/_tree.pyx":1358 - * - * # Allocate - * self.mean_left = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< - * self.mean_right = calloc(n_outputs, sizeof(double)) - * self.mean_init = calloc(n_outputs, sizeof(double)) - */ - __pyx_v_self->mean_left = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - - /* "sklearn/tree/_tree.pyx":1359 - * # Allocate - * self.mean_left = calloc(n_outputs, sizeof(double)) - * self.mean_right = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< - * self.mean_init = calloc(n_outputs, sizeof(double)) - * self.sq_sum_left = calloc(n_outputs, sizeof(double)) - */ - __pyx_v_self->mean_right = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - - /* "sklearn/tree/_tree.pyx":1360 - * self.mean_left = calloc(n_outputs, sizeof(double)) - * self.mean_right = calloc(n_outputs, sizeof(double)) - * self.mean_init = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< - * self.sq_sum_left = calloc(n_outputs, sizeof(double)) - * self.sq_sum_right = calloc(n_outputs, sizeof(double)) - */ - __pyx_v_self->mean_init = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - - /* "sklearn/tree/_tree.pyx":1361 - * self.mean_right = calloc(n_outputs, sizeof(double)) - * self.mean_init = calloc(n_outputs, sizeof(double)) - * self.sq_sum_left = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< - * self.sq_sum_right = calloc(n_outputs, sizeof(double)) - * self.sq_sum_init = calloc(n_outputs, sizeof(double)) - */ - __pyx_v_self->sq_sum_left = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - - /* "sklearn/tree/_tree.pyx":1362 - * self.mean_init = calloc(n_outputs, sizeof(double)) - * self.sq_sum_left = calloc(n_outputs, sizeof(double)) - * self.sq_sum_right = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< - * self.sq_sum_init = calloc(n_outputs, sizeof(double)) - * self.var_left = calloc(n_outputs, sizeof(double)) - */ - __pyx_v_self->sq_sum_right = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - - /* "sklearn/tree/_tree.pyx":1363 - * self.sq_sum_left = calloc(n_outputs, sizeof(double)) - * self.sq_sum_right = calloc(n_outputs, sizeof(double)) - * self.sq_sum_init = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< - * self.var_left = calloc(n_outputs, sizeof(double)) - * self.var_right = calloc(n_outputs, sizeof(double)) - */ - __pyx_v_self->sq_sum_init = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - - /* "sklearn/tree/_tree.pyx":1364 - * self.sq_sum_right = calloc(n_outputs, sizeof(double)) - * self.sq_sum_init = calloc(n_outputs, sizeof(double)) - * self.var_left = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< - * self.var_right = calloc(n_outputs, sizeof(double)) - * - */ - __pyx_v_self->var_left = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); - - /* "sklearn/tree/_tree.pyx":1365 - * self.sq_sum_init = calloc(n_outputs, sizeof(double)) - * self.var_left = calloc(n_outputs, sizeof(double)) - * self.var_right = calloc(n_outputs, sizeof(double)) # <<<<<<<<<<<<<< - * - * # Check for allocation errors + /* "sklearn/tree/_tree.pyx":1579 + * # Initialize pointers + * self.X_old = NULL + * self.X_argsorted_ptr = NULL # <<<<<<<<<<<<<< + * self.X_argsorted_stride = 0 + * self.sample_mask = NULL */ - __pyx_v_self->var_right = ((double *)calloc(__pyx_v_n_outputs, (sizeof(double)))); + __pyx_v_self->X_argsorted_ptr = NULL; - /* "sklearn/tree/_tree.pyx":1368 + /* "sklearn/tree/_tree.pyx":1580 + * self.X_old = NULL + * self.X_argsorted_ptr = NULL + * self.X_argsorted_stride = 0 # <<<<<<<<<<<<<< + * self.sample_mask = NULL * - * # Check for allocation errors - * if self.mean_left == NULL or \ # <<<<<<<<<<<<<< - * self.mean_right == NULL or \ - * self.mean_init == NULL or \ - */ - __pyx_t_1 = (__pyx_v_self->mean_left == NULL); - if (!__pyx_t_1) { - - /* "sklearn/tree/_tree.pyx":1369 - * # Check for allocation errors - * if self.mean_left == NULL or \ - * self.mean_right == NULL or \ # <<<<<<<<<<<<<< - * self.mean_init == NULL or \ - * self.sq_sum_left == NULL or \ - */ - __pyx_t_2 = (__pyx_v_self->mean_right == NULL); - if (!__pyx_t_2) { - - /* "sklearn/tree/_tree.pyx":1370 - * if self.mean_left == NULL or \ - * self.mean_right == NULL or \ - * self.mean_init == NULL or \ # <<<<<<<<<<<<<< - * self.sq_sum_left == NULL or \ - * self.sq_sum_right == NULL or \ - */ - __pyx_t_3 = (__pyx_v_self->mean_init == NULL); - if (!__pyx_t_3) { - - /* "sklearn/tree/_tree.pyx":1371 - * self.mean_right == NULL or \ - * self.mean_init == NULL or \ - * self.sq_sum_left == NULL or \ # <<<<<<<<<<<<<< - * self.sq_sum_right == NULL or \ - * self.sq_sum_init == NULL or \ - */ - __pyx_t_4 = (__pyx_v_self->sq_sum_left == NULL); - if (!__pyx_t_4) { - - /* "sklearn/tree/_tree.pyx":1372 - * self.mean_init == NULL or \ - * self.sq_sum_left == NULL or \ - * self.sq_sum_right == NULL or \ # <<<<<<<<<<<<<< - * self.sq_sum_init == NULL or \ - * self.var_left == NULL or \ - */ - __pyx_t_5 = (__pyx_v_self->sq_sum_right == NULL); - if (!__pyx_t_5) { - - /* "sklearn/tree/_tree.pyx":1373 - * self.sq_sum_left == NULL or \ - * self.sq_sum_right == NULL or \ - * self.sq_sum_init == NULL or \ # <<<<<<<<<<<<<< - * self.var_left == NULL or \ - * self.var_right == NULL: - */ - __pyx_t_6 = (__pyx_v_self->sq_sum_init == NULL); - if (!__pyx_t_6) { - - /* "sklearn/tree/_tree.pyx":1374 - * self.sq_sum_right == NULL or \ - * self.sq_sum_init == NULL or \ - * self.var_left == NULL or \ # <<<<<<<<<<<<<< - * self.var_right == NULL: - * free(self.mean_left) - */ - __pyx_t_7 = (__pyx_v_self->var_left == NULL); - if (!__pyx_t_7) { - - /* "sklearn/tree/_tree.pyx":1375 - * self.sq_sum_init == NULL or \ - * self.var_left == NULL or \ - * self.var_right == NULL: # <<<<<<<<<<<<<< - * free(self.mean_left) - * free(self.mean_right) - */ - __pyx_t_8 = (__pyx_v_self->var_right == NULL); - __pyx_t_9 = __pyx_t_8; - } else { - __pyx_t_9 = __pyx_t_7; - } - __pyx_t_7 = __pyx_t_9; - } else { - __pyx_t_7 = __pyx_t_6; - } - __pyx_t_6 = __pyx_t_7; - } else { - __pyx_t_6 = __pyx_t_5; - } - __pyx_t_5 = __pyx_t_6; - } else { - __pyx_t_5 = __pyx_t_4; - } - __pyx_t_4 = __pyx_t_5; - } else { - __pyx_t_4 = __pyx_t_3; - } - __pyx_t_3 = __pyx_t_4; - } else { - __pyx_t_3 = __pyx_t_2; - } - __pyx_t_2 = __pyx_t_3; - } else { - __pyx_t_2 = __pyx_t_1; - } - if (__pyx_t_2) { - - /* "sklearn/tree/_tree.pyx":1376 - * self.var_left == NULL or \ - * self.var_right == NULL: - * free(self.mean_left) # <<<<<<<<<<<<<< - * free(self.mean_right) - * free(self.mean_init) - */ - free(__pyx_v_self->mean_left); - - /* "sklearn/tree/_tree.pyx":1377 - * self.var_right == NULL: - * free(self.mean_left) - * free(self.mean_right) # <<<<<<<<<<<<<< - * free(self.mean_init) - * free(self.sq_sum_left) - */ - free(__pyx_v_self->mean_right); - - /* "sklearn/tree/_tree.pyx":1378 - * free(self.mean_left) - * free(self.mean_right) - * free(self.mean_init) # <<<<<<<<<<<<<< - * free(self.sq_sum_left) - * free(self.sq_sum_right) - */ - free(__pyx_v_self->mean_init); - - /* "sklearn/tree/_tree.pyx":1379 - * free(self.mean_right) - * free(self.mean_init) - * free(self.sq_sum_left) # <<<<<<<<<<<<<< - * free(self.sq_sum_right) - * free(self.sq_sum_init) - */ - free(__pyx_v_self->sq_sum_left); - - /* "sklearn/tree/_tree.pyx":1380 - * free(self.mean_init) - * free(self.sq_sum_left) - * free(self.sq_sum_right) # <<<<<<<<<<<<<< - * free(self.sq_sum_init) - * free(self.var_left) - */ - free(__pyx_v_self->sq_sum_right); - - /* "sklearn/tree/_tree.pyx":1381 - * free(self.sq_sum_left) - * free(self.sq_sum_right) - * free(self.sq_sum_init) # <<<<<<<<<<<<<< - * free(self.var_left) - * free(self.var_right) - */ - free(__pyx_v_self->sq_sum_init); - - /* "sklearn/tree/_tree.pyx":1382 - * free(self.sq_sum_right) - * free(self.sq_sum_init) - * free(self.var_left) # <<<<<<<<<<<<<< - * free(self.var_right) - * raise MemoryError() */ - free(__pyx_v_self->var_left); + __pyx_v_self->X_argsorted_stride = 0; - /* "sklearn/tree/_tree.pyx":1383 - * free(self.sq_sum_init) - * free(self.var_left) - * free(self.var_right) # <<<<<<<<<<<<<< - * raise MemoryError() + /* "sklearn/tree/_tree.pyx":1581 + * self.X_argsorted_ptr = NULL + * self.X_argsorted_stride = 0 + * self.sample_mask = NULL # <<<<<<<<<<<<<< * + * def __dealloc__(self): */ - free(__pyx_v_self->var_right); + __pyx_v_self->sample_mask = NULL; - /* "sklearn/tree/_tree.pyx":1384 - * free(self.var_left) - * free(self.var_right) - * raise MemoryError() # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1573 + * cdef unsigned char* sample_mask * - * def __dealloc__(self): + * def __cinit__(self, Criterion criterion, SIZE_t max_features, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, + * double min_weight_leaf, */ - PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; - } - __pyx_L3:; + /* function exit code */ __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("sklearn.tree._tree.RegressionCriterion.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } +/* "sklearn/tree/_tree.pyx":1583 + * self.sample_mask = NULL + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Destructor.""" + * free(self.sample_mask) + */ + /* Python wrapper */ -static void __pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_3__dealloc__(PyObject *__pyx_v_self) { +static void __pyx_pw_7sklearn_4tree_5_tree_19PresortBestSplitter_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_7sklearn_4tree_5_tree_19PresortBestSplitter_3__dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_2__dealloc__(((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self)); + __pyx_pf_7sklearn_4tree_5_tree_19PresortBestSplitter_2__dealloc__(((struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *)__pyx_v_self)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "sklearn/tree/_tree.pyx":1386 - * raise MemoryError() - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * """Destructor.""" - * free(self.mean_left) - */ - -static void __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self) { +static void __pyx_pf_7sklearn_4tree_5_tree_19PresortBestSplitter_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__", 0); - /* "sklearn/tree/_tree.pyx":1388 + /* "sklearn/tree/_tree.pyx":1585 * def __dealloc__(self): * """Destructor.""" - * free(self.mean_left) # <<<<<<<<<<<<<< - * free(self.mean_right) - * free(self.mean_init) - */ - free(__pyx_v_self->mean_left); - - /* "sklearn/tree/_tree.pyx":1389 - * """Destructor.""" - * free(self.mean_left) - * free(self.mean_right) # <<<<<<<<<<<<<< - * free(self.mean_init) - * free(self.sq_sum_left) - */ - free(__pyx_v_self->mean_right); - - /* "sklearn/tree/_tree.pyx":1390 - * free(self.mean_left) - * free(self.mean_right) - * free(self.mean_init) # <<<<<<<<<<<<<< - * free(self.sq_sum_left) - * free(self.sq_sum_right) - */ - free(__pyx_v_self->mean_init); - - /* "sklearn/tree/_tree.pyx":1391 - * free(self.mean_right) - * free(self.mean_init) - * free(self.sq_sum_left) # <<<<<<<<<<<<<< - * free(self.sq_sum_right) - * free(self.sq_sum_init) - */ - free(__pyx_v_self->sq_sum_left); - - /* "sklearn/tree/_tree.pyx":1392 - * free(self.mean_init) - * free(self.sq_sum_left) - * free(self.sq_sum_right) # <<<<<<<<<<<<<< - * free(self.sq_sum_init) - * free(self.var_left) - */ - free(__pyx_v_self->sq_sum_right); - - /* "sklearn/tree/_tree.pyx":1393 - * free(self.sq_sum_left) - * free(self.sq_sum_right) - * free(self.sq_sum_init) # <<<<<<<<<<<<<< - * free(self.var_left) - * free(self.var_right) - */ - free(__pyx_v_self->sq_sum_init); - - /* "sklearn/tree/_tree.pyx":1394 - * free(self.sq_sum_right) - * free(self.sq_sum_init) - * free(self.var_left) # <<<<<<<<<<<<<< - * free(self.var_right) + * free(self.sample_mask) # <<<<<<<<<<<<<< * + * def __reduce__(self): */ - free(__pyx_v_self->var_left); + free(__pyx_v_self->sample_mask); - /* "sklearn/tree/_tree.pyx":1395 - * free(self.sq_sum_init) - * free(self.var_left) - * free(self.var_right) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1583 + * self.sample_mask = NULL * - * def __reduce__(self): + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Destructor.""" + * free(self.sample_mask) */ - free(__pyx_v_self->var_right); + /* function exit code */ __Pyx_RefNannyFinishContext(); } +/* "sklearn/tree/_tree.pyx":1587 + * free(self.sample_mask) + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (PresortBestSplitter, (self.criterion, + * self.max_features, + */ + /* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19PresortBestSplitter_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19PresortBestSplitter_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_4__reduce__(((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self)); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_19PresortBestSplitter_4__reduce__(((struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *)__pyx_v_self)); + + /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pyx":1397 - * free(self.var_right) - * - * def __reduce__(self): # <<<<<<<<<<<<<< - * return (RegressionCriterion, - * (self.n_outputs,), - */ - -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self) { +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19PresortBestSplitter_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__reduce__", 0); - /* "sklearn/tree/_tree.pyx":1398 + /* "sklearn/tree/_tree.pyx":1588 * * def __reduce__(self): - * return (RegressionCriterion, # <<<<<<<<<<<<<< - * (self.n_outputs,), - * self.__getstate__()) + * return (PresortBestSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, */ __Pyx_XDECREF(__pyx_r); - /* "sklearn/tree/_tree.pyx":1399 + /* "sklearn/tree/_tree.pyx":1589 * def __reduce__(self): - * return (RegressionCriterion, - * (self.n_outputs,), # <<<<<<<<<<<<<< - * self.__getstate__()) - * + * return (PresortBestSplitter, (self.criterion, + * self.max_features, # <<<<<<<<<<<<<< + * self.min_samples_leaf, + * self.min_weight_leaf, */ - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->n_outputs); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.__pyx_base.max_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":1590 + * return (PresortBestSplitter, (self.criterion, + * self.max_features, + * self.min_samples_leaf, # <<<<<<<<<<<<<< + * self.min_weight_leaf, + * self.random_state), self.__getstate__()) + */ + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.__pyx_base.min_samples_leaf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + + /* "sklearn/tree/_tree.pyx":1591 + * self.max_features, + * self.min_samples_leaf, + * self.min_weight_leaf, # <<<<<<<<<<<<<< + * self.random_state), self.__getstate__()) + * + */ + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_self->__pyx_base.__pyx_base.min_weight_leaf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "sklearn/tree/_tree.pyx":1588 + * + * def __reduce__(self): + * return (PresortBestSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, + */ + __pyx_t_4 = PyTuple_New(5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_self->__pyx_base.__pyx_base.random_state); + PyTuple_SET_ITEM(__pyx_t_4, 4, __pyx_v_self->__pyx_base.__pyx_base.random_state); + __Pyx_GIVEREF(__pyx_v_self->__pyx_base.__pyx_base.random_state); __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; - /* "sklearn/tree/_tree.pyx":1400 - * return (RegressionCriterion, - * (self.n_outputs,), - * self.__getstate__()) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1592 + * self.min_samples_leaf, + * self.min_weight_leaf, + * self.random_state), self.__getstate__()) # <<<<<<<<<<<<<< * - * def __getstate__(self): + * cdef void init(self, object X, */ - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_self), __pyx_n_s____getstate__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_getstate); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (__pyx_t_1) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RegressionCriterion))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RegressionCriterion))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RegressionCriterion))); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/tree/_tree.pyx":1588 + * + * def __reduce__(self): + * return (PresortBestSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, + */ + __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_PresortBestSplitter))); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_PresortBestSplitter))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_PresortBestSplitter))); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_2 = 0; + __pyx_t_4 = 0; __pyx_t_3 = 0; - __pyx_r = ((PyObject *)__pyx_t_1); - __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/tree/_tree.pyx":1587 + * free(self.sample_mask) + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (PresortBestSplitter, (self.criterion, + * self.max_features, + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("sklearn.tree._tree.RegressionCriterion.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.PresortBestSplitter.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); @@ -12170,6020 +13153,20670 @@ static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_4__reduce_ return __pyx_r; } -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getstate__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_6__getstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/tree/_tree.pyx":1402 - * self.__getstate__()) - * - * def __getstate__(self): # <<<<<<<<<<<<<< - * return {} +/* "sklearn/tree/_tree.pyx":1594 + * self.random_state), self.__getstate__()) * + * cdef void init(self, object X, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, + * DOUBLE_t* sample_weight) except *: */ -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_6__getstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self) { - PyObject *__pyx_r = NULL; +static void __pyx_f_7sklearn_4tree_5_tree_19PresortBestSplitter_init(struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *__pyx_v_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight) { + void *__pyx_v_sample_mask; + PyArrayObject *__pyx_v_X_ndarray = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_y; + __Pyx_Buffer __pyx_pybuffer_y; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_8; + unsigned char *__pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getstate__", 0); + __Pyx_RefNannySetupContext("init", 0); + __pyx_pybuffer_y.pybuffer.buf = NULL; + __pyx_pybuffer_y.refcount = 0; + __pyx_pybuffernd_y.data = NULL; + __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DOUBLE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1594; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_y.diminfo[1].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_y.diminfo[1].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[1]; - /* "sklearn/tree/_tree.pyx":1403 + /* "sklearn/tree/_tree.pyx":1598 + * DOUBLE_t* sample_weight) except *: * - * def __getstate__(self): - * return {} # <<<<<<<<<<<<<< + * cdef void* sample_mask = NULL # <<<<<<<<<<<<<< * - * def __setstate__(self, d): + * # Call parent initializer */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_r = ((PyObject *)__pyx_t_1); - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.RegressionCriterion.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d); /*proto*/ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate__ (wrapper)", 0); - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_8__setstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self), ((PyObject *)__pyx_v_d)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_v_sample_mask = NULL; -/* "sklearn/tree/_tree.pyx":1405 - * return {} + /* "sklearn/tree/_tree.pyx":1601 * - * def __setstate__(self, d): # <<<<<<<<<<<<<< - * pass + * # Call parent initializer + * BaseDenseSplitter.init(self, X, y, sample_weight) # <<<<<<<<<<<<<< * + * cdef np.ndarray X_ndarray = X */ + __pyx_f_7sklearn_4tree_5_tree_17BaseDenseSplitter_init(((struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter *)__pyx_v_self), __pyx_v_X, ((PyArrayObject *)__pyx_v_y), __pyx_v_sample_weight); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1601; __pyx_clineno = __LINE__; goto __pyx_L1_error;} -static PyObject *__pyx_pf_7sklearn_4tree_5_tree_19RegressionCriterion_8__setstate__(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_d) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate__", 0); - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":1603 + * BaseDenseSplitter.init(self, X, y, sample_weight) + * + * cdef np.ndarray X_ndarray = X # <<<<<<<<<<<<<< + * + * # Pre-sort X + */ + if (!(likely(((__pyx_v_X) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_X, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1603; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_v_X; + __Pyx_INCREF(__pyx_t_1); + __pyx_v_X_ndarray = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; -/* "sklearn/tree/_tree.pyx":1408 - * pass + /* "sklearn/tree/_tree.pyx":1606 * - * cdef void init(self, DOUBLE_t* y, int y_stride, BOOL_t* sample_mask, # <<<<<<<<<<<<<< - * int n_samples, int n_total_samples): - * """Initialise the criterion class; assume all samples + * # Pre-sort X + * if self.X_old != self.X: # <<<<<<<<<<<<<< + * self.X_old = self.X + * self.X_argsorted = np.asfortranarray(np.argsort(X_ndarray, axis=0), */ + __pyx_t_2 = ((__pyx_v_self->X_old != __pyx_v_self->__pyx_base.X) != 0); + if (__pyx_t_2) { -static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_init(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, int __pyx_v_y_stride, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *__pyx_v_sample_mask, int __pyx_v_n_samples, int __pyx_v_n_total_samples) { - double *__pyx_v_mean_left; - double *__pyx_v_mean_right; - double *__pyx_v_mean_init; - double *__pyx_v_sq_sum_left; - double *__pyx_v_sq_sum_right; - double *__pyx_v_sq_sum_init; - double *__pyx_v_var_left; - double *__pyx_v_var_right; - int __pyx_v_n_outputs; - int __pyx_v_k; - int __pyx_v_j; - __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t __pyx_v_y_jk; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - __Pyx_RefNannySetupContext("init", 0); + /* "sklearn/tree/_tree.pyx":1607 + * # Pre-sort X + * if self.X_old != self.X: + * self.X_old = self.X # <<<<<<<<<<<<<< + * self.X_argsorted = np.asfortranarray(np.argsort(X_ndarray, axis=0), + * dtype=np.int32) + */ + __pyx_t_3 = __pyx_v_self->__pyx_base.X; + __pyx_v_self->X_old = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":1413 - * are in the right branch and store the mean and squared - * sum in `self.mean_init` and `self.sq_sum_init`. """ - * cdef double* mean_left = self.mean_left # <<<<<<<<<<<<<< - * cdef double* mean_right = self.mean_right - * cdef double* mean_init = self.mean_init + /* "sklearn/tree/_tree.pyx":1608 + * if self.X_old != self.X: + * self.X_old = self.X + * self.X_argsorted = np.asfortranarray(np.argsort(X_ndarray, axis=0), # <<<<<<<<<<<<<< + * dtype=np.int32) + * self.X_argsorted_ptr = self.X_argsorted.data */ - __pyx_v_mean_left = __pyx_v_self->mean_left; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_asfortranarray); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_argsort); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_X_ndarray)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_X_ndarray)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_X_ndarray)); + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_axis, __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_1, __pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); - /* "sklearn/tree/_tree.pyx":1414 - * sum in `self.mean_init` and `self.sq_sum_init`. """ - * cdef double* mean_left = self.mean_left - * cdef double* mean_right = self.mean_right # <<<<<<<<<<<<<< - * cdef double* mean_init = self.mean_init - * cdef double* sq_sum_left = self.sq_sum_left + /* "sklearn/tree/_tree.pyx":1609 + * self.X_old = self.X + * self.X_argsorted = np.asfortranarray(np.argsort(X_ndarray, axis=0), + * dtype=np.int32) # <<<<<<<<<<<<<< + * self.X_argsorted_ptr = self.X_argsorted.data + * self.X_argsorted_stride = ( self.X_argsorted.strides[1] / */ - __pyx_v_mean_right = __pyx_v_self->mean_right; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_int32); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - /* "sklearn/tree/_tree.pyx":1415 - * cdef double* mean_left = self.mean_left - * cdef double* mean_right = self.mean_right - * cdef double* mean_init = self.mean_init # <<<<<<<<<<<<<< - * cdef double* sq_sum_left = self.sq_sum_left - * cdef double* sq_sum_right = self.sq_sum_right + /* "sklearn/tree/_tree.pyx":1608 + * if self.X_old != self.X: + * self.X_old = self.X + * self.X_argsorted = np.asfortranarray(np.argsort(X_ndarray, axis=0), # <<<<<<<<<<<<<< + * dtype=np.int32) + * self.X_argsorted_ptr = self.X_argsorted.data */ - __pyx_v_mean_init = __pyx_v_self->mean_init; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, __pyx_t_7); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_v_self->X_argsorted); + __Pyx_DECREF(((PyObject *)__pyx_v_self->X_argsorted)); + __pyx_v_self->X_argsorted = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "sklearn/tree/_tree.pyx":1610 + * self.X_argsorted = np.asfortranarray(np.argsort(X_ndarray, axis=0), + * dtype=np.int32) + * self.X_argsorted_ptr = self.X_argsorted.data # <<<<<<<<<<<<<< + * self.X_argsorted_stride = ( self.X_argsorted.strides[1] / + * self.X_argsorted.itemsize) + */ + __pyx_v_self->X_argsorted_ptr = ((__pyx_t_7sklearn_4tree_5_tree_INT32_t *)__pyx_v_self->X_argsorted->data); + + /* "sklearn/tree/_tree.pyx":1612 + * self.X_argsorted_ptr = self.X_argsorted.data + * self.X_argsorted_stride = ( self.X_argsorted.strides[1] / + * self.X_argsorted.itemsize) # <<<<<<<<<<<<<< + * + * self.n_total_samples = X.shape[0] + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->X_argsorted), __pyx_n_s_itemsize); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_8 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_5); if (unlikely((__pyx_t_8 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - /* "sklearn/tree/_tree.pyx":1416 - * cdef double* mean_right = self.mean_right - * cdef double* mean_init = self.mean_init - * cdef double* sq_sum_left = self.sq_sum_left # <<<<<<<<<<<<<< - * cdef double* sq_sum_right = self.sq_sum_right - * cdef double* sq_sum_init = self.sq_sum_init + /* "sklearn/tree/_tree.pyx":1611 + * dtype=np.int32) + * self.X_argsorted_ptr = self.X_argsorted.data + * self.X_argsorted_stride = ( self.X_argsorted.strides[1] / # <<<<<<<<<<<<<< + * self.X_argsorted.itemsize) + * */ - __pyx_v_sq_sum_left = __pyx_v_self->sq_sum_left; + __pyx_v_self->X_argsorted_stride = (((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)(__pyx_v_self->X_argsorted->strides[1])) / ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)__pyx_t_8)); - /* "sklearn/tree/_tree.pyx":1417 - * cdef double* mean_init = self.mean_init - * cdef double* sq_sum_left = self.sq_sum_left - * cdef double* sq_sum_right = self.sq_sum_right # <<<<<<<<<<<<<< - * cdef double* sq_sum_init = self.sq_sum_init - * cdef double* var_left = self.var_left + /* "sklearn/tree/_tree.pyx":1614 + * self.X_argsorted.itemsize) + * + * self.n_total_samples = X.shape[0] # <<<<<<<<<<<<<< + * sample_mask = safe_realloc(&self.sample_mask, self.n_total_samples) + * memset(sample_mask, 0, self.n_total_samples) */ - __pyx_v_sq_sum_right = __pyx_v_self->sq_sum_right; + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = __Pyx_GetItemInt(__pyx_t_5, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1614; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_8 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_7); if (unlikely((__pyx_t_8 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_self->n_total_samples = __pyx_t_8; - /* "sklearn/tree/_tree.pyx":1418 - * cdef double* sq_sum_left = self.sq_sum_left - * cdef double* sq_sum_right = self.sq_sum_right - * cdef double* sq_sum_init = self.sq_sum_init # <<<<<<<<<<<<<< - * cdef double* var_left = self.var_left - * cdef double* var_right = self.var_right + /* "sklearn/tree/_tree.pyx":1615 + * + * self.n_total_samples = X.shape[0] + * sample_mask = safe_realloc(&self.sample_mask, self.n_total_samples) # <<<<<<<<<<<<<< + * memset(sample_mask, 0, self.n_total_samples) + * */ - __pyx_v_sq_sum_init = __pyx_v_self->sq_sum_init; + __pyx_t_9 = __pyx_fuse_2__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_self->sample_mask), __pyx_v_self->n_total_samples); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1615; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_sample_mask = __pyx_t_9; - /* "sklearn/tree/_tree.pyx":1419 - * cdef double* sq_sum_right = self.sq_sum_right - * cdef double* sq_sum_init = self.sq_sum_init - * cdef double* var_left = self.var_left # <<<<<<<<<<<<<< - * cdef double* var_right = self.var_right - * cdef int n_outputs = self.n_outputs + /* "sklearn/tree/_tree.pyx":1616 + * self.n_total_samples = X.shape[0] + * sample_mask = safe_realloc(&self.sample_mask, self.n_total_samples) + * memset(sample_mask, 0, self.n_total_samples) # <<<<<<<<<<<<<< + * + * cdef void node_split(self, double impurity, SplitRecord* split, */ - __pyx_v_var_left = __pyx_v_self->var_left; + memset(__pyx_v_sample_mask, 0, __pyx_v_self->n_total_samples); + goto __pyx_L3; + } + __pyx_L3:; - /* "sklearn/tree/_tree.pyx":1420 - * cdef double* sq_sum_init = self.sq_sum_init - * cdef double* var_left = self.var_left - * cdef double* var_right = self.var_right # <<<<<<<<<<<<<< - * cdef int n_outputs = self.n_outputs + /* "sklearn/tree/_tree.pyx":1594 + * self.random_state), self.__getstate__()) * + * cdef void init(self, object X, # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, + * DOUBLE_t* sample_weight) except *: */ - __pyx_v_var_right = __pyx_v_self->var_right; - /* "sklearn/tree/_tree.pyx":1421 - * cdef double* var_left = self.var_left - * cdef double* var_right = self.var_right - * cdef int n_outputs = self.n_outputs # <<<<<<<<<<<<<< + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.tree._tree.PresortBestSplitter.init", __pyx_clineno, __pyx_lineno, __pyx_filename); + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_X_ndarray); + __Pyx_RefNannyFinishContext(); +} + +/* "sklearn/tree/_tree.pyx":1618 + * memset(sample_mask, 0, self.n_total_samples) + * + * cdef void node_split(self, double impurity, SplitRecord* split, # <<<<<<<<<<<<<< + * SIZE_t* n_constant_features) nogil: + * """Find the best split on node samples[start:end].""" + */ + +static void __pyx_f_7sklearn_4tree_5_tree_19PresortBestSplitter_node_split(struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *__pyx_v_self, double __pyx_v_impurity, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_constant_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_features; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_X_sample_stride; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_X_fx_stride; + __pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_v_X_argsorted; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_X_argsorted_stride; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_total_samples; + unsigned char *__pyx_v_sample_mask; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + double __pyx_v_min_weight_leaf; + __pyx_t_7sklearn_4tree_5_tree_UINT32_t *__pyx_v_random_state; + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_best; + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_current; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_f_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_f_j; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_found_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_drawn_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_known_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_total_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_visited_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_partition_end; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_j; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_tmp; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_t_4; + unsigned char *__pyx_t_5; + double __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + + /* "sklearn/tree/_tree.pyx":1622 + * """Find the best split on node samples[start:end].""" + * # Find the best split + * cdef SIZE_t* samples = self.samples # <<<<<<<<<<<<<< + * cdef SIZE_t start = self.start + * cdef SIZE_t end = self.end + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.samples; + __pyx_v_samples = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":1623 + * # Find the best split + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t start = self.start # <<<<<<<<<<<<<< + * cdef SIZE_t end = self.end * - * cdef int k = 0 */ - __pyx_v_n_outputs = __pyx_v_self->n_outputs; + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.start; + __pyx_v_start = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1423 - * cdef int n_outputs = self.n_outputs + /* "sklearn/tree/_tree.pyx":1624 + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t start = self.start + * cdef SIZE_t end = self.end # <<<<<<<<<<<<<< * - * cdef int k = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t* features = self.features + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.end; + __pyx_v_end = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":1626 + * cdef SIZE_t end = self.end * - * for k from 0 <= k < n_outputs: + * cdef SIZE_t* features = self.features # <<<<<<<<<<<<<< + * cdef SIZE_t* constant_features = self.constant_features + * cdef SIZE_t n_features = self.n_features */ - __pyx_v_k = 0; + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.features; + __pyx_v_features = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":1425 - * cdef int k = 0 + /* "sklearn/tree/_tree.pyx":1627 + * + * cdef SIZE_t* features = self.features + * cdef SIZE_t* constant_features = self.constant_features # <<<<<<<<<<<<<< + * cdef SIZE_t n_features = self.n_features * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * mean_left[k] = 0.0 - * mean_right[k] = 0.0 */ - __pyx_t_1 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_1; __pyx_v_k++) { + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.constant_features; + __pyx_v_constant_features = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":1426 + /* "sklearn/tree/_tree.pyx":1628 + * cdef SIZE_t* features = self.features + * cdef SIZE_t* constant_features = self.constant_features + * cdef SIZE_t n_features = self.n_features # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: - * mean_left[k] = 0.0 # <<<<<<<<<<<<<< - * mean_right[k] = 0.0 - * mean_init[k] = 0.0 + * cdef DTYPE_t* X = self.X */ - (__pyx_v_mean_left[__pyx_v_k]) = 0.0; + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.n_features; + __pyx_v_n_features = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1427 - * for k from 0 <= k < n_outputs: - * mean_left[k] = 0.0 - * mean_right[k] = 0.0 # <<<<<<<<<<<<<< - * mean_init[k] = 0.0 - * sq_sum_right[k] = 0.0 + /* "sklearn/tree/_tree.pyx":1630 + * cdef SIZE_t n_features = self.n_features + * + * cdef DTYPE_t* X = self.X # <<<<<<<<<<<<<< + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t X_sample_stride = self.X_sample_stride */ - (__pyx_v_mean_right[__pyx_v_k]) = 0.0; + __pyx_t_3 = __pyx_v_self->__pyx_base.X; + __pyx_v_X = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":1428 - * mean_left[k] = 0.0 - * mean_right[k] = 0.0 - * mean_init[k] = 0.0 # <<<<<<<<<<<<<< - * sq_sum_right[k] = 0.0 - * sq_sum_left[k] = 0.0 + /* "sklearn/tree/_tree.pyx":1631 + * + * cdef DTYPE_t* X = self.X + * cdef DTYPE_t* Xf = self.feature_values # <<<<<<<<<<<<<< + * cdef SIZE_t X_sample_stride = self.X_sample_stride + * cdef SIZE_t X_fx_stride = self.X_fx_stride */ - (__pyx_v_mean_init[__pyx_v_k]) = 0.0; + __pyx_t_3 = __pyx_v_self->__pyx_base.__pyx_base.feature_values; + __pyx_v_Xf = __pyx_t_3; - /* "sklearn/tree/_tree.pyx":1429 - * mean_right[k] = 0.0 - * mean_init[k] = 0.0 - * sq_sum_right[k] = 0.0 # <<<<<<<<<<<<<< - * sq_sum_left[k] = 0.0 - * sq_sum_init[k] = 0.0 + /* "sklearn/tree/_tree.pyx":1632 + * cdef DTYPE_t* X = self.X + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t X_sample_stride = self.X_sample_stride # <<<<<<<<<<<<<< + * cdef SIZE_t X_fx_stride = self.X_fx_stride + * cdef INT32_t* X_argsorted = self.X_argsorted_ptr */ - (__pyx_v_sq_sum_right[__pyx_v_k]) = 0.0; + __pyx_t_2 = __pyx_v_self->__pyx_base.X_sample_stride; + __pyx_v_X_sample_stride = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1430 - * mean_init[k] = 0.0 - * sq_sum_right[k] = 0.0 - * sq_sum_left[k] = 0.0 # <<<<<<<<<<<<<< - * sq_sum_init[k] = 0.0 - * var_left[k] = 0.0 + /* "sklearn/tree/_tree.pyx":1633 + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t X_sample_stride = self.X_sample_stride + * cdef SIZE_t X_fx_stride = self.X_fx_stride # <<<<<<<<<<<<<< + * cdef INT32_t* X_argsorted = self.X_argsorted_ptr + * cdef SIZE_t X_argsorted_stride = self.X_argsorted_stride */ - (__pyx_v_sq_sum_left[__pyx_v_k]) = 0.0; + __pyx_t_2 = __pyx_v_self->__pyx_base.X_fx_stride; + __pyx_v_X_fx_stride = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1431 - * sq_sum_right[k] = 0.0 - * sq_sum_left[k] = 0.0 - * sq_sum_init[k] = 0.0 # <<<<<<<<<<<<<< - * var_left[k] = 0.0 - * var_right[k] = 0.0 + /* "sklearn/tree/_tree.pyx":1634 + * cdef SIZE_t X_sample_stride = self.X_sample_stride + * cdef SIZE_t X_fx_stride = self.X_fx_stride + * cdef INT32_t* X_argsorted = self.X_argsorted_ptr # <<<<<<<<<<<<<< + * cdef SIZE_t X_argsorted_stride = self.X_argsorted_stride + * cdef SIZE_t n_total_samples = self.n_total_samples */ - (__pyx_v_sq_sum_init[__pyx_v_k]) = 0.0; + __pyx_t_4 = __pyx_v_self->X_argsorted_ptr; + __pyx_v_X_argsorted = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":1432 - * sq_sum_left[k] = 0.0 - * sq_sum_init[k] = 0.0 - * var_left[k] = 0.0 # <<<<<<<<<<<<<< - * var_right[k] = 0.0 - * + /* "sklearn/tree/_tree.pyx":1635 + * cdef SIZE_t X_fx_stride = self.X_fx_stride + * cdef INT32_t* X_argsorted = self.X_argsorted_ptr + * cdef SIZE_t X_argsorted_stride = self.X_argsorted_stride # <<<<<<<<<<<<<< + * cdef SIZE_t n_total_samples = self.n_total_samples + * cdef unsigned char* sample_mask = self.sample_mask */ - (__pyx_v_var_left[__pyx_v_k]) = 0.0; + __pyx_t_2 = __pyx_v_self->X_argsorted_stride; + __pyx_v_X_argsorted_stride = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1433 - * sq_sum_init[k] = 0.0 - * var_left[k] = 0.0 - * var_right[k] = 0.0 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1636 + * cdef INT32_t* X_argsorted = self.X_argsorted_ptr + * cdef SIZE_t X_argsorted_stride = self.X_argsorted_stride + * cdef SIZE_t n_total_samples = self.n_total_samples # <<<<<<<<<<<<<< + * cdef unsigned char* sample_mask = self.sample_mask * - * self.n_samples = n_samples */ - (__pyx_v_var_right[__pyx_v_k]) = 0.0; - } + __pyx_t_2 = __pyx_v_self->n_total_samples; + __pyx_v_n_total_samples = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1435 - * var_right[k] = 0.0 + /* "sklearn/tree/_tree.pyx":1637 + * cdef SIZE_t X_argsorted_stride = self.X_argsorted_stride + * cdef SIZE_t n_total_samples = self.n_total_samples + * cdef unsigned char* sample_mask = self.sample_mask # <<<<<<<<<<<<<< * - * self.n_samples = n_samples # <<<<<<<<<<<<<< - * - * cdef int j = 0 + * cdef SIZE_t max_features = self.max_features */ - __pyx_v_self->n_samples = __pyx_v_n_samples; + __pyx_t_5 = __pyx_v_self->sample_mask; + __pyx_v_sample_mask = __pyx_t_5; - /* "sklearn/tree/_tree.pyx":1437 - * self.n_samples = n_samples - * - * cdef int j = 0 # <<<<<<<<<<<<<< - * cdef DOUBLE_t y_jk = 0.0 + /* "sklearn/tree/_tree.pyx":1639 + * cdef unsigned char* sample_mask = self.sample_mask * + * cdef SIZE_t max_features = self.max_features # <<<<<<<<<<<<<< + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf */ - __pyx_v_j = 0; + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.max_features; + __pyx_v_max_features = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1438 - * - * cdef int j = 0 - * cdef DOUBLE_t y_jk = 0.0 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1640 * - * for j from 0 <= j < n_total_samples: + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf # <<<<<<<<<<<<<< + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef UINT32_t* random_state = &self.rand_r_state */ - __pyx_v_y_jk = 0.0; + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.min_samples_leaf; + __pyx_v_min_samples_leaf = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1440 - * cdef DOUBLE_t y_jk = 0.0 + /* "sklearn/tree/_tree.pyx":1641 + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf # <<<<<<<<<<<<<< + * cdef UINT32_t* random_state = &self.rand_r_state * - * for j from 0 <= j < n_total_samples: # <<<<<<<<<<<<<< - * if sample_mask[j] == 0: - * continue */ - __pyx_t_1 = __pyx_v_n_total_samples; - for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_1; __pyx_v_j++) { + __pyx_t_6 = __pyx_v_self->__pyx_base.__pyx_base.min_weight_leaf; + __pyx_v_min_weight_leaf = __pyx_t_6; - /* "sklearn/tree/_tree.pyx":1441 - * - * for j from 0 <= j < n_total_samples: - * if sample_mask[j] == 0: # <<<<<<<<<<<<<< - * continue + /* "sklearn/tree/_tree.pyx":1642 + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef UINT32_t* random_state = &self.rand_r_state # <<<<<<<<<<<<<< * + * cdef SplitRecord best, current */ - __pyx_t_2 = ((__pyx_v_sample_mask[__pyx_v_j]) == 0); - if (__pyx_t_2) { + __pyx_v_random_state = (&__pyx_v_self->__pyx_base.__pyx_base.rand_r_state); - /* "sklearn/tree/_tree.pyx":1442 - * for j from 0 <= j < n_total_samples: - * if sample_mask[j] == 0: - * continue # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1646 + * cdef SplitRecord best, current * - * for k from 0 <= k < n_outputs: + * cdef SIZE_t f_i = n_features # <<<<<<<<<<<<<< + * cdef SIZE_t f_j, p + * # Number of features discovered to be constant during the split search */ - goto __pyx_L5_continue; - goto __pyx_L7; - } - __pyx_L7:; + __pyx_v_f_i = __pyx_v_n_features; - /* "sklearn/tree/_tree.pyx":1444 - * continue - * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * y_jk = y[j * y_stride + k] - * sq_sum_init[k] += y_jk * y_jk + /* "sklearn/tree/_tree.pyx":1649 + * cdef SIZE_t f_j, p + * # Number of features discovered to be constant during the split search + * cdef SIZE_t n_found_constants = 0 # <<<<<<<<<<<<<< + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 */ - __pyx_t_3 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_3; __pyx_v_k++) { + __pyx_v_n_found_constants = 0; - /* "sklearn/tree/_tree.pyx":1445 - * - * for k from 0 <= k < n_outputs: - * y_jk = y[j * y_stride + k] # <<<<<<<<<<<<<< - * sq_sum_init[k] += y_jk * y_jk - * mean_init[k] += y_jk + /* "sklearn/tree/_tree.pyx":1651 + * cdef SIZE_t n_found_constants = 0 + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t n_known_constants = n_constant_features[0] + * # n_total_constants = n_known_constants + n_found_constants */ - __pyx_v_y_jk = (__pyx_v_y[((__pyx_v_j * __pyx_v_y_stride) + __pyx_v_k)]); + __pyx_v_n_drawn_constants = 0; - /* "sklearn/tree/_tree.pyx":1446 - * for k from 0 <= k < n_outputs: - * y_jk = y[j * y_stride + k] - * sq_sum_init[k] += y_jk * y_jk # <<<<<<<<<<<<<< - * mean_init[k] += y_jk - * + /* "sklearn/tree/_tree.pyx":1652 + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 + * cdef SIZE_t n_known_constants = n_constant_features[0] # <<<<<<<<<<<<<< + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants */ - __pyx_t_4 = __pyx_v_k; - (__pyx_v_sq_sum_init[__pyx_t_4]) = ((__pyx_v_sq_sum_init[__pyx_t_4]) + (__pyx_v_y_jk * __pyx_v_y_jk)); + __pyx_v_n_known_constants = (__pyx_v_n_constant_features[0]); - /* "sklearn/tree/_tree.pyx":1447 - * y_jk = y[j * y_stride + k] - * sq_sum_init[k] += y_jk * y_jk - * mean_init[k] += y_jk # <<<<<<<<<<<<<< - * - * for k from 0 <= k < n_outputs: + /* "sklearn/tree/_tree.pyx":1654 + * cdef SIZE_t n_known_constants = n_constant_features[0] + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants # <<<<<<<<<<<<<< + * cdef SIZE_t n_visited_features = 0 + * cdef SIZE_t partition_end */ - __pyx_t_4 = __pyx_v_k; - (__pyx_v_mean_init[__pyx_t_4]) = ((__pyx_v_mean_init[__pyx_t_4]) + __pyx_v_y_jk); - } - __pyx_L5_continue:; - } + __pyx_v_n_total_constants = __pyx_v_n_known_constants; - /* "sklearn/tree/_tree.pyx":1449 - * mean_init[k] += y_jk - * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * mean_init[k] /= n_samples - * + /* "sklearn/tree/_tree.pyx":1655 + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants + * cdef SIZE_t n_visited_features = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t partition_end + * cdef SIZE_t i, j */ - __pyx_t_1 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_1; __pyx_v_k++) { + __pyx_v_n_visited_features = 0; - /* "sklearn/tree/_tree.pyx":1450 + /* "sklearn/tree/_tree.pyx":1659 + * cdef SIZE_t i, j * - * for k from 0 <= k < n_outputs: - * mean_init[k] /= n_samples # <<<<<<<<<<<<<< + * _init_split(&best, end) # <<<<<<<<<<<<<< * - * self.reset() + * # Set sample mask */ - __pyx_t_3 = __pyx_v_k; - (__pyx_v_mean_init[__pyx_t_3]) = ((__pyx_v_mean_init[__pyx_t_3]) / __pyx_v_n_samples); - } + __pyx_f_7sklearn_4tree_5_tree__init_split((&__pyx_v_best), __pyx_v_end); - /* "sklearn/tree/_tree.pyx":1452 - * mean_init[k] /= n_samples + /* "sklearn/tree/_tree.pyx":1662 * - * self.reset() # <<<<<<<<<<<<<< + * # Set sample mask + * for p in range(start, end): # <<<<<<<<<<<<<< + * sample_mask[samples[p]] = 1 * - * cdef void reset(self): */ - ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RegressionCriterion *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.reset(((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self)); + __pyx_t_2 = __pyx_v_end; + for (__pyx_t_7 = __pyx_v_start; __pyx_t_7 < __pyx_t_2; __pyx_t_7+=1) { + __pyx_v_p = __pyx_t_7; - __Pyx_RefNannyFinishContext(); -} - -/* "sklearn/tree/_tree.pyx":1454 - * self.reset() - * - * cdef void reset(self): # <<<<<<<<<<<<<< - * """Reset criterion for new feature. + /* "sklearn/tree/_tree.pyx":1663 + * # Set sample mask + * for p in range(start, end): + * sample_mask[samples[p]] = 1 # <<<<<<<<<<<<<< * + * # Sample up to max_features without replacement using a */ + (__pyx_v_sample_mask[(__pyx_v_samples[__pyx_v_p])]) = 1; + } -static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_reset(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self) { - double *__pyx_v_mean_left; - double *__pyx_v_mean_right; - double *__pyx_v_mean_init; - double *__pyx_v_sq_sum_left; - double *__pyx_v_sq_sum_right; - double *__pyx_v_sq_sum_init; - double *__pyx_v_var_left; - double *__pyx_v_var_right; - int __pyx_v_n_samples; - int __pyx_v_n_outputs; - int __pyx_v_k; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("reset", 0); - - /* "sklearn/tree/_tree.pyx":1461 - * right branch. - * """ - * cdef double* mean_left = self.mean_left # <<<<<<<<<<<<<< - * cdef double* mean_right = self.mean_right - * cdef double* mean_init = self.mean_init + /* "sklearn/tree/_tree.pyx":1674 + * # newly discovered constant features to spare computation on descendant + * # nodes. + * while (f_i > n_total_constants and # Stop early if remaining features # <<<<<<<<<<<<<< + * # are constant + * (n_visited_features < max_features or */ - __pyx_v_mean_left = __pyx_v_self->mean_left; + while (1) { + __pyx_t_9 = ((__pyx_v_f_i > __pyx_v_n_total_constants) != 0); + if (__pyx_t_9) { + } else { + __pyx_t_8 = __pyx_t_9; + goto __pyx_L7_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":1462 - * """ - * cdef double* mean_left = self.mean_left - * cdef double* mean_right = self.mean_right # <<<<<<<<<<<<<< - * cdef double* mean_init = self.mean_init - * cdef double* sq_sum_left = self.sq_sum_left + /* "sklearn/tree/_tree.pyx":1676 + * while (f_i > n_total_constants and # Stop early if remaining features + * # are constant + * (n_visited_features < max_features or # <<<<<<<<<<<<<< + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): */ - __pyx_v_mean_right = __pyx_v_self->mean_right; + __pyx_t_9 = ((__pyx_v_n_visited_features < __pyx_v_max_features) != 0); + if (!__pyx_t_9) { + } else { + __pyx_t_8 = __pyx_t_9; + goto __pyx_L7_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":1463 - * cdef double* mean_left = self.mean_left - * cdef double* mean_right = self.mean_right - * cdef double* mean_init = self.mean_init # <<<<<<<<<<<<<< - * cdef double* sq_sum_left = self.sq_sum_left - * cdef double* sq_sum_right = self.sq_sum_right + /* "sklearn/tree/_tree.pyx":1678 + * (n_visited_features < max_features or + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): # <<<<<<<<<<<<<< + * n_visited_features += 1 + * */ - __pyx_v_mean_init = __pyx_v_self->mean_init; + __pyx_t_9 = ((__pyx_v_n_visited_features <= (__pyx_v_n_found_constants + __pyx_v_n_drawn_constants)) != 0); + __pyx_t_8 = __pyx_t_9; + __pyx_L7_bool_binop_done:; + if (!__pyx_t_8) break; - /* "sklearn/tree/_tree.pyx":1464 - * cdef double* mean_right = self.mean_right - * cdef double* mean_init = self.mean_init - * cdef double* sq_sum_left = self.sq_sum_left # <<<<<<<<<<<<<< - * cdef double* sq_sum_right = self.sq_sum_right - * cdef double* sq_sum_init = self.sq_sum_init + /* "sklearn/tree/_tree.pyx":1679 + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): + * n_visited_features += 1 # <<<<<<<<<<<<<< + * + * # Loop invariant: elements of features in */ - __pyx_v_sq_sum_left = __pyx_v_self->sq_sum_left; + __pyx_v_n_visited_features = (__pyx_v_n_visited_features + 1); - /* "sklearn/tree/_tree.pyx":1465 - * cdef double* mean_init = self.mean_init - * cdef double* sq_sum_left = self.sq_sum_left - * cdef double* sq_sum_right = self.sq_sum_right # <<<<<<<<<<<<<< - * cdef double* sq_sum_init = self.sq_sum_init - * cdef double* var_left = self.var_left + /* "sklearn/tree/_tree.pyx":1693 + * + * # Draw a feature at random + * f_j = rand_int(n_drawn_constants, f_i - n_found_constants, # <<<<<<<<<<<<<< + * random_state) + * */ - __pyx_v_sq_sum_right = __pyx_v_self->sq_sum_right; + __pyx_v_f_j = __pyx_f_7sklearn_4tree_5_tree_rand_int(__pyx_v_n_drawn_constants, (__pyx_v_f_i - __pyx_v_n_found_constants), __pyx_v_random_state); - /* "sklearn/tree/_tree.pyx":1466 - * cdef double* sq_sum_left = self.sq_sum_left - * cdef double* sq_sum_right = self.sq_sum_right - * cdef double* sq_sum_init = self.sq_sum_init # <<<<<<<<<<<<<< - * cdef double* var_left = self.var_left - * cdef double* var_right = self.var_right + /* "sklearn/tree/_tree.pyx":1696 + * random_state) + * + * if f_j < n_known_constants: # <<<<<<<<<<<<<< + * # f_j is in [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] */ - __pyx_v_sq_sum_init = __pyx_v_self->sq_sum_init; + __pyx_t_8 = ((__pyx_v_f_j < __pyx_v_n_known_constants) != 0); + if (__pyx_t_8) { - /* "sklearn/tree/_tree.pyx":1467 - * cdef double* sq_sum_right = self.sq_sum_right - * cdef double* sq_sum_init = self.sq_sum_init - * cdef double* var_left = self.var_left # <<<<<<<<<<<<<< - * cdef double* var_right = self.var_right - * + /* "sklearn/tree/_tree.pyx":1698 + * if f_j < n_known_constants: + * # f_j is in [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] # <<<<<<<<<<<<<< + * features[f_j] = features[n_drawn_constants] + * features[n_drawn_constants] = tmp */ - __pyx_v_var_left = __pyx_v_self->var_left; + __pyx_v_tmp = (__pyx_v_features[__pyx_v_f_j]); - /* "sklearn/tree/_tree.pyx":1468 - * cdef double* sq_sum_init = self.sq_sum_init - * cdef double* var_left = self.var_left - * cdef double* var_right = self.var_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1699 + * # f_j is in [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] + * features[f_j] = features[n_drawn_constants] # <<<<<<<<<<<<<< + * features[n_drawn_constants] = tmp * - * cdef int n_samples = self.n_samples */ - __pyx_v_var_right = __pyx_v_self->var_right; + (__pyx_v_features[__pyx_v_f_j]) = (__pyx_v_features[__pyx_v_n_drawn_constants]); - /* "sklearn/tree/_tree.pyx":1470 - * cdef double* var_right = self.var_right - * - * cdef int n_samples = self.n_samples # <<<<<<<<<<<<<< - * cdef int n_outputs = self.n_outputs + /* "sklearn/tree/_tree.pyx":1700 + * tmp = features[f_j] + * features[f_j] = features[n_drawn_constants] + * features[n_drawn_constants] = tmp # <<<<<<<<<<<<<< * + * n_drawn_constants += 1 */ - __pyx_v_n_samples = __pyx_v_self->n_samples; + (__pyx_v_features[__pyx_v_n_drawn_constants]) = __pyx_v_tmp; - /* "sklearn/tree/_tree.pyx":1471 + /* "sklearn/tree/_tree.pyx":1702 + * features[n_drawn_constants] = tmp * - * cdef int n_samples = self.n_samples - * cdef int n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * n_drawn_constants += 1 # <<<<<<<<<<<<<< * - * cdef int k = 0 + * else: */ - __pyx_v_n_outputs = __pyx_v_self->n_outputs; + __pyx_v_n_drawn_constants = (__pyx_v_n_drawn_constants + 1); + goto __pyx_L10; + } + /*else*/ { - /* "sklearn/tree/_tree.pyx":1473 - * cdef int n_outputs = self.n_outputs - * - * cdef int k = 0 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1706 + * else: + * # f_j in the interval [n_known_constants, f_i - n_found_constants[ + * f_j += n_found_constants # <<<<<<<<<<<<<< + * # f_j in the interval [n_total_constants, f_i[ * - * self.n_right = self.n_samples */ - __pyx_v_k = 0; + __pyx_v_f_j = (__pyx_v_f_j + __pyx_v_n_found_constants); - /* "sklearn/tree/_tree.pyx":1475 - * cdef int k = 0 + /* "sklearn/tree/_tree.pyx":1709 + * # f_j in the interval [n_total_constants, f_i[ * - * self.n_right = self.n_samples # <<<<<<<<<<<<<< - * self.n_left = 0 + * current.feature = features[f_j] # <<<<<<<<<<<<<< * + * # Extract ordering from X_argsorted */ - __pyx_v_self->n_right = __pyx_v_self->n_samples; + __pyx_v_current.feature = (__pyx_v_features[__pyx_v_f_j]); - /* "sklearn/tree/_tree.pyx":1476 + /* "sklearn/tree/_tree.pyx":1712 * - * self.n_right = self.n_samples - * self.n_left = 0 # <<<<<<<<<<<<<< + * # Extract ordering from X_argsorted + * p = start # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: + * for i in range(n_total_samples): */ - __pyx_v_self->n_left = 0; + __pyx_v_p = __pyx_v_start; - /* "sklearn/tree/_tree.pyx":1478 - * self.n_left = 0 + /* "sklearn/tree/_tree.pyx":1714 + * p = start * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * mean_right[k] = mean_init[k] - * mean_left[k] = 0.0 + * for i in range(n_total_samples): # <<<<<<<<<<<<<< + * j = X_argsorted[X_argsorted_stride * current.feature + i] + * if sample_mask[j] == 1: */ - __pyx_t_1 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_1; __pyx_v_k++) { + __pyx_t_2 = __pyx_v_n_total_samples; + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_2; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; - /* "sklearn/tree/_tree.pyx":1479 + /* "sklearn/tree/_tree.pyx":1715 * - * for k from 0 <= k < n_outputs: - * mean_right[k] = mean_init[k] # <<<<<<<<<<<<<< - * mean_left[k] = 0.0 - * sq_sum_right[k] = sq_sum_init[k] + * for i in range(n_total_samples): + * j = X_argsorted[X_argsorted_stride * current.feature + i] # <<<<<<<<<<<<<< + * if sample_mask[j] == 1: + * samples[p] = j */ - (__pyx_v_mean_right[__pyx_v_k]) = (__pyx_v_mean_init[__pyx_v_k]); + __pyx_v_j = (__pyx_v_X_argsorted[((__pyx_v_X_argsorted_stride * __pyx_v_current.feature) + __pyx_v_i)]); - /* "sklearn/tree/_tree.pyx":1480 - * for k from 0 <= k < n_outputs: - * mean_right[k] = mean_init[k] - * mean_left[k] = 0.0 # <<<<<<<<<<<<<< - * sq_sum_right[k] = sq_sum_init[k] - * sq_sum_left[k] = 0.0 + /* "sklearn/tree/_tree.pyx":1716 + * for i in range(n_total_samples): + * j = X_argsorted[X_argsorted_stride * current.feature + i] + * if sample_mask[j] == 1: # <<<<<<<<<<<<<< + * samples[p] = j + * Xf[p] = X[X_sample_stride * j + */ - (__pyx_v_mean_left[__pyx_v_k]) = 0.0; + __pyx_t_8 = (((__pyx_v_sample_mask[__pyx_v_j]) == 1) != 0); + if (__pyx_t_8) { - /* "sklearn/tree/_tree.pyx":1481 - * mean_right[k] = mean_init[k] - * mean_left[k] = 0.0 - * sq_sum_right[k] = sq_sum_init[k] # <<<<<<<<<<<<<< - * sq_sum_left[k] = 0.0 - * var_left[k] = 0.0 + /* "sklearn/tree/_tree.pyx":1717 + * j = X_argsorted[X_argsorted_stride * current.feature + i] + * if sample_mask[j] == 1: + * samples[p] = j # <<<<<<<<<<<<<< + * Xf[p] = X[X_sample_stride * j + + * X_fx_stride * current.feature] */ - (__pyx_v_sq_sum_right[__pyx_v_k]) = (__pyx_v_sq_sum_init[__pyx_v_k]); + (__pyx_v_samples[__pyx_v_p]) = __pyx_v_j; - /* "sklearn/tree/_tree.pyx":1482 - * mean_left[k] = 0.0 - * sq_sum_right[k] = sq_sum_init[k] - * sq_sum_left[k] = 0.0 # <<<<<<<<<<<<<< - * var_left[k] = 0.0 - * var_right[k] = sq_sum_right[k] - n_samples * (mean_right[k] * mean_right[k]) + /* "sklearn/tree/_tree.pyx":1718 + * if sample_mask[j] == 1: + * samples[p] = j + * Xf[p] = X[X_sample_stride * j + # <<<<<<<<<<<<<< + * X_fx_stride * current.feature] + * p += 1 */ - (__pyx_v_sq_sum_left[__pyx_v_k]) = 0.0; + (__pyx_v_Xf[__pyx_v_p]) = (__pyx_v_X[((__pyx_v_X_sample_stride * __pyx_v_j) + (__pyx_v_X_fx_stride * __pyx_v_current.feature))]); - /* "sklearn/tree/_tree.pyx":1483 - * sq_sum_right[k] = sq_sum_init[k] - * sq_sum_left[k] = 0.0 - * var_left[k] = 0.0 # <<<<<<<<<<<<<< - * var_right[k] = sq_sum_right[k] - n_samples * (mean_right[k] * mean_right[k]) + /* "sklearn/tree/_tree.pyx":1720 + * Xf[p] = X[X_sample_stride * j + + * X_fx_stride * current.feature] + * p += 1 # <<<<<<<<<<<<<< * + * # Evaluate all splits */ - (__pyx_v_var_left[__pyx_v_k]) = 0.0; + __pyx_v_p = (__pyx_v_p + 1); + goto __pyx_L13; + } + __pyx_L13:; + } - /* "sklearn/tree/_tree.pyx":1484 - * sq_sum_left[k] = 0.0 - * var_left[k] = 0.0 - * var_right[k] = sq_sum_right[k] - n_samples * (mean_right[k] * mean_right[k]) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1723 * - * cdef int update(self, int a, int b, DOUBLE_t* y, int y_stride, + * # Evaluate all splits + * if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: # <<<<<<<<<<<<<< + * features[f_j] = features[n_total_constants] + * features[n_total_constants] = current.feature */ - (__pyx_v_var_right[__pyx_v_k]) = ((__pyx_v_sq_sum_right[__pyx_v_k]) - (__pyx_v_n_samples * ((__pyx_v_mean_right[__pyx_v_k]) * (__pyx_v_mean_right[__pyx_v_k])))); - } - - __Pyx_RefNannyFinishContext(); -} + __pyx_t_8 = (((__pyx_v_Xf[(__pyx_v_end - 1)]) <= ((__pyx_v_Xf[__pyx_v_start]) + __pyx_v_7sklearn_4tree_5_tree_FEATURE_THRESHOLD)) != 0); + if (__pyx_t_8) { -/* "sklearn/tree/_tree.pyx":1486 - * var_right[k] = sq_sum_right[k] - n_samples * (mean_right[k] * mean_right[k]) + /* "sklearn/tree/_tree.pyx":1724 + * # Evaluate all splits + * if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: + * features[f_j] = features[n_total_constants] # <<<<<<<<<<<<<< + * features[n_total_constants] = current.feature * - * cdef int update(self, int a, int b, DOUBLE_t* y, int y_stride, # <<<<<<<<<<<<<< - * int* X_argsorted_i, BOOL_t* sample_mask): - * """Update the criteria for each value in interval [a,b) (where a and b - */ - -static int __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_update(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, int __pyx_v_a, int __pyx_v_b, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_y, int __pyx_v_y_stride, int *__pyx_v_X_argsorted_i, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *__pyx_v_sample_mask) { - double *__pyx_v_mean_left; - double *__pyx_v_mean_right; - double *__pyx_v_sq_sum_left; - double *__pyx_v_sq_sum_right; - double *__pyx_v_var_left; - double *__pyx_v_var_right; - int __pyx_v_n_samples; - int __pyx_v_n_outputs; - int __pyx_v_n_left; - int __pyx_v_n_right; - double __pyx_v_y_idx; - int __pyx_v_idx; - int __pyx_v_j; - int __pyx_v_k; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - __Pyx_RefNannySetupContext("update", 0); - - /* "sklearn/tree/_tree.pyx":1490 - * """Update the criteria for each value in interval [a,b) (where a and b - * are indices in `X_argsorted_i`).""" - * cdef double* mean_left = self.mean_left # <<<<<<<<<<<<<< - * cdef double* mean_right = self.mean_right - * cdef double* sq_sum_left = self.sq_sum_left */ - __pyx_v_mean_left = __pyx_v_self->mean_left; + (__pyx_v_features[__pyx_v_f_j]) = (__pyx_v_features[__pyx_v_n_total_constants]); - /* "sklearn/tree/_tree.pyx":1491 - * are indices in `X_argsorted_i`).""" - * cdef double* mean_left = self.mean_left - * cdef double* mean_right = self.mean_right # <<<<<<<<<<<<<< - * cdef double* sq_sum_left = self.sq_sum_left - * cdef double* sq_sum_right = self.sq_sum_right + /* "sklearn/tree/_tree.pyx":1725 + * if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: + * features[f_j] = features[n_total_constants] + * features[n_total_constants] = current.feature # <<<<<<<<<<<<<< + * + * n_found_constants += 1 */ - __pyx_v_mean_right = __pyx_v_self->mean_right; + __pyx_t_2 = __pyx_v_current.feature; + (__pyx_v_features[__pyx_v_n_total_constants]) = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1492 - * cdef double* mean_left = self.mean_left - * cdef double* mean_right = self.mean_right - * cdef double* sq_sum_left = self.sq_sum_left # <<<<<<<<<<<<<< - * cdef double* sq_sum_right = self.sq_sum_right - * cdef double* var_left = self.var_left + /* "sklearn/tree/_tree.pyx":1727 + * features[n_total_constants] = current.feature + * + * n_found_constants += 1 # <<<<<<<<<<<<<< + * n_total_constants += 1 + * */ - __pyx_v_sq_sum_left = __pyx_v_self->sq_sum_left; + __pyx_v_n_found_constants = (__pyx_v_n_found_constants + 1); - /* "sklearn/tree/_tree.pyx":1493 - * cdef double* mean_right = self.mean_right - * cdef double* sq_sum_left = self.sq_sum_left - * cdef double* sq_sum_right = self.sq_sum_right # <<<<<<<<<<<<<< - * cdef double* var_left = self.var_left - * cdef double* var_right = self.var_right + /* "sklearn/tree/_tree.pyx":1728 + * + * n_found_constants += 1 + * n_total_constants += 1 # <<<<<<<<<<<<<< + * + * else: */ - __pyx_v_sq_sum_right = __pyx_v_self->sq_sum_right; + __pyx_v_n_total_constants = (__pyx_v_n_total_constants + 1); + goto __pyx_L14; + } + /*else*/ { - /* "sklearn/tree/_tree.pyx":1494 - * cdef double* sq_sum_left = self.sq_sum_left - * cdef double* sq_sum_right = self.sq_sum_right - * cdef double* var_left = self.var_left # <<<<<<<<<<<<<< - * cdef double* var_right = self.var_right + /* "sklearn/tree/_tree.pyx":1731 + * + * else: + * f_i -= 1 # <<<<<<<<<<<<<< + * features[f_i], features[f_j] = features[f_j], features[f_i] * */ - __pyx_v_var_left = __pyx_v_self->var_left; + __pyx_v_f_i = (__pyx_v_f_i - 1); - /* "sklearn/tree/_tree.pyx":1495 - * cdef double* sq_sum_right = self.sq_sum_right - * cdef double* var_left = self.var_left - * cdef double* var_right = self.var_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1732 + * else: + * f_i -= 1 + * features[f_i], features[f_j] = features[f_j], features[f_i] # <<<<<<<<<<<<<< * - * cdef int n_samples = self.n_samples + * self.criterion.reset() */ - __pyx_v_var_right = __pyx_v_self->var_right; + __pyx_t_2 = (__pyx_v_features[__pyx_v_f_j]); + __pyx_t_7 = (__pyx_v_features[__pyx_v_f_i]); + (__pyx_v_features[__pyx_v_f_i]) = __pyx_t_2; + (__pyx_v_features[__pyx_v_f_j]) = __pyx_t_7; - /* "sklearn/tree/_tree.pyx":1497 - * cdef double* var_right = self.var_right + /* "sklearn/tree/_tree.pyx":1734 + * features[f_i], features[f_j] = features[f_j], features[f_i] + * + * self.criterion.reset() # <<<<<<<<<<<<<< + * p = start * - * cdef int n_samples = self.n_samples # <<<<<<<<<<<<<< - * cdef int n_outputs = self.n_outputs - * cdef int n_left = self.n_left */ - __pyx_v_n_samples = __pyx_v_self->n_samples; + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->reset(__pyx_v_self->__pyx_base.__pyx_base.criterion); - /* "sklearn/tree/_tree.pyx":1498 + /* "sklearn/tree/_tree.pyx":1735 + * + * self.criterion.reset() + * p = start # <<<<<<<<<<<<<< * - * cdef int n_samples = self.n_samples - * cdef int n_outputs = self.n_outputs # <<<<<<<<<<<<<< - * cdef int n_left = self.n_left - * cdef int n_right = self.n_right + * while p < end: */ - __pyx_v_n_outputs = __pyx_v_self->n_outputs; + __pyx_v_p = __pyx_v_start; - /* "sklearn/tree/_tree.pyx":1499 - * cdef int n_samples = self.n_samples - * cdef int n_outputs = self.n_outputs - * cdef int n_left = self.n_left # <<<<<<<<<<<<<< - * cdef int n_right = self.n_right + /* "sklearn/tree/_tree.pyx":1737 + * p = start * + * while p < end: # <<<<<<<<<<<<<< + * while (p + 1 < end and + * Xf[p + 1] <= Xf[p] + FEATURE_THRESHOLD): */ - __pyx_v_n_left = __pyx_v_self->n_left; + while (1) { + __pyx_t_8 = ((__pyx_v_p < __pyx_v_end) != 0); + if (!__pyx_t_8) break; - /* "sklearn/tree/_tree.pyx":1500 - * cdef int n_outputs = self.n_outputs - * cdef int n_left = self.n_left - * cdef int n_right = self.n_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1738 * - * cdef double y_idx = 0.0 + * while p < end: + * while (p + 1 < end and # <<<<<<<<<<<<<< + * Xf[p + 1] <= Xf[p] + FEATURE_THRESHOLD): + * p += 1 */ - __pyx_v_n_right = __pyx_v_self->n_right; + while (1) { + __pyx_t_9 = (((__pyx_v_p + 1) < __pyx_v_end) != 0); + if (__pyx_t_9) { + } else { + __pyx_t_8 = __pyx_t_9; + goto __pyx_L19_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":1502 - * cdef int n_right = self.n_right - * - * cdef double y_idx = 0.0 # <<<<<<<<<<<<<< - * cdef int idx, j, k + /* "sklearn/tree/_tree.pyx":1739 + * while p < end: + * while (p + 1 < end and + * Xf[p + 1] <= Xf[p] + FEATURE_THRESHOLD): # <<<<<<<<<<<<<< + * p += 1 * */ - __pyx_v_y_idx = 0.0; + __pyx_t_9 = (((__pyx_v_Xf[(__pyx_v_p + 1)]) <= ((__pyx_v_Xf[__pyx_v_p]) + __pyx_v_7sklearn_4tree_5_tree_FEATURE_THRESHOLD)) != 0); + __pyx_t_8 = __pyx_t_9; + __pyx_L19_bool_binop_done:; + if (!__pyx_t_8) break; - /* "sklearn/tree/_tree.pyx":1506 - * - * # post condition: all samples from [0:b) are on the left side - * for idx from a <= idx < b: # <<<<<<<<<<<<<< - * j = X_argsorted_i[idx] + /* "sklearn/tree/_tree.pyx":1740 + * while (p + 1 < end and + * Xf[p + 1] <= Xf[p] + FEATURE_THRESHOLD): + * p += 1 # <<<<<<<<<<<<<< * + * # (p + 1 >= end) or (X[samples[p + 1], current.feature] > */ - __pyx_t_1 = __pyx_v_b; - for (__pyx_v_idx = __pyx_v_a; __pyx_v_idx < __pyx_t_1; __pyx_v_idx++) { + __pyx_v_p = (__pyx_v_p + 1); + } - /* "sklearn/tree/_tree.pyx":1507 - * # post condition: all samples from [0:b) are on the left side - * for idx from a <= idx < b: - * j = X_argsorted_i[idx] # <<<<<<<<<<<<<< - * - * if sample_mask[j] == 0: + /* "sklearn/tree/_tree.pyx":1744 + * # (p + 1 >= end) or (X[samples[p + 1], current.feature] > + * # X[samples[p], current.feature]) + * p += 1 # <<<<<<<<<<<<<< + * # (p >= end) or (X[samples[p], current.feature] > + * # X[samples[p - 1], current.feature]) */ - __pyx_v_j = (__pyx_v_X_argsorted_i[__pyx_v_idx]); + __pyx_v_p = (__pyx_v_p + 1); - /* "sklearn/tree/_tree.pyx":1509 - * j = X_argsorted_i[idx] + /* "sklearn/tree/_tree.pyx":1748 + * # X[samples[p - 1], current.feature]) * - * if sample_mask[j] == 0: # <<<<<<<<<<<<<< - * continue + * if p < end: # <<<<<<<<<<<<<< + * current.pos = p * */ - __pyx_t_2 = ((__pyx_v_sample_mask[__pyx_v_j]) == 0); - if (__pyx_t_2) { + __pyx_t_8 = ((__pyx_v_p < __pyx_v_end) != 0); + if (__pyx_t_8) { - /* "sklearn/tree/_tree.pyx":1510 + /* "sklearn/tree/_tree.pyx":1749 * - * if sample_mask[j] == 0: - * continue # <<<<<<<<<<<<<< + * if p < end: + * current.pos = p # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: + * # Reject if min_samples_leaf is not guaranteed */ - goto __pyx_L3_continue; - goto __pyx_L5; - } - __pyx_L5:; + __pyx_v_current.pos = __pyx_v_p; - /* "sklearn/tree/_tree.pyx":1512 - * continue + /* "sklearn/tree/_tree.pyx":1752 * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * y_idx = y[j * y_stride + k] - * sq_sum_left[k] += (y_idx * y_idx) + * # Reject if min_samples_leaf is not guaranteed + * if (((current.pos - start) < min_samples_leaf) or # <<<<<<<<<<<<<< + * ((end - current.pos) < min_samples_leaf)): + * continue */ - __pyx_t_3 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_3; __pyx_v_k++) { + __pyx_t_9 = (((__pyx_v_current.pos - __pyx_v_start) < __pyx_v_min_samples_leaf) != 0); + if (!__pyx_t_9) { + } else { + __pyx_t_8 = __pyx_t_9; + goto __pyx_L23_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":1513 + /* "sklearn/tree/_tree.pyx":1753 + * # Reject if min_samples_leaf is not guaranteed + * if (((current.pos - start) < min_samples_leaf) or + * ((end - current.pos) < min_samples_leaf)): # <<<<<<<<<<<<<< + * continue * - * for k from 0 <= k < n_outputs: - * y_idx = y[j * y_stride + k] # <<<<<<<<<<<<<< - * sq_sum_left[k] += (y_idx * y_idx) - * sq_sum_right[k] -= (y_idx * y_idx) */ - __pyx_v_y_idx = (__pyx_v_y[((__pyx_v_j * __pyx_v_y_stride) + __pyx_v_k)]); + __pyx_t_9 = (((__pyx_v_end - __pyx_v_current.pos) < __pyx_v_min_samples_leaf) != 0); + __pyx_t_8 = __pyx_t_9; + __pyx_L23_bool_binop_done:; + if (__pyx_t_8) { - /* "sklearn/tree/_tree.pyx":1514 - * for k from 0 <= k < n_outputs: - * y_idx = y[j * y_stride + k] - * sq_sum_left[k] += (y_idx * y_idx) # <<<<<<<<<<<<<< - * sq_sum_right[k] -= (y_idx * y_idx) + /* "sklearn/tree/_tree.pyx":1754 + * if (((current.pos - start) < min_samples_leaf) or + * ((end - current.pos) < min_samples_leaf)): + * continue # <<<<<<<<<<<<<< * + * self.criterion.update(current.pos) */ - __pyx_t_4 = __pyx_v_k; - (__pyx_v_sq_sum_left[__pyx_t_4]) = ((__pyx_v_sq_sum_left[__pyx_t_4]) + (__pyx_v_y_idx * __pyx_v_y_idx)); + goto __pyx_L15_continue; + } - /* "sklearn/tree/_tree.pyx":1515 - * y_idx = y[j * y_stride + k] - * sq_sum_left[k] += (y_idx * y_idx) - * sq_sum_right[k] -= (y_idx * y_idx) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1756 + * continue + * + * self.criterion.update(current.pos) # <<<<<<<<<<<<<< * - * mean_left[k] = (n_left * mean_left[k] + y_idx) / (n_left + 1) + * # Reject if min_weight_leaf is not satisfied */ - __pyx_t_4 = __pyx_v_k; - (__pyx_v_sq_sum_right[__pyx_t_4]) = ((__pyx_v_sq_sum_right[__pyx_t_4]) - (__pyx_v_y_idx * __pyx_v_y_idx)); + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->update(__pyx_v_self->__pyx_base.__pyx_base.criterion, __pyx_v_current.pos); - /* "sklearn/tree/_tree.pyx":1517 - * sq_sum_right[k] -= (y_idx * y_idx) - * - * mean_left[k] = (n_left * mean_left[k] + y_idx) / (n_left + 1) # <<<<<<<<<<<<<< - * mean_right[k] = ((n_samples - n_left) * mean_right[k] - y_idx) / (n_samples - n_left - 1) + /* "sklearn/tree/_tree.pyx":1759 * + * # Reject if min_weight_leaf is not satisfied + * if ((self.criterion.weighted_n_left < min_weight_leaf) or # <<<<<<<<<<<<<< + * (self.criterion.weighted_n_right < min_weight_leaf)): + * continue */ - (__pyx_v_mean_left[__pyx_v_k]) = (((__pyx_v_n_left * (__pyx_v_mean_left[__pyx_v_k])) + __pyx_v_y_idx) / ((double)(__pyx_v_n_left + 1))); + __pyx_t_9 = ((__pyx_v_self->__pyx_base.__pyx_base.criterion->weighted_n_left < __pyx_v_min_weight_leaf) != 0); + if (!__pyx_t_9) { + } else { + __pyx_t_8 = __pyx_t_9; + goto __pyx_L26_bool_binop_done; + } - /* "sklearn/tree/_tree.pyx":1518 - * - * mean_left[k] = (n_left * mean_left[k] + y_idx) / (n_left + 1) - * mean_right[k] = ((n_samples - n_left) * mean_right[k] - y_idx) / (n_samples - n_left - 1) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1760 + * # Reject if min_weight_leaf is not satisfied + * if ((self.criterion.weighted_n_left < min_weight_leaf) or + * (self.criterion.weighted_n_right < min_weight_leaf)): # <<<<<<<<<<<<<< + * continue * - * n_left += 1 */ - (__pyx_v_mean_right[__pyx_v_k]) = ((((__pyx_v_n_samples - __pyx_v_n_left) * (__pyx_v_mean_right[__pyx_v_k])) - __pyx_v_y_idx) / ((double)((__pyx_v_n_samples - __pyx_v_n_left) - 1))); - } + __pyx_t_9 = ((__pyx_v_self->__pyx_base.__pyx_base.criterion->weighted_n_right < __pyx_v_min_weight_leaf) != 0); + __pyx_t_8 = __pyx_t_9; + __pyx_L26_bool_binop_done:; + if (__pyx_t_8) { - /* "sklearn/tree/_tree.pyx":1520 - * mean_right[k] = ((n_samples - n_left) * mean_right[k] - y_idx) / (n_samples - n_left - 1) + /* "sklearn/tree/_tree.pyx":1761 + * if ((self.criterion.weighted_n_left < min_weight_leaf) or + * (self.criterion.weighted_n_right < min_weight_leaf)): + * continue # <<<<<<<<<<<<<< * - * n_left += 1 # <<<<<<<<<<<<<< - * self.n_left = n_left - * n_right -= 1 + * current.improvement = self.criterion.impurity_improvement(impurity) */ - __pyx_v_n_left = (__pyx_v_n_left + 1); + goto __pyx_L15_continue; + } - /* "sklearn/tree/_tree.pyx":1521 + /* "sklearn/tree/_tree.pyx":1763 + * continue * - * n_left += 1 - * self.n_left = n_left # <<<<<<<<<<<<<< - * n_right -= 1 - * self.n_right = n_right + * current.improvement = self.criterion.impurity_improvement(impurity) # <<<<<<<<<<<<<< + * + * if current.improvement > best.improvement: */ - __pyx_v_self->n_left = __pyx_v_n_left; + __pyx_v_current.improvement = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->impurity_improvement(__pyx_v_self->__pyx_base.__pyx_base.criterion, __pyx_v_impurity); - /* "sklearn/tree/_tree.pyx":1522 - * n_left += 1 - * self.n_left = n_left - * n_right -= 1 # <<<<<<<<<<<<<< - * self.n_right = n_right + /* "sklearn/tree/_tree.pyx":1765 + * current.improvement = self.criterion.impurity_improvement(impurity) * + * if current.improvement > best.improvement: # <<<<<<<<<<<<<< + * self.criterion.children_impurity(¤t.impurity_left, + * ¤t.impurity_right) */ - __pyx_v_n_right = (__pyx_v_n_right - 1); + __pyx_t_8 = ((__pyx_v_current.improvement > __pyx_v_best.improvement) != 0); + if (__pyx_t_8) { - /* "sklearn/tree/_tree.pyx":1523 - * self.n_left = n_left - * n_right -= 1 - * self.n_right = n_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1766 + * + * if current.improvement > best.improvement: + * self.criterion.children_impurity(¤t.impurity_left, # <<<<<<<<<<<<<< + * ¤t.impurity_right) * - * for k from 0 <= k < n_outputs: */ - __pyx_v_self->n_right = __pyx_v_n_right; + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->children_impurity(__pyx_v_self->__pyx_base.__pyx_base.criterion, (&__pyx_v_current.impurity_left), (&__pyx_v_current.impurity_right)); - /* "sklearn/tree/_tree.pyx":1525 - * self.n_right = n_right + /* "sklearn/tree/_tree.pyx":1769 + * ¤t.impurity_right) * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * var_left[k] = sq_sum_left[k] - n_left * (mean_left[k] * mean_left[k]) - * var_right[k] = sq_sum_right[k] - n_right * (mean_right[k] * mean_right[k]) + * current.threshold = (Xf[p - 1] + Xf[p]) / 2.0 # <<<<<<<<<<<<<< + * if current.threshold == Xf[p]: + * current.threshold = Xf[p - 1] */ - __pyx_t_3 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_3; __pyx_v_k++) { + __pyx_v_current.threshold = (((__pyx_v_Xf[(__pyx_v_p - 1)]) + (__pyx_v_Xf[__pyx_v_p])) / 2.0); - /* "sklearn/tree/_tree.pyx":1526 + /* "sklearn/tree/_tree.pyx":1770 * - * for k from 0 <= k < n_outputs: - * var_left[k] = sq_sum_left[k] - n_left * (mean_left[k] * mean_left[k]) # <<<<<<<<<<<<<< - * var_right[k] = sq_sum_right[k] - n_right * (mean_right[k] * mean_right[k]) + * current.threshold = (Xf[p - 1] + Xf[p]) / 2.0 + * if current.threshold == Xf[p]: # <<<<<<<<<<<<<< + * current.threshold = Xf[p - 1] * */ - (__pyx_v_var_left[__pyx_v_k]) = ((__pyx_v_sq_sum_left[__pyx_v_k]) - (__pyx_v_n_left * ((__pyx_v_mean_left[__pyx_v_k]) * (__pyx_v_mean_left[__pyx_v_k])))); + __pyx_t_8 = ((__pyx_v_current.threshold == (__pyx_v_Xf[__pyx_v_p])) != 0); + if (__pyx_t_8) { - /* "sklearn/tree/_tree.pyx":1527 - * for k from 0 <= k < n_outputs: - * var_left[k] = sq_sum_left[k] - n_left * (mean_left[k] * mean_left[k]) - * var_right[k] = sq_sum_right[k] - n_right * (mean_right[k] * mean_right[k]) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1771 + * current.threshold = (Xf[p - 1] + Xf[p]) / 2.0 + * if current.threshold == Xf[p]: + * current.threshold = Xf[p - 1] # <<<<<<<<<<<<<< * - * return n_left + * best = current # copy */ - (__pyx_v_var_right[__pyx_v_k]) = ((__pyx_v_sq_sum_right[__pyx_v_k]) - (__pyx_v_n_right * ((__pyx_v_mean_right[__pyx_v_k]) * (__pyx_v_mean_right[__pyx_v_k])))); - } - __pyx_L3_continue:; - } + __pyx_v_current.threshold = (__pyx_v_Xf[(__pyx_v_p - 1)]); + goto __pyx_L29; + } + __pyx_L29:; - /* "sklearn/tree/_tree.pyx":1529 - * var_right[k] = sq_sum_right[k] - n_right * (mean_right[k] * mean_right[k]) + /* "sklearn/tree/_tree.pyx":1773 + * current.threshold = Xf[p - 1] * - * return n_left # <<<<<<<<<<<<<< + * best = current # copy # <<<<<<<<<<<<<< * - * cdef double eval(self): + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] */ - __pyx_r = __pyx_v_n_left; - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_v_best = __pyx_v_current; + goto __pyx_L28; + } + __pyx_L28:; + goto __pyx_L21; + } + __pyx_L21:; + __pyx_L15_continue:; + } + } + __pyx_L14:; + } + __pyx_L10:; + } -/* "sklearn/tree/_tree.pyx":1531 - * return n_left + /* "sklearn/tree/_tree.pyx":1776 * - * cdef double eval(self): # <<<<<<<<<<<<<< - * """Evaluate the criteria (aka the split error).""" - * pass + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + * if best.pos < end: # <<<<<<<<<<<<<< + * partition_end = end + * p = start */ + __pyx_t_8 = ((__pyx_v_best.pos < __pyx_v_end) != 0); + if (__pyx_t_8) { -static double __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_eval(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self) { - double __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("eval", 0); - - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/tree/_tree.pyx":1535 - * pass + /* "sklearn/tree/_tree.pyx":1777 + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + * if best.pos < end: + * partition_end = end # <<<<<<<<<<<<<< + * p = start * - * cdef void init_value(self, double* buffer_value): # <<<<<<<<<<<<<< - * """Get the initial value of the criterion (`init` must be called - * before).""" */ + __pyx_v_partition_end = __pyx_v_end; -static void __pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_init_value(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *__pyx_v_self, double *__pyx_v_buffer_value) { - int __pyx_v_n_outputs; - double *__pyx_v_mean_init; - int __pyx_v_k; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("init_value", 0); - - /* "sklearn/tree/_tree.pyx":1538 - * """Get the initial value of the criterion (`init` must be called - * before).""" - * cdef int n_outputs = self.n_outputs # <<<<<<<<<<<<<< - * cdef double* mean_init = self.mean_init + /* "sklearn/tree/_tree.pyx":1778 + * if best.pos < end: + * partition_end = end + * p = start # <<<<<<<<<<<<<< * + * while p < partition_end: */ - __pyx_v_n_outputs = __pyx_v_self->n_outputs; + __pyx_v_p = __pyx_v_start; - /* "sklearn/tree/_tree.pyx":1539 - * before).""" - * cdef int n_outputs = self.n_outputs - * cdef double* mean_init = self.mean_init # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1780 + * p = start * - * cdef int k + * while p < partition_end: # <<<<<<<<<<<<<< + * if X[X_sample_stride * samples[p] + + * X_fx_stride * best.feature] <= best.threshold: */ - __pyx_v_mean_init = __pyx_v_self->mean_init; + while (1) { + __pyx_t_8 = ((__pyx_v_p < __pyx_v_partition_end) != 0); + if (!__pyx_t_8) break; - /* "sklearn/tree/_tree.pyx":1543 - * cdef int k - * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * buffer_value[k] = mean_init[k] + /* "sklearn/tree/_tree.pyx":1782 + * while p < partition_end: + * if X[X_sample_stride * samples[p] + + * X_fx_stride * best.feature] <= best.threshold: # <<<<<<<<<<<<<< + * p += 1 * */ - __pyx_t_1 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_1; __pyx_v_k++) { + __pyx_t_8 = (((__pyx_v_X[((__pyx_v_X_sample_stride * (__pyx_v_samples[__pyx_v_p])) + (__pyx_v_X_fx_stride * __pyx_v_best.feature))]) <= __pyx_v_best.threshold) != 0); + if (__pyx_t_8) { - /* "sklearn/tree/_tree.pyx":1544 + /* "sklearn/tree/_tree.pyx":1783 + * if X[X_sample_stride * samples[p] + + * X_fx_stride * best.feature] <= best.threshold: + * p += 1 # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: - * buffer_value[k] = mean_init[k] # <<<<<<<<<<<<<< + * else: + */ + __pyx_v_p = (__pyx_v_p + 1); + goto __pyx_L33; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":1786 * + * else: + * partition_end -= 1 # <<<<<<<<<<<<<< * + * tmp = samples[partition_end] */ - (__pyx_v_buffer_value[__pyx_v_k]) = (__pyx_v_mean_init[__pyx_v_k]); - } - - __Pyx_RefNannyFinishContext(); -} + __pyx_v_partition_end = (__pyx_v_partition_end - 1); -/* "sklearn/tree/_tree.pyx":1553 - * """ + /* "sklearn/tree/_tree.pyx":1788 + * partition_end -= 1 * - * cdef double eval(self): # <<<<<<<<<<<<<< - * cdef double* var_left = self.var_left - * cdef double* var_right = self.var_right + * tmp = samples[partition_end] # <<<<<<<<<<<<<< + * samples[partition_end] = samples[p] + * samples[p] = tmp */ + __pyx_v_tmp = (__pyx_v_samples[__pyx_v_partition_end]); -static double __pyx_f_7sklearn_4tree_5_tree_3MSE_eval(struct __pyx_obj_7sklearn_4tree_5_tree_MSE *__pyx_v_self) { - double *__pyx_v_var_left; - double *__pyx_v_var_right; - int __pyx_v_n_outputs; - int __pyx_v_k; - double __pyx_v_total; - double __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("eval", 0); - - /* "sklearn/tree/_tree.pyx":1554 + /* "sklearn/tree/_tree.pyx":1789 * - * cdef double eval(self): - * cdef double* var_left = self.var_left # <<<<<<<<<<<<<< - * cdef double* var_right = self.var_right + * tmp = samples[partition_end] + * samples[partition_end] = samples[p] # <<<<<<<<<<<<<< + * samples[p] = tmp * */ - __pyx_v_var_left = __pyx_v_self->__pyx_base.var_left; + (__pyx_v_samples[__pyx_v_partition_end]) = (__pyx_v_samples[__pyx_v_p]); - /* "sklearn/tree/_tree.pyx":1555 - * cdef double eval(self): - * cdef double* var_left = self.var_left - * cdef double* var_right = self.var_right # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1790 + * tmp = samples[partition_end] + * samples[partition_end] = samples[p] + * samples[p] = tmp # <<<<<<<<<<<<<< * - * cdef int n_outputs = self.n_outputs + * # Reset sample mask */ - __pyx_v_var_right = __pyx_v_self->__pyx_base.var_right; + (__pyx_v_samples[__pyx_v_p]) = __pyx_v_tmp; + } + __pyx_L33:; + } + goto __pyx_L30; + } + __pyx_L30:; - /* "sklearn/tree/_tree.pyx":1557 - * cdef double* var_right = self.var_right + /* "sklearn/tree/_tree.pyx":1793 * - * cdef int n_outputs = self.n_outputs # <<<<<<<<<<<<<< + * # Reset sample mask + * for p in range(start, end): # <<<<<<<<<<<<<< + * sample_mask[samples[p]] = 0 * - * cdef int k */ - __pyx_v_n_outputs = __pyx_v_self->__pyx_base.n_outputs; + __pyx_t_7 = __pyx_v_end; + for (__pyx_t_2 = __pyx_v_start; __pyx_t_2 < __pyx_t_7; __pyx_t_2+=1) { + __pyx_v_p = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1560 - * - * cdef int k - * cdef double total = 0.0 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1794 + * # Reset sample mask + * for p in range(start, end): + * sample_mask[samples[p]] = 0 # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: + * # Respect invariant for constant features: the original order of */ - __pyx_v_total = 0.0; + (__pyx_v_sample_mask[(__pyx_v_samples[__pyx_v_p])]) = 0; + } - /* "sklearn/tree/_tree.pyx":1562 - * cdef double total = 0.0 + /* "sklearn/tree/_tree.pyx":1799 + * # element in features[:n_known_constants] must be preserved for sibling + * # and child nodes + * memcpy(features, constant_features, sizeof(SIZE_t) * n_known_constants) # <<<<<<<<<<<<<< * - * for k from 0 <= k < n_outputs: # <<<<<<<<<<<<<< - * total += var_left[k] - * total += var_right[k] + * # Copy newly found constant features */ - __pyx_t_1 = __pyx_v_n_outputs; - for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_1; __pyx_v_k++) { + memcpy(__pyx_v_features, __pyx_v_constant_features, ((sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)) * __pyx_v_n_known_constants)); - /* "sklearn/tree/_tree.pyx":1563 - * - * for k from 0 <= k < n_outputs: - * total += var_left[k] # <<<<<<<<<<<<<< - * total += var_right[k] + /* "sklearn/tree/_tree.pyx":1802 * + * # Copy newly found constant features + * memcpy(constant_features + n_known_constants, # <<<<<<<<<<<<<< + * features + n_known_constants, + * sizeof(SIZE_t) * n_found_constants) */ - __pyx_v_total = (__pyx_v_total + (__pyx_v_var_left[__pyx_v_k])); + memcpy((__pyx_v_constant_features + __pyx_v_n_known_constants), (__pyx_v_features + __pyx_v_n_known_constants), ((sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)) * __pyx_v_n_found_constants)); - /* "sklearn/tree/_tree.pyx":1564 - * for k from 0 <= k < n_outputs: - * total += var_left[k] - * total += var_right[k] # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1807 + * + * # Return values + * split[0] = best # <<<<<<<<<<<<<< + * n_constant_features[0] = n_total_constants * - * return total / n_outputs */ - __pyx_v_total = (__pyx_v_total + (__pyx_v_var_right[__pyx_v_k])); - } + (__pyx_v_split[0]) = __pyx_v_best; - /* "sklearn/tree/_tree.pyx":1566 - * total += var_right[k] + /* "sklearn/tree/_tree.pyx":1808 + * # Return values + * split[0] = best + * n_constant_features[0] = n_total_constants # <<<<<<<<<<<<<< * - * return total / n_outputs # <<<<<<<<<<<<<< * + */ + (__pyx_v_n_constant_features[0]) = __pyx_v_n_total_constants; + + /* "sklearn/tree/_tree.pyx":1618 + * memset(sample_mask, 0, self.n_total_samples) * + * cdef void node_split(self, double impurity, SplitRecord* split, # <<<<<<<<<<<<<< + * SIZE_t* n_constant_features) nogil: + * """Find the best split on node samples[start:end].""" */ - __pyx_r = (__pyx_v_total / __pyx_v_n_outputs); - goto __pyx_L0; - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; + /* function exit code */ } -/* "sklearn/tree/_tree.pyx":1573 - * # ============================================================================== +/* "sklearn/tree/_tree.pyx":1822 + * cdef SIZE_t* sorted_samples * - * cdef inline np.ndarray intp_to_ndarray(int* data, int size): # <<<<<<<<<<<<<< - * """Encapsulate data into a 1D numpy array of int's.""" - * cdef np.npy_intp shape[1] + * def __cinit__(self, Criterion criterion, SIZE_t max_features, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, double min_weight_leaf, + * object random_state): */ -static CYTHON_INLINE PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_intp_to_ndarray(int *__pyx_v_data, int __pyx_v_size) { - npy_intp __pyx_v_shape[1]; - PyArrayObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_18BaseSparseSplitter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_18BaseSparseSplitter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion = 0; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + CYTHON_UNUSED double __pyx_v_min_weight_leaf; + CYTHON_UNUSED PyObject *__pyx_v_random_state = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("intp_to_ndarray", 0); + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_criterion,&__pyx_n_s_max_features,&__pyx_n_s_min_samples_leaf,&__pyx_n_s_min_weight_leaf,&__pyx_n_s_random_state,0}; + PyObject* values[5] = {0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_criterion)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_features)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1822; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_samples_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1822; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_weight_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1822; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_random_state)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1822; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1822; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + } + __pyx_v_criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)values[0]); + __pyx_v_max_features = __Pyx_PyInt_As_Py_intptr_t(values[1]); if (unlikely((__pyx_v_max_features == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1822; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_samples_leaf = __Pyx_PyInt_As_Py_intptr_t(values[2]); if (unlikely((__pyx_v_min_samples_leaf == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1823; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_weight_leaf = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_min_weight_leaf == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1823; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_random_state = values[4]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1822; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._tree.BaseSparseSplitter.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_criterion), __pyx_ptype_7sklearn_4tree_5_tree_Criterion, 1, "criterion", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_18BaseSparseSplitter___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *)__pyx_v_self), __pyx_v_criterion, __pyx_v_max_features, __pyx_v_min_samples_leaf, __pyx_v_min_weight_leaf, __pyx_v_random_state); - /* "sklearn/tree/_tree.pyx":1576 - * """Encapsulate data into a 1D numpy array of int's.""" - * cdef np.npy_intp shape[1] - * shape[0] = size # <<<<<<<<<<<<<< - * return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT, data) + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_5_tree_18BaseSparseSplitter___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *__pyx_v_self, CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *__pyx_v_criterion, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features, CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, CYTHON_UNUSED double __pyx_v_min_weight_leaf, CYTHON_UNUSED PyObject *__pyx_v_random_state) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "sklearn/tree/_tree.pyx":1827 + * # Parent __cinit__ is automatically called * + * self.X_data = NULL # <<<<<<<<<<<<<< + * self.X_indices = NULL + * self.X_indptr = NULL */ - (__pyx_v_shape[0]) = ((npy_intp)__pyx_v_size); + __pyx_v_self->X_data = NULL; - /* "sklearn/tree/_tree.pyx":1577 - * cdef np.npy_intp shape[1] - * shape[0] = size - * return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT, data) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1828 + * + * self.X_data = NULL + * self.X_indices = NULL # <<<<<<<<<<<<<< + * self.X_indptr = NULL * - * cdef inline np.ndarray doublep_to_ndarray(double* data, int size): */ - __Pyx_XDECREF(((PyObject *)__pyx_r)); - __pyx_t_1 = PyArray_SimpleNewFromData(1, __pyx_v_shape, NPY_INT, __pyx_v_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1577; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1577; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_v_self->X_indices = NULL; - __pyx_r = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.intp_to_ndarray", __pyx_clineno, __pyx_lineno, __pyx_filename); + /* "sklearn/tree/_tree.pyx":1829 + * self.X_data = NULL + * self.X_indices = NULL + * self.X_indptr = NULL # <<<<<<<<<<<<<< + * + * self.n_total_samples = 0 + */ + __pyx_v_self->X_indptr = NULL; + + /* "sklearn/tree/_tree.pyx":1831 + * self.X_indptr = NULL + * + * self.n_total_samples = 0 # <<<<<<<<<<<<<< + * + * self.index_to_samples = NULL + */ + __pyx_v_self->n_total_samples = 0; + + /* "sklearn/tree/_tree.pyx":1833 + * self.n_total_samples = 0 + * + * self.index_to_samples = NULL # <<<<<<<<<<<<<< + * self.sorted_samples = NULL + * + */ + __pyx_v_self->index_to_samples = NULL; + + /* "sklearn/tree/_tree.pyx":1834 + * + * self.index_to_samples = NULL + * self.sorted_samples = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(self): + */ + __pyx_v_self->sorted_samples = NULL; + + /* "sklearn/tree/_tree.pyx":1822 + * cdef SIZE_t* sorted_samples + * + * def __cinit__(self, Criterion criterion, SIZE_t max_features, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, double min_weight_leaf, + * object random_state): + */ + + /* function exit code */ __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/tree/_tree.pyx":1579 - * return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT, data) +/* "sklearn/tree/_tree.pyx":1836 + * self.sorted_samples = NULL * - * cdef inline np.ndarray doublep_to_ndarray(double* data, int size): # <<<<<<<<<<<<<< - * """Encapsulate data into a 1D numpy array of double's.""" - * cdef np.npy_intp shape[1] + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Deallocate memory""" + * free(self.index_to_samples) */ -static CYTHON_INLINE PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_doublep_to_ndarray(double *__pyx_v_data, int __pyx_v_size) { - npy_intp __pyx_v_shape[1]; - PyArrayObject *__pyx_r = NULL; +/* Python wrapper */ +static void __pyx_pw_7sklearn_4tree_5_tree_18BaseSparseSplitter_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_7sklearn_4tree_5_tree_18BaseSparseSplitter_3__dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_pf_7sklearn_4tree_5_tree_18BaseSparseSplitter_2__dealloc__(((struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_7sklearn_4tree_5_tree_18BaseSparseSplitter_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "sklearn/tree/_tree.pyx":1838 + * def __dealloc__(self): + * """Deallocate memory""" + * free(self.index_to_samples) # <<<<<<<<<<<<<< + * free(self.sorted_samples) + * + */ + free(__pyx_v_self->index_to_samples); + + /* "sklearn/tree/_tree.pyx":1839 + * """Deallocate memory""" + * free(self.index_to_samples) + * free(self.sorted_samples) # <<<<<<<<<<<<<< + * + * cdef void init(self, + */ + free(__pyx_v_self->sorted_samples); + + /* "sklearn/tree/_tree.pyx":1836 + * self.sorted_samples = NULL + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Deallocate memory""" + * free(self.index_to_samples) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "sklearn/tree/_tree.pyx":1841 + * free(self.sorted_samples) + * + * cdef void init(self, # <<<<<<<<<<<<<< + * object X, + * np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, + */ + +static void __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter_init(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *__pyx_v_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_samples; + PyArrayObject *__pyx_v_data = 0; + PyArrayObject *__pyx_v_indices = 0; + PyArrayObject *__pyx_v_indptr = 0; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_total_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_index_to_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __Pyx_LocalBuf_ND __pyx_pybuffernd_data; + __Pyx_Buffer __pyx_pybuffer_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices; + __Pyx_Buffer __pyx_pybuffer_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr; + __Pyx_Buffer __pyx_pybuffer_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_y; + __Pyx_Buffer __pyx_pybuffer_y; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_4; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_5; + PyArrayObject *__pyx_t_6 = NULL; + PyArrayObject *__pyx_t_7 = NULL; + PyArrayObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_10; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("doublep_to_ndarray", 0); + __Pyx_RefNannySetupContext("init", 0); + __pyx_pybuffer_data.pybuffer.buf = NULL; + __pyx_pybuffer_data.refcount = 0; + __pyx_pybuffernd_data.data = NULL; + __pyx_pybuffernd_data.rcbuffer = &__pyx_pybuffer_data; + __pyx_pybuffer_indices.pybuffer.buf = NULL; + __pyx_pybuffer_indices.refcount = 0; + __pyx_pybuffernd_indices.data = NULL; + __pyx_pybuffernd_indices.rcbuffer = &__pyx_pybuffer_indices; + __pyx_pybuffer_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_indptr.refcount = 0; + __pyx_pybuffernd_indptr.data = NULL; + __pyx_pybuffernd_indptr.rcbuffer = &__pyx_pybuffer_indptr; + __pyx_pybuffer_y.pybuffer.buf = NULL; + __pyx_pybuffer_y.refcount = 0; + __pyx_pybuffernd_y.data = NULL; + __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DOUBLE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_y.diminfo[1].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_y.diminfo[1].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[1]; - /* "sklearn/tree/_tree.pyx":1582 - * """Encapsulate data into a 1D numpy array of double's.""" - * cdef np.npy_intp shape[1] - * shape[0] = size # <<<<<<<<<<<<<< - * return np.PyArray_SimpleNewFromData(1, shape, np.NPY_DOUBLE, data) + /* "sklearn/tree/_tree.pyx":1848 + * + * # Call parent init + * Splitter.init(self, X, y, sample_weight) # <<<<<<<<<<<<<< * + * if not isinstance(X, csc_matrix): */ - (__pyx_v_shape[0]) = ((npy_intp)__pyx_v_size); + __pyx_f_7sklearn_4tree_5_tree_8Splitter_init(((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_v_self), __pyx_v_X, ((PyArrayObject *)__pyx_v_y), __pyx_v_sample_weight); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1848; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/tree/_tree.pyx":1583 - * cdef np.npy_intp shape[1] - * shape[0] = size - * return np.PyArray_SimpleNewFromData(1, shape, np.NPY_DOUBLE, data) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1850 + * Splitter.init(self, X, y, sample_weight) + * + * if not isinstance(X, csc_matrix): # <<<<<<<<<<<<<< + * raise ValueError("X should be in csc format") * - * cdef inline int _smallest_sample_larger_than(int sample_idx, */ - __Pyx_XDECREF(((PyObject *)__pyx_r)); - __pyx_t_1 = PyArray_SimpleNewFromData(1, __pyx_v_shape, NPY_DOUBLE, __pyx_v_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_csc_matrix); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1850; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1583; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("sklearn.tree._tree.doublep_to_ndarray", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF((PyObject *)__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_t_2 = PyObject_IsInstance(__pyx_v_X, __pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1850; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0); + if (__pyx_t_3) { -/* "sklearn/tree/_tree.pyx":1585 - * return np.PyArray_SimpleNewFromData(1, shape, np.NPY_DOUBLE, data) + /* "sklearn/tree/_tree.pyx":1851 + * + * if not isinstance(X, csc_matrix): + * raise ValueError("X should be in csc format") # <<<<<<<<<<<<<< * - * cdef inline int _smallest_sample_larger_than(int sample_idx, # <<<<<<<<<<<<<< - * DTYPE_t* X_i, - * int* X_argsorted_i, + * cdef SIZE_t* samples = self.samples */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1851; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1851; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } -static CYTHON_INLINE int __pyx_f_7sklearn_4tree_5_tree__smallest_sample_larger_than(int __pyx_v_sample_idx, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_i, int *__pyx_v_X_argsorted_i, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *__pyx_v_sample_mask, int __pyx_v_n_total_samples) { - int __pyx_v_idx; - int __pyx_v_j; - __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_threshold; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - __Pyx_RefNannySetupContext("_smallest_sample_larger_than", 0); + /* "sklearn/tree/_tree.pyx":1853 + * raise ValueError("X should be in csc format") + * + * cdef SIZE_t* samples = self.samples # <<<<<<<<<<<<<< + * cdef SIZE_t n_samples = self.n_samples + * + */ + __pyx_t_4 = __pyx_v_self->__pyx_base.samples; + __pyx_v_samples = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":1604 - * -1 if no such element exists. - * """ - * cdef int idx = 0, j # <<<<<<<<<<<<<< - * cdef DTYPE_t threshold = -DBL_MAX + /* "sklearn/tree/_tree.pyx":1854 * + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t n_samples = self.n_samples # <<<<<<<<<<<<<< + * + * # Initialize X */ - __pyx_v_idx = 0; + __pyx_t_5 = __pyx_v_self->__pyx_base.n_samples; + __pyx_v_n_samples = __pyx_t_5; - /* "sklearn/tree/_tree.pyx":1605 - * """ - * cdef int idx = 0, j - * cdef DTYPE_t threshold = -DBL_MAX # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1857 * - * if sample_idx > -1: + * # Initialize X + * cdef np.ndarray[dtype=DTYPE_t, ndim=1] data = X.data # <<<<<<<<<<<<<< + * cdef np.ndarray[dtype=INT32_t, ndim=1] indices = X.indices + * cdef np.ndarray[dtype=INT32_t, ndim=1] indptr = X.indptr + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_data.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_data.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_data.diminfo[0].strides = __pyx_pybuffernd_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_data.diminfo[0].shape = __pyx_pybuffernd_data.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __pyx_v_data = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":1858 + * # Initialize X + * cdef np.ndarray[dtype=DTYPE_t, ndim=1] data = X.data + * cdef np.ndarray[dtype=INT32_t, ndim=1] indices = X.indices # <<<<<<<<<<<<<< + * cdef np.ndarray[dtype=INT32_t, ndim=1] indptr = X.indptr + * cdef SIZE_t n_total_samples = X.shape[0] */ - __pyx_v_threshold = (-DBL_MAX); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1858; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1858; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_INT32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_indices.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1858; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_indices.diminfo[0].strides = __pyx_pybuffernd_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices.diminfo[0].shape = __pyx_pybuffernd_indices.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_7 = 0; + __pyx_v_indices = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; - /* "sklearn/tree/_tree.pyx":1607 - * cdef DTYPE_t threshold = -DBL_MAX + /* "sklearn/tree/_tree.pyx":1859 + * cdef np.ndarray[dtype=DTYPE_t, ndim=1] data = X.data + * cdef np.ndarray[dtype=INT32_t, ndim=1] indices = X.indices + * cdef np.ndarray[dtype=INT32_t, ndim=1] indptr = X.indptr # <<<<<<<<<<<<<< + * cdef SIZE_t n_total_samples = X.shape[0] * - * if sample_idx > -1: # <<<<<<<<<<<<<< - * threshold = X_i[X_argsorted_i[sample_idx]] + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1859; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1859; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_INT32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1859; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_indptr.diminfo[0].strides = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr.diminfo[0].shape = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_8 = 0; + __pyx_v_indptr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":1860 + * cdef np.ndarray[dtype=INT32_t, ndim=1] indices = X.indices + * cdef np.ndarray[dtype=INT32_t, ndim=1] indptr = X.indptr + * cdef SIZE_t n_total_samples = X.shape[0] # <<<<<<<<<<<<<< * + * self.X_data = data.data */ - __pyx_t_1 = (__pyx_v_sample_idx > -1); - if (__pyx_t_1) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_9 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1860; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_n_total_samples = __pyx_t_5; - /* "sklearn/tree/_tree.pyx":1608 + /* "sklearn/tree/_tree.pyx":1862 + * cdef SIZE_t n_total_samples = X.shape[0] * - * if sample_idx > -1: - * threshold = X_i[X_argsorted_i[sample_idx]] # <<<<<<<<<<<<<< + * self.X_data = data.data # <<<<<<<<<<<<<< + * self.X_indices = indices.data + * self.X_indptr = indptr.data + */ + __pyx_v_self->X_data = ((__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *)__pyx_v_data->data); + + /* "sklearn/tree/_tree.pyx":1863 * - * for idx from sample_idx < idx < n_total_samples: + * self.X_data = data.data + * self.X_indices = indices.data # <<<<<<<<<<<<<< + * self.X_indptr = indptr.data + * self.n_total_samples = n_total_samples */ - __pyx_v_threshold = (__pyx_v_X_i[(__pyx_v_X_argsorted_i[__pyx_v_sample_idx])]); - goto __pyx_L3; - } - __pyx_L3:; + __pyx_v_self->X_indices = ((__pyx_t_7sklearn_4tree_5_tree_INT32_t *)__pyx_v_indices->data); - /* "sklearn/tree/_tree.pyx":1610 - * threshold = X_i[X_argsorted_i[sample_idx]] + /* "sklearn/tree/_tree.pyx":1864 + * self.X_data = data.data + * self.X_indices = indices.data + * self.X_indptr = indptr.data # <<<<<<<<<<<<<< + * self.n_total_samples = n_total_samples * - * for idx from sample_idx < idx < n_total_samples: # <<<<<<<<<<<<<< - * j = X_argsorted_i[idx] + */ + __pyx_v_self->X_indptr = ((__pyx_t_7sklearn_4tree_5_tree_INT32_t *)__pyx_v_indptr->data); + + /* "sklearn/tree/_tree.pyx":1865 + * self.X_indices = indices.data + * self.X_indptr = indptr.data + * self.n_total_samples = n_total_samples # <<<<<<<<<<<<<< * + * # Initialize auxiliary array used to perform split */ - __pyx_t_2 = __pyx_v_n_total_samples; - for (__pyx_v_idx = __pyx_v_sample_idx+1; __pyx_v_idx < __pyx_t_2; __pyx_v_idx++) { + __pyx_v_self->n_total_samples = __pyx_v_n_total_samples; - /* "sklearn/tree/_tree.pyx":1611 + /* "sklearn/tree/_tree.pyx":1868 * - * for idx from sample_idx < idx < n_total_samples: - * j = X_argsorted_i[idx] # <<<<<<<<<<<<<< + * # Initialize auxiliary array used to perform split + * safe_realloc(&self.index_to_samples, n_total_samples * sizeof(SIZE_t)) # <<<<<<<<<<<<<< + * safe_realloc(&self.sorted_samples, n_samples * sizeof(SIZE_t)) * - * if sample_mask[j] == 0: */ - __pyx_v_j = (__pyx_v_X_argsorted_i[__pyx_v_idx]); + __pyx_fuse_1__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_self->index_to_samples), (__pyx_v_n_total_samples * (sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)))); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1868; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/tree/_tree.pyx":1613 - * j = X_argsorted_i[idx] + /* "sklearn/tree/_tree.pyx":1869 + * # Initialize auxiliary array used to perform split + * safe_realloc(&self.index_to_samples, n_total_samples * sizeof(SIZE_t)) + * safe_realloc(&self.sorted_samples, n_samples * sizeof(SIZE_t)) # <<<<<<<<<<<<<< * - * if sample_mask[j] == 0: # <<<<<<<<<<<<<< - * continue + * cdef SIZE_t* index_to_samples = self.index_to_samples + */ + __pyx_fuse_1__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_self->sorted_samples), (__pyx_v_n_samples * (sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)))); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1869; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":1871 + * safe_realloc(&self.sorted_samples, n_samples * sizeof(SIZE_t)) * + * cdef SIZE_t* index_to_samples = self.index_to_samples # <<<<<<<<<<<<<< + * cdef SIZE_t p + * for p in range(n_total_samples): */ - __pyx_t_1 = ((__pyx_v_sample_mask[__pyx_v_j]) == 0); - if (__pyx_t_1) { + __pyx_t_4 = __pyx_v_self->index_to_samples; + __pyx_v_index_to_samples = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":1614 + /* "sklearn/tree/_tree.pyx":1873 + * cdef SIZE_t* index_to_samples = self.index_to_samples + * cdef SIZE_t p + * for p in range(n_total_samples): # <<<<<<<<<<<<<< + * index_to_samples[p] = -1 * - * if sample_mask[j] == 0: - * continue # <<<<<<<<<<<<<< + */ + __pyx_t_5 = __pyx_v_n_total_samples; + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_5; __pyx_t_10+=1) { + __pyx_v_p = __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":1874 + * cdef SIZE_t p + * for p in range(n_total_samples): + * index_to_samples[p] = -1 # <<<<<<<<<<<<<< * - * if X_i[j] > threshold + 1.e-7: + * for p in range(n_samples): */ - goto __pyx_L4_continue; - goto __pyx_L6; - } - __pyx_L6:; + (__pyx_v_index_to_samples[__pyx_v_p]) = -1; + } - /* "sklearn/tree/_tree.pyx":1616 - * continue + /* "sklearn/tree/_tree.pyx":1876 + * index_to_samples[p] = -1 * - * if X_i[j] > threshold + 1.e-7: # <<<<<<<<<<<<<< - * return idx + * for p in range(n_samples): # <<<<<<<<<<<<<< + * index_to_samples[samples[p]] = p * */ - __pyx_t_1 = ((__pyx_v_X_i[__pyx_v_j]) > (__pyx_v_threshold + 1.e-7)); - if (__pyx_t_1) { + __pyx_t_5 = __pyx_v_n_samples; + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_5; __pyx_t_10+=1) { + __pyx_v_p = __pyx_t_10; - /* "sklearn/tree/_tree.pyx":1617 + /* "sklearn/tree/_tree.pyx":1877 * - * if X_i[j] > threshold + 1.e-7: - * return idx # <<<<<<<<<<<<<< + * for p in range(n_samples): + * index_to_samples[samples[p]] = p # <<<<<<<<<<<<<< * - * return -1 + * cdef inline SIZE_t _partition(self, double threshold, */ - __pyx_r = __pyx_v_idx; - goto __pyx_L0; - goto __pyx_L7; - } - __pyx_L7:; - __pyx_L4_continue:; + (__pyx_v_index_to_samples[(__pyx_v_samples[__pyx_v_p])]) = __pyx_v_p; } - /* "sklearn/tree/_tree.pyx":1619 - * return idx - * - * return -1 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1841 + * free(self.sorted_samples) * - * def _random_sample_mask(int n_total_samples, int n_total_in_bag, random_state): + * cdef void init(self, # <<<<<<<<<<<<<< + * object X, + * np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, */ - __pyx_r = -1; - goto __pyx_L0; - __pyx_r = 0; + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_9); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.tree._tree.BaseSparseSplitter.init", __pyx_clineno, __pyx_lineno, __pyx_filename); + goto __pyx_L2; __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_data); + __Pyx_XDECREF((PyObject *)__pyx_v_indices); + __Pyx_XDECREF((PyObject *)__pyx_v_indptr); __Pyx_RefNannyFinishContext(); - return __pyx_r; } -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_1_random_sample_mask(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_4tree_5_tree__random_sample_mask[] = "Create a random sample mask where ``n_total_in_bag`` elements are set.\n\n Parameters\n ----------\n n_total_samples : int\n The length of the resulting mask.\n\n n_total_in_bag : int\n The number of elements in the sample mask which are set to 1.\n\n random_state : np.RandomState\n A numpy ``RandomState`` object.\n\n Returns\n -------\n sample_mask : np.ndarray, shape=[n_total_samples]\n An ndarray where ``n_total_in_bag`` elements are set to ``True``\n the others are ``False``.\n "; -static PyMethodDef __pyx_mdef_7sklearn_4tree_5_tree_1_random_sample_mask = {__Pyx_NAMESTR("_random_sample_mask"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_1_random_sample_mask, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_4tree_5_tree__random_sample_mask)}; -static PyObject *__pyx_pw_7sklearn_4tree_5_tree_1_random_sample_mask(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - int __pyx_v_n_total_samples; - int __pyx_v_n_total_in_bag; - PyObject *__pyx_v_random_state = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_random_sample_mask (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_total_samples,&__pyx_n_s__n_total_in_bag,&__pyx_n_s__random_state,0}; - PyObject* values[3] = {0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_total_samples)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_total_in_bag)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_random_sample_mask", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1621; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__random_state)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_random_sample_mask", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1621; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_random_sample_mask") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1621; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - } - __pyx_v_n_total_samples = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_total_samples == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1621; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_n_total_in_bag = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_n_total_in_bag == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1621; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_random_state = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_random_sample_mask", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1621; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.tree._tree._random_sample_mask", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7sklearn_4tree_5_tree__random_sample_mask(__pyx_self, __pyx_v_n_total_samples, __pyx_v_n_total_in_bag, __pyx_v_random_state); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/tree/_tree.pyx":1621 - * return -1 +/* "sklearn/tree/_tree.pyx":1879 + * index_to_samples[samples[p]] = p * - * def _random_sample_mask(int n_total_samples, int n_total_in_bag, random_state): # <<<<<<<<<<<<<< - * """Create a random sample mask where ``n_total_in_bag`` elements are set. - * - */ - -static PyObject *__pyx_pf_7sklearn_4tree_5_tree__random_sample_mask(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_total_samples, int __pyx_v_n_total_in_bag, PyObject *__pyx_v_random_state) { - PyArrayObject *__pyx_v_rand = 0; - PyArrayObject *__pyx_v_sample_mask = 0; - int __pyx_v_n_bagged; - int __pyx_v_i; - __Pyx_LocalBuf_ND __pyx_pybuffernd_rand; - __Pyx_Buffer __pyx_pybuffer_rand; - __Pyx_LocalBuf_ND __pyx_pybuffernd_sample_mask; - __Pyx_Buffer __pyx_pybuffer_sample_mask; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyArrayObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyArrayObject *__pyx_t_7 = NULL; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; - int __pyx_t_11; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_random_sample_mask", 0); - __pyx_pybuffer_rand.pybuffer.buf = NULL; - __pyx_pybuffer_rand.refcount = 0; - __pyx_pybuffernd_rand.data = NULL; - __pyx_pybuffernd_rand.rcbuffer = &__pyx_pybuffer_rand; - __pyx_pybuffer_sample_mask.pybuffer.buf = NULL; - __pyx_pybuffer_sample_mask.refcount = 0; - __pyx_pybuffernd_sample_mask.data = NULL; - __pyx_pybuffernd_sample_mask.rcbuffer = &__pyx_pybuffer_sample_mask; - - /* "sklearn/tree/_tree.pyx":1642 - * """ - * cdef np.ndarray[np.float64_t, ndim=1, mode="c"] rand = \ - * random_state.rand(n_total_samples) # <<<<<<<<<<<<<< - * cdef np.ndarray[BOOL_t, ndim=1, mode="c"] sample_mask = \ - * np.zeros((n_total_samples,), dtype=np.int8) + * cdef inline SIZE_t _partition(self, double threshold, # <<<<<<<<<<<<<< + * SIZE_t end_negative, SIZE_t start_positive, + * SIZE_t zero_pos) nogil: */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_random_state, __pyx_n_s__rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromLong(__pyx_v_n_total_samples); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = ((PyArrayObject *)__pyx_t_2); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_rand.rcbuffer->pybuffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - __pyx_v_rand = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_rand.rcbuffer->pybuffer.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_pybuffernd_rand.diminfo[0].strides = __pyx_pybuffernd_rand.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_rand.diminfo[0].shape = __pyx_pybuffernd_rand.rcbuffer->pybuffer.shape[0]; - } - } - __pyx_t_4 = 0; - __pyx_v_rand = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - /* "sklearn/tree/_tree.pyx":1644 - * random_state.rand(n_total_samples) - * cdef np.ndarray[BOOL_t, ndim=1, mode="c"] sample_mask = \ - * np.zeros((n_total_samples,), dtype=np.int8) # <<<<<<<<<<<<<< - * - * cdef int n_bagged = 0 - */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyInt_FromLong(__pyx_v_n_total_samples); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_1)); - __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__int8); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1644; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = ((PyArrayObject *)__pyx_t_6); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_mask.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_BOOL_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_sample_mask = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_sample_mask.rcbuffer->pybuffer.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_pybuffernd_sample_mask.diminfo[0].strides = __pyx_pybuffernd_sample_mask.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_mask.diminfo[0].shape = __pyx_pybuffernd_sample_mask.rcbuffer->pybuffer.shape[0]; - } - } - __pyx_t_7 = 0; - __pyx_v_sample_mask = ((PyArrayObject *)__pyx_t_6); - __pyx_t_6 = 0; +static CYTHON_INLINE __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter__partition(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *__pyx_v_self, double __pyx_v_threshold, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end_negative, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start_positive, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_zero_pos) { + double __pyx_v_value; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_partition_end; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_index_to_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_r; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_2; + int __pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_4; - /* "sklearn/tree/_tree.pyx":1646 - * np.zeros((n_total_samples,), dtype=np.int8) - * - * cdef int n_bagged = 0 # <<<<<<<<<<<<<< - * cdef int i = 0 + /* "sklearn/tree/_tree.pyx":1888 + * cdef SIZE_t p * + * cdef DTYPE_t* Xf = self.feature_values # <<<<<<<<<<<<<< + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t* index_to_samples = self.index_to_samples */ - __pyx_v_n_bagged = 0; + __pyx_t_1 = __pyx_v_self->__pyx_base.feature_values; + __pyx_v_Xf = __pyx_t_1; - /* "sklearn/tree/_tree.pyx":1647 + /* "sklearn/tree/_tree.pyx":1889 * - * cdef int n_bagged = 0 - * cdef int i = 0 # <<<<<<<<<<<<<< + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t* samples = self.samples # <<<<<<<<<<<<<< + * cdef SIZE_t* index_to_samples = self.index_to_samples * - * for i from 0 <= i < n_total_samples: */ - __pyx_v_i = 0; + __pyx_t_2 = __pyx_v_self->__pyx_base.samples; + __pyx_v_samples = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1649 - * cdef int i = 0 + /* "sklearn/tree/_tree.pyx":1890 + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t* index_to_samples = self.index_to_samples # <<<<<<<<<<<<<< * - * for i from 0 <= i < n_total_samples: # <<<<<<<<<<<<<< - * if rand[i] * (n_total_samples - i) < (n_total_in_bag - n_bagged): - * sample_mask[i] = 1 + * if threshold < 0.: */ - __pyx_t_8 = __pyx_v_n_total_samples; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_8; __pyx_v_i++) { + __pyx_t_2 = __pyx_v_self->index_to_samples; + __pyx_v_index_to_samples = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":1650 + /* "sklearn/tree/_tree.pyx":1892 + * cdef SIZE_t* index_to_samples = self.index_to_samples * - * for i from 0 <= i < n_total_samples: - * if rand[i] * (n_total_samples - i) < (n_total_in_bag - n_bagged): # <<<<<<<<<<<<<< - * sample_mask[i] = 1 - * n_bagged += 1 + * if threshold < 0.: # <<<<<<<<<<<<<< + * p = self.start + * partition_end = end_negative */ - __pyx_t_9 = __pyx_v_i; - __pyx_t_10 = (((*__Pyx_BufPtrCContig1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_rand.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_rand.diminfo[0].strides)) * (__pyx_v_n_total_samples - __pyx_v_i)) < (__pyx_v_n_total_in_bag - __pyx_v_n_bagged)); - if (__pyx_t_10) { + __pyx_t_3 = ((__pyx_v_threshold < 0.) != 0); + if (__pyx_t_3) { - /* "sklearn/tree/_tree.pyx":1651 - * for i from 0 <= i < n_total_samples: - * if rand[i] * (n_total_samples - i) < (n_total_in_bag - n_bagged): - * sample_mask[i] = 1 # <<<<<<<<<<<<<< - * n_bagged += 1 + /* "sklearn/tree/_tree.pyx":1893 * + * if threshold < 0.: + * p = self.start # <<<<<<<<<<<<<< + * partition_end = end_negative + * elif threshold > 0.: */ - __pyx_t_11 = __pyx_v_i; - *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_4tree_5_tree_BOOL_t *, __pyx_pybuffernd_sample_mask.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_sample_mask.diminfo[0].strides) = 1; + __pyx_t_4 = __pyx_v_self->__pyx_base.start; + __pyx_v_p = __pyx_t_4; - /* "sklearn/tree/_tree.pyx":1652 - * if rand[i] * (n_total_samples - i) < (n_total_in_bag - n_bagged): - * sample_mask[i] = 1 - * n_bagged += 1 # <<<<<<<<<<<<<< - * - * return sample_mask.astype(np.bool) + /* "sklearn/tree/_tree.pyx":1894 + * if threshold < 0.: + * p = self.start + * partition_end = end_negative # <<<<<<<<<<<<<< + * elif threshold > 0.: + * p = start_positive */ - __pyx_v_n_bagged = (__pyx_v_n_bagged + 1); - goto __pyx_L5; - } - __pyx_L5:; + __pyx_v_partition_end = __pyx_v_end_negative; + goto __pyx_L3; } - /* "sklearn/tree/_tree.pyx":1654 - * n_bagged += 1 - * - * return sample_mask.astype(np.bool) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1895 + * p = self.start + * partition_end = end_negative + * elif threshold > 0.: # <<<<<<<<<<<<<< + * p = start_positive + * partition_end = self.end */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_6 = PyObject_GetAttr(((PyObject *)__pyx_v_sample_mask), __pyx_n_s__astype); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__bool); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_rand.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_mask.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.tree._tree._random_sample_mask", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_rand.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_mask.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_rand); - __Pyx_XDECREF((PyObject *)__pyx_v_sample_mask); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + __pyx_t_3 = ((__pyx_v_threshold > 0.) != 0); + if (__pyx_t_3) { -/* "numpy.pxd":194 - * # experimental exception made for __getbuffer__ and __releasebuffer__ - * # -- the details of this may change. - * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< - * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP. + /* "sklearn/tree/_tree.pyx":1896 + * partition_end = end_negative + * elif threshold > 0.: + * p = start_positive # <<<<<<<<<<<<<< + * partition_end = self.end + * else: */ + __pyx_v_p = __pyx_v_start_positive; -static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_v_copy_shape; - int __pyx_v_i; - int __pyx_v_ndim; - int __pyx_v_endian_detector; - int __pyx_v_little_endian; - int __pyx_v_t; - char *__pyx_v_f; - PyArray_Descr *__pyx_v_descr = 0; - int __pyx_v_offset; - int __pyx_v_hasfields; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - char *__pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__", 0); - if (__pyx_v_info != NULL) { - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); + /* "sklearn/tree/_tree.pyx":1897 + * elif threshold > 0.: + * p = start_positive + * partition_end = self.end # <<<<<<<<<<<<<< + * else: + * # Data are already split + */ + __pyx_t_4 = __pyx_v_self->__pyx_base.end; + __pyx_v_partition_end = __pyx_t_4; + goto __pyx_L3; } + /*else*/ { - /* "numpy.pxd":200 - * # of flags - * - * if info == NULL: return # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1900 + * else: + * # Data are already split + * return zero_pos # <<<<<<<<<<<<<< * - * cdef int copy_shape, i, ndim + * while p < partition_end: */ - __pyx_t_1 = (__pyx_v_info == NULL); - if (__pyx_t_1) { - __pyx_r = 0; + __pyx_r = __pyx_v_zero_pos; goto __pyx_L0; - goto __pyx_L3; } __pyx_L3:; - /* "numpy.pxd":203 + /* "sklearn/tree/_tree.pyx":1902 + * return zero_pos * - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) + * while p < partition_end: # <<<<<<<<<<<<<< + * value = Xf[p] * */ - __pyx_v_endian_detector = 1; + while (1) { + __pyx_t_3 = ((__pyx_v_p < __pyx_v_partition_end) != 0); + if (!__pyx_t_3) break; - /* "numpy.pxd":204 - * cdef int copy_shape, i, ndim - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1903 * - * ndim = PyArray_NDIM(self) + * while p < partition_end: + * value = Xf[p] # <<<<<<<<<<<<<< + * + * if value <= threshold: */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + __pyx_v_value = (__pyx_v_Xf[__pyx_v_p]); - /* "numpy.pxd":206 - * cdef bint little_endian = ((&endian_detector)[0] != 0) + /* "sklearn/tree/_tree.pyx":1905 + * value = Xf[p] * - * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * if value <= threshold: # <<<<<<<<<<<<<< + * p += 1 * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + __pyx_t_3 = ((__pyx_v_value <= __pyx_v_threshold) != 0); + if (__pyx_t_3) { - /* "numpy.pxd":208 - * ndim = PyArray_NDIM(self) + /* "sklearn/tree/_tree.pyx":1906 + * + * if value <= threshold: + * p += 1 # <<<<<<<<<<<<<< * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * copy_shape = 1 * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); - if (__pyx_t_1) { + __pyx_v_p = (__pyx_v_p + 1); + goto __pyx_L6; + } + /*else*/ { - /* "numpy.pxd":209 + /* "sklearn/tree/_tree.pyx":1909 * - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * copy_shape = 1 # <<<<<<<<<<<<<< * else: - * copy_shape = 0 + * partition_end -= 1 # <<<<<<<<<<<<<< + * + * Xf[p] = Xf[partition_end] */ - __pyx_v_copy_shape = 1; - goto __pyx_L4; - } - /*else*/ { + __pyx_v_partition_end = (__pyx_v_partition_end - 1); - /* "numpy.pxd":211 - * copy_shape = 1 - * else: - * copy_shape = 0 # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1911 + * partition_end -= 1 * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * Xf[p] = Xf[partition_end] # <<<<<<<<<<<<<< + * Xf[partition_end] = value + * sparse_swap(index_to_samples, samples, p, partition_end) */ - __pyx_v_copy_shape = 0; - } - __pyx_L4:; + (__pyx_v_Xf[__pyx_v_p]) = (__pyx_v_Xf[__pyx_v_partition_end]); - /* "numpy.pxd":213 - * copy_shape = 0 + /* "sklearn/tree/_tree.pyx":1912 + * + * Xf[p] = Xf[partition_end] + * Xf[partition_end] = value # <<<<<<<<<<<<<< + * sparse_swap(index_to_samples, samples, p, partition_end) * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); - if (__pyx_t_1) { + (__pyx_v_Xf[__pyx_v_partition_end]) = __pyx_v_value; - /* "numpy.pxd":214 - * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not C contiguous") + /* "sklearn/tree/_tree.pyx":1913 + * Xf[p] = Xf[partition_end] + * Xf[partition_end] = value + * sparse_swap(index_to_samples, samples, p, partition_end) # <<<<<<<<<<<<<< * + * return partition_end */ - __pyx_t_2 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS)); - __pyx_t_3 = __pyx_t_2; - } else { - __pyx_t_3 = __pyx_t_1; + __pyx_f_7sklearn_4tree_5_tree_sparse_swap(__pyx_v_index_to_samples, __pyx_v_samples, __pyx_v_p, __pyx_v_partition_end); + } + __pyx_L6:; } - if (__pyx_t_3) { - /* "numpy.pxd":215 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1915 + * sparse_swap(index_to_samples, samples, p, partition_end) * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "numpy.pxd":217 - * raise ValueError(u"ndarray is not C contiguous") + * return partition_end # <<<<<<<<<<<<<< * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") + * cdef inline void extract_nnz(self, SIZE_t feature, */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); - if (__pyx_t_3) { + __pyx_r = __pyx_v_partition_end; + goto __pyx_L0; - /* "numpy.pxd":218 - * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not Fortran contiguous") + /* "sklearn/tree/_tree.pyx":1879 + * index_to_samples[samples[p]] = p * + * cdef inline SIZE_t _partition(self, double threshold, # <<<<<<<<<<<<<< + * SIZE_t end_negative, SIZE_t start_positive, + * SIZE_t zero_pos) nogil: */ - __pyx_t_1 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS)); - __pyx_t_2 = __pyx_t_1; - } else { - __pyx_t_2 = __pyx_t_3; - } - if (__pyx_t_2) { - /* "numpy.pxd":219 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< - * - * info.buf = PyArray_DATA(self) - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} - /* "numpy.pxd":221 - * raise ValueError(u"ndarray is not Fortran contiguous") +/* "sklearn/tree/_tree.pyx":1917 + * return partition_end * - * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< - * info.ndim = ndim - * if copy_shape: + * cdef inline void extract_nnz(self, SIZE_t feature, # <<<<<<<<<<<<<< + * SIZE_t* end_negative, SIZE_t* start_positive, + * bint* is_samples_sorted) nogil: */ - __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":222 - * - * info.buf = PyArray_DATA(self) - * info.ndim = ndim # <<<<<<<<<<<<<< - * if copy_shape: - * # Allocate new buffer for strides and shape info. - */ - __pyx_v_info->ndim = __pyx_v_ndim; +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter_extract_nnz(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_feature, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_end_negative, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_start_positive, int *__pyx_v_is_samples_sorted) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_indptr_start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_indptr_end; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_indices; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_samples; + int __pyx_t_1; - /* "numpy.pxd":223 - * info.buf = PyArray_DATA(self) - * info.ndim = ndim - * if copy_shape: # <<<<<<<<<<<<<< - * # Allocate new buffer for strides and shape info. - * # This is allocated as one block, strides first. + /* "sklearn/tree/_tree.pyx":1949 + * + * """ + * cdef SIZE_t indptr_start = self.X_indptr[feature], # <<<<<<<<<<<<<< + * cdef SIZE_t indptr_end = self.X_indptr[feature + 1] + * cdef SIZE_t n_indices = (indptr_end - indptr_start) */ - if (__pyx_v_copy_shape) { + __pyx_v_indptr_start = (__pyx_v_self->X_indptr[__pyx_v_feature]); - /* "numpy.pxd":226 - * # Allocate new buffer for strides and shape info. - * # This is allocated as one block, strides first. - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< - * info.shape = info.strides + ndim - * for i in range(ndim): + /* "sklearn/tree/_tree.pyx":1950 + * """ + * cdef SIZE_t indptr_start = self.X_indptr[feature], + * cdef SIZE_t indptr_end = self.X_indptr[feature + 1] # <<<<<<<<<<<<<< + * cdef SIZE_t n_indices = (indptr_end - indptr_start) + * cdef SIZE_t n_samples = self.end - self.start */ - __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + __pyx_v_indptr_end = (__pyx_v_self->X_indptr[(__pyx_v_feature + 1)]); - /* "numpy.pxd":227 - * # This is allocated as one block, strides first. - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) - * info.shape = info.strides + ndim # <<<<<<<<<<<<<< - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] + /* "sklearn/tree/_tree.pyx":1951 + * cdef SIZE_t indptr_start = self.X_indptr[feature], + * cdef SIZE_t indptr_end = self.X_indptr[feature + 1] + * cdef SIZE_t n_indices = (indptr_end - indptr_start) # <<<<<<<<<<<<<< + * cdef SIZE_t n_samples = self.end - self.start + * */ - __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + __pyx_v_n_indices = ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)(__pyx_v_indptr_end - __pyx_v_indptr_start)); - /* "numpy.pxd":228 - * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) - * info.shape = info.strides + ndim - * for i in range(ndim): # <<<<<<<<<<<<<< - * info.strides[i] = PyArray_STRIDES(self)[i] - * info.shape[i] = PyArray_DIMS(self)[i] + /* "sklearn/tree/_tree.pyx":1952 + * cdef SIZE_t indptr_end = self.X_indptr[feature + 1] + * cdef SIZE_t n_indices = (indptr_end - indptr_start) + * cdef SIZE_t n_samples = self.end - self.start # <<<<<<<<<<<<<< + * + * # Use binary search if n_samples * log(n_indices) < */ - __pyx_t_5 = __pyx_v_ndim; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; + __pyx_v_n_samples = (__pyx_v_self->__pyx_base.end - __pyx_v_self->__pyx_base.start); - /* "numpy.pxd":229 - * info.shape = info.strides + ndim - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< - * info.shape[i] = PyArray_DIMS(self)[i] - * else: + /* "sklearn/tree/_tree.pyx":1960 + * # approach. + * if ((1 - is_samples_sorted[0]) * n_samples * log(n_samples) + + * n_samples * log(n_indices) < EXTRACT_NNZ_SWITCH * n_indices): # <<<<<<<<<<<<<< + * extract_nnz_binary_search(self.X_indices, self.X_data, + * indptr_start, indptr_end, */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + __pyx_t_1 = ((((((1 - (__pyx_v_is_samples_sorted[0])) * __pyx_v_n_samples) * __pyx_f_7sklearn_4tree_5_tree_log(__pyx_v_n_samples)) + (__pyx_v_n_samples * __pyx_f_7sklearn_4tree_5_tree_log(__pyx_v_n_indices))) < (__pyx_v_7sklearn_4tree_5_tree_EXTRACT_NNZ_SWITCH * __pyx_v_n_indices)) != 0); + if (__pyx_t_1) { - /* "numpy.pxd":230 - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] - * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< - * else: - * info.strides = PyArray_STRIDES(self) + /* "sklearn/tree/_tree.pyx":1961 + * if ((1 - is_samples_sorted[0]) * n_samples * log(n_samples) + + * n_samples * log(n_indices) < EXTRACT_NNZ_SWITCH * n_indices): + * extract_nnz_binary_search(self.X_indices, self.X_data, # <<<<<<<<<<<<<< + * indptr_start, indptr_end, + * self.samples, self.start, self.end, */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); - } - goto __pyx_L7; + __pyx_f_7sklearn_4tree_5_tree_extract_nnz_binary_search(__pyx_v_self->X_indices, __pyx_v_self->X_data, __pyx_v_indptr_start, __pyx_v_indptr_end, __pyx_v_self->__pyx_base.samples, __pyx_v_self->__pyx_base.start, __pyx_v_self->__pyx_base.end, __pyx_v_self->index_to_samples, __pyx_v_self->__pyx_base.feature_values, __pyx_v_end_negative, __pyx_v_start_positive, __pyx_v_self->sorted_samples, __pyx_v_is_samples_sorted); + goto __pyx_L3; } /*else*/ { - /* "numpy.pxd":232 - * info.shape[i] = PyArray_DIMS(self)[i] - * else: - * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL - */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - - /* "numpy.pxd":233 - * else: - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) + /* "sklearn/tree/_tree.pyx":1972 + * # index_to_samples is a mapping from X_indices to samples + * else: + * extract_nnz_index_to_samples(self.X_indices, self.X_data, # <<<<<<<<<<<<<< + * indptr_start, indptr_end, + * self.samples, self.start, self.end, */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + __pyx_f_7sklearn_4tree_5_tree_extract_nnz_index_to_samples(__pyx_v_self->X_indices, __pyx_v_self->X_data, __pyx_v_indptr_start, __pyx_v_indptr_end, __pyx_v_self->__pyx_base.samples, __pyx_v_self->__pyx_base.start, __pyx_v_self->__pyx_base.end, __pyx_v_self->index_to_samples, __pyx_v_self->__pyx_base.feature_values, __pyx_v_end_negative, __pyx_v_start_positive); } - __pyx_L7:; + __pyx_L3:; - /* "numpy.pxd":234 - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * info.itemsize = PyArray_ITEMSIZE(self) - * info.readonly = not PyArray_ISWRITEABLE(self) + /* "sklearn/tree/_tree.pyx":1917 + * return partition_end + * + * cdef inline void extract_nnz(self, SIZE_t feature, # <<<<<<<<<<<<<< + * SIZE_t* end_negative, SIZE_t* start_positive, + * bint* is_samples_sorted) nogil: */ - __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":235 - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< - * info.readonly = not PyArray_ISWRITEABLE(self) + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":1980 + * * + * cdef int compare_SIZE_t(const void* a, const void* b) nogil: # <<<<<<<<<<<<<< + * """Comparison function for sort""" + * return ((a)[0] - (b)[0]) */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":236 - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) - * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< +static int __pyx_f_7sklearn_4tree_5_tree_compare_SIZE_t(void const *__pyx_v_a, void const *__pyx_v_b) { + int __pyx_r; + + /* "sklearn/tree/_tree.pyx":1982 + * cdef int compare_SIZE_t(const void* a, const void* b) nogil: + * """Comparison function for sort""" + * return ((a)[0] - (b)[0]) # <<<<<<<<<<<<<< + * * - * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); + __pyx_r = ((int)((((__pyx_t_7sklearn_4tree_5_tree_SIZE_t *)__pyx_v_a)[0]) - (((__pyx_t_7sklearn_4tree_5_tree_SIZE_t *)__pyx_v_b)[0]))); + goto __pyx_L0; - /* "numpy.pxd":239 + /* "sklearn/tree/_tree.pyx":1980 * - * cdef int t - * cdef char* f = NULL # <<<<<<<<<<<<<< - * cdef dtype descr = self.descr - * cdef list stack + * + * cdef int compare_SIZE_t(const void* a, const void* b) nogil: # <<<<<<<<<<<<<< + * """Comparison function for sort""" + * return ((a)[0] - (b)[0]) */ - __pyx_v_f = NULL; - /* "numpy.pxd":240 - * cdef int t - * cdef char* f = NULL - * cdef dtype descr = self.descr # <<<<<<<<<<<<<< - * cdef list stack - * cdef int offset - */ - __Pyx_INCREF(((PyObject *)__pyx_v_self->descr)); - __pyx_v_descr = __pyx_v_self->descr; + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} - /* "numpy.pxd":244 - * cdef int offset +/* "sklearn/tree/_tree.pyx":1985 * - * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< * - * if not hasfields and not copy_shape: + * cdef inline void binary_search(INT32_t* sorted_array, # <<<<<<<<<<<<<< + * INT32_t start, INT32_t end, + * SIZE_t value, SIZE_t* index, */ - __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":246 - * cdef bint hasfields = PyDataType_HASFIELDS(descr) +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_binary_search(__pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_v_sorted_array, __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_v_end, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_value, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_index, __pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_v_new_start) { + __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_v_pivot; + int __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":1994 + * """ + * cdef INT32_t pivot + * index[0] = -1 # <<<<<<<<<<<<<< + * while start < end: + * pivot = start + (end - start) / 2 + */ + (__pyx_v_index[0]) = -1; + + /* "sklearn/tree/_tree.pyx":1995 + * cdef INT32_t pivot + * index[0] = -1 + * while start < end: # <<<<<<<<<<<<<< + * pivot = start + (end - start) / 2 * - * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< - * # do not call releasebuffer - * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); - if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); - __pyx_t_1 = __pyx_t_3; - } else { - __pyx_t_1 = __pyx_t_2; - } - if (__pyx_t_1) { + while (1) { + __pyx_t_1 = ((__pyx_v_start < __pyx_v_end) != 0); + if (!__pyx_t_1) break; - /* "numpy.pxd":248 - * if not hasfields and not copy_shape: - * # do not call releasebuffer - * info.obj = None # <<<<<<<<<<<<<< - * else: - * # need to call releasebuffer + /* "sklearn/tree/_tree.pyx":1996 + * index[0] = -1 + * while start < end: + * pivot = start + (end - start) / 2 # <<<<<<<<<<<<<< + * + * if sorted_array[pivot] == value: */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = Py_None; - goto __pyx_L10; - } - /*else*/ { + __pyx_v_pivot = (__pyx_v_start + ((__pyx_v_end - __pyx_v_start) / 2)); - /* "numpy.pxd":251 - * else: - * # need to call releasebuffer - * info.obj = self # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":1998 + * pivot = start + (end - start) / 2 * - * if not hasfields: + * if sorted_array[pivot] == value: # <<<<<<<<<<<<<< + * index[0] = pivot + * start = pivot + 1 */ - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - } - __pyx_L10:; + __pyx_t_1 = (((__pyx_v_sorted_array[__pyx_v_pivot]) == __pyx_v_value) != 0); + if (__pyx_t_1) { - /* "numpy.pxd":253 - * info.obj = self + /* "sklearn/tree/_tree.pyx":1999 * - * if not hasfields: # <<<<<<<<<<<<<< - * t = descr.type_num - * if ((descr.byteorder == c'>' and little_endian) or + * if sorted_array[pivot] == value: + * index[0] = pivot # <<<<<<<<<<<<<< + * start = pivot + 1 + * break */ - __pyx_t_1 = (!__pyx_v_hasfields); - if (__pyx_t_1) { + (__pyx_v_index[0]) = __pyx_v_pivot; - /* "numpy.pxd":254 + /* "sklearn/tree/_tree.pyx":2000 + * if sorted_array[pivot] == value: + * index[0] = pivot + * start = pivot + 1 # <<<<<<<<<<<<<< + * break * - * if not hasfields: - * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == c'>' and little_endian) or - * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_v_start = (__pyx_v_pivot + 1); - /* "numpy.pxd":255 - * if not hasfields: - * t = descr.type_num - * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") + /* "sklearn/tree/_tree.pyx":2001 + * index[0] = pivot + * start = pivot + 1 + * break # <<<<<<<<<<<<<< + * + * if sorted_array[pivot] < value: */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); - if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; - } else { - __pyx_t_2 = __pyx_t_1; + goto __pyx_L4_break; } - if (!__pyx_t_2) { - /* "numpy.pxd":256 - * t = descr.type_num - * if ((descr.byteorder == c'>' and little_endian) or - * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" + /* "sklearn/tree/_tree.pyx":2003 + * break + * + * if sorted_array[pivot] < value: # <<<<<<<<<<<<<< + * start = pivot + 1 + * else: */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); - if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); - __pyx_t_7 = __pyx_t_3; - } else { - __pyx_t_7 = __pyx_t_1; - } - __pyx_t_1 = __pyx_t_7; - } else { - __pyx_t_1 = __pyx_t_2; - } + __pyx_t_1 = (((__pyx_v_sorted_array[__pyx_v_pivot]) < __pyx_v_value) != 0); if (__pyx_t_1) { - /* "numpy.pxd":257 - * if ((descr.byteorder == c'>' and little_endian) or - * (descr.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" + /* "sklearn/tree/_tree.pyx":2004 + * + * if sorted_array[pivot] < value: + * start = pivot + 1 # <<<<<<<<<<<<<< + * else: + * end = pivot */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L12; + __pyx_v_start = (__pyx_v_pivot + 1); + goto __pyx_L6; } - __pyx_L12:; + /*else*/ { - /* "numpy.pxd":258 - * (descr.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" + /* "sklearn/tree/_tree.pyx":2006 + * start = pivot + 1 + * else: + * end = pivot # <<<<<<<<<<<<<< + * new_start[0] = start + * */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__b; - goto __pyx_L13; + __pyx_v_end = __pyx_v_pivot; } + __pyx_L6:; + } + __pyx_L4_break:; - /* "numpy.pxd":259 - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" + /* "sklearn/tree/_tree.pyx":2007 + * else: + * end = pivot + * new_start[0] = start # <<<<<<<<<<<<<< + * + * */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__B; - goto __pyx_L13; - } + (__pyx_v_new_start[0]) = __pyx_v_start; - /* "numpy.pxd":260 - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" + /* "sklearn/tree/_tree.pyx":1985 + * + * + * cdef inline void binary_search(INT32_t* sorted_array, # <<<<<<<<<<<<<< + * INT32_t start, INT32_t end, + * SIZE_t value, SIZE_t* index, */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__h; - goto __pyx_L13; - } - /* "numpy.pxd":261 - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" - */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__H; - goto __pyx_L13; - } + /* function exit code */ +} - /* "numpy.pxd":262 - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" +/* "sklearn/tree/_tree.pyx":2010 + * + * + * cdef inline void extract_nnz_index_to_samples(INT32_t* X_indices, # <<<<<<<<<<<<<< + * DTYPE_t* X_data, + * INT32_t indptr_start, */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__i; - goto __pyx_L13; - } - /* "numpy.pxd":263 - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" - */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__I; - goto __pyx_L13; - } +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_extract_nnz_index_to_samples(__pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_v_X_indices, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_data, __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_v_indptr_start, __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_v_indptr_end, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_index_to_samples, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_end_negative, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_start_positive) { + __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_index; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end_negative_; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start_positive_; + __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; - /* "numpy.pxd":264 - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" + /* "sklearn/tree/_tree.pyx":2027 + * cdef INT32_t k + * cdef SIZE_t index + * cdef SIZE_t end_negative_ = start # <<<<<<<<<<<<<< + * cdef SIZE_t start_positive_ = end + * */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__l; - goto __pyx_L13; - } + __pyx_v_end_negative_ = __pyx_v_start; - /* "numpy.pxd":265 - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" + /* "sklearn/tree/_tree.pyx":2028 + * cdef SIZE_t index + * cdef SIZE_t end_negative_ = start + * cdef SIZE_t start_positive_ = end # <<<<<<<<<<<<<< + * + * for k in range(indptr_start, indptr_end): */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__L; - goto __pyx_L13; - } + __pyx_v_start_positive_ = __pyx_v_end; - /* "numpy.pxd":266 - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" + /* "sklearn/tree/_tree.pyx":2030 + * cdef SIZE_t start_positive_ = end + * + * for k in range(indptr_start, indptr_end): # <<<<<<<<<<<<<< + * if start <= index_to_samples[X_indices[k]] < end: + * if X_data[k] > 0: */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__q; - goto __pyx_L13; - } + __pyx_t_1 = __pyx_v_indptr_end; + for (__pyx_t_2 = __pyx_v_indptr_start; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_k = __pyx_t_2; - /* "numpy.pxd":267 - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" + /* "sklearn/tree/_tree.pyx":2031 + * + * for k in range(indptr_start, indptr_end): + * if start <= index_to_samples[X_indices[k]] < end: # <<<<<<<<<<<<<< + * if X_data[k] > 0: + * start_positive_ -= 1 */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Q; - goto __pyx_L13; + __pyx_t_3 = (__pyx_v_start <= (__pyx_v_index_to_samples[(__pyx_v_X_indices[__pyx_v_k])])); + if (__pyx_t_3) { + __pyx_t_3 = ((__pyx_v_index_to_samples[(__pyx_v_X_indices[__pyx_v_k])]) < __pyx_v_end); } + __pyx_t_4 = (__pyx_t_3 != 0); + if (__pyx_t_4) { - /* "numpy.pxd":268 - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" + /* "sklearn/tree/_tree.pyx":2032 + * for k in range(indptr_start, indptr_end): + * if start <= index_to_samples[X_indices[k]] < end: + * if X_data[k] > 0: # <<<<<<<<<<<<<< + * start_positive_ -= 1 + * Xf[start_positive_] = X_data[k] */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__f; - goto __pyx_L13; - } + __pyx_t_4 = (((__pyx_v_X_data[__pyx_v_k]) > 0.0) != 0); + if (__pyx_t_4) { - /* "numpy.pxd":269 - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" + /* "sklearn/tree/_tree.pyx":2033 + * if start <= index_to_samples[X_indices[k]] < end: + * if X_data[k] > 0: + * start_positive_ -= 1 # <<<<<<<<<<<<<< + * Xf[start_positive_] = X_data[k] + * index = index_to_samples[X_indices[k]] */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__d; - goto __pyx_L13; - } + __pyx_v_start_positive_ = (__pyx_v_start_positive_ - 1); - /* "numpy.pxd":270 - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" + /* "sklearn/tree/_tree.pyx":2034 + * if X_data[k] > 0: + * start_positive_ -= 1 + * Xf[start_positive_] = X_data[k] # <<<<<<<<<<<<<< + * index = index_to_samples[X_indices[k]] + * sparse_swap(index_to_samples, samples, index, start_positive_) */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__g; - goto __pyx_L13; - } + (__pyx_v_Xf[__pyx_v_start_positive_]) = (__pyx_v_X_data[__pyx_v_k]); - /* "numpy.pxd":271 - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" + /* "sklearn/tree/_tree.pyx":2035 + * start_positive_ -= 1 + * Xf[start_positive_] = X_data[k] + * index = index_to_samples[X_indices[k]] # <<<<<<<<<<<<<< + * sparse_swap(index_to_samples, samples, index, start_positive_) + * */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zf; - goto __pyx_L13; - } + __pyx_v_index = (__pyx_v_index_to_samples[(__pyx_v_X_indices[__pyx_v_k])]); - /* "numpy.pxd":272 - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< - * elif t == NPY_CLONGDOUBLE: f = "Zg" - * elif t == NPY_OBJECT: f = "O" + /* "sklearn/tree/_tree.pyx":2036 + * Xf[start_positive_] = X_data[k] + * index = index_to_samples[X_indices[k]] + * sparse_swap(index_to_samples, samples, index, start_positive_) # <<<<<<<<<<<<<< + * + * */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zd; - goto __pyx_L13; - } + __pyx_f_7sklearn_4tree_5_tree_sparse_swap(__pyx_v_index_to_samples, __pyx_v_samples, __pyx_v_index, __pyx_v_start_positive_); + goto __pyx_L6; + } - /* "numpy.pxd":273 - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< - * elif t == NPY_OBJECT: f = "O" - * else: + /* "sklearn/tree/_tree.pyx":2039 + * + * + * elif X_data[k] < 0: # <<<<<<<<<<<<<< + * Xf[end_negative_] = X_data[k] + * index = index_to_samples[X_indices[k]] */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zg; - goto __pyx_L13; - } + __pyx_t_4 = (((__pyx_v_X_data[__pyx_v_k]) < 0.0) != 0); + if (__pyx_t_4) { - /* "numpy.pxd":274 - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" - * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + /* "sklearn/tree/_tree.pyx":2040 + * + * elif X_data[k] < 0: + * Xf[end_negative_] = X_data[k] # <<<<<<<<<<<<<< + * index = index_to_samples[X_indices[k]] + * sparse_swap(index_to_samples, samples, index, end_negative_) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L13; - } - /*else*/ { + (__pyx_v_Xf[__pyx_v_end_negative_]) = (__pyx_v_X_data[__pyx_v_k]); - /* "numpy.pxd":276 - * elif t == NPY_OBJECT: f = "O" - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< - * info.format = f - * return + /* "sklearn/tree/_tree.pyx":2041 + * elif X_data[k] < 0: + * Xf[end_negative_] = X_data[k] + * index = index_to_samples[X_indices[k]] # <<<<<<<<<<<<<< + * sparse_swap(index_to_samples, samples, index, end_negative_) + * end_negative_ += 1 */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_13), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); - __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L13:; + __pyx_v_index = (__pyx_v_index_to_samples[(__pyx_v_X_indices[__pyx_v_k])]); - /* "numpy.pxd":277 - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * info.format = f # <<<<<<<<<<<<<< - * return - * else: + /* "sklearn/tree/_tree.pyx":2042 + * Xf[end_negative_] = X_data[k] + * index = index_to_samples[X_indices[k]] + * sparse_swap(index_to_samples, samples, index, end_negative_) # <<<<<<<<<<<<<< + * end_negative_ += 1 + * */ - __pyx_v_info->format = __pyx_v_f; + __pyx_f_7sklearn_4tree_5_tree_sparse_swap(__pyx_v_index_to_samples, __pyx_v_samples, __pyx_v_index, __pyx_v_end_negative_); - /* "numpy.pxd":278 - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * info.format = f - * return # <<<<<<<<<<<<<< - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) + /* "sklearn/tree/_tree.pyx":2043 + * index = index_to_samples[X_indices[k]] + * sparse_swap(index_to_samples, samples, index, end_negative_) + * end_negative_ += 1 # <<<<<<<<<<<<<< + * + * # Returned values */ - __pyx_r = 0; - goto __pyx_L0; - goto __pyx_L11; + __pyx_v_end_negative_ = (__pyx_v_end_negative_ + 1); + goto __pyx_L6; + } + __pyx_L6:; + goto __pyx_L5; + } + __pyx_L5:; } - /*else*/ { - - /* "numpy.pxd":280 - * return - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = c'^' # Native data types, manual alignment - * offset = 0 - */ - __pyx_v_info->format = ((char *)malloc(255)); - - /* "numpy.pxd":281 - * else: - * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< - * offset = 0 - * f = _util_dtypestring(descr, info.format + 1, - */ - (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":282 - * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = c'^' # Native data types, manual alignment - * offset = 0 # <<<<<<<<<<<<<< - * f = _util_dtypestring(descr, info.format + 1, - * info.format + _buffer_format_string_len, + /* "sklearn/tree/_tree.pyx":2046 + * + * # Returned values + * end_negative[0] = end_negative_ # <<<<<<<<<<<<<< + * start_positive[0] = start_positive_ + * */ - __pyx_v_offset = 0; + (__pyx_v_end_negative[0]) = __pyx_v_end_negative_; - /* "numpy.pxd":285 - * f = _util_dtypestring(descr, info.format + 1, - * info.format + _buffer_format_string_len, - * &offset) # <<<<<<<<<<<<<< - * f[0] = c'\0' # Terminate format string + /* "sklearn/tree/_tree.pyx":2047 + * # Returned values + * end_negative[0] = end_negative_ + * start_positive[0] = start_positive_ # <<<<<<<<<<<<<< + * * */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_9; + (__pyx_v_start_positive[0]) = __pyx_v_start_positive_; - /* "numpy.pxd":286 - * info.format + _buffer_format_string_len, - * &offset) - * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2010 * - * def __releasebuffer__(ndarray self, Py_buffer* info): + * + * cdef inline void extract_nnz_index_to_samples(INT32_t* X_indices, # <<<<<<<<<<<<<< + * DTYPE_t* X_data, + * INT32_t indptr_start, */ - (__pyx_v_f[0]) = '\x00'; - } - __pyx_L11:; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; - } - goto __pyx_L2; - __pyx_L0:; - if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { - __Pyx_GOTREF(Py_None); - __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; - } - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_descr); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -/* Python wrapper */ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); - __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); - __Pyx_RefNannyFinishContext(); + /* function exit code */ } -/* "numpy.pxd":288 - * f[0] = c'\0' # Terminate format string +/* "sklearn/tree/_tree.pyx":2050 * - * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) + * + * cdef inline void extract_nnz_binary_search(INT32_t* X_indices, # <<<<<<<<<<<<<< + * DTYPE_t* X_data, + * INT32_t indptr_start, */ -static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { - __Pyx_RefNannyDeclarations +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_extract_nnz_binary_search(__pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_v_X_indices, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_data, __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_v_indptr_start, __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_v_indptr_end, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_index_to_samples, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_end_negative, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_start_positive, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_sorted_samples, int *__pyx_v_is_samples_sorted) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_index; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end_negative_; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start_positive_; int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__", 0); + int __pyx_t_2; - /* "numpy.pxd":289 + /* "sklearn/tree/_tree.pyx":2073 + * cdef SIZE_t n_samples * - * def __releasebuffer__(ndarray self, Py_buffer* info): - * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< - * stdlib.free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * if not is_samples_sorted[0]: # <<<<<<<<<<<<<< + * n_samples = end - start + * memcpy(sorted_samples + start, samples + start, */ - __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); + __pyx_t_1 = ((!((__pyx_v_is_samples_sorted[0]) != 0)) != 0); if (__pyx_t_1) { - /* "numpy.pxd":290 - * def __releasebuffer__(ndarray self, Py_buffer* info): - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) # <<<<<<<<<<<<<< - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * stdlib.free(info.strides) + /* "sklearn/tree/_tree.pyx":2074 + * + * if not is_samples_sorted[0]: + * n_samples = end - start # <<<<<<<<<<<<<< + * memcpy(sorted_samples + start, samples + start, + * n_samples * sizeof(SIZE_t)) */ - free(__pyx_v_info->format); + __pyx_v_n_samples = (__pyx_v_end - __pyx_v_start); + + /* "sklearn/tree/_tree.pyx":2075 + * if not is_samples_sorted[0]: + * n_samples = end - start + * memcpy(sorted_samples + start, samples + start, # <<<<<<<<<<<<<< + * n_samples * sizeof(SIZE_t)) + * qsort(sorted_samples + start, n_samples, sizeof(SIZE_t), + */ + memcpy((__pyx_v_sorted_samples + __pyx_v_start), (__pyx_v_samples + __pyx_v_start), (__pyx_v_n_samples * (sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)))); + + /* "sklearn/tree/_tree.pyx":2077 + * memcpy(sorted_samples + start, samples + start, + * n_samples * sizeof(SIZE_t)) + * qsort(sorted_samples + start, n_samples, sizeof(SIZE_t), # <<<<<<<<<<<<<< + * compare_SIZE_t) + * is_samples_sorted[0] = 1 + */ + qsort((__pyx_v_sorted_samples + __pyx_v_start), __pyx_v_n_samples, (sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)), __pyx_f_7sklearn_4tree_5_tree_compare_SIZE_t); + + /* "sklearn/tree/_tree.pyx":2079 + * qsort(sorted_samples + start, n_samples, sizeof(SIZE_t), + * compare_SIZE_t) + * is_samples_sorted[0] = 1 # <<<<<<<<<<<<<< + * + * while (indptr_start < indptr_end and + */ + (__pyx_v_is_samples_sorted[0]) = 1; goto __pyx_L3; } __pyx_L3:; - /* "numpy.pxd":291 - * if PyArray_HASFIELDS(self): - * stdlib.free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * stdlib.free(info.strides) - * # info.shape was stored after info.strides in the same block + /* "sklearn/tree/_tree.pyx":2081 + * is_samples_sorted[0] = 1 + * + * while (indptr_start < indptr_end and # <<<<<<<<<<<<<< + * sorted_samples[start] > X_indices[indptr_start]): + * indptr_start += 1 */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); - if (__pyx_t_1) { + while (1) { + __pyx_t_2 = ((__pyx_v_indptr_start < __pyx_v_indptr_end) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L6_bool_binop_done; + } - /* "numpy.pxd":292 - * stdlib.free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * stdlib.free(info.strides) # <<<<<<<<<<<<<< - * # info.shape was stored after info.strides in the same block + /* "sklearn/tree/_tree.pyx":2082 + * + * while (indptr_start < indptr_end and + * sorted_samples[start] > X_indices[indptr_start]): # <<<<<<<<<<<<<< + * indptr_start += 1 * */ - free(__pyx_v_info->strides); - goto __pyx_L4; + __pyx_t_2 = (((__pyx_v_sorted_samples[__pyx_v_start]) > (__pyx_v_X_indices[__pyx_v_indptr_start])) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L6_bool_binop_done:; + if (!__pyx_t_1) break; + + /* "sklearn/tree/_tree.pyx":2083 + * while (indptr_start < indptr_end and + * sorted_samples[start] > X_indices[indptr_start]): + * indptr_start += 1 # <<<<<<<<<<<<<< + * + * while (indptr_start < indptr_end and + */ + __pyx_v_indptr_start = (__pyx_v_indptr_start + 1); } - __pyx_L4:; - __Pyx_RefNannyFinishContext(); -} + /* "sklearn/tree/_tree.pyx":2085 + * indptr_start += 1 + * + * while (indptr_start < indptr_end and # <<<<<<<<<<<<<< + * sorted_samples[end - 1] < X_indices[indptr_end - 1]): + * indptr_end -= 1 + */ + while (1) { + __pyx_t_2 = ((__pyx_v_indptr_start < __pyx_v_indptr_end) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L10_bool_binop_done; + } -/* "numpy.pxd":768 - * ctypedef npy_cdouble complex_t + /* "sklearn/tree/_tree.pyx":2086 * - * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(1, a) + * while (indptr_start < indptr_end and + * sorted_samples[end - 1] < X_indices[indptr_end - 1]): # <<<<<<<<<<<<<< + * indptr_end -= 1 * */ + __pyx_t_2 = (((__pyx_v_sorted_samples[(__pyx_v_end - 1)]) < (__pyx_v_X_indices[(__pyx_v_indptr_end - 1)])) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L10_bool_binop_done:; + if (!__pyx_t_1) break; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + /* "sklearn/tree/_tree.pyx":2087 + * while (indptr_start < indptr_end and + * sorted_samples[end - 1] < X_indices[indptr_end - 1]): + * indptr_end -= 1 # <<<<<<<<<<<<<< + * + * cdef SIZE_t p = start + */ + __pyx_v_indptr_end = (__pyx_v_indptr_end - 1); + } - /* "numpy.pxd":769 + /* "sklearn/tree/_tree.pyx":2089 + * indptr_end -= 1 * - * cdef inline object PyArray_MultiIterNew1(a): - * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * cdef SIZE_t p = start # <<<<<<<<<<<<<< + * cdef SIZE_t index + * cdef SIZE_t k + */ + __pyx_v_p = __pyx_v_start; + + /* "sklearn/tree/_tree.pyx":2092 + * cdef SIZE_t index + * cdef SIZE_t k + * cdef SIZE_t end_negative_ = start # <<<<<<<<<<<<<< + * cdef SIZE_t start_positive_ = end * - * cdef inline object PyArray_MultiIterNew2(a, b): */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_v_end_negative_ = __pyx_v_start; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":2093 + * cdef SIZE_t k + * cdef SIZE_t end_negative_ = start + * cdef SIZE_t start_positive_ = end # <<<<<<<<<<<<<< + * + * while (p < end and indptr_start < indptr_end): + */ + __pyx_v_start_positive_ = __pyx_v_end; -/* "numpy.pxd":771 - * return PyArray_MultiIterNew(1, a) + /* "sklearn/tree/_tree.pyx":2095 + * cdef SIZE_t start_positive_ = end * - * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(2, a, b) + * while (p < end and indptr_start < indptr_end): # <<<<<<<<<<<<<< + * # Find index of sorted_samples[p] in X_indices + * binary_search(X_indices, indptr_start, indptr_end, + */ + while (1) { + __pyx_t_2 = ((__pyx_v_p < __pyx_v_end) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L14_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_indptr_start < __pyx_v_indptr_end) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L14_bool_binop_done:; + if (!__pyx_t_1) break; + + /* "sklearn/tree/_tree.pyx":2097 + * while (p < end and indptr_start < indptr_end): + * # Find index of sorted_samples[p] in X_indices + * binary_search(X_indices, indptr_start, indptr_end, # <<<<<<<<<<<<<< + * sorted_samples[p], &k, &indptr_start) * */ + __pyx_f_7sklearn_4tree_5_tree_binary_search(__pyx_v_X_indices, __pyx_v_indptr_start, __pyx_v_indptr_end, (__pyx_v_sorted_samples[__pyx_v_p]), (&__pyx_v_k), (&__pyx_v_indptr_start)); -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + /* "sklearn/tree/_tree.pyx":2100 + * sorted_samples[p], &k, &indptr_start) + * + * if k != -1: # <<<<<<<<<<<<<< + * # If k != -1, we have found a non zero value + * + */ + __pyx_t_1 = ((__pyx_v_k != -1) != 0); + if (__pyx_t_1) { - /* "numpy.pxd":772 + /* "sklearn/tree/_tree.pyx":2103 + * # If k != -1, we have found a non zero value * - * cdef inline object PyArray_MultiIterNew2(a, b): - * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * if X_data[k] > 0: # <<<<<<<<<<<<<< + * start_positive_ -= 1 + * Xf[start_positive_] = X_data[k] + */ + __pyx_t_1 = (((__pyx_v_X_data[__pyx_v_k]) > 0.0) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":2104 * - * cdef inline object PyArray_MultiIterNew3(a, b, c): + * if X_data[k] > 0: + * start_positive_ -= 1 # <<<<<<<<<<<<<< + * Xf[start_positive_] = X_data[k] + * index = index_to_samples[X_indices[k]] */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_v_start_positive_ = (__pyx_v_start_positive_ - 1); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":2105 + * if X_data[k] > 0: + * start_positive_ -= 1 + * Xf[start_positive_] = X_data[k] # <<<<<<<<<<<<<< + * index = index_to_samples[X_indices[k]] + * sparse_swap(index_to_samples, samples, index, start_positive_) + */ + (__pyx_v_Xf[__pyx_v_start_positive_]) = (__pyx_v_X_data[__pyx_v_k]); -/* "numpy.pxd":774 - * return PyArray_MultiIterNew(2, a, b) + /* "sklearn/tree/_tree.pyx":2106 + * start_positive_ -= 1 + * Xf[start_positive_] = X_data[k] + * index = index_to_samples[X_indices[k]] # <<<<<<<<<<<<<< + * sparse_swap(index_to_samples, samples, index, start_positive_) + * + */ + __pyx_v_index = (__pyx_v_index_to_samples[(__pyx_v_X_indices[__pyx_v_k])]); + + /* "sklearn/tree/_tree.pyx":2107 + * Xf[start_positive_] = X_data[k] + * index = index_to_samples[X_indices[k]] + * sparse_swap(index_to_samples, samples, index, start_positive_) # <<<<<<<<<<<<<< * - * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(3, a, b, c) * */ + __pyx_f_7sklearn_4tree_5_tree_sparse_swap(__pyx_v_index_to_samples, __pyx_v_samples, __pyx_v_index, __pyx_v_start_positive_); + goto __pyx_L17; + } -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + /* "sklearn/tree/_tree.pyx":2110 + * + * + * elif X_data[k] < 0: # <<<<<<<<<<<<<< + * Xf[end_negative_] = X_data[k] + * index = index_to_samples[X_indices[k]] + */ + __pyx_t_1 = (((__pyx_v_X_data[__pyx_v_k]) < 0.0) != 0); + if (__pyx_t_1) { - /* "numpy.pxd":775 + /* "sklearn/tree/_tree.pyx":2111 * - * cdef inline object PyArray_MultiIterNew3(a, b, c): - * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * elif X_data[k] < 0: + * Xf[end_negative_] = X_data[k] # <<<<<<<<<<<<<< + * index = index_to_samples[X_indices[k]] + * sparse_swap(index_to_samples, samples, index, end_negative_) + */ + (__pyx_v_Xf[__pyx_v_end_negative_]) = (__pyx_v_X_data[__pyx_v_k]); + + /* "sklearn/tree/_tree.pyx":2112 + * elif X_data[k] < 0: + * Xf[end_negative_] = X_data[k] + * index = index_to_samples[X_indices[k]] # <<<<<<<<<<<<<< + * sparse_swap(index_to_samples, samples, index, end_negative_) + * end_negative_ += 1 + */ + __pyx_v_index = (__pyx_v_index_to_samples[(__pyx_v_X_indices[__pyx_v_k])]); + + /* "sklearn/tree/_tree.pyx":2113 + * Xf[end_negative_] = X_data[k] + * index = index_to_samples[X_indices[k]] + * sparse_swap(index_to_samples, samples, index, end_negative_) # <<<<<<<<<<<<<< + * end_negative_ += 1 + * p += 1 + */ + __pyx_f_7sklearn_4tree_5_tree_sparse_swap(__pyx_v_index_to_samples, __pyx_v_samples, __pyx_v_index, __pyx_v_end_negative_); + + /* "sklearn/tree/_tree.pyx":2114 + * index = index_to_samples[X_indices[k]] + * sparse_swap(index_to_samples, samples, index, end_negative_) + * end_negative_ += 1 # <<<<<<<<<<<<<< + * p += 1 * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + __pyx_v_end_negative_ = (__pyx_v_end_negative_ + 1); + goto __pyx_L17; + } + __pyx_L17:; + goto __pyx_L16; + } + __pyx_L16:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":2115 + * sparse_swap(index_to_samples, samples, index, end_negative_) + * end_negative_ += 1 + * p += 1 # <<<<<<<<<<<<<< + * + * # Returned values + */ + __pyx_v_p = (__pyx_v_p + 1); + } -/* "numpy.pxd":777 - * return PyArray_MultiIterNew(3, a, b, c) + /* "sklearn/tree/_tree.pyx":2118 * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(4, a, b, c, d) + * # Returned values + * end_negative[0] = end_negative_ # <<<<<<<<<<<<<< + * start_positive[0] = start_positive_ * */ + (__pyx_v_end_negative[0]) = __pyx_v_end_negative_; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + /* "sklearn/tree/_tree.pyx":2119 + * # Returned values + * end_negative[0] = end_negative_ + * start_positive[0] = start_positive_ # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_start_positive[0]) = __pyx_v_start_positive_; - /* "numpy.pxd":778 + /* "sklearn/tree/_tree.pyx":2050 * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): - * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * cdef inline void extract_nnz_binary_search(INT32_t* X_indices, # <<<<<<<<<<<<<< + * DTYPE_t* X_data, + * INT32_t indptr_start, */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; + /* function exit code */ } -/* "numpy.pxd":780 - * return PyArray_MultiIterNew(4, a, b, c, d) +/* "sklearn/tree/_tree.pyx":2122 * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(5, a, b, c, d, e) * + * cdef inline void sparse_swap(SIZE_t* index_to_samples, SIZE_t* samples, # <<<<<<<<<<<<<< + * SIZE_t pos_1, SIZE_t pos_2) nogil : + * """Swap sample pos_1 and pos_2 preserving sparse invariant""" */ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); +static CYTHON_INLINE void __pyx_f_7sklearn_4tree_5_tree_sparse_swap(__pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_index_to_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_pos_1, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_pos_2) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; - /* "numpy.pxd":781 - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): - * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2125 + * SIZE_t pos_1, SIZE_t pos_2) 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 + * index_to_samples[samples[pos_2]] = pos_2 + */ + __pyx_t_1 = (__pyx_v_samples[__pyx_v_pos_2]); + __pyx_t_2 = (__pyx_v_samples[__pyx_v_pos_1]); + (__pyx_v_samples[__pyx_v_pos_1]) = __pyx_t_1; + (__pyx_v_samples[__pyx_v_pos_2]) = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":2126 + * """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 # <<<<<<<<<<<<<< + * index_to_samples[samples[pos_2]] = pos_2 * - * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; + (__pyx_v_index_to_samples[(__pyx_v_samples[__pyx_v_pos_1])]) = __pyx_v_pos_1; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":2127 + * samples[pos_1], samples[pos_2] = samples[pos_2], samples[pos_1] + * index_to_samples[samples[pos_1]] = pos_1 + * index_to_samples[samples[pos_2]] = pos_2 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_index_to_samples[(__pyx_v_samples[__pyx_v_pos_2])]) = __pyx_v_pos_2; -/* "numpy.pxd":783 - * return PyArray_MultiIterNew(5, a, b, c, d, e) + /* "sklearn/tree/_tree.pyx":2122 * - * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< - * # Recursive utility function used in __getbuffer__ to get format - * # string. The new location in the format string is returned. + * + * cdef inline void sparse_swap(SIZE_t* index_to_samples, SIZE_t* samples, # <<<<<<<<<<<<<< + * SIZE_t pos_1, SIZE_t pos_2) nogil : + * """Swap sample pos_1 and pos_2 preserving sparse invariant""" */ -static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { - PyArray_Descr *__pyx_v_child = 0; - int __pyx_v_endian_detector; - int __pyx_v_little_endian; - PyObject *__pyx_v_fields = 0; - PyObject *__pyx_v_childname = NULL; - PyObject *__pyx_v_new_offset = NULL; - PyObject *__pyx_v_t = NULL; - char *__pyx_r; + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":2133 + * """Splitter for finding the best split, using the sparse data.""" + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (BestSparseSplitter, (self.criterion, + * self.max_features, + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_18BestSparseSplitter_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_18BestSparseSplitter_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_18BestSparseSplitter___reduce__(((struct __pyx_obj_7sklearn_4tree_5_tree_BestSparseSplitter *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_18BestSparseSplitter___reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_BestSparseSplitter *__pyx_v_self) { + PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *(*__pyx_t_6)(PyObject *); - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; - long __pyx_t_11; - char *__pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring", 0); + __Pyx_RefNannySetupContext("__reduce__", 0); - /* "numpy.pxd":790 - * cdef int delta_offset - * cdef tuple i - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * cdef tuple fields + /* "sklearn/tree/_tree.pyx":2134 + * + * def __reduce__(self): + * return (BestSparseSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, */ - __pyx_v_endian_detector = 1; + __Pyx_XDECREF(__pyx_r); - /* "numpy.pxd":791 - * cdef tuple i - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< - * cdef tuple fields + /* "sklearn/tree/_tree.pyx":2135 + * def __reduce__(self): + * return (BestSparseSplitter, (self.criterion, + * self.max_features, # <<<<<<<<<<<<<< + * self.min_samples_leaf, + * self.min_weight_leaf, + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.__pyx_base.max_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "sklearn/tree/_tree.pyx":2136 + * return (BestSparseSplitter, (self.criterion, + * self.max_features, + * self.min_samples_leaf, # <<<<<<<<<<<<<< + * self.min_weight_leaf, + * self.random_state), self.__getstate__()) + */ + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.__pyx_base.min_samples_leaf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + + /* "sklearn/tree/_tree.pyx":2137 + * self.max_features, + * self.min_samples_leaf, + * self.min_weight_leaf, # <<<<<<<<<<<<<< + * self.random_state), self.__getstate__()) * */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_self->__pyx_base.__pyx_base.min_weight_leaf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2137; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); - /* "numpy.pxd":794 - * cdef tuple fields + /* "sklearn/tree/_tree.pyx":2134 * - * for childname in descr.names: # <<<<<<<<<<<<<< - * fields = descr.fields[childname] - * child, new_offset = fields + * def __reduce__(self): + * return (BestSparseSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, */ - if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyTuple_New(5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_self->__pyx_base.__pyx_base.random_state); + PyTuple_SET_ITEM(__pyx_t_4, 4, __pyx_v_self->__pyx_base.__pyx_base.random_state); + __Pyx_GIVEREF(__pyx_v_self->__pyx_base.__pyx_base.random_state); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + + /* "sklearn/tree/_tree.pyx":2138 + * self.min_samples_leaf, + * self.min_weight_leaf, + * self.random_state), self.__getstate__()) # <<<<<<<<<<<<<< + * + * cdef void node_split(self, double impurity, SplitRecord* split, + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_getstate); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } } - __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; - __pyx_t_3 = 0; + if (__pyx_t_1) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "numpy.pxd":795 + /* "sklearn/tree/_tree.pyx":2134 * - * for childname in descr.names: - * fields = descr.fields[childname] # <<<<<<<<<<<<<< - * child, new_offset = fields + * def __reduce__(self): + * return (BestSparseSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, + */ + __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_BestSparseSplitter))); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_BestSparseSplitter))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_BestSparseSplitter))); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":2133 + * """Splitter for finding the best split, using the sparse data.""" * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (BestSparseSplitter, (self.criterion, + * self.max_features, */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - /* "numpy.pxd":796 - * for childname in descr.names: - * fields = descr.fields[childname] - * child, new_offset = fields # <<<<<<<<<<<<<< + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.BestSparseSplitter.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":2140 + * self.random_state), self.__getstate__()) + * + * cdef void node_split(self, double impurity, SplitRecord* split, # <<<<<<<<<<<<<< + * SIZE_t* n_constant_features) nogil: + * """Find the best split on node samples[start:end], using sparse + */ + +static void __pyx_f_7sklearn_4tree_5_tree_18BestSparseSplitter_node_split(struct __pyx_obj_7sklearn_4tree_5_tree_BestSparseSplitter *__pyx_v_self, double __pyx_v_impurity, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_v_X_indices; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_v_X_indptr; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_data; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_constant_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_features; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_sorted_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_index_to_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + double __pyx_v_min_weight_leaf; + __pyx_t_7sklearn_4tree_5_tree_UINT32_t *__pyx_v_random_state; + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_best; + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_current; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_f_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_f_j; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_tmp; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_visited_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_found_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_drawn_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_known_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_total_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p_next; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p_prev; + int __pyx_v_is_samples_sorted; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start_positive; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end_negative; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_t_4; + double __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_8; + + /* "sklearn/tree/_tree.pyx":2146 + * """ + * # Find the best split + * cdef SIZE_t* samples = self.samples # <<<<<<<<<<<<<< + * cdef SIZE_t start = self.start + * cdef SIZE_t end = self.end + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.samples; + __pyx_v_samples = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":2147 + * # Find the best split + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t start = self.start # <<<<<<<<<<<<<< + * cdef SIZE_t end = self.end * - * if (end - f) - (new_offset - offset[0]) < 15: */ - if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { - PyObject* sequence = ((PyObject *)__pyx_v_fields); - #if CYTHON_COMPILING_IN_CPYTHON - Py_ssize_t size = Py_SIZE(sequence); - #else - Py_ssize_t size = PySequence_Size(sequence); - #endif - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - } else if (1) { - __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else - { - Py_ssize_t index = -1; - __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; - index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = NULL; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_L6_unpacking_done:; - } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); - __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; - __pyx_t_4 = 0; + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.start; + __pyx_v_start = __pyx_t_2; - /* "numpy.pxd":798 - * child, new_offset = fields + /* "sklearn/tree/_tree.pyx":2148 + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t start = self.start + * cdef SIZE_t end = self.end # <<<<<<<<<<<<<< * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * cdef INT32_t* X_indices = self.X_indices + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.end; + __pyx_v_end = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":2150 + * cdef SIZE_t end = self.end * + * cdef INT32_t* X_indices = self.X_indices # <<<<<<<<<<<<<< + * cdef INT32_t* X_indptr = self.X_indptr + * cdef DTYPE_t* X_data = self.X_data */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_7) { + __pyx_t_3 = __pyx_v_self->__pyx_base.X_indices; + __pyx_v_X_indices = __pyx_t_3; - /* "numpy.pxd":799 + /* "sklearn/tree/_tree.pyx":2151 * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * cdef INT32_t* X_indices = self.X_indices + * cdef INT32_t* X_indptr = self.X_indptr # <<<<<<<<<<<<<< + * cdef DTYPE_t* X_data = self.X_data * - * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; + __pyx_t_3 = __pyx_v_self->__pyx_base.X_indptr; + __pyx_v_X_indptr = __pyx_t_3; - /* "numpy.pxd":801 - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + /* "sklearn/tree/_tree.pyx":2152 + * cdef INT32_t* X_indices = self.X_indices + * cdef INT32_t* X_indptr = self.X_indptr + * cdef DTYPE_t* X_data = self.X_data # <<<<<<<<<<<<<< * - * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") + * cdef SIZE_t* features = self.features */ - __pyx_t_7 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_7) { - __pyx_t_8 = __pyx_v_little_endian; - } else { - __pyx_t_8 = __pyx_t_7; - } - if (!__pyx_t_8) { + __pyx_t_4 = __pyx_v_self->__pyx_base.X_data; + __pyx_v_X_data = __pyx_t_4; - /* "numpy.pxd":802 + /* "sklearn/tree/_tree.pyx":2154 + * cdef DTYPE_t* X_data = self.X_data * - * if ((child.byteorder == c'>' and little_endian) or - * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< - * raise ValueError(u"Non-native byte order not supported") - * # One could encode it in the format string and have Cython + * cdef SIZE_t* features = self.features # <<<<<<<<<<<<<< + * cdef SIZE_t* constant_features = self.constant_features + * cdef SIZE_t n_features = self.n_features */ - __pyx_t_7 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_7) { - __pyx_t_9 = (!__pyx_v_little_endian); - __pyx_t_10 = __pyx_t_9; - } else { - __pyx_t_10 = __pyx_t_7; - } - __pyx_t_7 = __pyx_t_10; - } else { - __pyx_t_7 = __pyx_t_8; - } - if (__pyx_t_7) { + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.features; + __pyx_v_features = __pyx_t_1; - /* "numpy.pxd":803 - * if ((child.byteorder == c'>' and little_endian) or - * (child.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * # One could encode it in the format string and have Cython - * # complain instead, BUT: < and > in format strings also imply + /* "sklearn/tree/_tree.pyx":2155 + * + * cdef SIZE_t* features = self.features + * cdef SIZE_t* constant_features = self.constant_features # <<<<<<<<<<<<<< + * cdef SIZE_t n_features = self.n_features + * */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; - } - __pyx_L8:; + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.constant_features; + __pyx_v_constant_features = __pyx_t_1; - /* "numpy.pxd":813 + /* "sklearn/tree/_tree.pyx":2156 + * cdef SIZE_t* features = self.features + * cdef SIZE_t* constant_features = self.constant_features + * cdef SIZE_t n_features = self.n_features # <<<<<<<<<<<<<< * - * # Output padding bytes - * while offset[0] < new_offset: # <<<<<<<<<<<<<< - * f[0] = 120 # "x"; pad byte - * f += 1 + * cdef DTYPE_t* Xf = self.feature_values */ - while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!__pyx_t_7) break; + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.n_features; + __pyx_v_n_features = __pyx_t_2; - /* "numpy.pxd":814 - * # Output padding bytes - * while offset[0] < new_offset: - * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< - * f += 1 - * offset[0] += 1 + /* "sklearn/tree/_tree.pyx":2158 + * cdef SIZE_t n_features = self.n_features + * + * cdef DTYPE_t* Xf = self.feature_values # <<<<<<<<<<<<<< + * cdef SIZE_t* sorted_samples = self.sorted_samples + * cdef SIZE_t* index_to_samples = self.index_to_samples */ - (__pyx_v_f[0]) = 120; + __pyx_t_4 = __pyx_v_self->__pyx_base.__pyx_base.feature_values; + __pyx_v_Xf = __pyx_t_4; - /* "numpy.pxd":815 - * while offset[0] < new_offset: - * f[0] = 120 # "x"; pad byte - * f += 1 # <<<<<<<<<<<<<< - * offset[0] += 1 + /* "sklearn/tree/_tree.pyx":2159 * + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t* sorted_samples = self.sorted_samples # <<<<<<<<<<<<<< + * cdef SIZE_t* index_to_samples = self.index_to_samples + * cdef SIZE_t max_features = self.max_features */ - __pyx_v_f = (__pyx_v_f + 1); + __pyx_t_1 = __pyx_v_self->__pyx_base.sorted_samples; + __pyx_v_sorted_samples = __pyx_t_1; - /* "numpy.pxd":816 - * f[0] = 120 # "x"; pad byte - * f += 1 - * offset[0] += 1 # <<<<<<<<<<<<<< - * - * offset[0] += child.itemsize + /* "sklearn/tree/_tree.pyx":2160 + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t* sorted_samples = self.sorted_samples + * cdef SIZE_t* index_to_samples = self.index_to_samples # <<<<<<<<<<<<<< + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf */ - __pyx_t_11 = 0; - (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); - } + __pyx_t_1 = __pyx_v_self->__pyx_base.index_to_samples; + __pyx_v_index_to_samples = __pyx_t_1; - /* "numpy.pxd":818 - * offset[0] += 1 - * - * offset[0] += child.itemsize # <<<<<<<<<<<<<< - * - * if not PyDataType_HASFIELDS(child): + /* "sklearn/tree/_tree.pyx":2161 + * cdef SIZE_t* sorted_samples = self.sorted_samples + * cdef SIZE_t* index_to_samples = self.index_to_samples + * cdef SIZE_t max_features = self.max_features # <<<<<<<<<<<<<< + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf */ - __pyx_t_11 = 0; - (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.max_features; + __pyx_v_max_features = __pyx_t_2; - /* "numpy.pxd":820 - * offset[0] += child.itemsize - * - * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< - * t = child.type_num - * if end - f < 5: + /* "sklearn/tree/_tree.pyx":2162 + * cdef SIZE_t* index_to_samples = self.index_to_samples + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf # <<<<<<<<<<<<<< + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef UINT32_t* random_state = &self.rand_r_state */ - __pyx_t_7 = (!PyDataType_HASFIELDS(__pyx_v_child)); - if (__pyx_t_7) { + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.min_samples_leaf; + __pyx_v_min_samples_leaf = __pyx_t_2; - /* "numpy.pxd":821 + /* "sklearn/tree/_tree.pyx":2163 + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf # <<<<<<<<<<<<<< + * cdef UINT32_t* random_state = &self.rand_r_state * - * if not PyDataType_HASFIELDS(child): - * t = child.type_num # <<<<<<<<<<<<<< - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_5 = __pyx_v_self->__pyx_base.__pyx_base.min_weight_leaf; + __pyx_v_min_weight_leaf = __pyx_t_5; - /* "numpy.pxd":822 - * if not PyDataType_HASFIELDS(child): - * t = child.type_num - * if end - f < 5: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short.") + /* "sklearn/tree/_tree.pyx":2164 + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef UINT32_t* random_state = &self.rand_r_state # <<<<<<<<<<<<<< * + * cdef SplitRecord best, current */ - __pyx_t_7 = ((__pyx_v_end - __pyx_v_f) < 5); - if (__pyx_t_7) { + __pyx_v_random_state = (&__pyx_v_self->__pyx_base.__pyx_base.rand_r_state); - /* "numpy.pxd":823 - * t = child.type_num - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2167 * - * # Until ticket #99 is fixed, use integers to avoid warnings + * cdef SplitRecord best, current + * _init_split(&best, end) # <<<<<<<<<<<<<< + * + * cdef SIZE_t f_i = n_features */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_18), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L12; - } - __pyx_L12:; + __pyx_f_7sklearn_4tree_5_tree__init_split((&__pyx_v_best), __pyx_v_end); - /* "numpy.pxd":826 + /* "sklearn/tree/_tree.pyx":2169 + * _init_split(&best, end) * - * # Until ticket #99 is fixed, use integers to avoid warnings - * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" + * cdef SIZE_t f_i = n_features # <<<<<<<<<<<<<< + * cdef SIZE_t f_j, p, tmp + * cdef SIZE_t n_visited_features = 0 */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 98; - goto __pyx_L13; - } + __pyx_v_f_i = __pyx_v_n_features; - /* "numpy.pxd":827 - * # Until ticket #99 is fixed, use integers to avoid warnings - * if t == NPY_BYTE: f[0] = 98 #"b" - * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" + /* "sklearn/tree/_tree.pyx":2171 + * cdef SIZE_t f_i = n_features + * cdef SIZE_t f_j, p, tmp + * cdef SIZE_t n_visited_features = 0 # <<<<<<<<<<<<<< + * # Number of features discovered to be constant during the split search + * cdef SIZE_t n_found_constants = 0 */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 66; - goto __pyx_L13; - } + __pyx_v_n_visited_features = 0; - /* "numpy.pxd":828 - * if t == NPY_BYTE: f[0] = 98 #"b" - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" + /* "sklearn/tree/_tree.pyx":2173 + * cdef SIZE_t n_visited_features = 0 + * # Number of features discovered to be constant during the split search + * cdef SIZE_t n_found_constants = 0 # <<<<<<<<<<<<<< + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 104; - goto __pyx_L13; - } + __pyx_v_n_found_constants = 0; - /* "numpy.pxd":829 - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" + /* "sklearn/tree/_tree.pyx":2175 + * cdef SIZE_t n_found_constants = 0 + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t n_known_constants = n_constant_features[0] + * # n_total_constants = n_known_constants + n_found_constants */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 72; - goto __pyx_L13; - } + __pyx_v_n_drawn_constants = 0; - /* "numpy.pxd":830 - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" + /* "sklearn/tree/_tree.pyx":2176 + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 + * cdef SIZE_t n_known_constants = n_constant_features[0] # <<<<<<<<<<<<<< + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 105; - goto __pyx_L13; - } + __pyx_v_n_known_constants = (__pyx_v_n_constant_features[0]); - /* "numpy.pxd":831 - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" + /* "sklearn/tree/_tree.pyx":2178 + * cdef SIZE_t n_known_constants = n_constant_features[0] + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants # <<<<<<<<<<<<<< + * cdef DTYPE_t current_feature_value + * */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 73; - goto __pyx_L13; - } + __pyx_v_n_total_constants = __pyx_v_n_known_constants; - /* "numpy.pxd":832 - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" + /* "sklearn/tree/_tree.pyx":2183 + * cdef SIZE_t p_next + * cdef SIZE_t p_prev + * cdef bint is_samples_sorted = 0 # indicate is sorted_samples is # <<<<<<<<<<<<<< + * # inititialized + * */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 108; - goto __pyx_L13; - } + __pyx_v_is_samples_sorted = 0; - /* "numpy.pxd":833 - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + /* "sklearn/tree/_tree.pyx":2200 + * # newly discovered constant features to spare computation on descendant + * # nodes. + * while (f_i > n_total_constants and # Stop early if remaining features # <<<<<<<<<<<<<< + * # are constant + * (n_visited_features < max_features or */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 76; - goto __pyx_L13; - } + while (1) { + __pyx_t_7 = ((__pyx_v_f_i > __pyx_v_n_total_constants) != 0); + if (__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L5_bool_binop_done; + } - /* "numpy.pxd":834 - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" + /* "sklearn/tree/_tree.pyx":2202 + * while (f_i > n_total_constants and # Stop early if remaining features + * # are constant + * (n_visited_features < max_features or # <<<<<<<<<<<<<< + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 113; - goto __pyx_L13; - } + __pyx_t_7 = ((__pyx_v_n_visited_features < __pyx_v_max_features) != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L5_bool_binop_done; + } - /* "numpy.pxd":835 - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" + /* "sklearn/tree/_tree.pyx":2204 + * (n_visited_features < max_features or + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): # <<<<<<<<<<<<<< + * + * n_visited_features += 1 */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 81; - goto __pyx_L13; - } + __pyx_t_7 = ((__pyx_v_n_visited_features <= (__pyx_v_n_found_constants + __pyx_v_n_drawn_constants)) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L5_bool_binop_done:; + if (!__pyx_t_6) break; - /* "numpy.pxd":836 - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + /* "sklearn/tree/_tree.pyx":2206 + * n_visited_features <= n_found_constants + n_drawn_constants)): + * + * n_visited_features += 1 # <<<<<<<<<<<<<< + * + * # Loop invariant: elements of features in */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 102; - goto __pyx_L13; - } + __pyx_v_n_visited_features = (__pyx_v_n_visited_features + 1); - /* "numpy.pxd":837 - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + /* "sklearn/tree/_tree.pyx":2220 + * + * # Draw a feature at random + * f_j = rand_int(n_drawn_constants, f_i - n_found_constants, # <<<<<<<<<<<<<< + * random_state) + * */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 100; - goto __pyx_L13; - } + __pyx_v_f_j = __pyx_f_7sklearn_4tree_5_tree_rand_int(__pyx_v_n_drawn_constants, (__pyx_v_f_i - __pyx_v_n_found_constants), __pyx_v_random_state); - /* "numpy.pxd":838 - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + /* "sklearn/tree/_tree.pyx":2223 + * random_state) + * + * if f_j < n_known_constants: # <<<<<<<<<<<<<< + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 103; - goto __pyx_L13; - } + __pyx_t_6 = ((__pyx_v_f_j < __pyx_v_n_known_constants) != 0); + if (__pyx_t_6) { - /* "numpy.pxd":839 - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + /* "sklearn/tree/_tree.pyx":2225 + * if f_j < n_known_constants: + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] # <<<<<<<<<<<<<< + * features[f_j] = features[n_drawn_constants] + * features[n_drawn_constants] = tmp */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 102; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L13; - } + __pyx_v_tmp = (__pyx_v_features[__pyx_v_f_j]); - /* "numpy.pxd":840 - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg - * elif t == NPY_OBJECT: f[0] = 79 #"O" + /* "sklearn/tree/_tree.pyx":2226 + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] + * features[f_j] = features[n_drawn_constants] # <<<<<<<<<<<<<< + * features[n_drawn_constants] = tmp + * */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 100; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L13; - } + (__pyx_v_features[__pyx_v_f_j]) = (__pyx_v_features[__pyx_v_n_drawn_constants]); - /* "numpy.pxd":841 - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< - * elif t == NPY_OBJECT: f[0] = 79 #"O" - * else: + /* "sklearn/tree/_tree.pyx":2227 + * tmp = features[f_j] + * features[f_j] = features[n_drawn_constants] + * features[n_drawn_constants] = tmp # <<<<<<<<<<<<<< + * + * n_drawn_constants += 1 */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 103; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L13; - } + (__pyx_v_features[__pyx_v_n_drawn_constants]) = __pyx_v_tmp; - /* "numpy.pxd":842 - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg - * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2229 + * features[n_drawn_constants] = tmp + * + * n_drawn_constants += 1 # <<<<<<<<<<<<<< + * * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_7) { - (__pyx_v_f[0]) = 79; - goto __pyx_L13; - } - /*else*/ { + __pyx_v_n_drawn_constants = (__pyx_v_n_drawn_constants + 1); + goto __pyx_L8; + } + /*else*/ { - /* "numpy.pxd":844 - * elif t == NPY_OBJECT: f[0] = 79 #"O" + /* "sklearn/tree/_tree.pyx":2233 * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< - * f += 1 - * else: + * # f_j in the interval [n_known_constants, f_i - n_found_constants[ + * f_j += n_found_constants # <<<<<<<<<<<<<< + * # f_j in the interval [n_total_constants, f_i[ + * */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_13), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L13:; + __pyx_v_f_j = (__pyx_v_f_j + __pyx_v_n_found_constants); - /* "numpy.pxd":845 - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * f += 1 # <<<<<<<<<<<<<< - * else: - * # Cython ignores struct boundary information ("T{...}"), + /* "sklearn/tree/_tree.pyx":2236 + * # f_j in the interval [n_total_constants, f_i[ + * + * current.feature = features[f_j] # <<<<<<<<<<<<<< + * self.extract_nnz(current.feature, + * &end_negative, &start_positive, */ - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; - } - /*else*/ { + __pyx_v_current.feature = (__pyx_v_features[__pyx_v_f_j]); - /* "numpy.pxd":849 - * # Cython ignores struct boundary information ("T{...}"), - * # so don't output it - * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< - * return f + /* "sklearn/tree/_tree.pyx":2237 * + * current.feature = features[f_j] + * self.extract_nnz(current.feature, # <<<<<<<<<<<<<< + * &end_negative, &start_positive, + * &is_samples_sorted) */ - __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_12; - } - __pyx_L11:; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter_extract_nnz(((struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *)__pyx_v_self), __pyx_v_current.feature, (&__pyx_v_end_negative), (&__pyx_v_start_positive), (&__pyx_v_is_samples_sorted)); - /* "numpy.pxd":850 - * # so don't output it - * f = _util_dtypestring(child, f, end, offset) - * return f # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2242 * + * # Sort the positive and negative parts of `Xf` + * sort(Xf + start, samples + start, end_negative - start) # <<<<<<<<<<<<<< + * sort(Xf + start_positive, samples + start_positive, + * end - start_positive) + */ + __pyx_f_7sklearn_4tree_5_tree_sort((__pyx_v_Xf + __pyx_v_start), (__pyx_v_samples + __pyx_v_start), (__pyx_v_end_negative - __pyx_v_start)); + + /* "sklearn/tree/_tree.pyx":2243 + * # Sort the positive and negative parts of `Xf` + * sort(Xf + start, samples + start, end_negative - start) + * sort(Xf + start_positive, samples + start_positive, # <<<<<<<<<<<<<< + * end - start_positive) * */ - __pyx_r = __pyx_v_f; - goto __pyx_L0; + __pyx_f_7sklearn_4tree_5_tree_sort((__pyx_v_Xf + __pyx_v_start_positive), (__pyx_v_samples + __pyx_v_start_positive), (__pyx_v_end - __pyx_v_start_positive)); - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_child); - __Pyx_XDECREF(__pyx_v_fields); - __Pyx_XDECREF(__pyx_v_childname); - __Pyx_XDECREF(__pyx_v_new_offset); - __Pyx_XDECREF(__pyx_v_t); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/tree/_tree.pyx":2247 + * + * # Update index_to_samples to take into account the sort + * for p in range(start, end_negative): # <<<<<<<<<<<<<< + * index_to_samples[samples[p]] = p + * for p in range(start_positive, end): + */ + __pyx_t_2 = __pyx_v_end_negative; + for (__pyx_t_8 = __pyx_v_start; __pyx_t_8 < __pyx_t_2; __pyx_t_8+=1) { + __pyx_v_p = __pyx_t_8; + + /* "sklearn/tree/_tree.pyx":2248 + * # Update index_to_samples to take into account the sort + * for p in range(start, end_negative): + * index_to_samples[samples[p]] = p # <<<<<<<<<<<<<< + * for p in range(start_positive, end): + * index_to_samples[samples[p]] = p + */ + (__pyx_v_index_to_samples[(__pyx_v_samples[__pyx_v_p])]) = __pyx_v_p; + } -/* "numpy.pxd":965 + /* "sklearn/tree/_tree.pyx":2249 + * for p in range(start, end_negative): + * index_to_samples[samples[p]] = p + * for p in range(start_positive, end): # <<<<<<<<<<<<<< + * index_to_samples[samples[p]] = p * + */ + __pyx_t_2 = __pyx_v_end; + for (__pyx_t_8 = __pyx_v_start_positive; __pyx_t_8 < __pyx_t_2; __pyx_t_8+=1) { + __pyx_v_p = __pyx_t_8; + + /* "sklearn/tree/_tree.pyx":2250 + * index_to_samples[samples[p]] = p + * for p in range(start_positive, end): + * index_to_samples[samples[p]] = p # <<<<<<<<<<<<<< * - * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< - * cdef PyObject* baseptr - * if base is None: + * # Add one or two zeros in Xf, if there is any */ + (__pyx_v_index_to_samples[(__pyx_v_samples[__pyx_v_p])]) = __pyx_v_p; + } -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { - PyObject *__pyx_v_baseptr; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base", 0); + /* "sklearn/tree/_tree.pyx":2253 + * + * # Add one or two zeros in Xf, if there is any + * if end_negative < start_positive: # <<<<<<<<<<<<<< + * start_positive -= 1 + * Xf[start_positive] = 0. + */ + __pyx_t_6 = ((__pyx_v_end_negative < __pyx_v_start_positive) != 0); + if (__pyx_t_6) { - /* "numpy.pxd":967 - * cdef inline void set_array_base(ndarray arr, object base): - * cdef PyObject* baseptr - * if base is None: # <<<<<<<<<<<<<< - * baseptr = NULL - * else: + /* "sklearn/tree/_tree.pyx":2254 + * # Add one or two zeros in Xf, if there is any + * if end_negative < start_positive: + * start_positive -= 1 # <<<<<<<<<<<<<< + * Xf[start_positive] = 0. + * */ - __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_v_start_positive = (__pyx_v_start_positive - 1); - /* "numpy.pxd":968 - * cdef PyObject* baseptr - * if base is None: - * baseptr = NULL # <<<<<<<<<<<<<< - * else: - * Py_INCREF(base) # important to do this before decref below! + /* "sklearn/tree/_tree.pyx":2255 + * if end_negative < start_positive: + * start_positive -= 1 + * Xf[start_positive] = 0. # <<<<<<<<<<<<<< + * + * if end_negative != start_positive: */ - __pyx_v_baseptr = NULL; - goto __pyx_L3; - } - /*else*/ { + (__pyx_v_Xf[__pyx_v_start_positive]) = 0.; - /* "numpy.pxd":970 - * baseptr = NULL - * else: - * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< - * baseptr = base - * Py_XDECREF(arr.base) + /* "sklearn/tree/_tree.pyx":2257 + * Xf[start_positive] = 0. + * + * if end_negative != start_positive: # <<<<<<<<<<<<<< + * Xf[end_negative] = 0. + * end_negative += 1 */ - Py_INCREF(__pyx_v_base); + __pyx_t_6 = ((__pyx_v_end_negative != __pyx_v_start_positive) != 0); + if (__pyx_t_6) { - /* "numpy.pxd":971 - * else: - * Py_INCREF(base) # important to do this before decref below! - * baseptr = base # <<<<<<<<<<<<<< - * Py_XDECREF(arr.base) - * arr.base = baseptr + /* "sklearn/tree/_tree.pyx":2258 + * + * if end_negative != start_positive: + * Xf[end_negative] = 0. # <<<<<<<<<<<<<< + * end_negative += 1 + * */ - __pyx_v_baseptr = ((PyObject *)__pyx_v_base); - } - __pyx_L3:; + (__pyx_v_Xf[__pyx_v_end_negative]) = 0.; - /* "numpy.pxd":972 - * Py_INCREF(base) # important to do this before decref below! - * baseptr = base - * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< - * arr.base = baseptr + /* "sklearn/tree/_tree.pyx":2259 + * if end_negative != start_positive: + * Xf[end_negative] = 0. + * end_negative += 1 # <<<<<<<<<<<<<< * + * if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: */ - Py_XDECREF(__pyx_v_arr->base); + __pyx_v_end_negative = (__pyx_v_end_negative + 1); + goto __pyx_L14; + } + __pyx_L14:; + goto __pyx_L13; + } + __pyx_L13:; - /* "numpy.pxd":973 - * baseptr = base - * Py_XDECREF(arr.base) - * arr.base = baseptr # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2261 + * end_negative += 1 * - * cdef inline object get_array_base(ndarray arr): + * if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: # <<<<<<<<<<<<<< + * features[f_j] = features[n_total_constants] + * features[n_total_constants] = current.feature */ - __pyx_v_arr->base = __pyx_v_baseptr; + __pyx_t_6 = (((__pyx_v_Xf[(__pyx_v_end - 1)]) <= ((__pyx_v_Xf[__pyx_v_start]) + __pyx_v_7sklearn_4tree_5_tree_FEATURE_THRESHOLD)) != 0); + if (__pyx_t_6) { - __Pyx_RefNannyFinishContext(); -} + /* "sklearn/tree/_tree.pyx":2262 + * + * if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: + * features[f_j] = features[n_total_constants] # <<<<<<<<<<<<<< + * features[n_total_constants] = current.feature + * + */ + (__pyx_v_features[__pyx_v_f_j]) = (__pyx_v_features[__pyx_v_n_total_constants]); -/* "numpy.pxd":975 - * arr.base = baseptr + /* "sklearn/tree/_tree.pyx":2263 + * if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: + * features[f_j] = features[n_total_constants] + * features[n_total_constants] = current.feature # <<<<<<<<<<<<<< * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * if arr.base is NULL: - * return None + * n_found_constants += 1 */ + __pyx_t_2 = __pyx_v_current.feature; + (__pyx_v_features[__pyx_v_n_total_constants]) = __pyx_t_2; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base", 0); + /* "sklearn/tree/_tree.pyx":2265 + * features[n_total_constants] = current.feature + * + * n_found_constants += 1 # <<<<<<<<<<<<<< + * n_total_constants += 1 + * + */ + __pyx_v_n_found_constants = (__pyx_v_n_found_constants + 1); - /* "numpy.pxd":976 + /* "sklearn/tree/_tree.pyx":2266 * - * cdef inline object get_array_base(ndarray arr): - * if arr.base is NULL: # <<<<<<<<<<<<<< - * return None - * else: + * n_found_constants += 1 + * n_total_constants += 1 # <<<<<<<<<<<<<< + * + * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); - if (__pyx_t_1) { + __pyx_v_n_total_constants = (__pyx_v_n_total_constants + 1); + goto __pyx_L15; + } + /*else*/ { - /* "numpy.pxd":977 - * cdef inline object get_array_base(ndarray arr): - * if arr.base is NULL: - * return None # <<<<<<<<<<<<<< - * else: - * return arr.base + /* "sklearn/tree/_tree.pyx":2269 + * + * else: + * f_i -= 1 # <<<<<<<<<<<<<< + * features[f_i], features[f_j] = features[f_j], features[f_i] + * */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_None); - __pyx_r = Py_None; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { + __pyx_v_f_i = (__pyx_v_f_i - 1); - /* "numpy.pxd":979 - * return None - * else: - * return arr.base # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2270 + * else: + * f_i -= 1 + * features[f_i], features[f_j] = features[f_j], features[f_i] # <<<<<<<<<<<<<< + * + * # Evaluate all splits */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); - __pyx_r = ((PyObject *)__pyx_v_arr->base); - goto __pyx_L0; - } - __pyx_L3:; + __pyx_t_2 = (__pyx_v_features[__pyx_v_f_j]); + __pyx_t_8 = (__pyx_v_features[__pyx_v_f_i]); + (__pyx_v_features[__pyx_v_f_i]) = __pyx_t_2; + (__pyx_v_features[__pyx_v_f_j]) = __pyx_t_8; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion __pyx_vtable_7sklearn_4tree_5_tree_Criterion; + /* "sklearn/tree/_tree.pyx":2273 + * + * # Evaluate all splits + * self.criterion.reset() # <<<<<<<<<<<<<< + * p = start + * + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->reset(__pyx_v_self->__pyx_base.__pyx_base.criterion); -static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Criterion(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *p; - PyObject *o = (*t->tp_alloc)(t, 0); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)o); - p->__pyx_vtab = __pyx_vtabptr_7sklearn_4tree_5_tree_Criterion; - return o; -} + /* "sklearn/tree/_tree.pyx":2274 + * # Evaluate all splits + * self.criterion.reset() + * p = start # <<<<<<<<<<<<<< + * + * while p < end: + */ + __pyx_v_p = __pyx_v_start; -static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_Criterion(PyObject *o) { - (*Py_TYPE(o)->tp_free)(o); -} + /* "sklearn/tree/_tree.pyx":2276 + * p = start + * + * while p < end: # <<<<<<<<<<<<<< + * if p + 1 != end_negative: + * p_next = p + 1 + */ + while (1) { + __pyx_t_6 = ((__pyx_v_p < __pyx_v_end) != 0); + if (!__pyx_t_6) break; -static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_Criterion[] = { - {0, 0, 0, 0} -}; + /* "sklearn/tree/_tree.pyx":2277 + * + * while p < end: + * if p + 1 != end_negative: # <<<<<<<<<<<<<< + * p_next = p + 1 + * else: + */ + __pyx_t_6 = (((__pyx_v_p + 1) != __pyx_v_end_negative) != 0); + if (__pyx_t_6) { -static PyNumberMethods __pyx_tp_as_number_Criterion = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2278 + * while p < end: + * if p + 1 != end_negative: + * p_next = p + 1 # <<<<<<<<<<<<<< + * else: + * p_next = start_positive + */ + __pyx_v_p_next = (__pyx_v_p + 1); + goto __pyx_L18; + } + /*else*/ { -static PySequenceMethods __pyx_tp_as_sequence_Criterion = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "sklearn/tree/_tree.pyx":2280 + * p_next = p + 1 + * else: + * p_next = start_positive # <<<<<<<<<<<<<< + * + * while (p_next < end and + */ + __pyx_v_p_next = __pyx_v_start_positive; + } + __pyx_L18:; -static PyMappingMethods __pyx_tp_as_mapping_Criterion = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* "sklearn/tree/_tree.pyx":2282 + * p_next = start_positive + * + * while (p_next < end and # <<<<<<<<<<<<<< + * Xf[p_next] <= Xf[p] + FEATURE_THRESHOLD): + * p = p_next + */ + while (1) { + __pyx_t_7 = ((__pyx_v_p_next < __pyx_v_end) != 0); + if (__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L21_bool_binop_done; + } -static PyBufferProcs __pyx_tp_as_buffer_Criterion = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2283 + * + * while (p_next < end and + * Xf[p_next] <= Xf[p] + FEATURE_THRESHOLD): # <<<<<<<<<<<<<< + * p = p_next + * if p + 1 != end_negative: + */ + __pyx_t_7 = (((__pyx_v_Xf[__pyx_v_p_next]) <= ((__pyx_v_Xf[__pyx_v_p]) + __pyx_v_7sklearn_4tree_5_tree_FEATURE_THRESHOLD)) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L21_bool_binop_done:; + if (!__pyx_t_6) break; + + /* "sklearn/tree/_tree.pyx":2284 + * while (p_next < end and + * Xf[p_next] <= Xf[p] + FEATURE_THRESHOLD): + * p = p_next # <<<<<<<<<<<<<< + * if p + 1 != end_negative: + * p_next = p + 1 + */ + __pyx_v_p = __pyx_v_p_next; + + /* "sklearn/tree/_tree.pyx":2285 + * Xf[p_next] <= Xf[p] + FEATURE_THRESHOLD): + * p = p_next + * if p + 1 != end_negative: # <<<<<<<<<<<<<< + * p_next = p + 1 + * else: + */ + __pyx_t_6 = (((__pyx_v_p + 1) != __pyx_v_end_negative) != 0); + if (__pyx_t_6) { + + /* "sklearn/tree/_tree.pyx":2286 + * p = p_next + * if p + 1 != end_negative: + * p_next = p + 1 # <<<<<<<<<<<<<< + * else: + * p_next = start_positive + */ + __pyx_v_p_next = (__pyx_v_p + 1); + goto __pyx_L23; + } + /*else*/ { -static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_Criterion = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.tree._tree.Criterion"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_4tree_5_tree_Criterion, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_Criterion, /*tp_as_number*/ - &__pyx_tp_as_sequence_Criterion, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_Criterion, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_Criterion, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Interface for splitting criteria (regression and classification)."), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_4tree_5_tree_Criterion, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_4tree_5_tree_Criterion, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree __pyx_vtable_7sklearn_4tree_5_tree_Tree; + /* "sklearn/tree/_tree.pyx":2288 + * p_next = p + 1 + * else: + * p_next = start_positive # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_next = __pyx_v_start_positive; + } + __pyx_L23:; + } -static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Tree(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_4tree_5_tree_Tree *p; - PyObject *o = (*t->tp_alloc)(t, 0); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)o); - p->__pyx_vtab = __pyx_vtabptr_7sklearn_4tree_5_tree_Tree; - p->criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)Py_None); Py_INCREF(Py_None); - p->random_state = Py_None; Py_INCREF(Py_None); - if (__pyx_pw_7sklearn_4tree_5_tree_4Tree_1__cinit__(o, a, k) < 0) { - Py_DECREF(o); o = 0; - } - return o; -} - -static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_Tree(PyObject *o) { - struct __pyx_obj_7sklearn_4tree_5_tree_Tree *p = (struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)o; - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - ++Py_REFCNT(o); - __pyx_pw_7sklearn_4tree_5_tree_4Tree_3__dealloc__(o); - if (PyErr_Occurred()) PyErr_WriteUnraisable(o); - --Py_REFCNT(o); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->criterion); - Py_CLEAR(p->random_state); - (*Py_TYPE(o)->tp_free)(o); -} + /* "sklearn/tree/_tree.pyx":2293 + * # (p_next >= end) or (X[samples[p_next], current.feature] > + * # X[samples[p], current.feature]) + * p_prev = p # <<<<<<<<<<<<<< + * p = p_next + * # (p >= end) or (X[samples[p], current.feature] > + */ + __pyx_v_p_prev = __pyx_v_p; -static int __pyx_tp_traverse_7sklearn_4tree_5_tree_Tree(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7sklearn_4tree_5_tree_Tree *p = (struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)o; - if (p->criterion) { - e = (*v)(((PyObject*)p->criterion), a); if (e) return e; - } - if (p->random_state) { - e = (*v)(p->random_state, a); if (e) return e; - } - return 0; -} + /* "sklearn/tree/_tree.pyx":2294 + * # X[samples[p], current.feature]) + * p_prev = p + * p = p_next # <<<<<<<<<<<<<< + * # (p >= end) or (X[samples[p], current.feature] > + * # X[samples[p_prev], current.feature]) + */ + __pyx_v_p = __pyx_v_p_next; -static int __pyx_tp_clear_7sklearn_4tree_5_tree_Tree(PyObject *o) { - struct __pyx_obj_7sklearn_4tree_5_tree_Tree *p = (struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)o; - PyObject* tmp; - tmp = ((PyObject*)p->criterion); - p->criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->random_state); - p->random_state = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} + /* "sklearn/tree/_tree.pyx":2299 + * + * + * if p < end: # <<<<<<<<<<<<<< + * current.pos = p + * + */ + __pyx_t_6 = ((__pyx_v_p < __pyx_v_end) != 0); + if (__pyx_t_6) { -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_classes(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_classes_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2300 + * + * if p < end: + * current.pos = p # <<<<<<<<<<<<<< + * + * # Reject if min_samples_leaf is not guaranteed + */ + __pyx_v_current.pos = __pyx_v_p; -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_children_left(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_13children_left_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2303 + * + * # Reject if min_samples_leaf is not guaranteed + * if (((current.pos - start) < min_samples_leaf) or # <<<<<<<<<<<<<< + * ((end - current.pos) < min_samples_leaf)): + * continue + */ + __pyx_t_7 = (((__pyx_v_current.pos - __pyx_v_start) < __pyx_v_min_samples_leaf) != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L26_bool_binop_done; + } -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_children_right(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_14children_right_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2304 + * # Reject if min_samples_leaf is not guaranteed + * if (((current.pos - start) < min_samples_leaf) or + * ((end - current.pos) < min_samples_leaf)): # <<<<<<<<<<<<<< + * continue + * + */ + __pyx_t_7 = (((__pyx_v_end - __pyx_v_current.pos) < __pyx_v_min_samples_leaf) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L26_bool_binop_done:; + if (__pyx_t_6) { -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_feature(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_7feature_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2305 + * if (((current.pos - start) < min_samples_leaf) or + * ((end - current.pos) < min_samples_leaf)): + * continue # <<<<<<<<<<<<<< + * + * self.criterion.update(current.pos) + */ + goto __pyx_L16_continue; + } -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_threshold(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9threshold_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2307 + * continue + * + * self.criterion.update(current.pos) # <<<<<<<<<<<<<< + * + * # Reject if min_weight_leaf is not satisfied + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->update(__pyx_v_self->__pyx_base.__pyx_base.criterion, __pyx_v_current.pos); -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_value(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_5value_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2310 + * + * # Reject if min_weight_leaf is not satisfied + * if ((self.criterion.weighted_n_left < min_weight_leaf) or # <<<<<<<<<<<<<< + * (self.criterion.weighted_n_right < min_weight_leaf)): + * continue + */ + __pyx_t_7 = ((__pyx_v_self->__pyx_base.__pyx_base.criterion->weighted_n_left < __pyx_v_min_weight_leaf) != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L29_bool_binop_done; + } -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_best_error(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_10best_error_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2311 + * # Reject if min_weight_leaf is not satisfied + * if ((self.criterion.weighted_n_left < min_weight_leaf) or + * (self.criterion.weighted_n_right < min_weight_leaf)): # <<<<<<<<<<<<<< + * continue + * + */ + __pyx_t_7 = ((__pyx_v_self->__pyx_base.__pyx_base.criterion->weighted_n_right < __pyx_v_min_weight_leaf) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L29_bool_binop_done:; + if (__pyx_t_6) { -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_init_error(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_10init_error_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2312 + * if ((self.criterion.weighted_n_left < min_weight_leaf) or + * (self.criterion.weighted_n_right < min_weight_leaf)): + * continue # <<<<<<<<<<<<<< + * + * current.improvement = self.criterion.impurity_improvement(impurity) + */ + goto __pyx_L16_continue; + } -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_samples(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_samples_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2314 + * continue + * + * current.improvement = self.criterion.impurity_improvement(impurity) # <<<<<<<<<<<<<< + * if current.improvement > best.improvement: + * self.criterion.children_impurity(¤t.impurity_left, + */ + __pyx_v_current.improvement = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->impurity_improvement(__pyx_v_self->__pyx_base.__pyx_base.criterion, __pyx_v_impurity); -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_features(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2315 + * + * current.improvement = self.criterion.impurity_improvement(impurity) + * if current.improvement > best.improvement: # <<<<<<<<<<<<<< + * self.criterion.children_impurity(¤t.impurity_left, + * ¤t.impurity_right) + */ + __pyx_t_6 = ((__pyx_v_current.improvement > __pyx_v_best.improvement) != 0); + if (__pyx_t_6) { -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_n_features(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; - } -} + /* "sklearn/tree/_tree.pyx":2316 + * current.improvement = self.criterion.impurity_improvement(impurity) + * if current.improvement > best.improvement: + * self.criterion.children_impurity(¤t.impurity_left, # <<<<<<<<<<<<<< + * ¤t.impurity_right) + * + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->children_impurity(__pyx_v_self->__pyx_base.__pyx_base.criterion, (&__pyx_v_current.impurity_left), (&__pyx_v_current.impurity_right)); -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_outputs(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2319 + * ¤t.impurity_right) + * + * current.threshold = (Xf[p_prev] + Xf[p]) / 2.0 # <<<<<<<<<<<<<< + * if current.threshold == Xf[p]: + * current.threshold = Xf[p_prev] + */ + __pyx_v_current.threshold = (((__pyx_v_Xf[__pyx_v_p_prev]) + (__pyx_v_Xf[__pyx_v_p])) / 2.0); -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_n_outputs(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; - } -} + /* "sklearn/tree/_tree.pyx":2320 + * + * current.threshold = (Xf[p_prev] + Xf[p]) / 2.0 + * if current.threshold == Xf[p]: # <<<<<<<<<<<<<< + * current.threshold = Xf[p_prev] + * + */ + __pyx_t_6 = ((__pyx_v_current.threshold == (__pyx_v_Xf[__pyx_v_p])) != 0); + if (__pyx_t_6) { -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_max_n_classes(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2321 + * current.threshold = (Xf[p_prev] + Xf[p]) / 2.0 + * if current.threshold == Xf[p]: + * current.threshold = Xf[p_prev] # <<<<<<<<<<<<<< + * + * best = current + */ + __pyx_v_current.threshold = (__pyx_v_Xf[__pyx_v_p_prev]); + goto __pyx_L32; + } + __pyx_L32:; -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_max_n_classes(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; + /* "sklearn/tree/_tree.pyx":2323 + * current.threshold = Xf[p_prev] + * + * best = current # <<<<<<<<<<<<<< + * + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + */ + __pyx_v_best = __pyx_v_current; + goto __pyx_L31; + } + __pyx_L31:; + goto __pyx_L24; + } + __pyx_L24:; + __pyx_L16_continue:; + } + } + __pyx_L15:; + } + __pyx_L8:; } -} -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_value_stride(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_12value_stride_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2326 + * + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + * if best.pos < end: # <<<<<<<<<<<<<< + * self.extract_nnz(best.feature, &end_negative, &start_positive, + * &is_samples_sorted) + */ + __pyx_t_6 = ((__pyx_v_best.pos < __pyx_v_end) != 0); + if (__pyx_t_6) { -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_value_stride(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_12value_stride_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; + /* "sklearn/tree/_tree.pyx":2327 + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + * if best.pos < end: + * self.extract_nnz(best.feature, &end_negative, &start_positive, # <<<<<<<<<<<<<< + * &is_samples_sorted) + * + */ + __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter_extract_nnz(((struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *)__pyx_v_self), __pyx_v_best.feature, (&__pyx_v_end_negative), (&__pyx_v_start_positive), (&__pyx_v_is_samples_sorted)); + + /* "sklearn/tree/_tree.pyx":2330 + * &is_samples_sorted) + * + * self._partition(best.threshold, end_negative, start_positive, # <<<<<<<<<<<<<< + * best.pos) + * + */ + __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter__partition(((struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *)__pyx_v_self), __pyx_v_best.threshold, __pyx_v_end_negative, __pyx_v_start_positive, __pyx_v_best.pos); + goto __pyx_L33; } -} + __pyx_L33:; -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_criterion(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9criterion_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2336 + * # element in features[:n_known_constants] must be preserved for sibling + * # and child nodes + * memcpy(features, constant_features, sizeof(SIZE_t) * n_known_constants) # <<<<<<<<<<<<<< + * + * # Copy newly found constant features + */ + memcpy(__pyx_v_features, __pyx_v_constant_features, ((sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)) * __pyx_v_n_known_constants)); -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_criterion(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9criterion_3__set__(o, v); - } - else { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9criterion_5__del__(o); - } -} + /* "sklearn/tree/_tree.pyx":2339 + * + * # Copy newly found constant features + * memcpy(constant_features + n_known_constants, # <<<<<<<<<<<<<< + * features + n_known_constants, + * sizeof(SIZE_t) * n_found_constants) + */ + memcpy((__pyx_v_constant_features + __pyx_v_n_known_constants), (__pyx_v_features + __pyx_v_n_known_constants), ((sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)) * __pyx_v_n_found_constants)); -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_max_depth(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2344 + * + * # Return values + * split[0] = best # <<<<<<<<<<<<<< + * n_constant_features[0] = n_total_constants + * + */ + (__pyx_v_split[0]) = __pyx_v_best; -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_max_depth(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; - } -} + /* "sklearn/tree/_tree.pyx":2345 + * # Return values + * split[0] = best + * n_constant_features[0] = n_total_constants # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_n_constant_features[0]) = __pyx_v_n_total_constants; -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_min_samples_split(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_17min_samples_split_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2140 + * self.random_state), self.__getstate__()) + * + * cdef void node_split(self, double impurity, SplitRecord* split, # <<<<<<<<<<<<<< + * SIZE_t* n_constant_features) nogil: + * """Find the best split on node samples[start:end], using sparse + */ -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_min_samples_split(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_17min_samples_split_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; - } + /* function exit code */ } -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_min_samples_leaf(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf_1__get__(o); -} +/* "sklearn/tree/_tree.pyx":2351 + * """Splitter for finding a random split, using the sparse data.""" + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (RandomSparseSplitter, (self.criterion, + * self.max_features, + */ -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_min_samples_leaf(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_16min_samples_leaf_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; - } -} +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_20RandomSparseSplitter_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_20RandomSparseSplitter_1__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_20RandomSparseSplitter___reduce__(((struct __pyx_obj_7sklearn_4tree_5_tree_RandomSparseSplitter *)__pyx_v_self)); -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_min_density(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_11min_density_1__get__(o); + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; } -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_min_density(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_11min_density_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; - } -} +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_20RandomSparseSplitter___reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_RandomSparseSplitter *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce__", 0); -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_max_features(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_12max_features_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2352 + * + * def __reduce__(self): + * return (RandomSparseSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, + */ + __Pyx_XDECREF(__pyx_r); -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_max_features(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_12max_features_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; - } -} + /* "sklearn/tree/_tree.pyx":2353 + * def __reduce__(self): + * return (RandomSparseSplitter, (self.criterion, + * self.max_features, # <<<<<<<<<<<<<< + * self.min_samples_leaf, + * self.min_weight_leaf, + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.__pyx_base.max_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2353; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_find_split_algorithm(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2354 + * return (RandomSparseSplitter, (self.criterion, + * self.max_features, + * self.min_samples_leaf, # <<<<<<<<<<<<<< + * self.min_weight_leaf, + * self.random_state), self.__getstate__()) + */ + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->__pyx_base.__pyx_base.min_samples_leaf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2354; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_find_split_algorithm(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_20find_split_algorithm_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; - } -} + /* "sklearn/tree/_tree.pyx":2355 + * self.max_features, + * self.min_samples_leaf, + * self.min_weight_leaf, # <<<<<<<<<<<<<< + * self.random_state), self.__getstate__()) + * + */ + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_self->__pyx_base.__pyx_base.min_weight_leaf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_random_state(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_12random_state_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2352 + * + * def __reduce__(self): + * return (RandomSparseSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, + */ + __pyx_t_4 = PyTuple_New(5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self->__pyx_base.__pyx_base.criterion)); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 3, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_self->__pyx_base.__pyx_base.random_state); + PyTuple_SET_ITEM(__pyx_t_4, 4, __pyx_v_self->__pyx_base.__pyx_base.random_state); + __Pyx_GIVEREF(__pyx_v_self->__pyx_base.__pyx_base.random_state); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_random_state(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_12random_state_3__set__(o, v); + /* "sklearn/tree/_tree.pyx":2356 + * self.min_samples_leaf, + * self.min_weight_leaf, + * self.random_state), self.__getstate__()) # <<<<<<<<<<<<<< + * + * cdef void node_split(self, double impurity, SplitRecord* split, + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_getstate); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } } - else { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_12random_state_5__del__(o); + if (__pyx_t_1) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } -} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_node_count(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_1__get__(o); -} + /* "sklearn/tree/_tree.pyx":2352 + * + * def __reduce__(self): + * return (RandomSparseSplitter, (self.criterion, # <<<<<<<<<<<<<< + * self.max_features, + * self.min_samples_leaf, + */ + __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RandomSparseSplitter))); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RandomSparseSplitter))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_RandomSparseSplitter))); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_node_count(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; - } -} + /* "sklearn/tree/_tree.pyx":2351 + * """Splitter for finding a random split, using the sparse data.""" + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (RandomSparseSplitter, (self.criterion, + * self.max_features, + */ -static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_capacity(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_1__get__(o); + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.RandomSparseSplitter.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; } -static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_capacity(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { - if (v) { - return __pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_3__set__(o, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__del__"); - return -1; - } -} +/* "sklearn/tree/_tree.pyx":2358 + * self.random_state), self.__getstate__()) + * + * cdef void node_split(self, double impurity, SplitRecord* split, # <<<<<<<<<<<<<< + * SIZE_t* n_constant_features) nogil: + * """Find a random split on node samples[start:end], using sparse + */ + +static void __pyx_f_7sklearn_4tree_5_tree_20RandomSparseSplitter_node_split(struct __pyx_obj_7sklearn_4tree_5_tree_RandomSparseSplitter *__pyx_v_self, double __pyx_v_impurity, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *__pyx_v_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_n_constant_features) { + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_v_X_indices; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_v_X_indptr; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_data; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_constant_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_features; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_Xf; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_sorted_samples; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_index_to_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + double __pyx_v_min_weight_leaf; + __pyx_t_7sklearn_4tree_5_tree_UINT32_t *__pyx_v_random_state; + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_best; + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_current; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_current_feature_value; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_f_i; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_f_j; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_p; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_tmp; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_visited_features; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_found_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_drawn_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_known_constants; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_total_constants; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_min_feature_value; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_max_feature_value; + int __pyx_v_is_samples_sorted; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start_positive; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end_negative; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_t_1; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + __pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_t_4; + double __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_8; -static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_Tree[] = { - {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_5__reduce__, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_4tree_5_tree_4Tree_4__reduce__)}, - {__Pyx_NAMESTR("__getstate__"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_7__getstate__, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_4tree_5_tree_4Tree_6__getstate__)}, - {__Pyx_NAMESTR("__setstate__"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_9__setstate__, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_4tree_5_tree_4Tree_8__setstate__)}, - {__Pyx_NAMESTR("build"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_11build, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_4tree_5_tree_4Tree_10build)}, - {__Pyx_NAMESTR("predict"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_13predict, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_4tree_5_tree_4Tree_12predict)}, - {__Pyx_NAMESTR("apply"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_15apply, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_4tree_5_tree_4Tree_14apply)}, - {__Pyx_NAMESTR("compute_feature_importances"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_17compute_feature_importances, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_4tree_5_tree_4Tree_16compute_feature_importances)}, - {0, 0, 0, 0} -}; + /* "sklearn/tree/_tree.pyx":2364 + * """ + * # Find the best split + * cdef SIZE_t* samples = self.samples # <<<<<<<<<<<<<< + * cdef SIZE_t start = self.start + * cdef SIZE_t end = self.end + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.samples; + __pyx_v_samples = __pyx_t_1; -static struct PyGetSetDef __pyx_getsets_7sklearn_4tree_5_tree_Tree[] = { - {(char *)"n_classes", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_classes, 0, 0, 0}, - {(char *)"children_left", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_children_left, 0, 0, 0}, - {(char *)"children_right", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_children_right, 0, 0, 0}, - {(char *)"feature", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_feature, 0, 0, 0}, - {(char *)"threshold", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_threshold, 0, 0, 0}, - {(char *)"value", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_value, 0, 0, 0}, - {(char *)"best_error", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_best_error, 0, 0, 0}, - {(char *)"init_error", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_init_error, 0, 0, 0}, - {(char *)"n_samples", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_samples, 0, 0, 0}, - {(char *)"n_features", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_features, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_n_features, 0, 0}, - {(char *)"n_outputs", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_outputs, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_n_outputs, 0, 0}, - {(char *)"max_n_classes", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_max_n_classes, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_max_n_classes, 0, 0}, - {(char *)"value_stride", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_value_stride, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_value_stride, 0, 0}, - {(char *)"criterion", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_criterion, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_criterion, 0, 0}, - {(char *)"max_depth", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_max_depth, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_max_depth, 0, 0}, - {(char *)"min_samples_split", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_min_samples_split, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_min_samples_split, 0, 0}, - {(char *)"min_samples_leaf", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_min_samples_leaf, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_min_samples_leaf, 0, 0}, - {(char *)"min_density", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_min_density, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_min_density, 0, 0}, - {(char *)"max_features", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_max_features, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_max_features, 0, 0}, - {(char *)"find_split_algorithm", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_find_split_algorithm, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_find_split_algorithm, 0, 0}, - {(char *)"random_state", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_random_state, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_random_state, 0, 0}, - {(char *)"node_count", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_node_count, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_node_count, 0, 0}, - {(char *)"capacity", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_capacity, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_capacity, 0, 0}, - {0, 0, 0, 0, 0} -}; + /* "sklearn/tree/_tree.pyx":2365 + * # Find the best split + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t start = self.start # <<<<<<<<<<<<<< + * cdef SIZE_t end = self.end + * + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.start; + __pyx_v_start = __pyx_t_2; -static PyNumberMethods __pyx_tp_as_number_Tree = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2366 + * cdef SIZE_t* samples = self.samples + * cdef SIZE_t start = self.start + * cdef SIZE_t end = self.end # <<<<<<<<<<<<<< + * + * cdef INT32_t* X_indices = self.X_indices + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.end; + __pyx_v_end = __pyx_t_2; -static PySequenceMethods __pyx_tp_as_sequence_Tree = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "sklearn/tree/_tree.pyx":2368 + * cdef SIZE_t end = self.end + * + * cdef INT32_t* X_indices = self.X_indices # <<<<<<<<<<<<<< + * cdef INT32_t* X_indptr = self.X_indptr + * cdef DTYPE_t* X_data = self.X_data + */ + __pyx_t_3 = __pyx_v_self->__pyx_base.X_indices; + __pyx_v_X_indices = __pyx_t_3; -static PyMappingMethods __pyx_tp_as_mapping_Tree = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* "sklearn/tree/_tree.pyx":2369 + * + * cdef INT32_t* X_indices = self.X_indices + * cdef INT32_t* X_indptr = self.X_indptr # <<<<<<<<<<<<<< + * cdef DTYPE_t* X_data = self.X_data + * + */ + __pyx_t_3 = __pyx_v_self->__pyx_base.X_indptr; + __pyx_v_X_indptr = __pyx_t_3; -static PyBufferProcs __pyx_tp_as_buffer_Tree = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2370 + * cdef INT32_t* X_indices = self.X_indices + * cdef INT32_t* X_indptr = self.X_indptr + * cdef DTYPE_t* X_data = self.X_data # <<<<<<<<<<<<<< + * + * cdef SIZE_t* features = self.features + */ + __pyx_t_4 = __pyx_v_self->__pyx_base.X_data; + __pyx_v_X_data = __pyx_t_4; -static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_Tree = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.tree._tree.Tree"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Tree), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_4tree_5_tree_Tree, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_Tree, /*tp_as_number*/ - &__pyx_tp_as_sequence_Tree, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_Tree, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_Tree, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - __Pyx_DOCSTR("Struct-of-arrays representation of a binary decision tree.\n\n The binary tree is represented as a number of parallel arrays.\n The i-th element of each array holds information about the\n node `i`. You can find a detailed description of all arrays\n below. NOTE: Some of the arrays only apply to either leaves or\n split nodes, resp. In this case the values of nodes of the other\n type are arbitrary!\n\n Parameters\n ----------\n n_features : int\n The number of features\n\n n_classes : array-like\n n_classes[k] is the number of classes for output k.\n\n n_outputs : int\n The number of outputs.\n\n criterion : Criterion\n max_depth : double\n min_samples_split : int\n min_samples_leaf : int\n min_density : double\n max_features : int\n find_split_algorithm : int\n\n Attributes\n ----------\n node_count : int\n The number of nodes (internal nodes + leaves) in the tree.\n\n capacity : int\n The current capacity (i.e., size) of the arrays.\n\n children_left : int*\n children_left[i] holds the node id of the child if node i.\n For leaves, children_left[i] == TREE_LEAF.\n\n children_right : int*\n children_left[i] holds the node id of the child if node i.\n For leaves, children_left[i] == TREE_LEAF.\n\n feature : int*\n feature[i] holds the feature to split on, for the internal node i.\n\n threshold : double*\n threshold[i] holds the threshold for the internal node i.\n\n value : double*\n Contains the constant prediction value of each node.\n\n best_error : double*\n best_error[i] holds the error of the (best) split at node i.\n For leaves init_error[i] == best_error[i].\n\n init_error : double*\n init_error[i] holds the initial error at node i (before splitting).\n For leaves init_error[i] == best_error[i].\n\n n_samples : int*\n n_samples[i] holds the number of training samples reaching node i.\n "), /*tp_doc*/ - __pyx_tp_traverse_7sklearn_4tree_5_tree_Tree, /*tp_traverse*/ - __pyx_tp_clear_7sklearn_4tree_5_tree_Tree, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_4tree_5_tree_Tree, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets_7sklearn_4tree_5_tree_Tree, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_4tree_5_tree_Tree, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion; + /* "sklearn/tree/_tree.pyx":2372 + * cdef DTYPE_t* X_data = self.X_data + * + * cdef SIZE_t* features = self.features # <<<<<<<<<<<<<< + * cdef SIZE_t* constant_features = self.constant_features + * cdef SIZE_t n_features = self.n_features + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.features; + __pyx_v_features = __pyx_t_1; -static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_ClassificationCriterion(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *p; - PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_Criterion(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion; - if (__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_1__cinit__(o, a, k) < 0) { - Py_DECREF(o); o = 0; - } - return o; -} + /* "sklearn/tree/_tree.pyx":2373 + * + * cdef SIZE_t* features = self.features + * cdef SIZE_t* constant_features = self.constant_features # <<<<<<<<<<<<<< + * cdef SIZE_t n_features = self.n_features + * + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base.constant_features; + __pyx_v_constant_features = __pyx_t_1; -static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_ClassificationCriterion(PyObject *o) { - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - ++Py_REFCNT(o); - __pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_3__dealloc__(o); - if (PyErr_Occurred()) PyErr_WriteUnraisable(o); - --Py_REFCNT(o); - PyErr_Restore(etype, eval, etb); - } - __pyx_tp_dealloc_7sklearn_4tree_5_tree_Criterion(o); -} + /* "sklearn/tree/_tree.pyx":2374 + * cdef SIZE_t* features = self.features + * cdef SIZE_t* constant_features = self.constant_features + * cdef SIZE_t n_features = self.n_features # <<<<<<<<<<<<<< + * + * cdef DTYPE_t* Xf = self.feature_values + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.n_features; + __pyx_v_n_features = __pyx_t_2; -static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_ClassificationCriterion[] = { - {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_5__reduce__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__getstate__"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_7__getstate__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__setstate__"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_9__setstate__, METH_O, __Pyx_DOCSTR(0)}, - {0, 0, 0, 0} -}; + /* "sklearn/tree/_tree.pyx":2376 + * cdef SIZE_t n_features = self.n_features + * + * cdef DTYPE_t* Xf = self.feature_values # <<<<<<<<<<<<<< + * cdef SIZE_t* sorted_samples = self.sorted_samples + * cdef SIZE_t* index_to_samples = self.index_to_samples + */ + __pyx_t_4 = __pyx_v_self->__pyx_base.__pyx_base.feature_values; + __pyx_v_Xf = __pyx_t_4; -static PyNumberMethods __pyx_tp_as_number_ClassificationCriterion = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2377 + * + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t* sorted_samples = self.sorted_samples # <<<<<<<<<<<<<< + * cdef SIZE_t* index_to_samples = self.index_to_samples + * cdef SIZE_t max_features = self.max_features + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.sorted_samples; + __pyx_v_sorted_samples = __pyx_t_1; -static PySequenceMethods __pyx_tp_as_sequence_ClassificationCriterion = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "sklearn/tree/_tree.pyx":2378 + * cdef DTYPE_t* Xf = self.feature_values + * cdef SIZE_t* sorted_samples = self.sorted_samples + * cdef SIZE_t* index_to_samples = self.index_to_samples # <<<<<<<<<<<<<< + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + */ + __pyx_t_1 = __pyx_v_self->__pyx_base.index_to_samples; + __pyx_v_index_to_samples = __pyx_t_1; -static PyMappingMethods __pyx_tp_as_mapping_ClassificationCriterion = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* "sklearn/tree/_tree.pyx":2379 + * cdef SIZE_t* sorted_samples = self.sorted_samples + * cdef SIZE_t* index_to_samples = self.index_to_samples + * cdef SIZE_t max_features = self.max_features # <<<<<<<<<<<<<< + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.max_features; + __pyx_v_max_features = __pyx_t_2; -static PyBufferProcs __pyx_tp_as_buffer_ClassificationCriterion = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2380 + * cdef SIZE_t* index_to_samples = self.index_to_samples + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf # <<<<<<<<<<<<<< + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef UINT32_t* random_state = &self.rand_r_state + */ + __pyx_t_2 = __pyx_v_self->__pyx_base.__pyx_base.min_samples_leaf; + __pyx_v_min_samples_leaf = __pyx_t_2; -static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.tree._tree.ClassificationCriterion"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_4tree_5_tree_ClassificationCriterion, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_ClassificationCriterion, /*tp_as_number*/ - &__pyx_tp_as_sequence_ClassificationCriterion, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_ClassificationCriterion, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_ClassificationCriterion, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Abstract criterion for classification.\n\n Attributes\n ----------\n n_outputs : int\n The number of outputs.\n\n n_classes : int*\n n_classes[k] is the number of classes for output k.\n\n n_samples : int\n The number of samples.\n\n label_count_stride : int\n The stride between outputs in label_count_* arrays.\n\n label_count_left : int*\n label_count_left[k * label_count_stride + c] is the number of samples\n of class c left of splitting point for output k.\n\n label_count_right : int*\n label_count_rightt[k * label_count_stride + c] is the number of samples\n of class c right of splitting point for output k.\n\n label_count_init : int*\n label_count_init[k * label_count_stride + c] is the initial number of\n samples of class c for output k. Used to reset `label_count_right` for\n each feature.\n\n n_left : int\n The number of samples left of splitting point.\n\n n_right : int\n The number of samples right of splitting point.\n\n References\n ----------\n\n [1] Hastie et al. \"Elements of Statistical Learning\", 2009.\n "), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_4tree_5_tree_ClassificationCriterion, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_4tree_5_tree_ClassificationCriterion, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Gini __pyx_vtable_7sklearn_4tree_5_tree_Gini; + /* "sklearn/tree/_tree.pyx":2381 + * cdef SIZE_t max_features = self.max_features + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf # <<<<<<<<<<<<<< + * cdef UINT32_t* random_state = &self.rand_r_state + * + */ + __pyx_t_5 = __pyx_v_self->__pyx_base.__pyx_base.min_weight_leaf; + __pyx_v_min_weight_leaf = __pyx_t_5; -static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Gini(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_4tree_5_tree_Gini *p; - PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_ClassificationCriterion(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_4tree_5_tree_Gini *)o); - p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__pyx_vtabptr_7sklearn_4tree_5_tree_Gini; - return o; -} + /* "sklearn/tree/_tree.pyx":2382 + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef UINT32_t* random_state = &self.rand_r_state # <<<<<<<<<<<<<< + * + * cdef SplitRecord best, current + */ + __pyx_v_random_state = (&__pyx_v_self->__pyx_base.__pyx_base.rand_r_state); -static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_Gini[] = { - {0, 0, 0, 0} -}; + /* "sklearn/tree/_tree.pyx":2385 + * + * cdef SplitRecord best, current + * _init_split(&best, end) # <<<<<<<<<<<<<< + * + * cdef DTYPE_t current_feature_value + */ + __pyx_f_7sklearn_4tree_5_tree__init_split((&__pyx_v_best), __pyx_v_end); -static PyNumberMethods __pyx_tp_as_number_Gini = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2389 + * cdef DTYPE_t current_feature_value + * + * cdef SIZE_t f_i = n_features # <<<<<<<<<<<<<< + * cdef SIZE_t f_j, p, tmp + * cdef SIZE_t n_visited_features = 0 + */ + __pyx_v_f_i = __pyx_v_n_features; -static PySequenceMethods __pyx_tp_as_sequence_Gini = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "sklearn/tree/_tree.pyx":2391 + * cdef SIZE_t f_i = n_features + * cdef SIZE_t f_j, p, tmp + * cdef SIZE_t n_visited_features = 0 # <<<<<<<<<<<<<< + * # Number of features discovered to be constant during the split search + * cdef SIZE_t n_found_constants = 0 + */ + __pyx_v_n_visited_features = 0; -static PyMappingMethods __pyx_tp_as_mapping_Gini = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* "sklearn/tree/_tree.pyx":2393 + * cdef SIZE_t n_visited_features = 0 + * # Number of features discovered to be constant during the split search + * cdef SIZE_t n_found_constants = 0 # <<<<<<<<<<<<<< + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 + */ + __pyx_v_n_found_constants = 0; -static PyBufferProcs __pyx_tp_as_buffer_Gini = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2395 + * cdef SIZE_t n_found_constants = 0 + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 # <<<<<<<<<<<<<< + * cdef SIZE_t n_known_constants = n_constant_features[0] + * # n_total_constants = n_known_constants + n_found_constants + */ + __pyx_v_n_drawn_constants = 0; -static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_Gini = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.tree._tree.Gini"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Gini), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_4tree_5_tree_ClassificationCriterion, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_Gini, /*tp_as_number*/ - &__pyx_tp_as_sequence_Gini, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_Gini, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_Gini, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Gini Index splitting criteria.\n\n Let the target be a classification outcome taking values in 0, 1, ..., K-1.\n If node m represents a region Rm with Nm observations, then let\n\n pmk = 1/ Nm \\sum_{x_i in Rm} I(yi = k)\n\n be the proportion of class k observations in node m.\n\n The Gini Index is then defined as:\n\n index = \\sum_{k=0}^{K-1} pmk (1 - pmk)\n = 1 - \\sum_{k=0}^{K-1} pmk ** 2\n "), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_4tree_5_tree_Gini, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_4tree_5_tree_Gini, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Entropy __pyx_vtable_7sklearn_4tree_5_tree_Entropy; + /* "sklearn/tree/_tree.pyx":2396 + * # Number of features known to be constant and drawn without replacement + * cdef SIZE_t n_drawn_constants = 0 + * cdef SIZE_t n_known_constants = n_constant_features[0] # <<<<<<<<<<<<<< + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants + */ + __pyx_v_n_known_constants = (__pyx_v_n_constant_features[0]); -static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Entropy(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_4tree_5_tree_Entropy *p; - PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_ClassificationCriterion(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_4tree_5_tree_Entropy *)o); - p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__pyx_vtabptr_7sklearn_4tree_5_tree_Entropy; - return o; -} + /* "sklearn/tree/_tree.pyx":2398 + * cdef SIZE_t n_known_constants = n_constant_features[0] + * # n_total_constants = n_known_constants + n_found_constants + * cdef SIZE_t n_total_constants = n_known_constants # <<<<<<<<<<<<<< + * cdef SIZE_t partition_end + * + */ + __pyx_v_n_total_constants = __pyx_v_n_known_constants; -static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_Entropy[] = { - {0, 0, 0, 0} -}; + /* "sklearn/tree/_tree.pyx":2404 + * cdef DTYPE_t max_feature_value + * + * cdef bint is_samples_sorted = 0 # indicate that sorted_samples is # <<<<<<<<<<<<<< + * # inititialized + * + */ + __pyx_v_is_samples_sorted = 0; -static PyNumberMethods __pyx_tp_as_number_Entropy = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2421 + * # newly discovered constant features to spare computation on descendant + * # nodes. + * while (f_i > n_total_constants and # Stop early if remaining features # <<<<<<<<<<<<<< + * # are constant + * (n_visited_features < max_features or + */ + while (1) { + __pyx_t_7 = ((__pyx_v_f_i > __pyx_v_n_total_constants) != 0); + if (__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L5_bool_binop_done; + } -static PySequenceMethods __pyx_tp_as_sequence_Entropy = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "sklearn/tree/_tree.pyx":2423 + * while (f_i > n_total_constants and # Stop early if remaining features + * # are constant + * (n_visited_features < max_features or # <<<<<<<<<<<<<< + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): + */ + __pyx_t_7 = ((__pyx_v_n_visited_features < __pyx_v_max_features) != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L5_bool_binop_done; + } -static PyMappingMethods __pyx_tp_as_mapping_Entropy = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* "sklearn/tree/_tree.pyx":2425 + * (n_visited_features < max_features or + * # At least one drawn features must be non constant + * n_visited_features <= n_found_constants + n_drawn_constants)): # <<<<<<<<<<<<<< + * + * n_visited_features += 1 + */ + __pyx_t_7 = ((__pyx_v_n_visited_features <= (__pyx_v_n_found_constants + __pyx_v_n_drawn_constants)) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L5_bool_binop_done:; + if (!__pyx_t_6) break; -static PyBufferProcs __pyx_tp_as_buffer_Entropy = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2427 + * n_visited_features <= n_found_constants + n_drawn_constants)): + * + * n_visited_features += 1 # <<<<<<<<<<<<<< + * + * # Loop invariant: elements of features in + */ + __pyx_v_n_visited_features = (__pyx_v_n_visited_features + 1); -static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_Entropy = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.tree._tree.Entropy"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Entropy), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_4tree_5_tree_ClassificationCriterion, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_Entropy, /*tp_as_number*/ - &__pyx_tp_as_sequence_Entropy, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_Entropy, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_Entropy, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Cross Entropy splitting criteria.\n\n Let the target be a classification outcome taking values in 0, 1, ..., K-1.\n If node m represents a region Rm with Nm observations, then let\n\n pmk = 1/ Nm \\sum_{x_i in Rm} I(yi = k)\n\n be the proportion of class k observations in node m.\n\n The cross-entropy is then defined as\n\n cross-entropy = - \\sum_{k=0}^{K-1} pmk log(pmk)\n "), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_4tree_5_tree_Entropy, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_4tree_5_tree_Entropy, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RegressionCriterion __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion; + /* "sklearn/tree/_tree.pyx":2441 + * + * # Draw a feature at random + * f_j = rand_int(n_drawn_constants, f_i - n_found_constants, # <<<<<<<<<<<<<< + * random_state) + * + */ + __pyx_v_f_j = __pyx_f_7sklearn_4tree_5_tree_rand_int(__pyx_v_n_drawn_constants, (__pyx_v_f_i - __pyx_v_n_found_constants), __pyx_v_random_state); -static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_RegressionCriterion(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *p; - PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_Criterion(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__pyx_vtabptr_7sklearn_4tree_5_tree_RegressionCriterion; - if (__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_1__cinit__(o, a, k) < 0) { - Py_DECREF(o); o = 0; - } - return o; -} - -static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_RegressionCriterion(PyObject *o) { - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - ++Py_REFCNT(o); - __pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_3__dealloc__(o); - if (PyErr_Occurred()) PyErr_WriteUnraisable(o); - --Py_REFCNT(o); - PyErr_Restore(etype, eval, etb); - } - __pyx_tp_dealloc_7sklearn_4tree_5_tree_Criterion(o); -} - -static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_RegressionCriterion[] = { - {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_5__reduce__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__getstate__"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_7__getstate__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__setstate__"), (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_9__setstate__, METH_O, __Pyx_DOCSTR(0)}, - {0, 0, 0, 0} -}; - -static PyNumberMethods __pyx_tp_as_number_RegressionCriterion = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; - -static PySequenceMethods __pyx_tp_as_sequence_RegressionCriterion = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_RegressionCriterion = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_RegressionCriterion = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; - -static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_RegressionCriterion = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.tree._tree.RegressionCriterion"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_4tree_5_tree_RegressionCriterion, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_RegressionCriterion, /*tp_as_number*/ - &__pyx_tp_as_sequence_RegressionCriterion, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_RegressionCriterion, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_RegressionCriterion, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Abstract criterion for regression.\n\n Computes variance of the target values left and right of the split point.\n Computation is linear in `n_samples` by using ::\n\n var = \\sum_i^n (y_i - y_bar) ** 2\n = (\\sum_i^n y_i ** 2) - n_samples y_bar ** 2\n\n Attributes\n ----------\n n_outputs : int\n The number of outputs.\n\n n_samples : int\n The number of samples\n\n mean_left : double*\n mean_left[k] is the mean target value of the samples left of the split\n point for output k.\n\n mean_right : double*\n mean_right[k] is the mean target value of the samples right of the split\n point for output k.\n\n sq_sum_left : double*\n sq_sum_left[k] is the sum of squared target values left of the split\n point for output k.\n\n sq_sum_right : double*\n sq_sum_right[k] is the sum of squared target values right of the split\n point for output k.\n\n var_left : double*\n var_left[k] is the variance of the values left of the split point for\n output k.\n\n var_right : double*\n var_right[k] is the variance of the values riht of the split point for\n output k.\n\n n_left : int\n number of samples left of split point.\n\n n_right : int\n number of samples right of split point.\n "), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_4tree_5_tree_RegressionCriterion, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_4tree_5_tree_RegressionCriterion, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; -static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_MSE __pyx_vtable_7sklearn_4tree_5_tree_MSE; - -static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_MSE(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7sklearn_4tree_5_tree_MSE *p; - PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_RegressionCriterion(t, a, k); - if (!o) return 0; - p = ((struct __pyx_obj_7sklearn_4tree_5_tree_MSE *)o); - p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__pyx_vtabptr_7sklearn_4tree_5_tree_MSE; - return o; -} - -static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_MSE[] = { - {0, 0, 0, 0} -}; - -static PyNumberMethods __pyx_tp_as_number_MSE = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; - -static PySequenceMethods __pyx_tp_as_sequence_MSE = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "sklearn/tree/_tree.pyx":2444 + * random_state) + * + * if f_j < n_known_constants: # <<<<<<<<<<<<<< + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] + */ + __pyx_t_6 = ((__pyx_v_f_j < __pyx_v_n_known_constants) != 0); + if (__pyx_t_6) { -static PyMappingMethods __pyx_tp_as_mapping_MSE = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; + /* "sklearn/tree/_tree.pyx":2446 + * if f_j < n_known_constants: + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] # <<<<<<<<<<<<<< + * features[f_j] = features[n_drawn_constants] + * features[n_drawn_constants] = tmp + */ + __pyx_v_tmp = (__pyx_v_features[__pyx_v_f_j]); -static PyBufferProcs __pyx_tp_as_buffer_MSE = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2447 + * # f_j in the interval [n_drawn_constants, n_known_constants[ + * tmp = features[f_j] + * features[f_j] = features[n_drawn_constants] # <<<<<<<<<<<<<< + * features[n_drawn_constants] = tmp + * + */ + (__pyx_v_features[__pyx_v_f_j]) = (__pyx_v_features[__pyx_v_n_drawn_constants]); -static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_MSE = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.tree._tree.MSE"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_MSE), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_4tree_5_tree_RegressionCriterion, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_MSE, /*tp_as_number*/ - &__pyx_tp_as_sequence_MSE, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_MSE, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_MSE, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("Mean squared error impurity criterion.\n\n MSE = var_left + var_right\n "), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7sklearn_4tree_5_tree_MSE, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7sklearn_4tree_5_tree_MSE, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; + /* "sklearn/tree/_tree.pyx":2448 + * tmp = features[f_j] + * features[f_j] = features[n_drawn_constants] + * features[n_drawn_constants] = tmp # <<<<<<<<<<<<<< + * + * n_drawn_constants += 1 + */ + (__pyx_v_features[__pyx_v_n_drawn_constants]) = __pyx_v_tmp; -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; + /* "sklearn/tree/_tree.pyx":2450 + * features[n_drawn_constants] = tmp + * + * n_drawn_constants += 1 # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_v_n_drawn_constants = (__pyx_v_n_drawn_constants + 1); + goto __pyx_L8; + } + /*else*/ { -#if PY_MAJOR_VERSION >= 3 -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - __Pyx_NAMESTR("_tree"), - 0, /* m_doc */ - -1, /* m_size */ - __pyx_methods /* m_methods */, - NULL, /* m_reload */ - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif + /* "sklearn/tree/_tree.pyx":2454 + * else: + * # f_j in the interval [n_known_constants, f_i - n_found_constants[ + * f_j += n_found_constants # <<<<<<<<<<<<<< + * # f_j in the interval [n_total_constants, f_i[ + * + */ + __pyx_v_f_j = (__pyx_v_f_j + __pyx_v_n_found_constants); -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_n_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 1}, - {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, - {&__pyx_kp_u_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 1, 0, 0}, - {&__pyx_kp_u_14, __pyx_k_14, sizeof(__pyx_k_14), 0, 1, 0, 0}, - {&__pyx_kp_u_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 1, 0, 0}, - {&__pyx_kp_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 0}, - {&__pyx_kp_s_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 1, 0}, - {&__pyx_n_s_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 1, 1}, - {&__pyx_n_s_4, __pyx_k_4, sizeof(__pyx_k_4), 0, 0, 1, 1}, - {&__pyx_kp_s_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 0, 1, 0}, - {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, - {&__pyx_kp_u_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 1, 0, 0}, - {&__pyx_n_s__C, __pyx_k__C, sizeof(__pyx_k__C), 0, 0, 1, 1}, - {&__pyx_n_s__DOUBLE, __pyx_k__DOUBLE, sizeof(__pyx_k__DOUBLE), 0, 0, 1, 1}, - {&__pyx_n_s__DTYPE, __pyx_k__DTYPE, sizeof(__pyx_k__DTYPE), 0, 0, 1, 1}, - {&__pyx_n_s__F, __pyx_k__F, sizeof(__pyx_k__F), 0, 0, 1, 1}, - {&__pyx_n_s__MemoryError, __pyx_k__MemoryError, sizeof(__pyx_k__MemoryError), 0, 0, 1, 1}, - {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__T, __pyx_k__T, sizeof(__pyx_k__T), 0, 0, 1, 1}, - {&__pyx_n_s__TREE_LEAF, __pyx_k__TREE_LEAF, sizeof(__pyx_k__TREE_LEAF), 0, 0, 1, 1}, - {&__pyx_n_s__TREE_SPLIT_BEST, __pyx_k__TREE_SPLIT_BEST, sizeof(__pyx_k__TREE_SPLIT_BEST), 0, 0, 1, 1}, - {&__pyx_n_s__TREE_SPLIT_RANDOM, __pyx_k__TREE_SPLIT_RANDOM, sizeof(__pyx_k__TREE_SPLIT_RANDOM), 0, 0, 1, 1}, - {&__pyx_n_s__TREE_UNDEFINED, __pyx_k__TREE_UNDEFINED, sizeof(__pyx_k__TREE_UNDEFINED), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, - {&__pyx_n_s__X_argsorted, __pyx_k__X_argsorted, sizeof(__pyx_k__X_argsorted), 0, 0, 1, 1}, - {&__pyx_n_s____getstate__, __pyx_k____getstate__, sizeof(__pyx_k____getstate__), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s___random_sample_mask, __pyx_k___random_sample_mask, sizeof(__pyx_k___random_sample_mask), 0, 0, 1, 1}, - {&__pyx_n_s__apply, __pyx_k__apply, sizeof(__pyx_k__apply), 0, 0, 1, 1}, - {&__pyx_n_s__arange, __pyx_k__arange, sizeof(__pyx_k__arange), 0, 0, 1, 1}, - {&__pyx_n_s__argsort, __pyx_k__argsort, sizeof(__pyx_k__argsort), 0, 0, 1, 1}, - {&__pyx_n_s__asarray, __pyx_k__asarray, sizeof(__pyx_k__asarray), 0, 0, 1, 1}, - {&__pyx_n_s__asfortranarray, __pyx_k__asfortranarray, sizeof(__pyx_k__asfortranarray), 0, 0, 1, 1}, - {&__pyx_n_s__astype, __pyx_k__astype, sizeof(__pyx_k__astype), 0, 0, 1, 1}, - {&__pyx_n_s__axis, __pyx_k__axis, sizeof(__pyx_k__axis), 0, 0, 1, 1}, - {&__pyx_n_s__best_error, __pyx_k__best_error, sizeof(__pyx_k__best_error), 0, 0, 1, 1}, - {&__pyx_n_s__bool, __pyx_k__bool, sizeof(__pyx_k__bool), 0, 0, 1, 1}, - {&__pyx_n_s__build, __pyx_k__build, sizeof(__pyx_k__build), 0, 0, 1, 1}, - {&__pyx_n_s__capacity, __pyx_k__capacity, sizeof(__pyx_k__capacity), 0, 0, 1, 1}, - {&__pyx_n_s__children_left, __pyx_k__children_left, sizeof(__pyx_k__children_left), 0, 0, 1, 1}, - {&__pyx_n_s__children_right, __pyx_k__children_right, sizeof(__pyx_k__children_right), 0, 0, 1, 1}, - {&__pyx_n_s__contiguous, __pyx_k__contiguous, sizeof(__pyx_k__contiguous), 0, 0, 1, 1}, - {&__pyx_n_s__criterion, __pyx_k__criterion, sizeof(__pyx_k__criterion), 0, 0, 1, 1}, - {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, - {&__pyx_n_s__feature, __pyx_k__feature, sizeof(__pyx_k__feature), 0, 0, 1, 1}, - {&__pyx_n_s__flags, __pyx_k__flags, sizeof(__pyx_k__flags), 0, 0, 1, 1}, - {&__pyx_n_s__float32, __pyx_k__float32, sizeof(__pyx_k__float32), 0, 0, 1, 1}, - {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, - {&__pyx_n_s__gini, __pyx_k__gini, sizeof(__pyx_k__gini), 0, 0, 1, 1}, - {&__pyx_n_s__i, __pyx_k__i, sizeof(__pyx_k__i), 0, 0, 1, 1}, - {&__pyx_n_s__inf, __pyx_k__inf, sizeof(__pyx_k__inf), 0, 0, 1, 1}, - {&__pyx_n_s__init_error, __pyx_k__init_error, sizeof(__pyx_k__init_error), 0, 0, 1, 1}, - {&__pyx_n_s__int32, __pyx_k__int32, sizeof(__pyx_k__int32), 0, 0, 1, 1}, - {&__pyx_n_s__int8, __pyx_k__int8, sizeof(__pyx_k__int8), 0, 0, 1, 1}, - {&__pyx_n_s__isfortran, __pyx_k__isfortran, sizeof(__pyx_k__isfortran), 0, 0, 1, 1}, - {&__pyx_n_s__max, __pyx_k__max, sizeof(__pyx_k__max), 0, 0, 1, 1}, - {&__pyx_n_s__max_depth, __pyx_k__max_depth, sizeof(__pyx_k__max_depth), 0, 0, 1, 1}, - {&__pyx_n_s__max_features, __pyx_k__max_features, sizeof(__pyx_k__max_features), 0, 0, 1, 1}, - {&__pyx_n_s__method, __pyx_k__method, sizeof(__pyx_k__method), 0, 0, 1, 1}, - {&__pyx_n_s__min_density, __pyx_k__min_density, sizeof(__pyx_k__min_density), 0, 0, 1, 1}, - {&__pyx_n_s__min_samples_leaf, __pyx_k__min_samples_leaf, sizeof(__pyx_k__min_samples_leaf), 0, 0, 1, 1}, - {&__pyx_n_s__min_samples_split, __pyx_k__min_samples_split, sizeof(__pyx_k__min_samples_split), 0, 0, 1, 1}, - {&__pyx_n_s__n_bagged, __pyx_k__n_bagged, sizeof(__pyx_k__n_bagged), 0, 0, 1, 1}, - {&__pyx_n_s__n_classes, __pyx_k__n_classes, sizeof(__pyx_k__n_classes), 0, 0, 1, 1}, - {&__pyx_n_s__n_features, __pyx_k__n_features, sizeof(__pyx_k__n_features), 0, 0, 1, 1}, - {&__pyx_n_s__n_outputs, __pyx_k__n_outputs, sizeof(__pyx_k__n_outputs), 0, 0, 1, 1}, - {&__pyx_n_s__n_samples, __pyx_k__n_samples, sizeof(__pyx_k__n_samples), 0, 0, 1, 1}, - {&__pyx_n_s__n_total_in_bag, __pyx_k__n_total_in_bag, sizeof(__pyx_k__n_total_in_bag), 0, 0, 1, 1}, - {&__pyx_n_s__n_total_samples, __pyx_k__n_total_samples, sizeof(__pyx_k__n_total_samples), 0, 0, 1, 1}, - {&__pyx_n_s__node_count, __pyx_k__node_count, sizeof(__pyx_k__node_count), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__ones, __pyx_k__ones, sizeof(__pyx_k__ones), 0, 0, 1, 1}, - {&__pyx_n_s__order, __pyx_k__order, sizeof(__pyx_k__order), 0, 0, 1, 1}, - {&__pyx_n_s__permutation, __pyx_k__permutation, sizeof(__pyx_k__permutation), 0, 0, 1, 1}, - {&__pyx_n_s__predict, __pyx_k__predict, sizeof(__pyx_k__predict), 0, 0, 1, 1}, - {&__pyx_n_s__rand, __pyx_k__rand, sizeof(__pyx_k__rand), 0, 0, 1, 1}, - {&__pyx_n_s__random_state, __pyx_k__random_state, sizeof(__pyx_k__random_state), 0, 0, 1, 1}, - {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__sample_mask, __pyx_k__sample_mask, sizeof(__pyx_k__sample_mask), 0, 0, 1, 1}, - {&__pyx_n_s__squared, __pyx_k__squared, sizeof(__pyx_k__squared), 0, 0, 1, 1}, - {&__pyx_n_s__sum, __pyx_k__sum, sizeof(__pyx_k__sum), 0, 0, 1, 1}, - {&__pyx_n_s__threshold, __pyx_k__threshold, sizeof(__pyx_k__threshold), 0, 0, 1, 1}, - {&__pyx_n_s__value, __pyx_k__value, sizeof(__pyx_k__value), 0, 0, 1, 1}, - {&__pyx_n_s__y, __pyx_k__y, sizeof(__pyx_k__y), 0, 0, 1, 1}, - {&__pyx_n_s__zeros, __pyx_k__zeros, sizeof(__pyx_k__zeros), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_MemoryError = __Pyx_GetName(__pyx_b, __pyx_n_s__MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - return 0; - __pyx_L1_error:; - return -1; -} + /* "sklearn/tree/_tree.pyx":2457 + * # f_j in the interval [n_total_constants, f_i[ + * + * current.feature = features[f_j] # <<<<<<<<<<<<<< + * + * self.extract_nnz(current.feature, + */ + __pyx_v_current.feature = (__pyx_v_features[__pyx_v_f_j]); -static int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + /* "sklearn/tree/_tree.pyx":2459 + * current.feature = features[f_j] + * + * self.extract_nnz(current.feature, # <<<<<<<<<<<<<< + * &end_negative, &start_positive, + * &is_samples_sorted) + */ + __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter_extract_nnz(((struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *)__pyx_v_self), __pyx_v_current.feature, (&__pyx_v_end_negative), (&__pyx_v_start_positive), (&__pyx_v_is_samples_sorted)); - /* "sklearn/tree/_tree.pyx":447 - * # Count samples - * if n_node_samples == 0: - * raise ValueError("Attempting to find a split " # <<<<<<<<<<<<<< - * "with an empty sample_mask") + /* "sklearn/tree/_tree.pyx":2464 * + * # Add one or two zeros in Xf, if there is any + * if end_negative < start_positive: # <<<<<<<<<<<<<< + * start_positive -= 1 + * Xf[start_positive] = 0. */ - __pyx_k_tuple_3 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_3); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_2)); - PyTuple_SET_ITEM(__pyx_k_tuple_3, 0, ((PyObject *)__pyx_kp_s_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_3)); + __pyx_t_6 = ((__pyx_v_end_negative < __pyx_v_start_positive) != 0); + if (__pyx_t_6) { - /* "sklearn/tree/_tree.pyx":894 - * """ - * if method != "gini" and method != "squared": - * raise ValueError( # <<<<<<<<<<<<<< - * 'Invalid value for method. Allowed string ' - * 'values are "gini", or "squared".') - */ - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 894; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_6); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_s_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); - - /* "numpy.pxd":215 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2465 + * # Add one or two zeros in Xf, if there is any + * if end_negative < start_positive: + * start_positive -= 1 # <<<<<<<<<<<<<< + * Xf[start_positive] = 0. * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_8 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_8); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_7)); - PyTuple_SET_ITEM(__pyx_k_tuple_8, 0, ((PyObject *)__pyx_kp_u_7)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_7)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); + __pyx_v_start_positive = (__pyx_v_start_positive - 1); - /* "numpy.pxd":219 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2466 + * if end_negative < start_positive: + * start_positive -= 1 + * Xf[start_positive] = 0. # <<<<<<<<<<<<<< * - * info.buf = PyArray_DATA(self) + * if end_negative != start_positive: */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_10); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_9)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + (__pyx_v_Xf[__pyx_v_start_positive]) = 0.; - /* "numpy.pxd":257 - * if ((descr.byteorder == c'>' and little_endian) or - * (descr.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" + /* "sklearn/tree/_tree.pyx":2468 + * Xf[start_positive] = 0. + * + * if end_negative != start_positive: # <<<<<<<<<<<<<< + * Xf[end_negative] = 0. + * end_negative += 1 */ - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_12); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); - PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + __pyx_t_6 = ((__pyx_v_end_negative != __pyx_v_start_positive) != 0); + if (__pyx_t_6) { - /* "numpy.pxd":799 + /* "sklearn/tree/_tree.pyx":2469 * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * if end_negative != start_positive: + * Xf[end_negative] = 0. # <<<<<<<<<<<<<< + * end_negative += 1 * - * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_15 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_15); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_14)); - PyTuple_SET_ITEM(__pyx_k_tuple_15, 0, ((PyObject *)__pyx_kp_u_14)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_14)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); + (__pyx_v_Xf[__pyx_v_end_negative]) = 0.; - /* "numpy.pxd":803 - * if ((child.byteorder == c'>' and little_endian) or - * (child.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * # One could encode it in the format string and have Cython - * # complain instead, BUT: < and > in format strings also imply + /* "sklearn/tree/_tree.pyx":2470 + * if end_negative != start_positive: + * Xf[end_negative] = 0. + * end_negative += 1 # <<<<<<<<<<<<<< + * + * # Find min, max in Xf[start:end_negative] */ - __pyx_k_tuple_16 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_16); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); - PyTuple_SET_ITEM(__pyx_k_tuple_16, 0, ((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); + __pyx_v_end_negative = (__pyx_v_end_negative + 1); + goto __pyx_L10; + } + __pyx_L10:; + goto __pyx_L9; + } + __pyx_L9:; - /* "numpy.pxd":823 - * t = child.type_num - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2473 + * + * # Find min, max in Xf[start:end_negative] + * min_feature_value = Xf[start] # <<<<<<<<<<<<<< + * max_feature_value = min_feature_value * - * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_18 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_18)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_18); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_17)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 0, ((PyObject *)__pyx_kp_u_17)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_17)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_18)); - - /* "sklearn/tree/_tree.pyx":1621 - * return -1 - * - * def _random_sample_mask(int n_total_samples, int n_total_in_bag, random_state): # <<<<<<<<<<<<<< - * """Create a random sample mask where ``n_total_in_bag`` elements are set. - * - */ - __pyx_k_tuple_19 = PyTuple_New(7); if (unlikely(!__pyx_k_tuple_19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1621; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_19); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_total_samples)); - PyTuple_SET_ITEM(__pyx_k_tuple_19, 0, ((PyObject *)__pyx_n_s__n_total_samples)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_total_samples)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_total_in_bag)); - PyTuple_SET_ITEM(__pyx_k_tuple_19, 1, ((PyObject *)__pyx_n_s__n_total_in_bag)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_total_in_bag)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__random_state)); - PyTuple_SET_ITEM(__pyx_k_tuple_19, 2, ((PyObject *)__pyx_n_s__random_state)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__random_state)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__rand)); - PyTuple_SET_ITEM(__pyx_k_tuple_19, 3, ((PyObject *)__pyx_n_s__rand)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__rand)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__sample_mask)); - PyTuple_SET_ITEM(__pyx_k_tuple_19, 4, ((PyObject *)__pyx_n_s__sample_mask)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__sample_mask)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_bagged)); - PyTuple_SET_ITEM(__pyx_k_tuple_19, 5, ((PyObject *)__pyx_n_s__n_bagged)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_bagged)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__i)); - PyTuple_SET_ITEM(__pyx_k_tuple_19, 6, ((PyObject *)__pyx_n_s__i)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_19)); - __pyx_k_codeobj_20 = (PyObject*)__Pyx_PyCode_New(3, 0, 7, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_19, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_21, __pyx_n_s___random_sample_mask, 1621, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1621; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} + __pyx_v_min_feature_value = (__pyx_v_Xf[__pyx_v_start]); -static int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_neg_2 = PyInt_FromLong(-2); if (unlikely(!__pyx_int_neg_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - return 0; - __pyx_L1_error:; - return -1; -} + /* "sklearn/tree/_tree.pyx":2474 + * # Find min, max in Xf[start:end_negative] + * min_feature_value = Xf[start] + * max_feature_value = min_feature_value # <<<<<<<<<<<<<< + * + * for p in range(start, end_negative): + */ + __pyx_v_max_feature_value = __pyx_v_min_feature_value; -#if PY_MAJOR_VERSION < 3 -PyMODINIT_FUNC init_tree(void); /*proto*/ -PyMODINIT_FUNC init_tree(void) -#else -PyMODINIT_FUNC PyInit__tree(void); /*proto*/ -PyMODINIT_FUNC PyInit__tree(void) -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - double __pyx_t_3; - int __pyx_t_4; - __Pyx_RefNannyDeclarations - #if CYTHON_REFNANNY - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); - if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); - } - #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__tree(void)", 0); - if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __Pyx_CyFunction_USED - if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #endif - /*--- Module creation code ---*/ - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_tree"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #if CYTHON_COMPILING_IN_PYPY - Py_INCREF(__pyx_b); - #endif - if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - /*--- Initialize various global constants etc. ---*/ - if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_module_is_main_sklearn__tree___tree) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - } - /*--- Builtin init code ---*/ - if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Constants init code ---*/ - if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Global init code ---*/ - /*--- Variable export code ---*/ - /*--- Function export code ---*/ - /*--- Type init code ---*/ - __pyx_vtabptr_7sklearn_4tree_5_tree_Criterion = &__pyx_vtable_7sklearn_4tree_5_tree_Criterion; - __pyx_vtable_7sklearn_4tree_5_tree_Criterion.init = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int))__pyx_f_7sklearn_4tree_5_tree_9Criterion_init; - __pyx_vtable_7sklearn_4tree_5_tree_Criterion.reset = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_9Criterion_reset; - __pyx_vtable_7sklearn_4tree_5_tree_Criterion.update = (int (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, int, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, int *, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *))__pyx_f_7sklearn_4tree_5_tree_9Criterion_update; - __pyx_vtable_7sklearn_4tree_5_tree_Criterion.eval = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_9Criterion_eval; - __pyx_vtable_7sklearn_4tree_5_tree_Criterion.init_value = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *))__pyx_f_7sklearn_4tree_5_tree_9Criterion_init_value; - if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_Criterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 933; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_Criterion.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_Criterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 933; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "Criterion", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_Criterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 933; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_4tree_5_tree_Criterion = &__pyx_type_7sklearn_4tree_5_tree_Criterion; - __pyx_vtabptr_7sklearn_4tree_5_tree_Tree = &__pyx_vtable_7sklearn_4tree_5_tree_Tree; - __pyx_vtable_7sklearn_4tree_5_tree_Tree.resize = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_resize *__pyx_optional_args))__pyx_f_7sklearn_4tree_5_tree_4Tree_resize; - __pyx_vtable_7sklearn_4tree_5_tree_Tree.build = (PyObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_build *__pyx_optional_args))__pyx_f_7sklearn_4tree_5_tree_4Tree_build; - __pyx_vtable_7sklearn_4tree_5_tree_Tree.recursive_partition = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, int, int, int, int, double *))__pyx_f_7sklearn_4tree_5_tree_4Tree_recursive_partition; - __pyx_vtable_7sklearn_4tree_5_tree_Tree.add_split_node = (int (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int, int, int, double, double *, double, double, int))__pyx_f_7sklearn_4tree_5_tree_4Tree_add_split_node; - __pyx_vtable_7sklearn_4tree_5_tree_Tree.add_leaf = (int (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int, int, double *, double, int))__pyx_f_7sklearn_4tree_5_tree_4Tree_add_leaf; - __pyx_vtable_7sklearn_4tree_5_tree_Tree.find_split = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, int, int *, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int, int *, double *, double *, double *))__pyx_f_7sklearn_4tree_5_tree_4Tree_find_split; - __pyx_vtable_7sklearn_4tree_5_tree_Tree.find_best_split = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, int, int *, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int, int *, double *, double *, double *))__pyx_f_7sklearn_4tree_5_tree_4Tree_find_best_split; - __pyx_vtable_7sklearn_4tree_5_tree_Tree.find_random_split = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *, int, int *, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int, int *, double *, double *, double *))__pyx_f_7sklearn_4tree_5_tree_4Tree_find_random_split; - __pyx_vtable_7sklearn_4tree_5_tree_Tree.predict = (PyObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, int __pyx_skip_dispatch))__pyx_f_7sklearn_4tree_5_tree_4Tree_predict; - __pyx_vtable_7sklearn_4tree_5_tree_Tree.apply = (PyObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyArrayObject *, int __pyx_skip_dispatch))__pyx_f_7sklearn_4tree_5_tree_4Tree_apply; - __pyx_vtable_7sklearn_4tree_5_tree_Tree.compute_feature_importances = (PyObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances *__pyx_optional_args))__pyx_f_7sklearn_4tree_5_tree_4Tree_compute_feature_importances; - __pyx_vtable_7sklearn_4tree_5_tree_Tree._compute_feature_importances_gini = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int))__pyx_f_7sklearn_4tree_5_tree_4Tree__compute_feature_importances_gini; - __pyx_vtable_7sklearn_4tree_5_tree_Tree._compute_feature_importances_squared = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int))__pyx_f_7sklearn_4tree_5_tree_4Tree__compute_feature_importances_squared; - if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_Tree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_Tree.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_Tree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "Tree", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_Tree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_4tree_5_tree_Tree = &__pyx_type_7sklearn_4tree_5_tree_Tree; - __pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion = &__pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion; - __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_Criterion; - __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base.init = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int))__pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_init; - __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base.reset = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_reset; - __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base.update = (int (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, int, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, int *, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *))__pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_update; - __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base.eval = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_eval; - __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base.init_value = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *))__pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_init_value; - __pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_Criterion; - if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 961; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 961; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "ClassificationCriterion", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 961; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion = &__pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion; - __pyx_vtabptr_7sklearn_4tree_5_tree_Gini = &__pyx_vtable_7sklearn_4tree_5_tree_Gini; - __pyx_vtable_7sklearn_4tree_5_tree_Gini.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion; - __pyx_vtable_7sklearn_4tree_5_tree_Gini.__pyx_base.__pyx_base.eval = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_4Gini_eval; - __pyx_type_7sklearn_4tree_5_tree_Gini.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion; - if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_Gini) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_Gini.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_Gini) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "Gini", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_Gini) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_4tree_5_tree_Gini = &__pyx_type_7sklearn_4tree_5_tree_Gini; - __pyx_vtabptr_7sklearn_4tree_5_tree_Entropy = &__pyx_vtable_7sklearn_4tree_5_tree_Entropy; - __pyx_vtable_7sklearn_4tree_5_tree_Entropy.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion; - __pyx_vtable_7sklearn_4tree_5_tree_Entropy.__pyx_base.__pyx_base.eval = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_7Entropy_eval; - __pyx_type_7sklearn_4tree_5_tree_Entropy.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion; - if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_Entropy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_Entropy.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_Entropy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "Entropy", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_Entropy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_4tree_5_tree_Entropy = &__pyx_type_7sklearn_4tree_5_tree_Entropy; - __pyx_vtabptr_7sklearn_4tree_5_tree_RegressionCriterion = &__pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion; - __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_Criterion; - __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base.init = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *, int, int))__pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_init; - __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base.reset = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_reset; - __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base.update = (int (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, int, int, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, int, int *, __pyx_t_7sklearn_4tree_5_tree_BOOL_t *))__pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_update; - __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base.eval = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_eval; - __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base.init_value = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *))__pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_init_value; - __pyx_type_7sklearn_4tree_5_tree_RegressionCriterion.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_Criterion; - if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_RegressionCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_RegressionCriterion.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_RegressionCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "RegressionCriterion", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_RegressionCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_4tree_5_tree_RegressionCriterion = &__pyx_type_7sklearn_4tree_5_tree_RegressionCriterion; - __pyx_vtabptr_7sklearn_4tree_5_tree_MSE = &__pyx_vtable_7sklearn_4tree_5_tree_MSE; - __pyx_vtable_7sklearn_4tree_5_tree_MSE.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_RegressionCriterion; - __pyx_vtable_7sklearn_4tree_5_tree_MSE.__pyx_base.__pyx_base.eval = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_3MSE_eval; - __pyx_type_7sklearn_4tree_5_tree_MSE.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_RegressionCriterion; - if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_MSE) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1547; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_MSE.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_MSE) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1547; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "MSE", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_MSE) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1547; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7sklearn_4tree_5_tree_MSE = &__pyx_type_7sklearn_4tree_5_tree_MSE; - /*--- Type import code ---*/ - __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", - #if CYTHON_COMPILING_IN_PYPY - sizeof(PyTypeObject), - #else - sizeof(PyHeapTypeObject), - #endif - 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Variable import code ---*/ - /*--- Function import code ---*/ - /*--- Execution code ---*/ + /* "sklearn/tree/_tree.pyx":2476 + * max_feature_value = min_feature_value + * + * for p in range(start, end_negative): # <<<<<<<<<<<<<< + * current_feature_value = Xf[p] + * + */ + __pyx_t_2 = __pyx_v_end_negative; + for (__pyx_t_8 = __pyx_v_start; __pyx_t_8 < __pyx_t_2; __pyx_t_8+=1) { + __pyx_v_p = __pyx_t_8; - /* "sklearn/tree/_tree.pyx":17 - * cimport cython + /* "sklearn/tree/_tree.pyx":2477 * - * import numpy as np # <<<<<<<<<<<<<< - * cimport numpy as np - * np.import_array() + * for p in range(start, end_negative): + * current_feature_value = Xf[p] # <<<<<<<<<<<<<< + * + * if current_feature_value < min_feature_value: */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_current_feature_value = (__pyx_v_Xf[__pyx_v_p]); - /* "sklearn/tree/_tree.pyx":19 - * import numpy as np - * cimport numpy as np - * np.import_array() # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2479 + * current_feature_value = Xf[p] * - * cdef extern from "stdlib.h": + * if current_feature_value < min_feature_value: # <<<<<<<<<<<<<< + * min_feature_value = current_feature_value + * elif current_feature_value > max_feature_value: */ - import_array(); + __pyx_t_6 = ((__pyx_v_current_feature_value < __pyx_v_min_feature_value) != 0); + if (__pyx_t_6) { - /* "sklearn/tree/_tree.pyx":43 + /* "sklearn/tree/_tree.pyx":2480 * - * # Dtype - * DTYPE = np.float32 # <<<<<<<<<<<<<< - * DOUBLE = np.float64 - * # ctypedef np.float32_t DTYPE_t + * if current_feature_value < min_feature_value: + * min_feature_value = current_feature_value # <<<<<<<<<<<<<< + * elif current_feature_value > max_feature_value: + * max_feature_value = current_feature_value */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__float32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__DTYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_min_feature_value = __pyx_v_current_feature_value; + goto __pyx_L13; + } - /* "sklearn/tree/_tree.pyx":44 - * # Dtype - * DTYPE = np.float32 - * DOUBLE = np.float64 # <<<<<<<<<<<<<< - * # ctypedef np.float32_t DTYPE_t - * # ctypedef np.float64_t DOUBLE_t + /* "sklearn/tree/_tree.pyx":2481 + * if current_feature_value < min_feature_value: + * min_feature_value = current_feature_value + * elif current_feature_value > max_feature_value: # <<<<<<<<<<<<<< + * max_feature_value = current_feature_value + * */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__DOUBLE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_6 = ((__pyx_v_current_feature_value > __pyx_v_max_feature_value) != 0); + if (__pyx_t_6) { - /* "sklearn/tree/_tree.pyx":50 + /* "sklearn/tree/_tree.pyx":2482 + * min_feature_value = current_feature_value + * elif current_feature_value > max_feature_value: + * max_feature_value = current_feature_value # <<<<<<<<<<<<<< * - * # Constants - * cdef double INFINITY = np.inf # <<<<<<<<<<<<<< + * # Update min, max given Xf[start_positive:end] + */ + __pyx_v_max_feature_value = __pyx_v_current_feature_value; + goto __pyx_L13; + } + __pyx_L13:; + } + + /* "sklearn/tree/_tree.pyx":2485 + * + * # Update min, max given Xf[start_positive:end] + * for p in range(start_positive, end): # <<<<<<<<<<<<<< + * current_feature_value = Xf[p] * - * TREE_LEAF = -1 */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_3 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_7sklearn_4tree_5_tree_INFINITY = __pyx_t_3; + __pyx_t_2 = __pyx_v_end; + for (__pyx_t_8 = __pyx_v_start_positive; __pyx_t_8 < __pyx_t_2; __pyx_t_8+=1) { + __pyx_v_p = __pyx_t_8; - /* "sklearn/tree/_tree.pyx":52 - * cdef double INFINITY = np.inf + /* "sklearn/tree/_tree.pyx":2486 + * # Update min, max given Xf[start_positive:end] + * for p in range(start_positive, end): + * current_feature_value = Xf[p] # <<<<<<<<<<<<<< * - * TREE_LEAF = -1 # <<<<<<<<<<<<<< - * TREE_UNDEFINED = -2 - * cdef int _TREE_LEAF = TREE_LEAF + * if current_feature_value < min_feature_value: */ - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__TREE_LEAF, __pyx_int_neg_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_current_feature_value = (__pyx_v_Xf[__pyx_v_p]); - /* "sklearn/tree/_tree.pyx":53 + /* "sklearn/tree/_tree.pyx":2488 + * current_feature_value = Xf[p] * - * TREE_LEAF = -1 - * TREE_UNDEFINED = -2 # <<<<<<<<<<<<<< - * cdef int _TREE_LEAF = TREE_LEAF - * cdef int _TREE_UNDEFINED = TREE_UNDEFINED + * if current_feature_value < min_feature_value: # <<<<<<<<<<<<<< + * min_feature_value = current_feature_value + * elif current_feature_value > max_feature_value: */ - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__TREE_UNDEFINED, __pyx_int_neg_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((__pyx_v_current_feature_value < __pyx_v_min_feature_value) != 0); + if (__pyx_t_6) { - /* "sklearn/tree/_tree.pyx":54 - * TREE_LEAF = -1 - * TREE_UNDEFINED = -2 - * cdef int _TREE_LEAF = TREE_LEAF # <<<<<<<<<<<<<< - * cdef int _TREE_UNDEFINED = TREE_UNDEFINED + /* "sklearn/tree/_tree.pyx":2489 * + * if current_feature_value < min_feature_value: + * min_feature_value = current_feature_value # <<<<<<<<<<<<<< + * elif current_feature_value > max_feature_value: + * max_feature_value = current_feature_value */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__TREE_LEAF); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyInt_AsInt(__pyx_t_2); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF = __pyx_t_4; + __pyx_v_min_feature_value = __pyx_v_current_feature_value; + goto __pyx_L16; + } - /* "sklearn/tree/_tree.pyx":55 - * TREE_UNDEFINED = -2 - * cdef int _TREE_LEAF = TREE_LEAF - * cdef int _TREE_UNDEFINED = TREE_UNDEFINED # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2490 + * if current_feature_value < min_feature_value: + * min_feature_value = current_feature_value + * elif current_feature_value > max_feature_value: # <<<<<<<<<<<<<< + * max_feature_value = current_feature_value * - * TREE_SPLIT_BEST = 1 */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__TREE_UNDEFINED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyInt_AsInt(__pyx_t_2); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_7sklearn_4tree_5_tree__TREE_UNDEFINED = __pyx_t_4; + __pyx_t_6 = ((__pyx_v_current_feature_value > __pyx_v_max_feature_value) != 0); + if (__pyx_t_6) { - /* "sklearn/tree/_tree.pyx":57 - * cdef int _TREE_UNDEFINED = TREE_UNDEFINED + /* "sklearn/tree/_tree.pyx":2491 + * min_feature_value = current_feature_value + * elif current_feature_value > max_feature_value: + * max_feature_value = current_feature_value # <<<<<<<<<<<<<< + * + * if max_feature_value <= min_feature_value + FEATURE_THRESHOLD: + */ + __pyx_v_max_feature_value = __pyx_v_current_feature_value; + goto __pyx_L16; + } + __pyx_L16:; + } + + /* "sklearn/tree/_tree.pyx":2493 + * max_feature_value = current_feature_value * - * TREE_SPLIT_BEST = 1 # <<<<<<<<<<<<<< - * TREE_SPLIT_RANDOM = 2 - * cdef int _TREE_SPLIT_BEST = TREE_SPLIT_BEST + * if max_feature_value <= min_feature_value + FEATURE_THRESHOLD: # <<<<<<<<<<<<<< + * features[f_j] = features[n_total_constants] + * features[n_total_constants] = current.feature */ - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__TREE_SPLIT_BEST, __pyx_int_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((__pyx_v_max_feature_value <= (__pyx_v_min_feature_value + __pyx_v_7sklearn_4tree_5_tree_FEATURE_THRESHOLD)) != 0); + if (__pyx_t_6) { - /* "sklearn/tree/_tree.pyx":58 + /* "sklearn/tree/_tree.pyx":2494 + * + * if max_feature_value <= min_feature_value + FEATURE_THRESHOLD: + * features[f_j] = features[n_total_constants] # <<<<<<<<<<<<<< + * features[n_total_constants] = current.feature * - * TREE_SPLIT_BEST = 1 - * TREE_SPLIT_RANDOM = 2 # <<<<<<<<<<<<<< - * cdef int _TREE_SPLIT_BEST = TREE_SPLIT_BEST - * cdef int _TREE_SPLIT_RANDOM = TREE_SPLIT_RANDOM */ - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__TREE_SPLIT_RANDOM, __pyx_int_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + (__pyx_v_features[__pyx_v_f_j]) = (__pyx_v_features[__pyx_v_n_total_constants]); - /* "sklearn/tree/_tree.pyx":59 - * TREE_SPLIT_BEST = 1 - * TREE_SPLIT_RANDOM = 2 - * cdef int _TREE_SPLIT_BEST = TREE_SPLIT_BEST # <<<<<<<<<<<<<< - * cdef int _TREE_SPLIT_RANDOM = TREE_SPLIT_RANDOM + /* "sklearn/tree/_tree.pyx":2495 + * if max_feature_value <= min_feature_value + FEATURE_THRESHOLD: + * features[f_j] = features[n_total_constants] + * features[n_total_constants] = current.feature # <<<<<<<<<<<<<< * + * n_found_constants += 1 */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__TREE_SPLIT_BEST); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyInt_AsInt(__pyx_t_2); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_7sklearn_4tree_5_tree__TREE_SPLIT_BEST = __pyx_t_4; + __pyx_t_2 = __pyx_v_current.feature; + (__pyx_v_features[__pyx_v_n_total_constants]) = __pyx_t_2; - /* "sklearn/tree/_tree.pyx":60 - * TREE_SPLIT_RANDOM = 2 - * cdef int _TREE_SPLIT_BEST = TREE_SPLIT_BEST - * cdef int _TREE_SPLIT_RANDOM = TREE_SPLIT_RANDOM # <<<<<<<<<<<<<< + /* "sklearn/tree/_tree.pyx":2497 + * features[n_total_constants] = current.feature * + * n_found_constants += 1 # <<<<<<<<<<<<<< + * n_total_constants += 1 * */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__TREE_SPLIT_RANDOM); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyInt_AsInt(__pyx_t_2); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_7sklearn_4tree_5_tree__TREE_SPLIT_RANDOM = __pyx_t_4; + __pyx_v_n_found_constants = (__pyx_v_n_found_constants + 1); - /* "sklearn/tree/_tree.pyx":1621 - * return -1 + /* "sklearn/tree/_tree.pyx":2498 * - * def _random_sample_mask(int n_total_samples, int n_total_in_bag, random_state): # <<<<<<<<<<<<<< - * """Create a random sample mask where ``n_total_in_bag`` elements are set. + * n_found_constants += 1 + * n_total_constants += 1 # <<<<<<<<<<<<<< * + * else: */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_4tree_5_tree_1_random_sample_mask, NULL, __pyx_n_s_22); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1621; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___random_sample_mask, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1621; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_n_total_constants = (__pyx_v_n_total_constants + 1); + goto __pyx_L17; + } + /*else*/ { - /* "sklearn/tree/_tree.pyx":1 - * # encoding: utf-8 # <<<<<<<<<<<<<< - * # cython: cdivision=True - * # cython: boundscheck=False + /* "sklearn/tree/_tree.pyx":2501 + * + * else: + * f_i -= 1 # <<<<<<<<<<<<<< + * features[f_i], features[f_j] = features[f_j], features[f_i] + * */ - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_v_f_i = (__pyx_v_f_i - 1); - /* "numpy.pxd":975 - * arr.base = baseptr + /* "sklearn/tree/_tree.pyx":2502 + * else: + * f_i -= 1 + * features[f_i], features[f_j] = features[f_j], features[f_i] # <<<<<<<<<<<<<< * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * if arr.base is NULL: - * return None + * # Draw a random threshold */ - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - if (__pyx_m) { - __Pyx_AddTraceback("init sklearn.tree._tree", __pyx_clineno, __pyx_lineno, __pyx_filename); - Py_DECREF(__pyx_m); __pyx_m = 0; - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init sklearn.tree._tree"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if PY_MAJOR_VERSION < 3 - return; - #else - return __pyx_m; - #endif -} + __pyx_t_2 = (__pyx_v_features[__pyx_v_f_j]); + __pyx_t_8 = (__pyx_v_features[__pyx_v_f_i]); + (__pyx_v_features[__pyx_v_f_i]) = __pyx_t_2; + (__pyx_v_features[__pyx_v_f_j]) = __pyx_t_8; -/* Runtime support code */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule((char *)modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif /* CYTHON_REFNANNY */ + /* "sklearn/tree/_tree.pyx":2505 + * + * # Draw a random threshold + * current.threshold = rand_uniform(min_feature_value, # <<<<<<<<<<<<<< + * max_feature_value, + * random_state) + */ + __pyx_v_current.threshold = __pyx_f_7sklearn_4tree_5_tree_rand_uniform(__pyx_v_min_feature_value, __pyx_v_max_feature_value, __pyx_v_random_state); -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } + /* "sklearn/tree/_tree.pyx":2509 + * random_state) + * + * if current.threshold == max_feature_value: # <<<<<<<<<<<<<< + * current.threshold = min_feature_value + * + */ + __pyx_t_6 = ((__pyx_v_current.threshold == __pyx_v_max_feature_value) != 0); + if (__pyx_t_6) { + + /* "sklearn/tree/_tree.pyx":2510 + * + * if current.threshold == max_feature_value: + * current.threshold = min_feature_value # <<<<<<<<<<<<<< + * + * # Partition + */ + __pyx_v_current.threshold = __pyx_v_min_feature_value; + goto __pyx_L18; + } + __pyx_L18:; + + /* "sklearn/tree/_tree.pyx":2513 + * + * # Partition + * current.pos = self._partition(current.threshold, # <<<<<<<<<<<<<< + * end_negative, + * start_positive, + */ + __pyx_v_current.pos = __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter__partition(((struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *)__pyx_v_self), __pyx_v_current.threshold, __pyx_v_end_negative, __pyx_v_start_positive, (__pyx_v_start_positive + ((__pyx_v_Xf[__pyx_v_start_positive]) == 0.))); + + /* "sklearn/tree/_tree.pyx":2520 + * + * # Reject if min_samples_leaf is not guaranteed + * if (((current.pos - start) < min_samples_leaf) or # <<<<<<<<<<<<<< + * ((end - current.pos) < min_samples_leaf)): + * continue + */ + __pyx_t_7 = (((__pyx_v_current.pos - __pyx_v_start) < __pyx_v_min_samples_leaf) != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L20_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":2521 + * # Reject if min_samples_leaf is not guaranteed + * if (((current.pos - start) < min_samples_leaf) or + * ((end - current.pos) < min_samples_leaf)): # <<<<<<<<<<<<<< + * continue + * + */ + __pyx_t_7 = (((__pyx_v_end - __pyx_v_current.pos) < __pyx_v_min_samples_leaf) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L20_bool_binop_done:; + if (__pyx_t_6) { + + /* "sklearn/tree/_tree.pyx":2522 + * if (((current.pos - start) < min_samples_leaf) or + * ((end - current.pos) < min_samples_leaf)): + * continue # <<<<<<<<<<<<<< + * + * # Evaluate split + */ + goto __pyx_L3_continue; + } + + /* "sklearn/tree/_tree.pyx":2525 + * + * # Evaluate split + * self.criterion.reset() # <<<<<<<<<<<<<< + * self.criterion.update(current.pos) + * + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->reset(__pyx_v_self->__pyx_base.__pyx_base.criterion); + + /* "sklearn/tree/_tree.pyx":2526 + * # Evaluate split + * self.criterion.reset() + * self.criterion.update(current.pos) # <<<<<<<<<<<<<< + * + * # Reject if min_weight_leaf is not satisfied + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->update(__pyx_v_self->__pyx_base.__pyx_base.criterion, __pyx_v_current.pos); + + /* "sklearn/tree/_tree.pyx":2529 + * + * # Reject if min_weight_leaf is not satisfied + * if ((self.criterion.weighted_n_left < min_weight_leaf) or # <<<<<<<<<<<<<< + * (self.criterion.weighted_n_right < min_weight_leaf)): + * continue + */ + __pyx_t_7 = ((__pyx_v_self->__pyx_base.__pyx_base.criterion->weighted_n_left < __pyx_v_min_weight_leaf) != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L23_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":2530 + * # Reject if min_weight_leaf is not satisfied + * if ((self.criterion.weighted_n_left < min_weight_leaf) or + * (self.criterion.weighted_n_right < min_weight_leaf)): # <<<<<<<<<<<<<< + * continue + * + */ + __pyx_t_7 = ((__pyx_v_self->__pyx_base.__pyx_base.criterion->weighted_n_right < __pyx_v_min_weight_leaf) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L23_bool_binop_done:; + if (__pyx_t_6) { + + /* "sklearn/tree/_tree.pyx":2531 + * if ((self.criterion.weighted_n_left < min_weight_leaf) or + * (self.criterion.weighted_n_right < min_weight_leaf)): + * continue # <<<<<<<<<<<<<< + * + * current.improvement = self.criterion.impurity_improvement(impurity) + */ + goto __pyx_L3_continue; + } + + /* "sklearn/tree/_tree.pyx":2533 + * continue + * + * current.improvement = self.criterion.impurity_improvement(impurity) # <<<<<<<<<<<<<< + * + * if current.improvement > best.improvement: + */ + __pyx_v_current.improvement = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->impurity_improvement(__pyx_v_self->__pyx_base.__pyx_base.criterion, __pyx_v_impurity); + + /* "sklearn/tree/_tree.pyx":2535 + * current.improvement = self.criterion.impurity_improvement(impurity) + * + * if current.improvement > best.improvement: # <<<<<<<<<<<<<< + * self.criterion.children_impurity(¤t.impurity_left, + * ¤t.impurity_right) + */ + __pyx_t_6 = ((__pyx_v_current.improvement > __pyx_v_best.improvement) != 0); + if (__pyx_t_6) { + + /* "sklearn/tree/_tree.pyx":2536 + * + * if current.improvement > best.improvement: + * self.criterion.children_impurity(¤t.impurity_left, # <<<<<<<<<<<<<< + * ¤t.impurity_right) + * best = current + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion *)__pyx_v_self->__pyx_base.__pyx_base.criterion->__pyx_vtab)->children_impurity(__pyx_v_self->__pyx_base.__pyx_base.criterion, (&__pyx_v_current.impurity_left), (&__pyx_v_current.impurity_right)); + + /* "sklearn/tree/_tree.pyx":2538 + * self.criterion.children_impurity(¤t.impurity_left, + * ¤t.impurity_right) + * best = current # <<<<<<<<<<<<<< + * + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + */ + __pyx_v_best = __pyx_v_current; + goto __pyx_L25; + } + __pyx_L25:; + } + __pyx_L17:; + } + __pyx_L8:; + __pyx_L3_continue:; + } + + /* "sklearn/tree/_tree.pyx":2541 + * + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + * if best.pos < end and current.feature != best.feature: # <<<<<<<<<<<<<< + * self.extract_nnz(best.feature, &end_negative, &start_positive, + * &is_samples_sorted) + */ + __pyx_t_7 = ((__pyx_v_best.pos < __pyx_v_end) != 0); + if (__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L27_bool_binop_done; + } + __pyx_t_7 = ((__pyx_v_current.feature != __pyx_v_best.feature) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L27_bool_binop_done:; + if (__pyx_t_6) { + + /* "sklearn/tree/_tree.pyx":2542 + * # Reorganize into samples[start:best.pos] + samples[best.pos:end] + * if best.pos < end and current.feature != best.feature: + * self.extract_nnz(best.feature, &end_negative, &start_positive, # <<<<<<<<<<<<<< + * &is_samples_sorted) + * + */ + __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter_extract_nnz(((struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *)__pyx_v_self), __pyx_v_best.feature, (&__pyx_v_end_negative), (&__pyx_v_start_positive), (&__pyx_v_is_samples_sorted)); + + /* "sklearn/tree/_tree.pyx":2545 + * &is_samples_sorted) + * + * self._partition(best.threshold, end_negative, start_positive, # <<<<<<<<<<<<<< + * best.pos) + * + */ + __pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter__partition(((struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *)__pyx_v_self), __pyx_v_best.threshold, __pyx_v_end_negative, __pyx_v_start_positive, __pyx_v_best.pos); + goto __pyx_L26; + } + __pyx_L26:; + + /* "sklearn/tree/_tree.pyx":2551 + * # element in features[:n_known_constants] must be preserved for sibling + * # and child nodes + * memcpy(features, constant_features, sizeof(SIZE_t) * n_known_constants) # <<<<<<<<<<<<<< + * + * # Copy newly found constant features + */ + memcpy(__pyx_v_features, __pyx_v_constant_features, ((sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)) * __pyx_v_n_known_constants)); + + /* "sklearn/tree/_tree.pyx":2554 + * + * # Copy newly found constant features + * memcpy(constant_features + n_known_constants, # <<<<<<<<<<<<<< + * features + n_known_constants, + * sizeof(SIZE_t) * n_found_constants) + */ + memcpy((__pyx_v_constant_features + __pyx_v_n_known_constants), (__pyx_v_features + __pyx_v_n_known_constants), ((sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)) * __pyx_v_n_found_constants)); + + /* "sklearn/tree/_tree.pyx":2559 + * + * # Return values + * split[0] = best # <<<<<<<<<<<<<< + * n_constant_features[0] = n_total_constants + * + */ + (__pyx_v_split[0]) = __pyx_v_best; + + /* "sklearn/tree/_tree.pyx":2560 + * # Return values + * split[0] = best + * n_constant_features[0] = n_total_constants # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_n_constant_features[0]) = __pyx_v_n_total_constants; + + /* "sklearn/tree/_tree.pyx":2358 + * self.random_state), self.__getstate__()) + * + * cdef void node_split(self, double impurity, SplitRecord* split, # <<<<<<<<<<<<<< + * SIZE_t* n_constant_features) nogil: + * """Find a random split on node samples[start:end], using sparse + */ + + /* function exit code */ +} + +/* "sklearn/tree/_tree.pyx":2569 + * """Interface for different tree building strategies. """ + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_11TreeBuilder_1build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyObject *__pyx_f_7sklearn_4tree_5_tree_11TreeBuilder_build(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *__pyx_v_self, CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, CYTHON_UNUSED PyObject *__pyx_v_X, CYTHON_UNUSED PyArrayObject *__pyx_v_y, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build *__pyx_optional_args) { + + /* "sklearn/tree/_tree.pyx":2570 + * + * cpdef build(self, Tree tree, object X, np.ndarray y, + * np.ndarray sample_weight=None): # <<<<<<<<<<<<<< + * """Build a decision tree from the training set (X, y).""" + * pass + */ + PyArrayObject *__pyx_v_sample_weight = ((PyArrayObject *)Py_None); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("build", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_sample_weight = __pyx_optional_args->sample_weight; + } + } + + /* "sklearn/tree/_tree.pyx":2569 + * """Interface for different tree building strategies. """ + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + /* Check if called by wrapper */ + if (unlikely(__pyx_skip_dispatch)) ; + /* Check if overridden in Python */ + else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_build); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_11TreeBuilder_1build)) { + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_3 = __pyx_t_1; __pyx_t_4 = NULL; + __pyx_t_5 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_5 = 1; + } + } + __pyx_t_6 = PyTuple_New(4+__pyx_t_5); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (__pyx_t_4) { + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + } + __Pyx_INCREF(((PyObject *)__pyx_v_tree)); + PyTuple_SET_ITEM(__pyx_t_6, 0+__pyx_t_5, ((PyObject *)__pyx_v_tree)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_tree)); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_6, 1+__pyx_t_5, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __Pyx_INCREF(((PyObject *)__pyx_v_y)); + PyTuple_SET_ITEM(__pyx_t_6, 2+__pyx_t_5, ((PyObject *)__pyx_v_y)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); + __Pyx_INCREF(((PyObject *)__pyx_v_sample_weight)); + PyTuple_SET_ITEM(__pyx_t_6, 3+__pyx_t_5, ((PyObject *)__pyx_v_sample_weight)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_sample_weight)); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "sklearn/tree/_tree.pyx":2571 + * cpdef build(self, Tree tree, object X, np.ndarray y, + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" # <<<<<<<<<<<<<< + * pass + * + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("sklearn.tree._tree.TreeBuilder.build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":2569 + * """Interface for different tree building strategies. """ + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_11TreeBuilder_1build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_4tree_5_tree_11TreeBuilder_build[] = "Build a decision tree from the training set (X, y)."; +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_11TreeBuilder_1build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree = 0; + PyObject *__pyx_v_X = 0; + PyArrayObject *__pyx_v_y = 0; + PyArrayObject *__pyx_v_sample_weight = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("build (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_tree,&__pyx_n_s_X,&__pyx_n_s_y,&__pyx_n_s_sample_weight,0}; + PyObject* values[4] = {0,0,0,0}; + + /* "sklearn/tree/_tree.pyx":2570 + * + * cpdef build(self, Tree tree, object X, np.ndarray y, + * np.ndarray sample_weight=None): # <<<<<<<<<<<<<< + * """Build a decision tree from the training set (X, y).""" + * pass + */ + values[3] = (PyObject *)((PyArrayObject *)Py_None); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tree)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build", 0, 3, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2569; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build", 0, 3, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2569; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sample_weight); + if (value) { values[3] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "build") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2569; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_tree = ((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)values[0]); + __pyx_v_X = values[1]; + __pyx_v_y = ((PyArrayObject *)values[2]); + __pyx_v_sample_weight = ((PyArrayObject *)values[3]); + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("build", 0, 3, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2569; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._tree.TreeBuilder.build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_tree), __pyx_ptype_7sklearn_4tree_5_tree_Tree, 1, "tree", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_11TreeBuilder_build(((struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *)__pyx_v_self), __pyx_v_tree, __pyx_v_X, __pyx_v_y, __pyx_v_sample_weight); + + /* "sklearn/tree/_tree.pyx":2569 + * """Interface for different tree building strategies. """ + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_11TreeBuilder_build(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_weight) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("build", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_2.__pyx_n = 1; + __pyx_t_2.sample_weight = __pyx_v_sample_weight; + __pyx_t_1 = __pyx_vtabptr_7sklearn_4tree_5_tree_TreeBuilder->build(__pyx_v_self, __pyx_v_tree, __pyx_v_X, __pyx_v_y, 1, &__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.TreeBuilder.build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":2574 + * pass + * + * cdef inline _check_input(self, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight): + * """Check input dtype, layout and format""" + */ + +static PyObject *__pyx_f_7sklearn_4tree_5_tree_11TreeBuilder__check_input(CYTHON_UNUSED struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *__pyx_v_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_weight) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_check_input", 0); + __Pyx_INCREF(__pyx_v_X); + __Pyx_INCREF((PyObject *)__pyx_v_y); + __Pyx_INCREF((PyObject *)__pyx_v_sample_weight); + + /* "sklearn/tree/_tree.pyx":2577 + * np.ndarray sample_weight): + * """Check input dtype, layout and format""" + * if issparse(X): # <<<<<<<<<<<<<< + * X = X.tocsc() + * X.sort_indices() + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_issparse); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2577; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (!__pyx_t_3) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_X); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2577; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2577; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2577; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2577; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_5) { + + /* "sklearn/tree/_tree.pyx":2578 + * """Check input dtype, layout and format""" + * if issparse(X): + * X = X.tocsc() # <<<<<<<<<<<<<< + * X.sort_indices() + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_tocsc); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2578; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (__pyx_t_4) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2578; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2578; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":2579 + * if issparse(X): + * X = X.tocsc() + * X.sort_indices() # <<<<<<<<<<<<<< + * + * if X.data.dtype != DTYPE: + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_sort_indices); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (__pyx_t_4) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":2581 + * X.sort_indices() + * + * if X.data.dtype != DTYPE: # <<<<<<<<<<<<<< + * X.data = np.ascontiguousarray(X.data, dtype=DTYPE) + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2581; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_dtype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2581; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2581; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_2, __pyx_t_1, Py_NE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2581; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2581; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_5) { + + /* "sklearn/tree/_tree.pyx":2582 + * + * if X.data.dtype != DTYPE: + * X.data = np.ascontiguousarray(X.data, dtype=DTYPE) # <<<<<<<<<<<<<< + * + * if X.indices.dtype != np.int32 or X.indptr.dtype != np.int32: + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_ascontiguousarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__Pyx_PyObject_SetAttrStr(__pyx_v_X, __pyx_n_s_data, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2582; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L4; + } + __pyx_L4:; + + /* "sklearn/tree/_tree.pyx":2584 + * X.data = np.ascontiguousarray(X.data, dtype=DTYPE) + * + * if X.indices.dtype != np.int32 or X.indptr.dtype != np.int32: # <<<<<<<<<<<<<< + * raise ValueError("No support for np.int64 index based " + * "sparse matrices") + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_dtype); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_int32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_RichCompare(__pyx_t_4, __pyx_t_2, Py_NE); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_dtype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_int32); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_RichCompare(__pyx_t_2, __pyx_t_4, Py_NE); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = __pyx_t_6; + __pyx_L6_bool_binop_done:; + if (__pyx_t_5) { + + /* "sklearn/tree/_tree.pyx":2585 + * + * if X.indices.dtype != np.int32 or X.indptr.dtype != np.int32: + * raise ValueError("No support for np.int64 index based " # <<<<<<<<<<<<<< + * "sparse matrices") + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + goto __pyx_L3; + } + + /* "sklearn/tree/_tree.pyx":2588 + * "sparse matrices") + * + * elif X.dtype != DTYPE: # <<<<<<<<<<<<<< + * # since we have to copy we will make it fortran for efficiency + * X = np.asfortranarray(X, dtype=DTYPE) + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_dtype); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = PyObject_RichCompare(__pyx_t_3, __pyx_t_4, Py_NE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_5) { + + /* "sklearn/tree/_tree.pyx":2590 + * elif X.dtype != DTYPE: + * # since we have to copy we will make it fortran for efficiency + * X = np.asfortranarray(X, dtype=DTYPE) # <<<<<<<<<<<<<< + * + * if y.dtype != DOUBLE or not y.flags.contiguous: + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_asfortranarray); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/tree/_tree.pyx":2592 + * X = np.asfortranarray(X, dtype=DTYPE) + * + * if y.dtype != DOUBLE or not y.flags.contiguous: # <<<<<<<<<<<<<< + * y = np.ascontiguousarray(y, dtype=DOUBLE) + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_y), __pyx_n_s_dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyObject_RichCompare(__pyx_t_1, __pyx_t_3, Py_NE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L9_bool_binop_done; + } + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_y), __pyx_n_s_flags); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_contiguous); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = ((!__pyx_t_6) != 0); + __pyx_t_5 = __pyx_t_7; + __pyx_L9_bool_binop_done:; + if (__pyx_t_5) { + + /* "sklearn/tree/_tree.pyx":2593 + * + * if y.dtype != DOUBLE or not y.flags.contiguous: + * y = np.ascontiguousarray(y, dtype=DOUBLE) # <<<<<<<<<<<<<< + * + * if (sample_weight is not None and + */ + __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_ascontiguousarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_y)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_y)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF_SET(__pyx_v_y, ((PyArrayObject *)__pyx_t_4)); + __pyx_t_4 = 0; + goto __pyx_L8; + } + __pyx_L8:; + + /* "sklearn/tree/_tree.pyx":2595 + * y = np.ascontiguousarray(y, dtype=DOUBLE) + * + * if (sample_weight is not None and # <<<<<<<<<<<<<< + * (sample_weight.dtype != DOUBLE or + * not sample_weight.flags.contiguous)): + */ + __pyx_t_7 = (((PyObject *)__pyx_v_sample_weight) != Py_None); + __pyx_t_6 = (__pyx_t_7 != 0); + if (__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L12_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":2596 + * + * if (sample_weight is not None and + * (sample_weight.dtype != DOUBLE or # <<<<<<<<<<<<<< + * not sample_weight.flags.contiguous)): + * sample_weight = np.asarray(sample_weight, dtype=DOUBLE, + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_sample_weight), __pyx_n_s_dtype); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2596; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_DOUBLE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2596; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_4, __pyx_t_1, Py_NE); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2596; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2596; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L12_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":2597 + * if (sample_weight is not None and + * (sample_weight.dtype != DOUBLE or + * not sample_weight.flags.contiguous)): # <<<<<<<<<<<<<< + * sample_weight = np.asarray(sample_weight, dtype=DOUBLE, + * order="C") + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_sample_weight), __pyx_n_s_flags); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_contiguous); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_7 = ((!__pyx_t_6) != 0); + __pyx_t_5 = __pyx_t_7; + __pyx_L12_bool_binop_done:; + if (__pyx_t_5) { + + /* "sklearn/tree/_tree.pyx":2598 + * (sample_weight.dtype != DOUBLE or + * not sample_weight.flags.contiguous)): + * sample_weight = np.asarray(sample_weight, dtype=DOUBLE, # <<<<<<<<<<<<<< + * order="C") + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_asarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_sample_weight)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_sample_weight)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_sample_weight)); + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DOUBLE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_order, __pyx_n_s_C) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_1, __pyx_t_4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF_SET(__pyx_v_sample_weight, ((PyArrayObject *)__pyx_t_2)); + __pyx_t_2 = 0; + goto __pyx_L11; + } + __pyx_L11:; + + /* "sklearn/tree/_tree.pyx":2601 + * order="C") + * + * return X, y, sample_weight # <<<<<<<<<<<<<< + * + * # Depth first builder --------------------------------------------------------- + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2601; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __Pyx_INCREF(((PyObject *)__pyx_v_y)); + PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_y)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); + __Pyx_INCREF(((PyObject *)__pyx_v_sample_weight)); + PyTuple_SET_ITEM(__pyx_t_2, 2, ((PyObject *)__pyx_v_sample_weight)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_sample_weight)); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":2574 + * pass + * + * cdef inline _check_input(self, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight): + * """Check input dtype, layout and format""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.TreeBuilder._check_input", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_X); + __Pyx_XDECREF((PyObject *)__pyx_v_y); + __Pyx_XDECREF((PyObject *)__pyx_v_sample_weight); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":2608 + * """Build a decision tree in depth-first fashion.""" + * + * def __cinit__(self, Splitter splitter, SIZE_t min_samples_split, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, double min_weight_leaf, + * SIZE_t max_depth): + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_splitter = 0; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_split; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + double __pyx_v_min_weight_leaf; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_depth; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_splitter,&__pyx_n_s_min_samples_split,&__pyx_n_s_min_samples_leaf,&__pyx_n_s_min_weight_leaf,&__pyx_n_s_max_depth,0}; + PyObject* values[5] = {0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_splitter)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_samples_split)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_samples_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_weight_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_depth)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + } + __pyx_v_splitter = ((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)values[0]); + __pyx_v_min_samples_split = __Pyx_PyInt_As_Py_intptr_t(values[1]); if (unlikely((__pyx_v_min_samples_split == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_samples_leaf = __Pyx_PyInt_As_Py_intptr_t(values[2]); if (unlikely((__pyx_v_min_samples_leaf == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2609; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_weight_leaf = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_min_weight_leaf == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2609; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_max_depth = __Pyx_PyInt_As_Py_intptr_t(values[4]); if (unlikely((__pyx_v_max_depth == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2610; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2608; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._tree.DepthFirstTreeBuilder.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_splitter), __pyx_ptype_7sklearn_4tree_5_tree_Splitter, 1, "splitter", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder *)__pyx_v_self), __pyx_v_splitter, __pyx_v_min_samples_split, __pyx_v_min_samples_leaf, __pyx_v_min_weight_leaf, __pyx_v_max_depth); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_splitter, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, double __pyx_v_min_weight_leaf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_depth) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "sklearn/tree/_tree.pyx":2611 + * SIZE_t min_samples_leaf, double min_weight_leaf, + * SIZE_t max_depth): + * self.splitter = splitter # <<<<<<<<<<<<<< + * self.min_samples_split = min_samples_split + * self.min_samples_leaf = min_samples_leaf + */ + __Pyx_INCREF(((PyObject *)__pyx_v_splitter)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_splitter)); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.splitter); + __Pyx_DECREF(((PyObject *)__pyx_v_self->__pyx_base.splitter)); + __pyx_v_self->__pyx_base.splitter = __pyx_v_splitter; + + /* "sklearn/tree/_tree.pyx":2612 + * SIZE_t max_depth): + * self.splitter = splitter + * self.min_samples_split = min_samples_split # <<<<<<<<<<<<<< + * self.min_samples_leaf = min_samples_leaf + * self.min_weight_leaf = min_weight_leaf + */ + __pyx_v_self->__pyx_base.min_samples_split = __pyx_v_min_samples_split; + + /* "sklearn/tree/_tree.pyx":2613 + * self.splitter = splitter + * self.min_samples_split = min_samples_split + * self.min_samples_leaf = min_samples_leaf # <<<<<<<<<<<<<< + * self.min_weight_leaf = min_weight_leaf + * self.max_depth = max_depth + */ + __pyx_v_self->__pyx_base.min_samples_leaf = __pyx_v_min_samples_leaf; + + /* "sklearn/tree/_tree.pyx":2614 + * self.min_samples_split = min_samples_split + * self.min_samples_leaf = min_samples_leaf + * self.min_weight_leaf = min_weight_leaf # <<<<<<<<<<<<<< + * self.max_depth = max_depth + * + */ + __pyx_v_self->__pyx_base.min_weight_leaf = __pyx_v_min_weight_leaf; + + /* "sklearn/tree/_tree.pyx":2615 + * self.min_samples_leaf = min_samples_leaf + * self.min_weight_leaf = min_weight_leaf + * self.max_depth = max_depth # <<<<<<<<<<<<<< + * + * cpdef build(self, Tree tree, object X, np.ndarray y, + */ + __pyx_v_self->__pyx_base.max_depth = __pyx_v_max_depth; + + /* "sklearn/tree/_tree.pyx":2608 + * """Build a decision tree in depth-first fashion.""" + * + * def __cinit__(self, Splitter splitter, SIZE_t min_samples_split, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, double min_weight_leaf, + * SIZE_t max_depth): + */ + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":2617 + * self.max_depth = max_depth + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_3build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyObject *__pyx_f_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_build(struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_build *__pyx_optional_args) { + + /* "sklearn/tree/_tree.pyx":2618 + * + * cpdef build(self, Tree tree, object X, np.ndarray y, + * np.ndarray sample_weight=None): # <<<<<<<<<<<<<< + * """Build a decision tree from the training set (X, y).""" + * + */ + PyArrayObject *__pyx_v_sample_weight = ((PyArrayObject *)Py_None); + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight_ptr; + int __pyx_v_init_capacity; + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_splitter = 0; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_depth; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + double __pyx_v_min_weight_leaf; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_split; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_depth; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_parent; + int __pyx_v_is_left; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_node_samples; + CYTHON_UNUSED double __pyx_v_weighted_n_samples; + double __pyx_v_weighted_n_node_samples; + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_split; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_node_id; + double __pyx_v_impurity; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_constant_features; + int __pyx_v_is_leaf; + int __pyx_v_first; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_depth_seen; + int __pyx_v_rc; + struct __pyx_obj_7sklearn_4tree_6_utils_Stack *__pyx_v_stack = 0; + struct __pyx_t_7sklearn_4tree_6_utils_StackRecord __pyx_v_stack_record; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *(*__pyx_t_7)(PyObject *); + int __pyx_t_8; + int __pyx_t_9; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_10; + double __pyx_t_11; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_t_12; + int __pyx_t_13; + struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("build", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_sample_weight = __pyx_optional_args->sample_weight; + } + } + __Pyx_INCREF(__pyx_v_X); + __Pyx_INCREF((PyObject *)__pyx_v_y); + __Pyx_INCREF((PyObject *)__pyx_v_sample_weight); + + /* "sklearn/tree/_tree.pyx":2617 + * self.max_depth = max_depth + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + /* Check if called by wrapper */ + if (unlikely(__pyx_skip_dispatch)) ; + /* Check if overridden in Python */ + else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_build); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2617; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_3build)) { + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_3 = __pyx_t_1; __pyx_t_4 = NULL; + __pyx_t_5 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_5 = 1; + } + } + __pyx_t_6 = PyTuple_New(4+__pyx_t_5); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2617; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (__pyx_t_4) { + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + } + __Pyx_INCREF(((PyObject *)__pyx_v_tree)); + PyTuple_SET_ITEM(__pyx_t_6, 0+__pyx_t_5, ((PyObject *)__pyx_v_tree)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_tree)); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_6, 1+__pyx_t_5, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __Pyx_INCREF(((PyObject *)__pyx_v_y)); + PyTuple_SET_ITEM(__pyx_t_6, 2+__pyx_t_5, ((PyObject *)__pyx_v_y)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); + __Pyx_INCREF(((PyObject *)__pyx_v_sample_weight)); + PyTuple_SET_ITEM(__pyx_t_6, 3+__pyx_t_5, ((PyObject *)__pyx_v_sample_weight)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_sample_weight)); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2617; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "sklearn/tree/_tree.pyx":2622 + * + * # check input + * X, y, sample_weight = self._check_input(X, y, sample_weight) # <<<<<<<<<<<<<< + * + * cdef DOUBLE_t* sample_weight_ptr = NULL + */ + __pyx_t_1 = __pyx_f_7sklearn_4tree_5_tree_11TreeBuilder__check_input(((struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *)__pyx_v_self), __pyx_v_X, __pyx_v_y, __pyx_v_sample_weight); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 3)) { + if (size > 3) __Pyx_RaiseTooManyValuesError(3); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 2); + } else { + __pyx_t_2 = PyList_GET_ITEM(sequence, 0); + __pyx_t_3 = PyList_GET_ITEM(sequence, 1); + __pyx_t_6 = PyList_GET_ITEM(sequence, 2); + } + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_6); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_7 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_2 = __pyx_t_7(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_3 = __pyx_t_7(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 2; __pyx_t_6 = __pyx_t_7(__pyx_t_4); if (unlikely(!__pyx_t_6)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_4), 3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = NULL; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_7 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L4_unpacking_done:; + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2622; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_2); + __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_y, ((PyArrayObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_sample_weight, ((PyArrayObject *)__pyx_t_6)); + __pyx_t_6 = 0; + + /* "sklearn/tree/_tree.pyx":2624 + * X, y, sample_weight = self._check_input(X, y, sample_weight) + * + * cdef DOUBLE_t* sample_weight_ptr = NULL # <<<<<<<<<<<<<< + * if sample_weight is not None: + * sample_weight_ptr = sample_weight.data + */ + __pyx_v_sample_weight_ptr = NULL; + + /* "sklearn/tree/_tree.pyx":2625 + * + * cdef DOUBLE_t* sample_weight_ptr = NULL + * if sample_weight is not None: # <<<<<<<<<<<<<< + * sample_weight_ptr = sample_weight.data + * + */ + __pyx_t_8 = (((PyObject *)__pyx_v_sample_weight) != Py_None); + __pyx_t_9 = (__pyx_t_8 != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2626 + * cdef DOUBLE_t* sample_weight_ptr = NULL + * if sample_weight is not None: + * sample_weight_ptr = sample_weight.data # <<<<<<<<<<<<<< + * + * # Initial capacity + */ + __pyx_v_sample_weight_ptr = ((__pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *)__pyx_v_sample_weight->data); + goto __pyx_L5; + } + __pyx_L5:; + + /* "sklearn/tree/_tree.pyx":2631 + * cdef int init_capacity + * + * if tree.max_depth <= 10: # <<<<<<<<<<<<<< + * init_capacity = (2 ** (tree.max_depth + 1)) - 1 + * else: + */ + __pyx_t_9 = ((__pyx_v_tree->max_depth <= 10) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2632 + * + * if tree.max_depth <= 10: + * init_capacity = (2 ** (tree.max_depth + 1)) - 1 # <<<<<<<<<<<<<< + * else: + * init_capacity = 2047 + */ + __pyx_v_init_capacity = (__Pyx_pow_long(2, (__pyx_v_tree->max_depth + 1)) - 1); + goto __pyx_L6; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":2634 + * init_capacity = (2 ** (tree.max_depth + 1)) - 1 + * else: + * init_capacity = 2047 # <<<<<<<<<<<<<< + * + * tree._resize(init_capacity) + */ + __pyx_v_init_capacity = 2047; + } + __pyx_L6:; + + /* "sklearn/tree/_tree.pyx":2636 + * init_capacity = 2047 + * + * tree._resize(init_capacity) # <<<<<<<<<<<<<< + * + * # Parameters + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_tree->__pyx_vtab)->_resize(__pyx_v_tree, __pyx_v_init_capacity); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2636; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":2639 + * + * # Parameters + * cdef Splitter splitter = self.splitter # <<<<<<<<<<<<<< + * cdef SIZE_t max_depth = self.max_depth + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + */ + __pyx_t_1 = ((PyObject *)__pyx_v_self->__pyx_base.splitter); + __Pyx_INCREF(__pyx_t_1); + __pyx_v_splitter = ((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":2640 + * # Parameters + * cdef Splitter splitter = self.splitter + * cdef SIZE_t max_depth = self.max_depth # <<<<<<<<<<<<<< + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf + */ + __pyx_t_10 = __pyx_v_self->__pyx_base.max_depth; + __pyx_v_max_depth = __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":2641 + * cdef Splitter splitter = self.splitter + * cdef SIZE_t max_depth = self.max_depth + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf # <<<<<<<<<<<<<< + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef SIZE_t min_samples_split = self.min_samples_split + */ + __pyx_t_10 = __pyx_v_self->__pyx_base.min_samples_leaf; + __pyx_v_min_samples_leaf = __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":2642 + * cdef SIZE_t max_depth = self.max_depth + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf # <<<<<<<<<<<<<< + * cdef SIZE_t min_samples_split = self.min_samples_split + * + */ + __pyx_t_11 = __pyx_v_self->__pyx_base.min_weight_leaf; + __pyx_v_min_weight_leaf = __pyx_t_11; + + /* "sklearn/tree/_tree.pyx":2643 + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef SIZE_t min_samples_split = self.min_samples_split # <<<<<<<<<<<<<< + * + * # Recursive partition (without actual recursion) + */ + __pyx_t_10 = __pyx_v_self->__pyx_base.min_samples_split; + __pyx_v_min_samples_split = __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":2646 + * + * # Recursive partition (without actual recursion) + * splitter.init(X, y, sample_weight_ptr) # <<<<<<<<<<<<<< + * + * cdef SIZE_t start + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *)__pyx_v_splitter->__pyx_vtab)->init(__pyx_v_splitter, __pyx_v_X, __pyx_v_y, __pyx_v_sample_weight_ptr); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":2653 + * cdef SIZE_t parent + * cdef bint is_left + * cdef SIZE_t n_node_samples = splitter.n_samples # <<<<<<<<<<<<<< + * cdef double weighted_n_samples = splitter.weighted_n_samples + * cdef double weighted_n_node_samples + */ + __pyx_t_10 = __pyx_v_splitter->n_samples; + __pyx_v_n_node_samples = __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":2654 + * cdef bint is_left + * cdef SIZE_t n_node_samples = splitter.n_samples + * cdef double weighted_n_samples = splitter.weighted_n_samples # <<<<<<<<<<<<<< + * cdef double weighted_n_node_samples + * cdef SplitRecord split + */ + __pyx_t_11 = __pyx_v_splitter->weighted_n_samples; + __pyx_v_weighted_n_samples = __pyx_t_11; + + /* "sklearn/tree/_tree.pyx":2660 + * + * cdef double threshold + * cdef double impurity = INFINITY # <<<<<<<<<<<<<< + * cdef SIZE_t n_constant_features + * cdef bint is_leaf + */ + __pyx_v_impurity = __pyx_v_7sklearn_4tree_5_tree_INFINITY; + + /* "sklearn/tree/_tree.pyx":2663 + * cdef SIZE_t n_constant_features + * cdef bint is_leaf + * cdef bint first = 1 # <<<<<<<<<<<<<< + * cdef SIZE_t max_depth_seen = -1 + * cdef int rc = 0 + */ + __pyx_v_first = 1; + + /* "sklearn/tree/_tree.pyx":2664 + * cdef bint is_leaf + * cdef bint first = 1 + * cdef SIZE_t max_depth_seen = -1 # <<<<<<<<<<<<<< + * cdef int rc = 0 + * + */ + __pyx_v_max_depth_seen = -1; + + /* "sklearn/tree/_tree.pyx":2665 + * cdef bint first = 1 + * cdef SIZE_t max_depth_seen = -1 + * cdef int rc = 0 # <<<<<<<<<<<<<< + * + * cdef Stack stack = Stack(INITIAL_STACK_SIZE) + */ + __pyx_v_rc = 0; + + /* "sklearn/tree/_tree.pyx":2667 + * cdef int rc = 0 + * + * cdef Stack stack = Stack(INITIAL_STACK_SIZE) # <<<<<<<<<<<<<< + * cdef StackRecord stack_record + * + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_7sklearn_4tree_5_tree_INITIAL_STACK_SIZE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_6_utils_Stack)), __pyx_t_6, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_stack = ((struct __pyx_obj_7sklearn_4tree_6_utils_Stack *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":2671 + * + * # push root node onto stack + * rc = stack.push(0, n_node_samples, 0, _TREE_UNDEFINED, 0, INFINITY, 0) # <<<<<<<<<<<<<< + * if rc == -1: + * # got return code -1 - out-of-memory + */ + __pyx_v_rc = ((struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack *)__pyx_v_stack->__pyx_vtab)->push(__pyx_v_stack, 0, __pyx_v_n_node_samples, 0, __pyx_v_7sklearn_4tree_5_tree__TREE_UNDEFINED, 0, __pyx_v_7sklearn_4tree_5_tree_INFINITY, 0); + + /* "sklearn/tree/_tree.pyx":2672 + * # push root node onto stack + * rc = stack.push(0, n_node_samples, 0, _TREE_UNDEFINED, 0, INFINITY, 0) + * if rc == -1: # <<<<<<<<<<<<<< + * # got return code -1 - out-of-memory + * raise MemoryError() + */ + __pyx_t_9 = ((__pyx_v_rc == -1) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2674 + * if rc == -1: + * # got return code -1 - out-of-memory + * raise MemoryError() # <<<<<<<<<<<<<< + * + * with nogil: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2674; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":2676 + * raise MemoryError() + * + * with nogil: # <<<<<<<<<<<<<< + * while not stack.is_empty(): + * stack.pop(&stack_record) + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/tree/_tree.pyx":2677 + * + * with nogil: + * while not stack.is_empty(): # <<<<<<<<<<<<<< + * stack.pop(&stack_record) + * + */ + while (1) { + __pyx_t_9 = ((!(((struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack *)__pyx_v_stack->__pyx_vtab)->is_empty(__pyx_v_stack) != 0)) != 0); + if (!__pyx_t_9) break; + + /* "sklearn/tree/_tree.pyx":2678 + * with nogil: + * while not stack.is_empty(): + * stack.pop(&stack_record) # <<<<<<<<<<<<<< + * + * start = stack_record.start + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack *)__pyx_v_stack->__pyx_vtab)->pop(__pyx_v_stack, (&__pyx_v_stack_record)); + + /* "sklearn/tree/_tree.pyx":2680 + * stack.pop(&stack_record) + * + * start = stack_record.start # <<<<<<<<<<<<<< + * end = stack_record.end + * depth = stack_record.depth + */ + __pyx_t_12 = __pyx_v_stack_record.start; + __pyx_v_start = __pyx_t_12; + + /* "sklearn/tree/_tree.pyx":2681 + * + * start = stack_record.start + * end = stack_record.end # <<<<<<<<<<<<<< + * depth = stack_record.depth + * parent = stack_record.parent + */ + __pyx_t_12 = __pyx_v_stack_record.end; + __pyx_v_end = __pyx_t_12; + + /* "sklearn/tree/_tree.pyx":2682 + * start = stack_record.start + * end = stack_record.end + * depth = stack_record.depth # <<<<<<<<<<<<<< + * parent = stack_record.parent + * is_left = stack_record.is_left + */ + __pyx_t_12 = __pyx_v_stack_record.depth; + __pyx_v_depth = __pyx_t_12; + + /* "sklearn/tree/_tree.pyx":2683 + * end = stack_record.end + * depth = stack_record.depth + * parent = stack_record.parent # <<<<<<<<<<<<<< + * is_left = stack_record.is_left + * impurity = stack_record.impurity + */ + __pyx_t_12 = __pyx_v_stack_record.parent; + __pyx_v_parent = __pyx_t_12; + + /* "sklearn/tree/_tree.pyx":2684 + * depth = stack_record.depth + * parent = stack_record.parent + * is_left = stack_record.is_left # <<<<<<<<<<<<<< + * impurity = stack_record.impurity + * n_constant_features = stack_record.n_constant_features + */ + __pyx_t_9 = __pyx_v_stack_record.is_left; + __pyx_v_is_left = __pyx_t_9; + + /* "sklearn/tree/_tree.pyx":2685 + * parent = stack_record.parent + * is_left = stack_record.is_left + * impurity = stack_record.impurity # <<<<<<<<<<<<<< + * n_constant_features = stack_record.n_constant_features + * + */ + __pyx_t_11 = __pyx_v_stack_record.impurity; + __pyx_v_impurity = __pyx_t_11; + + /* "sklearn/tree/_tree.pyx":2686 + * is_left = stack_record.is_left + * impurity = stack_record.impurity + * n_constant_features = stack_record.n_constant_features # <<<<<<<<<<<<<< + * + * n_node_samples = end - start + */ + __pyx_t_12 = __pyx_v_stack_record.n_constant_features; + __pyx_v_n_constant_features = __pyx_t_12; + + /* "sklearn/tree/_tree.pyx":2688 + * n_constant_features = stack_record.n_constant_features + * + * n_node_samples = end - start # <<<<<<<<<<<<<< + * splitter.node_reset(start, end, &weighted_n_node_samples) + * + */ + __pyx_v_n_node_samples = (__pyx_v_end - __pyx_v_start); + + /* "sklearn/tree/_tree.pyx":2689 + * + * n_node_samples = end - start + * splitter.node_reset(start, end, &weighted_n_node_samples) # <<<<<<<<<<<<<< + * + * is_leaf = ((depth >= max_depth) or + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *)__pyx_v_splitter->__pyx_vtab)->node_reset(__pyx_v_splitter, __pyx_v_start, __pyx_v_end, (&__pyx_v_weighted_n_node_samples)); + + /* "sklearn/tree/_tree.pyx":2691 + * splitter.node_reset(start, end, &weighted_n_node_samples) + * + * is_leaf = ((depth >= max_depth) or # <<<<<<<<<<<<<< + * (n_node_samples < min_samples_split) or + * (n_node_samples < 2 * min_samples_leaf) or + */ + __pyx_t_8 = ((__pyx_v_depth >= __pyx_v_max_depth) != 0); + if (!__pyx_t_8) { + } else { + __pyx_t_9 = __pyx_t_8; + goto __pyx_L13_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":2692 + * + * is_leaf = ((depth >= max_depth) or + * (n_node_samples < min_samples_split) or # <<<<<<<<<<<<<< + * (n_node_samples < 2 * min_samples_leaf) or + * (weighted_n_node_samples < min_weight_leaf)) + */ + __pyx_t_8 = ((__pyx_v_n_node_samples < __pyx_v_min_samples_split) != 0); + if (!__pyx_t_8) { + } else { + __pyx_t_9 = __pyx_t_8; + goto __pyx_L13_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":2693 + * is_leaf = ((depth >= max_depth) or + * (n_node_samples < min_samples_split) or + * (n_node_samples < 2 * min_samples_leaf) or # <<<<<<<<<<<<<< + * (weighted_n_node_samples < min_weight_leaf)) + * + */ + __pyx_t_8 = ((__pyx_v_n_node_samples < (2 * __pyx_v_min_samples_leaf)) != 0); + if (!__pyx_t_8) { + } else { + __pyx_t_9 = __pyx_t_8; + goto __pyx_L13_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":2694 + * (n_node_samples < min_samples_split) or + * (n_node_samples < 2 * min_samples_leaf) or + * (weighted_n_node_samples < min_weight_leaf)) # <<<<<<<<<<<<<< + * + * if first: + */ + __pyx_t_8 = ((__pyx_v_weighted_n_node_samples < __pyx_v_min_weight_leaf) != 0); + __pyx_t_9 = __pyx_t_8; + __pyx_L13_bool_binop_done:; + __pyx_v_is_leaf = __pyx_t_9; + + /* "sklearn/tree/_tree.pyx":2696 + * (weighted_n_node_samples < min_weight_leaf)) + * + * if first: # <<<<<<<<<<<<<< + * impurity = splitter.node_impurity() + * first = 0 + */ + __pyx_t_9 = (__pyx_v_first != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2697 + * + * if first: + * impurity = splitter.node_impurity() # <<<<<<<<<<<<<< + * first = 0 + * + */ + __pyx_v_impurity = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *)__pyx_v_splitter->__pyx_vtab)->node_impurity(__pyx_v_splitter); + + /* "sklearn/tree/_tree.pyx":2698 + * if first: + * impurity = splitter.node_impurity() + * first = 0 # <<<<<<<<<<<<<< + * + * is_leaf = is_leaf or (impurity <= MIN_IMPURITY_SPLIT) + */ + __pyx_v_first = 0; + goto __pyx_L17; + } + __pyx_L17:; + + /* "sklearn/tree/_tree.pyx":2700 + * first = 0 + * + * is_leaf = is_leaf or (impurity <= MIN_IMPURITY_SPLIT) # <<<<<<<<<<<<<< + * + * if not is_leaf: + */ + __pyx_t_8 = (__pyx_v_is_leaf != 0); + if (!__pyx_t_8) { + } else { + __pyx_t_9 = __pyx_t_8; + goto __pyx_L18_bool_binop_done; + } + __pyx_t_8 = ((__pyx_v_impurity <= __pyx_v_7sklearn_4tree_5_tree_MIN_IMPURITY_SPLIT) != 0); + __pyx_t_9 = __pyx_t_8; + __pyx_L18_bool_binop_done:; + __pyx_v_is_leaf = __pyx_t_9; + + /* "sklearn/tree/_tree.pyx":2702 + * is_leaf = is_leaf or (impurity <= MIN_IMPURITY_SPLIT) + * + * if not is_leaf: # <<<<<<<<<<<<<< + * splitter.node_split(impurity, &split, &n_constant_features) + * is_leaf = is_leaf or (split.pos >= end) + */ + __pyx_t_9 = ((!(__pyx_v_is_leaf != 0)) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2703 + * + * if not is_leaf: + * splitter.node_split(impurity, &split, &n_constant_features) # <<<<<<<<<<<<<< + * is_leaf = is_leaf or (split.pos >= end) + * + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *)__pyx_v_splitter->__pyx_vtab)->node_split(__pyx_v_splitter, __pyx_v_impurity, (&__pyx_v_split), (&__pyx_v_n_constant_features)); + + /* "sklearn/tree/_tree.pyx":2704 + * if not is_leaf: + * splitter.node_split(impurity, &split, &n_constant_features) + * is_leaf = is_leaf or (split.pos >= end) # <<<<<<<<<<<<<< + * + * node_id = tree._add_node(parent, is_left, is_leaf, split.feature, + */ + __pyx_t_8 = (__pyx_v_is_leaf != 0); + if (!__pyx_t_8) { + } else { + __pyx_t_9 = __pyx_t_8; + goto __pyx_L21_bool_binop_done; + } + __pyx_t_8 = ((__pyx_v_split.pos >= __pyx_v_end) != 0); + __pyx_t_9 = __pyx_t_8; + __pyx_L21_bool_binop_done:; + __pyx_v_is_leaf = __pyx_t_9; + goto __pyx_L20; + } + __pyx_L20:; + + /* "sklearn/tree/_tree.pyx":2706 + * is_leaf = is_leaf or (split.pos >= end) + * + * node_id = tree._add_node(parent, is_left, is_leaf, split.feature, # <<<<<<<<<<<<<< + * split.threshold, impurity, n_node_samples, + * weighted_n_node_samples) + */ + __pyx_v_node_id = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_tree->__pyx_vtab)->_add_node(__pyx_v_tree, __pyx_v_parent, __pyx_v_is_left, __pyx_v_is_leaf, __pyx_v_split.feature, __pyx_v_split.threshold, __pyx_v_impurity, __pyx_v_n_node_samples, __pyx_v_weighted_n_node_samples); + + /* "sklearn/tree/_tree.pyx":2710 + * weighted_n_node_samples) + * + * if is_leaf: # <<<<<<<<<<<<<< + * # Don't store value for internal nodes + * splitter.node_value(tree.value + + */ + __pyx_t_9 = (__pyx_v_is_leaf != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2712 + * if is_leaf: + * # Don't store value for internal nodes + * splitter.node_value(tree.value + # <<<<<<<<<<<<<< + * node_id * tree.value_stride) + * + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *)__pyx_v_splitter->__pyx_vtab)->node_value(__pyx_v_splitter, (__pyx_v_tree->value + (__pyx_v_node_id * __pyx_v_tree->value_stride))); + goto __pyx_L23; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":2717 + * else: + * # Push right child on stack + * rc = stack.push(split.pos, end, depth + 1, node_id, 0, # <<<<<<<<<<<<<< + * split.impurity_right, n_constant_features) + * if rc == -1: + */ + __pyx_v_rc = ((struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack *)__pyx_v_stack->__pyx_vtab)->push(__pyx_v_stack, __pyx_v_split.pos, __pyx_v_end, (__pyx_v_depth + 1), __pyx_v_node_id, 0, __pyx_v_split.impurity_right, __pyx_v_n_constant_features); + + /* "sklearn/tree/_tree.pyx":2719 + * rc = stack.push(split.pos, end, depth + 1, node_id, 0, + * split.impurity_right, n_constant_features) + * if rc == -1: # <<<<<<<<<<<<<< + * break + * + */ + __pyx_t_9 = ((__pyx_v_rc == -1) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2720 + * split.impurity_right, n_constant_features) + * if rc == -1: + * break # <<<<<<<<<<<<<< + * + * # Push left child on stack + */ + goto __pyx_L12_break; + } + + /* "sklearn/tree/_tree.pyx":2723 + * + * # Push left child on stack + * rc = stack.push(start, split.pos, depth + 1, node_id, 1, # <<<<<<<<<<<<<< + * split.impurity_left, n_constant_features) + * if rc == -1: + */ + __pyx_v_rc = ((struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack *)__pyx_v_stack->__pyx_vtab)->push(__pyx_v_stack, __pyx_v_start, __pyx_v_split.pos, (__pyx_v_depth + 1), __pyx_v_node_id, 1, __pyx_v_split.impurity_left, __pyx_v_n_constant_features); + + /* "sklearn/tree/_tree.pyx":2725 + * rc = stack.push(start, split.pos, depth + 1, node_id, 1, + * split.impurity_left, n_constant_features) + * if rc == -1: # <<<<<<<<<<<<<< + * break + * + */ + __pyx_t_9 = ((__pyx_v_rc == -1) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2726 + * split.impurity_left, n_constant_features) + * if rc == -1: + * break # <<<<<<<<<<<<<< + * + * if depth > max_depth_seen: + */ + goto __pyx_L12_break; + } + } + __pyx_L23:; + + /* "sklearn/tree/_tree.pyx":2728 + * break + * + * if depth > max_depth_seen: # <<<<<<<<<<<<<< + * max_depth_seen = depth + * + */ + __pyx_t_9 = ((__pyx_v_depth > __pyx_v_max_depth_seen) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2729 + * + * if depth > max_depth_seen: + * max_depth_seen = depth # <<<<<<<<<<<<<< + * + * if rc >= 0: + */ + __pyx_v_max_depth_seen = __pyx_v_depth; + goto __pyx_L26; + } + __pyx_L26:; + } + __pyx_L12_break:; + + /* "sklearn/tree/_tree.pyx":2731 + * max_depth_seen = depth + * + * if rc >= 0: # <<<<<<<<<<<<<< + * rc = tree._resize_c(tree.node_count) + * + */ + __pyx_t_9 = ((__pyx_v_rc >= 0) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2732 + * + * if rc >= 0: + * rc = tree._resize_c(tree.node_count) # <<<<<<<<<<<<<< + * + * if rc >= 0: + */ + __pyx_t_14.__pyx_n = 1; + __pyx_t_14.capacity = __pyx_v_tree->node_count; + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_tree->__pyx_vtab)->_resize_c(__pyx_v_tree, &__pyx_t_14); + __pyx_v_rc = __pyx_t_13; + goto __pyx_L27; + } + __pyx_L27:; + + /* "sklearn/tree/_tree.pyx":2734 + * rc = tree._resize_c(tree.node_count) + * + * if rc >= 0: # <<<<<<<<<<<<<< + * tree.max_depth = max_depth_seen + * if rc == -1: + */ + __pyx_t_9 = ((__pyx_v_rc >= 0) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2735 + * + * if rc >= 0: + * tree.max_depth = max_depth_seen # <<<<<<<<<<<<<< + * if rc == -1: + * raise MemoryError() + */ + __pyx_v_tree->max_depth = __pyx_v_max_depth_seen; + goto __pyx_L28; + } + __pyx_L28:; + } + + /* "sklearn/tree/_tree.pyx":2676 + * raise MemoryError() + * + * with nogil: # <<<<<<<<<<<<<< + * while not stack.is_empty(): + * stack.pop(&stack_record) + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L10; + } + __pyx_L10:; + } + } + + /* "sklearn/tree/_tree.pyx":2736 + * if rc >= 0: + * tree.max_depth = max_depth_seen + * if rc == -1: # <<<<<<<<<<<<<< + * raise MemoryError() + * + */ + __pyx_t_9 = ((__pyx_v_rc == -1) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2737 + * tree.max_depth = max_depth_seen + * if rc == -1: + * raise MemoryError() # <<<<<<<<<<<<<< + * + * + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2737; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":2617 + * self.max_depth = max_depth + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("sklearn.tree._tree.DepthFirstTreeBuilder.build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_splitter); + __Pyx_XDECREF((PyObject *)__pyx_v_stack); + __Pyx_XDECREF(__pyx_v_X); + __Pyx_XDECREF((PyObject *)__pyx_v_y); + __Pyx_XDECREF((PyObject *)__pyx_v_sample_weight); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_3build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_2build[] = "Build a decision tree from the training set (X, y)."; +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_3build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree = 0; + PyObject *__pyx_v_X = 0; + PyArrayObject *__pyx_v_y = 0; + PyArrayObject *__pyx_v_sample_weight = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("build (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_tree,&__pyx_n_s_X,&__pyx_n_s_y,&__pyx_n_s_sample_weight,0}; + PyObject* values[4] = {0,0,0,0}; + + /* "sklearn/tree/_tree.pyx":2618 + * + * cpdef build(self, Tree tree, object X, np.ndarray y, + * np.ndarray sample_weight=None): # <<<<<<<<<<<<<< + * """Build a decision tree from the training set (X, y).""" + * + */ + values[3] = (PyObject *)((PyArrayObject *)Py_None); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tree)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build", 0, 3, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2617; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build", 0, 3, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2617; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sample_weight); + if (value) { values[3] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "build") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2617; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_tree = ((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)values[0]); + __pyx_v_X = values[1]; + __pyx_v_y = ((PyArrayObject *)values[2]); + __pyx_v_sample_weight = ((PyArrayObject *)values[3]); + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("build", 0, 3, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2617; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._tree.DepthFirstTreeBuilder.build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_tree), __pyx_ptype_7sklearn_4tree_5_tree_Tree, 1, "tree", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2617; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2617; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2618; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_2build(((struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder *)__pyx_v_self), __pyx_v_tree, __pyx_v_X, __pyx_v_y, __pyx_v_sample_weight); + + /* "sklearn/tree/_tree.pyx":2617 + * self.max_depth = max_depth + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_2build(struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_weight) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("build", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_2.__pyx_n = 1; + __pyx_t_2.sample_weight = __pyx_v_sample_weight; + __pyx_t_1 = __pyx_vtabptr_7sklearn_4tree_5_tree_DepthFirstTreeBuilder->__pyx_base.build(((struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *)__pyx_v_self), __pyx_v_tree, __pyx_v_X, __pyx_v_y, 1, &__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2617; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.DepthFirstTreeBuilder.build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":2742 + * # Best first builder ---------------------------------------------------------- + * + * cdef inline int _add_to_frontier(PriorityHeapRecord* rec, # <<<<<<<<<<<<<< + * PriorityHeap frontier) nogil: + * """Adds record ``rec`` to the priority queue ``frontier``; returns -1 + */ + +static CYTHON_INLINE int __pyx_f_7sklearn_4tree_5_tree__add_to_frontier(struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *__pyx_v_rec, struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_frontier) { + int __pyx_r; + + /* "sklearn/tree/_tree.pyx":2746 + * """Adds record ``rec`` to the priority queue ``frontier``; returns -1 + * on memory-error. """ + * return frontier.push(rec.node_id, rec.start, rec.end, rec.pos, rec.depth, # <<<<<<<<<<<<<< + * rec.is_leaf, rec.improvement, rec.impurity, + * rec.impurity_left, rec.impurity_right) + */ + __pyx_r = ((struct __pyx_vtabstruct_7sklearn_4tree_6_utils_PriorityHeap *)__pyx_v_frontier->__pyx_vtab)->push(__pyx_v_frontier, __pyx_v_rec->node_id, __pyx_v_rec->start, __pyx_v_rec->end, __pyx_v_rec->pos, __pyx_v_rec->depth, __pyx_v_rec->is_leaf, __pyx_v_rec->improvement, __pyx_v_rec->impurity, __pyx_v_rec->impurity_left, __pyx_v_rec->impurity_right); + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":2742 + * # Best first builder ---------------------------------------------------------- + * + * cdef inline int _add_to_frontier(PriorityHeapRecord* rec, # <<<<<<<<<<<<<< + * PriorityHeap frontier) nogil: + * """Adds record ``rec`` to the priority queue ``frontier``; returns -1 + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":2761 + * cdef SIZE_t max_leaf_nodes + * + * def __cinit__(self, Splitter splitter, SIZE_t min_samples_split, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, min_weight_leaf, + * SIZE_t max_depth, SIZE_t max_leaf_nodes): + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_splitter = 0; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_split; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + PyObject *__pyx_v_min_weight_leaf = 0; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_depth; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_leaf_nodes; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_splitter,&__pyx_n_s_min_samples_split,&__pyx_n_s_min_samples_leaf,&__pyx_n_s_min_weight_leaf,&__pyx_n_s_max_depth,&__pyx_n_s_max_leaf_nodes,0}; + PyObject* values[6] = {0,0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_splitter)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_samples_split)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 6, 6, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2761; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_samples_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 6, 6, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2761; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_min_weight_leaf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 6, 6, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2761; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 4: + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_depth)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 6, 6, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2761; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 5: + if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_leaf_nodes)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 6, 6, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2761; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2761; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 6) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + } + __pyx_v_splitter = ((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)values[0]); + __pyx_v_min_samples_split = __Pyx_PyInt_As_Py_intptr_t(values[1]); if (unlikely((__pyx_v_min_samples_split == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2761; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_samples_leaf = __Pyx_PyInt_As_Py_intptr_t(values[2]); if (unlikely((__pyx_v_min_samples_leaf == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2762; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_min_weight_leaf = values[3]; + __pyx_v_max_depth = __Pyx_PyInt_As_Py_intptr_t(values[4]); if (unlikely((__pyx_v_max_depth == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2763; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_max_leaf_nodes = __Pyx_PyInt_As_Py_intptr_t(values[5]); if (unlikely((__pyx_v_max_leaf_nodes == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2763; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 6, 6, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2761; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._tree.BestFirstTreeBuilder.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_splitter), __pyx_ptype_7sklearn_4tree_5_tree_Splitter, 1, "splitter", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2761; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_20BestFirstTreeBuilder___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *)__pyx_v_self), __pyx_v_splitter, __pyx_v_min_samples_split, __pyx_v_min_samples_leaf, __pyx_v_min_weight_leaf, __pyx_v_max_depth, __pyx_v_max_leaf_nodes); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_5_tree_20BestFirstTreeBuilder___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_splitter, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_split, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf, PyObject *__pyx_v_min_weight_leaf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_depth, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_leaf_nodes) { + int __pyx_r; + __Pyx_RefNannyDeclarations + double __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "sklearn/tree/_tree.pyx":2764 + * SIZE_t min_samples_leaf, min_weight_leaf, + * SIZE_t max_depth, SIZE_t max_leaf_nodes): + * self.splitter = splitter # <<<<<<<<<<<<<< + * self.min_samples_split = min_samples_split + * self.min_samples_leaf = min_samples_leaf + */ + __Pyx_INCREF(((PyObject *)__pyx_v_splitter)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_splitter)); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.splitter); + __Pyx_DECREF(((PyObject *)__pyx_v_self->__pyx_base.splitter)); + __pyx_v_self->__pyx_base.splitter = __pyx_v_splitter; + + /* "sklearn/tree/_tree.pyx":2765 + * SIZE_t max_depth, SIZE_t max_leaf_nodes): + * self.splitter = splitter + * self.min_samples_split = min_samples_split # <<<<<<<<<<<<<< + * self.min_samples_leaf = min_samples_leaf + * self.min_weight_leaf = min_weight_leaf + */ + __pyx_v_self->__pyx_base.min_samples_split = __pyx_v_min_samples_split; + + /* "sklearn/tree/_tree.pyx":2766 + * self.splitter = splitter + * self.min_samples_split = min_samples_split + * self.min_samples_leaf = min_samples_leaf # <<<<<<<<<<<<<< + * self.min_weight_leaf = min_weight_leaf + * self.max_depth = max_depth + */ + __pyx_v_self->__pyx_base.min_samples_leaf = __pyx_v_min_samples_leaf; + + /* "sklearn/tree/_tree.pyx":2767 + * self.min_samples_split = min_samples_split + * self.min_samples_leaf = min_samples_leaf + * self.min_weight_leaf = min_weight_leaf # <<<<<<<<<<<<<< + * self.max_depth = max_depth + * self.max_leaf_nodes = max_leaf_nodes + */ + __pyx_t_1 = __pyx_PyFloat_AsDouble(__pyx_v_min_weight_leaf); if (unlikely((__pyx_t_1 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->__pyx_base.min_weight_leaf = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":2768 + * self.min_samples_leaf = min_samples_leaf + * self.min_weight_leaf = min_weight_leaf + * self.max_depth = max_depth # <<<<<<<<<<<<<< + * self.max_leaf_nodes = max_leaf_nodes + * + */ + __pyx_v_self->__pyx_base.max_depth = __pyx_v_max_depth; + + /* "sklearn/tree/_tree.pyx":2769 + * self.min_weight_leaf = min_weight_leaf + * self.max_depth = max_depth + * self.max_leaf_nodes = max_leaf_nodes # <<<<<<<<<<<<<< + * + * cpdef build(self, Tree tree, object X, np.ndarray y, + */ + __pyx_v_self->max_leaf_nodes = __pyx_v_max_leaf_nodes; + + /* "sklearn/tree/_tree.pyx":2761 + * cdef SIZE_t max_leaf_nodes + * + * def __cinit__(self, Splitter splitter, SIZE_t min_samples_split, # <<<<<<<<<<<<<< + * SIZE_t min_samples_leaf, min_weight_leaf, + * SIZE_t max_depth, SIZE_t max_leaf_nodes): + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.tree._tree.BestFirstTreeBuilder.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":2771 + * self.max_leaf_nodes = max_leaf_nodes + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_3build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyObject *__pyx_f_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_build(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_build *__pyx_optional_args) { + + /* "sklearn/tree/_tree.pyx":2772 + * + * cpdef build(self, Tree tree, object X, np.ndarray y, + * np.ndarray sample_weight=None): # <<<<<<<<<<<<<< + * """Build a decision tree from the training set (X, y).""" + * + */ + PyArrayObject *__pyx_v_sample_weight = ((PyArrayObject *)Py_None); + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_sample_weight_ptr; + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_splitter = 0; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_leaf_nodes; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_leaf; + CYTHON_UNUSED double __pyx_v_min_weight_leaf; + CYTHON_UNUSED __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_min_samples_split; + struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_frontier = 0; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord __pyx_v_record; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord __pyx_v_split_node_left; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord __pyx_v_split_node_right; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_node_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_split_nodes; + int __pyx_v_is_leaf; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_max_depth_seen; + int __pyx_v_rc; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_node; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_init_capacity; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *(*__pyx_t_7)(PyObject *); + int __pyx_t_8; + int __pyx_t_9; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_10; + double __pyx_t_11; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_t_12; + int __pyx_t_13; + struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("build", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_sample_weight = __pyx_optional_args->sample_weight; + } + } + __Pyx_INCREF(__pyx_v_X); + __Pyx_INCREF((PyObject *)__pyx_v_y); + __Pyx_INCREF((PyObject *)__pyx_v_sample_weight); + + /* "sklearn/tree/_tree.pyx":2771 + * self.max_leaf_nodes = max_leaf_nodes + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + /* Check if called by wrapper */ + if (unlikely(__pyx_skip_dispatch)) ; + /* Check if overridden in Python */ + else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_build); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_3build)) { + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_3 = __pyx_t_1; __pyx_t_4 = NULL; + __pyx_t_5 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_5 = 1; + } + } + __pyx_t_6 = PyTuple_New(4+__pyx_t_5); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (__pyx_t_4) { + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + } + __Pyx_INCREF(((PyObject *)__pyx_v_tree)); + PyTuple_SET_ITEM(__pyx_t_6, 0+__pyx_t_5, ((PyObject *)__pyx_v_tree)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_tree)); + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_6, 1+__pyx_t_5, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __Pyx_INCREF(((PyObject *)__pyx_v_y)); + PyTuple_SET_ITEM(__pyx_t_6, 2+__pyx_t_5, ((PyObject *)__pyx_v_y)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_y)); + __Pyx_INCREF(((PyObject *)__pyx_v_sample_weight)); + PyTuple_SET_ITEM(__pyx_t_6, 3+__pyx_t_5, ((PyObject *)__pyx_v_sample_weight)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_sample_weight)); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "sklearn/tree/_tree.pyx":2776 + * + * # check input + * X, y, sample_weight = self._check_input(X, y, sample_weight) # <<<<<<<<<<<<<< + * + * cdef DOUBLE_t* sample_weight_ptr = NULL + */ + __pyx_t_1 = __pyx_f_7sklearn_4tree_5_tree_11TreeBuilder__check_input(((struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *)__pyx_v_self), __pyx_v_X, __pyx_v_y, __pyx_v_sample_weight); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 3)) { + if (size > 3) __Pyx_RaiseTooManyValuesError(3); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 2); + } else { + __pyx_t_2 = PyList_GET_ITEM(sequence, 0); + __pyx_t_3 = PyList_GET_ITEM(sequence, 1); + __pyx_t_6 = PyList_GET_ITEM(sequence, 2); + } + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_6); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_7 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_2 = __pyx_t_7(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_3 = __pyx_t_7(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 2; __pyx_t_6 = __pyx_t_7(__pyx_t_4); if (unlikely(!__pyx_t_6)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_4), 3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = NULL; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_7 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L4_unpacking_done:; + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2776; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF_SET(__pyx_v_X, __pyx_t_2); + __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_y, ((PyArrayObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_sample_weight, ((PyArrayObject *)__pyx_t_6)); + __pyx_t_6 = 0; + + /* "sklearn/tree/_tree.pyx":2778 + * X, y, sample_weight = self._check_input(X, y, sample_weight) + * + * cdef DOUBLE_t* sample_weight_ptr = NULL # <<<<<<<<<<<<<< + * if sample_weight is not None: + * sample_weight_ptr = sample_weight.data + */ + __pyx_v_sample_weight_ptr = NULL; + + /* "sklearn/tree/_tree.pyx":2779 + * + * cdef DOUBLE_t* sample_weight_ptr = NULL + * if sample_weight is not None: # <<<<<<<<<<<<<< + * sample_weight_ptr = sample_weight.data + * + */ + __pyx_t_8 = (((PyObject *)__pyx_v_sample_weight) != Py_None); + __pyx_t_9 = (__pyx_t_8 != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2780 + * cdef DOUBLE_t* sample_weight_ptr = NULL + * if sample_weight is not None: + * sample_weight_ptr = sample_weight.data # <<<<<<<<<<<<<< + * + * # Parameters + */ + __pyx_v_sample_weight_ptr = ((__pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *)__pyx_v_sample_weight->data); + goto __pyx_L5; + } + __pyx_L5:; + + /* "sklearn/tree/_tree.pyx":2783 + * + * # Parameters + * cdef Splitter splitter = self.splitter # <<<<<<<<<<<<<< + * cdef SIZE_t max_leaf_nodes = self.max_leaf_nodes + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + */ + __pyx_t_1 = ((PyObject *)__pyx_v_self->__pyx_base.splitter); + __Pyx_INCREF(__pyx_t_1); + __pyx_v_splitter = ((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":2784 + * # Parameters + * cdef Splitter splitter = self.splitter + * cdef SIZE_t max_leaf_nodes = self.max_leaf_nodes # <<<<<<<<<<<<<< + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf + */ + __pyx_t_10 = __pyx_v_self->max_leaf_nodes; + __pyx_v_max_leaf_nodes = __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":2785 + * cdef Splitter splitter = self.splitter + * cdef SIZE_t max_leaf_nodes = self.max_leaf_nodes + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf # <<<<<<<<<<<<<< + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef SIZE_t min_samples_split = self.min_samples_split + */ + __pyx_t_10 = __pyx_v_self->__pyx_base.min_samples_leaf; + __pyx_v_min_samples_leaf = __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":2786 + * cdef SIZE_t max_leaf_nodes = self.max_leaf_nodes + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf # <<<<<<<<<<<<<< + * cdef SIZE_t min_samples_split = self.min_samples_split + * + */ + __pyx_t_11 = __pyx_v_self->__pyx_base.min_weight_leaf; + __pyx_v_min_weight_leaf = __pyx_t_11; + + /* "sklearn/tree/_tree.pyx":2787 + * cdef SIZE_t min_samples_leaf = self.min_samples_leaf + * cdef double min_weight_leaf = self.min_weight_leaf + * cdef SIZE_t min_samples_split = self.min_samples_split # <<<<<<<<<<<<<< + * + * # Recursive partition (without actual recursion) + */ + __pyx_t_10 = __pyx_v_self->__pyx_base.min_samples_split; + __pyx_v_min_samples_split = __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":2790 + * + * # Recursive partition (without actual recursion) + * splitter.init(X, y, sample_weight_ptr) # <<<<<<<<<<<<<< + * + * cdef PriorityHeap frontier = PriorityHeap(INITIAL_STACK_SIZE) + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *)__pyx_v_splitter->__pyx_vtab)->init(__pyx_v_splitter, __pyx_v_X, __pyx_v_y, __pyx_v_sample_weight_ptr); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":2792 + * splitter.init(X, y, sample_weight_ptr) + * + * cdef PriorityHeap frontier = PriorityHeap(INITIAL_STACK_SIZE) # <<<<<<<<<<<<<< + * cdef PriorityHeapRecord record + * cdef PriorityHeapRecord split_node_left + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_7sklearn_4tree_5_tree_INITIAL_STACK_SIZE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_6_utils_PriorityHeap)), __pyx_t_6, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_frontier = ((struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":2797 + * cdef PriorityHeapRecord split_node_right + * + * cdef SIZE_t n_node_samples = splitter.n_samples # <<<<<<<<<<<<<< + * cdef SIZE_t max_split_nodes = max_leaf_nodes - 1 + * cdef bint is_leaf + */ + __pyx_t_10 = __pyx_v_splitter->n_samples; + __pyx_v_n_node_samples = __pyx_t_10; + + /* "sklearn/tree/_tree.pyx":2798 + * + * cdef SIZE_t n_node_samples = splitter.n_samples + * cdef SIZE_t max_split_nodes = max_leaf_nodes - 1 # <<<<<<<<<<<<<< + * cdef bint is_leaf + * cdef SIZE_t max_depth_seen = -1 + */ + __pyx_v_max_split_nodes = (__pyx_v_max_leaf_nodes - 1); + + /* "sklearn/tree/_tree.pyx":2800 + * cdef SIZE_t max_split_nodes = max_leaf_nodes - 1 + * cdef bint is_leaf + * cdef SIZE_t max_depth_seen = -1 # <<<<<<<<<<<<<< + * cdef int rc = 0 + * cdef Node* node + */ + __pyx_v_max_depth_seen = -1; + + /* "sklearn/tree/_tree.pyx":2801 + * cdef bint is_leaf + * cdef SIZE_t max_depth_seen = -1 + * cdef int rc = 0 # <<<<<<<<<<<<<< + * cdef Node* node + * + */ + __pyx_v_rc = 0; + + /* "sklearn/tree/_tree.pyx":2805 + * + * # Initial capacity + * cdef SIZE_t init_capacity = max_split_nodes + max_leaf_nodes # <<<<<<<<<<<<<< + * tree._resize(init_capacity) + * + */ + __pyx_v_init_capacity = (__pyx_v_max_split_nodes + __pyx_v_max_leaf_nodes); + + /* "sklearn/tree/_tree.pyx":2806 + * # Initial capacity + * cdef SIZE_t init_capacity = max_split_nodes + max_leaf_nodes + * tree._resize(init_capacity) # <<<<<<<<<<<<<< + * + * with nogil: + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_tree->__pyx_vtab)->_resize(__pyx_v_tree, __pyx_v_init_capacity); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":2808 + * tree._resize(init_capacity) + * + * with nogil: # <<<<<<<<<<<<<< + * # add root to frontier + * rc = self._add_split_node(splitter, tree, 0, n_node_samples, + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/tree/_tree.pyx":2810 + * with nogil: + * # add root to frontier + * rc = self._add_split_node(splitter, tree, 0, n_node_samples, # <<<<<<<<<<<<<< + * INFINITY, IS_FIRST, IS_LEFT, NULL, 0, + * &split_node_left) + */ + __pyx_v_rc = __pyx_f_7sklearn_4tree_5_tree_20BestFirstTreeBuilder__add_split_node(__pyx_v_self, __pyx_v_splitter, __pyx_v_tree, 0, __pyx_v_n_node_samples, __pyx_v_7sklearn_4tree_5_tree_INFINITY, __pyx_v_7sklearn_4tree_5_tree_IS_FIRST, __pyx_v_7sklearn_4tree_5_tree_IS_LEFT, NULL, 0, (&__pyx_v_split_node_left)); + + /* "sklearn/tree/_tree.pyx":2813 + * INFINITY, IS_FIRST, IS_LEFT, NULL, 0, + * &split_node_left) + * if rc >= 0: # <<<<<<<<<<<<<< + * rc = _add_to_frontier(&split_node_left, frontier) + * if rc == -1: + */ + __pyx_t_9 = ((__pyx_v_rc >= 0) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2814 + * &split_node_left) + * if rc >= 0: + * rc = _add_to_frontier(&split_node_left, frontier) # <<<<<<<<<<<<<< + * if rc == -1: + * raise MemoryError() + */ + __pyx_v_rc = __pyx_f_7sklearn_4tree_5_tree__add_to_frontier((&__pyx_v_split_node_left), __pyx_v_frontier); + goto __pyx_L9; + } + __pyx_L9:; + } + + /* "sklearn/tree/_tree.pyx":2808 + * tree._resize(init_capacity) + * + * with nogil: # <<<<<<<<<<<<<< + * # add root to frontier + * rc = self._add_split_node(splitter, tree, 0, n_node_samples, + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L8; + } + __pyx_L8:; + } + } + + /* "sklearn/tree/_tree.pyx":2815 + * if rc >= 0: + * rc = _add_to_frontier(&split_node_left, frontier) + * if rc == -1: # <<<<<<<<<<<<<< + * raise MemoryError() + * + */ + __pyx_t_9 = ((__pyx_v_rc == -1) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2816 + * rc = _add_to_frontier(&split_node_left, frontier) + * if rc == -1: + * raise MemoryError() # <<<<<<<<<<<<<< + * + * with nogil: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":2818 + * raise MemoryError() + * + * with nogil: # <<<<<<<<<<<<<< + * while not frontier.is_empty(): + * frontier.pop(&record) + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/tree/_tree.pyx":2819 + * + * with nogil: + * while not frontier.is_empty(): # <<<<<<<<<<<<<< + * frontier.pop(&record) + * + */ + while (1) { + __pyx_t_9 = ((!(((struct __pyx_vtabstruct_7sklearn_4tree_6_utils_PriorityHeap *)__pyx_v_frontier->__pyx_vtab)->is_empty(__pyx_v_frontier) != 0)) != 0); + if (!__pyx_t_9) break; + + /* "sklearn/tree/_tree.pyx":2820 + * with nogil: + * while not frontier.is_empty(): + * frontier.pop(&record) # <<<<<<<<<<<<<< + * + * node = &tree.nodes[record.node_id] + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_6_utils_PriorityHeap *)__pyx_v_frontier->__pyx_vtab)->pop(__pyx_v_frontier, (&__pyx_v_record)); + + /* "sklearn/tree/_tree.pyx":2822 + * frontier.pop(&record) + * + * node = &tree.nodes[record.node_id] # <<<<<<<<<<<<<< + * is_leaf = (record.is_leaf or max_split_nodes <= 0) + * + */ + __pyx_v_node = (&(__pyx_v_tree->nodes[__pyx_v_record.node_id])); + + /* "sklearn/tree/_tree.pyx":2823 + * + * node = &tree.nodes[record.node_id] + * is_leaf = (record.is_leaf or max_split_nodes <= 0) # <<<<<<<<<<<<<< + * + * if is_leaf: + */ + __pyx_t_8 = (__pyx_v_record.is_leaf != 0); + if (!__pyx_t_8) { + } else { + __pyx_t_9 = __pyx_t_8; + goto __pyx_L16_bool_binop_done; + } + __pyx_t_8 = ((__pyx_v_max_split_nodes <= 0) != 0); + __pyx_t_9 = __pyx_t_8; + __pyx_L16_bool_binop_done:; + __pyx_v_is_leaf = __pyx_t_9; + + /* "sklearn/tree/_tree.pyx":2825 + * is_leaf = (record.is_leaf or max_split_nodes <= 0) + * + * if is_leaf: # <<<<<<<<<<<<<< + * # Node is not expandable; set node as leaf + * node.left_child = _TREE_LEAF + */ + __pyx_t_9 = (__pyx_v_is_leaf != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2827 + * if is_leaf: + * # Node is not expandable; set node as leaf + * node.left_child = _TREE_LEAF # <<<<<<<<<<<<<< + * node.right_child = _TREE_LEAF + * node.feature = _TREE_UNDEFINED + */ + __pyx_v_node->left_child = __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF; + + /* "sklearn/tree/_tree.pyx":2828 + * # Node is not expandable; set node as leaf + * node.left_child = _TREE_LEAF + * node.right_child = _TREE_LEAF # <<<<<<<<<<<<<< + * node.feature = _TREE_UNDEFINED + * node.threshold = _TREE_UNDEFINED + */ + __pyx_v_node->right_child = __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF; + + /* "sklearn/tree/_tree.pyx":2829 + * node.left_child = _TREE_LEAF + * node.right_child = _TREE_LEAF + * node.feature = _TREE_UNDEFINED # <<<<<<<<<<<<<< + * node.threshold = _TREE_UNDEFINED + * + */ + __pyx_v_node->feature = __pyx_v_7sklearn_4tree_5_tree__TREE_UNDEFINED; + + /* "sklearn/tree/_tree.pyx":2830 + * node.right_child = _TREE_LEAF + * node.feature = _TREE_UNDEFINED + * node.threshold = _TREE_UNDEFINED # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_v_node->threshold = __pyx_v_7sklearn_4tree_5_tree__TREE_UNDEFINED; + goto __pyx_L18; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":2836 + * + * # Decrement number of split nodes available + * max_split_nodes -= 1 # <<<<<<<<<<<<<< + * + * # Compute left split node + */ + __pyx_v_max_split_nodes = (__pyx_v_max_split_nodes - 1); + + /* "sklearn/tree/_tree.pyx":2839 + * + * # Compute left split node + * rc = self._add_split_node(splitter, tree, # <<<<<<<<<<<<<< + * record.start, record.pos, + * record.impurity_left, + */ + __pyx_v_rc = __pyx_f_7sklearn_4tree_5_tree_20BestFirstTreeBuilder__add_split_node(__pyx_v_self, __pyx_v_splitter, __pyx_v_tree, __pyx_v_record.start, __pyx_v_record.pos, __pyx_v_record.impurity_left, __pyx_v_7sklearn_4tree_5_tree_IS_NOT_FIRST, __pyx_v_7sklearn_4tree_5_tree_IS_LEFT, __pyx_v_node, (__pyx_v_record.depth + 1), (&__pyx_v_split_node_left)); + + /* "sklearn/tree/_tree.pyx":2845 + * record.depth + 1, + * &split_node_left) + * if rc == -1: # <<<<<<<<<<<<<< + * break + * + */ + __pyx_t_9 = ((__pyx_v_rc == -1) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2846 + * &split_node_left) + * if rc == -1: + * break # <<<<<<<<<<<<<< + * + * # tree.nodes may have changed + */ + goto __pyx_L15_break; + } + + /* "sklearn/tree/_tree.pyx":2849 + * + * # tree.nodes may have changed + * node = &tree.nodes[record.node_id] # <<<<<<<<<<<<<< + * + * # Compute right split node + */ + __pyx_v_node = (&(__pyx_v_tree->nodes[__pyx_v_record.node_id])); + + /* "sklearn/tree/_tree.pyx":2852 + * + * # Compute right split node + * rc = self._add_split_node(splitter, tree, record.pos, # <<<<<<<<<<<<<< + * record.end, + * record.impurity_right, + */ + __pyx_v_rc = __pyx_f_7sklearn_4tree_5_tree_20BestFirstTreeBuilder__add_split_node(__pyx_v_self, __pyx_v_splitter, __pyx_v_tree, __pyx_v_record.pos, __pyx_v_record.end, __pyx_v_record.impurity_right, __pyx_v_7sklearn_4tree_5_tree_IS_NOT_FIRST, __pyx_v_7sklearn_4tree_5_tree_IS_NOT_LEFT, __pyx_v_node, (__pyx_v_record.depth + 1), (&__pyx_v_split_node_right)); + + /* "sklearn/tree/_tree.pyx":2858 + * record.depth + 1, + * &split_node_right) + * if rc == -1: # <<<<<<<<<<<<<< + * break + * + */ + __pyx_t_9 = ((__pyx_v_rc == -1) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2859 + * &split_node_right) + * if rc == -1: + * break # <<<<<<<<<<<<<< + * + * # Add nodes to queue + */ + goto __pyx_L15_break; + } + + /* "sklearn/tree/_tree.pyx":2862 + * + * # Add nodes to queue + * rc = _add_to_frontier(&split_node_left, frontier) # <<<<<<<<<<<<<< + * if rc == -1: + * break + */ + __pyx_v_rc = __pyx_f_7sklearn_4tree_5_tree__add_to_frontier((&__pyx_v_split_node_left), __pyx_v_frontier); + + /* "sklearn/tree/_tree.pyx":2863 + * # Add nodes to queue + * rc = _add_to_frontier(&split_node_left, frontier) + * if rc == -1: # <<<<<<<<<<<<<< + * break + * + */ + __pyx_t_9 = ((__pyx_v_rc == -1) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2864 + * rc = _add_to_frontier(&split_node_left, frontier) + * if rc == -1: + * break # <<<<<<<<<<<<<< + * + * rc = _add_to_frontier(&split_node_right, frontier) + */ + goto __pyx_L15_break; + } + + /* "sklearn/tree/_tree.pyx":2866 + * break + * + * rc = _add_to_frontier(&split_node_right, frontier) # <<<<<<<<<<<<<< + * if rc == -1: + * break + */ + __pyx_v_rc = __pyx_f_7sklearn_4tree_5_tree__add_to_frontier((&__pyx_v_split_node_right), __pyx_v_frontier); + + /* "sklearn/tree/_tree.pyx":2867 + * + * rc = _add_to_frontier(&split_node_right, frontier) + * if rc == -1: # <<<<<<<<<<<<<< + * break + * + */ + __pyx_t_9 = ((__pyx_v_rc == -1) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2868 + * rc = _add_to_frontier(&split_node_right, frontier) + * if rc == -1: + * break # <<<<<<<<<<<<<< + * + * if record.depth > max_depth_seen: + */ + goto __pyx_L15_break; + } + } + __pyx_L18:; + + /* "sklearn/tree/_tree.pyx":2870 + * break + * + * if record.depth > max_depth_seen: # <<<<<<<<<<<<<< + * max_depth_seen = record.depth + * + */ + __pyx_t_9 = ((__pyx_v_record.depth > __pyx_v_max_depth_seen) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2871 + * + * if record.depth > max_depth_seen: + * max_depth_seen = record.depth # <<<<<<<<<<<<<< + * + * if rc >= 0: + */ + __pyx_t_12 = __pyx_v_record.depth; + __pyx_v_max_depth_seen = __pyx_t_12; + goto __pyx_L23; + } + __pyx_L23:; + } + __pyx_L15_break:; + + /* "sklearn/tree/_tree.pyx":2873 + * max_depth_seen = record.depth + * + * if rc >= 0: # <<<<<<<<<<<<<< + * rc = tree._resize_c(tree.node_count) + * + */ + __pyx_t_9 = ((__pyx_v_rc >= 0) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2874 + * + * if rc >= 0: + * rc = tree._resize_c(tree.node_count) # <<<<<<<<<<<<<< + * + * if rc >= 0: + */ + __pyx_t_14.__pyx_n = 1; + __pyx_t_14.capacity = __pyx_v_tree->node_count; + __pyx_t_13 = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_tree->__pyx_vtab)->_resize_c(__pyx_v_tree, &__pyx_t_14); + __pyx_v_rc = __pyx_t_13; + goto __pyx_L24; + } + __pyx_L24:; + + /* "sklearn/tree/_tree.pyx":2876 + * rc = tree._resize_c(tree.node_count) + * + * if rc >= 0: # <<<<<<<<<<<<<< + * tree.max_depth = max_depth_seen + * + */ + __pyx_t_9 = ((__pyx_v_rc >= 0) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2877 + * + * if rc >= 0: + * tree.max_depth = max_depth_seen # <<<<<<<<<<<<<< + * + * if rc == -1: + */ + __pyx_v_tree->max_depth = __pyx_v_max_depth_seen; + goto __pyx_L25; + } + __pyx_L25:; + } + + /* "sklearn/tree/_tree.pyx":2818 + * raise MemoryError() + * + * with nogil: # <<<<<<<<<<<<<< + * while not frontier.is_empty(): + * frontier.pop(&record) + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L13; + } + __pyx_L13:; + } + } + + /* "sklearn/tree/_tree.pyx":2879 + * tree.max_depth = max_depth_seen + * + * if rc == -1: # <<<<<<<<<<<<<< + * raise MemoryError() + * + */ + __pyx_t_9 = ((__pyx_v_rc == -1) != 0); + if (__pyx_t_9) { + + /* "sklearn/tree/_tree.pyx":2880 + * + * if rc == -1: + * raise MemoryError() # <<<<<<<<<<<<<< + * + * cdef inline int _add_split_node(self, Splitter splitter, Tree tree, + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2880; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":2771 + * self.max_leaf_nodes = max_leaf_nodes + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("sklearn.tree._tree.BestFirstTreeBuilder.build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_splitter); + __Pyx_XDECREF((PyObject *)__pyx_v_frontier); + __Pyx_XDECREF(__pyx_v_X); + __Pyx_XDECREF((PyObject *)__pyx_v_y); + __Pyx_XDECREF((PyObject *)__pyx_v_sample_weight); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_3build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_2build[] = "Build a decision tree from the training set (X, y)."; +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_3build(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree = 0; + PyObject *__pyx_v_X = 0; + PyArrayObject *__pyx_v_y = 0; + PyArrayObject *__pyx_v_sample_weight = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("build (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_tree,&__pyx_n_s_X,&__pyx_n_s_y,&__pyx_n_s_sample_weight,0}; + PyObject* values[4] = {0,0,0,0}; + + /* "sklearn/tree/_tree.pyx":2772 + * + * cpdef build(self, Tree tree, object X, np.ndarray y, + * np.ndarray sample_weight=None): # <<<<<<<<<<<<<< + * """Build a decision tree from the training set (X, y).""" + * + */ + values[3] = (PyObject *)((PyArrayObject *)Py_None); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_tree)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build", 0, 3, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2771; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build", 0, 3, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2771; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sample_weight); + if (value) { values[3] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "build") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2771; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_tree = ((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)values[0]); + __pyx_v_X = values[1]; + __pyx_v_y = ((PyArrayObject *)values[2]); + __pyx_v_sample_weight = ((PyArrayObject *)values[3]); + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("build", 0, 3, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2771; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._tree.BestFirstTreeBuilder.build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_tree), __pyx_ptype_7sklearn_4tree_5_tree_Tree, 1, "tree", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_2build(((struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *)__pyx_v_self), __pyx_v_tree, __pyx_v_X, __pyx_v_y, __pyx_v_sample_weight); + + /* "sklearn/tree/_tree.pyx":2771 + * self.max_leaf_nodes = max_leaf_nodes + * + * cpdef build(self, Tree tree, object X, np.ndarray y, # <<<<<<<<<<<<<< + * np.ndarray sample_weight=None): + * """Build a decision tree from the training set (X, y).""" + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_2build(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_sample_weight) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("build", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_2.__pyx_n = 1; + __pyx_t_2.sample_weight = __pyx_v_sample_weight; + __pyx_t_1 = __pyx_vtabptr_7sklearn_4tree_5_tree_BestFirstTreeBuilder->__pyx_base.build(((struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *)__pyx_v_self), __pyx_v_tree, __pyx_v_X, __pyx_v_y, 1, &__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.BestFirstTreeBuilder.build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":2882 + * raise MemoryError() + * + * cdef inline int _add_split_node(self, Splitter splitter, Tree tree, # <<<<<<<<<<<<<< + * SIZE_t start, SIZE_t end, double impurity, + * bint is_first, bint is_left, Node* parent, + */ + +static CYTHON_INLINE int __pyx_f_7sklearn_4tree_5_tree_20BestFirstTreeBuilder__add_split_node(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *__pyx_v_self, struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *__pyx_v_splitter, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_tree, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_end, double __pyx_v_impurity, int __pyx_v_is_first, int __pyx_v_is_left, struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_parent, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_depth, struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *__pyx_v_res) { + struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord __pyx_v_split; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_node_id; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_node_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_constant_features; + CYTHON_UNUSED double __pyx_v_weighted_n_samples; + double __pyx_v_weighted_n_node_samples; + int __pyx_v_is_leaf; + int __pyx_r; + double __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + ptrdiff_t __pyx_t_4; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_5; + + /* "sklearn/tree/_tree.pyx":2891 + * cdef SIZE_t node_id + * cdef SIZE_t n_node_samples + * cdef SIZE_t n_constant_features = 0 # <<<<<<<<<<<<<< + * cdef double weighted_n_samples = splitter.weighted_n_samples + * cdef double weighted_n_node_samples + */ + __pyx_v_n_constant_features = 0; + + /* "sklearn/tree/_tree.pyx":2892 + * cdef SIZE_t n_node_samples + * cdef SIZE_t n_constant_features = 0 + * cdef double weighted_n_samples = splitter.weighted_n_samples # <<<<<<<<<<<<<< + * cdef double weighted_n_node_samples + * cdef bint is_leaf + */ + __pyx_t_1 = __pyx_v_splitter->weighted_n_samples; + __pyx_v_weighted_n_samples = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":2898 + * cdef double imp_diff + * + * splitter.node_reset(start, end, &weighted_n_node_samples) # <<<<<<<<<<<<<< + * + * if is_first: + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *)__pyx_v_splitter->__pyx_vtab)->node_reset(__pyx_v_splitter, __pyx_v_start, __pyx_v_end, (&__pyx_v_weighted_n_node_samples)); + + /* "sklearn/tree/_tree.pyx":2900 + * splitter.node_reset(start, end, &weighted_n_node_samples) + * + * if is_first: # <<<<<<<<<<<<<< + * impurity = splitter.node_impurity() + * + */ + __pyx_t_2 = (__pyx_v_is_first != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":2901 + * + * if is_first: + * impurity = splitter.node_impurity() # <<<<<<<<<<<<<< + * + * n_node_samples = end - start + */ + __pyx_v_impurity = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *)__pyx_v_splitter->__pyx_vtab)->node_impurity(__pyx_v_splitter); + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/tree/_tree.pyx":2903 + * impurity = splitter.node_impurity() + * + * n_node_samples = end - start # <<<<<<<<<<<<<< + * is_leaf = ((depth > self.max_depth) or + * (n_node_samples < self.min_samples_split) or + */ + __pyx_v_n_node_samples = (__pyx_v_end - __pyx_v_start); + + /* "sklearn/tree/_tree.pyx":2904 + * + * n_node_samples = end - start + * is_leaf = ((depth > self.max_depth) or # <<<<<<<<<<<<<< + * (n_node_samples < self.min_samples_split) or + * (n_node_samples < 2 * self.min_samples_leaf) or + */ + __pyx_t_3 = ((__pyx_v_depth > __pyx_v_self->__pyx_base.max_depth) != 0); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":2905 + * n_node_samples = end - start + * is_leaf = ((depth > self.max_depth) or + * (n_node_samples < self.min_samples_split) or # <<<<<<<<<<<<<< + * (n_node_samples < 2 * self.min_samples_leaf) or + * (weighted_n_node_samples < self.min_weight_leaf) or + */ + __pyx_t_3 = ((__pyx_v_n_node_samples < __pyx_v_self->__pyx_base.min_samples_split) != 0); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":2906 + * is_leaf = ((depth > self.max_depth) or + * (n_node_samples < self.min_samples_split) or + * (n_node_samples < 2 * self.min_samples_leaf) or # <<<<<<<<<<<<<< + * (weighted_n_node_samples < self.min_weight_leaf) or + * (impurity <= MIN_IMPURITY_SPLIT)) + */ + __pyx_t_3 = ((__pyx_v_n_node_samples < (2 * __pyx_v_self->__pyx_base.min_samples_leaf)) != 0); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":2907 + * (n_node_samples < self.min_samples_split) or + * (n_node_samples < 2 * self.min_samples_leaf) or + * (weighted_n_node_samples < self.min_weight_leaf) or # <<<<<<<<<<<<<< + * (impurity <= MIN_IMPURITY_SPLIT)) + * + */ + __pyx_t_3 = ((__pyx_v_weighted_n_node_samples < __pyx_v_self->__pyx_base.min_weight_leaf) != 0); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":2908 + * (n_node_samples < 2 * self.min_samples_leaf) or + * (weighted_n_node_samples < self.min_weight_leaf) or + * (impurity <= MIN_IMPURITY_SPLIT)) # <<<<<<<<<<<<<< + * + * if not is_leaf: + */ + __pyx_t_3 = ((__pyx_v_impurity <= __pyx_v_7sklearn_4tree_5_tree_MIN_IMPURITY_SPLIT) != 0); + __pyx_t_2 = __pyx_t_3; + __pyx_L4_bool_binop_done:; + __pyx_v_is_leaf = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":2910 + * (impurity <= MIN_IMPURITY_SPLIT)) + * + * if not is_leaf: # <<<<<<<<<<<<<< + * splitter.node_split(impurity, &split, &n_constant_features) + * is_leaf = is_leaf or (split.pos >= end) + */ + __pyx_t_2 = ((!(__pyx_v_is_leaf != 0)) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":2911 + * + * if not is_leaf: + * splitter.node_split(impurity, &split, &n_constant_features) # <<<<<<<<<<<<<< + * is_leaf = is_leaf or (split.pos >= end) + * + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *)__pyx_v_splitter->__pyx_vtab)->node_split(__pyx_v_splitter, __pyx_v_impurity, (&__pyx_v_split), (&__pyx_v_n_constant_features)); + + /* "sklearn/tree/_tree.pyx":2912 + * if not is_leaf: + * splitter.node_split(impurity, &split, &n_constant_features) + * is_leaf = is_leaf or (split.pos >= end) # <<<<<<<<<<<<<< + * + * node_id = tree._add_node(parent - tree.nodes + */ + __pyx_t_3 = (__pyx_v_is_leaf != 0); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L10_bool_binop_done; + } + __pyx_t_3 = ((__pyx_v_split.pos >= __pyx_v_end) != 0); + __pyx_t_2 = __pyx_t_3; + __pyx_L10_bool_binop_done:; + __pyx_v_is_leaf = __pyx_t_2; + goto __pyx_L9; + } + __pyx_L9:; + + /* "sklearn/tree/_tree.pyx":2915 + * + * node_id = tree._add_node(parent - tree.nodes + * if parent != NULL # <<<<<<<<<<<<<< + * else _TREE_UNDEFINED, + * is_left, is_leaf, + */ + if (((__pyx_v_parent != NULL) != 0)) { + + /* "sklearn/tree/_tree.pyx":2914 + * is_leaf = is_leaf or (split.pos >= end) + * + * node_id = tree._add_node(parent - tree.nodes # <<<<<<<<<<<<<< + * if parent != NULL + * else _TREE_UNDEFINED, + */ + __pyx_t_4 = (__pyx_v_parent - __pyx_v_tree->nodes); + } else { + + /* "sklearn/tree/_tree.pyx":2916 + * node_id = tree._add_node(parent - tree.nodes + * if parent != NULL + * else _TREE_UNDEFINED, # <<<<<<<<<<<<<< + * is_left, is_leaf, + * split.feature, split.threshold, impurity, n_node_samples, + */ + __pyx_t_4 = __pyx_v_7sklearn_4tree_5_tree__TREE_UNDEFINED; + } + + /* "sklearn/tree/_tree.pyx":2914 + * is_leaf = is_leaf or (split.pos >= end) + * + * node_id = tree._add_node(parent - tree.nodes # <<<<<<<<<<<<<< + * if parent != NULL + * else _TREE_UNDEFINED, + */ + __pyx_v_node_id = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_tree->__pyx_vtab)->_add_node(__pyx_v_tree, __pyx_t_4, __pyx_v_is_left, __pyx_v_is_leaf, __pyx_v_split.feature, __pyx_v_split.threshold, __pyx_v_impurity, __pyx_v_n_node_samples, __pyx_v_weighted_n_node_samples); + + /* "sklearn/tree/_tree.pyx":2920 + * split.feature, split.threshold, impurity, n_node_samples, + * weighted_n_node_samples) + * if node_id == (-1): # <<<<<<<<<<<<<< + * return -1 + * + */ + __pyx_t_2 = ((__pyx_v_node_id == ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)-1)) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":2921 + * weighted_n_node_samples) + * if node_id == (-1): + * return -1 # <<<<<<<<<<<<<< + * + * # compute values also for split nodes (might become leafs later). + */ + __pyx_r = -1; + goto __pyx_L0; + } + + /* "sklearn/tree/_tree.pyx":2924 + * + * # compute values also for split nodes (might become leafs later). + * splitter.node_value(tree.value + node_id * tree.value_stride) # <<<<<<<<<<<<<< + * + * res.node_id = node_id + */ + ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter *)__pyx_v_splitter->__pyx_vtab)->node_value(__pyx_v_splitter, (__pyx_v_tree->value + (__pyx_v_node_id * __pyx_v_tree->value_stride))); + + /* "sklearn/tree/_tree.pyx":2926 + * splitter.node_value(tree.value + node_id * tree.value_stride) + * + * res.node_id = node_id # <<<<<<<<<<<<<< + * res.start = start + * res.end = end + */ + __pyx_v_res->node_id = __pyx_v_node_id; + + /* "sklearn/tree/_tree.pyx":2927 + * + * res.node_id = node_id + * res.start = start # <<<<<<<<<<<<<< + * res.end = end + * res.depth = depth + */ + __pyx_v_res->start = __pyx_v_start; + + /* "sklearn/tree/_tree.pyx":2928 + * res.node_id = node_id + * res.start = start + * res.end = end # <<<<<<<<<<<<<< + * res.depth = depth + * res.impurity = impurity + */ + __pyx_v_res->end = __pyx_v_end; + + /* "sklearn/tree/_tree.pyx":2929 + * res.start = start + * res.end = end + * res.depth = depth # <<<<<<<<<<<<<< + * res.impurity = impurity + * + */ + __pyx_v_res->depth = __pyx_v_depth; + + /* "sklearn/tree/_tree.pyx":2930 + * res.end = end + * res.depth = depth + * res.impurity = impurity # <<<<<<<<<<<<<< + * + * if not is_leaf: + */ + __pyx_v_res->impurity = __pyx_v_impurity; + + /* "sklearn/tree/_tree.pyx":2932 + * res.impurity = impurity + * + * if not is_leaf: # <<<<<<<<<<<<<< + * # is split node + * res.pos = split.pos + */ + __pyx_t_2 = ((!(__pyx_v_is_leaf != 0)) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":2934 + * if not is_leaf: + * # is split node + * res.pos = split.pos # <<<<<<<<<<<<<< + * res.is_leaf = 0 + * res.improvement = split.improvement + */ + __pyx_t_5 = __pyx_v_split.pos; + __pyx_v_res->pos = __pyx_t_5; + + /* "sklearn/tree/_tree.pyx":2935 + * # is split node + * res.pos = split.pos + * res.is_leaf = 0 # <<<<<<<<<<<<<< + * res.improvement = split.improvement + * res.impurity_left = split.impurity_left + */ + __pyx_v_res->is_leaf = 0; + + /* "sklearn/tree/_tree.pyx":2936 + * res.pos = split.pos + * res.is_leaf = 0 + * res.improvement = split.improvement # <<<<<<<<<<<<<< + * res.impurity_left = split.impurity_left + * res.impurity_right = split.impurity_right + */ + __pyx_t_1 = __pyx_v_split.improvement; + __pyx_v_res->improvement = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":2937 + * res.is_leaf = 0 + * res.improvement = split.improvement + * res.impurity_left = split.impurity_left # <<<<<<<<<<<<<< + * res.impurity_right = split.impurity_right + * + */ + __pyx_t_1 = __pyx_v_split.impurity_left; + __pyx_v_res->impurity_left = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":2938 + * res.improvement = split.improvement + * res.impurity_left = split.impurity_left + * res.impurity_right = split.impurity_right # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_t_1 = __pyx_v_split.impurity_right; + __pyx_v_res->impurity_right = __pyx_t_1; + goto __pyx_L13; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":2942 + * else: + * # is leaf => 0 improvement + * res.pos = end # <<<<<<<<<<<<<< + * res.is_leaf = 1 + * res.improvement = 0.0 + */ + __pyx_v_res->pos = __pyx_v_end; + + /* "sklearn/tree/_tree.pyx":2943 + * # is leaf => 0 improvement + * res.pos = end + * res.is_leaf = 1 # <<<<<<<<<<<<<< + * res.improvement = 0.0 + * res.impurity_left = impurity + */ + __pyx_v_res->is_leaf = 1; + + /* "sklearn/tree/_tree.pyx":2944 + * res.pos = end + * res.is_leaf = 1 + * res.improvement = 0.0 # <<<<<<<<<<<<<< + * res.impurity_left = impurity + * res.impurity_right = impurity + */ + __pyx_v_res->improvement = 0.0; + + /* "sklearn/tree/_tree.pyx":2945 + * res.is_leaf = 1 + * res.improvement = 0.0 + * res.impurity_left = impurity # <<<<<<<<<<<<<< + * res.impurity_right = impurity + * + */ + __pyx_v_res->impurity_left = __pyx_v_impurity; + + /* "sklearn/tree/_tree.pyx":2946 + * res.improvement = 0.0 + * res.impurity_left = impurity + * res.impurity_right = impurity # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_v_res->impurity_right = __pyx_v_impurity; + } + __pyx_L13:; + + /* "sklearn/tree/_tree.pyx":2948 + * res.impurity_right = impurity + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":2882 + * raise MemoryError() + * + * cdef inline int _add_split_node(self, Splitter splitter, Tree tree, # <<<<<<<<<<<<<< + * SIZE_t start, SIZE_t end, double impurity, + * bint is_first, bint is_left, Node* parent, + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3014 + * # (i.e. through `_resize` or `__setstate__`) + * property n_classes: + * def __get__(self): # <<<<<<<<<<<<<< + * # it's small; copy for memory safety + * return sizet_ptr_to_ndarray(self.n_classes, self.n_outputs).copy() + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_classes_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_classes_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_classes___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_classes___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "sklearn/tree/_tree.pyx":3016 + * def __get__(self): + * # it's small; copy for memory safety + * return sizet_ptr_to_ndarray(self.n_classes, self.n_outputs).copy() # <<<<<<<<<<<<<< + * + * property children_left: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_sizet_ptr_to_ndarray(__pyx_v_self->n_classes, __pyx_v_self->n_outputs)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3016; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_copy); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3016; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (__pyx_t_2) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3016; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3016; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3014 + * # (i.e. through `_resize` or `__setstate__`) + * property n_classes: + * def __get__(self): # <<<<<<<<<<<<<< + * # it's small; copy for memory safety + * return sizet_ptr_to_ndarray(self.n_classes, self.n_outputs).copy() + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_classes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3019 + * + * property children_left: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['left_child'][:self.node_count] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13children_left_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13children_left_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_13children_left___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_13children_left___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "sklearn/tree/_tree.pyx":3020 + * property children_left: + * def __get__(self): + * return self._get_node_ndarray()['left_child'][:self.node_count] # <<<<<<<<<<<<<< + * + * property children_right: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_get_node_ndarray(__pyx_v_self)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3020; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_n_s_left_child); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3020; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_t_2, 0, __pyx_v_self->node_count, NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3020; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3019 + * + * property children_left: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['left_child'][:self.node_count] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.children_left.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3023 + * + * property children_right: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['right_child'][:self.node_count] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_14children_right_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_14children_right_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_14children_right___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_14children_right___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "sklearn/tree/_tree.pyx":3024 + * property children_right: + * def __get__(self): + * return self._get_node_ndarray()['right_child'][:self.node_count] # <<<<<<<<<<<<<< + * + * property feature: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_get_node_ndarray(__pyx_v_self)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3024; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_n_s_right_child); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3024; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_t_2, 0, __pyx_v_self->node_count, NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3024; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3023 + * + * property children_right: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['right_child'][:self.node_count] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.children_right.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3027 + * + * property feature: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['feature'][:self.node_count] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_7feature_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_7feature_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_7feature___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_7feature___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "sklearn/tree/_tree.pyx":3028 + * property feature: + * def __get__(self): + * return self._get_node_ndarray()['feature'][:self.node_count] # <<<<<<<<<<<<<< + * + * property threshold: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_get_node_ndarray(__pyx_v_self)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_n_s_feature); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3028; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_t_2, 0, __pyx_v_self->node_count, NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3027 + * + * property feature: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['feature'][:self.node_count] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.feature.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3031 + * + * property threshold: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['threshold'][:self.node_count] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9threshold_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9threshold_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9threshold___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9threshold___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "sklearn/tree/_tree.pyx":3032 + * property threshold: + * def __get__(self): + * return self._get_node_ndarray()['threshold'][:self.node_count] # <<<<<<<<<<<<<< + * + * property impurity: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_get_node_ndarray(__pyx_v_self)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3032; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_n_s_threshold); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3032; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_t_2, 0, __pyx_v_self->node_count, NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3032; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3031 + * + * property threshold: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['threshold'][:self.node_count] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.threshold.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3035 + * + * property impurity: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['impurity'][:self.node_count] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_8impurity_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_8impurity_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_8impurity___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_8impurity___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "sklearn/tree/_tree.pyx":3036 + * property impurity: + * def __get__(self): + * return self._get_node_ndarray()['impurity'][:self.node_count] # <<<<<<<<<<<<<< + * + * property n_node_samples: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_get_node_ndarray(__pyx_v_self)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3036; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_n_s_impurity); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3036; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_t_2, 0, __pyx_v_self->node_count, NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3036; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3035 + * + * property impurity: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['impurity'][:self.node_count] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.impurity.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3039 + * + * property n_node_samples: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['n_node_samples'][:self.node_count] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_14n_node_samples_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_14n_node_samples_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_14n_node_samples___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_14n_node_samples___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "sklearn/tree/_tree.pyx":3040 + * property n_node_samples: + * def __get__(self): + * return self._get_node_ndarray()['n_node_samples'][:self.node_count] # <<<<<<<<<<<<<< + * + * property weighted_n_node_samples: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_get_node_ndarray(__pyx_v_self)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3040; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_n_s_n_node_samples); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3040; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_t_2, 0, __pyx_v_self->node_count, NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3040; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3039 + * + * property n_node_samples: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['n_node_samples'][:self.node_count] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_node_samples.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3043 + * + * property weighted_n_node_samples: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['weighted_n_node_samples'][:self.node_count] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_23weighted_n_node_samples_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_23weighted_n_node_samples_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_23weighted_n_node_samples___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_23weighted_n_node_samples___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "sklearn/tree/_tree.pyx":3044 + * property weighted_n_node_samples: + * def __get__(self): + * return self._get_node_ndarray()['weighted_n_node_samples'][:self.node_count] # <<<<<<<<<<<<<< + * + * property value: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_get_node_ndarray(__pyx_v_self)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3044; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_n_s_weighted_n_node_samples); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3044; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_t_2, 0, __pyx_v_self->node_count, NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3044; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3043 + * + * property weighted_n_node_samples: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_node_ndarray()['weighted_n_node_samples'][:self.node_count] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.weighted_n_node_samples.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3047 + * + * property value: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_value_ndarray()[:self.node_count] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_5value_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_5value_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_5value___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_5value___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "sklearn/tree/_tree.pyx":3048 + * property value: + * def __get__(self): + * return self._get_value_ndarray()[:self.node_count] # <<<<<<<<<<<<<< + * + * def __cinit__(self, int n_features, np.ndarray[SIZE_t, ndim=1] n_classes, + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_get_value_ndarray(__pyx_v_self)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3048; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_t_1, 0, __pyx_v_self->node_count, NULL, NULL, NULL, 0, 1, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3048; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3047 + * + * property value: + * def __get__(self): # <<<<<<<<<<<<<< + * return self._get_value_ndarray()[:self.node_count] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.value.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3050 + * return self._get_value_ndarray()[:self.node_count] + * + * def __cinit__(self, int n_features, np.ndarray[SIZE_t, ndim=1] n_classes, # <<<<<<<<<<<<<< + * int n_outputs): + * """Constructor.""" + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_v_n_features; + PyArrayObject *__pyx_v_n_classes = 0; + int __pyx_v_n_outputs; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_n_features,&__pyx_n_s_n_classes,&__pyx_n_s_n_outputs,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_features)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_classes)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3050; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_outputs)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3050; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3050; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v_n_features = __Pyx_PyInt_As_int(values[0]); if (unlikely((__pyx_v_n_features == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3050; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_classes = ((PyArrayObject *)values[1]); + __pyx_v_n_outputs = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_n_outputs == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3051; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3050; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._tree.Tree.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_n_classes), __pyx_ptype_5numpy_ndarray, 1, "n_classes", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree___cinit__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), __pyx_v_n_features, __pyx_v_n_classes, __pyx_v_n_outputs); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_5_tree_4Tree___cinit__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, int __pyx_v_n_features, PyArrayObject *__pyx_v_n_classes, int __pyx_v_n_outputs) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_k; + __Pyx_LocalBuf_ND __pyx_pybuffernd_n_classes; + __Pyx_Buffer __pyx_pybuffer_n_classes; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_5; + int __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __pyx_pybuffer_n_classes.pybuffer.buf = NULL; + __pyx_pybuffer_n_classes.refcount = 0; + __pyx_pybuffernd_n_classes.data = NULL; + __pyx_pybuffernd_n_classes.rcbuffer = &__pyx_pybuffer_n_classes; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_n_classes.rcbuffer->pybuffer, (PyObject*)__pyx_v_n_classes, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_SIZE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_n_classes.diminfo[0].strides = __pyx_pybuffernd_n_classes.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_n_classes.diminfo[0].shape = __pyx_pybuffernd_n_classes.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/tree/_tree.pyx":3054 + * """Constructor.""" + * # Input/Output layout + * self.n_features = n_features # <<<<<<<<<<<<<< + * self.n_outputs = n_outputs + * self.n_classes = NULL + */ + __pyx_v_self->n_features = __pyx_v_n_features; + + /* "sklearn/tree/_tree.pyx":3055 + * # Input/Output layout + * self.n_features = n_features + * self.n_outputs = n_outputs # <<<<<<<<<<<<<< + * self.n_classes = NULL + * safe_realloc(&self.n_classes, n_outputs) + */ + __pyx_v_self->n_outputs = __pyx_v_n_outputs; + + /* "sklearn/tree/_tree.pyx":3056 + * self.n_features = n_features + * self.n_outputs = n_outputs + * self.n_classes = NULL # <<<<<<<<<<<<<< + * safe_realloc(&self.n_classes, n_outputs) + * + */ + __pyx_v_self->n_classes = NULL; + + /* "sklearn/tree/_tree.pyx":3057 + * self.n_outputs = n_outputs + * self.n_classes = NULL + * safe_realloc(&self.n_classes, n_outputs) # <<<<<<<<<<<<<< + * + * self.max_n_classes = np.max(n_classes) + */ + __pyx_fuse_1__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_self->n_classes), __pyx_v_n_outputs); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3057; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":3059 + * safe_realloc(&self.n_classes, n_outputs) + * + * self.max_n_classes = np.max(n_classes) # <<<<<<<<<<<<<< + * self.value_stride = n_outputs * self.max_n_classes + * + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_max); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (!__pyx_t_2) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, ((PyObject *)__pyx_v_n_classes)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = NULL; + __Pyx_INCREF(((PyObject *)__pyx_v_n_classes)); + PyTuple_SET_ITEM(__pyx_t_4, 0+1, ((PyObject *)__pyx_v_n_classes)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_n_classes)); + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_5 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->max_n_classes = __pyx_t_5; + + /* "sklearn/tree/_tree.pyx":3060 + * + * self.max_n_classes = np.max(n_classes) + * self.value_stride = n_outputs * self.max_n_classes # <<<<<<<<<<<<<< + * + * cdef SIZE_t k + */ + __pyx_v_self->value_stride = (__pyx_v_n_outputs * __pyx_v_self->max_n_classes); + + /* "sklearn/tree/_tree.pyx":3063 + * + * cdef SIZE_t k + * for k in range(n_outputs): # <<<<<<<<<<<<<< + * self.n_classes[k] = n_classes[k] + * + */ + __pyx_t_6 = __pyx_v_n_outputs; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_6; __pyx_t_5+=1) { + __pyx_v_k = __pyx_t_5; + + /* "sklearn/tree/_tree.pyx":3064 + * cdef SIZE_t k + * for k in range(n_outputs): + * self.n_classes[k] = n_classes[k] # <<<<<<<<<<<<<< + * + * # Inner structures + */ + __pyx_t_7 = __pyx_v_k; + (__pyx_v_self->n_classes[__pyx_v_k]) = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_pybuffernd_n_classes.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_n_classes.diminfo[0].strides)); + } + + /* "sklearn/tree/_tree.pyx":3067 + * + * # Inner structures + * self.max_depth = 0 # <<<<<<<<<<<<<< + * self.node_count = 0 + * self.capacity = 0 + */ + __pyx_v_self->max_depth = 0; + + /* "sklearn/tree/_tree.pyx":3068 + * # Inner structures + * self.max_depth = 0 + * self.node_count = 0 # <<<<<<<<<<<<<< + * self.capacity = 0 + * self.value = NULL + */ + __pyx_v_self->node_count = 0; + + /* "sklearn/tree/_tree.pyx":3069 + * self.max_depth = 0 + * self.node_count = 0 + * self.capacity = 0 # <<<<<<<<<<<<<< + * self.value = NULL + * self.nodes = NULL + */ + __pyx_v_self->capacity = 0; + + /* "sklearn/tree/_tree.pyx":3070 + * self.node_count = 0 + * self.capacity = 0 + * self.value = NULL # <<<<<<<<<<<<<< + * self.nodes = NULL + * + */ + __pyx_v_self->value = NULL; + + /* "sklearn/tree/_tree.pyx":3071 + * self.capacity = 0 + * self.value = NULL + * self.nodes = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(self): + */ + __pyx_v_self->nodes = NULL; + + /* "sklearn/tree/_tree.pyx":3050 + * return self._get_value_ndarray()[:self.node_count] + * + * def __cinit__(self, int n_features, np.ndarray[SIZE_t, ndim=1] n_classes, # <<<<<<<<<<<<<< + * int n_outputs): + * """Constructor.""" + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_n_classes.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.tree._tree.Tree.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_n_classes.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3073 + * self.nodes = NULL + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Destructor.""" + * # Free all inner structures + */ + +/* Python wrapper */ +static void __pyx_pw_7sklearn_4tree_5_tree_4Tree_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_7sklearn_4tree_5_tree_4Tree_3__dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_pf_7sklearn_4tree_5_tree_4Tree_2__dealloc__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_7sklearn_4tree_5_tree_4Tree_2__dealloc__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "sklearn/tree/_tree.pyx":3076 + * """Destructor.""" + * # Free all inner structures + * free(self.n_classes) # <<<<<<<<<<<<<< + * free(self.value) + * free(self.nodes) + */ + free(__pyx_v_self->n_classes); + + /* "sklearn/tree/_tree.pyx":3077 + * # Free all inner structures + * free(self.n_classes) + * free(self.value) # <<<<<<<<<<<<<< + * free(self.nodes) + * + */ + free(__pyx_v_self->value); + + /* "sklearn/tree/_tree.pyx":3078 + * free(self.n_classes) + * free(self.value) + * free(self.nodes) # <<<<<<<<<<<<<< + * + * def __reduce__(self): + */ + free(__pyx_v_self->nodes); + + /* "sklearn/tree/_tree.pyx":3073 + * self.nodes = NULL + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * """Destructor.""" + * # Free all inner structures + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "sklearn/tree/_tree.pyx":3080 + * free(self.nodes) + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * """Reduce re-implementation, for pickling.""" + * return (Tree, (self.n_features, + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_4__reduce__[] = "Reduce re-implementation, for pickling."; +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_5__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_4__reduce__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_4__reduce__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce__", 0); + + /* "sklearn/tree/_tree.pyx":3082 + * def __reduce__(self): + * """Reduce re-implementation, for pickling.""" + * return (Tree, (self.n_features, # <<<<<<<<<<<<<< + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs), + * self.n_outputs), self.__getstate__()) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3082; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "sklearn/tree/_tree.pyx":3083 + * """Reduce re-implementation, for pickling.""" + * return (Tree, (self.n_features, + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs), # <<<<<<<<<<<<<< + * self.n_outputs), self.__getstate__()) + * + */ + __pyx_t_2 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_sizet_ptr_to_ndarray(__pyx_v_self->n_classes, __pyx_v_self->n_outputs)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3083; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + + /* "sklearn/tree/_tree.pyx":3084 + * return (Tree, (self.n_features, + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs), + * self.n_outputs), self.__getstate__()) # <<<<<<<<<<<<<< + * + * def __getstate__(self): + */ + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_outputs); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "sklearn/tree/_tree.pyx":3082 + * def __reduce__(self): + * """Reduce re-implementation, for pickling.""" + * return (Tree, (self.n_features, # <<<<<<<<<<<<<< + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs), + * self.n_outputs), self.__getstate__()) + */ + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3082; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + + /* "sklearn/tree/_tree.pyx":3084 + * return (Tree, (self.n_features, + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs), + * self.n_outputs), self.__getstate__()) # <<<<<<<<<<<<<< + * + * def __getstate__(self): + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_getstate); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (__pyx_t_1) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/tree/_tree.pyx":3082 + * def __reduce__(self): + * """Reduce re-implementation, for pickling.""" + * return (Tree, (self.n_features, # <<<<<<<<<<<<<< + * sizet_ptr_to_ndarray(self.n_classes, self.n_outputs), + * self.n_outputs), self.__getstate__()) + */ + __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3082; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_Tree))); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_Tree))); + __Pyx_GIVEREF(((PyObject *)((PyObject*)__pyx_ptype_7sklearn_4tree_5_tree_Tree))); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3080 + * free(self.nodes) + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * """Reduce re-implementation, for pickling.""" + * return (Tree, (self.n_features, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3086 + * self.n_outputs), self.__getstate__()) + * + * def __getstate__(self): # <<<<<<<<<<<<<< + * """Getstate re-implementation, for pickling.""" + * d = {} + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_6__getstate__[] = "Getstate re-implementation, for pickling."; +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_7__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_6__getstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_6__getstate__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_v_d = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getstate__", 0); + + /* "sklearn/tree/_tree.pyx":3088 + * def __getstate__(self): + * """Getstate re-implementation, for pickling.""" + * d = {} # <<<<<<<<<<<<<< + * d["node_count"] = self.node_count + * d["nodes"] = self._get_node_ndarray() + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3088; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_d = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":3089 + * """Getstate re-implementation, for pickling.""" + * d = {} + * d["node_count"] = self.node_count # <<<<<<<<<<<<<< + * d["nodes"] = self._get_node_ndarray() + * d["values"] = self._get_value_ndarray() + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->node_count); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3089; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(PyDict_SetItem(__pyx_v_d, __pyx_n_s_node_count, __pyx_t_1) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3089; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":3090 + * d = {} + * d["node_count"] = self.node_count + * d["nodes"] = self._get_node_ndarray() # <<<<<<<<<<<<<< + * d["values"] = self._get_value_ndarray() + * return d + */ + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_get_node_ndarray(__pyx_v_self)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3090; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(PyDict_SetItem(__pyx_v_d, __pyx_n_s_nodes, __pyx_t_1) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3090; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":3091 + * d["node_count"] = self.node_count + * d["nodes"] = self._get_node_ndarray() + * d["values"] = self._get_value_ndarray() # <<<<<<<<<<<<<< + * return d + * + */ + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_get_value_ndarray(__pyx_v_self)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3091; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(PyDict_SetItem(__pyx_v_d, __pyx_n_s_values, __pyx_t_1) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3091; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":3092 + * d["nodes"] = self._get_node_ndarray() + * d["values"] = self._get_value_ndarray() + * return d # <<<<<<<<<<<<<< + * + * def __setstate__(self, d): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_d); + __pyx_r = __pyx_v_d; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3086 + * self.n_outputs), self.__getstate__()) + * + * def __getstate__(self): # <<<<<<<<<<<<<< + * """Getstate re-implementation, for pickling.""" + * d = {} + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_d); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3094 + * return d + * + * def __setstate__(self, d): # <<<<<<<<<<<<<< + * """Setstate re-implementation, for unpickling.""" + * self.node_count = d["node_count"] + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d); /*proto*/ +static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_8__setstate__[] = "Setstate re-implementation, for unpickling."; +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_d) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_8__setstate__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_d)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_8__setstate__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_d) { + PyObject *__pyx_v_node_ndarray = NULL; + PyObject *__pyx_v_value_ndarray = NULL; + PyObject *__pyx_v_value_shape = NULL; + CYTHON_UNUSED void *__pyx_v_nodes; + CYTHON_UNUSED void *__pyx_v_value; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + int __pyx_t_9; + struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate__", 0); + + /* "sklearn/tree/_tree.pyx":3096 + * def __setstate__(self, d): + * """Setstate re-implementation, for unpickling.""" + * self.node_count = d["node_count"] # <<<<<<<<<<<<<< + * + * if 'nodes' not in d: + */ + __pyx_t_1 = PyObject_GetItem(__pyx_v_d, __pyx_n_s_node_count); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3096; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_2 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3096; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->node_count = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":3098 + * self.node_count = d["node_count"] + * + * if 'nodes' not in d: # <<<<<<<<<<<<<< + * raise ValueError('You have loaded Tree version which ' + * 'cannot be imported') + */ + __pyx_t_3 = (__Pyx_PySequence_Contains(__pyx_n_s_nodes, __pyx_v_d, Py_NE)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3098; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = (__pyx_t_3 != 0); + if (__pyx_t_4) { + + /* "sklearn/tree/_tree.pyx":3099 + * + * if 'nodes' not in d: + * raise ValueError('You have loaded Tree version which ' # <<<<<<<<<<<<<< + * 'cannot be imported') + * + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3099; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3099; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3102 + * 'cannot be imported') + * + * node_ndarray = d['nodes'] # <<<<<<<<<<<<<< + * value_ndarray = d['values'] + * + */ + __pyx_t_1 = PyObject_GetItem(__pyx_v_d, __pyx_n_s_nodes); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3102; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_node_ndarray = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":3103 + * + * node_ndarray = d['nodes'] + * value_ndarray = d['values'] # <<<<<<<<<<<<<< + * + * value_shape = (node_ndarray.shape[0], self.n_outputs, + */ + __pyx_t_1 = PyObject_GetItem(__pyx_v_d, __pyx_n_s_values); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3103; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_value_ndarray = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":3105 + * value_ndarray = d['values'] + * + * value_shape = (node_ndarray.shape[0], self.n_outputs, # <<<<<<<<<<<<<< + * self.max_n_classes) + * if (node_ndarray.ndim != 1 or + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_node_ndarray, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3105; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_outputs); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "sklearn/tree/_tree.pyx":3106 + * + * value_shape = (node_ndarray.shape[0], self.n_outputs, + * self.max_n_classes) # <<<<<<<<<<<<<< + * if (node_ndarray.ndim != 1 or + * node_ndarray.dtype != NODE_DTYPE or + */ + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->max_n_classes); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "sklearn/tree/_tree.pyx":3105 + * value_ndarray = d['values'] + * + * value_shape = (node_ndarray.shape[0], self.n_outputs, # <<<<<<<<<<<<<< + * self.max_n_classes) + * if (node_ndarray.ndim != 1 or + */ + __pyx_t_7 = PyTuple_New(3); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_7, 2, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_5 = 0; + __pyx_t_1 = 0; + __pyx_t_6 = 0; + __pyx_v_value_shape = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + + /* "sklearn/tree/_tree.pyx":3107 + * value_shape = (node_ndarray.shape[0], self.n_outputs, + * self.max_n_classes) + * if (node_ndarray.ndim != 1 or # <<<<<<<<<<<<<< + * node_ndarray.dtype != NODE_DTYPE or + * not node_ndarray.flags.c_contiguous or + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_node_ndarray, __pyx_n_s_ndim); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_7, __pyx_int_1, Py_NE); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!__pyx_t_3) { + } else { + __pyx_t_4 = __pyx_t_3; + goto __pyx_L5_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":3108 + * self.max_n_classes) + * if (node_ndarray.ndim != 1 or + * node_ndarray.dtype != NODE_DTYPE or # <<<<<<<<<<<<<< + * not node_ndarray.flags.c_contiguous or + * value_ndarray.shape != value_shape or + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_node_ndarray, __pyx_n_s_dtype); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_NODE_DTYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_1 = PyObject_RichCompare(__pyx_t_6, __pyx_t_7, Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!__pyx_t_3) { + } else { + __pyx_t_4 = __pyx_t_3; + goto __pyx_L5_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":3109 + * if (node_ndarray.ndim != 1 or + * node_ndarray.dtype != NODE_DTYPE or + * not node_ndarray.flags.c_contiguous or # <<<<<<<<<<<<<< + * value_ndarray.shape != value_shape or + * not value_ndarray.flags.c_contiguous or + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_node_ndarray, __pyx_n_s_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_c_contiguous); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = ((!__pyx_t_3) != 0); + if (!__pyx_t_8) { + } else { + __pyx_t_4 = __pyx_t_8; + goto __pyx_L5_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":3110 + * node_ndarray.dtype != NODE_DTYPE or + * not node_ndarray.flags.c_contiguous or + * value_ndarray.shape != value_shape or # <<<<<<<<<<<<<< + * not value_ndarray.flags.c_contiguous or + * value_ndarray.dtype != np.float64): + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_value_ndarray, __pyx_n_s_shape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_1 = PyObject_RichCompare(__pyx_t_7, __pyx_v_value_shape, Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!__pyx_t_8) { + } else { + __pyx_t_4 = __pyx_t_8; + goto __pyx_L5_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":3111 + * not node_ndarray.flags.c_contiguous or + * value_ndarray.shape != value_shape or + * not value_ndarray.flags.c_contiguous or # <<<<<<<<<<<<<< + * value_ndarray.dtype != np.float64): + * raise ValueError('Did not recognise loaded array layout') + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_value_ndarray, __pyx_n_s_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_c_contiguous); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3111; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_3 = ((!__pyx_t_8) != 0); + if (!__pyx_t_3) { + } else { + __pyx_t_4 = __pyx_t_3; + goto __pyx_L5_bool_binop_done; + } + + /* "sklearn/tree/_tree.pyx":3112 + * value_ndarray.shape != value_shape or + * not value_ndarray.flags.c_contiguous or + * value_ndarray.dtype != np.float64): # <<<<<<<<<<<<<< + * raise ValueError('Did not recognise loaded array layout') + * + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_value_ndarray, __pyx_n_s_dtype); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_RichCompare(__pyx_t_7, __pyx_t_6, Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_4 = __pyx_t_3; + __pyx_L5_bool_binop_done:; + if (__pyx_t_4) { + + /* "sklearn/tree/_tree.pyx":3113 + * not value_ndarray.flags.c_contiguous or + * value_ndarray.dtype != np.float64): + * raise ValueError('Did not recognise loaded array layout') # <<<<<<<<<<<<<< + * + * self.capacity = node_ndarray.shape[0] + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3115 + * raise ValueError('Did not recognise loaded array layout') + * + * self.capacity = node_ndarray.shape[0] # <<<<<<<<<<<<<< + * if self._resize_c(self.capacity) != 0: + * raise MemoryError("resizing tree to %d" % self.capacity) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_node_ndarray, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3115; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_2 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_6); if (unlikely((__pyx_t_2 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_self->capacity = __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":3116 + * + * self.capacity = node_ndarray.shape[0] + * if self._resize_c(self.capacity) != 0: # <<<<<<<<<<<<<< + * raise MemoryError("resizing tree to %d" % self.capacity) + * nodes = memcpy(self.nodes, ( node_ndarray).data, + */ + __pyx_t_10.__pyx_n = 1; + __pyx_t_10.capacity = __pyx_v_self->capacity; + __pyx_t_9 = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_resize_c(__pyx_v_self, &__pyx_t_10); + __pyx_t_4 = ((__pyx_t_9 != 0) != 0); + if (__pyx_t_4) { + + /* "sklearn/tree/_tree.pyx":3117 + * self.capacity = node_ndarray.shape[0] + * if self._resize_c(self.capacity) != 0: + * raise MemoryError("resizing tree to %d" % self.capacity) # <<<<<<<<<<<<<< + * nodes = memcpy(self.nodes, ( node_ndarray).data, + * self.capacity * sizeof(Node)) + */ + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->capacity); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_resizing_tree_to_d, __pyx_t_6); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_t_6, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3118 + * if self._resize_c(self.capacity) != 0: + * raise MemoryError("resizing tree to %d" % self.capacity) + * nodes = memcpy(self.nodes, ( node_ndarray).data, # <<<<<<<<<<<<<< + * self.capacity * sizeof(Node)) + * value = memcpy(self.value, ( value_ndarray).data, + */ + __pyx_v_nodes = memcpy(__pyx_v_self->nodes, ((PyArrayObject *)__pyx_v_node_ndarray)->data, (__pyx_v_self->capacity * (sizeof(struct __pyx_t_7sklearn_4tree_5_tree_Node)))); + + /* "sklearn/tree/_tree.pyx":3120 + * nodes = memcpy(self.nodes, ( node_ndarray).data, + * self.capacity * sizeof(Node)) + * value = memcpy(self.value, ( value_ndarray).data, # <<<<<<<<<<<<<< + * self.capacity * self.value_stride * sizeof(double)) + * + */ + __pyx_v_value = memcpy(__pyx_v_self->value, ((PyArrayObject *)__pyx_v_value_ndarray)->data, ((__pyx_v_self->capacity * __pyx_v_self->value_stride) * (sizeof(double)))); + + /* "sklearn/tree/_tree.pyx":3094 + * return d + * + * def __setstate__(self, d): # <<<<<<<<<<<<<< + * """Setstate re-implementation, for unpickling.""" + * self.node_count = d["node_count"] + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.__setstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_node_ndarray); + __Pyx_XDECREF(__pyx_v_value_ndarray); + __Pyx_XDECREF(__pyx_v_value_shape); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3123 + * self.capacity * self.value_stride * sizeof(double)) + * + * cdef void _resize(self, SIZE_t capacity) except *: # <<<<<<<<<<<<<< + * """Resize all inner arrays to `capacity`, if `capacity` == -1, then + * double the size of the inner arrays.""" + */ + +static void __pyx_f_7sklearn_4tree_5_tree_4Tree__resize(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_capacity) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c __pyx_t_2; + int __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_resize", 0); + + /* "sklearn/tree/_tree.pyx":3126 + * """Resize all inner arrays to `capacity`, if `capacity` == -1, then + * double the size of the inner arrays.""" + * if self._resize_c(capacity) != 0: # <<<<<<<<<<<<<< + * raise MemoryError() + * + */ + __pyx_t_2.__pyx_n = 1; + __pyx_t_2.capacity = __pyx_v_capacity; + __pyx_t_1 = ((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_resize_c(__pyx_v_self, &__pyx_t_2); + __pyx_t_3 = ((__pyx_t_1 != 0) != 0); + if (__pyx_t_3) { + + /* "sklearn/tree/_tree.pyx":3127 + * double the size of the inner arrays.""" + * if self._resize_c(capacity) != 0: + * raise MemoryError() # <<<<<<<<<<<<<< + * + * # XXX using (size_t)(-1) is ugly, but SIZE_MAX is not available in C89 + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3123 + * self.capacity * self.value_stride * sizeof(double)) + * + * cdef void _resize(self, SIZE_t capacity) except *: # <<<<<<<<<<<<<< + * """Resize all inner arrays to `capacity`, if `capacity` == -1, then + * double the size of the inner arrays.""" + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.tree._tree.Tree._resize", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_L0:; + __Pyx_RefNannyFinishContext(); +} + +/* "sklearn/tree/_tree.pyx":3131 + * # XXX using (size_t)(-1) is ugly, but SIZE_MAX is not available in C89 + * # (i.e., older MSVC). + * cdef int _resize_c(self, SIZE_t capacity=(-1)) nogil: # <<<<<<<<<<<<<< + * """Guts of _resize. Returns 0 for success, -1 for error.""" + * if capacity == self.capacity and self.nodes != NULL: + */ + +static int __pyx_f_7sklearn_4tree_5_tree_4Tree__resize_c(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c *__pyx_optional_args) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_capacity = __pyx_k__5; + void *__pyx_v_ptr; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_capacity = __pyx_optional_args->capacity; + } + } + + /* "sklearn/tree/_tree.pyx":3133 + * cdef int _resize_c(self, SIZE_t capacity=(-1)) nogil: + * """Guts of _resize. Returns 0 for success, -1 for error.""" + * if capacity == self.capacity and self.nodes != NULL: # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_t_2 = ((__pyx_v_capacity == __pyx_v_self->capacity) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_self->nodes != NULL) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L4_bool_binop_done:; + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3134 + * """Guts of _resize. Returns 0 for success, -1 for error.""" + * if capacity == self.capacity and self.nodes != NULL: + * return 0 # <<<<<<<<<<<<<< + * + * if capacity == (-1): + */ + __pyx_r = 0; + goto __pyx_L0; + } + + /* "sklearn/tree/_tree.pyx":3136 + * return 0 + * + * if capacity == (-1): # <<<<<<<<<<<<<< + * if self.capacity == 0: + * capacity = 3 # default initial value + */ + __pyx_t_1 = ((__pyx_v_capacity == ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)-1)) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3137 + * + * if capacity == (-1): + * if self.capacity == 0: # <<<<<<<<<<<<<< + * capacity = 3 # default initial value + * else: + */ + __pyx_t_1 = ((__pyx_v_self->capacity == 0) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3138 + * if capacity == (-1): + * if self.capacity == 0: + * capacity = 3 # default initial value # <<<<<<<<<<<<<< + * else: + * capacity = 2 * self.capacity + */ + __pyx_v_capacity = 3; + goto __pyx_L7; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":3140 + * capacity = 3 # default initial value + * else: + * capacity = 2 * self.capacity # <<<<<<<<<<<<<< + * + * # XXX no safe_realloc here because we need to grab the GIL + */ + __pyx_v_capacity = (2 * __pyx_v_self->capacity); + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + + /* "sklearn/tree/_tree.pyx":3143 + * + * # XXX no safe_realloc here because we need to grab the GIL + * cdef void* ptr = realloc(self.nodes, capacity * sizeof(Node)) # <<<<<<<<<<<<<< + * if ptr == NULL: + * return -1 + */ + __pyx_v_ptr = realloc(__pyx_v_self->nodes, (__pyx_v_capacity * (sizeof(struct __pyx_t_7sklearn_4tree_5_tree_Node)))); + + /* "sklearn/tree/_tree.pyx":3144 + * # XXX no safe_realloc here because we need to grab the GIL + * cdef void* ptr = realloc(self.nodes, capacity * sizeof(Node)) + * if ptr == NULL: # <<<<<<<<<<<<<< + * return -1 + * self.nodes = ptr + */ + __pyx_t_1 = ((__pyx_v_ptr == NULL) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3145 + * cdef void* ptr = realloc(self.nodes, capacity * sizeof(Node)) + * if ptr == NULL: + * return -1 # <<<<<<<<<<<<<< + * self.nodes = ptr + * ptr = realloc(self.value, + */ + __pyx_r = -1; + goto __pyx_L0; + } + + /* "sklearn/tree/_tree.pyx":3146 + * if ptr == NULL: + * return -1 + * self.nodes = ptr # <<<<<<<<<<<<<< + * ptr = realloc(self.value, + * capacity * self.value_stride * sizeof(double)) + */ + __pyx_v_self->nodes = ((struct __pyx_t_7sklearn_4tree_5_tree_Node *)__pyx_v_ptr); + + /* "sklearn/tree/_tree.pyx":3147 + * return -1 + * self.nodes = ptr + * ptr = realloc(self.value, # <<<<<<<<<<<<<< + * capacity * self.value_stride * sizeof(double)) + * if ptr == NULL: + */ + __pyx_v_ptr = realloc(__pyx_v_self->value, ((__pyx_v_capacity * __pyx_v_self->value_stride) * (sizeof(double)))); + + /* "sklearn/tree/_tree.pyx":3149 + * ptr = realloc(self.value, + * capacity * self.value_stride * sizeof(double)) + * if ptr == NULL: # <<<<<<<<<<<<<< + * return -1 + * self.value = ptr + */ + __pyx_t_1 = ((__pyx_v_ptr == NULL) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3150 + * capacity * self.value_stride * sizeof(double)) + * if ptr == NULL: + * return -1 # <<<<<<<<<<<<<< + * self.value = ptr + * + */ + __pyx_r = -1; + goto __pyx_L0; + } + + /* "sklearn/tree/_tree.pyx":3151 + * if ptr == NULL: + * return -1 + * self.value = ptr # <<<<<<<<<<<<<< + * + * # value memory is initialised to 0 to enable classifier argmax + */ + __pyx_v_self->value = ((double *)__pyx_v_ptr); + + /* "sklearn/tree/_tree.pyx":3154 + * + * # value memory is initialised to 0 to enable classifier argmax + * if capacity > self.capacity: # <<<<<<<<<<<<<< + * memset((self.value + self.capacity * self.value_stride), 0, + * (capacity - self.capacity) * self.value_stride * + */ + __pyx_t_1 = ((__pyx_v_capacity > __pyx_v_self->capacity) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3155 + * # value memory is initialised to 0 to enable classifier argmax + * if capacity > self.capacity: + * memset((self.value + self.capacity * self.value_stride), 0, # <<<<<<<<<<<<<< + * (capacity - self.capacity) * self.value_stride * + * sizeof(double)) + */ + memset(((void *)(__pyx_v_self->value + (__pyx_v_self->capacity * __pyx_v_self->value_stride))), 0, (((__pyx_v_capacity - __pyx_v_self->capacity) * __pyx_v_self->value_stride) * (sizeof(double)))); + goto __pyx_L10; + } + __pyx_L10:; + + /* "sklearn/tree/_tree.pyx":3160 + * + * # if capacity smaller than node_count, adjust the counter + * if capacity < self.node_count: # <<<<<<<<<<<<<< + * self.node_count = capacity + * + */ + __pyx_t_1 = ((__pyx_v_capacity < __pyx_v_self->node_count) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3161 + * # if capacity smaller than node_count, adjust the counter + * if capacity < self.node_count: + * self.node_count = capacity # <<<<<<<<<<<<<< + * + * self.capacity = capacity + */ + __pyx_v_self->node_count = __pyx_v_capacity; + goto __pyx_L11; + } + __pyx_L11:; + + /* "sklearn/tree/_tree.pyx":3163 + * self.node_count = capacity + * + * self.capacity = capacity # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_v_self->capacity = __pyx_v_capacity; + + /* "sklearn/tree/_tree.pyx":3164 + * + * self.capacity = capacity + * return 0 # <<<<<<<<<<<<<< + * + * cdef SIZE_t _add_node(self, SIZE_t parent, bint is_left, bint is_leaf, + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3131 + * # XXX using (size_t)(-1) is ugly, but SIZE_MAX is not available in C89 + * # (i.e., older MSVC). + * cdef int _resize_c(self, SIZE_t capacity=(-1)) nogil: # <<<<<<<<<<<<<< + * """Guts of _resize. Returns 0 for success, -1 for error.""" + * if capacity == self.capacity and self.nodes != NULL: + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3166 + * return 0 + * + * 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: + */ + +static __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_f_7sklearn_4tree_5_tree_4Tree__add_node(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_parent, int __pyx_v_is_left, int __pyx_v_is_leaf, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_feature, double __pyx_v_threshold, double __pyx_v_impurity, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_node_samples, double __pyx_v_weighted_n_node_samples) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_node_id; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_node; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_r; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + int __pyx_t_2; + + /* "sklearn/tree/_tree.pyx":3175 + * Returns (size_t)(-1) on error. + * """ + * cdef SIZE_t node_id = self.node_count # <<<<<<<<<<<<<< + * + * if node_id >= self.capacity: + */ + __pyx_t_1 = __pyx_v_self->node_count; + __pyx_v_node_id = __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":3177 + * cdef SIZE_t node_id = self.node_count + * + * if node_id >= self.capacity: # <<<<<<<<<<<<<< + * if self._resize_c() != 0: + * return (-1) + */ + __pyx_t_2 = ((__pyx_v_node_id >= __pyx_v_self->capacity) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":3178 + * + * if node_id >= self.capacity: + * if self._resize_c() != 0: # <<<<<<<<<<<<<< + * return (-1) + * + */ + __pyx_t_2 = ((((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_resize_c(__pyx_v_self, NULL) != 0) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":3179 + * if node_id >= self.capacity: + * if self._resize_c() != 0: + * return (-1) # <<<<<<<<<<<<<< + * + * cdef Node* node = &self.nodes[node_id] + */ + __pyx_r = ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)-1); + goto __pyx_L0; + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/tree/_tree.pyx":3181 + * return (-1) + * + * cdef Node* node = &self.nodes[node_id] # <<<<<<<<<<<<<< + * node.impurity = impurity + * node.n_node_samples = n_node_samples + */ + __pyx_v_node = (&(__pyx_v_self->nodes[__pyx_v_node_id])); + + /* "sklearn/tree/_tree.pyx":3182 + * + * cdef Node* node = &self.nodes[node_id] + * node.impurity = impurity # <<<<<<<<<<<<<< + * node.n_node_samples = n_node_samples + * node.weighted_n_node_samples = weighted_n_node_samples + */ + __pyx_v_node->impurity = __pyx_v_impurity; + + /* "sklearn/tree/_tree.pyx":3183 + * cdef Node* node = &self.nodes[node_id] + * node.impurity = impurity + * node.n_node_samples = n_node_samples # <<<<<<<<<<<<<< + * node.weighted_n_node_samples = weighted_n_node_samples + * + */ + __pyx_v_node->n_node_samples = __pyx_v_n_node_samples; + + /* "sklearn/tree/_tree.pyx":3184 + * node.impurity = impurity + * node.n_node_samples = n_node_samples + * node.weighted_n_node_samples = weighted_n_node_samples # <<<<<<<<<<<<<< + * + * if parent != _TREE_UNDEFINED: + */ + __pyx_v_node->weighted_n_node_samples = __pyx_v_weighted_n_node_samples; + + /* "sklearn/tree/_tree.pyx":3186 + * node.weighted_n_node_samples = weighted_n_node_samples + * + * if parent != _TREE_UNDEFINED: # <<<<<<<<<<<<<< + * if is_left: + * self.nodes[parent].left_child = node_id + */ + __pyx_t_2 = ((__pyx_v_parent != __pyx_v_7sklearn_4tree_5_tree__TREE_UNDEFINED) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":3187 + * + * if parent != _TREE_UNDEFINED: + * if is_left: # <<<<<<<<<<<<<< + * self.nodes[parent].left_child = node_id + * else: + */ + __pyx_t_2 = (__pyx_v_is_left != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":3188 + * if parent != _TREE_UNDEFINED: + * if is_left: + * self.nodes[parent].left_child = node_id # <<<<<<<<<<<<<< + * else: + * self.nodes[parent].right_child = node_id + */ + (__pyx_v_self->nodes[__pyx_v_parent]).left_child = __pyx_v_node_id; + goto __pyx_L6; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":3190 + * self.nodes[parent].left_child = node_id + * else: + * self.nodes[parent].right_child = node_id # <<<<<<<<<<<<<< + * + * if is_leaf: + */ + (__pyx_v_self->nodes[__pyx_v_parent]).right_child = __pyx_v_node_id; + } + __pyx_L6:; + goto __pyx_L5; + } + __pyx_L5:; + + /* "sklearn/tree/_tree.pyx":3192 + * self.nodes[parent].right_child = node_id + * + * if is_leaf: # <<<<<<<<<<<<<< + * node.left_child = _TREE_LEAF + * node.right_child = _TREE_LEAF + */ + __pyx_t_2 = (__pyx_v_is_leaf != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":3193 + * + * if is_leaf: + * node.left_child = _TREE_LEAF # <<<<<<<<<<<<<< + * node.right_child = _TREE_LEAF + * node.feature = _TREE_UNDEFINED + */ + __pyx_v_node->left_child = __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF; + + /* "sklearn/tree/_tree.pyx":3194 + * if is_leaf: + * node.left_child = _TREE_LEAF + * node.right_child = _TREE_LEAF # <<<<<<<<<<<<<< + * node.feature = _TREE_UNDEFINED + * node.threshold = _TREE_UNDEFINED + */ + __pyx_v_node->right_child = __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF; + + /* "sklearn/tree/_tree.pyx":3195 + * node.left_child = _TREE_LEAF + * node.right_child = _TREE_LEAF + * node.feature = _TREE_UNDEFINED # <<<<<<<<<<<<<< + * node.threshold = _TREE_UNDEFINED + * + */ + __pyx_v_node->feature = __pyx_v_7sklearn_4tree_5_tree__TREE_UNDEFINED; + + /* "sklearn/tree/_tree.pyx":3196 + * node.right_child = _TREE_LEAF + * node.feature = _TREE_UNDEFINED + * node.threshold = _TREE_UNDEFINED # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_v_node->threshold = __pyx_v_7sklearn_4tree_5_tree__TREE_UNDEFINED; + goto __pyx_L7; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":3200 + * else: + * # left_child and right_child will be set later + * node.feature = feature # <<<<<<<<<<<<<< + * node.threshold = threshold + * + */ + __pyx_v_node->feature = __pyx_v_feature; + + /* "sklearn/tree/_tree.pyx":3201 + * # left_child and right_child will be set later + * node.feature = feature + * node.threshold = threshold # <<<<<<<<<<<<<< + * + * self.node_count += 1 + */ + __pyx_v_node->threshold = __pyx_v_threshold; + } + __pyx_L7:; + + /* "sklearn/tree/_tree.pyx":3203 + * node.threshold = threshold + * + * self.node_count += 1 # <<<<<<<<<<<<<< + * + * return node_id + */ + __pyx_v_self->node_count = (__pyx_v_self->node_count + 1); + + /* "sklearn/tree/_tree.pyx":3205 + * self.node_count += 1 + * + * return node_id # <<<<<<<<<<<<<< + * + * cpdef np.ndarray predict(self, object X): + */ + __pyx_r = __pyx_v_node_id; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3166 + * return 0 + * + * 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: + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3207 + * return node_id + * + * cpdef np.ndarray predict(self, object X): # <<<<<<<<<<<<<< + * """Predict target for X.""" + * out = self._get_value_ndarray().take(self.apply(X), axis=0, + */ + +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_11predict(PyObject *__pyx_v_self, PyObject *__pyx_v_X); /*proto*/ +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree_predict(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X, int __pyx_skip_dispatch) { + PyObject *__pyx_v_out = NULL; + PyArrayObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("predict", 0); + /* Check if called by wrapper */ + if (unlikely(__pyx_skip_dispatch)) ; + /* Check if overridden in Python */ + else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_predict); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_11predict)) { + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_3 = __pyx_t_1; __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (!__pyx_t_4) { + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_X); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + } else { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "sklearn/tree/_tree.pyx":3209 + * cpdef np.ndarray predict(self, object X): + * """Predict target for X.""" + * out = self._get_value_ndarray().take(self.apply(X), axis=0, # <<<<<<<<<<<<<< + * mode='clip') + * if self.n_outputs == 1: + */ + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->_get_value_ndarray(__pyx_v_self)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_take); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = ((PyObject *)((struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree *)__pyx_v_self->__pyx_vtab)->apply(__pyx_v_self, __pyx_v_X, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_axis, __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_mode, __pyx_n_s_clip) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_out = __pyx_t_5; + __pyx_t_5 = 0; + + /* "sklearn/tree/_tree.pyx":3211 + * out = self._get_value_ndarray().take(self.apply(X), axis=0, + * mode='clip') + * if self.n_outputs == 1: # <<<<<<<<<<<<<< + * out = out.reshape(X.shape[0], self.max_n_classes) + * return out + */ + __pyx_t_6 = ((__pyx_v_self->n_outputs == 1) != 0); + if (__pyx_t_6) { + + /* "sklearn/tree/_tree.pyx":3212 + * mode='clip') + * if self.n_outputs == 1: + * out = out.reshape(X.shape[0], self.max_n_classes) # <<<<<<<<<<<<<< + * return out + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_out, __pyx_n_s_reshape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_3, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3212; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->max_n_classes); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = NULL; + __pyx_t_7 = 0; + if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_1); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_1, function); + __pyx_t_7 = 1; + } + } + __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (__pyx_t_4) { + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + } + PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_8, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF_SET(__pyx_v_out, __pyx_t_5); + __pyx_t_5 = 0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/tree/_tree.pyx":3213 + * if self.n_outputs == 1: + * out = out.reshape(X.shape[0], self.max_n_classes) + * return out # <<<<<<<<<<<<<< + * + * cpdef np.ndarray apply(self, object X): + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + if (!(likely(((__pyx_v_out) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_out, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_out); + __pyx_r = ((PyArrayObject *)__pyx_v_out); + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3207 + * return node_id + * + * cpdef np.ndarray predict(self, object X): # <<<<<<<<<<<<<< + * """Predict target for X.""" + * out = self._get_value_ndarray().take(self.apply(X), axis=0, + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.predict", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_out); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_11predict(PyObject *__pyx_v_self, PyObject *__pyx_v_X); /*proto*/ +static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_10predict[] = "Predict target for X."; +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_11predict(PyObject *__pyx_v_self, PyObject *__pyx_v_X) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("predict (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10predict(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_X)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10predict(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("predict", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_4Tree_predict(__pyx_v_self, __pyx_v_X, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.predict", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3215 + * return out + * + * cpdef np.ndarray apply(self, object X): # <<<<<<<<<<<<<< + * """Finds the terminal region (=leaf node) for each sample in X.""" + * if issparse(X): + */ + +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13apply(PyObject *__pyx_v_self, PyObject *__pyx_v_X); /*proto*/ +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree_apply(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X, int __pyx_skip_dispatch) { + PyArrayObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("apply", 0); + /* Check if called by wrapper */ + if (unlikely(__pyx_skip_dispatch)) ; + /* Check if overridden in Python */ + else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_apply); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_13apply)) { + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_3 = __pyx_t_1; __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (!__pyx_t_4) { + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_X); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + } else { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "sklearn/tree/_tree.pyx":3217 + * cpdef np.ndarray apply(self, object X): + * """Finds the terminal region (=leaf node) for each sample in X.""" + * if issparse(X): # <<<<<<<<<<<<<< + * return self._apply_sparse_csr(X) + * else: + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_issparse); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (!__pyx_t_3) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_X); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_v_X); + PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_v_X); + __Pyx_GIVEREF(__pyx_v_X); + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_6) { + + /* "sklearn/tree/_tree.pyx":3218 + * """Finds the terminal region (=leaf node) for each sample in X.""" + * if issparse(X): + * return self._apply_sparse_csr(X) # <<<<<<<<<<<<<< + * else: + * return self._apply_dense(X) + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_4Tree__apply_sparse_csr(__pyx_v_self, __pyx_v_X)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":3220 + * return self._apply_sparse_csr(X) + * else: + * return self._apply_dense(X) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_4Tree__apply_dense(__pyx_v_self, __pyx_v_X)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + } + + /* "sklearn/tree/_tree.pyx":3215 + * return out + * + * cpdef np.ndarray apply(self, object X): # <<<<<<<<<<<<<< + * """Finds the terminal region (=leaf node) for each sample in X.""" + * if issparse(X): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.apply", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13apply(PyObject *__pyx_v_self, PyObject *__pyx_v_X); /*proto*/ +static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_12apply[] = "Finds the terminal region (=leaf node) for each sample in X."; +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13apply(PyObject *__pyx_v_self, PyObject *__pyx_v_X) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("apply (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_12apply(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_X)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_12apply(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("apply", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_4tree_5_tree_4Tree_apply(__pyx_v_self, __pyx_v_X, 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.apply", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3223 + * + * + * cdef inline np.ndarray _apply_dense(self, object X): # <<<<<<<<<<<<<< + * """Finds the terminal region (=leaf node) for each sample in X.""" + * + */ + +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree__apply_dense(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X) { + PyArrayObject *__pyx_v_X_ndarray = 0; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_ptr; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_X_sample_stride; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_X_fx_stride; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_samples; + PyArrayObject *__pyx_v_out = 0; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_out_ptr; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_node; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_i; + __Pyx_LocalBuf_ND __pyx_pybuffernd_out; + __Pyx_Buffer __pyx_pybuffer_out; + PyArrayObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_6; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyArrayObject *__pyx_t_10 = NULL; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_apply_dense", 0); + __pyx_pybuffer_out.pybuffer.buf = NULL; + __pyx_pybuffer_out.refcount = 0; + __pyx_pybuffernd_out.data = NULL; + __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; + + /* "sklearn/tree/_tree.pyx":3227 + * + * # Check input + * if not isinstance(X, np.ndarray): # <<<<<<<<<<<<<< + * raise ValueError("X should be in np.ndarray format, got %s" + * % type(X)) + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_X, ((PyObject*)__pyx_ptype_5numpy_ndarray)); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":3229 + * if not isinstance(X, np.ndarray): + * raise ValueError("X should be in np.ndarray format, got %s" + * % type(X)) # <<<<<<<<<<<<<< + * + * if X.dtype != DTYPE: + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_X_should_be_in_np_ndarray_format, ((PyObject *)Py_TYPE(__pyx_v_X))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3229; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + + /* "sklearn/tree/_tree.pyx":3228 + * # Check input + * if not isinstance(X, np.ndarray): + * raise ValueError("X should be in np.ndarray format, got %s" # <<<<<<<<<<<<<< + * % type(X)) + * + */ + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3231 + * % type(X)) + * + * if X.dtype != DTYPE: # <<<<<<<<<<<<<< + * raise ValueError("X.dtype should be np.float32, got %s" % X.dtype) + * + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_dtype); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_t_4, Py_NE); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":3232 + * + * if X.dtype != DTYPE: + * raise ValueError("X.dtype should be np.float32, got %s" % X.dtype) # <<<<<<<<<<<<<< + * + * # Extract input + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_dtype); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_X_dtype_should_be_np_float32_got, __pyx_t_5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3235 + * + * # Extract input + * cdef np.ndarray X_ndarray = X # <<<<<<<<<<<<<< + * cdef DTYPE_t* X_ptr = X_ndarray.data + * cdef SIZE_t X_sample_stride = X.strides[0] / X.itemsize + */ + if (!(likely(((__pyx_v_X) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_X, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_v_X; + __Pyx_INCREF(__pyx_t_4); + __pyx_v_X_ndarray = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/tree/_tree.pyx":3236 + * # Extract input + * cdef np.ndarray X_ndarray = X + * cdef DTYPE_t* X_ptr = X_ndarray.data # <<<<<<<<<<<<<< + * cdef SIZE_t X_sample_stride = X.strides[0] / X.itemsize + * cdef SIZE_t X_fx_stride = X.strides[1] / X.itemsize + */ + __pyx_v_X_ptr = ((__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *)__pyx_v_X_ndarray->data); + + /* "sklearn/tree/_tree.pyx":3237 + * cdef np.ndarray X_ndarray = X + * cdef DTYPE_t* X_ptr = X_ndarray.data + * cdef SIZE_t X_sample_stride = X.strides[0] / X.itemsize # <<<<<<<<<<<<<< + * cdef SIZE_t X_fx_stride = X.strides[1] / X.itemsize + * cdef SIZE_t n_samples = X.shape[0] + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_strides); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3237; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_4, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3237; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_5); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3237; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3237; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_5); if (unlikely((__pyx_t_7 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3237; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_X_sample_stride = (((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)__pyx_t_6) / ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)__pyx_t_7)); + + /* "sklearn/tree/_tree.pyx":3238 + * cdef DTYPE_t* X_ptr = X_ndarray.data + * cdef SIZE_t X_sample_stride = X.strides[0] / X.itemsize + * cdef SIZE_t X_fx_stride = X.strides[1] / X.itemsize # <<<<<<<<<<<<<< + * cdef SIZE_t n_samples = X.shape[0] + * + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_strides); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_GetItemInt(__pyx_t_5, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_4 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3238; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_4); if (unlikely((__pyx_t_7 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_4); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_X_fx_stride = (((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)__pyx_t_7) / ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)__pyx_t_6)); + + /* "sklearn/tree/_tree.pyx":3239 + * cdef SIZE_t X_sample_stride = X.strides[0] / X.itemsize + * cdef SIZE_t X_fx_stride = X.strides[1] / X.itemsize + * cdef SIZE_t n_samples = X.shape[0] # <<<<<<<<<<<<<< + * + * # Initialize output + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_4, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3239; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_5); if (unlikely((__pyx_t_6 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_n_samples = __pyx_t_6; + + /* "sklearn/tree/_tree.pyx":3242 + * + * # Initialize output + * cdef np.ndarray[SIZE_t] out = np.zeros((n_samples,), dtype=np.intp) # <<<<<<<<<<<<<< + * cdef SIZE_t* out_ptr = out.data + * + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_samples); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_intp); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, __pyx_t_3); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_9) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_9, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = ((PyArrayObject *)__pyx_t_9); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_10, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_SIZE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_out.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_10 = 0; + __pyx_v_out = ((PyArrayObject *)__pyx_t_9); + __pyx_t_9 = 0; + + /* "sklearn/tree/_tree.pyx":3243 + * # Initialize output + * cdef np.ndarray[SIZE_t] out = np.zeros((n_samples,), dtype=np.intp) + * cdef SIZE_t* out_ptr = out.data # <<<<<<<<<<<<<< + * + * # Initialize auxiliary data-structure + */ + __pyx_v_out_ptr = ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t *)__pyx_v_out->data); + + /* "sklearn/tree/_tree.pyx":3246 + * + * # Initialize auxiliary data-structure + * cdef Node* node = NULL # <<<<<<<<<<<<<< + * cdef SIZE_t i = 0 + * + */ + __pyx_v_node = NULL; + + /* "sklearn/tree/_tree.pyx":3247 + * # Initialize auxiliary data-structure + * cdef Node* node = NULL + * cdef SIZE_t i = 0 # <<<<<<<<<<<<<< + * + * with nogil: + */ + __pyx_v_i = 0; + + /* "sklearn/tree/_tree.pyx":3249 + * cdef SIZE_t i = 0 + * + * with nogil: # <<<<<<<<<<<<<< + * for i in range(n_samples): + * node = self.nodes + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/tree/_tree.pyx":3250 + * + * with nogil: + * for i in range(n_samples): # <<<<<<<<<<<<<< + * node = self.nodes + * # While node not a leaf + */ + __pyx_t_6 = __pyx_v_n_samples; + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; + + /* "sklearn/tree/_tree.pyx":3251 + * with nogil: + * for i in range(n_samples): + * node = self.nodes # <<<<<<<<<<<<<< + * # While node not a leaf + * while node.left_child != _TREE_LEAF: + */ + __pyx_t_11 = __pyx_v_self->nodes; + __pyx_v_node = __pyx_t_11; + + /* "sklearn/tree/_tree.pyx":3253 + * node = self.nodes + * # While node not a leaf + * while node.left_child != _TREE_LEAF: # <<<<<<<<<<<<<< + * # ... and node.right_child != _TREE_LEAF: + * if X_ptr[X_sample_stride * i + + */ + while (1) { + __pyx_t_2 = ((__pyx_v_node->left_child != __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF) != 0); + if (!__pyx_t_2) break; + + /* "sklearn/tree/_tree.pyx":3256 + * # ... and node.right_child != _TREE_LEAF: + * if X_ptr[X_sample_stride * i + + * X_fx_stride * node.feature] <= node.threshold: # <<<<<<<<<<<<<< + * node = &self.nodes[node.left_child] + * else: + */ + __pyx_t_2 = (((__pyx_v_X_ptr[((__pyx_v_X_sample_stride * __pyx_v_i) + (__pyx_v_X_fx_stride * __pyx_v_node->feature))]) <= __pyx_v_node->threshold) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_tree.pyx":3257 + * if X_ptr[X_sample_stride * i + + * X_fx_stride * node.feature] <= node.threshold: + * node = &self.nodes[node.left_child] # <<<<<<<<<<<<<< + * else: + * node = &self.nodes[node.right_child] + */ + __pyx_v_node = (&(__pyx_v_self->nodes[__pyx_v_node->left_child])); + goto __pyx_L12; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":3259 + * node = &self.nodes[node.left_child] + * else: + * node = &self.nodes[node.right_child] # <<<<<<<<<<<<<< + * + * out_ptr[i] = (node - self.nodes) # node offset + */ + __pyx_v_node = (&(__pyx_v_self->nodes[__pyx_v_node->right_child])); + } + __pyx_L12:; + } + + /* "sklearn/tree/_tree.pyx":3261 + * node = &self.nodes[node.right_child] + * + * out_ptr[i] = (node - self.nodes) # node offset # <<<<<<<<<<<<<< + * + * return out + */ + (__pyx_v_out_ptr[__pyx_v_i]) = ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)(__pyx_v_node - __pyx_v_self->nodes)); + } + } + + /* "sklearn/tree/_tree.pyx":3249 + * cdef SIZE_t i = 0 + * + * with nogil: # <<<<<<<<<<<<<< + * for i in range(n_samples): + * node = self.nodes + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L7; + } + __pyx_L7:; + } + } + + /* "sklearn/tree/_tree.pyx":3263 + * out_ptr[i] = (node - self.nodes) # node offset + * + * return out # <<<<<<<<<<<<<< + * + * cdef inline np.ndarray _apply_sparse_csr(self, object X): + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_out)); + __pyx_r = ((PyArrayObject *)__pyx_v_out); + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3223 + * + * + * cdef inline np.ndarray _apply_dense(self, object X): # <<<<<<<<<<<<<< + * """Finds the terminal region (=leaf node) for each sample in X.""" + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.tree._tree.Tree._apply_dense", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_X_ndarray); + __Pyx_XDECREF((PyObject *)__pyx_v_out); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3265 + * return out + * + * cdef inline np.ndarray _apply_sparse_csr(self, object X): # <<<<<<<<<<<<<< + * """Finds the terminal region (=leaf node) for each sample in sparse X. + * + */ + +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree__apply_sparse_csr(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_X) { + PyArrayObject *__pyx_v_X_data_ndarray = 0; + PyArrayObject *__pyx_v_X_indices_ndarray = 0; + PyArrayObject *__pyx_v_X_indptr_ndarray = 0; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_data; + __pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_v_X_indices; + __pyx_t_7sklearn_4tree_5_tree_INT32_t *__pyx_v_X_indptr; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_samples; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_n_features; + PyArrayObject *__pyx_v_out = 0; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_out_ptr; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t __pyx_v_feature_value; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_node; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_X_sample; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_i; + __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_v_k; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_feature_to_sample; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_data_ndarray; + __Pyx_Buffer __pyx_pybuffer_X_data_ndarray; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indices_ndarray; + __Pyx_Buffer __pyx_pybuffer_X_indices_ndarray; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indptr_ndarray; + __Pyx_Buffer __pyx_pybuffer_X_indptr_ndarray; + __Pyx_LocalBuf_ND __pyx_pybuffernd_out; + __Pyx_Buffer __pyx_pybuffer_out; + PyArrayObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + PyArrayObject *__pyx_t_7 = NULL; + PyArrayObject *__pyx_t_8 = NULL; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + PyArrayObject *__pyx_t_12 = NULL; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_13; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_t_14; + __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_t_15; + __pyx_t_7sklearn_4tree_5_tree_INT32_t __pyx_t_16; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_apply_sparse_csr", 0); + __pyx_pybuffer_X_data_ndarray.pybuffer.buf = NULL; + __pyx_pybuffer_X_data_ndarray.refcount = 0; + __pyx_pybuffernd_X_data_ndarray.data = NULL; + __pyx_pybuffernd_X_data_ndarray.rcbuffer = &__pyx_pybuffer_X_data_ndarray; + __pyx_pybuffer_X_indices_ndarray.pybuffer.buf = NULL; + __pyx_pybuffer_X_indices_ndarray.refcount = 0; + __pyx_pybuffernd_X_indices_ndarray.data = NULL; + __pyx_pybuffernd_X_indices_ndarray.rcbuffer = &__pyx_pybuffer_X_indices_ndarray; + __pyx_pybuffer_X_indptr_ndarray.pybuffer.buf = NULL; + __pyx_pybuffer_X_indptr_ndarray.refcount = 0; + __pyx_pybuffernd_X_indptr_ndarray.data = NULL; + __pyx_pybuffernd_X_indptr_ndarray.rcbuffer = &__pyx_pybuffer_X_indptr_ndarray; + __pyx_pybuffer_out.pybuffer.buf = NULL; + __pyx_pybuffer_out.refcount = 0; + __pyx_pybuffernd_out.data = NULL; + __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; + + /* "sklearn/tree/_tree.pyx":3270 + * """ + * # Check input + * if not isinstance(X, csr_matrix): # <<<<<<<<<<<<<< + * raise ValueError("X should be in csr_matrix format, got %s" + * % type(X)) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_csr_matrix); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_IsInstance(__pyx_v_X, __pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3270; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0); + if (__pyx_t_3) { + + /* "sklearn/tree/_tree.pyx":3272 + * if not isinstance(X, csr_matrix): + * raise ValueError("X should be in csr_matrix format, got %s" + * % type(X)) # <<<<<<<<<<<<<< + * + * if X.dtype != DTYPE: + */ + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_X_should_be_in_csr_matrix_format, ((PyObject *)Py_TYPE(__pyx_v_X))); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "sklearn/tree/_tree.pyx":3271 + * # Check input + * if not isinstance(X, csr_matrix): + * raise ValueError("X should be in csr_matrix format, got %s" # <<<<<<<<<<<<<< + * % type(X)) + * + */ + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3274 + * % type(X)) + * + * if X.dtype != DTYPE: # <<<<<<<<<<<<<< + * raise ValueError("X.dtype should be np.float32, got %s" % X.dtype) + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3274; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3274; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyObject_RichCompare(__pyx_t_1, __pyx_t_4, Py_NE); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3274; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3274; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_3) { + + /* "sklearn/tree/_tree.pyx":3275 + * + * if X.dtype != DTYPE: + * raise ValueError("X.dtype should be np.float32, got %s" % X.dtype) # <<<<<<<<<<<<<< + * + * # Extract input + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_dtype); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_X_dtype_should_be_np_float32_got, __pyx_t_5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3278 + * + * # Extract input + * cdef np.ndarray[ndim=1, dtype=DTYPE_t] X_data_ndarray = X.data # <<<<<<<<<<<<<< + * cdef np.ndarray[ndim=1, dtype=INT32_t] X_indices_ndarray = X.indices + * cdef np.ndarray[ndim=1, dtype=INT32_t] X_indptr_ndarray = X.indptr + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_data_ndarray.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_data_ndarray = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_data_ndarray.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_data_ndarray.diminfo[0].strides = __pyx_pybuffernd_X_data_ndarray.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_data_ndarray.diminfo[0].shape = __pyx_pybuffernd_X_data_ndarray.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __pyx_v_X_data_ndarray = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/tree/_tree.pyx":3279 + * # Extract input + * cdef np.ndarray[ndim=1, dtype=DTYPE_t] X_data_ndarray = X.data + * cdef np.ndarray[ndim=1, dtype=INT32_t] X_indices_ndarray = X.indices # <<<<<<<<<<<<<< + * cdef np.ndarray[ndim=1, dtype=INT32_t] X_indptr_ndarray = X.indptr + * + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indices_ndarray.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_INT32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indices_ndarray = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indices_ndarray.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indices_ndarray.diminfo[0].strides = __pyx_pybuffernd_X_indices_ndarray.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indices_ndarray.diminfo[0].shape = __pyx_pybuffernd_X_indices_ndarray.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_7 = 0; + __pyx_v_X_indices_ndarray = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/tree/_tree.pyx":3280 + * cdef np.ndarray[ndim=1, dtype=DTYPE_t] X_data_ndarray = X.data + * cdef np.ndarray[ndim=1, dtype=INT32_t] X_indices_ndarray = X.indices + * cdef np.ndarray[ndim=1, dtype=INT32_t] X_indptr_ndarray = X.indptr # <<<<<<<<<<<<<< + * + * cdef DTYPE_t* X_data = X_data_ndarray.data + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indptr_ndarray.rcbuffer->pybuffer, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_INT32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indptr_ndarray = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indptr_ndarray.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indptr_ndarray.diminfo[0].strides = __pyx_pybuffernd_X_indptr_ndarray.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indptr_ndarray.diminfo[0].shape = __pyx_pybuffernd_X_indptr_ndarray.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_8 = 0; + __pyx_v_X_indptr_ndarray = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/tree/_tree.pyx":3282 + * cdef np.ndarray[ndim=1, dtype=INT32_t] X_indptr_ndarray = X.indptr + * + * cdef DTYPE_t* X_data = X_data_ndarray.data # <<<<<<<<<<<<<< + * cdef INT32_t* X_indices = X_indices_ndarray.data + * cdef INT32_t* X_indptr = X_indptr_ndarray.data + */ + __pyx_v_X_data = ((__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *)__pyx_v_X_data_ndarray->data); + + /* "sklearn/tree/_tree.pyx":3283 + * + * cdef DTYPE_t* X_data = X_data_ndarray.data + * cdef INT32_t* X_indices = X_indices_ndarray.data # <<<<<<<<<<<<<< + * cdef INT32_t* X_indptr = X_indptr_ndarray.data + * + */ + __pyx_v_X_indices = ((__pyx_t_7sklearn_4tree_5_tree_INT32_t *)__pyx_v_X_indices_ndarray->data); + + /* "sklearn/tree/_tree.pyx":3284 + * cdef DTYPE_t* X_data = X_data_ndarray.data + * cdef INT32_t* X_indices = X_indices_ndarray.data + * cdef INT32_t* X_indptr = X_indptr_ndarray.data # <<<<<<<<<<<<<< + * + * cdef SIZE_t n_samples = X.shape[0] + */ + __pyx_v_X_indptr = ((__pyx_t_7sklearn_4tree_5_tree_INT32_t *)__pyx_v_X_indptr_ndarray->data); + + /* "sklearn/tree/_tree.pyx":3286 + * cdef INT32_t* X_indptr = X_indptr_ndarray.data + * + * cdef SIZE_t n_samples = X.shape[0] # <<<<<<<<<<<<<< + * cdef SIZE_t n_features = X.shape[1] + * + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_t_4, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3286; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_9 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_5); if (unlikely((__pyx_t_9 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_n_samples = __pyx_t_9; + + /* "sklearn/tree/_tree.pyx":3287 + * + * cdef SIZE_t n_samples = X.shape[0] + * cdef SIZE_t n_features = X.shape[1] # <<<<<<<<<<<<<< + * + * # Initialize output + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_GetItemInt(__pyx_t_5, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_4 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3287; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_9 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_4); if (unlikely((__pyx_t_9 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_n_features = __pyx_t_9; + + /* "sklearn/tree/_tree.pyx":3290 + * + * # Initialize output + * cdef np.ndarray[SIZE_t, ndim=1] out = np.zeros((n_samples,), # <<<<<<<<<<<<<< + * dtype=np.intp) + * cdef SIZE_t* out_ptr = out.data + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_samples); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "sklearn/tree/_tree.pyx":3291 + * # Initialize output + * cdef np.ndarray[SIZE_t, ndim=1] out = np.zeros((n_samples,), + * dtype=np.intp) # <<<<<<<<<<<<<< + * cdef SIZE_t* out_ptr = out.data + * + */ + __pyx_t_10 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_t_10, __pyx_n_s_intp); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_11) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + + /* "sklearn/tree/_tree.pyx":3290 + * + * # Initialize output + * cdef np.ndarray[SIZE_t, ndim=1] out = np.zeros((n_samples,), # <<<<<<<<<<<<<< + * dtype=np.intp) + * cdef SIZE_t* out_ptr = out.data + */ + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_11) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_11, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = ((PyArrayObject *)__pyx_t_11); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_12, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_4tree_5_tree_SIZE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_out.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_12 = 0; + __pyx_v_out = ((PyArrayObject *)__pyx_t_11); + __pyx_t_11 = 0; + + /* "sklearn/tree/_tree.pyx":3292 + * cdef np.ndarray[SIZE_t, ndim=1] out = np.zeros((n_samples,), + * dtype=np.intp) + * cdef SIZE_t* out_ptr = out.data # <<<<<<<<<<<<<< + * + * # Initialize auxiliary data-structure + */ + __pyx_v_out_ptr = ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t *)__pyx_v_out->data); + + /* "sklearn/tree/_tree.pyx":3295 + * + * # Initialize auxiliary data-structure + * cdef DTYPE_t feature_value = 0. # <<<<<<<<<<<<<< + * cdef Node* node = NULL + * cdef DTYPE_t* X_sample = NULL + */ + __pyx_v_feature_value = 0.; + + /* "sklearn/tree/_tree.pyx":3296 + * # Initialize auxiliary data-structure + * cdef DTYPE_t feature_value = 0. + * cdef Node* node = NULL # <<<<<<<<<<<<<< + * cdef DTYPE_t* X_sample = NULL + * cdef SIZE_t i = 0 + */ + __pyx_v_node = NULL; + + /* "sklearn/tree/_tree.pyx":3297 + * cdef DTYPE_t feature_value = 0. + * cdef Node* node = NULL + * cdef DTYPE_t* X_sample = NULL # <<<<<<<<<<<<<< + * cdef SIZE_t i = 0 + * cdef INT32_t k = 0 + */ + __pyx_v_X_sample = NULL; + + /* "sklearn/tree/_tree.pyx":3298 + * cdef Node* node = NULL + * cdef DTYPE_t* X_sample = NULL + * cdef SIZE_t i = 0 # <<<<<<<<<<<<<< + * cdef INT32_t k = 0 + * + */ + __pyx_v_i = 0; + + /* "sklearn/tree/_tree.pyx":3299 + * cdef DTYPE_t* X_sample = NULL + * cdef SIZE_t i = 0 + * cdef INT32_t k = 0 # <<<<<<<<<<<<<< + * + * # feature_to_sample as a data structure records the last seen sample + */ + __pyx_v_k = 0; + + /* "sklearn/tree/_tree.pyx":3304 + * # for each feature; functionally, it is an efficient way to identify + * # which features are nonzero in the present sample. + * cdef SIZE_t* feature_to_sample = NULL # <<<<<<<<<<<<<< + * + * safe_realloc(&X_sample, n_features * sizeof(DTYPE_t)) + */ + __pyx_v_feature_to_sample = NULL; + + /* "sklearn/tree/_tree.pyx":3306 + * cdef SIZE_t* feature_to_sample = NULL + * + * safe_realloc(&X_sample, n_features * sizeof(DTYPE_t)) # <<<<<<<<<<<<<< + * safe_realloc(&feature_to_sample, n_features * sizeof(SIZE_t)) + * + */ + __pyx_fuse_0__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_X_sample), (__pyx_v_n_features * (sizeof(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t)))); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3306; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":3307 + * + * safe_realloc(&X_sample, n_features * sizeof(DTYPE_t)) + * safe_realloc(&feature_to_sample, n_features * sizeof(SIZE_t)) # <<<<<<<<<<<<<< + * + * with nogil: + */ + __pyx_fuse_1__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_feature_to_sample), (__pyx_v_n_features * (sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)))); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3307; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":3309 + * safe_realloc(&feature_to_sample, n_features * sizeof(SIZE_t)) + * + * with nogil: # <<<<<<<<<<<<<< + * memset(feature_to_sample, -1, n_features * sizeof(SIZE_t)) + * + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/tree/_tree.pyx":3310 + * + * with nogil: + * memset(feature_to_sample, -1, n_features * sizeof(SIZE_t)) # <<<<<<<<<<<<<< + * + * for i in range(n_samples): + */ + memset(__pyx_v_feature_to_sample, -1, (__pyx_v_n_features * (sizeof(__pyx_t_7sklearn_4tree_5_tree_SIZE_t)))); + + /* "sklearn/tree/_tree.pyx":3312 + * memset(feature_to_sample, -1, n_features * sizeof(SIZE_t)) + * + * for i in range(n_samples): # <<<<<<<<<<<<<< + * node = self.nodes + * + */ + __pyx_t_9 = __pyx_v_n_samples; + for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_9; __pyx_t_13+=1) { + __pyx_v_i = __pyx_t_13; + + /* "sklearn/tree/_tree.pyx":3313 + * + * for i in range(n_samples): + * node = self.nodes # <<<<<<<<<<<<<< + * + * for k in range(X_indptr[i], X_indptr[i + 1]): + */ + __pyx_t_14 = __pyx_v_self->nodes; + __pyx_v_node = __pyx_t_14; + + /* "sklearn/tree/_tree.pyx":3315 + * node = self.nodes + * + * for k in range(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< + * feature_to_sample[X_indices[k]] = i + * X_sample[X_indices[k]] = X_data[k] + */ + __pyx_t_15 = (__pyx_v_X_indptr[(__pyx_v_i + 1)]); + for (__pyx_t_16 = (__pyx_v_X_indptr[__pyx_v_i]); __pyx_t_16 < __pyx_t_15; __pyx_t_16+=1) { + __pyx_v_k = __pyx_t_16; + + /* "sklearn/tree/_tree.pyx":3316 + * + * for k in range(X_indptr[i], X_indptr[i + 1]): + * feature_to_sample[X_indices[k]] = i # <<<<<<<<<<<<<< + * X_sample[X_indices[k]] = X_data[k] + * + */ + (__pyx_v_feature_to_sample[(__pyx_v_X_indices[__pyx_v_k])]) = __pyx_v_i; + + /* "sklearn/tree/_tree.pyx":3317 + * for k in range(X_indptr[i], X_indptr[i + 1]): + * feature_to_sample[X_indices[k]] = i + * X_sample[X_indices[k]] = X_data[k] # <<<<<<<<<<<<<< + * + * # While node not a leaf + */ + (__pyx_v_X_sample[(__pyx_v_X_indices[__pyx_v_k])]) = (__pyx_v_X_data[__pyx_v_k]); + } + + /* "sklearn/tree/_tree.pyx":3320 + * + * # While node not a leaf + * while node.left_child != _TREE_LEAF: # <<<<<<<<<<<<<< + * # ... and node.right_child != _TREE_LEAF: + * if feature_to_sample[node.feature] == i: + */ + while (1) { + __pyx_t_3 = ((__pyx_v_node->left_child != __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF) != 0); + if (!__pyx_t_3) break; + + /* "sklearn/tree/_tree.pyx":3322 + * while node.left_child != _TREE_LEAF: + * # ... and node.right_child != _TREE_LEAF: + * if feature_to_sample[node.feature] == i: # <<<<<<<<<<<<<< + * feature_value = X_sample[node.feature] + * + */ + __pyx_t_3 = (((__pyx_v_feature_to_sample[__pyx_v_node->feature]) == __pyx_v_i) != 0); + if (__pyx_t_3) { + + /* "sklearn/tree/_tree.pyx":3323 + * # ... and node.right_child != _TREE_LEAF: + * if feature_to_sample[node.feature] == i: + * feature_value = X_sample[node.feature] # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_v_feature_value = (__pyx_v_X_sample[__pyx_v_node->feature]); + goto __pyx_L14; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":3326 + * + * else: + * feature_value = 0. # <<<<<<<<<<<<<< + * + * if feature_value <= node.threshold: + */ + __pyx_v_feature_value = 0.; + } + __pyx_L14:; + + /* "sklearn/tree/_tree.pyx":3328 + * feature_value = 0. + * + * if feature_value <= node.threshold: # <<<<<<<<<<<<<< + * node = &self.nodes[node.left_child] + * else: + */ + __pyx_t_3 = ((__pyx_v_feature_value <= __pyx_v_node->threshold) != 0); + if (__pyx_t_3) { + + /* "sklearn/tree/_tree.pyx":3329 + * + * if feature_value <= node.threshold: + * node = &self.nodes[node.left_child] # <<<<<<<<<<<<<< + * else: + * node = &self.nodes[node.right_child] + */ + __pyx_v_node = (&(__pyx_v_self->nodes[__pyx_v_node->left_child])); + goto __pyx_L15; + } + /*else*/ { + + /* "sklearn/tree/_tree.pyx":3331 + * node = &self.nodes[node.left_child] + * else: + * node = &self.nodes[node.right_child] # <<<<<<<<<<<<<< + * + * out_ptr[i] = (node - self.nodes) # node offset + */ + __pyx_v_node = (&(__pyx_v_self->nodes[__pyx_v_node->right_child])); + } + __pyx_L15:; + } + + /* "sklearn/tree/_tree.pyx":3333 + * node = &self.nodes[node.right_child] + * + * out_ptr[i] = (node - self.nodes) # node offset # <<<<<<<<<<<<<< + * + * # Free auxiliary arrays + */ + (__pyx_v_out_ptr[__pyx_v_i]) = ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)(__pyx_v_node - __pyx_v_self->nodes)); + } + + /* "sklearn/tree/_tree.pyx":3336 + * + * # Free auxiliary arrays + * free(X_sample) # <<<<<<<<<<<<<< + * free(feature_to_sample) + * + */ + free(__pyx_v_X_sample); + + /* "sklearn/tree/_tree.pyx":3337 + * # Free auxiliary arrays + * free(X_sample) + * free(feature_to_sample) # <<<<<<<<<<<<<< + * + * return out + */ + free(__pyx_v_feature_to_sample); + } + + /* "sklearn/tree/_tree.pyx":3309 + * safe_realloc(&feature_to_sample, n_features * sizeof(SIZE_t)) + * + * with nogil: # <<<<<<<<<<<<<< + * memset(feature_to_sample, -1, n_features * sizeof(SIZE_t)) + * + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L7; + } + __pyx_L7:; + } + } + + /* "sklearn/tree/_tree.pyx":3339 + * free(feature_to_sample) + * + * return out # <<<<<<<<<<<<<< + * + * cpdef compute_feature_importances(self, normalize=True): + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_out)); + __pyx_r = ((PyArrayObject *)__pyx_v_out); + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3265 + * return out + * + * cdef inline np.ndarray _apply_sparse_csr(self, object X): # <<<<<<<<<<<<<< + * """Finds the terminal region (=leaf node) for each sample in sparse X. + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data_ndarray.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices_ndarray.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr_ndarray.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.tree._tree.Tree._apply_sparse_csr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data_ndarray.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices_ndarray.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr_ndarray.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_X_data_ndarray); + __Pyx_XDECREF((PyObject *)__pyx_v_X_indices_ndarray); + __Pyx_XDECREF((PyObject *)__pyx_v_X_indptr_ndarray); + __Pyx_XDECREF((PyObject *)__pyx_v_out); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3341 + * return out + * + * cpdef compute_feature_importances(self, normalize=True): # <<<<<<<<<<<<<< + * """Computes the importance of each feature (aka variable).""" + * cdef Node* left + */ + +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_15compute_feature_importances(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyObject *__pyx_f_7sklearn_4tree_5_tree_4Tree_compute_feature_importances(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances *__pyx_optional_args) { + PyObject *__pyx_v_normalize = ((PyObject *)Py_True); + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_left; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_right; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_nodes; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_node; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_v_end_node; + double __pyx_v_normalizer; + PyArrayObject *__pyx_v_importances = 0; + __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *__pyx_v_importance_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_importances; + __Pyx_Buffer __pyx_pybuffer_importances; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + struct __pyx_t_7sklearn_4tree_5_tree_Node *__pyx_t_6; + PyArrayObject *__pyx_t_7 = NULL; + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_t_12; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_13; + double __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("compute_feature_importances", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_normalize = __pyx_optional_args->normalize; + } + } + __pyx_pybuffer_importances.pybuffer.buf = NULL; + __pyx_pybuffer_importances.refcount = 0; + __pyx_pybuffernd_importances.data = NULL; + __pyx_pybuffernd_importances.rcbuffer = &__pyx_pybuffer_importances; + /* Check if called by wrapper */ + if (unlikely(__pyx_skip_dispatch)) ; + /* Check if overridden in Python */ + else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_compute_feature_importances); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_15compute_feature_importances)) { + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_3 = __pyx_t_1; __pyx_t_4 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (!__pyx_t_4) { + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_normalize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + } else { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_v_normalize); + PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_v_normalize); + __Pyx_GIVEREF(__pyx_v_normalize); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "sklearn/tree/_tree.pyx":3345 + * cdef Node* left + * cdef Node* right + * cdef Node* nodes = self.nodes # <<<<<<<<<<<<<< + * cdef Node* node = nodes + * cdef Node* end_node = node + self.node_count + */ + __pyx_t_6 = __pyx_v_self->nodes; + __pyx_v_nodes = __pyx_t_6; + + /* "sklearn/tree/_tree.pyx":3346 + * cdef Node* right + * cdef Node* nodes = self.nodes + * cdef Node* node = nodes # <<<<<<<<<<<<<< + * cdef Node* end_node = node + self.node_count + * + */ + __pyx_v_node = __pyx_v_nodes; + + /* "sklearn/tree/_tree.pyx":3347 + * cdef Node* nodes = self.nodes + * cdef Node* node = nodes + * cdef Node* end_node = node + self.node_count # <<<<<<<<<<<<<< + * + * cdef double normalizer = 0. + */ + __pyx_v_end_node = (__pyx_v_node + __pyx_v_self->node_count); + + /* "sklearn/tree/_tree.pyx":3349 + * cdef Node* end_node = node + self.node_count + * + * cdef double normalizer = 0. # <<<<<<<<<<<<<< + * + * cdef np.ndarray[np.float64_t, ndim=1] importances + */ + __pyx_v_normalizer = 0.; + + /* "sklearn/tree/_tree.pyx":3352 + * + * cdef np.ndarray[np.float64_t, ndim=1] importances + * importances = np.zeros((self.n_features,)) # <<<<<<<<<<<<<< + * cdef DOUBLE_t* importance_data = importances.data + * + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_features); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + if (!__pyx_t_2) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = NULL; + PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_importances.rcbuffer->pybuffer); + __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_importances.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_8 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_importances.rcbuffer->pybuffer, (PyObject*)__pyx_v_importances, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } + } + __pyx_pybuffernd_importances.diminfo[0].strides = __pyx_pybuffernd_importances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_importances.diminfo[0].shape = __pyx_pybuffernd_importances.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_7 = 0; + __pyx_v_importances = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":3353 + * cdef np.ndarray[np.float64_t, ndim=1] importances + * importances = np.zeros((self.n_features,)) + * cdef DOUBLE_t* importance_data = importances.data # <<<<<<<<<<<<<< + * + * with nogil: + */ + __pyx_v_importance_data = ((__pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *)__pyx_v_importances->data); + + /* "sklearn/tree/_tree.pyx":3355 + * cdef DOUBLE_t* importance_data = importances.data + * + * with nogil: # <<<<<<<<<<<<<< + * while node != end_node: + * if node.left_child != _TREE_LEAF: + */ + { + #ifdef WITH_THREAD + PyThreadState *_save; + Py_UNBLOCK_THREADS + #endif + /*try:*/ { + + /* "sklearn/tree/_tree.pyx":3356 + * + * with nogil: + * while node != end_node: # <<<<<<<<<<<<<< + * if node.left_child != _TREE_LEAF: + * # ... and node.right_child != _TREE_LEAF: + */ + while (1) { + __pyx_t_12 = ((__pyx_v_node != __pyx_v_end_node) != 0); + if (!__pyx_t_12) break; + + /* "sklearn/tree/_tree.pyx":3357 + * with nogil: + * while node != end_node: + * if node.left_child != _TREE_LEAF: # <<<<<<<<<<<<<< + * # ... and node.right_child != _TREE_LEAF: + * left = &nodes[node.left_child] + */ + __pyx_t_12 = ((__pyx_v_node->left_child != __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF) != 0); + if (__pyx_t_12) { + + /* "sklearn/tree/_tree.pyx":3359 + * if node.left_child != _TREE_LEAF: + * # ... and node.right_child != _TREE_LEAF: + * left = &nodes[node.left_child] # <<<<<<<<<<<<<< + * right = &nodes[node.right_child] + * + */ + __pyx_v_left = (&(__pyx_v_nodes[__pyx_v_node->left_child])); + + /* "sklearn/tree/_tree.pyx":3360 + * # ... and node.right_child != _TREE_LEAF: + * left = &nodes[node.left_child] + * right = &nodes[node.right_child] # <<<<<<<<<<<<<< + * + * importance_data[node.feature] += ( + */ + __pyx_v_right = (&(__pyx_v_nodes[__pyx_v_node->right_child])); + + /* "sklearn/tree/_tree.pyx":3362 + * right = &nodes[node.right_child] + * + * importance_data[node.feature] += ( # <<<<<<<<<<<<<< + * node.weighted_n_node_samples * node.impurity - + * left.weighted_n_node_samples * left.impurity - + */ + __pyx_t_13 = __pyx_v_node->feature; + + /* "sklearn/tree/_tree.pyx":3364 + * importance_data[node.feature] += ( + * node.weighted_n_node_samples * node.impurity - + * left.weighted_n_node_samples * left.impurity - # <<<<<<<<<<<<<< + * right.weighted_n_node_samples * right.impurity) + * node += 1 + */ + (__pyx_v_importance_data[__pyx_t_13]) = ((__pyx_v_importance_data[__pyx_t_13]) + (((__pyx_v_node->weighted_n_node_samples * __pyx_v_node->impurity) - (__pyx_v_left->weighted_n_node_samples * __pyx_v_left->impurity)) - (__pyx_v_right->weighted_n_node_samples * __pyx_v_right->impurity))); + goto __pyx_L8; + } + __pyx_L8:; + + /* "sklearn/tree/_tree.pyx":3366 + * left.weighted_n_node_samples * left.impurity - + * right.weighted_n_node_samples * right.impurity) + * node += 1 # <<<<<<<<<<<<<< + * + * importances /= nodes[0].weighted_n_node_samples + */ + __pyx_v_node = (__pyx_v_node + 1); + } + } + + /* "sklearn/tree/_tree.pyx":3355 + * cdef DOUBLE_t* importance_data = importances.data + * + * with nogil: # <<<<<<<<<<<<<< + * while node != end_node: + * if node.left_child != _TREE_LEAF: + */ + /*finally:*/ { + /*normal exit:*/{ + #ifdef WITH_THREAD + Py_BLOCK_THREADS + #endif + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "sklearn/tree/_tree.pyx":3368 + * node += 1 + * + * importances /= nodes[0].weighted_n_node_samples # <<<<<<<<<<<<<< + * + * if normalize: + */ + __pyx_t_1 = PyFloat_FromDouble((__pyx_v_nodes[0]).weighted_n_node_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyNumber_InPlaceDivide(((PyObject *)__pyx_v_importances), __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_3); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_importances.rcbuffer->pybuffer); + __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_importances.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_8 < 0)) { + PyErr_Fetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_importances.rcbuffer->pybuffer, (PyObject*)__pyx_v_importances, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_11, __pyx_t_10, __pyx_t_9); + } + } + __pyx_pybuffernd_importances.diminfo[0].strides = __pyx_pybuffernd_importances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_importances.diminfo[0].shape = __pyx_pybuffernd_importances.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_7 = 0; + __Pyx_DECREF_SET(__pyx_v_importances, ((PyArrayObject *)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "sklearn/tree/_tree.pyx":3370 + * importances /= nodes[0].weighted_n_node_samples + * + * if normalize: # <<<<<<<<<<<<<< + * normalizer = np.sum(importances) + * + */ + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_normalize); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_12) { + + /* "sklearn/tree/_tree.pyx":3371 + * + * if normalize: + * normalizer = np.sum(importances) # <<<<<<<<<<<<<< + * + * if normalizer > 0.0: + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3371; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_sum); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3371; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = NULL; + if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + } + } + if (!__pyx_t_1) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, ((PyObject *)__pyx_v_importances)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3371; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + } else { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3371; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = NULL; + __Pyx_INCREF(((PyObject *)__pyx_v_importances)); + PyTuple_SET_ITEM(__pyx_t_5, 0+1, ((PyObject *)__pyx_v_importances)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_importances)); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3371; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_14 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_14 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3371; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_normalizer = __pyx_t_14; + + /* "sklearn/tree/_tree.pyx":3373 + * normalizer = np.sum(importances) + * + * if normalizer > 0.0: # <<<<<<<<<<<<<< + * # Avoid dividing by zero (e.g., when root is pure) + * importances /= normalizer + */ + __pyx_t_12 = ((__pyx_v_normalizer > 0.0) != 0); + if (__pyx_t_12) { + + /* "sklearn/tree/_tree.pyx":3375 + * if normalizer > 0.0: + * # Avoid dividing by zero (e.g., when root is pure) + * importances /= normalizer # <<<<<<<<<<<<<< + * + * return importances + */ + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_normalizer); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyNumber_InPlaceDivide(((PyObject *)__pyx_v_importances), __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_importances.rcbuffer->pybuffer); + __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_importances.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_8 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_importances.rcbuffer->pybuffer, (PyObject*)__pyx_v_importances, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } + } + __pyx_pybuffernd_importances.diminfo[0].strides = __pyx_pybuffernd_importances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_importances.diminfo[0].shape = __pyx_pybuffernd_importances.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_7 = 0; + __Pyx_DECREF_SET(__pyx_v_importances, ((PyArrayObject *)__pyx_t_4)); + __pyx_t_4 = 0; + goto __pyx_L10; + } + __pyx_L10:; + goto __pyx_L9; + } + __pyx_L9:; + + /* "sklearn/tree/_tree.pyx":3377 + * importances /= normalizer + * + * return importances # <<<<<<<<<<<<<< + * + * cdef np.ndarray _get_value_ndarray(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_importances)); + __pyx_r = ((PyObject *)__pyx_v_importances); + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3341 + * return out + * + * cpdef compute_feature_importances(self, normalize=True): # <<<<<<<<<<<<<< + * """Computes the importance of each feature (aka variable).""" + * cdef Node* left + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_importances.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.tree._tree.Tree.compute_feature_importances", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_importances.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_importances); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_15compute_feature_importances(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_4tree_5_tree_4Tree_14compute_feature_importances[] = "Computes the importance of each feature (aka variable)."; +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_15compute_feature_importances(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_normalize = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("compute_feature_importances (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_normalize,0}; + PyObject* values[1] = {0}; + values[0] = ((PyObject *)Py_True); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_normalize); + if (value) { values[0] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "compute_feature_importances") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3341; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_normalize = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("compute_feature_importances", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3341; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._tree.Tree.compute_feature_importances", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_14compute_feature_importances(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), __pyx_v_normalize); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_14compute_feature_importances(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_normalize) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("compute_feature_importances", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_2.__pyx_n = 1; + __pyx_t_2.normalize = __pyx_v_normalize; + __pyx_t_1 = __pyx_vtabptr_7sklearn_4tree_5_tree_Tree->compute_feature_importances(__pyx_v_self, 1, &__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.compute_feature_importances", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3379 + * return importances + * + * cdef np.ndarray _get_value_ndarray(self): # <<<<<<<<<<<<<< + * """Wraps value as a 3-d NumPy array + * + */ + +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree__get_value_ndarray(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + npy_intp __pyx_v_shape[3]; + PyArrayObject *__pyx_v_arr = 0; + PyArrayObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_get_value_ndarray", 0); + + /* "sklearn/tree/_tree.pyx":3386 + * """ + * cdef np.npy_intp shape[3] + * shape[0] = self.node_count # <<<<<<<<<<<<<< + * shape[1] = self.n_outputs + * shape[2] = self.max_n_classes + */ + (__pyx_v_shape[0]) = ((npy_intp)__pyx_v_self->node_count); + + /* "sklearn/tree/_tree.pyx":3387 + * cdef np.npy_intp shape[3] + * shape[0] = self.node_count + * shape[1] = self.n_outputs # <<<<<<<<<<<<<< + * shape[2] = self.max_n_classes + * cdef np.ndarray arr + */ + (__pyx_v_shape[1]) = ((npy_intp)__pyx_v_self->n_outputs); + + /* "sklearn/tree/_tree.pyx":3388 + * shape[0] = self.node_count + * shape[1] = self.n_outputs + * shape[2] = self.max_n_classes # <<<<<<<<<<<<<< + * cdef np.ndarray arr + * arr = np.PyArray_SimpleNewFromData(3, shape, np.NPY_DOUBLE, self.value) + */ + (__pyx_v_shape[2]) = ((npy_intp)__pyx_v_self->max_n_classes); + + /* "sklearn/tree/_tree.pyx":3390 + * shape[2] = self.max_n_classes + * cdef np.ndarray arr + * arr = np.PyArray_SimpleNewFromData(3, shape, np.NPY_DOUBLE, self.value) # <<<<<<<<<<<<<< + * Py_INCREF(self) + * arr.base = self + */ + __pyx_t_1 = PyArray_SimpleNewFromData(3, __pyx_v_shape, NPY_DOUBLE, __pyx_v_self->value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_arr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":3391 + * cdef np.ndarray arr + * arr = np.PyArray_SimpleNewFromData(3, shape, np.NPY_DOUBLE, self.value) + * Py_INCREF(self) # <<<<<<<<<<<<<< + * arr.base = self + * return arr + */ + Py_INCREF(((PyObject *)__pyx_v_self)); + + /* "sklearn/tree/_tree.pyx":3392 + * arr = np.PyArray_SimpleNewFromData(3, shape, np.NPY_DOUBLE, self.value) + * Py_INCREF(self) + * arr.base = self # <<<<<<<<<<<<<< + * return arr + * + */ + __pyx_v_arr->base = ((PyObject *)__pyx_v_self); + + /* "sklearn/tree/_tree.pyx":3393 + * Py_INCREF(self) + * arr.base = self + * return arr # <<<<<<<<<<<<<< + * + * cdef np.ndarray _get_node_ndarray(self): + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_arr)); + __pyx_r = __pyx_v_arr; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3379 + * return importances + * + * cdef np.ndarray _get_value_ndarray(self): # <<<<<<<<<<<<<< + * """Wraps value as a 3-d NumPy array + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.Tree._get_value_ndarray", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_arr); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3395 + * return arr + * + * cdef np.ndarray _get_node_ndarray(self): # <<<<<<<<<<<<<< + * """Wraps nodes as a NumPy struct array + * + */ + +static PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_4Tree__get_node_ndarray(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + npy_intp __pyx_v_shape[1]; + npy_intp __pyx_v_strides[1]; + PyArrayObject *__pyx_v_arr = 0; + PyArrayObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_get_node_ndarray", 0); + + /* "sklearn/tree/_tree.pyx":3403 + * """ + * cdef np.npy_intp shape[1] + * shape[0] = self.node_count # <<<<<<<<<<<<<< + * cdef np.npy_intp strides[1] + * strides[0] = sizeof(Node) + */ + (__pyx_v_shape[0]) = ((npy_intp)__pyx_v_self->node_count); + + /* "sklearn/tree/_tree.pyx":3405 + * shape[0] = self.node_count + * cdef np.npy_intp strides[1] + * strides[0] = sizeof(Node) # <<<<<<<<<<<<<< + * cdef np.ndarray arr + * Py_INCREF(NODE_DTYPE) + */ + (__pyx_v_strides[0]) = (sizeof(struct __pyx_t_7sklearn_4tree_5_tree_Node)); + + /* "sklearn/tree/_tree.pyx":3407 + * strides[0] = sizeof(Node) + * cdef np.ndarray arr + * Py_INCREF(NODE_DTYPE) # <<<<<<<<<<<<<< + * arr = PyArray_NewFromDescr(np.ndarray, NODE_DTYPE, 1, shape, + * strides, self.nodes, + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_NODE_DTYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + Py_INCREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":3408 + * cdef np.ndarray arr + * Py_INCREF(NODE_DTYPE) + * arr = PyArray_NewFromDescr(np.ndarray, NODE_DTYPE, 1, shape, # <<<<<<<<<<<<<< + * strides, self.nodes, + * np.NPY_DEFAULT, None) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_NODE_DTYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "sklearn/tree/_tree.pyx":3410 + * arr = PyArray_NewFromDescr(np.ndarray, NODE_DTYPE, 1, shape, + * strides, self.nodes, + * np.NPY_DEFAULT, None) # <<<<<<<<<<<<<< + * Py_INCREF(self) + * arr.base = self + */ + __pyx_t_2 = PyArray_NewFromDescr(((PyObject *)((PyObject*)__pyx_ptype_5numpy_ndarray)), ((PyArray_Descr *)__pyx_t_1), 1, __pyx_v_shape, __pyx_v_strides, ((void *)__pyx_v_self->nodes), NPY_DEFAULT, Py_None); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":3408 + * cdef np.ndarray arr + * Py_INCREF(NODE_DTYPE) + * arr = PyArray_NewFromDescr(np.ndarray, NODE_DTYPE, 1, shape, # <<<<<<<<<<<<<< + * strides, self.nodes, + * np.NPY_DEFAULT, None) + */ + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_arr = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/tree/_tree.pyx":3411 + * strides, self.nodes, + * np.NPY_DEFAULT, None) + * Py_INCREF(self) # <<<<<<<<<<<<<< + * arr.base = self + * return arr + */ + Py_INCREF(((PyObject *)__pyx_v_self)); + + /* "sklearn/tree/_tree.pyx":3412 + * np.NPY_DEFAULT, None) + * Py_INCREF(self) + * arr.base = self # <<<<<<<<<<<<<< + * return arr + * + */ + __pyx_v_arr->base = ((PyObject *)__pyx_v_self); + + /* "sklearn/tree/_tree.pyx":3413 + * Py_INCREF(self) + * arr.base = self + * return arr # <<<<<<<<<<<<<< + * + * # ============================================================================= + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_arr)); + __pyx_r = __pyx_v_arr; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3395 + * return arr + * + * cdef np.ndarray _get_node_ndarray(self): # <<<<<<<<<<<<<< + * """Wraps nodes as a NumPy struct array + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("sklearn.tree._tree.Tree._get_node_ndarray", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_arr); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pxd":164 + * + * # Input/Output layout + * cdef public SIZE_t n_features # Number of features in X # <<<<<<<<<<<<<< + * cdef SIZE_t* n_classes # Number of classes in y[:, k] + * cdef public SIZE_t n_outputs # Number of outputs in y + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_features.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_10n_features_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_value); if (unlikely((__pyx_t_1 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->n_features = __pyx_t_1; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_features.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pxd":166 + * cdef public SIZE_t n_features # Number of features in X + * cdef SIZE_t* n_classes # Number of classes in y[:, k] + * cdef public SIZE_t n_outputs # Number of outputs in y # <<<<<<<<<<<<<< + * cdef public SIZE_t max_n_classes # max(n_classes) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->n_outputs); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_outputs.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_9n_outputs_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_value); if (unlikely((__pyx_t_1 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->n_outputs = __pyx_t_1; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.tree._tree.Tree.n_outputs.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pxd":167 + * cdef SIZE_t* n_classes # Number of classes in y[:, k] + * cdef public SIZE_t n_outputs # Number of outputs in y + * cdef public SIZE_t max_n_classes # max(n_classes) # <<<<<<<<<<<<<< + * + * # Inner structures: values are stored separately from node structure, + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->max_n_classes); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.max_n_classes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_13max_n_classes_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_value); if (unlikely((__pyx_t_1 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->max_n_classes = __pyx_t_1; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.tree._tree.Tree.max_n_classes.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pxd":171 + * # Inner structures: values are stored separately from node structure, + * # since size is determined at runtime. + * cdef public SIZE_t max_depth # Max depth of the tree # <<<<<<<<<<<<<< + * cdef public SIZE_t node_count # Counter for node IDs + * cdef public SIZE_t capacity # Capacity of tree, in terms of nodes + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9max_depth___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_9max_depth___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->max_depth); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.max_depth.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_9max_depth_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_9max_depth_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_value); if (unlikely((__pyx_t_1 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->max_depth = __pyx_t_1; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.tree._tree.Tree.max_depth.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pxd":172 + * # since size is determined at runtime. + * cdef public SIZE_t max_depth # Max depth of the tree + * cdef public SIZE_t node_count # Counter for node IDs # <<<<<<<<<<<<<< + * cdef public SIZE_t capacity # Capacity of tree, in terms of nodes + * cdef Node* nodes # Array of nodes + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10node_count___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_10node_count___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->node_count); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.node_count.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_10node_count_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_10node_count_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_value); if (unlikely((__pyx_t_1 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->node_count = __pyx_t_1; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.tree._tree.Tree.node_count.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pxd":173 + * cdef public SIZE_t max_depth # Max depth of the tree + * cdef public SIZE_t node_count # Counter for node IDs + * cdef public SIZE_t capacity # Capacity of tree, in terms of nodes # <<<<<<<<<<<<<< + * cdef Node* nodes # Array of nodes + * cdef double* value # (capacity, n_outputs, max_n_classes) array of values + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_8capacity___get__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree_4Tree_8capacity___get__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_self->capacity); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.Tree.capacity.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree_4Tree_8capacity_2__set__(((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_5_tree_4Tree_8capacity_2__set__(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __Pyx_PyInt_As_Py_intptr_t(__pyx_v_value); if (unlikely((__pyx_t_1 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->capacity = __pyx_t_1; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.tree._tree.Tree.capacity.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3430 + * (unsigned char*) + * + * cdef realloc_ptr safe_realloc(realloc_ptr* p, size_t nelems) except *: # <<<<<<<<<<<<<< + * # sizeof(realloc_ptr[0]) would be more like idiomatic C, but causes Cython + * # 0.20.1 to crash. + */ + +static __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_fuse_0__pyx_f_7sklearn_4tree_5_tree_safe_realloc(__pyx_t_7sklearn_4tree_5_tree_DTYPE_t **__pyx_v_p, size_t __pyx_v_nelems) { + size_t __pyx_v_nbytes; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_v_tmp; + __pyx_t_7sklearn_4tree_5_tree_DTYPE_t *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_fuse_0safe_realloc", 0); + + /* "sklearn/tree/_tree.pyx":3433 + * # 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]) # <<<<<<<<<<<<<< + * if nbytes / sizeof(p[0][0]) != nelems: + * # Overflow in the multiplication + */ + __pyx_v_nbytes = (__pyx_v_nelems * (sizeof(((__pyx_v_p[0])[0])))); + + /* "sklearn/tree/_tree.pyx":3434 + * # 0.20.1 to crash. + * cdef size_t nbytes = nelems * sizeof(p[0][0]) + * if nbytes / sizeof(p[0][0]) != nelems: # <<<<<<<<<<<<<< + * # Overflow in the multiplication + * raise MemoryError("could not allocate (%d * %d) bytes" + */ + __pyx_t_1 = (((__pyx_v_nbytes / (sizeof(((__pyx_v_p[0])[0])))) != __pyx_v_nelems) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3437 + * # Overflow in the multiplication + * raise MemoryError("could not allocate (%d * %d) bytes" + * % (nelems, sizeof(p[0][0]))) # <<<<<<<<<<<<<< + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + * if tmp == NULL: + */ + __pyx_t_2 = __Pyx_PyInt_FromSize_t(__pyx_v_nelems); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyInt_FromSize_t((sizeof(((__pyx_v_p[0])[0])))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_could_not_allocate_d_d_bytes, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "sklearn/tree/_tree.pyx":3436 + * if nbytes / sizeof(p[0][0]) != nelems: + * # Overflow in the multiplication + * raise MemoryError("could not allocate (%d * %d) bytes" # <<<<<<<<<<<<<< + * % (nelems, sizeof(p[0][0]))) + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + */ + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3438 + * raise MemoryError("could not allocate (%d * %d) bytes" + * % (nelems, sizeof(p[0][0]))) + * cdef realloc_ptr tmp = realloc(p[0], nbytes) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError("could not allocate %d bytes" % nbytes) + */ + __pyx_v_tmp = ((__pyx_t_7sklearn_4tree_5_tree_DTYPE_t *)realloc((__pyx_v_p[0]), __pyx_v_nbytes)); + + /* "sklearn/tree/_tree.pyx":3439 + * % (nelems, sizeof(p[0][0]))) + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate %d bytes" % nbytes) + * + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3440 + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + * if tmp == NULL: + * raise MemoryError("could not allocate %d bytes" % nbytes) # <<<<<<<<<<<<<< + * + * p[0] = tmp + */ + __pyx_t_3 = __Pyx_PyInt_FromSize_t(__pyx_v_nbytes); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_could_not_allocate_d_bytes, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3442 + * raise MemoryError("could not allocate %d bytes" % nbytes) + * + * p[0] = tmp # <<<<<<<<<<<<<< + * return tmp # for convenience + * + */ + (__pyx_v_p[0]) = __pyx_v_tmp; + + /* "sklearn/tree/_tree.pyx":3443 + * + * p[0] = tmp + * return tmp # for convenience # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_tmp; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3430 + * (unsigned char*) + * + * cdef realloc_ptr safe_realloc(realloc_ptr* p, size_t nelems) except *: # <<<<<<<<<<<<<< + * # sizeof(realloc_ptr[0]) would be more like idiomatic C, but causes Cython + * # 0.20.1 to crash. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.safe_realloc", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_fuse_1__pyx_f_7sklearn_4tree_5_tree_safe_realloc(__pyx_t_7sklearn_4tree_5_tree_SIZE_t **__pyx_v_p, size_t __pyx_v_nelems) { + size_t __pyx_v_nbytes; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_tmp; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_fuse_1safe_realloc", 0); + + /* "sklearn/tree/_tree.pyx":3433 + * # 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]) # <<<<<<<<<<<<<< + * if nbytes / sizeof(p[0][0]) != nelems: + * # Overflow in the multiplication + */ + __pyx_v_nbytes = (__pyx_v_nelems * (sizeof(((__pyx_v_p[0])[0])))); + + /* "sklearn/tree/_tree.pyx":3434 + * # 0.20.1 to crash. + * cdef size_t nbytes = nelems * sizeof(p[0][0]) + * if nbytes / sizeof(p[0][0]) != nelems: # <<<<<<<<<<<<<< + * # Overflow in the multiplication + * raise MemoryError("could not allocate (%d * %d) bytes" + */ + __pyx_t_1 = (((__pyx_v_nbytes / (sizeof(((__pyx_v_p[0])[0])))) != __pyx_v_nelems) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3437 + * # Overflow in the multiplication + * raise MemoryError("could not allocate (%d * %d) bytes" + * % (nelems, sizeof(p[0][0]))) # <<<<<<<<<<<<<< + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + * if tmp == NULL: + */ + __pyx_t_2 = __Pyx_PyInt_FromSize_t(__pyx_v_nelems); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyInt_FromSize_t((sizeof(((__pyx_v_p[0])[0])))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_could_not_allocate_d_d_bytes, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "sklearn/tree/_tree.pyx":3436 + * if nbytes / sizeof(p[0][0]) != nelems: + * # Overflow in the multiplication + * raise MemoryError("could not allocate (%d * %d) bytes" # <<<<<<<<<<<<<< + * % (nelems, sizeof(p[0][0]))) + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + */ + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3438 + * raise MemoryError("could not allocate (%d * %d) bytes" + * % (nelems, sizeof(p[0][0]))) + * cdef realloc_ptr tmp = realloc(p[0], nbytes) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError("could not allocate %d bytes" % nbytes) + */ + __pyx_v_tmp = ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t *)realloc((__pyx_v_p[0]), __pyx_v_nbytes)); + + /* "sklearn/tree/_tree.pyx":3439 + * % (nelems, sizeof(p[0][0]))) + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate %d bytes" % nbytes) + * + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3440 + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + * if tmp == NULL: + * raise MemoryError("could not allocate %d bytes" % nbytes) # <<<<<<<<<<<<<< + * + * p[0] = tmp + */ + __pyx_t_3 = __Pyx_PyInt_FromSize_t(__pyx_v_nbytes); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_could_not_allocate_d_bytes, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3442 + * raise MemoryError("could not allocate %d bytes" % nbytes) + * + * p[0] = tmp # <<<<<<<<<<<<<< + * return tmp # for convenience + * + */ + (__pyx_v_p[0]) = __pyx_v_tmp; + + /* "sklearn/tree/_tree.pyx":3443 + * + * p[0] = tmp + * return tmp # for convenience # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_tmp; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3430 + * (unsigned char*) + * + * cdef realloc_ptr safe_realloc(realloc_ptr* p, size_t nelems) except *: # <<<<<<<<<<<<<< + * # sizeof(realloc_ptr[0]) would be more like idiomatic C, but causes Cython + * # 0.20.1 to crash. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.safe_realloc", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static unsigned char *__pyx_fuse_2__pyx_f_7sklearn_4tree_5_tree_safe_realloc(unsigned char **__pyx_v_p, size_t __pyx_v_nelems) { + size_t __pyx_v_nbytes; + unsigned char *__pyx_v_tmp; + unsigned char *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_fuse_2safe_realloc", 0); + + /* "sklearn/tree/_tree.pyx":3433 + * # 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]) # <<<<<<<<<<<<<< + * if nbytes / sizeof(p[0][0]) != nelems: + * # Overflow in the multiplication + */ + __pyx_v_nbytes = (__pyx_v_nelems * (sizeof(((__pyx_v_p[0])[0])))); + + /* "sklearn/tree/_tree.pyx":3434 + * # 0.20.1 to crash. + * cdef size_t nbytes = nelems * sizeof(p[0][0]) + * if nbytes / sizeof(p[0][0]) != nelems: # <<<<<<<<<<<<<< + * # Overflow in the multiplication + * raise MemoryError("could not allocate (%d * %d) bytes" + */ + __pyx_t_1 = (((__pyx_v_nbytes / (sizeof(((__pyx_v_p[0])[0])))) != __pyx_v_nelems) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3437 + * # Overflow in the multiplication + * raise MemoryError("could not allocate (%d * %d) bytes" + * % (nelems, sizeof(p[0][0]))) # <<<<<<<<<<<<<< + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + * if tmp == NULL: + */ + __pyx_t_2 = __Pyx_PyInt_FromSize_t(__pyx_v_nelems); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyInt_FromSize_t((sizeof(((__pyx_v_p[0])[0])))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_could_not_allocate_d_d_bytes, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "sklearn/tree/_tree.pyx":3436 + * if nbytes / sizeof(p[0][0]) != nelems: + * # Overflow in the multiplication + * raise MemoryError("could not allocate (%d * %d) bytes" # <<<<<<<<<<<<<< + * % (nelems, sizeof(p[0][0]))) + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + */ + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3438 + * raise MemoryError("could not allocate (%d * %d) bytes" + * % (nelems, sizeof(p[0][0]))) + * cdef realloc_ptr tmp = realloc(p[0], nbytes) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError("could not allocate %d bytes" % nbytes) + */ + __pyx_v_tmp = ((unsigned char *)realloc((__pyx_v_p[0]), __pyx_v_nbytes)); + + /* "sklearn/tree/_tree.pyx":3439 + * % (nelems, sizeof(p[0][0]))) + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate %d bytes" % nbytes) + * + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3440 + * cdef realloc_ptr tmp = realloc(p[0], nbytes) + * if tmp == NULL: + * raise MemoryError("could not allocate %d bytes" % nbytes) # <<<<<<<<<<<<<< + * + * p[0] = tmp + */ + __pyx_t_3 = __Pyx_PyInt_FromSize_t(__pyx_v_nbytes); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_could_not_allocate_d_bytes, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_tree.pyx":3442 + * raise MemoryError("could not allocate %d bytes" % nbytes) + * + * p[0] = tmp # <<<<<<<<<<<<<< + * return tmp # for convenience + * + */ + (__pyx_v_p[0]) = __pyx_v_tmp; + + /* "sklearn/tree/_tree.pyx":3443 + * + * p[0] = tmp + * return tmp # for convenience # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_tmp; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3430 + * (unsigned char*) + * + * cdef realloc_ptr safe_realloc(realloc_ptr* p, size_t nelems) except *: # <<<<<<<<<<<<<< + * # sizeof(realloc_ptr[0]) would be more like idiomatic C, but causes Cython + * # 0.20.1 to crash. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.tree._tree.safe_realloc", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3446 + * + * + * def _realloc_test(): # <<<<<<<<<<<<<< + * # Helper for tests. Tries to allocate (-1) / 2 * sizeof(size_t) + * # bytes, which will always overflow. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_1_realloc_test(PyObject *__pyx_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_4tree_5_tree_1_realloc_test = {"_realloc_test", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_1_realloc_test, METH_NOARGS, 0}; +static PyObject *__pyx_pw_7sklearn_4tree_5_tree_1_realloc_test(PyObject *__pyx_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_realloc_test (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_4tree_5_tree__realloc_test(__pyx_self); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_4tree_5_tree__realloc_test(CYTHON_UNUSED PyObject *__pyx_self) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_p; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_realloc_test", 0); + + /* "sklearn/tree/_tree.pyx":3449 + * # Helper for tests. Tries to allocate (-1) / 2 * sizeof(size_t) + * # bytes, which will always overflow. + * cdef SIZE_t* p = NULL # <<<<<<<<<<<<<< + * safe_realloc(&p, (-1) / 2) + * if p != NULL: + */ + __pyx_v_p = NULL; + + /* "sklearn/tree/_tree.pyx":3450 + * # bytes, which will always overflow. + * cdef SIZE_t* p = NULL + * safe_realloc(&p, (-1) / 2) # <<<<<<<<<<<<<< + * if p != NULL: + * free(p) + */ + __pyx_fuse_1__pyx_f_7sklearn_4tree_5_tree_safe_realloc((&__pyx_v_p), (((size_t)-1) / 2)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":3451 + * cdef SIZE_t* p = NULL + * safe_realloc(&p, (-1) / 2) + * if p != NULL: # <<<<<<<<<<<<<< + * free(p) + * assert False + */ + __pyx_t_1 = ((__pyx_v_p != NULL) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_tree.pyx":3452 + * safe_realloc(&p, (-1) / 2) + * if p != NULL: + * free(p) # <<<<<<<<<<<<<< + * assert False + * + */ + free(__pyx_v_p); + + /* "sklearn/tree/_tree.pyx":3453 + * if p != NULL: + * free(p) + * assert False # <<<<<<<<<<<<<< + * + * + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!0)) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/tree/_tree.pyx":3446 + * + * + * def _realloc_test(): # <<<<<<<<<<<<<< + * # Helper for tests. Tries to allocate (-1) / 2 * sizeof(size_t) + * # bytes, which will always overflow. + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.tree._tree._realloc_test", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3458 + * # rand_r replacement using a 32bit XorShift generator + * # See http://www.jstatsoft.org/v08/i14/paper for details + * cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil: # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) + */ + +static CYTHON_INLINE __pyx_t_7sklearn_4tree_5_tree_UINT32_t __pyx_f_7sklearn_4tree_5_tree_our_rand_r(__pyx_t_7sklearn_4tree_5_tree_UINT32_t *__pyx_v_seed) { + __pyx_t_7sklearn_4tree_5_tree_UINT32_t __pyx_r; + long __pyx_t_1; + + /* "sklearn/tree/_tree.pyx":3459 + * # See http://www.jstatsoft.org/v08/i14/paper for details + * cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil: + * seed[0] ^= (seed[0] << 13) # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] >> 17) + * seed[0] ^= (seed[0] << 5) + */ + __pyx_t_1 = 0; + (__pyx_v_seed[__pyx_t_1]) = ((__pyx_v_seed[__pyx_t_1]) ^ ((__pyx_t_7sklearn_4tree_5_tree_UINT32_t)((__pyx_v_seed[0]) << 13))); + + /* "sklearn/tree/_tree.pyx":3460 + * cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil: + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] << 5) + * + */ + __pyx_t_1 = 0; + (__pyx_v_seed[__pyx_t_1]) = ((__pyx_v_seed[__pyx_t_1]) ^ ((__pyx_t_7sklearn_4tree_5_tree_UINT32_t)((__pyx_v_seed[0]) >> 17))); + + /* "sklearn/tree/_tree.pyx":3461 + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) + * seed[0] ^= (seed[0] << 5) # <<<<<<<<<<<<<< + * + * return seed[0] % (RAND_R_MAX + 1) + */ + __pyx_t_1 = 0; + (__pyx_v_seed[__pyx_t_1]) = ((__pyx_v_seed[__pyx_t_1]) ^ ((__pyx_t_7sklearn_4tree_5_tree_UINT32_t)((__pyx_v_seed[0]) << 5))); + + /* "sklearn/tree/_tree.pyx":3463 + * seed[0] ^= (seed[0] << 5) + * + * return seed[0] % (RAND_R_MAX + 1) # <<<<<<<<<<<<<< + * + * cdef inline np.ndarray sizet_ptr_to_ndarray(SIZE_t* data, SIZE_t size): + */ + __pyx_r = ((__pyx_v_seed[0]) % (((__pyx_t_7sklearn_4tree_5_tree_UINT32_t)__pyx_e_7sklearn_4tree_5_tree_RAND_R_MAX) + 1)); + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3458 + * # rand_r replacement using a 32bit XorShift generator + * # See http://www.jstatsoft.org/v08/i14/paper for details + * cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil: # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3465 + * return seed[0] % (RAND_R_MAX + 1) + * + * cdef inline np.ndarray sizet_ptr_to_ndarray(SIZE_t* data, SIZE_t size): # <<<<<<<<<<<<<< + * """Encapsulate data into a 1D numpy array of intp's.""" + * cdef np.npy_intp shape[1] + */ + +static CYTHON_INLINE PyArrayObject *__pyx_f_7sklearn_4tree_5_tree_sizet_ptr_to_ndarray(__pyx_t_7sklearn_4tree_5_tree_SIZE_t *__pyx_v_data, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_size) { + npy_intp __pyx_v_shape[1]; + PyArrayObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("sizet_ptr_to_ndarray", 0); + + /* "sklearn/tree/_tree.pyx":3468 + * """Encapsulate data into a 1D numpy array of intp's.""" + * cdef np.npy_intp shape[1] + * shape[0] = size # <<<<<<<<<<<<<< + * return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INTP, data) + * + */ + (__pyx_v_shape[0]) = ((npy_intp)__pyx_v_size); + + /* "sklearn/tree/_tree.pyx":3469 + * cdef np.npy_intp shape[1] + * shape[0] = size + * return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INTP, data) # <<<<<<<<<<<<<< + * + * cdef inline SIZE_t rand_int(SIZE_t low, SIZE_t high, + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __pyx_t_1 = PyArray_SimpleNewFromData(1, __pyx_v_shape, NPY_INTP, __pyx_v_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3465 + * return seed[0] % (RAND_R_MAX + 1) + * + * cdef inline np.ndarray sizet_ptr_to_ndarray(SIZE_t* data, SIZE_t size): # <<<<<<<<<<<<<< + * """Encapsulate data into a 1D numpy array of intp's.""" + * cdef np.npy_intp shape[1] + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.tree._tree.sizet_ptr_to_ndarray", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3471 + * return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INTP, data) + * + * cdef inline SIZE_t rand_int(SIZE_t low, SIZE_t high, # <<<<<<<<<<<<<< + * UINT32_t* random_state) nogil: + * """Generate a random integer in [0; end).""" + */ + +static CYTHON_INLINE __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_f_7sklearn_4tree_5_tree_rand_int(__pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_low, __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_v_high, __pyx_t_7sklearn_4tree_5_tree_UINT32_t *__pyx_v_random_state) { + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_r; + + /* "sklearn/tree/_tree.pyx":3474 + * UINT32_t* random_state) nogil: + * """Generate a random integer in [0; end).""" + * return low + our_rand_r(random_state) % (high - low) # <<<<<<<<<<<<<< + * + * cdef inline double rand_uniform(double low, double high, + */ + __pyx_r = (__pyx_v_low + (__pyx_f_7sklearn_4tree_5_tree_our_rand_r(__pyx_v_random_state) % (__pyx_v_high - __pyx_v_low))); + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3471 + * return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INTP, data) + * + * cdef inline SIZE_t rand_int(SIZE_t low, SIZE_t high, # <<<<<<<<<<<<<< + * UINT32_t* random_state) nogil: + * """Generate a random integer in [0; end).""" + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3476 + * return low + our_rand_r(random_state) % (high - low) + * + * cdef inline double rand_uniform(double low, double high, # <<<<<<<<<<<<<< + * UINT32_t* random_state) nogil: + * """Generate a random double in [low; high).""" + */ + +static CYTHON_INLINE double __pyx_f_7sklearn_4tree_5_tree_rand_uniform(double __pyx_v_low, double __pyx_v_high, __pyx_t_7sklearn_4tree_5_tree_UINT32_t *__pyx_v_random_state) { + double __pyx_r; + + /* "sklearn/tree/_tree.pyx":3480 + * """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: + */ + __pyx_r = ((((__pyx_v_high - __pyx_v_low) * ((double)__pyx_f_7sklearn_4tree_5_tree_our_rand_r(__pyx_v_random_state))) / ((double)__pyx_e_7sklearn_4tree_5_tree_RAND_R_MAX)) + __pyx_v_low); + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3476 + * return low + our_rand_r(random_state) % (high - low) + * + * cdef inline double rand_uniform(double low, double high, # <<<<<<<<<<<<<< + * UINT32_t* random_state) nogil: + * """Generate a random double in [low; high).""" + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_tree.pyx":3482 + * RAND_R_MAX) + low + * + * cdef inline double log(double x) nogil: # <<<<<<<<<<<<<< + * return ln(x) / ln(2.0) + * + */ + +static CYTHON_INLINE double __pyx_f_7sklearn_4tree_5_tree_log(double __pyx_v_x) { + double __pyx_r; + + /* "sklearn/tree/_tree.pyx":3483 + * + * cdef inline double log(double x) nogil: + * return ln(x) / ln(2.0) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (log(__pyx_v_x) / log(2.0)); + goto __pyx_L0; + + /* "sklearn/tree/_tree.pyx":3482 + * RAND_R_MAX) + low + * + * cdef inline double log(double x) nogil: # <<<<<<<<<<<<<< + * return ln(x) / ln(2.0) + * + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":197 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":203 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":206 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":207 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":209 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":211 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":212 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":216 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L6_bool_binop_done; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":217 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L6_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":220 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L9_bool_binop_done; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":221 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L9_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":224 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":225 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_1 = (__pyx_v_copy_shape != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":229 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":230 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":231 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_4 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":232 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L11; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":236 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L11:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":237 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":238 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":242 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":243 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":247 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":249 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L15_bool_binop_done; + } + __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L15_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":251 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L14; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":254 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L14:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":256 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_4 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_4; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); + if (!__pyx_t_2) { + goto __pyx_L20_next_or; + } else { + } + __pyx_t_2 = (__pyx_v_little_endian != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_L20_next_or:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L19_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":261 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":262 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":263 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":264 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":266 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":267 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":268 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":269 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":271 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":273 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":275 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":279 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":281 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":284 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":285 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":286 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< + * info.format + _buffer_format_string_len, + * &offset) + */ + __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_7; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":289 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":197 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":293 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":294 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":295 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":772 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":775 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":778 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":781 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":784 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 784; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":786 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + long __pyx_t_8; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":793 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":797 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); + __pyx_t_3 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":798 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + if (unlikely(__pyx_v_descr->fields == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); + __pyx_t_4 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":804 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (!__pyx_t_7) { + goto __pyx_L8_next_or; + } else { + } + __pyx_t_7 = (__pyx_v_little_endian != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_L8_next_or:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":805 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L7_bool_binop_done:; + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":806 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":816 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_6) break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":817 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":819 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":821 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":824 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":825 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":829 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":830 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":831 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":832 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":833 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":834 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":835 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":836 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":838 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":839 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":840 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":841 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":843 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":844 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":845 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L15; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":847 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L15:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":848 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":852 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 852; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + } + __pyx_L13:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":797 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":853 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":786 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":971 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":972 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":974 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":975 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":977 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":979 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":980 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":981 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":983 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":979 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion __pyx_vtable_7sklearn_4tree_5_tree_Criterion; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Criterion(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_4tree_5_tree_Criterion; + return o; +} + +static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_Criterion(PyObject *o) { + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + (*Py_TYPE(o)->tp_free)(o); +} + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_Criterion = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.Criterion", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_Criterion, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Interface for impurity criteria.", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_Criterion, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter __pyx_vtable_7sklearn_4tree_5_tree_Splitter; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Splitter(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_4tree_5_tree_Splitter; + p->criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)Py_None); Py_INCREF(Py_None); + p->random_state = Py_None; Py_INCREF(Py_None); + if (unlikely(__pyx_pw_7sklearn_4tree_5_tree_8Splitter_1__cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_Splitter(PyObject *o) { + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *p = (struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_pw_7sklearn_4tree_5_tree_8Splitter_3__dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->criterion); + Py_CLEAR(p->random_state); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_7sklearn_4tree_5_tree_Splitter(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *p = (struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)o; + if (p->criterion) { + e = (*v)(((PyObject*)p->criterion), a); if (e) return e; + } + if (p->random_state) { + e = (*v)(p->random_state, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_7sklearn_4tree_5_tree_Splitter(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *p = (struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)o; + tmp = ((PyObject*)p->criterion); + p->criterion = ((struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->random_state); + p->random_state = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_8Splitter_criterion(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_8Splitter_9criterion_1__get__(o); +} + +static int __pyx_setprop_7sklearn_4tree_5_tree_8Splitter_criterion(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_4tree_5_tree_8Splitter_9criterion_3__set__(o, v); + } + else { + return __pyx_pw_7sklearn_4tree_5_tree_8Splitter_9criterion_5__del__(o); + } +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_8Splitter_max_features(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_8Splitter_12max_features_1__get__(o); +} + +static int __pyx_setprop_7sklearn_4tree_5_tree_8Splitter_max_features(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_4tree_5_tree_8Splitter_12max_features_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_8Splitter_min_samples_leaf(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf_1__get__(o); +} + +static int __pyx_setprop_7sklearn_4tree_5_tree_8Splitter_min_samples_leaf(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_4tree_5_tree_8Splitter_16min_samples_leaf_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_8Splitter_min_weight_leaf(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf_1__get__(o); +} + +static int __pyx_setprop_7sklearn_4tree_5_tree_8Splitter_min_weight_leaf(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_4tree_5_tree_8Splitter_15min_weight_leaf_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_Splitter[] = { + {"__getstate__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_8Splitter_5__getstate__, METH_NOARGS, 0}, + {"__setstate__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_8Splitter_7__setstate__, METH_O, 0}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_7sklearn_4tree_5_tree_Splitter[] = { + {(char *)"criterion", __pyx_getprop_7sklearn_4tree_5_tree_8Splitter_criterion, __pyx_setprop_7sklearn_4tree_5_tree_8Splitter_criterion, 0, 0}, + {(char *)"max_features", __pyx_getprop_7sklearn_4tree_5_tree_8Splitter_max_features, __pyx_setprop_7sklearn_4tree_5_tree_8Splitter_max_features, 0, 0}, + {(char *)"min_samples_leaf", __pyx_getprop_7sklearn_4tree_5_tree_8Splitter_min_samples_leaf, __pyx_setprop_7sklearn_4tree_5_tree_8Splitter_min_samples_leaf, 0, 0}, + {(char *)"min_weight_leaf", __pyx_getprop_7sklearn_4tree_5_tree_8Splitter_min_weight_leaf, __pyx_setprop_7sklearn_4tree_5_tree_8Splitter_min_weight_leaf, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_Splitter = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.Splitter", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_Splitter, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_7sklearn_4tree_5_tree_Splitter, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_4tree_5_tree_Splitter, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_Splitter, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_7sklearn_4tree_5_tree_Splitter, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_Splitter, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Tree __pyx_vtable_7sklearn_4tree_5_tree_Tree; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Tree(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_Tree *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_Tree *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_4tree_5_tree_Tree; + if (unlikely(__pyx_pw_7sklearn_4tree_5_tree_4Tree_1__cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_Tree(PyObject *o) { + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_pw_7sklearn_4tree_5_tree_4Tree_3__dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + (*Py_TYPE(o)->tp_free)(o); +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_classes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_classes_1__get__(o); +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_children_left(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_13children_left_1__get__(o); +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_children_right(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_14children_right_1__get__(o); +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_feature(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_7feature_1__get__(o); +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_threshold(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9threshold_1__get__(o); +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_impurity(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_8impurity_1__get__(o); +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_node_samples(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_14n_node_samples_1__get__(o); +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_weighted_n_node_samples(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_23weighted_n_node_samples_1__get__(o); +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_value(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_5value_1__get__(o); +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_features(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_1__get__(o); +} + +static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_n_features(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_10n_features_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_outputs(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_1__get__(o); +} + +static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_n_outputs(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9n_outputs_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_max_n_classes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_1__get__(o); +} + +static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_max_n_classes(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_13max_n_classes_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_max_depth(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_1__get__(o); +} + +static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_max_depth(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_9max_depth_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_node_count(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_1__get__(o); +} + +static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_node_count(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_10node_count_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyObject *__pyx_getprop_7sklearn_4tree_5_tree_4Tree_capacity(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_1__get__(o); +} + +static int __pyx_setprop_7sklearn_4tree_5_tree_4Tree_capacity(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_7sklearn_4tree_5_tree_4Tree_8capacity_3__set__(o, v); + } + else { + PyErr_SetString(PyExc_NotImplementedError, "__del__"); + return -1; + } +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_Tree[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_5__reduce__, METH_NOARGS, __pyx_doc_7sklearn_4tree_5_tree_4Tree_4__reduce__}, + {"__getstate__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_7__getstate__, METH_NOARGS, __pyx_doc_7sklearn_4tree_5_tree_4Tree_6__getstate__}, + {"__setstate__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_9__setstate__, METH_O, __pyx_doc_7sklearn_4tree_5_tree_4Tree_8__setstate__}, + {"predict", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_11predict, METH_O, __pyx_doc_7sklearn_4tree_5_tree_4Tree_10predict}, + {"apply", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_13apply, METH_O, __pyx_doc_7sklearn_4tree_5_tree_4Tree_12apply}, + {"compute_feature_importances", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_4Tree_15compute_feature_importances, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_4tree_5_tree_4Tree_14compute_feature_importances}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_7sklearn_4tree_5_tree_Tree[] = { + {(char *)"n_classes", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_classes, 0, 0, 0}, + {(char *)"children_left", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_children_left, 0, 0, 0}, + {(char *)"children_right", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_children_right, 0, 0, 0}, + {(char *)"feature", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_feature, 0, 0, 0}, + {(char *)"threshold", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_threshold, 0, 0, 0}, + {(char *)"impurity", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_impurity, 0, 0, 0}, + {(char *)"n_node_samples", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_node_samples, 0, 0, 0}, + {(char *)"weighted_n_node_samples", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_weighted_n_node_samples, 0, 0, 0}, + {(char *)"value", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_value, 0, 0, 0}, + {(char *)"n_features", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_features, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_n_features, 0, 0}, + {(char *)"n_outputs", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_n_outputs, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_n_outputs, 0, 0}, + {(char *)"max_n_classes", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_max_n_classes, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_max_n_classes, 0, 0}, + {(char *)"max_depth", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_max_depth, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_max_depth, 0, 0}, + {(char *)"node_count", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_node_count, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_node_count, 0, 0}, + {(char *)"capacity", __pyx_getprop_7sklearn_4tree_5_tree_4Tree_capacity, __pyx_setprop_7sklearn_4tree_5_tree_4Tree_capacity, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_Tree = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.Tree", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Tree), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_Tree, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Array-based representation of a binary decision tree.\n\n The binary tree is represented as a number of parallel arrays. The i-th\n element of each array holds information about the node `i`. Node 0 is the\n tree's root. You can find a detailed description of all arrays in\n `_tree.pxd`. NOTE: Some of the arrays only apply to either leaves or split\n nodes, resp. In this case the values of nodes of the other type are\n arbitrary!\n\n Attributes\n ----------\n node_count : int\n The number of nodes (internal nodes + leaves) in the tree.\n\n capacity : int\n The current capacity (i.e., size) of the arrays, which is at least as\n great as `node_count`.\n\n max_depth : int\n The maximal depth of the tree.\n\n children_left : array of int, shape [node_count]\n children_left[i] holds the node id of the left child of node i.\n For leaves, children_left[i] == TREE_LEAF. Otherwise,\n children_left[i] > i. This child handles the case where\n X[:, feature[i]] <= threshold[i].\n\n children_right : array of int, shape [node_count]\n children_right[i] holds the node id of the right child of node i.\n For leaves, children_right[i] == TREE_LEAF. Otherwise,\n children_right[i] > i. This child handles the case where\n X[:, feature[i]] > threshold[i].\n\n feature : array of int, shape [node_count]\n feature[i] holds the feature to split on, for the internal node i.\n\n threshold : array of double, shape [node_count]\n threshold[i] holds the threshold for the internal node i.\n\n value : array of double, shape [node_count, n_outputs, max_n_classes]\n Contains the constant prediction value of each node.\n\n impurity : array of double, shape [node_count]\n impurity[i] holds the impurity (i.e., the value of the splitting\n criterion) at node i.\n\n n_node_samples : array of int, shape [node_count]\n n_node_samples[i] holds the number of training samples reaching node i.\n\n weighted_n_node_samples : array of int, shape [node_count]\n weighted_n_node_samples[i] holds the weighted number of training samples\n reaching node i.\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_Tree, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_7sklearn_4tree_5_tree_Tree, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_Tree, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder __pyx_vtable_7sklearn_4tree_5_tree_TreeBuilder; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_TreeBuilder(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_4tree_5_tree_TreeBuilder; + p->splitter = ((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)Py_None); Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_TreeBuilder(PyObject *o) { + struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *p = (struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->splitter); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_7sklearn_4tree_5_tree_TreeBuilder(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *p = (struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *)o; + if (p->splitter) { + e = (*v)(((PyObject*)p->splitter), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_7sklearn_4tree_5_tree_TreeBuilder(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *p = (struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *)o; + tmp = ((PyObject*)p->splitter); + p->splitter = ((struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_TreeBuilder[] = { + {"build", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_11TreeBuilder_1build, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_4tree_5_tree_11TreeBuilder_build}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_TreeBuilder = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.TreeBuilder", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_TreeBuilder, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + "Interface for different tree building strategies. ", /*tp_doc*/ + __pyx_tp_traverse_7sklearn_4tree_5_tree_TreeBuilder, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_4tree_5_tree_TreeBuilder, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_TreeBuilder, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_TreeBuilder, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_ClassificationCriterion __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_ClassificationCriterion(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_Criterion(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion; + if (unlikely(__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_1__cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_ClassificationCriterion(PyObject *o) { + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_3__dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + __pyx_tp_dealloc_7sklearn_4tree_5_tree_Criterion(o); +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_ClassificationCriterion[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_5__reduce__, METH_NOARGS, 0}, + {"__getstate__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_7__getstate__, METH_NOARGS, 0}, + {"__setstate__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_23ClassificationCriterion_9__setstate__, METH_O, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.ClassificationCriterion", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_ClassificationCriterion), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_ClassificationCriterion, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Abstract criterion for classification.", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_ClassificationCriterion, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_ClassificationCriterion, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Entropy __pyx_vtable_7sklearn_4tree_5_tree_Entropy; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Entropy(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_Entropy *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_ClassificationCriterion(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_Entropy *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__pyx_vtabptr_7sklearn_4tree_5_tree_Entropy; + return o; +} + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_Entropy = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.Entropy", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Entropy), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_ClassificationCriterion, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Cross Entropy impurity criteria.\n\n Let the target be a classification outcome taking values in 0, 1, ..., K-1.\n If node m represents a region Rm with Nm observations, then let\n\n pmk = 1/ Nm \\sum_{x_i in Rm} I(yi = k)\n\n be the proportion of class k observations in node m.\n\n The cross-entropy is then defined as\n\n cross-entropy = - \\sum_{k=0}^{K-1} pmk log(pmk)\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_Entropy, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Gini __pyx_vtable_7sklearn_4tree_5_tree_Gini; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_Gini(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_Gini *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_ClassificationCriterion(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_Gini *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__pyx_vtabptr_7sklearn_4tree_5_tree_Gini; + return o; +} + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_Gini = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.Gini", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_Gini), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_ClassificationCriterion, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Gini Index impurity criteria.\n\n Let the target be a classification outcome taking values in 0, 1, ..., K-1.\n If node m represents a region Rm with Nm observations, then let\n\n pmk = 1/ Nm \\sum_{x_i in Rm} I(yi = k)\n\n be the proportion of class k observations in node m.\n\n The Gini Index is then defined as:\n\n index = \\sum_{k=0}^{K-1} pmk (1 - pmk)\n = 1 - \\sum_{k=0}^{K-1} pmk ** 2\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_Gini, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RegressionCriterion __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_RegressionCriterion(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_Criterion(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__pyx_vtabptr_7sklearn_4tree_5_tree_RegressionCriterion; + if (unlikely(__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_1__cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_RegressionCriterion(PyObject *o) { + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_3__dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + __pyx_tp_dealloc_7sklearn_4tree_5_tree_Criterion(o); +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_RegressionCriterion[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_5__reduce__, METH_NOARGS, 0}, + {"__getstate__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_7__getstate__, METH_NOARGS, 0}, + {"__setstate__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_19RegressionCriterion_9__setstate__, METH_O, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_RegressionCriterion = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.RegressionCriterion", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_RegressionCriterion), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_RegressionCriterion, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Abstract criterion for regression.\n\n Computes variance of the target values left and right of the split point.\n Computation is linear in `n_samples` by using ::\n\n var = \\sum_i^n (y_i - y_bar) ** 2\n = (\\sum_i^n y_i ** 2) - n_samples y_bar ** 2\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_RegressionCriterion, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_RegressionCriterion, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_MSE __pyx_vtable_7sklearn_4tree_5_tree_MSE; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_MSE(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_MSE *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_RegressionCriterion(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_MSE *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__pyx_vtabptr_7sklearn_4tree_5_tree_MSE; + return o; +} + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_MSE = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.MSE", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_MSE), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_RegressionCriterion, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Mean squared error impurity criterion.\n\n MSE = var_left + var_right\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_MSE, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_FriedmanMSE __pyx_vtable_7sklearn_4tree_5_tree_FriedmanMSE; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_FriedmanMSE(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_FriedmanMSE *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_MSE(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_FriedmanMSE *)o); + p->__pyx_base.__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Criterion*)__pyx_vtabptr_7sklearn_4tree_5_tree_FriedmanMSE; + return o; +} + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_FriedmanMSE = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.FriedmanMSE", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_FriedmanMSE), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_RegressionCriterion, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Mean squared error impurity criterion with improvement score by Friedman\n\n Uses the formula (35) in Friedmans original Gradient Boosting paper:\n\n diff = mean_left - mean_right\n improvement = n_left * n_right * diff^2 / (n_left + n_right)\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_FriedmanMSE, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BaseDenseSplitter __pyx_vtable_7sklearn_4tree_5_tree_BaseDenseSplitter; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_BaseDenseSplitter(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_Splitter(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter*)__pyx_vtabptr_7sklearn_4tree_5_tree_BaseDenseSplitter; + if (unlikely(__pyx_pw_7sklearn_4tree_5_tree_17BaseDenseSplitter_1__cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_BaseDenseSplitter[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_BaseDenseSplitter = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.BaseDenseSplitter", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_BaseDenseSplitter), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_Splitter, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_7sklearn_4tree_5_tree_Splitter, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_4tree_5_tree_Splitter, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_BaseDenseSplitter, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_BaseDenseSplitter, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BestSplitter __pyx_vtable_7sklearn_4tree_5_tree_BestSplitter; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_BestSplitter(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_BestSplitter *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_BaseDenseSplitter(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_BestSplitter *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter*)__pyx_vtabptr_7sklearn_4tree_5_tree_BestSplitter; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_BestSplitter[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_12BestSplitter_1__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_BestSplitter = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.BestSplitter", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_BestSplitter), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_Splitter, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + "Splitter for finding the best split.", /*tp_doc*/ + __pyx_tp_traverse_7sklearn_4tree_5_tree_Splitter, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_4tree_5_tree_Splitter, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_BestSplitter, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_BestSplitter, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RandomSplitter __pyx_vtable_7sklearn_4tree_5_tree_RandomSplitter; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_RandomSplitter(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_RandomSplitter *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_BaseDenseSplitter(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_RandomSplitter *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter*)__pyx_vtabptr_7sklearn_4tree_5_tree_RandomSplitter; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_RandomSplitter[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_14RandomSplitter_1__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_RandomSplitter = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.RandomSplitter", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_RandomSplitter), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_Splitter, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + "Splitter for finding the best random split.", /*tp_doc*/ + __pyx_tp_traverse_7sklearn_4tree_5_tree_Splitter, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_4tree_5_tree_Splitter, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_RandomSplitter, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_RandomSplitter, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_PresortBestSplitter __pyx_vtable_7sklearn_4tree_5_tree_PresortBestSplitter; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_PresortBestSplitter(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_BaseDenseSplitter(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter*)__pyx_vtabptr_7sklearn_4tree_5_tree_PresortBestSplitter; + p->X_argsorted = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_pw_7sklearn_4tree_5_tree_19PresortBestSplitter_1__cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_PresortBestSplitter(PyObject *o) { + struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *p = (struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_pw_7sklearn_4tree_5_tree_19PresortBestSplitter_3__dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->X_argsorted); + PyObject_GC_Track(o); + __pyx_tp_dealloc_7sklearn_4tree_5_tree_Splitter(o); +} + +static int __pyx_tp_traverse_7sklearn_4tree_5_tree_PresortBestSplitter(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *p = (struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *)o; + e = __pyx_tp_traverse_7sklearn_4tree_5_tree_Splitter(o, v, a); if (e) return e; + if (p->X_argsorted) { + e = (*v)(((PyObject*)p->X_argsorted), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_7sklearn_4tree_5_tree_PresortBestSplitter(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *p = (struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter *)o; + __pyx_tp_clear_7sklearn_4tree_5_tree_Splitter(o); + tmp = ((PyObject*)p->X_argsorted); + p->X_argsorted = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_PresortBestSplitter[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_19PresortBestSplitter_5__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_PresortBestSplitter = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.PresortBestSplitter", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_PresortBestSplitter), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_PresortBestSplitter, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + "Splitter for finding the best split, using presorting.", /*tp_doc*/ + __pyx_tp_traverse_7sklearn_4tree_5_tree_PresortBestSplitter, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_4tree_5_tree_PresortBestSplitter, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_PresortBestSplitter, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_PresortBestSplitter, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BaseSparseSplitter __pyx_vtable_7sklearn_4tree_5_tree_BaseSparseSplitter; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_BaseSparseSplitter(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_Splitter(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter*)__pyx_vtabptr_7sklearn_4tree_5_tree_BaseSparseSplitter; + if (unlikely(__pyx_pw_7sklearn_4tree_5_tree_18BaseSparseSplitter_1__cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_4tree_5_tree_BaseSparseSplitter(PyObject *o) { + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_pw_7sklearn_4tree_5_tree_18BaseSparseSplitter_3__dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + PyObject_GC_Track(o); + __pyx_tp_dealloc_7sklearn_4tree_5_tree_Splitter(o); +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_BaseSparseSplitter[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_BaseSparseSplitter = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.BaseSparseSplitter", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_BaseSparseSplitter, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_7sklearn_4tree_5_tree_Splitter, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_4tree_5_tree_Splitter, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_BaseSparseSplitter, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_BaseSparseSplitter, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BestSparseSplitter __pyx_vtable_7sklearn_4tree_5_tree_BestSparseSplitter; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_BestSparseSplitter(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_BestSparseSplitter *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_BaseSparseSplitter(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_BestSparseSplitter *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter*)__pyx_vtabptr_7sklearn_4tree_5_tree_BestSparseSplitter; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_BestSparseSplitter[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_18BestSparseSplitter_1__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_BestSparseSplitter = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.BestSparseSplitter", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_BestSparseSplitter), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_BaseSparseSplitter, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + "Splitter for finding the best split, using the sparse data.", /*tp_doc*/ + __pyx_tp_traverse_7sklearn_4tree_5_tree_Splitter, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_4tree_5_tree_Splitter, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_BestSparseSplitter, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_BestSparseSplitter, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_RandomSparseSplitter __pyx_vtable_7sklearn_4tree_5_tree_RandomSparseSplitter; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_RandomSparseSplitter(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_RandomSparseSplitter *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_BaseSparseSplitter(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_RandomSparseSplitter *)o); + p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_Splitter*)__pyx_vtabptr_7sklearn_4tree_5_tree_RandomSparseSplitter; + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_RandomSparseSplitter[] = { + {"__reduce__", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_20RandomSparseSplitter_1__reduce__, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_RandomSparseSplitter = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.RandomSparseSplitter", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_RandomSparseSplitter), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_BaseSparseSplitter, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + "Splitter for finding a random split, using the sparse data.", /*tp_doc*/ + __pyx_tp_traverse_7sklearn_4tree_5_tree_Splitter, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_4tree_5_tree_Splitter, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_RandomSparseSplitter, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_RandomSparseSplitter, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_DepthFirstTreeBuilder __pyx_vtable_7sklearn_4tree_5_tree_DepthFirstTreeBuilder; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_DepthFirstTreeBuilder(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_TreeBuilder(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder*)__pyx_vtabptr_7sklearn_4tree_5_tree_DepthFirstTreeBuilder; + if (unlikely(__pyx_pw_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_1__cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_DepthFirstTreeBuilder[] = { + {"build", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_3build, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_2build}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_DepthFirstTreeBuilder = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.DepthFirstTreeBuilder", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_DepthFirstTreeBuilder), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_TreeBuilder, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + "Build a decision tree in depth-first fashion.", /*tp_doc*/ + __pyx_tp_traverse_7sklearn_4tree_5_tree_TreeBuilder, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_4tree_5_tree_TreeBuilder, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_DepthFirstTreeBuilder, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_DepthFirstTreeBuilder, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_5_tree_BestFirstTreeBuilder __pyx_vtable_7sklearn_4tree_5_tree_BestFirstTreeBuilder; + +static PyObject *__pyx_tp_new_7sklearn_4tree_5_tree_BestFirstTreeBuilder(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *p; + PyObject *o = __pyx_tp_new_7sklearn_4tree_5_tree_TreeBuilder(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_4tree_5_tree_TreeBuilder*)__pyx_vtabptr_7sklearn_4tree_5_tree_BestFirstTreeBuilder; + if (unlikely(__pyx_pw_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_1__cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_5_tree_BestFirstTreeBuilder[] = { + {"build", (PyCFunction)__pyx_pw_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_3build, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_2build}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_5_tree_BestFirstTreeBuilder = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._tree.BestFirstTreeBuilder", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_5_tree_TreeBuilder, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + "Build a decision tree in best-first fashion.\n\n The best node to expand is given by the node at the frontier that has the\n highest impurity improvement.\n\n NOTE: this TreeBuilder will ignore ``tree.max_depth`` .\n ", /*tp_doc*/ + __pyx_tp_traverse_7sklearn_4tree_5_tree_TreeBuilder, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_4tree_5_tree_TreeBuilder, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_5_tree_BestFirstTreeBuilder, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_5_tree_BestFirstTreeBuilder, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + "_tree", + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_n_s_C, __pyx_k_C, sizeof(__pyx_k_C), 0, 0, 1, 1}, + {&__pyx_n_s_DOUBLE, __pyx_k_DOUBLE, sizeof(__pyx_k_DOUBLE), 0, 0, 1, 1}, + {&__pyx_n_s_DTYPE, __pyx_k_DTYPE, sizeof(__pyx_k_DTYPE), 0, 0, 1, 1}, + {&__pyx_kp_s_Did_not_recognise_loaded_array_l, __pyx_k_Did_not_recognise_loaded_array_l, sizeof(__pyx_k_Did_not_recognise_loaded_array_l), 0, 0, 1, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, + {&__pyx_n_s_NODE_DTYPE, __pyx_k_NODE_DTYPE, sizeof(__pyx_k_NODE_DTYPE), 0, 0, 1, 1}, + {&__pyx_kp_s_No_support_for_np_int64_index_ba, __pyx_k_No_support_for_np_int64_index_ba, sizeof(__pyx_k_No_support_for_np_int64_index_ba), 0, 0, 1, 0}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_TREE_LEAF, __pyx_k_TREE_LEAF, sizeof(__pyx_k_TREE_LEAF), 0, 0, 1, 1}, + {&__pyx_n_s_TREE_UNDEFINED, __pyx_k_TREE_UNDEFINED, sizeof(__pyx_k_TREE_UNDEFINED), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_kp_s_X_dtype_should_be_np_float32_got, __pyx_k_X_dtype_should_be_np_float32_got, sizeof(__pyx_k_X_dtype_should_be_np_float32_got), 0, 0, 1, 0}, + {&__pyx_kp_s_X_should_be_in_csc_format, __pyx_k_X_should_be_in_csc_format, sizeof(__pyx_k_X_should_be_in_csc_format), 0, 0, 1, 0}, + {&__pyx_kp_s_X_should_be_in_csr_matrix_format, __pyx_k_X_should_be_in_csr_matrix_format, sizeof(__pyx_k_X_should_be_in_csr_matrix_format), 0, 0, 1, 0}, + {&__pyx_kp_s_X_should_be_in_np_ndarray_format, __pyx_k_X_should_be_in_np_ndarray_format, sizeof(__pyx_k_X_should_be_in_np_ndarray_format), 0, 0, 1, 0}, + {&__pyx_kp_s_You_have_loaded_Tree_version_whi, __pyx_k_You_have_loaded_Tree_version_whi, sizeof(__pyx_k_You_have_loaded_Tree_version_whi), 0, 0, 1, 0}, + {&__pyx_n_s_apply, __pyx_k_apply, sizeof(__pyx_k_apply), 0, 0, 1, 1}, + {&__pyx_n_s_argsort, __pyx_k_argsort, sizeof(__pyx_k_argsort), 0, 0, 1, 1}, + {&__pyx_n_s_asarray, __pyx_k_asarray, sizeof(__pyx_k_asarray), 0, 0, 1, 1}, + {&__pyx_n_s_ascontiguousarray, __pyx_k_ascontiguousarray, sizeof(__pyx_k_ascontiguousarray), 0, 0, 1, 1}, + {&__pyx_n_s_asfortranarray, __pyx_k_asfortranarray, sizeof(__pyx_k_asfortranarray), 0, 0, 1, 1}, + {&__pyx_n_s_axis, __pyx_k_axis, sizeof(__pyx_k_axis), 0, 0, 1, 1}, + {&__pyx_n_s_build, __pyx_k_build, sizeof(__pyx_k_build), 0, 0, 1, 1}, + {&__pyx_n_s_c_contiguous, __pyx_k_c_contiguous, sizeof(__pyx_k_c_contiguous), 0, 0, 1, 1}, + {&__pyx_n_s_clip, __pyx_k_clip, sizeof(__pyx_k_clip), 0, 0, 1, 1}, + {&__pyx_n_s_compute_feature_importances, __pyx_k_compute_feature_importances, sizeof(__pyx_k_compute_feature_importances), 0, 0, 1, 1}, + {&__pyx_n_s_contiguous, __pyx_k_contiguous, sizeof(__pyx_k_contiguous), 0, 0, 1, 1}, + {&__pyx_n_s_copy, __pyx_k_copy, sizeof(__pyx_k_copy), 0, 0, 1, 1}, + {&__pyx_kp_s_could_not_allocate_d_bytes, __pyx_k_could_not_allocate_d_bytes, sizeof(__pyx_k_could_not_allocate_d_bytes), 0, 0, 1, 0}, + {&__pyx_kp_s_could_not_allocate_d_d_bytes, __pyx_k_could_not_allocate_d_d_bytes, sizeof(__pyx_k_could_not_allocate_d_d_bytes), 0, 0, 1, 0}, + {&__pyx_n_s_criterion, __pyx_k_criterion, sizeof(__pyx_k_criterion), 0, 0, 1, 1}, + {&__pyx_n_s_csc_matrix, __pyx_k_csc_matrix, sizeof(__pyx_k_csc_matrix), 0, 0, 1, 1}, + {&__pyx_n_s_csr_matrix, __pyx_k_csr_matrix, sizeof(__pyx_k_csr_matrix), 0, 0, 1, 1}, + {&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_feature, __pyx_k_feature, sizeof(__pyx_k_feature), 0, 0, 1, 1}, + {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, + {&__pyx_n_s_float32, __pyx_k_float32, sizeof(__pyx_k_float32), 0, 0, 1, 1}, + {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 0, 0, 1, 1}, + {&__pyx_n_s_formats, __pyx_k_formats, sizeof(__pyx_k_formats), 0, 0, 1, 1}, + {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, + {&__pyx_kp_s_home_gilles_src_scikit_learn_sk, __pyx_k_home_gilles_src_scikit_learn_sk, sizeof(__pyx_k_home_gilles_src_scikit_learn_sk), 0, 0, 1, 0}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_impurity, __pyx_k_impurity, sizeof(__pyx_k_impurity), 0, 0, 1, 1}, + {&__pyx_n_s_indices, __pyx_k_indices, sizeof(__pyx_k_indices), 0, 0, 1, 1}, + {&__pyx_n_s_indptr, __pyx_k_indptr, sizeof(__pyx_k_indptr), 0, 0, 1, 1}, + {&__pyx_n_s_inf, __pyx_k_inf, sizeof(__pyx_k_inf), 0, 0, 1, 1}, + {&__pyx_n_s_int32, __pyx_k_int32, sizeof(__pyx_k_int32), 0, 0, 1, 1}, + {&__pyx_n_s_intp, __pyx_k_intp, sizeof(__pyx_k_intp), 0, 0, 1, 1}, + {&__pyx_n_s_issparse, __pyx_k_issparse, sizeof(__pyx_k_issparse), 0, 0, 1, 1}, + {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, + {&__pyx_n_s_left_child, __pyx_k_left_child, sizeof(__pyx_k_left_child), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_max, __pyx_k_max, sizeof(__pyx_k_max), 0, 0, 1, 1}, + {&__pyx_n_s_max_depth, __pyx_k_max_depth, sizeof(__pyx_k_max_depth), 0, 0, 1, 1}, + {&__pyx_n_s_max_features, __pyx_k_max_features, sizeof(__pyx_k_max_features), 0, 0, 1, 1}, + {&__pyx_n_s_max_leaf_nodes, __pyx_k_max_leaf_nodes, sizeof(__pyx_k_max_leaf_nodes), 0, 0, 1, 1}, + {&__pyx_n_s_min_samples_leaf, __pyx_k_min_samples_leaf, sizeof(__pyx_k_min_samples_leaf), 0, 0, 1, 1}, + {&__pyx_n_s_min_samples_split, __pyx_k_min_samples_split, sizeof(__pyx_k_min_samples_split), 0, 0, 1, 1}, + {&__pyx_n_s_min_weight_leaf, __pyx_k_min_weight_leaf, sizeof(__pyx_k_min_weight_leaf), 0, 0, 1, 1}, + {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, + {&__pyx_n_s_n_classes, __pyx_k_n_classes, sizeof(__pyx_k_n_classes), 0, 0, 1, 1}, + {&__pyx_n_s_n_features, __pyx_k_n_features, sizeof(__pyx_k_n_features), 0, 0, 1, 1}, + {&__pyx_n_s_n_node_samples, __pyx_k_n_node_samples, sizeof(__pyx_k_n_node_samples), 0, 0, 1, 1}, + {&__pyx_n_s_n_outputs, __pyx_k_n_outputs, sizeof(__pyx_k_n_outputs), 0, 0, 1, 1}, + {&__pyx_n_s_names, __pyx_k_names, sizeof(__pyx_k_names), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, + {&__pyx_n_s_node_count, __pyx_k_node_count, sizeof(__pyx_k_node_count), 0, 0, 1, 1}, + {&__pyx_n_s_nodes, __pyx_k_nodes, sizeof(__pyx_k_nodes), 0, 0, 1, 1}, + {&__pyx_n_s_normalize, __pyx_k_normalize, sizeof(__pyx_k_normalize), 0, 0, 1, 1}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_offsets, __pyx_k_offsets, sizeof(__pyx_k_offsets), 0, 0, 1, 1}, + {&__pyx_n_s_order, __pyx_k_order, sizeof(__pyx_k_order), 0, 0, 1, 1}, + {&__pyx_n_s_p, __pyx_k_p, sizeof(__pyx_k_p), 0, 0, 1, 1}, + {&__pyx_n_s_predict, __pyx_k_predict, sizeof(__pyx_k_predict), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_n_s_randint, __pyx_k_randint, sizeof(__pyx_k_randint), 0, 0, 1, 1}, + {&__pyx_n_s_random_state, __pyx_k_random_state, sizeof(__pyx_k_random_state), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_realloc_test, __pyx_k_realloc_test, sizeof(__pyx_k_realloc_test), 0, 0, 1, 1}, + {&__pyx_n_s_reshape, __pyx_k_reshape, sizeof(__pyx_k_reshape), 0, 0, 1, 1}, + {&__pyx_kp_s_resizing_tree_to_d, __pyx_k_resizing_tree_to_d, sizeof(__pyx_k_resizing_tree_to_d), 0, 0, 1, 0}, + {&__pyx_n_s_right_child, __pyx_k_right_child, sizeof(__pyx_k_right_child), 0, 0, 1, 1}, + {&__pyx_n_s_sample_weight, __pyx_k_sample_weight, sizeof(__pyx_k_sample_weight), 0, 0, 1, 1}, + {&__pyx_n_s_scipy_sparse, __pyx_k_scipy_sparse, sizeof(__pyx_k_scipy_sparse), 0, 0, 1, 1}, + {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_tree__tree, __pyx_k_sklearn_tree__tree, sizeof(__pyx_k_sklearn_tree__tree), 0, 0, 1, 1}, + {&__pyx_n_s_sort_indices, __pyx_k_sort_indices, sizeof(__pyx_k_sort_indices), 0, 0, 1, 1}, + {&__pyx_n_s_splitter, __pyx_k_splitter, sizeof(__pyx_k_splitter), 0, 0, 1, 1}, + {&__pyx_n_s_strides, __pyx_k_strides, sizeof(__pyx_k_strides), 0, 0, 1, 1}, + {&__pyx_n_s_sum, __pyx_k_sum, sizeof(__pyx_k_sum), 0, 0, 1, 1}, + {&__pyx_n_s_take, __pyx_k_take, sizeof(__pyx_k_take), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_threshold, __pyx_k_threshold, sizeof(__pyx_k_threshold), 0, 0, 1, 1}, + {&__pyx_n_s_tocsc, __pyx_k_tocsc, sizeof(__pyx_k_tocsc), 0, 0, 1, 1}, + {&__pyx_n_s_tree, __pyx_k_tree, sizeof(__pyx_k_tree), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_values, __pyx_k_values, sizeof(__pyx_k_values), 0, 0, 1, 1}, + {&__pyx_n_s_weighted_n_node_samples, __pyx_k_weighted_n_node_samples, sizeof(__pyx_k_weighted_n_node_samples), 0, 0, 1, 1}, + {&__pyx_n_s_y, __pyx_k_y, sizeof(__pyx_k_y), 0, 0, 1, 1}, + {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1851; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "sklearn/tree/_tree.pyx":1851 + * + * if not isinstance(X, csc_matrix): + * raise ValueError("X should be in csc format") # <<<<<<<<<<<<<< + * + * cdef SIZE_t* samples = self.samples + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_s_X_should_be_in_csc_format); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1851; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "sklearn/tree/_tree.pyx":2585 + * + * if X.indices.dtype != np.int32 or X.indptr.dtype != np.int32: + * raise ValueError("No support for np.int64 index based " # <<<<<<<<<<<<<< + * "sparse matrices") + * + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_No_support_for_np_int64_index_ba); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "sklearn/tree/_tree.pyx":3099 + * + * if 'nodes' not in d: + * raise ValueError('You have loaded Tree version which ' # <<<<<<<<<<<<<< + * 'cannot be imported') + * + */ + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_You_have_loaded_Tree_version_whi); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3099; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + + /* "sklearn/tree/_tree.pyx":3113 + * not value_ndarray.flags.c_contiguous or + * value_ndarray.dtype != np.float64): + * raise ValueError('Did not recognise loaded array layout') # <<<<<<<<<<<<<< + * + * self.capacity = node_ndarray.shape[0] + */ + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s_Did_not_recognise_loaded_array_l); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":806 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__11); + __Pyx_GIVEREF(__pyx_tuple__11); + + /* "sklearn/tree/_tree.pyx":3446 + * + * + * def _realloc_test(): # <<<<<<<<<<<<<< + * # Helper for tests. Tries to allocate (-1) / 2 * sizeof(size_t) + * # bytes, which will always overflow. + */ + __pyx_tuple__12 = PyTuple_Pack(1, __pyx_n_s_p); if (unlikely(!__pyx_tuple__12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + __pyx_codeobj__13 = (PyObject*)__Pyx_PyCode_New(0, 0, 1, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__12, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_gilles_src_scikit_learn_sk, __pyx_n_s_realloc_test, 3446, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_int_neg_2 = PyInt_FromLong(-2); if (unlikely(!__pyx_int_neg_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC init_tree(void); /*proto*/ +PyMODINIT_FUNC init_tree(void) +#else +PyMODINIT_FUNC PyInit__tree(void); /*proto*/ +PyMODINIT_FUNC PyInit__tree(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + double __pyx_t_3; + __pyx_t_7sklearn_4tree_5_tree_SIZE_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__tree(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4("_tree", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__tree___tree) { + if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.tree._tree")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.tree._tree", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + __pyx_vtabptr_7sklearn_4tree_5_tree_Criterion = &__pyx_vtable_7sklearn_4tree_5_tree_Criterion; + __pyx_vtable_7sklearn_4tree_5_tree_Criterion.init = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, double, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t))__pyx_f_7sklearn_4tree_5_tree_9Criterion_init; + __pyx_vtable_7sklearn_4tree_5_tree_Criterion.reset = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_9Criterion_reset; + __pyx_vtable_7sklearn_4tree_5_tree_Criterion.update = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t))__pyx_f_7sklearn_4tree_5_tree_9Criterion_update; + __pyx_vtable_7sklearn_4tree_5_tree_Criterion.node_impurity = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_9Criterion_node_impurity; + __pyx_vtable_7sklearn_4tree_5_tree_Criterion.children_impurity = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *, double *))__pyx_f_7sklearn_4tree_5_tree_9Criterion_children_impurity; + __pyx_vtable_7sklearn_4tree_5_tree_Criterion.node_value = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *))__pyx_f_7sklearn_4tree_5_tree_9Criterion_node_value; + __pyx_vtable_7sklearn_4tree_5_tree_Criterion.impurity_improvement = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double))__pyx_f_7sklearn_4tree_5_tree_9Criterion_impurity_improvement; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_Criterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_Criterion.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_Criterion.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_Criterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "Criterion", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_Criterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_Criterion = &__pyx_type_7sklearn_4tree_5_tree_Criterion; + __pyx_vtabptr_7sklearn_4tree_5_tree_Splitter = &__pyx_vtable_7sklearn_4tree_5_tree_Splitter; + __pyx_vtable_7sklearn_4tree_5_tree_Splitter.init = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, PyObject *, PyArrayObject *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *))__pyx_f_7sklearn_4tree_5_tree_8Splitter_init; + __pyx_vtable_7sklearn_4tree_5_tree_Splitter.node_reset = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double *))__pyx_f_7sklearn_4tree_5_tree_8Splitter_node_reset; + __pyx_vtable_7sklearn_4tree_5_tree_Splitter.node_split = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, double, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *))__pyx_f_7sklearn_4tree_5_tree_8Splitter_node_split; + __pyx_vtable_7sklearn_4tree_5_tree_Splitter.node_value = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, double *))__pyx_f_7sklearn_4tree_5_tree_8Splitter_node_value; + __pyx_vtable_7sklearn_4tree_5_tree_Splitter.node_impurity = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *))__pyx_f_7sklearn_4tree_5_tree_8Splitter_node_impurity; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_Splitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_Splitter.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_Splitter.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_Splitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "Splitter", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_Splitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_Splitter = &__pyx_type_7sklearn_4tree_5_tree_Splitter; + __pyx_vtabptr_7sklearn_4tree_5_tree_Tree = &__pyx_vtable_7sklearn_4tree_5_tree_Tree; + __pyx_vtable_7sklearn_4tree_5_tree_Tree._add_node = (__pyx_t_7sklearn_4tree_5_tree_SIZE_t (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, int, int, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double, double, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double))__pyx_f_7sklearn_4tree_5_tree_4Tree__add_node; + __pyx_vtable_7sklearn_4tree_5_tree_Tree._resize = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t))__pyx_f_7sklearn_4tree_5_tree_4Tree__resize; + __pyx_vtable_7sklearn_4tree_5_tree_Tree._resize_c = (int (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree__resize_c *__pyx_optional_args))__pyx_f_7sklearn_4tree_5_tree_4Tree__resize_c; + __pyx_vtable_7sklearn_4tree_5_tree_Tree._get_value_ndarray = (PyArrayObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *))__pyx_f_7sklearn_4tree_5_tree_4Tree__get_value_ndarray; + __pyx_vtable_7sklearn_4tree_5_tree_Tree._get_node_ndarray = (PyArrayObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *))__pyx_f_7sklearn_4tree_5_tree_4Tree__get_node_ndarray; + __pyx_vtable_7sklearn_4tree_5_tree_Tree.predict = (PyArrayObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *, int __pyx_skip_dispatch))__pyx_f_7sklearn_4tree_5_tree_4Tree_predict; + __pyx_vtable_7sklearn_4tree_5_tree_Tree.apply = (PyArrayObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *, int __pyx_skip_dispatch))__pyx_f_7sklearn_4tree_5_tree_4Tree_apply; + __pyx_vtable_7sklearn_4tree_5_tree_Tree._apply_dense = (PyArrayObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *))__pyx_f_7sklearn_4tree_5_tree_4Tree__apply_dense; + __pyx_vtable_7sklearn_4tree_5_tree_Tree._apply_sparse_csr = (PyArrayObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *))__pyx_f_7sklearn_4tree_5_tree_4Tree__apply_sparse_csr; + __pyx_vtable_7sklearn_4tree_5_tree_Tree.compute_feature_importances = (PyObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_4Tree_compute_feature_importances *__pyx_optional_args))__pyx_f_7sklearn_4tree_5_tree_4Tree_compute_feature_importances; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_Tree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2955; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_Tree.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_Tree.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_Tree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2955; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "Tree", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_Tree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2955; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_Tree = &__pyx_type_7sklearn_4tree_5_tree_Tree; + __pyx_vtabptr_7sklearn_4tree_5_tree_TreeBuilder = &__pyx_vtable_7sklearn_4tree_5_tree_TreeBuilder; + __pyx_vtable_7sklearn_4tree_5_tree_TreeBuilder.build = (PyObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *, PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build *__pyx_optional_args))__pyx_f_7sklearn_4tree_5_tree_11TreeBuilder_build; + __pyx_vtable_7sklearn_4tree_5_tree_TreeBuilder._check_input = (PyObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *, PyObject *, PyArrayObject *, PyArrayObject *))__pyx_f_7sklearn_4tree_5_tree_11TreeBuilder__check_input; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_TreeBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_TreeBuilder.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_TreeBuilder.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_TreeBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "TreeBuilder", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_TreeBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2566; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_TreeBuilder = &__pyx_type_7sklearn_4tree_5_tree_TreeBuilder; + __pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion = &__pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion; + __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_Criterion; + __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base.init = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, double, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t))__pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_init; + __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base.reset = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_reset; + __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base.update = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t))__pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_update; + __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base.node_impurity = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_node_impurity; + __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base.children_impurity = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *, double *))__pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_children_impurity; + __pyx_vtable_7sklearn_4tree_5_tree_ClassificationCriterion.__pyx_base.node_value = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *))__pyx_f_7sklearn_4tree_5_tree_23ClassificationCriterion_node_value; + __pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_Criterion; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "ClassificationCriterion", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion = &__pyx_type_7sklearn_4tree_5_tree_ClassificationCriterion; + __pyx_vtabptr_7sklearn_4tree_5_tree_Entropy = &__pyx_vtable_7sklearn_4tree_5_tree_Entropy; + __pyx_vtable_7sklearn_4tree_5_tree_Entropy.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion; + __pyx_vtable_7sklearn_4tree_5_tree_Entropy.__pyx_base.__pyx_base.node_impurity = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_7Entropy_node_impurity; + __pyx_vtable_7sklearn_4tree_5_tree_Entropy.__pyx_base.__pyx_base.children_impurity = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *, double *))__pyx_f_7sklearn_4tree_5_tree_7Entropy_children_impurity; + __pyx_type_7sklearn_4tree_5_tree_Entropy.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_Entropy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_Entropy.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_Entropy.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_Entropy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "Entropy", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_Entropy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_Entropy = &__pyx_type_7sklearn_4tree_5_tree_Entropy; + __pyx_vtabptr_7sklearn_4tree_5_tree_Gini = &__pyx_vtable_7sklearn_4tree_5_tree_Gini; + __pyx_vtable_7sklearn_4tree_5_tree_Gini.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_ClassificationCriterion; + __pyx_vtable_7sklearn_4tree_5_tree_Gini.__pyx_base.__pyx_base.node_impurity = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_4Gini_node_impurity; + __pyx_vtable_7sklearn_4tree_5_tree_Gini.__pyx_base.__pyx_base.children_impurity = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *, double *))__pyx_f_7sklearn_4tree_5_tree_4Gini_children_impurity; + __pyx_type_7sklearn_4tree_5_tree_Gini.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_ClassificationCriterion; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_Gini) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_Gini.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_Gini.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_Gini) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "Gini", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_Gini) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_Gini = &__pyx_type_7sklearn_4tree_5_tree_Gini; + __pyx_vtabptr_7sklearn_4tree_5_tree_RegressionCriterion = &__pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion; + __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_Criterion; + __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base.init = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *, double, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t))__pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_init; + __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base.reset = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_reset; + __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base.update = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t))__pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_update; + __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base.node_impurity = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_node_impurity; + __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base.children_impurity = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *, double *))__pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_children_impurity; + __pyx_vtable_7sklearn_4tree_5_tree_RegressionCriterion.__pyx_base.node_value = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *))__pyx_f_7sklearn_4tree_5_tree_19RegressionCriterion_node_value; + __pyx_type_7sklearn_4tree_5_tree_RegressionCriterion.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_Criterion; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_RegressionCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_RegressionCriterion.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_RegressionCriterion.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_RegressionCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "RegressionCriterion", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_RegressionCriterion) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_RegressionCriterion = &__pyx_type_7sklearn_4tree_5_tree_RegressionCriterion; + __pyx_vtabptr_7sklearn_4tree_5_tree_MSE = &__pyx_vtable_7sklearn_4tree_5_tree_MSE; + __pyx_vtable_7sklearn_4tree_5_tree_MSE.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_RegressionCriterion; + __pyx_vtable_7sklearn_4tree_5_tree_MSE.__pyx_base.__pyx_base.node_impurity = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *))__pyx_f_7sklearn_4tree_5_tree_3MSE_node_impurity; + __pyx_vtable_7sklearn_4tree_5_tree_MSE.__pyx_base.__pyx_base.children_impurity = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double *, double *))__pyx_f_7sklearn_4tree_5_tree_3MSE_children_impurity; + __pyx_type_7sklearn_4tree_5_tree_MSE.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_RegressionCriterion; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_MSE) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_MSE.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_MSE.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_MSE) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "MSE", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_MSE) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_MSE = &__pyx_type_7sklearn_4tree_5_tree_MSE; + __pyx_vtabptr_7sklearn_4tree_5_tree_FriedmanMSE = &__pyx_vtable_7sklearn_4tree_5_tree_FriedmanMSE; + __pyx_vtable_7sklearn_4tree_5_tree_FriedmanMSE.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_MSE; + __pyx_vtable_7sklearn_4tree_5_tree_FriedmanMSE.__pyx_base.__pyx_base.__pyx_base.impurity_improvement = (double (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Criterion *, double))__pyx_f_7sklearn_4tree_5_tree_11FriedmanMSE_impurity_improvement; + __pyx_type_7sklearn_4tree_5_tree_FriedmanMSE.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_MSE; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_FriedmanMSE) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 877; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_FriedmanMSE.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_FriedmanMSE.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_FriedmanMSE) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 877; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "FriedmanMSE", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_FriedmanMSE) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 877; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_FriedmanMSE = &__pyx_type_7sklearn_4tree_5_tree_FriedmanMSE; + __pyx_vtabptr_7sklearn_4tree_5_tree_BaseDenseSplitter = &__pyx_vtable_7sklearn_4tree_5_tree_BaseDenseSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_BaseDenseSplitter.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_Splitter; + __pyx_vtable_7sklearn_4tree_5_tree_BaseDenseSplitter.__pyx_base.init = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, PyObject *, PyArrayObject *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *))__pyx_f_7sklearn_4tree_5_tree_17BaseDenseSplitter_init; + __pyx_type_7sklearn_4tree_5_tree_BaseDenseSplitter.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_Splitter; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_BaseDenseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1031; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_BaseDenseSplitter.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_BaseDenseSplitter.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_BaseDenseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1031; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "BaseDenseSplitter", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_BaseDenseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1031; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_BaseDenseSplitter = &__pyx_type_7sklearn_4tree_5_tree_BaseDenseSplitter; + __pyx_vtabptr_7sklearn_4tree_5_tree_BestSplitter = &__pyx_vtable_7sklearn_4tree_5_tree_BestSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_BestSplitter.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_BaseDenseSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_BestSplitter.__pyx_base.__pyx_base.node_split = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, double, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *))__pyx_f_7sklearn_4tree_5_tree_12BestSplitter_node_split; + __pyx_type_7sklearn_4tree_5_tree_BestSplitter.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_BaseDenseSplitter; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_BestSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_BestSplitter.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_BestSplitter.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_BestSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "BestSplitter", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_BestSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_BestSplitter = &__pyx_type_7sklearn_4tree_5_tree_BestSplitter; + __pyx_vtabptr_7sklearn_4tree_5_tree_RandomSplitter = &__pyx_vtable_7sklearn_4tree_5_tree_RandomSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_RandomSplitter.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_BaseDenseSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_RandomSplitter.__pyx_base.__pyx_base.node_split = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, double, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *))__pyx_f_7sklearn_4tree_5_tree_14RandomSplitter_node_split; + __pyx_type_7sklearn_4tree_5_tree_RandomSplitter.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_BaseDenseSplitter; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_RandomSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_RandomSplitter.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_RandomSplitter.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_RandomSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "RandomSplitter", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_RandomSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_RandomSplitter = &__pyx_type_7sklearn_4tree_5_tree_RandomSplitter; + __pyx_vtabptr_7sklearn_4tree_5_tree_PresortBestSplitter = &__pyx_vtable_7sklearn_4tree_5_tree_PresortBestSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_PresortBestSplitter.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_BaseDenseSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_PresortBestSplitter.__pyx_base.__pyx_base.init = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, PyObject *, PyArrayObject *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *))__pyx_f_7sklearn_4tree_5_tree_19PresortBestSplitter_init; + __pyx_vtable_7sklearn_4tree_5_tree_PresortBestSplitter.__pyx_base.__pyx_base.node_split = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, double, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *))__pyx_f_7sklearn_4tree_5_tree_19PresortBestSplitter_node_split; + __pyx_type_7sklearn_4tree_5_tree_PresortBestSplitter.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_BaseDenseSplitter; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_PresortBestSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_PresortBestSplitter.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_PresortBestSplitter.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_PresortBestSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "PresortBestSplitter", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_PresortBestSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_PresortBestSplitter = &__pyx_type_7sklearn_4tree_5_tree_PresortBestSplitter; + __pyx_vtabptr_7sklearn_4tree_5_tree_BaseSparseSplitter = &__pyx_vtable_7sklearn_4tree_5_tree_BaseSparseSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_BaseSparseSplitter.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_Splitter; + __pyx_vtable_7sklearn_4tree_5_tree_BaseSparseSplitter.__pyx_base.init = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, PyObject *, PyArrayObject *, __pyx_t_7sklearn_4tree_5_tree_DOUBLE_t *))__pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter_init; + __pyx_vtable_7sklearn_4tree_5_tree_BaseSparseSplitter._partition = (__pyx_t_7sklearn_4tree_5_tree_SIZE_t (*)(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *, double, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t))__pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter__partition; + __pyx_vtable_7sklearn_4tree_5_tree_BaseSparseSplitter.extract_nnz = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_BaseSparseSplitter *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *, int *))__pyx_f_7sklearn_4tree_5_tree_18BaseSparseSplitter_extract_nnz; + __pyx_type_7sklearn_4tree_5_tree_BaseSparseSplitter.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_Splitter; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_BaseSparseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1811; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_BaseSparseSplitter.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_BaseSparseSplitter.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_BaseSparseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1811; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "BaseSparseSplitter", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_BaseSparseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1811; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_BaseSparseSplitter = &__pyx_type_7sklearn_4tree_5_tree_BaseSparseSplitter; + __pyx_vtabptr_7sklearn_4tree_5_tree_BestSparseSplitter = &__pyx_vtable_7sklearn_4tree_5_tree_BestSparseSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_BestSparseSplitter.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_BaseSparseSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_BestSparseSplitter.__pyx_base.__pyx_base.node_split = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, double, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *))__pyx_f_7sklearn_4tree_5_tree_18BestSparseSplitter_node_split; + __pyx_type_7sklearn_4tree_5_tree_BestSparseSplitter.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_BaseSparseSplitter; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_BestSparseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_BestSparseSplitter.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_BestSparseSplitter.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_BestSparseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "BestSparseSplitter", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_BestSparseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_BestSparseSplitter = &__pyx_type_7sklearn_4tree_5_tree_BestSparseSplitter; + __pyx_vtabptr_7sklearn_4tree_5_tree_RandomSparseSplitter = &__pyx_vtable_7sklearn_4tree_5_tree_RandomSparseSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_RandomSparseSplitter.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_BaseSparseSplitter; + __pyx_vtable_7sklearn_4tree_5_tree_RandomSparseSplitter.__pyx_base.__pyx_base.node_split = (void (*)(struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, double, struct __pyx_t_7sklearn_4tree_5_tree_SplitRecord *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t *))__pyx_f_7sklearn_4tree_5_tree_20RandomSparseSplitter_node_split; + __pyx_type_7sklearn_4tree_5_tree_RandomSparseSplitter.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_BaseSparseSplitter; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_RandomSparseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_RandomSparseSplitter.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_RandomSparseSplitter.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_RandomSparseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "RandomSparseSplitter", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_RandomSparseSplitter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_RandomSparseSplitter = &__pyx_type_7sklearn_4tree_5_tree_RandomSparseSplitter; + __pyx_vtabptr_7sklearn_4tree_5_tree_DepthFirstTreeBuilder = &__pyx_vtable_7sklearn_4tree_5_tree_DepthFirstTreeBuilder; + __pyx_vtable_7sklearn_4tree_5_tree_DepthFirstTreeBuilder.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_TreeBuilder; + __pyx_vtable_7sklearn_4tree_5_tree_DepthFirstTreeBuilder.__pyx_base.build = (PyObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *, PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build *__pyx_optional_args))__pyx_f_7sklearn_4tree_5_tree_21DepthFirstTreeBuilder_build; + __pyx_type_7sklearn_4tree_5_tree_DepthFirstTreeBuilder.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_TreeBuilder; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_DepthFirstTreeBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2605; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_DepthFirstTreeBuilder.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_DepthFirstTreeBuilder.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_DepthFirstTreeBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2605; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "DepthFirstTreeBuilder", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_DepthFirstTreeBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2605; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_DepthFirstTreeBuilder = &__pyx_type_7sklearn_4tree_5_tree_DepthFirstTreeBuilder; + __pyx_vtabptr_7sklearn_4tree_5_tree_BestFirstTreeBuilder = &__pyx_vtable_7sklearn_4tree_5_tree_BestFirstTreeBuilder; + __pyx_vtable_7sklearn_4tree_5_tree_BestFirstTreeBuilder.__pyx_base = *__pyx_vtabptr_7sklearn_4tree_5_tree_TreeBuilder; + __pyx_vtable_7sklearn_4tree_5_tree_BestFirstTreeBuilder.__pyx_base.build = (PyObject *(*)(struct __pyx_obj_7sklearn_4tree_5_tree_TreeBuilder *, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, PyObject *, PyArrayObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_4tree_5_tree_11TreeBuilder_build *__pyx_optional_args))__pyx_f_7sklearn_4tree_5_tree_20BestFirstTreeBuilder_build; + __pyx_vtable_7sklearn_4tree_5_tree_BestFirstTreeBuilder._add_split_node = (int (*)(struct __pyx_obj_7sklearn_4tree_5_tree_BestFirstTreeBuilder *, struct __pyx_obj_7sklearn_4tree_5_tree_Splitter *, struct __pyx_obj_7sklearn_4tree_5_tree_Tree *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, double, int, int, struct __pyx_t_7sklearn_4tree_5_tree_Node *, __pyx_t_7sklearn_4tree_5_tree_SIZE_t, struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *))__pyx_f_7sklearn_4tree_5_tree_20BestFirstTreeBuilder__add_split_node; + __pyx_type_7sklearn_4tree_5_tree_BestFirstTreeBuilder.tp_base = __pyx_ptype_7sklearn_4tree_5_tree_TreeBuilder; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_5_tree_BestFirstTreeBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_5_tree_BestFirstTreeBuilder.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_5_tree_BestFirstTreeBuilder.tp_dict, __pyx_vtabptr_7sklearn_4tree_5_tree_BestFirstTreeBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "BestFirstTreeBuilder", (PyObject *)&__pyx_type_7sklearn_4tree_5_tree_BestFirstTreeBuilder) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2751; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_5_tree_BestFirstTreeBuilder = &__pyx_type_7sklearn_4tree_5_tree_BestFirstTreeBuilder; + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 864; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), 0); if (unlikely(!__pyx_ptype_7cpython_4bool_bool)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), 0); if (unlikely(!__pyx_ptype_7cpython_7complex_complex)) {__pyx_filename = __pyx_f[5]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_6_utils_Stack = __Pyx_ImportType("sklearn.tree._utils", "Stack", sizeof(struct __pyx_obj_7sklearn_4tree_6_utils_Stack), 1); if (unlikely(!__pyx_ptype_7sklearn_4tree_6_utils_Stack)) {__pyx_filename = __pyx_f[6]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_4tree_6_utils_Stack = (struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack*)__Pyx_GetVtable(__pyx_ptype_7sklearn_4tree_6_utils_Stack->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_4tree_6_utils_Stack)) {__pyx_filename = __pyx_f[6]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_6_utils_PriorityHeap = __Pyx_ImportType("sklearn.tree._utils", "PriorityHeap", sizeof(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap), 1); if (unlikely(!__pyx_ptype_7sklearn_4tree_6_utils_PriorityHeap)) {__pyx_filename = __pyx_f[6]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_7sklearn_4tree_6_utils_PriorityHeap = (struct __pyx_vtabstruct_7sklearn_4tree_6_utils_PriorityHeap*)__Pyx_GetVtable(__pyx_ptype_7sklearn_4tree_6_utils_PriorityHeap->tp_dict); if (unlikely(!__pyx_vtabptr_7sklearn_4tree_6_utils_PriorityHeap)) {__pyx_filename = __pyx_f[6]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/tree/_tree.pyx":23 + * from cpython cimport Py_INCREF, PyObject + * + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * np.import_array() + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":25 + * import numpy as np + * cimport numpy as np + * np.import_array() # <<<<<<<<<<<<<< + * + * from scipy.sparse import issparse, csc_matrix, csr_matrix + */ + import_array(); + + /* "sklearn/tree/_tree.pyx":27 + * np.import_array() + * + * from scipy.sparse import issparse, csc_matrix, csr_matrix # <<<<<<<<<<<<<< + * + * from sklearn.tree._utils cimport Stack, StackRecord + */ + __pyx_t_1 = PyList_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s_issparse); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_issparse); + __Pyx_GIVEREF(__pyx_n_s_issparse); + __Pyx_INCREF(__pyx_n_s_csc_matrix); + PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_csc_matrix); + __Pyx_GIVEREF(__pyx_n_s_csc_matrix); + __Pyx_INCREF(__pyx_n_s_csr_matrix); + PyList_SET_ITEM(__pyx_t_1, 2, __pyx_n_s_csr_matrix); + __Pyx_GIVEREF(__pyx_n_s_csr_matrix); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_scipy_sparse, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_issparse); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_issparse, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_csc_matrix); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_csc_matrix, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_csr_matrix); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_csr_matrix, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/tree/_tree.pyx":44 + * # ============================================================================= + * + * from numpy import float32 as DTYPE # <<<<<<<<<<<<<< + * from numpy import float64 as DOUBLE + * + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_float32); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_float32); + __Pyx_GIVEREF(__pyx_n_s_float32); + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, __pyx_t_2, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_float32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":45 + * + * from numpy import float32 as DTYPE + * from numpy import float64 as DOUBLE # <<<<<<<<<<<<<< + * + * cdef double INFINITY = np.inf + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s_float64); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_float64); + __Pyx_GIVEREF(__pyx_n_s_float64); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_numpy, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_DOUBLE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/tree/_tree.pyx":47 + * from numpy import float64 as DOUBLE + * + * cdef double INFINITY = np.inf # <<<<<<<<<<<<<< + * TREE_LEAF = -1 + * TREE_UNDEFINED = -2 + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_inf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_3 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_7sklearn_4tree_5_tree_INFINITY = __pyx_t_3; + + /* "sklearn/tree/_tree.pyx":48 + * + * cdef double INFINITY = np.inf + * TREE_LEAF = -1 # <<<<<<<<<<<<<< + * TREE_UNDEFINED = -2 + * cdef SIZE_t _TREE_LEAF = TREE_LEAF + */ + if (PyDict_SetItem(__pyx_d, __pyx_n_s_TREE_LEAF, __pyx_int_neg_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":49 + * cdef double INFINITY = np.inf + * TREE_LEAF = -1 + * TREE_UNDEFINED = -2 # <<<<<<<<<<<<<< + * cdef SIZE_t _TREE_LEAF = TREE_LEAF + * cdef SIZE_t _TREE_UNDEFINED = TREE_UNDEFINED + */ + if (PyDict_SetItem(__pyx_d, __pyx_n_s_TREE_UNDEFINED, __pyx_int_neg_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/tree/_tree.pyx":50 + * TREE_LEAF = -1 + * TREE_UNDEFINED = -2 + * cdef SIZE_t _TREE_LEAF = TREE_LEAF # <<<<<<<<<<<<<< + * cdef SIZE_t _TREE_UNDEFINED = TREE_UNDEFINED + * cdef SIZE_t INITIAL_STACK_SIZE = 10 + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_TREE_LEAF); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_4 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_7sklearn_4tree_5_tree__TREE_LEAF = __pyx_t_4; + + /* "sklearn/tree/_tree.pyx":51 + * TREE_UNDEFINED = -2 + * cdef SIZE_t _TREE_LEAF = TREE_LEAF + * cdef SIZE_t _TREE_UNDEFINED = TREE_UNDEFINED # <<<<<<<<<<<<<< + * cdef SIZE_t INITIAL_STACK_SIZE = 10 + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_TREE_UNDEFINED); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyInt_As_Py_intptr_t(__pyx_t_1); if (unlikely((__pyx_t_4 == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_7sklearn_4tree_5_tree__TREE_UNDEFINED = __pyx_t_4; + + /* "sklearn/tree/_tree.pyx":52 + * cdef SIZE_t _TREE_LEAF = TREE_LEAF + * cdef SIZE_t _TREE_UNDEFINED = TREE_UNDEFINED + * cdef SIZE_t INITIAL_STACK_SIZE = 10 # <<<<<<<<<<<<<< + * + * cdef DTYPE_t MIN_IMPURITY_SPLIT = 1e-7 + */ + __pyx_v_7sklearn_4tree_5_tree_INITIAL_STACK_SIZE = 10; + + /* "sklearn/tree/_tree.pyx":54 + * cdef SIZE_t INITIAL_STACK_SIZE = 10 + * + * cdef DTYPE_t MIN_IMPURITY_SPLIT = 1e-7 # <<<<<<<<<<<<<< + * + * # Mitigate precision differences between 32 bit and 64 bit + */ + __pyx_v_7sklearn_4tree_5_tree_MIN_IMPURITY_SPLIT = 1e-7; + + /* "sklearn/tree/_tree.pyx":57 + * + * # Mitigate precision differences between 32 bit and 64 bit + * cdef DTYPE_t FEATURE_THRESHOLD = 1e-7 # <<<<<<<<<<<<<< + * + * # Constant to switch between algorithm non zero value extract algorithm + */ + __pyx_v_7sklearn_4tree_5_tree_FEATURE_THRESHOLD = 1e-7; + + /* "sklearn/tree/_tree.pyx":61 + * # Constant to switch between algorithm non zero value extract algorithm + * # in SparseSplitter + * cdef DTYPE_t EXTRACT_NNZ_SWITCH = 0.1 # <<<<<<<<<<<<<< + * + * # Some handy constants (BestFirstTreeBuilder) + */ + __pyx_v_7sklearn_4tree_5_tree_EXTRACT_NNZ_SWITCH = 0.1; + + /* "sklearn/tree/_tree.pyx":64 + * + * # Some handy constants (BestFirstTreeBuilder) + * cdef int IS_FIRST = 1 # <<<<<<<<<<<<<< + * cdef int IS_NOT_FIRST = 0 + * cdef int IS_LEFT = 1 + */ + __pyx_v_7sklearn_4tree_5_tree_IS_FIRST = 1; + + /* "sklearn/tree/_tree.pyx":65 + * # Some handy constants (BestFirstTreeBuilder) + * cdef int IS_FIRST = 1 + * cdef int IS_NOT_FIRST = 0 # <<<<<<<<<<<<<< + * cdef int IS_LEFT = 1 + * cdef int IS_NOT_LEFT = 0 + */ + __pyx_v_7sklearn_4tree_5_tree_IS_NOT_FIRST = 0; + + /* "sklearn/tree/_tree.pyx":66 + * cdef int IS_FIRST = 1 + * cdef int IS_NOT_FIRST = 0 + * cdef int IS_LEFT = 1 # <<<<<<<<<<<<<< + * cdef int IS_NOT_LEFT = 0 + * + */ + __pyx_v_7sklearn_4tree_5_tree_IS_LEFT = 1; + + /* "sklearn/tree/_tree.pyx":67 + * cdef int IS_NOT_FIRST = 0 + * cdef int IS_LEFT = 1 + * cdef int IS_NOT_LEFT = 0 # <<<<<<<<<<<<<< + * + * cdef enum: + */ + __pyx_v_7sklearn_4tree_5_tree_IS_NOT_LEFT = 0; + + /* "sklearn/tree/_tree.pyx":76 + * + * # Repeat struct definition for numpy + * NODE_DTYPE = np.dtype({ # <<<<<<<<<<<<<< + * 'names': ['left_child', 'right_child', 'feature', 'threshold', 'impurity', + * 'n_node_samples', 'weighted_n_node_samples'], + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "sklearn/tree/_tree.pyx":77 + * # Repeat struct definition for numpy + * NODE_DTYPE = np.dtype({ + * 'names': ['left_child', 'right_child', 'feature', 'threshold', 'impurity', # <<<<<<<<<<<<<< + * 'n_node_samples', 'weighted_n_node_samples'], + * 'formats': [np.intp, np.intp, np.intp, np.float64, np.float64, np.intp, + */ + __pyx_t_2 = PyList_New(7); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_left_child); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_left_child); + __Pyx_GIVEREF(__pyx_n_s_left_child); + __Pyx_INCREF(__pyx_n_s_right_child); + PyList_SET_ITEM(__pyx_t_2, 1, __pyx_n_s_right_child); + __Pyx_GIVEREF(__pyx_n_s_right_child); + __Pyx_INCREF(__pyx_n_s_feature); + PyList_SET_ITEM(__pyx_t_2, 2, __pyx_n_s_feature); + __Pyx_GIVEREF(__pyx_n_s_feature); + __Pyx_INCREF(__pyx_n_s_threshold); + PyList_SET_ITEM(__pyx_t_2, 3, __pyx_n_s_threshold); + __Pyx_GIVEREF(__pyx_n_s_threshold); + __Pyx_INCREF(__pyx_n_s_impurity); + PyList_SET_ITEM(__pyx_t_2, 4, __pyx_n_s_impurity); + __Pyx_GIVEREF(__pyx_n_s_impurity); + __Pyx_INCREF(__pyx_n_s_n_node_samples); + PyList_SET_ITEM(__pyx_t_2, 5, __pyx_n_s_n_node_samples); + __Pyx_GIVEREF(__pyx_n_s_n_node_samples); + __Pyx_INCREF(__pyx_n_s_weighted_n_node_samples); + PyList_SET_ITEM(__pyx_t_2, 6, __pyx_n_s_weighted_n_node_samples); + __Pyx_GIVEREF(__pyx_n_s_weighted_n_node_samples); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_names, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/tree/_tree.pyx":79 + * 'names': ['left_child', 'right_child', 'feature', 'threshold', 'impurity', + * 'n_node_samples', 'weighted_n_node_samples'], + * 'formats': [np.intp, np.intp, np.intp, np.float64, np.float64, np.intp, # <<<<<<<<<<<<<< + * np.float64], + * 'offsets': [ + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_intp); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_intp); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_intp); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_10 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_intp); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/tree/_tree.pyx":80 + * 'n_node_samples', 'weighted_n_node_samples'], + * 'formats': [np.intp, np.intp, np.intp, np.float64, np.float64, np.intp, + * np.float64], # <<<<<<<<<<<<<< + * 'offsets': [ + * &( NULL).left_child, + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/tree/_tree.pyx":79 + * 'names': ['left_child', 'right_child', 'feature', 'threshold', 'impurity', + * 'n_node_samples', 'weighted_n_node_samples'], + * 'formats': [np.intp, np.intp, np.intp, np.float64, np.float64, np.intp, # <<<<<<<<<<<<<< + * np.float64], + * 'offsets': [ + */ + __pyx_t_2 = PyList_New(7); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyList_SET_ITEM(__pyx_t_2, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyList_SET_ITEM(__pyx_t_2, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyList_SET_ITEM(__pyx_t_2, 3, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_2, 4, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + PyList_SET_ITEM(__pyx_t_2, 5, __pyx_t_10); + __Pyx_GIVEREF(__pyx_t_10); + PyList_SET_ITEM(__pyx_t_2, 6, __pyx_t_11); + __Pyx_GIVEREF(__pyx_t_11); + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_8 = 0; + __pyx_t_9 = 0; + __pyx_t_10 = 0; + __pyx_t_11 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_formats, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/tree/_tree.pyx":82 + * np.float64], + * 'offsets': [ + * &( NULL).left_child, # <<<<<<<<<<<<<< + * &( NULL).right_child, + * &( NULL).feature, + */ + __pyx_t_2 = PyInt_FromSsize_t(((Py_ssize_t)(&((struct __pyx_t_7sklearn_4tree_5_tree_Node *)NULL)->left_child))); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + + /* "sklearn/tree/_tree.pyx":83 + * 'offsets': [ + * &( NULL).left_child, + * &( NULL).right_child, # <<<<<<<<<<<<<< + * &( NULL).feature, + * &( NULL).threshold, + */ + __pyx_t_11 = PyInt_FromSsize_t(((Py_ssize_t)(&((struct __pyx_t_7sklearn_4tree_5_tree_Node *)NULL)->right_child))); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + + /* "sklearn/tree/_tree.pyx":84 + * &( NULL).left_child, + * &( NULL).right_child, + * &( NULL).feature, # <<<<<<<<<<<<<< + * &( NULL).threshold, + * &( NULL).impurity, + */ + __pyx_t_10 = PyInt_FromSsize_t(((Py_ssize_t)(&((struct __pyx_t_7sklearn_4tree_5_tree_Node *)NULL)->feature))); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + + /* "sklearn/tree/_tree.pyx":85 + * &( NULL).right_child, + * &( NULL).feature, + * &( NULL).threshold, # <<<<<<<<<<<<<< + * &( NULL).impurity, + * &( NULL).n_node_samples, + */ + __pyx_t_9 = PyInt_FromSsize_t(((Py_ssize_t)(&((struct __pyx_t_7sklearn_4tree_5_tree_Node *)NULL)->threshold))); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + + /* "sklearn/tree/_tree.pyx":86 + * &( NULL).feature, + * &( NULL).threshold, + * &( NULL).impurity, # <<<<<<<<<<<<<< + * &( NULL).n_node_samples, + * &( NULL).weighted_n_node_samples + */ + __pyx_t_8 = PyInt_FromSsize_t(((Py_ssize_t)(&((struct __pyx_t_7sklearn_4tree_5_tree_Node *)NULL)->impurity))); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + + /* "sklearn/tree/_tree.pyx":87 + * &( NULL).threshold, + * &( NULL).impurity, + * &( NULL).n_node_samples, # <<<<<<<<<<<<<< + * &( NULL).weighted_n_node_samples + * ] + */ + __pyx_t_7 = PyInt_FromSsize_t(((Py_ssize_t)(&((struct __pyx_t_7sklearn_4tree_5_tree_Node *)NULL)->n_node_samples))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + + /* "sklearn/tree/_tree.pyx":88 + * &( NULL).impurity, + * &( NULL).n_node_samples, + * &( NULL).weighted_n_node_samples # <<<<<<<<<<<<<< + * ] + * }) + */ + __pyx_t_6 = PyInt_FromSsize_t(((Py_ssize_t)(&((struct __pyx_t_7sklearn_4tree_5_tree_Node *)NULL)->weighted_n_node_samples))); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "sklearn/tree/_tree.pyx":81 + * 'formats': [np.intp, np.intp, np.intp, np.float64, np.float64, np.intp, + * np.float64], + * 'offsets': [ # <<<<<<<<<<<<<< + * &( NULL).left_child, + * &( NULL).right_child, + */ + __pyx_t_5 = PyList_New(7); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyList_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyList_SET_ITEM(__pyx_t_5, 1, __pyx_t_11); + __Pyx_GIVEREF(__pyx_t_11); + PyList_SET_ITEM(__pyx_t_5, 2, __pyx_t_10); + __Pyx_GIVEREF(__pyx_t_10); + PyList_SET_ITEM(__pyx_t_5, 3, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_9); + PyList_SET_ITEM(__pyx_t_5, 4, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_5, 5, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + PyList_SET_ITEM(__pyx_t_5, 6, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_2 = 0; + __pyx_t_11 = 0; + __pyx_t_10 = 0; + __pyx_t_9 = 0; + __pyx_t_8 = 0; + __pyx_t_7 = 0; + __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_offsets, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "sklearn/tree/_tree.pyx":76 + * + * # Repeat struct definition for numpy + * NODE_DTYPE = np.dtype({ # <<<<<<<<<<<<<< + * 'names': ['left_child', 'right_child', 'feature', 'threshold', 'impurity', + * 'n_node_samples', 'weighted_n_node_samples'], + */ + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_5numpy_dtype)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_NODE_DTYPE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":3131 + * # XXX using (size_t)(-1) is ugly, but SIZE_MAX is not available in C89 + * # (i.e., older MSVC). + * cdef int _resize_c(self, SIZE_t capacity=(-1)) nogil: # <<<<<<<<<<<<<< + * """Guts of _resize. Returns 0 for success, -1 for error.""" + * if capacity == self.capacity and self.nodes != NULL: + */ + __pyx_k__5 = ((__pyx_t_7sklearn_4tree_5_tree_SIZE_t)-1); + + /* "sklearn/tree/_tree.pyx":3446 + * + * + * def _realloc_test(): # <<<<<<<<<<<<<< + * # Helper for tests. Tries to allocate (-1) / 2 * sizeof(size_t) + * # bytes, which will always overflow. + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_4tree_5_tree_1_realloc_test, NULL, __pyx_n_s_sklearn_tree__tree); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_realloc_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/tree/_tree.pyx":1 + * # cython: cdivision=True # <<<<<<<<<<<<<< + * # cython: boundscheck=False + * # cython: wraparound=False + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":979 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + if (__pyx_m) { + if (__pyx_d) { + __Pyx_AddTraceback("init sklearn.tree._tree", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.tree._tree"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* --- Runtime support code --- */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(PyObject_TypeCheck(obj, type))) return 1; + } + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case '\r': + case '\n': + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; + } + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); } return result; } +#endif -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = PyCFunction_GET_FUNCTION(func); + self = PyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); } - if (exact) { - more_or_less = "exactly"; + return result; +} +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *result; + PyObject *args = PyTuple_New(1); + if (unlikely(!args)) return NULL; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, arg); + result = __Pyx_PyObject_Call(func, args, NULL); + Py_DECREF(args); + return result; +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { +#ifdef __Pyx_CyFunction_USED + if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { +#else + if (likely(PyCFunction_Check(func))) { +#endif + if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { + return __Pyx_PyObject_CallMethO(func, arg); + } } - PyErr_Format(PyExc_TypeError, - "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); + return __Pyx__PyObject_CallOneArg(func, arg); } +#else +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject* args = PyTuple_Pack(1, arg); + return (likely(args)) ? __Pyx_PyObject_Call(func, args, NULL) : NULL; +} +#endif -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { +#ifdef __Pyx_CyFunction_USED + if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { +#else + if (likely(PyCFunction_Check(func))) { +#endif + if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { + return __Pyx_PyObject_CallMethO(func, NULL); + } + } + return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); } +#endif -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; } - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 - if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : - #endif - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; } } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; + return m->sq_item(o, i); } } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact) -{ - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; - } - if (none_allowed && obj == Py_None) return 1; - else if (exact) { - if (Py_TYPE(obj) == type) return 1; - } - else { - if (PyObject_TypeCheck(obj, type)) return 1; +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); } static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); + PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) @@ -18193,960 +33826,1171 @@ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { return 0; } -static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { - unsigned int n = 1; - return *(unsigned char*)(&n) != 0; -} -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type) { - stack[0].field = &ctx->root; - stack[0].parent_offset = 0; - ctx->root.type = type; - ctx->root.name = "buffer dtype"; - ctx->root.offset = 0; - ctx->head = stack; - ctx->head->field = &ctx->root; - ctx->fmt_offset = 0; - ctx->head->parent_offset = 0; - ctx->new_packmode = '@'; - ctx->enc_packmode = '@'; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->is_complex = 0; - ctx->is_valid_array = 0; - ctx->struct_alignment = 0; - while (type->typegroup == 'S') { - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = 0; - type = type->fields->type; - } -} -static int __Pyx_BufFmt_ParseNumber(const char** ts) { - int count; - const char* t = *ts; - if (*t < '0' || *t > '9') { - return -1; +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (likely(result)) { + Py_INCREF(result); } else { - count = *t++ - '0'; - while (*t >= '0' && *t < '9') { - count *= 10; - count += *t++ - '0'; - } +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); } - *ts = t; - return count; -} -static int __Pyx_BufFmt_ExpectNumber(const char **ts) { - int number = __Pyx_BufFmt_ParseNumber(ts); - if (number == -1) /* First char was not a digit */ - PyErr_Format(PyExc_ValueError,\ - "Does not understand character buffer dtype format string ('%c')", **ts); - return number; -} -static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { - PyErr_Format(PyExc_ValueError, - "Unexpected format string character: '%c'", ch); -} -static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { - switch (ch) { - case 'c': return "'char'"; - case 'b': return "'signed char'"; - case 'B': return "'unsigned char'"; - case 'h': return "'short'"; - case 'H': return "'unsigned short'"; - case 'i': return "'int'"; - case 'I': return "'unsigned int'"; - case 'l': return "'long'"; - case 'L': return "'unsigned long'"; - case 'q': return "'long long'"; - case 'Q': return "'unsigned long long'"; - case 'f': return (is_complex ? "'complex float'" : "'float'"); - case 'd': return (is_complex ? "'complex double'" : "'double'"); - case 'g': return (is_complex ? "'complex long double'" : "'long double'"); - case 'T': return "a struct"; - case 'O': return "Python object"; - case 'P': return "a pointer"; - case 's': case 'p': return "a string"; - case 0: return "end"; - default: return "unparseable format string"; - } + return result; } -static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return 2; - case 'i': case 'I': case 'l': case 'L': return 4; - case 'q': case 'Q': return 8; - case 'f': return (is_complex ? 8 : 4); - case 'd': return (is_complex ? 16 : 8); - case 'g': { - PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); - return 0; + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } - case 'O': case 'P': return sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; + if (PyType_Check(type)) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; } -static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { - switch (ch) { - case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(short); - case 'i': case 'I': return sizeof(int); - case 'l': case 'L': return sizeof(long); - #ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(PY_LONG_LONG); - #endif - case 'f': return sizeof(float) * (is_complex ? 2 : 1); - case 'd': return sizeof(double) * (is_complex ? 2 : 1); - case 'g': return sizeof(long double) * (is_complex ? 2 : 1); - case 'O': case 'P': return sizeof(void*); - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; +#else +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; } - } -} -typedef struct { char c; short x; } __Pyx_st_short; -typedef struct { char c; int x; } __Pyx_st_int; -typedef struct { char c; long x; } __Pyx_st_long; -typedef struct { char c; float x; } __Pyx_st_float; -typedef struct { char c; double x; } __Pyx_st_double; -typedef struct { char c; long double x; } __Pyx_st_longdouble; -typedef struct { char c; void *x; } __Pyx_st_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; -#endif -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_st_float) - sizeof(float); - case 'd': return sizeof(__Pyx_st_double) - sizeof(double); - case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; } -} -/* These are for computing the padding at the end of the struct to align - on the first member of the struct. This will probably the same as above, - but we don't have any guarantees. - */ -typedef struct { short x; char c; } __Pyx_pad_short; -typedef struct { int x; char c; } __Pyx_pad_int; -typedef struct { long x; char c; } __Pyx_pad_long; -typedef struct { float x; char c; } __Pyx_pad_float; -typedef struct { double x; char c; } __Pyx_pad_double; -typedef struct { long double x; char c; } __Pyx_pad_longdouble; -typedef struct { void *x; char c; } __Pyx_pad_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; -#endif -static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { #endif - case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); - case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); - case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); } -} -static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { - switch (ch) { - case 'c': - return 'H'; - case 'b': case 'h': case 'i': - case 'l': case 'q': case 's': case 'p': - return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': - return 'U'; - case 'f': case 'd': case 'g': - return (is_complex ? 'C' : 'R'); - case 'O': - return 'O'; - case 'P': - return 'P'; - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; + PyErr_SetObject(type, value); + if (tb) { +#if CYTHON_COMPILING_IN_PYPY + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(tmp_type, tmp_value, tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#else + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#endif } - } +bad: + Py_XDECREF(owned_instance); + return; } -static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { - if (ctx->head == NULL || ctx->head->field == &ctx->root) { - const char* expected; - const char* quote; - if (ctx->head == NULL) { - expected = "end"; - quote = ""; - } else { - expected = ctx->head->field->type->name; - quote = "'"; - } +#endif + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected %s%s%s but got %s", - quote, expected, quote, - __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); - } else { - __Pyx_StructField* field = ctx->head->field; - __Pyx_StructField* parent = (ctx->head - 1)->field; + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", - field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), - parent->type->name, field->name); - } + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); } -static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { - char group; - size_t size, offset, arraysize = 1; - if (ctx->enc_type == 0) return 0; - if (ctx->head->field->type->arraysize[0]) { - int i, ndim = 0; - if (ctx->enc_type == 's' || ctx->enc_type == 'p') { - ctx->is_valid_array = ctx->head->field->type->ndim == 1; - ndim = 1; - if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { - PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %zu", - ctx->head->field->type->arraysize[0], ctx->enc_count); + +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { return -1; } } - if (!ctx->is_valid_array) { - PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", - ctx->head->field->type->ndim, ndim); - return -1; - } - for (i = 0; i < ctx->head->field->type->ndim; i++) { - arraysize *= ctx->head->field->type->arraysize[i]; + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } } - ctx->is_valid_array = 0; - ctx->enc_count = 1; - } - group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); - do { - __Pyx_StructField* field = ctx->head->field; - __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { - size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; } else { - size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + return __Pyx_IterFinish(); } - if (ctx->enc_packmode == '@') { - size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); - size_t align_mod_offset; - if (align_at == 0) return -1; - align_mod_offset = ctx->fmt_offset % align_at; - if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; - if (ctx->struct_alignment == 0) - ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, - ctx->is_complex); + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { +#if CYTHON_COMPILING_IN_CPYTHON + PyMappingMethods* mp; +#if PY_MAJOR_VERSION < 3 + PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; + if (likely(ms && ms->sq_slice)) { + if (!has_cstart) { + if (_py_start && (*_py_start != Py_None)) { + cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); + if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstart = 0; + } + if (!has_cstop) { + if (_py_stop && (*_py_stop != Py_None)) { + cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); + if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstop = PY_SSIZE_T_MAX; + } + if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { + Py_ssize_t l = ms->sq_length(obj); + if (likely(l >= 0)) { + if (cstop < 0) { + cstop += l; + if (cstop < 0) cstop = 0; + } + if (cstart < 0) { + cstart += l; + if (cstart < 0) cstart = 0; + } + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + goto bad; + } + } + return ms->sq_slice(obj, cstart, cstop); } - if (type->size != size || type->typegroup != group) { - if (type->typegroup == 'C' && type->fields != NULL) { - size_t parent_offset = ctx->head->parent_offset + field->offset; - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = parent_offset; - continue; - } - if ((type->typegroup == 'H' || group == 'H') && type->size == size) { - } else { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } +#endif + mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_subscript)) +#endif + { + PyObject* result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyInt_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyInt_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_COMPILING_IN_CPYTHON + result = mp->mp_subscript(obj, py_slice); +#else + result = PyObject_GetItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } + PyErr_Format(PyExc_TypeError, + "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); +bad: + return NULL; +} + +static void __Pyx_RaiseBufferFallbackError(void) { + PyErr_SetString(PyExc_ValueError, + "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +static void* __Pyx_GetVtable(PyObject *dict) { + void* ptr; + PyObject *ob = PyObject_GetItem(dict, __pyx_n_s_pyx_vtable); + if (!ob) + goto bad; +#if PY_VERSION_HEX >= 0x02070000 + ptr = PyCapsule_GetPointer(ob, 0); +#else + ptr = PyCObject_AsVoidPtr(ob); +#endif + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif } - offset = ctx->head->parent_offset + field->offset; - if (ctx->fmt_offset != offset) { - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", - (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); - return -1; + return value; +} + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; } - ctx->fmt_offset += size; - if (arraysize) - ctx->fmt_offset += (arraysize - 1) * size; - --ctx->enc_count; /* Consume from buffer string */ - while (1) { - if (field == &ctx->root) { - ctx->head = NULL; - if (ctx->enc_count != 0) { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; } - break; /* breaks both loops as ctx->enc_count == 0 */ - } - ctx->head->field = ++field; - if (field->type == NULL) { - --ctx->head; - field = ctx->head->field; - continue; - } else if (field->type->typegroup == 'S') { - size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; /* empty struct */ - field = field->type->fields; - ++ctx->head; - ctx->head->field = field; - ctx->head->parent_offset = parent_offset; - break; - } else { - break; - } } - } while (ctx->enc_count); - ctx->enc_type = 0; - ctx->is_complex = 0; - return 0; + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } } -static CYTHON_INLINE PyObject * -__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) -{ - const char *ts = *tsp; - int i = 0, number; - int ndim = ctx->head->field->type->ndim; -; - ++ts; - if (ctx->new_count != 1) { - PyErr_SetString(PyExc_ValueError, - "Cannot handle repeated arrays in format string"); +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - while (*ts && *ts != ')') { - if (isspace(*ts)) - continue; - number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) - return PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %d", - ctx->head->field->type->arraysize[i], number); - if (*ts != ',' && *ts != ')') - return PyErr_Format(PyExc_ValueError, - "Expected a comma in format string, got '%c'", *ts); - if (*ts == ',') ts++; - i++; - } - if (i != ndim) - return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", - ctx->head->field->type->ndim, i); - if (!*ts) { - PyErr_SetString(PyExc_ValueError, - "Unexpected end of format string, expected ')'"); + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } - ctx->is_valid_array = 1; - ctx->new_count = 1; - *tsp = ++ts; - return Py_None; + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; } -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { - int got_Z = 0; - while (1) { - switch(*ts) { - case 0: - if (ctx->enc_type != 0 && ctx->head == NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - if (ctx->head != NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - return ts; - case ' ': - case 10: - case 13: - ++ts; - break; - case '<': - if (!__Pyx_IsLittleEndian()) { - PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '>': - case '!': - if (__Pyx_IsLittleEndian()) { - PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '=': - case '@': - case '^': - ctx->new_packmode = *ts++; - break; - case 'T': /* substruct */ - { - const char* ts_after_sub; - size_t i, struct_count = ctx->new_count; - size_t struct_alignment = ctx->struct_alignment; - ctx->new_count = 1; - ++ts; - if (*ts != '{') { - PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; /* Erase processed last struct element */ - ctx->enc_count = 0; - ctx->struct_alignment = 0; - ++ts; - ts_after_sub = ts; - for (i = 0; i != struct_count; ++i) { - ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); - if (!ts_after_sub) return NULL; - } - ts = ts_after_sub; - if (struct_alignment) ctx->struct_alignment = struct_alignment; - } - break; - case '}': /* end of substruct; either repeat or move on */ - { - size_t alignment = ctx->struct_alignment; - ++ts; - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; /* Erase processed last struct element */ - if (alignment && ctx->fmt_offset % alignment) { - ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); - } - } - return ts; - case 'x': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->fmt_offset += ctx->new_count; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->enc_packmode = ctx->new_packmode; - ++ts; - break; - case 'Z': - got_Z = 1; - ++ts; - if (*ts != 'f' && *ts != 'd' && *ts != 'g') { - __Pyx_BufFmt_RaiseUnexpectedChar('Z'); - return NULL; - } /* fall through */ - case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': - case 'l': case 'L': case 'q': case 'Q': - case 'f': case 'd': case 'g': - case 'O': case 's': case 'p': - if (ctx->enc_type == *ts && got_Z == ctx->is_complex && - ctx->enc_packmode == ctx->new_packmode) { - ctx->enc_count += ctx->new_count; - } else { - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); } - ++ts; - ctx->new_count = 1; - got_Z = 0; - break; - case ':': - ++ts; - while(*ts != ':') ++ts; - ++ts; - break; - case '(': - if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; - break; - default: - { - int number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - ctx->new_count = (size_t)number; + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; } - } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); } -static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { - buf->buf = NULL; - buf->obj = NULL; - buf->strides = __Pyx_zeros; - buf->shape = __Pyx_zeros; - buf->suboffsets = __Pyx_minusones; + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; } -static CYTHON_INLINE int __Pyx_GetBufferAndValidate( - Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, - int nd, int cast, __Pyx_BufFmt_StackElem* stack) -{ - if (obj == Py_None || obj == NULL) { - __Pyx_ZeroBuffer(buf); - return 0; - } - buf->buf = NULL; - if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; - if (buf->ndim != nd) { - PyErr_Format(PyExc_ValueError, - "Buffer has wrong number of dimensions (expected %d, got %d)", - nd, buf->ndim); - goto fail; - } - if (!cast) { - __Pyx_BufFmt_Context ctx; - __Pyx_BufFmt_Init(&ctx, stack, dtype); - if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; - } - if ((unsigned)buf->itemsize != dtype->size) { - PyErr_Format(PyExc_ValueError, - "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", - buf->itemsize, (buf->itemsize > 1) ? "s" : "", - dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); - goto fail; - } - if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; - return 0; -fail:; - __Pyx_ZeroBuffer(buf); - return -1; +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); } -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { - if (info->buf == NULL) return; - if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; - __Pyx_ReleaseBuffer(info); + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; } -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_Restore(type, value, tb); -#endif +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); + return -1; } -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(type, value, tb); -#endif +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + Py_DECREF(obj); + view->obj = NULL; } +#endif + + #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ + { \ + func_type value = func_value; \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + if (is_unsigned && unlikely(value < zero)) \ + goto raise_neg_overflow; \ + else \ + goto raise_overflow; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *x) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; + if (likely(PyInt_Check(x))) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (Py_intptr_t) val; } - } - #if PY_VERSION_HEX < 0x02050000 - if (PyClass_Check(type)) { - #else - if (PyType_Check(type)) { - #endif -#if CYTHON_COMPILING_IN_PYPY - if (!value) { - Py_INCREF(Py_None); - value = Py_None; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(Py_intptr_t) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyLong_AsLong(x)) + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long long, PyLong_AsLongLong(x)) + } } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + Py_intptr_t val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } #endif - PyErr_NormalizeException(&type, &value, &tb); + return (Py_intptr_t) -1; + } } else { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; + Py_intptr_t val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (Py_intptr_t) -1; + val = __Pyx_PyInt_As_Py_intptr_t(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to Py_intptr_t"); + return (Py_intptr_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; +} + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; } - value = type; - #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, ((PyLongObject*)x)->ob_digit[0]); } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; } - #else - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong(x)) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong(x)) } - #endif - } - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} -#else /* Python 3+ */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; } - else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyEval_CallObject(type, args); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; } } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; } - if (cause && cause != Py_None) { - PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } - else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); } - else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; + } else { + if (sizeof(Py_intptr_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); } - PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); } -bad: - Py_XDECREF(owned_instance); - return; -} -#endif - -static void __Pyx_RaiseBufferFallbackError(void) { - PyErr_Format(PyExc_ValueError, - "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); -} - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); -} - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", - index, (index == 1) ? "" : "s"); } -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } } -static CYTHON_INLINE int __Pyx_IterFinish(void) { -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); - PyObject* exc_type = tstate->curexc_type; - if (unlikely(exc_type)) { - if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { - PyObject *exc_value, *exc_tb; - exc_value = tstate->curexc_value; - exc_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; - Py_DECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; +static CYTHON_INLINE npy_uint32 __Pyx_PyInt_As_npy_uint32(PyObject *x) { + const npy_uint32 neg_one = (npy_uint32) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(npy_uint32) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, long, PyInt_AS_LONG(x)) } else { - return -1; + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (npy_uint32) val; } - } - return 0; -#else - if (unlikely(PyErr_Occurred())) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { - PyErr_Clear(); - return 0; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_uint32, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(npy_uint32) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(npy_uint32) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } } else { - return -1; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_uint32, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(npy_uint32, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(npy_uint32) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, long, PyLong_AsLong(x)) + } else if (sizeof(npy_uint32) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(npy_uint32, long long, PyLong_AsLongLong(x)) + } } - } - return 0; + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + npy_uint32 val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } #endif -} - -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { - if (unlikely(retval)) { - Py_DECREF(retval); - __Pyx_RaiseTooManyValuesError(expected); - return -1; + return (npy_uint32) -1; + } } else { - return __Pyx_IterFinish(); + npy_uint32 val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (npy_uint32) -1; + val = __Pyx_PyInt_As_npy_uint32(tmp); + Py_DECREF(tmp); + return val; } - return 0; -} - -#if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - CYTHON_UNUSED PyObject *getbuffer_cobj; - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (getbuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_getbuffer"))) { - getbufferproc func; - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (getbufferproc) PyCapsule_GetPointer(getbuffer_cobj, "getbuffer(obj, view, flags)"); - #else - func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); - #endif - Py_DECREF(getbuffer_cobj); - if (!func) - goto fail; - return func(obj, view, flags); +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to npy_uint32"); + return (npy_uint32) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to npy_uint32"); + return (npy_uint32) -1; +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } } else { - PyErr_Clear(); - } - #endif - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); -#if PY_VERSION_HEX < 0x02060000 -fail: -#endif - return -1; -} -static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject *obj = view->obj; - CYTHON_UNUSED PyObject *releasebuffer_cobj; - if (!obj) return; - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) { - PyBuffer_Release(view); - return; + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } } - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (releasebuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_releasebuffer"))) { - releasebufferproc func; - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (releasebufferproc) PyCapsule_GetPointer(releasebuffer_cobj, "releasebuffer(obj, view)"); - #else - func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); - #endif - Py_DECREF(releasebuffer_cobj); - if (!func) - goto fail; - func(obj, view); - return; - } else { - PyErr_Clear(); + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); } - #endif - goto nofail; -#if PY_VERSION_HEX < 0x02060000 -fail: -#endif - PyErr_WriteUnraisable(obj); -nofail: - Py_DECREF(obj); - view->obj = NULL; } -#endif /* PY_MAJOR_VERSION < 3 */ - - static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); - if (!py_import) - goto bad; - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_int32(npy_int32 value) { + const npy_int32 neg_one = (npy_int32) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(npy_int32) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(npy_int32) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(npy_int32) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(npy_int32) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(npy_int32) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - #if PY_VERSION_HEX >= 0x02050000 { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if (strchr(__Pyx_MODULE_NAME, '.')) { - /* try package relative import first */ - PyObject *py_level = PyInt_FromLong(1); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(npy_int32), + little, !is_unsigned); + } +} + +static CYTHON_INLINE npy_int32 __Pyx_PyInt_As_npy_int32(PyObject *x) { + const npy_int32 neg_one = (npy_int32) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(npy_int32) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; } - level = 0; /* try absolute import on failure */ + return (npy_int32) val; } - #endif - if (!module) { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_int32, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(npy_int32) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(npy_int32) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(npy_int32, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(npy_int32, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(npy_int32) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, long, PyLong_AsLong(x)) + } else if (sizeof(npy_int32) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(npy_int32, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + npy_int32 val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (npy_int32) -1; } + } else { + npy_int32 val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (npy_int32) -1; + val = __Pyx_PyInt_As_npy_int32(tmp); + Py_DECREF(tmp); + return val; } - #else - if (level>0) { - PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); - goto bad; +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to npy_int32"); + return (npy_int32) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to npy_int32"); + return (npy_int32) -1; +} + +static CYTHON_INLINE long __Pyx_pow_long(long b, long e) { + long t = b; + switch (e) { + case 3: + t *= b; + case 2: + t *= b; + case 1: + return t; + case 0: + return 1; } - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, NULL); + #if 1 + if (unlikely(e<0)) return 0; #endif -bad: - Py_XDECREF(empty_list); - Py_XDECREF(py_import); - Py_XDECREF(empty_dict); - return module; -} - -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t val) { - const Py_intptr_t neg_one = (Py_intptr_t)-1, const_zero = (Py_intptr_t)0; - const int is_unsigned = const_zero < neg_one; - if ((sizeof(Py_intptr_t) == sizeof(char)) || - (sizeof(Py_intptr_t) == sizeof(short))) { - return PyInt_FromLong((long)val); - } else if ((sizeof(Py_intptr_t) == sizeof(int)) || - (sizeof(Py_intptr_t) == sizeof(long))) { - if (is_unsigned) - return PyLong_FromUnsignedLong((unsigned long)val); - else - return PyInt_FromLong((long)val); - } else if (sizeof(Py_intptr_t) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); - else - return PyLong_FromLongLong((PY_LONG_LONG)val); - } else { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), - little, !is_unsigned); + t = 1; + while (likely(e)) { + t *= (b * (e&1)) | ((~e)&1); /* 1 or b */ + b *= b; + e >>= 1; } + return t; } #if CYTHON_CCOMPLEX @@ -19380,432 +35224,108 @@ static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t val) { theta = atan2(a.imag, a.real); } lnr = log(r); - z_r = exp(lnr * b.real - theta * b.imag); - z_theta = theta * b.real + lnr * b.imag; - z.real = z_r * cos(z_theta); - z.imag = z_r * sin(z_theta); - return z; - } - #endif -#endif - -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; - } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; - } - return (unsigned short)val; - } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; - } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; - } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; - } - return (short)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; - } - return (signed char)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; - } - return (signed short)val; - } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; - } - return (signed int)val; - } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)PyLong_AsUnsignedLong(x); - } else { - return (unsigned long)PyLong_AsLong(x); - } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)PyLong_AsUnsignedLong(x); - } else { - return (long)PyLong_AsLong(x); - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)PyLong_AsUnsignedLong(x); - } else { - return (signed long)PyLong_AsLong(x); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; } - } else { - signed long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} + #endif +#endif -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; } - return (signed PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + goto raise_neg_overflow; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong(x)) } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong(x)) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; } } else { - signed PY_LONG_LONG val; + long val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } -} - -static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, - CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename) { - PyObject *old_exc, *old_val, *old_tb; - PyObject *ctx; - __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); - #if PY_MAJOR_VERSION < 3 - ctx = PyString_FromString(name); - #else - ctx = PyUnicode_FromString(name); - #endif - __Pyx_ErrRestore(old_exc, old_val, old_tb); - if (!ctx) { - PyErr_WriteUnraisable(Py_None); - } else { - PyErr_WriteUnraisable(ctx); - Py_DECREF(ctx); - } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; } static int __Pyx_check_binary_version(void) { @@ -19818,32 +35338,11 @@ static int __Pyx_check_binary_version(void) { "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); - #if PY_VERSION_HEX < 0x02050000 - return PyErr_Warn(NULL, message); - #else return PyErr_WarnEx(NULL, message, 1); - #endif } return 0; } -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItemString(dict, "__pyx_vtable__", ob) < 0) - goto bad; - Py_DECREF(ob); - return 0; -bad: - Py_XDECREF(ob); - return -1; -} - #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { @@ -19870,6 +35369,10 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; @@ -19885,23 +35388,31 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", + "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } - if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); - #if PY_VERSION_HEX < 0x02050000 - if (PyErr_Warn(NULL, warning) < 0) goto bad; - #else if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - #endif } - else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", + "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } @@ -19913,168 +35424,6 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = (start + end) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, /*int argcount,*/ - 0, /*int kwonlyargcount,*/ - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ - 0, /*int flags,*/ - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, /*int firstlineno,*/ - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_globals = 0; - PyFrameObject *py_frame = 0; - py_code = __pyx_find_code_object(c_line ? c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? c_line : py_line, py_code); - } - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_frame = PyFrame_New( - PyThreadState_GET(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - py_globals, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = py_line; - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 @@ -20085,7 +35434,7 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } - #else /* Python 3+ has unicode identifiers */ + #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); @@ -20105,27 +35454,88 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } - -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else + if (__Pyx_PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif + } else +#endif +#if !CYTHON_COMPILING_IN_PYPY + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -20141,13 +35551,13 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", + "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; @@ -20159,40 +35569,33 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { -#if PY_VERSION_HEX < 0x02050000 - if (ival <= LONG_MAX) - return PyInt_FromLong((long)ival); - else { - unsigned char *bytes = (unsigned char *) &ival; - int one = 1; int little = (int)*(unsigned char*)&one; - return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); - } -#else - return PyInt_FromSize_t(ival); -#endif -} - -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; + return PyInt_FromSize_t(ival); } diff --git a/sklearn/tree/_tree.pxd b/sklearn/tree/_tree.pxd index 311cda6d1483c..2256a10480648 100644 --- a/sklearn/tree/_tree.pxd +++ b/sklearn/tree/_tree.pxd @@ -1,123 +1,218 @@ -# Author: Peter Prettenhofer, Brian Holt, Gilles Louppe -# License: BSD Style. +# Authors: Gilles Louppe +# Peter Prettenhofer +# Brian Holt +# Joel Nothman +# Arnaud Joly +# +# Licence: BSD 3 clause # See _tree.pyx for details. +import numpy as np cimport numpy as np -ctypedef np.float32_t DTYPE_t -ctypedef np.float64_t DOUBLE_t -ctypedef np.int8_t BOOL_t +ctypedef np.npy_float32 DTYPE_t # Type of X +ctypedef np.npy_float64 DOUBLE_t # Type of y, sample_weight +ctypedef np.npy_intp SIZE_t # Type for indices and counters +ctypedef np.npy_int32 INT32_t # Signed 32 bit integer +ctypedef np.npy_uint32 UINT32_t # Unsigned 32 bit integer -# ============================================================================== +# ============================================================================= # Criterion -# ============================================================================== +# ============================================================================= cdef class Criterion: + # The criterion computes the impurity of a node and the reduction of + # impurity of a split on that node. It also computes the output statistics + # such as the mean in regression and class probabilities in classification. + + # Internal structures + cdef DOUBLE_t* y # Values of y + cdef SIZE_t y_stride # Stride in y (since n_outputs >= 1) + cdef DOUBLE_t* sample_weight # Sample weights + + cdef SIZE_t* samples # Sample indices in X, y + cdef SIZE_t start # samples[start:pos] are the samples in the left node + cdef SIZE_t pos # samples[pos:end] are the samples in the right node + cdef SIZE_t end + + cdef SIZE_t n_outputs # Number of outputs + cdef SIZE_t n_node_samples # Number of samples in the node (end-start) + cdef double weighted_n_samples # Weighted number of samples (in total) + cdef double weighted_n_node_samples # Weighted number of samples in the node + cdef double weighted_n_left # Weighted number of samples in the left node + cdef double weighted_n_right # Weighted number of samples in the right node + + # The criterion object is maintained such that left and right collected + # statistics correspond to samples[start:pos] and samples[pos:end]. + + # Methods + cdef void init(self, DOUBLE_t* y, SIZE_t y_stride, DOUBLE_t* sample_weight, + double weighted_n_samples, SIZE_t* samples, SIZE_t start, + SIZE_t end) nogil + cdef void reset(self) nogil + cdef void update(self, SIZE_t new_pos) nogil + cdef double node_impurity(self) nogil + cdef void children_impurity(self, double* impurity_left, + double* impurity_right) nogil + cdef void node_value(self, double* dest) nogil + cdef double impurity_improvement(self, double impurity) nogil + + +# ============================================================================= +# Splitter +# ============================================================================= + +cdef struct SplitRecord: + # Data to track sample split + SIZE_t feature # Which feature to split on. + SIZE_t pos # Split samples array at the given position, + # i.e. count of samples below threshold for feature. + # pos is >= end if the node is a leaf. + double threshold # Threshold to split at. + double improvement # Impurity improvement given parent node. + double impurity_left # Impurity of the left split. + double impurity_right # Impurity of the right split. + + +cdef class Splitter: + # The splitter searches in the input space for a feature and a threshold + # to split the samples samples[start:end]. + # + # The impurity computations are delegated to a criterion object. + + # Internal structures + cdef public Criterion criterion # Impurity criterion + cdef public SIZE_t max_features # Number of features to test + cdef public SIZE_t min_samples_leaf # Min samples in a leaf + cdef public double min_weight_leaf # Minimum weight in a leaf + + cdef object random_state # Random state + cdef UINT32_t rand_r_state # sklearn_rand_r random number state + + cdef SIZE_t* samples # Sample indices in X, y + cdef SIZE_t n_samples # X.shape[0] + cdef double weighted_n_samples # Weighted number of samples + cdef SIZE_t* features # Feature indices in X + cdef SIZE_t* constant_features # Constant features indices + cdef SIZE_t n_features # X.shape[1] + cdef DTYPE_t* feature_values # temp. array holding feature values + + cdef SIZE_t start # Start position for the current node + cdef SIZE_t end # End position for the current node + + cdef DOUBLE_t* y + cdef SIZE_t y_stride + cdef DOUBLE_t* sample_weight + + # The samples vector `samples` is maintained by the Splitter object such + # that the samples contained in a node are contiguous. With this setting, + # `node_split` reorganizes the node samples `samples[start:end]` in two + # subsets `samples[start:pos]` and `samples[pos:end]`. + + # The 1-d `features` array of size n_features contains the features + # indices and allows fast sampling without replacement of features. + + # The 1-d `constant_features` array of size n_features holds in + # `constant_features[:n_constant_features]` the feature ids with + # constant values for all the samples that reached a specific node. + # The value `n_constant_features` is given by the the parent node to its + # child nodes. The content of the range `[n_constant_features:]` is left + # undefined, but preallocated for performance reasons + # This allows optimization with depth-based tree building. + # Methods - cdef void init(self, DOUBLE_t* y, int y_stride, BOOL_t* sample_mask, - int n_samples, int n_total_samples) + cdef void init(self, object X, np.ndarray y, + DOUBLE_t* sample_weight) except * - cdef void reset(self) + cdef void node_reset(self, SIZE_t start, SIZE_t end, + double* weighted_n_node_samples) nogil - cdef int update(self, int a, int b, DOUBLE_t* y, int y_stride, - int* X_argsorted_i, BOOL_t* sample_mask) + cdef void node_split(self, + double impurity, # Impurity of the node + SplitRecord* split, + SIZE_t* n_constant_features) nogil - cdef double eval(self) + cdef void node_value(self, double* dest) nogil - cdef void init_value(self, double* buffer_value) + cdef double node_impurity(self) nogil -# ============================================================================== +# ============================================================================= # Tree -# ============================================================================== +# ============================================================================= + +cdef struct Node: + # Base storage structure for the nodes in a Tree object + + SIZE_t left_child # id of the left child of the node + SIZE_t right_child # id of the right child of the node + SIZE_t feature # Feature used for splitting the node + DOUBLE_t threshold # Threshold value at the node + DOUBLE_t impurity # Impurity of the node (i.e., the value of the criterion) + SIZE_t n_node_samples # Number of samples at the node + DOUBLE_t weighted_n_node_samples # Weighted number of samples at the node + cdef class Tree: + # The Tree object is a binary tree structure constructed by the + # TreeBuilder. The tree structure is used for predictions and + # feature importances. + # Input/Output layout - cdef public int n_features - cdef int* n_classes - cdef public int n_outputs - - cdef public int max_n_classes - cdef public int value_stride - - # Parameters - cdef public Criterion criterion - cdef public double max_depth - cdef public int min_samples_split - cdef public int min_samples_leaf - cdef public double min_density - cdef public int max_features - cdef public int find_split_algorithm - cdef public object random_state - - # Inner structures - cdef public int node_count - cdef public int capacity - cdef int* children_left - cdef int* children_right - cdef int* feature - cdef double* threshold - cdef double* value - cdef double* best_error - cdef double* init_error - cdef int* n_samples + cdef public SIZE_t n_features # Number of features in X + cdef SIZE_t* n_classes # Number of classes in y[:, k] + cdef public SIZE_t n_outputs # Number of outputs in y + cdef public SIZE_t max_n_classes # max(n_classes) + + # Inner structures: values are stored separately from node structure, + # since size is determined at runtime. + cdef public SIZE_t max_depth # Max depth of the tree + cdef public SIZE_t node_count # Counter for node IDs + cdef public SIZE_t capacity # Capacity of tree, in terms of nodes + cdef Node* nodes # Array of nodes + cdef double* value # (capacity, n_outputs, max_n_classes) array of values + cdef SIZE_t value_stride # = n_outputs * max_n_classes # Methods - cdef void resize(self, int capacity=*) - - cpdef build(self, np.ndarray X, np.ndarray y, - np.ndarray sample_mask=*, np.ndarray X_argsorted=*) - - cdef void recursive_partition(self, - np.ndarray[DTYPE_t, ndim=2, mode="fortran"] X, - np.ndarray[np.int32_t, ndim=2, mode="fortran"] X_argsorted, - np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, - np.ndarray sample_mask, - int n_node_samples, - int depth, - int parent, - int is_left_child, - double* buffer_value) - - cdef int add_split_node(self, int parent, int is_left_child, int feature, - double threshold, double* value, - double best_error, double init_error, - int n_samples) - - cdef int add_leaf(self, int parent, int is_left_child, double* value, - double error, int n_samples) - - cdef void find_split(self, DTYPE_t* X_ptr, int X_stride, - int* X_argsorted_ptr, int X_argsorted_stride, - DOUBLE_t* y_ptr, int y_stride, BOOL_t* sample_mask_ptr, - int n_node_samples, int n_total_samples, int* _best_i, - double* _best_t, double* _best_error, - double* _initial_error) - - cdef void find_best_split(self, DTYPE_t* X_ptr, int X_stride, - int* X_argsorted_ptr, int X_argsorted_stride, - DOUBLE_t* y_ptr, int y_stride, - BOOL_t* sample_mask_ptr, int n_node_samples, - int n_total_samples, int* _best_i, - double* _best_t, double* _best_error, - double* _initial_error) - - cdef void find_random_split(self, DTYPE_t* X_ptr, int X_stride, - int* X_argsorted_ptr, int X_argsorted_stride, - DOUBLE_t* y_ptr, int y_stride, - BOOL_t* sample_mask_ptr, int n_node_samples, - int n_total_samples, int* _best_i, - double* _best_t, double* _best_error, - double* _initial_error) - - cpdef predict(self, np.ndarray[DTYPE_t, ndim=2] X) - - cpdef apply(self, np.ndarray[DTYPE_t, ndim=2] X) - - cpdef compute_feature_importances(self, method=*) - - cdef inline double _compute_feature_importances_gini(self, int node) - - cdef inline double _compute_feature_importances_squared(self, int node) + 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_samples) nogil + cdef void _resize(self, SIZE_t capacity) except * + cdef int _resize_c(self, SIZE_t capacity=*) nogil + + cdef np.ndarray _get_value_ndarray(self) + cdef np.ndarray _get_node_ndarray(self) + + cpdef np.ndarray predict(self, object X) + cpdef np.ndarray apply(self, object X) + cdef np.ndarray _apply_dense(self, object X) + cdef np.ndarray _apply_sparse_csr(self, object X) + + cpdef compute_feature_importances(self, normalize=*) + + +# ============================================================================= +# Tree builder +# ============================================================================= + +cdef class TreeBuilder: + # The TreeBuilder recursively builds a Tree object from training samples, + # using a Splitter object for splitting internal nodes and assigning + # values to leaves. + # + # This class controls the various stopping criteria and the node splitting + # evaluation order, e.g. depth-first or best-first. + + cdef Splitter splitter # Splitting algorithm + + cdef SIZE_t min_samples_split # Minimum number of samples in an internal node + cdef SIZE_t min_samples_leaf # Minimum number of samples in a leaf + cdef double min_weight_leaf # Minimum weight in a leaf + cdef SIZE_t max_depth # Maximal tree depth + + cpdef build(self, Tree tree, object X, np.ndarray y, + np.ndarray sample_weight=*) + cdef _check_input(self, object X, np.ndarray y, np.ndarray sample_weight) diff --git a/sklearn/tree/_tree.pyx b/sklearn/tree/_tree.pyx index bf0a4f18b638f..6d6b609d4932e 100644 --- a/sklearn/tree/_tree.pyx +++ b/sklearn/tree/_tree.pyx @@ -1,1654 +1,3485 @@ -# encoding: utf-8 # cython: cdivision=True # cython: boundscheck=False # cython: wraparound=False -# -# Author: Peter Prettenhofer, Brian Holt, Gilles Louppe -# -# License: BSD Style. +# Authors: Gilles Louppe +# Peter Prettenhofer +# Brian Holt +# Noel Dawe +# Satrajit Gosh +# Lars Buitinck +# Arnaud Joly +# Joel Nothman +# Fares Hedayati +# +# Licence: BSD 3 clause -# ============================================================================== -# Imports -# ============================================================================== +from libc.stdlib cimport calloc, free, realloc, qsort -cimport cython +from libc.string cimport memcpy, memset +from libc.math cimport log as ln +from cpython cimport Py_INCREF, PyObject import numpy as np cimport numpy as np np.import_array() -cdef extern from "stdlib.h": - void* malloc(size_t size) - void* calloc(size_t nmemb, size_t size) - void* realloc(void* ptr, size_t size) - void free(void* ptr) +from scipy.sparse import issparse, csc_matrix, csr_matrix -cdef extern from "string.h": - void* memcpy(void* dest, void* src, size_t n) +from sklearn.tree._utils cimport Stack, StackRecord +from sklearn.tree._utils cimport PriorityHeap, PriorityHeapRecord -cdef extern from "math.h": - cdef extern double log(double x) - cdef extern double pow(double base, double exponent) -cdef extern from "float.h": - cdef extern double DBL_MAX +cdef extern from "numpy/arrayobject.h": + object PyArray_NewFromDescr(object subtype, np.dtype descr, + int nd, np.npy_intp* dims, + np.npy_intp* strides, + void* data, int flags, object obj) -# ============================================================================== +# ============================================================================= # Types and constants -# ============================================================================== +# ============================================================================= -# Dtype -DTYPE = np.float32 -DOUBLE = np.float64 -# ctypedef np.float32_t DTYPE_t -# ctypedef np.float64_t DOUBLE_t -# ctypedef np.int8_t BOOL_t +from numpy import float32 as DTYPE +from numpy import float64 as DOUBLE -# Constants cdef double INFINITY = np.inf - TREE_LEAF = -1 TREE_UNDEFINED = -2 -cdef int _TREE_LEAF = TREE_LEAF -cdef int _TREE_UNDEFINED = TREE_UNDEFINED +cdef SIZE_t _TREE_LEAF = TREE_LEAF +cdef SIZE_t _TREE_UNDEFINED = TREE_UNDEFINED +cdef SIZE_t INITIAL_STACK_SIZE = 10 + +cdef DTYPE_t MIN_IMPURITY_SPLIT = 1e-7 + +# Mitigate precision differences between 32 bit and 64 bit +cdef DTYPE_t FEATURE_THRESHOLD = 1e-7 + +# Constant to switch between algorithm non zero value extract algorithm +# in SparseSplitter +cdef DTYPE_t EXTRACT_NNZ_SWITCH = 0.1 + +# Some handy constants (BestFirstTreeBuilder) +cdef int IS_FIRST = 1 +cdef int IS_NOT_FIRST = 0 +cdef int IS_LEFT = 1 +cdef int IS_NOT_LEFT = 0 + +cdef enum: + # Max value for our rand_r replacement (near the bottom). + # We don't use RAND_MAX because it's different across platforms and + # particularly tiny on Windows/MSVC. + RAND_R_MAX = 0x7FFFFFFF + +# Repeat struct definition for numpy +NODE_DTYPE = np.dtype({ + 'names': ['left_child', 'right_child', 'feature', 'threshold', 'impurity', + 'n_node_samples', 'weighted_n_node_samples'], + 'formats': [np.intp, np.intp, np.intp, np.float64, np.float64, np.intp, + np.float64], + 'offsets': [ + &( NULL).left_child, + &( NULL).right_child, + &( NULL).feature, + &( NULL).threshold, + &( NULL).impurity, + &( NULL).n_node_samples, + &( NULL).weighted_n_node_samples + ] +}) + + +# ============================================================================= +# Criterion +# ============================================================================= -TREE_SPLIT_BEST = 1 -TREE_SPLIT_RANDOM = 2 -cdef int _TREE_SPLIT_BEST = TREE_SPLIT_BEST -cdef int _TREE_SPLIT_RANDOM = TREE_SPLIT_RANDOM +cdef class Criterion: + """Interface for impurity criteria.""" + cdef void init(self, DOUBLE_t* y, SIZE_t y_stride, DOUBLE_t* sample_weight, + double weighted_n_samples, SIZE_t* samples, SIZE_t start, + SIZE_t end) nogil: + """Initialize the criterion at node samples[start:end] and + children samples[start:start] and samples[start:end].""" + pass -# ============================================================================== -# Tree -# ============================================================================== + cdef void reset(self) nogil: + """Reset the criterion at pos=start.""" + pass -cdef class Tree: - """Struct-of-arrays representation of a binary decision tree. + cdef void update(self, SIZE_t new_pos) nogil: + """Update the collected statistics by moving samples[pos:new_pos] from + the right child to the left child.""" + pass - The binary tree is represented as a number of parallel arrays. - The i-th element of each array holds information about the - node `i`. You can find a detailed description of all arrays - below. NOTE: Some of the arrays only apply to either leaves or - split nodes, resp. In this case the values of nodes of the other - type are arbitrary! + cdef double node_impurity(self) nogil: + """Evaluate the impurity of the current node, i.e. the impurity of + samples[start:end].""" + pass - Parameters - ---------- - n_features : int - The number of features + cdef void children_impurity(self, double* impurity_left, + double* impurity_right) nogil: + """Evaluate the impurity in children nodes, i.e. the impurity of + samples[start:pos] + the impurity of samples[pos:end].""" + pass - n_classes : array-like - n_classes[k] is the number of classes for output k. + cdef void node_value(self, double* dest) nogil: + """Compute the node value of samples[start:end] into dest.""" + pass - n_outputs : int - The number of outputs. + cdef double impurity_improvement(self, double impurity) nogil: + """Weighted impurity improvement, i.e. - criterion : Criterion - max_depth : double - min_samples_split : int - min_samples_leaf : int - min_density : double - max_features : int - find_split_algorithm : int + N_t / N * (impurity - N_t_L / N_t * left impurity + - N_t_L / N_t * right impurity), - Attributes - ---------- - node_count : int - The number of nodes (internal nodes + leaves) in the tree. + where N is the total number of samples, N_t is the number of samples + in the current node, N_t_L is the number of samples in the left + child and N_t_R is the number of samples in the right child.""" + cdef double impurity_left + cdef double impurity_right - capacity : int - The current capacity (i.e., size) of the arrays. + self.children_impurity(&impurity_left, &impurity_right) - children_left : int* - children_left[i] holds the node id of the child if node i. - For leaves, children_left[i] == TREE_LEAF. + return ((self.weighted_n_node_samples / self.weighted_n_samples) * + (impurity - self.weighted_n_right / self.weighted_n_node_samples * impurity_right + - self.weighted_n_left / self.weighted_n_node_samples * impurity_left)) - children_right : int* - children_left[i] holds the node id of the child if node i. - For leaves, children_left[i] == TREE_LEAF. - feature : int* - feature[i] holds the feature to split on, for the internal node i. +cdef class ClassificationCriterion(Criterion): + """Abstract criterion for classification.""" + cdef SIZE_t* n_classes + cdef SIZE_t label_count_stride + cdef double* label_count_left + cdef double* label_count_right + cdef double* label_count_total + + def __cinit__(self, SIZE_t n_outputs, + np.ndarray[SIZE_t, ndim=1] n_classes): + # Default values + self.y = NULL + self.y_stride = 0 + self.sample_weight = NULL + + self.samples = NULL + self.start = 0 + self.pos = 0 + self.end = 0 - threshold : double* - threshold[i] holds the threshold for the internal node i. + self.n_outputs = n_outputs + self.n_node_samples = 0 + self.weighted_n_node_samples = 0.0 + self.weighted_n_left = 0.0 + self.weighted_n_right = 0.0 - value : double* - Contains the constant prediction value of each node. + self.label_count_left = NULL + self.label_count_right = NULL + self.label_count_total = NULL + + # Count labels for each output + self.n_classes = NULL + safe_realloc(&self.n_classes, n_outputs) + + cdef SIZE_t k = 0 + cdef SIZE_t label_count_stride = 0 + + for k in range(n_outputs): + self.n_classes[k] = n_classes[k] + + if n_classes[k] > label_count_stride: + label_count_stride = n_classes[k] + + self.label_count_stride = label_count_stride + + # Allocate counters + cdef SIZE_t n_elements = n_outputs * label_count_stride + self.label_count_left = calloc(n_elements, sizeof(double)) + self.label_count_right = calloc(n_elements, sizeof(double)) + self.label_count_total = calloc(n_elements, sizeof(double)) + + # Check for allocation errors + if (self.label_count_left == NULL or + self.label_count_right == NULL or + self.label_count_total == NULL): + raise MemoryError() + + def __dealloc__(self): + """Destructor.""" + free(self.n_classes) + free(self.label_count_left) + free(self.label_count_right) + free(self.label_count_total) + + def __reduce__(self): + return (ClassificationCriterion, + (self.n_outputs, + sizet_ptr_to_ndarray(self.n_classes, self.n_outputs)), + self.__getstate__()) + + def __getstate__(self): + return {} + + def __setstate__(self, d): + pass + + cdef void init(self, DOUBLE_t* y, SIZE_t y_stride, + DOUBLE_t* sample_weight, double weighted_n_samples, + SIZE_t* samples, SIZE_t start, SIZE_t end) nogil: + """Initialize the criterion at node samples[start:end] and + children samples[start:start] and samples[start:end].""" + # Initialize fields + self.y = y + self.y_stride = y_stride + self.sample_weight = sample_weight + self.samples = samples + self.start = start + self.end = end + self.n_node_samples = end - start + self.weighted_n_samples = weighted_n_samples + cdef double weighted_n_node_samples = 0.0 + + # Initialize label_count_total and weighted_n_node_samples + cdef SIZE_t n_outputs = self.n_outputs + cdef SIZE_t* n_classes = self.n_classes + cdef SIZE_t label_count_stride = self.label_count_stride + cdef double* label_count_total = self.label_count_total + + cdef SIZE_t i = 0 + cdef SIZE_t p = 0 + cdef SIZE_t k = 0 + cdef SIZE_t c = 0 + cdef DOUBLE_t w = 1.0 + cdef SIZE_t offset = 0 + + for k in range(n_outputs): + memset(label_count_total + offset, 0, + n_classes[k] * sizeof(double)) + offset += label_count_stride + + for p in range(start, end): + i = samples[p] + + if sample_weight != NULL: + w = sample_weight[i] + + for k in range(n_outputs): + c = y[i * y_stride + k] + label_count_total[k * label_count_stride + c] += w + + weighted_n_node_samples += w + + self.weighted_n_node_samples = weighted_n_node_samples + + # Reset to pos=start + self.reset() + + cdef void reset(self) nogil: + """Reset the criterion at pos=start.""" + self.pos = self.start + + self.weighted_n_left = 0.0 + self.weighted_n_right = self.weighted_n_node_samples + + cdef SIZE_t n_outputs = self.n_outputs + cdef SIZE_t* n_classes = self.n_classes + cdef SIZE_t label_count_stride = self.label_count_stride + cdef double* label_count_total = self.label_count_total + cdef double* label_count_left = self.label_count_left + cdef double* label_count_right = self.label_count_right + + cdef SIZE_t k = 0 + + for k in range(n_outputs): + memset(label_count_left, 0, n_classes[k] * sizeof(double)) + memcpy(label_count_right, label_count_total, + n_classes[k] * sizeof(double)) + + label_count_total += label_count_stride + label_count_left += label_count_stride + label_count_right += label_count_stride + + cdef void update(self, SIZE_t new_pos) nogil: + """Update the collected statistics by moving samples[pos:new_pos] from + the right child to the left child.""" + cdef DOUBLE_t* y = self.y + cdef SIZE_t y_stride = self.y_stride + cdef DOUBLE_t* sample_weight = self.sample_weight + + cdef SIZE_t* samples = self.samples + cdef SIZE_t pos = self.pos + + cdef SIZE_t n_outputs = self.n_outputs + cdef SIZE_t* n_classes = self.n_classes + cdef SIZE_t label_count_stride = self.label_count_stride + cdef double* label_count_total = self.label_count_total + cdef double* label_count_left = self.label_count_left + cdef double* label_count_right = self.label_count_right + + cdef SIZE_t i + cdef SIZE_t p + cdef SIZE_t k + cdef SIZE_t label_index + cdef DOUBLE_t w = 1.0 + cdef DOUBLE_t diff_w = 0.0 + + # Note: We assume start <= pos < new_pos <= end + + for p in range(pos, new_pos): + i = samples[p] + + if sample_weight != NULL: + w = sample_weight[i] + + for k in range(n_outputs): + label_index = (k * label_count_stride + + y[i * y_stride + k]) + label_count_left[label_index] += w + label_count_right[label_index] -= w + + diff_w += w + + self.weighted_n_left += diff_w + self.weighted_n_right -= diff_w + + self.pos = new_pos + + cdef double node_impurity(self) nogil: + pass + + cdef void children_impurity(self, double* impurity_left, + double* impurity_right) nogil: + pass + + cdef void node_value(self, double* dest) nogil: + """Compute the node value of samples[start:end] into dest.""" + cdef SIZE_t n_outputs = self.n_outputs + cdef SIZE_t* n_classes = self.n_classes + cdef SIZE_t label_count_stride = self.label_count_stride + cdef double* label_count_total = self.label_count_total + cdef SIZE_t k - best_error : double* - best_error[i] holds the error of the (best) split at node i. - For leaves init_error[i] == best_error[i]. + for k in range(n_outputs): + memcpy(dest, label_count_total, n_classes[k] * sizeof(double)) + dest += label_count_stride + label_count_total += label_count_stride - init_error : double* - init_error[i] holds the initial error at node i (before splitting). - For leaves init_error[i] == best_error[i]. - n_samples : int* - n_samples[i] holds the number of training samples reaching node i. +cdef class Entropy(ClassificationCriterion): + """Cross Entropy impurity criteria. + + Let the target be a classification outcome taking values in 0, 1, ..., K-1. + If node m represents a region Rm with Nm observations, then let + + pmk = 1/ Nm \sum_{x_i in Rm} I(yi = k) + + be the proportion of class k observations in node m. + + The cross-entropy is then defined as + + cross-entropy = - \sum_{k=0}^{K-1} pmk log(pmk) """ + cdef double node_impurity(self) nogil: + """Evaluate the impurity of the current node, i.e. the impurity of + samples[start:end].""" + cdef double weighted_n_node_samples = self.weighted_n_node_samples - # # Input/Output layout - # cdef public int n_features - # cdef int* n_classes - # cdef public int n_outputs - - # cdef public int max_n_classes - # cdef public int value_stride - - # # Parameters - # cdef public Criterion criterion - # cdef public double max_depth - # cdef public int min_samples_split - # cdef public int min_samples_leaf - # cdef public double min_density - # cdef public int max_features - # cdef public int find_split_algorithm - # cdef public object random_state - - # # Inner structures - # cdef public int node_count - # cdef public int capacity - # cdef int* children_left - # cdef int* children_right - # cdef int* feature - # cdef double* threshold - # cdef double* value - # cdef double* best_error - # cdef double* init_error - # cdef int* n_samples - - # Wrap for outside world - property n_classes: - def __get__(self): - return intp_to_ndarray(self.n_classes, self.n_outputs) + cdef SIZE_t n_outputs = self.n_outputs + cdef SIZE_t* n_classes = self.n_classes + cdef SIZE_t label_count_stride = self.label_count_stride + cdef double* label_count_total = self.label_count_total - property children_left: - def __get__(self): - return intp_to_ndarray(self.children_left, self.node_count) + cdef double entropy = 0.0 + cdef double total = 0.0 + cdef double tmp + cdef SIZE_t k + cdef SIZE_t c - property children_right: - def __get__(self): - return intp_to_ndarray(self.children_right, self.node_count) + for k in range(n_outputs): + entropy = 0.0 - property feature: - def __get__(self): - return intp_to_ndarray(self.feature, self.node_count) + for c in range(n_classes[k]): + tmp = label_count_total[c] + if tmp > 0.0: + tmp /= weighted_n_node_samples + entropy -= tmp * log(tmp) - property threshold: - def __get__(self): - return doublep_to_ndarray(self.threshold, self.node_count) + total += entropy + label_count_total += label_count_stride - property value: - def __get__(self): - cdef np.npy_intp shape[3] - shape[0] = self.node_count - shape[1] = self.n_outputs - shape[2] = self.max_n_classes - return np.PyArray_SimpleNewFromData(3, shape, np.NPY_DOUBLE, self.value) + return total / n_outputs - property best_error: - def __get__(self): - return doublep_to_ndarray(self.best_error, self.node_count) + cdef void children_impurity(self, double* impurity_left, + double* impurity_right) nogil: + """Evaluate the impurity in children nodes, i.e. the impurity of the + left child (samples[start:pos]) and the impurity the right child + (samples[pos:end]).""" + cdef double weighted_n_node_samples = self.weighted_n_node_samples + cdef double weighted_n_left = self.weighted_n_left + cdef double weighted_n_right = self.weighted_n_right + + cdef SIZE_t n_outputs = self.n_outputs + cdef SIZE_t* n_classes = self.n_classes + cdef SIZE_t label_count_stride = self.label_count_stride + cdef double* label_count_left = self.label_count_left + cdef double* label_count_right = self.label_count_right + + cdef double entropy_left = 0.0 + cdef double entropy_right = 0.0 + cdef double total_left = 0.0 + cdef double total_right = 0.0 + cdef double tmp + cdef SIZE_t k + cdef SIZE_t c + + for k in range(n_outputs): + entropy_left = 0.0 + entropy_right = 0.0 + + for c in range(n_classes[k]): + tmp = label_count_left[c] + if tmp > 0.0: + tmp /= weighted_n_left + entropy_left -= tmp * log(tmp) + + tmp = label_count_right[c] + if tmp > 0.0: + tmp /= weighted_n_right + entropy_right -= tmp * log(tmp) + + total_left += entropy_left + total_right += entropy_right + label_count_left += label_count_stride + label_count_right += label_count_stride + + impurity_left[0] = total_left / n_outputs + impurity_right[0] = total_right / n_outputs - property init_error: - def __get__(self): - return doublep_to_ndarray(self.init_error, self.node_count) - property n_samples: - def __get__(self): - return intp_to_ndarray(self.n_samples, self.node_count) +cdef class Gini(ClassificationCriterion): + """Gini Index impurity criteria. - def __cinit__(self, int n_features, object n_classes, int n_outputs, - Criterion criterion, double max_depth, int min_samples_split, - int min_samples_leaf, double min_density, int max_features, - int find_split_algorithm, object random_state): - """Constructor.""" - # Input/Output layout - cdef int k + Let the target be a classification outcome taking values in 0, 1, ..., K-1. + If node m represents a region Rm with Nm observations, then let - self.n_features = n_features - self.n_outputs = n_outputs - self.n_classes = malloc(n_outputs * sizeof(int)) + pmk = 1/ Nm \sum_{x_i in Rm} I(yi = k) - if self.n_classes == NULL: - raise MemoryError() + be the proportion of class k observations in node m. - self.max_n_classes = np.max(n_classes) - self.value_stride = self.n_outputs * self.max_n_classes + The Gini Index is then defined as: - for k from 0 <= k < n_outputs: - self.n_classes[k] = n_classes[k] + index = \sum_{k=0}^{K-1} pmk (1 - pmk) + = 1 - \sum_{k=0}^{K-1} pmk ** 2 + """ + cdef double node_impurity(self) nogil: + """Evaluate the impurity of the current node, i.e. the impurity of + samples[start:end].""" + cdef double weighted_n_node_samples = self.weighted_n_node_samples - # Parameters - self.criterion = criterion - self.max_depth = max_depth - self.min_samples_split = min_samples_split - self.min_samples_leaf = min_samples_leaf - self.min_density = min_density - self.max_features = max_features - self.find_split_algorithm = find_split_algorithm - self.random_state = random_state + cdef SIZE_t n_outputs = self.n_outputs + cdef SIZE_t* n_classes = self.n_classes + cdef SIZE_t label_count_stride = self.label_count_stride + cdef double* label_count_total = self.label_count_total - # Inner structures - self.node_count = 0 - self.capacity = 0 + cdef double gini = 0.0 + cdef double total = 0.0 + cdef double tmp + cdef SIZE_t k + cdef SIZE_t c - self.children_left = NULL - self.children_right = NULL - self.feature = NULL - self.threshold = NULL - self.value = NULL - self.best_error = NULL - self.init_error = NULL - self.n_samples = NULL + for k in range(n_outputs): + gini = 0.0 + + for c in range(n_classes[k]): + tmp = label_count_total[c] + gini += tmp * tmp + + gini = 1.0 - gini / (weighted_n_node_samples * + weighted_n_node_samples) + + total += gini + label_count_total += label_count_stride + + return total / n_outputs + + cdef void children_impurity(self, double* impurity_left, + double* impurity_right) nogil: + """Evaluate the impurity in children nodes, i.e. the impurity of the + left child (samples[start:pos]) and the impurity the right child + (samples[pos:end]).""" + cdef double weighted_n_node_samples = self.weighted_n_node_samples + cdef double weighted_n_left = self.weighted_n_left + cdef double weighted_n_right = self.weighted_n_right + + cdef SIZE_t n_outputs = self.n_outputs + cdef SIZE_t* n_classes = self.n_classes + cdef SIZE_t label_count_stride = self.label_count_stride + cdef double* label_count_left = self.label_count_left + cdef double* label_count_right = self.label_count_right + + cdef double gini_left = 0.0 + cdef double gini_right = 0.0 + cdef double total = 0.0 + cdef double total_left = 0.0 + cdef double total_right = 0.0 + cdef double tmp + cdef SIZE_t k + cdef SIZE_t c + + for k in range(n_outputs): + gini_left = 0.0 + gini_right = 0.0 + + for c in range(n_classes[k]): + tmp = label_count_left[c] + gini_left += tmp * tmp + tmp = label_count_right[c] + gini_right += tmp * tmp + + gini_left = 1.0 - gini_left / (weighted_n_left * + weighted_n_left) + gini_right = 1.0 - gini_right / (weighted_n_right * + weighted_n_right) + + total_left += gini_left + total_right += gini_right + label_count_left += label_count_stride + label_count_right += label_count_stride + + impurity_left[0] = total_left / n_outputs + impurity_right[0] = total_right / n_outputs + + +cdef class RegressionCriterion(Criterion): + """Abstract criterion for regression. + + Computes variance of the target values left and right of the split point. + Computation is linear in `n_samples` by using :: + + var = \sum_i^n (y_i - y_bar) ** 2 + = (\sum_i^n y_i ** 2) - n_samples y_bar ** 2 + """ + cdef double* mean_left + cdef double* mean_right + cdef double* mean_total + cdef double* sq_sum_left + cdef double* sq_sum_right + cdef double* sq_sum_total + cdef double* var_left + cdef double* var_right + cdef double* sum_left + cdef double* sum_right + cdef double* sum_total + + def __cinit__(self, SIZE_t n_outputs): + # Default values + self.y = NULL + self.y_stride = 0 + self.sample_weight = NULL + + self.samples = NULL + self.start = 0 + self.pos = 0 + self.end = 0 + + self.n_outputs = n_outputs + self.n_node_samples = 0 + self.weighted_n_node_samples = 0.0 + self.weighted_n_left = 0.0 + self.weighted_n_right = 0.0 + + # Allocate accumulators. Make sure they are NULL, not uninitialized, + # before an exception can be raised (which triggers __dealloc__). + self.mean_left = NULL + self.mean_right = NULL + self.mean_total = NULL + self.sq_sum_left = NULL + self.sq_sum_right = NULL + self.sq_sum_total = NULL + self.var_left = NULL + self.var_right = NULL + self.sum_left = NULL + self.sum_right = NULL + self.sum_total = NULL + + self.mean_left = calloc(n_outputs, sizeof(double)) + self.mean_right = calloc(n_outputs, sizeof(double)) + self.mean_total = calloc(n_outputs, sizeof(double)) + self.sq_sum_left = calloc(n_outputs, sizeof(double)) + self.sq_sum_right = calloc(n_outputs, sizeof(double)) + self.sq_sum_total = calloc(n_outputs, sizeof(double)) + self.var_left = calloc(n_outputs, sizeof(double)) + self.var_right = calloc(n_outputs, sizeof(double)) + self.sum_left = calloc(n_outputs, sizeof(double)) + self.sum_right = calloc(n_outputs, sizeof(double)) + self.sum_total = calloc(n_outputs, sizeof(double)) + + if (self.mean_left == NULL or + self.mean_right == NULL or + self.mean_total == NULL or + self.sq_sum_left == NULL or + self.sq_sum_right == NULL or + self.sq_sum_total == NULL or + self.var_left == NULL or + self.var_right == NULL or + self.sum_left == NULL or + self.sum_right == NULL or + self.sum_total == NULL): + raise MemoryError() def __dealloc__(self): """Destructor.""" - # Free all inner structures - free(self.n_classes) - free(self.children_left) - free(self.children_right) - free(self.feature) - free(self.threshold) - free(self.value) - free(self.best_error) - free(self.init_error) - free(self.n_samples) + free(self.mean_left) + free(self.mean_right) + free(self.mean_total) + free(self.sq_sum_left) + free(self.sq_sum_right) + free(self.sq_sum_total) + free(self.var_left) + free(self.var_right) + free(self.sum_left) + free(self.sum_right) + free(self.sum_total) def __reduce__(self): - """Reduce re-implementation, for pickling.""" - return (Tree, (self.n_features, - intp_to_ndarray(self.n_classes, self.n_outputs), - self.n_outputs, - self.criterion, - self.max_depth, - self.min_samples_split, - self.min_samples_leaf, - self.min_density, - self.max_features, - self.find_split_algorithm, - self.random_state), self.__getstate__()) + return (RegressionCriterion, (self.n_outputs,), self.__getstate__()) def __getstate__(self): - """Getstate re-implementation, for pickling.""" - d = {} + return {} - d["node_count"] = self.node_count - d["capacity"] = self.capacity - d["children_left"] = intp_to_ndarray(self.children_left, self.capacity) - d["children_right"] = intp_to_ndarray(self.children_right, self.capacity) - d["feature"] = intp_to_ndarray(self.feature, self.capacity) - d["threshold"] = doublep_to_ndarray(self.threshold, self.capacity) - d["value"] = doublep_to_ndarray(self.value, self.capacity * self.value_stride) - d["best_error"] = doublep_to_ndarray(self.best_error, self.capacity) - d["init_error"] = doublep_to_ndarray(self.init_error, self.capacity) - d["n_samples"] = intp_to_ndarray(self.n_samples, self.capacity) + def __setstate__(self, d): + pass - return d + cdef void init(self, DOUBLE_t* y, SIZE_t y_stride, DOUBLE_t* sample_weight, + double weighted_n_samples, SIZE_t* samples, SIZE_t start, + SIZE_t end) nogil: + """Initialize the criterion at node samples[start:end] and + children samples[start:start] and samples[start:end].""" + # Initialize fields + self.y = y + self.y_stride = y_stride + self.sample_weight = sample_weight + self.samples = samples + self.start = start + self.end = end + self.n_node_samples = end - start + self.weighted_n_samples = weighted_n_samples + cdef double weighted_n_node_samples = 0. + + # Initialize accumulators + cdef SIZE_t n_outputs = self.n_outputs + cdef double* mean_left = self.mean_left + cdef double* mean_right = self.mean_right + cdef double* mean_total = self.mean_total + cdef double* sq_sum_left = self.sq_sum_left + cdef double* sq_sum_right = self.sq_sum_right + cdef double* sq_sum_total = self.sq_sum_total + cdef double* var_left = self.var_left + cdef double* var_right = self.var_right + cdef double* sum_left = self.sum_left + cdef double* sum_right = self.sum_right + cdef double* sum_total = self.sum_total + + cdef SIZE_t i = 0 + cdef SIZE_t p = 0 + cdef SIZE_t k = 0 + cdef DOUBLE_t y_ik = 0.0 + cdef DOUBLE_t w_y_ik = 0.0 + cdef DOUBLE_t w = 1.0 + + cdef SIZE_t n_bytes = n_outputs * sizeof(double) + memset(mean_left, 0, n_bytes) + memset(mean_right, 0, n_bytes) + memset(mean_total, 0, n_bytes) + memset(sq_sum_left, 0, n_bytes) + memset(sq_sum_right, 0, n_bytes) + memset(sq_sum_total, 0, n_bytes) + memset(var_left, 0, n_bytes) + memset(var_right, 0, n_bytes) + memset(sum_left, 0, n_bytes) + memset(sum_right, 0, n_bytes) + memset(sum_total, 0, n_bytes) + + for p in range(start, end): + i = samples[p] + + if sample_weight != NULL: + w = sample_weight[i] + + for k in range(n_outputs): + y_ik = y[i * y_stride + k] + w_y_ik = w * y_ik + sum_total[k] += w_y_ik + sq_sum_total[k] += w_y_ik * y_ik + + weighted_n_node_samples += w + + self.weighted_n_node_samples = weighted_n_node_samples + + for k in range(n_outputs): + mean_total[k] = sum_total[k] / weighted_n_node_samples + + # Reset to pos=start + self.reset() - def __setstate__(self, d): - """Setstate re-implementation, for unpickling.""" - self.resize(d["capacity"]) - self.node_count = d["node_count"] + cdef void reset(self) nogil: + """Reset the criterion at pos=start.""" + self.pos = self.start - cdef int* children_left = ( d["children_left"]).data - cdef int* children_right = ( d["children_right"]).data - cdef int* feature = ( d["feature"]).data - cdef double* threshold = ( d["threshold"]).data - cdef double* value = ( d["value"]).data - cdef double* best_error = ( d["best_error"]).data - cdef double* init_error = ( d["init_error"]).data - cdef int* n_samples = ( d["n_samples"]).data - - memcpy(self.children_left, children_left, self.capacity * sizeof(int)) - memcpy(self.children_right, children_right, self.capacity * sizeof(int)) - memcpy(self.feature, feature, self.capacity * sizeof(int)) - memcpy(self.threshold, threshold, self.capacity * sizeof(double)) - memcpy(self.value, value, self.capacity * self.value_stride * sizeof(double)) - memcpy(self.best_error, best_error, self.capacity * sizeof(double)) - memcpy(self.init_error, init_error, self.capacity * sizeof(double)) - memcpy(self.n_samples, n_samples, self.capacity * sizeof(int)) - - cdef void resize(self, int capacity=-1): - """Resize all inner arrays to `capacity`, if < 0 double capacity.""" - if capacity == self.capacity: - return + self.weighted_n_left = 0.0 + self.weighted_n_right = self.weighted_n_node_samples - if capacity < 0: - if self.capacity <= 0: - capacity = 3 # default initial value - else: - capacity = 2 * self.capacity + cdef SIZE_t n_outputs = self.n_outputs + cdef double* mean_left = self.mean_left + cdef double* mean_right = self.mean_right + cdef double* mean_total = self.mean_total + cdef double* sq_sum_left = self.sq_sum_left + cdef double* sq_sum_right = self.sq_sum_right + cdef double* sq_sum_total = self.sq_sum_total + cdef double* var_left = self.var_left + cdef double* var_right = self.var_right + cdef double weighted_n_node_samples = self.weighted_n_node_samples + cdef double* sum_left = self.sum_left + cdef double* sum_right = self.sum_right + cdef double* sum_total = self.sum_total - self.capacity = capacity + cdef SIZE_t k = 0 - cdef int* tmp_children_left = realloc(self.children_left, capacity * sizeof(int)) - if tmp_children_left != NULL: self.children_left = tmp_children_left + for k in range(n_outputs): + mean_right[k] = mean_total[k] + mean_left[k] = 0.0 + sq_sum_right[k] = sq_sum_total[k] + sq_sum_left[k] = 0.0 + var_right[k] = (sq_sum_right[k] / weighted_n_node_samples - + mean_right[k] * mean_right[k]) + var_left[k] = 0.0 + sum_right[k] = sum_total[k] + sum_left[k] = 0.0 - cdef int* tmp_children_right = realloc(self.children_right, capacity * sizeof(int)) - if tmp_children_right != NULL: self.children_right = tmp_children_right + cdef void update(self, SIZE_t new_pos) nogil: + """Update the collected statistics by moving samples[pos:new_pos] from + the right child to the left child.""" + cdef DOUBLE_t* y = self.y + cdef SIZE_t y_stride = self.y_stride + cdef DOUBLE_t* sample_weight = self.sample_weight - cdef int* tmp_feature = realloc(self.feature, capacity * sizeof(int)) - if tmp_feature != NULL: self.feature = tmp_feature + cdef SIZE_t* samples = self.samples + cdef SIZE_t pos = self.pos - cdef double* tmp_threshold = realloc(self.threshold, capacity * sizeof(double)) - if tmp_threshold != NULL: self.threshold = tmp_threshold + cdef SIZE_t n_outputs = self.n_outputs + cdef double* mean_left = self.mean_left + cdef double* mean_right = self.mean_right + cdef double* sq_sum_left = self.sq_sum_left + cdef double* sq_sum_right = self.sq_sum_right + cdef double* var_left = self.var_left + cdef double* var_right = self.var_right + cdef double* sum_left = self.sum_left + cdef double* sum_right = self.sum_right - cdef double* tmp_value = realloc(self.value, capacity * self.value_stride * sizeof(double)) - if tmp_value != NULL: self.value = tmp_value + cdef double weighted_n_left = self.weighted_n_left + cdef double weighted_n_right = self.weighted_n_right - cdef double* tmp_best_error = realloc(self.best_error, capacity * sizeof(double)) - if tmp_best_error != NULL: self.best_error = tmp_best_error + cdef SIZE_t i + cdef SIZE_t p + cdef SIZE_t k + cdef DOUBLE_t w = 1.0 + cdef DOUBLE_t diff_w = 0.0 + cdef DOUBLE_t y_ik, w_y_ik - cdef double* tmp_init_error = realloc(self.init_error, capacity * sizeof(double)) - if tmp_init_error != NULL: self.init_error = tmp_init_error + # Note: We assume start <= pos < new_pos <= end + for p in range(pos, new_pos): + i = samples[p] - cdef int* tmp_n_samples = realloc(self.n_samples, capacity * sizeof(int)) - if tmp_n_samples != NULL: self.n_samples = tmp_n_samples + if sample_weight != NULL: + w = sample_weight[i] - if tmp_children_left == NULL or \ - tmp_children_right == NULL or \ - tmp_feature == NULL or \ - tmp_threshold == NULL or \ - tmp_value == NULL or \ - tmp_best_error == NULL or \ - tmp_init_error == NULL or \ - tmp_n_samples == NULL: - raise MemoryError() + for k in range(n_outputs): + y_ik = y[i * y_stride + k] + w_y_ik = w * y_ik - # if capacity smaller than node_count, adjust the counter - if capacity < self.node_count: - self.node_count = capacity + sum_left[k] += w_y_ik + sum_right[k] -= w_y_ik - cpdef build(self, np.ndarray X, np.ndarray y, - np.ndarray sample_mask=None, np.ndarray X_argsorted=None): - """Build a decision tree from the training set (X, y). + sq_sum_left[k] += w_y_ik * y_ik + sq_sum_right[k] -= w_y_ik * y_ik - Parameters - ---------- - X : ndarray of shape [n_samples, n_features] - The training input samples. + diff_w += w - y : ndarray of shape [n_samples, n_outputs] - The target values. - """ - # Check input before recursive partitioning - if X.dtype != DTYPE or not np.isfortran(X): - X = np.asarray(X, dtype=DTYPE, order="F") + weighted_n_left += diff_w + weighted_n_right -= diff_w - if y.dtype != DOUBLE or not y.flags.contiguous: - y = np.asarray(y, dtype=DOUBLE, order="C") + for k in range(n_outputs): + mean_left[k] = sum_left[k] / weighted_n_left + mean_right[k] = sum_right[k] / weighted_n_right + var_left[k] = (sq_sum_left[k] / weighted_n_left - + mean_left[k] * mean_left[k]) + var_right[k] = (sq_sum_right[k] / weighted_n_right - + mean_right[k] * mean_right[k]) - if sample_mask is None: - sample_mask = np.ones((X.shape[0],), dtype=np.bool) + self.weighted_n_left = weighted_n_left + self.weighted_n_right = weighted_n_right - if X_argsorted is None: - X_argsorted = np.asfortranarray( - np.argsort(X.T, axis=1).astype(np.int32).T) + self.pos = new_pos - # Pre-allocate some space - cdef int init_capacity + cdef double node_impurity(self) nogil: + pass - if self.max_depth <= 10: - init_capacity = (2 ** (int(self.max_depth) + 1)) - 1 - else: - init_capacity = 2047 + cdef void children_impurity(self, double* impurity_left, + double* impurity_right) nogil: + pass - self.resize(init_capacity) - cdef double* buffer_value = malloc(self.value_stride * sizeof(double)) - - # Build the tree by recursive partitioning - self.recursive_partition(X, X_argsorted, y, sample_mask, np.sum(sample_mask), 0, -1, False, buffer_value) - - # Compactify - self.resize(self.node_count) - free(buffer_value) - - cdef void recursive_partition(self, - np.ndarray[DTYPE_t, ndim=2, mode="fortran"] X, - np.ndarray[np.int32_t, ndim=2, mode="fortran"] X_argsorted, - np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, - np.ndarray sample_mask, - int n_node_samples, - int depth, - int parent, - int is_left_child, - double* buffer_value): - """Recursive partition algorithm for the tree construction.""" - # Variables - cdef Criterion criterion = self.criterion - - cdef DTYPE_t* X_ptr = X.data - cdef int* X_argsorted_ptr = X_argsorted.data - cdef DOUBLE_t* y_ptr = y.data - cdef BOOL_t* sample_mask_ptr = sample_mask.data - - cdef int X_stride = X.strides[1] / X.strides[0] - cdef int X_argsorted_stride = X_argsorted.strides[1] / X_argsorted.strides[0] - cdef int y_stride = y.strides[0] / y.strides[1] - - cdef int n_total_samples = y.shape[0] - cdef int feature - cdef double threshold - cdef double best_error - cdef double init_error - - cdef int i - cdef np.ndarray sample_mask_left - cdef np.ndarray sample_mask_right - cdef int n_node_samples_left - cdef int n_node_samples_right - - # Count samples - if n_node_samples == 0: - raise ValueError("Attempting to find a split " - "with an empty sample_mask") - - # Split samples - if depth < self.max_depth and \ - n_node_samples >= self.min_samples_split and \ - n_node_samples >= 2 * self.min_samples_leaf: - self.find_split(X_ptr, X_stride, - X_argsorted_ptr, X_argsorted_stride, - y_ptr, y_stride, - sample_mask_ptr, - n_node_samples, - n_total_samples, - &feature, &threshold, &best_error, &init_error) + cdef void node_value(self, double* dest) nogil: + """Compute the node value of samples[start:end] into dest.""" + memcpy(dest, self.mean_total, self.n_outputs * sizeof(double)) - else: - feature = -1 - criterion.init(y_ptr, y_stride, sample_mask_ptr, n_node_samples, n_total_samples) - init_error = criterion.eval() - criterion.init_value(buffer_value) +cdef class MSE(RegressionCriterion): + """Mean squared error impurity criterion. - # Current node is leaf - if feature == -1: - self.add_leaf(parent, is_left_child, buffer_value, init_error, n_node_samples) + MSE = var_left + var_right + """ + cdef double node_impurity(self) nogil: + """Evaluate the impurity of the current node, i.e. the impurity of + samples[start:end].""" + cdef SIZE_t n_outputs = self.n_outputs + cdef double* sq_sum_total = self.sq_sum_total + cdef double* mean_total = self.mean_total + cdef double weighted_n_node_samples = self.weighted_n_node_samples + cdef double total = 0.0 + cdef SIZE_t k - # Current node is internal node (= split node) - else: - # Sample mask is too sparse? - if 1. * n_node_samples / n_total_samples <= self.min_density: - X = X[sample_mask] - X_argsorted = np.asfortranarray(np.argsort(X.T, axis=1).astype(np.int32).T) - y = y[sample_mask] - sample_mask = np.ones((n_node_samples, ), dtype=np.bool) - - n_total_samples = n_node_samples - - X_ptr = X.data - X_stride = X.strides[1] / X.strides[0] - sample_mask_ptr = sample_mask.data - - # !! No need to update the other variables - # X_argsorted_ptr = X_argsorted.data - # y_ptr = y.data - # X_argsorted_stride = X_argsorted.strides[1] / X_argsorted.strides[0] - # y_stride = y.strides[0] / y.strides[1] - - # Split - X_ptr = X_ptr + feature * X_stride - sample_mask_left = np.zeros((n_total_samples, ), dtype=np.bool) - sample_mask_right = np.zeros((n_total_samples, ), dtype=np.bool) - n_node_samples_left = 0 - n_node_samples_right = 0 - - for i from 0 <= i < n_total_samples: - if sample_mask_ptr[i]: - if X_ptr[i] <= threshold: - sample_mask_left[i] = 1 - n_node_samples_left += 1 - else: - sample_mask_right[i] = 1 - n_node_samples_right += 1 - - node_id = self.add_split_node(parent, is_left_child, feature, - threshold, buffer_value, best_error, - init_error, n_node_samples) - - # Left child recursion - self.recursive_partition(X, X_argsorted, y, sample_mask_left, - n_node_samples_left, depth + 1, node_id, - True, buffer_value) - - # Right child recursion - self.recursive_partition(X, X_argsorted, y, sample_mask_right, - n_node_samples_right, depth + 1, node_id, - False, buffer_value) - - cdef int add_split_node(self, int parent, int is_left_child, int feature, - double threshold, double* value, - double best_error, double init_error, - int n_samples): - """Add a splitting node to the tree. The new node registers itself as - the child of its parent. """ - cdef int node_id = self.node_count + for k in range(n_outputs): + total += (sq_sum_total[k] / weighted_n_node_samples - + mean_total[k] * mean_total[k]) - if node_id >= self.capacity: - self.resize() + return total / n_outputs + + cdef void children_impurity(self, double* impurity_left, + double* impurity_right) nogil: + """Evaluate the impurity in children nodes, i.e. the impurity of the + left child (samples[start:pos]) and the impurity the right child + (samples[pos:end]).""" + cdef SIZE_t n_outputs = self.n_outputs + cdef double* var_left = self.var_left + cdef double* var_right = self.var_right + cdef double total_left = 0.0 + cdef double total_right = 0.0 + cdef SIZE_t k + + for k in range(n_outputs): + total_left += var_left[k] + total_right += var_right[k] + + impurity_left[0] = total_left / n_outputs + impurity_right[0] = total_right / n_outputs + + +cdef class FriedmanMSE(MSE): + """Mean squared error impurity criterion with improvement score by Friedman + + Uses the formula (35) in Friedmans original Gradient Boosting paper: + + diff = mean_left - mean_right + improvement = n_left * n_right * diff^2 / (n_left + n_right) + """ + + cdef double impurity_improvement(self, double impurity) nogil: + cdef SIZE_t n_outputs = self.n_outputs + cdef SIZE_t k + cdef double* sum_left = self.sum_left + cdef double* sum_right = self.sum_right + cdef double total_sum_left = 0.0 + cdef double total_sum_right = 0.0 + cdef double weighted_n_left = self.weighted_n_left + cdef double weighted_n_right = self.weighted_n_right + cdef double diff = 0.0 - self.feature[node_id] = feature - self.threshold[node_id] = threshold + for k from 0 <= k < n_outputs: + total_sum_left += sum_left[k] + total_sum_right += sum_right[k] + + total_sum_left = total_sum_left / n_outputs + total_sum_right = total_sum_right / n_outputs + diff = ((total_sum_left / weighted_n_left) - + (total_sum_right / weighted_n_right)) + + return (weighted_n_left * weighted_n_right * diff * diff / + (weighted_n_left + weighted_n_right)) + +# ============================================================================= +# Splitter +# ============================================================================= + +cdef inline void _init_split(SplitRecord* self, SIZE_t start_pos) nogil: + self.impurity_left = INFINITY + self.impurity_right = INFINITY + self.pos = start_pos + self.feature = 0 + self.threshold = 0. + self.improvement = -INFINITY + + +cdef class Splitter: + def __cinit__(self, Criterion criterion, SIZE_t max_features, + SIZE_t min_samples_leaf, double min_weight_leaf, + object random_state): + self.criterion = criterion + + self.samples = NULL + self.n_samples = 0 + self.features = NULL + self.n_features = 0 + self.feature_values = NULL - cdef int offset_node = node_id * self.value_stride - memcpy(self.value + offset_node, value, self.value_stride * sizeof(double)) + self.y = NULL + self.y_stride = 0 + self.sample_weight = NULL + + self.max_features = max_features + self.min_samples_leaf = min_samples_leaf + self.min_weight_leaf = min_weight_leaf + self.random_state = random_state + + def __dealloc__(self): + """Destructor.""" + free(self.samples) + free(self.features) + free(self.constant_features) + free(self.feature_values) + + def __getstate__(self): + return {} - self.init_error[node_id] = init_error - self.best_error[node_id] = best_error - self.n_samples[node_id] = n_samples + def __setstate__(self, d): + pass - # set as left or right child of parent - if parent > _TREE_LEAF: - if is_left_child: - self.children_left[parent] = node_id + cdef void init(self, + object X, + np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, + DOUBLE_t* sample_weight) except *: + """Initialize the splitter.""" + # Reset random state + self.rand_r_state = self.random_state.randint(0, RAND_R_MAX) + # Initialize samples and features structures + cdef SIZE_t n_samples = X.shape[0] + cdef SIZE_t* samples = safe_realloc(&self.samples, n_samples) + + cdef SIZE_t i, j + cdef double weighted_n_samples = 0.0 + j = 0 + + for i in range(n_samples): + # Only work with positively weighted samples + if sample_weight == NULL or sample_weight[i] != 0.0: + samples[j] = i + j += 1 + + if sample_weight != NULL: + weighted_n_samples += sample_weight[i] else: - self.children_right[parent] = node_id + weighted_n_samples += 1.0 - self.node_count += 1 + self.n_samples = j + self.weighted_n_samples = weighted_n_samples - return node_id + cdef SIZE_t n_features = X.shape[1] + cdef SIZE_t* features = safe_realloc(&self.features, n_features) - cdef int add_leaf(self, int parent, int is_left_child, double* value, - double error, int n_samples): - """Add a leaf to the tree. The new node registers itself as the - child of its parent. """ - cdef int node_id = self.node_count + for i in range(n_features): + features[i] = i - if node_id >= self.capacity: - self.resize() + self.n_features = n_features + + safe_realloc(&self.feature_values, n_samples) + safe_realloc(&self.constant_features, n_features) + + # Initialize y, sample_weight + self.y = y.data + self.y_stride = y.strides[0] / y.itemsize + self.sample_weight = sample_weight + + cdef void node_reset(self, SIZE_t start, SIZE_t end, + double* weighted_n_node_samples) nogil: + """Reset splitter on node samples[start:end].""" + self.start = start + self.end = end + + self.criterion.init(self.y, + self.y_stride, + self.sample_weight, + self.weighted_n_samples, + self.samples, + start, + end) + + weighted_n_node_samples[0] = self.criterion.weighted_n_node_samples + + cdef void node_split(self, double impurity, SplitRecord* split, + SIZE_t* n_constant_features) nogil: + """Find a split on node samples[start:end].""" + pass + + cdef void node_value(self, double* dest) nogil: + """Copy the value of node samples[start:end] into dest.""" + self.criterion.node_value(dest) + + cdef double node_impurity(self) nogil: + """Copy the impurity of node samples[start:end.""" + return self.criterion.node_impurity() + + +cdef class BaseDenseSplitter(Splitter): + cdef DTYPE_t* X + cdef SIZE_t X_sample_stride + cdef SIZE_t X_fx_stride - cdef int offset_node = node_id * self.n_outputs * self.max_n_classes - memcpy(self.value + offset_node, value, self.value_stride * sizeof(double)) + def __cinit__(self, Criterion criterion, SIZE_t max_features, + SIZE_t min_samples_leaf, double min_weight_leaf, + object random_state): + # Parent __cinit__ is automatically called - self.init_error[node_id] = error - self.best_error[node_id] = error - self.n_samples[node_id] = n_samples + self.X = NULL + self.X_sample_stride = 0 + self.X_fx_stride = 0 + + cdef void init(self, + object X, + np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, + DOUBLE_t* sample_weight) except *: + """Initialize the splitter.""" + + # Call parent init + Splitter.init(self, X, y, sample_weight) + + # Initialize X + cdef np.ndarray X_ndarray = X + + self.X = X_ndarray.data + self.X_sample_stride = X.strides[0] / X.itemsize + self.X_fx_stride = X.strides[1] / X.itemsize + + +cdef class BestSplitter(BaseDenseSplitter): + """Splitter for finding the best split.""" + def __reduce__(self): + return (BestSplitter, (self.criterion, + self.max_features, + self.min_samples_leaf, + self.min_weight_leaf, + self.random_state), self.__getstate__()) + + cdef void node_split(self, double impurity, SplitRecord* split, + SIZE_t* n_constant_features) nogil: + """Find the best split on node samples[start:end].""" + # Find the best split + cdef SIZE_t* samples = self.samples + cdef SIZE_t start = self.start + cdef SIZE_t end = self.end + + cdef SIZE_t* features = self.features + cdef SIZE_t* constant_features = self.constant_features + cdef SIZE_t n_features = self.n_features + + cdef DTYPE_t* X = self.X + cdef DTYPE_t* Xf = self.feature_values + cdef SIZE_t X_sample_stride = self.X_sample_stride + cdef SIZE_t X_fx_stride = self.X_fx_stride + cdef SIZE_t max_features = self.max_features + cdef SIZE_t min_samples_leaf = self.min_samples_leaf + cdef double min_weight_leaf = self.min_weight_leaf + cdef UINT32_t* random_state = &self.rand_r_state + + cdef SplitRecord best, current + + cdef SIZE_t f_i = n_features + cdef SIZE_t f_j, p, tmp + cdef SIZE_t n_visited_features = 0 + # Number of features discovered to be constant during the split search + cdef SIZE_t n_found_constants = 0 + # Number of features known to be constant and drawn without replacement + cdef SIZE_t n_drawn_constants = 0 + cdef SIZE_t n_known_constants = n_constant_features[0] + # n_total_constants = n_known_constants + n_found_constants + cdef SIZE_t n_total_constants = n_known_constants + cdef DTYPE_t current_feature_value + cdef SIZE_t partition_end + + _init_split(&best, end) + + # Sample up to max_features without replacement using a + # Fisher-Yates-based algorithm (using the local variables `f_i` and + # `f_j` to compute a permutation of the `features` array). + # + # Skip the CPU intensive evaluation of the impurity criterion for + # features that were already detected as constant (hence not suitable + # for good splitting) by ancestor nodes and save the information on + # newly discovered constant features to spare computation on descendant + # nodes. + while (f_i > n_total_constants and # Stop early if remaining features + # are constant + (n_visited_features < max_features or + # At least one drawn features must be non constant + n_visited_features <= n_found_constants + n_drawn_constants)): + + n_visited_features += 1 + + # Loop invariant: elements of features in + # - [:n_drawn_constant[ holds drawn and known constant features; + # - [n_drawn_constant:n_known_constant[ holds known constant + # features that haven't been drawn yet; + # - [n_known_constant:n_total_constant[ holds newly found constant + # features; + # - [n_total_constant:f_i[ holds features that haven't been drawn + # yet and aren't constant apriori. + # - [f_i:n_features[ holds features that have been drawn + # and aren't constant. + + # Draw a feature at random + f_j = rand_int(n_drawn_constants, f_i - n_found_constants, + random_state) + + if f_j < n_known_constants: + # f_j in the interval [n_drawn_constants, n_known_constants[ + tmp = features[f_j] + features[f_j] = features[n_drawn_constants] + features[n_drawn_constants] = tmp + + n_drawn_constants += 1 - if parent >= 0: - if is_left_child: - self.children_left[parent] = node_id else: - self.children_right[parent] = node_id + # f_j in the interval [n_known_constants, f_i - n_found_constants[ + f_j += n_found_constants + # f_j in the interval [n_total_constants, f_i[ - self.children_left[node_id] = _TREE_LEAF - self.children_right[node_id] = _TREE_LEAF + current.feature = features[f_j] - self.node_count += 1 + # Sort samples along that feature; first copy the feature + # values for the active samples into Xf, s.t. + # Xf[i] == X[samples[i], j], so the sort uses the cache more + # effectively. + for p in range(start, end): + Xf[p] = X[X_sample_stride * samples[p] + + X_fx_stride * current.feature] - return node_id + sort(Xf + start, samples + start, end - start) - cdef void find_split(self, DTYPE_t* X_ptr, int X_stride, - int* X_argsorted_ptr, int X_argsorted_stride, - DOUBLE_t* y_ptr, int y_stride, BOOL_t* sample_mask_ptr, - int n_node_samples, int n_total_samples, int* _best_i, - double* _best_t, double* _best_error, - double* _initial_error): - """Find the best dimension and threshold that minimises the error.""" - if self.find_split_algorithm == _TREE_SPLIT_BEST: - self.find_best_split(X_ptr, X_stride, X_argsorted_ptr, - X_argsorted_stride, y_ptr, y_stride, - sample_mask_ptr, n_node_samples, - n_total_samples, _best_i, _best_t, - _best_error, _initial_error) - - elif self.find_split_algorithm == _TREE_SPLIT_RANDOM: - self.find_random_split(X_ptr, X_stride, X_argsorted_ptr, - X_argsorted_stride, y_ptr, y_stride, - sample_mask_ptr, n_node_samples, - n_total_samples, _best_i, _best_t, - _best_error, _initial_error) - - cdef void find_best_split(self, DTYPE_t* X_ptr, int X_stride, - int* X_argsorted_ptr, int X_argsorted_stride, - DOUBLE_t* y_ptr, int y_stride, - BOOL_t* sample_mask_ptr, int n_node_samples, - int n_total_samples, int* _best_i, - double* _best_t, double* _best_error, - double* _initial_error): - """Implementation of `find_split` that looks for the best threshold.""" - # Variables declarations - cdef Criterion criterion = self.criterion - cdef int n_features = self.n_features - cdef int max_features = self.max_features - cdef int min_samples_leaf = self.min_samples_leaf - cdef object random_state = self.random_state - - cdef int i, a, b, best_i = -1 - cdef np.int32_t feature_idx = -1 - cdef int n_left = 0 - - cdef double t, initial_error, error - cdef double best_error = INFINITY, best_t = INFINITY - - cdef DTYPE_t* X_i = NULL - cdef int* X_argsorted_i = NULL - cdef DTYPE_t X_a, X_b - - cdef np.ndarray[np.int32_t, ndim=1, mode="c"] features = None - - # Compute the initial criterion value in the node - criterion.init(y_ptr, y_stride, sample_mask_ptr, n_node_samples, n_total_samples) - initial_error = criterion.eval() - - if initial_error == 0: # break early if the node is pure - _best_i[0] = best_i - _best_t[0] = best_t - _best_error[0] = initial_error - _initial_error[0] = initial_error + if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: + features[f_j] = features[n_total_constants] + features[n_total_constants] = current.feature - return + n_found_constants += 1 + n_total_constants += 1 + + else: + f_i -= 1 + features[f_i], features[f_j] = features[f_j], features[f_i] + + # Evaluate all splits + self.criterion.reset() + p = start - best_error = initial_error + while p < end: + while (p + 1 < end and + Xf[p + 1] <= Xf[p] + FEATURE_THRESHOLD): + p += 1 + + # (p + 1 >= end) or (X[samples[p + 1], current.feature] > + # X[samples[p], current.feature]) + p += 1 + # (p >= end) or (X[samples[p], current.feature] > + # X[samples[p - 1], current.feature]) + + if p < end: + current.pos = p + + # Reject if min_samples_leaf is not guaranteed + if (((current.pos - start) < min_samples_leaf) or + ((end - current.pos) < min_samples_leaf)): + continue + + self.criterion.update(current.pos) + + # Reject if min_weight_leaf is not satisfied + if ((self.criterion.weighted_n_left < min_weight_leaf) or + (self.criterion.weighted_n_right < min_weight_leaf)): + continue + + current.improvement = self.criterion.impurity_improvement(impurity) + + if current.improvement > best.improvement: + self.criterion.children_impurity(¤t.impurity_left, + ¤t.impurity_right) + current.threshold = (Xf[p - 1] + Xf[p]) / 2.0 + + if current.threshold == Xf[p]: + current.threshold = Xf[p - 1] + + best = current # copy + + # Reorganize into samples[start:best.pos] + samples[best.pos:end] + if best.pos < end: + partition_end = end + p = start + + while p < partition_end: + if X[X_sample_stride * samples[p] + + X_fx_stride * best.feature] <= best.threshold: + p += 1 + + else: + partition_end -= 1 - # Features to consider - features = np.arange(n_features, dtype=np.int32) + tmp = samples[partition_end] + samples[partition_end] = samples[p] + samples[p] = tmp - if max_features < 0 or max_features >= n_features: - max_features = n_features + # Respect invariant for constant features: the original order of + # element in features[:n_known_constants] must be preserved for sibling + # and child nodes + memcpy(features, constant_features, sizeof(SIZE_t) * n_known_constants) + # Copy newly found constant features + memcpy(constant_features + n_known_constants, + features + n_known_constants, + sizeof(SIZE_t) * n_found_constants) + + # Return values + split[0] = best + n_constant_features[0] = n_total_constants + + +# Sort n-element arrays pointed to by Xf and samples, simultaneously, +# by the values in Xf. Algorithm: Introsort (Musser, SP&E, 1997). +cdef inline void sort(DTYPE_t* Xf, SIZE_t* samples, SIZE_t n) nogil: + cdef int maxd = 2 * log(n) + introsort(Xf, samples, n, maxd) + + +cdef inline void swap(DTYPE_t* Xf, SIZE_t* samples, SIZE_t i, SIZE_t j) nogil: + # Helper for sort + Xf[i], Xf[j] = Xf[j], Xf[i] + samples[i], samples[j] = samples[j], samples[i] + + +cdef inline DTYPE_t median3(DTYPE_t* Xf, SIZE_t n) 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 = Xf[0], b = Xf[n / 2], c = Xf[n - 1] + if a < b: + if b < c: + return b + elif a < c: + return c else: - features = random_state.permutation(features)[:max_features] - - # Look for the best split - for feature_idx from 0 <= feature_idx < max_features: - i = features[feature_idx] - - # Get i-th col of X and X_sorted - X_i = X_ptr + X_stride * i - X_argsorted_i = X_argsorted_ptr + X_argsorted_stride * i - - # Reset the criterion for this feature - criterion.reset() - - # Index of smallest sample in X_argsorted_i that is in the sample mask - a = 0 - - while sample_mask_ptr[X_argsorted_i[a]] == 0: - a = a + 1 - - # Consider splits between two consecutive samples - while True: - # Find the following larger sample - b = _smallest_sample_larger_than(a, X_i, X_argsorted_i, - sample_mask_ptr, n_total_samples) - if b == -1: - break - - # Better split than the best so far? - n_left = criterion.update(a, b, y_ptr, y_stride, X_argsorted_i, sample_mask_ptr) - - # Only consider splits that respect min_leaf - if n_left < min_samples_leaf or (n_node_samples - n_left) < min_samples_leaf: - a = b - continue - - error = criterion.eval() - - if error < best_error: - X_a = X_i[X_argsorted_i[a]] - X_b = X_i[X_argsorted_i[b]] - - t = X_a + (X_b - X_a) / 2.0 - if t == X_b: - t = X_a - - best_i = i - best_t = t - best_error = error - - # Proceed to the next interval - a = b - - _best_i[0] = best_i - _best_t[0] = best_t - _best_error[0] = best_error - _initial_error[0] = initial_error - - cdef void find_random_split(self, DTYPE_t* X_ptr, int X_stride, - int* X_argsorted_ptr, int X_argsorted_stride, - DOUBLE_t* y_ptr, int y_stride, - BOOL_t* sample_mask_ptr, int n_node_samples, - int n_total_samples, int* _best_i, - double* _best_t, double* _best_error, - double* _initial_error): - """Implementation of `find_split` that looks for the best threshold - among randomly drawn thresholds at each feature.""" - # Variables declarations - cdef Criterion criterion = self.criterion - cdef int n_features = self.n_features - cdef int max_features = self.max_features - cdef int min_samples_leaf = self.min_samples_leaf - cdef object random_state = self.random_state - - cdef int i, a, b, c, best_i = -1 - cdef np.int32_t feature_idx = -1 - cdef int n_left = 0 - cdef double random - - cdef double t, initial_error, error - cdef double best_error = INFINITY, best_t = INFINITY - - cdef DTYPE_t* X_i = NULL - cdef int* X_argsorted_i = NULL - cdef DTYPE_t X_a, X_b - - cdef np.ndarray[np.int32_t, ndim=1, mode="c"] features = None - - # Compute the initial criterion value in the node - criterion.init(y_ptr, y_stride, sample_mask_ptr, n_node_samples, n_total_samples) - initial_error = criterion.eval() - - if initial_error == 0: # break early if the node is pure - _best_i[0] = best_i - _best_t[0] = best_t - _best_error[0] = initial_error - _initial_error[0] = initial_error + return a + elif b < c: + if a < c: + return a + else: + return c + else: + return b + + +# 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* Xf, SIZE_t *samples, SIZE_t n, int maxd) nogil: + cdef DTYPE_t pivot + cdef SIZE_t i, l, r + while n > 1: + if maxd <= 0: # max depth limit exceeded ("gone quadratic") + heapsort(Xf, samples, n) return + maxd -= 1 + + pivot = median3(Xf, n) + + # Three-way partition. + i = l = 0 + r = n + while i < r: + if Xf[i] < pivot: + swap(Xf, samples, i, l) + i += 1 + l += 1 + elif Xf[i] > pivot: + r -= 1 + swap(Xf, samples, i, r) + else: + i += 1 + + introsort(Xf, samples, l, maxd) + Xf += r + samples += r + n -= r + - best_error = initial_error +cdef inline void sift_down(DTYPE_t* Xf, SIZE_t* samples, + SIZE_t start, SIZE_t end) nogil: + # Restore heap order in Xf[start:end] by moving the max element to start. + cdef SIZE_t child, maxind, root - # Features to consider - features = np.arange(n_features, dtype=np.int32) + root = start + while True: + child = root * 2 + 1 - if max_features < 0 or max_features >= n_features: - max_features = n_features + # find max of root, left child, right child + maxind = root + if child < end and Xf[maxind] < Xf[child]: + maxind = child + if child + 1 < end and Xf[maxind] < Xf[child + 1]: + maxind = child + 1 + if maxind == root: + break else: - features = random_state.permutation(features)[:max_features] - - # Look for the best split - for feature_idx from 0 <= feature_idx < max_features: - i = features[feature_idx] - - # Get i-th col of X and X_sorted - X_i = X_ptr + X_stride * i - X_argsorted_i = X_argsorted_ptr + X_argsorted_stride * i - - # Reset the criterion for this feature - criterion.reset() - - # Find min and max - a = 0 - while sample_mask_ptr[X_argsorted_i[a]] == 0: - a = a + 1 - X_a = X_i[X_argsorted_i[a]] - - b = n_total_samples - 1 - while sample_mask_ptr[X_argsorted_i[b]] == 0: - b = b - 1 - X_b = X_i[X_argsorted_i[b]] - - if b <= a or X_a == X_b: - continue - - # Draw a random threshold in [a, b) - random = random_state.rand() - t = X_a + (random * (X_b - X_a)) - if t == X_b: - t = X_a - - # Find the sample just greater than t - c = a + 1 - - while True: - if sample_mask_ptr[X_argsorted_i[c]] != 0: - # FIXME why is t cast to DTYPE_t? - if X_i[X_argsorted_i[c]] > ( t) or c == b: - break + swap(Xf, samples, root, maxind) + root = maxind - c += 1 - # Better than the best so far? - n_left = criterion.update(0, c, y_ptr, y_stride, X_argsorted_i, sample_mask_ptr) - error = criterion.eval() +cdef void heapsort(DTYPE_t* Xf, SIZE_t* samples, SIZE_t n) nogil: + cdef SIZE_t start, end - if n_left < min_samples_leaf or (n_node_samples - n_left) < min_samples_leaf: - continue + # heapify + start = (n - 2) / 2 + end = n + while True: + sift_down(Xf, samples, start, end) + if start == 0: + break + start -= 1 - if error < best_error: - best_i = i - best_t = t - best_error = error + # sort by shrinking the heap, putting the max element immediately after it + end = n - 1 + while end > 0: + swap(Xf, samples, 0, end) + sift_down(Xf, samples, 0, end) + end = end - 1 - _best_i[0] = best_i - _best_t[0] = best_t - _best_error[0] = best_error - _initial_error[0] = initial_error - cpdef predict(self, np.ndarray[DTYPE_t, ndim=2] X): - """Predict target for X.""" - cdef int i, k, c - cdef int n_samples = X.shape[0] - cdef int node_id = 0 - cdef int offset_node - cdef int offset_output - - cdef np.ndarray[np.float64_t, ndim=3] out - out = np.zeros((n_samples, self.n_outputs, self.max_n_classes), dtype=np.float64) - - for i from 0 <= i < n_samples: - node_id = 0 - - # While node_id not a leaf - while self.children_left[node_id] != _TREE_LEAF: # and self.children_right[node_id] != _TREE_LEAF: - if X[i, self.feature[node_id]] <= self.threshold[node_id]: - node_id = self.children_left[node_id] +cdef class RandomSplitter(BaseDenseSplitter): + """Splitter for finding the best random split.""" + def __reduce__(self): + return (RandomSplitter, (self.criterion, + self.max_features, + self.min_samples_leaf, + self.min_weight_leaf, + self.random_state), self.__getstate__()) + + cdef void node_split(self, double impurity, SplitRecord* split, + SIZE_t* n_constant_features) nogil: + """Find the best random split on node samples[start:end].""" + # Draw random splits and pick the best + cdef SIZE_t* samples = self.samples + cdef SIZE_t start = self.start + cdef SIZE_t end = self.end + + cdef SIZE_t* features = self.features + cdef SIZE_t* constant_features = self.constant_features + cdef SIZE_t n_features = self.n_features + + cdef DTYPE_t* X = self.X + cdef DTYPE_t* Xf = self.feature_values + cdef SIZE_t X_sample_stride = self.X_sample_stride + cdef SIZE_t X_fx_stride = self.X_fx_stride + cdef SIZE_t max_features = self.max_features + cdef SIZE_t min_samples_leaf = self.min_samples_leaf + cdef double min_weight_leaf = self.min_weight_leaf + cdef UINT32_t* random_state = &self.rand_r_state + + cdef SplitRecord best, current + + cdef SIZE_t f_i = n_features + cdef SIZE_t f_j, p, tmp + # Number of features discovered to be constant during the split search + cdef SIZE_t n_found_constants = 0 + # Number of features known to be constant and drawn without replacement + cdef SIZE_t n_drawn_constants = 0 + cdef SIZE_t n_known_constants = n_constant_features[0] + # n_total_constants = n_known_constants + n_found_constants + cdef SIZE_t n_total_constants = n_known_constants + cdef SIZE_t n_visited_features = 0 + cdef DTYPE_t min_feature_value + cdef DTYPE_t max_feature_value + cdef DTYPE_t current_feature_value + cdef SIZE_t partition_end + + _init_split(&best, end) + + # Sample up to max_features without replacement using a + # Fisher-Yates-based algorithm (using the local variables `f_i` and + # `f_j` to compute a permutation of the `features` array). + # + # Skip the CPU intensive evaluation of the impurity criterion for + # features that were already detected as constant (hence not suitable + # for good splitting) by ancestor nodes and save the information on + # newly discovered constant features to spare computation on descendant + # nodes. + while (f_i > n_total_constants and # Stop early if remaining features + # are constant + (n_visited_features < max_features or + # At least one drawn features must be non constant + n_visited_features <= n_found_constants + n_drawn_constants)): + n_visited_features += 1 + + # Loop invariant: elements of features in + # - [:n_drawn_constant[ holds drawn and known constant features; + # - [n_drawn_constant:n_known_constant[ holds known constant + # features that haven't been drawn yet; + # - [n_known_constant:n_total_constant[ holds newly found constant + # features; + # - [n_total_constant:f_i[ holds features that haven't been drawn + # yet and aren't constant apriori. + # - [f_i:n_features[ holds features that have been drawn + # and aren't constant. + + # Draw a feature at random + f_j = rand_int(n_drawn_constants, f_i - n_found_constants, + random_state) + + if f_j < n_known_constants: + # f_j in the interval [n_drawn_constants, n_known_constants[ + tmp = features[f_j] + features[f_j] = features[n_drawn_constants] + features[n_drawn_constants] = tmp + + n_drawn_constants += 1 + + else: + # f_j in the interval [n_known_constants, f_i - n_found_constants[ + f_j += n_found_constants + # f_j in the interval [n_total_constants, f_i[ + + current.feature = features[f_j] + + # Find min, max + min_feature_value = X[X_sample_stride * samples[start] + + X_fx_stride * current.feature] + max_feature_value = min_feature_value + Xf[start] = min_feature_value + + for p in range(start + 1, end): + current_feature_value = X[X_sample_stride * samples[p] + + X_fx_stride * current.feature] + Xf[p] = current_feature_value + + if current_feature_value < min_feature_value: + min_feature_value = current_feature_value + elif current_feature_value > max_feature_value: + max_feature_value = current_feature_value + + if max_feature_value <= min_feature_value + FEATURE_THRESHOLD: + features[f_j] = features[n_total_constants] + features[n_total_constants] = current.feature + + n_found_constants += 1 + n_total_constants += 1 + + else: + f_i -= 1 + features[f_i], features[f_j] = features[f_j], features[f_i] + + # Draw a random threshold + current.threshold = rand_uniform(min_feature_value, + max_feature_value, + random_state) + + if current.threshold == max_feature_value: + current.threshold = min_feature_value + + # Partition + partition_end = end + p = start + while p < partition_end: + current_feature_value = Xf[p] + if current_feature_value <= current.threshold: + p += 1 + else: + partition_end -= 1 + + Xf[p] = Xf[partition_end] + Xf[partition_end] = current_feature_value + + tmp = samples[partition_end] + samples[partition_end] = samples[p] + samples[p] = tmp + + current.pos = partition_end + + # Reject if min_samples_leaf is not guaranteed + if (((current.pos - start) < min_samples_leaf) or + ((end - current.pos) < min_samples_leaf)): + continue + + # Evaluate split + self.criterion.reset() + self.criterion.update(current.pos) + + # Reject if min_weight_leaf is not satisfied + if ((self.criterion.weighted_n_left < min_weight_leaf) or + (self.criterion.weighted_n_right < min_weight_leaf)): + continue + + current.improvement = self.criterion.impurity_improvement(impurity) + + if current.improvement > best.improvement: + self.criterion.children_impurity(¤t.impurity_left, + ¤t.impurity_right) + best = current # copy + + # Reorganize into samples[start:best.pos] + samples[best.pos:end] + if best.pos < end and current.feature != best.feature: + partition_end = end + p = start + + while p < partition_end: + if X[X_sample_stride * samples[p] + + X_fx_stride * best.feature] <= best.threshold: + p += 1 + else: - node_id = self.children_right[node_id] + partition_end -= 1 + + tmp = samples[partition_end] + samples[partition_end] = samples[p] + samples[p] = tmp + + # Respect invariant for constant features: the original order of + # element in features[:n_known_constants] must be preserved for sibling + # and child nodes + memcpy(features, constant_features, sizeof(SIZE_t) * n_known_constants) + + # Copy newly found constant features + memcpy(constant_features + n_known_constants, + features + n_known_constants, + sizeof(SIZE_t) * n_found_constants) + + # Return values + split[0] = best + n_constant_features[0] = n_total_constants + + +cdef class PresortBestSplitter(BaseDenseSplitter): + """Splitter for finding the best split, using presorting.""" + cdef DTYPE_t* X_old + cdef np.ndarray X_argsorted + cdef INT32_t* X_argsorted_ptr + cdef SIZE_t X_argsorted_stride + + cdef SIZE_t n_total_samples + cdef unsigned char* sample_mask + + def __cinit__(self, Criterion criterion, SIZE_t max_features, + SIZE_t min_samples_leaf, + double min_weight_leaf, + object random_state): + # Initialize pointers + self.X_old = NULL + self.X_argsorted_ptr = NULL + self.X_argsorted_stride = 0 + self.sample_mask = NULL - offset_node = node_id * self.value_stride + def __dealloc__(self): + """Destructor.""" + free(self.sample_mask) - for k from 0 <= k < self.n_outputs: - offset_output = k * self.max_n_classes + def __reduce__(self): + return (PresortBestSplitter, (self.criterion, + self.max_features, + self.min_samples_leaf, + self.min_weight_leaf, + self.random_state), self.__getstate__()) + + cdef void init(self, object X, + np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, + DOUBLE_t* sample_weight) except *: + + cdef void* sample_mask = NULL + + # Call parent initializer + BaseDenseSplitter.init(self, X, y, sample_weight) + + cdef np.ndarray X_ndarray = X + + # Pre-sort X + if self.X_old != self.X: + self.X_old = self.X + self.X_argsorted = np.asfortranarray(np.argsort(X_ndarray, axis=0), + dtype=np.int32) + self.X_argsorted_ptr = self.X_argsorted.data + self.X_argsorted_stride = ( self.X_argsorted.strides[1] / + self.X_argsorted.itemsize) + + self.n_total_samples = X.shape[0] + sample_mask = safe_realloc(&self.sample_mask, self.n_total_samples) + memset(sample_mask, 0, self.n_total_samples) + + cdef void node_split(self, double impurity, SplitRecord* split, + SIZE_t* n_constant_features) nogil: + """Find the best split on node samples[start:end].""" + # Find the best split + cdef SIZE_t* samples = self.samples + cdef SIZE_t start = self.start + cdef SIZE_t end = self.end + + cdef SIZE_t* features = self.features + cdef SIZE_t* constant_features = self.constant_features + cdef SIZE_t n_features = self.n_features + + cdef DTYPE_t* X = self.X + cdef DTYPE_t* Xf = self.feature_values + cdef SIZE_t X_sample_stride = self.X_sample_stride + cdef SIZE_t X_fx_stride = self.X_fx_stride + cdef INT32_t* X_argsorted = self.X_argsorted_ptr + cdef SIZE_t X_argsorted_stride = self.X_argsorted_stride + cdef SIZE_t n_total_samples = self.n_total_samples + cdef unsigned char* sample_mask = self.sample_mask + + cdef SIZE_t max_features = self.max_features + cdef SIZE_t min_samples_leaf = self.min_samples_leaf + cdef double min_weight_leaf = self.min_weight_leaf + cdef UINT32_t* random_state = &self.rand_r_state + + cdef SplitRecord best, current + + cdef SIZE_t f_i = n_features + cdef SIZE_t f_j, p + # Number of features discovered to be constant during the split search + cdef SIZE_t n_found_constants = 0 + # Number of features known to be constant and drawn without replacement + cdef SIZE_t n_drawn_constants = 0 + cdef SIZE_t n_known_constants = n_constant_features[0] + # n_total_constants = n_known_constants + n_found_constants + cdef SIZE_t n_total_constants = n_known_constants + cdef SIZE_t n_visited_features = 0 + cdef SIZE_t partition_end + cdef SIZE_t i, j + + _init_split(&best, end) + + # Set sample mask + for p in range(start, end): + sample_mask[samples[p]] = 1 + + # Sample up to max_features without replacement using a + # Fisher-Yates-based algorithm (using the local variables `f_i` and + # `f_j` to compute a permutation of the `features` array). + # + # Skip the CPU intensive evaluation of the impurity criterion for + # features that were already detected as constant (hence not suitable + # for good splitting) by ancestor nodes and save the information on + # newly discovered constant features to spare computation on descendant + # nodes. + while (f_i > n_total_constants and # Stop early if remaining features + # are constant + (n_visited_features < max_features or + # At least one drawn features must be non constant + n_visited_features <= n_found_constants + n_drawn_constants)): + n_visited_features += 1 + + # Loop invariant: elements of features in + # - [:n_drawn_constant[ holds drawn and known constant features; + # - [n_drawn_constant:n_known_constant[ holds known constant + # features that haven't been drawn yet; + # - [n_known_constant:n_total_constant[ holds newly found constant + # features; + # - [n_total_constant:f_i[ holds features that haven't been drawn + # yet and aren't constant apriori. + # - [f_i:n_features[ holds features that have been drawn + # and aren't constant. + + # Draw a feature at random + f_j = rand_int(n_drawn_constants, f_i - n_found_constants, + random_state) + + if f_j < n_known_constants: + # f_j is in [n_drawn_constants, n_known_constants[ + tmp = features[f_j] + features[f_j] = features[n_drawn_constants] + features[n_drawn_constants] = tmp + + n_drawn_constants += 1 - for c from 0 <= c < self.n_classes[k]: - out[i, k, c] = self.value[offset_node + offset_output + c] + else: + # f_j in the interval [n_known_constants, f_i - n_found_constants[ + f_j += n_found_constants + # f_j in the interval [n_total_constants, f_i[ - return out + current.feature = features[f_j] - cpdef apply(self, np.ndarray[DTYPE_t, ndim=2] X): - """Finds the terminal region (=leaf node) for each sample in X.""" - cdef int i = 0 - cdef int n_samples = X.shape[0] - cdef int node_id = 0 + # Extract ordering from X_argsorted + p = start - cdef np.ndarray[np.int32_t, ndim=1] out - out = np.zeros((n_samples, ), dtype=np.int32) + for i in range(n_total_samples): + j = X_argsorted[X_argsorted_stride * current.feature + i] + if sample_mask[j] == 1: + samples[p] = j + Xf[p] = X[X_sample_stride * j + + X_fx_stride * current.feature] + p += 1 - for i from 0 <= i < n_samples: - node_id = 0 + # Evaluate all splits + if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: + features[f_j] = features[n_total_constants] + features[n_total_constants] = current.feature + + n_found_constants += 1 + n_total_constants += 1 - # While node_id not a leaf - while self.children_left[node_id] != _TREE_LEAF: # and self.children_right[node_id] != _TREE_LEAF: - if X[i, self.feature[node_id]] <= self.threshold[node_id]: - node_id = self.children_left[node_id] else: - node_id = self.children_right[node_id] + f_i -= 1 + features[f_i], features[f_j] = features[f_j], features[f_i] - out[i] = node_id + self.criterion.reset() + p = start - return out + while p < end: + while (p + 1 < end and + Xf[p + 1] <= Xf[p] + FEATURE_THRESHOLD): + p += 1 + + # (p + 1 >= end) or (X[samples[p + 1], current.feature] > + # X[samples[p], current.feature]) + p += 1 + # (p >= end) or (X[samples[p], current.feature] > + # X[samples[p - 1], current.feature]) + + if p < end: + current.pos = p + + # Reject if min_samples_leaf is not guaranteed + if (((current.pos - start) < min_samples_leaf) or + ((end - current.pos) < min_samples_leaf)): + continue + + self.criterion.update(current.pos) + + # Reject if min_weight_leaf is not satisfied + if ((self.criterion.weighted_n_left < min_weight_leaf) or + (self.criterion.weighted_n_right < min_weight_leaf)): + continue + + current.improvement = self.criterion.impurity_improvement(impurity) + + if current.improvement > best.improvement: + self.criterion.children_impurity(¤t.impurity_left, + ¤t.impurity_right) + + current.threshold = (Xf[p - 1] + Xf[p]) / 2.0 + if current.threshold == Xf[p]: + current.threshold = Xf[p - 1] + + best = current # copy + + # Reorganize into samples[start:best.pos] + samples[best.pos:end] + if best.pos < end: + partition_end = end + p = start + + while p < partition_end: + if X[X_sample_stride * samples[p] + + X_fx_stride * best.feature] <= best.threshold: + p += 1 + + else: + partition_end -= 1 + + tmp = samples[partition_end] + samples[partition_end] = samples[p] + samples[p] = tmp + + # Reset sample mask + for p in range(start, end): + sample_mask[samples[p]] = 0 + + # Respect invariant for constant features: the original order of + # element in features[:n_known_constants] must be preserved for sibling + # and child nodes + memcpy(features, constant_features, sizeof(SIZE_t) * n_known_constants) + + # Copy newly found constant features + memcpy(constant_features + n_known_constants, + features + n_known_constants, + sizeof(SIZE_t) * n_found_constants) - cpdef compute_feature_importances(self, method="gini"): - """Computes the importance of each feature (aka variable). + # Return values + split[0] = best + n_constant_features[0] = n_total_constants - The following `method`s are supported: - * "gini" : The difference of the initial error and the error of the - split times the number of samples that passed the node. - * "squared" : The empirical improvement in squared error. +cdef class BaseSparseSplitter(Splitter): + # The sparse splitter works only with csc sparse matrix format + cdef DTYPE_t* X_data + cdef INT32_t* X_indices + cdef INT32_t* X_indptr + + cdef SIZE_t n_total_samples + + cdef SIZE_t* index_to_samples + cdef SIZE_t* sorted_samples + + def __cinit__(self, Criterion criterion, SIZE_t max_features, + SIZE_t min_samples_leaf, double min_weight_leaf, + object random_state): + # Parent __cinit__ is automatically called + + self.X_data = NULL + self.X_indices = NULL + self.X_indptr = NULL + + self.n_total_samples = 0 + + self.index_to_samples = NULL + self.sorted_samples = NULL + + def __dealloc__(self): + """Deallocate memory""" + free(self.index_to_samples) + free(self.sorted_samples) + + cdef void init(self, + object X, + np.ndarray[DOUBLE_t, ndim=2, mode="c"] y, + DOUBLE_t* sample_weight) except *: + """Initialize the splitter.""" + + # Call parent init + Splitter.init(self, X, y, sample_weight) + + if not isinstance(X, csc_matrix): + raise ValueError("X should be in csc format") + + cdef SIZE_t* samples = self.samples + cdef SIZE_t n_samples = self.n_samples + + # Initialize X + cdef np.ndarray[dtype=DTYPE_t, ndim=1] data = X.data + cdef np.ndarray[dtype=INT32_t, ndim=1] indices = X.indices + cdef np.ndarray[dtype=INT32_t, ndim=1] indptr = X.indptr + cdef SIZE_t n_total_samples = X.shape[0] + + self.X_data = data.data + self.X_indices = indices.data + self.X_indptr = indptr.data + self.n_total_samples = n_total_samples + + # Initialize auxiliary array used to perform split + safe_realloc(&self.index_to_samples, n_total_samples * sizeof(SIZE_t)) + safe_realloc(&self.sorted_samples, n_samples * sizeof(SIZE_t)) + + cdef SIZE_t* index_to_samples = self.index_to_samples + cdef SIZE_t p + for p in range(n_total_samples): + index_to_samples[p] = -1 + + for p in range(n_samples): + index_to_samples[samples[p]] = p + + cdef inline SIZE_t _partition(self, double threshold, + SIZE_t end_negative, SIZE_t start_positive, + SIZE_t zero_pos) nogil: + """Partition samples[start:end] based on threshold""" + + cdef double value + cdef SIZE_t partition_end + cdef SIZE_t p + + cdef DTYPE_t* Xf = self.feature_values + cdef SIZE_t* samples = self.samples + cdef SIZE_t* index_to_samples = self.index_to_samples + + if threshold < 0.: + p = self.start + partition_end = end_negative + elif threshold > 0.: + p = start_positive + partition_end = self.end + else: + # Data are already split + return zero_pos + + while p < partition_end: + value = Xf[p] + + if value <= threshold: + p += 1 + + else: + partition_end -= 1 + + Xf[p] = Xf[partition_end] + Xf[partition_end] = value + sparse_swap(index_to_samples, samples, p, partition_end) + + return partition_end + + cdef inline void extract_nnz(self, SIZE_t feature, + SIZE_t* end_negative, SIZE_t* start_positive, + bint* is_samples_sorted) nogil: + """Extract and partition values for a given feature + + The extracted values are partitioned between negative values + Xf[start:end_negative[0]] and positive values Xf[start_positive[0]:end]. + The samples and index_to_samples are modified according to this + partition. + + The extraction corresponds to the intersection between the arrays + X_indices[indptr_start:indptr_end] and samples[start:end]. + This is done efficiently using either an index_to_samples based approach + or binary search based approach. Parameters ---------- - method : str, optional (default="gini") - The method to estimate the importance of a feature. Either "gini" - or "squared". + feature : SIZE_t, + Index of the feature we want to extract non zero value. + + + end_negative, start_positive : SIZE_t*, SIZE_t*, + Return extracted non zero values in self.samples[start:end] where + negative values are in self.feature_values[start:end_negative[0]] + and positive values are in + self.feature_values[start_positive[0]:end]. + + is_samples_sorted : bint*, + If is_samples_sorted, then self.sorted_samples[start:end] will be + the sorted version of self.samples[start:end]. + """ - if method != "gini" and method != "squared": - raise ValueError( - 'Invalid value for method. Allowed string ' - 'values are "gini", or "squared".') + cdef SIZE_t indptr_start = self.X_indptr[feature], + cdef SIZE_t indptr_end = self.X_indptr[feature + 1] + cdef SIZE_t n_indices = (indptr_end - indptr_start) + cdef SIZE_t n_samples = self.end - self.start + + # Use binary search if n_samples * log(n_indices) < + # n_indices and index_to_samples approach otherwise. + # O(n_samples * log(n_indices)) is the running time of binary + # search and O(n_indices) is the running time of index_to_samples + # approach. + if ((1 - is_samples_sorted[0]) * n_samples * log(n_samples) + + n_samples * log(n_indices) < EXTRACT_NNZ_SWITCH * n_indices): + extract_nnz_binary_search(self.X_indices, self.X_data, + indptr_start, indptr_end, + self.samples, self.start, self.end, + self.index_to_samples, + self.feature_values, + end_negative, start_positive, + self.sorted_samples, is_samples_sorted) + + # Using an index to samples technique to extract non zero values + # index_to_samples is a mapping from X_indices to samples + else: + extract_nnz_index_to_samples(self.X_indices, self.X_data, + indptr_start, indptr_end, + self.samples, self.start, self.end, + self.index_to_samples, + self.feature_values, + end_negative, start_positive) + + +cdef int compare_SIZE_t(const void* a, const void* b) nogil: + """Comparison function for sort""" + return ((a)[0] - (b)[0]) - cdef int node - cdef np.ndarray[np.float64_t, ndim=1] importances - importances = np.zeros((self.n_features,), dtype=np.float64) - if method == "gini": - for node from 0 <= node < self.node_count: - if self.children_left[node] != _TREE_LEAF: # and self.children_right[node] != _TREE_LEAF: - importances[self.feature[node]] += \ - self._compute_feature_importances_gini(node) +cdef inline void binary_search(INT32_t* sorted_array, + INT32_t start, INT32_t end, + SIZE_t value, SIZE_t* index, + INT32_t* new_start) nogil: + """Return the index of value in the sorted array + + If not found, return -1. new_start is the last pivot + 1 + """ + cdef INT32_t pivot + index[0] = -1 + while start < end: + pivot = start + (end - start) / 2 + + if sorted_array[pivot] == value: + index[0] = pivot + start = pivot + 1 + break + + if sorted_array[pivot] < value: + start = pivot + 1 else: - for node from 0 <= node < self.node_count: - if self.children_left[node] != _TREE_LEAF: # and self.children_right[node] != _TREE_LEAF: - importances[self.feature[node]] += \ - self._compute_feature_importances_squared(node) + end = pivot + new_start[0] = start + + +cdef inline void extract_nnz_index_to_samples(INT32_t* X_indices, + DTYPE_t* X_data, + INT32_t indptr_start, + INT32_t indptr_end, + SIZE_t* samples, + SIZE_t start, + SIZE_t end, + SIZE_t* index_to_samples, + DTYPE_t* Xf, + SIZE_t* end_negative, + SIZE_t* start_positive) nogil: + """Extract and partition values for a feature using index_to_samples + + Complexity is O(indptr_end - indptr_start). + """ + cdef INT32_t k + cdef SIZE_t index + cdef SIZE_t end_negative_ = start + cdef SIZE_t start_positive_ = end + + for k in range(indptr_start, indptr_end): + if start <= index_to_samples[X_indices[k]] < end: + if X_data[k] > 0: + start_positive_ -= 1 + Xf[start_positive_] = X_data[k] + index = index_to_samples[X_indices[k]] + sparse_swap(index_to_samples, samples, index, start_positive_) + + + elif X_data[k] < 0: + Xf[end_negative_] = X_data[k] + index = index_to_samples[X_indices[k]] + sparse_swap(index_to_samples, samples, index, end_negative_) + end_negative_ += 1 + + # Returned values + end_negative[0] = end_negative_ + start_positive[0] = start_positive_ + + +cdef inline void extract_nnz_binary_search(INT32_t* X_indices, + DTYPE_t* X_data, + INT32_t indptr_start, + INT32_t indptr_end, + SIZE_t* samples, + SIZE_t start, + SIZE_t end, + SIZE_t* index_to_samples, + DTYPE_t* Xf, + SIZE_t* end_negative, + SIZE_t* start_positive, + SIZE_t* sorted_samples, + bint* is_samples_sorted) nogil: + """Extract and partition values for a given feature using binary search + + If n_samples = end - start and n_indices = indptr_end - indptr_start, + the complexity is + + O((1 - is_samples_sorted[0]) * n_samples * log(n_samples) + + n_samples * log(n_indices)). + """ + cdef SIZE_t n_samples - cdef double normalizer = np.sum(importances) + if not is_samples_sorted[0]: + n_samples = end - start + memcpy(sorted_samples + start, samples + start, + n_samples * sizeof(SIZE_t)) + qsort(sorted_samples + start, n_samples, sizeof(SIZE_t), + compare_SIZE_t) + is_samples_sorted[0] = 1 - if normalizer > 0.0: - # Avoid dividing by zero (e.g., when root is pure) - importances /= normalizer + while (indptr_start < indptr_end and + sorted_samples[start] > X_indices[indptr_start]): + indptr_start += 1 - return importances + while (indptr_start < indptr_end and + sorted_samples[end - 1] < X_indices[indptr_end - 1]): + indptr_end -= 1 - cdef inline double _compute_feature_importances_gini(self, int node): - return self.n_samples[node] * (self.init_error[node] - self.best_error[node]) + cdef SIZE_t p = start + cdef SIZE_t index + cdef SIZE_t k + cdef SIZE_t end_negative_ = start + cdef SIZE_t start_positive_ = end - cdef inline double _compute_feature_importances_squared(self, int node): - cdef double error = self.init_error[node] - self.best_error[node] - return error * error + while (p < end and indptr_start < indptr_end): + # Find index of sorted_samples[p] in X_indices + binary_search(X_indices, indptr_start, indptr_end, + sorted_samples[p], &k, &indptr_start) + if k != -1: + # If k != -1, we have found a non zero value -# ============================================================================== -# Criterion -# ============================================================================== + if X_data[k] > 0: + start_positive_ -= 1 + Xf[start_positive_] = X_data[k] + index = index_to_samples[X_indices[k]] + sparse_swap(index_to_samples, samples, index, start_positive_) -cdef class Criterion: - """Interface for splitting criteria (regression and classification).""" - cdef void init(self, DOUBLE_t* y, int y_stride, BOOL_t* - sample_mask, int n_samples, int n_total_samples): - """Initialise the criterion.""" - pass + elif X_data[k] < 0: + Xf[end_negative_] = X_data[k] + index = index_to_samples[X_indices[k]] + sparse_swap(index_to_samples, samples, index, end_negative_) + end_negative_ += 1 + p += 1 + + # Returned values + end_negative[0] = end_negative_ + start_positive[0] = start_positive_ + + +cdef inline void sparse_swap(SIZE_t* index_to_samples, SIZE_t* samples, + SIZE_t pos_1, SIZE_t pos_2) 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 + index_to_samples[samples[pos_2]] = pos_2 + + +cdef class BestSparseSplitter(BaseSparseSplitter): + """Splitter for finding the best split, using the sparse data.""" + + def __reduce__(self): + return (BestSparseSplitter, (self.criterion, + self.max_features, + self.min_samples_leaf, + self.min_weight_leaf, + self.random_state), self.__getstate__()) + + cdef void node_split(self, double impurity, SplitRecord* split, + SIZE_t* n_constant_features) nogil: + """Find the best split on node samples[start:end], using sparse + features. + """ + # Find the best split + cdef SIZE_t* samples = self.samples + cdef SIZE_t start = self.start + cdef SIZE_t end = self.end + + cdef INT32_t* X_indices = self.X_indices + cdef INT32_t* X_indptr = self.X_indptr + cdef DTYPE_t* X_data = self.X_data + + cdef SIZE_t* features = self.features + cdef SIZE_t* constant_features = self.constant_features + cdef SIZE_t n_features = self.n_features + + cdef DTYPE_t* Xf = self.feature_values + cdef SIZE_t* sorted_samples = self.sorted_samples + cdef SIZE_t* index_to_samples = self.index_to_samples + cdef SIZE_t max_features = self.max_features + cdef SIZE_t min_samples_leaf = self.min_samples_leaf + cdef double min_weight_leaf = self.min_weight_leaf + cdef UINT32_t* random_state = &self.rand_r_state + + cdef SplitRecord best, current + _init_split(&best, end) + + cdef SIZE_t f_i = n_features + cdef SIZE_t f_j, p, tmp + cdef SIZE_t n_visited_features = 0 + # Number of features discovered to be constant during the split search + cdef SIZE_t n_found_constants = 0 + # Number of features known to be constant and drawn without replacement + cdef SIZE_t n_drawn_constants = 0 + cdef SIZE_t n_known_constants = n_constant_features[0] + # n_total_constants = n_known_constants + n_found_constants + cdef SIZE_t n_total_constants = n_known_constants + cdef DTYPE_t current_feature_value + + cdef SIZE_t p_next + cdef SIZE_t p_prev + cdef bint is_samples_sorted = 0 # indicate is sorted_samples is + # inititialized + + # We assume implicitely that end_positive = end and + # start_negative = start + cdef SIZE_t start_positive + cdef SIZE_t end_negative + + # Sample up to max_features without replacement using a + # Fisher-Yates-based algorithm (using the local variables `f_i` and + # `f_j` to compute a permutation of the `features` array). + # + # Skip the CPU intensive evaluation of the impurity criterion for + # features that were already detected as constant (hence not suitable + # for good splitting) by ancestor nodes and save the information on + # newly discovered constant features to spare computation on descendant + # nodes. + while (f_i > n_total_constants and # Stop early if remaining features + # are constant + (n_visited_features < max_features or + # At least one drawn features must be non constant + n_visited_features <= n_found_constants + n_drawn_constants)): + + n_visited_features += 1 + + # Loop invariant: elements of features in + # - [:n_drawn_constant[ holds drawn and known constant features; + # - [n_drawn_constant:n_known_constant[ holds known constant + # features that haven't been drawn yet; + # - [n_known_constant:n_total_constant[ holds newly found constant + # features; + # - [n_total_constant:f_i[ holds features that haven't been drawn + # yet and aren't constant apriori. + # - [f_i:n_features[ holds features that have been drawn + # and aren't constant. + + # Draw a feature at random + f_j = rand_int(n_drawn_constants, f_i - n_found_constants, + random_state) + + if f_j < n_known_constants: + # f_j in the interval [n_drawn_constants, n_known_constants[ + tmp = features[f_j] + features[f_j] = features[n_drawn_constants] + features[n_drawn_constants] = tmp + + n_drawn_constants += 1 + + else: + # f_j in the interval [n_known_constants, f_i - n_found_constants[ + f_j += n_found_constants + # f_j in the interval [n_total_constants, f_i[ + + current.feature = features[f_j] + self.extract_nnz(current.feature, + &end_negative, &start_positive, + &is_samples_sorted) + + # Sort the positive and negative parts of `Xf` + sort(Xf + start, samples + start, end_negative - start) + sort(Xf + start_positive, samples + start_positive, + end - start_positive) + + # Update index_to_samples to take into account the sort + for p in range(start, end_negative): + index_to_samples[samples[p]] = p + for p in range(start_positive, end): + index_to_samples[samples[p]] = p + + # Add one or two zeros in Xf, if there is any + if end_negative < start_positive: + start_positive -= 1 + Xf[start_positive] = 0. + + if end_negative != start_positive: + Xf[end_negative] = 0. + end_negative += 1 + + if Xf[end - 1] <= Xf[start] + FEATURE_THRESHOLD: + features[f_j] = features[n_total_constants] + features[n_total_constants] = current.feature + + n_found_constants += 1 + n_total_constants += 1 + + else: + f_i -= 1 + features[f_i], features[f_j] = features[f_j], features[f_i] + + # Evaluate all splits + self.criterion.reset() + p = start + + while p < end: + if p + 1 != end_negative: + p_next = p + 1 + else: + p_next = start_positive + + while (p_next < end and + Xf[p_next] <= Xf[p] + FEATURE_THRESHOLD): + p = p_next + if p + 1 != end_negative: + p_next = p + 1 + else: + p_next = start_positive + + + # (p_next >= end) or (X[samples[p_next], current.feature] > + # X[samples[p], current.feature]) + p_prev = p + p = p_next + # (p >= end) or (X[samples[p], current.feature] > + # X[samples[p_prev], current.feature]) + - cdef void reset(self): - """Reset the criterion for a new feature index.""" - pass + if p < end: + current.pos = p - cdef int update(self, int a, int b, DOUBLE_t* y, int y_stride, - int* X_argsorted_i, BOOL_t* sample_mask): - """Update the criteria for each value in interval [a,b) (where a and b - are indices in `X_argsorted_i`).""" - pass + # Reject if min_samples_leaf is not guaranteed + if (((current.pos - start) < min_samples_leaf) or + ((end - current.pos) < min_samples_leaf)): + continue - cdef double eval(self): - """Evaluate the criteria (aka the split error).""" - pass + self.criterion.update(current.pos) - cdef void init_value(self, double* buffer_value): - """Get the initial value of the criterion (`init` must be called - before).""" - pass + # Reject if min_weight_leaf is not satisfied + if ((self.criterion.weighted_n_left < min_weight_leaf) or + (self.criterion.weighted_n_right < min_weight_leaf)): + continue + current.improvement = self.criterion.impurity_improvement(impurity) + if current.improvement > best.improvement: + self.criterion.children_impurity(¤t.impurity_left, + ¤t.impurity_right) -cdef class ClassificationCriterion(Criterion): - """Abstract criterion for classification. + current.threshold = (Xf[p_prev] + Xf[p]) / 2.0 + if current.threshold == Xf[p]: + current.threshold = Xf[p_prev] - Attributes - ---------- - n_outputs : int - The number of outputs. + best = current - n_classes : int* - n_classes[k] is the number of classes for output k. + # Reorganize into samples[start:best.pos] + samples[best.pos:end] + if best.pos < end: + self.extract_nnz(best.feature, &end_negative, &start_positive, + &is_samples_sorted) - n_samples : int - The number of samples. + self._partition(best.threshold, end_negative, start_positive, + best.pos) - label_count_stride : int - The stride between outputs in label_count_* arrays. + # Respect invariant for constant features: the original order of + # element in features[:n_known_constants] must be preserved for sibling + # and child nodes + memcpy(features, constant_features, sizeof(SIZE_t) * n_known_constants) - label_count_left : int* - label_count_left[k * label_count_stride + c] is the number of samples - of class c left of splitting point for output k. + # Copy newly found constant features + memcpy(constant_features + n_known_constants, + features + n_known_constants, + sizeof(SIZE_t) * n_found_constants) - label_count_right : int* - label_count_rightt[k * label_count_stride + c] is the number of samples - of class c right of splitting point for output k. + # Return values + split[0] = best + n_constant_features[0] = n_total_constants - label_count_init : int* - label_count_init[k * label_count_stride + c] is the initial number of - samples of class c for output k. Used to reset `label_count_right` for - each feature. - n_left : int - The number of samples left of splitting point. +cdef class RandomSparseSplitter(BaseSparseSplitter): + """Splitter for finding a random split, using the sparse data.""" - n_right : int - The number of samples right of splitting point. + def __reduce__(self): + return (RandomSparseSplitter, (self.criterion, + self.max_features, + self.min_samples_leaf, + self.min_weight_leaf, + self.random_state), self.__getstate__()) + + cdef void node_split(self, double impurity, SplitRecord* split, + SIZE_t* n_constant_features) nogil: + """Find a random split on node samples[start:end], using sparse + features. + """ + # Find the best split + cdef SIZE_t* samples = self.samples + cdef SIZE_t start = self.start + cdef SIZE_t end = self.end + + cdef INT32_t* X_indices = self.X_indices + cdef INT32_t* X_indptr = self.X_indptr + cdef DTYPE_t* X_data = self.X_data + + cdef SIZE_t* features = self.features + cdef SIZE_t* constant_features = self.constant_features + cdef SIZE_t n_features = self.n_features + + cdef DTYPE_t* Xf = self.feature_values + cdef SIZE_t* sorted_samples = self.sorted_samples + cdef SIZE_t* index_to_samples = self.index_to_samples + cdef SIZE_t max_features = self.max_features + cdef SIZE_t min_samples_leaf = self.min_samples_leaf + cdef double min_weight_leaf = self.min_weight_leaf + cdef UINT32_t* random_state = &self.rand_r_state + + cdef SplitRecord best, current + _init_split(&best, end) + + cdef DTYPE_t current_feature_value + + cdef SIZE_t f_i = n_features + cdef SIZE_t f_j, p, tmp + cdef SIZE_t n_visited_features = 0 + # Number of features discovered to be constant during the split search + cdef SIZE_t n_found_constants = 0 + # Number of features known to be constant and drawn without replacement + cdef SIZE_t n_drawn_constants = 0 + cdef SIZE_t n_known_constants = n_constant_features[0] + # n_total_constants = n_known_constants + n_found_constants + cdef SIZE_t n_total_constants = n_known_constants + cdef SIZE_t partition_end + + cdef DTYPE_t min_feature_value + cdef DTYPE_t max_feature_value + + cdef bint is_samples_sorted = 0 # indicate that sorted_samples is + # inititialized + + # We assume implicitely that end_positive = end and + # start_negative = start + cdef SIZE_t start_positive + cdef SIZE_t end_negative + + # Sample up to max_features without replacement using a + # Fisher-Yates-based algorithm (using the local variables `f_i` and + # `f_j` to compute a permutation of the `features` array). + # + # Skip the CPU intensive evaluation of the impurity criterion for + # features that were already detected as constant (hence not suitable + # for good splitting) by ancestor nodes and save the information on + # newly discovered constant features to spare computation on descendant + # nodes. + while (f_i > n_total_constants and # Stop early if remaining features + # are constant + (n_visited_features < max_features or + # At least one drawn features must be non constant + n_visited_features <= n_found_constants + n_drawn_constants)): + + n_visited_features += 1 + + # Loop invariant: elements of features in + # - [:n_drawn_constant[ holds drawn and known constant features; + # - [n_drawn_constant:n_known_constant[ holds known constant + # features that haven't been drawn yet; + # - [n_known_constant:n_total_constant[ holds newly found constant + # features; + # - [n_total_constant:f_i[ holds features that haven't been drawn + # yet and aren't constant apriori. + # - [f_i:n_features[ holds features that have been drawn + # and aren't constant. + + # Draw a feature at random + f_j = rand_int(n_drawn_constants, f_i - n_found_constants, + random_state) + + if f_j < n_known_constants: + # f_j in the interval [n_drawn_constants, n_known_constants[ + tmp = features[f_j] + features[f_j] = features[n_drawn_constants] + features[n_drawn_constants] = tmp + + n_drawn_constants += 1 - References - ---------- + else: + # f_j in the interval [n_known_constants, f_i - n_found_constants[ + f_j += n_found_constants + # f_j in the interval [n_total_constants, f_i[ - [1] Hastie et al. "Elements of Statistical Learning", 2009. - """ - cdef int n_outputs - cdef int* n_classes - cdef int n_samples + current.feature = features[f_j] - cdef int label_count_stride - cdef int* label_count_left - cdef int* label_count_right - cdef int* label_count_init + self.extract_nnz(current.feature, + &end_negative, &start_positive, + &is_samples_sorted) - cdef int n_left - cdef int n_right + # Add one or two zeros in Xf, if there is any + if end_negative < start_positive: + start_positive -= 1 + Xf[start_positive] = 0. - def __cinit__(self, int n_outputs, object n_classes): - """Constructor.""" - cdef int k = 0 + if end_negative != start_positive: + Xf[end_negative] = 0. + end_negative += 1 - self.n_outputs = n_outputs - self.n_samples = 0 - self.n_left = 0 - self.n_right = 0 + # Find min, max in Xf[start:end_negative] + min_feature_value = Xf[start] + max_feature_value = min_feature_value - self.n_classes = malloc(n_outputs * sizeof(int)) - if self.n_classes == NULL: - raise MemoryError() + for p in range(start, end_negative): + current_feature_value = Xf[p] - cdef int label_count_stride = -1 + if current_feature_value < min_feature_value: + min_feature_value = current_feature_value + elif current_feature_value > max_feature_value: + max_feature_value = current_feature_value - for k from 0 <= k < n_outputs: - self.n_classes[k] = n_classes[k] + # Update min, max given Xf[start_positive:end] + for p in range(start_positive, end): + current_feature_value = Xf[p] - if n_classes[k] > label_count_stride: - label_count_stride = n_classes[k] + if current_feature_value < min_feature_value: + min_feature_value = current_feature_value + elif current_feature_value > max_feature_value: + max_feature_value = current_feature_value - self.label_count_stride = label_count_stride + if max_feature_value <= min_feature_value + FEATURE_THRESHOLD: + features[f_j] = features[n_total_constants] + features[n_total_constants] = current.feature - # Allocate - self.label_count_left = calloc(n_outputs * label_count_stride, sizeof(int)) - self.label_count_right = calloc(n_outputs * label_count_stride, sizeof(int)) - self.label_count_init = calloc(n_outputs * label_count_stride, sizeof(int)) + n_found_constants += 1 + n_total_constants += 1 - # Check for allocation errors - if self.label_count_left == NULL or \ - self.label_count_right == NULL or \ - self.label_count_init == NULL: - free(self.n_classes) - free(self.label_count_left) - free(self.label_count_right) - free(self.label_count_init) - raise MemoryError() + else: + f_i -= 1 + features[f_i], features[f_j] = features[f_j], features[f_i] + + # Draw a random threshold + current.threshold = rand_uniform(min_feature_value, + max_feature_value, + random_state) + + if current.threshold == max_feature_value: + current.threshold = min_feature_value + + # Partition + current.pos = self._partition(current.threshold, + end_negative, + start_positive, + start_positive + + (Xf[start_positive] == 0.)) + + # Reject if min_samples_leaf is not guaranteed + if (((current.pos - start) < min_samples_leaf) or + ((end - current.pos) < min_samples_leaf)): + continue + + # Evaluate split + self.criterion.reset() + self.criterion.update(current.pos) + + # Reject if min_weight_leaf is not satisfied + if ((self.criterion.weighted_n_left < min_weight_leaf) or + (self.criterion.weighted_n_right < min_weight_leaf)): + continue + + current.improvement = self.criterion.impurity_improvement(impurity) + + if current.improvement > best.improvement: + self.criterion.children_impurity(¤t.impurity_left, + ¤t.impurity_right) + best = current + + # Reorganize into samples[start:best.pos] + samples[best.pos:end] + if best.pos < end and current.feature != best.feature: + self.extract_nnz(best.feature, &end_negative, &start_positive, + &is_samples_sorted) + + self._partition(best.threshold, end_negative, start_positive, + best.pos) + + # Respect invariant for constant features: the original order of + # element in features[:n_known_constants] must be preserved for sibling + # and child nodes + memcpy(features, constant_features, sizeof(SIZE_t) * n_known_constants) + + # Copy newly found constant features + memcpy(constant_features + n_known_constants, + features + n_known_constants, + sizeof(SIZE_t) * n_found_constants) + + # Return values + split[0] = best + n_constant_features[0] = n_total_constants + + +# ============================================================================= +# Tree builders +# ============================================================================= +cdef class TreeBuilder: + """Interface for different tree building strategies. """ + + cpdef build(self, Tree tree, object X, np.ndarray y, + np.ndarray sample_weight=None): + """Build a decision tree from the training set (X, y).""" + pass - def __dealloc__(self): - """Destructor.""" - free(self.n_classes) - free(self.label_count_left) - free(self.label_count_right) - free(self.label_count_init) + cdef inline _check_input(self, object X, np.ndarray y, + np.ndarray sample_weight): + """Check input dtype, layout and format""" + if issparse(X): + X = X.tocsc() + X.sort_indices() - def __reduce__(self): - return (ClassificationCriterion, - (self.n_outputs, intp_to_ndarray(self.n_classes, - self.n_outputs)), - self.__getstate__()) + if X.data.dtype != DTYPE: + X.data = np.ascontiguousarray(X.data, dtype=DTYPE) - def __getstate__(self): - return {} + if X.indices.dtype != np.int32 or X.indptr.dtype != np.int32: + raise ValueError("No support for np.int64 index based " + "sparse matrices") - def __setstate__(self, d): - pass + elif X.dtype != DTYPE: + # since we have to copy we will make it fortran for efficiency + X = np.asfortranarray(X, dtype=DTYPE) - cdef void init(self, DOUBLE_t* y, int y_stride, BOOL_t *sample_mask, - int n_samples, int n_total_samples): - """Initialise the criterion.""" - cdef int n_outputs = self.n_outputs - cdef int* n_classes = self.n_classes - cdef int label_count_stride = self.label_count_stride - cdef int* label_count_init = self.label_count_init + if y.dtype != DOUBLE or not y.flags.contiguous: + y = np.ascontiguousarray(y, dtype=DOUBLE) - cdef int k = 0 - cdef int c = 0 - cdef int j = 0 + if (sample_weight is not None and + (sample_weight.dtype != DOUBLE or + not sample_weight.flags.contiguous)): + sample_weight = np.asarray(sample_weight, dtype=DOUBLE, + order="C") - self.n_samples = n_samples + return X, y, sample_weight - for k from 0 <= k < n_outputs: - for c from 0 <= c < n_classes[k]: - label_count_init[k * label_count_stride + c] = 0 +# Depth first builder --------------------------------------------------------- - for j from 0 <= j < n_total_samples: - if sample_mask[j] == 0: - continue +cdef class DepthFirstTreeBuilder(TreeBuilder): + """Build a decision tree in depth-first fashion.""" - for k from 0 <= k < n_outputs: - c = y[j * y_stride + k] - label_count_init[k * label_count_stride + c] += 1 + def __cinit__(self, Splitter splitter, SIZE_t min_samples_split, + SIZE_t min_samples_leaf, double min_weight_leaf, + SIZE_t max_depth): + self.splitter = splitter + self.min_samples_split = min_samples_split + self.min_samples_leaf = min_samples_leaf + self.min_weight_leaf = min_weight_leaf + self.max_depth = max_depth - self.reset() + cpdef build(self, Tree tree, object X, np.ndarray y, + np.ndarray sample_weight=None): + """Build a decision tree from the training set (X, y).""" - cdef void reset(self): - """Reset the criterion for a new feature index.""" - cdef int n_outputs = self.n_outputs - cdef int* n_classes = self.n_classes - cdef int label_count_stride = self.label_count_stride - cdef int* label_count_init = self.label_count_init - cdef int* label_count_left = self.label_count_left - cdef int* label_count_right = self.label_count_right + # check input + X, y, sample_weight = self._check_input(X, y, sample_weight) - cdef int k = 0 - cdef int c = 0 - self.n_left = 0 - self.n_right = self.n_samples + cdef DOUBLE_t* sample_weight_ptr = NULL + if sample_weight is not None: + sample_weight_ptr = sample_weight.data - for k from 0 <= k < n_outputs: - for c from 0 <= c < n_classes[k]: - # Reset left label counts to 0 - label_count_left[k * label_count_stride + c] = 0 + # Initial capacity + cdef int init_capacity - # Reset right label counts to the initial counts - label_count_right[k * label_count_stride + c] = label_count_init[k * label_count_stride + c] + if tree.max_depth <= 10: + init_capacity = (2 ** (tree.max_depth + 1)) - 1 + else: + init_capacity = 2047 - cdef int update(self, int a, int b, DOUBLE_t* y, int y_stride, - int* X_argsorted_i, BOOL_t* sample_mask): - """Update the criteria for each value in interval [a,b) (where a and b - are indices in `X_argsorted_i`).""" - cdef int n_outputs = self.n_outputs - cdef int label_count_stride = self.label_count_stride - cdef int* label_count_left = self.label_count_left - cdef int* label_count_right = self.label_count_right - cdef int n_left = self.n_left - cdef int n_right = self.n_right + tree._resize(init_capacity) - cdef int idx, k, c, s + # Parameters + cdef Splitter splitter = self.splitter + cdef SIZE_t max_depth = self.max_depth + cdef SIZE_t min_samples_leaf = self.min_samples_leaf + cdef double min_weight_leaf = self.min_weight_leaf + cdef SIZE_t min_samples_split = self.min_samples_split + + # Recursive partition (without actual recursion) + splitter.init(X, y, sample_weight_ptr) + + cdef SIZE_t start + cdef SIZE_t end + cdef SIZE_t depth + cdef SIZE_t parent + cdef bint is_left + cdef SIZE_t n_node_samples = splitter.n_samples + cdef double weighted_n_samples = splitter.weighted_n_samples + cdef double weighted_n_node_samples + cdef SplitRecord split + cdef SIZE_t node_id - # post condition: all samples from [0:b) are on the left side - for idx from a <= idx < b: - s = X_argsorted_i[idx] + cdef double threshold + cdef double impurity = INFINITY + cdef SIZE_t n_constant_features + cdef bint is_leaf + cdef bint first = 1 + cdef SIZE_t max_depth_seen = -1 + cdef int rc = 0 + + cdef Stack stack = Stack(INITIAL_STACK_SIZE) + cdef StackRecord stack_record + + # push root node onto stack + rc = stack.push(0, n_node_samples, 0, _TREE_UNDEFINED, 0, INFINITY, 0) + if rc == -1: + # got return code -1 - out-of-memory + raise MemoryError() - if sample_mask[s] == 0: - continue + with nogil: + while not stack.is_empty(): + stack.pop(&stack_record) - for k from 0 <= k < n_outputs: - c = y[s * y_stride + k] - label_count_right[k * label_count_stride + c] -= 1 - label_count_left[k * label_count_stride + c] += 1 + start = stack_record.start + end = stack_record.end + depth = stack_record.depth + parent = stack_record.parent + is_left = stack_record.is_left + impurity = stack_record.impurity + n_constant_features = stack_record.n_constant_features - n_left += 1 - n_right -=1 + n_node_samples = end - start + splitter.node_reset(start, end, &weighted_n_node_samples) - self.n_left = n_left - self.n_right = n_right + is_leaf = ((depth >= max_depth) or + (n_node_samples < min_samples_split) or + (n_node_samples < 2 * min_samples_leaf) or + (weighted_n_node_samples < min_weight_leaf)) - return n_left + if first: + impurity = splitter.node_impurity() + first = 0 - cdef double eval(self): - """Evaluate the criteria (aka the split error).""" - pass + is_leaf = is_leaf or (impurity <= MIN_IMPURITY_SPLIT) - cdef void init_value(self, double* buffer_value): - """Get the initial value of the criterion (`init` must be called - before).""" - cdef int n_outputs = self.n_outputs - cdef int* n_classes = self.n_classes - cdef int label_count_stride = self.label_count_stride - cdef int* label_count_init = self.label_count_init + if not is_leaf: + splitter.node_split(impurity, &split, &n_constant_features) + is_leaf = is_leaf or (split.pos >= end) - cdef int k, c + node_id = tree._add_node(parent, is_left, is_leaf, split.feature, + split.threshold, impurity, n_node_samples, + weighted_n_node_samples) - for k from 0 <= k < n_outputs: - for c from 0 <= c < n_classes[k]: - buffer_value[k * label_count_stride + c] = label_count_init[k * label_count_stride + c] + if is_leaf: + # Don't store value for internal nodes + splitter.node_value(tree.value + + node_id * tree.value_stride) + else: + # Push right child on stack + rc = stack.push(split.pos, end, depth + 1, node_id, 0, + split.impurity_right, n_constant_features) + if rc == -1: + break -cdef class Gini(ClassificationCriterion): - """Gini Index splitting criteria. + # Push left child on stack + rc = stack.push(start, split.pos, depth + 1, node_id, 1, + split.impurity_left, n_constant_features) + if rc == -1: + break - Let the target be a classification outcome taking values in 0, 1, ..., K-1. - If node m represents a region Rm with Nm observations, then let + if depth > max_depth_seen: + max_depth_seen = depth - pmk = 1/ Nm \sum_{x_i in Rm} I(yi = k) + if rc >= 0: + rc = tree._resize_c(tree.node_count) - be the proportion of class k observations in node m. + if rc >= 0: + tree.max_depth = max_depth_seen + if rc == -1: + raise MemoryError() - The Gini Index is then defined as: - index = \sum_{k=0}^{K-1} pmk (1 - pmk) - = 1 - \sum_{k=0}^{K-1} pmk ** 2 - """ +# Best first builder ---------------------------------------------------------- - cdef double eval(self): - """Returns Gini index of left branch + Gini index of right branch.""" - cdef int n_samples = self.n_samples - cdef int n_outputs = self.n_outputs - cdef int* n_classes = self.n_classes - cdef int label_count_stride = self.label_count_stride - cdef int* label_count_left = self.label_count_left - cdef int* label_count_right = self.label_count_right - cdef double n_left = self.n_left - cdef double n_right = self.n_right +cdef inline int _add_to_frontier(PriorityHeapRecord* rec, + PriorityHeap frontier) nogil: + """Adds record ``rec`` to the priority queue ``frontier``; returns -1 + on memory-error. """ + return frontier.push(rec.node_id, rec.start, rec.end, rec.pos, rec.depth, + rec.is_leaf, rec.improvement, rec.impurity, + rec.impurity_left, rec.impurity_right) - cdef double total = 0.0 - cdef double H_left - cdef double H_right - cdef int k, c, count_left, count_right - for k from 0 <= k < n_outputs: - H_left = n_left * n_left - H_right = n_right * n_right +cdef class BestFirstTreeBuilder(TreeBuilder): + """Build a decision tree in best-first fashion. - for c from 0 <= c < n_classes[k]: - count_left = label_count_left[k * label_count_stride + c] - if count_left > 0: - H_left -= (count_left * count_left) + The best node to expand is given by the node at the frontier that has the + highest impurity improvement. - count_right = label_count_right[k * label_count_stride + c] - if count_right > 0: - H_right -= (count_right * count_right) + NOTE: this TreeBuilder will ignore ``tree.max_depth`` . + """ + cdef SIZE_t max_leaf_nodes - if n_left == 0: - H_left = 0 - else: - H_left /= n_left + def __cinit__(self, Splitter splitter, SIZE_t min_samples_split, + SIZE_t min_samples_leaf, min_weight_leaf, + SIZE_t max_depth, SIZE_t max_leaf_nodes): + self.splitter = splitter + self.min_samples_split = min_samples_split + self.min_samples_leaf = min_samples_leaf + self.min_weight_leaf = min_weight_leaf + self.max_depth = max_depth + self.max_leaf_nodes = max_leaf_nodes - if n_right == 0: - H_right = 0 - else: - H_right /= n_right + cpdef build(self, Tree tree, object X, np.ndarray y, + np.ndarray sample_weight=None): + """Build a decision tree from the training set (X, y).""" - total += (H_left + H_right) + # check input + X, y, sample_weight = self._check_input(X, y, sample_weight) - return total / (n_samples * n_outputs) + cdef DOUBLE_t* sample_weight_ptr = NULL + if sample_weight is not None: + sample_weight_ptr = sample_weight.data + # Parameters + cdef Splitter splitter = self.splitter + cdef SIZE_t max_leaf_nodes = self.max_leaf_nodes + cdef SIZE_t min_samples_leaf = self.min_samples_leaf + cdef double min_weight_leaf = self.min_weight_leaf + cdef SIZE_t min_samples_split = self.min_samples_split + + # Recursive partition (without actual recursion) + splitter.init(X, y, sample_weight_ptr) + + cdef PriorityHeap frontier = PriorityHeap(INITIAL_STACK_SIZE) + cdef PriorityHeapRecord record + cdef PriorityHeapRecord split_node_left + cdef PriorityHeapRecord split_node_right + + cdef SIZE_t n_node_samples = splitter.n_samples + cdef SIZE_t max_split_nodes = max_leaf_nodes - 1 + cdef bint is_leaf + cdef SIZE_t max_depth_seen = -1 + cdef int rc = 0 + cdef Node* node + + # Initial capacity + cdef SIZE_t init_capacity = max_split_nodes + max_leaf_nodes + tree._resize(init_capacity) + + with nogil: + # add root to frontier + rc = self._add_split_node(splitter, tree, 0, n_node_samples, + INFINITY, IS_FIRST, IS_LEFT, NULL, 0, + &split_node_left) + if rc >= 0: + rc = _add_to_frontier(&split_node_left, frontier) + if rc == -1: + raise MemoryError() -cdef class Entropy(ClassificationCriterion): - """Cross Entropy splitting criteria. + with nogil: + while not frontier.is_empty(): + frontier.pop(&record) - Let the target be a classification outcome taking values in 0, 1, ..., K-1. - If node m represents a region Rm with Nm observations, then let + node = &tree.nodes[record.node_id] + is_leaf = (record.is_leaf or max_split_nodes <= 0) - pmk = 1/ Nm \sum_{x_i in Rm} I(yi = k) + if is_leaf: + # Node is not expandable; set node as leaf + node.left_child = _TREE_LEAF + node.right_child = _TREE_LEAF + node.feature = _TREE_UNDEFINED + node.threshold = _TREE_UNDEFINED - be the proportion of class k observations in node m. + else: + # Node is expandable + + # Decrement number of split nodes available + max_split_nodes -= 1 + + # Compute left split node + rc = self._add_split_node(splitter, tree, + record.start, record.pos, + record.impurity_left, + IS_NOT_FIRST, IS_LEFT, node, + record.depth + 1, + &split_node_left) + if rc == -1: + break - The cross-entropy is then defined as + # tree.nodes may have changed + node = &tree.nodes[record.node_id] + + # Compute right split node + rc = self._add_split_node(splitter, tree, record.pos, + record.end, + record.impurity_right, + IS_NOT_FIRST, IS_NOT_LEFT, node, + record.depth + 1, + &split_node_right) + if rc == -1: + break - cross-entropy = - \sum_{k=0}^{K-1} pmk log(pmk) - """ + # Add nodes to queue + rc = _add_to_frontier(&split_node_left, frontier) + if rc == -1: + break - cdef double eval(self): - """Returns Entropy of left branch + Entropy index of right branch. """ - cdef int n_samples = self.n_samples - cdef int n_outputs = self.n_outputs - cdef int* n_classes = self.n_classes - cdef int label_count_stride = self.label_count_stride - cdef int* label_count_left = self.label_count_left - cdef int* label_count_right = self.label_count_right - cdef double n_left = self.n_left - cdef double n_right = self.n_right + rc = _add_to_frontier(&split_node_right, frontier) + if rc == -1: + break - cdef double total = 0.0 - cdef double H_left - cdef double H_right - cdef int k, c - cdef double e1, e2 + if record.depth > max_depth_seen: + max_depth_seen = record.depth - for k from 0 <= k < n_outputs: - H_left = 0.0 - H_right = 0.0 + if rc >= 0: + rc = tree._resize_c(tree.node_count) - for c from 0 <= c < n_classes[k]: - if label_count_left[k * label_count_stride + c] > 0: - H_left -= ((label_count_left[k * label_count_stride + c] / n_left) * log(label_count_left[k * label_count_stride + c] / n_left)) + if rc >= 0: + tree.max_depth = max_depth_seen - if self.label_count_right[k * label_count_stride + c] > 0: - H_right -= ((label_count_right[k * label_count_stride + c] / n_right) * log(label_count_right[k * label_count_stride + c] / n_right)) + if rc == -1: + raise MemoryError() - e1 = (n_left / n_samples) * H_left - e2 = (n_right / n_samples) * H_right + cdef inline int _add_split_node(self, Splitter splitter, Tree tree, + SIZE_t start, SIZE_t end, double impurity, + bint is_first, bint is_left, Node* parent, + SIZE_t depth, + PriorityHeapRecord* res) nogil: + """Adds node w/ partition ``[start, end)`` to the frontier. """ + cdef SplitRecord split + cdef SIZE_t node_id + cdef SIZE_t n_node_samples + cdef SIZE_t n_constant_features = 0 + cdef double weighted_n_samples = splitter.weighted_n_samples + cdef double weighted_n_node_samples + cdef bint is_leaf + cdef SIZE_t n_left, n_right + cdef double imp_diff + + splitter.node_reset(start, end, &weighted_n_node_samples) + + if is_first: + impurity = splitter.node_impurity() + + n_node_samples = end - start + is_leaf = ((depth > self.max_depth) or + (n_node_samples < self.min_samples_split) or + (n_node_samples < 2 * self.min_samples_leaf) or + (weighted_n_node_samples < self.min_weight_leaf) or + (impurity <= MIN_IMPURITY_SPLIT)) + + if not is_leaf: + splitter.node_split(impurity, &split, &n_constant_features) + is_leaf = is_leaf or (split.pos >= end) + + node_id = tree._add_node(parent - tree.nodes + if parent != NULL + else _TREE_UNDEFINED, + is_left, is_leaf, + split.feature, split.threshold, impurity, n_node_samples, + weighted_n_node_samples) + if node_id == (-1): + return -1 + + # compute values also for split nodes (might become leafs later). + splitter.node_value(tree.value + node_id * tree.value_stride) + + res.node_id = node_id + res.start = start + res.end = end + res.depth = depth + res.impurity = impurity + + if not is_leaf: + # is split node + res.pos = split.pos + res.is_leaf = 0 + res.improvement = split.improvement + res.impurity_left = split.impurity_left + res.impurity_right = split.impurity_right - total += e1 + e2 + else: + # is leaf => 0 improvement + res.pos = end + res.is_leaf = 1 + res.improvement = 0.0 + res.impurity_left = impurity + res.impurity_right = impurity - return total / n_outputs + return 0 -cdef class RegressionCriterion(Criterion): - """Abstract criterion for regression. +# ============================================================================= +# Tree +# ============================================================================= - Computes variance of the target values left and right of the split point. - Computation is linear in `n_samples` by using :: +cdef class Tree: + """Array-based representation of a binary decision tree. - var = \sum_i^n (y_i - y_bar) ** 2 - = (\sum_i^n y_i ** 2) - n_samples y_bar ** 2 + The binary tree is represented as a number of parallel arrays. The i-th + element of each array holds information about the node `i`. Node 0 is the + tree's root. You can find a detailed description of all arrays in + `_tree.pxd`. NOTE: Some of the arrays only apply to either leaves or split + nodes, resp. In this case the values of nodes of the other type are + arbitrary! Attributes ---------- - n_outputs : int - The number of outputs. + node_count : int + The number of nodes (internal nodes + leaves) in the tree. - n_samples : int - The number of samples + capacity : int + The current capacity (i.e., size) of the arrays, which is at least as + great as `node_count`. + + max_depth : int + The maximal depth of the tree. - mean_left : double* - mean_left[k] is the mean target value of the samples left of the split - point for output k. + children_left : array of int, shape [node_count] + children_left[i] holds the node id of the left child of node i. + For leaves, children_left[i] == TREE_LEAF. Otherwise, + children_left[i] > i. This child handles the case where + X[:, feature[i]] <= threshold[i]. - mean_right : double* - mean_right[k] is the mean target value of the samples right of the split - point for output k. + children_right : array of int, shape [node_count] + children_right[i] holds the node id of the right child of node i. + For leaves, children_right[i] == TREE_LEAF. Otherwise, + children_right[i] > i. This child handles the case where + X[:, feature[i]] > threshold[i]. - sq_sum_left : double* - sq_sum_left[k] is the sum of squared target values left of the split - point for output k. + feature : array of int, shape [node_count] + feature[i] holds the feature to split on, for the internal node i. - sq_sum_right : double* - sq_sum_right[k] is the sum of squared target values right of the split - point for output k. + threshold : array of double, shape [node_count] + threshold[i] holds the threshold for the internal node i. - var_left : double* - var_left[k] is the variance of the values left of the split point for - output k. + value : array of double, shape [node_count, n_outputs, max_n_classes] + Contains the constant prediction value of each node. - var_right : double* - var_right[k] is the variance of the values riht of the split point for - output k. + impurity : array of double, shape [node_count] + impurity[i] holds the impurity (i.e., the value of the splitting + criterion) at node i. - n_left : int - number of samples left of split point. + n_node_samples : array of int, shape [node_count] + n_node_samples[i] holds the number of training samples reaching node i. - n_right : int - number of samples right of split point. + weighted_n_node_samples : array of int, shape [node_count] + weighted_n_node_samples[i] holds the weighted number of training samples + reaching node i. """ + # Wrap for outside world. + # WARNING: these reference the current `nodes` and `value` buffers, which + # must not be be freed by a subsequent memory allocation. + # (i.e. through `_resize` or `__setstate__`) + property n_classes: + def __get__(self): + # it's small; copy for memory safety + return sizet_ptr_to_ndarray(self.n_classes, self.n_outputs).copy() + + property children_left: + def __get__(self): + return self._get_node_ndarray()['left_child'][:self.node_count] - cdef int n_outputs - cdef int n_samples + property children_right: + def __get__(self): + return self._get_node_ndarray()['right_child'][:self.node_count] - cdef double* mean_left - cdef double* mean_right - cdef double* mean_init - cdef double* sq_sum_left - cdef double* sq_sum_right - cdef double* sq_sum_init - cdef double* var_left - cdef double* var_right + property feature: + def __get__(self): + return self._get_node_ndarray()['feature'][:self.node_count] - cdef int n_right - cdef int n_left + property threshold: + def __get__(self): + return self._get_node_ndarray()['threshold'][:self.node_count] - def __cinit__(self, int n_outputs): - """Constructor.""" - cdef int k = 0 + property impurity: + def __get__(self): + return self._get_node_ndarray()['impurity'][:self.node_count] + property n_node_samples: + def __get__(self): + return self._get_node_ndarray()['n_node_samples'][:self.node_count] + + property weighted_n_node_samples: + def __get__(self): + return self._get_node_ndarray()['weighted_n_node_samples'][:self.node_count] + + property value: + def __get__(self): + return self._get_value_ndarray()[:self.node_count] + + def __cinit__(self, int n_features, np.ndarray[SIZE_t, ndim=1] n_classes, + int n_outputs): + """Constructor.""" + # Input/Output layout + self.n_features = n_features self.n_outputs = n_outputs + self.n_classes = NULL + safe_realloc(&self.n_classes, n_outputs) - self.n_samples = 0 - self.n_left = 0 - self.n_right = 0 + self.max_n_classes = np.max(n_classes) + self.value_stride = n_outputs * self.max_n_classes - # Allocate - self.mean_left = calloc(n_outputs, sizeof(double)) - self.mean_right = calloc(n_outputs, sizeof(double)) - self.mean_init = calloc(n_outputs, sizeof(double)) - self.sq_sum_left = calloc(n_outputs, sizeof(double)) - self.sq_sum_right = calloc(n_outputs, sizeof(double)) - self.sq_sum_init = calloc(n_outputs, sizeof(double)) - self.var_left = calloc(n_outputs, sizeof(double)) - self.var_right = calloc(n_outputs, sizeof(double)) + cdef SIZE_t k + for k in range(n_outputs): + self.n_classes[k] = n_classes[k] - # Check for allocation errors - if self.mean_left == NULL or \ - self.mean_right == NULL or \ - self.mean_init == NULL or \ - self.sq_sum_left == NULL or \ - self.sq_sum_right == NULL or \ - self.sq_sum_init == NULL or \ - self.var_left == NULL or \ - self.var_right == NULL: - free(self.mean_left) - free(self.mean_right) - free(self.mean_init) - free(self.sq_sum_left) - free(self.sq_sum_right) - free(self.sq_sum_init) - free(self.var_left) - free(self.var_right) - raise MemoryError() + # Inner structures + self.max_depth = 0 + self.node_count = 0 + self.capacity = 0 + self.value = NULL + self.nodes = NULL def __dealloc__(self): """Destructor.""" - free(self.mean_left) - free(self.mean_right) - free(self.mean_init) - free(self.sq_sum_left) - free(self.sq_sum_right) - free(self.sq_sum_init) - free(self.var_left) - free(self.var_right) + # Free all inner structures + free(self.n_classes) + free(self.value) + free(self.nodes) def __reduce__(self): - return (RegressionCriterion, - (self.n_outputs,), - self.__getstate__()) + """Reduce re-implementation, for pickling.""" + return (Tree, (self.n_features, + sizet_ptr_to_ndarray(self.n_classes, self.n_outputs), + self.n_outputs), self.__getstate__()) def __getstate__(self): - return {} + """Getstate re-implementation, for pickling.""" + d = {} + d["node_count"] = self.node_count + d["nodes"] = self._get_node_ndarray() + d["values"] = self._get_value_ndarray() + return d def __setstate__(self, d): - pass + """Setstate re-implementation, for unpickling.""" + self.node_count = d["node_count"] - cdef void init(self, DOUBLE_t* y, int y_stride, BOOL_t* sample_mask, - int n_samples, int n_total_samples): - """Initialise the criterion class; assume all samples - are in the right branch and store the mean and squared - sum in `self.mean_init` and `self.sq_sum_init`. """ - cdef double* mean_left = self.mean_left - cdef double* mean_right = self.mean_right - cdef double* mean_init = self.mean_init - cdef double* sq_sum_left = self.sq_sum_left - cdef double* sq_sum_right = self.sq_sum_right - cdef double* sq_sum_init = self.sq_sum_init - cdef double* var_left = self.var_left - cdef double* var_right = self.var_right - cdef int n_outputs = self.n_outputs + if 'nodes' not in d: + raise ValueError('You have loaded Tree version which ' + 'cannot be imported') + + node_ndarray = d['nodes'] + value_ndarray = d['values'] + + value_shape = (node_ndarray.shape[0], self.n_outputs, + self.max_n_classes) + if (node_ndarray.ndim != 1 or + node_ndarray.dtype != NODE_DTYPE or + not node_ndarray.flags.c_contiguous or + value_ndarray.shape != value_shape or + not value_ndarray.flags.c_contiguous or + value_ndarray.dtype != np.float64): + raise ValueError('Did not recognise loaded array layout') + + self.capacity = node_ndarray.shape[0] + if self._resize_c(self.capacity) != 0: + raise MemoryError("resizing tree to %d" % self.capacity) + nodes = memcpy(self.nodes, ( node_ndarray).data, + self.capacity * sizeof(Node)) + value = memcpy(self.value, ( value_ndarray).data, + self.capacity * self.value_stride * sizeof(double)) + + cdef void _resize(self, SIZE_t capacity) except *: + """Resize all inner arrays to `capacity`, if `capacity` == -1, then + double the size of the inner arrays.""" + if self._resize_c(capacity) != 0: + raise MemoryError() - cdef int k = 0 + # XXX using (size_t)(-1) is ugly, but SIZE_MAX is not available in C89 + # (i.e., older MSVC). + cdef int _resize_c(self, SIZE_t capacity=(-1)) nogil: + """Guts of _resize. Returns 0 for success, -1 for error.""" + if capacity == self.capacity and self.nodes != NULL: + return 0 - for k from 0 <= k < n_outputs: - mean_left[k] = 0.0 - mean_right[k] = 0.0 - mean_init[k] = 0.0 - sq_sum_right[k] = 0.0 - sq_sum_left[k] = 0.0 - sq_sum_init[k] = 0.0 - var_left[k] = 0.0 - var_right[k] = 0.0 + if capacity == (-1): + if self.capacity == 0: + capacity = 3 # default initial value + else: + capacity = 2 * self.capacity - self.n_samples = n_samples + # XXX no safe_realloc here because we need to grab the GIL + cdef void* ptr = realloc(self.nodes, capacity * sizeof(Node)) + if ptr == NULL: + return -1 + self.nodes = ptr + ptr = realloc(self.value, + capacity * self.value_stride * sizeof(double)) + if ptr == NULL: + return -1 + self.value = ptr + + # value memory is initialised to 0 to enable classifier argmax + if capacity > self.capacity: + memset((self.value + self.capacity * self.value_stride), 0, + (capacity - self.capacity) * self.value_stride * + sizeof(double)) - cdef int j = 0 - cdef DOUBLE_t y_jk = 0.0 + # if capacity smaller than node_count, adjust the counter + if capacity < self.node_count: + self.node_count = capacity - for j from 0 <= j < n_total_samples: - if sample_mask[j] == 0: - continue + self.capacity = capacity + return 0 - for k from 0 <= k < n_outputs: - y_jk = y[j * y_stride + k] - sq_sum_init[k] += y_jk * y_jk - mean_init[k] += y_jk + 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: + """Add a node to the tree. - for k from 0 <= k < n_outputs: - mean_init[k] /= n_samples + The new node registers itself as the child of its parent. - self.reset() + Returns (size_t)(-1) on error. + """ + cdef SIZE_t node_id = self.node_count - cdef void reset(self): - """Reset criterion for new feature. + if node_id >= self.capacity: + if self._resize_c() != 0: + return (-1) - Assume all data in right branch and copy statistics of the - whole dataset into the auxiliary variables of the - right branch. - """ - cdef double* mean_left = self.mean_left - cdef double* mean_right = self.mean_right - cdef double* mean_init = self.mean_init - cdef double* sq_sum_left = self.sq_sum_left - cdef double* sq_sum_right = self.sq_sum_right - cdef double* sq_sum_init = self.sq_sum_init - cdef double* var_left = self.var_left - cdef double* var_right = self.var_right + cdef Node* node = &self.nodes[node_id] + node.impurity = impurity + node.n_node_samples = n_node_samples + node.weighted_n_node_samples = weighted_n_node_samples - cdef int n_samples = self.n_samples - cdef int n_outputs = self.n_outputs + if parent != _TREE_UNDEFINED: + if is_left: + self.nodes[parent].left_child = node_id + else: + self.nodes[parent].right_child = node_id - cdef int k = 0 + if is_leaf: + node.left_child = _TREE_LEAF + node.right_child = _TREE_LEAF + node.feature = _TREE_UNDEFINED + node.threshold = _TREE_UNDEFINED - self.n_right = self.n_samples - self.n_left = 0 + else: + # left_child and right_child will be set later + node.feature = feature + node.threshold = threshold - for k from 0 <= k < n_outputs: - mean_right[k] = mean_init[k] - mean_left[k] = 0.0 - sq_sum_right[k] = sq_sum_init[k] - sq_sum_left[k] = 0.0 - var_left[k] = 0.0 - var_right[k] = sq_sum_right[k] - n_samples * (mean_right[k] * mean_right[k]) + self.node_count += 1 - cdef int update(self, int a, int b, DOUBLE_t* y, int y_stride, - int* X_argsorted_i, BOOL_t* sample_mask): - """Update the criteria for each value in interval [a,b) (where a and b - are indices in `X_argsorted_i`).""" - cdef double* mean_left = self.mean_left - cdef double* mean_right = self.mean_right - cdef double* sq_sum_left = self.sq_sum_left - cdef double* sq_sum_right = self.sq_sum_right - cdef double* var_left = self.var_left - cdef double* var_right = self.var_right + return node_id - cdef int n_samples = self.n_samples - cdef int n_outputs = self.n_outputs - cdef int n_left = self.n_left - cdef int n_right = self.n_right + cpdef np.ndarray predict(self, object X): + """Predict target for X.""" + out = self._get_value_ndarray().take(self.apply(X), axis=0, + mode='clip') + if self.n_outputs == 1: + out = out.reshape(X.shape[0], self.max_n_classes) + return out - cdef double y_idx = 0.0 - cdef int idx, j, k + cpdef np.ndarray apply(self, object X): + """Finds the terminal region (=leaf node) for each sample in X.""" + if issparse(X): + return self._apply_sparse_csr(X) + else: + return self._apply_dense(X) - # post condition: all samples from [0:b) are on the left side - for idx from a <= idx < b: - j = X_argsorted_i[idx] - if sample_mask[j] == 0: - continue + cdef inline np.ndarray _apply_dense(self, object X): + """Finds the terminal region (=leaf node) for each sample in X.""" - for k from 0 <= k < n_outputs: - y_idx = y[j * y_stride + k] - sq_sum_left[k] += (y_idx * y_idx) - sq_sum_right[k] -= (y_idx * y_idx) + # Check input + if not isinstance(X, np.ndarray): + raise ValueError("X should be in np.ndarray format, got %s" + % type(X)) + + if X.dtype != DTYPE: + raise ValueError("X.dtype should be np.float32, got %s" % X.dtype) + + # Extract input + cdef np.ndarray X_ndarray = X + cdef DTYPE_t* X_ptr = X_ndarray.data + cdef SIZE_t X_sample_stride = X.strides[0] / X.itemsize + cdef SIZE_t X_fx_stride = X.strides[1] / X.itemsize + cdef SIZE_t n_samples = X.shape[0] + + # Initialize output + cdef np.ndarray[SIZE_t] out = np.zeros((n_samples,), dtype=np.intp) + cdef SIZE_t* out_ptr = out.data + + # Initialize auxiliary data-structure + cdef Node* node = NULL + cdef SIZE_t i = 0 + + with nogil: + for i in range(n_samples): + node = self.nodes + # While node not a leaf + while node.left_child != _TREE_LEAF: + # ... and node.right_child != _TREE_LEAF: + if X_ptr[X_sample_stride * i + + X_fx_stride * node.feature] <= node.threshold: + node = &self.nodes[node.left_child] + else: + node = &self.nodes[node.right_child] - mean_left[k] = (n_left * mean_left[k] + y_idx) / (n_left + 1) - mean_right[k] = ((n_samples - n_left) * mean_right[k] - y_idx) / (n_samples - n_left - 1) + out_ptr[i] = (node - self.nodes) # node offset - n_left += 1 - self.n_left = n_left - n_right -= 1 - self.n_right = n_right + return out - for k from 0 <= k < n_outputs: - var_left[k] = sq_sum_left[k] - n_left * (mean_left[k] * mean_left[k]) - var_right[k] = sq_sum_right[k] - n_right * (mean_right[k] * mean_right[k]) + cdef inline np.ndarray _apply_sparse_csr(self, object X): + """Finds the terminal region (=leaf node) for each sample in sparse X. - return n_left + """ + # Check input + if not isinstance(X, csr_matrix): + raise ValueError("X should be in csr_matrix format, got %s" + % type(X)) + + if X.dtype != DTYPE: + raise ValueError("X.dtype should be np.float32, got %s" % X.dtype) + + # Extract input + cdef np.ndarray[ndim=1, dtype=DTYPE_t] X_data_ndarray = X.data + cdef np.ndarray[ndim=1, dtype=INT32_t] X_indices_ndarray = X.indices + cdef np.ndarray[ndim=1, dtype=INT32_t] X_indptr_ndarray = X.indptr + + cdef DTYPE_t* X_data = X_data_ndarray.data + cdef INT32_t* X_indices = X_indices_ndarray.data + cdef INT32_t* X_indptr = X_indptr_ndarray.data + + cdef SIZE_t n_samples = X.shape[0] + cdef SIZE_t n_features = X.shape[1] + + # Initialize output + cdef np.ndarray[SIZE_t, ndim=1] out = np.zeros((n_samples,), + dtype=np.intp) + cdef SIZE_t* out_ptr = out.data + + # Initialize auxiliary data-structure + cdef DTYPE_t feature_value = 0. + cdef Node* node = NULL + cdef DTYPE_t* X_sample = NULL + cdef SIZE_t i = 0 + cdef INT32_t k = 0 + + # feature_to_sample as a data structure records the last seen sample + # for each feature; functionally, it is an efficient way to identify + # which features are nonzero in the present sample. + cdef SIZE_t* feature_to_sample = NULL + + safe_realloc(&X_sample, n_features * sizeof(DTYPE_t)) + safe_realloc(&feature_to_sample, n_features * sizeof(SIZE_t)) + + with nogil: + memset(feature_to_sample, -1, n_features * sizeof(SIZE_t)) + + for i in range(n_samples): + node = self.nodes + + for k in range(X_indptr[i], X_indptr[i + 1]): + feature_to_sample[X_indices[k]] = i + X_sample[X_indices[k]] = X_data[k] + + # While node not a leaf + while node.left_child != _TREE_LEAF: + # ... and node.right_child != _TREE_LEAF: + if feature_to_sample[node.feature] == i: + feature_value = X_sample[node.feature] - cdef double eval(self): - """Evaluate the criteria (aka the split error).""" - pass + else: + feature_value = 0. - cdef void init_value(self, double* buffer_value): - """Get the initial value of the criterion (`init` must be called - before).""" - cdef int n_outputs = self.n_outputs - cdef double* mean_init = self.mean_init + if feature_value <= node.threshold: + node = &self.nodes[node.left_child] + else: + node = &self.nodes[node.right_child] - cdef int k + out_ptr[i] = (node - self.nodes) # node offset - for k from 0 <= k < n_outputs: - buffer_value[k] = mean_init[k] + # Free auxiliary arrays + free(X_sample) + free(feature_to_sample) + return out -cdef class MSE(RegressionCriterion): - """Mean squared error impurity criterion. + cpdef compute_feature_importances(self, normalize=True): + """Computes the importance of each feature (aka variable).""" + cdef Node* left + cdef Node* right + cdef Node* nodes = self.nodes + cdef Node* node = nodes + cdef Node* end_node = node + self.node_count - MSE = var_left + var_right - """ + cdef double normalizer = 0. - cdef double eval(self): - cdef double* var_left = self.var_left - cdef double* var_right = self.var_right + cdef np.ndarray[np.float64_t, ndim=1] importances + importances = np.zeros((self.n_features,)) + cdef DOUBLE_t* importance_data = importances.data - cdef int n_outputs = self.n_outputs + with nogil: + while node != end_node: + if node.left_child != _TREE_LEAF: + # ... and node.right_child != _TREE_LEAF: + left = &nodes[node.left_child] + right = &nodes[node.right_child] - cdef int k - cdef double total = 0.0 + importance_data[node.feature] += ( + node.weighted_n_node_samples * node.impurity - + left.weighted_n_node_samples * left.impurity - + right.weighted_n_node_samples * right.impurity) + node += 1 - for k from 0 <= k < n_outputs: - total += var_left[k] - total += var_right[k] + importances /= nodes[0].weighted_n_node_samples - return total / n_outputs + if normalize: + normalizer = np.sum(importances) + if normalizer > 0.0: + # Avoid dividing by zero (e.g., when root is pure) + importances /= normalizer -# ============================================================================== -# Utils -# ============================================================================== + return importances -cdef inline np.ndarray intp_to_ndarray(int* data, int size): - """Encapsulate data into a 1D numpy array of int's.""" - cdef np.npy_intp shape[1] - shape[0] = size - return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INT, data) + cdef np.ndarray _get_value_ndarray(self): + """Wraps value as a 3-d NumPy array -cdef inline np.ndarray doublep_to_ndarray(double* data, int size): - """Encapsulate data into a 1D numpy array of double's.""" + The array keeps a reference to this Tree, which manages the underlying + memory. + """ + cdef np.npy_intp shape[3] + shape[0] = self.node_count + shape[1] = self.n_outputs + shape[2] = self.max_n_classes + cdef np.ndarray arr + arr = np.PyArray_SimpleNewFromData(3, shape, np.NPY_DOUBLE, self.value) + Py_INCREF(self) + arr.base = self + return arr + + cdef np.ndarray _get_node_ndarray(self): + """Wraps nodes as a NumPy struct array + + The array keeps a reference to this Tree, which manages the underlying + memory. Individual fields are publicly accessible as properties of the + Tree. + """ + cdef np.npy_intp shape[1] + shape[0] = self.node_count + cdef np.npy_intp strides[1] + strides[0] = sizeof(Node) + cdef np.ndarray arr + Py_INCREF(NODE_DTYPE) + arr = PyArray_NewFromDescr(np.ndarray, NODE_DTYPE, 1, shape, + strides, self.nodes, + np.NPY_DEFAULT, None) + Py_INCREF(self) + arr.base = self + return arr + +# ============================================================================= +# Utils +# ============================================================================= + +# safe_realloc(&p, n) resizes the allocation of p to n * sizeof(*p) bytes or +# raises a MemoryError. It never calls free, since that's __dealloc__'s job. +# cdef DTYPE_t *p = NULL +# safe_realloc(&p, n) +# is equivalent to p = malloc(n * sizeof(*p)) with error checking. +ctypedef fused realloc_ptr: + # Add pointer types here as needed. + (DTYPE_t*) + (SIZE_t*) + (unsigned char*) + +cdef realloc_ptr safe_realloc(realloc_ptr* p, size_t nelems) except *: + # 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]) + if nbytes / sizeof(p[0][0]) != nelems: + # Overflow in the multiplication + raise MemoryError("could not allocate (%d * %d) bytes" + % (nelems, sizeof(p[0][0]))) + cdef realloc_ptr tmp = realloc(p[0], nbytes) + if tmp == NULL: + raise MemoryError("could not allocate %d bytes" % nbytes) + + p[0] = tmp + return tmp # for convenience + + +def _realloc_test(): + # Helper for tests. Tries to allocate (-1) / 2 * sizeof(size_t) + # bytes, which will always overflow. + cdef SIZE_t* p = NULL + safe_realloc(&p, (-1) / 2) + if p != NULL: + free(p) + assert False + + +# rand_r replacement using a 32bit XorShift generator +# See http://www.jstatsoft.org/v08/i14/paper for details +cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil: + seed[0] ^= (seed[0] << 13) + seed[0] ^= (seed[0] >> 17) + seed[0] ^= (seed[0] << 5) + + return seed[0] % (RAND_R_MAX + 1) + +cdef inline np.ndarray sizet_ptr_to_ndarray(SIZE_t* data, SIZE_t size): + """Encapsulate data into a 1D numpy array of intp's.""" cdef np.npy_intp shape[1] shape[0] = size - return np.PyArray_SimpleNewFromData(1, shape, np.NPY_DOUBLE, data) - -cdef inline int _smallest_sample_larger_than(int sample_idx, - DTYPE_t* X_i, - int* X_argsorted_i, - BOOL_t* sample_mask, - int n_total_samples): - """Find the largest next sample. - - Find the index in the `X_i` array for sample who's feature - `i` value is just about greater than those of the sample - `X_argsorted_i[sample_idx]`. - - Returns - ------- - next_sample_idx : int - The index of the next smallest sample in `X_argsorted` - with different feature value than `sample_idx` . - I.e. `X_argsorted_i[sample_idx] < X_argsorted_i[next_sample_idx]` - -1 if no such element exists. - """ - cdef int idx = 0, j - cdef DTYPE_t threshold = -DBL_MAX - - if sample_idx > -1: - threshold = X_i[X_argsorted_i[sample_idx]] - - for idx from sample_idx < idx < n_total_samples: - j = X_argsorted_i[idx] + return np.PyArray_SimpleNewFromData(1, shape, np.NPY_INTP, data) - if sample_mask[j] == 0: - continue +cdef inline SIZE_t rand_int(SIZE_t low, SIZE_t high, + UINT32_t* random_state) nogil: + """Generate a random integer in [0; end).""" + return low + our_rand_r(random_state) % (high - low) - if X_i[j] > threshold + 1.e-7: - return idx - - return -1 - -def _random_sample_mask(int n_total_samples, int n_total_in_bag, random_state): - """Create a random sample mask where ``n_total_in_bag`` elements are set. - - Parameters - ---------- - n_total_samples : int - The length of the resulting mask. - - n_total_in_bag : int - The number of elements in the sample mask which are set to 1. - - random_state : np.RandomState - A numpy ``RandomState`` object. - - Returns - ------- - sample_mask : np.ndarray, shape=[n_total_samples] - An ndarray where ``n_total_in_bag`` elements are set to ``True`` - the others are ``False``. - """ - cdef np.ndarray[np.float64_t, ndim=1, mode="c"] rand = \ - random_state.rand(n_total_samples) - cdef np.ndarray[BOOL_t, ndim=1, mode="c"] sample_mask = \ - np.zeros((n_total_samples,), dtype=np.int8) +cdef inline double rand_uniform(double low, double high, + UINT32_t* random_state) nogil: + """Generate a random double in [low; high).""" + return ((high - low) * our_rand_r(random_state) / + RAND_R_MAX) + low - cdef int n_bagged = 0 - cdef int i = 0 +cdef inline double log(double x) nogil: + return ln(x) / ln(2.0) - for i from 0 <= i < n_total_samples: - if rand[i] * (n_total_samples - i) < (n_total_in_bag - n_bagged): - sample_mask[i] = 1 - n_bagged += 1 - return sample_mask.astype(np.bool) diff --git a/sklearn/tree/_utils.c b/sklearn/tree/_utils.c new file mode 100644 index 0000000000000..902d7ad2e566a --- /dev/null +++ b/sklearn/tree/_utils.c @@ -0,0 +1,6554 @@ +/* Generated by Cython 0.22 */ + +#define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) + #error Cython requires Python 2.6+ or Python 3.2+. +#else +#define CYTHON_ABI "0_22" +#include +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) +#define Py_OptimizeFlag 0 +#endif +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) + #define __Pyx_PyFrozenSet_Size(s) PyObject_Size(s) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) + #define __Pyx_PyFrozenSet_Size(s) PySet_Size(s) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY + #ifndef PyUnicode_InternFromString + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) + #endif +#endif +#if PY_VERSION_HEX < 0x030200A4 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#else + #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) +#endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#define __Pyx_void_to_None(void_result) (void_result, Py_INCREF(Py_None), Py_None) +#ifdef __cplusplus +template +void __Pyx_call_destructor(T* x) { + x->~T(); +} +template +class __Pyx_FakeReference { + public: + __Pyx_FakeReference() : ptr(NULL) { } + __Pyx_FakeReference(T& ref) : ptr(&ref) { } + T *operator->() { return ptr; } + operator T&() { return *ptr; } + private: + T *ptr; +}; +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__tree___utils +#define __PYX_HAVE_API__sklearn__tree___utils +#include "string.h" +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "sklearn/tree/_utils.pyx", + "__init__.pxd", + "type.pxd", +}; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":726 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":727 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":728 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":729 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":733 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":734 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":735 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":736 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":740 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":741 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":750 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":751 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":752 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":754 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":755 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":756 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":758 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":759 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":761 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":762 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":763 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; + +/* "sklearn/tree/_utils.pxd":12 + * cimport numpy as np + * + * ctypedef np.npy_intp SIZE_t # Type for indices and counters # <<<<<<<<<<<<<< + * + * + */ +typedef npy_intp __pyx_t_7sklearn_4tree_6_utils_SIZE_t; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ +struct __pyx_obj_7sklearn_4tree_6_utils_Stack; +struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":765 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":766 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":767 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":769 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; +struct __pyx_t_7sklearn_4tree_6_utils_StackRecord; +struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord; + +/* "sklearn/tree/_utils.pxd":20 + * + * # A record on the stack for depth-first tree growing + * cdef struct StackRecord: # <<<<<<<<<<<<<< + * SIZE_t start + * SIZE_t end + */ +struct __pyx_t_7sklearn_4tree_6_utils_StackRecord { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t start; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t end; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t depth; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t parent; + int is_left; + double impurity; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t n_constant_features; +}; + +/* "sklearn/tree/_utils.pxd":46 + * + * # A record on the frontier for best-first tree growing + * cdef struct PriorityHeapRecord: # <<<<<<<<<<<<<< + * SIZE_t node_id + * SIZE_t start + */ +struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t node_id; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t start; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t end; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t pos; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t depth; + int is_leaf; + double impurity; + double impurity_left; + double impurity_right; + double improvement; +}; + +/* "sklearn/tree/_utils.pxd":29 + * SIZE_t n_constant_features + * + * cdef class Stack: # <<<<<<<<<<<<<< + * cdef SIZE_t capacity + * cdef SIZE_t top + */ +struct __pyx_obj_7sklearn_4tree_6_utils_Stack { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack *__pyx_vtab; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t capacity; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t top; + struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *stack_; +}; + + +/* "sklearn/tree/_utils.pxd":58 + * double improvement + * + * cdef class PriorityHeap: # <<<<<<<<<<<<<< + * cdef SIZE_t capacity + * cdef SIZE_t heap_ptr + */ +struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_4tree_6_utils_PriorityHeap *__pyx_vtab; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t capacity; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t heap_ptr; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *heap_; +}; + + + +/* "sklearn/tree/_utils.pyx":17 + * # ============================================================================= + * + * cdef class Stack: # <<<<<<<<<<<<<< + * """A LIFO data structure. + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack { + int (*is_empty)(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *); + int (*push)(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, int, double, __pyx_t_7sklearn_4tree_6_utils_SIZE_t); + int (*pop)(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *, struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *); +}; +static struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack *__pyx_vtabptr_7sklearn_4tree_6_utils_Stack; + + +/* "sklearn/tree/_utils.pyx":135 + * + * + * cdef class PriorityHeap: # <<<<<<<<<<<<<< + * """A priority queue implemented as a binary heap. + * + */ + +struct __pyx_vtabstruct_7sklearn_4tree_6_utils_PriorityHeap { + int (*is_empty)(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *); + int (*push)(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, int, double, double, double, double); + int (*pop)(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *, struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *); +}; +static struct __pyx_vtabstruct_7sklearn_4tree_6_utils_PriorityHeap *__pyx_vtabptr_7sklearn_4tree_6_utils_PriorityHeap; + +/* --- Runtime support code (head) --- */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +#if PY_MAJOR_VERSION >= 3 +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { + PyObject *value; + value = PyDict_GetItemWithError(d, key); + if (unlikely(!value)) { + if (!PyErr_Occurred()) { + PyObject* args = PyTuple_Pack(1, key); + if (likely(args)) + PyErr_SetObject(PyExc_KeyError, args); + Py_XDECREF(args); + } + return NULL; + } + Py_INCREF(value); + return value; +} +#else + #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) +#endif + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); + +static int __Pyx_SetVtable(PyObject *dict, void *vtable); + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *); + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); + +static int __Pyx_check_binary_version(void); + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); + +static int __pyx_f_7sklearn_4tree_6_utils_5Stack_is_empty(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *__pyx_v_self); /* proto*/ +static int __pyx_f_7sklearn_4tree_6_utils_5Stack_push(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *__pyx_v_self, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_end, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_depth, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_parent, int __pyx_v_is_left, double __pyx_v_impurity, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_n_constant_features); /* proto*/ +static int __pyx_f_7sklearn_4tree_6_utils_5Stack_pop(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *__pyx_v_self, struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *__pyx_v_res); /* proto*/ +static int __pyx_f_7sklearn_4tree_6_utils_12PriorityHeap_is_empty(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_self); /* proto*/ +static int __pyx_f_7sklearn_4tree_6_utils_12PriorityHeap_push(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_self, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_node_id, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_end, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_pos, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_depth, int __pyx_v_is_leaf, double __pyx_v_improvement, double __pyx_v_impurity, double __pyx_v_impurity_left, double __pyx_v_impurity_right); /* proto*/ +static int __pyx_f_7sklearn_4tree_6_utils_12PriorityHeap_pop(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_self, struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *__pyx_v_res); /* proto*/ + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'sklearn.tree._utils' */ +static PyTypeObject *__pyx_ptype_7sklearn_4tree_6_utils_Stack = 0; +static PyTypeObject *__pyx_ptype_7sklearn_4tree_6_utils_PriorityHeap = 0; +static void __pyx_f_7sklearn_4tree_6_utils_heapify_up(struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *, __pyx_t_7sklearn_4tree_6_utils_SIZE_t); /*proto*/ +static void __pyx_f_7sklearn_4tree_6_utils_heapify_down(struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t); /*proto*/ +#define __Pyx_MODULE_NAME "sklearn.tree._utils" +int __pyx_module_is_main_sklearn__tree___utils = 0; + +/* Implementation of 'sklearn.tree._utils' */ +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_RuntimeError; +static int __pyx_pf_7sklearn_4tree_6_utils_5Stack___cinit__(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *__pyx_v_self, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_capacity); /* proto */ +static void __pyx_pf_7sklearn_4tree_6_utils_5Stack_2__dealloc__(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *__pyx_v_self); /* proto */ +static int __pyx_pf_7sklearn_4tree_6_utils_12PriorityHeap___cinit__(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_self, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_capacity); /* proto */ +static void __pyx_pf_7sklearn_4tree_6_utils_12PriorityHeap_2__dealloc__(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_self); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static PyObject *__pyx_tp_new_7sklearn_4tree_6_utils_Stack(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_4tree_6_utils_PriorityHeap(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_B[] = "B"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_capacity[] = "capacity"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static char __pyx_k_MemoryError[] = "MemoryError"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_n_s_MemoryError; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_capacity; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_pyx_vtable; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; + +/* "sklearn/tree/_utils.pyx":33 + * """ + * + * def __cinit__(self, SIZE_t capacity): # <<<<<<<<<<<<<< + * self.capacity = capacity + * self.top = 0 + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_6_utils_5Stack_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_4tree_6_utils_5Stack_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_capacity; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_capacity,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_capacity)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_capacity = __Pyx_PyInt_As_Py_intptr_t(values[0]); if (unlikely((__pyx_v_capacity == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._utils.Stack.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_4tree_6_utils_5Stack___cinit__(((struct __pyx_obj_7sklearn_4tree_6_utils_Stack *)__pyx_v_self), __pyx_v_capacity); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_6_utils_5Stack___cinit__(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *__pyx_v_self, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_capacity) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "sklearn/tree/_utils.pyx":34 + * + * def __cinit__(self, SIZE_t capacity): + * self.capacity = capacity # <<<<<<<<<<<<<< + * self.top = 0 + * self.stack_ = malloc(capacity * sizeof(StackRecord)) + */ + __pyx_v_self->capacity = __pyx_v_capacity; + + /* "sklearn/tree/_utils.pyx":35 + * def __cinit__(self, SIZE_t capacity): + * self.capacity = capacity + * self.top = 0 # <<<<<<<<<<<<<< + * self.stack_ = malloc(capacity * sizeof(StackRecord)) + * if self.stack_ == NULL: + */ + __pyx_v_self->top = 0; + + /* "sklearn/tree/_utils.pyx":36 + * self.capacity = capacity + * self.top = 0 + * self.stack_ = malloc(capacity * sizeof(StackRecord)) # <<<<<<<<<<<<<< + * if self.stack_ == NULL: + * raise MemoryError() + */ + __pyx_v_self->stack_ = ((struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *)malloc((__pyx_v_capacity * (sizeof(struct __pyx_t_7sklearn_4tree_6_utils_StackRecord))))); + + /* "sklearn/tree/_utils.pyx":37 + * self.top = 0 + * self.stack_ = malloc(capacity * sizeof(StackRecord)) + * if self.stack_ == NULL: # <<<<<<<<<<<<<< + * raise MemoryError() + * + */ + __pyx_t_1 = ((__pyx_v_self->stack_ == NULL) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_utils.pyx":38 + * self.stack_ = malloc(capacity * sizeof(StackRecord)) + * if self.stack_ == NULL: + * raise MemoryError() # <<<<<<<<<<<<<< + * + * def __dealloc__(self): + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_utils.pyx":33 + * """ + * + * def __cinit__(self, SIZE_t capacity): # <<<<<<<<<<<<<< + * self.capacity = capacity + * self.top = 0 + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.tree._utils.Stack.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_utils.pyx":40 + * raise MemoryError() + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * free(self.stack_) + * + */ + +/* Python wrapper */ +static void __pyx_pw_7sklearn_4tree_6_utils_5Stack_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_7sklearn_4tree_6_utils_5Stack_3__dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_pf_7sklearn_4tree_6_utils_5Stack_2__dealloc__(((struct __pyx_obj_7sklearn_4tree_6_utils_Stack *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_7sklearn_4tree_6_utils_5Stack_2__dealloc__(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "sklearn/tree/_utils.pyx":41 + * + * def __dealloc__(self): + * free(self.stack_) # <<<<<<<<<<<<<< + * + * cdef bint is_empty(self) nogil: + */ + free(__pyx_v_self->stack_); + + /* "sklearn/tree/_utils.pyx":40 + * raise MemoryError() + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * free(self.stack_) + * + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "sklearn/tree/_utils.pyx":43 + * free(self.stack_) + * + * cdef bint is_empty(self) nogil: # <<<<<<<<<<<<<< + * return self.top <= 0 + * + */ + +static int __pyx_f_7sklearn_4tree_6_utils_5Stack_is_empty(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *__pyx_v_self) { + int __pyx_r; + + /* "sklearn/tree/_utils.pyx":44 + * + * cdef bint is_empty(self) nogil: + * return self.top <= 0 # <<<<<<<<<<<<<< + * + * cdef int push(self, SIZE_t start, SIZE_t end, SIZE_t depth, SIZE_t parent, + */ + __pyx_r = (__pyx_v_self->top <= 0); + goto __pyx_L0; + + /* "sklearn/tree/_utils.pyx":43 + * free(self.stack_) + * + * cdef bint is_empty(self) nogil: # <<<<<<<<<<<<<< + * return self.top <= 0 + * + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_utils.pyx":46 + * return self.top <= 0 + * + * cdef int push(self, SIZE_t start, SIZE_t end, SIZE_t depth, SIZE_t parent, # <<<<<<<<<<<<<< + * bint is_left, double impurity, + * SIZE_t n_constant_features) nogil: + */ + +static int __pyx_f_7sklearn_4tree_6_utils_5Stack_push(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *__pyx_v_self, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_end, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_depth, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_parent, int __pyx_v_is_left, double __pyx_v_impurity, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_n_constant_features) { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_top; + struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *__pyx_v_stack; + int __pyx_r; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_t_1; + int __pyx_t_2; + struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *__pyx_t_3; + + /* "sklearn/tree/_utils.pyx":53 + * Returns 0 if successful; -1 on out of memory error. + * """ + * cdef SIZE_t top = self.top # <<<<<<<<<<<<<< + * cdef StackRecord* stack = NULL + * + */ + __pyx_t_1 = __pyx_v_self->top; + __pyx_v_top = __pyx_t_1; + + /* "sklearn/tree/_utils.pyx":54 + * """ + * cdef SIZE_t top = self.top + * cdef StackRecord* stack = NULL # <<<<<<<<<<<<<< + * + * # Resize if capacity not sufficient + */ + __pyx_v_stack = NULL; + + /* "sklearn/tree/_utils.pyx":57 + * + * # Resize if capacity not sufficient + * if top >= self.capacity: # <<<<<<<<<<<<<< + * self.capacity *= 2 + * stack = realloc(self.stack_, + */ + __pyx_t_2 = ((__pyx_v_top >= __pyx_v_self->capacity) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_utils.pyx":58 + * # Resize if capacity not sufficient + * if top >= self.capacity: + * self.capacity *= 2 # <<<<<<<<<<<<<< + * stack = realloc(self.stack_, + * self.capacity * sizeof(StackRecord)) + */ + __pyx_v_self->capacity = (__pyx_v_self->capacity * 2); + + /* "sklearn/tree/_utils.pyx":59 + * if top >= self.capacity: + * self.capacity *= 2 + * stack = realloc(self.stack_, # <<<<<<<<<<<<<< + * self.capacity * sizeof(StackRecord)) + * if stack == NULL: + */ + __pyx_v_stack = ((struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *)realloc(__pyx_v_self->stack_, (__pyx_v_self->capacity * (sizeof(struct __pyx_t_7sklearn_4tree_6_utils_StackRecord))))); + + /* "sklearn/tree/_utils.pyx":61 + * stack = realloc(self.stack_, + * self.capacity * sizeof(StackRecord)) + * if stack == NULL: # <<<<<<<<<<<<<< + * # no free; __dealloc__ handles that + * return -1 + */ + __pyx_t_2 = ((__pyx_v_stack == NULL) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_utils.pyx":63 + * if stack == NULL: + * # no free; __dealloc__ handles that + * return -1 # <<<<<<<<<<<<<< + * self.stack_ = stack + * + */ + __pyx_r = -1; + goto __pyx_L0; + } + + /* "sklearn/tree/_utils.pyx":64 + * # no free; __dealloc__ handles that + * return -1 + * self.stack_ = stack # <<<<<<<<<<<<<< + * + * stack = self.stack_ + */ + __pyx_v_self->stack_ = __pyx_v_stack; + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/tree/_utils.pyx":66 + * self.stack_ = stack + * + * stack = self.stack_ # <<<<<<<<<<<<<< + * stack[top].start = start + * stack[top].end = end + */ + __pyx_t_3 = __pyx_v_self->stack_; + __pyx_v_stack = __pyx_t_3; + + /* "sklearn/tree/_utils.pyx":67 + * + * stack = self.stack_ + * stack[top].start = start # <<<<<<<<<<<<<< + * stack[top].end = end + * stack[top].depth = depth + */ + (__pyx_v_stack[__pyx_v_top]).start = __pyx_v_start; + + /* "sklearn/tree/_utils.pyx":68 + * stack = self.stack_ + * stack[top].start = start + * stack[top].end = end # <<<<<<<<<<<<<< + * stack[top].depth = depth + * stack[top].parent = parent + */ + (__pyx_v_stack[__pyx_v_top]).end = __pyx_v_end; + + /* "sklearn/tree/_utils.pyx":69 + * stack[top].start = start + * stack[top].end = end + * stack[top].depth = depth # <<<<<<<<<<<<<< + * stack[top].parent = parent + * stack[top].is_left = is_left + */ + (__pyx_v_stack[__pyx_v_top]).depth = __pyx_v_depth; + + /* "sklearn/tree/_utils.pyx":70 + * stack[top].end = end + * stack[top].depth = depth + * stack[top].parent = parent # <<<<<<<<<<<<<< + * stack[top].is_left = is_left + * stack[top].impurity = impurity + */ + (__pyx_v_stack[__pyx_v_top]).parent = __pyx_v_parent; + + /* "sklearn/tree/_utils.pyx":71 + * stack[top].depth = depth + * stack[top].parent = parent + * stack[top].is_left = is_left # <<<<<<<<<<<<<< + * stack[top].impurity = impurity + * stack[top].n_constant_features = n_constant_features + */ + (__pyx_v_stack[__pyx_v_top]).is_left = __pyx_v_is_left; + + /* "sklearn/tree/_utils.pyx":72 + * stack[top].parent = parent + * stack[top].is_left = is_left + * stack[top].impurity = impurity # <<<<<<<<<<<<<< + * stack[top].n_constant_features = n_constant_features + * + */ + (__pyx_v_stack[__pyx_v_top]).impurity = __pyx_v_impurity; + + /* "sklearn/tree/_utils.pyx":73 + * stack[top].is_left = is_left + * stack[top].impurity = impurity + * stack[top].n_constant_features = n_constant_features # <<<<<<<<<<<<<< + * + * # Increment stack pointer + */ + (__pyx_v_stack[__pyx_v_top]).n_constant_features = __pyx_v_n_constant_features; + + /* "sklearn/tree/_utils.pyx":76 + * + * # Increment stack pointer + * self.top = top + 1 # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_v_self->top = (__pyx_v_top + 1); + + /* "sklearn/tree/_utils.pyx":77 + * # Increment stack pointer + * self.top = top + 1 + * return 0 # <<<<<<<<<<<<<< + * + * cdef int pop(self, StackRecord* res) nogil: + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/tree/_utils.pyx":46 + * return self.top <= 0 + * + * cdef int push(self, SIZE_t start, SIZE_t end, SIZE_t depth, SIZE_t parent, # <<<<<<<<<<<<<< + * bint is_left, double impurity, + * SIZE_t n_constant_features) nogil: + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_utils.pyx":79 + * return 0 + * + * cdef int pop(self, StackRecord* res) nogil: # <<<<<<<<<<<<<< + * """Remove the top element from the stack and copy to ``res``. + * + */ + +static int __pyx_f_7sklearn_4tree_6_utils_5Stack_pop(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *__pyx_v_self, struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *__pyx_v_res) { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_top; + struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *__pyx_v_stack; + int __pyx_r; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_t_1; + struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *__pyx_t_2; + int __pyx_t_3; + + /* "sklearn/tree/_utils.pyx":85 + * otherwise. + * """ + * cdef SIZE_t top = self.top # <<<<<<<<<<<<<< + * cdef StackRecord* stack = self.stack_ + * + */ + __pyx_t_1 = __pyx_v_self->top; + __pyx_v_top = __pyx_t_1; + + /* "sklearn/tree/_utils.pyx":86 + * """ + * cdef SIZE_t top = self.top + * cdef StackRecord* stack = self.stack_ # <<<<<<<<<<<<<< + * + * if top <= 0: + */ + __pyx_t_2 = __pyx_v_self->stack_; + __pyx_v_stack = __pyx_t_2; + + /* "sklearn/tree/_utils.pyx":88 + * cdef StackRecord* stack = self.stack_ + * + * if top <= 0: # <<<<<<<<<<<<<< + * return -1 + * + */ + __pyx_t_3 = ((__pyx_v_top <= 0) != 0); + if (__pyx_t_3) { + + /* "sklearn/tree/_utils.pyx":89 + * + * if top <= 0: + * return -1 # <<<<<<<<<<<<<< + * + * res[0] = stack[top - 1] + */ + __pyx_r = -1; + goto __pyx_L0; + } + + /* "sklearn/tree/_utils.pyx":91 + * return -1 + * + * res[0] = stack[top - 1] # <<<<<<<<<<<<<< + * self.top = top - 1 + * + */ + (__pyx_v_res[0]) = (__pyx_v_stack[(__pyx_v_top - 1)]); + + /* "sklearn/tree/_utils.pyx":92 + * + * res[0] = stack[top - 1] + * self.top = top - 1 # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_v_self->top = (__pyx_v_top - 1); + + /* "sklearn/tree/_utils.pyx":94 + * self.top = top - 1 + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/tree/_utils.pyx":79 + * return 0 + * + * cdef int pop(self, StackRecord* res) nogil: # <<<<<<<<<<<<<< + * """Remove the top element from the stack and copy to ``res``. + * + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_utils.pyx":101 + * # ============================================================================= + * + * cdef void heapify_up(PriorityHeapRecord* heap, SIZE_t pos) nogil: # <<<<<<<<<<<<<< + * """Restore heap invariant parent.improvement > child.improvement from + * ``pos`` upwards. """ + */ + +static void __pyx_f_7sklearn_4tree_6_utils_heapify_up(struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *__pyx_v_heap, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_pos) { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_parent_pos; + int __pyx_t_1; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord __pyx_t_2; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord __pyx_t_3; + + /* "sklearn/tree/_utils.pyx":104 + * """Restore heap invariant parent.improvement > child.improvement from + * ``pos`` upwards. """ + * if pos == 0: # <<<<<<<<<<<<<< + * return + * + */ + __pyx_t_1 = ((__pyx_v_pos == 0) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_utils.pyx":105 + * ``pos`` upwards. """ + * if pos == 0: + * return # <<<<<<<<<<<<<< + * + * cdef SIZE_t parent_pos = (pos - 1) / 2 + */ + goto __pyx_L0; + } + + /* "sklearn/tree/_utils.pyx":107 + * return + * + * cdef SIZE_t parent_pos = (pos - 1) / 2 # <<<<<<<<<<<<<< + * + * if heap[parent_pos].improvement < heap[pos].improvement: + */ + __pyx_v_parent_pos = ((__pyx_v_pos - 1) / 2); + + /* "sklearn/tree/_utils.pyx":109 + * cdef SIZE_t parent_pos = (pos - 1) / 2 + * + * if heap[parent_pos].improvement < heap[pos].improvement: # <<<<<<<<<<<<<< + * heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos] + * heapify_up(heap, parent_pos) + */ + __pyx_t_1 = (((__pyx_v_heap[__pyx_v_parent_pos]).improvement < (__pyx_v_heap[__pyx_v_pos]).improvement) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_utils.pyx":110 + * + * if heap[parent_pos].improvement < heap[pos].improvement: + * heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos] # <<<<<<<<<<<<<< + * heapify_up(heap, parent_pos) + * + */ + __pyx_t_2 = (__pyx_v_heap[__pyx_v_pos]); + __pyx_t_3 = (__pyx_v_heap[__pyx_v_parent_pos]); + (__pyx_v_heap[__pyx_v_parent_pos]) = __pyx_t_2; + (__pyx_v_heap[__pyx_v_pos]) = __pyx_t_3; + + /* "sklearn/tree/_utils.pyx":111 + * if heap[parent_pos].improvement < heap[pos].improvement: + * heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos] + * heapify_up(heap, parent_pos) # <<<<<<<<<<<<<< + * + * + */ + __pyx_f_7sklearn_4tree_6_utils_heapify_up(__pyx_v_heap, __pyx_v_parent_pos); + goto __pyx_L4; + } + __pyx_L4:; + + /* "sklearn/tree/_utils.pyx":101 + * # ============================================================================= + * + * cdef void heapify_up(PriorityHeapRecord* heap, SIZE_t pos) nogil: # <<<<<<<<<<<<<< + * """Restore heap invariant parent.improvement > child.improvement from + * ``pos`` upwards. """ + */ + + /* function exit code */ + __pyx_L0:; +} + +/* "sklearn/tree/_utils.pyx":114 + * + * + * cdef void heapify_down(PriorityHeapRecord* heap, SIZE_t pos, # <<<<<<<<<<<<<< + * SIZE_t heap_length) nogil: + * """Restore heap invariant parent.improvement > children.improvement from + */ + +static void __pyx_f_7sklearn_4tree_6_utils_heapify_down(struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *__pyx_v_heap, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_pos, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_heap_length) { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_left_pos; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_right_pos; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_largest; + int __pyx_t_1; + int __pyx_t_2; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord __pyx_t_3; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord __pyx_t_4; + + /* "sklearn/tree/_utils.pyx":118 + * """Restore heap invariant parent.improvement > children.improvement from + * ``pos`` downwards. """ + * cdef SIZE_t left_pos = 2 * (pos + 1) - 1 # <<<<<<<<<<<<<< + * cdef SIZE_t right_pos = 2 * (pos + 1) + * cdef SIZE_t largest = pos + */ + __pyx_v_left_pos = ((2 * (__pyx_v_pos + 1)) - 1); + + /* "sklearn/tree/_utils.pyx":119 + * ``pos`` downwards. """ + * cdef SIZE_t left_pos = 2 * (pos + 1) - 1 + * cdef SIZE_t right_pos = 2 * (pos + 1) # <<<<<<<<<<<<<< + * cdef SIZE_t largest = pos + * + */ + __pyx_v_right_pos = (2 * (__pyx_v_pos + 1)); + + /* "sklearn/tree/_utils.pyx":120 + * cdef SIZE_t left_pos = 2 * (pos + 1) - 1 + * cdef SIZE_t right_pos = 2 * (pos + 1) + * cdef SIZE_t largest = pos # <<<<<<<<<<<<<< + * + * if (left_pos < heap_length and + */ + __pyx_v_largest = __pyx_v_pos; + + /* "sklearn/tree/_utils.pyx":122 + * cdef SIZE_t largest = pos + * + * if (left_pos < heap_length and # <<<<<<<<<<<<<< + * heap[left_pos].improvement > heap[largest].improvement): + * largest = left_pos + */ + __pyx_t_2 = ((__pyx_v_left_pos < __pyx_v_heap_length) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } + + /* "sklearn/tree/_utils.pyx":123 + * + * if (left_pos < heap_length and + * heap[left_pos].improvement > heap[largest].improvement): # <<<<<<<<<<<<<< + * largest = left_pos + * + */ + __pyx_t_2 = (((__pyx_v_heap[__pyx_v_left_pos]).improvement > (__pyx_v_heap[__pyx_v_largest]).improvement) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L4_bool_binop_done:; + if (__pyx_t_1) { + + /* "sklearn/tree/_utils.pyx":124 + * if (left_pos < heap_length and + * heap[left_pos].improvement > heap[largest].improvement): + * largest = left_pos # <<<<<<<<<<<<<< + * + * if (right_pos < heap_length and + */ + __pyx_v_largest = __pyx_v_left_pos; + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/tree/_utils.pyx":126 + * largest = left_pos + * + * if (right_pos < heap_length and # <<<<<<<<<<<<<< + * heap[right_pos].improvement > heap[largest].improvement): + * largest = right_pos + */ + __pyx_t_2 = ((__pyx_v_right_pos < __pyx_v_heap_length) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L7_bool_binop_done; + } + + /* "sklearn/tree/_utils.pyx":127 + * + * if (right_pos < heap_length and + * heap[right_pos].improvement > heap[largest].improvement): # <<<<<<<<<<<<<< + * largest = right_pos + * + */ + __pyx_t_2 = (((__pyx_v_heap[__pyx_v_right_pos]).improvement > (__pyx_v_heap[__pyx_v_largest]).improvement) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L7_bool_binop_done:; + if (__pyx_t_1) { + + /* "sklearn/tree/_utils.pyx":128 + * if (right_pos < heap_length and + * heap[right_pos].improvement > heap[largest].improvement): + * largest = right_pos # <<<<<<<<<<<<<< + * + * if largest != pos: + */ + __pyx_v_largest = __pyx_v_right_pos; + goto __pyx_L6; + } + __pyx_L6:; + + /* "sklearn/tree/_utils.pyx":130 + * largest = right_pos + * + * if largest != pos: # <<<<<<<<<<<<<< + * heap[pos], heap[largest] = heap[largest], heap[pos] + * heapify_down(heap, largest, heap_length) + */ + __pyx_t_1 = ((__pyx_v_largest != __pyx_v_pos) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_utils.pyx":131 + * + * if largest != pos: + * heap[pos], heap[largest] = heap[largest], heap[pos] # <<<<<<<<<<<<<< + * heapify_down(heap, largest, heap_length) + * + */ + __pyx_t_3 = (__pyx_v_heap[__pyx_v_largest]); + __pyx_t_4 = (__pyx_v_heap[__pyx_v_pos]); + (__pyx_v_heap[__pyx_v_pos]) = __pyx_t_3; + (__pyx_v_heap[__pyx_v_largest]) = __pyx_t_4; + + /* "sklearn/tree/_utils.pyx":132 + * if largest != pos: + * heap[pos], heap[largest] = heap[largest], heap[pos] + * heapify_down(heap, largest, heap_length) # <<<<<<<<<<<<<< + * + * + */ + __pyx_f_7sklearn_4tree_6_utils_heapify_down(__pyx_v_heap, __pyx_v_largest, __pyx_v_heap_length); + goto __pyx_L9; + } + __pyx_L9:; + + /* "sklearn/tree/_utils.pyx":114 + * + * + * cdef void heapify_down(PriorityHeapRecord* heap, SIZE_t pos, # <<<<<<<<<<<<<< + * SIZE_t heap_length) nogil: + * """Restore heap invariant parent.improvement > children.improvement from + */ + + /* function exit code */ +} + +/* "sklearn/tree/_utils.pyx":155 + * """ + * + * def __cinit__(self, SIZE_t capacity): # <<<<<<<<<<<<<< + * self.capacity = capacity + * self.heap_ptr = 0 + */ + +/* Python wrapper */ +static int __pyx_pw_7sklearn_4tree_6_utils_12PriorityHeap_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_4tree_6_utils_12PriorityHeap_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_capacity; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_capacity,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_capacity)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_capacity = __Pyx_PyInt_As_Py_intptr_t(values[0]); if (unlikely((__pyx_v_capacity == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.tree._utils.PriorityHeap.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_4tree_6_utils_12PriorityHeap___cinit__(((struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *)__pyx_v_self), __pyx_v_capacity); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_4tree_6_utils_12PriorityHeap___cinit__(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_self, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_capacity) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "sklearn/tree/_utils.pyx":156 + * + * def __cinit__(self, SIZE_t capacity): + * self.capacity = capacity # <<<<<<<<<<<<<< + * self.heap_ptr = 0 + * self.heap_ = malloc(capacity * sizeof(PriorityHeapRecord)) + */ + __pyx_v_self->capacity = __pyx_v_capacity; + + /* "sklearn/tree/_utils.pyx":157 + * def __cinit__(self, SIZE_t capacity): + * self.capacity = capacity + * self.heap_ptr = 0 # <<<<<<<<<<<<<< + * self.heap_ = malloc(capacity * sizeof(PriorityHeapRecord)) + * if self.heap_ == NULL: + */ + __pyx_v_self->heap_ptr = 0; + + /* "sklearn/tree/_utils.pyx":158 + * self.capacity = capacity + * self.heap_ptr = 0 + * self.heap_ = malloc(capacity * sizeof(PriorityHeapRecord)) # <<<<<<<<<<<<<< + * if self.heap_ == NULL: + * raise MemoryError() + */ + __pyx_v_self->heap_ = ((struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *)malloc((__pyx_v_capacity * (sizeof(struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord))))); + + /* "sklearn/tree/_utils.pyx":159 + * self.heap_ptr = 0 + * self.heap_ = malloc(capacity * sizeof(PriorityHeapRecord)) + * if self.heap_ == NULL: # <<<<<<<<<<<<<< + * raise MemoryError() + * + */ + __pyx_t_1 = ((__pyx_v_self->heap_ == NULL) != 0); + if (__pyx_t_1) { + + /* "sklearn/tree/_utils.pyx":160 + * self.heap_ = malloc(capacity * sizeof(PriorityHeapRecord)) + * if self.heap_ == NULL: + * raise MemoryError() # <<<<<<<<<<<<<< + * + * def __dealloc__(self): + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/tree/_utils.pyx":155 + * """ + * + * def __cinit__(self, SIZE_t capacity): # <<<<<<<<<<<<<< + * self.capacity = capacity + * self.heap_ptr = 0 + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.tree._utils.PriorityHeap.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/tree/_utils.pyx":162 + * raise MemoryError() + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * free(self.heap_) + * + */ + +/* Python wrapper */ +static void __pyx_pw_7sklearn_4tree_6_utils_12PriorityHeap_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_7sklearn_4tree_6_utils_12PriorityHeap_3__dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_pf_7sklearn_4tree_6_utils_12PriorityHeap_2__dealloc__(((struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_7sklearn_4tree_6_utils_12PriorityHeap_2__dealloc__(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "sklearn/tree/_utils.pyx":163 + * + * def __dealloc__(self): + * free(self.heap_) # <<<<<<<<<<<<<< + * + * cdef bint is_empty(self) nogil: + */ + free(__pyx_v_self->heap_); + + /* "sklearn/tree/_utils.pyx":162 + * raise MemoryError() + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * free(self.heap_) + * + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "sklearn/tree/_utils.pyx":165 + * free(self.heap_) + * + * cdef bint is_empty(self) nogil: # <<<<<<<<<<<<<< + * return self.heap_ptr <= 0 + * + */ + +static int __pyx_f_7sklearn_4tree_6_utils_12PriorityHeap_is_empty(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_self) { + int __pyx_r; + + /* "sklearn/tree/_utils.pyx":166 + * + * cdef bint is_empty(self) nogil: + * return self.heap_ptr <= 0 # <<<<<<<<<<<<<< + * + * cdef int push(self, SIZE_t node_id, SIZE_t start, SIZE_t end, SIZE_t pos, + */ + __pyx_r = (__pyx_v_self->heap_ptr <= 0); + goto __pyx_L0; + + /* "sklearn/tree/_utils.pyx":165 + * free(self.heap_) + * + * cdef bint is_empty(self) nogil: # <<<<<<<<<<<<<< + * return self.heap_ptr <= 0 + * + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_utils.pyx":168 + * return self.heap_ptr <= 0 + * + * cdef int push(self, SIZE_t node_id, SIZE_t start, SIZE_t end, SIZE_t pos, # <<<<<<<<<<<<<< + * SIZE_t depth, bint is_leaf, double improvement, + * double impurity, double impurity_left, + */ + +static int __pyx_f_7sklearn_4tree_6_utils_12PriorityHeap_push(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_self, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_node_id, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_start, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_end, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_pos, __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_depth, int __pyx_v_is_leaf, double __pyx_v_improvement, double __pyx_v_impurity, double __pyx_v_impurity_left, double __pyx_v_impurity_right) { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_heap_ptr; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *__pyx_v_heap; + int __pyx_r; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_t_1; + int __pyx_t_2; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *__pyx_t_3; + + /* "sklearn/tree/_utils.pyx":176 + * Returns 0 if successful; -1 on out of memory error. + * """ + * cdef SIZE_t heap_ptr = self.heap_ptr # <<<<<<<<<<<<<< + * cdef PriorityHeapRecord* heap = NULL + * + */ + __pyx_t_1 = __pyx_v_self->heap_ptr; + __pyx_v_heap_ptr = __pyx_t_1; + + /* "sklearn/tree/_utils.pyx":177 + * """ + * cdef SIZE_t heap_ptr = self.heap_ptr + * cdef PriorityHeapRecord* heap = NULL # <<<<<<<<<<<<<< + * + * # Resize if capacity not sufficient + */ + __pyx_v_heap = NULL; + + /* "sklearn/tree/_utils.pyx":180 + * + * # Resize if capacity not sufficient + * if heap_ptr >= self.capacity: # <<<<<<<<<<<<<< + * self.capacity *= 2 + * heap = realloc(self.heap_, + */ + __pyx_t_2 = ((__pyx_v_heap_ptr >= __pyx_v_self->capacity) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_utils.pyx":181 + * # Resize if capacity not sufficient + * if heap_ptr >= self.capacity: + * self.capacity *= 2 # <<<<<<<<<<<<<< + * heap = realloc(self.heap_, + * self.capacity * + */ + __pyx_v_self->capacity = (__pyx_v_self->capacity * 2); + + /* "sklearn/tree/_utils.pyx":182 + * if heap_ptr >= self.capacity: + * self.capacity *= 2 + * heap = realloc(self.heap_, # <<<<<<<<<<<<<< + * self.capacity * + * sizeof(PriorityHeapRecord)) + */ + __pyx_v_heap = ((struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *)realloc(__pyx_v_self->heap_, (__pyx_v_self->capacity * (sizeof(struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord))))); + + /* "sklearn/tree/_utils.pyx":185 + * self.capacity * + * sizeof(PriorityHeapRecord)) + * if heap == NULL: # <<<<<<<<<<<<<< + * # no free; __dealloc__ handles that + * return -1 + */ + __pyx_t_2 = ((__pyx_v_heap == NULL) != 0); + if (__pyx_t_2) { + + /* "sklearn/tree/_utils.pyx":187 + * if heap == NULL: + * # no free; __dealloc__ handles that + * return -1 # <<<<<<<<<<<<<< + * self.heap_ = heap + * + */ + __pyx_r = -1; + goto __pyx_L0; + } + + /* "sklearn/tree/_utils.pyx":188 + * # no free; __dealloc__ handles that + * return -1 + * self.heap_ = heap # <<<<<<<<<<<<<< + * + * # Put element as last element of heap + */ + __pyx_v_self->heap_ = __pyx_v_heap; + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/tree/_utils.pyx":191 + * + * # Put element as last element of heap + * heap = self.heap_ # <<<<<<<<<<<<<< + * heap[heap_ptr].node_id = node_id + * heap[heap_ptr].start = start + */ + __pyx_t_3 = __pyx_v_self->heap_; + __pyx_v_heap = __pyx_t_3; + + /* "sklearn/tree/_utils.pyx":192 + * # Put element as last element of heap + * heap = self.heap_ + * heap[heap_ptr].node_id = node_id # <<<<<<<<<<<<<< + * heap[heap_ptr].start = start + * heap[heap_ptr].end = end + */ + (__pyx_v_heap[__pyx_v_heap_ptr]).node_id = __pyx_v_node_id; + + /* "sklearn/tree/_utils.pyx":193 + * heap = self.heap_ + * heap[heap_ptr].node_id = node_id + * heap[heap_ptr].start = start # <<<<<<<<<<<<<< + * heap[heap_ptr].end = end + * heap[heap_ptr].pos = pos + */ + (__pyx_v_heap[__pyx_v_heap_ptr]).start = __pyx_v_start; + + /* "sklearn/tree/_utils.pyx":194 + * heap[heap_ptr].node_id = node_id + * heap[heap_ptr].start = start + * heap[heap_ptr].end = end # <<<<<<<<<<<<<< + * heap[heap_ptr].pos = pos + * heap[heap_ptr].depth = depth + */ + (__pyx_v_heap[__pyx_v_heap_ptr]).end = __pyx_v_end; + + /* "sklearn/tree/_utils.pyx":195 + * heap[heap_ptr].start = start + * heap[heap_ptr].end = end + * heap[heap_ptr].pos = pos # <<<<<<<<<<<<<< + * heap[heap_ptr].depth = depth + * heap[heap_ptr].is_leaf = is_leaf + */ + (__pyx_v_heap[__pyx_v_heap_ptr]).pos = __pyx_v_pos; + + /* "sklearn/tree/_utils.pyx":196 + * heap[heap_ptr].end = end + * heap[heap_ptr].pos = pos + * heap[heap_ptr].depth = depth # <<<<<<<<<<<<<< + * heap[heap_ptr].is_leaf = is_leaf + * heap[heap_ptr].impurity = impurity + */ + (__pyx_v_heap[__pyx_v_heap_ptr]).depth = __pyx_v_depth; + + /* "sklearn/tree/_utils.pyx":197 + * heap[heap_ptr].pos = pos + * heap[heap_ptr].depth = depth + * heap[heap_ptr].is_leaf = is_leaf # <<<<<<<<<<<<<< + * heap[heap_ptr].impurity = impurity + * heap[heap_ptr].impurity_left = impurity_left + */ + (__pyx_v_heap[__pyx_v_heap_ptr]).is_leaf = __pyx_v_is_leaf; + + /* "sklearn/tree/_utils.pyx":198 + * heap[heap_ptr].depth = depth + * heap[heap_ptr].is_leaf = is_leaf + * heap[heap_ptr].impurity = impurity # <<<<<<<<<<<<<< + * heap[heap_ptr].impurity_left = impurity_left + * heap[heap_ptr].impurity_right = impurity_right + */ + (__pyx_v_heap[__pyx_v_heap_ptr]).impurity = __pyx_v_impurity; + + /* "sklearn/tree/_utils.pyx":199 + * heap[heap_ptr].is_leaf = is_leaf + * heap[heap_ptr].impurity = impurity + * heap[heap_ptr].impurity_left = impurity_left # <<<<<<<<<<<<<< + * heap[heap_ptr].impurity_right = impurity_right + * heap[heap_ptr].improvement = improvement + */ + (__pyx_v_heap[__pyx_v_heap_ptr]).impurity_left = __pyx_v_impurity_left; + + /* "sklearn/tree/_utils.pyx":200 + * heap[heap_ptr].impurity = impurity + * heap[heap_ptr].impurity_left = impurity_left + * heap[heap_ptr].impurity_right = impurity_right # <<<<<<<<<<<<<< + * heap[heap_ptr].improvement = improvement + * + */ + (__pyx_v_heap[__pyx_v_heap_ptr]).impurity_right = __pyx_v_impurity_right; + + /* "sklearn/tree/_utils.pyx":201 + * heap[heap_ptr].impurity_left = impurity_left + * heap[heap_ptr].impurity_right = impurity_right + * heap[heap_ptr].improvement = improvement # <<<<<<<<<<<<<< + * + * # Heapify up + */ + (__pyx_v_heap[__pyx_v_heap_ptr]).improvement = __pyx_v_improvement; + + /* "sklearn/tree/_utils.pyx":204 + * + * # Heapify up + * heapify_up(heap, heap_ptr) # <<<<<<<<<<<<<< + * + * # Increase element count + */ + __pyx_f_7sklearn_4tree_6_utils_heapify_up(__pyx_v_heap, __pyx_v_heap_ptr); + + /* "sklearn/tree/_utils.pyx":207 + * + * # Increase element count + * self.heap_ptr = heap_ptr + 1 # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_v_self->heap_ptr = (__pyx_v_heap_ptr + 1); + + /* "sklearn/tree/_utils.pyx":208 + * # Increase element count + * self.heap_ptr = heap_ptr + 1 + * return 0 # <<<<<<<<<<<<<< + * + * cdef int pop(self, PriorityHeapRecord* res) nogil: + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/tree/_utils.pyx":168 + * return self.heap_ptr <= 0 + * + * cdef int push(self, SIZE_t node_id, SIZE_t start, SIZE_t end, SIZE_t pos, # <<<<<<<<<<<<<< + * SIZE_t depth, bint is_leaf, double improvement, + * double impurity, double impurity_left, + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "sklearn/tree/_utils.pyx":210 + * return 0 + * + * cdef int pop(self, PriorityHeapRecord* res) nogil: # <<<<<<<<<<<<<< + * """Remove max element from the heap. """ + * cdef SIZE_t heap_ptr = self.heap_ptr + */ + +static int __pyx_f_7sklearn_4tree_6_utils_12PriorityHeap_pop(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *__pyx_v_self, struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *__pyx_v_res) { + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_v_heap_ptr; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *__pyx_v_heap; + int __pyx_r; + __pyx_t_7sklearn_4tree_6_utils_SIZE_t __pyx_t_1; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *__pyx_t_2; + int __pyx_t_3; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord __pyx_t_4; + struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord __pyx_t_5; + + /* "sklearn/tree/_utils.pyx":212 + * cdef int pop(self, PriorityHeapRecord* res) nogil: + * """Remove max element from the heap. """ + * cdef SIZE_t heap_ptr = self.heap_ptr # <<<<<<<<<<<<<< + * cdef PriorityHeapRecord* heap = self.heap_ + * + */ + __pyx_t_1 = __pyx_v_self->heap_ptr; + __pyx_v_heap_ptr = __pyx_t_1; + + /* "sklearn/tree/_utils.pyx":213 + * """Remove max element from the heap. """ + * cdef SIZE_t heap_ptr = self.heap_ptr + * cdef PriorityHeapRecord* heap = self.heap_ # <<<<<<<<<<<<<< + * + * if heap_ptr <= 0: + */ + __pyx_t_2 = __pyx_v_self->heap_; + __pyx_v_heap = __pyx_t_2; + + /* "sklearn/tree/_utils.pyx":215 + * cdef PriorityHeapRecord* heap = self.heap_ + * + * if heap_ptr <= 0: # <<<<<<<<<<<<<< + * return -1 + * + */ + __pyx_t_3 = ((__pyx_v_heap_ptr <= 0) != 0); + if (__pyx_t_3) { + + /* "sklearn/tree/_utils.pyx":216 + * + * if heap_ptr <= 0: + * return -1 # <<<<<<<<<<<<<< + * + * # Take first element + */ + __pyx_r = -1; + goto __pyx_L0; + } + + /* "sklearn/tree/_utils.pyx":219 + * + * # Take first element + * res[0] = heap[0] # <<<<<<<<<<<<<< + * + * # Put last element to the front + */ + (__pyx_v_res[0]) = (__pyx_v_heap[0]); + + /* "sklearn/tree/_utils.pyx":222 + * + * # Put last element to the front + * heap[0], heap[heap_ptr - 1] = heap[heap_ptr - 1], heap[0] # <<<<<<<<<<<<<< + * + * # Restore heap invariant + */ + __pyx_t_4 = (__pyx_v_heap[(__pyx_v_heap_ptr - 1)]); + __pyx_t_5 = (__pyx_v_heap[0]); + (__pyx_v_heap[0]) = __pyx_t_4; + (__pyx_v_heap[(__pyx_v_heap_ptr - 1)]) = __pyx_t_5; + + /* "sklearn/tree/_utils.pyx":225 + * + * # Restore heap invariant + * if heap_ptr > 1: # <<<<<<<<<<<<<< + * heapify_down(heap, 0, heap_ptr - 1) + * + */ + __pyx_t_3 = ((__pyx_v_heap_ptr > 1) != 0); + if (__pyx_t_3) { + + /* "sklearn/tree/_utils.pyx":226 + * # Restore heap invariant + * if heap_ptr > 1: + * heapify_down(heap, 0, heap_ptr - 1) # <<<<<<<<<<<<<< + * + * self.heap_ptr = heap_ptr - 1 + */ + __pyx_f_7sklearn_4tree_6_utils_heapify_down(__pyx_v_heap, 0, (__pyx_v_heap_ptr - 1)); + goto __pyx_L4; + } + __pyx_L4:; + + /* "sklearn/tree/_utils.pyx":228 + * heapify_down(heap, 0, heap_ptr - 1) + * + * self.heap_ptr = heap_ptr - 1 # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_v_self->heap_ptr = (__pyx_v_heap_ptr - 1); + + /* "sklearn/tree/_utils.pyx":230 + * self.heap_ptr = heap_ptr - 1 + * + * return 0 # <<<<<<<<<<<<<< + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "sklearn/tree/_utils.pyx":210 + * return 0 + * + * cdef int pop(self, PriorityHeapRecord* res) nogil: # <<<<<<<<<<<<<< + * """Remove max element from the heap. """ + * cdef SIZE_t heap_ptr = self.heap_ptr + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":197 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":203 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":206 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":207 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":209 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":211 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":212 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":216 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L6_bool_binop_done; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":217 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L6_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":220 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L9_bool_binop_done; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":221 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L9_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":224 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":225 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_1 = (__pyx_v_copy_shape != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":229 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":230 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":231 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_4 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":232 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L11; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":236 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L11:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":237 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":238 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":242 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":243 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":247 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":249 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L15_bool_binop_done; + } + __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L15_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":251 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L14; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":254 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L14:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":256 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_4 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_4; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); + if (!__pyx_t_2) { + goto __pyx_L20_next_or; + } else { + } + __pyx_t_2 = (__pyx_v_little_endian != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_L20_next_or:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L19_bool_binop_done:; + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":261 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":262 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":263 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":264 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":266 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":267 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":268 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":269 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":271 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":273 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":275 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":279 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":281 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":284 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":285 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":286 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< + * info.format + _buffer_format_string_len, + * &offset) + */ + __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_7; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":289 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":197 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":293 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":294 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":295 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":772 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":775 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":778 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":781 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":784 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 784; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":786 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + long __pyx_t_8; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":793 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":797 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); + __pyx_t_3 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":798 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + if (unlikely(__pyx_v_descr->fields == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); + __pyx_t_4 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":804 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (!__pyx_t_7) { + goto __pyx_L8_next_or; + } else { + } + __pyx_t_7 = (__pyx_v_little_endian != 0); + if (!__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_L8_next_or:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":805 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + } else { + __pyx_t_6 = __pyx_t_7; + goto __pyx_L7_bool_binop_done; + } + __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_6 = __pyx_t_7; + __pyx_L7_bool_binop_done:; + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":806 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":816 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_6) break; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":817 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":819 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":821 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_8 = 0; + (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":824 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":825 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_6) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":829 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":830 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":831 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":832 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":833 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":834 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":835 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":836 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":838 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":839 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":840 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":841 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":843 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":844 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L15; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":845 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L15; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":847 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L15:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":848 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":852 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 852; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + } + __pyx_L13:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":797 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":853 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":786 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":971 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":972 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":974 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":975 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":977 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":979 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":980 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":981 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + /*else*/ { + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":983 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":979 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static struct __pyx_vtabstruct_7sklearn_4tree_6_utils_Stack __pyx_vtable_7sklearn_4tree_6_utils_Stack; + +static PyObject *__pyx_tp_new_7sklearn_4tree_6_utils_Stack(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_6_utils_Stack *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_6_utils_Stack *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_4tree_6_utils_Stack; + if (unlikely(__pyx_pw_7sklearn_4tree_6_utils_5Stack_1__cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_4tree_6_utils_Stack(PyObject *o) { + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_pw_7sklearn_4tree_6_utils_5Stack_3__dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + (*Py_TYPE(o)->tp_free)(o); +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_6_utils_Stack[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_6_utils_Stack = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._utils.Stack", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_6_utils_Stack), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_6_utils_Stack, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "A LIFO data structure.\n\n Attributes\n ----------\n capacity : SIZE_t\n The elements the stack can hold; if more added then ``self.stack_``\n needs to be resized.\n\n top : SIZE_t\n The number of elements currently on the stack.\n\n stack : StackRecord pointer\n The stack of records (upward in the stack corresponds to the right).\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_6_utils_Stack, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_6_utils_Stack, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_4tree_6_utils_PriorityHeap __pyx_vtable_7sklearn_4tree_6_utils_PriorityHeap; + +static PyObject *__pyx_tp_new_7sklearn_4tree_6_utils_PriorityHeap(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_4tree_6_utils_PriorityHeap; + if (unlikely(__pyx_pw_7sklearn_4tree_6_utils_12PriorityHeap_1__cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_7sklearn_4tree_6_utils_PriorityHeap(PyObject *o) { + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_pw_7sklearn_4tree_6_utils_12PriorityHeap_3__dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + (*Py_TYPE(o)->tp_free)(o); +} + +static PyMethodDef __pyx_methods_7sklearn_4tree_6_utils_PriorityHeap[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_4tree_6_utils_PriorityHeap = { + PyVarObject_HEAD_INIT(0, 0) + "sklearn.tree._utils.PriorityHeap", /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_4tree_6_utils_PriorityHeap, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "A priority queue implemented as a binary heap.\n\n The heap invariant is that the impurity improvement of the parent record\n is larger then the impurity improvement of the children.\n\n Attributes\n ----------\n capacity : SIZE_t\n The capacity of the heap\n\n heap_ptr : SIZE_t\n The water mark of the heap; the heap grows from left to right in the\n array ``heap_``. The following invariant holds ``heap_ptr < capacity``.\n\n heap_ : PriorityHeapRecord*\n The array of heap records. The maximum element is on the left;\n the heap grows from left to right\n ", /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_4tree_6_utils_PriorityHeap, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_4tree_6_utils_PriorityHeap, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + "_utils", + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_capacity, __pyx_k_capacity, sizeof(__pyx_k_capacity), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":806 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC init_utils(void); /*proto*/ +PyMODINIT_FUNC init_utils(void) +#else +PyMODINIT_FUNC PyInit__utils(void); /*proto*/ +PyMODINIT_FUNC PyInit__utils(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__utils(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4("_utils", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__tree___utils) { + if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.tree._utils")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.tree._utils", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + __pyx_vtabptr_7sklearn_4tree_6_utils_Stack = &__pyx_vtable_7sklearn_4tree_6_utils_Stack; + __pyx_vtable_7sklearn_4tree_6_utils_Stack.is_empty = (int (*)(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *))__pyx_f_7sklearn_4tree_6_utils_5Stack_is_empty; + __pyx_vtable_7sklearn_4tree_6_utils_Stack.push = (int (*)(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, int, double, __pyx_t_7sklearn_4tree_6_utils_SIZE_t))__pyx_f_7sklearn_4tree_6_utils_5Stack_push; + __pyx_vtable_7sklearn_4tree_6_utils_Stack.pop = (int (*)(struct __pyx_obj_7sklearn_4tree_6_utils_Stack *, struct __pyx_t_7sklearn_4tree_6_utils_StackRecord *))__pyx_f_7sklearn_4tree_6_utils_5Stack_pop; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_6_utils_Stack) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_6_utils_Stack.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_6_utils_Stack.tp_dict, __pyx_vtabptr_7sklearn_4tree_6_utils_Stack) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "Stack", (PyObject *)&__pyx_type_7sklearn_4tree_6_utils_Stack) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_6_utils_Stack = &__pyx_type_7sklearn_4tree_6_utils_Stack; + __pyx_vtabptr_7sklearn_4tree_6_utils_PriorityHeap = &__pyx_vtable_7sklearn_4tree_6_utils_PriorityHeap; + __pyx_vtable_7sklearn_4tree_6_utils_PriorityHeap.is_empty = (int (*)(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *))__pyx_f_7sklearn_4tree_6_utils_12PriorityHeap_is_empty; + __pyx_vtable_7sklearn_4tree_6_utils_PriorityHeap.push = (int (*)(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, __pyx_t_7sklearn_4tree_6_utils_SIZE_t, int, double, double, double, double))__pyx_f_7sklearn_4tree_6_utils_12PriorityHeap_push; + __pyx_vtable_7sklearn_4tree_6_utils_PriorityHeap.pop = (int (*)(struct __pyx_obj_7sklearn_4tree_6_utils_PriorityHeap *, struct __pyx_t_7sklearn_4tree_6_utils_PriorityHeapRecord *))__pyx_f_7sklearn_4tree_6_utils_12PriorityHeap_pop; + if (PyType_Ready(&__pyx_type_7sklearn_4tree_6_utils_PriorityHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_4tree_6_utils_PriorityHeap.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_4tree_6_utils_PriorityHeap.tp_dict, __pyx_vtabptr_7sklearn_4tree_6_utils_PriorityHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "PriorityHeap", (PyObject *)&__pyx_type_7sklearn_4tree_6_utils_PriorityHeap) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_4tree_6_utils_PriorityHeap = &__pyx_type_7sklearn_4tree_6_utils_PriorityHeap; + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 864; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/tree/_utils.pyx":1 + * # cython: cdivision=True # <<<<<<<<<<<<<< + * # cython: boundscheck=False + * # cython: wraparound=False + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "../../../../anaconda/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":979 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + if (__pyx_m) { + if (__pyx_d) { + __Pyx_AddTraceback("init sklearn.tree._utils", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.tree._utils"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* --- Runtime support code --- */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + if (PyType_Check(type)) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if CYTHON_COMPILING_IN_PYPY + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(tmp_type, tmp_value, tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#else + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ + { \ + func_type value = func_value; \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + if (is_unsigned && unlikely(value < zero)) \ + goto raise_neg_overflow; \ + else \ + goto raise_overflow; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *x) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (Py_intptr_t) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(Py_intptr_t, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(Py_intptr_t) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyLong_AsLong(x)) + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + Py_intptr_t val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (Py_intptr_t) -1; + } + } else { + Py_intptr_t val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (Py_intptr_t) -1; + val = __Pyx_PyInt_As_Py_intptr_t(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to Py_intptr_t"); + return (Py_intptr_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } +} + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong(x)) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); + } +} + +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, +(((PyLongObject*)x)->ob_digit[0])); + case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + } + #endif +#endif + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong(x)) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong(x)) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + return PyErr_WarnEx(NULL, message, 1); + } + return 0; +} + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + } + else if ((size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else + if (__Pyx_PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif + } else +#endif +#if !CYTHON_COMPILING_IN_PYPY + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_MAJOR_VERSION < 3 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%.4s__ returned non-%.4s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { + return PyInt_FromSize_t(ival); +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/tree/_utils.pxd b/sklearn/tree/_utils.pxd new file mode 100644 index 0000000000000..eef93aa99643b --- /dev/null +++ b/sklearn/tree/_utils.pxd @@ -0,0 +1,68 @@ +# Authors: Gilles Louppe +# Peter Prettenhofer +# Arnaud Joly +# +# Licence: BSD 3 clause + +# See _utils.pyx for details. + +import numpy as np +cimport numpy as np + +ctypedef np.npy_intp SIZE_t # Type for indices and counters + + +# ============================================================================= +# Stack data structure +# ============================================================================= + +# A record on the stack for depth-first tree growing +cdef struct StackRecord: + SIZE_t start + SIZE_t end + SIZE_t depth + SIZE_t parent + bint is_left + double impurity + SIZE_t n_constant_features + +cdef class Stack: + cdef SIZE_t capacity + cdef SIZE_t top + cdef StackRecord* stack_ + + cdef bint is_empty(self) nogil + cdef int push(self, SIZE_t start, SIZE_t end, SIZE_t depth, SIZE_t parent, + bint is_left, double impurity, + SIZE_t n_constant_features) nogil + cdef int pop(self, StackRecord* res) nogil + + +# ============================================================================= +# PriorityHeap data structure +# ============================================================================= + +# A record on the frontier for best-first tree growing +cdef struct PriorityHeapRecord: + SIZE_t node_id + SIZE_t start + SIZE_t end + SIZE_t pos + SIZE_t depth + bint is_leaf + double impurity + double impurity_left + double impurity_right + double improvement + +cdef class PriorityHeap: + cdef SIZE_t capacity + cdef SIZE_t heap_ptr + cdef PriorityHeapRecord* heap_ + + cdef bint is_empty(self) nogil + cdef int push(self, SIZE_t node_id, SIZE_t start, SIZE_t end, SIZE_t pos, + SIZE_t depth, bint is_leaf, double improvement, + double impurity, double impurity_left, + double impurity_right) nogil + cdef int pop(self, PriorityHeapRecord* res) nogil diff --git a/sklearn/tree/_utils.pyx b/sklearn/tree/_utils.pyx new file mode 100644 index 0000000000000..a52031181bc37 --- /dev/null +++ b/sklearn/tree/_utils.pyx @@ -0,0 +1,230 @@ +# cython: cdivision=True +# cython: boundscheck=False +# cython: wraparound=False + +# Authors: Gilles Louppe +# Peter Prettenhofer +# Arnaud Joly +# +# Licence: BSD 3 clause + +from libc.stdlib cimport free, malloc, realloc + +# ============================================================================= +# Stack data structure +# ============================================================================= + +cdef class Stack: + """A LIFO data structure. + + Attributes + ---------- + capacity : SIZE_t + The elements the stack can hold; if more added then ``self.stack_`` + needs to be resized. + + top : SIZE_t + The number of elements currently on the stack. + + stack : StackRecord pointer + The stack of records (upward in the stack corresponds to the right). + """ + + def __cinit__(self, SIZE_t capacity): + self.capacity = capacity + self.top = 0 + self.stack_ = malloc(capacity * sizeof(StackRecord)) + if self.stack_ == NULL: + raise MemoryError() + + def __dealloc__(self): + free(self.stack_) + + cdef bint is_empty(self) nogil: + return self.top <= 0 + + cdef int push(self, SIZE_t start, SIZE_t end, SIZE_t depth, SIZE_t parent, + bint is_left, double impurity, + SIZE_t n_constant_features) nogil: + """Push a new element onto the stack. + + Returns 0 if successful; -1 on out of memory error. + """ + cdef SIZE_t top = self.top + cdef StackRecord* stack = NULL + + # Resize if capacity not sufficient + if top >= self.capacity: + self.capacity *= 2 + stack = realloc(self.stack_, + self.capacity * sizeof(StackRecord)) + if stack == NULL: + # no free; __dealloc__ handles that + return -1 + self.stack_ = stack + + stack = self.stack_ + stack[top].start = start + stack[top].end = end + stack[top].depth = depth + stack[top].parent = parent + stack[top].is_left = is_left + stack[top].impurity = impurity + stack[top].n_constant_features = n_constant_features + + # Increment stack pointer + self.top = top + 1 + return 0 + + cdef int pop(self, StackRecord* res) nogil: + """Remove the top element from the stack and copy to ``res``. + + Returns 0 if pop was successful (and ``res`` is set); -1 + otherwise. + """ + cdef SIZE_t top = self.top + cdef StackRecord* stack = self.stack_ + + if top <= 0: + return -1 + + res[0] = stack[top - 1] + self.top = top - 1 + + return 0 + + +# ============================================================================= +# PriorityHeap data structure +# ============================================================================= + +cdef void heapify_up(PriorityHeapRecord* heap, SIZE_t pos) nogil: + """Restore heap invariant parent.improvement > child.improvement from + ``pos`` upwards. """ + if pos == 0: + return + + cdef SIZE_t parent_pos = (pos - 1) / 2 + + if heap[parent_pos].improvement < heap[pos].improvement: + heap[parent_pos], heap[pos] = heap[pos], heap[parent_pos] + heapify_up(heap, parent_pos) + + +cdef void heapify_down(PriorityHeapRecord* heap, SIZE_t pos, + SIZE_t heap_length) nogil: + """Restore heap invariant parent.improvement > children.improvement from + ``pos`` downwards. """ + cdef SIZE_t left_pos = 2 * (pos + 1) - 1 + cdef SIZE_t right_pos = 2 * (pos + 1) + cdef SIZE_t largest = pos + + if (left_pos < heap_length and + heap[left_pos].improvement > heap[largest].improvement): + largest = left_pos + + if (right_pos < heap_length and + heap[right_pos].improvement > heap[largest].improvement): + largest = right_pos + + if largest != pos: + heap[pos], heap[largest] = heap[largest], heap[pos] + heapify_down(heap, largest, heap_length) + + +cdef class PriorityHeap: + """A priority queue implemented as a binary heap. + + The heap invariant is that the impurity improvement of the parent record + is larger then the impurity improvement of the children. + + Attributes + ---------- + capacity : SIZE_t + The capacity of the heap + + heap_ptr : SIZE_t + The water mark of the heap; the heap grows from left to right in the + array ``heap_``. The following invariant holds ``heap_ptr < capacity``. + + heap_ : PriorityHeapRecord* + The array of heap records. The maximum element is on the left; + the heap grows from left to right + """ + + def __cinit__(self, SIZE_t capacity): + self.capacity = capacity + self.heap_ptr = 0 + self.heap_ = malloc(capacity * sizeof(PriorityHeapRecord)) + if self.heap_ == NULL: + raise MemoryError() + + def __dealloc__(self): + free(self.heap_) + + cdef bint is_empty(self) nogil: + return self.heap_ptr <= 0 + + cdef int push(self, SIZE_t node_id, SIZE_t start, SIZE_t end, SIZE_t pos, + SIZE_t depth, bint is_leaf, double improvement, + double impurity, double impurity_left, + double impurity_right) nogil: + """Push record on the priority heap. + + Returns 0 if successful; -1 on out of memory error. + """ + cdef SIZE_t heap_ptr = self.heap_ptr + cdef PriorityHeapRecord* heap = NULL + + # Resize if capacity not sufficient + if heap_ptr >= self.capacity: + self.capacity *= 2 + heap = realloc(self.heap_, + self.capacity * + sizeof(PriorityHeapRecord)) + if heap == NULL: + # no free; __dealloc__ handles that + return -1 + self.heap_ = heap + + # Put element as last element of heap + heap = self.heap_ + heap[heap_ptr].node_id = node_id + heap[heap_ptr].start = start + heap[heap_ptr].end = end + heap[heap_ptr].pos = pos + heap[heap_ptr].depth = depth + heap[heap_ptr].is_leaf = is_leaf + heap[heap_ptr].impurity = impurity + heap[heap_ptr].impurity_left = impurity_left + heap[heap_ptr].impurity_right = impurity_right + heap[heap_ptr].improvement = improvement + + # Heapify up + heapify_up(heap, heap_ptr) + + # Increase element count + self.heap_ptr = heap_ptr + 1 + return 0 + + cdef int pop(self, PriorityHeapRecord* res) nogil: + """Remove max element from the heap. """ + cdef SIZE_t heap_ptr = self.heap_ptr + cdef PriorityHeapRecord* heap = self.heap_ + + if heap_ptr <= 0: + return -1 + + # Take first element + res[0] = heap[0] + + # Put last element to the front + heap[0], heap[heap_ptr - 1] = heap[heap_ptr - 1], heap[0] + + # Restore heap invariant + if heap_ptr > 1: + heapify_down(heap, 0, heap_ptr - 1) + + self.heap_ptr = heap_ptr - 1 + + return 0 diff --git a/sklearn/tree/export.py b/sklearn/tree/export.py new file mode 100644 index 0000000000000..62cd2102359eb --- /dev/null +++ b/sklearn/tree/export.py @@ -0,0 +1,133 @@ +""" +This module defines export functions for decision trees. +""" + +# Authors: Gilles Louppe +# Peter Prettenhofer +# Brian Holt +# Noel Dawe +# Satrajit Gosh +# Licence: BSD 3 clause + +from ..externals import six + +from . import _tree + + +def export_graphviz(decision_tree, out_file="tree.dot", feature_names=None, + max_depth=None): + """Export a decision tree in DOT format. + + This function generates a GraphViz representation of the decision tree, + which is then written into `out_file`. Once exported, graphical renderings + can be generated using, for example:: + + $ dot -Tps tree.dot -o tree.ps (PostScript format) + $ dot -Tpng tree.dot -o tree.png (PNG format) + + The sample counts that are shown are weighted with any sample_weights that + might be present. + + Parameters + ---------- + decision_tree : decision tree classifier + The decision tree to be exported to GraphViz. + + out_file : file object or string, optional (default="tree.dot") + Handle or name of the output file. + + feature_names : list of strings, optional (default=None) + Names of each of the features. + + max_depth : int, optional (default=None) + The maximum depth of the representation. If None, the tree is fully + generated. + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn import tree + + >>> clf = tree.DecisionTreeClassifier() + >>> iris = load_iris() + + >>> clf = clf.fit(iris.data, iris.target) + >>> tree.export_graphviz(clf, + ... out_file='tree.dot') # doctest: +SKIP + """ + def node_to_str(tree, node_id, criterion): + if not isinstance(criterion, six.string_types): + criterion = "impurity" + + value = tree.value[node_id] + if tree.n_outputs == 1: + value = value[0, :] + + if tree.children_left[node_id] == _tree.TREE_LEAF: + return "%s = %.4f\\nsamples = %s\\nvalue = %s" \ + % (criterion, + tree.impurity[node_id], + tree.n_node_samples[node_id], + value) + else: + if feature_names is not None: + feature = feature_names[tree.feature[node_id]] + else: + feature = "X[%s]" % tree.feature[node_id] + + return "%s <= %.4f\\n%s = %s\\nsamples = %s" \ + % (feature, + tree.threshold[node_id], + criterion, + tree.impurity[node_id], + tree.n_node_samples[node_id]) + + def recurse(tree, node_id, criterion, parent=None, depth=0): + if node_id == _tree.TREE_LEAF: + raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF) + + left_child = tree.children_left[node_id] + right_child = tree.children_right[node_id] + + # Add node with description + if max_depth is None or depth <= max_depth: + out_file.write('%d [label="%s", shape="box"] ;\n' % + (node_id, node_to_str(tree, node_id, criterion))) + + if parent is not None: + # Add edge to parent + out_file.write('%d -> %d ;\n' % (parent, node_id)) + + if left_child != _tree.TREE_LEAF: + recurse(tree, left_child, criterion=criterion, parent=node_id, + depth=depth + 1) + recurse(tree, right_child, criterion=criterion, parent=node_id, + depth=depth + 1) + + else: + out_file.write('%d [label="(...)", shape="box"] ;\n' % node_id) + + if parent is not None: + # Add edge to parent + out_file.write('%d -> %d ;\n' % (parent, node_id)) + + own_file = False + try: + if isinstance(out_file, six.string_types): + if six.PY3: + out_file = open(out_file, "w", encoding="utf-8") + else: + out_file = open(out_file, "wb") + own_file = True + + out_file.write("digraph Tree {\n") + + if isinstance(decision_tree, _tree.Tree): + recurse(decision_tree, 0, criterion="impurity") + else: + recurse(decision_tree.tree_, 0, criterion=decision_tree.criterion) + out_file.write("}") + + finally: + if own_file: + out_file.close() diff --git a/sklearn/tree/setup.py b/sklearn/tree/setup.py index 6cd819647c947..d38420ebce181 100644 --- a/sklearn/tree/setup.py +++ b/sklearn/tree/setup.py @@ -12,7 +12,13 @@ def configuration(parent_package="", top_path=None): config.add_extension("_tree", sources=["_tree.c"], include_dirs=[numpy.get_include()], - libraries=libraries) + libraries=libraries, + extra_compile_args=["-O3"]) + config.add_extension("_utils", + sources=["_utils.c"], + include_dirs=[numpy.get_include()], + libraries=libraries, + extra_compile_args=["-O3"]) config.add_subpackage("tests") diff --git a/sklearn/tree/tests/test_export.py b/sklearn/tree/tests/test_export.py new file mode 100644 index 0000000000000..30af1bb8f3b08 --- /dev/null +++ b/sklearn/tree/tests/test_export.py @@ -0,0 +1,88 @@ +""" +Testing for export functions of decision trees (sklearn.tree.export). +""" + +from numpy.testing import assert_equal +from nose.tools import assert_raises + +from sklearn.tree import DecisionTreeClassifier +from sklearn.tree import export_graphviz +from sklearn.externals.six import StringIO + +# toy sample +X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] +y = [-1, -1, -1, 1, 1, 1] +T = [[-1, -1], [2, 2], [3, 2]] +true_result = [-1, 1, 1] + + +def test_graphviz_toy(): + """Check correctness of export_graphviz""" + clf = DecisionTreeClassifier(max_depth=3, + min_samples_split=1, + criterion="gini", + random_state=2) + clf.fit(X, y) + + # Test export code + out = StringIO() + export_graphviz(clf, out_file=out) + contents1 = out.getvalue() + contents2 = "digraph Tree {\n" \ + "0 [label=\"X[0] <= 0.0000\\ngini = 0.5\\n" \ + "samples = 6\", shape=\"box\"] ;\n" \ + "1 [label=\"gini = 0.0000\\nsamples = 3\\n" \ + "value = [ 3. 0.]\", shape=\"box\"] ;\n" \ + "0 -> 1 ;\n" \ + "2 [label=\"gini = 0.0000\\nsamples = 3\\n" \ + "value = [ 0. 3.]\", shape=\"box\"] ;\n" \ + "0 -> 2 ;\n" \ + "}" + + assert_equal(contents1, contents2) + + # Test with feature_names + out = StringIO() + export_graphviz(clf, out_file=out, feature_names=["feature0", "feature1"]) + contents1 = out.getvalue() + contents2 = "digraph Tree {\n" \ + "0 [label=\"feature0 <= 0.0000\\ngini = 0.5\\n" \ + "samples = 6\", shape=\"box\"] ;\n" \ + "1 [label=\"gini = 0.0000\\nsamples = 3\\n" \ + "value = [ 3. 0.]\", shape=\"box\"] ;\n" \ + "0 -> 1 ;\n" \ + "2 [label=\"gini = 0.0000\\nsamples = 3\\n" \ + "value = [ 0. 3.]\", shape=\"box\"] ;\n" \ + "0 -> 2 ;\n" \ + "}" + + assert_equal(contents1, contents2) + + # Test max_depth + out = StringIO() + export_graphviz(clf, out_file=out, max_depth=0) + contents1 = out.getvalue() + contents2 = "digraph Tree {\n" \ + "0 [label=\"X[0] <= 0.0000\\ngini = 0.5\\n" \ + "samples = 6\", shape=\"box\"] ;\n" \ + "1 [label=\"(...)\", shape=\"box\"] ;\n" \ + "0 -> 1 ;\n" \ + "2 [label=\"(...)\", shape=\"box\"] ;\n" \ + "0 -> 2 ;\n" \ + "}" + + assert_equal(contents1, contents2) + + +def test_graphviz_errors(): + """Check for errors of export_graphviz""" + clf = DecisionTreeClassifier(max_depth=3, min_samples_split=1) + clf.fit(X, y) + + out = StringIO() + assert_raises(IndexError, export_graphviz, clf, out, feature_names=[]) + + +if __name__ == "__main__": + import nose + nose.runmodule() diff --git a/sklearn/tree/tests/test_tree.py b/sklearn/tree/tests/test_tree.py index f8cbf2fbfca2e..c8f68b21bbe58 100644 --- a/sklearn/tree/tests/test_tree.py +++ b/sklearn/tree/tests/test_tree.py @@ -1,18 +1,103 @@ """ Testing for the tree module (sklearn.tree). """ +import pickle +from functools import partial +from itertools import product +import platform import numpy as np -from numpy.testing import assert_array_equal -from numpy.testing import assert_array_almost_equal -from numpy.testing import assert_almost_equal -from numpy.testing import assert_equal -from nose.tools import assert_raises -from nose.tools import assert_true +from scipy.sparse import csc_matrix +from scipy.sparse import csr_matrix +from scipy.sparse import coo_matrix + +from sklearn.random_projection import sparse_random_matrix +from sklearn.utils.random import sample_without_replacement + +from sklearn.metrics import accuracy_score +from sklearn.metrics import mean_squared_error + +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_in +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_greater_equal +from sklearn.utils.testing import assert_less +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import raises +from sklearn.utils.validation import check_random_state + +from sklearn.tree import DecisionTreeClassifier +from sklearn.tree import DecisionTreeRegressor +from sklearn.tree import ExtraTreeClassifier +from sklearn.tree import ExtraTreeRegressor from sklearn import tree +from sklearn.tree.tree import SPARSE_SPLITTERS +from sklearn.tree._tree import TREE_LEAF from sklearn import datasets +from sklearn.preprocessing._weights import _balance_weights + + +CLF_CRITERIONS = ("gini", "entropy") +REG_CRITERIONS = ("mse", ) + +CLF_TREES = { + "DecisionTreeClassifier": DecisionTreeClassifier, + "Presort-DecisionTreeClassifier": partial(DecisionTreeClassifier, + splitter="presort-best"), + "ExtraTreeClassifier": ExtraTreeClassifier, +} + +REG_TREES = { + "DecisionTreeRegressor": DecisionTreeRegressor, + "Presort-DecisionTreeRegressor": partial(DecisionTreeRegressor, + splitter="presort-best"), + "ExtraTreeRegressor": ExtraTreeRegressor, +} + +ALL_TREES = dict() +ALL_TREES.update(CLF_TREES) +ALL_TREES.update(REG_TREES) + +SPARSE_TREES = [name for name, Tree in ALL_TREES.items() + if Tree().splitter in SPARSE_SPLITTERS] + + +X_small = np.array([ + [0, 0, 4, 0, 0, 0, 1, -14, 0, -4, 0, 0, 0, 0, ], + [0, 0, 5, 3, 0, -4, 0, 0, 1, -5, 0.2, 0, 4, 1, ], + [-1, -1, 0, 0, -4.5, 0, 0, 2.1, 1, 0, 0, -4.5, 0, 1, ], + [-1, -1, 0, -1.2, 0, 0, 0, 0, 0, 0, 0.2, 0, 0, 1, ], + [-1, -1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, ], + [-1, -2, 0, 4, -3, 10, 4, 0, -3.2, 0, 4, 3, -4, 1, ], + [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -3, 1, ], + [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1, ], + [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1, ], + [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -1, 0, ], + [2, 8, 5, 1, 0.5, -4, 10, 0, 1, -5, 3, 0, 2, 0, ], + [2, 0, 1, 1, 1, -1, 1, 0, 0, -2, 3, 0, 1, 0, ], + [2, 0, 1, 2, 3, -1, 10, 2, 0, -1, 1, 2, 2, 0, ], + [1, 1, 0, 2, 2, -1, 1, 2, 0, -5, 1, 2, 3, 0, ], + [3, 1, 0, 3, 0, -4, 10, 0, 1, -5, 3, 0, 3, 1, ], + [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 0.5, 0, -3, 1, ], + [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 1.5, 1, -1, -1, ], + [2.11, 8, -6, -0.5, 0, 10, 0, 0, -3.2, 6, 0.5, 0, -1, -1, ], + [2, 0, 5, 1, 0.5, -2, 10, 0, 1, -5, 3, 1, 0, -1, ], + [2, 0, 1, 1, 1, -2, 1, 0, 0, -2, 0, 0, 0, 1, ], + [2, 1, 1, 1, 2, -1, 10, 2, 0, -1, 0, 2, 1, 1, ], + [1, 1, 0, 0, 1, -3, 1, 2, 0, -5, 1, 2, 1, 1, ], + [3, 1, 0, 1, 0, -4, 1, 0, 1, -2, 0, 0, 1, 0, ]]) + +y_small = [1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, + 0, 0] +y_small_reg = [1.0, 2.1, 1.2, 0.05, 10, 2.4, 3.1, 1.01, 0.01, 2.98, 3.1, 1.1, + 0.0, 1.2, 2, 11, 0, 0, 4.5, 0.201, 1.06, 0.9, 0] + # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y = [-1, -1, -1, 1, 1, 1] @@ -34,150 +119,200 @@ boston.data = boston.data[perm] boston.target = boston.target[perm] +digits = datasets.load_digits() +perm = rng.permutation(digits.target.size) +digits.data = digits.data[perm] +digits.target = digits.target[perm] + +random_state = check_random_state(0) +X_multilabel, y_multilabel = datasets.make_multilabel_classification( + random_state=0, return_indicator=True, n_samples=30, n_features=10) + +X_sparse_pos = random_state.uniform(size=(20, 5)) +X_sparse_pos[X_sparse_pos <= 0.8] = 0. +y_random = random_state.randint(0, 4, size=(20, )) +X_sparse_mix = sparse_random_matrix(20, 10, density=0.25, random_state=0) + + +DATASETS = { + "iris": {"X": iris.data, "y": iris.target}, + "boston": {"X": boston.data, "y": boston.target}, + "digits": {"X": digits.data, "y": digits.target}, + "toy": {"X": X, "y": y}, + "clf_small": {"X": X_small, "y": y_small}, + "reg_small": {"X": X_small, "y": y_small_reg}, + "multilabel": {"X": X_multilabel, "y": y_multilabel}, + "sparse-pos": {"X": X_sparse_pos, "y": y_random}, + "sparse-neg": {"X": - X_sparse_pos, "y": y_random}, + "sparse-mix": {"X": X_sparse_mix, "y": y_random}, + "zeros": {"X": np.zeros((20, 3)), "y": y_random} +} + +for name in DATASETS: + DATASETS[name]["X_sparse"] = csc_matrix(DATASETS[name]["X"]) + + +def assert_tree_equal(d, s, message): + assert_equal(s.node_count, d.node_count, + "{0}: inequal number of node ({1} != {2})" + "".format(message, s.node_count, d.node_count)) + + assert_array_equal(d.children_right, s.children_right, + message + ": inequal children_right") + assert_array_equal(d.children_left, s.children_left, + message + ": inequal children_left") + + external = d.children_right == TREE_LEAF + internal = np.logical_not(external) + + assert_array_equal(d.feature[internal], s.feature[internal], + message + ": inequal features") + assert_array_equal(d.threshold[internal], s.threshold[internal], + message + ": inequal threshold") + assert_array_equal(d.n_node_samples.sum(), s.n_node_samples.sum(), + message + ": inequal sum(n_node_samples)") + assert_array_equal(d.n_node_samples, s.n_node_samples, + message + ": inequal n_node_samples") + + assert_almost_equal(d.impurity, s.impurity, + err_msg=message + ": inequal impurity") + + assert_array_almost_equal(d.value[external], s.value[external], + err_msg=message + ": inequal value") + def test_classification_toy(): """Check classification on a toy dataset.""" - clf = tree.DecisionTreeClassifier() - clf.fit(X, y) + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) + clf.fit(X, y) + assert_array_equal(clf.predict(T), true_result, + "Failed with {0}".format(name)) + + clf = Tree(max_features=1, random_state=1) + clf.fit(X, y) + assert_array_equal(clf.predict(T), true_result, + "Failed with {0}".format(name)) + - assert_array_equal(clf.predict(T), true_result) +def test_weighted_classification_toy(): + """Check classification on a weighted toy dataset.""" + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) - # With subsampling - clf = tree.DecisionTreeClassifier(max_features=1, random_state=1) - clf.fit(X, y) + clf.fit(X, y, sample_weight=np.ones(len(X))) + assert_array_equal(clf.predict(T), true_result, + "Failed with {0}".format(name)) - assert_array_equal(clf.predict(T), true_result) + clf.fit(X, y, sample_weight=np.ones(len(X)) * 0.5) + assert_array_equal(clf.predict(T), true_result, + "Failed with {0}".format(name)) def test_regression_toy(): """Check regression on a toy dataset.""" - clf = tree.DecisionTreeRegressor() - clf.fit(X, y) - - assert_almost_equal(clf.predict(T), true_result) - - # With subsampling - clf = tree.DecisionTreeRegressor(max_features=1, random_state=1) - clf.fit(X, y) - - assert_almost_equal(clf.predict(T), true_result) - - -def test_graphviz_toy(): - """Check correctness of graphviz output on a toy dataset.""" - clf = tree.DecisionTreeClassifier(max_depth=3, min_samples_split=1) - clf.fit(X, y) - from StringIO import StringIO - - # test export code - out = StringIO() - tree.export_graphviz(clf, out_file=out) - contents1 = out.getvalue() - - tree_toy = StringIO("digraph Tree {\n" - "0 [label=\"X[0] <= 0.0000\\nerror = 0.5" - "\\nsamples = 6\\nvalue = [ 3. 3.]\", shape=\"box\"] ;\n" - "1 [label=\"error = 0.0000\\nsamples = 3\\nvalue = [ 3. 0.]\", shape=\"box\"] ;\n" - "0 -> 1 ;\n" - "2 [label=\"error = 0.0000\\nsamples = 3\\nvalue = [ 0. 3.]\", shape=\"box\"] ;\n" - "0 -> 2 ;\n" - "}") - contents2 = tree_toy.getvalue() - - assert contents1 == contents2, \ - "graphviz output test failed\n: %s != %s" % (contents1, contents2) - - # test with feature_names - out = StringIO() - out = tree.export_graphviz(clf, out_file=out, - feature_names=["feature1", ""]) - contents1 = out.getvalue() - - tree_toy = StringIO("digraph Tree {\n" - "0 [label=\"feature1 <= 0.0000\\nerror = 0.5" - "\\nsamples = 6\\nvalue = [ 3. 3.]\", shape=\"box\"] ;\n" - "1 [label=\"error = 0.0000\\nsamples = 3\\nvalue = [ 3. 0.]\", shape=\"box\"] ;\n" - "0 -> 1 ;\n" - "2 [label=\"error = 0.0000\\nsamples = 3\\nvalue = [ 0. 3.]\", shape=\"box\"] ;\n" - "0 -> 2 ;\n" - "}") - contents2 = tree_toy.getvalue() - - assert contents1 == contents2, \ - "graphviz output test failed\n: %s != %s" % (contents1, contents2) - - # test improperly formed feature_names - out = StringIO() - assert_raises(IndexError, tree.export_graphviz, - clf, out, feature_names=[]) + for name, Tree in REG_TREES.items(): + reg = Tree(random_state=1) + reg.fit(X, y) + assert_almost_equal(reg.predict(T), true_result, + err_msg="Failed with {0}".format(name)) + clf = Tree(max_features=1, random_state=1) + clf.fit(X, y) + assert_almost_equal(reg.predict(T), true_result, + err_msg="Failed with {0}".format(name)) -def test_iris(): - """Check consistency on dataset iris.""" - for c in ('gini', \ - 'entropy'): - clf = tree.DecisionTreeClassifier(criterion=c)\ - .fit(iris.data, iris.target) - score = np.mean(clf.predict(iris.data) == iris.target) - assert score > 0.9, "Failed with criterion " + c + \ - " and score = " + str(score) +def test_xor(): + """Check on a XOR problem""" + y = np.zeros((10, 10)) + y[:5, :5] = 1 + y[5:, 5:] = 1 + + gridx, gridy = np.indices(y.shape) - clf = tree.DecisionTreeClassifier(criterion=c, - max_features=2, - random_state=1)\ - .fit(iris.data, iris.target) + X = np.vstack([gridx.ravel(), gridy.ravel()]).T + y = y.ravel() - score = np.mean(clf.predict(iris.data) == iris.target) - assert score > 0.5, "Failed with criterion " + c + \ - " and score = " + str(score) + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) + clf.fit(X, y) + assert_equal(clf.score(X, y), 1.0, + "Failed with {0}".format(name)) + + clf = Tree(random_state=0, max_features=1) + clf.fit(X, y) + assert_equal(clf.score(X, y), 1.0, + "Failed with {0}".format(name)) + + +def test_iris(): + """Check consistency on dataset iris.""" + for (name, Tree), criterion in product(CLF_TREES.items(), CLF_CRITERIONS): + clf = Tree(criterion=criterion, random_state=0) + clf.fit(iris.data, iris.target) + score = accuracy_score(clf.predict(iris.data), iris.target) + assert_greater(score, 0.9, + "Failed with {0}, criterion = {1} and score = {2}" + "".format(name, criterion, score)) + + clf = Tree(criterion=criterion, max_features=2, random_state=0) + clf.fit(iris.data, iris.target) + score = accuracy_score(clf.predict(iris.data), iris.target) + assert_greater(score, 0.5, + "Failed with {0}, criterion = {1} and score = {2}" + "".format(name, criterion, score)) def test_boston(): """Check consistency on dataset boston house prices.""" - for c in ('mse',): - clf = tree.DecisionTreeRegressor(criterion=c)\ - .fit(boston.data, boston.target) - - score = np.mean(np.power(clf.predict(boston.data) - boston.target, 2)) - assert score < 1, "Failed with criterion " + c + \ - " and score = " + str(score) - clf = tree.DecisionTreeRegressor(criterion=c, - max_features=6, - random_state=1)\ - .fit(boston.data, boston.target) + for (name, Tree), criterion in product(REG_TREES.items(), REG_CRITERIONS): + reg = Tree(criterion=criterion, random_state=0) + reg.fit(boston.data, boston.target) + score = mean_squared_error(boston.target, reg.predict(boston.data)) + assert_less(score, 1, + "Failed with {0}, criterion = {1} and score = {2}" + "".format(name, criterion, score)) - #using fewer features reduces the learning ability of this tree, + # using fewer features reduces the learning ability of this tree, # but reduces training time. - score = np.mean(np.power(clf.predict(boston.data) - boston.target, 2)) - assert score < 2, "Failed with criterion " + c + \ - " and score = " + str(score) + reg = Tree(criterion=criterion, max_features=6, random_state=0) + reg.fit(boston.data, boston.target) + score = mean_squared_error(boston.target, reg.predict(boston.data)) + assert_less(score, 2, + "Failed with {0}, criterion = {1} and score = {2}" + "".format(name, criterion, score)) def test_probability(): """Predict probabilities using DecisionTreeClassifier.""" - clf = tree.DecisionTreeClassifier(max_depth=1, max_features=1, - random_state=42) - clf.fit(iris.data, iris.target) - prob_predict = clf.predict_proba(iris.data) - assert_array_almost_equal( - np.sum(prob_predict, 1), np.ones(iris.data.shape[0])) - assert np.mean(np.argmax(prob_predict, 1) - == clf.predict(iris.data)) > 0.9 + for name, Tree in CLF_TREES.items(): + clf = Tree(max_depth=1, max_features=1, random_state=42) + clf.fit(iris.data, iris.target) - assert_almost_equal(clf.predict_proba(iris.data), - np.exp(clf.predict_log_proba(iris.data)), 8) + prob_predict = clf.predict_proba(iris.data) + assert_array_almost_equal(np.sum(prob_predict, 1), + np.ones(iris.data.shape[0]), + err_msg="Failed with {0}".format(name)) + assert_array_equal(np.argmax(prob_predict, 1), + clf.predict(iris.data), + err_msg="Failed with {0}".format(name)) + assert_almost_equal(clf.predict_proba(iris.data), + np.exp(clf.predict_log_proba(iris.data)), 8, + err_msg="Failed with {0}".format(name)) def test_arrayrepr(): """Check the array representation.""" # Check resize - clf = tree.DecisionTreeRegressor(max_depth=None) X = np.arange(10000)[:, np.newaxis] y = np.arange(10000) - clf.fit(X, y) + + for name, Tree in REG_TREES.items(): + reg = Tree(max_depth=None, random_state=0) + reg.fit(X, y) def test_pure_set(): @@ -185,20 +320,23 @@ def test_pure_set(): X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y = [1, 1, 1, 1, 1, 1] - clf = tree.DecisionTreeClassifier().fit(X, y) - assert_array_equal(clf.predict(X), y) + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(random_state=0) + clf.fit(X, y) + assert_array_equal(clf.predict(X), y, + err_msg="Failed with {0}".format(name)) - clf = tree.DecisionTreeRegressor().fit(X, y) - assert_array_equal(clf.predict(X), y) + for name, TreeRegressor in REG_TREES.items(): + reg = TreeRegressor(random_state=0) + reg.fit(X, y) + assert_almost_equal(clf.predict(X), y, + err_msg="Failed with {0}".format(name)) def test_numerical_stability(): """Check numerical stability.""" - old_settings = np.geterr() - np.seterr(all="raise") - - X = np.array( - [[152.08097839, 140.40744019, 129.75102234, 159.90493774], + X = np.array([ + [152.08097839, 140.40744019, 129.75102234, 159.90493774], [142.50700378, 135.81935120, 117.82884979, 162.75781250], [127.28772736, 140.40744019, 129.75102234, 159.90493774], [132.37025452, 143.71923828, 138.35694885, 157.84558105], @@ -207,20 +345,20 @@ def test_numerical_stability(): [120.91514587, 140.40744019, 129.75102234, 159.90493774]]) y = np.array( - [1., 0.70209277, 0.53896582, 0., 0.90914464, 0.48026916, 0.49622521]) - - dt = tree.DecisionTreeRegressor() - dt.fit(X, y) - dt.fit(X, -y) - dt.fit(-X, y) - dt.fit(-X, -y) + [1., 0.70209277, 0.53896582, 0., 0.90914464, 0.48026916, 0.49622521]) - np.seterr(**old_settings) + with np.errstate(all="raise"): + for name, Tree in REG_TREES.items(): + reg = Tree(random_state=0) + reg.fit(X, y) + reg.fit(X, -y) + reg.fit(-X, y) + reg.fit(-X, -y) def test_importances(): """Check variable importances.""" - X, y = datasets.make_classification(n_samples=1000, + X, y = datasets.make_classification(n_samples=2000, n_features=10, n_informative=3, n_redundant=0, @@ -228,151 +366,287 @@ def test_importances(): shuffle=False, random_state=0) - clf = tree.DecisionTreeClassifier(compute_importances=True) - clf.fit(X, y) - importances = clf.feature_importances_ - n_important = sum(importances > 0.1) + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) - assert_equal(importances.shape[0], 10) - assert_equal(n_important, 3) + clf.fit(X, y) + importances = clf.feature_importances_ + n_important = np.sum(importances > 0.1) - X_new = clf.transform(X, threshold="mean") - assert 0 < X_new.shape[1] < X.shape[1] + assert_equal(importances.shape[0], 10, "Failed with {0}".format(name)) + assert_equal(n_important, 3, "Failed with {0}".format(name)) - clf = tree.DecisionTreeClassifier() - clf.fit(X, y) - assert_true(clf.feature_importances_ is None) + X_new = clf.transform(X, threshold="mean") + assert_less(0, X_new.shape[1], "Failed with {0}".format(name)) + assert_less(X_new.shape[1], X.shape[1], "Failed with {0}".format(name)) + # Check on iris that importances are the same for all builders + clf = DecisionTreeClassifier(random_state=0) + clf.fit(iris.data, iris.target) + clf2 = DecisionTreeClassifier(random_state=0, + max_leaf_nodes=len(iris.data)) + clf2.fit(iris.data, iris.target) -def test_error(): - """Test that it gives proper exception on deficient input.""" - # Invalid values for parameters - assert_raises(ValueError, - tree.DecisionTreeClassifier(min_samples_leaf=-1).fit, - X, y) - - assert_raises(ValueError, - tree.DecisionTreeClassifier(max_depth=-1).fit, - X, y) - - assert_raises(ValueError, - tree.DecisionTreeClassifier(min_density=2.0).fit, - X, y) - - assert_raises(ValueError, - tree.DecisionTreeClassifier(max_features=42).fit, - X, y) - - # Wrong dimensions - clf = tree.DecisionTreeClassifier() - y2 = y[:-1] - assert_raises(ValueError, clf.fit, X, y2) - - # Test with arrays that are non-contiguous. - Xf = np.asfortranarray(X) - clf = tree.DecisionTreeClassifier() - clf.fit(Xf, y) - assert_array_equal(clf.predict(T), true_result) - - # predict before fitting - clf = tree.DecisionTreeClassifier() - assert_raises(Exception, clf.predict, T) - # predict on vector with different dims - clf.fit(X, y) - t = np.asarray(T) - assert_raises(ValueError, clf.predict, t[:, 1:]) - - # use values of max_features that are invalid - clf = tree.DecisionTreeClassifier(max_features=10) - assert_raises(ValueError, clf.fit, X, y) + assert_array_equal(clf.feature_importances_, + clf2.feature_importances_) - clf = tree.DecisionTreeClassifier(max_features=-1) - assert_raises(ValueError, clf.fit, X, y) - clf = tree.DecisionTreeClassifier(max_features="foobar") - assert_raises(ValueError, clf.fit, X, y) +@raises(ValueError) +def test_importances_raises(): + """Check if variable importance before fit raises ValueError. """ + clf = DecisionTreeClassifier() + clf.feature_importances_ - tree.DecisionTreeClassifier(max_features="auto").fit(X, y) - tree.DecisionTreeClassifier(max_features="sqrt").fit(X, y) - tree.DecisionTreeClassifier(max_features="log2").fit(X, y) - tree.DecisionTreeClassifier(max_features=None).fit(X, y) - # predict before fit - clf = tree.DecisionTreeClassifier() - assert_raises(Exception, clf.predict_proba, X) +def test_importances_gini_equal_mse(): + """Check that gini is equivalent to mse for binary output variable""" - clf.fit(X, y) - X2 = [-2, -1, 1] # wrong feature shape for sample - assert_raises(ValueError, clf.predict_proba, X2) + X, y = datasets.make_classification(n_samples=2000, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0) - # wrong sample shape - Xt = np.array(X).T + # The gini index and the mean square error (variance) might differ due + # to numerical instability. Since those instabilities mainly occurs at + # high tree depth, we restrict this maximal depth. + clf = DecisionTreeClassifier(criterion="gini", max_depth=5, + random_state=0).fit(X, y) + reg = DecisionTreeRegressor(criterion="mse", max_depth=5, + random_state=0).fit(X, y) - clf = tree.DecisionTreeClassifier() - clf.fit(np.dot(X, Xt), y) - assert_raises(ValueError, clf.predict, X) + assert_almost_equal(clf.feature_importances_, reg.feature_importances_) + assert_array_equal(clf.tree_.feature, reg.tree_.feature) + assert_array_equal(clf.tree_.children_left, reg.tree_.children_left) + assert_array_equal(clf.tree_.children_right, reg.tree_.children_right) + assert_array_equal(clf.tree_.n_node_samples, reg.tree_.n_node_samples) - clf = tree.DecisionTreeClassifier() - clf.fit(X, y) - assert_raises(ValueError, clf.predict, Xt) - # wrong length of sample mask - clf = tree.DecisionTreeClassifier() - sample_mask = np.array([1]) - assert_raises(ValueError, clf.fit, X, y, sample_mask=sample_mask) +def test_max_features(): + """Check max_features.""" + for name, TreeRegressor in REG_TREES.items(): + reg = TreeRegressor(max_features="auto") + reg.fit(boston.data, boston.target) + assert_equal(reg.max_features_, boston.data.shape[1]) - # wrong length of X_argsorted - clf = tree.DecisionTreeClassifier() - X_argsorted = np.array([1]) - assert_raises(ValueError, clf.fit, X, y, X_argsorted=X_argsorted) + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(max_features="auto") + clf.fit(iris.data, iris.target) + assert_equal(clf.max_features_, 2) + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(max_features="sqrt") + est.fit(iris.data, iris.target) + assert_equal(est.max_features_, + int(np.sqrt(iris.data.shape[1]))) -def test_min_samples_leaf(): - """Test if leaves contain more than leaf_count training examples""" - X = np.asfortranarray(iris.data.astype(tree._tree.DTYPE)) - y = iris.target + est = TreeEstimator(max_features="log2") + est.fit(iris.data, iris.target) + assert_equal(est.max_features_, + int(np.log2(iris.data.shape[1]))) - for tree_class in [tree.DecisionTreeClassifier, tree.ExtraTreeClassifier]: - clf = tree_class(min_samples_leaf=5).fit(X, y) + est = TreeEstimator(max_features=1) + est.fit(iris.data, iris.target) + assert_equal(est.max_features_, 1) - out = clf.tree_.apply(X) - node_counts = np.bincount(out) - leaf_count = node_counts[node_counts != 0] # drop inner nodes + est = TreeEstimator(max_features=3) + est.fit(iris.data, iris.target) + assert_equal(est.max_features_, 3) - assert np.min(leaf_count) >= 5 + est = TreeEstimator(max_features=0.01) + est.fit(iris.data, iris.target) + assert_equal(est.max_features_, 1) + est = TreeEstimator(max_features=0.5) + est.fit(iris.data, iris.target) + assert_equal(est.max_features_, + int(0.5 * iris.data.shape[1])) -def test_pickle(): - import pickle + est = TreeEstimator(max_features=1.0) + est.fit(iris.data, iris.target) + assert_equal(est.max_features_, iris.data.shape[1]) + + est = TreeEstimator(max_features=None) + est.fit(iris.data, iris.target) + assert_equal(est.max_features_, iris.data.shape[1]) - # classification - obj = tree.DecisionTreeClassifier() - obj.fit(iris.data, iris.target) - score = obj.score(iris.data, iris.target) - s = pickle.dumps(obj) + # use values of max_features that are invalid + est = TreeEstimator(max_features=10) + assert_raises(ValueError, est.fit, X, y) - obj2 = pickle.loads(s) - assert_equal(type(obj2), obj.__class__) - score2 = obj2.score(iris.data, iris.target) - assert score == score2, "Failed to generate same score " + \ - " after pickling (classification) " + est = TreeEstimator(max_features=-1) + assert_raises(ValueError, est.fit, X, y) - # regression - obj = tree.DecisionTreeRegressor() - obj.fit(boston.data, boston.target) - score = obj.score(boston.data, boston.target) - s = pickle.dumps(obj) + est = TreeEstimator(max_features=0.0) + assert_raises(ValueError, est.fit, X, y) - obj2 = pickle.loads(s) - assert_equal(type(obj2), obj.__class__) - score2 = obj2.score(boston.data, boston.target) - assert score == score2, "Failed to generate same score " + \ - " after pickling (regression) " + est = TreeEstimator(max_features=1.5) + assert_raises(ValueError, est.fit, X, y) + + est = TreeEstimator(max_features="foobar") + assert_raises(ValueError, est.fit, X, y) + + +def test_error(): + """Test that it gives proper exception on deficient input.""" + for name, TreeEstimator in CLF_TREES.items(): + # predict before fit + est = TreeEstimator() + assert_raises(Exception, est.predict_proba, X) + + est.fit(X, y) + X2 = [-2, -1, 1] # wrong feature shape for sample + assert_raises(ValueError, est.predict_proba, X2) + + for name, TreeEstimator in ALL_TREES.items(): + # Invalid values for parameters + assert_raises(ValueError, TreeEstimator(min_samples_leaf=-1).fit, X, y) + assert_raises(ValueError, + TreeEstimator(min_weight_fraction_leaf=-1).fit, + X, y) + assert_raises(ValueError, + TreeEstimator(min_weight_fraction_leaf=0.51).fit, + X, y) + assert_raises(ValueError, TreeEstimator(min_samples_split=-1).fit, + X, y) + assert_raises(ValueError, TreeEstimator(max_depth=-1).fit, X, y) + assert_raises(ValueError, TreeEstimator(max_features=42).fit, X, y) + + # Wrong dimensions + est = TreeEstimator() + y2 = y[:-1] + assert_raises(ValueError, est.fit, X, y2) + + # Test with arrays that are non-contiguous. + Xf = np.asfortranarray(X) + est = TreeEstimator() + est.fit(Xf, y) + assert_almost_equal(est.predict(T), true_result) + + # predict before fitting + est = TreeEstimator() + assert_raises(Exception, est.predict, T) + + # predict on vector with different dims + est.fit(X, y) + t = np.asarray(T) + assert_raises(ValueError, est.predict, t[:, 1:]) + + # wrong sample shape + Xt = np.array(X).T + + est = TreeEstimator() + est.fit(np.dot(X, Xt), y) + assert_raises(ValueError, est.predict, X) + + clf = TreeEstimator() + clf.fit(X, y) + assert_raises(ValueError, clf.predict, Xt) + + +def test_min_samples_leaf(): + """Test if leaves contain more than leaf_count training examples""" + X = np.asfortranarray(iris.data.astype(tree._tree.DTYPE)) + y = iris.target + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes in (None, 1000): + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(min_samples_leaf=5, + max_leaf_nodes=max_leaf_nodes, + random_state=0) + est.fit(X, y) + out = est.tree_.apply(X) + node_counts = np.bincount(out) + # drop inner nodes + leaf_count = node_counts[node_counts != 0] + assert_greater(np.min(leaf_count), 4, + "Failed with {0}".format(name)) + + +def check_min_weight_fraction_leaf(name, datasets, sparse=False): + """Test if leaves contain at least min_weight_fraction_leaf of the + training set""" + if sparse: + X = DATASETS[datasets]["X_sparse"].astype(np.float32) + else: + X = DATASETS[datasets]["X"].astype(np.float32) + y = DATASETS[datasets]["y"] + + weights = rng.rand(X.shape[0]) + total_weight = np.sum(weights) + + TreeEstimator = ALL_TREES[name] + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 6)): + est = TreeEstimator(min_weight_fraction_leaf=frac, + max_leaf_nodes=max_leaf_nodes, + random_state=0) + est.fit(X, y, sample_weight=weights) + + if sparse: + out = est.tree_.apply(X.tocsr()) + + else: + out = est.tree_.apply(X) + + node_weights = np.bincount(out, weights=weights) + # drop inner nodes + leaf_weights = node_weights[node_weights != 0] + assert_greater_equal( + np.min(leaf_weights), + total_weight * est.min_weight_fraction_leaf, + "Failed with {0} " + "min_weight_fraction_leaf={1}".format( + name, est.min_weight_fraction_leaf)) + + +def test_min_weight_fraction_leaf(): + # Check on dense input + for name in ALL_TREES: + yield check_min_weight_fraction_leaf, name, "iris" + + # Check on sparse input + for name in SPARSE_TREES: + yield check_min_weight_fraction_leaf, name, "multilabel", True + + +def test_pickle(): + """Check that tree estimator are pickable """ + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(random_state=0) + clf.fit(iris.data, iris.target) + score = clf.score(iris.data, iris.target) + + serialized_object = pickle.dumps(clf) + clf2 = pickle.loads(serialized_object) + assert_equal(type(clf2), clf.__class__) + score2 = clf2.score(iris.data, iris.target) + assert_equal(score, score2, "Failed to generate same score " + "after pickling (classification) " + "with {0}".format(name)) + + for name, TreeRegressor in REG_TREES.items(): + reg = TreeRegressor(random_state=0) + reg.fit(boston.data, boston.target) + score = reg.score(boston.data, boston.target) + + serialized_object = pickle.dumps(reg) + reg2 = pickle.loads(serialized_object) + assert_equal(type(reg2), reg.__class__) + score2 = reg2.score(boston.data, boston.target) + assert_equal(score, score2, "Failed to generate same score " + "after pickling (regression) " + "with {0}".format(name)) def test_multioutput(): """Check estimators on multi-output problems.""" - X = [[-2, -1], [-1, -1], [-1, -2], @@ -403,28 +677,594 @@ def test_multioutput(): y_true = [[-1, 0], [1, 1], [-1, 2], [1, 3]] # toy classification problem - clf = tree.DecisionTreeClassifier() - y_hat = clf.fit(X, y).predict(T) - assert_array_equal(y_hat, y_true) - assert_equal(y_hat.shape, (4, 2)) + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(random_state=0) + y_hat = clf.fit(X, y).predict(T) + assert_array_equal(y_hat, y_true) + assert_equal(y_hat.shape, (4, 2)) + + proba = clf.predict_proba(T) + assert_equal(len(proba), 2) + assert_equal(proba[0].shape, (4, 2)) + assert_equal(proba[1].shape, (4, 4)) + + log_proba = clf.predict_log_proba(T) + assert_equal(len(log_proba), 2) + assert_equal(log_proba[0].shape, (4, 2)) + assert_equal(log_proba[1].shape, (4, 4)) - proba = clf.predict_proba(T) - assert_equal(len(proba), 2) - assert_equal(proba[0].shape, (4, 2)) - assert_equal(proba[1].shape, (4, 4)) + # toy regression problem + for name, TreeRegressor in REG_TREES.items(): + reg = TreeRegressor(random_state=0) + y_hat = reg.fit(X, y).predict(T) + assert_almost_equal(y_hat, y_true) + assert_equal(y_hat.shape, (4, 2)) + + +def test_classes_shape(): + """Test that n_classes_ and classes_ have proper shape.""" + for name, TreeClassifier in CLF_TREES.items(): + # Classification, single output + clf = TreeClassifier(random_state=0) + clf.fit(X, y) + + assert_equal(clf.n_classes_, 2) + assert_array_equal(clf.classes_, [-1, 1]) + + # Classification, multi-output + _y = np.vstack((y, np.array(y) * 2)).T + clf = TreeClassifier(random_state=0) + clf.fit(X, _y) + assert_equal(len(clf.n_classes_), 2) + assert_equal(len(clf.classes_), 2) + assert_array_equal(clf.n_classes_, [2, 2]) + assert_array_equal(clf.classes_, [[-1, 1], [-2, 2]]) + + +def test_unbalanced_iris(): + """Check class rebalancing.""" + unbalanced_X = iris.data[:125] + unbalanced_y = iris.target[:125] + sample_weight = _balance_weights(unbalanced_y) + + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(random_state=0) + clf.fit(unbalanced_X, unbalanced_y, sample_weight=sample_weight) + assert_almost_equal(clf.predict(unbalanced_X), unbalanced_y) + + +def test_memory_layout(): + """Check that it works no matter the memory layout""" + for (name, TreeEstimator), dtype in product(ALL_TREES.items(), + [np.float64, np.float32]): + est = TreeEstimator(random_state=0) + + # Nothing + X = np.asarray(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # C-order + X = np.asarray(iris.data, order="C", dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # F-order + X = np.asarray(iris.data, order="F", dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # Contiguous + X = np.ascontiguousarray(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + if est.splitter in SPARSE_SPLITTERS: + # csr matrix + X = csr_matrix(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # csc_matrix + X = csc_matrix(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # Strided + X = np.asarray(iris.data[::3], dtype=dtype) + y = iris.target[::3] + assert_array_equal(est.fit(X, y).predict(X), y) + + +def test_sample_weight(): + """Check sample weighting.""" + # Test that zero-weighted samples are not taken into account + X = np.arange(100)[:, np.newaxis] + y = np.ones(100) + y[:50] = 0.0 + + sample_weight = np.ones(100) + sample_weight[y == 0] = 0.0 + + clf = DecisionTreeClassifier(random_state=0) + clf.fit(X, y, sample_weight=sample_weight) + assert_array_equal(clf.predict(X), np.ones(100)) + + # Test that low weighted samples are not taken into account at low depth + X = np.arange(200)[:, np.newaxis] + y = np.zeros(200) + y[50:100] = 1 + y[100:200] = 2 + X[100:200, 0] = 200 + + sample_weight = np.ones(200) + + sample_weight[y == 2] = .51 # Samples of class '2' are still weightier + clf = DecisionTreeClassifier(max_depth=1, random_state=0) + clf.fit(X, y, sample_weight=sample_weight) + assert_equal(clf.tree_.threshold[0], 149.5) + + sample_weight[y == 2] = .5 # Samples of class '2' are no longer weightier + clf = DecisionTreeClassifier(max_depth=1, random_state=0) + clf.fit(X, y, sample_weight=sample_weight) + assert_equal(clf.tree_.threshold[0], 49.5) # Threshold should have moved + + # Test that sample weighting is the same as having duplicates + X = iris.data + y = iris.target - log_proba = clf.predict_log_proba(T) - assert_equal(len(log_proba), 2) - assert_equal(log_proba[0].shape, (4, 2)) - assert_equal(log_proba[1].shape, (4, 4)) + duplicates = rng.randint(0, X.shape[0], 200) - # toy regression problem - clf = tree.DecisionTreeRegressor() - y_hat = clf.fit(X, y).predict(T) - assert_almost_equal(y_hat, y_true) - assert_equal(y_hat.shape, (4, 2)) + clf = DecisionTreeClassifier(random_state=1) + clf.fit(X[duplicates], y[duplicates]) + + sample_weight = np.bincount(duplicates, minlength=X.shape[0]) + clf2 = DecisionTreeClassifier(random_state=1) + clf2.fit(X, y, sample_weight=sample_weight) + + internal = clf.tree_.children_left != tree._tree.TREE_LEAF + assert_array_almost_equal(clf.tree_.threshold[internal], + clf2.tree_.threshold[internal]) + + +def test_sample_weight_invalid(): + """Check sample weighting raises errors.""" + X = np.arange(100)[:, np.newaxis] + y = np.ones(100) + y[:50] = 0.0 + + clf = DecisionTreeClassifier(random_state=0) + + sample_weight = np.random.rand(100, 1) + assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) + + sample_weight = np.array(0) + assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) + + sample_weight = np.ones(101) + assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) + + sample_weight = np.ones(99) + assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) + + +def check_class_weights(name): + """Check class_weights resemble sample_weights behavior.""" + TreeClassifier = CLF_TREES[name] + + # Iris is balanced, so no effect expected for using 'auto' weights + clf1 = TreeClassifier(random_state=0) + clf1.fit(iris.data, iris.target) + clf2 = TreeClassifier(class_weight='auto', random_state=0) + clf2.fit(iris.data, iris.target) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + # Make a multi-output problem with three copies of Iris + iris_multi = np.vstack((iris.target, iris.target, iris.target)).T + # Create user-defined weights that should balance over the outputs + clf3 = TreeClassifier(class_weight=[{0: 2., 1: 2., 2: 1.}, + {0: 2., 1: 1., 2: 2.}, + {0: 1., 1: 2., 2: 2.}], + random_state=0) + clf3.fit(iris.data, iris_multi) + assert_almost_equal(clf2.feature_importances_, clf3.feature_importances_) + # Check against multi-output "auto" which should also have no effect + clf4 = TreeClassifier(class_weight='auto', random_state=0) + clf4.fit(iris.data, iris_multi) + assert_almost_equal(clf3.feature_importances_, clf4.feature_importances_) + + # Inflate importance of class 1, check against user-defined weights + sample_weight = np.ones(iris.target.shape) + sample_weight[iris.target == 1] *= 100 + class_weight = {0: 1., 1: 100., 2: 1.} + clf1 = TreeClassifier(random_state=0) + clf1.fit(iris.data, iris.target, sample_weight) + clf2 = TreeClassifier(class_weight=class_weight, random_state=0) + clf2.fit(iris.data, iris.target) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + # Check that sample_weight and class_weight are multiplicative + clf1 = TreeClassifier(random_state=0) + clf1.fit(iris.data, iris.target, sample_weight**2) + clf2 = TreeClassifier(class_weight=class_weight, random_state=0) + clf2.fit(iris.data, iris.target, sample_weight) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + +def test_class_weights(): + for name in CLF_TREES: + yield check_class_weights, name + + +def check_class_weight_errors(name): + """Test if class_weight raises errors and warnings when expected.""" + TreeClassifier = CLF_TREES[name] + _y = np.vstack((y, np.array(y) * 2)).T + + # Invalid preset string + clf = TreeClassifier(class_weight='the larch', random_state=0) + assert_raises(ValueError, clf.fit, X, y) + assert_raises(ValueError, clf.fit, X, _y) + + # Not a list or preset for multi-output + clf = TreeClassifier(class_weight=1, random_state=0) + assert_raises(ValueError, clf.fit, X, _y) + + # Incorrect length list for multi-output + clf = TreeClassifier(class_weight=[{-1: 0.5, 1: 1.}], random_state=0) + assert_raises(ValueError, clf.fit, X, _y) + + +def test_class_weight_errors(): + for name in CLF_TREES: + yield check_class_weight_errors, name + + +def test_max_leaf_nodes(): + """Test greedy trees with max_depth + 1 leafs. """ + from sklearn.tree._tree import TREE_LEAF + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + k = 4 + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(max_depth=None, max_leaf_nodes=k + 1).fit(X, y) + tree = est.tree_ + assert_equal((tree.children_left == TREE_LEAF).sum(), k + 1) + + # max_leaf_nodes in (0, 1) should raise ValueError + est = TreeEstimator(max_depth=None, max_leaf_nodes=0) + assert_raises(ValueError, est.fit, X, y) + est = TreeEstimator(max_depth=None, max_leaf_nodes=1) + assert_raises(ValueError, est.fit, X, y) + est = TreeEstimator(max_depth=None, max_leaf_nodes=0.1) + assert_raises(ValueError, est.fit, X, y) + + +def test_max_leaf_nodes_max_depth(): + """Test preceedence of max_leaf_nodes over max_depth. """ + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + k = 4 + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(max_depth=1, max_leaf_nodes=k).fit(X, y) + tree = est.tree_ + assert_greater(tree.max_depth, 1) + + +def test_arrays_persist(): + """Ensure property arrays' memory stays alive when tree disappears + + non-regression for #2726 + """ + for attr in ['n_classes', 'value', 'children_left', 'children_right', + 'threshold', 'impurity', 'feature', 'n_node_samples']: + value = getattr(DecisionTreeClassifier().fit([[0]], [0]).tree_, attr) + # if pointing to freed memory, contents may be arbitrary + assert_true(-2 <= value.flat[0] < 2, + 'Array points to arbitrary memory') + + +def test_only_constant_features(): + random_state = check_random_state(0) + X = np.zeros((10, 20)) + y = random_state.randint(0, 2, (10, )) + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(random_state=0) + est.fit(X, y) + assert_equal(est.tree_.max_depth, 0) + + +def test_with_only_one_non_constant_features(): + X = np.hstack([np.array([[1.], [1.], [0.], [0.]]), + np.zeros((4, 1000))]) + + y = np.array([0., 1., 0., 1.0]) + for name, TreeEstimator in CLF_TREES.items(): + est = TreeEstimator(random_state=0, max_features=1) + est.fit(X, y) + assert_equal(est.tree_.max_depth, 1) + assert_array_equal(est.predict_proba(X), 0.5 * np.ones((4, 2))) + + for name, TreeEstimator in REG_TREES.items(): + est = TreeEstimator(random_state=0, max_features=1) + est.fit(X, y) + assert_equal(est.tree_.max_depth, 1) + assert_array_equal(est.predict(X), 0.5 * np.ones((4, ))) + + +def test_big_input(): + """Test if the warning for too large inputs is appropriate.""" + X = np.repeat(10 ** 40., 4).astype(np.float64).reshape(-1, 1) + clf = DecisionTreeClassifier() + try: + clf.fit(X, [0, 1, 0, 1]) + except ValueError as e: + assert_in("float32", str(e)) + + +def test_realloc(): + from sklearn.tree._tree import _realloc_test + assert_raises(MemoryError, _realloc_test) + + +def test_huge_allocations(): + n_bits = int(platform.architecture()[0].rstrip('bit')) + + X = np.random.randn(10, 2) + y = np.random.randint(0, 2, 10) + + # Sanity check: we cannot request more memory than the size of the address + # space. Currently raises OverflowError. + huge = 2 ** (n_bits + 1) + clf = DecisionTreeClassifier(splitter='best', max_leaf_nodes=huge) + assert_raises(Exception, clf.fit, X, y) + + # Non-regression test: MemoryError used to be dropped by Cython + # because of missing "except *". + huge = 2 ** (n_bits - 1) - 1 + clf = DecisionTreeClassifier(splitter='best', max_leaf_nodes=huge) + assert_raises(MemoryError, clf.fit, X, y) + + +def check_sparse_input(tree, dataset, max_depth=None): + TreeEstimator = ALL_TREES[tree] + X = DATASETS[dataset]["X"] + X_sparse = DATASETS[dataset]["X_sparse"] + y = DATASETS[dataset]["y"] + + # Gain testing time + if dataset in ["digits", "boston"]: + n_samples = X.shape[0] // 5 + X = X[:n_samples] + X_sparse = X_sparse[:n_samples] + y = y[:n_samples] + + for sparse_format in (csr_matrix, csc_matrix, coo_matrix): + X_sparse = sparse_format(X_sparse) + + # Check the default (depth first search) + d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) + s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) + + assert_tree_equal(d.tree_, s.tree_, + "{0} with dense and sparse format gave different " + "trees".format(tree)) + + y_pred = d.predict(X) + if tree in CLF_TREES: + y_proba = d.predict_proba(X) + y_log_proba = d.predict_log_proba(X) + + for sparse_matrix in (csr_matrix, csc_matrix, coo_matrix): + X_sparse_test = sparse_matrix(X_sparse, dtype=np.float32) + + assert_array_almost_equal(s.predict(X_sparse_test), y_pred) + + if tree in CLF_TREES: + assert_array_almost_equal(s.predict_proba(X_sparse_test), + y_proba) + assert_array_almost_equal(s.predict_log_proba(X_sparse_test), + y_log_proba) + + +def test_sparse_input(): + for tree, dataset in product(SPARSE_TREES, + ("clf_small", "toy", "digits", "multilabel", + "sparse-pos", "sparse-neg", "sparse-mix", + "zeros")): + max_depth = 3 if dataset == "digits" else None + yield (check_sparse_input, tree, dataset, max_depth) + + # Due to numerical instability of MSE and too strict test, we limit the + # maximal depth + for tree, dataset in product(REG_TREES, ["boston", "reg_small"]): + if tree in SPARSE_TREES: + yield (check_sparse_input, tree, dataset, 2) + + +def check_sparse_parameters(tree, dataset): + TreeEstimator = ALL_TREES[tree] + X = DATASETS[dataset]["X"] + X_sparse = DATASETS[dataset]["X_sparse"] + y = DATASETS[dataset]["y"] + + # Check max_features + d = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X, y) + s = TreeEstimator(random_state=0, max_features=1, + max_depth=2).fit(X_sparse, y) + assert_tree_equal(d.tree_, s.tree_, + "{0} with dense and sparse format gave different " + "trees".format(tree)) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + # Check min_samples_split + d = TreeEstimator(random_state=0, max_features=1, + min_samples_split=10).fit(X, y) + s = TreeEstimator(random_state=0, max_features=1, + min_samples_split=10).fit(X_sparse, y) + assert_tree_equal(d.tree_, s.tree_, + "{0} with dense and sparse format gave different " + "trees".format(tree)) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + # Check min_samples_leaf + d = TreeEstimator(random_state=0, + min_samples_leaf=X_sparse.shape[0] // 2).fit(X, y) + s = TreeEstimator(random_state=0, + min_samples_leaf=X_sparse.shape[0] // 2).fit(X_sparse, y) + assert_tree_equal(d.tree_, s.tree_, + "{0} with dense and sparse format gave different " + "trees".format(tree)) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + # Check best-first search + d = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X, y) + s = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X_sparse, y) + assert_tree_equal(d.tree_, s.tree_, + "{0} with dense and sparse format gave different " + "trees".format(tree)) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + +def test_sparse_parameters(): + for tree, dataset in product(SPARSE_TREES, + ["sparse-pos", "sparse-neg", "sparse-mix", + "zeros"]): + yield (check_sparse_parameters, tree, dataset) + + +def check_sparse_criterion(tree, dataset): + TreeEstimator = ALL_TREES[tree] + X = DATASETS[dataset]["X"] + X_sparse = DATASETS[dataset]["X_sparse"] + y = DATASETS[dataset]["y"] + + # Check various criterion + CRITERIONS = REG_CRITERIONS if tree in REG_TREES else CLF_CRITERIONS + for criterion in CRITERIONS: + d = TreeEstimator(random_state=0, max_depth=3, + criterion=criterion).fit(X, y) + s = TreeEstimator(random_state=0, max_depth=3, + criterion=criterion).fit(X_sparse, y) + + assert_tree_equal(d.tree_, s.tree_, + "{0} with dense and sparse format gave different " + "trees".format(tree)) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + +def test_sparse_criterion(): + for tree, dataset in product(SPARSE_TREES, + ["sparse-pos", "sparse-neg", "sparse-mix", + "zeros"]): + yield (check_sparse_criterion, tree, dataset) + + +def check_explicit_sparse_zeros(tree, max_depth=3, + n_features=10): + TreeEstimator = ALL_TREES[tree] + + # n_samples set n_feature to ease construction of a simultaneous + # construction of a csr and csc matrix + n_samples = n_features + samples = np.arange(n_samples) + + # Generate X, y + random_state = check_random_state(0) + indices = [] + data = [] + offset = 0 + indptr = [offset] + for i in range(n_features): + n_nonzero_i = random_state.binomial(n_samples, 0.5) + indices_i = random_state.permutation(samples)[:n_nonzero_i] + indices.append(indices_i) + data_i = random_state.binomial(3, 0.5, size=(n_nonzero_i, )) - 1 + data.append(data_i) + offset += n_nonzero_i + indptr.append(offset) + + indices = np.concatenate(indices) + data = np.array(np.concatenate(data), dtype=np.float32) + X_sparse = csc_matrix((data, indices, indptr), + shape=(n_samples, n_features)) + X = X_sparse.toarray() + X_sparse_test = csr_matrix((data, indices, indptr), + shape=(n_samples, n_features)) + X_test = X_sparse_test.toarray() + y = random_state.randint(0, 3, size=(n_samples, )) + + # Ensure that X_sparse_test owns its data, indices and indptr array + X_sparse_test = X_sparse_test.copy() + + # Ensure that we have explicit zeros + assert_greater((X_sparse.data == 0.).sum(), 0) + assert_greater((X_sparse_test.data == 0.).sum(), 0) + + # Perform the comparison + d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) + s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) + + assert_tree_equal(d.tree_, s.tree_, + "{0} with dense and sparse format gave different " + "trees".format(tree)) + + Xs = (X_test, X_sparse_test) + for X1, X2 in product(Xs, Xs): + assert_array_almost_equal(s.tree_.apply(X1), d.tree_.apply(X2)) + assert_array_almost_equal(s.predict(X1), d.predict(X2)) + + if tree in CLF_TREES: + assert_array_almost_equal(s.predict_proba(X1), + d.predict_proba(X2)) + + +def test_explicit_sparse_zeros(): + for tree in SPARSE_TREES: + yield (check_explicit_sparse_zeros, tree) + + +def check_raise_error_on_1d_input(name): + TreeEstimator = ALL_TREES[name] + + X = iris.data[:, 0].ravel() + X_2d = iris.data[:, 0].reshape((-1, 1)) + y = iris.target + + assert_raises(ValueError, TreeEstimator(random_state=0).fit, X, y) + + est = TreeEstimator(random_state=0) + est.fit(X_2d, y) + assert_raises(ValueError, est.predict, X) + + +def test_1d_input(): + for name in ALL_TREES: + yield check_raise_error_on_1d_input, name + + +def _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight): + # Private function to keep pretty printing in nose yielded tests + est = TreeEstimator(random_state=0) + est.fit(X, y, sample_weight=sample_weight) + assert_equal(est.tree_.max_depth, 1) + + est = TreeEstimator(random_state=0, min_weight_fraction_leaf=0.4) + est.fit(X, y, sample_weight=sample_weight) + assert_equal(est.tree_.max_depth, 0) + + +def check_min_weight_leaf_split_level(name): + TreeEstimator = ALL_TREES[name] + + X = np.array([[0], [0], [0], [0], [1]]) + y = [0, 0, 0, 0, 1] + sample_weight = [0.2, 0.2, 0.2, 0.2, 0.2] + _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight) + + if TreeEstimator().splitter in SPARSE_SPLITTERS: + _check_min_weight_leaf_split_level(TreeEstimator, csc_matrix(X), y, + sample_weight) -if __name__ == "__main__": - import nose - nose.runmodule() +def test_min_weight_leaf_split_level(): + for name in ALL_TREES: + yield check_min_weight_leaf_split_level, name diff --git a/sklearn/tree/tree.py b/sklearn/tree/tree.py index 3c3c6a25d469f..8d4a900d31324 100644 --- a/sklearn/tree/tree.py +++ b/sklearn/tree/tree.py @@ -3,243 +3,194 @@ randomized trees. Single and multi-output problems are both handled. """ -# Code is originally adapted from MILK: Machine Learning Toolkit -# Copyright (C) 2008-2011, Luis Pedro Coelho -# License: MIT. See COPYING.MIT file in the milk distribution - -# Authors: Brian Holt, Peter Prettenhofer, Satrajit Ghosh, Gilles Louppe -# License: BSD3 +# Authors: Gilles Louppe +# Peter Prettenhofer +# Brian Holt +# Noel Dawe +# Satrajit Gosh +# Joly Arnaud +# Fares Hedayati +# +# Licence: BSD 3 clause from __future__ import division -import numpy as np + + +import numbers from abc import ABCMeta, abstractmethod +import numpy as np +from scipy.sparse import issparse + from ..base import BaseEstimator, ClassifierMixin, RegressorMixin -from ..feature_selection.selector_mixin import SelectorMixin -from ..utils import array2d, check_random_state +from ..externals import six +from ..feature_selection.from_model import _LearntSelectorMixin +from ..utils import check_array, check_random_state, compute_sample_weight +from ..utils.validation import NotFittedError, check_is_fitted -from . import _tree +from ._tree import Criterion +from ._tree import Splitter +from ._tree import DepthFirstTreeBuilder, BestFirstTreeBuilder +from ._tree import Tree +from . import _tree __all__ = ["DecisionTreeClassifier", "DecisionTreeRegressor", "ExtraTreeClassifier", "ExtraTreeRegressor"] -DTYPE = _tree.DTYPE -DOUBLE = _tree.DOUBLE - -CLASSIFICATION = { - "gini": _tree.Gini, - "entropy": _tree.Entropy, -} - -REGRESSION = { - "mse": _tree.MSE, -} +# ============================================================================= +# Types and constants +# ============================================================================= -def export_graphviz(decision_tree, out_file=None, feature_names=None): - """Export a decision tree in DOT format. - - This function generates a GraphViz representation of the decision tree, - which is then written into `out_file`. Once exported, graphical renderings - can be generated using, for example:: - - $ dot -Tps tree.dot -o tree.ps (PostScript format) - $ dot -Tpng tree.dot -o tree.png (PNG format) - - Parameters - ---------- - decision_tree : decision tree classifier - The decision tree to be exported to graphviz. - - out : file object or string, optional (default=None) - Handle or name of the output file. - - feature_names : list of strings, optional (default=None) - Names of each of the features. - - Returns - ------- - out_file : file object - The file object to which the tree was exported. The user is - expected to `close()` this object when done with it. - - Examples - -------- - >>> from sklearn.datasets import load_iris - >>> from sklearn import tree - - >>> clf = tree.DecisionTreeClassifier() - >>> iris = load_iris() - - >>> clf = clf.fit(iris.data, iris.target) - >>> import tempfile - >>> out_file = tree.export_graphviz(clf, out_file=tempfile.TemporaryFile()) - >>> out_file.close() - """ - def node_to_str(tree, node_id): - value = tree.value[node_id] - if tree.n_outputs == 1: - value = value[0, :] - - if tree.children_left[node_id] == _tree.TREE_LEAF: - return "error = %.4f\\nsamples = %s\\nvalue = %s" \ - % (tree.init_error[node_id], - tree.n_samples[node_id], - value) - else: - if feature_names is not None: - feature = feature_names[tree.feature[node_id]] - else: - feature = "X[%s]" % tree.feature[node_id] - - return "%s <= %.4f\\nerror = %s\\nsamples = %s\\nvalue = %s" \ - % (feature, - tree.threshold[node_id], - tree.init_error[node_id], - tree.n_samples[node_id], - value) - - def recurse(tree, node_id, parent=None): - if node_id == _tree.TREE_LEAF: - raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF) - - left_child = tree.children_left[node_id] - right_child = tree.children_right[node_id] - - # Add node with description - out_file.write('%d [label="%s", shape="box"] ;\n' % - (node_id, node_to_str(tree, node_id))) - - if parent is not None: - # Add edge to parent - out_file.write('%d -> %d ;\n' % (parent, node_id)) +DTYPE = _tree.DTYPE +DOUBLE = _tree.DOUBLE - if left_child != _tree.TREE_LEAF: # and right_child != _tree.TREE_LEAF - recurse(tree, left_child, node_id) - recurse(tree, right_child, node_id) +CRITERIA_CLF = {"gini": _tree.Gini, "entropy": _tree.Entropy} +CRITERIA_REG = {"mse": _tree.MSE, "friedman_mse": _tree.FriedmanMSE} - if out_file is None: - out_file = open("tree.dot", "w") - elif isinstance(out_file, basestring): - out_file = open(out_file, "w") +DENSE_SPLITTERS = {"best": _tree.BestSplitter, + "presort-best": _tree.PresortBestSplitter, + "random": _tree.RandomSplitter} - out_file.write("digraph Tree {\n") - if isinstance(decision_tree, _tree.Tree): - recurse(decision_tree, 0) - else: - recurse(decision_tree.tree_, 0) - out_file.write("}") +SPARSE_SPLITTERS = {"best": _tree.BestSparseSplitter, + "random": _tree.RandomSparseSplitter} - return out_file +# ============================================================================= +# Base decision tree +# ============================================================================= -class BaseDecisionTree(BaseEstimator, SelectorMixin): +class BaseDecisionTree(six.with_metaclass(ABCMeta, BaseEstimator, + _LearntSelectorMixin)): """Base class for decision trees. Warning: This class should not be used directly. Use derived classes instead. """ - __metaclass__ = ABCMeta @abstractmethod - def __init__(self, criterion, - max_depth, - min_samples_split, - min_samples_leaf, - min_density, - max_features, - compute_importances, - random_state): + def __init__(self, + criterion, + splitter, + max_depth, + min_samples_split, + min_samples_leaf, + min_weight_fraction_leaf, + max_features, + max_leaf_nodes, + random_state, + class_weight=None): self.criterion = criterion + self.splitter = splitter self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf - self.min_density = min_density + self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features - self.compute_importances = compute_importances self.random_state = random_state + self.max_leaf_nodes = max_leaf_nodes + self.class_weight = class_weight self.n_features_ = None self.n_outputs_ = None self.classes_ = None self.n_classes_ = None - self.find_split_ = _tree.TREE_SPLIT_BEST self.tree_ = None - self.feature_importances_ = None + self.max_features_ = None - def fit(self, X, y, sample_mask=None, X_argsorted=None): + def fit(self, X, y, sample_weight=None, check_input=True): """Build a decision tree from the training set (X, y). Parameters ---------- - X : array-like of shape = [n_samples, n_features] - The training input samples. Use ``dtype=np.float32`` - and ``order='F'`` for maximum efficiency. + X : array-like or sparse matrix, shape = [n_samples, n_features] + The training input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csc_matrix``. y : array-like, shape = [n_samples] or [n_samples, n_outputs] - The target values (integers that correspond to classes in - classification, real numbers in regression). - Use ``dtype=np.float64`` and ``order='C'`` for maximum - efficiency. + The target values (class labels in classification, real numbers in + regression). In the regression case, use ``dtype=np.float64`` and + ``order='C'`` for maximum efficiency. + + sample_weight : array-like, shape = [n_samples] or None + Sample weights. If None, then samples are equally weighted. Splits + that would create child nodes with net zero or negative weight are + ignored while searching for a split in each node. In the case of + classification, splits are also ignored if they would result in any + single class carrying a negative weight in either child node. + + check_input : boolean, (default=True) + Allow to bypass several input checking. + Don't use this parameter unless you know what you do. Returns ------- self : object Returns self. """ - self.random_state = check_random_state(self.random_state) + random_state = check_random_state(self.random_state) + if check_input: + X = check_array(X, dtype=DTYPE, accept_sparse="csc") + if issparse(X): + X.sort_indices() - # set min_samples_split sensibly - self.min_samples_split = max(self.min_samples_split, - 2 * self.min_samples_leaf) - - # Convert data - if getattr(X, "dtype", None) != DTYPE or \ - X.ndim != 2 or not X.flags.fortran: - X = array2d(X, dtype=DTYPE, order="F") + if X.indices.dtype != np.intc or X.indptr.dtype != np.intc: + raise ValueError("No support for np.int64 index based " + "sparse matrices") + # Determine output settings n_samples, self.n_features_ = X.shape - is_classification = isinstance(self, ClassifierMixin) y = np.atleast_1d(y) + expanded_class_weight = None + if y.ndim == 1: - y = y[:, np.newaxis] + # reshape is necessary to preserve the data contiguity against vs + # [:, np.newaxis] that does not. + y = np.reshape(y, (-1, 1)) - self.classes_ = [] - self.n_classes_ = [] self.n_outputs_ = y.shape[1] if is_classification: y = np.copy(y) - for k in xrange(self.n_outputs_): - unique = np.unique(y[:, k]) - self.classes_.append(unique) - self.n_classes_.append(unique.shape[0]) - y[:, k] = np.searchsorted(unique, y[:, k]) + self.classes_ = [] + self.n_classes_ = [] + + if self.class_weight is not None: + y_original = np.copy(y) + + for k in range(self.n_outputs_): + classes_k, y[:, k] = np.unique(y[:, k], return_inverse=True) + self.classes_.append(classes_k) + self.n_classes_.append(classes_k.shape[0]) + + if self.class_weight is not None: + expanded_class_weight = compute_sample_weight( + self.class_weight, y_original) else: self.classes_ = [None] * self.n_outputs_ self.n_classes_ = [1] * self.n_outputs_ + self.n_classes_ = np.array(self.n_classes_, dtype=np.intp) + if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous: y = np.ascontiguousarray(y, dtype=DOUBLE) - if is_classification: - criterion = CLASSIFICATION[self.criterion](self.n_outputs_, - self.n_classes_) - else: - criterion = REGRESSION[self.criterion](self.n_outputs_) - # Check parameters - max_depth = np.inf if self.max_depth is None else self.max_depth + max_depth = ((2 ** 31) - 1 if self.max_depth is None + else self.max_depth) + max_leaf_nodes = (-1 if self.max_leaf_nodes is None + else self.max_leaf_nodes) - if isinstance(self.max_features, basestring): + if isinstance(self.max_features, six.string_types): if self.max_features == "auto": if is_classification: max_features = max(1, int(np.sqrt(self.n_features_))) @@ -255,8 +206,15 @@ def fit(self, X, y, sample_mask=None, X_argsorted=None): 'values are "auto", "sqrt" or "log2".') elif self.max_features is None: max_features = self.n_features_ - else: + elif isinstance(self.max_features, (numbers.Integral, np.integer)): max_features = self.max_features + else: # float + if self.max_features > 0.0: + max_features = max(1, int(self.max_features * self.n_features_)) + else: + max_features = 0 + + self.max_features_ = max_features if len(y) != n_samples: raise ValueError("Number of labels=%d does not match " @@ -265,39 +223,94 @@ def fit(self, X, y, sample_mask=None, X_argsorted=None): raise ValueError("min_samples_split must be greater than zero.") if self.min_samples_leaf <= 0: raise ValueError("min_samples_leaf must be greater than zero.") + if not 0 <= self.min_weight_fraction_leaf <= 0.5: + raise ValueError("min_weight_fraction_leaf must in [0, 0.5]") if max_depth <= 0: raise ValueError("max_depth must be greater than zero. ") - if self.min_density < 0.0 or self.min_density > 1.0: - raise ValueError("min_density must be in [0, 1]") if not (0 < max_features <= self.n_features_): raise ValueError("max_features must be in (0, n_features]") - if sample_mask is not None and len(sample_mask) != n_samples: - raise ValueError("Length of sample_mask=%d does not match " - "number of samples=%d" % (len(sample_mask), - n_samples)) - if X_argsorted is not None and len(X_argsorted) != n_samples: - raise ValueError("Length of X_argsorted=%d does not match " - "number of samples=%d" % (len(X_argsorted), - n_samples)) + if not isinstance(max_leaf_nodes, (numbers.Integral, np.integer)): + raise ValueError("max_leaf_nodes must be integral number but was " + "%r" % max_leaf_nodes) + if -1 < max_leaf_nodes < 2: + raise ValueError(("max_leaf_nodes {0} must be either smaller than " + "0 or larger than 1").format(max_leaf_nodes)) + + if sample_weight is not None: + if (getattr(sample_weight, "dtype", None) != DOUBLE or + not sample_weight.flags.contiguous): + sample_weight = np.ascontiguousarray( + sample_weight, dtype=DOUBLE) + if len(sample_weight.shape) > 1: + raise ValueError("Sample weights array has more " + "than one dimension: %d" % + len(sample_weight.shape)) + if len(sample_weight) != n_samples: + raise ValueError("Number of weights=%d does not match " + "number of samples=%d" % + (len(sample_weight), n_samples)) + + if expanded_class_weight is not None: + if sample_weight is not None: + sample_weight = sample_weight * expanded_class_weight + else: + sample_weight = expanded_class_weight + + # Set min_weight_leaf from min_weight_fraction_leaf + if self.min_weight_fraction_leaf != 0. and sample_weight is not None: + min_weight_leaf = (self.min_weight_fraction_leaf * + np.sum(sample_weight)) + else: + min_weight_leaf = 0. + + # Set min_samples_split sensibly + min_samples_split = max(self.min_samples_split, + 2 * self.min_samples_leaf) # Build tree - self.tree_ = _tree.Tree(self.n_features_, self.n_classes_, - self.n_outputs_, criterion, max_depth, - self.min_samples_split, self.min_samples_leaf, - self.min_density, max_features, - self.find_split_, self.random_state) + criterion = self.criterion + if not isinstance(criterion, Criterion): + if is_classification: + criterion = CRITERIA_CLF[self.criterion](self.n_outputs_, + self.n_classes_) + else: + criterion = CRITERIA_REG[self.criterion](self.n_outputs_) + + SPLITTERS = SPARSE_SPLITTERS if issparse(X) else DENSE_SPLITTERS + + splitter = self.splitter + if not isinstance(self.splitter, Splitter): + splitter = SPLITTERS[self.splitter](criterion, + self.max_features_, + self.min_samples_leaf, + min_weight_leaf, + random_state) + + self.tree_ = Tree(self.n_features_, self.n_classes_, self.n_outputs_) + + # Use BestFirst if max_leaf_nodes given; use DepthFirst otherwise + if max_leaf_nodes < 0: + builder = DepthFirstTreeBuilder(splitter, min_samples_split, + self.min_samples_leaf, + min_weight_leaf, + max_depth) + else: + builder = BestFirstTreeBuilder(splitter, min_samples_split, + self.min_samples_leaf, + min_weight_leaf, + max_depth, + max_leaf_nodes) - self.tree_.build(X, y, sample_mask=sample_mask, - X_argsorted=X_argsorted) + builder.build(self.tree_, X, y, sample_weight) - if self.compute_importances: - self.feature_importances_ = \ - self.tree_.compute_feature_importances() + if self.n_outputs_ == 1: + self.n_classes_ = self.n_classes_[0] + self.classes_ = self.classes_[0] return self def predict(self, X): - """Predict class or regression target for X. + """Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is @@ -305,21 +318,26 @@ def predict(self, X): Parameters ---------- - X : array-like of shape = [n_samples, n_features] - The input samples. + X : array-like or sparse matrix of shape = [n_samples, n_features] + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. Returns ------- y : array of shape = [n_samples] or [n_samples, n_outputs] The predicted classes, or the predict values. """ - if getattr(X, "dtype", None) != DTYPE or X.ndim != 2: - X = array2d(X, dtype=DTYPE, order="F") + X = check_array(X, dtype=DTYPE, accept_sparse="csr") + if issparse(X) and (X.indices.dtype != np.intc or + X.indptr.dtype != np.intc): + raise ValueError("No support for np.int64 index based " + "sparse matrices") n_samples, n_features = X.shape if self.tree_ is None: - raise Exception("Tree not initialized. Perform a fit first") + raise NotFittedError("Tree not initialized. Perform a fit first") if self.n_features_ != n_features: raise ValueError("Number of features of the model must " @@ -327,23 +345,53 @@ def predict(self, X): " input n_features is %s " % (self.n_features_, n_features)) - P = self.tree_.predict(X) + proba = self.tree_.predict(X) + # Classification if isinstance(self, ClassifierMixin): - predictions = np.zeros((n_samples, self.n_outputs_)) + if self.n_outputs_ == 1: + return self.classes_.take(np.argmax(proba, axis=1), axis=0) - for k in xrange(self.n_outputs_): - predictions[:, k] = self.classes_[k].take(np.argmax(P[:, k], - axis=1), - axis=0) + else: + predictions = np.zeros((n_samples, self.n_outputs_)) + + for k in range(self.n_outputs_): + predictions[:, k] = self.classes_[k].take( + np.argmax(proba[:, k], axis=1), + axis=0) + + return predictions + + # Regression else: - predictions = P[:, :, 0] + if self.n_outputs_ == 1: + return proba[:, 0] - if self.n_outputs_ == 1: - predictions = predictions.reshape((n_samples, )) + else: + return proba[:, :, 0] + + @property + def feature_importances_(self): + """Return the feature importances. + + The importance of a feature is computed as the (normalized) total + reduction of the criterion brought by that feature. + It is also known as the Gini importance. + + Returns + ------- + feature_importances_ : array, shape = [n_features] + """ + if self.tree_ is None: + raise NotFittedError("Estimator not fitted, call `fit` before" + " `feature_importances_`.") + + return self.tree_.compute_feature_importances() - return predictions +# ============================================================================= +# Public estimators +# ============================================================================= class DecisionTreeClassifier(BaseDecisionTree, ClassifierMixin): """A decision tree classifier. @@ -354,38 +402,62 @@ class DecisionTreeClassifier(BaseDecisionTree, ClassifierMixin): The function to measure the quality of a split. Supported criteria are "gini" for the Gini impurity and "entropy" for the information gain. - max_depth : integer or None, optional (default=None) + splitter : string, optional (default="best") + The strategy used to choose the split at each node. Supported + strategies are "best" to choose the best split and "random" to choose + the best random split. + + max_features : int, float, string or None, optional (default=None) + The number of features to consider when looking for the best split: + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a percentage and + `int(max_features * n_features)` features are considered at each + split. + - If "auto", then `max_features=sqrt(n_features)`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + + max_depth : int or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. + Ignored if ``max_leaf_nodes`` is not None. - min_samples_split : integer, optional (default=1) + min_samples_split : int, optional (default=2) The minimum number of samples required to split an internal node. - min_samples_leaf : integer, optional (default=1) + min_samples_leaf : int, optional (default=1) The minimum number of samples required to be at a leaf node. - min_density : float, optional (default=0.1) - This parameter controls a trade-off in an optimization heuristic. It - controls the minimum density of the `sample_mask` (i.e. the - fraction of samples in the mask). If the density falls below this - threshold the mask is recomputed and the input data is packed - which results in data copying. If `min_density` equals to one, - the partitions are always represented as copies of the original - data. Otherwise, partitions are represented as bit masks (aka - sample masks). - - max_features : int, string or None, optional (default=None) - The number of features to consider when looking for the best split. - If "auto", then `max_features=sqrt(n_features)` on classification - tasks and `max_features=n_features` on regression problems. If "sqrt", - then `max_features=sqrt(n_features)`. If "log2", then - `max_features=log2(n_features)`. If None, then - `max_features=n_features`. - - compute_importances : boolean, optional (default=False) - Whether feature importances are computed and stored into the - ``feature_importances_`` attribute when calling fit. + min_weight_fraction_leaf : float, optional (default=0.) + The minimum weighted fraction of the input samples required to be at a + leaf node. + + max_leaf_nodes : int or None, optional (default=None) + Grow a tree with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + If not None then ``max_depth`` will be ignored. + + class_weight : dict, list of dicts, "auto" or None, optional + (default=None) + Weights associated with classes in the form ``{class_label: weight}``. + If not given, all classes are supposed to have weight one. For + multi-output problems, a list of dicts can be provided in the same + order as the columns of y. + + The "auto" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data. + + For multi-output, the weights of each column of y will be multiplied. + + Note that these weights will be multiplied with sample_weight (passed + through the fit method) if sample_weight is specified. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; @@ -395,15 +467,26 @@ class DecisionTreeClassifier(BaseDecisionTree, ClassifierMixin): Attributes ---------- - `tree_` : Tree object + tree_ : Tree object The underlying Tree object. - `feature_importances_` : array of shape = [n_features] - The feature importances (the higher, the more important the feature). - The importance I(f) of a feature f is computed as the (normalized) - total reduction of error brought by that feature. It is also known as - the Gini importance [4]_. + max_features_ : int, + The inferred value of max_features. + + classes_ : array of shape = [n_classes] or a list of such arrays + The classes labels (single output problem), + or a list of arrays of class labels (multi-output problem). + n_classes_ : int or list + The number of classes (for single output problems), + or a list containing the number of classes for each + output (for multi-output problems). + + feature_importances_ : array of shape = [n_features] + The feature importances. The higher, the more important the + feature. The importance of a feature is computed as the (normalized) + total reduction of the criterion brought by that feature. It is also + known as the Gini importance [4]_. See also -------- @@ -428,55 +511,68 @@ class DecisionTreeClassifier(BaseDecisionTree, ClassifierMixin): >>> from sklearn.datasets import load_iris >>> from sklearn.cross_validation import cross_val_score >>> from sklearn.tree import DecisionTreeClassifier - >>> clf = DecisionTreeClassifier(random_state=0) >>> iris = load_iris() - >>> cross_val_score(clf, iris.data, iris.target, cv=10) ... # doctest: +SKIP ... array([ 1. , 0.93..., 0.86..., 0.93..., 0.93..., 0.93..., 0.93..., 1. , 0.93..., 1. ]) """ - def __init__(self, criterion="gini", - max_depth=None, - min_samples_split=1, - min_samples_leaf=1, - min_density=0.1, - max_features=None, - compute_importances=False, - random_state=None): - super(DecisionTreeClassifier, self).__init__(criterion, - max_depth, - min_samples_split, - min_samples_leaf, - min_density, - max_features, - compute_importances, - random_state) + def __init__(self, + criterion="gini", + splitter="best", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0., + max_features=None, + random_state=None, + max_leaf_nodes=None, + class_weight=None): + super(DecisionTreeClassifier, self).__init__( + criterion=criterion, + splitter=splitter, + max_depth=max_depth, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_features=max_features, + max_leaf_nodes=max_leaf_nodes, + class_weight=class_weight, + random_state=random_state) def predict_proba(self, X): """Predict class probabilities of the input samples X. + The predicted class probability is the fraction of samples of the same + class in a leaf. + Parameters ---------- - X : array-like of shape = [n_samples, n_features] - The input samples. + X : array-like or sparse matrix of shape = [n_samples, n_features] + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. Returns ------- p : array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1. - The class probabilities of the input samples. Classes are ordered - by arithmetical order. + The class probabilities of the input samples. The order of the + classes corresponds to that in the attribute `classes_`. """ - if getattr(X, "dtype", None) != DTYPE or X.ndim != 2: - X = array2d(X, dtype=DTYPE, order="F") + check_is_fitted(self, 'n_outputs_') + X = check_array(X, dtype=DTYPE, accept_sparse="csr") + if issparse(X) and (X.indices.dtype != np.intc or + X.indptr.dtype != np.intc): + raise ValueError("No support for np.int64 index based " + "sparse matrices") n_samples, n_features = X.shape if self.tree_ is None: - raise Exception("Tree not initialized. Perform a fit first.") + raise NotFittedError("Tree not initialized. Perform a fit first.") if self.n_features_ != n_features: raise ValueError("Number of features of the model must " @@ -484,36 +580,44 @@ def predict_proba(self, X): " input n_features is %s " % (self.n_features_, n_features)) - proba = [] - P = self.tree_.predict(X) + proba = self.tree_.predict(X) - for k in xrange(self.n_outputs_): - P_k = P[:, k, :self.n_classes_[k]] - normalizer = P_k.sum(axis=1)[:, np.newaxis] + if self.n_outputs_ == 1: + proba = proba[:, :self.n_classes_] + normalizer = proba.sum(axis=1)[:, np.newaxis] normalizer[normalizer == 0.0] = 1.0 - P_k /= normalizer - proba.append(P_k) + proba /= normalizer - if self.n_outputs_ == 1: - return proba[0] + return proba else: - return proba + all_proba = [] + + for k in range(self.n_outputs_): + proba_k = proba[:, k, :self.n_classes_[k]] + normalizer = proba_k.sum(axis=1)[:, np.newaxis] + normalizer[normalizer == 0.0] = 1.0 + proba_k /= normalizer + all_proba.append(proba_k) + + return all_proba def predict_log_proba(self, X): """Predict class log-probabilities of the input samples X. Parameters ---------- - X : array-like of shape = [n_samples, n_features] - The input samples. + X : array-like or sparse matrix of shape = [n_samples, n_features] + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. Returns ------- p : array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1. - The class log-probabilities of the input samples. Classes are - ordered by arithmetical order. + The class log-probabilities of the input samples. The order of the + classes corresponds to that in the attribute `classes_`. """ proba = self.predict_proba(X) @@ -521,14 +625,14 @@ def predict_log_proba(self, X): return np.log(proba) else: - for k in xrange(self.n_outputs_): + for k in range(self.n_outputs_): proba[k] = np.log(proba[k]) return proba class DecisionTreeRegressor(BaseDecisionTree, RegressorMixin): - """A tree regressor. + """A decision tree regressor. Parameters ---------- @@ -536,38 +640,47 @@ class DecisionTreeRegressor(BaseDecisionTree, RegressorMixin): The function to measure the quality of a split. The only supported criterion is "mse" for the mean squared error. - max_depth : integer or None, optional (default=None) + splitter : string, optional (default="best") + The strategy used to choose the split at each node. Supported + strategies are "best" to choose the best split and "random" to choose + the best random split. + + max_features : int, float, string or None, optional (default=None) + The number of features to consider when looking for the best split: + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a percentage and + `int(max_features * n_features)` features are considered at each + split. + - If "auto", then `max_features=n_features`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + + max_depth : int or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. + Ignored if ``max_leaf_nodes`` is not None. - min_samples_split : integer, optional (default=1) + min_samples_split : int, optional (default=2) The minimum number of samples required to split an internal node. - min_samples_leaf : integer, optional (default=1) + min_samples_leaf : int, optional (default=1) The minimum number of samples required to be at a leaf node. - min_density : float, optional (default=0.1) - This parameter controls a trade-off in an optimization heuristic. It - controls the minimum density of the `sample_mask` (i.e. the - fraction of samples in the mask). If the density falls below this - threshold the mask is recomputed and the input data is packed - which results in data copying. If `min_density` equals to one, - the partitions are always represented as copies of the original - data. Otherwise, partitions are represented as bit masks (aka - sample masks). - - max_features : int, string or None, optional (default=None) - The number of features to consider when looking for the best split. - If "auto", then `max_features=sqrt(n_features)` on classification - tasks and `max_features=n_features` on regression problems. If "sqrt", - then `max_features=sqrt(n_features)`. If "log2", then - `max_features=log2(n_features)`. If None, then - `max_features=n_features`. - - compute_importances : boolean, optional (default=True) - Whether feature importances are computed and stored into the - ``feature_importances_`` attribute when calling fit. + min_weight_fraction_leaf : float, optional (default=0.) + The minimum weighted fraction of the input samples required to be at a + leaf node. + + max_leaf_nodes : int or None, optional (default=None) + Grow a tree with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + If not None then ``max_depth`` will be ignored. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; @@ -577,15 +690,18 @@ class DecisionTreeRegressor(BaseDecisionTree, RegressorMixin): Attributes ---------- - `tree_` : Tree object + tree_ : Tree object The underlying Tree object. - `feature_importances_` : array of shape = [n_features] - The feature importances (the higher, the more important the feature). - The importance I(f) of a feature f is computed as the (normalized) - total reduction of error brought by that feature. It is also known as - the Gini importance [4]_. + max_features_ : int, + The inferred value of max_features. + feature_importances_ : array of shape = [n_features] + The feature importances. + The higher, the more important the feature. + The importance of a feature is computed as the + (normalized) total reduction of the criterion brought + by that feature. It is also known as the Gini importance [4]_. See also -------- @@ -610,34 +726,34 @@ class DecisionTreeRegressor(BaseDecisionTree, RegressorMixin): >>> from sklearn.datasets import load_boston >>> from sklearn.cross_validation import cross_val_score >>> from sklearn.tree import DecisionTreeRegressor - >>> boston = load_boston() >>> regressor = DecisionTreeRegressor(random_state=0) - - R2 scores (a.k.a. coefficient of determination) over 10-folds CV: - >>> cross_val_score(regressor, boston.data, boston.target, cv=10) ... # doctest: +SKIP ... array([ 0.61..., 0.57..., -0.34..., 0.41..., 0.75..., 0.07..., 0.29..., 0.33..., -1.42..., -1.77...]) """ - def __init__(self, criterion="mse", - max_depth=None, - min_samples_split=1, - min_samples_leaf=1, - min_density=0.1, - max_features=None, - compute_importances=False, - random_state=None): - super(DecisionTreeRegressor, self).__init__(criterion, - max_depth, - min_samples_split, - min_samples_leaf, - min_density, - max_features, - compute_importances, - random_state) + def __init__(self, + criterion="mse", + splitter="best", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0., + max_features=None, + random_state=None, + max_leaf_nodes=None): + super(DecisionTreeRegressor, self).__init__( + criterion=criterion, + splitter=splitter, + max_depth=max_depth, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_features=max_features, + max_leaf_nodes=max_leaf_nodes, + random_state=random_state) class ExtraTreeClassifier(DecisionTreeClassifier): @@ -662,24 +778,28 @@ class ExtraTreeClassifier(DecisionTreeClassifier): .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. """ - def __init__(self, criterion="gini", - max_depth=None, - min_samples_split=1, - min_samples_leaf=1, - min_density=0.1, - max_features="auto", - compute_importances=False, - random_state=None): - super(ExtraTreeClassifier, self).__init__(criterion, - max_depth, - min_samples_split, - min_samples_leaf, - min_density, - max_features, - compute_importances, - random_state) - - self.find_split_ = _tree.TREE_SPLIT_RANDOM + def __init__(self, + criterion="gini", + splitter="random", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0., + max_features="auto", + random_state=None, + max_leaf_nodes=None, + class_weight=None): + super(ExtraTreeClassifier, self).__init__( + criterion=criterion, + splitter=splitter, + max_depth=max_depth, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_features=max_features, + max_leaf_nodes=max_leaf_nodes, + class_weight=class_weight, + random_state=random_state) class ExtraTreeRegressor(DecisionTreeRegressor): @@ -696,11 +816,7 @@ class ExtraTreeRegressor(DecisionTreeRegressor): See also -------- - ExtraTreeClassifier : A classifier base on extremely randomized trees - sklearn.ensemble.ExtraTreesClassifier : An ensemble of extra-trees for - classification - sklearn.ensemble.ExtraTreesRegressor : An ensemble of extra-trees for - regression + ExtraTreeClassifier, ExtraTreesClassifier, ExtraTreesRegressor References ---------- @@ -708,21 +824,23 @@ class ExtraTreeRegressor(DecisionTreeRegressor): .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. """ - def __init__(self, criterion="mse", - max_depth=None, - min_samples_split=1, - min_samples_leaf=1, - min_density=0.1, - max_features="auto", - compute_importances=False, - random_state=None): - super(ExtraTreeRegressor, self).__init__(criterion, - max_depth, - min_samples_split, - min_samples_leaf, - min_density, - max_features, - compute_importances, - random_state) - - self.find_split_ = _tree.TREE_SPLIT_RANDOM + def __init__(self, + criterion="mse", + splitter="random", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0., + max_features="auto", + random_state=None, + max_leaf_nodes=None): + super(ExtraTreeRegressor, self).__init__( + criterion=criterion, + splitter=splitter, + max_depth=max_depth, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_features=max_features, + max_leaf_nodes=max_leaf_nodes, + random_state=random_state) diff --git a/sklearn/utils/__init__.py b/sklearn/utils/__init__.py index c09cc3d1c17dd..1728195e7eab4 100644 --- a/sklearn/utils/__init__.py +++ b/sklearn/utils/__init__.py @@ -1,16 +1,30 @@ """ -The :mod:`sklearn.utils` module includes various utilites. +The :mod:`sklearn.utils` module includes various utilities. """ +from collections import Sequence import numpy as np from scipy.sparse import issparse import warnings -from .validation import * from .murmurhash import murmurhash3_32 +from .validation import (as_float_array, + assert_all_finite, warn_if_not_float, + check_random_state, column_or_1d, check_array, + check_consistent_length, check_X_y, indexable, + check_symmetric) +from .class_weight import compute_class_weight, compute_sample_weight +from ..externals.joblib import cpu_count -# Make sure that DeprecationWarning get printed -warnings.simplefilter("always", DeprecationWarning) + +__all__ = ["murmurhash3_32", "as_float_array", + "assert_all_finite", "check_array", + "warn_if_not_float", + "check_random_state", + "compute_class_weight", "compute_sample_weight", + "column_or_1d", "safe_indexing", + "check_consistent_length", "check_X_y", 'indexable', + "check_symmetric"] class deprecated(object): @@ -110,7 +124,7 @@ def safe_mask(X, mask): ------- mask """ - mask = np.asanyarray(mask) + mask = np.asarray(mask) if np.issubdtype(mask.dtype, np.int): return mask @@ -120,6 +134,33 @@ def safe_mask(X, mask): return mask +def safe_indexing(X, indices): + """Return items or rows from X using indices. + + Allows simple indexing of lists or arrays. + + Parameters + ---------- + X : array-like, sparse-matrix, list. + Data from which to sample rows or items. + + indices : array-like, list + Indices according to which X will be subsampled. + """ + if hasattr(X, "iloc"): + # Pandas Dataframes and Series + return X.iloc[indices] + elif hasattr(X, "shape"): + if hasattr(X, 'take') and (hasattr(indices, 'dtype') and + indices.dtype.kind == 'i'): + # This is often substantially faster than X[indices] + return X.take(indices, axis=0) + else: + return X[indices] + else: + return [X[idx] for idx in indices] + + def resample(*arrays, **options): """Resample arrays or sparse matrices in a consistent way @@ -128,7 +169,7 @@ def resample(*arrays, **options): Parameters ---------- - `*arrays` : sequence of arrays or scipy.sparse matrices with same shape[0] + *arrays : sequence of arrays or scipy.sparse matrices with same shape[0] replace : boolean, True by default Implements resampling with replacement. If False, this will implement @@ -143,8 +184,10 @@ def resample(*arrays, **options): Returns ------- - Sequence of resampled views of the collections. The original arrays are - not impacted. + resampled_arrays : sequence of arrays or scipy.sparse matrices with same \ + shape[0] + Sequence of resampled views of the collections. The original arrays are + not impacted. Examples -------- @@ -203,7 +246,9 @@ def resample(*arrays, **options): raise ValueError("Cannot sample %d out of arrays with dim %d" % ( max_n_samples, n_samples)) - arrays = check_arrays(*arrays, sparse_format='csr') + check_consistent_length(*arrays) + arrays = [check_array(x, accept_sparse='csr', ensure_2d=False, + allow_nd=True) for x in arrays] if replace: indices = random_state.randint(0, n_samples, size=(max_n_samples,)) @@ -233,7 +278,7 @@ def shuffle(*arrays, **options): Parameters ---------- - `*arrays` : sequence of arrays or scipy.sparse matrices with same shape[0] + *arrays : sequence of arrays or scipy.sparse matrices with same shape[0] random_state : int or RandomState instance Control the shuffling for reproducible behavior. @@ -244,8 +289,10 @@ def shuffle(*arrays, **options): Returns ------- - Sequence of shuffled views of the collections. The original arrays are - not impacted. + shuffled_arrays : sequence of arrays or scipy.sparse matrices with same \ + shape[0] + Sequence of shuffled views of the collections. The original arrays are + not impacted. Examples -------- @@ -294,11 +341,15 @@ def safe_sqr(X, copy=True): ---------- X : array like, matrix, sparse matrix + copy : boolean, optional, default True + Whether to create a copy of X and operate on it or to perform + inplace computation (default behaviour). + Returns ------- X ** 2 : element wise square """ - X = safe_asarray(X) + X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) if issparse(X): if copy: X = X.copy() @@ -311,9 +362,37 @@ def safe_sqr(X, copy=True): return X -def gen_even_slices(n, n_packs): +def gen_batches(n, batch_size): + """Generator to create slices containing batch_size elements, from 0 to n. + + The last slice may contain less than batch_size elements, when batch_size + does not divide n. + + Examples + -------- + >>> from sklearn.utils import gen_batches + >>> list(gen_batches(7, 3)) + [slice(0, 3, None), slice(3, 6, None), slice(6, 7, None)] + >>> list(gen_batches(6, 3)) + [slice(0, 3, None), slice(3, 6, None)] + >>> list(gen_batches(2, 3)) + [slice(0, 2, None)] + """ + start = 0 + for _ in range(int(n // batch_size)): + end = start + batch_size + yield slice(start, end) + start = end + if start < n: + yield slice(start, n) + + +def gen_even_slices(n, n_packs, n_samples=None): """Generator to create n_packs slices going up to n. + Pass n_samples when the slices are to be used for sparse matrix indexing; + slicing off-the-end raises an exception, while it works for NumPy arrays. + Examples -------- >>> from sklearn.utils import gen_even_slices @@ -333,9 +412,64 @@ def gen_even_slices(n, n_packs): this_n += 1 if this_n > 0: end = start + this_n + if n_samples is not None: + end = min(n_samples, end) yield slice(start, end, None) start = end -class ConvergenceWarning(Warning): - "Custom warning to capture convergence problems" +def _get_n_jobs(n_jobs): + """Get number of jobs for the computation. + + This function reimplements the logic of joblib to determine the actual + number of jobs depending on the cpu count. If -1 all CPUs are used. + If 1 is given, no parallel computing code is used at all, which is useful + for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. + Thus for n_jobs = -2, all CPUs but one are used. + + Parameters + ---------- + n_jobs : int + Number of jobs stated in joblib convention. + + Returns + ------- + n_jobs : int + The actual number of jobs as positive integer. + + Examples + -------- + >>> from sklearn.utils import _get_n_jobs + >>> _get_n_jobs(4) + 4 + >>> jobs = _get_n_jobs(-2) + >>> assert jobs == max(cpu_count() - 1, 1) + >>> _get_n_jobs(0) + Traceback (most recent call last): + ... + ValueError: Parameter n_jobs == 0 has no meaning. + """ + if n_jobs < 0: + return max(cpu_count() + 1 + n_jobs, 1) + elif n_jobs == 0: + raise ValueError('Parameter n_jobs == 0 has no meaning.') + else: + return n_jobs + + +def tosequence(x): + """Cast iterable x to a Sequence, avoiding a copy if possible.""" + if isinstance(x, np.ndarray): + return np.asarray(x) + elif isinstance(x, Sequence): + return x + else: + return list(x) + + +class ConvergenceWarning(UserWarning): + """Custom warning to capture convergence problems""" + + +class DataDimensionalityWarning(UserWarning): + """Custom warning to notify potential issues with data dimensionality""" diff --git a/sklearn/utils/_csgraph.py b/sklearn/utils/_csgraph.py deleted file mode 100644 index e9dbb2e563369..0000000000000 --- a/sklearn/utils/_csgraph.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Compressed Sparse graph algorithms""" -# Backported from scipy 0.9: scipy.sparse.csgraph - -# Some compatibility fixes for scipy 0.6 -# Fabian Pedregosa, October 2010 - -__docformat__ = "restructuredtext en" - -__all__ = ['cs_graph_components'] - -import numpy as np - -from .sparsetools import cs_graph_components as _cs_graph_components - -from scipy.sparse import csr_matrix -from scipy.sparse import isspmatrix - -_msg0 = 'x must be a symmetric square matrix!' -_msg1 = _msg0 + '(has shape %s)' - - -def cs_graph_components(x): - """ - Determine connected compoments of a graph stored as a compressed sparse row - or column matrix. For speed reasons, the symmetry of the matrix x is not - checked. - - Parameters - ---------- - x: ndarray-like, 2 dimensions, or sparse matrix - The adjacency matrix of the graph. Only the upper triangular part - is used. - - Returns - ------- - n_components: int - The number of connected components. - label: ndarray (ints, 1 dimension): - The label array of each connected component (-2 is used to - indicate empty rows: 0 everywhere, including diagonal). - - Notes - ----- - - The matrix is assumed to be symmetric and the upper triangular part - of the matrix is used. The matrix is converted to a CSR matrix unless - it is already a CSR. - - Examples - -------- - - >>> from scipy.sparse import cs_graph_components - >>> import numpy as np - >>> D = np.eye(4) - >>> D[0,1] = D[1,0] = 1 - >>> cs_graph_components(D) - (3, array([0, 0, 1, 2])) - >>> from scipy.sparse import dok_matrix - >>> cs_graph_components(dok_matrix(D)) - (3, array([0, 0, 1, 2])) - - """ - try: - shape = x.shape - except AttributeError: - raise ValueError(_msg0) - - if not ((len(x.shape) == 2) and (x.shape[0] == x.shape[1])): - raise ValueError(_msg1 % x.shape) - - if isspmatrix(x): - x = x.tocsr() - else: - x = csr_matrix(x) - - label = np.empty((shape[0],), dtype=x.indptr.dtype) - - n_components = _cs_graph_components(shape[0], x.indptr, x.indices, label) - - return n_components, label diff --git a/sklearn/cluster/_hierarchical.c b/sklearn/utils/_logistic_sigmoid.c similarity index 63% rename from sklearn/cluster/_hierarchical.c rename to sklearn/utils/_logistic_sigmoid.c index ae791de8171a2..36ef5f5213781 100644 --- a/sklearn/cluster/_hierarchical.c +++ b/sklearn/utils/_logistic_sigmoid.c @@ -1,6 +1,18 @@ -/* Generated by Cython 0.17pre on Wed Jul 18 15:14:12 2012 */ +/* Generated by Cython 0.19 on Sun Jul 28 16:43:38 2013 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. @@ -11,7 +23,6 @@ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -23,22 +34,18 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif - #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 @@ -46,25 +53,28 @@ #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif - #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ (PyErr_Format(PyExc_TypeError, \ "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ (PyObject*)0)) - #define PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && !PyComplex_Check(o)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) #define __PYX_BUILD_PY_SSIZE_T "i" #else #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -72,7 +82,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -86,7 +95,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -98,11 +106,9 @@ #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) - typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ @@ -112,21 +118,19 @@ #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #endif - #if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - - +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ @@ -139,10 +143,8 @@ #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #endif - #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -150,7 +152,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -169,7 +170,14 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) +#endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -177,9 +185,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -196,11 +202,9 @@ #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - #if PY_VERSION_HEX < 0x03020000 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong @@ -209,7 +213,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -228,11 +231,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -242,7 +243,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -250,6 +250,30 @@ #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) @@ -271,8 +295,10 @@ #define _USE_MATH_DEFINES #endif #include -#define __PYX_HAVE__sklearn__cluster___hierarchical -#define __PYX_HAVE_API__sklearn__cluster___hierarchical +#define __PYX_HAVE__sklearn__utils___logistic_sigmoid +#define __PYX_HAVE_API__sklearn__utils___logistic_sigmoid +#include "math.h" +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" @@ -285,21 +311,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -313,30 +324,130 @@ # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - #if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + #ifdef __GNUC__ /* Test for GCC > 2.95 */ @@ -351,8 +462,9 @@ static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -384,8 +496,9 @@ static const char *__pyx_filename; static const char *__pyx_f[] = { - "_hierarchical.pyx", + "_logistic_sigmoid.pyx", "numpy.pxd", + "type.pxd", }; #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; @@ -396,7 +509,7 @@ typedef struct { size_t size; /* sizeof(type) */ size_t arraysize[8]; /* length of array in each dimension */ int ndim; - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ char is_unsigned; int flags; } __Pyx_TypeInfo; @@ -423,7 +536,7 @@ typedef struct { } __Pyx_BufFmt_Context; -/* "numpy.pxd":722 +/* "numpy.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -432,7 +545,7 @@ typedef struct { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":723 +/* "numpy.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -441,7 +554,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":724 +/* "numpy.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -450,7 +563,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":725 +/* "numpy.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -459,7 +572,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":729 +/* "numpy.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -468,7 +581,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":730 +/* "numpy.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -477,7 +590,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":731 +/* "numpy.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -486,7 +599,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":732 +/* "numpy.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -495,7 +608,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":736 +/* "numpy.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -504,7 +617,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":737 +/* "numpy.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -513,7 +626,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":746 +/* "numpy.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -522,7 +635,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":747 +/* "numpy.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -531,7 +644,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":748 +/* "numpy.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -540,7 +653,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":750 +/* "numpy.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -549,7 +662,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":751 +/* "numpy.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -558,7 +671,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":752 +/* "numpy.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -567,7 +680,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":754 +/* "numpy.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -576,7 +689,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":755 +/* "numpy.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -585,7 +698,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":757 +/* "numpy.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -594,7 +707,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":758 +/* "numpy.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -603,7 +716,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":759 +/* "numpy.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -612,32 +725,14 @@ typedef npy_double __pyx_t_5numpy_double_t; */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; -/* "sklearn/cluster/_hierarchical.pyx":4 +/* "sklearn/utils/_logistic_sigmoid.pyx":10 * cimport numpy as np - * cimport cython - * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< - * ctypedef np.int_t INT - * ctypedef np.int8_t INT8 - */ -typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE; - -/* "sklearn/cluster/_hierarchical.pyx":5 - * cimport cython - * ctypedef np.float64_t DOUBLE - * ctypedef np.int_t INT # <<<<<<<<<<<<<< - * ctypedef np.int8_t INT8 * - */ -typedef __pyx_t_5numpy_int_t __pyx_t_7sklearn_7cluster_13_hierarchical_INT; - -/* "sklearn/cluster/_hierarchical.pyx":6 - * ctypedef np.float64_t DOUBLE - * ctypedef np.int_t INT - * ctypedef np.int8_t INT8 # <<<<<<<<<<<<<< + * ctypedef np.float64_t DTYPE_t # <<<<<<<<<<<<<< * * */ -typedef __pyx_t_5numpy_int8_t __pyx_t_7sklearn_7cluster_13_hierarchical_INT8; +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t; #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -661,7 +756,7 @@ typedef __pyx_t_5numpy_int8_t __pyx_t_7sklearn_7cluster_13_hierarchical_INT8; /*--- Type declarations ---*/ -/* "numpy.pxd":761 +/* "numpy.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -670,7 +765,7 @@ typedef __pyx_t_5numpy_int8_t __pyx_t_7sklearn_7cluster_13_hierarchical_INT8; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":762 +/* "numpy.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -679,7 +774,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":763 +/* "numpy.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -688,7 +783,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":765 +/* "numpy.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -750,7 +845,22 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ @@ -768,132 +878,10 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* o __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); -#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) #define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ -static CYTHON_INLINE PyObject* __Pyx_PyObject_Pop(PyObject* L) { -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x02040000 - if (likely(PyList_CheckExact(L)) - && likely(PyList_GET_SIZE(L) > (((PyListObject*)L)->allocated >> 1))) { - Py_SIZE(L) -= 1; - return PyList_GET_ITEM(L, PyList_GET_SIZE(L)); - } -#if PY_VERSION_HEX >= 0x02050000 - else if (Py_TYPE(L) == (&PySet_Type)) { - return PySet_Pop(L); - } -#endif -#endif - return PyObject_CallMethod(L, (char*)"pop", NULL); -} - -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -#define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_List_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { -#if CYTHON_COMPILING_IN_CPYTHON - if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Tuple_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { -#if CYTHON_COMPILING_IN_CPYTHON - if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -#define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Fast(o, i) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { -#if CYTHON_COMPILING_IN_CPYTHON - if (PyList_CheckExact(o)) { - Py_ssize_t n = (likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if (likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = (likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if (likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { /* inlined PySequence_GetItem() */ - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (unlikely(l < 0)) return NULL; - i += l; - } - return m->sq_item(o, i); - } - } -#else - if (PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ - -static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ - -static CYTHON_INLINE PyObject* __Pyx_PyObject_Append(PyObject* L, PyObject* x) { - if (likely(PyList_CheckExact(L))) { - if (unlikely(PyList_Append(L, x) < 0)) return NULL; - Py_INCREF(Py_None); - return Py_None; /* this is just to have an accurate signature */ - } else { - PyObject *r, *m; - m = __Pyx_GetAttrString(L, "append"); - if (!m) return NULL; - r = PyObject_CallFunctionObjArgs(m, x, NULL); - Py_DECREF(m); - return r; - } -} - static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); @@ -906,6 +894,8 @@ static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + typedef struct { Py_ssize_t shape, strides, suboffsets; } __Pyx_Buf_DimInfo; @@ -927,10 +917,11 @@ typedef struct { #define __Pyx_ReleaseBuffer PyBuffer_Release #endif + static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -1072,10 +1063,10 @@ static int __Pyx_check_binary_version(void); #endif #endif -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ - static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + typedef struct { int code_line; PyCodeObject* code_object; @@ -1096,14 +1087,23 @@ static void __Pyx_AddTraceback(const char *funcname, int c_line, static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ +/* Module declarations from 'libc.math' */ + /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -1116,39 +1116,35 @@ static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -/* Module declarations from 'cython' */ +/* Module declarations from 'sklearn.utils._logistic_sigmoid' */ +static __pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t __pyx_f_7sklearn_5utils_17_logistic_sigmoid__inner_log_logistic_sigmoid(__pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; +#define __Pyx_MODULE_NAME "sklearn.utils._logistic_sigmoid" +int __pyx_module_is_main_sklearn__utils___logistic_sigmoid = 0; -/* Module declarations from 'sklearn.cluster._hierarchical' */ -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE), { 0 }, 0, 'R', 0, 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INT = { "INT", NULL, sizeof(__pyx_t_7sklearn_7cluster_13_hierarchical_INT), { 0 }, 0, 'I', IS_UNSIGNED(__pyx_t_7sklearn_7cluster_13_hierarchical_INT), 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INT8 = { "INT8", NULL, sizeof(__pyx_t_7sklearn_7cluster_13_hierarchical_INT8), { 0 }, 0, 'I', IS_UNSIGNED(__pyx_t_7sklearn_7cluster_13_hierarchical_INT8), 0 }; -#define __Pyx_MODULE_NAME "sklearn.cluster._hierarchical" -int __pyx_module_is_main_sklearn__cluster___hierarchical = 0; - -/* Implementation of 'sklearn.cluster._hierarchical' */ +/* Implementation of 'sklearn.utils._logistic_sigmoid' */ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; -static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_compute_ward_dist(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_m_1, PyArrayObject *__pyx_v_m_2, PyArrayObject *__pyx_v_coord_row, PyArrayObject *__pyx_v_coord_col, PyArrayObject *__pyx_v_res); /* proto */ -static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_2_hc_get_descendent(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_node, PyObject *__pyx_v_children, int __pyx_v_n_leaves); /* proto */ -static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_4hc_get_heads(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_parents, PyObject *__pyx_v_copy); /* proto */ -static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_6_get_parents(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_nodes, PyObject *__pyx_v_heads, PyArrayObject *__pyx_v_parents, PyArrayObject *__pyx_v_not_visited); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_17_logistic_sigmoid__log_logistic_sigmoid(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_samples, int __pyx_v_n_features, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_out); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ -static char __pyx_k_2[] = "ndarray is not C contiguous"; -static char __pyx_k_4[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_6[] = "Non-native byte order not supported"; -static char __pyx_k_8[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_9[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_12[] = "Format string allocated too short."; -static char __pyx_k_16[] = "/volatile/varoquau/dev/scikit-learn/sklearn/cluster/_hierarchical.pyx"; -static char __pyx_k_17[] = "sklearn.cluster._hierarchical"; +static char __pyx_k_1[] = "ndarray is not C contiguous"; +static char __pyx_k_3[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_5[] = "Non-native byte order not supported"; +static char __pyx_k_7[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_8[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_11[] = "Format string allocated too short."; +static char __pyx_k_15[] = "_log_logistic_sigmoid"; +static char __pyx_k_16[] = "/home/lars/src/scikit-learn/sklearn/utils/_logistic_sigmoid.pyx"; +static char __pyx_k_17[] = "sklearn.utils._logistic_sigmoid"; static char __pyx_k__B[] = "B"; static char __pyx_k__H[] = "H"; static char __pyx_k__I[] = "I"; static char __pyx_k__L[] = "L"; static char __pyx_k__O[] = "O"; static char __pyx_k__Q[] = "Q"; +static char __pyx_k__X[] = "X"; static char __pyx_k__b[] = "b"; static char __pyx_k__d[] = "d"; static char __pyx_k__f[] = "f"; @@ -1157,131 +1153,134 @@ static char __pyx_k__h[] = "h"; static char __pyx_k__i[] = "i"; static char __pyx_k__j[] = "j"; static char __pyx_k__l[] = "l"; -static char __pyx_k__n[] = "n"; static char __pyx_k__q[] = "q"; static char __pyx_k__Zd[] = "Zd"; static char __pyx_k__Zf[] = "Zf"; static char __pyx_k__Zg[] = "Zg"; static char __pyx_k__np[] = "np"; -static char __pyx_k__pa[] = "pa"; -static char __pyx_k__col[] = "col"; -static char __pyx_k__ind[] = "ind"; -static char __pyx_k__m_1[] = "m_1"; -static char __pyx_k__m_2[] = "m_2"; -static char __pyx_k__res[] = "res"; -static char __pyx_k__row[] = "row"; -static char __pyx_k__copy[] = "copy"; -static char __pyx_k__node[] = "node"; -static char __pyx_k__size[] = "size"; -static char __pyx_k__heads[] = "heads"; -static char __pyx_k__node0[] = "node0"; -static char __pyx_k__nodes[] = "nodes"; +static char __pyx_k__out[] = "out"; static char __pyx_k__numpy[] = "numpy"; static char __pyx_k__range[] = "range"; -static char __pyx_k__extend[] = "extend"; -static char __pyx_k__parent[] = "parent"; -static char __pyx_k__parents[] = "parents"; static char __pyx_k____main__[] = "__main__"; static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__children[] = "children"; -static char __pyx_k__n_leaves[] = "n_leaves"; -static char __pyx_k__size_max[] = "size_max"; -static char __pyx_k__coord_col[] = "coord_col"; -static char __pyx_k__coord_row[] = "coord_row"; -static char __pyx_k__n_indices[] = "n_indices"; +static char __pyx_k__n_samples[] = "n_samples"; static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__descendent[] = "descendent"; +static char __pyx_k____import__[] = "__import__"; static char __pyx_k__n_features[] = "n_features"; -static char __pyx_k__not_visited[] = "not_visited"; static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k___get_parents[] = "_get_parents"; -static char __pyx_k__hc_get_heads[] = "hc_get_heads"; -static char __pyx_k__compute_ward_dist[] = "compute_ward_dist"; -static char __pyx_k___hc_get_descendent[] = "_hc_get_descendent"; -static PyObject *__pyx_kp_u_12; +static char __pyx_k____pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k____pyx_releasebuffer[] = "__pyx_releasebuffer"; +static PyObject *__pyx_kp_u_1; +static PyObject *__pyx_kp_u_11; +static PyObject *__pyx_n_s_15; static PyObject *__pyx_kp_s_16; static PyObject *__pyx_n_s_17; -static PyObject *__pyx_kp_u_2; -static PyObject *__pyx_kp_u_4; -static PyObject *__pyx_kp_u_6; +static PyObject *__pyx_kp_u_3; +static PyObject *__pyx_kp_u_5; +static PyObject *__pyx_kp_u_7; static PyObject *__pyx_kp_u_8; -static PyObject *__pyx_kp_u_9; static PyObject *__pyx_n_s__RuntimeError; static PyObject *__pyx_n_s__ValueError; +static PyObject *__pyx_n_s__X; +static PyObject *__pyx_n_s____import__; static PyObject *__pyx_n_s____main__; +static PyObject *__pyx_n_s____pyx_getbuffer; +static PyObject *__pyx_n_s____pyx_releasebuffer; static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s___get_parents; -static PyObject *__pyx_n_s___hc_get_descendent; -static PyObject *__pyx_n_s__children; -static PyObject *__pyx_n_s__col; -static PyObject *__pyx_n_s__compute_ward_dist; -static PyObject *__pyx_n_s__coord_col; -static PyObject *__pyx_n_s__coord_row; -static PyObject *__pyx_n_s__copy; -static PyObject *__pyx_n_s__descendent; -static PyObject *__pyx_n_s__extend; -static PyObject *__pyx_n_s__hc_get_heads; -static PyObject *__pyx_n_s__heads; static PyObject *__pyx_n_s__i; -static PyObject *__pyx_n_s__ind; static PyObject *__pyx_n_s__j; -static PyObject *__pyx_n_s__m_1; -static PyObject *__pyx_n_s__m_2; -static PyObject *__pyx_n_s__n; static PyObject *__pyx_n_s__n_features; -static PyObject *__pyx_n_s__n_indices; -static PyObject *__pyx_n_s__n_leaves; -static PyObject *__pyx_n_s__node; -static PyObject *__pyx_n_s__node0; -static PyObject *__pyx_n_s__nodes; -static PyObject *__pyx_n_s__not_visited; +static PyObject *__pyx_n_s__n_samples; static PyObject *__pyx_n_s__np; static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__pa; -static PyObject *__pyx_n_s__parent; -static PyObject *__pyx_n_s__parents; +static PyObject *__pyx_n_s__out; static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__res; -static PyObject *__pyx_n_s__row; -static PyObject *__pyx_n_s__size; -static PyObject *__pyx_n_s__size_max; static PyObject *__pyx_int_15; -static PyObject *__pyx_k_1; -static PyObject *__pyx_k_tuple_3; -static PyObject *__pyx_k_tuple_5; -static PyObject *__pyx_k_tuple_7; +static PyObject *__pyx_k_tuple_2; +static PyObject *__pyx_k_tuple_4; +static PyObject *__pyx_k_tuple_6; +static PyObject *__pyx_k_tuple_9; static PyObject *__pyx_k_tuple_10; -static PyObject *__pyx_k_tuple_11; +static PyObject *__pyx_k_tuple_12; static PyObject *__pyx_k_tuple_13; -static PyObject *__pyx_k_tuple_14; -static PyObject *__pyx_k_tuple_18; -static PyObject *__pyx_k_tuple_20; -static PyObject *__pyx_k_tuple_22; -static PyObject *__pyx_k_codeobj_15; -static PyObject *__pyx_k_codeobj_19; -static PyObject *__pyx_k_codeobj_21; -static PyObject *__pyx_k_codeobj_23; +static PyObject *__pyx_k_codeobj_14; + +/* "sklearn/utils/_logistic_sigmoid.pyx":13 + * + * + * cdef DTYPE_t _inner_log_logistic_sigmoid(DTYPE_t x): # <<<<<<<<<<<<<< + * """Log of the logistic sigmoid function log(1 / (1 + e ** -x))""" + * if x > 0: + */ + +static __pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t __pyx_f_7sklearn_5utils_17_logistic_sigmoid__inner_log_logistic_sigmoid(__pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t __pyx_v_x) { + __pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("_inner_log_logistic_sigmoid", 0); + + /* "sklearn/utils/_logistic_sigmoid.pyx":15 + * cdef DTYPE_t _inner_log_logistic_sigmoid(DTYPE_t x): + * """Log of the logistic sigmoid function log(1 / (1 + e ** -x))""" + * if x > 0: # <<<<<<<<<<<<<< + * return -log(1 + exp(-x)) + * else: + */ + __pyx_t_1 = (__pyx_v_x > 0.0); + if (__pyx_t_1) { + + /* "sklearn/utils/_logistic_sigmoid.pyx":16 + * """Log of the logistic sigmoid function log(1 / (1 + e ** -x))""" + * if x > 0: + * return -log(1 + exp(-x)) # <<<<<<<<<<<<<< + * else: + * return x - log(1 + exp(x)) + */ + __pyx_r = (-log((1.0 + exp((-__pyx_v_x))))); + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/utils/_logistic_sigmoid.pyx":18 + * return -log(1 + exp(-x)) + * else: + * return x - log(1 + exp(x)) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = (__pyx_v_x - log((1.0 + exp(__pyx_v_x)))); + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} /* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_1compute_ward_dist(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7sklearn_7cluster_13_hierarchical_1compute_ward_dist = {__Pyx_NAMESTR("compute_ward_dist"), (PyCFunction)__pyx_pw_7sklearn_7cluster_13_hierarchical_1compute_ward_dist, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; -static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_1compute_ward_dist(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_m_1 = 0; - PyArrayObject *__pyx_v_m_2 = 0; - PyArrayObject *__pyx_v_coord_row = 0; - PyArrayObject *__pyx_v_coord_col = 0; - PyArrayObject *__pyx_v_res = 0; +static PyObject *__pyx_pw_7sklearn_5utils_17_logistic_sigmoid_1_log_logistic_sigmoid(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_5utils_17_logistic_sigmoid_1_log_logistic_sigmoid = {__Pyx_NAMESTR("_log_logistic_sigmoid"), (PyCFunction)__pyx_pw_7sklearn_5utils_17_logistic_sigmoid_1_log_logistic_sigmoid, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_5utils_17_logistic_sigmoid_1_log_logistic_sigmoid(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + int __pyx_v_n_samples; + int __pyx_v_n_features; + PyArrayObject *__pyx_v_X = 0; + PyArrayObject *__pyx_v_out = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("compute_ward_dist (wrapper)", 0); + __Pyx_RefNannySetupContext("_log_logistic_sigmoid (wrapper)", 0); { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__m_1,&__pyx_n_s__m_2,&__pyx_n_s__coord_row,&__pyx_n_s__coord_col,&__pyx_n_s__res,0}; - PyObject* values[5] = {0,0,0,0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_samples,&__pyx_n_s__n_features,&__pyx_n_s__X,&__pyx_n_s__out,0}; + PyObject* values[4] = {0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); @@ -1292,61 +1291,51 @@ static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_1compute_ward_dist(P kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__m_1)) != 0)) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_samples)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__m_2)) != 0)) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_features)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("compute_ward_dist", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_log_logistic_sigmoid", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coord_row)) != 0)) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("compute_ward_dist", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_log_logistic_sigmoid", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__coord_col)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("compute_ward_dist", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 4: - if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__res)) != 0)) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__out)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("compute_ward_dist", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_log_logistic_sigmoid", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "compute_ward_dist") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_log_logistic_sigmoid") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { + } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); } - __pyx_v_m_1 = ((PyArrayObject *)values[0]); - __pyx_v_m_2 = ((PyArrayObject *)values[1]); - __pyx_v_coord_row = ((PyArrayObject *)values[2]); - __pyx_v_coord_col = ((PyArrayObject *)values[3]); - __pyx_v_res = ((PyArrayObject *)values[4]); + __pyx_v_n_samples = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_n_samples == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_features = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_n_features == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X = ((PyArrayObject *)values[2]); + __pyx_v_out = ((PyArrayObject *)values[3]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("compute_ward_dist", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_log_logistic_sigmoid", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.cluster._hierarchical.compute_ward_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.utils._logistic_sigmoid._log_logistic_sigmoid", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_m_1), __pyx_ptype_5numpy_ndarray, 1, "m_1", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_m_2), __pyx_ptype_5numpy_ndarray, 1, "m_2", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_coord_row), __pyx_ptype_5numpy_ndarray, 1, "coord_row", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_coord_col), __pyx_ptype_5numpy_ndarray, 1, "coord_col", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_res), __pyx_ptype_5numpy_ndarray, 1, "res", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_compute_ward_dist(__pyx_self, __pyx_v_m_1, __pyx_v_m_2, __pyx_v_coord_row, __pyx_v_coord_col, __pyx_v_res); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_out), __pyx_ptype_5numpy_ndarray, 1, "out", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_17_logistic_sigmoid__log_logistic_sigmoid(__pyx_self, __pyx_v_n_samples, __pyx_v_n_features, __pyx_v_X, __pyx_v_out); goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; @@ -1355,1106 +1344,114 @@ static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_1compute_ward_dist(P return __pyx_r; } -/* "sklearn/cluster/_hierarchical.pyx":12 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def compute_ward_dist(np.ndarray[DOUBLE, ndim=1] m_1,\ # <<<<<<<<<<<<<< - * np.ndarray[DOUBLE, ndim=2] m_2,\ - * np.ndarray[INT, ndim=1] coord_row, +/* "sklearn/utils/_logistic_sigmoid.pyx":21 + * + * + * def _log_logistic_sigmoid(int n_samples, int n_features, # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2] X, + * np.ndarray[DTYPE_t, ndim=2] out): */ -static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_compute_ward_dist(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_m_1, PyArrayObject *__pyx_v_m_2, PyArrayObject *__pyx_v_coord_row, PyArrayObject *__pyx_v_coord_col, PyArrayObject *__pyx_v_res) { - int __pyx_v_size_max; - int __pyx_v_n_features; - int __pyx_v_i; - int __pyx_v_j; - int __pyx_v_row; - int __pyx_v_col; - __pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE __pyx_v_pa; - __pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE __pyx_v_n; - __Pyx_LocalBuf_ND __pyx_pybuffernd_coord_col; - __Pyx_Buffer __pyx_pybuffer_coord_col; - __Pyx_LocalBuf_ND __pyx_pybuffernd_coord_row; - __Pyx_Buffer __pyx_pybuffer_coord_row; - __Pyx_LocalBuf_ND __pyx_pybuffernd_m_1; - __Pyx_Buffer __pyx_pybuffer_m_1; - __Pyx_LocalBuf_ND __pyx_pybuffernd_m_2; - __Pyx_Buffer __pyx_pybuffer_m_2; - __Pyx_LocalBuf_ND __pyx_pybuffernd_res; - __Pyx_Buffer __pyx_pybuffer_res; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; - int __pyx_t_11; - int __pyx_t_12; - int __pyx_t_13; - int __pyx_t_14; - int __pyx_t_15; - int __pyx_t_16; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("compute_ward_dist", 0); - __pyx_pybuffer_m_1.pybuffer.buf = NULL; - __pyx_pybuffer_m_1.refcount = 0; - __pyx_pybuffernd_m_1.data = NULL; - __pyx_pybuffernd_m_1.rcbuffer = &__pyx_pybuffer_m_1; - __pyx_pybuffer_m_2.pybuffer.buf = NULL; - __pyx_pybuffer_m_2.refcount = 0; - __pyx_pybuffernd_m_2.data = NULL; - __pyx_pybuffernd_m_2.rcbuffer = &__pyx_pybuffer_m_2; - __pyx_pybuffer_coord_row.pybuffer.buf = NULL; - __pyx_pybuffer_coord_row.refcount = 0; - __pyx_pybuffernd_coord_row.data = NULL; - __pyx_pybuffernd_coord_row.rcbuffer = &__pyx_pybuffer_coord_row; - __pyx_pybuffer_coord_col.pybuffer.buf = NULL; - __pyx_pybuffer_coord_col.refcount = 0; - __pyx_pybuffernd_coord_col.data = NULL; - __pyx_pybuffernd_coord_col.rcbuffer = &__pyx_pybuffer_coord_col; - __pyx_pybuffer_res.pybuffer.buf = NULL; - __pyx_pybuffer_res.refcount = 0; - __pyx_pybuffernd_res.data = NULL; - __pyx_pybuffernd_res.rcbuffer = &__pyx_pybuffer_res; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_m_1.rcbuffer->pybuffer, (PyObject*)__pyx_v_m_1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_m_1.diminfo[0].strides = __pyx_pybuffernd_m_1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_m_1.diminfo[0].shape = __pyx_pybuffernd_m_1.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_m_2.rcbuffer->pybuffer, (PyObject*)__pyx_v_m_2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_m_2.diminfo[0].strides = __pyx_pybuffernd_m_2.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_m_2.diminfo[0].shape = __pyx_pybuffernd_m_2.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_m_2.diminfo[1].strides = __pyx_pybuffernd_m_2.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_m_2.diminfo[1].shape = __pyx_pybuffernd_m_2.rcbuffer->pybuffer.shape[1]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_coord_row.rcbuffer->pybuffer, (PyObject*)__pyx_v_coord_row, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_coord_row.diminfo[0].strides = __pyx_pybuffernd_coord_row.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_coord_row.diminfo[0].shape = __pyx_pybuffernd_coord_row.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_coord_col.rcbuffer->pybuffer, (PyObject*)__pyx_v_coord_col, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_coord_col.diminfo[0].strides = __pyx_pybuffernd_coord_col.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_coord_col.diminfo[0].shape = __pyx_pybuffernd_coord_col.rcbuffer->pybuffer.shape[0]; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_res.rcbuffer->pybuffer, (PyObject*)__pyx_v_res, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_res.diminfo[0].strides = __pyx_pybuffernd_res.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_res.diminfo[0].shape = __pyx_pybuffernd_res.rcbuffer->pybuffer.shape[0]; - - /* "sklearn/cluster/_hierarchical.pyx":17 - * np.ndarray[INT, ndim=1] coord_col,\ - * np.ndarray[DOUBLE, ndim=1] res): - * cdef int size_max = coord_row.shape[0] # <<<<<<<<<<<<<< - * cdef int n_features = m_2.shape[1] - * cdef int i, j, row, col - */ - __pyx_v_size_max = (__pyx_v_coord_row->dimensions[0]); - - /* "sklearn/cluster/_hierarchical.pyx":18 - * np.ndarray[DOUBLE, ndim=1] res): - * cdef int size_max = coord_row.shape[0] - * cdef int n_features = m_2.shape[1] # <<<<<<<<<<<<<< - * cdef int i, j, row, col - * cdef DOUBLE pa, n - */ - __pyx_v_n_features = (__pyx_v_m_2->dimensions[1]); - - /* "sklearn/cluster/_hierarchical.pyx":21 - * cdef int i, j, row, col - * cdef DOUBLE pa, n - * for i in range(size_max): # <<<<<<<<<<<<<< - * row = coord_row[i] - * col = coord_col[i] - */ - __pyx_t_1 = __pyx_v_size_max; - for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { - __pyx_v_i = __pyx_t_2; - - /* "sklearn/cluster/_hierarchical.pyx":22 - * cdef DOUBLE pa, n - * for i in range(size_max): - * row = coord_row[i] # <<<<<<<<<<<<<< - * col = coord_col[i] - * n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) - */ - __pyx_t_3 = __pyx_v_i; - __pyx_v_row = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INT *, __pyx_pybuffernd_coord_row.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_coord_row.diminfo[0].strides)); - - /* "sklearn/cluster/_hierarchical.pyx":23 - * for i in range(size_max): - * row = coord_row[i] - * col = coord_col[i] # <<<<<<<<<<<<<< - * n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) - * pa = 0. - */ - __pyx_t_4 = __pyx_v_i; - __pyx_v_col = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INT *, __pyx_pybuffernd_coord_col.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_coord_col.diminfo[0].strides)); - - /* "sklearn/cluster/_hierarchical.pyx":24 - * row = coord_row[i] - * col = coord_col[i] - * n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) # <<<<<<<<<<<<<< - * pa = 0. - * for j in range(n_features): - */ - __pyx_t_5 = __pyx_v_row; - __pyx_t_6 = __pyx_v_col; - __pyx_t_7 = __pyx_v_row; - __pyx_t_8 = __pyx_v_col; - __pyx_v_n = (((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_m_1.diminfo[0].strides)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_m_1.diminfo[0].strides))) / ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_m_1.diminfo[0].strides)) + (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_m_1.diminfo[0].strides)))); - - /* "sklearn/cluster/_hierarchical.pyx":25 - * col = coord_col[i] - * n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) - * pa = 0. # <<<<<<<<<<<<<< - * for j in range(n_features): - * pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col])**2 - */ - __pyx_v_pa = 0.; - - /* "sklearn/cluster/_hierarchical.pyx":26 - * n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) - * pa = 0. - * for j in range(n_features): # <<<<<<<<<<<<<< - * pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col])**2 - * res[i] = pa * n - */ - __pyx_t_9 = __pyx_v_n_features; - for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { - __pyx_v_j = __pyx_t_10; - - /* "sklearn/cluster/_hierarchical.pyx":27 - * pa = 0. - * for j in range(n_features): - * pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col])**2 # <<<<<<<<<<<<<< - * res[i] = pa * n - * return res - */ - __pyx_t_11 = __pyx_v_row; - __pyx_t_12 = __pyx_v_j; - __pyx_t_13 = __pyx_v_row; - __pyx_t_14 = __pyx_v_col; - __pyx_t_15 = __pyx_v_j; - __pyx_t_16 = __pyx_v_col; - __pyx_v_pa = (__pyx_v_pa + pow((((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_2.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_m_2.diminfo[0].strides, __pyx_t_12, __pyx_pybuffernd_m_2.diminfo[1].strides)) / (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_m_1.diminfo[0].strides))) - ((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_2.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_m_2.diminfo[0].strides, __pyx_t_15, __pyx_pybuffernd_m_2.diminfo[1].strides)) / (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_m_1.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_m_1.diminfo[0].strides)))), 2.0)); - } - - /* "sklearn/cluster/_hierarchical.pyx":28 - * for j in range(n_features): - * pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col])**2 - * res[i] = pa * n # <<<<<<<<<<<<<< - * return res - * - */ - __pyx_t_9 = __pyx_v_i; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_DOUBLE *, __pyx_pybuffernd_res.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_res.diminfo[0].strides) = (__pyx_v_pa * __pyx_v_n); - } - - /* "sklearn/cluster/_hierarchical.pyx":29 - * pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col])**2 - * res[i] = pa * n - * return res # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_res)); - __pyx_r = ((PyObject *)__pyx_v_res); - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_coord_col.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_coord_row.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_m_1.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_m_2.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.cluster._hierarchical.compute_ward_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_coord_col.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_coord_row.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_m_1.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_m_2.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_res.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_3_hc_get_descendent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_7cluster_13_hierarchical_2_hc_get_descendent[] = "\n Function returning all the descendent leaves of a set of nodes in the tree.\n\n Parameters\n ----------\n node : int\n The node for which we want the descendents.\n\n children : list of pairs. Length of n_nodes\n List of the children of each nodes.\n This is not defined for leaves.\n\n n_leaves : int\n Number of leaves.\n\n Return\n ------\n descendent : list of int\n "; -static PyMethodDef __pyx_mdef_7sklearn_7cluster_13_hierarchical_3_hc_get_descendent = {__Pyx_NAMESTR("_hc_get_descendent"), (PyCFunction)__pyx_pw_7sklearn_7cluster_13_hierarchical_3_hc_get_descendent, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_13_hierarchical_2_hc_get_descendent)}; -static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_3_hc_get_descendent(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - int __pyx_v_node; - PyObject *__pyx_v_children = 0; - int __pyx_v_n_leaves; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_hc_get_descendent (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__node,&__pyx_n_s__children,&__pyx_n_s__n_leaves,0}; - PyObject* values[3] = {0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__node)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__children)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_hc_get_descendent", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_leaves)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_hc_get_descendent", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_hc_get_descendent") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - } - __pyx_v_node = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_node == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_children = values[1]; - __pyx_v_n_leaves = __Pyx_PyInt_AsInt(values[2]); if (unlikely((__pyx_v_n_leaves == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_hc_get_descendent", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.cluster._hierarchical._hc_get_descendent", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_2_hc_get_descendent(__pyx_self, __pyx_v_node, __pyx_v_children, __pyx_v_n_leaves); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/cluster/_hierarchical.pyx":32 - * - * - * def _hc_get_descendent(int node, children, int n_leaves): # <<<<<<<<<<<<<< - * """ - * Function returning all the descendent leaves of a set of nodes in the tree. - */ - -static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_2_hc_get_descendent(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_node, PyObject *__pyx_v_children, int __pyx_v_n_leaves) { - PyObject *__pyx_v_ind = NULL; - PyObject *__pyx_v_descendent = NULL; - int __pyx_v_n_indices; - int __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_hc_get_descendent", 0); - - /* "sklearn/cluster/_hierarchical.pyx":52 - * descendent : list of int - * """ - * ind = [node] # <<<<<<<<<<<<<< - * if node < n_leaves: - * return ind - */ - __pyx_t_1 = PyInt_FromLong(__pyx_v_node); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_v_ind = __pyx_t_2; - __pyx_t_2 = 0; - - /* "sklearn/cluster/_hierarchical.pyx":53 - * """ - * ind = [node] - * if node < n_leaves: # <<<<<<<<<<<<<< - * return ind - * descendent = [] - */ - __pyx_t_3 = (__pyx_v_node < __pyx_v_n_leaves); - if (__pyx_t_3) { - - /* "sklearn/cluster/_hierarchical.pyx":54 - * ind = [node] - * if node < n_leaves: - * return ind # <<<<<<<<<<<<<< - * descendent = [] - * # It is actually faster to do the accounting of the number of - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_ind)); - __pyx_r = ((PyObject *)__pyx_v_ind); - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "sklearn/cluster/_hierarchical.pyx":55 - * if node < n_leaves: - * return ind - * descendent = [] # <<<<<<<<<<<<<< - * # It is actually faster to do the accounting of the number of - * # elements is the list ourselves: len is a lengthy operation on a - */ - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_descendent = __pyx_t_2; - __pyx_t_2 = 0; - - /* "sklearn/cluster/_hierarchical.pyx":59 - * # elements is the list ourselves: len is a lengthy operation on a - * # chained list - * cdef int n_indices = 1 # <<<<<<<<<<<<<< - * cdef int i - * while n_indices: - */ - __pyx_v_n_indices = 1; - - /* "sklearn/cluster/_hierarchical.pyx":61 - * cdef int n_indices = 1 - * cdef int i - * while n_indices: # <<<<<<<<<<<<<< - * i = ind.pop() - * if i < n_leaves: - */ - while (1) { - if (!__pyx_v_n_indices) break; - - /* "sklearn/cluster/_hierarchical.pyx":62 - * cdef int i - * while n_indices: - * i = ind.pop() # <<<<<<<<<<<<<< - * if i < n_leaves: - * descendent.append(i) - */ - __pyx_t_2 = __Pyx_PyObject_Pop(((PyObject *)__pyx_v_ind)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyInt_AsInt(__pyx_t_2); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_i = __pyx_t_4; - - /* "sklearn/cluster/_hierarchical.pyx":63 - * while n_indices: - * i = ind.pop() - * if i < n_leaves: # <<<<<<<<<<<<<< - * descendent.append(i) - * n_indices -= 1 - */ - __pyx_t_3 = (__pyx_v_i < __pyx_v_n_leaves); - if (__pyx_t_3) { - - /* "sklearn/cluster/_hierarchical.pyx":64 - * i = ind.pop() - * if i < n_leaves: - * descendent.append(i) # <<<<<<<<<<<<<< - * n_indices -= 1 - * else: - */ - __pyx_t_2 = PyInt_FromLong(__pyx_v_i); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyList_Append(__pyx_v_descendent, __pyx_t_2); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "sklearn/cluster/_hierarchical.pyx":65 - * if i < n_leaves: - * descendent.append(i) - * n_indices -= 1 # <<<<<<<<<<<<<< - * else: - * ind.extend(children[i - n_leaves]) - */ - __pyx_v_n_indices = (__pyx_v_n_indices - 1); - goto __pyx_L6; - } - /*else*/ { - - /* "sklearn/cluster/_hierarchical.pyx":67 - * n_indices -= 1 - * else: - * ind.extend(children[i - n_leaves]) # <<<<<<<<<<<<<< - * n_indices += 1 - * return descendent - */ - __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_ind), __pyx_n_s__extend); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = (__pyx_v_i - __pyx_v_n_leaves); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_children, __pyx_t_4, sizeof(int), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "sklearn/cluster/_hierarchical.pyx":68 - * else: - * ind.extend(children[i - n_leaves]) - * n_indices += 1 # <<<<<<<<<<<<<< - * return descendent - * - */ - __pyx_v_n_indices = (__pyx_v_n_indices + 1); - } - __pyx_L6:; - } - - /* "sklearn/cluster/_hierarchical.pyx":69 - * ind.extend(children[i - n_leaves]) - * n_indices += 1 - * return descendent # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_descendent)); - __pyx_r = ((PyObject *)__pyx_v_descendent); - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("sklearn.cluster._hierarchical._hc_get_descendent", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_ind); - __Pyx_XDECREF(__pyx_v_descendent); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_5hc_get_heads(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_7cluster_13_hierarchical_4hc_get_heads[] = " Return the heads of the forest, as defined by parents\n \n Parameters\n ===========\n parents: array of integers\n The parent structure defining the forest (ensemble of trees)\n copy: boolean\n If copy is False, the input 'parents' array is modified inplace\n\n Returns\n =======\n heads: array of integers of same shape as parents\n The indices in the 'parents' of the tree heads\n\n "; -static PyMethodDef __pyx_mdef_7sklearn_7cluster_13_hierarchical_5hc_get_heads = {__Pyx_NAMESTR("hc_get_heads"), (PyCFunction)__pyx_pw_7sklearn_7cluster_13_hierarchical_5hc_get_heads, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_13_hierarchical_4hc_get_heads)}; -static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_5hc_get_heads(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_parents = 0; - PyObject *__pyx_v_copy = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("hc_get_heads (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__parents,&__pyx_n_s__copy,0}; - PyObject* values[2] = {0,0}; - values[1] = __pyx_k_1; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__parents)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__copy); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "hc_get_heads") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_parents = ((PyArrayObject *)values[0]); - __pyx_v_copy = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("hc_get_heads", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.cluster._hierarchical.hc_get_heads", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_parents), __pyx_ptype_5numpy_ndarray, 1, "parents", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_4hc_get_heads(__pyx_self, __pyx_v_parents, __pyx_v_copy); - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/cluster/_hierarchical.pyx":74 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * def hc_get_heads(np.ndarray[INT, ndim=1] parents, copy=True): # <<<<<<<<<<<<<< - * """ Return the heads of the forest, as defined by parents - * - */ - -static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_4hc_get_heads(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_parents, PyObject *__pyx_v_copy) { - unsigned int __pyx_v_parent; - unsigned int __pyx_v_node0; - unsigned int __pyx_v_node; - unsigned int __pyx_v_size; - __Pyx_LocalBuf_ND __pyx_pybuffernd_parents; - __Pyx_Buffer __pyx_pybuffer_parents; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyArrayObject *__pyx_t_5 = NULL; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - unsigned int __pyx_t_10; - unsigned int __pyx_t_11; - unsigned int __pyx_t_12; - unsigned int __pyx_t_13; - unsigned int __pyx_t_14; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("hc_get_heads", 0); - __Pyx_INCREF((PyObject *)__pyx_v_parents); - __pyx_pybuffer_parents.pybuffer.buf = NULL; - __pyx_pybuffer_parents.refcount = 0; - __pyx_pybuffernd_parents.data = NULL; - __pyx_pybuffernd_parents.rcbuffer = &__pyx_pybuffer_parents; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_parents.rcbuffer->pybuffer, (PyObject*)__pyx_v_parents, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INT, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_pybuffernd_parents.diminfo[0].strides = __pyx_pybuffernd_parents.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_parents.diminfo[0].shape = __pyx_pybuffernd_parents.rcbuffer->pybuffer.shape[0]; - - /* "sklearn/cluster/_hierarchical.pyx":91 - * """ - * cdef unsigned int parent, node0, node, size - * if copy: # <<<<<<<<<<<<<< - * parents = np.copy(parents) - * size = parents.size - */ - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_copy); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_1) { - - /* "sklearn/cluster/_hierarchical.pyx":92 - * cdef unsigned int parent, node0, node, size - * if copy: - * parents = np.copy(parents) # <<<<<<<<<<<<<< - * size = parents.size - * for node0 in range(size): - */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__copy); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_v_parents)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_parents)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_parents)); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = ((PyArrayObject *)__pyx_t_4); - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_parents.rcbuffer->pybuffer); - __pyx_t_6 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_parents.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INT, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); - if (unlikely(__pyx_t_6 < 0)) { - PyErr_Fetch(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_parents.rcbuffer->pybuffer, (PyObject*)__pyx_v_parents, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INT, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - Py_XDECREF(__pyx_t_7); Py_XDECREF(__pyx_t_8); Py_XDECREF(__pyx_t_9); - __Pyx_RaiseBufferFallbackError(); - } else { - PyErr_Restore(__pyx_t_7, __pyx_t_8, __pyx_t_9); - } - } - __pyx_pybuffernd_parents.diminfo[0].strides = __pyx_pybuffernd_parents.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_parents.diminfo[0].shape = __pyx_pybuffernd_parents.rcbuffer->pybuffer.shape[0]; - if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_v_parents)); - __pyx_v_parents = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "sklearn/cluster/_hierarchical.pyx":93 - * if copy: - * parents = np.copy(parents) - * size = parents.size # <<<<<<<<<<<<<< - * for node0 in range(size): - * # Start from the top of the tree and go down - */ - __pyx_t_4 = PyObject_GetAttr(((PyObject *)__pyx_v_parents), __pyx_n_s__size); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_10 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_4); if (unlikely((__pyx_t_10 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_size = __pyx_t_10; - - /* "sklearn/cluster/_hierarchical.pyx":94 - * parents = np.copy(parents) - * size = parents.size - * for node0 in range(size): # <<<<<<<<<<<<<< - * # Start from the top of the tree and go down - * node0 = size - node0 - 1 - */ - __pyx_t_10 = __pyx_v_size; - for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) { - __pyx_v_node0 = __pyx_t_11; - - /* "sklearn/cluster/_hierarchical.pyx":96 - * for node0 in range(size): - * # Start from the top of the tree and go down - * node0 = size - node0 - 1 # <<<<<<<<<<<<<< - * node = node0 - * parent = parents[node] - */ - __pyx_v_node0 = ((__pyx_v_size - __pyx_v_node0) - 1); - - /* "sklearn/cluster/_hierarchical.pyx":97 - * # Start from the top of the tree and go down - * node0 = size - node0 - 1 - * node = node0 # <<<<<<<<<<<<<< - * parent = parents[node] - * while parent != node: - */ - __pyx_v_node = __pyx_v_node0; - - /* "sklearn/cluster/_hierarchical.pyx":98 - * node0 = size - node0 - 1 - * node = node0 - * parent = parents[node] # <<<<<<<<<<<<<< - * while parent != node: - * parents[node0] = parent - */ - __pyx_t_12 = __pyx_v_node; - __pyx_v_parent = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INT *, __pyx_pybuffernd_parents.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_parents.diminfo[0].strides)); - - /* "sklearn/cluster/_hierarchical.pyx":99 - * node = node0 - * parent = parents[node] - * while parent != node: # <<<<<<<<<<<<<< - * parents[node0] = parent - * node = parent - */ - while (1) { - __pyx_t_1 = (__pyx_v_parent != __pyx_v_node); - if (!__pyx_t_1) break; - - /* "sklearn/cluster/_hierarchical.pyx":100 - * parent = parents[node] - * while parent != node: - * parents[node0] = parent # <<<<<<<<<<<<<< - * node = parent - * parent = parents[node] - */ - __pyx_t_13 = __pyx_v_node0; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INT *, __pyx_pybuffernd_parents.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_parents.diminfo[0].strides) = __pyx_v_parent; - - /* "sklearn/cluster/_hierarchical.pyx":101 - * while parent != node: - * parents[node0] = parent - * node = parent # <<<<<<<<<<<<<< - * parent = parents[node] - * return parents - */ - __pyx_v_node = __pyx_v_parent; - - /* "sklearn/cluster/_hierarchical.pyx":102 - * parents[node0] = parent - * node = parent - * parent = parents[node] # <<<<<<<<<<<<<< - * return parents - * - */ - __pyx_t_14 = __pyx_v_node; - __pyx_v_parent = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INT *, __pyx_pybuffernd_parents.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_parents.diminfo[0].strides)); - } - } - - /* "sklearn/cluster/_hierarchical.pyx":103 - * node = parent - * parent = parents[node] - * return parents # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_parents)); - __pyx_r = ((PyObject *)__pyx_v_parents); - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_parents.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.cluster._hierarchical.hc_get_heads", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_parents.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_parents); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_7_get_parents(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_7cluster_13_hierarchical_6_get_parents[] = " Return the heads of the given nodes, as defined by parents\n \n Modifies in-place 'heads' and 'not_visited'\n\n Parameters\n ===========\n nodes: list of integers\n The nodes to start from\n heads: list of integers\n A list to hold the results (modified inplace)\n parents: array of integers\n The parent structure defining the tree\n not_visited:\n The tree nodes to consider (modified inplace)\n\n "; -static PyMethodDef __pyx_mdef_7sklearn_7cluster_13_hierarchical_7_get_parents = {__Pyx_NAMESTR("_get_parents"), (PyCFunction)__pyx_pw_7sklearn_7cluster_13_hierarchical_7_get_parents, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7cluster_13_hierarchical_6_get_parents)}; -static PyObject *__pyx_pw_7sklearn_7cluster_13_hierarchical_7_get_parents(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_nodes = 0; - PyObject *__pyx_v_heads = 0; - PyArrayObject *__pyx_v_parents = 0; - PyArrayObject *__pyx_v_not_visited = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_get_parents (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__nodes,&__pyx_n_s__heads,&__pyx_n_s__parents,&__pyx_n_s__not_visited,0}; - PyObject* values[4] = {0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nodes)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__heads)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_get_parents", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__parents)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_get_parents", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 3: - if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__not_visited)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_get_parents", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_get_parents") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - } - __pyx_v_nodes = values[0]; - __pyx_v_heads = values[1]; - __pyx_v_parents = ((PyArrayObject *)values[2]); - __pyx_v_not_visited = ((PyArrayObject *)values[3]); - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_get_parents", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.cluster._hierarchical._get_parents", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_parents), __pyx_ptype_5numpy_ndarray, 1, "parents", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_not_visited), __pyx_ptype_5numpy_ndarray, 1, "not_visited", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7sklearn_7cluster_13_hierarchical_6_get_parents(__pyx_self, __pyx_v_nodes, __pyx_v_heads, __pyx_v_parents, __pyx_v_not_visited); - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "sklearn/cluster/_hierarchical.pyx":108 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * def _get_parents(nodes, heads, np.ndarray[INT, ndim=1] parents, # <<<<<<<<<<<<<< - * np.ndarray[INT8, ndim=1] not_visited): - * """ Return the heads of the given nodes, as defined by parents - */ - -static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_6_get_parents(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_nodes, PyObject *__pyx_v_heads, PyArrayObject *__pyx_v_parents, PyArrayObject *__pyx_v_not_visited) { - unsigned int __pyx_v_parent; - unsigned int __pyx_v_node; - __Pyx_LocalBuf_ND __pyx_pybuffernd_not_visited; - __Pyx_Buffer __pyx_pybuffer_not_visited; - __Pyx_LocalBuf_ND __pyx_pybuffernd_parents; - __Pyx_Buffer __pyx_pybuffer_parents; +static PyObject *__pyx_pf_7sklearn_5utils_17_logistic_sigmoid__log_logistic_sigmoid(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_n_samples, int __pyx_v_n_features, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_out) { + int __pyx_v_i; + int __pyx_v_j; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_LocalBuf_ND __pyx_pybuffernd_out; + __Pyx_Buffer __pyx_pybuffer_out; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *(*__pyx_t_3)(PyObject *); - PyObject *__pyx_t_4 = NULL; - unsigned int __pyx_t_5; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; int __pyx_t_6; - unsigned int __pyx_t_7; - unsigned int __pyx_t_8; - __pyx_t_7sklearn_7cluster_13_hierarchical_INT8 __pyx_t_9; - unsigned int __pyx_t_10; - PyObject *__pyx_t_11 = NULL; + int __pyx_t_7; + int __pyx_t_8; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_get_parents", 0); - __pyx_pybuffer_parents.pybuffer.buf = NULL; - __pyx_pybuffer_parents.refcount = 0; - __pyx_pybuffernd_parents.data = NULL; - __pyx_pybuffernd_parents.rcbuffer = &__pyx_pybuffer_parents; - __pyx_pybuffer_not_visited.pybuffer.buf = NULL; - __pyx_pybuffer_not_visited.refcount = 0; - __pyx_pybuffernd_not_visited.data = NULL; - __pyx_pybuffernd_not_visited.rcbuffer = &__pyx_pybuffer_not_visited; + __Pyx_RefNannySetupContext("_log_logistic_sigmoid", 0); + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + __pyx_pybuffer_out.pybuffer.buf = NULL; + __pyx_pybuffer_out.refcount = 0; + __pyx_pybuffernd_out.data = NULL; + __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_parents.rcbuffer->pybuffer, (PyObject*)__pyx_v_parents, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INT, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_pybuffernd_parents.diminfo[0].strides = __pyx_pybuffernd_parents.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_parents.diminfo[0].shape = __pyx_pybuffernd_parents.rcbuffer->pybuffer.shape[0]; + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_not_visited.rcbuffer->pybuffer, (PyObject*)__pyx_v_not_visited, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_7cluster_13_hierarchical_INT8, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_v_out, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_pybuffernd_not_visited.diminfo[0].strides = __pyx_pybuffernd_not_visited.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_not_visited.diminfo[0].shape = __pyx_pybuffernd_not_visited.rcbuffer->pybuffer.shape[0]; - - /* "sklearn/cluster/_hierarchical.pyx":127 - * """ - * cdef unsigned int parent, node - * for node in nodes: # <<<<<<<<<<<<<< - * parent = parents[node] - * while parent != node: - */ - if (PyList_CheckExact(__pyx_v_nodes) || PyTuple_CheckExact(__pyx_v_nodes)) { - __pyx_t_1 = __pyx_v_nodes; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - __pyx_t_3 = NULL; - } else { - __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_nodes); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = Py_TYPE(__pyx_t_1)->tp_iternext; - } - for (;;) { - if (!__pyx_t_3 && PyList_CheckExact(__pyx_t_1)) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #endif - } else if (!__pyx_t_3 && PyTuple_CheckExact(__pyx_t_1)) { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #endif - } else { - __pyx_t_4 = __pyx_t_3(__pyx_t_1); - if (unlikely(!__pyx_t_4)) { - if (PyErr_Occurred()) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_4); - } - __pyx_t_5 = __Pyx_PyInt_AsUnsignedInt(__pyx_t_4); if (unlikely((__pyx_t_5 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_node = __pyx_t_5; + __pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_out.diminfo[1].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_out.diminfo[1].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[1]; - /* "sklearn/cluster/_hierarchical.pyx":128 - * cdef unsigned int parent, node - * for node in nodes: - * parent = parents[node] # <<<<<<<<<<<<<< - * while parent != node: - * node = parent + /* "sklearn/utils/_logistic_sigmoid.pyx":24 + * np.ndarray[DTYPE_t, ndim=2] X, + * np.ndarray[DTYPE_t, ndim=2] out): + * for i in range(n_samples): # <<<<<<<<<<<<<< + * for j in range(n_features): + * out[i, j] = _inner_log_logistic_sigmoid(X[i, j]) */ - __pyx_t_5 = __pyx_v_node; - __pyx_v_parent = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INT *, __pyx_pybuffernd_parents.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_parents.diminfo[0].strides)); + __pyx_t_1 = __pyx_v_n_samples; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; - /* "sklearn/cluster/_hierarchical.pyx":129 - * for node in nodes: - * parent = parents[node] - * while parent != node: # <<<<<<<<<<<<<< - * node = parent - * parent = parents[node] + /* "sklearn/utils/_logistic_sigmoid.pyx":25 + * np.ndarray[DTYPE_t, ndim=2] out): + * for i in range(n_samples): + * for j in range(n_features): # <<<<<<<<<<<<<< + * out[i, j] = _inner_log_logistic_sigmoid(X[i, j]) + * return out */ - while (1) { - __pyx_t_6 = (__pyx_v_parent != __pyx_v_node); - if (!__pyx_t_6) break; - - /* "sklearn/cluster/_hierarchical.pyx":130 - * parent = parents[node] - * while parent != node: - * node = parent # <<<<<<<<<<<<<< - * parent = parents[node] - * if not_visited[node]: - */ - __pyx_v_node = __pyx_v_parent; - - /* "sklearn/cluster/_hierarchical.pyx":131 - * while parent != node: - * node = parent - * parent = parents[node] # <<<<<<<<<<<<<< - * if not_visited[node]: - * not_visited[node] = 0 - */ - __pyx_t_7 = __pyx_v_node; - __pyx_v_parent = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INT *, __pyx_pybuffernd_parents.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_parents.diminfo[0].strides)); - } + __pyx_t_3 = __pyx_v_n_features; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_j = __pyx_t_4; - /* "sklearn/cluster/_hierarchical.pyx":132 - * node = parent - * parent = parents[node] - * if not_visited[node]: # <<<<<<<<<<<<<< - * not_visited[node] = 0 - * heads.append(node) - */ - __pyx_t_8 = __pyx_v_node; - __pyx_t_9 = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INT8 *, __pyx_pybuffernd_not_visited.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_not_visited.diminfo[0].strides)); - if (__pyx_t_9) { - - /* "sklearn/cluster/_hierarchical.pyx":133 - * parent = parents[node] - * if not_visited[node]: - * not_visited[node] = 0 # <<<<<<<<<<<<<< - * heads.append(node) - * return heads - */ - __pyx_t_10 = __pyx_v_node; - *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_7cluster_13_hierarchical_INT8 *, __pyx_pybuffernd_not_visited.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_not_visited.diminfo[0].strides) = 0; - - /* "sklearn/cluster/_hierarchical.pyx":134 - * if not_visited[node]: - * not_visited[node] = 0 - * heads.append(node) # <<<<<<<<<<<<<< - * return heads - */ - __pyx_t_4 = PyLong_FromUnsignedLong(__pyx_v_node); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_11 = __Pyx_PyObject_Append(__pyx_v_heads, __pyx_t_4); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - goto __pyx_L7; + /* "sklearn/utils/_logistic_sigmoid.pyx":26 + * for i in range(n_samples): + * for j in range(n_features): + * out[i, j] = _inner_log_logistic_sigmoid(X[i, j]) # <<<<<<<<<<<<<< + * return out + */ + __pyx_t_5 = __pyx_v_i; + __pyx_t_6 = __pyx_v_j; + __pyx_t_7 = __pyx_v_i; + __pyx_t_8 = __pyx_v_j; + *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t *, __pyx_pybuffernd_out.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_out.diminfo[0].strides, __pyx_t_8, __pyx_pybuffernd_out.diminfo[1].strides) = __pyx_f_7sklearn_5utils_17_logistic_sigmoid__inner_log_logistic_sigmoid((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_17_logistic_sigmoid_DTYPE_t *, __pyx_pybuffernd_X.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_X.diminfo[0].strides, __pyx_t_6, __pyx_pybuffernd_X.diminfo[1].strides))); } - __pyx_L7:; } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/cluster/_hierarchical.pyx":135 - * not_visited[node] = 0 - * heads.append(node) - * return heads # <<<<<<<<<<<<<< + /* "sklearn/utils/_logistic_sigmoid.pyx":27 + * for j in range(n_features): + * out[i, j] = _inner_log_logistic_sigmoid(X[i, j]) + * return out # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_heads); - __pyx_r = __pyx_v_heads; + __Pyx_INCREF(((PyObject *)__pyx_v_out)); + __pyx_r = ((PyObject *)__pyx_v_out); goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_11); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_not_visited.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_parents.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("sklearn.cluster._hierarchical._get_parents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.utils._logistic_sigmoid._log_logistic_sigmoid", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_not_visited.rcbuffer->pybuffer); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_parents.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); @@ -2462,8 +1459,8 @@ static PyObject *__pyx_pf_7sklearn_7cluster_13_hierarchical_6_get_parents(CYTHON } /* Python wrapper */ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); @@ -2472,7 +1469,7 @@ static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_bu return __pyx_r; } -/* "numpy.pxd":193 +/* "numpy.pxd":194 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< @@ -2511,7 +1508,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":199 + /* "numpy.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< @@ -2526,7 +1523,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } __pyx_L3:; - /* "numpy.pxd":202 + /* "numpy.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -2535,7 +1532,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":203 + /* "numpy.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -2544,7 +1541,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":205 + /* "numpy.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< @@ -2553,7 +1550,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":207 + /* "numpy.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< @@ -2563,7 +1560,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_t_1) { - /* "numpy.pxd":208 + /* "numpy.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -2575,7 +1572,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /*else*/ { - /* "numpy.pxd":210 + /* "numpy.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -2586,7 +1583,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } __pyx_L4:; - /* "numpy.pxd":212 + /* "numpy.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< @@ -2596,7 +1593,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); if (__pyx_t_1) { - /* "numpy.pxd":213 + /* "numpy.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< @@ -2610,23 +1607,23 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } if (__pyx_t_3) { - /* "numpy.pxd":214 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; - /* "numpy.pxd":216 + /* "numpy.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< @@ -2636,7 +1633,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); if (__pyx_t_3) { - /* "numpy.pxd":217 + /* "numpy.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< @@ -2650,23 +1647,23 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } if (__pyx_t_2) { - /* "numpy.pxd":218 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; - /* "numpy.pxd":220 + /* "numpy.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< @@ -2675,7 +1672,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":221 + /* "numpy.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -2684,7 +1681,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":222 + /* "numpy.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< @@ -2693,7 +1690,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ if (__pyx_v_copy_shape) { - /* "numpy.pxd":225 + /* "numpy.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -2702,7 +1699,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":226 + /* "numpy.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -2711,7 +1708,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":227 + /* "numpy.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< @@ -2722,7 +1719,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "numpy.pxd":228 + /* "numpy.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< @@ -2731,7 +1728,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":229 + /* "numpy.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< @@ -2744,7 +1741,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /*else*/ { - /* "numpy.pxd":231 + /* "numpy.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< @@ -2753,7 +1750,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":232 + /* "numpy.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< @@ -2764,7 +1761,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } __pyx_L7:; - /* "numpy.pxd":233 + /* "numpy.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -2773,7 +1770,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":234 + /* "numpy.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< @@ -2782,7 +1779,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":235 + /* "numpy.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< @@ -2791,7 +1788,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); - /* "numpy.pxd":238 + /* "numpy.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -2800,17 +1797,19 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_f = NULL; - /* "numpy.pxd":239 + /* "numpy.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)__pyx_v_self->descr)); - __pyx_v_descr = __pyx_v_self->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":243 + /* "numpy.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -2819,7 +1818,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":245 + /* "numpy.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< @@ -2835,7 +1834,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } if (__pyx_t_1) { - /* "numpy.pxd":247 + /* "numpy.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -2851,7 +1850,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /*else*/ { - /* "numpy.pxd":250 + /* "numpy.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< @@ -2866,7 +1865,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } __pyx_L10:; - /* "numpy.pxd":252 + /* "numpy.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< @@ -2876,16 +1875,17 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P __pyx_t_1 = (!__pyx_v_hasfields); if (__pyx_t_1) { - /* "numpy.pxd":253 + /* "numpy.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; - /* "numpy.pxd":254 + /* "numpy.pxd":255 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< @@ -2900,7 +1900,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } if (!__pyx_t_2) { - /* "numpy.pxd":255 + /* "numpy.pxd":256 * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< @@ -2920,271 +1920,246 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } if (__pyx_t_1) { - /* "numpy.pxd":256 + /* "numpy.pxd":257 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_7), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L12; } __pyx_L12:; - /* "numpy.pxd":257 + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "numpy.pxd":258 * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { + case NPY_BYTE: __pyx_v_f = __pyx_k__b; - goto __pyx_L13; - } + break; - /* "numpy.pxd":258 + /* "numpy.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { + case NPY_UBYTE: __pyx_v_f = __pyx_k__B; - goto __pyx_L13; - } + break; - /* "numpy.pxd":259 + /* "numpy.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { + case NPY_SHORT: __pyx_v_f = __pyx_k__h; - goto __pyx_L13; - } + break; - /* "numpy.pxd":260 + /* "numpy.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { + case NPY_USHORT: __pyx_v_f = __pyx_k__H; - goto __pyx_L13; - } + break; - /* "numpy.pxd":261 + /* "numpy.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { + case NPY_INT: __pyx_v_f = __pyx_k__i; - goto __pyx_L13; - } + break; - /* "numpy.pxd":262 + /* "numpy.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { + case NPY_UINT: __pyx_v_f = __pyx_k__I; - goto __pyx_L13; - } + break; - /* "numpy.pxd":263 + /* "numpy.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { + case NPY_LONG: __pyx_v_f = __pyx_k__l; - goto __pyx_L13; - } + break; - /* "numpy.pxd":264 + /* "numpy.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { + case NPY_ULONG: __pyx_v_f = __pyx_k__L; - goto __pyx_L13; - } + break; - /* "numpy.pxd":265 + /* "numpy.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { + case NPY_LONGLONG: __pyx_v_f = __pyx_k__q; - goto __pyx_L13; - } + break; - /* "numpy.pxd":266 + /* "numpy.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { + case NPY_ULONGLONG: __pyx_v_f = __pyx_k__Q; - goto __pyx_L13; - } + break; - /* "numpy.pxd":267 + /* "numpy.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { + case NPY_FLOAT: __pyx_v_f = __pyx_k__f; - goto __pyx_L13; - } + break; - /* "numpy.pxd":268 + /* "numpy.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { + case NPY_DOUBLE: __pyx_v_f = __pyx_k__d; - goto __pyx_L13; - } + break; - /* "numpy.pxd":269 + /* "numpy.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { + case NPY_LONGDOUBLE: __pyx_v_f = __pyx_k__g; - goto __pyx_L13; - } + break; - /* "numpy.pxd":270 + /* "numpy.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { + case NPY_CFLOAT: __pyx_v_f = __pyx_k__Zf; - goto __pyx_L13; - } + break; - /* "numpy.pxd":271 + /* "numpy.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { + case NPY_CDOUBLE: __pyx_v_f = __pyx_k__Zd; - goto __pyx_L13; - } + break; - /* "numpy.pxd":272 + /* "numpy.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { + case NPY_CLONGDOUBLE: __pyx_v_f = __pyx_k__Zg; - goto __pyx_L13; - } + break; - /* "numpy.pxd":273 + /* "numpy.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { + case NPY_OBJECT: __pyx_v_f = __pyx_k__O; - goto __pyx_L13; - } - /*else*/ { + break; + default: - /* "numpy.pxd":275 + /* "numpy.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_8), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_8)); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L13:; - /* "numpy.pxd":276 + /* "numpy.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -3193,7 +2168,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":277 + /* "numpy.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -3206,7 +2181,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /*else*/ { - /* "numpy.pxd":279 + /* "numpy.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< @@ -3215,7 +2190,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":280 + /* "numpy.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< @@ -3224,7 +2199,7 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":281 + /* "numpy.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< @@ -3233,17 +2208,17 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P */ __pyx_v_offset = 0; - /* "numpy.pxd":284 + /* "numpy.pxd":285 * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, * &offset) # <<<<<<<<<<<<<< * f[0] = c'\0' # Terminate format string * */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; - /* "numpy.pxd":285 + /* "numpy.pxd":286 * info.format + _buffer_format_string_len, * &offset) * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< @@ -3278,15 +2253,15 @@ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, P } /* Python wrapper */ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":287 +/* "numpy.pxd":288 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< @@ -3299,7 +2274,7 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s int __pyx_t_1; __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":288 + /* "numpy.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< @@ -3309,7 +2284,7 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); if (__pyx_t_1) { - /* "numpy.pxd":289 + /* "numpy.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -3321,7 +2296,7 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s } __pyx_L3:; - /* "numpy.pxd":290 + /* "numpy.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< @@ -3331,7 +2306,7 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_t_1) { - /* "numpy.pxd":291 + /* "numpy.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -3346,7 +2321,7 @@ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_s __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":767 +/* "numpy.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -3363,7 +2338,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":768 + /* "numpy.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -3371,7 +2346,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3389,7 +2364,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "numpy.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -3406,7 +2381,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":771 + /* "numpy.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -3414,7 +2389,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3432,7 +2407,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "numpy.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -3449,7 +2424,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":774 + /* "numpy.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -3457,7 +2432,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3475,7 +2450,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "numpy.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -3492,7 +2467,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":777 + /* "numpy.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -3500,7 +2475,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3518,7 +2493,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "numpy.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -3535,7 +2510,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":780 + /* "numpy.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -3543,7 +2518,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3561,7 +2536,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":782 +/* "numpy.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -3596,7 +2571,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":789 + /* "numpy.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -3605,7 +2580,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":790 + /* "numpy.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -3614,7 +2589,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":793 + /* "numpy.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< @@ -3623,35 +2598,35 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif __Pyx_XDECREF(__pyx_v_childname); __pyx_v_childname = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":794 + /* "numpy.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); __pyx_v_fields = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":795 + /* "numpy.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< @@ -3668,7 +2643,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); @@ -3676,22 +2651,24 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); #endif } else if (1) { - __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } else { Py_ssize_t index = -1; - __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; __Pyx_GOTREF(__pyx_t_3); index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; __Pyx_GOTREF(__pyx_t_4); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = NULL; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; goto __pyx_L6_unpacking_done; @@ -3699,10 +2676,10 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = NULL; if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_L6_unpacking_done:; } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_child)); __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; @@ -3710,48 +2687,47 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_v_new_offset = __pyx_t_4; __pyx_t_4 = 0; - /* "numpy.pxd":797 + /* "numpy.pxd":798 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { - /* "numpy.pxd":798 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; - /* "numpy.pxd":800 + /* "numpy.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< @@ -3766,7 +2742,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } if (!__pyx_t_8) { - /* "numpy.pxd":801 + /* "numpy.pxd":802 * * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< @@ -3786,23 +2762,23 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } if (__pyx_t_7) { - /* "numpy.pxd":802 + /* "numpy.pxd":803 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L8; } __pyx_L8:; - /* "numpy.pxd":812 + /* "numpy.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -3810,16 +2786,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!__pyx_t_7) break; - /* "numpy.pxd":813 + /* "numpy.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -3828,7 +2803,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":814 + /* "numpy.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -3837,7 +2812,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":815 + /* "numpy.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< @@ -3848,7 +2823,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); } - /* "numpy.pxd":817 + /* "numpy.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< @@ -3858,7 +2833,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_t_11 = 0; (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); - /* "numpy.pxd":819 + /* "numpy.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< @@ -3868,20 +2843,20 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_t_7 = (!PyDataType_HASFIELDS(__pyx_v_child)); if (__pyx_t_7) { - /* "numpy.pxd":820 + /* "numpy.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 820; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XDECREF(__pyx_v_t); __pyx_v_t = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":821 + /* "numpy.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< @@ -3891,282 +2866,268 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_t_7 = ((__pyx_v_end - __pyx_v_f) < 5); if (__pyx_t_7) { - /* "numpy.pxd":822 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_13), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L12; } __pyx_L12:; - /* "numpy.pxd":825 + /* "numpy.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 98; goto __pyx_L13; } - /* "numpy.pxd":826 + /* "numpy.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 66; goto __pyx_L13; } - /* "numpy.pxd":827 + /* "numpy.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 104; goto __pyx_L13; } - /* "numpy.pxd":828 + /* "numpy.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 72; goto __pyx_L13; } - /* "numpy.pxd":829 + /* "numpy.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 105; goto __pyx_L13; } - /* "numpy.pxd":830 + /* "numpy.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 73; goto __pyx_L13; } - /* "numpy.pxd":831 + /* "numpy.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 108; goto __pyx_L13; } - /* "numpy.pxd":832 + /* "numpy.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 76; goto __pyx_L13; } - /* "numpy.pxd":833 + /* "numpy.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 113; goto __pyx_L13; } - /* "numpy.pxd":834 + /* "numpy.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 81; goto __pyx_L13; } - /* "numpy.pxd":835 + /* "numpy.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 102; goto __pyx_L13; } - /* "numpy.pxd":836 + /* "numpy.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 100; goto __pyx_L13; } - /* "numpy.pxd":837 + /* "numpy.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 103; goto __pyx_L13; } - /* "numpy.pxd":838 + /* "numpy.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 90; @@ -4175,19 +3136,18 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L13; } - /* "numpy.pxd":839 + /* "numpy.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 90; @@ -4196,19 +3156,18 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L13; } - /* "numpy.pxd":840 + /* "numpy.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 90; @@ -4217,19 +3176,18 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L13; } - /* "numpy.pxd":841 + /* "numpy.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_7) { (__pyx_v_f[0]) = 79; @@ -4237,30 +3195,30 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } /*else*/ { - /* "numpy.pxd":843 + /* "numpy.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_8), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L13:; - /* "numpy.pxd":844 + /* "numpy.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -4272,21 +3230,21 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } /*else*/ { - /* "numpy.pxd":848 + /* "numpy.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 848; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_12; } __pyx_L11:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":849 + /* "numpy.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -4315,7 +3273,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":964 +/* "numpy.pxd":965 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -4329,7 +3287,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a int __pyx_t_1; __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":966 + /* "numpy.pxd":967 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -4339,7 +3297,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a __pyx_t_1 = (__pyx_v_base == Py_None); if (__pyx_t_1) { - /* "numpy.pxd":967 + /* "numpy.pxd":968 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -4351,7 +3309,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":969 + /* "numpy.pxd":970 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -4360,7 +3318,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":970 + /* "numpy.pxd":971 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -4371,7 +3329,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":971 + /* "numpy.pxd":972 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -4380,7 +3338,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":972 + /* "numpy.pxd":973 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -4392,7 +3350,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":974 +/* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -4406,7 +3364,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":975 + /* "numpy.pxd":976 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< @@ -4416,7 +3374,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __pyx_t_1 = (__pyx_v_arr->base == NULL); if (__pyx_t_1) { - /* "numpy.pxd":976 + /* "numpy.pxd":977 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -4431,7 +3389,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py } /*else*/ { - /* "numpy.pxd":978 + /* "numpy.pxd":979 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -4456,8 +3414,12 @@ static PyMethodDef __pyx_methods[] = { #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else PyModuleDef_HEAD_INIT, - __Pyx_NAMESTR("_hierarchical"), + #endif + __Pyx_NAMESTR("_logistic_sigmoid"), 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, @@ -4469,59 +3431,37 @@ static struct PyModuleDef __pyx_moduledef = { #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_u_12, __pyx_k_12, sizeof(__pyx_k_12), 0, 1, 0, 0}, + {&__pyx_kp_u_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 1, 0, 0}, + {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, + {&__pyx_n_s_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 0, 1, 1}, {&__pyx_kp_s_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 1, 0}, {&__pyx_n_s_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 0, 1, 1}, - {&__pyx_kp_u_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 1, 0, 0}, - {&__pyx_kp_u_4, __pyx_k_4, sizeof(__pyx_k_4), 0, 1, 0, 0}, - {&__pyx_kp_u_6, __pyx_k_6, sizeof(__pyx_k_6), 0, 1, 0, 0}, + {&__pyx_kp_u_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 1, 0, 0}, + {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, + {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, - {&__pyx_kp_u_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 1, 0, 0}, {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, + {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, + {&__pyx_n_s____import__, __pyx_k____import__, sizeof(__pyx_k____import__), 0, 0, 1, 1}, {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_getbuffer, __pyx_k____pyx_getbuffer, sizeof(__pyx_k____pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_releasebuffer, __pyx_k____pyx_releasebuffer, sizeof(__pyx_k____pyx_releasebuffer), 0, 0, 1, 1}, {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s___get_parents, __pyx_k___get_parents, sizeof(__pyx_k___get_parents), 0, 0, 1, 1}, - {&__pyx_n_s___hc_get_descendent, __pyx_k___hc_get_descendent, sizeof(__pyx_k___hc_get_descendent), 0, 0, 1, 1}, - {&__pyx_n_s__children, __pyx_k__children, sizeof(__pyx_k__children), 0, 0, 1, 1}, - {&__pyx_n_s__col, __pyx_k__col, sizeof(__pyx_k__col), 0, 0, 1, 1}, - {&__pyx_n_s__compute_ward_dist, __pyx_k__compute_ward_dist, sizeof(__pyx_k__compute_ward_dist), 0, 0, 1, 1}, - {&__pyx_n_s__coord_col, __pyx_k__coord_col, sizeof(__pyx_k__coord_col), 0, 0, 1, 1}, - {&__pyx_n_s__coord_row, __pyx_k__coord_row, sizeof(__pyx_k__coord_row), 0, 0, 1, 1}, - {&__pyx_n_s__copy, __pyx_k__copy, sizeof(__pyx_k__copy), 0, 0, 1, 1}, - {&__pyx_n_s__descendent, __pyx_k__descendent, sizeof(__pyx_k__descendent), 0, 0, 1, 1}, - {&__pyx_n_s__extend, __pyx_k__extend, sizeof(__pyx_k__extend), 0, 0, 1, 1}, - {&__pyx_n_s__hc_get_heads, __pyx_k__hc_get_heads, sizeof(__pyx_k__hc_get_heads), 0, 0, 1, 1}, - {&__pyx_n_s__heads, __pyx_k__heads, sizeof(__pyx_k__heads), 0, 0, 1, 1}, {&__pyx_n_s__i, __pyx_k__i, sizeof(__pyx_k__i), 0, 0, 1, 1}, - {&__pyx_n_s__ind, __pyx_k__ind, sizeof(__pyx_k__ind), 0, 0, 1, 1}, {&__pyx_n_s__j, __pyx_k__j, sizeof(__pyx_k__j), 0, 0, 1, 1}, - {&__pyx_n_s__m_1, __pyx_k__m_1, sizeof(__pyx_k__m_1), 0, 0, 1, 1}, - {&__pyx_n_s__m_2, __pyx_k__m_2, sizeof(__pyx_k__m_2), 0, 0, 1, 1}, - {&__pyx_n_s__n, __pyx_k__n, sizeof(__pyx_k__n), 0, 0, 1, 1}, {&__pyx_n_s__n_features, __pyx_k__n_features, sizeof(__pyx_k__n_features), 0, 0, 1, 1}, - {&__pyx_n_s__n_indices, __pyx_k__n_indices, sizeof(__pyx_k__n_indices), 0, 0, 1, 1}, - {&__pyx_n_s__n_leaves, __pyx_k__n_leaves, sizeof(__pyx_k__n_leaves), 0, 0, 1, 1}, - {&__pyx_n_s__node, __pyx_k__node, sizeof(__pyx_k__node), 0, 0, 1, 1}, - {&__pyx_n_s__node0, __pyx_k__node0, sizeof(__pyx_k__node0), 0, 0, 1, 1}, - {&__pyx_n_s__nodes, __pyx_k__nodes, sizeof(__pyx_k__nodes), 0, 0, 1, 1}, - {&__pyx_n_s__not_visited, __pyx_k__not_visited, sizeof(__pyx_k__not_visited), 0, 0, 1, 1}, + {&__pyx_n_s__n_samples, __pyx_k__n_samples, sizeof(__pyx_k__n_samples), 0, 0, 1, 1}, {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__pa, __pyx_k__pa, sizeof(__pyx_k__pa), 0, 0, 1, 1}, - {&__pyx_n_s__parent, __pyx_k__parent, sizeof(__pyx_k__parent), 0, 0, 1, 1}, - {&__pyx_n_s__parents, __pyx_k__parents, sizeof(__pyx_k__parents), 0, 0, 1, 1}, + {&__pyx_n_s__out, __pyx_k__out, sizeof(__pyx_k__out), 0, 0, 1, 1}, {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__res, __pyx_k__res, sizeof(__pyx_k__res), 0, 0, 1, 1}, - {&__pyx_n_s__row, __pyx_k__row, sizeof(__pyx_k__row), 0, 0, 1, 1}, - {&__pyx_n_s__size, __pyx_k__size, sizeof(__pyx_k__size), 0, 0, 1, 1}, - {&__pyx_n_s__size_max, __pyx_k__size_max, sizeof(__pyx_k__size_max), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -4531,233 +3471,83 @@ static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "numpy.pxd":214 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_3 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_3); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_2)); - PyTuple_SET_ITEM(__pyx_k_tuple_3, 0, ((PyObject *)__pyx_kp_u_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_3)); + __pyx_k_tuple_2 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_1)); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_2); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); - /* "numpy.pxd":218 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_5 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_5); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_4)); - PyTuple_SET_ITEM(__pyx_k_tuple_5, 0, ((PyObject *)__pyx_kp_u_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_4)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); + __pyx_k_tuple_4 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_3)); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_4); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); - /* "numpy.pxd":256 + /* "numpy.pxd":257 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_7 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_7); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_6)); - PyTuple_SET_ITEM(__pyx_k_tuple_7, 0, ((PyObject *)__pyx_kp_u_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); + __pyx_k_tuple_6 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_5)); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_6); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); - /* "numpy.pxd":798 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_10); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_9)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + __pyx_k_tuple_9 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_8)); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_9); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); - /* "numpy.pxd":802 + /* "numpy.pxd":803 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_11 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_11); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_6)); - PyTuple_SET_ITEM(__pyx_k_tuple_11, 0, ((PyObject *)__pyx_kp_u_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_6)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); + __pyx_k_tuple_10 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_5)); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_10); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); - /* "numpy.pxd":822 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_13 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_tuple_12 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_11)); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_12); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + + /* "sklearn/utils/_logistic_sigmoid.pyx":21 + * + * + * def _log_logistic_sigmoid(int n_samples, int n_features, # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2] X, + * np.ndarray[DTYPE_t, ndim=2] out): + */ + __pyx_k_tuple_13 = PyTuple_Pack(6, ((PyObject *)__pyx_n_s__n_samples), ((PyObject *)__pyx_n_s__n_features), ((PyObject *)__pyx_n_s__X), ((PyObject *)__pyx_n_s__out), ((PyObject *)__pyx_n_s__i), ((PyObject *)__pyx_n_s__j)); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_13); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_12)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 0, ((PyObject *)__pyx_kp_u_12)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_12)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); - - /* "sklearn/cluster/_hierarchical.pyx":12 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def compute_ward_dist(np.ndarray[DOUBLE, ndim=1] m_1,\ # <<<<<<<<<<<<<< - * np.ndarray[DOUBLE, ndim=2] m_2,\ - * np.ndarray[INT, ndim=1] coord_row, - */ - __pyx_k_tuple_14 = PyTuple_New(13); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_14); - __Pyx_INCREF(((PyObject *)__pyx_n_s__m_1)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, ((PyObject *)__pyx_n_s__m_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__m_1)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__m_2)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 1, ((PyObject *)__pyx_n_s__m_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__m_2)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__coord_row)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 2, ((PyObject *)__pyx_n_s__coord_row)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__coord_row)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__coord_col)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 3, ((PyObject *)__pyx_n_s__coord_col)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__coord_col)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__res)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 4, ((PyObject *)__pyx_n_s__res)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__res)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__size_max)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 5, ((PyObject *)__pyx_n_s__size_max)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__size_max)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_features)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 6, ((PyObject *)__pyx_n_s__n_features)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_features)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__i)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 7, ((PyObject *)__pyx_n_s__i)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__j)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 8, ((PyObject *)__pyx_n_s__j)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__j)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__row)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 9, ((PyObject *)__pyx_n_s__row)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__row)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__col)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 10, ((PyObject *)__pyx_n_s__col)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__col)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__pa)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 11, ((PyObject *)__pyx_n_s__pa)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__pa)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 12, ((PyObject *)__pyx_n_s__n)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); - __pyx_k_codeobj_15 = (PyObject*)__Pyx_PyCode_New(5, 0, 13, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_14, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_16, __pyx_n_s__compute_ward_dist, 12, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/cluster/_hierarchical.pyx":32 - * - * - * def _hc_get_descendent(int node, children, int n_leaves): # <<<<<<<<<<<<<< - * """ - * Function returning all the descendent leaves of a set of nodes in the tree. - */ - __pyx_k_tuple_18 = PyTuple_New(7); if (unlikely(!__pyx_k_tuple_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_18); - __Pyx_INCREF(((PyObject *)__pyx_n_s__node)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 0, ((PyObject *)__pyx_n_s__node)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__node)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__children)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 1, ((PyObject *)__pyx_n_s__children)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__children)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_leaves)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 2, ((PyObject *)__pyx_n_s__n_leaves)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_leaves)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__ind)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 3, ((PyObject *)__pyx_n_s__ind)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__ind)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__descendent)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 4, ((PyObject *)__pyx_n_s__descendent)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__descendent)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__n_indices)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 5, ((PyObject *)__pyx_n_s__n_indices)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_indices)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__i)); - PyTuple_SET_ITEM(__pyx_k_tuple_18, 6, ((PyObject *)__pyx_n_s__i)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_18)); - __pyx_k_codeobj_19 = (PyObject*)__Pyx_PyCode_New(3, 0, 7, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_18, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_16, __pyx_n_s___hc_get_descendent, 32, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/cluster/_hierarchical.pyx":74 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * def hc_get_heads(np.ndarray[INT, ndim=1] parents, copy=True): # <<<<<<<<<<<<<< - * """ Return the heads of the forest, as defined by parents - * - */ - __pyx_k_tuple_20 = PyTuple_New(6); if (unlikely(!__pyx_k_tuple_20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_20); - __Pyx_INCREF(((PyObject *)__pyx_n_s__parents)); - PyTuple_SET_ITEM(__pyx_k_tuple_20, 0, ((PyObject *)__pyx_n_s__parents)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__parents)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__copy)); - PyTuple_SET_ITEM(__pyx_k_tuple_20, 1, ((PyObject *)__pyx_n_s__copy)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__copy)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__parent)); - PyTuple_SET_ITEM(__pyx_k_tuple_20, 2, ((PyObject *)__pyx_n_s__parent)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__parent)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__node0)); - PyTuple_SET_ITEM(__pyx_k_tuple_20, 3, ((PyObject *)__pyx_n_s__node0)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__node0)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__node)); - PyTuple_SET_ITEM(__pyx_k_tuple_20, 4, ((PyObject *)__pyx_n_s__node)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__node)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__size)); - PyTuple_SET_ITEM(__pyx_k_tuple_20, 5, ((PyObject *)__pyx_n_s__size)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__size)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_20)); - __pyx_k_codeobj_21 = (PyObject*)__Pyx_PyCode_New(2, 0, 6, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_20, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_16, __pyx_n_s__hc_get_heads, 74, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_21)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/cluster/_hierarchical.pyx":108 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * def _get_parents(nodes, heads, np.ndarray[INT, ndim=1] parents, # <<<<<<<<<<<<<< - * np.ndarray[INT8, ndim=1] not_visited): - * """ Return the heads of the given nodes, as defined by parents - */ - __pyx_k_tuple_22 = PyTuple_New(6); if (unlikely(!__pyx_k_tuple_22)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_22); - __Pyx_INCREF(((PyObject *)__pyx_n_s__nodes)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 0, ((PyObject *)__pyx_n_s__nodes)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nodes)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__heads)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 1, ((PyObject *)__pyx_n_s__heads)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__heads)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__parents)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 2, ((PyObject *)__pyx_n_s__parents)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__parents)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__not_visited)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 3, ((PyObject *)__pyx_n_s__not_visited)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__not_visited)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__parent)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 4, ((PyObject *)__pyx_n_s__parent)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__parent)); - __Pyx_INCREF(((PyObject *)__pyx_n_s__node)); - PyTuple_SET_ITEM(__pyx_k_tuple_22, 5, ((PyObject *)__pyx_n_s__node)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__node)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_22)); - __pyx_k_codeobj_23 = (PyObject*)__Pyx_PyCode_New(4, 0, 6, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_22, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_16, __pyx_n_s___get_parents, 108, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_k_codeobj_14 = (PyObject*)__Pyx_PyCode_New(4, 0, 6, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_13, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_16, __pyx_n_s_15, 21, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -4774,14 +3564,17 @@ static int __Pyx_InitGlobals(void) { } #if PY_MAJOR_VERSION < 3 -PyMODINIT_FUNC init_hierarchical(void); /*proto*/ -PyMODINIT_FUNC init_hierarchical(void) +PyMODINIT_FUNC init_logistic_sigmoid(void); /*proto*/ +PyMODINIT_FUNC init_logistic_sigmoid(void) #else -PyMODINIT_FUNC PyInit__hierarchical(void); /*proto*/ -PyMODINIT_FUNC PyInit__hierarchical(void) +PyMODINIT_FUNC PyInit__logistic_sigmoid(void); /*proto*/ +PyMODINIT_FUNC PyInit__logistic_sigmoid(void) #endif { PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -4792,7 +3585,7 @@ PyMODINIT_FUNC PyInit__hierarchical(void) Py_FatalError("failed to import 'refnanny' module"); } #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__hierarchical(void)", 0); + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__logistic_sigmoid(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} @@ -4814,23 +3607,32 @@ PyMODINIT_FUNC PyInit__hierarchical(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_hierarchical"), __pyx_methods, 0, 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_logistic_sigmoid"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.utils._logistic_sigmoid")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.utils._logistic_sigmoid", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_module_is_main_sklearn__cluster___hierarchical) { + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__utils___logistic_sigmoid) { if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } /*--- Builtin init code ---*/ @@ -4842,89 +3644,57 @@ PyMODINIT_FUNC PyInit__hierarchical(void) /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ - /* "sklearn/cluster/_hierarchical.pyx":1 + /* "sklearn/utils/_logistic_sigmoid.pyx":7 + * from libc.math cimport log, exp + * * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np - * cimport cython - */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "sklearn/cluster/_hierarchical.pyx":12 - * @cython.wraparound(False) - * @cython.cdivision(True) - * def compute_ward_dist(np.ndarray[DOUBLE, ndim=1] m_1,\ # <<<<<<<<<<<<<< - * np.ndarray[DOUBLE, ndim=2] m_2,\ - * np.ndarray[INT, ndim=1] coord_row, - */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_13_hierarchical_1compute_ward_dist, NULL, __pyx_n_s_17); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__compute_ward_dist, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "sklearn/cluster/_hierarchical.pyx":32 * - * - * def _hc_get_descendent(int node, children, int n_leaves): # <<<<<<<<<<<<<< - * """ - * Function returning all the descendent leaves of a set of nodes in the tree. */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_13_hierarchical_3_hc_get_descendent, NULL, __pyx_n_s_17); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___hc_get_descendent, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/cluster/_hierarchical.pyx":74 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * def hc_get_heads(np.ndarray[INT, ndim=1] parents, copy=True): # <<<<<<<<<<<<<< - * """ Return the heads of the forest, as defined by parents + /* "sklearn/utils/_logistic_sigmoid.pyx":21 * + * + * def _log_logistic_sigmoid(int n_samples, int n_features, # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=2] X, + * np.ndarray[DTYPE_t, ndim=2] out): */ - __pyx_t_1 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_k_1 = __pyx_t_1; - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_13_hierarchical_5hc_get_heads, NULL, __pyx_n_s_17); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__hc_get_heads, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "sklearn/cluster/_hierarchical.pyx":108 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * def _get_parents(nodes, heads, np.ndarray[INT, ndim=1] parents, # <<<<<<<<<<<<<< - * np.ndarray[INT8, ndim=1] not_visited): - * """ Return the heads of the given nodes, as defined by parents - */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_7cluster_13_hierarchical_7_get_parents, NULL, __pyx_n_s_17); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_17_logistic_sigmoid_1_log_logistic_sigmoid, NULL, __pyx_n_s_17); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s___get_parents, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_15, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/cluster/_hierarchical.pyx":1 - * import numpy as np # <<<<<<<<<<<<<< - * cimport numpy as np - * cimport cython + /* "sklearn/utils/_logistic_sigmoid.pyx":1 + * #cython: boundscheck=False # <<<<<<<<<<<<<< + * #cython: cdivision=True + * #cython: wraparound=False */ __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - /* "numpy.pxd":974 + /* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -4935,10 +3705,10 @@ PyMODINIT_FUNC PyInit__hierarchical(void) __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); if (__pyx_m) { - __Pyx_AddTraceback("init sklearn.cluster._hierarchical", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("init sklearn.utils._logistic_sigmoid", __pyx_clineno, __pyx_lineno, __pyx_filename); Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init sklearn.cluster._hierarchical"); + PyErr_SetString(PyExc_ImportError, "init sklearn.utils._logistic_sigmoid"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); @@ -4966,17 +3736,15 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { } #endif /* CYTHON_REFNANNY */ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%s' is not defined", PyString_AS_STRING(name)); +#endif } return result; } @@ -5001,7 +3769,7 @@ static void __Pyx_RaiseArgtupleInvalid( more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, - "%s() takes %s %" PY_FORMAT_SIZE_T "d positional argument%s (%" PY_FORMAT_SIZE_T "d given)", + "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } @@ -5015,7 +3783,7 @@ static void __Pyx_RaiseDoubleKeywordsError( "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); + PyString_AsString(kw_name)); #endif } @@ -5036,48 +3804,72 @@ static int __Pyx_ParseOptionalKeywords( while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; } - if (*name) { + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { values[name-argnames] = value; - } else { - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; } } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; } } return 0; arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); + __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, @@ -5175,7 +3967,8 @@ static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { - case 'b': return "'char'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; @@ -5295,7 +4088,9 @@ static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_compl } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'h': case 'i': + case 'c': + return 'H'; + case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case 'B': case 'H': case 'I': case 'L': case 'Q': @@ -5390,13 +4185,16 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ctx->head->parent_offset = parent_offset; continue; } - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %" PY_FORMAT_SIZE_T "d but %" PY_FORMAT_SIZE_T "d expected", + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } @@ -5636,7 +4434,7 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate( } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%" PY_FORMAT_SIZE_T "d byte%s) does not match size of '%s' (%" PY_FORMAT_SIZE_T "d byte%s)", + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; @@ -5684,74 +4482,61 @@ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyOb #endif } -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; - } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -static void __Pyx_RaiseBufferFallbackError(void) { - PyErr_Format(PyExc_ValueError, - "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); -} - #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) + if (PyClass_Check(type)) { #else - if (!PyType_Check(type)) + if (PyType_Check(type)) { #endif - { - if (value != Py_None) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } #endif } __Pyx_ErrRestore(type, value, tb); @@ -5764,6 +4549,7 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, } #else /* Python 3+ */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -5781,31 +4567,55 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } +#if PY_VERSION_HEX >= 0x03030000 if (cause) { +#else + if (cause && cause != Py_None) { +#endif PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; - } - else if (PyExceptionInstance_Check(cause)) { + } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); @@ -5819,18 +4629,19 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } } bad: + Py_XDECREF(owned_instance); return; } #endif static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" PY_FORMAT_SIZE_T "d)", expected); + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "need more than %" PY_FORMAT_SIZE_T "d value%s to unpack", + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", index, (index == 1) ? "" : "s"); } @@ -5883,109 +4694,95 @@ static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { return 0; } +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - CYTHON_UNUSED PyObject *getbuffer_cobj; - #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (getbuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_getbuffer"))) { - getbufferproc func; - - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (getbufferproc) PyCapsule_GetPointer(getbuffer_cobj, "getbuffer(obj, view, flags)"); - #else - func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); - #endif - Py_DECREF(getbuffer_cobj); - if (!func) - goto fail; - - return func(obj, view, flags); - } else { - PyErr_Clear(); + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } } #endif - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - #if PY_VERSION_HEX < 0x02060000 fail: #endif - return -1; } - static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; - CYTHON_UNUSED PyObject *releasebuffer_cobj; - if (!obj) return; - #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } - #if PY_VERSION_HEX < 0x02060000 - if (obj->ob_type->tp_dict && - (releasebuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, - "__pyx_releasebuffer"))) { - releasebufferproc func; - - #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) - func = (releasebufferproc) PyCapsule_GetPointer(releasebuffer_cobj, "releasebuffer(obj, view)"); - #else - func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); - #endif - - Py_DECREF(releasebuffer_cobj); - - if (!func) - goto fail; - - func(obj, view); - return; - } else { - PyErr_Clear(); + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } } #endif - goto nofail; - #if PY_VERSION_HEX < 0x02060000 fail: #endif PyErr_WriteUnraisable(obj); - nofail: Py_DECREF(obj); view->obj = NULL; } - #endif /* PY_MAJOR_VERSION < 3 */ - static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s____import__); if (!py_import) goto bad; + #endif if (from_list) list = from_list; else { @@ -6005,13 +4802,17 @@ static void __Pyx_ReleaseBuffer(Py_buffer *view) { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { - /* try package relative import first */ + #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(1); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; @@ -6022,12 +4823,17 @@ static void __Pyx_ReleaseBuffer(Py_buffer *view) { } #endif if (!module) { + #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif } } #else @@ -6039,8 +4845,10 @@ static void __Pyx_ReleaseBuffer(Py_buffer *view) { name, global_dict, empty_dict, list, NULL); #endif bad: - Py_XDECREF(empty_list); + #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } @@ -6475,10 +5283,15 @@ static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { return (int)__Pyx_PyInt_AsLong(x); } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { const unsigned long neg_one = (unsigned long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6491,6 +5304,16 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); @@ -6498,6 +5321,17 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { } return (unsigned long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (unsigned long)PyLong_AsLong(x); } } else { @@ -6510,10 +5344,15 @@ static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6526,6 +5365,16 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned PY_LONG_LONG"); @@ -6533,6 +5382,17 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje } return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -6545,10 +5405,15 @@ static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObje } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { const long neg_one = (long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6561,6 +5426,16 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); @@ -6568,6 +5443,17 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { } return (long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (long)PyLong_AsLong(x); } } else { @@ -6580,10 +5466,15 @@ static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6596,6 +5487,16 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to PY_LONG_LONG"); @@ -6603,6 +5504,17 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { } return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -6615,10 +5527,15 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { const signed long neg_one = (signed long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6631,6 +5548,16 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed long"); @@ -6638,6 +5565,17 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { } return (signed long)PyLong_AsUnsignedLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (signed long)PyLong_AsLong(x); } } else { @@ -6650,10 +5588,15 @@ static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { } } +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { @@ -6666,6 +5609,16 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed PY_LONG_LONG"); @@ -6673,6 +5626,17 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* } return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif return (signed PY_LONG_LONG)PyLong_AsLongLong(x); } } else { @@ -6704,6 +5668,23 @@ static int __Pyx_check_binary_version(void) { return 0; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -6713,6 +5694,10 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; @@ -6732,7 +5717,19 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class module_name, class_name); goto bad; } - if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -6742,7 +5739,7 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%s.%s has the wrong size, try recompiling", module_name, class_name); @@ -6756,23 +5753,6 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - py_name = __Pyx_PyIdentifier_FromString(name); - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; -} -#endif - static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { @@ -6965,27 +5945,82 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } - -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (r < 0) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -7001,7 +6036,7 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { @@ -7019,7 +6054,6 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject* x = PyNumber_Index(b); @@ -7028,7 +6062,6 @@ static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) @@ -7042,14 +6075,12 @@ static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); #endif } - static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); + if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); return (size_t)-1; } return (size_t)val; diff --git a/sklearn/utils/_logistic_sigmoid.pyx b/sklearn/utils/_logistic_sigmoid.pyx new file mode 100644 index 0000000000000..58809eb7c1b7b --- /dev/null +++ b/sklearn/utils/_logistic_sigmoid.pyx @@ -0,0 +1,27 @@ +#cython: boundscheck=False +#cython: cdivision=True +#cython: wraparound=False + +from libc.math cimport log, exp + +import numpy as np +cimport numpy as np + +ctypedef np.float64_t DTYPE_t + + +cdef DTYPE_t _inner_log_logistic_sigmoid(DTYPE_t x): + """Log of the logistic sigmoid function log(1 / (1 + e ** -x))""" + if x > 0: + return -log(1 + exp(-x)) + else: + return x - log(1 + exp(x)) + + +def _log_logistic_sigmoid(int n_samples, int n_features, + np.ndarray[DTYPE_t, ndim=2] X, + np.ndarray[DTYPE_t, ndim=2] out): + for i in range(n_samples): + for j in range(n_features): + out[i, j] = _inner_log_logistic_sigmoid(X[i, j]) + return out diff --git a/sklearn/utils/_random.c b/sklearn/utils/_random.c new file mode 100644 index 0000000000000..ddfb88e924473 --- /dev/null +++ b/sklearn/utils/_random.c @@ -0,0 +1,8041 @@ +/* Generated by Cython 0.19.1 on Sun Dec 8 01:42:22 2013 */ + +#define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_VERSION_HEX < 0x03020000 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__utils___random +#define __PYX_HAVE_API__sklearn__utils___random +#include "string.h" +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +#ifdef __GNUC__ + /* Test for GCC > 2.95 */ + #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) + #else /* __GNUC__ > 2 ... */ + #define likely(x) (x) + #define unlikely(x) (x) + #endif /* __GNUC__ > 2 ... */ +#else /* __GNUC__ */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "_random.pyx", + "numpy.pxd", + "type.pxd", +}; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + + +/* "numpy.pxd":723 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "numpy.pxd":724 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "numpy.pxd":725 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "numpy.pxd":726 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "numpy.pxd":730 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "numpy.pxd":731 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "numpy.pxd":732 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "numpy.pxd":733 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "numpy.pxd":737 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "numpy.pxd":738 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "numpy.pxd":747 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "numpy.pxd":748 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "numpy.pxd":749 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "numpy.pxd":751 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "numpy.pxd":752 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "numpy.pxd":753 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "numpy.pxd":755 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "numpy.pxd":756 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "numpy.pxd":758 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "numpy.pxd":759 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "numpy.pxd":760 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ + +/* "numpy.pxd":762 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "numpy.pxd":763 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "numpy.pxd":764 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "numpy.pxd":766 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; +struct __pyx_opt_args_7sklearn_5utils_7_random_sample_without_replacement; +struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_tracking_selection; +struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_pool; +struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_reservoir_sampling; + +/* "sklearn/utils/_random.pxd":10 + * + * + * cpdef sample_without_replacement(np.int_t n_population, # <<<<<<<<<<<<<< + * np.int_t n_samples, + * method=*, + */ +struct __pyx_opt_args_7sklearn_5utils_7_random_sample_without_replacement { + int __pyx_n; + PyObject *method; + PyObject *random_state; +}; + +/* "sklearn/utils/_random.pyx":42 + * + * cpdef _sample_without_replacement_with_tracking_selection( + * np.int_t n_population, # <<<<<<<<<<<<<< + * np.int_t n_samples, + * random_state=None): + */ +struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_tracking_selection { + int __pyx_n; + PyObject *random_state; +}; + +/* "sklearn/utils/_random.pyx":107 + * + * + * cpdef _sample_without_replacement_with_pool(np.int_t n_population, # <<<<<<<<<<<<<< + * np.int_t n_samples, + * random_state=None): + */ +struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_pool { + int __pyx_n; + PyObject *random_state; +}; + +/* "sklearn/utils/_random.pyx":168 + * + * cpdef _sample_without_replacement_with_reservoir_sampling( + * np.int_t n_population, # <<<<<<<<<<<<<< + * np.int_t n_samples, + * random_state=None): + */ +struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_reservoir_sampling { + int __pyx_n; + PyObject *random_state; +}; +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +#if PY_VERSION_HEX < 0x02050000 +#ifndef PyAnySet_CheckExact +#define PyAnySet_CheckExact(ob) \ + ((ob)->ob_type == &PySet_Type || \ + (ob)->ob_type == &PyFrozenSet_Type) +#define PySet_New(iterable) \ + PyObject_CallFunctionObjArgs((PyObject *)&PySet_Type, (iterable), NULL) +#define Pyx_PyFrozenSet_New(iterable) \ + PyObject_CallFunctionObjArgs((PyObject *)&PyFrozenSet_Type, (iterable), NULL) +#define PySet_Size(anyset) \ + PyObject_Size((anyset)) +#define PySet_Contains(anyset, key) \ + PySequence_Contains((anyset), (key)) +#define PySet_Pop(set) \ + PyObject_CallMethod(set, (char *)"pop", NULL) +static CYTHON_INLINE int PySet_Clear(PyObject *set) { + PyObject *ret = PyObject_CallMethod(set, (char *)"clear", NULL); + if (!ret) return -1; + Py_DECREF(ret); return 0; +} +static CYTHON_INLINE int PySet_Discard(PyObject *set, PyObject *key) { + PyObject *ret = PyObject_CallMethod(set, (char *)"discard", (char *)"O", key); + if (!ret) return -1; + Py_DECREF(ret); return 0; +} +static CYTHON_INLINE int PySet_Add(PyObject *set, PyObject *key) { + PyObject *ret = PyObject_CallMethod(set, (char *)"add", (char *)"O", key); + if (!ret) return -1; + Py_DECREF(ret); return 0; +} +#endif /* PyAnySet_CheckExact (<= Py2.4) */ +#endif /* < Py2.5 */ + +static CYTHON_INLINE int __Pyx_PySequence_Contains(PyObject* item, PyObject* seq, int eq) { + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /*proto*/ + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static CYTHON_INLINE npy_long __Pyx_PyInt_from_py_npy_long(PyObject *); + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_long(npy_long); + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); + +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); + +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); + +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); + +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); + +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); + +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); + +static int __Pyx_check_binary_version(void); + +static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig); /*proto*/ + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'cython' */ + +/* Module declarations from 'sklearn.utils._random' */ +static PyObject *__pyx_f_7sklearn_5utils_7_random_sample_without_replacement(__pyx_t_5numpy_int_t, __pyx_t_5numpy_int_t, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_5utils_7_random_sample_without_replacement *__pyx_optional_args); /*proto*/ +static PyObject *__pyx_f_7sklearn_5utils_7_random__sample_without_replacement_check_input(__pyx_t_5numpy_int_t, __pyx_t_5numpy_int_t, int __pyx_skip_dispatch); /*proto*/ +static PyObject *__pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_tracking_selection(__pyx_t_5numpy_int_t, __pyx_t_5numpy_int_t, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_tracking_selection *__pyx_optional_args); /*proto*/ +static PyObject *__pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_pool(__pyx_t_5numpy_int_t, __pyx_t_5numpy_int_t, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_pool *__pyx_optional_args); /*proto*/ +static PyObject *__pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_reservoir_sampling(__pyx_t_5numpy_int_t, __pyx_t_5numpy_int_t, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_reservoir_sampling *__pyx_optional_args); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int_t = { "int_t", NULL, sizeof(__pyx_t_5numpy_int_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_int_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_int_t), 0 }; +#define __Pyx_MODULE_NAME "sklearn.utils._random" +int __pyx_module_is_main_sklearn__utils___random = 0; + +/* Implementation of 'sklearn.utils._random' */ +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_xrange; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_pf_7sklearn_5utils_7_random__sample_without_replacement_check_input(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_7_random_2_sample_without_replacement_with_tracking_selection(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, PyObject *__pyx_v_random_state); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_7_random_4_sample_without_replacement_with_pool(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, PyObject *__pyx_v_random_state); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_7_random_6_sample_without_replacement_with_reservoir_sampling(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, PyObject *__pyx_v_random_state); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_7_random_8sample_without_replacement(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, PyObject *__pyx_v_method, PyObject *__pyx_v_random_state); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static char __pyx_k_1[] = "n_population should be greater than 0, got %s."; +static char __pyx_k_2[] = "n_population should be greater or equal than n_samples, got n_samples > n_population (%s > %s)"; +static char __pyx_k_4[] = "Expected a method name in %s, got %s. "; +static char __pyx_k_5[] = "ndarray is not C contiguous"; +static char __pyx_k_7[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_9[] = "Non-native byte order not supported"; +static char __pyx_k_11[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_12[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_15[] = "Format string allocated too short."; +static char __pyx_k_17[] = "\nRandom utility function\n=======================\nThis module complements missing features of ``numpy.random``.\n\nThe module contains:\n * Several algorithms to sample integers without replacement.\n\n"; +static char __pyx_k_18[] = "sklearn.utils"; +static char __pyx_k__B[] = "B"; +static char __pyx_k__H[] = "H"; +static char __pyx_k__I[] = "I"; +static char __pyx_k__L[] = "L"; +static char __pyx_k__O[] = "O"; +static char __pyx_k__Q[] = "Q"; +static char __pyx_k__b[] = "b"; +static char __pyx_k__d[] = "d"; +static char __pyx_k__f[] = "f"; +static char __pyx_k__g[] = "g"; +static char __pyx_k__h[] = "h"; +static char __pyx_k__i[] = "i"; +static char __pyx_k__l[] = "l"; +static char __pyx_k__q[] = "q"; +static char __pyx_k__Zd[] = "Zd"; +static char __pyx_k__Zf[] = "Zf"; +static char __pyx_k__Zg[] = "Zg"; +static char __pyx_k__np[] = "np"; +static char __pyx_k__int[] = "int"; +static char __pyx_k__auto[] = "auto"; +static char __pyx_k__pool[] = "pool"; +static char __pyx_k__dtype[] = "dtype"; +static char __pyx_k__empty[] = "empty"; +static char __pyx_k__numpy[] = "numpy"; +static char __pyx_k__range[] = "range"; +static char __pyx_k__method[] = "method"; +static char __pyx_k__xrange[] = "xrange"; +static char __pyx_k__randint[] = "randint"; +static char __pyx_k____main__[] = "__main__"; +static char __pyx_k____test__[] = "__test__"; +static char __pyx_k__n_samples[] = "n_samples"; +static char __pyx_k__ValueError[] = "ValueError"; +static char __pyx_k____import__[] = "__import__"; +static char __pyx_k__RuntimeError[] = "RuntimeError"; +static char __pyx_k__n_population[] = "n_population"; +static char __pyx_k__random_state[] = "random_state"; +static char __pyx_k____pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k__check_random_state[] = "check_random_state"; +static char __pyx_k__reservoir_sampling[] = "reservoir_sampling"; +static char __pyx_k__tracking_selection[] = "tracking_selection"; +static char __pyx_k____pyx_releasebuffer[] = "__pyx_releasebuffer"; +static PyObject *__pyx_kp_s_1; +static PyObject *__pyx_kp_u_11; +static PyObject *__pyx_kp_u_12; +static PyObject *__pyx_kp_u_15; +static PyObject *__pyx_n_s_18; +static PyObject *__pyx_kp_s_2; +static PyObject *__pyx_kp_s_4; +static PyObject *__pyx_kp_u_5; +static PyObject *__pyx_kp_u_7; +static PyObject *__pyx_kp_u_9; +static PyObject *__pyx_n_s__RuntimeError; +static PyObject *__pyx_n_s__ValueError; +static PyObject *__pyx_n_s____import__; +static PyObject *__pyx_n_s____main__; +static PyObject *__pyx_n_s____pyx_getbuffer; +static PyObject *__pyx_n_s____pyx_releasebuffer; +static PyObject *__pyx_n_s____test__; +static PyObject *__pyx_n_s__auto; +static PyObject *__pyx_n_s__check_random_state; +static PyObject *__pyx_n_s__dtype; +static PyObject *__pyx_n_s__empty; +static PyObject *__pyx_n_s__int; +static PyObject *__pyx_n_s__method; +static PyObject *__pyx_n_s__n_population; +static PyObject *__pyx_n_s__n_samples; +static PyObject *__pyx_n_s__np; +static PyObject *__pyx_n_s__numpy; +static PyObject *__pyx_n_s__pool; +static PyObject *__pyx_n_s__randint; +static PyObject *__pyx_n_s__random_state; +static PyObject *__pyx_n_s__range; +static PyObject *__pyx_n_s__reservoir_sampling; +static PyObject *__pyx_n_s__tracking_selection; +static PyObject *__pyx_n_s__xrange; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_15; +static PyObject *__pyx_k_tuple_3; +static PyObject *__pyx_k_tuple_6; +static PyObject *__pyx_k_tuple_8; +static PyObject *__pyx_k_tuple_10; +static PyObject *__pyx_k_tuple_13; +static PyObject *__pyx_k_tuple_14; +static PyObject *__pyx_k_tuple_16; + +/* "sklearn/utils/_random.pyx":28 + * + * + * cpdef _sample_without_replacement_check_input(np.int_t n_population, # <<<<<<<<<<<<<< + * np.int_t n_samples): + * """ Check that input are consistent for sample_without_replacement""" + */ + +static PyObject *__pyx_pw_7sklearn_5utils_7_random_1_sample_without_replacement_check_input(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyObject *__pyx_f_7sklearn_5utils_7_random__sample_without_replacement_check_input(__pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, CYTHON_UNUSED int __pyx_skip_dispatch) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_sample_without_replacement_check_input", 0); + + /* "sklearn/utils/_random.pyx":31 + * np.int_t n_samples): + * """ Check that input are consistent for sample_without_replacement""" + * if n_population < 0: # <<<<<<<<<<<<<< + * raise ValueError('n_population should be greater than 0, got %s.' + * % n_population) + */ + __pyx_t_1 = ((__pyx_v_n_population < 0) != 0); + if (__pyx_t_1) { + + /* "sklearn/utils/_random.pyx":33 + * if n_population < 0: + * raise ValueError('n_population should be greater than 0, got %s.' + * % n_population) # <<<<<<<<<<<<<< + * + * if n_samples > n_population: + */ + __pyx_t_2 = __Pyx_PyInt_to_py_npy_long(__pyx_v_n_population); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_1), __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/utils/_random.pyx":35 + * % n_population) + * + * if n_samples > n_population: # <<<<<<<<<<<<<< + * raise ValueError('n_population should be greater or equal than ' + * 'n_samples, got n_samples > n_population (%s > %s)' + */ + __pyx_t_1 = ((__pyx_v_n_samples > __pyx_v_n_population) != 0); + if (__pyx_t_1) { + + /* "sklearn/utils/_random.pyx":38 + * raise ValueError('n_population should be greater or equal than ' + * 'n_samples, got n_samples > n_population (%s > %s)' + * % (n_samples, n_population)) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __Pyx_PyInt_to_py_npy_long(__pyx_v_n_samples); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyInt_to_py_npy_long(__pyx_v_n_population); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_3 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_2), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_2)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_check_input", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_7_random_1_sample_without_replacement_check_input(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_7_random__sample_without_replacement_check_input[] = " Check that input are consistent for sample_without_replacement"; +static PyObject *__pyx_pw_7sklearn_5utils_7_random_1_sample_without_replacement_check_input(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_5numpy_int_t __pyx_v_n_population; + __pyx_t_5numpy_int_t __pyx_v_n_samples; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_sample_without_replacement_check_input (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_population,&__pyx_n_s__n_samples,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_population)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_samples)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sample_without_replacement_check_input", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_sample_without_replacement_check_input") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_n_population = __Pyx_PyInt_from_py_npy_long(values[0]); if (unlikely((__pyx_v_n_population == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_samples = __Pyx_PyInt_from_py_npy_long(values[1]); if (unlikely((__pyx_v_n_samples == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_sample_without_replacement_check_input", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_check_input", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_7_random__sample_without_replacement_check_input(__pyx_self, __pyx_v_n_population, __pyx_v_n_samples); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_random.pyx":28 + * + * + * cpdef _sample_without_replacement_check_input(np.int_t n_population, # <<<<<<<<<<<<<< + * np.int_t n_samples): + * """ Check that input are consistent for sample_without_replacement""" + */ + +static PyObject *__pyx_pf_7sklearn_5utils_7_random__sample_without_replacement_check_input(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_sample_without_replacement_check_input", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_check_input(__pyx_v_n_population, __pyx_v_n_samples, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_check_input", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_random.pyx":41 + * + * + * cpdef _sample_without_replacement_with_tracking_selection( # <<<<<<<<<<<<<< + * np.int_t n_population, + * np.int_t n_samples, + */ + +static PyObject *__pyx_pw_7sklearn_5utils_7_random_3_sample_without_replacement_with_tracking_selection(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyObject *__pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_tracking_selection(__pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, CYTHON_UNUSED int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_tracking_selection *__pyx_optional_args) { + + /* "sklearn/utils/_random.pyx":44 + * np.int_t n_population, + * np.int_t n_samples, + * random_state=None): # <<<<<<<<<<<<<< + * """Sample integers without replacement. + * + */ + PyObject *__pyx_v_random_state = ((PyObject *)Py_None); + __pyx_t_5numpy_int_t __pyx_v_i; + __pyx_t_5numpy_int_t __pyx_v_j; + PyArrayObject *__pyx_v_out = 0; + PyObject *__pyx_v_rng = NULL; + PyObject *__pyx_v_rng_randint = NULL; + PyObject *__pyx_v_selected = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_out; + __Pyx_Buffer __pyx_pybuffer_out; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + __pyx_t_5numpy_int_t __pyx_t_7; + __pyx_t_5numpy_int_t __pyx_t_8; + __pyx_t_5numpy_int_t __pyx_t_9; + int __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_sample_without_replacement_with_tracking_selection", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_random_state = __pyx_optional_args->random_state; + } + } + __pyx_pybuffer_out.pybuffer.buf = NULL; + __pyx_pybuffer_out.refcount = 0; + __pyx_pybuffernd_out.data = NULL; + __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; + + /* "sklearn/utils/_random.pyx":83 + * The sampled subsets of integer. + * """ + * _sample_without_replacement_check_input(n_population, n_samples) # <<<<<<<<<<<<<< + * + * cdef np.int_t i + */ + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_check_input(__pyx_v_n_population, __pyx_v_n_samples, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/_random.pyx":87 + * cdef np.int_t i + * cdef np.int_t j + * cdef np.ndarray[np.int_t, ndim=1] out = np.empty((n_samples, ), # <<<<<<<<<<<<<< + * dtype=np.int) + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_to_py_npy_long(__pyx_v_n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + + /* "sklearn/utils/_random.pyx":88 + * cdef np.int_t j + * cdef np.ndarray[np.int_t, ndim=1] out = np.empty((n_samples, ), + * dtype=np.int) # <<<<<<<<<<<<<< + * + * rng = check_random_state(random_state) + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__int); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_out.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __pyx_v_out = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "sklearn/utils/_random.pyx":90 + * dtype=np.int) + * + * rng = check_random_state(random_state) # <<<<<<<<<<<<<< + * rng_randint = rng.randint + * + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__check_random_state); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_random_state); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_random_state); + __Pyx_GIVEREF(__pyx_v_random_state); + __pyx_t_1 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_rng = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_random.pyx":91 + * + * rng = check_random_state(random_state) + * rng_randint = rng.randint # <<<<<<<<<<<<<< + * + * # The following line of code are heavily inspired from python core, + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_rng, __pyx_n_s__randint); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_rng_randint = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_random.pyx":95 + * # The following line of code are heavily inspired from python core, + * # more precisely of random.sample. + * cdef set selected = set() # <<<<<<<<<<<<<< + * + * for i in range(n_samples): + */ + __pyx_t_1 = PySet_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_v_selected = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/_random.pyx":97 + * cdef set selected = set() + * + * for i in range(n_samples): # <<<<<<<<<<<<<< + * j = rng_randint(n_population) + * while j in selected: + */ + __pyx_t_7 = __pyx_v_n_samples; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "sklearn/utils/_random.pyx":98 + * + * for i in range(n_samples): + * j = rng_randint(n_population) # <<<<<<<<<<<<<< + * while j in selected: + * j = rng_randint(n_population) + */ + __pyx_t_1 = __Pyx_PyInt_to_py_npy_long(__pyx_v_n_population); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_v_rng_randint, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_t_9 = __Pyx_PyInt_from_py_npy_long(__pyx_t_1); if (unlikely((__pyx_t_9 == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_j = __pyx_t_9; + + /* "sklearn/utils/_random.pyx":99 + * for i in range(n_samples): + * j = rng_randint(n_population) + * while j in selected: # <<<<<<<<<<<<<< + * j = rng_randint(n_population) + * selected.add(j) + */ + while (1) { + __pyx_t_1 = __Pyx_PyInt_to_py_npy_long(__pyx_v_j); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_10 = (__Pyx_PySequence_Contains(__pyx_t_1, ((PyObject *)__pyx_v_selected), Py_EQ)); if (unlikely(__pyx_t_10 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_11 = (__pyx_t_10 != 0); + if (!__pyx_t_11) break; + + /* "sklearn/utils/_random.pyx":100 + * j = rng_randint(n_population) + * while j in selected: + * j = rng_randint(n_population) # <<<<<<<<<<<<<< + * selected.add(j) + * out[i] = j + */ + __pyx_t_1 = __Pyx_PyInt_to_py_npy_long(__pyx_v_n_population); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_v_rng_randint, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_t_9 = __Pyx_PyInt_from_py_npy_long(__pyx_t_1); if (unlikely((__pyx_t_9 == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_j = __pyx_t_9; + } + + /* "sklearn/utils/_random.pyx":101 + * while j in selected: + * j = rng_randint(n_population) + * selected.add(j) # <<<<<<<<<<<<<< + * out[i] = j + * + */ + __pyx_t_1 = __Pyx_PyInt_to_py_npy_long(__pyx_v_j); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_12 = PySet_Add(__pyx_v_selected, __pyx_t_1); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/_random.pyx":102 + * j = rng_randint(n_population) + * selected.add(j) + * out[i] = j # <<<<<<<<<<<<<< + * + * return out + */ + __pyx_t_9 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_pybuffernd_out.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_out.diminfo[0].strides) = __pyx_v_j; + } + + /* "sklearn/utils/_random.pyx":104 + * out[i] = j + * + * return out # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_out)); + __pyx_r = ((PyObject *)__pyx_v_out); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_with_tracking_selection", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_out); + __Pyx_XDECREF(__pyx_v_rng); + __Pyx_XDECREF(__pyx_v_rng_randint); + __Pyx_XDECREF(__pyx_v_selected); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_7_random_3_sample_without_replacement_with_tracking_selection(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_7_random_2_sample_without_replacement_with_tracking_selection[] = "Sample integers without replacement.\n\n Select n_samples integers from the set [0, n_population) without\n replacement.\n\n Time complexity:\n - Worst-case: unbounded\n - Average-case:\n O(O(np.random.randint) * \\sum_{i=1}^n_samples 1 /\n (1 - i / n_population)))\n <= O(O(np.random.randint) *\n n_population * ln((n_population - 2)\n /(n_population - 1 - n_samples)))\n <= O(O(np.random.randint) *\n n_population * 1 / (1 - n_samples / n_population))\n\n Space complexity of O(n_samples) in a python set.\n\n\n Parameters\n ----------\n n_population : int,\n The size of the set to sample from.\n\n n_samples : int,\n The number of integer to sample.\n\n random_state : int, RandomState instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by `np.random`.\n\n Returns\n -------\n out : array of size (n_samples, )\n The sampled subsets of integer.\n "; +static PyObject *__pyx_pw_7sklearn_5utils_7_random_3_sample_without_replacement_with_tracking_selection(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_5numpy_int_t __pyx_v_n_population; + __pyx_t_5numpy_int_t __pyx_v_n_samples; + PyObject *__pyx_v_random_state = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_sample_without_replacement_with_tracking_selection (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_population,&__pyx_n_s__n_samples,&__pyx_n_s__random_state,0}; + PyObject* values[3] = {0,0,0}; + + /* "sklearn/utils/_random.pyx":44 + * np.int_t n_population, + * np.int_t n_samples, + * random_state=None): # <<<<<<<<<<<<<< + * """Sample integers without replacement. + * + */ + values[2] = ((PyObject *)Py_None); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_population)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_samples)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sample_without_replacement_with_tracking_selection", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__random_state); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_sample_without_replacement_with_tracking_selection") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_n_population = __Pyx_PyInt_from_py_npy_long(values[0]); if (unlikely((__pyx_v_n_population == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_samples = __Pyx_PyInt_from_py_npy_long(values[1]); if (unlikely((__pyx_v_n_samples == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_random_state = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_sample_without_replacement_with_tracking_selection", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_with_tracking_selection", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_7_random_2_sample_without_replacement_with_tracking_selection(__pyx_self, __pyx_v_n_population, __pyx_v_n_samples, __pyx_v_random_state); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_random.pyx":41 + * + * + * cpdef _sample_without_replacement_with_tracking_selection( # <<<<<<<<<<<<<< + * np.int_t n_population, + * np.int_t n_samples, + */ + +static PyObject *__pyx_pf_7sklearn_5utils_7_random_2_sample_without_replacement_with_tracking_selection(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, PyObject *__pyx_v_random_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_tracking_selection __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_sample_without_replacement_with_tracking_selection", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_2.__pyx_n = 1; + __pyx_t_2.random_state = __pyx_v_random_state; + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_tracking_selection(__pyx_v_n_population, __pyx_v_n_samples, 0, &__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_with_tracking_selection", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_random.pyx":107 + * + * + * cpdef _sample_without_replacement_with_pool(np.int_t n_population, # <<<<<<<<<<<<<< + * np.int_t n_samples, + * random_state=None): + */ + +static PyObject *__pyx_pw_7sklearn_5utils_7_random_5_sample_without_replacement_with_pool(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyObject *__pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_pool(__pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, CYTHON_UNUSED int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_pool *__pyx_optional_args) { + + /* "sklearn/utils/_random.pyx":109 + * cpdef _sample_without_replacement_with_pool(np.int_t n_population, + * np.int_t n_samples, + * random_state=None): # <<<<<<<<<<<<<< + * """Sample integers without replacement. + * + */ + PyObject *__pyx_v_random_state = ((PyObject *)Py_None); + __pyx_t_5numpy_int_t __pyx_v_i; + __pyx_t_5numpy_int_t __pyx_v_j; + PyArrayObject *__pyx_v_out = 0; + PyArrayObject *__pyx_v_pool = 0; + PyObject *__pyx_v_rng = NULL; + PyObject *__pyx_v_rng_randint = NULL; + __Pyx_LocalBuf_ND __pyx_pybuffernd_out; + __Pyx_Buffer __pyx_pybuffer_out; + __Pyx_LocalBuf_ND __pyx_pybuffernd_pool; + __Pyx_Buffer __pyx_pybuffer_pool; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + PyArrayObject *__pyx_t_7 = NULL; + __pyx_t_5numpy_int_t __pyx_t_8; + __pyx_t_5numpy_int_t __pyx_t_9; + __pyx_t_5numpy_int_t __pyx_t_10; + __pyx_t_5numpy_int_t __pyx_t_11; + __pyx_t_5numpy_int_t __pyx_t_12; + long __pyx_t_13; + __pyx_t_5numpy_int_t __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_sample_without_replacement_with_pool", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_random_state = __pyx_optional_args->random_state; + } + } + __pyx_pybuffer_out.pybuffer.buf = NULL; + __pyx_pybuffer_out.refcount = 0; + __pyx_pybuffernd_out.data = NULL; + __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; + __pyx_pybuffer_pool.pybuffer.buf = NULL; + __pyx_pybuffer_pool.refcount = 0; + __pyx_pybuffernd_pool.data = NULL; + __pyx_pybuffernd_pool.rcbuffer = &__pyx_pybuffer_pool; + + /* "sklearn/utils/_random.pyx":139 + * The sampled subsets of integer. + * """ + * _sample_without_replacement_check_input(n_population, n_samples) # <<<<<<<<<<<<<< + * + * cdef np.int_t i + */ + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_check_input(__pyx_v_n_population, __pyx_v_n_samples, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/_random.pyx":143 + * cdef np.int_t i + * cdef np.int_t j + * cdef np.ndarray[np.int_t, ndim=1] out = np.empty((n_samples, ), # <<<<<<<<<<<<<< + * dtype=np.int) + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_to_py_npy_long(__pyx_v_n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + + /* "sklearn/utils/_random.pyx":144 + * cdef np.int_t j + * cdef np.ndarray[np.int_t, ndim=1] out = np.empty((n_samples, ), + * dtype=np.int) # <<<<<<<<<<<<<< + * + * cdef np.ndarray[np.int_t, ndim=1] pool = np.empty((n_population, ), + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__int); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_out.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __pyx_v_out = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "sklearn/utils/_random.pyx":146 + * dtype=np.int) + * + * cdef np.ndarray[np.int_t, ndim=1] pool = np.empty((n_population, ), # <<<<<<<<<<<<<< + * dtype=np.int) + * + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyInt_to_py_npy_long(__pyx_v_n_population); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_t_1)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_1)); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + + /* "sklearn/utils/_random.pyx":147 + * + * cdef np.ndarray[np.int_t, ndim=1] pool = np.empty((n_population, ), + * dtype=np.int) # <<<<<<<<<<<<<< + * + * rng = check_random_state(random_state) + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__int); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_pool.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_pool = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_pool.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_pool.diminfo[0].strides = __pyx_pybuffernd_pool.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_pool.diminfo[0].shape = __pyx_pybuffernd_pool.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_7 = 0; + __pyx_v_pool = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/utils/_random.pyx":149 + * dtype=np.int) + * + * rng = check_random_state(random_state) # <<<<<<<<<<<<<< + * rng_randint = rng.randint + * + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__check_random_state); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_random_state); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_random_state); + __Pyx_GIVEREF(__pyx_v_random_state); + __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_v_rng = __pyx_t_5; + __pyx_t_5 = 0; + + /* "sklearn/utils/_random.pyx":150 + * + * rng = check_random_state(random_state) + * rng_randint = rng.randint # <<<<<<<<<<<<<< + * + * # Initialize the pool + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_rng, __pyx_n_s__randint); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_rng_randint = __pyx_t_5; + __pyx_t_5 = 0; + + /* "sklearn/utils/_random.pyx":153 + * + * # Initialize the pool + * for i in xrange(n_population): # <<<<<<<<<<<<<< + * pool[i] = i + * + */ + __pyx_t_8 = __pyx_v_n_population; + for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { + __pyx_v_i = __pyx_t_9; + + /* "sklearn/utils/_random.pyx":154 + * # Initialize the pool + * for i in xrange(n_population): + * pool[i] = i # <<<<<<<<<<<<<< + * + * # The following line of code are heavily inspired from python core, + */ + __pyx_t_10 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_pybuffernd_pool.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_pool.diminfo[0].strides) = __pyx_v_i; + } + + /* "sklearn/utils/_random.pyx":158 + * # The following line of code are heavily inspired from python core, + * # more precisely of random.sample. + * for i in xrange(n_samples): # <<<<<<<<<<<<<< + * j = rng_randint(n_population - i) # invariant: non-selected at [0,n-i) + * out[i] = pool[j] + */ + __pyx_t_8 = __pyx_v_n_samples; + for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { + __pyx_v_i = __pyx_t_9; + + /* "sklearn/utils/_random.pyx":159 + * # more precisely of random.sample. + * for i in xrange(n_samples): + * j = rng_randint(n_population - i) # invariant: non-selected at [0,n-i) # <<<<<<<<<<<<<< + * out[i] = pool[j] + * pool[j] = pool[n_population - i - 1] # move non-selected item into + */ + __pyx_t_5 = __Pyx_PyInt_to_py_npy_long((__pyx_v_n_population - __pyx_v_i)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_v_rng_randint, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_11 = __Pyx_PyInt_from_py_npy_long(__pyx_t_5); if (unlikely((__pyx_t_11 == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_j = __pyx_t_11; + + /* "sklearn/utils/_random.pyx":160 + * for i in xrange(n_samples): + * j = rng_randint(n_population - i) # invariant: non-selected at [0,n-i) + * out[i] = pool[j] # <<<<<<<<<<<<<< + * pool[j] = pool[n_population - i - 1] # move non-selected item into + * # vacancy + */ + __pyx_t_11 = __pyx_v_j; + __pyx_t_12 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_pybuffernd_out.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_out.diminfo[0].strides) = (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_pybuffernd_pool.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_pool.diminfo[0].strides)); + + /* "sklearn/utils/_random.pyx":161 + * j = rng_randint(n_population - i) # invariant: non-selected at [0,n-i) + * out[i] = pool[j] + * pool[j] = pool[n_population - i - 1] # move non-selected item into # <<<<<<<<<<<<<< + * # vacancy + * + */ + __pyx_t_13 = ((__pyx_v_n_population - __pyx_v_i) - 1); + __pyx_t_14 = __pyx_v_j; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_pybuffernd_pool.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_pool.diminfo[0].strides) = (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_pybuffernd_pool.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_pool.diminfo[0].strides)); + } + + /* "sklearn/utils/_random.pyx":164 + * # vacancy + * + * return out # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_out)); + __pyx_r = ((PyObject *)__pyx_v_out); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_pool.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_with_pool", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_pool.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_out); + __Pyx_XDECREF((PyObject *)__pyx_v_pool); + __Pyx_XDECREF(__pyx_v_rng); + __Pyx_XDECREF(__pyx_v_rng_randint); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_7_random_5_sample_without_replacement_with_pool(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_7_random_4_sample_without_replacement_with_pool[] = "Sample integers without replacement.\n\n Select n_samples integers from the set [0, n_population) without\n replacement.\n\n Time complexity: O(n_population + O(np.random.randint) * n_samples)\n\n Space complexity of O(n_population + n_samples).\n\n\n Parameters\n ----------\n n_population : int,\n The size of the set to sample from.\n\n n_samples : int,\n The number of integer to sample.\n\n random_state : int, RandomState instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by `np.random`.\n\n Returns\n -------\n out : array of size (n_samples, )\n The sampled subsets of integer.\n "; +static PyObject *__pyx_pw_7sklearn_5utils_7_random_5_sample_without_replacement_with_pool(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_5numpy_int_t __pyx_v_n_population; + __pyx_t_5numpy_int_t __pyx_v_n_samples; + PyObject *__pyx_v_random_state = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_sample_without_replacement_with_pool (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_population,&__pyx_n_s__n_samples,&__pyx_n_s__random_state,0}; + PyObject* values[3] = {0,0,0}; + + /* "sklearn/utils/_random.pyx":109 + * cpdef _sample_without_replacement_with_pool(np.int_t n_population, + * np.int_t n_samples, + * random_state=None): # <<<<<<<<<<<<<< + * """Sample integers without replacement. + * + */ + values[2] = ((PyObject *)Py_None); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_population)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_samples)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sample_without_replacement_with_pool", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__random_state); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_sample_without_replacement_with_pool") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_n_population = __Pyx_PyInt_from_py_npy_long(values[0]); if (unlikely((__pyx_v_n_population == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_samples = __Pyx_PyInt_from_py_npy_long(values[1]); if (unlikely((__pyx_v_n_samples == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_random_state = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_sample_without_replacement_with_pool", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_with_pool", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_7_random_4_sample_without_replacement_with_pool(__pyx_self, __pyx_v_n_population, __pyx_v_n_samples, __pyx_v_random_state); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_random.pyx":107 + * + * + * cpdef _sample_without_replacement_with_pool(np.int_t n_population, # <<<<<<<<<<<<<< + * np.int_t n_samples, + * random_state=None): + */ + +static PyObject *__pyx_pf_7sklearn_5utils_7_random_4_sample_without_replacement_with_pool(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, PyObject *__pyx_v_random_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_pool __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_sample_without_replacement_with_pool", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_2.__pyx_n = 1; + __pyx_t_2.random_state = __pyx_v_random_state; + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_pool(__pyx_v_n_population, __pyx_v_n_samples, 0, &__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_with_pool", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_random.pyx":167 + * + * + * cpdef _sample_without_replacement_with_reservoir_sampling( # <<<<<<<<<<<<<< + * np.int_t n_population, + * np.int_t n_samples, + */ + +static PyObject *__pyx_pw_7sklearn_5utils_7_random_7_sample_without_replacement_with_reservoir_sampling(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyObject *__pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_reservoir_sampling(__pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, CYTHON_UNUSED int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_reservoir_sampling *__pyx_optional_args) { + + /* "sklearn/utils/_random.pyx":170 + * np.int_t n_population, + * np.int_t n_samples, + * random_state=None): # <<<<<<<<<<<<<< + * """Sample integers without replacement. + * + */ + PyObject *__pyx_v_random_state = ((PyObject *)Py_None); + __pyx_t_5numpy_int_t __pyx_v_i; + __pyx_t_5numpy_int_t __pyx_v_j; + PyArrayObject *__pyx_v_out = 0; + PyObject *__pyx_v_rng = NULL; + PyObject *__pyx_v_rng_randint = NULL; + __Pyx_LocalBuf_ND __pyx_pybuffernd_out; + __Pyx_Buffer __pyx_pybuffer_out; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + __pyx_t_5numpy_int_t __pyx_t_7; + __pyx_t_5numpy_int_t __pyx_t_8; + __pyx_t_5numpy_int_t __pyx_t_9; + int __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_sample_without_replacement_with_reservoir_sampling", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_random_state = __pyx_optional_args->random_state; + } + } + __pyx_pybuffer_out.pybuffer.buf = NULL; + __pyx_pybuffer_out.refcount = 0; + __pyx_pybuffernd_out.data = NULL; + __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; + + /* "sklearn/utils/_random.pyx":202 + * of the items has to be randomized. + * """ + * _sample_without_replacement_check_input(n_population, n_samples) # <<<<<<<<<<<<<< + * + * cdef np.int_t i + */ + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_check_input(__pyx_v_n_population, __pyx_v_n_samples, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/_random.pyx":206 + * cdef np.int_t i + * cdef np.int_t j + * cdef np.ndarray[np.int_t, ndim=1] out = np.empty((n_samples, ), # <<<<<<<<<<<<<< + * dtype=np.int) + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_to_py_npy_long(__pyx_v_n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + + /* "sklearn/utils/_random.pyx":207 + * cdef np.int_t j + * cdef np.ndarray[np.int_t, ndim=1] out = np.empty((n_samples, ), + * dtype=np.int) # <<<<<<<<<<<<<< + * + * rng = check_random_state(random_state) + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__int); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_out.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 206; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __pyx_v_out = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "sklearn/utils/_random.pyx":209 + * dtype=np.int) + * + * rng = check_random_state(random_state) # <<<<<<<<<<<<<< + * rng_randint = rng.randint + * + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__check_random_state); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_random_state); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_random_state); + __Pyx_GIVEREF(__pyx_v_random_state); + __pyx_t_1 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_rng = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_random.pyx":210 + * + * rng = check_random_state(random_state) + * rng_randint = rng.randint # <<<<<<<<<<<<<< + * + * # This cython implementation is based on the one of Robert Kern: + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_rng, __pyx_n_s__randint); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_rng_randint = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_random.pyx":216 + * # 054289.html + * # + * for i in range(n_samples): # <<<<<<<<<<<<<< + * out[i] = i + * + */ + __pyx_t_7 = __pyx_v_n_samples; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "sklearn/utils/_random.pyx":217 + * # + * for i in range(n_samples): + * out[i] = i # <<<<<<<<<<<<<< + * + * for i from n_samples <= i < n_population: + */ + __pyx_t_9 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_pybuffernd_out.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_out.diminfo[0].strides) = __pyx_v_i; + } + + /* "sklearn/utils/_random.pyx":219 + * out[i] = i + * + * for i from n_samples <= i < n_population: # <<<<<<<<<<<<<< + * j = rng_randint(0, i + 1) + * if j < n_samples: + */ + __pyx_t_7 = __pyx_v_n_population; + for (__pyx_v_i = __pyx_v_n_samples; __pyx_v_i < __pyx_t_7; __pyx_v_i++) { + + /* "sklearn/utils/_random.pyx":220 + * + * for i from n_samples <= i < n_population: + * j = rng_randint(0, i + 1) # <<<<<<<<<<<<<< + * if j < n_samples: + * out[j] = i + */ + __pyx_t_1 = PyInt_FromLong((__pyx_v_i + 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_v_rng_randint, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_t_8 = __Pyx_PyInt_from_py_npy_long(__pyx_t_1); if (unlikely((__pyx_t_8 == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_j = __pyx_t_8; + + /* "sklearn/utils/_random.pyx":221 + * for i from n_samples <= i < n_population: + * j = rng_randint(0, i + 1) + * if j < n_samples: # <<<<<<<<<<<<<< + * out[j] = i + * + */ + __pyx_t_10 = ((__pyx_v_j < __pyx_v_n_samples) != 0); + if (__pyx_t_10) { + + /* "sklearn/utils/_random.pyx":222 + * j = rng_randint(0, i + 1) + * if j < n_samples: + * out[j] = i # <<<<<<<<<<<<<< + * + * return out + */ + __pyx_t_8 = __pyx_v_j; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int_t *, __pyx_pybuffernd_out.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_out.diminfo[0].strides) = __pyx_v_i; + goto __pyx_L7; + } + __pyx_L7:; + } + + /* "sklearn/utils/_random.pyx":224 + * out[j] = i + * + * return out # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_out)); + __pyx_r = ((PyObject *)__pyx_v_out); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_with_reservoir_sampling", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_out); + __Pyx_XDECREF(__pyx_v_rng); + __Pyx_XDECREF(__pyx_v_rng_randint); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_7_random_7_sample_without_replacement_with_reservoir_sampling(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_7_random_6_sample_without_replacement_with_reservoir_sampling[] = "Sample integers without replacement.\n\n Select n_samples integers from the set [0, n_population) without\n replacement.\n\n Time complexity of\n O((n_population - n_samples) * O(np.random.randint) + n_samples)\n Space complexity of O(n_samples)\n\n\n Parameters\n ----------\n n_population : int,\n The size of the set to sample from.\n\n n_samples : int,\n The number of integer to sample.\n\n random_state : int, RandomState instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by `np.random`.\n\n Returns\n -------\n out : array of size (n_samples, )\n The sampled subsets of integer. The order of the items is not\n necessarily random. Use a random permutation of the array if the order\n of the items has to be randomized.\n "; +static PyObject *__pyx_pw_7sklearn_5utils_7_random_7_sample_without_replacement_with_reservoir_sampling(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_5numpy_int_t __pyx_v_n_population; + __pyx_t_5numpy_int_t __pyx_v_n_samples; + PyObject *__pyx_v_random_state = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_sample_without_replacement_with_reservoir_sampling (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_population,&__pyx_n_s__n_samples,&__pyx_n_s__random_state,0}; + PyObject* values[3] = {0,0,0}; + + /* "sklearn/utils/_random.pyx":170 + * np.int_t n_population, + * np.int_t n_samples, + * random_state=None): # <<<<<<<<<<<<<< + * """Sample integers without replacement. + * + */ + values[2] = ((PyObject *)Py_None); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_population)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_samples)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("_sample_without_replacement_with_reservoir_sampling", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__random_state); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_sample_without_replacement_with_reservoir_sampling") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_n_population = __Pyx_PyInt_from_py_npy_long(values[0]); if (unlikely((__pyx_v_n_population == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_samples = __Pyx_PyInt_from_py_npy_long(values[1]); if (unlikely((__pyx_v_n_samples == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_random_state = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_sample_without_replacement_with_reservoir_sampling", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_with_reservoir_sampling", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_7_random_6_sample_without_replacement_with_reservoir_sampling(__pyx_self, __pyx_v_n_population, __pyx_v_n_samples, __pyx_v_random_state); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_random.pyx":167 + * + * + * cpdef _sample_without_replacement_with_reservoir_sampling( # <<<<<<<<<<<<<< + * np.int_t n_population, + * np.int_t n_samples, + */ + +static PyObject *__pyx_pf_7sklearn_5utils_7_random_6_sample_without_replacement_with_reservoir_sampling(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, PyObject *__pyx_v_random_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_reservoir_sampling __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_sample_without_replacement_with_reservoir_sampling", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_2.__pyx_n = 1; + __pyx_t_2.random_state = __pyx_v_random_state; + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_reservoir_sampling(__pyx_v_n_population, __pyx_v_n_samples, 0, &__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.utils._random._sample_without_replacement_with_reservoir_sampling", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_random.pyx":227 + * + * + * cpdef sample_without_replacement(np.int_t n_population, # <<<<<<<<<<<<<< + * np.int_t n_samples, + * method="auto", + */ + +static PyObject *__pyx_pw_7sklearn_5utils_7_random_9sample_without_replacement(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyObject *__pyx_f_7sklearn_5utils_7_random_sample_without_replacement(__pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, CYTHON_UNUSED int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_5utils_7_random_sample_without_replacement *__pyx_optional_args) { + PyObject *__pyx_v_method = ((PyObject *)__pyx_n_s__auto); + + /* "sklearn/utils/_random.pyx":230 + * np.int_t n_samples, + * method="auto", + * random_state=None): # <<<<<<<<<<<<<< + * """Sample integers without replacement. + * + */ + PyObject *__pyx_v_random_state = ((PyObject *)Py_None); + PyObject *__pyx_v_all_methods = NULL; + double __pyx_v_ratio; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + double __pyx_t_5; + struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_tracking_selection __pyx_t_6; + struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_reservoir_sampling __pyx_t_7; + struct __pyx_opt_args_7sklearn_5utils_7_random__sample_without_replacement_with_pool __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("sample_without_replacement", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_method = __pyx_optional_args->method; + if (__pyx_optional_args->__pyx_n > 1) { + __pyx_v_random_state = __pyx_optional_args->random_state; + } + } + } + + /* "sklearn/utils/_random.pyx":274 + * not be randomized, see the method argument. + * """ + * _sample_without_replacement_check_input(n_population, n_samples) # <<<<<<<<<<<<<< + * + * all_methods = ("auto", "tracking_selection", "reservoir_sampling", "pool") + */ + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_check_input(__pyx_v_n_population, __pyx_v_n_samples, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 274; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/_random.pyx":276 + * _sample_without_replacement_check_input(n_population, n_samples) + * + * all_methods = ("auto", "tracking_selection", "reservoir_sampling", "pool") # <<<<<<<<<<<<<< + * + * if method == "auto" or method == "tracking_selection": + */ + __Pyx_INCREF(((PyObject *)__pyx_k_tuple_3)); + __pyx_v_all_methods = __pyx_k_tuple_3; + + /* "sklearn/utils/_random.pyx":278 + * all_methods = ("auto", "tracking_selection", "reservoir_sampling", "pool") + * + * if method == "auto" or method == "tracking_selection": # <<<<<<<<<<<<<< + * # TODO the pool based method can also be used. + * # however, it requires special benchmark to take into account + */ + __pyx_t_1 = PyObject_RichCompare(__pyx_v_method, ((PyObject *)__pyx_n_s__auto), Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!__pyx_t_2) { + __pyx_t_1 = PyObject_RichCompare(__pyx_v_method, ((PyObject *)__pyx_n_s__tracking_selection), Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_4 = __pyx_t_3; + } else { + __pyx_t_4 = __pyx_t_2; + } + if (__pyx_t_4) { + + /* "sklearn/utils/_random.pyx":282 + * # however, it requires special benchmark to take into account + * # the memory requirement of the array vs the set. + * ratio = n_samples / n_population if n_population != 0.0 else 1.0 # <<<<<<<<<<<<<< + * + * # The value 0.2 has been determined through benchmarking. + */ + if (((__pyx_v_n_population != 0.0) != 0)) { + __pyx_t_5 = (__pyx_v_n_samples / __pyx_v_n_population); + } else { + __pyx_t_5 = 1.0; + } + __pyx_v_ratio = __pyx_t_5; + + /* "sklearn/utils/_random.pyx":285 + * + * # The value 0.2 has been determined through benchmarking. + * if ratio < 0.2: # <<<<<<<<<<<<<< + * return _sample_without_replacement_with_tracking_selection( + * n_population, n_samples, random_state) + */ + __pyx_t_4 = ((__pyx_v_ratio < 0.2) != 0); + if (__pyx_t_4) { + + /* "sklearn/utils/_random.pyx":286 + * # The value 0.2 has been determined through benchmarking. + * if ratio < 0.2: + * return _sample_without_replacement_with_tracking_selection( # <<<<<<<<<<<<<< + * n_population, n_samples, random_state) + * else: + */ + __Pyx_XDECREF(__pyx_r); + + /* "sklearn/utils/_random.pyx":287 + * if ratio < 0.2: + * return _sample_without_replacement_with_tracking_selection( + * n_population, n_samples, random_state) # <<<<<<<<<<<<<< + * else: + * return _sample_without_replacement_with_reservoir_sampling( + */ + __pyx_t_6.__pyx_n = 1; + __pyx_t_6.random_state = __pyx_v_random_state; + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_tracking_selection(__pyx_v_n_population, __pyx_v_n_samples, 0, &__pyx_t_6); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + goto __pyx_L4; + } + /*else*/ { + + /* "sklearn/utils/_random.pyx":289 + * n_population, n_samples, random_state) + * else: + * return _sample_without_replacement_with_reservoir_sampling( # <<<<<<<<<<<<<< + * n_population, n_samples, random_state) + * + */ + __Pyx_XDECREF(__pyx_r); + + /* "sklearn/utils/_random.pyx":290 + * else: + * return _sample_without_replacement_with_reservoir_sampling( + * n_population, n_samples, random_state) # <<<<<<<<<<<<<< + * + * elif method == "reservoir_sampling": + */ + __pyx_t_7.__pyx_n = 1; + __pyx_t_7.random_state = __pyx_v_random_state; + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_reservoir_sampling(__pyx_v_n_population, __pyx_v_n_samples, 0, &__pyx_t_7); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + } + __pyx_L4:; + goto __pyx_L3; + } + + /* "sklearn/utils/_random.pyx":292 + * n_population, n_samples, random_state) + * + * elif method == "reservoir_sampling": # <<<<<<<<<<<<<< + * return _sample_without_replacement_with_reservoir_sampling( + * n_population, n_samples, random_state) + */ + __pyx_t_1 = PyObject_RichCompare(__pyx_v_method, ((PyObject *)__pyx_n_s__reservoir_sampling), Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 292; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 292; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_4) { + + /* "sklearn/utils/_random.pyx":293 + * + * elif method == "reservoir_sampling": + * return _sample_without_replacement_with_reservoir_sampling( # <<<<<<<<<<<<<< + * n_population, n_samples, random_state) + * + */ + __Pyx_XDECREF(__pyx_r); + + /* "sklearn/utils/_random.pyx":294 + * elif method == "reservoir_sampling": + * return _sample_without_replacement_with_reservoir_sampling( + * n_population, n_samples, random_state) # <<<<<<<<<<<<<< + * + * elif method == "pool": + */ + __pyx_t_7.__pyx_n = 1; + __pyx_t_7.random_state = __pyx_v_random_state; + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_reservoir_sampling(__pyx_v_n_population, __pyx_v_n_samples, 0, &__pyx_t_7); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 293; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + goto __pyx_L3; + } + + /* "sklearn/utils/_random.pyx":296 + * n_population, n_samples, random_state) + * + * elif method == "pool": # <<<<<<<<<<<<<< + * return _sample_without_replacement_with_pool(n_population, n_samples, + * random_state) + */ + __pyx_t_1 = PyObject_RichCompare(__pyx_v_method, ((PyObject *)__pyx_n_s__pool), Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_4) { + + /* "sklearn/utils/_random.pyx":297 + * + * elif method == "pool": + * return _sample_without_replacement_with_pool(n_population, n_samples, # <<<<<<<<<<<<<< + * random_state) + * else: + */ + __Pyx_XDECREF(__pyx_r); + + /* "sklearn/utils/_random.pyx":298 + * elif method == "pool": + * return _sample_without_replacement_with_pool(n_population, n_samples, + * random_state) # <<<<<<<<<<<<<< + * else: + * raise ValueError('Expected a method name in %s, got %s. ' + */ + __pyx_t_8.__pyx_n = 1; + __pyx_t_8.random_state = __pyx_v_random_state; + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random__sample_without_replacement_with_pool(__pyx_v_n_population, __pyx_v_n_samples, 0, &__pyx_t_8); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/utils/_random.pyx":301 + * else: + * raise ValueError('Expected a method name in %s, got %s. ' + * % (all_methods, method)) # <<<<<<<<<<<<<< + */ + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_all_methods)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_all_methods)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_all_methods)); + __Pyx_INCREF(__pyx_v_method); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_method); + __Pyx_GIVEREF(__pyx_v_method); + __pyx_t_9 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_4), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_9)); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_9)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_9)); + __pyx_t_9 = 0; + __pyx_t_9 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("sklearn.utils._random.sample_without_replacement", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_all_methods); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_7_random_9sample_without_replacement(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_7_random_8sample_without_replacement[] = "Sample integers without replacement.\n\n Select n_samples integers from the set [0, n_population) without\n replacement.\n\n\n Parameters\n ----------\n n_population : int,\n The size of the set to sample from.\n\n n_samples : int,\n The number of integer to sample.\n\n random_state : int, RandomState instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by `np.random`.\n\n method : \"auto\", \"tracking_selection\" or \"reservoir_sampling\"\n If method == \"auto\", an algorithm is automatically selected.\n The subset of selected integer is not randomized.\n\n If method ==\"tracking_selection\", a set based implementation is used\n which is suitable for `n_samples` <<< `n_population`.\n\n If method == \"reservoir_sampling\", a reservoir sampling algorithm is\n used which is suitable for high memory constraint or when\n O(`n_samples`) ~ O(`n_population`).\n The subset of selected integer is not randomized.\n\n If method == \"pool\", a pool based algorithm is particularly fast, even\n faster than the tracking selection method. Hovewer, a vector containing\n the entire population has to be initialized.\n If n_samples ~ n_population, the reservoir sampling method is faster.\n\n Returns\n -------\n out : array of size (n_samples, )\n The sampled subsets of integer. The subset of selected integer might\n not be randomized, see the method argument.\n "; +static PyObject *__pyx_pw_7sklearn_5utils_7_random_9sample_without_replacement(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_5numpy_int_t __pyx_v_n_population; + __pyx_t_5numpy_int_t __pyx_v_n_samples; + PyObject *__pyx_v_method = 0; + PyObject *__pyx_v_random_state = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("sample_without_replacement (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n_population,&__pyx_n_s__n_samples,&__pyx_n_s__method,&__pyx_n_s__random_state,0}; + PyObject* values[4] = {0,0,0,0}; + values[2] = ((PyObject *)__pyx_n_s__auto); + + /* "sklearn/utils/_random.pyx":230 + * np.int_t n_samples, + * method="auto", + * random_state=None): # <<<<<<<<<<<<<< + * """Sample integers without replacement. + * + */ + values[3] = ((PyObject *)Py_None); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_population)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n_samples)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("sample_without_replacement", 0, 2, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__method); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__random_state); + if (value) { values[3] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "sample_without_replacement") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_n_population = __Pyx_PyInt_from_py_npy_long(values[0]); if (unlikely((__pyx_v_n_population == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_n_samples = __Pyx_PyInt_from_py_npy_long(values[1]); if (unlikely((__pyx_v_n_samples == (npy_long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_method = values[2]; + __pyx_v_random_state = values[3]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("sample_without_replacement", 0, 2, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils._random.sample_without_replacement", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_7_random_8sample_without_replacement(__pyx_self, __pyx_v_n_population, __pyx_v_n_samples, __pyx_v_method, __pyx_v_random_state); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_random.pyx":227 + * + * + * cpdef sample_without_replacement(np.int_t n_population, # <<<<<<<<<<<<<< + * np.int_t n_samples, + * method="auto", + */ + +static PyObject *__pyx_pf_7sklearn_5utils_7_random_8sample_without_replacement(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_5numpy_int_t __pyx_v_n_population, __pyx_t_5numpy_int_t __pyx_v_n_samples, PyObject *__pyx_v_method, PyObject *__pyx_v_random_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + struct __pyx_opt_args_7sklearn_5utils_7_random_sample_without_replacement __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("sample_without_replacement", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_2.__pyx_n = 2; + __pyx_t_2.method = __pyx_v_method; + __pyx_t_2.random_state = __pyx_v_random_state; + __pyx_t_1 = __pyx_f_7sklearn_5utils_7_random_sample_without_replacement(__pyx_v_n_population, __pyx_v_n_samples, 0, &__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.utils._random.sample_without_replacement", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "numpy.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "numpy.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "numpy.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "numpy.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "numpy.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "numpy.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_3) { + + /* "numpy.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "numpy.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "numpy.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "numpy.pxd":222 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "numpy.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { + + /* "numpy.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "numpy.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "numpy.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "numpy.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "numpy.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "numpy.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "numpy.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "numpy.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "numpy.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "numpy.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "numpy.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "numpy.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "numpy.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "numpy.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "numpy.pxd":251 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "numpy.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; + + /* "numpy.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); + if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "numpy.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_1) { + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "numpy.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k__b; + break; + + /* "numpy.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k__B; + break; + + /* "numpy.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k__h; + break; + + /* "numpy.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k__H; + break; + + /* "numpy.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k__i; + break; + + /* "numpy.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k__I; + break; + + /* "numpy.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k__l; + break; + + /* "numpy.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k__L; + break; + + /* "numpy.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k__q; + break; + + /* "numpy.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k__Q; + break; + + /* "numpy.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k__f; + break; + + /* "numpy.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k__d; + break; + + /* "numpy.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k__g; + break; + + /* "numpy.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k__Zf; + break; + + /* "numpy.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k__Zd; + break; + + /* "numpy.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k__Zg; + break; + + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k__O; + break; + default: + + /* "numpy.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_11), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "numpy.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "numpy.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "numpy.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "numpy.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "numpy.pxd":285 + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + * &offset) # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "numpy.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + __pyx_L11:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "numpy.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "numpy.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "numpy.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "numpy.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "numpy.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "numpy.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + long __pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "numpy.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF(__pyx_v_childname); + __pyx_v_childname = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); + __pyx_v_fields = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "numpy.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { + PyObject* sequence = ((PyObject *)__pyx_v_fields); + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_child)); + __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_v_new_offset); + __pyx_v_new_offset = __pyx_t_4; + __pyx_t_4 = 0; + + /* "numpy.pxd":798 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + + /* "numpy.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_13), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + + /* "numpy.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_7) { + __pyx_t_8 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_8 = __pyx_t_7; + } + if (!__pyx_t_8) { + + /* "numpy.pxd":802 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + __pyx_t_9 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_10 = __pyx_t_9; + } else { + __pyx_t_10 = __pyx_t_7; + } + __pyx_t_7 = __pyx_t_10; + } else { + __pyx_t_7 = __pyx_t_8; + } + if (__pyx_t_7) { + + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + + /* "numpy.pxd":813 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_7) break; + + /* "numpy.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "numpy.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "numpy.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); + } + + /* "numpy.pxd":818 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); + + /* "numpy.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_7 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_7) { + + /* "numpy.pxd":821 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_v_t); + __pyx_v_t = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_7 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_7) { + + /* "numpy.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 98; + goto __pyx_L13; + } + + /* "numpy.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 66; + goto __pyx_L13; + } + + /* "numpy.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 104; + goto __pyx_L13; + } + + /* "numpy.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 72; + goto __pyx_L13; + } + + /* "numpy.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 105; + goto __pyx_L13; + } + + /* "numpy.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 73; + goto __pyx_L13; + } + + /* "numpy.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 108; + goto __pyx_L13; + } + + /* "numpy.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 76; + goto __pyx_L13; + } + + /* "numpy.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 113; + goto __pyx_L13; + } + + /* "numpy.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 81; + goto __pyx_L13; + } + + /* "numpy.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 102; + goto __pyx_L13; + } + + /* "numpy.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 100; + goto __pyx_L13; + } + + /* "numpy.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 103; + goto __pyx_L13; + } + + /* "numpy.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 79; + goto __pyx_L13; + } + /*else*/ { + + /* "numpy.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_11), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L13:; + + /* "numpy.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_12; + } + __pyx_L11:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "numpy.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":965 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "numpy.pxd":967 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "numpy.pxd":968 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":970 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "numpy.pxd":971 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "numpy.pxd":972 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "numpy.pxd":973 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":975 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "numpy.pxd":976 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":977 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":979 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyMethodDef __pyx_methods[] = { + {__Pyx_NAMESTR("_sample_without_replacement_check_input"), (PyCFunction)__pyx_pw_7sklearn_5utils_7_random_1_sample_without_replacement_check_input, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_7_random__sample_without_replacement_check_input)}, + {__Pyx_NAMESTR("_sample_without_replacement_with_tracking_selection"), (PyCFunction)__pyx_pw_7sklearn_5utils_7_random_3_sample_without_replacement_with_tracking_selection, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_7_random_2_sample_without_replacement_with_tracking_selection)}, + {__Pyx_NAMESTR("_sample_without_replacement_with_pool"), (PyCFunction)__pyx_pw_7sklearn_5utils_7_random_5_sample_without_replacement_with_pool, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_7_random_4_sample_without_replacement_with_pool)}, + {__Pyx_NAMESTR("_sample_without_replacement_with_reservoir_sampling"), (PyCFunction)__pyx_pw_7sklearn_5utils_7_random_7_sample_without_replacement_with_reservoir_sampling, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_7_random_6_sample_without_replacement_with_reservoir_sampling)}, + {__Pyx_NAMESTR("sample_without_replacement"), (PyCFunction)__pyx_pw_7sklearn_5utils_7_random_9sample_without_replacement, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_7_random_8sample_without_replacement)}, + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + __Pyx_NAMESTR("_random"), + __Pyx_DOCSTR(__pyx_k_17), /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 0}, + {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, + {&__pyx_kp_u_12, __pyx_k_12, sizeof(__pyx_k_12), 0, 1, 0, 0}, + {&__pyx_kp_u_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 1, 0, 0}, + {&__pyx_n_s_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 0, 1, 1}, + {&__pyx_kp_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 0}, + {&__pyx_kp_s_4, __pyx_k_4, sizeof(__pyx_k_4), 0, 0, 1, 0}, + {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, + {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, + {&__pyx_kp_u_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 1, 0, 0}, + {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, + {&__pyx_n_s____import__, __pyx_k____import__, sizeof(__pyx_k____import__), 0, 0, 1, 1}, + {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_getbuffer, __pyx_k____pyx_getbuffer, sizeof(__pyx_k____pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_releasebuffer, __pyx_k____pyx_releasebuffer, sizeof(__pyx_k____pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, + {&__pyx_n_s__auto, __pyx_k__auto, sizeof(__pyx_k__auto), 0, 0, 1, 1}, + {&__pyx_n_s__check_random_state, __pyx_k__check_random_state, sizeof(__pyx_k__check_random_state), 0, 0, 1, 1}, + {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, + {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, + {&__pyx_n_s__int, __pyx_k__int, sizeof(__pyx_k__int), 0, 0, 1, 1}, + {&__pyx_n_s__method, __pyx_k__method, sizeof(__pyx_k__method), 0, 0, 1, 1}, + {&__pyx_n_s__n_population, __pyx_k__n_population, sizeof(__pyx_k__n_population), 0, 0, 1, 1}, + {&__pyx_n_s__n_samples, __pyx_k__n_samples, sizeof(__pyx_k__n_samples), 0, 0, 1, 1}, + {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, + {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, + {&__pyx_n_s__pool, __pyx_k__pool, sizeof(__pyx_k__pool), 0, 0, 1, 1}, + {&__pyx_n_s__randint, __pyx_k__randint, sizeof(__pyx_k__randint), 0, 0, 1, 1}, + {&__pyx_n_s__random_state, __pyx_k__random_state, sizeof(__pyx_k__random_state), 0, 0, 1, 1}, + {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, + {&__pyx_n_s__reservoir_sampling, __pyx_k__reservoir_sampling, sizeof(__pyx_k__reservoir_sampling), 0, 0, 1, 1}, + {&__pyx_n_s__tracking_selection, __pyx_k__tracking_selection, sizeof(__pyx_k__tracking_selection), 0, 0, 1, 1}, + {&__pyx_n_s__xrange, __pyx_k__xrange, sizeof(__pyx_k__xrange), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "sklearn/utils/_random.pyx":276 + * _sample_without_replacement_check_input(n_population, n_samples) + * + * all_methods = ("auto", "tracking_selection", "reservoir_sampling", "pool") # <<<<<<<<<<<<<< + * + * if method == "auto" or method == "tracking_selection": + */ + __pyx_k_tuple_3 = PyTuple_Pack(4, ((PyObject *)__pyx_n_s__auto), ((PyObject *)__pyx_n_s__tracking_selection), ((PyObject *)__pyx_n_s__reservoir_sampling), ((PyObject *)__pyx_n_s__pool)); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_3); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_3)); + + /* "numpy.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_k_tuple_6 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_5)); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_6); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); + + /* "numpy.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_k_tuple_8 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_7)); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_8); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); + + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_k_tuple_10 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_9)); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_10); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + + /* "numpy.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_k_tuple_13 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_12)); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_13); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); + + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_k_tuple_14 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_9)); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_14); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + + /* "numpy.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_k_tuple_16 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_15)); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_16); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC init_random(void); /*proto*/ +PyMODINIT_FUNC init_random(void) +#else +PyMODINIT_FUNC PyInit__random(void); /*proto*/ +PyMODINIT_FUNC PyInit__random(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__random(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_random"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_17), 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.utils._random")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.utils._random", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__utils___random) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + if (__Pyx_ExportFunction("sample_without_replacement", (void (*)(void))__pyx_f_7sklearn_5utils_7_random_sample_without_replacement, "PyObject *(__pyx_t_5numpy_int_t, __pyx_t_5numpy_int_t, int __pyx_skip_dispatch, struct __pyx_opt_args_7sklearn_5utils_7_random_sample_without_replacement *__pyx_optional_args)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Type init code ---*/ + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/utils/_random.pyx":21 + * cimport cython + * + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * np.import_array() + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/_random.pyx":23 + * import numpy as np + * cimport numpy as np + * np.import_array() # <<<<<<<<<<<<<< + * + * from sklearn.utils import check_random_state + */ + import_array(); + + /* "sklearn/utils/_random.pyx":25 + * np.import_array() + * + * from sklearn.utils import check_random_state # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_n_s__check_random_state)); + PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s__check_random_state)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__check_random_state)); + __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s_18), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s__check_random_state); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__check_random_state, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_random.pyx":1 + * # cython: cdivision=True # <<<<<<<<<<<<<< + * # cython: boundscheck=False + * # cython: wraparound=False + */ + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + + /* "numpy.pxd":975 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.utils._random", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.utils._random"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { + #endif +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; /* Consume from buffer string */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + if (isspace(*ts)) + continue; + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case 10: + case 13: + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } /* fall through */ + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 's': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + } else { + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + } + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; +} + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif + } + return value; +} + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s____import__); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } + } + #endif + PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: + Py_DECREF(obj); + view->obj = NULL; +} +#endif /* PY_MAJOR_VERSION < 3 */ + + + static CYTHON_INLINE npy_long __Pyx_PyInt_from_py_npy_long(PyObject* x) { + const npy_long neg_one = (npy_long)-1, const_zero = (npy_long)0; + const int is_unsigned = const_zero < neg_one; + if (sizeof(npy_long) == sizeof(char)) { + if (is_unsigned) + return (npy_long)__Pyx_PyInt_AsUnsignedChar(x); + else + return (npy_long)__Pyx_PyInt_AsSignedChar(x); + } else if (sizeof(npy_long) == sizeof(short)) { + if (is_unsigned) + return (npy_long)__Pyx_PyInt_AsUnsignedShort(x); + else + return (npy_long)__Pyx_PyInt_AsSignedShort(x); + } else if (sizeof(npy_long) == sizeof(int)) { + if (is_unsigned) + return (npy_long)__Pyx_PyInt_AsUnsignedInt(x); + else + return (npy_long)__Pyx_PyInt_AsSignedInt(x); + } else if (sizeof(npy_long) == sizeof(long)) { + if (is_unsigned) + return (npy_long)__Pyx_PyInt_AsUnsignedLong(x); + else + return (npy_long)__Pyx_PyInt_AsSignedLong(x); + } else if (sizeof(npy_long) == sizeof(PY_LONG_LONG)) { + if (is_unsigned) + return (npy_long)__Pyx_PyInt_AsUnsignedLongLong(x); + else + return (npy_long)__Pyx_PyInt_AsSignedLongLong(x); + } else { + #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); + #else + npy_long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } + #endif + return (npy_long)-1; + } +} + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_long(npy_long val) { + const npy_long neg_one = (npy_long)-1, const_zero = (npy_long)0; + const int is_unsigned = const_zero < neg_one; + if ((sizeof(npy_long) == sizeof(char)) || + (sizeof(npy_long) == sizeof(short))) { + return PyInt_FromLong((long)val); + } else if ((sizeof(npy_long) == sizeof(int)) || + (sizeof(npy_long) == sizeof(long))) { + if (is_unsigned) + return PyLong_FromUnsignedLong((unsigned long)val); + else + return PyInt_FromLong((long)val); + } else if (sizeof(npy_long) == sizeof(PY_LONG_LONG)) { + if (is_unsigned) + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); + else + return PyLong_FromLongLong((PY_LONG_LONG)val); + } else { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + return _PyLong_FromByteArray(bytes, sizeof(npy_long), + little, !is_unsigned); + } +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { + const unsigned char neg_one = (unsigned char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned char" : + "value too large to convert to unsigned char"); + } + return (unsigned char)-1; + } + return (unsigned char)val; + } + return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { + const unsigned short neg_one = (unsigned short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned short" : + "value too large to convert to unsigned short"); + } + return (unsigned short)-1; + } + return (unsigned short)val; + } + return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { + const unsigned int neg_one = (unsigned int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned int" : + "value too large to convert to unsigned int"); + } + return (unsigned int)-1; + } + return (unsigned int)val; + } + return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { + const char neg_one = (char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to char" : + "value too large to convert to char"); + } + return (char)-1; + } + return (char)val; + } + return (char)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { + const short neg_one = (short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to short" : + "value too large to convert to short"); + } + return (short)-1; + } + return (short)val; + } + return (short)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { + const signed char neg_one = (signed char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed char" : + "value too large to convert to signed char"); + } + return (signed char)-1; + } + return (signed char)val; + } + return (signed char)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { + const signed short neg_one = (signed short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed short" : + "value too large to convert to signed short"); + } + return (signed short)-1; + } + return (signed short)val; + } + return (signed short)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { + const signed int neg_one = (signed int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed int" : + "value too large to convert to signed int"); + } + return (signed int)-1; + } + return (signed int)val; + } + return (signed int)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { + const unsigned long neg_one = (unsigned long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (unsigned long)PyLong_AsLong(x); + } + } else { + unsigned long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned long)-1; + val = __Pyx_PyInt_AsUnsignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { + const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + unsigned PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsUnsignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { + const long neg_one = (long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (long)PyLong_AsLong(x); + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long)-1; + val = __Pyx_PyInt_AsLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { + const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { + const signed long neg_one = (signed long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (signed long)PyLong_AsLong(x); + } + } else { + signed long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed long)-1; + val = __Pyx_PyInt_AsSignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { + const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + signed PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsSignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(__pyx_m, (char *)"__pyx_capi__"); + if (!d) { + PyErr_Clear(); + d = PyDict_New(); + if (!d) + goto bad; + Py_INCREF(d); + if (PyModule_AddObject(__pyx_m, (char *)"__pyx_capi__", d) < 0) + goto bad; + } + tmp.fp = f; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + cobj = PyCapsule_New(tmp.p, sig, 0); +#else + cobj = PyCObject_FromVoidPtrAndDesc(tmp.p, (void *)sig, 0); +#endif + if (!cobj) + goto bad; + if (PyDict_SetItemString(d, name, cobj) < 0) + goto bad; + Py_DECREF(cobj); + Py_DECREF(d); + return 0; +bad: + Py_XDECREF(cobj); + Py_XDECREF(d); + return -1; +} + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%s.%s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + #if PY_VERSION_HEX < 0x02050000 + if (PyErr_Warn(NULL, warning) < 0) goto bad; + #else + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + #endif + } + else if ((size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%s.%s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (r < 0) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_MAJOR_VERSION < 3 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%s__ returned non-%s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject* x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { + unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); + if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); + return (size_t)-1; + } + return (size_t)val; +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/utils/_random.pxd b/sklearn/utils/_random.pxd new file mode 100644 index 0000000000000..2cf45a4200a18 --- /dev/null +++ b/sklearn/utils/_random.pxd @@ -0,0 +1,14 @@ +# Authors: Arnaud Joly +# +# Licence: BSD 3 clause + + +import numpy as np +cimport numpy as np + + +cpdef sample_without_replacement(np.int_t n_population, + np.int_t n_samples, + method=*, + random_state=*) + diff --git a/sklearn/utils/_random.pyx b/sklearn/utils/_random.pyx new file mode 100644 index 0000000000000..d61d452eac006 --- /dev/null +++ b/sklearn/utils/_random.pyx @@ -0,0 +1,301 @@ +# cython: cdivision=True +# cython: boundscheck=False +# cython: wraparound=False +# +# Author: Arnaud Joly +# +# Licence: BSD 3 clause +""" +Random utility function +======================= +This module complements missing features of ``numpy.random``. + +The module contains: + * Several algorithms to sample integers without replacement. + +""" +from __future__ import division + +cimport cython + +import numpy as np +cimport numpy as np +np.import_array() + +from sklearn.utils import check_random_state + + +cpdef _sample_without_replacement_check_input(np.int_t n_population, + np.int_t n_samples): + """ Check that input are consistent for sample_without_replacement""" + if n_population < 0: + raise ValueError('n_population should be greater than 0, got %s.' + % n_population) + + if n_samples > n_population: + raise ValueError('n_population should be greater or equal than ' + 'n_samples, got n_samples > n_population (%s > %s)' + % (n_samples, n_population)) + + +cpdef _sample_without_replacement_with_tracking_selection( + np.int_t n_population, + np.int_t n_samples, + random_state=None): + """Sample integers without replacement. + + Select n_samples integers from the set [0, n_population) without + replacement. + + Time complexity: + - Worst-case: unbounded + - Average-case: + O(O(np.random.randint) * \sum_{i=1}^n_samples 1 / + (1 - i / n_population))) + <= O(O(np.random.randint) * + n_population * ln((n_population - 2) + /(n_population - 1 - n_samples))) + <= O(O(np.random.randint) * + n_population * 1 / (1 - n_samples / n_population)) + + Space complexity of O(n_samples) in a python set. + + + Parameters + ---------- + n_population : int, + The size of the set to sample from. + + n_samples : int, + The number of integer to sample. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + Returns + ------- + out : array of size (n_samples, ) + The sampled subsets of integer. + """ + _sample_without_replacement_check_input(n_population, n_samples) + + cdef np.int_t i + cdef np.int_t j + cdef np.ndarray[np.int_t, ndim=1] out = np.empty((n_samples, ), + dtype=np.int) + + rng = check_random_state(random_state) + rng_randint = rng.randint + + # The following line of code are heavily inspired from python core, + # more precisely of random.sample. + cdef set selected = set() + + for i in range(n_samples): + j = rng_randint(n_population) + while j in selected: + j = rng_randint(n_population) + selected.add(j) + out[i] = j + + return out + + +cpdef _sample_without_replacement_with_pool(np.int_t n_population, + np.int_t n_samples, + random_state=None): + """Sample integers without replacement. + + Select n_samples integers from the set [0, n_population) without + replacement. + + Time complexity: O(n_population + O(np.random.randint) * n_samples) + + Space complexity of O(n_population + n_samples). + + + Parameters + ---------- + n_population : int, + The size of the set to sample from. + + n_samples : int, + The number of integer to sample. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + Returns + ------- + out : array of size (n_samples, ) + The sampled subsets of integer. + """ + _sample_without_replacement_check_input(n_population, n_samples) + + cdef np.int_t i + cdef np.int_t j + cdef np.ndarray[np.int_t, ndim=1] out = np.empty((n_samples, ), + dtype=np.int) + + cdef np.ndarray[np.int_t, ndim=1] pool = np.empty((n_population, ), + dtype=np.int) + + rng = check_random_state(random_state) + rng_randint = rng.randint + + # Initialize the pool + for i in xrange(n_population): + pool[i] = i + + # The following line of code are heavily inspired from python core, + # more precisely of random.sample. + for i in xrange(n_samples): + j = rng_randint(n_population - i) # invariant: non-selected at [0,n-i) + out[i] = pool[j] + pool[j] = pool[n_population - i - 1] # move non-selected item into + # vacancy + + return out + + +cpdef _sample_without_replacement_with_reservoir_sampling( + np.int_t n_population, + np.int_t n_samples, + random_state=None): + """Sample integers without replacement. + + Select n_samples integers from the set [0, n_population) without + replacement. + + Time complexity of + O((n_population - n_samples) * O(np.random.randint) + n_samples) + Space complexity of O(n_samples) + + + Parameters + ---------- + n_population : int, + The size of the set to sample from. + + n_samples : int, + The number of integer to sample. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + Returns + ------- + out : array of size (n_samples, ) + The sampled subsets of integer. The order of the items is not + necessarily random. Use a random permutation of the array if the order + of the items has to be randomized. + """ + _sample_without_replacement_check_input(n_population, n_samples) + + cdef np.int_t i + cdef np.int_t j + cdef np.ndarray[np.int_t, ndim=1] out = np.empty((n_samples, ), + dtype=np.int) + + rng = check_random_state(random_state) + rng_randint = rng.randint + + # This cython implementation is based on the one of Robert Kern: + # http://mail.scipy.org/pipermail/numpy-discussion/2010-December/ + # 054289.html + # + for i in range(n_samples): + out[i] = i + + for i from n_samples <= i < n_population: + j = rng_randint(0, i + 1) + if j < n_samples: + out[j] = i + + return out + + +cpdef sample_without_replacement(np.int_t n_population, + np.int_t n_samples, + method="auto", + random_state=None): + """Sample integers without replacement. + + Select n_samples integers from the set [0, n_population) without + replacement. + + + Parameters + ---------- + n_population : int, + The size of the set to sample from. + + n_samples : int, + The number of integer to sample. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + method : "auto", "tracking_selection" or "reservoir_sampling" + If method == "auto", an algorithm is automatically selected. + The subset of selected integer is not randomized. + + If method =="tracking_selection", a set based implementation is used + which is suitable for `n_samples` <<< `n_population`. + + If method == "reservoir_sampling", a reservoir sampling algorithm is + used which is suitable for high memory constraint or when + O(`n_samples`) ~ O(`n_population`). + The subset of selected integer is not randomized. + + If method == "pool", a pool based algorithm is particularly fast, even + faster than the tracking selection method. Hovewer, a vector containing + the entire population has to be initialized. + If n_samples ~ n_population, the reservoir sampling method is faster. + + Returns + ------- + out : array of size (n_samples, ) + The sampled subsets of integer. The subset of selected integer might + not be randomized, see the method argument. + """ + _sample_without_replacement_check_input(n_population, n_samples) + + all_methods = ("auto", "tracking_selection", "reservoir_sampling", "pool") + + if method == "auto" or method == "tracking_selection": + # TODO the pool based method can also be used. + # however, it requires special benchmark to take into account + # the memory requirement of the array vs the set. + ratio = n_samples / n_population if n_population != 0.0 else 1.0 + + # The value 0.2 has been determined through benchmarking. + if ratio < 0.2: + return _sample_without_replacement_with_tracking_selection( + n_population, n_samples, random_state) + else: + return _sample_without_replacement_with_reservoir_sampling( + n_population, n_samples, random_state) + + elif method == "reservoir_sampling": + return _sample_without_replacement_with_reservoir_sampling( + n_population, n_samples, random_state) + + elif method == "pool": + return _sample_without_replacement_with_pool(n_population, n_samples, + random_state) + else: + raise ValueError('Expected a method name in %s, got %s. ' + % (all_methods, method)) diff --git a/sklearn/utils/_scipy_sparse_lsqr_backport.py b/sklearn/utils/_scipy_sparse_lsqr_backport.py new file mode 100644 index 0000000000000..7ebb24d905e9e --- /dev/null +++ b/sklearn/utils/_scipy_sparse_lsqr_backport.py @@ -0,0 +1,508 @@ +"""Sparse Equations and Least Squares. + +The original Fortran code was written by C. C. Paige and M. A. Saunders as +described in + +C. C. Paige and M. A. Saunders, LSQR: An algorithm for sparse linear +equations and sparse least squares, TOMS 8(1), 43--71 (1982). + +C. C. Paige and M. A. Saunders, Algorithm 583; LSQR: Sparse linear +equations and least-squares problems, TOMS 8(2), 195--209 (1982). + +It is licensed under the following BSD license: + +Copyright (c) 2006, Systems Optimization Laboratory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of Stanford University nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The Fortran code was translated to Python for use in CVXOPT by Jeffery +Kline with contributions by Mridul Aanjaneya and Bob Myhill. + +Adapted for SciPy by Stefan van der Walt. + +""" + +from __future__ import division, print_function, absolute_import + +__all__ = ['lsqr'] + +import numpy as np +from math import sqrt +from scipy.sparse.linalg.interface import aslinearoperator + +eps = np.finfo(np.float64).eps + + +def _sym_ortho(a, b): + """ + Stable implementation of Givens rotation. + + Notes + ----- + The routine 'SymOrtho' was added for numerical stability. This is + recommended by S.-C. Choi in [1]_. It removes the unpleasant potential of + ``1/eps`` in some important places (see, for example text following + "Compute the next plane rotation Qk" in minres.py). + + References + ---------- + .. [1] S.-C. Choi, "Iterative Methods for Singular Linear Equations + and Least-Squares Problems", Dissertation, + http://www.stanford.edu/group/SOL/dissertations/sou-cheng-choi-thesis.pdf + + """ + if b == 0: + return np.sign(a), 0, abs(a) + elif a == 0: + return 0, np.sign(b), abs(b) + elif abs(b) > abs(a): + tau = a / b + s = np.sign(b) / sqrt(1 + tau * tau) + c = s * tau + r = b / s + else: + tau = b / a + c = np.sign(a) / sqrt(1+tau*tau) + s = c * tau + r = a / c + return c, s, r + + +def lsqr(A, b, damp=0.0, atol=1e-8, btol=1e-8, conlim=1e8, + iter_lim=None, show=False, calc_var=False): + """Find the least-squares solution to a large, sparse, linear system + of equations. + + The function solves ``Ax = b`` or ``min ||b - Ax||^2`` or + ``min ||Ax - b||^2 + d^2 ||x||^2``. + + The matrix A may be square or rectangular (over-determined or + under-determined), and may have any rank. + + :: + + 1. Unsymmetric equations -- solve A*x = b + + 2. Linear least squares -- solve A*x = b + in the least-squares sense + + 3. Damped least squares -- solve ( A )*x = ( b ) + ( damp*I ) ( 0 ) + in the least-squares sense + + Parameters + ---------- + A : {sparse matrix, ndarray, LinearOperatorLinear} + Representation of an m-by-n matrix. It is required that + the linear operator can produce ``Ax`` and ``A^T x``. + b : (m,) ndarray + Right-hand side vector ``b``. + damp : float + Damping coefficient. + atol, btol : float, default 1.0e-8 + Stopping tolerances. If both are 1.0e-9 (say), the final + residual norm should be accurate to about 9 digits. (The + final x will usually have fewer correct digits, depending on + cond(A) and the size of damp.) + conlim : float + Another stopping tolerance. lsqr terminates if an estimate of + ``cond(A)`` exceeds `conlim`. For compatible systems ``Ax = + b``, `conlim` could be as large as 1.0e+12 (say). For + least-squares problems, conlim should be less than 1.0e+8. + Maximum precision can be obtained by setting ``atol = btol = + conlim = zero``, but the number of iterations may then be + excessive. + iter_lim : int + Explicit limitation on number of iterations (for safety). + show : bool + Display an iteration log. + calc_var : bool + Whether to estimate diagonals of ``(A'A + damp^2*I)^{-1}``. + + Returns + ------- + x : ndarray of float + The final solution. + istop : int + Gives the reason for termination. + 1 means x is an approximate solution to Ax = b. + 2 means x approximately solves the least-squares problem. + itn : int + Iteration number upon termination. + r1norm : float + ``norm(r)``, where ``r = b - Ax``. + r2norm : float + ``sqrt( norm(r)^2 + damp^2 * norm(x)^2 )``. Equal to `r1norm` if + ``damp == 0``. + anorm : float + Estimate of Frobenius norm of ``Abar = [[A]; [damp*I]]``. + acond : float + Estimate of ``cond(Abar)``. + arnorm : float + Estimate of ``norm(A'*r - damp^2*x)``. + xnorm : float + ``norm(x)`` + var : ndarray of float + If ``calc_var`` is True, estimates all diagonals of + ``(A'A)^{-1}`` (if ``damp == 0``) or more generally ``(A'A + + damp^2*I)^{-1}``. This is well defined if A has full column + rank or ``damp > 0``. (Not sure what var means if ``rank(A) + < n`` and ``damp = 0.``) + + Notes + ----- + LSQR uses an iterative method to approximate the solution. The + number of iterations required to reach a certain accuracy depends + strongly on the scaling of the problem. Poor scaling of the rows + or columns of A should therefore be avoided where possible. + + For example, in problem 1 the solution is unaltered by + row-scaling. If a row of A is very small or large compared to + the other rows of A, the corresponding row of ( A b ) should be + scaled up or down. + + In problems 1 and 2, the solution x is easily recovered + following column-scaling. Unless better information is known, + the nonzero columns of A should be scaled so that they all have + the same Euclidean norm (e.g., 1.0). + + In problem 3, there is no freedom to re-scale if damp is + nonzero. However, the value of damp should be assigned only + after attention has been paid to the scaling of A. + + The parameter damp is intended to help regularize + ill-conditioned systems, by preventing the true solution from + being very large. Another aid to regularization is provided by + the parameter acond, which may be used to terminate iterations + before the computed solution becomes very large. + + If some initial estimate ``x0`` is known and if ``damp == 0``, + one could proceed as follows: + + 1. Compute a residual vector ``r0 = b - A*x0``. + 2. Use LSQR to solve the system ``A*dx = r0``. + 3. Add the correction dx to obtain a final solution ``x = x0 + dx``. + + This requires that ``x0`` be available before and after the call + to LSQR. To judge the benefits, suppose LSQR takes k1 iterations + to solve A*x = b and k2 iterations to solve A*dx = r0. + If x0 is "good", norm(r0) will be smaller than norm(b). + If the same stopping tolerances atol and btol are used for each + system, k1 and k2 will be similar, but the final solution x0 + dx + should be more accurate. The only way to reduce the total work + is to use a larger stopping tolerance for the second system. + If some value btol is suitable for A*x = b, the larger value + btol*norm(b)/norm(r0) should be suitable for A*dx = r0. + + Preconditioning is another way to reduce the number of iterations. + If it is possible to solve a related system ``M*x = b`` + efficiently, where M approximates A in some helpful way (e.g. M - + A has low rank or its elements are small relative to those of A), + LSQR may converge more rapidly on the system ``A*M(inverse)*z = + b``, after which x can be recovered by solving M*x = z. + + If A is symmetric, LSQR should not be used! + + Alternatives are the symmetric conjugate-gradient method (cg) + and/or SYMMLQ. SYMMLQ is an implementation of symmetric cg that + applies to any symmetric A and will converge more rapidly than + LSQR. If A is positive definite, there are other implementations + of symmetric cg that require slightly less work per iteration than + SYMMLQ (but will take the same number of iterations). + + References + ---------- + .. [1] C. C. Paige and M. A. Saunders (1982a). + "LSQR: An algorithm for sparse linear equations and + sparse least squares", ACM TOMS 8(1), 43-71. + .. [2] C. C. Paige and M. A. Saunders (1982b). + "Algorithm 583. LSQR: Sparse linear equations and least + squares problems", ACM TOMS 8(2), 195-209. + .. [3] M. A. Saunders (1995). "Solution of sparse rectangular + systems using LSQR and CRAIG", BIT 35, 588-604. + + """ + A = aslinearoperator(A) + if len(b.shape) > 1: + b = b.squeeze() + + m, n = A.shape + if iter_lim is None: + iter_lim = 2 * n + var = np.zeros(n) + + msg = ('The exact solution is x = 0 ', + 'Ax - b is small enough, given atol, btol ', + 'The least-squares solution is good enough, given atol ', + 'The estimate of cond(Abar) has exceeded conlim ', + 'Ax - b is small enough for this machine ', + 'The least-squares solution is good enough for this machine', + 'Cond(Abar) seems to be too large for this machine ', + 'The iteration limit has been reached ') + + if show: + print(' ') + print('LSQR Least-squares solution of Ax = b') + str1 = 'The matrix A has %8g rows and %8g cols' % (m, n) + str2 = 'damp = %20.14e calc_var = %8g' % (damp, calc_var) + str3 = 'atol = %8.2e conlim = %8.2e' % (atol, conlim) + str4 = 'btol = %8.2e iter_lim = %8g' % (btol, iter_lim) + print(str1) + print(str2) + print(str3) + print(str4) + + itn = 0 + istop = 0 + nstop = 0 + ctol = 0 + if conlim > 0: + ctol = 1/conlim + anorm = 0 + acond = 0 + dampsq = damp**2 + ddnorm = 0 + res2 = 0 + xnorm = 0 + xxnorm = 0 + z = 0 + cs2 = -1 + sn2 = 0 + + """ + Set up the first vectors u and v for the bidiagonalization. + These satisfy beta*u = b, alfa*v = A'u. + """ + __xm = np.zeros(m) # a matrix for temporary holding + __xn = np.zeros(n) # a matrix for temporary holding + v = np.zeros(n) + u = b + x = np.zeros(n) + alfa = 0 + beta = np.linalg.norm(u) + w = np.zeros(n) + + if beta > 0: + u = (1/beta) * u + v = A.rmatvec(u) + alfa = np.linalg.norm(v) + + if alfa > 0: + v = (1/alfa) * v + w = v.copy() + + rhobar = alfa + phibar = beta + bnorm = beta + rnorm = beta + r1norm = rnorm + r2norm = rnorm + + # Reverse the order here from the original matlab code because + # there was an error on return when arnorm==0 + arnorm = alfa * beta + if arnorm == 0: + print(msg[0]) + return x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var + + head1 = ' Itn x[0] r1norm r2norm ' + head2 = ' Compatible LS Norm A Cond A' + + if show: + print(' ') + print(head1, head2) + test1 = 1 + test2 = alfa / beta + str1 = '%6g %12.5e' % (itn, x[0]) + str2 = ' %10.3e %10.3e' % (r1norm, r2norm) + str3 = ' %8.1e %8.1e' % (test1, test2) + print(str1, str2, str3) + + # Main iteration loop. + while itn < iter_lim: + itn = itn + 1 + """ + % Perform the next step of the bidiagonalization to obtain the + % next beta, u, alfa, v. These satisfy the relations + % beta*u = a*v - alfa*u, + % alfa*v = A'*u - beta*v. + """ + u = A.matvec(v) - alfa * u + beta = np.linalg.norm(u) + + if beta > 0: + u = (1/beta) * u + anorm = sqrt(anorm**2 + alfa**2 + beta**2 + damp**2) + v = A.rmatvec(u) - beta * v + alfa = np.linalg.norm(v) + if alfa > 0: + v = (1 / alfa) * v + + # Use a plane rotation to eliminate the damping parameter. + # This alters the diagonal (rhobar) of the lower-bidiagonal matrix. + rhobar1 = sqrt(rhobar**2 + damp**2) + cs1 = rhobar / rhobar1 + sn1 = damp / rhobar1 + psi = sn1 * phibar + phibar = cs1 * phibar + + # Use a plane rotation to eliminate the subdiagonal element (beta) + # of the lower-bidiagonal matrix, giving an upper-bidiagonal matrix. + cs, sn, rho = _sym_ortho(rhobar1, beta) + + theta = sn * alfa + rhobar = -cs * alfa + phi = cs * phibar + phibar = sn * phibar + tau = sn * phi + + # Update x and w. + t1 = phi / rho + t2 = -theta / rho + dk = (1 / rho) * w + + x = x + t1 * w + w = v + t2 * w + ddnorm = ddnorm + np.linalg.norm(dk)**2 + + if calc_var: + var = var + dk**2 + + # Use a plane rotation on the right to eliminate the + # super-diagonal element (theta) of the upper-bidiagonal matrix. + # Then use the result to estimate norm(x). + delta = sn2 * rho + gambar = -cs2 * rho + rhs = phi - delta * z + zbar = rhs / gambar + xnorm = sqrt(xxnorm + zbar**2) + gamma = sqrt(gambar**2 + theta**2) + cs2 = gambar / gamma + sn2 = theta / gamma + z = rhs / gamma + xxnorm = xxnorm + z**2 + + # Test for convergence. + # First, estimate the condition of the matrix Abar, + # and the norms of rbar and Abar'rbar. + acond = anorm * sqrt(ddnorm) + res1 = phibar**2 + res2 = res2 + psi**2 + rnorm = sqrt(res1 + res2) + arnorm = alfa * abs(tau) + + # Distinguish between + # r1norm = ||b - Ax|| and + # r2norm = rnorm in current code + # = sqrt(r1norm^2 + damp^2*||x||^2). + # Estimate r1norm from + # r1norm = sqrt(r2norm^2 - damp^2*||x||^2). + # Although there is cancellation, it might be accurate enough. + r1sq = rnorm**2 - dampsq * xxnorm + r1norm = sqrt(abs(r1sq)) + if r1sq < 0: + r1norm = -r1norm + r2norm = rnorm + + # Now use these norms to estimate certain other quantities, + # some of which will be small near a solution. + test1 = rnorm / bnorm + test2 = arnorm / (anorm * rnorm + eps) + test3 = 1 / (acond + eps) + t1 = test1 / (1 + anorm * xnorm / bnorm) + rtol = btol + atol * anorm * xnorm / bnorm + + # The following tests guard against extremely small values of + # atol, btol or ctol. (The user may have set any or all of + # the parameters atol, btol, conlim to 0.) + # The effect is equivalent to the normal tests using + # atol = eps, btol = eps, conlim = 1/eps. + if itn >= iter_lim: + istop = 7 + if 1 + test3 <= 1: + istop = 6 + if 1 + test2 <= 1: + istop = 5 + if 1 + t1 <= 1: + istop = 4 + + # Allow for tolerances set by the user. + if test3 <= ctol: + istop = 3 + if test2 <= atol: + istop = 2 + if test1 <= rtol: + istop = 1 + + # See if it is time to print something. + prnt = False + if n <= 40: + prnt = True + if itn <= 10: + prnt = True + if itn >= iter_lim-10: + prnt = True + # if itn%10 == 0: prnt = True + if test3 <= 2*ctol: + prnt = True + if test2 <= 10*atol: + prnt = True + if test1 <= 10*rtol: + prnt = True + if istop != 0: + prnt = True + + if prnt: + if show: + str1 = '%6g %12.5e' % (itn, x[0]) + str2 = ' %10.3e %10.3e' % (r1norm, r2norm) + str3 = ' %8.1e %8.1e' % (test1, test2) + str4 = ' %8.1e %8.1e' % (anorm, acond) + print(str1, str2, str3, str4) + + if istop != 0: + break + + # End of iteration loop. + # Print the stopping condition. + if show: + print(' ') + print('LSQR finished') + print(msg[istop]) + print(' ') + str1 = 'istop =%8g r1norm =%8.1e' % (istop, r1norm) + str2 = 'anorm =%8.1e arnorm =%8.1e' % (anorm, arnorm) + str3 = 'itn =%8g r2norm =%8.1e' % (itn, r2norm) + str4 = 'acond =%8.1e xnorm =%8.1e' % (acond, xnorm) + print(str1 + ' ' + str2) + print(str3 + ' ' + str4) + print(' ') + + return x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var diff --git a/sklearn/utils/arpack.py b/sklearn/utils/arpack.py index 166236e3987b5..43e42d9437f79 100644 --- a/sklearn/utils/arpack.py +++ b/sklearn/utils/arpack.py @@ -45,6 +45,7 @@ __docformat__ = "restructuredtext en" __all__ = ['eigs', 'eigsh', 'svds', 'ArpackError', 'ArpackNoConvergence'] +import warnings from scipy.sparse.linalg.eigen.arpack import _arpack import numpy as np @@ -81,9 +82,9 @@ -8: "Error return from LAPACK eigenvalue calculation;", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4.", - -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatable.", + -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", - -13: "NEV and WHICH = 'BE' are incompatable.", + -13: "NEV and WHICH = 'BE' are incompatible.", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " @@ -118,9 +119,9 @@ "Informational error from LAPACK routine dsteqr .", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4,5.", - -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatable.", + -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", - -13: "NEV and WHICH = 'BE' are incompatable. ", + -13: "NEV and WHICH = 'BE' are incompatible. ", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " @@ -137,7 +138,7 @@ "increase the size of the arrays DR and DI to have " "dimension at least dimension NCV and allocate at least NCV " "columns for Z. NOTE: Not necessary if Z and V share " - "the same space. Please notify the authors if this error" + "the same space. Please notify the authors if this error " "occurs.", -1: "N must be positive.", -2: "NEV must be positive.", @@ -208,8 +209,7 @@ "converged Ritz values than ZNAUPD got. This " "indicates the user probably made an error in passing " "data from ZNAUPD to ZNEUPD or that the data was " - "modified before entering ZNEUPD" -} + "modified before entering ZNEUPD"} CNEUPD_ERRORS = ZNEUPD_ERRORS.copy() CNEUPD_ERRORS[-14] = ("CNAUPD did not find any eigenvalues to sufficient " @@ -763,11 +763,11 @@ def extract(self, return_eigenvectors): di = np.zeros(k + 1, self.tp) zr = np.zeros((n, k + 1), self.tp) dr, di, zr, ierr = \ - self._arpack_extract(return_eigenvectors, - howmny, sselect, sigmar, sigmai, workev, - self.bmat, self.which, k, self.tol, self.resid, - self.v, self.iparam, self.ipntr, - self.workd, self.workl, self.info) + self._arpack_extract( + return_eigenvectors, howmny, sselect, sigmar, sigmai, + workev, self.bmat, self.which, k, self.tol, self.resid, + self.v, self.iparam, self.ipntr, self.workd, self.workl, + self.info) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) nreturned = self.iparam[4] # number of good eigenvalues returned @@ -862,11 +862,11 @@ def extract(self, return_eigenvectors): else: # complex is so much simpler... d, z, ierr =\ - self._arpack_extract(return_eigenvectors, - howmny, sselect, self.sigma, workev, - self.bmat, self.which, k, self.tol, self.resid, - self.v, self.iparam, self.ipntr, - self.workd, self.workl, self.rwork, ierr) + self._arpack_extract( + return_eigenvectors, howmny, sselect, self.sigma, workev, + self.bmat, self.which, k, self.tol, self.resid, self.v, + self.iparam, self.ipntr, self.workd, self.workl, + self.rwork, ierr) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) @@ -1018,7 +1018,7 @@ def get_OPinv_matvec(A, M, sigma, symmetric=False, tol=0): #M is the identity matrix if isdense(A): if (np.issubdtype(A.dtype, np.complexfloating) - or np.imag(sigma) == 0): + or np.imag(sigma) == 0): A = np.copy(A) else: A = A + 0j @@ -1030,14 +1030,14 @@ def get_OPinv_matvec(A, M, sigma, symmetric=False, tol=0): A = A.T return SpLuInv(A.tocsc()).matvec else: - return IterOpInv(_aslinearoperator_with_dtype(A), - M, sigma, tol=tol).matvec + return IterOpInv(_aslinearoperator_with_dtype(A), M, sigma, + tol=tol).matvec else: if ((not isdense(A) and not isspmatrix(A)) or - (not isdense(M) and not isspmatrix(M))): + (not isdense(M) and not isspmatrix(M))): return IterOpInv(_aslinearoperator_with_dtype(A), - _aslinearoperator_with_dtype(M), - sigma, tol=tol).matvec + _aslinearoperator_with_dtype(M), sigma, + tol=tol).matvec elif isdense(A) or isdense(M): return LuInv(A - sigma * M).matvec else: @@ -1047,9 +1047,9 @@ def get_OPinv_matvec(A, M, sigma, symmetric=False, tol=0): return SpLuInv(OP.tocsc()).matvec -def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, - ncv=None, maxiter=None, tol=0, return_eigenvectors=True, - Minv=None, OPinv=None, OPpart=None): +def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, + maxiter=None, tol=0, return_eigenvectors=True, Minv=None, OPinv=None, + OPpart=None): """ Find k eigenvalues and eigenvectors of the square matrix A. @@ -1062,23 +1062,17 @@ def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, Parameters ---------- - A : An N x N matrix, array, sparse matrix, or LinearOperator representing - the operation A * x, where A is a real or complex square matrix. - k : integer + A : An N x N matrix, array, sparse matrix, or LinearOperator representing \ + the operation A * x, where A is a real or complex square matrix. + + k : int, default 6 The number of eigenvalues and eigenvectors desired. `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. - Returns - ------- - w : array - Array of k eigenvalues. - v : array - An array of `k` eigenvectors. - ``v[:, i]`` is the eigenvector corresponding to the eigenvalue w[i]. + return_eigenvectors : boolean, default True + Whether to return the eigenvectors along with the eigenvalues. - Other Parameters - ---------------- M : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation M*x for the generalized eigenvalue problem ``A * x = w * M * x`` @@ -1092,6 +1086,7 @@ def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, iterative solver for a general linear operator. Alternatively, the user can supply the matrix or operator Minv, which gives x = Minv * b = M^-1 * b + sigma : real or complex Find eigenvalues near sigma using shift-invert mode. This requires an operator to compute the solution of the linear system @@ -1111,11 +1106,14 @@ def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, w'[i] = 1/2i * [ 1/(w[i]-sigma) - 1/(w[i]-conj(sigma)) ] * If A is complex, w'[i] = 1/(w[i]-sigma) + v0 : array Starting vector for iteration. + ncv : integer The number of Lanczos vectors generated `ncv` must be greater than `k`; it is recommended that ``ncv > 2*k``. + which : string ['LM' | 'SM' | 'LR' | 'SR' | 'LI' | 'SI'] Which `k` eigenvectors and eigenvalues to find: - 'LM' : largest magnitude @@ -1128,20 +1126,34 @@ def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, (see discussion in 'sigma', above). ARPACK is generally better at finding large values than small values. If small eigenvalues are desired, consider using shift-invert mode for better performance. + maxiter : integer Maximum number of Arnoldi update iterations allowed + tol : float Relative accuracy for eigenvalues (stopping criterion) The default value of 0 implies machine precision. + return_eigenvectors : boolean Return eigenvectors (True) in addition to eigenvalues + Minv : N x N matrix, array, sparse matrix, or linear operator See notes in M, above. + OPinv : N x N matrix, array, sparse matrix, or linear operator See notes in sigma, above. OPpart : 'r' or 'i'. See notes in sigma, above + Returns + ------- + w : array + Array of k eigenvalues. + + v : array + An array of `k` eigenvectors. + ``v[:, i]`` is the eigenvector corresponding to the eigenvalue w[i]. + Raises ------ ArpackNoConvergence @@ -1188,7 +1200,6 @@ def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): - import warnings warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] @@ -1263,9 +1274,9 @@ def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, return params.extract(return_eigenvectors) -def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, - ncv=None, maxiter=None, tol=0, return_eigenvectors=True, - Minv=None, OPinv=None, mode='normal'): +def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, + maxiter=None, tol=0, return_eigenvectors=True, Minv=None, + OPinv=None, mode='normal'): """ Find k eigenvalues and eigenvectors of the real symmetric square matrix or complex hermitian matrix A. @@ -1288,16 +1299,6 @@ def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. - Returns - ------- - w : array - Array of k eigenvalues - v : array - An array of k eigenvectors - The v[i] is the eigenvector corresponding to the eigenvector w[i] - - Other Parameters - ---------------- M : An N x N matrix, array, sparse matrix, or linear operator representing the operation M * x for the generalized eigenvalue problem ``A * x = w * M * x``. @@ -1338,7 +1339,7 @@ def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, it is recommended that ncv > 2*k which : string ['LM' | 'SM' | 'LA' | 'SA' | 'BE'] If A is a complex hermitian matrix, 'BE' is invalid. - Which `k` eigenvectors and eigenvalues to find: + Which `k` eigenvectors and eigenvalues to find - 'LM' : Largest (in magnitude) eigenvalues - 'SM' : Smallest (in magnitude) eigenvalues - 'LA' : Largest (algebraic) eigenvalues @@ -1382,6 +1383,14 @@ def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, the keyword 'which', and can also impact the stability of convergence (see [2] for a discussion) + Returns + ------- + w : array + Array of k eigenvalues + v : array + An array of k eigenvectors + The v[i] is the eigenvector corresponding to the eigenvector w[i] + Raises ------ ArpackNoConvergence @@ -1409,7 +1418,7 @@ def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, >>> vals, vecs = eigsh(id, k=6) >>> vals # doctest: +SKIP array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]) - >>> vecs.shape + >>> print(vecs.shape) (13, 6) References @@ -1447,7 +1456,6 @@ def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): - import warnings warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] @@ -1580,22 +1588,36 @@ def _svds(A, k=6, ncv=None, tol=0): XH = A X = herm(A) - def matvec_XH_X(x): - return XH.dot(X.dot(x)) + if hasattr(XH, 'dot'): + def matvec_XH_X(x): + return XH.dot(X.dot(x)) + else: + def matvec_XH_X(x): + return np.dot(XH, np.dot(X, x)) XH_X = LinearOperator(matvec=matvec_XH_X, dtype=X.dtype, shape=(X.shape[1], X.shape[1])) - eigvals, eigvec = eigensolver(XH_X, k=k, tol=tol ** 2) + # Ignore deprecation warnings here: dot on matrices is deprecated, + # but this code is a backport anyhow + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + eigvals, eigvec = eigensolver(XH_X, k=k, tol=tol ** 2) s = np.sqrt(eigvals) if n > m: v = eigvec - u = X.dot(v) / s + if hasattr(X, 'dot'): + u = X.dot(v) / s + else: + u = np.dot(X, v) / s vh = herm(v) else: u = eigvec - vh = herm(X.dot(u) / s) + if hasattr(X, 'dot'): + vh = herm(X.dot(u) / s) + else: + vh = herm(np.dot(X, u) / s) return u, s, vh diff --git a/sklearn/utils/arraybuilder.pyx b/sklearn/utils/arraybuilder.pyx deleted file mode 100644 index be37e59481670..0000000000000 --- a/sklearn/utils/arraybuilder.pyx +++ /dev/null @@ -1,47 +0,0 @@ -# Author: Lars Buitinck -# License: BSD-style - -cimport cython -cimport numpy as np -import numpy as np - - -cdef class ArrayBuilder(object): - """Helper class to incrementally build a 1-d numpy.ndarray""" - # Or: let's reinvent the wheel! - - GROWTH_FACTOR = 1.5 - - cdef Py_ssize_t _nelems - cdef object _arr # object because we don't know the dtype statically - - def __init__(self, dtype, initial_capacity=256): - assert self.GROWTH_FACTOR > 1 - assert initial_capacity >= 2 - self._arr = np.empty(initial_capacity, dtype=dtype) - self._nelems = 0 - - def __len__(self): - return self._nelems - - @cython.boundscheck(False) - def append(self, x): - """Append a single value. - - Complexity: amortized O(1). - """ - if self._nelems == self._arr.size: - self._grow() - self._arr[self._nelems] = x - self._nelems += 1 - - def get(self): - """Return the constructed array. - - Don't use an ArrayBuilder after calling this method. - """ - self._arr.resize(self._nelems) - return self._arr - - cdef _grow(self): - self._arr.resize(self._arr.size * self.GROWTH_FACTOR) diff --git a/sklearn/utils/arrayfuncs.c b/sklearn/utils/arrayfuncs.c index 8c25250823664..832605f79b4c8 100644 --- a/sklearn/utils/arrayfuncs.c +++ b/sklearn/utils/arrayfuncs.c @@ -1,16 +1,29 @@ -/* Generated by Cython 0.15 on Sat Sep 3 13:08:58 2011 */ +/* Generated by Cython 0.20.1 on Wed Mar 5 14:00:37 2014 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. #else - +#define CYTHON_ABI "0_20_1" #include /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -22,36 +35,50 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - -#if PY_VERSION_HEX < 0x02040000 - #define METH_COEXIST 0 - #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) - #define PyDict_Contains(d,o) PySequence_Contains(d,o) +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if CYTHON_COMPILING_IN_PYPY +#define Py_OptimizeFlag 0 #endif - #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -59,7 +86,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -73,7 +99,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -83,24 +108,74 @@ #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT) + #define Py_TPFLAGS_IS_ABSTRACT 0 +#endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -108,7 +183,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -127,7 +201,14 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -135,9 +216,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -153,13 +232,12 @@ #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - -#if PY_VERSION_HEX < 0x03020000 +#if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong @@ -167,16 +245,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -195,11 +263,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -209,7 +275,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -217,6 +282,49 @@ #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus @@ -232,13 +340,13 @@ #include #define __PYX_HAVE__sklearn__utils__arrayfuncs #define __PYX_HAVE_API__sklearn__utils__arrayfuncs +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" -#include "cblas.h" #include "float.h" -#include "src/cholesky_delete.c" +#include "src/cholesky_delete.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -247,21 +355,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -269,31 +362,148 @@ # else # define CYTHON_UNUSED # endif -# elif defined(__ICC) || defined(__INTEL_COMPILER) +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif #ifdef __GNUC__ @@ -309,8 +519,9 @@ static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -319,7 +530,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -329,7 +539,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -337,18 +546,19 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { "arrayfuncs.pyx", - "numpy.pxd", + "__init__.pxd", + "type.pxd", }; -/* "numpy.pxd":719 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -357,7 +567,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -366,7 +576,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -375,7 +585,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -384,7 +594,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -393,7 +603,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -402,7 +612,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -411,7 +621,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -420,7 +630,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -429,7 +639,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -438,7 +648,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -447,7 +657,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -456,7 +666,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -465,7 +675,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -474,7 +684,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -483,7 +693,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -492,7 +702,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -501,7 +711,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -510,7 +720,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -519,7 +729,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -528,7 +738,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -537,15 +747,14 @@ typedef npy_double __pyx_t_5numpy_double_t; */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; -/* "sklearn/utils/arrayfuncs.pyx":44 - * int float_cholesky_delete (int m, int n, float *L, int go_out) +/* "sklearn/utils/arrayfuncs.pyx":16 + * int cholesky_delete_flt(int m, int n, float *L, int go_out) * * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< * * */ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_10arrayfuncs_DOUBLE; - #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -566,9 +775,10 @@ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_10arrayfuncs_DOUBLE; typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ -/* "numpy.pxd":758 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -577,7 +787,7 @@ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_10arrayfuncs_DOUBLE; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -586,7 +796,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -595,7 +805,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -603,12 +813,9 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; - - #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -621,8 +828,21 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -633,7 +853,7 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -644,12 +864,55 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); /*proto*/ +#include + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals +#else +#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ @@ -658,34 +921,27 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ - -#include - -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ - -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals -#else -#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals -#endif +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -699,8 +955,7 @@ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - -#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else @@ -786,57 +1041,61 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); +static int __Pyx_check_binary_version(void); -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif -static int __Pyx_check_binary_version(void); +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -847,19 +1106,12 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ - -/* Module declarations from 'cython.cython.view' */ /* Module declarations from 'cython' */ +/* Module declarations from 'libc.float' */ + /* Module declarations from 'sklearn.utils.arrayfuncs' */ static float __pyx_f_7sklearn_5utils_10arrayfuncs__float_min_pos(float *, Py_ssize_t); /*proto*/ static double __pyx_f_7sklearn_5utils_10arrayfuncs__double_min_pos(double *, Py_ssize_t); /*proto*/ @@ -869,102 +1121,135 @@ int __pyx_module_is_main_sklearn__utils__arrayfuncs = 0; /* Implementation of 'sklearn.utils.arrayfuncs' */ static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_TypeError; static PyObject *__pyx_builtin_RuntimeError; -static char __pyx_k_1[] = "Unsupported dtype for array X"; -static char __pyx_k_3[] = "Unsupported or inconsistent dtype in arrays X, y"; -static char __pyx_k_5[] = "ndarray is not C contiguous"; -static char __pyx_k_7[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_9[] = "Non-native byte order not supported"; -static char __pyx_k_11[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_12[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_15[] = "Format string allocated too short."; -static char __pyx_k_17[] = "\nSmall collection of auxiliary functions that operate on arrays\n\n"; -static char __pyx_k_18[] = "sklearn.utils.arrayfuncs"; -static char __pyx_k__B[] = "B"; -static char __pyx_k__H[] = "H"; -static char __pyx_k__I[] = "I"; -static char __pyx_k__L[] = "L"; -static char __pyx_k__O[] = "O"; -static char __pyx_k__Q[] = "Q"; -static char __pyx_k__X[] = "X"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__d[] = "d"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__g[] = "g"; -static char __pyx_k__h[] = "h"; -static char __pyx_k__i[] = "i"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__q[] = "q"; -static char __pyx_k__y[] = "y"; -static char __pyx_k__Zd[] = "Zd"; -static char __pyx_k__Zf[] = "Zf"; -static char __pyx_k__Zg[] = "Zg"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__name[] = "name"; -static char __pyx_k__size[] = "size"; -static char __pyx_k__dtype[] = "dtype"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__range[] = "range"; -static char __pyx_k__go_out[] = "go_out"; -static char __pyx_k__float32[] = "float32"; -static char __pyx_k__float64[] = "float64"; -static char __pyx_k__min_pos[] = "min_pos"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k__cholesky_delete[] = "cholesky_delete"; -static char __pyx_k__solve_triangular[] = "solve_triangular"; -static PyObject *__pyx_kp_s_1; -static PyObject *__pyx_kp_u_11; -static PyObject *__pyx_kp_u_12; -static PyObject *__pyx_kp_u_15; -static PyObject *__pyx_n_s_18; -static PyObject *__pyx_kp_s_3; -static PyObject *__pyx_kp_u_5; -static PyObject *__pyx_kp_u_7; -static PyObject *__pyx_kp_u_9; -static PyObject *__pyx_n_s__L; -static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s__X; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__cholesky_delete; -static PyObject *__pyx_n_s__dtype; -static PyObject *__pyx_n_s__float32; -static PyObject *__pyx_n_s__float64; -static PyObject *__pyx_n_s__go_out; -static PyObject *__pyx_n_s__min_pos; -static PyObject *__pyx_n_s__name; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__size; -static PyObject *__pyx_n_s__solve_triangular; -static PyObject *__pyx_n_s__y; -static PyObject *__pyx_int_15; -static PyObject *__pyx_k_tuple_2; -static PyObject *__pyx_k_tuple_4; -static PyObject *__pyx_k_tuple_6; -static PyObject *__pyx_k_tuple_8; -static PyObject *__pyx_k_tuple_10; -static PyObject *__pyx_k_tuple_13; -static PyObject *__pyx_k_tuple_14; -static PyObject *__pyx_k_tuple_16; - -/* "sklearn/utils/arrayfuncs.pyx":47 +static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_min_pos(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_2cholesky_delete(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_L, int __pyx_v_go_out); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static char __pyx_k_B[] = "B"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_X[] = "X"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_m[] = "m"; +static char __pyx_k_n[] = "n"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_name[] = "name"; +static char __pyx_k_size[] = "size"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_go_out[] = "go_out"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_float32[] = "float32"; +static char __pyx_k_float64[] = "float64"; +static char __pyx_k_min_pos[] = "min_pos"; +static char __pyx_k_TypeError[] = "TypeError"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_cholesky_delete[] = "cholesky_delete"; +static char __pyx_k_unsupported_dtype_r[] = "unsupported dtype %r."; +static char __pyx_k_sklearn_utils_arrayfuncs[] = "sklearn.utils.arrayfuncs"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_Unsupported_dtype_for_array_X[] = "Unsupported dtype for array X"; +static char __pyx_k_Small_collection_of_auxiliary_f[] = "\nSmall collection of auxiliary functions that operate on arrays\n\n"; +static char __pyx_k_home_larsb_src_scikit_learn_skl[] = "/home/larsb/src/scikit-learn/sklearn/utils/arrayfuncs.pyx"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_n_s_L; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_TypeError; +static PyObject *__pyx_kp_s_Unsupported_dtype_for_array_X; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_n_s_cholesky_delete; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_float32; +static PyObject *__pyx_n_s_float64; +static PyObject *__pyx_n_s_go_out; +static PyObject *__pyx_kp_s_home_larsb_src_scikit_learn_skl; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_m; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_min_pos; +static PyObject *__pyx_n_s_n; +static PyObject *__pyx_n_s_name; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_size; +static PyObject *__pyx_n_s_sklearn_utils_arrayfuncs; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_kp_s_unsupported_dtype_r; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__8; +static PyObject *__pyx_tuple__10; +static PyObject *__pyx_codeobj__9; +static PyObject *__pyx_codeobj__11; + +/* "sklearn/utils/arrayfuncs.pyx":22 * * * def min_pos(np.ndarray X): # <<<<<<<<<<<<<< * """ - * Find the minimum value of an array over positivie values - */ + * Find the minimum value of an array over positive values + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_10arrayfuncs_1min_pos(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ +static char __pyx_doc_7sklearn_5utils_10arrayfuncs_min_pos[] = "\n Find the minimum value of an array over positive values\n\n Returns a huge value if none of the values are positive\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_10arrayfuncs_1min_pos = {__Pyx_NAMESTR("min_pos"), (PyCFunction)__pyx_pw_7sklearn_5utils_10arrayfuncs_1min_pos, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10arrayfuncs_min_pos)}; +static PyObject *__pyx_pw_7sklearn_5utils_10arrayfuncs_1min_pos(PyObject *__pyx_self, PyObject *__pyx_v_X) { + CYTHON_UNUSED int __pyx_lineno = 0; + CYTHON_UNUSED const char *__pyx_filename = NULL; + CYTHON_UNUSED int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("min_pos (wrapper)", 0); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_10arrayfuncs_min_pos(__pyx_self, ((PyArrayObject *)__pyx_v_X)); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} -static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_min_pos(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ -static char __pyx_doc_7sklearn_5utils_10arrayfuncs_min_pos[] = "\n Find the minimum value of an array over positivie values\n\n Returns a huge value if none of the values are positive\n "; -static PyMethodDef __pyx_mdef_7sklearn_5utils_10arrayfuncs_min_pos = {__Pyx_NAMESTR("min_pos"), (PyCFunction)__pyx_pf_7sklearn_5utils_10arrayfuncs_min_pos, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10arrayfuncs_min_pos)}; -static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_min_pos(PyObject *__pyx_self, PyObject *__pyx_v_X) { +static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_min_pos(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_X) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -974,27 +1259,25 @@ static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_min_pos(PyObject *__pyx_s int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("min_pos"); - __pyx_self = __pyx_self; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RefNannySetupContext("min_pos", 0); - /* "sklearn/utils/arrayfuncs.pyx":53 + /* "sklearn/utils/arrayfuncs.pyx":28 * Returns a huge value if none of the values are positive * """ * if X.dtype.name == 'float32': # <<<<<<<<<<<<<< * return _float_min_pos( X.data, X.size) * elif X.dtype.name == 'float64': */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_X), __pyx_n_s_dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__name); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_name); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyString_Equals(__pyx_t_2, ((PyObject *)__pyx_n_s__float32), Py_EQ); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_t_2, __pyx_n_s_float32, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_3) { - /* "sklearn/utils/arrayfuncs.pyx":54 + /* "sklearn/utils/arrayfuncs.pyx":29 * """ * if X.dtype.name == 'float32': * return _float_min_pos( X.data, X.size) # <<<<<<<<<<<<<< @@ -1002,35 +1285,34 @@ static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_min_pos(PyObject *__pyx_s * return _double_min_pos( X.data, X.size) */ __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__size); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_X), __pyx_n_s_size); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyIndex_AsSsize_t(__pyx_t_2); if (unlikely((__pyx_t_4 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyIndex_AsSsize_t(__pyx_t_2); if (unlikely((__pyx_t_4 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(__pyx_f_7sklearn_5utils_10arrayfuncs__float_min_pos(((float *)((PyArrayObject *)__pyx_v_X)->data), __pyx_t_4)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyFloat_FromDouble(__pyx_f_7sklearn_5utils_10arrayfuncs__float_min_pos(((float *)__pyx_v_X->data), __pyx_t_4)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; - goto __pyx_L5; } - /* "sklearn/utils/arrayfuncs.pyx":55 + /* "sklearn/utils/arrayfuncs.pyx":30 * if X.dtype.name == 'float32': * return _float_min_pos( X.data, X.size) * elif X.dtype.name == 'float64': # <<<<<<<<<<<<<< * return _double_min_pos( X.data, X.size) * else: */ - __pyx_t_2 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__dtype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_X), __pyx_n_s_dtype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_3 = __Pyx_PyString_Equals(__pyx_t_1, ((PyObject *)__pyx_n_s__float64), Py_EQ); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_t_1, __pyx_n_s_float64, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_3) { - /* "sklearn/utils/arrayfuncs.pyx":56 + /* "sklearn/utils/arrayfuncs.pyx":31 * return _float_min_pos( X.data, X.size) * elif X.dtype.name == 'float64': * return _double_min_pos( X.data, X.size) # <<<<<<<<<<<<<< @@ -1038,36 +1320,41 @@ static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_min_pos(PyObject *__pyx_s * raise ValueError('Unsupported dtype for array X') */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyObject_GetAttr(__pyx_v_X, __pyx_n_s__size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_X), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyIndex_AsSsize_t(__pyx_t_1); if (unlikely((__pyx_t_4 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyIndex_AsSsize_t(__pyx_t_1); if (unlikely((__pyx_t_4 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyFloat_FromDouble(__pyx_f_7sklearn_5utils_10arrayfuncs__double_min_pos(((double *)((PyArrayObject *)__pyx_v_X)->data), __pyx_t_4)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyFloat_FromDouble(__pyx_f_7sklearn_5utils_10arrayfuncs__double_min_pos(((double *)__pyx_v_X->data), __pyx_t_4)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - goto __pyx_L5; } /*else*/ { - /* "sklearn/utils/arrayfuncs.pyx":58 + /* "sklearn/utils/arrayfuncs.pyx":33 * return _double_min_pos( X.data, X.size) * else: * raise ValueError('Unsupported dtype for array X') # <<<<<<<<<<<<<< * * */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L5:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "sklearn/utils/arrayfuncs.pyx":22 + * + * + * def min_pos(np.ndarray X): # <<<<<<<<<<<<<< + * """ + * Find the minimum value of an array over positive values + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); @@ -1079,10 +1366,10 @@ static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_min_pos(PyObject *__pyx_s return __pyx_r; } -/* "sklearn/utils/arrayfuncs.pyx":61 +/* "sklearn/utils/arrayfuncs.pyx":36 * * - * cdef float _float_min_pos (float *X, Py_ssize_t size): # <<<<<<<<<<<<<< + * cdef float _float_min_pos(float *X, Py_ssize_t size): # <<<<<<<<<<<<<< * cdef Py_ssize_t i * cdef float min_val = DBL_MAX */ @@ -1097,10 +1384,10 @@ static float __pyx_f_7sklearn_5utils_10arrayfuncs__float_min_pos(float *__pyx_v_ int __pyx_t_3; int __pyx_t_4; int __pyx_t_5; - __Pyx_RefNannySetupContext("_float_min_pos"); + __Pyx_RefNannySetupContext("_float_min_pos", 0); - /* "sklearn/utils/arrayfuncs.pyx":63 - * cdef float _float_min_pos (float *X, Py_ssize_t size): + /* "sklearn/utils/arrayfuncs.pyx":38 + * cdef float _float_min_pos(float *X, Py_ssize_t size): * cdef Py_ssize_t i * cdef float min_val = DBL_MAX # <<<<<<<<<<<<<< * for i in range(size): @@ -1108,7 +1395,7 @@ static float __pyx_f_7sklearn_5utils_10arrayfuncs__float_min_pos(float *__pyx_v_ */ __pyx_v_min_val = DBL_MAX; - /* "sklearn/utils/arrayfuncs.pyx":64 + /* "sklearn/utils/arrayfuncs.pyx":39 * cdef Py_ssize_t i * cdef float min_val = DBL_MAX * for i in range(size): # <<<<<<<<<<<<<< @@ -1119,23 +1406,23 @@ static float __pyx_f_7sklearn_5utils_10arrayfuncs__float_min_pos(float *__pyx_v_ for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; - /* "sklearn/utils/arrayfuncs.pyx":65 + /* "sklearn/utils/arrayfuncs.pyx":40 * cdef float min_val = DBL_MAX * for i in range(size): * if X[i] > 0. and X[i] < min_val: # <<<<<<<<<<<<<< * min_val = X[i] * return min_val */ - __pyx_t_3 = ((__pyx_v_X[__pyx_v_i]) > 0.); + __pyx_t_3 = (((__pyx_v_X[__pyx_v_i]) > 0.) != 0); if (__pyx_t_3) { - __pyx_t_4 = ((__pyx_v_X[__pyx_v_i]) < __pyx_v_min_val); + __pyx_t_4 = (((__pyx_v_X[__pyx_v_i]) < __pyx_v_min_val) != 0); __pyx_t_5 = __pyx_t_4; } else { __pyx_t_5 = __pyx_t_3; } if (__pyx_t_5) { - /* "sklearn/utils/arrayfuncs.pyx":66 + /* "sklearn/utils/arrayfuncs.pyx":41 * for i in range(size): * if X[i] > 0. and X[i] < min_val: * min_val = X[i] # <<<<<<<<<<<<<< @@ -1148,7 +1435,7 @@ static float __pyx_f_7sklearn_5utils_10arrayfuncs__float_min_pos(float *__pyx_v_ __pyx_L5:; } - /* "sklearn/utils/arrayfuncs.pyx":67 + /* "sklearn/utils/arrayfuncs.pyx":42 * if X[i] > 0. and X[i] < min_val: * min_val = X[i] * return min_val # <<<<<<<<<<<<<< @@ -1158,16 +1445,24 @@ static float __pyx_f_7sklearn_5utils_10arrayfuncs__float_min_pos(float *__pyx_v_ __pyx_r = __pyx_v_min_val; goto __pyx_L0; - __pyx_r = 0; + /* "sklearn/utils/arrayfuncs.pyx":36 + * + * + * cdef float _float_min_pos(float *X, Py_ssize_t size): # <<<<<<<<<<<<<< + * cdef Py_ssize_t i + * cdef float min_val = DBL_MAX + */ + + /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/utils/arrayfuncs.pyx":70 +/* "sklearn/utils/arrayfuncs.pyx":45 * * - * cdef double _double_min_pos (double *X, Py_ssize_t size): # <<<<<<<<<<<<<< + * cdef double _double_min_pos(double *X, Py_ssize_t size): # <<<<<<<<<<<<<< * cdef Py_ssize_t i * cdef np.float64_t min_val = FLT_MAX */ @@ -1182,10 +1477,10 @@ static double __pyx_f_7sklearn_5utils_10arrayfuncs__double_min_pos(double *__pyx int __pyx_t_3; int __pyx_t_4; int __pyx_t_5; - __Pyx_RefNannySetupContext("_double_min_pos"); + __Pyx_RefNannySetupContext("_double_min_pos", 0); - /* "sklearn/utils/arrayfuncs.pyx":72 - * cdef double _double_min_pos (double *X, Py_ssize_t size): + /* "sklearn/utils/arrayfuncs.pyx":47 + * cdef double _double_min_pos(double *X, Py_ssize_t size): * cdef Py_ssize_t i * cdef np.float64_t min_val = FLT_MAX # <<<<<<<<<<<<<< * for i in range(size): @@ -1193,7 +1488,7 @@ static double __pyx_f_7sklearn_5utils_10arrayfuncs__double_min_pos(double *__pyx */ __pyx_v_min_val = FLT_MAX; - /* "sklearn/utils/arrayfuncs.pyx":73 + /* "sklearn/utils/arrayfuncs.pyx":48 * cdef Py_ssize_t i * cdef np.float64_t min_val = FLT_MAX * for i in range(size): # <<<<<<<<<<<<<< @@ -1204,23 +1499,23 @@ static double __pyx_f_7sklearn_5utils_10arrayfuncs__double_min_pos(double *__pyx for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; - /* "sklearn/utils/arrayfuncs.pyx":74 + /* "sklearn/utils/arrayfuncs.pyx":49 * cdef np.float64_t min_val = FLT_MAX * for i in range(size): * if X[i] > 0. and X[i] < min_val: # <<<<<<<<<<<<<< * min_val = X[i] * return min_val */ - __pyx_t_3 = ((__pyx_v_X[__pyx_v_i]) > 0.); + __pyx_t_3 = (((__pyx_v_X[__pyx_v_i]) > 0.) != 0); if (__pyx_t_3) { - __pyx_t_4 = ((__pyx_v_X[__pyx_v_i]) < __pyx_v_min_val); + __pyx_t_4 = (((__pyx_v_X[__pyx_v_i]) < __pyx_v_min_val) != 0); __pyx_t_5 = __pyx_t_4; } else { __pyx_t_5 = __pyx_t_3; } if (__pyx_t_5) { - /* "sklearn/utils/arrayfuncs.pyx":75 + /* "sklearn/utils/arrayfuncs.pyx":50 * for i in range(size): * if X[i] > 0. and X[i] < min_val: * min_val = X[i] # <<<<<<<<<<<<<< @@ -1233,242 +1528,106 @@ static double __pyx_f_7sklearn_5utils_10arrayfuncs__double_min_pos(double *__pyx __pyx_L5:; } - /* "sklearn/utils/arrayfuncs.pyx":76 + /* "sklearn/utils/arrayfuncs.pyx":51 * if X[i] > 0. and X[i] < min_val: * min_val = X[i] * return min_val # <<<<<<<<<<<<<< * - * def solve_triangular (np.ndarray X, np.ndarray y): + * */ __pyx_r = __pyx_v_min_val; goto __pyx_L0; - __pyx_r = 0; + /* "sklearn/utils/arrayfuncs.pyx":45 + * + * + * cdef double _double_min_pos(double *X, Py_ssize_t size): # <<<<<<<<<<<<<< + * cdef Py_ssize_t i + * cdef np.float64_t min_val = FLT_MAX + */ + + /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/utils/arrayfuncs.pyx":78 - * return min_val +/* "sklearn/utils/arrayfuncs.pyx":55 * - * def solve_triangular (np.ndarray X, np.ndarray y): # <<<<<<<<<<<<<< - * """ - * Solves a triangular system (overwrites y) + * # we should be using np.npy_intp or Py_ssize_t for indices, but BLAS wants int + * def cholesky_delete(np.ndarray L, int go_out): # <<<<<<<<<<<<<< + * cdef int n = L.shape[0] + * cdef int m = L.strides[0] */ -static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_1solve_triangular(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_5utils_10arrayfuncs_1solve_triangular[] = "\n Solves a triangular system (overwrites y)\n\n Note: The lapack function to solve triangular systems was added to\n scipy v0.9. Remove this when we stop supporting earlier versions.\n "; -static PyMethodDef __pyx_mdef_7sklearn_5utils_10arrayfuncs_1solve_triangular = {__Pyx_NAMESTR("solve_triangular"), (PyCFunction)__pyx_pf_7sklearn_5utils_10arrayfuncs_1solve_triangular, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10arrayfuncs_1solve_triangular)}; -static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_1solve_triangular(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_X = 0; - PyArrayObject *__pyx_v_y = 0; - int __pyx_v_lda; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - size_t __pyx_t_6; +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_10arrayfuncs_3cholesky_delete(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_5utils_10arrayfuncs_3cholesky_delete = {__Pyx_NAMESTR("cholesky_delete"), (PyCFunction)__pyx_pw_7sklearn_5utils_10arrayfuncs_3cholesky_delete, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_5utils_10arrayfuncs_3cholesky_delete(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_L = 0; + int __pyx_v_go_out; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__y,0}; - __Pyx_RefNannySetupContext("solve_triangular"); - __pyx_self = __pyx_self; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("cholesky_delete (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_L,&__pyx_n_s_go_out,0}; PyObject* values[2] = {0,0}; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__y); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("solve_triangular", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_L)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_go_out)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("cholesky_delete", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "cholesky_delete") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "solve_triangular") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - __pyx_v_X = ((PyArrayObject *)values[0]); - __pyx_v_y = ((PyArrayObject *)values[1]); - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - __pyx_v_X = ((PyArrayObject *)PyTuple_GET_ITEM(__pyx_args, 0)); - __pyx_v_y = ((PyArrayObject *)PyTuple_GET_ITEM(__pyx_args, 1)); + __pyx_v_L = ((PyArrayObject *)values[0]); + __pyx_v_go_out = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_go_out == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("solve_triangular", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("cholesky_delete", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.utils.arrayfuncs.solve_triangular", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("sklearn.utils.arrayfuncs.cholesky_delete", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "sklearn/utils/arrayfuncs.pyx":87 - * cdef int lda - * - * if X.dtype.name == 'float64' and y.dtype.name == 'float64': # <<<<<<<<<<<<<< - * lda = X.strides[0] / sizeof(double) - * - */ - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_X), __pyx_n_s__dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__name); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyString_Equals(__pyx_t_2, ((PyObject *)__pyx_n_s__float64), Py_EQ); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_3) { - __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_y), __pyx_n_s__dtype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_4 = __Pyx_PyString_Equals(__pyx_t_1, ((PyObject *)__pyx_n_s__float64), Py_EQ); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = __pyx_t_4; - } else { - __pyx_t_5 = __pyx_t_3; - } - if (__pyx_t_5) { - - /* "sklearn/utils/arrayfuncs.pyx":88 - * - * if X.dtype.name == 'float64' and y.dtype.name == 'float64': - * lda = X.strides[0] / sizeof(double) # <<<<<<<<<<<<<< - * - * cblas_dtrsv (CblasRowMajor, CblasLower, CblasNoTrans, - */ - __pyx_t_6 = (sizeof(double)); - if (unlikely(__pyx_t_6 == 0)) { - PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_v_lda = (((int)(__pyx_v_X->strides[0])) / __pyx_t_6); - - /* "sklearn/utils/arrayfuncs.pyx":92 - * cblas_dtrsv (CblasRowMajor, CblasLower, CblasNoTrans, - * CblasNonUnit, X.shape[0], X.data, - * lda, y.data, 1); # <<<<<<<<<<<<<< - * - * elif X.dtype.name == 'float32' and y.dtype.name == 'float32': - */ - cblas_dtrsv(CblasRowMajor, CblasLower, CblasNoTrans, CblasNonUnit, ((int)(__pyx_v_X->dimensions[0])), ((double *)__pyx_v_X->data), __pyx_v_lda, ((double *)__pyx_v_y->data), 1); - goto __pyx_L6; - } - - /* "sklearn/utils/arrayfuncs.pyx":94 - * lda, y.data, 1); - * - * elif X.dtype.name == 'float32' and y.dtype.name == 'float32': # <<<<<<<<<<<<<< - * lda = X.strides[0] / sizeof(float) - * - */ - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_X), __pyx_n_s__dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__name); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = __Pyx_PyString_Equals(__pyx_t_2, ((PyObject *)__pyx_n_s__float32), Py_EQ); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_5) { - __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_y), __pyx_n_s__dtype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_3 = __Pyx_PyString_Equals(__pyx_t_1, ((PyObject *)__pyx_n_s__float32), Py_EQ); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_4 = __pyx_t_3; - } else { - __pyx_t_4 = __pyx_t_5; - } - if (__pyx_t_4) { - - /* "sklearn/utils/arrayfuncs.pyx":95 - * - * elif X.dtype.name == 'float32' and y.dtype.name == 'float32': - * lda = X.strides[0] / sizeof(float) # <<<<<<<<<<<<<< - * - * cblas_strsv (CblasRowMajor, CblasLower, CblasNoTrans, - */ - __pyx_t_6 = (sizeof(float)); - if (unlikely(__pyx_t_6 == 0)) { - PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_v_lda = (((int)(__pyx_v_X->strides[0])) / __pyx_t_6); - - /* "sklearn/utils/arrayfuncs.pyx":99 - * cblas_strsv (CblasRowMajor, CblasLower, CblasNoTrans, - * CblasNonUnit, X.shape[0], X.data, - * lda, y.data, 1); # <<<<<<<<<<<<<< - * else: - * raise ValueError ('Unsupported or inconsistent dtype in arrays X, y') - */ - cblas_strsv(CblasRowMajor, CblasLower, CblasNoTrans, CblasNonUnit, ((int)(__pyx_v_X->dimensions[0])), ((float *)__pyx_v_X->data), __pyx_v_lda, ((float *)__pyx_v_y->data), 1); - goto __pyx_L6; - } - /*else*/ { - - /* "sklearn/utils/arrayfuncs.pyx":101 - * lda, y.data, 1); - * else: - * raise ValueError ('Unsupported or inconsistent dtype in arrays X, y') # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L6:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_L), __pyx_ptype_5numpy_ndarray, 1, "L", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_10arrayfuncs_2cholesky_delete(__pyx_self, __pyx_v_L, __pyx_v_go_out); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("sklearn.utils.arrayfuncs.solve_triangular", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/utils/arrayfuncs.pyx":104 - * - * - * def cholesky_delete (np.ndarray L, int go_out): # <<<<<<<<<<<<<< - * - * cdef int n = L.shape[0] - */ - -static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_2cholesky_delete(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7sklearn_5utils_10arrayfuncs_2cholesky_delete = {__Pyx_NAMESTR("cholesky_delete"), (PyCFunction)__pyx_pf_7sklearn_5utils_10arrayfuncs_2cholesky_delete, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; -static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_2cholesky_delete(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_L = 0; - int __pyx_v_go_out; +static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_2cholesky_delete(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_L, int __pyx_v_go_out) { int __pyx_v_n; int __pyx_v_m; PyObject *__pyx_r = NULL; @@ -1480,142 +1639,136 @@ static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_2cholesky_delete(PyObject int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__L,&__pyx_n_s__go_out,0}; - __Pyx_RefNannySetupContext("cholesky_delete"); - __pyx_self = __pyx_self; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); - PyObject* values[2] = {0,0}; - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__L); - if (likely(values[0])) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__go_out); - if (likely(values[1])) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("cholesky_delete", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "cholesky_delete") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - __pyx_v_L = ((PyArrayObject *)values[0]); - __pyx_v_go_out = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_go_out == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - __pyx_v_L = ((PyArrayObject *)PyTuple_GET_ITEM(__pyx_args, 0)); - __pyx_v_go_out = __Pyx_PyInt_AsInt(PyTuple_GET_ITEM(__pyx_args, 1)); if (unlikely((__pyx_v_go_out == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("cholesky_delete", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("sklearn.utils.arrayfuncs.cholesky_delete", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_L), __pyx_ptype_5numpy_ndarray, 1, "L", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RefNannySetupContext("cholesky_delete", 0); - /* "sklearn/utils/arrayfuncs.pyx":106 - * def cholesky_delete (np.ndarray L, int go_out): - * + /* "sklearn/utils/arrayfuncs.pyx":56 + * # we should be using np.npy_intp or Py_ssize_t for indices, but BLAS wants int + * def cholesky_delete(np.ndarray L, int go_out): * cdef int n = L.shape[0] # <<<<<<<<<<<<<< - * cdef int m + * cdef int m = L.strides[0] * */ __pyx_v_n = ((int)(__pyx_v_L->dimensions[0])); - /* "sklearn/utils/arrayfuncs.pyx":109 - * cdef int m + /* "sklearn/utils/arrayfuncs.pyx":57 + * def cholesky_delete(np.ndarray L, int go_out): + * cdef int n = L.shape[0] + * cdef int m = L.strides[0] # <<<<<<<<<<<<<< + * + * if L.dtype.name == 'float64': + */ + __pyx_v_m = ((int)(__pyx_v_L->strides[0])); + + /* "sklearn/utils/arrayfuncs.pyx":59 + * cdef int m = L.strides[0] * * if L.dtype.name == 'float64': # <<<<<<<<<<<<<< - * m = L.strides[0] / sizeof (double) - * double_cholesky_delete (m, n, L.data, go_out) + * cholesky_delete_dbl(m / sizeof(double), n, L.data, go_out) + * elif L.dtype.name == 'float32': */ - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_L), __pyx_n_s__dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_L), __pyx_n_s_dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__name); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_name); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyString_Equals(__pyx_t_2, ((PyObject *)__pyx_n_s__float64), Py_EQ); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_t_2, __pyx_n_s_float64, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_3) { - /* "sklearn/utils/arrayfuncs.pyx":110 + /* "sklearn/utils/arrayfuncs.pyx":60 * * if L.dtype.name == 'float64': - * m = L.strides[0] / sizeof (double) # <<<<<<<<<<<<<< - * double_cholesky_delete (m, n, L.data, go_out) + * cholesky_delete_dbl(m / sizeof(double), n, L.data, go_out) # <<<<<<<<<<<<<< * elif L.dtype.name == 'float32': + * cholesky_delete_flt(m / sizeof(float), n, L.data, go_out) */ __pyx_t_4 = (sizeof(double)); if (unlikely(__pyx_t_4 == 0)) { - PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_v_m = (((int)(__pyx_v_L->strides[0])) / __pyx_t_4); - - /* "sklearn/utils/arrayfuncs.pyx":111 - * if L.dtype.name == 'float64': - * m = L.strides[0] / sizeof (double) - * double_cholesky_delete (m, n, L.data, go_out) # <<<<<<<<<<<<<< - * elif L.dtype.name == 'float32': - * m = L.strides[0] / sizeof (float) - */ - double_cholesky_delete(__pyx_v_m, __pyx_v_n, ((double *)__pyx_v_L->data), __pyx_v_go_out); - goto __pyx_L6; + cholesky_delete_dbl((__pyx_v_m / __pyx_t_4), __pyx_v_n, ((double *)__pyx_v_L->data), __pyx_v_go_out); + goto __pyx_L3; } - /* "sklearn/utils/arrayfuncs.pyx":112 - * m = L.strides[0] / sizeof (double) - * double_cholesky_delete (m, n, L.data, go_out) + /* "sklearn/utils/arrayfuncs.pyx":61 + * if L.dtype.name == 'float64': + * cholesky_delete_dbl(m / sizeof(double), n, L.data, go_out) * elif L.dtype.name == 'float32': # <<<<<<<<<<<<<< - * m = L.strides[0] / sizeof (float) - * float_cholesky_delete (m, n, L.data, go_out) + * cholesky_delete_flt(m / sizeof(float), n, L.data, go_out) + * else: */ - __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_L), __pyx_n_s__dtype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_L), __pyx_n_s_dtype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_3 = __Pyx_PyString_Equals(__pyx_t_1, ((PyObject *)__pyx_n_s__float32), Py_EQ); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = (__Pyx_PyString_Equals(__pyx_t_1, __pyx_n_s_float32, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_3) { - /* "sklearn/utils/arrayfuncs.pyx":113 - * double_cholesky_delete (m, n, L.data, go_out) + /* "sklearn/utils/arrayfuncs.pyx":62 + * cholesky_delete_dbl(m / sizeof(double), n, L.data, go_out) * elif L.dtype.name == 'float32': - * m = L.strides[0] / sizeof (float) # <<<<<<<<<<<<<< - * float_cholesky_delete (m, n, L.data, go_out) - * + * cholesky_delete_flt(m / sizeof(float), n, L.data, go_out) # <<<<<<<<<<<<<< + * else: + * raise TypeError("unsupported dtype %r." % L.dtype) */ __pyx_t_4 = (sizeof(float)); if (unlikely(__pyx_t_4 == 0)) { - PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_v_m = (((int)(__pyx_v_L->strides[0])) / __pyx_t_4); + cholesky_delete_flt((__pyx_v_m / __pyx_t_4), __pyx_v_n, ((float *)__pyx_v_L->data), __pyx_v_go_out); + goto __pyx_L3; + } + /*else*/ { - /* "sklearn/utils/arrayfuncs.pyx":114 - * elif L.dtype.name == 'float32': - * m = L.strides[0] / sizeof (float) - * float_cholesky_delete (m, n, L.data, go_out) # <<<<<<<<<<<<<< - * + /* "sklearn/utils/arrayfuncs.pyx":64 + * cholesky_delete_flt(m / sizeof(float), n, L.data, go_out) + * else: + * raise TypeError("unsupported dtype %r." % L.dtype) # <<<<<<<<<<<<<< */ - float_cholesky_delete(__pyx_v_m, __pyx_v_n, ((float *)__pyx_v_L->data), __pyx_v_go_out); - goto __pyx_L6; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_L), __pyx_n_s_dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyString_Format(__pyx_kp_s_unsupported_dtype_r, __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; + __pyx_L3:; + + /* "sklearn/utils/arrayfuncs.pyx":55 + * + * # we should be using np.npy_intp or Py_ssize_t for indices, but BLAS wants int + * def cholesky_delete(np.ndarray L, int go_out): # <<<<<<<<<<<<<< + * cdef int n = L.shape[0] + * cdef int m = L.strides[0] + */ + /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; @@ -1629,7 +1782,7 @@ static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_2cholesky_delete(PyObject return __pyx_r; } -/* "numpy.pxd":190 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< @@ -1637,8 +1790,20 @@ static PyObject *__pyx_pf_7sklearn_5utils_10arrayfuncs_2cholesky_delete(PyObject * # requirements, and does not yet fullfill the PEP. */ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; @@ -1663,28 +1828,26 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__"); + __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":196 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ - __pyx_t_1 = (__pyx_v_info == NULL); + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; - goto __pyx_L5; } - __pyx_L5:; - /* "numpy.pxd":199 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -1693,7 +1856,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":200 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -1702,26 +1865,26 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":202 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":204 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":205 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -1729,11 +1892,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ * copy_shape = 0 */ __pyx_v_copy_shape = 1; - goto __pyx_L6; + goto __pyx_L4; } /*else*/ { - /* "numpy.pxd":207 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -1742,98 +1905,94 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_copy_shape = 0; } - __pyx_L6:; + __pyx_L4:; - /* "numpy.pxd":209 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_1) { - /* "numpy.pxd":210 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { - /* "numpy.pxd":211 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L7:; - /* "numpy.pxd":213 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_3) { - /* "numpy.pxd":214 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { - /* "numpy.pxd":215 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L8:; - /* "numpy.pxd":217 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":218 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -1842,16 +2001,17 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":219 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ - if (__pyx_v_copy_shape) { + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { - /* "numpy.pxd":222 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -1860,7 +2020,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":223 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -1869,7 +2029,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":224 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< @@ -1880,49 +2040,49 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "numpy.pxd":225 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":226 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } - goto __pyx_L9; + goto __pyx_L7; } /*else*/ { - /* "numpy.pxd":228 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":229 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } - __pyx_L9:; + __pyx_L7:; - /* "numpy.pxd":230 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -1931,25 +2091,25 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":231 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":232 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - /* "numpy.pxd":235 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -1958,17 +2118,19 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_f = NULL; - /* "numpy.pxd":236 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":240 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -1977,23 +2139,23 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":242 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; } if (__pyx_t_1) { - /* "numpy.pxd":244 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -2005,69 +2167,70 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; - goto __pyx_L12; + goto __pyx_L10; } /*else*/ { - /* "numpy.pxd":247 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } - __pyx_L12:; + __pyx_L10:; - /* "numpy.pxd":249 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { - /* "numpy.pxd":250 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; - /* "numpy.pxd":251 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; + __pyx_t_2 = (__pyx_v_little_endian != 0); } else { __pyx_t_2 = __pyx_t_1; } if (!__pyx_t_2) { - /* "numpy.pxd":252 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_7 = __pyx_t_3; } else { __pyx_t_7 = __pyx_t_1; @@ -2078,271 +2241,244 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (__pyx_t_1) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L14:; - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__b; - goto __pyx_L15; - } + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; - /* "numpy.pxd":255 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__B; - goto __pyx_L15; - } + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; - /* "numpy.pxd":256 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__h; - goto __pyx_L15; - } + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; - /* "numpy.pxd":257 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__H; - goto __pyx_L15; - } + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; - /* "numpy.pxd":258 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__i; - goto __pyx_L15; - } + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; - /* "numpy.pxd":259 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__I; - goto __pyx_L15; - } + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; - /* "numpy.pxd":260 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__l; - goto __pyx_L15; - } + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; - /* "numpy.pxd":261 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__L; - goto __pyx_L15; - } + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; - /* "numpy.pxd":262 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__q; - goto __pyx_L15; - } + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; - /* "numpy.pxd":263 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; - } + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; - /* "numpy.pxd":264 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__f; - goto __pyx_L15; - } + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; - /* "numpy.pxd":265 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__d; - goto __pyx_L15; - } + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; - /* "numpy.pxd":266 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__g; - goto __pyx_L15; - } + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; - /* "numpy.pxd":267 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; - } + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; - /* "numpy.pxd":268 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; - } + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; - /* "numpy.pxd":269 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; - } + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; - /* "numpy.pxd":270 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L15; - } - /*else*/ { + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: - /* "numpy.pxd":272 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_11), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L15:; - /* "numpy.pxd":273 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -2351,7 +2487,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":274 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -2360,58 +2496,65 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":276 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":277 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":278 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":281 - * f = _util_dtypestring(descr, info.format + 1, + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, - * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string - * + * &offset) */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; - /* "numpy.pxd":282 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L13:; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; @@ -2435,31 +2578,41 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ return __pyx_r; } -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__"); + __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":285 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { - /* "numpy.pxd":286 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -2467,21 +2620,21 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * stdlib.free(info.strides) */ free(__pyx_v_info->format); - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":287 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":288 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -2489,14 +2642,23 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * */ free(__pyx_v_info->strides); - goto __pyx_L6; + goto __pyx_L4; } - __pyx_L6:; + __pyx_L4:; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":764 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -2511,9 +2673,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":765 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -2521,14 +2683,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -2539,7 +2708,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":767 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -2554,9 +2723,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":768 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -2564,14 +2733,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -2582,7 +2758,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -2597,9 +2773,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":771 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -2607,14 +2783,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -2625,7 +2808,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -2640,9 +2823,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":774 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -2650,14 +2833,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -2668,7 +2858,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -2683,9 +2873,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":777 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -2693,25 +2883,32 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "numpy.pxd":779 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -2733,7 +2930,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; + int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; int __pyx_t_8; @@ -2743,9 +2940,9 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring"); + __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":786 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -2754,7 +2951,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":787 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -2763,134 +2960,136 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":790 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ - if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":791 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; - /* "numpy.pxd":792 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * - * if (end - f) - (new_offset - offset[0]) < 15: - */ - if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { - PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; - /* "numpy.pxd":794 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { - /* "numpy.pxd":795 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_13), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L5:; - /* "numpy.pxd":797 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); + __pyx_t_6 = ((__pyx_v_child->byteorder == '>') != 0); if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = (__pyx_v_little_endian != 0); } else { __pyx_t_7 = __pyx_t_6; } if (!__pyx_t_7) { - /* "numpy.pxd":798 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); + __pyx_t_6 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); + __pyx_t_8 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_9 = __pyx_t_8; } else { __pyx_t_9 = __pyx_t_6; @@ -2901,23 +3100,21 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } if (__pyx_t_6) { - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; - /* "numpy.pxd":809 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -2925,16 +3122,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; - /* "numpy.pxd":810 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -2943,7 +3139,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":811 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -2952,7 +3148,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":812 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< @@ -2963,7 +3159,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); } - /* "numpy.pxd":814 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< @@ -2973,316 +3169,299 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_t_10 = 0; (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); - /* "numpy.pxd":816 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { - /* "numpy.pxd":817 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":818 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { - /* "numpy.pxd":819 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L10:; - /* "numpy.pxd":822 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L11; } - /* "numpy.pxd":823 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L11; } - /* "numpy.pxd":824 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 104; goto __pyx_L11; } - /* "numpy.pxd":825 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L11; } - /* "numpy.pxd":826 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 105; goto __pyx_L11; } - /* "numpy.pxd":827 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L11; } - /* "numpy.pxd":828 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 108; goto __pyx_L11; } - /* "numpy.pxd":829 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L11; } - /* "numpy.pxd":830 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 113; goto __pyx_L11; } - /* "numpy.pxd":831 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L11; } - /* "numpy.pxd":832 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 102; goto __pyx_L11; } - /* "numpy.pxd":833 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 100; goto __pyx_L11; } - /* "numpy.pxd":834 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 103; goto __pyx_L11; } - /* "numpy.pxd":835 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; @@ -3290,20 +3469,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":836 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; @@ -3311,20 +3489,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":837 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; @@ -3332,50 +3509,49 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":838 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":840 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_11), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L11:; - /* "numpy.pxd":841 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -3387,21 +3563,21 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } /*else*/ { - /* "numpy.pxd":845 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_11; } __pyx_L9:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":846 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -3411,13 +3587,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_r = __pyx_v_f; goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -3430,7 +3612,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":961 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -3442,9 +3624,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base"); + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":963 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -3452,9 +3635,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "numpy.pxd":964 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":969 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -3466,7 +3650,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":966 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":971 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -3475,7 +3659,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":967 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":972 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -3486,7 +3670,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":968 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":973 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -3495,7 +3679,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":969 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":974 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -3504,10 +3688,19 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ __pyx_v_arr->base = __pyx_v_baseptr; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":971 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -3519,19 +3712,19 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base"); + __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":972 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { - /* "numpy.pxd":973 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":978 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -3542,11 +3735,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "numpy.pxd":975 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -3556,9 +3748,16 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } - __pyx_L3:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); @@ -3571,9 +3770,13 @@ static PyMethodDef __pyx_methods[] = { #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else PyModuleDef_HEAD_INIT, + #endif __Pyx_NAMESTR("arrayfuncs"), - __Pyx_DOCSTR(__pyx_k_17), /* m_doc */ + __Pyx_DOCSTR(__pyx_k_Small_collection_of_auxiliary_f), /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ @@ -3584,40 +3787,44 @@ static struct PyModuleDef __pyx_moduledef = { #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 0}, - {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, - {&__pyx_kp_u_12, __pyx_k_12, sizeof(__pyx_k_12), 0, 1, 0, 0}, - {&__pyx_kp_u_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 1, 0, 0}, - {&__pyx_n_s_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 0, 1, 1}, - {&__pyx_kp_s_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 0, 1, 0}, - {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, - {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, - {&__pyx_kp_u_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 1, 0, 0}, - {&__pyx_n_s__L, __pyx_k__L, sizeof(__pyx_k__L), 0, 0, 1, 1}, - {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__cholesky_delete, __pyx_k__cholesky_delete, sizeof(__pyx_k__cholesky_delete), 0, 0, 1, 1}, - {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, - {&__pyx_n_s__float32, __pyx_k__float32, sizeof(__pyx_k__float32), 0, 0, 1, 1}, - {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, - {&__pyx_n_s__go_out, __pyx_k__go_out, sizeof(__pyx_k__go_out), 0, 0, 1, 1}, - {&__pyx_n_s__min_pos, __pyx_k__min_pos, sizeof(__pyx_k__min_pos), 0, 0, 1, 1}, - {&__pyx_n_s__name, __pyx_k__name, sizeof(__pyx_k__name), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__size, __pyx_k__size, sizeof(__pyx_k__size), 0, 0, 1, 1}, - {&__pyx_n_s__solve_triangular, __pyx_k__solve_triangular, sizeof(__pyx_k__solve_triangular), 0, 0, 1, 1}, - {&__pyx_n_s__y, __pyx_k__y, sizeof(__pyx_k__y), 0, 0, 1, 1}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_n_s_L, __pyx_k_L, sizeof(__pyx_k_L), 0, 0, 1, 1}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, + {&__pyx_kp_s_Unsupported_dtype_for_array_X, __pyx_k_Unsupported_dtype_for_array_X, sizeof(__pyx_k_Unsupported_dtype_for_array_X), 0, 0, 1, 0}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_n_s_cholesky_delete, __pyx_k_cholesky_delete, sizeof(__pyx_k_cholesky_delete), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_float32, __pyx_k_float32, sizeof(__pyx_k_float32), 0, 0, 1, 1}, + {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 0, 0, 1, 1}, + {&__pyx_n_s_go_out, __pyx_k_go_out, sizeof(__pyx_k_go_out), 0, 0, 1, 1}, + {&__pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_k_home_larsb_src_scikit_learn_skl, sizeof(__pyx_k_home_larsb_src_scikit_learn_skl), 0, 0, 1, 0}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_m, __pyx_k_m, sizeof(__pyx_k_m), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_min_pos, __pyx_k_min_pos, sizeof(__pyx_k_min_pos), 0, 0, 1, 1}, + {&__pyx_n_s_n, __pyx_k_n, sizeof(__pyx_k_n), 0, 0, 1, 1}, + {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_utils_arrayfuncs, __pyx_k_sklearn_utils_arrayfuncs, sizeof(__pyx_k_sklearn_utils_arrayfuncs), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_kp_s_unsupported_dtype_r, __pyx_k_unsupported_dtype_r, sizeof(__pyx_k_unsupported_dtype_r), 0, 0, 1, 0}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -3625,119 +3832,108 @@ static int __Pyx_InitCachedBuiltins(void) { static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "sklearn/utils/arrayfuncs.pyx":58 + /* "sklearn/utils/arrayfuncs.pyx":33 * return _double_min_pos( X.data, X.size) * else: * raise ValueError('Unsupported dtype for array X') # <<<<<<<<<<<<<< * * */ - __pyx_k_tuple_2 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_2)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_1)); - PyTuple_SET_ITEM(__pyx_k_tuple_2, 0, ((PyObject *)__pyx_kp_s_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); - - /* "sklearn/utils/arrayfuncs.pyx":101 - * lda, y.data, 1); - * else: - * raise ValueError ('Unsupported or inconsistent dtype in arrays X, y') # <<<<<<<<<<<<<< - * - * - */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_4)); - __Pyx_INCREF(((PyObject *)__pyx_kp_s_3)); - PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_s_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_s_Unsupported_dtype_for_array_X); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); - /* "numpy.pxd":211 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_6)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); - /* "numpy.pxd":215 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_8 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_8)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_7)); - PyTuple_SET_ITEM(__pyx_k_tuple_8, 0, ((PyObject *)__pyx_kp_u_7)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_7)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_10)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_9)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); - /* "numpy.pxd":795 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_13 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_13)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_12)); - PyTuple_SET_ITEM(__pyx_k_tuple_13, 0, ((PyObject *)__pyx_kp_u_12)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_12)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_14 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_14)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_9)); - PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, ((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_9)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); - /* "numpy.pxd":819 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_16 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_16)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_15)); - PyTuple_SET_ITEM(__pyx_k_tuple_16, 0, ((PyObject *)__pyx_kp_u_15)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_15)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + + /* "sklearn/utils/arrayfuncs.pyx":22 + * + * + * def min_pos(np.ndarray X): # <<<<<<<<<<<<<< + * """ + * Find the minimum value of an array over positive values + */ + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_n_s_X); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + __pyx_codeobj__9 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__8, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_min_pos, 22, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/arrayfuncs.pyx":55 + * + * # we should be using np.npy_intp or Py_ssize_t for indices, but BLAS wants int + * def cholesky_delete(np.ndarray L, int go_out): # <<<<<<<<<<<<<< + * cdef int n = L.shape[0] + * cdef int m = L.strides[0] + */ + __pyx_tuple__10 = PyTuple_Pack(4, __pyx_n_s_L, __pyx_n_s_go_out, __pyx_n_s_n, __pyx_n_s_m); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + __pyx_codeobj__11 = (PyObject*)__Pyx_PyCode_New(2, 0, 4, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__10, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_cholesky_delete, 55, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -3747,7 +3943,6 @@ static int __Pyx_InitCachedConstants(void) { static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; return 0; __pyx_L1_error:; return -1; @@ -3762,6 +3957,9 @@ PyMODINIT_FUNC PyInit_arrayfuncs(void) #endif { PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -3772,12 +3970,18 @@ PyMODINIT_FUNC PyInit_arrayfuncs(void) Py_FatalError("failed to import 'refnanny' module"); } #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_arrayfuncs(void)"); + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_arrayfuncs(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __pyx_binding_PyCFunctionType_USED - if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -3788,22 +3992,34 @@ PyMODINIT_FUNC PyInit_arrayfuncs(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("arrayfuncs"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_17), 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("arrayfuncs"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_Small_collection_of_auxiliary_f), 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif if (__pyx_module_is_main_sklearn__utils__arrayfuncs) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.utils.arrayfuncs")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.utils.arrayfuncs", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ @@ -3813,11 +4029,18 @@ PyMODINIT_FUNC PyInit_arrayfuncs(void) /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ @@ -3829,45 +4052,42 @@ PyMODINIT_FUNC PyInit_arrayfuncs(void) * * cimport cython */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/utils/arrayfuncs.pyx":47 + /* "sklearn/utils/arrayfuncs.pyx":19 + * + * + * np.import_array() # <<<<<<<<<<<<<< * * - * def min_pos(np.ndarray X): # <<<<<<<<<<<<<< - * """ - * Find the minimum value of an array over positivie values */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_10arrayfuncs_min_pos, NULL, __pyx_n_s_18); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__min_pos, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + import_array(); - /* "sklearn/utils/arrayfuncs.pyx":78 - * return min_val + /* "sklearn/utils/arrayfuncs.pyx":22 + * * - * def solve_triangular (np.ndarray X, np.ndarray y): # <<<<<<<<<<<<<< - * """ - * Solves a triangular system (overwrites y) + * def min_pos(np.ndarray X): # <<<<<<<<<<<<<< + * """ + * Find the minimum value of an array over positive values */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_10arrayfuncs_1solve_triangular, NULL, __pyx_n_s_18); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_10arrayfuncs_1min_pos, NULL, __pyx_n_s_sklearn_utils_arrayfuncs); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__solve_triangular, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_min_pos, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/utils/arrayfuncs.pyx":104 - * - * - * def cholesky_delete (np.ndarray L, int go_out): # <<<<<<<<<<<<<< + /* "sklearn/utils/arrayfuncs.pyx":55 * + * # we should be using np.npy_intp or Py_ssize_t for indices, but BLAS wants int + * def cholesky_delete(np.ndarray L, int go_out): # <<<<<<<<<<<<<< * cdef int n = L.shape[0] + * cdef int m = L.strides[0] */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_10arrayfuncs_2cholesky_delete, NULL, __pyx_n_s_18); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_10arrayfuncs_3cholesky_delete, NULL, __pyx_n_s_sklearn_utils_arrayfuncs); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__cholesky_delete, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_cholesky_delete, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "sklearn/utils/arrayfuncs.pyx":1 @@ -3876,11 +4096,11 @@ PyMODINIT_FUNC PyInit_arrayfuncs(void) * */ __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":971 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -3906,7 +4126,6 @@ PyMODINIT_FUNC PyInit_arrayfuncs(void) } /* Runtime support code */ - #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; @@ -3923,45 +4142,194 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { } #endif /* CYTHON_REFNANNY */ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif } return result; } -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { - if (Py_TYPE(obj) == type) return 1; + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif } else { - if (PyObject_TypeCheck(obj, type)) return 1; + if (likely(PyObject_TypeCheck(obj, type))) return 1; } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); + } +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + #if CYTHON_PEP393_ENABLED + if (unlikely(PyUnicode_READY(s1) < 0) || unlikely(PyUnicode_READY(s2) < 0)) + return -1; + #endif + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, length * kind); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; +#endif + result = (*call)(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + Py_LeaveRecursiveCall(); +#endif + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; @@ -3971,78 +4339,81 @@ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyOb Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif } - static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif } - #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) + if (PyClass_Check(type)) { #else - if (!PyType_Check(type)) + if (PyType_Check(type)) { #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - /* Normalize to raise , */ - Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } #endif } - __Pyx_ErrRestore(type, value, tb); return; raise_error: @@ -4051,10 +4422,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tb); return; } - #else /* Python 3+ */ - static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -4064,7 +4434,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } if (value == Py_None) value = 0; - if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, @@ -4073,37 +4442,71 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } - +#if PY_VERSION_HEX >= 0x03030000 if (cause) { +#else + if (cause && cause != Py_None) { +#endif PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; - } - else if (PyExceptionInstance_Check(cause)) { + } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; @@ -4113,8 +4516,8 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tmp_tb); } } - bad: + Py_XDECREF(owned_instance); return; } #endif @@ -4128,7 +4531,6 @@ static void __Pyx_RaiseArgtupleInvalid( { Py_ssize_t num_expected; const char *more_or_less; - if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; @@ -4140,7 +4542,7 @@ static void __Pyx_RaiseArgtupleInvalid( more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } @@ -4154,7 +4556,7 @@ static void __Pyx_RaiseDoubleKeywordsError( "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); + PyString_AsString(kw_name)); #endif } @@ -4170,64 +4572,86 @@ static int __Pyx_ParseOptionalKeywords( Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { values[name-argnames] = value; - } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; } } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; } } return 0; arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); + __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); + "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", + "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", @@ -4237,34 +4661,24 @@ static int __Pyx_ParseOptionalKeywords( return -1; } -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); - } else { - __Pyx_RaiseTooManyValuesError(index); - } -} - static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); + PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) @@ -4274,16 +4688,18 @@ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { return 0; } -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; + #endif if (from_list) list = from_list; else { @@ -4300,12 +4716,42 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { goto bad; #if PY_VERSION_HEX >= 0x02050000 { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } } #else if (level>0) { @@ -4316,71 +4762,127 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { name, global_dict, empty_dict, list, NULL); #endif bad: - Py_XDECREF(empty_list); + #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { - if (s1 == s2) { /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */ - return (equals == Py_EQ); - } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { - if (PyBytes_GET_SIZE(s1) != PyBytes_GET_SIZE(s2)) { - return (equals == Py_NE); - } else if (PyBytes_GET_SIZE(s1) == 1) { - if (equals == Py_EQ) - return (PyBytes_AS_STRING(s1)[0] == PyBytes_AS_STRING(s2)[0]); - else - return (PyBytes_AS_STRING(s1)[0] != PyBytes_AS_STRING(s2)[0]); - } else { - int result = memcmp(PyBytes_AS_STRING(s1), PyBytes_AS_STRING(s2), (size_t)PyBytes_GET_SIZE(s1)); - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { - return (equals == Py_NE); - } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { - return (equals == Py_NE); - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \ + { \ + func_type value = func(x); \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + PyErr_SetString(PyExc_OverflowError, \ + (is_unsigned && unlikely(value < zero)) ? \ + "can't convert negative value to " #target_type : \ + "value too large to convert to " #target_type); \ + return (target_type) -1; \ + } \ + } \ + return (target_type) value; \ } -} -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { - if (s1 == s2) { /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */ - return (equals == Py_EQ); - } else if (PyUnicode_CheckExact(s1) & PyUnicode_CheckExact(s2)) { - if (PyUnicode_GET_SIZE(s1) != PyUnicode_GET_SIZE(s2)) { - return (equals == Py_NE); - } else if (PyUnicode_GET_SIZE(s1) == 1) { - if (equals == Py_EQ) - return (PyUnicode_AS_UNICODE(s1)[0] == PyUnicode_AS_UNICODE(s2)[0]); - else - return (PyUnicode_AS_UNICODE(s1)[0] != PyUnicode_AS_UNICODE(s2)[0]); +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG) } else { - int result = PyUnicode_Compare(s1, s2); - if ((result == -1) && unlikely(PyErr_Occurred())) - return -1; - return (equals == Py_EQ) ? (result == 0) : (result != 0); + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(int) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; } - } else if ((s1 == Py_None) & PyUnicode_CheckExact(s2)) { - return (equals == Py_NE); - } else if ((s2 == Py_None) & PyUnicode_CheckExact(s1)) { - return (equals == Py_NE); } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; } } @@ -4624,401 +5126,153 @@ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; - } - return (unsigned short)val; - } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; - } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; - } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; - } - return (short)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); } - return (int)val; } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); } - return (signed char)__Pyx_PyInt_AsSignedLong(x); } -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); } - return (signed short)val; - } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); } - return (signed int)val; } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); } - return (int)__Pyx_PyInt_AsLong(x); } -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; + "can't convert negative value to long"); + return (long) -1; } - return (unsigned long)PyLong_AsUnsignedLong(x); - } else { - return (unsigned long)PyLong_AsLong(x); - } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; + return (long) val; } - return (unsigned PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)val; - } else + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); - return (long)-1; + return (long) -1; } - return (long)PyLong_AsUnsignedLong(x); - } else { - return (long)PyLong_AsLong(x); - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong) } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { - return (PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)val; - } else +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong) } - return (signed long)PyLong_AsUnsignedLong(x); - } else { - return (signed long)PyLong_AsLong(x); } - } else { - signed long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; - } - return (signed PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; } } else { - signed PY_LONG_LONG val; + long val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } @@ -5043,6 +5297,23 @@ static int __Pyx_check_binary_version(void) { return 0; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -5052,15 +5323,14 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(class_name); - #else - py_name = PyUnicode_FromString(class_name); - #endif + py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); @@ -5072,11 +5342,23 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", + "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -5086,9 +5368,9 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", + "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } @@ -5100,51 +5382,105 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(name); - #else - py_name = PyUnicode_FromString(name); - #endif - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); } -#endif #include "compile.h" #include "frameobject.h" #include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); + py_srcfile = PyString_FromString(filename); #else - py_srcfile = PyUnicode_FromString(__pyx_filename); + py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; - if (__pyx_clineno) { + if (c_line) { #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { @@ -5155,28 +5491,45 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, #endif } if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_code = PyCode_New( + py_code = __Pyx_PyCode_New( 0, /*int argcount,*/ - #if PY_MAJOR_VERSION >= 3 0, /*int kwonlyargcount,*/ - #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ + py_line, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); - if (!py_code) goto bad; + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ @@ -5184,11 +5537,9 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; + py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); } @@ -5223,26 +5574,90 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ +#if !CYTHON_COMPILING_IN_PYPY +#if PY_VERSION_HEX >= 0x02060000 + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -5258,13 +5673,13 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", + "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; @@ -5276,16 +5691,40 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + #if PY_VERSION_HEX < 0x02060000 + return PyInt_AsSsize_t(b); + #else + return PyLong_AsSsize_t(b); + #endif + } + x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) @@ -5300,17 +5739,5 @@ static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #endif } -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; -} - #endif /* Py_PYTHON_H */ diff --git a/sklearn/utils/arrayfuncs.pyx b/sklearn/utils/arrayfuncs.pyx index d75f6cc447d4d..156edf45864c3 100644 --- a/sklearn/utils/arrayfuncs.pyx +++ b/sklearn/utils/arrayfuncs.pyx @@ -7,46 +7,21 @@ import numpy as np cimport cython -cdef extern from "cblas.h": - enum CBLAS_ORDER: - CblasRowMajor=101 - CblasColMajor=102 - enum CBLAS_TRANSPOSE: - CblasNoTrans=111 - CblasTrans=112 - CblasConjTrans=113 - AtlasConj=114 - enum CBLAS_UPLO: - CblasUpper=121 - CblasLower=122 - enum CBLAS_DIAG: - CblasNonUnit=131 - CblasUnit=132 - - void cblas_dtrsv(CBLAS_ORDER Order, CBLAS_UPLO Uplo, - CBLAS_TRANSPOSE TransA, CBLAS_DIAG Diag, - int N, double *A, int lda, double *X, - int incX) - - void cblas_strsv(CBLAS_ORDER Order, CBLAS_UPLO Uplo, - CBLAS_TRANSPOSE TransA, CBLAS_DIAG Diag, - int N, float *A, int lda, float *X, - int incX) - -cdef extern from "float.h": - cdef double DBL_MAX - cdef float FLT_MAX - -cdef extern from "src/cholesky_delete.c": - int double_cholesky_delete (int m, int n, double *L, int go_out) - int float_cholesky_delete (int m, int n, float *L, int go_out) - +from libc.float cimport DBL_MAX, FLT_MAX + +cdef extern from "src/cholesky_delete.h": + int cholesky_delete_dbl(int m, int n, double *L, int go_out) + int cholesky_delete_flt(int m, int n, float *L, int go_out) + ctypedef np.float64_t DOUBLE +np.import_array() + + def min_pos(np.ndarray X): """ - Find the minimum value of an array over positivie values + Find the minimum value of an array over positive values Returns a huge value if none of the values are positive """ @@ -58,7 +33,7 @@ def min_pos(np.ndarray X): raise ValueError('Unsupported dtype for array X') -cdef float _float_min_pos (float *X, Py_ssize_t size): +cdef float _float_min_pos(float *X, Py_ssize_t size): cdef Py_ssize_t i cdef float min_val = DBL_MAX for i in range(size): @@ -67,7 +42,7 @@ cdef float _float_min_pos (float *X, Py_ssize_t size): return min_val -cdef double _double_min_pos (double *X, Py_ssize_t size): +cdef double _double_min_pos(double *X, Py_ssize_t size): cdef Py_ssize_t i cdef np.float64_t min_val = FLT_MAX for i in range(size): @@ -75,41 +50,15 @@ cdef double _double_min_pos (double *X, Py_ssize_t size): min_val = X[i] return min_val -def solve_triangular (np.ndarray X, np.ndarray y): - """ - Solves a triangular system (overwrites y) - - Note: The lapack function to solve triangular systems was added to - scipy v0.9. Remove this when we stop supporting earlier versions. - """ - cdef int lda - - if X.dtype.name == 'float64' and y.dtype.name == 'float64': - lda = X.strides[0] / sizeof(double) - - cblas_dtrsv (CblasRowMajor, CblasLower, CblasNoTrans, - CblasNonUnit, X.shape[0], X.data, - lda, y.data, 1); - - elif X.dtype.name == 'float32' and y.dtype.name == 'float32': - lda = X.strides[0] / sizeof(float) - - cblas_strsv (CblasRowMajor, CblasLower, CblasNoTrans, - CblasNonUnit, X.shape[0], X.data, - lda, y.data, 1); - else: - raise ValueError ('Unsupported or inconsistent dtype in arrays X, y') - - -def cholesky_delete (np.ndarray L, int go_out): +# we should be using np.npy_intp or Py_ssize_t for indices, but BLAS wants int +def cholesky_delete(np.ndarray L, int go_out): cdef int n = L.shape[0] - cdef int m + cdef int m = L.strides[0] if L.dtype.name == 'float64': - m = L.strides[0] / sizeof (double) - double_cholesky_delete (m, n, L.data, go_out) + cholesky_delete_dbl(m / sizeof(double), n, L.data, go_out) elif L.dtype.name == 'float32': - m = L.strides[0] / sizeof (float) - float_cholesky_delete (m, n, L.data, go_out) - + cholesky_delete_flt(m / sizeof(float), n, L.data, go_out) + else: + raise TypeError("unsupported dtype %r." % L.dtype) diff --git a/sklearn/utils/class_weight.py b/sklearn/utils/class_weight.py new file mode 100644 index 0000000000000..88b07eb1dec02 --- /dev/null +++ b/sklearn/utils/class_weight.py @@ -0,0 +1,166 @@ +# Authors: Andreas Mueller +# Manoj Kumar +# License: BSD 3 clause + +import numpy as np +from ..externals import six +from ..utils.fixes import in1d + +from .fixes import bincount + + +def compute_class_weight(class_weight, classes, y): + """Estimate class weights for unbalanced datasets. + + Parameters + ---------- + class_weight : dict, 'auto' or None + If 'auto', class weights will be given inverse proportional + to the frequency of the class in the data. + If a dictionary is given, keys are classes and values + are corresponding class weights. + If None is given, the class weights will be uniform. + + classes : ndarray + Array of the classes occurring in the data, as given by + ``np.unique(y_org)`` with ``y_org`` the original class labels. + + y : array-like, shape (n_samples,) + Array of original class labels per sample; + + Returns + ------- + class_weight_vect : ndarray, shape (n_classes,) + Array with class_weight_vect[i] the weight for i-th class + """ + # Import error caused by circular imports. + from ..preprocessing import LabelEncoder + + if class_weight is None or len(class_weight) == 0: + # uniform class weights + weight = np.ones(classes.shape[0], dtype=np.float64, order='C') + elif class_weight == 'auto': + # Find the weight of each class as present in y. + le = LabelEncoder() + y_ind = le.fit_transform(y) + if not all(np.in1d(classes, le.classes_)): + raise ValueError("classes should have valid labels that are in y") + + # inversely proportional to the number of samples in the class + recip_freq = 1. / bincount(y_ind) + weight = recip_freq[le.transform(classes)] / np.mean(recip_freq) + else: + # user-defined dictionary + weight = np.ones(classes.shape[0], dtype=np.float64, order='C') + if not isinstance(class_weight, dict): + raise ValueError("class_weight must be dict, 'auto', or None," + " got: %r" % class_weight) + for c in class_weight: + i = np.searchsorted(classes, c) + if classes[i] != c: + raise ValueError("Class label %d not present." % c) + else: + weight[i] = class_weight[c] + + return weight + + +def compute_sample_weight(class_weight, y, indices=None): + """Estimate sample weights by class for unbalanced datasets. + + Parameters + ---------- + class_weight : dict, list of dicts, "auto", or None, optional + Weights associated with classes in the form ``{class_label: weight}``. + If not given, all classes are supposed to have weight one. For + multi-output problems, a list of dicts can be provided in the same + order as the columns of y. + + The "auto" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data. + + For multi-output, the weights of each column of y will be multiplied. + + y : array-like, shape = [n_samples] or [n_samples, n_outputs] + Array of original class labels per sample. + + indices : array-like, shape (n_subsample,), or None + Array of indices to be used in a subsample. Can be of length less than + n_samples in the case of a subsample, or equal to n_samples in the + case of a bootstrap subsample with repeated indices. If None, the + sample weight will be calculated over the full sample. Only "auto" is + supported for class_weight if this is provided. + + Returns + ------- + sample_weight_vect : ndarray, shape (n_samples,) + Array with sample weights as applied to the original y + """ + + y = np.atleast_1d(y) + if y.ndim == 1: + y = np.reshape(y, (-1, 1)) + n_outputs = y.shape[1] + + if isinstance(class_weight, six.string_types): + if class_weight != 'auto': + raise ValueError('The only valid preset for class_weight is ' + '"auto". Given "%s".' % class_weight) + elif (indices is not None and + not isinstance(class_weight, six.string_types)): + raise ValueError('The only valid class_weight for subsampling is ' + '"auto". Given "%s".' % class_weight) + elif n_outputs > 1: + if (not hasattr(class_weight, "__iter__") or + isinstance(class_weight, dict)): + raise ValueError("For multi-output, class_weight should be a " + "list of dicts, or a valid string.") + if len(class_weight) != n_outputs: + raise ValueError("For multi-output, number of elements in " + "class_weight should match number of outputs.") + + expanded_class_weight = [] + for k in range(n_outputs): + + y_full = y[:, k] + classes_full = np.unique(y_full) + classes_missing = None + + if class_weight == 'auto' or n_outputs == 1: + class_weight_k = class_weight + else: + class_weight_k = class_weight[k] + + if indices is not None: + # Get class weights for the subsample, covering all classes in + # case some labels that were present in the original data are + # missing from the sample. + y_subsample = y[indices, k] + classes_subsample = np.unique(y_subsample) + + weight_k = np.choose(np.searchsorted(classes_subsample, + classes_full), + compute_class_weight(class_weight_k, + classes_subsample, + y_subsample), + mode='clip') + + classes_missing = set(classes_full) - set(classes_subsample) + else: + weight_k = compute_class_weight(class_weight_k, + classes_full, + y_full) + + weight_k = weight_k[np.searchsorted(classes_full, y_full)] + + if classes_missing: + # Make missing classes' weight zero + weight_k[in1d(y_full, list(classes_missing))] = 0. + + expanded_class_weight.append(weight_k) + + expanded_class_weight = np.prod(expanded_class_weight, + axis=0, + dtype=np.float64) + + return expanded_class_weight diff --git a/sklearn/utils/estimator_checks.py b/sklearn/utils/estimator_checks.py new file mode 100644 index 0000000000000..59b18cc195a4e --- /dev/null +++ b/sklearn/utils/estimator_checks.py @@ -0,0 +1,1123 @@ +from __future__ import print_function + +import warnings +import sys +import traceback +import inspect +import pickle +from copy import deepcopy + +import numpy as np +from scipy import sparse +import struct + +from sklearn.externals.six.moves import zip +from sklearn.externals.joblib import hash +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_raise_message +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import META_ESTIMATORS +from sklearn.utils.testing import set_random_state +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import SkipTest +from sklearn.utils.testing import check_skip_travis +from sklearn.utils.testing import ignore_warnings + +from sklearn.base import clone, ClassifierMixin +from sklearn.metrics import accuracy_score, adjusted_rand_score, f1_score + +from sklearn.lda import LDA +from sklearn.random_projection import BaseRandomProjection +from sklearn.feature_selection import SelectKBest +from sklearn.svm.base import BaseLibSVM +from sklearn.pipeline import make_pipeline + +from sklearn.utils.validation import DataConversionWarning, NotFittedError +from sklearn.cross_validation import train_test_split + +from sklearn.utils import shuffle +from sklearn.preprocessing import StandardScaler +from sklearn.datasets import load_iris, load_boston, make_blobs + + +BOSTON = None +CROSS_DECOMPOSITION = ['PLSCanonical', 'PLSRegression', 'CCA', 'PLSSVD'] + + +def _boston_subset(n_samples=200): + global BOSTON + if BOSTON is None: + boston = load_boston() + X, y = boston.data, boston.target + X, y = shuffle(X, y, random_state=0) + X, y = X[:n_samples], y[:n_samples] + X = StandardScaler().fit_transform(X) + BOSTON = X, y + return BOSTON + + +def set_fast_parameters(estimator): + # speed up some estimators + params = estimator.get_params() + if estimator.__class__.__name__ == 'OrthogonalMatchingPursuitCV': + # FIXME: This test is unstable on Travis, see issue #3190. + check_skip_travis() + if ("n_iter" in params + and estimator.__class__.__name__ != "TSNE"): + estimator.set_params(n_iter=5) + if "max_iter" in params: + # NMF + if estimator.max_iter is not None: + estimator.set_params(max_iter=min(5, estimator.max_iter)) + # LinearSVR + if estimator.__class__.__name__ == 'LinearSVR': + estimator.set_params(max_iter=20) + if "n_resampling" in params: + # randomized lasso + estimator.set_params(n_resampling=5) + if "n_estimators" in params: + # especially gradient boosting with default 100 + estimator.set_params(n_estimators=min(5, estimator.n_estimators)) + if "max_trials" in params: + # RANSAC + estimator.set_params(max_trials=10) + if "n_init" in params: + # K-Means + estimator.set_params(n_init=2) + + if estimator.__class__.__name__ == "SelectFdr": + # be tolerant of noisy datasets (not actually speed) + estimator.set_params(alpha=.5) + + if estimator.__class__.__name__ == "TheilSenRegressor": + estimator.max_subpopulation = 100 + + if isinstance(estimator, BaseRandomProjection): + # Due to the jl lemma and often very few samples, the number + # of components of the random matrix projection will be probably + # greater than the number of features. + # So we impose a smaller number (avoid "auto" mode) + estimator.set_params(n_components=1) + + if isinstance(estimator, SelectKBest): + # SelectKBest has a default of k=10 + # which is more feature than we have in most case. + estimator.set_params(k=1) + + +class NotAnArray(object): + " An object that is convertable to an array" + + def __init__(self, data): + self.data = data + + def __array__(self, dtype=None): + return self.data + + +def _is_32bit(): + """Detect if process is 32bit Python.""" + return struct.calcsize('P') * 8 == 32 + + +def check_estimator_sparse_data(name, Estimator): + rng = np.random.RandomState(0) + X = rng.rand(40, 10) + X[X < .8] = 0 + X = sparse.csr_matrix(X) + y = (4 * rng.rand(40)).astype(np.int) + # catch deprecation warnings + with warnings.catch_warnings(): + if name in ['Scaler', 'StandardScaler']: + estimator = Estimator(with_mean=False) + else: + estimator = Estimator() + set_fast_parameters(estimator) + # fit and predict + try: + estimator.fit(X, y) + if hasattr(estimator, "predict"): + estimator.predict(X) + if hasattr(estimator, 'predict_proba'): + estimator.predict_proba(X) + except TypeError as e: + if 'sparse' not in repr(e): + print("Estimator %s doesn't seem to fail gracefully on " + "sparse data: error message state explicitly that " + "sparse input is not supported if this is not the case." + % name) + raise + except Exception: + print("Estimator %s doesn't seem to fail gracefully on " + "sparse data: it should raise a TypeError if sparse input " + "is explicitly not supported." % name) + raise + + +def check_dtype_object(name, Estimator): + # check that estimators treat dtype object as numeric if possible + rng = np.random.RandomState(0) + X = rng.rand(40, 10).astype(object) + y = (X[:, 0] * 4).astype(np.int) + y = multioutput_estimator_convert_y_2d(name, y) + with warnings.catch_warnings(): + estimator = Estimator() + set_fast_parameters(estimator) + + estimator.fit(X, y) + if hasattr(estimator, "predict"): + estimator.predict(X) + + if hasattr(estimator, "transform"): + estimator.transform(X) + + try: + estimator.fit(X, y.astype(object)) + except Exception as e: + if "Unknown label type" not in str(e): + raise + + X[0, 0] = {'foo': 'bar'} + assert_raise_message(TypeError, "string or a number", estimator.fit, X, y) + + +def check_transformer(name, Transformer): + X, y = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, n_features=2, cluster_std=0.1) + X = StandardScaler().fit_transform(X) + X -= X.min() + _check_transformer(name, Transformer, X, y) + _check_transformer(name, Transformer, X.tolist(), y.tolist()) + + +def check_transformer_data_not_an_array(name, Transformer): + X, y = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, n_features=2, cluster_std=0.1) + X = StandardScaler().fit_transform(X) + # We need to make sure that we have non negative data, for things + # like NMF + X -= X.min() - .1 + this_X = NotAnArray(X) + this_y = NotAnArray(np.asarray(y)) + _check_transformer(name, Transformer, this_X, this_y) + + +def check_transformers_unfitted(name, Transformer): + X, y = _boston_subset() + + with warnings.catch_warnings(record=True): + transformer = Transformer() + + assert_raises(NotFittedError, transformer.transform, X) + + +def _check_transformer(name, Transformer, X, y): + if name in ('CCA', 'LocallyLinearEmbedding', 'KernelPCA') and _is_32bit(): + # Those transformers yield non-deterministic output when executed on + # a 32bit Python. The same transformers are stable on 64bit Python. + # FIXME: try to isolate a minimalistic reproduction case only depending + # on numpy & scipy and/or maybe generate a test dataset that does not + # cause such unstable behaviors. + msg = name + ' is non deterministic on 32bit Python' + raise SkipTest(msg) + n_samples, n_features = np.asarray(X).shape + # catch deprecation warnings + with warnings.catch_warnings(record=True): + transformer = Transformer() + set_random_state(transformer) + set_fast_parameters(transformer) + + # fit + + if name in CROSS_DECOMPOSITION: + y_ = np.c_[y, y] + y_[::2, 1] *= 2 + else: + y_ = y + + transformer.fit(X, y_) + X_pred = transformer.fit_transform(X, y=y_) + if isinstance(X_pred, tuple): + for x_pred in X_pred: + assert_equal(x_pred.shape[0], n_samples) + else: + assert_equal(X_pred.shape[0], n_samples) + + if hasattr(transformer, 'transform'): + if name in CROSS_DECOMPOSITION: + X_pred2 = transformer.transform(X, y_) + X_pred3 = transformer.fit_transform(X, y=y_) + else: + X_pred2 = transformer.transform(X) + X_pred3 = transformer.fit_transform(X, y=y_) + if isinstance(X_pred, tuple) and isinstance(X_pred2, tuple): + for x_pred, x_pred2, x_pred3 in zip(X_pred, X_pred2, X_pred3): + assert_array_almost_equal( + x_pred, x_pred2, 2, + "fit_transform and transform outcomes not consistent in %s" + % Transformer) + assert_array_almost_equal( + x_pred, x_pred3, 2, + "consecutive fit_transform outcomes not consistent in %s" + % Transformer) + else: + assert_array_almost_equal( + X_pred, X_pred2, 2, + "fit_transform and transform outcomes not consistent in %s" + % Transformer) + assert_array_almost_equal( + X_pred, X_pred3, 2, + "consecutive fit_transform outcomes not consistent in %s" + % Transformer) + + # raises error on malformed input for transform + if hasattr(X, 'T'): + # If it's not an array, it does not have a 'T' property + assert_raises(ValueError, transformer.transform, X.T) + + +@ignore_warnings +def check_pipeline_consistency(name, Estimator): + if name in ('CCA', 'LocallyLinearEmbedding', 'KernelPCA') and _is_32bit(): + # Those transformers yield non-deterministic output when executed on + # a 32bit Python. The same transformers are stable on 64bit Python. + # FIXME: try to isolate a minimalistic reproduction case only depending + # scipy and/or maybe generate a test dataset that does not + # cause such unstable behaviors. + msg = name + ' is non deterministic on 32bit Python' + raise SkipTest(msg) + + # check that make_pipeline(est) gives same score as est + X, y = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, n_features=2, cluster_std=0.1) + X -= X.min() + y = multioutput_estimator_convert_y_2d(name, y) + estimator = Estimator() + set_fast_parameters(estimator) + set_random_state(estimator) + pipeline = make_pipeline(estimator) + estimator.fit(X, y) + pipeline.fit(X, y) + funcs = ["score", "fit_transform"] + for func_name in funcs: + func = getattr(estimator, func_name, None) + if func is not None: + func_pipeline = getattr(pipeline, func_name) + result = func(X, y) + result_pipe = func_pipeline(X, y) + assert_array_almost_equal(result, result_pipe) + + +@ignore_warnings +def check_fit_score_takes_y(name, Estimator): + # check that all estimators accept an optional y + # in fit and score so they can be used in pipelines + rnd = np.random.RandomState(0) + X = rnd.uniform(size=(10, 3)) + y = np.arange(10) % 3 + y = multioutput_estimator_convert_y_2d(name, y) + estimator = Estimator() + set_fast_parameters(estimator) + set_random_state(estimator) + funcs = ["fit", "score", "partial_fit", "fit_predict", "fit_transform"] + + for func_name in funcs: + func = getattr(estimator, func_name, None) + if func is not None: + func(X, y) + args = inspect.getargspec(func).args + assert_true(args[2] in ["y", "Y"]) + + +@ignore_warnings +def check_estimators_dtypes(name, Estimator): + rnd = np.random.RandomState(0) + X_train_32 = 3 * rnd.uniform(size=(20, 5)).astype(np.float32) + X_train_64 = X_train_32.astype(np.float64) + X_train_int_64 = X_train_32.astype(np.int64) + X_train_int_32 = X_train_32.astype(np.int32) + y = X_train_int_64[:, 0] + y = multioutput_estimator_convert_y_2d(name, y) + for X_train in [X_train_32, X_train_64, X_train_int_64, X_train_int_32]: + with warnings.catch_warnings(record=True): + estimator = Estimator() + set_fast_parameters(estimator) + set_random_state(estimator, 1) + estimator.fit(X_train, y) + + for method in ["predict", "transform", "decision_function", + "predict_proba"]: + if hasattr(estimator, method): + getattr(estimator, method)(X_train) + + +def check_estimators_empty_data_messages(name, Estimator): + e = Estimator() + set_fast_parameters(e) + set_random_state(e, 1) + + X_zero_samples = np.empty(0).reshape(0, 3) + # The precise message can change depending on whether X or y is + # validated first. Let us test the type of exception only: + assert_raises(ValueError, e.fit, X_zero_samples, []) + + X_zero_features = np.empty(0).reshape(3, 0) + # the following y should be accepted by both classifiers and regressors + # and ignored by unsupervised models + y = multioutput_estimator_convert_y_2d(name, np.array([1, 0, 1])) + msg = "0 feature(s) (shape=(3, 0)) while a minimum of 1 is required." + assert_raise_message(ValueError, msg, e.fit, X_zero_features, y) + + +def check_estimators_nan_inf(name, Estimator): + rnd = np.random.RandomState(0) + X_train_finite = rnd.uniform(size=(10, 3)) + X_train_nan = rnd.uniform(size=(10, 3)) + X_train_nan[0, 0] = np.nan + X_train_inf = rnd.uniform(size=(10, 3)) + X_train_inf[0, 0] = np.inf + y = np.ones(10) + y[:5] = 0 + y = multioutput_estimator_convert_y_2d(name, y) + error_string_fit = "Estimator doesn't check for NaN and inf in fit." + error_string_predict = ("Estimator doesn't check for NaN and inf in" + " predict.") + error_string_transform = ("Estimator doesn't check for NaN and inf in" + " transform.") + for X_train in [X_train_nan, X_train_inf]: + # catch deprecation warnings + with warnings.catch_warnings(record=True): + estimator = Estimator() + set_fast_parameters(estimator) + set_random_state(estimator, 1) + # try to fit + try: + estimator.fit(X_train, y) + except ValueError as e: + if 'inf' not in repr(e) and 'NaN' not in repr(e): + print(error_string_fit, Estimator, e) + traceback.print_exc(file=sys.stdout) + raise e + except Exception as exc: + print(error_string_fit, Estimator, exc) + traceback.print_exc(file=sys.stdout) + raise exc + else: + raise AssertionError(error_string_fit, Estimator) + # actually fit + estimator.fit(X_train_finite, y) + + # predict + if hasattr(estimator, "predict"): + try: + estimator.predict(X_train) + except ValueError as e: + if 'inf' not in repr(e) and 'NaN' not in repr(e): + print(error_string_predict, Estimator, e) + traceback.print_exc(file=sys.stdout) + raise e + except Exception as exc: + print(error_string_predict, Estimator, exc) + traceback.print_exc(file=sys.stdout) + else: + raise AssertionError(error_string_predict, Estimator) + + # transform + if hasattr(estimator, "transform"): + try: + estimator.transform(X_train) + except ValueError as e: + if 'inf' not in repr(e) and 'NaN' not in repr(e): + print(error_string_transform, Estimator, e) + traceback.print_exc(file=sys.stdout) + raise e + except Exception as exc: + print(error_string_transform, Estimator, exc) + traceback.print_exc(file=sys.stdout) + else: + raise AssertionError(error_string_transform, Estimator) + + +def check_transformer_pickle(name, Transformer): + X, y = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, n_features=2, cluster_std=0.1) + n_samples, n_features = X.shape + X = StandardScaler().fit_transform(X) + X -= X.min() + # catch deprecation warnings + with warnings.catch_warnings(record=True): + transformer = Transformer() + if not hasattr(transformer, 'transform'): + return + set_random_state(transformer) + set_fast_parameters(transformer) + + # fit + if name in CROSS_DECOMPOSITION: + random_state = np.random.RandomState(seed=12345) + y_ = np.vstack([y, 2 * y + random_state.randint(2, size=len(y))]) + y_ = y_.T + else: + y_ = y + + transformer.fit(X, y_) + X_pred = transformer.fit(X, y_).transform(X) + pickled_transformer = pickle.dumps(transformer) + unpickled_transformer = pickle.loads(pickled_transformer) + pickled_X_pred = unpickled_transformer.transform(X) + + assert_array_almost_equal(pickled_X_pred, X_pred) + + +def check_estimators_partial_fit_n_features(name, Alg): + # check if number of features changes between calls to partial_fit. + if not hasattr(Alg, 'partial_fit'): + return + X, y = make_blobs(n_samples=50, random_state=1) + X -= X.min() + with warnings.catch_warnings(record=True): + alg = Alg() + set_fast_parameters(alg) + if isinstance(alg, ClassifierMixin): + classes = np.unique(y) + alg.partial_fit(X, y, classes=classes) + else: + alg.partial_fit(X, y) + + assert_raises(ValueError, alg.partial_fit, X[:, :-1], y) + + +def check_clustering(name, Alg): + X, y = make_blobs(n_samples=50, random_state=1) + X, y = shuffle(X, y, random_state=7) + X = StandardScaler().fit_transform(X) + n_samples, n_features = X.shape + # catch deprecation and neighbors warnings + with warnings.catch_warnings(record=True): + alg = Alg() + set_fast_parameters(alg) + if hasattr(alg, "n_clusters"): + alg.set_params(n_clusters=3) + set_random_state(alg) + if name == 'AffinityPropagation': + alg.set_params(preference=-100) + alg.set_params(max_iter=100) + + # fit + alg.fit(X) + # with lists + alg.fit(X.tolist()) + + assert_equal(alg.labels_.shape, (n_samples,)) + pred = alg.labels_ + assert_greater(adjusted_rand_score(pred, y), 0.4) + # fit another time with ``fit_predict`` and compare results + if name is 'SpectralClustering': + # there is no way to make Spectral clustering deterministic :( + return + set_random_state(alg) + with warnings.catch_warnings(record=True): + pred2 = alg.fit_predict(X) + assert_array_equal(pred, pred2) + + +def check_clusterer_compute_labels_predict(name, Clusterer): + """Check that predict is invariant of compute_labels""" + X, y = make_blobs(n_samples=20, random_state=0) + clusterer = Clusterer() + + if hasattr(clusterer, "compute_labels"): + # MiniBatchKMeans + if hasattr(clusterer, "random_state"): + clusterer.set_params(random_state=0) + + X_pred1 = clusterer.fit(X).predict(X) + clusterer.set_params(compute_labels=False) + X_pred2 = clusterer.fit(X).predict(X) + assert_array_equal(X_pred1, X_pred2) + + +def check_classifiers_one_label(name, Classifier): + error_string_fit = "Classifier can't train when only one class is present." + error_string_predict = ("Classifier can't predict when only one class is " + "present.") + rnd = np.random.RandomState(0) + X_train = rnd.uniform(size=(10, 3)) + X_test = rnd.uniform(size=(10, 3)) + y = np.ones(10) + # catch deprecation warnings + with warnings.catch_warnings(record=True): + classifier = Classifier() + set_fast_parameters(classifier) + # try to fit + try: + classifier.fit(X_train, y) + except ValueError as e: + if 'class' not in repr(e): + print(error_string_fit, Classifier, e) + traceback.print_exc(file=sys.stdout) + raise e + else: + return + except Exception as exc: + print(error_string_fit, Classifier, exc) + traceback.print_exc(file=sys.stdout) + raise exc + # predict + try: + assert_array_equal(classifier.predict(X_test), y) + except Exception as exc: + print(error_string_predict, Classifier, exc) + raise exc + + +def check_classifiers_train(name, Classifier): + X_m, y_m = make_blobs(random_state=0) + X_m, y_m = shuffle(X_m, y_m, random_state=7) + X_m = StandardScaler().fit_transform(X_m) + # generate binary problem from multi-class one + y_b = y_m[y_m != 2] + X_b = X_m[y_m != 2] + for (X, y) in [(X_m, y_m), (X_b, y_b)]: + # catch deprecation warnings + classes = np.unique(y) + n_classes = len(classes) + n_samples, n_features = X.shape + with warnings.catch_warnings(record=True): + classifier = Classifier() + if name in ['BernoulliNB', 'MultinomialNB']: + X -= X.min() + set_fast_parameters(classifier) + set_random_state(classifier) + # raises error on malformed input for fit + assert_raises(ValueError, classifier.fit, X, y[:-1]) + + # fit + classifier.fit(X, y) + # with lists + classifier.fit(X.tolist(), y.tolist()) + assert_true(hasattr(classifier, "classes_")) + y_pred = classifier.predict(X) + assert_equal(y_pred.shape, (n_samples,)) + # training set performance + if name not in ['BernoulliNB', 'MultinomialNB']: + assert_greater(accuracy_score(y, y_pred), 0.83) + + # raises error on malformed input for predict + assert_raises(ValueError, classifier.predict, X.T) + if hasattr(classifier, "decision_function"): + try: + # decision_function agrees with predict + decision = classifier.decision_function(X) + if n_classes is 2: + assert_equal(decision.shape, (n_samples,)) + dec_pred = (decision.ravel() > 0).astype(np.int) + assert_array_equal(dec_pred, y_pred) + if (n_classes is 3 + and not isinstance(classifier, BaseLibSVM)): + # 1on1 of LibSVM works differently + assert_equal(decision.shape, (n_samples, n_classes)) + assert_array_equal(np.argmax(decision, axis=1), y_pred) + + # raises error on malformed input + assert_raises(ValueError, + classifier.decision_function, X.T) + # raises error on malformed input for decision_function + assert_raises(ValueError, + classifier.decision_function, X.T) + except NotImplementedError: + pass + if hasattr(classifier, "predict_proba"): + # predict_proba agrees with predict + y_prob = classifier.predict_proba(X) + assert_equal(y_prob.shape, (n_samples, n_classes)) + assert_array_equal(np.argmax(y_prob, axis=1), y_pred) + # check that probas for all classes sum to one + assert_array_almost_equal(np.sum(y_prob, axis=1), + np.ones(n_samples)) + # raises error on malformed input + assert_raises(ValueError, classifier.predict_proba, X.T) + # raises error on malformed input for predict_proba + assert_raises(ValueError, classifier.predict_proba, X.T) + + +def check_estimators_unfitted(name, Estimator): + """Check if NotFittedError is raised when calling predict and related + functions""" + + # Common test for Regressors as well as Classifiers + X, y = _boston_subset() + + with warnings.catch_warnings(record=True): + est = Estimator() + + assert_raises(NotFittedError, est.predict, X) + + if hasattr(est, 'predict'): + assert_raises(NotFittedError, est.predict, X) + + if hasattr(est, 'decision_function'): + assert_raises(NotFittedError, est.decision_function, X) + + if hasattr(est, 'predict_proba'): + assert_raises(NotFittedError, est.predict_proba, X) + + if hasattr(est, 'predict_log_proba'): + assert_raises(NotFittedError, est.predict_log_proba, X) + + +def check_classifiers_input_shapes(name, Classifier): + iris = load_iris() + X, y = iris.data, iris.target + X, y = shuffle(X, y, random_state=1) + X = StandardScaler().fit_transform(X) + # catch deprecation warnings + with warnings.catch_warnings(record=True): + classifier = Classifier() + set_fast_parameters(classifier) + set_random_state(classifier) + # fit + classifier.fit(X, y) + y_pred = classifier.predict(X) + + set_random_state(classifier) + # Check that when a 2D y is given, a DataConversionWarning is + # raised + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always", DataConversionWarning) + warnings.simplefilter("ignore", RuntimeWarning) + classifier.fit(X, y[:, np.newaxis]) + msg = "expected 1 DataConversionWarning, got: %s" % ( + ", ".join([str(w_x) for w_x in w])) + assert_equal(len(w), 1, msg) + assert_array_equal(y_pred, classifier.predict(X)) + + +def check_classifiers_classes(name, Classifier): + X, y = make_blobs(n_samples=30, random_state=0, cluster_std=0.1) + X, y = shuffle(X, y, random_state=7) + X = StandardScaler().fit_transform(X) + # We need to make sure that we have non negative data, for things + # like NMF + X -= X.min() - .1 + y_names = np.array(["one", "two", "three"])[y] + + for y_names in [y_names, y_names.astype('O')]: + if name in ["LabelPropagation", "LabelSpreading"]: + # TODO some complication with -1 label + y_ = y + else: + y_ = y_names + + classes = np.unique(y_) + # catch deprecation warnings + with warnings.catch_warnings(record=True): + classifier = Classifier() + if name == 'BernoulliNB': + classifier.set_params(binarize=X.mean()) + set_fast_parameters(classifier) + # fit + classifier.fit(X, y_) + + y_pred = classifier.predict(X) + # training set performance + assert_array_equal(np.unique(y_), np.unique(y_pred)) + if np.any(classifier.classes_ != classes): + print("Unexpected classes_ attribute for %r: " + "expected %s, got %s" % + (classifier, classes, classifier.classes_)) + + +def check_classifiers_pickle(name, Classifier): + X, y = make_blobs(random_state=0) + X, y = shuffle(X, y, random_state=7) + X -= X.min() + + # catch deprecation warnings + with warnings.catch_warnings(record=True): + classifier = Classifier() + set_fast_parameters(classifier) + # raises error on malformed input for fit + assert_raises(ValueError, classifier.fit, X, y[:-1]) + + # fit + classifier.fit(X, y) + y_pred = classifier.predict(X) + pickled_classifier = pickle.dumps(classifier) + unpickled_classifier = pickle.loads(pickled_classifier) + pickled_y_pred = unpickled_classifier.predict(X) + + assert_array_almost_equal(pickled_y_pred, y_pred) + + +def check_regressors_int(name, Regressor): + X, _ = _boston_subset() + X = X[:50] + rnd = np.random.RandomState(0) + y = rnd.randint(3, size=X.shape[0]) + y = multioutput_estimator_convert_y_2d(name, y) + rnd = np.random.RandomState(0) + # catch deprecation warnings + with warnings.catch_warnings(record=True): + # separate estimators to control random seeds + regressor_1 = Regressor() + regressor_2 = Regressor() + set_fast_parameters(regressor_1) + set_fast_parameters(regressor_2) + set_random_state(regressor_1) + set_random_state(regressor_2) + + if name in CROSS_DECOMPOSITION: + y_ = np.vstack([y, 2 * y + rnd.randint(2, size=len(y))]) + y_ = y_.T + else: + y_ = y + + # fit + regressor_1.fit(X, y_) + pred1 = regressor_1.predict(X) + regressor_2.fit(X, y_.astype(np.float)) + pred2 = regressor_2.predict(X) + assert_array_almost_equal(pred1, pred2, 2, name) + + +def check_regressors_train(name, Regressor): + X, y = _boston_subset() + y = StandardScaler().fit_transform(y) # X is already scaled + y = multioutput_estimator_convert_y_2d(name, y) + rnd = np.random.RandomState(0) + # catch deprecation warnings + with warnings.catch_warnings(record=True): + regressor = Regressor() + set_fast_parameters(regressor) + if not hasattr(regressor, 'alphas') and hasattr(regressor, 'alpha'): + # linear regressors need to set alpha, but not generalized CV ones + regressor.alpha = 0.01 + if name == 'PassiveAggressiveRegressor': + regressor.C = 0.01 + + # raises error on malformed input for fit + assert_raises(ValueError, regressor.fit, X, y[:-1]) + # fit + if name in CROSS_DECOMPOSITION: + y_ = np.vstack([y, 2 * y + rnd.randint(2, size=len(y))]) + y_ = y_.T + else: + y_ = y + set_random_state(regressor) + regressor.fit(X, y_) + regressor.fit(X.tolist(), y_.tolist()) + regressor.predict(X) + + # TODO: find out why PLS and CCA fail. RANSAC is random + # and furthermore assumes the presence of outliers, hence + # skipped + if name not in ('PLSCanonical', 'CCA', 'RANSACRegressor'): + print(regressor) + assert_greater(regressor.score(X, y_), 0.5) + + +def check_regressors_pickle(name, Regressor): + X, y = _boston_subset() + y = StandardScaler().fit_transform(y) # X is already scaled + y = multioutput_estimator_convert_y_2d(name, y) + rnd = np.random.RandomState(0) + # catch deprecation warnings + with warnings.catch_warnings(record=True): + regressor = Regressor() + set_fast_parameters(regressor) + if not hasattr(regressor, 'alphas') and hasattr(regressor, 'alpha'): + # linear regressors need to set alpha, but not generalized CV ones + regressor.alpha = 0.01 + + if name in CROSS_DECOMPOSITION: + y_ = np.vstack([y, 2 * y + rnd.randint(2, size=len(y))]) + y_ = y_.T + else: + y_ = y + regressor.fit(X, y_) + y_pred = regressor.predict(X) + # store old predictions + pickled_regressor = pickle.dumps(regressor) + unpickled_regressor = pickle.loads(pickled_regressor) + pickled_y_pred = unpickled_regressor.predict(X) + assert_array_almost_equal(pickled_y_pred, y_pred) + + +def check_class_weight_classifiers(name, Classifier): + for n_centers in [2, 3]: + # create a very noisy dataset + X, y = make_blobs(centers=n_centers, random_state=0, cluster_std=20) + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, + random_state=0) + n_centers = len(np.unique(y_train)) + + if n_centers == 2: + class_weight = {0: 1000, 1: 0.0001} + else: + class_weight = {0: 1000, 1: 0.0001, 2: 0.0001} + + with warnings.catch_warnings(record=True): + classifier = Classifier(class_weight=class_weight) + if hasattr(classifier, "n_iter"): + classifier.set_params(n_iter=100) + if hasattr(classifier, "min_weight_fraction_leaf"): + classifier.set_params(min_weight_fraction_leaf=0.01) + + set_random_state(classifier) + classifier.fit(X_train, y_train) + y_pred = classifier.predict(X_test) + assert_greater(np.mean(y_pred == 0), 0.89) + + +def check_class_weight_auto_classifiers(name, Classifier, X_train, y_train, + X_test, y_test, weights): + with warnings.catch_warnings(record=True): + classifier = Classifier() + if hasattr(classifier, "n_iter"): + classifier.set_params(n_iter=100) + + set_random_state(classifier) + classifier.fit(X_train, y_train) + y_pred = classifier.predict(X_test) + + classifier.set_params(class_weight='auto') + classifier.fit(X_train, y_train) + y_pred_auto = classifier.predict(X_test) + assert_greater(f1_score(y_test, y_pred_auto, average='weighted'), + f1_score(y_test, y_pred, average='weighted')) + + +def check_class_weight_auto_linear_classifier(name, Classifier): + """Test class weights with non-contiguous class labels.""" + X = np.array([[-1.0, -1.0], [-1.0, 0], [-.8, -1.0], + [1.0, 1.0], [1.0, 0.0]]) + y = [1, 1, 1, -1, -1] + + with warnings.catch_warnings(record=True): + classifier = Classifier() + if hasattr(classifier, "n_iter"): + # This is a very small dataset, default n_iter are likely to prevent + # convergence + classifier.set_params(n_iter=1000) + set_random_state(classifier) + + # Let the model compute the class frequencies + classifier.set_params(class_weight='auto') + coef_auto = classifier.fit(X, y).coef_.copy() + + # Count each label occurrence to reweight manually + mean_weight = (1. / 3 + 1. / 2) / 2 + class_weight = { + 1: 1. / 3 / mean_weight, + -1: 1. / 2 / mean_weight, + } + classifier.set_params(class_weight=class_weight) + coef_manual = classifier.fit(X, y).coef_.copy() + + assert_array_almost_equal(coef_auto, coef_manual) + + +def check_estimators_overwrite_params(name, Estimator): + X, y = make_blobs(random_state=0, n_samples=9) + y = multioutput_estimator_convert_y_2d(name, y) + # some want non-negative input + X -= X.min() + with warnings.catch_warnings(record=True): + # catch deprecation warnings + estimator = Estimator() + + if name == 'MiniBatchDictLearning' or name == 'MiniBatchSparsePCA': + # FIXME + # for MiniBatchDictLearning and MiniBatchSparsePCA + estimator.batch_size = 1 + + set_fast_parameters(estimator) + set_random_state(estimator) + + # Make a physical copy of the orginal estimator parameters before fitting. + params = estimator.get_params() + original_params = deepcopy(params) + + # Fit the model + estimator.fit(X, y) + + # Compare the state of the model parameters with the original parameters + new_params = estimator.get_params() + for param_name, original_value in original_params.items(): + new_value = new_params[param_name] + + # We should never change or mutate the internal state of input + # parameters by default. To check this we use the joblib.hash function + # that introspects recursively any subobjects to compute a checksum. + # The only exception to this rule of immutable constructor parameters + # is possible RandomState instance but in this check we explicitly + # fixed the random_state params recursively to be integer seeds. + assert_equal(hash(new_value), hash(original_value), + "Estimator %s should not change or mutate " + " the parameter %s from %s to %s during fit." + % (name, param_name, original_value, new_value)) + + +def check_sparsify_coefficients(name, Estimator): + X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1], + [-1, -2], [2, 2], [-2, -2]]) + y = [1, 1, 1, 2, 2, 2, 3, 3, 3] + est = Estimator() + + est.fit(X, y) + pred_orig = est.predict(X) + + # test sparsify with dense inputs + est.sparsify() + assert_true(sparse.issparse(est.coef_)) + pred = est.predict(X) + assert_array_equal(pred, pred_orig) + + # pickle and unpickle with sparse coef_ + est = pickle.loads(pickle.dumps(est)) + assert_true(sparse.issparse(est.coef_)) + pred = est.predict(X) + assert_array_equal(pred, pred_orig) + + +def check_classifier_data_not_an_array(name, Estimator): + X = np.array([[3, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 1]]) + y = [1, 1, 1, 2, 2, 2] + y = multioutput_estimator_convert_y_2d(name, y) + check_estimators_data_not_an_array(name, Estimator, X, y) + + +def check_regressor_data_not_an_array(name, Estimator): + X, y = _boston_subset(n_samples=50) + y = multioutput_estimator_convert_y_2d(name, y) + check_estimators_data_not_an_array(name, Estimator, X, y) + + +def check_estimators_data_not_an_array(name, Estimator, X, y): + + if name in CROSS_DECOMPOSITION: + raise SkipTest + # catch deprecation warnings + with warnings.catch_warnings(record=True): + # separate estimators to control random seeds + estimator_1 = Estimator() + estimator_2 = Estimator() + set_fast_parameters(estimator_1) + set_fast_parameters(estimator_2) + set_random_state(estimator_1) + set_random_state(estimator_2) + + y_ = NotAnArray(np.asarray(y)) + X_ = NotAnArray(np.asarray(X)) + + # fit + estimator_1.fit(X_, y_) + pred1 = estimator_1.predict(X_) + estimator_2.fit(X, y) + pred2 = estimator_2.predict(X) + assert_array_almost_equal(pred1, pred2, 2, name) + + +def check_parameters_default_constructible(name, Estimator): + classifier = LDA() + # test default-constructibility + # get rid of deprecation warnings + with warnings.catch_warnings(record=True): + if name in META_ESTIMATORS: + estimator = Estimator(classifier) + else: + estimator = Estimator() + # test cloning + clone(estimator) + # test __repr__ + repr(estimator) + # test that set_params returns self + assert_true(isinstance(estimator.set_params(), Estimator)) + + # test if init does nothing but set parameters + # this is important for grid_search etc. + # We get the default parameters from init and then + # compare these against the actual values of the attributes. + + # this comes from getattr. Gets rid of deprecation decorator. + init = getattr(estimator.__init__, 'deprecated_original', + estimator.__init__) + try: + args, varargs, kws, defaults = inspect.getargspec(init) + except TypeError: + # init is not a python function. + # true for mixins + return + params = estimator.get_params() + if name in META_ESTIMATORS: + # they need a non-default argument + args = args[2:] + else: + args = args[1:] + if args: + # non-empty list + assert_equal(len(args), len(defaults)) + else: + return + for arg, default in zip(args, defaults): + if arg not in params.keys(): + # deprecated parameter, not in get_params + assert_true(default is None) + continue + + if isinstance(params[arg], np.ndarray): + assert_array_equal(params[arg], default) + else: + assert_equal(params[arg], default) + + +def multioutput_estimator_convert_y_2d(name, y): + # Estimators in mono_output_task_error raise ValueError if y is of 1-D + # Convert into a 2-D y for those estimators. + if name in (['MultiTaskElasticNetCV', 'MultiTaskLassoCV', + 'MultiTaskLasso', 'MultiTaskElasticNet']): + return y[:, np.newaxis] + return y + + +def check_non_transformer_estimators_n_iter(name, estimator, + multi_output=False): + # Check if all iterative solvers, run for more than one iteratiom + + iris = load_iris() + X, y_ = iris.data, iris.target + + if multi_output: + y_ = y_[:, np.newaxis] + + set_random_state(estimator, 0) + if name == 'AffinityPropagation': + estimator.fit(X) + else: + estimator.fit(X, y_) + assert_greater(estimator.n_iter_, 0) + + +def check_transformer_n_iter(name, estimator): + if name in CROSS_DECOMPOSITION: + # Check using default data + X = [[0., 0., 1.], [1., 0., 0.], [2., 2., 2.], [2., 5., 4.]] + y_ = [[0.1, -0.2], [0.9, 1.1], [0.1, -0.5], [0.3, -0.2]] + + else: + X, y_ = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, n_features=2, cluster_std=0.1) + X -= X.min() - 0.1 + set_random_state(estimator, 0) + estimator.fit(X, y_) + + # These return a n_iter per component. + if name in CROSS_DECOMPOSITION: + for iter_ in estimator.n_iter_: + assert_greater(iter_, 1) + else: + assert_greater(estimator.n_iter_, 1) diff --git a/sklearn/utils/extmath.py b/sklearn/utils/extmath.py index 6ce09e502f3fd..bf9b935859c93 100644 --- a/sklearn/utils/extmath.py +++ b/sklearn/utils/extmath.py @@ -1,41 +1,78 @@ """ Extended math utilities. """ -# Authors: G. Varoquaux, A. Gramfort, A. Passos, O. Grisel -# License: BSD +# Authors: Gael Varoquaux +# Alexandre Gramfort +# Alexandre T. Passos +# Olivier Grisel +# Lars Buitinck +# Stefan van der Walt +# Kyle Kastner +# License: BSD 3 clause + +from __future__ import division +from functools import partial +import warnings import numpy as np from scipy import linalg +from scipy.sparse import issparse -from . import check_random_state -from .fixes import qr_economic +from . import check_random_state, deprecated +from .fixes import np_version +from ._logistic_sigmoid import _log_logistic_sigmoid +from ..externals.six.moves import xrange +from .sparsefuncs_fast import csr_row_norms +from .validation import check_array, NonBLASDotWarning -def norm(v): - v = np.asarray(v) - __nrm2, = linalg.get_blas_funcs(['nrm2'], [v]) - return __nrm2(v) +def norm(x): + """Compute the Euclidean or Frobenius norm of x. + Returns the Euclidean norm when x is a vector, the Frobenius norm when x + is a matrix (2-d array). More precise than sqrt(squared_norm(x)). + """ + x = np.asarray(x) + nrm2, = linalg.get_blas_funcs(['nrm2'], [x]) + return nrm2(x) -def _fast_logdet(A): - """Compute log(det(A)) for A symmetric - Equivalent to : np.log(np.linalg.det(A)) but more robust. - It returns -Inf if det(A) is non positive or is not defined. +# Newer NumPy has a ravel that needs less copying. +if np_version < (1, 7, 1): + _ravel = np.ravel +else: + _ravel = partial(np.ravel, order='K') + + +def squared_norm(x): + """Squared Euclidean or Frobenius norm of x. + + Returns the Euclidean norm when x is a vector, the Frobenius norm when x + is a matrix (2-d array). Faster than norm(x) ** 2. """ - # XXX: Should be implemented as in numpy, using ATLAS - # http://projects.scipy.org/numpy/browser/ \ - # trunk/numpy/linalg/linalg.py#L1559 - ld = np.sum(np.log(np.diag(A))) - a = np.exp(ld / A.shape[0]) - d = np.linalg.det(A / a) - ld += np.log(d) - if not np.isfinite(ld): - return -np.inf - return ld + x = _ravel(x) + return np.dot(x, x) + + +def row_norms(X, squared=False): + """Row-wise (squared) Euclidean norm of X. + + Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports CSR sparse + matrices and does not create an X.shape-sized temporary. + + Performs no input validation. + """ + if issparse(X): + norms = csr_row_norms(X) + else: + norms = np.einsum('ij,ij->i', X, X) + if not squared: + np.sqrt(norms, norms) + return norms -def _fast_logdet_numpy(A): + +def fast_logdet(A): """Compute log(det(A)) for A symmetric Equivalent to : np.log(nl.det(A)) but more robust. @@ -47,11 +84,76 @@ def _fast_logdet_numpy(A): return ld -# Numpy >= 1.5 provides a fast logdet -if hasattr(np.linalg, 'slogdet'): - fast_logdet = _fast_logdet_numpy +def _impose_f_order(X): + """Helper Function""" + # important to access flags instead of calling np.isfortran, + # this catches corner cases. + if X.flags.c_contiguous: + return check_array(X.T, copy=False, order='F'), True + else: + return check_array(X, copy=False, order='F'), False + + +def _fast_dot(A, B): + if B.shape[0] != A.shape[A.ndim - 1]: # check adopted from '_dotblas.c' + raise ValueError + + if A.dtype != B.dtype or any(x.dtype not in (np.float32, np.float64) + for x in [A, B]): + warnings.warn('Data must be of same type. Supported types ' + 'are 32 and 64 bit float. ' + 'Falling back to np.dot.', NonBLASDotWarning) + raise ValueError + + if min(A.shape) == 1 or min(B.shape) == 1 or A.ndim != 2 or B.ndim != 2: + raise ValueError + + # scipy 0.9 compliant API + dot = linalg.get_blas_funcs(['gemm'], (A, B))[0] + A, trans_a = _impose_f_order(A) + B, trans_b = _impose_f_order(B) + return dot(alpha=1.0, a=A, b=B, trans_a=trans_a, trans_b=trans_b) + + +def _have_blas_gemm(): + try: + linalg.get_blas_funcs(['gemm']) + return True + except (AttributeError, ValueError): + warnings.warn('Could not import BLAS, falling back to np.dot') + return False + + +# Only use fast_dot for older NumPy; newer ones have tackled the speed issue. +if np_version < (1, 7, 2) and _have_blas_gemm(): + def fast_dot(A, B): + """Compute fast dot products directly calling BLAS. + + This function calls BLAS directly while warranting Fortran contiguity. + This helps avoiding extra copies `np.dot` would have created. + For details see section `Linear Algebra on large Arrays`: + http://wiki.scipy.org/PerformanceTips + + Parameters + ---------- + A, B: instance of np.ndarray + Input arrays. Arrays are supposed to be of the same dtype and to + have exactly 2 dimensions. Currently only floats are supported. + In case these requirements aren't met np.dot(A, B) is returned + instead. To activate the related warning issued in this case + execute the following lines of code: + + >> import warnings + >> from sklearn.utils.validation import NonBLASDotWarning + >> warnings.simplefilter('always', NonBLASDotWarning) + """ + try: + return _fast_dot(A, B) + except ValueError: + # Maltyped or malformed data. + return np.dot(A, B) else: - fast_logdet = _fast_logdet + fast_dot = np.dot def density(w, **kwargs): @@ -59,26 +161,29 @@ def density(w, **kwargs): Return a value between 0 and 1 """ - if hasattr(w, "tocsr"): - d = float(w.data.size) / w.size + if hasattr(w, "toarray"): + d = float(w.nnz) / (w.shape[0] * w.shape[1]) else: d = 0 if w is None else float((w != 0).sum()) / w.size return d def safe_sparse_dot(a, b, dense_output=False): - """Dot product that handle the sparse matrix case correctly""" - from scipy import sparse - if sparse.issparse(a) or sparse.issparse(b): + """Dot product that handle the sparse matrix case correctly + + Uses BLAS GEMM as replacement for numpy.dot where possible + to avoid unnecessary copies. + """ + if issparse(a) or issparse(b): ret = a * b if dense_output and hasattr(ret, "toarray"): ret = ret.toarray() return ret else: - return np.dot(a, b) + return fast_dot(a, b) -def randomized_range_finder(A, size, n_iterations, random_state=None): +def randomized_range_finder(A, size, n_iter, random_state=None): """Computes an orthonormal matrix whose range approximates the range of A. Parameters @@ -87,7 +192,7 @@ def randomized_range_finder(A, size, n_iterations, random_state=None): The input data matrix size: integer Size of the return array - n_iterations: integer + n_iter: integer Number of power iterations used to stabilize the result random_state: RandomState or an int seed (0 by default) A random number generator instance @@ -117,16 +222,16 @@ def randomized_range_finder(A, size, n_iterations, random_state=None): # perform power iterations with Y to further 'imprint' the top # singular vectors of A in Y - for i in xrange(n_iterations): + for i in xrange(n_iter): Y = safe_sparse_dot(A, safe_sparse_dot(A.T, Y)) # extracting an orthonormal basis of the A range samples - Q, R = qr_economic(Y) + Q, R = linalg.qr(Y, mode='economic') return Q -def randomized_svd(M, n_components, n_oversamples=10, n_iterations=0, - transpose='auto', random_state=0): +def randomized_svd(M, n_components, n_oversamples=10, n_iter=0, + transpose='auto', flip_sign=True, random_state=0): """Computes a truncated randomized SVD Parameters @@ -142,7 +247,7 @@ def randomized_svd(M, n_components, n_oversamples=10, n_iterations=0, to ensure proper conditioning. The total number of random vectors used to find the range of M is n_components + n_oversamples. - n_iterations: int (default is 0) + n_iter: int (default is 0) Number of power iterations (can be used to deal with very noisy problems). @@ -153,6 +258,12 @@ def randomized_svd(M, n_components, n_oversamples=10, n_iterations=0, implementation of randomized SVD tend to be a little faster in that case). + flip_sign: boolean, (True by default) + The output of a singular value decomposition is only unique up to a + permutation of the signs of the singular vectors. If `flip_sign` is + set to `True`, the sign ambiguity is resolved by making the largest + loadings for each component in the left singular vectors positive. + random_state: RandomState or an int seed (0 by default) A random number generator instance to make behavior @@ -182,7 +293,7 @@ def randomized_svd(M, n_components, n_oversamples=10, n_iterations=0, # this implementation is a bit faster with smaller shape[1] M = M.T - Q = randomized_range_finder(M, n_random, n_iterations, random_state) + Q = randomized_range_finder(M, n_random, n_iter, random_state) # project M to the (k + p) dimensional space using the basis vectors B = safe_sparse_dot(Q.T, M) @@ -192,6 +303,9 @@ def randomized_svd(M, n_components, n_oversamples=10, n_iterations=0, del B U = np.dot(Q, Uhat) + if flip_sign: + U, V = svd_flip(U, V) + if transpose: # transpose back the results according to the input convention return V[:n_components, :].T, s[:n_components], U[:, :n_components].T @@ -309,12 +423,21 @@ def pinvh(a, cond=None, rcond=None, lower=True): ---------- a : array, shape (N, N) Real symmetric or complex hermetian matrix to be pseudo-inverted - cond, rcond : float or None + + cond : float or None, default None Cutoff for 'small' eigenvalues. Singular values smaller than rcond * largest_eigenvalue are considered zero. If None or -1, suitable machine precision is used. + + rcond : float or None, default None (deprecated) + Cutoff for 'small' eigenvalues. + Singular values smaller than rcond * largest_eigenvalue are considered + zero. + + If None or -1, suitable machine precision is used. + lower : boolean Whether the pertinent array data is taken from the lower or upper triangle of a. (Default: lower) @@ -330,13 +453,13 @@ def pinvh(a, cond=None, rcond=None, lower=True): Examples -------- - >>> from numpy import * - >>> a = random.randn(9, 6) + >>> import numpy as np + >>> a = np.random.randn(9, 6) >>> a = np.dot(a, a.T) >>> B = pinvh(a) - >>> allclose(a, dot(a, dot(B, a))) + >>> np.allclose(a, np.dot(a, np.dot(B, a))) True - >>> allclose(B, dot(B, dot(a, B))) + >>> np.allclose(B, np.dot(B, np.dot(a, B))) True """ @@ -356,3 +479,238 @@ def pinvh(a, cond=None, rcond=None, lower=True): psigma_diag[above_cutoff] = 1.0 / s[above_cutoff] return np.dot(u * psigma_diag, np.conjugate(u).T) + + +def cartesian(arrays, out=None): + """Generate a cartesian product of input arrays. + + Parameters + ---------- + arrays : list of array-like + 1-D arrays to form the cartesian product of. + out : ndarray + Array to place the cartesian product in. + + Returns + ------- + out : ndarray + 2-D array of shape (M, len(arrays)) containing cartesian products + formed of input arrays. + + Examples + -------- + >>> cartesian(([1, 2, 3], [4, 5], [6, 7])) + array([[1, 4, 6], + [1, 4, 7], + [1, 5, 6], + [1, 5, 7], + [2, 4, 6], + [2, 4, 7], + [2, 5, 6], + [2, 5, 7], + [3, 4, 6], + [3, 4, 7], + [3, 5, 6], + [3, 5, 7]]) + + """ + arrays = [np.asarray(x) for x in arrays] + shape = (len(x) for x in arrays) + dtype = arrays[0].dtype + + ix = np.indices(shape) + ix = ix.reshape(len(arrays), -1).T + + if out is None: + out = np.empty_like(ix, dtype=dtype) + + for n, arr in enumerate(arrays): + out[:, n] = arrays[n][ix[:, n]] + + return out + + +def svd_flip(u, v, u_based_decision=True): + """Sign correction to ensure deterministic output from SVD. + + Adjusts the columns of u and the rows of v such that the loadings in the + columns in u that are largest in absolute value are always positive. + + Parameters + ---------- + u, v : ndarray + u and v are the output of `linalg.svd` or + `sklearn.utils.extmath.randomized_svd`, with matching inner dimensions + so one can compute `np.dot(u * s, v)`. + + u_based_decision : boolean, (default=True) + If True, use the columns of u as the basis for sign flipping. Otherwise, + use the rows of v. The choice of which variable to base the decision on + is generally algorithm dependent. + + + Returns + ------- + u_adjusted, v_adjusted : arrays with the same dimensions as the input. + + """ + if u_based_decision: + # columns of u, rows of v + max_abs_cols = np.argmax(np.abs(u), axis=0) + signs = np.sign(u[max_abs_cols, xrange(u.shape[1])]) + u *= signs + v *= signs[:, np.newaxis] + else: + # rows of v, columns of u + max_abs_rows = np.argmax(np.abs(v), axis=1) + signs = np.sign(v[xrange(v.shape[0]), max_abs_rows]) + u *= signs + v *= signs[:, np.newaxis] + return u, v + + +@deprecated('to be removed in 0.17; use scipy.special.expit or log_logistic') +def logistic_sigmoid(X, log=False, out=None): + """Logistic function, ``1 / (1 + e ** (-x))``, or its log.""" + from .fixes import expit + fn = log_logistic if log else expit + return fn(X, out) + + +def log_logistic(X, out=None): + """Compute the log of the logistic function, ``log(1 / (1 + e ** -x))``. + + This implementation is numerically stable because it splits positive and + negative values:: + + -log(1 + exp(-x_i)) if x_i > 0 + x_i - log(1 + exp(x_i)) if x_i <= 0 + + For the ordinary logistic function, use ``sklearn.utils.fixes.expit``. + + Parameters + ---------- + X: array-like, shape (M, N) + Argument to the logistic function + + out: array-like, shape: (M, N), optional: + Preallocated output array. + + Returns + ------- + out: array, shape (M, N) + Log of the logistic function evaluated at every point in x + + Notes + ----- + See the blog post describing this implementation: + http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression/ + """ + is_1d = X.ndim == 1 + X = check_array(X, dtype=np.float) + + n_samples, n_features = X.shape + + if out is None: + out = np.empty_like(X) + + _log_logistic_sigmoid(n_samples, n_features, X, out) + + if is_1d: + return np.squeeze(out) + return out + + +def safe_min(X): + """Returns the minimum value of a dense or a CSR/CSC matrix. + + Adapated from http://stackoverflow.com/q/13426580 + + """ + if issparse(X): + if len(X.data) == 0: + return 0 + m = X.data.min() + return m if X.getnnz() == X.size else min(m, 0) + else: + return X.min() + + +def make_nonnegative(X, min_value=0): + """Ensure `X.min()` >= `min_value`.""" + min_ = safe_min(X) + if min_ < min_value: + if issparse(X): + raise ValueError("Cannot make the data matrix" + " nonnegative because it is sparse." + " Adding a value to every entry would" + " make it no longer sparse.") + X = X + (min_value - min_) + return X + + +def _batch_mean_variance_update(X, old_mean, old_variance, old_sample_count): + """Calculate an average mean update and a Youngs and Cramer variance update. + + From the paper "Algorithms for computing the sample variance: analysis and + recommendations", by Chan, Golub, and LeVeque. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Data to use for variance update + + old_mean : array-like, shape: (n_features,) + + old_variance : array-like, shape: (n_features,) + + old_sample_count : int + + Returns + ------- + updated_mean : array, shape (n_features,) + + updated_variance : array, shape (n_features,) + + updated_sample_count : int + + References + ---------- + T. Chan, G. Golub, R. LeVeque. Algorithms for computing the sample variance: + recommendations, The American Statistician, Vol. 37, No. 3, pp. 242-247 + + """ + new_sum = X.sum(axis=0) + new_variance = X.var(axis=0) * X.shape[0] + old_sum = old_mean * old_sample_count + n_samples = X.shape[0] + updated_sample_count = old_sample_count + n_samples + partial_variance = old_sample_count / (n_samples * updated_sample_count) * ( + n_samples / old_sample_count * old_sum - new_sum) ** 2 + unnormalized_variance = old_variance * old_sample_count + new_variance + \ + partial_variance + return ((old_sum + new_sum) / updated_sample_count, + unnormalized_variance / updated_sample_count, + updated_sample_count) + + +def _deterministic_vector_sign_flip(u): + """Modify the sign of vectors for reproducibility + + Flips the sign of elements of all the vectors (rows of u) such that + the absolute maximum element of each vector is positive. + + Parameters + ---------- + u : ndarray + Array with vectors as its rows. + + Returns + ------- + u_flipped : ndarray with same shape as u + Array with the sign flipped vectors as its rows. + """ + max_abs_rows = np.argmax(np.abs(u), axis=1) + signs = np.sign(u[range(u.shape[0]), max_abs_rows]) + u *= signs[:, np.newaxis] + return u diff --git a/sklearn/utils/fast_dict.cpp b/sklearn/utils/fast_dict.cpp new file mode 100644 index 0000000000000..923f0b0ee65a9 --- /dev/null +++ b/sklearn/utils/fast_dict.cpp @@ -0,0 +1,20985 @@ +/* Generated by Cython 0.19.1 on Mon Feb 17 15:25:01 2014 */ + +#define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_VERSION_HEX < 0x03020000 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__utils__fast_dict +#define __PYX_HAVE_API__sklearn__utils__fast_dict +#include +#include "ios" +#include "new" +#include "stdexcept" +#include "typeinfo" +#include +#include "string.h" +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#include "pythread.h" +#include "pystate.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params() { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +#ifdef __GNUC__ + /* Test for GCC > 2.95 */ + #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) + #else /* __GNUC__ > 2 ... */ + #define likely(x) (x) + #define unlikely(x) (x) + #endif /* __GNUC__ > 2 ... */ +#else /* __GNUC__ */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "fast_dict.pyx", + "numpy.pxd", + "stringsource", + "type.pxd", +}; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + +struct __pyx_memoryview_obj; +typedef struct { + struct __pyx_memoryview_obj *memview; + char *data; + Py_ssize_t shape[8]; + Py_ssize_t strides[8]; + Py_ssize_t suboffsets[8]; +} __Pyx_memviewslice; + +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __pyx_atomic_int_type int +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ + !defined(__i386__) + #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && MSC_VER + #include + #define __pyx_atomic_int_type LONG + #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using MSVC atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 + #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using Intel atomics" + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif +typedef volatile __pyx_atomic_int_type __pyx_atomic_int; +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview) \ + __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) +#else + #define __pyx_add_acquisition_count(memview) \ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif + + +/* "numpy.pxd":723 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "numpy.pxd":724 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "numpy.pxd":725 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "numpy.pxd":726 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "numpy.pxd":730 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "numpy.pxd":731 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "numpy.pxd":732 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "numpy.pxd":733 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "numpy.pxd":737 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "numpy.pxd":738 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "numpy.pxd":747 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "numpy.pxd":748 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "numpy.pxd":749 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "numpy.pxd":751 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "numpy.pxd":752 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "numpy.pxd":753 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "numpy.pxd":755 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "numpy.pxd":756 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "numpy.pxd":758 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "numpy.pxd":759 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "numpy.pxd":760 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; + +/* "sklearn/utils/fast_dict.pxd":14 + * + * DTYPE = np.float64 + * ctypedef np.float64_t DTYPE_t # <<<<<<<<<<<<<< + * + * ITYPE = np.intp + */ +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t; + +/* "sklearn/utils/fast_dict.pxd":17 + * + * ITYPE = np.intp + * ctypedef np.intp_t ITYPE_t # <<<<<<<<<<<<<< + * + * ############################################################################### + */ +typedef __pyx_t_5numpy_intp_t __pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ +struct __pyx_MemviewEnum_obj; +struct __pyx_memoryview_obj; +struct __pyx_memoryviewslice_obj; +struct __pyx_array_obj; +struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict; +struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__; + +/* "numpy.pxd":762 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "numpy.pxd":763 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "numpy.pxd":764 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "numpy.pxd":766 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; + +/* "View.MemoryView":275 + * + * @cname('__pyx_MemviewEnum') + * cdef class Enum(object): # <<<<<<<<<<<<<< + * cdef object name + * def __init__(self, name): + */ +struct __pyx_MemviewEnum_obj { + PyObject_HEAD + PyObject *name; +}; + + +/* "View.MemoryView":308 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ +struct __pyx_memoryview_obj { + PyObject_HEAD + struct __pyx_vtabstruct_memoryview *__pyx_vtab; + PyObject *obj; + PyObject *_size; + PyObject *_array_interface; + PyThread_type_lock lock; + __pyx_atomic_int acquisition_count[2]; + __pyx_atomic_int *acquisition_count_aligned_p; + Py_buffer view; + int flags; + int dtype_is_object; + __Pyx_TypeInfo *typeinfo; +}; + + +/* "View.MemoryView":927 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ +struct __pyx_memoryviewslice_obj { + struct __pyx_memoryview_obj __pyx_base; + __Pyx_memviewslice from_slice; + PyObject *from_object; + PyObject *(*to_object_func)(char *); + int (*to_dtype_func)(char *, PyObject *); +}; + + +/* "View.MemoryView":96 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ +struct __pyx_array_obj { + PyObject_HEAD + char *data; + Py_ssize_t len; + char *format; + int ndim; + Py_ssize_t *_shape; + Py_ssize_t *_strides; + Py_ssize_t itemsize; + PyObject *mode; + PyObject *_format; + void (*callback_free_data)(void *); + int free_data; + int dtype_is_object; +}; + + +/* "sklearn/utils/fast_dict.pxd":22 + * # An object to be used in Python + * + * cdef class IntFloatDict: # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t] my_map + * cdef _to_arrays(self, ITYPE_t [:] keys, DTYPE_t [:] values) + */ +struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict { + PyObject_HEAD + struct __pyx_vtabstruct_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_vtab; + std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t> my_map; +}; + + +/* "sklearn/utils/fast_dict.pyx":74 + * # inc(it) + * + * def __iter__(self): # <<<<<<<<<<<<<< + * cdef int size = self.my_map.size() + * cdef ITYPE_t [:] keys = np.empty(size, dtype=np.intp) + */ +struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ { + PyObject_HEAD + int __pyx_v_idx; + __pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t __pyx_v_key; + __Pyx_memviewslice __pyx_v_keys; + struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self; + int __pyx_v_size; + __pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t __pyx_v_value; + __Pyx_memviewslice __pyx_v_values; + int __pyx_t_0; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; +}; + + + +/* "View.MemoryView":308 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ + +struct __pyx_vtabstruct_memoryview { + char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); + PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); +}; +static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; + + +/* "View.MemoryView":927 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ + +struct __pyx_vtabstruct__memoryviewslice { + struct __pyx_vtabstruct_memoryview __pyx_base; +}; +static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; + + +/* "sklearn/utils/fast_dict.pyx":39 + * # consumption is reduced a lot compared to a Python dict + * + * cdef class IntFloatDict: # <<<<<<<<<<<<<< + * + * @cython.boundscheck(False) + */ + +struct __pyx_vtabstruct_7sklearn_5utils_9fast_dict_IntFloatDict { + PyObject *(*_to_arrays)(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *, __Pyx_memviewslice, __Pyx_memviewslice); +}; +static struct __pyx_vtabstruct_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_vtabptr_7sklearn_5utils_9fast_dict_IntFloatDict; + +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); /*proto*/ + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +static void __Pyx_RaiseBufferIndexError(int axis); /*proto*/ + +#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d +#define __Pyx_MEMVIEW_DIRECT 1 +#define __Pyx_MEMVIEW_PTR 2 +#define __Pyx_MEMVIEW_FULL 4 +#define __Pyx_MEMVIEW_CONTIG 8 +#define __Pyx_MEMVIEW_STRIDED 16 +#define __Pyx_MEMVIEW_FOLLOW 32 +#define __Pyx_IS_C_CONTIG 1 +#define __Pyx_IS_F_CONTIG 2 +static int __Pyx_init_memviewslice( + struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference); +static CYTHON_INLINE int __pyx_add_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) +#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) +#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) +#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) +static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/ + +static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); /* proto */ + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) + +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +#include + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +#define __Pyx_GetItemInt(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Fast(o, i, is_list, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +#define __Pyx_GetItemInt_List(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_List_Fast(o, i, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ + (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, i, wraparound, boundscheck) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); + +static CYTHON_INLINE long __Pyx_div_long(long, long); /* proto */ + +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename); /*proto*/ + +static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ + +#include + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_from_py_Py_intptr_t(PyObject *); + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t); + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim); + +static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize); + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object); + +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); + +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); + +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); + +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); + +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); + +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); + +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); + +static PyObject* __Pyx_PyObject_CallMethodTuple(PyObject* obj, PyObject* method_name, PyObject* args) { + PyObject *method, *result = NULL; + if (unlikely(!args)) return NULL; + method = __Pyx_PyObject_GetAttrStr(obj, method_name); + if (unlikely(!method)) goto bad; + result = PyObject_Call(method, args, NULL); + Py_DECREF(method); +bad: + Py_DECREF(args); + return result; +} +#define __Pyx_PyObject_CallMethod3(obj, name, arg1, arg2, arg3) \ + __Pyx_PyObject_CallMethodTuple(obj, name, PyTuple_Pack(3, arg1, arg2, arg3)) +#define __Pyx_PyObject_CallMethod2(obj, name, arg1, arg2) \ + __Pyx_PyObject_CallMethodTuple(obj, name, PyTuple_Pack(2, arg1, arg2)) +#define __Pyx_PyObject_CallMethod1(obj, name, arg1) \ + __Pyx_PyObject_CallMethodTuple(obj, name, PyTuple_Pack(1, arg1)) +#define __Pyx_PyObject_CallMethod0(obj, name) \ + __Pyx_PyObject_CallMethodTuple(obj, name, (Py_INCREF(__pyx_empty_tuple), __pyx_empty_tuple)) + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +#define __Pyx_Generator_USED +#include +#include +typedef PyObject *(*__pyx_generator_body_t)(PyObject *, PyObject *); +typedef struct { + PyObject_HEAD + __pyx_generator_body_t body; + PyObject *closure; + PyObject *exc_type; + PyObject *exc_value; + PyObject *exc_traceback; + PyObject *gi_weakreflist; + PyObject *classobj; + PyObject *yieldfrom; + int resume_label; + char is_running; // using T_BOOL for property below requires char value +} __pyx_GeneratorObject; +static __pyx_GeneratorObject *__Pyx_Generator_New(__pyx_generator_body_t body, + PyObject *closure); +static int __pyx_Generator_init(void); +static int __Pyx_Generator_clear(PyObject* self); +#if 1 || PY_VERSION_HEX < 0x030300B0 +static int __Pyx_PyGen_FetchStopIterationValue(PyObject **pvalue); +#else +#define __Pyx_PyGen_FetchStopIterationValue(pvalue) PyGen_FetchStopIterationValue(pvalue) +#endif + +static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); + +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t(PyObject *); + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t(PyObject *); + +static int __Pyx_check_binary_version(void); + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'libcpp.utility' */ + +/* Module declarations from 'libcpp.map' */ + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'cython.view' */ + +/* Module declarations from 'cython' */ + +/* Module declarations from 'sklearn.utils.fast_dict' */ +static PyTypeObject *__pyx_MemviewEnum_type = 0; +static PyTypeObject *__pyx_memoryview_type = 0; +static PyTypeObject *__pyx_memoryviewslice_type = 0; +static PyTypeObject *__pyx_array_type = 0; +static PyTypeObject *__pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict = 0; +static PyTypeObject *__pyx_ptype_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ = 0; +static PyObject *generic = 0; +static PyObject *strided = 0; +static PyObject *indirect = 0; +static PyObject *contiguous = 0; +static PyObject *indirect_contiguous = 0; +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ +static void *__pyx_align_pointer(void *, size_t); /*proto*/ +static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ +static PyObject *_unellipsify(PyObject *, int); /*proto*/ +static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ +static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, int); /*proto*/ +static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ +static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ +static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ +static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ +static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ +static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ +static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t = { "ITYPE_t", NULL, sizeof(__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; +#define __Pyx_MODULE_NAME "sklearn.utils.fast_dict" +int __pyx_module_is_main_sklearn__utils__fast_dict = 0; + +/* Implementation of 'sklearn.utils.fast_dict' */ +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_KeyError; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_Ellipsis; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_xrange; +static PyObject *__pyx_builtin_id; +static PyObject *__pyx_builtin_IndexError; +static int __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict___init__(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self, PyArrayObject *__pyx_v_keys, PyArrayObject *__pyx_v_values); /* proto */ +static Py_ssize_t __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_2__len__(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_4__getitem__(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self, int __pyx_v_key); /* proto */ +static int __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_6__setitem__(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self, int __pyx_v_key, float __pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_8__iter__(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_11to_arrays(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_13update(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_other); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_15copy(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_17append(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self, __pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t __pyx_v_key, __pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t __pyx_v_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_argmin(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_d); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_5utils_9fast_dict_IntFloatDict(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_1[] = "%i"; +static char __pyx_k_2[] = "ndarray is not C contiguous"; +static char __pyx_k_4[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_6[] = "Non-native byte order not supported"; +static char __pyx_k_8[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_9[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_12[] = "Format string allocated too short."; +static char __pyx_k_14[] = "Empty shape tuple for cython.array"; +static char __pyx_k_16[] = "itemsize <= 0 for cython.array"; +static char __pyx_k_19[] = "unable to allocate shape or strides."; +static char __pyx_k_21[] = "Invalid shape in axis %d: %d."; +static char __pyx_k_22[] = "Invalid mode, expected 'c' or 'fortran', got %s"; +static char __pyx_k_24[] = "unable to allocate array data."; +static char __pyx_k_26[] = "Can only create a buffer that is contiguous in memory."; +static char __pyx_k_28[] = "Unable to convert item to object"; +static char __pyx_k_30[] = "Buffer view does not expose strides"; +static char __pyx_k_32[] = ""; +static char __pyx_k_33[] = ""; +static char __pyx_k_36[] = "Cannot index with type '%s'"; +static char __pyx_k_38[] = "Indirect dimensions not supported"; +static char __pyx_k_40[] = "Index out of bounds (axis %d)"; +static char __pyx_k_41[] = "Step may not be zero (axis %d)"; +static char __pyx_k_42[] = "All dimensions preceding dimension %d must be indexed and not sliced"; +static char __pyx_k_43[] = "Out of bounds on buffer access (axis %d)"; +static char __pyx_k_44[] = "Cannot transpose memoryview with indirect dimensions"; +static char __pyx_k_45[] = "got differing extents in dimension %d (got %d and %d)"; +static char __pyx_k_46[] = "Dimension %d is not direct"; +static char __pyx_k_47[] = "\nUses C++ map containers for fast dict-like behavior with keys being\nintegers, and values float.\n"; +static char __pyx_k_50[] = "/home/varoquau/dev/scikit-learn/sklearn/utils/fast_dict.pyx"; +static char __pyx_k_51[] = "sklearn.utils.fast_dict"; +static char __pyx_k_52[] = "getbuffer(obj, view, flags)"; +static char __pyx_k_53[] = ""; +static char __pyx_k_55[] = ""; +static char __pyx_k_57[] = ""; +static char __pyx_k_59[] = ""; +static char __pyx_k_61[] = ""; +static char __pyx_k__B[] = "B"; +static char __pyx_k__H[] = "H"; +static char __pyx_k__I[] = "I"; +static char __pyx_k__L[] = "L"; +static char __pyx_k__O[] = "O"; +static char __pyx_k__Q[] = "Q"; +static char __pyx_k__b[] = "b"; +static char __pyx_k__c[] = "c"; +static char __pyx_k__d[] = "d"; +static char __pyx_k__f[] = "f"; +static char __pyx_k__g[] = "g"; +static char __pyx_k__h[] = "h"; +static char __pyx_k__i[] = "i"; +static char __pyx_k__l[] = "l"; +static char __pyx_k__q[] = "q"; +static char __pyx_k__Zd[] = "Zd"; +static char __pyx_k__Zf[] = "Zf"; +static char __pyx_k__Zg[] = "Zg"; +static char __pyx_k__id[] = "id"; +static char __pyx_k__it[] = "it"; +static char __pyx_k__np[] = "np"; +static char __pyx_k__end[] = "end"; +static char __pyx_k__inf[] = "inf"; +static char __pyx_k__key[] = "key"; +static char __pyx_k__obj[] = "obj"; +static char __pyx_k__args[] = "args"; +static char __pyx_k__base[] = "base"; +static char __pyx_k__intp[] = "intp"; +static char __pyx_k__keys[] = "keys"; +static char __pyx_k__mode[] = "mode"; +static char __pyx_k__name[] = "name"; +static char __pyx_k__ndim[] = "ndim"; +static char __pyx_k__pack[] = "pack"; +static char __pyx_k__send[] = "send"; +static char __pyx_k__size[] = "size"; +static char __pyx_k__step[] = "step"; +static char __pyx_k__stop[] = "stop"; +static char __pyx_k__ASCII[] = "ASCII"; +static char __pyx_k__close[] = "close"; +static char __pyx_k__dtype[] = "dtype"; +static char __pyx_k__empty[] = "empty"; +static char __pyx_k__error[] = "error"; +static char __pyx_k__flags[] = "flags"; +static char __pyx_k__numpy[] = "numpy"; +static char __pyx_k__range[] = "range"; +static char __pyx_k__shape[] = "shape"; +static char __pyx_k__start[] = "start"; +static char __pyx_k__throw[] = "throw"; +static char __pyx_k__value[] = "value"; +static char __pyx_k__argmin[] = "argmin"; +static char __pyx_k__decode[] = "decode"; +static char __pyx_k__encode[] = "encode"; +static char __pyx_k__extend[] = "extend"; +static char __pyx_k__format[] = "format"; +static char __pyx_k__struct[] = "struct"; +static char __pyx_k__unpack[] = "unpack"; +static char __pyx_k__values[] = "values"; +static char __pyx_k__xrange[] = "xrange"; +static char __pyx_k__float64[] = "float64"; +static char __pyx_k__fortran[] = "fortran"; +static char __pyx_k__memview[] = "memview"; +static char __pyx_k__min_key[] = "min_key"; +static char __pyx_k__Ellipsis[] = "Ellipsis"; +static char __pyx_k__KeyError[] = "KeyError"; +static char __pyx_k____main__[] = "__main__"; +static char __pyx_k____name__[] = "__name__"; +static char __pyx_k____test__[] = "__test__"; +static char __pyx_k__itemsize[] = "itemsize"; +static char __pyx_k__TypeError[] = "TypeError"; +static char __pyx_k____class__[] = "__class__"; +static char __pyx_k__enumerate[] = "enumerate"; +static char __pyx_k__min_value[] = "min_value"; +static char __pyx_k__IndexError[] = "IndexError"; +static char __pyx_k__ValueError[] = "ValueError"; +static char __pyx_k____import__[] = "__import__"; +static char __pyx_k__MemoryError[] = "MemoryError"; +static char __pyx_k__RuntimeError[] = "RuntimeError"; +static char __pyx_k____pyx_vtable__[] = "__pyx_vtable__"; +static char __pyx_k____pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k__allocate_buffer[] = "allocate_buffer"; +static char __pyx_k__dtype_is_object[] = "dtype_is_object"; +static char __pyx_k____pyx_releasebuffer[] = "__pyx_releasebuffer"; +static PyObject *__pyx_kp_s_1; +static PyObject *__pyx_kp_u_12; +static PyObject *__pyx_kp_s_14; +static PyObject *__pyx_kp_s_16; +static PyObject *__pyx_kp_s_19; +static PyObject *__pyx_kp_u_2; +static PyObject *__pyx_kp_s_21; +static PyObject *__pyx_kp_s_22; +static PyObject *__pyx_kp_s_24; +static PyObject *__pyx_kp_s_26; +static PyObject *__pyx_kp_s_28; +static PyObject *__pyx_kp_s_30; +static PyObject *__pyx_kp_s_32; +static PyObject *__pyx_kp_s_33; +static PyObject *__pyx_kp_s_36; +static PyObject *__pyx_kp_s_38; +static PyObject *__pyx_kp_u_4; +static PyObject *__pyx_kp_s_43; +static PyObject *__pyx_kp_s_45; +static PyObject *__pyx_kp_s_50; +static PyObject *__pyx_n_s_51; +static PyObject *__pyx_kp_s_53; +static PyObject *__pyx_kp_s_55; +static PyObject *__pyx_kp_s_57; +static PyObject *__pyx_kp_s_59; +static PyObject *__pyx_kp_u_6; +static PyObject *__pyx_kp_s_61; +static PyObject *__pyx_kp_u_8; +static PyObject *__pyx_kp_u_9; +static PyObject *__pyx_n_s__ASCII; +static PyObject *__pyx_n_s__Ellipsis; +static PyObject *__pyx_n_s__IndexError; +static PyObject *__pyx_n_s__KeyError; +static PyObject *__pyx_n_s__MemoryError; +static PyObject *__pyx_n_b__O; +static PyObject *__pyx_n_s__RuntimeError; +static PyObject *__pyx_n_s__TypeError; +static PyObject *__pyx_n_s__ValueError; +static PyObject *__pyx_n_s____class__; +static PyObject *__pyx_n_s____import__; +static PyObject *__pyx_n_s____main__; +static PyObject *__pyx_n_s____name__; +static PyObject *__pyx_n_s____pyx_getbuffer; +static PyObject *__pyx_n_s____pyx_releasebuffer; +static PyObject *__pyx_n_s____pyx_vtable__; +static PyObject *__pyx_n_s____test__; +static PyObject *__pyx_n_s__allocate_buffer; +static PyObject *__pyx_n_s__argmin; +static PyObject *__pyx_n_s__args; +static PyObject *__pyx_n_s__base; +static PyObject *__pyx_n_b__c; +static PyObject *__pyx_n_s__c; +static PyObject *__pyx_n_u__c; +static PyObject *__pyx_n_s__close; +static PyObject *__pyx_n_s__d; +static PyObject *__pyx_n_s__decode; +static PyObject *__pyx_n_s__dtype; +static PyObject *__pyx_n_s__dtype_is_object; +static PyObject *__pyx_n_s__empty; +static PyObject *__pyx_n_s__encode; +static PyObject *__pyx_n_s__end; +static PyObject *__pyx_n_s__enumerate; +static PyObject *__pyx_n_s__error; +static PyObject *__pyx_n_s__extend; +static PyObject *__pyx_n_s__flags; +static PyObject *__pyx_n_s__float64; +static PyObject *__pyx_n_s__format; +static PyObject *__pyx_n_b__fortran; +static PyObject *__pyx_n_s__fortran; +static PyObject *__pyx_n_s__id; +static PyObject *__pyx_n_s__inf; +static PyObject *__pyx_n_s__intp; +static PyObject *__pyx_n_s__it; +static PyObject *__pyx_n_s__itemsize; +static PyObject *__pyx_n_s__key; +static PyObject *__pyx_n_s__keys; +static PyObject *__pyx_n_s__memview; +static PyObject *__pyx_n_s__min_key; +static PyObject *__pyx_n_s__min_value; +static PyObject *__pyx_n_s__mode; +static PyObject *__pyx_n_s__name; +static PyObject *__pyx_n_s__ndim; +static PyObject *__pyx_n_s__np; +static PyObject *__pyx_n_s__numpy; +static PyObject *__pyx_n_s__obj; +static PyObject *__pyx_n_s__pack; +static PyObject *__pyx_n_s__range; +static PyObject *__pyx_n_s__send; +static PyObject *__pyx_n_s__shape; +static PyObject *__pyx_n_s__size; +static PyObject *__pyx_n_s__start; +static PyObject *__pyx_n_s__step; +static PyObject *__pyx_n_s__stop; +static PyObject *__pyx_n_s__struct; +static PyObject *__pyx_n_s__throw; +static PyObject *__pyx_n_s__unpack; +static PyObject *__pyx_n_s__value; +static PyObject *__pyx_n_s__values; +static PyObject *__pyx_n_s__xrange; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_1; +static PyObject *__pyx_int_neg_1; +static PyObject *__pyx_int_15; +static PyObject *__pyx_k_tuple_3; +static PyObject *__pyx_k_tuple_5; +static PyObject *__pyx_k_tuple_7; +static PyObject *__pyx_k_tuple_10; +static PyObject *__pyx_k_tuple_11; +static PyObject *__pyx_k_tuple_13; +static PyObject *__pyx_k_tuple_15; +static PyObject *__pyx_k_tuple_17; +static PyObject *__pyx_k_tuple_18; +static PyObject *__pyx_k_tuple_20; +static PyObject *__pyx_k_tuple_23; +static PyObject *__pyx_k_tuple_25; +static PyObject *__pyx_k_tuple_27; +static PyObject *__pyx_k_tuple_29; +static PyObject *__pyx_k_tuple_31; +static PyObject *__pyx_k_tuple_34; +static PyObject *__pyx_k_tuple_35; +static PyObject *__pyx_k_tuple_37; +static PyObject *__pyx_k_tuple_39; +static PyObject *__pyx_k_tuple_48; +static PyObject *__pyx_k_tuple_54; +static PyObject *__pyx_k_tuple_56; +static PyObject *__pyx_k_tuple_58; +static PyObject *__pyx_k_tuple_60; +static PyObject *__pyx_k_tuple_62; +static PyObject *__pyx_k_codeobj_49; + +/* Python wrapper */ +static int __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_keys = 0; + PyArrayObject *__pyx_v_values = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__keys,&__pyx_n_s__values,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__keys)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__values)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_keys = ((PyArrayObject *)values[0]); + __pyx_v_values = ((PyArrayObject *)values[1]); + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils.fast_dict.IntFloatDict.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_keys), __pyx_ptype_5numpy_ndarray, 1, "keys", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_values), __pyx_ptype_5numpy_ndarray, 1, "values", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict___init__(((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_self), __pyx_v_keys, __pyx_v_values); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/fast_dict.pyx":43 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def __init__(self, np.ndarray[ITYPE_t, ndim=1] keys, # <<<<<<<<<<<<<< + * np.ndarray[DTYPE_t, ndim=1] values): + * cdef int i + */ + +static int __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict___init__(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self, PyArrayObject *__pyx_v_keys, PyArrayObject *__pyx_v_values) { + int __pyx_v_i; + int __pyx_v_size; + __Pyx_LocalBuf_ND __pyx_pybuffernd_keys; + __Pyx_Buffer __pyx_pybuffer_keys; + __Pyx_LocalBuf_ND __pyx_pybuffernd_values; + __Pyx_Buffer __pyx_pybuffer_values; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + __pyx_pybuffer_keys.pybuffer.buf = NULL; + __pyx_pybuffer_keys.refcount = 0; + __pyx_pybuffernd_keys.data = NULL; + __pyx_pybuffernd_keys.rcbuffer = &__pyx_pybuffer_keys; + __pyx_pybuffer_values.pybuffer.buf = NULL; + __pyx_pybuffer_values.refcount = 0; + __pyx_pybuffernd_values.data = NULL; + __pyx_pybuffernd_values.rcbuffer = &__pyx_pybuffer_values; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_keys.rcbuffer->pybuffer, (PyObject*)__pyx_v_keys, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_keys.diminfo[0].strides = __pyx_pybuffernd_keys.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_keys.diminfo[0].shape = __pyx_pybuffernd_keys.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_values.rcbuffer->pybuffer, (PyObject*)__pyx_v_values, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_values.diminfo[0].strides = __pyx_pybuffernd_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_values.diminfo[0].shape = __pyx_pybuffernd_values.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/utils/fast_dict.pyx":46 + * np.ndarray[DTYPE_t, ndim=1] values): + * cdef int i + * cdef int size = values.size # <<<<<<<<<<<<<< + * # Should check that sizes for keys and values are equal, and + * # after should boundcheck(False) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_values), __pyx_n_s__size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_size = __pyx_t_2; + + /* "sklearn/utils/fast_dict.pyx":49 + * # Should check that sizes for keys and values are equal, and + * # after should boundcheck(False) + * for i in range(size): # <<<<<<<<<<<<<< + * self.my_map[keys[i]] = values[i] + * + */ + __pyx_t_2 = __pyx_v_size; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "sklearn/utils/fast_dict.pyx":50 + * # after should boundcheck(False) + * for i in range(size): + * self.my_map[keys[i]] = values[i] # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __pyx_t_4 = __pyx_v_i; + __pyx_t_5 = __pyx_v_i; + (__pyx_v_self->my_map[(*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t *, __pyx_pybuffernd_keys.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_keys.diminfo[0].strides))]) = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t *, __pyx_pybuffernd_values.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_values.diminfo[0].strides)); + } + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_keys.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_values.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.utils.fast_dict.IntFloatDict.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_keys.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_values.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static Py_ssize_t __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_3__len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_3__len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_2__len__(((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/fast_dict.pyx":52 + * self.my_map[keys[i]] = values[i] + * + * def __len__(self): # <<<<<<<<<<<<<< + * return self.my_map.size() + * + */ + +static Py_ssize_t __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_2__len__(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__", 0); + + /* "sklearn/utils/fast_dict.pyx":53 + * + * def __len__(self): + * return self.my_map.size() # <<<<<<<<<<<<<< + * + * def __getitem__(self, int key): + */ + __pyx_r = __pyx_v_self->my_map.size(); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_5__getitem__(PyObject *__pyx_v_self, PyObject *__pyx_arg_key); /*proto*/ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_5__getitem__(PyObject *__pyx_v_self, PyObject *__pyx_arg_key) { + int __pyx_v_key; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + assert(__pyx_arg_key); { + __pyx_v_key = __Pyx_PyInt_AsInt(__pyx_arg_key); if (unlikely((__pyx_v_key == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils.fast_dict.IntFloatDict.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_4__getitem__(((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_self), ((int)__pyx_v_key)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/fast_dict.pyx":55 + * return self.my_map.size() + * + * def __getitem__(self, int key): # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = self.my_map.find(key) + * if it == self.my_map.end(): + */ + +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_4__getitem__(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self, int __pyx_v_key) { + std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t>::iterator __pyx_v_it; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "sklearn/utils/fast_dict.pyx":56 + * + * def __getitem__(self, int key): + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = self.my_map.find(key) # <<<<<<<<<<<<<< + * if it == self.my_map.end(): + * # The key is not in the dict + */ + __pyx_v_it = __pyx_v_self->my_map.find(__pyx_v_key); + + /* "sklearn/utils/fast_dict.pyx":57 + * def __getitem__(self, int key): + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = self.my_map.find(key) + * if it == self.my_map.end(): # <<<<<<<<<<<<<< + * # The key is not in the dict + * raise KeyError('%i' % key) + */ + __pyx_t_1 = ((__pyx_v_it == __pyx_v_self->my_map.end()) != 0); + if (__pyx_t_1) { + + /* "sklearn/utils/fast_dict.pyx":59 + * if it == self.my_map.end(): + * # The key is not in the dict + * raise KeyError('%i' % key) # <<<<<<<<<<<<<< + * return deref(it).second + * + */ + __pyx_t_2 = PyInt_FromLong(__pyx_v_key); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_1), __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_KeyError, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/utils/fast_dict.pyx":60 + * # The key is not in the dict + * raise KeyError('%i' % key) + * return deref(it).second # <<<<<<<<<<<<<< + * + * def __setitem__(self, int key, float value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = PyFloat_FromDouble((*__pyx_v_it).second); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("sklearn.utils.fast_dict.IntFloatDict.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_7__setitem__(PyObject *__pyx_v_self, PyObject *__pyx_arg_key, PyObject *__pyx_arg_value); /*proto*/ +static int __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_7__setitem__(PyObject *__pyx_v_self, PyObject *__pyx_arg_key, PyObject *__pyx_arg_value) { + int __pyx_v_key; + float __pyx_v_value; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + assert(__pyx_arg_key); { + __pyx_v_key = __Pyx_PyInt_AsInt(__pyx_arg_key); if (unlikely((__pyx_v_key == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + assert(__pyx_arg_value); { + __pyx_v_value = __pyx_PyFloat_AsFloat(__pyx_arg_value); if (unlikely((__pyx_v_value == (float)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils.fast_dict.IntFloatDict.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_6__setitem__(((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_self), ((int)__pyx_v_key), ((float)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/fast_dict.pyx":62 + * return deref(it).second + * + * def __setitem__(self, int key, float value): # <<<<<<<<<<<<<< + * self.my_map[key] = value + * + */ + +static int __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_6__setitem__(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self, int __pyx_v_key, float __pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "sklearn/utils/fast_dict.pyx":63 + * + * def __setitem__(self, int key, float value): + * self.my_map[key] = value # <<<<<<<<<<<<<< + * + * # Cython 0.20 generates buggy code below. Commenting this out for now + */ + (__pyx_v_self->my_map[__pyx_v_key]) = __pyx_v_value; + + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static PyObject *__pyx_gb_7sklearn_5utils_9fast_dict_12IntFloatDict_10generator(__pyx_GeneratorObject *__pyx_generator, PyObject *__pyx_sent_value); /* proto */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_9__iter__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_9__iter__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_8__iter__(((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/fast_dict.pyx":74 + * # inc(it) + * + * def __iter__(self): # <<<<<<<<<<<<<< + * cdef int size = self.my_map.size() + * cdef ITYPE_t [:] keys = np.empty(size, dtype=np.intp) + */ + +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_8__iter__(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self) { + struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *__pyx_cur_scope; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__iter__", 0); + __pyx_cur_scope = (struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *)__pyx_tp_new_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__(__pyx_ptype_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__, __pyx_empty_tuple, NULL); + if (unlikely(!__pyx_cur_scope)) { + __Pyx_RefNannyFinishContext(); + return NULL; + } + __Pyx_GOTREF(__pyx_cur_scope); + __pyx_cur_scope->__pyx_v_self = __pyx_v_self; + __Pyx_INCREF((PyObject *)__pyx_cur_scope->__pyx_v_self); + __Pyx_GIVEREF((PyObject *)__pyx_cur_scope->__pyx_v_self); + { + __pyx_GeneratorObject *gen = __Pyx_Generator_New((__pyx_generator_body_t) __pyx_gb_7sklearn_5utils_9fast_dict_12IntFloatDict_10generator, (PyObject *) __pyx_cur_scope); if (unlikely(!gen)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_cur_scope); + __Pyx_RefNannyFinishContext(); + return (PyObject *) gen; + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.utils.fast_dict.IntFloatDict.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_gb_7sklearn_5utils_9fast_dict_12IntFloatDict_10generator(__pyx_GeneratorObject *__pyx_generator, PyObject *__pyx_sent_value) /* generator body */ +{ + struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *__pyx_cur_scope = ((struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *)__pyx_generator->closure); + PyObject *__pyx_r = NULL; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("None", 0); + switch (__pyx_generator->resume_label) { + case 0: goto __pyx_L3_first_run; + case 1: goto __pyx_L6_resume_from_yield; + default: /* CPython raises the right error here */ + __Pyx_RefNannyFinishContext(); + return NULL; + } + __pyx_L3_first_run:; + if (unlikely(!__pyx_sent_value)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/fast_dict.pyx":75 + * + * def __iter__(self): + * cdef int size = self.my_map.size() # <<<<<<<<<<<<<< + * cdef ITYPE_t [:] keys = np.empty(size, dtype=np.intp) + * cdef DTYPE_t [:] values = np.empty(size, dtype=np.float64) + */ + __pyx_cur_scope->__pyx_v_size = __pyx_cur_scope->__pyx_v_self->my_map.size(); + + /* "sklearn/utils/fast_dict.pyx":76 + * def __iter__(self): + * cdef int size = self.my_map.size() + * cdef ITYPE_t [:] keys = np.empty(size, dtype=np.intp) # <<<<<<<<<<<<<< + * cdef DTYPE_t [:] values = np.empty(size, dtype=np.float64) + * self._to_arrays(keys, values) + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyInt_FromLong(__pyx_cur_scope->__pyx_v_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__intp); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_6 = __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t(__pyx_t_5); + if (unlikely(!__pyx_t_6.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_cur_scope->__pyx_v_keys = __pyx_t_6; + __pyx_t_6.memview = NULL; + __pyx_t_6.data = NULL; + + /* "sklearn/utils/fast_dict.pyx":77 + * cdef int size = self.my_map.size() + * cdef ITYPE_t [:] keys = np.empty(size, dtype=np.intp) + * cdef DTYPE_t [:] values = np.empty(size, dtype=np.float64) # <<<<<<<<<<<<<< + * self._to_arrays(keys, values) + * cdef int idx + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyInt_FromLong(__pyx_cur_scope->__pyx_v_size); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t(__pyx_t_4); + if (unlikely(!__pyx_t_7.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_cur_scope->__pyx_v_values = __pyx_t_7; + __pyx_t_7.memview = NULL; + __pyx_t_7.data = NULL; + + /* "sklearn/utils/fast_dict.pyx":78 + * cdef ITYPE_t [:] keys = np.empty(size, dtype=np.intp) + * cdef DTYPE_t [:] values = np.empty(size, dtype=np.float64) + * self._to_arrays(keys, values) # <<<<<<<<<<<<<< + * cdef int idx + * cdef ITYPE_t key + */ + __pyx_t_4 = ((struct __pyx_vtabstruct_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_cur_scope->__pyx_v_self->__pyx_vtab)->_to_arrays(__pyx_cur_scope->__pyx_v_self, __pyx_cur_scope->__pyx_v_keys, __pyx_cur_scope->__pyx_v_values); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "sklearn/utils/fast_dict.pyx":82 + * cdef ITYPE_t key + * cdef DTYPE_t value + * for idx in range(size): # <<<<<<<<<<<<<< + * key = keys[idx] + * value = values[idx] + */ + __pyx_t_8 = __pyx_cur_scope->__pyx_v_size; + for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { + __pyx_cur_scope->__pyx_v_idx = __pyx_t_9; + + /* "sklearn/utils/fast_dict.pyx":83 + * cdef DTYPE_t value + * for idx in range(size): + * key = keys[idx] # <<<<<<<<<<<<<< + * value = values[idx] + * yield key, value + */ + __pyx_t_10 = __pyx_cur_scope->__pyx_v_idx; + __pyx_t_11 = -1; + if (__pyx_t_10 < 0) { + __pyx_t_10 += __pyx_cur_scope->__pyx_v_keys.shape[0]; + if (unlikely(__pyx_t_10 < 0)) __pyx_t_11 = 0; + } else if (unlikely(__pyx_t_10 >= __pyx_cur_scope->__pyx_v_keys.shape[0])) __pyx_t_11 = 0; + if (unlikely(__pyx_t_11 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_11); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_cur_scope->__pyx_v_key = (*((__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t *) ( /* dim=0 */ (__pyx_cur_scope->__pyx_v_keys.data + __pyx_t_10 * __pyx_cur_scope->__pyx_v_keys.strides[0]) ))); + + /* "sklearn/utils/fast_dict.pyx":84 + * for idx in range(size): + * key = keys[idx] + * value = values[idx] # <<<<<<<<<<<<<< + * yield key, value + * + */ + __pyx_t_11 = __pyx_cur_scope->__pyx_v_idx; + __pyx_t_12 = -1; + if (__pyx_t_11 < 0) { + __pyx_t_11 += __pyx_cur_scope->__pyx_v_values.shape[0]; + if (unlikely(__pyx_t_11 < 0)) __pyx_t_12 = 0; + } else if (unlikely(__pyx_t_11 >= __pyx_cur_scope->__pyx_v_values.shape[0])) __pyx_t_12 = 0; + if (unlikely(__pyx_t_12 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_12); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_cur_scope->__pyx_v_value = (*((__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t *) ( /* dim=0 */ (__pyx_cur_scope->__pyx_v_values.data + __pyx_t_11 * __pyx_cur_scope->__pyx_v_values.strides[0]) ))); + + /* "sklearn/utils/fast_dict.pyx":85 + * key = keys[idx] + * value = values[idx] + * yield key, value # <<<<<<<<<<<<<< + * + * def to_arrays(self): + */ + __pyx_t_4 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_cur_scope->__pyx_v_key); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyFloat_FromDouble(__pyx_cur_scope->__pyx_v_value); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_r = ((PyObject *)__pyx_t_3); + __pyx_t_3 = 0; + __pyx_cur_scope->__pyx_t_0 = __pyx_t_8; + __pyx_cur_scope->__pyx_t_1 = __pyx_t_9; + __pyx_cur_scope->__pyx_t_2 = __pyx_t_10; + __pyx_cur_scope->__pyx_t_3 = __pyx_t_11; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + /* return from generator, yielding value */ + __pyx_generator->resume_label = 1; + return __pyx_r; + __pyx_L6_resume_from_yield:; + __pyx_t_8 = __pyx_cur_scope->__pyx_t_0; + __pyx_t_9 = __pyx_cur_scope->__pyx_t_1; + __pyx_t_10 = __pyx_cur_scope->__pyx_t_2; + __pyx_t_11 = __pyx_cur_scope->__pyx_t_3; + if (unlikely(!__pyx_sent_value)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + PyErr_SetNone(PyExc_StopIteration); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); + __Pyx_AddTraceback("__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_L0:; + __Pyx_XDECREF(__pyx_r); + __pyx_generator->resume_label = -1; + __Pyx_Generator_clear((PyObject*)__pyx_generator); + __Pyx_RefNannyFinishContext(); + return NULL; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_12to_arrays(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static char __pyx_doc_7sklearn_5utils_9fast_dict_12IntFloatDict_11to_arrays[] = "Return the key, value representation of the IntFloatDict\n object.\n\n Returns\n =======\n keys : ndarray, shape (n_items, ), dtype=int\n The indices of the data points\n values : ndarray, shape (n_items, ), dtype=float\n The values of the data points\n "; +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_12to_arrays(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("to_arrays (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_11to_arrays(((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/fast_dict.pyx":87 + * yield key, value + * + * def to_arrays(self): # <<<<<<<<<<<<<< + * """Return the key, value representation of the IntFloatDict + * object. + */ + +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_11to_arrays(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self) { + int __pyx_v_size; + PyArrayObject *__pyx_v_keys = 0; + PyArrayObject *__pyx_v_values = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_keys; + __Pyx_Buffer __pyx_pybuffer_keys; + __Pyx_LocalBuf_ND __pyx_pybuffernd_values; + __Pyx_Buffer __pyx_pybuffer_values; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + PyArrayObject *__pyx_t_7 = NULL; + __Pyx_memviewslice __pyx_t_8 = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_t_9 = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("to_arrays", 0); + __pyx_pybuffer_keys.pybuffer.buf = NULL; + __pyx_pybuffer_keys.refcount = 0; + __pyx_pybuffernd_keys.data = NULL; + __pyx_pybuffernd_keys.rcbuffer = &__pyx_pybuffer_keys; + __pyx_pybuffer_values.pybuffer.buf = NULL; + __pyx_pybuffer_values.refcount = 0; + __pyx_pybuffernd_values.data = NULL; + __pyx_pybuffernd_values.rcbuffer = &__pyx_pybuffer_values; + + /* "sklearn/utils/fast_dict.pyx":98 + * The values of the data points + * """ + * cdef int size = self.my_map.size() # <<<<<<<<<<<<<< + * cdef np.ndarray[ITYPE_t, ndim=1] keys = np.empty(size, + * dtype=np.intp) + */ + __pyx_v_size = __pyx_v_self->my_map.size(); + + /* "sklearn/utils/fast_dict.pyx":99 + * """ + * cdef int size = self.my_map.size() + * cdef np.ndarray[ITYPE_t, ndim=1] keys = np.empty(size, # <<<<<<<<<<<<<< + * dtype=np.intp) + * cdef np.ndarray[DTYPE_t, ndim=1] values = np.empty(size, + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyInt_FromLong(__pyx_v_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + + /* "sklearn/utils/fast_dict.pyx":100 + * cdef int size = self.my_map.size() + * cdef np.ndarray[ITYPE_t, ndim=1] keys = np.empty(size, + * dtype=np.intp) # <<<<<<<<<<<<<< + * cdef np.ndarray[DTYPE_t, ndim=1] values = np.empty(size, + * dtype=np.float64) + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__intp); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_keys.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_keys = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_keys.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_keys.diminfo[0].strides = __pyx_pybuffernd_keys.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_keys.diminfo[0].shape = __pyx_pybuffernd_keys.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __pyx_v_keys = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "sklearn/utils/fast_dict.pyx":101 + * cdef np.ndarray[ITYPE_t, ndim=1] keys = np.empty(size, + * dtype=np.intp) + * cdef np.ndarray[DTYPE_t, ndim=1] values = np.empty(size, # <<<<<<<<<<<<<< + * dtype=np.float64) + * self._to_arrays(keys, values) + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyInt_FromLong(__pyx_v_size); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + + /* "sklearn/utils/fast_dict.pyx":102 + * dtype=np.intp) + * cdef np.ndarray[DTYPE_t, ndim=1] values = np.empty(size, + * dtype=np.float64) # <<<<<<<<<<<<<< + * self._to_arrays(keys, values) + * return keys, values + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_values.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_values = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_values.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_values.diminfo[0].strides = __pyx_pybuffernd_values.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_values.diminfo[0].shape = __pyx_pybuffernd_values.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_7 = 0; + __pyx_v_values = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/utils/fast_dict.pyx":103 + * cdef np.ndarray[DTYPE_t, ndim=1] values = np.empty(size, + * dtype=np.float64) + * self._to_arrays(keys, values) # <<<<<<<<<<<<<< + * return keys, values + * + */ + __pyx_t_8 = __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t(((PyObject *)__pyx_v_keys)); + if (unlikely(!__pyx_t_8.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t(((PyObject *)__pyx_v_values)); + if (unlikely(!__pyx_t_9.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = ((struct __pyx_vtabstruct_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_self->__pyx_vtab)->_to_arrays(__pyx_v_self, __pyx_t_8, __pyx_t_9); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __PYX_XDEC_MEMVIEW(&__pyx_t_8, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_9, 1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "sklearn/utils/fast_dict.pyx":104 + * dtype=np.float64) + * self._to_arrays(keys, values) + * return keys, values # <<<<<<<<<<<<<< + * + * cdef _to_arrays(self, ITYPE_t [:] keys, DTYPE_t [:] values): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_keys)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_keys)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_keys)); + __Pyx_INCREF(((PyObject *)__pyx_v_values)); + PyTuple_SET_ITEM(__pyx_t_4, 1, ((PyObject *)__pyx_v_values)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_values)); + __pyx_r = ((PyObject *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __PYX_XDEC_MEMVIEW(&__pyx_t_8, 1); + __PYX_XDEC_MEMVIEW(&__pyx_t_9, 1); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_keys.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_values.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.utils.fast_dict.IntFloatDict.to_arrays", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_keys.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_values.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_keys); + __Pyx_XDECREF((PyObject *)__pyx_v_values); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/fast_dict.pyx":106 + * return keys, values + * + * cdef _to_arrays(self, ITYPE_t [:] keys, DTYPE_t [:] values): # <<<<<<<<<<<<<< + * # Internal version of to_arrays that takes already-initialized arrays + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = self.my_map.begin() + */ + +static PyObject *__pyx_f_7sklearn_5utils_9fast_dict_12IntFloatDict__to_arrays(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self, __Pyx_memviewslice __pyx_v_keys, __Pyx_memviewslice __pyx_v_values) { + std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t>::iterator __pyx_v_it; + std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t>::iterator __pyx_v_end; + int __pyx_v_index; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + __pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t __pyx_t_5; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_to_arrays", 0); + + /* "sklearn/utils/fast_dict.pyx":108 + * cdef _to_arrays(self, ITYPE_t [:] keys, DTYPE_t [:] values): + * # Internal version of to_arrays that takes already-initialized arrays + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = self.my_map.begin() # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = self.my_map.end() + * cdef int index = 0 + */ + __pyx_v_it = __pyx_v_self->my_map.begin(); + + /* "sklearn/utils/fast_dict.pyx":109 + * # Internal version of to_arrays that takes already-initialized arrays + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = self.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = self.my_map.end() # <<<<<<<<<<<<<< + * cdef int index = 0 + * while it != end: + */ + __pyx_v_end = __pyx_v_self->my_map.end(); + + /* "sklearn/utils/fast_dict.pyx":110 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = self.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = self.my_map.end() + * cdef int index = 0 # <<<<<<<<<<<<<< + * while it != end: + * keys[index] = deref(it).first + */ + __pyx_v_index = 0; + + /* "sklearn/utils/fast_dict.pyx":111 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = self.my_map.end() + * cdef int index = 0 + * while it != end: # <<<<<<<<<<<<<< + * keys[index] = deref(it).first + * values[index] = deref(it).second + */ + while (1) { + __pyx_t_1 = ((__pyx_v_it != __pyx_v_end) != 0); + if (!__pyx_t_1) break; + + /* "sklearn/utils/fast_dict.pyx":112 + * cdef int index = 0 + * while it != end: + * keys[index] = deref(it).first # <<<<<<<<<<<<<< + * values[index] = deref(it).second + * inc(it) + */ + __pyx_t_2 = (*__pyx_v_it).first; + __pyx_t_3 = __pyx_v_index; + __pyx_t_4 = -1; + if (__pyx_t_3 < 0) { + __pyx_t_3 += __pyx_v_keys.shape[0]; + if (unlikely(__pyx_t_3 < 0)) __pyx_t_4 = 0; + } else if (unlikely(__pyx_t_3 >= __pyx_v_keys.shape[0])) __pyx_t_4 = 0; + if (unlikely(__pyx_t_4 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_4); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *((__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t *) ( /* dim=0 */ (__pyx_v_keys.data + __pyx_t_3 * __pyx_v_keys.strides[0]) )) = __pyx_t_2; + + /* "sklearn/utils/fast_dict.pyx":113 + * while it != end: + * keys[index] = deref(it).first + * values[index] = deref(it).second # <<<<<<<<<<<<<< + * inc(it) + * index += 1 + */ + __pyx_t_5 = (*__pyx_v_it).second; + __pyx_t_4 = __pyx_v_index; + __pyx_t_6 = -1; + if (__pyx_t_4 < 0) { + __pyx_t_4 += __pyx_v_values.shape[0]; + if (unlikely(__pyx_t_4 < 0)) __pyx_t_6 = 0; + } else if (unlikely(__pyx_t_4 >= __pyx_v_values.shape[0])) __pyx_t_6 = 0; + if (unlikely(__pyx_t_6 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_6); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *((__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t *) ( /* dim=0 */ (__pyx_v_values.data + __pyx_t_4 * __pyx_v_values.strides[0]) )) = __pyx_t_5; + + /* "sklearn/utils/fast_dict.pyx":114 + * keys[index] = deref(it).first + * values[index] = deref(it).second + * inc(it) # <<<<<<<<<<<<<< + * index += 1 + * + */ + (++__pyx_v_it); + + /* "sklearn/utils/fast_dict.pyx":115 + * values[index] = deref(it).second + * inc(it) + * index += 1 # <<<<<<<<<<<<<< + * + * def update(self, IntFloatDict other): + */ + __pyx_v_index = (__pyx_v_index + 1); + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("sklearn.utils.fast_dict.IntFloatDict._to_arrays", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_14update(PyObject *__pyx_v_self, PyObject *__pyx_v_other); /*proto*/ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_14update(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { + CYTHON_UNUSED int __pyx_lineno = 0; + CYTHON_UNUSED const char *__pyx_filename = NULL; + CYTHON_UNUSED int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("update (wrapper)", 0); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_other), __pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict, 1, "other", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_13update(((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_self), ((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_other)); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/fast_dict.pyx":117 + * index += 1 + * + * def update(self, IntFloatDict other): # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = other.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = other.my_map.end() + */ + +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_13update(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_other) { + std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t>::iterator __pyx_v_it; + std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t>::iterator __pyx_v_end; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t __pyx_t_2; + __Pyx_RefNannySetupContext("update", 0); + + /* "sklearn/utils/fast_dict.pyx":118 + * + * def update(self, IntFloatDict other): + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = other.my_map.begin() # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = other.my_map.end() + * while it != end: + */ + __pyx_v_it = __pyx_v_other->my_map.begin(); + + /* "sklearn/utils/fast_dict.pyx":119 + * def update(self, IntFloatDict other): + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = other.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = other.my_map.end() # <<<<<<<<<<<<<< + * while it != end: + * self.my_map[deref(it).first] = deref(it).second + */ + __pyx_v_end = __pyx_v_other->my_map.end(); + + /* "sklearn/utils/fast_dict.pyx":120 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = other.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = other.my_map.end() + * while it != end: # <<<<<<<<<<<<<< + * self.my_map[deref(it).first] = deref(it).second + * inc(it) + */ + while (1) { + __pyx_t_1 = ((__pyx_v_it != __pyx_v_end) != 0); + if (!__pyx_t_1) break; + + /* "sklearn/utils/fast_dict.pyx":121 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = other.my_map.end() + * while it != end: + * self.my_map[deref(it).first] = deref(it).second # <<<<<<<<<<<<<< + * inc(it) + * + */ + __pyx_t_2 = (*__pyx_v_it).second; + (__pyx_v_self->my_map[(*__pyx_v_it).first]) = __pyx_t_2; + + /* "sklearn/utils/fast_dict.pyx":122 + * while it != end: + * self.my_map[deref(it).first] = deref(it).second + * inc(it) # <<<<<<<<<<<<<< + * + * def copy(self): + */ + (++__pyx_v_it); + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_16copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_16copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_15copy(((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/fast_dict.pyx":124 + * inc(it) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) + * # The '=' operator is a copy operator for C++ maps + */ + +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_15copy(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self) { + struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_out_obj = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t> __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "sklearn/utils/fast_dict.pyx":125 + * + * def copy(self): + * cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) # <<<<<<<<<<<<<< + * # The '=' operator is a copy operator for C++ maps + * out_obj.my_map = self.my_map + */ + __pyx_t_1 = __pyx_tp_new_7sklearn_5utils_9fast_dict_IntFloatDict(((PyTypeObject *)((PyObject*)__pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict)), ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict)))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_out_obj = ((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/fast_dict.pyx":127 + * cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) + * # The '=' operator is a copy operator for C++ maps + * out_obj.my_map = self.my_map # <<<<<<<<<<<<<< + * return out_obj + * + */ + __pyx_t_2 = __pyx_v_self->my_map; + __pyx_v_out_obj->my_map = __pyx_t_2; + + /* "sklearn/utils/fast_dict.pyx":128 + * # The '=' operator is a copy operator for C++ maps + * out_obj.my_map = self.my_map + * return out_obj # <<<<<<<<<<<<<< + * + * def append(self, ITYPE_t key, DTYPE_t value): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_out_obj)); + __pyx_r = ((PyObject *)__pyx_v_out_obj); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("sklearn.utils.fast_dict.IntFloatDict.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_out_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_18append(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_18append(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t __pyx_v_key; + __pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t __pyx_v_value; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("append (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__value,0}; + PyObject* values[2] = {0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__value)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("append", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "append") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + } + __pyx_v_key = __Pyx_PyInt_from_py_Py_intptr_t(values[0]); if (unlikely((__pyx_v_key == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_value = __pyx_PyFloat_AsDouble(values[1]); if (unlikely((__pyx_v_value == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("append", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils.fast_dict.IntFloatDict.append", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_17append(((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_self), __pyx_v_key, __pyx_v_value); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/fast_dict.pyx":130 + * return out_obj + * + * def append(self, ITYPE_t key, DTYPE_t value): # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = self.my_map.end() + * # Decrement the iterator + */ + +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_12IntFloatDict_17append(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_self, __pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t __pyx_v_key, __pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t __pyx_v_value) { + std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t>::iterator __pyx_v_end; + std::pair<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t> __pyx_v_args; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("append", 0); + + /* "sklearn/utils/fast_dict.pyx":131 + * + * def append(self, ITYPE_t key, DTYPE_t value): + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = self.my_map.end() # <<<<<<<<<<<<<< + * # Decrement the iterator + * dec(end) + */ + __pyx_v_end = __pyx_v_self->my_map.end(); + + /* "sklearn/utils/fast_dict.pyx":133 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = self.my_map.end() + * # Decrement the iterator + * dec(end) # <<<<<<<<<<<<<< + * # Construct our arguments + * cdef pair[ITYPE_t, DTYPE_t] args + */ + (--__pyx_v_end); + + /* "sklearn/utils/fast_dict.pyx":136 + * # Construct our arguments + * cdef pair[ITYPE_t, DTYPE_t] args + * args.first = key # <<<<<<<<<<<<<< + * args.second = value + * self.my_map.insert(end, args) + */ + __pyx_v_args.first = __pyx_v_key; + + /* "sklearn/utils/fast_dict.pyx":137 + * cdef pair[ITYPE_t, DTYPE_t] args + * args.first = key + * args.second = value # <<<<<<<<<<<<<< + * self.my_map.insert(end, args) + * + */ + __pyx_v_args.second = __pyx_v_value; + + /* "sklearn/utils/fast_dict.pyx":138 + * args.first = key + * args.second = value + * self.my_map.insert(end, args) # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_self->my_map.insert(__pyx_v_end, __pyx_v_args); + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_1argmin(PyObject *__pyx_self, PyObject *__pyx_v_d); /*proto*/ +static PyMethodDef __pyx_mdef_7sklearn_5utils_9fast_dict_1argmin = {__Pyx_NAMESTR("argmin"), (PyCFunction)__pyx_pw_7sklearn_5utils_9fast_dict_1argmin, METH_O, __Pyx_DOCSTR(0)}; +static PyObject *__pyx_pw_7sklearn_5utils_9fast_dict_1argmin(PyObject *__pyx_self, PyObject *__pyx_v_d) { + CYTHON_UNUSED int __pyx_lineno = 0; + CYTHON_UNUSED const char *__pyx_filename = NULL; + CYTHON_UNUSED int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("argmin (wrapper)", 0); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_d), __pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict, 1, "d", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_9fast_dict_argmin(__pyx_self, ((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)__pyx_v_d)); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/fast_dict.pyx":144 + * # operation on dict + * + * def argmin(IntFloatDict d): # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = d.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = d.my_map.end() + */ + +static PyObject *__pyx_pf_7sklearn_5utils_9fast_dict_argmin(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *__pyx_v_d) { + std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t>::iterator __pyx_v_it; + std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t>::iterator __pyx_v_end; + __pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t __pyx_v_min_key; + __pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t __pyx_v_min_value; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + __pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t __pyx_t_3; + int __pyx_t_4; + __pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("argmin", 0); + + /* "sklearn/utils/fast_dict.pyx":145 + * + * def argmin(IntFloatDict d): + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = d.my_map.begin() # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = d.my_map.end() + * cdef ITYPE_t min_key + */ + __pyx_v_it = __pyx_v_d->my_map.begin(); + + /* "sklearn/utils/fast_dict.pyx":146 + * def argmin(IntFloatDict d): + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = d.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = d.my_map.end() # <<<<<<<<<<<<<< + * cdef ITYPE_t min_key + * cdef DTYPE_t min_value = np.inf + */ + __pyx_v_end = __pyx_v_d->my_map.end(); + + /* "sklearn/utils/fast_dict.pyx":148 + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = d.my_map.end() + * cdef ITYPE_t min_key + * cdef DTYPE_t min_value = np.inf # <<<<<<<<<<<<<< + * while it != end: + * if deref(it).second < min_value: + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_3 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_min_value = __pyx_t_3; + + /* "sklearn/utils/fast_dict.pyx":149 + * cdef ITYPE_t min_key + * cdef DTYPE_t min_value = np.inf + * while it != end: # <<<<<<<<<<<<<< + * if deref(it).second < min_value: + * min_value = deref(it).second + */ + while (1) { + __pyx_t_4 = ((__pyx_v_it != __pyx_v_end) != 0); + if (!__pyx_t_4) break; + + /* "sklearn/utils/fast_dict.pyx":150 + * cdef DTYPE_t min_value = np.inf + * while it != end: + * if deref(it).second < min_value: # <<<<<<<<<<<<<< + * min_value = deref(it).second + * min_key = deref(it).first + */ + __pyx_t_4 = (((*__pyx_v_it).second < __pyx_v_min_value) != 0); + if (__pyx_t_4) { + + /* "sklearn/utils/fast_dict.pyx":151 + * while it != end: + * if deref(it).second < min_value: + * min_value = deref(it).second # <<<<<<<<<<<<<< + * min_key = deref(it).first + * inc(it) + */ + __pyx_t_3 = (*__pyx_v_it).second; + __pyx_v_min_value = __pyx_t_3; + + /* "sklearn/utils/fast_dict.pyx":152 + * if deref(it).second < min_value: + * min_value = deref(it).second + * min_key = deref(it).first # <<<<<<<<<<<<<< + * inc(it) + * return min_key, min_value + */ + __pyx_t_5 = (*__pyx_v_it).first; + __pyx_v_min_key = __pyx_t_5; + goto __pyx_L5; + } + __pyx_L5:; + + /* "sklearn/utils/fast_dict.pyx":153 + * min_value = deref(it).second + * min_key = deref(it).first + * inc(it) # <<<<<<<<<<<<<< + * return min_key, min_value + * + */ + (++__pyx_v_it); + } + + /* "sklearn/utils/fast_dict.pyx":154 + * min_key = deref(it).first + * inc(it) + * return min_key, min_value # <<<<<<<<<<<<<< + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyInt_to_py_Py_intptr_t(__pyx_v_min_key); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_min_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_2 = 0; + __pyx_t_1 = 0; + __pyx_r = ((PyObject *)__pyx_t_6); + __pyx_t_6 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("sklearn.utils.fast_dict.argmin", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "numpy.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "numpy.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "numpy.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "numpy.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "numpy.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "numpy.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_3) { + + /* "numpy.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "numpy.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "numpy.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "numpy.pxd":222 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "numpy.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { + + /* "numpy.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "numpy.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "numpy.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "numpy.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "numpy.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "numpy.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "numpy.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "numpy.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "numpy.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "numpy.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "numpy.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "numpy.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "numpy.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "numpy.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "numpy.pxd":251 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "numpy.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; + + /* "numpy.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); + if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "numpy.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_1) { + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_7), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "numpy.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k__b; + break; + + /* "numpy.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k__B; + break; + + /* "numpy.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k__h; + break; + + /* "numpy.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k__H; + break; + + /* "numpy.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k__i; + break; + + /* "numpy.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k__I; + break; + + /* "numpy.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k__l; + break; + + /* "numpy.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k__L; + break; + + /* "numpy.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k__q; + break; + + /* "numpy.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k__Q; + break; + + /* "numpy.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k__f; + break; + + /* "numpy.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k__d; + break; + + /* "numpy.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k__g; + break; + + /* "numpy.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k__Zf; + break; + + /* "numpy.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k__Zd; + break; + + /* "numpy.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k__Zg; + break; + + /* "numpy.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k__O; + break; + default: + + /* "numpy.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_8), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "numpy.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "numpy.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "numpy.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "numpy.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "numpy.pxd":285 + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + * &offset) # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "numpy.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + __pyx_L11:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "numpy.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "numpy.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "numpy.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "numpy.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "numpy.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "numpy.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + long __pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "numpy.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF(__pyx_v_childname); + __pyx_v_childname = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); + __pyx_v_fields = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "numpy.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { + PyObject* sequence = ((PyObject *)__pyx_v_fields); + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_child)); + __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_v_new_offset); + __pyx_v_new_offset = __pyx_t_4; + __pyx_t_4 = 0; + + /* "numpy.pxd":798 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + + /* "numpy.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + + /* "numpy.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_7) { + __pyx_t_8 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_8 = __pyx_t_7; + } + if (!__pyx_t_8) { + + /* "numpy.pxd":802 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_7) { + __pyx_t_9 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_10 = __pyx_t_9; + } else { + __pyx_t_10 = __pyx_t_7; + } + __pyx_t_7 = __pyx_t_10; + } else { + __pyx_t_7 = __pyx_t_8; + } + if (__pyx_t_7) { + + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + + /* "numpy.pxd":813 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_7) break; + + /* "numpy.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "numpy.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "numpy.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); + } + + /* "numpy.pxd":818 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); + + /* "numpy.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_7 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_7) { + + /* "numpy.pxd":821 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_v_t); + __pyx_v_t = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_7 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_7) { + + /* "numpy.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_13), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 98; + goto __pyx_L13; + } + + /* "numpy.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 66; + goto __pyx_L13; + } + + /* "numpy.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 104; + goto __pyx_L13; + } + + /* "numpy.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 72; + goto __pyx_L13; + } + + /* "numpy.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 105; + goto __pyx_L13; + } + + /* "numpy.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 73; + goto __pyx_L13; + } + + /* "numpy.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 108; + goto __pyx_L13; + } + + /* "numpy.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 76; + goto __pyx_L13; + } + + /* "numpy.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 113; + goto __pyx_L13; + } + + /* "numpy.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 81; + goto __pyx_L13; + } + + /* "numpy.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 102; + goto __pyx_L13; + } + + /* "numpy.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 100; + goto __pyx_L13; + } + + /* "numpy.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 103; + goto __pyx_L13; + } + + /* "numpy.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L13; + } + + /* "numpy.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_7) { + (__pyx_v_f[0]) = 79; + goto __pyx_L13; + } + /*else*/ { + + /* "numpy.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_8), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L13:; + + /* "numpy.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_12; + } + __pyx_L11:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "numpy.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":965 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "numpy.pxd":967 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "numpy.pxd":968 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":970 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "numpy.pxd":971 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "numpy.pxd":972 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "numpy.pxd":973 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":975 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "numpy.pxd":976 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "numpy.pxd":977 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":979 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_shape = 0; + Py_ssize_t __pyx_v_itemsize; + PyObject *__pyx_v_format = 0; + PyObject *__pyx_v_mode = 0; + int __pyx_v_allocate_buffer; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__shape,&__pyx_n_s__itemsize,&__pyx_n_s__format,&__pyx_n_s__mode,&__pyx_n_s__allocate_buffer,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[3] = ((PyObject *)__pyx_n_u__c); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shape)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__itemsize)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__format)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__mode); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__allocate_buffer); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_shape = ((PyObject*)values[0]); + __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_format = values[2]; + __pyx_v_mode = values[3]; + if (values[4]) { + __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "View.MemoryView":114 + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, + * mode=u"c", bint allocate_buffer=True): # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_v_allocate_buffer = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { + PyErr_Format(PyExc_TypeError, "Argument 'format' must not be None"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_r = __pyx_array_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":113 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode=u"c", bint allocate_buffer=True): + * + */ + +static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { + int __pyx_v_idx; + Py_ssize_t __pyx_v_i; + PyObject **__pyx_v_p; + PyObject *__pyx_v_encode = NULL; + PyObject *__pyx_v_dim = NULL; + char __pyx_v_order; + PyObject *__pyx_v_decode = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_INCREF(__pyx_v_format); + __Pyx_INCREF(__pyx_v_mode); + + /* "View.MemoryView":120 + * cdef PyObject **p + * + * self.ndim = len(shape) # <<<<<<<<<<<<<< + * self.itemsize = itemsize + * + */ + if (unlikely(((PyObject *)__pyx_v_shape) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = PyTuple_GET_SIZE(((PyObject *)__pyx_v_shape)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->ndim = __pyx_t_1; + + /* "View.MemoryView":121 + * + * self.ndim = len(shape) + * self.itemsize = itemsize # <<<<<<<<<<<<<< + * + * if not self.ndim: + */ + __pyx_v_self->itemsize = __pyx_v_itemsize; + + /* "View.MemoryView":123 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ + __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":124 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if self.itemsize <= 0: + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":126 + * raise ValueError("Empty shape tuple for cython.array") + * + * if self.itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ + __pyx_t_2 = ((__pyx_v_self->itemsize <= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":127 + * + * if self.itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * encode = getattr(format, 'encode', None) + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_17), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":129 + * raise ValueError("itemsize <= 0 for cython.array") + * + * encode = getattr(format, 'encode', None) # <<<<<<<<<<<<<< + * if encode: + * format = encode('ASCII') + */ + __pyx_t_3 = __Pyx_GetAttr3(__pyx_v_format, ((PyObject *)__pyx_n_s__encode), Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_encode = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":130 + * + * encode = getattr(format, 'encode', None) + * if encode: # <<<<<<<<<<<<<< + * format = encode('ASCII') + * self._format = format + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_encode); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":131 + * encode = getattr(format, 'encode', None) + * if encode: + * format = encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format + * self.format = self._format + */ + __pyx_t_3 = PyObject_Call(__pyx_v_encode, ((PyObject *)__pyx_k_tuple_18), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_format); + __pyx_v_format = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":132 + * if encode: + * format = encode('ASCII') + * self._format = format # <<<<<<<<<<<<<< + * self.format = self._format + * + */ + if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_format); + __Pyx_GIVEREF(__pyx_v_format); + __Pyx_GOTREF(__pyx_v_self->_format); + __Pyx_DECREF(((PyObject *)__pyx_v_self->_format)); + __pyx_v_self->_format = ((PyObject*)__pyx_v_format); + + /* "View.MemoryView":133 + * format = encode('ASCII') + * self._format = format + * self.format = self._format # <<<<<<<<<<<<<< + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) + */ + __pyx_t_4 = __Pyx_PyObject_AsString(((PyObject *)__pyx_v_self->_format)); if (unlikely((!__pyx_t_4) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_self->format = __pyx_t_4; + + /* "View.MemoryView":135 + * self.format = self._format + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<< + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) + * + */ + __pyx_v_self->_shape = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim))); + + /* "View.MemoryView":136 + * + * self._shape = malloc(sizeof(Py_ssize_t)*self.ndim) + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<< + * + * if not self._shape or not self._strides: + */ + __pyx_v_self->_strides = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim))); + + /* "View.MemoryView":138 + * self._strides = malloc(sizeof(Py_ssize_t)*self.ndim) + * + * if not self._shape or not self._strides: # <<<<<<<<<<<<<< + * free(self._shape) + * free(self._strides) + */ + __pyx_t_2 = ((!(__pyx_v_self->_shape != 0)) != 0); + if (!__pyx_t_2) { + __pyx_t_5 = ((!(__pyx_v_self->_strides != 0)) != 0); + __pyx_t_6 = __pyx_t_5; + } else { + __pyx_t_6 = __pyx_t_2; + } + if (__pyx_t_6) { + + /* "View.MemoryView":139 + * + * if not self._shape or not self._strides: + * free(self._shape) # <<<<<<<<<<<<<< + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") + */ + free(__pyx_v_self->_shape); + + /* "View.MemoryView":140 + * if not self._shape or not self._strides: + * free(self._shape) + * free(self._strides) # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape or strides.") + * + */ + free(__pyx_v_self->_strides); + + /* "View.MemoryView":141 + * free(self._shape) + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_20), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":144 + * + * + * idx = 0 # <<<<<<<<<<<<<< + * for idx, dim in enumerate(shape): + * if dim <= 0: + */ + __pyx_v_idx = 0; + + /* "View.MemoryView":145 + * + * idx = 0 + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + __pyx_t_7 = 0; + __pyx_t_3 = ((PyObject *)__pyx_v_shape); __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; + for (;;) { + if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_8 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_8); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_8 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF(__pyx_v_dim); + __pyx_v_dim = __pyx_t_8; + __pyx_t_8 = 0; + __pyx_v_idx = __pyx_t_7; + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":146 + * idx = 0 + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * + */ + __pyx_t_8 = PyObject_RichCompare(__pyx_v_dim, __pyx_int_0, Py_LE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (__pyx_t_6) { + + /* "View.MemoryView":147 + * for idx, dim in enumerate(shape): + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< + * + * self._shape[idx] = dim + */ + __pyx_t_8 = PyInt_FromLong(__pyx_v_idx); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_dim); + PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_dim); + __Pyx_GIVEREF(__pyx_v_dim); + __pyx_t_8 = 0; + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_21), ((PyObject *)__pyx_t_9)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_9, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":149 + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * + * self._shape[idx] = dim # <<<<<<<<<<<<<< + * idx += 1 + * + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_dim); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_t_10; + + /* "View.MemoryView":150 + * + * self._shape[idx] = dim + * idx += 1 # <<<<<<<<<<<<<< + * + * if mode not in ("fortran", "c"): + */ + __pyx_v_idx = (__pyx_v_idx + 1); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":152 + * idx += 1 + * + * if mode not in ("fortran", "c"): # <<<<<<<<<<<<<< + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + * + */ + __Pyx_INCREF(__pyx_v_mode); + __pyx_t_3 = __pyx_v_mode; + __pyx_t_8 = PyObject_RichCompare(__pyx_t_3, ((PyObject *)__pyx_n_s__fortran), Py_NE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (((int)__pyx_t_6)) { + __pyx_t_8 = PyObject_RichCompare(__pyx_t_3, ((PyObject *)__pyx_n_s__c), Py_NE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_5 = ((int)__pyx_t_2); + } else { + __pyx_t_5 = ((int)__pyx_t_6); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = (__pyx_t_5 != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":153 + * + * if mode not in ("fortran", "c"): + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< + * + * cdef char order + */ + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_22), __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":156 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = 'F' + * else: + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_mode, ((PyObject *)__pyx_n_s__fortran), Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + + /* "View.MemoryView":157 + * cdef char order + * if mode == 'fortran': + * order = 'F' # <<<<<<<<<<<<<< + * else: + * order = 'C' + */ + __pyx_v_order = 'F'; + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":159 + * order = 'F' + * else: + * order = 'C' # <<<<<<<<<<<<<< + * + * self.len = fill_contig_strides_array(self._shape, self._strides, + */ + __pyx_v_order = 'C'; + } + __pyx_L11:; + + /* "View.MemoryView":161 + * order = 'C' + * + * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< + * itemsize, self.ndim, order) + * + */ + __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); + + /* "View.MemoryView":164 + * itemsize, self.ndim, order) + * + * decode = getattr(mode, 'decode', None) # <<<<<<<<<<<<<< + * if decode: + * mode = decode('ASCII') + */ + __pyx_t_3 = __Pyx_GetAttr3(__pyx_v_mode, ((PyObject *)__pyx_n_s__decode), Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_decode = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":165 + * + * decode = getattr(mode, 'decode', None) + * if decode: # <<<<<<<<<<<<<< + * mode = decode('ASCII') + * self.mode = mode + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_decode); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":166 + * decode = getattr(mode, 'decode', None) + * if decode: + * mode = decode('ASCII') # <<<<<<<<<<<<<< + * self.mode = mode + * + */ + __pyx_t_3 = PyObject_Call(__pyx_v_decode, ((PyObject *)__pyx_k_tuple_23), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_mode); + __pyx_v_mode = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":167 + * if decode: + * mode = decode('ASCII') + * self.mode = mode # <<<<<<<<<<<<<< + * + * self.free_data = allocate_buffer + */ + if (!(likely(PyUnicode_CheckExact(__pyx_v_mode))||((__pyx_v_mode) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected unicode, got %.200s", Py_TYPE(__pyx_v_mode)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(__pyx_v_mode); + __Pyx_GIVEREF(__pyx_v_mode); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(((PyObject *)__pyx_v_self->mode)); + __pyx_v_self->mode = ((PyObject*)__pyx_v_mode); + + /* "View.MemoryView":169 + * self.mode = mode + * + * self.free_data = allocate_buffer # <<<<<<<<<<<<<< + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + */ + __pyx_v_self->free_data = __pyx_v_allocate_buffer; + + /* "View.MemoryView":170 + * + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< + * if allocate_buffer: + * self.data = malloc(self.len) + */ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_format, ((PyObject *)__pyx_n_b__O), Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_6; + + /* "View.MemoryView":171 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * self.data = malloc(self.len) + * if not self.data: + */ + __pyx_t_6 = (__pyx_v_allocate_buffer != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":172 + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + * self.data = malloc(self.len) # <<<<<<<<<<<<<< + * if not self.data: + * raise MemoryError("unable to allocate array data.") + */ + __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); + + /* "View.MemoryView":173 + * if allocate_buffer: + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ + __pyx_t_6 = ((!(__pyx_v_self->data != 0)) != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":174 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_MemoryError, ((PyObject *)__pyx_k_tuple_25), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":176 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ + __pyx_t_6 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_6) { + + /* "View.MemoryView":177 + * + * if self.dtype_is_object: + * p = self.data # <<<<<<<<<<<<<< + * for i in range(self.len / itemsize): + * p[i] = Py_None + */ + __pyx_v_p = ((PyObject **)__pyx_v_self->data); + + /* "View.MemoryView":178 + * if self.dtype_is_object: + * p = self.data + * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< + * p[i] = Py_None + * Py_INCREF(Py_None) + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_1; __pyx_t_10+=1) { + __pyx_v_i = __pyx_t_10; + + /* "View.MemoryView":179 + * p = self.data + * for i in range(self.len / itemsize): + * p[i] = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + (__pyx_v_p[__pyx_v_i]) = Py_None; + + /* "View.MemoryView":180 + * for i in range(self.len / itemsize): + * p[i] = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + Py_INCREF(Py_None); + } + goto __pyx_L15; + } + __pyx_L15:; + goto __pyx_L13; + } + __pyx_L13:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_encode); + __Pyx_XDECREF(__pyx_v_dim); + __Pyx_XDECREF(__pyx_v_decode); + __Pyx_XDECREF(__pyx_v_format); + __Pyx_XDECREF(__pyx_v_mode); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":183 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == b"c": + */ + +static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_bufmode; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + Py_ssize_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":184 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 # <<<<<<<<<<<<<< + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = -1; + + /* "View.MemoryView":185 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == b"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": + */ + __pyx_t_1 = (__Pyx_PyUnicode_Equals(((PyObject *)__pyx_v_self->mode), ((PyObject *)__pyx_n_b__c), Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":186 + * cdef int bufmode = -1 + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + + /* "View.MemoryView":187 + * if self.mode == b"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ + __pyx_t_2 = (__Pyx_PyUnicode_Equals(((PyObject *)__pyx_v_self->mode), ((PyObject *)__pyx_n_b__fortran), Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":188 + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + */ + __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":189 + * elif self.mode == b"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ + __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":190 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_27), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":191 + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data # <<<<<<<<<<<<<< + * info.len = self.len + * info.ndim = self.ndim + */ + __pyx_t_4 = __pyx_v_self->data; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":192 + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + * info.len = self.len # <<<<<<<<<<<<<< + * info.ndim = self.ndim + * info.shape = self._shape + */ + __pyx_t_5 = __pyx_v_self->len; + __pyx_v_info->len = __pyx_t_5; + + /* "View.MemoryView":193 + * info.buf = self.data + * info.len = self.len + * info.ndim = self.ndim # <<<<<<<<<<<<<< + * info.shape = self._shape + * info.strides = self._strides + */ + __pyx_t_6 = __pyx_v_self->ndim; + __pyx_v_info->ndim = __pyx_t_6; + + /* "View.MemoryView":194 + * info.len = self.len + * info.ndim = self.ndim + * info.shape = self._shape # <<<<<<<<<<<<<< + * info.strides = self._strides + * info.suboffsets = NULL + */ + __pyx_t_7 = __pyx_v_self->_shape; + __pyx_v_info->shape = __pyx_t_7; + + /* "View.MemoryView":195 + * info.ndim = self.ndim + * info.shape = self._shape + * info.strides = self._strides # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = self.itemsize + */ + __pyx_t_7 = __pyx_v_self->_strides; + __pyx_v_info->strides = __pyx_t_7; + + /* "View.MemoryView":196 + * info.shape = self._shape + * info.strides = self._strides + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = self.itemsize + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; + + /* "View.MemoryView":197 + * info.strides = self._strides + * info.suboffsets = NULL + * info.itemsize = self.itemsize # <<<<<<<<<<<<<< + * info.readonly = 0 + * + */ + __pyx_t_5 = __pyx_v_self->itemsize; + __pyx_v_info->itemsize = __pyx_t_5; + + /* "View.MemoryView":198 + * info.suboffsets = NULL + * info.itemsize = self.itemsize + * info.readonly = 0 # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":200 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":201 + * + * if flags & PyBUF_FORMAT: + * info.format = self.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_4 = __pyx_v_self->format; + __pyx_v_info->format = __pyx_t_4; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":203 + * info.format = self.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.obj = self + */ + __pyx_v_info->format = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":205 + * info.format = NULL + * + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_array_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":209 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + +static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":210 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ + __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":211 + * def __dealloc__(array self): + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) # <<<<<<<<<<<<<< + * elif self.free_data: + * if self.dtype_is_object: + */ + __pyx_v_self->callback_free_data(__pyx_v_self->data); + goto __pyx_L3; + } + + /* "View.MemoryView":212 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ + __pyx_t_1 = (__pyx_v_self->free_data != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":213 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":215 + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) # <<<<<<<<<<<<<< + * free(self.data) + * + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":216 + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + * free(self.data) # <<<<<<<<<<<<<< + * + * free(self._strides) + */ + free(__pyx_v_self->data); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":218 + * free(self.data) + * + * free(self._strides) # <<<<<<<<<<<<<< + * free(self._shape) + * + */ + free(__pyx_v_self->_strides); + + /* "View.MemoryView":219 + * + * free(self._strides) + * free(self._shape) # <<<<<<<<<<<<<< + * + * property memview: + */ + free(__pyx_v_self->_shape); + + __Pyx_RefNannyFinishContext(); +} + +/* Python wrapper */ +static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static PyObject *get_memview(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = get_memview_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":223 + * property memview: + * @cname('get_memview') + * def __get__(self): # <<<<<<<<<<<<<< + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + */ + +static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":225 + * def __get__(self): + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< + * return memoryview(self, flags, self.dtype_is_object) + * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":226 + * + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromLong(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":229 + * + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + +static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":230 + * + * def __getattr__(self, attr): + * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * + * def __getitem__(self, item): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":232 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + +static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":233 + * + * def __getitem__(self, item): + * return self.memview[item] # <<<<<<<<<<<<<< + * + * def __setitem__(self, item, value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (!__pyx_t_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_array_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":235 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + +static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "View.MemoryView":236 + * + * def __setitem__(self, item, value): + * self.memview[item] = value # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":240 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + +static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { + struct __pyx_array_obj *__pyx_v_result = 0; + struct __pyx_array_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("array_cwrapper", 0); + + /* "View.MemoryView":244 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":245 + * + * if buf == NULL: + * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_shape)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 2, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + PyTuple_SET_ITEM(__pyx_t_5, 3, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":247 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_shape)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_shape)); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 2, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + PyTuple_SET_ITEM(__pyx_t_2, 3, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + + /* "View.MemoryView":248 + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) # <<<<<<<<<<<<<< + * result.data = buf + * + */ + __pyx_t_5 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 248; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__allocate_buffer), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":249 + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) + * result.data = buf # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->data = __pyx_v_buf; + } + __pyx_L3:; + + /* "View.MemoryView":251 + * result.data = buf + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + __pyx_r = ((struct __pyx_array_obj *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_name = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__name,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__name)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_name = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":277 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + +static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "View.MemoryView":278 + * cdef object name + * def __init__(self, name): + * self.name = name # <<<<<<<<<<<<<< + * def __repr__(self): + * return self.name + */ + __Pyx_INCREF(__pyx_v_name); + __Pyx_GIVEREF(__pyx_v_name); + __Pyx_GOTREF(__pyx_v_self->name); + __Pyx_DECREF(__pyx_v_self->name); + __pyx_v_self->name = __pyx_v_name; + + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":279 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + +static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":280 + * self.name = name + * def __repr__(self): + * return self.name # <<<<<<<<<<<<<< + * + * cdef generic = Enum("") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->name); + __pyx_r = __pyx_v_self->name; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":294 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + +static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { + Py_intptr_t __pyx_v_aligned_p; + size_t __pyx_v_offset; + void *__pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":296 + * cdef void *align_pointer(void *memory, size_t alignment) nogil: + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< + * cdef size_t offset + * + */ + __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + + /* "View.MemoryView":300 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":302 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + __pyx_t_1 = ((__pyx_v_offset > 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":303 + * + * if offset > 0: + * aligned_p += alignment - offset # <<<<<<<<<<<<<< + * + * return aligned_p + */ + __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":305 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview') + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_obj = 0; + int __pyx_v_flags; + int __pyx_v_dtype_is_object; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__obj,&__pyx_n_s__flags,&__pyx_n_s__dtype_is_object,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__obj)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__flags)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dtype_is_object); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_obj = values[0]; + __pyx_v_flags = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (values[2]) { + __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } else { + + /* "View.MemoryView":323 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + __pyx_v_dtype_is_object = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_memoryview_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "View.MemoryView":324 + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj # <<<<<<<<<<<<<< + * self.flags = flags + * if type(self) is memoryview or obj is not None: + */ + __Pyx_INCREF(__pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __Pyx_GOTREF(__pyx_v_self->obj); + __Pyx_DECREF(__pyx_v_self->obj); + __pyx_v_self->obj = __pyx_v_obj; + + /* "View.MemoryView":325 + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj + * self.flags = flags # <<<<<<<<<<<<<< + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + */ + __pyx_v_self->flags = __pyx_v_flags; + + /* "View.MemoryView":326 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ + __pyx_t_1 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type))); + if (!(__pyx_t_1 != 0)) { + __pyx_t_2 = (__pyx_v_obj != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + } else { + __pyx_t_3 = (__pyx_t_1 != 0); + } + if (__pyx_t_3) { + + /* "View.MemoryView":327 + * self.flags = flags + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + */ + __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":328 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_t_3 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":329 + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; + + /* "View.MemoryView":330 + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * self.lock = PyThread_allocate_lock() + */ + Py_INCREF(Py_None); + goto __pyx_L4; + } + __pyx_L4:; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":332 + * Py_INCREF(Py_None) + * + * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< + * if self.lock == NULL: + * raise MemoryError + */ + __pyx_v_self->lock = PyThread_allocate_lock(); + + /* "View.MemoryView":333 + * + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + __pyx_t_3 = ((__pyx_v_self->lock == NULL) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":334 + * self.lock = PyThread_allocate_lock() + * if self.lock == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":336 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = self.view.format == b'O' + * else: + */ + __pyx_t_3 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":337 + * + * if flags & PyBUF_FORMAT: + * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< + * else: + * self.dtype_is_object = dtype_is_object + */ + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_6 = PyObject_RichCompare(((PyObject *)__pyx_t_5), ((PyObject *)__pyx_n_b__O), Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":339 + * self.dtype_is_object = self.view.format == b'O' + * else: + * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + */ + __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; + } + __pyx_L6:; + + /* "View.MemoryView":341 + * self.dtype_is_object = dtype_is_object + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL + */ + __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); + + /* "View.MemoryView":343 + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(memoryview self): + */ + __pyx_v_self->typeinfo = NULL; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":345 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + +static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":346 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< + * __Pyx_ReleaseBuffer(&self.view) + * + */ + __pyx_t_1 = (__pyx_v_self->obj != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":347 + * def __dealloc__(memoryview self): + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< + * + * if self.lock != NULL: + */ + __Pyx_ReleaseBuffer((&__pyx_v_self->view)); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":349 + * __Pyx_ReleaseBuffer(&self.view) + * + * if self.lock != NULL: # <<<<<<<<<<<<<< + * PyThread_free_lock(self.lock) + * + */ + __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":350 + * + * if self.lock != NULL: + * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + */ + PyThread_free_lock(__pyx_v_self->lock); + goto __pyx_L4; + } + __pyx_L4:; + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":352 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + Py_ssize_t __pyx_v_dim; + char *__pyx_v_itemp; + PyObject *__pyx_v_idx = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_item_pointer", 0); + + /* "View.MemoryView":354 + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< + * + * for dim, idx in enumerate(index): + */ + __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); + + /* "View.MemoryView":356 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + __pyx_t_1 = 0; + if (PyList_CheckExact(__pyx_v_index) || PyTuple_CheckExact(__pyx_v_index)) { + __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; + } + for (;;) { + if (!__pyx_t_4 && PyList_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_4 && PyTuple_CheckExact(__pyx_t_2)) { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF(__pyx_v_idx); + __pyx_v_idx = __pyx_t_5; + __pyx_t_5 = 0; + __pyx_v_dim = __pyx_t_1; + __pyx_t_1 = (__pyx_t_1 + 1); + + /* "View.MemoryView":357 + * + * for dim, idx in enumerate(index): + * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< + * + * return itemp + */ + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_7; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":359 + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + * return itemp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_itemp; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":362 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_indices = NULL; + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *(*__pyx_t_7)(PyObject *); + char *__pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":363 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":364 + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: + * return self # <<<<<<<<<<<<<< + * + * have_slices, indices = _unellipsify(index, self.view.ndim) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __pyx_r = ((PyObject *)__pyx_v_self); + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":366 + * return self + * + * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * cdef char *itemp + */ + __pyx_t_3 = ((PyObject *)_unellipsify(__pyx_v_index, __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (likely(PyTuple_CheckExact(__pyx_t_3))) { + PyObject* sequence = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_6 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = Py_TYPE(__pyx_t_6)->tp_iternext; + index = 0; __pyx_t_4 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_4)) goto __pyx_L4_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + index = 1; __pyx_t_5 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_5)) goto __pyx_L4_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_6), 2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = NULL; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L5_unpacking_done; + __pyx_L4_unpacking_failed:; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_7 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L5_unpacking_done:; + } + __pyx_v_have_slices = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; + + /* "View.MemoryView":369 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_2) { + + /* "View.MemoryView":370 + * cdef char *itemp + * if have_slices: + * return memview_slice(self, indices) # <<<<<<<<<<<<<< + * else: + * itemp = self.get_item_pointer(indices) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":372 + * return memview_slice(self, indices) + * else: + * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< + * return self.convert_item_to_object(itemp) + * + */ + __pyx_t_8 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_8 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_8; + + /* "View.MemoryView":373 + * else: + * itemp = self.get_item_pointer(indices) + * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< + * + * def __setitem__(memoryview self, object index, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + __pyx_L6:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":375 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * have_slices, index = _unellipsify(index, self.view.ndim) + * + */ + +static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_obj = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *(*__pyx_t_5)(PyObject *); + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_INCREF(__pyx_v_index); + + /* "View.MemoryView":376 + * + * def __setitem__(memoryview self, object index, object value): + * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * if have_slices: + */ + __pyx_t_1 = ((PyObject *)_unellipsify(__pyx_v_index, __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (likely(PyTuple_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_3 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = NULL; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L4_unpacking_done:; + } + __pyx_v_have_slices = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_v_index); + __pyx_v_index = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":378 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":379 + * + * if have_slices: + * obj = self.is_slice(value) # <<<<<<<<<<<<<< + * if obj: + * self.setitem_slice_assignment(self[index], obj) + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_obj = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":380 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "View.MemoryView":381 + * obj = self.is_slice(value) + * if obj: + * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< + * else: + * self.setitem_slice_assign_scalar(self[index], value) + */ + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (!__pyx_t_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":383 + * self.setitem_slice_assignment(self[index], obj) + * else: + * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< + * else: + * self.setitem_indexed(index, value) + */ + __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (!__pyx_t_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":385 + * self.setitem_slice_assign_scalar(self[index], value) + * else: + * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< + * + * cdef is_slice(self, obj): + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L5:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":387 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_slice", 0); + __Pyx_INCREF(__pyx_v_obj); + + /* "View.MemoryView":388 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type)); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":389 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + { + __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + /*try:*/ { + + /* "View.MemoryView":390 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_6 = PyInt_FromLong((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":391 + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * except TypeError: + * return None + */ + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_7 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_v_obj); + __pyx_v_obj = __pyx_t_7; + __pyx_t_7 = 0; + } + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L11_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":392 + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + * except TypeError: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":393 + * self.dtype_is_object) + * except TypeError: + * return None # <<<<<<<<<<<<<< + * + * return obj + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L7_except_return; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L5_exception_handled; + } + __pyx_L6_except_error:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L1_error; + __pyx_L7_except_return:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L0; + __pyx_L5_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + __pyx_L11_try_end:; + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":395 + * return None + * + * return obj # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assignment(self, dst, src): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_obj); + __pyx_r = __pyx_v_obj; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":397 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { + __Pyx_memviewslice __pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_src_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); + + /* "View.MemoryView":401 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":402 + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< + * src.ndim, dst.ndim, self.dtype_is_object) + * + */ + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":403 + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s__ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s__ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":405 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { + int __pyx_v_array[128]; + void *__pyx_v_tmp; + void *__pyx_v_item; + __Pyx_memviewslice __pyx_v_tmp_slice; + __Pyx_memviewslice *__pyx_v_dst_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); + + /* "View.MemoryView":407 + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + * cdef int array[128] + * cdef void *tmp = NULL # <<<<<<<<<<<<<< + * cdef void *item + * + */ + __pyx_v_tmp = NULL; + + /* "View.MemoryView":411 + * + * cdef __Pyx_memviewslice tmp_slice, *dst_slice + * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< + * + * if self.view.itemsize > sizeof(array): + */ + __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); + + /* "View.MemoryView":413 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: + */ + __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":414 + * + * if self.view.itemsize > sizeof(array): + * tmp = malloc(self.view.itemsize) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError + */ + __pyx_v_tmp = malloc(__pyx_v_self->view.itemsize); + + /* "View.MemoryView":415 + * if self.view.itemsize > sizeof(array): + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":416 + * tmp = malloc(self.view.itemsize) + * if tmp == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * item = tmp + * else: + */ + PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":417 + * if tmp == NULL: + * raise MemoryError + * item = tmp # <<<<<<<<<<<<<< + * else: + * item = array + */ + __pyx_v_item = __pyx_v_tmp; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":419 + * item = tmp + * else: + * item = array # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_v_item = ((void *)__pyx_v_array); + } + __pyx_L3:; + + /* "View.MemoryView":421 + * item = array + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":422 + * + * if self.dtype_is_object: + * ( item)[0] = value # <<<<<<<<<<<<<< + * else: + * try: + */ + (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":424 + * ( item)[0] = value + * else: + * try: # <<<<<<<<<<<<<< + * self.assign_item_from_object( item, value) + * except: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":425 + * else: + * try: + * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< + * except: + * free(tmp) + */ + __pyx_t_5 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L13_try_end; + __pyx_L6_error:; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":426 + * try: + * self.assign_item_from_object( item, value) + * except: # <<<<<<<<<<<<<< + * free(tmp) + * raise + */ + /*except:*/ { + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 426; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":427 + * self.assign_item_from_object( item, value) + * except: + * free(tmp) # <<<<<<<<<<<<<< + * raise + * + */ + free(__pyx_v_tmp); + + /* "View.MemoryView":428 + * except: + * free(tmp) + * raise # <<<<<<<<<<<<<< + * + * + */ + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_7); + __Pyx_ErrRestore(__pyx_t_5, __pyx_t_6, __pyx_t_7); + __pyx_t_5 = 0; __pyx_t_6 = 0; __pyx_t_7 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 428; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L7_exception_handled; + } + __pyx_L8_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L7_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L13_try_end:; + } + } + __pyx_L5:; + + /* "View.MemoryView":432 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":433 + * + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + */ + __pyx_t_7 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":435 + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) # <<<<<<<<<<<<<< + * free(tmp) + * + */ + __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); + + /* "View.MemoryView":436 + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + * free(tmp) # <<<<<<<<<<<<<< + * + * cdef setitem_indexed(self, index, value): + */ + free(__pyx_v_tmp); + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":438 + * free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_indexed", 0); + + /* "View.MemoryView":439 + * + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< + * self.assign_item_from_object(itemp, value) + * + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_itemp = __pyx_t_1; + + /* "View.MemoryView":440 + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":442 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_v_struct = NULL; + PyObject *__pyx_v_bytesitem = 0; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":445 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef bytes bytesitem + * + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__struct), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":448 + * cdef bytes bytesitem + * + * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< + * try: + * result = struct.unpack(self.view.format, bytesitem) + */ + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":449 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + { + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":450 + * bytesitem = itemp[:self.view.itemsize] + * try: + * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< + * except struct.error: + * raise ValueError("Unable to convert item to object") + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__unpack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __Pyx_INCREF(((PyObject *)__pyx_v_bytesitem)); + PyTuple_SET_ITEM(__pyx_t_6, 1, ((PyObject *)__pyx_v_bytesitem)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_bytesitem)); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + __pyx_v_result = __pyx_t_5; + __pyx_t_5 = 0; + } + /*else:*/ { + + /* "View.MemoryView":454 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + __pyx_t_7 = strlen(__pyx_v_self->view.format); + __pyx_t_8 = ((__pyx_t_7 == 1) != 0); + if (__pyx_t_8) { + + /* "View.MemoryView":455 + * else: + * if len(self.view.format) == 1: + * return result[0] # <<<<<<<<<<<<<< + * return result + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_result, 0, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_5) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L6_except_return; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":456 + * if len(self.view.format) == 1: + * return result[0] + * return result # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L6_except_return; + } + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L10_try_end; + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "View.MemoryView":451 + * try: + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: # <<<<<<<<<<<<<< + * raise ValueError("Unable to convert item to object") + * else: + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__error); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_9 = PyErr_ExceptionMatches(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_1); + + /* "View.MemoryView":452 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_t_10 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_29), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L4_exception_handled; + } + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L6_except_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + __pyx_L4_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + __pyx_L10_try_end:; + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesitem); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":458 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_v_struct = NULL; + char __pyx_v_c; + PyObject *__pyx_v_bytesvalue = 0; + Py_ssize_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + char *__pyx_t_10; + char *__pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":461 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef char c + * cdef bytes bytesvalue + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__struct), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":466 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + __pyx_t_2 = PyTuple_Check(__pyx_v_value); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":467 + * + * if isinstance(value, tuple): + * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< + * else: + * bytesvalue = struct.pack(self.view.format, value) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = 0; + __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_6 = PyNumber_Add(((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":469 + * bytesvalue = struct.pack(self.view.format, *value) + * else: + * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< + * + * for i, c in enumerate(bytesvalue): + */ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s__pack); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_6)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_6)); + __Pyx_INCREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + __pyx_t_6 = 0; + __pyx_t_6 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_6)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":471 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = 0; + if (unlikely(((PyObject *)__pyx_v_bytesvalue) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_INCREF(((PyObject *)__pyx_v_bytesvalue)); + __pyx_t_8 = __pyx_v_bytesvalue; + __pyx_t_10 = PyBytes_AS_STRING(__pyx_t_8); + __pyx_t_11 = (__pyx_t_10 + PyBytes_GET_SIZE(__pyx_t_8)); + for (__pyx_t_12 = __pyx_t_10; __pyx_t_12 < __pyx_t_11; __pyx_t_12++) { + __pyx_t_9 = __pyx_t_12; + __pyx_v_c = (__pyx_t_9[0]); + + /* "View.MemoryView":472 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + __pyx_v_i = __pyx_t_7; + + /* "View.MemoryView":471 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_7 = (__pyx_t_7 + 1); + + /* "View.MemoryView":472 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; + } + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(((PyObject *)__pyx_t_8)); + __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":475 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape + */ + +static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + char *__pyx_t_3; + void *__pyx_t_4; + int __pyx_t_5; + Py_ssize_t __pyx_t_6; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "View.MemoryView":476 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":477 + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: + * info.shape = self.view.shape # <<<<<<<<<<<<<< + * else: + * info.shape = NULL + */ + __pyx_t_2 = __pyx_v_self->view.shape; + __pyx_v_info->shape = __pyx_t_2; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":479 + * info.shape = self.view.shape + * else: + * info.shape = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_STRIDES: + */ + __pyx_v_info->shape = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":481 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":482 + * + * if flags & PyBUF_STRIDES: + * info.strides = self.view.strides # <<<<<<<<<<<<<< + * else: + * info.strides = NULL + */ + __pyx_t_2 = __pyx_v_self->view.strides; + __pyx_v_info->strides = __pyx_t_2; + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":484 + * info.strides = self.view.strides + * else: + * info.strides = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_INDIRECT: + */ + __pyx_v_info->strides = NULL; + } + __pyx_L4:; + + /* "View.MemoryView":486 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":487 + * + * if flags & PyBUF_INDIRECT: + * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< + * else: + * info.suboffsets = NULL + */ + __pyx_t_2 = __pyx_v_self->view.suboffsets; + __pyx_v_info->suboffsets = __pyx_t_2; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":489 + * info.suboffsets = self.view.suboffsets + * else: + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->suboffsets = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":491 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":492 + * + * if flags & PyBUF_FORMAT: + * info.format = self.view.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_3 = __pyx_v_self->view.format; + __pyx_v_info->format = __pyx_t_3; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":494 + * info.format = self.view.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.buf = self.view.buf + */ + __pyx_v_info->format = NULL; + } + __pyx_L6:; + + /* "View.MemoryView":496 + * info.format = NULL + * + * info.buf = self.view.buf # <<<<<<<<<<<<<< + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + */ + __pyx_t_4 = __pyx_v_self->view.buf; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":497 + * + * info.buf = self.view.buf + * info.ndim = self.view.ndim # <<<<<<<<<<<<<< + * info.itemsize = self.view.itemsize + * info.len = self.view.len + */ + __pyx_t_5 = __pyx_v_self->view.ndim; + __pyx_v_info->ndim = __pyx_t_5; + + /* "View.MemoryView":498 + * info.buf = self.view.buf + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< + * info.len = self.view.len + * info.readonly = 0 + */ + __pyx_t_6 = __pyx_v_self->view.itemsize; + __pyx_v_info->itemsize = __pyx_t_6; + + /* "View.MemoryView":499 + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + * info.len = self.view.len # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.obj = self + */ + __pyx_t_6 = __pyx_v_self->view.len; + __pyx_v_info->len = __pyx_t_6; + + /* "View.MemoryView":500 + * info.itemsize = self.view.itemsize + * info.len = self.view.len + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.obj = self + * + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":501 + * info.len = self.view.len + * info.readonly = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + __pyx_r = 0; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":508 + * property T: + * @cname('__pyx_memoryview_transpose') + * def __get__(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + +static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":509 + * @cname('__pyx_memoryview_transpose') + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< + * transpose_memslice(&result.from_slice) + * return result + */ + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":510 + * def __get__(self): + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":511 + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + * return result # <<<<<<<<<<<<<< + * + * property base: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":515 + * property base: + * @cname('__pyx_memoryview__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + +static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":516 + * @cname('__pyx_memoryview__get__base') + * def __get__(self): + * return self.obj # <<<<<<<<<<<<<< + * + * property shape: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->obj); + __pyx_r = __pyx_v_self->obj; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":520 + * property shape: + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): # <<<<<<<<<<<<<< + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + * + */ + +static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":521 + * @cname('__pyx_memoryview_get_shape') + * def __get__(self): + * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property strides: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_v_self->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->view.shape[__pyx_v_i])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __pyx_t_4 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_1))); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_r = ((PyObject *)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":525 + * property strides: + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + +static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":526 + * @cname('__pyx_memoryview_get_strides') + * def __get__(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":528 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_31), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":530 + * raise ValueError("Buffer view does not expose strides") + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property suboffsets: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.strides[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_2))); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_5); + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":534 + * property suboffsets: + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim + */ + +static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":535 + * @cname('__pyx_memoryview_get_suboffsets') + * def __get__(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return [-1] * self.view.ndim + * + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":536 + * def __get__(self): + * if self.view.suboffsets == NULL: + * return [-1] * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(1 * ((__pyx_v_self->view.ndim<0) ? 0:__pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_self->view.ndim; __pyx_temp++) { + __Pyx_INCREF(__pyx_int_neg_1); + PyList_SET_ITEM(__pyx_t_2, __pyx_temp, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + } + } + __pyx_r = ((PyObject *)__pyx_t_2); + __pyx_t_2 = 0; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":538 + * return [-1] * self.view.ndim + * + * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * + * property ndim: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __pyx_v_self->view.ndim; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.suboffsets[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = ((PyObject *)PyList_AsTuple(((PyObject*)__pyx_t_2))); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_5); + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":542 + * property ndim: + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + +static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":543 + * @cname('__pyx_memoryview_get_ndim') + * def __get__(self): + * return self.view.ndim # <<<<<<<<<<<<<< + * + * property itemsize: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromLong(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":547 + * property itemsize: + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + +static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":548 + * @cname('__pyx_memoryview_get_itemsize') + * def __get__(self): + * return self.view.itemsize # <<<<<<<<<<<<<< + * + * property nbytes: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":552 + * property nbytes: + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + +static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":553 + * @cname('__pyx_memoryview_get_nbytes') + * def __get__(self): + * return self.size * self.view.itemsize # <<<<<<<<<<<<<< + * + * property size: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":557 + * property size: + * @cname('__pyx_memoryview_get_size') + * def __get__(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + +static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":558 + * @cname('__pyx_memoryview_get_size') + * def __get__(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + __pyx_t_1 = (__pyx_v_self->_size == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":559 + * def __get__(self): + * if self._size is None: + * result = 1 # <<<<<<<<<<<<<< + * + * for length in self.shape: + */ + __Pyx_INCREF(__pyx_int_1); + __pyx_v_result = __pyx_int_1; + + /* "View.MemoryView":561 + * result = 1 + * + * for length in self.shape: # <<<<<<<<<<<<<< + * result *= length + * + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyList_CheckExact(__pyx_t_3) || PyTuple_CheckExact(__pyx_t_3)) { + __pyx_t_4 = __pyx_t_3; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_3 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_3)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF(__pyx_v_length); + __pyx_v_length = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":562 + * + * for length in self.shape: + * result *= length # <<<<<<<<<<<<<< + * + * self._size = result + */ + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_result); + __pyx_v_result = __pyx_t_3; + __pyx_t_3 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "View.MemoryView":564 + * result *= length + * + * self._size = result # <<<<<<<<<<<<<< + * + * return self._size + */ + __Pyx_INCREF(__pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __Pyx_GOTREF(__pyx_v_self->_size); + __Pyx_DECREF(__pyx_v_self->_size); + __pyx_v_self->_size = __pyx_v_result; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":566 + * self._size = result + * + * return self._size # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->_size); + __pyx_r = __pyx_v_self->_size; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":568 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + +static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__len__", 0); + + /* "View.MemoryView":569 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":570 + * def __len__(self): + * if self.view.ndim >= 1: + * return self.view.shape[0] # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_r = (__pyx_v_self->view.shape[0]); + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":572 + * return self.view.shape[0] + * + * return 0 # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":574 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":575 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s____class__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s____name__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":576 + * def __repr__(self): + * return "" % (self.base.__class__.__name__, + * id(self)) # <<<<<<<<<<<<<< + * + * def __str__(self): + */ + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __pyx_t_3 = PyObject_Call(__pyx_builtin_id, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_32), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":578 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__str__", 0); + + /* "View.MemoryView":579 + * + * def __str__(self): + * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s____class__); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s____name__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_33), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":582 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_c_contig", 0); + + /* "View.MemoryView":584 + * def is_c_contig(self): + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":585 + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< + * + * def is_f_contig(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":587 + * return slice_is_contig(mslice, 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_f_contig", 0); + + /* "View.MemoryView":589 + * def is_f_contig(self): + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + */ + __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); + + /* "View.MemoryView":590 + * cdef __Pyx_memviewslice *mslice, tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< + * + * def copy(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":592 + * return slice_is_contig(mslice, 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_mslice; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "View.MemoryView":594 + * def copy(self): + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &mslice) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); + + /* "View.MemoryView":596 + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + * + * slice_copy(self, &mslice) # <<<<<<<<<<<<<< + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); + + /* "View.MemoryView":600 + * self.view.itemsize, + * flags|PyBUF_C_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * + * return memoryview_copy_from_slice(self, &mslice) + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k__c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":602 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< + * + * def copy_fortran(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); + __pyx_r = __pyx_memoryview_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":604 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + +static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy_fortran", 0); + + /* "View.MemoryView":606 + * def copy_fortran(self): + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &src) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); + + /* "View.MemoryView":608 + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + * + * slice_copy(self, &src) # <<<<<<<<<<<<<< + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); + + /* "View.MemoryView":612 + * self.view.itemsize, + * flags|PyBUF_F_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * + * return memoryview_copy_from_slice(self, &dst) + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k__fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_dst = __pyx_t_1; + + /* "View.MemoryView":614 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":618 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + +static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { + struct __pyx_memoryview_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); + + /* "View.MemoryView":619 + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< + * result.typeinfo = typeinfo + * return result + */ + __pyx_t_1 = PyInt_FromLong(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); + __Pyx_GIVEREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":620 + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_v_result->typeinfo = __pyx_v_typeinfo; + + /* "View.MemoryView":621 + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_check') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":624 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("memoryview_check", 0); + + /* "View.MemoryView":625 + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): + * return isinstance(o, memoryview) # <<<<<<<<<<<<<< + * + * cdef tuple _unellipsify(object index, int ndim): + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type)); + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":627 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + +static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { + PyObject *__pyx_v_tup = NULL; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_have_slices = NULL; + int __pyx_v_seen_ellipsis; + CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_item = NULL; + PyObject *__pyx_v_nslices = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + Py_ssize_t __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_unellipsify", 0); + + /* "View.MemoryView":632 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + __pyx_t_1 = PyTuple_Check(__pyx_v_index); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":633 + * """ + * if not isinstance(index, tuple): + * tup = (index,) # <<<<<<<<<<<<<< + * else: + * tup = index + */ + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 633; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_index); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); + __Pyx_GIVEREF(__pyx_v_index); + __pyx_v_tup = ((PyObject *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":635 + * tup = (index,) + * else: + * tup = index # <<<<<<<<<<<<<< + * + * result = [] + */ + __Pyx_INCREF(__pyx_v_index); + __pyx_v_tup = __pyx_v_index; + } + __pyx_L3:; + + /* "View.MemoryView":637 + * tup = index + * + * result = [] # <<<<<<<<<<<<<< + * have_slices = False + * seen_ellipsis = False + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_result = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":638 + * + * result = [] + * have_slices = False # <<<<<<<<<<<<<< + * seen_ellipsis = False + * for idx, item in enumerate(tup): + */ + __pyx_t_3 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_have_slices = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":639 + * result = [] + * have_slices = False + * seen_ellipsis = False # <<<<<<<<<<<<<< + * for idx, item in enumerate(tup): + * if item is Ellipsis: + */ + __pyx_v_seen_ellipsis = 0; + + /* "View.MemoryView":640 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_3 = __pyx_int_0; + if (PyList_CheckExact(__pyx_v_tup) || PyTuple_CheckExact(__pyx_v_tup)) { + __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; + } + for (;;) { + if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_7 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_7)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_XDECREF(__pyx_v_item); + __pyx_v_item = __pyx_t_7; + __pyx_t_7 = 0; + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_v_idx); + __pyx_v_idx = __pyx_t_3; + __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_t_7; + __pyx_t_7 = 0; + + /* "View.MemoryView":641 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ + __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":642 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ + __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":643 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_result), __pyx_n_s__extend); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_34), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_9) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_9) + 1))); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_9) + 1); __pyx_temp++) { + __Pyx_INCREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_10, __pyx_temp, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + } + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_10)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_10)); + __pyx_t_10 = 0; + __pyx_t_10 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + + /* "View.MemoryView":644 + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True # <<<<<<<<<<<<<< + * else: + * result.append(slice(None)) + */ + __pyx_v_seen_ellipsis = 1; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":646 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_t_10 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_35), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_result, __pyx_t_10); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + } + __pyx_L7:; + + /* "View.MemoryView":647 + * else: + * result.append(slice(None)) + * have_slices = True # <<<<<<<<<<<<<< + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + */ + __pyx_t_10 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_v_have_slices); + __pyx_v_have_slices = __pyx_t_10; + __pyx_t_10 = 0; + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":649 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ + __pyx_t_1 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_1 = ((!(__Pyx_PyIndex_Check(__pyx_v_item) != 0)) != 0); + __pyx_t_12 = __pyx_t_1; + } else { + __pyx_t_12 = __pyx_t_2; + } + if (__pyx_t_12) { + + /* "View.MemoryView":650 + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< + * + * have_slices = have_slices or isinstance(item, slice) + */ + __pyx_t_10 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_36), ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_10)); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_10)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_10)); + __pyx_t_10 = 0; + __pyx_t_10 = PyObject_Call(__pyx_builtin_TypeError, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":652 + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< + * result.append(item) + * + */ + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_12) { + __pyx_t_12 = PySlice_Check(__pyx_v_item); + __pyx_t_10 = __Pyx_PyBool_FromLong(__pyx_t_12); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_8 = __pyx_t_10; + __pyx_t_10 = 0; + } else { + __Pyx_INCREF(__pyx_v_have_slices); + __pyx_t_8 = __pyx_v_have_slices; + } + __Pyx_DECREF(__pyx_v_have_slices); + __pyx_v_have_slices = __pyx_t_8; + __pyx_t_8 = 0; + + /* "View.MemoryView":653 + * + * have_slices = have_slices or isinstance(item, slice) + * result.append(item) # <<<<<<<<<<<<<< + * + * nslices = ndim - len(result) + */ + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":655 + * result.append(item) + * + * nslices = ndim - len(result) # <<<<<<<<<<<<<< + * if nslices: + * result.extend([slice(None)] * nslices) + */ + __pyx_t_5 = PyList_GET_SIZE(((PyObject *)__pyx_v_result)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromSsize_t((__pyx_v_ndim - __pyx_t_5)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_nslices = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":656 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_nslices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_12) { + + /* "View.MemoryView":657 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_result), __pyx_n_s__extend); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), ((PyObject *)__pyx_k_tuple_37), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyList_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + PyList_SET_ITEM(__pyx_t_8, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + { PyObject* __pyx_temp = PyNumber_InPlaceMultiply(__pyx_t_8, __pyx_v_nslices); if (unlikely(!__pyx_temp)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_temp); + __Pyx_DECREF(__pyx_t_8); + __pyx_t_8 = __pyx_temp; + } + __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":659 + * result.extend([slice(None)] * nslices) + * + * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_12 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_12) { + __Pyx_INCREF(__pyx_v_nslices); + __pyx_t_8 = __pyx_v_nslices; + } else { + __Pyx_INCREF(__pyx_v_have_slices); + __pyx_t_8 = __pyx_v_have_slices; + } + __pyx_t_4 = ((PyObject *)PyList_AsTuple(__pyx_v_result)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_8 = 0; + __pyx_t_4 = 0; + __pyx_r = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = ((PyObject*)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_tup); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_item); + __Pyx_XDECREF(__pyx_v_nslices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":661 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * cdef int i + * for i in range(ndim): + */ + +static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); + + /* "View.MemoryView":663 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * cdef int i + * for i in range(ndim): # <<<<<<<<<<<<<< + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":664 + * cdef int i + * for i in range(ndim): + * if suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ + __pyx_t_3 = (((__pyx_v_suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":665 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_39), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":672 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { + int __pyx_v_new_ndim; + int __pyx_v_suboffset_dim; + int __pyx_v_dim; + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + __Pyx_memviewslice *__pyx_v_p_src; + struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; + __Pyx_memviewslice *__pyx_v_p_dst; + int *__pyx_v_p_suboffset_dim; + Py_ssize_t __pyx_v_start; + Py_ssize_t __pyx_v_stop; + Py_ssize_t __pyx_v_step; + int __pyx_v_have_start; + int __pyx_v_have_stop; + int __pyx_v_have_step; + PyObject *__pyx_v_index = NULL; + struct __pyx_memoryview_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + struct __pyx_memoryview_obj *__pyx_t_3; + char *__pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + PyObject *__pyx_t_12 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memview_slice", 0); + + /* "View.MemoryView":673 + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): + * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< + * cdef bint negative_step + * cdef __Pyx_memviewslice src, dst + */ + __pyx_v_new_ndim = 0; + __pyx_v_suboffset_dim = -1; + + /* "View.MemoryView":680 + * + * + * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< + * + * cdef _memoryviewslice memviewsliceobj + */ + memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); + + /* "View.MemoryView":684 + * cdef _memoryviewslice memviewsliceobj + * + * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 684; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #endif + + /* "View.MemoryView":686 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":687 + * + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview # <<<<<<<<<<<<<< + * p_src = &memviewsliceobj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(((PyObject *)__pyx_v_memview)); + __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview); + + /* "View.MemoryView":688 + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, &src) + */ + __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":690 + * p_src = &memviewsliceobj.from_slice + * else: + * slice_copy(memview, &src) # <<<<<<<<<<<<<< + * p_src = &src + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); + + /* "View.MemoryView":691 + * else: + * slice_copy(memview, &src) + * p_src = &src # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_src = (&__pyx_v_src); + } + __pyx_L3:; + + /* "View.MemoryView":697 + * + * + * dst.memview = p_src.memview # <<<<<<<<<<<<<< + * dst.data = p_src.data + * + */ + __pyx_t_3 = __pyx_v_p_src->memview; + __pyx_v_dst.memview = __pyx_t_3; + + /* "View.MemoryView":698 + * + * dst.memview = p_src.memview + * dst.data = p_src.data # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = __pyx_v_p_src->data; + __pyx_v_dst.data = __pyx_t_4; + + /* "View.MemoryView":703 + * + * + * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< + * cdef int *p_suboffset_dim = &suboffset_dim + * cdef Py_ssize_t start, stop, step + */ + __pyx_v_p_dst = (&__pyx_v_dst); + + /* "View.MemoryView":704 + * + * cdef __Pyx_memviewslice *p_dst = &dst + * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< + * cdef Py_ssize_t start, stop, step + * cdef bint have_start, have_stop, have_step + */ + __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); + + /* "View.MemoryView":708 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + __pyx_t_5 = 0; + if (PyList_CheckExact(__pyx_v_indices) || PyTuple_CheckExact(__pyx_v_indices)) { + __pyx_t_6 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_6); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = Py_TYPE(__pyx_t_6)->tp_iternext; + } + for (;;) { + if (!__pyx_t_8 && PyList_CheckExact(__pyx_t_6)) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_6)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_6, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_6, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (!__pyx_t_8 && PyTuple_CheckExact(__pyx_t_6)) { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_6)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_6, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else { + __pyx_t_9 = __pyx_t_8(__pyx_t_6); + if (unlikely(!__pyx_t_9)) { + if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear(); + else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + break; + } + __Pyx_GOTREF(__pyx_t_9); + } + __Pyx_XDECREF(__pyx_v_index); + __pyx_v_index = __pyx_t_9; + __pyx_t_9 = 0; + __pyx_v_dim = __pyx_t_5; + __pyx_t_5 = (__pyx_t_5 + 1); + + /* "View.MemoryView":709 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ + __pyx_t_2 = (__Pyx_PyIndex_Check(__pyx_v_index) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":713 + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< + * 0, 0, 0, # have_{start,stop,step} + * False) + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":715 + * index, 0, 0, # start, stop, step + * 0, 0, 0, # have_{start,stop,step} + * False) # <<<<<<<<<<<<<< + * elif index is None: + * p_dst.shape[new_ndim] = 1 + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 710; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + + /* "View.MemoryView":716 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ + __pyx_t_2 = (__pyx_v_index == Py_None); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":717 + * False) + * elif index is None: + * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + */ + (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; + + /* "View.MemoryView":718 + * elif index is None: + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 + */ + (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; + + /* "View.MemoryView":719 + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< + * new_ndim += 1 + * else: + */ + (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1; + + /* "View.MemoryView":720 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 # <<<<<<<<<<<<<< + * else: + * start = index.start or 0 + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":722 + * new_ndim += 1 + * else: + * start = index.start or 0 # <<<<<<<<<<<<<< + * stop = index.stop or 0 + * step = index.step or 0 + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_start = __pyx_t_10; + + /* "View.MemoryView":723 + * else: + * start = index.start or 0 + * stop = index.stop or 0 # <<<<<<<<<<<<<< + * step = index.step or 0 + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_12); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_9 = __pyx_int_0; + } else { + __pyx_t_9 = __pyx_t_12; + __pyx_t_12 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_stop = __pyx_t_10; + + /* "View.MemoryView":724 + * start = index.start or 0 + * stop = index.stop or 0 + * step = index.step or 0 # <<<<<<<<<<<<<< + * + * have_start = index.start is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_INCREF(__pyx_int_0); + __pyx_t_12 = __pyx_int_0; + } else { + __pyx_t_12 = __pyx_t_9; + __pyx_t_9 = 0; + } + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_step = __pyx_t_10; + + /* "View.MemoryView":726 + * step = index.step or 0 + * + * have_start = index.start is not None # <<<<<<<<<<<<<< + * have_stop = index.stop is not None + * have_step = index.step is not None + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__start); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 726; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_start = __pyx_t_1; + + /* "View.MemoryView":727 + * + * have_start = index.start is not None + * have_stop = index.stop is not None # <<<<<<<<<<<<<< + * have_step = index.step is not None + * + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 727; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_stop = __pyx_t_1; + + /* "View.MemoryView":728 + * have_start = index.start is not None + * have_stop = index.stop is not None + * have_step = index.step is not None # <<<<<<<<<<<<<< + * + * slice_memviewslice( + */ + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s__step); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_1 = (__pyx_t_12 != Py_None); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_have_step = __pyx_t_1; + + /* "View.MemoryView":735 + * start, stop, step, + * have_start, have_stop, have_step, + * True) # <<<<<<<<<<<<<< + * new_ndim += 1 + * + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 730; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":736 + * have_start, have_stop, have_step, + * True) + * new_ndim += 1 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + } + __pyx_L6:; + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "View.MemoryView":738 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":739 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":740 + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 740; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + + /* "View.MemoryView":742 + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + */ + __pyx_t_6 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_6); + __pyx_t_6 = 0; + goto __pyx_L0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":744 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":745 + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_6 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 744; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 744; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_6); + __pyx_t_6 = 0; + goto __pyx_L0; + } + __pyx_L7:; + + __pyx_r = ((struct __pyx_memoryview_obj *)Py_None); __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":769 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { + Py_ssize_t __pyx_v_new_shape; + int __pyx_v_negative_step; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":789 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":791 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + __pyx_t_1 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":792 + * + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + goto __pyx_L4; + } + __pyx_L4:; + + /* "View.MemoryView":793 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + __pyx_t_1 = (0 <= __pyx_v_start); + if (__pyx_t_1) { + __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); + } + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":794 + * start += shape + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< + * else: + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_40, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":797 + * else: + * + * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< + * + * if have_step and step == 0: + */ + __pyx_t_2 = (__pyx_v_have_step != 0); + if (__pyx_t_2) { + __pyx_t_1 = (__pyx_v_step < 0); + __pyx_t_4 = __pyx_t_1; + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_v_negative_step = __pyx_t_4; + + /* "View.MemoryView":799 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + if ((__pyx_v_have_step != 0)) { + __pyx_t_4 = (__pyx_v_step == 0); + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = (__pyx_v_have_step != 0); + } + if (__pyx_t_2) { + + /* "View.MemoryView":800 + * + * if have_step and step == 0: + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_41, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":803 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + __pyx_t_2 = (__pyx_v_have_start != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":804 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":805 + * if have_start: + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if start < 0: + * start = 0 + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":806 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":807 + * start += shape + * if start < 0: + * start = 0 # <<<<<<<<<<<<<< + * elif start >= shape: + * if negative_step: + */ + __pyx_v_start = 0; + goto __pyx_L9; + } + __pyx_L9:; + goto __pyx_L8; + } + + /* "View.MemoryView":808 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":809 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":810 + * elif start >= shape: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = shape + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L10; + } + /*else*/ { + + /* "View.MemoryView":812 + * start = shape - 1 + * else: + * start = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_start = __pyx_v_shape; + } + __pyx_L10:; + goto __pyx_L8; + } + __pyx_L8:; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":814 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":815 + * else: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = 0 + */ + __pyx_v_start = (__pyx_v_shape - 1); + goto __pyx_L11; + } + /*else*/ { + + /* "View.MemoryView":817 + * start = shape - 1 + * else: + * start = 0 # <<<<<<<<<<<<<< + * + * if have_stop: + */ + __pyx_v_start = 0; + } + __pyx_L11:; + } + __pyx_L7:; + + /* "View.MemoryView":819 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + __pyx_t_2 = (__pyx_v_have_stop != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":820 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":821 + * if have_stop: + * if stop < 0: + * stop += shape # <<<<<<<<<<<<<< + * if stop < 0: + * stop = 0 + */ + __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); + + /* "View.MemoryView":822 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":823 + * stop += shape + * if stop < 0: + * stop = 0 # <<<<<<<<<<<<<< + * elif stop > shape: + * stop = shape + */ + __pyx_v_stop = 0; + goto __pyx_L14; + } + __pyx_L14:; + goto __pyx_L13; + } + + /* "View.MemoryView":824 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":825 + * stop = 0 + * elif stop > shape: + * stop = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_stop = __pyx_v_shape; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L12; + } + /*else*/ { + + /* "View.MemoryView":827 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":828 + * else: + * if negative_step: + * stop = -1 # <<<<<<<<<<<<<< + * else: + * stop = shape + */ + __pyx_v_stop = -1; + goto __pyx_L15; + } + /*else*/ { + + /* "View.MemoryView":830 + * stop = -1 + * else: + * stop = shape # <<<<<<<<<<<<<< + * + * if not have_step: + */ + __pyx_v_stop = __pyx_v_shape; + } + __pyx_L15:; + } + __pyx_L12:; + + /* "View.MemoryView":832 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":833 + * + * if not have_step: + * step = 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_step = 1; + goto __pyx_L16; + } + __pyx_L16:; + + /* "View.MemoryView":837 + * + * with cython.cdivision(True): + * new_shape = (stop - start) // step # <<<<<<<<<<<<<< + * + * if (stop - start) - step * new_shape: + */ + __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); + + /* "View.MemoryView":839 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":840 + * + * if (stop - start) - step * new_shape: + * new_shape += 1 # <<<<<<<<<<<<<< + * + * if new_shape < 0: + */ + __pyx_v_new_shape = (__pyx_v_new_shape + 1); + goto __pyx_L17; + } + __pyx_L17:; + + /* "View.MemoryView":842 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":843 + * + * if new_shape < 0: + * new_shape = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_new_shape = 0; + goto __pyx_L18; + } + __pyx_L18:; + + /* "View.MemoryView":846 + * + * + * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset + */ + (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); + + /* "View.MemoryView":847 + * + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< + * dst.suboffsets[new_ndim] = suboffset + * + */ + (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; + + /* "View.MemoryView":848 + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; + } + __pyx_L3:; + + /* "View.MemoryView":851 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":852 + * + * if suboffset_dim[0] < 0: + * dst.data += start * stride # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride + */ + __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); + goto __pyx_L19; + } + /*else*/ { + + /* "View.MemoryView":854 + * dst.data += start * stride + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< + * + * if suboffset >= 0: + */ + __pyx_t_3 = (__pyx_v_suboffset_dim[0]); + (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); + } + __pyx_L19:; + + /* "View.MemoryView":856 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":857 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":858 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":859 + * if not is_slice: + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + */ + __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); + goto __pyx_L22; + } + /*else*/ { + + /* "View.MemoryView":862 + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< + * else: + * suboffset_dim[0] = new_ndim + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_42, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L22:; + goto __pyx_L21; + } + /*else*/ { + + /* "View.MemoryView":864 + * "must be indexed and not sliced", dim) + * else: + * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< + * + * return 0 + */ + (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; + } + __pyx_L21:; + goto __pyx_L20; + } + __pyx_L20:; + + /* "View.MemoryView":866 + * suboffset_dim[0] = new_ndim + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":872 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + +static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, int __pyx_v_dim) { + Py_ssize_t __pyx_v_shape; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_suboffset; + Py_ssize_t __pyx_v_itemsize; + char *__pyx_v_resultp; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pybuffer_index", 0); + + /* "View.MemoryView":874 + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< + * cdef Py_ssize_t itemsize = view.itemsize + * cdef char *resultp + */ + __pyx_v_suboffset = -1; + + /* "View.MemoryView":875 + * int dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< + * cdef char *resultp + * + */ + __pyx_t_1 = __pyx_v_view->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":878 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":879 + * + * if view.ndim == 0: + * shape = view.len / itemsize # <<<<<<<<<<<<<< + * stride = itemsize + * else: + */ + if (unlikely(__pyx_v_itemsize == 0)) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 879; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + PyErr_Format(PyExc_OverflowError, "value too large to perform division"); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 879; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); + + /* "View.MemoryView":880 + * if view.ndim == 0: + * shape = view.len / itemsize + * stride = itemsize # <<<<<<<<<<<<<< + * else: + * shape = view.shape[dim] + */ + __pyx_v_stride = __pyx_v_itemsize; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":882 + * stride = itemsize + * else: + * shape = view.shape[dim] # <<<<<<<<<<<<<< + * stride = view.strides[dim] + * if view.suboffsets != NULL: + */ + __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); + + /* "View.MemoryView":883 + * else: + * shape = view.shape[dim] + * stride = view.strides[dim] # <<<<<<<<<<<<<< + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] + */ + __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); + + /* "View.MemoryView":884 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":885 + * stride = view.strides[dim] + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< + * + * if index < 0: + */ + __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); + goto __pyx_L4; + } + __pyx_L4:; + } + __pyx_L3:; + + /* "View.MemoryView":887 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":888 + * + * if index < 0: + * index += view.shape[dim] # <<<<<<<<<<<<<< + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + */ + __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); + + /* "View.MemoryView":889 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":890 + * index += view.shape[dim] + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * if index >= shape: + */ + __pyx_t_3 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_43), __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_builtin_IndexError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 890; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + goto __pyx_L5; + } + __pyx_L5:; + + /* "View.MemoryView":892 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":893 + * + * if index >= shape: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * resultp = bufp + index * stride + */ + __pyx_t_4 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_43), __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_IndexError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + + /* "View.MemoryView":895 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * resultp = bufp + index * stride # <<<<<<<<<<<<<< + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset + */ + __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); + + /* "View.MemoryView":896 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":897 + * resultp = bufp + index * stride + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< + * + * return resultp + */ + __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); + goto __pyx_L8; + } + __pyx_L8:; + + /* "View.MemoryView":899 + * resultp = ( resultp)[0] + suboffset + * + * return resultp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_resultp; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":905 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + +static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { + int __pyx_v_ndim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + int __pyx_v_i; + int __pyx_v_j; + int __pyx_r; + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + long __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":906 + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: + * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< + * + * cdef Py_ssize_t *shape = memslice.shape + */ + __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; + __pyx_v_ndim = __pyx_t_1; + + /* "View.MemoryView":908 + * cdef int ndim = memslice.memview.view.ndim + * + * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< + * cdef Py_ssize_t *strides = memslice.strides + * + */ + __pyx_t_2 = __pyx_v_memslice->shape; + __pyx_v_shape = __pyx_t_2; + + /* "View.MemoryView":909 + * + * cdef Py_ssize_t *shape = memslice.shape + * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_v_memslice->strides; + __pyx_v_strides = __pyx_t_2; + + /* "View.MemoryView":913 + * + * cdef int i, j + * for i in range(ndim / 2): # <<<<<<<<<<<<<< + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + */ + __pyx_t_3 = __Pyx_div_long(__pyx_v_ndim, 2); + for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":914 + * cdef int i, j + * for i in range(ndim / 2): + * j = ndim - 1 - i # <<<<<<<<<<<<<< + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] + */ + __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); + + /* "View.MemoryView":915 + * for i in range(ndim / 2): + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< + * shape[i], shape[j] = shape[j], shape[i] + * + */ + __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); + __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); + (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; + (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; + + /* "View.MemoryView":916 + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + */ + __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); + __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); + (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; + (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; + + /* "View.MemoryView":918 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + __pyx_t_6 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); + if (!__pyx_t_6) { + __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); + __pyx_t_8 = __pyx_t_7; + } else { + __pyx_t_8 = __pyx_t_6; + } + if (__pyx_t_8) { + + /* "View.MemoryView":919 + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< + * + * return 1 + */ + __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_44); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 919; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "View.MemoryView":921 + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + * return 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 1; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":938 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + +static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":939 + * + * def __dealloc__(self): + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":941 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":942 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":943 + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) # <<<<<<<<<<<<<< + * else: + * return memoryview.convert_item_to_object(self, itemp) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":945 + * return self.to_object_func(itemp) + * else: + * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_vtabptr_memoryview->convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 945; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":947 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":948 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":949 + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< + * else: + * memoryview.assign_item_from_object(self, itemp, value) + */ + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":951 + * self.to_dtype_func(itemp, value) + * else: + * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< + * + * property base: + */ + __pyx_t_3 = __pyx_vtabptr_memoryview->assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 951; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":955 + * property base: + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + +static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":956 + * @cname('__pyx_memoryviewslice__get__base') + * def __get__(self): + * return self.from_object # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->from_object); + __pyx_r = __pyx_v_self->from_object; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":962 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_TypeInfo *__pyx_t_4; + Py_buffer __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_fromslice", 0); + + /* "View.MemoryView":971 + * cdef int i + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":972 + * + * if memviewslice.memview == Py_None: + * return None # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":977 + * + * + * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< + * + * result.from_slice = memviewslice + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":979 + * result = _memoryviewslice(None, 0, dtype_is_object) + * + * result.from_slice = memviewslice # <<<<<<<<<<<<<< + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + */ + __pyx_v_result->from_slice = __pyx_v_memviewslice; + + /* "View.MemoryView":980 + * + * result.from_slice = memviewslice + * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< + * + * result.from_object = ( memviewslice.memview).base + */ + __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); + + /* "View.MemoryView":982 + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< + * result.typeinfo = memviewslice.memview.typeinfo + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s__base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 982; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_result->from_object); + __Pyx_DECREF(__pyx_v_result->from_object); + __pyx_v_result->from_object = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":983 + * + * result.from_object = ( memviewslice.memview).base + * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< + * + * result.view = memviewslice.memview.view + */ + __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; + __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; + + /* "View.MemoryView":985 + * result.typeinfo = memviewslice.memview.typeinfo + * + * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + */ + __pyx_t_5 = __pyx_v_memviewslice.memview->view; + __pyx_v_result->__pyx_base.view = __pyx_t_5; + + /* "View.MemoryView":986 + * + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + */ + __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); + + /* "View.MemoryView":987 + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data + * result.view.ndim = ndim # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; + + /* "View.MemoryView":988 + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; + + /* "View.MemoryView":989 + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * result.flags = PyBUF_RECORDS + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":991 + * Py_INCREF(Py_None) + * + * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< + * + * result.view.shape = result.from_slice.shape + */ + __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; + + /* "View.MemoryView":993 + * result.flags = PyBUF_RECORDS + * + * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets + */ + __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); + + /* "View.MemoryView":994 + * + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * + */ + __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); + + /* "View.MemoryView":995 + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides + * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + * + * result.view.len = result.view.itemsize + */ + __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + + /* "View.MemoryView":997 + * result.view.suboffsets = result.from_slice.suboffsets + * + * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< + * for i in range(ndim): + * result.view.len *= result.view.shape[i] + */ + __pyx_t_6 = __pyx_v_result->__pyx_base.view.itemsize; + __pyx_v_result->__pyx_base.view.len = __pyx_t_6; + + /* "View.MemoryView":998 + * + * result.view.len = result.view.itemsize + * for i in range(ndim): # <<<<<<<<<<<<<< + * result.view.len *= result.view.shape[i] + * + */ + __pyx_t_7 = __pyx_v_ndim; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "View.MemoryView":999 + * result.view.len = result.view.itemsize + * for i in range(ndim): + * result.view.len *= result.view.shape[i] # <<<<<<<<<<<<<< + * + * result.to_object_func = to_object_func + */ + __pyx_v_result->__pyx_base.view.len = (__pyx_v_result->__pyx_base.view.len * (__pyx_v_result->__pyx_base.view.shape[__pyx_v_i])); + } + + /* "View.MemoryView":1001 + * result.view.len *= result.view.shape[i] + * + * result.to_object_func = to_object_func # <<<<<<<<<<<<<< + * result.to_dtype_func = to_dtype_func + * + */ + __pyx_v_result->to_object_func = __pyx_v_to_object_func; + + /* "View.MemoryView":1002 + * + * result.to_object_func = to_object_func + * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; + + /* "View.MemoryView":1004 + * result.to_dtype_func = to_dtype_func + * + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1007 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + */ + +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { + struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; + __Pyx_memviewslice *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_slice_from_memview", 0); + + /* "View.MemoryView":1010 + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1011 + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): + * obj = memview # <<<<<<<<<<<<<< + * return &obj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1011; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_INCREF(((PyObject *)__pyx_v_memview)); + __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview); + + /* "View.MemoryView":1012 + * if isinstance(memview, _memoryviewslice): + * obj = memview + * return &obj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, mslice) + */ + __pyx_r = (&__pyx_v_obj->from_slice); + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1014 + * return &obj.from_slice + * else: + * slice_copy(memview, mslice) # <<<<<<<<<<<<<< + * return mslice + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); + + /* "View.MemoryView":1015 + * else: + * slice_copy(memview, mslice) + * return mslice # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_copy') + */ + __pyx_r = __pyx_v_mslice; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_obj); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1018 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef Py_ssize_t *shape, *strides, *suboffsets + */ + +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { + int __pyx_v_dim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + Py_ssize_t *__pyx_v_suboffsets; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + __Pyx_RefNannySetupContext("slice_copy", 0); + + /* "View.MemoryView":1022 + * cdef Py_ssize_t *shape, *strides, *suboffsets + * + * shape = memview.view.shape # <<<<<<<<<<<<<< + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets + */ + __pyx_t_1 = __pyx_v_memview->view.shape; + __pyx_v_shape = __pyx_t_1; + + /* "View.MemoryView":1023 + * + * shape = memview.view.shape + * strides = memview.view.strides # <<<<<<<<<<<<<< + * suboffsets = memview.view.suboffsets + * + */ + __pyx_t_1 = __pyx_v_memview->view.strides; + __pyx_v_strides = __pyx_t_1; + + /* "View.MemoryView":1024 + * shape = memview.view.shape + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< + * + * dst.memview = <__pyx_memoryview *> memview + */ + __pyx_t_1 = __pyx_v_memview->view.suboffsets; + __pyx_v_suboffsets = __pyx_t_1; + + /* "View.MemoryView":1026 + * suboffsets = memview.view.suboffsets + * + * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< + * dst.data = memview.view.buf + * + */ + __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); + + /* "View.MemoryView":1027 + * + * dst.memview = <__pyx_memoryview *> memview + * dst.data = memview.view.buf # <<<<<<<<<<<<<< + * + * for dim in range(memview.view.ndim): + */ + __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); + + /* "View.MemoryView":1029 + * dst.data = memview.view.buf + * + * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + */ + __pyx_t_2 = __pyx_v_memview->view.ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_dim = __pyx_t_3; + + /* "View.MemoryView":1030 + * + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + */ + (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); + + /* "View.MemoryView":1031 + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 + */ + (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); + + /* "View.MemoryView":1032 + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: # <<<<<<<<<<<<<< + * dst.suboffsets[dim] = -1 + * else: + */ + __pyx_t_4 = ((__pyx_v_suboffsets == NULL) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":1033 + * dst.strides[dim] = strides[dim] + * if suboffsets == NULL: + * dst.suboffsets[dim] = -1 # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[dim] = suboffsets[dim] + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = -1; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1035 + * dst.suboffsets[dim] = -1 + * else: + * dst.suboffsets[dim] = suboffsets[dim] # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object') + */ + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = (__pyx_v_suboffsets[__pyx_v_dim]); + } + __pyx_L5:; + } + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1038 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { + __Pyx_memviewslice __pyx_v_memviewslice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy", 0); + + /* "View.MemoryView":1041 + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< + * return memoryview_copy_from_slice(memview, &memviewslice) + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); + + /* "View.MemoryView":1042 + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) + * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object_from_slice') + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1042; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1045 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { + PyObject *(*__pyx_v_to_object_func)(char *); + int (*__pyx_v_to_dtype_func)(char *, PyObject *); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *(*__pyx_t_3)(char *); + int (*__pyx_t_4)(char *, PyObject *); + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); + + /* "View.MemoryView":1052 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1053 + * + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + */ + __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; + __pyx_v_to_object_func = __pyx_t_3; + + /* "View.MemoryView":1054 + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< + * else: + * to_object_func = NULL + */ + __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; + __pyx_v_to_dtype_func = __pyx_t_4; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1056 + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + * to_object_func = NULL # <<<<<<<<<<<<<< + * to_dtype_func = NULL + * + */ + __pyx_v_to_object_func = NULL; + + /* "View.MemoryView":1057 + * else: + * to_object_func = NULL + * to_dtype_func = NULL # <<<<<<<<<<<<<< + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + */ + __pyx_v_to_dtype_func = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":1059 + * to_dtype_func = NULL + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< + * to_object_func, to_dtype_func, + * memview.dtype_is_object) + */ + __Pyx_XDECREF(__pyx_r); + + /* "View.MemoryView":1061 + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + * to_object_func, to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1067 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + +static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { + Py_ssize_t __pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":1068 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + __pyx_t_1 = ((__pyx_v_arg < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1069 + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: + * return -arg # <<<<<<<<<<<<<< + * else: + * return arg + */ + __pyx_r = (-__pyx_v_arg); + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1071 + * return -arg + * else: + * return arg # <<<<<<<<<<<<<< + * + * @cname('__pyx_get_best_slice_order') + */ + __pyx_r = __pyx_v_arg; + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1074 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + +static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_c_stride; + Py_ssize_t __pyx_v_f_stride; + char __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1079 + * """ + * cdef int i + * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t f_stride = 0 + * + */ + __pyx_v_c_stride = 0; + + /* "View.MemoryView":1080 + * cdef int i + * cdef Py_ssize_t c_stride = 0 + * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_f_stride = 0; + + /* "View.MemoryView":1082 + * cdef Py_ssize_t f_stride = 0 + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1083 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1084 + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1085 + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + goto __pyx_L4_break; + goto __pyx_L5; + } + __pyx_L5:; + } + __pyx_L4_break:; + + /* "View.MemoryView":1087 + * break + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + */ + __pyx_t_1 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1088 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1089 + * for i in range(ndim): + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1090 + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + */ + goto __pyx_L7_break; + goto __pyx_L8; + } + __pyx_L8:; + } + __pyx_L7_break:; + + /* "View.MemoryView":1092 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1093 + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + * return 'C' # <<<<<<<<<<<<<< + * else: + * return 'F' + */ + __pyx_r = 'C'; + goto __pyx_L0; + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1095 + * return 'C' + * else: + * return 'F' # <<<<<<<<<<<<<< + * + * @cython.cdivision(True) + */ + __pyx_r = 'F'; + goto __pyx_L0; + } + __pyx_L9:; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1098 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + +static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; + Py_ssize_t __pyx_v_dst_extent; + Py_ssize_t __pyx_v_src_stride; + Py_ssize_t __pyx_v_dst_stride; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + + /* "View.MemoryView":1105 + * + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + */ + __pyx_v_src_extent = (__pyx_v_src_shape[0]); + + /* "View.MemoryView":1106 + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] + */ + __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); + + /* "View.MemoryView":1107 + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + */ + __pyx_v_src_stride = (__pyx_v_src_strides[0]); + + /* "View.MemoryView":1108 + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); + + /* "View.MemoryView":1110 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1111 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + __pyx_t_1 = ((__pyx_v_src_stride > 0) != 0); + if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1112 + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + */ + __pyx_t_3 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); + if (__pyx_t_3) { + __pyx_t_3 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); + } + __pyx_t_4 = (__pyx_t_3 != 0); + } else { + __pyx_t_4 = __pyx_t_2; + } + __pyx_t_2 = __pyx_t_4; + } else { + __pyx_t_2 = __pyx_t_1; + } + if (__pyx_t_2) { + + /* "View.MemoryView":1113 + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); + goto __pyx_L4; + } + /*else*/ { + + /* "View.MemoryView":1115 + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1116 + * else: + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); + + /* "View.MemoryView":1117 + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * else: + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1118 + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L4:; + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1120 + * dst_data += dst_stride + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * _copy_strided_to_strided(src_data, src_strides + 1, + * dst_data, dst_strides + 1, + */ + __pyx_t_5 = __pyx_v_dst_extent; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1124 + * dst_data, dst_strides + 1, + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); + + /* "View.MemoryView":1125 + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1126 + * ndim - 1, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L3:; + +} + +/* "View.MemoryView":1128 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + +static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + + /* "View.MemoryView":1132 + * int ndim, size_t itemsize) nogil: + * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, + * src.shape, dst.shape, ndim, itemsize) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_get_size') + */ + _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); + +} + +/* "View.MemoryView":1135 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + */ + +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_size; + Py_ssize_t __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1138 + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef int i + * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_size = __pyx_t_1; + + /* "View.MemoryView":1140 + * cdef Py_ssize_t size = src.memview.view.itemsize + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * size *= src.shape[i] + * + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1141 + * + * for i in range(ndim): + * size *= src.shape[i] # <<<<<<<<<<<<<< + * + * return size + */ + __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); + } + + /* "View.MemoryView":1143 + * size *= src.shape[i] + * + * return size # <<<<<<<<<<<<<< + * + * @cname('__pyx_fill_contig_strides_array') + */ + __pyx_r = __pyx_v_size; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1146 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { + int __pyx_v_idx; + Py_ssize_t __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1155 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + __pyx_t_1 = ((__pyx_v_order == 'F') != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1156 + * + * if order == 'F': + * for idx in range(ndim): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + __pyx_t_2 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_idx = __pyx_t_3; + + /* "View.MemoryView":1157 + * if order == 'F': + * for idx in range(ndim): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * else: + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1158 + * for idx in range(ndim): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * else: + * for idx in range(ndim - 1, -1, -1): + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1160 + * stride = stride * shape[idx] + * else: + * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride = stride * shape[idx] + */ + for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { + __pyx_v_idx = __pyx_t_2; + + /* "View.MemoryView":1161 + * else: + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride = stride * shape[idx] + * + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1162 + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride + * stride = stride * shape[idx] # <<<<<<<<<<<<<< + * + * return stride + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + } + __pyx_L3:; + + /* "View.MemoryView":1164 + * stride = stride * shape[idx] + * + * return stride # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_data_to_temp') + */ + __pyx_r = __pyx_v_stride; + goto __pyx_L0; + + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1167 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { + int __pyx_v_i; + void *__pyx_v_result; + size_t __pyx_v_itemsize; + size_t __pyx_v_size; + void *__pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + struct __pyx_memoryview_obj *__pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1178 + * cdef void *result + * + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef size_t size = slice_get_size(src, ndim) + * + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1179 + * + * cdef size_t itemsize = src.memview.view.itemsize + * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< + * + * result = malloc(size) + */ + __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); + + /* "View.MemoryView":1181 + * cdef size_t size = slice_get_size(src, ndim) + * + * result = malloc(size) # <<<<<<<<<<<<<< + * if not result: + * _err(MemoryError, NULL) + */ + __pyx_v_result = malloc(__pyx_v_size); + + /* "View.MemoryView":1182 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1183 + * result = malloc(size) + * if not result: + * _err(MemoryError, NULL) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1186 + * + * + * tmpslice.data = result # <<<<<<<<<<<<<< + * tmpslice.memview = src.memview + * for i in range(ndim): + */ + __pyx_v_tmpslice->data = ((char *)__pyx_v_result); + + /* "View.MemoryView":1187 + * + * tmpslice.data = result + * tmpslice.memview = src.memview # <<<<<<<<<<<<<< + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + */ + __pyx_t_4 = __pyx_v_src->memview; + __pyx_v_tmpslice->memview = __pyx_t_4; + + /* "View.MemoryView":1188 + * tmpslice.data = result + * tmpslice.memview = src.memview + * for i in range(ndim): # <<<<<<<<<<<<<< + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1189 + * tmpslice.memview = src.memview + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< + * tmpslice.suboffsets[i] = -1 + * + */ + (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); + + /* "View.MemoryView":1190 + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + */ + (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1; + } + + /* "View.MemoryView":1193 + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + * ndim, order) # <<<<<<<<<<<<<< + * + * + */ + __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); + + /* "View.MemoryView":1196 + * + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 + */ + __pyx_t_3 = __pyx_v_ndim; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":1197 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1198 + * for i in range(ndim): + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< + * + * if slice_is_contig(src, order, ndim): + */ + (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1200 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1201 + * + * if slice_is_contig(src, order, ndim): + * memcpy(result, src.data, size) # <<<<<<<<<<<<<< + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + */ + memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); + goto __pyx_L9; + } + /*else*/ { + + /* "View.MemoryView":1203 + * memcpy(result, src.data, size) + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< + * + * return result + */ + copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); + } + __pyx_L9:; + + /* "View.MemoryView":1205 + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = NULL; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1210 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + +static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_extents", 0); + + /* "View.MemoryView":1213 + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + * (i, extent1, extent2)) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err_dim') + */ + __pyx_t_1 = PyInt_FromLong(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_45), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1216 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + +static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_dim", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1217 + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: + * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err') + */ + __pyx_t_1 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_2 = PyInt_FromLong(__pyx_v_dim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_t_1), __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_v_error, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1220 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + +static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1221 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ + __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1222 + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: + * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< + * else: + * raise error + */ + __pyx_t_2 = ((PyObject *)__Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_2)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_v_error, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1224 + * raise error(msg.decode('ascii')) + * else: + * raise error # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_contents') + */ + __Pyx_Raise(__pyx_v_error, 0, 0, 0); + {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L3:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1227 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { + void *__pyx_v_tmpdata; + size_t __pyx_v_itemsize; + int __pyx_v_i; + char __pyx_v_order; + int __pyx_v_broadcasting; + int __pyx_v_direct_copy; + __Pyx_memviewslice __pyx_v_tmp; + int __pyx_v_ndim; + int __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + void *__pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1235 + * Check for overlapping memory and verify the shapes. + * """ + * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + */ + __pyx_v_tmpdata = NULL; + + /* "View.MemoryView":1236 + * """ + * cdef void *tmpdata = NULL + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + */ + __pyx_t_1 = __pyx_v_src.memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1238 + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< + * cdef bint broadcasting = False + * cdef bint direct_copy = False + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); + + /* "View.MemoryView":1239 + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False # <<<<<<<<<<<<<< + * cdef bint direct_copy = False + * cdef __Pyx_memviewslice tmp + */ + __pyx_v_broadcasting = 0; + + /* "View.MemoryView":1240 + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False + * cdef bint direct_copy = False # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice tmp + * + */ + __pyx_v_direct_copy = 0; + + /* "View.MemoryView":1243 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ + __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1244 + * + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); + goto __pyx_L3; + } + + /* "View.MemoryView":1245 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ + __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1246 + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< + * + * cdef int ndim = max(src_ndim, dst_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); + goto __pyx_L3; + } + __pyx_L3:; + + /* "View.MemoryView":1248 + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_3 = __pyx_v_dst_ndim; + __pyx_t_4 = __pyx_v_src_ndim; + if (((__pyx_t_3 > __pyx_t_4) != 0)) { + __pyx_t_5 = __pyx_t_3; + } else { + __pyx_t_5 = __pyx_t_4; + } + __pyx_v_ndim = __pyx_t_5; + + /* "View.MemoryView":1250 + * cdef int ndim = max(src_ndim, dst_ndim) + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1251 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1252 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1253 + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + * broadcasting = True # <<<<<<<<<<<<<< + * src.strides[i] = 0 + * else: + */ + __pyx_v_broadcasting = 1; + + /* "View.MemoryView":1254 + * if src.shape[i] == 1: + * broadcasting = True + * src.strides[i] = 0 # <<<<<<<<<<<<<< + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) + */ + (__pyx_v_src.strides[__pyx_v_i]) = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "View.MemoryView":1256 + * src.strides[i] = 0 + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< + * + * if src.suboffsets[i] >= 0: + */ + __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L7:; + goto __pyx_L6; + } + __pyx_L6:; + + /* "View.MemoryView":1258 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ + __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1259 + * + * if src.suboffsets[i] >= 0: + * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< + * + * if slices_overlap(&src, &dst, ndim, itemsize): + */ + __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_46, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1259; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; + } + __pyx_L8:; + } + + /* "View.MemoryView":1261 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(&src, order, ndim): + */ + __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1263 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1264 + * + * if not slice_is_contig(&src, order, ndim): + * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); + goto __pyx_L10; + } + __pyx_L10:; + + /* "View.MemoryView":1266 + * order = get_best_order(&dst, ndim) + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< + * src = tmp + * + */ + __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_tmpdata = __pyx_t_6; + + /* "View.MemoryView":1267 + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + * src = tmp # <<<<<<<<<<<<<< + * + * if not broadcasting: + */ + __pyx_v_src = __pyx_v_tmp; + goto __pyx_L9; + } + __pyx_L9:; + + /* "View.MemoryView":1269 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1272 + * + * + * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1273 + * + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); + goto __pyx_L12; + } + + /* "View.MemoryView":1274 + * if slice_is_contig(&src, 'C', ndim): + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1275 + * direct_copy = slice_is_contig(&dst, 'C', ndim) + * elif slice_is_contig(&src, 'F', ndim): + * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< + * + * if direct_copy: + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); + goto __pyx_L12; + } + __pyx_L12:; + + /* "View.MemoryView":1277 + * direct_copy = slice_is_contig(&dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_2 = (__pyx_v_direct_copy != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1279 + * if direct_copy: + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1280 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * return 0 + */ + memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); + + /* "View.MemoryView":1281 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * return 0 + * + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1282 + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + * return 0 # <<<<<<<<<<<<<< + * + * if order == 'F' == get_best_order(&dst, ndim): + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L13; + } + __pyx_L13:; + goto __pyx_L11; + } + __pyx_L11:; + + /* "View.MemoryView":1284 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = (__pyx_v_order == 'F'); + if (__pyx_t_2) { + __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); + } + __pyx_t_7 = (__pyx_t_2 != 0); + if (__pyx_t_7) { + + /* "View.MemoryView":1287 + * + * + * transpose_memslice(&src) # <<<<<<<<<<<<<< + * transpose_memslice(&dst) + * + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":1288 + * + * transpose_memslice(&src) + * transpose_memslice(&dst) # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L14; + } + __pyx_L14:; + + /* "View.MemoryView":1290 + * transpose_memslice(&dst) + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1291 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + */ + copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1292 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * free(tmpdata) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1294 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1295 + * + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_broadcast_leading') + */ + __pyx_r = 0; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1298 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice, int __pyx_v_ndim, int __pyx_v_ndim_other) { + int __pyx_v_i; + int __pyx_v_offset; + int __pyx_t_1; + int __pyx_t_2; + + /* "View.MemoryView":1302 + * int ndim_other) nogil: + * cdef int i + * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); + + /* "View.MemoryView":1304 + * cdef int offset = ndim_other - ndim + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1305 + * + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] # <<<<<<<<<<<<<< + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] + */ + (__pyx_v_slice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->shape[__pyx_v_i]); + + /* "View.MemoryView":1306 + * for i in range(ndim - 1, -1, -1): + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] # <<<<<<<<<<<<<< + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + */ + (__pyx_v_slice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->strides[__pyx_v_i]); + + /* "View.MemoryView":1307 + * slice.shape[i + offset] = slice.shape[i] + * slice.strides[i + offset] = slice.strides[i] + * slice.suboffsets[i + offset] = slice.suboffsets[i] # <<<<<<<<<<<<<< + * + * for i in range(offset): + */ + (__pyx_v_slice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->suboffsets[__pyx_v_i]); + } + + /* "View.MemoryView":1309 + * slice.suboffsets[i + offset] = slice.suboffsets[i] + * + * for i in range(offset): # <<<<<<<<<<<<<< + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + */ + __pyx_t_1 = __pyx_v_offset; + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1310 + * + * for i in range(offset): + * slice.shape[i] = 1 # <<<<<<<<<<<<<< + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 + */ + (__pyx_v_slice->shape[__pyx_v_i]) = 1; + + /* "View.MemoryView":1311 + * for i in range(offset): + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] # <<<<<<<<<<<<<< + * slice.suboffsets[i] = -1 + * + */ + (__pyx_v_slice->strides[__pyx_v_i]) = (__pyx_v_slice->strides[0]); + + /* "View.MemoryView":1312 + * slice.shape[i] = 1 + * slice.strides[i] = slice.strides[0] + * slice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_slice->suboffsets[__pyx_v_i]) = -1; + } + +} + +/* "View.MemoryView":1320 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { + int __pyx_t_1; + + /* "View.MemoryView":1324 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + __pyx_t_1 = (__pyx_v_dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1326 + * if dtype_is_object: + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + */ + __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); + goto __pyx_L3; + } + __pyx_L3:; + +} + +/* "View.MemoryView":1329 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + __Pyx_RefNannyDeclarations + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); + + /* "View.MemoryView":1332 + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); + + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif +} + +/* "View.MemoryView":1335 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + +static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); + + /* "View.MemoryView":1339 + * cdef Py_ssize_t i + * + * for i in range(shape[0]): # <<<<<<<<<<<<<< + * if ndim == 1: + * if inc: + */ + __pyx_t_1 = (__pyx_v_shape[0]); + for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { + __pyx_v_i = __pyx_t_2; + + /* "View.MemoryView":1340 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1341 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + __pyx_t_3 = (__pyx_v_inc != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":1342 + * if ndim == 1: + * if inc: + * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * Py_DECREF(( data)[0]) + */ + Py_INCREF((((PyObject **)__pyx_v_data)[0])); + goto __pyx_L6; + } + /*else*/ { + + /* "View.MemoryView":1344 + * Py_INCREF(( data)[0]) + * else: + * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + */ + Py_DECREF((((PyObject **)__pyx_v_data)[0])); + } + __pyx_L6:; + goto __pyx_L5; + } + /*else*/ { + + /* "View.MemoryView":1347 + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + * ndim - 1, inc) # <<<<<<<<<<<<<< + * + * data += strides[0] + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); + } + __pyx_L5:; + + /* "View.MemoryView":1349 + * ndim - 1, inc) + * + * data += strides[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); + } + + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1355 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { + + /* "View.MemoryView":1358 + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1360 + * refcount_copying(dst, dtype_is_object, ndim, False) + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) # <<<<<<<<<<<<<< + * refcount_copying(dst, dtype_is_object, ndim, True) + * + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1361 + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + +} + +/* "View.MemoryView":1365 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + +static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_extent; + int __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + + /* "View.MemoryView":1369 + * size_t itemsize, void *item) nogil: + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t extent = shape[0] + * + */ + __pyx_v_stride = (__pyx_v_strides[0]); + + /* "View.MemoryView":1370 + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] + * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_extent = (__pyx_v_shape[0]); + + /* "View.MemoryView":1372 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1373 + * + * if ndim == 1: + * for i in range(extent): # <<<<<<<<<<<<<< + * memcpy(data, item, itemsize) + * data += stride + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1374 + * if ndim == 1: + * for i in range(extent): + * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< + * data += stride + * else: + */ + memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); + + /* "View.MemoryView":1375 + * for i in range(extent): + * memcpy(data, item, itemsize) + * data += stride # <<<<<<<<<<<<<< + * else: + * for i in range(extent): + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + goto __pyx_L3; + } + /*else*/ { + + /* "View.MemoryView":1377 + * data += stride + * else: + * for i in range(extent): # <<<<<<<<<<<<<< + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + */ + __pyx_t_2 = __pyx_v_extent; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1379 + * for i in range(extent): + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) # <<<<<<<<<<<<<< + * data += stride + * + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1380 + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + * data += stride # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + } + __pyx_L3:; + +} + +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_MemviewEnum_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_MemviewEnum_obj *)o); + p->name = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + PyObject_GC_UnTrack(o); + Py_CLEAR(p->name); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + if (p->name) { + e = (*v)(p->name, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->name); + p->name = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_Enum[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_MemviewEnum = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.utils.fast_dict.Enum"), /*tp_name*/ + sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_Enum, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_MemviewEnum___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_Enum, /*tp_traverse*/ + __pyx_tp_clear_Enum, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_Enum, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_MemviewEnum___init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_Enum, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; + +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryview_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryview_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_memoryview; + p->obj = Py_None; Py_INCREF(Py_None); + p->_size = Py_None; Py_INCREF(Py_None); + p->_array_interface = Py_None; Py_INCREF(Py_None); + p->view.obj = NULL; + if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryview___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->obj); + Py_CLEAR(p->_size); + Py_CLEAR(p->_array_interface); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + if (p->obj) { + e = (*v)(p->obj, a); if (e) return e; + } + if (p->_size) { + e = (*v)(p->_size, a); if (e) return e; + } + if (p->_array_interface) { + e = (*v)(p->_array_interface, a); if (e) return e; + } + if (p->view.obj) { + e = (*v)(p->view.obj, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->obj); + p->obj = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_size); + p->_size = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_array_interface); + p->_array_interface = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + Py_CLEAR(p->view.obj); + return 0; +} +static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_memoryview___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_transpose(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview__get__base(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_shape(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_strides(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_suboffsets(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_ndim(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_itemsize(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_nbytes(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryview_get_size(o); +} + +static PyMethodDef __pyx_methods_memoryview[] = { + {__Pyx_NAMESTR("is_c_contig"), (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("is_f_contig"), (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy"), (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy_fortran"), (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_memoryview[] = { + {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, + {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, + {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, + {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, + {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, + {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, + {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, + {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_memoryview = { + __pyx_memoryview___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_memoryview, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_memoryview = { + __pyx_memoryview___len__, /*mp_length*/ + __pyx_memoryview___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_memoryview = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_memoryview_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_memoryview = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.utils.fast_dict.memoryview"), /*tp_name*/ + sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + __pyx_memoryview___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_memoryview___str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_memoryview, /*tp_traverse*/ + __pyx_tp_clear_memoryview, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_memoryview, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_memoryview, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_memoryview, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; + +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryviewslice_obj *p; + PyObject *o = __pyx_tp_new_memoryview(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryviewslice_obj *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; + p->from_object = Py_None; Py_INCREF(Py_None); + p->from_slice.memview = NULL; + return o; +} + +static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_memoryviewslice___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->from_object); + PyObject_GC_Track(o); + __pyx_tp_dealloc_memoryview(o); +} + +static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; + if (p->from_object) { + e = (*v)(p->from_object, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + PyObject* tmp; + __pyx_tp_clear_memoryview(o); + tmp = ((PyObject*)p->from_object); + p->from_object = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + __PYX_XDEC_MEMVIEW(&p->from_slice, 1); + return 0; +} + +static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_memoryviewslice__get__base(o); +} + +static PyMethodDef __pyx_methods__memoryviewslice[] = { + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { + {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_memoryviewslice = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.utils.fast_dict._memoryviewslice"), /*tp_name*/ + sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___repr__, /*tp_repr*/ + #else + 0, /*tp_repr*/ + #endif + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___str__, /*tp_str*/ + #else + 0, /*tp_str*/ + #endif + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Internal class for passing memoryview slices to Python"), /*tp_doc*/ + __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ + __pyx_tp_clear__memoryviewslice, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods__memoryviewslice, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets__memoryviewslice, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new__memoryviewslice, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_array_obj *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_array_obj *)o); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { + Py_DECREF(o); o = 0; + } + return o; +} + +static void __pyx_tp_dealloc_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_array___dealloc__(o); + if (PyErr_Occurred()) PyErr_WriteUnraisable(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->mode); + Py_CLEAR(p->_format); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_array(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + if (p->mode) { + e = (*v)(p->mode, a); if (e) return e; + } + if (p->_format) { + e = (*v)(p->_format, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + PyObject* tmp; + tmp = ((PyObject*)p->mode); + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_format); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} +static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_array___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { + PyObject *v = PyObject_GenericGetAttr(o, n); + if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + v = __pyx_array___getattr__(o, n); + } + return v; +} + +static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { + return get_memview(o); +} + +static PyMethodDef __pyx_methods_array[] = { + {__Pyx_NAMESTR("__getattr__"), (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_array[] = { + {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_array = { + 0, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_array, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_array = { + 0, /*mp_length*/ + __pyx_array___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_array = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + __pyx_array_getbuffer, /*bf_getbuffer*/ + #endif + #if PY_VERSION_HEX >= 0x02060000 + 0, /*bf_releasebuffer*/ + #endif +}; + +static PyTypeObject __pyx_type___pyx_array = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.utils.fast_dict.array"), /*tp_name*/ + sizeof(struct __pyx_array_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_array, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + __pyx_tp_getattro_array, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_array, /*tp_traverse*/ + __pyx_tp_clear_array, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_array, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_array, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_array, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; +static struct __pyx_vtabstruct_7sklearn_5utils_9fast_dict_IntFloatDict __pyx_vtable_7sklearn_5utils_9fast_dict_IntFloatDict; + +static PyObject *__pyx_tp_new_7sklearn_5utils_9fast_dict_IntFloatDict(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *p; + PyObject *o; + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)o); + p->__pyx_vtab = __pyx_vtabptr_7sklearn_5utils_9fast_dict_IntFloatDict; + new((void*)&(p->my_map)) std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t>(); + return o; +} + +static void __pyx_tp_dealloc_7sklearn_5utils_9fast_dict_IntFloatDict(PyObject *o) { + struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *p = (struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)o; + p->my_map.std::map<__pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t,__pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t>::~map(); + (*Py_TYPE(o)->tp_free)(o); +} +static PyObject *__pyx_sq_item_7sklearn_5utils_9fast_dict_IntFloatDict(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_7sklearn_5utils_9fast_dict_IntFloatDict(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_7__setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyMethodDef __pyx_methods_7sklearn_5utils_9fast_dict_IntFloatDict[] = { + {__Pyx_NAMESTR("to_arrays"), (PyCFunction)__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_12to_arrays, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_9fast_dict_12IntFloatDict_11to_arrays)}, + {__Pyx_NAMESTR("update"), (PyCFunction)__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_14update, METH_O, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("copy"), (PyCFunction)__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_16copy, METH_NOARGS, __Pyx_DOCSTR(0)}, + {__Pyx_NAMESTR("append"), (PyCFunction)__pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_18append, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, + {0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_IntFloatDict = { + __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_3__len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_7sklearn_5utils_9fast_dict_IntFloatDict, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_IntFloatDict = { + __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_3__len__, /*mp_length*/ + __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_5__getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_7sklearn_5utils_9fast_dict_IntFloatDict, /*mp_ass_subscript*/ +}; + +static PyTypeObject __pyx_type_7sklearn_5utils_9fast_dict_IntFloatDict = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.utils.fast_dict.IntFloatDict"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_5utils_9fast_dict_IntFloatDict, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_IntFloatDict, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_IntFloatDict, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_9__iter__, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_5utils_9fast_dict_IntFloatDict, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_pw_7sklearn_5utils_9fast_dict_12IntFloatDict_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_5utils_9fast_dict_IntFloatDict, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *__pyx_freelist_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__[8]; +static int __pyx_freecount_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ = 0; + +static PyObject *__pyx_tp_new_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *p; + PyObject *o; + if (likely((__pyx_freecount_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__)))) { + o = (PyObject*)__pyx_freelist_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__[--__pyx_freecount_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__]; + memset(o, 0, sizeof(struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__)); + PyObject_INIT(o, t); + PyObject_GC_Track(o); + } else { + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + } + p = ((struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *)o); + p->__pyx_v_self = 0; + p->__pyx_v_keys.data = NULL; + p->__pyx_v_keys.memview = NULL; + p->__pyx_v_values.data = NULL; + p->__pyx_v_values.memview = NULL; + return o; +} + +static void __pyx_tp_dealloc_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__(PyObject *o) { + struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *p = (struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *)o; + PyObject_GC_UnTrack(o); + Py_CLEAR(p->__pyx_v_self); + __PYX_XDEC_MEMVIEW(&p->__pyx_v_keys, 1); + __PYX_XDEC_MEMVIEW(&p->__pyx_v_values, 1); + if ((__pyx_freecount_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__))) { + __pyx_freelist_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__[__pyx_freecount_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__++] = ((struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *)o); + } else { + (*Py_TYPE(o)->tp_free)(o); + } +} + +static int __pyx_tp_traverse_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *p = (struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *)o; + if (p->__pyx_v_self) { + e = (*v)(((PyObject*)p->__pyx_v_self), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__(PyObject *o) { + struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *p = (struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ *)o; + PyObject* tmp; + tmp = ((PyObject*)p->__pyx_v_self); + p->__pyx_v_self = ((struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__[] = { + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.utils.fast_dict.__pyx_scope_struct____iter__"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #else + 0, /*reserved*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + #if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + __Pyx_NAMESTR("fast_dict"), + __Pyx_DOCSTR(__pyx_k_47), /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 0}, + {&__pyx_kp_u_12, __pyx_k_12, sizeof(__pyx_k_12), 0, 1, 0, 0}, + {&__pyx_kp_s_14, __pyx_k_14, sizeof(__pyx_k_14), 0, 0, 1, 0}, + {&__pyx_kp_s_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 1, 0}, + {&__pyx_kp_s_19, __pyx_k_19, sizeof(__pyx_k_19), 0, 0, 1, 0}, + {&__pyx_kp_u_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 1, 0, 0}, + {&__pyx_kp_s_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 1, 0}, + {&__pyx_kp_s_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 1, 0}, + {&__pyx_kp_s_24, __pyx_k_24, sizeof(__pyx_k_24), 0, 0, 1, 0}, + {&__pyx_kp_s_26, __pyx_k_26, sizeof(__pyx_k_26), 0, 0, 1, 0}, + {&__pyx_kp_s_28, __pyx_k_28, sizeof(__pyx_k_28), 0, 0, 1, 0}, + {&__pyx_kp_s_30, __pyx_k_30, sizeof(__pyx_k_30), 0, 0, 1, 0}, + {&__pyx_kp_s_32, __pyx_k_32, sizeof(__pyx_k_32), 0, 0, 1, 0}, + {&__pyx_kp_s_33, __pyx_k_33, sizeof(__pyx_k_33), 0, 0, 1, 0}, + {&__pyx_kp_s_36, __pyx_k_36, sizeof(__pyx_k_36), 0, 0, 1, 0}, + {&__pyx_kp_s_38, __pyx_k_38, sizeof(__pyx_k_38), 0, 0, 1, 0}, + {&__pyx_kp_u_4, __pyx_k_4, sizeof(__pyx_k_4), 0, 1, 0, 0}, + {&__pyx_kp_s_43, __pyx_k_43, sizeof(__pyx_k_43), 0, 0, 1, 0}, + {&__pyx_kp_s_45, __pyx_k_45, sizeof(__pyx_k_45), 0, 0, 1, 0}, + {&__pyx_kp_s_50, __pyx_k_50, sizeof(__pyx_k_50), 0, 0, 1, 0}, + {&__pyx_n_s_51, __pyx_k_51, sizeof(__pyx_k_51), 0, 0, 1, 1}, + {&__pyx_kp_s_53, __pyx_k_53, sizeof(__pyx_k_53), 0, 0, 1, 0}, + {&__pyx_kp_s_55, __pyx_k_55, sizeof(__pyx_k_55), 0, 0, 1, 0}, + {&__pyx_kp_s_57, __pyx_k_57, sizeof(__pyx_k_57), 0, 0, 1, 0}, + {&__pyx_kp_s_59, __pyx_k_59, sizeof(__pyx_k_59), 0, 0, 1, 0}, + {&__pyx_kp_u_6, __pyx_k_6, sizeof(__pyx_k_6), 0, 1, 0, 0}, + {&__pyx_kp_s_61, __pyx_k_61, sizeof(__pyx_k_61), 0, 0, 1, 0}, + {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, + {&__pyx_kp_u_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 1, 0, 0}, + {&__pyx_n_s__ASCII, __pyx_k__ASCII, sizeof(__pyx_k__ASCII), 0, 0, 1, 1}, + {&__pyx_n_s__Ellipsis, __pyx_k__Ellipsis, sizeof(__pyx_k__Ellipsis), 0, 0, 1, 1}, + {&__pyx_n_s__IndexError, __pyx_k__IndexError, sizeof(__pyx_k__IndexError), 0, 0, 1, 1}, + {&__pyx_n_s__KeyError, __pyx_k__KeyError, sizeof(__pyx_k__KeyError), 0, 0, 1, 1}, + {&__pyx_n_s__MemoryError, __pyx_k__MemoryError, sizeof(__pyx_k__MemoryError), 0, 0, 1, 1}, + {&__pyx_n_b__O, __pyx_k__O, sizeof(__pyx_k__O), 0, 0, 0, 1}, + {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s__TypeError, __pyx_k__TypeError, sizeof(__pyx_k__TypeError), 0, 0, 1, 1}, + {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, + {&__pyx_n_s____class__, __pyx_k____class__, sizeof(__pyx_k____class__), 0, 0, 1, 1}, + {&__pyx_n_s____import__, __pyx_k____import__, sizeof(__pyx_k____import__), 0, 0, 1, 1}, + {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, + {&__pyx_n_s____name__, __pyx_k____name__, sizeof(__pyx_k____name__), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_getbuffer, __pyx_k____pyx_getbuffer, sizeof(__pyx_k____pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_releasebuffer, __pyx_k____pyx_releasebuffer, sizeof(__pyx_k____pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s____pyx_vtable__, __pyx_k____pyx_vtable__, sizeof(__pyx_k____pyx_vtable__), 0, 0, 1, 1}, + {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, + {&__pyx_n_s__allocate_buffer, __pyx_k__allocate_buffer, sizeof(__pyx_k__allocate_buffer), 0, 0, 1, 1}, + {&__pyx_n_s__argmin, __pyx_k__argmin, sizeof(__pyx_k__argmin), 0, 0, 1, 1}, + {&__pyx_n_s__args, __pyx_k__args, sizeof(__pyx_k__args), 0, 0, 1, 1}, + {&__pyx_n_s__base, __pyx_k__base, sizeof(__pyx_k__base), 0, 0, 1, 1}, + {&__pyx_n_b__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 0, 0, 1}, + {&__pyx_n_s__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 0, 1, 1}, + {&__pyx_n_u__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 1, 0, 1}, + {&__pyx_n_s__close, __pyx_k__close, sizeof(__pyx_k__close), 0, 0, 1, 1}, + {&__pyx_n_s__d, __pyx_k__d, sizeof(__pyx_k__d), 0, 0, 1, 1}, + {&__pyx_n_s__decode, __pyx_k__decode, sizeof(__pyx_k__decode), 0, 0, 1, 1}, + {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, + {&__pyx_n_s__dtype_is_object, __pyx_k__dtype_is_object, sizeof(__pyx_k__dtype_is_object), 0, 0, 1, 1}, + {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, + {&__pyx_n_s__encode, __pyx_k__encode, sizeof(__pyx_k__encode), 0, 0, 1, 1}, + {&__pyx_n_s__end, __pyx_k__end, sizeof(__pyx_k__end), 0, 0, 1, 1}, + {&__pyx_n_s__enumerate, __pyx_k__enumerate, sizeof(__pyx_k__enumerate), 0, 0, 1, 1}, + {&__pyx_n_s__error, __pyx_k__error, sizeof(__pyx_k__error), 0, 0, 1, 1}, + {&__pyx_n_s__extend, __pyx_k__extend, sizeof(__pyx_k__extend), 0, 0, 1, 1}, + {&__pyx_n_s__flags, __pyx_k__flags, sizeof(__pyx_k__flags), 0, 0, 1, 1}, + {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, + {&__pyx_n_s__format, __pyx_k__format, sizeof(__pyx_k__format), 0, 0, 1, 1}, + {&__pyx_n_b__fortran, __pyx_k__fortran, sizeof(__pyx_k__fortran), 0, 0, 0, 1}, + {&__pyx_n_s__fortran, __pyx_k__fortran, sizeof(__pyx_k__fortran), 0, 0, 1, 1}, + {&__pyx_n_s__id, __pyx_k__id, sizeof(__pyx_k__id), 0, 0, 1, 1}, + {&__pyx_n_s__inf, __pyx_k__inf, sizeof(__pyx_k__inf), 0, 0, 1, 1}, + {&__pyx_n_s__intp, __pyx_k__intp, sizeof(__pyx_k__intp), 0, 0, 1, 1}, + {&__pyx_n_s__it, __pyx_k__it, sizeof(__pyx_k__it), 0, 0, 1, 1}, + {&__pyx_n_s__itemsize, __pyx_k__itemsize, sizeof(__pyx_k__itemsize), 0, 0, 1, 1}, + {&__pyx_n_s__key, __pyx_k__key, sizeof(__pyx_k__key), 0, 0, 1, 1}, + {&__pyx_n_s__keys, __pyx_k__keys, sizeof(__pyx_k__keys), 0, 0, 1, 1}, + {&__pyx_n_s__memview, __pyx_k__memview, sizeof(__pyx_k__memview), 0, 0, 1, 1}, + {&__pyx_n_s__min_key, __pyx_k__min_key, sizeof(__pyx_k__min_key), 0, 0, 1, 1}, + {&__pyx_n_s__min_value, __pyx_k__min_value, sizeof(__pyx_k__min_value), 0, 0, 1, 1}, + {&__pyx_n_s__mode, __pyx_k__mode, sizeof(__pyx_k__mode), 0, 0, 1, 1}, + {&__pyx_n_s__name, __pyx_k__name, sizeof(__pyx_k__name), 0, 0, 1, 1}, + {&__pyx_n_s__ndim, __pyx_k__ndim, sizeof(__pyx_k__ndim), 0, 0, 1, 1}, + {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, + {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, + {&__pyx_n_s__obj, __pyx_k__obj, sizeof(__pyx_k__obj), 0, 0, 1, 1}, + {&__pyx_n_s__pack, __pyx_k__pack, sizeof(__pyx_k__pack), 0, 0, 1, 1}, + {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, + {&__pyx_n_s__send, __pyx_k__send, sizeof(__pyx_k__send), 0, 0, 1, 1}, + {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, + {&__pyx_n_s__size, __pyx_k__size, sizeof(__pyx_k__size), 0, 0, 1, 1}, + {&__pyx_n_s__start, __pyx_k__start, sizeof(__pyx_k__start), 0, 0, 1, 1}, + {&__pyx_n_s__step, __pyx_k__step, sizeof(__pyx_k__step), 0, 0, 1, 1}, + {&__pyx_n_s__stop, __pyx_k__stop, sizeof(__pyx_k__stop), 0, 0, 1, 1}, + {&__pyx_n_s__struct, __pyx_k__struct, sizeof(__pyx_k__struct), 0, 0, 1, 1}, + {&__pyx_n_s__throw, __pyx_k__throw, sizeof(__pyx_k__throw), 0, 0, 1, 1}, + {&__pyx_n_s__unpack, __pyx_k__unpack, sizeof(__pyx_k__unpack), 0, 0, 1, 1}, + {&__pyx_n_s__value, __pyx_k__value, sizeof(__pyx_k__value), 0, 0, 1, 1}, + {&__pyx_n_s__values, __pyx_k__values, sizeof(__pyx_k__values), 0, 0, 1, 1}, + {&__pyx_n_s__xrange, __pyx_k__xrange, sizeof(__pyx_k__xrange), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_KeyError = __Pyx_GetBuiltinName(__pyx_n_s__KeyError); if (!__pyx_builtin_KeyError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s__MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s__enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s__Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s__TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s__xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s__id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s__IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "numpy.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_k_tuple_3 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_2)); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_3); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_3)); + + /* "numpy.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_k_tuple_5 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_4)); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_5); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); + + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_k_tuple_7 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_6)); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_7); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); + + /* "numpy.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_k_tuple_10 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_9)); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_10); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_k_tuple_11 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_6)); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_11); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); + + /* "numpy.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_k_tuple_13 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_u_12)); if (unlikely(!__pyx_k_tuple_13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_13); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_13)); + + /* "View.MemoryView":124 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if self.itemsize <= 0: + */ + __pyx_k_tuple_15 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_14)); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_15); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); + + /* "View.MemoryView":127 + * + * if self.itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * encode = getattr(format, 'encode', None) + */ + __pyx_k_tuple_17 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_16)); if (unlikely(!__pyx_k_tuple_17)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_17); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_17)); + + /* "View.MemoryView":131 + * encode = getattr(format, 'encode', None) + * if encode: + * format = encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format + * self.format = self._format + */ + __pyx_k_tuple_18 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__ASCII)); if (unlikely(!__pyx_k_tuple_18)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_18); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_18)); + + /* "View.MemoryView":141 + * free(self._shape) + * free(self._strides) + * raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_20 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_19)); if (unlikely(!__pyx_k_tuple_20)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_20); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_20)); + + /* "View.MemoryView":166 + * decode = getattr(mode, 'decode', None) + * if decode: + * mode = decode('ASCII') # <<<<<<<<<<<<<< + * self.mode = mode + * + */ + __pyx_k_tuple_23 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__ASCII)); if (unlikely(!__pyx_k_tuple_23)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_23); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_23)); + + /* "View.MemoryView":174 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_k_tuple_25 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_24)); if (unlikely(!__pyx_k_tuple_25)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_25); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_25)); + + /* "View.MemoryView":190 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_k_tuple_27 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_26)); if (unlikely(!__pyx_k_tuple_27)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_27); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_27)); + + /* "View.MemoryView":452 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_k_tuple_29 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_28)); if (unlikely(!__pyx_k_tuple_29)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_29); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_29)); + + /* "View.MemoryView":528 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + */ + __pyx_k_tuple_31 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_30)); if (unlikely(!__pyx_k_tuple_31)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_31); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_31)); + + /* "View.MemoryView":643 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_k_tuple_34 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_34)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_34); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_34)); + + /* "View.MemoryView":646 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + __pyx_k_tuple_35 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_35)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_35); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_35)); + + /* "View.MemoryView":657 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_k_tuple_37 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_k_tuple_37)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_37); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_37)); + + /* "View.MemoryView":665 + * for i in range(ndim): + * if suboffsets[i] >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_39 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_38)); if (unlikely(!__pyx_k_tuple_39)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 665; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_39); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_39)); + + /* "sklearn/utils/fast_dict.pyx":144 + * # operation on dict + * + * def argmin(IntFloatDict d): # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = d.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = d.my_map.end() + */ + __pyx_k_tuple_48 = PyTuple_Pack(5, ((PyObject *)__pyx_n_s__d), ((PyObject *)__pyx_n_s__it), ((PyObject *)__pyx_n_s__end), ((PyObject *)__pyx_n_s__min_key), ((PyObject *)__pyx_n_s__min_value)); if (unlikely(!__pyx_k_tuple_48)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_48); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_48)); + __pyx_k_codeobj_49 = (PyObject*)__Pyx_PyCode_New(1, 0, 5, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_48, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_50, __pyx_n_s__argmin, 144, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_49)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "View.MemoryView":282 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_k_tuple_54 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_53)); if (unlikely(!__pyx_k_tuple_54)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_54); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_54)); + + /* "View.MemoryView":283 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_k_tuple_56 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_55)); if (unlikely(!__pyx_k_tuple_56)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_56); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_56)); + + /* "View.MemoryView":284 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_58 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_57)); if (unlikely(!__pyx_k_tuple_58)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_58); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_58)); + + /* "View.MemoryView":287 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_k_tuple_60 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_59)); if (unlikely(!__pyx_k_tuple_60)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_60); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_60)); + + /* "View.MemoryView":288 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_k_tuple_62 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_61)); if (unlikely(!__pyx_k_tuple_62)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_62); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_62)); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC initfast_dict(void); /*proto*/ +PyMODINIT_FUNC initfast_dict(void) +#else +PyMODINIT_FUNC PyInit_fast_dict(void); /*proto*/ +PyMODINIT_FUNC PyInit_fast_dict(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_fast_dict(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("fast_dict"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_47), 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.utils.fast_dict")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.utils.fast_dict", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__utils__fast_dict) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + generic = Py_None; Py_INCREF(Py_None); + strided = Py_None; Py_INCREF(Py_None); + indirect = Py_None; Py_INCREF(Py_None); + contiguous = Py_None; Py_INCREF(Py_None); + indirect_contiguous = Py_None; Py_INCREF(Py_None); + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; + __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; + __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; + __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; + __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; + __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; + __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; + __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; + __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; + if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryview_type = &__pyx_type___pyx_memoryview; + __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; + __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; + __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; + __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; + __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 927; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 927; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; + if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_array_type = &__pyx_type___pyx_array; + __pyx_vtabptr_7sklearn_5utils_9fast_dict_IntFloatDict = &__pyx_vtable_7sklearn_5utils_9fast_dict_IntFloatDict; + __pyx_vtable_7sklearn_5utils_9fast_dict_IntFloatDict._to_arrays = (PyObject *(*)(struct __pyx_obj_7sklearn_5utils_9fast_dict_IntFloatDict *, __Pyx_memviewslice, __Pyx_memviewslice))__pyx_f_7sklearn_5utils_9fast_dict_12IntFloatDict__to_arrays; + if (PyType_Ready(&__pyx_type_7sklearn_5utils_9fast_dict_IntFloatDict) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type_7sklearn_5utils_9fast_dict_IntFloatDict.tp_dict, __pyx_vtabptr_7sklearn_5utils_9fast_dict_IntFloatDict) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "IntFloatDict", (PyObject *)&__pyx_type_7sklearn_5utils_9fast_dict_IntFloatDict) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_5utils_9fast_dict_IntFloatDict = &__pyx_type_7sklearn_5utils_9fast_dict_IntFloatDict; + if (PyType_Ready(&__pyx_type_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__ = &__pyx_type_7sklearn_5utils_9fast_dict___pyx_scope_struct____iter__; + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/utils/fast_dict.pyx":16 + * from libcpp.map cimport map as cpp_map + * + * import numpy as np # <<<<<<<<<<<<<< + * + * # Import the C-level symbols of numpy + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/fast_dict.pyx":23 + * # Numpy must be initialized. When using numpy from C or Cython you must + * # _always_ do that, or you will have segfaults + * np.import_array() # <<<<<<<<<<<<<< + * + * #DTYPE = np.float64 + */ + import_array(); + + /* "sklearn/utils/fast_dict.pyx":144 + * # operation on dict + * + * def argmin(IntFloatDict d): # <<<<<<<<<<<<<< + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = d.my_map.begin() + * cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = d.my_map.end() + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_9fast_dict_1argmin, NULL, __pyx_n_s_51); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s__argmin, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/fast_dict.pyx":1 + * """ # <<<<<<<<<<<<<< + * Uses C++ map containers for fast dict-like behavior with keys being + * integers, and values float. + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + + /* "View.MemoryView":207 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * def __dealloc__(array self): + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_52); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_array_type); + + /* "View.MemoryView":282 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_54), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(generic); + __Pyx_DECREF(generic); + __Pyx_GIVEREF(__pyx_t_1); + generic = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":283 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_56), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(strided); + __Pyx_DECREF(strided); + __Pyx_GIVEREF(__pyx_t_1); + strided = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":284 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_58), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(indirect); + __Pyx_DECREF(indirect); + __Pyx_GIVEREF(__pyx_t_1); + indirect = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":287 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_60), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(contiguous); + __Pyx_DECREF(contiguous); + __Pyx_GIVEREF(__pyx_t_1); + contiguous = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":288 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), ((PyObject *)__pyx_k_tuple_62), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(indirect_contiguous); + __Pyx_DECREF(indirect_contiguous); + __Pyx_GIVEREF(__pyx_t_1); + indirect_contiguous = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":503 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_52); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_memoryview_type); + + /* "View.MemoryView":958 + * return self.from_object + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_52); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 958; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s____pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 958; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_memoryviewslice_type); + + /* "View.MemoryView":1365 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.utils.fast_dict", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.utils.fast_dict"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (!type) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (Py_TYPE(obj) == type) return 1; + } + else { + if (PyObject_TypeCheck(obj, type)) return 1; + } + PyErr_Format(PyExc_TypeError, + "Argument '%s' has incorrect type (expected %s, got %s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; /* Consume from buffer string */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + if (isspace(*ts)) + continue; + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case 10: + case 13: + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } /* fall through */ + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 's': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + } else { + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + } + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { + #endif +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +static void __Pyx_RaiseBufferIndexError(int axis) { + PyErr_Format(PyExc_IndexError, + "Out of bounds on buffer access (axis %d)", axis); +} + +static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (!buf) { + PyErr_SetString(PyExc_ValueError, + "buf is NULL."); + goto fail; + } else if (memviewslice->memview || memviewslice->data) { + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); + } + retval = 0; + goto no_fail; +fail: + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} +static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { + va_list vargs; + char msg[200]; + va_start(vargs, fmt); +#ifdef HAVE_STDARG_PROTOTYPES + va_start(vargs, fmt); +#else + va_start(vargs); +#endif + vsnprintf(msg, 200, fmt, vargs); + Py_FatalError(msg); + va_end(vargs); +} +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) +{ + int first_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview || (PyObject *) memview == Py_None) + return; /* allow uninitialized memoryview assignment */ + if (__pyx_get_slice_count(memview) < 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + first_time = __pyx_add_acquisition_count(memview) == 0; + if (first_time) { + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); + } + } +} +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, + int have_gil, int lineno) { + int last_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview ) { + return; + } else if ((PyObject *) memview == Py_None) { + memslice->memview = NULL; + return; + } + if (__pyx_get_slice_count(memview) <= 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; + if (last_time) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } + } else { + memslice->memview = NULL; + } +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +#if CYTHON_COMPILING_IN_CPYTHON +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) +#else + if (likely(PyString_Check(n))) +#endif + return __Pyx_PyObject_GetAttrStr(o, n); +#endif + return PyObject_GetAttr(o, n); +} + +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r = __Pyx_GetAttr(o, n); + if (!r) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + goto bad; + PyErr_Clear(); + r = d; + Py_INCREF(d); + } + return r; +bad: + return NULL; +} + +static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { + Py_ssize_t q = a / b; + Py_ssize_t r = a - q*b; + q -= ((r != 0) & ((r ^ b) < 0)); + return q; +} + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyUnicode_CheckExact(s1) & PyUnicode_CheckExact(s2)) { + #if CYTHON_PEP393_ENABLED + if ((PyUnicode_READY(s1) < 0) || (PyUnicode_READY(s2) < 0)) + return -1; + if (PyUnicode_GET_LENGTH(s1) != PyUnicode_GET_LENGTH(s2)) { + return (equals == Py_NE); + } else if (PyUnicode_GET_LENGTH(s1) == 1) { + Py_UCS4 ch1 = PyUnicode_READ_CHAR(s1, 0); + Py_UCS4 ch2 = PyUnicode_READ_CHAR(s2, 0); + return (equals == Py_EQ) ? (ch1 == ch2) : (ch1 != ch2); + #else + if (PyUnicode_GET_SIZE(s1) != PyUnicode_GET_SIZE(s2)) { + return (equals == Py_NE); + } else if (PyUnicode_GET_SIZE(s1) == 1) { + Py_UNICODE ch1 = PyUnicode_AS_UNICODE(s1)[0]; + Py_UNICODE ch2 = PyUnicode_AS_UNICODE(s2)[0]; + return (equals == Py_EQ) ? (ch1 == ch2) : (ch1 != ch2); + #endif + } else { + int result = PyUnicode_Compare(s1, s2); + if ((result == -1) && unlikely(PyErr_Occurred())) + return -1; + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyUnicode_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyUnicode_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + length = strlen(cstring); + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + #endif + Py_INCREF(local_type); + Py_INCREF(local_value); + Py_INCREF(local_tb); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_COMPILING_IN_CPYTHON + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + /* Make sure tstate is in a consistent state when we XDECREF + these objects (DECREF may run arbitrary code). */ + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +static CYTHON_INLINE long __Pyx_div_long(long a, long b) { + long q = a / b; + long r = a - q*b; + q -= ((r != 0) & ((r ^ b) < 0)); + return q; +} + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s____pyx_vtable__, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); + if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } + } + #endif + PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s____pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: + Py_DECREF(obj); + view->obj = NULL; +} +#endif /* PY_MAJOR_VERSION < 3 */ + + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s____import__); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_from_py_Py_intptr_t(PyObject* x) { + const Py_intptr_t neg_one = (Py_intptr_t)-1, const_zero = (Py_intptr_t)0; + const int is_unsigned = const_zero < neg_one; + if (sizeof(Py_intptr_t) == sizeof(char)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedChar(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedChar(x); + } else if (sizeof(Py_intptr_t) == sizeof(short)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedShort(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedShort(x); + } else if (sizeof(Py_intptr_t) == sizeof(int)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedInt(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedInt(x); + } else if (sizeof(Py_intptr_t) == sizeof(long)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedLong(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedLong(x); + } else if (sizeof(Py_intptr_t) == sizeof(PY_LONG_LONG)) { + if (is_unsigned) + return (Py_intptr_t)__Pyx_PyInt_AsUnsignedLongLong(x); + else + return (Py_intptr_t)__Pyx_PyInt_AsSignedLongLong(x); + } else { + #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); + #else + Py_intptr_t val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } + #endif + return (Py_intptr_t)-1; + } +} + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_Py_intptr_t(Py_intptr_t val) { + const Py_intptr_t neg_one = (Py_intptr_t)-1, const_zero = (Py_intptr_t)0; + const int is_unsigned = const_zero < neg_one; + if ((sizeof(Py_intptr_t) == sizeof(char)) || + (sizeof(Py_intptr_t) == sizeof(short))) { + return PyInt_FromLong((long)val); + } else if ((sizeof(Py_intptr_t) == sizeof(int)) || + (sizeof(Py_intptr_t) == sizeof(long))) { + if (is_unsigned) + return PyLong_FromUnsignedLong((unsigned long)val); + else + return PyInt_FromLong((long)val); + } else if (sizeof(Py_intptr_t) == sizeof(PY_LONG_LONG)) { + if (is_unsigned) + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); + else + return PyLong_FromLongLong((PY_LONG_LONG)val); + } else { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); + } +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +static int +__pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, + char order, int ndim) +{ + int i, index, step, start; + Py_ssize_t itemsize = mvs->memview->view.itemsize; + if (order == 'F') { + step = 1; + start = 0; + } else { + step = -1; + start = ndim - 1; + } + for (i = 0; i < ndim; i++) { + index = start + step * i; + if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) + return 0; + itemsize *= mvs->shape[index]; + } + return 1; +} + +static void +__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + start = end = slice->data; + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + if (extent == 0) { + *out_start = *out_end = start; + return; + } else { + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); + } + } + *out_start = start; + *out_end = end + itemsize; +} +static int +__pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize) +{ + void *start1, *end1, *start2, *end2; + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + return (start1 < end2) && (start2 < end1); +} + +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + for (i = 0; i < ndim; i++) { + if (from_mvs->suboffsets[i] >= 0) { + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; + } + } + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; + } + __Pyx_GOTREF(shape_tuple); + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromLong(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; + } else { + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; + } + } + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + goto no_fail; +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; +} + +static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) +{ + PyObject *cobj; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); +#endif + return cobj; +} + +static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +#else + PyErr_GetExcInfo(type, value, tb); +#endif +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(type, value, tb); +#endif +} + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { + const unsigned char neg_one = (unsigned char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned char" : + "value too large to convert to unsigned char"); + } + return (unsigned char)-1; + } + return (unsigned char)val; + } + return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { + const unsigned short neg_one = (unsigned short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned short" : + "value too large to convert to unsigned short"); + } + return (unsigned short)-1; + } + return (unsigned short)val; + } + return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { + const unsigned int neg_one = (unsigned int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned int" : + "value too large to convert to unsigned int"); + } + return (unsigned int)-1; + } + return (unsigned int)val; + } + return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { + const char neg_one = (char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to char" : + "value too large to convert to char"); + } + return (char)-1; + } + return (char)val; + } + return (char)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { + const short neg_one = (short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to short" : + "value too large to convert to short"); + } + return (short)-1; + } + return (short)val; + } + return (short)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { + const signed char neg_one = (signed char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed char" : + "value too large to convert to signed char"); + } + return (signed char)-1; + } + return (signed char)val; + } + return (signed char)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { + const signed short neg_one = (signed short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed short" : + "value too large to convert to signed short"); + } + return (signed short)-1; + } + return (signed short)val; + } + return (signed short)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { + const signed int neg_one = (signed int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed int" : + "value too large to convert to signed int"); + } + return (signed int)-1; + } + return (signed int)val; + } + return (signed int)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { + const unsigned long neg_one = (unsigned long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (unsigned long)PyLong_AsLong(x); + } + } else { + unsigned long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned long)-1; + val = __Pyx_PyInt_AsUnsignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { + const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + unsigned PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsUnsignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { + const long neg_one = (long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (long)PyLong_AsLong(x); + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long)-1; + val = __Pyx_PyInt_AsLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { + const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { + const signed long neg_one = (signed long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)PyLong_AsUnsignedLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (signed long)PyLong_AsLong(x); + } + } else { + signed long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed long)-1; + val = __Pyx_PyInt_AsSignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS +#include "longintrepr.h" +#endif +#endif +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { + const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +#if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; + } + } +#endif +#endif + return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + signed PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsSignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; +#else + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); +#endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} + +static PyObject *__Pyx_Generator_Next(PyObject *self); +static PyObject *__Pyx_Generator_Send(PyObject *self, PyObject *value); +static PyObject *__Pyx_Generator_Close(PyObject *self); +static PyObject *__Pyx_Generator_Throw(PyObject *gen, PyObject *args); +static PyTypeObject *__pyx_GeneratorType = 0; +#define __Pyx_Generator_CheckExact(obj) (Py_TYPE(obj) == __pyx_GeneratorType) +#define __Pyx_Generator_Undelegate(gen) Py_CLEAR((gen)->yieldfrom) +#if 1 || PY_VERSION_HEX < 0x030300B0 +static int __Pyx_PyGen_FetchStopIterationValue(PyObject **pvalue) { + PyObject *et, *ev, *tb; + PyObject *value = NULL; + __Pyx_ErrFetch(&et, &ev, &tb); + if (!et) { + Py_XDECREF(tb); + Py_XDECREF(ev); + Py_INCREF(Py_None); + *pvalue = Py_None; + return 0; + } + if (unlikely(et != PyExc_StopIteration) && + unlikely(!PyErr_GivenExceptionMatches(et, PyExc_StopIteration))) { + __Pyx_ErrRestore(et, ev, tb); + return -1; + } + if (likely(et == PyExc_StopIteration)) { + if (likely(!ev) || !PyObject_IsInstance(ev, PyExc_StopIteration)) { + if (!ev) { + Py_INCREF(Py_None); + ev = Py_None; + } + Py_XDECREF(tb); + Py_DECREF(et); + *pvalue = ev; + return 0; + } + } + PyErr_NormalizeException(&et, &ev, &tb); + if (unlikely(!PyObject_IsInstance(ev, PyExc_StopIteration))) { + __Pyx_ErrRestore(et, ev, tb); + return -1; + } + Py_XDECREF(tb); + Py_DECREF(et); +#if PY_VERSION_HEX >= 0x030300A0 + value = ((PyStopIterationObject *)ev)->value; + Py_INCREF(value); + Py_DECREF(ev); +#else + { + PyObject* args = PyObject_GetAttr(ev, __pyx_n_s__args); + Py_DECREF(ev); + if (likely(args)) { + value = PyObject_GetItem(args, 0); + Py_DECREF(args); + } + if (unlikely(!value)) { + __Pyx_ErrRestore(NULL, NULL, NULL); + Py_INCREF(Py_None); + value = Py_None; + } + } +#endif + *pvalue = value; + return 0; +} +#endif +static CYTHON_INLINE +void __Pyx_Generator_ExceptionClear(__pyx_GeneratorObject *self) { + PyObject *exc_type = self->exc_type; + PyObject *exc_value = self->exc_value; + PyObject *exc_traceback = self->exc_traceback; + self->exc_type = NULL; + self->exc_value = NULL; + self->exc_traceback = NULL; + Py_XDECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_traceback); +} +static CYTHON_INLINE +int __Pyx_Generator_CheckRunning(__pyx_GeneratorObject *gen) { + if (unlikely(gen->is_running)) { + PyErr_SetString(PyExc_ValueError, + "generator already executing"); + return 1; + } + return 0; +} +static CYTHON_INLINE +PyObject *__Pyx_Generator_SendEx(__pyx_GeneratorObject *self, PyObject *value) { + PyObject *retval; + assert(!self->is_running); + if (unlikely(self->resume_label == 0)) { + if (unlikely(value && value != Py_None)) { + PyErr_SetString(PyExc_TypeError, + "can't send non-None value to a " + "just-started generator"); + return NULL; + } + } + if (unlikely(self->resume_label == -1)) { + PyErr_SetNone(PyExc_StopIteration); + return NULL; + } + if (value) { +#if CYTHON_COMPILING_IN_PYPY +#else + /* Generators always return to their most recent caller, not + * necessarily their creator. */ + if (self->exc_traceback) { + PyThreadState *tstate = PyThreadState_GET(); + PyTracebackObject *tb = (PyTracebackObject *) self->exc_traceback; + PyFrameObject *f = tb->tb_frame; + Py_XINCREF(tstate->frame); + assert(f->f_back == NULL); + f->f_back = tstate->frame; + } +#endif + __Pyx_ExceptionSwap(&self->exc_type, &self->exc_value, + &self->exc_traceback); + } else { + __Pyx_Generator_ExceptionClear(self); + } + self->is_running = 1; + retval = self->body((PyObject *) self, value); + self->is_running = 0; + if (retval) { + __Pyx_ExceptionSwap(&self->exc_type, &self->exc_value, + &self->exc_traceback); +#if CYTHON_COMPILING_IN_PYPY +#else + /* Don't keep the reference to f_back any longer than necessary. It + * may keep a chain of frames alive or it could create a reference + * cycle. */ + if (self->exc_traceback) { + PyTracebackObject *tb = (PyTracebackObject *) self->exc_traceback; + PyFrameObject *f = tb->tb_frame; + Py_CLEAR(f->f_back); + } +#endif + } else { + __Pyx_Generator_ExceptionClear(self); + } + return retval; +} +static CYTHON_INLINE +PyObject *__Pyx_Generator_FinishDelegation(__pyx_GeneratorObject *gen) { + PyObject *ret; + PyObject *val = NULL; + __Pyx_Generator_Undelegate(gen); + __Pyx_PyGen_FetchStopIterationValue(&val); + ret = __Pyx_Generator_SendEx(gen, val); + Py_XDECREF(val); + return ret; +} +static PyObject *__Pyx_Generator_Next(PyObject *self) { + __pyx_GeneratorObject *gen = (__pyx_GeneratorObject*) self; + PyObject *yf = gen->yieldfrom; + if (unlikely(__Pyx_Generator_CheckRunning(gen))) + return NULL; + if (yf) { + PyObject *ret; + gen->is_running = 1; + ret = Py_TYPE(yf)->tp_iternext(yf); + gen->is_running = 0; + if (likely(ret)) { + return ret; + } + return __Pyx_Generator_FinishDelegation(gen); + } + return __Pyx_Generator_SendEx(gen, Py_None); +} +static PyObject *__Pyx_Generator_Send(PyObject *self, PyObject *value) { + __pyx_GeneratorObject *gen = (__pyx_GeneratorObject*) self; + PyObject *yf = gen->yieldfrom; + if (unlikely(__Pyx_Generator_CheckRunning(gen))) + return NULL; + if (yf) { + PyObject *ret; + gen->is_running = 1; + if (__Pyx_Generator_CheckExact(yf)) { + ret = __Pyx_Generator_Send(yf, value); + } else { + if (value == Py_None) + ret = PyIter_Next(yf); + else + ret = __Pyx_PyObject_CallMethod1(yf, __pyx_n_s__send, value); + } + gen->is_running = 0; + if (likely(ret)) { + return ret; + } + return __Pyx_Generator_FinishDelegation(gen); + } + return __Pyx_Generator_SendEx(gen, value); +} +static int __Pyx_Generator_CloseIter(__pyx_GeneratorObject *gen, PyObject *yf) { + PyObject *retval = NULL; + int err = 0; + if (__Pyx_Generator_CheckExact(yf)) { + retval = __Pyx_Generator_Close(yf); + if (!retval) + return -1; + } else { + PyObject *meth; + gen->is_running = 1; + meth = PyObject_GetAttr(yf, __pyx_n_s__close); + if (unlikely(!meth)) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_WriteUnraisable(yf); + } + PyErr_Clear(); + } else { + retval = PyObject_CallFunction(meth, NULL); + Py_DECREF(meth); + if (!retval) + err = -1; + } + gen->is_running = 0; + } + Py_XDECREF(retval); + return err; +} +static PyObject *__Pyx_Generator_Close(PyObject *self) { + __pyx_GeneratorObject *gen = (__pyx_GeneratorObject *) self; + PyObject *retval, *raised_exception; + PyObject *yf = gen->yieldfrom; + int err = 0; + if (unlikely(__Pyx_Generator_CheckRunning(gen))) + return NULL; + if (yf) { + Py_INCREF(yf); + err = __Pyx_Generator_CloseIter(gen, yf); + __Pyx_Generator_Undelegate(gen); + Py_DECREF(yf); + } + if (err == 0) +#if PY_VERSION_HEX < 0x02050000 + PyErr_SetNone(PyExc_StopIteration); +#else + PyErr_SetNone(PyExc_GeneratorExit); +#endif + retval = __Pyx_Generator_SendEx(gen, NULL); + if (retval) { + Py_DECREF(retval); + PyErr_SetString(PyExc_RuntimeError, + "generator ignored GeneratorExit"); + return NULL; + } + raised_exception = PyErr_Occurred(); + if (!raised_exception + || raised_exception == PyExc_StopIteration +#if PY_VERSION_HEX >= 0x02050000 + || raised_exception == PyExc_GeneratorExit + || PyErr_GivenExceptionMatches(raised_exception, PyExc_GeneratorExit) +#endif + || PyErr_GivenExceptionMatches(raised_exception, PyExc_StopIteration)) + { + if (raised_exception) PyErr_Clear(); /* ignore these errors */ + Py_INCREF(Py_None); + return Py_None; + } + return NULL; +} +static PyObject *__Pyx_Generator_Throw(PyObject *self, PyObject *args) { + __pyx_GeneratorObject *gen = (__pyx_GeneratorObject *) self; + PyObject *typ; + PyObject *tb = NULL; + PyObject *val = NULL; + PyObject *yf = gen->yieldfrom; + if (!PyArg_UnpackTuple(args, (char *)"throw", 1, 3, &typ, &val, &tb)) + return NULL; + if (unlikely(__Pyx_Generator_CheckRunning(gen))) + return NULL; + if (yf) { + PyObject *ret; + Py_INCREF(yf); +#if PY_VERSION_HEX >= 0x02050000 + if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit)) { + int err = __Pyx_Generator_CloseIter(gen, yf); + Py_DECREF(yf); + __Pyx_Generator_Undelegate(gen); + if (err < 0) + return __Pyx_Generator_SendEx(gen, NULL); + goto throw_here; + } +#endif + gen->is_running = 1; + if (__Pyx_Generator_CheckExact(yf)) { + ret = __Pyx_Generator_Throw(yf, args); + } else { + PyObject *meth = PyObject_GetAttr(yf, __pyx_n_s__throw); + if (unlikely(!meth)) { + Py_DECREF(yf); + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { + gen->is_running = 0; + return NULL; + } + PyErr_Clear(); + __Pyx_Generator_Undelegate(gen); + gen->is_running = 0; + goto throw_here; + } + ret = PyObject_CallObject(meth, args); + Py_DECREF(meth); + } + gen->is_running = 0; + Py_DECREF(yf); + if (!ret) { + ret = __Pyx_Generator_FinishDelegation(gen); + } + return ret; + } +throw_here: + __Pyx_Raise(typ, val, tb, NULL); + return __Pyx_Generator_SendEx(gen, NULL); +} +static int __Pyx_Generator_traverse(PyObject *self, visitproc visit, void *arg) { + __pyx_GeneratorObject *gen = (__pyx_GeneratorObject *) self; + Py_VISIT(gen->closure); + Py_VISIT(gen->classobj); + Py_VISIT(gen->yieldfrom); + Py_VISIT(gen->exc_type); + Py_VISIT(gen->exc_value); + Py_VISIT(gen->exc_traceback); + return 0; +} +static int __Pyx_Generator_clear(PyObject *self) { + __pyx_GeneratorObject *gen = (__pyx_GeneratorObject *) self; + Py_CLEAR(gen->closure); + Py_CLEAR(gen->classobj); + Py_CLEAR(gen->yieldfrom); + Py_CLEAR(gen->exc_type); + Py_CLEAR(gen->exc_value); + Py_CLEAR(gen->exc_traceback); + return 0; +} +static void __Pyx_Generator_dealloc(PyObject *self) { + __pyx_GeneratorObject *gen = (__pyx_GeneratorObject *) self; + PyObject_GC_UnTrack(gen); + if (gen->gi_weakreflist != NULL) + PyObject_ClearWeakRefs(self); + PyObject_GC_Track(self); + if (gen->resume_label > 0) { + Py_TYPE(gen)->tp_del(self); + if (self->ob_refcnt > 0) + return; /* resurrected. :( */ + } + PyObject_GC_UnTrack(self); + __Pyx_Generator_clear(self); + PyObject_GC_Del(gen); +} +static void __Pyx_Generator_del(PyObject *self) { + PyObject *res; + PyObject *error_type, *error_value, *error_traceback; + __pyx_GeneratorObject *gen = (__pyx_GeneratorObject *) self; + if (gen->resume_label <= 0) + return ; + assert(self->ob_refcnt == 0); + self->ob_refcnt = 1; + __Pyx_ErrFetch(&error_type, &error_value, &error_traceback); + res = __Pyx_Generator_Close(self); + if (res == NULL) + PyErr_WriteUnraisable(self); + else + Py_DECREF(res); + __Pyx_ErrRestore(error_type, error_value, error_traceback); + /* Undo the temporary resurrection; can't use DECREF here, it would + * cause a recursive call. + */ + assert(self->ob_refcnt > 0); + if (--self->ob_refcnt == 0) + return; /* this is the normal path out */ + /* close() resurrected it! Make it look like the original Py_DECREF + * never happened. + */ + { + Py_ssize_t refcnt = self->ob_refcnt; + _Py_NewReference(self); + self->ob_refcnt = refcnt; + } +#if CYTHON_COMPILING_IN_CPYTHON + assert(PyType_IS_GC(self->ob_type) && + _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); + /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so + * we need to undo that. */ + _Py_DEC_REFTOTAL; +#endif + /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object + * chain, so no more to do there. + * If COUNT_ALLOCS, the original decref bumped tp_frees, and + * _Py_NewReference bumped tp_allocs: both of those need to be + * undone. + */ +#ifdef COUNT_ALLOCS + --Py_TYPE(self)->tp_frees; + --Py_TYPE(self)->tp_allocs; +#endif +} +static PyMemberDef __pyx_Generator_memberlist[] = { + {(char *) "gi_running", +#if PY_VERSION_HEX >= 0x02060000 + T_BOOL, +#else + T_BYTE, +#endif + offsetof(__pyx_GeneratorObject, is_running), + READONLY, + NULL}, + {0, 0, 0, 0, 0} +}; +static PyMethodDef __pyx_Generator_methods[] = { + {__Pyx_NAMESTR("send"), (PyCFunction) __Pyx_Generator_Send, METH_O, 0}, + {__Pyx_NAMESTR("throw"), (PyCFunction) __Pyx_Generator_Throw, METH_VARARGS, 0}, + {__Pyx_NAMESTR("close"), (PyCFunction) __Pyx_Generator_Close, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; +static PyTypeObject __pyx_GeneratorType_type = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("generator"), /*tp_name*/ + sizeof(__pyx_GeneratorObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor) __Pyx_Generator_dealloc,/*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ +#if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ +#else + 0, /*reserved*/ +#endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags*/ + 0, /*tp_doc*/ + (traverseproc) __Pyx_Generator_traverse, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + offsetof(__pyx_GeneratorObject, gi_weakreflist), /* tp_weaklistoffse */ + 0, /*tp_iter*/ + (iternextfunc) __Pyx_Generator_Next, /*tp_iternext*/ + __pyx_Generator_methods, /*tp_methods*/ + __pyx_Generator_memberlist, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + __Pyx_Generator_del, /*tp_del*/ +#if PY_VERSION_HEX >= 0x02060000 + 0, /*tp_version_tag*/ +#endif +}; +static __pyx_GeneratorObject *__Pyx_Generator_New(__pyx_generator_body_t body, + PyObject *closure) { + __pyx_GeneratorObject *gen = + PyObject_GC_New(__pyx_GeneratorObject, &__pyx_GeneratorType_type); + if (gen == NULL) + return NULL; + gen->body = body; + gen->closure = closure; + Py_XINCREF(closure); + gen->is_running = 0; + gen->resume_label = 0; + gen->classobj = NULL; + gen->yieldfrom = NULL; + gen->exc_type = NULL; + gen->exc_value = NULL; + gen->exc_traceback = NULL; + gen->gi_weakreflist = NULL; + PyObject_GC_Track(gen); + return gen; +} +static int __pyx_Generator_init(void) { + __pyx_GeneratorType_type.tp_getattro = PyObject_GenericGetAttr; + __pyx_GeneratorType_type.tp_iter = PyObject_SelfIter; + if (PyType_Ready(&__pyx_GeneratorType_type)) { + return -1; + } + __pyx_GeneratorType = &__pyx_GeneratorType_type; + return 0; +} + +static int +__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) +{ + int i; + if (!a || !b) + return 0; + if (a == b) + return 1; + if (a->size != b->size || a->typegroup != b->typegroup || + a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { + if (a->typegroup == 'H' || b->typegroup == 'H') { + return a->size == b->size; + } else { + return 0; + } + } + if (a->ndim) { + for (i = 0; i < a->ndim; i++) + if (a->arraysize[i] != b->arraysize[i]) + return 0; + } + if (a->typegroup == 'S') { + if (a->flags != b->flags) + return 0; + if (a->fields || b->fields) { + if (!(a->fields && b->fields)) + return 0; + for (i = 0; a->fields[i].type && b->fields[i].type; i++) { + __Pyx_StructField *field_a = a->fields + i; + __Pyx_StructField *field_b = b->fields + i; + if (field_a->offset != field_b->offset || + !__pyx_typeinfo_cmp(field_a->type, field_b->type)) + return 0; + } + return !a->fields[i].type && !b->fields[i].type; + } + } + return 1; +} + +static int +__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) +{ + if (buf->shape[dim] <= 1) + return 1; + if (buf->strides) { + if (spec & __Pyx_MEMVIEW_CONTIG) { + if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { + if (buf->strides[dim] != sizeof(void *)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly contiguous " + "in dimension %d.", dim); + goto fail; + } + } else if (buf->strides[dim] != buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_FOLLOW) { + Py_ssize_t stride = buf->strides[dim]; + if (stride < 0) + stride = -stride; + if (stride < buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + } else { + if (spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not contiguous in " + "dimension %d", dim); + goto fail; + } else if (spec & (__Pyx_MEMVIEW_PTR)) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not indirect in " + "dimension %d", dim); + goto fail; + } else if (buf->suboffsets) { + PyErr_SetString(PyExc_ValueError, + "Buffer exposes suboffsets but no strides"); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) +{ + if (spec & __Pyx_MEMVIEW_DIRECT) { + if (buf->suboffsets && buf->suboffsets[dim] >= 0) { + PyErr_Format(PyExc_ValueError, + "Buffer not compatible with direct access " + "in dimension %d.", dim); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_PTR) { + if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly accessisble " + "in dimension %d.", dim); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) +{ + int i; + if (c_or_f_flag & __Pyx_IS_F_CONTIG) { + Py_ssize_t stride = 1; + for (i = 0; i < ndim; i++) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) + { + PyErr_SetString(PyExc_ValueError, + "Buffer not fortran contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { + Py_ssize_t stride = 1; + for (i = ndim - 1; i >- 1; i--) { + if (stride * buf->itemsize != buf->strides[i] && + buf->shape[i] > 1) { + PyErr_SetString(PyExc_ValueError, + "Buffer not C contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } + return 1; +fail: + return 0; +} +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj) +{ + struct __pyx_memoryview_obj *memview, *new_memview; + __Pyx_RefNannyDeclarations + Py_buffer *buf; + int i, spec = 0, retval = -1; + __Pyx_BufFmt_Context ctx; + int from_memoryview = __pyx_memoryview_check(original_obj); + __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); + if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) + original_obj)->typeinfo)) { + memview = (struct __pyx_memoryview_obj *) original_obj; + new_memview = NULL; + } else { + memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + original_obj, buf_flags, 0, dtype); + new_memview = memview; + if (unlikely(!memview)) + goto fail; + } + buf = &memview->view; + if (buf->ndim != ndim) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + ndim, buf->ndim); + goto fail; + } + if (new_memview) { + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned) buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " + "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", + buf->itemsize, + (buf->itemsize > 1) ? "s" : "", + dtype->name, + dtype->size, + (dtype->size > 1) ? "s" : ""); + goto fail; + } + for (i = 0; i < ndim; i++) { + spec = axes_specs[i]; + if (!__pyx_check_strides(buf, i, ndim, spec)) + goto fail; + if (!__pyx_check_suboffsets(buf, i, ndim, spec)) + goto fail; + } + if (buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, + new_memview != NULL) == -1)) { + goto fail; + } + retval = 0; + goto no_fail; +fail: + Py_XDECREF(new_memview); + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS, 1, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_9fast_dict_ITYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t(PyObject *obj) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS, 1, + &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_9fast_dict_DTYPE_t, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%s.%s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + #if PY_VERSION_HEX < 0x02050000 + if (PyErr_Warn(NULL, warning) < 0) goto bad; + #else + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + #endif + } + else if ((size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%s.%s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (r < 0) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_MAJOR_VERSION < 3 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%s__ returned non-%s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject* x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { + unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); + if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); + return (size_t)-1; + } + return (size_t)val; +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/utils/fast_dict.pxd b/sklearn/utils/fast_dict.pxd new file mode 100644 index 0000000000000..5893c53ac541f --- /dev/null +++ b/sklearn/utils/fast_dict.pxd @@ -0,0 +1,24 @@ +""" +Uses C++ map containers for fast dict-like behavior with keys being +integers, and values float. +""" +# Author: Gael Varoquaux +# License: BSD + +from libcpp.map cimport map as cpp_map + +# Import the C-level symbols of numpy +cimport numpy as np + +DTYPE = np.float64 +ctypedef np.float64_t DTYPE_t + +ITYPE = np.intp +ctypedef np.intp_t ITYPE_t + +############################################################################### +# An object to be used in Python + +cdef class IntFloatDict: + cdef cpp_map[ITYPE_t, DTYPE_t] my_map + cdef _to_arrays(self, ITYPE_t [:] keys, DTYPE_t [:] values) diff --git a/sklearn/utils/fast_dict.pyx b/sklearn/utils/fast_dict.pyx new file mode 100644 index 0000000000000..719cafc3cc8c1 --- /dev/null +++ b/sklearn/utils/fast_dict.pyx @@ -0,0 +1,155 @@ +""" +Uses C++ map containers for fast dict-like behavior with keys being +integers, and values float. +""" +# Author: Gael Varoquaux +# License: BSD + +cimport cython + +# C++ +from cython.operator cimport dereference as deref, preincrement as inc, \ + predecrement as dec +from libcpp.utility cimport pair +from libcpp.map cimport map as cpp_map + +import numpy as np + +# Import the C-level symbols of numpy +cimport numpy as np + +# Numpy must be initialized. When using numpy from C or Cython you must +# _always_ do that, or you will have segfaults +np.import_array() + +#DTYPE = np.float64 +#ctypedef np.float64_t DTYPE_t + +#ITYPE = np.intp +#ctypedef np.intp_t ITYPE_t + +############################################################################### +# An object to be used in Python + +# Lookup is faster than dict (up to 10 times), and so is full traversal +# (up to 50 times), and assignment (up to 6 times), but creation is +# slower (up to 3 times). Also, a large benefit is that memory +# consumption is reduced a lot compared to a Python dict + +cdef class IntFloatDict: + + @cython.boundscheck(False) + @cython.wraparound(False) + def __init__(self, np.ndarray[ITYPE_t, ndim=1] keys, + np.ndarray[DTYPE_t, ndim=1] values): + cdef int i + cdef int size = values.size + # Should check that sizes for keys and values are equal, and + # after should boundcheck(False) + for i in range(size): + self.my_map[keys[i]] = values[i] + + def __len__(self): + return self.my_map.size() + + def __getitem__(self, int key): + cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = self.my_map.find(key) + if it == self.my_map.end(): + # The key is not in the dict + raise KeyError('%i' % key) + return deref(it).second + + def __setitem__(self, int key, float value): + self.my_map[key] = value + + # Cython 0.20 generates buggy code below. Commenting this out for now + # and relying on the to_arrays method + #def __iter__(self): + # cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = self.my_map.begin() + # cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = self.my_map.end() + # while it != end: + # yield deref(it).first, deref(it).second + # inc(it) + + def __iter__(self): + cdef int size = self.my_map.size() + cdef ITYPE_t [:] keys = np.empty(size, dtype=np.intp) + cdef DTYPE_t [:] values = np.empty(size, dtype=np.float64) + self._to_arrays(keys, values) + cdef int idx + cdef ITYPE_t key + cdef DTYPE_t value + for idx in range(size): + key = keys[idx] + value = values[idx] + yield key, value + + def to_arrays(self): + """Return the key, value representation of the IntFloatDict + object. + + Returns + ======= + keys : ndarray, shape (n_items, ), dtype=int + The indices of the data points + values : ndarray, shape (n_items, ), dtype=float + The values of the data points + """ + cdef int size = self.my_map.size() + cdef np.ndarray[ITYPE_t, ndim=1] keys = np.empty(size, + dtype=np.intp) + cdef np.ndarray[DTYPE_t, ndim=1] values = np.empty(size, + dtype=np.float64) + self._to_arrays(keys, values) + return keys, values + + cdef _to_arrays(self, ITYPE_t [:] keys, DTYPE_t [:] values): + # Internal version of to_arrays that takes already-initialized arrays + cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = self.my_map.begin() + cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = self.my_map.end() + cdef int index = 0 + while it != end: + keys[index] = deref(it).first + values[index] = deref(it).second + inc(it) + index += 1 + + def update(self, IntFloatDict other): + cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = other.my_map.begin() + cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = other.my_map.end() + while it != end: + self.my_map[deref(it).first] = deref(it).second + inc(it) + + def copy(self): + cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) + # The '=' operator is a copy operator for C++ maps + out_obj.my_map = self.my_map + return out_obj + + def append(self, ITYPE_t key, DTYPE_t value): + cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = self.my_map.end() + # Decrement the iterator + dec(end) + # Construct our arguments + cdef pair[ITYPE_t, DTYPE_t] args + args.first = key + args.second = value + self.my_map.insert(end, args) + + +############################################################################### +# operation on dict + +def argmin(IntFloatDict d): + cdef cpp_map[ITYPE_t, DTYPE_t].iterator it = d.my_map.begin() + cdef cpp_map[ITYPE_t, DTYPE_t].iterator end = d.my_map.end() + cdef ITYPE_t min_key + cdef DTYPE_t min_value = np.inf + while it != end: + if deref(it).second < min_value: + min_value = deref(it).second + min_key = deref(it).first + inc(it) + return min_key, min_value + diff --git a/sklearn/utils/fixes.py b/sklearn/utils/fixes.py index 9ac402ce244bb..e0f10bcae8e4e 100644 --- a/sklearn/utils/fixes.py +++ b/sklearn/utils/fixes.py @@ -6,173 +6,348 @@ # Authors: Emmanuelle Gouillart # Gael Varoquaux # Fabian Pedregosa -# Lars Buitinck -# License: BSD +# Lars Buitinck +# +# License: BSD 3 clause + +import inspect +import warnings +import sys +import functools -import collections import numpy as np -from operator import itemgetter +import scipy.sparse as sp +import scipy + + +def _parse_version(version_string): + version = [] + for x in version_string.split('.'): + try: + version.append(int(x)) + except ValueError: + # x may be of the form dev-1ea1592 + version.append(x) + return tuple(version) + + +np_version = _parse_version(np.__version__) +sp_version = _parse_version(scipy.__version__) try: - Counter = collections.Counter -except AttributeError: - class Counter(collections.defaultdict): - """Partial replacement for Python 2.7 collections.Counter.""" - def __init__(self, iterable=(), **kwargs): - super(Counter, self).__init__(int, **kwargs) - self.update(iterable) - - def most_common(self): - return sorted(self.iteritems(), key=itemgetter(1), reverse=True) - - def update(self, other): - """Adds counts for elements in other""" - if isinstance(other, self.__class__): - for x, n in other.iteritems(): - self[x] += n - else: - for x in other: - self[x] += 1 - - -def lsqr(X, y, tol=1e-3): - import scipy.sparse.linalg as sp_linalg - from ..utils.extmath import safe_sparse_dot - - if hasattr(sp_linalg, 'lsqr'): - # scipy 0.8 or greater - return sp_linalg.lsqr(X, y) - else: - n_samples, n_features = X.shape - if n_samples > n_features: - coef, _ = sp_linalg.cg(safe_sparse_dot(X.T, X), - safe_sparse_dot(X.T, y), - tol=tol) + from scipy.special import expit # SciPy >= 0.10 + with np.errstate(invalid='ignore', over='ignore'): + if np.isnan(expit(1000)): # SciPy < 0.14 + raise ImportError("no stable expit in scipy.special") +except ImportError: + def expit(x, out=None): + """Logistic sigmoid function, ``1 / (1 + exp(-x))``. + + See sklearn.utils.extmath.log_logistic for the log of this function. + """ + if out is None: + out = np.empty(np.atleast_1d(x).shape, dtype=np.float64) + out[:] = x + + # 1 / (1 + exp(-x)) = (1 + tanh(x / 2)) / 2 + # This way of computing the logistic is both fast and stable. + out *= .5 + np.tanh(out, out) + out += 1 + out *= .5 + + return out.reshape(np.shape(x)) + + +# little danse to see if np.copy has an 'order' keyword argument +if 'order' in inspect.getargspec(np.copy)[0]: + def safe_copy(X): + # Copy, but keep the order + return np.copy(X, order='K') +else: + # Before an 'order' argument was introduced, numpy wouldn't muck with + # the ordering + safe_copy = np.copy + +try: + if (not np.allclose(np.divide(.4, 1, casting="unsafe"), + np.divide(.4, 1, casting="unsafe", dtype=np.float)) + or not np.allclose(np.divide(.4, 1), .4)): + raise TypeError('Divide not working with dtype: ' + 'https://github.com/numpy/numpy/issues/3484') + divide = np.divide + +except TypeError: + # Compat for old versions of np.divide that do not provide support for + # the dtype args + def divide(x1, x2, out=None, dtype=None): + out_orig = out + if out is None: + out = np.asarray(x1, dtype=dtype) + if out is x1: + out = x1.copy() else: - coef, _ = sp_linalg.cg(safe_sparse_dot(X, X.T), y, tol=tol) - coef = safe_sparse_dot(X.T, coef) + if out is not x1: + out[:] = x1 + if dtype is not None and out.dtype != dtype: + out = out.astype(dtype) + out /= x2 + if out_orig is None and np.isscalar(x1): + out = np.asscalar(out) + return out + + +try: + np.array(5).astype(float, copy=False) +except TypeError: + # Compat where astype accepted no copy argument + def astype(array, dtype, copy=True): + if array.dtype == dtype: + return array + return array.astype(dtype) +else: + astype = np.ndarray.astype + - residues = y - safe_sparse_dot(X, coef) - return coef, None, None, residues +try: + with warnings.catch_warnings(record=True): + # Don't raise the numpy deprecation warnings that appear in + # 1.9, but avoid Python bug due to simplefilter('ignore') + warnings.simplefilter('always') + sp.csr_matrix([1.0, 2.0, 3.0]).max(axis=0) +except (TypeError, AttributeError): + # in scipy < 14.0, sparse matrix min/max doesn't accept an `axis` argument + # the following code is taken from the scipy 0.14 codebase + def _minor_reduce(X, ufunc): + major_index = np.flatnonzero(np.diff(X.indptr)) + if X.data.size == 0 and major_index.size == 0: + # Numpy < 1.8.0 don't handle empty arrays in reduceat + value = np.zeros_like(X.data) + else: + value = ufunc.reduceat(X.data, X.indptr[major_index]) + return major_index, value -def _unique(ar, return_index=False, return_inverse=False): - """A replacement for the np.unique that appeared in numpy 1.4. + def _min_or_max_axis(X, axis, min_or_max): + N = X.shape[axis] + if N == 0: + raise ValueError("zero-size array to reduction operation") + M = X.shape[1 - axis] + mat = X.tocsc() if axis == 0 else X.tocsr() + mat.sum_duplicates() + major_index, value = _minor_reduce(mat, min_or_max) + not_full = np.diff(mat.indptr)[major_index] < N + value[not_full] = min_or_max(value[not_full], 0) + mask = value != 0 + major_index = np.compress(mask, major_index) + value = np.compress(mask, value) - While np.unique existed long before, keyword return_inverse was - only added in 1.4. - """ - try: - ar = ar.flatten() - except AttributeError: - if not return_inverse and not return_index: - items = sorted(set(ar)) - return np.asarray(items) + from scipy.sparse import coo_matrix + if axis == 0: + res = coo_matrix((value, (np.zeros(len(value)), major_index)), + dtype=X.dtype, shape=(1, M)) else: - ar = np.asarray(ar).flatten() + res = coo_matrix((value, (major_index, np.zeros(len(value)))), + dtype=X.dtype, shape=(M, 1)) + return res.A.ravel() - if ar.size == 0: - if return_inverse and return_index: - return ar, np.empty(0, np.bool), np.empty(0, np.bool) - elif return_inverse or return_index: - return ar, np.empty(0, np.bool) + def _sparse_min_or_max(X, axis, min_or_max): + if axis is None: + if 0 in X.shape: + raise ValueError("zero-size array to reduction operation") + zero = X.dtype.type(0) + if X.nnz == 0: + return zero + m = min_or_max.reduce(X.data.ravel()) + if X.nnz != np.product(X.shape): + m = min_or_max(zero, m) + return m + if axis < 0: + axis += 2 + if (axis == 0) or (axis == 1): + return _min_or_max_axis(X, axis, min_or_max) else: - return ar - - if return_inverse or return_index: - perm = ar.argsort() - aux = ar[perm] - flag = np.concatenate(([True], aux[1:] != aux[:-1])) - if return_inverse: - iflag = np.cumsum(flag) - 1 - iperm = perm.argsort() - if return_index: - return aux[flag], perm[flag], iflag[iperm] + raise ValueError("invalid axis, use 0 for rows, or 1 for columns") + + def sparse_min_max(X, axis): + return (_sparse_min_or_max(X, axis, np.minimum), + _sparse_min_or_max(X, axis, np.maximum)) + +else: + def sparse_min_max(X, axis): + return (X.min(axis=axis).toarray().ravel(), + X.max(axis=axis).toarray().ravel()) + + +try: + from numpy import argpartition +except ImportError: + # numpy.argpartition was introduced in v 1.8.0 + def argpartition(a, kth, axis=-1, kind='introselect', order=None): + return np.argsort(a, axis=axis, order=order) + + +try: + from itertools import combinations_with_replacement +except ImportError: + # Backport of itertools.combinations_with_replacement for Python 2.6, + # from Python 3.4 documentation (http://tinyurl.com/comb-w-r), copyright + # Python Software Foundation (https://docs.python.org/3/license.html) + def combinations_with_replacement(iterable, r): + # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC + pool = tuple(iterable) + n = len(pool) + if not n and r: + return + indices = [0] * r + yield tuple(pool[i] for i in indices) + while True: + for i in reversed(range(r)): + if indices[i] != n - 1: + break else: - return aux[flag], iflag[iperm] + return + indices[i:] = [indices[i] + 1] * (r - i) + yield tuple(pool[i] for i in indices) + + +try: + from numpy import isclose +except ImportError: + def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): + """ + Returns a boolean array where two arrays are element-wise equal within + a tolerance. + + This function was added to numpy v1.7.0, and the version you are + running has been backported from numpy v1.8.1. See its documentation + for more details. + """ + def within_tol(x, y, atol, rtol): + with np.errstate(invalid='ignore'): + result = np.less_equal(abs(x-y), atol + rtol * abs(y)) + if np.isscalar(a) and np.isscalar(b): + result = bool(result) + return result + + x = np.array(a, copy=False, subok=True, ndmin=1) + y = np.array(b, copy=False, subok=True, ndmin=1) + xfin = np.isfinite(x) + yfin = np.isfinite(y) + if all(xfin) and all(yfin): + return within_tol(x, y, atol, rtol) else: - return aux[flag], perm[flag] + finite = xfin & yfin + cond = np.zeros_like(finite, subok=True) + # Since we're using boolean indexing, x & y must be the same shape. + # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in + # lib.stride_tricks, though, so we can't import it here. + x = x * np.ones_like(cond) + y = y * np.ones_like(cond) + # Avoid subtraction with infinite/nan values... + cond[finite] = within_tol(x[finite], y[finite], atol, rtol) + # Check for equality of infinite values... + cond[~finite] = (x[~finite] == y[~finite]) + if equal_nan: + # Make NaN == NaN + cond[np.isnan(x) & np.isnan(y)] = True + return cond - else: - ar.sort() - flag = np.concatenate(([True], ar[1:] != ar[:-1])) - return ar[flag] -np_version = np.__version__.split('.') -if int(np_version[0]) < 2 and int(np_version[1]) < 5: - unique = _unique +if np_version < (1, 7): + # Prior to 1.7.0, np.frombuffer wouldn't work for empty first arg. + def frombuffer_empty(buf, dtype): + if len(buf) == 0: + return np.empty(0, dtype=dtype) + else: + return np.frombuffer(buf, dtype=dtype) else: - unique = np.unique + frombuffer_empty = np.frombuffer -def _copysign(x1, x2): - """Slow replacement for np.copysign, which was introduced in numpy 1.4""" - return np.abs(x1) * np.sign(x2) +if np_version < (1, 8): + def in1d(ar1, ar2, assume_unique=False, invert=False): + # Backport of numpy function in1d 1.8.1 to support numpy 1.6.2 + # Ravel both arrays, behavior for the first array could be different + ar1 = np.asarray(ar1).ravel() + ar2 = np.asarray(ar2).ravel() -if not hasattr(np, 'copysign'): - copysign = _copysign + # This code is significantly faster when the condition is satisfied. + if len(ar2) < 10 * len(ar1) ** 0.145: + if invert: + mask = np.ones(len(ar1), dtype=np.bool) + for a in ar2: + mask &= (ar1 != a) + else: + mask = np.zeros(len(ar1), dtype=np.bool) + for a in ar2: + mask |= (ar1 == a) + return mask + + # Otherwise use sorting + if not assume_unique: + ar1, rev_idx = np.unique(ar1, return_inverse=True) + ar2 = np.unique(ar2) + + ar = np.concatenate((ar1, ar2)) + # We need this to be a stable sort, so always use 'mergesort' + # here. The values from the first array should always come before + # the values from the second array. + order = ar.argsort(kind='mergesort') + sar = ar[order] + if invert: + bool_ar = (sar[1:] != sar[:-1]) + else: + bool_ar = (sar[1:] == sar[:-1]) + flag = np.concatenate((bool_ar, [invert])) + indx = order.argsort(kind='mergesort')[:len(ar1)] + + if assume_unique: + return flag[indx] + else: + return flag[indx][rev_idx] else: - copysign = np.copysign - - -def _in1d(ar1, ar2, assume_unique=False): - """Replacement for in1d that is provided for numpy >= 1.4""" - if not assume_unique: - ar1, rev_idx = unique(ar1, return_inverse=True) - ar2 = np.unique(ar2) - ar = np.concatenate((ar1, ar2)) - # We need this to be a stable sort, so always use 'mergesort' - # here. The values from the first array should always come before - # the values from the second array. - order = ar.argsort(kind='mergesort') - sar = ar[order] - equal_adj = (sar[1:] == sar[:-1]) - flag = np.concatenate((equal_adj, [False])) - indx = order.argsort(kind='mergesort')[:len(ar1)] - - if assume_unique: - return flag[indx] - else: - return flag[indx][rev_idx] - -if not hasattr(np, 'in1d'): - in1d = _in1d + from numpy import in1d + + +if sp_version < (0, 15): + # Backport fix for scikit-learn/scikit-learn#2986 / scipy/scipy#4142 + from ._scipy_sparse_lsqr_backport import lsqr as sparse_lsqr else: - in1d = np.in1d - - -def qr_economic(A, **kwargs): - """Compat function for the QR-decomposition in economic mode - - Scipy 0.9 changed the keyword econ=True to mode='economic' - """ - import scipy.linalg - # trick: triangular solve has introduced in 0.9 - if hasattr(scipy.linalg, 'solve_triangular'): - return scipy.linalg.qr(A, mode='economic', **kwargs) - else: - import warnings - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - return scipy.linalg.qr(A, econ=True, **kwargs) - - -def savemat(file_name, mdict, oned_as="column", **kwargs): - """MATLAB-format output routine that is compatible with SciPy 0.7's. - - 0.7.2 (or .1?) added the oned_as keyword arg with 'column' as the default - value. It issues a warning if this is not provided, stating that "This will - change to 'row' in future versions." - """ - import scipy.io - try: - return scipy.io.savemat(file_name, mdict, oned_as=oned_as, **kwargs) - except TypeError: - return scipy.io.savemat(file_name, mdict, **kwargs) + from scipy.sparse.linalg import lsqr as sparse_lsqr -try: - from numpy import count_nonzero -except ImportError: - def count_nonzero(X): - return len(np.flatnonzero(X)) + +if sys.version_info < (2, 7, 0): + # partial cannot be pickled in Python 2.6 + # http://bugs.python.org/issue1398 + class partial(object): + def __init__(self, func, *args, **keywords): + functools.update_wrapper(self, func) + self.func = func + self.args = args + self.keywords = keywords + + def __call__(self, *args, **keywords): + args = self.args + args + kwargs = self.keywords.copy() + kwargs.update(keywords) + return self.func(*args, **kwargs) +else: + from functools import partial + + +if np_version < (1, 6, 2): + # Allow bincount to accept empty arrays + # https://github.com/numpy/numpy/commit/40f0844846a9d7665616b142407a3d74cb65a040 + def bincount(x, weights=None, minlength=None): + if len(x) > 0: + return np.bincount(x, weights, minlength) + else: + if minlength is None: + minlength = 0 + minlength = np.asscalar(np.asarray(minlength, dtype=np.intp)) + return np.zeros(minlength, dtype=np.intp) + +else: + from numpy import bincount diff --git a/sklearn/utils/graph.py b/sklearn/utils/graph.py index cf6ca1240f41a..650e71841d359 100644 --- a/sklearn/utils/graph.py +++ b/sklearn/utils/graph.py @@ -7,7 +7,8 @@ # Authors: Aric Hagberg # Gael Varoquaux -# License: BSD +# Jake Vanderplas +# License: BSD 3 clause import numpy as np from scipy import sparse @@ -67,15 +68,62 @@ def single_source_shortest_path_length(graph, source, cutoff=None): return seen # return all path lengths as dictionary -if hasattr(sparse, 'cs_graph_components'): - cs_graph_components = sparse.cs_graph_components +if hasattr(sparse, 'connected_components'): + connected_components = sparse.connected_components else: - from ._csgraph import cs_graph_components + from .sparsetools import connected_components ############################################################################### # Graph laplacian -def _graph_laplacian_sparse(graph, normed=False, return_diag=False): +def graph_laplacian(csgraph, normed=False, return_diag=False): + """ Return the Laplacian matrix of a directed graph. + + For non-symmetric graphs the out-degree is used in the computation. + + Parameters + ---------- + csgraph : array_like or sparse matrix, 2 dimensions + compressed-sparse graph, with shape (N, N). + normed : bool, optional + If True, then compute normalized Laplacian. + return_diag : bool, optional + If True, then return diagonal as well as laplacian. + + Returns + ------- + lap : ndarray + The N x N laplacian matrix of graph. + diag : ndarray + The length-N diagonal of the laplacian matrix. + diag is returned only if return_diag is True. + + Notes + ----- + The Laplacian matrix of a graph is sometimes referred to as the + "Kirchoff matrix" or the "admittance matrix", and is useful in many + parts of spectral graph theory. In particular, the eigen-decomposition + of the laplacian matrix can give insight into many properties of the graph. + + For non-symmetric directed graphs, the laplacian is computed using the + out-degree of each node. + """ + if csgraph.ndim != 2 or csgraph.shape[0] != csgraph.shape[1]: + raise ValueError('csgraph must be a square matrix or array') + + if normed and (np.issubdtype(csgraph.dtype, np.int) + or np.issubdtype(csgraph.dtype, np.uint)): + csgraph = csgraph.astype(np.float) + + if sparse.isspmatrix(csgraph): + return _laplacian_sparse(csgraph, normed=normed, + return_diag=return_diag) + else: + return _laplacian_dense(csgraph, normed=normed, + return_diag=return_diag) + + +def _laplacian_sparse(graph, normed=False, return_diag=False): n_nodes = graph.shape[0] if not graph.format == 'coo': lap = (-graph).tocoo() @@ -86,59 +134,49 @@ def _graph_laplacian_sparse(graph, normed=False, return_diag=False): # The sparsity pattern of the matrix has holes on the diagonal, # we need to fix that diag_idx = lap.row[diag_mask] - - lap = lap.tolil() - - diagonal_holes = list(set(range(n_nodes)).difference( - diag_idx)) - lap[diagonal_holes, diagonal_holes] = 1 - lap = lap.tocoo() + diagonal_holes = list(set(range(n_nodes)).difference(diag_idx)) + new_data = np.concatenate([lap.data, np.ones(len(diagonal_holes))]) + new_row = np.concatenate([lap.row, diagonal_holes]) + new_col = np.concatenate([lap.col, diagonal_holes]) + lap = sparse.coo_matrix((new_data, (new_row, new_col)), + shape=lap.shape) diag_mask = (lap.row == lap.col) + lap.data[diag_mask] = 0 w = -np.asarray(lap.sum(axis=1)).squeeze() if normed: w = np.sqrt(w) - w_zeros = w == 0 + w_zeros = (w == 0) w[w_zeros] = 1 lap.data /= w[lap.row] lap.data /= w[lap.col] - lap.data[diag_mask] = (1 - w_zeros).astype(lap.data.dtype) + lap.data[diag_mask] = (1 - w_zeros[lap.row[diag_mask]]).astype( + lap.data.dtype) else: lap.data[diag_mask] = w[lap.row[diag_mask]] + if return_diag: return lap, w return lap -def _graph_laplacian_dense(graph, normed=False, return_diag=False): +def _laplacian_dense(graph, normed=False, return_diag=False): n_nodes = graph.shape[0] - lap = -graph.copy() + lap = -np.asarray(graph) # minus sign leads to a copy + + # set diagonal to zero lap.flat[::n_nodes + 1] = 0 w = -lap.sum(axis=0) if normed: w = np.sqrt(w) - w_zeros = w == 0 + w_zeros = (w == 0) w[w_zeros] = 1 lap /= w lap /= w[:, np.newaxis] - lap.flat[::n_nodes + 1] = 1 - w_zeros + lap.flat[::n_nodes + 1] = (1 - w_zeros).astype(lap.dtype) else: - lap.flat[::n_nodes + 1] = w + lap.flat[::n_nodes + 1] = w.astype(lap.dtype) + if return_diag: return lap, w return lap - - -def graph_laplacian(graph, normed=False, return_diag=False): - """ Return the Laplacian of the given graph. - """ - if normed and (np.issubdtype(graph.dtype, np.int) - or np.issubdtype(graph.dtype, np.uint)): - graph = graph.astype(np.float) - if sparse.isspmatrix(graph): - return _graph_laplacian_sparse(graph, normed=normed, - return_diag=return_diag) - else: - # We have a numpy array - return _graph_laplacian_dense(graph, normed=normed, - return_diag=return_diag) diff --git a/sklearn/utils/graph_shortest_path.c b/sklearn/utils/graph_shortest_path.c index 27a9c6e686a95..246f58ac3d4ed 100644 --- a/sklearn/utils/graph_shortest_path.c +++ b/sklearn/utils/graph_shortest_path.c @@ -1,16 +1,16 @@ -/* Generated by Cython 0.15.1 on Sat Feb 25 08:12:27 2012 */ +/* Generated by Cython 0.17.4 on Mon Jan 7 18:14:53 2013 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. #else - #include /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -22,36 +22,47 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - -#if PY_VERSION_HEX < 0x02040000 - #define METH_COEXIST 0 - #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) - #define PyDict_Contains(d,o) PySequence_Contains(d,o) +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 #endif - #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -59,7 +70,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -73,7 +83,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -83,24 +92,44 @@ #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -108,7 +137,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -127,7 +155,6 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -135,9 +162,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -154,11 +179,9 @@ #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - #if PY_VERSION_HEX < 0x03020000 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong @@ -167,16 +190,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -195,11 +208,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -209,7 +220,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -218,6 +228,15 @@ #define __Pyx_DOCSTR(n) (n) #endif + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" @@ -266,7 +285,7 @@ # else # define CYTHON_UNUSED # endif -# elif defined(__ICC) || defined(__INTEL_COMPILER) +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED @@ -290,8 +309,12 @@ static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) - +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #ifdef __GNUC__ /* Test for GCC > 2.95 */ @@ -316,7 +339,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -326,7 +348,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -334,18 +355,54 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { "graph_shortest_path.pyx", "numpy.pxd", + "type.pxd", }; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + -/* "numpy.pxd":719 +/* "numpy.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -354,7 +411,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "numpy.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -363,7 +420,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "numpy.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -372,7 +429,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "numpy.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -381,7 +438,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "numpy.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -390,7 +447,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "numpy.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -399,7 +456,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "numpy.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -408,7 +465,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "numpy.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -417,7 +474,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "numpy.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -426,7 +483,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "numpy.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -435,7 +492,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "numpy.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -444,7 +501,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "numpy.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -453,7 +510,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "numpy.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -462,7 +519,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "numpy.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -471,7 +528,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "numpy.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -480,7 +537,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "numpy.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -489,7 +546,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "numpy.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -498,7 +555,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "numpy.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -507,7 +564,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "numpy.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -516,7 +573,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "numpy.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -525,7 +582,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "numpy.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -534,7 +591,7 @@ typedef npy_double __pyx_t_5numpy_double_t; */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; -/* "sklearn/utils/graph_shortest_path.pyx":22 +/* "sklearn/utils/graph_shortest_path.pyx":24 * * DTYPE = np.float64 * ctypedef np.float64_t DTYPE_t # <<<<<<<<<<<<<< @@ -543,7 +600,7 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; */ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t; -/* "sklearn/utils/graph_shortest_path.pyx":25 +/* "sklearn/utils/graph_shortest_path.pyx":27 * * ITYPE = np.int32 * ctypedef np.int32_t ITYPE_t # <<<<<<<<<<<<<< @@ -551,7 +608,6 @@ typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_19graph_shortest_path_D * */ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t; - #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -572,9 +628,10 @@ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_5utils_19graph_shortest_path_ITY typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ -/* "numpy.pxd":758 +/* "numpy.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -583,7 +640,7 @@ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_5utils_19graph_shortest_path_ITY */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "numpy.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -592,7 +649,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "numpy.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -601,7 +658,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "numpy.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -615,7 +672,7 @@ struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode; struct __pyx_opt_args_7sklearn_5utils_19graph_shortest_path_initialize_node; struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciHeap; -/* "sklearn/utils/graph_shortest_path.pyx":94 +/* "sklearn/utils/graph_shortest_path.pyx":96 * * @cython.boundscheck(False) * cdef np.ndarray floyd_warshall(np.ndarray[DTYPE_t, ndim=2, mode='c'] graph, # <<<<<<<<<<<<<< @@ -627,7 +684,7 @@ struct __pyx_opt_args_7sklearn_5utils_19graph_shortest_path_floyd_warshall { int directed; }; -/* "sklearn/utils/graph_shortest_path.pyx":156 +/* "sklearn/utils/graph_shortest_path.pyx":158 * * @cython.boundscheck(False) * cdef np.ndarray dijkstra(dist_matrix, # <<<<<<<<<<<<<< @@ -639,7 +696,7 @@ struct __pyx_opt_args_7sklearn_5utils_19graph_shortest_path_dijkstra { int directed; }; -/* "sklearn/utils/graph_shortest_path.pyx":242 +/* "sklearn/utils/graph_shortest_path.pyx":244 * # * * cdef struct FibonacciNode: # <<<<<<<<<<<<<< @@ -657,7 +714,7 @@ struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode { struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *children; }; -/* "sklearn/utils/graph_shortest_path.pyx":253 +/* "sklearn/utils/graph_shortest_path.pyx":255 * * * cdef void initialize_node(FibonacciNode* node, # <<<<<<<<<<<<<< @@ -669,7 +726,7 @@ struct __pyx_opt_args_7sklearn_5utils_19graph_shortest_path_initialize_node { __pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t val; }; -/* "sklearn/utils/graph_shortest_path.pyx":339 +/* "sklearn/utils/graph_shortest_path.pyx":341 * # routines to implement a Fibonacci heap * * ctypedef FibonacciNode* pFibonacciNode # <<<<<<<<<<<<<< @@ -678,7 +735,7 @@ struct __pyx_opt_args_7sklearn_5utils_19graph_shortest_path_initialize_node { */ typedef struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_t_7sklearn_5utils_19graph_shortest_path_pFibonacciNode; -/* "sklearn/utils/graph_shortest_path.pyx":342 +/* "sklearn/utils/graph_shortest_path.pyx":344 * * * cdef struct FibonacciHeap: # <<<<<<<<<<<<<< @@ -689,12 +746,9 @@ struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciHeap { struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *min_node; __pyx_t_7sklearn_5utils_19graph_shortest_path_pFibonacciNode roots_by_rank[100]; }; - - #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -707,8 +761,21 @@ struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciHeap { static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -719,7 +786,7 @@ struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciHeap { #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -730,18 +797,20 @@ struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciHeap { #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ - static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { PyObject *r; if (!j) return NULL; @@ -749,70 +818,83 @@ static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j Py_DECREF(j); return r; } - - #define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ __Pyx_GetItemInt_List_Fast(o, i) : \ __Pyx_GetItemInt_Generic(o, to_py_func(i))) - static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } +#if CYTHON_COMPILING_IN_CPYTHON + if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { + PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); + Py_INCREF(r); + return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif } - #define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ __Pyx_GetItemInt_Tuple_Fast(o, i) : \ __Pyx_GetItemInt_Generic(o, to_py_func(i))) - static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { - if (likely(o != Py_None)) { - if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { - PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); - Py_INCREF(r); - return r; - } +#if CYTHON_COMPILING_IN_CPYTHON + if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { + PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); + Py_INCREF(r); + return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif } - - #define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ __Pyx_GetItemInt_Fast(o, i) : \ __Pyx_GetItemInt_Generic(o, to_py_func(i))) - static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { - PyObject *r; - if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) { - r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - } - else if (PyTuple_CheckExact(o) && ((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); +#if CYTHON_COMPILING_IN_CPYTHON + if (PyList_CheckExact(o)) { + Py_ssize_t n = (likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if (likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } } - else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0))) { - r = PySequence_GetItem(o, i); + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = (likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if (likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { /* inlined PySequence_GetItem() */ + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (unlikely(l < 0)) return NULL; + i += l; + } + return m->sq_item(o, i); + } } - else { - r = __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + if (PySequence_Check(o)) { + return PySequence_GetItem(o, i); } - return r; +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); } static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ @@ -822,64 +904,50 @@ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyOb static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ -/* Run-time type information about structs used with buffers */ -struct __Pyx_StructField_; - -typedef struct { - const char* name; /* for error messages only */ - struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ -} __Pyx_TypeInfo; - -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; - -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; - - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + #define __Pyx_BufPtrCContig2d(type, buf, i0, s0, i1, s1) ((type)((char*)buf + i0 * s0) + i1) #define __Pyx_BufPtrCContig1d(type, buf, i0, s0) ((type)buf + i0) +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + #if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); -static void __Pyx_ReleaseBuffer(Py_buffer *view); + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); #else -#define __Pyx_GetBuffer PyObject_GetBuffer -#define __Pyx_ReleaseBuffer PyBuffer_Release + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release #endif -Py_ssize_t __Pyx_zeros[] = {0, 0}; -Py_ssize_t __Pyx_minusones[] = {-1, -1}; - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ - -#include -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals -#else -#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals -#endif +static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name); #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -893,7 +961,6 @@ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - #if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) @@ -1017,15 +1084,38 @@ static void __Pyx_WriteUnraisable(const char *name, int clineno, static int __Pyx_check_binary_version(void); -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ @@ -1034,6 +1124,11 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -1044,16 +1139,7 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ - -/* Module declarations from 'cython.cython.view' */ /* Module declarations from 'cython' */ @@ -1072,8 +1158,8 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_f_7sklearn_5utils_19graph_shortest_path_remove_min(struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciHeap *); /*proto*/ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_row(unsigned int, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciHeap *, struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *); /*proto*/ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsigned int, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciHeap *, struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *); /*proto*/ -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t), 'R' }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t = { "ITYPE_t", NULL, sizeof(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t), 'I' }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t = { "ITYPE_t", NULL, sizeof(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t), 0 }; #define __Pyx_MODULE_NAME "sklearn.utils.graph_shortest_path" int __pyx_module_is_main_sklearn__utils__graph_shortest_path = 0; @@ -1081,6 +1167,9 @@ int __pyx_module_is_main_sklearn__utils__graph_shortest_path = 0; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_path(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_dist_matrix, PyObject *__pyx_v_directed, PyObject *__pyx_v_method); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static char __pyx_k_2[] = "unrecognized method '%s'"; static char __pyx_k_3[] = "ndarray is not C contiguous"; static char __pyx_k_5[] = "ndarray is not Fortran contiguous"; @@ -1090,13 +1179,15 @@ static char __pyx_k_10[] = "Format string allocated too short, see comment in nu static char __pyx_k_13[] = "Format string allocated too short."; static char __pyx_k_15[] = "\nRoutines for performing shortest-path graph searches\n\nThe main interface is in the function `graph_shortest_path`. This\ncalls cython routines that compute the shortest path using either\nthe Floyd-Warshall algorithm, or Dykstra's algorithm with Fibonacci Heaps.\n"; static char __pyx_k_16[] = "scipy.sparse"; -static char __pyx_k_17[] = "sklearn.utils.graph_shortest_path"; +static char __pyx_k_19[] = "/scratch/apps/src/scikit-learn/sklearn/utils/graph_shortest_path.pyx"; +static char __pyx_k_20[] = "sklearn.utils.graph_shortest_path"; static char __pyx_k__B[] = "B"; static char __pyx_k__C[] = "C"; static char __pyx_k__D[] = "D"; static char __pyx_k__H[] = "H"; static char __pyx_k__I[] = "I"; static char __pyx_k__L[] = "L"; +static char __pyx_k__N[] = "N"; static char __pyx_k__O[] = "O"; static char __pyx_k__Q[] = "Q"; static char __pyx_k__T[] = "T"; @@ -1109,6 +1200,7 @@ static char __pyx_k__i[] = "i"; static char __pyx_k__l[] = "l"; static char __pyx_k__q[] = "q"; static char __pyx_k__FW[] = "FW"; +static char __pyx_k__Nk[] = "Nk"; static char __pyx_k__Zd[] = "Zd"; static char __pyx_k__Zf[] = "Zf"; static char __pyx_k__Zg[] = "Zg"; @@ -1120,6 +1212,7 @@ static char __pyx_k__flat[] = "flat"; static char __pyx_k__DTYPE[] = "DTYPE"; static char __pyx_k__ITYPE[] = "ITYPE"; static char __pyx_k__dtype[] = "dtype"; +static char __pyx_k__graph[] = "graph"; static char __pyx_k__int32[] = "int32"; static char __pyx_k__isinf[] = "isinf"; static char __pyx_k__numpy[] = "numpy"; @@ -1148,8 +1241,9 @@ static char __pyx_k__graph_shortest_path[] = "graph_shortest_path"; static PyObject *__pyx_kp_u_10; static PyObject *__pyx_kp_u_13; static PyObject *__pyx_n_s_16; -static PyObject *__pyx_n_s_17; +static PyObject *__pyx_kp_s_19; static PyObject *__pyx_kp_s_2; +static PyObject *__pyx_n_s_20; static PyObject *__pyx_kp_u_3; static PyObject *__pyx_kp_u_5; static PyObject *__pyx_kp_u_7; @@ -1159,6 +1253,8 @@ static PyObject *__pyx_n_s__D; static PyObject *__pyx_n_s__DTYPE; static PyObject *__pyx_n_s__FW; static PyObject *__pyx_n_s__ITYPE; +static PyObject *__pyx_n_s__N; +static PyObject *__pyx_n_s__Nk; static PyObject *__pyx_n_s__RuntimeError; static PyObject *__pyx_n_s__T; static PyObject *__pyx_n_s__ValueError; @@ -1173,6 +1269,7 @@ static PyObject *__pyx_n_s__dist_matrix; static PyObject *__pyx_n_s__dtype; static PyObject *__pyx_n_s__flat; static PyObject *__pyx_n_s__float64; +static PyObject *__pyx_n_s__graph; static PyObject *__pyx_n_s__graph_shortest_path; static PyObject *__pyx_n_s__indices; static PyObject *__pyx_n_s__indptr; @@ -1201,50 +1298,29 @@ static PyObject *__pyx_k_tuple_8; static PyObject *__pyx_k_tuple_11; static PyObject *__pyx_k_tuple_12; static PyObject *__pyx_k_tuple_14; +static PyObject *__pyx_k_tuple_17; +static PyObject *__pyx_k_codeobj_18; -/* "sklearn/utils/graph_shortest_path.pyx":28 - * - * - * def graph_shortest_path(dist_matrix, directed=True, method='auto'): # <<<<<<<<<<<<<< - * """ - * Perform a shortest-path graph search on a positive directed or - */ - -static PyObject *__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_path(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_19graph_shortest_path_1graph_shortest_path(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_7sklearn_5utils_19graph_shortest_path_graph_shortest_path[] = "\n Perform a shortest-path graph search on a positive directed or\n undirected graph.\n\n Parameters\n ----------\n dist_matrix : arraylike or sparse matrix, shape = (N,N)\n Array of positive distances.\n If vertex i is connected to vertex j, then dist_matrix[i,j] gives\n the distance between the vertices.\n If vertex i is not connected to vertex j, then dist_matrix[i,j] = 0\n directed : boolean\n if True, then find the shortest path on a directed graph: only\n progress from a point to its neighbors, not the other way around.\n if False, then find the shortest path on an undirected graph: the\n algorithm can progress from a point to its neighbors and vice versa.\n method : string ['auto'|'FW'|'D']\n method to use. Options are\n 'auto' : attempt to choose the best method for the current problem\n 'FW' : Floyd-Warshall algorithm. O[N^3]\n 'D' : Dijkstra's algorithm with Fibonacci stacks. O[(k+log(N))N^2]\n\n Returns\n -------\n G : np.ndarray, float, shape = [N,N]\n G[i,j] gives the shortest distance from point i to point j\n along the graph.\n\n Notes\n -----\n As currently implemented, Dijkstra's algorithm does not work for\n graphs with direction-dependent distances when directed == False.\n i.e., if dist_matrix[i,j] and dist_matrix[j,i] are not equal and\n both are nonzero, method='D' will not necessarily yield the correct\n result.\n\n Also, these routines have not been tested for graphs with negative\n distances. Negative distances can lead to infinite cycles that must\n be handled by specialized algorithms.\n "; -static PyMethodDef __pyx_mdef_7sklearn_5utils_19graph_shortest_path_graph_shortest_path = {__Pyx_NAMESTR("graph_shortest_path"), (PyCFunction)__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_path, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_19graph_shortest_path_graph_shortest_path)}; -static PyObject *__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_path(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +static PyMethodDef __pyx_mdef_7sklearn_5utils_19graph_shortest_path_1graph_shortest_path = {__Pyx_NAMESTR("graph_shortest_path"), (PyCFunction)__pyx_pw_7sklearn_5utils_19graph_shortest_path_1graph_shortest_path, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_19graph_shortest_path_graph_shortest_path)}; +static PyObject *__pyx_pw_7sklearn_5utils_19graph_shortest_path_1graph_shortest_path(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_dist_matrix = 0; PyObject *__pyx_v_directed = 0; PyObject *__pyx_v_method = 0; - PyObject *__pyx_v_N = NULL; - Py_ssize_t __pyx_v_Nk; - PyObject *__pyx_v_graph = NULL; - PyObject *__pyx_r = NULL; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - Py_ssize_t __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - struct __pyx_opt_args_7sklearn_5utils_19graph_shortest_path_floyd_warshall __pyx_t_9; - struct __pyx_opt_args_7sklearn_5utils_19graph_shortest_path_dijkstra __pyx_t_10; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__dist_matrix,&__pyx_n_s__directed,&__pyx_n_s__method,0}; - __Pyx_RefNannySetupContext("graph_shortest_path"); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("graph_shortest_path (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__dist_matrix,&__pyx_n_s__directed,&__pyx_n_s__method,0}; PyObject* values[3] = {0,0,0}; values[1] = __pyx_k_1; values[2] = ((PyObject *)__pyx_n_s__auto); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); @@ -1252,10 +1328,9 @@ static PyObject *__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_p default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dist_matrix); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dist_matrix)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (kw_args > 0) { @@ -1269,7 +1344,7 @@ static PyObject *__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_p } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "graph_shortest_path") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "graph_shortest_path") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { @@ -1286,124 +1361,158 @@ static PyObject *__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_p } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("graph_shortest_path", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("graph_shortest_path", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.utils.graph_shortest_path.graph_shortest_path", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_path(__pyx_self, __pyx_v_dist_matrix, __pyx_v_directed, __pyx_v_method); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/graph_shortest_path.pyx":30 + * + * + * def graph_shortest_path(dist_matrix, directed=True, method='auto'): # <<<<<<<<<<<<<< + * """ + * Perform a shortest-path graph search on a positive directed or + */ + +static PyObject *__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_path(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_dist_matrix, PyObject *__pyx_v_directed, PyObject *__pyx_v_method) { + PyObject *__pyx_v_N = NULL; + PyObject *__pyx_v_Nk = NULL; + PyObject *__pyx_v_graph = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + Py_ssize_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + struct __pyx_opt_args_7sklearn_5utils_19graph_shortest_path_floyd_warshall __pyx_t_9; + struct __pyx_opt_args_7sklearn_5utils_19graph_shortest_path_dijkstra __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("graph_shortest_path", 0); __Pyx_INCREF(__pyx_v_dist_matrix); __Pyx_INCREF(__pyx_v_method); - /* "sklearn/utils/graph_shortest_path.pyx":69 + /* "sklearn/utils/graph_shortest_path.pyx":71 * be handled by specialized algorithms. * """ * if not isspmatrix_csr(dist_matrix): # <<<<<<<<<<<<<< * dist_matrix = csr_matrix(dist_matrix) * */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__isspmatrix_csr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__isspmatrix_csr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_dist_matrix); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_dist_matrix); __Pyx_GIVEREF(__pyx_v_dist_matrix); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_5 = (!__pyx_t_4); if (__pyx_t_5) { - /* "sklearn/utils/graph_shortest_path.pyx":70 + /* "sklearn/utils/graph_shortest_path.pyx":72 * """ * if not isspmatrix_csr(dist_matrix): * dist_matrix = csr_matrix(dist_matrix) # <<<<<<<<<<<<<< * * N = dist_matrix.shape[0] */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__csr_matrix); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__csr_matrix); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_dist_matrix); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_dist_matrix); __Pyx_GIVEREF(__pyx_v_dist_matrix); - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_v_dist_matrix); __pyx_v_dist_matrix = __pyx_t_1; __pyx_t_1 = 0; - goto __pyx_L6; + goto __pyx_L3; } - __pyx_L6:; + __pyx_L3:; - /* "sklearn/utils/graph_shortest_path.pyx":72 + /* "sklearn/utils/graph_shortest_path.pyx":74 * dist_matrix = csr_matrix(dist_matrix) * * N = dist_matrix.shape[0] # <<<<<<<<<<<<<< * Nk = len(dist_matrix.data) * */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_N = __pyx_t_2; __pyx_t_2 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":73 + /* "sklearn/utils/graph_shortest_path.pyx":75 * * N = dist_matrix.shape[0] * Nk = len(dist_matrix.data) # <<<<<<<<<<<<<< * * if method == 'auto': */ - __pyx_t_2 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__data); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__data); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = PyObject_Length(__pyx_t_2); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyObject_Length(__pyx_t_2); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_Nk = __pyx_t_6; + __pyx_t_2 = PyInt_FromSsize_t(__pyx_t_6); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_Nk = __pyx_t_2; + __pyx_t_2 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":75 + /* "sklearn/utils/graph_shortest_path.pyx":77 * Nk = len(dist_matrix.data) * * if method == 'auto': # <<<<<<<<<<<<<< * if Nk < N * N / 4: * method = 'D' */ - __pyx_t_5 = __Pyx_PyString_Equals(__pyx_v_method, ((PyObject *)__pyx_n_s__auto), Py_EQ); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_RichCompare(__pyx_v_method, ((PyObject *)__pyx_n_s__auto), Py_EQ); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_5) { - /* "sklearn/utils/graph_shortest_path.pyx":76 + /* "sklearn/utils/graph_shortest_path.pyx":78 * * if method == 'auto': * if Nk < N * N / 4: # <<<<<<<<<<<<<< * method = 'D' * else: */ - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_Nk); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyNumber_Multiply(__pyx_v_N, __pyx_v_N); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyNumber_Multiply(__pyx_v_N, __pyx_v_N); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_int_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_RichCompare(__pyx_t_2, __pyx_t_3, Py_LT); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyNumber_Divide(__pyx_t_2, __pyx_int_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_RichCompare(__pyx_v_Nk, __pyx_t_1, Py_LT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_5) { - /* "sklearn/utils/graph_shortest_path.pyx":77 + /* "sklearn/utils/graph_shortest_path.pyx":79 * if method == 'auto': * if Nk < N * N / 4: * method = 'D' # <<<<<<<<<<<<<< @@ -1413,11 +1522,11 @@ static PyObject *__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_p __Pyx_INCREF(((PyObject *)__pyx_n_s__D)); __Pyx_DECREF(__pyx_v_method); __pyx_v_method = ((PyObject *)__pyx_n_s__D); - goto __pyx_L8; + goto __pyx_L5; } /*else*/ { - /* "sklearn/utils/graph_shortest_path.pyx":79 + /* "sklearn/utils/graph_shortest_path.pyx":81 * method = 'D' * else: * method = 'FW' # <<<<<<<<<<<<<< @@ -1428,173 +1537,177 @@ static PyObject *__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_p __Pyx_DECREF(__pyx_v_method); __pyx_v_method = ((PyObject *)__pyx_n_s__FW); } - __pyx_L8:; - goto __pyx_L7; + __pyx_L5:; + goto __pyx_L4; } - __pyx_L7:; + __pyx_L4:; - /* "sklearn/utils/graph_shortest_path.pyx":81 + /* "sklearn/utils/graph_shortest_path.pyx":83 * method = 'FW' * * if method == 'FW': # <<<<<<<<<<<<<< * graph = np.asarray(dist_matrix.toarray(), dtype=DTYPE, order='C') * floyd_warshall(graph, directed) */ - __pyx_t_5 = __Pyx_PyString_Equals(__pyx_v_method, ((PyObject *)__pyx_n_s__FW), Py_EQ); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_RichCompare(__pyx_v_method, ((PyObject *)__pyx_n_s__FW), Py_EQ); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_5) { - /* "sklearn/utils/graph_shortest_path.pyx":82 + /* "sklearn/utils/graph_shortest_path.pyx":84 * * if method == 'FW': * graph = np.asarray(dist_matrix.toarray(), dtype=DTYPE, order='C') # <<<<<<<<<<<<<< * floyd_warshall(graph, directed) * elif method == 'D': */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__toarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__toarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = PyEval_CallObjectWithKeywords(__pyx_t_3, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __pyx_v_graph = __pyx_t_7; __pyx_t_7 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":83 + /* "sklearn/utils/graph_shortest_path.pyx":85 * if method == 'FW': * graph = np.asarray(dist_matrix.toarray(), dtype=DTYPE, order='C') * floyd_warshall(graph, directed) # <<<<<<<<<<<<<< * elif method == 'D': * graph = np.zeros((N, N), dtype=DTYPE, order='C') */ - if (!(likely(((__pyx_v_graph) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_graph, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_v_graph) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_graph, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_7 = __pyx_v_graph; __Pyx_INCREF(__pyx_t_7); - __pyx_t_8 = __Pyx_PyInt_AsInt(__pyx_v_directed); if (unlikely((__pyx_t_8 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __Pyx_PyInt_AsInt(__pyx_v_directed); if (unlikely((__pyx_t_8 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_9.__pyx_n = 1; __pyx_t_9.directed = __pyx_t_8; - __pyx_t_2 = ((PyObject *)__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warshall(((PyArrayObject *)__pyx_t_7), &__pyx_t_9)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = ((PyObject *)__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warshall(((PyArrayObject *)__pyx_t_7), &__pyx_t_9)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - goto __pyx_L9; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L6; } - /* "sklearn/utils/graph_shortest_path.pyx":84 + /* "sklearn/utils/graph_shortest_path.pyx":86 * graph = np.asarray(dist_matrix.toarray(), dtype=DTYPE, order='C') * floyd_warshall(graph, directed) * elif method == 'D': # <<<<<<<<<<<<<< * graph = np.zeros((N, N), dtype=DTYPE, order='C') * dijkstra(dist_matrix, graph, directed) */ - __pyx_t_5 = __Pyx_PyString_Equals(__pyx_v_method, ((PyObject *)__pyx_n_s__D), Py_EQ); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_RichCompare(__pyx_v_method, ((PyObject *)__pyx_n_s__D), Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_5) { - /* "sklearn/utils/graph_shortest_path.pyx":85 + /* "sklearn/utils/graph_shortest_path.pyx":87 * floyd_warshall(graph, directed) * elif method == 'D': * graph = np.zeros((N, N), dtype=DTYPE, order='C') # <<<<<<<<<<<<<< * dijkstra(dist_matrix, graph, directed) * else: */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__zeros); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__zeros); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_N); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_N); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_N); __Pyx_GIVEREF(__pyx_v_N); __Pyx_INCREF(__pyx_v_N); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_N); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_N); __Pyx_GIVEREF(__pyx_v_N); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); - __pyx_t_2 = 0; - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = PyEval_CallObjectWithKeywords(__pyx_t_7, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_v_graph = __pyx_t_3; - __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_graph = __pyx_t_1; + __pyx_t_1 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":86 + /* "sklearn/utils/graph_shortest_path.pyx":88 * elif method == 'D': * graph = np.zeros((N, N), dtype=DTYPE, order='C') * dijkstra(dist_matrix, graph, directed) # <<<<<<<<<<<<<< * else: * raise ValueError("unrecognized method '%s'" % method) */ - if (!(likely(((__pyx_v_graph) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_graph, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __pyx_v_graph; - __Pyx_INCREF(__pyx_t_3); - __pyx_t_8 = __Pyx_PyInt_AsInt(__pyx_v_directed); if (unlikely((__pyx_t_8 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_v_graph) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_graph, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_v_graph; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_8 = __Pyx_PyInt_AsInt(__pyx_v_directed); if (unlikely((__pyx_t_8 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_10.__pyx_n = 1; __pyx_t_10.directed = __pyx_t_8; - __pyx_t_2 = ((PyObject *)__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(__pyx_v_dist_matrix, ((PyArrayObject *)__pyx_t_3), &__pyx_t_10)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = ((PyObject *)__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(__pyx_v_dist_matrix, ((PyArrayObject *)__pyx_t_1), &__pyx_t_10)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - goto __pyx_L9; + goto __pyx_L6; } /*else*/ { - /* "sklearn/utils/graph_shortest_path.pyx":88 + /* "sklearn/utils/graph_shortest_path.pyx":90 * dijkstra(dist_matrix, graph, directed) * else: * raise ValueError("unrecognized method '%s'" % method) # <<<<<<<<<<<<<< * * return graph */ - __pyx_t_2 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_2), __pyx_v_method); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_2), __pyx_v_method); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_2)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L9:; + __pyx_L6:; - /* "sklearn/utils/graph_shortest_path.pyx":90 + /* "sklearn/utils/graph_shortest_path.pyx":92 * raise ValueError("unrecognized method '%s'" % method) * * return graph # <<<<<<<<<<<<<< @@ -1617,6 +1730,7 @@ static PyObject *__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_p __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_N); + __Pyx_XDECREF(__pyx_v_Nk); __Pyx_XDECREF(__pyx_v_graph); __Pyx_XDECREF(__pyx_v_dist_matrix); __Pyx_XDECREF(__pyx_v_method); @@ -1625,7 +1739,7 @@ static PyObject *__pyx_pf_7sklearn_5utils_19graph_shortest_path_graph_shortest_p return __pyx_r; } -/* "sklearn/utils/graph_shortest_path.pyx":94 +/* "sklearn/utils/graph_shortest_path.pyx":96 * * @cython.boundscheck(False) * cdef np.ndarray floyd_warshall(np.ndarray[DTYPE_t, ndim=2, mode='c'] graph, # <<<<<<<<<<<<<< @@ -1641,11 +1755,8 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha unsigned int __pyx_v_k; __pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t __pyx_v_infinity; __pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t __pyx_v_sum_ijk; - Py_buffer __pyx_bstruct_graph; - Py_ssize_t __pyx_bstride_0_graph = 0; - Py_ssize_t __pyx_bstride_1_graph = 0; - Py_ssize_t __pyx_bshape_0_graph = 0; - Py_ssize_t __pyx_bshape_1_graph = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_graph; + __Pyx_Buffer __pyx_pybuffer_graph; PyArrayObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -1682,21 +1793,23 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("floyd_warshall"); + __Pyx_RefNannySetupContext("floyd_warshall", 0); if (__pyx_optional_args) { if (__pyx_optional_args->__pyx_n > 0) { __pyx_v_directed = __pyx_optional_args->directed; } } - __pyx_bstruct_graph.buf = NULL; + __pyx_pybuffer_graph.pybuffer.buf = NULL; + __pyx_pybuffer_graph.refcount = 0; + __pyx_pybuffernd_graph.data = NULL; + __pyx_pybuffernd_graph.rcbuffer = &__pyx_pybuffer_graph; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_graph, (PyObject*)__pyx_v_graph, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_graph.rcbuffer->pybuffer, (PyObject*)__pyx_v_graph, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_graph = __pyx_bstruct_graph.strides[0]; __pyx_bstride_1_graph = __pyx_bstruct_graph.strides[1]; - __pyx_bshape_0_graph = __pyx_bstruct_graph.shape[0]; __pyx_bshape_1_graph = __pyx_bstruct_graph.shape[1]; + __pyx_pybuffernd_graph.diminfo[0].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_graph.diminfo[0].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_graph.diminfo[1].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_graph.diminfo[1].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[1]; - /* "sklearn/utils/graph_shortest_path.pyx":117 + /* "sklearn/utils/graph_shortest_path.pyx":119 * If no path exists, the path length is zero * """ * cdef int N = graph.shape[0] # <<<<<<<<<<<<<< @@ -1705,7 +1818,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha */ __pyx_v_N = (__pyx_v_graph->dimensions[0]); - /* "sklearn/utils/graph_shortest_path.pyx":118 + /* "sklearn/utils/graph_shortest_path.pyx":120 * """ * cdef int N = graph.shape[0] * assert graph.shape[1] == N # <<<<<<<<<<<<<< @@ -1715,74 +1828,73 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!((__pyx_v_graph->dimensions[1]) == __pyx_v_N))) { PyErr_SetNone(PyExc_AssertionError); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #endif - /* "sklearn/utils/graph_shortest_path.pyx":122 + /* "sklearn/utils/graph_shortest_path.pyx":124 * cdef unsigned int i, j, k, m * * cdef DTYPE_t infinity = np.inf # <<<<<<<<<<<<<< * cdef DTYPE_t sum_ijk * */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_3 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_PyFloat_AsDouble(__pyx_t_2); if (unlikely((__pyx_t_3 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_infinity = __pyx_t_3; - /* "sklearn/utils/graph_shortest_path.pyx":126 + /* "sklearn/utils/graph_shortest_path.pyx":128 * * #initialize all distances to infinity * graph[np.where(graph == 0)] = infinity # <<<<<<<<<<<<<< * * #graph[i,i] should be zero */ - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_infinity); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_infinity); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__where); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__where); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_RichCompare(((PyObject *)__pyx_v_graph), __pyx_int_0, Py_EQ); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_1 = PyObject_RichCompare(((PyObject *)__pyx_v_graph), __pyx_int_0, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (PyObject_SetItem(((PyObject *)__pyx_v_graph), __pyx_t_1, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetItem(((PyObject *)__pyx_v_graph), __pyx_t_1, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":129 + /* "sklearn/utils/graph_shortest_path.pyx":131 * * #graph[i,i] should be zero * graph.flat[::N + 1] = 0 # <<<<<<<<<<<<<< * * # for a non-directed graph, we need to symmetrize the distances */ - __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_graph), __pyx_n_s__flat); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(((PyObject *)__pyx_v_graph), __pyx_n_s__flat); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyInt_FromLong((__pyx_v_N + 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyInt_FromLong((__pyx_v_N + 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = PySlice_New(Py_None, Py_None, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PySlice_New(Py_None, Py_None, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyObject_SetItem(__pyx_t_2, __pyx_t_5, __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetItem(__pyx_t_2, __pyx_t_5, __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":132 + /* "sklearn/utils/graph_shortest_path.pyx":134 * * # for a non-directed graph, we need to symmetrize the distances * if not directed: # <<<<<<<<<<<<<< @@ -1792,7 +1904,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha __pyx_t_6 = (!__pyx_v_directed); if (__pyx_t_6) { - /* "sklearn/utils/graph_shortest_path.pyx":133 + /* "sklearn/utils/graph_shortest_path.pyx":135 * # for a non-directed graph, we need to symmetrize the distances * if not directed: * for i from 0 <= i < N: # <<<<<<<<<<<<<< @@ -1802,7 +1914,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha __pyx_t_7 = __pyx_v_N; for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_7; __pyx_v_i++) { - /* "sklearn/utils/graph_shortest_path.pyx":134 + /* "sklearn/utils/graph_shortest_path.pyx":136 * if not directed: * for i from 0 <= i < N: * for j from i + 1 <= j < N: # <<<<<<<<<<<<<< @@ -1812,7 +1924,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha __pyx_t_8 = __pyx_v_N; for (__pyx_v_j = (__pyx_v_i + 1); __pyx_v_j < __pyx_t_8; __pyx_v_j++) { - /* "sklearn/utils/graph_shortest_path.pyx":135 + /* "sklearn/utils/graph_shortest_path.pyx":137 * for i from 0 <= i < N: * for j from i + 1 <= j < N: * if graph[j, i] <= graph[i, j]: # <<<<<<<<<<<<<< @@ -1823,10 +1935,10 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha __pyx_t_10 = __pyx_v_i; __pyx_t_11 = __pyx_v_i; __pyx_t_12 = __pyx_v_j; - __pyx_t_6 = ((*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_9, __pyx_bstride_0_graph, __pyx_t_10, __pyx_bstride_1_graph)) <= (*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_11, __pyx_bstride_0_graph, __pyx_t_12, __pyx_bstride_1_graph))); + __pyx_t_6 = ((*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_10, __pyx_pybuffernd_graph.diminfo[1].strides)) <= (*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_12, __pyx_pybuffernd_graph.diminfo[1].strides))); if (__pyx_t_6) { - /* "sklearn/utils/graph_shortest_path.pyx":136 + /* "sklearn/utils/graph_shortest_path.pyx":138 * for j from i + 1 <= j < N: * if graph[j, i] <= graph[i, j]: * graph[i, j] = graph[j, i] # <<<<<<<<<<<<<< @@ -1837,12 +1949,12 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha __pyx_t_14 = __pyx_v_i; __pyx_t_15 = __pyx_v_i; __pyx_t_16 = __pyx_v_j; - *__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_15, __pyx_bstride_0_graph, __pyx_t_16, __pyx_bstride_1_graph) = (*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_13, __pyx_bstride_0_graph, __pyx_t_14, __pyx_bstride_1_graph)); + *__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_16, __pyx_pybuffernd_graph.diminfo[1].strides) = (*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_14, __pyx_pybuffernd_graph.diminfo[1].strides)); goto __pyx_L8; } /*else*/ { - /* "sklearn/utils/graph_shortest_path.pyx":138 + /* "sklearn/utils/graph_shortest_path.pyx":140 * graph[i, j] = graph[j, i] * else: * graph[j, i] = graph[i, j] # <<<<<<<<<<<<<< @@ -1853,7 +1965,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha __pyx_t_18 = __pyx_v_j; __pyx_t_19 = __pyx_v_j; __pyx_t_20 = __pyx_v_i; - *__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_19, __pyx_bstride_0_graph, __pyx_t_20, __pyx_bstride_1_graph) = (*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_17, __pyx_bstride_0_graph, __pyx_t_18, __pyx_bstride_1_graph)); + *__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_20, __pyx_pybuffernd_graph.diminfo[1].strides) = (*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_18, __pyx_pybuffernd_graph.diminfo[1].strides)); } __pyx_L8:; } @@ -1862,7 +1974,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha } __pyx_L3:; - /* "sklearn/utils/graph_shortest_path.pyx":141 + /* "sklearn/utils/graph_shortest_path.pyx":143 * * #now perform the Floyd-Warshall algorithm * for k from 0 <= k < N: # <<<<<<<<<<<<<< @@ -1872,7 +1984,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha __pyx_t_7 = __pyx_v_N; for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_7; __pyx_v_k++) { - /* "sklearn/utils/graph_shortest_path.pyx":142 + /* "sklearn/utils/graph_shortest_path.pyx":144 * #now perform the Floyd-Warshall algorithm * for k from 0 <= k < N: * for i from 0 <= i < N: # <<<<<<<<<<<<<< @@ -1882,7 +1994,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha __pyx_t_8 = __pyx_v_N; for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_8; __pyx_v_i++) { - /* "sklearn/utils/graph_shortest_path.pyx":143 + /* "sklearn/utils/graph_shortest_path.pyx":145 * for k from 0 <= k < N: * for i from 0 <= i < N: * if graph[i, k] == infinity: # <<<<<<<<<<<<<< @@ -1891,10 +2003,10 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha */ __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_k; - __pyx_t_6 = ((*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_21, __pyx_bstride_0_graph, __pyx_t_22, __pyx_bstride_1_graph)) == __pyx_v_infinity); + __pyx_t_6 = ((*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_22, __pyx_pybuffernd_graph.diminfo[1].strides)) == __pyx_v_infinity); if (__pyx_t_6) { - /* "sklearn/utils/graph_shortest_path.pyx":144 + /* "sklearn/utils/graph_shortest_path.pyx":146 * for i from 0 <= i < N: * if graph[i, k] == infinity: * continue # <<<<<<<<<<<<<< @@ -1906,7 +2018,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha } __pyx_L13:; - /* "sklearn/utils/graph_shortest_path.pyx":145 + /* "sklearn/utils/graph_shortest_path.pyx":147 * if graph[i, k] == infinity: * continue * for j from 0 <= j < N: # <<<<<<<<<<<<<< @@ -1916,7 +2028,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha __pyx_t_23 = __pyx_v_N; for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_23; __pyx_v_j++) { - /* "sklearn/utils/graph_shortest_path.pyx":146 + /* "sklearn/utils/graph_shortest_path.pyx":148 * continue * for j from 0 <= j < N: * sum_ijk = graph[i, k] + graph[k, j] # <<<<<<<<<<<<<< @@ -1927,9 +2039,9 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha __pyx_t_25 = __pyx_v_k; __pyx_t_26 = __pyx_v_k; __pyx_t_27 = __pyx_v_j; - __pyx_v_sum_ijk = ((*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_24, __pyx_bstride_0_graph, __pyx_t_25, __pyx_bstride_1_graph)) + (*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_26, __pyx_bstride_0_graph, __pyx_t_27, __pyx_bstride_1_graph))); + __pyx_v_sum_ijk = ((*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_25, __pyx_pybuffernd_graph.diminfo[1].strides)) + (*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_26, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_27, __pyx_pybuffernd_graph.diminfo[1].strides))); - /* "sklearn/utils/graph_shortest_path.pyx":147 + /* "sklearn/utils/graph_shortest_path.pyx":149 * for j from 0 <= j < N: * sum_ijk = graph[i, k] + graph[k, j] * if sum_ijk < graph[i, j]: # <<<<<<<<<<<<<< @@ -1938,10 +2050,10 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha */ __pyx_t_28 = __pyx_v_i; __pyx_t_29 = __pyx_v_j; - __pyx_t_6 = (__pyx_v_sum_ijk < (*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_28, __pyx_bstride_0_graph, __pyx_t_29, __pyx_bstride_1_graph))); + __pyx_t_6 = (__pyx_v_sum_ijk < (*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_28, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_29, __pyx_pybuffernd_graph.diminfo[1].strides))); if (__pyx_t_6) { - /* "sklearn/utils/graph_shortest_path.pyx":148 + /* "sklearn/utils/graph_shortest_path.pyx":150 * sum_ijk = graph[i, k] + graph[k, j] * if sum_ijk < graph[i, j]: * graph[i, j] = sum_ijk # <<<<<<<<<<<<<< @@ -1950,7 +2062,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha */ __pyx_t_30 = __pyx_v_i; __pyx_t_31 = __pyx_v_j; - *__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_30, __pyx_bstride_0_graph, __pyx_t_31, __pyx_bstride_1_graph) = __pyx_v_sum_ijk; + *__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_30, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_31, __pyx_pybuffernd_graph.diminfo[1].strides) = __pyx_v_sum_ijk; goto __pyx_L16; } __pyx_L16:; @@ -1959,45 +2071,45 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha } } - /* "sklearn/utils/graph_shortest_path.pyx":150 + /* "sklearn/utils/graph_shortest_path.pyx":152 * graph[i, j] = sum_ijk * * graph[np.where(np.isinf(graph))] = 0 # <<<<<<<<<<<<<< * * return graph */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__where); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__where); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__isinf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__isinf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(((PyObject *)__pyx_v_graph)); PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_graph)); __Pyx_GIVEREF(((PyObject *)__pyx_v_graph)); - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (PyObject_SetItem(((PyObject *)__pyx_v_graph), __pyx_t_4, __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetItem(((PyObject *)__pyx_v_graph), __pyx_t_4, __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":152 + /* "sklearn/utils/graph_shortest_path.pyx":154 * graph[np.where(np.isinf(graph))] = 0 * * return graph # <<<<<<<<<<<<<< @@ -2018,20 +2130,20 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_floyd_warsha __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_graph); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.utils.graph_shortest_path.floyd_warshall", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_graph); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/utils/graph_shortest_path.pyx":156 +/* "sklearn/utils/graph_shortest_path.pyx":158 * * @cython.boundscheck(False) * cdef np.ndarray dijkstra(dist_matrix, # <<<<<<<<<<<<<< @@ -2052,11 +2164,8 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO PyArrayObject *__pyx_v_neighbors2 = 0; PyArrayObject *__pyx_v_indptr2 = 0; PyObject *__pyx_v_dist_matrix_T = NULL; - Py_buffer __pyx_bstruct_graph; - Py_ssize_t __pyx_bstride_0_graph = 0; - Py_ssize_t __pyx_bstride_1_graph = 0; - Py_ssize_t __pyx_bshape_0_graph = 0; - Py_ssize_t __pyx_bshape_1_graph = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_graph; + __Pyx_Buffer __pyx_pybuffer_graph; PyArrayObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -2069,22 +2178,24 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dijkstra"); + __Pyx_RefNannySetupContext("dijkstra", 0); if (__pyx_optional_args) { if (__pyx_optional_args->__pyx_n > 0) { __pyx_v_directed = __pyx_optional_args->directed; } } __Pyx_INCREF(__pyx_v_dist_matrix); - __pyx_bstruct_graph.buf = NULL; + __pyx_pybuffer_graph.pybuffer.buf = NULL; + __pyx_pybuffer_graph.refcount = 0; + __pyx_pybuffernd_graph.data = NULL; + __pyx_pybuffernd_graph.rcbuffer = &__pyx_pybuffer_graph; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_graph, (PyObject*)__pyx_v_graph, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_graph.rcbuffer->pybuffer, (PyObject*)__pyx_v_graph, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_graph = __pyx_bstruct_graph.strides[0]; __pyx_bstride_1_graph = __pyx_bstruct_graph.strides[1]; - __pyx_bshape_0_graph = __pyx_bstruct_graph.shape[0]; __pyx_bshape_1_graph = __pyx_bstruct_graph.shape[1]; + __pyx_pybuffernd_graph.diminfo[0].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_graph.diminfo[0].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_graph.diminfo[1].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_graph.diminfo[1].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[1]; - /* "sklearn/utils/graph_shortest_path.pyx":187 + /* "sklearn/utils/graph_shortest_path.pyx":189 * If no path exists, the path length is zero * """ * cdef unsigned int N = graph.shape[0] # <<<<<<<<<<<<<< @@ -2093,7 +2204,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO */ __pyx_v_N = (__pyx_v_graph->dimensions[0]); - /* "sklearn/utils/graph_shortest_path.pyx":193 + /* "sklearn/utils/graph_shortest_path.pyx":195 * * cdef FibonacciNode* nodes = malloc(N * * sizeof(FibonacciNode)) # <<<<<<<<<<<<<< @@ -2102,44 +2213,44 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO */ __pyx_v_nodes = ((struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *)malloc((__pyx_v_N * (sizeof(struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode))))); - /* "sklearn/utils/graph_shortest_path.pyx":198 + /* "sklearn/utils/graph_shortest_path.pyx":200 * cdef np.ndarray distances2, neighbors2, indptr2 * * if not isspmatrix_csr(dist_matrix): # <<<<<<<<<<<<<< * dist_matrix = csr_matrix(dist_matrix) * */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__isspmatrix_csr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__isspmatrix_csr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_dist_matrix); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_dist_matrix); __Pyx_GIVEREF(__pyx_v_dist_matrix); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 198; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_5 = (!__pyx_t_4); if (__pyx_t_5) { - /* "sklearn/utils/graph_shortest_path.pyx":199 + /* "sklearn/utils/graph_shortest_path.pyx":201 * * if not isspmatrix_csr(dist_matrix): * dist_matrix = csr_matrix(dist_matrix) # <<<<<<<<<<<<<< * * distances = np.asarray(dist_matrix.data, dtype=DTYPE, order='C') */ - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__csr_matrix); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__csr_matrix); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_dist_matrix); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_dist_matrix); __Pyx_GIVEREF(__pyx_v_dist_matrix); - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; @@ -2150,112 +2261,112 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO } __pyx_L3:; - /* "sklearn/utils/graph_shortest_path.pyx":201 + /* "sklearn/utils/graph_shortest_path.pyx":203 * dist_matrix = csr_matrix(dist_matrix) * * distances = np.asarray(dist_matrix.data, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< * neighbors = np.asarray(dist_matrix.indices, dtype=ITYPE, order='C') * indptr = np.asarray(dist_matrix.indptr, dtype=ITYPE, order='C') */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_distances = ((PyArrayObject *)__pyx_t_6); __pyx_t_6 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":202 + /* "sklearn/utils/graph_shortest_path.pyx":204 * * distances = np.asarray(dist_matrix.data, dtype=DTYPE, order='C') * neighbors = np.asarray(dist_matrix.indices, dtype=ITYPE, order='C') # <<<<<<<<<<<<<< * indptr = np.asarray(dist_matrix.indptr, dtype=ITYPE, order='C') * */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__indices); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__indices); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 202; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 204; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_neighbors = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":203 + /* "sklearn/utils/graph_shortest_path.pyx":205 * distances = np.asarray(dist_matrix.data, dtype=DTYPE, order='C') * neighbors = np.asarray(dist_matrix.indices, dtype=ITYPE, order='C') * indptr = np.asarray(dist_matrix.indptr, dtype=ITYPE, order='C') # <<<<<<<<<<<<<< * * for i from 0 <= i < N: */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__asarray); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__asarray); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__indptr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__indptr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = PyEval_CallObjectWithKeywords(__pyx_t_6, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_indptr = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":205 + /* "sklearn/utils/graph_shortest_path.pyx":207 * indptr = np.asarray(dist_matrix.indptr, dtype=ITYPE, order='C') * * for i from 0 <= i < N: # <<<<<<<<<<<<<< @@ -2265,7 +2376,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO __pyx_t_7 = __pyx_v_N; for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_7; __pyx_v_i++) { - /* "sklearn/utils/graph_shortest_path.pyx":206 + /* "sklearn/utils/graph_shortest_path.pyx":208 * * for i from 0 <= i < N: * initialize_node(&nodes[i], i) # <<<<<<<<<<<<<< @@ -2275,7 +2386,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node((&(__pyx_v_nodes[__pyx_v_i])), __pyx_v_i, NULL); } - /* "sklearn/utils/graph_shortest_path.pyx":208 + /* "sklearn/utils/graph_shortest_path.pyx":210 * initialize_node(&nodes[i], i) * * heap.min_node = NULL # <<<<<<<<<<<<<< @@ -2284,7 +2395,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO */ __pyx_v_heap.min_node = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":210 + /* "sklearn/utils/graph_shortest_path.pyx":212 * heap.min_node = NULL * * if directed: # <<<<<<<<<<<<<< @@ -2293,7 +2404,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO */ if (__pyx_v_directed) { - /* "sklearn/utils/graph_shortest_path.pyx":211 + /* "sklearn/utils/graph_shortest_path.pyx":213 * * if directed: * for i from 0 <= i < N: # <<<<<<<<<<<<<< @@ -2303,7 +2414,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO __pyx_t_7 = __pyx_v_N; for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_7; __pyx_v_i++) { - /* "sklearn/utils/graph_shortest_path.pyx":213 + /* "sklearn/utils/graph_shortest_path.pyx":215 * for i from 0 <= i < N: * dijkstra_directed_one_row(i, neighbors, distances, indptr, * graph, &heap, nodes) # <<<<<<<<<<<<<< @@ -2316,154 +2427,154 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO } /*else*/ { - /* "sklearn/utils/graph_shortest_path.pyx":217 + /* "sklearn/utils/graph_shortest_path.pyx":219 * #use the csr -> csc sparse matrix conversion to quickly get * # both directions of neigbors * dist_matrix_T = dist_matrix.T.tocsr() # <<<<<<<<<<<<<< * * distances2 = np.asarray(dist_matrix_T.data, */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__T); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_v_dist_matrix, __pyx_n_s__T); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__tocsr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__tocsr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_dist_matrix_T = __pyx_t_1; __pyx_t_1 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":219 + /* "sklearn/utils/graph_shortest_path.pyx":221 * dist_matrix_T = dist_matrix.T.tocsr() * * distances2 = np.asarray(dist_matrix_T.data, # <<<<<<<<<<<<<< * dtype=DTYPE, order='C') * neighbors2 = np.asarray(dist_matrix_T.indices, */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_v_dist_matrix_T, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_v_dist_matrix_T, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - /* "sklearn/utils/graph_shortest_path.pyx":220 + /* "sklearn/utils/graph_shortest_path.pyx":222 * * distances2 = np.asarray(dist_matrix_T.data, * dtype=DTYPE, order='C') # <<<<<<<<<<<<<< * neighbors2 = np.asarray(dist_matrix_T.indices, * dtype=ITYPE, order='C') */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_distances2 = ((PyArrayObject *)__pyx_t_6); __pyx_t_6 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":221 + /* "sklearn/utils/graph_shortest_path.pyx":223 * distances2 = np.asarray(dist_matrix_T.data, * dtype=DTYPE, order='C') * neighbors2 = np.asarray(dist_matrix_T.indices, # <<<<<<<<<<<<<< * dtype=ITYPE, order='C') * indptr2 = np.asarray(dist_matrix_T.indptr, */ - __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_t_6, __pyx_n_s__asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyObject_GetAttr(__pyx_v_dist_matrix_T, __pyx_n_s__indices); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyObject_GetAttr(__pyx_v_dist_matrix_T, __pyx_n_s__indices); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_6)); - /* "sklearn/utils/graph_shortest_path.pyx":222 + /* "sklearn/utils/graph_shortest_path.pyx":224 * dtype=DTYPE, order='C') * neighbors2 = np.asarray(dist_matrix_T.indices, * dtype=ITYPE, order='C') # <<<<<<<<<<<<<< * indptr2 = np.asarray(dist_matrix_T.indptr, * dtype=ITYPE, order='C') */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_neighbors2 = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":223 + /* "sklearn/utils/graph_shortest_path.pyx":225 * neighbors2 = np.asarray(dist_matrix_T.indices, * dtype=ITYPE, order='C') * indptr2 = np.asarray(dist_matrix_T.indptr, # <<<<<<<<<<<<<< * dtype=ITYPE, order='C') * */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__asarray); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__asarray); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetAttr(__pyx_v_dist_matrix_T, __pyx_n_s__indptr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_v_dist_matrix_T, __pyx_n_s__indptr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - /* "sklearn/utils/graph_shortest_path.pyx":224 + /* "sklearn/utils/graph_shortest_path.pyx":226 * dtype=ITYPE, order='C') * indptr2 = np.asarray(dist_matrix_T.indptr, * dtype=ITYPE, order='C') # <<<<<<<<<<<<<< * * for i from 0 <= i < N: */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = PyEval_CallObjectWithKeywords(__pyx_t_6, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_indptr2 = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":226 + /* "sklearn/utils/graph_shortest_path.pyx":228 * dtype=ITYPE, order='C') * * for i from 0 <= i < N: # <<<<<<<<<<<<<< @@ -2473,7 +2584,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO __pyx_t_7 = __pyx_v_N; for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_7; __pyx_v_i++) { - /* "sklearn/utils/graph_shortest_path.pyx":229 + /* "sklearn/utils/graph_shortest_path.pyx":231 * dijkstra_one_row(i, neighbors, distances, indptr, * neighbors2, distances2, indptr2, * graph, &heap, nodes) # <<<<<<<<<<<<<< @@ -2485,7 +2596,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO } __pyx_L6:; - /* "sklearn/utils/graph_shortest_path.pyx":231 + /* "sklearn/utils/graph_shortest_path.pyx":233 * graph, &heap, nodes) * * free(nodes) # <<<<<<<<<<<<<< @@ -2494,7 +2605,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO */ free(__pyx_v_nodes); - /* "sklearn/utils/graph_shortest_path.pyx":233 + /* "sklearn/utils/graph_shortest_path.pyx":235 * free(nodes) * * return graph # <<<<<<<<<<<<<< @@ -2515,13 +2626,13 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO __Pyx_XDECREF(__pyx_t_6); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_graph); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.utils.graph_shortest_path.dijkstra", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_graph); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_distances); __Pyx_XDECREF((PyObject *)__pyx_v_neighbors); @@ -2536,7 +2647,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO return __pyx_r; } -/* "sklearn/utils/graph_shortest_path.pyx":253 +/* "sklearn/utils/graph_shortest_path.pyx":255 * * * cdef void initialize_node(FibonacciNode* node, # <<<<<<<<<<<<<< @@ -2546,7 +2657,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra(PyO static void __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node(struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_node, unsigned int __pyx_v_index, struct __pyx_opt_args_7sklearn_5utils_19graph_shortest_path_initialize_node *__pyx_optional_args) { - /* "sklearn/utils/graph_shortest_path.pyx":255 + /* "sklearn/utils/graph_shortest_path.pyx":257 * cdef void initialize_node(FibonacciNode* node, * unsigned int index, * DTYPE_t val=0): # <<<<<<<<<<<<<< @@ -2555,14 +2666,14 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node(struct */ __pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t __pyx_v_val = ((__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t)0.0); __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("initialize_node"); + __Pyx_RefNannySetupContext("initialize_node", 0); if (__pyx_optional_args) { if (__pyx_optional_args->__pyx_n > 0) { __pyx_v_val = __pyx_optional_args->val; } } - /* "sklearn/utils/graph_shortest_path.pyx":258 + /* "sklearn/utils/graph_shortest_path.pyx":260 * # Assumptions: - node is a valid pointer * # - node is not currently part of a heap * node.index = index # <<<<<<<<<<<<<< @@ -2571,7 +2682,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node(struct */ __pyx_v_node->index = __pyx_v_index; - /* "sklearn/utils/graph_shortest_path.pyx":259 + /* "sklearn/utils/graph_shortest_path.pyx":261 * # - node is not currently part of a heap * node.index = index * node.val = val # <<<<<<<<<<<<<< @@ -2580,7 +2691,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node(struct */ __pyx_v_node->val = __pyx_v_val; - /* "sklearn/utils/graph_shortest_path.pyx":260 + /* "sklearn/utils/graph_shortest_path.pyx":262 * node.index = index * node.val = val * node.rank = 0 # <<<<<<<<<<<<<< @@ -2589,7 +2700,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node(struct */ __pyx_v_node->rank = 0; - /* "sklearn/utils/graph_shortest_path.pyx":261 + /* "sklearn/utils/graph_shortest_path.pyx":263 * node.val = val * node.rank = 0 * node.state = 0 # 0 -> NOT_IN_HEAP # <<<<<<<<<<<<<< @@ -2598,7 +2709,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node(struct */ __pyx_v_node->state = 0; - /* "sklearn/utils/graph_shortest_path.pyx":263 + /* "sklearn/utils/graph_shortest_path.pyx":265 * node.state = 0 # 0 -> NOT_IN_HEAP * * node.parent = NULL # <<<<<<<<<<<<<< @@ -2607,7 +2718,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node(struct */ __pyx_v_node->parent = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":264 + /* "sklearn/utils/graph_shortest_path.pyx":266 * * node.parent = NULL * node.left_sibling = NULL # <<<<<<<<<<<<<< @@ -2616,7 +2727,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node(struct */ __pyx_v_node->left_sibling = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":265 + /* "sklearn/utils/graph_shortest_path.pyx":267 * node.parent = NULL * node.left_sibling = NULL * node.right_sibling = NULL # <<<<<<<<<<<<<< @@ -2625,7 +2736,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node(struct */ __pyx_v_node->right_sibling = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":266 + /* "sklearn/utils/graph_shortest_path.pyx":268 * node.left_sibling = NULL * node.right_sibling = NULL * node.children = NULL # <<<<<<<<<<<<<< @@ -2637,7 +2748,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node(struct __Pyx_RefNannyFinishContext(); } -/* "sklearn/utils/graph_shortest_path.pyx":269 +/* "sklearn/utils/graph_shortest_path.pyx":271 * * * cdef FibonacciNode* rightmost_sibling(FibonacciNode* node): # <<<<<<<<<<<<<< @@ -2650,9 +2761,10 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("rightmost_sibling"); + struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_t_2; + __Pyx_RefNannySetupContext("rightmost_sibling", 0); - /* "sklearn/utils/graph_shortest_path.pyx":271 + /* "sklearn/utils/graph_shortest_path.pyx":273 * cdef FibonacciNode* rightmost_sibling(FibonacciNode* node): * # Assumptions: - node is a valid pointer * cdef FibonacciNode* temp = node # <<<<<<<<<<<<<< @@ -2661,7 +2773,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ __pyx_v_temp = __pyx_v_node; - /* "sklearn/utils/graph_shortest_path.pyx":272 + /* "sklearn/utils/graph_shortest_path.pyx":274 * # Assumptions: - node is a valid pointer * cdef FibonacciNode* temp = node * while(temp.right_sibling): # <<<<<<<<<<<<<< @@ -2672,17 +2784,18 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx __pyx_t_1 = (__pyx_v_temp->right_sibling != 0); if (!__pyx_t_1) break; - /* "sklearn/utils/graph_shortest_path.pyx":273 + /* "sklearn/utils/graph_shortest_path.pyx":275 * cdef FibonacciNode* temp = node * while(temp.right_sibling): * temp = temp.right_sibling # <<<<<<<<<<<<<< * return temp * */ - __pyx_v_temp = __pyx_v_temp->right_sibling; + __pyx_t_2 = __pyx_v_temp->right_sibling; + __pyx_v_temp = __pyx_t_2; } - /* "sklearn/utils/graph_shortest_path.pyx":274 + /* "sklearn/utils/graph_shortest_path.pyx":276 * while(temp.right_sibling): * temp = temp.right_sibling * return temp # <<<<<<<<<<<<<< @@ -2698,7 +2811,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx return __pyx_r; } -/* "sklearn/utils/graph_shortest_path.pyx":277 +/* "sklearn/utils/graph_shortest_path.pyx":279 * * * cdef FibonacciNode* leftmost_sibling(FibonacciNode* node): # <<<<<<<<<<<<<< @@ -2711,9 +2824,10 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("leftmost_sibling"); + struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_t_2; + __Pyx_RefNannySetupContext("leftmost_sibling", 0); - /* "sklearn/utils/graph_shortest_path.pyx":279 + /* "sklearn/utils/graph_shortest_path.pyx":281 * cdef FibonacciNode* leftmost_sibling(FibonacciNode* node): * # Assumptions: - node is a valid pointer * cdef FibonacciNode* temp = node # <<<<<<<<<<<<<< @@ -2722,7 +2836,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ __pyx_v_temp = __pyx_v_node; - /* "sklearn/utils/graph_shortest_path.pyx":280 + /* "sklearn/utils/graph_shortest_path.pyx":282 * # Assumptions: - node is a valid pointer * cdef FibonacciNode* temp = node * while(temp.left_sibling): # <<<<<<<<<<<<<< @@ -2733,17 +2847,18 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx __pyx_t_1 = (__pyx_v_temp->left_sibling != 0); if (!__pyx_t_1) break; - /* "sklearn/utils/graph_shortest_path.pyx":281 + /* "sklearn/utils/graph_shortest_path.pyx":283 * cdef FibonacciNode* temp = node * while(temp.left_sibling): * temp = temp.left_sibling # <<<<<<<<<<<<<< * return temp * */ - __pyx_v_temp = __pyx_v_temp->left_sibling; + __pyx_t_2 = __pyx_v_temp->left_sibling; + __pyx_v_temp = __pyx_t_2; } - /* "sklearn/utils/graph_shortest_path.pyx":282 + /* "sklearn/utils/graph_shortest_path.pyx":284 * while(temp.left_sibling): * temp = temp.left_sibling * return temp # <<<<<<<<<<<<<< @@ -2759,7 +2874,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx return __pyx_r; } -/* "sklearn/utils/graph_shortest_path.pyx":285 +/* "sklearn/utils/graph_shortest_path.pyx":287 * * * cdef void add_child(FibonacciNode* node, FibonacciNode* new_child): # <<<<<<<<<<<<<< @@ -2770,9 +2885,9 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_child(struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_node, struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_new_child) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("add_child"); + __Pyx_RefNannySetupContext("add_child", 0); - /* "sklearn/utils/graph_shortest_path.pyx":289 + /* "sklearn/utils/graph_shortest_path.pyx":291 * # - new_child is a valid pointer * # - new_child is not the sibling or child of another node * new_child.parent = node # <<<<<<<<<<<<<< @@ -2781,7 +2896,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_child(struct __pyx */ __pyx_v_new_child->parent = __pyx_v_node; - /* "sklearn/utils/graph_shortest_path.pyx":291 + /* "sklearn/utils/graph_shortest_path.pyx":293 * new_child.parent = node * * if node.children: # <<<<<<<<<<<<<< @@ -2791,7 +2906,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_child(struct __pyx __pyx_t_1 = (__pyx_v_node->children != 0); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":292 + /* "sklearn/utils/graph_shortest_path.pyx":294 * * if node.children: * add_sibling(node.children, new_child) # <<<<<<<<<<<<<< @@ -2803,7 +2918,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_child(struct __pyx } /*else*/ { - /* "sklearn/utils/graph_shortest_path.pyx":294 + /* "sklearn/utils/graph_shortest_path.pyx":296 * add_sibling(node.children, new_child) * else: * node.children = new_child # <<<<<<<<<<<<<< @@ -2812,7 +2927,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_child(struct __pyx */ __pyx_v_node->children = __pyx_v_new_child; - /* "sklearn/utils/graph_shortest_path.pyx":295 + /* "sklearn/utils/graph_shortest_path.pyx":297 * else: * node.children = new_child * new_child.right_sibling = NULL # <<<<<<<<<<<<<< @@ -2821,7 +2936,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_child(struct __pyx */ __pyx_v_new_child->right_sibling = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":296 + /* "sklearn/utils/graph_shortest_path.pyx":298 * node.children = new_child * new_child.right_sibling = NULL * new_child.left_sibling = NULL # <<<<<<<<<<<<<< @@ -2830,7 +2945,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_child(struct __pyx */ __pyx_v_new_child->left_sibling = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":297 + /* "sklearn/utils/graph_shortest_path.pyx":299 * new_child.right_sibling = NULL * new_child.left_sibling = NULL * node.rank = 1 # <<<<<<<<<<<<<< @@ -2844,7 +2959,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_child(struct __pyx __Pyx_RefNannyFinishContext(); } -/* "sklearn/utils/graph_shortest_path.pyx":300 +/* "sklearn/utils/graph_shortest_path.pyx":302 * * * cdef void add_sibling(FibonacciNode* node, FibonacciNode* new_sibling): # <<<<<<<<<<<<<< @@ -2855,10 +2970,11 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_child(struct __pyx static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_sibling(struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_node, struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_new_sibling) { struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_temp; __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("add_sibling"); + struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("add_sibling", 0); - /* "sklearn/utils/graph_shortest_path.pyx":304 + /* "sklearn/utils/graph_shortest_path.pyx":306 * # - new_sibling is a valid pointer * # - new_sibling is not the child or sibling of another node * cdef FibonacciNode* temp = rightmost_sibling(node) # <<<<<<<<<<<<<< @@ -2867,7 +2983,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_sibling(struct __p */ __pyx_v_temp = __pyx_f_7sklearn_5utils_19graph_shortest_path_rightmost_sibling(__pyx_v_node); - /* "sklearn/utils/graph_shortest_path.pyx":305 + /* "sklearn/utils/graph_shortest_path.pyx":307 * # - new_sibling is not the child or sibling of another node * cdef FibonacciNode* temp = rightmost_sibling(node) * temp.right_sibling = new_sibling # <<<<<<<<<<<<<< @@ -2876,7 +2992,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_sibling(struct __p */ __pyx_v_temp->right_sibling = __pyx_v_new_sibling; - /* "sklearn/utils/graph_shortest_path.pyx":306 + /* "sklearn/utils/graph_shortest_path.pyx":308 * cdef FibonacciNode* temp = rightmost_sibling(node) * temp.right_sibling = new_sibling * new_sibling.left_sibling = temp # <<<<<<<<<<<<<< @@ -2885,7 +3001,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_sibling(struct __p */ __pyx_v_new_sibling->left_sibling = __pyx_v_temp; - /* "sklearn/utils/graph_shortest_path.pyx":307 + /* "sklearn/utils/graph_shortest_path.pyx":309 * temp.right_sibling = new_sibling * new_sibling.left_sibling = temp * new_sibling.right_sibling = NULL # <<<<<<<<<<<<<< @@ -2894,26 +3010,27 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_sibling(struct __p */ __pyx_v_new_sibling->right_sibling = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":308 + /* "sklearn/utils/graph_shortest_path.pyx":310 * new_sibling.left_sibling = temp * new_sibling.right_sibling = NULL * new_sibling.parent = node.parent # <<<<<<<<<<<<<< * if new_sibling.parent: * new_sibling.parent.rank += 1 */ - __pyx_v_new_sibling->parent = __pyx_v_node->parent; + __pyx_t_1 = __pyx_v_node->parent; + __pyx_v_new_sibling->parent = __pyx_t_1; - /* "sklearn/utils/graph_shortest_path.pyx":309 + /* "sklearn/utils/graph_shortest_path.pyx":311 * new_sibling.right_sibling = NULL * new_sibling.parent = node.parent * if new_sibling.parent: # <<<<<<<<<<<<<< * new_sibling.parent.rank += 1 * */ - __pyx_t_1 = (__pyx_v_new_sibling->parent != 0); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v_new_sibling->parent != 0); + if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":310 + /* "sklearn/utils/graph_shortest_path.pyx":312 * new_sibling.parent = node.parent * if new_sibling.parent: * new_sibling.parent.rank += 1 # <<<<<<<<<<<<<< @@ -2928,7 +3045,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_sibling(struct __p __Pyx_RefNannyFinishContext(); } -/* "sklearn/utils/graph_shortest_path.pyx":313 +/* "sklearn/utils/graph_shortest_path.pyx":315 * * * cdef void remove(FibonacciNode* node): # <<<<<<<<<<<<<< @@ -2939,9 +3056,10 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_add_sibling(struct __p static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_node) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("remove"); + struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_t_2; + __Pyx_RefNannySetupContext("remove", 0); - /* "sklearn/utils/graph_shortest_path.pyx":315 + /* "sklearn/utils/graph_shortest_path.pyx":317 * cdef void remove(FibonacciNode* node): * # Assumptions: - node is a valid pointer * if node.parent: # <<<<<<<<<<<<<< @@ -2951,7 +3069,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_ __pyx_t_1 = (__pyx_v_node->parent != 0); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":316 + /* "sklearn/utils/graph_shortest_path.pyx":318 * # Assumptions: - node is a valid pointer * if node.parent: * node.parent.rank -= 1 # <<<<<<<<<<<<<< @@ -2960,7 +3078,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_ */ __pyx_v_node->parent->rank = (__pyx_v_node->parent->rank - 1); - /* "sklearn/utils/graph_shortest_path.pyx":317 + /* "sklearn/utils/graph_shortest_path.pyx":319 * if node.parent: * node.parent.rank -= 1 * if node.left_sibling: # <<<<<<<<<<<<<< @@ -2970,18 +3088,19 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_ __pyx_t_1 = (__pyx_v_node->left_sibling != 0); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":318 + /* "sklearn/utils/graph_shortest_path.pyx":320 * node.parent.rank -= 1 * if node.left_sibling: * node.parent.children = node.left_sibling # <<<<<<<<<<<<<< * elif node.right_sibling: * node.parent.children = node.right_sibling */ - __pyx_v_node->parent->children = __pyx_v_node->left_sibling; + __pyx_t_2 = __pyx_v_node->left_sibling; + __pyx_v_node->parent->children = __pyx_t_2; goto __pyx_L4; } - /* "sklearn/utils/graph_shortest_path.pyx":319 + /* "sklearn/utils/graph_shortest_path.pyx":321 * if node.left_sibling: * node.parent.children = node.left_sibling * elif node.right_sibling: # <<<<<<<<<<<<<< @@ -2991,19 +3110,20 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_ __pyx_t_1 = (__pyx_v_node->right_sibling != 0); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":320 + /* "sklearn/utils/graph_shortest_path.pyx":322 * node.parent.children = node.left_sibling * elif node.right_sibling: * node.parent.children = node.right_sibling # <<<<<<<<<<<<<< * else: * node.parent.children = NULL */ - __pyx_v_node->parent->children = __pyx_v_node->right_sibling; + __pyx_t_2 = __pyx_v_node->right_sibling; + __pyx_v_node->parent->children = __pyx_t_2; goto __pyx_L4; } /*else*/ { - /* "sklearn/utils/graph_shortest_path.pyx":322 + /* "sklearn/utils/graph_shortest_path.pyx":324 * node.parent.children = node.right_sibling * else: * node.parent.children = NULL # <<<<<<<<<<<<<< @@ -3017,7 +3137,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_ } __pyx_L3:; - /* "sklearn/utils/graph_shortest_path.pyx":324 + /* "sklearn/utils/graph_shortest_path.pyx":326 * node.parent.children = NULL * * if node.left_sibling: # <<<<<<<<<<<<<< @@ -3027,19 +3147,20 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_ __pyx_t_1 = (__pyx_v_node->left_sibling != 0); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":325 + /* "sklearn/utils/graph_shortest_path.pyx":327 * * if node.left_sibling: * node.left_sibling.right_sibling = node.right_sibling # <<<<<<<<<<<<<< * if node.right_sibling: * node.right_sibling.left_sibling = node.left_sibling */ - __pyx_v_node->left_sibling->right_sibling = __pyx_v_node->right_sibling; + __pyx_t_2 = __pyx_v_node->right_sibling; + __pyx_v_node->left_sibling->right_sibling = __pyx_t_2; goto __pyx_L5; } __pyx_L5:; - /* "sklearn/utils/graph_shortest_path.pyx":326 + /* "sklearn/utils/graph_shortest_path.pyx":328 * if node.left_sibling: * node.left_sibling.right_sibling = node.right_sibling * if node.right_sibling: # <<<<<<<<<<<<<< @@ -3049,19 +3170,20 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_ __pyx_t_1 = (__pyx_v_node->right_sibling != 0); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":327 + /* "sklearn/utils/graph_shortest_path.pyx":329 * node.left_sibling.right_sibling = node.right_sibling * if node.right_sibling: * node.right_sibling.left_sibling = node.left_sibling # <<<<<<<<<<<<<< * * node.left_sibling = NULL */ - __pyx_v_node->right_sibling->left_sibling = __pyx_v_node->left_sibling; + __pyx_t_2 = __pyx_v_node->left_sibling; + __pyx_v_node->right_sibling->left_sibling = __pyx_t_2; goto __pyx_L6; } __pyx_L6:; - /* "sklearn/utils/graph_shortest_path.pyx":329 + /* "sklearn/utils/graph_shortest_path.pyx":331 * node.right_sibling.left_sibling = node.left_sibling * * node.left_sibling = NULL # <<<<<<<<<<<<<< @@ -3070,7 +3192,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_ */ __pyx_v_node->left_sibling = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":330 + /* "sklearn/utils/graph_shortest_path.pyx":332 * * node.left_sibling = NULL * node.right_sibling = NULL # <<<<<<<<<<<<<< @@ -3079,7 +3201,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_ */ __pyx_v_node->right_sibling = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":331 + /* "sklearn/utils/graph_shortest_path.pyx":333 * node.left_sibling = NULL * node.right_sibling = NULL * node.parent = NULL # <<<<<<<<<<<<<< @@ -3091,7 +3213,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_ __Pyx_RefNannyFinishContext(); } -/* "sklearn/utils/graph_shortest_path.pyx":347 +/* "sklearn/utils/graph_shortest_path.pyx":349 * * * cdef void insert_node(FibonacciHeap* heap, # <<<<<<<<<<<<<< @@ -3102,9 +3224,9 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(struct __pyx_t_ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_insert_node(struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciHeap *__pyx_v_heap, struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_node) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("insert_node"); + __Pyx_RefNannySetupContext("insert_node", 0); - /* "sklearn/utils/graph_shortest_path.pyx":352 + /* "sklearn/utils/graph_shortest_path.pyx":354 * # - node is a valid pointer * # - node is not the child or sibling of another node * if heap.min_node: # <<<<<<<<<<<<<< @@ -3114,7 +3236,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_insert_node(struct __p __pyx_t_1 = (__pyx_v_heap->min_node != 0); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":353 + /* "sklearn/utils/graph_shortest_path.pyx":355 * # - node is not the child or sibling of another node * if heap.min_node: * add_sibling(heap.min_node, node) # <<<<<<<<<<<<<< @@ -3123,7 +3245,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_insert_node(struct __p */ __pyx_f_7sklearn_5utils_19graph_shortest_path_add_sibling(__pyx_v_heap->min_node, __pyx_v_node); - /* "sklearn/utils/graph_shortest_path.pyx":354 + /* "sklearn/utils/graph_shortest_path.pyx":356 * if heap.min_node: * add_sibling(heap.min_node, node) * if node.val < heap.min_node.val: # <<<<<<<<<<<<<< @@ -3133,7 +3255,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_insert_node(struct __p __pyx_t_1 = (__pyx_v_node->val < __pyx_v_heap->min_node->val); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":355 + /* "sklearn/utils/graph_shortest_path.pyx":357 * add_sibling(heap.min_node, node) * if node.val < heap.min_node.val: * heap.min_node = node # <<<<<<<<<<<<<< @@ -3148,7 +3270,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_insert_node(struct __p } /*else*/ { - /* "sklearn/utils/graph_shortest_path.pyx":357 + /* "sklearn/utils/graph_shortest_path.pyx":359 * heap.min_node = node * else: * heap.min_node = node # <<<<<<<<<<<<<< @@ -3162,7 +3284,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_insert_node(struct __p __Pyx_RefNannyFinishContext(); } -/* "sklearn/utils/graph_shortest_path.pyx":360 +/* "sklearn/utils/graph_shortest_path.pyx":362 * * * cdef void decrease_val(FibonacciHeap* heap, # <<<<<<<<<<<<<< @@ -3174,9 +3296,9 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_decrease_val(struct __ __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; - __Pyx_RefNannySetupContext("decrease_val"); + __Pyx_RefNannySetupContext("decrease_val", 0); - /* "sklearn/utils/graph_shortest_path.pyx":367 + /* "sklearn/utils/graph_shortest_path.pyx":369 * # - node is a valid pointer * # - node is not the child or sibling of another node * node.val = newval # <<<<<<<<<<<<<< @@ -3185,7 +3307,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_decrease_val(struct __ */ __pyx_v_node->val = __pyx_v_newval; - /* "sklearn/utils/graph_shortest_path.pyx":368 + /* "sklearn/utils/graph_shortest_path.pyx":370 * # - node is not the child or sibling of another node * node.val = newval * if node.parent and (node.parent.val >= newval): # <<<<<<<<<<<<<< @@ -3200,7 +3322,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_decrease_val(struct __ } if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":369 + /* "sklearn/utils/graph_shortest_path.pyx":371 * node.val = newval * if node.parent and (node.parent.val >= newval): * remove(node) # <<<<<<<<<<<<<< @@ -3209,7 +3331,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_decrease_val(struct __ */ __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(__pyx_v_node); - /* "sklearn/utils/graph_shortest_path.pyx":370 + /* "sklearn/utils/graph_shortest_path.pyx":372 * if node.parent and (node.parent.val >= newval): * remove(node) * insert_node(heap, node) # <<<<<<<<<<<<<< @@ -3220,7 +3342,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_decrease_val(struct __ goto __pyx_L3; } - /* "sklearn/utils/graph_shortest_path.pyx":371 + /* "sklearn/utils/graph_shortest_path.pyx":373 * remove(node) * insert_node(heap, node) * elif heap.min_node.val > node.val: # <<<<<<<<<<<<<< @@ -3230,7 +3352,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_decrease_val(struct __ __pyx_t_2 = (__pyx_v_heap->min_node->val > __pyx_v_node->val); if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":372 + /* "sklearn/utils/graph_shortest_path.pyx":374 * insert_node(heap, node) * elif heap.min_node.val > node.val: * heap.min_node = node # <<<<<<<<<<<<<< @@ -3245,7 +3367,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_decrease_val(struct __ __Pyx_RefNannyFinishContext(); } -/* "sklearn/utils/graph_shortest_path.pyx":375 +/* "sklearn/utils/graph_shortest_path.pyx":377 * * * cdef void link(FibonacciHeap* heap, FibonacciNode* node): # <<<<<<<<<<<<<< @@ -3259,9 +3381,9 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; - __Pyx_RefNannySetupContext("link"); + __Pyx_RefNannySetupContext("link", 0); - /* "sklearn/utils/graph_shortest_path.pyx":382 + /* "sklearn/utils/graph_shortest_path.pyx":384 * cdef FibonacciNode *linknode, *parent, *child * * if heap.roots_by_rank[node.rank] == NULL: # <<<<<<<<<<<<<< @@ -3271,7 +3393,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s __pyx_t_1 = ((__pyx_v_heap->roots_by_rank[__pyx_v_node->rank]) == NULL); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":383 + /* "sklearn/utils/graph_shortest_path.pyx":385 * * if heap.roots_by_rank[node.rank] == NULL: * heap.roots_by_rank[node.rank] = node # <<<<<<<<<<<<<< @@ -3283,7 +3405,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s } /*else*/ { - /* "sklearn/utils/graph_shortest_path.pyx":385 + /* "sklearn/utils/graph_shortest_path.pyx":387 * heap.roots_by_rank[node.rank] = node * else: * linknode = heap.roots_by_rank[node.rank] # <<<<<<<<<<<<<< @@ -3292,7 +3414,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s */ __pyx_v_linknode = (__pyx_v_heap->roots_by_rank[__pyx_v_node->rank]); - /* "sklearn/utils/graph_shortest_path.pyx":386 + /* "sklearn/utils/graph_shortest_path.pyx":388 * else: * linknode = heap.roots_by_rank[node.rank] * heap.roots_by_rank[node.rank] = NULL # <<<<<<<<<<<<<< @@ -3301,7 +3423,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s */ (__pyx_v_heap->roots_by_rank[__pyx_v_node->rank]) = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":388 + /* "sklearn/utils/graph_shortest_path.pyx":390 * heap.roots_by_rank[node.rank] = NULL * * if node.val < linknode.val or node == heap.min_node: # <<<<<<<<<<<<<< @@ -3317,7 +3439,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s } if (__pyx_t_3) { - /* "sklearn/utils/graph_shortest_path.pyx":389 + /* "sklearn/utils/graph_shortest_path.pyx":391 * * if node.val < linknode.val or node == heap.min_node: * remove(linknode) # <<<<<<<<<<<<<< @@ -3326,7 +3448,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s */ __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(__pyx_v_linknode); - /* "sklearn/utils/graph_shortest_path.pyx":390 + /* "sklearn/utils/graph_shortest_path.pyx":392 * if node.val < linknode.val or node == heap.min_node: * remove(linknode) * add_child(node, linknode) # <<<<<<<<<<<<<< @@ -3335,7 +3457,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s */ __pyx_f_7sklearn_5utils_19graph_shortest_path_add_child(__pyx_v_node, __pyx_v_linknode); - /* "sklearn/utils/graph_shortest_path.pyx":391 + /* "sklearn/utils/graph_shortest_path.pyx":393 * remove(linknode) * add_child(node, linknode) * link(heap, node) # <<<<<<<<<<<<<< @@ -3347,7 +3469,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s } /*else*/ { - /* "sklearn/utils/graph_shortest_path.pyx":393 + /* "sklearn/utils/graph_shortest_path.pyx":395 * link(heap, node) * else: * remove(node) # <<<<<<<<<<<<<< @@ -3356,7 +3478,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s */ __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(__pyx_v_node); - /* "sklearn/utils/graph_shortest_path.pyx":394 + /* "sklearn/utils/graph_shortest_path.pyx":396 * else: * remove(node) * add_child(linknode, node) # <<<<<<<<<<<<<< @@ -3365,7 +3487,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s */ __pyx_f_7sklearn_5utils_19graph_shortest_path_add_child(__pyx_v_linknode, __pyx_v_node); - /* "sklearn/utils/graph_shortest_path.pyx":395 + /* "sklearn/utils/graph_shortest_path.pyx":397 * remove(node) * add_child(linknode, node) * link(heap, linknode) # <<<<<<<<<<<<<< @@ -3381,7 +3503,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_link(struct __pyx_t_7s __Pyx_RefNannyFinishContext(); } -/* "sklearn/utils/graph_shortest_path.pyx":398 +/* "sklearn/utils/graph_shortest_path.pyx":400 * * * cdef FibonacciNode* remove_min(FibonacciHeap* heap): # <<<<<<<<<<<<<< @@ -3397,9 +3519,10 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("remove_min"); + struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_t_2; + __Pyx_RefNannySetupContext("remove_min", 0); - /* "sklearn/utils/graph_shortest_path.pyx":405 + /* "sklearn/utils/graph_shortest_path.pyx":407 * * # make all min_node children into root nodes * if heap.min_node.children: # <<<<<<<<<<<<<< @@ -3409,7 +3532,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx __pyx_t_1 = (__pyx_v_heap->min_node->children != 0); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":406 + /* "sklearn/utils/graph_shortest_path.pyx":408 * # make all min_node children into root nodes * if heap.min_node.children: * temp = leftmost_sibling(heap.min_node.children) # <<<<<<<<<<<<<< @@ -3418,7 +3541,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ __pyx_v_temp = __pyx_f_7sklearn_5utils_19graph_shortest_path_leftmost_sibling(__pyx_v_heap->min_node->children); - /* "sklearn/utils/graph_shortest_path.pyx":407 + /* "sklearn/utils/graph_shortest_path.pyx":409 * if heap.min_node.children: * temp = leftmost_sibling(heap.min_node.children) * temp_right = NULL # <<<<<<<<<<<<<< @@ -3427,7 +3550,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ __pyx_v_temp_right = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":409 + /* "sklearn/utils/graph_shortest_path.pyx":411 * temp_right = NULL * * while temp: # <<<<<<<<<<<<<< @@ -3438,16 +3561,17 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx __pyx_t_1 = (__pyx_v_temp != 0); if (!__pyx_t_1) break; - /* "sklearn/utils/graph_shortest_path.pyx":410 + /* "sklearn/utils/graph_shortest_path.pyx":412 * * while temp: * temp_right = temp.right_sibling # <<<<<<<<<<<<<< * remove(temp) * add_sibling(heap.min_node, temp) */ - __pyx_v_temp_right = __pyx_v_temp->right_sibling; + __pyx_t_2 = __pyx_v_temp->right_sibling; + __pyx_v_temp_right = __pyx_t_2; - /* "sklearn/utils/graph_shortest_path.pyx":411 + /* "sklearn/utils/graph_shortest_path.pyx":413 * while temp: * temp_right = temp.right_sibling * remove(temp) # <<<<<<<<<<<<<< @@ -3456,7 +3580,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(__pyx_v_temp); - /* "sklearn/utils/graph_shortest_path.pyx":412 + /* "sklearn/utils/graph_shortest_path.pyx":414 * temp_right = temp.right_sibling * remove(temp) * add_sibling(heap.min_node, temp) # <<<<<<<<<<<<<< @@ -3465,7 +3589,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ __pyx_f_7sklearn_5utils_19graph_shortest_path_add_sibling(__pyx_v_heap->min_node, __pyx_v_temp); - /* "sklearn/utils/graph_shortest_path.pyx":413 + /* "sklearn/utils/graph_shortest_path.pyx":415 * remove(temp) * add_sibling(heap.min_node, temp) * temp = temp_right # <<<<<<<<<<<<<< @@ -3475,7 +3599,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx __pyx_v_temp = __pyx_v_temp_right; } - /* "sklearn/utils/graph_shortest_path.pyx":415 + /* "sklearn/utils/graph_shortest_path.pyx":417 * temp = temp_right * * heap.min_node.children = NULL # <<<<<<<<<<<<<< @@ -3487,7 +3611,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx } __pyx_L3:; - /* "sklearn/utils/graph_shortest_path.pyx":418 + /* "sklearn/utils/graph_shortest_path.pyx":420 * * # choose a root node other than min_node * temp = leftmost_sibling(heap.min_node) # <<<<<<<<<<<<<< @@ -3496,7 +3620,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ __pyx_v_temp = __pyx_f_7sklearn_5utils_19graph_shortest_path_leftmost_sibling(__pyx_v_heap->min_node); - /* "sklearn/utils/graph_shortest_path.pyx":419 + /* "sklearn/utils/graph_shortest_path.pyx":421 * # choose a root node other than min_node * temp = leftmost_sibling(heap.min_node) * if temp == heap.min_node: # <<<<<<<<<<<<<< @@ -3506,7 +3630,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx __pyx_t_1 = (__pyx_v_temp == __pyx_v_heap->min_node); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":420 + /* "sklearn/utils/graph_shortest_path.pyx":422 * temp = leftmost_sibling(heap.min_node) * if temp == heap.min_node: * if heap.min_node.right_sibling: # <<<<<<<<<<<<<< @@ -3516,28 +3640,30 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx __pyx_t_1 = (__pyx_v_heap->min_node->right_sibling != 0); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":421 + /* "sklearn/utils/graph_shortest_path.pyx":423 * if temp == heap.min_node: * if heap.min_node.right_sibling: * temp = heap.min_node.right_sibling # <<<<<<<<<<<<<< * else: * out = heap.min_node */ - __pyx_v_temp = __pyx_v_heap->min_node->right_sibling; + __pyx_t_2 = __pyx_v_heap->min_node->right_sibling; + __pyx_v_temp = __pyx_t_2; goto __pyx_L7; } /*else*/ { - /* "sklearn/utils/graph_shortest_path.pyx":423 + /* "sklearn/utils/graph_shortest_path.pyx":425 * temp = heap.min_node.right_sibling * else: * out = heap.min_node # <<<<<<<<<<<<<< * heap.min_node = NULL * return out */ - __pyx_v_out = __pyx_v_heap->min_node; + __pyx_t_2 = __pyx_v_heap->min_node; + __pyx_v_out = __pyx_t_2; - /* "sklearn/utils/graph_shortest_path.pyx":424 + /* "sklearn/utils/graph_shortest_path.pyx":426 * else: * out = heap.min_node * heap.min_node = NULL # <<<<<<<<<<<<<< @@ -3546,7 +3672,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ __pyx_v_heap->min_node = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":425 + /* "sklearn/utils/graph_shortest_path.pyx":427 * out = heap.min_node * heap.min_node = NULL * return out # <<<<<<<<<<<<<< @@ -3561,16 +3687,17 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx } __pyx_L6:; - /* "sklearn/utils/graph_shortest_path.pyx":428 + /* "sklearn/utils/graph_shortest_path.pyx":430 * * # remove min_node, and point heap to the new min * out = heap.min_node # <<<<<<<<<<<<<< * remove(heap.min_node) * heap.min_node = temp */ - __pyx_v_out = __pyx_v_heap->min_node; + __pyx_t_2 = __pyx_v_heap->min_node; + __pyx_v_out = __pyx_t_2; - /* "sklearn/utils/graph_shortest_path.pyx":429 + /* "sklearn/utils/graph_shortest_path.pyx":431 * # remove min_node, and point heap to the new min * out = heap.min_node * remove(heap.min_node) # <<<<<<<<<<<<<< @@ -3579,7 +3706,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ __pyx_f_7sklearn_5utils_19graph_shortest_path_remove(__pyx_v_heap->min_node); - /* "sklearn/utils/graph_shortest_path.pyx":430 + /* "sklearn/utils/graph_shortest_path.pyx":432 * out = heap.min_node * remove(heap.min_node) * heap.min_node = temp # <<<<<<<<<<<<<< @@ -3588,7 +3715,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ __pyx_v_heap->min_node = __pyx_v_temp; - /* "sklearn/utils/graph_shortest_path.pyx":433 + /* "sklearn/utils/graph_shortest_path.pyx":435 * * # re-link the heap * for i from 0 <= i < 100: # <<<<<<<<<<<<<< @@ -3597,7 +3724,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ for (__pyx_v_i = 0; __pyx_v_i < 100; __pyx_v_i++) { - /* "sklearn/utils/graph_shortest_path.pyx":434 + /* "sklearn/utils/graph_shortest_path.pyx":436 * # re-link the heap * for i from 0 <= i < 100: * heap.roots_by_rank[i] = NULL # <<<<<<<<<<<<<< @@ -3607,7 +3734,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx (__pyx_v_heap->roots_by_rank[__pyx_v_i]) = NULL; } - /* "sklearn/utils/graph_shortest_path.pyx":436 + /* "sklearn/utils/graph_shortest_path.pyx":438 * heap.roots_by_rank[i] = NULL * * while temp: # <<<<<<<<<<<<<< @@ -3618,7 +3745,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx __pyx_t_1 = (__pyx_v_temp != 0); if (!__pyx_t_1) break; - /* "sklearn/utils/graph_shortest_path.pyx":437 + /* "sklearn/utils/graph_shortest_path.pyx":439 * * while temp: * if temp.val < heap.min_node.val: # <<<<<<<<<<<<<< @@ -3628,7 +3755,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx __pyx_t_1 = (__pyx_v_temp->val < __pyx_v_heap->min_node->val); if (__pyx_t_1) { - /* "sklearn/utils/graph_shortest_path.pyx":438 + /* "sklearn/utils/graph_shortest_path.pyx":440 * while temp: * if temp.val < heap.min_node.val: * heap.min_node = temp # <<<<<<<<<<<<<< @@ -3640,16 +3767,17 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx } __pyx_L12:; - /* "sklearn/utils/graph_shortest_path.pyx":439 + /* "sklearn/utils/graph_shortest_path.pyx":441 * if temp.val < heap.min_node.val: * heap.min_node = temp * temp_right = temp.right_sibling # <<<<<<<<<<<<<< * link(heap, temp) * temp = temp_right */ - __pyx_v_temp_right = __pyx_v_temp->right_sibling; + __pyx_t_2 = __pyx_v_temp->right_sibling; + __pyx_v_temp_right = __pyx_t_2; - /* "sklearn/utils/graph_shortest_path.pyx":440 + /* "sklearn/utils/graph_shortest_path.pyx":442 * heap.min_node = temp * temp_right = temp.right_sibling * link(heap, temp) # <<<<<<<<<<<<<< @@ -3658,7 +3786,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx */ __pyx_f_7sklearn_5utils_19graph_shortest_path_link(__pyx_v_heap, __pyx_v_temp); - /* "sklearn/utils/graph_shortest_path.pyx":441 + /* "sklearn/utils/graph_shortest_path.pyx":443 * temp_right = temp.right_sibling * link(heap, temp) * temp = temp_right # <<<<<<<<<<<<<< @@ -3668,7 +3796,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx __pyx_v_temp = __pyx_v_temp_right; } - /* "sklearn/utils/graph_shortest_path.pyx":443 + /* "sklearn/utils/graph_shortest_path.pyx":445 * temp = temp_right * * return out # <<<<<<<<<<<<<< @@ -3684,7 +3812,7 @@ static struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx return __pyx_r; } -/* "sklearn/utils/graph_shortest_path.pyx":466 +/* "sklearn/utils/graph_shortest_path.pyx":468 * * @cython.boundscheck(False) * cdef void dijkstra_directed_one_row( # <<<<<<<<<<<<<< @@ -3698,20 +3826,14 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_v; struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_current_neighbor; __pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t __pyx_v_dist; - Py_buffer __pyx_bstruct_neighbors; - Py_ssize_t __pyx_bstride_0_neighbors = 0; - Py_ssize_t __pyx_bshape_0_neighbors = 0; - Py_buffer __pyx_bstruct_distances; - Py_ssize_t __pyx_bstride_0_distances = 0; - Py_ssize_t __pyx_bshape_0_distances = 0; - Py_buffer __pyx_bstruct_graph; - Py_ssize_t __pyx_bstride_0_graph = 0; - Py_ssize_t __pyx_bstride_1_graph = 0; - Py_ssize_t __pyx_bshape_0_graph = 0; - Py_ssize_t __pyx_bshape_1_graph = 0; - Py_buffer __pyx_bstruct_indptr; - Py_ssize_t __pyx_bstride_0_indptr = 0; - Py_ssize_t __pyx_bshape_0_indptr = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_distances; + __Pyx_Buffer __pyx_pybuffer_distances; + __Pyx_LocalBuf_ND __pyx_pybuffernd_graph; + __Pyx_Buffer __pyx_pybuffer_graph; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr; + __Pyx_Buffer __pyx_pybuffer_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_neighbors; + __Pyx_Buffer __pyx_pybuffer_neighbors; __Pyx_RefNannyDeclarations unsigned int __pyx_t_1; int __pyx_t_2; @@ -3719,42 +3841,51 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ __pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t __pyx_t_4; unsigned int __pyx_t_5; unsigned int __pyx_t_6; - unsigned int __pyx_t_7; + __pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t __pyx_t_7; unsigned int __pyx_t_8; + unsigned int __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dijkstra_directed_one_row"); - __pyx_bstruct_neighbors.buf = NULL; - __pyx_bstruct_distances.buf = NULL; - __pyx_bstruct_indptr.buf = NULL; - __pyx_bstruct_graph.buf = NULL; + __Pyx_RefNannySetupContext("dijkstra_directed_one_row", 0); + __pyx_pybuffer_neighbors.pybuffer.buf = NULL; + __pyx_pybuffer_neighbors.refcount = 0; + __pyx_pybuffernd_neighbors.data = NULL; + __pyx_pybuffernd_neighbors.rcbuffer = &__pyx_pybuffer_neighbors; + __pyx_pybuffer_distances.pybuffer.buf = NULL; + __pyx_pybuffer_distances.refcount = 0; + __pyx_pybuffernd_distances.data = NULL; + __pyx_pybuffernd_distances.rcbuffer = &__pyx_pybuffer_distances; + __pyx_pybuffer_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_indptr.refcount = 0; + __pyx_pybuffernd_indptr.data = NULL; + __pyx_pybuffernd_indptr.rcbuffer = &__pyx_pybuffer_indptr; + __pyx_pybuffer_graph.pybuffer.buf = NULL; + __pyx_pybuffer_graph.refcount = 0; + __pyx_pybuffernd_graph.data = NULL; + __pyx_pybuffernd_graph.rcbuffer = &__pyx_pybuffer_graph; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_neighbors, (PyObject*)__pyx_v_neighbors, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 466; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_neighbors.rcbuffer->pybuffer, (PyObject*)__pyx_v_neighbors, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_neighbors = __pyx_bstruct_neighbors.strides[0]; - __pyx_bshape_0_neighbors = __pyx_bstruct_neighbors.shape[0]; + __pyx_pybuffernd_neighbors.diminfo[0].strides = __pyx_pybuffernd_neighbors.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_neighbors.diminfo[0].shape = __pyx_pybuffernd_neighbors.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_distances, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 466; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_distances.rcbuffer->pybuffer, (PyObject*)__pyx_v_distances, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_distances = __pyx_bstruct_distances.strides[0]; - __pyx_bshape_0_distances = __pyx_bstruct_distances.shape[0]; + __pyx_pybuffernd_distances.diminfo[0].strides = __pyx_pybuffernd_distances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_distances.diminfo[0].shape = __pyx_pybuffernd_distances.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_indptr, (PyObject*)__pyx_v_indptr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 466; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_indptr = __pyx_bstruct_indptr.strides[0]; - __pyx_bshape_0_indptr = __pyx_bstruct_indptr.shape[0]; + __pyx_pybuffernd_indptr.diminfo[0].strides = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr.diminfo[0].shape = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_graph, (PyObject*)__pyx_v_graph, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 466; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_graph.rcbuffer->pybuffer, (PyObject*)__pyx_v_graph, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_graph = __pyx_bstruct_graph.strides[0]; __pyx_bstride_1_graph = __pyx_bstruct_graph.strides[1]; - __pyx_bshape_0_graph = __pyx_bstruct_graph.shape[0]; __pyx_bshape_1_graph = __pyx_bstruct_graph.shape[1]; + __pyx_pybuffernd_graph.diminfo[0].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_graph.diminfo[0].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_graph.diminfo[1].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_graph.diminfo[1].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[1]; - /* "sklearn/utils/graph_shortest_path.pyx":494 + /* "sklearn/utils/graph_shortest_path.pyx":496 * nodes : the array of nodes to use * """ * cdef unsigned int N = graph.shape[0] # <<<<<<<<<<<<<< @@ -3763,7 +3894,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ */ __pyx_v_N = (__pyx_v_graph->dimensions[0]); - /* "sklearn/utils/graph_shortest_path.pyx":500 + /* "sklearn/utils/graph_shortest_path.pyx":502 * * # initialize nodes * for i from 0 <= i < N: # <<<<<<<<<<<<<< @@ -3773,7 +3904,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ __pyx_t_1 = __pyx_v_N; for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_1; __pyx_v_i++) { - /* "sklearn/utils/graph_shortest_path.pyx":501 + /* "sklearn/utils/graph_shortest_path.pyx":503 * # initialize nodes * for i from 0 <= i < N: * initialize_node(&nodes[i], i) # <<<<<<<<<<<<<< @@ -3783,7 +3914,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ __pyx_f_7sklearn_5utils_19graph_shortest_path_initialize_node((&(__pyx_v_nodes[__pyx_v_i])), __pyx_v_i, NULL); } - /* "sklearn/utils/graph_shortest_path.pyx":503 + /* "sklearn/utils/graph_shortest_path.pyx":505 * initialize_node(&nodes[i], i) * * heap.min_node = NULL # <<<<<<<<<<<<<< @@ -3792,7 +3923,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ */ __pyx_v_heap->min_node = NULL; - /* "sklearn/utils/graph_shortest_path.pyx":504 + /* "sklearn/utils/graph_shortest_path.pyx":506 * * heap.min_node = NULL * insert_node(heap, &nodes[i_node]) # <<<<<<<<<<<<<< @@ -3801,7 +3932,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ */ __pyx_f_7sklearn_5utils_19graph_shortest_path_insert_node(__pyx_v_heap, (&(__pyx_v_nodes[__pyx_v_i_node]))); - /* "sklearn/utils/graph_shortest_path.pyx":506 + /* "sklearn/utils/graph_shortest_path.pyx":508 * insert_node(heap, &nodes[i_node]) * * while heap.min_node: # <<<<<<<<<<<<<< @@ -3812,7 +3943,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ __pyx_t_2 = (__pyx_v_heap->min_node != 0); if (!__pyx_t_2) break; - /* "sklearn/utils/graph_shortest_path.pyx":507 + /* "sklearn/utils/graph_shortest_path.pyx":509 * * while heap.min_node: * v = remove_min(heap) # <<<<<<<<<<<<<< @@ -3821,7 +3952,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ */ __pyx_v_v = __pyx_f_7sklearn_5utils_19graph_shortest_path_remove_min(__pyx_v_heap); - /* "sklearn/utils/graph_shortest_path.pyx":508 + /* "sklearn/utils/graph_shortest_path.pyx":510 * while heap.min_node: * v = remove_min(heap) * v.state = 2 # 2 -> SCANNED # <<<<<<<<<<<<<< @@ -3830,7 +3961,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ */ __pyx_v_v->state = 2; - /* "sklearn/utils/graph_shortest_path.pyx":510 + /* "sklearn/utils/graph_shortest_path.pyx":512 * v.state = 2 # 2 -> SCANNED * * for i from indptr[v.index] <= i < indptr[v.index + 1]: # <<<<<<<<<<<<<< @@ -3839,11 +3970,11 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ */ __pyx_t_1 = __pyx_v_v->index; __pyx_t_3 = (__pyx_v_v->index + 1); - if (__pyx_t_3 < 0) __pyx_t_3 += __pyx_bshape_0_indptr; - __pyx_t_4 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_bstruct_indptr.buf, __pyx_t_3, __pyx_bstride_0_indptr)); - for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_bstruct_indptr.buf, __pyx_t_1, __pyx_bstride_0_indptr)); __pyx_v_i < __pyx_t_4; __pyx_v_i++) { + if (__pyx_t_3 < 0) __pyx_t_3 += __pyx_pybuffernd_indptr.diminfo[0].shape; + __pyx_t_4 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_indptr.diminfo[0].strides)); + for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_1, __pyx_pybuffernd_indptr.diminfo[0].strides)); __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - /* "sklearn/utils/graph_shortest_path.pyx":511 + /* "sklearn/utils/graph_shortest_path.pyx":513 * * for i from indptr[v.index] <= i < indptr[v.index + 1]: * current_neighbor = &nodes[neighbors[i]] # <<<<<<<<<<<<<< @@ -3851,9 +3982,9 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ * dist = distances[i] */ __pyx_t_5 = __pyx_v_i; - __pyx_v_current_neighbor = (&(__pyx_v_nodes[(*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_bstruct_neighbors.buf, __pyx_t_5, __pyx_bstride_0_neighbors))])); + __pyx_v_current_neighbor = (&(__pyx_v_nodes[(*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_pybuffernd_neighbors.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_neighbors.diminfo[0].strides))])); - /* "sklearn/utils/graph_shortest_path.pyx":512 + /* "sklearn/utils/graph_shortest_path.pyx":514 * for i from indptr[v.index] <= i < indptr[v.index + 1]: * current_neighbor = &nodes[neighbors[i]] * if current_neighbor.state != 2: # 2 -> SCANNED # <<<<<<<<<<<<<< @@ -3863,7 +3994,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ __pyx_t_2 = (__pyx_v_current_neighbor->state != 2); if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":513 + /* "sklearn/utils/graph_shortest_path.pyx":515 * current_neighbor = &nodes[neighbors[i]] * if current_neighbor.state != 2: # 2 -> SCANNED * dist = distances[i] # <<<<<<<<<<<<<< @@ -3871,9 +4002,9 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ * current_neighbor.state = 1 # 1 -> IN_HEAP */ __pyx_t_6 = __pyx_v_i; - __pyx_v_dist = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_distances.buf, __pyx_t_6, __pyx_bstride_0_distances)); + __pyx_v_dist = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_distances.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_distances.diminfo[0].strides)); - /* "sklearn/utils/graph_shortest_path.pyx":514 + /* "sklearn/utils/graph_shortest_path.pyx":516 * if current_neighbor.state != 2: # 2 -> SCANNED * dist = distances[i] * if current_neighbor.state == 0: # 0 -> NOT_IN_HEAP # <<<<<<<<<<<<<< @@ -3883,7 +4014,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ __pyx_t_2 = (__pyx_v_current_neighbor->state == 0); if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":515 + /* "sklearn/utils/graph_shortest_path.pyx":517 * dist = distances[i] * if current_neighbor.state == 0: # 0 -> NOT_IN_HEAP * current_neighbor.state = 1 # 1 -> IN_HEAP # <<<<<<<<<<<<<< @@ -3892,7 +4023,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ */ __pyx_v_current_neighbor->state = 1; - /* "sklearn/utils/graph_shortest_path.pyx":516 + /* "sklearn/utils/graph_shortest_path.pyx":518 * if current_neighbor.state == 0: # 0 -> NOT_IN_HEAP * current_neighbor.state = 1 # 1 -> IN_HEAP * current_neighbor.val = v.val + dist # <<<<<<<<<<<<<< @@ -3901,7 +4032,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ */ __pyx_v_current_neighbor->val = (__pyx_v_v->val + __pyx_v_dist); - /* "sklearn/utils/graph_shortest_path.pyx":517 + /* "sklearn/utils/graph_shortest_path.pyx":519 * current_neighbor.state = 1 # 1 -> IN_HEAP * current_neighbor.val = v.val + dist * insert_node(heap, current_neighbor) # <<<<<<<<<<<<<< @@ -3912,7 +4043,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ goto __pyx_L10; } - /* "sklearn/utils/graph_shortest_path.pyx":518 + /* "sklearn/utils/graph_shortest_path.pyx":520 * current_neighbor.val = v.val + dist * insert_node(heap, current_neighbor) * elif current_neighbor.val > v.val + dist: # <<<<<<<<<<<<<< @@ -3922,7 +4053,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ __pyx_t_2 = (__pyx_v_current_neighbor->val > (__pyx_v_v->val + __pyx_v_dist)); if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":520 + /* "sklearn/utils/graph_shortest_path.pyx":522 * elif current_neighbor.val > v.val + dist: * decrease_val(heap, current_neighbor, * v.val + dist) # <<<<<<<<<<<<<< @@ -3938,39 +4069,40 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_directed_one_ __pyx_L9:; } - /* "sklearn/utils/graph_shortest_path.pyx":523 + /* "sklearn/utils/graph_shortest_path.pyx":525 * * #v has now been scanned: add the distance to the results * graph[i_node, v.index] = v.val # <<<<<<<<<<<<<< * * */ - __pyx_t_7 = __pyx_v_i_node; - __pyx_t_8 = __pyx_v_v->index; - *__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_7, __pyx_bstride_0_graph, __pyx_t_8, __pyx_bstride_1_graph) = __pyx_v_v->val; + __pyx_t_7 = __pyx_v_v->val; + __pyx_t_8 = __pyx_v_i_node; + __pyx_t_9 = __pyx_v_v->index; + *__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_9, __pyx_pybuffernd_graph.diminfo[1].strides) = __pyx_t_7; } goto __pyx_L0; __pyx_L1_error:; { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_neighbors); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_graph); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_indptr); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_neighbors.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_WriteUnraisable("sklearn.utils.graph_shortest_path.dijkstra_directed_one_row", __pyx_clineno, __pyx_lineno, __pyx_filename); goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_neighbors); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_graph); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_indptr); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_neighbors.rcbuffer->pybuffer); __pyx_L2:; __Pyx_RefNannyFinishContext(); } -/* "sklearn/utils/graph_shortest_path.pyx":527 +/* "sklearn/utils/graph_shortest_path.pyx":529 * * @cython.boundscheck(False) * cdef void dijkstra_one_row(unsigned int i_node, # <<<<<<<<<<<<<< @@ -3984,29 +4116,20 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_v; struct __pyx_t_7sklearn_5utils_19graph_shortest_path_FibonacciNode *__pyx_v_current_neighbor; __pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t __pyx_v_dist; - Py_buffer __pyx_bstruct_neighbors1; - Py_ssize_t __pyx_bstride_0_neighbors1 = 0; - Py_ssize_t __pyx_bshape_0_neighbors1 = 0; - Py_buffer __pyx_bstruct_distances2; - Py_ssize_t __pyx_bstride_0_distances2 = 0; - Py_ssize_t __pyx_bshape_0_distances2 = 0; - Py_buffer __pyx_bstruct_neighbors2; - Py_ssize_t __pyx_bstride_0_neighbors2 = 0; - Py_ssize_t __pyx_bshape_0_neighbors2 = 0; - Py_buffer __pyx_bstruct_graph; - Py_ssize_t __pyx_bstride_0_graph = 0; - Py_ssize_t __pyx_bstride_1_graph = 0; - Py_ssize_t __pyx_bshape_0_graph = 0; - Py_ssize_t __pyx_bshape_1_graph = 0; - Py_buffer __pyx_bstruct_indptr2; - Py_ssize_t __pyx_bstride_0_indptr2 = 0; - Py_ssize_t __pyx_bshape_0_indptr2 = 0; - Py_buffer __pyx_bstruct_distances1; - Py_ssize_t __pyx_bstride_0_distances1 = 0; - Py_ssize_t __pyx_bshape_0_distances1 = 0; - Py_buffer __pyx_bstruct_indptr1; - Py_ssize_t __pyx_bstride_0_indptr1 = 0; - Py_ssize_t __pyx_bshape_0_indptr1 = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_distances1; + __Pyx_Buffer __pyx_pybuffer_distances1; + __Pyx_LocalBuf_ND __pyx_pybuffernd_distances2; + __Pyx_Buffer __pyx_pybuffer_distances2; + __Pyx_LocalBuf_ND __pyx_pybuffernd_graph; + __Pyx_Buffer __pyx_pybuffer_graph; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr1; + __Pyx_Buffer __pyx_pybuffer_indptr1; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr2; + __Pyx_Buffer __pyx_pybuffer_indptr2; + __Pyx_LocalBuf_ND __pyx_pybuffernd_neighbors1; + __Pyx_Buffer __pyx_pybuffer_neighbors1; + __Pyx_LocalBuf_ND __pyx_pybuffernd_neighbors2; + __Pyx_Buffer __pyx_pybuffer_neighbors2; __Pyx_RefNannyDeclarations unsigned int __pyx_t_1; int __pyx_t_2; @@ -4018,63 +4141,78 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig long __pyx_t_8; unsigned int __pyx_t_9; unsigned int __pyx_t_10; - unsigned int __pyx_t_11; + __pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t __pyx_t_11; unsigned int __pyx_t_12; + unsigned int __pyx_t_13; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dijkstra_one_row"); - __pyx_bstruct_neighbors1.buf = NULL; - __pyx_bstruct_distances1.buf = NULL; - __pyx_bstruct_indptr1.buf = NULL; - __pyx_bstruct_neighbors2.buf = NULL; - __pyx_bstruct_distances2.buf = NULL; - __pyx_bstruct_indptr2.buf = NULL; - __pyx_bstruct_graph.buf = NULL; + __Pyx_RefNannySetupContext("dijkstra_one_row", 0); + __pyx_pybuffer_neighbors1.pybuffer.buf = NULL; + __pyx_pybuffer_neighbors1.refcount = 0; + __pyx_pybuffernd_neighbors1.data = NULL; + __pyx_pybuffernd_neighbors1.rcbuffer = &__pyx_pybuffer_neighbors1; + __pyx_pybuffer_distances1.pybuffer.buf = NULL; + __pyx_pybuffer_distances1.refcount = 0; + __pyx_pybuffernd_distances1.data = NULL; + __pyx_pybuffernd_distances1.rcbuffer = &__pyx_pybuffer_distances1; + __pyx_pybuffer_indptr1.pybuffer.buf = NULL; + __pyx_pybuffer_indptr1.refcount = 0; + __pyx_pybuffernd_indptr1.data = NULL; + __pyx_pybuffernd_indptr1.rcbuffer = &__pyx_pybuffer_indptr1; + __pyx_pybuffer_neighbors2.pybuffer.buf = NULL; + __pyx_pybuffer_neighbors2.refcount = 0; + __pyx_pybuffernd_neighbors2.data = NULL; + __pyx_pybuffernd_neighbors2.rcbuffer = &__pyx_pybuffer_neighbors2; + __pyx_pybuffer_distances2.pybuffer.buf = NULL; + __pyx_pybuffer_distances2.refcount = 0; + __pyx_pybuffernd_distances2.data = NULL; + __pyx_pybuffernd_distances2.rcbuffer = &__pyx_pybuffer_distances2; + __pyx_pybuffer_indptr2.pybuffer.buf = NULL; + __pyx_pybuffer_indptr2.refcount = 0; + __pyx_pybuffernd_indptr2.data = NULL; + __pyx_pybuffernd_indptr2.rcbuffer = &__pyx_pybuffer_indptr2; + __pyx_pybuffer_graph.pybuffer.buf = NULL; + __pyx_pybuffer_graph.refcount = 0; + __pyx_pybuffernd_graph.data = NULL; + __pyx_pybuffernd_graph.rcbuffer = &__pyx_pybuffer_graph; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_neighbors1, (PyObject*)__pyx_v_neighbors1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_neighbors1.rcbuffer->pybuffer, (PyObject*)__pyx_v_neighbors1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_neighbors1 = __pyx_bstruct_neighbors1.strides[0]; - __pyx_bshape_0_neighbors1 = __pyx_bstruct_neighbors1.shape[0]; + __pyx_pybuffernd_neighbors1.diminfo[0].strides = __pyx_pybuffernd_neighbors1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_neighbors1.diminfo[0].shape = __pyx_pybuffernd_neighbors1.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_distances1, (PyObject*)__pyx_v_distances1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_distances1.rcbuffer->pybuffer, (PyObject*)__pyx_v_distances1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_distances1 = __pyx_bstruct_distances1.strides[0]; - __pyx_bshape_0_distances1 = __pyx_bstruct_distances1.shape[0]; + __pyx_pybuffernd_distances1.diminfo[0].strides = __pyx_pybuffernd_distances1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_distances1.diminfo[0].shape = __pyx_pybuffernd_distances1.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_indptr1, (PyObject*)__pyx_v_indptr1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_indptr1 = __pyx_bstruct_indptr1.strides[0]; - __pyx_bshape_0_indptr1 = __pyx_bstruct_indptr1.shape[0]; + __pyx_pybuffernd_indptr1.diminfo[0].strides = __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr1.diminfo[0].shape = __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_neighbors2, (PyObject*)__pyx_v_neighbors2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_neighbors2.rcbuffer->pybuffer, (PyObject*)__pyx_v_neighbors2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_neighbors2 = __pyx_bstruct_neighbors2.strides[0]; - __pyx_bshape_0_neighbors2 = __pyx_bstruct_neighbors2.shape[0]; + __pyx_pybuffernd_neighbors2.diminfo[0].strides = __pyx_pybuffernd_neighbors2.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_neighbors2.diminfo[0].shape = __pyx_pybuffernd_neighbors2.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_distances2, (PyObject*)__pyx_v_distances2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_distances2.rcbuffer->pybuffer, (PyObject*)__pyx_v_distances2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_distances2 = __pyx_bstruct_distances2.strides[0]; - __pyx_bshape_0_distances2 = __pyx_bstruct_distances2.shape[0]; + __pyx_pybuffernd_distances2.diminfo[0].strides = __pyx_pybuffernd_distances2.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_distances2.diminfo[0].shape = __pyx_pybuffernd_distances2.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_indptr2, (PyObject*)__pyx_v_indptr2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_indptr2 = __pyx_bstruct_indptr2.strides[0]; - __pyx_bshape_0_indptr2 = __pyx_bstruct_indptr2.shape[0]; + __pyx_pybuffernd_indptr2.diminfo[0].strides = __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr2.diminfo[0].shape = __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_graph, (PyObject*)__pyx_v_graph, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_graph.rcbuffer->pybuffer, (PyObject*)__pyx_v_graph, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_graph = __pyx_bstruct_graph.strides[0]; __pyx_bstride_1_graph = __pyx_bstruct_graph.strides[1]; - __pyx_bshape_0_graph = __pyx_bstruct_graph.shape[0]; __pyx_bshape_1_graph = __pyx_bstruct_graph.shape[1]; + __pyx_pybuffernd_graph.diminfo[0].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_graph.diminfo[0].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_graph.diminfo[1].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_graph.diminfo[1].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[1]; - /* "sklearn/utils/graph_shortest_path.pyx":558 + /* "sklearn/utils/graph_shortest_path.pyx":560 * nodes : the array of nodes to use * """ * cdef unsigned int N = graph.shape[0] # <<<<<<<<<<<<<< @@ -4083,7 +4221,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig */ __pyx_v_N = (__pyx_v_graph->dimensions[0]); - /* "sklearn/utils/graph_shortest_path.pyx":567 + /* "sklearn/utils/graph_shortest_path.pyx":569 * # rank should already be 0, index will already be set * # we just need to re-set state and val * for i from 0 <= i < N: # <<<<<<<<<<<<<< @@ -4093,7 +4231,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig __pyx_t_1 = __pyx_v_N; for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_1; __pyx_v_i++) { - /* "sklearn/utils/graph_shortest_path.pyx":568 + /* "sklearn/utils/graph_shortest_path.pyx":570 * # we just need to re-set state and val * for i from 0 <= i < N: * nodes[i].state = 0 # 0 -> NOT_IN_HEAP # <<<<<<<<<<<<<< @@ -4102,7 +4240,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig */ (__pyx_v_nodes[__pyx_v_i]).state = 0; - /* "sklearn/utils/graph_shortest_path.pyx":569 + /* "sklearn/utils/graph_shortest_path.pyx":571 * for i from 0 <= i < N: * nodes[i].state = 0 # 0 -> NOT_IN_HEAP * nodes[i].val = 0 # <<<<<<<<<<<<<< @@ -4112,7 +4250,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig (__pyx_v_nodes[__pyx_v_i]).val = 0.0; } - /* "sklearn/utils/graph_shortest_path.pyx":571 + /* "sklearn/utils/graph_shortest_path.pyx":573 * nodes[i].val = 0 * * insert_node(heap, &nodes[i_node]) # <<<<<<<<<<<<<< @@ -4121,7 +4259,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig */ __pyx_f_7sklearn_5utils_19graph_shortest_path_insert_node(__pyx_v_heap, (&(__pyx_v_nodes[__pyx_v_i_node]))); - /* "sklearn/utils/graph_shortest_path.pyx":573 + /* "sklearn/utils/graph_shortest_path.pyx":575 * insert_node(heap, &nodes[i_node]) * * while heap.min_node: # <<<<<<<<<<<<<< @@ -4132,7 +4270,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig __pyx_t_2 = (__pyx_v_heap->min_node != 0); if (!__pyx_t_2) break; - /* "sklearn/utils/graph_shortest_path.pyx":574 + /* "sklearn/utils/graph_shortest_path.pyx":576 * * while heap.min_node: * v = remove_min(heap) # <<<<<<<<<<<<<< @@ -4141,7 +4279,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig */ __pyx_v_v = __pyx_f_7sklearn_5utils_19graph_shortest_path_remove_min(__pyx_v_heap); - /* "sklearn/utils/graph_shortest_path.pyx":575 + /* "sklearn/utils/graph_shortest_path.pyx":577 * while heap.min_node: * v = remove_min(heap) * v.state = 2 # 2 -> SCANNED # <<<<<<<<<<<<<< @@ -4150,7 +4288,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig */ __pyx_v_v->state = 2; - /* "sklearn/utils/graph_shortest_path.pyx":577 + /* "sklearn/utils/graph_shortest_path.pyx":579 * v.state = 2 # 2 -> SCANNED * * for i from indptr1[v.index] <= i < indptr1[v.index + 1]: # <<<<<<<<<<<<<< @@ -4159,11 +4297,11 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig */ __pyx_t_1 = __pyx_v_v->index; __pyx_t_3 = (__pyx_v_v->index + 1); - if (__pyx_t_3 < 0) __pyx_t_3 += __pyx_bshape_0_indptr1; - __pyx_t_4 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_bstruct_indptr1.buf, __pyx_t_3, __pyx_bstride_0_indptr1)); - for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_bstruct_indptr1.buf, __pyx_t_1, __pyx_bstride_0_indptr1)); __pyx_v_i < __pyx_t_4; __pyx_v_i++) { + if (__pyx_t_3 < 0) __pyx_t_3 += __pyx_pybuffernd_indptr1.diminfo[0].shape; + __pyx_t_4 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_indptr1.diminfo[0].strides)); + for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.buf, __pyx_t_1, __pyx_pybuffernd_indptr1.diminfo[0].strides)); __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - /* "sklearn/utils/graph_shortest_path.pyx":578 + /* "sklearn/utils/graph_shortest_path.pyx":580 * * for i from indptr1[v.index] <= i < indptr1[v.index + 1]: * current_neighbor = &nodes[neighbors1[i]] # <<<<<<<<<<<<<< @@ -4171,9 +4309,9 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig * dist = distances1[i] */ __pyx_t_5 = __pyx_v_i; - __pyx_v_current_neighbor = (&(__pyx_v_nodes[(*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_bstruct_neighbors1.buf, __pyx_t_5, __pyx_bstride_0_neighbors1))])); + __pyx_v_current_neighbor = (&(__pyx_v_nodes[(*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_pybuffernd_neighbors1.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_neighbors1.diminfo[0].strides))])); - /* "sklearn/utils/graph_shortest_path.pyx":579 + /* "sklearn/utils/graph_shortest_path.pyx":581 * for i from indptr1[v.index] <= i < indptr1[v.index + 1]: * current_neighbor = &nodes[neighbors1[i]] * if current_neighbor.state != 2: # 2 -> SCANNED # <<<<<<<<<<<<<< @@ -4183,7 +4321,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig __pyx_t_2 = (__pyx_v_current_neighbor->state != 2); if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":580 + /* "sklearn/utils/graph_shortest_path.pyx":582 * current_neighbor = &nodes[neighbors1[i]] * if current_neighbor.state != 2: # 2 -> SCANNED * dist = distances1[i] # <<<<<<<<<<<<<< @@ -4191,9 +4329,9 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig * current_neighbor.state = 1 # 1 -> IN_HEAP */ __pyx_t_6 = __pyx_v_i; - __pyx_v_dist = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_distances1.buf, __pyx_t_6, __pyx_bstride_0_distances1)); + __pyx_v_dist = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_distances1.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_distances1.diminfo[0].strides)); - /* "sklearn/utils/graph_shortest_path.pyx":581 + /* "sklearn/utils/graph_shortest_path.pyx":583 * if current_neighbor.state != 2: # 2 -> SCANNED * dist = distances1[i] * if current_neighbor.state == 0: # 0 -> NOT_IN_HEAP # <<<<<<<<<<<<<< @@ -4203,7 +4341,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig __pyx_t_2 = (__pyx_v_current_neighbor->state == 0); if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":582 + /* "sklearn/utils/graph_shortest_path.pyx":584 * dist = distances1[i] * if current_neighbor.state == 0: # 0 -> NOT_IN_HEAP * current_neighbor.state = 1 # 1 -> IN_HEAP # <<<<<<<<<<<<<< @@ -4212,7 +4350,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig */ __pyx_v_current_neighbor->state = 1; - /* "sklearn/utils/graph_shortest_path.pyx":583 + /* "sklearn/utils/graph_shortest_path.pyx":585 * if current_neighbor.state == 0: # 0 -> NOT_IN_HEAP * current_neighbor.state = 1 # 1 -> IN_HEAP * current_neighbor.val = v.val + dist # <<<<<<<<<<<<<< @@ -4221,7 +4359,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig */ __pyx_v_current_neighbor->val = (__pyx_v_v->val + __pyx_v_dist); - /* "sklearn/utils/graph_shortest_path.pyx":584 + /* "sklearn/utils/graph_shortest_path.pyx":586 * current_neighbor.state = 1 # 1 -> IN_HEAP * current_neighbor.val = v.val + dist * insert_node(heap, current_neighbor) # <<<<<<<<<<<<<< @@ -4232,7 +4370,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig goto __pyx_L10; } - /* "sklearn/utils/graph_shortest_path.pyx":585 + /* "sklearn/utils/graph_shortest_path.pyx":587 * current_neighbor.val = v.val + dist * insert_node(heap, current_neighbor) * elif current_neighbor.val > v.val + dist: # <<<<<<<<<<<<<< @@ -4242,7 +4380,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig __pyx_t_2 = (__pyx_v_current_neighbor->val > (__pyx_v_v->val + __pyx_v_dist)); if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":587 + /* "sklearn/utils/graph_shortest_path.pyx":589 * elif current_neighbor.val > v.val + dist: * decrease_val(heap, current_neighbor, * v.val + dist) # <<<<<<<<<<<<<< @@ -4258,7 +4396,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig __pyx_L9:; } - /* "sklearn/utils/graph_shortest_path.pyx":589 + /* "sklearn/utils/graph_shortest_path.pyx":591 * v.val + dist) * * for i from indptr2[v.index] <= i < indptr2[v.index + 1]: # <<<<<<<<<<<<<< @@ -4267,11 +4405,11 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig */ __pyx_t_7 = __pyx_v_v->index; __pyx_t_8 = (__pyx_v_v->index + 1); - if (__pyx_t_8 < 0) __pyx_t_8 += __pyx_bshape_0_indptr2; - __pyx_t_4 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_bstruct_indptr2.buf, __pyx_t_8, __pyx_bstride_0_indptr2)); - for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_bstruct_indptr2.buf, __pyx_t_7, __pyx_bstride_0_indptr2)); __pyx_v_i < __pyx_t_4; __pyx_v_i++) { + if (__pyx_t_8 < 0) __pyx_t_8 += __pyx_pybuffernd_indptr2.diminfo[0].shape; + __pyx_t_4 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_indptr2.diminfo[0].strides)); + for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_indptr2.diminfo[0].strides)); __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - /* "sklearn/utils/graph_shortest_path.pyx":590 + /* "sklearn/utils/graph_shortest_path.pyx":592 * * for i from indptr2[v.index] <= i < indptr2[v.index + 1]: * current_neighbor = &nodes[neighbors2[i]] # <<<<<<<<<<<<<< @@ -4279,9 +4417,9 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig * dist = distances2[i] */ __pyx_t_9 = __pyx_v_i; - __pyx_v_current_neighbor = (&(__pyx_v_nodes[(*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_bstruct_neighbors2.buf, __pyx_t_9, __pyx_bstride_0_neighbors2))])); + __pyx_v_current_neighbor = (&(__pyx_v_nodes[(*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_ITYPE_t *, __pyx_pybuffernd_neighbors2.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_neighbors2.diminfo[0].strides))])); - /* "sklearn/utils/graph_shortest_path.pyx":591 + /* "sklearn/utils/graph_shortest_path.pyx":593 * for i from indptr2[v.index] <= i < indptr2[v.index + 1]: * current_neighbor = &nodes[neighbors2[i]] * if current_neighbor.state != 2: # 2 -> SCANNED # <<<<<<<<<<<<<< @@ -4291,7 +4429,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig __pyx_t_2 = (__pyx_v_current_neighbor->state != 2); if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":592 + /* "sklearn/utils/graph_shortest_path.pyx":594 * current_neighbor = &nodes[neighbors2[i]] * if current_neighbor.state != 2: # 2 -> SCANNED * dist = distances2[i] # <<<<<<<<<<<<<< @@ -4299,9 +4437,9 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig * current_neighbor.state = 1 # 1 -> IN_HEAP */ __pyx_t_10 = __pyx_v_i; - __pyx_v_dist = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_distances2.buf, __pyx_t_10, __pyx_bstride_0_distances2)); + __pyx_v_dist = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_distances2.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_distances2.diminfo[0].strides)); - /* "sklearn/utils/graph_shortest_path.pyx":593 + /* "sklearn/utils/graph_shortest_path.pyx":595 * if current_neighbor.state != 2: # 2 -> SCANNED * dist = distances2[i] * if current_neighbor.state == 0: # 0 -> NOT_IN_HEAP # <<<<<<<<<<<<<< @@ -4311,7 +4449,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig __pyx_t_2 = (__pyx_v_current_neighbor->state == 0); if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":594 + /* "sklearn/utils/graph_shortest_path.pyx":596 * dist = distances2[i] * if current_neighbor.state == 0: # 0 -> NOT_IN_HEAP * current_neighbor.state = 1 # 1 -> IN_HEAP # <<<<<<<<<<<<<< @@ -4320,7 +4458,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig */ __pyx_v_current_neighbor->state = 1; - /* "sklearn/utils/graph_shortest_path.pyx":595 + /* "sklearn/utils/graph_shortest_path.pyx":597 * if current_neighbor.state == 0: # 0 -> NOT_IN_HEAP * current_neighbor.state = 1 # 1 -> IN_HEAP * current_neighbor.val = v.val + dist # <<<<<<<<<<<<<< @@ -4329,7 +4467,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig */ __pyx_v_current_neighbor->val = (__pyx_v_v->val + __pyx_v_dist); - /* "sklearn/utils/graph_shortest_path.pyx":596 + /* "sklearn/utils/graph_shortest_path.pyx":598 * current_neighbor.state = 1 # 1 -> IN_HEAP * current_neighbor.val = v.val + dist * insert_node(heap, current_neighbor) # <<<<<<<<<<<<<< @@ -4340,7 +4478,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig goto __pyx_L14; } - /* "sklearn/utils/graph_shortest_path.pyx":597 + /* "sklearn/utils/graph_shortest_path.pyx":599 * current_neighbor.val = v.val + dist * insert_node(heap, current_neighbor) * elif current_neighbor.val > v.val + dist: # <<<<<<<<<<<<<< @@ -4350,7 +4488,7 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig __pyx_t_2 = (__pyx_v_current_neighbor->val > (__pyx_v_v->val + __pyx_v_dist)); if (__pyx_t_2) { - /* "sklearn/utils/graph_shortest_path.pyx":599 + /* "sklearn/utils/graph_shortest_path.pyx":601 * elif current_neighbor.val > v.val + dist: * decrease_val(heap, current_neighbor, * v.val + dist) # <<<<<<<<<<<<<< @@ -4366,52 +4504,63 @@ static void __pyx_f_7sklearn_5utils_19graph_shortest_path_dijkstra_one_row(unsig __pyx_L13:; } - /* "sklearn/utils/graph_shortest_path.pyx":602 + /* "sklearn/utils/graph_shortest_path.pyx":604 * * #v has now been scanned: add the distance to the results * graph[i_node, v.index] = v.val # <<<<<<<<<<<<<< */ - __pyx_t_11 = __pyx_v_i_node; - __pyx_t_12 = __pyx_v_v->index; - *__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_bstruct_graph.buf, __pyx_t_11, __pyx_bstride_0_graph, __pyx_t_12, __pyx_bstride_1_graph) = __pyx_v_v->val; + __pyx_t_11 = __pyx_v_v->val; + __pyx_t_12 = __pyx_v_i_node; + __pyx_t_13 = __pyx_v_v->index; + *__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_19graph_shortest_path_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_13, __pyx_pybuffernd_graph.diminfo[1].strides) = __pyx_t_11; } goto __pyx_L0; __pyx_L1_error:; { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_neighbors1); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances2); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_neighbors2); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_graph); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_indptr2); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances1); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_indptr1); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_neighbors1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_neighbors2.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_WriteUnraisable("sklearn.utils.graph_shortest_path.dijkstra_one_row", __pyx_clineno, __pyx_lineno, __pyx_filename); goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_neighbors1); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances2); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_neighbors2); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_graph); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_indptr2); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_distances1); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_indptr1); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_distances2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_neighbors1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_neighbors2.rcbuffer->pybuffer); __pyx_L2:; __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":190 +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":194 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP. + * # requirements, and does not yet fulfill the PEP. */ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; @@ -4436,13 +4585,13 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__"); + __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":196 + /* "numpy.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< @@ -4453,11 +4602,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":199 + /* "numpy.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -4466,7 +4615,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":200 + /* "numpy.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -4475,16 +4624,16 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":202 + /* "numpy.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":204 + /* "numpy.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< @@ -4494,7 +4643,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_t_1) { - /* "numpy.pxd":205 + /* "numpy.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -4502,11 +4651,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ * copy_shape = 0 */ __pyx_v_copy_shape = 1; - goto __pyx_L6; + goto __pyx_L4; } /*else*/ { - /* "numpy.pxd":207 + /* "numpy.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -4515,9 +4664,9 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_copy_shape = 0; } - __pyx_L6:; + __pyx_L4:; - /* "numpy.pxd":209 + /* "numpy.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< @@ -4527,37 +4676,37 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); if (__pyx_t_1) { - /* "numpy.pxd":210 + /* "numpy.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); + __pyx_t_2 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS)); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { - /* "numpy.pxd":211 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; } - __pyx_L7:; + __pyx_L5:; - /* "numpy.pxd":213 + /* "numpy.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< @@ -4567,46 +4716,46 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); if (__pyx_t_3) { - /* "numpy.pxd":214 + /* "numpy.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); + __pyx_t_1 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS)); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { - /* "numpy.pxd":215 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; } - __pyx_L8:; + __pyx_L6:; - /* "numpy.pxd":217 + /* "numpy.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":218 + /* "numpy.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -4615,7 +4764,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":219 + /* "numpy.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< @@ -4624,7 +4773,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ if (__pyx_v_copy_shape) { - /* "numpy.pxd":222 + /* "numpy.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -4633,7 +4782,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":223 + /* "numpy.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -4642,7 +4791,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":224 + /* "numpy.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< @@ -4653,49 +4802,49 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "numpy.pxd":225 + /* "numpy.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":226 + /* "numpy.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } - goto __pyx_L9; + goto __pyx_L7; } /*else*/ { - /* "numpy.pxd":228 + /* "numpy.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":229 + /* "numpy.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } - __pyx_L9:; + __pyx_L7:; - /* "numpy.pxd":230 + /* "numpy.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -4704,25 +4853,25 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":231 + /* "numpy.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":232 + /* "numpy.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); - /* "numpy.pxd":235 + /* "numpy.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -4731,17 +4880,19 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_f = NULL; - /* "numpy.pxd":236 + /* "numpy.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":240 + /* "numpy.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -4750,7 +4901,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":242 + /* "numpy.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< @@ -4766,7 +4917,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (__pyx_t_1) { - /* "numpy.pxd":244 + /* "numpy.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -4778,49 +4929,50 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; - goto __pyx_L12; + goto __pyx_L10; } /*else*/ { - /* "numpy.pxd":247 + /* "numpy.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } - __pyx_L12:; + __pyx_L10:; - /* "numpy.pxd":249 + /* "numpy.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ __pyx_t_1 = (!__pyx_v_hasfields); if (__pyx_t_1) { - /* "numpy.pxd":250 + /* "numpy.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; - /* "numpy.pxd":251 + /* "numpy.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); @@ -4831,10 +4983,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (!__pyx_t_2) { - /* "numpy.pxd":252 + /* "numpy.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ @@ -4851,24 +5003,24 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (__pyx_t_1) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; } - __pyx_L14:; + __pyx_L12:; - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" @@ -4877,10 +5029,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_BYTE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__b; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":255 + /* "numpy.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< @@ -4890,10 +5042,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__B; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":256 + /* "numpy.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< @@ -4903,10 +5055,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_SHORT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__h; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":257 + /* "numpy.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< @@ -4916,10 +5068,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_USHORT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__H; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":258 + /* "numpy.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< @@ -4929,10 +5081,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_INT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__i; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":259 + /* "numpy.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< @@ -4942,10 +5094,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_UINT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__I; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":260 + /* "numpy.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< @@ -4955,10 +5107,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_LONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__l; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":261 + /* "numpy.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< @@ -4968,10 +5120,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_ULONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__L; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":262 + /* "numpy.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< @@ -4981,10 +5133,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__q; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":263 + /* "numpy.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< @@ -4994,10 +5146,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":264 + /* "numpy.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< @@ -5007,10 +5159,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__f; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":265 + /* "numpy.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< @@ -5020,10 +5172,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__d; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":266 + /* "numpy.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< @@ -5033,10 +5185,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__g; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":267 + /* "numpy.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< @@ -5046,10 +5198,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":268 + /* "numpy.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< @@ -5059,10 +5211,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":269 + /* "numpy.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< @@ -5072,10 +5224,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":270 + /* "numpy.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< @@ -5085,37 +5237,37 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__O; - goto __pyx_L15; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":272 + /* "numpy.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_9), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_9), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_8)); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L15:; + __pyx_L13:; - /* "numpy.pxd":273 + /* "numpy.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -5124,7 +5276,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":274 + /* "numpy.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -5133,57 +5285,57 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L13; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":276 + /* "numpy.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":277 + /* "numpy.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":278 + /* "numpy.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":281 + /* "numpy.pxd":285 * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string + * f[0] = c'\0' # Terminate format string * */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; - /* "numpy.pxd":282 + /* "numpy.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L13:; + __pyx_L11:; __pyx_r = 0; goto __pyx_L0; @@ -5208,31 +5360,39 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ return __pyx_r; } -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":288 + * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__"); + __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":285 + /* "numpy.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); if (__pyx_t_1) { - /* "numpy.pxd":286 + /* "numpy.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -5240,11 +5400,11 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * stdlib.free(info.strides) */ free(__pyx_v_info->format); - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":287 + /* "numpy.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< @@ -5254,7 +5414,7 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_t_1) { - /* "numpy.pxd":288 + /* "numpy.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -5262,14 +5422,14 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * */ free(__pyx_v_info->strides); - goto __pyx_L6; + goto __pyx_L4; } - __pyx_L6:; + __pyx_L4:; __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":764 +/* "numpy.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -5284,9 +5444,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":765 + /* "numpy.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -5294,7 +5454,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -5312,7 +5472,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":767 +/* "numpy.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -5327,9 +5487,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":768 + /* "numpy.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -5337,7 +5497,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -5355,7 +5515,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "numpy.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -5370,9 +5530,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":771 + /* "numpy.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -5380,7 +5540,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -5398,7 +5558,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "numpy.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -5413,9 +5573,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":774 + /* "numpy.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -5423,7 +5583,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -5441,7 +5601,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "numpy.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -5456,9 +5616,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":777 + /* "numpy.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -5466,7 +5626,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -5484,7 +5644,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "numpy.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -5507,18 +5667,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; + PyObject *(*__pyx_t_6)(PyObject *); int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; + int __pyx_t_10; + long __pyx_t_11; + char *__pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring"); + __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":786 + /* "numpy.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -5527,7 +5688,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":787 + /* "numpy.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -5536,7 +5697,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":790 + /* "numpy.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< @@ -5544,31 +5705,36 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * child, new_offset = fields */ if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif __Pyx_XDECREF(__pyx_v_childname); __pyx_v_childname = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":791 + /* "numpy.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); __pyx_v_fields = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":792 + /* "numpy.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< @@ -5577,20 +5743,49 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); - } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_child)); __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; @@ -5598,99 +5793,98 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_v_new_offset = __pyx_t_4; __pyx_t_4 = 0; - /* "numpy.pxd":794 + /* "numpy.pxd":798 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":795 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_11), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; } - __pyx_L5:; + __pyx_L7:; - /* "numpy.pxd":797 + /* "numpy.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = (__pyx_v_child->byteorder == '>'); + if (__pyx_t_7) { + __pyx_t_8 = __pyx_v_little_endian; } else { - __pyx_t_7 = __pyx_t_6; + __pyx_t_8 = __pyx_t_7; } - if (!__pyx_t_7) { + if (!__pyx_t_8) { - /* "numpy.pxd":798 + /* "numpy.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; + __pyx_t_7 = (__pyx_v_child->byteorder == '<'); + if (__pyx_t_7) { + __pyx_t_9 = (!__pyx_v_little_endian); + __pyx_t_10 = __pyx_t_9; } else { - __pyx_t_9 = __pyx_t_6; + __pyx_t_10 = __pyx_t_7; } - __pyx_t_6 = __pyx_t_9; + __pyx_t_7 = __pyx_t_10; } else { - __pyx_t_6 = __pyx_t_7; + __pyx_t_7 = __pyx_t_8; } - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; } - __pyx_L6:; + __pyx_L8:; - /* "numpy.pxd":809 + /* "numpy.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -5698,16 +5892,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!__pyx_t_6) break; + if (!__pyx_t_7) break; - /* "numpy.pxd":810 + /* "numpy.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -5716,7 +5909,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":811 + /* "numpy.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -5725,430 +5918,413 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":812 + /* "numpy.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); } - /* "numpy.pxd":814 + /* "numpy.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); - /* "numpy.pxd":816 + /* "numpy.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); - if (__pyx_t_6) { + __pyx_t_7 = (!PyDataType_HASFIELDS(__pyx_v_child)); + if (__pyx_t_7) { - /* "numpy.pxd":817 + /* "numpy.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XDECREF(__pyx_v_t); __pyx_v_t = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":818 + /* "numpy.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); - if (__pyx_t_6) { + __pyx_t_7 = ((__pyx_v_end - __pyx_v_f) < 5); + if (__pyx_t_7) { - /* "numpy.pxd":819 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; } - __pyx_L10:; + __pyx_L12:; - /* "numpy.pxd":822 + /* "numpy.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 98; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":823 + /* "numpy.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 66; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":824 + /* "numpy.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 104; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":825 + /* "numpy.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 72; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":826 + /* "numpy.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 105; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":827 + /* "numpy.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 73; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":828 + /* "numpy.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 108; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":829 + /* "numpy.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 76; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":830 + /* "numpy.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 113; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":831 + /* "numpy.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 81; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":832 + /* "numpy.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 102; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":833 + /* "numpy.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 100; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":834 + /* "numpy.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 103; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":835 + /* "numpy.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":836 + /* "numpy.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":837 + /* "numpy.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":838 + /* "numpy.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 79; - goto __pyx_L11; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":840 + /* "numpy.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_9), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_9), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L11:; + __pyx_L13:; - /* "numpy.pxd":841 + /* "numpy.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -6156,25 +6332,25 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":845 + /* "numpy.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_12; } - __pyx_L9:; + __pyx_L11:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":846 + /* "numpy.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -6203,7 +6379,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":961 +/* "numpy.pxd":965 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -6215,9 +6391,9 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base"); + __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":963 + /* "numpy.pxd":967 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -6227,7 +6403,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a __pyx_t_1 = (__pyx_v_base == Py_None); if (__pyx_t_1) { - /* "numpy.pxd":964 + /* "numpy.pxd":968 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -6239,7 +6415,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":966 + /* "numpy.pxd":970 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -6248,7 +6424,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":967 + /* "numpy.pxd":971 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -6259,7 +6435,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":968 + /* "numpy.pxd":972 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -6268,7 +6444,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":969 + /* "numpy.pxd":973 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -6280,7 +6456,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":971 +/* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -6292,9 +6468,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base"); + __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":972 + /* "numpy.pxd":976 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< @@ -6304,7 +6480,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __pyx_t_1 = (__pyx_v_arr->base == NULL); if (__pyx_t_1) { - /* "numpy.pxd":973 + /* "numpy.pxd":977 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -6319,7 +6495,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py } /*else*/ { - /* "numpy.pxd":975 + /* "numpy.pxd":979 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -6360,8 +6536,9 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_u_10, __pyx_k_10, sizeof(__pyx_k_10), 0, 1, 0, 0}, {&__pyx_kp_u_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 1, 0, 0}, {&__pyx_n_s_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 1, 1}, - {&__pyx_n_s_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 0, 1, 1}, + {&__pyx_kp_s_19, __pyx_k_19, sizeof(__pyx_k_19), 0, 0, 1, 0}, {&__pyx_kp_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 0}, + {&__pyx_n_s_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 1, 1}, {&__pyx_kp_u_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 1, 0, 0}, {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, @@ -6371,6 +6548,8 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s__DTYPE, __pyx_k__DTYPE, sizeof(__pyx_k__DTYPE), 0, 0, 1, 1}, {&__pyx_n_s__FW, __pyx_k__FW, sizeof(__pyx_k__FW), 0, 0, 1, 1}, {&__pyx_n_s__ITYPE, __pyx_k__ITYPE, sizeof(__pyx_k__ITYPE), 0, 0, 1, 1}, + {&__pyx_n_s__N, __pyx_k__N, sizeof(__pyx_k__N), 0, 0, 1, 1}, + {&__pyx_n_s__Nk, __pyx_k__Nk, sizeof(__pyx_k__Nk), 0, 0, 1, 1}, {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s__T, __pyx_k__T, sizeof(__pyx_k__T), 0, 0, 1, 1}, {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, @@ -6385,6 +6564,7 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, {&__pyx_n_s__flat, __pyx_k__flat, sizeof(__pyx_k__flat), 0, 0, 1, 1}, {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, + {&__pyx_n_s__graph, __pyx_k__graph, sizeof(__pyx_k__graph), 0, 0, 1, 1}, {&__pyx_n_s__graph_shortest_path, __pyx_k__graph_shortest_path, sizeof(__pyx_k__graph_shortest_path), 0, 0, 1, 1}, {&__pyx_n_s__indices, __pyx_k__indices, sizeof(__pyx_k__indices), 0, 0, 1, 1}, {&__pyx_n_s__indptr, __pyx_k__indptr, sizeof(__pyx_k__indptr), 0, 0, 1, 1}, @@ -6406,9 +6586,9 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -6416,91 +6596,121 @@ static int __Pyx_InitCachedBuiltins(void) { static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "numpy.pxd":211 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_4)); + __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_4); __Pyx_INCREF(((PyObject *)__pyx_kp_u_3)); PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_u_3)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_3)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); - /* "numpy.pxd":215 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_6)); + __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_6); __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_u_5)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_8 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_8)); + __pyx_k_tuple_8 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_8); __Pyx_INCREF(((PyObject *)__pyx_kp_u_7)); PyTuple_SET_ITEM(__pyx_k_tuple_8, 0, ((PyObject *)__pyx_kp_u_7)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_7)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); - /* "numpy.pxd":795 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_11 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_11)); + __pyx_k_tuple_11 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_11); __Pyx_INCREF(((PyObject *)__pyx_kp_u_10)); PyTuple_SET_ITEM(__pyx_k_tuple_11, 0, ((PyObject *)__pyx_kp_u_10)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_10)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_11)); - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_12)); + __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_12); __Pyx_INCREF(((PyObject *)__pyx_kp_u_7)); PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_7)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_7)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); - /* "numpy.pxd":819 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_14 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_14)); + __pyx_k_tuple_14 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_14); __Pyx_INCREF(((PyObject *)__pyx_kp_u_13)); PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, ((PyObject *)__pyx_kp_u_13)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_13)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + + /* "sklearn/utils/graph_shortest_path.pyx":30 + * + * + * def graph_shortest_path(dist_matrix, directed=True, method='auto'): # <<<<<<<<<<<<<< + * """ + * Perform a shortest-path graph search on a positive directed or + */ + __pyx_k_tuple_17 = PyTuple_New(6); if (unlikely(!__pyx_k_tuple_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_17); + __Pyx_INCREF(((PyObject *)__pyx_n_s__dist_matrix)); + PyTuple_SET_ITEM(__pyx_k_tuple_17, 0, ((PyObject *)__pyx_n_s__dist_matrix)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__dist_matrix)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__directed)); + PyTuple_SET_ITEM(__pyx_k_tuple_17, 1, ((PyObject *)__pyx_n_s__directed)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__directed)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__method)); + PyTuple_SET_ITEM(__pyx_k_tuple_17, 2, ((PyObject *)__pyx_n_s__method)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__method)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__N)); + PyTuple_SET_ITEM(__pyx_k_tuple_17, 3, ((PyObject *)__pyx_n_s__N)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__N)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__Nk)); + PyTuple_SET_ITEM(__pyx_k_tuple_17, 4, ((PyObject *)__pyx_n_s__Nk)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__Nk)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__graph)); + PyTuple_SET_ITEM(__pyx_k_tuple_17, 5, ((PyObject *)__pyx_n_s__graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_17)); + __pyx_k_codeobj_18 = (PyObject*)__Pyx_PyCode_New(3, 0, 6, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_17, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_19, __pyx_n_s__graph_shortest_path, 30, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -6538,12 +6748,18 @@ PyMODINIT_FUNC PyInit_graph_shortest_path(void) Py_FatalError("failed to import 'refnanny' module"); } #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_graph_shortest_path(void)"); + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_graph_shortest_path(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __pyx_binding_PyCFunctionType_USED - if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -6554,16 +6770,23 @@ PyMODINIT_FUNC PyInit_graph_shortest_path(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("graph_shortest_path"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_15), 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("graph_shortest_path"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_15), 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.utils.graph_shortest_path")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.utils.graph_shortest_path", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} @@ -6579,17 +6802,24 @@ PyMODINIT_FUNC PyInit_graph_shortest_path(void) /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ /* "sklearn/utils/graph_shortest_path.pyx":12 - * # License: BSD, (C) 2011 + * # License: BSD 3 clause, (C) 2011 * * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np @@ -6608,7 +6838,7 @@ PyMODINIT_FUNC PyInit_graph_shortest_path(void) * cimport cython */ __pyx_t_1 = PyList_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(((PyObject *)__pyx_n_s__csr_matrix)); PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s__csr_matrix)); __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csr_matrix)); @@ -6621,15 +6851,27 @@ PyMODINIT_FUNC PyInit_graph_shortest_path(void) __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s_16), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__csr_matrix); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__csr_matrix); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__csr_matrix); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } __Pyx_GOTREF(__pyx_t_1); if (PyObject_SetAttr(__pyx_m, __pyx_n_s__csr_matrix, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isspmatrix); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isspmatrix); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__isspmatrix); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } __Pyx_GOTREF(__pyx_t_1); if (PyObject_SetAttr(__pyx_m, __pyx_n_s__isspmatrix, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isspmatrix_csr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isspmatrix_csr); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__isspmatrix_csr); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } __Pyx_GOTREF(__pyx_t_1); if (PyObject_SetAttr(__pyx_m, __pyx_n_s__isspmatrix_csr, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; @@ -6638,48 +6880,57 @@ PyMODINIT_FUNC PyInit_graph_shortest_path(void) /* "sklearn/utils/graph_shortest_path.pyx":21 * from libc.stdlib cimport malloc, free * + * np.import_array() # <<<<<<<<<<<<<< + * + * DTYPE = np.float64 + */ + import_array(); + + /* "sklearn/utils/graph_shortest_path.pyx":23 + * np.import_array() + * * DTYPE = np.float64 # <<<<<<<<<<<<<< * ctypedef np.float64_t DTYPE_t * */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__DTYPE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__DTYPE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":24 + /* "sklearn/utils/graph_shortest_path.pyx":26 * ctypedef np.float64_t DTYPE_t * * ITYPE = np.int32 # <<<<<<<<<<<<<< * ctypedef np.int32_t ITYPE_t * */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__int32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__int32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__ITYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__ITYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "sklearn/utils/graph_shortest_path.pyx":28 + /* "sklearn/utils/graph_shortest_path.pyx":30 * * * def graph_shortest_path(dist_matrix, directed=True, method='auto'): # <<<<<<<<<<<<<< * """ * Perform a shortest-path graph search on a positive directed or */ - __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_k_1 = __pyx_t_2; __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_19graph_shortest_path_graph_shortest_path, NULL, __pyx_n_s_17); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_19graph_shortest_path_1graph_shortest_path, NULL, __pyx_n_s_20); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__graph_shortest_path, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__graph_shortest_path, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "sklearn/utils/graph_shortest_path.pyx":1 @@ -6692,7 +6943,7 @@ PyMODINIT_FUNC PyInit_graph_shortest_path(void) if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - /* "numpy.pxd":971 + /* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -6719,7 +6970,6 @@ PyMODINIT_FUNC PyInit_graph_shortest_path(void) } /* Runtime support code */ - #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; @@ -6760,7 +7010,7 @@ static void __Pyx_RaiseDoubleKeywordsError( "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); + PyString_AsString(kw_name)); #endif } @@ -6776,55 +7026,77 @@ static int __Pyx_ParseOptionalKeywords( Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { values[name-argnames] = value; - } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; } } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; } } return 0; arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); + __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, @@ -6852,7 +7124,6 @@ static void __Pyx_RaiseArgtupleInvalid( { Py_ssize_t num_expected; const char *more_or_less; - if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; @@ -6864,12 +7135,11 @@ static void __Pyx_RaiseArgtupleInvalid( more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", + "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } - static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_Format(PyExc_SystemError, "Missing type object"); @@ -6883,9 +7153,9 @@ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { } static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; @@ -6895,55 +7165,60 @@ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyOb Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif } - static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif } - #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) + if (PyClass_Check(type)) { #else - if (!PyType_Check(type)) + if (PyType_Check(type)) { #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - /* Normalize to raise , */ - Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 if (PyInstance_Check(type)) { @@ -6966,7 +7241,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } #endif } - __Pyx_ErrRestore(type, value, tb); return; raise_error: @@ -6975,10 +7249,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tb); return; } - #else /* Python 3+ */ - static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -6988,7 +7261,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } if (value == Py_None) value = 0; - if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, @@ -6997,13 +7269,36 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } + else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } - - if (cause) { + if (cause && cause != Py_None) { PyObject *fixed_cause; if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); @@ -7020,14 +7315,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; @@ -7037,8 +7327,8 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tmp_tb); } } - bad: + Py_XDECREF(owned_instance); return; } #endif @@ -7047,18 +7337,6 @@ static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } - -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; -} __Pyx_BufFmt_Context; - static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { @@ -7077,6 +7355,8 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; @@ -7084,7 +7364,6 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, type = type->fields->type; } } - static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; @@ -7100,15 +7379,21 @@ static int __Pyx_BufFmt_ParseNumber(const char** ts) { *ts = t; return count; } - +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } - static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { - case 'b': return "'char'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; @@ -7124,14 +7409,14 @@ static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; + case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } - static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; @@ -7147,10 +7432,9 @@ static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { return 0; } } - static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'B': return 1; + case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); @@ -7167,7 +7451,6 @@ static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { } } } - typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; @@ -7178,10 +7461,9 @@ typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif - -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); @@ -7197,21 +7479,59 @@ static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { return 0; } } - +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'h': case 'i': case 'l': case 'q': return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; - case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); - case 'O': return 'O'; - case 'P': return 'P'; + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } - static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; @@ -7236,16 +7556,37 @@ static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { parent->type->name, field->name); } } - static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; - size_t size, offset; + size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { @@ -7257,35 +7598,35 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); } - if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { - /* special case -- treat as struct rather than complex number */ size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } - - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } - offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } - ctx->fmt_offset += size; - + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; /* Consume from buffer string */ - - /* Done checking, move to next field, pushing or popping struct stack if needed */ while (1) { if (field == &ctx->root) { ctx->head = NULL; @@ -7317,7 +7658,48 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ctx->is_complex = 0; return 0; } - +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + if (isspace(*ts)) + continue; + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { @@ -7332,7 +7714,7 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } - return ts; + return ts; case ' ': case 10: case 13: @@ -7364,12 +7746,17 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { @@ -7377,10 +7764,19 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha if (!ts_after_sub) return NULL; } ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': /* end of substruct; either repeat or move on */ - ++ts; + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; @@ -7401,13 +7797,11 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': - case 'O': + case 'O': case 's': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { - /* Continue pooling same type */ ctx->enc_count += ctx->new_count; } else { - /* New type */ if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; @@ -7423,20 +7817,18 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha while(*ts != ':') ++ts; ++ts; break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; default: { - int number = __Pyx_BufFmt_ParseNumber(&ts); - if (number == -1) { /* First char was not a digit */ - PyErr_Format(PyExc_ValueError, - "Does not understand character buffer dtype format string ('%c')", *ts); - return NULL; - } - ctx->new_count = (size_t)number; + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; } } } } - static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; @@ -7444,8 +7836,10 @@ static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; @@ -7465,7 +7859,7 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* ob } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; @@ -7476,65 +7870,146 @@ fail:; __Pyx_ZeroBuffer(buf); return -1; } - static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", + index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; } else { - __Pyx_RaiseTooManyValuesError(index); + return __Pyx_IterFinish(); } + return 0; } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + CYTHON_UNUSED PyObject *getbuffer_cobj; #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); - else { - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict && + (getbuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, + "__pyx_getbuffer"))) { + getbufferproc func; + #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + func = (getbufferproc) PyCapsule_GetPointer(getbuffer_cobj, "getbuffer(obj, view, flags)"); + #else + func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + #endif + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); } + #endif + PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; } - static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject* obj = view->obj; - if (obj) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;} - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray_1__releasebuffer__(obj, view); + PyObject *obj = view->obj; + CYTHON_UNUSED PyObject *releasebuffer_cobj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict && + (releasebuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, + "__pyx_releasebuffer"))) { + releasebufferproc func; + #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + func = (releasebufferproc) PyCapsule_GetPointer(releasebuffer_cobj, "releasebuffer(obj, view)"); + #else + func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + #endif + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: Py_DECREF(obj); view->obj = NULL; - } } +#endif /* PY_MAJOR_VERSION < 3 */ -#endif -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { PyObject *py_import = 0; PyObject *empty_list = 0; PyObject *module = 0; @@ -7560,12 +8035,33 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { goto bad; #if PY_VERSION_HEX >= 0x02050000 { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + /* try package relative import first */ + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + } } #else if (level>0) { @@ -7582,66 +8078,13 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { return module; } -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { - if (s1 == s2) { /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */ - return (equals == Py_EQ); - } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { - if (PyBytes_GET_SIZE(s1) != PyBytes_GET_SIZE(s2)) { - return (equals == Py_NE); - } else if (PyBytes_GET_SIZE(s1) == 1) { - if (equals == Py_EQ) - return (PyBytes_AS_STRING(s1)[0] == PyBytes_AS_STRING(s2)[0]); - else - return (PyBytes_AS_STRING(s1)[0] != PyBytes_AS_STRING(s2)[0]); - } else { - int result = memcmp(PyBytes_AS_STRING(s1), PyBytes_AS_STRING(s2), (size_t)PyBytes_GET_SIZE(s1)); - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { - return (equals == Py_NE); - } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { - return (equals == Py_NE); - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -} - -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { - if (s1 == s2) { /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */ - return (equals == Py_EQ); - } else if (PyUnicode_CheckExact(s1) & PyUnicode_CheckExact(s2)) { - if (PyUnicode_GET_SIZE(s1) != PyUnicode_GET_SIZE(s2)) { - return (equals == Py_NE); - } else if (PyUnicode_GET_SIZE(s1) == 1) { - if (equals == Py_EQ) - return (PyUnicode_AS_UNICODE(s1)[0] == PyUnicode_AS_UNICODE(s2)[0]); - else - return (PyUnicode_AS_UNICODE(s1)[0] != PyUnicode_AS_UNICODE(s2)[0]); - } else { - int result = PyUnicode_Compare(s1, s2); - if ((result == -1) && unlikely(PyErr_Occurred())) - return -1; - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & PyUnicode_CheckExact(s2)) { - return (equals == Py_NE); - } else if ((s2 == Py_None) & PyUnicode_CheckExact(s1)) { - return (equals == Py_NE); - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } +static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name) { +#if PY_MAJOR_VERSION < 3 + PyErr_Format(PyExc_ImportError, "cannot import name %.230s", + PyString_AsString(name)); +#else + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); +#endif } #if CYTHON_CCOMPLEX @@ -8284,8 +8727,8 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* } } -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename) { +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); @@ -8322,6 +8765,23 @@ static int __Pyx_check_binary_version(void) { return 0; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -8331,15 +8791,10 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(class_name); - #else - py_name = PyUnicode_FromString(class_name); - #endif + py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); @@ -8355,7 +8810,7 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { + if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -8365,7 +8820,7 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { PyErr_Format(PyExc_ValueError, "%s.%s has the wrong size, try recompiling", module_name, class_name); @@ -8379,51 +8834,105 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(name); - #else - py_name = PyUnicode_FromString(name); - #endif - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); } -#endif #include "compile.h" #include "frameobject.h" #include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); + py_srcfile = PyString_FromString(filename); #else - py_srcfile = PyUnicode_FromString(__pyx_filename); + py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; - if (__pyx_clineno) { + if (c_line) { #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { @@ -8434,28 +8943,45 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, #endif } if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_code = PyCode_New( + py_code = __Pyx_PyCode_New( 0, /*int argcount,*/ - #if PY_MAJOR_VERSION >= 3 0, /*int kwonlyargcount,*/ - #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ + py_line, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); - if (!py_code) goto bad; + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ @@ -8463,11 +8989,9 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; + py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); } @@ -8502,6 +9026,7 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } + /* Type Conversion Functions */ static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { diff --git a/sklearn/utils/graph_shortest_path.pyx b/sklearn/utils/graph_shortest_path.pyx index 2fc18c5ede103..7d8363403bd57 100644 --- a/sklearn/utils/graph_shortest_path.pyx +++ b/sklearn/utils/graph_shortest_path.pyx @@ -7,7 +7,7 @@ the Floyd-Warshall algorithm, or Dykstra's algorithm with Fibonacci Heaps. """ # Author: Jake Vanderplas -- -# License: BSD, (C) 2011 +# License: BSD 3 clause, (C) 2011 import numpy as np cimport numpy as np @@ -18,6 +18,8 @@ cimport cython from libc.stdlib cimport malloc, free +np.import_array() + DTYPE = np.float64 ctypedef np.float64_t DTYPE_t diff --git a/sklearn/utils/lgamma.c b/sklearn/utils/lgamma.c new file mode 100644 index 0000000000000..6cea77fdf4b23 --- /dev/null +++ b/sklearn/utils/lgamma.c @@ -0,0 +1,1676 @@ +/* Generated by Cython 0.17.2 on Thu Jan 31 01:17:35 2013 */ + +#define PY_SSIZE_T_CLEAN +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_VERSION_HEX < 0x03020000 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__utils__lgamma +#define __PYX_HAVE_API__sklearn__utils__lgamma +#include "src/gamma.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + + +/* inline attribute */ +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* unused attribute */ +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif + +typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + + +/* Type Conversion Predeclarations */ + +#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) +#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) + +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); + +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); + +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) + +#ifdef __GNUC__ + /* Test for GCC > 2.95 */ + #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) + #else /* __GNUC__ > 2 ... */ + #define likely(x) (x) + #define unlikely(x) (x) + #endif /* __GNUC__ > 2 ... */ +#else /* __GNUC__ */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + + +static const char *__pyx_f[] = { + "lgamma.pyx", +}; + +/*--- Type declarations ---*/ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); + +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); + +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); + +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); + +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); + +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); + +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); + +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename); /*proto*/ + +static int __Pyx_check_binary_version(void); + +static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'sklearn.utils.lgamma' */ +#define __Pyx_MODULE_NAME "sklearn.utils.lgamma" +int __pyx_module_is_main_sklearn__utils__lgamma = 0; + +/* Implementation of 'sklearn.utils.lgamma' */ +static PyObject *__pyx_builtin_ValueError; +static char __pyx_k_1[] = "x must be strictly positive, got %f"; +static char __pyx_k____main__[] = "__main__"; +static char __pyx_k____test__[] = "__test__"; +static char __pyx_k__ValueError[] = "ValueError"; +static PyObject *__pyx_kp_s_1; +static PyObject *__pyx_n_s__ValueError; +static PyObject *__pyx_n_s____main__; +static PyObject *__pyx_n_s____test__; + +/* "sklearn/utils/lgamma.pyx":5 + * + * + * cdef double lgamma(double x): # <<<<<<<<<<<<<< + * if x <= 0: + * raise ValueError("x must be strictly positive, got %f" % x) + */ + +static double __pyx_f_7sklearn_5utils_6lgamma_lgamma(double __pyx_v_x) { + double __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("lgamma", 0); + + /* "sklearn/utils/lgamma.pyx":6 + * + * cdef double lgamma(double x): + * if x <= 0: # <<<<<<<<<<<<<< + * raise ValueError("x must be strictly positive, got %f" % x) + * return sklearn_lgamma(x) + */ + __pyx_t_1 = (__pyx_v_x <= 0.0); + if (__pyx_t_1) { + + /* "sklearn/utils/lgamma.pyx":7 + * cdef double lgamma(double x): + * if x <= 0: + * raise ValueError("x must be strictly positive, got %f" % x) # <<<<<<<<<<<<<< + * return sklearn_lgamma(x) + */ + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_x); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_1), __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_t_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/utils/lgamma.pyx":8 + * if x <= 0: + * raise ValueError("x must be strictly positive, got %f" % x) + * return sklearn_lgamma(x) # <<<<<<<<<<<<<< + */ + __pyx_r = sklearn_lgamma(__pyx_v_x); + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_WriteUnraisable("sklearn.utils.lgamma.lgamma", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + PyModuleDef_HEAD_INIT, + __Pyx_NAMESTR("lgamma"), + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 0}, + {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, + {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, + {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC initlgamma(void); /*proto*/ +PyMODINIT_FUNC initlgamma(void) +#else +PyMODINIT_FUNC PyInit_lgamma(void); /*proto*/ +PyMODINIT_FUNC PyInit_lgamma(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_lgamma(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("lgamma"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.utils.lgamma")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.utils.lgamma", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_module_is_main_sklearn__utils__lgamma) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + if (__Pyx_ExportFunction("lgamma", (void (*)(void))__pyx_f_7sklearn_5utils_6lgamma_lgamma, "double (double)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Type init code ---*/ + /*--- Type import code ---*/ + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/utils/lgamma.pyx":1 + * cdef extern from "src/gamma.h": # <<<<<<<<<<<<<< + * cdef double sklearn_lgamma(double x) + * + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.utils.lgamma", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.utils.lgamma"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { + PyObject *result; + result = PyObject_GetAttr(dict, name); + if (!result) { + if (dict != __pyx_b) { + PyErr_Clear(); + result = PyObject_GetAttr(__pyx_b, name); + } + if (!result) { + PyErr_SetObject(PyExc_NameError, name); + } + } + return result; +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { + #endif +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } + else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } + else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause && cause != Py_None) { + PyObject *fixed_cause; + if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } + else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } + else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { + const unsigned char neg_one = (unsigned char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned char" : + "value too large to convert to unsigned char"); + } + return (unsigned char)-1; + } + return (unsigned char)val; + } + return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { + const unsigned short neg_one = (unsigned short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned short" : + "value too large to convert to unsigned short"); + } + return (unsigned short)-1; + } + return (unsigned short)val; + } + return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { + const unsigned int neg_one = (unsigned int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned int" : + "value too large to convert to unsigned int"); + } + return (unsigned int)-1; + } + return (unsigned int)val; + } + return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { + const char neg_one = (char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to char" : + "value too large to convert to char"); + } + return (char)-1; + } + return (char)val; + } + return (char)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { + const short neg_one = (short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to short" : + "value too large to convert to short"); + } + return (short)-1; + } + return (short)val; + } + return (short)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { + const signed char neg_one = (signed char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed char" : + "value too large to convert to signed char"); + } + return (signed char)-1; + } + return (signed char)val; + } + return (signed char)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { + const signed short neg_one = (signed short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed short" : + "value too large to convert to signed short"); + } + return (signed short)-1; + } + return (signed short)val; + } + return (signed short)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { + const signed int neg_one = (signed int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed int" : + "value too large to convert to signed int"); + } + return (signed int)-1; + } + return (signed int)val; + } + return (signed int)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { + const unsigned long neg_one = (unsigned long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)PyLong_AsUnsignedLong(x); + } else { + return (unsigned long)PyLong_AsLong(x); + } + } else { + unsigned long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned long)-1; + val = __Pyx_PyInt_AsUnsignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { + const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { + return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + unsigned PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsUnsignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { + const long neg_one = (long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)PyLong_AsUnsignedLong(x); + } else { + return (long)PyLong_AsLong(x); + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long)-1; + val = __Pyx_PyInt_AsLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { + const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { + return (PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { + const signed long neg_one = (signed long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)PyLong_AsUnsignedLong(x); + } else { + return (signed long)PyLong_AsLong(x); + } + } else { + signed long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed long)-1; + val = __Pyx_PyInt_AsSignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { + const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { + return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + signed PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsSignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(__pyx_m, (char *)"__pyx_capi__"); + if (!d) { + PyErr_Clear(); + d = PyDict_New(); + if (!d) + goto bad; + Py_INCREF(d); + if (PyModule_AddObject(__pyx_m, (char *)"__pyx_capi__", d) < 0) + goto bad; + } + tmp.fp = f; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + cobj = PyCapsule_New(tmp.p, sig, 0); +#else + cobj = PyCObject_FromVoidPtrAndDesc(tmp.p, (void *)sig, 0); +#endif + if (!cobj) + goto bad; + if (PyDict_SetItemString(d, name, cobj) < 0) + goto bad; + Py_DECREF(cobj); + Py_DECREF(d); + return 0; +bad: + Py_XDECREF(cobj); + Py_XDECREF(d); + return -1; +} + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + + +/* Type Conversion Functions */ + +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} + +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_VERSION_HEX < 0x03000000 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_VERSION_HEX < 0x03000000 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_VERSION_HEX < 0x03000000 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%s__ returned non-%s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} + +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject* x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} + +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} + +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { + unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); + if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { + return (size_t)-1; + } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); + return (size_t)-1; + } + return (size_t)val; +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/utils/lgamma.pxd b/sklearn/utils/lgamma.pxd new file mode 100644 index 0000000000000..2010af8f4adc3 --- /dev/null +++ b/sklearn/utils/lgamma.pxd @@ -0,0 +1 @@ +cdef double lgamma(double x) diff --git a/sklearn/utils/lgamma.pyx b/sklearn/utils/lgamma.pyx new file mode 100644 index 0000000000000..c0d21a304c7dc --- /dev/null +++ b/sklearn/utils/lgamma.pyx @@ -0,0 +1,8 @@ +cdef extern from "src/gamma.h": + cdef double sklearn_lgamma(double x) + + +cdef double lgamma(double x): + if x <= 0: + raise ValueError("x must be strictly positive, got %f" % x) + return sklearn_lgamma(x) diff --git a/sklearn/utils/linear_assignment_.py b/sklearn/utils/linear_assignment_.py new file mode 100644 index 0000000000000..431aaa6cd86c3 --- /dev/null +++ b/sklearn/utils/linear_assignment_.py @@ -0,0 +1,281 @@ +""" +Solve the unique lowest-cost assignment problem using the +Hungarian algorithm (also known as Munkres algorithm). + +""" +# Based on original code by Brain Clapper, adapted to NumPy by Gael Varoquaux. +# Heavily refactored by Lars Buitinck. + +# Copyright (c) 2008 Brian M. Clapper , Gael Varoquaux +# Author: Brian M. Clapper, Gael Varoquaux +# LICENSE: BSD + +import numpy as np + +from .fixes import astype + + +def linear_assignment(X): + """Solve the linear assignment problem using the Hungarian algorithm. + + The problem is also known as maximum weight matching in bipartite graphs. + The method is also known as the Munkres or Kuhn-Munkres algorithm. + + Parameters + ---------- + X : array + The cost matrix of the bipartite graph + + Returns + ------- + indices : array, + The pairs of (row, col) indices in the original array giving + the original ordering. + + References + ---------- + + 1. http://www.public.iastate.edu/~ddoty/HungarianAlgorithm.html + + 2. Harold W. Kuhn. The Hungarian Method for the assignment problem. + *Naval Research Logistics Quarterly*, 2:83-97, 1955. + + 3. Harold W. Kuhn. Variants of the Hungarian method for assignment + problems. *Naval Research Logistics Quarterly*, 3: 253-258, 1956. + + 4. Munkres, J. Algorithms for the Assignment and Transportation Problems. + *Journal of the Society of Industrial and Applied Mathematics*, + 5(1):32-38, March, 1957. + + 5. http://en.wikipedia.org/wiki/Hungarian_algorithm + """ + indices = _hungarian(X).tolist() + indices.sort() + # Re-force dtype to ints in case of empty list + indices = np.array(indices, dtype=int) + # Make sure the array is 2D with 2 columns. + # This is needed when dealing with an empty list + indices.shape = (-1, 2) + return indices + + +class _HungarianState(object): + """State of one execution of the Hungarian algorithm. + + Parameters + ---------- + cost_matrix : 2D matrix + The cost matrix. Does not have to be square. + """ + + def __init__(self, cost_matrix): + cost_matrix = np.atleast_2d(cost_matrix) + + # If there are more rows (n) than columns (m), then the algorithm + # will not be able to work correctly. Therefore, we + # transpose the cost function when needed. Just have to + # remember to swap the result columns back later. + transposed = (cost_matrix.shape[1] < cost_matrix.shape[0]) + if transposed: + self.C = (cost_matrix.T).copy() + else: + self.C = cost_matrix.copy() + self.transposed = transposed + + # At this point, m >= n. + n, m = self.C.shape + self.row_uncovered = np.ones(n, dtype=np.bool) + self.col_uncovered = np.ones(m, dtype=np.bool) + self.Z0_r = 0 + self.Z0_c = 0 + self.path = np.zeros((n + m, 2), dtype=int) + self.marked = np.zeros((n, m), dtype=int) + + def _find_prime_in_row(self, row): + """ + Find the first prime element in the specified row. Returns + the column index, or -1 if no starred element was found. + """ + col = np.argmax(self.marked[row] == 2) + if self.marked[row, col] != 2: + col = -1 + return col + + def _clear_covers(self): + """Clear all covered matrix cells""" + self.row_uncovered[:] = True + self.col_uncovered[:] = True + + +def _hungarian(cost_matrix): + """The Hungarian algorithm. + + Calculate the Munkres solution to the classical assignment problem and + return the indices for the lowest-cost pairings. + + Parameters + ---------- + cost_matrix : 2D matrix + The cost matrix. Does not have to be square. + + Returns + ------- + indices : 2D array of indices + The pairs of (row, col) indices in the original array giving + the original ordering. + """ + state = _HungarianState(cost_matrix) + + # No need to bother with assignments if one of the dimensions + # of the cost matrix is zero-length. + step = None if 0 in cost_matrix.shape else _step1 + + while step is not None: + step = step(state) + + # Look for the starred columns + results = np.array(np.where(state.marked == 1)).T + + # We need to swap the columns because we originally + # did a transpose on the input cost matrix. + if state.transposed: + results = results[:, ::-1] + + return results + + +# Individual steps of the algorithm follow, as a state machine: they return +# the next step to be taken (function to be called), if any. + +def _step1(state): + """Steps 1 and 2 in the Wikipedia page.""" + + # Step1: For each row of the matrix, find the smallest element and + # subtract it from every element in its row. + state.C -= state.C.min(axis=1)[:, np.newaxis] + # Step2: Find a zero (Z) in the resulting matrix. If there is no + # starred zero in its row or column, star Z. Repeat for each element + # in the matrix. + for i, j in zip(*np.where(state.C == 0)): + if state.col_uncovered[j] and state.row_uncovered[i]: + state.marked[i, j] = 1 + state.col_uncovered[j] = False + state.row_uncovered[i] = False + + state._clear_covers() + return _step3 + + +def _step3(state): + """ + Cover each column containing a starred zero. If n columns are covered, + the starred zeros describe a complete set of unique assignments. + In this case, Go to DONE, otherwise, Go to Step 4. + """ + marked = (state.marked == 1) + state.col_uncovered[np.any(marked, axis=0)] = False + + if marked.sum() < state.C.shape[0]: + return _step4 + + +def _step4(state): + """ + Find a noncovered zero and prime it. If there is no starred zero + in the row containing this primed zero, Go to Step 5. Otherwise, + cover this row and uncover the column containing the starred + zero. Continue in this manner until there are no uncovered zeros + left. Save the smallest uncovered value and Go to Step 6. + """ + # We convert to int as numpy operations are faster on int + C = (state.C == 0).astype(np.int) + covered_C = C * state.row_uncovered[:, np.newaxis] + covered_C *= astype(state.col_uncovered, dtype=np.int, copy=False) + n = state.C.shape[0] + m = state.C.shape[1] + while True: + # Find an uncovered zero + row, col = np.unravel_index(np.argmax(covered_C), (n, m)) + if covered_C[row, col] == 0: + return _step6 + else: + state.marked[row, col] = 2 + # Find the first starred element in the row + star_col = np.argmax(state.marked[row] == 1) + if not state.marked[row, star_col] == 1: + # Could not find one + state.Z0_r = row + state.Z0_c = col + return _step5 + else: + col = star_col + state.row_uncovered[row] = False + state.col_uncovered[col] = True + covered_C[:, col] = C[:, col] * ( + astype(state.row_uncovered, dtype=np.int, copy=False)) + covered_C[row] = 0 + + +def _step5(state): + """ + Construct a series of alternating primed and starred zeros as follows. + Let Z0 represent the uncovered primed zero found in Step 4. + Let Z1 denote the starred zero in the column of Z0 (if any). + Let Z2 denote the primed zero in the row of Z1 (there will always be one). + Continue until the series terminates at a primed zero that has no starred + zero in its column. Unstar each starred zero of the series, star each + primed zero of the series, erase all primes and uncover every line in the + matrix. Return to Step 3 + """ + count = 0 + path = state.path + path[count, 0] = state.Z0_r + path[count, 1] = state.Z0_c + + while True: + # Find the first starred element in the col defined by + # the path. + row = np.argmax(state.marked[:, path[count, 1]] == 1) + if not state.marked[row, path[count, 1]] == 1: + # Could not find one + break + else: + count += 1 + path[count, 0] = row + path[count, 1] = path[count - 1, 1] + + # Find the first prime element in the row defined by the + # first path step + col = np.argmax(state.marked[path[count, 0]] == 2) + if state.marked[row, col] != 2: + col = -1 + count += 1 + path[count, 0] = path[count - 1, 0] + path[count, 1] = col + + # Convert paths + for i in range(count + 1): + if state.marked[path[i, 0], path[i, 1]] == 1: + state.marked[path[i, 0], path[i, 1]] = 0 + else: + state.marked[path[i, 0], path[i, 1]] = 1 + + state._clear_covers() + # Erase all prime markings + state.marked[state.marked == 2] = 0 + return _step3 + + +def _step6(state): + """ + Add the value found in Step 4 to every element of each covered row, + and subtract it from every element of each uncovered column. + Return to Step 4 without altering any stars, primes, or covered lines. + """ + # the smallest uncovered value in the matrix + if np.any(state.row_uncovered) and np.any(state.col_uncovered): + minval = np.min(state.C[state.row_uncovered], axis=0) + minval = np.min(minval[state.col_uncovered]) + state.C[np.logical_not(state.row_uncovered)] += minval + state.C[:, state.col_uncovered] -= minval + return _step4 diff --git a/sklearn/utils/metaestimators.py b/sklearn/utils/metaestimators.py new file mode 100644 index 0000000000000..a131315320608 --- /dev/null +++ b/sklearn/utils/metaestimators.py @@ -0,0 +1,72 @@ +"""Utilities for meta-estimators""" +# Author: Joel Nothman +# Andreas Mueller +# Licence: BSD + +from operator import attrgetter +from functools import update_wrapper + + +__all__ = ['if_delegate_has_method'] + + +class _IffHasAttrDescriptor(object): + """Implements a conditional property using the descriptor protocol. + + Using this class to create a decorator will raise an ``AttributeError`` + if the ``attribute_name`` is not present on the base object. + + This allows ducktyping of the decorated method based on ``attribute_name``. + + See https://docs.python.org/3/howto/descriptor.html for an explanation of + descriptors. + """ + def __init__(self, fn, attribute_name): + self.fn = fn + self.get_attribute = attrgetter(attribute_name) + # update the docstring of the descriptor + update_wrapper(self, fn) + + def __get__(self, obj, type=None): + # raise an AttributeError if the attribute is not present on the object + if obj is not None: + # delegate only on instances, not the classes. + # this is to allow access to the docstrings. + self.get_attribute(obj) + # lambda, but not partial, allows help() to work with update_wrapper + out = lambda *args, **kwargs: self.fn(obj, *args, **kwargs) + # update the docstring of the returned function + update_wrapper(out, self.fn) + return out + + +def if_delegate_has_method(delegate): + """Create a decorator for methods that are delegated to a sub-estimator + + This enables ducktyping by hasattr returning True according to the + sub-estimator. + + >>> from sklearn.utils.metaestimators import if_delegate_has_method + >>> + >>> + >>> class MetaEst(object): + ... def __init__(self, sub_est): + ... self.sub_est = sub_est + ... + ... @if_delegate_has_method(delegate='sub_est') + ... def predict(self, X): + ... return self.sub_est.predict(X) + ... + >>> class HasPredict(object): + ... def predict(self, X): + ... return X.sum(axis=1) + ... + >>> class HasNoPredict(object): + ... pass + ... + >>> hasattr(MetaEst(HasPredict()), 'predict') + True + >>> hasattr(MetaEst(HasNoPredict()), 'predict') + False + """ + return lambda fn: _IffHasAttrDescriptor(fn, '%s.%s' % (delegate, fn.__name__)) diff --git a/sklearn/utils/mocking.py b/sklearn/utils/mocking.py new file mode 100644 index 0000000000000..f85a05220da78 --- /dev/null +++ b/sklearn/utils/mocking.py @@ -0,0 +1,65 @@ +from sklearn.base import BaseEstimator +from sklearn.utils.testing import assert_true + + +class ArraySlicingWrapper(object): + def __init__(self, array): + self.array = array + + def __getitem__(self, aslice): + return MockDataFrame(self.array[aslice]) + + +class MockDataFrame(object): + + # have shape an length but don't support indexing. + def __init__(self, array): + self.array = array + self.shape = array.shape + self.ndim = array.ndim + # ugly hack to make iloc work. + self.iloc = ArraySlicingWrapper(array) + + def __len__(self): + return len(self.array) + + def __array__(self): + # Pandas data frames also are array-like: we want to make sure that + # input validation in cross-validation does not try to call that + # method. + return self.array + + +class CheckingClassifier(BaseEstimator): + """Dummy classifier to test pipelining and meta-estimators. + + Checks some property of X and y in fit / predict. + This allows testing whether pipelines / cross-validation or metaestimators + changed the input. + """ + def __init__(self, check_y=None, + check_X=None, foo_param=0): + self.check_y = check_y + self.check_X = check_X + self.foo_param = foo_param + + def fit(self, X, y): + assert_true(len(X) == len(y)) + if self.check_X is not None: + assert_true(self.check_X(X)) + if self.check_y is not None: + assert_true(self.check_y(y)) + + return self + + def predict(self, T): + if self.check_X is not None: + assert_true(self.check_X(T)) + return T.shape[0] + + def score(self, X=None, Y=None): + if self.foo_param > 1: + score = 1. + else: + score = 0. + return score diff --git a/sklearn/utils/multiclass.py b/sklearn/utils/multiclass.py new file mode 100644 index 0000000000000..caf2524fd1a42 --- /dev/null +++ b/sklearn/utils/multiclass.py @@ -0,0 +1,426 @@ +# Author: Arnaud Joly, Joel Nothman, Hamzeh Alsalhi +# +# License: BSD 3 clause +""" +Multi-class / multi-label utility function +========================================== + +""" +from __future__ import division +from collections import Sequence +from itertools import chain +import warnings + +from scipy.sparse import issparse +from scipy.sparse.base import spmatrix +from scipy.sparse import dok_matrix +from scipy.sparse import lil_matrix + +import numpy as np + +from ..externals.six import string_types + +from .validation import check_array + +from ..utils.fixes import bincount + + +def _unique_multiclass(y): + if hasattr(y, '__array__'): + return np.unique(np.asarray(y)) + else: + return set(y) + + +def _unique_sequence_of_sequence(y): + if hasattr(y, '__array__'): + y = np.asarray(y) + return set(chain.from_iterable(y)) + + +def _unique_indicator(y): + return np.arange(check_array(y, ['csr', 'csc', 'coo']).shape[1]) + + +_FN_UNIQUE_LABELS = { + 'binary': _unique_multiclass, + 'multiclass': _unique_multiclass, + 'multilabel-sequences': _unique_sequence_of_sequence, + 'multilabel-indicator': _unique_indicator, +} + + +def unique_labels(*ys): + """Extract an ordered array of unique labels + + We don't allow: + - mix of multilabel and multiclass (single label) targets + - mix of label indicator matrix and anything else, + because there are no explicit labels) + - mix of label indicator matrices of different sizes + - mix of string and integer labels + + At the moment, we also don't allow "multiclass-multioutput" input type. + + Parameters + ---------- + *ys : array-likes, + + Returns + ------- + out : numpy array of shape [n_unique_labels] + An ordered array of unique labels. + + Examples + -------- + >>> from sklearn.utils.multiclass import unique_labels + >>> unique_labels([3, 5, 5, 5, 7, 7]) + array([3, 5, 7]) + >>> unique_labels([1, 2, 3, 4], [2, 2, 3, 4]) + array([1, 2, 3, 4]) + >>> unique_labels([1, 2, 10], [5, 11]) + array([ 1, 2, 5, 10, 11]) + """ + if not ys: + raise ValueError('No argument has been passed.') + # Check that we don't mix label format + + ys_types = set(type_of_target(x) for x in ys) + if ys_types == set(["binary", "multiclass"]): + ys_types = set(["multiclass"]) + + if len(ys_types) > 1: + raise ValueError("Mix type of y not allowed, got types %s" % ys_types) + + label_type = ys_types.pop() + + # Check consistency for the indicator format + if (label_type == "multilabel-indicator" and + len(set(check_array(y, ['csr', 'csc', 'coo']).shape[1] for y in ys)) > 1): + raise ValueError("Multi-label binary indicator input with " + "different numbers of labels") + + # Get the unique set of labels + _unique_labels = _FN_UNIQUE_LABELS.get(label_type, None) + if not _unique_labels: + raise ValueError("Unknown label type: %r" % ys) + + ys_labels = set(chain.from_iterable(_unique_labels(y) for y in ys)) + + # Check that we don't mix string type with number type + if (len(set(isinstance(label, string_types) for label in ys_labels)) > 1): + raise ValueError("Mix of label input types (string and number)") + + return np.array(sorted(ys_labels)) + + +def _is_integral_float(y): + return y.dtype.kind == 'f' and np.all(y.astype(int) == y) + + +def is_label_indicator_matrix(y): + """ Check if ``y`` is in the label indicator matrix format (multilabel). + + Parameters + ---------- + y : numpy array of shape [n_samples] or sequence of sequences + Target values. In the multilabel case the nested sequences can + have variable lengths. + + Returns + ------- + out : bool, + Return ``True``, if ``y`` is in a label indicator matrix format, + else ``False``. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.utils.multiclass import is_label_indicator_matrix + >>> is_label_indicator_matrix([0, 1, 0, 1]) + False + >>> is_label_indicator_matrix([[1], [0, 2], []]) + False + >>> is_label_indicator_matrix(np.array([[1, 0], [0, 0]])) + True + >>> is_label_indicator_matrix(np.array([[1], [0], [0]])) + False + >>> is_label_indicator_matrix(np.array([[1, 0, 0]])) + True + + """ + if hasattr(y, '__array__'): + y = np.asarray(y) + if not (hasattr(y, "shape") and y.ndim == 2 and y.shape[1] > 1): + return False + + if issparse(y): + if isinstance(y, (dok_matrix, lil_matrix)): + y = y.tocsr() + return (len(y.data) == 0 or np.ptp(y.data) == 0 and + (y.dtype.kind in 'biu' or # bool, int, uint + _is_integral_float(np.unique(y.data)))) + else: + labels = np.unique(y) + + return len(labels) < 3 and (y.dtype.kind in 'biu' or # bool, int, uint + _is_integral_float(labels)) + + +def is_sequence_of_sequences(y): + """ Check if ``y`` is in the sequence of sequences format (multilabel). + + This format is DEPRECATED. + + Parameters + ---------- + y : sequence or array. + + Returns + ------- + out : bool, + Return ``True``, if ``y`` is a sequence of sequences else ``False``. + """ + # the explicit check for ndarray is for forward compatibility; future + # versions of Numpy might want to register ndarray as a Sequence + try: + if hasattr(y, '__array__'): + y = np.asarray(y) + out = (not hasattr(y[0], '__array__') and isinstance(y[0], Sequence) + and not isinstance(y[0], string_types)) + except (IndexError, TypeError): + return False + if out: + warnings.warn('Direct support for sequence of sequences multilabel ' + 'representation will be unavailable from version 0.17. ' + 'Use sklearn.preprocessing.MultiLabelBinarizer to ' + 'convert to a label indicator representation.', + DeprecationWarning) + return out + + +def is_multilabel(y): + """ Check if ``y`` is in a multilabel format. + + Parameters + ---------- + y : numpy array of shape [n_samples] or sequence of sequences + Target values. In the multilabel case the nested sequences can + have variable lengths. + + Returns + ------- + out : bool, + Return ``True``, if ``y`` is in a multilabel format, else ```False``. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.utils.multiclass import is_multilabel + >>> is_multilabel([0, 1, 0, 1]) + False + >>> is_multilabel(np.array([[1, 0], [0, 0]])) + True + >>> is_multilabel(np.array([[1], [0], [0]])) + False + >>> is_multilabel(np.array([[1, 0, 0]])) + True + + """ + return is_label_indicator_matrix(y) or is_sequence_of_sequences(y) + + +def type_of_target(y): + """Determine the type of data indicated by target `y` + + Parameters + ---------- + y : array-like + + Returns + ------- + target_type : string + One of: + * 'continuous': `y` is an array-like of floats that are not all + integers, and is 1d or a column vector. + * 'continuous-multioutput': `y` is a 2d array of floats that are + not all integers, and both dimensions are of size > 1. + * 'binary': `y` contains <= 2 discrete values and is 1d or a column + vector. + * 'multiclass': `y` contains more than two discrete values, is not a + sequence of sequences, and is 1d or a column vector. + * 'multiclass-multioutput': `y` is a 2d array that contains more + than two discrete values, is not a sequence of sequences, and both + dimensions are of size > 1. + * 'multilabel-sequences': `y` is a sequence of sequences, a 1d + array-like of objects that are sequences of labels. + * 'multilabel-indicator': `y` is a label indicator matrix, an array + of two dimensions with at least two columns, and at most 2 unique + values. + * 'unknown': `y` is array-like but none of the above, such as a 3d + array, or an array of non-sequence objects. + + Examples + -------- + >>> import numpy as np + >>> type_of_target([0.1, 0.6]) + 'continuous' + >>> type_of_target([1, -1, -1, 1]) + 'binary' + >>> type_of_target(['a', 'b', 'a']) + 'binary' + >>> type_of_target([1, 0, 2]) + 'multiclass' + >>> type_of_target(['a', 'b', 'c']) + 'multiclass' + >>> type_of_target(np.array([[1, 2], [3, 1]])) + 'multiclass-multioutput' + >>> type_of_target(np.array([[1.5, 2.0], [3.0, 1.6]])) + 'continuous-multioutput' + >>> type_of_target(np.array([[0, 1], [1, 1]])) + 'multilabel-indicator' + """ + valid = ((isinstance(y, (Sequence, spmatrix)) or hasattr(y, '__array__')) + and not isinstance(y, string_types)) + if not valid: + raise ValueError('Expected array-like (array or non-string sequence), ' + 'got %r' % y) + + if is_sequence_of_sequences(y): + return 'multilabel-sequences' + elif is_label_indicator_matrix(y): + return 'multilabel-indicator' + + try: + y = np.asarray(y) + except ValueError: + # known to fail in numpy 1.3 for array of arrays + return 'unknown' + if y.ndim > 2 or (y.dtype == object and len(y) and + not isinstance(y.flat[0], string_types)): + return 'unknown' + if y.ndim == 2 and y.shape[1] == 0: + return 'unknown' + elif y.ndim == 2 and y.shape[1] > 1: + suffix = '-multioutput' + else: + # column vector or 1d + suffix = '' + + # check float and contains non-integer float values: + if y.dtype.kind == 'f' and np.any(y != y.astype(int)): + return 'continuous' + suffix + if len(np.unique(y)) <= 2: + assert not suffix, "2d binary array-like should be multilabel" + return 'binary' + else: + return 'multiclass' + suffix + + +def _check_partial_fit_first_call(clf, classes=None): + """Private helper function for factorizing common classes param logic + + Estimators that implement the ``partial_fit`` API need to be provided with + the list of possible classes at the first call to partial_fit. + + Subsequent calls to partial_fit should check that ``classes`` is still + consistent with a previous value of ``clf.classes_`` when provided. + + This function returns True if it detects that this was the first call to + ``partial_fit`` on ``clf``. In that case the ``classes_`` attribute is also + set on ``clf``. + + """ + if getattr(clf, 'classes_', None) is None and classes is None: + raise ValueError("classes must be passed on the first call " + "to partial_fit.") + + elif classes is not None: + if getattr(clf, 'classes_', None) is not None: + if not np.all(clf.classes_ == unique_labels(classes)): + raise ValueError( + "`classes=%r` is not the same as on last call " + "to partial_fit, was: %r" % (classes, clf.classes_)) + + else: + # This is the first call to partial_fit + clf.classes_ = unique_labels(classes) + return True + + # classes is None and clf.classes_ has already previously been set: + # nothing to do + return False + + +def class_distribution(y, sample_weight=None): + """Compute class priors from multioutput-multiclass target data + + Parameters + ---------- + y : array like or sparse matrix of size (n_samples, n_outputs) + The labels for each example. + + sample_weight : array-like of shape = (n_samples,), optional + Sample weights. + + Returns + ------- + classes : list of size n_outputs of arrays of size (n_classes,) + List of classes for each column. + + n_classes : list of integrs of size n_outputs + Number of classes in each column + + class_prior : list of size n_outputs of arrays of size (n_classes,) + Class distribution of each column. + + """ + classes = [] + n_classes = [] + class_prior = [] + + n_samples, n_outputs = y.shape + + if issparse(y): + y = y.tocsc() + y_nnz = np.diff(y.indptr) + + for k in range(n_outputs): + col_nonzero = y.indices[y.indptr[k]:y.indptr[k + 1]] + # separate sample weights for zero and non-zero elements + if sample_weight is not None: + nz_samp_weight = np.asarray(sample_weight)[col_nonzero] + zeros_samp_weight_sum = (np.sum(sample_weight) - + np.sum(nz_samp_weight)) + else: + nz_samp_weight = None + zeros_samp_weight_sum = y.shape[0] - y_nnz[k] + + classes_k, y_k = np.unique(y.data[y.indptr[k]:y.indptr[k + 1]], + return_inverse=True) + class_prior_k = bincount(y_k, weights=nz_samp_weight) + + # An explicit zero was found, combine its wieght with the wieght + # of the implicit zeros + if 0 in classes_k: + class_prior_k[classes_k == 0] += zeros_samp_weight_sum + + # If an there is an implict zero and it is not in classes and + # class_prior, make an entry for it + if 0 not in classes_k and y_nnz[k] < y.shape[0]: + classes_k = np.insert(classes_k, 0, 0) + class_prior_k = np.insert(class_prior_k, 0, + zeros_samp_weight_sum) + + classes.append(classes_k) + n_classes.append(classes_k.shape[0]) + class_prior.append(class_prior_k / class_prior_k.sum()) + else: + for k in range(n_outputs): + classes_k, y_k = np.unique(y[:, k], return_inverse=True) + classes.append(classes_k) + n_classes.append(classes_k.shape[0]) + class_prior_k = bincount(y_k, weights=sample_weight) + class_prior.append(class_prior_k / class_prior_k.sum()) + + return (classes, n_classes, class_prior) diff --git a/sklearn/utils/murmurhash.c b/sklearn/utils/murmurhash.c index c1d6aacf31281..772d0199e3966 100644 --- a/sklearn/utils/murmurhash.c +++ b/sklearn/utils/murmurhash.c @@ -1,16 +1,16 @@ -/* Generated by Cython 0.15.1 on Wed Jan 18 12:16:50 2012 */ +/* Generated by Cython 0.17.4 on Mon Jan 7 18:14:54 2013 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. #else - #include /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -22,36 +22,47 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - -#if PY_VERSION_HEX < 0x02040000 - #define METH_COEXIST 0 - #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) - #define PyDict_Contains(d,o) PySequence_Contains(d,o) +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 #endif - #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -59,7 +70,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -73,7 +83,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -83,24 +92,44 @@ #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -108,7 +137,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -127,7 +155,6 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -135,9 +162,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -154,11 +179,9 @@ #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - #if PY_VERSION_HEX < 0x03020000 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong @@ -167,16 +190,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -195,11 +208,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -209,7 +220,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -218,6 +228,15 @@ #define __Pyx_DOCSTR(n) (n) #endif + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" @@ -236,7 +255,7 @@ #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" -#include "MurmurHash3.h" +#include "src/MurmurHash3.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -267,7 +286,7 @@ # else # define CYTHON_UNUSED # endif -# elif defined(__ICC) || defined(__INTEL_COMPILER) +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED @@ -291,8 +310,12 @@ static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) - +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #ifdef __GNUC__ /* Test for GCC > 2.95 */ @@ -317,7 +340,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -327,7 +349,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -335,18 +356,54 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { "murmurhash.pyx", "numpy.pxd", + "type.pxd", }; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + -/* "numpy.pxd":719 +/* "numpy.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -355,7 +412,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "numpy.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -364,7 +421,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "numpy.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -373,7 +430,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "numpy.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -382,7 +439,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "numpy.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -391,7 +448,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "numpy.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -400,7 +457,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "numpy.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -409,7 +466,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "numpy.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -418,7 +475,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "numpy.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -427,7 +484,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "numpy.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -436,7 +493,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "numpy.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -445,7 +502,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "numpy.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -454,7 +511,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "numpy.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -463,7 +520,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "numpy.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -472,7 +529,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "numpy.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -481,7 +538,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "numpy.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -490,7 +547,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "numpy.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -499,7 +556,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "numpy.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -508,7 +565,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "numpy.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -517,7 +574,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "numpy.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -526,7 +583,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "numpy.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -534,7 +591,6 @@ typedef npy_double __pyx_t_5numpy_double_t; * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; - #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -555,9 +611,10 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ -/* "numpy.pxd":758 +/* "numpy.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -566,7 +623,7 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "numpy.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -575,7 +632,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "numpy.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -584,7 +641,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "numpy.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -592,12 +649,9 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; - - #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -610,8 +664,21 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -622,7 +689,7 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -633,70 +700,69 @@ typedef npy_cdouble __pyx_t_5numpy_complex_t; #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); /*proto*/ -/* Run-time type information about structs used with buffers */ -struct __Pyx_StructField_; - -typedef struct { - const char* name; /* for error messages only */ - struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ -} __Pyx_TypeInfo; - -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; - -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; - - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ -#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) +#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + #if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); -static void __Pyx_ReleaseBuffer(Py_buffer *view); + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); #else -#define __Pyx_GetBuffer PyObject_GetBuffer -#define __Pyx_ReleaseBuffer PyBuffer_Release + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release #endif -Py_ssize_t __Pyx_zeros[] = {0}; -Py_ssize_t __Pyx_minusones[] = {-1}; + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ @@ -720,7 +786,6 @@ static CYTHON_INLINE npy_int32 __Pyx_PyInt_from_py_npy_int32(PyObject *); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - #if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) @@ -846,15 +911,38 @@ static int __Pyx_check_binary_version(void); static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig); /*proto*/ -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ @@ -863,6 +951,11 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -873,16 +966,7 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ - -/* Module declarations from 'cython.cython.view' */ /* Module declarations from 'cython' */ @@ -893,8 +977,8 @@ static __pyx_t_5numpy_uint32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_ static __pyx_t_5numpy_int32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32(PyObject *, unsigned int, int __pyx_skip_dispatch); /*proto*/ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_u32(PyArrayObject *, unsigned int, int __pyx_skip_dispatch); /*proto*/ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_s32(PyArrayObject *, unsigned int, int __pyx_skip_dispatch); /*proto*/ -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t = { "int32_t", NULL, sizeof(__pyx_t_5numpy_int32_t), 'I' }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_uint32_t = { "uint32_t", NULL, sizeof(__pyx_t_5numpy_uint32_t), 'U' }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t = { "int32_t", NULL, sizeof(__pyx_t_5numpy_int32_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_int32_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_int32_t), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_uint32_t = { "uint32_t", NULL, sizeof(__pyx_t_5numpy_uint32_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_uint32_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_uint32_t), 0 }; #define __Pyx_MODULE_NAME "sklearn.utils.murmurhash" int __pyx_module_is_main_sklearn__utils__murmurhash = 0; @@ -903,6 +987,15 @@ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_TypeError; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_key, unsigned int __pyx_v_seed); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_2murmurhash3_int_s32(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_key, unsigned int __pyx_v_seed); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_u32(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_key, unsigned int __pyx_v_seed); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_bytes_s32(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_key, unsigned int __pyx_v_seed); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_8murmurhash3_bytes_array_u32(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_key, unsigned int __pyx_v_seed); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_10murmurhash3_bytes_array_s32(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_key, unsigned int __pyx_v_seed); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_12murmurhash3_32(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_key, PyObject *__pyx_v_seed, PyObject *__pyx_v_positive); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static char __pyx_k_2[] = "utf-8"; static char __pyx_k_5[] = "key.dtype should be int32, got %s"; static char __pyx_k_6[] = "key %r with type %s is not supported. Explicit conversion to bytes is required"; @@ -913,7 +1006,8 @@ static char __pyx_k_13[] = "unknown dtype code in numpy.pxd (%d)"; static char __pyx_k_14[] = "Format string allocated too short, see comment in numpy.pxd"; static char __pyx_k_17[] = "Format string allocated too short."; static char __pyx_k_19[] = "Cython wrapper for MurmurHash3 non-cryptographic hash function\n\nMurmurHash is an extensively tested and very fast hash function that has\ngood distribution properties suitable for machine learning use cases\nsuch as feature hashing and random projections.\n\nThe original C++ code by Austin Appleby is released the public domain\nand can be found here:\n\n https://code.google.com/p/smhasher/\n\n"; -static char __pyx_k_20[] = "sklearn.utils.murmurhash"; +static char __pyx_k_22[] = "/scratch/apps/src/scikit-learn/sklearn/utils/murmurhash.pyx"; +static char __pyx_k_23[] = "sklearn.utils.murmurhash"; static char __pyx_k__B[] = "B"; static char __pyx_k__H[] = "H"; static char __pyx_k__I[] = "I"; @@ -957,7 +1051,8 @@ static PyObject *__pyx_kp_u_13; static PyObject *__pyx_kp_u_14; static PyObject *__pyx_kp_u_17; static PyObject *__pyx_kp_s_2; -static PyObject *__pyx_n_s_20; +static PyObject *__pyx_kp_s_22; +static PyObject *__pyx_n_s_23; static PyObject *__pyx_kp_s_5; static PyObject *__pyx_kp_s_6; static PyObject *__pyx_kp_u_7; @@ -994,8 +1089,10 @@ static PyObject *__pyx_k_tuple_12; static PyObject *__pyx_k_tuple_15; static PyObject *__pyx_k_tuple_16; static PyObject *__pyx_k_tuple_18; +static PyObject *__pyx_k_tuple_20; +static PyObject *__pyx_k_codeobj_21; -/* "sklearn/utils/murmurhash.pyx":22 +/* "sklearn/utils/murmurhash.pyx":29 * * * cpdef np.uint32_t murmurhash3_int_u32(int key, unsigned int seed): # <<<<<<<<<<<<<< @@ -1003,14 +1100,14 @@ static PyObject *__pyx_k_tuple_18; * cdef np.uint32_t out */ -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static __pyx_t_5numpy_uint32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(int __pyx_v_key, unsigned int __pyx_v_seed, int __pyx_skip_dispatch) { +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_1murmurhash3_int_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static __pyx_t_5numpy_uint32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(int __pyx_v_key, unsigned int __pyx_v_seed, CYTHON_UNUSED int __pyx_skip_dispatch) { __pyx_t_5numpy_uint32_t __pyx_v_out; __pyx_t_5numpy_uint32_t __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("murmurhash3_int_u32"); + __Pyx_RefNannySetupContext("murmurhash3_int_u32", 0); - /* "sklearn/utils/murmurhash.pyx":25 + /* "sklearn/utils/murmurhash.pyx":32 * """Compute the 32bit murmurhash3 of a int key at seed.""" * cdef np.uint32_t out * MurmurHash3_x86_32(&key, sizeof(int), seed, &out) # <<<<<<<<<<<<<< @@ -1019,7 +1116,7 @@ static __pyx_t_5numpy_uint32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_ */ MurmurHash3_x86_32((&__pyx_v_key), (sizeof(int)), __pyx_v_seed, (&__pyx_v_out)); - /* "sklearn/utils/murmurhash.pyx":26 + /* "sklearn/utils/murmurhash.pyx":33 * cdef np.uint32_t out * MurmurHash3_x86_32(&key, sizeof(int), seed, &out) * return out # <<<<<<<<<<<<<< @@ -1035,53 +1132,40 @@ static __pyx_t_5numpy_uint32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_ return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":22 - * - * - * cpdef np.uint32_t murmurhash3_int_u32(int key, unsigned int seed): # <<<<<<<<<<<<<< - * """Compute the 32bit murmurhash3 of a int key at seed.""" - * cdef np.uint32_t out - */ - -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_1murmurhash3_int_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_7sklearn_5utils_10murmurhash_murmurhash3_int_u32[] = "Compute the 32bit murmurhash3 of a int key at seed."; -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_1murmurhash3_int_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_key; unsigned int __pyx_v_seed; - PyObject *__pyx_r = NULL; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; - __Pyx_RefNannySetupContext("murmurhash3_int_u32"); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("murmurhash3_int_u32 (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("murmurhash3_int_u32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_int_u32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "murmurhash3_int_u32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "murmurhash3_int_u32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; @@ -1089,19 +1173,40 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(PyObj values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } - __pyx_v_key = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_key == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_key = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_key == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("murmurhash3_int_u32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_int_u32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.utils.murmurhash.murmurhash3_int_u32", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(__pyx_self, __pyx_v_key, __pyx_v_seed); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/murmurhash.pyx":29 + * + * + * cpdef np.uint32_t murmurhash3_int_u32(int key, unsigned int seed): # <<<<<<<<<<<<<< + * """Compute the 32bit murmurhash3 of a int key at seed.""" + * cdef np.uint32_t out + */ + +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_key, unsigned int __pyx_v_seed) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("murmurhash3_int_u32", 0); __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_to_py_npy_uint32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_to_py_npy_uint32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -1119,7 +1224,7 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(PyObj return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":29 +/* "sklearn/utils/murmurhash.pyx":36 * * * cpdef np.int32_t murmurhash3_int_s32(int key, unsigned int seed): # <<<<<<<<<<<<<< @@ -1127,14 +1232,14 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(PyObj * cdef np.int32_t out */ -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_1murmurhash3_int_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static __pyx_t_5numpy_int32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_s32(int __pyx_v_key, unsigned int __pyx_v_seed, int __pyx_skip_dispatch) { +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_3murmurhash3_int_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static __pyx_t_5numpy_int32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_s32(int __pyx_v_key, unsigned int __pyx_v_seed, CYTHON_UNUSED int __pyx_skip_dispatch) { __pyx_t_5numpy_int32_t __pyx_v_out; __pyx_t_5numpy_int32_t __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("murmurhash3_int_s32"); + __Pyx_RefNannySetupContext("murmurhash3_int_s32", 0); - /* "sklearn/utils/murmurhash.pyx":32 + /* "sklearn/utils/murmurhash.pyx":39 * """Compute the 32bit murmurhash3 of a int key at seed.""" * cdef np.int32_t out * MurmurHash3_x86_32(&key, sizeof(int), seed, &out) # <<<<<<<<<<<<<< @@ -1143,7 +1248,7 @@ static __pyx_t_5numpy_int32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_i */ MurmurHash3_x86_32((&__pyx_v_key), (sizeof(int)), __pyx_v_seed, (&__pyx_v_out)); - /* "sklearn/utils/murmurhash.pyx":33 + /* "sklearn/utils/murmurhash.pyx":40 * cdef np.int32_t out * MurmurHash3_x86_32(&key, sizeof(int), seed, &out) * return out # <<<<<<<<<<<<<< @@ -1159,53 +1264,40 @@ static __pyx_t_5numpy_int32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_i return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":29 - * - * - * cpdef np.int32_t murmurhash3_int_s32(int key, unsigned int seed): # <<<<<<<<<<<<<< - * """Compute the 32bit murmurhash3 of a int key at seed.""" - * cdef np.int32_t out - */ - -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_1murmurhash3_int_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_5utils_10murmurhash_1murmurhash3_int_s32[] = "Compute the 32bit murmurhash3 of a int key at seed."; -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_1murmurhash3_int_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_3murmurhash3_int_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_10murmurhash_2murmurhash3_int_s32[] = "Compute the 32bit murmurhash3 of a int key at seed."; +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_3murmurhash3_int_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_key; unsigned int __pyx_v_seed; - PyObject *__pyx_r = NULL; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; - __Pyx_RefNannySetupContext("murmurhash3_int_s32"); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("murmurhash3_int_s32 (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("murmurhash3_int_s32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_int_s32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "murmurhash3_int_s32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "murmurhash3_int_s32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; @@ -1213,19 +1305,40 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_1murmurhash3_int_s32(PyOb values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } - __pyx_v_key = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_key == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_key = __Pyx_PyInt_AsInt(values[0]); if (unlikely((__pyx_v_key == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("murmurhash3_int_s32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_int_s32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.utils.murmurhash.murmurhash3_int_s32", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_10murmurhash_2murmurhash3_int_s32(__pyx_self, __pyx_v_key, __pyx_v_seed); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/murmurhash.pyx":36 + * + * + * cpdef np.int32_t murmurhash3_int_s32(int key, unsigned int seed): # <<<<<<<<<<<<<< + * """Compute the 32bit murmurhash3 of a int key at seed.""" + * cdef np.int32_t out + */ + +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_2murmurhash3_int_s32(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_key, unsigned int __pyx_v_seed) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("murmurhash3_int_s32", 0); __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_s32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_s32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -1243,7 +1356,7 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_1murmurhash3_int_s32(PyOb return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":36 +/* "sklearn/utils/murmurhash.pyx":43 * * * cpdef np.uint32_t murmurhash3_bytes_u32(bytes key, unsigned int seed): # <<<<<<<<<<<<<< @@ -1251,8 +1364,8 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_1murmurhash3_int_s32(PyOb * cdef np.uint32_t out */ -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_2murmurhash3_bytes_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static __pyx_t_5numpy_uint32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_u32(PyObject *__pyx_v_key, unsigned int __pyx_v_seed, int __pyx_skip_dispatch) { +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static __pyx_t_5numpy_uint32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_u32(PyObject *__pyx_v_key, unsigned int __pyx_v_seed, CYTHON_UNUSED int __pyx_skip_dispatch) { __pyx_t_5numpy_uint32_t __pyx_v_out; __pyx_t_5numpy_uint32_t __pyx_r; __Pyx_RefNannyDeclarations @@ -1261,23 +1374,24 @@ static __pyx_t_5numpy_uint32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("murmurhash3_bytes_u32"); + __Pyx_RefNannySetupContext("murmurhash3_bytes_u32", 0); - /* "sklearn/utils/murmurhash.pyx":39 + /* "sklearn/utils/murmurhash.pyx":46 * """Compute the 32bit murmurhash3 of a bytes key at seed.""" * cdef np.uint32_t out * MurmurHash3_x86_32( key, len(key), seed, &out) # <<<<<<<<<<<<<< * return out * */ - __pyx_t_1 = PyBytes_AsString(((PyObject *)__pyx_v_key)); if (unlikely((!__pyx_t_1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyBytes_AsString(((PyObject *)__pyx_v_key)); if (unlikely((!__pyx_t_1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(((PyObject *)__pyx_v_key) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_2 = PyBytes_GET_SIZE(((PyObject *)__pyx_v_key)); + __pyx_t_2 = PyBytes_GET_SIZE(((PyObject *)__pyx_v_key)); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} MurmurHash3_x86_32(((char *)__pyx_t_1), __pyx_t_2, __pyx_v_seed, (&__pyx_v_out)); - /* "sklearn/utils/murmurhash.pyx":40 + /* "sklearn/utils/murmurhash.pyx":47 * cdef np.uint32_t out * MurmurHash3_x86_32( key, len(key), seed, &out) * return out # <<<<<<<<<<<<<< @@ -1297,53 +1411,40 @@ static __pyx_t_5numpy_uint32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_ return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":36 - * - * - * cpdef np.uint32_t murmurhash3_bytes_u32(bytes key, unsigned int seed): # <<<<<<<<<<<<<< - * """Compute the 32bit murmurhash3 of a bytes key at seed.""" - * cdef np.uint32_t out - */ - -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_2murmurhash3_bytes_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_5utils_10murmurhash_2murmurhash3_bytes_u32[] = "Compute the 32bit murmurhash3 of a bytes key at seed."; -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_2murmurhash3_bytes_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_u32[] = "Compute the 32bit murmurhash3 of a bytes key at seed."; +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_key = 0; unsigned int __pyx_v_seed; - PyObject *__pyx_r = NULL; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; - __Pyx_RefNannySetupContext("murmurhash3_bytes_u32"); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("murmurhash3_bytes_u32 (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_u32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_u32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "murmurhash3_bytes_u32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "murmurhash3_bytes_u32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; @@ -1352,19 +1453,44 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_2murmurhash3_bytes_u32(Py values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_key = ((PyObject*)values[0]); - __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_u32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_u32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.utils.murmurhash.murmurhash3_bytes_u32", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_key), (&PyBytes_Type), 1, "key", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_key), (&PyBytes_Type), 1, "key", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_u32(__pyx_self, __pyx_v_key, __pyx_v_seed); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/murmurhash.pyx":43 + * + * + * cpdef np.uint32_t murmurhash3_bytes_u32(bytes key, unsigned int seed): # <<<<<<<<<<<<<< + * """Compute the 32bit murmurhash3 of a bytes key at seed.""" + * cdef np.uint32_t out + */ + +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_u32(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_key, unsigned int __pyx_v_seed) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("murmurhash3_bytes_u32", 0); __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_to_py_npy_uint32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_u32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_to_py_npy_uint32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_u32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -1382,7 +1508,7 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_2murmurhash3_bytes_u32(Py return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":43 +/* "sklearn/utils/murmurhash.pyx":50 * * * cpdef np.int32_t murmurhash3_bytes_s32(bytes key, unsigned int seed): # <<<<<<<<<<<<<< @@ -1390,8 +1516,8 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_2murmurhash3_bytes_u32(Py * cdef np.int32_t out */ -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_3murmurhash3_bytes_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static __pyx_t_5numpy_int32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32(PyObject *__pyx_v_key, unsigned int __pyx_v_seed, int __pyx_skip_dispatch) { +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_7murmurhash3_bytes_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static __pyx_t_5numpy_int32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32(PyObject *__pyx_v_key, unsigned int __pyx_v_seed, CYTHON_UNUSED int __pyx_skip_dispatch) { __pyx_t_5numpy_int32_t __pyx_v_out; __pyx_t_5numpy_int32_t __pyx_r; __Pyx_RefNannyDeclarations @@ -1400,23 +1526,24 @@ static __pyx_t_5numpy_int32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_b int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("murmurhash3_bytes_s32"); + __Pyx_RefNannySetupContext("murmurhash3_bytes_s32", 0); - /* "sklearn/utils/murmurhash.pyx":46 + /* "sklearn/utils/murmurhash.pyx":53 * """Compute the 32bit murmurhash3 of a bytes key at seed.""" * cdef np.int32_t out * MurmurHash3_x86_32( key, len(key), seed, &out) # <<<<<<<<<<<<<< * return out * */ - __pyx_t_1 = PyBytes_AsString(((PyObject *)__pyx_v_key)); if (unlikely((!__pyx_t_1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyBytes_AsString(((PyObject *)__pyx_v_key)); if (unlikely((!__pyx_t_1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(((PyObject *)__pyx_v_key) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_2 = PyBytes_GET_SIZE(((PyObject *)__pyx_v_key)); + __pyx_t_2 = PyBytes_GET_SIZE(((PyObject *)__pyx_v_key)); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} MurmurHash3_x86_32(((char *)__pyx_t_1), __pyx_t_2, __pyx_v_seed, (&__pyx_v_out)); - /* "sklearn/utils/murmurhash.pyx":47 + /* "sklearn/utils/murmurhash.pyx":54 * cdef np.int32_t out * MurmurHash3_x86_32( key, len(key), seed, &out) * return out # <<<<<<<<<<<<<< @@ -1436,53 +1563,40 @@ static __pyx_t_5numpy_int32_t __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_b return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":43 - * - * - * cpdef np.int32_t murmurhash3_bytes_s32(bytes key, unsigned int seed): # <<<<<<<<<<<<<< - * """Compute the 32bit murmurhash3 of a bytes key at seed.""" - * cdef np.int32_t out - */ - -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_3murmurhash3_bytes_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_5utils_10murmurhash_3murmurhash3_bytes_s32[] = "Compute the 32bit murmurhash3 of a bytes key at seed."; -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_3murmurhash3_bytes_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_7murmurhash3_bytes_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_10murmurhash_6murmurhash3_bytes_s32[] = "Compute the 32bit murmurhash3 of a bytes key at seed."; +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_7murmurhash3_bytes_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_key = 0; unsigned int __pyx_v_seed; - PyObject *__pyx_r = NULL; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; - __Pyx_RefNannySetupContext("murmurhash3_bytes_s32"); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("murmurhash3_bytes_s32 (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_s32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_s32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "murmurhash3_bytes_s32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "murmurhash3_bytes_s32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; @@ -1491,19 +1605,44 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_3murmurhash3_bytes_s32(Py values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_key = ((PyObject*)values[0]); - __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_s32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_s32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.utils.murmurhash.murmurhash3_bytes_s32", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_key), (&PyBytes_Type), 1, "key", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_key), (&PyBytes_Type), 1, "key", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_bytes_s32(__pyx_self, __pyx_v_key, __pyx_v_seed); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/murmurhash.pyx":50 + * + * + * cpdef np.int32_t murmurhash3_bytes_s32(bytes key, unsigned int seed): # <<<<<<<<<<<<<< + * """Compute the 32bit murmurhash3 of a bytes key at seed.""" + * cdef np.int32_t out + */ + +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_bytes_s32(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_key, unsigned int __pyx_v_seed) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("murmurhash3_bytes_s32", 0); __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -1521,7 +1660,7 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_3murmurhash3_bytes_s32(Py return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":51 +/* "sklearn/utils/murmurhash.pyx":58 * * @cython.boundscheck(False) * cpdef np.ndarray[np.uint32_t, ndim=1] murmurhash3_bytes_array_u32( # <<<<<<<<<<<<<< @@ -1529,16 +1668,14 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_3murmurhash3_bytes_s32(Py * """Compute 32bit murmurhash3 hashes of a key int array at seed.""" */ -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_array_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_u32(PyArrayObject *__pyx_v_key, unsigned int __pyx_v_seed, int __pyx_skip_dispatch) { +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_9murmurhash3_bytes_array_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_u32(PyArrayObject *__pyx_v_key, unsigned int __pyx_v_seed, CYTHON_UNUSED int __pyx_skip_dispatch) { PyArrayObject *__pyx_v_out = 0; Py_ssize_t __pyx_v_i; - Py_buffer __pyx_bstruct_key; - Py_ssize_t __pyx_bstride_0_key = 0; - Py_ssize_t __pyx_bshape_0_key = 0; - Py_buffer __pyx_bstruct_out; - Py_ssize_t __pyx_bstride_0_out = 0; - Py_ssize_t __pyx_bshape_0_out = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_key; + __Pyx_Buffer __pyx_pybuffer_key; + __Pyx_LocalBuf_ND __pyx_pybuffernd_out; + __Pyx_Buffer __pyx_pybuffer_out; PyArrayObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -1553,63 +1690,67 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_arr int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("murmurhash3_bytes_array_u32"); - __pyx_bstruct_out.buf = NULL; - __pyx_bstruct_key.buf = NULL; + __Pyx_RefNannySetupContext("murmurhash3_bytes_array_u32", 0); + __pyx_pybuffer_out.pybuffer.buf = NULL; + __pyx_pybuffer_out.refcount = 0; + __pyx_pybuffernd_out.data = NULL; + __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; + __pyx_pybuffer_key.pybuffer.buf = NULL; + __pyx_pybuffer_key.refcount = 0; + __pyx_pybuffernd_key.data = NULL; + __pyx_pybuffernd_key.rcbuffer = &__pyx_pybuffer_key; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_key, (PyObject*)__pyx_v_key, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_key.rcbuffer->pybuffer, (PyObject*)__pyx_v_key, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_key = __pyx_bstruct_key.strides[0]; - __pyx_bshape_0_key = __pyx_bstruct_key.shape[0]; + __pyx_pybuffernd_key.diminfo[0].strides = __pyx_pybuffernd_key.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_key.diminfo[0].shape = __pyx_pybuffernd_key.rcbuffer->pybuffer.shape[0]; - /* "sklearn/utils/murmurhash.pyx":55 + /* "sklearn/utils/murmurhash.pyx":62 * """Compute 32bit murmurhash3 hashes of a key int array at seed.""" - * # TODO make it possible to pass preallocated ouput array + * # TODO make it possible to pass preallocated output array * cdef np.ndarray[np.uint32_t, ndim=1] out = np.zeros(key.size, np.uint32) # <<<<<<<<<<<<<< * cdef Py_ssize_t i * for i in range(key.shape[0]): */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_key), __pyx_n_s__size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_key), __pyx_n_s__size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__uint32); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__uint32); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_1 = 0; __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_5 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_out, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_5numpy_uint32_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_out.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_out = __pyx_bstruct_out.strides[0]; - __pyx_bshape_0_out = __pyx_bstruct_out.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_5numpy_uint32_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_out.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; } } __pyx_t_5 = 0; __pyx_v_out = ((PyArrayObject *)__pyx_t_4); __pyx_t_4 = 0; - /* "sklearn/utils/murmurhash.pyx":57 + /* "sklearn/utils/murmurhash.pyx":64 * cdef np.ndarray[np.uint32_t, ndim=1] out = np.zeros(key.size, np.uint32) * cdef Py_ssize_t i * for i in range(key.shape[0]): # <<<<<<<<<<<<<< @@ -1620,7 +1761,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_arr for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { __pyx_v_i = __pyx_t_7; - /* "sklearn/utils/murmurhash.pyx":58 + /* "sklearn/utils/murmurhash.pyx":65 * cdef Py_ssize_t i * for i in range(key.shape[0]): * out[i] = murmurhash3_int_u32(key[i], seed) # <<<<<<<<<<<<<< @@ -1628,13 +1769,13 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_arr * */ __pyx_t_8 = __pyx_v_i; - if (__pyx_t_8 < 0) __pyx_t_8 += __pyx_bshape_0_key; + if (__pyx_t_8 < 0) __pyx_t_8 += __pyx_pybuffernd_key.diminfo[0].shape; __pyx_t_9 = __pyx_v_i; - if (__pyx_t_9 < 0) __pyx_t_9 += __pyx_bshape_0_out; - *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_uint32_t *, __pyx_bstruct_out.buf, __pyx_t_9, __pyx_bstride_0_out) = __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_u32((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int32_t *, __pyx_bstruct_key.buf, __pyx_t_8, __pyx_bstride_0_key)), __pyx_v_seed, 0); + if (__pyx_t_9 < 0) __pyx_t_9 += __pyx_pybuffernd_out.diminfo[0].shape; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_uint32_t *, __pyx_pybuffernd_out.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_out.diminfo[0].strides) = __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_u32((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int32_t *, __pyx_pybuffernd_key.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_key.diminfo[0].strides)), __pyx_v_seed, 0); } - /* "sklearn/utils/murmurhash.pyx":59 + /* "sklearn/utils/murmurhash.pyx":66 * for i in range(key.shape[0]): * out[i] = murmurhash3_int_u32(key[i], seed) * return out # <<<<<<<<<<<<<< @@ -1655,15 +1796,15 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_arr __Pyx_XDECREF(__pyx_t_4); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_key); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_out); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_key.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.utils.murmurhash.murmurhash3_bytes_array_u32", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_key); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_out); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_key.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_out); __Pyx_XGIVEREF((PyObject *)__pyx_r); @@ -1671,56 +1812,40 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_arr return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":51 - * - * @cython.boundscheck(False) - * cpdef np.ndarray[np.uint32_t, ndim=1] murmurhash3_bytes_array_u32( # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t] key, unsigned int seed): - * """Compute 32bit murmurhash3 hashes of a key int array at seed.""" - */ - -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_array_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_array_u32[] = "Compute 32bit murmurhash3 hashes of a key int array at seed."; -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_array_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_9murmurhash3_bytes_array_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_10murmurhash_8murmurhash3_bytes_array_u32[] = "Compute 32bit murmurhash3 hashes of a key int array at seed."; +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_9murmurhash3_bytes_array_u32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_key = 0; unsigned int __pyx_v_seed; - Py_buffer __pyx_bstruct_key; - Py_ssize_t __pyx_bstride_0_key = 0; - Py_ssize_t __pyx_bshape_0_key = 0; - PyObject *__pyx_r = NULL; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; - __Pyx_RefNannySetupContext("murmurhash3_bytes_array_u32"); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("murmurhash3_bytes_array_u32 (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_array_u32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_array_u32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "murmurhash3_bytes_array_u32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "murmurhash3_bytes_array_u32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; @@ -1729,26 +1854,55 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_array_ values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_key = ((PyArrayObject *)values[0]); - __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_array_u32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_array_u32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.utils.murmurhash.murmurhash3_bytes_array_u32", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_key.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_key), __pyx_ptype_5numpy_ndarray, 1, "key", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_key), __pyx_ptype_5numpy_ndarray, 1, "key", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_10murmurhash_8murmurhash3_bytes_array_u32(__pyx_self, __pyx_v_key, __pyx_v_seed); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/murmurhash.pyx":58 + * + * @cython.boundscheck(False) + * cpdef np.ndarray[np.uint32_t, ndim=1] murmurhash3_bytes_array_u32( # <<<<<<<<<<<<<< + * np.ndarray[np.int32_t] key, unsigned int seed): + * """Compute 32bit murmurhash3 hashes of a key int array at seed.""" + */ + +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_8murmurhash3_bytes_array_u32(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_key, unsigned int __pyx_v_seed) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_key; + __Pyx_Buffer __pyx_pybuffer_key; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("murmurhash3_bytes_array_u32", 0); + __pyx_pybuffer_key.pybuffer.buf = NULL; + __pyx_pybuffer_key.refcount = 0; + __pyx_pybuffernd_key.data = NULL; + __pyx_pybuffernd_key.rcbuffer = &__pyx_pybuffer_key; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_key, (PyObject*)__pyx_v_key, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_key.rcbuffer->pybuffer, (PyObject*)__pyx_v_key, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_key = __pyx_bstruct_key.strides[0]; - __pyx_bshape_0_key = __pyx_bstruct_key.shape[0]; + __pyx_pybuffernd_key.diminfo[0].strides = __pyx_pybuffernd_key.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_key.diminfo[0].shape = __pyx_pybuffernd_key.rcbuffer->pybuffer.shape[0]; __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_u32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_u32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -1760,20 +1914,20 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_array_ __Pyx_XDECREF(__pyx_t_1); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_key); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_key.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.utils.murmurhash.murmurhash3_bytes_array_u32", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_key); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_key.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":63 +/* "sklearn/utils/murmurhash.pyx":70 * * @cython.boundscheck(False) * cpdef np.ndarray[np.int32_t, ndim=1] murmurhash3_bytes_array_s32( # <<<<<<<<<<<<<< @@ -1781,16 +1935,14 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_array_ * """Compute 32bit murmurhash3 hashes of a key int array at seed.""" */ -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_array_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_s32(PyArrayObject *__pyx_v_key, unsigned int __pyx_v_seed, int __pyx_skip_dispatch) { +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_11murmurhash3_bytes_array_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_s32(PyArrayObject *__pyx_v_key, unsigned int __pyx_v_seed, CYTHON_UNUSED int __pyx_skip_dispatch) { PyArrayObject *__pyx_v_out = 0; Py_ssize_t __pyx_v_i; - Py_buffer __pyx_bstruct_key; - Py_ssize_t __pyx_bstride_0_key = 0; - Py_ssize_t __pyx_bshape_0_key = 0; - Py_buffer __pyx_bstruct_out; - Py_ssize_t __pyx_bstride_0_out = 0; - Py_ssize_t __pyx_bshape_0_out = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_key; + __Pyx_Buffer __pyx_pybuffer_key; + __Pyx_LocalBuf_ND __pyx_pybuffernd_out; + __Pyx_Buffer __pyx_pybuffer_out; PyArrayObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -1805,63 +1957,67 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_arr int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("murmurhash3_bytes_array_s32"); - __pyx_bstruct_out.buf = NULL; - __pyx_bstruct_key.buf = NULL; + __Pyx_RefNannySetupContext("murmurhash3_bytes_array_s32", 0); + __pyx_pybuffer_out.pybuffer.buf = NULL; + __pyx_pybuffer_out.refcount = 0; + __pyx_pybuffernd_out.data = NULL; + __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; + __pyx_pybuffer_key.pybuffer.buf = NULL; + __pyx_pybuffer_key.refcount = 0; + __pyx_pybuffernd_key.data = NULL; + __pyx_pybuffernd_key.rcbuffer = &__pyx_pybuffer_key; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_key, (PyObject*)__pyx_v_key, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_key.rcbuffer->pybuffer, (PyObject*)__pyx_v_key, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_key = __pyx_bstruct_key.strides[0]; - __pyx_bshape_0_key = __pyx_bstruct_key.shape[0]; + __pyx_pybuffernd_key.diminfo[0].strides = __pyx_pybuffernd_key.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_key.diminfo[0].shape = __pyx_pybuffernd_key.rcbuffer->pybuffer.shape[0]; - /* "sklearn/utils/murmurhash.pyx":67 + /* "sklearn/utils/murmurhash.pyx":74 * """Compute 32bit murmurhash3 hashes of a key int array at seed.""" - * # TODO make it possible to pass preallocated ouput array + * # TODO make it possible to pass preallocated output array * cdef np.ndarray[np.int32_t, ndim=1] out = np.zeros(key.size, np.int32) # <<<<<<<<<<<<<< * cdef Py_ssize_t i * for i in range(key.shape[0]): */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_key), __pyx_n_s__size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_key), __pyx_n_s__size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__int32); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__int32); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_1 = 0; __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_5 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_out, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { - __pyx_v_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_out.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_out = __pyx_bstruct_out.strides[0]; - __pyx_bshape_0_out = __pyx_bstruct_out.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_out = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_out.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; } } __pyx_t_5 = 0; __pyx_v_out = ((PyArrayObject *)__pyx_t_4); __pyx_t_4 = 0; - /* "sklearn/utils/murmurhash.pyx":69 + /* "sklearn/utils/murmurhash.pyx":76 * cdef np.ndarray[np.int32_t, ndim=1] out = np.zeros(key.size, np.int32) * cdef Py_ssize_t i * for i in range(key.shape[0]): # <<<<<<<<<<<<<< @@ -1872,7 +2028,7 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_arr for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { __pyx_v_i = __pyx_t_7; - /* "sklearn/utils/murmurhash.pyx":70 + /* "sklearn/utils/murmurhash.pyx":77 * cdef Py_ssize_t i * for i in range(key.shape[0]): * out[i] = murmurhash3_int_s32(key[i], seed) # <<<<<<<<<<<<<< @@ -1880,13 +2036,13 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_arr * */ __pyx_t_8 = __pyx_v_i; - if (__pyx_t_8 < 0) __pyx_t_8 += __pyx_bshape_0_key; + if (__pyx_t_8 < 0) __pyx_t_8 += __pyx_pybuffernd_key.diminfo[0].shape; __pyx_t_9 = __pyx_v_i; - if (__pyx_t_9 < 0) __pyx_t_9 += __pyx_bshape_0_out; - *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int32_t *, __pyx_bstruct_out.buf, __pyx_t_9, __pyx_bstride_0_out) = __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_s32((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int32_t *, __pyx_bstruct_key.buf, __pyx_t_8, __pyx_bstride_0_key)), __pyx_v_seed, 0); + if (__pyx_t_9 < 0) __pyx_t_9 += __pyx_pybuffernd_out.diminfo[0].shape; + *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int32_t *, __pyx_pybuffernd_out.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_out.diminfo[0].strides) = __pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_s32((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_int32_t *, __pyx_pybuffernd_key.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_key.diminfo[0].strides)), __pyx_v_seed, 0); } - /* "sklearn/utils/murmurhash.pyx":71 + /* "sklearn/utils/murmurhash.pyx":78 * for i in range(key.shape[0]): * out[i] = murmurhash3_int_s32(key[i], seed) * return out # <<<<<<<<<<<<<< @@ -1907,15 +2063,15 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_arr __Pyx_XDECREF(__pyx_t_4); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_key); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_out); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_key.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.utils.murmurhash.murmurhash3_bytes_array_s32", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_key); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_out); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_key.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_out); __Pyx_XGIVEREF((PyObject *)__pyx_r); @@ -1923,56 +2079,40 @@ static PyArrayObject *__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_arr return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":63 - * - * @cython.boundscheck(False) - * cpdef np.ndarray[np.int32_t, ndim=1] murmurhash3_bytes_array_s32( # <<<<<<<<<<<<<< - * np.ndarray[np.int32_t] key, unsigned int seed): - * """Compute 32bit murmurhash3 hashes of a key int array at seed.""" - */ - -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_array_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_array_s32[] = "Compute 32bit murmurhash3 hashes of a key int array at seed."; -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_array_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_11murmurhash3_bytes_array_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_10murmurhash_10murmurhash3_bytes_array_s32[] = "Compute 32bit murmurhash3 hashes of a key int array at seed."; +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_11murmurhash3_bytes_array_s32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_key = 0; unsigned int __pyx_v_seed; - Py_buffer __pyx_bstruct_key; - Py_ssize_t __pyx_bstride_0_key = 0; - Py_ssize_t __pyx_bshape_0_key = 0; - PyObject *__pyx_r = NULL; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; - __Pyx_RefNannySetupContext("murmurhash3_bytes_array_s32"); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("murmurhash3_bytes_array_s32 (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_array_s32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_array_s32", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "murmurhash3_bytes_array_s32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "murmurhash3_bytes_array_s32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; @@ -1981,26 +2121,55 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_array_ values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_key = ((PyArrayObject *)values[0]); - __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_seed = __Pyx_PyInt_AsUnsignedInt(values[1]); if (unlikely((__pyx_v_seed == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_array_s32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_bytes_array_s32", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.utils.murmurhash.murmurhash3_bytes_array_s32", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_key.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_key), __pyx_ptype_5numpy_ndarray, 1, "key", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_key), __pyx_ptype_5numpy_ndarray, 1, "key", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_10murmurhash_10murmurhash3_bytes_array_s32(__pyx_self, __pyx_v_key, __pyx_v_seed); + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/murmurhash.pyx":70 + * + * @cython.boundscheck(False) + * cpdef np.ndarray[np.int32_t, ndim=1] murmurhash3_bytes_array_s32( # <<<<<<<<<<<<<< + * np.ndarray[np.int32_t] key, unsigned int seed): + * """Compute 32bit murmurhash3 hashes of a key int array at seed.""" + */ + +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_10murmurhash3_bytes_array_s32(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_key, unsigned int __pyx_v_seed) { + __Pyx_LocalBuf_ND __pyx_pybuffernd_key; + __Pyx_Buffer __pyx_pybuffer_key; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("murmurhash3_bytes_array_s32", 0); + __pyx_pybuffer_key.pybuffer.buf = NULL; + __pyx_pybuffer_key.refcount = 0; + __pyx_pybuffernd_key.data = NULL; + __pyx_pybuffernd_key.rcbuffer = &__pyx_pybuffer_key; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_key, (PyObject*)__pyx_v_key, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_key.rcbuffer->pybuffer, (PyObject*)__pyx_v_key, &__Pyx_TypeInfo_nn___pyx_t_5numpy_int32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_key = __pyx_bstruct_key.strides[0]; - __pyx_bshape_0_key = __pyx_bstruct_key.shape[0]; + __pyx_pybuffernd_key.diminfo[0].strides = __pyx_pybuffernd_key.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_key.diminfo[0].shape = __pyx_pybuffernd_key.rcbuffer->pybuffer.shape[0]; __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_s32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((PyObject *)__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_s32(__pyx_v_key, __pyx_v_seed, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -2012,57 +2181,39 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_array_ __Pyx_XDECREF(__pyx_t_1); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_key); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_key.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.utils.murmurhash.murmurhash3_bytes_array_s32", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_key); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_key.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/utils/murmurhash.pyx":74 - * - * - * def murmurhash3_32(key, seed=0, positive=False): # <<<<<<<<<<<<<< - * """Compute the 32bit murmurhash3 of key at seed. - * - */ - -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7sklearn_5utils_10murmurhash_6murmurhash3_32[] = "Compute the 32bit murmurhash3 of key at seed.\n\n The underlying implementation is MurmurHash3_x86_32 generating low\n latency 32bits hash suitable for implementing lookup tables, Bloom\n filters, count min sketch or feature hashing.\n\n Parameters\n ----------\n key: int32, bytes, unicode or ndarray with dtype int32\n the physical object to hash\n\n seed: int, optional default is 0\n integer seed for the hashing algorithm.\n\n positive: boolean, optional default is False\n True: the results is casted to an unsigned int\n from 0 to 2 ** 32 - 1\n False: the results is casted to a signed int\n from -(2 ** 31) to 2 ** 31 - 1\n\n "; -static PyMethodDef __pyx_mdef_7sklearn_5utils_10murmurhash_6murmurhash3_32 = {__Pyx_NAMESTR("murmurhash3_32"), (PyCFunction)__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_6murmurhash3_32)}; -static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_13murmurhash3_32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_10murmurhash_12murmurhash3_32[] = "Compute the 32bit murmurhash3 of key at seed.\n\n The underlying implementation is MurmurHash3_x86_32 generating low\n latency 32bits hash suitable for implementing lookup tables, Bloom\n filters, count min sketch or feature hashing.\n\n Parameters\n ----------\n key: int32, bytes, unicode or ndarray with dtype int32\n the physical object to hash\n\n seed: int, optional default is 0\n integer seed for the hashing algorithm.\n\n positive: boolean, optional default is False\n True: the results is casted to an unsigned int\n from 0 to 2 ** 32 - 1\n False: the results is casted to a signed int\n from -(2 ** 31) to 2 ** 31 - 1\n\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_10murmurhash_13murmurhash3_32 = {__Pyx_NAMESTR("murmurhash3_32"), (PyCFunction)__pyx_pw_7sklearn_5utils_10murmurhash_13murmurhash3_32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_12murmurhash3_32)}; +static PyObject *__pyx_pw_7sklearn_5utils_10murmurhash_13murmurhash3_32(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_key = 0; PyObject *__pyx_v_seed = 0; PyObject *__pyx_v_positive = 0; - PyObject *__pyx_r = NULL; + PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - unsigned int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - __pyx_t_5numpy_int32_t __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,&__pyx_n_s__positive,0}; - __Pyx_RefNannySetupContext("murmurhash3_32"); - __pyx_self = __pyx_self; + __Pyx_RefNannySetupContext("murmurhash3_32 (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__key,&__pyx_n_s__seed,&__pyx_n_s__positive,0}; PyObject* values[3] = {0,0,0}; values[1] = ((PyObject *)__pyx_int_0); values[2] = __pyx_k_1; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); @@ -2070,10 +2221,9 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__key)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (kw_args > 0) { @@ -2087,7 +2237,7 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "murmurhash3_32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "murmurhash3_32") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { @@ -2104,14 +2254,42 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("murmurhash3_32", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("murmurhash3_32", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.utils.murmurhash.murmurhash3_32", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_10murmurhash_12murmurhash3_32(__pyx_self, __pyx_v_key, __pyx_v_seed, __pyx_v_positive); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "sklearn/utils/murmurhash.pyx":96 +/* "sklearn/utils/murmurhash.pyx":81 + * + * + * def murmurhash3_32(key, seed=0, positive=False): # <<<<<<<<<<<<<< + * """Compute the 32bit murmurhash3 of key at seed. + * + */ + +static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_12murmurhash3_32(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_key, PyObject *__pyx_v_seed, PyObject *__pyx_v_positive) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + unsigned int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + __pyx_t_5numpy_int32_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("murmurhash3_32", 0); + + /* "sklearn/utils/murmurhash.pyx":103 * * """ * if isinstance(key, bytes): # <<<<<<<<<<<<<< @@ -2124,17 +2302,17 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_2) { - /* "sklearn/utils/murmurhash.pyx":97 + /* "sklearn/utils/murmurhash.pyx":104 * """ * if isinstance(key, bytes): * if positive: # <<<<<<<<<<<<<< * return murmurhash3_bytes_u32(key, seed) * else: */ - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_positive); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_positive); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_2) { - /* "sklearn/utils/murmurhash.pyx":98 + /* "sklearn/utils/murmurhash.pyx":105 * if isinstance(key, bytes): * if positive: * return murmurhash3_bytes_u32(key, seed) # <<<<<<<<<<<<<< @@ -2142,21 +2320,21 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject * return murmurhash3_bytes_s32(key, seed) */ __Pyx_XDECREF(__pyx_r); - if (!(likely(PyBytes_CheckExact(__pyx_v_key))||((__pyx_v_key) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_v_key)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyBytes_CheckExact(__pyx_v_key))||((__pyx_v_key) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_v_key)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_1 = __pyx_v_key; __Pyx_INCREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = __Pyx_PyInt_to_py_npy_uint32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_u32(((PyObject*)__pyx_t_1), __pyx_t_3, 0)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_to_py_npy_uint32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_u32(((PyObject*)__pyx_t_1), __pyx_t_3, 0)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L0; - goto __pyx_L7; + goto __pyx_L4; } /*else*/ { - /* "sklearn/utils/murmurhash.pyx":100 + /* "sklearn/utils/murmurhash.pyx":107 * return murmurhash3_bytes_u32(key, seed) * else: * return murmurhash3_bytes_s32(key, seed) # <<<<<<<<<<<<<< @@ -2164,22 +2342,22 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject * if positive: */ __Pyx_XDECREF(__pyx_r); - if (!(likely(PyBytes_CheckExact(__pyx_v_key))||((__pyx_v_key) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_v_key)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyBytes_CheckExact(__pyx_v_key))||((__pyx_v_key) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_v_key)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_4 = __pyx_v_key; __Pyx_INCREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32(((PyObject*)__pyx_t_4), __pyx_t_3, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32(((PyObject*)__pyx_t_4), __pyx_t_3, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; } - __pyx_L7:; - goto __pyx_L6; + __pyx_L4:; + goto __pyx_L3; } - /* "sklearn/utils/murmurhash.pyx":101 + /* "sklearn/utils/murmurhash.pyx":108 * else: * return murmurhash3_bytes_s32(key, seed) * elif isinstance(key, unicode): # <<<<<<<<<<<<<< @@ -2192,17 +2370,17 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_2) { - /* "sklearn/utils/murmurhash.pyx":102 + /* "sklearn/utils/murmurhash.pyx":109 * return murmurhash3_bytes_s32(key, seed) * elif isinstance(key, unicode): * if positive: # <<<<<<<<<<<<<< * return murmurhash3_bytes_u32(key.encode('utf-8'), seed) * else: */ - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_positive); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_positive); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_2) { - /* "sklearn/utils/murmurhash.pyx":103 + /* "sklearn/utils/murmurhash.pyx":110 * elif isinstance(key, unicode): * if positive: * return murmurhash3_bytes_u32(key.encode('utf-8'), seed) # <<<<<<<<<<<<<< @@ -2210,24 +2388,24 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject * return murmurhash3_bytes_s32(key.encode('utf-8'), seed) */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__encode); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__encode); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = __Pyx_PyInt_to_py_npy_uint32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_u32(((PyObject*)__pyx_t_4), __pyx_t_3, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_to_py_npy_uint32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_u32(((PyObject*)__pyx_t_4), __pyx_t_3, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - goto __pyx_L8; + goto __pyx_L5; } /*else*/ { - /* "sklearn/utils/murmurhash.pyx":105 + /* "sklearn/utils/murmurhash.pyx":112 * return murmurhash3_bytes_u32(key.encode('utf-8'), seed) * else: * return murmurhash3_bytes_s32(key.encode('utf-8'), seed) # <<<<<<<<<<<<<< @@ -2235,25 +2413,25 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject * if positive: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__encode); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__encode); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32(((PyObject*)__pyx_t_4), __pyx_t_3, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected bytes, got %.200s", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32(((PyObject*)__pyx_t_4), __pyx_t_3, 0)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; } - __pyx_L8:; - goto __pyx_L6; + __pyx_L5:; + goto __pyx_L3; } - /* "sklearn/utils/murmurhash.pyx":106 + /* "sklearn/utils/murmurhash.pyx":113 * else: * return murmurhash3_bytes_s32(key.encode('utf-8'), seed) * elif isinstance(key, int) or isinstance(key, np.int32): # <<<<<<<<<<<<<< @@ -2265,12 +2443,12 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject __pyx_t_2 = __Pyx_TypeCheck(__pyx_v_key, __pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (!__pyx_t_2) { - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__int32); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__int32); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = PyObject_IsInstance(__pyx_v_key, __pyx_t_4); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_IsInstance(__pyx_v_key, __pyx_t_4); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __pyx_t_5; } else { @@ -2278,17 +2456,17 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject } if (__pyx_t_6) { - /* "sklearn/utils/murmurhash.pyx":107 + /* "sklearn/utils/murmurhash.pyx":114 * return murmurhash3_bytes_s32(key.encode('utf-8'), seed) * elif isinstance(key, int) or isinstance(key, np.int32): * if positive: # <<<<<<<<<<<<<< * return murmurhash3_int_u32(key, seed) * else: */ - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_positive); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_positive); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_6) { - /* "sklearn/utils/murmurhash.pyx":108 + /* "sklearn/utils/murmurhash.pyx":115 * elif isinstance(key, int) or isinstance(key, np.int32): * if positive: * return murmurhash3_int_u32(key, seed) # <<<<<<<<<<<<<< @@ -2296,18 +2474,18 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject * return murmurhash3_int_s32(key, seed) */ __Pyx_XDECREF(__pyx_r); - __pyx_t_7 = __Pyx_PyInt_from_py_npy_int32(__pyx_v_key); if (unlikely((__pyx_t_7 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = __Pyx_PyInt_to_py_npy_uint32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(((__pyx_t_5numpy_int32_t)__pyx_t_7), __pyx_t_3, 0)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyInt_from_py_npy_int32(__pyx_v_key); if (unlikely((__pyx_t_7 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_to_py_npy_uint32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_u32(((__pyx_t_5numpy_int32_t)__pyx_t_7), __pyx_t_3, 0)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_r = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L0; - goto __pyx_L9; + goto __pyx_L6; } /*else*/ { - /* "sklearn/utils/murmurhash.pyx":110 + /* "sklearn/utils/murmurhash.pyx":117 * return murmurhash3_int_u32(key, seed) * else: * return murmurhash3_int_s32(key, seed) # <<<<<<<<<<<<<< @@ -2315,19 +2493,19 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject * if key.dtype != np.int32: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_7 = __Pyx_PyInt_from_py_npy_int32(__pyx_v_key); if (unlikely((__pyx_t_7 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = __Pyx_PyInt_to_py_npy_int32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_s32(((__pyx_t_5numpy_int32_t)__pyx_t_7), __pyx_t_3, 0)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyInt_from_py_npy_int32(__pyx_v_key); if (unlikely((__pyx_t_7 == (npy_int32)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_to_py_npy_int32(__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_int_s32(((__pyx_t_5numpy_int32_t)__pyx_t_7), __pyx_t_3, 0)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_r = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L0; } - __pyx_L9:; - goto __pyx_L6; + __pyx_L6:; + goto __pyx_L3; } - /* "sklearn/utils/murmurhash.pyx":111 + /* "sklearn/utils/murmurhash.pyx":118 * else: * return murmurhash3_int_s32(key, seed) * elif isinstance(key, np.ndarray): # <<<<<<<<<<<<<< @@ -2340,66 +2518,65 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { - /* "sklearn/utils/murmurhash.pyx":112 + /* "sklearn/utils/murmurhash.pyx":119 * return murmurhash3_int_s32(key, seed) * elif isinstance(key, np.ndarray): * if key.dtype != np.int32: # <<<<<<<<<<<<<< * raise TypeError( * "key.dtype should be int32, got %s" % key.dtype) */ - __pyx_t_4 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__dtype); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__dtype); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_8 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__int32); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__int32); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_RichCompare(__pyx_t_4, __pyx_t_8, Py_NE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __pyx_t_1 = PyObject_RichCompare(__pyx_t_4, __pyx_t_8, Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_6) { - /* "sklearn/utils/murmurhash.pyx":114 + /* "sklearn/utils/murmurhash.pyx":121 * if key.dtype != np.int32: * raise TypeError( * "key.dtype should be int32, got %s" % key.dtype) # <<<<<<<<<<<<<< * if positive: * return murmurhash3_bytes_array_u32(key.ravel(), */ - __pyx_t_1 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__dtype); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_5), __pyx_t_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_5), __pyx_t_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_8)); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_t_8)); __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_TypeError, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Call(__pyx_builtin_TypeError, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; } - __pyx_L10:; + __pyx_L7:; - /* "sklearn/utils/murmurhash.pyx":115 + /* "sklearn/utils/murmurhash.pyx":122 * raise TypeError( * "key.dtype should be int32, got %s" % key.dtype) * if positive: # <<<<<<<<<<<<<< * return murmurhash3_bytes_array_u32(key.ravel(), * seed).reshape(key.shape) */ - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_positive); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_positive); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_6) { - /* "sklearn/utils/murmurhash.pyx":116 + /* "sklearn/utils/murmurhash.pyx":123 * "key.dtype should be int32, got %s" % key.dtype) * if positive: * return murmurhash3_bytes_array_u32(key.ravel(), # <<<<<<<<<<<<<< @@ -2408,61 +2585,61 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject */ __Pyx_XDECREF(__pyx_r); - /* "sklearn/utils/murmurhash.pyx":117 + /* "sklearn/utils/murmurhash.pyx":124 * if positive: * return murmurhash3_bytes_array_u32(key.ravel(), * seed).reshape(key.shape) # <<<<<<<<<<<<<< * else: * return murmurhash3_bytes_array_s32(key.ravel(), */ - __pyx_t_8 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__ravel); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__ravel); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); - /* "sklearn/utils/murmurhash.pyx":116 + /* "sklearn/utils/murmurhash.pyx":123 * "key.dtype should be int32, got %s" % key.dtype) * if positive: * return murmurhash3_bytes_array_u32(key.ravel(), # <<<<<<<<<<<<<< * seed).reshape(key.shape) * else: */ - __pyx_t_1 = PyObject_Call(__pyx_t_8, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_8, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/utils/murmurhash.pyx":117 + /* "sklearn/utils/murmurhash.pyx":124 * if positive: * return murmurhash3_bytes_array_u32(key.ravel(), * seed).reshape(key.shape) # <<<<<<<<<<<<<< * else: * return murmurhash3_bytes_array_s32(key.ravel(), */ - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_8 = ((PyObject *)__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_u32(((PyArrayObject *)__pyx_t_1), __pyx_t_3, 0)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((PyObject *)__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_u32(((PyArrayObject *)__pyx_t_1), __pyx_t_3, 0)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_8, __pyx_n_s__reshape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_GetAttr(__pyx_t_8, __pyx_n_s__reshape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__shape); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__shape); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); __Pyx_GIVEREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __pyx_r = __pyx_t_8; __pyx_t_8 = 0; goto __pyx_L0; - goto __pyx_L11; + goto __pyx_L8; } /*else*/ { - /* "sklearn/utils/murmurhash.pyx":119 + /* "sklearn/utils/murmurhash.pyx":126 * seed).reshape(key.shape) * else: * return murmurhash3_bytes_array_s32(key.ravel(), # <<<<<<<<<<<<<< @@ -2471,50 +2648,50 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject */ __Pyx_XDECREF(__pyx_r); - /* "sklearn/utils/murmurhash.pyx":120 + /* "sklearn/utils/murmurhash.pyx":127 * else: * return murmurhash3_bytes_array_s32(key.ravel(), * seed).reshape(key.shape) # <<<<<<<<<<<<<< * else: * raise TypeError( */ - __pyx_t_8 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__ravel); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__ravel); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); - /* "sklearn/utils/murmurhash.pyx":119 + /* "sklearn/utils/murmurhash.pyx":126 * seed).reshape(key.shape) * else: * return murmurhash3_bytes_array_s32(key.ravel(), # <<<<<<<<<<<<<< * seed).reshape(key.shape) * else: */ - __pyx_t_4 = PyObject_Call(__pyx_t_8, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_8, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "sklearn/utils/murmurhash.pyx":120 + /* "sklearn/utils/murmurhash.pyx":127 * else: * return murmurhash3_bytes_array_s32(key.ravel(), * seed).reshape(key.shape) # <<<<<<<<<<<<<< * else: * raise TypeError( */ - __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_8 = ((PyObject *)__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_s32(((PyArrayObject *)__pyx_t_4), __pyx_t_3, 0)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_seed); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = ((PyObject *)__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_array_s32(((PyArrayObject *)__pyx_t_4), __pyx_t_3, 0)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_GetAttr(__pyx_t_8, __pyx_n_s__reshape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_GetAttr(__pyx_t_8, __pyx_n_s__reshape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__shape); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_GetAttr(__pyx_v_key, __pyx_n_s__shape); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_8); __Pyx_GIVEREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; @@ -2522,40 +2699,40 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject __pyx_t_8 = 0; goto __pyx_L0; } - __pyx_L11:; - goto __pyx_L6; + __pyx_L8:; + goto __pyx_L3; } /*else*/ { - /* "sklearn/utils/murmurhash.pyx":124 + /* "sklearn/utils/murmurhash.pyx":131 * raise TypeError( * "key %r with type %s is not supported. " * "Explicit conversion to bytes is required" % (key, type(key))) # <<<<<<<<<<<<<< */ - __pyx_t_8 = PyTuple_New(2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = PyTuple_New(2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); __Pyx_INCREF(__pyx_v_key); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_key); __Pyx_GIVEREF(__pyx_v_key); __Pyx_INCREF(((PyObject *)Py_TYPE(__pyx_v_key))); PyTuple_SET_ITEM(__pyx_t_8, 1, ((PyObject *)Py_TYPE(__pyx_v_key))); __Pyx_GIVEREF(((PyObject *)Py_TYPE(__pyx_v_key))); - __pyx_t_1 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_6), ((PyObject *)__pyx_t_8)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyNumber_Remainder(((PyObject *)__pyx_kp_s_6), ((PyObject *)__pyx_t_8)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_1)); __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_8, 0, ((PyObject *)__pyx_t_1)); __Pyx_GIVEREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_builtin_TypeError, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_builtin_TypeError, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; + __pyx_L3:; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; @@ -2571,16 +2748,26 @@ static PyObject *__pyx_pf_7sklearn_5utils_10murmurhash_6murmurhash3_32(PyObject return __pyx_r; } -/* "numpy.pxd":190 +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":194 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP. + * # requirements, and does not yet fulfill the PEP. */ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; @@ -2605,13 +2792,13 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__"); + __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":196 + /* "numpy.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< @@ -2622,11 +2809,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":199 + /* "numpy.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -2635,7 +2822,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":200 + /* "numpy.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -2644,16 +2831,16 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":202 + /* "numpy.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":204 + /* "numpy.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< @@ -2663,7 +2850,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_t_1) { - /* "numpy.pxd":205 + /* "numpy.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -2671,11 +2858,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ * copy_shape = 0 */ __pyx_v_copy_shape = 1; - goto __pyx_L6; + goto __pyx_L4; } /*else*/ { - /* "numpy.pxd":207 + /* "numpy.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -2684,9 +2871,9 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_copy_shape = 0; } - __pyx_L6:; + __pyx_L4:; - /* "numpy.pxd":209 + /* "numpy.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< @@ -2696,37 +2883,37 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); if (__pyx_t_1) { - /* "numpy.pxd":210 + /* "numpy.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); + __pyx_t_2 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS)); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { - /* "numpy.pxd":211 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; } - __pyx_L7:; + __pyx_L5:; - /* "numpy.pxd":213 + /* "numpy.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< @@ -2736,46 +2923,46 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); if (__pyx_t_3) { - /* "numpy.pxd":214 + /* "numpy.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); + __pyx_t_1 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS)); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { - /* "numpy.pxd":215 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; } - __pyx_L8:; + __pyx_L6:; - /* "numpy.pxd":217 + /* "numpy.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":218 + /* "numpy.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -2784,7 +2971,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":219 + /* "numpy.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< @@ -2793,7 +2980,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ if (__pyx_v_copy_shape) { - /* "numpy.pxd":222 + /* "numpy.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -2802,7 +2989,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":223 + /* "numpy.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -2811,7 +2998,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":224 + /* "numpy.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< @@ -2822,49 +3009,49 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "numpy.pxd":225 + /* "numpy.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":226 + /* "numpy.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } - goto __pyx_L9; + goto __pyx_L7; } /*else*/ { - /* "numpy.pxd":228 + /* "numpy.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":229 + /* "numpy.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } - __pyx_L9:; + __pyx_L7:; - /* "numpy.pxd":230 + /* "numpy.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -2873,25 +3060,25 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":231 + /* "numpy.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":232 + /* "numpy.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); - /* "numpy.pxd":235 + /* "numpy.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -2900,17 +3087,19 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_f = NULL; - /* "numpy.pxd":236 + /* "numpy.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":240 + /* "numpy.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -2919,7 +3108,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":242 + /* "numpy.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< @@ -2935,7 +3124,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (__pyx_t_1) { - /* "numpy.pxd":244 + /* "numpy.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -2947,49 +3136,50 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; - goto __pyx_L12; + goto __pyx_L10; } /*else*/ { - /* "numpy.pxd":247 + /* "numpy.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } - __pyx_L12:; + __pyx_L10:; - /* "numpy.pxd":249 + /* "numpy.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ __pyx_t_1 = (!__pyx_v_hasfields); if (__pyx_t_1) { - /* "numpy.pxd":250 + /* "numpy.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; - /* "numpy.pxd":251 + /* "numpy.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); @@ -3000,10 +3190,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (!__pyx_t_2) { - /* "numpy.pxd":252 + /* "numpy.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ @@ -3020,24 +3210,24 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (__pyx_t_1) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; } - __pyx_L14:; + __pyx_L12:; - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" @@ -3046,10 +3236,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_BYTE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__b; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":255 + /* "numpy.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< @@ -3059,10 +3249,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__B; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":256 + /* "numpy.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< @@ -3072,10 +3262,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_SHORT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__h; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":257 + /* "numpy.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< @@ -3085,10 +3275,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_USHORT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__H; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":258 + /* "numpy.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< @@ -3098,10 +3288,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_INT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__i; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":259 + /* "numpy.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< @@ -3111,10 +3301,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_UINT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__I; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":260 + /* "numpy.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< @@ -3124,10 +3314,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_LONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__l; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":261 + /* "numpy.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< @@ -3137,10 +3327,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_ULONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__L; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":262 + /* "numpy.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< @@ -3150,10 +3340,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__q; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":263 + /* "numpy.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< @@ -3163,10 +3353,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":264 + /* "numpy.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< @@ -3176,10 +3366,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__f; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":265 + /* "numpy.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< @@ -3189,10 +3379,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__d; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":266 + /* "numpy.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< @@ -3202,10 +3392,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__g; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":267 + /* "numpy.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< @@ -3215,10 +3405,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":268 + /* "numpy.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< @@ -3228,10 +3418,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":269 + /* "numpy.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< @@ -3241,10 +3431,10 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; + goto __pyx_L13; } - /* "numpy.pxd":270 + /* "numpy.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< @@ -3254,37 +3444,37 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__O; - goto __pyx_L15; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":272 + /* "numpy.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_13), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_13), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_8)); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L15:; + __pyx_L13:; - /* "numpy.pxd":273 + /* "numpy.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -3293,7 +3483,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":274 + /* "numpy.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -3302,57 +3492,57 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L13; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":276 + /* "numpy.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":277 + /* "numpy.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":278 + /* "numpy.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":281 + /* "numpy.pxd":285 * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string + * f[0] = c'\0' # Terminate format string * */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; - /* "numpy.pxd":282 + /* "numpy.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L13:; + __pyx_L11:; __pyx_r = 0; goto __pyx_L0; @@ -3377,31 +3567,39 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ return __pyx_r; } -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":288 + * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__"); + __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":285 + /* "numpy.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); if (__pyx_t_1) { - /* "numpy.pxd":286 + /* "numpy.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -3409,11 +3607,11 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * stdlib.free(info.strides) */ free(__pyx_v_info->format); - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":287 + /* "numpy.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< @@ -3423,7 +3621,7 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_t_1) { - /* "numpy.pxd":288 + /* "numpy.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -3431,14 +3629,14 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * */ free(__pyx_v_info->strides); - goto __pyx_L6; + goto __pyx_L4; } - __pyx_L6:; + __pyx_L4:; __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":764 +/* "numpy.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -3453,9 +3651,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":765 + /* "numpy.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -3463,7 +3661,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3481,7 +3679,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":767 +/* "numpy.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -3496,9 +3694,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":768 + /* "numpy.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -3506,7 +3704,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3524,7 +3722,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "numpy.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -3539,9 +3737,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":771 + /* "numpy.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -3549,7 +3747,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3567,7 +3765,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "numpy.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -3582,9 +3780,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":774 + /* "numpy.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -3592,7 +3790,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3610,7 +3808,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "numpy.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -3625,9 +3823,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":777 + /* "numpy.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -3635,7 +3833,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3653,7 +3851,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "numpy.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -3676,18 +3874,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; + PyObject *(*__pyx_t_6)(PyObject *); int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; - long __pyx_t_10; - char *__pyx_t_11; + int __pyx_t_10; + long __pyx_t_11; + char *__pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring"); + __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":786 + /* "numpy.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -3696,7 +3895,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":787 + /* "numpy.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -3705,7 +3904,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":790 + /* "numpy.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< @@ -3713,31 +3912,36 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * child, new_offset = fields */ if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif __Pyx_XDECREF(__pyx_v_childname); __pyx_v_childname = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":791 + /* "numpy.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); __pyx_v_fields = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":792 + /* "numpy.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< @@ -3746,20 +3950,49 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); - } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + } else if (1) { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else + { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(((PyObject *)__pyx_v_fields)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L6_unpacking_done:; } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_child)); __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; @@ -3767,99 +4000,98 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_v_new_offset = __pyx_t_4; __pyx_t_4 = 0; - /* "numpy.pxd":794 + /* "numpy.pxd":798 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":795 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; } - __pyx_L5:; + __pyx_L7:; - /* "numpy.pxd":797 + /* "numpy.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); - if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = (__pyx_v_child->byteorder == '>'); + if (__pyx_t_7) { + __pyx_t_8 = __pyx_v_little_endian; } else { - __pyx_t_7 = __pyx_t_6; + __pyx_t_8 = __pyx_t_7; } - if (!__pyx_t_7) { + if (!__pyx_t_8) { - /* "numpy.pxd":798 + /* "numpy.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); - if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); - __pyx_t_9 = __pyx_t_8; + __pyx_t_7 = (__pyx_v_child->byteorder == '<'); + if (__pyx_t_7) { + __pyx_t_9 = (!__pyx_v_little_endian); + __pyx_t_10 = __pyx_t_9; } else { - __pyx_t_9 = __pyx_t_6; + __pyx_t_10 = __pyx_t_7; } - __pyx_t_6 = __pyx_t_9; + __pyx_t_7 = __pyx_t_10; } else { - __pyx_t_6 = __pyx_t_7; + __pyx_t_7 = __pyx_t_8; } - if (__pyx_t_6) { + if (__pyx_t_7) { - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L8; } - __pyx_L6:; + __pyx_L8:; - /* "numpy.pxd":809 + /* "numpy.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -3867,16 +4099,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!__pyx_t_6) break; + if (!__pyx_t_7) break; - /* "numpy.pxd":810 + /* "numpy.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -3885,7 +4116,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":811 + /* "numpy.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -3894,430 +4125,413 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":812 + /* "numpy.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + 1); } - /* "numpy.pxd":814 + /* "numpy.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ - __pyx_t_10 = 0; - (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + __pyx_t_11 = 0; + (__pyx_v_offset[__pyx_t_11]) = ((__pyx_v_offset[__pyx_t_11]) + __pyx_v_child->elsize); - /* "numpy.pxd":816 + /* "numpy.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); - if (__pyx_t_6) { + __pyx_t_7 = (!PyDataType_HASFIELDS(__pyx_v_child)); + if (__pyx_t_7) { - /* "numpy.pxd":817 + /* "numpy.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XDECREF(__pyx_v_t); __pyx_v_t = __pyx_t_3; __pyx_t_3 = 0; - /* "numpy.pxd":818 + /* "numpy.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); - if (__pyx_t_6) { + __pyx_t_7 = ((__pyx_v_end - __pyx_v_f) < 5); + if (__pyx_t_7) { - /* "numpy.pxd":819 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_18), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_18), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; } - __pyx_L10:; + __pyx_L12:; - /* "numpy.pxd":822 + /* "numpy.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 98; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":823 + /* "numpy.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 66; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":824 + /* "numpy.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 104; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":825 + /* "numpy.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 72; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":826 + /* "numpy.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 105; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":827 + /* "numpy.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 73; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":828 + /* "numpy.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 108; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":829 + /* "numpy.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 76; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":830 + /* "numpy.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 113; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":831 + /* "numpy.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 81; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":832 + /* "numpy.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 102; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":833 + /* "numpy.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 100; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":834 + /* "numpy.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 103; - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":835 + /* "numpy.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":836 + /* "numpy.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":837 + /* "numpy.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L11; + goto __pyx_L13; } - /* "numpy.pxd":838 + /* "numpy.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_6) { + if (__pyx_t_7) { (__pyx_v_f[0]) = 79; - goto __pyx_L11; + goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":840 + /* "numpy.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_13), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_13), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L11:; + __pyx_L13:; - /* "numpy.pxd":841 + /* "numpy.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -4325,25 +4539,25 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L9; + goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":845 + /* "numpy.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_f = __pyx_t_11; + __pyx_t_12 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_12 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_12; } - __pyx_L9:; + __pyx_L11:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":846 + /* "numpy.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -4372,7 +4586,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":961 +/* "numpy.pxd":965 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -4384,9 +4598,9 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base"); + __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":963 + /* "numpy.pxd":967 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -4396,7 +4610,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a __pyx_t_1 = (__pyx_v_base == Py_None); if (__pyx_t_1) { - /* "numpy.pxd":964 + /* "numpy.pxd":968 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -4408,7 +4622,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":966 + /* "numpy.pxd":970 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -4417,7 +4631,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":967 + /* "numpy.pxd":971 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -4428,7 +4642,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":968 + /* "numpy.pxd":972 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -4437,7 +4651,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":969 + /* "numpy.pxd":973 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -4449,7 +4663,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":971 +/* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -4461,9 +4675,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base"); + __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":972 + /* "numpy.pxd":976 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< @@ -4473,7 +4687,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __pyx_t_1 = (__pyx_v_arr->base == NULL); if (__pyx_t_1) { - /* "numpy.pxd":973 + /* "numpy.pxd":977 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -4488,7 +4702,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py } /*else*/ { - /* "numpy.pxd":975 + /* "numpy.pxd":979 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -4508,12 +4722,12 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py } static PyMethodDef __pyx_methods[] = { - {__Pyx_NAMESTR("murmurhash3_int_u32"), (PyCFunction)__pyx_pf_7sklearn_5utils_10murmurhash_murmurhash3_int_u32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_murmurhash3_int_u32)}, - {__Pyx_NAMESTR("murmurhash3_int_s32"), (PyCFunction)__pyx_pf_7sklearn_5utils_10murmurhash_1murmurhash3_int_s32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_1murmurhash3_int_s32)}, - {__Pyx_NAMESTR("murmurhash3_bytes_u32"), (PyCFunction)__pyx_pf_7sklearn_5utils_10murmurhash_2murmurhash3_bytes_u32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_2murmurhash3_bytes_u32)}, - {__Pyx_NAMESTR("murmurhash3_bytes_s32"), (PyCFunction)__pyx_pf_7sklearn_5utils_10murmurhash_3murmurhash3_bytes_s32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_3murmurhash3_bytes_s32)}, - {__Pyx_NAMESTR("murmurhash3_bytes_array_u32"), (PyCFunction)__pyx_pf_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_array_u32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_array_u32)}, - {__Pyx_NAMESTR("murmurhash3_bytes_array_s32"), (PyCFunction)__pyx_pf_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_array_s32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_array_s32)}, + {__Pyx_NAMESTR("murmurhash3_int_u32"), (PyCFunction)__pyx_pw_7sklearn_5utils_10murmurhash_1murmurhash3_int_u32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_murmurhash3_int_u32)}, + {__Pyx_NAMESTR("murmurhash3_int_s32"), (PyCFunction)__pyx_pw_7sklearn_5utils_10murmurhash_3murmurhash3_int_s32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_2murmurhash3_int_s32)}, + {__Pyx_NAMESTR("murmurhash3_bytes_u32"), (PyCFunction)__pyx_pw_7sklearn_5utils_10murmurhash_5murmurhash3_bytes_u32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_4murmurhash3_bytes_u32)}, + {__Pyx_NAMESTR("murmurhash3_bytes_s32"), (PyCFunction)__pyx_pw_7sklearn_5utils_10murmurhash_7murmurhash3_bytes_s32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_6murmurhash3_bytes_s32)}, + {__Pyx_NAMESTR("murmurhash3_bytes_array_u32"), (PyCFunction)__pyx_pw_7sklearn_5utils_10murmurhash_9murmurhash3_bytes_array_u32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_8murmurhash3_bytes_array_u32)}, + {__Pyx_NAMESTR("murmurhash3_bytes_array_s32"), (PyCFunction)__pyx_pw_7sklearn_5utils_10murmurhash_11murmurhash3_bytes_array_s32, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_10murmurhash_10murmurhash3_bytes_array_s32)}, {0, 0, 0, 0} }; @@ -4537,7 +4751,8 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_u_14, __pyx_k_14, sizeof(__pyx_k_14), 0, 1, 0, 0}, {&__pyx_kp_u_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 1, 0, 0}, {&__pyx_kp_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 0}, - {&__pyx_n_s_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 1, 1}, + {&__pyx_kp_s_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 1, 0}, + {&__pyx_n_s_23, __pyx_k_23, sizeof(__pyx_k_23), 0, 0, 1, 1}, {&__pyx_kp_s_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 0, 1, 0}, {&__pyx_kp_s_6, __pyx_k_6, sizeof(__pyx_k_6), 0, 0, 1, 0}, {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, @@ -4566,10 +4781,10 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_TypeError = __Pyx_GetName(__pyx_b, __pyx_n_s__TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetName(__pyx_b, __pyx_n_s__TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -4577,119 +4792,140 @@ static int __Pyx_InitCachedBuiltins(void) { static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "sklearn/utils/murmurhash.pyx":103 + /* "sklearn/utils/murmurhash.pyx":110 * elif isinstance(key, unicode): * if positive: * return murmurhash3_bytes_u32(key.encode('utf-8'), seed) # <<<<<<<<<<<<<< * else: * return murmurhash3_bytes_s32(key.encode('utf-8'), seed) */ - __pyx_k_tuple_3 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_3)); + __pyx_k_tuple_3 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_3); __Pyx_INCREF(((PyObject *)__pyx_kp_s_2)); PyTuple_SET_ITEM(__pyx_k_tuple_3, 0, ((PyObject *)__pyx_kp_s_2)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_2)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_3)); - /* "sklearn/utils/murmurhash.pyx":105 + /* "sklearn/utils/murmurhash.pyx":112 * return murmurhash3_bytes_u32(key.encode('utf-8'), seed) * else: * return murmurhash3_bytes_s32(key.encode('utf-8'), seed) # <<<<<<<<<<<<<< * elif isinstance(key, int) or isinstance(key, np.int32): * if positive: */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 105; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_4)); + __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_4); __Pyx_INCREF(((PyObject *)__pyx_kp_s_2)); PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_s_2)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_2)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); - /* "numpy.pxd":211 + /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_8 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_8)); + __pyx_k_tuple_8 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_8); __Pyx_INCREF(((PyObject *)__pyx_kp_u_7)); PyTuple_SET_ITEM(__pyx_k_tuple_8, 0, ((PyObject *)__pyx_kp_u_7)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_7)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); - /* "numpy.pxd":215 + /* "numpy.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_10)); + __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_10); __Pyx_INCREF(((PyObject *)__pyx_kp_u_9)); PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_9)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_9)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "numpy.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_12)); + __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_12); __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_11)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); - /* "numpy.pxd":795 + /* "numpy.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_15 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_15)); + __pyx_k_tuple_15 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_15); __Pyx_INCREF(((PyObject *)__pyx_kp_u_14)); PyTuple_SET_ITEM(__pyx_k_tuple_15, 0, ((PyObject *)__pyx_kp_u_14)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_14)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "numpy.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_16 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_16)); + __pyx_k_tuple_16 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_16); __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); PyTuple_SET_ITEM(__pyx_k_tuple_16, 0, ((PyObject *)__pyx_kp_u_11)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); - /* "numpy.pxd":819 + /* "numpy.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_18 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_18)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_18)); + __pyx_k_tuple_18 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_18)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_18); __Pyx_INCREF(((PyObject *)__pyx_kp_u_17)); PyTuple_SET_ITEM(__pyx_k_tuple_18, 0, ((PyObject *)__pyx_kp_u_17)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_17)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_18)); + + /* "sklearn/utils/murmurhash.pyx":81 + * + * + * def murmurhash3_32(key, seed=0, positive=False): # <<<<<<<<<<<<<< + * """Compute the 32bit murmurhash3 of key at seed. + * + */ + __pyx_k_tuple_20 = PyTuple_New(3); if (unlikely(!__pyx_k_tuple_20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_20); + __Pyx_INCREF(((PyObject *)__pyx_n_s__key)); + PyTuple_SET_ITEM(__pyx_k_tuple_20, 0, ((PyObject *)__pyx_n_s__key)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__key)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__seed)); + PyTuple_SET_ITEM(__pyx_k_tuple_20, 1, ((PyObject *)__pyx_n_s__seed)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__seed)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__positive)); + PyTuple_SET_ITEM(__pyx_k_tuple_20, 2, ((PyObject *)__pyx_n_s__positive)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__positive)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_20)); + __pyx_k_codeobj_21 = (PyObject*)__Pyx_PyCode_New(3, 0, 3, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_20, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_22, __pyx_n_s__murmurhash3_32, 81, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_21)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -4725,12 +4961,18 @@ PyMODINIT_FUNC PyInit_murmurhash(void) Py_FatalError("failed to import 'refnanny' module"); } #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_murmurhash(void)"); + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_murmurhash(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __pyx_binding_PyCFunctionType_USED - if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -4741,16 +4983,23 @@ PyMODINIT_FUNC PyInit_murmurhash(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("murmurhash"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_19), 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("murmurhash"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_19), 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.utils.murmurhash")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.utils.murmurhash", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} @@ -4770,11 +5019,18 @@ PyMODINIT_FUNC PyInit_murmurhash(void) if (__Pyx_ExportFunction("murmurhash3_bytes_s32", (void (*)(void))__pyx_f_7sklearn_5utils_10murmurhash_murmurhash3_bytes_s32, "__pyx_t_5numpy_int32_t (PyObject *, unsigned int, int __pyx_skip_dispatch)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Type init code ---*/ /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ @@ -4784,28 +5040,37 @@ PyMODINIT_FUNC PyInit_murmurhash(void) * cimport numpy as np * import numpy as np # <<<<<<<<<<<<<< * - * + * cdef extern from "src/MurmurHash3.h": */ __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "sklearn/utils/murmurhash.pyx":74 + /* "sklearn/utils/murmurhash.pyx":26 + * void MurmurHash3_x64_128 (void *key, int len, np.uint32_t seed, void *out) + * + * np.import_array() # <<<<<<<<<<<<<< + * + * + */ + import_array(); + + /* "sklearn/utils/murmurhash.pyx":81 * * * def murmurhash3_32(key, seed=0, positive=False): # <<<<<<<<<<<<<< * """Compute the 32bit murmurhash3 of key at seed. * */ - __pyx_t_1 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_k_1 = __pyx_t_1; __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_10murmurhash_6murmurhash3_32, NULL, __pyx_n_s_20); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_10murmurhash_13murmurhash3_32, NULL, __pyx_n_s_23); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__murmurhash3_32, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__murmurhash3_32, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "sklearn/utils/murmurhash.pyx":1 @@ -4818,7 +5083,7 @@ PyMODINIT_FUNC PyInit_murmurhash(void) if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - /* "numpy.pxd":971 + /* "numpy.pxd":975 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -4844,7 +5109,6 @@ PyMODINIT_FUNC PyInit_murmurhash(void) } /* Runtime support code */ - #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; @@ -4885,7 +5149,6 @@ static void __Pyx_RaiseArgtupleInvalid( { Py_ssize_t num_expected; const char *more_or_less; - if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; @@ -4897,7 +5160,7 @@ static void __Pyx_RaiseArgtupleInvalid( more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", + "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } @@ -4911,7 +5174,7 @@ static void __Pyx_RaiseDoubleKeywordsError( "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); + PyString_AsString(kw_name)); #endif } @@ -4927,55 +5190,77 @@ static int __Pyx_ParseOptionalKeywords( Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; } - if (*name) { + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { values[name-argnames] = value; - } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; } } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; } } return 0; arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); + __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, @@ -5018,18 +5303,6 @@ static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } - -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; -} __Pyx_BufFmt_Context; - static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { @@ -5048,6 +5321,8 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; @@ -5055,7 +5330,6 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, type = type->fields->type; } } - static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; @@ -5071,15 +5345,21 @@ static int __Pyx_BufFmt_ParseNumber(const char** ts) { *ts = t; return count; } - +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } - static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { - case 'b': return "'char'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; @@ -5095,14 +5375,14 @@ static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; + case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } - static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; @@ -5118,10 +5398,9 @@ static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { return 0; } } - static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'B': return 1; + case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); @@ -5138,7 +5417,6 @@ static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { } } } - typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; @@ -5149,10 +5427,9 @@ typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif - -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); @@ -5168,21 +5445,59 @@ static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { return 0; } } - +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'h': case 'i': case 'l': case 'q': return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; - case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); - case 'O': return 'O'; - case 'P': return 'P'; + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } - static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; @@ -5207,16 +5522,37 @@ static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { parent->type->name, field->name); } } - static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; - size_t size, offset; + size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { @@ -5228,35 +5564,35 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); } - if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { - /* special case -- treat as struct rather than complex number */ size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } - - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } - offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } - ctx->fmt_offset += size; - + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; /* Consume from buffer string */ - - /* Done checking, move to next field, pushing or popping struct stack if needed */ while (1) { if (field == &ctx->root) { ctx->head = NULL; @@ -5288,7 +5624,48 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ctx->is_complex = 0; return 0; } - +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + if (isspace(*ts)) + continue; + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { @@ -5303,7 +5680,7 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } - return ts; + return ts; case ' ': case 10: case 13: @@ -5335,12 +5712,17 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { @@ -5348,10 +5730,19 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha if (!ts_after_sub) return NULL; } ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': /* end of substruct; either repeat or move on */ - ++ts; + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; @@ -5372,13 +5763,11 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': - case 'O': + case 'O': case 's': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { - /* Continue pooling same type */ ctx->enc_count += ctx->new_count; } else { - /* New type */ if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; @@ -5394,20 +5783,18 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha while(*ts != ':') ++ts; ++ts; break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; default: { - int number = __Pyx_BufFmt_ParseNumber(&ts); - if (number == -1) { /* First char was not a digit */ - PyErr_Format(PyExc_ValueError, - "Does not understand character buffer dtype format string ('%c')", *ts); - return NULL; - } - ctx->new_count = (size_t)number; + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; } } } } - static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; @@ -5415,8 +5802,10 @@ static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; @@ -5436,7 +5825,7 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* ob } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; @@ -5447,7 +5836,6 @@ fail:; __Pyx_ZeroBuffer(buf); return -1; } - static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; @@ -5467,9 +5855,9 @@ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { } static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; @@ -5479,55 +5867,60 @@ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyOb Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif } - static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif } - #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) + if (PyClass_Check(type)) { #else - if (!PyType_Check(type)) + if (PyType_Check(type)) { #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - /* Normalize to raise , */ - Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 if (PyInstance_Check(type)) { @@ -5550,7 +5943,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } #endif } - __Pyx_ErrRestore(type, value, tb); return; raise_error: @@ -5559,10 +5951,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tb); return; } - #else /* Python 3+ */ - static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -5572,7 +5963,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } if (value == Py_None) value = 0; - if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, @@ -5581,13 +5971,36 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } + else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyEval_CallObject(type, args); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } - - if (cause) { + if (cause && cause != Py_None) { PyObject *fixed_cause; if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); @@ -5604,14 +6017,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; @@ -5621,64 +6029,146 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tmp_tb); } } - bad: + Py_XDECREF(owned_instance); return; } #endif -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", + index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; } else { - __Pyx_RaiseTooManyValuesError(index); + return __Pyx_IterFinish(); } + return 0; } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + CYTHON_UNUSED PyObject *getbuffer_cobj; #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); - else { - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict && + (getbuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, + "__pyx_getbuffer"))) { + getbufferproc func; + #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + func = (getbufferproc) PyCapsule_GetPointer(getbuffer_cobj, "getbuffer(obj, view, flags)"); + #else + func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + #endif + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); } + #endif + PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; } - static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject* obj = view->obj; - if (obj) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;} - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray_1__releasebuffer__(obj, view); + PyObject *obj = view->obj; + CYTHON_UNUSED PyObject *releasebuffer_cobj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict && + (releasebuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, + "__pyx_releasebuffer"))) { + releasebufferproc func; + #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + func = (releasebufferproc) PyCapsule_GetPointer(releasebuffer_cobj, "releasebuffer(obj, view)"); + #else + func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + #endif + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: Py_DECREF(obj); view->obj = NULL; - } } +#endif /* PY_MAJOR_VERSION < 3 */ -#endif -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { PyObject *py_import = 0; PyObject *empty_list = 0; PyObject *module = 0; @@ -5704,12 +6194,33 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { goto bad; #if PY_VERSION_HEX >= 0x02050000 { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + /* try package relative import first */ + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + } } #else if (level>0) { @@ -5830,6 +6341,10 @@ static CYTHON_INLINE npy_int32 __Pyx_PyInt_from_py_npy_int32(PyObject* x) { else return (npy_int32)__Pyx_PyInt_AsSignedLongLong(x); } else { + #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); + #else npy_int32 val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_VERSION_HEX < 0x03000000 @@ -5849,6 +6364,7 @@ static CYTHON_INLINE npy_int32 __Pyx_PyInt_from_py_npy_int32(PyObject* x) { if (likely(!ret)) return val; } + #endif return (npy_int32)-1; } } @@ -6493,8 +7009,8 @@ static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* } } -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename) { +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); @@ -6538,7 +7054,6 @@ static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *s void (*fp)(void); void *p; } tmp; - d = PyObject_GetAttrString(__pyx_m, (char *)"__pyx_capi__"); if (!d) { PyErr_Clear(); @@ -6568,6 +7083,23 @@ static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *s return -1; } +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -6577,15 +7109,10 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(class_name); - #else - py_name = PyUnicode_FromString(class_name); - #endif + py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); @@ -6601,7 +7128,7 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { + if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -6611,7 +7138,7 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { PyErr_Format(PyExc_ValueError, "%s.%s has the wrong size, try recompiling", module_name, class_name); @@ -6625,51 +7152,105 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(name); - #else - py_name = PyUnicode_FromString(name); - #endif - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); } -#endif #include "compile.h" #include "frameobject.h" #include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); + py_srcfile = PyString_FromString(filename); #else - py_srcfile = PyUnicode_FromString(__pyx_filename); + py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; - if (__pyx_clineno) { + if (c_line) { #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { @@ -6680,28 +7261,45 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, #endif } if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_code = PyCode_New( + py_code = __Pyx_PyCode_New( 0, /*int argcount,*/ - #if PY_MAJOR_VERSION >= 3 0, /*int kwonlyargcount,*/ - #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ + py_line, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); - if (!py_code) goto bad; + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ @@ -6709,11 +7307,9 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; + py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); } @@ -6748,6 +7344,7 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } + /* Type Conversion Functions */ static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { diff --git a/sklearn/utils/murmurhash.pxd b/sklearn/utils/murmurhash.pxd index f090bdca63222..ed34ef6c9f006 100644 --- a/sklearn/utils/murmurhash.pxd +++ b/sklearn/utils/murmurhash.pxd @@ -2,15 +2,17 @@ cimport numpy as np -cdef extern from "MurmurHash3.h": - void MurmurHash3_x86_32(void* key, int len, unsigned int seed, - void* out) - - void MurmurHash3_x86_128(void* key, int len, unsigned int seed, - void* out) - - void MurmurHash3_x64_128(void* key, int len, unsigned int seed, - void* out) +# The C API is disabled for now, since it requires -I flags to get +# compilation to work even when these functions are not used. +#cdef extern from "MurmurHash3.h": +# void MurmurHash3_x86_32(void* key, int len, unsigned int seed, +# void* out) +# +# void MurmurHash3_x86_128(void* key, int len, unsigned int seed, +# void* out) +# +# void MurmurHash3_x64_128(void* key, int len, unsigned int seed, +# void* out) cpdef np.uint32_t murmurhash3_int_u32(int key, unsigned int seed) diff --git a/sklearn/utils/murmurhash.pyx b/sklearn/utils/murmurhash.pyx index 78d4b79416337..a6b4a49e83584 100644 --- a/sklearn/utils/murmurhash.pyx +++ b/sklearn/utils/murmurhash.pyx @@ -12,12 +12,19 @@ and can be found here: """ # Author: Olivier Grisel # -# License: BSD Style. +# Licence: BSD 3 clause cimport cython cimport numpy as np import numpy as np +cdef extern from "src/MurmurHash3.h": + void MurmurHash3_x86_32(void *key, int len, np.uint32_t seed, void *out) + void MurmurHash3_x86_128(void *key, int len, np.uint32_t seed, void *out) + void MurmurHash3_x64_128 (void *key, int len, np.uint32_t seed, void *out) + +np.import_array() + cpdef np.uint32_t murmurhash3_int_u32(int key, unsigned int seed): """Compute the 32bit murmurhash3 of a int key at seed.""" @@ -51,7 +58,7 @@ cpdef np.int32_t murmurhash3_bytes_s32(bytes key, unsigned int seed): cpdef np.ndarray[np.uint32_t, ndim=1] murmurhash3_bytes_array_u32( np.ndarray[np.int32_t] key, unsigned int seed): """Compute 32bit murmurhash3 hashes of a key int array at seed.""" - # TODO make it possible to pass preallocated ouput array + # TODO make it possible to pass preallocated output array cdef np.ndarray[np.uint32_t, ndim=1] out = np.zeros(key.size, np.uint32) cdef Py_ssize_t i for i in range(key.shape[0]): @@ -63,7 +70,7 @@ cpdef np.ndarray[np.uint32_t, ndim=1] murmurhash3_bytes_array_u32( cpdef np.ndarray[np.int32_t, ndim=1] murmurhash3_bytes_array_s32( np.ndarray[np.int32_t] key, unsigned int seed): """Compute 32bit murmurhash3 hashes of a key int array at seed.""" - # TODO make it possible to pass preallocated ouput array + # TODO make it possible to pass preallocated output array cdef np.ndarray[np.int32_t, ndim=1] out = np.zeros(key.size, np.int32) cdef Py_ssize_t i for i in range(key.shape[0]): diff --git a/sklearn/utils/optimize.py b/sklearn/utils/optimize.py new file mode 100644 index 0000000000000..c1f8403438d11 --- /dev/null +++ b/sklearn/utils/optimize.py @@ -0,0 +1,176 @@ +""" +Our own implementation of the Newton algorithm + +Unlike the scipy.optimize version, this version of the Newton conjugate +gradient solver uses only one function call to retrieve the +func value, the gradient value and a callable for the Hessian matvec +product. If the function call is very expensive (e.g. for logistic +regression with large design matrix), this approach gives very +significant speedups. +""" +# This is a modified file from scipy.optimize +# Original authors: Travis Oliphant, Eric Jones +# Modifications by Gael Varoquaux +# License: BSD + +import numpy as np +import warnings +from scipy.optimize.linesearch import line_search_wolfe2, line_search_wolfe1 + + +class _LineSearchError(RuntimeError): + pass + + +def _line_search_wolfe12(f, fprime, xk, pk, gfk, old_fval, old_old_fval, + **kwargs): + """ + Same as line_search_wolfe1, but fall back to line_search_wolfe2 if + suitable step length is not found, and raise an exception if a + suitable step length is not found. + + Raises + ------ + _LineSearchError + If no suitable step size is found + + """ + ret = line_search_wolfe1(f, fprime, xk, pk, gfk, + old_fval, old_old_fval, + **kwargs) + + if ret[0] is None: + # line search failed: try different one. + ret = line_search_wolfe2(f, fprime, xk, pk, gfk, + old_fval, old_old_fval, **kwargs) + + if ret[0] is None: + raise _LineSearchError() + + return ret + + +def newton_cg(func_grad_hess, func, grad, x0, args=(), eps=1e-4, tol=1e-4, + maxiter=100): + """ + Minimization of scalar function of one or more variables using the + Newton-CG algorithm. + + Parameters + ---------- + func_grad_hess : callable + Should return the value of the function, the gradient, and a + callable returning the matvec product of the Hessian. + + func : callable + Should return the value of the function. + + grad : callable + Should return the function value and the gradient. This is used + by the linesearch functions. + + x0 : float + Initial guess. + + args: tuple, optional + Arguments passed to func_grad_hess, func and grad. + + tol : float + Stopping criterion. The iteration will stop when + ``max{|g_i | i = 1, ..., n} <= tol`` + where ``g_i`` is the i-th component of the gradient. + + eps : float, optional + If fhess is approximated, use this value for the step size. + + maxiter : int + Number of iterations. + + Returns + ------- + xk : float + Estimated minimum. + """ + x0 = np.asarray(x0).flatten() + xk = x0 + k = 1 + old_fval = func(x0, *args) + old_old_fval = None + + # Outer loop: our Newton iteration + while k <= maxiter: + + # Compute a search direction pk by applying the CG method to + # del2 f(xk) p = - fgrad f(xk) starting from 0. + fval, fgrad, fhess_p = func_grad_hess(xk, *args) + + absgrad = np.abs(fgrad) + if np.max(absgrad) < tol: + break + + maggrad = np.sum(absgrad) + eta = min([0.5, np.sqrt(maggrad)]) + termcond = eta * maggrad + xsupi = np.zeros(len(x0), dtype=x0.dtype) + ri = fgrad + psupi = -ri + i = 0 + dri0 = np.dot(ri, ri) + + # Inner loop: solve the Newton update by conjugate gradient, to + # avoid inverting the Hessian + while np.sum(np.abs(ri)) > termcond: + Ap = fhess_p(psupi) + # check curvature + curv = np.dot(psupi, Ap) + if 0 <= curv <= 3*np.finfo(np.float64).eps: + break + elif curv < 0: + if (i > 0): + break + else: + # fall back to steepest descent direction + xsupi = xsupi + dri0 / curv * psupi + break + alphai = dri0 / curv + xsupi = xsupi + alphai * psupi + ri = ri + alphai * Ap + dri1 = np.dot(ri, ri) + betai = dri1 / dri0 + psupi = -ri + betai * psupi + i = i + 1 + dri0 = dri1 # update np.dot(ri,ri) for next time. + + try: + alphak, fc, gc, old_fval, old_old_fval, gfkp1 = \ + _line_search_wolfe12(func, grad, xk, xsupi, fgrad, + old_fval, old_old_fval, args=args) + except _LineSearchError: + warnings.warn('Line Search failed') + break + + update = alphak * xsupi + xk = xk + update # upcast if necessary + k += 1 + + if k > maxiter: + warnings.warn("newton-cg failed to converge. Increase the " + "number of iterations.") + return xk + + +############################################################################### +# Tests + +if __name__ == "__main__": + A = np.random.normal(size=(10, 10)) + + def func(x): + Ax = A.dot(x) + return .5*(Ax).dot(Ax) + + def func_grad_hess(x): + return func(x), A.T.dot(A.dot(x)), lambda x: A.T.dot(A.dot(x)) + + x0 = np.ones(10) + out = newton_cg(func_grad_hess, func, x0) diff --git a/sklearn/utils/random.py b/sklearn/utils/random.py new file mode 100644 index 0000000000000..b2a7fa498c079 --- /dev/null +++ b/sklearn/utils/random.py @@ -0,0 +1,287 @@ +# Author: Hamzeh Alsalhi +# +# License: BSD 3 clause +from __future__ import division +import numpy as np +import scipy.sparse as sp +import operator +import array + +from sklearn.utils import check_random_state + +from ._random import sample_without_replacement + +__all__ = ['sample_without_replacement', 'choice'] + + +# This is a backport of np.random.choice from numpy 1.7 +# The function can be removed when we bump the requirements to >=1.7 +def choice(a, size=None, replace=True, p=None, random_state=None): + """ + choice(a, size=None, replace=True, p=None) + + Generates a random sample from a given 1-D array + + .. versionadded:: 1.7.0 + + Parameters + ----------- + a : 1-D array-like or int + If an ndarray, a random sample is generated from its elements. + If an int, the random sample is generated as if a was np.arange(n) + + size : int or tuple of ints, optional + Output shape. Default is None, in which case a single value is + returned. + + replace : boolean, optional + Whether the sample is with or without replacement. + + p : 1-D array-like, optional + The probabilities associated with each entry in a. + If not given the sample assumes a uniform distribtion over all + entries in a. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + + Returns + -------- + samples : 1-D ndarray, shape (size,) + The generated random samples + + Raises + ------- + ValueError + If a is an int and less than zero, if a or p are not 1-dimensional, + if a is an array-like of size 0, if p is not a vector of + probabilities, if a and p have different lengths, or if + replace=False and the sample size is greater than the population + size + + See Also + --------- + randint, shuffle, permutation + + Examples + --------- + Generate a uniform random sample from np.arange(5) of size 3: + + >>> np.random.choice(5, 3) # doctest: +SKIP + array([0, 3, 4]) + >>> #This is equivalent to np.random.randint(0,5,3) + + Generate a non-uniform random sample from np.arange(5) of size 3: + + >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) # doctest: +SKIP + array([3, 3, 0]) + + Generate a uniform random sample from np.arange(5) of size 3 without + replacement: + + >>> np.random.choice(5, 3, replace=False) # doctest: +SKIP + array([3,1,0]) + >>> #This is equivalent to np.random.shuffle(np.arange(5))[:3] + + Generate a non-uniform random sample from np.arange(5) of size + 3 without replacement: + + >>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0]) + ... # doctest: +SKIP + array([2, 3, 0]) + + Any of the above can be repeated with an arbitrary array-like + instead of just integers. For instance: + + >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher'] + >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3]) + ... # doctest: +SKIP + array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], + dtype='|S11') + + """ + random_state = check_random_state(random_state) + + # Format and Verify input + a = np.array(a, copy=False) + if a.ndim == 0: + try: + # __index__ must return an integer by python rules. + pop_size = operator.index(a.item()) + except TypeError: + raise ValueError("a must be 1-dimensional or an integer") + if pop_size <= 0: + raise ValueError("a must be greater than 0") + elif a.ndim != 1: + raise ValueError("a must be 1-dimensional") + else: + pop_size = a.shape[0] + if pop_size is 0: + raise ValueError("a must be non-empty") + + if None != p: + p = np.array(p, dtype=np.double, ndmin=1, copy=False) + if p.ndim != 1: + raise ValueError("p must be 1-dimensional") + if p.size != pop_size: + raise ValueError("a and p must have same size") + if np.any(p < 0): + raise ValueError("probabilities are not non-negative") + if not np.allclose(p.sum(), 1): + raise ValueError("probabilities do not sum to 1") + + shape = size + if shape is not None: + size = np.prod(shape, dtype=np.intp) + else: + size = 1 + + # Actual sampling + if replace: + if None != p: + cdf = p.cumsum() + cdf /= cdf[-1] + uniform_samples = random_state.random_sample(shape) + idx = cdf.searchsorted(uniform_samples, side='right') + # searchsorted returns a scalar + idx = np.array(idx, copy=False) + else: + idx = random_state.randint(0, pop_size, size=shape) + else: + if size > pop_size: + raise ValueError("Cannot take a larger sample than " + "population when 'replace=False'") + + if None != p: + if np.sum(p > 0) < size: + raise ValueError("Fewer non-zero entries in p than size") + n_uniq = 0 + p = p.copy() + found = np.zeros(shape, dtype=np.int) + flat_found = found.ravel() + while n_uniq < size: + x = random_state.rand(size - n_uniq) + if n_uniq > 0: + p[flat_found[0:n_uniq]] = 0 + cdf = np.cumsum(p) + cdf /= cdf[-1] + new = cdf.searchsorted(x, side='right') + _, unique_indices = np.unique(new, return_index=True) + unique_indices.sort() + new = new.take(unique_indices) + flat_found[n_uniq:n_uniq + new.size] = new + n_uniq += new.size + idx = found + else: + idx = random_state.permutation(pop_size)[:size] + if shape is not None: + idx.shape = shape + + if shape is None and isinstance(idx, np.ndarray): + # In most cases a scalar will have been made an array + idx = idx.item(0) + + # Use samples as indices for a if a is array-like + if a.ndim == 0: + return idx + + if shape is not None and idx.ndim == 0: + # If size == () then the user requested a 0-d array as opposed to + # a scalar object when size is None. However a[idx] is always a + # scalar and not an array. So this makes sure the result is an + # array, taking into account that np.array(item) may not work + # for object arrays. + res = np.empty((), dtype=a.dtype) + res[()] = a[idx] + return res + + return a[idx] + + +def random_choice_csc(n_samples, classes, class_probability=None, + random_state=None): + """Generate a sparse random matrix given column class distributions + + Parameters + ---------- + n_samples : int, + Number of samples to draw in each column. + + classes : list of size n_outputs of arrays of size (n_classes,) + List of classes for each column. + + class_probability : list of size n_outputs of arrays of size (n_classes,) + Optional (default=None). Class distribution of each column. If None the + uniform distribution is assumed. + + random_state : int, RandomState instance or None, optional (default=None) + If int, random_state is the seed used by the random number generator; + If RandomState instance, random_state is the random number generator; + If None, the random number generator is the RandomState instance used + by `np.random`. + + Returns + ------- + random_matrix : sparse csc matrix of size (n_samples, n_outputs) + + """ + data = array.array('i') + indices = array.array('i') + indptr = array.array('i', [0]) + + for j in range(len(classes)): + classes[j] = np.asarray(classes[j]) + if classes[j].dtype.kind != 'i': + raise ValueError("class dtype %s is not supported" % + classes[j].dtype) + classes[j] = classes[j].astype(int) + + # use uniform distribution if no class_probability is given + if class_probability is None: + class_prob_j = np.empty(shape=classes[j].shape[0]) + class_prob_j.fill(1 / classes[j].shape[0]) + else: + class_prob_j = np.asarray(class_probability[j]) + + if np.sum(class_prob_j) != 1.0: + raise ValueError("Probability array at index {0} does not sum to " + "one".format(j)) + + if class_prob_j.shape[0] != classes[j].shape[0]: + raise ValueError("classes[{0}] (length {1}) and " + "class_probability[{0}] (length {2}) have " + "different length.".format(j, + classes[j].shape[0], + class_prob_j.shape[0])) + + # If 0 is not present in the classes insert it with a probability 0.0 + if 0 not in classes[j]: + classes[j] = np.insert(classes[j], 0, 0) + class_prob_j = np.insert(class_prob_j, 0, 0.0) + + # If there are nonzero classes choose randomly using class_probability + if classes[j].shape[0] > 1: + p_nonzero = 1 - class_prob_j[classes[j] == 0] + nnz = int(n_samples * p_nonzero) + ind_sample = sample_without_replacement(n_population=n_samples, + n_samples=nnz, + random_state=random_state) + indices.extend(ind_sample) + + # Normalize probabilites for the nonzero elements + classes_j_nonzero = classes[j] != 0 + class_probability_nz = class_prob_j[classes_j_nonzero] + class_probability_nz_norm = (class_probability_nz / + np.sum(class_probability_nz)) + classes_ind = np.searchsorted(class_probability_nz_norm.cumsum(), + np.random.rand(nnz)) + data.extend(classes[j][classes_j_nonzero][classes_ind]) + indptr.append(len(indices)) + + return sp.csc_matrix((data, indices, indptr), + (n_samples, len(classes)), + dtype=int) diff --git a/sklearn/utils/seq_dataset.c b/sklearn/utils/seq_dataset.c index ecb26f0e7a90c..2ac39050c2adc 100644 --- a/sklearn/utils/seq_dataset.c +++ b/sklearn/utils/seq_dataset.c @@ -1,16 +1,29 @@ -/* Generated by Cython 0.15.1 on Sun Mar 18 20:56:58 2012 */ +/* Generated by Cython 0.20.1 on Sat Mar 15 15:41:05 2014 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. #else - +#define CYTHON_ABI "0_20_1" #include /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -22,36 +35,50 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - -#if PY_VERSION_HEX < 0x02040000 - #define METH_COEXIST 0 - #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) - #define PyDict_Contains(d,o) PySequence_Contains(d,o) +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if CYTHON_COMPILING_IN_PYPY +#define Py_OptimizeFlag 0 #endif - #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -59,7 +86,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -73,7 +99,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -83,24 +108,74 @@ #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT) + #define Py_TPFLAGS_IS_ABSTRACT 0 +#endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -108,7 +183,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -127,7 +201,14 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -135,9 +216,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -153,13 +232,12 @@ #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - -#if PY_VERSION_HEX < 0x03020000 +#if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong @@ -167,16 +245,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -195,11 +263,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -209,7 +275,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -217,6 +282,49 @@ #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus @@ -232,10 +340,12 @@ #include #define __PYX_HAVE__sklearn__utils__seq_dataset #define __PYX_HAVE_API__sklearn__utils__seq_dataset +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" +#include "limits.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -244,21 +354,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -266,31 +361,148 @@ # else # define CYTHON_UNUSED # endif -# elif defined(__ICC) || defined(__INTEL_COMPILER) +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif #ifdef __GNUC__ @@ -306,8 +518,9 @@ static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -316,7 +529,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -326,7 +538,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -334,18 +545,54 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { "seq_dataset.pyx", - "numpy.pxd", + "__init__.pxd", + "type.pxd", }; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + -/* "numpy.pxd":719 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -354,7 +601,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -363,7 +610,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -372,7 +619,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -381,7 +628,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -390,7 +637,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -399,7 +646,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -408,7 +655,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -417,7 +664,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -426,7 +673,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -435,7 +682,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -444,7 +691,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -453,7 +700,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -462,7 +709,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -471,7 +718,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -480,7 +727,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -489,7 +736,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -498,7 +745,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -507,7 +754,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -516,7 +763,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -525,7 +772,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -533,25 +780,6 @@ typedef npy_double __pyx_t_5numpy_double_t; * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; - -/* "sklearn/utils/seq_dataset.pxd":5 - * cimport numpy as np - * - * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< - * ctypedef np.int32_t INTEGER - * - */ -typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE; - -/* "sklearn/utils/seq_dataset.pxd":6 - * - * ctypedef np.float64_t DOUBLE - * ctypedef np.int32_t INTEGER # <<<<<<<<<<<<<< - * - * - */ -typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER; - #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -572,12 +800,13 @@ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER; typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset; struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset; struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset; -/* "numpy.pxd":758 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -586,7 +815,7 @@ struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -595,7 +824,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -604,7 +833,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -613,67 +842,75 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; */ typedef npy_cdouble __pyx_t_5numpy_complex_t; -/* "sklearn/utils/seq_dataset.pxd":9 +/* "sklearn/utils/seq_dataset.pyx":184 * * - * cdef class SequentialDataset: # <<<<<<<<<<<<<< - * cdef Py_ssize_t n_samples + * cdef enum: # <<<<<<<<<<<<<< + * RAND_R_MAX = 0x7FFFFFFF + * + */ +enum { + __pyx_e_7sklearn_5utils_11seq_dataset_RAND_R_MAX = 0x7FFFFFFF +}; + +/* "sklearn/utils/seq_dataset.pxd":8 + * # iterators over the rows of a matrix X and corresponding target values y. * + * cdef class SequentialDataset: # <<<<<<<<<<<<<< + * cdef int current_index + * cdef np.ndarray index */ struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset { PyObject_HEAD struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_vtab; + int current_index; + PyArrayObject *index; + int *index_data_ptr; Py_ssize_t n_samples; }; -/* "sklearn/utils/seq_dataset.pxd":17 +/* "sklearn/utils/seq_dataset.pxd":19 * * * cdef class ArrayDataset(SequentialDataset): # <<<<<<<<<<<<<< * cdef Py_ssize_t n_features - * cdef int current_index + * cdef int stride */ struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset { struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; Py_ssize_t n_features; - int current_index; int stride; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *X_data_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *Y_data_ptr; + double *X_data_ptr; + double *Y_data_ptr; PyArrayObject *feature_indices; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *feature_indices_ptr; - PyArrayObject *index; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *index_data_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *sample_weight_data; + int *feature_indices_ptr; + double *sample_weight_data; }; -/* "sklearn/utils/seq_dataset.pxd":34 +/* "sklearn/utils/seq_dataset.pxd":32 * * * cdef class CSRDataset(SequentialDataset): # <<<<<<<<<<<<<< - * cdef int current_index * cdef int stride + * cdef double *X_data_ptr */ struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset { struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; - int current_index; int stride; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *X_data_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *X_indptr_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *X_indices_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *Y_data_ptr; + double *X_data_ptr; + int *X_indptr_ptr; + int *X_indices_ptr; + double *Y_data_ptr; PyArrayObject *feature_indices; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *feature_indices_ptr; - PyArrayObject *index; - __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *index_data_ptr; - __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *sample_weight_data; + int *feature_indices_ptr; + double *sample_weight_data; }; -/* "sklearn/utils/seq_dataset.pyx":16 +/* "sklearn/utils/seq_dataset.pyx":17 * * * cdef class SequentialDataset: # <<<<<<<<<<<<<< @@ -682,44 +919,41 @@ struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset { */ struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset { - void (*next)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE **, __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER **, int *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *); - void (*shuffle)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, PyObject *); + void (*next)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, double **, int **, int *, double *, double *); + void (*shuffle)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, __pyx_t_5numpy_uint32_t); }; static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset; -/* "sklearn/utils/seq_dataset.pyx":112 +/* "sklearn/utils/seq_dataset.pyx":54 * * - * cdef class CSRDataset(SequentialDataset): # <<<<<<<<<<<<<< - * """A ``SequentialDataset`` backed by a scipy sparse CSR matrix. """ + * cdef class ArrayDataset(SequentialDataset): # <<<<<<<<<<<<<< + * """Dataset backed by a two-dimensional numpy array. * */ -struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_CSRDataset { +struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset { struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_CSRDataset *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset; +static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset; -/* "sklearn/utils/seq_dataset.pyx":46 +/* "sklearn/utils/seq_dataset.pyx":121 * * - * cdef class ArrayDataset(SequentialDataset): # <<<<<<<<<<<<<< - * """Dataset backed by a two-dimensional numpy array. + * cdef class CSRDataset(SequentialDataset): # <<<<<<<<<<<<<< + * """A ``SequentialDataset`` backed by a scipy sparse CSR matrix. """ * */ -struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset { +struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_CSRDataset { struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_base; }; -static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset; - - +static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_CSRDataset *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset; #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -732,8 +966,21 @@ static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -744,7 +991,7 @@ static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -755,71 +1002,117 @@ static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename, + int full_traceback); /*proto*/ + static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); /*proto*/ -/* Run-time type information about structs used with buffers */ -struct __Pyx_StructField_; - -typedef struct { - const char* name; /* for error messages only */ - struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ -} __Pyx_TypeInfo; - -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; - -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; - - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ -#if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); -static void __Pyx_ReleaseBuffer(Py_buffer *view); -#else -#define __Pyx_GetBuffer PyObject_GetBuffer -#define __Pyx_ReleaseBuffer PyBuffer_Release -#endif +static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif -Py_ssize_t __Pyx_zeros[] = {0, 0}; -Py_ssize_t __Pyx_minusones[] = {-1, -1}; -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -833,8 +1126,7 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - -#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else @@ -920,62 +1212,57 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); - -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename); /*proto*/ +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); static int __Pyx_check_binary_version(void); -static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ @@ -986,238 +1273,333 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ - -/* Module declarations from 'cython.cython.view' */ /* Module declarations from 'cython' */ +/* Module declarations from 'libc.limits' */ + /* Module declarations from 'sklearn.utils.seq_dataset' */ static PyTypeObject *__pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset = 0; static PyTypeObject *__pyx_ptype_7sklearn_5utils_11seq_dataset_ArrayDataset = 0; static PyTypeObject *__pyx_ptype_7sklearn_5utils_11seq_dataset_CSRDataset = 0; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE), 'R' }; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_INTEGER = { "INTEGER", NULL, sizeof(__pyx_t_7sklearn_5utils_11seq_dataset_INTEGER), 'I' }; +static CYTHON_INLINE __pyx_t_5numpy_uint32_t __pyx_f_7sklearn_5utils_11seq_dataset_our_rand_r(__pyx_t_5numpy_uint32_t *); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 }; #define __Pyx_MODULE_NAME "sklearn.utils.seq_dataset" int __pyx_module_is_main_sklearn__utils__seq_dataset = 0; /* Implementation of 'sklearn.utils.seq_dataset' */ static PyObject *__pyx_builtin_NotImplementedError; -static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; -static char __pyx_k_1[] = "ndarray is not C contiguous"; -static char __pyx_k_3[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_5[] = "Non-native byte order not supported"; -static char __pyx_k_7[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_8[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_11[] = "Format string allocated too short."; -static char __pyx_k__B[] = "B"; -static char __pyx_k__H[] = "H"; -static char __pyx_k__I[] = "I"; -static char __pyx_k__L[] = "L"; -static char __pyx_k__O[] = "O"; -static char __pyx_k__Q[] = "Q"; -static char __pyx_k__X[] = "X"; -static char __pyx_k__Y[] = "Y"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__d[] = "d"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__g[] = "g"; -static char __pyx_k__h[] = "h"; -static char __pyx_k__i[] = "i"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__q[] = "q"; -static char __pyx_k__Zd[] = "Zd"; -static char __pyx_k__Zf[] = "Zf"; -static char __pyx_k__Zg[] = "Zg"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__dtype[] = "dtype"; -static char __pyx_k__int32[] = "int32"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__range[] = "range"; -static char __pyx_k__X_data[] = "X_data"; -static char __pyx_k__arange[] = "arange"; -static char __pyx_k__random[] = "random"; -static char __pyx_k__shuffle[] = "shuffle"; -static char __pyx_k__X_indptr[] = "X_indptr"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__X_indices[] = "X_indices"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__RandomState[] = "RandomState"; -static char __pyx_k__RuntimeError[] = "RuntimeError"; -static char __pyx_k__sample_weight[] = "sample_weight"; -static char __pyx_k__sample_weights[] = "sample_weights"; -static char __pyx_k__NotImplementedError[] = "NotImplementedError"; -static PyObject *__pyx_kp_u_1; -static PyObject *__pyx_kp_u_11; -static PyObject *__pyx_kp_u_3; -static PyObject *__pyx_kp_u_5; -static PyObject *__pyx_kp_u_7; -static PyObject *__pyx_kp_u_8; -static PyObject *__pyx_n_s__NotImplementedError; -static PyObject *__pyx_n_s__RandomState; -static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s__X; -static PyObject *__pyx_n_s__X_data; -static PyObject *__pyx_n_s__X_indices; -static PyObject *__pyx_n_s__X_indptr; -static PyObject *__pyx_n_s__Y; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__arange; -static PyObject *__pyx_n_s__dtype; -static PyObject *__pyx_n_s__int32; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__random; -static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__sample_weight; -static PyObject *__pyx_n_s__sample_weights; -static PyObject *__pyx_n_s__shuffle; +static int __pyx_pf_7sklearn_5utils_11seq_dataset_12ArrayDataset___cinit__(struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx_v_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, PyArrayObject *__pyx_v_sample_weights); /* proto */ +static int __pyx_pf_7sklearn_5utils_11seq_dataset_10CSRDataset___cinit__(struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *__pyx_v_self, PyArrayObject *__pyx_v_X_data, PyArrayObject *__pyx_v_X_indptr, PyArrayObject *__pyx_v_X_indices, PyArrayObject *__pyx_v_Y, PyArrayObject *__pyx_v_sample_weight); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static PyObject *__pyx_tp_new_7sklearn_5utils_11seq_dataset_SequentialDataset(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_5utils_11seq_dataset_ArrayDataset(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_7sklearn_5utils_11seq_dataset_CSRDataset(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_B[] = "B"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_X[] = "X"; +static char __pyx_k_Y[] = "Y"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_intc[] = "intc"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_X_data[] = "X_data"; +static char __pyx_k_arange[] = "arange"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_X_indptr[] = "X_indptr"; +static char __pyx_k_itemsize[] = "itemsize"; +static char __pyx_k_X_indices[] = "X_indices"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k_sample_weight[] = "sample_weight"; +static char __pyx_k_sample_weights[] = "sample_weights"; +static char __pyx_k_pyx_releasebuffer[] = "__pyx_releasebuffer"; +static char __pyx_k_NotImplementedError[] = "NotImplementedError"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_More_than_d_samples_or_features[] = "More than %d samples or features not supported; got (%d, %d)."; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_kp_s_More_than_d_samples_or_features; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_s_NotImplementedError; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_n_s_X_data; +static PyObject *__pyx_n_s_X_indices; +static PyObject *__pyx_n_s_X_indptr; +static PyObject *__pyx_n_s_Y; +static PyObject *__pyx_n_s_arange; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_intc; +static PyObject *__pyx_n_s_itemsize; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_releasebuffer; +static PyObject *__pyx_n_s_pyx_vtable; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_sample_weight; +static PyObject *__pyx_n_s_sample_weights; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; static PyObject *__pyx_int_0; -static PyObject *__pyx_int_15; -static PyObject *__pyx_k_tuple_2; -static PyObject *__pyx_k_tuple_4; -static PyObject *__pyx_k_tuple_6; -static PyObject *__pyx_k_tuple_9; -static PyObject *__pyx_k_tuple_10; -static PyObject *__pyx_k_tuple_12; - -/* "sklearn/utils/seq_dataset.pyx":19 +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; + +/* "sklearn/utils/seq_dataset.pyx":20 * """Base class for datasets with sequential data access. """ * - * cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, # <<<<<<<<<<<<<< - * int *nnz, DOUBLE *y, DOUBLE *sample_weight): + * cdef void next(self, double **x_data_ptr, int **x_ind_ptr, # <<<<<<<<<<<<<< + * int *nnz, double *y, double *sample_weight) nogil: * """Get the next example ``x`` from the dataset. */ -static void __pyx_f_7sklearn_5utils_11seq_dataset_17SequentialDataset_next(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_self, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE **__pyx_v_x_data_ptr, __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER **__pyx_v_x_ind_ptr, int *__pyx_v_nnz, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *__pyx_v_y, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *__pyx_v_sample_weight) { +static void __pyx_f_7sklearn_5utils_11seq_dataset_17SequentialDataset_next(CYTHON_UNUSED struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_self, CYTHON_UNUSED double **__pyx_v_x_data_ptr, CYTHON_UNUSED int **__pyx_v_x_ind_ptr, CYTHON_UNUSED int *__pyx_v_nnz, CYTHON_UNUSED double *__pyx_v_y, CYTHON_UNUSED double *__pyx_v_sample_weight) { __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("next"); + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("next", 0); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + /*try:*/ { - /* "sklearn/utils/seq_dataset.pyx":39 + /* "sklearn/utils/seq_dataset.pyx":40 * The weight of the next example. * """ - * raise NotImplementedError() # <<<<<<<<<<<<<< + * with gil: # <<<<<<<<<<<<<< + * raise NotImplementedError() * - * cdef void shuffle(self, seed): */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_NotImplementedError, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + #endif + /*try:*/ { + + /* "sklearn/utils/seq_dataset.pyx":41 + * """ + * with gil: + * raise NotImplementedError() # <<<<<<<<<<<<<< + * + * cdef void shuffle(self, np.uint32_t seed) nogil: + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_NotImplementedError, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L7_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L7_error;} + } + + /* "sklearn/utils/seq_dataset.pyx":40 + * The weight of the next example. + * """ + * with gil: # <<<<<<<<<<<<<< + * raise NotImplementedError() + * + */ + /*finally:*/ { + __pyx_L7_error: { + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif + goto __pyx_L4_error; + } + } + } + } + + /* "sklearn/utils/seq_dataset.pyx":22 + * cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + * int *nnz, double *y, double *sample_weight) nogil: + * """Get the next example ``x`` from the dataset. # <<<<<<<<<<<<<< + * + * Parameters + */ + /*finally:*/ { + __pyx_L4_error: { + #ifdef WITH_THREAD + __pyx_gilstate_save = PyGILState_Ensure(); + #endif + goto __pyx_L1_error; + } + } + + /* "sklearn/utils/seq_dataset.pyx":20 + * """Base class for datasets with sequential data access. """ + * + * cdef void next(self, double **x_data_ptr, int **x_ind_ptr, # <<<<<<<<<<<<<< + * int *nnz, double *y, double *sample_weight) nogil: + * """Get the next example ``x`` from the dataset. + */ + /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_WriteUnraisable("sklearn.utils.seq_dataset.SequentialDataset.next", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_WriteUnraisable("sklearn.utils.seq_dataset.SequentialDataset.next", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); __pyx_L0:; - __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + PyGILState_Release(__pyx_gilstate_save); + #endif } -/* "sklearn/utils/seq_dataset.pyx":41 - * raise NotImplementedError() +/* "sklearn/utils/seq_dataset.pyx":43 + * raise NotImplementedError() * - * cdef void shuffle(self, seed): # <<<<<<<<<<<<<< - * """Permutes the ordering of examples. """ - * raise NotImplementedError() + * cdef void shuffle(self, np.uint32_t seed) nogil: # <<<<<<<<<<<<<< + * """Permutes the ordering of examples.""" + * # Fisher-Yates shuffle */ -static void __pyx_f_7sklearn_5utils_11seq_dataset_17SequentialDataset_shuffle(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_self, PyObject *__pyx_v_seed) { - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("shuffle"); +static void __pyx_f_7sklearn_5utils_11seq_dataset_17SequentialDataset_shuffle(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *__pyx_v_self, __pyx_t_5numpy_uint32_t __pyx_v_seed) { + int *__pyx_v_ind; + int __pyx_v_n; + unsigned int __pyx_v_i; + unsigned int __pyx_v_j; + int *__pyx_t_1; + Py_ssize_t __pyx_t_2; + long __pyx_t_3; + unsigned int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; - /* "sklearn/utils/seq_dataset.pyx":43 - * cdef void shuffle(self, seed): - * """Permutes the ordering of examples. """ - * raise NotImplementedError() # <<<<<<<<<<<<<< + /* "sklearn/utils/seq_dataset.pyx":46 + * """Permutes the ordering of examples.""" + * # Fisher-Yates shuffle + * cdef int *ind = self.index_data_ptr # <<<<<<<<<<<<<< + * cdef int n = self.n_samples + * cdef unsigned i, j + */ + __pyx_t_1 = __pyx_v_self->index_data_ptr; + __pyx_v_ind = __pyx_t_1; + + /* "sklearn/utils/seq_dataset.pyx":47 + * # Fisher-Yates shuffle + * cdef int *ind = self.index_data_ptr + * cdef int n = self.n_samples # <<<<<<<<<<<<<< + * cdef unsigned i, j + * for i in range(n - 1): + */ + __pyx_t_2 = __pyx_v_self->n_samples; + __pyx_v_n = __pyx_t_2; + + /* "sklearn/utils/seq_dataset.pyx":49 + * cdef int n = self.n_samples + * cdef unsigned i, j + * for i in range(n - 1): # <<<<<<<<<<<<<< + * j = i + our_rand_r(&seed) % (n - i) + * ind[i], ind[j] = ind[j], ind[i] + */ + __pyx_t_3 = (__pyx_v_n - 1); + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + + /* "sklearn/utils/seq_dataset.pyx":50 + * cdef unsigned i, j + * for i in range(n - 1): + * j = i + our_rand_r(&seed) % (n - i) # <<<<<<<<<<<<<< + * ind[i], ind[j] = ind[j], ind[i] + * + */ + __pyx_v_j = (__pyx_v_i + (__pyx_f_7sklearn_5utils_11seq_dataset_our_rand_r((&__pyx_v_seed)) % (__pyx_v_n - __pyx_v_i))); + + /* "sklearn/utils/seq_dataset.pyx":51 + * for i in range(n - 1): + * j = i + our_rand_r(&seed) % (n - i) + * ind[i], ind[j] = ind[j], ind[i] # <<<<<<<<<<<<<< * * */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_NotImplementedError, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = (__pyx_v_ind[__pyx_v_j]); + __pyx_t_6 = (__pyx_v_ind[__pyx_v_i]); + (__pyx_v_ind[__pyx_v_i]) = __pyx_t_5; + (__pyx_v_ind[__pyx_v_j]) = __pyx_t_6; + } - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_WriteUnraisable("sklearn.utils.seq_dataset.SequentialDataset.shuffle", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_RefNannyFinishContext(); + /* "sklearn/utils/seq_dataset.pyx":43 + * raise NotImplementedError() + * + * cdef void shuffle(self, np.uint32_t seed) nogil: # <<<<<<<<<<<<<< + * """Permutes the ordering of examples.""" + * # Fisher-Yates shuffle + */ + + /* function exit code */ } -/* "sklearn/utils/seq_dataset.pyx":53 +/* "sklearn/utils/seq_dataset.pyx":61 * """ * - * def __cinit__(self, np.ndarray[DOUBLE, ndim=2, mode='c'] X, # <<<<<<<<<<<<<< - * np.ndarray[DOUBLE, ndim=1, mode='c'] Y, - * np.ndarray[DOUBLE, ndim=1, mode='c'] sample_weights): + * def __cinit__(self, np.ndarray[double, ndim=2, mode='c'] X, # <<<<<<<<<<<<<< + * np.ndarray[double, ndim=1, mode='c'] Y, + * np.ndarray[double, ndim=1, mode='c'] sample_weights): */ -static int __pyx_pf_7sklearn_5utils_11seq_dataset_12ArrayDataset___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pf_7sklearn_5utils_11seq_dataset_12ArrayDataset___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static int __pyx_pw_7sklearn_5utils_11seq_dataset_12ArrayDataset_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_5utils_11seq_dataset_12ArrayDataset_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_X = 0; PyArrayObject *__pyx_v_Y = 0; PyArrayObject *__pyx_v_sample_weights = 0; - PyArrayObject *__pyx_v_feature_indices = 0; - PyArrayObject *__pyx_v_index = 0; - Py_buffer __pyx_bstruct_index; - Py_ssize_t __pyx_bstride_0_index = 0; - Py_ssize_t __pyx_bshape_0_index = 0; - Py_buffer __pyx_bstruct_sample_weights; - Py_ssize_t __pyx_bstride_0_sample_weights = 0; - Py_ssize_t __pyx_bshape_0_sample_weights = 0; - Py_buffer __pyx_bstruct_feature_indices; - Py_ssize_t __pyx_bstride_0_feature_indices = 0; - Py_ssize_t __pyx_bshape_0_feature_indices = 0; - Py_buffer __pyx_bstruct_Y; - Py_ssize_t __pyx_bstride_0_Y = 0; - Py_ssize_t __pyx_bshape_0_Y = 0; - Py_buffer __pyx_bstruct_X; - Py_ssize_t __pyx_bstride_0_X = 0; - Py_ssize_t __pyx_bstride_1_X = 0; - Py_ssize_t __pyx_bshape_0_X = 0; - Py_ssize_t __pyx_bshape_1_X = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - PyArrayObject *__pyx_t_7 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X,&__pyx_n_s__Y,&__pyx_n_s__sample_weights,0}; - __Pyx_RefNannySetupContext("__cinit__"); + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_Y,&__pyx_n_s_sample_weights,0}; PyObject* values[3] = {0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); @@ -1225,26 +1607,23 @@ static int __pyx_pf_7sklearn_5utils_11seq_dataset_12ArrayDataset___cinit__(PyObj default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__Y); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sample_weights); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sample_weights)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -1259,289 +1638,423 @@ static int __pyx_pf_7sklearn_5utils_11seq_dataset_12ArrayDataset___cinit__(PyObj } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.utils.seq_dataset.ArrayDataset.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_feature_indices.buf = NULL; - __pyx_bstruct_index.buf = NULL; - __pyx_bstruct_X.buf = NULL; - __pyx_bstruct_Y.buf = NULL; - __pyx_bstruct_sample_weights.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weights), __pyx_ptype_5numpy_ndarray, 1, "sample_weights", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X), __pyx_ptype_5numpy_ndarray, 1, "X", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weights), __pyx_ptype_5numpy_ndarray, 1, "sample_weights", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_11seq_dataset_12ArrayDataset___cinit__(((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self), __pyx_v_X, __pyx_v_Y, __pyx_v_sample_weights); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_5utils_11seq_dataset_12ArrayDataset___cinit__(struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx_v_self, PyArrayObject *__pyx_v_X, PyArrayObject *__pyx_v_Y, PyArrayObject *__pyx_v_sample_weights) { + PyArrayObject *__pyx_v_feature_indices = 0; + PyArrayObject *__pyx_v_index = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X; + __Pyx_Buffer __pyx_pybuffer_X; + __Pyx_LocalBuf_ND __pyx_pybuffernd_Y; + __Pyx_Buffer __pyx_pybuffer_Y; + __Pyx_LocalBuf_ND __pyx_pybuffernd_feature_indices; + __Pyx_Buffer __pyx_pybuffer_feature_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_index; + __Pyx_Buffer __pyx_pybuffer_index; + __Pyx_LocalBuf_ND __pyx_pybuffernd_sample_weights; + __Pyx_Buffer __pyx_pybuffer_sample_weights; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyArrayObject *__pyx_t_9 = NULL; + int __pyx_t_10; + PyArrayObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __pyx_pybuffer_feature_indices.pybuffer.buf = NULL; + __pyx_pybuffer_feature_indices.refcount = 0; + __pyx_pybuffernd_feature_indices.data = NULL; + __pyx_pybuffernd_feature_indices.rcbuffer = &__pyx_pybuffer_feature_indices; + __pyx_pybuffer_index.pybuffer.buf = NULL; + __pyx_pybuffer_index.refcount = 0; + __pyx_pybuffernd_index.data = NULL; + __pyx_pybuffernd_index.rcbuffer = &__pyx_pybuffer_index; + __pyx_pybuffer_X.pybuffer.buf = NULL; + __pyx_pybuffer_X.refcount = 0; + __pyx_pybuffernd_X.data = NULL; + __pyx_pybuffernd_X.rcbuffer = &__pyx_pybuffer_X; + __pyx_pybuffer_Y.pybuffer.buf = NULL; + __pyx_pybuffer_Y.refcount = 0; + __pyx_pybuffernd_Y.data = NULL; + __pyx_pybuffernd_Y.rcbuffer = &__pyx_pybuffer_Y; + __pyx_pybuffer_sample_weights.pybuffer.buf = NULL; + __pyx_pybuffer_sample_weights.refcount = 0; + __pyx_pybuffernd_sample_weights.data = NULL; + __pyx_pybuffernd_sample_weights.rcbuffer = &__pyx_pybuffer_sample_weights; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X.rcbuffer->pybuffer, (PyObject*)__pyx_v_X, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_X = __pyx_bstruct_X.strides[0]; __pyx_bstride_1_X = __pyx_bstruct_X.strides[1]; - __pyx_bshape_0_X = __pyx_bstruct_X.shape[0]; __pyx_bshape_1_X = __pyx_bstruct_X.shape[1]; + __pyx_pybuffernd_X.diminfo[0].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X.diminfo[0].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_X.diminfo[1].strides = __pyx_pybuffernd_X.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_X.diminfo[1].shape = __pyx_pybuffernd_X.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_Y, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Y.rcbuffer->pybuffer, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_Y = __pyx_bstruct_Y.strides[0]; - __pyx_bshape_0_Y = __pyx_bstruct_Y.shape[0]; + __pyx_pybuffernd_Y.diminfo[0].strides = __pyx_pybuffernd_Y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_Y.diminfo[0].shape = __pyx_pybuffernd_Y.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_sample_weights, (PyObject*)__pyx_v_sample_weights, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weights.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weights, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_sample_weights.diminfo[0].strides = __pyx_pybuffernd_sample_weights.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weights.diminfo[0].shape = __pyx_pybuffernd_sample_weights.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/utils/seq_dataset.pyx":78 + * array of dtype double. + * """ + * if X.shape[0] > INT_MAX or X.shape[1] > INT_MAX: # <<<<<<<<<<<<<< + * raise ValueError("More than %d samples or features not supported;" + * " got (%d, %d)." + */ + __pyx_t_1 = (((__pyx_v_X->dimensions[0]) > INT_MAX) != 0); + if (!__pyx_t_1) { + __pyx_t_2 = (((__pyx_v_X->dimensions[1]) > INT_MAX) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; } - __pyx_bstride_0_sample_weights = __pyx_bstruct_sample_weights.strides[0]; - __pyx_bshape_0_sample_weights = __pyx_bstruct_sample_weights.shape[0]; + if (__pyx_t_3) { + + /* "sklearn/utils/seq_dataset.pyx":81 + * raise ValueError("More than %d samples or features not supported;" + * " got (%d, %d)." + * % (INT_MAX, X.shape[0], X.shape[1])) # <<<<<<<<<<<<<< + * + * self.n_samples = X.shape[0] + */ + __pyx_t_4 = __Pyx_PyInt_From_int(INT_MAX); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->dimensions[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->dimensions[1])); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyTuple_New(3); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_7, 2, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyString_Format(__pyx_kp_s_More_than_d_samples_or_features, __pyx_t_7); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - /* "sklearn/utils/seq_dataset.pyx":70 - * array of dtype np.float64. + /* "sklearn/utils/seq_dataset.pyx":79 * """ + * if X.shape[0] > INT_MAX or X.shape[1] > INT_MAX: + * raise ValueError("More than %d samples or features not supported;" # <<<<<<<<<<<<<< + * " got (%d, %d)." + * % (INT_MAX, X.shape[0], X.shape[1])) + */ + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/utils/seq_dataset.pyx":83 + * % (INT_MAX, X.shape[0], X.shape[1])) + * * self.n_samples = X.shape[0] # <<<<<<<<<<<<<< * self.n_features = X.shape[1] - * cdef np.ndarray[INTEGER, ndim=1, + * cdef np.ndarray[int, ndim=1, */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->__pyx_base.n_samples = (__pyx_v_X->dimensions[0]); + __pyx_v_self->__pyx_base.n_samples = (__pyx_v_X->dimensions[0]); - /* "sklearn/utils/seq_dataset.pyx":71 - * """ + /* "sklearn/utils/seq_dataset.pyx":84 + * * self.n_samples = X.shape[0] * self.n_features = X.shape[1] # <<<<<<<<<<<<<< - * cdef np.ndarray[INTEGER, ndim=1, + * cdef np.ndarray[int, ndim=1, * mode='c'] feature_indices = np.arange(0, self.n_features, */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->n_features = (__pyx_v_X->dimensions[1]); + __pyx_v_self->n_features = (__pyx_v_X->dimensions[1]); - /* "sklearn/utils/seq_dataset.pyx":73 + /* "sklearn/utils/seq_dataset.pyx":86 * self.n_features = X.shape[1] - * cdef np.ndarray[INTEGER, ndim=1, + * cdef np.ndarray[int, ndim=1, * mode='c'] feature_indices = np.arange(0, self.n_features, # <<<<<<<<<<<<<< - * dtype=np.int32) + * dtype=np.intc) * self.feature_indices = feature_indices */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__arange); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromSsize_t(((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_arange); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_self->n_features); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); - /* "sklearn/utils/seq_dataset.pyx":74 - * cdef np.ndarray[INTEGER, ndim=1, + /* "sklearn/utils/seq_dataset.pyx":87 + * cdef np.ndarray[int, ndim=1, * mode='c'] feature_indices = np.arange(0, self.n_features, - * dtype=np.int32) # <<<<<<<<<<<<<< + * dtype=np.intc) # <<<<<<<<<<<<<< * self.feature_indices = feature_indices - * self.feature_indices_ptr = feature_indices.data + * self.feature_indices_ptr = feature_indices.data */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_intc); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "sklearn/utils/seq_dataset.pyx":86 + * self.n_features = X.shape[1] + * cdef np.ndarray[int, ndim=1, + * mode='c'] feature_indices = np.arange(0, self.n_features, # <<<<<<<<<<<<<< + * dtype=np.intc) + * self.feature_indices = feature_indices + */ + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_5, __pyx_t_6); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_8) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_8, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = ((PyArrayObject *)__pyx_t_8); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_feature_indices, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_INTEGER, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - __pyx_v_feature_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_feature_indices.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_feature_indices = __pyx_bstruct_feature_indices.strides[0]; - __pyx_bshape_0_feature_indices = __pyx_bstruct_feature_indices.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_feature_indices.rcbuffer->pybuffer, (PyObject*)__pyx_t_9, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_feature_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_feature_indices.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_feature_indices.diminfo[0].strides = __pyx_pybuffernd_feature_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_feature_indices.diminfo[0].shape = __pyx_pybuffernd_feature_indices.rcbuffer->pybuffer.shape[0]; } } - __pyx_t_6 = 0; - __pyx_v_feature_indices = ((PyArrayObject *)__pyx_t_5); - __pyx_t_5 = 0; + __pyx_t_9 = 0; + __pyx_v_feature_indices = ((PyArrayObject *)__pyx_t_8); + __pyx_t_8 = 0; - /* "sklearn/utils/seq_dataset.pyx":75 + /* "sklearn/utils/seq_dataset.pyx":88 * mode='c'] feature_indices = np.arange(0, self.n_features, - * dtype=np.int32) + * dtype=np.intc) * self.feature_indices = feature_indices # <<<<<<<<<<<<<< - * self.feature_indices_ptr = feature_indices.data + * self.feature_indices_ptr = feature_indices.data * self.current_index = -1 */ __Pyx_INCREF(((PyObject *)__pyx_v_feature_indices)); __Pyx_GIVEREF(((PyObject *)__pyx_v_feature_indices)); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->feature_indices); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->feature_indices)); - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->feature_indices = ((PyArrayObject *)__pyx_v_feature_indices); + __Pyx_GOTREF(__pyx_v_self->feature_indices); + __Pyx_DECREF(((PyObject *)__pyx_v_self->feature_indices)); + __pyx_v_self->feature_indices = ((PyArrayObject *)__pyx_v_feature_indices); - /* "sklearn/utils/seq_dataset.pyx":76 - * dtype=np.int32) + /* "sklearn/utils/seq_dataset.pyx":89 + * dtype=np.intc) * self.feature_indices = feature_indices - * self.feature_indices_ptr = feature_indices.data # <<<<<<<<<<<<<< + * self.feature_indices_ptr = feature_indices.data # <<<<<<<<<<<<<< * self.current_index = -1 - * self.stride = X.strides[0] / X.strides[1] + * self.stride = X.strides[0] / X.itemsize */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->feature_indices_ptr = ((__pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *)__pyx_v_feature_indices->data); + __pyx_v_self->feature_indices_ptr = ((int *)__pyx_v_feature_indices->data); - /* "sklearn/utils/seq_dataset.pyx":77 + /* "sklearn/utils/seq_dataset.pyx":90 * self.feature_indices = feature_indices - * self.feature_indices_ptr = feature_indices.data + * self.feature_indices_ptr = feature_indices.data * self.current_index = -1 # <<<<<<<<<<<<<< - * self.stride = X.strides[0] / X.strides[1] - * self.X_data_ptr = X.data + * self.stride = X.strides[0] / X.itemsize + * self.X_data_ptr = X.data */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->current_index = -1; + __pyx_v_self->__pyx_base.current_index = -1; - /* "sklearn/utils/seq_dataset.pyx":78 - * self.feature_indices_ptr = feature_indices.data + /* "sklearn/utils/seq_dataset.pyx":91 + * self.feature_indices_ptr = feature_indices.data * self.current_index = -1 - * self.stride = X.strides[0] / X.strides[1] # <<<<<<<<<<<<<< - * self.X_data_ptr = X.data - * self.Y_data_ptr = Y.data - */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->stride = ((__pyx_v_X->strides[0]) / (__pyx_v_X->strides[1])); + * self.stride = X.strides[0] / X.itemsize # <<<<<<<<<<<<<< + * self.X_data_ptr = X.data + * self.Y_data_ptr = Y.data + */ + __pyx_t_8 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X->strides[0])); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_X), __pyx_n_s_itemsize); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_PyNumber_Divide(__pyx_t_8, __pyx_t_6); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_10 = __Pyx_PyInt_As_int(__pyx_t_5); if (unlikely((__pyx_t_10 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_self->stride = __pyx_t_10; - /* "sklearn/utils/seq_dataset.pyx":79 + /* "sklearn/utils/seq_dataset.pyx":92 * self.current_index = -1 - * self.stride = X.strides[0] / X.strides[1] - * self.X_data_ptr = X.data # <<<<<<<<<<<<<< - * self.Y_data_ptr = Y.data - * self.sample_weight_data = sample_weights.data + * self.stride = X.strides[0] / X.itemsize + * self.X_data_ptr = X.data # <<<<<<<<<<<<<< + * self.Y_data_ptr = Y.data + * self.sample_weight_data = sample_weights.data */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->X_data_ptr = ((__pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *)__pyx_v_X->data); + __pyx_v_self->X_data_ptr = ((double *)__pyx_v_X->data); - /* "sklearn/utils/seq_dataset.pyx":80 - * self.stride = X.strides[0] / X.strides[1] - * self.X_data_ptr = X.data - * self.Y_data_ptr = Y.data # <<<<<<<<<<<<<< - * self.sample_weight_data = sample_weights.data + /* "sklearn/utils/seq_dataset.pyx":93 + * self.stride = X.strides[0] / X.itemsize + * self.X_data_ptr = X.data + * self.Y_data_ptr = Y.data # <<<<<<<<<<<<<< + * self.sample_weight_data = sample_weights.data * */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->Y_data_ptr = ((__pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *)__pyx_v_Y->data); + __pyx_v_self->Y_data_ptr = ((double *)__pyx_v_Y->data); - /* "sklearn/utils/seq_dataset.pyx":81 - * self.X_data_ptr = X.data - * self.Y_data_ptr = Y.data - * self.sample_weight_data = sample_weights.data # <<<<<<<<<<<<<< + /* "sklearn/utils/seq_dataset.pyx":94 + * self.X_data_ptr = X.data + * self.Y_data_ptr = Y.data + * self.sample_weight_data = sample_weights.data # <<<<<<<<<<<<<< * * # Use index array for fast shuffling */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->sample_weight_data = ((__pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *)__pyx_v_sample_weights->data); + __pyx_v_self->sample_weight_data = ((double *)__pyx_v_sample_weights->data); - /* "sklearn/utils/seq_dataset.pyx":85 + /* "sklearn/utils/seq_dataset.pyx":98 * # Use index array for fast shuffling - * cdef np.ndarray[INTEGER, ndim=1, - * mode='c'] index = np.arange(0, self.n_samples, # <<<<<<<<<<<<<< - * dtype=np.int32) + * cdef np.ndarray[int, ndim=1, mode='c'] index = \ + * np.arange(0, self.n_samples, dtype=np.intc) # <<<<<<<<<<<<<< * self.index = index + * self.index_data_ptr = index.data */ - __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_1 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__arange); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_arange); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyInt_FromSsize_t(((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->__pyx_base.n_samples); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_self->__pyx_base.n_samples); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_8 = PyTuple_New(2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - - /* "sklearn/utils/seq_dataset.pyx":86 - * cdef np.ndarray[INTEGER, ndim=1, - * mode='c'] index = np.arange(0, self.n_samples, - * dtype=np.int32) # <<<<<<<<<<<<<< - * self.index = index - * self.index_data_ptr = index.data - */ - __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__int32); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_intc); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyEval_CallObjectWithKeywords(__pyx_t_1, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, __pyx_t_5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = ((PyArrayObject *)__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_index, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_INTEGER, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - __pyx_v_index = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_index.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_index = __pyx_bstruct_index.strides[0]; - __pyx_bshape_0_index = __pyx_bstruct_index.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_index.rcbuffer->pybuffer, (PyObject*)__pyx_t_11, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_index = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_index.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 97; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_index.diminfo[0].strides = __pyx_pybuffernd_index.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_index.diminfo[0].shape = __pyx_pybuffernd_index.rcbuffer->pybuffer.shape[0]; } } - __pyx_t_7 = 0; + __pyx_t_11 = 0; __pyx_v_index = ((PyArrayObject *)__pyx_t_4); __pyx_t_4 = 0; - /* "sklearn/utils/seq_dataset.pyx":87 - * mode='c'] index = np.arange(0, self.n_samples, - * dtype=np.int32) + /* "sklearn/utils/seq_dataset.pyx":99 + * cdef np.ndarray[int, ndim=1, mode='c'] index = \ + * np.arange(0, self.n_samples, dtype=np.intc) * self.index = index # <<<<<<<<<<<<<< - * self.index_data_ptr = index.data + * self.index_data_ptr = index.data * */ __Pyx_INCREF(((PyObject *)__pyx_v_index)); __Pyx_GIVEREF(((PyObject *)__pyx_v_index)); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->index); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->index)); - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->index = ((PyArrayObject *)__pyx_v_index); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.index); + __Pyx_DECREF(((PyObject *)__pyx_v_self->__pyx_base.index)); + __pyx_v_self->__pyx_base.index = ((PyArrayObject *)__pyx_v_index); - /* "sklearn/utils/seq_dataset.pyx":88 - * dtype=np.int32) + /* "sklearn/utils/seq_dataset.pyx":100 + * np.arange(0, self.n_samples, dtype=np.intc) * self.index = index - * self.index_data_ptr = index.data # <<<<<<<<<<<<<< + * self.index_data_ptr = index.data # <<<<<<<<<<<<<< + * + * cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + */ + __pyx_v_self->__pyx_base.index_data_ptr = ((int *)__pyx_v_index->data); + + /* "sklearn/utils/seq_dataset.pyx":61 + * """ * - * cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, + * def __cinit__(self, np.ndarray[double, ndim=2, mode='c'] X, # <<<<<<<<<<<<<< + * np.ndarray[double, ndim=1, mode='c'] Y, + * np.ndarray[double, ndim=1, mode='c'] sample_weights): */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)__pyx_v_self)->index_data_ptr = ((__pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *)__pyx_v_index->data); + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_index); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_sample_weights); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_feature_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_Y); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Y.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_feature_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_index.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_weights.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.utils.seq_dataset.ArrayDataset.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_index); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_sample_weights); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_feature_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_Y); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Y.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_feature_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_index.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_weights.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_feature_indices); __Pyx_XDECREF((PyObject *)__pyx_v_index); @@ -1549,42 +2062,44 @@ static int __pyx_pf_7sklearn_5utils_11seq_dataset_12ArrayDataset___cinit__(PyObj return __pyx_r; } -/* "sklearn/utils/seq_dataset.pyx":90 - * self.index_data_ptr = index.data +/* "sklearn/utils/seq_dataset.pyx":102 + * self.index_data_ptr = index.data * - * cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, # <<<<<<<<<<<<<< - * int *nnz, DOUBLE *y, DOUBLE *sample_weight): + * cdef void next(self, double **x_data_ptr, int **x_ind_ptr, # <<<<<<<<<<<<<< + * int *nnz, double *y, double *sample_weight) nogil: * cdef int current_index = self.current_index */ -static void __pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_next(struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx_v_self, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE **__pyx_v_x_data_ptr, __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER **__pyx_v_x_ind_ptr, int *__pyx_v_nnz, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *__pyx_v_y, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *__pyx_v_sample_weight) { +static void __pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_next(struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx_v_self, double **__pyx_v_x_data_ptr, int **__pyx_v_x_ind_ptr, int *__pyx_v_nnz, double *__pyx_v_y, double *__pyx_v_sample_weight) { int __pyx_v_current_index; int __pyx_v_sample_idx; int __pyx_v_offset; - __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("next"); + int __pyx_t_2; + int *__pyx_t_3; + Py_ssize_t __pyx_t_4; - /* "sklearn/utils/seq_dataset.pyx":92 - * cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, - * int *nnz, DOUBLE *y, DOUBLE *sample_weight): + /* "sklearn/utils/seq_dataset.pyx":104 + * cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + * int *nnz, double *y, double *sample_weight) nogil: * cdef int current_index = self.current_index # <<<<<<<<<<<<<< * if current_index >= (self.n_samples - 1): * current_index = -1 */ - __pyx_v_current_index = __pyx_v_self->current_index; + __pyx_t_1 = __pyx_v_self->__pyx_base.current_index; + __pyx_v_current_index = __pyx_t_1; - /* "sklearn/utils/seq_dataset.pyx":93 - * int *nnz, DOUBLE *y, DOUBLE *sample_weight): + /* "sklearn/utils/seq_dataset.pyx":105 + * int *nnz, double *y, double *sample_weight) nogil: * cdef int current_index = self.current_index * if current_index >= (self.n_samples - 1): # <<<<<<<<<<<<<< * current_index = -1 * */ - __pyx_t_1 = (__pyx_v_current_index >= (__pyx_v_self->__pyx_base.n_samples - 1)); - if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_current_index >= (__pyx_v_self->__pyx_base.n_samples - 1)) != 0); + if (__pyx_t_2) { - /* "sklearn/utils/seq_dataset.pyx":94 + /* "sklearn/utils/seq_dataset.pyx":106 * cdef int current_index = self.current_index * if current_index >= (self.n_samples - 1): * current_index = -1 # <<<<<<<<<<<<<< @@ -1596,7 +2111,7 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_next(struct __p } __pyx_L3:; - /* "sklearn/utils/seq_dataset.pyx":96 + /* "sklearn/utils/seq_dataset.pyx":108 * current_index = -1 * * current_index += 1 # <<<<<<<<<<<<<< @@ -1605,16 +2120,16 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_next(struct __p */ __pyx_v_current_index = (__pyx_v_current_index + 1); - /* "sklearn/utils/seq_dataset.pyx":97 + /* "sklearn/utils/seq_dataset.pyx":109 * * current_index += 1 * cdef int sample_idx = self.index_data_ptr[current_index] # <<<<<<<<<<<<<< * cdef int offset = sample_idx * self.stride * */ - __pyx_v_sample_idx = (__pyx_v_self->index_data_ptr[__pyx_v_current_index]); + __pyx_v_sample_idx = (__pyx_v_self->__pyx_base.index_data_ptr[__pyx_v_current_index]); - /* "sklearn/utils/seq_dataset.pyx":98 + /* "sklearn/utils/seq_dataset.pyx":110 * current_index += 1 * cdef int sample_idx = self.index_data_ptr[current_index] * cdef int offset = sample_idx * self.stride # <<<<<<<<<<<<<< @@ -1623,7 +2138,7 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_next(struct __p */ __pyx_v_offset = (__pyx_v_sample_idx * __pyx_v_self->stride); - /* "sklearn/utils/seq_dataset.pyx":100 + /* "sklearn/utils/seq_dataset.pyx":112 * cdef int offset = sample_idx * self.stride * * y[0] = self.Y_data_ptr[sample_idx] # <<<<<<<<<<<<<< @@ -1632,7 +2147,7 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_next(struct __p */ (__pyx_v_y[0]) = (__pyx_v_self->Y_data_ptr[__pyx_v_sample_idx]); - /* "sklearn/utils/seq_dataset.pyx":101 + /* "sklearn/utils/seq_dataset.pyx":113 * * y[0] = self.Y_data_ptr[sample_idx] * x_data_ptr[0] = self.X_data_ptr + offset # <<<<<<<<<<<<<< @@ -1641,25 +2156,27 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_next(struct __p */ (__pyx_v_x_data_ptr[0]) = (__pyx_v_self->X_data_ptr + __pyx_v_offset); - /* "sklearn/utils/seq_dataset.pyx":102 + /* "sklearn/utils/seq_dataset.pyx":114 * y[0] = self.Y_data_ptr[sample_idx] * x_data_ptr[0] = self.X_data_ptr + offset * x_ind_ptr[0] = self.feature_indices_ptr # <<<<<<<<<<<<<< * nnz[0] = self.n_features * sample_weight[0] = self.sample_weight_data[sample_idx] */ - (__pyx_v_x_ind_ptr[0]) = __pyx_v_self->feature_indices_ptr; + __pyx_t_3 = __pyx_v_self->feature_indices_ptr; + (__pyx_v_x_ind_ptr[0]) = __pyx_t_3; - /* "sklearn/utils/seq_dataset.pyx":103 + /* "sklearn/utils/seq_dataset.pyx":115 * x_data_ptr[0] = self.X_data_ptr + offset * x_ind_ptr[0] = self.feature_indices_ptr * nnz[0] = self.n_features # <<<<<<<<<<<<<< * sample_weight[0] = self.sample_weight_data[sample_idx] * */ - (__pyx_v_nnz[0]) = __pyx_v_self->n_features; + __pyx_t_4 = __pyx_v_self->n_features; + (__pyx_v_nnz[0]) = __pyx_t_4; - /* "sklearn/utils/seq_dataset.pyx":104 + /* "sklearn/utils/seq_dataset.pyx":116 * x_ind_ptr[0] = self.feature_indices_ptr * nnz[0] = self.n_features * sample_weight[0] = self.sample_weight_data[sample_idx] # <<<<<<<<<<<<<< @@ -1668,136 +2185,55 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_next(struct __p */ (__pyx_v_sample_weight[0]) = (__pyx_v_self->sample_weight_data[__pyx_v_sample_idx]); - /* "sklearn/utils/seq_dataset.pyx":106 + /* "sklearn/utils/seq_dataset.pyx":118 * sample_weight[0] = self.sample_weight_data[sample_idx] * * self.current_index = current_index # <<<<<<<<<<<<<< * - * cdef void shuffle(self, seed): + * */ - __pyx_v_self->current_index = __pyx_v_current_index; + __pyx_v_self->__pyx_base.current_index = __pyx_v_current_index; - __Pyx_RefNannyFinishContext(); + /* "sklearn/utils/seq_dataset.pyx":102 + * self.index_data_ptr = index.data + * + * cdef void next(self, double **x_data_ptr, int **x_ind_ptr, # <<<<<<<<<<<<<< + * int *nnz, double *y, double *sample_weight) nogil: + * cdef int current_index = self.current_index + */ + + /* function exit code */ } -/* "sklearn/utils/seq_dataset.pyx":108 - * self.current_index = current_index - * - * cdef void shuffle(self, seed): # <<<<<<<<<<<<<< - * np.random.RandomState(seed).shuffle(self.index) +/* "sklearn/utils/seq_dataset.pyx":124 + * """A ``SequentialDataset`` backed by a scipy sparse CSR matrix. """ * + * def __cinit__(self, np.ndarray[double, ndim=1, mode='c'] X_data, # <<<<<<<<<<<<<< + * np.ndarray[int, ndim=1, mode='c'] X_indptr, + * np.ndarray[int, ndim=1, mode='c'] X_indices, */ -static void __pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_shuffle(struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *__pyx_v_self, PyObject *__pyx_v_seed) { - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; +/* Python wrapper */ +static int __pyx_pw_7sklearn_5utils_11seq_dataset_10CSRDataset_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_5utils_11seq_dataset_10CSRDataset_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_X_data = 0; + PyArrayObject *__pyx_v_X_indptr = 0; + PyArrayObject *__pyx_v_X_indices = 0; + PyArrayObject *__pyx_v_Y = 0; + PyArrayObject *__pyx_v_sample_weight = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("shuffle"); - - /* "sklearn/utils/seq_dataset.pyx":109 - * - * cdef void shuffle(self, seed): - * np.random.RandomState(seed).shuffle(self.index) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__random); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__RandomState); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(__pyx_v_seed); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_seed); - __Pyx_GIVEREF(__pyx_v_seed); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__shuffle); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(((PyObject *)__pyx_v_self->index)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self->index)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self->index)); - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_WriteUnraisable("sklearn.utils.seq_dataset.ArrayDataset.shuffle", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_RefNannyFinishContext(); -} - -/* "sklearn/utils/seq_dataset.pyx":115 - * """A ``SequentialDataset`` backed by a scipy sparse CSR matrix. """ - * - * def __cinit__(self, np.ndarray[DOUBLE, ndim=1, mode='c'] X_data, # <<<<<<<<<<<<<< - * np.ndarray[INTEGER, ndim=1, mode='c'] X_indptr, - * np.ndarray[INTEGER, ndim=1, mode='c'] X_indices, - */ - -static int __pyx_pf_7sklearn_5utils_11seq_dataset_10CSRDataset___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pf_7sklearn_5utils_11seq_dataset_10CSRDataset___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_X_data = 0; - PyArrayObject *__pyx_v_X_indptr = 0; - PyArrayObject *__pyx_v_X_indices = 0; - PyArrayObject *__pyx_v_Y = 0; - PyArrayObject *__pyx_v_sample_weight = 0; - PyArrayObject *__pyx_v_index = 0; - Py_buffer __pyx_bstruct_index; - Py_ssize_t __pyx_bstride_0_index = 0; - Py_ssize_t __pyx_bshape_0_index = 0; - Py_buffer __pyx_bstruct_X_indices; - Py_ssize_t __pyx_bstride_0_X_indices = 0; - Py_ssize_t __pyx_bshape_0_X_indices = 0; - Py_buffer __pyx_bstruct_X_indptr; - Py_ssize_t __pyx_bstride_0_X_indptr = 0; - Py_ssize_t __pyx_bshape_0_X_indptr = 0; - Py_buffer __pyx_bstruct_X_data; - Py_ssize_t __pyx_bstride_0_X_data = 0; - Py_ssize_t __pyx_bshape_0_X_data = 0; - Py_buffer __pyx_bstruct_Y; - Py_ssize_t __pyx_bstride_0_Y = 0; - Py_ssize_t __pyx_bshape_0_Y = 0; - Py_buffer __pyx_bstruct_sample_weight; - Py_ssize_t __pyx_bstride_0_sample_weight = 0; - Py_ssize_t __pyx_bshape_0_sample_weight = 0; int __pyx_r; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyArrayObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__X_data,&__pyx_n_s__X_indptr,&__pyx_n_s__X_indices,&__pyx_n_s__Y,&__pyx_n_s__sample_weight,0}; - __Pyx_RefNannySetupContext("__cinit__"); + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X_data,&__pyx_n_s_X_indptr,&__pyx_n_s_X_indices,&__pyx_n_s_Y,&__pyx_n_s_sample_weight,0}; PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); @@ -1807,38 +2243,33 @@ static int __pyx_pf_7sklearn_5utils_11seq_dataset_10CSRDataset___cinit__(PyObjec default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_data); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_data)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: - values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_indptr); - if (likely(values[1])) kw_args--; + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indptr)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: - values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__X_indices); - if (likely(values[2])) kw_args--; + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indices)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: - values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__Y); - if (likely(values[3])) kw_args--; + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: - values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sample_weight); - if (likely(values[4])) kw_args--; + if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_sample_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { goto __pyx_L5_argtuple_error; @@ -1857,198 +2288,261 @@ static int __pyx_pf_7sklearn_5utils_11seq_dataset_10CSRDataset___cinit__(PyObjec } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.utils.seq_dataset.CSRDataset.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_index.buf = NULL; - __pyx_bstruct_X_data.buf = NULL; - __pyx_bstruct_X_indptr.buf = NULL; - __pyx_bstruct_X_indices.buf = NULL; - __pyx_bstruct_Y.buf = NULL; - __pyx_bstruct_sample_weight.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_data), __pyx_ptype_5numpy_ndarray, 1, "X_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_indptr), __pyx_ptype_5numpy_ndarray, 1, "X_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_indices), __pyx_ptype_5numpy_ndarray, 1, "X_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_data), __pyx_ptype_5numpy_ndarray, 1, "X_data", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_indptr), __pyx_ptype_5numpy_ndarray, 1, "X_indptr", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_indices), __pyx_ptype_5numpy_ndarray, 1, "X_indices", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_Y), __pyx_ptype_5numpy_ndarray, 1, "Y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sample_weight), __pyx_ptype_5numpy_ndarray, 1, "sample_weight", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_11seq_dataset_10CSRDataset___cinit__(((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self), __pyx_v_X_data, __pyx_v_X_indptr, __pyx_v_X_indices, __pyx_v_Y, __pyx_v_sample_weight); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_5utils_11seq_dataset_10CSRDataset___cinit__(struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *__pyx_v_self, PyArrayObject *__pyx_v_X_data, PyArrayObject *__pyx_v_X_indptr, PyArrayObject *__pyx_v_X_indices, PyArrayObject *__pyx_v_Y, PyArrayObject *__pyx_v_sample_weight) { + PyArrayObject *__pyx_v_idx = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_data; + __Pyx_Buffer __pyx_pybuffer_X_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indices; + __Pyx_Buffer __pyx_pybuffer_X_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indptr; + __Pyx_Buffer __pyx_pybuffer_X_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_Y; + __Pyx_Buffer __pyx_pybuffer_Y; + __Pyx_LocalBuf_ND __pyx_pybuffernd_idx; + __Pyx_Buffer __pyx_pybuffer_idx; + __Pyx_LocalBuf_ND __pyx_pybuffernd_sample_weight; + __Pyx_Buffer __pyx_pybuffer_sample_weight; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __pyx_pybuffer_idx.pybuffer.buf = NULL; + __pyx_pybuffer_idx.refcount = 0; + __pyx_pybuffernd_idx.data = NULL; + __pyx_pybuffernd_idx.rcbuffer = &__pyx_pybuffer_idx; + __pyx_pybuffer_X_data.pybuffer.buf = NULL; + __pyx_pybuffer_X_data.refcount = 0; + __pyx_pybuffernd_X_data.data = NULL; + __pyx_pybuffernd_X_data.rcbuffer = &__pyx_pybuffer_X_data; + __pyx_pybuffer_X_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_X_indptr.refcount = 0; + __pyx_pybuffernd_X_indptr.data = NULL; + __pyx_pybuffernd_X_indptr.rcbuffer = &__pyx_pybuffer_X_indptr; + __pyx_pybuffer_X_indices.pybuffer.buf = NULL; + __pyx_pybuffer_X_indices.refcount = 0; + __pyx_pybuffernd_X_indices.data = NULL; + __pyx_pybuffernd_X_indices.rcbuffer = &__pyx_pybuffer_X_indices; + __pyx_pybuffer_Y.pybuffer.buf = NULL; + __pyx_pybuffer_Y.refcount = 0; + __pyx_pybuffernd_Y.data = NULL; + __pyx_pybuffernd_Y.rcbuffer = &__pyx_pybuffer_Y; + __pyx_pybuffer_sample_weight.pybuffer.buf = NULL; + __pyx_pybuffer_sample_weight.refcount = 0; + __pyx_pybuffernd_sample_weight.data = NULL; + __pyx_pybuffernd_sample_weight.rcbuffer = &__pyx_pybuffer_sample_weight; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_data, (PyObject*)__pyx_v_X_data, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_X_data, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_X_data = __pyx_bstruct_X_data.strides[0]; - __pyx_bshape_0_X_data = __pyx_bstruct_X_data.shape[0]; + __pyx_pybuffernd_X_data.diminfo[0].strides = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_data.diminfo[0].shape = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indptr, (PyObject*)__pyx_v_X_indptr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_INTEGER, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_X_indptr, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_X_indptr = __pyx_bstruct_X_indptr.strides[0]; - __pyx_bshape_0_X_indptr = __pyx_bstruct_X_indptr.shape[0]; + __pyx_pybuffernd_X_indptr.diminfo[0].strides = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indptr.diminfo[0].shape = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_X_indices, (PyObject*)__pyx_v_X_indices, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_INTEGER, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_X_indices, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_X_indices = __pyx_bstruct_X_indices.strides[0]; - __pyx_bshape_0_X_indices = __pyx_bstruct_X_indices.shape[0]; + __pyx_pybuffernd_X_indices.diminfo[0].strides = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indices.diminfo[0].shape = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_Y, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_Y.rcbuffer->pybuffer, (PyObject*)__pyx_v_Y, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_Y = __pyx_bstruct_Y.strides[0]; - __pyx_bshape_0_Y = __pyx_bstruct_Y.shape[0]; + __pyx_pybuffernd_Y.diminfo[0].strides = __pyx_pybuffernd_Y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_Y.diminfo[0].shape = __pyx_pybuffernd_Y.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_sample_weight, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer, (PyObject*)__pyx_v_sample_weight, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_sample_weight = __pyx_bstruct_sample_weight.strides[0]; - __pyx_bshape_0_sample_weight = __pyx_bstruct_sample_weight.shape[0]; + __pyx_pybuffernd_sample_weight.diminfo[0].strides = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_sample_weight.diminfo[0].shape = __pyx_pybuffernd_sample_weight.rcbuffer->pybuffer.shape[0]; - /* "sklearn/utils/seq_dataset.pyx":144 - * array of dtype np.float64. + /* "sklearn/utils/seq_dataset.pyx":153 + * array of dtype double. * """ * self.n_samples = Y.shape[0] # <<<<<<<<<<<<<< * self.current_index = -1 - * self.X_data_ptr = X_data.data + * self.X_data_ptr = X_data.data */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->__pyx_base.n_samples = (__pyx_v_Y->dimensions[0]); + __pyx_v_self->__pyx_base.n_samples = (__pyx_v_Y->dimensions[0]); - /* "sklearn/utils/seq_dataset.pyx":145 + /* "sklearn/utils/seq_dataset.pyx":154 * """ * self.n_samples = Y.shape[0] * self.current_index = -1 # <<<<<<<<<<<<<< - * self.X_data_ptr = X_data.data - * self.X_indptr_ptr = X_indptr.data + * self.X_data_ptr = X_data.data + * self.X_indptr_ptr = X_indptr.data */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->current_index = -1; + __pyx_v_self->__pyx_base.current_index = -1; - /* "sklearn/utils/seq_dataset.pyx":146 + /* "sklearn/utils/seq_dataset.pyx":155 * self.n_samples = Y.shape[0] * self.current_index = -1 - * self.X_data_ptr = X_data.data # <<<<<<<<<<<<<< - * self.X_indptr_ptr = X_indptr.data - * self.X_indices_ptr = X_indices.data + * self.X_data_ptr = X_data.data # <<<<<<<<<<<<<< + * self.X_indptr_ptr = X_indptr.data + * self.X_indices_ptr = X_indices.data */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->X_data_ptr = ((__pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *)__pyx_v_X_data->data); + __pyx_v_self->X_data_ptr = ((double *)__pyx_v_X_data->data); - /* "sklearn/utils/seq_dataset.pyx":147 + /* "sklearn/utils/seq_dataset.pyx":156 * self.current_index = -1 - * self.X_data_ptr = X_data.data - * self.X_indptr_ptr = X_indptr.data # <<<<<<<<<<<<<< - * self.X_indices_ptr = X_indices.data - * self.Y_data_ptr = Y.data - */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->X_indptr_ptr = ((__pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *)__pyx_v_X_indptr->data); - - /* "sklearn/utils/seq_dataset.pyx":148 - * self.X_data_ptr = X_data.data - * self.X_indptr_ptr = X_indptr.data - * self.X_indices_ptr = X_indices.data # <<<<<<<<<<<<<< - * self.Y_data_ptr = Y.data - * self.sample_weight_data = sample_weight.data - */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->X_indices_ptr = ((__pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *)__pyx_v_X_indices->data); - - /* "sklearn/utils/seq_dataset.pyx":149 - * self.X_indptr_ptr = X_indptr.data - * self.X_indices_ptr = X_indices.data - * self.Y_data_ptr = Y.data # <<<<<<<<<<<<<< - * self.sample_weight_data = sample_weight.data + * self.X_data_ptr = X_data.data + * self.X_indptr_ptr = X_indptr.data # <<<<<<<<<<<<<< + * self.X_indices_ptr = X_indices.data + * self.Y_data_ptr = Y.data + */ + __pyx_v_self->X_indptr_ptr = ((int *)__pyx_v_X_indptr->data); + + /* "sklearn/utils/seq_dataset.pyx":157 + * self.X_data_ptr = X_data.data + * self.X_indptr_ptr = X_indptr.data + * self.X_indices_ptr = X_indices.data # <<<<<<<<<<<<<< + * self.Y_data_ptr = Y.data + * self.sample_weight_data = sample_weight.data + */ + __pyx_v_self->X_indices_ptr = ((int *)__pyx_v_X_indices->data); + + /* "sklearn/utils/seq_dataset.pyx":158 + * self.X_indptr_ptr = X_indptr.data + * self.X_indices_ptr = X_indices.data + * self.Y_data_ptr = Y.data # <<<<<<<<<<<<<< + * self.sample_weight_data = sample_weight.data * # Use index array for fast shuffling */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->Y_data_ptr = ((__pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *)__pyx_v_Y->data); + __pyx_v_self->Y_data_ptr = ((double *)__pyx_v_Y->data); - /* "sklearn/utils/seq_dataset.pyx":150 - * self.X_indices_ptr = X_indices.data - * self.Y_data_ptr = Y.data - * self.sample_weight_data = sample_weight.data # <<<<<<<<<<<<<< + /* "sklearn/utils/seq_dataset.pyx":159 + * self.X_indices_ptr = X_indices.data + * self.Y_data_ptr = Y.data + * self.sample_weight_data = sample_weight.data # <<<<<<<<<<<<<< * # Use index array for fast shuffling - * cdef np.ndarray[INTEGER, ndim=1, + * cdef np.ndarray[int, ndim=1, mode='c'] idx = np.arange(self.n_samples, */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->sample_weight_data = ((__pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *)__pyx_v_sample_weight->data); + __pyx_v_self->sample_weight_data = ((double *)__pyx_v_sample_weight->data); - /* "sklearn/utils/seq_dataset.pyx":153 + /* "sklearn/utils/seq_dataset.pyx":161 + * self.sample_weight_data = sample_weight.data * # Use index array for fast shuffling - * cdef np.ndarray[INTEGER, ndim=1, - * mode='c'] index = np.arange(0, self.n_samples, # <<<<<<<<<<<<<< - * dtype=np.int32) - * self.index = index + * cdef np.ndarray[int, ndim=1, mode='c'] idx = np.arange(self.n_samples, # <<<<<<<<<<<<<< + * dtype=np.intc) + * self.index = idx */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__arange); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_arange); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyInt_FromSsize_t(((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->__pyx_base.n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->__pyx_base.n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); - /* "sklearn/utils/seq_dataset.pyx":154 - * cdef np.ndarray[INTEGER, ndim=1, - * mode='c'] index = np.arange(0, self.n_samples, - * dtype=np.int32) # <<<<<<<<<<<<<< - * self.index = index - * self.index_data_ptr = index.data + /* "sklearn/utils/seq_dataset.pyx":162 + * # Use index array for fast shuffling + * cdef np.ndarray[int, ndim=1, mode='c'] idx = np.arange(self.n_samples, + * dtype=np.intc) # <<<<<<<<<<<<<< + * self.index = idx + * self.index_data_ptr = idx.data */ - __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__int32); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_intc); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyEval_CallObjectWithKeywords(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/seq_dataset.pyx":161 + * self.sample_weight_data = sample_weight.data + * # Use index array for fast shuffling + * cdef np.ndarray[int, ndim=1, mode='c'] idx = np.arange(self.n_samples, # <<<<<<<<<<<<<< + * dtype=np.intc) + * self.index = idx + */ + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)__pyx_t_5); { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_index, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_11seq_dataset_INTEGER, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { - __pyx_v_index = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_index.buf = NULL; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } else {__pyx_bstride_0_index = __pyx_bstruct_index.strides[0]; - __pyx_bshape_0_index = __pyx_bstruct_index.shape[0]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_idx.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_idx = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_idx.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_idx.diminfo[0].strides = __pyx_pybuffernd_idx.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_idx.diminfo[0].shape = __pyx_pybuffernd_idx.rcbuffer->pybuffer.shape[0]; } } __pyx_t_6 = 0; - __pyx_v_index = ((PyArrayObject *)__pyx_t_5); + __pyx_v_idx = ((PyArrayObject *)__pyx_t_5); __pyx_t_5 = 0; - /* "sklearn/utils/seq_dataset.pyx":155 - * mode='c'] index = np.arange(0, self.n_samples, - * dtype=np.int32) - * self.index = index # <<<<<<<<<<<<<< - * self.index_data_ptr = index.data + /* "sklearn/utils/seq_dataset.pyx":163 + * cdef np.ndarray[int, ndim=1, mode='c'] idx = np.arange(self.n_samples, + * dtype=np.intc) + * self.index = idx # <<<<<<<<<<<<<< + * self.index_data_ptr = idx.data * */ - __Pyx_INCREF(((PyObject *)__pyx_v_index)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_index)); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->index); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->index)); - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->index = ((PyArrayObject *)__pyx_v_index); + __Pyx_INCREF(((PyObject *)__pyx_v_idx)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_idx)); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.index); + __Pyx_DECREF(((PyObject *)__pyx_v_self->__pyx_base.index)); + __pyx_v_self->__pyx_base.index = ((PyArrayObject *)__pyx_v_idx); - /* "sklearn/utils/seq_dataset.pyx":156 - * dtype=np.int32) - * self.index = index - * self.index_data_ptr = index.data # <<<<<<<<<<<<<< + /* "sklearn/utils/seq_dataset.pyx":164 + * dtype=np.intc) + * self.index = idx + * self.index_data_ptr = idx.data # <<<<<<<<<<<<<< * - * cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, + * cdef void next(self, double **x_data_ptr, int **x_ind_ptr, */ - ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)__pyx_v_self)->index_data_ptr = ((__pyx_t_7sklearn_5utils_11seq_dataset_INTEGER *)__pyx_v_index->data); + __pyx_v_self->__pyx_base.index_data_ptr = ((int *)__pyx_v_idx->data); + /* "sklearn/utils/seq_dataset.pyx":124 + * """A ``SequentialDataset`` backed by a scipy sparse CSR matrix. """ + * + * def __cinit__(self, np.ndarray[double, ndim=1, mode='c'] X_data, # <<<<<<<<<<<<<< + * np.ndarray[int, ndim=1, mode='c'] X_indptr, + * np.ndarray[int, ndim=1, mode='c'] X_indices, + */ + + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; @@ -2059,65 +2553,65 @@ static int __pyx_pf_7sklearn_5utils_11seq_dataset_10CSRDataset___cinit__(PyObjec __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_index); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_Y); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_sample_weight); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Y.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_idx.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.utils.seq_dataset.CSRDataset.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_index); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indices); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_indptr); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_X_data); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_Y); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_sample_weight); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_Y.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_idx.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_sample_weight.rcbuffer->pybuffer); __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_index); + __Pyx_XDECREF((PyObject *)__pyx_v_idx); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/utils/seq_dataset.pyx":158 - * self.index_data_ptr = index.data +/* "sklearn/utils/seq_dataset.pyx":166 + * self.index_data_ptr = idx.data * - * cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, # <<<<<<<<<<<<<< - * int *nnz, DOUBLE *y, DOUBLE *sample_weight): + * cdef void next(self, double **x_data_ptr, int **x_ind_ptr, # <<<<<<<<<<<<<< + * int *nnz, double *y, double *sample_weight) nogil: * cdef int current_index = self.current_index */ -static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next(struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *__pyx_v_self, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE **__pyx_v_x_data_ptr, __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER **__pyx_v_x_ind_ptr, int *__pyx_v_nnz, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *__pyx_v_y, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *__pyx_v_sample_weight) { +static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next(struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *__pyx_v_self, double **__pyx_v_x_data_ptr, int **__pyx_v_x_ind_ptr, int *__pyx_v_nnz, double *__pyx_v_y, double *__pyx_v_sample_weight) { int __pyx_v_current_index; int __pyx_v_sample_idx; int __pyx_v_offset; - __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("next"); + int __pyx_t_2; - /* "sklearn/utils/seq_dataset.pyx":160 - * cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, - * int *nnz, DOUBLE *y, DOUBLE *sample_weight): + /* "sklearn/utils/seq_dataset.pyx":168 + * cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + * int *nnz, double *y, double *sample_weight) nogil: * cdef int current_index = self.current_index # <<<<<<<<<<<<<< * if current_index >= (self.n_samples - 1): * current_index = -1 */ - __pyx_v_current_index = __pyx_v_self->current_index; + __pyx_t_1 = __pyx_v_self->__pyx_base.current_index; + __pyx_v_current_index = __pyx_t_1; - /* "sklearn/utils/seq_dataset.pyx":161 - * int *nnz, DOUBLE *y, DOUBLE *sample_weight): + /* "sklearn/utils/seq_dataset.pyx":169 + * int *nnz, double *y, double *sample_weight) nogil: * cdef int current_index = self.current_index * if current_index >= (self.n_samples - 1): # <<<<<<<<<<<<<< * current_index = -1 * */ - __pyx_t_1 = (__pyx_v_current_index >= (__pyx_v_self->__pyx_base.n_samples - 1)); - if (__pyx_t_1) { + __pyx_t_2 = ((__pyx_v_current_index >= (__pyx_v_self->__pyx_base.n_samples - 1)) != 0); + if (__pyx_t_2) { - /* "sklearn/utils/seq_dataset.pyx":162 + /* "sklearn/utils/seq_dataset.pyx":170 * cdef int current_index = self.current_index * if current_index >= (self.n_samples - 1): * current_index = -1 # <<<<<<<<<<<<<< @@ -2129,7 +2623,7 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next(struct __pyx } __pyx_L3:; - /* "sklearn/utils/seq_dataset.pyx":164 + /* "sklearn/utils/seq_dataset.pyx":172 * current_index = -1 * * current_index += 1 # <<<<<<<<<<<<<< @@ -2138,16 +2632,16 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next(struct __pyx */ __pyx_v_current_index = (__pyx_v_current_index + 1); - /* "sklearn/utils/seq_dataset.pyx":165 + /* "sklearn/utils/seq_dataset.pyx":173 * * current_index += 1 * cdef int sample_idx = self.index_data_ptr[current_index] # <<<<<<<<<<<<<< * cdef int offset = self.X_indptr_ptr[sample_idx] * y[0] = self.Y_data_ptr[sample_idx] */ - __pyx_v_sample_idx = (__pyx_v_self->index_data_ptr[__pyx_v_current_index]); + __pyx_v_sample_idx = (__pyx_v_self->__pyx_base.index_data_ptr[__pyx_v_current_index]); - /* "sklearn/utils/seq_dataset.pyx":166 + /* "sklearn/utils/seq_dataset.pyx":174 * current_index += 1 * cdef int sample_idx = self.index_data_ptr[current_index] * cdef int offset = self.X_indptr_ptr[sample_idx] # <<<<<<<<<<<<<< @@ -2156,7 +2650,7 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next(struct __pyx */ __pyx_v_offset = (__pyx_v_self->X_indptr_ptr[__pyx_v_sample_idx]); - /* "sklearn/utils/seq_dataset.pyx":167 + /* "sklearn/utils/seq_dataset.pyx":175 * cdef int sample_idx = self.index_data_ptr[current_index] * cdef int offset = self.X_indptr_ptr[sample_idx] * y[0] = self.Y_data_ptr[sample_idx] # <<<<<<<<<<<<<< @@ -2165,7 +2659,7 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next(struct __pyx */ (__pyx_v_y[0]) = (__pyx_v_self->Y_data_ptr[__pyx_v_sample_idx]); - /* "sklearn/utils/seq_dataset.pyx":168 + /* "sklearn/utils/seq_dataset.pyx":176 * cdef int offset = self.X_indptr_ptr[sample_idx] * y[0] = self.Y_data_ptr[sample_idx] * x_data_ptr[0] = self.X_data_ptr + offset # <<<<<<<<<<<<<< @@ -2174,7 +2668,7 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next(struct __pyx */ (__pyx_v_x_data_ptr[0]) = (__pyx_v_self->X_data_ptr + __pyx_v_offset); - /* "sklearn/utils/seq_dataset.pyx":169 + /* "sklearn/utils/seq_dataset.pyx":177 * y[0] = self.Y_data_ptr[sample_idx] * x_data_ptr[0] = self.X_data_ptr + offset * x_ind_ptr[0] = self.X_indices_ptr + offset # <<<<<<<<<<<<<< @@ -2183,7 +2677,7 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next(struct __pyx */ (__pyx_v_x_ind_ptr[0]) = (__pyx_v_self->X_indices_ptr + __pyx_v_offset); - /* "sklearn/utils/seq_dataset.pyx":170 + /* "sklearn/utils/seq_dataset.pyx":178 * x_data_ptr[0] = self.X_data_ptr + offset * x_ind_ptr[0] = self.X_indices_ptr + offset * nnz[0] = self.X_indptr_ptr[sample_idx + 1] - offset # <<<<<<<<<<<<<< @@ -2192,7 +2686,7 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next(struct __pyx */ (__pyx_v_nnz[0]) = ((__pyx_v_self->X_indptr_ptr[(__pyx_v_sample_idx + 1)]) - __pyx_v_offset); - /* "sklearn/utils/seq_dataset.pyx":171 + /* "sklearn/utils/seq_dataset.pyx":179 * x_ind_ptr[0] = self.X_indices_ptr + offset * nnz[0] = self.X_indptr_ptr[sample_idx + 1] - offset * sample_weight[0] = self.sample_weight_data[sample_idx] # <<<<<<<<<<<<<< @@ -2201,82 +2695,90 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next(struct __pyx */ (__pyx_v_sample_weight[0]) = (__pyx_v_self->sample_weight_data[__pyx_v_sample_idx]); - /* "sklearn/utils/seq_dataset.pyx":173 + /* "sklearn/utils/seq_dataset.pyx":181 * sample_weight[0] = self.sample_weight_data[sample_idx] * * self.current_index = current_index # <<<<<<<<<<<<<< * - * cdef void shuffle(self, seed): + * */ - __pyx_v_self->current_index = __pyx_v_current_index; + __pyx_v_self->__pyx_base.current_index = __pyx_v_current_index; - __Pyx_RefNannyFinishContext(); + /* "sklearn/utils/seq_dataset.pyx":166 + * self.index_data_ptr = idx.data + * + * cdef void next(self, double **x_data_ptr, int **x_ind_ptr, # <<<<<<<<<<<<<< + * int *nnz, double *y, double *sample_weight) nogil: + * cdef int current_index = self.current_index + */ + + /* function exit code */ } -/* "sklearn/utils/seq_dataset.pyx":175 - * self.current_index = current_index - * - * cdef void shuffle(self, seed): # <<<<<<<<<<<<<< - * np.random.RandomState(seed).shuffle(self.index) +/* "sklearn/utils/seq_dataset.pyx":191 + * # See http://www.jstatsoft.org/v08/i14/paper for details + * # XXX copied over from sklearn/tree/_tree.pyx, should refactor + * cdef inline np.uint32_t our_rand_r(np.uint32_t* seed) nogil: # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) */ -static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_shuffle(struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *__pyx_v_self, PyObject *__pyx_v_seed) { - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("shuffle"); +static CYTHON_INLINE __pyx_t_5numpy_uint32_t __pyx_f_7sklearn_5utils_11seq_dataset_our_rand_r(__pyx_t_5numpy_uint32_t *__pyx_v_seed) { + __pyx_t_5numpy_uint32_t __pyx_r; + long __pyx_t_1; - /* "sklearn/utils/seq_dataset.pyx":176 + /* "sklearn/utils/seq_dataset.pyx":192 + * # XXX copied over from sklearn/tree/_tree.pyx, should refactor + * cdef inline np.uint32_t our_rand_r(np.uint32_t* seed) nogil: + * seed[0] ^= (seed[0] << 13) # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] >> 17) + * seed[0] ^= (seed[0] << 5) + */ + __pyx_t_1 = 0; + (__pyx_v_seed[__pyx_t_1]) = ((__pyx_v_seed[__pyx_t_1]) ^ ((__pyx_t_5numpy_uint32_t)((__pyx_v_seed[0]) << 13))); + + /* "sklearn/utils/seq_dataset.pyx":193 + * cdef inline np.uint32_t our_rand_r(np.uint32_t* seed) nogil: + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] << 5) * - * cdef void shuffle(self, seed): - * np.random.RandomState(seed).shuffle(self.index) # <<<<<<<<<<<<<< */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__random); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__RandomState); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - __Pyx_INCREF(__pyx_v_seed); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_seed); - __Pyx_GIVEREF(__pyx_v_seed); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__shuffle); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __Pyx_INCREF(((PyObject *)__pyx_v_self->index)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self->index)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self->index)); - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = 0; + (__pyx_v_seed[__pyx_t_1]) = ((__pyx_v_seed[__pyx_t_1]) ^ ((__pyx_t_5numpy_uint32_t)((__pyx_v_seed[0]) >> 17))); + + /* "sklearn/utils/seq_dataset.pyx":194 + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) + * seed[0] ^= (seed[0] << 5) # <<<<<<<<<<<<<< + * + * return seed[0] % (RAND_R_MAX + 1) + */ + __pyx_t_1 = 0; + (__pyx_v_seed[__pyx_t_1]) = ((__pyx_v_seed[__pyx_t_1]) ^ ((__pyx_t_5numpy_uint32_t)((__pyx_v_seed[0]) << 5))); + /* "sklearn/utils/seq_dataset.pyx":196 + * seed[0] ^= (seed[0] << 5) + * + * return seed[0] % (RAND_R_MAX + 1) # <<<<<<<<<<<<<< + */ + __pyx_r = ((__pyx_v_seed[0]) % (((__pyx_t_5numpy_uint32_t)__pyx_e_7sklearn_5utils_11seq_dataset_RAND_R_MAX) + 1)); goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_WriteUnraisable("sklearn.utils.seq_dataset.CSRDataset.shuffle", __pyx_clineno, __pyx_lineno, __pyx_filename); + + /* "sklearn/utils/seq_dataset.pyx":191 + * # See http://www.jstatsoft.org/v08/i14/paper for details + * # XXX copied over from sklearn/tree/_tree.pyx, should refactor + * cdef inline np.uint32_t our_rand_r(np.uint32_t* seed) nogil: # <<<<<<<<<<<<<< + * seed[0] ^= (seed[0] << 13) + * seed[0] ^= (seed[0] >> 17) + */ + + /* function exit code */ __pyx_L0:; - __Pyx_RefNannyFinishContext(); + return __pyx_r; } -/* "numpy.pxd":190 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< @@ -2284,8 +2786,20 @@ static void __pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_shuffle(struct __ * # requirements, and does not yet fullfill the PEP. */ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; @@ -2310,28 +2824,26 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__"); + __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":196 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ - __pyx_t_1 = (__pyx_v_info == NULL); + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; - goto __pyx_L5; } - __pyx_L5:; - /* "numpy.pxd":199 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -2340,7 +2852,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":200 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -2349,26 +2861,26 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":202 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":204 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":205 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -2376,11 +2888,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ * copy_shape = 0 */ __pyx_v_copy_shape = 1; - goto __pyx_L6; + goto __pyx_L4; } /*else*/ { - /* "numpy.pxd":207 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -2389,98 +2901,94 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_copy_shape = 0; } - __pyx_L6:; + __pyx_L4:; - /* "numpy.pxd":209 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_1) { - /* "numpy.pxd":210 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { - /* "numpy.pxd":211 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L7:; - /* "numpy.pxd":213 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_3) { - /* "numpy.pxd":214 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { - /* "numpy.pxd":215 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L8:; - /* "numpy.pxd":217 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":218 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -2489,16 +2997,17 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":219 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ - if (__pyx_v_copy_shape) { + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { - /* "numpy.pxd":222 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -2507,7 +3016,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":223 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -2516,7 +3025,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":224 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< @@ -2527,49 +3036,49 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "numpy.pxd":225 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":226 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } - goto __pyx_L9; + goto __pyx_L7; } /*else*/ { - /* "numpy.pxd":228 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":229 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } - __pyx_L9:; + __pyx_L7:; - /* "numpy.pxd":230 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -2578,25 +3087,25 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":231 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":232 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - /* "numpy.pxd":235 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -2605,17 +3114,19 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_f = NULL; - /* "numpy.pxd":236 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":240 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -2624,23 +3135,23 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":242 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; } if (__pyx_t_1) { - /* "numpy.pxd":244 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -2652,69 +3163,70 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; - goto __pyx_L12; + goto __pyx_L10; } /*else*/ { - /* "numpy.pxd":247 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } - __pyx_L12:; + __pyx_L10:; - /* "numpy.pxd":249 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { - /* "numpy.pxd":250 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; - /* "numpy.pxd":251 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; + __pyx_t_2 = (__pyx_v_little_endian != 0); } else { __pyx_t_2 = __pyx_t_1; } if (!__pyx_t_2) { - /* "numpy.pxd":252 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_7 = __pyx_t_3; } else { __pyx_t_7 = __pyx_t_1; @@ -2725,271 +3237,244 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (__pyx_t_1) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L14:; - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__b; - goto __pyx_L15; - } + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; - /* "numpy.pxd":255 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__B; - goto __pyx_L15; - } + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; - /* "numpy.pxd":256 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__h; - goto __pyx_L15; - } + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; - /* "numpy.pxd":257 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__H; - goto __pyx_L15; - } + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; - /* "numpy.pxd":258 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__i; - goto __pyx_L15; - } + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; - /* "numpy.pxd":259 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__I; - goto __pyx_L15; - } + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; - /* "numpy.pxd":260 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__l; - goto __pyx_L15; - } + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; - /* "numpy.pxd":261 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__L; - goto __pyx_L15; - } + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; - /* "numpy.pxd":262 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__q; - goto __pyx_L15; - } + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; - /* "numpy.pxd":263 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; - } + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; - /* "numpy.pxd":264 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__f; - goto __pyx_L15; - } + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; - /* "numpy.pxd":265 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__d; - goto __pyx_L15; - } + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; - /* "numpy.pxd":266 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__g; - goto __pyx_L15; - } + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; - /* "numpy.pxd":267 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; - } + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; - /* "numpy.pxd":268 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; - } + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; - /* "numpy.pxd":269 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; - } + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; - /* "numpy.pxd":270 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L15; - } - /*else*/ { + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: - /* "numpy.pxd":272 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L15:; - /* "numpy.pxd":273 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -2998,7 +3483,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":274 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -3007,58 +3492,65 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":276 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":277 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":278 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":281 - * f = _util_dtypestring(descr, info.format + 1, + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, - * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string - * + * &offset) */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; - /* "numpy.pxd":282 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L13:; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; @@ -3082,31 +3574,41 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ return __pyx_r; } -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__"); + __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":285 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { - /* "numpy.pxd":286 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -3114,21 +3616,21 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * stdlib.free(info.strides) */ free(__pyx_v_info->format); - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":287 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":288 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -3136,14 +3638,23 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * */ free(__pyx_v_info->strides); - goto __pyx_L6; + goto __pyx_L4; } - __pyx_L6:; + __pyx_L4:; + + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":764 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -3158,9 +3669,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":765 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -3168,14 +3679,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -3186,7 +3704,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":767 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -3201,9 +3719,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":768 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -3211,14 +3729,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -3229,7 +3754,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -3244,9 +3769,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":771 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -3254,14 +3779,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -3272,7 +3804,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -3287,9 +3819,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":774 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -3297,14 +3829,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -3315,7 +3854,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -3330,9 +3869,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":777 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -3340,14 +3879,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -3358,7 +3904,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -3380,7 +3926,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; + int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; int __pyx_t_8; @@ -3390,9 +3936,9 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring"); + __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":786 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -3401,7 +3947,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":787 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -3410,134 +3956,136 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":790 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ - if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":791 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; - /* "numpy.pxd":792 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * - * if (end - f) - (new_offset - offset[0]) < 15: - */ - if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { - PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; - /* "numpy.pxd":794 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { - /* "numpy.pxd":795 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L5:; - /* "numpy.pxd":797 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); + __pyx_t_6 = ((__pyx_v_child->byteorder == '>') != 0); if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = (__pyx_v_little_endian != 0); } else { __pyx_t_7 = __pyx_t_6; } if (!__pyx_t_7) { - /* "numpy.pxd":798 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); + __pyx_t_6 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); + __pyx_t_8 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_9 = __pyx_t_8; } else { __pyx_t_9 = __pyx_t_6; @@ -3548,23 +4096,21 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } if (__pyx_t_6) { - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; - /* "numpy.pxd":809 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -3572,16 +4118,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; - /* "numpy.pxd":810 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -3590,7 +4135,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":811 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -3599,7 +4144,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":812 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< @@ -3610,7 +4155,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); } - /* "numpy.pxd":814 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< @@ -3620,316 +4165,299 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_t_10 = 0; (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); - /* "numpy.pxd":816 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { - /* "numpy.pxd":817 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":818 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { - /* "numpy.pxd":819 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L10:; - /* "numpy.pxd":822 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L11; } - /* "numpy.pxd":823 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L11; } - /* "numpy.pxd":824 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 104; goto __pyx_L11; } - /* "numpy.pxd":825 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L11; } - /* "numpy.pxd":826 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 105; goto __pyx_L11; } - /* "numpy.pxd":827 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L11; } - /* "numpy.pxd":828 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 108; goto __pyx_L11; } - /* "numpy.pxd":829 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L11; } - /* "numpy.pxd":830 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 113; goto __pyx_L11; } - /* "numpy.pxd":831 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L11; } - /* "numpy.pxd":832 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 102; goto __pyx_L11; } - /* "numpy.pxd":833 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 100; goto __pyx_L11; } - /* "numpy.pxd":834 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 103; goto __pyx_L11; } - /* "numpy.pxd":835 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; @@ -3937,20 +4465,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":836 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; @@ -3958,20 +4485,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":837 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; @@ -3979,50 +4505,49 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":838 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":840 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L11:; - /* "numpy.pxd":841 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -4034,21 +4559,21 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } /*else*/ { - /* "numpy.pxd":845 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_11; } __pyx_L9:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":846 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -4058,13 +4583,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_r = __pyx_v_f; goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -4077,7 +4608,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":961 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -4089,9 +4620,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base"); + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":963 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -4099,9 +4631,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "numpy.pxd":964 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":969 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -4113,7 +4646,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":966 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":971 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -4122,7 +4655,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":967 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":972 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -4133,7 +4666,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":968 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":973 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -4142,7 +4675,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":969 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":974 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -4151,10 +4684,19 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ __pyx_v_arr->base = __pyx_v_baseptr; + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":971 +/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -4166,19 +4708,19 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base"); + __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":972 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { - /* "numpy.pxd":973 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":978 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -4189,11 +4731,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "numpy.pxd":975 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -4203,9 +4744,16 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } - __pyx_L3:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); @@ -4213,120 +4761,50 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py } static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset __pyx_vtable_7sklearn_5utils_11seq_dataset_SequentialDataset; -static PyObject *__pyx_tp_new_7sklearn_5utils_11seq_dataset_SequentialDataset(PyTypeObject *t, PyObject *a, PyObject *k) { +static PyObject *__pyx_tp_new_7sklearn_5utils_11seq_dataset_SequentialDataset(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *p; - PyObject *o = (*t->tp_alloc)(t, 0); - if (!o) return 0; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; p = ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *)o); p->__pyx_vtab = __pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset; + p->index = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); return o; } static void __pyx_tp_dealloc_7sklearn_5utils_11seq_dataset_SequentialDataset(PyObject *o) { + struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *p = (struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *)o; + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->index); (*Py_TYPE(o)->tp_free)(o); } -static PyMethodDef __pyx_methods_7sklearn_5utils_11seq_dataset_SequentialDataset[] = { - {0, 0, 0, 0} -}; - -static PyNumberMethods __pyx_tp_as_number_SequentialDataset = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; - -static PySequenceMethods __pyx_tp_as_sequence_SequentialDataset = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_SequentialDataset = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; +static int __pyx_tp_traverse_7sklearn_5utils_11seq_dataset_SequentialDataset(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *p = (struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *)o; + if (p->index) { + e = (*v)(((PyObject*)p->index), a); if (e) return e; + } + return 0; +} -static PyBufferProcs __pyx_tp_as_buffer_SequentialDataset = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; +static int __pyx_tp_clear_7sklearn_5utils_11seq_dataset_SequentialDataset(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *p = (struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *)o; + tmp = ((PyObject*)p->index); + p->index = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} static PyTypeObject __pyx_type_7sklearn_5utils_11seq_dataset_SequentialDataset = { PyVarObject_HEAD_INIT(0, 0) @@ -4343,24 +4821,24 @@ static PyTypeObject __pyx_type_7sklearn_5utils_11seq_dataset_SequentialDataset = 0, /*reserved*/ #endif 0, /*tp_repr*/ - &__pyx_tp_as_number_SequentialDataset, /*tp_as_number*/ - &__pyx_tp_as_sequence_SequentialDataset, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_SequentialDataset, /*tp_as_mapping*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_SequentialDataset, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ __Pyx_DOCSTR("Base class for datasets with sequential data access. "), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ + __pyx_tp_traverse_7sklearn_5utils_11seq_dataset_SequentialDataset, /*tp_traverse*/ + __pyx_tp_clear_7sklearn_5utils_11seq_dataset_SequentialDataset, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ - __pyx_methods_7sklearn_5utils_11seq_dataset_SequentialDataset, /*tp_methods*/ + 0, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ @@ -4382,18 +4860,20 @@ static PyTypeObject __pyx_type_7sklearn_5utils_11seq_dataset_SequentialDataset = #if PY_VERSION_HEX >= 0x02060000 0, /*tp_version_tag*/ #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif }; static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_ArrayDataset __pyx_vtable_7sklearn_5utils_11seq_dataset_ArrayDataset; static PyObject *__pyx_tp_new_7sklearn_5utils_11seq_dataset_ArrayDataset(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *p; PyObject *o = __pyx_tp_new_7sklearn_5utils_11seq_dataset_SequentialDataset(t, a, k); - if (!o) return 0; + if (unlikely(!o)) return 0; p = ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)o); p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset*)__pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset; p->feature_indices = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - p->index = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - if (__pyx_pf_7sklearn_5utils_11seq_dataset_12ArrayDataset___cinit__(o, a, k) < 0) { + if (unlikely(__pyx_pw_7sklearn_5utils_11seq_dataset_12ArrayDataset_1__cinit__(o, a, k) < 0)) { Py_DECREF(o); o = 0; } return o; @@ -4401,38 +4881,34 @@ static PyObject *__pyx_tp_new_7sklearn_5utils_11seq_dataset_ArrayDataset(PyTypeO static void __pyx_tp_dealloc_7sklearn_5utils_11seq_dataset_ArrayDataset(PyObject *o) { struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *p = (struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)o; - Py_XDECREF(((PyObject *)p->feature_indices)); - Py_XDECREF(((PyObject *)p->index)); + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->feature_indices); + PyObject_GC_Track(o); __pyx_tp_dealloc_7sklearn_5utils_11seq_dataset_SequentialDataset(o); } static int __pyx_tp_traverse_7sklearn_5utils_11seq_dataset_ArrayDataset(PyObject *o, visitproc v, void *a) { int e; struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *p = (struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)o; - if (__pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset->tp_traverse) { - e = __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset->tp_traverse(o, v, a); if (e) return e; - } + e = __pyx_tp_traverse_7sklearn_5utils_11seq_dataset_SequentialDataset(o, v, a); if (e) return e; if (p->feature_indices) { e = (*v)(((PyObject*)p->feature_indices), a); if (e) return e; } - if (p->index) { - e = (*v)(((PyObject*)p->index), a); if (e) return e; - } return 0; } static int __pyx_tp_clear_7sklearn_5utils_11seq_dataset_ArrayDataset(PyObject *o) { - struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *p = (struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)o; PyObject* tmp; - if (__pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset->tp_clear) { - __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset->tp_clear(o); - } + struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *p = (struct __pyx_obj_7sklearn_5utils_11seq_dataset_ArrayDataset *)o; + __pyx_tp_clear_7sklearn_5utils_11seq_dataset_SequentialDataset(o); tmp = ((PyObject*)p->feature_indices); p->feature_indices = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); Py_XDECREF(tmp); - tmp = ((PyObject*)p->index); - p->index = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); return 0; } @@ -4440,104 +4916,6 @@ static PyMethodDef __pyx_methods_7sklearn_5utils_11seq_dataset_ArrayDataset[] = {0, 0, 0, 0} }; -static PyNumberMethods __pyx_tp_as_number_ArrayDataset = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; - -static PySequenceMethods __pyx_tp_as_sequence_ArrayDataset = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_ArrayDataset = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_ArrayDataset = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; - static PyTypeObject __pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset = { PyVarObject_HEAD_INIT(0, 0) __Pyx_NAMESTR("sklearn.utils.seq_dataset.ArrayDataset"), /*tp_name*/ @@ -4553,17 +4931,17 @@ static PyTypeObject __pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset = { 0, /*reserved*/ #endif 0, /*tp_repr*/ - &__pyx_tp_as_number_ArrayDataset, /*tp_as_number*/ - &__pyx_tp_as_sequence_ArrayDataset, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_ArrayDataset, /*tp_as_mapping*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_ArrayDataset, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - __Pyx_DOCSTR("Dataset backed by a two-dimensional numpy array.\n\n The dtype of the numpy array is expected to be ``np.float64``\n and C-style memory layout.\n "), /*tp_doc*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Dataset backed by a two-dimensional numpy array.\n\n The dtype of the numpy array is expected to be ``np.float64`` (double)\n and C-style memory layout.\n "), /*tp_doc*/ __pyx_tp_traverse_7sklearn_5utils_11seq_dataset_ArrayDataset, /*tp_traverse*/ __pyx_tp_clear_7sklearn_5utils_11seq_dataset_ArrayDataset, /*tp_clear*/ 0, /*tp_richcompare*/ @@ -4592,18 +4970,20 @@ static PyTypeObject __pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset = { #if PY_VERSION_HEX >= 0x02060000 0, /*tp_version_tag*/ #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif }; static struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_CSRDataset __pyx_vtable_7sklearn_5utils_11seq_dataset_CSRDataset; static PyObject *__pyx_tp_new_7sklearn_5utils_11seq_dataset_CSRDataset(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *p; PyObject *o = __pyx_tp_new_7sklearn_5utils_11seq_dataset_SequentialDataset(t, a, k); - if (!o) return 0; + if (unlikely(!o)) return 0; p = ((struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)o); p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7sklearn_5utils_11seq_dataset_SequentialDataset*)__pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset; p->feature_indices = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - p->index = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - if (__pyx_pf_7sklearn_5utils_11seq_dataset_10CSRDataset___cinit__(o, a, k) < 0) { + if (unlikely(__pyx_pw_7sklearn_5utils_11seq_dataset_10CSRDataset_1__cinit__(o, a, k) < 0)) { Py_DECREF(o); o = 0; } return o; @@ -4611,38 +4991,34 @@ static PyObject *__pyx_tp_new_7sklearn_5utils_11seq_dataset_CSRDataset(PyTypeObj static void __pyx_tp_dealloc_7sklearn_5utils_11seq_dataset_CSRDataset(PyObject *o) { struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *p = (struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)o; - Py_XDECREF(((PyObject *)p->feature_indices)); - Py_XDECREF(((PyObject *)p->index)); + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->feature_indices); + PyObject_GC_Track(o); __pyx_tp_dealloc_7sklearn_5utils_11seq_dataset_SequentialDataset(o); } static int __pyx_tp_traverse_7sklearn_5utils_11seq_dataset_CSRDataset(PyObject *o, visitproc v, void *a) { int e; struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *p = (struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)o; - if (__pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset->tp_traverse) { - e = __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset->tp_traverse(o, v, a); if (e) return e; - } + e = __pyx_tp_traverse_7sklearn_5utils_11seq_dataset_SequentialDataset(o, v, a); if (e) return e; if (p->feature_indices) { e = (*v)(((PyObject*)p->feature_indices), a); if (e) return e; } - if (p->index) { - e = (*v)(((PyObject*)p->index), a); if (e) return e; - } return 0; } static int __pyx_tp_clear_7sklearn_5utils_11seq_dataset_CSRDataset(PyObject *o) { - struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *p = (struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)o; PyObject* tmp; - if (__pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset->tp_clear) { - __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset->tp_clear(o); - } + struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *p = (struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset *)o; + __pyx_tp_clear_7sklearn_5utils_11seq_dataset_SequentialDataset(o); tmp = ((PyObject*)p->feature_indices); p->feature_indices = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); Py_XDECREF(tmp); - tmp = ((PyObject*)p->index); - p->index = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); return 0; } @@ -4650,129 +5026,31 @@ static PyMethodDef __pyx_methods_7sklearn_5utils_11seq_dataset_CSRDataset[] = { {0, 0, 0, 0} }; -static PyNumberMethods __pyx_tp_as_number_CSRDataset = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ +static PyTypeObject __pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.utils.seq_dataset.CSRDataset"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_5utils_11seq_dataset_CSRDataset, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; - -static PySequenceMethods __pyx_tp_as_sequence_CSRDataset = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_CSRDataset = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_CSRDataset = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; - -static PyTypeObject __pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.utils.seq_dataset.CSRDataset"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_5utils_11seq_dataset_CSRDataset), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_5utils_11seq_dataset_CSRDataset, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ + 0, /*tp_compare*/ #else 0, /*reserved*/ #endif 0, /*tp_repr*/ - &__pyx_tp_as_number_CSRDataset, /*tp_as_number*/ - &__pyx_tp_as_sequence_CSRDataset, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_CSRDataset, /*tp_as_mapping*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_CSRDataset, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ __Pyx_DOCSTR("A ``SequentialDataset`` backed by a scipy sparse CSR matrix. "), /*tp_doc*/ __pyx_tp_traverse_7sklearn_5utils_11seq_dataset_CSRDataset, /*tp_traverse*/ __pyx_tp_clear_7sklearn_5utils_11seq_dataset_CSRDataset, /*tp_clear*/ @@ -4802,6 +5080,9 @@ static PyTypeObject __pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset = { #if PY_VERSION_HEX >= 0x02060000 0, /*tp_version_tag*/ #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif }; static PyMethodDef __pyx_methods[] = { @@ -4810,7 +5091,11 @@ static PyMethodDef __pyx_methods[] = { #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else PyModuleDef_HEAD_INIT, + #endif __Pyx_NAMESTR("seq_dataset"), 0, /* m_doc */ -1, /* m_size */ @@ -4823,40 +5108,43 @@ static struct PyModuleDef __pyx_moduledef = { #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_u_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 1, 0, 0}, - {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, - {&__pyx_kp_u_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 1, 0, 0}, - {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, - {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, - {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, - {&__pyx_n_s__NotImplementedError, __pyx_k__NotImplementedError, sizeof(__pyx_k__NotImplementedError), 0, 0, 1, 1}, - {&__pyx_n_s__RandomState, __pyx_k__RandomState, sizeof(__pyx_k__RandomState), 0, 0, 1, 1}, - {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s__X, __pyx_k__X, sizeof(__pyx_k__X), 0, 0, 1, 1}, - {&__pyx_n_s__X_data, __pyx_k__X_data, sizeof(__pyx_k__X_data), 0, 0, 1, 1}, - {&__pyx_n_s__X_indices, __pyx_k__X_indices, sizeof(__pyx_k__X_indices), 0, 0, 1, 1}, - {&__pyx_n_s__X_indptr, __pyx_k__X_indptr, sizeof(__pyx_k__X_indptr), 0, 0, 1, 1}, - {&__pyx_n_s__Y, __pyx_k__Y, sizeof(__pyx_k__Y), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__arange, __pyx_k__arange, sizeof(__pyx_k__arange), 0, 0, 1, 1}, - {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, - {&__pyx_n_s__int32, __pyx_k__int32, sizeof(__pyx_k__int32), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__random, __pyx_k__random, sizeof(__pyx_k__random), 0, 0, 1, 1}, - {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__sample_weight, __pyx_k__sample_weight, sizeof(__pyx_k__sample_weight), 0, 0, 1, 1}, - {&__pyx_n_s__sample_weights, __pyx_k__sample_weights, sizeof(__pyx_k__sample_weights), 0, 0, 1, 1}, - {&__pyx_n_s__shuffle, __pyx_k__shuffle, sizeof(__pyx_k__shuffle), 0, 0, 1, 1}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_kp_s_More_than_d_samples_or_features, __pyx_k_More_than_d_samples_or_features, sizeof(__pyx_k_More_than_d_samples_or_features), 0, 0, 1, 0}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_s_NotImplementedError, __pyx_k_NotImplementedError, sizeof(__pyx_k_NotImplementedError), 0, 0, 1, 1}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_n_s_X_data, __pyx_k_X_data, sizeof(__pyx_k_X_data), 0, 0, 1, 1}, + {&__pyx_n_s_X_indices, __pyx_k_X_indices, sizeof(__pyx_k_X_indices), 0, 0, 1, 1}, + {&__pyx_n_s_X_indptr, __pyx_k_X_indptr, sizeof(__pyx_k_X_indptr), 0, 0, 1, 1}, + {&__pyx_n_s_Y, __pyx_k_Y, sizeof(__pyx_k_Y), 0, 0, 1, 1}, + {&__pyx_n_s_arange, __pyx_k_arange, sizeof(__pyx_k_arange), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_intc, __pyx_k_intc, sizeof(__pyx_k_intc), 0, 0, 1, 1}, + {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_releasebuffer, __pyx_k_pyx_releasebuffer, sizeof(__pyx_k_pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_sample_weight, __pyx_k_sample_weight, sizeof(__pyx_k_sample_weight), 0, 0, 1, 1}, + {&__pyx_n_s_sample_weights, __pyx_k_sample_weights, sizeof(__pyx_k_sample_weights), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_NotImplementedError = __Pyx_GetName(__pyx_b, __pyx_n_s__NotImplementedError); if (!__pyx_builtin_NotImplementedError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_NotImplementedError = __Pyx_GetBuiltinName(__pyx_n_s_NotImplementedError); if (!__pyx_builtin_NotImplementedError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -4864,91 +5152,73 @@ static int __Pyx_InitCachedBuiltins(void) { static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "numpy.pxd":211 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_2 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_2)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_1)); - PyTuple_SET_ITEM(__pyx_k_tuple_2, 0, ((PyObject *)__pyx_kp_u_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); - /* "numpy.pxd":215 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_4)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_3)); - PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_u_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_6)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); - /* "numpy.pxd":795 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_9)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_10)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); - /* "numpy.pxd":819 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_12)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); - PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -4958,8 +5228,7 @@ static int __Pyx_InitCachedConstants(void) { static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -4974,6 +5243,9 @@ PyMODINIT_FUNC PyInit_seq_dataset(void) #endif { PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -4984,12 +5256,18 @@ PyMODINIT_FUNC PyInit_seq_dataset(void) Py_FatalError("failed to import 'refnanny' module"); } #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_seq_dataset(void)"); + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_seq_dataset(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __pyx_binding_PyCFunctionType_USED - if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -5000,22 +5278,34 @@ PyMODINIT_FUNC PyInit_seq_dataset(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("seq_dataset"), __pyx_methods, 0, 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("seq_dataset"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif if (__pyx_module_is_main_sklearn__utils__seq_dataset) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.utils.seq_dataset")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.utils.seq_dataset", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } } + #endif /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ @@ -5025,63 +5315,80 @@ PyMODINIT_FUNC PyInit_seq_dataset(void) /*--- Function export code ---*/ /*--- Type init code ---*/ __pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset = &__pyx_vtable_7sklearn_5utils_11seq_dataset_SequentialDataset; - __pyx_vtable_7sklearn_5utils_11seq_dataset_SequentialDataset.next = (void (*)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE **, __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER **, int *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *))__pyx_f_7sklearn_5utils_11seq_dataset_17SequentialDataset_next; - __pyx_vtable_7sklearn_5utils_11seq_dataset_SequentialDataset.shuffle = (void (*)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, PyObject *))__pyx_f_7sklearn_5utils_11seq_dataset_17SequentialDataset_shuffle; - if (PyType_Ready(&__pyx_type_7sklearn_5utils_11seq_dataset_SequentialDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_5utils_11seq_dataset_SequentialDataset.tp_dict, __pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "SequentialDataset", (PyObject *)&__pyx_type_7sklearn_5utils_11seq_dataset_SequentialDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtable_7sklearn_5utils_11seq_dataset_SequentialDataset.next = (void (*)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, double **, int **, int *, double *, double *))__pyx_f_7sklearn_5utils_11seq_dataset_17SequentialDataset_next; + __pyx_vtable_7sklearn_5utils_11seq_dataset_SequentialDataset.shuffle = (void (*)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, __pyx_t_5numpy_uint32_t))__pyx_f_7sklearn_5utils_11seq_dataset_17SequentialDataset_shuffle; + if (PyType_Ready(&__pyx_type_7sklearn_5utils_11seq_dataset_SequentialDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_5utils_11seq_dataset_SequentialDataset.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_5utils_11seq_dataset_SequentialDataset.tp_dict, __pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "SequentialDataset", (PyObject *)&__pyx_type_7sklearn_5utils_11seq_dataset_SequentialDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset = &__pyx_type_7sklearn_5utils_11seq_dataset_SequentialDataset; __pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset = &__pyx_vtable_7sklearn_5utils_11seq_dataset_ArrayDataset; __pyx_vtable_7sklearn_5utils_11seq_dataset_ArrayDataset.__pyx_base = *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset; - __pyx_vtable_7sklearn_5utils_11seq_dataset_ArrayDataset.__pyx_base.next = (void (*)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE **, __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER **, int *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *))__pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_next; - __pyx_vtable_7sklearn_5utils_11seq_dataset_ArrayDataset.__pyx_base.shuffle = (void (*)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, PyObject *))__pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_shuffle; + __pyx_vtable_7sklearn_5utils_11seq_dataset_ArrayDataset.__pyx_base.next = (void (*)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, double **, int **, int *, double *, double *))__pyx_f_7sklearn_5utils_11seq_dataset_12ArrayDataset_next; __pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset.tp_base = __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset; - if (PyType_Ready(&__pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset.tp_dict, __pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "ArrayDataset", (PyObject *)&__pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyType_Ready(&__pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset.tp_dict, __pyx_vtabptr_7sklearn_5utils_11seq_dataset_ArrayDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "ArrayDataset", (PyObject *)&__pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_7sklearn_5utils_11seq_dataset_ArrayDataset = &__pyx_type_7sklearn_5utils_11seq_dataset_ArrayDataset; __pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset = &__pyx_vtable_7sklearn_5utils_11seq_dataset_CSRDataset; __pyx_vtable_7sklearn_5utils_11seq_dataset_CSRDataset.__pyx_base = *__pyx_vtabptr_7sklearn_5utils_11seq_dataset_SequentialDataset; - __pyx_vtable_7sklearn_5utils_11seq_dataset_CSRDataset.__pyx_base.next = (void (*)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE **, __pyx_t_7sklearn_5utils_11seq_dataset_INTEGER **, int *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *, __pyx_t_7sklearn_5utils_11seq_dataset_DOUBLE *))__pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next; - __pyx_vtable_7sklearn_5utils_11seq_dataset_CSRDataset.__pyx_base.shuffle = (void (*)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, PyObject *))__pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_shuffle; + __pyx_vtable_7sklearn_5utils_11seq_dataset_CSRDataset.__pyx_base.next = (void (*)(struct __pyx_obj_7sklearn_5utils_11seq_dataset_SequentialDataset *, double **, int **, int *, double *, double *))__pyx_f_7sklearn_5utils_11seq_dataset_10CSRDataset_next; __pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset.tp_base = __pyx_ptype_7sklearn_5utils_11seq_dataset_SequentialDataset; - if (PyType_Ready(&__pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset.tp_dict, __pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "CSRDataset", (PyObject *)&__pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyType_Ready(&__pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset.tp_dict, __pyx_vtabptr_7sklearn_5utils_11seq_dataset_CSRDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "CSRDataset", (PyObject *)&__pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_7sklearn_5utils_11seq_dataset_CSRDataset = &__pyx_type_7sklearn_5utils_11seq_dataset_CSRDataset; /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ - /* "sklearn/utils/seq_dataset.pyx":10 - * # License: BSD Style. - * + /* "sklearn/utils/seq_dataset.pyx":12 + * from libc.limits cimport INT_MAX + * cimport numpy as np * import numpy as np # <<<<<<<<<<<<<< * - * cimport numpy as np + * np.import_array() */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /* "sklearn/utils/seq_dataset.pyx":14 + * import numpy as np + * + * np.import_array() # <<<<<<<<<<<<<< + * + * + */ + import_array(); + /* "sklearn/utils/seq_dataset.pyx":1 - * # encoding: utf-8 # <<<<<<<<<<<<<< - * # cython: cdivision=True + * # cython: cdivision=True # <<<<<<<<<<<<<< * # cython: boundscheck=False + * # cython: wraparound=False */ __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":971 + /* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -5107,7 +5414,6 @@ PyMODINIT_FUNC PyInit_seq_dataset(void) } /* Runtime support code */ - #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; @@ -5124,25 +5430,46 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { } #endif /* CYTHON_REFNANNY */ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; +#endif + result = (*call)(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + Py_LeaveRecursiveCall(); +#endif + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); } return result; } +#endif static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; @@ -5152,78 +5479,81 @@ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyOb Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif } - static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif } - #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } } #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) + if (PyClass_Check(type)) { #else - if (!PyType_Check(type)) + if (PyType_Check(type)) { #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - /* Normalize to raise , */ - Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } #endif } - __Pyx_ErrRestore(type, value, tb); return; raise_error: @@ -5232,10 +5562,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tb); return; } - #else /* Python 3+ */ - static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -5245,7 +5574,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } if (value == Py_None) value = 0; - if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, @@ -5254,37 +5582,71 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } - +#if PY_VERSION_HEX >= 0x03030000 if (cause) { +#else + if (cause && cause != Py_None) { +#endif PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; - } - else if (PyExceptionInstance_Check(cause)) { + } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; @@ -5294,12 +5656,39 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tmp_tb); } } - bad: + Py_XDECREF(owned_instance); return; } #endif +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, + int full_traceback) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + if (full_traceback) { + Py_XINCREF(old_exc); + Py_XINCREF(old_val); + Py_XINCREF(old_tb); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + PyErr_PrintEx(1); + } + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, @@ -5309,7 +5698,6 @@ static void __Pyx_RaiseArgtupleInvalid( { Py_ssize_t num_expected; const char *more_or_less; - if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; @@ -5321,7 +5709,7 @@ static void __Pyx_RaiseArgtupleInvalid( more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } @@ -5335,7 +5723,7 @@ static void __Pyx_RaiseDoubleKeywordsError( "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); + PyString_AsString(kw_name)); #endif } @@ -5351,64 +5739,86 @@ static int __Pyx_ParseOptionalKeywords( Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { values[name-argnames] = value; - } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; } } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; } } return 0; arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); + __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); + "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", + "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", @@ -5418,23 +5828,29 @@ static int __Pyx_ParseOptionalKeywords( return -1; } -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { - if (Py_TYPE(obj) == type) return 1; + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif } else { - if (PyObject_TypeCheck(obj, type)) return 1; + if (likely(PyObject_TypeCheck(obj, type))) return 1; } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } @@ -5442,18 +5858,6 @@ static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } - -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; -} __Pyx_BufFmt_Context; - static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { @@ -5472,6 +5876,8 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; @@ -5479,7 +5885,6 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, type = type->fields->type; } } - static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; @@ -5495,15 +5900,21 @@ static int __Pyx_BufFmt_ParseNumber(const char** ts) { *ts = t; return count; } - +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } - static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { - case 'b': return "'char'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; @@ -5519,14 +5930,14 @@ static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; + case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } - static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; @@ -5542,10 +5953,9 @@ static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { return 0; } } - static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'B': return 1; + case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); @@ -5562,7 +5972,6 @@ static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { } } } - typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; @@ -5573,10 +5982,9 @@ typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif - -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); @@ -5592,21 +6000,59 @@ static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { return 0; } } - +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'h': case 'i': case 'l': case 'q': return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; - case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); - case 'O': return 'O'; - case 'P': return 'P'; + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } - static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; @@ -5631,16 +6077,37 @@ static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { parent->type->name, field->name); } } - static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; - size_t size, offset; + size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { @@ -5652,35 +6119,35 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); } - if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { - /* special case -- treat as struct rather than complex number */ size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } - - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } - offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } - ctx->fmt_offset += size; - + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; /* Consume from buffer string */ - - /* Done checking, move to next field, pushing or popping struct stack if needed */ while (1) { if (field == &ctx->root) { ctx->head = NULL; @@ -5712,7 +6179,50 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ctx->is_complex = 0; return 0; } - +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; /* not a 'break' in the loop */ + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { @@ -5727,7 +6237,7 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } - return ts; + return ts; case ' ': case 10: case 13: @@ -5759,12 +6269,17 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { @@ -5772,10 +6287,19 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha if (!ts_after_sub) return NULL; } ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': /* end of substruct; either repeat or move on */ - ++ts; + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; @@ -5796,13 +6320,11 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': - case 'O': + case 'O': case 's': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { - /* Continue pooling same type */ ctx->enc_count += ctx->new_count; } else { - /* New type */ if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; @@ -5818,20 +6340,18 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha while(*ts != ':') ++ts; ++ts; break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; default: { - int number = __Pyx_BufFmt_ParseNumber(&ts); - if (number == -1) { /* First char was not a digit */ - PyErr_Format(PyExc_ValueError, - "Does not understand character buffer dtype format string ('%c')", *ts); - return NULL; - } - ctx->new_count = (size_t)number; + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; } } } } - static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; @@ -5839,8 +6359,10 @@ static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; @@ -5860,7 +6382,7 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* ob } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; @@ -5871,16 +6393,32 @@ fail:; __Pyx_ZeroBuffer(buf); return -1; } - static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); + PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) @@ -5890,67 +6428,115 @@ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { return 0; } -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); - } else { - __Pyx_RaiseTooManyValuesError(index); - } +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); - else { - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } } + #endif + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; } - static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject* obj = view->obj; - if (obj) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;} - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray_1__releasebuffer__(obj, view); + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: Py_DECREF(obj); view->obj = NULL; - } } +#endif /* PY_MAJOR_VERSION < 3 */ -#endif -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; + #endif if (from_list) list = from_list; else { @@ -5967,12 +6553,42 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { goto bad; #if PY_VERSION_HEX >= 0x02050000 { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } } #else if (level>0) { @@ -5983,12 +6599,308 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { name, global_dict, empty_dict, list, NULL); #endif bad: - Py_XDECREF(empty_list); + #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); + } +} + +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \ + { \ + func_type value = func(x); \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + PyErr_SetString(PyExc_OverflowError, \ + (is_unsigned && unlikely(value < zero)) ? \ + "can't convert negative value to " #target_type : \ + "value too large to convert to " #target_type); \ + return (target_type) -1; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) { + const unsigned int neg_one = (unsigned int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(unsigned int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned int"); + return (unsigned int) -1; + } + return (unsigned int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned int"); + return (unsigned int) -1; + } + if (sizeof(unsigned int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(unsigned int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned int) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(unsigned int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyLong_AsLong) + } else if (sizeof(unsigned int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + unsigned int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (unsigned int) -1; + } + } else { + unsigned int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned int) -1; + val = __Pyx_PyInt_As_unsigned_int(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(Py_intptr_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(int) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +} + #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { @@ -6229,425 +7141,106 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; - } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; - } - return (unsigned short)val; - } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; - } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; - } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; - } - return (short)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; - } - return (signed char)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; - } - return (signed short)val; - } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; - } - return (signed int)val; - } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; + "can't convert negative value to long"); + return (long) -1; } - return (unsigned long)PyLong_AsUnsignedLong(x); - } else { - return (unsigned long)PyLong_AsLong(x); - } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; + return (long) val; } - return (unsigned PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)val; - } else + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); - return (long)-1; + return (long) -1; } - return (long)PyLong_AsUnsignedLong(x); - } else { - return (long)PyLong_AsLong(x); - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong) } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { - return (PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)val; - } else +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong) } - return (signed long)PyLong_AsUnsignedLong(x); - } else { - return (signed long)PyLong_AsLong(x); - } - } else { - signed long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; } - return (signed PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; } } else { - signed PY_LONG_LONG val; + long val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } } -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename) { - PyObject *old_exc, *old_val, *old_tb; - PyObject *ctx; - __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); - #if PY_MAJOR_VERSION < 3 - ctx = PyString_FromString(name); - #else - ctx = PyUnicode_FromString(name); - #endif - __Pyx_ErrRestore(old_exc, old_val, old_tb); - if (!ctx) { - PyErr_WriteUnraisable(Py_None); - } else { - PyErr_WriteUnraisable(ctx); - Py_DECREF(ctx); - } -} - static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); @@ -6667,22 +7260,22 @@ static int __Pyx_check_binary_version(void) { return 0; } -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItemString(dict, "__pyx_vtable__", ob) < 0) +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) goto bad; - Py_DECREF(ob); - return 0; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; bad: - Py_XDECREF(ob); - return -1; + Py_XDECREF(py_name); + return 0; } +#endif #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType @@ -6693,15 +7286,14 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(class_name); - #else - py_name = PyUnicode_FromString(class_name); - #endif + py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); @@ -6713,11 +7305,23 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", + "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -6727,9 +7331,9 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", + "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } @@ -6741,51 +7345,105 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(name); - #else - py_name = PyUnicode_FromString(name); - #endif - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); } -#endif #include "compile.h" #include "frameobject.h" #include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); + py_srcfile = PyString_FromString(filename); #else - py_srcfile = PyUnicode_FromString(__pyx_filename); + py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; - if (__pyx_clineno) { + if (c_line) { #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { @@ -6796,28 +7454,45 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, #endif } if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_code = PyCode_New( + py_code = __Pyx_PyCode_New( 0, /*int argcount,*/ - #if PY_MAJOR_VERSION >= 3 0, /*int kwonlyargcount,*/ - #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ + py_line, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); - if (!py_code) goto bad; + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ @@ -6825,11 +7500,9 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; + py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); } @@ -6864,26 +7537,90 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ +#if !CYTHON_COMPILING_IN_PYPY +#if PY_VERSION_HEX >= 0x02060000 + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -6899,13 +7636,13 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", + "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; @@ -6917,16 +7654,40 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + #if PY_VERSION_HEX < 0x02060000 + return PyInt_AsSsize_t(b); + #else + return PyLong_AsSsize_t(b); + #endif + } + x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) @@ -6941,17 +7702,5 @@ static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #endif } -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; -} - #endif /* Py_PYTHON_H */ diff --git a/sklearn/utils/seq_dataset.pxd b/sklearn/utils/seq_dataset.pxd index 1b38ca97820fb..61c8e9a059d3a 100644 --- a/sklearn/utils/seq_dataset.pxd +++ b/sklearn/utils/seq_dataset.pxd @@ -2,48 +2,42 @@ cimport numpy as np -ctypedef np.float64_t DOUBLE -ctypedef np.int32_t INTEGER - +# SequentialDataset and its two concrete subclasses are (optionally randomized) +# iterators over the rows of a matrix X and corresponding target values y. cdef class SequentialDataset: + cdef int current_index + cdef np.ndarray index + cdef int *index_data_ptr cdef Py_ssize_t n_samples - cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, - int *nnz, DOUBLE *y, DOUBLE *sample_weight) - cdef void shuffle(self, seed) + cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight) nogil + cdef void shuffle(self, np.uint32_t seed) nogil cdef class ArrayDataset(SequentialDataset): cdef Py_ssize_t n_features - cdef int current_index cdef int stride - cdef DOUBLE *X_data_ptr - cdef DOUBLE *Y_data_ptr + cdef double *X_data_ptr + cdef double *Y_data_ptr cdef np.ndarray feature_indices - cdef INTEGER *feature_indices_ptr - cdef np.ndarray index - cdef INTEGER *index_data_ptr - cdef DOUBLE *sample_weight_data + cdef int *feature_indices_ptr + cdef double *sample_weight_data - cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, - int *nnz, DOUBLE *y, DOUBLE *sample_weight) - cdef void shuffle(self, seed) + cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight) nogil cdef class CSRDataset(SequentialDataset): - cdef int current_index cdef int stride - cdef DOUBLE *X_data_ptr - cdef INTEGER *X_indptr_ptr - cdef INTEGER *X_indices_ptr - cdef DOUBLE *Y_data_ptr + cdef double *X_data_ptr + cdef int *X_indptr_ptr + cdef int *X_indices_ptr + cdef double *Y_data_ptr cdef np.ndarray feature_indices - cdef INTEGER *feature_indices_ptr - cdef np.ndarray index - cdef INTEGER *index_data_ptr - cdef DOUBLE *sample_weight_data + cdef int *feature_indices_ptr + cdef double *sample_weight_data - cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, - int *nnz, DOUBLE *y, DOUBLE *sample_weight) - cdef void shuffle(self, seed) + cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight) nogil diff --git a/sklearn/utils/seq_dataset.pyx b/sklearn/utils/seq_dataset.pyx index aada198e1ddb7..23e57c8e63bc8 100644 --- a/sklearn/utils/seq_dataset.pyx +++ b/sklearn/utils/seq_dataset.pyx @@ -1,94 +1,106 @@ -# encoding: utf-8 # cython: cdivision=True # cython: boundscheck=False # cython: wraparound=False # # Author: Peter Prettenhofer # -# License: BSD Style. +# Licence: BSD 3 clause +cimport cython +from libc.limits cimport INT_MAX +cimport numpy as np import numpy as np -cimport numpy as np -cimport cython +np.import_array() cdef class SequentialDataset: """Base class for datasets with sequential data access. """ - cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, - int *nnz, DOUBLE *y, DOUBLE *sample_weight): + cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight) nogil: """Get the next example ``x`` from the dataset. Parameters ---------- - x_data_ptr : np.float64** + x_data_ptr : double** A pointer to the double array which holds the feature values of the next example. - x_ind_ptr : np.int32** - A pointer to the int32 array which holds the feature + x_ind_ptr : np.intc** + A pointer to the int array which holds the feature indices of the next example. nnz : int* A pointer to an int holding the number of non-zero values of the next example. - y : np.float64* + y : double* The target value of the next example. - sample_weight : np.float64* + sample_weight : double* The weight of the next example. """ - raise NotImplementedError() + with gil: + raise NotImplementedError() - cdef void shuffle(self, seed): - """Permutes the ordering of examples. """ - raise NotImplementedError() + cdef void shuffle(self, np.uint32_t seed) nogil: + """Permutes the ordering of examples.""" + # Fisher-Yates shuffle + cdef int *ind = self.index_data_ptr + cdef int n = self.n_samples + cdef unsigned i, j + for i in range(n - 1): + j = i + our_rand_r(&seed) % (n - i) + ind[i], ind[j] = ind[j], ind[i] cdef class ArrayDataset(SequentialDataset): """Dataset backed by a two-dimensional numpy array. - The dtype of the numpy array is expected to be ``np.float64`` + The dtype of the numpy array is expected to be ``np.float64`` (double) and C-style memory layout. """ - def __cinit__(self, np.ndarray[DOUBLE, ndim=2, mode='c'] X, - np.ndarray[DOUBLE, ndim=1, mode='c'] Y, - np.ndarray[DOUBLE, ndim=1, mode='c'] sample_weights): + def __cinit__(self, np.ndarray[double, ndim=2, mode='c'] X, + np.ndarray[double, ndim=1, mode='c'] Y, + np.ndarray[double, ndim=1, mode='c'] sample_weights): """A ``SequentialDataset`` backed by a two-dimensional numpy array. - Paramters - --------- - X : ndarray, dtype=np.float64, ndim=2, mode='c' + Parameters + ---------- + X : ndarray, dtype=double, ndim=2, mode='c' The samples; a two-dimensional c-continuous numpy array of - dtype np.float64. - Y : ndarray, dtype=np.float64, ndim=1, mode='c' + dtype double. + Y : ndarray, dtype=double, ndim=1, mode='c' The target values; a one-dimensional c-continuous numpy array of - dtype np.float64. - sample_weights : ndarray, dtype=np.float64, ndim=1, mode='c' + dtype double. + sample_weights : ndarray, dtype=double, ndim=1, mode='c' The weight of each sample; a one-dimensional c-continuous numpy - array of dtype np.float64. + array of dtype double. """ + if X.shape[0] > INT_MAX or X.shape[1] > INT_MAX: + raise ValueError("More than %d samples or features not supported;" + " got (%d, %d)." + % (INT_MAX, X.shape[0], X.shape[1])) + self.n_samples = X.shape[0] self.n_features = X.shape[1] - cdef np.ndarray[INTEGER, ndim=1, + cdef np.ndarray[int, ndim=1, mode='c'] feature_indices = np.arange(0, self.n_features, - dtype=np.int32) + dtype=np.intc) self.feature_indices = feature_indices - self.feature_indices_ptr = feature_indices.data + self.feature_indices_ptr = feature_indices.data self.current_index = -1 - self.stride = X.strides[0] / X.strides[1] - self.X_data_ptr = X.data - self.Y_data_ptr = Y.data - self.sample_weight_data = sample_weights.data + self.stride = X.strides[0] / X.itemsize + self.X_data_ptr = X.data + self.Y_data_ptr = Y.data + self.sample_weight_data = sample_weights.data # Use index array for fast shuffling - cdef np.ndarray[INTEGER, ndim=1, - mode='c'] index = np.arange(0, self.n_samples, - dtype=np.int32) + cdef np.ndarray[int, ndim=1, mode='c'] index = \ + np.arange(0, self.n_samples, dtype=np.intc) self.index = index - self.index_data_ptr = index.data + self.index_data_ptr = index.data - cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, - int *nnz, DOUBLE *y, DOUBLE *sample_weight): + cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight) nogil: cdef int current_index = self.current_index if current_index >= (self.n_samples - 1): current_index = -1 @@ -105,18 +117,15 @@ cdef class ArrayDataset(SequentialDataset): self.current_index = current_index - cdef void shuffle(self, seed): - np.random.RandomState(seed).shuffle(self.index) - cdef class CSRDataset(SequentialDataset): """A ``SequentialDataset`` backed by a scipy sparse CSR matrix. """ - def __cinit__(self, np.ndarray[DOUBLE, ndim=1, mode='c'] X_data, - np.ndarray[INTEGER, ndim=1, mode='c'] X_indptr, - np.ndarray[INTEGER, ndim=1, mode='c'] X_indices, - np.ndarray[DOUBLE, ndim=1, mode='c'] Y, - np.ndarray[DOUBLE, ndim=1, mode='c'] sample_weight): + def __cinit__(self, np.ndarray[double, ndim=1, mode='c'] X_data, + np.ndarray[int, ndim=1, mode='c'] X_indptr, + np.ndarray[int, ndim=1, mode='c'] X_indices, + np.ndarray[double, ndim=1, mode='c'] Y, + np.ndarray[double, ndim=1, mode='c'] sample_weight): """Dataset backed by a scipy sparse CSR matrix. The feature indices of ``x`` are given by x_ind_ptr[0:nnz]. @@ -125,38 +134,37 @@ cdef class CSRDataset(SequentialDataset): Parameters ---------- - X_data : ndarray, dtype=np.float64, ndim=1, mode='c' + X_data : ndarray, dtype=double, ndim=1, mode='c' The data array of the CSR matrix; a one-dimensional c-continuous - numpy array of dtype np.float64. - X_indptr : ndarray, dtype=np.int32, ndim=1, mode='c' + numpy array of dtype double. + X_indptr : ndarray, dtype=np.intc, ndim=1, mode='c' The index pointer array of the CSR matrix; a one-dimensional - c-continuous numpy array of dtype np.int32. - X_indices : ndarray, dtype=np.int32, ndim=1, mode='c' + c-continuous numpy array of dtype np.intc. + X_indices : ndarray, dtype=np.intc, ndim=1, mode='c' The column indices array of the CSR matrix; a one-dimensional - c-continuous numpy array of dtype np.int32. - Y : ndarray, dtype=np.float64, ndim=1, mode='c' + c-continuous numpy array of dtype np.intc. + Y : ndarray, dtype=double, ndim=1, mode='c' The target values; a one-dimensional c-continuous numpy array of - dtype np.float64. - sample_weights : ndarray, dtype=np.float64, ndim=1, mode='c' + dtype double. + sample_weights : ndarray, dtype=double, ndim=1, mode='c' The weight of each sample; a one-dimensional c-continuous numpy - array of dtype np.float64. + array of dtype double. """ self.n_samples = Y.shape[0] self.current_index = -1 - self.X_data_ptr = X_data.data - self.X_indptr_ptr = X_indptr.data - self.X_indices_ptr = X_indices.data - self.Y_data_ptr = Y.data - self.sample_weight_data = sample_weight.data + self.X_data_ptr = X_data.data + self.X_indptr_ptr = X_indptr.data + self.X_indices_ptr = X_indices.data + self.Y_data_ptr = Y.data + self.sample_weight_data = sample_weight.data # Use index array for fast shuffling - cdef np.ndarray[INTEGER, ndim=1, - mode='c'] index = np.arange(0, self.n_samples, - dtype=np.int32) - self.index = index - self.index_data_ptr = index.data + cdef np.ndarray[int, ndim=1, mode='c'] idx = np.arange(self.n_samples, + dtype=np.intc) + self.index = idx + self.index_data_ptr = idx.data - cdef void next(self, DOUBLE **x_data_ptr, INTEGER **x_ind_ptr, - int *nnz, DOUBLE *y, DOUBLE *sample_weight): + cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight) nogil: cdef int current_index = self.current_index if current_index >= (self.n_samples - 1): current_index = -1 @@ -172,5 +180,17 @@ cdef class CSRDataset(SequentialDataset): self.current_index = current_index - cdef void shuffle(self, seed): - np.random.RandomState(seed).shuffle(self.index) + +cdef enum: + RAND_R_MAX = 0x7FFFFFFF + + +# rand_r replacement using a 32bit XorShift generator +# See http://www.jstatsoft.org/v08/i14/paper for details +# XXX copied over from sklearn/tree/_tree.pyx, should refactor +cdef inline np.uint32_t our_rand_r(np.uint32_t* seed) nogil: + seed[0] ^= (seed[0] << 13) + seed[0] ^= (seed[0] >> 17) + seed[0] ^= (seed[0] << 5) + + return seed[0] % (RAND_R_MAX + 1) diff --git a/sklearn/utils/setup.py b/sklearn/utils/setup.py index 16f717bfc1a2a..ac321e7d7aa5d 100644 --- a/sklearn/utils/setup.py +++ b/sklearn/utils/setup.py @@ -12,47 +12,67 @@ def configuration(parent_package='', top_path=None): config.add_subpackage('sparsetools') cblas_libs, blas_info = get_blas_info() + cblas_compile_args = blas_info.pop('extra_compile_args', []) + cblas_includes = [join('..', 'src', 'cblas'), + numpy.get_include(), + blas_info.pop('include_dirs', [])] libraries = [] if os.name == 'posix': libraries.append('m') cblas_libs.append('m') - config.add_extension('arraybuilder', - sources=['arraybuilder.c']) - - config.add_extension('sparsefuncs', - sources=['sparsefuncs.c'], - libraries=libraries) + config.add_extension('sparsefuncs_fast', sources=['sparsefuncs_fast.c'], + libraries=libraries) config.add_extension('arrayfuncs', - sources=['arrayfuncs.c'], - depends=[join('src', 'cholesky_delete.c')], - libraries=cblas_libs, - include_dirs=[join('..', 'src', 'cblas'), - numpy.get_include(), - blas_info.pop('include_dirs', [])], - extra_compile_args=blas_info.pop('extra_compile_args', []), - **blas_info - ) + sources=['arrayfuncs.c'], + depends=[join('src', 'cholesky_delete.h')], + libraries=cblas_libs, + include_dirs=cblas_includes, + extra_compile_args=cblas_compile_args, + **blas_info + ) config.add_extension( 'murmurhash', sources=['murmurhash.c', join('src', 'MurmurHash3.cpp')], include_dirs=['src']) + config.add_extension('lgamma', + sources=['lgamma.c', join('src', 'gamma.c')], + include_dirs=['src'], + libraries=libraries) + config.add_extension('graph_shortest_path', - sources=['graph_shortest_path.c'], - include_dirs=[numpy.get_include()]) + sources=['graph_shortest_path.c'], + include_dirs=[numpy.get_include()]) + + config.add_extension('fast_dict', + sources=['fast_dict.cpp'], + language="c++", + include_dirs=[numpy.get_include()], + libraries=libraries) config.add_extension('seq_dataset', - sources=['seq_dataset.c'], - include_dirs=[numpy.get_include()]) + sources=['seq_dataset.c'], + include_dirs=[numpy.get_include()]) config.add_extension('weight_vector', - sources=['weight_vector.c'], - include_dirs=[numpy.get_include()], - libraries=libraries) + sources=['weight_vector.c'], + include_dirs=cblas_includes, + libraries=cblas_libs, + **blas_info) + + config.add_extension("_random", + sources=["_random.c"], + include_dirs=[numpy.get_include()], + libraries=libraries) + + config.add_extension("_logistic_sigmoid", + sources=["_logistic_sigmoid.c"], + include_dirs=[numpy.get_include()], + libraries=libraries) return config diff --git a/sklearn/utils/sparsefuncs.py b/sklearn/utils/sparsefuncs.py new file mode 100644 index 0000000000000..04e383ab928b8 --- /dev/null +++ b/sklearn/utils/sparsefuncs.py @@ -0,0 +1,404 @@ +# Authors: Manoj Kumar +# Thomas Unterthiner + +# License: BSD 3 clause +import scipy.sparse as sp +import numpy as np + +from .fixes import sparse_min_max, bincount +from .sparsefuncs_fast import csr_mean_variance_axis0 as _csr_mean_var_axis0 +from .sparsefuncs_fast import csc_mean_variance_axis0 as _csc_mean_var_axis0 + + +def _raise_typeerror(X): + """Raises a TypeError if X is not a CSR or CSC matrix""" + input_type = X.format if sp.issparse(X) else type(X) + err = "Expected a CSR or CSC sparse matrix, got %s." % input_type + raise TypeError(err) + + +def inplace_csr_column_scale(X, scale): + """Inplace column scaling of a CSR matrix. + + Scale each feature of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X : CSR matrix with shape (n_samples, n_features) + Matrix to normalize using the variance of the features. + + scale : float array with shape (n_features,) + Array of precomputed feature-wise values to use for scaling. + """ + assert scale.shape[0] == X.shape[1] + X.data *= scale.take(X.indices, mode='clip') + + +def inplace_csr_row_scale(X, scale): + """ Inplace row scaling of a CSR matrix. + + Scale each sample of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X : CSR sparse matrix, shape (n_samples, n_features) + Matrix to be scaled. + + scale : float array with shape (n_samples,) + Array of precomputed sample-wise values to use for scaling. + """ + assert scale.shape[0] == X.shape[0] + X.data *= np.repeat(scale, np.diff(X.indptr)) + + +def mean_variance_axis(X, axis): + """Compute mean and variance along axis 0 on a CSR or CSC matrix + + Parameters + ---------- + X: CSR or CSC sparse matrix, shape (n_samples, n_features) + Input data. + + axis: int (either 0 or 1) + Axis along which the axis should be computed. + + Returns + ------- + + means: float array with shape (n_features,) + Feature-wise means + + variances: float array with shape (n_features,) + Feature-wise variances + + """ + if axis not in (0, 1): + raise ValueError( + "Unknown axis value: %d. Use 0 for rows, or 1 for columns" % axis) + + if isinstance(X, sp.csr_matrix): + if axis == 0: + return _csr_mean_var_axis0(X) + else: + return _csc_mean_var_axis0(X.T) + elif isinstance(X, sp.csc_matrix): + if axis == 0: + return _csc_mean_var_axis0(X) + else: + return _csr_mean_var_axis0(X.T) + else: + _raise_typeerror(X) + + +def inplace_column_scale(X, scale): + """Inplace column scaling of a CSC/CSR matrix. + + Scale each feature of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X: CSC or CSR matrix with shape (n_samples, n_features) + Matrix to normalize using the variance of the features. + + scale: float array with shape (n_features,) + Array of precomputed feature-wise values to use for scaling. + """ + if isinstance(X, sp.csc_matrix): + inplace_csr_row_scale(X.T, scale) + elif isinstance(X, sp.csr_matrix): + inplace_csr_column_scale(X, scale) + else: + _raise_typeerror(X) + + +def inplace_row_scale(X, scale): + """ Inplace row scaling of a CSR or CSC matrix. + + Scale each row of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X : CSR or CSC sparse matrix, shape (n_samples, n_features) + Matrix to be scaled. + + scale : float array with shape (n_features,) + Array of precomputed sample-wise values to use for scaling. + """ + if isinstance(X, sp.csc_matrix): + inplace_csr_column_scale(X.T, scale) + elif isinstance(X, sp.csr_matrix): + inplace_csr_row_scale(X, scale) + else: + _raise_typeerror(X) + + +def inplace_swap_row_csc(X, m, n): + """ + Swaps two rows of a CSC matrix in-place. + + Parameters + ---------- + X: scipy.sparse.csc_matrix, shape=(n_samples, n_features) + Matrix whose two rows are to be swapped. + + m: int + Index of the row of X to be swapped. + + n: int + Index of the row of X to be swapped. + """ + for t in [m, n]: + if isinstance(t, np.ndarray): + raise TypeError("m and n should be valid integers") + + if m < 0: + m += X.shape[0] + if n < 0: + n += X.shape[0] + + m_mask = X.indices == m + X.indices[X.indices == n] = m + X.indices[m_mask] = n + + +def inplace_swap_row_csr(X, m, n): + """ + Swaps two rows of a CSR matrix in-place. + + Parameters + ---------- + X: scipy.sparse.csr_matrix, shape=(n_samples, n_features) + Matrix whose two rows are to be swapped. + + m: int + Index of the row of X to be swapped. + + n: int + Index of the row of X to be swapped. + """ + for t in [m, n]: + if isinstance(t, np.ndarray): + raise TypeError("m and n should be valid integers") + + if m < 0: + m += X.shape[0] + if n < 0: + n += X.shape[0] + + # The following swapping makes life easier since m is assumed to be the + # smaller integer below. + if m > n: + m, n = n, m + + indptr = X.indptr + m_start = indptr[m] + m_stop = indptr[m + 1] + n_start = indptr[n] + n_stop = indptr[n + 1] + nz_m = m_stop - m_start + nz_n = n_stop - n_start + + if nz_m != nz_n: + # Modify indptr first + X.indptr[m + 2:n] += nz_n - nz_m + X.indptr[m + 1] = m_start + nz_n + X.indptr[n] = n_stop - nz_m + + X.indices = np.concatenate([X.indices[:m_start], + X.indices[n_start:n_stop], + X.indices[m_stop:n_start], + X.indices[m_start:m_stop], + X.indices[n_stop:]]) + X.data = np.concatenate([X.data[:m_start], + X.data[n_start:n_stop], + X.data[m_stop:n_start], + X.data[m_start:m_stop], + X.data[n_stop:]]) + + +def inplace_swap_row(X, m, n): + """ + Swaps two rows of a CSC/CSR matrix in-place. + + Parameters + ---------- + X : CSR or CSC sparse matrix, shape=(n_samples, n_features) + Matrix whose two rows are to be swapped. + + m: int + Index of the row of X to be swapped. + + n: int + Index of the row of X to be swapped. + """ + if isinstance(X, sp.csc_matrix): + return inplace_swap_row_csc(X, m, n) + elif isinstance(X, sp.csr_matrix): + return inplace_swap_row_csr(X, m, n) + else: + _raise_typeerror(X) + + +def inplace_swap_column(X, m, n): + """ + Swaps two columns of a CSC/CSR matrix in-place. + + Parameters + ---------- + X : CSR or CSC sparse matrix, shape=(n_samples, n_features) + Matrix whose two columns are to be swapped. + + m: int + Index of the column of X to be swapped. + + n : int + Index of the column of X to be swapped. + """ + if m < 0: + m += X.shape[1] + if n < 0: + n += X.shape[1] + if isinstance(X, sp.csc_matrix): + return inplace_swap_row_csr(X, m, n) + elif isinstance(X, sp.csr_matrix): + return inplace_swap_row_csc(X, m, n) + else: + _raise_typeerror(X) + + +def min_max_axis(X, axis): + """Compute minimum and maximum along an axis on a CSR or CSC matrix + + Parameters + ---------- + X : CSR or CSC sparse matrix, shape (n_samples, n_features) + Input data. + + axis: int (either 0 or 1) + Axis along which the axis should be computed. + + Returns + ------- + + mins: float array with shape (n_features,) + Feature-wise minima + + maxs: float array with shape (n_features,) + Feature-wise maxima + """ + if isinstance(X, sp.csr_matrix) or isinstance(X, sp.csc_matrix): + return sparse_min_max(X, axis=axis) + else: + _raise_typeerror(X) + + +def count_nonzero(X, axis=None, sample_weight=None): + """A variant of X.getnnz() with extension to weighting on axis 0 + + Useful in efficiently calculating multilabel metrics. + + Parameters + ---------- + X : CSR sparse matrix, shape = (n_samples, n_labels) + Input data. + + axis : None, 0 or 1 + The axis on which the data is aggregated. + + sample_weight : array, shape = (n_samples,), optional + Weight for each row of X. + """ + if axis == -1: + axis = 1 + elif axis == -2: + axis = 0 + elif X.format != 'csr': + raise TypeError('Expected CSR sparse format, got {0}'.format(X.format)) + + # We rely here on the fact that np.diff(Y.indptr) for a CSR + # will return the number of nonzero entries in each row. + # A bincount over Y.indices will return the number of nonzeros + # in each column. See ``csr_matrix.getnnz`` in scipy >= 0.14. + if axis is None: + if sample_weight is None: + return X.nnz + else: + return np.dot(np.diff(X.indptr), sample_weight) + elif axis == 1: + out = np.diff(X.indptr) + if sample_weight is None: + return out + return out * sample_weight + elif axis == 0: + if sample_weight is None: + return bincount(X.indices, minlength=X.shape[1]) + else: + weights = np.repeat(sample_weight, np.diff(X.indptr)) + return bincount(X.indices, minlength=X.shape[1], + weights=weights) + else: + raise ValueError('Unsupported axis: {0}'.format(axis)) + + +def _get_median(data, n_zeros): + """Compute the median of data with n_zeros additional zeros. + + This function is used to support sparse matrices; it modifies data in-place + """ + n_elems = len(data) + n_zeros + if not n_elems: + return np.nan + n_negative = np.count_nonzero(data < 0) + middle, is_odd = divmod(n_elems, 2) + data.sort() + + if is_odd: + return _get_elem_at_rank(middle, data, n_negative, n_zeros) + + return (_get_elem_at_rank(middle - 1, data, n_negative, n_zeros) + + _get_elem_at_rank(middle, data, n_negative, n_zeros)) / 2. + + +def _get_elem_at_rank(rank, data, n_negative, n_zeros): + """Find the value in data augmented with n_zeros for the given rank""" + if rank < n_negative: + return data[rank] + if rank - n_negative < n_zeros: + return 0 + return data[rank - n_zeros] + + +def csc_median_axis_0(X): + """Find the median across axis 0 of a CSC matrix. + It is equivalent to doing np.median(X, axis=0). + + Parameters + ---------- + X : CSC sparse matrix, shape (n_samples, n_features) + Input data. + + Returns + ------- + median : ndarray, shape (n_features,) + Median. + + """ + if not isinstance(X, sp.csc_matrix): + raise TypeError("Expected matrix of CSC format, got %s" % X.format) + + indptr = X.indptr + n_samples, n_features = X.shape + median = np.zeros(n_features) + + for f_ind, (start, end) in enumerate(zip(indptr[:-1], indptr[1:])): + + # Prevent modifying X in place + data = np.copy(X.data[start: end]) + nz = n_samples - data.size + median[f_ind] = _get_median(data, nz) + + return median diff --git a/sklearn/utils/sparsefuncs.pyx b/sklearn/utils/sparsefuncs.pyx deleted file mode 100644 index e26c858cc304b..0000000000000 --- a/sklearn/utils/sparsefuncs.pyx +++ /dev/null @@ -1,277 +0,0 @@ -# Author: Mathieu Blondel -# Olivier Grisel -# -# License: BSD Style. - -cimport numpy as np -import numpy as np -import scipy.sparse as sp -cimport cython - - -cdef extern from "math.h": - double fabs(double f) - double sqrt(double f) - -ctypedef np.float64_t DOUBLE - -@cython.boundscheck(False) -@cython.wraparound(False) -@cython.cdivision(True) -def csr_mean_variance_axis0(X): - """Compute mean and variance along axis 0 on a CSR matrix - - Parameters - ---------- - X: CSR sparse matrix, shape (n_samples, n_features) - Input data. - - Returns - ------- - - means: float array with shape (n_features,) - Feature-wise means - - variances: float array with shape (n_features,) - Feature-wise variances - - """ - cdef unsigned int n_samples = X.shape[0] - cdef unsigned int n_features = X.shape[1] - - cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - cdef np.ndarray[int, ndim=1] X_indices = X.indices - cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - - cdef unsigned int i - cdef unsigned int j - cdef unsigned int ind - cdef double diff - - # means[j] contains the mean of feature j - cdef np.ndarray[DOUBLE, ndim=1] means = np.asarray(X.mean(axis=0))[0] - - # variances[j] contains the variance of feature j - cdef np.ndarray[DOUBLE, ndim=1] variances = np.zeros_like(means) - - # counts[j] contains the number of samples where feature j is non-zero - counts = np.zeros_like(means) - - for i in xrange(n_samples): - for j in xrange(X_indptr[i], X_indptr[i + 1]): - ind = X_indices[j] - diff = X_data[j] - means[ind] - variances[ind] += diff * diff - counts[ind] += 1 - - nz = n_samples - counts - variances += nz * means ** 2 - variances /= n_samples - - return means, variances - -@cython.boundscheck(False) -@cython.wraparound(False) -@cython.cdivision(True) -def inplace_csr_row_normalize_l1(X): - """Inplace row normalize using the l1 norm""" - cdef unsigned int n_samples = X.shape[0] - cdef unsigned int n_features = X.shape[1] - - cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - cdef np.ndarray[int, ndim=1] X_indices = X.indices - cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - - # the column indices for row i are stored in: - # indices[indptr[i]:indices[i+1]] - # and their corresponding values are stored in: - # data[indptr[i]:indptr[i+1]] - cdef unsigned int i - cdef unsigned int j - cdef double sum_ - - for i in xrange(n_samples): - sum_ = 0.0 - - for j in xrange(X_indptr[i], X_indptr[i + 1]): - sum_ += fabs(X_data[j]) - - if sum_ == 0.0: - # do not normalize empty rows (can happen if CSR is not pruned - # correctly) - continue - - for j in xrange(X_indptr[i], X_indptr[i + 1]): - X_data[j] /= sum_ - - -@cython.boundscheck(False) -@cython.wraparound(False) -@cython.cdivision(True) -def inplace_csr_row_normalize_l2(X): - """Inplace row normalize using the l2 norm""" - cdef unsigned int n_samples = X.shape[0] - cdef unsigned int n_features = X.shape[1] - - cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - cdef np.ndarray[int, ndim=1] X_indices = X.indices - cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - - cdef unsigned int i - cdef unsigned int j - cdef double sum_ - - for i in xrange(n_samples): - sum_ = 0.0 - - for j in xrange(X_indptr[i], X_indptr[i + 1]): - sum_ += (X_data[j] * X_data[j]) - - if sum_ == 0.0: - # do not normalize empty rows (can happen if CSR is not pruned - # correctly) - continue - - sum_ = sqrt(sum_) - - for j in xrange(X_indptr[i], X_indptr[i + 1]): - X_data[j] /= sum_ - - -@cython.boundscheck(False) -@cython.wraparound(False) -@cython.cdivision(True) -def inplace_csr_column_scale(X, np.ndarray[DOUBLE, ndim=1] scale): - """Inplace column scaling of a CSR matrix. - - Scale each feature of the data matrix by multiplying with specific scale - provided by the caller assuming a (n_samples, n_features) shape. - - Parameters - ---------- - X: CSR matrix with shape (n_samples, n_features) - Matrix to normalize using the variance of the features. - - scale: float array with shape (n_features,) - Array of precomputed feature-wise values to use for scaling. - """ - cdef unsigned int n_samples = X.shape[0] - cdef unsigned int n_features = X.shape[1] - - cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - cdef np.ndarray[int, ndim=1] X_indices = X.indices - cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - - cdef unsigned int i, j - for i in xrange(n_samples): - for j in xrange(X_indptr[i], X_indptr[i + 1]): - X_data[j] *= scale[X_indices[j]] - - -@cython.boundscheck(False) -@cython.wraparound(False) -@cython.cdivision(True) -def csc_mean_variance_axis0(X): - """Compute mean and variance along axis 0 on a CSC matrix - - Parameters - ---------- - X: CSC sparse matrix, shape (n_samples, n_features) - Input data. - - Returns - ------- - - means: float array with shape (n_features,) - Feature-wise means - - variances: float array with shape (n_features,) - Feature-wise variances - - """ - cdef unsigned int n_samples = X.shape[0] - cdef unsigned int n_features = X.shape[1] - - cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - cdef np.ndarray[int, ndim=1] X_indices = X.indices - cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - - cdef unsigned int i - cdef unsigned int j - cdef double diff - - # means[j] contains the mean of feature j - cdef np.ndarray[DOUBLE, ndim=1] means = np.asarray(X.mean(axis=0))[0] - - # variances[j] contains the variance of feature j - cdef np.ndarray[DOUBLE, ndim=1] variances = np.zeros_like(means) - - # counts[j] contains the number of samples where feature j is non-zero - counts = np.zeros_like(means) - - for i in xrange(n_features): - for j in xrange(X_indptr[i], X_indptr[i + 1]): - diff = X_data[j] - means[i] - variances[i] += diff * diff - counts[i] += 1 - - nz = n_samples - counts - variances += nz * means ** 2 - variances /= n_samples - - return means, variances - - -@cython.boundscheck(False) -@cython.wraparound(False) -@cython.cdivision(True) -def inplace_csc_column_scale(X, np.ndarray[DOUBLE, ndim=1] scale): - """Inplace column scaling of a CSC matrix. - - Scale each feature of the data matrix by multiplying with specific scale - provided by the caller assuming a (n_samples, n_features) shape. - - Parameters - ---------- - X: CSC matrix with shape (n_samples, n_features) - Matrix to normalize using the variance of the features. - - scale: float array with shape (n_features,) - Array of precomputed feature-wise values to use for scaling. - """ - cdef unsigned int n_samples = X.shape[0] - cdef unsigned int n_features = X.shape[1] - - cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data - cdef np.ndarray[int, ndim=1] X_indices = X.indices - cdef np.ndarray[int, ndim=1] X_indptr = X.indptr - - cdef unsigned int i, j - for i in xrange(n_features): - for j in xrange(X_indptr[i], X_indptr[i + 1]): - X_data[j] *= scale[i] - -def mean_variance_axis0(X): - """Compute mean and variance along axis 0 on a CSR or CSC matrix - - Parameters - ---------- - X: CSR or CSC sparse matrix, shape (n_samples, n_features) - Input data. - - Returns - ------- - - means: float array with shape (n_features,) - Feature-wise means - - variances: float array with shape (n_features,) - Feature-wise variances - - """ - if isinstance(X, sp.csr_matrix): - return csr_mean_variance_axis0(X) - elif isinstance(X, sp.csc_matrix): - return csc_mean_variance_axis0(X) - else: - raise TypeError("Unsupported matrix type. Expected a CSR or CSC sparse matrix.") diff --git a/sklearn/utils/sparsefuncs_fast.c b/sklearn/utils/sparsefuncs_fast.c new file mode 100644 index 0000000000000..5aba88b38801d --- /dev/null +++ b/sklearn/utils/sparsefuncs_fast.c @@ -0,0 +1,9157 @@ +/* Generated by Cython 0.20.1post0 (Debian 0.20.1+git90-g0e6e38e-1ubuntu2) on Thu May 22 14:03:31 2014 */ + +#define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#define CYTHON_ABI "0_20_1post0" +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if CYTHON_COMPILING_IN_PYPY +#define Py_OptimizeFlag 0 +#endif +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT) + #define Py_TPFLAGS_IS_ABSTRACT 0 +#endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_VERSION_HEX < 0x030200A4 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#ifdef __cplusplus +template +void __Pyx_call_destructor(T* x) { + x->~T(); +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__utils__sparsefuncs_fast +#define __PYX_HAVE_API__sklearn__utils__sparsefuncs_fast +#include "string.h" +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#include "math.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +#if CYTHON_COMPILING_IN_CPYTHON +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "sparsefuncs_fast.pyx", + "__init__.pxd", + "type.pxd", +}; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":723 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":724 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":725 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":726 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":730 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":731 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":732 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":733 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":737 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":738 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":747 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":748 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":749 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":751 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":752 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":753 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":755 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":756 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":758 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":759 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":760 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; + +/* "sklearn/utils/sparsefuncs_fast.pyx":17 + * + * + * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< + * + * + */ +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":762 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":763 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":764 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":766 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ + +#define __Pyx_BufPtrCContig1d(type, buf, i0, s0) ((type)buf + i0) +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename, + int full_traceback); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); /*proto*/ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +#define __Pyx_PyObject_DelSlice(obj, cstart, cstop, py_start, py_stop, py_slice, has_cstart, has_cstop, wraparound) \ + __Pyx_PyObject_SetSlice(obj, (PyObject*)NULL, cstart, cstop, py_start, py_stop, py_slice, has_cstart, has_cstop, wraparound) +static CYTHON_INLINE int __Pyx_PyObject_SetSlice( + PyObject* obj, PyObject* value, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); + +#define __Pyx_BufPtrCContig2d(type, buf, i0, s0, i1, s1) ((type)((char*)buf + i0 * s0) + i1) +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value); + +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); + +static int __Pyx_check_binary_version(void); + +static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig); /*proto*/ + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'libc.math' */ + +/* Module declarations from 'cython' */ + +/* Module declarations from 'sklearn.utils.sparsefuncs_fast' */ +static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t = { "float64_t", NULL, sizeof(__pyx_t_5numpy_float64_t), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn_npy_intp = { "npy_intp", NULL, sizeof(npy_intp), { 0 }, 0, IS_UNSIGNED(npy_intp) ? 'U' : 'I', IS_UNSIGNED(npy_intp), 0 }; +#define __Pyx_MODULE_NAME "sklearn.utils.sparsefuncs_fast" +int __pyx_module_is_main_sklearn__utils__sparsefuncs_fast = 0; + +/* Implementation of 'sklearn.utils.sparsefuncs_fast' */ +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_xrange; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_csr_row_norms(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_2csr_mean_variance_axis0(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_4csc_mean_variance_axis0(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_6inplace_csr_row_normalize_l1(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_8inplace_csr_row_normalize_l2(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_10assign_rows_csr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_X_rows, PyArrayObject *__pyx_v_out_rows, PyArrayObject *__pyx_v_out); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static char __pyx_k_B[] = "B"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_X[] = "X"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_j[] = "j"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k__8[] = "*"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_rX[] = "rX"; +static char __pyx_k_sp[] = "sp"; +static char __pyx_k_ind[] = "ind"; +static char __pyx_k_out[] = "out"; +static char __pyx_k_sum[] = "sum_"; +static char __pyx_k_data[] = "data"; +static char __pyx_k_diff[] = "diff"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_dtype[] = "dtype"; +static char __pyx_k_int32[] = "int32"; +static char __pyx_k_means[] = "means"; +static char __pyx_k_norms[] = "norms"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_shape[] = "shape"; +static char __pyx_k_zeros[] = "zeros"; +static char __pyx_k_X_data[] = "X_data"; +static char __pyx_k_X_rows[] = "X_rows"; +static char __pyx_k_counts[] = "counts"; +static char __pyx_k_endptr[] = "endptr"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_indptr[] = "indptr"; +static char __pyx_k_xrange[] = "xrange"; +static char __pyx_k_asarray[] = "asarray"; +static char __pyx_k_col_ind[] = "col_ind"; +static char __pyx_k_float64[] = "float64"; +static char __pyx_k_indices[] = "indices"; +static char __pyx_k_X_indptr[] = "X_indptr"; +static char __pyx_k_non_zero[] = "non_zero"; +static char __pyx_k_out_rows[] = "out_rows"; +static char __pyx_k_startptr[] = "startptr"; +static char __pyx_k_X_indices[] = "X_indices"; +static char __pyx_k_n_samples[] = "n_samples"; +static char __pyx_k_variances[] = "variances"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_n_features[] = "n_features"; +static char __pyx_k_zeros_like[] = "zeros_like"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_scipy_sparse[] = "scipy.sparse"; +static char __pyx_k_csr_row_norms[] = "csr_row_norms"; +static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k_assign_rows_csr[] = "assign_rows_csr"; +static char __pyx_k_pyx_releasebuffer[] = "__pyx_releasebuffer"; +static char __pyx_k_csc_mean_variance_axis0[] = "csc_mean_variance_axis0"; +static char __pyx_k_csr_mean_variance_axis0[] = "csr_mean_variance_axis0"; +static char __pyx_k_cannot_assign_d_rows_to_d[] = "cannot assign %d rows to %d"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_inplace_csr_row_normalize_l1[] = "inplace_csr_row_normalize_l1"; +static char __pyx_k_inplace_csr_row_normalize_l2[] = "inplace_csr_row_normalize_l2"; +static char __pyx_k_sklearn_utils_sparsefuncs_fast[] = "sklearn.utils.sparsefuncs_fast"; +static char __pyx_k_files_work_opensource_scikit_le[] = "/files/work/opensource/scikit-learn/sklearn/utils/sparsefuncs_fast.pyx"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_X; +static PyObject *__pyx_n_s_X_data; +static PyObject *__pyx_n_s_X_indices; +static PyObject *__pyx_n_s_X_indptr; +static PyObject *__pyx_n_s_X_rows; +static PyObject *__pyx_n_s__8; +static PyObject *__pyx_n_s_asarray; +static PyObject *__pyx_n_s_assign_rows_csr; +static PyObject *__pyx_kp_s_cannot_assign_d_rows_to_d; +static PyObject *__pyx_n_s_col_ind; +static PyObject *__pyx_n_s_counts; +static PyObject *__pyx_n_s_csc_mean_variance_axis0; +static PyObject *__pyx_n_s_csr_mean_variance_axis0; +static PyObject *__pyx_n_s_csr_row_norms; +static PyObject *__pyx_n_s_data; +static PyObject *__pyx_n_s_diff; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_endptr; +static PyObject *__pyx_kp_s_files_work_opensource_scikit_le; +static PyObject *__pyx_n_s_float64; +static PyObject *__pyx_n_s_i; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_ind; +static PyObject *__pyx_n_s_indices; +static PyObject *__pyx_n_s_indptr; +static PyObject *__pyx_n_s_inplace_csr_row_normalize_l1; +static PyObject *__pyx_n_s_inplace_csr_row_normalize_l2; +static PyObject *__pyx_n_s_int32; +static PyObject *__pyx_n_s_j; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_means; +static PyObject *__pyx_n_s_n_features; +static PyObject *__pyx_n_s_n_samples; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_non_zero; +static PyObject *__pyx_n_s_norms; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_out; +static PyObject *__pyx_n_s_out_rows; +static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_releasebuffer; +static PyObject *__pyx_n_s_rX; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_scipy_sparse; +static PyObject *__pyx_n_s_shape; +static PyObject *__pyx_n_s_sklearn_utils_sparsefuncs_fast; +static PyObject *__pyx_n_s_sp; +static PyObject *__pyx_n_s_startptr; +static PyObject *__pyx_n_s_sum; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_variances; +static PyObject *__pyx_n_s_xrange; +static PyObject *__pyx_n_s_zeros; +static PyObject *__pyx_n_s_zeros_like; +static PyObject *__pyx_float_0_; +static PyObject *__pyx_slice_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_tuple__11; +static PyObject *__pyx_tuple__13; +static PyObject *__pyx_tuple__15; +static PyObject *__pyx_tuple__17; +static PyObject *__pyx_tuple__19; +static PyObject *__pyx_codeobj__10; +static PyObject *__pyx_codeobj__12; +static PyObject *__pyx_codeobj__14; +static PyObject *__pyx_codeobj__16; +static PyObject *__pyx_codeobj__18; +static PyObject *__pyx_codeobj__20; + +/* "sklearn/utils/sparsefuncs_fast.pyx":23 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csr_row_norms(X): # <<<<<<<<<<<<<< + * """L2 norm of each row in CSR matrix X.""" + * cdef: + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_1csr_row_norms(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ +static char __pyx_doc_7sklearn_5utils_16sparsefuncs_fast_csr_row_norms[] = "L2 norm of each row in CSR matrix X."; +static PyMethodDef __pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_1csr_row_norms = {__Pyx_NAMESTR("csr_row_norms"), (PyCFunction)__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_1csr_row_norms, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_16sparsefuncs_fast_csr_row_norms)}; +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_1csr_row_norms(PyObject *__pyx_self, PyObject *__pyx_v_X) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("csr_row_norms (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_5utils_16sparsefuncs_fast_csr_row_norms(__pyx_self, ((PyObject *)__pyx_v_X)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_csr_row_norms(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X) { + unsigned int __pyx_v_n_samples; + CYTHON_UNUSED unsigned int __pyx_v_n_features; + PyArrayObject *__pyx_v_norms = 0; + PyArrayObject *__pyx_v_data = 0; + CYTHON_UNUSED PyArrayObject *__pyx_v_indices = 0; + PyArrayObject *__pyx_v_indptr = 0; + npy_intp __pyx_v_i; + npy_intp __pyx_v_j; + double __pyx_v_sum_; + __Pyx_LocalBuf_ND __pyx_pybuffernd_data; + __Pyx_Buffer __pyx_pybuffer_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices; + __Pyx_Buffer __pyx_pybuffer_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr; + __Pyx_Buffer __pyx_pybuffer_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_norms; + __Pyx_Buffer __pyx_pybuffer_norms; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + unsigned int __pyx_t_3; + PyArrayObject *__pyx_t_4 = NULL; + PyArrayObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyArrayObject *__pyx_t_9 = NULL; + int __pyx_t_10; + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + PyArrayObject *__pyx_t_14 = NULL; + npy_intp __pyx_t_15; + long __pyx_t_16; + npy_intp __pyx_t_17; + npy_intp __pyx_t_18; + npy_intp __pyx_t_19; + npy_intp __pyx_t_20; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("csr_row_norms", 0); + __pyx_pybuffer_norms.pybuffer.buf = NULL; + __pyx_pybuffer_norms.refcount = 0; + __pyx_pybuffernd_norms.data = NULL; + __pyx_pybuffernd_norms.rcbuffer = &__pyx_pybuffer_norms; + __pyx_pybuffer_data.pybuffer.buf = NULL; + __pyx_pybuffer_data.refcount = 0; + __pyx_pybuffernd_data.data = NULL; + __pyx_pybuffernd_data.rcbuffer = &__pyx_pybuffer_data; + __pyx_pybuffer_indices.pybuffer.buf = NULL; + __pyx_pybuffer_indices.refcount = 0; + __pyx_pybuffernd_indices.data = NULL; + __pyx_pybuffernd_indices.rcbuffer = &__pyx_pybuffer_indices; + __pyx_pybuffer_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_indptr.refcount = 0; + __pyx_pybuffernd_indptr.data = NULL; + __pyx_pybuffernd_indptr.rcbuffer = &__pyx_pybuffer_indptr; + + /* "sklearn/utils/sparsefuncs_fast.pyx":26 + * """L2 norm of each row in CSR matrix X.""" + * cdef: + * unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< + * unsigned int n_features = X.shape[1] + * np.ndarray[DOUBLE, ndim=1, mode="c"] norms + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyInt_As_unsigned_int(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_n_samples = __pyx_t_3; + + /* "sklearn/utils/sparsefuncs_fast.pyx":27 + * cdef: + * unsigned int n_samples = X.shape[0] + * unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< + * np.ndarray[DOUBLE, ndim=1, mode="c"] norms + * np.ndarray[DOUBLE, ndim=1, mode="c"] data + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_PyInt_As_unsigned_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_n_features = __pyx_t_3; + + /* "sklearn/utils/sparsefuncs_fast.pyx":30 + * np.ndarray[DOUBLE, ndim=1, mode="c"] norms + * np.ndarray[DOUBLE, ndim=1, mode="c"] data + * np.ndarray[int, ndim=1, mode="c"] indices = X.indices # <<<<<<<<<<<<<< + * np.ndarray[int, ndim=1, mode="c"] indptr = X.indptr + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices.rcbuffer->pybuffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_indices.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_indices.diminfo[0].strides = __pyx_pybuffernd_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices.diminfo[0].shape = __pyx_pybuffernd_indices.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_4 = 0; + __pyx_v_indices = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":31 + * np.ndarray[DOUBLE, ndim=1, mode="c"] data + * np.ndarray[int, ndim=1, mode="c"] indices = X.indices + * np.ndarray[int, ndim=1, mode="c"] indptr = X.indptr # <<<<<<<<<<<<<< + * + * np.npy_intp i, j + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + __pyx_v_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_indptr.diminfo[0].strides = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr.diminfo[0].shape = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_5 = 0; + __pyx_v_indptr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":36 + * double sum_ + * + * norms = np.zeros(n_samples, dtype=np.float64) # <<<<<<<<<<<<<< + * data = np.asarray(X.data, dtype=np.float64) # might copy! + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_samples); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_float64); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_6, __pyx_t_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_8) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_8, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = ((PyArrayObject *)__pyx_t_8); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_norms.rcbuffer->pybuffer); + __pyx_t_10 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_norms.rcbuffer->pybuffer, (PyObject*)__pyx_t_9, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_10 < 0)) { + PyErr_Fetch(&__pyx_t_11, &__pyx_t_12, &__pyx_t_13); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_norms.rcbuffer->pybuffer, (PyObject*)__pyx_v_norms, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_13); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_11, __pyx_t_12, __pyx_t_13); + } + } + __pyx_pybuffernd_norms.diminfo[0].strides = __pyx_pybuffernd_norms.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_norms.diminfo[0].shape = __pyx_pybuffernd_norms.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_10 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_9 = 0; + __pyx_v_norms = ((PyArrayObject *)__pyx_t_8); + __pyx_t_8 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":37 + * + * norms = np.zeros(n_samples, dtype=np.float64) + * data = np.asarray(X.data, dtype=np.float64) # might copy! # <<<<<<<<<<<<<< + * + * for i in range(n_samples): + */ + __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = PyDict_New(); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_8, __pyx_n_s_dtype, __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, __pyx_t_8); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = ((PyArrayObject *)__pyx_t_7); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __pyx_t_10 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_data.rcbuffer->pybuffer, (PyObject*)__pyx_t_14, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_10 < 0)) { + PyErr_Fetch(&__pyx_t_13, &__pyx_t_12, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_data, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_13); Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_13, __pyx_t_12, __pyx_t_11); + } + } + __pyx_pybuffernd_data.diminfo[0].strides = __pyx_pybuffernd_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_data.diminfo[0].shape = __pyx_pybuffernd_data.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_10 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_14 = 0; + __pyx_v_data = ((PyArrayObject *)__pyx_t_7); + __pyx_t_7 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":39 + * data = np.asarray(X.data, dtype=np.float64) # might copy! + * + * for i in range(n_samples): # <<<<<<<<<<<<<< + * sum_ = 0.0 + * for j in range(indptr[i], indptr[i + 1]): + */ + __pyx_t_3 = __pyx_v_n_samples; + for (__pyx_t_15 = 0; __pyx_t_15 < __pyx_t_3; __pyx_t_15+=1) { + __pyx_v_i = __pyx_t_15; + + /* "sklearn/utils/sparsefuncs_fast.pyx":40 + * + * for i in range(n_samples): + * sum_ = 0.0 # <<<<<<<<<<<<<< + * for j in range(indptr[i], indptr[i + 1]): + * sum_ += data[j] * data[j] + */ + __pyx_v_sum_ = 0.0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":41 + * for i in range(n_samples): + * sum_ = 0.0 + * for j in range(indptr[i], indptr[i + 1]): # <<<<<<<<<<<<<< + * sum_ += data[j] * data[j] + * norms[i] = sum_ + */ + __pyx_t_16 = (__pyx_v_i + 1); + __pyx_t_10 = (*__Pyx_BufPtrCContig1d(int *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_indptr.diminfo[0].strides)); + __pyx_t_17 = __pyx_v_i; + for (__pyx_t_18 = (*__Pyx_BufPtrCContig1d(int *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_indptr.diminfo[0].strides)); __pyx_t_18 < __pyx_t_10; __pyx_t_18+=1) { + __pyx_v_j = __pyx_t_18; + + /* "sklearn/utils/sparsefuncs_fast.pyx":42 + * sum_ = 0.0 + * for j in range(indptr[i], indptr[i + 1]): + * sum_ += data[j] * data[j] # <<<<<<<<<<<<<< + * norms[i] = sum_ + * + */ + __pyx_t_19 = __pyx_v_j; + __pyx_t_20 = __pyx_v_j; + __pyx_v_sum_ = (__pyx_v_sum_ + ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_data.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_data.diminfo[0].strides)) * (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_data.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_data.diminfo[0].strides)))); + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":43 + * for j in range(indptr[i], indptr[i + 1]): + * sum_ += data[j] * data[j] + * norms[i] = sum_ # <<<<<<<<<<<<<< + * + * return norms + */ + __pyx_t_18 = __pyx_v_i; + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_norms.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_norms.diminfo[0].strides) = __pyx_v_sum_; + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":45 + * norms[i] = sum_ + * + * return norms # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_norms)); + __pyx_r = ((PyObject *)__pyx_v_norms); + goto __pyx_L0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":23 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csr_row_norms(X): # <<<<<<<<<<<<<< + * """L2 norm of each row in CSR matrix X.""" + * cdef: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_norms.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.utils.sparsefuncs_fast.csr_row_norms", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_norms.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_norms); + __Pyx_XDECREF((PyObject *)__pyx_v_data); + __Pyx_XDECREF((PyObject *)__pyx_v_indices); + __Pyx_XDECREF((PyObject *)__pyx_v_indptr); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/sparsefuncs_fast.pyx":51 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csr_mean_variance_axis0(X): # <<<<<<<<<<<<<< + * """Compute mean and variance along axis 0 on a CSR matrix + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_3csr_mean_variance_axis0(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ +static char __pyx_doc_7sklearn_5utils_16sparsefuncs_fast_2csr_mean_variance_axis0[] = "Compute mean and variance along axis 0 on a CSR matrix\n\n Parameters\n ----------\n X: CSR sparse matrix, shape (n_samples, n_features)\n Input data.\n\n Returns\n -------\n\n means: float array with shape (n_features,)\n Feature-wise means\n\n variances: float array with shape (n_features,)\n Feature-wise variances\n\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_3csr_mean_variance_axis0 = {__Pyx_NAMESTR("csr_mean_variance_axis0"), (PyCFunction)__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_3csr_mean_variance_axis0, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_16sparsefuncs_fast_2csr_mean_variance_axis0)}; +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_3csr_mean_variance_axis0(PyObject *__pyx_self, PyObject *__pyx_v_X) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("csr_mean_variance_axis0 (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_5utils_16sparsefuncs_fast_2csr_mean_variance_axis0(__pyx_self, ((PyObject *)__pyx_v_X)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_2csr_mean_variance_axis0(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X) { + unsigned int __pyx_v_n_samples; + unsigned int __pyx_v_n_features; + PyArrayObject *__pyx_v_X_data = 0; + PyArrayObject *__pyx_v_X_indices = 0; + unsigned int __pyx_v_i; + unsigned int __pyx_v_non_zero; + unsigned int __pyx_v_col_ind; + double __pyx_v_diff; + PyArrayObject *__pyx_v_means = 0; + PyArrayObject *__pyx_v_variances = 0; + PyArrayObject *__pyx_v_counts = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_data; + __Pyx_Buffer __pyx_pybuffer_X_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indices; + __Pyx_Buffer __pyx_pybuffer_X_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_counts; + __Pyx_Buffer __pyx_pybuffer_counts; + __Pyx_LocalBuf_ND __pyx_pybuffernd_means; + __Pyx_Buffer __pyx_pybuffer_means; + __Pyx_LocalBuf_ND __pyx_pybuffernd_variances; + __Pyx_Buffer __pyx_pybuffer_variances; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + unsigned int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyArrayObject *__pyx_t_7 = NULL; + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + PyArrayObject *__pyx_t_12 = NULL; + PyArrayObject *__pyx_t_13 = NULL; + PyArrayObject *__pyx_t_14 = NULL; + PyArrayObject *__pyx_t_15 = NULL; + unsigned int __pyx_t_16; + unsigned int __pyx_t_17; + unsigned int __pyx_t_18; + unsigned int __pyx_t_19; + unsigned int __pyx_t_20; + unsigned int __pyx_t_21; + unsigned int __pyx_t_22; + unsigned int __pyx_t_23; + unsigned int __pyx_t_24; + unsigned int __pyx_t_25; + unsigned int __pyx_t_26; + unsigned int __pyx_t_27; + unsigned int __pyx_t_28; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("csr_mean_variance_axis0", 0); + __pyx_pybuffer_X_data.pybuffer.buf = NULL; + __pyx_pybuffer_X_data.refcount = 0; + __pyx_pybuffernd_X_data.data = NULL; + __pyx_pybuffernd_X_data.rcbuffer = &__pyx_pybuffer_X_data; + __pyx_pybuffer_X_indices.pybuffer.buf = NULL; + __pyx_pybuffer_X_indices.refcount = 0; + __pyx_pybuffernd_X_indices.data = NULL; + __pyx_pybuffernd_X_indices.rcbuffer = &__pyx_pybuffer_X_indices; + __pyx_pybuffer_means.pybuffer.buf = NULL; + __pyx_pybuffer_means.refcount = 0; + __pyx_pybuffernd_means.data = NULL; + __pyx_pybuffernd_means.rcbuffer = &__pyx_pybuffer_means; + __pyx_pybuffer_variances.pybuffer.buf = NULL; + __pyx_pybuffer_variances.refcount = 0; + __pyx_pybuffernd_variances.data = NULL; + __pyx_pybuffernd_variances.rcbuffer = &__pyx_pybuffer_variances; + __pyx_pybuffer_counts.pybuffer.buf = NULL; + __pyx_pybuffer_counts.refcount = 0; + __pyx_pybuffernd_counts.data = NULL; + __pyx_pybuffernd_counts.rcbuffer = &__pyx_pybuffer_counts; + + /* "sklearn/utils/sparsefuncs_fast.pyx":69 + * + * """ + * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< + * cdef unsigned int n_features = X.shape[1] + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyInt_As_unsigned_int(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_n_samples = __pyx_t_3; + + /* "sklearn/utils/sparsefuncs_fast.pyx":70 + * """ + * cdef unsigned int n_samples = X.shape[0] + * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< + * + * cdef np.ndarray[DOUBLE, ndim=1, mode="c"] X_data + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_PyInt_As_unsigned_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_n_features = __pyx_t_3; + + /* "sklearn/utils/sparsefuncs_fast.pyx":73 + * + * cdef np.ndarray[DOUBLE, ndim=1, mode="c"] X_data + * X_data = np.asarray(X.data, dtype=np.float64) # might copy! # <<<<<<<<<<<<<< + * cdef np.ndarray[int, ndim=1] X_indices = X.indices + * + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_6); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_8 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_X_data, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } + } + __pyx_pybuffernd_X_data.diminfo[0].strides = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_data.diminfo[0].shape = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_7 = 0; + __pyx_v_X_data = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":74 + * cdef np.ndarray[DOUBLE, ndim=1, mode="c"] X_data + * X_data = np.asarray(X.data, dtype=np.float64) # might copy! + * cdef np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< + * + * cdef unsigned int i + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = ((PyArrayObject *)__pyx_t_6); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer, (PyObject*)__pyx_t_12, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indices.diminfo[0].strides = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indices.diminfo[0].shape = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_12 = 0; + __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":77 + * + * cdef unsigned int i + * cdef unsigned int non_zero = X_indices.shape[0] # <<<<<<<<<<<<<< + * cdef unsigned int col_ind + * cdef double diff + */ + __pyx_v_non_zero = (__pyx_v_X_indices->dimensions[0]); + + /* "sklearn/utils/sparsefuncs_fast.pyx":82 + * + * # means[j] contains the mean of feature j + * cdef np.ndarray[DOUBLE, ndim=1] means = np.zeros(n_features, # <<<<<<<<<<<<<< + * dtype=np.float64) + * + */ + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_features); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "sklearn/utils/sparsefuncs_fast.pyx":83 + * # means[j] contains the mean of feature j + * cdef np.ndarray[DOUBLE, ndim=1] means = np.zeros(n_features, + * dtype=np.float64) # <<<<<<<<<<<<<< + * + * # variances[j] contains the variance of feature j + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":82 + * + * # means[j] contains the mean of feature j + * cdef np.ndarray[DOUBLE, ndim=1] means = np.zeros(n_features, # <<<<<<<<<<<<<< + * dtype=np.float64) + * + */ + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_4, __pyx_t_6); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = ((PyArrayObject *)__pyx_t_5); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_means.rcbuffer->pybuffer, (PyObject*)__pyx_t_13, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_means = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_means.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_means.diminfo[0].strides = __pyx_pybuffernd_means.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_means.diminfo[0].shape = __pyx_pybuffernd_means.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_13 = 0; + __pyx_v_means = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":86 + * + * # variances[j] contains the variance of feature j + * cdef np.ndarray[DOUBLE, ndim=1] variances = np.zeros_like(means) # <<<<<<<<<<<<<< + * + * # counts[j] contains the number of samples where feature j is non-zero + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros_like); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(((PyObject *)__pyx_v_means)); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_means)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_means)); + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_variances.rcbuffer->pybuffer, (PyObject*)__pyx_t_14, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_variances = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_variances.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_variances.diminfo[0].strides = __pyx_pybuffernd_variances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_variances.diminfo[0].shape = __pyx_pybuffernd_variances.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_14 = 0; + __pyx_v_variances = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":89 + * + * # counts[j] contains the number of samples where feature j is non-zero + * cdef np.ndarray[int, ndim=1] counts = np.zeros(n_features, # <<<<<<<<<<<<<< + * dtype=np.int32) + * + */ + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_features); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + + /* "sklearn/utils/sparsefuncs_fast.pyx":90 + * # counts[j] contains the number of samples where feature j is non-zero + * cdef np.ndarray[int, ndim=1] counts = np.zeros(n_features, + * dtype=np.int32) # <<<<<<<<<<<<<< + * + * for i in xrange(non_zero): + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_int32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":89 + * + * # counts[j] contains the number of samples where feature j is non-zero + * cdef np.ndarray[int, ndim=1] counts = np.zeros(n_features, # <<<<<<<<<<<<<< + * dtype=np.int32) + * + */ + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_6, __pyx_t_4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_15 = ((PyArrayObject *)__pyx_t_2); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_counts.rcbuffer->pybuffer, (PyObject*)__pyx_t_15, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_counts = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_counts.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_counts.diminfo[0].strides = __pyx_pybuffernd_counts.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_counts.diminfo[0].shape = __pyx_pybuffernd_counts.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_15 = 0; + __pyx_v_counts = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":92 + * dtype=np.int32) + * + * for i in xrange(non_zero): # <<<<<<<<<<<<<< + * col_ind = X_indices[i] + * means[col_ind] += X_data[i] + */ + __pyx_t_3 = __pyx_v_non_zero; + for (__pyx_t_16 = 0; __pyx_t_16 < __pyx_t_3; __pyx_t_16+=1) { + __pyx_v_i = __pyx_t_16; + + /* "sklearn/utils/sparsefuncs_fast.pyx":93 + * + * for i in xrange(non_zero): + * col_ind = X_indices[i] # <<<<<<<<<<<<<< + * means[col_ind] += X_data[i] + * + */ + __pyx_t_17 = __pyx_v_i; + __pyx_v_col_ind = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_X_indices.diminfo[0].strides)); + + /* "sklearn/utils/sparsefuncs_fast.pyx":94 + * for i in xrange(non_zero): + * col_ind = X_indices[i] + * means[col_ind] += X_data[i] # <<<<<<<<<<<<<< + * + * means /= n_samples + */ + __pyx_t_18 = __pyx_v_i; + __pyx_t_19 = __pyx_v_col_ind; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_means.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_means.diminfo[0].strides) += (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_X_data.diminfo[0].strides)); + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":96 + * means[col_ind] += X_data[i] + * + * means /= n_samples # <<<<<<<<<<<<<< + * + * for i in xrange(non_zero): + */ + __pyx_t_2 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_samples); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyNumber_InPlaceDivide(((PyObject *)__pyx_v_means), __pyx_t_2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_means.rcbuffer->pybuffer); + __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_means.rcbuffer->pybuffer, (PyObject*)__pyx_t_13, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_8 < 0)) { + PyErr_Fetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_means.rcbuffer->pybuffer, (PyObject*)__pyx_v_means, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_11, __pyx_t_10, __pyx_t_9); + } + } + __pyx_pybuffernd_means.diminfo[0].strides = __pyx_pybuffernd_means.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_means.diminfo[0].shape = __pyx_pybuffernd_means.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_13 = 0; + __Pyx_DECREF_SET(__pyx_v_means, ((PyArrayObject *)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":98 + * means /= n_samples + * + * for i in xrange(non_zero): # <<<<<<<<<<<<<< + * col_ind = X_indices[i] + * diff = X_data[i] - means[col_ind] + */ + __pyx_t_3 = __pyx_v_non_zero; + for (__pyx_t_16 = 0; __pyx_t_16 < __pyx_t_3; __pyx_t_16+=1) { + __pyx_v_i = __pyx_t_16; + + /* "sklearn/utils/sparsefuncs_fast.pyx":99 + * + * for i in xrange(non_zero): + * col_ind = X_indices[i] # <<<<<<<<<<<<<< + * diff = X_data[i] - means[col_ind] + * variances[col_ind] += diff * diff + */ + __pyx_t_20 = __pyx_v_i; + __pyx_v_col_ind = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_X_indices.diminfo[0].strides)); + + /* "sklearn/utils/sparsefuncs_fast.pyx":100 + * for i in xrange(non_zero): + * col_ind = X_indices[i] + * diff = X_data[i] - means[col_ind] # <<<<<<<<<<<<<< + * variances[col_ind] += diff * diff + * counts[col_ind] += 1 + */ + __pyx_t_21 = __pyx_v_i; + __pyx_t_22 = __pyx_v_col_ind; + __pyx_v_diff = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_X_data.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_means.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_means.diminfo[0].strides))); + + /* "sklearn/utils/sparsefuncs_fast.pyx":101 + * col_ind = X_indices[i] + * diff = X_data[i] - means[col_ind] + * variances[col_ind] += diff * diff # <<<<<<<<<<<<<< + * counts[col_ind] += 1 + * + */ + __pyx_t_23 = __pyx_v_col_ind; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_variances.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_variances.diminfo[0].strides) += (__pyx_v_diff * __pyx_v_diff); + + /* "sklearn/utils/sparsefuncs_fast.pyx":102 + * diff = X_data[i] - means[col_ind] + * variances[col_ind] += diff * diff + * counts[col_ind] += 1 # <<<<<<<<<<<<<< + * + * for i in xrange(n_features): + */ + __pyx_t_24 = __pyx_v_col_ind; + *__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_counts.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_counts.diminfo[0].strides) += 1; + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":104 + * counts[col_ind] += 1 + * + * for i in xrange(n_features): # <<<<<<<<<<<<<< + * variances[i] += (n_samples - counts[i]) * means[i] ** 2 + * variances[i] /= n_samples + */ + __pyx_t_3 = __pyx_v_n_features; + for (__pyx_t_16 = 0; __pyx_t_16 < __pyx_t_3; __pyx_t_16+=1) { + __pyx_v_i = __pyx_t_16; + + /* "sklearn/utils/sparsefuncs_fast.pyx":105 + * + * for i in xrange(n_features): + * variances[i] += (n_samples - counts[i]) * means[i] ** 2 # <<<<<<<<<<<<<< + * variances[i] /= n_samples + * + */ + __pyx_t_25 = __pyx_v_i; + __pyx_t_26 = __pyx_v_i; + __pyx_t_27 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_variances.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_variances.diminfo[0].strides) += ((__pyx_v_n_samples - (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_counts.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_counts.diminfo[0].strides))) * pow((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_means.rcbuffer->pybuffer.buf, __pyx_t_26, __pyx_pybuffernd_means.diminfo[0].strides)), 2.0)); + + /* "sklearn/utils/sparsefuncs_fast.pyx":106 + * for i in xrange(n_features): + * variances[i] += (n_samples - counts[i]) * means[i] ** 2 + * variances[i] /= n_samples # <<<<<<<<<<<<<< + * + * return means, variances + */ + __pyx_t_28 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_variances.rcbuffer->pybuffer.buf, __pyx_t_28, __pyx_pybuffernd_variances.diminfo[0].strides) /= __pyx_v_n_samples; + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":108 + * variances[i] /= n_samples + * + * return means, variances # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_means)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_means)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_means)); + __Pyx_INCREF(((PyObject *)__pyx_v_variances)); + PyTuple_SET_ITEM(__pyx_t_4, 1, ((PyObject *)__pyx_v_variances)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_variances)); + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":51 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csr_mean_variance_axis0(X): # <<<<<<<<<<<<<< + * """Compute mean and variance along axis 0 on a CSR matrix + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_counts.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_means.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_variances.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.utils.sparsefuncs_fast.csr_mean_variance_axis0", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_counts.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_means.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_variances.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_X_data); + __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); + __Pyx_XDECREF((PyObject *)__pyx_v_means); + __Pyx_XDECREF((PyObject *)__pyx_v_variances); + __Pyx_XDECREF((PyObject *)__pyx_v_counts); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/sparsefuncs_fast.pyx":114 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csc_mean_variance_axis0(X): # <<<<<<<<<<<<<< + * """Compute mean and variance along axis 0 on a CSC matrix + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_5csc_mean_variance_axis0(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ +static char __pyx_doc_7sklearn_5utils_16sparsefuncs_fast_4csc_mean_variance_axis0[] = "Compute mean and variance along axis 0 on a CSC matrix\n\n Parameters\n ----------\n X: CSC sparse matrix, shape (n_samples, n_features)\n Input data.\n\n Returns\n -------\n\n means: float array with shape (n_features,)\n Feature-wise means\n\n variances: float array with shape (n_features,)\n Feature-wise variances\n\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_5csc_mean_variance_axis0 = {__Pyx_NAMESTR("csc_mean_variance_axis0"), (PyCFunction)__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_5csc_mean_variance_axis0, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_16sparsefuncs_fast_4csc_mean_variance_axis0)}; +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_5csc_mean_variance_axis0(PyObject *__pyx_self, PyObject *__pyx_v_X) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("csc_mean_variance_axis0 (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_5utils_16sparsefuncs_fast_4csc_mean_variance_axis0(__pyx_self, ((PyObject *)__pyx_v_X)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_4csc_mean_variance_axis0(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X) { + unsigned int __pyx_v_n_samples; + unsigned int __pyx_v_n_features; + PyArrayObject *__pyx_v_X_data = 0; + CYTHON_UNUSED PyArrayObject *__pyx_v_X_indices = 0; + PyArrayObject *__pyx_v_X_indptr = 0; + unsigned int __pyx_v_i; + unsigned int __pyx_v_j; + unsigned int __pyx_v_counts; + unsigned int __pyx_v_startptr; + unsigned int __pyx_v_endptr; + double __pyx_v_diff; + PyArrayObject *__pyx_v_means = 0; + PyArrayObject *__pyx_v_variances = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_data; + __Pyx_Buffer __pyx_pybuffer_X_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indices; + __Pyx_Buffer __pyx_pybuffer_X_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indptr; + __Pyx_Buffer __pyx_pybuffer_X_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_means; + __Pyx_Buffer __pyx_pybuffer_means; + __Pyx_LocalBuf_ND __pyx_pybuffernd_variances; + __Pyx_Buffer __pyx_pybuffer_variances; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + unsigned int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyArrayObject *__pyx_t_7 = NULL; + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + PyArrayObject *__pyx_t_12 = NULL; + PyArrayObject *__pyx_t_13 = NULL; + PyArrayObject *__pyx_t_14 = NULL; + PyArrayObject *__pyx_t_15 = NULL; + unsigned int __pyx_t_16; + unsigned int __pyx_t_17; + long __pyx_t_18; + unsigned int __pyx_t_19; + unsigned int __pyx_t_20; + unsigned int __pyx_t_21; + unsigned int __pyx_t_22; + unsigned int __pyx_t_23; + unsigned int __pyx_t_24; + unsigned int __pyx_t_25; + unsigned int __pyx_t_26; + unsigned int __pyx_t_27; + unsigned int __pyx_t_28; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("csc_mean_variance_axis0", 0); + __pyx_pybuffer_X_data.pybuffer.buf = NULL; + __pyx_pybuffer_X_data.refcount = 0; + __pyx_pybuffernd_X_data.data = NULL; + __pyx_pybuffernd_X_data.rcbuffer = &__pyx_pybuffer_X_data; + __pyx_pybuffer_X_indices.pybuffer.buf = NULL; + __pyx_pybuffer_X_indices.refcount = 0; + __pyx_pybuffernd_X_indices.data = NULL; + __pyx_pybuffernd_X_indices.rcbuffer = &__pyx_pybuffer_X_indices; + __pyx_pybuffer_X_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_X_indptr.refcount = 0; + __pyx_pybuffernd_X_indptr.data = NULL; + __pyx_pybuffernd_X_indptr.rcbuffer = &__pyx_pybuffer_X_indptr; + __pyx_pybuffer_means.pybuffer.buf = NULL; + __pyx_pybuffer_means.refcount = 0; + __pyx_pybuffernd_means.data = NULL; + __pyx_pybuffernd_means.rcbuffer = &__pyx_pybuffer_means; + __pyx_pybuffer_variances.pybuffer.buf = NULL; + __pyx_pybuffer_variances.refcount = 0; + __pyx_pybuffernd_variances.data = NULL; + __pyx_pybuffernd_variances.rcbuffer = &__pyx_pybuffer_variances; + + /* "sklearn/utils/sparsefuncs_fast.pyx":132 + * + * """ + * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< + * cdef unsigned int n_features = X.shape[1] + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyInt_As_unsigned_int(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_n_samples = __pyx_t_3; + + /* "sklearn/utils/sparsefuncs_fast.pyx":133 + * """ + * cdef unsigned int n_samples = X.shape[0] + * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< + * + * cdef np.ndarray[DOUBLE, ndim=1] X_data + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_PyInt_As_unsigned_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_n_features = __pyx_t_3; + + /* "sklearn/utils/sparsefuncs_fast.pyx":136 + * + * cdef np.ndarray[DOUBLE, ndim=1] X_data + * X_data = np.asarray(X.data, dtype=np.float64) # might copy! # <<<<<<<<<<<<<< + * cdef np.ndarray[int, ndim=1] X_indices = X.indices + * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr + */ + __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_asarray); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_float64); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = ((PyArrayObject *)__pyx_t_6); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __pyx_t_8 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer, (PyObject*)__pyx_t_7, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_8 < 0)) { + PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_X_data, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + } + } + __pyx_pybuffernd_X_data.diminfo[0].strides = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_data.diminfo[0].shape = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_8 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_7 = 0; + __pyx_v_X_data = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":137 + * cdef np.ndarray[DOUBLE, ndim=1] X_data + * X_data = np.asarray(X.data, dtype=np.float64) # might copy! + * cdef np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< + * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr + * + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 137; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 137; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = ((PyArrayObject *)__pyx_t_6); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer, (PyObject*)__pyx_t_12, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 137; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indices.diminfo[0].strides = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indices.diminfo[0].shape = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_12 = 0; + __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":138 + * X_data = np.asarray(X.data, dtype=np.float64) # might copy! + * cdef np.ndarray[int, ndim=1] X_indices = X.indices + * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< + * + * cdef unsigned int i + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_13 = ((PyArrayObject *)__pyx_t_6); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_t_13, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indptr.diminfo[0].strides = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indptr.diminfo[0].shape = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_13 = 0; + __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":148 + * + * # means[j] contains the mean of feature j + * cdef np.ndarray[DOUBLE, ndim=1] means = np.zeros(n_features, # <<<<<<<<<<<<<< + * dtype=np.float64) + * + */ + __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyInt_From_unsigned_int(__pyx_v_n_features); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + + /* "sklearn/utils/sparsefuncs_fast.pyx":149 + * # means[j] contains the mean of feature j + * cdef np.ndarray[DOUBLE, ndim=1] means = np.zeros(n_features, + * dtype=np.float64) # <<<<<<<<<<<<<< + * + * # variances[j] contains the variance of feature j + */ + __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_dtype, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":148 + * + * # means[j] contains the mean of feature j + * cdef np.ndarray[DOUBLE, ndim=1] means = np.zeros(n_features, # <<<<<<<<<<<<<< + * dtype=np.float64) + * + */ + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_4, __pyx_t_6); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_5) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_5, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_14 = ((PyArrayObject *)__pyx_t_5); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_means.rcbuffer->pybuffer, (PyObject*)__pyx_t_14, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_means = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_means.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_means.diminfo[0].strides = __pyx_pybuffernd_means.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_means.diminfo[0].shape = __pyx_pybuffernd_means.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_14 = 0; + __pyx_v_means = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":152 + * + * # variances[j] contains the variance of feature j + * cdef np.ndarray[DOUBLE, ndim=1] variances = np.zeros_like(means) # <<<<<<<<<<<<<< + * + * for i in xrange(n_features): + */ + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros_like); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(((PyObject *)__pyx_v_means)); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_means)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_means)); + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_15 = ((PyArrayObject *)__pyx_t_4); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_variances.rcbuffer->pybuffer, (PyObject*)__pyx_t_15, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_variances = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_variances.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_variances.diminfo[0].strides = __pyx_pybuffernd_variances.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_variances.diminfo[0].shape = __pyx_pybuffernd_variances.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_15 = 0; + __pyx_v_variances = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":154 + * cdef np.ndarray[DOUBLE, ndim=1] variances = np.zeros_like(means) + * + * for i in xrange(n_features): # <<<<<<<<<<<<<< + * + * startptr = X_indptr[i] + */ + __pyx_t_3 = __pyx_v_n_features; + for (__pyx_t_16 = 0; __pyx_t_16 < __pyx_t_3; __pyx_t_16+=1) { + __pyx_v_i = __pyx_t_16; + + /* "sklearn/utils/sparsefuncs_fast.pyx":156 + * for i in xrange(n_features): + * + * startptr = X_indptr[i] # <<<<<<<<<<<<<< + * endptr = X_indptr[i + 1] + * counts = endptr - startptr + */ + __pyx_t_17 = __pyx_v_i; + __pyx_v_startptr = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); + + /* "sklearn/utils/sparsefuncs_fast.pyx":157 + * + * startptr = X_indptr[i] + * endptr = X_indptr[i + 1] # <<<<<<<<<<<<<< + * counts = endptr - startptr + * + */ + __pyx_t_18 = (__pyx_v_i + 1); + __pyx_v_endptr = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); + + /* "sklearn/utils/sparsefuncs_fast.pyx":158 + * startptr = X_indptr[i] + * endptr = X_indptr[i + 1] + * counts = endptr - startptr # <<<<<<<<<<<<<< + * + * for j in xrange(startptr, endptr): + */ + __pyx_v_counts = (__pyx_v_endptr - __pyx_v_startptr); + + /* "sklearn/utils/sparsefuncs_fast.pyx":160 + * counts = endptr - startptr + * + * for j in xrange(startptr, endptr): # <<<<<<<<<<<<<< + * means[i] += X_data[j] + * means[i] /= n_samples + */ + __pyx_t_19 = __pyx_v_endptr; + for (__pyx_t_20 = __pyx_v_startptr; __pyx_t_20 < __pyx_t_19; __pyx_t_20+=1) { + __pyx_v_j = __pyx_t_20; + + /* "sklearn/utils/sparsefuncs_fast.pyx":161 + * + * for j in xrange(startptr, endptr): + * means[i] += X_data[j] # <<<<<<<<<<<<<< + * means[i] /= n_samples + * + */ + __pyx_t_21 = __pyx_v_j; + __pyx_t_22 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_means.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_means.diminfo[0].strides) += (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_X_data.diminfo[0].strides)); + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":162 + * for j in xrange(startptr, endptr): + * means[i] += X_data[j] + * means[i] /= n_samples # <<<<<<<<<<<<<< + * + * for j in xrange(startptr, endptr): + */ + __pyx_t_19 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_means.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_means.diminfo[0].strides) /= __pyx_v_n_samples; + + /* "sklearn/utils/sparsefuncs_fast.pyx":164 + * means[i] /= n_samples + * + * for j in xrange(startptr, endptr): # <<<<<<<<<<<<<< + * diff = X_data[j] - means[i] + * variances[i] += diff * diff + */ + __pyx_t_20 = __pyx_v_endptr; + for (__pyx_t_23 = __pyx_v_startptr; __pyx_t_23 < __pyx_t_20; __pyx_t_23+=1) { + __pyx_v_j = __pyx_t_23; + + /* "sklearn/utils/sparsefuncs_fast.pyx":165 + * + * for j in xrange(startptr, endptr): + * diff = X_data[j] - means[i] # <<<<<<<<<<<<<< + * variances[i] += diff * diff + * + */ + __pyx_t_24 = __pyx_v_j; + __pyx_t_25 = __pyx_v_i; + __pyx_v_diff = ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_X_data.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_means.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_means.diminfo[0].strides))); + + /* "sklearn/utils/sparsefuncs_fast.pyx":166 + * for j in xrange(startptr, endptr): + * diff = X_data[j] - means[i] + * variances[i] += diff * diff # <<<<<<<<<<<<<< + * + * variances[i] += (n_samples - counts) * means[i] * means[i] + */ + __pyx_t_26 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_variances.rcbuffer->pybuffer.buf, __pyx_t_26, __pyx_pybuffernd_variances.diminfo[0].strides) += (__pyx_v_diff * __pyx_v_diff); + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":168 + * variances[i] += diff * diff + * + * variances[i] += (n_samples - counts) * means[i] * means[i] # <<<<<<<<<<<<<< + * variances[i] /= n_samples + * + */ + __pyx_t_20 = __pyx_v_i; + __pyx_t_23 = __pyx_v_i; + __pyx_t_27 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_variances.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_variances.diminfo[0].strides) += (((__pyx_v_n_samples - __pyx_v_counts) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_means.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_means.diminfo[0].strides))) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_means.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_means.diminfo[0].strides))); + + /* "sklearn/utils/sparsefuncs_fast.pyx":169 + * + * variances[i] += (n_samples - counts) * means[i] * means[i] + * variances[i] /= n_samples # <<<<<<<<<<<<<< + * + * return means, variances + */ + __pyx_t_28 = __pyx_v_i; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_variances.rcbuffer->pybuffer.buf, __pyx_t_28, __pyx_pybuffernd_variances.diminfo[0].strides) /= __pyx_v_n_samples; + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":171 + * variances[i] /= n_samples + * + * return means, variances # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)__pyx_v_means)); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_means)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_means)); + __Pyx_INCREF(((PyObject *)__pyx_v_variances)); + PyTuple_SET_ITEM(__pyx_t_4, 1, ((PyObject *)__pyx_v_variances)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_variances)); + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":114 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csc_mean_variance_axis0(X): # <<<<<<<<<<<<<< + * """Compute mean and variance along axis 0 on a CSC matrix + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_means.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_variances.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.utils.sparsefuncs_fast.csc_mean_variance_axis0", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_means.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_variances.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_X_data); + __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); + __Pyx_XDECREF((PyObject *)__pyx_v_X_indptr); + __Pyx_XDECREF((PyObject *)__pyx_v_means); + __Pyx_XDECREF((PyObject *)__pyx_v_variances); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/sparsefuncs_fast.pyx":177 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def inplace_csr_row_normalize_l1(X): # <<<<<<<<<<<<<< + * """Inplace row normalize using the l1 norm""" + * cdef unsigned int n_samples = X.shape[0] + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_7inplace_csr_row_normalize_l1(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ +static char __pyx_doc_7sklearn_5utils_16sparsefuncs_fast_6inplace_csr_row_normalize_l1[] = "Inplace row normalize using the l1 norm"; +static PyMethodDef __pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_7inplace_csr_row_normalize_l1 = {__Pyx_NAMESTR("inplace_csr_row_normalize_l1"), (PyCFunction)__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_7inplace_csr_row_normalize_l1, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_16sparsefuncs_fast_6inplace_csr_row_normalize_l1)}; +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_7inplace_csr_row_normalize_l1(PyObject *__pyx_self, PyObject *__pyx_v_X) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("inplace_csr_row_normalize_l1 (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_5utils_16sparsefuncs_fast_6inplace_csr_row_normalize_l1(__pyx_self, ((PyObject *)__pyx_v_X)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_6inplace_csr_row_normalize_l1(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X) { + unsigned int __pyx_v_n_samples; + CYTHON_UNUSED unsigned int __pyx_v_n_features; + PyArrayObject *__pyx_v_X_data = 0; + CYTHON_UNUSED PyArrayObject *__pyx_v_X_indices = 0; + PyArrayObject *__pyx_v_X_indptr = 0; + unsigned int __pyx_v_i; + unsigned int __pyx_v_j; + double __pyx_v_sum_; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_data; + __Pyx_Buffer __pyx_pybuffer_X_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indices; + __Pyx_Buffer __pyx_pybuffer_X_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indptr; + __Pyx_Buffer __pyx_pybuffer_X_indptr; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + unsigned int __pyx_t_3; + PyArrayObject *__pyx_t_4 = NULL; + PyArrayObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + unsigned int __pyx_t_7; + long __pyx_t_8; + int __pyx_t_9; + unsigned int __pyx_t_10; + unsigned int __pyx_t_11; + unsigned int __pyx_t_12; + int __pyx_t_13; + long __pyx_t_14; + unsigned int __pyx_t_15; + unsigned int __pyx_t_16; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("inplace_csr_row_normalize_l1", 0); + __pyx_pybuffer_X_data.pybuffer.buf = NULL; + __pyx_pybuffer_X_data.refcount = 0; + __pyx_pybuffernd_X_data.data = NULL; + __pyx_pybuffernd_X_data.rcbuffer = &__pyx_pybuffer_X_data; + __pyx_pybuffer_X_indices.pybuffer.buf = NULL; + __pyx_pybuffer_X_indices.refcount = 0; + __pyx_pybuffernd_X_indices.data = NULL; + __pyx_pybuffernd_X_indices.rcbuffer = &__pyx_pybuffer_X_indices; + __pyx_pybuffer_X_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_X_indptr.refcount = 0; + __pyx_pybuffernd_X_indptr.data = NULL; + __pyx_pybuffernd_X_indptr.rcbuffer = &__pyx_pybuffer_X_indptr; + + /* "sklearn/utils/sparsefuncs_fast.pyx":179 + * def inplace_csr_row_normalize_l1(X): + * """Inplace row normalize using the l1 norm""" + * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< + * cdef unsigned int n_features = X.shape[1] + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyInt_As_unsigned_int(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_n_samples = __pyx_t_3; + + /* "sklearn/utils/sparsefuncs_fast.pyx":180 + * """Inplace row normalize using the l1 norm""" + * cdef unsigned int n_samples = X.shape[0] + * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< + * + * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_PyInt_As_unsigned_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_n_features = __pyx_t_3; + + /* "sklearn/utils/sparsefuncs_fast.pyx":182 + * cdef unsigned int n_features = X.shape[1] + * + * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data # <<<<<<<<<<<<<< + * cdef np.ndarray[int, ndim=1] X_indices = X.indices + * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_data.diminfo[0].strides = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_data.diminfo[0].shape = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_4 = 0; + __pyx_v_X_data = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":183 + * + * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data + * cdef np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< + * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indices.diminfo[0].strides = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indices.diminfo[0].shape = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_5 = 0; + __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":184 + * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data + * cdef np.ndarray[int, ndim=1] X_indices = X.indices + * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< + * + * # the column indices for row i are stored in: + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indptr.diminfo[0].strides = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indptr.diminfo[0].shape = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":194 + * cdef double sum_ + * + * for i in xrange(n_samples): # <<<<<<<<<<<<<< + * sum_ = 0.0 + * + */ + __pyx_t_3 = __pyx_v_n_samples; + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_3; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; + + /* "sklearn/utils/sparsefuncs_fast.pyx":195 + * + * for i in xrange(n_samples): + * sum_ = 0.0 # <<<<<<<<<<<<<< + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): + */ + __pyx_v_sum_ = 0.0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":197 + * sum_ = 0.0 + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< + * sum_ += fabs(X_data[j]) + * + */ + __pyx_t_8 = (__pyx_v_i + 1); + __pyx_t_9 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); + __pyx_t_10 = __pyx_v_i; + for (__pyx_t_11 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { + __pyx_v_j = __pyx_t_11; + + /* "sklearn/utils/sparsefuncs_fast.pyx":198 + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): + * sum_ += fabs(X_data[j]) # <<<<<<<<<<<<<< + * + * if sum_ == 0.0: + */ + __pyx_t_12 = __pyx_v_j; + __pyx_v_sum_ = (__pyx_v_sum_ + fabs((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_X_data.diminfo[0].strides)))); + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":200 + * sum_ += fabs(X_data[j]) + * + * if sum_ == 0.0: # <<<<<<<<<<<<<< + * # do not normalize empty rows (can happen if CSR is not pruned + * # correctly) + */ + __pyx_t_13 = ((__pyx_v_sum_ == 0.0) != 0); + if (__pyx_t_13) { + + /* "sklearn/utils/sparsefuncs_fast.pyx":203 + * # do not normalize empty rows (can happen if CSR is not pruned + * # correctly) + * continue # <<<<<<<<<<<<<< + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): + */ + goto __pyx_L3_continue; + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":205 + * continue + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< + * X_data[j] /= sum_ + * + */ + __pyx_t_14 = (__pyx_v_i + 1); + __pyx_t_9 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); + __pyx_t_11 = __pyx_v_i; + for (__pyx_t_15 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); __pyx_t_15 < __pyx_t_9; __pyx_t_15+=1) { + __pyx_v_j = __pyx_t_15; + + /* "sklearn/utils/sparsefuncs_fast.pyx":206 + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): + * X_data[j] /= sum_ # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_16 = __pyx_v_j; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_X_data.diminfo[0].strides) /= __pyx_v_sum_; + } + __pyx_L3_continue:; + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":177 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def inplace_csr_row_normalize_l1(X): # <<<<<<<<<<<<<< + * """Inplace row normalize using the l1 norm""" + * cdef unsigned int n_samples = X.shape[0] + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.utils.sparsefuncs_fast.inplace_csr_row_normalize_l1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_X_data); + __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); + __Pyx_XDECREF((PyObject *)__pyx_v_X_indptr); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/sparsefuncs_fast.pyx":212 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def inplace_csr_row_normalize_l2(X): # <<<<<<<<<<<<<< + * """Inplace row normalize using the l2 norm""" + * cdef unsigned int n_samples = X.shape[0] + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_9inplace_csr_row_normalize_l2(PyObject *__pyx_self, PyObject *__pyx_v_X); /*proto*/ +static char __pyx_doc_7sklearn_5utils_16sparsefuncs_fast_8inplace_csr_row_normalize_l2[] = "Inplace row normalize using the l2 norm"; +static PyMethodDef __pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_9inplace_csr_row_normalize_l2 = {__Pyx_NAMESTR("inplace_csr_row_normalize_l2"), (PyCFunction)__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_9inplace_csr_row_normalize_l2, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_16sparsefuncs_fast_8inplace_csr_row_normalize_l2)}; +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_9inplace_csr_row_normalize_l2(PyObject *__pyx_self, PyObject *__pyx_v_X) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("inplace_csr_row_normalize_l2 (wrapper)", 0); + __pyx_r = __pyx_pf_7sklearn_5utils_16sparsefuncs_fast_8inplace_csr_row_normalize_l2(__pyx_self, ((PyObject *)__pyx_v_X)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_8inplace_csr_row_normalize_l2(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X) { + unsigned int __pyx_v_n_samples; + CYTHON_UNUSED unsigned int __pyx_v_n_features; + PyArrayObject *__pyx_v_X_data = 0; + CYTHON_UNUSED PyArrayObject *__pyx_v_X_indices = 0; + PyArrayObject *__pyx_v_X_indptr = 0; + unsigned int __pyx_v_i; + unsigned int __pyx_v_j; + double __pyx_v_sum_; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_data; + __Pyx_Buffer __pyx_pybuffer_X_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indices; + __Pyx_Buffer __pyx_pybuffer_X_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_indptr; + __Pyx_Buffer __pyx_pybuffer_X_indptr; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + unsigned int __pyx_t_3; + PyArrayObject *__pyx_t_4 = NULL; + PyArrayObject *__pyx_t_5 = NULL; + PyArrayObject *__pyx_t_6 = NULL; + unsigned int __pyx_t_7; + long __pyx_t_8; + int __pyx_t_9; + unsigned int __pyx_t_10; + unsigned int __pyx_t_11; + unsigned int __pyx_t_12; + unsigned int __pyx_t_13; + int __pyx_t_14; + long __pyx_t_15; + unsigned int __pyx_t_16; + unsigned int __pyx_t_17; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("inplace_csr_row_normalize_l2", 0); + __pyx_pybuffer_X_data.pybuffer.buf = NULL; + __pyx_pybuffer_X_data.refcount = 0; + __pyx_pybuffernd_X_data.data = NULL; + __pyx_pybuffernd_X_data.rcbuffer = &__pyx_pybuffer_X_data; + __pyx_pybuffer_X_indices.pybuffer.buf = NULL; + __pyx_pybuffer_X_indices.refcount = 0; + __pyx_pybuffernd_X_indices.data = NULL; + __pyx_pybuffernd_X_indices.rcbuffer = &__pyx_pybuffer_X_indices; + __pyx_pybuffer_X_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_X_indptr.refcount = 0; + __pyx_pybuffernd_X_indptr.data = NULL; + __pyx_pybuffernd_X_indptr.rcbuffer = &__pyx_pybuffer_X_indptr; + + /* "sklearn/utils/sparsefuncs_fast.pyx":214 + * def inplace_csr_row_normalize_l2(X): + * """Inplace row normalize using the l2 norm""" + * cdef unsigned int n_samples = X.shape[0] # <<<<<<<<<<<<<< + * cdef unsigned int n_features = X.shape[1] + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyInt_As_unsigned_int(__pyx_t_2); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_n_samples = __pyx_t_3; + + /* "sklearn/utils/sparsefuncs_fast.pyx":215 + * """Inplace row normalize using the l2 norm""" + * cdef unsigned int n_samples = X.shape[0] + * cdef unsigned int n_features = X.shape[1] # <<<<<<<<<<<<<< + * + * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_PyInt_As_unsigned_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_n_features = __pyx_t_3; + + /* "sklearn/utils/sparsefuncs_fast.pyx":217 + * cdef unsigned int n_features = X.shape[1] + * + * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data # <<<<<<<<<<<<<< + * cdef np.ndarray[int, ndim=1] X_indices = X.indices + * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer, (PyObject*)__pyx_t_4, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_data.diminfo[0].strides = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_data.diminfo[0].shape = __pyx_pybuffernd_X_data.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_4 = 0; + __pyx_v_X_data = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":218 + * + * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data + * cdef np.ndarray[int, ndim=1] X_indices = X.indices # <<<<<<<<<<<<<< + * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indices.diminfo[0].strides = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indices.diminfo[0].shape = __pyx_pybuffernd_X_indices.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_5 = 0; + __pyx_v_X_indices = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":219 + * cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data + * cdef np.ndarray[int, ndim=1] X_indices = X.indices + * cdef np.ndarray[int, ndim=1] X_indptr = X.indptr # <<<<<<<<<<<<<< + * + * cdef unsigned int i + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_X_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_X_indptr.diminfo[0].strides = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_indptr.diminfo[0].shape = __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_6 = 0; + __pyx_v_X_indptr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":225 + * cdef double sum_ + * + * for i in xrange(n_samples): # <<<<<<<<<<<<<< + * sum_ = 0.0 + * + */ + __pyx_t_3 = __pyx_v_n_samples; + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_3; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; + + /* "sklearn/utils/sparsefuncs_fast.pyx":226 + * + * for i in xrange(n_samples): + * sum_ = 0.0 # <<<<<<<<<<<<<< + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): + */ + __pyx_v_sum_ = 0.0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":228 + * sum_ = 0.0 + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< + * sum_ += (X_data[j] * X_data[j]) + * + */ + __pyx_t_8 = (__pyx_v_i + 1); + __pyx_t_9 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); + __pyx_t_10 = __pyx_v_i; + for (__pyx_t_11 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { + __pyx_v_j = __pyx_t_11; + + /* "sklearn/utils/sparsefuncs_fast.pyx":229 + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): + * sum_ += (X_data[j] * X_data[j]) # <<<<<<<<<<<<<< + * + * if sum_ == 0.0: + */ + __pyx_t_12 = __pyx_v_j; + __pyx_t_13 = __pyx_v_j; + __pyx_v_sum_ = (__pyx_v_sum_ + ((*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_X_data.diminfo[0].strides)) * (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_X_data.diminfo[0].strides)))); + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":231 + * sum_ += (X_data[j] * X_data[j]) + * + * if sum_ == 0.0: # <<<<<<<<<<<<<< + * # do not normalize empty rows (can happen if CSR is not pruned + * # correctly) + */ + __pyx_t_14 = ((__pyx_v_sum_ == 0.0) != 0); + if (__pyx_t_14) { + + /* "sklearn/utils/sparsefuncs_fast.pyx":234 + * # do not normalize empty rows (can happen if CSR is not pruned + * # correctly) + * continue # <<<<<<<<<<<<<< + * + * sum_ = sqrt(sum_) + */ + goto __pyx_L3_continue; + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":236 + * continue + * + * sum_ = sqrt(sum_) # <<<<<<<<<<<<<< + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): + */ + __pyx_v_sum_ = sqrt(__pyx_v_sum_); + + /* "sklearn/utils/sparsefuncs_fast.pyx":238 + * sum_ = sqrt(sum_) + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): # <<<<<<<<<<<<<< + * X_data[j] /= sum_ + * + */ + __pyx_t_15 = (__pyx_v_i + 1); + __pyx_t_9 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); + __pyx_t_11 = __pyx_v_i; + for (__pyx_t_16 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_X_indptr.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_X_indptr.diminfo[0].strides)); __pyx_t_16 < __pyx_t_9; __pyx_t_16+=1) { + __pyx_v_j = __pyx_t_16; + + /* "sklearn/utils/sparsefuncs_fast.pyx":239 + * + * for j in xrange(X_indptr[i], X_indptr[i + 1]): + * X_data[j] /= sum_ # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_17 = __pyx_v_j; + *__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_X_data.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_X_data.diminfo[0].strides) /= __pyx_v_sum_; + } + __pyx_L3_continue:; + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":212 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def inplace_csr_row_normalize_l2(X): # <<<<<<<<<<<<<< + * """Inplace row normalize using the l2 norm""" + * cdef unsigned int n_samples = X.shape[0] + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.utils.sparsefuncs_fast.inplace_csr_row_normalize_l2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_indptr.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_X_data); + __Pyx_XDECREF((PyObject *)__pyx_v_X_indices); + __Pyx_XDECREF((PyObject *)__pyx_v_X_indptr); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/sparsefuncs_fast.pyx":244 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * cdef void add_row_csr(np.ndarray[np.float64_t, ndim=1] data, # <<<<<<<<<<<<<< + * np.ndarray[int, ndim=1] indices, + * np.ndarray[int, ndim=1] indptr, + */ + +static void __pyx_f_7sklearn_5utils_16sparsefuncs_fast_add_row_csr(PyArrayObject *__pyx_v_data, PyArrayObject *__pyx_v_indices, PyArrayObject *__pyx_v_indptr, int __pyx_v_i, PyArrayObject *__pyx_v_out) { + int __pyx_v_ind; + int __pyx_v_j; + __Pyx_LocalBuf_ND __pyx_pybuffernd_data; + __Pyx_Buffer __pyx_pybuffer_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices; + __Pyx_Buffer __pyx_pybuffer_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr; + __Pyx_Buffer __pyx_pybuffer_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_out; + __Pyx_Buffer __pyx_pybuffer_out; + __Pyx_RefNannyDeclarations + long __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("add_row_csr", 0); + __pyx_pybuffer_data.pybuffer.buf = NULL; + __pyx_pybuffer_data.refcount = 0; + __pyx_pybuffernd_data.data = NULL; + __pyx_pybuffernd_data.rcbuffer = &__pyx_pybuffer_data; + __pyx_pybuffer_indices.pybuffer.buf = NULL; + __pyx_pybuffer_indices.refcount = 0; + __pyx_pybuffernd_indices.data = NULL; + __pyx_pybuffernd_indices.rcbuffer = &__pyx_pybuffer_indices; + __pyx_pybuffer_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_indptr.refcount = 0; + __pyx_pybuffernd_indptr.data = NULL; + __pyx_pybuffernd_indptr.rcbuffer = &__pyx_pybuffer_indptr; + __pyx_pybuffer_out.pybuffer.buf = NULL; + __pyx_pybuffer_out.refcount = 0; + __pyx_pybuffernd_out.data = NULL; + __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_data, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_data.diminfo[0].strides = __pyx_pybuffernd_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_data.diminfo[0].shape = __pyx_pybuffernd_data.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indices.diminfo[0].strides = __pyx_pybuffernd_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices.diminfo[0].shape = __pyx_pybuffernd_indices.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indptr.diminfo[0].strides = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr.diminfo[0].shape = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_v_out, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/utils/sparsefuncs_fast.pyx":254 + * cdef int ind, j + * + * for ind in range(indptr[i], indptr[i + 1]): # <<<<<<<<<<<<<< + * j = indices[ind] + * out[j] += data[ind] + */ + __pyx_t_1 = (__pyx_v_i + 1); + __pyx_t_2 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_1, __pyx_pybuffernd_indptr.diminfo[0].strides)); + __pyx_t_3 = __pyx_v_i; + for (__pyx_t_4 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_indptr.diminfo[0].strides)); __pyx_t_4 < __pyx_t_2; __pyx_t_4+=1) { + __pyx_v_ind = __pyx_t_4; + + /* "sklearn/utils/sparsefuncs_fast.pyx":255 + * + * for ind in range(indptr[i], indptr[i + 1]): + * j = indices[ind] # <<<<<<<<<<<<<< + * out[j] += data[ind] + * + */ + __pyx_t_5 = __pyx_v_ind; + __pyx_v_j = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_indices.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_indices.diminfo[0].strides)); + + /* "sklearn/utils/sparsefuncs_fast.pyx":256 + * for ind in range(indptr[i], indptr[i + 1]): + * j = indices[ind] + * out[j] += data[ind] # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_6 = __pyx_v_ind; + __pyx_t_7 = __pyx_v_j; + *__Pyx_BufPtrCContig1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_out.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_out.diminfo[0].strides) += (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_data.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_data.diminfo[0].strides)); + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":244 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * cdef void add_row_csr(np.ndarray[np.float64_t, ndim=1] data, # <<<<<<<<<<<<<< + * np.ndarray[int, ndim=1] indices, + * np.ndarray[int, ndim=1] indptr, + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_WriteUnraisable("sklearn.utils.sparsefuncs_fast.add_row_csr", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_RefNannyFinishContext(); +} + +/* "sklearn/utils/sparsefuncs_fast.pyx":261 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def assign_rows_csr(X, # <<<<<<<<<<<<<< + * np.ndarray[np.npy_intp, ndim=1] X_rows, + * np.ndarray[np.npy_intp, ndim=1] out_rows, + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_11assign_rows_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_16sparsefuncs_fast_10assign_rows_csr[] = "Densify selected rows of a CSR matrix into a preallocated array.\n\n Like out[out_rows] = X[X_rows].toarray() but without copying.\n Only supported for dtype=np.float64.\n\n Parameters\n ----------\n X : scipy.sparse.csr_matrix, shape=(n_samples, n_features)\n X_rows : array, dtype=np.intp, shape=n_rows\n out_rows : array, dtype=np.intp, shape=n_rows\n out : array, shape=(arbitrary, n_features)\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_11assign_rows_csr = {__Pyx_NAMESTR("assign_rows_csr"), (PyCFunction)__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_11assign_rows_csr, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_16sparsefuncs_fast_10assign_rows_csr)}; +static PyObject *__pyx_pw_7sklearn_5utils_16sparsefuncs_fast_11assign_rows_csr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_X = 0; + PyArrayObject *__pyx_v_X_rows = 0; + PyArrayObject *__pyx_v_out_rows = 0; + PyArrayObject *__pyx_v_out = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("assign_rows_csr (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_X_rows,&__pyx_n_s_out_rows,&__pyx_n_s_out,0}; + PyObject* values[4] = {0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_rows)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("assign_rows_csr", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out_rows)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("assign_rows_csr", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 3: + if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("assign_rows_csr", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "assign_rows_csr") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + } + __pyx_v_X = values[0]; + __pyx_v_X_rows = ((PyArrayObject *)values[1]); + __pyx_v_out_rows = ((PyArrayObject *)values[2]); + __pyx_v_out = ((PyArrayObject *)values[3]); + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("assign_rows_csr", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils.sparsefuncs_fast.assign_rows_csr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_X_rows), __pyx_ptype_5numpy_ndarray, 1, "X_rows", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_out_rows), __pyx_ptype_5numpy_ndarray, 1, "out_rows", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 263; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_out), __pyx_ptype_5numpy_ndarray, 1, "out", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 264; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_16sparsefuncs_fast_10assign_rows_csr(__pyx_self, __pyx_v_X, __pyx_v_X_rows, __pyx_v_out_rows, __pyx_v_out); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7sklearn_5utils_16sparsefuncs_fast_10assign_rows_csr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_X, PyArrayObject *__pyx_v_X_rows, PyArrayObject *__pyx_v_out_rows, PyArrayObject *__pyx_v_out) { + int __pyx_v_i; + int __pyx_v_ind; + int __pyx_v_j; + npy_intp __pyx_v_rX; + PyArrayObject *__pyx_v_data = 0; + PyArrayObject *__pyx_v_indices = 0; + PyArrayObject *__pyx_v_indptr = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_X_rows; + __Pyx_Buffer __pyx_pybuffer_X_rows; + __Pyx_LocalBuf_ND __pyx_pybuffernd_data; + __Pyx_Buffer __pyx_pybuffer_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices; + __Pyx_Buffer __pyx_pybuffer_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr; + __Pyx_Buffer __pyx_pybuffer_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_out; + __Pyx_Buffer __pyx_pybuffer_out; + __Pyx_LocalBuf_ND __pyx_pybuffernd_out_rows; + __Pyx_Buffer __pyx_pybuffer_out_rows; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyArrayObject *__pyx_t_2 = NULL; + PyArrayObject *__pyx_t_3 = NULL; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + npy_intp __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + long __pyx_t_10; + int __pyx_t_11; + npy_intp __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + npy_intp __pyx_t_17; + int __pyx_t_18; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_rows_csr", 0); + __pyx_pybuffer_data.pybuffer.buf = NULL; + __pyx_pybuffer_data.refcount = 0; + __pyx_pybuffernd_data.data = NULL; + __pyx_pybuffernd_data.rcbuffer = &__pyx_pybuffer_data; + __pyx_pybuffer_indices.pybuffer.buf = NULL; + __pyx_pybuffer_indices.refcount = 0; + __pyx_pybuffernd_indices.data = NULL; + __pyx_pybuffernd_indices.rcbuffer = &__pyx_pybuffer_indices; + __pyx_pybuffer_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_indptr.refcount = 0; + __pyx_pybuffernd_indptr.data = NULL; + __pyx_pybuffernd_indptr.rcbuffer = &__pyx_pybuffer_indptr; + __pyx_pybuffer_X_rows.pybuffer.buf = NULL; + __pyx_pybuffer_X_rows.refcount = 0; + __pyx_pybuffernd_X_rows.data = NULL; + __pyx_pybuffernd_X_rows.rcbuffer = &__pyx_pybuffer_X_rows; + __pyx_pybuffer_out_rows.pybuffer.buf = NULL; + __pyx_pybuffer_out_rows.refcount = 0; + __pyx_pybuffernd_out_rows.data = NULL; + __pyx_pybuffernd_out_rows.rcbuffer = &__pyx_pybuffer_out_rows; + __pyx_pybuffer_out.pybuffer.buf = NULL; + __pyx_pybuffer_out.refcount = 0; + __pyx_pybuffernd_out.data = NULL; + __pyx_pybuffernd_out.rcbuffer = &__pyx_pybuffer_out; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_X_rows.rcbuffer->pybuffer, (PyObject*)__pyx_v_X_rows, &__Pyx_TypeInfo_nn_npy_intp, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_X_rows.diminfo[0].strides = __pyx_pybuffernd_X_rows.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_X_rows.diminfo[0].shape = __pyx_pybuffernd_X_rows.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out_rows.rcbuffer->pybuffer, (PyObject*)__pyx_v_out_rows, &__Pyx_TypeInfo_nn_npy_intp, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_out_rows.diminfo[0].strides = __pyx_pybuffernd_out_rows.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out_rows.diminfo[0].shape = __pyx_pybuffernd_out_rows.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_out.rcbuffer->pybuffer, (PyObject*)__pyx_v_out, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_out.diminfo[0].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_out.diminfo[0].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_out.diminfo[1].strides = __pyx_pybuffernd_out.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_out.diminfo[1].shape = __pyx_pybuffernd_out.rcbuffer->pybuffer.shape[1]; + + /* "sklearn/utils/sparsefuncs_fast.pyx":282 + * int i, ind, j + * np.npy_intp rX + * np.ndarray[DOUBLE, ndim=1] data = X.data # <<<<<<<<<<<<<< + * np.ndarray[int, ndim=1] indices = X.indices, indptr = X.indptr + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_data.rcbuffer->pybuffer, (PyObject*)__pyx_t_2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_data = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_data.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_data.diminfo[0].strides = __pyx_pybuffernd_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_data.diminfo[0].shape = __pyx_pybuffernd_data.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_2 = 0; + __pyx_v_data = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":283 + * np.npy_intp rX + * np.ndarray[DOUBLE, ndim=1] data = X.data + * np.ndarray[int, ndim=1] indices = X.indices, indptr = X.indptr # <<<<<<<<<<<<<< + * + * if X_rows.shape[0] != out_rows.shape[0]: + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices.rcbuffer->pybuffer, (PyObject*)__pyx_t_3, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_indices = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_indices.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_indices.diminfo[0].strides = __pyx_pybuffernd_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices.diminfo[0].shape = __pyx_pybuffernd_indices.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_3 = 0; + __pyx_v_indices = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_X, __pyx_n_s_indptr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyArrayObject *)__pyx_t_1); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_t_3, &__Pyx_TypeInfo_int, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { + __pyx_v_indptr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_indptr.diminfo[0].strides = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr.diminfo[0].shape = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.shape[0]; + } + } + __pyx_t_3 = 0; + __pyx_v_indptr = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":285 + * np.ndarray[int, ndim=1] indices = X.indices, indptr = X.indptr + * + * if X_rows.shape[0] != out_rows.shape[0]: # <<<<<<<<<<<<<< + * raise ValueError("cannot assign %d rows to %d" + * % (X_rows.shape[0], out_rows.shape[0])) + */ + __pyx_t_4 = (((__pyx_v_X_rows->dimensions[0]) != (__pyx_v_out_rows->dimensions[0])) != 0); + if (__pyx_t_4) { + + /* "sklearn/utils/sparsefuncs_fast.pyx":287 + * if X_rows.shape[0] != out_rows.shape[0]: + * raise ValueError("cannot assign %d rows to %d" + * % (X_rows.shape[0], out_rows.shape[0])) # <<<<<<<<<<<<<< + * + * out[:] = 0. + */ + __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_X_rows->dimensions[0])); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_out_rows->dimensions[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_1 = 0; + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyString_Format(__pyx_kp_s_cannot_assign_d_rows_to_d, __pyx_t_6); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":286 + * + * if X_rows.shape[0] != out_rows.shape[0]: + * raise ValueError("cannot assign %d rows to %d" # <<<<<<<<<<<<<< + * % (X_rows.shape[0], out_rows.shape[0])) + * + */ + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":289 + * % (X_rows.shape[0], out_rows.shape[0])) + * + * out[:] = 0. # <<<<<<<<<<<<<< + * for i in range(X_rows.shape[0]): + * # XXX we could reuse add_row_csr here, but the array slice + */ + if (__Pyx_PyObject_SetSlice(((PyObject *)__pyx_v_out), __pyx_float_0_, 0, 0, NULL, NULL, &__pyx_slice_, 0, 0, 0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/sparsefuncs_fast.pyx":290 + * + * out[:] = 0. + * for i in range(X_rows.shape[0]): # <<<<<<<<<<<<<< + * # XXX we could reuse add_row_csr here, but the array slice + * # is not optimized away. + */ + __pyx_t_7 = (__pyx_v_X_rows->dimensions[0]); + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_i = __pyx_t_8; + + /* "sklearn/utils/sparsefuncs_fast.pyx":293 + * # XXX we could reuse add_row_csr here, but the array slice + * # is not optimized away. + * rX = X_rows[i] # <<<<<<<<<<<<<< + * for ind in range(indptr[rX], indptr[rX + 1]): + * j = indices[ind] + */ + __pyx_t_9 = __pyx_v_i; + __pyx_v_rX = (*__Pyx_BufPtrStrided1d(npy_intp *, __pyx_pybuffernd_X_rows.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_X_rows.diminfo[0].strides)); + + /* "sklearn/utils/sparsefuncs_fast.pyx":294 + * # is not optimized away. + * rX = X_rows[i] + * for ind in range(indptr[rX], indptr[rX + 1]): # <<<<<<<<<<<<<< + * j = indices[ind] + * out[out_rows[i], j] = data[ind] + */ + __pyx_t_10 = (__pyx_v_rX + 1); + __pyx_t_11 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_indptr.diminfo[0].strides)); + __pyx_t_12 = __pyx_v_rX; + for (__pyx_t_13 = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_indptr.diminfo[0].strides)); __pyx_t_13 < __pyx_t_11; __pyx_t_13+=1) { + __pyx_v_ind = __pyx_t_13; + + /* "sklearn/utils/sparsefuncs_fast.pyx":295 + * rX = X_rows[i] + * for ind in range(indptr[rX], indptr[rX + 1]): + * j = indices[ind] # <<<<<<<<<<<<<< + * out[out_rows[i], j] = data[ind] + */ + __pyx_t_14 = __pyx_v_ind; + __pyx_v_j = (*__Pyx_BufPtrStrided1d(int *, __pyx_pybuffernd_indices.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_indices.diminfo[0].strides)); + + /* "sklearn/utils/sparsefuncs_fast.pyx":296 + * for ind in range(indptr[rX], indptr[rX + 1]): + * j = indices[ind] + * out[out_rows[i], j] = data[ind] # <<<<<<<<<<<<<< + */ + __pyx_t_15 = __pyx_v_ind; + __pyx_t_16 = __pyx_v_i; + __pyx_t_17 = (*__Pyx_BufPtrStrided1d(npy_intp *, __pyx_pybuffernd_out_rows.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_out_rows.diminfo[0].strides)); + __pyx_t_18 = __pyx_v_j; + *__Pyx_BufPtrCContig2d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_out.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_out.diminfo[0].strides, __pyx_t_18, __pyx_pybuffernd_out.diminfo[1].strides) = (*__Pyx_BufPtrStrided1d(__pyx_t_7sklearn_5utils_16sparsefuncs_fast_DOUBLE *, __pyx_pybuffernd_data.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_data.diminfo[0].strides)); + } + } + + /* "sklearn/utils/sparsefuncs_fast.pyx":261 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def assign_rows_csr(X, # <<<<<<<<<<<<<< + * np.ndarray[np.npy_intp, ndim=1] X_rows, + * np.ndarray[np.npy_intp, ndim=1] out_rows, + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_rows.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out_rows.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_AddTraceback("sklearn.utils.sparsefuncs_fast.assign_rows_csr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_X_rows.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_out_rows.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_data); + __Pyx_XDECREF((PyObject *)__pyx_v_indices); + __Pyx_XDECREF((PyObject *)__pyx_v_indptr); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":200 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":203 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":204 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":206 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":208 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":209 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":211 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":213 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":214 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":217 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); + if (__pyx_t_3) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":218 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":221 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":222 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":223 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":226 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":227 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":228 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":229 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":230 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":232 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":233 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":234 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":235 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":236 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":239 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":240 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":244 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":246 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_2) { + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":248 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":251 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":253 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + */ + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":254 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + */ + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":255 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); + if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":256 + * t = descr.type_num + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); + if (__pyx_t_1) { + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":259 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":260 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":261 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":262 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":263 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":264 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":265 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":266 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":267 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":268 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":269 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":270 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":271 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":272 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":273 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":276 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":277 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":278 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":280 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":281 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":282 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< + * info.format + _buffer_format_string_len, + * &offset) + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":286 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = '\x00'; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":289 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":290 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":291 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":292 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":769 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":772 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":775 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":778 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":781 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + long __pyx_t_10; + char *__pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":790 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":791 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":794 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); + __pyx_t_3 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":795 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":796 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":798 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":801 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_6 = ((__pyx_v_child->byteorder == '>') != 0); + if (__pyx_t_6) { + __pyx_t_7 = (__pyx_v_little_endian != 0); + } else { + __pyx_t_7 = __pyx_t_6; + } + if (!__pyx_t_7) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":802 + * + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_6 = ((__pyx_v_child->byteorder == '<') != 0); + if (__pyx_t_6) { + __pyx_t_8 = ((!(__pyx_v_little_endian != 0)) != 0); + __pyx_t_9 = __pyx_t_8; + } else { + __pyx_t_9 = __pyx_t_6; + } + __pyx_t_6 = __pyx_t_9; + } else { + __pyx_t_6 = __pyx_t_7; + } + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":813 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_6) break; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":814 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":815 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":816 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":818 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":820 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":821 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":822 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); + if (__pyx_t_6) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":826 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":827 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":828 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":829 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":830 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":831 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":832 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":833 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":834 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":835 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":836 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":837 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":838 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":839 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":840 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":841 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":842 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L11; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":844 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L11:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":845 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L9; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":849 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_11; + } + __pyx_L9:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":850 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":968 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":969 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":971 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":972 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":973 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":974 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":977 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); + if (__pyx_t_1) { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":978 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + } + /*else*/ { + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":980 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else + PyModuleDef_HEAD_INIT, + #endif + __Pyx_NAMESTR("sparsefuncs_fast"), + 0, /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, + {&__pyx_n_s_X_data, __pyx_k_X_data, sizeof(__pyx_k_X_data), 0, 0, 1, 1}, + {&__pyx_n_s_X_indices, __pyx_k_X_indices, sizeof(__pyx_k_X_indices), 0, 0, 1, 1}, + {&__pyx_n_s_X_indptr, __pyx_k_X_indptr, sizeof(__pyx_k_X_indptr), 0, 0, 1, 1}, + {&__pyx_n_s_X_rows, __pyx_k_X_rows, sizeof(__pyx_k_X_rows), 0, 0, 1, 1}, + {&__pyx_n_s__8, __pyx_k__8, sizeof(__pyx_k__8), 0, 0, 1, 1}, + {&__pyx_n_s_asarray, __pyx_k_asarray, sizeof(__pyx_k_asarray), 0, 0, 1, 1}, + {&__pyx_n_s_assign_rows_csr, __pyx_k_assign_rows_csr, sizeof(__pyx_k_assign_rows_csr), 0, 0, 1, 1}, + {&__pyx_kp_s_cannot_assign_d_rows_to_d, __pyx_k_cannot_assign_d_rows_to_d, sizeof(__pyx_k_cannot_assign_d_rows_to_d), 0, 0, 1, 0}, + {&__pyx_n_s_col_ind, __pyx_k_col_ind, sizeof(__pyx_k_col_ind), 0, 0, 1, 1}, + {&__pyx_n_s_counts, __pyx_k_counts, sizeof(__pyx_k_counts), 0, 0, 1, 1}, + {&__pyx_n_s_csc_mean_variance_axis0, __pyx_k_csc_mean_variance_axis0, sizeof(__pyx_k_csc_mean_variance_axis0), 0, 0, 1, 1}, + {&__pyx_n_s_csr_mean_variance_axis0, __pyx_k_csr_mean_variance_axis0, sizeof(__pyx_k_csr_mean_variance_axis0), 0, 0, 1, 1}, + {&__pyx_n_s_csr_row_norms, __pyx_k_csr_row_norms, sizeof(__pyx_k_csr_row_norms), 0, 0, 1, 1}, + {&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1}, + {&__pyx_n_s_diff, __pyx_k_diff, sizeof(__pyx_k_diff), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_endptr, __pyx_k_endptr, sizeof(__pyx_k_endptr), 0, 0, 1, 1}, + {&__pyx_kp_s_files_work_opensource_scikit_le, __pyx_k_files_work_opensource_scikit_le, sizeof(__pyx_k_files_work_opensource_scikit_le), 0, 0, 1, 0}, + {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 0, 0, 1, 1}, + {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_ind, __pyx_k_ind, sizeof(__pyx_k_ind), 0, 0, 1, 1}, + {&__pyx_n_s_indices, __pyx_k_indices, sizeof(__pyx_k_indices), 0, 0, 1, 1}, + {&__pyx_n_s_indptr, __pyx_k_indptr, sizeof(__pyx_k_indptr), 0, 0, 1, 1}, + {&__pyx_n_s_inplace_csr_row_normalize_l1, __pyx_k_inplace_csr_row_normalize_l1, sizeof(__pyx_k_inplace_csr_row_normalize_l1), 0, 0, 1, 1}, + {&__pyx_n_s_inplace_csr_row_normalize_l2, __pyx_k_inplace_csr_row_normalize_l2, sizeof(__pyx_k_inplace_csr_row_normalize_l2), 0, 0, 1, 1}, + {&__pyx_n_s_int32, __pyx_k_int32, sizeof(__pyx_k_int32), 0, 0, 1, 1}, + {&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_means, __pyx_k_means, sizeof(__pyx_k_means), 0, 0, 1, 1}, + {&__pyx_n_s_n_features, __pyx_k_n_features, sizeof(__pyx_k_n_features), 0, 0, 1, 1}, + {&__pyx_n_s_n_samples, __pyx_k_n_samples, sizeof(__pyx_k_n_samples), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_non_zero, __pyx_k_non_zero, sizeof(__pyx_k_non_zero), 0, 0, 1, 1}, + {&__pyx_n_s_norms, __pyx_k_norms, sizeof(__pyx_k_norms), 0, 0, 1, 1}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_out, __pyx_k_out, sizeof(__pyx_k_out), 0, 0, 1, 1}, + {&__pyx_n_s_out_rows, __pyx_k_out_rows, sizeof(__pyx_k_out_rows), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_releasebuffer, __pyx_k_pyx_releasebuffer, sizeof(__pyx_k_pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s_rX, __pyx_k_rX, sizeof(__pyx_k_rX), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_scipy_sparse, __pyx_k_scipy_sparse, sizeof(__pyx_k_scipy_sparse), 0, 0, 1, 1}, + {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, + {&__pyx_n_s_sklearn_utils_sparsefuncs_fast, __pyx_k_sklearn_utils_sparsefuncs_fast, sizeof(__pyx_k_sklearn_utils_sparsefuncs_fast), 0, 0, 1, 1}, + {&__pyx_n_s_sp, __pyx_k_sp, sizeof(__pyx_k_sp), 0, 0, 1, 1}, + {&__pyx_n_s_startptr, __pyx_k_startptr, sizeof(__pyx_k_startptr), 0, 0, 1, 1}, + {&__pyx_n_s_sum, __pyx_k_sum, sizeof(__pyx_k_sum), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_variances, __pyx_k_variances, sizeof(__pyx_k_variances), 0, 0, 1, 1}, + {&__pyx_n_s_xrange, __pyx_k_xrange, sizeof(__pyx_k_xrange), 0, 0, 1, 1}, + {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, + {&__pyx_n_s_zeros_like, __pyx_k_zeros_like, sizeof(__pyx_k_zeros_like), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION >= 3 + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "sklearn/utils/sparsefuncs_fast.pyx":289 + * % (X_rows.shape[0], out_rows.shape[0])) + * + * out[:] = 0. # <<<<<<<<<<<<<< + * for i in range(X_rows.shape[0]): + * # XXX we could reuse add_row_csr here, but the array slice + */ + __pyx_slice_ = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_slice_); + __Pyx_GIVEREF(__pyx_slice_); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == c'>' and little_endian) or + */ + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + + /* "sklearn/utils/sparsefuncs_fast.pyx":23 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csr_row_norms(X): # <<<<<<<<<<<<<< + * """L2 norm of each row in CSR matrix X.""" + * cdef: + */ + __pyx_tuple__9 = PyTuple_Pack(10, __pyx_n_s_X, __pyx_n_s_n_samples, __pyx_n_s_n_features, __pyx_n_s_norms, __pyx_n_s_data, __pyx_n_s_indices, __pyx_n_s_indptr, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_sum); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + __pyx_codeobj__10 = (PyObject*)__Pyx_PyCode_New(1, 0, 10, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__9, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_files_work_opensource_scikit_le, __pyx_n_s_csr_row_norms, 23, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/sparsefuncs_fast.pyx":51 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csr_mean_variance_axis0(X): # <<<<<<<<<<<<<< + * """Compute mean and variance along axis 0 on a CSR matrix + * + */ + __pyx_tuple__11 = PyTuple_Pack(12, __pyx_n_s_X, __pyx_n_s_n_samples, __pyx_n_s_n_features, __pyx_n_s_X_data, __pyx_n_s_X_indices, __pyx_n_s_i, __pyx_n_s_non_zero, __pyx_n_s_col_ind, __pyx_n_s_diff, __pyx_n_s_means, __pyx_n_s_variances, __pyx_n_s_counts); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__11); + __Pyx_GIVEREF(__pyx_tuple__11); + __pyx_codeobj__12 = (PyObject*)__Pyx_PyCode_New(1, 0, 12, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__11, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_files_work_opensource_scikit_le, __pyx_n_s_csr_mean_variance_axis0, 51, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/sparsefuncs_fast.pyx":114 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csc_mean_variance_axis0(X): # <<<<<<<<<<<<<< + * """Compute mean and variance along axis 0 on a CSC matrix + * + */ + __pyx_tuple__13 = PyTuple_Pack(14, __pyx_n_s_X, __pyx_n_s_n_samples, __pyx_n_s_n_features, __pyx_n_s_X_data, __pyx_n_s_X_indices, __pyx_n_s_X_indptr, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_counts, __pyx_n_s_startptr, __pyx_n_s_endptr, __pyx_n_s_diff, __pyx_n_s_means, __pyx_n_s_variances); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__13); + __Pyx_GIVEREF(__pyx_tuple__13); + __pyx_codeobj__14 = (PyObject*)__Pyx_PyCode_New(1, 0, 14, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__13, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_files_work_opensource_scikit_le, __pyx_n_s_csc_mean_variance_axis0, 114, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/sparsefuncs_fast.pyx":177 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def inplace_csr_row_normalize_l1(X): # <<<<<<<<<<<<<< + * """Inplace row normalize using the l1 norm""" + * cdef unsigned int n_samples = X.shape[0] + */ + __pyx_tuple__15 = PyTuple_Pack(9, __pyx_n_s_X, __pyx_n_s_n_samples, __pyx_n_s_n_features, __pyx_n_s_X_data, __pyx_n_s_X_indices, __pyx_n_s_X_indptr, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_sum); if (unlikely(!__pyx_tuple__15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__15); + __Pyx_GIVEREF(__pyx_tuple__15); + __pyx_codeobj__16 = (PyObject*)__Pyx_PyCode_New(1, 0, 9, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__15, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_files_work_opensource_scikit_le, __pyx_n_s_inplace_csr_row_normalize_l1, 177, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/sparsefuncs_fast.pyx":212 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def inplace_csr_row_normalize_l2(X): # <<<<<<<<<<<<<< + * """Inplace row normalize using the l2 norm""" + * cdef unsigned int n_samples = X.shape[0] + */ + __pyx_tuple__17 = PyTuple_Pack(9, __pyx_n_s_X, __pyx_n_s_n_samples, __pyx_n_s_n_features, __pyx_n_s_X_data, __pyx_n_s_X_indices, __pyx_n_s_X_indptr, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_sum); if (unlikely(!__pyx_tuple__17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__17); + __Pyx_GIVEREF(__pyx_tuple__17); + __pyx_codeobj__18 = (PyObject*)__Pyx_PyCode_New(1, 0, 9, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__17, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_files_work_opensource_scikit_le, __pyx_n_s_inplace_csr_row_normalize_l2, 212, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/sparsefuncs_fast.pyx":261 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def assign_rows_csr(X, # <<<<<<<<<<<<<< + * np.ndarray[np.npy_intp, ndim=1] X_rows, + * np.ndarray[np.npy_intp, ndim=1] out_rows, + */ + __pyx_tuple__19 = PyTuple_Pack(11, __pyx_n_s_X, __pyx_n_s_X_rows, __pyx_n_s_out_rows, __pyx_n_s_out, __pyx_n_s_i, __pyx_n_s_ind, __pyx_n_s_j, __pyx_n_s_rX, __pyx_n_s_data, __pyx_n_s_indices, __pyx_n_s_indptr); if (unlikely(!__pyx_tuple__19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__19); + __Pyx_GIVEREF(__pyx_tuple__19); + __pyx_codeobj__20 = (PyObject*)__Pyx_PyCode_New(4, 0, 11, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__19, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_files_work_opensource_scikit_le, __pyx_n_s_assign_rows_csr, 261, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_float_0_ = PyFloat_FromDouble(0.); if (unlikely(!__pyx_float_0_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC initsparsefuncs_fast(void); /*proto*/ +PyMODINIT_FUNC initsparsefuncs_fast(void) +#else +PyMODINIT_FUNC PyInit_sparsefuncs_fast(void); /*proto*/ +PyMODINIT_FUNC PyInit_sparsefuncs_fast(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_sparsefuncs_fast(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("sparsefuncs_fast"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + if (__pyx_module_is_main_sklearn__utils__sparsefuncs_fast) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.utils.sparsefuncs_fast")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.utils.sparsefuncs_fast", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + } + #endif + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + if (__Pyx_ExportFunction("add_row_csr", (void (*)(void))__pyx_f_7sklearn_5utils_16sparsefuncs_fast_add_row_csr, "void (PyArrayObject *, PyArrayObject *, PyArrayObject *, int, PyArrayObject *)") < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Type init code ---*/ + /*--- Type import code ---*/ + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/utils/sparsefuncs_fast.pyx":10 + * from libc.math cimport fabs, sqrt + * cimport numpy as np + * import numpy as np # <<<<<<<<<<<<<< + * import scipy.sparse as sp + * cimport cython + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":11 + * cimport numpy as np + * import numpy as np + * import scipy.sparse as sp # <<<<<<<<<<<<<< + * cimport cython + * + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s__8); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s__8); + __Pyx_GIVEREF(__pyx_n_s__8); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_scipy_sparse, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_sp, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":14 + * cimport cython + * + * np.import_array() # <<<<<<<<<<<<<< + * + * + */ + import_array(); + + /* "sklearn/utils/sparsefuncs_fast.pyx":23 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csr_row_norms(X): # <<<<<<<<<<<<<< + * """L2 norm of each row in CSR matrix X.""" + * cdef: + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_1csr_row_norms, NULL, __pyx_n_s_sklearn_utils_sparsefuncs_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_csr_row_norms, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":51 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csr_mean_variance_axis0(X): # <<<<<<<<<<<<<< + * """Compute mean and variance along axis 0 on a CSR matrix + * + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_3csr_mean_variance_axis0, NULL, __pyx_n_s_sklearn_utils_sparsefuncs_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_csr_mean_variance_axis0, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":114 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def csc_mean_variance_axis0(X): # <<<<<<<<<<<<<< + * """Compute mean and variance along axis 0 on a CSC matrix + * + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_5csc_mean_variance_axis0, NULL, __pyx_n_s_sklearn_utils_sparsefuncs_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_csc_mean_variance_axis0, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":177 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def inplace_csr_row_normalize_l1(X): # <<<<<<<<<<<<<< + * """Inplace row normalize using the l1 norm""" + * cdef unsigned int n_samples = X.shape[0] + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_7inplace_csr_row_normalize_l1, NULL, __pyx_n_s_sklearn_utils_sparsefuncs_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_inplace_csr_row_normalize_l1, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":212 + * @cython.wraparound(False) + * @cython.cdivision(True) + * def inplace_csr_row_normalize_l2(X): # <<<<<<<<<<<<<< + * """Inplace row normalize using the l2 norm""" + * cdef unsigned int n_samples = X.shape[0] + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_9inplace_csr_row_normalize_l2, NULL, __pyx_n_s_sklearn_utils_sparsefuncs_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_inplace_csr_row_normalize_l2, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":261 + * @cython.boundscheck(False) + * @cython.wraparound(False) + * def assign_rows_csr(X, # <<<<<<<<<<<<<< + * np.ndarray[np.npy_intp, ndim=1] X_rows, + * np.ndarray[np.npy_intp, ndim=1] out_rows, + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_16sparsefuncs_fast_11assign_rows_csr, NULL, __pyx_n_s_sklearn_utils_sparsefuncs_fast); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_assign_rows_csr, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/sparsefuncs_fast.pyx":1 + * # Authors: Mathieu Blondel # <<<<<<<<<<<<<< + * # Olivier Grisel + * # Peter Prettenhofer + */ + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "/usr/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.utils.sparsefuncs_fast", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.utils.sparsefuncs_fast"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck) { +#if CYTHON_COMPILING_IN_CPYTHON + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; /* Consume from buffer string */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; /* not a 'break' in the loop */ + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case '\r': + case '\n': + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; + } + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON + result = PyDict_GetItem(__pyx_d, name); + if (result) { + Py_INCREF(result); + } else { +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); +#endif + result = __Pyx_GetBuiltinName(name); + } + return result; +} + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; +#endif + result = (*call)(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + Py_LeaveRecursiveCall(); +#endif + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +static void __Pyx_RaiseBufferFallbackError(void) { + PyErr_SetString(PyExc_ValueError, + "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, + int full_traceback) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + if (full_traceback) { + Py_XINCREF(old_exc); + Py_XINCREF(old_val); + Py_XINCREF(old_tb); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + PyErr_PrintEx(1); + } + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); +} +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (none_allowed && obj == Py_None) return 1; + else if (exact) { + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(PyObject_TypeCheck(obj, type))) return 1; + } + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); + return 0; +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { + #endif +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } +#if PY_VERSION_HEX >= 0x03030000 + if (cause) { +#else + if (cause && cause != Py_None) { +#endif + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +static CYTHON_INLINE int __Pyx_PyObject_SetSlice( + PyObject* obj, PyObject* value, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { +#if CYTHON_COMPILING_IN_CPYTHON + PyMappingMethods* mp; +#if PY_MAJOR_VERSION < 3 + PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; + if (likely(ms && ms->sq_ass_slice)) { + if (!has_cstart) { + if (_py_start && (*_py_start != Py_None)) { + cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); + if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstart = 0; + } + if (!has_cstop) { + if (_py_stop && (*_py_stop != Py_None)) { + cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); + if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstop = PY_SSIZE_T_MAX; + } + if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { + Py_ssize_t l = ms->sq_length(obj); + if (likely(l >= 0)) { + if (cstop < 0) { + cstop += l; + if (cstop < 0) cstop = 0; + } + if (cstart < 0) { + cstart += l; + if (cstart < 0) cstart = 0; + } + } else { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + goto bad; + } + } + return ms->sq_ass_slice(obj, cstart, cstop, value); + } +#endif + mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_ass_subscript)) +#endif + { + int result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyInt_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyInt_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_COMPILING_IN_CPYTHON + result = mp->mp_ass_subscript(obj, py_slice, value); +#else + result = value ? PyObject_SetItem(obj, py_slice, value) : PyObject_DelItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } + PyErr_Format(PyExc_TypeError, + "'%.200s' object does not support slice %.10s", + Py_TYPE(obj)->tp_name, value ? "assignment" : "deletion"); +bad: + return -1; +} + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } + } + #endif + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: + Py_DECREF(obj); + view->obj = NULL; +} +#endif /* PY_MAJOR_VERSION < 3 */ + + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + #if PY_VERSION_HEX < 0x03030000 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); + } +} + +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \ + { \ + func_type value = func(x); \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + PyErr_SetString(PyExc_OverflowError, \ + (is_unsigned && unlikely(value < zero)) ? \ + "can't convert negative value to " #target_type : \ + "value too large to convert to " #target_type); \ + return (target_type) -1; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) { + const unsigned int neg_one = (unsigned int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(unsigned int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned int"); + return (unsigned int) -1; + } + return (unsigned int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (unsigned int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned int"); + return (unsigned int) -1; + } + if (sizeof(unsigned int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(unsigned int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(unsigned int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(unsigned int) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(unsigned int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(unsigned int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long, PyLong_AsLong) + } else if (sizeof(unsigned int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(unsigned int, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + unsigned int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (unsigned int) -1; + } + } else { + unsigned int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned int) -1; + val = __Pyx_PyInt_As_unsigned_int(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value) { + const unsigned int neg_one = (unsigned int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(unsigned int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(unsigned int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(unsigned int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(unsigned int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(unsigned int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(unsigned int), + little, !is_unsigned); + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *x) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; + } + return (Py_intptr_t) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(Py_intptr_t)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to Py_intptr_t"); + return (Py_intptr_t) -1; + } + if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(Py_intptr_t)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(Py_intptr_t) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(Py_intptr_t) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyLong_AsLong) + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(Py_intptr_t, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + Py_intptr_t val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (Py_intptr_t) -1; + } + } else { + Py_intptr_t val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (Py_intptr_t) -1; + val = __Pyx_PyInt_As_Py_intptr_t(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } +} + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(int) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(Py_intptr_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); + } +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; + } + return (long) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; + } + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); + Py_DECREF(tmp); + return val; + } +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(__pyx_m, (char *)"__pyx_capi__"); + if (!d) { + PyErr_Clear(); + d = PyDict_New(); + if (!d) + goto bad; + Py_INCREF(d); + if (PyModule_AddObject(__pyx_m, (char *)"__pyx_capi__", d) < 0) + goto bad; + } + tmp.fp = f; +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + cobj = PyCapsule_New(tmp.p, sig, 0); +#else + cobj = PyCObject_FromVoidPtrAndDesc(tmp.p, (void *)sig, 0); +#endif + if (!cobj) + goto bad; + if (PyDict_SetItemString(d, name, cobj) < 0) + goto bad; + Py_DECREF(cobj); + Py_DECREF(d); + return 0; +bad: + Py_XDECREF(cobj); + Py_XDECREF(d); + return -1; +} + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + #if PY_VERSION_HEX < 0x02050000 + if (PyErr_Warn(NULL, warning) < 0) goto bad; + #else + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + #endif + } + else if ((size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ +#if !CYTHON_COMPILING_IN_PYPY +#if PY_VERSION_HEX >= 0x02060000 + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_MAJOR_VERSION < 3 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%.4s__ returned non-%.4s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + #if PY_VERSION_HEX < 0x02060000 + return PyInt_AsSsize_t(b); + #else + return PyLong_AsSsize_t(b); + #endif + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/utils/sparsefuncs_fast.pxd b/sklearn/utils/sparsefuncs_fast.pxd new file mode 100644 index 0000000000000..f1a5455f64255 --- /dev/null +++ b/sklearn/utils/sparsefuncs_fast.pxd @@ -0,0 +1,8 @@ +cimport numpy as np + + +cdef void add_row_csr(np.ndarray[np.float64_t, ndim=1], + np.ndarray[int, ndim=1], + np.ndarray[int, ndim=1], + int i, np.ndarray[np.float64_t, ndim=1, mode="c"]) + diff --git a/sklearn/utils/sparsefuncs_fast.pyx b/sklearn/utils/sparsefuncs_fast.pyx new file mode 100644 index 0000000000000..b85488f5320e0 --- /dev/null +++ b/sklearn/utils/sparsefuncs_fast.pyx @@ -0,0 +1,296 @@ +# Authors: Mathieu Blondel +# Olivier Grisel +# Peter Prettenhofer +# Lars Buitinck +# +# Licence: BSD 3 clause + +from libc.math cimport fabs, sqrt +cimport numpy as np +import numpy as np +import scipy.sparse as sp +cimport cython + +np.import_array() + + +ctypedef np.float64_t DOUBLE + + +@cython.boundscheck(False) +@cython.wraparound(False) +@cython.cdivision(True) +def csr_row_norms(X): + """L2 norm of each row in CSR matrix X.""" + cdef: + unsigned int n_samples = X.shape[0] + unsigned int n_features = X.shape[1] + np.ndarray[DOUBLE, ndim=1, mode="c"] norms + np.ndarray[DOUBLE, ndim=1, mode="c"] data + np.ndarray[int, ndim=1, mode="c"] indices = X.indices + np.ndarray[int, ndim=1, mode="c"] indptr = X.indptr + + np.npy_intp i, j + double sum_ + + norms = np.zeros(n_samples, dtype=np.float64) + data = np.asarray(X.data, dtype=np.float64) # might copy! + + for i in range(n_samples): + sum_ = 0.0 + for j in range(indptr[i], indptr[i + 1]): + sum_ += data[j] * data[j] + norms[i] = sum_ + + return norms + + +@cython.boundscheck(False) +@cython.wraparound(False) +@cython.cdivision(True) +def csr_mean_variance_axis0(X): + """Compute mean and variance along axis 0 on a CSR matrix + + Parameters + ---------- + X: CSR sparse matrix, shape (n_samples, n_features) + Input data. + + Returns + ------- + + means: float array with shape (n_features,) + Feature-wise means + + variances: float array with shape (n_features,) + Feature-wise variances + + """ + cdef unsigned int n_samples = X.shape[0] + cdef unsigned int n_features = X.shape[1] + + cdef np.ndarray[DOUBLE, ndim=1, mode="c"] X_data + X_data = np.asarray(X.data, dtype=np.float64) # might copy! + cdef np.ndarray[int, ndim=1] X_indices = X.indices + + cdef unsigned int i + cdef unsigned int non_zero = X_indices.shape[0] + cdef unsigned int col_ind + cdef double diff + + # means[j] contains the mean of feature j + cdef np.ndarray[DOUBLE, ndim=1] means = np.zeros(n_features, + dtype=np.float64) + + # variances[j] contains the variance of feature j + cdef np.ndarray[DOUBLE, ndim=1] variances = np.zeros_like(means) + + # counts[j] contains the number of samples where feature j is non-zero + cdef np.ndarray[int, ndim=1] counts = np.zeros(n_features, + dtype=np.int32) + + for i in xrange(non_zero): + col_ind = X_indices[i] + means[col_ind] += X_data[i] + + means /= n_samples + + for i in xrange(non_zero): + col_ind = X_indices[i] + diff = X_data[i] - means[col_ind] + variances[col_ind] += diff * diff + counts[col_ind] += 1 + + for i in xrange(n_features): + variances[i] += (n_samples - counts[i]) * means[i] ** 2 + variances[i] /= n_samples + + return means, variances + + +@cython.boundscheck(False) +@cython.wraparound(False) +@cython.cdivision(True) +def csc_mean_variance_axis0(X): + """Compute mean and variance along axis 0 on a CSC matrix + + Parameters + ---------- + X: CSC sparse matrix, shape (n_samples, n_features) + Input data. + + Returns + ------- + + means: float array with shape (n_features,) + Feature-wise means + + variances: float array with shape (n_features,) + Feature-wise variances + + """ + cdef unsigned int n_samples = X.shape[0] + cdef unsigned int n_features = X.shape[1] + + cdef np.ndarray[DOUBLE, ndim=1] X_data + X_data = np.asarray(X.data, dtype=np.float64) # might copy! + cdef np.ndarray[int, ndim=1] X_indices = X.indices + cdef np.ndarray[int, ndim=1] X_indptr = X.indptr + + cdef unsigned int i + cdef unsigned int j + cdef unsigned int counts + cdef unsigned int startptr + cdef unsigned int endptr + cdef double diff + + # means[j] contains the mean of feature j + cdef np.ndarray[DOUBLE, ndim=1] means = np.zeros(n_features, + dtype=np.float64) + + # variances[j] contains the variance of feature j + cdef np.ndarray[DOUBLE, ndim=1] variances = np.zeros_like(means) + + for i in xrange(n_features): + + startptr = X_indptr[i] + endptr = X_indptr[i + 1] + counts = endptr - startptr + + for j in xrange(startptr, endptr): + means[i] += X_data[j] + means[i] /= n_samples + + for j in xrange(startptr, endptr): + diff = X_data[j] - means[i] + variances[i] += diff * diff + + variances[i] += (n_samples - counts) * means[i] * means[i] + variances[i] /= n_samples + + return means, variances + + +@cython.boundscheck(False) +@cython.wraparound(False) +@cython.cdivision(True) +def inplace_csr_row_normalize_l1(X): + """Inplace row normalize using the l1 norm""" + cdef unsigned int n_samples = X.shape[0] + cdef unsigned int n_features = X.shape[1] + + cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data + cdef np.ndarray[int, ndim=1] X_indices = X.indices + cdef np.ndarray[int, ndim=1] X_indptr = X.indptr + + # the column indices for row i are stored in: + # indices[indptr[i]:indices[i+1]] + # and their corresponding values are stored in: + # data[indptr[i]:indptr[i+1]] + cdef unsigned int i + cdef unsigned int j + cdef double sum_ + + for i in xrange(n_samples): + sum_ = 0.0 + + for j in xrange(X_indptr[i], X_indptr[i + 1]): + sum_ += fabs(X_data[j]) + + if sum_ == 0.0: + # do not normalize empty rows (can happen if CSR is not pruned + # correctly) + continue + + for j in xrange(X_indptr[i], X_indptr[i + 1]): + X_data[j] /= sum_ + + +@cython.boundscheck(False) +@cython.wraparound(False) +@cython.cdivision(True) +def inplace_csr_row_normalize_l2(X): + """Inplace row normalize using the l2 norm""" + cdef unsigned int n_samples = X.shape[0] + cdef unsigned int n_features = X.shape[1] + + cdef np.ndarray[DOUBLE, ndim=1] X_data = X.data + cdef np.ndarray[int, ndim=1] X_indices = X.indices + cdef np.ndarray[int, ndim=1] X_indptr = X.indptr + + cdef unsigned int i + cdef unsigned int j + cdef double sum_ + + for i in xrange(n_samples): + sum_ = 0.0 + + for j in xrange(X_indptr[i], X_indptr[i + 1]): + sum_ += (X_data[j] * X_data[j]) + + if sum_ == 0.0: + # do not normalize empty rows (can happen if CSR is not pruned + # correctly) + continue + + sum_ = sqrt(sum_) + + for j in xrange(X_indptr[i], X_indptr[i + 1]): + X_data[j] /= sum_ + + +@cython.boundscheck(False) +@cython.wraparound(False) +cdef void add_row_csr(np.ndarray[np.float64_t, ndim=1] data, + np.ndarray[int, ndim=1] indices, + np.ndarray[int, ndim=1] indptr, + int i, np.ndarray[np.float64_t, ndim=1, mode="c"] out): + """Add row i of CSR matrix (data, indices, indptr) to array out. + + Equivalent to out += X[i].toarray(). Returns None. + """ + cdef int ind, j + + for ind in range(indptr[i], indptr[i + 1]): + j = indices[ind] + out[j] += data[ind] + + +@cython.boundscheck(False) +@cython.wraparound(False) +def assign_rows_csr(X, + np.ndarray[np.npy_intp, ndim=1] X_rows, + np.ndarray[np.npy_intp, ndim=1] out_rows, + np.ndarray[np.float64_t, ndim=2, mode="c"] out): + """Densify selected rows of a CSR matrix into a preallocated array. + + Like out[out_rows] = X[X_rows].toarray() but without copying. + Only supported for dtype=np.float64. + + Parameters + ---------- + X : scipy.sparse.csr_matrix, shape=(n_samples, n_features) + X_rows : array, dtype=np.intp, shape=n_rows + out_rows : array, dtype=np.intp, shape=n_rows + out : array, shape=(arbitrary, n_features) + """ + cdef: + # npy_intp (np.intp in Python) is what np.where returns, + # but int is what scipy.sparse uses. + int i, ind, j + np.npy_intp rX + np.ndarray[DOUBLE, ndim=1] data = X.data + np.ndarray[int, ndim=1] indices = X.indices, indptr = X.indptr + + if X_rows.shape[0] != out_rows.shape[0]: + raise ValueError("cannot assign %d rows to %d" + % (X_rows.shape[0], out_rows.shape[0])) + + out[:] = 0. + for i in range(X_rows.shape[0]): + # XXX we could reuse add_row_csr here, but the array slice + # is not optimized away. + rX = X_rows[i] + for ind in range(indptr[rX], indptr[rX + 1]): + j = indices[ind] + out[out_rows[i], j] = data[ind] diff --git a/sklearn/utils/sparsetools/README b/sklearn/utils/sparsetools/README index e11ef3d97b7c9..ae03f7de3cf65 100644 --- a/sklearn/utils/sparsetools/README +++ b/sklearn/utils/sparsetools/README @@ -1,3 +1 @@ -This directory is backported from scipy 0.9: -scipy.sparse.sparsetools - +Backport of SciPy 0.13 code. diff --git a/sklearn/utils/sparsetools/__init__.py b/sklearn/utils/sparsetools/__init__.py index 0a80b0dc2e304..3a5c30036a1c2 100644 --- a/sklearn/utils/sparsetools/__init__.py +++ b/sklearn/utils/sparsetools/__init__.py @@ -1,3 +1,5 @@ """sparsetools - a collection of routines for sparse matrix operations""" -from .csgraph import cs_graph_components +from ._traversal import connected_components + +__all__ = ["connected_components"] diff --git a/sklearn/utils/sparsetools/_graph_tools.c b/sklearn/utils/sparsetools/_graph_tools.c new file mode 100644 index 0000000000000..618f8fe1744fe --- /dev/null +++ b/sklearn/utils/sparsetools/_graph_tools.c @@ -0,0 +1,9879 @@ +/* Generated by Cython 0.16 on Thu May 23 12:47:48 2013 */ + +#define PY_SSIZE_T_CLEAN +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif + +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif + +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif + +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif + +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif + +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif + +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyCFunction_Call PyObject_Call +#else + #define __Pyx_PyCFunction_Call PyCFunction_Call +#endif + +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) + #define PyNumber_Index(o) PyNumber_Int(o) + #define PyIndex_Check(o) PyNumber_Check(o) + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" +#endif + +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif + +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif + +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif + +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif + +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif + + +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_GET_LENGTH) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) +#endif + +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif + +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif + +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif + +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) + +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask +#endif + +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif + +#if PY_VERSION_HEX < 0x03020000 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif + +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif + +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif + +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif + +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__utils___graph_tools +#define __PYX_HAVE_API__sklearn__utils___graph_tools +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + + +/* inline attribute */ +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* unused attribute */ +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif + +typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + + +/* Type Conversion Predeclarations */ + +#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) +#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) + +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); + +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); + +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) + +#ifdef __GNUC__ + /* Test for GCC > 2.95 */ + #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) + #else /* __GNUC__ > 2 ... */ + #define likely(x) (x) + #define unlikely(x) (x) + #endif /* __GNUC__ > 2 ... */ +#else /* __GNUC__ */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "_graph_tools.pyx", + "numpy.pxd", +}; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + + +/* "numpy.pxd":722 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "numpy.pxd":723 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "numpy.pxd":724 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "numpy.pxd":725 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "numpy.pxd":729 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "numpy.pxd":730 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "numpy.pxd":731 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "numpy.pxd":732 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "numpy.pxd":736 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "numpy.pxd":737 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "numpy.pxd":746 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "numpy.pxd":747 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "numpy.pxd":748 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "numpy.pxd":750 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "numpy.pxd":751 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "numpy.pxd":752 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "numpy.pxd":754 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "numpy.pxd":755 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "numpy.pxd":757 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "numpy.pxd":758 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "numpy.pxd":759 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; + +/* "sklearn/utils/_graph_tools.pyx":15 + * + * DTYPE = np.float64 + * ctypedef np.float64_t DTYPE_t # <<<<<<<<<<<<<< + * + * ITYPE = np.int32 + */ +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t; + +/* "sklearn/utils/_graph_tools.pyx":18 + * + * ITYPE = np.int32 + * ctypedef np.int32_t ITYPE_t # <<<<<<<<<<<<<< + * + * # EPS is the precision of DTYPE + */ +typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ + +/* "numpy.pxd":761 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "numpy.pxd":762 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "numpy.pxd":763 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "numpy.pxd":765 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +#define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_List_Fast(o, i) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { + if (likely(o != Py_None)) { + if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { + PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); + Py_INCREF(r); + return r; + } + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} +#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, i) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { + if (likely(o != Py_None)) { + if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { + PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); + Py_INCREF(r); + return r; + } + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} +#define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Fast(o, i) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { + if (PyList_CheckExact(o)) { + Py_ssize_t n = (likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if (likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = (likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if (likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (likely(i >= 0)) { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + return m->sq_item(o, i); + } + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +static void __Pyx_RaiseBufferIndexError(int axis); /*proto*/ + +#define __Pyx_BufPtrCContig1d(type, buf, i0, s0) ((type)buf + i0) +#define __Pyx_BufPtrCContig2d(type, buf, i0, s0, i1, s1) ((type)((char*)buf + i0 * s0) + i1) +#define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ + +static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name); + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); + +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); + +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); + +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); + +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); + +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); + +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); + +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename); /*proto*/ + +static int __Pyx_check_binary_version(void); + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'sklearn.utils._graph_tools' */ +static __pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t __pyx_v_7sklearn_5utils_12_graph_tools_DTYPE_EPS; +static __pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t __pyx_v_7sklearn_5utils_12_graph_tools_NULL_IDX; +static void __pyx_f_7sklearn_5utils_12_graph_tools__populate_graph(PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, __pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t); /*proto*/ +static void __pyx_f_7sklearn_5utils_12_graph_tools__construct_dist_matrix(PyArrayObject *, PyArrayObject *, PyArrayObject *, int, __pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t = { "ITYPE_t", NULL, sizeof(__pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t), { 0 }, 0, 'I', IS_UNSIGNED(__pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t), 0 }; +#define __Pyx_MODULE_NAME "sklearn.utils._graph_tools" +int __pyx_module_is_main_sklearn__utils___graph_tools = 0; + +/* Implementation of 'sklearn.utils._graph_tools' */ +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_csgraph_from_masked(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_graph); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_2csgraph_masked_from_dense(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_graph, PyObject *__pyx_v_null_value, PyObject *__pyx_v_nan_null, PyObject *__pyx_v_infinity_null, PyObject *__pyx_v_copy); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_4csgraph_from_dense(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_graph, PyObject *__pyx_v_null_value, PyObject *__pyx_v_nan_null, PyObject *__pyx_v_infinity_null); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_6csgraph_to_dense(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_null_value); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_8csgraph_to_masked(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_10reconstruct_path(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_predecessors, PyObject *__pyx_v_directed); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_12construct_dist_matrix(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_graph, PyObject *__pyx_v_predecessors, PyObject *__pyx_v_directed, PyObject *__pyx_v_null_value); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static char __pyx_k_1[] = "graph should have two dimensions"; +static char __pyx_k_3[] = "graph should be a square array"; +static char __pyx_k_13[] = "csgraph_masked_from_dense"; +static char __pyx_k_14[] = "csgraph must be lil, csr, or csc format"; +static char __pyx_k_16[] = "csgraph should be a square matrix"; +static char __pyx_k_21[] = "graph and predecessors must have the same shape"; +static char __pyx_k_23[] = "ndarray is not C contiguous"; +static char __pyx_k_25[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_27[] = "Non-native byte order not supported"; +static char __pyx_k_29[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_30[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_33[] = "Format string allocated too short."; +static char __pyx_k_35[] = "\nTools and utilities for working with compressed sparse graphs\n"; +static char __pyx_k_36[] = "scipy.sparse"; +static char __pyx_k_39[] = "/home/x006/Code/scikit-learn/sklearn/utils/_graph_tools.pyx"; +static char __pyx_k_40[] = "sklearn.utils._graph_tools"; +static char __pyx_k_53[] = "construct_dist_matrix"; +static char __pyx_k_54[] = "csgraph_to_dense (line 172)"; +static char __pyx_k_55[] = "\n csgraph_to_dense(csgraph, null_value=0)\n\n Convert a sparse graph representation to a dense representation\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n csgraph : csr_matrix, csc_matrix, or lil_matrix\n Sparse representation of a graph.\n null_value : float, optional\n The value used to indicate null edges in the dense representation.\n Default is 0.\n\n Returns\n -------\n graph : ndarray\n The dense representation of the sparse graph.\n\n Notes\n -----\n For normal sparse graph representations, calling csgraph_to_dense with\n null_value=0 produces an equivalent result to using dense format\n conversions in the main sparse package. When the sparse representations\n have repeated values, however, the results will differ. The tools in\n scipy.sparse will add repeating values to obtain a final value. This\n function will select the minimum among repeating values to obtain a\n final value. For example, here we'll create a two-node directed sparse\n graph with multiple edges from node 0 to node 1, of weights 2 and 3.\n This illustrates the difference in behavior:\n\n >>> from scipy.sparse import csr_matrix\n >>> data = np.array([2, 3])\n >>> indices = np.array([1, 1])\n >>> indptr = np.array([0, 2, 2])\n >>> M = csr_matrix((data, indices, indptr), shape=(2, 2))\n >>> M.toarray()\n array([[0, 5],\n [0, 0]])\n >>> csgraph_to_dense(M)\n array([[0, 2],\n [0, 0]])\n\n The reason for this difference is to allow a compressed sparse graph to\n represent multiple edges between any two nodes. As most sparse graph\n algorithms are concerned with the single lowest-cost edge between any\n two nodes, the default scipy.sparse behavior of summming multiple weights\n does not make sense in this context.\n\n The other reason for using this routine is to allow for graphs with\n zero-weight edges. Let's look at"" the example of a two-node directed\n graph, connected by an edge of weight zero:\n\n >>> from scipy.sparse import csr_matrix\n >>> data = np.array([0.0])\n >>> indices = np.array([1])\n >>> indptr = np.array([0, 2, 2])\n >>> M = csr_matrix((data, indices, indptr), shape=(2, 2))\n >>> M.toarray()\n array([[0, 0],\n [0, 0]])\n >>> csgraph_to_dense(M, np.inf)\n array([[ Inf, 0.],\n [ Inf, Inf]])\n\n In the first case, the zero-weight edge gets lost in the dense\n representation. In the second case, we can choose a different null value\n and see the true form of the graph.\n "; +static char __pyx_k__B[] = "B"; +static char __pyx_k__C[] = "C"; +static char __pyx_k__H[] = "H"; +static char __pyx_k__I[] = "I"; +static char __pyx_k__L[] = "L"; +static char __pyx_k__N[] = "N"; +static char __pyx_k__O[] = "O"; +static char __pyx_k__Q[] = "Q"; +static char __pyx_k__b[] = "b"; +static char __pyx_k__c[] = "c"; +static char __pyx_k__d[] = "d"; +static char __pyx_k__f[] = "f"; +static char __pyx_k__g[] = "g"; +static char __pyx_k__h[] = "h"; +static char __pyx_k__i[] = "i"; +static char __pyx_k__l[] = "l"; +static char __pyx_k__q[] = "q"; +static char __pyx_k__Zd[] = "Zd"; +static char __pyx_k__Zf[] = "Zf"; +static char __pyx_k__Zg[] = "Zg"; +static char __pyx_k__ma[] = "ma"; +static char __pyx_k__np[] = "np"; +static char __pyx_k__inf[] = "inf"; +static char __pyx_k__nan[] = "nan"; +static char __pyx_k__sum[] = "sum"; +static char __pyx_k__bool[] = "bool"; +static char __pyx_k__copy[] = "copy"; +static char __pyx_k__data[] = "data"; +static char __pyx_k__fill[] = "fill"; +static char __pyx_k__mask[] = "mask"; +static char __pyx_k__ndim[] = "ndim"; +static char __pyx_k__ones[] = "ones"; +static char __pyx_k__pind[] = "pind"; +static char __pyx_k__DTYPE[] = "DTYPE"; +static char __pyx_k__ITYPE[] = "ITYPE"; +static char __pyx_k__array[] = "array"; +static char __pyx_k__data1[] = "data1"; +static char __pyx_k__data2[] = "data2"; +static char __pyx_k__dtype[] = "dtype"; +static char __pyx_k__empty[] = "empty"; +static char __pyx_k__graph[] = "graph"; +static char __pyx_k__int32[] = "int32"; +static char __pyx_k__isinf[] = "isinf"; +static char __pyx_k__isnan[] = "isnan"; +static char __pyx_k__nnull[] = "nnull"; +static char __pyx_k__numpy[] = "numpy"; +static char __pyx_k__order[] = "order"; +static char __pyx_k__range[] = "range"; +static char __pyx_k__ravel[] = "ravel"; +static char __pyx_k__shape[] = "shape"; +static char __pyx_k__tocsr[] = "tocsr"; +static char __pyx_k__zeros[] = "zeros"; +static char __pyx_k__arange[] = "arange"; +static char __pyx_k__astype[] = "astype"; +static char __pyx_k__cumsum[] = "cumsum"; +static char __pyx_k__indptr[] = "indptr"; +static char __pyx_k__argsort[] = "argsort"; +static char __pyx_k__asarray[] = "asarray"; +static char __pyx_k__csgraph[] = "csgraph"; +static char __pyx_k__float64[] = "float64"; +static char __pyx_k__indices[] = "indices"; +static char __pyx_k__minimum[] = "minimum"; +static char __pyx_k____main__[] = "__main__"; +static char __pyx_k____test__[] = "__test__"; +static char __pyx_k__directed[] = "directed"; +static char __pyx_k__idx_grid[] = "idx_grid"; +static char __pyx_k__nan_null[] = "nan_null"; +static char __pyx_k__is_masked[] = "is_masked"; +static char __pyx_k__ValueError[] = "ValueError"; +static char __pyx_k__compressed[] = "compressed"; +static char __pyx_k__csr_matrix[] = "csr_matrix"; +static char __pyx_k__csr_output[] = "csr_output"; +static char __pyx_k__isspmatrix[] = "isspmatrix"; +static char __pyx_k__null_value[] = "null_value"; +static char __pyx_k___validation[] = "_validation"; +static char __pyx_k__dist_matrix[] = "dist_matrix"; +static char __pyx_k__RuntimeError[] = "RuntimeError"; +static char __pyx_k__dense_output[] = "dense_output"; +static char __pyx_k__masked_array[] = "masked_array"; +static char __pyx_k__predecessors[] = "predecessors"; +static char __pyx_k__searchsorted[] = "searchsorted"; +static char __pyx_k__copy_if_dense[] = "copy_if_dense"; +static char __pyx_k__infinity_null[] = "infinity_null"; +static char __pyx_k__masked_values[] = "masked_values"; +static char __pyx_k__isspmatrix_csc[] = "isspmatrix_csc"; +static char __pyx_k__isspmatrix_csr[] = "isspmatrix_csr"; +static char __pyx_k__isspmatrix_lil[] = "isspmatrix_lil"; +static char __pyx_k__masked_invalid[] = "masked_invalid"; +static char __pyx_k__validate_graph[] = "validate_graph"; +static char __pyx_k__csgraph_to_dense[] = "csgraph_to_dense"; +static char __pyx_k__reconstruct_path[] = "reconstruct_path"; +static char __pyx_k__csgraph_to_masked[] = "csgraph_to_masked"; +static char __pyx_k__csgraph_from_dense[] = "csgraph_from_dense"; +static char __pyx_k__csgraph_from_masked[] = "csgraph_from_masked"; +static PyObject *__pyx_kp_s_1; +static PyObject *__pyx_n_s_13; +static PyObject *__pyx_kp_s_14; +static PyObject *__pyx_kp_s_16; +static PyObject *__pyx_kp_s_21; +static PyObject *__pyx_kp_u_23; +static PyObject *__pyx_kp_u_25; +static PyObject *__pyx_kp_u_27; +static PyObject *__pyx_kp_u_29; +static PyObject *__pyx_kp_s_3; +static PyObject *__pyx_kp_u_30; +static PyObject *__pyx_kp_u_33; +static PyObject *__pyx_n_s_36; +static PyObject *__pyx_kp_s_39; +static PyObject *__pyx_n_s_40; +static PyObject *__pyx_n_s_53; +static PyObject *__pyx_kp_u_54; +static PyObject *__pyx_kp_u_55; +static PyObject *__pyx_n_s__C; +static PyObject *__pyx_n_s__DTYPE; +static PyObject *__pyx_n_s__ITYPE; +static PyObject *__pyx_n_s__N; +static PyObject *__pyx_n_s__RuntimeError; +static PyObject *__pyx_n_s__ValueError; +static PyObject *__pyx_n_s____main__; +static PyObject *__pyx_n_s____test__; +static PyObject *__pyx_n_s___validation; +static PyObject *__pyx_n_s__arange; +static PyObject *__pyx_n_s__argsort; +static PyObject *__pyx_n_s__array; +static PyObject *__pyx_n_s__asarray; +static PyObject *__pyx_n_s__astype; +static PyObject *__pyx_n_s__bool; +static PyObject *__pyx_n_s__c; +static PyObject *__pyx_n_s__compressed; +static PyObject *__pyx_n_s__copy; +static PyObject *__pyx_n_s__copy_if_dense; +static PyObject *__pyx_n_s__csgraph; +static PyObject *__pyx_n_s__csgraph_from_dense; +static PyObject *__pyx_n_s__csgraph_from_masked; +static PyObject *__pyx_n_s__csgraph_to_dense; +static PyObject *__pyx_n_s__csgraph_to_masked; +static PyObject *__pyx_n_s__csr_matrix; +static PyObject *__pyx_n_s__csr_output; +static PyObject *__pyx_n_s__cumsum; +static PyObject *__pyx_n_s__data; +static PyObject *__pyx_n_s__data1; +static PyObject *__pyx_n_s__data2; +static PyObject *__pyx_n_s__dense_output; +static PyObject *__pyx_n_s__directed; +static PyObject *__pyx_n_s__dist_matrix; +static PyObject *__pyx_n_s__dtype; +static PyObject *__pyx_n_s__empty; +static PyObject *__pyx_n_s__fill; +static PyObject *__pyx_n_s__float64; +static PyObject *__pyx_n_s__graph; +static PyObject *__pyx_n_s__idx_grid; +static PyObject *__pyx_n_s__indices; +static PyObject *__pyx_n_s__indptr; +static PyObject *__pyx_n_s__inf; +static PyObject *__pyx_n_s__infinity_null; +static PyObject *__pyx_n_s__int32; +static PyObject *__pyx_n_s__is_masked; +static PyObject *__pyx_n_s__isinf; +static PyObject *__pyx_n_s__isnan; +static PyObject *__pyx_n_s__isspmatrix; +static PyObject *__pyx_n_s__isspmatrix_csc; +static PyObject *__pyx_n_s__isspmatrix_csr; +static PyObject *__pyx_n_s__isspmatrix_lil; +static PyObject *__pyx_n_s__ma; +static PyObject *__pyx_n_s__mask; +static PyObject *__pyx_n_s__masked_array; +static PyObject *__pyx_n_s__masked_invalid; +static PyObject *__pyx_n_s__masked_values; +static PyObject *__pyx_n_s__minimum; +static PyObject *__pyx_n_s__nan; +static PyObject *__pyx_n_s__nan_null; +static PyObject *__pyx_n_s__ndim; +static PyObject *__pyx_n_s__nnull; +static PyObject *__pyx_n_s__np; +static PyObject *__pyx_n_s__null_value; +static PyObject *__pyx_n_s__numpy; +static PyObject *__pyx_n_s__ones; +static PyObject *__pyx_n_s__order; +static PyObject *__pyx_n_s__pind; +static PyObject *__pyx_n_s__predecessors; +static PyObject *__pyx_n_s__range; +static PyObject *__pyx_n_s__ravel; +static PyObject *__pyx_n_s__reconstruct_path; +static PyObject *__pyx_n_s__searchsorted; +static PyObject *__pyx_n_s__shape; +static PyObject *__pyx_n_s__sum; +static PyObject *__pyx_n_s__tocsr; +static PyObject *__pyx_n_s__validate_graph; +static PyObject *__pyx_n_s__zeros; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_1; +static PyObject *__pyx_int_2; +static PyObject *__pyx_int_15; +static PyObject *__pyx_k_6; +static PyObject *__pyx_k_7; +static PyObject *__pyx_k_8; +static PyObject *__pyx_k_11; +static PyObject *__pyx_k_12; +static PyObject *__pyx_k_18; +static PyObject *__pyx_k_19; +static PyObject *__pyx_k_20; +static PyObject *__pyx_k_tuple_2; +static PyObject *__pyx_k_tuple_4; +static PyObject *__pyx_k_tuple_5; +static PyObject *__pyx_k_tuple_9; +static PyObject *__pyx_k_tuple_10; +static PyObject *__pyx_k_tuple_15; +static PyObject *__pyx_k_tuple_17; +static PyObject *__pyx_k_tuple_22; +static PyObject *__pyx_k_tuple_24; +static PyObject *__pyx_k_tuple_26; +static PyObject *__pyx_k_tuple_28; +static PyObject *__pyx_k_tuple_31; +static PyObject *__pyx_k_tuple_32; +static PyObject *__pyx_k_tuple_34; +static PyObject *__pyx_k_tuple_37; +static PyObject *__pyx_k_tuple_41; +static PyObject *__pyx_k_tuple_43; +static PyObject *__pyx_k_tuple_45; +static PyObject *__pyx_k_tuple_47; +static PyObject *__pyx_k_tuple_49; +static PyObject *__pyx_k_tuple_51; +static PyObject *__pyx_k_codeobj_38; +static PyObject *__pyx_k_codeobj_42; +static PyObject *__pyx_k_codeobj_44; +static PyObject *__pyx_k_codeobj_46; +static PyObject *__pyx_k_codeobj_48; +static PyObject *__pyx_k_codeobj_50; +static PyObject *__pyx_k_codeobj_52; + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_1csgraph_from_masked(PyObject *__pyx_self, PyObject *__pyx_v_graph); /*proto*/ +static char __pyx_doc_7sklearn_5utils_12_graph_tools_csgraph_from_masked[] = "\n csgraph_from_masked(graph)\n\n Construct a CSR-format graph from a masked array.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n graph : MaskedArray\n Input graph. Shape should be (n_nodes, n_nodes).\n\n Returns\n -------\n csgraph : csr_matrix\n Compressed sparse representation of graph, \n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_12_graph_tools_1csgraph_from_masked = {__Pyx_NAMESTR("csgraph_from_masked"), (PyCFunction)__pyx_pw_7sklearn_5utils_12_graph_tools_1csgraph_from_masked, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_12_graph_tools_csgraph_from_masked)}; +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_1csgraph_from_masked(PyObject *__pyx_self, PyObject *__pyx_v_graph) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("csgraph_from_masked (wrapper)", 0); + __pyx_self = __pyx_self; + __pyx_r = __pyx_pf_7sklearn_5utils_12_graph_tools_csgraph_from_masked(__pyx_self, ((PyObject *)__pyx_v_graph)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_graph_tools.pyx":26 + * cdef ITYPE_t NULL_IDX = -9999 + * + * def csgraph_from_masked(graph): # <<<<<<<<<<<<<< + * """ + * csgraph_from_masked(graph) + */ + +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_csgraph_from_masked(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_graph) { + PyObject *__pyx_v_N = NULL; + PyObject *__pyx_v_data = NULL; + PyObject *__pyx_v_mask = NULL; + PyObject *__pyx_v_idx_grid = NULL; + PyObject *__pyx_v_indices = NULL; + PyObject *__pyx_v_indptr = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("csgraph_from_masked", 0); + __Pyx_INCREF(__pyx_v_graph); + + /* "sklearn/utils/_graph_tools.pyx":45 + * """ + * # check that graph is a square matrix + * graph = np.ma.asarray(graph) # <<<<<<<<<<<<<< + * + * if graph.ndim != 2: + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__ma); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_graph); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_graph); + __Pyx_GIVEREF(__pyx_v_graph); + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_v_graph); + __pyx_v_graph = __pyx_t_3; + __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":47 + * graph = np.ma.asarray(graph) + * + * if graph.ndim != 2: # <<<<<<<<<<<<<< + * raise ValueError("graph should have two dimensions") + * N = graph.shape[0] + */ + __pyx_t_3 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyObject_RichCompare(__pyx_t_3, __pyx_int_2, Py_NE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_4) { + + /* "sklearn/utils/_graph_tools.pyx":48 + * + * if graph.ndim != 2: + * raise ValueError("graph should have two dimensions") # <<<<<<<<<<<<<< + * N = graph.shape[0] + * if graph.shape[1] != N: + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/utils/_graph_tools.pyx":49 + * if graph.ndim != 2: + * raise ValueError("graph should have two dimensions") + * N = graph.shape[0] # <<<<<<<<<<<<<< + * if graph.shape[1] != N: + * raise ValueError("graph should be a square array") + */ + __pyx_t_2 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_2, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_N = __pyx_t_3; + __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":50 + * raise ValueError("graph should have two dimensions") + * N = graph.shape[0] + * if graph.shape[1] != N: # <<<<<<<<<<<<<< + * raise ValueError("graph should be a square array") + * + */ + __pyx_t_3 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_3, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_RichCompare(__pyx_t_2, __pyx_v_N, Py_NE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 50; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_4) { + + /* "sklearn/utils/_graph_tools.pyx":51 + * N = graph.shape[0] + * if graph.shape[1] != N: + * raise ValueError("graph should be a square array") # <<<<<<<<<<<<<< + * + * # construct the csr matrix using graph and mask + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "sklearn/utils/_graph_tools.pyx":54 + * + * # construct the csr matrix using graph and mask + * if np.ma.is_masked(graph): # <<<<<<<<<<<<<< + * data = graph.compressed() + * mask = ~graph.mask + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__ma); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__is_masked); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_graph); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_graph); + __Pyx_GIVEREF(__pyx_v_graph); + __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_4) { + + /* "sklearn/utils/_graph_tools.pyx":55 + * # construct the csr matrix using graph and mask + * if np.ma.is_masked(graph): + * data = graph.compressed() # <<<<<<<<<<<<<< + * mask = ~graph.mask + * else: + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__compressed); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_data = __pyx_t_2; + __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":56 + * if np.ma.is_masked(graph): + * data = graph.compressed() + * mask = ~graph.mask # <<<<<<<<<<<<<< + * else: + * data = graph.data + */ + __pyx_t_2 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__mask); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyNumber_Invert(__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_mask = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L5; + } + /*else*/ { + + /* "sklearn/utils/_graph_tools.pyx":58 + * mask = ~graph.mask + * else: + * data = graph.data # <<<<<<<<<<<<<< + * mask = np.ones(graph.shape, dtype='bool') + * + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_data = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":59 + * else: + * data = graph.data + * mask = np.ones(graph.shape, dtype='bool') # <<<<<<<<<<<<<< + * + * data = np.asarray(data, dtype=DTYPE, order='c') + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__ones); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), ((PyObject *)__pyx_n_s__bool)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 59; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_v_mask = __pyx_t_5; + __pyx_t_5 = 0; + } + __pyx_L5:; + + /* "sklearn/utils/_graph_tools.pyx":61 + * mask = np.ones(graph.shape, dtype='bool') + * + * data = np.asarray(data, dtype=DTYPE, order='c') # <<<<<<<<<<<<<< + * + * idx_grid = np.empty((N, N), dtype=ITYPE) + */ + __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_data); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_data); + __Pyx_GIVEREF(__pyx_v_data); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__c)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_v_data); + __pyx_v_data = __pyx_t_2; + __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":63 + * data = np.asarray(data, dtype=DTYPE, order='c') + * + * idx_grid = np.empty((N, N), dtype=ITYPE) # <<<<<<<<<<<<<< + * idx_grid[:] = np.arange(N, dtype=ITYPE) + * indices = np.asarray(idx_grid[mask], dtype=ITYPE, order='c') + */ + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_N); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_N); + __Pyx_GIVEREF(__pyx_v_N); + __Pyx_INCREF(__pyx_v_N); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_N); + __Pyx_GIVEREF(__pyx_v_N); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_t_2)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_2)); + __pyx_t_2 = 0; + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_v_idx_grid = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":64 + * + * idx_grid = np.empty((N, N), dtype=ITYPE) + * idx_grid[:] = np.arange(N, dtype=ITYPE) # <<<<<<<<<<<<<< + * indices = np.asarray(idx_grid[mask], dtype=ITYPE, order='c') + * + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__arange); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_N); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_N); + __Pyx_GIVEREF(__pyx_v_N); + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + if (__Pyx_PySequence_SetSlice(__pyx_v_idx_grid, 0, PY_SSIZE_T_MAX, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":65 + * idx_grid = np.empty((N, N), dtype=ITYPE) + * idx_grid[:] = np.arange(N, dtype=ITYPE) + * indices = np.asarray(idx_grid[mask], dtype=ITYPE, order='c') # <<<<<<<<<<<<<< + * + * indptr = np.zeros(N + 1, dtype=ITYPE) + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__asarray); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_GetItem(__pyx_v_idx_grid, __pyx_v_mask); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__c)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_indices = __pyx_t_2; + __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":67 + * indices = np.asarray(idx_grid[mask], dtype=ITYPE, order='c') + * + * indptr = np.zeros(N + 1, dtype=ITYPE) # <<<<<<<<<<<<<< + * indptr[1:] = mask.sum(1).cumsum() + * + */ + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyNumber_Add(__pyx_v_N, __pyx_int_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 67; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_v_indptr = __pyx_t_5; + __pyx_t_5 = 0; + + /* "sklearn/utils/_graph_tools.pyx":68 + * + * indptr = np.zeros(N + 1, dtype=ITYPE) + * indptr[1:] = mask.sum(1).cumsum() # <<<<<<<<<<<<<< + * + * return csr_matrix((data, indices, indptr), (N, N)) + */ + __pyx_t_5 = PyObject_GetAttr(__pyx_v_mask, __pyx_n_s__sum); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_2 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_k_tuple_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__cumsum); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__Pyx_PySequence_SetSlice(__pyx_v_indptr, 1, PY_SSIZE_T_MAX, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":70 + * indptr[1:] = mask.sum(1).cumsum() + * + * return csr_matrix((data, indices, indptr), (N, N)) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__csr_matrix); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_data); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_data); + __Pyx_GIVEREF(__pyx_v_data); + __Pyx_INCREF(__pyx_v_indices); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_v_indices); + __Pyx_GIVEREF(__pyx_v_indices); + __Pyx_INCREF(__pyx_v_indptr); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_indptr); + __Pyx_GIVEREF(__pyx_v_indptr); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_N); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_N); + __Pyx_GIVEREF(__pyx_v_N); + __Pyx_INCREF(__pyx_v_N); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_N); + __Pyx_GIVEREF(__pyx_v_N); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_t_1)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_1)); + __pyx_t_5 = 0; + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("sklearn.utils._graph_tools.csgraph_from_masked", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_N); + __Pyx_XDECREF(__pyx_v_data); + __Pyx_XDECREF(__pyx_v_mask); + __Pyx_XDECREF(__pyx_v_idx_grid); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XDECREF(__pyx_v_indptr); + __Pyx_XDECREF(__pyx_v_graph); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_3csgraph_masked_from_dense(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_12_graph_tools_2csgraph_masked_from_dense[] = "\n csgraph_masked_from_dense(graph, null_value=0, nan_null=True,\n infinity_null=True, copy=True)\n\n Construct a masked array graph representation from a dense matrix.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n graph : array_like\n Input graph. Shape should be (n_nodes, n_nodes).\n null_value : float or None (optional)\n Value that denotes non-edges in the graph. Default is zero.\n infinity_null : bool\n If True (default), then infinite entries (both positive and negative)\n are treated as null edges.\n nan_null : bool\n If True (default), then NaN entries are treated as non-edges\n\n Returns\n -------\n csgraph : MaskedArray\n masked array representation of graph\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_12_graph_tools_3csgraph_masked_from_dense = {__Pyx_NAMESTR("csgraph_masked_from_dense"), (PyCFunction)__pyx_pw_7sklearn_5utils_12_graph_tools_3csgraph_masked_from_dense, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_12_graph_tools_2csgraph_masked_from_dense)}; +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_3csgraph_masked_from_dense(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_graph = 0; + PyObject *__pyx_v_null_value = 0; + PyObject *__pyx_v_nan_null = 0; + PyObject *__pyx_v_infinity_null = 0; + PyObject *__pyx_v_copy = 0; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__graph,&__pyx_n_s__null_value,&__pyx_n_s__nan_null,&__pyx_n_s__infinity_null,&__pyx_n_s__copy,0}; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("csgraph_masked_from_dense (wrapper)", 0); + __pyx_self = __pyx_self; + { + PyObject* values[5] = {0,0,0,0,0}; + values[1] = ((PyObject *)__pyx_int_0); + values[2] = __pyx_k_6; + values[3] = __pyx_k_7; + values[4] = __pyx_k_8; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__graph); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__null_value); + if (value) { values[1] = value; kw_args--; } + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nan_null); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__infinity_null); + if (value) { values[3] = value; kw_args--; } + } + case 4: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__copy); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "csgraph_masked_from_dense") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_graph = values[0]; + __pyx_v_null_value = values[1]; + __pyx_v_nan_null = values[2]; + __pyx_v_infinity_null = values[3]; + __pyx_v_copy = values[4]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("csgraph_masked_from_dense", 0, 1, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils._graph_tools.csgraph_masked_from_dense", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_12_graph_tools_2csgraph_masked_from_dense(__pyx_self, __pyx_v_graph, __pyx_v_null_value, __pyx_v_nan_null, __pyx_v_infinity_null, __pyx_v_copy); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_graph_tools.pyx":73 + * + * + * def csgraph_masked_from_dense(graph, # <<<<<<<<<<<<<< + * null_value=0, + * nan_null=True, + */ + +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_2csgraph_masked_from_dense(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_graph, PyObject *__pyx_v_null_value, PyObject *__pyx_v_nan_null, PyObject *__pyx_v_infinity_null, PyObject *__pyx_v_copy) { + PyObject *__pyx_v_N = NULL; + PyObject *__pyx_v_mask = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("csgraph_masked_from_dense", 0); + __Pyx_INCREF(__pyx_v_graph); + __Pyx_INCREF(__pyx_v_null_value); + __Pyx_INCREF(__pyx_v_nan_null); + __Pyx_INCREF(__pyx_v_infinity_null); + + /* "sklearn/utils/_graph_tools.pyx":103 + * masked array representation of graph + * """ + * graph = np.array(graph, copy=copy) # <<<<<<<<<<<<<< + * + * # check that graph is a square matrix + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__array); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_graph); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_graph); + __Pyx_GIVEREF(__pyx_v_graph); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__copy), __pyx_v_copy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 103; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_v_graph); + __pyx_v_graph = __pyx_t_4; + __pyx_t_4 = 0; + + /* "sklearn/utils/_graph_tools.pyx":106 + * + * # check that graph is a square matrix + * if graph.ndim != 2: # <<<<<<<<<<<<<< + * raise ValueError("graph should have two dimensions") + * N = graph.shape[0] + */ + __pyx_t_4 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__ndim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_4, __pyx_int_2, Py_NE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_5) { + + /* "sklearn/utils/_graph_tools.pyx":107 + * # check that graph is a square matrix + * if graph.ndim != 2: + * raise ValueError("graph should have two dimensions") # <<<<<<<<<<<<<< + * N = graph.shape[0] + * if graph.shape[1] != N: + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/utils/_graph_tools.pyx":108 + * if graph.ndim != 2: + * raise ValueError("graph should have two dimensions") + * N = graph.shape[0] # <<<<<<<<<<<<<< + * if graph.shape[1] != N: + * raise ValueError("graph should be a square array") + */ + __pyx_t_3 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetItemInt(__pyx_t_3, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_N = __pyx_t_4; + __pyx_t_4 = 0; + + /* "sklearn/utils/_graph_tools.pyx":109 + * raise ValueError("graph should have two dimensions") + * N = graph.shape[0] + * if graph.shape[1] != N: # <<<<<<<<<<<<<< + * raise ValueError("graph should be a square array") + * + */ + __pyx_t_4 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_4, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_N, Py_NE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_5) { + + /* "sklearn/utils/_graph_tools.pyx":110 + * N = graph.shape[0] + * if graph.shape[1] != N: + * raise ValueError("graph should be a square array") # <<<<<<<<<<<<<< + * + * # check whether null_value is infinity or NaN + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "sklearn/utils/_graph_tools.pyx":113 + * + * # check whether null_value is infinity or NaN + * if null_value is not None: # <<<<<<<<<<<<<< + * null_value = DTYPE(null_value) + * if np.isnan(null_value): + */ + __pyx_t_5 = (__pyx_v_null_value != Py_None); + if (__pyx_t_5) { + + /* "sklearn/utils/_graph_tools.pyx":114 + * # check whether null_value is infinity or NaN + * if null_value is not None: + * null_value = DTYPE(null_value) # <<<<<<<<<<<<<< + * if np.isnan(null_value): + * nan_null = True + */ + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_null_value); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_null_value); + __Pyx_GIVEREF(__pyx_v_null_value); + __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_v_null_value); + __pyx_v_null_value = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":115 + * if null_value is not None: + * null_value = DTYPE(null_value) + * if np.isnan(null_value): # <<<<<<<<<<<<<< + * nan_null = True + * null_value = None + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__isnan); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_null_value); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_null_value); + __Pyx_GIVEREF(__pyx_v_null_value); + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_5) { + + /* "sklearn/utils/_graph_tools.pyx":116 + * null_value = DTYPE(null_value) + * if np.isnan(null_value): + * nan_null = True # <<<<<<<<<<<<<< + * null_value = None + * elif np.isinf(null_value): + */ + __pyx_t_4 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_v_nan_null); + __pyx_v_nan_null = __pyx_t_4; + __pyx_t_4 = 0; + + /* "sklearn/utils/_graph_tools.pyx":117 + * if np.isnan(null_value): + * nan_null = True + * null_value = None # <<<<<<<<<<<<<< + * elif np.isinf(null_value): + * infinity_null = True + */ + __Pyx_INCREF(Py_None); + __Pyx_DECREF(__pyx_v_null_value); + __pyx_v_null_value = Py_None; + goto __pyx_L6; + } + + /* "sklearn/utils/_graph_tools.pyx":118 + * nan_null = True + * null_value = None + * elif np.isinf(null_value): # <<<<<<<<<<<<<< + * infinity_null = True + * null_value = None + */ + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__isinf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_null_value); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_null_value); + __Pyx_GIVEREF(__pyx_v_null_value); + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_5) { + + /* "sklearn/utils/_graph_tools.pyx":119 + * null_value = None + * elif np.isinf(null_value): + * infinity_null = True # <<<<<<<<<<<<<< + * null_value = None + * + */ + __pyx_t_3 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_v_infinity_null); + __pyx_v_infinity_null = __pyx_t_3; + __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":120 + * elif np.isinf(null_value): + * infinity_null = True + * null_value = None # <<<<<<<<<<<<<< + * + * # flag all the null edges + */ + __Pyx_INCREF(Py_None); + __Pyx_DECREF(__pyx_v_null_value); + __pyx_v_null_value = Py_None; + goto __pyx_L6; + } + __pyx_L6:; + goto __pyx_L5; + } + __pyx_L5:; + + /* "sklearn/utils/_graph_tools.pyx":123 + * + * # flag all the null edges + * if null_value is None: # <<<<<<<<<<<<<< + * mask = np.zeros(graph.shape, dtype='bool') + * graph = np.ma.masked_array(graph, mask, copy=False) + */ + __pyx_t_5 = (__pyx_v_null_value == Py_None); + if (__pyx_t_5) { + + /* "sklearn/utils/_graph_tools.pyx":124 + * # flag all the null edges + * if null_value is None: + * mask = np.zeros(graph.shape, dtype='bool') # <<<<<<<<<<<<<< + * graph = np.ma.masked_array(graph, mask, copy=False) + * else: + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__zeros); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), ((PyObject *)__pyx_n_s__bool)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_mask = __pyx_t_2; + __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":125 + * if null_value is None: + * mask = np.zeros(graph.shape, dtype='bool') + * graph = np.ma.masked_array(graph, mask, copy=False) # <<<<<<<<<<<<<< + * else: + * graph = np.ma.masked_values(graph, null_value, copy=False) + */ + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__ma); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__masked_array); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_graph); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_graph); + __Pyx_GIVEREF(__pyx_v_graph); + __Pyx_INCREF(__pyx_v_mask); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_mask); + __Pyx_GIVEREF(__pyx_v_mask); + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_4 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__copy), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_v_graph); + __pyx_v_graph = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L7; + } + /*else*/ { + + /* "sklearn/utils/_graph_tools.pyx":127 + * graph = np.ma.masked_array(graph, mask, copy=False) + * else: + * graph = np.ma.masked_values(graph, null_value, copy=False) # <<<<<<<<<<<<<< + * + * if infinity_null: + */ + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__ma); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__masked_values); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_graph); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_graph); + __Pyx_GIVEREF(__pyx_v_graph); + __Pyx_INCREF(__pyx_v_null_value); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_null_value); + __Pyx_GIVEREF(__pyx_v_null_value); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_2 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__copy), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_v_graph); + __pyx_v_graph = __pyx_t_2; + __pyx_t_2 = 0; + } + __pyx_L7:; + + /* "sklearn/utils/_graph_tools.pyx":129 + * graph = np.ma.masked_values(graph, null_value, copy=False) + * + * if infinity_null: # <<<<<<<<<<<<<< + * graph.mask |= np.isinf(graph) + * + */ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_infinity_null); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { + + /* "sklearn/utils/_graph_tools.pyx":130 + * + * if infinity_null: + * graph.mask |= np.isinf(graph) # <<<<<<<<<<<<<< + * + * if nan_null: + */ + __pyx_t_2 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__mask); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__isinf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_graph); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_graph); + __Pyx_GIVEREF(__pyx_v_graph); + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_InPlaceOr(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyObject_SetAttr(__pyx_v_graph, __pyx_n_s__mask, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L8; + } + __pyx_L8:; + + /* "sklearn/utils/_graph_tools.pyx":132 + * graph.mask |= np.isinf(graph) + * + * if nan_null: # <<<<<<<<<<<<<< + * graph.mask |= np.isnan(graph) + * + */ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_nan_null); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_5) { + + /* "sklearn/utils/_graph_tools.pyx":133 + * + * if nan_null: + * graph.mask |= np.isnan(graph) # <<<<<<<<<<<<<< + * + * return graph + */ + __pyx_t_3 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__mask); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__isnan); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_graph); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_graph); + __Pyx_GIVEREF(__pyx_v_graph); + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_InPlaceOr(__pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyObject_SetAttr(__pyx_v_graph, __pyx_n_s__mask, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L9; + } + __pyx_L9:; + + /* "sklearn/utils/_graph_tools.pyx":135 + * graph.mask |= np.isnan(graph) + * + * return graph # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_graph); + __pyx_r = __pyx_v_graph; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.utils._graph_tools.csgraph_masked_from_dense", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_N); + __Pyx_XDECREF(__pyx_v_mask); + __Pyx_XDECREF(__pyx_v_graph); + __Pyx_XDECREF(__pyx_v_null_value); + __Pyx_XDECREF(__pyx_v_nan_null); + __Pyx_XDECREF(__pyx_v_infinity_null); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_5csgraph_from_dense(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_12_graph_tools_4csgraph_from_dense[] = "\n csgraph_from_dense(graph, null_value=0, nan_null=True, infinity_null=True)\n\n Construct a CSR-format sparse graph from a dense matrix.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n graph : array_like\n Input graph. Shape should be (n_nodes, n_nodes).\n null_value : float or None (optional)\n Value that denotes non-edges in the graph. Default is zero.\n infinity_null : bool\n If True (default), then infinite entries (both positive and negative)\n are treated as null edges.\n nan_null : bool\n If True (default), then NaN entries are treated as non-edges\n\n Returns\n -------\n csgraph : csr_matrix\n Compressed sparse representation of graph, \n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_12_graph_tools_5csgraph_from_dense = {__Pyx_NAMESTR("csgraph_from_dense"), (PyCFunction)__pyx_pw_7sklearn_5utils_12_graph_tools_5csgraph_from_dense, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_12_graph_tools_4csgraph_from_dense)}; +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_5csgraph_from_dense(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_graph = 0; + PyObject *__pyx_v_null_value = 0; + PyObject *__pyx_v_nan_null = 0; + PyObject *__pyx_v_infinity_null = 0; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__graph,&__pyx_n_s__null_value,&__pyx_n_s__nan_null,&__pyx_n_s__infinity_null,0}; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("csgraph_from_dense (wrapper)", 0); + __pyx_self = __pyx_self; + { + PyObject* values[4] = {0,0,0,0}; + values[1] = ((PyObject *)__pyx_int_0); + values[2] = __pyx_k_11; + values[3] = __pyx_k_12; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__graph); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__null_value); + if (value) { values[1] = value; kw_args--; } + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nan_null); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__infinity_null); + if (value) { values[3] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "csgraph_from_dense") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_graph = values[0]; + __pyx_v_null_value = values[1]; + __pyx_v_nan_null = values[2]; + __pyx_v_infinity_null = values[3]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("csgraph_from_dense", 0, 1, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils._graph_tools.csgraph_from_dense", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_12_graph_tools_4csgraph_from_dense(__pyx_self, __pyx_v_graph, __pyx_v_null_value, __pyx_v_nan_null, __pyx_v_infinity_null); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_graph_tools.pyx":138 + * + * + * def csgraph_from_dense(graph, # <<<<<<<<<<<<<< + * null_value=0, + * nan_null=True, + */ + +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_4csgraph_from_dense(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_graph, PyObject *__pyx_v_null_value, PyObject *__pyx_v_nan_null, PyObject *__pyx_v_infinity_null) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("csgraph_from_dense", 0); + + /* "sklearn/utils/_graph_tools.pyx":166 + * Compressed sparse representation of graph, + * """ + * return csgraph_from_masked(csgraph_masked_from_dense(graph, # <<<<<<<<<<<<<< + * null_value, + * nan_null, + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__csgraph_from_masked); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s_13); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + + /* "sklearn/utils/_graph_tools.pyx":169 + * null_value, + * nan_null, + * infinity_null)) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = PyTuple_New(4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_graph); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_graph); + __Pyx_GIVEREF(__pyx_v_graph); + __Pyx_INCREF(__pyx_v_null_value); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_null_value); + __Pyx_GIVEREF(__pyx_v_null_value); + __Pyx_INCREF(__pyx_v_nan_null); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_v_nan_null); + __Pyx_GIVEREF(__pyx_v_nan_null); + __Pyx_INCREF(__pyx_v_infinity_null); + PyTuple_SET_ITEM(__pyx_t_3, 3, __pyx_v_infinity_null); + __Pyx_GIVEREF(__pyx_v_infinity_null); + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.utils._graph_tools.csgraph_from_dense", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_7csgraph_to_dense(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_12_graph_tools_6csgraph_to_dense[] = "\n csgraph_to_dense(csgraph, null_value=0)\n\n Convert a sparse graph representation to a dense representation\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n csgraph : csr_matrix, csc_matrix, or lil_matrix\n Sparse representation of a graph.\n null_value : float, optional\n The value used to indicate null edges in the dense representation.\n Default is 0.\n\n Returns\n -------\n graph : ndarray\n The dense representation of the sparse graph.\n\n Notes\n -----\n For normal sparse graph representations, calling csgraph_to_dense with\n null_value=0 produces an equivalent result to using dense format\n conversions in the main sparse package. When the sparse representations\n have repeated values, however, the results will differ. The tools in\n scipy.sparse will add repeating values to obtain a final value. This\n function will select the minimum among repeating values to obtain a\n final value. For example, here we'll create a two-node directed sparse\n graph with multiple edges from node 0 to node 1, of weights 2 and 3.\n This illustrates the difference in behavior:\n\n >>> from scipy.sparse import csr_matrix\n >>> data = np.array([2, 3])\n >>> indices = np.array([1, 1])\n >>> indptr = np.array([0, 2, 2])\n >>> M = csr_matrix((data, indices, indptr), shape=(2, 2))\n >>> M.toarray()\n array([[0, 5],\n [0, 0]])\n >>> csgraph_to_dense(M)\n array([[0, 2],\n [0, 0]])\n\n The reason for this difference is to allow a compressed sparse graph to\n represent multiple edges between any two nodes. As most sparse graph\n algorithms are concerned with the single lowest-cost edge between any\n two nodes, the default scipy.sparse behavior of summming multiple weights\n does not make sense in this context.\n\n The other reason for using this routine is to allow for graphs with\n zero-weight edges. Let's look at"" the example of a two-node directed\n graph, connected by an edge of weight zero:\n\n >>> from scipy.sparse import csr_matrix\n >>> data = np.array([0.0])\n >>> indices = np.array([1])\n >>> indptr = np.array([0, 2, 2])\n >>> M = csr_matrix((data, indices, indptr), shape=(2, 2))\n >>> M.toarray()\n array([[0, 0],\n [0, 0]])\n >>> csgraph_to_dense(M, np.inf)\n array([[ Inf, 0.],\n [ Inf, Inf]])\n\n In the first case, the zero-weight edge gets lost in the dense\n representation. In the second case, we can choose a different null value\n and see the true form of the graph.\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_12_graph_tools_7csgraph_to_dense = {__Pyx_NAMESTR("csgraph_to_dense"), (PyCFunction)__pyx_pw_7sklearn_5utils_12_graph_tools_7csgraph_to_dense, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_12_graph_tools_6csgraph_to_dense)}; +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_7csgraph_to_dense(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_csgraph = 0; + PyObject *__pyx_v_null_value = 0; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__csgraph,&__pyx_n_s__null_value,0}; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("csgraph_to_dense (wrapper)", 0); + __pyx_self = __pyx_self; + { + PyObject* values[2] = {0,0}; + values[1] = ((PyObject *)__pyx_int_0); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__csgraph); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__null_value); + if (value) { values[1] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "csgraph_to_dense") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_csgraph = values[0]; + __pyx_v_null_value = values[1]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("csgraph_to_dense", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils._graph_tools.csgraph_to_dense", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_12_graph_tools_6csgraph_to_dense(__pyx_self, __pyx_v_csgraph, __pyx_v_null_value); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_graph_tools.pyx":172 + * + * + * def csgraph_to_dense(csgraph, null_value=0): # <<<<<<<<<<<<<< + * """ + * csgraph_to_dense(csgraph, null_value=0) + */ + +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_6csgraph_to_dense(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_null_value) { + PyObject *__pyx_v_N = NULL; + PyObject *__pyx_v_data = NULL; + PyObject *__pyx_v_indices = NULL; + PyObject *__pyx_v_indptr = NULL; + PyObject *__pyx_v_graph = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + __pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("csgraph_to_dense", 0); + __Pyx_INCREF(__pyx_v_csgraph); + + /* "sklearn/utils/_graph_tools.pyx":245 + * # Allow only csr, lil and csc matrices: other formats when converted to csr + * # combine duplicated edges: we don't want this to happen in the background. + * if isspmatrix_csc(csgraph) or isspmatrix_lil(csgraph): # <<<<<<<<<<<<<< + * csgraph = csgraph.tocsr() + * elif not isspmatrix_csr(csgraph): + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__isspmatrix_csc); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_4) { + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__isspmatrix_lil); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_6 = __pyx_t_5; + } else { + __pyx_t_6 = __pyx_t_4; + } + if (__pyx_t_6) { + + /* "sklearn/utils/_graph_tools.pyx":246 + * # combine duplicated edges: we don't want this to happen in the background. + * if isspmatrix_csc(csgraph) or isspmatrix_lil(csgraph): + * csgraph = csgraph.tocsr() # <<<<<<<<<<<<<< + * elif not isspmatrix_csr(csgraph): + * raise ValueError("csgraph must be lil, csr, or csc format") + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__tocsr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_v_csgraph); + __pyx_v_csgraph = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L3; + } + + /* "sklearn/utils/_graph_tools.pyx":247 + * if isspmatrix_csc(csgraph) or isspmatrix_lil(csgraph): + * csgraph = csgraph.tocsr() + * elif not isspmatrix_csr(csgraph): # <<<<<<<<<<<<<< + * raise ValueError("csgraph must be lil, csr, or csc format") + * + */ + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__isspmatrix_csr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_4 = (!__pyx_t_6); + if (__pyx_t_4) { + + /* "sklearn/utils/_graph_tools.pyx":248 + * csgraph = csgraph.tocsr() + * elif not isspmatrix_csr(csgraph): + * raise ValueError("csgraph must be lil, csr, or csc format") # <<<<<<<<<<<<<< + * + * N = csgraph.shape[0] + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_15), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 248; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 248; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/utils/_graph_tools.pyx":250 + * raise ValueError("csgraph must be lil, csr, or csc format") + * + * N = csgraph.shape[0] # <<<<<<<<<<<<<< + * if csgraph.shape[1] != N: + * raise ValueError('csgraph should be a square matrix') + */ + __pyx_t_3 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_3, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_N = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":251 + * + * N = csgraph.shape[0] + * if csgraph.shape[1] != N: # <<<<<<<<<<<<<< + * raise ValueError('csgraph should be a square matrix') + * + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_1, 1, sizeof(long), PyInt_FromLong); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_RichCompare(__pyx_t_3, __pyx_v_N, Py_NE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_4) { + + /* "sklearn/utils/_graph_tools.pyx":252 + * N = csgraph.shape[0] + * if csgraph.shape[1] != N: + * raise ValueError('csgraph should be a square matrix') # <<<<<<<<<<<<<< + * + * # get attribute arrays + */ + __pyx_t_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_17), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L4; + } + __pyx_L4:; + + /* "sklearn/utils/_graph_tools.pyx":255 + * + * # get attribute arrays + * data = np.asarray(csgraph.data, dtype=DTYPE, order='C') # <<<<<<<<<<<<<< + * indices = np.asarray(csgraph.indices, dtype=ITYPE, order='C') + * indptr = np.asarray(csgraph.indptr, dtype=ITYPE, order='C') + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__data); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_v_data = __pyx_t_7; + __pyx_t_7 = 0; + + /* "sklearn/utils/_graph_tools.pyx":256 + * # get attribute arrays + * data = np.asarray(csgraph.data, dtype=DTYPE, order='C') + * indices = np.asarray(csgraph.indices, dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * indptr = np.asarray(csgraph.indptr, dtype=ITYPE, order='C') + * + */ + __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indices); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_7)); + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __pyx_v_indices = __pyx_t_3; + __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":257 + * data = np.asarray(csgraph.data, dtype=DTYPE, order='C') + * indices = np.asarray(csgraph.indices, dtype=ITYPE, order='C') + * indptr = np.asarray(csgraph.indptr, dtype=ITYPE, order='C') # <<<<<<<<<<<<<< + * + * # create the output array + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__asarray); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indptr); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_indptr = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":260 + * + * # create the output array + * graph = np.empty(csgraph.shape, dtype=DTYPE) # <<<<<<<<<<<<<< + * graph.fill(np.inf) + * _populate_graph(data, indices, indptr, graph, null_value) + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_v_graph = __pyx_t_7; + __pyx_t_7 = 0; + + /* "sklearn/utils/_graph_tools.pyx":261 + * # create the output array + * graph = np.empty(csgraph.shape, dtype=DTYPE) + * graph.fill(np.inf) # <<<<<<<<<<<<<< + * _populate_graph(data, indices, indptr, graph, null_value) + * return graph + */ + __pyx_t_7 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__fill); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__inf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":262 + * graph = np.empty(csgraph.shape, dtype=DTYPE) + * graph.fill(np.inf) + * _populate_graph(data, indices, indptr, graph, null_value) # <<<<<<<<<<<<<< + * return graph + * + */ + if (!(likely(((__pyx_v_data) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_data, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_v_data; + __Pyx_INCREF(__pyx_t_2); + if (!(likely(((__pyx_v_indices) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_indices, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_v_indices; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_v_indptr) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_indptr, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_v_indptr; + __Pyx_INCREF(__pyx_t_7); + if (!(likely(((__pyx_v_graph) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_graph, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_v_graph; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_8 = __pyx_PyFloat_AsDouble(__pyx_v_null_value); if (unlikely((__pyx_t_8 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_f_7sklearn_5utils_12_graph_tools__populate_graph(((PyArrayObject *)__pyx_t_2), ((PyArrayObject *)__pyx_t_1), ((PyArrayObject *)__pyx_t_7), ((PyArrayObject *)__pyx_t_3), __pyx_t_8); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":263 + * graph.fill(np.inf) + * _populate_graph(data, indices, indptr, graph, null_value) + * return graph # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_graph); + __pyx_r = __pyx_v_graph; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("sklearn.utils._graph_tools.csgraph_to_dense", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_N); + __Pyx_XDECREF(__pyx_v_data); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XDECREF(__pyx_v_indptr); + __Pyx_XDECREF(__pyx_v_graph); + __Pyx_XDECREF(__pyx_v_csgraph); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_9csgraph_to_masked(PyObject *__pyx_self, PyObject *__pyx_v_csgraph); /*proto*/ +static char __pyx_doc_7sklearn_5utils_12_graph_tools_8csgraph_to_masked[] = "\n csgraph_to_masked(csgraph)\n\n Convert a sparse graph representation to a masked array representation\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n csgraph : csr_matrix, csc_matrix, or lil_matrix\n Sparse representation of a graph.\n\n Returns\n -------\n graph : MaskedArray\n The masked dense representation of the sparse graph.\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_12_graph_tools_9csgraph_to_masked = {__Pyx_NAMESTR("csgraph_to_masked"), (PyCFunction)__pyx_pw_7sklearn_5utils_12_graph_tools_9csgraph_to_masked, METH_O, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_12_graph_tools_8csgraph_to_masked)}; +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_9csgraph_to_masked(PyObject *__pyx_self, PyObject *__pyx_v_csgraph) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("csgraph_to_masked (wrapper)", 0); + __pyx_self = __pyx_self; + __pyx_r = __pyx_pf_7sklearn_5utils_12_graph_tools_8csgraph_to_masked(__pyx_self, ((PyObject *)__pyx_v_csgraph)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_graph_tools.pyx":266 + * + * + * def csgraph_to_masked(csgraph): # <<<<<<<<<<<<<< + * """ + * csgraph_to_masked(csgraph) + */ + +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_8csgraph_to_masked(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("csgraph_to_masked", 0); + + /* "sklearn/utils/_graph_tools.pyx":284 + * The masked dense representation of the sparse graph. + * """ + * return np.ma.masked_invalid(csgraph_to_dense(csgraph, np.nan)) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__ma); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__masked_invalid); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__csgraph_to_dense); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__nan); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.utils._graph_tools.csgraph_to_masked", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_graph_tools.pyx":287 + * + * + * cdef void _populate_graph(np.ndarray[DTYPE_t, ndim=1, mode='c'] data, # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1, mode='c'] indices, + * np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr, + */ + +static void __pyx_f_7sklearn_5utils_12_graph_tools__populate_graph(PyArrayObject *__pyx_v_data, PyArrayObject *__pyx_v_indices, PyArrayObject *__pyx_v_indptr, PyArrayObject *__pyx_v_graph, __pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t __pyx_v_null_value) { + unsigned int __pyx_v_N; + PyArrayObject *__pyx_v_null_flag = 0; + npy_bool *__pyx_v_null_ptr; + unsigned int __pyx_v_row; + unsigned int __pyx_v_col; + unsigned int __pyx_v_i; + __Pyx_LocalBuf_ND __pyx_pybuffernd_data; + __Pyx_Buffer __pyx_pybuffer_data; + __Pyx_LocalBuf_ND __pyx_pybuffernd_graph; + __Pyx_Buffer __pyx_pybuffer_graph; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices; + __Pyx_Buffer __pyx_pybuffer_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr; + __Pyx_Buffer __pyx_pybuffer_indptr; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + unsigned int __pyx_t_5; + unsigned int __pyx_t_6; + int __pyx_t_7; + long __pyx_t_8; + __pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t __pyx_t_9; + unsigned int __pyx_t_10; + unsigned int __pyx_t_11; + unsigned int __pyx_t_12; + unsigned int __pyx_t_13; + int __pyx_t_14; + unsigned int __pyx_t_15; + unsigned int __pyx_t_16; + unsigned int __pyx_t_17; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_populate_graph", 0); + __pyx_pybuffer_data.pybuffer.buf = NULL; + __pyx_pybuffer_data.refcount = 0; + __pyx_pybuffernd_data.data = NULL; + __pyx_pybuffernd_data.rcbuffer = &__pyx_pybuffer_data; + __pyx_pybuffer_indices.pybuffer.buf = NULL; + __pyx_pybuffer_indices.refcount = 0; + __pyx_pybuffernd_indices.data = NULL; + __pyx_pybuffernd_indices.rcbuffer = &__pyx_pybuffer_indices; + __pyx_pybuffer_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_indptr.refcount = 0; + __pyx_pybuffernd_indptr.data = NULL; + __pyx_pybuffernd_indptr.rcbuffer = &__pyx_pybuffer_indptr; + __pyx_pybuffer_graph.pybuffer.buf = NULL; + __pyx_pybuffer_graph.refcount = 0; + __pyx_pybuffernd_graph.data = NULL; + __pyx_pybuffernd_graph.rcbuffer = &__pyx_pybuffer_graph; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_data, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_data.diminfo[0].strides = __pyx_pybuffernd_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_data.diminfo[0].shape = __pyx_pybuffernd_data.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indices.diminfo[0].strides = __pyx_pybuffernd_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices.diminfo[0].shape = __pyx_pybuffernd_indices.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indptr.diminfo[0].strides = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr.diminfo[0].shape = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_graph.rcbuffer->pybuffer, (PyObject*)__pyx_v_graph, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_graph.diminfo[0].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_graph.diminfo[0].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_graph.diminfo[1].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_graph.diminfo[1].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[1]; + + /* "sklearn/utils/_graph_tools.pyx":295 + * # on input, graph should be filled with infinities, and should be + * # of size [N, N], which is also the size of the sparse matrix + * cdef unsigned int N = graph.shape[0] # <<<<<<<<<<<<<< + * cdef np.ndarray null_flag = np.ones((N, N), dtype=bool, order='C') + * cdef np.npy_bool* null_ptr = null_flag.data + */ + __pyx_v_N = (__pyx_v_graph->dimensions[0]); + + /* "sklearn/utils/_graph_tools.pyx":296 + * # of size [N, N], which is also the size of the sparse matrix + * cdef unsigned int N = graph.shape[0] + * cdef np.ndarray null_flag = np.ones((N, N), dtype=bool, order='C') # <<<<<<<<<<<<<< + * cdef np.npy_bool* null_ptr = null_flag.data + * cdef unsigned int row, col, i + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__ones); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyLong_FromUnsignedLong(__pyx_v_N); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyLong_FromUnsignedLong(__pyx_v_N); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_4)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), ((PyObject*)&PyBool_Type)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__order), ((PyObject *)__pyx_n_s__C)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 296; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_null_flag = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":297 + * cdef unsigned int N = graph.shape[0] + * cdef np.ndarray null_flag = np.ones((N, N), dtype=bool, order='C') + * cdef np.npy_bool* null_ptr = null_flag.data # <<<<<<<<<<<<<< + * cdef unsigned int row, col, i + * + */ + __pyx_v_null_ptr = ((npy_bool *)__pyx_v_null_flag->data); + + /* "sklearn/utils/_graph_tools.pyx":300 + * cdef unsigned int row, col, i + * + * for row from 0 <= row < N: # <<<<<<<<<<<<<< + * for i from indptr[row] <= i < indptr[row + 1]: + * col = indices[i] + */ + __pyx_t_5 = __pyx_v_N; + for (__pyx_v_row = 0; __pyx_v_row < __pyx_t_5; __pyx_v_row++) { + + /* "sklearn/utils/_graph_tools.pyx":301 + * + * for row from 0 <= row < N: + * for i from indptr[row] <= i < indptr[row + 1]: # <<<<<<<<<<<<<< + * col = indices[i] + * null_ptr[col] = 0 + */ + __pyx_t_6 = __pyx_v_row; + __pyx_t_7 = -1; + if (unlikely(__pyx_t_6 >= (size_t)__pyx_pybuffernd_indptr.diminfo[0].shape)) __pyx_t_7 = 0; + if (unlikely(__pyx_t_7 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_7); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_8 = (__pyx_v_row + 1); + __pyx_t_7 = -1; + if (__pyx_t_8 < 0) { + __pyx_t_8 += __pyx_pybuffernd_indptr.diminfo[0].shape; + if (unlikely(__pyx_t_8 < 0)) __pyx_t_7 = 0; + } else if (unlikely(__pyx_t_8 >= __pyx_pybuffernd_indptr.diminfo[0].shape)) __pyx_t_7 = 0; + if (unlikely(__pyx_t_7 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_7); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_9 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_indptr.diminfo[0].strides)); + for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_indptr.diminfo[0].strides)); __pyx_v_i < __pyx_t_9; __pyx_v_i++) { + + /* "sklearn/utils/_graph_tools.pyx":302 + * for row from 0 <= row < N: + * for i from indptr[row] <= i < indptr[row + 1]: + * col = indices[i] # <<<<<<<<<<<<<< + * null_ptr[col] = 0 + * # in case of multiple edges, we'll choose the smallest + */ + __pyx_t_10 = __pyx_v_i; + __pyx_t_7 = -1; + if (unlikely(__pyx_t_10 >= (size_t)__pyx_pybuffernd_indices.diminfo[0].shape)) __pyx_t_7 = 0; + if (unlikely(__pyx_t_7 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_7); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_col = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t *, __pyx_pybuffernd_indices.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_indices.diminfo[0].strides)); + + /* "sklearn/utils/_graph_tools.pyx":303 + * for i from indptr[row] <= i < indptr[row + 1]: + * col = indices[i] + * null_ptr[col] = 0 # <<<<<<<<<<<<<< + * # in case of multiple edges, we'll choose the smallest + * if data[i] < graph[row, col]: + */ + (__pyx_v_null_ptr[__pyx_v_col]) = 0; + + /* "sklearn/utils/_graph_tools.pyx":305 + * null_ptr[col] = 0 + * # in case of multiple edges, we'll choose the smallest + * if data[i] < graph[row, col]: # <<<<<<<<<<<<<< + * graph[row, col] = data[i] + * null_ptr += N + */ + __pyx_t_11 = __pyx_v_i; + __pyx_t_7 = -1; + if (unlikely(__pyx_t_11 >= (size_t)__pyx_pybuffernd_data.diminfo[0].shape)) __pyx_t_7 = 0; + if (unlikely(__pyx_t_7 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_7); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_12 = __pyx_v_row; + __pyx_t_13 = __pyx_v_col; + __pyx_t_7 = -1; + if (unlikely(__pyx_t_12 >= (size_t)__pyx_pybuffernd_graph.diminfo[0].shape)) __pyx_t_7 = 0; + if (unlikely(__pyx_t_13 >= (size_t)__pyx_pybuffernd_graph.diminfo[1].shape)) __pyx_t_7 = 1; + if (unlikely(__pyx_t_7 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_7); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_14 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_data.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_data.diminfo[0].strides)) < (*__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_13, __pyx_pybuffernd_graph.diminfo[1].strides))); + if (__pyx_t_14) { + + /* "sklearn/utils/_graph_tools.pyx":306 + * # in case of multiple edges, we'll choose the smallest + * if data[i] < graph[row, col]: + * graph[row, col] = data[i] # <<<<<<<<<<<<<< + * null_ptr += N + * + */ + __pyx_t_15 = __pyx_v_i; + __pyx_t_7 = -1; + if (unlikely(__pyx_t_15 >= (size_t)__pyx_pybuffernd_data.diminfo[0].shape)) __pyx_t_7 = 0; + if (unlikely(__pyx_t_7 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_7); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 306; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_16 = __pyx_v_row; + __pyx_t_17 = __pyx_v_col; + __pyx_t_7 = -1; + if (unlikely(__pyx_t_16 >= (size_t)__pyx_pybuffernd_graph.diminfo[0].shape)) __pyx_t_7 = 0; + if (unlikely(__pyx_t_17 >= (size_t)__pyx_pybuffernd_graph.diminfo[1].shape)) __pyx_t_7 = 1; + if (unlikely(__pyx_t_7 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_7); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 306; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig2d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_17, __pyx_pybuffernd_graph.diminfo[1].strides) = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_data.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_data.diminfo[0].strides)); + goto __pyx_L7; + } + __pyx_L7:; + } + + /* "sklearn/utils/_graph_tools.pyx":307 + * if data[i] < graph[row, col]: + * graph[row, col] = data[i] + * null_ptr += N # <<<<<<<<<<<<<< + * + * graph[null_flag] = null_value + */ + __pyx_v_null_ptr = (__pyx_v_null_ptr + __pyx_v_N); + } + + /* "sklearn/utils/_graph_tools.pyx":309 + * null_ptr += N + * + * graph[null_flag] = null_value # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = PyFloat_FromDouble(__pyx_v_null_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 309; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetItem(((PyObject *)__pyx_v_graph), ((PyObject *)__pyx_v_null_flag), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 309; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_WriteUnraisable("sklearn.utils._graph_tools._populate_graph", __pyx_clineno, __pyx_lineno, __pyx_filename); + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_null_flag); + __Pyx_RefNannyFinishContext(); +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_11reconstruct_path(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_12_graph_tools_10reconstruct_path[] = "\n reconstruct_path(csgraph, predecessors, directed=True)\n\n Construct a tree from a graph and a predecessor list.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n csgraph : array_like or sparse matrix\n The N x N matrix representing the directed or undirected graph\n from which the predecessors are drawn.\n predecessors : array_like, one dimension\n The length-N array of indices of predecessors for the tree. The\n index of the parent of node i is given by predecessors[i].\n directed : bool, optional\n If True (default), then operate on a directed graph: only move from\n point i to point j along paths csgraph[i, j].\n If False, then operate on an undirected graph: the algorithm can\n progress from point i to j along csgraph[i, j] or csgraph[j, i].\n\n Returns\n -------\n cstree : csr matrix\n The N x N directed compressed-sparse representation of the tree drawn\n from csgraph which is encoded by the predecessor list.\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_12_graph_tools_11reconstruct_path = {__Pyx_NAMESTR("reconstruct_path"), (PyCFunction)__pyx_pw_7sklearn_5utils_12_graph_tools_11reconstruct_path, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_12_graph_tools_10reconstruct_path)}; +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_11reconstruct_path(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_csgraph = 0; + PyObject *__pyx_v_predecessors = 0; + PyObject *__pyx_v_directed = 0; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__csgraph,&__pyx_n_s__predecessors,&__pyx_n_s__directed,0}; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("reconstruct_path (wrapper)", 0); + __pyx_self = __pyx_self; + { + PyObject* values[3] = {0,0,0}; + values[2] = __pyx_k_18; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__csgraph); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__predecessors); + if (likely(values[1])) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("reconstruct_path", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__directed); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "reconstruct_path") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_csgraph = values[0]; + __pyx_v_predecessors = values[1]; + __pyx_v_directed = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("reconstruct_path", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils._graph_tools.reconstruct_path", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_12_graph_tools_10reconstruct_path(__pyx_self, __pyx_v_csgraph, __pyx_v_predecessors, __pyx_v_directed); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_graph_tools.pyx":312 + * + * + * def reconstruct_path(csgraph, predecessors, directed=True): # <<<<<<<<<<<<<< + * """ + * reconstruct_path(csgraph, predecessors, directed=True) + */ + +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_10reconstruct_path(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_predecessors, PyObject *__pyx_v_directed) { + PyObject *__pyx_v_validate_graph = NULL; + PyObject *__pyx_v_N = NULL; + PyObject *__pyx_v_nnull = NULL; + PyObject *__pyx_v_indices = NULL; + PyObject *__pyx_v_pind = NULL; + PyObject *__pyx_v_indptr = NULL; + PyObject *__pyx_v_data = NULL; + PyObject *__pyx_v_data1 = NULL; + PyObject *__pyx_v_data2 = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + Py_ssize_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("reconstruct_path", 0); + __Pyx_INCREF(__pyx_v_csgraph); + + /* "sklearn/utils/_graph_tools.pyx":340 + * from csgraph which is encoded by the predecessor list. + * """ + * from _validation import validate_graph # <<<<<<<<<<<<<< + * csgraph = validate_graph(csgraph, directed, dense_output=False) + * + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_n_s__validate_graph)); + PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s__validate_graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__validate_graph)); + __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s___validation), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__validate_graph); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__validate_graph); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 340; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_1); + __pyx_v_validate_graph = __pyx_t_1; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":341 + * """ + * from _validation import validate_graph + * csgraph = validate_graph(csgraph, directed, dense_output=False) # <<<<<<<<<<<<<< + * + * N = csgraph.shape[0] + */ + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + __Pyx_INCREF(__pyx_v_directed); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_directed); + __Pyx_GIVEREF(__pyx_v_directed); + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_3 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dense_output), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_v_validate_graph, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_v_csgraph); + __pyx_v_csgraph = __pyx_t_3; + __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":343 + * csgraph = validate_graph(csgraph, directed, dense_output=False) + * + * N = csgraph.shape[0] # <<<<<<<<<<<<<< + * + * nnull = (predecessors < 0).sum() + */ + __pyx_t_3 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_3, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_N = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":345 + * N = csgraph.shape[0] + * + * nnull = (predecessors < 0).sum() # <<<<<<<<<<<<<< + * + * indices = np.argsort(predecessors)[nnull:].astype(ITYPE) + */ + __pyx_t_1 = PyObject_RichCompare(__pyx_v_predecessors, __pyx_int_0, Py_LT); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__sum); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_nnull = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":347 + * nnull = (predecessors < 0).sum() + * + * indices = np.argsort(predecessors)[nnull:].astype(ITYPE) # <<<<<<<<<<<<<< + * pind = predecessors[indices] + * indptr = pind.searchsorted(np.arange(N + 1)).astype(ITYPE) + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__argsort); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_predecessors); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_predecessors); + __Pyx_GIVEREF(__pyx_v_predecessors); + __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_4 = __Pyx_PyIndex_AsSsize_t(__pyx_v_nnull); if (unlikely((__pyx_t_4 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PySequence_GetSlice(__pyx_t_2, __pyx_t_4, PY_SSIZE_T_MAX); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__astype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 347; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_indices = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":348 + * + * indices = np.argsort(predecessors)[nnull:].astype(ITYPE) + * pind = predecessors[indices] # <<<<<<<<<<<<<< + * indptr = pind.searchsorted(np.arange(N + 1)).astype(ITYPE) + * + */ + __pyx_t_1 = PyObject_GetItem(__pyx_v_predecessors, __pyx_v_indices); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 348; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_pind = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":349 + * indices = np.argsort(predecessors)[nnull:].astype(ITYPE) + * pind = predecessors[indices] + * indptr = pind.searchsorted(np.arange(N + 1)).astype(ITYPE) # <<<<<<<<<<<<<< + * + * if directed == True: + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_pind, __pyx_n_s__searchsorted); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__arange); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Add(__pyx_v_N, __pyx_int_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__astype); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_v_indptr = __pyx_t_3; + __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":351 + * indptr = pind.searchsorted(np.arange(N + 1)).astype(ITYPE) + * + * if directed == True: # <<<<<<<<<<<<<< + * data = csgraph[pind, indices] + * else: + */ + __pyx_t_3 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyObject_RichCompare(__pyx_v_directed, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_6) { + + /* "sklearn/utils/_graph_tools.pyx":352 + * + * if directed == True: + * data = csgraph[pind, indices] # <<<<<<<<<<<<<< + * else: + * data1 = csgraph[pind, indices] + */ + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_pind); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_pind); + __Pyx_GIVEREF(__pyx_v_pind); + __Pyx_INCREF(__pyx_v_indices); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_indices); + __Pyx_GIVEREF(__pyx_v_indices); + __pyx_t_3 = PyObject_GetItem(__pyx_v_csgraph, ((PyObject *)__pyx_t_1)); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_v_data = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/utils/_graph_tools.pyx":354 + * data = csgraph[pind, indices] + * else: + * data1 = csgraph[pind, indices] # <<<<<<<<<<<<<< + * data2 = csgraph[indices, pind] + * data1[data1 == 0] = np.inf + */ + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 354; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_pind); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_pind); + __Pyx_GIVEREF(__pyx_v_pind); + __Pyx_INCREF(__pyx_v_indices); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_indices); + __Pyx_GIVEREF(__pyx_v_indices); + __pyx_t_1 = PyObject_GetItem(__pyx_v_csgraph, ((PyObject *)__pyx_t_3)); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 354; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_data1 = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":355 + * else: + * data1 = csgraph[pind, indices] + * data2 = csgraph[indices, pind] # <<<<<<<<<<<<<< + * data1[data1 == 0] = np.inf + * data2[data2 == 0] = np.inf + */ + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_indices); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_indices); + __Pyx_GIVEREF(__pyx_v_indices); + __Pyx_INCREF(__pyx_v_pind); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_pind); + __Pyx_GIVEREF(__pyx_v_pind); + __pyx_t_3 = PyObject_GetItem(__pyx_v_csgraph, ((PyObject *)__pyx_t_1)); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_v_data2 = __pyx_t_3; + __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":356 + * data1 = csgraph[pind, indices] + * data2 = csgraph[indices, pind] + * data1[data1 == 0] = np.inf # <<<<<<<<<<<<<< + * data2[data2 == 0] = np.inf + * data = np.minimum(data1, data2) + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__inf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_RichCompare(__pyx_v_data1, __pyx_int_0, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyObject_SetItem(__pyx_v_data1, __pyx_t_3, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":357 + * data2 = csgraph[indices, pind] + * data1[data1 == 0] = np.inf + * data2[data2 == 0] = np.inf # <<<<<<<<<<<<<< + * data = np.minimum(data1, data2) + * + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__inf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_RichCompare(__pyx_v_data2, __pyx_int_0, Py_EQ); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetItem(__pyx_v_data2, __pyx_t_1, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":358 + * data1[data1 == 0] = np.inf + * data2[data2 == 0] = np.inf + * data = np.minimum(data1, data2) # <<<<<<<<<<<<<< + * + * data = np.asarray(data).ravel() + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 358; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__minimum); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 358; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 358; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_data1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_data1); + __Pyx_GIVEREF(__pyx_v_data1); + __Pyx_INCREF(__pyx_v_data2); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_data2); + __Pyx_GIVEREF(__pyx_v_data2); + __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 358; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_data = __pyx_t_5; + __pyx_t_5 = 0; + } + __pyx_L3:; + + /* "sklearn/utils/_graph_tools.pyx":360 + * data = np.minimum(data1, data2) + * + * data = np.asarray(data).ravel() # <<<<<<<<<<<<<< + * + * return csr_matrix((data, indices, indptr), shape=(N, N)) + */ + __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_5, __pyx_n_s__asarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_data); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_data); + __Pyx_GIVEREF(__pyx_v_data); + __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__ravel); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_v_data); + __pyx_v_data = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":362 + * data = np.asarray(data).ravel() + * + * return csr_matrix((data, indices, indptr), shape=(N, N)) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__csr_matrix); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_data); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_data); + __Pyx_GIVEREF(__pyx_v_data); + __Pyx_INCREF(__pyx_v_indices); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_v_indices); + __Pyx_GIVEREF(__pyx_v_indices); + __Pyx_INCREF(__pyx_v_indptr); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_indptr); + __Pyx_GIVEREF(__pyx_v_indptr); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __pyx_t_5 = 0; + __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_N); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_N); + __Pyx_GIVEREF(__pyx_v_N); + __Pyx_INCREF(__pyx_v_N); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_N); + __Pyx_GIVEREF(__pyx_v_N); + if (PyDict_SetItem(__pyx_t_5, ((PyObject *)__pyx_n_s__shape), ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), ((PyObject *)__pyx_t_5)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("sklearn.utils._graph_tools.reconstruct_path", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_validate_graph); + __Pyx_XDECREF(__pyx_v_N); + __Pyx_XDECREF(__pyx_v_nnull); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XDECREF(__pyx_v_pind); + __Pyx_XDECREF(__pyx_v_indptr); + __Pyx_XDECREF(__pyx_v_data); + __Pyx_XDECREF(__pyx_v_data1); + __Pyx_XDECREF(__pyx_v_data2); + __Pyx_XDECREF(__pyx_v_csgraph); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_13construct_dist_matrix(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_12_graph_tools_12construct_dist_matrix[] = "\n construct_dist_matrix(graph, predecessors, directed=True, null_value=np.inf)\n\n Construct distance matrix from a predecessor matrix\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n graph : array_like or sparse\n The N x N matrix representation of a directed or undirected graph.\n If dense, then non-edges are indicated by zeros or infinities.\n predecessors : array_like\n The N x N matrix of predecessors of each node (see Notes below).\n directed : bool, optional\n If True (default), then operate on a directed graph: only move from\n point i to point j along paths csgraph[i, j].\n If False, then operate on an undirected graph: the algorithm can\n progress from point i to j along csgraph[i, j] or csgraph[j, i].\n null_value : bool, optional\n value to use for distances between unconnected nodes. Default is\n np.inf\n\n Returns\n -------\n dist_matrix : ndarray\n The N x N matrix of distances between nodes along the path specified\n by the predecessor matrix. If no path exists, the distance is zero.\n\n Notes\n -----\n The predecessor matrix is of the form returned by\n :func:`graph_shortest_path`. Row i of the predecessor matrix contains\n information on the shortest paths from point i: each entry\n predecessors[i, j] gives the index of the previous node in the path from\n point i to point j. If no path exists between point i and j, then\n predecessors[i, j] = -9999\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_12_graph_tools_13construct_dist_matrix = {__Pyx_NAMESTR("construct_dist_matrix"), (PyCFunction)__pyx_pw_7sklearn_5utils_12_graph_tools_13construct_dist_matrix, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_12_graph_tools_12construct_dist_matrix)}; +static PyObject *__pyx_pw_7sklearn_5utils_12_graph_tools_13construct_dist_matrix(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_graph = 0; + PyObject *__pyx_v_predecessors = 0; + PyObject *__pyx_v_directed = 0; + PyObject *__pyx_v_null_value = 0; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__graph,&__pyx_n_s__predecessors,&__pyx_n_s__directed,&__pyx_n_s__null_value,0}; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("construct_dist_matrix (wrapper)", 0); + __pyx_self = __pyx_self; + { + PyObject* values[4] = {0,0,0,0}; + values[2] = __pyx_k_19; + values[3] = __pyx_k_20; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__graph); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__predecessors); + if (likely(values[1])) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("construct_dist_matrix", 0, 2, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 365; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__directed); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__null_value); + if (value) { values[3] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "construct_dist_matrix") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 365; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_graph = values[0]; + __pyx_v_predecessors = values[1]; + __pyx_v_directed = values[2]; + __pyx_v_null_value = values[3]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("construct_dist_matrix", 0, 2, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 365; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils._graph_tools.construct_dist_matrix", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_12_graph_tools_12construct_dist_matrix(__pyx_self, __pyx_v_graph, __pyx_v_predecessors, __pyx_v_directed, __pyx_v_null_value); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_graph_tools.pyx":365 + * + * + * def construct_dist_matrix(graph, # <<<<<<<<<<<<<< + * predecessors, + * directed=True, + */ + +static PyObject *__pyx_pf_7sklearn_5utils_12_graph_tools_12construct_dist_matrix(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_graph, PyObject *__pyx_v_predecessors, PyObject *__pyx_v_directed, PyObject *__pyx_v_null_value) { + PyObject *__pyx_v_validate_graph = NULL; + PyObject *__pyx_v_dist_matrix = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + __pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("construct_dist_matrix", 0); + __Pyx_INCREF(__pyx_v_graph); + __Pyx_INCREF(__pyx_v_predecessors); + + /* "sklearn/utils/_graph_tools.pyx":407 + * predecessors[i, j] = -9999 + * """ + * from _validation import validate_graph # <<<<<<<<<<<<<< + * graph = validate_graph(graph, directed, dtype=DTYPE, + * csr_output=False, + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_n_s__validate_graph)); + PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s__validate_graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__validate_graph)); + __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s___validation), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__validate_graph); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__validate_graph); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_1); + __pyx_v_validate_graph = __pyx_t_1; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":408 + * """ + * from _validation import validate_graph + * graph = validate_graph(graph, directed, dtype=DTYPE, # <<<<<<<<<<<<<< + * csr_output=False, + * copy_if_dense=not directed) + */ + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_graph); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_graph); + __Pyx_GIVEREF(__pyx_v_graph); + __Pyx_INCREF(__pyx_v_directed); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_directed); + __Pyx_GIVEREF(__pyx_v_directed); + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":409 + * from _validation import validate_graph + * graph = validate_graph(graph, directed, dtype=DTYPE, + * csr_output=False, # <<<<<<<<<<<<<< + * copy_if_dense=not directed) + * predecessors = np.asarray(predecessors) + */ + __pyx_t_3 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 409; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__csr_output), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":410 + * graph = validate_graph(graph, directed, dtype=DTYPE, + * csr_output=False, + * copy_if_dense=not directed) # <<<<<<<<<<<<<< + * predecessors = np.asarray(predecessors) + * + */ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_directed); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyBool_FromLong((!__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__copy_if_dense), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_v_validate_graph, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_v_graph); + __pyx_v_graph = __pyx_t_3; + __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":411 + * csr_output=False, + * copy_if_dense=not directed) + * predecessors = np.asarray(predecessors) # <<<<<<<<<<<<<< + * + * if predecessors.shape != graph.shape: + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__asarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_predecessors); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_predecessors); + __Pyx_GIVEREF(__pyx_v_predecessors); + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_v_predecessors); + __pyx_v_predecessors = __pyx_t_2; + __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":413 + * predecessors = np.asarray(predecessors) + * + * if predecessors.shape != graph.shape: # <<<<<<<<<<<<<< + * raise ValueError("graph and predecessors must have the same shape") + * + */ + __pyx_t_2 = PyObject_GetAttr(__pyx_v_predecessors, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyObject_RichCompare(__pyx_t_2, __pyx_t_3, Py_NE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_4) { + + /* "sklearn/utils/_graph_tools.pyx":414 + * + * if predecessors.shape != graph.shape: + * raise ValueError("graph and predecessors must have the same shape") # <<<<<<<<<<<<<< + * + * dist_matrix = np.zeros(graph.shape, dtype=DTYPE) + */ + __pyx_t_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_22), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/utils/_graph_tools.pyx":416 + * raise ValueError("graph and predecessors must have the same shape") + * + * dist_matrix = np.zeros(graph.shape, dtype=DTYPE) # <<<<<<<<<<<<<< + * _construct_dist_matrix(graph, predecessors, dist_matrix, + * directed, null_value) + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_v_graph, __pyx_n_s__shape); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__DTYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_v_dist_matrix = __pyx_t_5; + __pyx_t_5 = 0; + + /* "sklearn/utils/_graph_tools.pyx":417 + * + * dist_matrix = np.zeros(graph.shape, dtype=DTYPE) + * _construct_dist_matrix(graph, predecessors, dist_matrix, # <<<<<<<<<<<<<< + * directed, null_value) + * + */ + if (!(likely(((__pyx_v_graph) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_graph, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 417; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __pyx_v_graph; + __Pyx_INCREF(__pyx_t_5); + if (!(likely(((__pyx_v_predecessors) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_predecessors, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 417; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_v_predecessors; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_v_dist_matrix) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dist_matrix, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 417; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_v_dist_matrix; + __Pyx_INCREF(__pyx_t_2); + + /* "sklearn/utils/_graph_tools.pyx":418 + * dist_matrix = np.zeros(graph.shape, dtype=DTYPE) + * _construct_dist_matrix(graph, predecessors, dist_matrix, + * directed, null_value) # <<<<<<<<<<<<<< + * + * return dist_matrix + */ + __pyx_t_6 = __Pyx_PyInt_AsInt(__pyx_v_directed); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __pyx_PyFloat_AsDouble(__pyx_v_null_value); if (unlikely((__pyx_t_7 == (npy_float64)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_f_7sklearn_5utils_12_graph_tools__construct_dist_matrix(((PyArrayObject *)__pyx_t_5), ((PyArrayObject *)__pyx_t_1), ((PyArrayObject *)__pyx_t_2), __pyx_t_6, __pyx_t_7); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":420 + * directed, null_value) + * + * return dist_matrix # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_dist_matrix); + __pyx_r = __pyx_v_dist_matrix; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("sklearn.utils._graph_tools.construct_dist_matrix", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_validate_graph); + __Pyx_XDECREF(__pyx_v_dist_matrix); + __Pyx_XDECREF(__pyx_v_graph); + __Pyx_XDECREF(__pyx_v_predecessors); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/_graph_tools.pyx":423 + * + * + * cdef void _construct_dist_matrix(np.ndarray[DTYPE_t, ndim=2] graph, # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=2] pred, + * np.ndarray[DTYPE_t, ndim=2] dist, + */ + +static void __pyx_f_7sklearn_5utils_12_graph_tools__construct_dist_matrix(PyArrayObject *__pyx_v_graph, PyArrayObject *__pyx_v_pred, PyArrayObject *__pyx_v_dist, int __pyx_v_directed, __pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t __pyx_v_null_value) { + int __pyx_v_i; + int __pyx_v_j; + int __pyx_v_k1; + int __pyx_v_k2; + int __pyx_v_N; + int __pyx_v_null_path; + __Pyx_LocalBuf_ND __pyx_pybuffernd_dist; + __Pyx_Buffer __pyx_pybuffer_dist; + __Pyx_LocalBuf_ND __pyx_pybuffernd_graph; + __Pyx_Buffer __pyx_pybuffer_graph; + __Pyx_LocalBuf_ND __pyx_pybuffernd_pred; + __Pyx_Buffer __pyx_pybuffer_pred; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + int __pyx_t_17; + int __pyx_t_18; + int __pyx_t_19; + int __pyx_t_20; + int __pyx_t_21; + int __pyx_t_22; + int __pyx_t_23; + int __pyx_t_24; + int __pyx_t_25; + int __pyx_t_26; + int __pyx_t_27; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_construct_dist_matrix", 0); + __pyx_pybuffer_graph.pybuffer.buf = NULL; + __pyx_pybuffer_graph.refcount = 0; + __pyx_pybuffernd_graph.data = NULL; + __pyx_pybuffernd_graph.rcbuffer = &__pyx_pybuffer_graph; + __pyx_pybuffer_pred.pybuffer.buf = NULL; + __pyx_pybuffer_pred.refcount = 0; + __pyx_pybuffernd_pred.data = NULL; + __pyx_pybuffernd_pred.rcbuffer = &__pyx_pybuffer_pred; + __pyx_pybuffer_dist.pybuffer.buf = NULL; + __pyx_pybuffer_dist.refcount = 0; + __pyx_pybuffernd_dist.data = NULL; + __pyx_pybuffernd_dist.rcbuffer = &__pyx_pybuffer_dist; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_graph.rcbuffer->pybuffer, (PyObject*)__pyx_v_graph, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_graph.diminfo[0].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_graph.diminfo[0].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_graph.diminfo[1].strides = __pyx_pybuffernd_graph.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_graph.diminfo[1].shape = __pyx_pybuffernd_graph.rcbuffer->pybuffer.shape[1]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_pred.rcbuffer->pybuffer, (PyObject*)__pyx_v_pred, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_pred.diminfo[0].strides = __pyx_pybuffernd_pred.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_pred.diminfo[0].shape = __pyx_pybuffernd_pred.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_pred.diminfo[1].strides = __pyx_pybuffernd_pred.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_pred.diminfo[1].shape = __pyx_pybuffernd_pred.rcbuffer->pybuffer.shape[1]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_dist.rcbuffer->pybuffer, (PyObject*)__pyx_v_dist, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_dist.diminfo[0].strides = __pyx_pybuffernd_dist.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_dist.diminfo[0].shape = __pyx_pybuffernd_dist.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_dist.diminfo[1].strides = __pyx_pybuffernd_dist.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_dist.diminfo[1].shape = __pyx_pybuffernd_dist.rcbuffer->pybuffer.shape[1]; + + /* "sklearn/utils/_graph_tools.pyx":434 + * + * cdef int i, j, k1, k2, N, null_path + * N = graph.shape[0] # <<<<<<<<<<<<<< + * + * #------------------------------------------ + */ + __pyx_v_N = (__pyx_v_graph->dimensions[0]); + + /* "sklearn/utils/_graph_tools.pyx":438 + * #------------------------------------------ + * # symmetrize matrix if necessary + * if not directed: # <<<<<<<<<<<<<< + * graph[graph == 0] = np.inf + * for i from 0 <= i < N: + */ + __pyx_t_1 = (!__pyx_v_directed); + if (__pyx_t_1) { + + /* "sklearn/utils/_graph_tools.pyx":439 + * # symmetrize matrix if necessary + * if not directed: + * graph[graph == 0] = np.inf # <<<<<<<<<<<<<< + * for i from 0 <= i < N: + * for j from i + 1 <= j < N: + */ + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__inf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_RichCompare(((PyObject *)__pyx_v_graph), __pyx_int_0, Py_EQ); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetItem(((PyObject *)__pyx_v_graph), __pyx_t_2, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "sklearn/utils/_graph_tools.pyx":440 + * if not directed: + * graph[graph == 0] = np.inf + * for i from 0 <= i < N: # <<<<<<<<<<<<<< + * for j from i + 1 <= j < N: + * if graph[j, i] <= graph[i, j]: + */ + __pyx_t_4 = __pyx_v_N; + for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { + + /* "sklearn/utils/_graph_tools.pyx":441 + * graph[graph == 0] = np.inf + * for i from 0 <= i < N: + * for j from i + 1 <= j < N: # <<<<<<<<<<<<<< + * if graph[j, i] <= graph[i, j]: + * graph[i, j] = graph[j, i] + */ + __pyx_t_5 = __pyx_v_N; + for (__pyx_v_j = (__pyx_v_i + 1); __pyx_v_j < __pyx_t_5; __pyx_v_j++) { + + /* "sklearn/utils/_graph_tools.pyx":442 + * for i from 0 <= i < N: + * for j from i + 1 <= j < N: + * if graph[j, i] <= graph[i, j]: # <<<<<<<<<<<<<< + * graph[i, j] = graph[j, i] + * else: + */ + __pyx_t_6 = __pyx_v_j; + __pyx_t_7 = __pyx_v_i; + __pyx_t_8 = -1; + if (__pyx_t_6 < 0) { + __pyx_t_6 += __pyx_pybuffernd_graph.diminfo[0].shape; + if (unlikely(__pyx_t_6 < 0)) __pyx_t_8 = 0; + } else if (unlikely(__pyx_t_6 >= __pyx_pybuffernd_graph.diminfo[0].shape)) __pyx_t_8 = 0; + if (__pyx_t_7 < 0) { + __pyx_t_7 += __pyx_pybuffernd_graph.diminfo[1].shape; + if (unlikely(__pyx_t_7 < 0)) __pyx_t_8 = 1; + } else if (unlikely(__pyx_t_7 >= __pyx_pybuffernd_graph.diminfo[1].shape)) __pyx_t_8 = 1; + if (unlikely(__pyx_t_8 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_8); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_8 = __pyx_v_i; + __pyx_t_9 = __pyx_v_j; + __pyx_t_10 = -1; + if (__pyx_t_8 < 0) { + __pyx_t_8 += __pyx_pybuffernd_graph.diminfo[0].shape; + if (unlikely(__pyx_t_8 < 0)) __pyx_t_10 = 0; + } else if (unlikely(__pyx_t_8 >= __pyx_pybuffernd_graph.diminfo[0].shape)) __pyx_t_10 = 0; + if (__pyx_t_9 < 0) { + __pyx_t_9 += __pyx_pybuffernd_graph.diminfo[1].shape; + if (unlikely(__pyx_t_9 < 0)) __pyx_t_10 = 1; + } else if (unlikely(__pyx_t_9 >= __pyx_pybuffernd_graph.diminfo[1].shape)) __pyx_t_10 = 1; + if (unlikely(__pyx_t_10 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_10); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = ((*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_7, __pyx_pybuffernd_graph.diminfo[1].strides)) <= (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_9, __pyx_pybuffernd_graph.diminfo[1].strides))); + if (__pyx_t_1) { + + /* "sklearn/utils/_graph_tools.pyx":443 + * for j from i + 1 <= j < N: + * if graph[j, i] <= graph[i, j]: + * graph[i, j] = graph[j, i] # <<<<<<<<<<<<<< + * else: + * graph[j, i] = graph[i, j] + */ + __pyx_t_10 = __pyx_v_j; + __pyx_t_11 = __pyx_v_i; + __pyx_t_12 = -1; + if (__pyx_t_10 < 0) { + __pyx_t_10 += __pyx_pybuffernd_graph.diminfo[0].shape; + if (unlikely(__pyx_t_10 < 0)) __pyx_t_12 = 0; + } else if (unlikely(__pyx_t_10 >= __pyx_pybuffernd_graph.diminfo[0].shape)) __pyx_t_12 = 0; + if (__pyx_t_11 < 0) { + __pyx_t_11 += __pyx_pybuffernd_graph.diminfo[1].shape; + if (unlikely(__pyx_t_11 < 0)) __pyx_t_12 = 1; + } else if (unlikely(__pyx_t_11 >= __pyx_pybuffernd_graph.diminfo[1].shape)) __pyx_t_12 = 1; + if (unlikely(__pyx_t_12 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_12); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_12 = __pyx_v_i; + __pyx_t_13 = __pyx_v_j; + __pyx_t_14 = -1; + if (__pyx_t_12 < 0) { + __pyx_t_12 += __pyx_pybuffernd_graph.diminfo[0].shape; + if (unlikely(__pyx_t_12 < 0)) __pyx_t_14 = 0; + } else if (unlikely(__pyx_t_12 >= __pyx_pybuffernd_graph.diminfo[0].shape)) __pyx_t_14 = 0; + if (__pyx_t_13 < 0) { + __pyx_t_13 += __pyx_pybuffernd_graph.diminfo[1].shape; + if (unlikely(__pyx_t_13 < 0)) __pyx_t_14 = 1; + } else if (unlikely(__pyx_t_13 >= __pyx_pybuffernd_graph.diminfo[1].shape)) __pyx_t_14 = 1; + if (unlikely(__pyx_t_14 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_14); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_13, __pyx_pybuffernd_graph.diminfo[1].strides) = (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_11, __pyx_pybuffernd_graph.diminfo[1].strides)); + goto __pyx_L8; + } + /*else*/ { + + /* "sklearn/utils/_graph_tools.pyx":445 + * graph[i, j] = graph[j, i] + * else: + * graph[j, i] = graph[i, j] # <<<<<<<<<<<<<< + * #------------------------------------------ + * + */ + __pyx_t_14 = __pyx_v_i; + __pyx_t_15 = __pyx_v_j; + __pyx_t_16 = -1; + if (__pyx_t_14 < 0) { + __pyx_t_14 += __pyx_pybuffernd_graph.diminfo[0].shape; + if (unlikely(__pyx_t_14 < 0)) __pyx_t_16 = 0; + } else if (unlikely(__pyx_t_14 >= __pyx_pybuffernd_graph.diminfo[0].shape)) __pyx_t_16 = 0; + if (__pyx_t_15 < 0) { + __pyx_t_15 += __pyx_pybuffernd_graph.diminfo[1].shape; + if (unlikely(__pyx_t_15 < 0)) __pyx_t_16 = 1; + } else if (unlikely(__pyx_t_15 >= __pyx_pybuffernd_graph.diminfo[1].shape)) __pyx_t_16 = 1; + if (unlikely(__pyx_t_16 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_16); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_16 = __pyx_v_j; + __pyx_t_17 = __pyx_v_i; + __pyx_t_18 = -1; + if (__pyx_t_16 < 0) { + __pyx_t_16 += __pyx_pybuffernd_graph.diminfo[0].shape; + if (unlikely(__pyx_t_16 < 0)) __pyx_t_18 = 0; + } else if (unlikely(__pyx_t_16 >= __pyx_pybuffernd_graph.diminfo[0].shape)) __pyx_t_18 = 0; + if (__pyx_t_17 < 0) { + __pyx_t_17 += __pyx_pybuffernd_graph.diminfo[1].shape; + if (unlikely(__pyx_t_17 < 0)) __pyx_t_18 = 1; + } else if (unlikely(__pyx_t_17 >= __pyx_pybuffernd_graph.diminfo[1].shape)) __pyx_t_18 = 1; + if (unlikely(__pyx_t_18 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_18); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_17, __pyx_pybuffernd_graph.diminfo[1].strides) = (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_15, __pyx_pybuffernd_graph.diminfo[1].strides)); + } + __pyx_L8:; + } + } + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/utils/_graph_tools.pyx":448 + * #------------------------------------------ + * + * for i from 0 <= i < N: # <<<<<<<<<<<<<< + * for j from 0 <= j < N: + * null_path = True + */ + __pyx_t_4 = __pyx_v_N; + for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { + + /* "sklearn/utils/_graph_tools.pyx":449 + * + * for i from 0 <= i < N: + * for j from 0 <= j < N: # <<<<<<<<<<<<<< + * null_path = True + * k2 = j + */ + __pyx_t_5 = __pyx_v_N; + for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_5; __pyx_v_j++) { + + /* "sklearn/utils/_graph_tools.pyx":450 + * for i from 0 <= i < N: + * for j from 0 <= j < N: + * null_path = True # <<<<<<<<<<<<<< + * k2 = j + * while k2 != i: + */ + __pyx_v_null_path = 1; + + /* "sklearn/utils/_graph_tools.pyx":451 + * for j from 0 <= j < N: + * null_path = True + * k2 = j # <<<<<<<<<<<<<< + * while k2 != i: + * k1 = pred[i, k2] + */ + __pyx_v_k2 = __pyx_v_j; + + /* "sklearn/utils/_graph_tools.pyx":452 + * null_path = True + * k2 = j + * while k2 != i: # <<<<<<<<<<<<<< + * k1 = pred[i, k2] + * if k1 == NULL_IDX: + */ + while (1) { + __pyx_t_1 = (__pyx_v_k2 != __pyx_v_i); + if (!__pyx_t_1) break; + + /* "sklearn/utils/_graph_tools.pyx":453 + * k2 = j + * while k2 != i: + * k1 = pred[i, k2] # <<<<<<<<<<<<<< + * if k1 == NULL_IDX: + * break + */ + __pyx_t_18 = __pyx_v_i; + __pyx_t_19 = __pyx_v_k2; + __pyx_t_20 = -1; + if (__pyx_t_18 < 0) { + __pyx_t_18 += __pyx_pybuffernd_pred.diminfo[0].shape; + if (unlikely(__pyx_t_18 < 0)) __pyx_t_20 = 0; + } else if (unlikely(__pyx_t_18 >= __pyx_pybuffernd_pred.diminfo[0].shape)) __pyx_t_20 = 0; + if (__pyx_t_19 < 0) { + __pyx_t_19 += __pyx_pybuffernd_pred.diminfo[1].shape; + if (unlikely(__pyx_t_19 < 0)) __pyx_t_20 = 1; + } else if (unlikely(__pyx_t_19 >= __pyx_pybuffernd_pred.diminfo[1].shape)) __pyx_t_20 = 1; + if (unlikely(__pyx_t_20 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_20); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_k1 = (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_12_graph_tools_ITYPE_t *, __pyx_pybuffernd_pred.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_pred.diminfo[0].strides, __pyx_t_19, __pyx_pybuffernd_pred.diminfo[1].strides)); + + /* "sklearn/utils/_graph_tools.pyx":454 + * while k2 != i: + * k1 = pred[i, k2] + * if k1 == NULL_IDX: # <<<<<<<<<<<<<< + * break + * dist[i, j] += graph[k1, k2] + */ + __pyx_t_1 = (__pyx_v_k1 == __pyx_v_7sklearn_5utils_12_graph_tools_NULL_IDX); + if (__pyx_t_1) { + + /* "sklearn/utils/_graph_tools.pyx":455 + * k1 = pred[i, k2] + * if k1 == NULL_IDX: + * break # <<<<<<<<<<<<<< + * dist[i, j] += graph[k1, k2] + * null_path = False + */ + goto __pyx_L14_break; + goto __pyx_L15; + } + __pyx_L15:; + + /* "sklearn/utils/_graph_tools.pyx":456 + * if k1 == NULL_IDX: + * break + * dist[i, j] += graph[k1, k2] # <<<<<<<<<<<<<< + * null_path = False + * k2 = k1 + */ + __pyx_t_20 = __pyx_v_k1; + __pyx_t_21 = __pyx_v_k2; + __pyx_t_22 = -1; + if (__pyx_t_20 < 0) { + __pyx_t_20 += __pyx_pybuffernd_graph.diminfo[0].shape; + if (unlikely(__pyx_t_20 < 0)) __pyx_t_22 = 0; + } else if (unlikely(__pyx_t_20 >= __pyx_pybuffernd_graph.diminfo[0].shape)) __pyx_t_22 = 0; + if (__pyx_t_21 < 0) { + __pyx_t_21 += __pyx_pybuffernd_graph.diminfo[1].shape; + if (unlikely(__pyx_t_21 < 0)) __pyx_t_22 = 1; + } else if (unlikely(__pyx_t_21 >= __pyx_pybuffernd_graph.diminfo[1].shape)) __pyx_t_22 = 1; + if (unlikely(__pyx_t_22 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_22); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_22 = __pyx_v_i; + __pyx_t_23 = __pyx_v_j; + __pyx_t_24 = -1; + if (__pyx_t_22 < 0) { + __pyx_t_22 += __pyx_pybuffernd_dist.diminfo[0].shape; + if (unlikely(__pyx_t_22 < 0)) __pyx_t_24 = 0; + } else if (unlikely(__pyx_t_22 >= __pyx_pybuffernd_dist.diminfo[0].shape)) __pyx_t_24 = 0; + if (__pyx_t_23 < 0) { + __pyx_t_23 += __pyx_pybuffernd_dist.diminfo[1].shape; + if (unlikely(__pyx_t_23 < 0)) __pyx_t_24 = 1; + } else if (unlikely(__pyx_t_23 >= __pyx_pybuffernd_dist.diminfo[1].shape)) __pyx_t_24 = 1; + if (unlikely(__pyx_t_24 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_24); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_dist.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_dist.diminfo[0].strides, __pyx_t_23, __pyx_pybuffernd_dist.diminfo[1].strides) += (*__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_graph.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_graph.diminfo[0].strides, __pyx_t_21, __pyx_pybuffernd_graph.diminfo[1].strides)); + + /* "sklearn/utils/_graph_tools.pyx":457 + * break + * dist[i, j] += graph[k1, k2] + * null_path = False # <<<<<<<<<<<<<< + * k2 = k1 + * if null_path and i != j: + */ + __pyx_v_null_path = 0; + + /* "sklearn/utils/_graph_tools.pyx":458 + * dist[i, j] += graph[k1, k2] + * null_path = False + * k2 = k1 # <<<<<<<<<<<<<< + * if null_path and i != j: + * dist[i, j] = null_value + */ + __pyx_v_k2 = __pyx_v_k1; + } + __pyx_L14_break:; + + /* "sklearn/utils/_graph_tools.pyx":459 + * null_path = False + * k2 = k1 + * if null_path and i != j: # <<<<<<<<<<<<<< + * dist[i, j] = null_value + */ + if (__pyx_v_null_path) { + __pyx_t_1 = (__pyx_v_i != __pyx_v_j); + __pyx_t_25 = __pyx_t_1; + } else { + __pyx_t_25 = __pyx_v_null_path; + } + if (__pyx_t_25) { + + /* "sklearn/utils/_graph_tools.pyx":460 + * k2 = k1 + * if null_path and i != j: + * dist[i, j] = null_value # <<<<<<<<<<<<<< + */ + __pyx_t_24 = __pyx_v_i; + __pyx_t_26 = __pyx_v_j; + __pyx_t_27 = -1; + if (__pyx_t_24 < 0) { + __pyx_t_24 += __pyx_pybuffernd_dist.diminfo[0].shape; + if (unlikely(__pyx_t_24 < 0)) __pyx_t_27 = 0; + } else if (unlikely(__pyx_t_24 >= __pyx_pybuffernd_dist.diminfo[0].shape)) __pyx_t_27 = 0; + if (__pyx_t_26 < 0) { + __pyx_t_26 += __pyx_pybuffernd_dist.diminfo[1].shape; + if (unlikely(__pyx_t_26 < 0)) __pyx_t_27 = 1; + } else if (unlikely(__pyx_t_26 >= __pyx_pybuffernd_dist.diminfo[1].shape)) __pyx_t_27 = 1; + if (unlikely(__pyx_t_27 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_27); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrStrided2d(__pyx_t_7sklearn_5utils_12_graph_tools_DTYPE_t *, __pyx_pybuffernd_dist.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_dist.diminfo[0].strides, __pyx_t_26, __pyx_pybuffernd_dist.diminfo[1].strides) = __pyx_v_null_value; + goto __pyx_L16; + } + __pyx_L16:; + } + } + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dist.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_pred.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_WriteUnraisable("sklearn.utils._graph_tools._construct_dist_matrix", __pyx_clineno, __pyx_lineno, __pyx_filename); + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_dist.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_graph.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_pred.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_RefNannyFinishContext(); +} + +/* Python wrapper */ +static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":193 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "numpy.pxd":199 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = (__pyx_v_info == NULL); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":202 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":203 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":205 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "numpy.pxd":207 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + if (__pyx_t_1) { + + /* "numpy.pxd":208 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "numpy.pxd":210 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "numpy.pxd":212 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + if (__pyx_t_1) { + + /* "numpy.pxd":213 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS)); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "numpy.pxd":214 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_24), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "numpy.pxd":216 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + if (__pyx_t_3) { + + /* "numpy.pxd":217 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS)); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "numpy.pxd":218 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_26), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "numpy.pxd":220 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "numpy.pxd":221 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "numpy.pxd":222 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + if (__pyx_v_copy_shape) { + + /* "numpy.pxd":225 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "numpy.pxd":226 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "numpy.pxd":227 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "numpy.pxd":228 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "numpy.pxd":229 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "numpy.pxd":231 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "numpy.pxd":232 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "numpy.pxd":233 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "numpy.pxd":234 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "numpy.pxd":235 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); + + /* "numpy.pxd":238 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "numpy.pxd":239 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self->descr)); + __pyx_v_descr = __pyx_v_self->descr; + + /* "numpy.pxd":243 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "numpy.pxd":245 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = (!__pyx_v_hasfields); + if (__pyx_t_2) { + __pyx_t_3 = (!__pyx_v_copy_shape); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":247 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "numpy.pxd":250 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "numpy.pxd":252 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == '>' and little_endian) or + */ + __pyx_t_1 = (!__pyx_v_hasfields); + if (__pyx_t_1) { + + /* "numpy.pxd":253 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == '>' and little_endian) or + * (descr.byteorder == '<' and not little_endian)): + */ + __pyx_v_t = __pyx_v_descr->type_num; + + /* "numpy.pxd":254 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); + if (__pyx_t_1) { + __pyx_t_2 = __pyx_v_little_endian; + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "numpy.pxd":255 + * t = descr.type_num + * if ((descr.byteorder == '>' and little_endian) or + * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); + if (__pyx_t_1) { + __pyx_t_3 = (!__pyx_v_little_endian); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":256 + * if ((descr.byteorder == '>' and little_endian) or + * (descr.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_28), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":257 + * (descr.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + __pyx_t_1 = (__pyx_v_t == NPY_BYTE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__b; + goto __pyx_L13; + } + + /* "numpy.pxd":258 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__B; + goto __pyx_L13; + } + + /* "numpy.pxd":259 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + __pyx_t_1 = (__pyx_v_t == NPY_SHORT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__h; + goto __pyx_L13; + } + + /* "numpy.pxd":260 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + __pyx_t_1 = (__pyx_v_t == NPY_USHORT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__H; + goto __pyx_L13; + } + + /* "numpy.pxd":261 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + __pyx_t_1 = (__pyx_v_t == NPY_INT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__i; + goto __pyx_L13; + } + + /* "numpy.pxd":262 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + __pyx_t_1 = (__pyx_v_t == NPY_UINT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__I; + goto __pyx_L13; + } + + /* "numpy.pxd":263 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + __pyx_t_1 = (__pyx_v_t == NPY_LONG); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__l; + goto __pyx_L13; + } + + /* "numpy.pxd":264 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + __pyx_t_1 = (__pyx_v_t == NPY_ULONG); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__L; + goto __pyx_L13; + } + + /* "numpy.pxd":265 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__q; + goto __pyx_L13; + } + + /* "numpy.pxd":266 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__Q; + goto __pyx_L13; + } + + /* "numpy.pxd":267 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__f; + goto __pyx_L13; + } + + /* "numpy.pxd":268 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__d; + goto __pyx_L13; + } + + /* "numpy.pxd":269 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__g; + goto __pyx_L13; + } + + /* "numpy.pxd":270 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__Zf; + goto __pyx_L13; + } + + /* "numpy.pxd":271 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__Zd; + goto __pyx_L13; + } + + /* "numpy.pxd":272 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__Zg; + goto __pyx_L13; + } + + /* "numpy.pxd":273 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__O; + goto __pyx_L13; + } + /*else*/ { + + /* "numpy.pxd":275 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_29), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L13:; + + /* "numpy.pxd":276 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "numpy.pxd":277 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":279 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = '^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "numpy.pxd":280 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "numpy.pxd":281 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = '^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "numpy.pxd":284 + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + * &offset) # <<<<<<<<<<<<<< + * f[0] = 0 # Terminate format string + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "numpy.pxd":285 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = 0; + } + __pyx_L11:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":287 + * f[0] = 0 # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "numpy.pxd":288 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); + if (__pyx_t_1) { + + /* "numpy.pxd":289 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":290 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + if (__pyx_t_1) { + + /* "numpy.pxd":291 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":767 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "numpy.pxd":768 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":770 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "numpy.pxd":771 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":773 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "numpy.pxd":774 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":776 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "numpy.pxd":777 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":779 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "numpy.pxd":780 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":782 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + long __pyx_t_10; + char *__pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "numpy.pxd":789 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":790 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":793 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; + __Pyx_XDECREF(__pyx_v_childname); + __pyx_v_childname = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":794 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); + __pyx_v_fields = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "numpy.pxd":795 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { + PyObject* sequence = ((PyObject *)__pyx_v_fields); + if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { + if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); + else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + } else { + __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_child)); + __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_v_new_offset); + __pyx_v_new_offset = __pyx_t_4; + __pyx_t_4 = 0; + + /* "numpy.pxd":797 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + + /* "numpy.pxd":798 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == '>' and little_endian) or + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_31), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "numpy.pxd":800 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_6 = (__pyx_v_child->byteorder == '>'); + if (__pyx_t_6) { + __pyx_t_7 = __pyx_v_little_endian; + } else { + __pyx_t_7 = __pyx_t_6; + } + if (!__pyx_t_7) { + + /* "numpy.pxd":801 + * + * if ((child.byteorder == '>' and little_endian) or + * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_6 = (__pyx_v_child->byteorder == '<'); + if (__pyx_t_6) { + __pyx_t_8 = (!__pyx_v_little_endian); + __pyx_t_9 = __pyx_t_8; + } else { + __pyx_t_9 = __pyx_t_6; + } + __pyx_t_6 = __pyx_t_9; + } else { + __pyx_t_6 = __pyx_t_7; + } + if (__pyx_t_6) { + + /* "numpy.pxd":802 + * if ((child.byteorder == '>' and little_endian) or + * (child.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_32), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "numpy.pxd":812 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_6) break; + + /* "numpy.pxd":813 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "numpy.pxd":814 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "numpy.pxd":815 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + } + + /* "numpy.pxd":817 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + + /* "numpy.pxd":819 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); + if (__pyx_t_6) { + + /* "numpy.pxd":820 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 820; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_v_t); + __pyx_v_t = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":821 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); + if (__pyx_t_6) { + + /* "numpy.pxd":822 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_34), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L10; + } + __pyx_L10:; + + /* "numpy.pxd":825 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L11; + } + + /* "numpy.pxd":826 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L11; + } + + /* "numpy.pxd":827 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L11; + } + + /* "numpy.pxd":828 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L11; + } + + /* "numpy.pxd":829 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L11; + } + + /* "numpy.pxd":830 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L11; + } + + /* "numpy.pxd":831 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L11; + } + + /* "numpy.pxd":832 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L11; + } + + /* "numpy.pxd":833 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L11; + } + + /* "numpy.pxd":834 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L11; + } + + /* "numpy.pxd":835 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L11; + } + + /* "numpy.pxd":836 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L11; + } + + /* "numpy.pxd":837 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L11; + } + + /* "numpy.pxd":838 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "numpy.pxd":839 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "numpy.pxd":840 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "numpy.pxd":841 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":843 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_29), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L11:; + + /* "numpy.pxd":844 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L9; + } + /*else*/ { + + /* "numpy.pxd":848 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 848; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_11; + } + __pyx_L9:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "numpy.pxd":849 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":964 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "numpy.pxd":966 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + if (__pyx_t_1) { + + /* "numpy.pxd":967 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":969 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "numpy.pxd":970 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "numpy.pxd":971 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "numpy.pxd":972 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":974 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "numpy.pxd":975 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = (__pyx_v_arr->base == NULL); + if (__pyx_t_1) { + + /* "numpy.pxd":976 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":978 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + PyModuleDef_HEAD_INIT, + __Pyx_NAMESTR("_graph_tools"), + __Pyx_DOCSTR(__pyx_k_35), /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 0}, + {&__pyx_n_s_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 0, 1, 1}, + {&__pyx_kp_s_14, __pyx_k_14, sizeof(__pyx_k_14), 0, 0, 1, 0}, + {&__pyx_kp_s_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 1, 0}, + {&__pyx_kp_s_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 1, 0}, + {&__pyx_kp_u_23, __pyx_k_23, sizeof(__pyx_k_23), 0, 1, 0, 0}, + {&__pyx_kp_u_25, __pyx_k_25, sizeof(__pyx_k_25), 0, 1, 0, 0}, + {&__pyx_kp_u_27, __pyx_k_27, sizeof(__pyx_k_27), 0, 1, 0, 0}, + {&__pyx_kp_u_29, __pyx_k_29, sizeof(__pyx_k_29), 0, 1, 0, 0}, + {&__pyx_kp_s_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 0, 1, 0}, + {&__pyx_kp_u_30, __pyx_k_30, sizeof(__pyx_k_30), 0, 1, 0, 0}, + {&__pyx_kp_u_33, __pyx_k_33, sizeof(__pyx_k_33), 0, 1, 0, 0}, + {&__pyx_n_s_36, __pyx_k_36, sizeof(__pyx_k_36), 0, 0, 1, 1}, + {&__pyx_kp_s_39, __pyx_k_39, sizeof(__pyx_k_39), 0, 0, 1, 0}, + {&__pyx_n_s_40, __pyx_k_40, sizeof(__pyx_k_40), 0, 0, 1, 1}, + {&__pyx_n_s_53, __pyx_k_53, sizeof(__pyx_k_53), 0, 0, 1, 1}, + {&__pyx_kp_u_54, __pyx_k_54, sizeof(__pyx_k_54), 0, 1, 0, 0}, + {&__pyx_kp_u_55, __pyx_k_55, sizeof(__pyx_k_55), 0, 1, 0, 0}, + {&__pyx_n_s__C, __pyx_k__C, sizeof(__pyx_k__C), 0, 0, 1, 1}, + {&__pyx_n_s__DTYPE, __pyx_k__DTYPE, sizeof(__pyx_k__DTYPE), 0, 0, 1, 1}, + {&__pyx_n_s__ITYPE, __pyx_k__ITYPE, sizeof(__pyx_k__ITYPE), 0, 0, 1, 1}, + {&__pyx_n_s__N, __pyx_k__N, sizeof(__pyx_k__N), 0, 0, 1, 1}, + {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, + {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, + {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, + {&__pyx_n_s___validation, __pyx_k___validation, sizeof(__pyx_k___validation), 0, 0, 1, 1}, + {&__pyx_n_s__arange, __pyx_k__arange, sizeof(__pyx_k__arange), 0, 0, 1, 1}, + {&__pyx_n_s__argsort, __pyx_k__argsort, sizeof(__pyx_k__argsort), 0, 0, 1, 1}, + {&__pyx_n_s__array, __pyx_k__array, sizeof(__pyx_k__array), 0, 0, 1, 1}, + {&__pyx_n_s__asarray, __pyx_k__asarray, sizeof(__pyx_k__asarray), 0, 0, 1, 1}, + {&__pyx_n_s__astype, __pyx_k__astype, sizeof(__pyx_k__astype), 0, 0, 1, 1}, + {&__pyx_n_s__bool, __pyx_k__bool, sizeof(__pyx_k__bool), 0, 0, 1, 1}, + {&__pyx_n_s__c, __pyx_k__c, sizeof(__pyx_k__c), 0, 0, 1, 1}, + {&__pyx_n_s__compressed, __pyx_k__compressed, sizeof(__pyx_k__compressed), 0, 0, 1, 1}, + {&__pyx_n_s__copy, __pyx_k__copy, sizeof(__pyx_k__copy), 0, 0, 1, 1}, + {&__pyx_n_s__copy_if_dense, __pyx_k__copy_if_dense, sizeof(__pyx_k__copy_if_dense), 0, 0, 1, 1}, + {&__pyx_n_s__csgraph, __pyx_k__csgraph, sizeof(__pyx_k__csgraph), 0, 0, 1, 1}, + {&__pyx_n_s__csgraph_from_dense, __pyx_k__csgraph_from_dense, sizeof(__pyx_k__csgraph_from_dense), 0, 0, 1, 1}, + {&__pyx_n_s__csgraph_from_masked, __pyx_k__csgraph_from_masked, sizeof(__pyx_k__csgraph_from_masked), 0, 0, 1, 1}, + {&__pyx_n_s__csgraph_to_dense, __pyx_k__csgraph_to_dense, sizeof(__pyx_k__csgraph_to_dense), 0, 0, 1, 1}, + {&__pyx_n_s__csgraph_to_masked, __pyx_k__csgraph_to_masked, sizeof(__pyx_k__csgraph_to_masked), 0, 0, 1, 1}, + {&__pyx_n_s__csr_matrix, __pyx_k__csr_matrix, sizeof(__pyx_k__csr_matrix), 0, 0, 1, 1}, + {&__pyx_n_s__csr_output, __pyx_k__csr_output, sizeof(__pyx_k__csr_output), 0, 0, 1, 1}, + {&__pyx_n_s__cumsum, __pyx_k__cumsum, sizeof(__pyx_k__cumsum), 0, 0, 1, 1}, + {&__pyx_n_s__data, __pyx_k__data, sizeof(__pyx_k__data), 0, 0, 1, 1}, + {&__pyx_n_s__data1, __pyx_k__data1, sizeof(__pyx_k__data1), 0, 0, 1, 1}, + {&__pyx_n_s__data2, __pyx_k__data2, sizeof(__pyx_k__data2), 0, 0, 1, 1}, + {&__pyx_n_s__dense_output, __pyx_k__dense_output, sizeof(__pyx_k__dense_output), 0, 0, 1, 1}, + {&__pyx_n_s__directed, __pyx_k__directed, sizeof(__pyx_k__directed), 0, 0, 1, 1}, + {&__pyx_n_s__dist_matrix, __pyx_k__dist_matrix, sizeof(__pyx_k__dist_matrix), 0, 0, 1, 1}, + {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, + {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, + {&__pyx_n_s__fill, __pyx_k__fill, sizeof(__pyx_k__fill), 0, 0, 1, 1}, + {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, + {&__pyx_n_s__graph, __pyx_k__graph, sizeof(__pyx_k__graph), 0, 0, 1, 1}, + {&__pyx_n_s__idx_grid, __pyx_k__idx_grid, sizeof(__pyx_k__idx_grid), 0, 0, 1, 1}, + {&__pyx_n_s__indices, __pyx_k__indices, sizeof(__pyx_k__indices), 0, 0, 1, 1}, + {&__pyx_n_s__indptr, __pyx_k__indptr, sizeof(__pyx_k__indptr), 0, 0, 1, 1}, + {&__pyx_n_s__inf, __pyx_k__inf, sizeof(__pyx_k__inf), 0, 0, 1, 1}, + {&__pyx_n_s__infinity_null, __pyx_k__infinity_null, sizeof(__pyx_k__infinity_null), 0, 0, 1, 1}, + {&__pyx_n_s__int32, __pyx_k__int32, sizeof(__pyx_k__int32), 0, 0, 1, 1}, + {&__pyx_n_s__is_masked, __pyx_k__is_masked, sizeof(__pyx_k__is_masked), 0, 0, 1, 1}, + {&__pyx_n_s__isinf, __pyx_k__isinf, sizeof(__pyx_k__isinf), 0, 0, 1, 1}, + {&__pyx_n_s__isnan, __pyx_k__isnan, sizeof(__pyx_k__isnan), 0, 0, 1, 1}, + {&__pyx_n_s__isspmatrix, __pyx_k__isspmatrix, sizeof(__pyx_k__isspmatrix), 0, 0, 1, 1}, + {&__pyx_n_s__isspmatrix_csc, __pyx_k__isspmatrix_csc, sizeof(__pyx_k__isspmatrix_csc), 0, 0, 1, 1}, + {&__pyx_n_s__isspmatrix_csr, __pyx_k__isspmatrix_csr, sizeof(__pyx_k__isspmatrix_csr), 0, 0, 1, 1}, + {&__pyx_n_s__isspmatrix_lil, __pyx_k__isspmatrix_lil, sizeof(__pyx_k__isspmatrix_lil), 0, 0, 1, 1}, + {&__pyx_n_s__ma, __pyx_k__ma, sizeof(__pyx_k__ma), 0, 0, 1, 1}, + {&__pyx_n_s__mask, __pyx_k__mask, sizeof(__pyx_k__mask), 0, 0, 1, 1}, + {&__pyx_n_s__masked_array, __pyx_k__masked_array, sizeof(__pyx_k__masked_array), 0, 0, 1, 1}, + {&__pyx_n_s__masked_invalid, __pyx_k__masked_invalid, sizeof(__pyx_k__masked_invalid), 0, 0, 1, 1}, + {&__pyx_n_s__masked_values, __pyx_k__masked_values, sizeof(__pyx_k__masked_values), 0, 0, 1, 1}, + {&__pyx_n_s__minimum, __pyx_k__minimum, sizeof(__pyx_k__minimum), 0, 0, 1, 1}, + {&__pyx_n_s__nan, __pyx_k__nan, sizeof(__pyx_k__nan), 0, 0, 1, 1}, + {&__pyx_n_s__nan_null, __pyx_k__nan_null, sizeof(__pyx_k__nan_null), 0, 0, 1, 1}, + {&__pyx_n_s__ndim, __pyx_k__ndim, sizeof(__pyx_k__ndim), 0, 0, 1, 1}, + {&__pyx_n_s__nnull, __pyx_k__nnull, sizeof(__pyx_k__nnull), 0, 0, 1, 1}, + {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, + {&__pyx_n_s__null_value, __pyx_k__null_value, sizeof(__pyx_k__null_value), 0, 0, 1, 1}, + {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, + {&__pyx_n_s__ones, __pyx_k__ones, sizeof(__pyx_k__ones), 0, 0, 1, 1}, + {&__pyx_n_s__order, __pyx_k__order, sizeof(__pyx_k__order), 0, 0, 1, 1}, + {&__pyx_n_s__pind, __pyx_k__pind, sizeof(__pyx_k__pind), 0, 0, 1, 1}, + {&__pyx_n_s__predecessors, __pyx_k__predecessors, sizeof(__pyx_k__predecessors), 0, 0, 1, 1}, + {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, + {&__pyx_n_s__ravel, __pyx_k__ravel, sizeof(__pyx_k__ravel), 0, 0, 1, 1}, + {&__pyx_n_s__reconstruct_path, __pyx_k__reconstruct_path, sizeof(__pyx_k__reconstruct_path), 0, 0, 1, 1}, + {&__pyx_n_s__searchsorted, __pyx_k__searchsorted, sizeof(__pyx_k__searchsorted), 0, 0, 1, 1}, + {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, + {&__pyx_n_s__sum, __pyx_k__sum, sizeof(__pyx_k__sum), 0, 0, 1, 1}, + {&__pyx_n_s__tocsr, __pyx_k__tocsr, sizeof(__pyx_k__tocsr), 0, 0, 1, 1}, + {&__pyx_n_s__validate_graph, __pyx_k__validate_graph, sizeof(__pyx_k__validate_graph), 0, 0, 1, 1}, + {&__pyx_n_s__zeros, __pyx_k__zeros, sizeof(__pyx_k__zeros), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "sklearn/utils/_graph_tools.pyx":48 + * + * if graph.ndim != 2: + * raise ValueError("graph should have two dimensions") # <<<<<<<<<<<<<< + * N = graph.shape[0] + * if graph.shape[1] != N: + */ + __pyx_k_tuple_2 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_2); + __Pyx_INCREF(((PyObject *)__pyx_kp_s_1)); + PyTuple_SET_ITEM(__pyx_k_tuple_2, 0, ((PyObject *)__pyx_kp_s_1)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_1)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); + + /* "sklearn/utils/_graph_tools.pyx":51 + * N = graph.shape[0] + * if graph.shape[1] != N: + * raise ValueError("graph should be a square array") # <<<<<<<<<<<<<< + * + * # construct the csr matrix using graph and mask + */ + __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_4); + __Pyx_INCREF(((PyObject *)__pyx_kp_s_3)); + PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_s_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); + + /* "sklearn/utils/_graph_tools.pyx":68 + * + * indptr = np.zeros(N + 1, dtype=ITYPE) + * indptr[1:] = mask.sum(1).cumsum() # <<<<<<<<<<<<<< + * + * return csr_matrix((data, indices, indptr), (N, N)) + */ + __pyx_k_tuple_5 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_5); + __Pyx_INCREF(__pyx_int_1); + PyTuple_SET_ITEM(__pyx_k_tuple_5, 0, __pyx_int_1); + __Pyx_GIVEREF(__pyx_int_1); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); + + /* "sklearn/utils/_graph_tools.pyx":107 + * # check that graph is a square matrix + * if graph.ndim != 2: + * raise ValueError("graph should have two dimensions") # <<<<<<<<<<<<<< + * N = graph.shape[0] + * if graph.shape[1] != N: + */ + __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_9); + __Pyx_INCREF(((PyObject *)__pyx_kp_s_1)); + PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_s_1)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_1)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); + + /* "sklearn/utils/_graph_tools.pyx":110 + * N = graph.shape[0] + * if graph.shape[1] != N: + * raise ValueError("graph should be a square array") # <<<<<<<<<<<<<< + * + * # check whether null_value is infinity or NaN + */ + __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_10); + __Pyx_INCREF(((PyObject *)__pyx_kp_s_3)); + PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_s_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + + /* "sklearn/utils/_graph_tools.pyx":248 + * csgraph = csgraph.tocsr() + * elif not isspmatrix_csr(csgraph): + * raise ValueError("csgraph must be lil, csr, or csc format") # <<<<<<<<<<<<<< + * + * N = csgraph.shape[0] + */ + __pyx_k_tuple_15 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 248; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_15); + __Pyx_INCREF(((PyObject *)__pyx_kp_s_14)); + PyTuple_SET_ITEM(__pyx_k_tuple_15, 0, ((PyObject *)__pyx_kp_s_14)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_14)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_15)); + + /* "sklearn/utils/_graph_tools.pyx":252 + * N = csgraph.shape[0] + * if csgraph.shape[1] != N: + * raise ValueError('csgraph should be a square matrix') # <<<<<<<<<<<<<< + * + * # get attribute arrays + */ + __pyx_k_tuple_17 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_17); + __Pyx_INCREF(((PyObject *)__pyx_kp_s_16)); + PyTuple_SET_ITEM(__pyx_k_tuple_17, 0, ((PyObject *)__pyx_kp_s_16)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_16)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_17)); + + /* "sklearn/utils/_graph_tools.pyx":414 + * + * if predecessors.shape != graph.shape: + * raise ValueError("graph and predecessors must have the same shape") # <<<<<<<<<<<<<< + * + * dist_matrix = np.zeros(graph.shape, dtype=DTYPE) + */ + __pyx_k_tuple_22 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_22)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_22); + __Pyx_INCREF(((PyObject *)__pyx_kp_s_21)); + PyTuple_SET_ITEM(__pyx_k_tuple_22, 0, ((PyObject *)__pyx_kp_s_21)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_21)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_22)); + + /* "numpy.pxd":214 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_k_tuple_24 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_24)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_24); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_23)); + PyTuple_SET_ITEM(__pyx_k_tuple_24, 0, ((PyObject *)__pyx_kp_u_23)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_23)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_24)); + + /* "numpy.pxd":218 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_k_tuple_26 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_26)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_26); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_25)); + PyTuple_SET_ITEM(__pyx_k_tuple_26, 0, ((PyObject *)__pyx_kp_u_25)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_25)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_26)); + + /* "numpy.pxd":256 + * if ((descr.byteorder == '>' and little_endian) or + * (descr.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_k_tuple_28 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_28)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_28); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_27)); + PyTuple_SET_ITEM(__pyx_k_tuple_28, 0, ((PyObject *)__pyx_kp_u_27)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_27)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_28)); + + /* "numpy.pxd":798 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == '>' and little_endian) or + */ + __pyx_k_tuple_31 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_31)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_31); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_30)); + PyTuple_SET_ITEM(__pyx_k_tuple_31, 0, ((PyObject *)__pyx_kp_u_30)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_30)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_31)); + + /* "numpy.pxd":802 + * if ((child.byteorder == '>' and little_endian) or + * (child.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_k_tuple_32 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_32)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_32); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_27)); + PyTuple_SET_ITEM(__pyx_k_tuple_32, 0, ((PyObject *)__pyx_kp_u_27)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_27)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_32)); + + /* "numpy.pxd":822 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_k_tuple_34 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_34)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_34); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_33)); + PyTuple_SET_ITEM(__pyx_k_tuple_34, 0, ((PyObject *)__pyx_kp_u_33)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_33)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_34)); + + /* "sklearn/utils/_graph_tools.pyx":26 + * cdef ITYPE_t NULL_IDX = -9999 + * + * def csgraph_from_masked(graph): # <<<<<<<<<<<<<< + * """ + * csgraph_from_masked(graph) + */ + __pyx_k_tuple_37 = PyTuple_New(7); if (unlikely(!__pyx_k_tuple_37)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_37); + __Pyx_INCREF(((PyObject *)__pyx_n_s__graph)); + PyTuple_SET_ITEM(__pyx_k_tuple_37, 0, ((PyObject *)__pyx_n_s__graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__graph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__N)); + PyTuple_SET_ITEM(__pyx_k_tuple_37, 1, ((PyObject *)__pyx_n_s__N)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__N)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__data)); + PyTuple_SET_ITEM(__pyx_k_tuple_37, 2, ((PyObject *)__pyx_n_s__data)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__data)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__mask)); + PyTuple_SET_ITEM(__pyx_k_tuple_37, 3, ((PyObject *)__pyx_n_s__mask)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__mask)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__idx_grid)); + PyTuple_SET_ITEM(__pyx_k_tuple_37, 4, ((PyObject *)__pyx_n_s__idx_grid)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__idx_grid)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__indices)); + PyTuple_SET_ITEM(__pyx_k_tuple_37, 5, ((PyObject *)__pyx_n_s__indices)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__indices)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__indptr)); + PyTuple_SET_ITEM(__pyx_k_tuple_37, 6, ((PyObject *)__pyx_n_s__indptr)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__indptr)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_37)); + __pyx_k_codeobj_38 = (PyObject*)__Pyx_PyCode_New(1, 0, 7, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_37, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_39, __pyx_n_s__csgraph_from_masked, 26, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_38)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/_graph_tools.pyx":73 + * + * + * def csgraph_masked_from_dense(graph, # <<<<<<<<<<<<<< + * null_value=0, + * nan_null=True, + */ + __pyx_k_tuple_41 = PyTuple_New(7); if (unlikely(!__pyx_k_tuple_41)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_41); + __Pyx_INCREF(((PyObject *)__pyx_n_s__graph)); + PyTuple_SET_ITEM(__pyx_k_tuple_41, 0, ((PyObject *)__pyx_n_s__graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__graph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__null_value)); + PyTuple_SET_ITEM(__pyx_k_tuple_41, 1, ((PyObject *)__pyx_n_s__null_value)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__null_value)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__nan_null)); + PyTuple_SET_ITEM(__pyx_k_tuple_41, 2, ((PyObject *)__pyx_n_s__nan_null)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nan_null)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__infinity_null)); + PyTuple_SET_ITEM(__pyx_k_tuple_41, 3, ((PyObject *)__pyx_n_s__infinity_null)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__infinity_null)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__copy)); + PyTuple_SET_ITEM(__pyx_k_tuple_41, 4, ((PyObject *)__pyx_n_s__copy)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__copy)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__N)); + PyTuple_SET_ITEM(__pyx_k_tuple_41, 5, ((PyObject *)__pyx_n_s__N)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__N)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__mask)); + PyTuple_SET_ITEM(__pyx_k_tuple_41, 6, ((PyObject *)__pyx_n_s__mask)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__mask)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_41)); + __pyx_k_codeobj_42 = (PyObject*)__Pyx_PyCode_New(5, 0, 7, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_41, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_39, __pyx_n_s_13, 73, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_42)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/_graph_tools.pyx":138 + * + * + * def csgraph_from_dense(graph, # <<<<<<<<<<<<<< + * null_value=0, + * nan_null=True, + */ + __pyx_k_tuple_43 = PyTuple_New(4); if (unlikely(!__pyx_k_tuple_43)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_43); + __Pyx_INCREF(((PyObject *)__pyx_n_s__graph)); + PyTuple_SET_ITEM(__pyx_k_tuple_43, 0, ((PyObject *)__pyx_n_s__graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__graph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__null_value)); + PyTuple_SET_ITEM(__pyx_k_tuple_43, 1, ((PyObject *)__pyx_n_s__null_value)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__null_value)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__nan_null)); + PyTuple_SET_ITEM(__pyx_k_tuple_43, 2, ((PyObject *)__pyx_n_s__nan_null)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nan_null)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__infinity_null)); + PyTuple_SET_ITEM(__pyx_k_tuple_43, 3, ((PyObject *)__pyx_n_s__infinity_null)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__infinity_null)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_43)); + __pyx_k_codeobj_44 = (PyObject*)__Pyx_PyCode_New(4, 0, 4, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_43, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_39, __pyx_n_s__csgraph_from_dense, 138, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_44)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/_graph_tools.pyx":172 + * + * + * def csgraph_to_dense(csgraph, null_value=0): # <<<<<<<<<<<<<< + * """ + * csgraph_to_dense(csgraph, null_value=0) + */ + __pyx_k_tuple_45 = PyTuple_New(7); if (unlikely(!__pyx_k_tuple_45)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_45); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csgraph)); + PyTuple_SET_ITEM(__pyx_k_tuple_45, 0, ((PyObject *)__pyx_n_s__csgraph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csgraph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__null_value)); + PyTuple_SET_ITEM(__pyx_k_tuple_45, 1, ((PyObject *)__pyx_n_s__null_value)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__null_value)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__N)); + PyTuple_SET_ITEM(__pyx_k_tuple_45, 2, ((PyObject *)__pyx_n_s__N)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__N)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__data)); + PyTuple_SET_ITEM(__pyx_k_tuple_45, 3, ((PyObject *)__pyx_n_s__data)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__data)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__indices)); + PyTuple_SET_ITEM(__pyx_k_tuple_45, 4, ((PyObject *)__pyx_n_s__indices)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__indices)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__indptr)); + PyTuple_SET_ITEM(__pyx_k_tuple_45, 5, ((PyObject *)__pyx_n_s__indptr)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__indptr)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__graph)); + PyTuple_SET_ITEM(__pyx_k_tuple_45, 6, ((PyObject *)__pyx_n_s__graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_45)); + __pyx_k_codeobj_46 = (PyObject*)__Pyx_PyCode_New(2, 0, 7, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_45, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_39, __pyx_n_s__csgraph_to_dense, 172, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_46)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/_graph_tools.pyx":266 + * + * + * def csgraph_to_masked(csgraph): # <<<<<<<<<<<<<< + * """ + * csgraph_to_masked(csgraph) + */ + __pyx_k_tuple_47 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_47)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_47); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csgraph)); + PyTuple_SET_ITEM(__pyx_k_tuple_47, 0, ((PyObject *)__pyx_n_s__csgraph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csgraph)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_47)); + __pyx_k_codeobj_48 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_47, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_39, __pyx_n_s__csgraph_to_masked, 266, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_48)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/_graph_tools.pyx":312 + * + * + * def reconstruct_path(csgraph, predecessors, directed=True): # <<<<<<<<<<<<<< + * """ + * reconstruct_path(csgraph, predecessors, directed=True) + */ + __pyx_k_tuple_49 = PyTuple_New(12); if (unlikely(!__pyx_k_tuple_49)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_49); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csgraph)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 0, ((PyObject *)__pyx_n_s__csgraph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csgraph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__predecessors)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 1, ((PyObject *)__pyx_n_s__predecessors)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__predecessors)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__directed)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 2, ((PyObject *)__pyx_n_s__directed)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__directed)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__validate_graph)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 3, ((PyObject *)__pyx_n_s__validate_graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__validate_graph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__N)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 4, ((PyObject *)__pyx_n_s__N)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__N)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__nnull)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 5, ((PyObject *)__pyx_n_s__nnull)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__nnull)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__indices)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 6, ((PyObject *)__pyx_n_s__indices)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__indices)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__pind)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 7, ((PyObject *)__pyx_n_s__pind)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__pind)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__indptr)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 8, ((PyObject *)__pyx_n_s__indptr)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__indptr)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__data)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 9, ((PyObject *)__pyx_n_s__data)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__data)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__data1)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 10, ((PyObject *)__pyx_n_s__data1)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__data1)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__data2)); + PyTuple_SET_ITEM(__pyx_k_tuple_49, 11, ((PyObject *)__pyx_n_s__data2)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__data2)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_49)); + __pyx_k_codeobj_50 = (PyObject*)__Pyx_PyCode_New(3, 0, 12, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_49, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_39, __pyx_n_s__reconstruct_path, 312, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_50)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/_graph_tools.pyx":365 + * + * + * def construct_dist_matrix(graph, # <<<<<<<<<<<<<< + * predecessors, + * directed=True, + */ + __pyx_k_tuple_51 = PyTuple_New(6); if (unlikely(!__pyx_k_tuple_51)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 365; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_51); + __Pyx_INCREF(((PyObject *)__pyx_n_s__graph)); + PyTuple_SET_ITEM(__pyx_k_tuple_51, 0, ((PyObject *)__pyx_n_s__graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__graph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__predecessors)); + PyTuple_SET_ITEM(__pyx_k_tuple_51, 1, ((PyObject *)__pyx_n_s__predecessors)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__predecessors)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__directed)); + PyTuple_SET_ITEM(__pyx_k_tuple_51, 2, ((PyObject *)__pyx_n_s__directed)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__directed)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__null_value)); + PyTuple_SET_ITEM(__pyx_k_tuple_51, 3, ((PyObject *)__pyx_n_s__null_value)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__null_value)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__validate_graph)); + PyTuple_SET_ITEM(__pyx_k_tuple_51, 4, ((PyObject *)__pyx_n_s__validate_graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__validate_graph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__dist_matrix)); + PyTuple_SET_ITEM(__pyx_k_tuple_51, 5, ((PyObject *)__pyx_n_s__dist_matrix)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__dist_matrix)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_51)); + __pyx_k_codeobj_52 = (PyObject*)__Pyx_PyCode_New(4, 0, 6, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_51, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_39, __pyx_n_s_53, 365, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_52)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 365; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC init_graph_tools(void); /*proto*/ +PyMODINIT_FUNC init_graph_tools(void) +#else +PyMODINIT_FUNC PyInit__graph_tools(void); /*proto*/ +PyMODINIT_FUNC PyInit__graph_tools(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__graph_tools(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_graph_tools"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_35), 0, PYTHON_API_VERSION); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + #if PY_MAJOR_VERSION < 3 + Py_INCREF(__pyx_m); + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); + if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_module_is_main_sklearn__utils___graph_tools) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + /*--- Type import code ---*/ + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/utils/_graph_tools.pyx":8 + * # License: BSD, (C) 2012 + * + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":11 + * cimport numpy as np + * + * from scipy.sparse import csr_matrix, isspmatrix,\ # <<<<<<<<<<<<<< + * isspmatrix_csr, isspmatrix_csc, isspmatrix_lil + * + */ + __pyx_t_1 = PyList_New(5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csr_matrix)); + PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s__csr_matrix)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csr_matrix)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__isspmatrix)); + PyList_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_n_s__isspmatrix)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__isspmatrix)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__isspmatrix_csr)); + PyList_SET_ITEM(__pyx_t_1, 2, ((PyObject *)__pyx_n_s__isspmatrix_csr)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__isspmatrix_csr)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__isspmatrix_csc)); + PyList_SET_ITEM(__pyx_t_1, 3, ((PyObject *)__pyx_n_s__isspmatrix_csc)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__isspmatrix_csc)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__isspmatrix_lil)); + PyList_SET_ITEM(__pyx_t_1, 4, ((PyObject *)__pyx_n_s__isspmatrix_lil)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__isspmatrix_lil)); + __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s_36), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__csr_matrix); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__csr_matrix); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__csr_matrix, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isspmatrix); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__isspmatrix); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__isspmatrix, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isspmatrix_csr); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__isspmatrix_csr); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__isspmatrix_csr, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isspmatrix_csc); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__isspmatrix_csc); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__isspmatrix_csc, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isspmatrix_lil); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__isspmatrix_lil); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__isspmatrix_lil, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":14 + * isspmatrix_csr, isspmatrix_csc, isspmatrix_lil + * + * DTYPE = np.float64 # <<<<<<<<<<<<<< + * ctypedef np.float64_t DTYPE_t + * + */ + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__DTYPE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":17 + * ctypedef np.float64_t DTYPE_t + * + * ITYPE = np.int32 # <<<<<<<<<<<<<< + * ctypedef np.int32_t ITYPE_t + * + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__int32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__ITYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":21 + * + * # EPS is the precision of DTYPE + * cdef DTYPE_t DTYPE_EPS = 1E-15 # <<<<<<<<<<<<<< + * + * # NULL_IDX is the index used in predecessor matrices to store a non-path + */ + __pyx_v_7sklearn_5utils_12_graph_tools_DTYPE_EPS = 1E-15; + + /* "sklearn/utils/_graph_tools.pyx":24 + * + * # NULL_IDX is the index used in predecessor matrices to store a non-path + * cdef ITYPE_t NULL_IDX = -9999 # <<<<<<<<<<<<<< + * + * def csgraph_from_masked(graph): + */ + __pyx_v_7sklearn_5utils_12_graph_tools_NULL_IDX = -9999; + + /* "sklearn/utils/_graph_tools.pyx":26 + * cdef ITYPE_t NULL_IDX = -9999 + * + * def csgraph_from_masked(graph): # <<<<<<<<<<<<<< + * """ + * csgraph_from_masked(graph) + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_12_graph_tools_1csgraph_from_masked, NULL, __pyx_n_s_40); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__csgraph_from_masked, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":75 + * def csgraph_masked_from_dense(graph, + * null_value=0, + * nan_null=True, # <<<<<<<<<<<<<< + * infinity_null=True, + * copy=True): + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_6 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":76 + * null_value=0, + * nan_null=True, + * infinity_null=True, # <<<<<<<<<<<<<< + * copy=True): + * """ + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_7 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":77 + * nan_null=True, + * infinity_null=True, + * copy=True): # <<<<<<<<<<<<<< + * """ + * csgraph_masked_from_dense(graph, null_value=0, nan_null=True, + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_8 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":73 + * + * + * def csgraph_masked_from_dense(graph, # <<<<<<<<<<<<<< + * null_value=0, + * nan_null=True, + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_12_graph_tools_3csgraph_masked_from_dense, NULL, __pyx_n_s_40); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_13, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":140 + * def csgraph_from_dense(graph, + * null_value=0, + * nan_null=True, # <<<<<<<<<<<<<< + * infinity_null=True): + * """ + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_11 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":141 + * null_value=0, + * nan_null=True, + * infinity_null=True): # <<<<<<<<<<<<<< + * """ + * csgraph_from_dense(graph, null_value=0, nan_null=True, infinity_null=True) + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_12 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":138 + * + * + * def csgraph_from_dense(graph, # <<<<<<<<<<<<<< + * null_value=0, + * nan_null=True, + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_12_graph_tools_5csgraph_from_dense, NULL, __pyx_n_s_40); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__csgraph_from_dense, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":172 + * + * + * def csgraph_to_dense(csgraph, null_value=0): # <<<<<<<<<<<<<< + * """ + * csgraph_to_dense(csgraph, null_value=0) + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_12_graph_tools_7csgraph_to_dense, NULL, __pyx_n_s_40); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__csgraph_to_dense, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":266 + * + * + * def csgraph_to_masked(csgraph): # <<<<<<<<<<<<<< + * """ + * csgraph_to_masked(csgraph) + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_12_graph_tools_9csgraph_to_masked, NULL, __pyx_n_s_40); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__csgraph_to_masked, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":312 + * + * + * def reconstruct_path(csgraph, predecessors, directed=True): # <<<<<<<<<<<<<< + * """ + * reconstruct_path(csgraph, predecessors, directed=True) + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_18 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_12_graph_tools_11reconstruct_path, NULL, __pyx_n_s_40); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__reconstruct_path, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":367 + * def construct_dist_matrix(graph, + * predecessors, + * directed=True, # <<<<<<<<<<<<<< + * null_value=np.inf): + * """ + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 367; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_19 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/utils/_graph_tools.pyx":368 + * predecessors, + * directed=True, + * null_value=np.inf): # <<<<<<<<<<<<<< + * """ + * construct_dist_matrix(graph, predecessors, directed=True, null_value=np.inf) + */ + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__inf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_k_20 = __pyx_t_1; + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":365 + * + * + * def construct_dist_matrix(graph, # <<<<<<<<<<<<<< + * predecessors, + * directed=True, + */ + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_12_graph_tools_13construct_dist_matrix, NULL, __pyx_n_s_40); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 365; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_53, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 365; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/_graph_tools.pyx":1 + * """ # <<<<<<<<<<<<<< + * Tools and utilities for working with compressed sparse graphs + * """ + */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_54), ((PyObject *)__pyx_kp_u_55)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + + /* "numpy.pxd":974 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.utils._graph_tools", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.utils._graph_tools"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { + PyObject *result; + result = PyObject_GetAttr(dict, name); + if (!result) { + if (dict != __pyx_b) { + PyErr_Clear(); + result = PyObject_GetAttr(__pyx_b, name); + } + if (!result) { + PyErr_SetObject(PyExc_NameError, name); + } + } + return result; +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + Py_XINCREF(value); + Py_XINCREF(tb); + if (tb == Py_None) { + Py_DECREF(tb); + tb = 0; + } + else if (tb != NULL && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + if (value == NULL) { + value = Py_None; + Py_INCREF(value); + } + #if PY_VERSION_HEX < 0x02050000 + if (!PyClass_Check(type)) + #else + if (!PyType_Check(type)) + #endif + { + if (value != Py_None) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + Py_DECREF(value); + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } + else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (!PyExceptionClass_Check(type)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } + else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } + else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + if (!value) { + value = PyObject_CallObject(type, NULL); + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + return; +} +#endif + + + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AS_STRING(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + } else { + #if PY_MAJOR_VERSION < 3 + if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { + #else + if (unlikely(!PyUnicode_Check(key))) { + #endif + goto invalid_keyword_type; + } else { + for (name = first_kw_arg; *name; name++) { + #if PY_MAJOR_VERSION >= 3 + if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && + PyUnicode_Compare(**name, key) == 0) break; + #else + if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && + _PyString_Eq(**name, key)) break; + #endif + } + if (*name) { + values[name-argnames] = value; + } else { + for (name=argnames; name != first_kw_arg; name++) { + if (**name == key) goto arg_passed_twice; + #if PY_MAJOR_VERSION >= 3 + if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && + PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; + #else + if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && + _PyString_Eq(**name, key)) goto arg_passed_twice; + #endif + } + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + } + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, **name); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'b': return "'char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; /* Consume from buffer string */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + if (isspace(*ts)) + continue; + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case 10: + case 13: + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } /* fall through */ + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 's': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + } else { + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + } + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static void __Pyx_RaiseBufferIndexError(int axis) { + PyErr_Format(PyExc_IndexError, + "Out of bounds on buffer access (axis %d)", axis); +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { + if (t == Py_None) { + __Pyx_RaiseNoneNotIterableError(); + } else if (PyTuple_GET_SIZE(t) < index) { + __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); + } else { + __Pyx_RaiseTooManyValuesError(index); + } +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + PyObject *getbuffer_cobj; + + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + #endif + + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict && + (getbuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, + "__pyx_getbuffer"))) { + getbufferproc func; + + #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + func = (getbufferproc) PyCapsule_GetPointer(getbuffer_cobj, "getbuffer(obj, view, flags)"); + #else + func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + #endif + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + + return func(obj, view, flags); + } else { + PyErr_Clear(); + } + #endif + + PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); + +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + + return -1; +} + +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + PyObject *releasebuffer_cobj; + + if (!obj) return; + + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict && + (releasebuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, + "__pyx_releasebuffer"))) { + releasebufferproc func; + + #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + func = (releasebufferproc) PyCapsule_GetPointer(releasebuffer_cobj, "releasebuffer(obj, view)"); + #else + func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + #endif + + Py_DECREF(releasebuffer_cobj); + + if (!func) + goto fail; + + func(obj, view); + return; + } else { + PyErr_Clear(); + } + #endif + + goto nofail; + +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); + +nofail: + Py_DECREF(obj); + view->obj = NULL; +} + +#endif /* PY_MAJOR_VERSION < 3 */ + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { + PyObject *py_import = 0; + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); + if (!py_import) + goto bad; + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + /* try package relative import first */ + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + Py_XDECREF(empty_list); + Py_XDECREF(py_import); + Py_XDECREF(empty_dict); + return module; +} + +static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name) { +#if PY_MAJOR_VERSION < 3 + PyErr_Format(PyExc_ImportError, "cannot import name %.230s", + PyString_AsString(name)); +#else + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); +#endif +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { + const unsigned char neg_one = (unsigned char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned char" : + "value too large to convert to unsigned char"); + } + return (unsigned char)-1; + } + return (unsigned char)val; + } + return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { + const unsigned short neg_one = (unsigned short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned short" : + "value too large to convert to unsigned short"); + } + return (unsigned short)-1; + } + return (unsigned short)val; + } + return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { + const unsigned int neg_one = (unsigned int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned int" : + "value too large to convert to unsigned int"); + } + return (unsigned int)-1; + } + return (unsigned int)val; + } + return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { + const char neg_one = (char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to char" : + "value too large to convert to char"); + } + return (char)-1; + } + return (char)val; + } + return (char)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { + const short neg_one = (short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to short" : + "value too large to convert to short"); + } + return (short)-1; + } + return (short)val; + } + return (short)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { + const signed char neg_one = (signed char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed char" : + "value too large to convert to signed char"); + } + return (signed char)-1; + } + return (signed char)val; + } + return (signed char)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { + const signed short neg_one = (signed short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed short" : + "value too large to convert to signed short"); + } + return (signed short)-1; + } + return (signed short)val; + } + return (signed short)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { + const signed int neg_one = (signed int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed int" : + "value too large to convert to signed int"); + } + return (signed int)-1; + } + return (signed int)val; + } + return (signed int)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { + const unsigned long neg_one = (unsigned long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)PyLong_AsUnsignedLong(x); + } else { + return (unsigned long)PyLong_AsLong(x); + } + } else { + unsigned long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned long)-1; + val = __Pyx_PyInt_AsUnsignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { + const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { + return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + unsigned PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsUnsignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { + const long neg_one = (long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)PyLong_AsUnsignedLong(x); + } else { + return (long)PyLong_AsLong(x); + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long)-1; + val = __Pyx_PyInt_AsLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { + const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { + return (PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { + const signed long neg_one = (signed long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)PyLong_AsUnsignedLong(x); + } else { + return (signed long)PyLong_AsLong(x); + } + } else { + signed long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed long)-1; + val = __Pyx_PyInt_AsSignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { + const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { + return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + signed PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsSignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%s.%s is not a type object", + module_name, class_name); + goto bad; + } + if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + #if PY_VERSION_HEX < 0x02050000 + if (PyErr_Warn(NULL, warning) < 0) goto bad; + #else + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + #endif + } + else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%s.%s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + + +/* Type Conversion Functions */ + +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} + +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_VERSION_HEX < 0x03000000 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_VERSION_HEX < 0x03000000 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_VERSION_HEX < 0x03000000 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%s__ returned non-%s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} + +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject* x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} + +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} + +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { + unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); + if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { + return (size_t)-1; + } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); + return (size_t)-1; + } + return (size_t)val; +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/utils/sparsetools/_graph_tools.pyx b/sklearn/utils/sparsetools/_graph_tools.pyx new file mode 100644 index 0000000000000..e44f8623ddaed --- /dev/null +++ b/sklearn/utils/sparsetools/_graph_tools.pyx @@ -0,0 +1,460 @@ +""" +Tools and utilities for working with compressed sparse graphs +""" + +# Author: Jake Vanderplas -- +# License: BSD, (C) 2012 + +import numpy as np +cimport numpy as np + +from scipy.sparse import csr_matrix, isspmatrix,\ + isspmatrix_csr, isspmatrix_csc, isspmatrix_lil + +DTYPE = np.float64 +ctypedef np.float64_t DTYPE_t + +ITYPE = np.int32 +ctypedef np.int32_t ITYPE_t + +# EPS is the precision of DTYPE +cdef DTYPE_t DTYPE_EPS = 1E-15 + +# NULL_IDX is the index used in predecessor matrices to store a non-path +cdef ITYPE_t NULL_IDX = -9999 + +def csgraph_from_masked(graph): + """ + csgraph_from_masked(graph) + + Construct a CSR-format graph from a masked array. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + graph : MaskedArray + Input graph. Shape should be (n_nodes, n_nodes). + + Returns + ------- + csgraph : csr_matrix + Compressed sparse representation of graph, + """ + # check that graph is a square matrix + graph = np.ma.asarray(graph) + + if graph.ndim != 2: + raise ValueError("graph should have two dimensions") + N = graph.shape[0] + if graph.shape[1] != N: + raise ValueError("graph should be a square array") + + # construct the csr matrix using graph and mask + if np.ma.is_masked(graph): + data = graph.compressed() + mask = ~graph.mask + else: + data = graph.data + mask = np.ones(graph.shape, dtype='bool') + + data = np.asarray(data, dtype=DTYPE, order='c') + + idx_grid = np.empty((N, N), dtype=ITYPE) + idx_grid[:] = np.arange(N, dtype=ITYPE) + indices = np.asarray(idx_grid[mask], dtype=ITYPE, order='c') + + indptr = np.zeros(N + 1, dtype=ITYPE) + indptr[1:] = mask.sum(1).cumsum() + + return csr_matrix((data, indices, indptr), (N, N)) + + +def csgraph_masked_from_dense(graph, + null_value=0, + nan_null=True, + infinity_null=True, + copy=True): + """ + csgraph_masked_from_dense(graph, null_value=0, nan_null=True, + infinity_null=True, copy=True) + + Construct a masked array graph representation from a dense matrix. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + graph : array_like + Input graph. Shape should be (n_nodes, n_nodes). + null_value : float or None (optional) + Value that denotes non-edges in the graph. Default is zero. + infinity_null : bool + If True (default), then infinite entries (both positive and negative) + are treated as null edges. + nan_null : bool + If True (default), then NaN entries are treated as non-edges + + Returns + ------- + csgraph : MaskedArray + masked array representation of graph + """ + graph = np.array(graph, copy=copy) + + # check that graph is a square matrix + if graph.ndim != 2: + raise ValueError("graph should have two dimensions") + N = graph.shape[0] + if graph.shape[1] != N: + raise ValueError("graph should be a square array") + + # check whether null_value is infinity or NaN + if null_value is not None: + null_value = DTYPE(null_value) + if np.isnan(null_value): + nan_null = True + null_value = None + elif np.isinf(null_value): + infinity_null = True + null_value = None + + # flag all the null edges + if null_value is None: + mask = np.zeros(graph.shape, dtype='bool') + graph = np.ma.masked_array(graph, mask, copy=False) + else: + graph = np.ma.masked_values(graph, null_value, copy=False) + + if infinity_null: + graph.mask |= np.isinf(graph) + + if nan_null: + graph.mask |= np.isnan(graph) + + return graph + + +def csgraph_from_dense(graph, + null_value=0, + nan_null=True, + infinity_null=True): + """ + csgraph_from_dense(graph, null_value=0, nan_null=True, infinity_null=True) + + Construct a CSR-format sparse graph from a dense matrix. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + graph : array_like + Input graph. Shape should be (n_nodes, n_nodes). + null_value : float or None (optional) + Value that denotes non-edges in the graph. Default is zero. + infinity_null : bool + If True (default), then infinite entries (both positive and negative) + are treated as null edges. + nan_null : bool + If True (default), then NaN entries are treated as non-edges + + Returns + ------- + csgraph : csr_matrix + Compressed sparse representation of graph, + """ + return csgraph_from_masked(csgraph_masked_from_dense(graph, + null_value, + nan_null, + infinity_null)) + + +def csgraph_to_dense(csgraph, null_value=0): + """ + csgraph_to_dense(csgraph, null_value=0) + + Convert a sparse graph representation to a dense representation + + .. versionadded:: 0.11.0 + + Parameters + ---------- + csgraph : csr_matrix, csc_matrix, or lil_matrix + Sparse representation of a graph. + null_value : float, optional + The value used to indicate null edges in the dense representation. + Default is 0. + + Returns + ------- + graph : ndarray + The dense representation of the sparse graph. + + Notes + ----- + For normal sparse graph representations, calling csgraph_to_dense with + null_value=0 produces an equivalent result to using dense format + conversions in the main sparse package. When the sparse representations + have repeated values, however, the results will differ. The tools in + scipy.sparse will add repeating values to obtain a final value. This + function will select the minimum among repeating values to obtain a + final value. For example, here we'll create a two-node directed sparse + graph with multiple edges from node 0 to node 1, of weights 2 and 3. + This illustrates the difference in behavior: + + >>> from scipy.sparse import csr_matrix + >>> data = np.array([2, 3]) + >>> indices = np.array([1, 1]) + >>> indptr = np.array([0, 2, 2]) + >>> M = csr_matrix((data, indices, indptr), shape=(2, 2)) + >>> M.toarray() + array([[0, 5], + [0, 0]]) + >>> csgraph_to_dense(M) + array([[0, 2], + [0, 0]]) + + The reason for this difference is to allow a compressed sparse graph to + represent multiple edges between any two nodes. As most sparse graph + algorithms are concerned with the single lowest-cost edge between any + two nodes, the default scipy.sparse behavior of summming multiple weights + does not make sense in this context. + + The other reason for using this routine is to allow for graphs with + zero-weight edges. Let's look at the example of a two-node directed + graph, connected by an edge of weight zero: + + >>> from scipy.sparse import csr_matrix + >>> data = np.array([0.0]) + >>> indices = np.array([1]) + >>> indptr = np.array([0, 2, 2]) + >>> M = csr_matrix((data, indices, indptr), shape=(2, 2)) + >>> M.toarray() + array([[0, 0], + [0, 0]]) + >>> csgraph_to_dense(M, np.inf) + array([[ Inf, 0.], + [ Inf, Inf]]) + + In the first case, the zero-weight edge gets lost in the dense + representation. In the second case, we can choose a different null value + and see the true form of the graph. + """ + # Allow only csr, lil and csc matrices: other formats when converted to csr + # combine duplicated edges: we don't want this to happen in the background. + if isspmatrix_csc(csgraph) or isspmatrix_lil(csgraph): + csgraph = csgraph.tocsr() + elif not isspmatrix_csr(csgraph): + raise ValueError("csgraph must be lil, csr, or csc format") + + N = csgraph.shape[0] + if csgraph.shape[1] != N: + raise ValueError('csgraph should be a square matrix') + + # get attribute arrays + data = np.asarray(csgraph.data, dtype=DTYPE, order='C') + indices = np.asarray(csgraph.indices, dtype=ITYPE, order='C') + indptr = np.asarray(csgraph.indptr, dtype=ITYPE, order='C') + + # create the output array + graph = np.empty(csgraph.shape, dtype=DTYPE) + graph.fill(np.inf) + _populate_graph(data, indices, indptr, graph, null_value) + return graph + + +def csgraph_to_masked(csgraph): + """ + csgraph_to_masked(csgraph) + + Convert a sparse graph representation to a masked array representation + + .. versionadded:: 0.11.0 + + Parameters + ---------- + csgraph : csr_matrix, csc_matrix, or lil_matrix + Sparse representation of a graph. + + Returns + ------- + graph : MaskedArray + The masked dense representation of the sparse graph. + """ + return np.ma.masked_invalid(csgraph_to_dense(csgraph, np.nan)) + + +cdef void _populate_graph(np.ndarray[DTYPE_t, ndim=1, mode='c'] data, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indices, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr, + np.ndarray[DTYPE_t, ndim=2, mode='c'] graph, + DTYPE_t null_value): + # data, indices, indptr are the csr attributes of the sparse input. + # on input, graph should be filled with infinities, and should be + # of size [N, N], which is also the size of the sparse matrix + cdef unsigned int N = graph.shape[0] + cdef np.ndarray null_flag = np.ones((N, N), dtype=bool, order='C') + cdef np.npy_bool* null_ptr = null_flag.data + cdef unsigned int row, col, i + + for row from 0 <= row < N: + for i from indptr[row] <= i < indptr[row + 1]: + col = indices[i] + null_ptr[col] = 0 + # in case of multiple edges, we'll choose the smallest + if data[i] < graph[row, col]: + graph[row, col] = data[i] + null_ptr += N + + graph[null_flag] = null_value + + +def reconstruct_path(csgraph, predecessors, directed=True): + """ + reconstruct_path(csgraph, predecessors, directed=True) + + Construct a tree from a graph and a predecessor list. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + csgraph : array_like or sparse matrix + The N x N matrix representing the directed or undirected graph + from which the predecessors are drawn. + predecessors : array_like, one dimension + The length-N array of indices of predecessors for the tree. The + index of the parent of node i is given by predecessors[i]. + directed : bool, optional + If True (default), then operate on a directed graph: only move from + point i to point j along paths csgraph[i, j]. + If False, then operate on an undirected graph: the algorithm can + progress from point i to j along csgraph[i, j] or csgraph[j, i]. + + Returns + ------- + cstree : csr matrix + The N x N directed compressed-sparse representation of the tree drawn + from csgraph which is encoded by the predecessor list. + """ + from _validation import validate_graph + csgraph = validate_graph(csgraph, directed, dense_output=False) + + N = csgraph.shape[0] + + nnull = (predecessors < 0).sum() + + indices = np.argsort(predecessors)[nnull:].astype(ITYPE) + pind = predecessors[indices] + indptr = pind.searchsorted(np.arange(N + 1)).astype(ITYPE) + + if directed == True: + data = csgraph[pind, indices] + else: + data1 = csgraph[pind, indices] + data2 = csgraph[indices, pind] + data1[data1 == 0] = np.inf + data2[data2 == 0] = np.inf + data = np.minimum(data1, data2) + + data = np.asarray(data).ravel() + + return csr_matrix((data, indices, indptr), shape=(N, N)) + + +def construct_dist_matrix(graph, + predecessors, + directed=True, + null_value=np.inf): + """ + construct_dist_matrix(graph, predecessors, directed=True, null_value=np.inf) + + Construct distance matrix from a predecessor matrix + + .. versionadded:: 0.11.0 + + Parameters + ---------- + graph : array_like or sparse + The N x N matrix representation of a directed or undirected graph. + If dense, then non-edges are indicated by zeros or infinities. + predecessors : array_like + The N x N matrix of predecessors of each node (see Notes below). + directed : bool, optional + If True (default), then operate on a directed graph: only move from + point i to point j along paths csgraph[i, j]. + If False, then operate on an undirected graph: the algorithm can + progress from point i to j along csgraph[i, j] or csgraph[j, i]. + null_value : bool, optional + value to use for distances between unconnected nodes. Default is + np.inf + + Returns + ------- + dist_matrix : ndarray + The N x N matrix of distances between nodes along the path specified + by the predecessor matrix. If no path exists, the distance is zero. + + Notes + ----- + The predecessor matrix is of the form returned by + :func:`graph_shortest_path`. Row i of the predecessor matrix contains + information on the shortest paths from point i: each entry + predecessors[i, j] gives the index of the previous node in the path from + point i to point j. If no path exists between point i and j, then + predecessors[i, j] = -9999 + """ + from _validation import validate_graph + graph = validate_graph(graph, directed, dtype=DTYPE, + csr_output=False, + copy_if_dense=not directed) + predecessors = np.asarray(predecessors) + + if predecessors.shape != graph.shape: + raise ValueError("graph and predecessors must have the same shape") + + dist_matrix = np.zeros(graph.shape, dtype=DTYPE) + _construct_dist_matrix(graph, predecessors, dist_matrix, + directed, null_value) + + return dist_matrix + + +cdef void _construct_dist_matrix(np.ndarray[DTYPE_t, ndim=2] graph, + np.ndarray[ITYPE_t, ndim=2] pred, + np.ndarray[DTYPE_t, ndim=2] dist, + int directed, + DTYPE_t null_value): + # All matrices should be size N x N + # note that graph will be modified if directed == False + # dist should be all zero on entry + global NULL_IDX + + cdef int i, j, k1, k2, N, null_path + N = graph.shape[0] + + #------------------------------------------ + # symmetrize matrix if necessary + if not directed: + graph[graph == 0] = np.inf + for i from 0 <= i < N: + for j from i + 1 <= j < N: + if graph[j, i] <= graph[i, j]: + graph[i, j] = graph[j, i] + else: + graph[j, i] = graph[i, j] + #------------------------------------------ + + for i from 0 <= i < N: + for j from 0 <= j < N: + null_path = True + k2 = j + while k2 != i: + k1 = pred[i, k2] + if k1 == NULL_IDX: + break + dist[i, j] += graph[k1, k2] + null_path = False + k2 = k1 + if null_path and i != j: + dist[i, j] = null_value diff --git a/sklearn/utils/sparsetools/_graph_validation.py b/sklearn/utils/sparsetools/_graph_validation.py new file mode 100644 index 0000000000000..4136744cfdb76 --- /dev/null +++ b/sklearn/utils/sparsetools/_graph_validation.py @@ -0,0 +1,58 @@ +from __future__ import division, print_function, absolute_import + +import numpy as np +from scipy.sparse import csr_matrix, isspmatrix, isspmatrix_csc +from ._graph_tools import csgraph_to_dense, csgraph_from_dense,\ + csgraph_masked_from_dense, csgraph_from_masked + +DTYPE = np.float64 + + +def validate_graph(csgraph, directed, dtype=DTYPE, + csr_output=True, dense_output=True, + copy_if_dense=False, copy_if_sparse=False, + null_value_in=0, null_value_out=np.inf, + infinity_null=True, nan_null=True): + """Routine for validation and conversion of csgraph inputs""" + if not (csr_output or dense_output): + raise ValueError("Internal: dense or csr output must be true") + + # if undirected and csc storage, then transposing in-place + # is quicker than later converting to csr. + if (not directed) and isspmatrix_csc(csgraph): + csgraph = csgraph.T + + if isspmatrix(csgraph): + if csr_output: + csgraph = csr_matrix(csgraph, dtype=DTYPE, copy=copy_if_sparse) + else: + csgraph = csgraph_to_dense(csgraph, null_value=null_value_out) + elif np.ma.is_masked(csgraph): + if dense_output: + mask = csgraph.mask + csgraph = np.array(csgraph.data, dtype=DTYPE, copy=copy_if_dense) + csgraph[mask] = null_value_out + else: + csgraph = csgraph_from_masked(csgraph) + else: + if dense_output: + csgraph = csgraph_masked_from_dense(csgraph, + copy=copy_if_dense, + null_value=null_value_in, + nan_null=nan_null, + infinity_null=infinity_null) + mask = csgraph.mask + csgraph = np.asarray(csgraph.data, dtype=DTYPE) + csgraph[mask] = null_value_out + else: + csgraph = csgraph_from_dense(csgraph, null_value=null_value_in, + infinity_null=infinity_null, + nan_null=nan_null) + + if csgraph.ndim != 2: + raise ValueError("compressed-sparse graph must be two dimensional") + + if csgraph.shape[0] != csgraph.shape[1]: + raise ValueError("compressed-sparse graph must be shape (N, N)") + + return csgraph diff --git a/sklearn/utils/sparsetools/_traversal.c b/sklearn/utils/sparsetools/_traversal.c new file mode 100644 index 0000000000000..c20827adb5103 --- /dev/null +++ b/sklearn/utils/sparsetools/_traversal.c @@ -0,0 +1,12205 @@ +/* Generated by Cython 0.16 on Thu Jun 6 13:59:16 2013 */ + +#define PY_SSIZE_T_CLEAN +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. +#else +#include /* For offsetof */ +#ifndef offsetof +#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif + +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif + +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif + +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif + +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif + +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif + +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyCFunction_Call PyObject_Call +#else + #define __Pyx_PyCFunction_Call PyCFunction_Call +#endif + +#if PY_VERSION_HEX < 0x02050000 + typedef int Py_ssize_t; + #define PY_SSIZE_T_MAX INT_MAX + #define PY_SSIZE_T_MIN INT_MIN + #define PY_FORMAT_SIZE_T "" + #define PyInt_FromSsize_t(z) PyInt_FromLong(z) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) + #define PyNumber_Index(o) PyNumber_Int(o) + #define PyIndex_Check(o) PyNumber_Check(o) + #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" +#endif + +#if PY_VERSION_HEX < 0x02060000 + #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) + #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) + #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) + #define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + #define PyType_Modified(t) + + typedef struct { + void *buf; + PyObject *obj; + Py_ssize_t len; + Py_ssize_t itemsize; + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + void *internal; + } Py_buffer; + + #define PyBUF_SIMPLE 0 + #define PyBUF_WRITABLE 0x0001 + #define PyBUF_FORMAT 0x0004 + #define PyBUF_ND 0x0008 + #define PyBUF_STRIDES (0x0010 | PyBUF_ND) + #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) + #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) + #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) + #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); +#endif + +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif + +#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") +#endif + +#if PY_MAJOR_VERSION >= 3 + #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif + +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif + + +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_GET_LENGTH) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) +#endif + +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#endif + +#if PY_VERSION_HEX < 0x02060000 + #define PyBytesObject PyStringObject + #define PyBytes_Type PyString_Type + #define PyBytes_Check PyString_Check + #define PyBytes_CheckExact PyString_CheckExact + #define PyBytes_FromString PyString_FromString + #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #define PyBytes_FromFormat PyString_FromFormat + #define PyBytes_DecodeEscape PyString_DecodeEscape + #define PyBytes_AsString PyString_AsString + #define PyBytes_AsStringAndSize PyString_AsStringAndSize + #define PyBytes_Size PyString_Size + #define PyBytes_AS_STRING PyString_AS_STRING + #define PyBytes_GET_SIZE PyString_GET_SIZE + #define PyBytes_Repr PyString_Repr + #define PyBytes_Concat PyString_Concat + #define PyBytes_ConcatAndDel PyString_ConcatAndDel +#endif + +#if PY_VERSION_HEX < 0x02060000 + #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) + #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif + +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) + +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask +#endif + +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif + +#if PY_VERSION_HEX < 0x03020000 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif + +#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) + #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) + #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) +#else + #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) + #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) + #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ + (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ + (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ + (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) +#endif + +#if PY_MAJOR_VERSION >= 3 + #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) +#endif + +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) +#else + #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) + #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) + #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) +#endif + +#if PY_VERSION_HEX < 0x02050000 + #define __Pyx_NAMESTR(n) ((char *)(n)) + #define __Pyx_DOCSTR(n) ((char *)(n)) +#else + #define __Pyx_NAMESTR(n) (n) + #define __Pyx_DOCSTR(n) (n) +#endif + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) +#define _USE_MATH_DEFINES +#endif +#include +#define __PYX_HAVE__sklearn__utils__mst___traversal +#define __PYX_HAVE_API__sklearn__utils__mst___traversal +#include "stdio.h" +#include "stdlib.h" +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#ifdef PYREX_WITHOUT_ASSERTIONS +#define CYTHON_WITHOUT_ASSERTIONS +#endif + + +/* inline attribute */ +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* unused attribute */ +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif + +typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + + +/* Type Conversion Predeclarations */ + +#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) +#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) + +#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); + +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); + +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) + +#ifdef __GNUC__ + /* Test for GCC > 2.95 */ + #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) + #else /* __GNUC__ > 2 ... */ + #define likely(x) (x) + #define unlikely(x) (x) + #endif /* __GNUC__ > 2 ... */ +#else /* __GNUC__ */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ + +static PyObject *__pyx_m; +static PyObject *__pyx_b; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "_traversal.pyx", + "numpy.pxd", +}; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + + +/* "numpy.pxd":722 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "numpy.pxd":723 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "numpy.pxd":724 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "numpy.pxd":725 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "numpy.pxd":729 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "numpy.pxd":730 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "numpy.pxd":731 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "numpy.pxd":732 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "numpy.pxd":736 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "numpy.pxd":737 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "numpy.pxd":746 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "numpy.pxd":747 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "numpy.pxd":748 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "numpy.pxd":750 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "numpy.pxd":751 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "numpy.pxd":752 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "numpy.pxd":754 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "numpy.pxd":755 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "numpy.pxd":757 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "numpy.pxd":758 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "numpy.pxd":759 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; + +/* "sklearn/utils/mst/_traversal.pyx":19 + * + * DTYPE = np.float64 + * ctypedef np.float64_t DTYPE_t # <<<<<<<<<<<<<< + * + * ITYPE = np.int32 + */ +typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_3mst_10_traversal_DTYPE_t; + +/* "sklearn/utils/mst/_traversal.pyx":22 + * + * ITYPE = np.int32 + * ctypedef np.int32_t ITYPE_t # <<<<<<<<<<<<<< + * + * # EPS is the precision of DTYPE + */ +typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t; +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif + + +/*--- Type declarations ---*/ + +/* "numpy.pxd":761 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "numpy.pxd":762 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "numpy.pxd":763 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "numpy.pxd":765 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +#define __Pyx_GetItemInt_List(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_List_Fast(o, i) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i) { + if (likely(o != Py_None)) { + if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) { + PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i); + Py_INCREF(r); + return r; + } + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} +#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Tuple_Fast(o, i) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i) { + if (likely(o != Py_None)) { + if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, i); + Py_INCREF(r); + return r; + } + else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) { + PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i); + Py_INCREF(r); + return r; + } + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} +#define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \ + __Pyx_GetItemInt_Fast(o, i) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) { + if (PyList_CheckExact(o)) { + Py_ssize_t n = (likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if (likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = (likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if (likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (likely(i >= 0)) { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + return m->sq_item(o, i); + } + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); + +static void __Pyx_RaiseBufferIndexError(int axis); /*proto*/ + +#define __Pyx_BufPtrCContig1d(type, buf, i0, s0) ((type)buf + i0) +static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ + +static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name); + +#include + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals +#else +#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals +#endif + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32); + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eqf(a, b) ((a)==(b)) + #define __Pyx_c_sumf(a, b) ((a)+(b)) + #define __Pyx_c_difff(a, b) ((a)-(b)) + #define __Pyx_c_prodf(a, b) ((a)*(b)) + #define __Pyx_c_quotf(a, b) ((a)/(b)) + #define __Pyx_c_negf(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zerof(z) ((z)==(float)0) + #define __Pyx_c_conjf(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_absf(z) (::std::abs(z)) + #define __Pyx_c_powf(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zerof(z) ((z)==0) + #define __Pyx_c_conjf(z) (conjf(z)) + #if 1 + #define __Pyx_c_absf(z) (cabsf(z)) + #define __Pyx_c_powf(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq(a, b) ((a)==(b)) + #define __Pyx_c_sum(a, b) ((a)+(b)) + #define __Pyx_c_diff(a, b) ((a)-(b)) + #define __Pyx_c_prod(a, b) ((a)*(b)) + #define __Pyx_c_quot(a, b) ((a)/(b)) + #define __Pyx_c_neg(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero(z) ((z)==(double)0) + #define __Pyx_c_conj(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs(z) (::std::abs(z)) + #define __Pyx_c_pow(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero(z) ((z)==0) + #define __Pyx_c_conj(z) (conj(z)) + #if 1 + #define __Pyx_c_abs(z) (cabs(z)) + #define __Pyx_c_pow(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); + +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); + +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); + +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); + +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); + +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); + +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); + +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename); /*proto*/ + +static int __Pyx_check_binary_version(void); + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ + +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ + +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from 'libc.stdlib' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ + +/* Module declarations from 'cython' */ + +/* Module declarations from 'libc' */ + +/* Module declarations from 'sklearn.utils.mst._traversal' */ +static __pyx_t_7sklearn_5utils_3mst_10_traversal_DTYPE_t __pyx_v_7sklearn_5utils_3mst_10_traversal_DTYPE_EPS; +static __pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t __pyx_v_7sklearn_5utils_3mst_10_traversal_NULL_IDX; +static unsigned int __pyx_f_7sklearn_5utils_3mst_10_traversal__breadth_first_directed(unsigned int, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *); /*proto*/ +static unsigned int __pyx_f_7sklearn_5utils_3mst_10_traversal__breadth_first_undirected(unsigned int, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *); /*proto*/ +static unsigned int __pyx_f_7sklearn_5utils_3mst_10_traversal__depth_first_directed(unsigned int, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *); /*proto*/ +static unsigned int __pyx_f_7sklearn_5utils_3mst_10_traversal__depth_first_undirected(unsigned int, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *); /*proto*/ +static int __pyx_f_7sklearn_5utils_3mst_10_traversal__connected_components_directed(PyArrayObject *, PyArrayObject *, PyArrayObject *); /*proto*/ +static int __pyx_f_7sklearn_5utils_3mst_10_traversal__connected_components_undirected(PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t = { "ITYPE_t", NULL, sizeof(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t), { 0 }, 0, 'I', IS_UNSIGNED(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t), 0 }; +#define __Pyx_MODULE_NAME "sklearn.utils.mst._traversal" +int __pyx_module_is_main_sklearn__utils__mst___traversal = 0; + +/* Implementation of 'sklearn.utils.mst._traversal' */ +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_RuntimeError; +static PyObject *__pyx_pf_7sklearn_5utils_3mst_10_traversal_connected_components(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_directed, PyObject *__pyx_v_connection, PyObject *__pyx_v_return_labels); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_3mst_10_traversal_2breadth_first_tree(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_i_start, PyObject *__pyx_v_directed); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_3mst_10_traversal_4depth_first_tree(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_i_start, PyObject *__pyx_v_directed); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_3mst_10_traversal_6breadth_first_order(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_i_start, PyObject *__pyx_v_directed, PyObject *__pyx_v_return_predecessors); /* proto */ +static PyObject *__pyx_pf_7sklearn_5utils_3mst_10_traversal_8depth_first_order(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_i_start, PyObject *__pyx_v_directed, PyObject *__pyx_v_return_predecessors); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static char __pyx_k_3[] = "connection must be 'weak' or 'strong'"; +static char __pyx_k_11[] = "ndarray is not C contiguous"; +static char __pyx_k_13[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_15[] = "Non-native byte order not supported"; +static char __pyx_k_17[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_18[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_21[] = "Format string allocated too short."; +static char __pyx_k_23[] = "\nRoutines for traversing graphs in compressed sparse format\n"; +static char __pyx_k_24[] = "scipy.sparse"; +static char __pyx_k_27[] = "connected_components"; +static char __pyx_k_28[] = "/home/x006/Code/scikit-learn/sklearn/utils/mst/_traversal.pyx"; +static char __pyx_k_29[] = "sklearn.utils.mst._traversal"; +static char __pyx_k_38[] = "breadth_first_tree (line 99)"; +static char __pyx_k_39[] = "\n breadth_first_tree(csgraph, i_start, directed=True)\n\n Return the tree generated by a breadth-first search\n\n Note that a breadth-first tree from a specified node is unique.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n csgraph : array_like or sparse matrix\n The N x N matrix representing the compressed sparse graph. The input\n csgraph will be converted to csr format for the calculation.\n i_start : int\n The index of starting node.\n directed : bool, optional\n If True (default), then operate on a directed graph: only\n move from point i to point j along paths csgraph[i, j].\n If False, then find the shortest path on an undirected graph: the\n algorithm can progress from point i to j along csgraph[i, j] or\n csgraph[j, i].\n\n Returns\n -------\n cstree : csr matrix\n The N x N directed compressed-sparse representation of the breadth-\n first tree drawn from csgraph, starting at the specified node.\n\n Examples\n --------\n The following example shows the computation of a depth-first tree\n over a simple four-component graph, starting at node 0::\n\n input graph breadth first tree from (0)\n\n (0) (0)\n / \\ / \\\n 3 8 3 8\n / \\ / \\\n (3)---5---(1) (3) (1)\n \\ / /\n 6 2 2\n \\ / /\n (2) (2)\n\n In compressed sparse representation, the solution looks like this:\n\n >>> from scipy.sparse import csr_matrix\n >>> from scipy.sparse.csgraph import breadth_first_tree\n >>> X = csr_matrix([[0, 8, 0, 3],\n ... [0, 0, 2, 5],\n ... [0, 0, 0, 6],""\n ... [0, 0, 0, 0]])\n >>> Tcsr = breadth_first_tree(X, 0, directed=False)\n >>> Tcsr.toarray().astype(int)\n array([[0, 8, 0, 3],\n [0, 0, 2, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]])\n\n Note that the resulting graph is a Directed Acyclic Graph which spans\n the graph. A breadth-first tree from a given node is unique.\n "; +static char __pyx_k_40[] = "depth_first_tree (line 169)"; +static char __pyx_k_41[] = "\n depth_first_tree(csgraph, i_start, directed=True)\n\n Return a tree generated by a depth-first search.\n\n Note that a tree generated by a depth-first search is not unique:\n it depends on the order that the children of each node are searched.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n csgraph : array_like or sparse matrix\n The N x N matrix representing the compressed sparse graph. The input\n csgraph will be converted to csr format for the calculation.\n i_start : int\n The index of starting node.\n directed : bool, optional\n If True (default), then operate on a directed graph: only\n move from point i to point j along paths csgraph[i, j].\n If False, then find the shortest path on an undirected graph: the\n algorithm can progress from point i to j along csgraph[i, j] or\n csgraph[j, i].\n\n Returns\n -------\n cstree : csr matrix\n The N x N directed compressed-sparse representation of the depth-\n first tree drawn from csgraph, starting at the specified node.\n\n Examples\n --------\n The following example shows the computation of a depth-first tree\n over a simple four-component graph, starting at node 0::\n\n input graph depth first tree from (0)\n\n (0) (0)\n / \\ \\\n 3 8 8\n / \\ \\\n (3)---5---(1) (3) (1)\n \\ / \\ /\n 6 2 6 2\n \\ / \\ /\n (2) (2)\n\n In compressed sparse representation, the solution looks like this:\n\n >>> from scipy.sparse import csr_matrix\n >>> from scipy.sparse.csgraph import depth_first_tree\n >>> X = csr_matrix([[0, 8, 0, 3],\n ... "" [0, 0, 2, 5],\n ... [0, 0, 0, 6],\n ... [0, 0, 0, 0]])\n >>> Tcsr = depth_first_tree(X, 0, directed=False)\n >>> Tcsr.toarray().astype(int)\n array([[0, 8, 0, 0],\n [0, 0, 2, 0],\n [0, 0, 0, 6],\n [0, 0, 0, 0]])\n\n Note that the resulting graph is a Directed Acyclic Graph which spans\n the graph. Unlike a breadth-first tree, a depth-first tree of a given\n graph is not unique if the graph contains cycles. If the above solution\n had begun with the edge connecting nodes 0 and 3, the result would have\n been different.\n "; +static char __pyx_k__B[] = "B"; +static char __pyx_k__H[] = "H"; +static char __pyx_k__I[] = "I"; +static char __pyx_k__L[] = "L"; +static char __pyx_k__N[] = "N"; +static char __pyx_k__O[] = "O"; +static char __pyx_k__Q[] = "Q"; +static char __pyx_k__T[] = "T"; +static char __pyx_k__b[] = "b"; +static char __pyx_k__d[] = "d"; +static char __pyx_k__f[] = "f"; +static char __pyx_k__g[] = "g"; +static char __pyx_k__h[] = "h"; +static char __pyx_k__i[] = "i"; +static char __pyx_k__l[] = "l"; +static char __pyx_k__q[] = "q"; +static char __pyx_k__Zd[] = "Zd"; +static char __pyx_k__Zf[] = "Zf"; +static char __pyx_k__Zg[] = "Zg"; +static char __pyx_k__np[] = "np"; +static char __pyx_k__fill[] = "fill"; +static char __pyx_k__flag[] = "flag"; +static char __pyx_k__weak[] = "weak"; +static char __pyx_k__DTYPE[] = "DTYPE"; +static char __pyx_k__ITYPE[] = "ITYPE"; +static char __pyx_k__dtype[] = "dtype"; +static char __pyx_k__empty[] = "empty"; +static char __pyx_k__int32[] = "int32"; +static char __pyx_k__lower[] = "lower"; +static char __pyx_k__numpy[] = "numpy"; +static char __pyx_k__range[] = "range"; +static char __pyx_k__shape[] = "shape"; +static char __pyx_k__tocsr[] = "tocsr"; +static char __pyx_k__zeros[] = "zeros"; +static char __pyx_k__indptr[] = "indptr"; +static char __pyx_k__labels[] = "labels"; +static char __pyx_k__length[] = "length"; +static char __pyx_k__strong[] = "strong"; +static char __pyx_k__csgraph[] = "csgraph"; +static char __pyx_k__float64[] = "float64"; +static char __pyx_k__i_start[] = "i_start"; +static char __pyx_k__indices[] = "indices"; +static char __pyx_k____main__[] = "__main__"; +static char __pyx_k____test__[] = "__test__"; +static char __pyx_k__directed[] = "directed"; +static char __pyx_k__csgraph_T[] = "csgraph_T"; +static char __pyx_k__node_list[] = "node_list"; +static char __pyx_k__root_list[] = "root_list"; +static char __pyx_k__ValueError[] = "ValueError"; +static char __pyx_k__connection[] = "connection"; +static char __pyx_k__csr_matrix[] = "csr_matrix"; +static char __pyx_k__isspmatrix[] = "isspmatrix"; +static char __pyx_k__RuntimeError[] = "RuntimeError"; +static char __pyx_k___graph_tools[] = "_graph_tools"; +static char __pyx_k__dense_output[] = "dense_output"; +static char __pyx_k__n_components[] = "n_components"; +static char __pyx_k__predecessors[] = "predecessors"; +static char __pyx_k__return_labels[] = "return_labels"; +static char __pyx_k__isspmatrix_csc[] = "isspmatrix_csc"; +static char __pyx_k__isspmatrix_csr[] = "isspmatrix_csr"; +static char __pyx_k__validate_graph[] = "validate_graph"; +static char __pyx_k__depth_first_tree[] = "depth_first_tree"; +static char __pyx_k__reconstruct_path[] = "reconstruct_path"; +static char __pyx_k___graph_validation[] = "_graph_validation"; +static char __pyx_k__depth_first_order[] = "depth_first_order"; +static char __pyx_k__breadth_first_tree[] = "breadth_first_tree"; +static char __pyx_k__breadth_first_order[] = "breadth_first_order"; +static char __pyx_k__return_predecessors[] = "return_predecessors"; +static PyObject *__pyx_kp_u_11; +static PyObject *__pyx_kp_u_13; +static PyObject *__pyx_kp_u_15; +static PyObject *__pyx_kp_u_17; +static PyObject *__pyx_kp_u_18; +static PyObject *__pyx_kp_u_21; +static PyObject *__pyx_n_s_24; +static PyObject *__pyx_n_s_27; +static PyObject *__pyx_kp_s_28; +static PyObject *__pyx_n_s_29; +static PyObject *__pyx_kp_s_3; +static PyObject *__pyx_kp_u_38; +static PyObject *__pyx_kp_u_39; +static PyObject *__pyx_kp_u_40; +static PyObject *__pyx_kp_u_41; +static PyObject *__pyx_n_s__DTYPE; +static PyObject *__pyx_n_s__ITYPE; +static PyObject *__pyx_n_s__N; +static PyObject *__pyx_n_s__RuntimeError; +static PyObject *__pyx_n_s__T; +static PyObject *__pyx_n_s__ValueError; +static PyObject *__pyx_n_s____main__; +static PyObject *__pyx_n_s____test__; +static PyObject *__pyx_n_s___graph_tools; +static PyObject *__pyx_n_s___graph_validation; +static PyObject *__pyx_n_s__breadth_first_order; +static PyObject *__pyx_n_s__breadth_first_tree; +static PyObject *__pyx_n_s__connection; +static PyObject *__pyx_n_s__csgraph; +static PyObject *__pyx_n_s__csgraph_T; +static PyObject *__pyx_n_s__csr_matrix; +static PyObject *__pyx_n_s__dense_output; +static PyObject *__pyx_n_s__depth_first_order; +static PyObject *__pyx_n_s__depth_first_tree; +static PyObject *__pyx_n_s__directed; +static PyObject *__pyx_n_s__dtype; +static PyObject *__pyx_n_s__empty; +static PyObject *__pyx_n_s__fill; +static PyObject *__pyx_n_s__flag; +static PyObject *__pyx_n_s__float64; +static PyObject *__pyx_n_s__i_start; +static PyObject *__pyx_n_s__indices; +static PyObject *__pyx_n_s__indptr; +static PyObject *__pyx_n_s__int32; +static PyObject *__pyx_n_s__isspmatrix; +static PyObject *__pyx_n_s__isspmatrix_csc; +static PyObject *__pyx_n_s__isspmatrix_csr; +static PyObject *__pyx_n_s__labels; +static PyObject *__pyx_n_s__length; +static PyObject *__pyx_n_s__lower; +static PyObject *__pyx_n_s__n_components; +static PyObject *__pyx_n_s__node_list; +static PyObject *__pyx_n_s__np; +static PyObject *__pyx_n_s__numpy; +static PyObject *__pyx_n_s__predecessors; +static PyObject *__pyx_n_s__range; +static PyObject *__pyx_n_s__reconstruct_path; +static PyObject *__pyx_n_s__return_labels; +static PyObject *__pyx_n_s__return_predecessors; +static PyObject *__pyx_n_s__root_list; +static PyObject *__pyx_n_s__shape; +static PyObject *__pyx_n_s__strong; +static PyObject *__pyx_n_s__tocsr; +static PyObject *__pyx_n_s__validate_graph; +static PyObject *__pyx_n_s__weak; +static PyObject *__pyx_n_s__zeros; +static PyObject *__pyx_int_neg_1; +static PyObject *__pyx_int_15; +static PyObject *__pyx_k_1; +static PyObject *__pyx_k_2; +static PyObject *__pyx_k_5; +static PyObject *__pyx_k_6; +static PyObject *__pyx_k_7; +static PyObject *__pyx_k_8; +static PyObject *__pyx_k_9; +static PyObject *__pyx_k_10; +static PyObject *__pyx_k_tuple_4; +static PyObject *__pyx_k_tuple_12; +static PyObject *__pyx_k_tuple_14; +static PyObject *__pyx_k_tuple_16; +static PyObject *__pyx_k_tuple_19; +static PyObject *__pyx_k_tuple_20; +static PyObject *__pyx_k_tuple_22; +static PyObject *__pyx_k_tuple_25; +static PyObject *__pyx_k_tuple_30; +static PyObject *__pyx_k_tuple_32; +static PyObject *__pyx_k_tuple_34; +static PyObject *__pyx_k_tuple_36; +static PyObject *__pyx_k_codeobj_26; +static PyObject *__pyx_k_codeobj_31; +static PyObject *__pyx_k_codeobj_33; +static PyObject *__pyx_k_codeobj_35; +static PyObject *__pyx_k_codeobj_37; + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_3mst_10_traversal_1connected_components(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_3mst_10_traversal_connected_components[] = "\n connected_components(csgraph, directed=True, connection='weak',\n return_labels=True)\n\n Analyze the connected components of a sparse graph\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n csgraph : array_like or sparse matrix\n The N x N matrix representing the compressed sparse graph. The input\n csgraph will be converted to csr format for the calculation.\n directed : bool, optional\n If True (default), then operate on a directed graph: only\n move from point i to point j along paths csgraph[i, j].\n If False, then find the shortest path on an undirected graph: the\n algorithm can progress from point i to j along csgraph[i, j] or\n csgraph[j, i].\n connection : str, optional\n ['weak'|'strong']. For directed graphs, the type of connection to\n use. Nodes i and j are strongly connected if a path exists both\n from i to j and from j to i. Nodes i and j are weakly connected if\n only one of these paths exists. If directed == False, this keyword\n is not referenced.\n return_labels : str, optional\n If True (default), then return the labels for each of the connected\n components.\n\n Returns\n -------\n n_components: int\n The number of connected components.\n labels: ndarray\n The length-N array of labels of the connected components.\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_3mst_10_traversal_1connected_components = {__Pyx_NAMESTR("connected_components"), (PyCFunction)__pyx_pw_7sklearn_5utils_3mst_10_traversal_1connected_components, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_3mst_10_traversal_connected_components)}; +static PyObject *__pyx_pw_7sklearn_5utils_3mst_10_traversal_1connected_components(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_csgraph = 0; + PyObject *__pyx_v_directed = 0; + PyObject *__pyx_v_connection = 0; + PyObject *__pyx_v_return_labels = 0; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__csgraph,&__pyx_n_s__directed,&__pyx_n_s__connection,&__pyx_n_s__return_labels,0}; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("connected_components (wrapper)", 0); + __pyx_self = __pyx_self; + { + PyObject* values[4] = {0,0,0,0}; + values[1] = __pyx_k_1; + values[2] = ((PyObject *)__pyx_n_s__weak); + values[3] = __pyx_k_2; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__csgraph); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__directed); + if (value) { values[1] = value; kw_args--; } + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__connection); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__return_labels); + if (value) { values[3] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "connected_components") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_csgraph = values[0]; + __pyx_v_directed = values[1]; + __pyx_v_connection = values[2]; + __pyx_v_return_labels = values[3]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("connected_components", 0, 1, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils.mst._traversal.connected_components", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_3mst_10_traversal_connected_components(__pyx_self, __pyx_v_csgraph, __pyx_v_directed, __pyx_v_connection, __pyx_v_return_labels); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/mst/_traversal.pyx":30 + * cdef ITYPE_t NULL_IDX = -9999 + * + * def connected_components(csgraph, directed=True, connection='weak', # <<<<<<<<<<<<<< + * return_labels=True): + * """ + */ + +static PyObject *__pyx_pf_7sklearn_5utils_3mst_10_traversal_connected_components(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_directed, PyObject *__pyx_v_connection, PyObject *__pyx_v_return_labels) { + PyObject *__pyx_v_labels = NULL; + int __pyx_v_n_components; + PyObject *__pyx_v_csgraph_T = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("connected_components", 0); + __Pyx_INCREF(__pyx_v_csgraph); + __Pyx_INCREF(__pyx_v_directed); + + /* "sklearn/utils/mst/_traversal.pyx":68 + * The length-N array of labels of the connected components. + * """ + * if connection.lower() not in ['weak', 'strong']: # <<<<<<<<<<<<<< + * raise ValueError("connection must be 'weak' or 'strong'") + * + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_connection, __pyx_n_s__lower); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyString_Equals(__pyx_t_2, ((PyObject *)__pyx_n_s__weak), Py_NE); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (((int)__pyx_t_3)) { + __pyx_t_4 = __Pyx_PyString_Equals(__pyx_t_2, ((PyObject *)__pyx_n_s__strong), Py_NE); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = ((int)__pyx_t_4); + } else { + __pyx_t_5 = ((int)__pyx_t_3); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __pyx_t_5; + if (__pyx_t_3) { + + /* "sklearn/utils/mst/_traversal.pyx":69 + * """ + * if connection.lower() not in ['weak', 'strong']: + * raise ValueError("connection must be 'weak' or 'strong'") # <<<<<<<<<<<<<< + * + * # weak connections <=> components of undirected graph + */ + __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/utils/mst/_traversal.pyx":72 + * + * # weak connections <=> components of undirected graph + * if connection.lower() == 'weak': # <<<<<<<<<<<<<< + * directed = False + * + */ + __pyx_t_2 = PyObject_GetAttr(__pyx_v_connection, __pyx_n_s__lower); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_PyString_Equals(__pyx_t_1, ((PyObject *)__pyx_n_s__weak), Py_EQ); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 72; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_3) { + + /* "sklearn/utils/mst/_traversal.pyx":73 + * # weak connections <=> components of undirected graph + * if connection.lower() == 'weak': + * directed = False # <<<<<<<<<<<<<< + * + * csgraph = validate_graph(csgraph, directed, + */ + __pyx_t_1 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_v_directed); + __pyx_v_directed = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L4; + } + __pyx_L4:; + + /* "sklearn/utils/mst/_traversal.pyx":75 + * directed = False + * + * csgraph = validate_graph(csgraph, directed, # <<<<<<<<<<<<<< + * dense_output=False) + * + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__validate_graph); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + __Pyx_INCREF(__pyx_v_directed); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_directed); + __Pyx_GIVEREF(__pyx_v_directed); + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + + /* "sklearn/utils/mst/_traversal.pyx":76 + * + * csgraph = validate_graph(csgraph, directed, + * dense_output=False) # <<<<<<<<<<<<<< + * + * labels = np.empty(csgraph.shape[0], dtype=ITYPE) + */ + __pyx_t_7 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dense_output), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 75; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_v_csgraph); + __pyx_v_csgraph = __pyx_t_7; + __pyx_t_7 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":78 + * dense_output=False) + * + * labels = np.empty(csgraph.shape[0], dtype=ITYPE) # <<<<<<<<<<<<<< + * labels.fill(NULL_IDX) + * + */ + __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = PyObject_GetAttr(__pyx_t_7, __pyx_n_s__empty); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__shape); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_7, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_v_labels = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":79 + * + * labels = np.empty(csgraph.shape[0], dtype=ITYPE) + * labels.fill(NULL_IDX) # <<<<<<<<<<<<<< + * + * if directed: + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_labels, __pyx_n_s__fill); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_7sklearn_5utils_3mst_10_traversal_NULL_IDX); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":81 + * labels.fill(NULL_IDX) + * + * if directed: # <<<<<<<<<<<<<< + * n_components = _connected_components_directed(csgraph.indices, + * csgraph.indptr, + */ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_directed); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { + + /* "sklearn/utils/mst/_traversal.pyx":82 + * + * if directed: + * n_components = _connected_components_directed(csgraph.indices, # <<<<<<<<<<<<<< + * csgraph.indptr, + * labels) + */ + __pyx_t_2 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indices); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 82; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":83 + * if directed: + * n_components = _connected_components_directed(csgraph.indices, + * csgraph.indptr, # <<<<<<<<<<<<<< + * labels) + * else: + */ + __pyx_t_7 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indptr); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":84 + * n_components = _connected_components_directed(csgraph.indices, + * csgraph.indptr, + * labels) # <<<<<<<<<<<<<< + * else: + * csgraph_T = csgraph.T.tocsr() + */ + if (!(likely(((__pyx_v_labels) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_labels, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_v_labels; + __Pyx_INCREF(__pyx_t_1); + __pyx_v_n_components = __pyx_f_7sklearn_5utils_3mst_10_traversal__connected_components_directed(((PyArrayObject *)__pyx_t_2), ((PyArrayObject *)__pyx_t_7), ((PyArrayObject *)__pyx_t_1)); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L5; + } + /*else*/ { + + /* "sklearn/utils/mst/_traversal.pyx":86 + * labels) + * else: + * csgraph_T = csgraph.T.tocsr() # <<<<<<<<<<<<<< + * n_components = _connected_components_undirected(csgraph.indices, + * csgraph.indptr, + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__T); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__tocsr); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_csgraph_T = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":87 + * else: + * csgraph_T = csgraph.T.tocsr() + * n_components = _connected_components_undirected(csgraph.indices, # <<<<<<<<<<<<<< + * csgraph.indptr, + * csgraph_T.indices, + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":88 + * csgraph_T = csgraph.T.tocsr() + * n_components = _connected_components_undirected(csgraph.indices, + * csgraph.indptr, # <<<<<<<<<<<<<< + * csgraph_T.indices, + * csgraph_T.indptr, + */ + __pyx_t_7 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indptr); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":89 + * n_components = _connected_components_undirected(csgraph.indices, + * csgraph.indptr, + * csgraph_T.indices, # <<<<<<<<<<<<<< + * csgraph_T.indptr, + * labels) + */ + __pyx_t_2 = PyObject_GetAttr(__pyx_v_csgraph_T, __pyx_n_s__indices); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":90 + * csgraph.indptr, + * csgraph_T.indices, + * csgraph_T.indptr, # <<<<<<<<<<<<<< + * labels) + * + */ + __pyx_t_6 = PyObject_GetAttr(__pyx_v_csgraph_T, __pyx_n_s__indptr); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":91 + * csgraph_T.indices, + * csgraph_T.indptr, + * labels) # <<<<<<<<<<<<<< + * + * if return_labels: + */ + if (!(likely(((__pyx_v_labels) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_labels, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __pyx_v_labels; + __Pyx_INCREF(__pyx_t_8); + __pyx_v_n_components = __pyx_f_7sklearn_5utils_3mst_10_traversal__connected_components_undirected(((PyArrayObject *)__pyx_t_1), ((PyArrayObject *)__pyx_t_7), ((PyArrayObject *)__pyx_t_2), ((PyArrayObject *)__pyx_t_6), ((PyArrayObject *)__pyx_t_8)); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + } + __pyx_L5:; + + /* "sklearn/utils/mst/_traversal.pyx":93 + * labels) + * + * if return_labels: # <<<<<<<<<<<<<< + * return n_components, labels + * else: + */ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_return_labels); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_3) { + + /* "sklearn/utils/mst/_traversal.pyx":94 + * + * if return_labels: + * return n_components, labels # <<<<<<<<<<<<<< + * else: + * return n_components + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_8 = PyInt_FromLong(__pyx_v_n_components); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 94; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_labels); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_v_labels); + __Pyx_GIVEREF(__pyx_v_labels); + __pyx_t_8 = 0; + __pyx_r = ((PyObject *)__pyx_t_6); + __pyx_t_6 = 0; + goto __pyx_L0; + goto __pyx_L6; + } + /*else*/ { + + /* "sklearn/utils/mst/_traversal.pyx":96 + * return n_components, labels + * else: + * return n_components # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_6 = PyInt_FromLong(__pyx_v_n_components); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_r = __pyx_t_6; + __pyx_t_6 = 0; + goto __pyx_L0; + } + __pyx_L6:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("sklearn.utils.mst._traversal.connected_components", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_labels); + __Pyx_XDECREF(__pyx_v_csgraph_T); + __Pyx_XDECREF(__pyx_v_csgraph); + __Pyx_XDECREF(__pyx_v_directed); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_3mst_10_traversal_3breadth_first_tree(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_3mst_10_traversal_2breadth_first_tree[] = "\n breadth_first_tree(csgraph, i_start, directed=True)\n\n Return the tree generated by a breadth-first search\n\n Note that a breadth-first tree from a specified node is unique.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n csgraph : array_like or sparse matrix\n The N x N matrix representing the compressed sparse graph. The input\n csgraph will be converted to csr format for the calculation.\n i_start : int\n The index of starting node.\n directed : bool, optional\n If True (default), then operate on a directed graph: only\n move from point i to point j along paths csgraph[i, j].\n If False, then find the shortest path on an undirected graph: the\n algorithm can progress from point i to j along csgraph[i, j] or\n csgraph[j, i].\n\n Returns\n -------\n cstree : csr matrix\n The N x N directed compressed-sparse representation of the breadth-\n first tree drawn from csgraph, starting at the specified node.\n\n Examples\n --------\n The following example shows the computation of a depth-first tree\n over a simple four-component graph, starting at node 0::\n\n input graph breadth first tree from (0)\n\n (0) (0)\n / \\ / \\\n 3 8 3 8\n / \\ / \\\n (3)---5---(1) (3) (1)\n \\ / /\n 6 2 2\n \\ / /\n (2) (2)\n\n In compressed sparse representation, the solution looks like this:\n\n >>> from scipy.sparse import csr_matrix\n >>> from scipy.sparse.csgraph import breadth_first_tree\n >>> X = csr_matrix([[0, 8, 0, 3],\n ... [0, 0, 2, 5],\n ... [0, 0, 0, 6],""\n ... [0, 0, 0, 0]])\n >>> Tcsr = breadth_first_tree(X, 0, directed=False)\n >>> Tcsr.toarray().astype(int)\n array([[0, 8, 0, 3],\n [0, 0, 2, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]])\n\n Note that the resulting graph is a Directed Acyclic Graph which spans\n the graph. A breadth-first tree from a given node is unique.\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_3mst_10_traversal_3breadth_first_tree = {__Pyx_NAMESTR("breadth_first_tree"), (PyCFunction)__pyx_pw_7sklearn_5utils_3mst_10_traversal_3breadth_first_tree, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_3mst_10_traversal_2breadth_first_tree)}; +static PyObject *__pyx_pw_7sklearn_5utils_3mst_10_traversal_3breadth_first_tree(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_csgraph = 0; + PyObject *__pyx_v_i_start = 0; + PyObject *__pyx_v_directed = 0; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__csgraph,&__pyx_n_s__i_start,&__pyx_n_s__directed,0}; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("breadth_first_tree (wrapper)", 0); + __pyx_self = __pyx_self; + { + PyObject* values[3] = {0,0,0}; + values[2] = __pyx_k_5; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__csgraph); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__i_start); + if (likely(values[1])) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("breadth_first_tree", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__directed); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "breadth_first_tree") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_csgraph = values[0]; + __pyx_v_i_start = values[1]; + __pyx_v_directed = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("breadth_first_tree", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils.mst._traversal.breadth_first_tree", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_3mst_10_traversal_2breadth_first_tree(__pyx_self, __pyx_v_csgraph, __pyx_v_i_start, __pyx_v_directed); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/mst/_traversal.pyx":99 + * + * + * def breadth_first_tree(csgraph, i_start, directed=True): # <<<<<<<<<<<<<< + * r""" + * breadth_first_tree(csgraph, i_start, directed=True) + */ + +static PyObject *__pyx_pf_7sklearn_5utils_3mst_10_traversal_2breadth_first_tree(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_i_start, PyObject *__pyx_v_directed) { + CYTHON_UNUSED PyObject *__pyx_v_node_list = NULL; + PyObject *__pyx_v_predecessors = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *(*__pyx_t_5)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("breadth_first_tree", 0); + + /* "sklearn/utils/mst/_traversal.pyx":164 + * the graph. A breadth-first tree from a given node is unique. + * """ + * node_list, predecessors = breadth_first_order(csgraph, i_start, # <<<<<<<<<<<<<< + * directed, True) + * return reconstruct_path(csgraph, predecessors, directed) + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__breadth_first_order); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "sklearn/utils/mst/_traversal.pyx":165 + * """ + * node_list, predecessors = breadth_first_order(csgraph, i_start, + * directed, True) # <<<<<<<<<<<<<< + * return reconstruct_path(csgraph, predecessors, directed) + * + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + __Pyx_INCREF(__pyx_v_i_start); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_i_start); + __Pyx_GIVEREF(__pyx_v_i_start); + __Pyx_INCREF(__pyx_v_directed); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_v_directed); + __Pyx_GIVEREF(__pyx_v_directed); + PyTuple_SET_ITEM(__pyx_t_3, 3, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + if (likely(PyTuple_CheckExact(sequence))) { + if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { + if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); + else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); + } else { + if (unlikely(PyList_GET_SIZE(sequence) != 2)) { + if (PyList_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); + else __Pyx_RaiseNeedMoreValuesError(PyList_GET_SIZE(sequence)); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = PyList_GET_ITEM(sequence, 0); + __pyx_t_1 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_1 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_StopIteration)) PyErr_Clear(); + if (!PyErr_Occurred()) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L4_unpacking_done:; + } + + /* "sklearn/utils/mst/_traversal.pyx":164 + * the graph. A breadth-first tree from a given node is unique. + * """ + * node_list, predecessors = breadth_first_order(csgraph, i_start, # <<<<<<<<<<<<<< + * directed, True) + * return reconstruct_path(csgraph, predecessors, directed) + */ + __pyx_v_node_list = __pyx_t_3; + __pyx_t_3 = 0; + __pyx_v_predecessors = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":166 + * node_list, predecessors = breadth_first_order(csgraph, i_start, + * directed, True) + * return reconstruct_path(csgraph, predecessors, directed) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__reconstruct_path); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + __Pyx_INCREF(__pyx_v_predecessors); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_predecessors); + __Pyx_GIVEREF(__pyx_v_predecessors); + __Pyx_INCREF(__pyx_v_directed); + PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_directed); + __Pyx_GIVEREF(__pyx_v_directed); + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.utils.mst._traversal.breadth_first_tree", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_node_list); + __Pyx_XDECREF(__pyx_v_predecessors); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_3mst_10_traversal_5depth_first_tree(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_3mst_10_traversal_4depth_first_tree[] = "\n depth_first_tree(csgraph, i_start, directed=True)\n\n Return a tree generated by a depth-first search.\n\n Note that a tree generated by a depth-first search is not unique:\n it depends on the order that the children of each node are searched.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n csgraph : array_like or sparse matrix\n The N x N matrix representing the compressed sparse graph. The input\n csgraph will be converted to csr format for the calculation.\n i_start : int\n The index of starting node.\n directed : bool, optional\n If True (default), then operate on a directed graph: only\n move from point i to point j along paths csgraph[i, j].\n If False, then find the shortest path on an undirected graph: the\n algorithm can progress from point i to j along csgraph[i, j] or\n csgraph[j, i].\n\n Returns\n -------\n cstree : csr matrix\n The N x N directed compressed-sparse representation of the depth-\n first tree drawn from csgraph, starting at the specified node.\n\n Examples\n --------\n The following example shows the computation of a depth-first tree\n over a simple four-component graph, starting at node 0::\n\n input graph depth first tree from (0)\n\n (0) (0)\n / \\ \\\n 3 8 8\n / \\ \\\n (3)---5---(1) (3) (1)\n \\ / \\ /\n 6 2 6 2\n \\ / \\ /\n (2) (2)\n\n In compressed sparse representation, the solution looks like this:\n\n >>> from scipy.sparse import csr_matrix\n >>> from scipy.sparse.csgraph import depth_first_tree\n >>> X = csr_matrix([[0, 8, 0, 3],\n ... "" [0, 0, 2, 5],\n ... [0, 0, 0, 6],\n ... [0, 0, 0, 0]])\n >>> Tcsr = depth_first_tree(X, 0, directed=False)\n >>> Tcsr.toarray().astype(int)\n array([[0, 8, 0, 0],\n [0, 0, 2, 0],\n [0, 0, 0, 6],\n [0, 0, 0, 0]])\n\n Note that the resulting graph is a Directed Acyclic Graph which spans\n the graph. Unlike a breadth-first tree, a depth-first tree of a given\n graph is not unique if the graph contains cycles. If the above solution\n had begun with the edge connecting nodes 0 and 3, the result would have\n been different.\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_3mst_10_traversal_5depth_first_tree = {__Pyx_NAMESTR("depth_first_tree"), (PyCFunction)__pyx_pw_7sklearn_5utils_3mst_10_traversal_5depth_first_tree, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_3mst_10_traversal_4depth_first_tree)}; +static PyObject *__pyx_pw_7sklearn_5utils_3mst_10_traversal_5depth_first_tree(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_csgraph = 0; + PyObject *__pyx_v_i_start = 0; + PyObject *__pyx_v_directed = 0; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__csgraph,&__pyx_n_s__i_start,&__pyx_n_s__directed,0}; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("depth_first_tree (wrapper)", 0); + __pyx_self = __pyx_self; + { + PyObject* values[3] = {0,0,0}; + values[2] = __pyx_k_6; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__csgraph); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__i_start); + if (likely(values[1])) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("depth_first_tree", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__directed); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "depth_first_tree") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_csgraph = values[0]; + __pyx_v_i_start = values[1]; + __pyx_v_directed = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("depth_first_tree", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils.mst._traversal.depth_first_tree", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_3mst_10_traversal_4depth_first_tree(__pyx_self, __pyx_v_csgraph, __pyx_v_i_start, __pyx_v_directed); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/mst/_traversal.pyx":169 + * + * + * def depth_first_tree(csgraph, i_start, directed=True): # <<<<<<<<<<<<<< + * r""" + * depth_first_tree(csgraph, i_start, directed=True) + */ + +static PyObject *__pyx_pf_7sklearn_5utils_3mst_10_traversal_4depth_first_tree(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_i_start, PyObject *__pyx_v_directed) { + CYTHON_UNUSED PyObject *__pyx_v_node_list = NULL; + PyObject *__pyx_v_predecessors = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *(*__pyx_t_5)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("depth_first_tree", 0); + + /* "sklearn/utils/mst/_traversal.pyx":238 + * been different. + * """ + * node_list, predecessors = depth_first_order(csgraph, i_start, # <<<<<<<<<<<<<< + * directed, True) + * return reconstruct_path(csgraph, predecessors, directed) + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__depth_first_order); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + + /* "sklearn/utils/mst/_traversal.pyx":239 + * """ + * node_list, predecessors = depth_first_order(csgraph, i_start, + * directed, True) # <<<<<<<<<<<<<< + * return reconstruct_path(csgraph, predecessors, directed) + * + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + __Pyx_INCREF(__pyx_v_i_start); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_i_start); + __Pyx_GIVEREF(__pyx_v_i_start); + __Pyx_INCREF(__pyx_v_directed); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_v_directed); + __Pyx_GIVEREF(__pyx_v_directed); + PyTuple_SET_ITEM(__pyx_t_3, 3, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + if (likely(PyTuple_CheckExact(sequence))) { + if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { + if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); + else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); + } else { + if (unlikely(PyList_GET_SIZE(sequence) != 2)) { + if (PyList_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); + else __Pyx_RaiseNeedMoreValuesError(PyList_GET_SIZE(sequence)); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = PyList_GET_ITEM(sequence, 0); + __pyx_t_1 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_1 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_StopIteration)) PyErr_Clear(); + if (!PyErr_Occurred()) __Pyx_RaiseNeedMoreValuesError(index); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L4_unpacking_done:; + } + + /* "sklearn/utils/mst/_traversal.pyx":238 + * been different. + * """ + * node_list, predecessors = depth_first_order(csgraph, i_start, # <<<<<<<<<<<<<< + * directed, True) + * return reconstruct_path(csgraph, predecessors, directed) + */ + __pyx_v_node_list = __pyx_t_3; + __pyx_t_3 = 0; + __pyx_v_predecessors = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":240 + * node_list, predecessors = depth_first_order(csgraph, i_start, + * directed, True) + * return reconstruct_path(csgraph, predecessors, directed) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__reconstruct_path); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + __Pyx_INCREF(__pyx_v_predecessors); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_predecessors); + __Pyx_GIVEREF(__pyx_v_predecessors); + __Pyx_INCREF(__pyx_v_directed); + PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_directed); + __Pyx_GIVEREF(__pyx_v_directed); + __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.utils.mst._traversal.depth_first_tree", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_node_list); + __Pyx_XDECREF(__pyx_v_predecessors); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_3mst_10_traversal_7breadth_first_order(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_3mst_10_traversal_6breadth_first_order[] = "\n breadth_first_order(csgraph, i_start, directed=True, return_predecessors=True)\n\n Return a breadth-first ordering starting with specified node.\n\n Note that a breadth-first order is not unique, but the tree which it\n generates is unique.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n csgraph : array_like or sparse matrix\n The N x N compressed sparse graph. The input csgraph will be\n converted to csr format for the calculation.\n i_start : int\n The index of starting node.\n directed : bool, optional\n If True (default), then operate on a directed graph: only\n move from point i to point j along paths csgraph[i, j].\n If False, then find the shortest path on an undirected graph: the\n algorithm can progress from point i to j along csgraph[i, j] or\n csgraph[j, i].\n return_predecessors : bool, optional\n If True (default), then return the predecesor array (see below).\n\n Returns\n -------\n node_array : ndarray, one dimension\n The breadth-first list of nodes, starting with specified node. The\n length of node_array is the number of nodes reachable from the\n specified node.\n predecessors : ndarray, one dimension\n Returned only if return_predecessors is True.\n The length-N list of predecessors of each node in a breadth-first\n tree. If node i is in the tree, then its parent is given by\n predecessors[i]. If node i is not in the tree (and for the parent\n node) then predecessors[i] = -9999.\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_3mst_10_traversal_7breadth_first_order = {__Pyx_NAMESTR("breadth_first_order"), (PyCFunction)__pyx_pw_7sklearn_5utils_3mst_10_traversal_7breadth_first_order, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_3mst_10_traversal_6breadth_first_order)}; +static PyObject *__pyx_pw_7sklearn_5utils_3mst_10_traversal_7breadth_first_order(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_csgraph = 0; + PyObject *__pyx_v_i_start = 0; + PyObject *__pyx_v_directed = 0; + PyObject *__pyx_v_return_predecessors = 0; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__csgraph,&__pyx_n_s__i_start,&__pyx_n_s__directed,&__pyx_n_s__return_predecessors,0}; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("breadth_first_order (wrapper)", 0); + __pyx_self = __pyx_self; + { + PyObject* values[4] = {0,0,0,0}; + values[2] = __pyx_k_7; + values[3] = __pyx_k_8; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__csgraph); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__i_start); + if (likely(values[1])) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("breadth_first_order", 0, 2, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__directed); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__return_predecessors); + if (value) { values[3] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "breadth_first_order") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_csgraph = values[0]; + __pyx_v_i_start = values[1]; + __pyx_v_directed = values[2]; + __pyx_v_return_predecessors = values[3]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("breadth_first_order", 0, 2, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils.mst._traversal.breadth_first_order", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_3mst_10_traversal_6breadth_first_order(__pyx_self, __pyx_v_csgraph, __pyx_v_i_start, __pyx_v_directed, __pyx_v_return_predecessors); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/mst/_traversal.pyx":243 + * + * + * def breadth_first_order(csgraph, i_start, # <<<<<<<<<<<<<< + * directed=True, return_predecessors=True): + * """ + */ + +static PyObject *__pyx_pf_7sklearn_5utils_3mst_10_traversal_6breadth_first_order(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_i_start, PyObject *__pyx_v_directed, PyObject *__pyx_v_return_predecessors) { + int __pyx_v_N; + PyArrayObject *__pyx_v_node_list = 0; + PyArrayObject *__pyx_v_predecessors = 0; + unsigned int __pyx_v_length; + PyObject *__pyx_v_csgraph_T = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + unsigned int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("breadth_first_order", 0); + __Pyx_INCREF(__pyx_v_csgraph); + + /* "sklearn/utils/mst/_traversal.pyx":285 + * """ + * global NULL_IDX + * csgraph = validate_graph(csgraph, directed, dense_output=False) # <<<<<<<<<<<<<< + * cdef int N = csgraph.shape[0] + * + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__validate_graph); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + __Pyx_INCREF(__pyx_v_directed); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_directed); + __Pyx_GIVEREF(__pyx_v_directed); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dense_output), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_v_csgraph); + __pyx_v_csgraph = __pyx_t_4; + __pyx_t_4 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":286 + * global NULL_IDX + * csgraph = validate_graph(csgraph, directed, dense_output=False) + * cdef int N = csgraph.shape[0] # <<<<<<<<<<<<<< + * + * cdef np.ndarray node_list = np.empty(N, dtype=ITYPE) + */ + __pyx_t_4 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_4, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_AsInt(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_N = __pyx_t_5; + + /* "sklearn/utils/mst/_traversal.pyx":288 + * cdef int N = csgraph.shape[0] + * + * cdef np.ndarray node_list = np.empty(N, dtype=ITYPE) # <<<<<<<<<<<<<< + * cdef np.ndarray predecessors = np.empty(N, dtype=ITYPE) + * node_list.fill(NULL_IDX) + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyInt_FromLong(__pyx_v_N); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_node_list = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":289 + * + * cdef np.ndarray node_list = np.empty(N, dtype=ITYPE) + * cdef np.ndarray predecessors = np.empty(N, dtype=ITYPE) # <<<<<<<<<<<<<< + * node_list.fill(NULL_IDX) + * predecessors.fill(NULL_IDX) + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyInt_FromLong(__pyx_v_N); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_predecessors = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":290 + * cdef np.ndarray node_list = np.empty(N, dtype=ITYPE) + * cdef np.ndarray predecessors = np.empty(N, dtype=ITYPE) + * node_list.fill(NULL_IDX) # <<<<<<<<<<<<<< + * predecessors.fill(NULL_IDX) + * + */ + __pyx_t_4 = PyObject_GetAttr(((PyObject *)__pyx_v_node_list), __pyx_n_s__fill); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_7sklearn_5utils_3mst_10_traversal_NULL_IDX); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":291 + * cdef np.ndarray predecessors = np.empty(N, dtype=ITYPE) + * node_list.fill(NULL_IDX) + * predecessors.fill(NULL_IDX) # <<<<<<<<<<<<<< + * + * if directed: + */ + __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_predecessors), __pyx_n_s__fill); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_7sklearn_5utils_3mst_10_traversal_NULL_IDX); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 291; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":293 + * predecessors.fill(NULL_IDX) + * + * if directed: # <<<<<<<<<<<<<< + * length = _breadth_first_directed(i_start, + * csgraph.indices, csgraph.indptr, + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_directed); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 293; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "sklearn/utils/mst/_traversal.pyx":294 + * + * if directed: + * length = _breadth_first_directed(i_start, # <<<<<<<<<<<<<< + * csgraph.indices, csgraph.indptr, + * node_list, predecessors) + */ + __pyx_t_7 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_i_start); if (unlikely((__pyx_t_7 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":295 + * if directed: + * length = _breadth_first_directed(i_start, + * csgraph.indices, csgraph.indptr, # <<<<<<<<<<<<<< + * node_list, predecessors) + * else: + */ + __pyx_t_2 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indices); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 295; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 295; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indptr); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 295; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 295; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":296 + * length = _breadth_first_directed(i_start, + * csgraph.indices, csgraph.indptr, + * node_list, predecessors) # <<<<<<<<<<<<<< + * else: + * csgraph_T = csgraph.T.tocsr() + */ + __pyx_v_length = __pyx_f_7sklearn_5utils_3mst_10_traversal__breadth_first_directed(__pyx_t_7, ((PyArrayObject *)__pyx_t_2), ((PyArrayObject *)__pyx_t_4), ((PyArrayObject *)__pyx_v_node_list), ((PyArrayObject *)__pyx_v_predecessors)); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/utils/mst/_traversal.pyx":298 + * node_list, predecessors) + * else: + * csgraph_T = csgraph.T.tocsr() # <<<<<<<<<<<<<< + * length = _breadth_first_undirected(i_start, + * csgraph.indices, csgraph.indptr, + */ + __pyx_t_4 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__T); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__tocsr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_csgraph_T = __pyx_t_4; + __pyx_t_4 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":299 + * else: + * csgraph_T = csgraph.T.tocsr() + * length = _breadth_first_undirected(i_start, # <<<<<<<<<<<<<< + * csgraph.indices, csgraph.indptr, + * csgraph_T.indices, csgraph_T.indptr, + */ + __pyx_t_7 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_i_start); if (unlikely((__pyx_t_7 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 299; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":300 + * csgraph_T = csgraph.T.tocsr() + * length = _breadth_first_undirected(i_start, + * csgraph.indices, csgraph.indptr, # <<<<<<<<<<<<<< + * csgraph_T.indices, csgraph_T.indptr, + * node_list, predecessors) + */ + __pyx_t_4 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indptr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":301 + * length = _breadth_first_undirected(i_start, + * csgraph.indices, csgraph.indptr, + * csgraph_T.indices, csgraph_T.indptr, # <<<<<<<<<<<<<< + * node_list, predecessors) + * + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_csgraph_T, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetAttr(__pyx_v_csgraph_T, __pyx_n_s__indptr); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 301; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":302 + * csgraph.indices, csgraph.indptr, + * csgraph_T.indices, csgraph_T.indptr, + * node_list, predecessors) # <<<<<<<<<<<<<< + * + * if return_predecessors: + */ + __pyx_v_length = __pyx_f_7sklearn_5utils_3mst_10_traversal__breadth_first_undirected(__pyx_t_7, ((PyArrayObject *)__pyx_t_4), ((PyArrayObject *)__pyx_t_2), ((PyArrayObject *)__pyx_t_1), ((PyArrayObject *)__pyx_t_3), ((PyArrayObject *)__pyx_v_node_list), ((PyArrayObject *)__pyx_v_predecessors)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + /* "sklearn/utils/mst/_traversal.pyx":304 + * node_list, predecessors) + * + * if return_predecessors: # <<<<<<<<<<<<<< + * return node_list[:length], predecessors + * else: + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_return_predecessors); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 304; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "sklearn/utils/mst/_traversal.pyx":305 + * + * if return_predecessors: + * return node_list[:length], predecessors # <<<<<<<<<<<<<< + * else: + * return node_list[:length] + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __Pyx_PySequence_GetSlice(((PyObject *)__pyx_v_node_list), 0, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_predecessors)); + PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_predecessors)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_predecessors)); + __pyx_t_3 = 0; + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + goto __pyx_L4; + } + /*else*/ { + + /* "sklearn/utils/mst/_traversal.pyx":307 + * return node_list[:length], predecessors + * else: + * return node_list[:length] # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PySequence_GetSlice(((PyObject *)__pyx_v_node_list), 0, __pyx_v_length); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 307; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + } + __pyx_L4:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("sklearn.utils.mst._traversal.breadth_first_order", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_node_list); + __Pyx_XDECREF((PyObject *)__pyx_v_predecessors); + __Pyx_XDECREF(__pyx_v_csgraph_T); + __Pyx_XDECREF(__pyx_v_csgraph); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/mst/_traversal.pyx":310 + * + * + * cdef unsigned int _breadth_first_directed( # <<<<<<<<<<<<<< + * unsigned int head_node, + * np.ndarray[ITYPE_t, ndim=1, mode='c'] indices, + */ + +static unsigned int __pyx_f_7sklearn_5utils_3mst_10_traversal__breadth_first_directed(unsigned int __pyx_v_head_node, PyArrayObject *__pyx_v_indices, PyArrayObject *__pyx_v_indptr, PyArrayObject *__pyx_v_node_list, PyArrayObject *__pyx_v_predecessors) { + unsigned int __pyx_v_i; + unsigned int __pyx_v_pnode; + unsigned int __pyx_v_cnode; + unsigned int __pyx_v_i_nl; + unsigned int __pyx_v_i_nl_end; + CYTHON_UNUSED unsigned int __pyx_v_N; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices; + __Pyx_Buffer __pyx_pybuffer_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr; + __Pyx_Buffer __pyx_pybuffer_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_node_list; + __Pyx_Buffer __pyx_pybuffer_node_list; + __Pyx_LocalBuf_ND __pyx_pybuffernd_predecessors; + __Pyx_Buffer __pyx_pybuffer_predecessors; + unsigned int __pyx_r; + __Pyx_RefNannyDeclarations + long __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + unsigned int __pyx_t_4; + unsigned int __pyx_t_5; + long __pyx_t_6; + __pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t __pyx_t_7; + unsigned int __pyx_t_8; + unsigned int __pyx_t_9; + unsigned int __pyx_t_10; + unsigned int __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_breadth_first_directed", 0); + __pyx_pybuffer_indices.pybuffer.buf = NULL; + __pyx_pybuffer_indices.refcount = 0; + __pyx_pybuffernd_indices.data = NULL; + __pyx_pybuffernd_indices.rcbuffer = &__pyx_pybuffer_indices; + __pyx_pybuffer_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_indptr.refcount = 0; + __pyx_pybuffernd_indptr.data = NULL; + __pyx_pybuffernd_indptr.rcbuffer = &__pyx_pybuffer_indptr; + __pyx_pybuffer_node_list.pybuffer.buf = NULL; + __pyx_pybuffer_node_list.refcount = 0; + __pyx_pybuffernd_node_list.data = NULL; + __pyx_pybuffernd_node_list.rcbuffer = &__pyx_pybuffer_node_list; + __pyx_pybuffer_predecessors.pybuffer.buf = NULL; + __pyx_pybuffer_predecessors.refcount = 0; + __pyx_pybuffernd_predecessors.data = NULL; + __pyx_pybuffernd_predecessors.rcbuffer = &__pyx_pybuffer_predecessors; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indices.diminfo[0].strides = __pyx_pybuffernd_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices.diminfo[0].shape = __pyx_pybuffernd_indices.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indptr.diminfo[0].strides = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr.diminfo[0].shape = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer, (PyObject*)__pyx_v_node_list, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_node_list.diminfo[0].strides = __pyx_pybuffernd_node_list.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_node_list.diminfo[0].shape = __pyx_pybuffernd_node_list.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer, (PyObject*)__pyx_v_predecessors, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_predecessors.diminfo[0].strides = __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_predecessors.diminfo[0].shape = __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/utils/mst/_traversal.pyx":329 + * cdef unsigned int i, pnode, cnode + * cdef unsigned int i_nl, i_nl_end + * cdef unsigned int N = node_list.shape[0] # <<<<<<<<<<<<<< + * + * node_list[0] = head_node + */ + __pyx_v_N = (__pyx_v_node_list->dimensions[0]); + + /* "sklearn/utils/mst/_traversal.pyx":331 + * cdef unsigned int N = node_list.shape[0] + * + * node_list[0] = head_node # <<<<<<<<<<<<<< + * i_nl = 0 + * i_nl_end = 1 + */ + __pyx_t_1 = 0; + __pyx_t_2 = -1; + if (__pyx_t_1 < 0) { + __pyx_t_1 += __pyx_pybuffernd_node_list.diminfo[0].shape; + if (unlikely(__pyx_t_1 < 0)) __pyx_t_2 = 0; + } else if (unlikely(__pyx_t_1 >= __pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_1, __pyx_pybuffernd_node_list.diminfo[0].strides) = __pyx_v_head_node; + + /* "sklearn/utils/mst/_traversal.pyx":332 + * + * node_list[0] = head_node + * i_nl = 0 # <<<<<<<<<<<<<< + * i_nl_end = 1 + * + */ + __pyx_v_i_nl = 0; + + /* "sklearn/utils/mst/_traversal.pyx":333 + * node_list[0] = head_node + * i_nl = 0 + * i_nl_end = 1 # <<<<<<<<<<<<<< + * + * while i_nl < i_nl_end: + */ + __pyx_v_i_nl_end = 1; + + /* "sklearn/utils/mst/_traversal.pyx":335 + * i_nl_end = 1 + * + * while i_nl < i_nl_end: # <<<<<<<<<<<<<< + * pnode = node_list[i_nl] + * + */ + while (1) { + __pyx_t_3 = (__pyx_v_i_nl < __pyx_v_i_nl_end); + if (!__pyx_t_3) break; + + /* "sklearn/utils/mst/_traversal.pyx":336 + * + * while i_nl < i_nl_end: + * pnode = node_list[i_nl] # <<<<<<<<<<<<<< + * + * for i from indptr[pnode] <= i < indptr[pnode + 1]: + */ + __pyx_t_4 = __pyx_v_i_nl; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_4 >= (size_t)__pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 336; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_pnode = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_node_list.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":338 + * pnode = node_list[i_nl] + * + * for i from indptr[pnode] <= i < indptr[pnode + 1]: # <<<<<<<<<<<<<< + * cnode = indices[i] + * if (cnode == head_node): + */ + __pyx_t_5 = __pyx_v_pnode; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_5 >= (size_t)__pyx_pybuffernd_indptr.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 338; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_6 = (__pyx_v_pnode + 1); + __pyx_t_2 = -1; + if (__pyx_t_6 < 0) { + __pyx_t_6 += __pyx_pybuffernd_indptr.diminfo[0].shape; + if (unlikely(__pyx_t_6 < 0)) __pyx_t_2 = 0; + } else if (unlikely(__pyx_t_6 >= __pyx_pybuffernd_indptr.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 338; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_7 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_indptr.diminfo[0].strides)); + for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_indptr.diminfo[0].strides)); __pyx_v_i < __pyx_t_7; __pyx_v_i++) { + + /* "sklearn/utils/mst/_traversal.pyx":339 + * + * for i from indptr[pnode] <= i < indptr[pnode + 1]: + * cnode = indices[i] # <<<<<<<<<<<<<< + * if (cnode == head_node): + * continue + */ + __pyx_t_8 = __pyx_v_i; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_8 >= (size_t)__pyx_pybuffernd_indices.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 339; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_cnode = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indices.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_indices.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":340 + * for i from indptr[pnode] <= i < indptr[pnode + 1]: + * cnode = indices[i] + * if (cnode == head_node): # <<<<<<<<<<<<<< + * continue + * elif (predecessors[cnode] == NULL_IDX): + */ + __pyx_t_3 = (__pyx_v_cnode == __pyx_v_head_node); + if (__pyx_t_3) { + + /* "sklearn/utils/mst/_traversal.pyx":341 + * cnode = indices[i] + * if (cnode == head_node): + * continue # <<<<<<<<<<<<<< + * elif (predecessors[cnode] == NULL_IDX): + * node_list[i_nl_end] = cnode + */ + goto __pyx_L5_continue; + goto __pyx_L7; + } + + /* "sklearn/utils/mst/_traversal.pyx":342 + * if (cnode == head_node): + * continue + * elif (predecessors[cnode] == NULL_IDX): # <<<<<<<<<<<<<< + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + */ + __pyx_t_9 = __pyx_v_cnode; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_9 >= (size_t)__pyx_pybuffernd_predecessors.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 342; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_predecessors.diminfo[0].strides)) == __pyx_v_7sklearn_5utils_3mst_10_traversal_NULL_IDX); + if (__pyx_t_3) { + + /* "sklearn/utils/mst/_traversal.pyx":343 + * continue + * elif (predecessors[cnode] == NULL_IDX): + * node_list[i_nl_end] = cnode # <<<<<<<<<<<<<< + * predecessors[cnode] = pnode + * i_nl_end += 1 + */ + __pyx_t_10 = __pyx_v_i_nl_end; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_10 >= (size_t)__pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_node_list.diminfo[0].strides) = __pyx_v_cnode; + + /* "sklearn/utils/mst/_traversal.pyx":344 + * elif (predecessors[cnode] == NULL_IDX): + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode # <<<<<<<<<<<<<< + * i_nl_end += 1 + * + */ + __pyx_t_11 = __pyx_v_cnode; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_11 >= (size_t)__pyx_pybuffernd_predecessors.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 344; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_predecessors.diminfo[0].strides) = __pyx_v_pnode; + + /* "sklearn/utils/mst/_traversal.pyx":345 + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + * i_nl_end += 1 # <<<<<<<<<<<<<< + * + * i_nl += 1 + */ + __pyx_v_i_nl_end = (__pyx_v_i_nl_end + 1); + goto __pyx_L7; + } + __pyx_L7:; + __pyx_L5_continue:; + } + + /* "sklearn/utils/mst/_traversal.pyx":347 + * i_nl_end += 1 + * + * i_nl += 1 # <<<<<<<<<<<<<< + * + * return i_nl + */ + __pyx_v_i_nl = (__pyx_v_i_nl + 1); + } + + /* "sklearn/utils/mst/_traversal.pyx":349 + * i_nl += 1 + * + * return i_nl # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_i_nl; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_WriteUnraisable("sklearn.utils.mst._traversal._breadth_first_directed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/mst/_traversal.pyx":352 + * + * + * cdef unsigned int _breadth_first_undirected( # <<<<<<<<<<<<<< + * unsigned int head_node, + * np.ndarray[ITYPE_t, ndim=1, mode='c'] indices1, + */ + +static unsigned int __pyx_f_7sklearn_5utils_3mst_10_traversal__breadth_first_undirected(unsigned int __pyx_v_head_node, PyArrayObject *__pyx_v_indices1, PyArrayObject *__pyx_v_indptr1, PyArrayObject *__pyx_v_indices2, PyArrayObject *__pyx_v_indptr2, PyArrayObject *__pyx_v_node_list, PyArrayObject *__pyx_v_predecessors) { + unsigned int __pyx_v_i; + unsigned int __pyx_v_pnode; + unsigned int __pyx_v_cnode; + unsigned int __pyx_v_i_nl; + unsigned int __pyx_v_i_nl_end; + CYTHON_UNUSED unsigned int __pyx_v_N; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices1; + __Pyx_Buffer __pyx_pybuffer_indices1; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices2; + __Pyx_Buffer __pyx_pybuffer_indices2; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr1; + __Pyx_Buffer __pyx_pybuffer_indptr1; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr2; + __Pyx_Buffer __pyx_pybuffer_indptr2; + __Pyx_LocalBuf_ND __pyx_pybuffernd_node_list; + __Pyx_Buffer __pyx_pybuffer_node_list; + __Pyx_LocalBuf_ND __pyx_pybuffernd_predecessors; + __Pyx_Buffer __pyx_pybuffer_predecessors; + unsigned int __pyx_r; + __Pyx_RefNannyDeclarations + long __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + unsigned int __pyx_t_4; + unsigned int __pyx_t_5; + long __pyx_t_6; + __pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t __pyx_t_7; + unsigned int __pyx_t_8; + unsigned int __pyx_t_9; + unsigned int __pyx_t_10; + unsigned int __pyx_t_11; + unsigned int __pyx_t_12; + long __pyx_t_13; + unsigned int __pyx_t_14; + unsigned int __pyx_t_15; + unsigned int __pyx_t_16; + unsigned int __pyx_t_17; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_breadth_first_undirected", 0); + __pyx_pybuffer_indices1.pybuffer.buf = NULL; + __pyx_pybuffer_indices1.refcount = 0; + __pyx_pybuffernd_indices1.data = NULL; + __pyx_pybuffernd_indices1.rcbuffer = &__pyx_pybuffer_indices1; + __pyx_pybuffer_indptr1.pybuffer.buf = NULL; + __pyx_pybuffer_indptr1.refcount = 0; + __pyx_pybuffernd_indptr1.data = NULL; + __pyx_pybuffernd_indptr1.rcbuffer = &__pyx_pybuffer_indptr1; + __pyx_pybuffer_indices2.pybuffer.buf = NULL; + __pyx_pybuffer_indices2.refcount = 0; + __pyx_pybuffernd_indices2.data = NULL; + __pyx_pybuffernd_indices2.rcbuffer = &__pyx_pybuffer_indices2; + __pyx_pybuffer_indptr2.pybuffer.buf = NULL; + __pyx_pybuffer_indptr2.refcount = 0; + __pyx_pybuffernd_indptr2.data = NULL; + __pyx_pybuffernd_indptr2.rcbuffer = &__pyx_pybuffer_indptr2; + __pyx_pybuffer_node_list.pybuffer.buf = NULL; + __pyx_pybuffer_node_list.refcount = 0; + __pyx_pybuffernd_node_list.data = NULL; + __pyx_pybuffernd_node_list.rcbuffer = &__pyx_pybuffer_node_list; + __pyx_pybuffer_predecessors.pybuffer.buf = NULL; + __pyx_pybuffer_predecessors.refcount = 0; + __pyx_pybuffernd_predecessors.data = NULL; + __pyx_pybuffernd_predecessors.rcbuffer = &__pyx_pybuffer_predecessors; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices1.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indices1.diminfo[0].strides = __pyx_pybuffernd_indices1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices1.diminfo[0].shape = __pyx_pybuffernd_indices1.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indptr1.diminfo[0].strides = __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr1.diminfo[0].shape = __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices2.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indices2.diminfo[0].strides = __pyx_pybuffernd_indices2.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices2.diminfo[0].shape = __pyx_pybuffernd_indices2.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indptr2.diminfo[0].strides = __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr2.diminfo[0].shape = __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer, (PyObject*)__pyx_v_node_list, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_node_list.diminfo[0].strides = __pyx_pybuffernd_node_list.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_node_list.diminfo[0].shape = __pyx_pybuffernd_node_list.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer, (PyObject*)__pyx_v_predecessors, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_predecessors.diminfo[0].strides = __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_predecessors.diminfo[0].shape = __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/utils/mst/_traversal.pyx":375 + * cdef unsigned int i, pnode, cnode + * cdef unsigned int i_nl, i_nl_end + * cdef unsigned int N = node_list.shape[0] # <<<<<<<<<<<<<< + * + * node_list[0] = head_node + */ + __pyx_v_N = (__pyx_v_node_list->dimensions[0]); + + /* "sklearn/utils/mst/_traversal.pyx":377 + * cdef unsigned int N = node_list.shape[0] + * + * node_list[0] = head_node # <<<<<<<<<<<<<< + * i_nl = 0 + * i_nl_end = 1 + */ + __pyx_t_1 = 0; + __pyx_t_2 = -1; + if (__pyx_t_1 < 0) { + __pyx_t_1 += __pyx_pybuffernd_node_list.diminfo[0].shape; + if (unlikely(__pyx_t_1 < 0)) __pyx_t_2 = 0; + } else if (unlikely(__pyx_t_1 >= __pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_1, __pyx_pybuffernd_node_list.diminfo[0].strides) = __pyx_v_head_node; + + /* "sklearn/utils/mst/_traversal.pyx":378 + * + * node_list[0] = head_node + * i_nl = 0 # <<<<<<<<<<<<<< + * i_nl_end = 1 + * + */ + __pyx_v_i_nl = 0; + + /* "sklearn/utils/mst/_traversal.pyx":379 + * node_list[0] = head_node + * i_nl = 0 + * i_nl_end = 1 # <<<<<<<<<<<<<< + * + * while i_nl < i_nl_end: + */ + __pyx_v_i_nl_end = 1; + + /* "sklearn/utils/mst/_traversal.pyx":381 + * i_nl_end = 1 + * + * while i_nl < i_nl_end: # <<<<<<<<<<<<<< + * pnode = node_list[i_nl] + * + */ + while (1) { + __pyx_t_3 = (__pyx_v_i_nl < __pyx_v_i_nl_end); + if (!__pyx_t_3) break; + + /* "sklearn/utils/mst/_traversal.pyx":382 + * + * while i_nl < i_nl_end: + * pnode = node_list[i_nl] # <<<<<<<<<<<<<< + * + * for i from indptr1[pnode] <= i < indptr1[pnode + 1]: + */ + __pyx_t_4 = __pyx_v_i_nl; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_4 >= (size_t)__pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 382; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_pnode = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_node_list.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":384 + * pnode = node_list[i_nl] + * + * for i from indptr1[pnode] <= i < indptr1[pnode + 1]: # <<<<<<<<<<<<<< + * cnode = indices1[i] + * if (cnode == head_node): + */ + __pyx_t_5 = __pyx_v_pnode; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_5 >= (size_t)__pyx_pybuffernd_indptr1.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_6 = (__pyx_v_pnode + 1); + __pyx_t_2 = -1; + if (__pyx_t_6 < 0) { + __pyx_t_6 += __pyx_pybuffernd_indptr1.diminfo[0].shape; + if (unlikely(__pyx_t_6 < 0)) __pyx_t_2 = 0; + } else if (unlikely(__pyx_t_6 >= __pyx_pybuffernd_indptr1.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_7 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_indptr1.diminfo[0].strides)); + for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_indptr1.diminfo[0].strides)); __pyx_v_i < __pyx_t_7; __pyx_v_i++) { + + /* "sklearn/utils/mst/_traversal.pyx":385 + * + * for i from indptr1[pnode] <= i < indptr1[pnode + 1]: + * cnode = indices1[i] # <<<<<<<<<<<<<< + * if (cnode == head_node): + * continue + */ + __pyx_t_8 = __pyx_v_i; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_8 >= (size_t)__pyx_pybuffernd_indices1.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_cnode = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indices1.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_indices1.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":386 + * for i from indptr1[pnode] <= i < indptr1[pnode + 1]: + * cnode = indices1[i] + * if (cnode == head_node): # <<<<<<<<<<<<<< + * continue + * elif (predecessors[cnode] == NULL_IDX): + */ + __pyx_t_3 = (__pyx_v_cnode == __pyx_v_head_node); + if (__pyx_t_3) { + + /* "sklearn/utils/mst/_traversal.pyx":387 + * cnode = indices1[i] + * if (cnode == head_node): + * continue # <<<<<<<<<<<<<< + * elif (predecessors[cnode] == NULL_IDX): + * node_list[i_nl_end] = cnode + */ + goto __pyx_L5_continue; + goto __pyx_L7; + } + + /* "sklearn/utils/mst/_traversal.pyx":388 + * if (cnode == head_node): + * continue + * elif (predecessors[cnode] == NULL_IDX): # <<<<<<<<<<<<<< + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + */ + __pyx_t_9 = __pyx_v_cnode; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_9 >= (size_t)__pyx_pybuffernd_predecessors.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 388; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_predecessors.diminfo[0].strides)) == __pyx_v_7sklearn_5utils_3mst_10_traversal_NULL_IDX); + if (__pyx_t_3) { + + /* "sklearn/utils/mst/_traversal.pyx":389 + * continue + * elif (predecessors[cnode] == NULL_IDX): + * node_list[i_nl_end] = cnode # <<<<<<<<<<<<<< + * predecessors[cnode] = pnode + * i_nl_end += 1 + */ + __pyx_t_10 = __pyx_v_i_nl_end; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_10 >= (size_t)__pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 389; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_node_list.diminfo[0].strides) = __pyx_v_cnode; + + /* "sklearn/utils/mst/_traversal.pyx":390 + * elif (predecessors[cnode] == NULL_IDX): + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode # <<<<<<<<<<<<<< + * i_nl_end += 1 + * + */ + __pyx_t_11 = __pyx_v_cnode; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_11 >= (size_t)__pyx_pybuffernd_predecessors.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_predecessors.diminfo[0].strides) = __pyx_v_pnode; + + /* "sklearn/utils/mst/_traversal.pyx":391 + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + * i_nl_end += 1 # <<<<<<<<<<<<<< + * + * for i from indptr2[pnode] <= i < indptr2[pnode + 1]: + */ + __pyx_v_i_nl_end = (__pyx_v_i_nl_end + 1); + goto __pyx_L7; + } + __pyx_L7:; + __pyx_L5_continue:; + } + + /* "sklearn/utils/mst/_traversal.pyx":393 + * i_nl_end += 1 + * + * for i from indptr2[pnode] <= i < indptr2[pnode + 1]: # <<<<<<<<<<<<<< + * cnode = indices2[i] + * if (cnode == head_node): + */ + __pyx_t_12 = __pyx_v_pnode; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_12 >= (size_t)__pyx_pybuffernd_indptr2.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_13 = (__pyx_v_pnode + 1); + __pyx_t_2 = -1; + if (__pyx_t_13 < 0) { + __pyx_t_13 += __pyx_pybuffernd_indptr2.diminfo[0].shape; + if (unlikely(__pyx_t_13 < 0)) __pyx_t_2 = 0; + } else if (unlikely(__pyx_t_13 >= __pyx_pybuffernd_indptr2.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_7 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_indptr2.diminfo[0].strides)); + for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_indptr2.diminfo[0].strides)); __pyx_v_i < __pyx_t_7; __pyx_v_i++) { + + /* "sklearn/utils/mst/_traversal.pyx":394 + * + * for i from indptr2[pnode] <= i < indptr2[pnode + 1]: + * cnode = indices2[i] # <<<<<<<<<<<<<< + * if (cnode == head_node): + * continue + */ + __pyx_t_14 = __pyx_v_i; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_14 >= (size_t)__pyx_pybuffernd_indices2.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_cnode = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indices2.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_indices2.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":395 + * for i from indptr2[pnode] <= i < indptr2[pnode + 1]: + * cnode = indices2[i] + * if (cnode == head_node): # <<<<<<<<<<<<<< + * continue + * elif (predecessors[cnode] == NULL_IDX): + */ + __pyx_t_3 = (__pyx_v_cnode == __pyx_v_head_node); + if (__pyx_t_3) { + + /* "sklearn/utils/mst/_traversal.pyx":396 + * cnode = indices2[i] + * if (cnode == head_node): + * continue # <<<<<<<<<<<<<< + * elif (predecessors[cnode] == NULL_IDX): + * node_list[i_nl_end] = cnode + */ + goto __pyx_L8_continue; + goto __pyx_L10; + } + + /* "sklearn/utils/mst/_traversal.pyx":397 + * if (cnode == head_node): + * continue + * elif (predecessors[cnode] == NULL_IDX): # <<<<<<<<<<<<<< + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + */ + __pyx_t_15 = __pyx_v_cnode; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_15 >= (size_t)__pyx_pybuffernd_predecessors.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_predecessors.diminfo[0].strides)) == __pyx_v_7sklearn_5utils_3mst_10_traversal_NULL_IDX); + if (__pyx_t_3) { + + /* "sklearn/utils/mst/_traversal.pyx":398 + * continue + * elif (predecessors[cnode] == NULL_IDX): + * node_list[i_nl_end] = cnode # <<<<<<<<<<<<<< + * predecessors[cnode] = pnode + * i_nl_end += 1 + */ + __pyx_t_16 = __pyx_v_i_nl_end; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_16 >= (size_t)__pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_node_list.diminfo[0].strides) = __pyx_v_cnode; + + /* "sklearn/utils/mst/_traversal.pyx":399 + * elif (predecessors[cnode] == NULL_IDX): + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode # <<<<<<<<<<<<<< + * i_nl_end += 1 + * + */ + __pyx_t_17 = __pyx_v_cnode; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_17 >= (size_t)__pyx_pybuffernd_predecessors.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_predecessors.diminfo[0].strides) = __pyx_v_pnode; + + /* "sklearn/utils/mst/_traversal.pyx":400 + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + * i_nl_end += 1 # <<<<<<<<<<<<<< + * + * i_nl += 1 + */ + __pyx_v_i_nl_end = (__pyx_v_i_nl_end + 1); + goto __pyx_L10; + } + __pyx_L10:; + __pyx_L8_continue:; + } + + /* "sklearn/utils/mst/_traversal.pyx":402 + * i_nl_end += 1 + * + * i_nl += 1 # <<<<<<<<<<<<<< + * + * return i_nl + */ + __pyx_v_i_nl = (__pyx_v_i_nl + 1); + } + + /* "sklearn/utils/mst/_traversal.pyx":404 + * i_nl += 1 + * + * return i_nl # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_i_nl; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_WriteUnraisable("sklearn.utils.mst._traversal._breadth_first_undirected", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_7sklearn_5utils_3mst_10_traversal_9depth_first_order(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_7sklearn_5utils_3mst_10_traversal_8depth_first_order[] = "\n depth_first_order(csgraph, i_start, directed=True, return_predecessors=True)\n\n Return a depth-first ordering starting with specified node.\n\n Note that a depth-first order is not unique. Furthermore, for graphs\n with cycles, the tree generated by a depth-first search is not\n unique either.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n csgraph : array_like or sparse matrix\n The N x N compressed sparse graph. The input csgraph will be\n converted to csr format for the calculation.\n i_start : int\n The index of starting node.\n directed : bool, optional\n If True (default), then operate on a directed graph: only\n move from point i to point j along paths csgraph[i, j].\n If False, then find the shortest path on an undirected graph: the\n algorithm can progress from point i to j along csgraph[i, j] or\n csgraph[j, i].\n return_predecessors : bool, optional\n If True (default), then return the predecesor array (see below).\n\n Returns\n -------\n node_array : ndarray, one dimension\n The breadth-first list of nodes, starting with specified node. The\n length of node_array is the number of nodes reachable from the\n specified node.\n predecessors : ndarray, one dimension\n Returned only if return_predecessors is True.\n The length-N list of predecessors of each node in a breadth-first\n tree. If node i is in the tree, then its parent is given by\n predecessors[i]. If node i is not in the tree (and for the parent\n node) then predecessors[i] = -9999.\n "; +static PyMethodDef __pyx_mdef_7sklearn_5utils_3mst_10_traversal_9depth_first_order = {__Pyx_NAMESTR("depth_first_order"), (PyCFunction)__pyx_pw_7sklearn_5utils_3mst_10_traversal_9depth_first_order, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_5utils_3mst_10_traversal_8depth_first_order)}; +static PyObject *__pyx_pw_7sklearn_5utils_3mst_10_traversal_9depth_first_order(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_csgraph = 0; + PyObject *__pyx_v_i_start = 0; + PyObject *__pyx_v_directed = 0; + PyObject *__pyx_v_return_predecessors = 0; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__csgraph,&__pyx_n_s__i_start,&__pyx_n_s__directed,&__pyx_n_s__return_predecessors,0}; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("depth_first_order (wrapper)", 0); + __pyx_self = __pyx_self; + { + PyObject* values[4] = {0,0,0,0}; + values[2] = __pyx_k_9; + values[3] = __pyx_k_10; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__csgraph); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__i_start); + if (likely(values[1])) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("depth_first_order", 0, 2, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__directed); + if (value) { values[2] = value; kw_args--; } + } + case 3: + if (kw_args > 0) { + PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__return_predecessors); + if (value) { values[3] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "depth_first_order") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_csgraph = values[0]; + __pyx_v_i_start = values[1]; + __pyx_v_directed = values[2]; + __pyx_v_return_predecessors = values[3]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("depth_first_order", 0, 2, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_L3_error:; + __Pyx_AddTraceback("sklearn.utils.mst._traversal.depth_first_order", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_7sklearn_5utils_3mst_10_traversal_8depth_first_order(__pyx_self, __pyx_v_csgraph, __pyx_v_i_start, __pyx_v_directed, __pyx_v_return_predecessors); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/mst/_traversal.pyx":407 + * + * + * def depth_first_order(csgraph, i_start, # <<<<<<<<<<<<<< + * directed=True, return_predecessors=True): + * """ + */ + +static PyObject *__pyx_pf_7sklearn_5utils_3mst_10_traversal_8depth_first_order(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_csgraph, PyObject *__pyx_v_i_start, PyObject *__pyx_v_directed, PyObject *__pyx_v_return_predecessors) { + int __pyx_v_N; + PyObject *__pyx_v_node_list = NULL; + PyObject *__pyx_v_predecessors = NULL; + PyObject *__pyx_v_root_list = NULL; + PyObject *__pyx_v_flag = NULL; + unsigned int __pyx_v_length; + PyObject *__pyx_v_csgraph_T = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + unsigned int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("depth_first_order", 0); + __Pyx_INCREF(__pyx_v_csgraph); + + /* "sklearn/utils/mst/_traversal.pyx":450 + * """ + * global NULL_IDX + * csgraph = validate_graph(csgraph, directed, dense_output=False) # <<<<<<<<<<<<<< + * cdef int N = csgraph.shape[0] + * + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__validate_graph); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_csgraph); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_csgraph); + __Pyx_GIVEREF(__pyx_v_csgraph); + __Pyx_INCREF(__pyx_v_directed); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_directed); + __Pyx_GIVEREF(__pyx_v_directed); + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_4 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dense_output), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_v_csgraph); + __pyx_v_csgraph = __pyx_t_4; + __pyx_t_4 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":451 + * global NULL_IDX + * csgraph = validate_graph(csgraph, directed, dense_output=False) + * cdef int N = csgraph.shape[0] # <<<<<<<<<<<<<< + * + * node_list = np.empty(N, dtype=ITYPE) + */ + __pyx_t_4 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__shape); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_4, 0, sizeof(long), PyInt_FromLong); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = __Pyx_PyInt_AsInt(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_N = __pyx_t_5; + + /* "sklearn/utils/mst/_traversal.pyx":453 + * cdef int N = csgraph.shape[0] + * + * node_list = np.empty(N, dtype=ITYPE) # <<<<<<<<<<<<<< + * predecessors = np.empty(N, dtype=ITYPE) + * root_list = np.empty(N, dtype=ITYPE) + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyInt_FromLong(__pyx_v_N); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_node_list = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":454 + * + * node_list = np.empty(N, dtype=ITYPE) + * predecessors = np.empty(N, dtype=ITYPE) # <<<<<<<<<<<<<< + * root_list = np.empty(N, dtype=ITYPE) + * flag = np.zeros(N, dtype=ITYPE) + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyInt_FromLong(__pyx_v_N); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_1)); + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_v_predecessors = __pyx_t_4; + __pyx_t_4 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":455 + * node_list = np.empty(N, dtype=ITYPE) + * predecessors = np.empty(N, dtype=ITYPE) + * root_list = np.empty(N, dtype=ITYPE) # <<<<<<<<<<<<<< + * flag = np.zeros(N, dtype=ITYPE) + * node_list.fill(NULL_IDX) + */ + __pyx_t_4 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_4, __pyx_n_s__empty); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyInt_FromLong(__pyx_v_N); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_4)); + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __pyx_v_root_list = __pyx_t_3; + __pyx_t_3 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":456 + * predecessors = np.empty(N, dtype=ITYPE) + * root_list = np.empty(N, dtype=ITYPE) + * flag = np.zeros(N, dtype=ITYPE) # <<<<<<<<<<<<<< + * node_list.fill(NULL_IDX) + * predecessors.fill(NULL_IDX) + */ + __pyx_t_3 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyObject_GetAttr(__pyx_t_3, __pyx_n_s__zeros); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyInt_FromLong(__pyx_v_N); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_3)); + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __pyx_v_flag = __pyx_t_1; + __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":457 + * root_list = np.empty(N, dtype=ITYPE) + * flag = np.zeros(N, dtype=ITYPE) + * node_list.fill(NULL_IDX) # <<<<<<<<<<<<<< + * predecessors.fill(NULL_IDX) + * root_list.fill(NULL_IDX) + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_node_list, __pyx_n_s__fill); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_7sklearn_5utils_3mst_10_traversal_NULL_IDX); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":458 + * flag = np.zeros(N, dtype=ITYPE) + * node_list.fill(NULL_IDX) + * predecessors.fill(NULL_IDX) # <<<<<<<<<<<<<< + * root_list.fill(NULL_IDX) + * + */ + __pyx_t_3 = PyObject_GetAttr(__pyx_v_predecessors, __pyx_n_s__fill); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 458; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_7sklearn_5utils_3mst_10_traversal_NULL_IDX); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 458; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 458; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 458; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":459 + * node_list.fill(NULL_IDX) + * predecessors.fill(NULL_IDX) + * root_list.fill(NULL_IDX) # <<<<<<<<<<<<<< + * + * if directed: + */ + __pyx_t_2 = PyObject_GetAttr(__pyx_v_root_list, __pyx_n_s__fill); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyInt_to_py_npy_int32(__pyx_v_7sklearn_5utils_3mst_10_traversal_NULL_IDX); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":461 + * root_list.fill(NULL_IDX) + * + * if directed: # <<<<<<<<<<<<<< + * length = _depth_first_directed(i_start, + * csgraph.indices, csgraph.indptr, + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_directed); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "sklearn/utils/mst/_traversal.pyx":462 + * + * if directed: + * length = _depth_first_directed(i_start, # <<<<<<<<<<<<<< + * csgraph.indices, csgraph.indptr, + * node_list, predecessors, + */ + __pyx_t_7 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_i_start); if (unlikely((__pyx_t_7 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":463 + * if directed: + * length = _depth_first_directed(i_start, + * csgraph.indices, csgraph.indptr, # <<<<<<<<<<<<<< + * node_list, predecessors, + * root_list, flag) + */ + __pyx_t_1 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indices); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indptr); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":464 + * length = _depth_first_directed(i_start, + * csgraph.indices, csgraph.indptr, + * node_list, predecessors, # <<<<<<<<<<<<<< + * root_list, flag) + * else: + */ + if (!(likely(((__pyx_v_node_list) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_node_list, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_v_node_list; + __Pyx_INCREF(__pyx_t_2); + if (!(likely(((__pyx_v_predecessors) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_predecessors, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_v_predecessors; + __Pyx_INCREF(__pyx_t_4); + + /* "sklearn/utils/mst/_traversal.pyx":465 + * csgraph.indices, csgraph.indptr, + * node_list, predecessors, + * root_list, flag) # <<<<<<<<<<<<<< + * else: + * csgraph_T = csgraph.T.tocsr() + */ + if (!(likely(((__pyx_v_root_list) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_root_list, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 465; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __pyx_v_root_list; + __Pyx_INCREF(__pyx_t_8); + if (!(likely(((__pyx_v_flag) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_flag, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 465; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_v_flag; + __Pyx_INCREF(__pyx_t_9); + __pyx_v_length = __pyx_f_7sklearn_5utils_3mst_10_traversal__depth_first_directed(__pyx_t_7, ((PyArrayObject *)__pyx_t_1), ((PyArrayObject *)__pyx_t_3), ((PyArrayObject *)__pyx_t_2), ((PyArrayObject *)__pyx_t_4), ((PyArrayObject *)__pyx_t_8), ((PyArrayObject *)__pyx_t_9)); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L3; + } + /*else*/ { + + /* "sklearn/utils/mst/_traversal.pyx":467 + * root_list, flag) + * else: + * csgraph_T = csgraph.T.tocsr() # <<<<<<<<<<<<<< + * length = _depth_first_undirected(i_start, + * csgraph.indices, csgraph.indptr, + */ + __pyx_t_9 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__T); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_8 = PyObject_GetAttr(__pyx_t_9, __pyx_n_s__tocsr); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = PyObject_Call(__pyx_t_8, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 467; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_csgraph_T = __pyx_t_9; + __pyx_t_9 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":468 + * else: + * csgraph_T = csgraph.T.tocsr() + * length = _depth_first_undirected(i_start, # <<<<<<<<<<<<<< + * csgraph.indices, csgraph.indptr, + * csgraph_T.indices, csgraph_T.indptr, + */ + __pyx_t_7 = __Pyx_PyInt_AsUnsignedInt(__pyx_v_i_start); if (unlikely((__pyx_t_7 == (unsigned int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":469 + * csgraph_T = csgraph.T.tocsr() + * length = _depth_first_undirected(i_start, + * csgraph.indices, csgraph.indptr, # <<<<<<<<<<<<<< + * csgraph_T.indices, csgraph_T.indptr, + * node_list, predecessors, + */ + __pyx_t_9 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indices); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_9); + if (!(likely(((__pyx_t_9) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_9, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_GetAttr(__pyx_v_csgraph, __pyx_n_s__indptr); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + if (!(likely(((__pyx_t_8) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_8, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":470 + * length = _depth_first_undirected(i_start, + * csgraph.indices, csgraph.indptr, + * csgraph_T.indices, csgraph_T.indptr, # <<<<<<<<<<<<<< + * node_list, predecessors, + * root_list, flag) + */ + __pyx_t_4 = PyObject_GetAttr(__pyx_v_csgraph_T, __pyx_n_s__indices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyObject_GetAttr(__pyx_v_csgraph_T, __pyx_n_s__indptr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":471 + * csgraph.indices, csgraph.indptr, + * csgraph_T.indices, csgraph_T.indptr, + * node_list, predecessors, # <<<<<<<<<<<<<< + * root_list, flag) + * + */ + if (!(likely(((__pyx_v_node_list) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_node_list, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_v_node_list; + __Pyx_INCREF(__pyx_t_3); + if (!(likely(((__pyx_v_predecessors) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_predecessors, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_v_predecessors; + __Pyx_INCREF(__pyx_t_1); + + /* "sklearn/utils/mst/_traversal.pyx":472 + * csgraph_T.indices, csgraph_T.indptr, + * node_list, predecessors, + * root_list, flag) # <<<<<<<<<<<<<< + * + * if return_predecessors: + */ + if (!(likely(((__pyx_v_root_list) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_root_list, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 472; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __pyx_v_root_list; + __Pyx_INCREF(__pyx_t_10); + if (!(likely(((__pyx_v_flag) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_flag, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 472; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = __pyx_v_flag; + __Pyx_INCREF(__pyx_t_11); + __pyx_v_length = __pyx_f_7sklearn_5utils_3mst_10_traversal__depth_first_undirected(__pyx_t_7, ((PyArrayObject *)__pyx_t_9), ((PyArrayObject *)__pyx_t_8), ((PyArrayObject *)__pyx_t_4), ((PyArrayObject *)__pyx_t_2), ((PyArrayObject *)__pyx_t_3), ((PyArrayObject *)__pyx_t_1), ((PyArrayObject *)__pyx_t_10), ((PyArrayObject *)__pyx_t_11)); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + } + __pyx_L3:; + + /* "sklearn/utils/mst/_traversal.pyx":474 + * root_list, flag) + * + * if return_predecessors: # <<<<<<<<<<<<<< + * return node_list[:length], predecessors + * else: + */ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_return_predecessors); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_6) { + + /* "sklearn/utils/mst/_traversal.pyx":475 + * + * if return_predecessors: + * return node_list[:length], predecessors # <<<<<<<<<<<<<< + * else: + * return node_list[:length] + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_11 = __Pyx_PySequence_GetSlice(__pyx_v_node_list, 0, __pyx_v_length); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 475; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_11); + __Pyx_GIVEREF(__pyx_t_11); + __Pyx_INCREF(__pyx_v_predecessors); + PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_v_predecessors); + __Pyx_GIVEREF(__pyx_v_predecessors); + __pyx_t_11 = 0; + __pyx_r = ((PyObject *)__pyx_t_10); + __pyx_t_10 = 0; + goto __pyx_L0; + goto __pyx_L4; + } + /*else*/ { + + /* "sklearn/utils/mst/_traversal.pyx":477 + * return node_list[:length], predecessors + * else: + * return node_list[:length] # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_10 = __Pyx_PySequence_GetSlice(__pyx_v_node_list, 0, __pyx_v_length); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 477; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_10); + __pyx_r = __pyx_t_10; + __pyx_t_10 = 0; + goto __pyx_L0; + } + __pyx_L4:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_AddTraceback("sklearn.utils.mst._traversal.depth_first_order", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_node_list); + __Pyx_XDECREF(__pyx_v_predecessors); + __Pyx_XDECREF(__pyx_v_root_list); + __Pyx_XDECREF(__pyx_v_flag); + __Pyx_XDECREF(__pyx_v_csgraph_T); + __Pyx_XDECREF(__pyx_v_csgraph); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/mst/_traversal.pyx":480 + * + * + * cdef unsigned int _depth_first_directed( # <<<<<<<<<<<<<< + * unsigned int head_node, + * np.ndarray[ITYPE_t, ndim=1, mode='c'] indices, + */ + +static unsigned int __pyx_f_7sklearn_5utils_3mst_10_traversal__depth_first_directed(unsigned int __pyx_v_head_node, PyArrayObject *__pyx_v_indices, PyArrayObject *__pyx_v_indptr, PyArrayObject *__pyx_v_node_list, PyArrayObject *__pyx_v_predecessors, PyArrayObject *__pyx_v_root_list, PyArrayObject *__pyx_v_flag) { + unsigned int __pyx_v_i; + unsigned int __pyx_v_i_nl_end; + unsigned int __pyx_v_cnode; + unsigned int __pyx_v_pnode; + unsigned int __pyx_v_N; + int __pyx_v_no_children; + int __pyx_v_i_root; + __Pyx_LocalBuf_ND __pyx_pybuffernd_flag; + __Pyx_Buffer __pyx_pybuffer_flag; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices; + __Pyx_Buffer __pyx_pybuffer_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr; + __Pyx_Buffer __pyx_pybuffer_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_node_list; + __Pyx_Buffer __pyx_pybuffer_node_list; + __Pyx_LocalBuf_ND __pyx_pybuffernd_predecessors; + __Pyx_Buffer __pyx_pybuffer_predecessors; + __Pyx_LocalBuf_ND __pyx_pybuffernd_root_list; + __Pyx_Buffer __pyx_pybuffer_root_list; + unsigned int __pyx_r; + __Pyx_RefNannyDeclarations + long __pyx_t_1; + int __pyx_t_2; + long __pyx_t_3; + unsigned int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + unsigned int __pyx_t_7; + long __pyx_t_8; + __pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t __pyx_t_9; + unsigned int __pyx_t_10; + unsigned int __pyx_t_11; + __pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t __pyx_t_12; + int __pyx_t_13; + unsigned int __pyx_t_14; + unsigned int __pyx_t_15; + unsigned int __pyx_t_16; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_depth_first_directed", 0); + __pyx_pybuffer_indices.pybuffer.buf = NULL; + __pyx_pybuffer_indices.refcount = 0; + __pyx_pybuffernd_indices.data = NULL; + __pyx_pybuffernd_indices.rcbuffer = &__pyx_pybuffer_indices; + __pyx_pybuffer_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_indptr.refcount = 0; + __pyx_pybuffernd_indptr.data = NULL; + __pyx_pybuffernd_indptr.rcbuffer = &__pyx_pybuffer_indptr; + __pyx_pybuffer_node_list.pybuffer.buf = NULL; + __pyx_pybuffer_node_list.refcount = 0; + __pyx_pybuffernd_node_list.data = NULL; + __pyx_pybuffernd_node_list.rcbuffer = &__pyx_pybuffer_node_list; + __pyx_pybuffer_predecessors.pybuffer.buf = NULL; + __pyx_pybuffer_predecessors.refcount = 0; + __pyx_pybuffernd_predecessors.data = NULL; + __pyx_pybuffernd_predecessors.rcbuffer = &__pyx_pybuffer_predecessors; + __pyx_pybuffer_root_list.pybuffer.buf = NULL; + __pyx_pybuffer_root_list.refcount = 0; + __pyx_pybuffernd_root_list.data = NULL; + __pyx_pybuffernd_root_list.rcbuffer = &__pyx_pybuffer_root_list; + __pyx_pybuffer_flag.pybuffer.buf = NULL; + __pyx_pybuffer_flag.refcount = 0; + __pyx_pybuffernd_flag.data = NULL; + __pyx_pybuffernd_flag.rcbuffer = &__pyx_pybuffer_flag; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indices.diminfo[0].strides = __pyx_pybuffernd_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices.diminfo[0].shape = __pyx_pybuffernd_indices.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indptr.diminfo[0].strides = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr.diminfo[0].shape = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer, (PyObject*)__pyx_v_node_list, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_node_list.diminfo[0].strides = __pyx_pybuffernd_node_list.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_node_list.diminfo[0].shape = __pyx_pybuffernd_node_list.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer, (PyObject*)__pyx_v_predecessors, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_predecessors.diminfo[0].strides = __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_predecessors.diminfo[0].shape = __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_root_list.rcbuffer->pybuffer, (PyObject*)__pyx_v_root_list, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_root_list.diminfo[0].strides = __pyx_pybuffernd_root_list.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_root_list.diminfo[0].shape = __pyx_pybuffernd_root_list.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_flag.rcbuffer->pybuffer, (PyObject*)__pyx_v_flag, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_flag.diminfo[0].strides = __pyx_pybuffernd_flag.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_flag.diminfo[0].shape = __pyx_pybuffernd_flag.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/utils/mst/_traversal.pyx":489 + * np.ndarray[ITYPE_t, ndim=1, mode='c'] flag): + * cdef unsigned int i, j, i_nl_end, cnode, pnode + * cdef unsigned int N = node_list.shape[0] # <<<<<<<<<<<<<< + * cdef int no_children, i_root + * + */ + __pyx_v_N = (__pyx_v_node_list->dimensions[0]); + + /* "sklearn/utils/mst/_traversal.pyx":492 + * cdef int no_children, i_root + * + * node_list[0] = head_node # <<<<<<<<<<<<<< + * root_list[0] = head_node + * i_root = 0 + */ + __pyx_t_1 = 0; + __pyx_t_2 = -1; + if (__pyx_t_1 < 0) { + __pyx_t_1 += __pyx_pybuffernd_node_list.diminfo[0].shape; + if (unlikely(__pyx_t_1 < 0)) __pyx_t_2 = 0; + } else if (unlikely(__pyx_t_1 >= __pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_1, __pyx_pybuffernd_node_list.diminfo[0].strides) = __pyx_v_head_node; + + /* "sklearn/utils/mst/_traversal.pyx":493 + * + * node_list[0] = head_node + * root_list[0] = head_node # <<<<<<<<<<<<<< + * i_root = 0 + * i_nl_end = 1 + */ + __pyx_t_3 = 0; + __pyx_t_2 = -1; + if (__pyx_t_3 < 0) { + __pyx_t_3 += __pyx_pybuffernd_root_list.diminfo[0].shape; + if (unlikely(__pyx_t_3 < 0)) __pyx_t_2 = 0; + } else if (unlikely(__pyx_t_3 >= __pyx_pybuffernd_root_list.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_root_list.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_root_list.diminfo[0].strides) = __pyx_v_head_node; + + /* "sklearn/utils/mst/_traversal.pyx":494 + * node_list[0] = head_node + * root_list[0] = head_node + * i_root = 0 # <<<<<<<<<<<<<< + * i_nl_end = 1 + * flag[head_node] = 1 + */ + __pyx_v_i_root = 0; + + /* "sklearn/utils/mst/_traversal.pyx":495 + * root_list[0] = head_node + * i_root = 0 + * i_nl_end = 1 # <<<<<<<<<<<<<< + * flag[head_node] = 1 + * + */ + __pyx_v_i_nl_end = 1; + + /* "sklearn/utils/mst/_traversal.pyx":496 + * i_root = 0 + * i_nl_end = 1 + * flag[head_node] = 1 # <<<<<<<<<<<<<< + * + * while i_root >= 0: + */ + __pyx_t_4 = __pyx_v_head_node; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_4 >= (size_t)__pyx_pybuffernd_flag.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_flag.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_flag.diminfo[0].strides) = 1; + + /* "sklearn/utils/mst/_traversal.pyx":498 + * flag[head_node] = 1 + * + * while i_root >= 0: # <<<<<<<<<<<<<< + * pnode = root_list[i_root] + * no_children = True + */ + while (1) { + __pyx_t_5 = (__pyx_v_i_root >= 0); + if (!__pyx_t_5) break; + + /* "sklearn/utils/mst/_traversal.pyx":499 + * + * while i_root >= 0: + * pnode = root_list[i_root] # <<<<<<<<<<<<<< + * no_children = True + * for i from indptr[pnode] <= i < indptr[pnode + 1]: + */ + __pyx_t_2 = __pyx_v_i_root; + __pyx_t_6 = -1; + if (__pyx_t_2 < 0) { + __pyx_t_2 += __pyx_pybuffernd_root_list.diminfo[0].shape; + if (unlikely(__pyx_t_2 < 0)) __pyx_t_6 = 0; + } else if (unlikely(__pyx_t_2 >= __pyx_pybuffernd_root_list.diminfo[0].shape)) __pyx_t_6 = 0; + if (unlikely(__pyx_t_6 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_6); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_pnode = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_root_list.rcbuffer->pybuffer.buf, __pyx_t_2, __pyx_pybuffernd_root_list.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":500 + * while i_root >= 0: + * pnode = root_list[i_root] + * no_children = True # <<<<<<<<<<<<<< + * for i from indptr[pnode] <= i < indptr[pnode + 1]: + * cnode = indices[i] + */ + __pyx_v_no_children = 1; + + /* "sklearn/utils/mst/_traversal.pyx":501 + * pnode = root_list[i_root] + * no_children = True + * for i from indptr[pnode] <= i < indptr[pnode + 1]: # <<<<<<<<<<<<<< + * cnode = indices[i] + * if flag[cnode]: + */ + __pyx_t_7 = __pyx_v_pnode; + __pyx_t_6 = -1; + if (unlikely(__pyx_t_7 >= (size_t)__pyx_pybuffernd_indptr.diminfo[0].shape)) __pyx_t_6 = 0; + if (unlikely(__pyx_t_6 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_6); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 501; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_8 = (__pyx_v_pnode + 1); + __pyx_t_6 = -1; + if (__pyx_t_8 < 0) { + __pyx_t_8 += __pyx_pybuffernd_indptr.diminfo[0].shape; + if (unlikely(__pyx_t_8 < 0)) __pyx_t_6 = 0; + } else if (unlikely(__pyx_t_8 >= __pyx_pybuffernd_indptr.diminfo[0].shape)) __pyx_t_6 = 0; + if (unlikely(__pyx_t_6 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_6); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 501; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_9 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_indptr.diminfo[0].strides)); + for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_indptr.diminfo[0].strides)); __pyx_v_i < __pyx_t_9; __pyx_v_i++) { + + /* "sklearn/utils/mst/_traversal.pyx":502 + * no_children = True + * for i from indptr[pnode] <= i < indptr[pnode + 1]: + * cnode = indices[i] # <<<<<<<<<<<<<< + * if flag[cnode]: + * continue + */ + __pyx_t_10 = __pyx_v_i; + __pyx_t_6 = -1; + if (unlikely(__pyx_t_10 >= (size_t)__pyx_pybuffernd_indices.diminfo[0].shape)) __pyx_t_6 = 0; + if (unlikely(__pyx_t_6 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_6); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_cnode = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indices.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_indices.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":503 + * for i from indptr[pnode] <= i < indptr[pnode + 1]: + * cnode = indices[i] + * if flag[cnode]: # <<<<<<<<<<<<<< + * continue + * else: + */ + __pyx_t_11 = __pyx_v_cnode; + __pyx_t_6 = -1; + if (unlikely(__pyx_t_11 >= (size_t)__pyx_pybuffernd_flag.diminfo[0].shape)) __pyx_t_6 = 0; + if (unlikely(__pyx_t_6 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_6); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_12 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_flag.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_flag.diminfo[0].strides)); + if (__pyx_t_12) { + + /* "sklearn/utils/mst/_traversal.pyx":504 + * cnode = indices[i] + * if flag[cnode]: + * continue # <<<<<<<<<<<<<< + * else: + * i_root += 1 + */ + goto __pyx_L5_continue; + goto __pyx_L7; + } + /*else*/ { + + /* "sklearn/utils/mst/_traversal.pyx":506 + * continue + * else: + * i_root += 1 # <<<<<<<<<<<<<< + * root_list[i_root] = cnode + * node_list[i_nl_end] = cnode + */ + __pyx_v_i_root = (__pyx_v_i_root + 1); + + /* "sklearn/utils/mst/_traversal.pyx":507 + * else: + * i_root += 1 + * root_list[i_root] = cnode # <<<<<<<<<<<<<< + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + */ + __pyx_t_6 = __pyx_v_i_root; + __pyx_t_13 = -1; + if (__pyx_t_6 < 0) { + __pyx_t_6 += __pyx_pybuffernd_root_list.diminfo[0].shape; + if (unlikely(__pyx_t_6 < 0)) __pyx_t_13 = 0; + } else if (unlikely(__pyx_t_6 >= __pyx_pybuffernd_root_list.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_root_list.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_root_list.diminfo[0].strides) = __pyx_v_cnode; + + /* "sklearn/utils/mst/_traversal.pyx":508 + * i_root += 1 + * root_list[i_root] = cnode + * node_list[i_nl_end] = cnode # <<<<<<<<<<<<<< + * predecessors[cnode] = pnode + * flag[cnode] = 1 + */ + __pyx_t_14 = __pyx_v_i_nl_end; + __pyx_t_13 = -1; + if (unlikely(__pyx_t_14 >= (size_t)__pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_node_list.diminfo[0].strides) = __pyx_v_cnode; + + /* "sklearn/utils/mst/_traversal.pyx":509 + * root_list[i_root] = cnode + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode # <<<<<<<<<<<<<< + * flag[cnode] = 1 + * i_nl_end += 1 + */ + __pyx_t_15 = __pyx_v_cnode; + __pyx_t_13 = -1; + if (unlikely(__pyx_t_15 >= (size_t)__pyx_pybuffernd_predecessors.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_predecessors.diminfo[0].strides) = __pyx_v_pnode; + + /* "sklearn/utils/mst/_traversal.pyx":510 + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + * flag[cnode] = 1 # <<<<<<<<<<<<<< + * i_nl_end += 1 + * no_children = False + */ + __pyx_t_16 = __pyx_v_cnode; + __pyx_t_13 = -1; + if (unlikely(__pyx_t_16 >= (size_t)__pyx_pybuffernd_flag.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_flag.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_flag.diminfo[0].strides) = 1; + + /* "sklearn/utils/mst/_traversal.pyx":511 + * predecessors[cnode] = pnode + * flag[cnode] = 1 + * i_nl_end += 1 # <<<<<<<<<<<<<< + * no_children = False + * break + */ + __pyx_v_i_nl_end = (__pyx_v_i_nl_end + 1); + + /* "sklearn/utils/mst/_traversal.pyx":512 + * flag[cnode] = 1 + * i_nl_end += 1 + * no_children = False # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_no_children = 0; + + /* "sklearn/utils/mst/_traversal.pyx":513 + * i_nl_end += 1 + * no_children = False + * break # <<<<<<<<<<<<<< + * + * if i_nl_end == N: + */ + goto __pyx_L6_break; + } + __pyx_L7:; + __pyx_L5_continue:; + } + __pyx_L6_break:; + + /* "sklearn/utils/mst/_traversal.pyx":515 + * break + * + * if i_nl_end == N: # <<<<<<<<<<<<<< + * break + * + */ + __pyx_t_5 = (__pyx_v_i_nl_end == __pyx_v_N); + if (__pyx_t_5) { + + /* "sklearn/utils/mst/_traversal.pyx":516 + * + * if i_nl_end == N: + * break # <<<<<<<<<<<<<< + * + * if no_children: + */ + goto __pyx_L4_break; + goto __pyx_L8; + } + __pyx_L8:; + + /* "sklearn/utils/mst/_traversal.pyx":518 + * break + * + * if no_children: # <<<<<<<<<<<<<< + * i_root -= 1 + * + */ + if (__pyx_v_no_children) { + + /* "sklearn/utils/mst/_traversal.pyx":519 + * + * if no_children: + * i_root -= 1 # <<<<<<<<<<<<<< + * + * return i_nl_end + */ + __pyx_v_i_root = (__pyx_v_i_root - 1); + goto __pyx_L9; + } + __pyx_L9:; + } + __pyx_L4_break:; + + /* "sklearn/utils/mst/_traversal.pyx":521 + * i_root -= 1 + * + * return i_nl_end # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_i_nl_end; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_flag.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_root_list.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_WriteUnraisable("sklearn.utils.mst._traversal._depth_first_directed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_flag.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_root_list.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/mst/_traversal.pyx":524 + * + * + * cdef unsigned int _depth_first_undirected( # <<<<<<<<<<<<<< + * unsigned int head_node, + * np.ndarray[ITYPE_t, ndim=1, mode='c'] indices1, + */ + +static unsigned int __pyx_f_7sklearn_5utils_3mst_10_traversal__depth_first_undirected(unsigned int __pyx_v_head_node, PyArrayObject *__pyx_v_indices1, PyArrayObject *__pyx_v_indptr1, PyArrayObject *__pyx_v_indices2, PyArrayObject *__pyx_v_indptr2, PyArrayObject *__pyx_v_node_list, PyArrayObject *__pyx_v_predecessors, PyArrayObject *__pyx_v_root_list, PyArrayObject *__pyx_v_flag) { + unsigned int __pyx_v_i; + unsigned int __pyx_v_i_nl_end; + unsigned int __pyx_v_cnode; + unsigned int __pyx_v_pnode; + unsigned int __pyx_v_N; + int __pyx_v_no_children; + int __pyx_v_i_root; + __Pyx_LocalBuf_ND __pyx_pybuffernd_flag; + __Pyx_Buffer __pyx_pybuffer_flag; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices1; + __Pyx_Buffer __pyx_pybuffer_indices1; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices2; + __Pyx_Buffer __pyx_pybuffer_indices2; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr1; + __Pyx_Buffer __pyx_pybuffer_indptr1; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr2; + __Pyx_Buffer __pyx_pybuffer_indptr2; + __Pyx_LocalBuf_ND __pyx_pybuffernd_node_list; + __Pyx_Buffer __pyx_pybuffer_node_list; + __Pyx_LocalBuf_ND __pyx_pybuffernd_predecessors; + __Pyx_Buffer __pyx_pybuffer_predecessors; + __Pyx_LocalBuf_ND __pyx_pybuffernd_root_list; + __Pyx_Buffer __pyx_pybuffer_root_list; + unsigned int __pyx_r; + __Pyx_RefNannyDeclarations + long __pyx_t_1; + int __pyx_t_2; + long __pyx_t_3; + unsigned int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + unsigned int __pyx_t_7; + long __pyx_t_8; + __pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t __pyx_t_9; + unsigned int __pyx_t_10; + unsigned int __pyx_t_11; + __pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t __pyx_t_12; + int __pyx_t_13; + unsigned int __pyx_t_14; + unsigned int __pyx_t_15; + unsigned int __pyx_t_16; + unsigned int __pyx_t_17; + long __pyx_t_18; + unsigned int __pyx_t_19; + unsigned int __pyx_t_20; + int __pyx_t_21; + unsigned int __pyx_t_22; + unsigned int __pyx_t_23; + unsigned int __pyx_t_24; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_depth_first_undirected", 0); + __pyx_pybuffer_indices1.pybuffer.buf = NULL; + __pyx_pybuffer_indices1.refcount = 0; + __pyx_pybuffernd_indices1.data = NULL; + __pyx_pybuffernd_indices1.rcbuffer = &__pyx_pybuffer_indices1; + __pyx_pybuffer_indptr1.pybuffer.buf = NULL; + __pyx_pybuffer_indptr1.refcount = 0; + __pyx_pybuffernd_indptr1.data = NULL; + __pyx_pybuffernd_indptr1.rcbuffer = &__pyx_pybuffer_indptr1; + __pyx_pybuffer_indices2.pybuffer.buf = NULL; + __pyx_pybuffer_indices2.refcount = 0; + __pyx_pybuffernd_indices2.data = NULL; + __pyx_pybuffernd_indices2.rcbuffer = &__pyx_pybuffer_indices2; + __pyx_pybuffer_indptr2.pybuffer.buf = NULL; + __pyx_pybuffer_indptr2.refcount = 0; + __pyx_pybuffernd_indptr2.data = NULL; + __pyx_pybuffernd_indptr2.rcbuffer = &__pyx_pybuffer_indptr2; + __pyx_pybuffer_node_list.pybuffer.buf = NULL; + __pyx_pybuffer_node_list.refcount = 0; + __pyx_pybuffernd_node_list.data = NULL; + __pyx_pybuffernd_node_list.rcbuffer = &__pyx_pybuffer_node_list; + __pyx_pybuffer_predecessors.pybuffer.buf = NULL; + __pyx_pybuffer_predecessors.refcount = 0; + __pyx_pybuffernd_predecessors.data = NULL; + __pyx_pybuffernd_predecessors.rcbuffer = &__pyx_pybuffer_predecessors; + __pyx_pybuffer_root_list.pybuffer.buf = NULL; + __pyx_pybuffer_root_list.refcount = 0; + __pyx_pybuffernd_root_list.data = NULL; + __pyx_pybuffernd_root_list.rcbuffer = &__pyx_pybuffer_root_list; + __pyx_pybuffer_flag.pybuffer.buf = NULL; + __pyx_pybuffer_flag.refcount = 0; + __pyx_pybuffernd_flag.data = NULL; + __pyx_pybuffernd_flag.rcbuffer = &__pyx_pybuffer_flag; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices1.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indices1.diminfo[0].strides = __pyx_pybuffernd_indices1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices1.diminfo[0].shape = __pyx_pybuffernd_indices1.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indptr1.diminfo[0].strides = __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr1.diminfo[0].shape = __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices2.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indices2.diminfo[0].strides = __pyx_pybuffernd_indices2.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices2.diminfo[0].shape = __pyx_pybuffernd_indices2.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indptr2.diminfo[0].strides = __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr2.diminfo[0].shape = __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer, (PyObject*)__pyx_v_node_list, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_node_list.diminfo[0].strides = __pyx_pybuffernd_node_list.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_node_list.diminfo[0].shape = __pyx_pybuffernd_node_list.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer, (PyObject*)__pyx_v_predecessors, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_predecessors.diminfo[0].strides = __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_predecessors.diminfo[0].shape = __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_root_list.rcbuffer->pybuffer, (PyObject*)__pyx_v_root_list, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_root_list.diminfo[0].strides = __pyx_pybuffernd_root_list.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_root_list.diminfo[0].shape = __pyx_pybuffernd_root_list.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_flag.rcbuffer->pybuffer, (PyObject*)__pyx_v_flag, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_flag.diminfo[0].strides = __pyx_pybuffernd_flag.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_flag.diminfo[0].shape = __pyx_pybuffernd_flag.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/utils/mst/_traversal.pyx":535 + * np.ndarray[ITYPE_t, ndim=1, mode='c'] flag): + * cdef unsigned int i, j, i_nl_end, cnode, pnode + * cdef unsigned int N = node_list.shape[0] # <<<<<<<<<<<<<< + * cdef int no_children, i_root + * + */ + __pyx_v_N = (__pyx_v_node_list->dimensions[0]); + + /* "sklearn/utils/mst/_traversal.pyx":538 + * cdef int no_children, i_root + * + * node_list[0] = head_node # <<<<<<<<<<<<<< + * root_list[0] = head_node + * i_root = 0 + */ + __pyx_t_1 = 0; + __pyx_t_2 = -1; + if (__pyx_t_1 < 0) { + __pyx_t_1 += __pyx_pybuffernd_node_list.diminfo[0].shape; + if (unlikely(__pyx_t_1 < 0)) __pyx_t_2 = 0; + } else if (unlikely(__pyx_t_1 >= __pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_1, __pyx_pybuffernd_node_list.diminfo[0].strides) = __pyx_v_head_node; + + /* "sklearn/utils/mst/_traversal.pyx":539 + * + * node_list[0] = head_node + * root_list[0] = head_node # <<<<<<<<<<<<<< + * i_root = 0 + * i_nl_end = 1 + */ + __pyx_t_3 = 0; + __pyx_t_2 = -1; + if (__pyx_t_3 < 0) { + __pyx_t_3 += __pyx_pybuffernd_root_list.diminfo[0].shape; + if (unlikely(__pyx_t_3 < 0)) __pyx_t_2 = 0; + } else if (unlikely(__pyx_t_3 >= __pyx_pybuffernd_root_list.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_root_list.rcbuffer->pybuffer.buf, __pyx_t_3, __pyx_pybuffernd_root_list.diminfo[0].strides) = __pyx_v_head_node; + + /* "sklearn/utils/mst/_traversal.pyx":540 + * node_list[0] = head_node + * root_list[0] = head_node + * i_root = 0 # <<<<<<<<<<<<<< + * i_nl_end = 1 + * flag[head_node] = 1 + */ + __pyx_v_i_root = 0; + + /* "sklearn/utils/mst/_traversal.pyx":541 + * root_list[0] = head_node + * i_root = 0 + * i_nl_end = 1 # <<<<<<<<<<<<<< + * flag[head_node] = 1 + * + */ + __pyx_v_i_nl_end = 1; + + /* "sklearn/utils/mst/_traversal.pyx":542 + * i_root = 0 + * i_nl_end = 1 + * flag[head_node] = 1 # <<<<<<<<<<<<<< + * + * while i_root >= 0: + */ + __pyx_t_4 = __pyx_v_head_node; + __pyx_t_2 = -1; + if (unlikely(__pyx_t_4 >= (size_t)__pyx_pybuffernd_flag.diminfo[0].shape)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_2 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_2); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_flag.rcbuffer->pybuffer.buf, __pyx_t_4, __pyx_pybuffernd_flag.diminfo[0].strides) = 1; + + /* "sklearn/utils/mst/_traversal.pyx":544 + * flag[head_node] = 1 + * + * while i_root >= 0: # <<<<<<<<<<<<<< + * pnode = root_list[i_root] + * no_children = True + */ + while (1) { + __pyx_t_5 = (__pyx_v_i_root >= 0); + if (!__pyx_t_5) break; + + /* "sklearn/utils/mst/_traversal.pyx":545 + * + * while i_root >= 0: + * pnode = root_list[i_root] # <<<<<<<<<<<<<< + * no_children = True + * + */ + __pyx_t_2 = __pyx_v_i_root; + __pyx_t_6 = -1; + if (__pyx_t_2 < 0) { + __pyx_t_2 += __pyx_pybuffernd_root_list.diminfo[0].shape; + if (unlikely(__pyx_t_2 < 0)) __pyx_t_6 = 0; + } else if (unlikely(__pyx_t_2 >= __pyx_pybuffernd_root_list.diminfo[0].shape)) __pyx_t_6 = 0; + if (unlikely(__pyx_t_6 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_6); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_pnode = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_root_list.rcbuffer->pybuffer.buf, __pyx_t_2, __pyx_pybuffernd_root_list.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":546 + * while i_root >= 0: + * pnode = root_list[i_root] + * no_children = True # <<<<<<<<<<<<<< + * + * for i from indptr1[pnode] <= i < indptr1[pnode + 1]: + */ + __pyx_v_no_children = 1; + + /* "sklearn/utils/mst/_traversal.pyx":548 + * no_children = True + * + * for i from indptr1[pnode] <= i < indptr1[pnode + 1]: # <<<<<<<<<<<<<< + * cnode = indices1[i] + * if flag[cnode]: + */ + __pyx_t_7 = __pyx_v_pnode; + __pyx_t_6 = -1; + if (unlikely(__pyx_t_7 >= (size_t)__pyx_pybuffernd_indptr1.diminfo[0].shape)) __pyx_t_6 = 0; + if (unlikely(__pyx_t_6 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_6); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_8 = (__pyx_v_pnode + 1); + __pyx_t_6 = -1; + if (__pyx_t_8 < 0) { + __pyx_t_8 += __pyx_pybuffernd_indptr1.diminfo[0].shape; + if (unlikely(__pyx_t_8 < 0)) __pyx_t_6 = 0; + } else if (unlikely(__pyx_t_8 >= __pyx_pybuffernd_indptr1.diminfo[0].shape)) __pyx_t_6 = 0; + if (unlikely(__pyx_t_6 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_6); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_9 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_indptr1.diminfo[0].strides)); + for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_indptr1.diminfo[0].strides)); __pyx_v_i < __pyx_t_9; __pyx_v_i++) { + + /* "sklearn/utils/mst/_traversal.pyx":549 + * + * for i from indptr1[pnode] <= i < indptr1[pnode + 1]: + * cnode = indices1[i] # <<<<<<<<<<<<<< + * if flag[cnode]: + * continue + */ + __pyx_t_10 = __pyx_v_i; + __pyx_t_6 = -1; + if (unlikely(__pyx_t_10 >= (size_t)__pyx_pybuffernd_indices1.diminfo[0].shape)) __pyx_t_6 = 0; + if (unlikely(__pyx_t_6 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_6); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 549; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_cnode = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indices1.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_indices1.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":550 + * for i from indptr1[pnode] <= i < indptr1[pnode + 1]: + * cnode = indices1[i] + * if flag[cnode]: # <<<<<<<<<<<<<< + * continue + * else: + */ + __pyx_t_11 = __pyx_v_cnode; + __pyx_t_6 = -1; + if (unlikely(__pyx_t_11 >= (size_t)__pyx_pybuffernd_flag.diminfo[0].shape)) __pyx_t_6 = 0; + if (unlikely(__pyx_t_6 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_6); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_12 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_flag.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_flag.diminfo[0].strides)); + if (__pyx_t_12) { + + /* "sklearn/utils/mst/_traversal.pyx":551 + * cnode = indices1[i] + * if flag[cnode]: + * continue # <<<<<<<<<<<<<< + * else: + * i_root += 1 + */ + goto __pyx_L5_continue; + goto __pyx_L7; + } + /*else*/ { + + /* "sklearn/utils/mst/_traversal.pyx":553 + * continue + * else: + * i_root += 1 # <<<<<<<<<<<<<< + * root_list[i_root] = cnode + * node_list[i_nl_end] = cnode + */ + __pyx_v_i_root = (__pyx_v_i_root + 1); + + /* "sklearn/utils/mst/_traversal.pyx":554 + * else: + * i_root += 1 + * root_list[i_root] = cnode # <<<<<<<<<<<<<< + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + */ + __pyx_t_6 = __pyx_v_i_root; + __pyx_t_13 = -1; + if (__pyx_t_6 < 0) { + __pyx_t_6 += __pyx_pybuffernd_root_list.diminfo[0].shape; + if (unlikely(__pyx_t_6 < 0)) __pyx_t_13 = 0; + } else if (unlikely(__pyx_t_6 >= __pyx_pybuffernd_root_list.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_root_list.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_root_list.diminfo[0].strides) = __pyx_v_cnode; + + /* "sklearn/utils/mst/_traversal.pyx":555 + * i_root += 1 + * root_list[i_root] = cnode + * node_list[i_nl_end] = cnode # <<<<<<<<<<<<<< + * predecessors[cnode] = pnode + * flag[cnode] = 1 + */ + __pyx_t_14 = __pyx_v_i_nl_end; + __pyx_t_13 = -1; + if (unlikely(__pyx_t_14 >= (size_t)__pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 555; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_node_list.diminfo[0].strides) = __pyx_v_cnode; + + /* "sklearn/utils/mst/_traversal.pyx":556 + * root_list[i_root] = cnode + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode # <<<<<<<<<<<<<< + * flag[cnode] = 1 + * i_nl_end += 1 + */ + __pyx_t_15 = __pyx_v_cnode; + __pyx_t_13 = -1; + if (unlikely(__pyx_t_15 >= (size_t)__pyx_pybuffernd_predecessors.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 556; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_predecessors.diminfo[0].strides) = __pyx_v_pnode; + + /* "sklearn/utils/mst/_traversal.pyx":557 + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + * flag[cnode] = 1 # <<<<<<<<<<<<<< + * i_nl_end += 1 + * no_children = False + */ + __pyx_t_16 = __pyx_v_cnode; + __pyx_t_13 = -1; + if (unlikely(__pyx_t_16 >= (size_t)__pyx_pybuffernd_flag.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 557; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_flag.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_flag.diminfo[0].strides) = 1; + + /* "sklearn/utils/mst/_traversal.pyx":558 + * predecessors[cnode] = pnode + * flag[cnode] = 1 + * i_nl_end += 1 # <<<<<<<<<<<<<< + * no_children = False + * break + */ + __pyx_v_i_nl_end = (__pyx_v_i_nl_end + 1); + + /* "sklearn/utils/mst/_traversal.pyx":559 + * flag[cnode] = 1 + * i_nl_end += 1 + * no_children = False # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_no_children = 0; + + /* "sklearn/utils/mst/_traversal.pyx":560 + * i_nl_end += 1 + * no_children = False + * break # <<<<<<<<<<<<<< + * + * if no_children: + */ + goto __pyx_L6_break; + } + __pyx_L7:; + __pyx_L5_continue:; + } + __pyx_L6_break:; + + /* "sklearn/utils/mst/_traversal.pyx":562 + * break + * + * if no_children: # <<<<<<<<<<<<<< + * for i from indptr2[pnode] <= i < indptr2[pnode + 1]: + * cnode = indices2[i] + */ + if (__pyx_v_no_children) { + + /* "sklearn/utils/mst/_traversal.pyx":563 + * + * if no_children: + * for i from indptr2[pnode] <= i < indptr2[pnode + 1]: # <<<<<<<<<<<<<< + * cnode = indices2[i] + * if flag[cnode]: + */ + __pyx_t_17 = __pyx_v_pnode; + __pyx_t_13 = -1; + if (unlikely(__pyx_t_17 >= (size_t)__pyx_pybuffernd_indptr2.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_18 = (__pyx_v_pnode + 1); + __pyx_t_13 = -1; + if (__pyx_t_18 < 0) { + __pyx_t_18 += __pyx_pybuffernd_indptr2.diminfo[0].shape; + if (unlikely(__pyx_t_18 < 0)) __pyx_t_13 = 0; + } else if (unlikely(__pyx_t_18 >= __pyx_pybuffernd_indptr2.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_9 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_indptr2.diminfo[0].strides)); + for (__pyx_v_i = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_indptr2.diminfo[0].strides)); __pyx_v_i < __pyx_t_9; __pyx_v_i++) { + + /* "sklearn/utils/mst/_traversal.pyx":564 + * if no_children: + * for i from indptr2[pnode] <= i < indptr2[pnode + 1]: + * cnode = indices2[i] # <<<<<<<<<<<<<< + * if flag[cnode]: + * continue + */ + __pyx_t_19 = __pyx_v_i; + __pyx_t_13 = -1; + if (unlikely(__pyx_t_19 >= (size_t)__pyx_pybuffernd_indices2.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 564; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_cnode = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indices2.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_indices2.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":565 + * for i from indptr2[pnode] <= i < indptr2[pnode + 1]: + * cnode = indices2[i] + * if flag[cnode]: # <<<<<<<<<<<<<< + * continue + * else: + */ + __pyx_t_20 = __pyx_v_cnode; + __pyx_t_13 = -1; + if (unlikely(__pyx_t_20 >= (size_t)__pyx_pybuffernd_flag.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_12 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_flag.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_flag.diminfo[0].strides)); + if (__pyx_t_12) { + + /* "sklearn/utils/mst/_traversal.pyx":566 + * cnode = indices2[i] + * if flag[cnode]: + * continue # <<<<<<<<<<<<<< + * else: + * i_root += 1 + */ + goto __pyx_L9_continue; + goto __pyx_L11; + } + /*else*/ { + + /* "sklearn/utils/mst/_traversal.pyx":568 + * continue + * else: + * i_root += 1 # <<<<<<<<<<<<<< + * root_list[i_root] = cnode + * node_list[i_nl_end] = cnode + */ + __pyx_v_i_root = (__pyx_v_i_root + 1); + + /* "sklearn/utils/mst/_traversal.pyx":569 + * else: + * i_root += 1 + * root_list[i_root] = cnode # <<<<<<<<<<<<<< + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + */ + __pyx_t_13 = __pyx_v_i_root; + __pyx_t_21 = -1; + if (__pyx_t_13 < 0) { + __pyx_t_13 += __pyx_pybuffernd_root_list.diminfo[0].shape; + if (unlikely(__pyx_t_13 < 0)) __pyx_t_21 = 0; + } else if (unlikely(__pyx_t_13 >= __pyx_pybuffernd_root_list.diminfo[0].shape)) __pyx_t_21 = 0; + if (unlikely(__pyx_t_21 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_21); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_root_list.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_root_list.diminfo[0].strides) = __pyx_v_cnode; + + /* "sklearn/utils/mst/_traversal.pyx":570 + * i_root += 1 + * root_list[i_root] = cnode + * node_list[i_nl_end] = cnode # <<<<<<<<<<<<<< + * predecessors[cnode] = pnode + * flag[cnode] = 1 + */ + __pyx_t_22 = __pyx_v_i_nl_end; + __pyx_t_21 = -1; + if (unlikely(__pyx_t_22 >= (size_t)__pyx_pybuffernd_node_list.diminfo[0].shape)) __pyx_t_21 = 0; + if (unlikely(__pyx_t_21 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_21); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_node_list.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_node_list.diminfo[0].strides) = __pyx_v_cnode; + + /* "sklearn/utils/mst/_traversal.pyx":571 + * root_list[i_root] = cnode + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode # <<<<<<<<<<<<<< + * flag[cnode] = 1 + * i_nl_end += 1 + */ + __pyx_t_23 = __pyx_v_cnode; + __pyx_t_21 = -1; + if (unlikely(__pyx_t_23 >= (size_t)__pyx_pybuffernd_predecessors.diminfo[0].shape)) __pyx_t_21 = 0; + if (unlikely(__pyx_t_21 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_21); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_predecessors.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_predecessors.diminfo[0].strides) = __pyx_v_pnode; + + /* "sklearn/utils/mst/_traversal.pyx":572 + * node_list[i_nl_end] = cnode + * predecessors[cnode] = pnode + * flag[cnode] = 1 # <<<<<<<<<<<<<< + * i_nl_end += 1 + * no_children = False + */ + __pyx_t_24 = __pyx_v_cnode; + __pyx_t_21 = -1; + if (unlikely(__pyx_t_24 >= (size_t)__pyx_pybuffernd_flag.diminfo[0].shape)) __pyx_t_21 = 0; + if (unlikely(__pyx_t_21 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_21); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_flag.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_flag.diminfo[0].strides) = 1; + + /* "sklearn/utils/mst/_traversal.pyx":573 + * predecessors[cnode] = pnode + * flag[cnode] = 1 + * i_nl_end += 1 # <<<<<<<<<<<<<< + * no_children = False + * break + */ + __pyx_v_i_nl_end = (__pyx_v_i_nl_end + 1); + + /* "sklearn/utils/mst/_traversal.pyx":574 + * flag[cnode] = 1 + * i_nl_end += 1 + * no_children = False # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_no_children = 0; + + /* "sklearn/utils/mst/_traversal.pyx":575 + * i_nl_end += 1 + * no_children = False + * break # <<<<<<<<<<<<<< + * + * if i_nl_end == N: + */ + goto __pyx_L10_break; + } + __pyx_L11:; + __pyx_L9_continue:; + } + __pyx_L10_break:; + goto __pyx_L8; + } + __pyx_L8:; + + /* "sklearn/utils/mst/_traversal.pyx":577 + * break + * + * if i_nl_end == N: # <<<<<<<<<<<<<< + * break + * + */ + __pyx_t_5 = (__pyx_v_i_nl_end == __pyx_v_N); + if (__pyx_t_5) { + + /* "sklearn/utils/mst/_traversal.pyx":578 + * + * if i_nl_end == N: + * break # <<<<<<<<<<<<<< + * + * if no_children: + */ + goto __pyx_L4_break; + goto __pyx_L12; + } + __pyx_L12:; + + /* "sklearn/utils/mst/_traversal.pyx":580 + * break + * + * if no_children: # <<<<<<<<<<<<<< + * i_root -= 1 + * + */ + if (__pyx_v_no_children) { + + /* "sklearn/utils/mst/_traversal.pyx":581 + * + * if no_children: + * i_root -= 1 # <<<<<<<<<<<<<< + * + * return i_nl_end + */ + __pyx_v_i_root = (__pyx_v_i_root - 1); + goto __pyx_L13; + } + __pyx_L13:; + } + __pyx_L4_break:; + + /* "sklearn/utils/mst/_traversal.pyx":583 + * i_root -= 1 + * + * return i_nl_end # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_i_nl_end; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_flag.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_root_list.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_WriteUnraisable("sklearn.utils.mst._traversal._depth_first_undirected", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_flag.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_node_list.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_predecessors.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_root_list.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/mst/_traversal.pyx":586 + * + * + * cdef int _connected_components_directed( # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1, mode='c'] indices, + * np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr, + */ + +static int __pyx_f_7sklearn_5utils_3mst_10_traversal__connected_components_directed(PyArrayObject *__pyx_v_indices, PyArrayObject *__pyx_v_indptr, PyArrayObject *__pyx_v_labels) { + int __pyx_v_v; + int __pyx_v_w; + int __pyx_v_index; + int __pyx_v_low_v; + int __pyx_v_low_w; + int __pyx_v_label; + int __pyx_v_j; + int __pyx_v_SS_head; + int __pyx_v_root; + int __pyx_v_stack_head; + int __pyx_v_f; + int __pyx_v_b; + int __pyx_v_VOID; + int __pyx_v_END; + int __pyx_v_N; + PyArrayObject *__pyx_v_SS = 0; + PyArrayObject *__pyx_v_lowlinks = 0; + PyArrayObject *__pyx_v_stack_f = 0; + PyArrayObject *__pyx_v_stack_b = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_SS; + __Pyx_Buffer __pyx_pybuffer_SS; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices; + __Pyx_Buffer __pyx_pybuffer_indices; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr; + __Pyx_Buffer __pyx_pybuffer_indptr; + __Pyx_LocalBuf_ND __pyx_pybuffernd_labels; + __Pyx_Buffer __pyx_pybuffer_labels; + __Pyx_LocalBuf_ND __pyx_pybuffernd_lowlinks; + __Pyx_Buffer __pyx_pybuffer_lowlinks; + __Pyx_LocalBuf_ND __pyx_pybuffernd_stack_b; + __Pyx_Buffer __pyx_pybuffer_stack_b; + __Pyx_LocalBuf_ND __pyx_pybuffernd_stack_f; + __Pyx_Buffer __pyx_pybuffer_stack_f; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + long __pyx_t_17; + __pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t __pyx_t_18; + int __pyx_t_19; + int __pyx_t_20; + int __pyx_t_21; + int __pyx_t_22; + int __pyx_t_23; + int __pyx_t_24; + int __pyx_t_25; + int __pyx_t_26; + int __pyx_t_27; + int __pyx_t_28; + int __pyx_t_29; + int __pyx_t_30; + int __pyx_t_31; + int __pyx_t_32; + int __pyx_t_33; + int __pyx_t_34; + long __pyx_t_35; + int __pyx_t_36; + __pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t __pyx_t_37; + int __pyx_t_38; + int __pyx_t_39; + int __pyx_t_40; + int __pyx_t_41; + int __pyx_t_42; + int __pyx_t_43; + int __pyx_t_44; + int __pyx_t_45; + int __pyx_t_46; + int __pyx_t_47; + PyArrayObject *__pyx_t_48 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_connected_components_directed", 0); + __Pyx_INCREF((PyObject *)__pyx_v_labels); + __pyx_pybuffer_SS.pybuffer.buf = NULL; + __pyx_pybuffer_SS.refcount = 0; + __pyx_pybuffernd_SS.data = NULL; + __pyx_pybuffernd_SS.rcbuffer = &__pyx_pybuffer_SS; + __pyx_pybuffer_lowlinks.pybuffer.buf = NULL; + __pyx_pybuffer_lowlinks.refcount = 0; + __pyx_pybuffernd_lowlinks.data = NULL; + __pyx_pybuffernd_lowlinks.rcbuffer = &__pyx_pybuffer_lowlinks; + __pyx_pybuffer_stack_f.pybuffer.buf = NULL; + __pyx_pybuffer_stack_f.refcount = 0; + __pyx_pybuffernd_stack_f.data = NULL; + __pyx_pybuffernd_stack_f.rcbuffer = &__pyx_pybuffer_stack_f; + __pyx_pybuffer_stack_b.pybuffer.buf = NULL; + __pyx_pybuffer_stack_b.refcount = 0; + __pyx_pybuffernd_stack_b.data = NULL; + __pyx_pybuffernd_stack_b.rcbuffer = &__pyx_pybuffer_stack_b; + __pyx_pybuffer_indices.pybuffer.buf = NULL; + __pyx_pybuffer_indices.refcount = 0; + __pyx_pybuffernd_indices.data = NULL; + __pyx_pybuffernd_indices.rcbuffer = &__pyx_pybuffer_indices; + __pyx_pybuffer_indptr.pybuffer.buf = NULL; + __pyx_pybuffer_indptr.refcount = 0; + __pyx_pybuffernd_indptr.data = NULL; + __pyx_pybuffernd_indptr.rcbuffer = &__pyx_pybuffer_indptr; + __pyx_pybuffer_labels.pybuffer.buf = NULL; + __pyx_pybuffer_labels.refcount = 0; + __pyx_pybuffernd_labels.data = NULL; + __pyx_pybuffernd_labels.rcbuffer = &__pyx_pybuffer_labels; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indices.diminfo[0].strides = __pyx_pybuffernd_indices.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices.diminfo[0].shape = __pyx_pybuffernd_indices.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indptr.diminfo[0].strides = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr.diminfo[0].shape = __pyx_pybuffernd_indptr.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_labels.diminfo[0].strides = __pyx_pybuffernd_labels.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_labels.diminfo[0].shape = __pyx_pybuffernd_labels.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/utils/mst/_traversal.pyx":604 + * cdef int v, w, index, low_v, low_w, label, j + * cdef int SS_head, root, stack_head, f, b + * cdef int VOID = -1 # <<<<<<<<<<<<<< + * cdef int END = -2 + * cdef int N = labels.shape[0] + */ + __pyx_v_VOID = -1; + + /* "sklearn/utils/mst/_traversal.pyx":605 + * cdef int SS_head, root, stack_head, f, b + * cdef int VOID = -1 + * cdef int END = -2 # <<<<<<<<<<<<<< + * cdef int N = labels.shape[0] + * cdef np.ndarray[ITYPE_t, ndim=1, mode="c"] SS, lowlinks, stack_f, stack_b + */ + __pyx_v_END = -2; + + /* "sklearn/utils/mst/_traversal.pyx":606 + * cdef int VOID = -1 + * cdef int END = -2 + * cdef int N = labels.shape[0] # <<<<<<<<<<<<<< + * cdef np.ndarray[ITYPE_t, ndim=1, mode="c"] SS, lowlinks, stack_f, stack_b + * + */ + __pyx_v_N = (__pyx_v_labels->dimensions[0]); + + /* "sklearn/utils/mst/_traversal.pyx":609 + * cdef np.ndarray[ITYPE_t, ndim=1, mode="c"] SS, lowlinks, stack_f, stack_b + * + * lowlinks = labels # <<<<<<<<<<<<<< + * SS = np.ndarray((N,), dtype=ITYPE) + * stack_b = np.ndarray((N,), dtype=ITYPE) + */ + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_lowlinks.rcbuffer->pybuffer); + __pyx_t_1 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_lowlinks.rcbuffer->pybuffer, (PyObject*)((PyArrayObject *)__pyx_v_labels), &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_1 < 0)) { + PyErr_Fetch(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_lowlinks.rcbuffer->pybuffer, (PyObject*)__pyx_v_lowlinks, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_2); Py_XDECREF(__pyx_t_3); Py_XDECREF(__pyx_t_4); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_2, __pyx_t_3, __pyx_t_4); + } + } + __pyx_pybuffernd_lowlinks.diminfo[0].strides = __pyx_pybuffernd_lowlinks.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_lowlinks.diminfo[0].shape = __pyx_pybuffernd_lowlinks.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_INCREF(((PyObject *)__pyx_v_labels)); + __pyx_v_lowlinks = ((PyArrayObject *)__pyx_v_labels); + + /* "sklearn/utils/mst/_traversal.pyx":610 + * + * lowlinks = labels + * SS = np.ndarray((N,), dtype=ITYPE) # <<<<<<<<<<<<<< + * stack_b = np.ndarray((N,), dtype=ITYPE) + * stack_f = SS + */ + __pyx_t_5 = PyInt_FromLong(__pyx_v_N); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 610; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 610; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 610; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_t_6)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_6)); + __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 610; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __pyx_t_7 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 610; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 610; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_5numpy_ndarray)), ((PyObject *)__pyx_t_5), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 610; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_SS.rcbuffer->pybuffer); + __pyx_t_1 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SS.rcbuffer->pybuffer, (PyObject*)((PyArrayObject *)__pyx_t_7), &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_1 < 0)) { + PyErr_Fetch(&__pyx_t_4, &__pyx_t_3, &__pyx_t_2); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SS.rcbuffer->pybuffer, (PyObject*)__pyx_v_SS, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_3); Py_XDECREF(__pyx_t_2); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_4, __pyx_t_3, __pyx_t_2); + } + } + __pyx_pybuffernd_SS.diminfo[0].strides = __pyx_pybuffernd_SS.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_SS.diminfo[0].shape = __pyx_pybuffernd_SS.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 610; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_SS = ((PyArrayObject *)__pyx_t_7); + __pyx_t_7 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":611 + * lowlinks = labels + * SS = np.ndarray((N,), dtype=ITYPE) + * stack_b = np.ndarray((N,), dtype=ITYPE) # <<<<<<<<<<<<<< + * stack_f = SS + * + */ + __pyx_t_7 = PyInt_FromLong(__pyx_v_N); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, ((PyObject *)__pyx_t_6)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_6)); + __pyx_t_6 = 0; + __pyx_t_6 = PyDict_New(); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_6)); + __pyx_t_5 = __Pyx_GetName(__pyx_m, __pyx_n_s__ITYPE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_t_6, ((PyObject *)__pyx_n_s__dtype), __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_5numpy_ndarray)), ((PyObject *)__pyx_t_7), ((PyObject *)__pyx_t_6)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_stack_b.rcbuffer->pybuffer); + __pyx_t_1 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_stack_b.rcbuffer->pybuffer, (PyObject*)((PyArrayObject *)__pyx_t_5), &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_1 < 0)) { + PyErr_Fetch(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_stack_b.rcbuffer->pybuffer, (PyObject*)__pyx_v_stack_b, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_2); Py_XDECREF(__pyx_t_3); Py_XDECREF(__pyx_t_4); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_2, __pyx_t_3, __pyx_t_4); + } + } + __pyx_pybuffernd_stack_b.diminfo[0].strides = __pyx_pybuffernd_stack_b.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_stack_b.diminfo[0].shape = __pyx_pybuffernd_stack_b.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_stack_b = ((PyArrayObject *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":612 + * SS = np.ndarray((N,), dtype=ITYPE) + * stack_b = np.ndarray((N,), dtype=ITYPE) + * stack_f = SS # <<<<<<<<<<<<<< + * + * # The stack of nodes which have been backtracked and are in the current SCC + */ + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_stack_f.rcbuffer->pybuffer); + __pyx_t_1 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_stack_f.rcbuffer->pybuffer, (PyObject*)__pyx_v_SS, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_1 < 0)) { + PyErr_Fetch(&__pyx_t_4, &__pyx_t_3, &__pyx_t_2); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_stack_f.rcbuffer->pybuffer, (PyObject*)__pyx_v_stack_f, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_3); Py_XDECREF(__pyx_t_2); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_4, __pyx_t_3, __pyx_t_2); + } + } + __pyx_pybuffernd_stack_f.diminfo[0].strides = __pyx_pybuffernd_stack_f.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_stack_f.diminfo[0].shape = __pyx_pybuffernd_stack_f.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_INCREF(((PyObject *)__pyx_v_SS)); + __pyx_v_stack_f = __pyx_v_SS; + + /* "sklearn/utils/mst/_traversal.pyx":615 + * + * # The stack of nodes which have been backtracked and are in the current SCC + * SS.fill(VOID) # <<<<<<<<<<<<<< + * SS_head = END + * + */ + __pyx_t_5 = PyObject_GetAttr(((PyObject *)__pyx_v_SS), __pyx_n_s__fill); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 615; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyInt_FromLong(__pyx_v_VOID); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 615; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 615; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 615; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":616 + * # The stack of nodes which have been backtracked and are in the current SCC + * SS.fill(VOID) + * SS_head = END # <<<<<<<<<<<<<< + * + * # The array containing the lowlinks of nodes not yet assigned an SCC. Shares + */ + __pyx_v_SS_head = __pyx_v_END; + + /* "sklearn/utils/mst/_traversal.pyx":620 + * # The array containing the lowlinks of nodes not yet assigned an SCC. Shares + * # memory with the labels array, since they are not used at the same time. + * lowlinks.fill(VOID) # <<<<<<<<<<<<<< + * + * # The DFS stack. Stored with both forwards and backwards pointers to allow + */ + __pyx_t_6 = PyObject_GetAttr(((PyObject *)__pyx_v_lowlinks), __pyx_n_s__fill); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 620; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyInt_FromLong(__pyx_v_VOID); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 620; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 620; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_7); + __Pyx_GIVEREF(__pyx_t_7); + __pyx_t_7 = 0; + __pyx_t_7 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 620; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":626 + * # each node once. stack_f shares memory with SS, as nodes aren't put on the + * # SS stack until after they've been popped from the DFS stack. + * stack_head = END # <<<<<<<<<<<<<< + * stack_f.fill(VOID) + * stack_b.fill(VOID) + */ + __pyx_v_stack_head = __pyx_v_END; + + /* "sklearn/utils/mst/_traversal.pyx":627 + * # SS stack until after they've been popped from the DFS stack. + * stack_head = END + * stack_f.fill(VOID) # <<<<<<<<<<<<<< + * stack_b.fill(VOID) + * + */ + __pyx_t_7 = PyObject_GetAttr(((PyObject *)__pyx_v_stack_f), __pyx_n_s__fill); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 627; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_5 = PyInt_FromLong(__pyx_v_VOID); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 627; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 627; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_t_7, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 627; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":628 + * stack_head = END + * stack_f.fill(VOID) + * stack_b.fill(VOID) # <<<<<<<<<<<<<< + * + * index = 0 + */ + __pyx_t_5 = PyObject_GetAttr(((PyObject *)__pyx_v_stack_b), __pyx_n_s__fill); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyInt_FromLong(__pyx_v_VOID); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":630 + * stack_b.fill(VOID) + * + * index = 0 # <<<<<<<<<<<<<< + * # Count SCC labels backwards so as not to class with lowlinks values. + * label = N - 1 + */ + __pyx_v_index = 0; + + /* "sklearn/utils/mst/_traversal.pyx":632 + * index = 0 + * # Count SCC labels backwards so as not to class with lowlinks values. + * label = N - 1 # <<<<<<<<<<<<<< + * for v in range(N): + * if lowlinks[v] == VOID: + */ + __pyx_v_label = (__pyx_v_N - 1); + + /* "sklearn/utils/mst/_traversal.pyx":633 + * # Count SCC labels backwards so as not to class with lowlinks values. + * label = N - 1 + * for v in range(N): # <<<<<<<<<<<<<< + * if lowlinks[v] == VOID: + * # DFS-stack push + */ + __pyx_t_1 = __pyx_v_N; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_1; __pyx_t_8+=1) { + __pyx_v_v = __pyx_t_8; + + /* "sklearn/utils/mst/_traversal.pyx":634 + * label = N - 1 + * for v in range(N): + * if lowlinks[v] == VOID: # <<<<<<<<<<<<<< + * # DFS-stack push + * stack_head = v + */ + __pyx_t_9 = __pyx_v_v; + __pyx_t_10 = -1; + if (__pyx_t_9 < 0) { + __pyx_t_9 += __pyx_pybuffernd_lowlinks.diminfo[0].shape; + if (unlikely(__pyx_t_9 < 0)) __pyx_t_10 = 0; + } else if (unlikely(__pyx_t_9 >= __pyx_pybuffernd_lowlinks.diminfo[0].shape)) __pyx_t_10 = 0; + if (unlikely(__pyx_t_10 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_10); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_11 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_lowlinks.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_lowlinks.diminfo[0].strides)) == __pyx_v_VOID); + if (__pyx_t_11) { + + /* "sklearn/utils/mst/_traversal.pyx":636 + * if lowlinks[v] == VOID: + * # DFS-stack push + * stack_head = v # <<<<<<<<<<<<<< + * stack_f[v] = END + * stack_b[v] = END + */ + __pyx_v_stack_head = __pyx_v_v; + + /* "sklearn/utils/mst/_traversal.pyx":637 + * # DFS-stack push + * stack_head = v + * stack_f[v] = END # <<<<<<<<<<<<<< + * stack_b[v] = END + * while stack_head != END: + */ + __pyx_t_10 = __pyx_v_v; + __pyx_t_12 = -1; + if (__pyx_t_10 < 0) { + __pyx_t_10 += __pyx_pybuffernd_stack_f.diminfo[0].shape; + if (unlikely(__pyx_t_10 < 0)) __pyx_t_12 = 0; + } else if (unlikely(__pyx_t_10 >= __pyx_pybuffernd_stack_f.diminfo[0].shape)) __pyx_t_12 = 0; + if (unlikely(__pyx_t_12 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_12); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_f.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_stack_f.diminfo[0].strides) = __pyx_v_END; + + /* "sklearn/utils/mst/_traversal.pyx":638 + * stack_head = v + * stack_f[v] = END + * stack_b[v] = END # <<<<<<<<<<<<<< + * while stack_head != END: + * v = stack_head + */ + __pyx_t_12 = __pyx_v_v; + __pyx_t_13 = -1; + if (__pyx_t_12 < 0) { + __pyx_t_12 += __pyx_pybuffernd_stack_b.diminfo[0].shape; + if (unlikely(__pyx_t_12 < 0)) __pyx_t_13 = 0; + } else if (unlikely(__pyx_t_12 >= __pyx_pybuffernd_stack_b.diminfo[0].shape)) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_b.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_stack_b.diminfo[0].strides) = __pyx_v_END; + + /* "sklearn/utils/mst/_traversal.pyx":639 + * stack_f[v] = END + * stack_b[v] = END + * while stack_head != END: # <<<<<<<<<<<<<< + * v = stack_head + * if lowlinks[v] == VOID: + */ + while (1) { + __pyx_t_11 = (__pyx_v_stack_head != __pyx_v_END); + if (!__pyx_t_11) break; + + /* "sklearn/utils/mst/_traversal.pyx":640 + * stack_b[v] = END + * while stack_head != END: + * v = stack_head # <<<<<<<<<<<<<< + * if lowlinks[v] == VOID: + * lowlinks[v] = index + */ + __pyx_v_v = __pyx_v_stack_head; + + /* "sklearn/utils/mst/_traversal.pyx":641 + * while stack_head != END: + * v = stack_head + * if lowlinks[v] == VOID: # <<<<<<<<<<<<<< + * lowlinks[v] = index + * index += 1 + */ + __pyx_t_13 = __pyx_v_v; + __pyx_t_14 = -1; + if (__pyx_t_13 < 0) { + __pyx_t_13 += __pyx_pybuffernd_lowlinks.diminfo[0].shape; + if (unlikely(__pyx_t_13 < 0)) __pyx_t_14 = 0; + } else if (unlikely(__pyx_t_13 >= __pyx_pybuffernd_lowlinks.diminfo[0].shape)) __pyx_t_14 = 0; + if (unlikely(__pyx_t_14 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_14); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_11 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_lowlinks.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_lowlinks.diminfo[0].strides)) == __pyx_v_VOID); + if (__pyx_t_11) { + + /* "sklearn/utils/mst/_traversal.pyx":642 + * v = stack_head + * if lowlinks[v] == VOID: + * lowlinks[v] = index # <<<<<<<<<<<<<< + * index += 1 + * + */ + __pyx_t_14 = __pyx_v_v; + __pyx_t_15 = -1; + if (__pyx_t_14 < 0) { + __pyx_t_14 += __pyx_pybuffernd_lowlinks.diminfo[0].shape; + if (unlikely(__pyx_t_14 < 0)) __pyx_t_15 = 0; + } else if (unlikely(__pyx_t_14 >= __pyx_pybuffernd_lowlinks.diminfo[0].shape)) __pyx_t_15 = 0; + if (unlikely(__pyx_t_15 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_15); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 642; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_lowlinks.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_lowlinks.diminfo[0].strides) = __pyx_v_index; + + /* "sklearn/utils/mst/_traversal.pyx":643 + * if lowlinks[v] == VOID: + * lowlinks[v] = index + * index += 1 # <<<<<<<<<<<<<< + * + * # Add successor nodes + */ + __pyx_v_index = (__pyx_v_index + 1); + + /* "sklearn/utils/mst/_traversal.pyx":646 + * + * # Add successor nodes + * for j from indptr[v] <= j < indptr[v+1]: # <<<<<<<<<<<<<< + * w = indices[j] + * if lowlinks[w] == VOID: + */ + __pyx_t_15 = __pyx_v_v; + __pyx_t_16 = -1; + if (__pyx_t_15 < 0) { + __pyx_t_15 += __pyx_pybuffernd_indptr.diminfo[0].shape; + if (unlikely(__pyx_t_15 < 0)) __pyx_t_16 = 0; + } else if (unlikely(__pyx_t_15 >= __pyx_pybuffernd_indptr.diminfo[0].shape)) __pyx_t_16 = 0; + if (unlikely(__pyx_t_16 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_16); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_17 = (__pyx_v_v + 1); + __pyx_t_16 = -1; + if (__pyx_t_17 < 0) { + __pyx_t_17 += __pyx_pybuffernd_indptr.diminfo[0].shape; + if (unlikely(__pyx_t_17 < 0)) __pyx_t_16 = 0; + } else if (unlikely(__pyx_t_17 >= __pyx_pybuffernd_indptr.diminfo[0].shape)) __pyx_t_16 = 0; + if (unlikely(__pyx_t_16 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_16); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_18 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_indptr.diminfo[0].strides)); + for (__pyx_v_j = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_indptr.diminfo[0].strides)); __pyx_v_j < __pyx_t_18; __pyx_v_j++) { + + /* "sklearn/utils/mst/_traversal.pyx":647 + * # Add successor nodes + * for j from indptr[v] <= j < indptr[v+1]: + * w = indices[j] # <<<<<<<<<<<<<< + * if lowlinks[w] == VOID: + * # DFS-stack push + */ + __pyx_t_16 = __pyx_v_j; + __pyx_t_19 = -1; + if (__pyx_t_16 < 0) { + __pyx_t_16 += __pyx_pybuffernd_indices.diminfo[0].shape; + if (unlikely(__pyx_t_16 < 0)) __pyx_t_19 = 0; + } else if (unlikely(__pyx_t_16 >= __pyx_pybuffernd_indices.diminfo[0].shape)) __pyx_t_19 = 0; + if (unlikely(__pyx_t_19 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_19); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_w = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indices.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_indices.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":648 + * for j from indptr[v] <= j < indptr[v+1]: + * w = indices[j] + * if lowlinks[w] == VOID: # <<<<<<<<<<<<<< + * # DFS-stack push + * if stack_f[w] != VOID: + */ + __pyx_t_19 = __pyx_v_w; + __pyx_t_20 = -1; + if (__pyx_t_19 < 0) { + __pyx_t_19 += __pyx_pybuffernd_lowlinks.diminfo[0].shape; + if (unlikely(__pyx_t_19 < 0)) __pyx_t_20 = 0; + } else if (unlikely(__pyx_t_19 >= __pyx_pybuffernd_lowlinks.diminfo[0].shape)) __pyx_t_20 = 0; + if (unlikely(__pyx_t_20 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_20); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_11 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_lowlinks.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_lowlinks.diminfo[0].strides)) == __pyx_v_VOID); + if (__pyx_t_11) { + + /* "sklearn/utils/mst/_traversal.pyx":650 + * if lowlinks[w] == VOID: + * # DFS-stack push + * if stack_f[w] != VOID: # <<<<<<<<<<<<<< + * # w is already inside the stack, so excise it. + * f = stack_f[w] + */ + __pyx_t_20 = __pyx_v_w; + __pyx_t_21 = -1; + if (__pyx_t_20 < 0) { + __pyx_t_20 += __pyx_pybuffernd_stack_f.diminfo[0].shape; + if (unlikely(__pyx_t_20 < 0)) __pyx_t_21 = 0; + } else if (unlikely(__pyx_t_20 >= __pyx_pybuffernd_stack_f.diminfo[0].shape)) __pyx_t_21 = 0; + if (unlikely(__pyx_t_21 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_21); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_11 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_f.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_stack_f.diminfo[0].strides)) != __pyx_v_VOID); + if (__pyx_t_11) { + + /* "sklearn/utils/mst/_traversal.pyx":652 + * if stack_f[w] != VOID: + * # w is already inside the stack, so excise it. + * f = stack_f[w] # <<<<<<<<<<<<<< + * b = stack_b[w] + * if b != END: + */ + __pyx_t_21 = __pyx_v_w; + __pyx_t_22 = -1; + if (__pyx_t_21 < 0) { + __pyx_t_21 += __pyx_pybuffernd_stack_f.diminfo[0].shape; + if (unlikely(__pyx_t_21 < 0)) __pyx_t_22 = 0; + } else if (unlikely(__pyx_t_21 >= __pyx_pybuffernd_stack_f.diminfo[0].shape)) __pyx_t_22 = 0; + if (unlikely(__pyx_t_22 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_22); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_f = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_f.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_stack_f.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":653 + * # w is already inside the stack, so excise it. + * f = stack_f[w] + * b = stack_b[w] # <<<<<<<<<<<<<< + * if b != END: + * stack_f[b] = f + */ + __pyx_t_22 = __pyx_v_w; + __pyx_t_23 = -1; + if (__pyx_t_22 < 0) { + __pyx_t_22 += __pyx_pybuffernd_stack_b.diminfo[0].shape; + if (unlikely(__pyx_t_22 < 0)) __pyx_t_23 = 0; + } else if (unlikely(__pyx_t_22 >= __pyx_pybuffernd_stack_b.diminfo[0].shape)) __pyx_t_23 = 0; + if (unlikely(__pyx_t_23 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_23); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_b = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_b.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_stack_b.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":654 + * f = stack_f[w] + * b = stack_b[w] + * if b != END: # <<<<<<<<<<<<<< + * stack_f[b] = f + * if f != END: + */ + __pyx_t_11 = (__pyx_v_b != __pyx_v_END); + if (__pyx_t_11) { + + /* "sklearn/utils/mst/_traversal.pyx":655 + * b = stack_b[w] + * if b != END: + * stack_f[b] = f # <<<<<<<<<<<<<< + * if f != END: + * stack_b[f] = b + */ + __pyx_t_23 = __pyx_v_b; + __pyx_t_24 = -1; + if (__pyx_t_23 < 0) { + __pyx_t_23 += __pyx_pybuffernd_stack_f.diminfo[0].shape; + if (unlikely(__pyx_t_23 < 0)) __pyx_t_24 = 0; + } else if (unlikely(__pyx_t_23 >= __pyx_pybuffernd_stack_f.diminfo[0].shape)) __pyx_t_24 = 0; + if (unlikely(__pyx_t_24 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_24); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 655; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_f.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_stack_f.diminfo[0].strides) = __pyx_v_f; + goto __pyx_L13; + } + __pyx_L13:; + + /* "sklearn/utils/mst/_traversal.pyx":656 + * if b != END: + * stack_f[b] = f + * if f != END: # <<<<<<<<<<<<<< + * stack_b[f] = b + * + */ + __pyx_t_11 = (__pyx_v_f != __pyx_v_END); + if (__pyx_t_11) { + + /* "sklearn/utils/mst/_traversal.pyx":657 + * stack_f[b] = f + * if f != END: + * stack_b[f] = b # <<<<<<<<<<<<<< + * + * stack_f[w] = stack_head + */ + __pyx_t_24 = __pyx_v_f; + __pyx_t_25 = -1; + if (__pyx_t_24 < 0) { + __pyx_t_24 += __pyx_pybuffernd_stack_b.diminfo[0].shape; + if (unlikely(__pyx_t_24 < 0)) __pyx_t_25 = 0; + } else if (unlikely(__pyx_t_24 >= __pyx_pybuffernd_stack_b.diminfo[0].shape)) __pyx_t_25 = 0; + if (unlikely(__pyx_t_25 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_25); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 657; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_b.rcbuffer->pybuffer.buf, __pyx_t_24, __pyx_pybuffernd_stack_b.diminfo[0].strides) = __pyx_v_b; + goto __pyx_L14; + } + __pyx_L14:; + goto __pyx_L12; + } + __pyx_L12:; + + /* "sklearn/utils/mst/_traversal.pyx":659 + * stack_b[f] = b + * + * stack_f[w] = stack_head # <<<<<<<<<<<<<< + * stack_b[w] = END + * stack_b[stack_head] = w + */ + __pyx_t_25 = __pyx_v_w; + __pyx_t_26 = -1; + if (__pyx_t_25 < 0) { + __pyx_t_25 += __pyx_pybuffernd_stack_f.diminfo[0].shape; + if (unlikely(__pyx_t_25 < 0)) __pyx_t_26 = 0; + } else if (unlikely(__pyx_t_25 >= __pyx_pybuffernd_stack_f.diminfo[0].shape)) __pyx_t_26 = 0; + if (unlikely(__pyx_t_26 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_26); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_f.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_stack_f.diminfo[0].strides) = __pyx_v_stack_head; + + /* "sklearn/utils/mst/_traversal.pyx":660 + * + * stack_f[w] = stack_head + * stack_b[w] = END # <<<<<<<<<<<<<< + * stack_b[stack_head] = w + * stack_head = w + */ + __pyx_t_26 = __pyx_v_w; + __pyx_t_27 = -1; + if (__pyx_t_26 < 0) { + __pyx_t_26 += __pyx_pybuffernd_stack_b.diminfo[0].shape; + if (unlikely(__pyx_t_26 < 0)) __pyx_t_27 = 0; + } else if (unlikely(__pyx_t_26 >= __pyx_pybuffernd_stack_b.diminfo[0].shape)) __pyx_t_27 = 0; + if (unlikely(__pyx_t_27 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_27); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_b.rcbuffer->pybuffer.buf, __pyx_t_26, __pyx_pybuffernd_stack_b.diminfo[0].strides) = __pyx_v_END; + + /* "sklearn/utils/mst/_traversal.pyx":661 + * stack_f[w] = stack_head + * stack_b[w] = END + * stack_b[stack_head] = w # <<<<<<<<<<<<<< + * stack_head = w + * + */ + __pyx_t_27 = __pyx_v_stack_head; + __pyx_t_28 = -1; + if (__pyx_t_27 < 0) { + __pyx_t_27 += __pyx_pybuffernd_stack_b.diminfo[0].shape; + if (unlikely(__pyx_t_27 < 0)) __pyx_t_28 = 0; + } else if (unlikely(__pyx_t_27 >= __pyx_pybuffernd_stack_b.diminfo[0].shape)) __pyx_t_28 = 0; + if (unlikely(__pyx_t_28 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_28); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 661; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_b.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_stack_b.diminfo[0].strides) = __pyx_v_w; + + /* "sklearn/utils/mst/_traversal.pyx":662 + * stack_b[w] = END + * stack_b[stack_head] = w + * stack_head = w # <<<<<<<<<<<<<< + * + * else: + */ + __pyx_v_stack_head = __pyx_v_w; + goto __pyx_L11; + } + __pyx_L11:; + } + goto __pyx_L8; + } + /*else*/ { + + /* "sklearn/utils/mst/_traversal.pyx":666 + * else: + * # DFS-stack pop + * stack_head = stack_f[v] # <<<<<<<<<<<<<< + * if stack_head >= 0: + * stack_b[stack_head] = END + */ + __pyx_t_28 = __pyx_v_v; + __pyx_t_29 = -1; + if (__pyx_t_28 < 0) { + __pyx_t_28 += __pyx_pybuffernd_stack_f.diminfo[0].shape; + if (unlikely(__pyx_t_28 < 0)) __pyx_t_29 = 0; + } else if (unlikely(__pyx_t_28 >= __pyx_pybuffernd_stack_f.diminfo[0].shape)) __pyx_t_29 = 0; + if (unlikely(__pyx_t_29 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_29); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 666; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_stack_head = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_f.rcbuffer->pybuffer.buf, __pyx_t_28, __pyx_pybuffernd_stack_f.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":667 + * # DFS-stack pop + * stack_head = stack_f[v] + * if stack_head >= 0: # <<<<<<<<<<<<<< + * stack_b[stack_head] = END + * stack_f[v] = VOID + */ + __pyx_t_11 = (__pyx_v_stack_head >= 0); + if (__pyx_t_11) { + + /* "sklearn/utils/mst/_traversal.pyx":668 + * stack_head = stack_f[v] + * if stack_head >= 0: + * stack_b[stack_head] = END # <<<<<<<<<<<<<< + * stack_f[v] = VOID + * stack_b[v] = VOID + */ + __pyx_t_29 = __pyx_v_stack_head; + __pyx_t_30 = -1; + if (__pyx_t_29 < 0) { + __pyx_t_29 += __pyx_pybuffernd_stack_b.diminfo[0].shape; + if (unlikely(__pyx_t_29 < 0)) __pyx_t_30 = 0; + } else if (unlikely(__pyx_t_29 >= __pyx_pybuffernd_stack_b.diminfo[0].shape)) __pyx_t_30 = 0; + if (unlikely(__pyx_t_30 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_30); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_b.rcbuffer->pybuffer.buf, __pyx_t_29, __pyx_pybuffernd_stack_b.diminfo[0].strides) = __pyx_v_END; + goto __pyx_L15; + } + __pyx_L15:; + + /* "sklearn/utils/mst/_traversal.pyx":669 + * if stack_head >= 0: + * stack_b[stack_head] = END + * stack_f[v] = VOID # <<<<<<<<<<<<<< + * stack_b[v] = VOID + * + */ + __pyx_t_30 = __pyx_v_v; + __pyx_t_31 = -1; + if (__pyx_t_30 < 0) { + __pyx_t_30 += __pyx_pybuffernd_stack_f.diminfo[0].shape; + if (unlikely(__pyx_t_30 < 0)) __pyx_t_31 = 0; + } else if (unlikely(__pyx_t_30 >= __pyx_pybuffernd_stack_f.diminfo[0].shape)) __pyx_t_31 = 0; + if (unlikely(__pyx_t_31 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_31); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 669; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_f.rcbuffer->pybuffer.buf, __pyx_t_30, __pyx_pybuffernd_stack_f.diminfo[0].strides) = __pyx_v_VOID; + + /* "sklearn/utils/mst/_traversal.pyx":670 + * stack_b[stack_head] = END + * stack_f[v] = VOID + * stack_b[v] = VOID # <<<<<<<<<<<<<< + * + * root = 1 # True + */ + __pyx_t_31 = __pyx_v_v; + __pyx_t_32 = -1; + if (__pyx_t_31 < 0) { + __pyx_t_31 += __pyx_pybuffernd_stack_b.diminfo[0].shape; + if (unlikely(__pyx_t_31 < 0)) __pyx_t_32 = 0; + } else if (unlikely(__pyx_t_31 >= __pyx_pybuffernd_stack_b.diminfo[0].shape)) __pyx_t_32 = 0; + if (unlikely(__pyx_t_32 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_32); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 670; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_stack_b.rcbuffer->pybuffer.buf, __pyx_t_31, __pyx_pybuffernd_stack_b.diminfo[0].strides) = __pyx_v_VOID; + + /* "sklearn/utils/mst/_traversal.pyx":672 + * stack_b[v] = VOID + * + * root = 1 # True # <<<<<<<<<<<<<< + * low_v = lowlinks[v] + * for j from indptr[v] <= j < indptr[v+1]: + */ + __pyx_v_root = 1; + + /* "sklearn/utils/mst/_traversal.pyx":673 + * + * root = 1 # True + * low_v = lowlinks[v] # <<<<<<<<<<<<<< + * for j from indptr[v] <= j < indptr[v+1]: + * low_w = lowlinks[indices[j]] + */ + __pyx_t_32 = __pyx_v_v; + __pyx_t_33 = -1; + if (__pyx_t_32 < 0) { + __pyx_t_32 += __pyx_pybuffernd_lowlinks.diminfo[0].shape; + if (unlikely(__pyx_t_32 < 0)) __pyx_t_33 = 0; + } else if (unlikely(__pyx_t_32 >= __pyx_pybuffernd_lowlinks.diminfo[0].shape)) __pyx_t_33 = 0; + if (unlikely(__pyx_t_33 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_33); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 673; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_low_v = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_lowlinks.rcbuffer->pybuffer.buf, __pyx_t_32, __pyx_pybuffernd_lowlinks.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":674 + * root = 1 # True + * low_v = lowlinks[v] + * for j from indptr[v] <= j < indptr[v+1]: # <<<<<<<<<<<<<< + * low_w = lowlinks[indices[j]] + * if low_w < low_v: + */ + __pyx_t_33 = __pyx_v_v; + __pyx_t_34 = -1; + if (__pyx_t_33 < 0) { + __pyx_t_33 += __pyx_pybuffernd_indptr.diminfo[0].shape; + if (unlikely(__pyx_t_33 < 0)) __pyx_t_34 = 0; + } else if (unlikely(__pyx_t_33 >= __pyx_pybuffernd_indptr.diminfo[0].shape)) __pyx_t_34 = 0; + if (unlikely(__pyx_t_34 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_34); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 674; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_35 = (__pyx_v_v + 1); + __pyx_t_34 = -1; + if (__pyx_t_35 < 0) { + __pyx_t_35 += __pyx_pybuffernd_indptr.diminfo[0].shape; + if (unlikely(__pyx_t_35 < 0)) __pyx_t_34 = 0; + } else if (unlikely(__pyx_t_35 >= __pyx_pybuffernd_indptr.diminfo[0].shape)) __pyx_t_34 = 0; + if (unlikely(__pyx_t_34 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_34); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 674; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_18 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_35, __pyx_pybuffernd_indptr.diminfo[0].strides)); + for (__pyx_v_j = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr.rcbuffer->pybuffer.buf, __pyx_t_33, __pyx_pybuffernd_indptr.diminfo[0].strides)); __pyx_v_j < __pyx_t_18; __pyx_v_j++) { + + /* "sklearn/utils/mst/_traversal.pyx":675 + * low_v = lowlinks[v] + * for j from indptr[v] <= j < indptr[v+1]: + * low_w = lowlinks[indices[j]] # <<<<<<<<<<<<<< + * if low_w < low_v: + * low_v = low_w + */ + __pyx_t_34 = __pyx_v_j; + __pyx_t_36 = -1; + if (__pyx_t_34 < 0) { + __pyx_t_34 += __pyx_pybuffernd_indices.diminfo[0].shape; + if (unlikely(__pyx_t_34 < 0)) __pyx_t_36 = 0; + } else if (unlikely(__pyx_t_34 >= __pyx_pybuffernd_indices.diminfo[0].shape)) __pyx_t_36 = 0; + if (unlikely(__pyx_t_36 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_36); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 675; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_37 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indices.rcbuffer->pybuffer.buf, __pyx_t_34, __pyx_pybuffernd_indices.diminfo[0].strides)); + __pyx_t_36 = -1; + if (__pyx_t_37 < 0) { + __pyx_t_37 += __pyx_pybuffernd_lowlinks.diminfo[0].shape; + if (unlikely(__pyx_t_37 < 0)) __pyx_t_36 = 0; + } else if (unlikely(__pyx_t_37 >= __pyx_pybuffernd_lowlinks.diminfo[0].shape)) __pyx_t_36 = 0; + if (unlikely(__pyx_t_36 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_36); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 675; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_low_w = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_lowlinks.rcbuffer->pybuffer.buf, __pyx_t_37, __pyx_pybuffernd_lowlinks.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":676 + * for j from indptr[v] <= j < indptr[v+1]: + * low_w = lowlinks[indices[j]] + * if low_w < low_v: # <<<<<<<<<<<<<< + * low_v = low_w + * root = 0 # False + */ + __pyx_t_11 = (__pyx_v_low_w < __pyx_v_low_v); + if (__pyx_t_11) { + + /* "sklearn/utils/mst/_traversal.pyx":677 + * low_w = lowlinks[indices[j]] + * if low_w < low_v: + * low_v = low_w # <<<<<<<<<<<<<< + * root = 0 # False + * lowlinks[v] = low_v + */ + __pyx_v_low_v = __pyx_v_low_w; + + /* "sklearn/utils/mst/_traversal.pyx":678 + * if low_w < low_v: + * low_v = low_w + * root = 0 # False # <<<<<<<<<<<<<< + * lowlinks[v] = low_v + * + */ + __pyx_v_root = 0; + goto __pyx_L18; + } + __pyx_L18:; + } + + /* "sklearn/utils/mst/_traversal.pyx":679 + * low_v = low_w + * root = 0 # False + * lowlinks[v] = low_v # <<<<<<<<<<<<<< + * + * if root: # Found a root node + */ + __pyx_t_36 = __pyx_v_v; + __pyx_t_38 = -1; + if (__pyx_t_36 < 0) { + __pyx_t_36 += __pyx_pybuffernd_lowlinks.diminfo[0].shape; + if (unlikely(__pyx_t_36 < 0)) __pyx_t_38 = 0; + } else if (unlikely(__pyx_t_36 >= __pyx_pybuffernd_lowlinks.diminfo[0].shape)) __pyx_t_38 = 0; + if (unlikely(__pyx_t_38 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_38); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_lowlinks.rcbuffer->pybuffer.buf, __pyx_t_36, __pyx_pybuffernd_lowlinks.diminfo[0].strides) = __pyx_v_low_v; + + /* "sklearn/utils/mst/_traversal.pyx":681 + * lowlinks[v] = low_v + * + * if root: # Found a root node # <<<<<<<<<<<<<< + * index -= 1 + * # while S not empty and rindex[v] <= rindex[top[S] + */ + if (__pyx_v_root) { + + /* "sklearn/utils/mst/_traversal.pyx":682 + * + * if root: # Found a root node + * index -= 1 # <<<<<<<<<<<<<< + * # while S not empty and rindex[v] <= rindex[top[S] + * while SS_head != END and lowlinks[v] <= lowlinks[SS_head]: + */ + __pyx_v_index = (__pyx_v_index - 1); + + /* "sklearn/utils/mst/_traversal.pyx":684 + * index -= 1 + * # while S not empty and rindex[v] <= rindex[top[S] + * while SS_head != END and lowlinks[v] <= lowlinks[SS_head]: # <<<<<<<<<<<<<< + * w = SS_head # w = pop(S) + * SS_head = SS[w] + */ + while (1) { + __pyx_t_11 = (__pyx_v_SS_head != __pyx_v_END); + if (__pyx_t_11) { + __pyx_t_38 = __pyx_v_v; + __pyx_t_39 = -1; + if (__pyx_t_38 < 0) { + __pyx_t_38 += __pyx_pybuffernd_lowlinks.diminfo[0].shape; + if (unlikely(__pyx_t_38 < 0)) __pyx_t_39 = 0; + } else if (unlikely(__pyx_t_38 >= __pyx_pybuffernd_lowlinks.diminfo[0].shape)) __pyx_t_39 = 0; + if (unlikely(__pyx_t_39 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_39); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 684; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_39 = __pyx_v_SS_head; + __pyx_t_40 = -1; + if (__pyx_t_39 < 0) { + __pyx_t_39 += __pyx_pybuffernd_lowlinks.diminfo[0].shape; + if (unlikely(__pyx_t_39 < 0)) __pyx_t_40 = 0; + } else if (unlikely(__pyx_t_39 >= __pyx_pybuffernd_lowlinks.diminfo[0].shape)) __pyx_t_40 = 0; + if (unlikely(__pyx_t_40 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_40); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 684; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_41 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_lowlinks.rcbuffer->pybuffer.buf, __pyx_t_38, __pyx_pybuffernd_lowlinks.diminfo[0].strides)) <= (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_lowlinks.rcbuffer->pybuffer.buf, __pyx_t_39, __pyx_pybuffernd_lowlinks.diminfo[0].strides))); + __pyx_t_42 = __pyx_t_41; + } else { + __pyx_t_42 = __pyx_t_11; + } + if (!__pyx_t_42) break; + + /* "sklearn/utils/mst/_traversal.pyx":685 + * # while S not empty and rindex[v] <= rindex[top[S] + * while SS_head != END and lowlinks[v] <= lowlinks[SS_head]: + * w = SS_head # w = pop(S) # <<<<<<<<<<<<<< + * SS_head = SS[w] + * SS[w] = VOID + */ + __pyx_v_w = __pyx_v_SS_head; + + /* "sklearn/utils/mst/_traversal.pyx":686 + * while SS_head != END and lowlinks[v] <= lowlinks[SS_head]: + * w = SS_head # w = pop(S) + * SS_head = SS[w] # <<<<<<<<<<<<<< + * SS[w] = VOID + * + */ + __pyx_t_40 = __pyx_v_w; + __pyx_t_43 = -1; + if (__pyx_t_40 < 0) { + __pyx_t_40 += __pyx_pybuffernd_SS.diminfo[0].shape; + if (unlikely(__pyx_t_40 < 0)) __pyx_t_43 = 0; + } else if (unlikely(__pyx_t_40 >= __pyx_pybuffernd_SS.diminfo[0].shape)) __pyx_t_43 = 0; + if (unlikely(__pyx_t_43 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_43); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 686; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_SS_head = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_SS.rcbuffer->pybuffer.buf, __pyx_t_40, __pyx_pybuffernd_SS.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":687 + * w = SS_head # w = pop(S) + * SS_head = SS[w] + * SS[w] = VOID # <<<<<<<<<<<<<< + * + * labels[w] = label # rindex[w] = c + */ + __pyx_t_43 = __pyx_v_w; + __pyx_t_44 = -1; + if (__pyx_t_43 < 0) { + __pyx_t_43 += __pyx_pybuffernd_SS.diminfo[0].shape; + if (unlikely(__pyx_t_43 < 0)) __pyx_t_44 = 0; + } else if (unlikely(__pyx_t_43 >= __pyx_pybuffernd_SS.diminfo[0].shape)) __pyx_t_44 = 0; + if (unlikely(__pyx_t_44 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_44); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_SS.rcbuffer->pybuffer.buf, __pyx_t_43, __pyx_pybuffernd_SS.diminfo[0].strides) = __pyx_v_VOID; + + /* "sklearn/utils/mst/_traversal.pyx":689 + * SS[w] = VOID + * + * labels[w] = label # rindex[w] = c # <<<<<<<<<<<<<< + * index -= 1 # index = index - 1 + * labels[v] = label # rindex[v] = c + */ + __pyx_t_44 = __pyx_v_w; + __pyx_t_45 = -1; + if (__pyx_t_44 < 0) { + __pyx_t_44 += __pyx_pybuffernd_labels.diminfo[0].shape; + if (unlikely(__pyx_t_44 < 0)) __pyx_t_45 = 0; + } else if (unlikely(__pyx_t_44 >= __pyx_pybuffernd_labels.diminfo[0].shape)) __pyx_t_45 = 0; + if (unlikely(__pyx_t_45 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_45); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 689; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_labels.rcbuffer->pybuffer.buf, __pyx_t_44, __pyx_pybuffernd_labels.diminfo[0].strides) = __pyx_v_label; + + /* "sklearn/utils/mst/_traversal.pyx":690 + * + * labels[w] = label # rindex[w] = c + * index -= 1 # index = index - 1 # <<<<<<<<<<<<<< + * labels[v] = label # rindex[v] = c + * label -= 1 # c = c - 1 + */ + __pyx_v_index = (__pyx_v_index - 1); + } + + /* "sklearn/utils/mst/_traversal.pyx":691 + * labels[w] = label # rindex[w] = c + * index -= 1 # index = index - 1 + * labels[v] = label # rindex[v] = c # <<<<<<<<<<<<<< + * label -= 1 # c = c - 1 + * else: + */ + __pyx_t_45 = __pyx_v_v; + __pyx_t_46 = -1; + if (__pyx_t_45 < 0) { + __pyx_t_45 += __pyx_pybuffernd_labels.diminfo[0].shape; + if (unlikely(__pyx_t_45 < 0)) __pyx_t_46 = 0; + } else if (unlikely(__pyx_t_45 >= __pyx_pybuffernd_labels.diminfo[0].shape)) __pyx_t_46 = 0; + if (unlikely(__pyx_t_46 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_46); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 691; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_labels.rcbuffer->pybuffer.buf, __pyx_t_45, __pyx_pybuffernd_labels.diminfo[0].strides) = __pyx_v_label; + + /* "sklearn/utils/mst/_traversal.pyx":692 + * index -= 1 # index = index - 1 + * labels[v] = label # rindex[v] = c + * label -= 1 # c = c - 1 # <<<<<<<<<<<<<< + * else: + * SS[v] = SS_head # push(S, v) + */ + __pyx_v_label = (__pyx_v_label - 1); + goto __pyx_L19; + } + /*else*/ { + + /* "sklearn/utils/mst/_traversal.pyx":694 + * label -= 1 # c = c - 1 + * else: + * SS[v] = SS_head # push(S, v) # <<<<<<<<<<<<<< + * SS_head = v + * + */ + __pyx_t_46 = __pyx_v_v; + __pyx_t_47 = -1; + if (__pyx_t_46 < 0) { + __pyx_t_46 += __pyx_pybuffernd_SS.diminfo[0].shape; + if (unlikely(__pyx_t_46 < 0)) __pyx_t_47 = 0; + } else if (unlikely(__pyx_t_46 >= __pyx_pybuffernd_SS.diminfo[0].shape)) __pyx_t_47 = 0; + if (unlikely(__pyx_t_47 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_47); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 694; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_SS.rcbuffer->pybuffer.buf, __pyx_t_46, __pyx_pybuffernd_SS.diminfo[0].strides) = __pyx_v_SS_head; + + /* "sklearn/utils/mst/_traversal.pyx":695 + * else: + * SS[v] = SS_head # push(S, v) + * SS_head = v # <<<<<<<<<<<<<< + * + * # labels count down from N-1 to zero. Modify them so they + */ + __pyx_v_SS_head = __pyx_v_v; + } + __pyx_L19:; + } + __pyx_L8:; + } + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "sklearn/utils/mst/_traversal.pyx":699 + * # labels count down from N-1 to zero. Modify them so they + * # count upward from 0 + * labels *= -1 # <<<<<<<<<<<<<< + * labels += (N - 1) + * return (N - 1) - label + */ + __pyx_t_6 = PyNumber_InPlaceMultiply(((PyObject *)__pyx_v_labels), __pyx_int_neg_1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(((__pyx_t_6) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_48 = ((PyArrayObject *)__pyx_t_6); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __pyx_t_1 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_t_48, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_1 < 0)) { + PyErr_Fetch(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_2); Py_XDECREF(__pyx_t_3); Py_XDECREF(__pyx_t_4); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_2, __pyx_t_3, __pyx_t_4); + } + } + __pyx_pybuffernd_labels.diminfo[0].strides = __pyx_pybuffernd_labels.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_labels.diminfo[0].shape = __pyx_pybuffernd_labels.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_48 = 0; + __Pyx_DECREF(((PyObject *)__pyx_v_labels)); + __pyx_v_labels = ((PyArrayObject *)__pyx_t_6); + __pyx_t_6 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":700 + * # count upward from 0 + * labels *= -1 + * labels += (N - 1) # <<<<<<<<<<<<<< + * return (N - 1) - label + * + */ + __pyx_t_6 = PyInt_FromLong((__pyx_v_N - 1)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyNumber_InPlaceAdd(((PyObject *)__pyx_v_labels), __pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_48 = ((PyArrayObject *)__pyx_t_7); + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __pyx_t_1 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_t_48, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack); + if (unlikely(__pyx_t_1 < 0)) { + PyErr_Fetch(&__pyx_t_4, &__pyx_t_3, &__pyx_t_2); + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_3); Py_XDECREF(__pyx_t_2); + __Pyx_RaiseBufferFallbackError(); + } else { + PyErr_Restore(__pyx_t_4, __pyx_t_3, __pyx_t_2); + } + } + __pyx_pybuffernd_labels.diminfo[0].strides = __pyx_pybuffernd_labels.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_labels.diminfo[0].shape = __pyx_pybuffernd_labels.rcbuffer->pybuffer.shape[0]; + if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_48 = 0; + __Pyx_DECREF(((PyObject *)__pyx_v_labels)); + __pyx_v_labels = ((PyArrayObject *)__pyx_t_7); + __pyx_t_7 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":701 + * labels *= -1 + * labels += (N - 1) + * return (N - 1) - label # <<<<<<<<<<<<<< + * + * cdef int _connected_components_undirected( + */ + __pyx_r = ((__pyx_v_N - 1) - __pyx_v_label); + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_SS.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_lowlinks.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_stack_b.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_stack_f.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_WriteUnraisable("sklearn.utils.mst._traversal._connected_components_directed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_SS.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_lowlinks.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_stack_b.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_stack_f.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_SS); + __Pyx_XDECREF((PyObject *)__pyx_v_lowlinks); + __Pyx_XDECREF((PyObject *)__pyx_v_stack_f); + __Pyx_XDECREF((PyObject *)__pyx_v_stack_b); + __Pyx_XDECREF((PyObject *)__pyx_v_labels); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "sklearn/utils/mst/_traversal.pyx":703 + * return (N - 1) - label + * + * cdef int _connected_components_undirected( # <<<<<<<<<<<<<< + * np.ndarray[ITYPE_t, ndim=1, mode='c'] indices1, + * np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr1, + */ + +static int __pyx_f_7sklearn_5utils_3mst_10_traversal__connected_components_undirected(PyArrayObject *__pyx_v_indices1, PyArrayObject *__pyx_v_indptr1, PyArrayObject *__pyx_v_indices2, PyArrayObject *__pyx_v_indptr2, PyArrayObject *__pyx_v_labels) { + int __pyx_v_v; + int __pyx_v_w; + int __pyx_v_j; + int __pyx_v_label; + int __pyx_v_SS_head; + int __pyx_v_N; + int __pyx_v_VOID; + int __pyx_v_END; + PyArrayObject *__pyx_v_SS = 0; + __Pyx_LocalBuf_ND __pyx_pybuffernd_SS; + __Pyx_Buffer __pyx_pybuffer_SS; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices1; + __Pyx_Buffer __pyx_pybuffer_indices1; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indices2; + __Pyx_Buffer __pyx_pybuffer_indices2; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr1; + __Pyx_Buffer __pyx_pybuffer_indptr1; + __Pyx_LocalBuf_ND __pyx_pybuffernd_indptr2; + __Pyx_Buffer __pyx_pybuffer_indptr2; + __Pyx_LocalBuf_ND __pyx_pybuffernd_labels; + __Pyx_Buffer __pyx_pybuffer_labels; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + int __pyx_t_11; + int __pyx_t_12; + long __pyx_t_13; + __pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t __pyx_t_14; + int __pyx_t_15; + int __pyx_t_16; + int __pyx_t_17; + int __pyx_t_18; + long __pyx_t_19; + int __pyx_t_20; + int __pyx_t_21; + int __pyx_t_22; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_connected_components_undirected", 0); + __pyx_pybuffer_SS.pybuffer.buf = NULL; + __pyx_pybuffer_SS.refcount = 0; + __pyx_pybuffernd_SS.data = NULL; + __pyx_pybuffernd_SS.rcbuffer = &__pyx_pybuffer_SS; + __pyx_pybuffer_indices1.pybuffer.buf = NULL; + __pyx_pybuffer_indices1.refcount = 0; + __pyx_pybuffernd_indices1.data = NULL; + __pyx_pybuffernd_indices1.rcbuffer = &__pyx_pybuffer_indices1; + __pyx_pybuffer_indptr1.pybuffer.buf = NULL; + __pyx_pybuffer_indptr1.refcount = 0; + __pyx_pybuffernd_indptr1.data = NULL; + __pyx_pybuffernd_indptr1.rcbuffer = &__pyx_pybuffer_indptr1; + __pyx_pybuffer_indices2.pybuffer.buf = NULL; + __pyx_pybuffer_indices2.refcount = 0; + __pyx_pybuffernd_indices2.data = NULL; + __pyx_pybuffernd_indices2.rcbuffer = &__pyx_pybuffer_indices2; + __pyx_pybuffer_indptr2.pybuffer.buf = NULL; + __pyx_pybuffer_indptr2.refcount = 0; + __pyx_pybuffernd_indptr2.data = NULL; + __pyx_pybuffernd_indptr2.rcbuffer = &__pyx_pybuffer_indptr2; + __pyx_pybuffer_labels.pybuffer.buf = NULL; + __pyx_pybuffer_labels.refcount = 0; + __pyx_pybuffernd_labels.data = NULL; + __pyx_pybuffernd_labels.rcbuffer = &__pyx_pybuffer_labels; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices1.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indices1.diminfo[0].strides = __pyx_pybuffernd_indices1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices1.diminfo[0].shape = __pyx_pybuffernd_indices1.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr1, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indptr1.diminfo[0].strides = __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr1.diminfo[0].shape = __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indices2.rcbuffer->pybuffer, (PyObject*)__pyx_v_indices2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indices2.diminfo[0].strides = __pyx_pybuffernd_indices2.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indices2.diminfo[0].shape = __pyx_pybuffernd_indices2.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer, (PyObject*)__pyx_v_indptr2, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_indptr2.diminfo[0].strides = __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_indptr2.diminfo[0].shape = __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.shape[0]; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_labels.rcbuffer->pybuffer, (PyObject*)__pyx_v_labels, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_labels.diminfo[0].strides = __pyx_pybuffernd_labels.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_labels.diminfo[0].shape = __pyx_pybuffernd_labels.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/utils/mst/_traversal.pyx":711 + * + * cdef int v, w, j, label, SS_head + * cdef int N = labels.shape[0] # <<<<<<<<<<<<<< + * cdef int VOID = -1 + * cdef int END = -2 + */ + __pyx_v_N = (__pyx_v_labels->dimensions[0]); + + /* "sklearn/utils/mst/_traversal.pyx":712 + * cdef int v, w, j, label, SS_head + * cdef int N = labels.shape[0] + * cdef int VOID = -1 # <<<<<<<<<<<<<< + * cdef int END = -2 + * labels.fill(VOID) + */ + __pyx_v_VOID = -1; + + /* "sklearn/utils/mst/_traversal.pyx":713 + * cdef int N = labels.shape[0] + * cdef int VOID = -1 + * cdef int END = -2 # <<<<<<<<<<<<<< + * labels.fill(VOID) + * label = 0 + */ + __pyx_v_END = -2; + + /* "sklearn/utils/mst/_traversal.pyx":714 + * cdef int VOID = -1 + * cdef int END = -2 + * labels.fill(VOID) # <<<<<<<<<<<<<< + * label = 0 + * + */ + __pyx_t_1 = PyObject_GetAttr(((PyObject *)__pyx_v_labels), __pyx_n_s__fill); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 714; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromLong(__pyx_v_VOID); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 714; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 714; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 714; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":715 + * cdef int END = -2 + * labels.fill(VOID) + * label = 0 # <<<<<<<<<<<<<< + * + * # Share memory for the stack and labels, since labels are only + */ + __pyx_v_label = 0; + + /* "sklearn/utils/mst/_traversal.pyx":719 + * # Share memory for the stack and labels, since labels are only + * # applied once a node has been popped from the stack. + * cdef np.ndarray[ITYPE_t, ndim=1, mode="c"] SS = labels # <<<<<<<<<<<<<< + * SS_head = END + * for v in range(N): + */ + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_SS.rcbuffer->pybuffer, (PyObject*)((PyArrayObject *)__pyx_v_labels), &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { + __pyx_v_SS = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_SS.rcbuffer->pybuffer.buf = NULL; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else {__pyx_pybuffernd_SS.diminfo[0].strides = __pyx_pybuffernd_SS.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_SS.diminfo[0].shape = __pyx_pybuffernd_SS.rcbuffer->pybuffer.shape[0]; + } + } + __Pyx_INCREF(((PyObject *)__pyx_v_labels)); + __pyx_v_SS = ((PyArrayObject *)__pyx_v_labels); + + /* "sklearn/utils/mst/_traversal.pyx":720 + * # applied once a node has been popped from the stack. + * cdef np.ndarray[ITYPE_t, ndim=1, mode="c"] SS = labels + * SS_head = END # <<<<<<<<<<<<<< + * for v in range(N): + * if labels[v] == VOID: + */ + __pyx_v_SS_head = __pyx_v_END; + + /* "sklearn/utils/mst/_traversal.pyx":721 + * cdef np.ndarray[ITYPE_t, ndim=1, mode="c"] SS = labels + * SS_head = END + * for v in range(N): # <<<<<<<<<<<<<< + * if labels[v] == VOID: + * # SS.push(v) + */ + __pyx_t_4 = __pyx_v_N; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_v = __pyx_t_5; + + /* "sklearn/utils/mst/_traversal.pyx":722 + * SS_head = END + * for v in range(N): + * if labels[v] == VOID: # <<<<<<<<<<<<<< + * # SS.push(v) + * SS_head = v + */ + __pyx_t_6 = __pyx_v_v; + __pyx_t_7 = -1; + if (__pyx_t_6 < 0) { + __pyx_t_6 += __pyx_pybuffernd_labels.diminfo[0].shape; + if (unlikely(__pyx_t_6 < 0)) __pyx_t_7 = 0; + } else if (unlikely(__pyx_t_6 >= __pyx_pybuffernd_labels.diminfo[0].shape)) __pyx_t_7 = 0; + if (unlikely(__pyx_t_7 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_7); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_8 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_labels.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_labels.diminfo[0].strides)) == __pyx_v_VOID); + if (__pyx_t_8) { + + /* "sklearn/utils/mst/_traversal.pyx":724 + * if labels[v] == VOID: + * # SS.push(v) + * SS_head = v # <<<<<<<<<<<<<< + * SS[v] = END + * + */ + __pyx_v_SS_head = __pyx_v_v; + + /* "sklearn/utils/mst/_traversal.pyx":725 + * # SS.push(v) + * SS_head = v + * SS[v] = END # <<<<<<<<<<<<<< + * + * while SS_head != END: + */ + __pyx_t_7 = __pyx_v_v; + __pyx_t_9 = -1; + if (__pyx_t_7 < 0) { + __pyx_t_7 += __pyx_pybuffernd_SS.diminfo[0].shape; + if (unlikely(__pyx_t_7 < 0)) __pyx_t_9 = 0; + } else if (unlikely(__pyx_t_7 >= __pyx_pybuffernd_SS.diminfo[0].shape)) __pyx_t_9 = 0; + if (unlikely(__pyx_t_9 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_9); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_SS.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_SS.diminfo[0].strides) = __pyx_v_END; + + /* "sklearn/utils/mst/_traversal.pyx":727 + * SS[v] = END + * + * while SS_head != END: # <<<<<<<<<<<<<< + * # v = SS.pop() + * v = SS_head + */ + while (1) { + __pyx_t_8 = (__pyx_v_SS_head != __pyx_v_END); + if (!__pyx_t_8) break; + + /* "sklearn/utils/mst/_traversal.pyx":729 + * while SS_head != END: + * # v = SS.pop() + * v = SS_head # <<<<<<<<<<<<<< + * SS_head = SS[v] + * + */ + __pyx_v_v = __pyx_v_SS_head; + + /* "sklearn/utils/mst/_traversal.pyx":730 + * # v = SS.pop() + * v = SS_head + * SS_head = SS[v] # <<<<<<<<<<<<<< + * + * labels[v] = label + */ + __pyx_t_9 = __pyx_v_v; + __pyx_t_10 = -1; + if (__pyx_t_9 < 0) { + __pyx_t_9 += __pyx_pybuffernd_SS.diminfo[0].shape; + if (unlikely(__pyx_t_9 < 0)) __pyx_t_10 = 0; + } else if (unlikely(__pyx_t_9 >= __pyx_pybuffernd_SS.diminfo[0].shape)) __pyx_t_10 = 0; + if (unlikely(__pyx_t_10 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_10); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 730; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_SS_head = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_SS.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_SS.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":732 + * SS_head = SS[v] + * + * labels[v] = label # <<<<<<<<<<<<<< + * + * # Push children onto the stack if they havn't been + */ + __pyx_t_10 = __pyx_v_v; + __pyx_t_11 = -1; + if (__pyx_t_10 < 0) { + __pyx_t_10 += __pyx_pybuffernd_labels.diminfo[0].shape; + if (unlikely(__pyx_t_10 < 0)) __pyx_t_11 = 0; + } else if (unlikely(__pyx_t_10 >= __pyx_pybuffernd_labels.diminfo[0].shape)) __pyx_t_11 = 0; + if (unlikely(__pyx_t_11 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_11); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 732; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_labels.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_labels.diminfo[0].strides) = __pyx_v_label; + + /* "sklearn/utils/mst/_traversal.pyx":736 + * # Push children onto the stack if they havn't been + * # seen at all yet. + * for j from indptr1[v] <= j < indptr1[v+1]: # <<<<<<<<<<<<<< + * w = indices1[j] + * if SS[w] == VOID: + */ + __pyx_t_11 = __pyx_v_v; + __pyx_t_12 = -1; + if (__pyx_t_11 < 0) { + __pyx_t_11 += __pyx_pybuffernd_indptr1.diminfo[0].shape; + if (unlikely(__pyx_t_11 < 0)) __pyx_t_12 = 0; + } else if (unlikely(__pyx_t_11 >= __pyx_pybuffernd_indptr1.diminfo[0].shape)) __pyx_t_12 = 0; + if (unlikely(__pyx_t_12 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_12); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 736; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_13 = (__pyx_v_v + 1); + __pyx_t_12 = -1; + if (__pyx_t_13 < 0) { + __pyx_t_13 += __pyx_pybuffernd_indptr1.diminfo[0].shape; + if (unlikely(__pyx_t_13 < 0)) __pyx_t_12 = 0; + } else if (unlikely(__pyx_t_13 >= __pyx_pybuffernd_indptr1.diminfo[0].shape)) __pyx_t_12 = 0; + if (unlikely(__pyx_t_12 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_12); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 736; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_14 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_indptr1.diminfo[0].strides)); + for (__pyx_v_j = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr1.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_indptr1.diminfo[0].strides)); __pyx_v_j < __pyx_t_14; __pyx_v_j++) { + + /* "sklearn/utils/mst/_traversal.pyx":737 + * # seen at all yet. + * for j from indptr1[v] <= j < indptr1[v+1]: + * w = indices1[j] # <<<<<<<<<<<<<< + * if SS[w] == VOID: + * SS[w] = SS_head + */ + __pyx_t_12 = __pyx_v_j; + __pyx_t_15 = -1; + if (__pyx_t_12 < 0) { + __pyx_t_12 += __pyx_pybuffernd_indices1.diminfo[0].shape; + if (unlikely(__pyx_t_12 < 0)) __pyx_t_15 = 0; + } else if (unlikely(__pyx_t_12 >= __pyx_pybuffernd_indices1.diminfo[0].shape)) __pyx_t_15 = 0; + if (unlikely(__pyx_t_15 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_15); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 737; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_w = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indices1.rcbuffer->pybuffer.buf, __pyx_t_12, __pyx_pybuffernd_indices1.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":738 + * for j from indptr1[v] <= j < indptr1[v+1]: + * w = indices1[j] + * if SS[w] == VOID: # <<<<<<<<<<<<<< + * SS[w] = SS_head + * SS_head = w + */ + __pyx_t_15 = __pyx_v_w; + __pyx_t_16 = -1; + if (__pyx_t_15 < 0) { + __pyx_t_15 += __pyx_pybuffernd_SS.diminfo[0].shape; + if (unlikely(__pyx_t_15 < 0)) __pyx_t_16 = 0; + } else if (unlikely(__pyx_t_15 >= __pyx_pybuffernd_SS.diminfo[0].shape)) __pyx_t_16 = 0; + if (unlikely(__pyx_t_16 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_16); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 738; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_8 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_SS.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_SS.diminfo[0].strides)) == __pyx_v_VOID); + if (__pyx_t_8) { + + /* "sklearn/utils/mst/_traversal.pyx":739 + * w = indices1[j] + * if SS[w] == VOID: + * SS[w] = SS_head # <<<<<<<<<<<<<< + * SS_head = w + * for j from indptr2[v] <= j < indptr2[v+1]: + */ + __pyx_t_16 = __pyx_v_w; + __pyx_t_17 = -1; + if (__pyx_t_16 < 0) { + __pyx_t_16 += __pyx_pybuffernd_SS.diminfo[0].shape; + if (unlikely(__pyx_t_16 < 0)) __pyx_t_17 = 0; + } else if (unlikely(__pyx_t_16 >= __pyx_pybuffernd_SS.diminfo[0].shape)) __pyx_t_17 = 0; + if (unlikely(__pyx_t_17 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_17); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_SS.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_SS.diminfo[0].strides) = __pyx_v_SS_head; + + /* "sklearn/utils/mst/_traversal.pyx":740 + * if SS[w] == VOID: + * SS[w] = SS_head + * SS_head = w # <<<<<<<<<<<<<< + * for j from indptr2[v] <= j < indptr2[v+1]: + * w = indices2[j] + */ + __pyx_v_SS_head = __pyx_v_w; + goto __pyx_L10; + } + __pyx_L10:; + } + + /* "sklearn/utils/mst/_traversal.pyx":741 + * SS[w] = SS_head + * SS_head = w + * for j from indptr2[v] <= j < indptr2[v+1]: # <<<<<<<<<<<<<< + * w = indices2[j] + * if SS[w] == VOID: + */ + __pyx_t_17 = __pyx_v_v; + __pyx_t_18 = -1; + if (__pyx_t_17 < 0) { + __pyx_t_17 += __pyx_pybuffernd_indptr2.diminfo[0].shape; + if (unlikely(__pyx_t_17 < 0)) __pyx_t_18 = 0; + } else if (unlikely(__pyx_t_17 >= __pyx_pybuffernd_indptr2.diminfo[0].shape)) __pyx_t_18 = 0; + if (unlikely(__pyx_t_18 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_18); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 741; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_19 = (__pyx_v_v + 1); + __pyx_t_18 = -1; + if (__pyx_t_19 < 0) { + __pyx_t_19 += __pyx_pybuffernd_indptr2.diminfo[0].shape; + if (unlikely(__pyx_t_19 < 0)) __pyx_t_18 = 0; + } else if (unlikely(__pyx_t_19 >= __pyx_pybuffernd_indptr2.diminfo[0].shape)) __pyx_t_18 = 0; + if (unlikely(__pyx_t_18 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_18); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 741; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_14 = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_indptr2.diminfo[0].strides)); + for (__pyx_v_j = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indptr2.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_indptr2.diminfo[0].strides)); __pyx_v_j < __pyx_t_14; __pyx_v_j++) { + + /* "sklearn/utils/mst/_traversal.pyx":742 + * SS_head = w + * for j from indptr2[v] <= j < indptr2[v+1]: + * w = indices2[j] # <<<<<<<<<<<<<< + * if SS[w] == VOID: + * SS[w] = SS_head + */ + __pyx_t_18 = __pyx_v_j; + __pyx_t_20 = -1; + if (__pyx_t_18 < 0) { + __pyx_t_18 += __pyx_pybuffernd_indices2.diminfo[0].shape; + if (unlikely(__pyx_t_18 < 0)) __pyx_t_20 = 0; + } else if (unlikely(__pyx_t_18 >= __pyx_pybuffernd_indices2.diminfo[0].shape)) __pyx_t_20 = 0; + if (unlikely(__pyx_t_20 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_20); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 742; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_v_w = (*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_indices2.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_indices2.diminfo[0].strides)); + + /* "sklearn/utils/mst/_traversal.pyx":743 + * for j from indptr2[v] <= j < indptr2[v+1]: + * w = indices2[j] + * if SS[w] == VOID: # <<<<<<<<<<<<<< + * SS[w] = SS_head + * SS_head = w + */ + __pyx_t_20 = __pyx_v_w; + __pyx_t_21 = -1; + if (__pyx_t_20 < 0) { + __pyx_t_20 += __pyx_pybuffernd_SS.diminfo[0].shape; + if (unlikely(__pyx_t_20 < 0)) __pyx_t_21 = 0; + } else if (unlikely(__pyx_t_20 >= __pyx_pybuffernd_SS.diminfo[0].shape)) __pyx_t_21 = 0; + if (unlikely(__pyx_t_21 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_21); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 743; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_8 = ((*__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_SS.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_SS.diminfo[0].strides)) == __pyx_v_VOID); + if (__pyx_t_8) { + + /* "sklearn/utils/mst/_traversal.pyx":744 + * w = indices2[j] + * if SS[w] == VOID: + * SS[w] = SS_head # <<<<<<<<<<<<<< + * SS_head = w + * label += 1 + */ + __pyx_t_21 = __pyx_v_w; + __pyx_t_22 = -1; + if (__pyx_t_21 < 0) { + __pyx_t_21 += __pyx_pybuffernd_SS.diminfo[0].shape; + if (unlikely(__pyx_t_21 < 0)) __pyx_t_22 = 0; + } else if (unlikely(__pyx_t_21 >= __pyx_pybuffernd_SS.diminfo[0].shape)) __pyx_t_22 = 0; + if (unlikely(__pyx_t_22 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_22); + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 744; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + *__Pyx_BufPtrCContig1d(__pyx_t_7sklearn_5utils_3mst_10_traversal_ITYPE_t *, __pyx_pybuffernd_SS.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_SS.diminfo[0].strides) = __pyx_v_SS_head; + + /* "sklearn/utils/mst/_traversal.pyx":745 + * if SS[w] == VOID: + * SS[w] = SS_head + * SS_head = w # <<<<<<<<<<<<<< + * label += 1 + * + */ + __pyx_v_SS_head = __pyx_v_w; + goto __pyx_L13; + } + __pyx_L13:; + } + } + + /* "sklearn/utils/mst/_traversal.pyx":746 + * SS[w] = SS_head + * SS_head = w + * label += 1 # <<<<<<<<<<<<<< + * + * return label + */ + __pyx_v_label = (__pyx_v_label + 1); + goto __pyx_L5; + } + __pyx_L5:; + } + + /* "sklearn/utils/mst/_traversal.pyx":748 + * label += 1 + * + * return label # <<<<<<<<<<<<<< + */ + __pyx_r = __pyx_v_label; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_SS.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_WriteUnraisable("sklearn.utils.mst._traversal._connected_components_undirected", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + goto __pyx_L2; + __pyx_L0:; + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_SS.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indices2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr1.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_indptr2.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_labels.rcbuffer->pybuffer); + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_SS); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":193 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + int __pyx_v_t; + char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + int __pyx_v_offset; + int __pyx_v_hasfields; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + char *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getbuffer__", 0); + if (__pyx_v_info != NULL) { + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + } + + /* "numpy.pxd":199 + * # of flags + * + * if info == NULL: return # <<<<<<<<<<<<<< + * + * cdef int copy_shape, i, ndim + */ + __pyx_t_1 = (__pyx_v_info == NULL); + if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":202 + * + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":203 + * cdef int copy_shape, i, ndim + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * + * ndim = PyArray_NDIM(self) + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":205 + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); + + /* "numpy.pxd":207 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ + __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + if (__pyx_t_1) { + + /* "numpy.pxd":208 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L4; + } + /*else*/ { + + /* "numpy.pxd":210 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L4:; + + /* "numpy.pxd":212 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + if (__pyx_t_1) { + + /* "numpy.pxd":213 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not C contiguous") + * + */ + __pyx_t_2 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS)); + __pyx_t_3 = __pyx_t_2; + } else { + __pyx_t_3 = __pyx_t_1; + } + if (__pyx_t_3) { + + /* "numpy.pxd":214 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "numpy.pxd":216 + * raise ValueError(u"ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") + */ + __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + if (__pyx_t_3) { + + /* "numpy.pxd":217 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError(u"ndarray is not Fortran contiguous") + * + */ + __pyx_t_1 = (!PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS)); + __pyx_t_2 = __pyx_t_1; + } else { + __pyx_t_2 = __pyx_t_3; + } + if (__pyx_t_2) { + + /* "numpy.pxd":218 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "numpy.pxd":220 + * raise ValueError(u"ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); + + /* "numpy.pxd":221 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "numpy.pxd":222 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + */ + if (__pyx_v_copy_shape) { + + /* "numpy.pxd":225 + * # Allocate new buffer for strides and shape info. + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); + + /* "numpy.pxd":226 + * # This is allocated as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "numpy.pxd":227 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + __pyx_t_5 = __pyx_v_ndim; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "numpy.pxd":228 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); + + /* "numpy.pxd":229 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); + } + goto __pyx_L7; + } + /*else*/ { + + /* "numpy.pxd":231 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); + + /* "numpy.pxd":232 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); + } + __pyx_L7:; + + /* "numpy.pxd":233 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ + __pyx_v_info->suboffsets = NULL; + + /* "numpy.pxd":234 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); + + /* "numpy.pxd":235 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ + __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(__pyx_v_self)); + + /* "numpy.pxd":238 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ + __pyx_v_f = NULL; + + /* "numpy.pxd":239 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * cdef int offset + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self->descr)); + __pyx_v_descr = __pyx_v_self->descr; + + /* "numpy.pxd":243 + * cdef int offset + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * if not hasfields and not copy_shape: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "numpy.pxd":245 + * cdef bint hasfields = PyDataType_HASFIELDS(descr) + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_t_2 = (!__pyx_v_hasfields); + if (__pyx_t_2) { + __pyx_t_3 = (!__pyx_v_copy_shape); + __pyx_t_1 = __pyx_t_3; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":247 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L10; + } + /*else*/ { + + /* "numpy.pxd":250 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + } + __pyx_L10:; + + /* "numpy.pxd":252 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if ((descr.byteorder == '>' and little_endian) or + */ + __pyx_t_1 = (!__pyx_v_hasfields); + if (__pyx_t_1) { + + /* "numpy.pxd":253 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if ((descr.byteorder == '>' and little_endian) or + * (descr.byteorder == '<' and not little_endian)): + */ + __pyx_v_t = __pyx_v_descr->type_num; + + /* "numpy.pxd":254 + * if not hasfields: + * t = descr.type_num + * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); + if (__pyx_t_1) { + __pyx_t_2 = __pyx_v_little_endian; + } else { + __pyx_t_2 = __pyx_t_1; + } + if (!__pyx_t_2) { + + /* "numpy.pxd":255 + * t = descr.type_num + * if ((descr.byteorder == '>' and little_endian) or + * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + */ + __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); + if (__pyx_t_1) { + __pyx_t_3 = (!__pyx_v_little_endian); + __pyx_t_7 = __pyx_t_3; + } else { + __pyx_t_7 = __pyx_t_1; + } + __pyx_t_1 = __pyx_t_7; + } else { + __pyx_t_1 = __pyx_t_2; + } + if (__pyx_t_1) { + + /* "numpy.pxd":256 + * if ((descr.byteorder == '>' and little_endian) or + * (descr.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L12; + } + __pyx_L12:; + + /* "numpy.pxd":257 + * (descr.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + __pyx_t_1 = (__pyx_v_t == NPY_BYTE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__b; + goto __pyx_L13; + } + + /* "numpy.pxd":258 + * raise ValueError(u"Non-native byte order not supported") + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__B; + goto __pyx_L13; + } + + /* "numpy.pxd":259 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + __pyx_t_1 = (__pyx_v_t == NPY_SHORT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__h; + goto __pyx_L13; + } + + /* "numpy.pxd":260 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + __pyx_t_1 = (__pyx_v_t == NPY_USHORT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__H; + goto __pyx_L13; + } + + /* "numpy.pxd":261 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + __pyx_t_1 = (__pyx_v_t == NPY_INT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__i; + goto __pyx_L13; + } + + /* "numpy.pxd":262 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + __pyx_t_1 = (__pyx_v_t == NPY_UINT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__I; + goto __pyx_L13; + } + + /* "numpy.pxd":263 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + __pyx_t_1 = (__pyx_v_t == NPY_LONG); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__l; + goto __pyx_L13; + } + + /* "numpy.pxd":264 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + __pyx_t_1 = (__pyx_v_t == NPY_ULONG); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__L; + goto __pyx_L13; + } + + /* "numpy.pxd":265 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__q; + goto __pyx_L13; + } + + /* "numpy.pxd":266 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__Q; + goto __pyx_L13; + } + + /* "numpy.pxd":267 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__f; + goto __pyx_L13; + } + + /* "numpy.pxd":268 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__d; + goto __pyx_L13; + } + + /* "numpy.pxd":269 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__g; + goto __pyx_L13; + } + + /* "numpy.pxd":270 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__Zf; + goto __pyx_L13; + } + + /* "numpy.pxd":271 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__Zd; + goto __pyx_L13; + } + + /* "numpy.pxd":272 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__Zg; + goto __pyx_L13; + } + + /* "numpy.pxd":273 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); + if (__pyx_t_1) { + __pyx_v_f = __pyx_k__O; + goto __pyx_L13; + } + /*else*/ { + + /* "numpy.pxd":275 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_17), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = 0; + __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L13:; + + /* "numpy.pxd":276 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "numpy.pxd":277 + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":279 + * return + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< + * info.format[0] = '^' # Native data types, manual alignment + * offset = 0 + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "numpy.pxd":280 + * else: + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, + */ + (__pyx_v_info->format[0]) = '^'; + + /* "numpy.pxd":281 + * info.format = stdlib.malloc(_buffer_format_string_len) + * info.format[0] = '^' # Native data types, manual alignment + * offset = 0 # <<<<<<<<<<<<<< + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + */ + __pyx_v_offset = 0; + + /* "numpy.pxd":284 + * f = _util_dtypestring(descr, info.format + 1, + * info.format + _buffer_format_string_len, + * &offset) # <<<<<<<<<<<<<< + * f[0] = 0 # Terminate format string + * + */ + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_9; + + /* "numpy.pxd":285 + * info.format + _buffer_format_string_len, + * &offset) + * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + (__pyx_v_f[0]) = 0; + } + __pyx_L11:; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(Py_None); + __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; + } + __pyx_L2:; + __Pyx_XDECREF((PyObject *)__pyx_v_descr); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":287 + * f[0] = 0 # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__releasebuffer__", 0); + + /* "numpy.pxd":288 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_t_1 = PyArray_HASFIELDS(__pyx_v_self); + if (__pyx_t_1) { + + /* "numpy.pxd":289 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L3; + } + __pyx_L3:; + + /* "numpy.pxd":290 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + if (__pyx_t_1) { + + /* "numpy.pxd":291 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L4; + } + __pyx_L4:; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":767 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "numpy.pxd":768 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":770 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "numpy.pxd":771 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":773 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "numpy.pxd":774 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":776 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "numpy.pxd":777 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":779 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "numpy.pxd":780 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 780; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":782 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + +static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { + PyArray_Descr *__pyx_v_child = 0; + int __pyx_v_endian_detector; + int __pyx_v_little_endian; + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_childname = NULL; + PyObject *__pyx_v_new_offset = NULL; + PyObject *__pyx_v_t = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + long __pyx_t_10; + char *__pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_util_dtypestring", 0); + + /* "numpy.pxd":789 + * cdef int delta_offset + * cdef tuple i + * cdef int endian_detector = 1 # <<<<<<<<<<<<<< + * cdef bint little_endian = ((&endian_detector)[0] != 0) + * cdef tuple fields + */ + __pyx_v_endian_detector = 1; + + /* "numpy.pxd":790 + * cdef tuple i + * cdef int endian_detector = 1 + * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< + * cdef tuple fields + * + */ + __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); + + /* "numpy.pxd":793 + * cdef tuple fields + * + * for childname in descr.names: # <<<<<<<<<<<<<< + * fields = descr.fields[childname] + * child, new_offset = fields + */ + if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; + __Pyx_XDECREF(__pyx_v_childname); + __pyx_v_childname = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":794 + * + * for childname in descr.names: + * fields = descr.fields[childname] # <<<<<<<<<<<<<< + * child, new_offset = fields + * + */ + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); + __pyx_v_fields = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "numpy.pxd":795 + * for childname in descr.names: + * fields = descr.fields[childname] + * child, new_offset = fields # <<<<<<<<<<<<<< + * + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { + PyObject* sequence = ((PyObject *)__pyx_v_fields); + if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { + if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); + else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + } else { + __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF(((PyObject *)__pyx_v_child)); + __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_v_new_offset); + __pyx_v_new_offset = __pyx_t_4; + __pyx_t_4 = 0; + + /* "numpy.pxd":797 + * child, new_offset = fields + * + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + */ + __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + + /* "numpy.pxd":798 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == '>' and little_endian) or + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_19), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L5; + } + __pyx_L5:; + + /* "numpy.pxd":800 + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") + * + * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") + */ + __pyx_t_6 = (__pyx_v_child->byteorder == '>'); + if (__pyx_t_6) { + __pyx_t_7 = __pyx_v_little_endian; + } else { + __pyx_t_7 = __pyx_t_6; + } + if (!__pyx_t_7) { + + /* "numpy.pxd":801 + * + * if ((child.byteorder == '>' and little_endian) or + * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * raise ValueError(u"Non-native byte order not supported") + * # One could encode it in the format string and have Cython + */ + __pyx_t_6 = (__pyx_v_child->byteorder == '<'); + if (__pyx_t_6) { + __pyx_t_8 = (!__pyx_v_little_endian); + __pyx_t_9 = __pyx_t_8; + } else { + __pyx_t_9 = __pyx_t_6; + } + __pyx_t_6 = __pyx_t_9; + } else { + __pyx_t_6 = __pyx_t_7; + } + if (__pyx_t_6) { + + /* "numpy.pxd":802 + * if ((child.byteorder == '>' and little_endian) or + * (child.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_20), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; + } + __pyx_L6:; + + /* "numpy.pxd":812 + * + * # Output padding bytes + * while offset[0] < new_offset: # <<<<<<<<<<<<<< + * f[0] = 120 # "x"; pad byte + * f += 1 + */ + while (1) { + __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_6) break; + + /* "numpy.pxd":813 + * # Output padding bytes + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< + * f += 1 + * offset[0] += 1 + */ + (__pyx_v_f[0]) = 120; + + /* "numpy.pxd":814 + * while offset[0] < new_offset: + * f[0] = 120 # "x"; pad byte + * f += 1 # <<<<<<<<<<<<<< + * offset[0] += 1 + * + */ + __pyx_v_f = (__pyx_v_f + 1); + + /* "numpy.pxd":815 + * f[0] = 120 # "x"; pad byte + * f += 1 + * offset[0] += 1 # <<<<<<<<<<<<<< + * + * offset[0] += child.itemsize + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); + } + + /* "numpy.pxd":817 + * offset[0] += 1 + * + * offset[0] += child.itemsize # <<<<<<<<<<<<<< + * + * if not PyDataType_HASFIELDS(child): + */ + __pyx_t_10 = 0; + (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); + + /* "numpy.pxd":819 + * offset[0] += child.itemsize + * + * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< + * t = child.type_num + * if end - f < 5: + */ + __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); + if (__pyx_t_6) { + + /* "numpy.pxd":820 + * + * if not PyDataType_HASFIELDS(child): + * t = child.type_num # <<<<<<<<<<<<<< + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") + */ + __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 820; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_v_t); + __pyx_v_t = __pyx_t_3; + __pyx_t_3 = 0; + + /* "numpy.pxd":821 + * if not PyDataType_HASFIELDS(child): + * t = child.type_num + * if end - f < 5: # <<<<<<<<<<<<<< + * raise RuntimeError(u"Format string allocated too short.") + * + */ + __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); + if (__pyx_t_6) { + + /* "numpy.pxd":822 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_22), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L10; + } + __pyx_L10:; + + /* "numpy.pxd":825 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 98; + goto __pyx_L11; + } + + /* "numpy.pxd":826 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 66; + goto __pyx_L11; + } + + /* "numpy.pxd":827 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 104; + goto __pyx_L11; + } + + /* "numpy.pxd":828 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 72; + goto __pyx_L11; + } + + /* "numpy.pxd":829 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 105; + goto __pyx_L11; + } + + /* "numpy.pxd":830 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 73; + goto __pyx_L11; + } + + /* "numpy.pxd":831 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 108; + goto __pyx_L11; + } + + /* "numpy.pxd":832 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 76; + goto __pyx_L11; + } + + /* "numpy.pxd":833 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 113; + goto __pyx_L11; + } + + /* "numpy.pxd":834 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 81; + goto __pyx_L11; + } + + /* "numpy.pxd":835 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 102; + goto __pyx_L11; + } + + /* "numpy.pxd":836 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + */ + __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 100; + goto __pyx_L11; + } + + /* "numpy.pxd":837 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + */ + __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 103; + goto __pyx_L11; + } + + /* "numpy.pxd":838 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + */ + __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "numpy.pxd":839 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "numpy.pxd":840 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L11; + } + + /* "numpy.pxd":841 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_6) { + (__pyx_v_f[0]) = 79; + goto __pyx_L11; + } + /*else*/ { + + /* "numpy.pxd":843 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_17), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_5)); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); + __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); + __pyx_t_5 = 0; + __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_L11:; + + /* "numpy.pxd":844 + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * # Cython ignores struct boundary information ("T{...}"), + */ + __pyx_v_f = (__pyx_v_f + 1); + goto __pyx_L9; + } + /*else*/ { + + /* "numpy.pxd":848 + * # Cython ignores struct boundary information ("T{...}"), + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< + * return f + * + */ + __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 848; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_f = __pyx_t_11; + } + __pyx_L9:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "numpy.pxd":849 + * # so don't output it + * f = _util_dtypestring(child, f, end, offset) + * return f # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_f; + goto __pyx_L0; + + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_child); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_childname); + __Pyx_XDECREF(__pyx_v_new_offset); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "numpy.pxd":964 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + PyObject *__pyx_v_baseptr; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "numpy.pxd":966 + * cdef inline void set_array_base(ndarray arr, object base): + * cdef PyObject* baseptr + * if base is None: # <<<<<<<<<<<<<< + * baseptr = NULL + * else: + */ + __pyx_t_1 = (__pyx_v_base == Py_None); + if (__pyx_t_1) { + + /* "numpy.pxd":967 + * cdef PyObject* baseptr + * if base is None: + * baseptr = NULL # <<<<<<<<<<<<<< + * else: + * Py_INCREF(base) # important to do this before decref below! + */ + __pyx_v_baseptr = NULL; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":969 + * baseptr = NULL + * else: + * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< + * baseptr = base + * Py_XDECREF(arr.base) + */ + Py_INCREF(__pyx_v_base); + + /* "numpy.pxd":970 + * else: + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base # <<<<<<<<<<<<<< + * Py_XDECREF(arr.base) + * arr.base = baseptr + */ + __pyx_v_baseptr = ((PyObject *)__pyx_v_base); + } + __pyx_L3:; + + /* "numpy.pxd":971 + * Py_INCREF(base) # important to do this before decref below! + * baseptr = base + * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< + * arr.base = baseptr + * + */ + Py_XDECREF(__pyx_v_arr->base); + + /* "numpy.pxd":972 + * baseptr = base + * Py_XDECREF(arr.base) + * arr.base = baseptr # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + __pyx_v_arr->base = __pyx_v_baseptr; + + __Pyx_RefNannyFinishContext(); +} + +/* "numpy.pxd":974 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "numpy.pxd":975 + * + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: # <<<<<<<<<<<<<< + * return None + * else: + */ + __pyx_t_1 = (__pyx_v_arr->base == NULL); + if (__pyx_t_1) { + + /* "numpy.pxd":976 + * cdef inline object get_array_base(ndarray arr): + * if arr.base is NULL: + * return None # <<<<<<<<<<<<<< + * else: + * return arr.base + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_None); + __pyx_r = Py_None; + goto __pyx_L0; + goto __pyx_L3; + } + /*else*/ { + + /* "numpy.pxd":978 + * return None + * else: + * return arr.base # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); + __pyx_r = ((PyObject *)__pyx_v_arr->base); + goto __pyx_L0; + } + __pyx_L3:; + + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef __pyx_moduledef = { + PyModuleDef_HEAD_INIT, + __Pyx_NAMESTR("_traversal"), + __Pyx_DOCSTR(__pyx_k_23), /* m_doc */ + -1, /* m_size */ + __pyx_methods /* m_methods */, + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, + {&__pyx_kp_u_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 1, 0, 0}, + {&__pyx_kp_u_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 1, 0, 0}, + {&__pyx_kp_u_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 1, 0, 0}, + {&__pyx_kp_u_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 1, 0, 0}, + {&__pyx_kp_u_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 1, 0, 0}, + {&__pyx_n_s_24, __pyx_k_24, sizeof(__pyx_k_24), 0, 0, 1, 1}, + {&__pyx_n_s_27, __pyx_k_27, sizeof(__pyx_k_27), 0, 0, 1, 1}, + {&__pyx_kp_s_28, __pyx_k_28, sizeof(__pyx_k_28), 0, 0, 1, 0}, + {&__pyx_n_s_29, __pyx_k_29, sizeof(__pyx_k_29), 0, 0, 1, 1}, + {&__pyx_kp_s_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 0, 1, 0}, + {&__pyx_kp_u_38, __pyx_k_38, sizeof(__pyx_k_38), 0, 1, 0, 0}, + {&__pyx_kp_u_39, __pyx_k_39, sizeof(__pyx_k_39), 0, 1, 0, 0}, + {&__pyx_kp_u_40, __pyx_k_40, sizeof(__pyx_k_40), 0, 1, 0, 0}, + {&__pyx_kp_u_41, __pyx_k_41, sizeof(__pyx_k_41), 0, 1, 0, 0}, + {&__pyx_n_s__DTYPE, __pyx_k__DTYPE, sizeof(__pyx_k__DTYPE), 0, 0, 1, 1}, + {&__pyx_n_s__ITYPE, __pyx_k__ITYPE, sizeof(__pyx_k__ITYPE), 0, 0, 1, 1}, + {&__pyx_n_s__N, __pyx_k__N, sizeof(__pyx_k__N), 0, 0, 1, 1}, + {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s__T, __pyx_k__T, sizeof(__pyx_k__T), 0, 0, 1, 1}, + {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, + {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, + {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, + {&__pyx_n_s___graph_tools, __pyx_k___graph_tools, sizeof(__pyx_k___graph_tools), 0, 0, 1, 1}, + {&__pyx_n_s___graph_validation, __pyx_k___graph_validation, sizeof(__pyx_k___graph_validation), 0, 0, 1, 1}, + {&__pyx_n_s__breadth_first_order, __pyx_k__breadth_first_order, sizeof(__pyx_k__breadth_first_order), 0, 0, 1, 1}, + {&__pyx_n_s__breadth_first_tree, __pyx_k__breadth_first_tree, sizeof(__pyx_k__breadth_first_tree), 0, 0, 1, 1}, + {&__pyx_n_s__connection, __pyx_k__connection, sizeof(__pyx_k__connection), 0, 0, 1, 1}, + {&__pyx_n_s__csgraph, __pyx_k__csgraph, sizeof(__pyx_k__csgraph), 0, 0, 1, 1}, + {&__pyx_n_s__csgraph_T, __pyx_k__csgraph_T, sizeof(__pyx_k__csgraph_T), 0, 0, 1, 1}, + {&__pyx_n_s__csr_matrix, __pyx_k__csr_matrix, sizeof(__pyx_k__csr_matrix), 0, 0, 1, 1}, + {&__pyx_n_s__dense_output, __pyx_k__dense_output, sizeof(__pyx_k__dense_output), 0, 0, 1, 1}, + {&__pyx_n_s__depth_first_order, __pyx_k__depth_first_order, sizeof(__pyx_k__depth_first_order), 0, 0, 1, 1}, + {&__pyx_n_s__depth_first_tree, __pyx_k__depth_first_tree, sizeof(__pyx_k__depth_first_tree), 0, 0, 1, 1}, + {&__pyx_n_s__directed, __pyx_k__directed, sizeof(__pyx_k__directed), 0, 0, 1, 1}, + {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, + {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, + {&__pyx_n_s__fill, __pyx_k__fill, sizeof(__pyx_k__fill), 0, 0, 1, 1}, + {&__pyx_n_s__flag, __pyx_k__flag, sizeof(__pyx_k__flag), 0, 0, 1, 1}, + {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, + {&__pyx_n_s__i_start, __pyx_k__i_start, sizeof(__pyx_k__i_start), 0, 0, 1, 1}, + {&__pyx_n_s__indices, __pyx_k__indices, sizeof(__pyx_k__indices), 0, 0, 1, 1}, + {&__pyx_n_s__indptr, __pyx_k__indptr, sizeof(__pyx_k__indptr), 0, 0, 1, 1}, + {&__pyx_n_s__int32, __pyx_k__int32, sizeof(__pyx_k__int32), 0, 0, 1, 1}, + {&__pyx_n_s__isspmatrix, __pyx_k__isspmatrix, sizeof(__pyx_k__isspmatrix), 0, 0, 1, 1}, + {&__pyx_n_s__isspmatrix_csc, __pyx_k__isspmatrix_csc, sizeof(__pyx_k__isspmatrix_csc), 0, 0, 1, 1}, + {&__pyx_n_s__isspmatrix_csr, __pyx_k__isspmatrix_csr, sizeof(__pyx_k__isspmatrix_csr), 0, 0, 1, 1}, + {&__pyx_n_s__labels, __pyx_k__labels, sizeof(__pyx_k__labels), 0, 0, 1, 1}, + {&__pyx_n_s__length, __pyx_k__length, sizeof(__pyx_k__length), 0, 0, 1, 1}, + {&__pyx_n_s__lower, __pyx_k__lower, sizeof(__pyx_k__lower), 0, 0, 1, 1}, + {&__pyx_n_s__n_components, __pyx_k__n_components, sizeof(__pyx_k__n_components), 0, 0, 1, 1}, + {&__pyx_n_s__node_list, __pyx_k__node_list, sizeof(__pyx_k__node_list), 0, 0, 1, 1}, + {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, + {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, + {&__pyx_n_s__predecessors, __pyx_k__predecessors, sizeof(__pyx_k__predecessors), 0, 0, 1, 1}, + {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, + {&__pyx_n_s__reconstruct_path, __pyx_k__reconstruct_path, sizeof(__pyx_k__reconstruct_path), 0, 0, 1, 1}, + {&__pyx_n_s__return_labels, __pyx_k__return_labels, sizeof(__pyx_k__return_labels), 0, 0, 1, 1}, + {&__pyx_n_s__return_predecessors, __pyx_k__return_predecessors, sizeof(__pyx_k__return_predecessors), 0, 0, 1, 1}, + {&__pyx_n_s__root_list, __pyx_k__root_list, sizeof(__pyx_k__root_list), 0, 0, 1, 1}, + {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, + {&__pyx_n_s__strong, __pyx_k__strong, sizeof(__pyx_k__strong), 0, 0, 1, 1}, + {&__pyx_n_s__tocsr, __pyx_k__tocsr, sizeof(__pyx_k__tocsr), 0, 0, 1, 1}, + {&__pyx_n_s__validate_graph, __pyx_k__validate_graph, sizeof(__pyx_k__validate_graph), 0, 0, 1, 1}, + {&__pyx_n_s__weak, __pyx_k__weak, sizeof(__pyx_k__weak), 0, 0, 1, 1}, + {&__pyx_n_s__zeros, __pyx_k__zeros, sizeof(__pyx_k__zeros), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 633; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + return 0; + __pyx_L1_error:; + return -1; +} + +static int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "sklearn/utils/mst/_traversal.pyx":69 + * """ + * if connection.lower() not in ['weak', 'strong']: + * raise ValueError("connection must be 'weak' or 'strong'") # <<<<<<<<<<<<<< + * + * # weak connections <=> components of undirected graph + */ + __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_4); + __Pyx_INCREF(((PyObject *)__pyx_kp_s_3)); + PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_s_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_s_3)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); + + /* "numpy.pxd":214 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_12); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); + PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_11)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + + /* "numpy.pxd":218 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_k_tuple_14 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_14); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_13)); + PyTuple_SET_ITEM(__pyx_k_tuple_14, 0, ((PyObject *)__pyx_kp_u_13)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_13)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); + + /* "numpy.pxd":256 + * if ((descr.byteorder == '>' and little_endian) or + * (descr.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_k_tuple_16 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_16); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_15)); + PyTuple_SET_ITEM(__pyx_k_tuple_16, 0, ((PyObject *)__pyx_kp_u_15)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_15)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); + + /* "numpy.pxd":798 + * + * if (end - f) - (new_offset - offset[0]) < 15: + * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< + * + * if ((child.byteorder == '>' and little_endian) or + */ + __pyx_k_tuple_19 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_19)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_19); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_18)); + PyTuple_SET_ITEM(__pyx_k_tuple_19, 0, ((PyObject *)__pyx_kp_u_18)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_18)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_19)); + + /* "numpy.pxd":802 + * if ((child.byteorder == '>' and little_endian) or + * (child.byteorder == '<' and not little_endian)): + * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< + * # One could encode it in the format string and have Cython + * # complain instead, BUT: < and > in format strings also imply + */ + __pyx_k_tuple_20 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_20)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_20); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_15)); + PyTuple_SET_ITEM(__pyx_k_tuple_20, 0, ((PyObject *)__pyx_kp_u_15)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_15)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_20)); + + /* "numpy.pxd":822 + * t = child.type_num + * if end - f < 5: + * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_k_tuple_22 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_22)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_22); + __Pyx_INCREF(((PyObject *)__pyx_kp_u_21)); + PyTuple_SET_ITEM(__pyx_k_tuple_22, 0, ((PyObject *)__pyx_kp_u_21)); + __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_21)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_22)); + + /* "sklearn/utils/mst/_traversal.pyx":30 + * cdef ITYPE_t NULL_IDX = -9999 + * + * def connected_components(csgraph, directed=True, connection='weak', # <<<<<<<<<<<<<< + * return_labels=True): + * """ + */ + __pyx_k_tuple_25 = PyTuple_New(7); if (unlikely(!__pyx_k_tuple_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_25); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csgraph)); + PyTuple_SET_ITEM(__pyx_k_tuple_25, 0, ((PyObject *)__pyx_n_s__csgraph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csgraph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__directed)); + PyTuple_SET_ITEM(__pyx_k_tuple_25, 1, ((PyObject *)__pyx_n_s__directed)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__directed)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__connection)); + PyTuple_SET_ITEM(__pyx_k_tuple_25, 2, ((PyObject *)__pyx_n_s__connection)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__connection)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__return_labels)); + PyTuple_SET_ITEM(__pyx_k_tuple_25, 3, ((PyObject *)__pyx_n_s__return_labels)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__return_labels)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__labels)); + PyTuple_SET_ITEM(__pyx_k_tuple_25, 4, ((PyObject *)__pyx_n_s__labels)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__labels)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__n_components)); + PyTuple_SET_ITEM(__pyx_k_tuple_25, 5, ((PyObject *)__pyx_n_s__n_components)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__n_components)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csgraph_T)); + PyTuple_SET_ITEM(__pyx_k_tuple_25, 6, ((PyObject *)__pyx_n_s__csgraph_T)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csgraph_T)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_25)); + __pyx_k_codeobj_26 = (PyObject*)__Pyx_PyCode_New(4, 0, 7, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_25, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_28, __pyx_n_s_27, 30, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_26)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":99 + * + * + * def breadth_first_tree(csgraph, i_start, directed=True): # <<<<<<<<<<<<<< + * r""" + * breadth_first_tree(csgraph, i_start, directed=True) + */ + __pyx_k_tuple_30 = PyTuple_New(5); if (unlikely(!__pyx_k_tuple_30)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_30); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csgraph)); + PyTuple_SET_ITEM(__pyx_k_tuple_30, 0, ((PyObject *)__pyx_n_s__csgraph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csgraph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__i_start)); + PyTuple_SET_ITEM(__pyx_k_tuple_30, 1, ((PyObject *)__pyx_n_s__i_start)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i_start)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__directed)); + PyTuple_SET_ITEM(__pyx_k_tuple_30, 2, ((PyObject *)__pyx_n_s__directed)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__directed)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__node_list)); + PyTuple_SET_ITEM(__pyx_k_tuple_30, 3, ((PyObject *)__pyx_n_s__node_list)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__node_list)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__predecessors)); + PyTuple_SET_ITEM(__pyx_k_tuple_30, 4, ((PyObject *)__pyx_n_s__predecessors)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__predecessors)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_30)); + __pyx_k_codeobj_31 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_30, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_28, __pyx_n_s__breadth_first_tree, 99, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_31)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":169 + * + * + * def depth_first_tree(csgraph, i_start, directed=True): # <<<<<<<<<<<<<< + * r""" + * depth_first_tree(csgraph, i_start, directed=True) + */ + __pyx_k_tuple_32 = PyTuple_New(5); if (unlikely(!__pyx_k_tuple_32)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_32); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csgraph)); + PyTuple_SET_ITEM(__pyx_k_tuple_32, 0, ((PyObject *)__pyx_n_s__csgraph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csgraph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__i_start)); + PyTuple_SET_ITEM(__pyx_k_tuple_32, 1, ((PyObject *)__pyx_n_s__i_start)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i_start)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__directed)); + PyTuple_SET_ITEM(__pyx_k_tuple_32, 2, ((PyObject *)__pyx_n_s__directed)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__directed)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__node_list)); + PyTuple_SET_ITEM(__pyx_k_tuple_32, 3, ((PyObject *)__pyx_n_s__node_list)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__node_list)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__predecessors)); + PyTuple_SET_ITEM(__pyx_k_tuple_32, 4, ((PyObject *)__pyx_n_s__predecessors)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__predecessors)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_32)); + __pyx_k_codeobj_33 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_32, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_28, __pyx_n_s__depth_first_tree, 169, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_33)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":243 + * + * + * def breadth_first_order(csgraph, i_start, # <<<<<<<<<<<<<< + * directed=True, return_predecessors=True): + * """ + */ + __pyx_k_tuple_34 = PyTuple_New(9); if (unlikely(!__pyx_k_tuple_34)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_34); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csgraph)); + PyTuple_SET_ITEM(__pyx_k_tuple_34, 0, ((PyObject *)__pyx_n_s__csgraph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csgraph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__i_start)); + PyTuple_SET_ITEM(__pyx_k_tuple_34, 1, ((PyObject *)__pyx_n_s__i_start)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i_start)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__directed)); + PyTuple_SET_ITEM(__pyx_k_tuple_34, 2, ((PyObject *)__pyx_n_s__directed)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__directed)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__return_predecessors)); + PyTuple_SET_ITEM(__pyx_k_tuple_34, 3, ((PyObject *)__pyx_n_s__return_predecessors)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__return_predecessors)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__N)); + PyTuple_SET_ITEM(__pyx_k_tuple_34, 4, ((PyObject *)__pyx_n_s__N)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__N)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__node_list)); + PyTuple_SET_ITEM(__pyx_k_tuple_34, 5, ((PyObject *)__pyx_n_s__node_list)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__node_list)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__predecessors)); + PyTuple_SET_ITEM(__pyx_k_tuple_34, 6, ((PyObject *)__pyx_n_s__predecessors)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__predecessors)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__length)); + PyTuple_SET_ITEM(__pyx_k_tuple_34, 7, ((PyObject *)__pyx_n_s__length)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__length)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csgraph_T)); + PyTuple_SET_ITEM(__pyx_k_tuple_34, 8, ((PyObject *)__pyx_n_s__csgraph_T)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csgraph_T)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_34)); + __pyx_k_codeobj_35 = (PyObject*)__Pyx_PyCode_New(4, 0, 9, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_34, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_28, __pyx_n_s__breadth_first_order, 243, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_35)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "sklearn/utils/mst/_traversal.pyx":407 + * + * + * def depth_first_order(csgraph, i_start, # <<<<<<<<<<<<<< + * directed=True, return_predecessors=True): + * """ + */ + __pyx_k_tuple_36 = PyTuple_New(11); if (unlikely(!__pyx_k_tuple_36)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_k_tuple_36); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csgraph)); + PyTuple_SET_ITEM(__pyx_k_tuple_36, 0, ((PyObject *)__pyx_n_s__csgraph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csgraph)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__i_start)); + PyTuple_SET_ITEM(__pyx_k_tuple_36, 1, ((PyObject *)__pyx_n_s__i_start)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__i_start)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__directed)); + PyTuple_SET_ITEM(__pyx_k_tuple_36, 2, ((PyObject *)__pyx_n_s__directed)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__directed)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__return_predecessors)); + PyTuple_SET_ITEM(__pyx_k_tuple_36, 3, ((PyObject *)__pyx_n_s__return_predecessors)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__return_predecessors)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__N)); + PyTuple_SET_ITEM(__pyx_k_tuple_36, 4, ((PyObject *)__pyx_n_s__N)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__N)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__node_list)); + PyTuple_SET_ITEM(__pyx_k_tuple_36, 5, ((PyObject *)__pyx_n_s__node_list)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__node_list)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__predecessors)); + PyTuple_SET_ITEM(__pyx_k_tuple_36, 6, ((PyObject *)__pyx_n_s__predecessors)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__predecessors)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__root_list)); + PyTuple_SET_ITEM(__pyx_k_tuple_36, 7, ((PyObject *)__pyx_n_s__root_list)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__root_list)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__flag)); + PyTuple_SET_ITEM(__pyx_k_tuple_36, 8, ((PyObject *)__pyx_n_s__flag)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__flag)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__length)); + PyTuple_SET_ITEM(__pyx_k_tuple_36, 9, ((PyObject *)__pyx_n_s__length)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__length)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csgraph_T)); + PyTuple_SET_ITEM(__pyx_k_tuple_36, 10, ((PyObject *)__pyx_n_s__csgraph_T)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csgraph_T)); + __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_36)); + __pyx_k_codeobj_37 = (PyObject*)__Pyx_PyCode_New(4, 0, 11, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_36, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_28, __pyx_n_s__depth_first_order, 407, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_37)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + return 0; + __pyx_L1_error:; + return -1; +} + +#if PY_MAJOR_VERSION < 3 +PyMODINIT_FUNC init_traversal(void); /*proto*/ +PyMODINIT_FUNC init_traversal(void) +#else +PyMODINIT_FUNC PyInit__traversal(void); /*proto*/ +PyMODINIT_FUNC PyInit__traversal(void) +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + __Pyx_RefNannyDeclarations + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__traversal(void)", 0); + if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #endif + /*--- Module creation code ---*/ + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_traversal"), __pyx_methods, __Pyx_DOCSTR(__pyx_k_23), 0, PYTHON_API_VERSION); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + #if PY_MAJOR_VERSION < 3 + Py_INCREF(__pyx_m); + #endif + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); + if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*--- Initialize various global constants etc. ---*/ + if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_module_is_main_sklearn__utils__mst___traversal) { + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + /*--- Builtin init code ---*/ + if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Constants init code ---*/ + if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Global init code ---*/ + /*--- Variable export code ---*/ + /*--- Function export code ---*/ + /*--- Type init code ---*/ + /*--- Type import code ---*/ + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 860; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*--- Variable import code ---*/ + /*--- Function import code ---*/ + /*--- Execution code ---*/ + + /* "sklearn/utils/mst/_traversal.pyx":8 + * # License: BSD, (C) 2012 + * + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * + */ + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":11 + * cimport numpy as np + * + * from scipy.sparse import csr_matrix, isspmatrix, isspmatrix_csr, isspmatrix_csc # <<<<<<<<<<<<<< + * from ._graph_validation import validate_graph + * from ._graph_tools import reconstruct_path + */ + __pyx_t_1 = PyList_New(4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_n_s__csr_matrix)); + PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s__csr_matrix)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__csr_matrix)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__isspmatrix)); + PyList_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_n_s__isspmatrix)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__isspmatrix)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__isspmatrix_csr)); + PyList_SET_ITEM(__pyx_t_1, 2, ((PyObject *)__pyx_n_s__isspmatrix_csr)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__isspmatrix_csr)); + __Pyx_INCREF(((PyObject *)__pyx_n_s__isspmatrix_csc)); + PyList_SET_ITEM(__pyx_t_1, 3, ((PyObject *)__pyx_n_s__isspmatrix_csc)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__isspmatrix_csc)); + __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s_24), ((PyObject *)__pyx_t_1), -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__csr_matrix); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__csr_matrix); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__csr_matrix, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isspmatrix); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__isspmatrix); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__isspmatrix, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isspmatrix_csr); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__isspmatrix_csr); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__isspmatrix_csr, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__isspmatrix_csc); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__isspmatrix_csc); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__isspmatrix_csc, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":12 + * + * from scipy.sparse import csr_matrix, isspmatrix, isspmatrix_csr, isspmatrix_csc + * from ._graph_validation import validate_graph # <<<<<<<<<<<<<< + * from ._graph_tools import reconstruct_path + * + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(((PyObject *)__pyx_n_s__validate_graph)); + PyList_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_n_s__validate_graph)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__validate_graph)); + __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s___graph_validation), ((PyObject *)__pyx_t_2), 1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__validate_graph); + if (__pyx_t_2 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__validate_graph); + if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__validate_graph, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":13 + * from scipy.sparse import csr_matrix, isspmatrix, isspmatrix_csr, isspmatrix_csc + * from ._graph_validation import validate_graph + * from ._graph_tools import reconstruct_path # <<<<<<<<<<<<<< + * + * cimport cython + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_n_s__reconstruct_path)); + PyList_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_n_s__reconstruct_path)); + __Pyx_GIVEREF(((PyObject *)__pyx_n_s__reconstruct_path)); + __pyx_t_2 = __Pyx_Import(((PyObject *)__pyx_n_s___graph_tools), ((PyObject *)__pyx_t_1), 1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__reconstruct_path); + if (__pyx_t_1 == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) __Pyx_RaiseImportError(__pyx_n_s__reconstruct_path); + if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __Pyx_GOTREF(__pyx_t_1); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__reconstruct_path, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":18 + * from libc cimport stdlib + * + * DTYPE = np.float64 # <<<<<<<<<<<<<< + * ctypedef np.float64_t DTYPE_t + * + */ + __pyx_t_2 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__DTYPE, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":21 + * ctypedef np.float64_t DTYPE_t + * + * ITYPE = np.int32 # <<<<<<<<<<<<<< + * ctypedef np.int32_t ITYPE_t + * + */ + __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__int32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__ITYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":25 + * + * # EPS is the precision of DTYPE + * cdef DTYPE_t DTYPE_EPS = 1E-15 # <<<<<<<<<<<<<< + * + * # NULL_IDX is the index used in predecessor matrices to store a non-path + */ + __pyx_v_7sklearn_5utils_3mst_10_traversal_DTYPE_EPS = 1E-15; + + /* "sklearn/utils/mst/_traversal.pyx":28 + * + * # NULL_IDX is the index used in predecessor matrices to store a non-path + * cdef ITYPE_t NULL_IDX = -9999 # <<<<<<<<<<<<<< + * + * def connected_components(csgraph, directed=True, connection='weak', + */ + __pyx_v_7sklearn_5utils_3mst_10_traversal_NULL_IDX = -9999; + + /* "sklearn/utils/mst/_traversal.pyx":30 + * cdef ITYPE_t NULL_IDX = -9999 + * + * def connected_components(csgraph, directed=True, connection='weak', # <<<<<<<<<<<<<< + * return_labels=True): + * """ + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_1 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":31 + * + * def connected_components(csgraph, directed=True, connection='weak', + * return_labels=True): # <<<<<<<<<<<<<< + * """ + * connected_components(csgraph, directed=True, connection='weak', + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_2 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":30 + * cdef ITYPE_t NULL_IDX = -9999 + * + * def connected_components(csgraph, directed=True, connection='weak', # <<<<<<<<<<<<<< + * return_labels=True): + * """ + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_3mst_10_traversal_1connected_components, NULL, __pyx_n_s_29); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_27, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":99 + * + * + * def breadth_first_tree(csgraph, i_start, directed=True): # <<<<<<<<<<<<<< + * r""" + * breadth_first_tree(csgraph, i_start, directed=True) + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_5 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_3mst_10_traversal_3breadth_first_tree, NULL, __pyx_n_s_29); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__breadth_first_tree, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":169 + * + * + * def depth_first_tree(csgraph, i_start, directed=True): # <<<<<<<<<<<<<< + * r""" + * depth_first_tree(csgraph, i_start, directed=True) + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_6 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_3mst_10_traversal_5depth_first_tree, NULL, __pyx_n_s_29); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__depth_first_tree, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":244 + * + * def breadth_first_order(csgraph, i_start, + * directed=True, return_predecessors=True): # <<<<<<<<<<<<<< + * """ + * breadth_first_order(csgraph, i_start, directed=True, return_predecessors=True) + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_7 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_8 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":243 + * + * + * def breadth_first_order(csgraph, i_start, # <<<<<<<<<<<<<< + * directed=True, return_predecessors=True): + * """ + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_3mst_10_traversal_7breadth_first_order, NULL, __pyx_n_s_29); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__breadth_first_order, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":408 + * + * def depth_first_order(csgraph, i_start, + * directed=True, return_predecessors=True): # <<<<<<<<<<<<<< + * """ + * depth_first_order(csgraph, i_start, directed=True, return_predecessors=True) + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_9 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_k_10 = __pyx_t_2; + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":407 + * + * + * def depth_first_order(csgraph, i_start, # <<<<<<<<<<<<<< + * directed=True, return_predecessors=True): + * """ + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7sklearn_5utils_3mst_10_traversal_9depth_first_order, NULL, __pyx_n_s_29); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + if (PyObject_SetAttr(__pyx_m, __pyx_n_s__depth_first_order, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "sklearn/utils/mst/_traversal.pyx":1 + * """ # <<<<<<<<<<<<<< + * Routines for traversing graphs in compressed sparse format + * """ + */ + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(((PyObject *)__pyx_t_2)); + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_kp_u_38), ((PyObject *)__pyx_kp_u_39)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_kp_u_40), ((PyObject *)__pyx_kp_u_41)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; + + /* "numpy.pxd":974 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + __Pyx_AddTraceback("init sklearn.utils.mst._traversal", __pyx_clineno, __pyx_lineno, __pyx_filename); + Py_DECREF(__pyx_m); __pyx_m = 0; + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init sklearn.utils.mst._traversal"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if PY_MAJOR_VERSION < 3 + return; + #else + return __pyx_m; + #endif +} + +/* Runtime support code */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule((char *)modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + +static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { + PyObject *result; + result = PyObject_GetAttr(dict, name); + if (!result) { + if (dict != __pyx_b) { + PyErr_Clear(); + result = PyObject_GetAttr(__pyx_b, name); + } + if (!result) { + PyErr_SetObject(PyExc_NameError, name); + } + } + return result; +} + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AS_STRING(kw_name)); + #endif +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + } else { + #if PY_MAJOR_VERSION < 3 + if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { + #else + if (unlikely(!PyUnicode_Check(key))) { + #endif + goto invalid_keyword_type; + } else { + for (name = first_kw_arg; *name; name++) { + #if PY_MAJOR_VERSION >= 3 + if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && + PyUnicode_Compare(**name, key) == 0) break; + #else + if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && + _PyString_Eq(**name, key)) break; + #endif + } + if (*name) { + values[name-argnames] = value; + } else { + for (name=argnames; name != first_kw_arg; name++) { + if (**name == key) goto arg_passed_twice; + #if PY_MAJOR_VERSION >= 3 + if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && + PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; + #else + if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && + _PyString_Eq(**name, key)) goto arg_passed_twice; + #endif + } + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + } + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, **name); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(type, value, tb); +#endif +} + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + Py_XINCREF(type); + Py_XINCREF(value); + Py_XINCREF(tb); + if (tb == Py_None) { + Py_DECREF(tb); + tb = 0; + } + else if (tb != NULL && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + if (value == NULL) { + value = Py_None; + Py_INCREF(value); + } + #if PY_VERSION_HEX < 0x02050000 + if (!PyClass_Check(type)) + #else + if (!PyType_Check(type)) + #endif + { + if (value != Py_None) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + Py_DECREF(value); + value = type; + #if PY_VERSION_HEX < 0x02050000 + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; + Py_INCREF(type); + } + else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + #endif + } + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else /* Python 3+ */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (!PyExceptionClass_Check(type)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } + else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } + else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + if (!value) { + value = PyObject_CallObject(type, NULL); + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } + } +bad: + return; +} +#endif + + + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_Format(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", + index, (index == 1) ? "" : "s"); +} + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); +} + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else if (PyErr_Occurred()) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +} + +static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { + unsigned int n = 1; + return *(unsigned char*)(&n) != 0; +} +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'b': return "'char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; /* Consume from buffer string */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + if (isspace(*ts)) + continue; + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case 10: + case 13: + ++ts; + break; + case '<': + if (!__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_IsLittleEndian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } /* fall through */ + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 's': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + } else { + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + } + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} +static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { + buf->buf = NULL; + buf->obj = NULL; + buf->strides = __Pyx_zeros; + buf->shape = __Pyx_zeros; + buf->suboffsets = __Pyx_minusones; +} +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ + if (obj == Py_None || obj == NULL) { + __Pyx_ZeroBuffer(buf); + return 0; + } + buf->buf = NULL; + if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; + if (buf->ndim != nd) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + nd, buf->ndim); + goto fail; + } + if (!cast) { + __Pyx_BufFmt_Context ctx; + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((unsigned)buf->itemsize != dtype->size) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + buf->itemsize, (buf->itemsize > 1) ? "s" : "", + dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; + return 0; +fail:; + __Pyx_ZeroBuffer(buf); + return -1; +} +static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { + if (info->buf == NULL) return; + if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; + __Pyx_ReleaseBuffer(info); +} + +static void __Pyx_RaiseBufferIndexError(int axis) { + PyErr_Format(PyExc_IndexError, + "Out of bounds on buffer access (axis %d)", axis); +} + +static void __Pyx_RaiseBufferFallbackError(void) { + PyErr_Format(PyExc_ValueError, + "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +} + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { + if (t == Py_None) { + __Pyx_RaiseNoneNotIterableError(); + } else if (PyTuple_GET_SIZE(t) < index) { + __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); + } else { + __Pyx_RaiseTooManyValuesError(index); + } +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + PyObject *getbuffer_cobj; + + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + #endif + + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict && + (getbuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, + "__pyx_getbuffer"))) { + getbufferproc func; + + #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + func = (getbufferproc) PyCapsule_GetPointer(getbuffer_cobj, "getbuffer(obj, view, flags)"); + #else + func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + #endif + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + + return func(obj, view, flags); + } else { + PyErr_Clear(); + } + #endif + + PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); + +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + + return -1; +} + +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + PyObject *releasebuffer_cobj; + + if (!obj) return; + + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict && + (releasebuffer_cobj = PyMapping_GetItemString(obj->ob_type->tp_dict, + "__pyx_releasebuffer"))) { + releasebufferproc func; + + #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0) + func = (releasebufferproc) PyCapsule_GetPointer(releasebuffer_cobj, "releasebuffer(obj, view)"); + #else + func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + #endif + + Py_DECREF(releasebuffer_cobj); + + if (!func) + goto fail; + + func(obj, view); + return; + } else { + PyErr_Clear(); + } + #endif + + goto nofail; + +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); + +nofail: + Py_DECREF(obj); + view->obj = NULL; +} + +#endif /* PY_MAJOR_VERSION < 3 */ + + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { + PyObject *py_import = 0; + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); + if (!py_import) + goto bad; + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + #if PY_VERSION_HEX >= 0x02050000 + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + /* try package relative import first */ + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + } + } + #else + if (level>0) { + PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); + goto bad; + } + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, NULL); + #endif +bad: + Py_XDECREF(empty_list); + Py_XDECREF(py_import); + Py_XDECREF(empty_dict); + return module; +} + +static CYTHON_INLINE void __Pyx_RaiseImportError(PyObject *name) { +#if PY_MAJOR_VERSION < 3 + PyErr_Format(PyExc_ImportError, "cannot import name %.230s", + PyString_AsString(name)); +#else + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); +#endif +} + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + if (PyBytes_GET_SIZE(s1) != PyBytes_GET_SIZE(s2)) { + return (equals == Py_NE); + } else if (PyBytes_GET_SIZE(s1) == 1) { + if (equals == Py_EQ) + return (PyBytes_AS_STRING(s1)[0] == PyBytes_AS_STRING(s2)[0]); + else + return (PyBytes_AS_STRING(s1)[0] != PyBytes_AS_STRING(s2)[0]); + } else { + int result = memcmp(PyBytes_AS_STRING(s1), PyBytes_AS_STRING(s2), (size_t)PyBytes_GET_SIZE(s1)); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +} + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyUnicode_CheckExact(s1) & PyUnicode_CheckExact(s2)) { + #if CYTHON_PEP393_ENABLED + if ((PyUnicode_READY(s1) < 0) || (PyUnicode_READY(s2) < 0)) + return -1; + if (PyUnicode_GET_LENGTH(s1) != PyUnicode_GET_LENGTH(s2)) { + return (equals == Py_NE); + } else if (PyUnicode_GET_LENGTH(s1) == 1) { + Py_UCS4 ch1 = PyUnicode_READ_CHAR(s1, 0); + Py_UCS4 ch2 = PyUnicode_READ_CHAR(s2, 0); + return (equals == Py_EQ) ? (ch1 == ch2) : (ch1 != ch2); + #else + if (PyUnicode_GET_SIZE(s1) != PyUnicode_GET_SIZE(s2)) { + return (equals == Py_NE); + } else if (PyUnicode_GET_SIZE(s1) == 1) { + Py_UNICODE ch1 = PyUnicode_AS_UNICODE(s1)[0]; + Py_UNICODE ch2 = PyUnicode_AS_UNICODE(s2)[0]; + return (equals == Py_EQ) ? (ch1 == ch2) : (ch1 != ch2); + #endif + } else { + int result = PyUnicode_Compare(s1, s2); + if ((result == -1) && unlikely(PyErr_Occurred())) + return -1; + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyUnicode_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyUnicode_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +} + +static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_int32(npy_int32 val) { + const npy_int32 neg_one = (npy_int32)-1, const_zero = (npy_int32)0; + const int is_unsigned = const_zero < neg_one; + if ((sizeof(npy_int32) == sizeof(char)) || + (sizeof(npy_int32) == sizeof(short))) { + return PyInt_FromLong((long)val); + } else if ((sizeof(npy_int32) == sizeof(int)) || + (sizeof(npy_int32) == sizeof(long))) { + if (is_unsigned) + return PyLong_FromUnsignedLong((unsigned long)val); + else + return PyInt_FromLong((long)val); + } else if (sizeof(npy_int32) == sizeof(PY_LONG_LONG)) { + if (is_unsigned) + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); + else + return PyLong_FromLongLong((PY_LONG_LONG)val); + } else { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + return _PyLong_FromByteArray(bytes, sizeof(npy_int32), + little, !is_unsigned); + } +} + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(a, a); + case 3: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, a); + case 4: + z = __Pyx_c_prodf(a, a); + return __Pyx_c_prodf(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_absf(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double denom = b.real * b.real + b.imag * b.imag; + z.real = (a.real * b.real + a.imag * b.imag) / denom; + z.imag = (a.imag * b.real - a.real * b.imag) / denom; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(a, a); + case 3: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, a); + case 4: + z = __Pyx_c_prod(a, a); + return __Pyx_c_prod(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } + r = a.real; + theta = 0; + } else { + r = __Pyx_c_abs(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { + const unsigned char neg_one = (unsigned char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned char" : + "value too large to convert to unsigned char"); + } + return (unsigned char)-1; + } + return (unsigned char)val; + } + return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { + const unsigned short neg_one = (unsigned short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned short" : + "value too large to convert to unsigned short"); + } + return (unsigned short)-1; + } + return (unsigned short)val; + } + return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { + const unsigned int neg_one = (unsigned int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(unsigned int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(unsigned int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to unsigned int" : + "value too large to convert to unsigned int"); + } + return (unsigned int)-1; + } + return (unsigned int)val; + } + return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); +} + +static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { + const char neg_one = (char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to char" : + "value too large to convert to char"); + } + return (char)-1; + } + return (char)val; + } + return (char)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { + const short neg_one = (short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to short" : + "value too large to convert to short"); + } + return (short)-1; + } + return (short)val; + } + return (short)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { + const signed char neg_one = (signed char)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed char) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed char)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed char" : + "value too large to convert to signed char"); + } + return (signed char)-1; + } + return (signed char)val; + } + return (signed char)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { + const signed short neg_one = (signed short)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed short) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed short)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed short" : + "value too large to convert to signed short"); + } + return (signed short)-1; + } + return (signed short)val; + } + return (signed short)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { + const signed int neg_one = (signed int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(signed int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(signed int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to signed int" : + "value too large to convert to signed int"); + } + return (signed int)-1; + } + return (signed int)val; + } + return (signed int)__Pyx_PyInt_AsSignedLong(x); +} + +static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { + const int neg_one = (int)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (sizeof(int) < sizeof(long)) { + long val = __Pyx_PyInt_AsLong(x); + if (unlikely(val != (long)(int)val)) { + if (!unlikely(val == -1 && PyErr_Occurred())) { + PyErr_SetString(PyExc_OverflowError, + (is_unsigned && unlikely(val < 0)) ? + "can't convert negative value to int" : + "value too large to convert to int"); + } + return (int)-1; + } + return (int)val; + } + return (int)__Pyx_PyInt_AsLong(x); +} + +static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { + const unsigned long neg_one = (unsigned long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long)-1; + } + return (unsigned long)PyLong_AsUnsignedLong(x); + } else { + return (unsigned long)PyLong_AsLong(x); + } + } else { + unsigned long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned long)-1; + val = __Pyx_PyInt_AsUnsignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { + const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned PY_LONG_LONG"); + return (unsigned PY_LONG_LONG)-1; + } + return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { + return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + unsigned PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (unsigned PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsUnsignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { + const long neg_one = (long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long)-1; + } + return (long)PyLong_AsUnsignedLong(x); + } else { + return (long)PyLong_AsLong(x); + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (long)-1; + val = __Pyx_PyInt_AsLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { + const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to PY_LONG_LONG"); + return (PY_LONG_LONG)-1; + } + return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { + return (PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { + const signed long neg_one = (signed long)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed long"); + return (signed long)-1; + } + return (signed long)PyLong_AsUnsignedLong(x); + } else { + return (signed long)PyLong_AsLong(x); + } + } else { + signed long val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed long)-1; + val = __Pyx_PyInt_AsSignedLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { + const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_VERSION_HEX < 0x03000000 + if (likely(PyInt_Check(x))) { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)val; + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to signed PY_LONG_LONG"); + return (signed PY_LONG_LONG)-1; + } + return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); + } else { + return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + } + } else { + signed PY_LONG_LONG val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (signed PY_LONG_LONG)-1; + val = __Pyx_PyInt_AsSignedLongLong(tmp); + Py_DECREF(tmp); + return val; + } +} + +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } +} + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + #if PY_VERSION_HEX < 0x02050000 + return PyErr_Warn(NULL, message); + #else + return PyErr_WarnEx(NULL, message, 1); + #endif + } + return 0; +} + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, + size_t size, int strict) +{ + PyObject *py_module = 0; + PyObject *result = 0; + PyObject *py_name = 0; + char warning[200]; + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; + py_name = __Pyx_PyIdentifier_FromString(class_name); + if (!py_name) + goto bad; + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%s.%s is not a type object", + module_name, class_name); + goto bad; + } + if (!strict && (size_t)((PyTypeObject *)result)->tp_basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility", + module_name, class_name); + #if PY_VERSION_HEX < 0x02050000 + if (PyErr_Warn(NULL, warning) < 0) goto bad; + #else + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + #endif + } + else if ((size_t)((PyTypeObject *)result)->tp_basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%s.%s has the wrong size, try recompiling", + module_name, class_name); + goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(py_module); + Py_XDECREF(result); + return NULL; +} +#endif + +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) + goto bad; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; +bad: + Py_XDECREF(py_name); + return 0; +} +#endif + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; + py_frame = PyFrame_New( + PyThreadState_GET(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = py_line; + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + ++t; + } + return 0; +} + + +/* Type Conversion Functions */ + +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} + +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { + PyNumberMethods *m; + const char *name = NULL; + PyObject *res = NULL; +#if PY_VERSION_HEX < 0x03000000 + if (PyInt_Check(x) || PyLong_Check(x)) +#else + if (PyLong_Check(x)) +#endif + return Py_INCREF(x), x; + m = Py_TYPE(x)->tp_as_number; +#if PY_VERSION_HEX < 0x03000000 + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = PyNumber_Long(x); + } +#else + if (m && m->nb_int) { + name = "int"; + res = PyNumber_Long(x); + } +#endif + if (res) { +#if PY_VERSION_HEX < 0x03000000 + if (!PyInt_Check(res) && !PyLong_Check(res)) { +#else + if (!PyLong_Check(res)) { +#endif + PyErr_Format(PyExc_TypeError, + "__%s__ returned non-%s (type %.200s)", + name, name, Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} + +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject* x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} + +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { +#if PY_VERSION_HEX < 0x02050000 + if (ival <= LONG_MAX) + return PyInt_FromLong((long)ival); + else { + unsigned char *bytes = (unsigned char *) &ival; + int one = 1; int little = (int)*(unsigned char*)&one; + return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); + } +#else + return PyInt_FromSize_t(ival); +#endif +} + +static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { + unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); + if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { + return (size_t)-1; + } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); + return (size_t)-1; + } + return (size_t)val; +} + + +#endif /* Py_PYTHON_H */ diff --git a/sklearn/utils/sparsetools/_traversal.pyx b/sklearn/utils/sparsetools/_traversal.pyx new file mode 100644 index 0000000000000..09a91bd230b85 --- /dev/null +++ b/sklearn/utils/sparsetools/_traversal.pyx @@ -0,0 +1,748 @@ +""" +Routines for traversing graphs in compressed sparse format +""" + +# Author: Jake Vanderplas -- +# License: BSD, (C) 2012 + +import numpy as np +cimport numpy as np + +from scipy.sparse import csr_matrix, isspmatrix, isspmatrix_csr, isspmatrix_csc +from ._graph_validation import validate_graph +from ._graph_tools import reconstruct_path + +cimport cython +from libc cimport stdlib + +DTYPE = np.float64 +ctypedef np.float64_t DTYPE_t + +ITYPE = np.int32 +ctypedef np.int32_t ITYPE_t + +# EPS is the precision of DTYPE +cdef DTYPE_t DTYPE_EPS = 1E-15 + +# NULL_IDX is the index used in predecessor matrices to store a non-path +cdef ITYPE_t NULL_IDX = -9999 + +def connected_components(csgraph, directed=True, connection='weak', + return_labels=True): + """ + connected_components(csgraph, directed=True, connection='weak', + return_labels=True) + + Analyze the connected components of a sparse graph + + .. versionadded:: 0.11.0 + + Parameters + ---------- + csgraph : array_like or sparse matrix + The N x N matrix representing the compressed sparse graph. The input + csgraph will be converted to csr format for the calculation. + directed : bool, optional + If True (default), then operate on a directed graph: only + move from point i to point j along paths csgraph[i, j]. + If False, then find the shortest path on an undirected graph: the + algorithm can progress from point i to j along csgraph[i, j] or + csgraph[j, i]. + connection : str, optional + ['weak'|'strong']. For directed graphs, the type of connection to + use. Nodes i and j are strongly connected if a path exists both + from i to j and from j to i. Nodes i and j are weakly connected if + only one of these paths exists. If directed == False, this keyword + is not referenced. + return_labels : str, optional + If True (default), then return the labels for each of the connected + components. + + Returns + ------- + n_components: int + The number of connected components. + labels: ndarray + The length-N array of labels of the connected components. + """ + if connection.lower() not in ['weak', 'strong']: + raise ValueError("connection must be 'weak' or 'strong'") + + # weak connections <=> components of undirected graph + if connection.lower() == 'weak': + directed = False + + csgraph = validate_graph(csgraph, directed, + dense_output=False) + + labels = np.empty(csgraph.shape[0], dtype=ITYPE) + labels.fill(NULL_IDX) + + if directed: + n_components = _connected_components_directed(csgraph.indices, + csgraph.indptr, + labels) + else: + csgraph_T = csgraph.T.tocsr() + n_components = _connected_components_undirected(csgraph.indices, + csgraph.indptr, + csgraph_T.indices, + csgraph_T.indptr, + labels) + + if return_labels: + return n_components, labels + else: + return n_components + + +def breadth_first_tree(csgraph, i_start, directed=True): + r""" + breadth_first_tree(csgraph, i_start, directed=True) + + Return the tree generated by a breadth-first search + + Note that a breadth-first tree from a specified node is unique. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + csgraph : array_like or sparse matrix + The N x N matrix representing the compressed sparse graph. The input + csgraph will be converted to csr format for the calculation. + i_start : int + The index of starting node. + directed : bool, optional + If True (default), then operate on a directed graph: only + move from point i to point j along paths csgraph[i, j]. + If False, then find the shortest path on an undirected graph: the + algorithm can progress from point i to j along csgraph[i, j] or + csgraph[j, i]. + + Returns + ------- + cstree : csr matrix + The N x N directed compressed-sparse representation of the breadth- + first tree drawn from csgraph, starting at the specified node. + + Examples + -------- + The following example shows the computation of a depth-first tree + over a simple four-component graph, starting at node 0:: + + input graph breadth first tree from (0) + + (0) (0) + / \ / \ + 3 8 3 8 + / \ / \ + (3)---5---(1) (3) (1) + \ / / + 6 2 2 + \ / / + (2) (2) + + In compressed sparse representation, the solution looks like this: + + >>> from scipy.sparse import csr_matrix + >>> from scipy.sparse.csgraph import breadth_first_tree + >>> X = csr_matrix([[0, 8, 0, 3], + ... [0, 0, 2, 5], + ... [0, 0, 0, 6], + ... [0, 0, 0, 0]]) + >>> Tcsr = breadth_first_tree(X, 0, directed=False) + >>> Tcsr.toarray().astype(int) + array([[0, 8, 0, 3], + [0, 0, 2, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]]) + + Note that the resulting graph is a Directed Acyclic Graph which spans + the graph. A breadth-first tree from a given node is unique. + """ + node_list, predecessors = breadth_first_order(csgraph, i_start, + directed, True) + return reconstruct_path(csgraph, predecessors, directed) + + +def depth_first_tree(csgraph, i_start, directed=True): + r""" + depth_first_tree(csgraph, i_start, directed=True) + + Return a tree generated by a depth-first search. + + Note that a tree generated by a depth-first search is not unique: + it depends on the order that the children of each node are searched. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + csgraph : array_like or sparse matrix + The N x N matrix representing the compressed sparse graph. The input + csgraph will be converted to csr format for the calculation. + i_start : int + The index of starting node. + directed : bool, optional + If True (default), then operate on a directed graph: only + move from point i to point j along paths csgraph[i, j]. + If False, then find the shortest path on an undirected graph: the + algorithm can progress from point i to j along csgraph[i, j] or + csgraph[j, i]. + + Returns + ------- + cstree : csr matrix + The N x N directed compressed-sparse representation of the depth- + first tree drawn from csgraph, starting at the specified node. + + Examples + -------- + The following example shows the computation of a depth-first tree + over a simple four-component graph, starting at node 0:: + + input graph depth first tree from (0) + + (0) (0) + / \ \ + 3 8 8 + / \ \ + (3)---5---(1) (3) (1) + \ / \ / + 6 2 6 2 + \ / \ / + (2) (2) + + In compressed sparse representation, the solution looks like this: + + >>> from scipy.sparse import csr_matrix + >>> from scipy.sparse.csgraph import depth_first_tree + >>> X = csr_matrix([[0, 8, 0, 3], + ... [0, 0, 2, 5], + ... [0, 0, 0, 6], + ... [0, 0, 0, 0]]) + >>> Tcsr = depth_first_tree(X, 0, directed=False) + >>> Tcsr.toarray().astype(int) + array([[0, 8, 0, 0], + [0, 0, 2, 0], + [0, 0, 0, 6], + [0, 0, 0, 0]]) + + Note that the resulting graph is a Directed Acyclic Graph which spans + the graph. Unlike a breadth-first tree, a depth-first tree of a given + graph is not unique if the graph contains cycles. If the above solution + had begun with the edge connecting nodes 0 and 3, the result would have + been different. + """ + node_list, predecessors = depth_first_order(csgraph, i_start, + directed, True) + return reconstruct_path(csgraph, predecessors, directed) + + +def breadth_first_order(csgraph, i_start, + directed=True, return_predecessors=True): + """ + breadth_first_order(csgraph, i_start, directed=True, return_predecessors=True) + + Return a breadth-first ordering starting with specified node. + + Note that a breadth-first order is not unique, but the tree which it + generates is unique. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + csgraph : array_like or sparse matrix + The N x N compressed sparse graph. The input csgraph will be + converted to csr format for the calculation. + i_start : int + The index of starting node. + directed : bool, optional + If True (default), then operate on a directed graph: only + move from point i to point j along paths csgraph[i, j]. + If False, then find the shortest path on an undirected graph: the + algorithm can progress from point i to j along csgraph[i, j] or + csgraph[j, i]. + return_predecessors : bool, optional + If True (default), then return the predecesor array (see below). + + Returns + ------- + node_array : ndarray, one dimension + The breadth-first list of nodes, starting with specified node. The + length of node_array is the number of nodes reachable from the + specified node. + predecessors : ndarray, one dimension + Returned only if return_predecessors is True. + The length-N list of predecessors of each node in a breadth-first + tree. If node i is in the tree, then its parent is given by + predecessors[i]. If node i is not in the tree (and for the parent + node) then predecessors[i] = -9999. + """ + global NULL_IDX + csgraph = validate_graph(csgraph, directed, dense_output=False) + cdef int N = csgraph.shape[0] + + cdef np.ndarray node_list = np.empty(N, dtype=ITYPE) + cdef np.ndarray predecessors = np.empty(N, dtype=ITYPE) + node_list.fill(NULL_IDX) + predecessors.fill(NULL_IDX) + + if directed: + length = _breadth_first_directed(i_start, + csgraph.indices, csgraph.indptr, + node_list, predecessors) + else: + csgraph_T = csgraph.T.tocsr() + length = _breadth_first_undirected(i_start, + csgraph.indices, csgraph.indptr, + csgraph_T.indices, csgraph_T.indptr, + node_list, predecessors) + + if return_predecessors: + return node_list[:length], predecessors + else: + return node_list[:length] + + +cdef unsigned int _breadth_first_directed( + unsigned int head_node, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indices, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr, + np.ndarray[ITYPE_t, ndim=1, mode='c'] node_list, + np.ndarray[ITYPE_t, ndim=1, mode='c'] predecessors): + # Inputs: + # head_node: (input) index of the node from which traversal starts + # indices: (input) CSR indices of graph + # indptr: (input) CSR indptr of graph + # node_list: (output) breadth-first list of nodes + # predecessors: (output) list of predecessors of nodes in breadth-first + # tree. Should be initialized to NULL_IDX + # Returns: + # n_nodes: the number of nodes in the breadth-first tree + global NULL_IDX + + cdef unsigned int i, pnode, cnode + cdef unsigned int i_nl, i_nl_end + cdef unsigned int N = node_list.shape[0] + + node_list[0] = head_node + i_nl = 0 + i_nl_end = 1 + + while i_nl < i_nl_end: + pnode = node_list[i_nl] + + for i from indptr[pnode] <= i < indptr[pnode + 1]: + cnode = indices[i] + if (cnode == head_node): + continue + elif (predecessors[cnode] == NULL_IDX): + node_list[i_nl_end] = cnode + predecessors[cnode] = pnode + i_nl_end += 1 + + i_nl += 1 + + return i_nl + + +cdef unsigned int _breadth_first_undirected( + unsigned int head_node, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indices1, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr1, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indices2, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr2, + np.ndarray[ITYPE_t, ndim=1, mode='c'] node_list, + np.ndarray[ITYPE_t, ndim=1, mode='c'] predecessors): + # Inputs: + # head_node: (input) index of the node from which traversal starts + # indices1: (input) CSR indices of graph + # indptr1: (input) CSR indptr of graph + # indices2: (input) CSR indices of transposed graph + # indptr2: (input) CSR indptr of transposed graph + # node_list: (output) breadth-first list of nodes + # predecessors: (output) list of predecessors of nodes in breadth-first + # tree. Should be initialized to NULL_IDX + # Returns: + # n_nodes: the number of nodes in the breadth-first tree + global NULL_IDX + + cdef unsigned int i, pnode, cnode + cdef unsigned int i_nl, i_nl_end + cdef unsigned int N = node_list.shape[0] + + node_list[0] = head_node + i_nl = 0 + i_nl_end = 1 + + while i_nl < i_nl_end: + pnode = node_list[i_nl] + + for i from indptr1[pnode] <= i < indptr1[pnode + 1]: + cnode = indices1[i] + if (cnode == head_node): + continue + elif (predecessors[cnode] == NULL_IDX): + node_list[i_nl_end] = cnode + predecessors[cnode] = pnode + i_nl_end += 1 + + for i from indptr2[pnode] <= i < indptr2[pnode + 1]: + cnode = indices2[i] + if (cnode == head_node): + continue + elif (predecessors[cnode] == NULL_IDX): + node_list[i_nl_end] = cnode + predecessors[cnode] = pnode + i_nl_end += 1 + + i_nl += 1 + + return i_nl + + +def depth_first_order(csgraph, i_start, + directed=True, return_predecessors=True): + """ + depth_first_order(csgraph, i_start, directed=True, return_predecessors=True) + + Return a depth-first ordering starting with specified node. + + Note that a depth-first order is not unique. Furthermore, for graphs + with cycles, the tree generated by a depth-first search is not + unique either. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + csgraph : array_like or sparse matrix + The N x N compressed sparse graph. The input csgraph will be + converted to csr format for the calculation. + i_start : int + The index of starting node. + directed : bool, optional + If True (default), then operate on a directed graph: only + move from point i to point j along paths csgraph[i, j]. + If False, then find the shortest path on an undirected graph: the + algorithm can progress from point i to j along csgraph[i, j] or + csgraph[j, i]. + return_predecessors : bool, optional + If True (default), then return the predecesor array (see below). + + Returns + ------- + node_array : ndarray, one dimension + The breadth-first list of nodes, starting with specified node. The + length of node_array is the number of nodes reachable from the + specified node. + predecessors : ndarray, one dimension + Returned only if return_predecessors is True. + The length-N list of predecessors of each node in a breadth-first + tree. If node i is in the tree, then its parent is given by + predecessors[i]. If node i is not in the tree (and for the parent + node) then predecessors[i] = -9999. + """ + global NULL_IDX + csgraph = validate_graph(csgraph, directed, dense_output=False) + cdef int N = csgraph.shape[0] + + node_list = np.empty(N, dtype=ITYPE) + predecessors = np.empty(N, dtype=ITYPE) + root_list = np.empty(N, dtype=ITYPE) + flag = np.zeros(N, dtype=ITYPE) + node_list.fill(NULL_IDX) + predecessors.fill(NULL_IDX) + root_list.fill(NULL_IDX) + + if directed: + length = _depth_first_directed(i_start, + csgraph.indices, csgraph.indptr, + node_list, predecessors, + root_list, flag) + else: + csgraph_T = csgraph.T.tocsr() + length = _depth_first_undirected(i_start, + csgraph.indices, csgraph.indptr, + csgraph_T.indices, csgraph_T.indptr, + node_list, predecessors, + root_list, flag) + + if return_predecessors: + return node_list[:length], predecessors + else: + return node_list[:length] + + +cdef unsigned int _depth_first_directed( + unsigned int head_node, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indices, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr, + np.ndarray[ITYPE_t, ndim=1, mode='c'] node_list, + np.ndarray[ITYPE_t, ndim=1, mode='c'] predecessors, + np.ndarray[ITYPE_t, ndim=1, mode='c'] root_list, + np.ndarray[ITYPE_t, ndim=1, mode='c'] flag): + cdef unsigned int i, j, i_nl_end, cnode, pnode + cdef unsigned int N = node_list.shape[0] + cdef int no_children, i_root + + node_list[0] = head_node + root_list[0] = head_node + i_root = 0 + i_nl_end = 1 + flag[head_node] = 1 + + while i_root >= 0: + pnode = root_list[i_root] + no_children = True + for i from indptr[pnode] <= i < indptr[pnode + 1]: + cnode = indices[i] + if flag[cnode]: + continue + else: + i_root += 1 + root_list[i_root] = cnode + node_list[i_nl_end] = cnode + predecessors[cnode] = pnode + flag[cnode] = 1 + i_nl_end += 1 + no_children = False + break + + if i_nl_end == N: + break + + if no_children: + i_root -= 1 + + return i_nl_end + + +cdef unsigned int _depth_first_undirected( + unsigned int head_node, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indices1, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr1, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indices2, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr2, + np.ndarray[ITYPE_t, ndim=1, mode='c'] node_list, + np.ndarray[ITYPE_t, ndim=1, mode='c'] predecessors, + np.ndarray[ITYPE_t, ndim=1, mode='c'] root_list, + np.ndarray[ITYPE_t, ndim=1, mode='c'] flag): + cdef unsigned int i, j, i_nl_end, cnode, pnode + cdef unsigned int N = node_list.shape[0] + cdef int no_children, i_root + + node_list[0] = head_node + root_list[0] = head_node + i_root = 0 + i_nl_end = 1 + flag[head_node] = 1 + + while i_root >= 0: + pnode = root_list[i_root] + no_children = True + + for i from indptr1[pnode] <= i < indptr1[pnode + 1]: + cnode = indices1[i] + if flag[cnode]: + continue + else: + i_root += 1 + root_list[i_root] = cnode + node_list[i_nl_end] = cnode + predecessors[cnode] = pnode + flag[cnode] = 1 + i_nl_end += 1 + no_children = False + break + + if no_children: + for i from indptr2[pnode] <= i < indptr2[pnode + 1]: + cnode = indices2[i] + if flag[cnode]: + continue + else: + i_root += 1 + root_list[i_root] = cnode + node_list[i_nl_end] = cnode + predecessors[cnode] = pnode + flag[cnode] = 1 + i_nl_end += 1 + no_children = False + break + + if i_nl_end == N: + break + + if no_children: + i_root -= 1 + + return i_nl_end + + +cdef int _connected_components_directed( + np.ndarray[ITYPE_t, ndim=1, mode='c'] indices, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr, + np.ndarray[ITYPE_t, ndim=1, mode='c'] labels): + """ + Uses an iterative version of Tarjan's algorithm to find the + strongly connected components of a directed graph represented as a + sparse matrix (scipy.sparse.csc_matrix or scipy.sparse.csr_matrix). + + The algorithmic complexity is for a graph with E edges and V + vertices is O(E + V). + The storage requirement is 2*V integer arrays. + + Uses an iterative version of the algorithm described here: + http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.102.1707 + """ + cdef int v, w, index, low_v, low_w, label, j + cdef int SS_head, root, stack_head, f, b + cdef int VOID = -1 + cdef int END = -2 + cdef int N = labels.shape[0] + cdef np.ndarray[ITYPE_t, ndim=1, mode="c"] SS, lowlinks, stack_f, stack_b + + lowlinks = labels + SS = np.ndarray((N,), dtype=ITYPE) + stack_b = np.ndarray((N,), dtype=ITYPE) + stack_f = SS + + # The stack of nodes which have been backtracked and are in the current SCC + SS.fill(VOID) + SS_head = END + + # The array containing the lowlinks of nodes not yet assigned an SCC. Shares + # memory with the labels array, since they are not used at the same time. + lowlinks.fill(VOID) + + # The DFS stack. Stored with both forwards and backwards pointers to allow + # us to move a node up to the top of the stack, as we only need to visit + # each node once. stack_f shares memory with SS, as nodes aren't put on the + # SS stack until after they've been popped from the DFS stack. + stack_head = END + stack_f.fill(VOID) + stack_b.fill(VOID) + + index = 0 + # Count SCC labels backwards so as not to class with lowlinks values. + label = N - 1 + for v in range(N): + if lowlinks[v] == VOID: + # DFS-stack push + stack_head = v + stack_f[v] = END + stack_b[v] = END + while stack_head != END: + v = stack_head + if lowlinks[v] == VOID: + lowlinks[v] = index + index += 1 + + # Add successor nodes + for j from indptr[v] <= j < indptr[v+1]: + w = indices[j] + if lowlinks[w] == VOID: + # DFS-stack push + if stack_f[w] != VOID: + # w is already inside the stack, so excise it. + f = stack_f[w] + b = stack_b[w] + if b != END: + stack_f[b] = f + if f != END: + stack_b[f] = b + + stack_f[w] = stack_head + stack_b[w] = END + stack_b[stack_head] = w + stack_head = w + + else: + # DFS-stack pop + stack_head = stack_f[v] + if stack_head >= 0: + stack_b[stack_head] = END + stack_f[v] = VOID + stack_b[v] = VOID + + root = 1 # True + low_v = lowlinks[v] + for j from indptr[v] <= j < indptr[v+1]: + low_w = lowlinks[indices[j]] + if low_w < low_v: + low_v = low_w + root = 0 # False + lowlinks[v] = low_v + + if root: # Found a root node + index -= 1 + # while S not empty and rindex[v] <= rindex[top[S] + while SS_head != END and lowlinks[v] <= lowlinks[SS_head]: + w = SS_head # w = pop(S) + SS_head = SS[w] + SS[w] = VOID + + labels[w] = label # rindex[w] = c + index -= 1 # index = index - 1 + labels[v] = label # rindex[v] = c + label -= 1 # c = c - 1 + else: + SS[v] = SS_head # push(S, v) + SS_head = v + + # labels count down from N-1 to zero. Modify them so they + # count upward from 0 + labels *= -1 + labels += (N - 1) + return (N - 1) - label + +cdef int _connected_components_undirected( + np.ndarray[ITYPE_t, ndim=1, mode='c'] indices1, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr1, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indices2, + np.ndarray[ITYPE_t, ndim=1, mode='c'] indptr2, + np.ndarray[ITYPE_t, ndim=1, mode='c'] labels): + + cdef int v, w, j, label, SS_head + cdef int N = labels.shape[0] + cdef int VOID = -1 + cdef int END = -2 + labels.fill(VOID) + label = 0 + + # Share memory for the stack and labels, since labels are only + # applied once a node has been popped from the stack. + cdef np.ndarray[ITYPE_t, ndim=1, mode="c"] SS = labels + SS_head = END + for v in range(N): + if labels[v] == VOID: + # SS.push(v) + SS_head = v + SS[v] = END + + while SS_head != END: + # v = SS.pop() + v = SS_head + SS_head = SS[v] + + labels[v] = label + + # Push children onto the stack if they havn't been + # seen at all yet. + for j from indptr1[v] <= j < indptr1[v+1]: + w = indices1[j] + if SS[w] == VOID: + SS[w] = SS_head + SS_head = w + for j from indptr2[v] <= j < indptr2[v+1]: + w = indices2[j] + if SS[w] == VOID: + SS[w] = SS_head + SS_head = w + label += 1 + + return label diff --git a/sklearn/utils/sparsetools/complex_ops.h b/sklearn/utils/sparsetools/complex_ops.h deleted file mode 100644 index 77620016227f4..0000000000000 --- a/sklearn/utils/sparsetools/complex_ops.h +++ /dev/null @@ -1,98 +0,0 @@ -#ifndef COMPLEX_OPS_H -#define COMPLEX_OPS_H - -/* - * Functions to handle arithmetic operations on NumPy complex values - */ - -#include -#include - -template -class complex_wrapper : public npy_type { - template - friend std::ostream& operator<<(std::ostream&, const complex_wrapper& ); - - public: - complex_wrapper( const c_type r = c_type(0), const c_type i = c_type(0) ){ - npy_type::real = r; - npy_type::imag = i; - } - complex_wrapper operator-() const { - return complex_wrapper(-npy_type::real,-npy_type::imag); - } - complex_wrapper operator+(const complex_wrapper& B) const { - return complex_wrapper(npy_type::real + B.real, npy_type::imag + B.imag); - } - complex_wrapper operator-(const complex_wrapper& B) const { - return complex_wrapper(npy_type::real - B.real, npy_type::imag - B.imag); - } - complex_wrapper operator*(const complex_wrapper& B) const { - return complex_wrapper(npy_type::real * B.real - npy_type::imag * B.imag, - npy_type::real * B.imag + npy_type::imag * B.real); - } - complex_wrapper operator/(const complex_wrapper& B) const { - complex_wrapper result; - c_type denom = 1.0 / (B.real * B.real + B.imag * B.imag); - result.real = (npy_type::real * B.real + npy_type::imag * B.imag) * denom; - result.imag = (npy_type::imag * B.real - npy_type::real * B.imag) * denom; - return result; - } - complex_wrapper& operator+=(const complex_wrapper & B){ - npy_type::real += B.real; - npy_type::imag += B.imag; - return (*this); - } - complex_wrapper& operator-=(const complex_wrapper & B){ - npy_type::real -= B.real; - npy_type::imag -= B.imag; - return (*this); - } - complex_wrapper& operator*=(const complex_wrapper & B){ - c_type temp = npy_type::real * B.real - npy_type::imag * B.imag; - npy_type::imag = npy_type::real * B.imag + npy_type::imag * B.real; - npy_type::real = temp; - return (*this); - } - complex_wrapper& operator/=(const complex_wrapper & B){ - c_type denom = 1.0 / (B.real * B.real + B.imag * B.imag); - c_type temp = (npy_type::real * B.real + npy_type::imag * B.imag) * denom; - npy_type::imag = (npy_type::imag * B.real - npy_type::real * B.imag) * denom; - npy_type::real = temp; - return (*this); - } - bool operator==(const complex_wrapper& B) const{ - return npy_type::real == B.real && npy_type::imag == B.imag; - } - bool operator!=(const complex_wrapper& B) const{ - return npy_type::real != B.real || npy_type::imag != B.imag; - } - bool operator==(const c_type& B) const{ - return npy_type::real == B && npy_type::imag == c_type(0); - } - bool operator!=(const c_type& B) const{ - return npy_type::real != B || npy_type::imag != c_type(0); - } - complex_wrapper& operator=(const complex_wrapper& B){ - npy_type::real = B.real; - npy_type::imag = B.imag; - return (*this); - } - complex_wrapper& operator=(const c_type& B){ - npy_type::real = B; - npy_type::imag = c_type(0); - return (*this); - } -}; - -template -std::ostream& operator<<(std::ostream& out, const complex_wrapper& cw){ - return out << cw.real << " " << cw.imag; -} - -typedef complex_wrapper npy_cfloat_wrapper; -typedef complex_wrapper npy_cdouble_wrapper; -typedef complex_wrapper npy_clongdouble_wrapper; - - -#endif diff --git a/sklearn/utils/sparsetools/csgraph.h b/sklearn/utils/sparsetools/csgraph.h deleted file mode 100644 index 66cee0a058a78..0000000000000 --- a/sklearn/utils/sparsetools/csgraph.h +++ /dev/null @@ -1,148 +0,0 @@ -#ifndef __CSGRAPH_H__ -#define __CSGRAPH_H__ - -#include - -/* - * Determine connected compoments of a compressed sparse graph. - * Note: - * Output array flag must be preallocated - */ -template -I cs_graph_components(const I n_nod, - const I Ap[], - const I Aj[], - I flag[]) -{ - // pos is a work array: list of nodes (rows) to process. - std::vector pos(n_nod,01); - I n_comp = 0; - I n_tot, n_pos, n_pos_new, n_pos0, n_new, n_stop; - I icomp, ii, ir, ic; - - n_stop = n_nod; - for (ir = 0; ir < n_nod; ir++) { - flag[ir] = -1; - if (Ap[ir+1] == Ap[ir]) { - n_stop--; - flag[ir] = -2; - } - } - - n_tot = 0; - for (icomp = 0; icomp < n_nod; icomp++) { - // Find seed. - ii = 0; - while ((flag[ii] >= 0) || (flag[ii] == -2)) { - ii++; - if (ii >= n_nod) { - /* Sanity check, if this happens, the graph is corrupted. */ - return -1; - } - } - - flag[ii] = icomp; - pos[0] = ii; - n_pos0 = 0; - n_pos_new = n_pos = 1; - - for (ii = 0; ii < n_nod; ii++) { - n_new = 0; - for (ir = n_pos0; ir < n_pos; ir++) { - for (ic = Ap[pos[ir]]; ic < Ap[pos[ir]+1]; ic++) { - if (flag[Aj[ic]] == -1) { - flag[Aj[ic]] = icomp; - pos[n_pos_new] = Aj[ic]; - n_pos_new++; - n_new++; - } - } - } - n_pos0 = n_pos; - n_pos = n_pos_new; - if (n_new == 0) break; - } - n_tot += n_pos; - - if (n_tot == n_stop) { - n_comp = icomp + 1; - break; - } - } - - return n_comp; -} - -#endif -#ifndef __CSGRAPH_H__ -#define __CSGRAPH_H__ - -#include - -/* - * Determine connected compoments of a compressed sparse graph. - * Note: - * Output array flag must be preallocated - */ -template -I cs_graph_components(const I n_nod, - const I Ap[], - const I Aj[], - I flag[]) -{ - // pos is a work array: list of nodes (rows) to process. - std::vector pos(n_nod,01); - I n_comp; - I n_tot, n_pos, n_pos_new, n_pos0, n_new, n_stop; - I icomp, ii, ir, ic; - - n_stop = n_nod; - for (ir = 0; ir < n_nod; ir++) { - flag[ir] = -1; - if ((Ap[ir+1] - Ap[ir]) == 0) n_stop--; - } - - n_tot = 0; - for (icomp = 0; icomp < n_nod; icomp++) { - // Find seed. - ii = 0; - while (flag[ii] >= 0) { - ii++; - if (ii >= n_nod) { - /* Sanity check, if this happens, the graph is corrupted. */ - return -1; - } - } - flag[ii] = icomp; - pos[0] = ii; - n_pos0 = 0; - n_pos_new = n_pos = 1; - - for (ii = 0; ii < n_nod; ii++) { - n_new = 0; - for (ir = n_pos0; ir < n_pos; ir++) { - for (ic = Ap[pos[ir]]; ic < Ap[pos[ir]+1]; ic++) { - if (flag[Aj[ic]] == -1) { - flag[Aj[ic]] = icomp; - pos[n_pos_new] = Aj[ic]; - n_pos_new++; - n_new++; - } - } - } - n_pos0 = n_pos; - n_pos = n_pos_new; - if (n_new == 0) break; - } - n_tot += n_pos; - - if (n_tot == n_stop) { - n_comp = icomp + 1; - break; - } - } - - return n_comp; -} - -#endif diff --git a/sklearn/utils/sparsetools/csgraph.i b/sklearn/utils/sparsetools/csgraph.i deleted file mode 100644 index 16046223c8c1d..0000000000000 --- a/sklearn/utils/sparsetools/csgraph.i +++ /dev/null @@ -1,24 +0,0 @@ -/* -*- C -*- */ -%module csgraph - -%include "sparsetools.i" - -%{ -#include "csgraph.h" -%} - -%include "csgraph.h" - -INSTANTIATE_INDEX(cs_graph_components) -/* -*- C -*- */ -%module csgraph - -%include "sparsetools.i" - -%{ -#include "csgraph.h" -%} - -%include "csgraph.h" - -INSTANTIATE_INDEX(cs_graph_components) diff --git a/sklearn/utils/sparsetools/csgraph.py b/sklearn/utils/sparsetools/csgraph.py deleted file mode 100644 index 27189e1c1c929..0000000000000 --- a/sklearn/utils/sparsetools/csgraph.py +++ /dev/null @@ -1,85 +0,0 @@ -# This file was automatically generated by SWIG (http://www.swig.org). -# Version 2.0.1+capsulehack -# -# Do not make changes to this file unless you know what you are doing--modify -# the SWIG interface file instead. -# This file is compatible with both classic and new-style classes. - -from sys import version_info -if version_info >= (2, 6, 0): - def swig_import_helper(): - from os.path import dirname - import imp - fp = None - try: - fp, pathname, description = imp.find_module('_csgraph', - [dirname(__file__)]) - except ImportError: - import _csgraph - return _csgraph - if fp is not None: - try: - _mod = imp.load_module('_csgraph', fp, pathname, description) - finally: - fp.close() - return _mod - _csgraph = swig_import_helper() - del swig_import_helper -else: - import _csgraph -del version_info -try: - _swig_property = property -except NameError: - pass # Python < 2.2 doesn't have 'property'. - - -def _swig_setattr_nondynamic(self, class_type, name, value, static=1): - if (name == "thisown"): - return self.this.own(value) - if (name == "this"): - if type(value).__name__ == 'SwigPyObject': - self.__dict__[name] = value - return - method = class_type.__swig_setmethods__.get(name, None) - if method: - return method(self, value) - if (not static) or hasattr(self, name): - self.__dict__[name] = value - else: - raise AttributeError("You cannot add attributes to %s" % self) - - -def _swig_setattr(self, class_type, name, value): - return _swig_setattr_nondynamic(self, class_type, name, value, 0) - - -def _swig_getattr(self, class_type, name): - if (name == "thisown"): - return self.this.own() - method = class_type.__swig_getmethods__.get(name, None) - if method: - return method(self) - raise AttributeError(name) - - -def _swig_repr(self): - try: - strthis = "proxy of " + self.this.__repr__() - except: - strthis = "" - return "<%s.%s; %s >" % (self.__class__.__module__, - self.__class__.__name__, strthis,) - -try: - _object = object - _newclass = 1 -except AttributeError: - class _object: - pass - _newclass = 0 - - -def cs_graph_components(*args): - """cs_graph_components(int n_nod, int Ap, int Aj, int flag) -> int""" - return _csgraph.cs_graph_components(*args) diff --git a/sklearn/utils/sparsetools/csgraph_wrap.cxx b/sklearn/utils/sparsetools/csgraph_wrap.cxx deleted file mode 100644 index 6329d07f64aa1..0000000000000 --- a/sklearn/utils/sparsetools/csgraph_wrap.cxx +++ /dev/null @@ -1,4039 +0,0 @@ -/* ---------------------------------------------------------------------------- - * This file was automatically generated by SWIG (http://www.swig.org). - * Version 2.0.1+capsulehack - * - * This file is not intended to be easily readable and contains a number of - * coding conventions designed to improve portability and efficiency. Do not make - * changes to this file unless you know what you are doing--modify the SWIG - * interface file instead. - * ----------------------------------------------------------------------------- */ - -#define SWIGPYTHON -#define SWIG_PYTHON_DIRECTOR_NO_VTABLE - - -#ifdef __cplusplus -/* SwigValueWrapper is described in swig.swg */ -template class SwigValueWrapper { - struct SwigMovePointer { - T *ptr; - SwigMovePointer(T *p) : ptr(p) { } - ~SwigMovePointer() { delete ptr; } - SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; } - } pointer; - SwigValueWrapper& operator=(const SwigValueWrapper& rhs); - SwigValueWrapper(const SwigValueWrapper& rhs); -public: - SwigValueWrapper() : pointer(0) { } - SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; } - operator T&() const { return *pointer.ptr; } - T *operator&() { return pointer.ptr; } -}; - -template T SwigValueInit() { - return T(); -} -#endif - -/* ----------------------------------------------------------------------------- - * This section contains generic SWIG labels for method/variable - * declarations/attributes, and other compiler dependent labels. - * ----------------------------------------------------------------------------- */ - -/* template workaround for compilers that cannot correctly implement the C++ standard */ -#ifndef SWIGTEMPLATEDISAMBIGUATOR -# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) -# define SWIGTEMPLATEDISAMBIGUATOR template -# elif defined(__HP_aCC) -/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ -/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ -# define SWIGTEMPLATEDISAMBIGUATOR template -# else -# define SWIGTEMPLATEDISAMBIGUATOR -# endif -#endif - -/* inline attribute */ -#ifndef SWIGINLINE -# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) -# define SWIGINLINE inline -# else -# define SWIGINLINE -# endif -#endif - -/* attribute recognised by some compilers to avoid 'unused' warnings */ -#ifndef SWIGUNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define SWIGUNUSED __attribute__ ((__unused__)) -# else -# define SWIGUNUSED -# endif -# elif defined(__ICC) -# define SWIGUNUSED __attribute__ ((__unused__)) -# else -# define SWIGUNUSED -# endif -#endif - -#ifndef SWIG_MSC_UNSUPPRESS_4505 -# if defined(_MSC_VER) -# pragma warning(disable : 4505) /* unreferenced local function has been removed */ -# endif -#endif - -#ifndef SWIGUNUSEDPARM -# ifdef __cplusplus -# define SWIGUNUSEDPARM(p) -# else -# define SWIGUNUSEDPARM(p) p SWIGUNUSED -# endif -#endif - -/* internal SWIG method */ -#ifndef SWIGINTERN -# define SWIGINTERN static SWIGUNUSED -#endif - -/* internal inline SWIG method */ -#ifndef SWIGINTERNINLINE -# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE -#endif - -/* exporting methods */ -#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) -# ifndef GCC_HASCLASSVISIBILITY -# define GCC_HASCLASSVISIBILITY -# endif -#endif - -#ifndef SWIGEXPORT -# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) -# if defined(STATIC_LINKED) -# define SWIGEXPORT -# else -# define SWIGEXPORT __declspec(dllexport) -# endif -# else -# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) -# define SWIGEXPORT __attribute__ ((visibility("default"))) -# else -# define SWIGEXPORT -# endif -# endif -#endif - -/* calling conventions for Windows */ -#ifndef SWIGSTDCALL -# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) -# define SWIGSTDCALL __stdcall -# else -# define SWIGSTDCALL -# endif -#endif - -/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ -#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) -# define _CRT_SECURE_NO_DEPRECATE -#endif - -/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ -#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) -# define _SCL_SECURE_NO_DEPRECATE -#endif - - - -/* Python.h has to appear first */ -#include - -/* ----------------------------------------------------------------------------- - * swigrun.swg - * - * This file contains generic C API SWIG runtime support for pointer - * type checking. - * ----------------------------------------------------------------------------- */ - -/* This should only be incremented when either the layout of swig_type_info changes, - or for whatever reason, the runtime changes incompatibly */ -#define SWIG_RUNTIME_VERSION "4" - -/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ -#ifdef SWIG_TYPE_TABLE -# define SWIG_QUOTE_STRING(x) #x -# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) -# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) -#else -# define SWIG_TYPE_TABLE_NAME -#endif - -/* - You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for - creating a static or dynamic library from the SWIG runtime code. - In 99.9% of the cases, SWIG just needs to declare them as 'static'. - - But only do this if strictly necessary, ie, if you have problems - with your compiler or suchlike. -*/ - -#ifndef SWIGRUNTIME -# define SWIGRUNTIME SWIGINTERN -#endif - -#ifndef SWIGRUNTIMEINLINE -# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE -#endif - -/* Generic buffer size */ -#ifndef SWIG_BUFFER_SIZE -# define SWIG_BUFFER_SIZE 1024 -#endif - -/* Flags for pointer conversions */ -#define SWIG_POINTER_DISOWN 0x1 -#define SWIG_CAST_NEW_MEMORY 0x2 - -/* Flags for new pointer objects */ -#define SWIG_POINTER_OWN 0x1 - - -/* - Flags/methods for returning states. - - The SWIG conversion methods, as ConvertPtr, return an integer - that tells if the conversion was successful or not. And if not, - an error code can be returned (see swigerrors.swg for the codes). - - Use the following macros/flags to set or process the returning - states. - - In old versions of SWIG, code such as the following was usually written: - - if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { - // success code - } else { - //fail code - } - - Now you can be more explicit: - - int res = SWIG_ConvertPtr(obj,vptr,ty.flags); - if (SWIG_IsOK(res)) { - // success code - } else { - // fail code - } - - which is the same really, but now you can also do - - Type *ptr; - int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); - if (SWIG_IsOK(res)) { - // success code - if (SWIG_IsNewObj(res) { - ... - delete *ptr; - } else { - ... - } - } else { - // fail code - } - - I.e., now SWIG_ConvertPtr can return new objects and you can - identify the case and take care of the deallocation. Of course that - also requires SWIG_ConvertPtr to return new result values, such as - - int SWIG_ConvertPtr(obj, ptr,...) { - if () { - if () { - *ptr = ; - return SWIG_NEWOBJ; - } else { - *ptr = ; - return SWIG_OLDOBJ; - } - } else { - return SWIG_BADOBJ; - } - } - - Of course, returning the plain '0(success)/-1(fail)' still works, but you can be - more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the - SWIG errors code. - - Finally, if the SWIG_CASTRANK_MODE is enabled, the result code - allows to return the 'cast rank', for example, if you have this - - int food(double) - int fooi(int); - - and you call - - food(1) // cast rank '1' (1 -> 1.0) - fooi(1) // cast rank '0' - - just use the SWIG_AddCast()/SWIG_CheckState() -*/ - -#define SWIG_OK (0) -#define SWIG_ERROR (-1) -#define SWIG_IsOK(r) (r >= 0) -#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) - -/* The CastRankLimit says how many bits are used for the cast rank */ -#define SWIG_CASTRANKLIMIT (1 << 8) -/* The NewMask denotes the object was created (using new/malloc) */ -#define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) -/* The TmpMask is for in/out typemaps that use temporal objects */ -#define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) -/* Simple returning values */ -#define SWIG_BADOBJ (SWIG_ERROR) -#define SWIG_OLDOBJ (SWIG_OK) -#define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) -#define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) -/* Check, add and del mask methods */ -#define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) -#define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) -#define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) -#define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) -#define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) -#define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) - -/* Cast-Rank Mode */ -#if defined(SWIG_CASTRANK_MODE) -# ifndef SWIG_TypeRank -# define SWIG_TypeRank unsigned long -# endif -# ifndef SWIG_MAXCASTRANK /* Default cast allowed */ -# define SWIG_MAXCASTRANK (2) -# endif -# define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) -# define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) -SWIGINTERNINLINE int SWIG_AddCast(int r) { - return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; -} -SWIGINTERNINLINE int SWIG_CheckState(int r) { - return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; -} -#else /* no cast-rank mode */ -# define SWIG_AddCast -# define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) -#endif - - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void *(*swig_converter_func)(void *, int *); -typedef struct swig_type_info *(*swig_dycast_func)(void **); - -/* Structure to store information on one type */ -typedef struct swig_type_info { - const char *name; /* mangled name of this type */ - const char *str; /* human readable name of this type */ - swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ - struct swig_cast_info *cast; /* linked list of types that can cast into this type */ - void *clientdata; /* language specific type data */ - int owndata; /* flag if the structure owns the clientdata */ -} swig_type_info; - -/* Structure to store a type and conversion function used for casting */ -typedef struct swig_cast_info { - swig_type_info *type; /* pointer to type that is equivalent to this type */ - swig_converter_func converter; /* function to cast the void pointers */ - struct swig_cast_info *next; /* pointer to next cast in linked list */ - struct swig_cast_info *prev; /* pointer to the previous cast */ -} swig_cast_info; - -/* Structure used to store module information - * Each module generates one structure like this, and the runtime collects - * all of these structures and stores them in a circularly linked list.*/ -typedef struct swig_module_info { - swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ - size_t size; /* Number of types in this module */ - struct swig_module_info *next; /* Pointer to next element in circularly linked list */ - swig_type_info **type_initial; /* Array of initially generated type structures */ - swig_cast_info **cast_initial; /* Array of initially generated casting structures */ - void *clientdata; /* Language specific module data */ -} swig_module_info; - -/* - Compare two type names skipping the space characters, therefore - "char*" == "char *" and "Class" == "Class", etc. - - Return 0 when the two name types are equivalent, as in - strncmp, but skipping ' '. -*/ -SWIGRUNTIME int -SWIG_TypeNameComp(const char *f1, const char *l1, - const char *f2, const char *l2) { - for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { - while ((*f1 == ' ') && (f1 != l1)) ++f1; - while ((*f2 == ' ') && (f2 != l2)) ++f2; - if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; - } - return (int)((l1 - f1) - (l2 - f2)); -} - -/* - Check type equivalence in a name list like ||... - Return 0 if not equal, 1 if equal -*/ -SWIGRUNTIME int -SWIG_TypeEquiv(const char *nb, const char *tb) { - int equiv = 0; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (!equiv && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; - } - equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; - if (*ne) ++ne; - } - return equiv; -} - -/* - Check type equivalence in a name list like ||... - Return 0 if equal, -1 if nb < tb, 1 if nb > tb -*/ -SWIGRUNTIME int -SWIG_TypeCompare(const char *nb, const char *tb) { - int equiv = 0; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (!equiv && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; - } - equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; - if (*ne) ++ne; - } - return equiv; -} - - -/* - Check the typename -*/ -SWIGRUNTIME swig_cast_info * -SWIG_TypeCheck(const char *c, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (strcmp(iter->type->name, c) == 0) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; - } - } - return 0; -} - -/* - Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison -*/ -SWIGRUNTIME swig_cast_info * -SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (iter->type == from) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; - } - } - return 0; -} - -/* - Cast a pointer up an inheritance hierarchy -*/ -SWIGRUNTIMEINLINE void * -SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { - return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); -} - -/* - Dynamic pointer casting. Down an inheritance hierarchy -*/ -SWIGRUNTIME swig_type_info * -SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { - swig_type_info *lastty = ty; - if (!ty || !ty->dcast) return ty; - while (ty && (ty->dcast)) { - ty = (*ty->dcast)(ptr); - if (ty) lastty = ty; - } - return lastty; -} - -/* - Return the name associated with this type -*/ -SWIGRUNTIMEINLINE const char * -SWIG_TypeName(const swig_type_info *ty) { - return ty->name; -} - -/* - Return the pretty name associated with this type, - that is an unmangled type name in a form presentable to the user. -*/ -SWIGRUNTIME const char * -SWIG_TypePrettyName(const swig_type_info *type) { - /* The "str" field contains the equivalent pretty names of the - type, separated by vertical-bar characters. We choose - to print the last name, as it is often (?) the most - specific. */ - if (!type) return NULL; - if (type->str != NULL) { - const char *last_name = type->str; - const char *s; - for (s = type->str; *s; s++) - if (*s == '|') last_name = s+1; - return last_name; - } - else - return type->name; -} - -/* - Set the clientdata field for a type -*/ -SWIGRUNTIME void -SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { - swig_cast_info *cast = ti->cast; - /* if (ti->clientdata == clientdata) return; */ - ti->clientdata = clientdata; - - while (cast) { - if (!cast->converter) { - swig_type_info *tc = cast->type; - if (!tc->clientdata) { - SWIG_TypeClientData(tc, clientdata); - } - } - cast = cast->next; - } -} -SWIGRUNTIME void -SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { - SWIG_TypeClientData(ti, clientdata); - ti->owndata = 1; -} - -/* - Search for a swig_type_info structure only by mangled name - Search is a O(log #types) - - We start searching at module start, and finish searching when start == end. - Note: if start == end at the beginning of the function, we go all the way around - the circular list. -*/ -SWIGRUNTIME swig_type_info * -SWIG_MangledTypeQueryModule(swig_module_info *start, - swig_module_info *end, - const char *name) { - swig_module_info *iter = start; - do { - if (iter->size) { - register size_t l = 0; - register size_t r = iter->size - 1; - do { - /* since l+r >= 0, we can (>> 1) instead (/ 2) */ - register size_t i = (l + r) >> 1; - const char *iname = iter->types[i]->name; - if (iname) { - register int compare = strcmp(name, iname); - if (compare == 0) { - return iter->types[i]; - } else if (compare < 0) { - if (i) { - r = i - 1; - } else { - break; - } - } else if (compare > 0) { - l = i + 1; - } - } else { - break; /* should never happen */ - } - } while (l <= r); - } - iter = iter->next; - } while (iter != end); - return 0; -} - -/* - Search for a swig_type_info structure for either a mangled name or a human readable name. - It first searches the mangled names of the types, which is a O(log #types) - If a type is not found it then searches the human readable names, which is O(#types). - - We start searching at module start, and finish searching when start == end. - Note: if start == end at the beginning of the function, we go all the way around - the circular list. -*/ -SWIGRUNTIME swig_type_info * -SWIG_TypeQueryModule(swig_module_info *start, - swig_module_info *end, - const char *name) { - /* STEP 1: Search the name field using binary search */ - swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); - if (ret) { - return ret; - } else { - /* STEP 2: If the type hasn't been found, do a complete search - of the str field (the human readable name) */ - swig_module_info *iter = start; - do { - register size_t i = 0; - for (; i < iter->size; ++i) { - if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) - return iter->types[i]; - } - iter = iter->next; - } while (iter != end); - } - - /* neither found a match */ - return 0; -} - -/* - Pack binary data into a string -*/ -SWIGRUNTIME char * -SWIG_PackData(char *c, void *ptr, size_t sz) { - static const char hex[17] = "0123456789abcdef"; - register const unsigned char *u = (unsigned char *) ptr; - register const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - register unsigned char uu = *u; - *(c++) = hex[(uu & 0xf0) >> 4]; - *(c++) = hex[uu & 0xf]; - } - return c; -} - -/* - Unpack binary data from a string -*/ -SWIGRUNTIME const char * -SWIG_UnpackData(const char *c, void *ptr, size_t sz) { - register unsigned char *u = (unsigned char *) ptr; - register const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - register char d = *(c++); - register unsigned char uu; - if ((d >= '0') && (d <= '9')) - uu = ((d - '0') << 4); - else if ((d >= 'a') && (d <= 'f')) - uu = ((d - ('a'-10)) << 4); - else - return (char *) 0; - d = *(c++); - if ((d >= '0') && (d <= '9')) - uu |= (d - '0'); - else if ((d >= 'a') && (d <= 'f')) - uu |= (d - ('a'-10)); - else - return (char *) 0; - *u = uu; - } - return c; -} - -/* - Pack 'void *' into a string buffer. -*/ -SWIGRUNTIME char * -SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { - char *r = buff; - if ((2*sizeof(void *) + 2) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,&ptr,sizeof(void *)); - if (strlen(name) + 1 > (bsz - (r - buff))) return 0; - strcpy(r,name); - return buff; -} - -SWIGRUNTIME const char * -SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - *ptr = (void *) 0; - return name; - } else { - return 0; - } - } - return SWIG_UnpackData(++c,ptr,sizeof(void *)); -} - -SWIGRUNTIME char * -SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { - char *r = buff; - size_t lname = (name ? strlen(name) : 0); - if ((2*sz + 2 + lname) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,ptr,sz); - if (lname) { - strncpy(r,name,lname+1); - } else { - *r = 0; - } - return buff; -} - -SWIGRUNTIME const char * -SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - memset(ptr,0,sz); - return name; - } else { - return 0; - } - } - return SWIG_UnpackData(++c,ptr,sz); -} - -#ifdef __cplusplus -} -#endif - -/* Errors in SWIG */ -#define SWIG_UnknownError -1 -#define SWIG_IOError -2 -#define SWIG_RuntimeError -3 -#define SWIG_IndexError -4 -#define SWIG_TypeError -5 -#define SWIG_DivisionByZero -6 -#define SWIG_OverflowError -7 -#define SWIG_SyntaxError -8 -#define SWIG_ValueError -9 -#define SWIG_SystemError -10 -#define SWIG_AttributeError -11 -#define SWIG_MemoryError -12 -#define SWIG_NullReferenceError -13 - - - -/* Compatibility macros for Python 3 */ -#if PY_VERSION_HEX >= 0x03000000 - -#define PyClass_Check(obj) PyObject_IsInstance(obj, (PyObject *)&PyType_Type) -#define PyInt_Check(x) PyLong_Check(x) -#define PyInt_AsLong(x) PyLong_AsLong(x) -#define PyInt_FromLong(x) PyLong_FromLong(x) -#define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) - -#endif - -#ifndef Py_TYPE -# define Py_TYPE(op) ((op)->ob_type) -#endif - -/* SWIG APIs for compatibility of both Python 2 & 3 */ - -#if PY_VERSION_HEX >= 0x03000000 -# define SWIG_Python_str_FromFormat PyUnicode_FromFormat -#else -# define SWIG_Python_str_FromFormat PyString_FromFormat -#endif - - -/* Warning: This function will allocate a new string in Python 3, - * so please call SWIG_Python_str_DelForPy3(x) to free the space. - */ -SWIGINTERN char* -SWIG_Python_str_AsChar(PyObject *str) -{ -#if PY_VERSION_HEX >= 0x03000000 - char *cstr; - char *newstr; - Py_ssize_t len; - str = PyUnicode_AsUTF8String(str); - PyBytes_AsStringAndSize(str, &cstr, &len); - newstr = (char *) malloc(len+1); - memcpy(newstr, cstr, len+1); - Py_XDECREF(str); - return newstr; -#else - return PyString_AsString(str); -#endif -} - -#if PY_VERSION_HEX >= 0x03000000 -# define SWIG_Python_str_DelForPy3(x) free( (void*) (x) ) -#else -# define SWIG_Python_str_DelForPy3(x) -#endif - - -SWIGINTERN PyObject* -SWIG_Python_str_FromChar(const char *c) -{ -#if PY_VERSION_HEX >= 0x03000000 - return PyUnicode_FromString(c); -#else - return PyString_FromString(c); -#endif -} - -/* Add PyOS_snprintf for old Pythons */ -#if PY_VERSION_HEX < 0x02020000 -# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) -# define PyOS_snprintf _snprintf -# else -# define PyOS_snprintf snprintf -# endif -#endif - -/* A crude PyString_FromFormat implementation for old Pythons */ -#if PY_VERSION_HEX < 0x02020000 - -#ifndef SWIG_PYBUFFER_SIZE -# define SWIG_PYBUFFER_SIZE 1024 -#endif - -static PyObject * -PyString_FromFormat(const char *fmt, ...) { - va_list ap; - char buf[SWIG_PYBUFFER_SIZE * 2]; - int res; - va_start(ap, fmt); - res = vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); -} -#endif - -/* Add PyObject_Del for old Pythons */ -#if PY_VERSION_HEX < 0x01060000 -# define PyObject_Del(op) PyMem_DEL((op)) -#endif -#ifndef PyObject_DEL -# define PyObject_DEL PyObject_Del -#endif - -/* A crude PyExc_StopIteration exception for old Pythons */ -#if PY_VERSION_HEX < 0x02020000 -# ifndef PyExc_StopIteration -# define PyExc_StopIteration PyExc_RuntimeError -# endif -# ifndef PyObject_GenericGetAttr -# define PyObject_GenericGetAttr 0 -# endif -#endif - -/* Py_NotImplemented is defined in 2.1 and up. */ -#if PY_VERSION_HEX < 0x02010000 -# ifndef Py_NotImplemented -# define Py_NotImplemented PyExc_RuntimeError -# endif -#endif - -/* A crude PyString_AsStringAndSize implementation for old Pythons */ -#if PY_VERSION_HEX < 0x02010000 -# ifndef PyString_AsStringAndSize -# define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} -# endif -#endif - -/* PySequence_Size for old Pythons */ -#if PY_VERSION_HEX < 0x02000000 -# ifndef PySequence_Size -# define PySequence_Size PySequence_Length -# endif -#endif - -/* PyBool_FromLong for old Pythons */ -#if PY_VERSION_HEX < 0x02030000 -static -PyObject *PyBool_FromLong(long ok) -{ - PyObject *result = ok ? Py_True : Py_False; - Py_INCREF(result); - return result; -} -#endif - -/* Py_ssize_t for old Pythons */ -/* This code is as recommended by: */ -/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ -#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) -typedef int Py_ssize_t; -# define PY_SSIZE_T_MAX INT_MAX -# define PY_SSIZE_T_MIN INT_MIN -#endif - -/* ----------------------------------------------------------------------------- - * error manipulation - * ----------------------------------------------------------------------------- */ - -SWIGRUNTIME PyObject* -SWIG_Python_ErrorType(int code) { - PyObject* type = 0; - switch(code) { - case SWIG_MemoryError: - type = PyExc_MemoryError; - break; - case SWIG_IOError: - type = PyExc_IOError; - break; - case SWIG_RuntimeError: - type = PyExc_RuntimeError; - break; - case SWIG_IndexError: - type = PyExc_IndexError; - break; - case SWIG_TypeError: - type = PyExc_TypeError; - break; - case SWIG_DivisionByZero: - type = PyExc_ZeroDivisionError; - break; - case SWIG_OverflowError: - type = PyExc_OverflowError; - break; - case SWIG_SyntaxError: - type = PyExc_SyntaxError; - break; - case SWIG_ValueError: - type = PyExc_ValueError; - break; - case SWIG_SystemError: - type = PyExc_SystemError; - break; - case SWIG_AttributeError: - type = PyExc_AttributeError; - break; - default: - type = PyExc_RuntimeError; - } - return type; -} - - -SWIGRUNTIME void -SWIG_Python_AddErrorMsg(const char* mesg) -{ - PyObject *type = 0; - PyObject *value = 0; - PyObject *traceback = 0; - - if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); - if (value) { - char *tmp; - PyObject *old_str = PyObject_Str(value); - PyErr_Clear(); - Py_XINCREF(type); - - PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); - SWIG_Python_str_DelForPy3(tmp); - Py_DECREF(old_str); - Py_DECREF(value); - } else { - PyErr_SetString(PyExc_RuntimeError, mesg); - } -} - -#if defined(SWIG_PYTHON_NO_THREADS) -# if defined(SWIG_PYTHON_THREADS) -# undef SWIG_PYTHON_THREADS -# endif -#endif -#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ -# if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) -# if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ -# define SWIG_PYTHON_USE_GIL -# endif -# endif -# if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ -# ifndef SWIG_PYTHON_INITIALIZE_THREADS -# define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() -# endif -# ifdef __cplusplus /* C++ code */ - class SWIG_Python_Thread_Block { - bool status; - PyGILState_STATE state; - public: - void end() { if (status) { PyGILState_Release(state); status = false;} } - SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} - ~SWIG_Python_Thread_Block() { end(); } - }; - class SWIG_Python_Thread_Allow { - bool status; - PyThreadState *save; - public: - void end() { if (status) { PyEval_RestoreThread(save); status = false; }} - SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} - ~SWIG_Python_Thread_Allow() { end(); } - }; -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block -# define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow -# define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() -# else /* C code */ -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() -# define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() -# define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) -# endif -# else /* Old thread way, not implemented, user must provide it */ -# if !defined(SWIG_PYTHON_INITIALIZE_THREADS) -# define SWIG_PYTHON_INITIALIZE_THREADS -# endif -# if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK -# endif -# if !defined(SWIG_PYTHON_THREAD_END_BLOCK) -# define SWIG_PYTHON_THREAD_END_BLOCK -# endif -# if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW -# endif -# if !defined(SWIG_PYTHON_THREAD_END_ALLOW) -# define SWIG_PYTHON_THREAD_END_ALLOW -# endif -# endif -#else /* No thread support */ -# define SWIG_PYTHON_INITIALIZE_THREADS -# define SWIG_PYTHON_THREAD_BEGIN_BLOCK -# define SWIG_PYTHON_THREAD_END_BLOCK -# define SWIG_PYTHON_THREAD_BEGIN_ALLOW -# define SWIG_PYTHON_THREAD_END_ALLOW -#endif - -/* ----------------------------------------------------------------------------- - * Python API portion that goes into the runtime - * ----------------------------------------------------------------------------- */ - -#ifdef __cplusplus -extern "C" { -#if 0 -} /* cc-mode */ -#endif -#endif - -/* ----------------------------------------------------------------------------- - * Constant declarations - * ----------------------------------------------------------------------------- */ - -/* Constant Types */ -#define SWIG_PY_POINTER 4 -#define SWIG_PY_BINARY 5 - -/* Constant information structure */ -typedef struct swig_const_info { - int type; - char *name; - long lvalue; - double dvalue; - void *pvalue; - swig_type_info **ptype; -} swig_const_info; - - -/* ----------------------------------------------------------------------------- - * Wrapper of PyInstanceMethod_New() used in Python 3 - * It is exported to the generated module, used for -fastproxy - * ----------------------------------------------------------------------------- */ -SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *self, PyObject *func) -{ -#if PY_VERSION_HEX >= 0x03000000 - return PyInstanceMethod_New(func); -#else - return NULL; -#endif -} - -#ifdef __cplusplus -#if 0 -{ /* cc-mode */ -#endif -} -#endif - - -/* ----------------------------------------------------------------------------- - * pyrun.swg - * - * This file contains the runtime support for Python modules - * and includes code for managing global variables and pointer - * type checking. - * - * ----------------------------------------------------------------------------- */ - -/* Common SWIG API */ - -/* for raw pointers */ -#define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) -#define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) -#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) -#define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(ptr, type, flags) -#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) -#define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) -#define swig_owntype int - -/* for raw packed data */ -#define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) -#define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) - -/* for class or struct pointers */ -#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) -#define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) - -/* for C or C++ function pointers */ -#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) -#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(ptr, type, 0) - -/* for C++ member pointers, ie, member methods */ -#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) -#define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) - - -/* Runtime API */ - -#define SWIG_GetModule(clientdata) SWIG_Python_GetModule() -#define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) -#define SWIG_NewClientData(obj) SwigPyClientData_New(obj) - -#define SWIG_SetErrorObj SWIG_Python_SetErrorObj -#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg -#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) -#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) -#define SWIG_fail goto fail - -/* - * Python 2.7 and newer and Python 3.1 and newer should use Capsules API instead of - * CObjects API. - */ -#if ((PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 6) || \ - (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION > 0)) -#define USE_CAPSULES -#define TYPE_POINTER_NAME \ - ((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION ".type_pointer_capsule" SWIG_TYPE_TABLE_NAME) -#endif - -/* Runtime API implementation */ - -/* Error manipulation */ - -SWIGINTERN void -SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetObject(errtype, obj); - Py_DECREF(obj); - SWIG_PYTHON_THREAD_END_BLOCK; -} - -SWIGINTERN void -SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(errtype, (char *) msg); - SWIG_PYTHON_THREAD_END_BLOCK; -} - -#define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) - -/* Set a constant value */ - -SWIGINTERN void -SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { - PyDict_SetItemString(d, (char*) name, obj); - Py_DECREF(obj); -} - -/* Append a value to the result obj */ - -SWIGINTERN PyObject* -SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { -#if !defined(SWIG_PYTHON_OUTPUT_TUPLE) - if (!result) { - result = obj; - } else if (result == Py_None) { - Py_DECREF(result); - result = obj; - } else { - if (!PyList_Check(result)) { - PyObject *o2 = result; - result = PyList_New(1); - PyList_SetItem(result, 0, o2); - } - PyList_Append(result,obj); - Py_DECREF(obj); - } - return result; -#else - PyObject* o2; - PyObject* o3; - if (!result) { - result = obj; - } else if (result == Py_None) { - Py_DECREF(result); - result = obj; - } else { - if (!PyTuple_Check(result)) { - o2 = result; - result = PyTuple_New(1); - PyTuple_SET_ITEM(result, 0, o2); - } - o3 = PyTuple_New(1); - PyTuple_SET_ITEM(o3, 0, obj); - o2 = result; - result = PySequence_Concat(o2, o3); - Py_DECREF(o2); - Py_DECREF(o3); - } - return result; -#endif -} - -/* Unpack the argument tuple */ - -SWIGINTERN int -SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) -{ - if (!args) { - if (!min && !max) { - return 1; - } else { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", - name, (min == max ? "" : "at least "), (int)min); - return 0; - } - } - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); - return 0; - } else { - register Py_ssize_t l = PyTuple_GET_SIZE(args); - if (l < min) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at least "), (int)min, (int)l); - return 0; - } else if (l > max) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at most "), (int)max, (int)l); - return 0; - } else { - register int i; - for (i = 0; i < l; ++i) { - objs[i] = PyTuple_GET_ITEM(args, i); - } - for (; l < max; ++l) { - objs[l] = 0; - } - return i + 1; - } - } -} - -/* A functor is a function object with one single object argument */ -#if PY_VERSION_HEX >= 0x02020000 -#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); -#else -#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); -#endif - -/* - Helper for static pointer initialization for both C and C++ code, for example - static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); -*/ -#ifdef __cplusplus -#define SWIG_STATIC_POINTER(var) var -#else -#define SWIG_STATIC_POINTER(var) var = 0; if (!var) var -#endif - -/* ----------------------------------------------------------------------------- - * Pointer declarations - * ----------------------------------------------------------------------------- */ - -/* Flags for new pointer objects */ -#define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) -#define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) - -#define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) - -#ifdef __cplusplus -extern "C" { -#if 0 -} /* cc-mode */ -#endif -#endif - -/* How to access Py_None */ -#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) -# ifndef SWIG_PYTHON_NO_BUILD_NONE -# ifndef SWIG_PYTHON_BUILD_NONE -# define SWIG_PYTHON_BUILD_NONE -# endif -# endif -#endif - -#ifdef SWIG_PYTHON_BUILD_NONE -# ifdef Py_None -# undef Py_None -# define Py_None SWIG_Py_None() -# endif -SWIGRUNTIMEINLINE PyObject * -_SWIG_Py_None(void) -{ - PyObject *none = Py_BuildValue((char*)""); - Py_DECREF(none); - return none; -} -SWIGRUNTIME PyObject * -SWIG_Py_None(void) -{ - static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); - return none; -} -#endif - -/* The python void return value */ - -SWIGRUNTIMEINLINE PyObject * -SWIG_Py_Void(void) -{ - PyObject *none = Py_None; - Py_INCREF(none); - return none; -} - -/* SwigPyClientData */ - -typedef struct { - PyObject *klass; - PyObject *newraw; - PyObject *newargs; - PyObject *destroy; - int delargs; - int implicitconv; -} SwigPyClientData; - -SWIGRUNTIMEINLINE int -SWIG_Python_CheckImplicit(swig_type_info *ty) -{ - SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; - return data ? data->implicitconv : 0; -} - -SWIGRUNTIMEINLINE PyObject * -SWIG_Python_ExceptionType(swig_type_info *desc) { - SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; - PyObject *klass = data ? data->klass : 0; - return (klass ? klass : PyExc_RuntimeError); -} - - -SWIGRUNTIME SwigPyClientData * -SwigPyClientData_New(PyObject* obj) -{ - if (!obj) { - return 0; - } else { - SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); - /* the klass element */ - data->klass = obj; - Py_INCREF(data->klass); - /* the newraw method and newargs arguments used to create a new raw instance */ - if (PyClass_Check(obj)) { - data->newraw = 0; - data->newargs = obj; - Py_INCREF(obj); - } else { -#if (PY_VERSION_HEX < 0x02020000) - data->newraw = 0; -#else - data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); -#endif - if (data->newraw) { - Py_INCREF(data->newraw); - data->newargs = PyTuple_New(1); - PyTuple_SetItem(data->newargs, 0, obj); - } else { - data->newargs = obj; - } - Py_INCREF(data->newargs); - } - /* the destroy method, aka as the C++ delete method */ - data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); - if (PyErr_Occurred()) { - PyErr_Clear(); - data->destroy = 0; - } - if (data->destroy) { - int flags; - Py_INCREF(data->destroy); - flags = PyCFunction_GET_FLAGS(data->destroy); -#ifdef METH_O - data->delargs = !(flags & (METH_O)); -#else - data->delargs = 0; -#endif - } else { - data->delargs = 0; - } - data->implicitconv = 0; - return data; - } -} - -SWIGRUNTIME void -SwigPyClientData_Del(SwigPyClientData* data) -{ - Py_XDECREF(data->newraw); - Py_XDECREF(data->newargs); - Py_XDECREF(data->destroy); -} - -/* =============== SwigPyObject =====================*/ - -typedef struct { - PyObject_HEAD - void *ptr; - swig_type_info *ty; - int own; - PyObject *next; -} SwigPyObject; - -SWIGRUNTIME PyObject * -SwigPyObject_long(SwigPyObject *v) -{ - return PyLong_FromVoidPtr(v->ptr); -} - -SWIGRUNTIME PyObject * -SwigPyObject_format(const char* fmt, SwigPyObject *v) -{ - PyObject *res = NULL; - PyObject *args = PyTuple_New(1); - if (args) { - if (PyTuple_SetItem(args, 0, SwigPyObject_long(v)) == 0) { - PyObject *ofmt = SWIG_Python_str_FromChar(fmt); - if (ofmt) { -#if PY_VERSION_HEX >= 0x03000000 - res = PyUnicode_Format(ofmt,args); -#else - res = PyString_Format(ofmt,args); -#endif - Py_DECREF(ofmt); - } - Py_DECREF(args); - } - } - return res; -} - -SWIGRUNTIME PyObject * -SwigPyObject_oct(SwigPyObject *v) -{ - return SwigPyObject_format("%o",v); -} - -SWIGRUNTIME PyObject * -SwigPyObject_hex(SwigPyObject *v) -{ - return SwigPyObject_format("%x",v); -} - -SWIGRUNTIME PyObject * -#ifdef METH_NOARGS -SwigPyObject_repr(SwigPyObject *v) -#else -SwigPyObject_repr(SwigPyObject *v, PyObject *args) -#endif -{ - const char *name = SWIG_TypePrettyName(v->ty); - PyObject *repr = SWIG_Python_str_FromFormat("", name, v); - if (v->next) { -#ifdef METH_NOARGS - PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); -#else - PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next, args); -#endif -#if PY_VERSION_HEX >= 0x03000000 - PyObject *joined = PyUnicode_Concat(repr, nrep); - Py_DecRef(repr); - Py_DecRef(nrep); - repr = joined; -#else - PyString_ConcatAndDel(&repr,nrep); -#endif - } - return repr; -} - -SWIGRUNTIME int -SwigPyObject_print(SwigPyObject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) -{ - char *str; -#ifdef METH_NOARGS - PyObject *repr = SwigPyObject_repr(v); -#else - PyObject *repr = SwigPyObject_repr(v, NULL); -#endif - if (repr) { - str = SWIG_Python_str_AsChar(repr); - fputs(str, fp); - SWIG_Python_str_DelForPy3(str); - Py_DECREF(repr); - return 0; - } else { - return 1; - } -} - -SWIGRUNTIME PyObject * -SwigPyObject_str(SwigPyObject *v) -{ - char result[SWIG_BUFFER_SIZE]; - return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ? - SWIG_Python_str_FromChar(result) : 0; -} - -SWIGRUNTIME int -SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) -{ - void *i = v->ptr; - void *j = w->ptr; - return (i < j) ? -1 : ((i > j) ? 1 : 0); -} - -/* Added for Python 3.x, would it also be useful for Python 2.x? */ -SWIGRUNTIME PyObject* -SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) -{ - PyObject* res; - if( op != Py_EQ && op != Py_NE ) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ) - res = Py_True; - else - res = Py_False; - Py_INCREF(res); - return res; -} - - -SWIGRUNTIME PyTypeObject* _PySwigObject_type(void); - -SWIGRUNTIME PyTypeObject* -SwigPyObject_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type(); - return type; -} - -SWIGRUNTIMEINLINE int -SwigPyObject_Check(PyObject *op) { - return (Py_TYPE(op) == SwigPyObject_type()) - || (strcmp(Py_TYPE(op)->tp_name,"SwigPyObject") == 0); -} - -SWIGRUNTIME PyObject * -SwigPyObject_New(void *ptr, swig_type_info *ty, int own); - -SWIGRUNTIME void -SwigPyObject_dealloc(PyObject *v) -{ - SwigPyObject *sobj = (SwigPyObject *) v; - PyObject *next = sobj->next; - if (sobj->own == SWIG_POINTER_OWN) { - swig_type_info *ty = sobj->ty; - SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; - PyObject *destroy = data ? data->destroy : 0; - if (destroy) { - /* destroy is always a VARARGS method */ - PyObject *res; - if (data->delargs) { - /* we need to create a temporary object to carry the destroy operation */ - PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); - res = SWIG_Python_CallFunctor(destroy, tmp); - Py_DECREF(tmp); - } else { - PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); - PyObject *mself = PyCFunction_GET_SELF(destroy); - res = ((*meth)(mself, v)); - } - Py_XDECREF(res); - } -#if !defined(SWIG_PYTHON_SILENT_MEMLEAK) - else { - const char *name = SWIG_TypePrettyName(ty); - printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); - } -#endif - } - Py_XDECREF(next); - PyObject_DEL(v); -} - -SWIGRUNTIME PyObject* -SwigPyObject_append(PyObject* v, PyObject* next) -{ - SwigPyObject *sobj = (SwigPyObject *) v; -#ifndef METH_O - PyObject *tmp = 0; - if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; - next = tmp; -#endif - if (!SwigPyObject_Check(next)) { - return NULL; - } - sobj->next = next; - Py_INCREF(next); - return SWIG_Py_Void(); -} - -SWIGRUNTIME PyObject* -#ifdef METH_NOARGS -SwigPyObject_next(PyObject* v) -#else -SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -#endif -{ - SwigPyObject *sobj = (SwigPyObject *) v; - if (sobj->next) { - Py_INCREF(sobj->next); - return sobj->next; - } else { - return SWIG_Py_Void(); - } -} - -SWIGINTERN PyObject* -#ifdef METH_NOARGS -SwigPyObject_disown(PyObject *v) -#else -SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -#endif -{ - SwigPyObject *sobj = (SwigPyObject *)v; - sobj->own = 0; - return SWIG_Py_Void(); -} - -SWIGINTERN PyObject* -#ifdef METH_NOARGS -SwigPyObject_acquire(PyObject *v) -#else -SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -#endif -{ - SwigPyObject *sobj = (SwigPyObject *)v; - sobj->own = SWIG_POINTER_OWN; - return SWIG_Py_Void(); -} - -SWIGINTERN PyObject* -SwigPyObject_own(PyObject *v, PyObject *args) -{ - PyObject *val = 0; -#if (PY_VERSION_HEX < 0x02020000) - if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) -#else - if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) -#endif - { - return NULL; - } - else - { - SwigPyObject *sobj = (SwigPyObject *)v; - PyObject *obj = PyBool_FromLong(sobj->own); - if (val) { -#ifdef METH_NOARGS - if (PyObject_IsTrue(val)) { - SwigPyObject_acquire(v); - } else { - SwigPyObject_disown(v); - } -#else - if (PyObject_IsTrue(val)) { - SwigPyObject_acquire(v,args); - } else { - SwigPyObject_disown(v,args); - } -#endif - } - return obj; - } -} - -#ifdef METH_O -static PyMethodDef -swigobject_methods[] = { - {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, - {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_NOARGS, (char *)"aquires ownership of the pointer"}, - {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, - {(char *)"append", (PyCFunction)SwigPyObject_append, METH_O, (char *)"appends another 'this' object"}, - {(char *)"next", (PyCFunction)SwigPyObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, - {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_NOARGS, (char *)"returns object representation"}, - {0, 0, 0, 0} -}; -#else -static PyMethodDef -swigobject_methods[] = { - {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, - {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, - {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, - {(char *)"append", (PyCFunction)SwigPyObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, - {(char *)"next", (PyCFunction)SwigPyObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, - {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_VARARGS, (char *)"returns object representation"}, - {0, 0, 0, 0} -}; -#endif - -#if PY_VERSION_HEX < 0x02020000 -SWIGINTERN PyObject * -SwigPyObject_getattr(SwigPyObject *sobj,char *name) -{ - return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); -} -#endif - -SWIGRUNTIME PyTypeObject* -_PySwigObject_type(void) { - static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; - - static PyNumberMethods SwigPyObject_as_number = { - (binaryfunc)0, /*nb_add*/ - (binaryfunc)0, /*nb_subtract*/ - (binaryfunc)0, /*nb_multiply*/ - /* nb_divide removed in Python 3 */ -#if PY_VERSION_HEX < 0x03000000 - (binaryfunc)0, /*nb_divide*/ -#endif - (binaryfunc)0, /*nb_remainder*/ - (binaryfunc)0, /*nb_divmod*/ - (ternaryfunc)0,/*nb_power*/ - (unaryfunc)0, /*nb_negative*/ - (unaryfunc)0, /*nb_positive*/ - (unaryfunc)0, /*nb_absolute*/ - (inquiry)0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ -#if PY_VERSION_HEX < 0x03000000 - 0, /*nb_coerce*/ -#endif - (unaryfunc)SwigPyObject_long, /*nb_int*/ -#if PY_VERSION_HEX < 0x03000000 - (unaryfunc)SwigPyObject_long, /*nb_long*/ -#else - 0, /*nb_reserved*/ -#endif - (unaryfunc)0, /*nb_float*/ -#if PY_VERSION_HEX < 0x03000000 - (unaryfunc)SwigPyObject_oct, /*nb_oct*/ - (unaryfunc)SwigPyObject_hex, /*nb_hex*/ -#endif -#if PY_VERSION_HEX >= 0x03000000 /* 3.0 */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ -#elif PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ -#elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ -#elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ - 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ -#endif - }; - - static PyTypeObject swigpyobject_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp - = { - /* PyObject header changed in Python 3 */ -#if PY_VERSION_HEX >= 0x03000000 - PyVarObject_HEAD_INIT(&PyType_Type, 0) -#else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ -#endif - (char *)"SwigPyObject", /* tp_name */ - sizeof(SwigPyObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)SwigPyObject_dealloc, /* tp_dealloc */ - (printfunc)SwigPyObject_print, /* tp_print */ -#if PY_VERSION_HEX < 0x02020000 - (getattrfunc)SwigPyObject_getattr, /* tp_getattr */ -#else - (getattrfunc)0, /* tp_getattr */ -#endif - (setattrfunc)0, /* tp_setattr */ -#if PY_VERSION_HEX >= 0x03000000 - 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ -#else - (cmpfunc)SwigPyObject_compare, /* tp_compare */ -#endif - (reprfunc)SwigPyObject_repr, /* tp_repr */ - &SwigPyObject_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)SwigPyObject_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigobject_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)SwigPyObject_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ -#if PY_VERSION_HEX >= 0x02020000 - 0, /* tp_iter */ - 0, /* tp_iternext */ - swigobject_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ -#endif -#if PY_VERSION_HEX >= 0x02030000 - 0, /* tp_del */ -#endif -#ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ -#endif - }; - swigpyobject_type = tmp; - /* for Python 3 we already assigned ob_type in PyVarObject_HEAD_INIT() */ -#if PY_VERSION_HEX < 0x03000000 - swigpyobject_type.ob_type = &PyType_Type; -#endif - type_init = 1; - } - return &swigpyobject_type; -} - -SWIGRUNTIME PyObject * -SwigPyObject_New(void *ptr, swig_type_info *ty, int own) -{ - SwigPyObject *sobj = PyObject_NEW(SwigPyObject, SwigPyObject_type()); - if (sobj) { - sobj->ptr = ptr; - sobj->ty = ty; - sobj->own = own; - sobj->next = 0; - } - return (PyObject *)sobj; -} - -/* ----------------------------------------------------------------------------- - * Implements a simple Swig Packed type, and use it instead of string - * ----------------------------------------------------------------------------- */ - -typedef struct { - PyObject_HEAD - void *pack; - swig_type_info *ty; - size_t size; -} SwigPyPacked; - -SWIGRUNTIME int -SwigPyPacked_print(SwigPyPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) -{ - char result[SWIG_BUFFER_SIZE]; - fputs("pack, v->size, 0, sizeof(result))) { - fputs("at ", fp); - fputs(result, fp); - } - fputs(v->ty->name,fp); - fputs(">", fp); - return 0; -} - -SWIGRUNTIME PyObject * -SwigPyPacked_repr(SwigPyPacked *v) -{ - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { - return SWIG_Python_str_FromFormat("", result, v->ty->name); - } else { - return SWIG_Python_str_FromFormat("", v->ty->name); - } -} - -SWIGRUNTIME PyObject * -SwigPyPacked_str(SwigPyPacked *v) -{ - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ - return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); - } else { - return SWIG_Python_str_FromChar(v->ty->name); - } -} - -SWIGRUNTIME int -SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) -{ - size_t i = v->size; - size_t j = w->size; - int s = (i < j) ? -1 : ((i > j) ? 1 : 0); - return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); -} - -SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void); - -SWIGRUNTIME PyTypeObject* -SwigPyPacked_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type(); - return type; -} - -SWIGRUNTIMEINLINE int -SwigPyPacked_Check(PyObject *op) { - return ((op)->ob_type == _PySwigPacked_type()) - || (strcmp((op)->ob_type->tp_name,"SwigPyPacked") == 0); -} - -SWIGRUNTIME void -SwigPyPacked_dealloc(PyObject *v) -{ - if (SwigPyPacked_Check(v)) { - SwigPyPacked *sobj = (SwigPyPacked *) v; - free(sobj->pack); - } - PyObject_DEL(v); -} - -SWIGRUNTIME PyTypeObject* -_PySwigPacked_type(void) { - static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; - static PyTypeObject swigpypacked_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp - = { - /* PyObject header changed in Python 3 */ -#if PY_VERSION_HEX>=0x03000000 - PyVarObject_HEAD_INIT(&PyType_Type, 0) -#else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ -#endif - (char *)"SwigPyPacked", /* tp_name */ - sizeof(SwigPyPacked), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ - (printfunc)SwigPyPacked_print, /* tp_print */ - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ -#if PY_VERSION_HEX>=0x03000000 - 0, /* tp_reserved in 3.0.1 */ -#else - (cmpfunc)SwigPyPacked_compare, /* tp_compare */ -#endif - (reprfunc)SwigPyPacked_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)SwigPyPacked_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigpacked_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ -#if PY_VERSION_HEX >= 0x02020000 - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ -#endif -#if PY_VERSION_HEX >= 0x02030000 - 0, /* tp_del */ -#endif -#ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ -#endif - }; - swigpypacked_type = tmp; - /* for Python 3 the ob_type already assigned in PyVarObject_HEAD_INIT() */ -#if PY_VERSION_HEX < 0x03000000 - swigpypacked_type.ob_type = &PyType_Type; -#endif - type_init = 1; - } - return &swigpypacked_type; -} - -SWIGRUNTIME PyObject * -SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) -{ - SwigPyPacked *sobj = PyObject_NEW(SwigPyPacked, SwigPyPacked_type()); - if (sobj) { - void *pack = malloc(size); - if (pack) { - memcpy(pack, ptr, size); - sobj->pack = pack; - sobj->ty = ty; - sobj->size = size; - } else { - PyObject_DEL((PyObject *) sobj); - sobj = 0; - } - } - return (PyObject *) sobj; -} - -SWIGRUNTIME swig_type_info * -SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) -{ - if (SwigPyPacked_Check(obj)) { - SwigPyPacked *sobj = (SwigPyPacked *)obj; - if (sobj->size != size) return 0; - memcpy(ptr, sobj->pack, size); - return sobj->ty; - } else { - return 0; - } -} - -/* ----------------------------------------------------------------------------- - * pointers/data manipulation - * ----------------------------------------------------------------------------- */ - -SWIGRUNTIMEINLINE PyObject * -_SWIG_This(void) -{ - return SWIG_Python_str_FromChar("this"); -} - -static PyObject *swig_this = NULL; - -SWIGRUNTIME PyObject * -SWIG_This(void) -{ - if (swig_this == NULL) - swig_this = _SWIG_This(); - return swig_this; -} - -/* #define SWIG_PYTHON_SLOW_GETSET_THIS */ - -/* TODO: I don't know how to implement the fast getset in Python 3 right now */ -#if PY_VERSION_HEX>=0x03000000 -#define SWIG_PYTHON_SLOW_GETSET_THIS -#endif - -SWIGRUNTIME SwigPyObject * -SWIG_Python_GetSwigThis(PyObject *pyobj) -{ - if (SwigPyObject_Check(pyobj)) { - return (SwigPyObject *) pyobj; - } else { - PyObject *obj = 0; -#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) - if (PyInstance_Check(pyobj)) { - obj = _PyInstance_Lookup(pyobj, SWIG_This()); - } else { - PyObject **dictptr = _PyObject_GetDictPtr(pyobj); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; - } else { -#ifdef PyWeakref_CheckProxy - if (PyWeakref_CheckProxy(pyobj)) { - PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); - return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; - } -#endif - obj = PyObject_GetAttr(pyobj,SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } - } - } -#else - obj = PyObject_GetAttr(pyobj,SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } -#endif - if (obj && !SwigPyObject_Check(obj)) { - /* a PyObject is called 'this', try to get the 'real this' - SwigPyObject from it */ - return SWIG_Python_GetSwigThis(obj); - } - return (SwigPyObject *)obj; - } -} - -/* Acquire a pointer value */ - -SWIGRUNTIME int -SWIG_Python_AcquirePtr(PyObject *obj, int own) { - if (own == SWIG_POINTER_OWN) { - SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); - if (sobj) { - int oldown = sobj->own; - sobj->own = own; - return oldown; - } - } - return 0; -} - -/* Convert a pointer value */ - -SWIGRUNTIME int -SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { - if (!obj) return SWIG_ERROR; - if (obj == Py_None) { - if (ptr) *ptr = 0; - return SWIG_OK; - } else { - SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); - if (own) - *own = 0; - while (sobj) { - void *vptr = sobj->ptr; - if (ty) { - swig_type_info *to = sobj->ty; - if (to == ty) { - /* no type cast needed */ - if (ptr) *ptr = vptr; - break; - } else { - swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); - if (!tc) { - sobj = (SwigPyObject *)sobj->next; - } else { - if (ptr) { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc,vptr,&newmemory); - if (newmemory == SWIG_CAST_NEW_MEMORY) { - assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ - if (own) - *own = *own | SWIG_CAST_NEW_MEMORY; - } - } - break; - } - } - } else { - if (ptr) *ptr = vptr; - break; - } - } - if (sobj) { - if (own) - *own = *own | sobj->own; - if (flags & SWIG_POINTER_DISOWN) { - sobj->own = 0; - } - return SWIG_OK; - } else { - int res = SWIG_ERROR; - if (flags & SWIG_POINTER_IMPLICIT_CONV) { - SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; - if (data && !data->implicitconv) { - PyObject *klass = data->klass; - if (klass) { - PyObject *impconv; - data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ - impconv = SWIG_Python_CallFunctor(klass, obj); - data->implicitconv = 0; - if (PyErr_Occurred()) { - PyErr_Clear(); - impconv = 0; - } - if (impconv) { - SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); - if (iobj) { - void *vptr; - res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); - if (SWIG_IsOK(res)) { - if (ptr) { - *ptr = vptr; - /* transfer the ownership to 'ptr' */ - iobj->own = 0; - res = SWIG_AddCast(res); - res = SWIG_AddNewMask(res); - } else { - res = SWIG_AddCast(res); - } - } - } - Py_DECREF(impconv); - } - } - } - } - return res; - } - } -} - -/* Convert a function ptr value */ - -SWIGRUNTIME int -SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { - if (!PyCFunction_Check(obj)) { - return SWIG_ConvertPtr(obj, ptr, ty, 0); - } else { - void *vptr = 0; - - /* here we get the method pointer for callbacks */ - const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); - const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; - if (desc) - desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; - if (!desc) - return SWIG_ERROR; - if (ty) { - swig_cast_info *tc = SWIG_TypeCheck(desc,ty); - if (tc) { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc,vptr,&newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ - } else { - return SWIG_ERROR; - } - } else { - *ptr = vptr; - } - return SWIG_OK; - } -} - -/* Convert a packed value value */ - -SWIGRUNTIME int -SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { - swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); - if (!to) return SWIG_ERROR; - if (ty) { - if (to != ty) { - /* check type cast? */ - swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); - if (!tc) return SWIG_ERROR; - } - } - return SWIG_OK; -} - -/* ----------------------------------------------------------------------------- - * Create a new pointer object - * ----------------------------------------------------------------------------- */ - -/* - Create a new instance object, without calling __init__, and set the - 'this' attribute. -*/ - -SWIGRUNTIME PyObject* -SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) -{ -#if (PY_VERSION_HEX >= 0x02020000) - PyObject *inst = 0; - PyObject *newraw = data->newraw; - if (newraw) { - inst = PyObject_Call(newraw, data->newargs, NULL); - if (inst) { -#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - PyObject **dictptr = _PyObject_GetDictPtr(inst); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict == NULL) { - dict = PyDict_New(); - *dictptr = dict; - PyDict_SetItem(dict, SWIG_This(), swig_this); - } - } -#else - PyObject *key = SWIG_This(); - PyObject_SetAttr(inst, key, swig_this); -#endif - } - } else { -#if PY_VERSION_HEX >= 0x03000000 - inst = PyBaseObject_Type.tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); - PyObject_SetAttr(inst, SWIG_This(), swig_this); - Py_TYPE(inst)->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; -#else - PyObject *dict = PyDict_New(); - PyDict_SetItem(dict, SWIG_This(), swig_this); - inst = PyInstance_NewRaw(data->newargs, dict); - Py_DECREF(dict); -#endif - } - return inst; -#else -#if (PY_VERSION_HEX >= 0x02010000) - PyObject *inst; - PyObject *dict = PyDict_New(); - PyDict_SetItem(dict, SWIG_This(), swig_this); - inst = PyInstance_NewRaw(data->newargs, dict); - Py_DECREF(dict); - return (PyObject *) inst; -#else - PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); - if (inst == NULL) { - return NULL; - } - inst->in_class = (PyClassObject *)data->newargs; - Py_INCREF(inst->in_class); - inst->in_dict = PyDict_New(); - if (inst->in_dict == NULL) { - Py_DECREF(inst); - return NULL; - } -#ifdef Py_TPFLAGS_HAVE_WEAKREFS - inst->in_weakreflist = NULL; -#endif -#ifdef Py_TPFLAGS_GC - PyObject_GC_Init(inst); -#endif - PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); - return (PyObject *) inst; -#endif -#endif -} - -SWIGRUNTIME void -SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) -{ - PyObject *dict; -#if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - PyObject **dictptr = _PyObject_GetDictPtr(inst); - if (dictptr != NULL) { - dict = *dictptr; - if (dict == NULL) { - dict = PyDict_New(); - *dictptr = dict; - } - PyDict_SetItem(dict, SWIG_This(), swig_this); - return; - } -#endif - dict = PyObject_GetAttrString(inst, (char*)"__dict__"); - PyDict_SetItem(dict, SWIG_This(), swig_this); - Py_DECREF(dict); -} - - -SWIGINTERN PyObject * -SWIG_Python_InitShadowInstance(PyObject *args) { - PyObject *obj[2]; - if (!SWIG_Python_UnpackTuple(args,(char*)"swiginit", 2, 2, obj)) { - return NULL; - } else { - SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); - if (sthis) { - SwigPyObject_append((PyObject*) sthis, obj[1]); - } else { - SWIG_Python_SetSwigThis(obj[0], obj[1]); - } - return SWIG_Py_Void(); - } -} - -/* Create a new pointer object */ - -SWIGRUNTIME PyObject * -SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) { - if (!ptr) { - return SWIG_Py_Void(); - } else { - int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; - PyObject *robj = SwigPyObject_New(ptr, type, own); - SwigPyClientData *clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; - if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { - PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); - if (inst) { - Py_DECREF(robj); - robj = inst; - } - } - return robj; - } -} - -/* Create a new packed object */ - -SWIGRUNTIMEINLINE PyObject * -SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { - return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); -} - -/* -----------------------------------------------------------------------------* - * Get type list - * -----------------------------------------------------------------------------*/ - -#ifdef SWIG_LINK_RUNTIME -void *SWIG_ReturnGlobalTypeList(void *); -#endif - -SWIGRUNTIME swig_module_info * -SWIG_Python_GetModule(void) { - static void *type_pointer = (void *)0; - /* first check if module already created */ - if (!type_pointer) { -#ifdef SWIG_LINK_RUNTIME - type_pointer = SWIG_ReturnGlobalTypeList((void *)0); -#else -#ifdef USE_CAPSULES - type_pointer = PyCapsule_Import(TYPE_POINTER_NAME, 0); -#else - type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, - (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); -#endif - if (PyErr_Occurred()) { - PyErr_Clear(); - type_pointer = (void *)0; - } -#endif - } - return (swig_module_info *) type_pointer; -} - -#if PY_MAJOR_VERSION < 2 -/* PyModule_AddObject function was introduced in Python 2.0. The following function - is copied out of Python/modsupport.c in python version 2.3.4 */ -SWIGINTERN int -PyModule_AddObject(PyObject *m, char *name, PyObject *o) -{ - PyObject *dict; - if (!PyModule_Check(m)) { - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs module as first arg"); - return SWIG_ERROR; - } - if (!o) { - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs non-NULL value"); - return SWIG_ERROR; - } - - dict = PyModule_GetDict(m); - if (dict == NULL) { - /* Internal error -- modules must have a dict! */ - PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", - PyModule_GetName(m)); - return SWIG_ERROR; - } - if (PyDict_SetItemString(dict, name, o)) - return SWIG_ERROR; - Py_DECREF(o); - return SWIG_OK; -} -#endif - -SWIGRUNTIME void -SWIG_Python_DestroyModule(void *vptr) -{ - size_t i; -#ifdef USE_CAPSULES - swig_module_info *swig_module = - (swig_module_info *) PyCapsule_GetPointer((PyObject *)vptr, TYPE_POINTER_NAME); -#else - swig_module_info *swig_module = (swig_module_info *) vptr; -#endif - swig_type_info **types = swig_module->types; - for (i =0; i < swig_module->size; ++i) { - swig_type_info *ty = types[i]; - if (ty->owndata) { - SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; - if (data) SwigPyClientData_Del(data); - } - } - Py_DECREF(SWIG_This()); - swig_this = NULL; -} - -SWIGRUNTIME void -SWIG_Python_SetModule(swig_module_info *swig_module) { - static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */ - -#if PY_VERSION_HEX >= 0x03000000 - /* Add a dummy module object into sys.modules */ - PyObject *module = PyImport_AddModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION); -#else - PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, - swig_empty_runtime_method_table); -#endif -#ifdef USE_CAPSULES - PyObject *pointer = PyCapsule_New((void *)swig_module, TYPE_POINTER_NAME, - (PyCapsule_Destructor)SWIG_Python_DestroyModule); -#else - PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); -#endif - if (pointer && module) { -#ifdef USE_CAPSULES - PyModule_AddObject(module, (char*)"type_pointer_capsule" SWIG_TYPE_TABLE_NAME, pointer); -#else - PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer); -#endif - } else { - Py_XDECREF(pointer); - } -} - -/* The python cached type query */ -SWIGRUNTIME PyObject * -SWIG_Python_TypeCache(void) { - static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); - return cache; -} - -SWIGRUNTIME swig_type_info * -SWIG_Python_TypeQuery(const char *type) -{ - PyObject *cache = SWIG_Python_TypeCache(); - PyObject *key = SWIG_Python_str_FromChar(type); - PyObject *obj = PyDict_GetItem(cache, key); - swig_type_info *descriptor; - if (obj) { -#ifdef USE_CAPSULES - descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, type); -#else - descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); -#endif - } else { - swig_module_info *swig_module = SWIG_Python_GetModule(); - descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); - if (descriptor) { -#ifdef USE_CAPSULES - obj = PyCapsule_New(descriptor, type, NULL); -#else - obj = PyCObject_FromVoidPtr(descriptor, NULL); -#endif - PyDict_SetItem(cache, key, obj); - Py_DECREF(obj); - } - } - Py_DECREF(key); - return descriptor; -} - -/* - For backward compatibility only -*/ -#define SWIG_POINTER_EXCEPTION 0 -#define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) -#define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) - -SWIGRUNTIME int -SWIG_Python_AddErrMesg(const char* mesg, int infront) -{ - if (PyErr_Occurred()) { - PyObject *type = 0; - PyObject *value = 0; - PyObject *traceback = 0; - PyErr_Fetch(&type, &value, &traceback); - if (value) { - char *tmp; - PyObject *old_str = PyObject_Str(value); - Py_XINCREF(type); - PyErr_Clear(); - if (infront) { - PyErr_Format(type, "%s %s", mesg, tmp = SWIG_Python_str_AsChar(old_str)); - } else { - PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); - } - SWIG_Python_str_DelForPy3(tmp); - Py_DECREF(old_str); - } - return 1; - } else { - return 0; - } -} - -SWIGRUNTIME int -SWIG_Python_ArgFail(int argnum) -{ - if (PyErr_Occurred()) { - /* add information about failing argument */ - char mesg[256]; - PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); - return SWIG_Python_AddErrMesg(mesg, 1); - } else { - return 0; - } -} - -SWIGRUNTIMEINLINE const char * -SwigPyObject_GetDesc(PyObject *self) -{ - SwigPyObject *v = (SwigPyObject *)self; - swig_type_info *ty = v ? v->ty : 0; - return ty ? ty->str : (char*)""; -} - -SWIGRUNTIME void -SWIG_Python_TypeError(const char *type, PyObject *obj) -{ - if (type) { -#if defined(SWIG_COBJECT_TYPES) - if (obj && SwigPyObject_Check(obj)) { - const char *otype = (const char *) SwigPyObject_GetDesc(obj); - if (otype) { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", - type, otype); - return; - } - } else -#endif - { - const char *otype = (obj ? obj->ob_type->tp_name : 0); - if (otype) { - PyObject *str = PyObject_Str(obj); - const char *cstr = str ? SWIG_Python_str_AsChar(str) : 0; - if (cstr) { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", - type, otype, cstr); - SWIG_Python_str_DelForPy3(cstr); - } else { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", - type, otype); - } - Py_XDECREF(str); - return; - } - } - PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); - } else { - PyErr_Format(PyExc_TypeError, "unexpected type is received"); - } -} - - -/* Convert a pointer value, signal an exception on a type mismatch */ -SWIGRUNTIME void * -SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) { - void *result; - if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { - PyErr_Clear(); -#if SWIG_POINTER_EXCEPTION - if (flags) { - SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); - SWIG_Python_ArgFail(argnum); - } -#endif - } - return result; -} - - -#ifdef __cplusplus -#if 0 -{ /* cc-mode */ -#endif -} -#endif - - - -#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) - -#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else - - - -/* -------- TYPES TABLE (BEGIN) -------- */ - -#define SWIGTYPE_p_char swig_types[0] -static swig_type_info *swig_types[2]; -static swig_module_info swig_module = {swig_types, 1, 0, 0, 0, 0}; -#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) -#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) - -/* -------- TYPES TABLE (END) -------- */ - -#if (PY_VERSION_HEX <= 0x02000000) -# if !defined(SWIG_PYTHON_CLASSIC) -# error "This python version requires swig to be run with the '-classic' option" -# endif -#endif - -/*----------------------------------------------- - @(target):= _csgraph.so - ------------------------------------------------*/ -#if PY_VERSION_HEX >= 0x03000000 -# define SWIG_init PyInit__csgraph - -#else -# define SWIG_init init_csgraph - -#endif -#define SWIG_name "_csgraph" - -#define SWIGVERSION 0x020001 -#define SWIG_VERSION SWIGVERSION - - -#define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) -#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) - - -#include - - -namespace swig { - class SwigPtr_PyObject { - protected: - PyObject *_obj; - - public: - SwigPtr_PyObject() :_obj(0) - { - } - - SwigPtr_PyObject(const SwigPtr_PyObject& item) : _obj(item._obj) - { - Py_XINCREF(_obj); - } - - SwigPtr_PyObject(PyObject *obj, bool initial_ref = true) :_obj(obj) - { - if (initial_ref) { - Py_XINCREF(_obj); - } - } - - SwigPtr_PyObject & operator=(const SwigPtr_PyObject& item) - { - Py_XINCREF(item._obj); - Py_XDECREF(_obj); - _obj = item._obj; - return *this; - } - - ~SwigPtr_PyObject() - { - Py_XDECREF(_obj); - } - - operator PyObject *() const - { - return _obj; - } - - PyObject *operator->() const - { - return _obj; - } - }; -} - - -namespace swig { - struct SwigVar_PyObject : SwigPtr_PyObject { - SwigVar_PyObject(PyObject* obj = 0) : SwigPtr_PyObject(obj, false) { } - - SwigVar_PyObject & operator = (PyObject* obj) - { - Py_XDECREF(_obj); - _obj = obj; - return *this; - } - }; -} - - -#include "py3k.h" -#define SWIG_FILE_WITH_INIT -#include "Python.h" -#include "numpy/arrayobject.h" -#include "complex_ops.h" -/*#include "sparsetools.h"*/ - - -#ifndef SWIG_FILE_WITH_INIT -# define NO_IMPORT_ARRAY -#endif -#include "stdio.h" -#include -#include "complex_ops.h" - - -/* The following code originally appeared in - * enthought/kiva/agg/src/numeric.i written by Eric Jones. It was - * translated from C++ to C by John Hunter. Bill Spotz has modified - * it slightly to fix some minor bugs, upgrade to numpy (all - * versions), add some comments and some functionality. - */ - -/* Macros to extract array attributes. - */ -#define is_array(a) ((a) && PyArray_Check((PyArrayObject *)a)) -#define array_type(a) (int)(PyArray_TYPE(a)) -#define array_numdims(a) (((PyArrayObject *)a)->nd) -#define array_dimensions(a) (((PyArrayObject *)a)->dimensions) -#define array_size(a,i) (((PyArrayObject *)a)->dimensions[i]) -#define array_data(a) (((PyArrayObject *)a)->data) -#define array_is_contiguous(a) (PyArray_ISCONTIGUOUS(a)) -#define array_is_native(a) (PyArray_ISNOTSWAPPED(a)) - -/* Support older NumPy data type names -*/ -#if NDARRAY_VERSION < 0x01000000 -#define NPY_BOOL PyArray_BOOL -#define NPY_BYTE PyArray_BYTE -#define NPY_UBYTE PyArray_UBYTE -#define NPY_SHORT PyArray_SHORT -#define NPY_USHORT PyArray_USHORT -#define NPY_INT PyArray_INT -#define NPY_UINT PyArray_UINT -#define NPY_LONG PyArray_LONG -#define NPY_ULONG PyArray_ULONG -#define NPY_LONGLONG PyArray_LONGLONG -#define NPY_ULONGLONG PyArray_ULONGLONG -#define NPY_FLOAT PyArray_FLOAT -#define NPY_DOUBLE PyArray_DOUBLE -#define NPY_LONGDOUBLE PyArray_LONGDOUBLE -#define NPY_CFLOAT PyArray_CFLOAT -#define NPY_CDOUBLE PyArray_CDOUBLE -#define NPY_CLONGDOUBLE PyArray_CLONGDOUBLE -#define NPY_OBJECT PyArray_OBJECT -#define NPY_STRING PyArray_STRING -#define NPY_UNICODE PyArray_UNICODE -#define NPY_VOID PyArray_VOID -#define NPY_NTYPES PyArray_NTYPES -#define NPY_NOTYPE PyArray_NOTYPE -#define NPY_CHAR PyArray_CHAR -#define NPY_USERDEF PyArray_USERDEF -#define npy_intp intp -#endif - -/* Given a PyObject, return a string describing its type. - */ -const char* pytype_string(PyObject* py_obj) { - if (py_obj == NULL ) return "C NULL value"; - if (py_obj == Py_None ) return "Python None" ; - if (PyCallable_Check(py_obj)) return "callable" ; - if (PyString_Check( py_obj)) return "string" ; - if (PyInt_Check( py_obj)) return "int" ; - if (PyFloat_Check( py_obj)) return "float" ; - if (PyDict_Check( py_obj)) return "dict" ; - if (PyList_Check( py_obj)) return "list" ; - if (PyTuple_Check( py_obj)) return "tuple" ; - if (PyFile_Check( py_obj)) return "file" ; - if (PyModule_Check( py_obj)) return "module" ; - if (PyInstance_Check(py_obj)) return "instance" ; - - return "unkown type"; -} - -/* Given a NumPy typecode, return a string describing the type. - */ -const char* typecode_string(int typecode) { - static const char* type_names[25] = {"bool", "byte", "unsigned byte", - "short", "unsigned short", "int", - "unsigned int", "long", "unsigned long", - "long long", "unsigned long long", - "float", "double", "long double", - "complex float", "complex double", - "complex long double", "object", - "string", "unicode", "void", "ntypes", - "notype", "char", "unknown"}; - return typecode < 24 ? type_names[typecode] : type_names[24]; -} - -/* Make sure input has correct numpy type. Allow character and byte - * to match. Also allow int and long to match. This is deprecated. - * You should use PyArray_EquivTypenums() instead. - */ -int type_match(int actual_type, int desired_type) { - return PyArray_EquivTypenums(actual_type, desired_type); -} - -/* Given a PyObject pointer, cast it to a PyArrayObject pointer if - * legal. If not, set the python error string appropriately and - * return NULL. - */ -PyArrayObject* obj_to_array_no_conversion(PyObject* input, int typecode) { - PyArrayObject* ary = NULL; - if (is_array(input) && (typecode == NPY_NOTYPE || - PyArray_EquivTypenums(array_type(input), typecode))) { - ary = (PyArrayObject*) input; - } - else if is_array(input) { - const char* desired_type = typecode_string(typecode); - const char* actual_type = typecode_string(array_type(input)); - PyErr_Format(PyExc_TypeError, - "Array of type '%s' required. Array of type '%s' given", - desired_type, actual_type); - ary = NULL; - } - else { - const char * desired_type = typecode_string(typecode); - const char * actual_type = pytype_string(input); - PyErr_Format(PyExc_TypeError, - "Array of type '%s' required. A '%s' was given", - desired_type, actual_type); - ary = NULL; - } - return ary; -} - -/* Convert the given PyObject to a NumPy array with the given - * typecode. On success, return a valid PyArrayObject* with the - * correct type. On failure, the python error string will be set and - * the routine returns NULL. - */ -PyArrayObject* obj_to_array_allow_conversion(PyObject* input, int typecode, - int* is_new_object) { - PyArrayObject* ary = NULL; - PyObject* py_obj; - if (is_array(input) && (typecode == NPY_NOTYPE || - PyArray_EquivTypenums(array_type(input),typecode))) { - ary = (PyArrayObject*) input; - *is_new_object = 0; - } - else { - py_obj = PyArray_FromObject(input, typecode, 0, 0); - /* If NULL, PyArray_FromObject will have set python error value.*/ - ary = (PyArrayObject*) py_obj; - *is_new_object = 1; - } - return ary; -} - -/* Given a PyArrayObject, check to see if it is contiguous. If so, - * return the input pointer and flag it as not a new object. If it is - * not contiguous, create a new PyArrayObject using the original data, - * flag it as a new object and return the pointer. - */ -PyArrayObject* make_contiguous(PyArrayObject* ary, int* is_new_object, - int min_dims, int max_dims) { - PyArrayObject* result; - if (array_is_contiguous(ary)) { - result = ary; - *is_new_object = 0; - } - else { - result = (PyArrayObject*) PyArray_ContiguousFromObject((PyObject*)ary, - array_type(ary), - min_dims, - max_dims); - *is_new_object = 1; - } - return result; -} - -/* Convert a given PyObject to a contiguous PyArrayObject of the - * specified type. If the input object is not a contiguous - * PyArrayObject, a new one will be created and the new object flag - * will be set. - */ -PyArrayObject* obj_to_array_contiguous_allow_conversion(PyObject* input, - int typecode, - int* is_new_object) { - int is_new1 = 0; - int is_new2 = 0; - PyArrayObject* ary2; - PyArrayObject* ary1 = obj_to_array_allow_conversion(input, typecode, &is_new1); - if (ary1) { - ary2 = make_contiguous(ary1, &is_new2, 0, 0); - if ( is_new1 && is_new2) { - Py_DECREF(ary1); - } - ary1 = ary2; - } - *is_new_object = is_new1 || is_new2; - return ary1; -} - -/* Test whether a python object is contiguous. If array is - * contiguous, return 1. Otherwise, set the python error string and - * return 0. - */ -int require_contiguous(PyArrayObject* ary) { - int contiguous = 1; - if (!array_is_contiguous(ary)) { - PyErr_SetString(PyExc_TypeError, - "Array must be contiguous. A non-contiguous array was given"); - contiguous = 0; - } - return contiguous; -} - -/* Require that a numpy array is not byte-swapped. If the array is - * not byte-swapped, return 1. Otherwise, set the python error string - * and return 0. - */ -int require_native(PyArrayObject* ary) { - int native = 1; - if (!array_is_native(ary)) { - PyErr_SetString(PyExc_TypeError, - "Array must have native byteorder. A byte-swapped array was given"); - native = 0; - } - return native; -} - -/* Require the given PyArrayObject to have a specified number of - * dimensions. If the array has the specified number of dimensions, - * return 1. Otherwise, set the python error string and return 0. - */ -int require_dimensions(PyArrayObject* ary, int exact_dimensions) { - int success = 1; - if (array_numdims(ary) != exact_dimensions) { - PyErr_Format(PyExc_TypeError, - "Array must have %d dimensions. Given array has %d dimensions", - exact_dimensions, array_numdims(ary)); - success = 0; - } - return success; -} - -/* Require the given PyArrayObject to have one of a list of specified - * number of dimensions. If the array has one of the specified number - * of dimensions, return 1. Otherwise, set the python error string - * and return 0. - */ -int require_dimensions_n(PyArrayObject* ary, int* exact_dimensions, int n) { - int success = 0; - int i; - char dims_str[255] = ""; - char s[255]; - for (i = 0; i < n && !success; i++) { - if (array_numdims(ary) == exact_dimensions[i]) { - success = 1; - } - } - if (!success) { - for (i = 0; i < n-1; i++) { - sprintf(s, "%d, ", exact_dimensions[i]); - strcat(dims_str,s); - } - sprintf(s, " or %d", exact_dimensions[n-1]); - strcat(dims_str,s); - PyErr_Format(PyExc_TypeError, - "Array must be have %s dimensions. Given array has %d dimensions", - dims_str, array_numdims(ary)); - } - return success; -} - -/* Require the given PyArrayObject to have a specified shape. If the - * array has the specified shape, return 1. Otherwise, set the python - * error string and return 0. - */ -int require_size(PyArrayObject* ary, npy_intp* size, int n) { - int i; - int success = 1; - int len; - char desired_dims[255] = "["; - char s[255]; - char actual_dims[255] = "["; - for(i=0; i < n;i++) { - if (size[i] != -1 && size[i] != array_size(ary,i)) { - success = 0; - } - } - if (!success) { - for (i = 0; i < n; i++) { - if (size[i] == -1) { - sprintf(s, "*,"); - } - else - { - sprintf(s,"%" NPY_INTP_FMT ",", size[i]); - } - strcat(desired_dims,s); - } - len = strlen(desired_dims); - desired_dims[len-1] = ']'; - for (i = 0; i < n; i++) { - sprintf(s,"%" NPY_INTP_FMT ",", array_size(ary,i)); - strcat(actual_dims,s); - } - len = strlen(actual_dims); - actual_dims[len-1] = ']'; - PyErr_Format(PyExc_TypeError, - "Array must be have shape of %s. Given array has shape of %s", - desired_dims, actual_dims); - } - return success; -} -/* End John Hunter translation (with modifications by Bill Spotz) */ - - - - - -/*! - Appends @a what to @a where. On input, @a where need not to be a tuple, but on - return it always is. - - @par Revision history: - - 17.02.2005, c -*/ -PyObject *helper_appendToTuple( PyObject *where, PyObject *what ) { - PyObject *o2, *o3; - - if ((!where) || (where == Py_None)) { - where = what; - } else { - if (!PyTuple_Check( where )) { - o2 = where; - where = PyTuple_New( 1 ); - PyTuple_SetItem( where, 0, o2 ); - } - o3 = PyTuple_New( 1 ); - PyTuple_SetItem( o3, 0, what ); - o2 = where; - where = PySequence_Concat( o2, o3 ); - Py_DECREF( o2 ); - Py_DECREF( o3 ); - } - return where; -} - - - - - - -#include "csgraph.h" - - -#include -#if !defined(SWIG_NO_LLONG_MAX) -# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) -# define LLONG_MAX __LONG_LONG_MAX__ -# define LLONG_MIN (-LLONG_MAX - 1LL) -# define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) -# endif -#endif - - -SWIGINTERN int -SWIG_AsVal_double (PyObject *obj, double *val) -{ - int res = SWIG_TypeError; - if (PyFloat_Check(obj)) { - if (val) *val = PyFloat_AsDouble(obj); - return SWIG_OK; - } else if (PyInt_Check(obj)) { - if (val) *val = PyInt_AsLong(obj); - return SWIG_OK; - } else if (PyLong_Check(obj)) { - double v = PyLong_AsDouble(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_OK; - } else { - PyErr_Clear(); - } - } -#ifdef SWIG_PYTHON_CAST_MODE - { - int dispatch = 0; - double d = PyFloat_AsDouble(obj); - if (!PyErr_Occurred()) { - if (val) *val = d; - return SWIG_AddCast(SWIG_OK); - } else { - PyErr_Clear(); - } - if (!dispatch) { - long v = PyLong_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); - } else { - PyErr_Clear(); - } - } - } -#endif - return res; -} - - -#include - - -#include - - -SWIGINTERNINLINE int -SWIG_CanCastAsInteger(double *d, double min, double max) { - double x = *d; - if ((min <= x && x <= max)) { - double fx = floor(x); - double cx = ceil(x); - double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ - if ((errno == EDOM) || (errno == ERANGE)) { - errno = 0; - } else { - double summ, reps, diff; - if (rd < x) { - diff = x - rd; - } else if (rd > x) { - diff = rd - x; - } else { - return 1; - } - summ = rd + x; - reps = diff/summ; - if (reps < 8*DBL_EPSILON) { - *d = rd; - return 1; - } - } - } - return 0; -} - - -SWIGINTERN int -SWIG_AsVal_long (PyObject *obj, long* val) -{ - if (PyInt_Check(obj)) { - if (val) *val = PyInt_AsLong(obj); - return SWIG_OK; - } else if (PyLong_Check(obj)) { - long v = PyLong_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_OK; - } else { - PyErr_Clear(); - } - } -#ifdef SWIG_PYTHON_CAST_MODE - { - int dispatch = 0; - long v = PyInt_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_AddCast(SWIG_OK); - } else { - PyErr_Clear(); - } - if (!dispatch) { - double d; - int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); - if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) { - if (val) *val = (long)(d); - return res; - } - } - } -#endif - return SWIG_TypeError; -} - - -SWIGINTERN int -SWIG_AsVal_int (PyObject * obj, int *val) -{ - long v; - int res = SWIG_AsVal_long (obj, &v); - if (SWIG_IsOK(res)) { - if ((v < INT_MIN || v > INT_MAX)) { - return SWIG_OverflowError; - } else { - if (val) *val = static_cast< int >(v); - } - } - return res; -} - - - #define SWIG_From_long PyInt_FromLong - - -SWIGINTERNINLINE PyObject * -SWIG_From_int (int value) -{ - return SWIG_From_long (value); -} - - -#include "csgraph.h" - -#ifdef __cplusplus -extern "C" { -#endif -SWIGINTERN PyObject *_wrap_cs_graph_components(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *resultobj = 0; - int arg1 ; - int *arg2 ; - int *arg3 ; - int *arg4 ; - int val1 ; - int ecode1 = 0 ; - PyArrayObject *array2 = NULL ; - int is_new_object2 ; - PyArrayObject *array3 = NULL ; - int is_new_object3 ; - PyArrayObject *temp4 = NULL ; - PyObject * obj0 = 0 ; - PyObject * obj1 = 0 ; - PyObject * obj2 = 0 ; - PyObject * obj3 = 0 ; - int result; - - if (!PyArg_ParseTuple(args,(char *)"OOOO:cs_graph_components",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; - ecode1 = SWIG_AsVal_int(obj0, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "cs_graph_components" "', argument " "1"" of type '" "int""'"); - } - arg1 = static_cast< int >(val1); - { - npy_intp size[1] = { - -1 - }; - array2 = obj_to_array_contiguous_allow_conversion(obj1, PyArray_INT, &is_new_object2); - if (!array2 || !require_dimensions(array2,1) || !require_size(array2,size,1) - || !require_contiguous(array2) || !require_native(array2)) SWIG_fail; - - arg2 = (int*) array2->data; - } - { - npy_intp size[1] = { - -1 - }; - array3 = obj_to_array_contiguous_allow_conversion(obj2, PyArray_INT, &is_new_object3); - if (!array3 || !require_dimensions(array3,1) || !require_size(array3,size,1) - || !require_contiguous(array3) || !require_native(array3)) SWIG_fail; - - arg3 = (int*) array3->data; - } - { - temp4 = obj_to_array_no_conversion(obj3,PyArray_INT); - if (!temp4 || !require_contiguous(temp4) || !require_native(temp4)) SWIG_fail; - arg4 = (int*) array_data(temp4); - } - result = (int)cs_graph_components< int >(arg1,(int const (*))arg2,(int const (*))arg3,arg4); - resultobj = SWIG_From_int(static_cast< int >(result)); - { - if (is_new_object2 && array2) { - Py_DECREF(array2); - } - } - { - if (is_new_object3 && array3) { - Py_DECREF(array3); - } - } - return resultobj; -fail: - { - if (is_new_object2 && array2) { - Py_DECREF(array2); - } - } - { - if (is_new_object3 && array3) { - Py_DECREF(array3); - } - } - return NULL; -} - - -static PyMethodDef SwigMethods[] = { - { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, - { (char *)"cs_graph_components", _wrap_cs_graph_components, METH_VARARGS, (char *)"cs_graph_components(int n_nod, int Ap, int Aj, int flag) -> int"}, - { NULL, NULL, 0, NULL } -}; - - -/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ - -static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; - -static swig_type_info *swig_type_initial[] = { - &_swigt__p_char, -}; - -static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; - -static swig_cast_info *swig_cast_initial[] = { - _swigc__p_char, -}; - - -/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ - -static swig_const_info swig_const_table[] = { -{0, 0, 0, 0.0, 0, 0}}; - -#ifdef __cplusplus -} -#endif -/* ----------------------------------------------------------------------------- - * Type initialization: - * This problem is tough by the requirement that no dynamic - * memory is used. Also, since swig_type_info structures store pointers to - * swig_cast_info structures and swig_cast_info structures store pointers back - * to swig_type_info structures, we need some lookup code at initialization. - * The idea is that swig generates all the structures that are needed. - * The runtime then collects these partially filled structures. - * The SWIG_InitializeModule function takes these initial arrays out of - * swig_module, and does all the lookup, filling in the swig_module.types - * array with the correct data and linking the correct swig_cast_info - * structures together. - * - * The generated swig_type_info structures are assigned staticly to an initial - * array. We just loop through that array, and handle each type individually. - * First we lookup if this type has been already loaded, and if so, use the - * loaded structure instead of the generated one. Then we have to fill in the - * cast linked list. The cast data is initially stored in something like a - * two-dimensional array. Each row corresponds to a type (there are the same - * number of rows as there are in the swig_type_initial array). Each entry in - * a column is one of the swig_cast_info structures for that type. - * The cast_initial array is actually an array of arrays, because each row has - * a variable number of columns. So to actually build the cast linked list, - * we find the array of casts associated with the type, and loop through it - * adding the casts to the list. The one last trick we need to do is making - * sure the type pointer in the swig_cast_info struct is correct. - * - * First off, we lookup the cast->type name to see if it is already loaded. - * There are three cases to handle: - * 1) If the cast->type has already been loaded AND the type we are adding - * casting info to has not been loaded (it is in this module), THEN we - * replace the cast->type pointer with the type pointer that has already - * been loaded. - * 2) If BOTH types (the one we are adding casting info to, and the - * cast->type) are loaded, THEN the cast info has already been loaded by - * the previous module so we just ignore it. - * 3) Finally, if cast->type has not already been loaded, then we add that - * swig_cast_info to the linked list (because the cast->type) pointer will - * be correct. - * ----------------------------------------------------------------------------- */ - -#ifdef __cplusplus -extern "C" { -#if 0 -} /* c-mode */ -#endif -#endif - -#if 0 -#define SWIGRUNTIME_DEBUG -#endif - - -SWIGRUNTIME void -SWIG_InitializeModule(void *clientdata) { - size_t i; - swig_module_info *module_head, *iter; - int found, init; - - clientdata = clientdata; - - /* check to see if the circular list has been setup, if not, set it up */ - if (swig_module.next==0) { - /* Initialize the swig_module */ - swig_module.type_initial = swig_type_initial; - swig_module.cast_initial = swig_cast_initial; - swig_module.next = &swig_module; - init = 1; - } else { - init = 0; - } - - /* Try and load any already created modules */ - module_head = SWIG_GetModule(clientdata); - if (!module_head) { - /* This is the first module loaded for this interpreter */ - /* so set the swig module into the interpreter */ - SWIG_SetModule(clientdata, &swig_module); - module_head = &swig_module; - } else { - /* the interpreter has loaded a SWIG module, but has it loaded this one? */ - found=0; - iter=module_head; - do { - if (iter==&swig_module) { - found=1; - break; - } - iter=iter->next; - } while (iter!= module_head); - - /* if the is found in the list, then all is done and we may leave */ - if (found) return; - /* otherwise we must add out module into the list */ - swig_module.next = module_head->next; - module_head->next = &swig_module; - } - - /* When multiple interpeters are used, a module could have already been initialized in - a different interpreter, but not yet have a pointer in this interpreter. - In this case, we do not want to continue adding types... everything should be - set up already */ - if (init == 0) return; - - /* Now work on filling in swig_module.types */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: size %d\n", swig_module.size); -#endif - for (i = 0; i < swig_module.size; ++i) { - swig_type_info *type = 0; - swig_type_info *ret; - swig_cast_info *cast; - -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); -#endif - - /* if there is another module already loaded */ - if (swig_module.next != &swig_module) { - type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); - } - if (type) { - /* Overwrite clientdata field */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found type %s\n", type->name); -#endif - if (swig_module.type_initial[i]->clientdata) { - type->clientdata = swig_module.type_initial[i]->clientdata; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); -#endif - } - } else { - type = swig_module.type_initial[i]; - } - - /* Insert casting types */ - cast = swig_module.cast_initial[i]; - while (cast->type) { - /* Don't need to add information already in the list */ - ret = 0; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); -#endif - if (swig_module.next != &swig_module) { - ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); -#ifdef SWIGRUNTIME_DEBUG - if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); -#endif - } - if (ret) { - if (type == swig_module.type_initial[i]) { -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: skip old type %s\n", ret->name); -#endif - cast->type = ret; - ret = 0; - } else { - /* Check for casting already in the list */ - swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); -#ifdef SWIGRUNTIME_DEBUG - if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); -#endif - if (!ocast) ret = 0; - } - } - - if (!ret) { -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); -#endif - if (type->cast) { - type->cast->prev = cast; - cast->next = type->cast; - } - type->cast = cast; - } - cast++; - } - /* Set entry in modules->types array equal to the type */ - swig_module.types[i] = type; - } - swig_module.types[i] = 0; - -#ifdef SWIGRUNTIME_DEBUG - printf("**** SWIG_InitializeModule: Cast List ******\n"); - for (i = 0; i < swig_module.size; ++i) { - int j = 0; - swig_cast_info *cast = swig_module.cast_initial[i]; - printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); - while (cast->type) { - printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); - cast++; - ++j; - } - printf("---- Total casts: %d\n",j); - } - printf("**** SWIG_InitializeModule: Cast List ******\n"); -#endif -} - -/* This function will propagate the clientdata field of type to -* any new swig_type_info structures that have been added into the list -* of equivalent types. It is like calling -* SWIG_TypeClientData(type, clientdata) a second time. -*/ -SWIGRUNTIME void -SWIG_PropagateClientData(void) { - size_t i; - swig_cast_info *equiv; - static int init_run = 0; - - if (init_run) return; - init_run = 1; - - for (i = 0; i < swig_module.size; i++) { - if (swig_module.types[i]->clientdata) { - equiv = swig_module.types[i]->cast; - while (equiv) { - if (!equiv->converter) { - if (equiv->type && !equiv->type->clientdata) - SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); - } - equiv = equiv->next; - } - } - } -} - -#ifdef __cplusplus -#if 0 -{ - /* c-mode */ -#endif -} -#endif - - - -#ifdef __cplusplus -extern "C" { -#endif - - /* Python-specific SWIG API */ -#define SWIG_newvarlink() SWIG_Python_newvarlink() -#define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) -#define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) - - /* ----------------------------------------------------------------------------- - * global variable support code. - * ----------------------------------------------------------------------------- */ - - typedef struct swig_globalvar { - char *name; /* Name of global variable */ - PyObject *(*get_attr)(void); /* Return the current value */ - int (*set_attr)(PyObject *); /* Set the value */ - struct swig_globalvar *next; - } swig_globalvar; - - typedef struct swig_varlinkobject { - PyObject_HEAD - swig_globalvar *vars; - } swig_varlinkobject; - - SWIGINTERN PyObject * - swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { -#if PY_VERSION_HEX >= 0x03000000 - return PyUnicode_InternFromString(""); -#else - return PyString_FromString(""); -#endif - } - - SWIGINTERN PyObject * - swig_varlink_str(swig_varlinkobject *v) { -#if PY_VERSION_HEX >= 0x03000000 - PyObject *str = PyUnicode_InternFromString("("); - PyObject *tail; - PyObject *joined; - swig_globalvar *var; - for (var = v->vars; var; var=var->next) { - tail = PyUnicode_FromString(var->name); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; - if (var->next) { - tail = PyUnicode_InternFromString(", "); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; - } - } - tail = PyUnicode_InternFromString(")"); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; -#else - PyObject *str = PyString_FromString("("); - swig_globalvar *var; - for (var = v->vars; var; var=var->next) { - PyString_ConcatAndDel(&str,PyString_FromString(var->name)); - if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); - } - PyString_ConcatAndDel(&str,PyString_FromString(")")); -#endif - return str; - } - - SWIGINTERN int - swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { - char *tmp; - PyObject *str = swig_varlink_str(v); - fprintf(fp,"Swig global variables "); - fprintf(fp,"%s\n", tmp = SWIG_Python_str_AsChar(str)); - SWIG_Python_str_DelForPy3(tmp); - Py_DECREF(str); - return 0; - } - - SWIGINTERN void - swig_varlink_dealloc(swig_varlinkobject *v) { - swig_globalvar *var = v->vars; - while (var) { - swig_globalvar *n = var->next; - free(var->name); - free(var); - var = n; - } - } - - SWIGINTERN PyObject * - swig_varlink_getattr(swig_varlinkobject *v, char *n) { - PyObject *res = NULL; - swig_globalvar *var = v->vars; - while (var) { - if (strcmp(var->name,n) == 0) { - res = (*var->get_attr)(); - break; - } - var = var->next; - } - if (res == NULL && !PyErr_Occurred()) { - PyErr_SetString(PyExc_NameError,"Unknown C global variable"); - } - return res; - } - - SWIGINTERN int - swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { - int res = 1; - swig_globalvar *var = v->vars; - while (var) { - if (strcmp(var->name,n) == 0) { - res = (*var->set_attr)(p); - break; - } - var = var->next; - } - if (res == 1 && !PyErr_Occurred()) { - PyErr_SetString(PyExc_NameError,"Unknown C global variable"); - } - return res; - } - - SWIGINTERN PyTypeObject* - swig_varlink_type(void) { - static char varlink__doc__[] = "Swig var link object"; - static PyTypeObject varlink_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp - = { - /* PyObject header changed in Python 3 */ -#if PY_VERSION_HEX >= 0x03000000 - PyVarObject_HEAD_INIT(&PyType_Type, 0) -#else - PyObject_HEAD_INIT(NULL) - 0, /* Number of items in variable part (ob_size) */ -#endif - (char *)"swigvarlink", /* Type name (tp_name) */ - sizeof(swig_varlinkobject), /* Basic size (tp_basicsize) */ - 0, /* Itemsize (tp_itemsize) */ - (destructor) swig_varlink_dealloc, /* Deallocator (tp_dealloc) */ - (printfunc) swig_varlink_print, /* Print (tp_print) */ - (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */ - (setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */ - 0, /* tp_compare */ - (reprfunc) swig_varlink_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - (reprfunc) swig_varlink_str, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - 0, /* tp_flags */ - varlink__doc__, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ -#if PY_VERSION_HEX >= 0x02020000 - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ -#endif -#if PY_VERSION_HEX >= 0x02030000 - 0, /* tp_del */ -#endif -#ifdef COUNT_ALLOCS - 0,0,0,0 /* tp_alloc -> tp_next */ -#endif - }; - varlink_type = tmp; - /* for Python 3 we already assigned ob_type in PyVarObject_HEAD_INIT() */ -#if PY_VERSION_HEX < 0x03000000 - varlink_type.ob_type = &PyType_Type; -#endif - type_init = 1; - } - return &varlink_type; - } - - /* Create a variable linking object for use later */ - SWIGINTERN PyObject * - SWIG_Python_newvarlink(void) { - swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); - if (result) { - result->vars = 0; - } - return ((PyObject*) result); - } - - SWIGINTERN void - SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { - swig_varlinkobject *v = (swig_varlinkobject *) p; - swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); - if (gv) { - size_t size = strlen(name)+1; - gv->name = (char *)malloc(size); - if (gv->name) { - strncpy(gv->name,name,size); - gv->get_attr = get_attr; - gv->set_attr = set_attr; - gv->next = v->vars; - } - } - v->vars = gv; - } - - SWIGINTERN PyObject * - SWIG_globals(void) { - static PyObject *_SWIG_globals = 0; - if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); - return _SWIG_globals; - } - - /* ----------------------------------------------------------------------------- - * constants/methods manipulation - * ----------------------------------------------------------------------------- */ - - /* Install Constants */ - SWIGINTERN void - SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { - PyObject *obj = 0; - size_t i; - for (i = 0; constants[i].type; ++i) { - switch(constants[i].type) { - case SWIG_PY_POINTER: - obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); - break; - case SWIG_PY_BINARY: - obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); - break; - default: - obj = 0; - break; - } - if (obj) { - PyDict_SetItemString(d, constants[i].name, obj); - Py_DECREF(obj); - } - } - } - - /* -----------------------------------------------------------------------------*/ - /* Fix SwigMethods to carry the callback ptrs when needed */ - /* -----------------------------------------------------------------------------*/ - - SWIGINTERN void - SWIG_Python_FixMethods(PyMethodDef *methods, - swig_const_info *const_table, - swig_type_info **types, - swig_type_info **types_initial) { - size_t i; - for (i = 0; methods[i].ml_name; ++i) { - const char *c = methods[i].ml_doc; - if (c && (c = strstr(c, "swig_ptr: "))) { - int j; - swig_const_info *ci = 0; - const char *name = c + 10; - for (j = 0; const_table[j].type; ++j) { - if (strncmp(const_table[j].name, name, - strlen(const_table[j].name)) == 0) { - ci = &(const_table[j]); - break; - } - } - if (ci) { - void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; - if (ptr) { - size_t shift = (ci->ptype) - types; - swig_type_info *ty = types_initial[shift]; - size_t ldoc = (c - methods[i].ml_doc); - size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; - char *ndoc = (char*)malloc(ldoc + lptr + 10); - if (ndoc) { - char *buff = ndoc; - strncpy(buff, methods[i].ml_doc, ldoc); - buff += ldoc; - strncpy(buff, "swig_ptr: ", 10); - buff += 10; - SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); - methods[i].ml_doc = ndoc; - } - } - } - } - } - } - -#ifdef __cplusplus -} -#endif - -/* -----------------------------------------------------------------------------* - * Partial Init method - * -----------------------------------------------------------------------------*/ - -#ifdef __cplusplus -extern "C" -#endif - -SWIGEXPORT -#if PY_VERSION_HEX >= 0x03000000 -PyObject* -#else -void -#endif -SWIG_init(void) { - PyObject *m, *d; -#if PY_VERSION_HEX >= 0x03000000 - static struct PyModuleDef SWIG_module = { - PyModuleDef_HEAD_INIT, - (char *) SWIG_name, - NULL, - -1, - SwigMethods, - NULL, - NULL, - NULL, - NULL - }; -#endif - - /* Fix SwigMethods to carry the callback ptrs when needed */ - SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); - -#if PY_VERSION_HEX >= 0x03000000 - m = PyModule_Create(&SWIG_module); -#else - m = Py_InitModule((char *) SWIG_name, SwigMethods); -#endif - d = PyModule_GetDict(m); - - SWIG_InitializeModule(0); - SWIG_InstallConstants(d,swig_const_table); - - - - import_array(); - -#if PY_VERSION_HEX >= 0x03000000 - return m; -#else - return; -#endif -} - diff --git a/sklearn/utils/sparsetools/npy_3kcompat.h b/sklearn/utils/sparsetools/npy_3kcompat.h deleted file mode 100644 index 02355e85221a7..0000000000000 --- a/sklearn/utils/sparsetools/npy_3kcompat.h +++ /dev/null @@ -1,402 +0,0 @@ -/* - * This is a convenience header file providing compatibility utilities - * for supporting Python 2 and Python 3 in the same code base. - * - * If you want to use this for your own projects, it's recommended to make a - * copy of it. Although the stuff below is unlikely to change, we don't provide - * strong backwards compatibility guarantees at the moment. - */ - -#ifndef _NPY_3KCOMPAT_H_ -#define _NPY_3KCOMPAT_H_ - -#include -#include - -#if PY_VERSION_HEX >= 0x03000000 -#ifndef NPY_PY3K -#define NPY_PY3K -#endif -#endif - -#include "numpy/npy_common.h" -#include "numpy/ndarrayobject.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * PyInt -> PyLong - */ - -#if defined(NPY_PY3K) -/* Return True only if the long fits in a C long */ -static NPY_INLINE int PyInt_Check(PyObject *op) { - int overflow = 0; - if (!PyLong_Check(op)) { - return 0; - } - PyLong_AsLongAndOverflow(op, &overflow); - return (overflow == 0); -} - -#define PyInt_FromLong PyLong_FromLong -#define PyInt_AsLong PyLong_AsLong -#define PyInt_AS_LONG PyLong_AsLong -#define PyInt_AsSsize_t PyLong_AsSsize_t - -/* NOTE: - * - * Since the PyLong type is very different from the fixed-range PyInt, - * we don't define PyInt_Type -> PyLong_Type. - */ -#endif /* NPY_PY3K */ - -/* - * PyString -> PyBytes - */ - -#if defined(NPY_PY3K) - -#define PyString_Type PyBytes_Type -#define PyString_Check PyBytes_Check -#define PyStringObject PyBytesObject -#define PyString_FromString PyBytes_FromString -#define PyString_FromStringAndSize PyBytes_FromStringAndSize -#define PyString_AS_STRING PyBytes_AS_STRING -#define PyString_AsStringAndSize PyBytes_AsStringAndSize -#define PyString_FromFormat PyBytes_FromFormat -#define PyString_Concat PyBytes_Concat -#define PyString_ConcatAndDel PyBytes_ConcatAndDel -#define PyString_AsString PyBytes_AsString -#define PyString_GET_SIZE PyBytes_GET_SIZE -#define PyString_Size PyBytes_Size - -#define PyUString_Type PyUnicode_Type -#define PyUString_Check PyUnicode_Check -#define PyUStringObject PyUnicodeObject -#define PyUString_FromString PyUnicode_FromString -#define PyUString_FromStringAndSize PyUnicode_FromStringAndSize -#define PyUString_FromFormat PyUnicode_FromFormat -#define PyUString_Concat PyUnicode_Concat2 -#define PyUString_ConcatAndDel PyUnicode_ConcatAndDel -#define PyUString_GET_SIZE PyUnicode_GET_SIZE -#define PyUString_Size PyUnicode_Size -#define PyUString_InternFromString PyUnicode_InternFromString -#define PyUString_Format PyUnicode_Format - -#else - -#define PyBytes_Type PyString_Type -#define PyBytes_Check PyString_Check -#define PyBytesObject PyStringObject -#define PyBytes_FromString PyString_FromString -#define PyBytes_FromStringAndSize PyString_FromStringAndSize -#define PyBytes_AS_STRING PyString_AS_STRING -#define PyBytes_AsStringAndSize PyString_AsStringAndSize -#define PyBytes_FromFormat PyString_FromFormat -#define PyBytes_Concat PyString_Concat -#define PyBytes_ConcatAndDel PyString_ConcatAndDel -#define PyBytes_AsString PyString_AsString -#define PyBytes_GET_SIZE PyString_GET_SIZE -#define PyBytes_Size PyString_Size - -#define PyUString_Type PyString_Type -#define PyUString_Check PyString_Check -#define PyUStringObject PyStringObject -#define PyUString_FromString PyString_FromString -#define PyUString_FromStringAndSize PyString_FromStringAndSize -#define PyUString_FromFormat PyString_FromFormat -#define PyUString_Concat PyString_Concat -#define PyUString_ConcatAndDel PyString_ConcatAndDel -#define PyUString_GET_SIZE PyString_GET_SIZE -#define PyUString_Size PyString_Size -#define PyUString_InternFromString PyString_InternFromString -#define PyUString_Format PyString_Format - -#endif /* NPY_PY3K */ - - -static NPY_INLINE void -PyUnicode_ConcatAndDel(PyObject **left, PyObject *right) -{ - PyObject *newobj; - newobj = PyUnicode_Concat(*left, right); - Py_DECREF(*left); - Py_DECREF(right); - *left = newobj; -} - -static NPY_INLINE void -PyUnicode_Concat2(PyObject **left, PyObject *right) -{ - PyObject *newobj; - newobj = PyUnicode_Concat(*left, right); - Py_DECREF(*left); - *left = newobj; -} - - -/* - * Accessing items of ob_base - */ - -#if (PY_VERSION_HEX < 0x02060000) -#define Py_TYPE(o) (((PyObject*)(o))->ob_type) -#define Py_REFCNT(o) (((PyObject*)(o))->ob_refcnt) -#define Py_SIZE(o) (((PyVarObject*)(o))->ob_size) -#endif - -/* - * PyFile_* compatibility - */ -#if defined(NPY_PY3K) - -/* - * Get a FILE* handle to the file represented by the Python object - */ -static NPY_INLINE FILE* -npy_PyFile_Dup(PyObject *file, char *mode) -{ - int fd, fd2; - PyObject *ret, *os; - Py_ssize_t pos; - FILE *handle; - /* Flush first to ensure things end up in the file in the correct order */ - ret = PyObject_CallMethod(file, "flush", ""); - if (ret == NULL) { - return NULL; - } - Py_DECREF(ret); - fd = PyObject_AsFileDescriptor(file); - if (fd == -1) { - return NULL; - } - os = PyImport_ImportModule("os"); - if (os == NULL) { - return NULL; - } - ret = PyObject_CallMethod(os, "dup", "i", fd); - Py_DECREF(os); - if (ret == NULL) { - return NULL; - } - fd2 = PyNumber_AsSsize_t(ret, NULL); - Py_DECREF(ret); -#ifdef _WIN32 - handle = _fdopen(fd2, mode); -#else - handle = fdopen(fd2, mode); -#endif - if (handle == NULL) { - PyErr_SetString(PyExc_IOError, - "Getting a FILE* from a Python file object failed"); - } - ret = PyObject_CallMethod(file, "tell", ""); - if (ret == NULL) { - fclose(handle); - return NULL; - } - pos = PyNumber_AsSsize_t(ret, PyExc_OverflowError); - Py_DECREF(ret); - if (PyErr_Occurred()) { - fclose(handle); - return NULL; - } - fseek(handle, pos, SEEK_SET); - return handle; -} - -/* - * Close the dup-ed file handle, and seek the Python one to the current position - */ -static NPY_INLINE int -npy_PyFile_DupClose(PyObject *file, FILE* handle) -{ - PyObject *ret; - long position; - position = ftell(handle); - fclose(handle); - - ret = PyObject_CallMethod(file, "seek", "li", position, 0); - if (ret == NULL) { - return -1; - } - Py_DECREF(ret); - return 0; -} - -static NPY_INLINE int -npy_PyFile_Check(PyObject *file) -{ - int fd; - fd = PyObject_AsFileDescriptor(file); - if (fd == -1) { - PyErr_Clear(); - return 0; - } - return 1; -} - -#else - -#define npy_PyFile_Dup(file, mode) PyFile_AsFile(file) -#define npy_PyFile_DupClose(file, handle) (0) -#define npy_PyFile_Check PyFile_Check - -#endif - -static NPY_INLINE PyObject* -npy_PyFile_OpenFile(PyObject *filename, char *mode) -{ - PyObject *open; - open = PyDict_GetItemString(PyEval_GetBuiltins(), "open"); - if (open == NULL) { - return NULL; - } - return PyObject_CallFunction(open, "Os", filename, mode); -} - -/* - * PyObject_Cmp - */ -#if defined(NPY_PY3K) -static NPY_INLINE int -PyObject_Cmp(PyObject *i1, PyObject *i2, int *cmp) -{ - int v; - v = PyObject_RichCompareBool(i1, i2, Py_LT); - if (v == 0) { - *cmp = -1; - return 1; - } - else if (v == -1) { - return -1; - } - - v = PyObject_RichCompareBool(i1, i2, Py_GT); - if (v == 0) { - *cmp = 1; - return 1; - } - else if (v == -1) { - return -1; - } - - v = PyObject_RichCompareBool(i1, i2, Py_EQ); - if (v == 0) { - *cmp = 0; - return 1; - } - else { - *cmp = 0; - return -1; - } -} -#endif - -/* - * PyCObject functions adapted to PyCapsules. - * - * The main job here is to get rid of the improved error handling - * of PyCapsules. It's a shame... - */ -#if PY_VERSION_HEX >= 0x03000000 - -static NPY_INLINE PyObject * -NpyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *)) -{ - PyObject *ret = PyCapsule_New(ptr, NULL, dtor); - if (ret == NULL) { - PyErr_Clear(); - } - return ret; -} - -static NPY_INLINE PyObject * -NpyCapsule_FromVoidPtrAndDesc(void *ptr, void* context, void (*dtor)(PyObject *)) -{ - PyObject *ret = NpyCapsule_FromVoidPtr(ptr, dtor); - if (ret != NULL && PyCapsule_SetContext(ret, context) != 0) { - PyErr_Clear(); - Py_DECREF(ret); - ret = NULL; - } - return ret; -} - -static NPY_INLINE void * -NpyCapsule_AsVoidPtr(PyObject *obj) -{ - void *ret = PyCapsule_GetPointer(obj, NULL); - if (ret == NULL) { - PyErr_Clear(); - } - return ret; -} - -static NPY_INLINE void * -NpyCapsule_GetDesc(PyObject *obj) -{ - return PyCapsule_GetContext(obj); -} - -static NPY_INLINE int -NpyCapsule_Check(PyObject *ptr) -{ - return PyCapsule_CheckExact(ptr); -} - -static void -simple_capsule_dtor(PyObject *cap) -{ - PyArray_free(PyCapsule_GetPointer(cap, NULL)); -} - -#else - -static NPY_INLINE PyObject * -NpyCapsule_FromVoidPtr(void *ptr, void (*dtor)(void *)) -{ - return PyCObject_FromVoidPtr(ptr, dtor); -} - -static NPY_INLINE PyObject * -NpyCapsule_FromVoidPtrAndDesc(void *ptr, void* context, - void (*dtor)(void *, void *)) -{ - return PyCObject_FromVoidPtrAndDesc(ptr, context, dtor); -} - -static NPY_INLINE void * -NpyCapsule_AsVoidPtr(PyObject *ptr) -{ - return PyCObject_AsVoidPtr(ptr); -} - -static NPY_INLINE void * -NpyCapsule_GetDesc(PyObject *obj) -{ - return PyCObject_GetDesc(obj); -} - -static NPY_INLINE int -NpyCapsule_Check(PyObject *ptr) -{ - return PyCObject_Check(ptr); -} - -static void -simple_capsule_dtor(void *ptr) -{ - PyArray_free(ptr); -} - -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* _NPY_3KCOMPAT_H_ */ diff --git a/sklearn/utils/sparsetools/py3k.h b/sklearn/utils/sparsetools/py3k.h deleted file mode 100644 index 1b5916f80ed87..0000000000000 --- a/sklearn/utils/sparsetools/py3k.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Undefine macros defined by SWIG - */ -#if PY_VERSION_HEX >= 0x03000000 - -#ifdef PyInt_Check -#undef PyInt_Check -#endif - -static int __pyfile_check_guard(PyObject *x) -{ - return 0; -} -#define PyFile_Check(x) __pyfile_check_guard((x)) -static int __pyinstance_check_guard(PyObject *x) -{ - return 0; -} -#define PyInstance_Check(x) __pyinstance_check_guard((x)) -#include "npy_3kcompat.h" -#endif - - diff --git a/sklearn/utils/sparsetools/setup.py b/sklearn/utils/sparsetools/setup.py index 111a4ca4f0dee..8c23e2c1e51fe 100644 --- a/sklearn/utils/sparsetools/setup.py +++ b/sklearn/utils/sparsetools/setup.py @@ -1,13 +1,21 @@ +import numpy + + def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('sparsetools', parent_package, top_path) - fmt = 'csgraph' - sources = [fmt + '_wrap.cxx'] - depends = [fmt + '.h'] - config.add_extension('_' + fmt, sources=sources, - define_macros=[('__STDC_FORMAT_MACROS', 1)], depends=depends) + config.add_extension('_traversal', + sources=['_traversal.c'], + include_dirs=[numpy.get_include()], + #libraries=libraries + ) + config.add_extension('_graph_tools', + sources=['_graph_tools.c'], + include_dirs=[numpy.get_include()], + #libraries=libraries + ) return config diff --git a/sklearn/utils/sparsetools/tests/test_traversal.py b/sklearn/utils/sparsetools/tests/test_traversal.py new file mode 100644 index 0000000000000..9b42a62118073 --- /dev/null +++ b/sklearn/utils/sparsetools/tests/test_traversal.py @@ -0,0 +1,56 @@ +from __future__ import division, print_function, absolute_import + +from nose import SkipTest + +import numpy as np +from numpy.testing import assert_array_almost_equal +try: + from scipy.sparse.csgraph import breadth_first_tree, depth_first_tree,\ + csgraph_to_dense, csgraph_from_dense +except ImportError: + # Oldish versions of scipy don't have that + csgraph_from_dense = None + + +def test_graph_breadth_first(): + if csgraph_from_dense is None: + raise SkipTest("Old version of scipy, doesn't have csgraph.") + csgraph = np.array([[0, 1, 2, 0, 0], + [1, 0, 0, 0, 3], + [2, 0, 0, 7, 0], + [0, 0, 7, 0, 1], + [0, 3, 0, 1, 0]]) + csgraph = csgraph_from_dense(csgraph, null_value=0) + + bfirst = np.array([[0, 1, 2, 0, 0], + [0, 0, 0, 0, 3], + [0, 0, 0, 7, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]]) + + for directed in [True, False]: + bfirst_test = breadth_first_tree(csgraph, 0, directed) + assert_array_almost_equal(csgraph_to_dense(bfirst_test), + bfirst) + + +def test_graph_depth_first(): + if csgraph_from_dense is None: + raise SkipTest("Old version of scipy, doesn't have csgraph.") + csgraph = np.array([[0, 1, 2, 0, 0], + [1, 0, 0, 0, 3], + [2, 0, 0, 7, 0], + [0, 0, 7, 0, 1], + [0, 3, 0, 1, 0]]) + csgraph = csgraph_from_dense(csgraph, null_value=0) + + dfirst = np.array([[0, 1, 0, 0, 0], + [0, 0, 0, 0, 3], + [0, 0, 0, 0, 0], + [0, 0, 7, 0, 0], + [0, 0, 0, 1, 0]]) + + for directed in [True, False]: + dfirst_test = depth_first_tree(csgraph, 0, directed) + assert_array_almost_equal(csgraph_to_dense(dfirst_test), + dfirst) diff --git a/sklearn/utils/src/cholesky_delete.c b/sklearn/utils/src/cholesky_delete.h similarity index 50% rename from sklearn/utils/src/cholesky_delete.c rename to sklearn/utils/src/cholesky_delete.h index 66d587b819a04..6e20a2b003ed7 100644 --- a/sklearn/utils/src/cholesky_delete.c +++ b/sklearn/utils/src/cholesky_delete.h @@ -2,23 +2,24 @@ #include #ifdef _MSC_VER - #define copysign _copysign +# define inline __inline #endif -/* General Cholesky Delete. + +/* + * General Cholesky Delete. * Remove an element from the cholesky factorization * m = columns * n = rows * * TODO: put transpose as an option - * */ -int double_cholesky_delete (int m, int n, double *L, int go_out) { - +static inline void cholesky_delete_dbl(int m, int n, double *L, int go_out) +{ double c, s; /* delete row go_out */ - double *L1 = L + (go_out * m); + double *L1 = L + (go_out * m); int i; for (i = go_out; i < n - 1; ++i) { cblas_dcopy (i + 2, L1 + m , 1, L1, 1); @@ -28,54 +29,48 @@ int double_cholesky_delete (int m, int n, double *L, int go_out) { L1 = L + (go_out * m); for (i=go_out; i < n - 1; ++i) { - cblas_drotg (L1 + i, L1 + i + 1, &c, &s); + cblas_drotg(L1 + i, L1 + i + 1, &c, &s); if (L1[i] < 0) { /* Diagonals cannot be negative */ - L1[i] = copysign(L1[i], 1.0); + L1[i] = fabs(L1[i]); c = -c; s = -s; } L1[i+1] = 0.; /* just for cleanup */ L1 += m; - cblas_drot (n - (i + 2), L1 + i, m, L1 + i + 1, - m, c, s); - + cblas_drot(n - (i + 2), L1 + i, m, L1 + i + 1, + m, c, s); } - - return 0; } -int float_cholesky_delete (int m, int n, float *L, int go_out) { - +static inline void cholesky_delete_flt(int m, int n, float *L, int go_out) +{ float c, s; /* delete row go_out */ - float * _L = L + (go_out * m); + float *L1 = L + (go_out * m); int i; for (i = go_out; i < n - 1; ++i) { - cblas_scopy (i + 2, _L + m , 1, _L, 1); - _L += m; + cblas_scopy (i + 2, L1 + m , 1, L1, 1); + L1 += m; } - _L = L + (go_out * m); + L1 = L + (go_out * m); for (i=go_out; i < n - 1; ++i) { - cblas_srotg (_L + i, _L + i + 1, &c, &s); - if (_L[i] < 0) { + cblas_srotg(L1 + i, L1 + i + 1, &c, &s); + if (L1[i] < 0) { /* Diagonals cannot be negative */ - /* _L[i] = copysign(_L[i], 1.0); */ + L1[i] = fabsf(L1[i]); c = -c; s = -s; } - _L[i+1] = 0.; /* just for cleanup */ - _L += m; - - cblas_srot (n - (i + 2), _L + i, m, _L + i + 1, - m, c, s); + L1[i+1] = 0.; /* just for cleanup */ + L1 += m; + cblas_srot(n - (i + 2), L1 + i, m, L1 + i + 1, + m, c, s); } - - return 0; } diff --git a/sklearn/utils/src/gamma.c b/sklearn/utils/src/gamma.c new file mode 100644 index 0000000000000..41f61de426a5e --- /dev/null +++ b/sklearn/utils/src/gamma.c @@ -0,0 +1,155 @@ +/* + * John D. Cook's public domain version of lgamma, from + * http://www.johndcook.com/stand_alone_code.html + * + * Replaces the C99 standard lgamma for stone-age C compilers like the one + * from Redmond. + * + * I removed the test cases and added the cfloat import (Vlad N. ) + * + * Translated to C by Lars Buitinck. Input validation removed; we handle + * that in the Cython wrapper. + */ + +#include +#include +#include "gamma.h" + +/* Euler's gamma constant. */ +#define GAMMA 0.577215664901532860606512090 + +#define HALF_LOG2_PI 0.91893853320467274178032973640562 + + +static double sklearn_gamma(double x) +{ + /* + * Split the function domain into three intervals: + * (0, 0.001), [0.001, 12), and (12, infinity). + */ + + /* + * First interval: (0, 0.001). + * + * For small x, 1/Gamma(x) has power series x + gamma x^2 - ... + * So in this range, 1/Gamma(x) = x + gamma x^2 with error + * on the order of x^3. + * The relative error over this interval is less than 6e-7. + */ + if (x < 0.001) + return 1.0 / (x * (1.0 + GAMMA * x)); + + /* + * Second interval: [0.001, 12). + */ + if (x < 12.0) { + /* numerator coefficients for approximation over the interval (1,2) */ + static const double p[] = { + -1.71618513886549492533811E+0, + 2.47656508055759199108314E+1, + -3.79804256470945635097577E+2, + 6.29331155312818442661052E+2, + 8.66966202790413211295064E+2, + -3.14512729688483675254357E+4, + -3.61444134186911729807069E+4, + 6.64561438202405440627855E+4 + }; + + /* denominator coefficients for approximation over the interval (1,2) */ + static const double q[] = { + -3.08402300119738975254353E+1, + 3.15350626979604161529144E+2, + -1.01515636749021914166146E+3, + -3.10777167157231109440444E+3, + 2.25381184209801510330112E+4, + 4.75584627752788110767815E+3, + -1.34659959864969306392456E+5, + -1.15132259675553483497211E+5 + }; + + double den, num, result, z; + + /* The algorithm directly approximates gamma over (1,2) and uses + * reduction identities to reduce other arguments to this interval. */ + double y = x; + int i, n = 0; + int arg_was_less_than_one = (y < 1.0); + + /* Add or subtract integers as necessary to bring y into (1,2) + * Will correct for this below */ + if (arg_was_less_than_one) + y += 1.0; + else { + n = (int)floor(y) - 1; + y -= n; + } + + num = 0.0; + den = 1.0; + + z = y - 1; + for (i = 0; i < 8; i++) { + num = (num + p[i]) * z; + den = den * z + q[i]; + } + result = num/den + 1.0; + + /* Apply correction if argument was not initially in (1,2) */ + if (arg_was_less_than_one) + /* Use identity gamma(z) = gamma(z+1)/z + * The variable "result" now holds gamma of the original y + 1 + * Thus we use y-1 to get back the original y. */ + result /= (y-1.0); + else + /* Use the identity gamma(z+n) = z*(z+1)* ... *(z+n-1)*gamma(z) */ + for (i = 0; i < n; i++, y++) + result *= y; + + return result; + } + + /* + * Third interval: [12, infinity). + */ + if (x > 171.624) + /* Correct answer too large to display, force +infinity. */ + return 2 * DBL_MAX; + return exp(sklearn_lgamma(x)); +} + + +double sklearn_lgamma(double x) +{ + /* + * Abramowitz and Stegun 6.1.41 + * Asymptotic series should be good to at least 11 or 12 figures + * For error analysis, see Whittiker and Watson + * A Course in Modern Analysis (1927), page 252 + */ + static const double c[8] = + { + 1.0/12.0, + -1.0/360.0, + 1.0/1260.0, + -1.0/1680.0, + 1.0/1188.0, + -691.0/360360.0, + 1.0/156.0, + -3617.0/122400.0 + }; + + double z, sum; + int i; + + if (x < 12.0) + return log(fabs(sklearn_gamma(x))); + + z = 1.0 / (x * x); + sum = c[7]; + for (i=6; i >= 0; i--) { + sum *= z; + sum += c[i]; + } + + return (x - 0.5) * log(x) - x + HALF_LOG2_PI + sum / x; +} diff --git a/sklearn/utils/src/gamma.h b/sklearn/utils/src/gamma.h new file mode 100644 index 0000000000000..1f462f6d2d6b4 --- /dev/null +++ b/sklearn/utils/src/gamma.h @@ -0,0 +1,8 @@ +#ifndef GAMMA_H +#define GAMMA_H + +//double sklearn_gamma(double); +double sklearn_lgamma(double); + +#endif + diff --git a/sklearn/utils/stats.py b/sklearn/utils/stats.py new file mode 100644 index 0000000000000..463146d038c6b --- /dev/null +++ b/sklearn/utils/stats.py @@ -0,0 +1,59 @@ +import numpy as np +from scipy.stats import rankdata as _sp_rankdata +from .fixes import bincount + + +# To remove when we support scipy 0.13 +def _rankdata(a, method="average"): + """Assign ranks to data, dealing with ties appropriately. + + Ranks begin at 1. The method argument controls how ranks are assigned + to equal values. + + Parameters + ---------- + a : array_like + The array of values to be ranked. The array is first flattened. + + method : str, optional + The method used to assign ranks to tied elements. + The options are 'max'. + 'max': The maximum of the ranks that would have been assigned + to all the tied values is assigned to each value. + + Returns + ------- + ranks : ndarray + An array of length equal to the size of a, containing rank scores. + + Notes + ----- + We only backport the 'max' method + + """ + if method != "max": + raise NotImplementedError() + + unique_all, inverse = np.unique(a, return_inverse=True) + count = bincount(inverse, minlength=unique_all.size) + cum_count = count.cumsum() + rank = cum_count[inverse] + return rank + +try: + _sp_rankdata([1.], 'max') + rankdata = _sp_rankdata + +except TypeError as e: + rankdata = _rankdata + + +def _weighted_percentile(array, sample_weight, percentile=50): + """Compute the weighted ``percentile`` of ``array`` with ``sample_weight``. """ + sorted_idx = np.argsort(array) + + # Find index of median prediction for each sample + weight_cdf = sample_weight[sorted_idx].cumsum() + percentile_idx = np.searchsorted( + weight_cdf, (percentile / 100.) * weight_cdf[-1]) + return array[sorted_idx[percentile_idx]] diff --git a/sklearn/utils/testing.py b/sklearn/utils/testing.py index 832fa94afef66..a0ae8fb01b63d 100644 --- a/sklearn/utils/testing.py +++ b/sklearn/utils/testing.py @@ -1,23 +1,67 @@ """Testing utilities.""" -# Copyright (c) 2011 Pietro Berkes -# License: Simplified BSD +# Copyright (c) 2011, 2012 +# Authors: Pietro Berkes, +# Andreas Muller +# Mathieu Blondel +# Olivier Grisel +# Arnaud Joly +# Denis Engemann +# License: BSD 3 clause +import os import inspect import pkgutil +import warnings +import sys +import re +import platform -import urllib2 -from StringIO import StringIO import scipy as sp +import scipy.io +from functools import wraps +try: + # Python 2 + from urllib2 import urlopen + from urllib2 import HTTPError +except ImportError: + # Python 3+ + from urllib.request import urlopen + from urllib.error import HTTPError + import sklearn from sklearn.base import BaseEstimator -from .fixes import savemat + +# Conveniently import all assertions in one place. +from nose.tools import assert_equal +from nose.tools import assert_not_equal +from nose.tools import assert_true +from nose.tools import assert_false +from nose.tools import assert_raises +from nose.tools import raises +from nose import SkipTest +from nose import with_setup + +from numpy.testing import assert_almost_equal +from numpy.testing import assert_array_equal +from numpy.testing import assert_array_almost_equal +from numpy.testing import assert_array_less +import numpy as np + +from sklearn.base import (ClassifierMixin, RegressorMixin, TransformerMixin, + ClusterMixin) + +__all__ = ["assert_equal", "assert_not_equal", "assert_raises", + "assert_raises_regexp", "raises", "with_setup", "assert_true", + "assert_false", "assert_almost_equal", "assert_array_equal", + "assert_array_almost_equal", "assert_array_less", + "assert_less", "assert_less_equal", + "assert_greater", "assert_greater_equal"] try: from nose.tools import assert_in, assert_not_in except ImportError: # Nose < 1.0.0 - from nose.tools import assert_true, assert_false def assert_in(x, container): assert_true(x in container, msg="%r in %r" % (x, container)) @@ -25,6 +69,33 @@ def assert_in(x, container): def assert_not_in(x, container): assert_false(x in container, msg="%r in %r" % (x, container)) +try: + from nose.tools import assert_raises_regex +except ImportError: + # for Py 2.6 + def assert_raises_regex(expected_exception, expected_regexp, + callable_obj=None, *args, **kwargs): + """Helper function to check for message patterns in exceptions""" + + not_raised = False + try: + callable_obj(*args, **kwargs) + not_raised = True + except Exception as e: + error_message = str(e) + if not re.compile(expected_regexp).search(error_message): + raise AssertionError("Error message should match pattern " + "%r. %r does not." % + (expected_regexp, error_message)) + if not_raised: + raise AssertionError("Should have raised %r" % + expected_exception(expected_regexp)) + +# assert_raises_regexp is deprecated in Python 3.4 in favor of +# assert_raises_regex but lets keep the bacward compat in scikit-learn with +# the old name for now +assert_raises_regexp = assert_raises_regex + def _assert_less(a, b, msg=None): message = "%r is not lower than %r" % (a, b) @@ -40,6 +111,255 @@ def _assert_greater(a, b, msg=None): assert a > b, message +def assert_less_equal(a, b, msg=None): + message = "%r is not lower than or equal to %r" % (a, b) + if msg is not None: + message += ": " + msg + assert a <= b, message + + +def assert_greater_equal(a, b, msg=None): + message = "%r is not greater than or equal to %r" % (a, b) + if msg is not None: + message += ": " + msg + assert a >= b, message + + +def assert_warns(warning_class, func, *args, **kw): + """Test that a certain warning occurs. + + Parameters + ---------- + warning_class : the warning class + The class to test for, e.g. UserWarning. + + func : callable + Calable object to trigger warnings. + + *args : the positional arguments to `func`. + + **kw : the keyword arguments to `func` + + Returns + ------- + + result : the return value of `func` + + """ + + # very important to avoid uncontrolled state propagation + clean_warning_registry() + with warnings.catch_warnings(record=True) as w: + # Cause all warnings to always be triggered. + warnings.simplefilter("always") + # Trigger a warning. + result = func(*args, **kw) + if hasattr(np, 'VisibleDeprecationWarning'): + # Filter out numpy-specific warnings in numpy >= 1.9 + w = [e for e in w + if e.category is not np.VisibleDeprecationWarning] + + # Verify some things + if not len(w) > 0: + raise AssertionError("No warning raised when calling %s" + % func.__name__) + + found = any(warning.category is warning_class for warning in w) + if not found: + raise AssertionError("%s did not give warning: %s( is %s)" + % (func.__name__, warning_class, w)) + return result + + +def assert_warns_message(warning_class, message, func, *args, **kw): + # very important to avoid uncontrolled state propagation + """Test that a certain warning occurs and with a certain message. + + Parameters + ---------- + warning_class : the warning class + The class to test for, e.g. UserWarning. + + message : str | callable + The entire message or a substring to test for. If callable, + it takes a string as argument and will trigger an assertion error + if it returns `False`. + + func : callable + Calable object to trigger warnings. + + *args : the positional arguments to `func`. + + **kw : the keyword arguments to `func`. + + Returns + ------- + + result : the return value of `func` + + """ + clean_warning_registry() + with warnings.catch_warnings(record=True) as w: + # Cause all warnings to always be triggered. + warnings.simplefilter("always") + if hasattr(np, 'VisibleDeprecationWarning'): + # Let's not catch the numpy internal DeprecationWarnings + warnings.simplefilter('ignore', np.VisibleDeprecationWarning) + # Trigger a warning. + result = func(*args, **kw) + # Verify some things + if not len(w) > 0: + raise AssertionError("No warning raised when calling %s" + % func.__name__) + + found = [warning.category is warning_class for warning in w] + if not any(found): + raise AssertionError("No warning raised for %s with class " + "%s" + % (func.__name__, warning_class)) + + message_found = False + # Checks the message of all warnings belong to warning_class + for index in [i for i, x in enumerate(found) if x]: + # substring will match, the entire message with typo won't + msg = w[index].message # For Python 3 compatibility + msg = str(msg.args[0] if hasattr(msg, 'args') else msg) + if callable(message): # add support for certain tests + check_in_message = message + else: + check_in_message = lambda msg: message in msg + + if check_in_message(msg): + message_found = True + break + + if not message_found: + raise AssertionError("Did not receive the message you expected " + "('%s') for <%s>." + % (message, func.__name__)) + + return result + + +# To remove when we support numpy 1.7 +def assert_no_warnings(func, *args, **kw): + # XXX: once we may depend on python >= 2.6, this can be replaced by the + + # warnings module context manager. + # very important to avoid uncontrolled state propagation + clean_warning_registry() + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + + result = func(*args, **kw) + if hasattr(np, 'VisibleDeprecationWarning'): + # Filter out numpy-specific warnings in numpy >= 1.9 + w = [e for e in w + if e.category is not np.VisibleDeprecationWarning] + + if len(w) > 0: + raise AssertionError("Got warnings when calling %s: %s" + % (func.__name__, w)) + return result + + +def ignore_warnings(obj=None): + """ Context manager and decorator to ignore warnings + + Note. Using this (in both variants) will clear all warnings + from all python modules loaded. In case you need to test + cross-module-warning-logging this is not your tool of choice. + + Examples + -------- + >>> with ignore_warnings(): + ... warnings.warn('buhuhuhu') + + >>> def nasty_warn(): + ... warnings.warn('buhuhuhu') + ... print(42) + + >>> ignore_warnings(nasty_warn)() + 42 + + """ + if callable(obj): + return _ignore_warnings(obj) + else: + return _IgnoreWarnings() + + +def _ignore_warnings(fn): + """Decorator to catch and hide warnings without visual nesting""" + @wraps(fn) + def wrapper(*args, **kwargs): + # very important to avoid uncontrolled state propagation + clean_warning_registry() + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + return fn(*args, **kwargs) + w[:] = [] + + return wrapper + + +class _IgnoreWarnings(object): + + """Improved and simplified Python warnings context manager + + Copied from Python 2.7.5 and modified as required. + """ + + def __init__(self): + """ + Parameters + ========== + category : warning class + The category to filter. Defaults to Warning. If None, + all categories will be muted. + """ + self._record = True + self._module = sys.modules['warnings'] + self._entered = False + self.log = [] + + def __repr__(self): + args = [] + if self._record: + args.append("record=True") + if self._module is not sys.modules['warnings']: + args.append("module=%r" % self._module) + name = type(self).__name__ + return "%s(%s)" % (name, ", ".join(args)) + + def __enter__(self): + clean_warning_registry() # be safe and not propagate state + chaos + warnings.simplefilter('always') + if self._entered: + raise RuntimeError("Cannot enter %r twice" % self) + self._entered = True + self._filters = self._module.filters + self._module.filters = self._filters[:] + self._showwarning = self._module.showwarning + if self._record: + self.log = [] + + def showwarning(*args, **kwargs): + self.log.append(warnings.WarningMessage(*args, **kwargs)) + self._module.showwarning = showwarning + return self.log + else: + return None + + def __exit__(self, *exc_info): + if not self._entered: + raise RuntimeError("Cannot exit %r without entering first" % self) + self._module.filters = self._filters + self._module.showwarning = self._showwarning + self.log[:] = [] + clean_warning_registry() # be safe and not propagate state + chaos + + try: from nose.tools import assert_less except ImportError: @@ -51,19 +371,54 @@ def _assert_greater(a, b, msg=None): assert_greater = _assert_greater -def fake_mldata_cache(columns_dict, dataname, matfile, ordering=None): - """Create a fake mldata data set in the cache_path. +def _assert_allclose(actual, desired, rtol=1e-7, atol=0, + err_msg='', verbose=True): + actual, desired = np.asanyarray(actual), np.asanyarray(desired) + if np.allclose(actual, desired, rtol=rtol, atol=atol): + return + msg = ('Array not equal to tolerance rtol=%g, atol=%g: ' + 'actual %s, desired %s') % (rtol, atol, actual, desired) + raise AssertionError(msg) + + +if hasattr(np.testing, 'assert_allclose'): + assert_allclose = np.testing.assert_allclose +else: + assert_allclose = _assert_allclose + + +def assert_raise_message(exception, message, function, *args, **kwargs): + """Helper function to test error messages in exceptions""" + + try: + function(*args, **kwargs) + raise AssertionError("Should have raised %r" % exception(message)) + except exception as e: + error_message = str(e) + assert_in(message, error_message) + + +def fake_mldata(columns_dict, dataname, matfile, ordering=None): + """Create a fake mldata data set. Parameters ---------- - columns_dict: contains data as - columns_dict[column_name] = array of data - dataname: name of data set - matfile: file-like object or file name - ordering: list of column_names, determines the ordering in the data set - - Note: this function transposes all arrays, while fetch_mldata only - transposes 'data', keep that into account in the tests. + columns_dict : dict, keys=str, values=ndarray + Contains data as columns_dict[column_name] = array of data. + + dataname : string + Name of data set. + + matfile : string or file object + The file name string or the file-like object of the output file. + + ordering : list, default None + List of column_names, determines the ordering in the data set. + + Notes + ----- + This function transposes all arrays, while fetch_mldata only transposes + 'data', keep that into account in the tests. """ datasets = dict(columns_dict) @@ -80,51 +435,123 @@ def fake_mldata_cache(columns_dict, dataname, matfile, ordering=None): for i, name in enumerate(ordering): datasets['mldata_descr_ordering'][0, i] = name - savemat(matfile, datasets, oned_as='column') + scipy.io.savemat(matfile, datasets, oned_as='column') -class mock_urllib2(object): +class mock_mldata_urlopen(object): def __init__(self, mock_datasets): - """Object that mocks the urllib2 module to fake requests to mldata. + """Object that mocks the urlopen function to fake requests to mldata. `mock_datasets` is a dictionary of {dataset_name: data_dict}, or {dataset_name: (data_dict, ordering). `data_dict` itself is a dictionary of {column_name: data_array}, and `ordering` is a list of column_names to determine the ordering - in the data set (see `fake_mldata_cache` for details). + in the data set (see `fake_mldata` for details). When requesting a dataset with a name that is in mock_datasets, this object creates a fake dataset in a StringIO object and - returns it. Otherwise, it raises an URLError. + returns it. Otherwise, it raises an HTTPError. """ self.mock_datasets = mock_datasets - class HTTPError(urllib2.URLError): - code = 404 - - def urlopen(self, urlname): + def __call__(self, urlname): dataset_name = urlname.split('/')[-1] if dataset_name in self.mock_datasets: resource_name = '_' + dataset_name - matfile = StringIO() + from io import BytesIO + matfile = BytesIO() dataset = self.mock_datasets[dataset_name] ordering = None if isinstance(dataset, tuple): dataset, ordering = dataset - fake_mldata_cache(dataset, resource_name, matfile, ordering) + fake_mldata(dataset, resource_name, matfile, ordering) matfile.seek(0) return matfile else: - raise mock_urllib2.HTTPError('%s not found.' % urlname) - - def quote(self, string, safe='/'): - return urllib2.quote(string, safe) + raise HTTPError(urlname, 404, dataset_name + " is not available", + [], None) + + +def install_mldata_mock(mock_datasets): + # Lazy import to avoid mutually recursive imports + from sklearn import datasets + datasets.mldata.urlopen = mock_mldata_urlopen(mock_datasets) + + +def uninstall_mldata_mock(): + # Lazy import to avoid mutually recursive imports + from sklearn import datasets + datasets.mldata.urlopen = urlopen + + +# Meta estimators need another estimator to be instantiated. +META_ESTIMATORS = ["OneVsOneClassifier", + "OutputCodeClassifier", "OneVsRestClassifier", "RFE", + "RFECV", "BaseEnsemble"] +# estimators that there is no way to default-construct sensibly +OTHER = ["Pipeline", "FeatureUnion", "GridSearchCV", + "RandomizedSearchCV"] + +# some trange ones +DONT_TEST = ['SparseCoder', 'EllipticEnvelope', 'DictVectorizer', + 'LabelBinarizer', 'LabelEncoder', + 'MultiLabelBinarizer', 'TfidfTransformer', + 'TfidfVectorizer', 'IsotonicRegression', + 'OneHotEncoder', 'RandomTreesEmbedding', + 'FeatureHasher', 'DummyClassifier', 'DummyRegressor', + 'TruncatedSVD', 'PolynomialFeatures', + 'GaussianRandomProjectionHash', 'HashingVectorizer', + 'CheckingClassifier', 'PatchExtractor', 'CountVectorizer', + # GradientBoosting base estimators, maybe should + # exclude them in another way + 'ZeroEstimator', 'ScaledLogOddsEstimator', + 'QuantileEstimator', 'MeanEstimator', + 'LogOddsEstimator', 'PriorProbabilityEstimator', + '_SigmoidCalibration'] + + +def all_estimators(include_meta_estimators=False, + include_other=False, type_filter=None, + include_dont_test=False): + """Get a list of all estimators from sklearn. + + This function crawls the module and gets all classes that inherit + from BaseEstimator. Classes that are defined in test-modules are not + included. + By default meta_estimators such as GridSearchCV are also not included. - -def all_estimators(): + Parameters + ---------- + include_meta_estimators : boolean, default=False + Whether to include meta-estimators that can be constructed using + an estimator as their first argument. These are currently + BaseEnsemble, OneVsOneClassifier, OutputCodeClassifier, + OneVsRestClassifier, RFE, RFECV. + + include_other : boolean, default=False + Wether to include meta-estimators that are somehow special and can + not be default-constructed sensibly. These are currently + Pipeline, FeatureUnion and GridSearchCV + + include_dont_test : boolean, default=False + Whether to include "special" label estimator or test processors. + + type_filter : string, list of string, or None, default=None + Which kind of estimators should be returned. If None, no filter is + applied and all estimators are returned. Possible values are + 'classifier', 'regressor', 'cluster' and 'transformer' to get + estimators only of these specific types, or a list of these to + get the estimators that fit at least one of the types. + + Returns + ------- + estimators : list of tuples + List of (name, class), where ``name`` is the class name as string + and ``class`` is the actuall type of the class. + """ def is_abstract(c): if not(hasattr(c, '__abstractmethods__')): return False @@ -135,16 +562,115 @@ def is_abstract(c): all_classes = [] # get parent folder path = sklearn.__path__ - for importer, modname, ispkg in pkgutil.walk_packages(path=path, - prefix='sklearn.', onerror=lambda x: None): + for importer, modname, ispkg in pkgutil.walk_packages( + path=path, prefix='sklearn.', onerror=lambda x: None): + if ".tests." in modname: + continue module = __import__(modname, fromlist="dummy") classes = inspect.getmembers(module, inspect.isclass) - # get rid of abstract base classes all_classes.extend(classes) all_classes = set(all_classes) - estimators = [c for c in all_classes if issubclass(c[1], BaseEstimator)] + estimators = [c for c in all_classes + if (issubclass(c[1], BaseEstimator) + and c[0] != 'BaseEstimator')] + # get rid of abstract base classes estimators = [c for c in estimators if not is_abstract(c[1])] - # We sort in order to have reproducible test failures - return sorted(estimators) + + if not include_dont_test: + estimators = [c for c in estimators if not c[0] in DONT_TEST] + + if not include_other: + estimators = [c for c in estimators if not c[0] in OTHER] + # possibly get rid of meta estimators + if not include_meta_estimators: + estimators = [c for c in estimators if not c[0] in META_ESTIMATORS] + if type_filter is not None: + if not isinstance(type_filter, list): + type_filter = [type_filter] + else: + type_filter = list(type_filter) # copy + filtered_estimators = [] + filters = {'classifier': ClassifierMixin, + 'regressor': RegressorMixin, + 'transformer': TransformerMixin, + 'cluster': ClusterMixin} + for name, mixin in filters.items(): + if name in type_filter: + type_filter.remove(name) + filtered_estimators.extend([est for est in estimators + if issubclass(est[1], mixin)]) + estimators = filtered_estimators + if type_filter: + raise ValueError("Parameter type_filter must be 'classifier', " + "'regressor', 'transformer', 'cluster' or None, got" + " %s." % repr(type_filter)) + + # drop duplicates, sort for reproducibility + return sorted(set(estimators)) + + +def set_random_state(estimator, random_state=0): + if "random_state" in estimator.get_params().keys(): + estimator.set_params(random_state=random_state) + + +def if_matplotlib(func): + """Test decorator that skips test if matplotlib not installed. """ + + @wraps(func) + def run_test(*args, **kwargs): + try: + import matplotlib + matplotlib.use('Agg', warn=False) + # this fails if no $DISPLAY specified + matplotlib.pylab.figure() + except: + raise SkipTest('Matplotlib not available.') + else: + return func(*args, **kwargs) + return run_test + + +def if_not_mac_os(versions=('10.7', '10.8', '10.9'), + message='Multi-process bug in Mac OS X >= 10.7 ' + '(see issue #636)'): + """Test decorator that skips test if OS is Mac OS X and its + major version is one of ``versions``. + """ + mac_version, _, _ = platform.mac_ver() + skip = '.'.join(mac_version.split('.')[:2]) in versions + + def decorator(func): + if skip: + @wraps(func) + def func(*args, **kwargs): + raise SkipTest(message) + return func + return decorator + + +def clean_warning_registry(): + """Safe way to reset warnings """ + warnings.resetwarnings() + reg = "__warningregistry__" + for mod_name, mod in list(sys.modules.items()): + if 'six.moves' in mod_name: + continue + if hasattr(mod, reg): + getattr(mod, reg).clear() + + +def check_skip_network(): + if int(os.environ.get('SKLEARN_SKIP_NETWORK_TESTS', 0)): + raise SkipTest("Text tutorial requires large dataset download") + + +def check_skip_travis(): + """Skip test if being run on Travis.""" + if os.environ.get('TRAVIS') == "true": + raise SkipTest("This test needs to be skipped on Travis") + +with_network = with_setup(check_skip_network) +with_travis = with_setup(check_skip_travis) diff --git a/sklearn/utils/tests/test_bench.py b/sklearn/utils/tests/test_bench.py index cac08dbb94404..102d71d7abd51 100644 --- a/sklearn/utils/tests/test_bench.py +++ b/sklearn/utils/tests/test_bench.py @@ -6,6 +6,6 @@ def test_total_seconds(): - delta = datetime.datetime(2012, 1, 1, 5, 5, 1) - datetime.datetime(2012, 1, - 1, 5, 5, 4) + delta = (datetime.datetime(2012, 1, 1, 5, 5, 1) + - datetime.datetime(2012, 1, 1, 5, 5, 4)) assert_equal(86397, total_seconds(delta)) diff --git a/sklearn/utils/tests/test_class_weight.py b/sklearn/utils/tests/test_class_weight.py new file mode 100644 index 0000000000000..920ce5893b95a --- /dev/null +++ b/sklearn/utils/tests/test_class_weight.py @@ -0,0 +1,156 @@ +import numpy as np + +from sklearn.utils.class_weight import compute_class_weight +from sklearn.utils.class_weight import compute_sample_weight + +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_equal + + +def test_compute_class_weight(): + """Test (and demo) compute_class_weight.""" + y = np.asarray([2, 2, 2, 3, 3, 4]) + classes = np.unique(y) + cw = compute_class_weight("auto", classes, y) + assert_almost_equal(cw.sum(), classes.shape) + assert_true(cw[0] < cw[1] < cw[2]) + + +def test_compute_class_weight_not_present(): + """Raise error when y does not contain all class labels""" + classes = np.arange(4) + y = np.asarray([0, 0, 0, 1, 1, 2]) + assert_raises(ValueError, compute_class_weight, "auto", classes, y) + + +def test_compute_class_weight_auto_negative(): + """Test compute_class_weight when labels are negative""" + # Test with balanced class labels. + classes = np.array([-2, -1, 0]) + y = np.asarray([-1, -1, 0, 0, -2, -2]) + cw = compute_class_weight("auto", classes, y) + assert_almost_equal(cw.sum(), classes.shape) + assert_equal(len(cw), len(classes)) + assert_array_almost_equal(cw, np.array([1., 1., 1.])) + + # Test with unbalanced class labels. + y = np.asarray([-1, 0, 0, -2, -2, -2]) + cw = compute_class_weight("auto", classes, y) + assert_almost_equal(cw.sum(), classes.shape) + assert_equal(len(cw), len(classes)) + assert_array_almost_equal(cw, np.array([0.545, 1.636, 0.818]), decimal=3) + + +def test_compute_class_weight_auto_unordered(): + """Test compute_class_weight when classes are unordered""" + classes = np.array([1, 0, 3]) + y = np.asarray([1, 0, 0, 3, 3, 3]) + cw = compute_class_weight("auto", classes, y) + assert_almost_equal(cw.sum(), classes.shape) + assert_equal(len(cw), len(classes)) + assert_array_almost_equal(cw, np.array([1.636, 0.818, 0.545]), decimal=3) + + +def test_compute_sample_weight(): + """Test (and demo) compute_sample_weight.""" + # Test with balanced classes + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("auto", y) + assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) + + # Test with user-defined weights + sample_weight = compute_sample_weight({1: 2, 2: 1}, y) + assert_array_almost_equal(sample_weight, [2., 2., 2., 1., 1., 1.]) + + # Test with column vector of balanced classes + y = np.asarray([[1], [1], [1], [2], [2], [2]]) + sample_weight = compute_sample_weight("auto", y) + assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) + + # Test with unbalanced classes + y = np.asarray([1, 1, 1, 2, 2, 2, 3]) + sample_weight = compute_sample_weight("auto", y) + expected = np.asarray([.6, .6, .6, .6, .6, .6, 1.8]) + assert_array_almost_equal(sample_weight, expected) + + # Test with `None` weights + sample_weight = compute_sample_weight(None, y) + assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1., 1.]) + + # Test with multi-output of balanced classes + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight("auto", y) + assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) + + # Test with multi-output with user-defined weights + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight([{1: 2, 2: 1}, {0: 1, 1: 2}], y) + assert_array_almost_equal(sample_weight, [2., 2., 2., 2., 2., 2.]) + + # Test with multi-output of unbalanced classes + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [3, -1]]) + sample_weight = compute_sample_weight("auto", y) + assert_array_almost_equal(sample_weight, expected ** 2) + + +def test_compute_sample_weight_with_subsample(): + """Test compute_sample_weight with subsamples specified.""" + # Test with balanced classes and all samples present + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("auto", y, range(6)) + assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) + + # Test with column vector of balanced classes and all samples present + y = np.asarray([[1], [1], [1], [2], [2], [2]]) + sample_weight = compute_sample_weight("auto", y, range(6)) + assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) + + # Test with a subsample + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("auto", y, range(4)) + assert_array_almost_equal(sample_weight, [.5, .5, .5, 1.5, 1.5, 1.5]) + + # Test with a bootstrap subsample + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("auto", y, [0, 1, 1, 2, 2, 3]) + expected = np.asarray([1/3., 1/3., 1/3., 5/3., 5/3., 5/3.]) + assert_array_almost_equal(sample_weight, expected) + + # Test with a bootstrap subsample for multi-output + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight("auto", y, [0, 1, 1, 2, 2, 3]) + assert_array_almost_equal(sample_weight, expected ** 2) + + # Test with a missing class + y = np.asarray([1, 1, 1, 2, 2, 2, 3]) + sample_weight = compute_sample_weight("auto", y, range(6)) + assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1., 0.]) + + # Test with a missing class for multi-output + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [2, 2]]) + sample_weight = compute_sample_weight("auto", y, range(6)) + assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1., 0.]) + + +def test_compute_sample_weight_errors(): + """Test compute_sample_weight raises errors expected.""" + # Invalid preset string + y = np.asarray([1, 1, 1, 2, 2, 2]) + y_ = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + assert_raises(ValueError, compute_sample_weight, "ni", y) + assert_raises(ValueError, compute_sample_weight, "ni", y, range(4)) + assert_raises(ValueError, compute_sample_weight, "ni", y_) + assert_raises(ValueError, compute_sample_weight, "ni", y_, range(4)) + + # Not "auto" for subsample + assert_raises(ValueError, + compute_sample_weight, {1: 2, 2: 1}, y, range(4)) + + # Not a list or preset for multi-output + assert_raises(ValueError, compute_sample_weight, {1: 2, 2: 1}, y_) + + # Incorrect length list for multi-output + assert_raises(ValueError, compute_sample_weight, [{1: 2, 2: 1}], y_) diff --git a/sklearn/utils/tests/test_extmath.py b/sklearn/utils/tests/test_extmath.py new file mode 100644 index 0000000000000..643a4420a6bee --- /dev/null +++ b/sklearn/utils/tests/test_extmath.py @@ -0,0 +1,475 @@ +# Authors: Olivier Grisel +# Mathieu Blondel +# Denis Engemann +# +# License: BSD 3 clause +import warnings + +import numpy as np +from scipy import sparse +from scipy import linalg +from scipy import stats + +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_almost_equal +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_raises + +from sklearn.utils.extmath import density +from sklearn.utils.extmath import logsumexp +from sklearn.utils.extmath import norm, squared_norm +from sklearn.utils.extmath import randomized_svd +from sklearn.utils.extmath import row_norms +from sklearn.utils.extmath import weighted_mode +from sklearn.utils.extmath import cartesian +from sklearn.utils.extmath import log_logistic, logistic_sigmoid +from sklearn.utils.extmath import fast_dot, _fast_dot +from sklearn.utils.extmath import svd_flip +from sklearn.utils.extmath import _batch_mean_variance_update +from sklearn.utils.extmath import _deterministic_vector_sign_flip +from sklearn.datasets.samples_generator import make_low_rank_matrix + + +def test_density(): + rng = np.random.RandomState(0) + X = rng.randint(10, size=(10, 5)) + X[1, 2] = 0 + X[5, 3] = 0 + X_csr = sparse.csr_matrix(X) + X_csc = sparse.csc_matrix(X) + X_coo = sparse.coo_matrix(X) + X_lil = sparse.lil_matrix(X) + + for X_ in (X_csr, X_csc, X_coo, X_lil): + assert_equal(density(X_), density(X)) + + +def test_uniform_weights(): + # with uniform weights, results should be identical to stats.mode + rng = np.random.RandomState(0) + x = rng.randint(10, size=(10, 5)) + weights = np.ones(x.shape) + + for axis in (None, 0, 1): + mode, score = stats.mode(x, axis) + mode2, score2 = weighted_mode(x, weights, axis) + + assert_true(np.all(mode == mode2)) + assert_true(np.all(score == score2)) + + +def test_random_weights(): + # set this up so that each row should have a weighted mode of 6, + # with a score that is easily reproduced + mode_result = 6 + + rng = np.random.RandomState(0) + x = rng.randint(mode_result, size=(100, 10)) + w = rng.random_sample(x.shape) + + x[:, :5] = mode_result + w[:, :5] += 1 + + mode, score = weighted_mode(x, w, axis=1) + + assert_array_equal(mode, mode_result) + assert_array_almost_equal(score.ravel(), w[:, :5].sum(1)) + + +def test_logsumexp(): + # Try to add some smallish numbers in logspace + x = np.array([1e-40] * 1000000) + logx = np.log(x) + assert_almost_equal(np.exp(logsumexp(logx)), x.sum()) + + X = np.vstack([x, x]) + logX = np.vstack([logx, logx]) + assert_array_almost_equal(np.exp(logsumexp(logX, axis=0)), X.sum(axis=0)) + assert_array_almost_equal(np.exp(logsumexp(logX, axis=1)), X.sum(axis=1)) + + +def test_randomized_svd_low_rank(): + """Check that extmath.randomized_svd is consistent with linalg.svd""" + n_samples = 100 + n_features = 500 + rank = 5 + k = 10 + + # generate a matrix X of approximate effective rank `rank` and no noise + # component (very structured signal): + X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, + effective_rank=rank, tail_strength=0.0, + random_state=0) + assert_equal(X.shape, (n_samples, n_features)) + + # compute the singular values of X using the slow exact method + U, s, V = linalg.svd(X, full_matrices=False) + + # compute the singular values of X using the fast approximate method + Ua, sa, Va = randomized_svd(X, k) + assert_equal(Ua.shape, (n_samples, k)) + assert_equal(sa.shape, (k,)) + assert_equal(Va.shape, (k, n_features)) + + # ensure that the singular values of both methods are equal up to the real + # rank of the matrix + assert_almost_equal(s[:k], sa) + + # check the singular vectors too (while not checking the sign) + assert_almost_equal(np.dot(U[:, :k], V[:k, :]), np.dot(Ua, Va)) + + # check the sparse matrix representation + X = sparse.csr_matrix(X) + + # compute the singular values of X using the fast approximate method + Ua, sa, Va = randomized_svd(X, k) + assert_almost_equal(s[:rank], sa[:rank]) + + +def test_norm_squared_norm(): + X = np.random.RandomState(42).randn(50, 63) + X *= 100 # check stability + X += 200 + + assert_almost_equal(np.linalg.norm(X.ravel()), norm(X)) + assert_almost_equal(norm(X) ** 2, squared_norm(X), decimal=6) + assert_almost_equal(np.linalg.norm(X), np.sqrt(squared_norm(X)), decimal=6) + + +def test_row_norms(): + X = np.random.RandomState(42).randn(100, 100) + sq_norm = (X ** 2).sum(axis=1) + + assert_array_almost_equal(sq_norm, row_norms(X, squared=True), 5) + assert_array_almost_equal(np.sqrt(sq_norm), row_norms(X)) + + Xcsr = sparse.csr_matrix(X, dtype=np.float32) + assert_array_almost_equal(sq_norm, row_norms(Xcsr, squared=True), 5) + assert_array_almost_equal(np.sqrt(sq_norm), row_norms(Xcsr)) + + +def test_randomized_svd_low_rank_with_noise(): + """Check that extmath.randomized_svd can handle noisy matrices""" + n_samples = 100 + n_features = 500 + rank = 5 + k = 10 + + # generate a matrix X wity structure approximate rank `rank` and an + # important noisy component + X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, + effective_rank=rank, tail_strength=0.5, + random_state=0) + assert_equal(X.shape, (n_samples, n_features)) + + # compute the singular values of X using the slow exact method + _, s, _ = linalg.svd(X, full_matrices=False) + + # compute the singular values of X using the fast approximate method + # without the iterated power method + _, sa, _ = randomized_svd(X, k, n_iter=0) + + # the approximation does not tolerate the noise: + assert_greater(np.abs(s[:k] - sa).max(), 0.05) + + # compute the singular values of X using the fast approximate method with + # iterated power method + _, sap, _ = randomized_svd(X, k, n_iter=5) + + # the iterated power method is helping getting rid of the noise: + assert_almost_equal(s[:k], sap, decimal=3) + + +def test_randomized_svd_infinite_rank(): + """Check that extmath.randomized_svd can handle noisy matrices""" + n_samples = 100 + n_features = 500 + rank = 5 + k = 10 + + # let us try again without 'low_rank component': just regularly but slowly + # decreasing singular values: the rank of the data matrix is infinite + X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, + effective_rank=rank, tail_strength=1.0, + random_state=0) + assert_equal(X.shape, (n_samples, n_features)) + + # compute the singular values of X using the slow exact method + _, s, _ = linalg.svd(X, full_matrices=False) + + # compute the singular values of X using the fast approximate method + # without the iterated power method + _, sa, _ = randomized_svd(X, k, n_iter=0) + + # the approximation does not tolerate the noise: + assert_greater(np.abs(s[:k] - sa).max(), 0.1) + + # compute the singular values of X using the fast approximate method with + # iterated power method + _, sap, _ = randomized_svd(X, k, n_iter=5) + + # the iterated power method is still managing to get most of the structure + # at the requested rank + assert_almost_equal(s[:k], sap, decimal=3) + + +def test_randomized_svd_transpose_consistency(): + """Check that transposing the design matrix has limit impact""" + n_samples = 100 + n_features = 500 + rank = 4 + k = 10 + + X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, + effective_rank=rank, tail_strength=0.5, + random_state=0) + assert_equal(X.shape, (n_samples, n_features)) + + U1, s1, V1 = randomized_svd(X, k, n_iter=3, transpose=False, + random_state=0) + U2, s2, V2 = randomized_svd(X, k, n_iter=3, transpose=True, + random_state=0) + U3, s3, V3 = randomized_svd(X, k, n_iter=3, transpose='auto', + random_state=0) + U4, s4, V4 = linalg.svd(X, full_matrices=False) + + assert_almost_equal(s1, s4[:k], decimal=3) + assert_almost_equal(s2, s4[:k], decimal=3) + assert_almost_equal(s3, s4[:k], decimal=3) + + assert_almost_equal(np.dot(U1, V1), np.dot(U4[:, :k], V4[:k, :]), + decimal=2) + assert_almost_equal(np.dot(U2, V2), np.dot(U4[:, :k], V4[:k, :]), + decimal=2) + + # in this case 'auto' is equivalent to transpose + assert_almost_equal(s2, s3) + + +def test_svd_flip(): + """Check that svd_flip works in both situations, and reconstructs input.""" + rs = np.random.RandomState(1999) + n_samples = 20 + n_features = 10 + X = rs.randn(n_samples, n_features) + + # Check matrix reconstruction + U, S, V = linalg.svd(X, full_matrices=False) + U1, V1 = svd_flip(U, V, u_based_decision=False) + assert_almost_equal(np.dot(U1 * S, V1), X, decimal=6) + + # Check transposed matrix reconstruction + XT = X.T + U, S, V = linalg.svd(XT, full_matrices=False) + U2, V2 = svd_flip(U, V, u_based_decision=True) + assert_almost_equal(np.dot(U2 * S, V2), XT, decimal=6) + + # Check that different flip methods are equivalent under reconstruction + U_flip1, V_flip1 = svd_flip(U, V, u_based_decision=True) + assert_almost_equal(np.dot(U_flip1 * S, V_flip1), XT, decimal=6) + U_flip2, V_flip2 = svd_flip(U, V, u_based_decision=False) + assert_almost_equal(np.dot(U_flip2 * S, V_flip2), XT, decimal=6) + + +def test_randomized_svd_sign_flip(): + a = np.array([[2.0, 0.0], [0.0, 1.0]]) + u1, s1, v1 = randomized_svd(a, 2, flip_sign=True, random_state=41) + for seed in range(10): + u2, s2, v2 = randomized_svd(a, 2, flip_sign=True, random_state=seed) + assert_almost_equal(u1, u2) + assert_almost_equal(v1, v2) + assert_almost_equal(np.dot(u2 * s2, v2), a) + assert_almost_equal(np.dot(u2.T, u2), np.eye(2)) + assert_almost_equal(np.dot(v2.T, v2), np.eye(2)) + + +def test_cartesian(): + """Check if cartesian product delivers the right results""" + + axes = (np.array([1, 2, 3]), np.array([4, 5]), np.array([6, 7])) + + true_out = np.array([[1, 4, 6], + [1, 4, 7], + [1, 5, 6], + [1, 5, 7], + [2, 4, 6], + [2, 4, 7], + [2, 5, 6], + [2, 5, 7], + [3, 4, 6], + [3, 4, 7], + [3, 5, 6], + [3, 5, 7]]) + + out = cartesian(axes) + assert_array_equal(true_out, out) + + # check single axis + x = np.arange(3) + assert_array_equal(x[:, np.newaxis], cartesian((x,))) + + +def test_logistic_sigmoid(): + """Check correctness and robustness of logistic sigmoid implementation""" + naive_logistic = lambda x: 1 / (1 + np.exp(-x)) + naive_log_logistic = lambda x: np.log(naive_logistic(x)) + + x = np.linspace(-2, 2, 50) + with warnings.catch_warnings(record=True): + assert_array_almost_equal(logistic_sigmoid(x), naive_logistic(x)) + assert_array_almost_equal(log_logistic(x), naive_log_logistic(x)) + + extreme_x = np.array([-100., 100.]) + assert_array_almost_equal(log_logistic(extreme_x), [-100, 0]) + + +def test_fast_dot(): + """Check fast dot blas wrapper function""" + if fast_dot is np.dot: + return + + rng = np.random.RandomState(42) + A = rng.random_sample([2, 10]) + B = rng.random_sample([2, 10]) + + try: + linalg.get_blas_funcs(['gemm'])[0] + has_blas = True + except (AttributeError, ValueError): + has_blas = False + + if has_blas: + # Test _fast_dot for invalid input. + + # Maltyped data. + for dt1, dt2 in [['f8', 'f4'], ['i4', 'i4']]: + assert_raises(ValueError, _fast_dot, A.astype(dt1), + B.astype(dt2).T) + + # Malformed data. + + ## ndim == 0 + E = np.empty(0) + assert_raises(ValueError, _fast_dot, E, E) + + ## ndim == 1 + assert_raises(ValueError, _fast_dot, A, A[0]) + + ## ndim > 2 + assert_raises(ValueError, _fast_dot, A.T, np.array([A, A])) + + ## min(shape) == 1 + assert_raises(ValueError, _fast_dot, A, A[0, :][None, :]) + + # test for matrix mismatch error + assert_raises(ValueError, _fast_dot, A, A) + + # Test cov-like use case + dtypes. + for dtype in ['f8', 'f4']: + A = A.astype(dtype) + B = B.astype(dtype) + + # col < row + C = np.dot(A.T, A) + C_ = fast_dot(A.T, A) + assert_almost_equal(C, C_, decimal=5) + + C = np.dot(A.T, B) + C_ = fast_dot(A.T, B) + assert_almost_equal(C, C_, decimal=5) + + C = np.dot(A, B.T) + C_ = fast_dot(A, B.T) + assert_almost_equal(C, C_, decimal=5) + + # Test square matrix * rectangular use case. + A = rng.random_sample([2, 2]) + for dtype in ['f8', 'f4']: + A = A.astype(dtype) + B = B.astype(dtype) + + C = np.dot(A, B) + C_ = fast_dot(A, B) + assert_almost_equal(C, C_, decimal=5) + + C = np.dot(A.T, B) + C_ = fast_dot(A.T, B) + assert_almost_equal(C, C_, decimal=5) + + if has_blas: + for x in [np.array([[d] * 10] * 2) for d in [np.inf, np.nan]]: + assert_raises(ValueError, _fast_dot, x, x.T) + + +def test_incremental_variance_update_formulas(): + """Test Youngs and Cramer incremental variance formulas.""" + # Doggie data from http://www.mathsisfun.com/data/standard-deviation.html + A = np.array([[600, 470, 170, 430, 300], + [600, 470, 170, 430, 300], + [600, 470, 170, 430, 300], + [600, 470, 170, 430, 300]]).T + idx = 2 + X1 = A[:idx, :] + X2 = A[idx:, :] + + old_means = X1.mean(axis=0) + old_variances = X1.var(axis=0) + old_sample_count = X1.shape[0] + final_means, final_variances, final_count = _batch_mean_variance_update( + X2, old_means, old_variances, old_sample_count) + assert_almost_equal(final_means, A.mean(axis=0), 6) + assert_almost_equal(final_variances, A.var(axis=0), 6) + assert_almost_equal(final_count, A.shape[0]) + + +def test_incremental_variance_ddof(): + """Test that degrees of freedom parameter for calculations are correct.""" + rng = np.random.RandomState(1999) + X = rng.randn(50, 10) + n_samples, n_features = X.shape + for batch_size in [11, 20, 37]: + steps = np.arange(0, X.shape[0], batch_size) + if steps[-1] != X.shape[0]: + steps = np.hstack([steps, n_samples]) + + for i, j in zip(steps[:-1], steps[1:]): + batch = X[i:j, :] + if i == 0: + incremental_means = batch.mean(axis=0) + incremental_variances = batch.var(axis=0) + # Assign this twice so that the test logic is consistent + incremental_count = batch.shape[0] + sample_count = batch.shape[0] + else: + result = _batch_mean_variance_update(batch, incremental_means, + incremental_variances, + sample_count) + (incremental_means, incremental_variances, + incremental_count) = result + sample_count += batch.shape[0] + + calculated_means = np.mean(X[:j], axis=0) + calculated_variances = np.var(X[:j], axis=0) + assert_almost_equal(incremental_means, calculated_means, 6) + assert_almost_equal(incremental_variances, + calculated_variances, 6) + assert_equal(incremental_count, sample_count) + + +def test_vector_sign_flip(): + # Testing that sign flip is working & largest value has positive sign + data = np.random.RandomState(36).randn(5, 5) + max_abs_rows = np.argmax(np.abs(data), axis=1) + data_flipped = _deterministic_vector_sign_flip(data) + max_rows = np.argmax(data_flipped, axis=1) + assert_array_equal(max_abs_rows, max_rows) + signs = np.sign(data[range(data.shape[0]), max_abs_rows]) + assert_array_equal(data, data_flipped * signs[:, np.newaxis]) + + +if __name__ == '__main__': + import nose + nose.runmodule() diff --git a/sklearn/utils/tests/test_fast_dict.py b/sklearn/utils/tests/test_fast_dict.py new file mode 100644 index 0000000000000..0c0015c468d87 --- /dev/null +++ b/sklearn/utils/tests/test_fast_dict.py @@ -0,0 +1,32 @@ +""" Test fast_dict. +""" +import numpy as np +from nose.tools import assert_equal + +from sklearn.utils.fast_dict import IntFloatDict, argmin +from sklearn.externals.six.moves import xrange + +def test_int_float_dict(): + rng = np.random.RandomState(0) + keys = np.unique(rng.randint(100, size=10).astype(np.intp)) + values = rng.rand(len(keys)) + + d = IntFloatDict(keys, values) + for key, value in zip(keys, values): + assert_equal(d[key], value) + assert_equal(len(d), len(keys)) + + d.append(120, 3.) + assert_equal(d[120], 3.0) + assert_equal(len(d), len(keys) + 1) + for i in xrange(2000): + d.append(i + 1000, 4.0) + assert_equal(d[1100], 4.0) + + +def test_int_float_dict_argmin(): + # Test the argmin implementation on the IntFloatDict + keys = np.arange(100, dtype=np.intp) + values = np.arange(100, dtype=np.float) + d = IntFloatDict(keys, values) + assert_equal(argmin(d), (0, 0)) diff --git a/sklearn/utils/tests/test_fixes.py b/sklearn/utils/tests/test_fixes.py index 232331ed56c79..fde18d7c8999e 100644 --- a/sklearn/utils/tests/test_fixes.py +++ b/sklearn/utils/tests/test_fixes.py @@ -1,24 +1,30 @@ -# Authors: Emmanuelle Gouillart -# Gael Varoquaux -# License: BSD +# Authors: Gael Varoquaux +# Justin Vincent +# Lars Buitinck +# License: BSD 3 clause import numpy as np from nose.tools import assert_equal -from numpy.testing import assert_array_equal +from numpy.testing import (assert_almost_equal, + assert_array_almost_equal) -from ..fixes import _in1d, _copysign +from sklearn.utils.fixes import divide, expit -def test_in1d(): - a = np.arange(10) - b = a[a % 2 == 0] - assert_equal(_in1d(a, b).sum(), 5) +def test_expit(): + """Check numerical stability of expit (logistic function).""" + # Simulate our previous Cython implementation, based on + #http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression + assert_almost_equal(expit(1000.), 1. / (1. + np.exp(-1000.)), decimal=16) + assert_almost_equal(expit(-1000.), np.exp(-1000.) / (1. + np.exp(-1000.)), + decimal=16) -def test_copysign(): - a = np.array([-1, 1, -1]) - b = np.array([1, -1, 1]) + x = np.arange(10) + out = np.zeros_like(x, dtype=np.float32) + assert_array_almost_equal(expit(x), expit(x, out=out)) - assert_array_equal(_copysign(a, b), b) - assert_array_equal(_copysign(b, a), a) + +def test_divide(): + assert_equal(divide(.6, 1), .600000000000) diff --git a/sklearn/utils/tests/test_graph.py b/sklearn/utils/tests/test_graph.py index ab223d350f720..ffdbb6ee9add7 100644 --- a/sklearn/utils/tests/test_graph.py +++ b/sklearn/utils/tests/test_graph.py @@ -1,26 +1,24 @@ # Author: Gael Varoquaux -# License: BSD +# License: BSD 3 clause import numpy as np from scipy import sparse -from ..graph import graph_laplacian +from sklearn.utils.graph import graph_laplacian def test_graph_laplacian(): for mat in (np.arange(10) * np.arange(10)[:, np.newaxis], np.ones((7, 7)), np.eye(19), - np.vander(np.arange(4)) + np.vander(np.arange(4)).T, - ): + np.vander(np.arange(4)) + np.vander(np.arange(4)).T,): sp_mat = sparse.csr_matrix(mat) for normed in (True, False): laplacian = graph_laplacian(mat, normed=normed) n_nodes = mat.shape[0] if not normed: np.testing.assert_array_almost_equal(laplacian.sum(axis=0), - np.zeros(n_nodes)) - np.testing.assert_array_almost_equal(laplacian.T, - laplacian) - np.testing.assert_array_almost_equal(laplacian, - graph_laplacian(sp_mat, normed=normed).todense()) + np.zeros(n_nodes)) + np.testing.assert_array_almost_equal(laplacian.T, laplacian) + np.testing.assert_array_almost_equal( + laplacian, graph_laplacian(sp_mat, normed=normed).toarray()) diff --git a/sklearn/utils/tests/test_linear_assignment.py b/sklearn/utils/tests/test_linear_assignment.py new file mode 100644 index 0000000000000..36299536e1e05 --- /dev/null +++ b/sklearn/utils/tests/test_linear_assignment.py @@ -0,0 +1,60 @@ +# Author: Brian M. Clapper, G Varoquaux +# License: BSD + +import numpy as np + +# XXX we should be testing the public API here +from sklearn.utils.linear_assignment_ import _hungarian + + +def test_hungarian(): + matrices = [ + # Square + ([[400, 150, 400], + [400, 450, 600], + [300, 225, 300]], + 850 # expected cost + ), + + # Rectangular variant + ([[400, 150, 400, 1], + [400, 450, 600, 2], + [300, 225, 300, 3]], + 452 # expected cost + ), + + # Square + ([[10, 10, 8], + [9, 8, 1], + [9, 7, 4]], + 18 + ), + + # Rectangular variant + ([[10, 10, 8, 11], + [9, 8, 1, 1], + [9, 7, 4, 10]], + 15 + ), + + # n == 2, m == 0 matrix + ([[], []], + 0 + ), + ] + + for cost_matrix, expected_total in matrices: + cost_matrix = np.array(cost_matrix) + indexes = _hungarian(cost_matrix) + total_cost = 0 + for r, c in indexes: + x = cost_matrix[r, c] + total_cost += x + assert expected_total == total_cost + + indexes = _hungarian(cost_matrix.T) + total_cost = 0 + for c, r in indexes: + x = cost_matrix[r, c] + total_cost += x + assert expected_total == total_cost diff --git a/sklearn/utils/tests/test_logsumexp.py b/sklearn/utils/tests/test_logsumexp.py deleted file mode 100644 index 24505a0b93877..0000000000000 --- a/sklearn/utils/tests/test_logsumexp.py +++ /dev/null @@ -1,16 +0,0 @@ -from sklearn.utils.extmath import logsumexp - -from numpy.testing import assert_almost_equal, assert_array_almost_equal -import numpy as np - - -def test_logsumexp(): - # Try to add some smallish numbers in logspace - x = np.array([1e-40] * 1000000) - logx = np.log(x) - assert_almost_equal(np.exp(logsumexp(logx)), x.sum()) - - X = np.vstack([x, x]) - logX = np.vstack([logx, logx]) - assert_array_almost_equal(np.exp(logsumexp(logX, axis=0)), X.sum(axis=0)) - assert_array_almost_equal(np.exp(logsumexp(logX, axis=1)), X.sum(axis=1)) diff --git a/sklearn/utils/tests/test_metaestimators.py b/sklearn/utils/tests/test_metaestimators.py new file mode 100644 index 0000000000000..2ec07772cd3c8 --- /dev/null +++ b/sklearn/utils/tests/test_metaestimators.py @@ -0,0 +1,26 @@ +from sklearn.utils.metaestimators import if_delegate_has_method +from nose.tools import assert_true + + +class Prefix(object): + def func(): + pass + + +class MockMetaEstimator(object): + """This is a mock meta estimator""" + a_prefix = Prefix() + + @if_delegate_has_method(delegate="a_prefix") + def func(self): + """This is a mock delegated function""" + pass + + +def test_delegated_docstring(): + assert_true("This is a mock delegated function" + in str(MockMetaEstimator.__dict__['func'].__doc__)) + assert_true("This is a mock delegated function" + in str(MockMetaEstimator.func.__doc__)) + assert_true("This is a mock delegated function" + in str(MockMetaEstimator().func.__doc__)) diff --git a/sklearn/utils/tests/test_multiclass.py b/sklearn/utils/tests/test_multiclass.py new file mode 100644 index 0000000000000..d5f6b695e04af --- /dev/null +++ b/sklearn/utils/tests/test_multiclass.py @@ -0,0 +1,399 @@ +from __future__ import division +import numpy as np +import scipy.sparse as sp + +from itertools import product +from functools import partial +from sklearn.externals.six.moves import xrange +from sklearn.externals.six import iteritems + +from scipy.sparse import issparse +from scipy.sparse import csc_matrix +from scipy.sparse import csr_matrix +from scipy.sparse import coo_matrix +from scipy.sparse import dok_matrix +from scipy.sparse import lil_matrix + +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_warns +from sklearn.utils.testing import ignore_warnings + +from sklearn.utils.multiclass import unique_labels +from sklearn.utils.multiclass import is_label_indicator_matrix +from sklearn.utils.multiclass import is_multilabel +from sklearn.utils.multiclass import is_sequence_of_sequences +from sklearn.utils.multiclass import type_of_target +from sklearn.utils.multiclass import class_distribution + + +class NotAnArray(object): + """An object that is convertable to an array. This is useful to + simulate a Pandas timeseries.""" + + def __init__(self, data): + self.data = data + + def __array__(self): + return self.data + + +EXAMPLES = { + 'multilabel-indicator': [ + # valid when the data is formated as sparse or dense, identified + # by CSR format when the testing takes place + csr_matrix(np.random.RandomState(42).randint(2, size=(10, 10))), + csr_matrix(np.array([[0, 1], [1, 0]])), + csr_matrix(np.array([[0, 1], [1, 0]], dtype=np.bool)), + csr_matrix(np.array([[0, 1], [1, 0]], dtype=np.int8)), + csr_matrix(np.array([[0, 1], [1, 0]], dtype=np.uint8)), + csr_matrix(np.array([[0, 1], [1, 0]], dtype=np.float)), + csr_matrix(np.array([[0, 1], [1, 0]], dtype=np.float32)), + csr_matrix(np.array([[0, 0], [0, 0]])), + csr_matrix(np.array([[0, 1]])), + # Only valid when data is dense + np.array([[-1, 1], [1, -1]]), + np.array([[-3, 3], [3, -3]]), + NotAnArray(np.array([[-3, 3], [3, -3]])), + ], + 'multilabel-sequences': [ + [[0, 1]], + [[0], [1]], + [[1, 2, 3]], + [[1, 2, 1]], # duplicate values, why not? + [[1], [2], [0, 1]], + [[1], [2]], + [[]], + [()], + np.array([[], [1, 2]], dtype='object'), + NotAnArray(np.array([[], [1, 2]], dtype='object')), + ], + 'multiclass': [ + [1, 0, 2, 2, 1, 4, 2, 4, 4, 4], + np.array([1, 0, 2]), + np.array([1, 0, 2], dtype=np.int8), + np.array([1, 0, 2], dtype=np.uint8), + np.array([1, 0, 2], dtype=np.float), + np.array([1, 0, 2], dtype=np.float32), + np.array([[1], [0], [2]]), + NotAnArray(np.array([1, 0, 2])), + [0, 1, 2], + ['a', 'b', 'c'], + np.array([u'a', u'b', u'c']), + np.array([u'a', u'b', u'c'], dtype=object), + np.array(['a', 'b', 'c'], dtype=object), + ], + 'multiclass-multioutput': [ + np.array([[1, 0, 2, 2], [1, 4, 2, 4]]), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.int8), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.uint8), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.float), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.float32), + np.array([['a', 'b'], ['c', 'd']]), + np.array([[u'a', u'b'], [u'c', u'd']]), + np.array([[u'a', u'b'], [u'c', u'd']], dtype=object), + np.array([[1, 0, 2]]), + NotAnArray(np.array([[1, 0, 2]])), + ], + 'binary': [ + [0, 1], + [1, 1], + [], + [0], + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1]), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.bool), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.int8), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.uint8), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.float), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.float32), + np.array([[0], [1]]), + NotAnArray(np.array([[0], [1]])), + [1, -1], + [3, 5], + ['a'], + ['a', 'b'], + ['abc', 'def'], + np.array(['abc', 'def']), + [u'a', u'b'], + np.array(['abc', 'def'], dtype=object), + ], + 'continuous': [ + [1e-5], + [0, .5], + np.array([[0], [.5]]), + np.array([[0], [.5]], dtype=np.float32), + ], + 'continuous-multioutput': [ + np.array([[0, .5], [.5, 0]]), + np.array([[0, .5], [.5, 0]], dtype=np.float32), + np.array([[0, .5]]), + ], + 'unknown': [ + # empty second dimension + np.array([[], []]), + # 3d + np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]), + # not currently supported sequence of sequences + np.array([np.array([]), np.array([1, 2, 3])], dtype=object), + [np.array([]), np.array([1, 2, 3])], + [set([1, 2, 3]), set([1, 2])], + [frozenset([1, 2, 3]), frozenset([1, 2])], + # and also confusable as sequences of sequences + [{0: 'a', 1: 'b'}, {0: 'a'}], + ] +} + + +NON_ARRAY_LIKE_EXAMPLES = [ + set([1, 2, 3]), + {0: 'a', 1: 'b'}, + {0: [5], 1: [5]}, + 'abc', + frozenset([1, 2, 3]), + None, +] + + +def test_unique_labels(): + # Empty iterable + assert_raises(ValueError, unique_labels) + + # Multiclass problem + assert_array_equal(unique_labels(xrange(10)), np.arange(10)) + assert_array_equal(unique_labels(np.arange(10)), np.arange(10)) + assert_array_equal(unique_labels([4, 0, 2]), np.array([0, 2, 4])) + + # Multilabels + assert_array_equal(assert_warns(DeprecationWarning, + unique_labels, + [(0, 1, 2), (0,), tuple(), (2, 1)]), + np.arange(3)) + assert_array_equal(assert_warns(DeprecationWarning, + unique_labels, + [[0, 1, 2], [0], list(), [2, 1]]), + np.arange(3)) + + assert_array_equal(unique_labels(np.array([[0, 0, 1], + [1, 0, 1], + [0, 0, 0]])), + np.arange(3)) + + assert_array_equal(unique_labels(np.array([[0, 0, 1], + [0, 0, 0]])), + np.arange(3)) + + # Several arrays passed + assert_array_equal(unique_labels([4, 0, 2], xrange(5)), + np.arange(5)) + assert_array_equal(unique_labels((0, 1, 2), (0,), (2, 1)), + np.arange(3)) + + # Border line case with binary indicator matrix + assert_raises(ValueError, unique_labels, [4, 0, 2], np.ones((5, 5))) + assert_raises(ValueError, unique_labels, np.ones((5, 4)), np.ones((5, 5))) + assert_array_equal(unique_labels(np.ones((4, 5)), np.ones((5, 5))), + np.arange(5)) + + # Some tests with strings input + assert_array_equal(unique_labels(["a", "b", "c"], ["d"]), + ["a", "b", "c", "d"]) + + assert_array_equal(assert_warns(DeprecationWarning, unique_labels, + [["a", "b"], ["c"]], [["d"]]), + ["a", "b", "c", "d"]) + + +@ignore_warnings +def test_unique_labels_non_specific(): + """Test unique_labels with a variety of collected examples""" + + # Smoke test for all supported format + for format in ["binary", "multiclass", "multilabel-sequences", + "multilabel-indicator"]: + for y in EXAMPLES[format]: + unique_labels(y) + + # We don't support those format at the moment + for example in NON_ARRAY_LIKE_EXAMPLES: + assert_raises(ValueError, unique_labels, example) + + for y_type in ["unknown", "continuous", 'continuous-multioutput', + 'multiclass-multioutput']: + for example in EXAMPLES[y_type]: + assert_raises(ValueError, unique_labels, example) + + +@ignore_warnings +def test_unique_labels_mixed_types(): + # Mix of multilabel-indicator and multilabel-sequences + mix_multilabel_format = product(EXAMPLES["multilabel-indicator"], + EXAMPLES["multilabel-sequences"]) + for y_multilabel, y_multiclass in mix_multilabel_format: + assert_raises(ValueError, unique_labels, y_multiclass, y_multilabel) + assert_raises(ValueError, unique_labels, y_multilabel, y_multiclass) + + # Mix with binary or multiclass and multilabel + mix_clf_format = product(EXAMPLES["multilabel-indicator"] + + EXAMPLES["multilabel-sequences"], + EXAMPLES["multiclass"] + + EXAMPLES["binary"]) + + for y_multilabel, y_multiclass in mix_clf_format: + assert_raises(ValueError, unique_labels, y_multiclass, y_multilabel) + assert_raises(ValueError, unique_labels, y_multilabel, y_multiclass) + + # Mix string and number input type + assert_raises(ValueError, unique_labels, [[1, 2], [3]], + [["a", "d"]]) + assert_raises(ValueError, unique_labels, ["1", 2]) + assert_raises(ValueError, unique_labels, [["1", 2], [3]]) + assert_raises(ValueError, unique_labels, [["1", "2"], [3]]) + + assert_array_equal(unique_labels([(2,), (0, 2,)], [(), ()]), [0, 2]) + assert_array_equal(unique_labels([("2",), ("0", "2",)], [(), ()]), + ["0", "2"]) + + +@ignore_warnings +def test_is_multilabel(): + for group, group_examples in iteritems(EXAMPLES): + if group.startswith('multilabel'): + assert_, exp = assert_true, 'True' + else: + assert_, exp = assert_false, 'False' + for example in group_examples: + assert_(is_multilabel(example), + msg='is_multilabel(%r) should be %s' % (example, exp)) + + +def test_is_label_indicator_matrix(): + for group, group_examples in iteritems(EXAMPLES): + if group in ['multilabel-indicator']: + dense_assert_, dense_exp = assert_true, 'True' + else: + dense_assert_, dense_exp = assert_false, 'False' + + for example in group_examples: + # Only mark explicitly defined sparse examples as valid sparse + # multilabel-indicators + if group == 'multilabel-indicator' and issparse(example): + sparse_assert_, sparse_exp = assert_true, 'True' + else: + sparse_assert_, sparse_exp = assert_false, 'False' + + if (issparse(example) or + (hasattr(example, '__array__') and + np.asarray(example).ndim == 2 and + np.asarray(example).dtype.kind in 'biuf' and + np.asarray(example).shape[1] > 0)): + examples_sparse = [sparse_matrix(example) + for sparse_matrix in [coo_matrix, + csc_matrix, + csr_matrix, + dok_matrix, + lil_matrix]] + for exmpl_sparse in examples_sparse: + sparse_assert_(is_label_indicator_matrix(exmpl_sparse), + msg=('is_label_indicator_matrix(%r)' + ' should be %s') + % (exmpl_sparse, sparse_exp)) + + # Densify sparse examples before testing + if issparse(example): + example = example.toarray() + + dense_assert_(is_label_indicator_matrix(example), + msg='is_label_indicator_matrix(%r) should be %s' + % (example, dense_exp)) + + +def test_is_sequence_of_sequences(): + for group, group_examples in iteritems(EXAMPLES): + if group == 'multilabel-sequences': + assert_, exp = assert_true, 'True' + check = partial(assert_warns, DeprecationWarning, + is_sequence_of_sequences) + else: + assert_, exp = assert_false, 'False' + check = is_sequence_of_sequences + for example in group_examples: + assert_(check(example), + msg='is_sequence_of_sequences(%r) should be %s' + % (example, exp)) + + +@ignore_warnings +def test_type_of_target(): + for group, group_examples in iteritems(EXAMPLES): + for example in group_examples: + assert_equal(type_of_target(example), group, + msg='type_of_target(%r) should be %r, got %r' + % (example, group, type_of_target(example))) + + for example in NON_ARRAY_LIKE_EXAMPLES: + assert_raises(ValueError, type_of_target, example) + + +def test_class_distribution(): + y = np.array([[1, 0, 0, 1], + [2, 2, 0, 1], + [1, 3, 0, 1], + [4, 2, 0, 1], + [2, 0, 0, 1], + [1, 3, 0, 1]]) + # Define the sparse matrix with a mix of implicit and explicit zeros + data = np.array([1, 2, 1, 4, 2, 1, 0, 2, 3, 2, 3, 1, 1, 1, 1, 1, 1]) + indices = np.array([0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 5, 0, 1, 2, 3, 4, 5]) + indptr = np.array([0, 6, 11, 11, 17]) + y_sp = sp.csc_matrix((data, indices, indptr), shape=(6, 4)) + + classes, n_classes, class_prior = class_distribution(y) + classes_sp, n_classes_sp, class_prior_sp = class_distribution(y_sp) + classes_expected = [[1, 2, 4], + [0, 2, 3], + [0], + [1]] + n_classes_expected = [3, 3, 1, 1] + class_prior_expected = [[3/6, 2/6, 1/6], + [1/3, 1/3, 1/3], + [1.0], + [1.0]] + + for k in range(y.shape[1]): + assert_array_almost_equal(classes[k], classes_expected[k]) + assert_array_almost_equal(n_classes[k], n_classes_expected[k]) + assert_array_almost_equal(class_prior[k], class_prior_expected[k]) + + assert_array_almost_equal(classes_sp[k], classes_expected[k]) + assert_array_almost_equal(n_classes_sp[k], n_classes_expected[k]) + assert_array_almost_equal(class_prior_sp[k], class_prior_expected[k]) + + # Test again with explicit sample weights + (classes, + n_classes, + class_prior) = class_distribution(y, [1.0, 2.0, 1.0, 2.0, 1.0, 2.0]) + (classes_sp, + n_classes_sp, + class_prior_sp) = class_distribution(y, [1.0, 2.0, 1.0, 2.0, 1.0, 2.0]) + class_prior_expected = [[4/9, 3/9, 2/9], + [2/9, 4/9, 3/9], + [1.0], + [1.0]] + + for k in range(y.shape[1]): + assert_array_almost_equal(classes[k], classes_expected[k]) + assert_array_almost_equal(n_classes[k], n_classes_expected[k]) + assert_array_almost_equal(class_prior[k], class_prior_expected[k]) + + assert_array_almost_equal(classes_sp[k], classes_expected[k]) + assert_array_almost_equal(n_classes_sp[k], n_classes_expected[k]) + assert_array_almost_equal(class_prior_sp[k], class_prior_expected[k]) + + +if __name__ == "__main__": + import nose + nose.runmodule() diff --git a/sklearn/utils/tests/test_murmurhash.py b/sklearn/utils/tests/test_murmurhash.py index f56f5cee5c275..84522f0b90e94 100644 --- a/sklearn/utils/tests/test_murmurhash.py +++ b/sklearn/utils/tests/test_murmurhash.py @@ -1,8 +1,9 @@ # Author: Olivier Grisel # -# License: BSD Style. +# License: BSD 3 clause import numpy as np +from sklearn.externals.six import b, u from sklearn.utils.murmurhash import murmurhash3_32 from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_equal @@ -18,9 +19,9 @@ def test_mmhash3_int(): assert_equal(murmurhash3_32(3, seed=0, positive=False), 847579505) assert_equal(murmurhash3_32(3, seed=42, positive=False), -1823081949) - assert_equal(murmurhash3_32(3, positive=True), 847579505L) - assert_equal(murmurhash3_32(3, seed=0, positive=True), 847579505L) - assert_equal(murmurhash3_32(3, seed=42, positive=True), 2471885347L) + assert_equal(murmurhash3_32(3, positive=True), 847579505) + assert_equal(murmurhash3_32(3, seed=0, positive=True), 847579505) + assert_equal(murmurhash3_32(3, seed=42, positive=True), 2471885347) def test_mmhash3_int_array(): @@ -43,26 +44,26 @@ def test_mmhash3_int_array(): def test_mmhash3_bytes(): - assert_equal(murmurhash3_32('foo', 0), -156908512) - assert_equal(murmurhash3_32('foo', 42), -1322301282) + assert_equal(murmurhash3_32(b('foo'), 0), -156908512) + assert_equal(murmurhash3_32(b('foo'), 42), -1322301282) - assert_equal(murmurhash3_32('foo', 0, positive=True), 4138058784L) - assert_equal(murmurhash3_32('foo', 42, positive=True), 2972666014L) + assert_equal(murmurhash3_32(b('foo'), 0, positive=True), 4138058784) + assert_equal(murmurhash3_32(b('foo'), 42, positive=True), 2972666014) def test_mmhash3_unicode(): - assert_equal(murmurhash3_32(u'foo', 0), -156908512) - assert_equal(murmurhash3_32(u'foo', 42), -1322301282) + assert_equal(murmurhash3_32(u('foo'), 0), -156908512) + assert_equal(murmurhash3_32(u('foo'), 42), -1322301282) - assert_equal(murmurhash3_32(u'foo', 0, positive=True), 4138058784L) - assert_equal(murmurhash3_32(u'foo', 42, positive=True), 2972666014L) + assert_equal(murmurhash3_32(u('foo'), 0, positive=True), 4138058784) + assert_equal(murmurhash3_32(u('foo'), 42, positive=True), 2972666014) def test_no_collision_on_byte_range(): previous_hashes = set() for i in range(100): h = murmurhash3_32(' ' * i, 0) - assert_true(h not in previous_hashes, \ + assert_true(h not in previous_hashes, "Found collision on growing empty string") diff --git a/sklearn/utils/tests/test_random.py b/sklearn/utils/tests/test_random.py new file mode 100644 index 0000000000000..7538117d53909 --- /dev/null +++ b/sklearn/utils/tests/test_random.py @@ -0,0 +1,187 @@ +from __future__ import division + +import numpy as np +import scipy.sparse as sp +from scipy.misc import comb as combinations +from numpy.testing import assert_array_almost_equal +from sklearn.utils.random import sample_without_replacement +from sklearn.utils.random import random_choice_csc + +from sklearn.utils.testing import ( + assert_raises, + assert_equal, + assert_true) + + +############################################################################### +# test custom sampling without replacement algorithm +############################################################################### +def test_invalid_sample_without_replacement_algorithm(): + assert_raises(ValueError, sample_without_replacement, 5, 4, "unknown") + + +def test_sample_without_replacement_algorithms(): + methods = ("auto", "tracking_selection", "reservoir_sampling", "pool") + + for m in methods: + def sample_without_replacement_method(n_population, n_samples, + random_state=None): + return sample_without_replacement(n_population, n_samples, + method=m, + random_state=random_state) + + check_edge_case_of_sample_int(sample_without_replacement_method) + check_sample_int(sample_without_replacement_method) + check_sample_int_distribution(sample_without_replacement_method) + + +def check_edge_case_of_sample_int(sample_without_replacement): + + # n_poluation < n_sample + assert_raises(ValueError, sample_without_replacement, 0, 1) + assert_raises(ValueError, sample_without_replacement, 1, 2) + + # n_population == n_samples + assert_equal(sample_without_replacement(0, 0).shape, (0, )) + + assert_equal(sample_without_replacement(1, 1).shape, (1, )) + + # n_population >= n_samples + assert_equal(sample_without_replacement(5, 0).shape, (0, )) + assert_equal(sample_without_replacement(5, 1).shape, (1, )) + + # n_population < 0 or n_samples < 0 + assert_raises(ValueError, sample_without_replacement, -1, 5) + assert_raises(ValueError, sample_without_replacement, 5, -1) + + +def check_sample_int(sample_without_replacement): + # This test is heavily inspired from test_random.py of python-core. + # + # For the entire allowable range of 0 <= k <= N, validate that + # the sample is of the correct length and contains only unique items + n_population = 100 + + for n_samples in range(n_population + 1): + s = sample_without_replacement(n_population, n_samples) + assert_equal(len(s), n_samples) + unique = np.unique(s) + assert_equal(np.size(unique), n_samples) + assert_true(np.all(unique < n_population)) + + # test edge case n_population == n_samples == 0 + assert_equal(np.size(sample_without_replacement(0, 0)), 0) + + +def check_sample_int_distribution(sample_without_replacement): + # This test is heavily inspired from test_random.py of python-core. + # + # For the entire allowable range of 0 <= k <= N, validate that + # sample generates all possible permutations + n_population = 10 + + # a large number of trials prevents false negatives without slowing normal + # case + n_trials = 10000 + + for n_samples in range(n_population): + # Counting the number of combinations is not as good as counting the + # the number of permutations. However, it works with sampling algorithm + # that does not provide a random permutation of the subset of integer. + n_expected = combinations(n_population, n_samples, exact=True) + + output = {} + for i in range(n_trials): + output[frozenset(sample_without_replacement(n_population, + n_samples))] = None + + if len(output) == n_expected: + break + else: + raise AssertionError( + "number of combinations != number of expected (%s != %s)" % + (len(output), n_expected)) + + +def test_random_choice_csc(n_samples=10000, random_state=24): + # Explicit class probabilities + classes = [np.array([0, 1]), np.array([0, 1, 2])] + class_probabilites = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])] + + got = random_choice_csc(n_samples, classes, class_probabilites, + random_state) + assert_true(sp.issparse(got)) + + for k in range(len(classes)): + p = np.bincount(got.getcol(k).toarray().ravel()) / float(n_samples) + assert_array_almost_equal(class_probabilites[k], p, decimal=1) + + # Implicit class probabilities + classes = [[0, 1], [1, 2]] # test for array-like support + class_probabilites = [np.array([0.5, 0.5]), np.array([0, 1/2, 1/2])] + + got = random_choice_csc(n_samples=n_samples, + classes=classes, + random_state=random_state) + assert_true(sp.issparse(got)) + + for k in range(len(classes)): + p = np.bincount(got.getcol(k).toarray().ravel()) / float(n_samples) + assert_array_almost_equal(class_probabilites[k], p, decimal=1) + + # Edge case proabilites 1.0 and 0.0 + classes = [np.array([0, 1]), np.array([0, 1, 2])] + class_probabilites = [np.array([1.0, 0.0]), np.array([0.0, 1.0, 0.0])] + + got = random_choice_csc(n_samples, classes, class_probabilites, + random_state) + assert_true(sp.issparse(got)) + + for k in range(len(classes)): + p = np.bincount(got.getcol(k).toarray().ravel(), + minlength=len(class_probabilites[k])) / n_samples + assert_array_almost_equal(class_probabilites[k], p, decimal=1) + + # One class target data + classes = [[1], [0]] # test for array-like support + class_probabilites = [np.array([0.0, 1.0]), np.array([1.0])] + + got = random_choice_csc(n_samples=n_samples, + classes=classes, + random_state=random_state) + assert_true(sp.issparse(got)) + + for k in range(len(classes)): + p = np.bincount(got.getcol(k).toarray().ravel()) / n_samples + assert_array_almost_equal(class_probabilites[k], p, decimal=1) + + +def test_random_choice_csc_errors(): + # the length of an array in classes and class_probabilites is mismatched + classes = [np.array([0, 1]), np.array([0, 1, 2, 3])] + class_probabilites = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])] + assert_raises(ValueError, random_choice_csc, 4, classes, + class_probabilites, 1) + + # the class dtype is not supported + classes = [np.array(["a", "1"]), np.array(["z", "1", "2"])] + class_probabilites = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])] + assert_raises(ValueError, random_choice_csc, 4, classes, + class_probabilites, 1) + + # the class dtype is not supported + classes = [np.array([4.2, 0.1]), np.array([0.1, 0.2, 9.4])] + class_probabilites = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])] + assert_raises(ValueError, random_choice_csc, 4, classes, + class_probabilites, 1) + + # Given proabilites don't sum to 1 + classes = [np.array([0, 1]), np.array([0, 1, 2])] + class_probabilites = [np.array([0.5, 0.6]), np.array([0.6, 0.1, 0.3])] + assert_raises(ValueError, random_choice_csc, 4, classes, + class_probabilites, 1) + + +if __name__ == '__main__': + import nose + nose.runmodule() diff --git a/sklearn/utils/tests/test_shortest_path.py b/sklearn/utils/tests/test_shortest_path.py index 7d876a000d393..71f2d711dd3f5 100644 --- a/sklearn/utils/tests/test_shortest_path.py +++ b/sklearn/utils/tests/test_shortest_path.py @@ -37,7 +37,7 @@ def generate_graph(N=20): dist_matrix += dist_matrix.T #make graph sparse - i = (rng.randint(N, size=N * N / 2), rng.randint(N, size=N * N / 2)) + i = (rng.randint(N, size=N * N // 2), rng.randint(N, size=N * N // 2)) dist_matrix[i] = 0 #set diagonal to zero @@ -79,7 +79,8 @@ def test_shortest_path(): for i in range(dist_matrix.shape[0]): # Non-reachable nodes have distance 0 in graph_py dist_dict = defaultdict(int) - dist_dict.update(single_source_shortest_path_length(dist_matrix, i)) + dist_dict.update(single_source_shortest_path_length(dist_matrix, + i)) for j in range(graph_py[i].shape[0]): assert_array_almost_equal(dist_dict[j], graph_py[i, j]) diff --git a/sklearn/utils/tests/test_sparsefuncs.py b/sklearn/utils/tests/test_sparsefuncs.py index 2893cdc19a3ee..cc07ed734c105 100644 --- a/sklearn/utils/tests/test_sparsefuncs.py +++ b/sklearn/utils/tests/test_sparsefuncs.py @@ -1,9 +1,18 @@ import numpy as np import scipy.sparse as sp -from numpy.testing import assert_array_almost_equal + +from scipy import linalg +from numpy.testing import assert_array_almost_equal, assert_array_equal from sklearn.datasets import make_classification -from sklearn.utils.sparsefuncs import mean_variance_axis0 +from sklearn.utils.sparsefuncs import (mean_variance_axis, + inplace_column_scale, + inplace_row_scale, + inplace_swap_row, inplace_swap_column, + min_max_axis, + count_nonzero, csc_median_axis_0) +from sklearn.utils.sparsefuncs_fast import assign_rows_csr +from sklearn.utils.testing import assert_raises def test_mean_variance_axis0(): @@ -17,12 +26,369 @@ def test_mean_variance_axis0(): X[1, 0] = 0 X_csr = sp.csr_matrix(X_lil) - X_means, X_vars = mean_variance_axis0(X_csr) + X_means, X_vars = mean_variance_axis(X_csr, axis=0) assert_array_almost_equal(X_means, np.mean(X, axis=0)) assert_array_almost_equal(X_vars, np.var(X, axis=0)) X_csc = sp.csc_matrix(X_lil) - X_means, X_vars = mean_variance_axis0(X_csc) + X_means, X_vars = mean_variance_axis(X_csc, axis=0) assert_array_almost_equal(X_means, np.mean(X, axis=0)) assert_array_almost_equal(X_vars, np.var(X, axis=0)) + assert_raises(TypeError, mean_variance_axis, X_lil, axis=0) + + X = X.astype(np.float32) + X_csr = X_csr.astype(np.float32) + X_csc = X_csr.astype(np.float32) + X_means, X_vars = mean_variance_axis(X_csr, axis=0) + assert_array_almost_equal(X_means, np.mean(X, axis=0)) + assert_array_almost_equal(X_vars, np.var(X, axis=0)) + X_means, X_vars = mean_variance_axis(X_csc, axis=0) + assert_array_almost_equal(X_means, np.mean(X, axis=0)) + assert_array_almost_equal(X_vars, np.var(X, axis=0)) + assert_raises(TypeError, mean_variance_axis, X_lil, axis=0) + + +def test_mean_variance_illegal_axis(): + X, _ = make_classification(5, 4, random_state=0) + # Sparsify the array a little bit + X[0, 0] = 0 + X[2, 1] = 0 + X[4, 3] = 0 + X_csr = sp.csr_matrix(X) + assert_raises(ValueError, mean_variance_axis, X_csr, axis=-3) + assert_raises(ValueError, mean_variance_axis, X_csr, axis=2) + assert_raises(ValueError, mean_variance_axis, X_csr, axis=-1) + + +def test_mean_variance_axis1(): + X, _ = make_classification(5, 4, random_state=0) + # Sparsify the array a little bit + X[0, 0] = 0 + X[2, 1] = 0 + X[4, 3] = 0 + X_lil = sp.lil_matrix(X) + X_lil[1, 0] = 0 + X[1, 0] = 0 + X_csr = sp.csr_matrix(X_lil) + + X_means, X_vars = mean_variance_axis(X_csr, axis=1) + assert_array_almost_equal(X_means, np.mean(X, axis=1)) + assert_array_almost_equal(X_vars, np.var(X, axis=1)) + + X_csc = sp.csc_matrix(X_lil) + X_means, X_vars = mean_variance_axis(X_csc, axis=1) + + assert_array_almost_equal(X_means, np.mean(X, axis=1)) + assert_array_almost_equal(X_vars, np.var(X, axis=1)) + assert_raises(TypeError, mean_variance_axis, X_lil, axis=1) + + X = X.astype(np.float32) + X_csr = X_csr.astype(np.float32) + X_csc = X_csr.astype(np.float32) + X_means, X_vars = mean_variance_axis(X_csr, axis=1) + assert_array_almost_equal(X_means, np.mean(X, axis=1)) + assert_array_almost_equal(X_vars, np.var(X, axis=1)) + X_means, X_vars = mean_variance_axis(X_csc, axis=1) + assert_array_almost_equal(X_means, np.mean(X, axis=1)) + assert_array_almost_equal(X_vars, np.var(X, axis=1)) + assert_raises(TypeError, mean_variance_axis, X_lil, axis=1) + + +def test_densify_rows(): + X = sp.csr_matrix([[0, 3, 0], + [2, 4, 0], + [0, 0, 0], + [9, 8, 7], + [4, 0, 5]], dtype=np.float64) + rows = np.array([0, 2, 3], dtype=np.intp) + out = np.ones((rows.shape[0], X.shape[1]), dtype=np.float64) + + assign_rows_csr(X, rows, + np.arange(out.shape[0], dtype=np.intp)[::-1], out) + assert_array_equal(out, X[rows].toarray()[::-1]) + + +def test_inplace_column_scale(): + rng = np.random.RandomState(0) + X = sp.rand(100, 200, 0.05) + Xr = X.tocsr() + Xc = X.tocsc() + XA = X.toarray() + scale = rng.rand(200) + XA *= scale + + inplace_column_scale(Xc, scale) + inplace_column_scale(Xr, scale) + assert_array_almost_equal(Xr.toarray(), Xc.toarray()) + assert_array_almost_equal(XA, Xc.toarray()) + assert_array_almost_equal(XA, Xr.toarray()) + assert_raises(TypeError, inplace_column_scale, X.tolil(), scale) + + X = X.astype(np.float32) + scale = scale.astype(np.float32) + Xr = X.tocsr() + Xc = X.tocsc() + XA = X.toarray() + XA *= scale + inplace_column_scale(Xc, scale) + inplace_column_scale(Xr, scale) + assert_array_almost_equal(Xr.toarray(), Xc.toarray()) + assert_array_almost_equal(XA, Xc.toarray()) + assert_array_almost_equal(XA, Xr.toarray()) + assert_raises(TypeError, inplace_column_scale, X.tolil(), scale) + + +def test_inplace_row_scale(): + rng = np.random.RandomState(0) + X = sp.rand(100, 200, 0.05) + Xr = X.tocsr() + Xc = X.tocsc() + XA = X.toarray() + scale = rng.rand(100) + XA *= scale.reshape(-1, 1) + + inplace_row_scale(Xc, scale) + inplace_row_scale(Xr, scale) + assert_array_almost_equal(Xr.toarray(), Xc.toarray()) + assert_array_almost_equal(XA, Xc.toarray()) + assert_array_almost_equal(XA, Xr.toarray()) + assert_raises(TypeError, inplace_column_scale, X.tolil(), scale) + + X = X.astype(np.float32) + scale = scale.astype(np.float32) + Xr = X.tocsr() + Xc = X.tocsc() + XA = X.toarray() + XA *= scale.reshape(-1, 1) + inplace_row_scale(Xc, scale) + inplace_row_scale(Xr, scale) + assert_array_almost_equal(Xr.toarray(), Xc.toarray()) + assert_array_almost_equal(XA, Xc.toarray()) + assert_array_almost_equal(XA, Xr.toarray()) + assert_raises(TypeError, inplace_column_scale, X.tolil(), scale) + + +def test_inplace_swap_row(): + X = np.array([[0, 3, 0], + [2, 4, 0], + [0, 0, 0], + [9, 8, 7], + [4, 0, 5]], dtype=np.float64) + X_csr = sp.csr_matrix(X) + X_csc = sp.csc_matrix(X) + + swap = linalg.get_blas_funcs(('swap',), (X,)) + swap = swap[0] + X[0], X[-1] = swap(X[0], X[-1]) + inplace_swap_row(X_csr, 0, -1) + inplace_swap_row(X_csc, 0, -1) + assert_array_equal(X_csr.toarray(), X_csc.toarray()) + assert_array_equal(X, X_csc.toarray()) + assert_array_equal(X, X_csr.toarray()) + + X[2], X[3] = swap(X[2], X[3]) + inplace_swap_row(X_csr, 2, 3) + inplace_swap_row(X_csc, 2, 3) + assert_array_equal(X_csr.toarray(), X_csc.toarray()) + assert_array_equal(X, X_csc.toarray()) + assert_array_equal(X, X_csr.toarray()) + assert_raises(TypeError, inplace_swap_row, X_csr.tolil()) + + X = np.array([[0, 3, 0], + [2, 4, 0], + [0, 0, 0], + [9, 8, 7], + [4, 0, 5]], dtype=np.float32) + X_csr = sp.csr_matrix(X) + X_csc = sp.csc_matrix(X) + swap = linalg.get_blas_funcs(('swap',), (X,)) + swap = swap[0] + X[0], X[-1] = swap(X[0], X[-1]) + inplace_swap_row(X_csr, 0, -1) + inplace_swap_row(X_csc, 0, -1) + assert_array_equal(X_csr.toarray(), X_csc.toarray()) + assert_array_equal(X, X_csc.toarray()) + assert_array_equal(X, X_csr.toarray()) + X[2], X[3] = swap(X[2], X[3]) + inplace_swap_row(X_csr, 2, 3) + inplace_swap_row(X_csc, 2, 3) + assert_array_equal(X_csr.toarray(), X_csc.toarray()) + assert_array_equal(X, X_csc.toarray()) + assert_array_equal(X, X_csr.toarray()) + assert_raises(TypeError, inplace_swap_row, X_csr.tolil()) + + +def test_inplace_swap_column(): + X = np.array([[0, 3, 0], + [2, 4, 0], + [0, 0, 0], + [9, 8, 7], + [4, 0, 5]], dtype=np.float64) + X_csr = sp.csr_matrix(X) + X_csc = sp.csc_matrix(X) + + swap = linalg.get_blas_funcs(('swap',), (X,)) + swap = swap[0] + X[:, 0], X[:, -1] = swap(X[:, 0], X[:, -1]) + inplace_swap_column(X_csr, 0, -1) + inplace_swap_column(X_csc, 0, -1) + assert_array_equal(X_csr.toarray(), X_csc.toarray()) + assert_array_equal(X, X_csc.toarray()) + assert_array_equal(X, X_csr.toarray()) + + X[:, 0], X[:, 1] = swap(X[:, 0], X[:, 1]) + inplace_swap_column(X_csr, 0, 1) + inplace_swap_column(X_csc, 0, 1) + assert_array_equal(X_csr.toarray(), X_csc.toarray()) + assert_array_equal(X, X_csc.toarray()) + assert_array_equal(X, X_csr.toarray()) + assert_raises(TypeError, inplace_swap_column, X_csr.tolil()) + + X = np.array([[0, 3, 0], + [2, 4, 0], + [0, 0, 0], + [9, 8, 7], + [4, 0, 5]], dtype=np.float32) + X_csr = sp.csr_matrix(X) + X_csc = sp.csc_matrix(X) + swap = linalg.get_blas_funcs(('swap',), (X,)) + swap = swap[0] + X[:, 0], X[:, -1] = swap(X[:, 0], X[:, -1]) + inplace_swap_column(X_csr, 0, -1) + inplace_swap_column(X_csc, 0, -1) + assert_array_equal(X_csr.toarray(), X_csc.toarray()) + assert_array_equal(X, X_csc.toarray()) + assert_array_equal(X, X_csr.toarray()) + X[:, 0], X[:, 1] = swap(X[:, 0], X[:, 1]) + inplace_swap_column(X_csr, 0, 1) + inplace_swap_column(X_csc, 0, 1) + assert_array_equal(X_csr.toarray(), X_csc.toarray()) + assert_array_equal(X, X_csc.toarray()) + assert_array_equal(X, X_csr.toarray()) + assert_raises(TypeError, inplace_swap_column, X_csr.tolil()) + + +def test_min_max_axis0(): + X = np.array([[0, 3, 0], + [2, -1, 0], + [0, 0, 0], + [9, 8, 7], + [4, 0, 5]], dtype=np.float64) + X_csr = sp.csr_matrix(X) + X_csc = sp.csc_matrix(X) + + mins_csr, maxs_csr = min_max_axis(X_csr, axis=0) + assert_array_equal(mins_csr, X.min(axis=0)) + assert_array_equal(maxs_csr, X.max(axis=0)) + + mins_csc, maxs_csc = min_max_axis(X_csc, axis=0) + assert_array_equal(mins_csc, X.min(axis=0)) + assert_array_equal(maxs_csc, X.max(axis=0)) + + X = X.astype(np.float32) + X_csr = sp.csr_matrix(X) + X_csc = sp.csc_matrix(X) + mins_csr, maxs_csr = min_max_axis(X_csr, axis=0) + assert_array_equal(mins_csr, X.min(axis=0)) + assert_array_equal(maxs_csr, X.max(axis=0)) + mins_csc, maxs_csc = min_max_axis(X_csc, axis=0) + assert_array_equal(mins_csc, X.min(axis=0)) + assert_array_equal(maxs_csc, X.max(axis=0)) + + +def test_min_max_axis1(): + X = np.array([[0, 3, 0], + [2, -1, 0], + [0, 0, 0], + [9, 8, 7], + [4, 0, 5]], dtype=np.float64) + X_csr = sp.csr_matrix(X) + X_csc = sp.csc_matrix(X) + + mins_csr, maxs_csr = min_max_axis(X_csr, axis=1) + assert_array_equal(mins_csr, X.min(axis=1)) + assert_array_equal(maxs_csr, X.max(axis=1)) + + mins_csc, maxs_csc = min_max_axis(X_csc, axis=1) + assert_array_equal(mins_csc, X.min(axis=1)) + assert_array_equal(maxs_csc, X.max(axis=1)) + + X = X.astype(np.float32) + X_csr = sp.csr_matrix(X) + X_csc = sp.csc_matrix(X) + mins_csr, maxs_csr = min_max_axis(X_csr, axis=1) + assert_array_equal(mins_csr, X.min(axis=1)) + assert_array_equal(maxs_csr, X.max(axis=1)) + mins_csc, maxs_csc = min_max_axis(X_csc, axis=1) + assert_array_equal(mins_csc, X.min(axis=1)) + assert_array_equal(maxs_csc, X.max(axis=1)) + + +def test_min_max_axis_errors(): + X = np.array([[0, 3, 0], + [2, -1, 0], + [0, 0, 0], + [9, 8, 7], + [4, 0, 5]], dtype=np.float64) + X_csr = sp.csr_matrix(X) + X_csc = sp.csc_matrix(X) + assert_raises(TypeError, min_max_axis, X_csr.tolil(), axis=0) + assert_raises(ValueError, min_max_axis, X_csr, axis=2) + assert_raises(ValueError, min_max_axis, X_csc, axis=-3) + + +def test_count_nonzero(): + X = np.array([[0, 3, 0], + [2, -1, 0], + [0, 0, 0], + [9, 8, 7], + [4, 0, 5]], dtype=np.float64) + X_csr = sp.csr_matrix(X) + X_csc = sp.csc_matrix(X) + X_nonzero = X != 0 + sample_weight = [.5, .2, .3, .1, .1] + X_nonzero_weighted = X_nonzero * np.array(sample_weight)[:, None] + + for axis in [0, 1, -1, -2, None]: + assert_array_almost_equal(count_nonzero(X_csr, axis=axis), + X_nonzero.sum(axis=axis)) + assert_array_almost_equal(count_nonzero(X_csr, axis=axis, + sample_weight=sample_weight), + X_nonzero_weighted.sum(axis=axis)) + + assert_raises(TypeError, count_nonzero, X_csc) + assert_raises(ValueError, count_nonzero, X_csr, axis=2) + + +def test_csc_row_median(): + """Test csc_row_median actually calculates the median.""" + + # Test that it gives the same output when X is dense. + rng = np.random.RandomState(0) + X = rng.rand(100, 50) + dense_median = np.median(X, axis=0) + csc = sp.csc_matrix(X) + sparse_median = csc_median_axis_0(csc) + assert_array_equal(sparse_median, dense_median) + + # Test that it gives the same output when X is sparse + X = rng.rand(51, 100) + X[X < 0.7] = 0.0 + ind = rng.randint(0, 50, 10) + X[ind] = -X[ind] + csc = sp.csc_matrix(X) + dense_median = np.median(X, axis=0) + sparse_median = csc_median_axis_0(csc) + assert_array_equal(sparse_median, dense_median) + + # Test for toy data. + X = [[0, -2], [-1, -1], [1, 0], [2, 1]] + csc = sp.csc_matrix(X) + assert_array_equal(csc_median_axis_0(csc), np.array([0.5, -0.5])) + X = [[0, -2], [-1, -5], [1, -3]] + csc = sp.csc_matrix(X) + assert_array_equal(csc_median_axis_0(csc), np.array([0., -3])) + + # Test that it raises an Error for non-csc matrices. + assert_raises(TypeError, csc_median_axis_0, sp.csr_matrix(X)) diff --git a/sklearn/utils/tests/test_stats.py b/sklearn/utils/tests/test_stats.py new file mode 100644 index 0000000000000..6376cfa888ebd --- /dev/null +++ b/sklearn/utils/tests/test_stats.py @@ -0,0 +1,25 @@ +import numpy as np +from numpy.testing import TestCase +from sklearn.utils.testing import assert_array_equal + +from sklearn.utils.stats import rankdata + + +_cases = ( + # values, method, expected + ([100], 'max', [1.0]), + ([100, 100, 100], 'max', [3.0, 3.0, 3.0]), + ([100, 300, 200], 'max', [1.0, 3.0, 2.0]), + ([100, 200, 300, 200], 'max', [1.0, 3.0, 4.0, 3.0]), + ([100, 200, 300, 200, 100], 'max', [2.0, 4.0, 5.0, 4.0, 2.0]), +) + + +def test_cases(): + + def check_case(values, method, expected): + r = rankdata(values, method=method) + assert_array_equal(r, expected) + + for values, method, expected in _cases: + yield check_case, values, method, expected diff --git a/sklearn/utils/tests/test_svd.py b/sklearn/utils/tests/test_svd.py deleted file mode 100644 index 6e5cf6d96303e..0000000000000 --- a/sklearn/utils/tests/test_svd.py +++ /dev/null @@ -1,151 +0,0 @@ -# Author: Olivier Grisel -# License: BSD - -import numpy as np -from scipy import sparse -from scipy import linalg - -from numpy.testing import assert_equal -from numpy.testing import assert_almost_equal - -from sklearn.utils.testing import assert_greater - -from sklearn.utils.extmath import randomized_svd -from sklearn.datasets.samples_generator import make_low_rank_matrix - - -def test_randomized_svd_low_rank(): - """Check that extmath.randomized_svd is consistent with linalg.svd""" - n_samples = 100 - n_features = 500 - rank = 5 - k = 10 - - # generate a matrix X of approximate effective rank `rank` and no noise - # component (very structured signal): - X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, - effective_rank=rank, tail_strength=0.0, random_state=0) - assert_equal(X.shape, (n_samples, n_features)) - - # compute the singular values of X using the slow exact method - U, s, V = linalg.svd(X, full_matrices=False) - - # compute the singular values of X using the fast approximate method - Ua, sa, Va = randomized_svd(X, k) - assert_equal(Ua.shape, (n_samples, k)) - assert_equal(sa.shape, (k,)) - assert_equal(Va.shape, (k, n_features)) - - # ensure that the singular values of both methods are equal up to the real - # rank of the matrix - assert_almost_equal(s[:k], sa) - - # check the singular vectors too (while not checking the sign) - assert_almost_equal(np.dot(U[:, :k], V[:k, :]), np.dot(Ua, Va)) - - # check the sparse matrix representation - X = sparse.csr_matrix(X) - - # compute the singular values of X using the fast approximate method - Ua, sa, Va = randomized_svd(X, k) - assert_almost_equal(s[:rank], sa[:rank]) - - -def test_randomized_svd_low_rank_with_noise(): - """Check that extmath.randomized_svd can handle noisy matrices""" - n_samples = 100 - n_features = 500 - rank = 5 - k = 10 - - # generate a matrix X wity structure approximate rank `rank` and an - # important noisy component - X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, - effective_rank=rank, tail_strength=0.5, random_state=0) - assert_equal(X.shape, (n_samples, n_features)) - - # compute the singular values of X using the slow exact method - _, s, _ = linalg.svd(X, full_matrices=False) - - # compute the singular values of X using the fast approximate method - # without the iterated power method - _, sa, _ = randomized_svd(X, k, n_iterations=0) - - # the approximation does not tolerate the noise: - assert_greater(np.abs(s[:k] - sa).max(), 0.05) - - # compute the singular values of X using the fast approximate method with - # iterated power method - _, sap, _ = randomized_svd(X, k, n_iterations=5) - - # the iterated power method is helping getting rid of the noise: - assert_almost_equal(s[:k], sap, decimal=3) - - -def test_randomized_svd_infinite_rank(): - """Check that extmath.randomized_svd can handle noisy matrices""" - n_samples = 100 - n_features = 500 - rank = 5 - k = 10 - - # let us try again without 'low_rank component': just regularly but slowly - # decreasing singular values: the rank of the data matrix is infinite - X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, - effective_rank=rank, tail_strength=1.0, random_state=0) - assert_equal(X.shape, (n_samples, n_features)) - - # compute the singular values of X using the slow exact method - _, s, _ = linalg.svd(X, full_matrices=False) - - # compute the singular values of X using the fast approximate method - # without the iterated power method - _, sa, _ = randomized_svd(X, k, n_iterations=0) - - # the approximation does not tolerate the noise: - assert_greater(np.abs(s[:k] - sa).max(), 0.1) - - # compute the singular values of X using the fast approximate method with - # iterated power method - _, sap, _ = randomized_svd(X, k, n_iterations=5) - - # the iterated power method is still managing to get most of the structure - # at the requested rank - assert_almost_equal(s[:k], sap, decimal=3) - - -def test_randomized_svd_transpose_consistency(): - """Check that transposing the design matrix has limit impact""" - n_samples = 100 - n_features = 500 - rank = 4 - k = 10 - - X = make_low_rank_matrix(n_samples=n_samples, n_features=n_features, - effective_rank=rank, tail_strength=0.5, random_state=0) - assert_equal(X.shape, (n_samples, n_features)) - - U1, s1, V1 = randomized_svd(X, k, n_iterations=3, transpose=False, - random_state=0) - U2, s2, V2 = randomized_svd(X, k, n_iterations=3, transpose=True, - random_state=0) - U3, s3, V3 = randomized_svd(X, k, n_iterations=3, transpose='auto', - random_state=0) - U4, s4, V4 = linalg.svd(X, full_matrices=False) - - assert_almost_equal(s1, s4[:k], decimal=3) - assert_almost_equal(s2, s4[:k], decimal=3) - assert_almost_equal(s3, s4[:k], decimal=3) - - assert_almost_equal(np.dot(U1, V1), np.dot(U4[:, :k], V4[:k, :]), - decimal=2) - assert_almost_equal(np.dot(U2, V2), np.dot(U4[:, :k], V4[:k, :]), - decimal=2) - - # in this case 'auto' is equivalent to transpose - assert_almost_equal(s2, s3) - - -if __name__ == '__main__': - import nose - nose.runmodule() diff --git a/sklearn/utils/tests/test_testing.py b/sklearn/utils/tests/test_testing.py index c08f53723602b..d9908bb5c1790 100644 --- a/sklearn/utils/tests/test_testing.py +++ b/sklearn/utils/tests/test_testing.py @@ -1,6 +1,22 @@ +import warnings +import unittest +import sys + from nose.tools import assert_raises -from sklearn.utils.testing import _assert_less, _assert_greater +from sklearn.utils.testing import ( + _assert_less, + _assert_greater, + assert_less_equal, + assert_greater_equal, + assert_warns, + assert_no_warnings, + assert_equal, + set_random_state, + assert_raise_message) + +from sklearn.tree import DecisionTreeClassifier +from sklearn.lda import LDA try: from nose.tools import assert_less @@ -29,3 +45,84 @@ def test_assert_greater(): except ImportError: pass + + +def test_assert_less_equal(): + assert_less_equal(0, 1) + assert_less_equal(1, 1) + assert_raises(AssertionError, assert_less_equal, 1, 0) + + +def test_assert_greater_equal(): + assert_greater_equal(1, 0) + assert_greater_equal(1, 1) + assert_raises(AssertionError, assert_greater_equal, 0, 1) + + +def test_set_random_state(): + lda = LDA() + tree = DecisionTreeClassifier() + # LDA doesn't have random state: smoke test + set_random_state(lda, 3) + set_random_state(tree, 3) + assert_equal(tree.random_state, 3) + + +def test_assert_raise_message(): + def _raise_ValueError(message): + raise ValueError(message) + + assert_raise_message(ValueError, "test", + _raise_ValueError, "test") + + assert_raises(AssertionError, + assert_raise_message, ValueError, "something else", + _raise_ValueError, "test") + + assert_raises(ValueError, + assert_raise_message, TypeError, "something else", + _raise_ValueError, "test") + + +# This class is inspired from numpy 1.7 with an alteration to check +# the reset warning filters after calls to assert_warns. +# This assert_warns behavior is specific to scikit-learn because +#`clean_warning_registry()` is called internally by assert_warns +# and clears all previous filters. +class TestWarns(unittest.TestCase): + def test_warn(self): + def f(): + warnings.warn("yo") + return 3 + + # Test that assert_warns is not impacted by externally set + # filters and is reset internally. + # This is because `clean_warning_registry()` is called internally by + # assert_warns and clears all previous filters. + warnings.simplefilter("ignore", UserWarning) + assert_equal(assert_warns(UserWarning, f), 3) + + # Test that the warning registry is empty after assert_warns + assert_equal(sys.modules['warnings'].filters, []) + + assert_raises(AssertionError, assert_no_warnings, f) + assert_equal(assert_no_warnings(lambda x: x, 1), 1) + + def test_warn_wrong_warning(self): + def f(): + warnings.warn("yo", DeprecationWarning) + + failed = False + filters = sys.modules['warnings'].filters[:] + try: + try: + # Should raise an AssertionError + assert_warns(UserWarning, f) + failed = True + except AssertionError: + pass + finally: + sys.modules['warnings'].filters = filters + + if failed: + raise AssertionError("wrong warning caught by assert_warn") diff --git a/sklearn/utils/tests/test_utils.py b/sklearn/utils/tests/test_utils.py index 441f5d04dc500..34e560d08561a 100644 --- a/sklearn/utils/tests/test_utils.py +++ b/sklearn/utils/tests/test_utils.py @@ -4,14 +4,19 @@ import scipy.sparse as sp from scipy.linalg import pinv2 -from nose.tools import assert_equal, assert_raises, assert_true -from numpy.testing import assert_almost_equal +from sklearn.utils.testing import (assert_equal, assert_raises, assert_true, + assert_almost_equal, assert_array_equal, + SkipTest) from sklearn.utils import check_random_state from sklearn.utils import deprecated from sklearn.utils import resample from sklearn.utils import safe_mask +from sklearn.utils import column_or_1d +from sklearn.utils import safe_indexing +from sklearn.utils import shuffle from sklearn.utils.extmath import pinvh +from sklearn.utils.mocking import MockDataFrame def test_make_rng(): @@ -117,3 +122,67 @@ def test_pinvh_simple_complex(): a = np.dot(a, a.conj().T) a_pinv = pinvh(a) assert_almost_equal(np.dot(a, a_pinv), np.eye(3)) + + +def test_column_or_1d(): + EXAMPLES = [ + ("binary", ["spam", "egg", "spam"]), + ("binary", [0, 1, 0, 1]), + ("continuous", np.arange(10) / 20.), + ("multiclass", [1, 2, 3]), + ("multiclass", [0, 1, 2, 2, 0]), + ("multiclass", [[1], [2], [3]]), + ("multilabel-indicator", [[0, 1, 0], [0, 0, 1]]), + ("multiclass-multioutput", [[1, 2, 3]]), + ("multiclass-multioutput", [[1, 1], [2, 2], [3, 1]]), + ("multiclass-multioutput", [[5, 1], [4, 2], [3, 1]]), + ("multiclass-multioutput", [[1, 2, 3]]), + ("continuous-multioutput", np.arange(30).reshape((-1, 3))), + ] + + for y_type, y in EXAMPLES: + if y_type in ["binary", 'multiclass', "continuous"]: + assert_array_equal(column_or_1d(y), np.ravel(y)) + else: + assert_raises(ValueError, column_or_1d, y) + + +def test_safe_indexing(): + X = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + inds = np.array([1, 2]) + X_inds = safe_indexing(X, inds) + X_arrays = safe_indexing(np.array(X), inds) + assert_array_equal(np.array(X_inds), X_arrays) + assert_array_equal(np.array(X_inds), np.array(X)[inds]) + + +def test_safe_indexing_pandas(): + try: + import pandas as pd + except ImportError: + raise SkipTest("Pandas not found") + X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + X_df = pd.DataFrame(X) + inds = np.array([1, 2]) + X_df_indexed = safe_indexing(X_df, inds) + X_indexed = safe_indexing(X_df, inds) + assert_array_equal(np.array(X_df_indexed), X_indexed) + + +def test_safe_indexing_mock_pandas(): + X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + X_df = MockDataFrame(X) + inds = np.array([1, 2]) + X_df_indexed = safe_indexing(X_df, inds) + X_indexed = safe_indexing(X_df, inds) + assert_array_equal(np.array(X_df_indexed), X_indexed) + + +def test_shuffle_on_ndim_equals_three(): + def to_tuple(A): # to make the inner arrays hashable + return tuple(tuple(tuple(C) for C in B) for B in A) + + A = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # A.shape = (2,2,2) + S = set(to_tuple(A)) + shuffle(A) # shouldn't raise a ValueError for dim = 3 + assert_equal(set(to_tuple(A)), S) diff --git a/sklearn/utils/tests/test_validation.py b/sklearn/utils/tests/test_validation.py index 4c6d9bee13e71..0a35f76047ab5 100644 --- a/sklearn/utils/tests/test_validation.py +++ b/sklearn/utils/tests/test_validation.py @@ -1,13 +1,32 @@ """Tests for input validation functions""" +import warnings + from tempfile import NamedTemporaryFile +from itertools import product + import numpy as np -from numpy.testing import assert_array_equal +from numpy.testing import assert_array_equal, assert_warns import scipy.sparse as sp -from nose.tools import assert_raises, assert_true, assert_false +from nose.tools import assert_raises, assert_true, assert_false, assert_equal -from sklearn.utils import (array2d, as_float_array, atleast2d_or_csr, - atleast2d_or_csc, check_arrays, safe_asarray) +from sklearn.utils.testing import assert_raises_regexp +from sklearn.utils import as_float_array, check_array, check_symmetric +from sklearn.utils import check_X_y +from sklearn.utils.estimator_checks import NotAnArray +from sklearn.random_projection import sparse_random_matrix +from sklearn.linear_model import ARDRegression +from sklearn.neighbors import KNeighborsClassifier +from sklearn.ensemble import RandomForestRegressor +from sklearn.svm import SVR +from sklearn.datasets import make_blobs +from sklearn.utils.validation import ( + NotFittedError, + has_fit_parameter, + check_is_fitted, + check_consistent_length) + +from sklearn.utils.testing import assert_raise_message def test_as_float_array(): @@ -31,14 +50,16 @@ def test_as_float_array(): X = np.asfortranarray(X) assert_true(np.isfortran(as_float_array(X, copy=True))) - -def test_check_arrays_exceptions(): - """Check that invalid arguments raise appropriate exceptions""" - assert_raises(ValueError, check_arrays, [0], [0, 1]) - assert_raises(TypeError, check_arrays, 0, [0, 1]) - assert_raises(TypeError, check_arrays, [0], 0) - assert_raises(TypeError, check_arrays, [0, 1], [0, 1], meaning_of_life=42) - assert_raises(ValueError, check_arrays, [0], [0], sparse_format='fake') + # Test the copy parameter with some matrices + matrices = [ + np.matrix(np.arange(5)), + sp.csc_matrix(np.arange(5)).toarray(), + sparse_random_matrix(10, 10, density=0.10).toarray() + ] + for M in matrices: + N = as_float_array(M, copy=True) + N[0, 0] = np.nan + assert_false(np.isnan(M).any()) def test_np_matrix(): @@ -49,23 +70,6 @@ def test_np_matrix(): assert_false(isinstance(as_float_array(np.matrix(X)), np.matrix)) assert_false(isinstance(as_float_array(sp.csc_matrix(X)), np.matrix)) - assert_false(isinstance(atleast2d_or_csr(X), np.matrix)) - assert_false(isinstance(atleast2d_or_csr(np.matrix(X)), np.matrix)) - assert_false(isinstance(atleast2d_or_csr(sp.csc_matrix(X)), np.matrix)) - - assert_false(isinstance(atleast2d_or_csc(X), np.matrix)) - assert_false(isinstance(atleast2d_or_csc(np.matrix(X)), np.matrix)) - assert_false(isinstance(atleast2d_or_csc(sp.csr_matrix(X)), np.matrix)) - - assert_false(isinstance(safe_asarray(X), np.matrix)) - assert_false(isinstance(safe_asarray(np.matrix(X)), np.matrix)) - assert_false(isinstance(safe_asarray(sp.lil_matrix(X)), np.matrix)) - - assert_true(atleast2d_or_csr(X, copy=False) is X) - assert_false(atleast2d_or_csr(X, copy=True) is X) - assert_true(atleast2d_or_csc(X, copy=False) is X) - assert_false(atleast2d_or_csc(X, copy=True) is X) - def test_memmap(): """Confirm that input validation code doesn't copy memory mapped arrays""" @@ -76,8 +80,287 @@ def test_memmap(): M = np.memmap(tmp, shape=100, dtype=np.float32) M[:] = 0 - for f in (array2d, np.asarray, asflt, safe_asarray): + for f in (check_array, np.asarray, asflt): X = f(M) X[:] = 1 assert_array_equal(X.ravel(), M) X[:] = 0 + + +def test_ordering(): + """Check that ordering is enforced correctly by validation utilities. + + We need to check each validation utility, because a 'copy' without + 'order=K' will kill the ordering. + """ + X = np.ones((10, 5)) + for A in X, X.T: + for copy in (True, False): + B = check_array(A, order='C', copy=copy) + assert_true(B.flags['C_CONTIGUOUS']) + B = check_array(A, order='F', copy=copy) + assert_true(B.flags['F_CONTIGUOUS']) + if copy: + assert_false(A is B) + + X = sp.csr_matrix(X) + X.data = X.data[::-1] + assert_false(X.data.flags['C_CONTIGUOUS']) + + for copy in (True, False): + Y = check_array(X, accept_sparse='csr', copy=copy, order='C') + assert_true(Y.data.flags['C_CONTIGUOUS']) + + +def test_check_array(): + # accept_sparse == None + # raise error on sparse inputs + X = [[1, 2], [3, 4]] + X_csr = sp.csr_matrix(X) + assert_raises(TypeError, check_array, X_csr) + # ensure_2d + X_array = check_array([0, 1, 2]) + assert_equal(X_array.ndim, 2) + X_array = check_array([0, 1, 2], ensure_2d=False) + assert_equal(X_array.ndim, 1) + # don't allow ndim > 3 + X_ndim = np.arange(8).reshape(2, 2, 2) + assert_raises(ValueError, check_array, X_ndim) + check_array(X_ndim, allow_nd=True) # doesn't raise + # force_all_finite + X_inf = np.arange(4).reshape(2, 2).astype(np.float) + X_inf[0, 0] = np.inf + assert_raises(ValueError, check_array, X_inf) + check_array(X_inf, force_all_finite=False) # no raise + # nan check + X_nan = np.arange(4).reshape(2, 2).astype(np.float) + X_nan[0, 0] = np.nan + assert_raises(ValueError, check_array, X_nan) + check_array(X_inf, force_all_finite=False) # no raise + + # dtype and order enforcement. + X_C = np.arange(4).reshape(2, 2).copy("C") + X_F = X_C.copy("F") + X_int = X_C.astype(np.int) + X_float = X_C.astype(np.float) + Xs = [X_C, X_F, X_int, X_float] + dtypes = [np.int32, np.int, np.float, np.float32, None, np.bool, object] + orders = ['C', 'F', None] + copys = [True, False] + + for X, dtype, order, copy in product(Xs, dtypes, orders, copys): + X_checked = check_array(X, dtype=dtype, order=order, copy=copy) + if dtype is not None: + assert_equal(X_checked.dtype, dtype) + else: + assert_equal(X_checked.dtype, X.dtype) + if order == 'C': + assert_true(X_checked.flags['C_CONTIGUOUS']) + assert_false(X_checked.flags['F_CONTIGUOUS']) + elif order == 'F': + assert_true(X_checked.flags['F_CONTIGUOUS']) + assert_false(X_checked.flags['C_CONTIGUOUS']) + if copy: + assert_false(X is X_checked) + else: + # doesn't copy if it was already good + if (X.dtype == X_checked.dtype and + X_checked.flags['C_CONTIGUOUS'] == X.flags['C_CONTIGUOUS'] + and X_checked.flags['F_CONTIGUOUS'] == X.flags['F_CONTIGUOUS']): + assert_true(X is X_checked) + + # allowed sparse != None + X_csc = sp.csc_matrix(X_C) + X_coo = X_csc.tocoo() + X_dok = X_csc.todok() + X_int = X_csc.astype(np.int) + X_float = X_csc.astype(np.float) + + Xs = [X_csc, X_coo, X_dok, X_int, X_float] + accept_sparses = [['csr', 'coo'], ['coo', 'dok']] + for X, dtype, accept_sparse, copy in product(Xs, dtypes, accept_sparses, + copys): + with warnings.catch_warnings(record=True) as w: + X_checked = check_array(X, dtype=dtype, + accept_sparse=accept_sparse, copy=copy) + if (dtype is object or sp.isspmatrix_dok(X)) and len(w): + message = str(w[0].message) + messages = ["object dtype is not supported by sparse matrices", + "Can't check dok sparse matrix for nan or inf."] + assert_true(message in messages) + else: + assert_equal(len(w), 0) + if dtype is not None: + assert_equal(X_checked.dtype, dtype) + else: + assert_equal(X_checked.dtype, X.dtype) + if X.format in accept_sparse: + # no change if allowed + assert_equal(X.format, X_checked.format) + else: + # got converted + assert_equal(X_checked.format, accept_sparse[0]) + if copy: + assert_false(X is X_checked) + else: + # doesn't copy if it was already good + if (X.dtype == X_checked.dtype and X.format == X_checked.format): + assert_true(X is X_checked) + + # other input formats + # convert lists to arrays + X_dense = check_array([[1, 2], [3, 4]]) + assert_true(isinstance(X_dense, np.ndarray)) + # raise on too deep lists + assert_raises(ValueError, check_array, X_ndim.tolist()) + check_array(X_ndim.tolist(), allow_nd=True) # doesn't raise + # convert weird stuff to arrays + X_no_array = NotAnArray(X_dense) + result = check_array(X_no_array) + assert_true(isinstance(result, np.ndarray)) + + +def test_check_array_min_samples_and_features_messages(): + # empty list is considered 2D by default: + msg = "0 feature(s) (shape=(1, 0)) while a minimum of 1 is required." + assert_raise_message(ValueError, msg, check_array, []) + + # If considered a 1D collection when ensure_2d=False, then the minimum + # number of samples will break: + msg = "0 sample(s) (shape=(0,)) while a minimum of 1 is required." + assert_raise_message(ValueError, msg, check_array, [], ensure_2d=False) + + # Invalid edge case when checking the default minimum sample of a scalar + msg = "Singleton array array(42) cannot be considered a valid collection." + assert_raise_message(TypeError, msg, check_array, 42, ensure_2d=False) + + # But this works if the input data is forced to look like a 2 array with + # one sample and one feature: + X_checked = check_array(42, ensure_2d=True) + assert_array_equal(np.array([[42]]), X_checked) + + # Simulate a model that would need at least 2 samples to be well defined + X = np.ones((1, 10)) + y = np.ones(1) + msg = "1 sample(s) (shape=(1, 10)) while a minimum of 2 is required." + assert_raise_message(ValueError, msg, check_X_y, X, y, + ensure_min_samples=2) + + # The same message is raised if the data has 2 dimensions even if this is + # not mandatory + assert_raise_message(ValueError, msg, check_X_y, X, y, + ensure_min_samples=2, ensure_2d=False) + + # Simulate a model that would require at least 3 features (e.g. SelectKBest + # with k=3) + X = np.ones((10, 2)) + y = np.ones(2) + msg = "2 feature(s) (shape=(10, 2)) while a minimum of 3 is required." + assert_raise_message(ValueError, msg, check_X_y, X, y, + ensure_min_features=3) + + # Only the feature check is enabled whenever the number of dimensions is 2 + # even if allow_nd is enabled: + assert_raise_message(ValueError, msg, check_X_y, X, y, + ensure_min_features=3, allow_nd=True) + + # Simulate a case where a pipeline stage as trimmed all the features of a + # 2D dataset. + X = np.empty(0).reshape(10, 0) + y = np.ones(10) + msg = "0 feature(s) (shape=(10, 0)) while a minimum of 1 is required." + assert_raise_message(ValueError, msg, check_X_y, X, y) + + # nd-data is not checked for any minimum number of features by default: + X = np.ones((10, 0, 28, 28)) + y = np.ones(10) + X_checked, y_checked = check_X_y(X, y, allow_nd=True) + assert_array_equal(X, X_checked) + assert_array_equal(y, y_checked) + + +def test_has_fit_parameter(): + assert_false(has_fit_parameter(KNeighborsClassifier, "sample_weight")) + assert_true(has_fit_parameter(RandomForestRegressor, "sample_weight")) + assert_true(has_fit_parameter(SVR, "sample_weight")) + assert_true(has_fit_parameter(SVR(), "sample_weight")) + + +def test_check_symmetric(): + arr_sym = np.array([[0, 1], [1, 2]]) + arr_bad = np.ones(2) + arr_asym = np.array([[0, 2], [0, 2]]) + + test_arrays = {'dense': arr_asym, + 'dok': sp.dok_matrix(arr_asym), + 'csr': sp.csr_matrix(arr_asym), + 'csc': sp.csc_matrix(arr_asym), + 'coo': sp.coo_matrix(arr_asym), + 'lil': sp.lil_matrix(arr_asym), + 'bsr': sp.bsr_matrix(arr_asym)} + + # check error for bad inputs + assert_raises(ValueError, check_symmetric, arr_bad) + + # check that asymmetric arrays are properly symmetrized + for arr_format, arr in test_arrays.items(): + # Check for warnings and errors + assert_warns(UserWarning, check_symmetric, arr) + assert_raises(ValueError, check_symmetric, arr, raise_exception=True) + + output = check_symmetric(arr, raise_warning=False) + if sp.issparse(output): + assert_equal(output.format, arr_format) + assert_array_equal(output.toarray(), arr_sym) + else: + assert_array_equal(output, arr_sym) + + +def test_check_is_fitted(): + # Check is ValueError raised when non estimator instance passed + assert_raises(ValueError, check_is_fitted, ARDRegression, "coef_") + assert_raises(TypeError, check_is_fitted, "SVR", "support_") + + ard = ARDRegression() + svr = SVR() + + try: + assert_raises(NotFittedError, check_is_fitted, ard, "coef_") + assert_raises(NotFittedError, check_is_fitted, svr, "support_") + except ValueError: + assert False, "check_is_fitted failed with ValueError" + + # NotFittedError is a subclass of both ValueError and AttributeError + try: + check_is_fitted(ard, "coef_", "Random message %(name)s, %(name)s") + except ValueError as e: + assert_equal(str(e), "Random message ARDRegression, ARDRegression") + + try: + check_is_fitted(svr, "support_", "Another message %(name)s, %(name)s") + except AttributeError as e: + assert_equal(str(e), "Another message SVR, SVR") + + ard.fit(*make_blobs()) + svr.fit(*make_blobs()) + + assert_equal(None, check_is_fitted(ard, "coef_")) + assert_equal(None, check_is_fitted(svr, "support_")) + + +def test_check_consistent_length(): + check_consistent_length([1], [2], [3], [4], [5]) + check_consistent_length([[1, 2], [[1, 2]]], [1, 2], ['a', 'b']) + check_consistent_length([1], (2,), np.array([3]), sp.csr_matrix((1, 2))) + assert_raises_regexp(ValueError, 'inconsistent numbers of samples', + check_consistent_length, [1, 2], [1]) + assert_raises_regexp(TypeError, 'got <\w+ \'int\'>', + check_consistent_length, [1, 2], 1) + assert_raises_regexp(TypeError, 'got <\w+ \'object\'>', + check_consistent_length, [1, 2], object()) + + assert_raises(TypeError, check_consistent_length, [1, 2], np.array(1)) + # Despite ensembles having __len__ they must raise TypeError + assert_raises_regexp(TypeError, 'estimator', check_consistent_length, + [1, 2], RandomForestRegressor()) + # XXX: We should have a test with a string, but what is correct behaviour? diff --git a/sklearn/utils/tests/test_weighted_mode.py b/sklearn/utils/tests/test_weighted_mode.py deleted file mode 100644 index 85ef08fae2f08..0000000000000 --- a/sklearn/utils/tests/test_weighted_mode.py +++ /dev/null @@ -1,42 +0,0 @@ -import numpy as np -from nose.tools import assert_true -from sklearn.utils.extmath import weighted_mode - -from scipy import stats - - -def test_uniform_weights(): - # with uniform weights, results should be identical to stats.mode - rng = np.random.RandomState(0) - x = rng.randint(10, size=(10, 5)) - weights = np.ones(x.shape) - - for axis in (None, 0, 1): - mode, score = stats.mode(x, axis) - mode2, score2 = weighted_mode(x, weights, axis) - - assert_true(np.all(mode == mode2)) - assert_true(np.all(score == score2)) - - -def test_random_weights(): - # set this up so that each row should have a weighted mode of 6, - # with a score that is easily reproduced - mode_result = 6 - - rng = np.random.RandomState(0) - x = rng.randint(mode_result, size=(100, 10)) - w = rng.random_sample(x.shape) - - x[:, :5] = mode_result - w[:, :5] += 1 - - mode, score = weighted_mode(x, w, axis=1) - - assert_true(np.all(mode == mode_result)) - assert_true(np.all(score.ravel() == w[:, :5].sum(1))) - - -if __name__ == '__main__': - import nose - nose.runmodule() diff --git a/sklearn/utils/validation.py b/sklearn/utils/validation.py index 9ee13206de3f3..8582572ce90e8 100644 --- a/sklearn/utils/validation.py +++ b/sklearn/utils/validation.py @@ -1,36 +1,65 @@ """Utilities for input validation""" -# Authors: Olivier Grisel and others (please update me) -# License: BSD 3 +# Authors: Olivier Grisel +# Gael Varoquaux +# Andreas Mueller +# Lars Buitinck +# Alexandre Gramfort +# Nicolas Tresegnie +# License: BSD 3 clause +import warnings +import numbers import numpy as np -from scipy import sparse -import warnings +import scipy.sparse as sp +from ..externals import six +from inspect import getargspec -def assert_all_finite(X): - """Throw a ValueError if X contains NaN or infinity. - Input MUST be an np.ndarray instance or a scipy.sparse matrix.""" +class DataConversionWarning(UserWarning): + """A warning on implicit data conversions happening in the code""" + pass + +warnings.simplefilter("always", DataConversionWarning) + + +class NonBLASDotWarning(UserWarning): + """A warning on implicit dispatch to numpy.dot""" + +class NotFittedError(ValueError, AttributeError): + """Exception class to raise if estimator is used before fitting + + This class inherits from both ValueError and AttributeError to help with + exception handling and backward compatibility. + """ + + +# Silenced by default to reduce verbosity. Turn on at runtime for +# performance profiling. +warnings.simplefilter('ignore', NonBLASDotWarning) + + +def _assert_all_finite(X): + """Like assert_all_finite, but only for ndarray.""" + X = np.asanyarray(X) # First try an O(n) time, O(1) space solution for the common case that - # there everything is finite; fall back to O(n) space np.isfinite to - # prevent false positives from overflow in sum method. - if X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum()) \ - and not np.isfinite(X.data if sparse.issparse(X) else X).all(): - raise ValueError("array contains NaN or infinity") + # everything is finite; fall back to O(n) space np.isfinite to prevent + # false positives from overflow in sum method. + if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum()) + and not np.isfinite(X).all()): + raise ValueError("Input contains NaN, infinity" + " or a value too large for %r." % X.dtype) -def safe_asarray(X, dtype=None, order=None): - """Convert X to an array or sparse matrix. +def assert_all_finite(X): + """Throw a ValueError if X contains NaN or infinity. - Prevents copying X when possible; sparse matrices are passed through.""" - if not sparse.issparse(X): - X = np.asarray(X, dtype, order) - assert_all_finite(X) - return X + Input MUST be an np.ndarray instance or a scipy.sparse matrix.""" + _assert_all_finite(X.data if sp.issparse(X) else X) -def as_float_array(X, copy=True): +def as_float_array(X, copy=True, force_all_finite=True): """Converts an array-like to an array of floats The new dtype will be np.float32 or np.float64, depending on the original @@ -45,15 +74,20 @@ def as_float_array(X, copy=True): If True, a copy of X will be created. If False, a copy may still be returned if X's dtype is not a floating point type. + force_all_finite : boolean (default=True) + Whether to raise an error on np.inf and np.nan in X. + Returns ------- XT : {array, sparse matrix} An array of type np.float """ if isinstance(X, np.matrix) or (not isinstance(X, np.ndarray) - and not sparse.issparse(X)): - return safe_asarray(X, dtype=np.float64) - elif sparse.issparse(X) and X.dtype in [np.float32, np.float64]: + and not sp.issparse(X)): + return check_array(X, ['csr', 'csc', 'coo'], dtype=np.float64, + copy=copy, force_all_finite=force_all_finite, + ensure_2d=False) + elif sp.issparse(X) and X.dtype in [np.float32, np.float64]: return X.copy() if copy else X elif X.dtype in [np.float32, np.float64]: # is numpy array return X.copy('F' if X.flags['F_CONTIGUOUS'] else 'C') if copy else X @@ -61,149 +95,404 @@ def as_float_array(X, copy=True): return X.astype(np.float32 if X.dtype == np.int32 else np.float64) -def array2d(X, dtype=None, order=None, copy=False): - """Returns at least 2-d array with data from X""" - if sparse.issparse(X): - raise TypeError('A sparse matrix was passed, but dense data ' - 'is required. Use X.todense() to convert to dense.') - X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order) - if X is X_2d and copy: - X_2d = X_2d.copy() - return X_2d +def _is_arraylike(x): + """Returns whether the input is array-like""" + return (hasattr(x, '__len__') or + hasattr(x, 'shape') or + hasattr(x, '__array__')) + + +def _num_samples(x): + """Return number of samples in array-like x.""" + if hasattr(x, 'fit'): + # Don't get num_samples from an ensembles length! + raise TypeError('Expected sequence or array-like, got ' + 'estimator %s' % x) + if not hasattr(x, '__len__') and not hasattr(x, 'shape'): + if hasattr(x, '__array__'): + x = np.asarray(x) + else: + raise TypeError("Expected sequence or array-like, got %s" % + type(x)) + if hasattr(x, 'shape'): + if len(x.shape) == 0: + raise TypeError("Singleton array %r cannot be considered" + " a valid collection." % x) + return x.shape[0] + else: + return len(x) + + +def _shape_repr(shape): + """Return a platform independent reprensentation of an array shape + + Under Python 2, the `long` type introduces an 'L' suffix when using the + default %r format for tuples of integers (typically used to store the shape + of an array). + + Under Windows 64 bit (and Python 2), the `long` type is used by default + in numpy shapes even when the integer dimensions are well below 32 bit. + The platform specific type causes string messages or doctests to change + from one platform to another which is not desirable. + + Under Python 3, there is no more `long` type so the `L` suffix is never + introduced in string representation. + + >>> _shape_repr((1, 2)) + '(1, 2)' + >>> one = 2 ** 64 / 2 ** 64 # force an upcast to `long` under Python 2 + >>> _shape_repr((one, 2 * one)) + '(1, 2)' + >>> _shape_repr((1,)) + '(1,)' + >>> _shape_repr(()) + '()' + """ + if len(shape) == 0: + return "()" + joined = ", ".join("%d" % e for e in shape) + if len(shape) == 1: + # special notation for singleton tuples + joined += ',' + return "(%s)" % joined + + +def check_consistent_length(*arrays): + """Check that all arrays have consistent first dimensions. + Checks whether all objects in arrays have the same shape or length. + + Parameters + ---------- + *arrays : list or tuple of input objects. + Objects that will be checked for consistent length. + """ + + uniques = np.unique([_num_samples(X) for X in arrays if X is not None]) + if len(uniques) > 1: + raise ValueError("Found arrays with inconsistent numbers of samples: " + "%s" % str(uniques)) -def atleast2d_or_csc(X, dtype=None, order=None, copy=False): - """Like numpy.atleast_2d, but converts sparse matrices to CSC format - Also, converts np.matrix to np.ndarray. +def indexable(*iterables): + """Make arrays indexable for cross-validation. + + Checks consistent length, passes through None, and ensures that everything + can be indexed by converting sparse matrices to csr and converting + non-interable objects to arrays. + + Parameters + ---------- + *iterables : lists, dataframes, arrays, sparse matrices + List of objects to ensure sliceability. """ - X_init = X - if sparse.issparse(X): - # Note: order is ignored because CSR matrices hold data in 1-d arrays - if dtype is None or X.dtype == dtype: - X = X.tocsc() + result = [] + for X in iterables: + if sp.issparse(X): + result.append(X.tocsr()) + elif hasattr(X, "__getitem__") or hasattr(X, "iloc"): + result.append(X) + elif X is None: + result.append(X) else: - X = sparse.csc_matrix(X, dtype=dtype) - else: - X = array2d(X, dtype=dtype, order=order) - assert_all_finite(X) - if X is X_init and copy: - X = X.copy() - return X + result.append(np.array(X)) + check_consistent_length(*result) + return result + + +def _ensure_sparse_format(spmatrix, accept_sparse, dtype, order, copy, + force_all_finite): + """Convert a sparse matrix to a given format. + + Checks the sparse format of spmatrix and converts if necessary. + + Parameters + ---------- + spmatrix : scipy sparse matrix + Input to validate and convert. + + accept_sparse : string, list of string or None (default=None) + String[s] representing allowed sparse matrix formats ('csc', + 'csr', 'coo', 'dok', 'bsr', 'lil', 'dia'). None means that sparse + matrix input will raise an error. If the input is sparse but not in + the allowed format, it will be converted to the first listed format. + + dtype : string, type or None (default=none) + Data type of result. If None, the dtype of the input is preserved. + order : 'F', 'C' or None (default=None) + Whether an array will be forced to be fortran or c-style. -def atleast2d_or_csr(X, dtype=None, order=None, copy=False): - """Like numpy.atleast_2d, but converts sparse matrices to CSR format + copy : boolean (default=False) + Whether a forced copy will be triggered. If copy=False, a copy might + be triggered by a conversion. - Also, converts np.matrix to np.ndarray. + force_all_finite : boolean (default=True) + Whether to raise an error on np.inf and np.nan in X. + + Returns + ------- + spmatrix_converted : scipy sparse matrix. + Matrix that is ensured to have an allowed type. """ - X_init = X - if sparse.issparse(X): - # Note: order is ignored because CSR matrices hold data in 1-d arrays - if dtype is None or X.dtype == dtype: - X = X.tocsr() + if accept_sparse is None: + raise TypeError('A sparse matrix was passed, but dense ' + 'data is required. Use X.toarray() to ' + 'convert to a dense numpy array.') + sparse_type = spmatrix.format + if dtype is None: + dtype = spmatrix.dtype + if sparse_type in accept_sparse: + # correct type + if dtype == spmatrix.dtype: + # correct dtype + if copy: + spmatrix = spmatrix.copy() else: - X = sparse.csr_matrix(X, dtype=dtype) + # convert dtype + spmatrix = spmatrix.astype(dtype) else: - X = array2d(X, dtype=dtype, order=order) - assert_all_finite(X) - if X is X_init and copy: - X = X.copy() - return X + # create new + spmatrix = spmatrix.asformat(accept_sparse[0]).astype(dtype) + if force_all_finite: + if not hasattr(spmatrix, "data"): + warnings.warn("Can't check %s sparse matrix for nan or inf." + % spmatrix.format) + else: + _assert_all_finite(spmatrix.data) + if hasattr(spmatrix, "data"): + spmatrix.data = np.array(spmatrix.data, copy=False, order=order) + return spmatrix -def _num_samples(x): - """Return number of samples in array-like x.""" - if not hasattr(x, '__len__') and not hasattr(x, 'shape'): - raise TypeError("Expected sequence or array-like, got %r" % x) - return x.shape[0] if hasattr(x, 'shape') else len(x) +def check_array(array, accept_sparse=None, dtype="numeric", order=None, copy=False, + force_all_finite=True, ensure_2d=True, allow_nd=False, + ensure_min_samples=1, ensure_min_features=1): + """Input validation on an array, list, sparse matrix or similar. - -def check_arrays(*arrays, **options): - """Checked that all arrays have consistent first dimensions + By default, the input is converted to an at least 2nd numpy array. + If the dtype of the array is object, attempt converting to float, + raising on failure. Parameters ---------- - *arrays : sequence of arrays or scipy.sparse matrices with same shape[0] - Python lists or tuples occurring in arrays are converted to 1D numpy - arrays. + array : object + Input object to check / convert. + + accept_sparse : string, list of string or None (default=None) + String[s] representing allowed sparse matrix formats, such as 'csc', + 'csr', etc. None means that sparse matrix input will raise an error. + If the input is sparse but not in the allowed format, it will be + converted to the first listed format. - sparse_format : 'csr', 'csc' or 'dense', None by default - If not None, any scipy.sparse matrix is converted to - Compressed Sparse Rows or Compressed Sparse Columns representations. - If 'dense', an error is raised when a sparse array is - passed. + dtype : string, type or None (default="numeric") + Data type of result. If None, the dtype of the input is preserved. + If "numeric", dtype is preserved unless array.dtype is object. - copy : boolean, False by default - If copy is True, ensure that returned arrays are copies of the original - (if not already converted to another format earlier in the process). + order : 'F', 'C' or None (default=None) + Whether an array will be forced to be fortran or c-style. - check_ccontiguous : boolean, False by default - Check that the arrays are C contiguous + copy : boolean (default=False) + Whether a forced copy will be triggered. If copy=False, a copy might + be triggered by a conversion. - dtype : a numpy dtype instance, None by default - Enforce a specific dtype. + force_all_finite : boolean (default=True) + Whether to raise an error on np.inf and np.nan in X. + + ensure_2d : boolean (default=True) + Whether to make X at least 2d. + + allow_nd : boolean (default=False) + Whether to allow X.ndim > 2. + + ensure_min_samples : int (default=1) + Make sure that the array has a minimum number of samples in its first + axis (rows for a 2D array). Setting to 0 disables this check. + + ensure_min_features : int (default=1) + Make sure that the 2D array has some minimum number of features + (columns). The default value of 1 rejects empty datasets. + This check is only enforced when the input data has effectively 2 + dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0 + disables this check. + + Returns + ------- + X_converted : object + The converted and validated X. """ - sparse_format = options.pop('sparse_format', None) - if sparse_format not in (None, 'csr', 'csc', 'dense'): - raise ValueError('Unexpected sparse format: %r' % sparse_format) - copy = options.pop('copy', False) - check_ccontiguous = options.pop('check_ccontiguous', False) - dtype = options.pop('dtype', None) - if options: - raise TypeError("Unexpected keyword arguments: %r" % options.keys()) - - if len(arrays) == 0: - return None - - n_samples = _num_samples(arrays[0]) - - checked_arrays = [] - for array in arrays: - array_orig = array - if array is None: - # special case: ignore optional y=None kwarg pattern - checked_arrays.append(array) - continue - - size = _num_samples(array) - - if size != n_samples: - raise ValueError("Found array with dim %d. Expected %d" % ( - size, n_samples)) - - if sparse.issparse(array): - if sparse_format == 'csr': - array = array.tocsr() - elif sparse_format == 'csc': - array = array.tocsc() - elif sparse_format == 'dense': - raise TypeError('A sparse matrix was passed, but dense data ' - 'is required. Use X.todense() to convert to dense.') - if check_ccontiguous: - array.data = np.ascontiguousarray(array.data, dtype=dtype) - else: - array.data = np.asarray(array.data, dtype=dtype) - else: - if check_ccontiguous: - array = np.ascontiguousarray(array, dtype=dtype) + if isinstance(accept_sparse, str): + accept_sparse = [accept_sparse] + + if sp.issparse(array): + if dtype == "numeric": + dtype = None + array = _ensure_sparse_format(array, accept_sparse, dtype, order, + copy, force_all_finite) + else: + if ensure_2d: + array = np.atleast_2d(array) + if dtype == "numeric": + if hasattr(array, "dtype") and array.dtype.kind == "O": + # if input is object, convert to float. + dtype = np.float64 else: - array = np.asarray(array, dtype=dtype) + dtype = None + array = np.array(array, dtype=dtype, order=order, copy=copy) + if not allow_nd and array.ndim >= 3: + raise ValueError("Found array with dim %d. Expected <= 2" % + array.ndim) + if force_all_finite: + _assert_all_finite(array) + + shape_repr = _shape_repr(array.shape) + if ensure_min_samples > 0: + n_samples = _num_samples(array) + if n_samples < ensure_min_samples: + raise ValueError("Found array with %d sample(s) (shape=%s) while a" + " minimum of %d is required." + % (n_samples, shape_repr, ensure_min_samples)) + + + if ensure_min_features > 0 and array.ndim == 2: + n_features = array.shape[1] + if n_features < ensure_min_features: + raise ValueError("Found array with %d feature(s) (shape=%s) while" + " a minimum of %d is required." + % (n_features, shape_repr, ensure_min_features)) + return array + + +def check_X_y(X, y, accept_sparse=None, dtype="numeric", order=None, copy=False, + force_all_finite=True, ensure_2d=True, allow_nd=False, + multi_output=False, ensure_min_samples=1, + ensure_min_features=1, y_numeric=False): + """Input validation for standard estimators. + + Checks X and y for consistent length, enforces X 2d and y 1d. + Standard input checks are only applied to y. For multi-label y, + set multi_output=True to allow 2d and sparse y. + If the dtype of X is object, attempt converting to float, + raising on failure. + + Parameters + ---------- + X : nd-array, list or sparse matrix + Input data. + + y : nd-array, list or sparse matrix + Labels. + + accept_sparse : string, list of string or None (default=None) + String[s] representing allowed sparse matrix formats, such as 'csc', + 'csr', etc. None means that sparse matrix input will raise an error. + If the input is sparse but not in the allowed format, it will be + converted to the first listed format. + + dtype : string, type or None (default="numeric") + Data type of result. If None, the dtype of the input is preserved. + If "numeric", dtype is preserved unless array.dtype is object. + + order : 'F', 'C' or None (default=None) + Whether an array will be forced to be fortran or c-style. - if copy and array is array_orig: - array = array.copy() - checked_arrays.append(array) + copy : boolean (default=False) + Whether a forced copy will be triggered. If copy=False, a copy might + be triggered by a conversion. - return checked_arrays + force_all_finite : boolean (default=True) + Whether to raise an error on np.inf and np.nan in X. + + ensure_2d : boolean (default=True) + Whether to make X at least 2d. + + allow_nd : boolean (default=False) + Whether to allow X.ndim > 2. + + multi_output : boolean (default=False) + Whether to allow 2-d y (array or sparse matrix). If false, y will be + validated as a vector. + + ensure_min_samples : int (default=1) + Make sure that X has a minimum number of samples in its first + axis (rows for a 2D array). + + ensure_min_features : int (default=1) + Make sure that the 2D array has some minimum number of features + (columns). The default value of 1 rejects empty datasets. + This check is only enforced when X has effectively 2 dimensions or + is originally 1D and ``ensure_2d`` is True. Setting to 0 disables + this check. + + y_numeric : boolean (default=False) + Whether to ensure that y has a numeric type. If dtype of y is object, + it is converted to float64. Should only be used for regression + algorithms. + + Returns + ------- + X_converted : object + The converted and validated X. + """ + X = check_array(X, accept_sparse, dtype, order, copy, force_all_finite, + ensure_2d, allow_nd, ensure_min_samples, + ensure_min_features) + if multi_output: + y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False, + dtype=None) + else: + y = column_or_1d(y, warn=True) + _assert_all_finite(y) + if y_numeric and y.dtype.kind == 'O': + y = y.astype(np.float64) + + check_consistent_length(X, y) + + return X, y + + +def column_or_1d(y, warn=False): + """ Ravel column or 1d numpy array, else raises an error + + Parameters + ---------- + y : array-like + + warn : boolean, default False + To control display of warnings. + + Returns + ------- + y : array + + """ + shape = np.shape(y) + if len(shape) == 1: + return np.ravel(y) + if len(shape) == 2 and shape[1] == 1: + if warn: + warnings.warn("A column-vector y was passed when a 1d array was" + " expected. Please change the shape of y to " + "(n_samples, ), for example using ravel().", + DataConversionWarning, stacklevel=2) + return np.ravel(y) + + raise ValueError("bad input shape {0}".format(shape)) def warn_if_not_float(X, estimator='This algorithm'): - """Warning utility function to check that data type is floating point""" - if not isinstance(estimator, basestring): + """Warning utility function to check that data type is floating point. + + Returns True if a warning was raised (i.e. the input is not float) and + False otherwise, for easier input validation. + """ + if not isinstance(estimator, six.string_types): estimator = estimator.__class__.__name__ if X.dtype.kind != 'f': warnings.warn("%s assumes floating point values as input, " "got %s" % (estimator, X.dtype)) + return True + return False def check_random_state(seed): @@ -216,9 +505,118 @@ def check_random_state(seed): """ if seed is None or seed is np.random: return np.random.mtrand._rand - if isinstance(seed, (int, np.integer)): + if isinstance(seed, (numbers.Integral, np.integer)): return np.random.RandomState(seed) if isinstance(seed, np.random.RandomState): return seed raise ValueError('%r cannot be used to seed a numpy.random.RandomState' ' instance' % seed) + + +def has_fit_parameter(estimator, parameter): + """Checks whether the estimator's fit method supports the given parameter. + + Examples + -------- + >>> from sklearn.svm import SVC + >>> has_fit_parameter(SVC(), "sample_weight") + True + + """ + return parameter in getargspec(estimator.fit)[0] + + +def check_symmetric(array, tol=1E-10, raise_warning=True, + raise_exception=False): + """Make sure that array is 2D, square and symmetric. + + If the array is not symmetric, then a symmetrized version is returned. + Optionally, a warning or exception is raised if the matrix is not + symmetric. + + Parameters + ---------- + array : nd-array or sparse matrix + Input object to check / convert. Must be two-dimensional and square, + otherwise a ValueError will be raised. + tol : float + Absolute tolerance for equivalence of arrays. Default = 1E-10. + raise_warning : boolean (default=True) + If True then raise a warning if conversion is required. + raise_exception : boolean (default=False) + If True then raise an exception if array is not symmetric. + + Returns + ------- + array_sym : ndarray or sparse matrix + Symmetrized version of the input array, i.e. the average of array + and array.transpose(). If sparse, then duplicate entries are first + summed and zeros are eliminated. + """ + if (array.ndim != 2) or (array.shape[0] != array.shape[1]): + raise ValueError("array must be 2-dimensional and square. " + "shape = {0}".format(array.shape)) + + if sp.issparse(array): + diff = array - array.T + # only csr, csc, and coo have `data` attribute + if diff.format not in ['csr', 'csc', 'coo']: + diff = diff.tocsr() + symmetric = np.all(abs(diff.data) < tol) + else: + symmetric = np.allclose(array, array.T, atol=tol) + + if not symmetric: + if raise_exception: + raise ValueError("Array must be symmetric") + if raise_warning: + warnings.warn("Array is not symmetric, and will be converted " + "to symmetric by average with its transpose.") + if sp.issparse(array): + conversion = 'to' + array.format + array = getattr(0.5 * (array + array.T), conversion)() + else: + array = 0.5 * (array + array.T) + + return array + + +def check_is_fitted(estimator, attributes, msg=None, all_or_any=all): + """Perform is_fitted validation for estimator. + + Checks if the estimator is fitted by verifying the presence of + "all_or_any" of the passed attributes and raises a NotFittedError with the + given message. + + Parameters + ---------- + estimator : estimator instance. + estimator instance for which the check is performed. + + attributes : attribute name(s) given as string or a list/tuple of strings + Eg. : ["coef_", "estimator_", ...], "coef_" + + msg : string + The default error message is, "This %(name)s instance is not fitted + yet. Call 'fit' with appropriate arguments before using this method." + + For custom messages if "%(name)s" is present in the message string, + it is substituted for the estimator name. + + Eg. : "Estimator, %(name)s, must be fitted before sparsifying". + + all_or_any : callable, {all, any}, default all + Specify whether all or any of the given attributes must exist. + """ + if msg is None: + msg = ("This %(name)s instance is not fitted yet. Call 'fit' with " + "appropriate arguments before using this method.") + + if not hasattr(estimator, 'fit'): + raise TypeError("%s is not an estimator instance." % (estimator)) + + if not isinstance(attributes, (list, tuple)): + attributes = [attributes] + + if not all_or_any([hasattr(estimator, attr) for attr in attributes]): + raise NotFittedError(msg % {'name': type(estimator).__name__}) diff --git a/sklearn/utils/weight_vector.c b/sklearn/utils/weight_vector.c index 9eba15d28dd78..c3bfd2e52855a 100644 --- a/sklearn/utils/weight_vector.c +++ b/sklearn/utils/weight_vector.c @@ -1,16 +1,29 @@ -/* Generated by Cython 0.15.1 on Sun Mar 18 20:56:50 2012 */ +/* Generated by Cython 0.20.1 on Fri Oct 3 15:41:23 2014 */ #define PY_SSIZE_T_CLEAN +#ifndef CYTHON_USE_PYLONG_INTERNALS +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 0 +#else +#include "pyconfig.h" +#ifdef PYLONG_BITS_IN_DIGIT +#define CYTHON_USE_PYLONG_INTERNALS 1 +#else +#define CYTHON_USE_PYLONG_INTERNALS 0 +#endif +#endif +#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02040000 + #error Cython requires Python 2.4+. #else - +#define CYTHON_ABI "0_20_1" #include /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif - #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall @@ -22,36 +35,50 @@ #define __fastcall #endif #endif - #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif - #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - -#if PY_VERSION_HEX < 0x02040000 - #define METH_COEXIST 0 - #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) - #define PyDict_Contains(d,o) PySequence_Contains(d,o) +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION +#define CYTHON_COMPILING_IN_PYPY 1 +#define CYTHON_COMPILING_IN_CPYTHON 0 +#else +#define CYTHON_COMPILING_IN_PYPY 0 +#define CYTHON_COMPILING_IN_CPYTHON 1 +#endif +#if CYTHON_COMPILING_IN_PYPY +#define Py_OptimizeFlag 0 #endif - #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" + #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) PyNumber_Int(o) - #define PyIndex_Check(o) PyNumber_Check(o) + #define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o) + #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ + (PyErr_Format(PyExc_TypeError, \ + "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ + (PyObject*)0)) + #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ + !PyComplex_Check(o)) + #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) + #define __PYX_BUILD_PY_SSIZE_T "i" +#else + #define __PYX_BUILD_PY_SSIZE_T "n" + #define CYTHON_FORMAT_SSIZE_T "z" + #define __Pyx_PyIndex_Check PyIndex_Check #endif - #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) @@ -59,7 +86,6 @@ #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) - typedef struct { void *buf; PyObject *obj; @@ -73,7 +99,6 @@ Py_ssize_t *suboffsets; void *internal; } Py_buffer; - #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 @@ -83,24 +108,74 @@ #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - + #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) + #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) + typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); + typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif - #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyType_Type +#endif +#if PY_VERSION_HEX < 0x02060000 + #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif - #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif - #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif - +#if PY_VERSION_HEX < 0x02060000 + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif +#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT) + #define Py_TPFLAGS_IS_ABSTRACT 0 +#endif +#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) +#else + #define CYTHON_PEP393_ENABLED 0 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -108,7 +183,6 @@ #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif - #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type @@ -127,7 +201,14 @@ #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif - +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ + PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) @@ -135,9 +216,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif - #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) - #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -153,13 +232,12 @@ #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long #endif - #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif - -#if PY_VERSION_HEX < 0x03020000 +#if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong @@ -167,16 +245,6 @@ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif - - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif - #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) @@ -195,11 +263,9 @@ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif - #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) @@ -209,7 +275,6 @@ #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif - #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) @@ -217,6 +282,49 @@ #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif +#ifndef CYTHON_INLINE + #if defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and + a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is + a quiet NaN. */ + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus @@ -232,11 +340,14 @@ #include #define __PYX_HAVE__sklearn__utils__weight_vector #define __PYX_HAVE_API__sklearn__utils__weight_vector +#include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "math.h" +#include "limits.h" +#include "cblas.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -245,21 +356,6 @@ #define CYTHON_WITHOUT_ASSERTIONS #endif - -/* inline attribute */ -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -/* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) @@ -267,31 +363,148 @@ # else # define CYTHON_UNUSED # endif -# elif defined(__ICC) || defined(__INTEL_COMPILER) +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif - -typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - - -/* Type Conversion Predeclarations */ - -#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) -#define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) - +typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) +#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) +#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((char*)s) +#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) +#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) +#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return u_end - u - 1; +} +#else +#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen +#endif +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); - static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); - +#if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (ascii_chars_u == NULL) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + } + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys = NULL; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (sys == NULL) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + if (default_encoding == NULL) goto bad; + default_encoding_c = PyBytes_AS_STRING(default_encoding); + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(sys); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(sys); + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif #ifdef __GNUC__ @@ -307,8 +520,9 @@ static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ - + static PyObject *__pyx_m; +static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; @@ -317,7 +531,6 @@ static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; - #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 @@ -327,7 +540,6 @@ static const char *__pyx_filename; #define CYTHON_CCOMPLEX 0 #endif #endif - #if CYTHON_CCOMPLEX #ifdef __cplusplus #include @@ -335,18 +547,54 @@ static const char *__pyx_filename; #include #endif #endif - #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif + static const char *__pyx_f[] = { "weight_vector.pyx", - "numpy.pxd", + "__init__.pxd", + "type.pxd", }; +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + -/* "numpy.pxd":719 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":723 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< @@ -355,7 +603,7 @@ static const char *__pyx_f[] = { */ typedef npy_int8 __pyx_t_5numpy_int8_t; -/* "numpy.pxd":720 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":724 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< @@ -364,7 +612,7 @@ typedef npy_int8 __pyx_t_5numpy_int8_t; */ typedef npy_int16 __pyx_t_5numpy_int16_t; -/* "numpy.pxd":721 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":725 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< @@ -373,7 +621,7 @@ typedef npy_int16 __pyx_t_5numpy_int16_t; */ typedef npy_int32 __pyx_t_5numpy_int32_t; -/* "numpy.pxd":722 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":726 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< @@ -382,7 +630,7 @@ typedef npy_int32 __pyx_t_5numpy_int32_t; */ typedef npy_int64 __pyx_t_5numpy_int64_t; -/* "numpy.pxd":726 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":730 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< @@ -391,7 +639,7 @@ typedef npy_int64 __pyx_t_5numpy_int64_t; */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; -/* "numpy.pxd":727 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":731 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< @@ -400,7 +648,7 @@ typedef npy_uint8 __pyx_t_5numpy_uint8_t; */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; -/* "numpy.pxd":728 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":732 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< @@ -409,7 +657,7 @@ typedef npy_uint16 __pyx_t_5numpy_uint16_t; */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; -/* "numpy.pxd":729 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":733 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< @@ -418,7 +666,7 @@ typedef npy_uint32 __pyx_t_5numpy_uint32_t; */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; -/* "numpy.pxd":733 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":737 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< @@ -427,7 +675,7 @@ typedef npy_uint64 __pyx_t_5numpy_uint64_t; */ typedef npy_float32 __pyx_t_5numpy_float32_t; -/* "numpy.pxd":734 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":738 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< @@ -436,7 +684,7 @@ typedef npy_float32 __pyx_t_5numpy_float32_t; */ typedef npy_float64 __pyx_t_5numpy_float64_t; -/* "numpy.pxd":743 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":747 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< @@ -445,7 +693,7 @@ typedef npy_float64 __pyx_t_5numpy_float64_t; */ typedef npy_long __pyx_t_5numpy_int_t; -/* "numpy.pxd":744 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":748 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< @@ -454,7 +702,7 @@ typedef npy_long __pyx_t_5numpy_int_t; */ typedef npy_longlong __pyx_t_5numpy_long_t; -/* "numpy.pxd":745 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":749 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< @@ -463,7 +711,7 @@ typedef npy_longlong __pyx_t_5numpy_long_t; */ typedef npy_longlong __pyx_t_5numpy_longlong_t; -/* "numpy.pxd":747 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< @@ -472,7 +720,7 @@ typedef npy_longlong __pyx_t_5numpy_longlong_t; */ typedef npy_ulong __pyx_t_5numpy_uint_t; -/* "numpy.pxd":748 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":752 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< @@ -481,7 +729,7 @@ typedef npy_ulong __pyx_t_5numpy_uint_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; -/* "numpy.pxd":749 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< @@ -490,7 +738,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; -/* "numpy.pxd":751 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< @@ -499,7 +747,7 @@ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; */ typedef npy_intp __pyx_t_5numpy_intp_t; -/* "numpy.pxd":752 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":756 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< @@ -508,7 +756,7 @@ typedef npy_intp __pyx_t_5numpy_intp_t; */ typedef npy_uintp __pyx_t_5numpy_uintp_t; -/* "numpy.pxd":754 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< @@ -517,7 +765,7 @@ typedef npy_uintp __pyx_t_5numpy_uintp_t; */ typedef npy_double __pyx_t_5numpy_float_t; -/* "numpy.pxd":755 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< @@ -526,7 +774,7 @@ typedef npy_double __pyx_t_5numpy_float_t; */ typedef npy_double __pyx_t_5numpy_double_t; -/* "numpy.pxd":756 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< @@ -534,25 +782,6 @@ typedef npy_double __pyx_t_5numpy_double_t; * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; - -/* "sklearn/utils/weight_vector.pxd":10 - * - * - * ctypedef np.float64_t DOUBLE # <<<<<<<<<<<<<< - * ctypedef np.int32_t INTEGER - * - */ -typedef __pyx_t_5numpy_float64_t __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE; - -/* "sklearn/utils/weight_vector.pxd":11 - * - * ctypedef np.float64_t DOUBLE - * ctypedef np.int32_t INTEGER # <<<<<<<<<<<<<< - * - * - */ -typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_5utils_13weight_vector_INTEGER; - #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; @@ -573,10 +802,11 @@ typedef __pyx_t_5numpy_int32_t __pyx_t_7sklearn_5utils_13weight_vector_INTEGER; typedef struct { double real, imag; } __pyx_t_double_complex; #endif + /*--- Type declarations ---*/ struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector; -/* "numpy.pxd":758 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< @@ -585,7 +815,7 @@ struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector; */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; -/* "numpy.pxd":759 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":763 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< @@ -594,7 +824,7 @@ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; -/* "numpy.pxd":760 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< @@ -603,7 +833,7 @@ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; -/* "numpy.pxd":762 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< @@ -612,26 +842,30 @@ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; */ typedef npy_cdouble __pyx_t_5numpy_complex_t; -/* "sklearn/utils/weight_vector.pxd":14 +/* "sklearn/utils/weight_vector.pxd":10 * * * cdef class WeightVector(object): # <<<<<<<<<<<<<< * cdef np.ndarray w - * cdef DOUBLE *w_data_ptr + * cdef np.ndarray aw */ struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector { PyObject_HEAD struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__pyx_vtab; PyArrayObject *w; - __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *w_data_ptr; + PyArrayObject *aw; + double *w_data_ptr; + double *aw_data_ptr; double wscale; - Py_ssize_t n_features; + double average_a; + double average_b; + int n_features; double sq_norm; }; -/* "sklearn/utils/weight_vector.pyx":18 +/* "sklearn/utils/weight_vector.pyx":27 * * * cdef class WeightVector(object): # <<<<<<<<<<<<<< @@ -640,19 +874,17 @@ struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector { */ struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector { - void (*add)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *, __pyx_t_7sklearn_5utils_13weight_vector_INTEGER *, int, double); - double (*dot)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *, __pyx_t_7sklearn_5utils_13weight_vector_INTEGER *, int); + void (*add)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double *, int *, int, double); + void (*add_average)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double *, int *, int, double, double); + double (*dot)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double *, int *, int); void (*scale)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double); void (*reset_wscale)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *); double (*norm)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *); }; static struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__pyx_vtabptr_7sklearn_5utils_13weight_vector_WeightVector; - - #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif - #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); @@ -665,8 +897,21 @@ static struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__p static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; - #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) - #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -677,7 +922,7 @@ static struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__p #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name) + #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) @@ -688,71 +933,103 @@ static struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *__p #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ - -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, PyObject* kw_name); /*proto*/ - -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact); /*proto*/ - -/* Run-time type information about structs used with buffers */ -struct __Pyx_StructField_; - -typedef struct { - const char* name; /* for error messages only */ - struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ -} __Pyx_TypeInfo; - -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, + const char *name, int exact); /*proto*/ -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); +static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, + __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ - static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + #if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); -static void __Pyx_ReleaseBuffer(Py_buffer *view); + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); #else -#define __Pyx_GetBuffer PyObject_GetBuffer -#define __Pyx_ReleaseBuffer PyBuffer_Release + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release #endif -Py_ssize_t __Pyx_zeros[] = {0}; -Py_ssize_t __Pyx_minusones[] = {-1}; -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ +static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; +static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); + +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); #if CYTHON_CCOMPLEX #ifdef __cplusplus @@ -766,8 +1043,7 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif - -#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX +#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else @@ -853,65 +1129,62 @@ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(do #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); +static int __Pyx_check_binary_version(void); -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); +typedef struct { + int code_line; + PyCodeObject* code_object; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); +/* Module declarations from 'cpython.buffer' */ -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); +/* Module declarations from 'cpython.ref' */ -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); +/* Module declarations from 'libc.string' */ -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); +/* Module declarations from 'libc.stdio' */ -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); +/* Module declarations from 'cpython.object' */ -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename); /*proto*/ +/* Module declarations from '__builtin__' */ -static int __Pyx_check_binary_version(void); +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; -static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ +/* Module declarations from 'libc.stdlib' */ -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ - -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename); /*proto*/ - -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ - -/* Module declarations from 'cpython.buffer' */ - -/* Module declarations from 'cpython.ref' */ - -/* Module declarations from 'libc.stdio' */ - -/* Module declarations from 'cpython.object' */ - -/* Module declarations from 'libc.stdlib' */ - -/* Module declarations from 'numpy' */ +/* Module declarations from 'numpy' */ /* Module declarations from 'numpy' */ static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; @@ -919,263 +1192,422 @@ static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ - -/* Module declarations from 'cython.cython.view' */ /* Module declarations from 'cython' */ +/* Module declarations from 'libc.limits' */ + +/* Module declarations from 'libc.math' */ + /* Module declarations from 'sklearn.utils.weight_vector' */ static PyTypeObject *__pyx_ptype_7sklearn_5utils_13weight_vector_WeightVector = 0; -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_13weight_vector_DOUBLE = { "DOUBLE", NULL, sizeof(__pyx_t_7sklearn_5utils_13weight_vector_DOUBLE), 'R' }; +static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "sklearn.utils.weight_vector" int __pyx_module_is_main_sklearn__utils__weight_vector = 0; /* Implementation of 'sklearn.utils.weight_vector' */ -static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_RuntimeError; -static char __pyx_k_1[] = "ndarray is not C contiguous"; -static char __pyx_k_3[] = "ndarray is not Fortran contiguous"; -static char __pyx_k_5[] = "Non-native byte order not supported"; -static char __pyx_k_7[] = "unknown dtype code in numpy.pxd (%d)"; -static char __pyx_k_8[] = "Format string allocated too short, see comment in numpy.pxd"; -static char __pyx_k_11[] = "Format string allocated too short."; -static char __pyx_k__B[] = "B"; -static char __pyx_k__H[] = "H"; -static char __pyx_k__I[] = "I"; -static char __pyx_k__L[] = "L"; -static char __pyx_k__O[] = "O"; -static char __pyx_k__Q[] = "Q"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__d[] = "d"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__g[] = "g"; -static char __pyx_k__h[] = "h"; -static char __pyx_k__i[] = "i"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__q[] = "q"; -static char __pyx_k__w[] = "w"; -static char __pyx_k__Zd[] = "Zd"; -static char __pyx_k__Zf[] = "Zf"; -static char __pyx_k__Zg[] = "Zg"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__dot[] = "dot"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__range[] = "range"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k__RuntimeError[] = "RuntimeError"; -static PyObject *__pyx_kp_u_1; -static PyObject *__pyx_kp_u_11; -static PyObject *__pyx_kp_u_3; -static PyObject *__pyx_kp_u_5; -static PyObject *__pyx_kp_u_7; -static PyObject *__pyx_kp_u_8; -static PyObject *__pyx_n_s__RuntimeError; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s__dot; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__range; -static PyObject *__pyx_n_s__w; -static PyObject *__pyx_int_15; -static PyObject *__pyx_k_tuple_2; -static PyObject *__pyx_k_tuple_4; -static PyObject *__pyx_k_tuple_6; -static PyObject *__pyx_k_tuple_9; -static PyObject *__pyx_k_tuple_10; -static PyObject *__pyx_k_tuple_12; - -/* "sklearn/utils/weight_vector.pyx":40 +static int __pyx_pf_7sklearn_5utils_13weight_vector_12WeightVector___cinit__(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_self, PyArrayObject *__pyx_v_w, PyArrayObject *__pyx_v_aw); /* proto */ +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static PyObject *__pyx_tp_new_7sklearn_5utils_13weight_vector_WeightVector(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static char __pyx_k_B[] = "B"; +static char __pyx_k_H[] = "H"; +static char __pyx_k_I[] = "I"; +static char __pyx_k_L[] = "L"; +static char __pyx_k_O[] = "O"; +static char __pyx_k_Q[] = "Q"; +static char __pyx_k_b[] = "b"; +static char __pyx_k_d[] = "d"; +static char __pyx_k_f[] = "f"; +static char __pyx_k_g[] = "g"; +static char __pyx_k_h[] = "h"; +static char __pyx_k_i[] = "i"; +static char __pyx_k_l[] = "l"; +static char __pyx_k_q[] = "q"; +static char __pyx_k_w[] = "w"; +static char __pyx_k_Zd[] = "Zd"; +static char __pyx_k_Zf[] = "Zf"; +static char __pyx_k_Zg[] = "Zg"; +static char __pyx_k_aw[] = "aw"; +static char __pyx_k_np[] = "np"; +static char __pyx_k_main[] = "__main__"; +static char __pyx_k_test[] = "__test__"; +static char __pyx_k_numpy[] = "numpy"; +static char __pyx_k_range[] = "range"; +static char __pyx_k_import[] = "__import__"; +static char __pyx_k_ValueError[] = "ValueError"; +static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static char __pyx_k_RuntimeError[] = "RuntimeError"; +static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static char __pyx_k_pyx_releasebuffer[] = "__pyx_releasebuffer"; +static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; +static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; +static char __pyx_k_More_than_d_features_not_support[] = "More than %d features not supported; got %d."; +static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; +static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; +static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; +static PyObject *__pyx_kp_s_More_than_d_features_not_support; +static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; +static PyObject *__pyx_n_s_RuntimeError; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_aw; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; +static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; +static PyObject *__pyx_n_s_np; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_releasebuffer; +static PyObject *__pyx_n_s_pyx_vtable; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; +static PyObject *__pyx_n_s_w; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; + +/* "sklearn/utils/weight_vector.pyx":51 * """ * - * def __cinit__(self, np.ndarray[DOUBLE, ndim=1, mode='c'] w): # <<<<<<<<<<<<<< - * self.w = w - * self.w_data_ptr = w.data + * def __cinit__(self, # <<<<<<<<<<<<<< + * np.ndarray[double, ndim=1, mode='c'] w, + * np.ndarray[double, ndim=1, mode='c'] aw): */ -static int __pyx_pf_7sklearn_5utils_13weight_vector_12WeightVector___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pf_7sklearn_5utils_13weight_vector_12WeightVector___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { +/* Python wrapper */ +static int __pyx_pw_7sklearn_5utils_13weight_vector_12WeightVector_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_7sklearn_5utils_13weight_vector_12WeightVector_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_w = 0; - Py_buffer __pyx_bstruct_w; - Py_ssize_t __pyx_bstride_0_w = 0; - Py_ssize_t __pyx_bshape_0_w = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - double __pyx_t_4; + PyArrayObject *__pyx_v_aw = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__w,0}; - __Pyx_RefNannySetupContext("__cinit__"); + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { - PyObject* values[1] = {0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_w,&__pyx_n_s_aw,0}; + PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; - switch (PyTuple_GET_SIZE(__pyx_args)) { + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); - switch (PyTuple_GET_SIZE(__pyx_args)) { + switch (pos_args) { case 0: - values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__w); - if (likely(values[0])) kw_args--; + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_w)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_aw)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_w = ((PyArrayObject *)values[0]); + __pyx_v_aw = ((PyArrayObject *)values[1]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("sklearn.utils.weight_vector.WeightVector.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; - __pyx_bstruct_w.buf = NULL; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_w), __pyx_ptype_5numpy_ndarray, 1, "w", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_w), __pyx_ptype_5numpy_ndarray, 1, "w", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_aw), __pyx_ptype_5numpy_ndarray, 1, "aw", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = __pyx_pf_7sklearn_5utils_13weight_vector_12WeightVector___cinit__(((struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_self), __pyx_v_w, __pyx_v_aw); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7sklearn_5utils_13weight_vector_12WeightVector___cinit__(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_self, PyArrayObject *__pyx_v_w, PyArrayObject *__pyx_v_aw) { + double *__pyx_v_wdata; + __Pyx_LocalBuf_ND __pyx_pybuffernd_aw; + __Pyx_Buffer __pyx_pybuffer_aw; + __Pyx_LocalBuf_ND __pyx_pybuffernd_w; + __Pyx_Buffer __pyx_pybuffer_w; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __pyx_pybuffer_w.pybuffer.buf = NULL; + __pyx_pybuffer_w.refcount = 0; + __pyx_pybuffernd_w.data = NULL; + __pyx_pybuffernd_w.rcbuffer = &__pyx_pybuffer_w; + __pyx_pybuffer_aw.pybuffer.buf = NULL; + __pyx_pybuffer_aw.refcount = 0; + __pyx_pybuffernd_aw.data = NULL; + __pyx_pybuffernd_aw.rcbuffer = &__pyx_pybuffer_aw; + { + __Pyx_BufFmt_StackElem __pyx_stack[1]; + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_w.rcbuffer->pybuffer, (PyObject*)__pyx_v_w, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + __pyx_pybuffernd_w.diminfo[0].strides = __pyx_pybuffernd_w.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_w.diminfo[0].shape = __pyx_pybuffernd_w.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_w, (PyObject*)__pyx_v_w, &__Pyx_TypeInfo_nn___pyx_t_7sklearn_5utils_13weight_vector_DOUBLE, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_aw.rcbuffer->pybuffer, (PyObject*)__pyx_v_aw, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_bstride_0_w = __pyx_bstruct_w.strides[0]; - __pyx_bshape_0_w = __pyx_bstruct_w.shape[0]; + __pyx_pybuffernd_aw.diminfo[0].strides = __pyx_pybuffernd_aw.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_aw.diminfo[0].shape = __pyx_pybuffernd_aw.rcbuffer->pybuffer.shape[0]; + + /* "sklearn/utils/weight_vector.pyx":54 + * np.ndarray[double, ndim=1, mode='c'] w, + * np.ndarray[double, ndim=1, mode='c'] aw): + * cdef double *wdata = w.data # <<<<<<<<<<<<<< + * + * if w.shape[0] > INT_MAX: + */ + __pyx_v_wdata = ((double *)__pyx_v_w->data); + + /* "sklearn/utils/weight_vector.pyx":56 + * cdef double *wdata = w.data + * + * if w.shape[0] > INT_MAX: # <<<<<<<<<<<<<< + * raise ValueError("More than %d features not supported; got %d." + * % (INT_MAX, w.shape[0])) + */ + __pyx_t_1 = (((__pyx_v_w->dimensions[0]) > INT_MAX) != 0); + if (__pyx_t_1) { + + /* "sklearn/utils/weight_vector.pyx":58 + * if w.shape[0] > INT_MAX: + * raise ValueError("More than %d features not supported; got %d." + * % (INT_MAX, w.shape[0])) # <<<<<<<<<<<<<< + * self.w = w + * self.w_data_ptr = wdata + */ + __pyx_t_2 = __Pyx_PyInt_From_int(INT_MAX); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_w->dimensions[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_More_than_d_features_not_support, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 58; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - /* "sklearn/utils/weight_vector.pyx":41 + /* "sklearn/utils/weight_vector.pyx":57 * - * def __cinit__(self, np.ndarray[DOUBLE, ndim=1, mode='c'] w): + * if w.shape[0] > INT_MAX: + * raise ValueError("More than %d features not supported; got %d." # <<<<<<<<<<<<<< + * % (INT_MAX, w.shape[0])) + * self.w = w + */ + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "sklearn/utils/weight_vector.pyx":59 + * raise ValueError("More than %d features not supported; got %d." + * % (INT_MAX, w.shape[0])) * self.w = w # <<<<<<<<<<<<<< - * self.w_data_ptr = w.data + * self.w_data_ptr = wdata * self.wscale = 1.0 */ __Pyx_INCREF(((PyObject *)__pyx_v_w)); __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __Pyx_GOTREF(((struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_self)->w); - __Pyx_DECREF(((PyObject *)((struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_self)->w)); - ((struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_self)->w = ((PyArrayObject *)__pyx_v_w); + __Pyx_GOTREF(__pyx_v_self->w); + __Pyx_DECREF(((PyObject *)__pyx_v_self->w)); + __pyx_v_self->w = ((PyArrayObject *)__pyx_v_w); - /* "sklearn/utils/weight_vector.pyx":42 - * def __cinit__(self, np.ndarray[DOUBLE, ndim=1, mode='c'] w): + /* "sklearn/utils/weight_vector.pyx":60 + * % (INT_MAX, w.shape[0])) * self.w = w - * self.w_data_ptr = w.data # <<<<<<<<<<<<<< + * self.w_data_ptr = wdata # <<<<<<<<<<<<<< * self.wscale = 1.0 * self.n_features = w.shape[0] */ - ((struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_self)->w_data_ptr = ((__pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *)__pyx_v_w->data); + __pyx_v_self->w_data_ptr = __pyx_v_wdata; - /* "sklearn/utils/weight_vector.pyx":43 + /* "sklearn/utils/weight_vector.pyx":61 * self.w = w - * self.w_data_ptr = w.data + * self.w_data_ptr = wdata * self.wscale = 1.0 # <<<<<<<<<<<<<< * self.n_features = w.shape[0] - * self.sq_norm = np.dot(w, w) + * self.sq_norm = ddot(w.shape[0], wdata, 1, wdata, 1) */ - ((struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_self)->wscale = 1.0; + __pyx_v_self->wscale = 1.0; - /* "sklearn/utils/weight_vector.pyx":44 - * self.w_data_ptr = w.data + /* "sklearn/utils/weight_vector.pyx":62 + * self.w_data_ptr = wdata * self.wscale = 1.0 * self.n_features = w.shape[0] # <<<<<<<<<<<<<< - * self.sq_norm = np.dot(w, w) + * self.sq_norm = ddot(w.shape[0], wdata, 1, wdata, 1) * */ - ((struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_self)->n_features = (__pyx_v_w->dimensions[0]); + __pyx_v_self->n_features = (__pyx_v_w->dimensions[0]); - /* "sklearn/utils/weight_vector.pyx":45 + /* "sklearn/utils/weight_vector.pyx":63 * self.wscale = 1.0 * self.n_features = w.shape[0] - * self.sq_norm = np.dot(w, w) # <<<<<<<<<<<<<< + * self.sq_norm = ddot(w.shape[0], wdata, 1, wdata, 1) # <<<<<<<<<<<<<< * - * cdef void add(self, DOUBLE *x_data_ptr, INTEGER *x_ind_ptr, + * self.aw = aw + */ + __pyx_v_self->sq_norm = cblas_ddot(((int)(__pyx_v_w->dimensions[0])), __pyx_v_wdata, 1, __pyx_v_wdata, 1); + + /* "sklearn/utils/weight_vector.pyx":65 + * self.sq_norm = ddot(w.shape[0], wdata, 1, wdata, 1) + * + * self.aw = aw # <<<<<<<<<<<<<< + * if self.aw is not None: + * self.aw_data_ptr = aw.data + */ + __Pyx_INCREF(((PyObject *)__pyx_v_aw)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_aw)); + __Pyx_GOTREF(__pyx_v_self->aw); + __Pyx_DECREF(((PyObject *)__pyx_v_self->aw)); + __pyx_v_self->aw = ((PyArrayObject *)__pyx_v_aw); + + /* "sklearn/utils/weight_vector.pyx":66 + * + * self.aw = aw + * if self.aw is not None: # <<<<<<<<<<<<<< + * self.aw_data_ptr = aw.data + * self.average_a = 0.0 + */ + __pyx_t_1 = (((PyObject *)__pyx_v_self->aw) != Py_None); + __pyx_t_5 = (__pyx_t_1 != 0); + if (__pyx_t_5) { + + /* "sklearn/utils/weight_vector.pyx":67 + * self.aw = aw + * if self.aw is not None: + * self.aw_data_ptr = aw.data # <<<<<<<<<<<<<< + * self.average_a = 0.0 + * self.average_b = 1.0 + */ + __pyx_v_self->aw_data_ptr = ((double *)__pyx_v_aw->data); + + /* "sklearn/utils/weight_vector.pyx":68 + * if self.aw is not None: + * self.aw_data_ptr = aw.data + * self.average_a = 0.0 # <<<<<<<<<<<<<< + * self.average_b = 1.0 + * + */ + __pyx_v_self->average_a = 0.0; + + /* "sklearn/utils/weight_vector.pyx":69 + * self.aw_data_ptr = aw.data + * self.average_a = 0.0 + * self.average_b = 1.0 # <<<<<<<<<<<<<< + * + * cdef void add(self, double *x_data_ptr, int *x_ind_ptr, int xnnz, + */ + __pyx_v_self->average_b = 1.0; + goto __pyx_L4; + } + __pyx_L4:; + + /* "sklearn/utils/weight_vector.pyx":51 + * """ + * + * def __cinit__(self, # <<<<<<<<<<<<<< + * np.ndarray[double, ndim=1, mode='c'] w, + * np.ndarray[double, ndim=1, mode='c'] aw): */ - __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__dot); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __Pyx_INCREF(((PyObject *)__pyx_v_w)); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_w)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_w)); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_4 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_4 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - ((struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_self)->sq_norm = __pyx_t_4; + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_w); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_aw.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("sklearn.utils.weight_vector.WeightVector.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_bstruct_w); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_aw.rcbuffer->pybuffer); + __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_w.rcbuffer->pybuffer); __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/utils/weight_vector.pyx":47 - * self.sq_norm = np.dot(w, w) +/* "sklearn/utils/weight_vector.pyx":71 + * self.average_b = 1.0 * - * cdef void add(self, DOUBLE *x_data_ptr, INTEGER *x_ind_ptr, # <<<<<<<<<<<<<< - * int xnnz, double c): - * """Scales example x by constant c and adds it to the weight vector. + * cdef void add(self, double *x_data_ptr, int *x_ind_ptr, int xnnz, # <<<<<<<<<<<<<< + * double c) nogil: + * """Scales sample x by constant c and adds it to the weight vector. */ -static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_self, __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *__pyx_v_x_data_ptr, __pyx_t_7sklearn_5utils_13weight_vector_INTEGER *__pyx_v_x_ind_ptr, int __pyx_v_xnnz, double __pyx_v_c) { +static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_self, double *__pyx_v_x_data_ptr, int *__pyx_v_x_ind_ptr, int __pyx_v_xnnz, double __pyx_v_c) { int __pyx_v_j; int __pyx_v_idx; double __pyx_v_val; double __pyx_v_innerprod; double __pyx_v_xsqnorm; double __pyx_v_wscale; - __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *__pyx_v_w_data_ptr; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; + double *__pyx_v_w_data_ptr; + double __pyx_t_1; + double *__pyx_t_2; int __pyx_t_3; - __Pyx_RefNannySetupContext("add"); + int __pyx_t_4; + int __pyx_t_5; - /* "sklearn/utils/weight_vector.pyx":67 + /* "sklearn/utils/weight_vector.pyx":91 * cdef int idx * cdef double val * cdef double innerprod = 0.0 # <<<<<<<<<<<<<< @@ -1184,7 +1616,7 @@ static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add(struct __ */ __pyx_v_innerprod = 0.0; - /* "sklearn/utils/weight_vector.pyx":68 + /* "sklearn/utils/weight_vector.pyx":92 * cdef double val * cdef double innerprod = 0.0 * cdef double xsqnorm = 0.0 # <<<<<<<<<<<<<< @@ -1193,36 +1625,38 @@ static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add(struct __ */ __pyx_v_xsqnorm = 0.0; - /* "sklearn/utils/weight_vector.pyx":71 + /* "sklearn/utils/weight_vector.pyx":95 * * # the next two lines save a factor of 2! * cdef double wscale = self.wscale # <<<<<<<<<<<<<< - * cdef DOUBLE* w_data_ptr = self.w_data_ptr + * cdef double* w_data_ptr = self.w_data_ptr * */ - __pyx_v_wscale = __pyx_v_self->wscale; + __pyx_t_1 = __pyx_v_self->wscale; + __pyx_v_wscale = __pyx_t_1; - /* "sklearn/utils/weight_vector.pyx":72 + /* "sklearn/utils/weight_vector.pyx":96 * # the next two lines save a factor of 2! * cdef double wscale = self.wscale - * cdef DOUBLE* w_data_ptr = self.w_data_ptr # <<<<<<<<<<<<<< + * cdef double* w_data_ptr = self.w_data_ptr # <<<<<<<<<<<<<< * * for j in range(xnnz): */ - __pyx_v_w_data_ptr = __pyx_v_self->w_data_ptr; + __pyx_t_2 = __pyx_v_self->w_data_ptr; + __pyx_v_w_data_ptr = __pyx_t_2; - /* "sklearn/utils/weight_vector.pyx":74 - * cdef DOUBLE* w_data_ptr = self.w_data_ptr + /* "sklearn/utils/weight_vector.pyx":98 + * cdef double* w_data_ptr = self.w_data_ptr * * for j in range(xnnz): # <<<<<<<<<<<<<< * idx = x_ind_ptr[j] * val = x_data_ptr[j] */ - __pyx_t_1 = __pyx_v_xnnz; - for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { - __pyx_v_j = __pyx_t_2; + __pyx_t_3 = __pyx_v_xnnz; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_j = __pyx_t_4; - /* "sklearn/utils/weight_vector.pyx":75 + /* "sklearn/utils/weight_vector.pyx":99 * * for j in range(xnnz): * idx = x_ind_ptr[j] # <<<<<<<<<<<<<< @@ -1231,7 +1665,7 @@ static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add(struct __ */ __pyx_v_idx = (__pyx_v_x_ind_ptr[__pyx_v_j]); - /* "sklearn/utils/weight_vector.pyx":76 + /* "sklearn/utils/weight_vector.pyx":100 * for j in range(xnnz): * idx = x_ind_ptr[j] * val = x_data_ptr[j] # <<<<<<<<<<<<<< @@ -1240,7 +1674,7 @@ static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add(struct __ */ __pyx_v_val = (__pyx_v_x_data_ptr[__pyx_v_j]); - /* "sklearn/utils/weight_vector.pyx":77 + /* "sklearn/utils/weight_vector.pyx":101 * idx = x_ind_ptr[j] * val = x_data_ptr[j] * innerprod += (w_data_ptr[idx] * val) # <<<<<<<<<<<<<< @@ -1249,7 +1683,7 @@ static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add(struct __ */ __pyx_v_innerprod = (__pyx_v_innerprod + ((__pyx_v_w_data_ptr[__pyx_v_idx]) * __pyx_v_val)); - /* "sklearn/utils/weight_vector.pyx":78 + /* "sklearn/utils/weight_vector.pyx":102 * val = x_data_ptr[j] * innerprod += (w_data_ptr[idx] * val) * xsqnorm += (val * val) # <<<<<<<<<<<<<< @@ -1258,79 +1692,231 @@ static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add(struct __ */ __pyx_v_xsqnorm = (__pyx_v_xsqnorm + (__pyx_v_val * __pyx_v_val)); - /* "sklearn/utils/weight_vector.pyx":79 + /* "sklearn/utils/weight_vector.pyx":103 * innerprod += (w_data_ptr[idx] * val) * xsqnorm += (val * val) * w_data_ptr[idx] += val * (c / wscale) # <<<<<<<<<<<<<< * * self.sq_norm += (xsqnorm * c * c) + (2.0 * innerprod * wscale * c) */ - __pyx_t_3 = __pyx_v_idx; - (__pyx_v_w_data_ptr[__pyx_t_3]) = ((__pyx_v_w_data_ptr[__pyx_t_3]) + (__pyx_v_val * (__pyx_v_c / __pyx_v_wscale))); + __pyx_t_5 = __pyx_v_idx; + (__pyx_v_w_data_ptr[__pyx_t_5]) = ((__pyx_v_w_data_ptr[__pyx_t_5]) + (__pyx_v_val * (__pyx_v_c / __pyx_v_wscale))); } - /* "sklearn/utils/weight_vector.pyx":81 + /* "sklearn/utils/weight_vector.pyx":105 * w_data_ptr[idx] += val * (c / wscale) * * self.sq_norm += (xsqnorm * c * c) + (2.0 * innerprod * wscale * c) # <<<<<<<<<<<<<< * - * cdef double dot(self, DOUBLE *x_data_ptr, INTEGER *x_ind_ptr, int xnnz): + * # Update the average weights according to the sparse trick defined */ __pyx_v_self->sq_norm = (__pyx_v_self->sq_norm + (((__pyx_v_xsqnorm * __pyx_v_c) * __pyx_v_c) + (((2.0 * __pyx_v_innerprod) * __pyx_v_wscale) * __pyx_v_c))); - __Pyx_RefNannyFinishContext(); + /* "sklearn/utils/weight_vector.pyx":71 + * self.average_b = 1.0 + * + * cdef void add(self, double *x_data_ptr, int *x_ind_ptr, int xnnz, # <<<<<<<<<<<<<< + * double c) nogil: + * """Scales sample x by constant c and adds it to the weight vector. + */ + + /* function exit code */ } -/* "sklearn/utils/weight_vector.pyx":83 - * self.sq_norm += (xsqnorm * c * c) + (2.0 * innerprod * wscale * c) +/* "sklearn/utils/weight_vector.pyx":110 + * # here: http://research.microsoft.com/pubs/192769/tricks-2012.pdf + * # by Leon Bottou + * cdef void add_average(self, double *x_data_ptr, int *x_ind_ptr, int xnnz, # <<<<<<<<<<<<<< + * double c, double num_iter) nogil: + * """Updates the average weight vector. + */ + +static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add_average(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_self, double *__pyx_v_x_data_ptr, int *__pyx_v_x_ind_ptr, int __pyx_v_xnnz, double __pyx_v_c, double __pyx_v_num_iter) { + int __pyx_v_j; + int __pyx_v_idx; + double __pyx_v_val; + double __pyx_v_mu; + CYTHON_UNUSED double __pyx_v_average_a; + double __pyx_v_wscale; + double *__pyx_v_aw_data_ptr; + double __pyx_t_1; + double *__pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + + /* "sklearn/utils/weight_vector.pyx":130 + * cdef int idx + * cdef double val + * cdef double mu = 1.0 / num_iter # <<<<<<<<<<<<<< + * cdef double average_a = self.average_a + * cdef double wscale = self.wscale + */ + __pyx_v_mu = (1.0 / __pyx_v_num_iter); + + /* "sklearn/utils/weight_vector.pyx":131 + * cdef double val + * cdef double mu = 1.0 / num_iter + * cdef double average_a = self.average_a # <<<<<<<<<<<<<< + * cdef double wscale = self.wscale + * cdef double* aw_data_ptr = self.aw_data_ptr + */ + __pyx_t_1 = __pyx_v_self->average_a; + __pyx_v_average_a = __pyx_t_1; + + /* "sklearn/utils/weight_vector.pyx":132 + * cdef double mu = 1.0 / num_iter + * cdef double average_a = self.average_a + * cdef double wscale = self.wscale # <<<<<<<<<<<<<< + * cdef double* aw_data_ptr = self.aw_data_ptr * - * cdef double dot(self, DOUBLE *x_data_ptr, INTEGER *x_ind_ptr, int xnnz): # <<<<<<<<<<<<<< - * """Computes the dot product of a sample x and the weight vector. + */ + __pyx_t_1 = __pyx_v_self->wscale; + __pyx_v_wscale = __pyx_t_1; + + /* "sklearn/utils/weight_vector.pyx":133 + * cdef double average_a = self.average_a + * cdef double wscale = self.wscale + * cdef double* aw_data_ptr = self.aw_data_ptr # <<<<<<<<<<<<<< + * + * for j in range(xnnz): + */ + __pyx_t_2 = __pyx_v_self->aw_data_ptr; + __pyx_v_aw_data_ptr = __pyx_t_2; + + /* "sklearn/utils/weight_vector.pyx":135 + * cdef double* aw_data_ptr = self.aw_data_ptr + * + * for j in range(xnnz): # <<<<<<<<<<<<<< + * idx = x_ind_ptr[j] + * val = x_data_ptr[j] + */ + __pyx_t_3 = __pyx_v_xnnz; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_j = __pyx_t_4; + + /* "sklearn/utils/weight_vector.pyx":136 + * + * for j in range(xnnz): + * idx = x_ind_ptr[j] # <<<<<<<<<<<<<< + * val = x_data_ptr[j] + * aw_data_ptr[idx] += (self.average_a * val * (-c / wscale)) + */ + __pyx_v_idx = (__pyx_v_x_ind_ptr[__pyx_v_j]); + + /* "sklearn/utils/weight_vector.pyx":137 + * for j in range(xnnz): + * idx = x_ind_ptr[j] + * val = x_data_ptr[j] # <<<<<<<<<<<<<< + * aw_data_ptr[idx] += (self.average_a * val * (-c / wscale)) + * + */ + __pyx_v_val = (__pyx_v_x_data_ptr[__pyx_v_j]); + + /* "sklearn/utils/weight_vector.pyx":138 + * idx = x_ind_ptr[j] + * val = x_data_ptr[j] + * aw_data_ptr[idx] += (self.average_a * val * (-c / wscale)) # <<<<<<<<<<<<<< + * + * # Once the the sample has been processed + */ + __pyx_t_5 = __pyx_v_idx; + (__pyx_v_aw_data_ptr[__pyx_t_5]) = ((__pyx_v_aw_data_ptr[__pyx_t_5]) + ((__pyx_v_self->average_a * __pyx_v_val) * ((-__pyx_v_c) / __pyx_v_wscale))); + } + + /* "sklearn/utils/weight_vector.pyx":142 + * # Once the the sample has been processed + * # update the average_a and average_b + * if num_iter > 1: # <<<<<<<<<<<<<< + * self.average_b /= (1.0 - mu) + * self.average_a += mu * self.average_b * wscale + */ + __pyx_t_6 = ((__pyx_v_num_iter > 1.0) != 0); + if (__pyx_t_6) { + + /* "sklearn/utils/weight_vector.pyx":143 + * # update the average_a and average_b + * if num_iter > 1: + * self.average_b /= (1.0 - mu) # <<<<<<<<<<<<<< + * self.average_a += mu * self.average_b * wscale + * + */ + __pyx_v_self->average_b = (__pyx_v_self->average_b / (1.0 - __pyx_v_mu)); + goto __pyx_L5; + } + __pyx_L5:; + + /* "sklearn/utils/weight_vector.pyx":144 + * if num_iter > 1: + * self.average_b /= (1.0 - mu) + * self.average_a += mu * self.average_b * wscale # <<<<<<<<<<<<<< + * + * cdef double dot(self, double *x_data_ptr, int *x_ind_ptr, + */ + __pyx_v_self->average_a = (__pyx_v_self->average_a + ((__pyx_v_mu * __pyx_v_self->average_b) * __pyx_v_wscale)); + + /* "sklearn/utils/weight_vector.pyx":110 + * # here: http://research.microsoft.com/pubs/192769/tricks-2012.pdf + * # by Leon Bottou + * cdef void add_average(self, double *x_data_ptr, int *x_ind_ptr, int xnnz, # <<<<<<<<<<<<<< + * double c, double num_iter) nogil: + * """Updates the average weight vector. + */ + + /* function exit code */ +} + +/* "sklearn/utils/weight_vector.pyx":146 + * self.average_a += mu * self.average_b * wscale * + * cdef double dot(self, double *x_data_ptr, int *x_ind_ptr, # <<<<<<<<<<<<<< + * int xnnz) nogil: + * """Computes the dot product of a sample x and the weight vector. */ -static double __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_dot(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_self, __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *__pyx_v_x_data_ptr, __pyx_t_7sklearn_5utils_13weight_vector_INTEGER *__pyx_v_x_ind_ptr, int __pyx_v_xnnz) { +static double __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_dot(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_self, double *__pyx_v_x_data_ptr, int *__pyx_v_x_ind_ptr, int __pyx_v_xnnz) { int __pyx_v_j; int __pyx_v_idx; double __pyx_v_innerprod; - __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *__pyx_v_w_data_ptr; + double *__pyx_v_w_data_ptr; double __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; + double *__pyx_t_1; int __pyx_t_2; - __Pyx_RefNannySetupContext("dot"); + int __pyx_t_3; - /* "sklearn/utils/weight_vector.pyx":102 + /* "sklearn/utils/weight_vector.pyx":166 * cdef int j * cdef int idx * cdef double innerprod = 0.0 # <<<<<<<<<<<<<< - * cdef DOUBLE* w_data_ptr = self.w_data_ptr + * cdef double* w_data_ptr = self.w_data_ptr * for j in range(xnnz): */ __pyx_v_innerprod = 0.0; - /* "sklearn/utils/weight_vector.pyx":103 + /* "sklearn/utils/weight_vector.pyx":167 * cdef int idx * cdef double innerprod = 0.0 - * cdef DOUBLE* w_data_ptr = self.w_data_ptr # <<<<<<<<<<<<<< + * cdef double* w_data_ptr = self.w_data_ptr # <<<<<<<<<<<<<< * for j in range(xnnz): * idx = x_ind_ptr[j] */ - __pyx_v_w_data_ptr = __pyx_v_self->w_data_ptr; + __pyx_t_1 = __pyx_v_self->w_data_ptr; + __pyx_v_w_data_ptr = __pyx_t_1; - /* "sklearn/utils/weight_vector.pyx":104 + /* "sklearn/utils/weight_vector.pyx":168 * cdef double innerprod = 0.0 - * cdef DOUBLE* w_data_ptr = self.w_data_ptr + * cdef double* w_data_ptr = self.w_data_ptr * for j in range(xnnz): # <<<<<<<<<<<<<< * idx = x_ind_ptr[j] * innerprod += w_data_ptr[idx] * x_data_ptr[j] */ - __pyx_t_1 = __pyx_v_xnnz; - for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { - __pyx_v_j = __pyx_t_2; + __pyx_t_2 = __pyx_v_xnnz; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_j = __pyx_t_3; - /* "sklearn/utils/weight_vector.pyx":105 - * cdef DOUBLE* w_data_ptr = self.w_data_ptr + /* "sklearn/utils/weight_vector.pyx":169 + * cdef double* w_data_ptr = self.w_data_ptr * for j in range(xnnz): * idx = x_ind_ptr[j] # <<<<<<<<<<<<<< * innerprod += w_data_ptr[idx] * x_data_ptr[j] @@ -1338,7 +1924,7 @@ static double __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_dot(struct */ __pyx_v_idx = (__pyx_v_x_ind_ptr[__pyx_v_j]); - /* "sklearn/utils/weight_vector.pyx":106 + /* "sklearn/utils/weight_vector.pyx":170 * for j in range(xnnz): * idx = x_ind_ptr[j] * innerprod += w_data_ptr[idx] * x_data_ptr[j] # <<<<<<<<<<<<<< @@ -1348,7 +1934,7 @@ static double __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_dot(struct __pyx_v_innerprod = (__pyx_v_innerprod + ((__pyx_v_w_data_ptr[__pyx_v_idx]) * (__pyx_v_x_data_ptr[__pyx_v_j]))); } - /* "sklearn/utils/weight_vector.pyx":107 + /* "sklearn/utils/weight_vector.pyx":171 * idx = x_ind_ptr[j] * innerprod += w_data_ptr[idx] * x_data_ptr[j] * innerprod *= self.wscale # <<<<<<<<<<<<<< @@ -1357,36 +1943,41 @@ static double __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_dot(struct */ __pyx_v_innerprod = (__pyx_v_innerprod * __pyx_v_self->wscale); - /* "sklearn/utils/weight_vector.pyx":108 + /* "sklearn/utils/weight_vector.pyx":172 * innerprod += w_data_ptr[idx] * x_data_ptr[j] * innerprod *= self.wscale * return innerprod # <<<<<<<<<<<<<< * - * cdef void scale(self, double c): + * cdef void scale(self, double c) nogil: */ __pyx_r = __pyx_v_innerprod; goto __pyx_L0; - __pyx_r = 0; + /* "sklearn/utils/weight_vector.pyx":146 + * self.average_a += mu * self.average_b * wscale + * + * cdef double dot(self, double *x_data_ptr, int *x_ind_ptr, # <<<<<<<<<<<<<< + * int xnnz) nogil: + * """Computes the dot product of a sample x and the weight vector. + */ + + /* function exit code */ __pyx_L0:; - __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "sklearn/utils/weight_vector.pyx":110 +/* "sklearn/utils/weight_vector.pyx":174 * return innerprod * - * cdef void scale(self, double c): # <<<<<<<<<<<<<< + * cdef void scale(self, double c) nogil: # <<<<<<<<<<<<<< * """Scales the weight vector by a constant ``c``. * */ static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_scale(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_self, double __pyx_v_c) { - __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("scale"); - /* "sklearn/utils/weight_vector.pyx":115 + /* "sklearn/utils/weight_vector.pyx":179 * It updates ``wscale`` and ``sq_norm``. If ``wscale`` gets too * small we call ``reset_swcale``.""" * self.wscale *= c # <<<<<<<<<<<<<< @@ -1395,7 +1986,7 @@ static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_scale(struct */ __pyx_v_self->wscale = (__pyx_v_self->wscale * __pyx_v_c); - /* "sklearn/utils/weight_vector.pyx":116 + /* "sklearn/utils/weight_vector.pyx":180 * small we call ``reset_swcale``.""" * self.wscale *= c * self.sq_norm *= (c * c) # <<<<<<<<<<<<<< @@ -1404,113 +1995,163 @@ static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_scale(struct */ __pyx_v_self->sq_norm = (__pyx_v_self->sq_norm * (__pyx_v_c * __pyx_v_c)); - /* "sklearn/utils/weight_vector.pyx":117 + /* "sklearn/utils/weight_vector.pyx":181 * self.wscale *= c * self.sq_norm *= (c * c) * if self.wscale < 1e-9: # <<<<<<<<<<<<<< * self.reset_wscale() * */ - __pyx_t_1 = (__pyx_v_self->wscale < 1e-9); + __pyx_t_1 = ((__pyx_v_self->wscale < 1e-9) != 0); if (__pyx_t_1) { - /* "sklearn/utils/weight_vector.pyx":118 + /* "sklearn/utils/weight_vector.pyx":182 * self.sq_norm *= (c * c) * if self.wscale < 1e-9: * self.reset_wscale() # <<<<<<<<<<<<<< * - * cdef void reset_wscale(self): + * cdef void reset_wscale(self) nogil: */ ((struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector *)__pyx_v_self->__pyx_vtab)->reset_wscale(__pyx_v_self); goto __pyx_L3; } __pyx_L3:; - __Pyx_RefNannyFinishContext(); + /* "sklearn/utils/weight_vector.pyx":174 + * return innerprod + * + * cdef void scale(self, double c) nogil: # <<<<<<<<<<<<<< + * """Scales the weight vector by a constant ``c``. + * + */ + + /* function exit code */ } -/* "sklearn/utils/weight_vector.pyx":120 +/* "sklearn/utils/weight_vector.pyx":184 * self.reset_wscale() * - * cdef void reset_wscale(self): # <<<<<<<<<<<<<< + * cdef void reset_wscale(self) nogil: # <<<<<<<<<<<<<< * """Scales each coef of ``w`` by ``wscale`` and resets it to 1. """ - * self.w *= self.wscale + * if self.aw is not None: */ static void __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_reset_wscale(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_self) { - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("reset_wscale"); + int __pyx_t_1; + int __pyx_t_2; + + /* "sklearn/utils/weight_vector.pyx":186 + * cdef void reset_wscale(self) nogil: + * """Scales each coef of ``w`` by ``wscale`` and resets it to 1. """ + * if self.aw is not None: # <<<<<<<<<<<<<< + * daxpy(self.aw.shape[0], self.average_a, + * self.w.data, 1, self.aw.data, 1) + */ + __pyx_t_1 = (((PyObject *)__pyx_v_self->aw) != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "sklearn/utils/weight_vector.pyx":122 - * cdef void reset_wscale(self): + /* "sklearn/utils/weight_vector.pyx":187 * """Scales each coef of ``w`` by ``wscale`` and resets it to 1. """ - * self.w *= self.wscale # <<<<<<<<<<<<<< + * if self.aw is not None: + * daxpy(self.aw.shape[0], self.average_a, # <<<<<<<<<<<<<< + * self.w.data, 1, self.aw.data, 1) + * dscal(self.aw.shape[0], 1.0 / self.average_b, + */ + cblas_daxpy(((int)(__pyx_v_self->aw->dimensions[0])), __pyx_v_self->average_a, ((double *)__pyx_v_self->w->data), 1, ((double *)__pyx_v_self->aw->data), 1); + + /* "sklearn/utils/weight_vector.pyx":189 + * daxpy(self.aw.shape[0], self.average_a, + * self.w.data, 1, self.aw.data, 1) + * dscal(self.aw.shape[0], 1.0 / self.average_b, # <<<<<<<<<<<<<< + * self.aw.data, 1) + * self.average_a = 0.0 + */ + cblas_dscal(((int)(__pyx_v_self->aw->dimensions[0])), (1.0 / __pyx_v_self->average_b), ((double *)__pyx_v_self->aw->data), 1); + + /* "sklearn/utils/weight_vector.pyx":191 + * dscal(self.aw.shape[0], 1.0 / self.average_b, + * self.aw.data, 1) + * self.average_a = 0.0 # <<<<<<<<<<<<<< + * self.average_b = 1.0 + * + */ + __pyx_v_self->average_a = 0.0; + + /* "sklearn/utils/weight_vector.pyx":192 + * self.aw.data, 1) + * self.average_a = 0.0 + * self.average_b = 1.0 # <<<<<<<<<<<<<< + * + * dscal(self.w.shape[0], self.wscale, self.w.data, 1) + */ + __pyx_v_self->average_b = 1.0; + goto __pyx_L3; + } + __pyx_L3:; + + /* "sklearn/utils/weight_vector.pyx":194 + * self.average_b = 1.0 + * + * dscal(self.w.shape[0], self.wscale, self.w.data, 1) # <<<<<<<<<<<<<< * self.wscale = 1.0 * */ - __pyx_t_1 = PyFloat_FromDouble(__pyx_v_self->wscale); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_InPlaceMultiply(((PyObject *)__pyx_v_self->w), __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_GOTREF(__pyx_v_self->w); - __Pyx_DECREF(((PyObject *)__pyx_v_self->w)); - __pyx_v_self->w = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; + cblas_dscal(((int)(__pyx_v_self->w->dimensions[0])), __pyx_v_self->wscale, ((double *)__pyx_v_self->w->data), 1); - /* "sklearn/utils/weight_vector.pyx":123 - * """Scales each coef of ``w`` by ``wscale`` and resets it to 1. """ - * self.w *= self.wscale + /* "sklearn/utils/weight_vector.pyx":195 + * + * dscal(self.w.shape[0], self.wscale, self.w.data, 1) * self.wscale = 1.0 # <<<<<<<<<<<<<< * - * cdef double norm(self): + * cdef double norm(self) nogil: */ __pyx_v_self->wscale = 1.0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_WriteUnraisable("sklearn.utils.weight_vector.WeightVector.reset_wscale", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_RefNannyFinishContext(); + /* "sklearn/utils/weight_vector.pyx":184 + * self.reset_wscale() + * + * cdef void reset_wscale(self) nogil: # <<<<<<<<<<<<<< + * """Scales each coef of ``w`` by ``wscale`` and resets it to 1. """ + * if self.aw is not None: + */ + + /* function exit code */ } -/* "sklearn/utils/weight_vector.pyx":125 +/* "sklearn/utils/weight_vector.pyx":197 * self.wscale = 1.0 * - * cdef double norm(self): # <<<<<<<<<<<<<< + * cdef double norm(self) nogil: # <<<<<<<<<<<<<< * """The L2 norm of the weight vector. """ * return sqrt(self.sq_norm) */ static double __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_norm(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *__pyx_v_self) { double __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("norm"); - /* "sklearn/utils/weight_vector.pyx":127 - * cdef double norm(self): + /* "sklearn/utils/weight_vector.pyx":199 + * cdef double norm(self) nogil: * """The L2 norm of the weight vector. """ * return sqrt(self.sq_norm) # <<<<<<<<<<<<<< */ __pyx_r = sqrt(__pyx_v_self->sq_norm); goto __pyx_L0; - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "sklearn/utils/weight_vector.pyx":197 + * self.wscale = 1.0 + * + * cdef double norm(self) nogil: # <<<<<<<<<<<<<< + * """The L2 norm of the weight vector. """ + * return sqrt(self.sq_norm) + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} -/* "numpy.pxd":190 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< @@ -1518,8 +2159,20 @@ static double __pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_norm(struct * # requirements, and does not yet fullfill the PEP. */ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; @@ -1544,28 +2197,26 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getbuffer__"); + __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "numpy.pxd":196 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":200 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ - __pyx_t_1 = (__pyx_v_info == NULL); + __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; - goto __pyx_L5; } - __pyx_L5:; - /* "numpy.pxd":199 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":203 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -1574,7 +2225,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":200 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":204 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -1583,26 +2234,26 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":202 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":206 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - /* "numpy.pxd":204 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":208 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":205 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":209 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< @@ -1610,11 +2261,11 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ * copy_shape = 0 */ __pyx_v_copy_shape = 1; - goto __pyx_L6; + goto __pyx_L4; } /*else*/ { - /* "numpy.pxd":207 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":211 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< @@ -1623,98 +2274,94 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_copy_shape = 0; } - __pyx_L6:; + __pyx_L4:; - /* "numpy.pxd":209 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":213 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + __pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_1) { - /* "numpy.pxd":210 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ - __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); + __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { - /* "numpy.pxd":211 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L7:; - /* "numpy.pxd":213 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":217 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ - __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + __pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_3) { - /* "numpy.pxd":214 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ - __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); + __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { - /* "numpy.pxd":215 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L8:; - /* "numpy.pxd":217 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":221 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ - __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - /* "numpy.pxd":218 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< @@ -1723,16 +2370,17 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->ndim = __pyx_v_ndim; - /* "numpy.pxd":219 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":223 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ - if (__pyx_v_copy_shape) { + __pyx_t_2 = (__pyx_v_copy_shape != 0); + if (__pyx_t_2) { - /* "numpy.pxd":222 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< @@ -1741,7 +2389,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); - /* "numpy.pxd":223 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":227 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< @@ -1750,7 +2398,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - /* "numpy.pxd":224 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":228 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< @@ -1761,49 +2409,49 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "numpy.pxd":225 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":229 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - /* "numpy.pxd":226 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":230 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } - goto __pyx_L9; + goto __pyx_L7; } /*else*/ { - /* "numpy.pxd":228 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - /* "numpy.pxd":229 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } - __pyx_L9:; + __pyx_L7:; - /* "numpy.pxd":230 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":234 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -1812,25 +2460,25 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->suboffsets = NULL; - /* "numpy.pxd":231 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - /* "numpy.pxd":232 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":236 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ - __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - /* "numpy.pxd":235 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< @@ -1839,17 +2487,19 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_f = NULL; - /* "numpy.pxd":236 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":240 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); - __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); + __Pyx_INCREF(__pyx_t_4); + __pyx_v_descr = ((PyArray_Descr *)__pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":240 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":244 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< @@ -1858,23 +2508,23 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "numpy.pxd":242 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":246 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ - __pyx_t_2 = (!__pyx_v_hasfields); + __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { - __pyx_t_3 = (!__pyx_v_copy_shape); + __pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; } if (__pyx_t_1) { - /* "numpy.pxd":244 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":248 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< @@ -1886,69 +2536,70 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; - goto __pyx_L12; + goto __pyx_L10; } /*else*/ { - /* "numpy.pxd":247 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":251 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ - __Pyx_INCREF(__pyx_v_self); - __Pyx_GIVEREF(__pyx_v_self); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = __pyx_v_self; + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } - __pyx_L12:; + __pyx_L10:; - /* "numpy.pxd":249 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":253 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or + * if ((descr.byteorder == c'>' and little_endian) or */ - __pyx_t_1 = (!__pyx_v_hasfields); + __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { - /* "numpy.pxd":250 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":254 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): */ - __pyx_v_t = __pyx_v_descr->type_num; + __pyx_t_5 = __pyx_v_descr->type_num; + __pyx_v_t = __pyx_t_5; - /* "numpy.pxd":251 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":255 * if not hasfields: * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == '<' and not little_endian)): + * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0); if (__pyx_t_1) { - __pyx_t_2 = __pyx_v_little_endian; + __pyx_t_2 = (__pyx_v_little_endian != 0); } else { __pyx_t_2 = __pyx_t_1; } if (!__pyx_t_2) { - /* "numpy.pxd":252 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":256 * t = descr.type_num - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ - __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); + __pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_1) { - __pyx_t_3 = (!__pyx_v_little_endian); + __pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_7 = __pyx_t_3; } else { __pyx_t_7 = __pyx_t_1; @@ -1959,271 +2610,244 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ } if (__pyx_t_1) { - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L14:; - /* "numpy.pxd":254 - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) + */ + switch (__pyx_v_t) { + + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ - __pyx_t_1 = (__pyx_v_t == NPY_BYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__b; - goto __pyx_L15; - } + case NPY_BYTE: + __pyx_v_f = __pyx_k_b; + break; - /* "numpy.pxd":255 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ - __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__B; - goto __pyx_L15; - } + case NPY_UBYTE: + __pyx_v_f = __pyx_k_B; + break; - /* "numpy.pxd":256 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ - __pyx_t_1 = (__pyx_v_t == NPY_SHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__h; - goto __pyx_L15; - } + case NPY_SHORT: + __pyx_v_f = __pyx_k_h; + break; - /* "numpy.pxd":257 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":261 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ - __pyx_t_1 = (__pyx_v_t == NPY_USHORT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__H; - goto __pyx_L15; - } + case NPY_USHORT: + __pyx_v_f = __pyx_k_H; + break; - /* "numpy.pxd":258 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":262 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ - __pyx_t_1 = (__pyx_v_t == NPY_INT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__i; - goto __pyx_L15; - } + case NPY_INT: + __pyx_v_f = __pyx_k_i; + break; - /* "numpy.pxd":259 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ - __pyx_t_1 = (__pyx_v_t == NPY_UINT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__I; - goto __pyx_L15; - } + case NPY_UINT: + __pyx_v_f = __pyx_k_I; + break; - /* "numpy.pxd":260 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__l; - goto __pyx_L15; - } + case NPY_LONG: + __pyx_v_f = __pyx_k_l; + break; - /* "numpy.pxd":261 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__L; - goto __pyx_L15; - } + case NPY_ULONG: + __pyx_v_f = __pyx_k_L; + break; - /* "numpy.pxd":262 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__q; - goto __pyx_L15; - } + case NPY_LONGLONG: + __pyx_v_f = __pyx_k_q; + break; - /* "numpy.pxd":263 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ - __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Q; - goto __pyx_L15; - } + case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_Q; + break; - /* "numpy.pxd":264 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ - __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__f; - goto __pyx_L15; - } + case NPY_FLOAT: + __pyx_v_f = __pyx_k_f; + break; - /* "numpy.pxd":265 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ - __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__d; - goto __pyx_L15; - } + case NPY_DOUBLE: + __pyx_v_f = __pyx_k_d; + break; - /* "numpy.pxd":266 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ - __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__g; - goto __pyx_L15; - } + case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_g; + break; - /* "numpy.pxd":267 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ - __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zf; - goto __pyx_L15; - } + case NPY_CFLOAT: + __pyx_v_f = __pyx_k_Zf; + break; - /* "numpy.pxd":268 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ - __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zd; - goto __pyx_L15; - } + case NPY_CDOUBLE: + __pyx_v_f = __pyx_k_Zd; + break; - /* "numpy.pxd":269 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ - __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__Zg; - goto __pyx_L15; - } + case NPY_CLONGDOUBLE: + __pyx_v_f = __pyx_k_Zg; + break; - /* "numpy.pxd":270 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); - if (__pyx_t_1) { - __pyx_v_f = __pyx_k__O; - goto __pyx_L15; - } - /*else*/ { + case NPY_OBJECT: + __pyx_v_f = __pyx_k_O; + break; + default: - /* "numpy.pxd":272 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ - __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_8)); + __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8); + __Pyx_GIVEREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + break; } - __pyx_L15:; - /* "numpy.pxd":273 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< @@ -2232,7 +2856,7 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_v_info->format = __pyx_v_f; - /* "numpy.pxd":274 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":278 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< @@ -2241,58 +2865,65 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ */ __pyx_r = 0; goto __pyx_L0; - goto __pyx_L13; } /*else*/ { - /* "numpy.pxd":276 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); - /* "numpy.pxd":277 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":281 * else: * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< + * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; - /* "numpy.pxd":278 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":282 * info.format = stdlib.malloc(_buffer_format_string_len) - * info.format[0] = '^' # Native data types, manual alignment + * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; - /* "numpy.pxd":281 - * f = _util_dtypestring(descr, info.format + 1, + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 + * info.format[0] = c'^' # Native data types, manual alignment + * offset = 0 + * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, - * &offset) # <<<<<<<<<<<<<< - * f[0] = 0 # Terminate format string - * + * &offset) */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; - /* "numpy.pxd":282 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":286 * info.format + _buffer_format_string_len, * &offset) - * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< + * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ - (__pyx_v_f[0]) = 0; + (__pyx_v_f[0]) = '\x00'; } - __pyx_L13:; + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":194 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + + /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; @@ -2316,31 +2947,41 @@ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_ return __pyx_r; } -/* "numpy.pxd":284 - * f[0] = 0 # Terminate format string +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { +/* Python wrapper */ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__"); + __Pyx_RefNannySetupContext("__releasebuffer__", 0); - /* "numpy.pxd":285 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":289 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ - __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { - /* "numpy.pxd":286 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":290 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< @@ -2348,21 +2989,21 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * stdlib.free(info.strides) */ free(__pyx_v_info->format); - goto __pyx_L5; + goto __pyx_L3; } - __pyx_L5:; + __pyx_L3:; - /* "numpy.pxd":287 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ - __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { - /* "numpy.pxd":288 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< @@ -2370,14 +3011,23 @@ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject * * */ free(__pyx_v_info->strides); - goto __pyx_L6; + goto __pyx_L4; } - __pyx_L6:; + __pyx_L4:; + + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 + * f[0] = c'\0' # Terminate format string + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":764 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< @@ -2392,9 +3042,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - /* "numpy.pxd":765 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":769 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< @@ -2402,14 +3052,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -2420,7 +3077,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__ return __pyx_r; } -/* "numpy.pxd":767 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< @@ -2435,9 +3092,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - /* "numpy.pxd":768 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":772 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< @@ -2445,14 +3102,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -2463,7 +3127,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__ return __pyx_r; } -/* "numpy.pxd":770 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< @@ -2478,9 +3142,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - /* "numpy.pxd":771 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":775 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< @@ -2488,14 +3152,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -2506,7 +3177,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__ return __pyx_r; } -/* "numpy.pxd":773 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< @@ -2521,9 +3192,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - /* "numpy.pxd":774 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":778 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< @@ -2531,14 +3202,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -2549,7 +3227,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__ return __pyx_r; } -/* "numpy.pxd":776 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< @@ -2564,9 +3242,9 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - /* "numpy.pxd":777 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":781 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< @@ -2574,14 +3252,21 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -2592,7 +3277,7 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__ return __pyx_r; } -/* "numpy.pxd":779 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< @@ -2614,7 +3299,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; + int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; int __pyx_t_8; @@ -2624,9 +3309,9 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_util_dtypestring"); + __Pyx_RefNannySetupContext("_util_dtypestring", 0); - /* "numpy.pxd":786 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":790 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< @@ -2635,7 +3320,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_endian_detector = 1; - /* "numpy.pxd":787 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":791 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< @@ -2644,134 +3329,136 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - /* "numpy.pxd":790 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ - if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_v_descr->names == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; + __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; - __Pyx_XDECREF(__pyx_v_childname); - __pyx_v_childname = __pyx_t_3; + #if CYTHON_COMPILING_IN_CPYTHON + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; - /* "numpy.pxd":791 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ - __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); - __pyx_v_fields = ((PyObject*)__pyx_t_3); + if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; - /* "numpy.pxd":792 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * - * if (end - f) - (new_offset - offset[0]) < 15: - */ - if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { - PyObject* sequence = ((PyObject *)__pyx_v_fields); - if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { - if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); - else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + * if (end - f) - (new_offset - offset[0]) < 15: + */ + if (likely(__pyx_v_fields != Py_None)) { + PyObject* sequence = __pyx_v_fields; + #if CYTHON_COMPILING_IN_CPYTHON + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + #endif } else { - __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF(((PyObject *)__pyx_v_child)); - __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_new_offset); - __pyx_v_new_offset = __pyx_t_4; + __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; - /* "numpy.pxd":794 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< + * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ - __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { - /* "numpy.pxd":795 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L5:; - /* "numpy.pxd":797 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * - * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == '<' and not little_endian)): + * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ - __pyx_t_6 = (__pyx_v_child->byteorder == '>'); + __pyx_t_6 = ((__pyx_v_child->byteorder == '>') != 0); if (__pyx_t_6) { - __pyx_t_7 = __pyx_v_little_endian; + __pyx_t_7 = (__pyx_v_little_endian != 0); } else { __pyx_t_7 = __pyx_t_6; } if (!__pyx_t_7) { - /* "numpy.pxd":798 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 * - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ - __pyx_t_6 = (__pyx_v_child->byteorder == '<'); + __pyx_t_6 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_6) { - __pyx_t_8 = (!__pyx_v_little_endian); + __pyx_t_8 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_9 = __pyx_t_8; } else { __pyx_t_9 = __pyx_t_6; @@ -2782,23 +3469,21 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } if (__pyx_t_6) { - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L6:; - /* "numpy.pxd":809 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< @@ -2806,16 +3491,15 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx * f += 1 */ while (1) { - __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; - /* "numpy.pxd":810 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< @@ -2824,7 +3508,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ (__pyx_v_f[0]) = 120; - /* "numpy.pxd":811 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< @@ -2833,7 +3517,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx */ __pyx_v_f = (__pyx_v_f + 1); - /* "numpy.pxd":812 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< @@ -2844,7 +3528,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); } - /* "numpy.pxd":814 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< @@ -2854,316 +3538,299 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_t_10 = 0; (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); - /* "numpy.pxd":816 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ - __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); + __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { - /* "numpy.pxd":817 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ - __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_v_t); - __pyx_v_t = __pyx_t_3; - __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); + __pyx_t_4 = 0; - /* "numpy.pxd":818 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ - __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); + __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { - /* "numpy.pxd":819 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_L10:; - /* "numpy.pxd":822 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ - __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L11; } - /* "numpy.pxd":823 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ - __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L11; } - /* "numpy.pxd":824 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ - __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 104; goto __pyx_L11; } - /* "numpy.pxd":825 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ - __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L11; } - /* "numpy.pxd":826 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ - __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 105; goto __pyx_L11; } - /* "numpy.pxd":827 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ - __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L11; } - /* "numpy.pxd":828 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 108; goto __pyx_L11; } - /* "numpy.pxd":829 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L11; } - /* "numpy.pxd":830 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 113; goto __pyx_L11; } - /* "numpy.pxd":831 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ - __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L11; } - /* "numpy.pxd":832 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ - __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 102; goto __pyx_L11; } - /* "numpy.pxd":833 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ - __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 100; goto __pyx_L11; } - /* "numpy.pxd":834 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ - __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 103; goto __pyx_L11; } - /* "numpy.pxd":835 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ - __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; @@ -3171,20 +3838,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":836 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ - __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; @@ -3192,20 +3858,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":837 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ - __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; @@ -3213,50 +3878,49 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx goto __pyx_L11; } - /* "numpy.pxd":838 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ - __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L11; } /*else*/ { - /* "numpy.pxd":840 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ - __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_5)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L11:; - /* "numpy.pxd":841 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< @@ -3268,21 +3932,21 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx } /*else*/ { - /* "numpy.pxd":845 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ - __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_11; } __pyx_L9:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":846 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< @@ -3292,13 +3956,19 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx __pyx_r = __pyx_v_f; goto __pyx_L0; - __pyx_r = 0; - goto __pyx_L0; + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< + * # Recursive utility function used in __getbuffer__ to get format + * # string. The new location in the format string is returned. + */ + + /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -3311,7 +3981,7 @@ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx return __pyx_r; } -/* "numpy.pxd":961 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< @@ -3323,9 +3993,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("set_array_base"); + int __pyx_t_2; + __Pyx_RefNannySetupContext("set_array_base", 0); - /* "numpy.pxd":963 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< @@ -3333,9 +4004,10 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "numpy.pxd":964 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< @@ -3347,7 +4019,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } /*else*/ { - /* "numpy.pxd":966 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":971 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< @@ -3356,7 +4028,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_INCREF(__pyx_v_base); - /* "numpy.pxd":967 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":972 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< @@ -3367,7 +4039,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a } __pyx_L3:; - /* "numpy.pxd":968 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":973 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< @@ -3376,7 +4048,7 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ Py_XDECREF(__pyx_v_arr->base); - /* "numpy.pxd":969 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":974 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< @@ -3385,10 +4057,19 @@ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_a */ __pyx_v_arr->base = __pyx_v_baseptr; + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 + * + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * cdef PyObject* baseptr + * if base is None: + */ + + /* function exit code */ __Pyx_RefNannyFinishContext(); } -/* "numpy.pxd":971 +/* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -3400,19 +4081,19 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base"); + __Pyx_RefNannySetupContext("get_array_base", 0); - /* "numpy.pxd":972 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ - __pyx_t_1 = (__pyx_v_arr->base == NULL); + __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { - /* "numpy.pxd":973 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":978 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< @@ -3423,11 +4104,10 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; - goto __pyx_L3; } /*else*/ { - /* "numpy.pxd":975 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return arr.base # <<<<<<<<<<<<<< @@ -3437,9 +4117,16 @@ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__py __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } - __pyx_L3:; - __pyx_r = Py_None; __Pyx_INCREF(Py_None); + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 + * arr.base = baseptr + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * if arr.base is NULL: + * return None + */ + + /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); @@ -3449,12 +4136,18 @@ static struct __pyx_vtabstruct_7sklearn_5utils_13weight_vector_WeightVector __py static PyObject *__pyx_tp_new_7sklearn_5utils_13weight_vector_WeightVector(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *p; - PyObject *o = (*t->tp_alloc)(t, 0); - if (!o) return 0; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; p = ((struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)o); p->__pyx_vtab = __pyx_vtabptr_7sklearn_5utils_13weight_vector_WeightVector; p->w = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - if (__pyx_pf_7sklearn_5utils_13weight_vector_12WeightVector___cinit__(o, a, k) < 0) { + p->aw = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_pw_7sklearn_5utils_13weight_vector_12WeightVector_1__cinit__(o, a, k) < 0)) { Py_DECREF(o); o = 0; } return o; @@ -3462,7 +4155,14 @@ static PyObject *__pyx_tp_new_7sklearn_5utils_13weight_vector_WeightVector(PyTyp static void __pyx_tp_dealloc_7sklearn_5utils_13weight_vector_WeightVector(PyObject *o) { struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *p = (struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)o; - Py_XDECREF(((PyObject *)p->w)); + #if PY_VERSION_HEX >= 0x030400a1 + if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->w); + Py_CLEAR(p->aw); (*Py_TYPE(o)->tp_free)(o); } @@ -3472,15 +4172,21 @@ static int __pyx_tp_traverse_7sklearn_5utils_13weight_vector_WeightVector(PyObje if (p->w) { e = (*v)(((PyObject*)p->w), a); if (e) return e; } + if (p->aw) { + e = (*v)(((PyObject*)p->aw), a); if (e) return e; + } return 0; } static int __pyx_tp_clear_7sklearn_5utils_13weight_vector_WeightVector(PyObject *o) { - struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *p = (struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)o; PyObject* tmp; + struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *p = (struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *)o; tmp = ((PyObject*)p->w); p->w = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); Py_XDECREF(tmp); + tmp = ((PyObject*)p->aw); + p->aw = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); return 0; } @@ -3488,130 +4194,32 @@ static PyMethodDef __pyx_methods_7sklearn_5utils_13weight_vector_WeightVector[] {0, 0, 0, 0} }; -static PyNumberMethods __pyx_tp_as_number_WeightVector = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ +static PyTypeObject __pyx_type_7sklearn_5utils_13weight_vector_WeightVector = { + PyVarObject_HEAD_INIT(0, 0) + __Pyx_NAMESTR("sklearn.utils.weight_vector.WeightVector"), /*tp_name*/ + sizeof(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_7sklearn_5utils_13weight_vector_WeightVector, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; - -static PySequenceMethods __pyx_tp_as_sequence_WeightVector = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_WeightVector = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_WeightVector = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; - -static PyTypeObject __pyx_type_7sklearn_5utils_13weight_vector_WeightVector = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("sklearn.utils.weight_vector.WeightVector"), /*tp_name*/ - sizeof(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7sklearn_5utils_13weight_vector_WeightVector, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ + 0, /*tp_compare*/ #else 0, /*reserved*/ #endif 0, /*tp_repr*/ - &__pyx_tp_as_number_WeightVector, /*tp_as_number*/ - &__pyx_tp_as_sequence_WeightVector, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_WeightVector, /*tp_as_mapping*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_WeightVector, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - __Pyx_DOCSTR("Dense vector represented by a scalar and a numpy array.\n\n The class provides methods to ``add`` a sparse vector\n and scale the vector.\n Representing a vector explicitly as a scalar times a\n vector allows for efficient scaling operations.\n\n Attributes\n ----------\n w : ndarray, dtype=np.float64, order='C'\n The numpy array which backs the weight vector.\n w_data_ptr : np.float64*\n A pointer to the data of the numpy array.\n wscale : double\n The scale of the vector.\n n_features : int\n The number of features (= dimensionality of ``w``).\n sq_norm : double\n The squared norm of ``w``.\n "), /*tp_doc*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + __Pyx_DOCSTR("Dense vector represented by a scalar and a numpy array.\n\n The class provides methods to ``add`` a sparse vector\n and scale the vector.\n Representing a vector explicitly as a scalar times a\n vector allows for efficient scaling operations.\n\n Attributes\n ----------\n w : ndarray, dtype=double, order='C'\n The numpy array which backs the weight vector.\n aw : ndarray, dtype=double, order='C'\n The numpy array which backs the average_weight vector.\n w_data_ptr : double*\n A pointer to the data of the numpy array.\n wscale : double\n The scale of the vector.\n n_features : int\n The number of features (= dimensionality of ``w``).\n sq_norm : double\n The squared norm of ``w``.\n "), /*tp_doc*/ __pyx_tp_traverse_7sklearn_5utils_13weight_vector_WeightVector, /*tp_traverse*/ __pyx_tp_clear_7sklearn_5utils_13weight_vector_WeightVector, /*tp_clear*/ 0, /*tp_richcompare*/ @@ -3640,6 +4248,9 @@ static PyTypeObject __pyx_type_7sklearn_5utils_13weight_vector_WeightVector = { #if PY_VERSION_HEX >= 0x02060000 0, /*tp_version_tag*/ #endif + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif }; static PyMethodDef __pyx_methods[] = { @@ -3648,7 +4259,11 @@ static PyMethodDef __pyx_methods[] = { #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { + #if PY_VERSION_HEX < 0x03020000 + { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, + #else PyModuleDef_HEAD_INIT, + #endif __Pyx_NAMESTR("weight_vector"), 0, /* m_doc */ -1, /* m_size */ @@ -3661,27 +4276,32 @@ static struct PyModuleDef __pyx_moduledef = { #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_u_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 1, 0, 0}, - {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, - {&__pyx_kp_u_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 1, 0, 0}, - {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, - {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, - {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, - {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s__dot, __pyx_k__dot, sizeof(__pyx_k__dot), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, - {&__pyx_n_s__w, __pyx_k__w, sizeof(__pyx_k__w), 0, 0, 1, 1}, + {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, + {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, + {&__pyx_kp_s_More_than_d_features_not_support, __pyx_k_More_than_d_features_not_support, sizeof(__pyx_k_More_than_d_features_not_support), 0, 0, 1, 0}, + {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_aw, __pyx_k_aw, sizeof(__pyx_k_aw), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, + {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, + {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_releasebuffer, __pyx_k_pyx_releasebuffer, sizeof(__pyx_k_pyx_releasebuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, + {&__pyx_n_s_w, __pyx_k_w, sizeof(__pyx_k_w), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -3689,91 +4309,73 @@ static int __Pyx_InitCachedBuiltins(void) { static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "numpy.pxd":211 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":215 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ - __pyx_k_tuple_2 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_2)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_1)); - PyTuple_SET_ITEM(__pyx_k_tuple_2, 0, ((PyObject *)__pyx_kp_u_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); - /* "numpy.pxd":215 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":219 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ - __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_4)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_3)); - PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_u_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_3)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); - /* "numpy.pxd":253 - * if ((descr.byteorder == '>' and little_endian) or - * (descr.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 + * if ((descr.byteorder == c'>' and little_endian) or + * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ - __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_6)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); - /* "numpy.pxd":795 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 * - * if (end - f) - (new_offset - offset[0]) < 15: + * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * - * if ((child.byteorder == '>' and little_endian) or + * if ((child.byteorder == c'>' and little_endian) or */ - __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_9)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); - PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); - /* "numpy.pxd":799 - * if ((child.byteorder == '>' and little_endian) or - * (child.byteorder == '<' and not little_endian)): + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 + * if ((child.byteorder == c'>' and little_endian) or + * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ - __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_10)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); - PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); - /* "numpy.pxd":819 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ - __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_12)); - __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); - PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -3783,7 +4385,6 @@ static int __Pyx_InitCachedConstants(void) { static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; return 0; __pyx_L1_error:; return -1; @@ -3798,6 +4399,9 @@ PyMODINIT_FUNC PyInit_weight_vector(void) #endif { PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -3808,12 +4412,18 @@ PyMODINIT_FUNC PyInit_weight_vector(void) Py_FatalError("failed to import 'refnanny' module"); } #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_weight_vector(void)"); + __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_weight_vector(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __pyx_binding_PyCFunctionType_USED - if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #ifdef __Pyx_CyFunction_USED + if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -3824,22 +4434,34 @@ PyMODINIT_FUNC PyInit_weight_vector(void) #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("weight_vector"), __pyx_methods, 0, 0, PYTHON_API_VERSION); + __pyx_m = Py_InitModule4(__Pyx_NAMESTR("weight_vector"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - #if PY_MAJOR_VERSION < 3 - Py_INCREF(__pyx_m); + if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); - if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #endif if (__pyx_module_is_main_sklearn__utils__weight_vector) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!PyDict_GetItemString(modules, "sklearn.utils.weight_vector")) { + if (unlikely(PyDict_SetItemString(modules, "sklearn.utils.weight_vector", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } } + #endif /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ @@ -3849,48 +4471,66 @@ PyMODINIT_FUNC PyInit_weight_vector(void) /*--- Function export code ---*/ /*--- Type init code ---*/ __pyx_vtabptr_7sklearn_5utils_13weight_vector_WeightVector = &__pyx_vtable_7sklearn_5utils_13weight_vector_WeightVector; - __pyx_vtable_7sklearn_5utils_13weight_vector_WeightVector.add = (void (*)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *, __pyx_t_7sklearn_5utils_13weight_vector_INTEGER *, int, double))__pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add; - __pyx_vtable_7sklearn_5utils_13weight_vector_WeightVector.dot = (double (*)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, __pyx_t_7sklearn_5utils_13weight_vector_DOUBLE *, __pyx_t_7sklearn_5utils_13weight_vector_INTEGER *, int))__pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_dot; + __pyx_vtable_7sklearn_5utils_13weight_vector_WeightVector.add = (void (*)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double *, int *, int, double))__pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add; + __pyx_vtable_7sklearn_5utils_13weight_vector_WeightVector.add_average = (void (*)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double *, int *, int, double, double))__pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_add_average; + __pyx_vtable_7sklearn_5utils_13weight_vector_WeightVector.dot = (double (*)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double *, int *, int))__pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_dot; __pyx_vtable_7sklearn_5utils_13weight_vector_WeightVector.scale = (void (*)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *, double))__pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_scale; __pyx_vtable_7sklearn_5utils_13weight_vector_WeightVector.reset_wscale = (void (*)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *))__pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_reset_wscale; __pyx_vtable_7sklearn_5utils_13weight_vector_WeightVector.norm = (double (*)(struct __pyx_obj_7sklearn_5utils_13weight_vector_WeightVector *))__pyx_f_7sklearn_5utils_13weight_vector_12WeightVector_norm; - if (PyType_Ready(&__pyx_type_7sklearn_5utils_13weight_vector_WeightVector) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetVtable(__pyx_type_7sklearn_5utils_13weight_vector_WeightVector.tp_dict, __pyx_vtabptr_7sklearn_5utils_13weight_vector_WeightVector) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "WeightVector", (PyObject *)&__pyx_type_7sklearn_5utils_13weight_vector_WeightVector) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyType_Ready(&__pyx_type_7sklearn_5utils_13weight_vector_WeightVector) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_type_7sklearn_5utils_13weight_vector_WeightVector.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type_7sklearn_5utils_13weight_vector_WeightVector.tp_dict, __pyx_vtabptr_7sklearn_5utils_13weight_vector_WeightVector) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetAttrString(__pyx_m, "WeightVector", (PyObject *)&__pyx_type_7sklearn_5utils_13weight_vector_WeightVector) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_7sklearn_5utils_13weight_vector_WeightVector = &__pyx_type_7sklearn_5utils_13weight_vector_WeightVector; /*--- Type import code ---*/ - __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", + #if CYTHON_COMPILING_IN_PYPY + sizeof(PyTypeObject), + #else + sizeof(PyHeapTypeObject), + #endif + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ - /* "sklearn/utils/weight_vector.pyx":11 - * - * + /* "sklearn/utils/weight_vector.pyx":14 + * from libc.limits cimport INT_MAX + * from libc.math cimport sqrt * import numpy as np # <<<<<<<<<<<<<< - * + * cimport numpy as np * */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /* "sklearn/utils/weight_vector.pyx":24 + * + * + * np.import_array() # <<<<<<<<<<<<<< + * + * + */ + import_array(); + /* "sklearn/utils/weight_vector.pyx":1 - * # encoding: utf-8 # <<<<<<<<<<<<<< - * # cython: cdivision=True + * # cython: cdivision=True # <<<<<<<<<<<<<< * # cython: boundscheck=False + * # cython: wraparound=False */ __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "numpy.pxd":971 + /* "/usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< @@ -3916,7 +4556,6 @@ PyMODINIT_FUNC PyInit_weight_vector(void) } /* Runtime support code */ - #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; @@ -3933,21 +4572,44 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { } #endif /* CYTHON_REFNANNY */ -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { - PyObject *result; - result = PyObject_GetAttr(dict, name); - if (!result) { - if (dict != __pyx_b) { - PyErr_Clear(); - result = PyObject_GetAttr(__pyx_b, name); - } - if (!result) { - PyErr_SetObject(PyExc_NameError, name); - } +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif } return result; } +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) @@ -3957,7 +4619,7 @@ static void __Pyx_RaiseDoubleKeywordsError( "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AS_STRING(kw_name)); + PyString_AsString(kw_name)); #endif } @@ -3973,64 +4635,86 @@ static int __Pyx_ParseOptionalKeywords( Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; - } else { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { - #else - if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { - #endif - goto invalid_keyword_type; - } else { - for (name = first_kw_arg; *name; name++) { - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) break; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) break; - #endif - } - if (*name) { + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { values[name-argnames] = value; - } else { - /* unexpected keyword found */ - for (name=argnames; name != first_kw_arg; name++) { - if (**name == key) goto arg_passed_twice; - #if PY_MAJOR_VERSION >= 3 - if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && - PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; - #else - if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && - _PyString_Eq(**name, key)) goto arg_passed_twice; - #endif - } - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; } } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; } } return 0; arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, **name); + __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); + "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", + "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", @@ -4040,49 +4724,29 @@ static int __Pyx_ParseOptionalKeywords( return -1; } -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } +static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { PyErr_Format(PyExc_TypeError, - "%s() takes %s %"PY_FORMAT_SIZE_T"d positional argument%s (%"PY_FORMAT_SIZE_T"d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); } - -static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { - if (!type) { - PyErr_Format(PyExc_SystemError, "Missing type object"); + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { - if (Py_TYPE(obj) == type) return 1; + if (likely(Py_TYPE(obj) == type)) return 1; + #if PY_MAJOR_VERSION == 2 + else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif } else { - if (PyObject_TypeCheck(obj, type)) return 1; + if (likely(PyObject_TypeCheck(obj, type))) return 1; } - PyErr_Format(PyExc_TypeError, - "Argument '%s' has incorrect type (expected %s, got %s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); + __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } @@ -4090,18 +4754,6 @@ static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } - -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; -} __Pyx_BufFmt_Context; - static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { @@ -4120,6 +4772,8 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; @@ -4127,7 +4781,6 @@ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, type = type->fields->type; } } - static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; @@ -4143,15 +4796,21 @@ static int __Pyx_BufFmt_ParseNumber(const char** ts) { *ts = t; return count; } - +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } - static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { - case 'b': return "'char'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; @@ -4167,14 +4826,14 @@ static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; + case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } - static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; @@ -4190,10 +4849,9 @@ static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { return 0; } } - static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'B': return 1; + case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); @@ -4210,7 +4868,6 @@ static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { } } } - typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; @@ -4221,10 +4878,9 @@ typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif - -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { - case '?': case 'c': case 'b': case 'B': return 1; + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); @@ -4240,21 +4896,59 @@ static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { return 0; } } - +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { - case 'c': case 'b': case 'h': case 'i': case 'l': case 'q': return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; - case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); - case 'O': return 'O'; - case 'P': return 'P'; + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } - static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; @@ -4279,16 +4973,37 @@ static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { parent->type->name, field->name); } } - static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; - size_t size, offset; + size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { @@ -4300,35 +5015,35 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); } - if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { - /* special case -- treat as struct rather than complex number */ size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } - - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } - offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } - ctx->fmt_offset += size; - + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; /* Consume from buffer string */ - - /* Done checking, move to next field, pushing or popping struct stack if needed */ while (1) { if (field == &ctx->root) { ctx->head = NULL; @@ -4360,7 +5075,50 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ctx->is_complex = 0; return 0; } - +static CYTHON_INLINE PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; /* not a 'break' in the loop */ + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { @@ -4375,7 +5133,7 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } - return ts; + return ts; case ' ': case 10: case 13: @@ -4407,12 +5165,17 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { @@ -4420,10 +5183,19 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha if (!ts_after_sub) return NULL; } ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': /* end of substruct; either repeat or move on */ - ++ts; + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; @@ -4444,13 +5216,11 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': - case 'O': + case 'O': case 's': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { - /* Continue pooling same type */ ctx->enc_count += ctx->new_count; } else { - /* New type */ if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; @@ -4466,20 +5236,18 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha while(*ts != ':') ++ts; ++ts; break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; default: { - int number = __Pyx_BufFmt_ParseNumber(&ts); - if (number == -1) { /* First char was not a digit */ - PyErr_Format(PyExc_ValueError, - "Does not understand character buffer dtype format string ('%c')", *ts); - return NULL; - } - ctx->new_count = (size_t)number; + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; } } } } - static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; @@ -4487,8 +5255,10 @@ static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } - -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { +static CYTHON_INLINE int __Pyx_GetBufferAndValidate( + Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, + int nd, int cast, __Pyx_BufFmt_StackElem* stack) +{ if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; @@ -4508,7 +5278,7 @@ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* ob } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, - "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; @@ -4519,17 +5289,39 @@ fail:; __Pyx_ZeroBuffer(buf); return -1; } - static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; +#endif + result = (*call)(func, arg, kw); +#if PY_VERSION_HEX >= 0x02060000 + Py_LeaveRecursiveCall(); +#endif + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; @@ -4539,90 +5331,81 @@ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyOb Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); +#else + PyErr_Restore(type, value, tb); +#endif } - static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { +#if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; -} - - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; - } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; +#else + PyErr_Fetch(type, value, tb); +#endif } #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - /* cause is unused */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - /* First, check the traceback argument, replacing None with NULL. */ - if (tb == Py_None) { - Py_DECREF(tb); - tb = 0; - } - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - /* Next, replace a missing value with None */ - if (value == NULL) { - value = Py_None; + if (!value || value == Py_None) + value = NULL; + else Py_INCREF(value); - } - #if PY_VERSION_HEX < 0x02050000 - if (!PyClass_Check(type)) - #else - if (!PyType_Check(type)) + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + #if PY_VERSION_HEX < 0x02050000 + if (PyClass_Check(type)) { + #else + if (PyType_Check(type)) { #endif - { - /* Raising an instance. The value should be a dummy. */ - if (value != Py_None) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } - /* Normalize to raise , */ - Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } - else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); + if (PyInstance_Check(type)) { + type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } + } else { + type = 0; + PyErr_SetString(PyExc_TypeError, + "raise: exception must be an old-style class or instance"); + goto raise_error; + } + #else + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } #endif } - __Pyx_ErrRestore(type, value, tb); return; raise_error: @@ -4631,10 +5414,9 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tb); return; } - #else /* Python 3+ */ - static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { @@ -4644,7 +5426,6 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } if (value == Py_None) value = 0; - if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, @@ -4653,37 +5434,71 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } value = type; type = (PyObject*) Py_TYPE(value); - } else if (!PyExceptionClass_Check(type)) { + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + if (PyObject_IsSubclass(instance_class, type)) { + type = instance_class; + } else { + instance_class = NULL; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } - +#if PY_VERSION_HEX >= 0x03030000 if (cause) { +#else + if (cause && cause != Py_None) { +#endif PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; - } - else if (PyExceptionInstance_Check(cause)) { + } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } - if (!value) { - value = PyObject_CallObject(type, NULL); - } PyException_SetCause(value, fixed_cause); } - PyErr_SetObject(type, value); - if (tb) { PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; @@ -4693,73 +5508,133 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tmp_tb); } } - bad: + Py_XDECREF(owned_instance); return; } #endif -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, - "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", - index, (index == 1) ? "" : "s"); + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); - } else { - __Pyx_RaiseTooManyValuesError(index); +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; } + if (likely(PyObject_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); - else { - PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *getbuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_getbuffer); + if (getbuffer_cobj) { + getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj); + Py_DECREF(getbuffer_cobj); + if (!func) + goto fail; + return func(obj, view, flags); + } else { + PyErr_Clear(); + } } + #endif + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + return -1; } - static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject* obj = view->obj; - if (obj) { - #if PY_VERSION_HEX >= 0x02060000 - if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;} - #endif - if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray_1__releasebuffer__(obj, view); + PyObject *obj = view->obj; + if (!obj) return; + #if PY_VERSION_HEX >= 0x02060000 + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + #endif + if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } + #if PY_VERSION_HEX < 0x02060000 + if (obj->ob_type->tp_dict) { + PyObject *releasebuffer_cobj = PyObject_GetItem( + obj->ob_type->tp_dict, __pyx_n_s_pyx_releasebuffer); + if (releasebuffer_cobj) { + releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj); + Py_DECREF(releasebuffer_cobj); + if (!func) + goto fail; + func(obj, view); + return; + } else { + PyErr_Clear(); + } + } + #endif + goto nofail; +#if PY_VERSION_HEX < 0x02060000 +fail: +#endif + PyErr_WriteUnraisable(obj); +nofail: Py_DECREF(obj); view->obj = NULL; - } } +#endif /* PY_MAJOR_VERSION < 3 */ -#endif -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { - PyObject *py_import = 0; + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; - py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; + #endif if (from_list) list = from_list; else { @@ -4776,12 +5651,42 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { goto bad; #if PY_VERSION_HEX >= 0x02050000 { - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(1); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + #endif + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { + #if PY_VERSION_HEX < 0x03030000 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } } #else if (level>0) { @@ -4792,12 +5697,182 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { name, global_dict, empty_dict, list, NULL); #endif bad: - Py_XDECREF(empty_list); + #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(int) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } +} + +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { + const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(Py_intptr_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } else { + if (sizeof(Py_intptr_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(Py_intptr_t) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), + little, !is_unsigned); + } +} + +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \ + { \ + func_type value = func(x); \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ + PyErr_SetString(PyExc_OverflowError, \ + (is_unsigned && unlikely(value < zero)) ? \ + "can't convert negative value to " #target_type : \ + "value too large to convert to " #target_type); \ + return (target_type) -1; \ + } \ + } \ + return (target_type) value; \ + } + +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (unlikely(Py_SIZE(x) < 0)) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(int) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong) + } + } else { +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(int)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(int) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(int) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong) + } else if (sizeof(int) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong) + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_Int(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +} + #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { @@ -5038,425 +6113,132 @@ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { #endif #endif -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); + } else if (sizeof(long) <= sizeof(unsigned long long)) { + return PyLong_FromUnsignedLongLong((unsigned long long) value); } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; - } - return (unsigned short)val; - } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; - } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; - } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; - } - return (short)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; - } - return (signed char)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; - } - return (signed short)val; - } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(long long)) { + return PyLong_FromLongLong((long long) value); } - return (signed int)val; } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); } - return (int)__Pyx_PyInt_AsLong(x); } -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; + "can't convert negative value to long"); + return (long) -1; } - return (unsigned long)PyLong_AsUnsignedLong(x); - } else { - return (unsigned long)PyLong_AsLong(x); + return (long) val; } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; + } } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)val; - } else + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); - return (long)-1; + return (long) -1; } - return (long)PyLong_AsUnsignedLong(x); - } else { - return (long)PyLong_AsLong(x); - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong) + } else if (sizeof(long) <= sizeof(unsigned long long)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong) } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { - return (PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)val; - } else +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + if (sizeof(digit) <= sizeof(long)) { + switch (Py_SIZE(x)) { + case 0: return 0; + case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; + case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; + } + } + #endif #endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong) + } else if (sizeof(long) <= sizeof(long long)) { + __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong) } - return (signed long)PyLong_AsUnsignedLong(x); - } else { - return (signed long)PyLong_AsLong(x); } - } else { - signed long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_VERSION_HEX < 0x03000000 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; - } - return (signed PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_Int(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; } } else { - signed PY_LONG_LONG val; + long val; PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } } -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename) { - PyObject *old_exc, *old_val, *old_tb; - PyObject *ctx; - __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); - #if PY_MAJOR_VERSION < 3 - ctx = PyString_FromString(name); - #else - ctx = PyUnicode_FromString(name); - #endif - __Pyx_ErrRestore(old_exc, old_val, old_tb); - if (!ctx) { - PyErr_WriteUnraisable(Py_None); - } else { - PyErr_WriteUnraisable(ctx); - Py_DECREF(ctx); - } -} - static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); @@ -5476,22 +6258,22 @@ static int __Pyx_check_binary_version(void) { return 0; } -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0) - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItemString(dict, "__pyx_vtable__", ob) < 0) +#ifndef __PYX_HAVE_RT_ImportModule +#define __PYX_HAVE_RT_ImportModule +static PyObject *__Pyx_ImportModule(const char *name) { + PyObject *py_name = 0; + PyObject *py_module = 0; + py_name = __Pyx_PyIdentifier_FromString(name); + if (!py_name) goto bad; - Py_DECREF(ob); - return 0; + py_module = PyImport_Import(py_name); + Py_DECREF(py_name); + return py_module; bad: - Py_XDECREF(ob); - return -1; + Py_XDECREF(py_name); + return 0; } +#endif #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType @@ -5502,15 +6284,14 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class PyObject *result = 0; PyObject *py_name = 0; char warning[200]; - + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(class_name); - #else - py_name = PyUnicode_FromString(class_name); - #endif + py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); @@ -5522,11 +6303,23 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", + "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } - if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); @@ -5536,9 +6329,9 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } - else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { + else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", + "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } @@ -5550,51 +6343,105 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class } #endif -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - - #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(name); - #else - py_name = PyUnicode_FromString(name); - #endif - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = (start + end) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); } -#endif #include "compile.h" #include "frameobject.h" #include "traceback.h" - -static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, - int __pyx_lineno, const char *__pyx_filename) { +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(__pyx_filename); + py_srcfile = PyString_FromString(filename); #else - py_srcfile = PyUnicode_FromString(__pyx_filename); + py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; - if (__pyx_clineno) { + if (c_line) { #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { @@ -5605,28 +6452,45 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, #endif } if (!py_funcname) goto bad; - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_code = PyCode_New( + py_code = __Pyx_PyCode_New( 0, /*int argcount,*/ - #if PY_MAJOR_VERSION >= 3 0, /*int kwonlyargcount,*/ - #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ - __pyx_lineno, /*int firstlineno,*/ + py_line, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); - if (!py_code) goto bad; + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_globals = 0; + PyFrameObject *py_frame = 0; + py_code = __pyx_find_code_object(c_line ? c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? c_line : py_line, py_code); + } + py_globals = PyModule_GetDict(__pyx_m); + if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ @@ -5634,11 +6498,9 @@ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; - py_frame->f_lineno = __pyx_lineno; + py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); } @@ -5673,26 +6535,90 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { return 0; } -/* Type Conversion Functions */ - +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { +#if PY_VERSION_HEX < 0x03030000 + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +#else /* PY_VERSION_HEX < 0x03030000 */ + if (PyUnicode_READY(o) == -1) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (PyUnicode_IS_ASCII(o)) { + *length = PyUnicode_GET_DATA_SIZE(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ + return PyUnicode_AsUTF8AndSize(o, length); +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* PY_VERSION_HEX < 0x03030000 */ + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ +#if !CYTHON_COMPILING_IN_PYPY +#if PY_VERSION_HEX >= 0x02060000 + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } - static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); @@ -5708,13 +6634,13 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } #endif if (res) { -#if PY_VERSION_HEX < 0x03000000 +#if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", + "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; @@ -5726,16 +6652,40 @@ static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { } return res; } - +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #endif +#endif static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) + return PyInt_AS_LONG(b); +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_USE_PYLONG_INTERNALS + switch (Py_SIZE(b)) { + case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; + case 0: return 0; + case 1: return ((PyLongObject*)b)->ob_digit[0]; + } + #endif + #endif + #if PY_VERSION_HEX < 0x02060000 + return PyInt_AsSsize_t(b); + #else + return PyLong_AsSsize_t(b); + #endif + } + x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } - static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) @@ -5750,17 +6700,5 @@ static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #endif } -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { - return (size_t)-1; - } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; -} - #endif /* Py_PYTHON_H */ diff --git a/sklearn/utils/weight_vector.pxd b/sklearn/utils/weight_vector.pxd index d21907c45d401..36af4e39e97c1 100644 --- a/sklearn/utils/weight_vector.pxd +++ b/sklearn/utils/weight_vector.pxd @@ -7,21 +7,23 @@ cdef extern from "math.h": cdef extern double sqrt(double x) -ctypedef np.float64_t DOUBLE -ctypedef np.int32_t INTEGER - - cdef class WeightVector(object): cdef np.ndarray w - cdef DOUBLE *w_data_ptr + cdef np.ndarray aw + cdef double *w_data_ptr + cdef double *aw_data_ptr cdef double wscale - cdef Py_ssize_t n_features + cdef double average_a + cdef double average_b + cdef int n_features cdef double sq_norm - cdef void add(self, DOUBLE *x_data_ptr, INTEGER *x_ind_ptr, - int xnnz, double c) - cdef double dot(self, DOUBLE *x_data_ptr, INTEGER *x_ind_ptr, - int xnnz) - cdef void scale(self, double c) - cdef void reset_wscale(self) - cdef double norm(self) \ No newline at end of file + cdef void add(self, double *x_data_ptr, int *x_ind_ptr, + int xnnz, double c) nogil + cdef void add_average(self, double *x_data_ptr, int *x_ind_ptr, + int xnnz, double c, double num_iter) nogil + cdef double dot(self, double *x_data_ptr, int *x_ind_ptr, + int xnnz) nogil + cdef void scale(self, double c) nogil + cdef void reset_wscale(self) nogil + cdef double norm(self) nogil diff --git a/sklearn/utils/weight_vector.pyx b/sklearn/utils/weight_vector.pyx index 3c52f1f9cd2df..1c727eb6d3c36 100644 --- a/sklearn/utils/weight_vector.pyx +++ b/sklearn/utils/weight_vector.pyx @@ -1,18 +1,27 @@ -# encoding: utf-8 # cython: cdivision=True # cython: boundscheck=False # cython: wraparound=False # # Author: Peter Prettenhofer +# Lars Buitinck +# Danny Sullivan # -# License: BSD Style. - +# Licence: BSD 3 clause +cimport cython +from libc.limits cimport INT_MAX +from libc.math cimport sqrt import numpy as np +cimport numpy as np +cdef extern from "cblas.h": + double ddot "cblas_ddot"(int, double *, int, double *, int) nogil + void dscal "cblas_dscal"(int, double, double *, int) nogil + void daxpy "cblas_daxpy" (int, double, const double*, + int, double*, int) nogil -cimport numpy as np -cimport cython + +np.import_array() cdef class WeightVector(object): @@ -25,9 +34,11 @@ cdef class WeightVector(object): Attributes ---------- - w : ndarray, dtype=np.float64, order='C' + w : ndarray, dtype=double, order='C' The numpy array which backs the weight vector. - w_data_ptr : np.float64* + aw : ndarray, dtype=double, order='C' + The numpy array which backs the average_weight vector. + w_data_ptr : double* A pointer to the data of the numpy array. wscale : double The scale of the vector. @@ -37,16 +48,29 @@ cdef class WeightVector(object): The squared norm of ``w``. """ - def __cinit__(self, np.ndarray[DOUBLE, ndim=1, mode='c'] w): + def __cinit__(self, + np.ndarray[double, ndim=1, mode='c'] w, + np.ndarray[double, ndim=1, mode='c'] aw): + cdef double *wdata = w.data + + if w.shape[0] > INT_MAX: + raise ValueError("More than %d features not supported; got %d." + % (INT_MAX, w.shape[0])) self.w = w - self.w_data_ptr = w.data + self.w_data_ptr = wdata self.wscale = 1.0 self.n_features = w.shape[0] - self.sq_norm = np.dot(w, w) + self.sq_norm = ddot(w.shape[0], wdata, 1, wdata, 1) + + self.aw = aw + if self.aw is not None: + self.aw_data_ptr = aw.data + self.average_a = 0.0 + self.average_b = 1.0 - cdef void add(self, DOUBLE *x_data_ptr, INTEGER *x_ind_ptr, - int xnnz, double c): - """Scales example x by constant c and adds it to the weight vector. + cdef void add(self, double *x_data_ptr, int *x_ind_ptr, int xnnz, + double c) nogil: + """Scales sample x by constant c and adds it to the weight vector. This operation updates ``sq_norm``. @@ -54,7 +78,7 @@ cdef class WeightVector(object): ---------- x_data_ptr : double* The array which holds the feature values of ``x``. - x_ind_ptr : np.int32* + x_ind_ptr : np.intc* The array which holds the feature indices of ``x``. xnnz : int The number of non-zero features of ``x``. @@ -69,7 +93,7 @@ cdef class WeightVector(object): # the next two lines save a factor of 2! cdef double wscale = self.wscale - cdef DOUBLE* w_data_ptr = self.w_data_ptr + cdef double* w_data_ptr = self.w_data_ptr for j in range(xnnz): idx = x_ind_ptr[j] @@ -80,17 +104,57 @@ cdef class WeightVector(object): self.sq_norm += (xsqnorm * c * c) + (2.0 * innerprod * wscale * c) - cdef double dot(self, DOUBLE *x_data_ptr, INTEGER *x_ind_ptr, int xnnz): - """Computes the dot product of a sample x and the weight vector. + # Update the average weights according to the sparse trick defined + # here: http://research.microsoft.com/pubs/192769/tricks-2012.pdf + # by Leon Bottou + cdef void add_average(self, double *x_data_ptr, int *x_ind_ptr, int xnnz, + double c, double num_iter) nogil: + """Updates the average weight vector. Parameters ---------- x_data_ptr : double* The array which holds the feature values of ``x``. - x_ind_ptr : np.int32* + x_ind_ptr : np.intc* The array which holds the feature indices of ``x``. xnnz : int The number of non-zero features of ``x``. + c : double + The scaling constant for the example. + num_iter : double + The total number of iterations. + """ + cdef int j + cdef int idx + cdef double val + cdef double mu = 1.0 / num_iter + cdef double average_a = self.average_a + cdef double wscale = self.wscale + cdef double* aw_data_ptr = self.aw_data_ptr + + for j in range(xnnz): + idx = x_ind_ptr[j] + val = x_data_ptr[j] + aw_data_ptr[idx] += (self.average_a * val * (-c / wscale)) + + # Once the the sample has been processed + # update the average_a and average_b + if num_iter > 1: + self.average_b /= (1.0 - mu) + self.average_a += mu * self.average_b * wscale + + cdef double dot(self, double *x_data_ptr, int *x_ind_ptr, + int xnnz) nogil: + """Computes the dot product of a sample x and the weight vector. + + Parameters + ---------- + x_data_ptr : double* + The array which holds the feature values of ``x``. + x_ind_ptr : np.intc* + The array which holds the feature indices of ``x``. + xnnz : int + The number of non-zero features of ``x`` (length of x_ind_ptr). Returns ------- @@ -100,14 +164,14 @@ cdef class WeightVector(object): cdef int j cdef int idx cdef double innerprod = 0.0 - cdef DOUBLE* w_data_ptr = self.w_data_ptr + cdef double* w_data_ptr = self.w_data_ptr for j in range(xnnz): idx = x_ind_ptr[j] innerprod += w_data_ptr[idx] * x_data_ptr[j] innerprod *= self.wscale return innerprod - cdef void scale(self, double c): + cdef void scale(self, double c) nogil: """Scales the weight vector by a constant ``c``. It updates ``wscale`` and ``sq_norm``. If ``wscale`` gets too @@ -117,11 +181,19 @@ cdef class WeightVector(object): if self.wscale < 1e-9: self.reset_wscale() - cdef void reset_wscale(self): + cdef void reset_wscale(self) nogil: """Scales each coef of ``w`` by ``wscale`` and resets it to 1. """ - self.w *= self.wscale + if self.aw is not None: + daxpy(self.aw.shape[0], self.average_a, + self.w.data, 1, self.aw.data, 1) + dscal(self.aw.shape[0], 1.0 / self.average_b, + self.aw.data, 1) + self.average_a = 0.0 + self.average_b = 1.0 + + dscal(self.w.shape[0], self.wscale, self.w.data, 1) self.wscale = 1.0 - cdef double norm(self): + cdef double norm(self) nogil: """The L2 norm of the weight vector. """ return sqrt(self.sq_norm)